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/.appveyor/check-generate-code.bat b/.appveyor/check-generate-code.bat
deleted file mode 100644
index ba7398a..0000000
--- a/.appveyor/check-generate-code.bat
+++ /dev/null
@@ -1,41 +0,0 @@
-:: Copyright 2018 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.
-set buildtype=Release
-if "%1"=="-b" set buildtype=%2
-
-cd tests
-call generate_code.bat -b %buildtype% || goto FAIL
-
-:: TODO: Release and Debug builds produce differences here for some reason.
-git checkout HEAD -- monster_test.bfbs
-git checkout HEAD -- arrays_test.bfbs
-
-git -c core.autocrlf=true diff --exit-code --quiet || goto :DIFFFOUND
-goto SUCCESS
-
-:DIFFFOUND
-@echo "" >&2
-@echo "ERROR: ********************************************************" >&2
-@echo "ERROR: The following differences were found after running the" >&2
-@echo "ERROR: tests/generate_code.sh script. Maybe you forgot to run" >&2
-@echo "ERROR: it after making changes in a generator or schema?" >&2
-@echo "ERROR: ********************************************************" >&2
-@echo "" >&2
-@git -c core.autocrlf=true --no-pager diff --binary
-
-:FAIL
-set EXITCODE=1
-:SUCCESS
-cd ..
-EXIT /B %EXITCODE%
\ No newline at end of file
diff --git a/.bazelci/presubmit.yml b/.bazelci/presubmit.yml
index a6e38fd..33cb7c2 100644
--- a/.bazelci/presubmit.yml
+++ b/.bazelci/presubmit.yml
@@ -1,18 +1,18 @@
---
buildifier: latest
platforms:
- ubuntu1604:
- build_targets:
- - "..."
- test_targets:
- - "..."
ubuntu1804:
build_targets:
- - "..."
+ - "//..."
test_targets:
- - "..."
+ - "//..."
+ ubuntu2004:
+ build_targets:
+ - "//..."
+ test_targets:
+ - "//..."
macos:
build_targets:
- - "..."
+ - "//..."
test_targets:
- - "..."
+ - "//..."
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
index 4cbb292..0f05239 100644
--- a/.github/PULL_REQUEST_TEMPLATE.md
+++ b/.github/PULL_REQUEST_TEMPLATE.md
@@ -2,18 +2,17 @@
Please delete this standard text once you've created your own description.
-Make sure you include the names of the affected language(s) in your PR title.
-This helps us get the correct maintainers to look at your issue.
+If you make changes to any of the code generators (`src/idl_gen*`) be sure to
+build your project, as it will generate code based on the changes. If necessary
+the code generation script can be directly run (`scripts/generate_code.py`),
+requires Python3. This allows us to better see the effect of the PR.
-If you make changes to any of the code generators, be sure to run
-`cd tests && sh generate_code.sh` (or equivalent .bat) and include the generated
-code changes in the PR. This allows us to better see the effect of the PR.
-
-If your PR includes C++ code, please adhere to the Google C++ Style Guide,
+If your PR includes C++ code, please adhere to the
+[Google C++ Style Guide](https://google.github.io/styleguide/cppguide.html),
and don't forget we try to support older compilers (e.g. VS2010, GCC 4.6.3),
so only some C++11 support is available.
-For any C++ changes, please make sure to run `sh src/clang-format-git.sh`
+For any C++ changes, please make sure to run `sh scripts/clang-format-git.sh`
Include other details as appropriate.
diff --git a/.github/labeler.yml b/.github/labeler.yml
index 33c2346..5de0c3a 100644
--- a/.github/labeler.yml
+++ b/.github/labeler.yml
@@ -22,11 +22,11 @@
javascript:
- '**/*.js'
- - src/idl_gen_js_ts.cpp
+ - src/idl_gen_ts.cpp
typescript:
- '**/*.ts'
- - src/idl_gen_js_ts.cpp
+ - src/idl_gen_ts.cpp
- grpc/flatbuffers-js-grpc/**/*.ts
golang:
@@ -49,6 +49,7 @@
- '**/*.lua'
- lua/**/*
- src/idl_gen_lua.cpp
+ - src/bfbs_gen_lua.cpp
lobster:
- '**/*.lobster'
@@ -85,11 +86,9 @@
CI:
- '.github/**/*'
- - '.appveyor/**/*
- '.travis/**/*'
- - '.bazelci/**/*
+ - '.bazelci/**/*'
- .travis.yml
- - appveyor.yml
grpc:
- grpc/**/*
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 14e2346..925e86a 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -14,15 +14,19 @@
runs-on: ubuntu-latest
strategy:
matrix:
- cxx: [g++-9, clang++-9]
+ cxx: [g++-10, clang++-12]
steps:
- - uses: actions/checkout@v1
+ - uses: actions/checkout@v2
- name: cmake
run: CXX=${{ matrix.cxx }} cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release .
- name: build
run: make -j4
- name: test
run: ./flattests
+ - name: make flatc executable
+ run: |
+ chmod +x flatc
+ ./flatc --version
- name: upload build artifacts
uses: actions/upload-artifact@v1
with:
@@ -30,14 +34,14 @@
path: flatc
build-windows:
- name: Build Windows
- runs-on: windows-latest
+ name: Build Windows 2019
+ runs-on: windows-2019
steps:
- - uses: actions/checkout@v1
+ - uses: actions/checkout@v2
- name: Add msbuild to PATH
- uses: microsoft/setup-msbuild@v1.0.2
+ uses: microsoft/setup-msbuild@v1.1
- name: cmake
- run: cmake -G "Visual Studio 16 2019" -A x64 -DCMAKE_BUILD_TYPE=Release .
+ run: cmake -G "Visual Studio 16 2019" -A x64 -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_BUILD_CPP17=ON .
- name: build
run: msbuild.exe FlatBuffers.sln /p:Configuration=Release /p:Platform=x64
- name: test
@@ -48,28 +52,94 @@
name: Windows flatc binary
path: Release\flatc.exe
+ build-windows-2017:
+ name: Build Windows 2017
+ runs-on: windows-2019
+ steps:
+ - uses: actions/checkout@v2
+ - name: Add msbuild to PATH
+ uses: microsoft/setup-msbuild@v1.1
+ - name: cmake
+ run: cmake -G "Visual Studio 16 2019" -A x64 -DCMAKE_BUILD_TYPE=Release .
+ - name: build tool version 15 (VS 2017)
+ run: msbuild.exe FlatBuffers.sln /p:Configuration=Release /p:Platform=x64 /p:VisualStudioVersion=15.0
+ - name: test
+ run: Release\flattests.exe
+
+ build-windows-2015:
+ name: Build Windows 2015
+ runs-on: windows-2019
+ steps:
+ - uses: actions/checkout@v2
+ - name: Add msbuild to PATH
+ uses: microsoft/setup-msbuild@v1.1
+ - name: cmake
+ run: cmake -G "Visual Studio 14 2015" -A x64 -DCMAKE_BUILD_TYPE=Release .
+ - name: build tool version 14 (VS 2015)
+ run: msbuild.exe FlatBuffers.sln /p:Configuration=Release /p:Platform=x64 /p:VisualStudioVersion=14.0
+ - name: test
+ run: Release\flattests.exe
+
+ build-dotnet-windows:
+ name: Build .NET Windows
+ runs-on: windows-2019
+ strategy:
+ matrix:
+ configuration: [
+ '',
+ '-p:UnsafeByteBuffer=true',
+ # Fails two tests currently.
+ #'-p:EnableSpanT=true,UnsafeByteBuffer=true'
+ ]
+ steps:
+ - uses: actions/checkout@v2
+ - name: Setup .NET Core SDK
+ uses: actions/setup-dotnet@v1.9.0
+ with:
+ dotnet-version: '3.1.x'
+ - name: Build
+ run: |
+ cd tests\FlatBuffers.Test
+ dotnet new sln --force --name FlatBuffers.Core.Test
+ dotnet sln FlatBuffers.Core.Test.sln add FlatBuffers.Core.Test.csproj
+ dotnet build -c Release ${{matrix.configuration}} -o out FlatBuffers.Core.Test.sln
+ - name: Run
+ run: |
+ cd tests\FlatBuffers.Test
+ out\FlatBuffers.Core.Test.exe
+
build-mac:
name: Build Mac
runs-on: macos-latest
steps:
- - uses: actions/checkout@v1
+ - uses: actions/checkout@v2
- name: cmake
- run: cmake -G "Xcode" -DCMAKE_BUILD_TYPE=Release .
+ run: cmake -G "Xcode" -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_FLATC_EXECUTABLE=_build/Release/flatc .
- name: build
- run: xcodebuild -toolchain clang -configuration Release -target flattests
+ # NOTE: we need this _build dir to not have xcodebuild's default ./build dir clash with the BUILD file.
+ run: xcodebuild -toolchain clang -configuration Release -target flattests SYMROOT=$(PWD)/_build
+ - name: check that the binary is "universal"
+ run: |
+ info=$(file _build/Release/flatc)
+ echo $info
+ echo $info | grep "universal binary with 2 architectures"
- name: test
- run: Release/flattests
+ run: _build/Release/flattests
+ - name: make flatc executable
+ run: |
+ chmod +x _build/Release/flatc
+ ./_build/Release/flatc --version
- name: upload build artifacts
uses: actions/upload-artifact@v1
with:
name: Mac flatc binary
- path: Release/flatc
+ path: _build/Release/flatc
build-android:
name: Build Android (on Linux)
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@v1
+ - uses: actions/checkout@v2
- name: set up JDK 1.8
uses: actions/setup-java@v1
with:
@@ -82,3 +152,151 @@
- name: build
working-directory: android
run: bash ./gradlew clean build
+
+ build-generator:
+ name: Check Generated Code
+ runs-on: ubuntu-latest
+ strategy:
+ matrix:
+ cxx: [g++-10, clang++-12]
+ steps:
+ - uses: actions/checkout@v2
+ - name: cmake
+ run: CXX=${{ matrix.cxx }} cmake -G "Unix Makefiles" -DFLATBUFFERS_BUILD_TESTS=OFF -DCMAKE_BUILD_TYPE=Release . && make -j4
+ - name: Generate
+ run: scripts/check_generate_code.py
+ - name: Generate gRPC
+ run: bash scripts/check-grpc-generated-code.sh
+
+ build-benchmarks:
+ name: Build Benchmarks (on Linux)
+ runs-on: ubuntu-latest
+ strategy:
+ matrix:
+ cxx: [g++-10]
+ steps:
+ - uses: actions/checkout@v2
+ - name: cmake
+ run: CXX=${{ matrix.cxx }} cmake -G "Unix Makefiles" -DFLATBUFFERS_CXX_FLAGS="-Wno-unused-parameter -fno-aligned-new" -DFLATBUFFERS_BUILD_BENCHMARKS=ON -DCMAKE_BUILD_TYPE=Release . && make -j4
+ - name: Run benchmarks
+ run: ./flatbenchmark --benchmark_repetitions=5 --benchmark_display_aggregates_only=true --benchmark_out_format=console --benchmark_out=benchmarks/results_${{matrix.cxx}}
+ - name: Upload benchmarks results
+ uses: actions/upload-artifact@v1
+ with:
+ name: Linux flatbenchmark results ${{matrix.cxx}}
+ path: benchmarks/results_${{matrix.cxx}}
+
+ build-java:
+ name: Build Java
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v2
+ - name: test
+ working-directory: tests
+ run: bash JavaTest.sh
+
+ build-kotlin-macos:
+ name: Build Kotlin MacOS
+ runs-on: macos-latest
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v2
+ - uses: actions/setup-java@v2
+ with:
+ distribution: 'adopt-hotspot'
+ java-version: '11'
+ - name: Build
+ working-directory: kotlin
+ run: ./gradlew clean iosX64Test macosX64Test jsTest jsBrowserTest
+
+ build-kotlin-linux:
+ name: Build Kotlin Linux
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v2
+ - uses: actions/setup-java@v2
+ with:
+ distribution: 'adopt-hotspot'
+ java-version: '8'
+ - name: Build
+ working-directory: kotlin
+ run: ./gradlew jvmMainClasses jvmTest
+ - name: Run Benchmark
+ working-directory: kotlin
+ run: ./gradlew jvmBenchmark
+ - name: Generate Benchmark Report
+ working-directory: kotlin
+ run: |
+ ./gradlew jmhReport;
+ mv benchmark/build/reports/benchmarks/main/* benchmark_latest
+ - name: Archive benchmark report
+ uses: actions/upload-artifact@v1
+ with:
+ name: Kotlin Benchmark Report
+ path: kotlin/benchmark_latest
+
+ build-rust:
+ name: Build Rust
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v2
+ - name: test
+ working-directory: tests
+ run: bash RustTest.sh
+
+ build-python:
+ name: Build Python
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v2
+ - name: test
+ working-directory: tests
+ run: bash PythonTest.sh
+
+ build-go:
+ name: Build Go
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v2
+ - name: flatc
+ # FIXME: make test script not rely on flatc
+ run: cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_BUILD_TESTS=OFF -DFLATBUFFERS_INSTALL=OFF -DFLATBUFFERS_BUILD_FLATLIB=OFF -DFLATBUFFERS_BUILD_FLATHASH=OFF . && make -j4
+ - name: test
+ working-directory: tests
+ run: bash GoTest.sh
+
+ build-swift:
+ name: Build Swift
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v2
+ - name: test
+ working-directory: tests/FlatBuffers.Test.Swift
+ run: sh SwiftTest.sh
+
+ build-ts:
+ name: Build TS
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v2
+ - name: compile
+ run: npm run compile
+ - name: test
+ working-directory: tests
+ run: sh TypeScriptTest.sh
+
+ build-dart:
+ name: Build Dart
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v2
+ - uses: dart-lang/setup-dart@v1
+ with:
+ sdk: stable
+ - name: flatc
+ # FIXME: make test script not rely on flatc
+ run: cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_BUILD_TESTS=OFF -DFLATBUFFERS_INSTALL=OFF -DFLATBUFFERS_BUILD_FLATLIB=OFF -DFLATBUFFERS_BUILD_FLATHASH=OFF . && make -j4
+ - name: test
+ working-directory: tests
+ run: bash DartTest.sh
diff --git a/.github/workflows/label_notify.yml b/.github/workflows/label_notify.yml
deleted file mode 100644
index 21cad08..0000000
--- a/.github/workflows/label_notify.yml
+++ /dev/null
@@ -1,17 +0,0 @@
-name: Notify users based on issue labels
-
-on:
- issues:
- types: [labeled]
- pull_requests:
- types: [labeled]
-
-jobs:
- notify:
- runs-on: ubuntu-latest
- steps:
- - uses: jenschelkopf/issue-label-notification-action@1.3
- with:
- recipients: |
- lua=@dbaileychess
- c++=@aardappel
\ No newline at end of file
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml
new file mode 100644
index 0000000..4ec5ad4
--- /dev/null
+++ b/.github/workflows/main.yml
@@ -0,0 +1,32 @@
+name: CIFuzz
+on:
+ pull_request:
+ branches:
+ - master
+ paths:
+ - include/**
+ - src/**
+ - tests/**.cpp
+ - tests/**.h
+jobs:
+ Fuzzing:
+ runs-on: ubuntu-latest
+ steps:
+ - name: Build Fuzzers
+ id: build
+ uses: google/oss-fuzz/infra/cifuzz/actions/build_fuzzers@master
+ with:
+ oss-fuzz-project-name: 'flatbuffers'
+ language: c++
+ - name: Run Fuzzers
+ uses: google/oss-fuzz/infra/cifuzz/actions/run_fuzzers@master
+ with:
+ oss-fuzz-project-name: 'flatbuffers'
+ language: c++
+ fuzz-seconds: 600
+ - name: Upload Crash
+ uses: actions/upload-artifact@v1
+ if: failure() && steps.build.outcome == 'success'
+ with:
+ name: artifacts
+ path: ./out/artifacts
diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml
index a27225d..b322b74 100644
--- a/.github/workflows/stale.yml
+++ b/.github/workflows/stale.yml
@@ -10,7 +10,7 @@
runs-on: ubuntu-latest
steps:
- - uses: actions/stale@v3
+ - uses: actions/stale@v4.0.0
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
stale-pr-message: 'This pull request is stale because it has been open 6 months with no activity. Please comment or this will be closed in 14 days.'
@@ -18,3 +18,6 @@
days-before-stale: 182 # 6 months
days-before-close: 14
operations-per-run: 1500
+ exempt-issue-labels: not-stale
+ exempt-pr-labels: not-stale
+ exempt-all-milestones: true
diff --git a/.gitignore b/.gitignore
index b783d0a..c4bfbc9 100644
--- a/.gitignore
+++ b/.gitignore
@@ -2,6 +2,7 @@
*_wire.bin
.DS_Store
**/.build
+build
**/Packages
/*.xcodeproj
**/xcuserdata/
@@ -45,6 +46,8 @@
proguard-project.txt
linklint_results
Makefile
+flatbenchmark
+flatbenchmark.exe
flatc
flatc.exe
flathash
@@ -69,10 +72,7 @@
tests/monsterdata_javascript_wire.mon
tests/monsterdata_lobster_wire.mon
tests/monsterdata_rust_wire.mon
-tests/unicode_test.mon
-tests/ts/
tests/php/
-tests/js/
CMakeLists.txt.user
CMakeScripts/**
CTestTestfile.cmake
@@ -103,7 +103,10 @@
samples/android/.externalNativeBuild/
samples/android/.gradle/
samples/android/build/
-js/flatbuffers.mjs
+js/**/*.js
+js/**/*.d.ts
+mjs/**/*.js
+mjs/**/*.d.ts
/bazel-bin
/bazel-flatbuffers
/bazel-genfiles
@@ -131,11 +134,16 @@
/*.ilk
/*.pdb
.clwb
-js/**/*.js
-js/**/*.d.ts
-mjs/**/*.js
-mjs/**/*.d.ts
yarn-error.log
.cache/
/flatbuffers.lib
.cmake/
+**/dist
+**/vendor
+**/go.sum
+flatbuffers.pc
+**/FlatBuffers.Test.Swift.xcodeproj
+**/html/**
+**/latex/**
+# https://cmake.org/cmake/help/latest/module/FetchContent.html#variable:FETCHCONTENT_BASE_DIR
+_deps/
\ No newline at end of file
diff --git a/.travis.yml b/.travis.yml
index 17d3cc0..2e95109 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -104,6 +104,7 @@
- if [ "$TRAVIS_OS_NAME" == "linux" ]; then sudo ln -s -v -f $(which gcc-$GCC_VERSION) /usr/bin/gcc; fi
script:
+ - pip install cmake
- bash .travis/check-sources.sh
- bash grpc/build_grpc.sh
- cmake .
@@ -114,7 +115,6 @@
-DFLATBUFFERS_CODE_SANITIZE=ON
- cmake --build . --target all --clean-first -- -j${JOBS}
- LD_LIBRARY_PATH=$TRAVIS_BUILD_DIR/google/grpc/install/lib ctest --extra-verbose --output-on-failure
- - bash .travis/check-generate-code.sh
- language: cpp
os: osx
@@ -125,6 +125,11 @@
- BUILD_TYPE=Release
script:
+ - pip install --user cmake
+ - mkdir ~/cmake_path
+ - ln -s $(find ~/Library/Python -name cmake -type f | head -n 1) ~/cmake_path/cmake
+ - ln -s $(find ~/Library/Python -name ctest -type f | head -n 1) ~/cmake_path/ctest
+ - export PATH=~/cmake_path:${PATH}
- bash grpc/build_grpc.sh
- cmake .
-DCMAKE_BUILD_TYPE=$BUILD_TYPE
@@ -134,7 +139,6 @@
-DFLATBUFFERS_CODE_SANITIZE=ON
- cmake --build . -- -j${JOBS}
- DYLD_LIBRARY_PATH=$TRAVIS_BUILD_DIR/google/grpc/install/lib ctest --extra-verbose --output-on-failure
- - bash .travis/check-generate-code.sh
- <<: *conan-linux-master
env: CONAN_GCC_VERSIONS=8 CONAN_DOCKER_IMAGE=conanio/gcc8
@@ -200,3 +204,12 @@
script:
- cmake -DFLATBUFFERS_BUILD_TESTS=OFF -DFLATBUFFERS_BUILD_FLATLIB=OFF -DFLATBUFFERS_BUILD_FLATHASH=OFF .; make; export PATH="$PATH:${PWD}"
- cd android; ./gradlew clean build
+
+ - language: generic
+ if: type IN (pull_request)
+ os: linux
+ install:
+ - bash .travis/format_install.sh
+
+ script:
+ - bash .travis/format_check.sh
diff --git a/.travis/check-generate-code.sh b/.travis/check-generate-code.sh
deleted file mode 100755
index 1f2d84d..0000000
--- a/.travis/check-generate-code.sh
+++ /dev/null
@@ -1,36 +0,0 @@
-#!/bin/bash
-#
-# Copyright 2018 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.
-set -e
-
-cd tests
-./generate_code.sh
-cd ..
-
-# TODO: Linux and macos builds produce differences here for some reason.
-git checkout HEAD -- tests/monster_test.bfbs
-git checkout HEAD -- tests/arrays_test.bfbs
-git checkout HEAD -- samples/monster.bfbs
-
-if ! git diff --quiet; then
- echo >&2
- echo "ERROR: ********************************************************" >&2
- echo "ERROR: The following differences were found after running the" >&2
- echo "ERROR: tests/generate_code.sh script. Maybe you forgot to run" >&2
- echo "ERROR: it after making changes in a generator or schema?" >&2
- echo "ERROR: ********************************************************" >&2
- echo >&2
- git diff --binary --exit-code
-fi
diff --git a/.travis/format_check.sh b/.travis/format_check.sh
new file mode 100644
index 0000000..cbd1d9b
--- /dev/null
+++ b/.travis/format_check.sh
@@ -0,0 +1,52 @@
+#!/bin/bash
+#
+# Copyright 2021 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.
+
+set -e
+
+# HACKY solution to make nodejs work.
+source ~/.nvm/nvm.sh
+nvm alias default node
+nvm use default
+
+sh scripts/clang-format-git.sh
+
+# Check formatting for go lang
+
+cd go
+gofmt -w .
+cd ..
+cd grpc/examples/go
+sh format.sh
+cd ../../..
+
+node_modules/.bin/eslint ts/** --ext .ts --quiet --fix
+
+#PYTHON IS DISABLED UNTIL WE CREATE A .pylintrc FILE FOR IT
+pylint python/** --disable=all
+
+swiftformat --config swift.swiftformat .
+
+
+if ! git diff --quiet; then
+ echo >&2
+ echo "ERROR: ********************************************************" >&2
+ echo "ERROR: The following differences were found after running" >&2
+ echo "ERROR: .travis/format_check.sh script. Maybe you forgot to format" >&2
+ echo "ERROR: the code after making changes? please check Formatters.md" >&2
+ echo "ERROR: ********************************************************" >&2
+ echo >&2
+ git diff --binary --exit-code
+fi
\ No newline at end of file
diff --git a/.travis/format_install.sh b/.travis/format_install.sh
new file mode 100644
index 0000000..74908d5
--- /dev/null
+++ b/.travis/format_install.sh
@@ -0,0 +1,90 @@
+#!/bin/bash
+#
+# Copyright 2020 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.
+
+set -e
+set -x
+
+# install devtools
+install_languages() {
+ sudo apt update
+
+ # Install nodeJS and yarn
+ wget https://raw.githubusercontent.com/creationix/nvm/v0.31.0/nvm.sh -O ~/.nvm/nvm.sh
+ source ~/.nvm/nvm.sh
+ nvm install node
+ node --version
+ curl -o- -L https://yarnpkg.com/install.sh | bash
+ export PATH="$HOME/.yarn/bin:$PATH"
+ yarn config set prefix ~/.yarn -g
+ export PATH="$HOME/.yarn/bin:$HOME/.config/yarn/global/node_modules/.bin:$PATH"
+
+ # Install swift
+ sudo apt-get install \
+ binutils \
+ git \
+ libc6-dev \
+ libcurl3 \
+ libedit2 \
+ libgcc-5-dev \
+ libpython2.7 \
+ libsqlite3-0 \
+ libstdc++-5-dev \
+ libxml2 \
+ pkg-config \
+ tzdata \
+ zlib1g-dev
+
+ SWIFT_URL=https://swift.org/builds/swift-5.3.1-release/ubuntu1604/swift-5.3.1-RELEASE/swift-5.3.1-RELEASE-ubuntu16.04.tar.gz
+ curl -fSsL "$SWIFT_URL" -o swift.tar.gz
+
+ mkdir ~/swiftbuild
+ tar -xvzf swift.tar.gz -C ~/swiftbuild
+
+ export PATH="~/swiftbuild/swift-5.3.1-RELEASE-ubuntu16.04/usr/bin:$PATH"
+
+
+ mkdir ~/gobuild
+ wget -c https://golang.org/dl/go1.15.2.linux-amd64.tar.gz
+ tar -xvzf go1.15.2.linux-amd64.tar.gz -C ~/gobuild
+
+ export PATH="~/gobuild/go/bin:$PATH"
+
+ swift --version
+ go version
+ yarn -v
+ node -v
+}
+
+install_formatters() {
+ # installing swift formatter
+ git clone --depth 1 --branch 0.47.4 https://github.com/nicklockwood/SwiftFormat.git
+ cd SwiftFormat
+ swift build -c release
+ sudo cp .build/release/swiftformat /usr/local/bin/swiftformat
+ cd ..
+
+ which yarn
+ which node
+ yarn -v
+ node -v
+
+ yarn install
+ pip install pylint
+}
+
+install_languages
+export PATH="~/swift/swift/usr/bin:$PATH"
+install_formatters
\ No newline at end of file
diff --git a/BUILD b/BUILD
deleted file mode 100644
index 936ef9d..0000000
--- a/BUILD
+++ /dev/null
@@ -1,79 +0,0 @@
-licenses(["notice"])
-
-load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library")
-
-package(
- default_visibility = ["//visibility:public"],
-)
-
-exports_files([
- "LICENSE",
-])
-
-# Public flatc library to compile flatbuffer files at runtime.
-cc_library(
- name = "flatbuffers",
- hdrs = ["//:public_headers"],
- linkstatic = 1,
- strip_include_prefix = "/include",
- deps = ["//src:flatbuffers"],
-)
-
-# Public C++ headers for the Flatbuffers library.
-filegroup(
- name = "public_headers",
- srcs = [
- "include/flatbuffers/base.h",
- "include/flatbuffers/code_generators.h",
- "include/flatbuffers/flatbuffers.h",
- "include/flatbuffers/flexbuffers.h",
- "include/flatbuffers/grpc.h",
- "include/flatbuffers/hash.h",
- "include/flatbuffers/idl.h",
- "include/flatbuffers/minireflect.h",
- "include/flatbuffers/reflection.h",
- "include/flatbuffers/reflection_generated.h",
- "include/flatbuffers/registry.h",
- "include/flatbuffers/stl_emulation.h",
- "include/flatbuffers/util.h",
- ],
-)
-
-# Public flatc compiler library.
-cc_library(
- name = "flatc_library",
- linkstatic = 1,
- deps = [
- "//src:flatc_library",
- ],
-)
-
-# Public flatc compiler.
-cc_binary(
- name = "flatc",
- deps = [
- "//src:flatc",
- ],
-)
-
-filegroup(
- name = "flatc_headers",
- srcs = [
- "include/flatbuffers/flatc.h",
- ],
- visibility = ["//:__subpackages__"],
-)
-
-# Library used by flatbuffer_cc_library rules.
-cc_library(
- name = "runtime_cc",
- hdrs = [
- "include/flatbuffers/base.h",
- "include/flatbuffers/flatbuffers.h",
- "include/flatbuffers/flexbuffers.h",
- "include/flatbuffers/stl_emulation.h",
- "include/flatbuffers/util.h",
- ],
- linkstatic = 1,
- strip_include_prefix = "/include",
-)
diff --git a/BUILD.bazel b/BUILD.bazel
new file mode 100644
index 0000000..7d47143
--- /dev/null
+++ b/BUILD.bazel
@@ -0,0 +1,111 @@
+load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library")
+
+licenses(["notice"])
+
+package(
+ default_visibility = ["//visibility:public"],
+)
+
+exports_files([
+ "LICENSE",
+ "tsconfig.json",
+])
+
+config_setting(
+ name = "platform_freebsd",
+ constraint_values = [
+ "@platforms//os:freebsd",
+ ],
+)
+
+config_setting(
+ name = "platform_openbsd",
+ constraint_values = [
+ "@platforms//os:openbsd",
+ ],
+)
+
+# Public flatc library to compile flatbuffer files at runtime.
+cc_library(
+ name = "flatbuffers",
+ hdrs = ["//:public_headers"],
+ linkstatic = 1,
+ strip_include_prefix = "/include",
+ deps = ["//src:flatbuffers"],
+)
+
+# Public C++ headers for the Flatbuffers library.
+filegroup(
+ name = "public_headers",
+ srcs = [
+ "include/flatbuffers/allocator.h",
+ "include/flatbuffers/array.h",
+ "include/flatbuffers/base.h",
+ "include/flatbuffers/bfbs_generator.h",
+ "include/flatbuffers/buffer.h",
+ "include/flatbuffers/buffer_ref.h",
+ "include/flatbuffers/code_generators.h",
+ "include/flatbuffers/default_allocator.h",
+ "include/flatbuffers/detached_buffer.h",
+ "include/flatbuffers/flatbuffer_builder.h",
+ "include/flatbuffers/flatbuffers.h",
+ "include/flatbuffers/flexbuffers.h",
+ "include/flatbuffers/grpc.h",
+ "include/flatbuffers/hash.h",
+ "include/flatbuffers/idl.h",
+ "include/flatbuffers/minireflect.h",
+ "include/flatbuffers/reflection.h",
+ "include/flatbuffers/reflection_generated.h",
+ "include/flatbuffers/registry.h",
+ "include/flatbuffers/stl_emulation.h",
+ "include/flatbuffers/string.h",
+ "include/flatbuffers/struct.h",
+ "include/flatbuffers/table.h",
+ "include/flatbuffers/util.h",
+ "include/flatbuffers/vector.h",
+ "include/flatbuffers/vector_downward.h",
+ "include/flatbuffers/verifier.h",
+ ],
+)
+
+# Public flatc compiler library.
+cc_library(
+ name = "flatc_library",
+ linkstatic = 1,
+ deps = [
+ "//src:flatc_library",
+ ],
+)
+
+# Public flatc compiler.
+cc_binary(
+ name = "flatc",
+ data = ["//reflection:reflection_fbs_schema"],
+ deps = [
+ "//src:flatc",
+ ],
+)
+
+filegroup(
+ name = "flatc_headers",
+ srcs = [
+ "include/flatbuffers/flatc.h",
+ ],
+ visibility = ["//:__subpackages__"],
+)
+
+# Library used by flatbuffer_cc_library rules.
+cc_library(
+ name = "runtime_cc",
+ hdrs = [
+ "include/flatbuffers/base.h",
+ "include/flatbuffers/flatbuffers.h",
+ "include/flatbuffers/flexbuffers.h",
+ "include/flatbuffers/stl_emulation.h",
+ "include/flatbuffers/util.h",
+ "include/flatbuffers/vector.h",
+ "include/flatbuffers/verifier.h",
+ ],
+ linkstatic = 1,
+ strip_include_prefix = "/include",
+)
diff --git a/CMake/BuildFlatBuffers.cmake b/CMake/BuildFlatBuffers.cmake
index 01db72d..b0c5c8f 100644
--- a/CMake/BuildFlatBuffers.cmake
+++ b/CMake/BuildFlatBuffers.cmake
@@ -95,7 +95,7 @@
set(generated_include ${generated_includes_dir}/${filename}_generated.h)
add_custom_command(
OUTPUT ${generated_include}
- COMMAND ${FLATC} ${FLATC_ARGS}
+ COMMAND ${FLATC} ${FLATC_SCHEMA_ARGS}
-o ${generated_includes_dir}
${include_params}
-c ${schema}
@@ -230,16 +230,30 @@
foreach(schema ${FLATBUFFERS_GENERATE_HEADERS_SCHEMAS})
get_filename_component(filename ${schema} NAME_WE)
set(generated_include "${generated_include_dir}/${filename}_generated.h")
+
+ # Generate files for grpc if needed
+ set(generated_source_file)
+ if("${FLATBUFFERS_GENERATE_HEADERS_FLAGS}" MATCHES "--grpc")
+ # Check if schema file contain a rpc_service definition
+ file(STRINGS ${schema} has_grpc REGEX "rpc_service")
+ if(has_grpc)
+ list(APPEND generated_include "${generated_include_dir}/${filename}.grpc.fb.h")
+ set(generated_source_file "${generated_include_dir}/${filename}.grpc.fb.cc")
+ endif()
+ endif()
+
add_custom_command(
- OUTPUT ${generated_include}
+ OUTPUT ${generated_include} ${generated_source_file}
COMMAND ${FLATC} ${FLATC_ARGS}
-o ${generated_include_dir}
${include_params}
-c ${schema}
${FLATBUFFERS_GENERATE_HEADERS_FLAGS}
DEPENDS ${FLATC_TARGET} ${schema}
- WORKING_DIRECTORY "${working_dir}")
+ WORKING_DIRECTORY "${working_dir}"
+ COMMENT "Building ${schema} flatbuffers...")
list(APPEND all_generated_header_files ${generated_include})
+ list(APPEND all_generated_source_files ${generated_source_file})
# Geneate the binary flatbuffers schemas if instructed to.
if (NOT ${FLATBUFFERS_GENERATE_HEADERS_BINARY_SCHEMAS_DIR} STREQUAL "")
@@ -264,6 +278,7 @@
INTERFACE
${all_generated_header_files}
${all_generated_binary_files}
+ ${all_generated_source_files}
${FLATBUFFERS_GENERATE_HEADERS_SCHEMAS})
add_dependencies(
${FLATBUFFERS_GENERATE_HEADERS_TARGET}
@@ -279,6 +294,10 @@
PREFIX "Flatbuffers/Generated/Headers Files"
FILES ${all_generated_header_files})
source_group(
+ TREE "${generated_target_dir}"
+ PREFIX "Flatbuffers/Generated/Source Files"
+ FILES ${all_generated_source_files})
+ source_group(
TREE ${working_dir}
PREFIX "Flatbuffers/Schemas"
FILES ${FLATBUFFERS_GENERATE_HEADERS_SCHEMAS})
@@ -371,7 +390,8 @@
-b ${FLATBUFFERS_GENERATE_BINARY_FILES_SCHEMA} ${json_file}
${FLATBUFFERS_GENERATE_BINARY_FILES_FLAGS}
DEPENDS ${FLATC_TARGET} ${json_file}
- WORKING_DIRECTORY "${working_dir}")
+ WORKING_DIRECTORY "${working_dir}"
+ COMMENT "Building ${json_file} binary flatbuffers...")
list(APPEND all_generated_binary_files ${generated_binary_file})
endforeach()
diff --git a/CMake/CMakeLists_legacy.cmake.in b/CMake/CMakeLists_legacy.cmake.in
new file mode 100644
index 0000000..0a0efd3
--- /dev/null
+++ b/CMake/CMakeLists_legacy.cmake.in
@@ -0,0 +1,774 @@
+# This was the legacy <root>/CMakeLists.txt that supported cmake version 2.8.12.
+# It was originally copied on Jan 30 2022, and is conditionally included in the
+# current <root>/CMakeLists.txt if the cmake version used is older than the new
+# minimum version.
+#
+# Only add to this file to fix immediate issues or if a change cannot be made
+# <root>/CMakeList.txt in a compatible way.
+
+if (POLICY CMP0048)
+ cmake_policy(SET CMP0048 NEW)
+ project(FlatBuffers
+ DESCRIPTION "Flatbuffers serialization library"
+ VERSION 2.0.0
+ LANGUAGES CXX)
+else()
+ project(FlatBuffers)
+endif (POLICY CMP0048)
+
+include(CMake/Version.cmake)
+
+# generate compile_commands.json
+set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
+
+# NOTE: Code coverage only works on Linux & OSX.
+option(FLATBUFFERS_CODE_COVERAGE "Enable the code coverage build option." OFF)
+option(FLATBUFFERS_BUILD_TESTS "Enable the build of tests and samples." ON)
+option(FLATBUFFERS_INSTALL "Enable the installation of targets." ON)
+option(FLATBUFFERS_BUILD_FLATLIB "Enable the build of the flatbuffers library"
+ ON)
+option(FLATBUFFERS_BUILD_FLATC "Enable the build of the flatbuffers compiler"
+ ON)
+option(FLATBUFFERS_STATIC_FLATC "Build flatbuffers compiler with -static flag"
+ OFF)
+option(FLATBUFFERS_BUILD_FLATHASH "Enable the build of flathash" ON)
+option(FLATBUFFERS_BUILD_BENCHMARKS "Enable the build of flatbenchmark. \"
+ Requires C++11."
+ OFF)
+option(FLATBUFFERS_BUILD_GRPCTEST "Enable the build of grpctest" OFF)
+option(FLATBUFFERS_BUILD_SHAREDLIB
+ "Enable the build of the flatbuffers shared library"
+ OFF)
+option(FLATBUFFERS_LIBCXX_WITH_CLANG "Force libc++ when using Clang" ON)
+# NOTE: Sanitizer check only works on Linux & OSX (gcc & llvm).
+option(FLATBUFFERS_CODE_SANITIZE
+ "Add '-fsanitize' flags to 'flattests' and 'flatc' targets."
+ OFF)
+option(FLATBUFFERS_PACKAGE_REDHAT
+ "Build an rpm using the 'package' target."
+ OFF)
+option(FLATBUFFERS_PACKAGE_DEBIAN
+ "Build an deb using the 'package' target."
+ OFF)
+option(FLATBUFFERS_BUILD_CPP17
+ "Enable the build of c++17 test target. \"
+ Requirements: Clang6, GCC7, MSVC2017 (_MSC_VER >= 1914) or higher."
+ OFF)
+option(FLATBUFFERS_BUILD_LEGACY
+ "Run C++ code generator with '--cpp-std c++0x' switch."
+ OFF)
+option(FLATBUFFERS_ENABLE_PCH
+ "Enable precompile headers support for 'flatbuffers' and 'flatc'. \"
+ Only work if CMake supports 'target_precompile_headers'. \"
+ This can speed up compilation time."
+ OFF)
+option(FLATBUFFERS_SKIP_MONSTER_EXTRA
+ "Skip generating monster_extra.fbs that contains non-supported numerical\"
+ types." OFF)
+option(FLATBUFFERS_OSX_BUILD_UNIVERSAL
+ "Enable the build for multiple architectures on OS X (arm64, x86_64)."
+ ON)
+
+if(NOT FLATBUFFERS_BUILD_FLATC AND FLATBUFFERS_BUILD_TESTS)
+ message(WARNING
+ "Cannot build tests without building the compiler. Tests will be disabled.")
+ set(FLATBUFFERS_BUILD_TESTS OFF)
+endif()
+
+if(DEFINED FLATBUFFERS_MAX_PARSING_DEPTH)
+ # Override the default recursion depth limit.
+ add_definitions(-DFLATBUFFERS_MAX_PARSING_DEPTH=${FLATBUFFERS_MAX_PARSING_DEPTH})
+ message(STATUS "FLATBUFFERS_MAX_PARSING_DEPTH: ${FLATBUFFERS_MAX_PARSING_DEPTH}")
+endif()
+
+# Auto-detect locale-narrow 'strtod_l' and 'strtoull_l' functions.
+if(NOT DEFINED FLATBUFFERS_LOCALE_INDEPENDENT)
+ include(CheckCXXSymbolExists)
+
+ set(FLATBUFFERS_LOCALE_INDEPENDENT 0)
+ if(MSVC)
+ check_cxx_symbol_exists(_strtof_l stdlib.h FLATBUFFERS_HAS_STRTOF_L)
+ check_cxx_symbol_exists(_strtoui64_l stdlib.h FLATBUFFERS_HAS_STRTOULL_L)
+ else()
+ check_cxx_symbol_exists(strtof_l stdlib.h FLATBUFFERS_HAS_STRTOF_L)
+ check_cxx_symbol_exists(strtoull_l stdlib.h FLATBUFFERS_HAS_STRTOULL_L)
+ endif()
+ if(FLATBUFFERS_HAS_STRTOF_L AND FLATBUFFERS_HAS_STRTOULL_L)
+ set(FLATBUFFERS_LOCALE_INDEPENDENT 1)
+ endif()
+endif()
+add_definitions(-DFLATBUFFERS_LOCALE_INDEPENDENT=$<BOOL:${FLATBUFFERS_LOCALE_INDEPENDENT}>)
+
+set(FlatBuffers_Library_SRCS
+ include/flatbuffers/allocator.h
+ include/flatbuffers/array.h
+ include/flatbuffers/base.h
+ include/flatbuffers/bfbs_generator.h
+ include/flatbuffers/buffer.h
+ include/flatbuffers/buffer_ref.h
+ include/flatbuffers/default_allocator.h
+ include/flatbuffers/detached_buffer.h
+ include/flatbuffers/flatbuffer_builder.h
+ include/flatbuffers/flatbuffers.h
+ include/flatbuffers/flexbuffers.h
+ include/flatbuffers/hash.h
+ include/flatbuffers/idl.h
+ include/flatbuffers/minireflect.h
+ include/flatbuffers/reflection.h
+ include/flatbuffers/reflection_generated.h
+ include/flatbuffers/registry.h
+ include/flatbuffers/stl_emulation.h
+ include/flatbuffers/string.h
+ include/flatbuffers/struct.h
+ include/flatbuffers/table.h
+ include/flatbuffers/util.h
+ include/flatbuffers/vector.h
+ include/flatbuffers/vector_downward.h
+ include/flatbuffers/verifier.h
+ src/idl_parser.cpp
+ src/idl_gen_text.cpp
+ src/reflection.cpp
+ src/util.cpp
+)
+
+set(FlatBuffers_Compiler_SRCS
+ ${FlatBuffers_Library_SRCS}
+ src/idl_gen_cpp.cpp
+ src/idl_gen_csharp.cpp
+ src/idl_gen_dart.cpp
+ src/idl_gen_kotlin.cpp
+ src/idl_gen_go.cpp
+ src/idl_gen_java.cpp
+ src/idl_gen_ts.cpp
+ src/idl_gen_php.cpp
+ src/idl_gen_python.cpp
+ src/idl_gen_lobster.cpp
+ src/idl_gen_lua.cpp
+ src/idl_gen_rust.cpp
+ src/idl_gen_fbs.cpp
+ src/idl_gen_grpc.cpp
+ src/idl_gen_json_schema.cpp
+ src/idl_gen_swift.cpp
+ src/flatc.cpp
+ src/flatc_main.cpp
+ src/bfbs_gen.h
+ src/bfbs_gen_lua.h
+ include/flatbuffers/code_generators.h
+ src/bfbs_gen_lua.cpp
+ src/code_generators.cpp
+ grpc/src/compiler/schema_interface.h
+ grpc/src/compiler/cpp_generator.h
+ grpc/src/compiler/cpp_generator.cc
+ grpc/src/compiler/go_generator.h
+ grpc/src/compiler/go_generator.cc
+ grpc/src/compiler/java_generator.h
+ grpc/src/compiler/java_generator.cc
+ grpc/src/compiler/python_generator.h
+ grpc/src/compiler/python_generator.cc
+ grpc/src/compiler/swift_generator.h
+ grpc/src/compiler/swift_generator.cc
+ grpc/src/compiler/ts_generator.h
+ grpc/src/compiler/ts_generator.cc
+)
+
+set(FlatHash_SRCS
+ include/flatbuffers/hash.h
+ src/flathash.cpp
+)
+
+set(FlatBuffers_Tests_SRCS
+ ${FlatBuffers_Library_SRCS}
+ src/idl_gen_fbs.cpp
+ tests/test.cpp
+ tests/test_assert.h
+ tests/test_assert.cpp
+ tests/test_builder.h
+ tests/test_builder.cpp
+ tests/native_type_test_impl.h
+ tests/native_type_test_impl.cpp
+ include/flatbuffers/code_generators.h
+ src/code_generators.cpp
+ # file generate by running compiler on tests/monster_test.fbs
+ ${CMAKE_CURRENT_BINARY_DIR}/tests/monster_test_generated.h
+ # file generate by running compiler on namespace_test/namespace_test1.fbs
+ ${CMAKE_CURRENT_BINARY_DIR}/tests/namespace_test/namespace_test1_generated.h
+ ${CMAKE_CURRENT_BINARY_DIR}/tests/namespace_test/namespace_test2_generated.h
+ # file generate by running compiler on union_vector/union_vector.fbs
+ ${CMAKE_CURRENT_BINARY_DIR}/tests/union_vector/union_vector_generated.h
+ # file generate by running compiler on tests/arrays_test.fbs
+ ${CMAKE_CURRENT_BINARY_DIR}/tests/arrays_test_generated.h
+ # file generate by running compiler on tests/native_type_test.fbs
+ ${CMAKE_CURRENT_BINARY_DIR}/tests/native_type_test_generated.h
+ # file generate by running compiler on tests/monster_extra.fbs
+ ${CMAKE_CURRENT_BINARY_DIR}/tests/monster_extra_generated.h
+ # file generate by running compiler on tests/monster_test.fbs
+ ${CMAKE_CURRENT_BINARY_DIR}/tests/monster_test_bfbs_generated.h
+ # file generate by running compiler on tests/optional_scalars.fbs
+ ${CMAKE_CURRENT_BINARY_DIR}/tests/optional_scalars_generated.h
+)
+
+set(FlatBuffers_Tests_CPP17_SRCS
+ ${FlatBuffers_Library_SRCS}
+ tests/test_assert.h
+ tests/test_assert.cpp
+ tests/cpp17/test_cpp17.cpp
+ # file generate by running compiler on tests/monster_test.fbs
+ ${CMAKE_CURRENT_BINARY_DIR}/tests/cpp17/generated_cpp17/monster_test_generated.h
+ ${CMAKE_CURRENT_BINARY_DIR}/tests/monster_test_generated.h
+ ${CMAKE_CURRENT_BINARY_DIR}/tests/cpp17/generated_cpp17/optional_scalars_generated.h
+ ${CMAKE_CURRENT_BINARY_DIR}/tests/optional_scalars_generated.h
+)
+
+set(FlatBuffers_Sample_Binary_SRCS
+ include/flatbuffers/flatbuffers.h
+ samples/sample_binary.cpp
+ # file generated by running compiler on samples/monster.fbs
+ ${CMAKE_CURRENT_BINARY_DIR}/samples/monster_generated.h
+)
+
+set(FlatBuffers_Sample_Text_SRCS
+ ${FlatBuffers_Library_SRCS}
+ samples/sample_text.cpp
+ # file generated by running compiler on samples/monster.fbs
+ ${CMAKE_CURRENT_BINARY_DIR}/samples/monster_generated.h
+)
+
+set(FlatBuffers_Sample_BFBS_SRCS
+ ${FlatBuffers_Library_SRCS}
+ samples/sample_bfbs.cpp
+ # file generated by running compiler on samples/monster.fbs
+ ${CMAKE_CURRENT_BINARY_DIR}/samples/monster_generated.h
+)
+
+set(FlatBuffers_GRPCTest_SRCS
+ include/flatbuffers/flatbuffers.h
+ include/flatbuffers/grpc.h
+ include/flatbuffers/util.h
+ src/util.cpp
+ tests/monster_test.grpc.fb.h
+ tests/test_assert.h
+ tests/test_builder.h
+ tests/monster_test.grpc.fb.cc
+ tests/test_assert.cpp
+ tests/test_builder.cpp
+ grpc/tests/grpctest.cpp
+ grpc/tests/message_builder_test.cpp
+ # file generate by running compiler on tests/monster_test.fbs
+ ${CMAKE_CURRENT_BINARY_DIR}/tests/monster_test_generated.h
+)
+
+# source_group(Compiler FILES ${FlatBuffers_Compiler_SRCS})
+# source_group(Tests FILES ${FlatBuffers_Tests_SRCS})
+
+if(EXISTS "${CMAKE_TOOLCHAIN_FILE}")
+ # do not apply any global settings if the toolchain
+ # is being configured externally
+ message(STATUS "Using toolchain file: ${CMAKE_TOOLCHAIN_FILE}.")
+elseif(CMAKE_COMPILER_IS_GNUCXX)
+ if(CYGWIN)
+ set(CMAKE_CXX_FLAGS
+ "${CMAKE_CXX_FLAGS} -std=gnu++11")
+ else(CYGWIN)
+ set(CMAKE_CXX_FLAGS
+ "${CMAKE_CXX_FLAGS} -std=c++0x")
+ endif(CYGWIN)
+ set(CMAKE_CXX_FLAGS
+ "${CMAKE_CXX_FLAGS} -Wall -pedantic -Werror -Wextra -Werror=shadow")
+ set(FLATBUFFERS_PRIVATE_CXX_FLAGS "-Wold-style-cast")
+ if (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 4.4)
+ if (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 7.0)
+ set(CMAKE_CXX_FLAGS
+ "${CMAKE_CXX_FLAGS} -faligned-new -Werror=implicit-fallthrough=2")
+ endif()
+ set(CMAKE_CXX_FLAGS
+ "${CMAKE_CXX_FLAGS} -Wunused-result -Werror=unused-result -Wunused-parameter -Werror=unused-parameter")
+ endif()
+
+ # Certain platforms such as ARM do not use signed chars by default
+ # which causes issues with certain bounds checks.
+ set(CMAKE_CXX_FLAGS
+ "${CMAKE_CXX_FLAGS} -fsigned-char")
+
+# MSVC **MUST** come before the Clang check, as clang-cl is flagged by CMake as "MSVC", but it still textually
+# matches as Clang in its Compiler Id :)
+# Note: in CMake >= 3.14 we can check CMAKE_CXX_COMPILER_FRONTEND_VARIANT STREQUAL "GNU" or "MSVC" to differentiate...
+elseif(MSVC)
+ # Visual Studio pedantic build settings
+ # warning C4512: assignment operator could not be generated
+ # warning C4316: object allocated on the heap may not be aligned
+ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /W4 /WX /wd4512 /wd4316")
+
+ if(${CMAKE_CXX_COMPILER_ID} MATCHES "Clang")
+ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /D_CRT_SECURE_NO_WARNINGS")
+ endif()
+
+elseif(${CMAKE_CXX_COMPILER_ID} MATCHES "Clang")
+ if(APPLE)
+ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
+
+ if(FLATBUFFERS_OSX_BUILD_UNIVERSAL)
+ set(CMAKE_OSX_ARCHITECTURES "arm64;x86_64")
+ endif()
+ else()
+ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x")
+ endif()
+
+ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -pedantic -Werror -Wextra -Wno-unused-parameter")
+ set(FLATBUFFERS_PRIVATE_CXX_FLAGS "-Wold-style-cast")
+ if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 3.8)
+ list(APPEND FLATBUFFERS_PRIVATE_CXX_FLAGS "-Wimplicit-fallthrough" "-Wextra-semi" "-Werror=unused-private-field") # enable warning
+ endif()
+ if(FLATBUFFERS_LIBCXX_WITH_CLANG)
+ if(NOT "${CMAKE_SYSTEM_NAME}" MATCHES "Linux")
+ set(CMAKE_CXX_FLAGS
+ "${CMAKE_CXX_FLAGS} -stdlib=libc++")
+ endif()
+ if(NOT ("${CMAKE_SYSTEM_NAME}" MATCHES "FreeBSD" OR
+ "${CMAKE_SYSTEM_NAME}" MATCHES "Linux"))
+ set(CMAKE_EXE_LINKER_FLAGS
+ "${CMAKE_EXE_LINKER_FLAGS} -lc++abi")
+ endif()
+ endif()
+
+ # Certain platforms such as ARM do not use signed chars by default
+ # which causes issues with certain bounds checks.
+ set(CMAKE_CXX_FLAGS
+ "${CMAKE_CXX_FLAGS} -fsigned-char")
+
+endif()
+
+# Append FLATBUFFERS_CXX_FLAGS to CMAKE_CXX_FLAGS.
+if(DEFINED FLATBUFFERS_CXX_FLAGS AND NOT EXISTS "${CMAKE_TOOLCHAIN_FILE}")
+ message(STATUS "extend CXX_FLAGS with ${FLATBUFFERS_CXX_FLAGS}")
+ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${FLATBUFFERS_CXX_FLAGS}")
+endif()
+message(STATUS "CMAKE_CXX_FLAGS: ${CMAKE_CXX_FLAGS}")
+
+if(FLATBUFFERS_CODE_COVERAGE)
+ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g -fprofile-arcs -ftest-coverage")
+ set(CMAKE_EXE_LINKER_FLAGS
+ "${CMAKE_EXE_LINKER_FLAGS} -fprofile-arcs -ftest-coverage")
+endif()
+
+function(add_fsanitize_to_target _target _sanitizer)
+ if(WIN32)
+ target_compile_definitions(${_target} PRIVATE FLATBUFFERS_MEMORY_LEAK_TRACKING)
+ message(STATUS "Sanitizer MSVC::_CrtDumpMemoryLeaks added to ${_target}")
+ else()
+ # FLATBUFFERS_CODE_SANITIZE: boolean {ON,OFF,YES,NO} or string with list of sanitizer.
+ # List of sanitizer is string starts with '=': "=address,undefined,thread,memory".
+ if((${CMAKE_CXX_COMPILER_ID} MATCHES "Clang") OR
+ ((${CMAKE_CXX_COMPILER_ID} MATCHES "GNU") AND NOT (CMAKE_CXX_COMPILER_VERSION VERSION_LESS "4.9"))
+ )
+ set(_sanitizer_flags "=address,undefined")
+ if(_sanitizer MATCHES "=.*")
+ # override default by user-defined sanitizer list
+ set(_sanitizer_flags ${_sanitizer})
+ endif()
+ target_compile_options(${_target} PRIVATE
+ -g -fsigned-char -fno-omit-frame-pointer
+ "-fsanitize${_sanitizer_flags}")
+ target_link_libraries(${_target} PRIVATE
+ "-fsanitize${_sanitizer_flags}")
+ set_property(TARGET ${_target} PROPERTY POSITION_INDEPENDENT_CODE ON)
+ message(STATUS "Sanitizer ${_sanitizer_flags} added to ${_target}")
+ endif()
+ endif()
+endfunction()
+
+function(add_pch_to_target _target _pch_header)
+ if(COMMAND target_precompile_headers)
+ target_precompile_headers(${_target} PRIVATE ${_pch_header})
+ if(NOT MSVC)
+ set_source_files_properties(src/util.cpp PROPERTIES SKIP_PRECOMPILE_HEADERS ON)
+ endif()
+ endif()
+endfunction()
+
+if(BIICODE)
+ include(biicode/cmake/biicode.cmake)
+ return()
+endif()
+
+include_directories(include)
+include_directories(grpc)
+
+if(FLATBUFFERS_BUILD_FLATLIB)
+ add_library(flatbuffers STATIC ${FlatBuffers_Library_SRCS})
+ # Attach header directory for when build via add_subdirectory().
+ target_include_directories(flatbuffers INTERFACE
+ $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>)
+ target_compile_options(flatbuffers PRIVATE "${FLATBUFFERS_PRIVATE_CXX_FLAGS}")
+ if(FLATBUFFERS_ENABLE_PCH)
+ add_pch_to_target(flatbuffers include/flatbuffers/pch/pch.h)
+ endif()
+endif()
+
+if(FLATBUFFERS_BUILD_FLATC)
+ add_executable(flatc ${FlatBuffers_Compiler_SRCS})
+ if(FLATBUFFERS_ENABLE_PCH)
+ add_pch_to_target(flatc include/flatbuffers/pch/flatc_pch.h)
+ endif()
+ target_compile_options(flatc PRIVATE "${FLATBUFFERS_PRIVATE_CXX_FLAGS}")
+ if(FLATBUFFERS_CODE_SANITIZE AND NOT WIN32)
+ add_fsanitize_to_target(flatc ${FLATBUFFERS_CODE_SANITIZE})
+ endif()
+ if(NOT FLATBUFFERS_FLATC_EXECUTABLE)
+ set(FLATBUFFERS_FLATC_EXECUTABLE $<TARGET_FILE:flatc>)
+ endif()
+ if(MSVC)
+ # Make flatc.exe not depend on runtime dlls for easy distribution.
+ target_compile_options(flatc PUBLIC $<$<CONFIG:Release>:/MT>)
+ endif()
+ if(FLATBUFFERS_STATIC_FLATC AND NOT MSVC)
+ target_link_libraries(flatc PRIVATE -static)
+ endif()
+endif()
+
+if(FLATBUFFERS_BUILD_FLATHASH)
+ add_executable(flathash ${FlatHash_SRCS})
+endif()
+
+if(FLATBUFFERS_BUILD_SHAREDLIB)
+ add_library(flatbuffers_shared SHARED ${FlatBuffers_Library_SRCS})
+
+ # Shared object version: "major.minor.micro"
+ # - micro updated every release when there is no API/ABI changes
+ # - minor updated when there are additions in API/ABI
+ # - major (ABI number) updated when there are changes in ABI (or removals)
+ set(FlatBuffers_Library_SONAME_MAJOR ${VERSION_MAJOR})
+ set(FlatBuffers_Library_SONAME_FULL "${FlatBuffers_Library_SONAME_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}")
+ set_target_properties(flatbuffers_shared PROPERTIES OUTPUT_NAME flatbuffers
+ SOVERSION "${FlatBuffers_Library_SONAME_MAJOR}"
+ VERSION "${FlatBuffers_Library_SONAME_FULL}")
+ if(FLATBUFFERS_ENABLE_PCH)
+ add_pch_to_target(flatbuffers_shared include/flatbuffers/pch/pch.h)
+ endif()
+endif()
+
+# Global list of generated files.
+# Use the global property to be independent of PARENT_SCOPE.
+set_property(GLOBAL PROPERTY FBS_GENERATED_OUTPUTS)
+
+function(get_generated_output generated_files)
+ get_property(tmp GLOBAL PROPERTY FBS_GENERATED_OUTPUTS)
+ set(${generated_files} ${tmp} PARENT_SCOPE)
+endfunction(get_generated_output)
+
+function(register_generated_output file_name)
+ get_property(tmp GLOBAL PROPERTY FBS_GENERATED_OUTPUTS)
+ list(APPEND tmp ${file_name})
+ set_property(GLOBAL PROPERTY FBS_GENERATED_OUTPUTS ${tmp})
+endfunction(register_generated_output)
+
+function(compile_flatbuffers_schema_to_cpp_opt SRC_FBS OPT)
+ if(FLATBUFFERS_BUILD_LEGACY)
+ set(OPT ${OPT};--cpp-std c++0x)
+ else()
+ # --cpp-std is defined by flatc default settings.
+ endif()
+ message(STATUS "`${SRC_FBS}`: add generation of C++ code with '${OPT}'")
+ get_filename_component(SRC_FBS_DIR ${SRC_FBS} PATH)
+ string(REGEX REPLACE "\\.fbs$" "_generated.h" GEN_HEADER ${SRC_FBS})
+ add_custom_command(
+ OUTPUT ${GEN_HEADER}
+ COMMAND "${FLATBUFFERS_FLATC_EXECUTABLE}"
+ --cpp --gen-mutable --gen-object-api --reflect-names
+ --cpp-ptr-type flatbuffers::unique_ptr # Used to test with C++98 STLs
+ ${OPT}
+ -I "${CMAKE_CURRENT_SOURCE_DIR}/tests/include_test"
+ -o "${SRC_FBS_DIR}"
+ "${CMAKE_CURRENT_SOURCE_DIR}/${SRC_FBS}"
+ DEPENDS flatc
+ COMMENT "Run generation: '${GEN_HEADER}'")
+ register_generated_output(${GEN_HEADER})
+endfunction()
+
+function(compile_flatbuffers_schema_to_cpp SRC_FBS)
+ compile_flatbuffers_schema_to_cpp_opt(${SRC_FBS} "--no-includes;--gen-compare")
+endfunction()
+
+function(compile_flatbuffers_schema_to_binary SRC_FBS)
+ message(STATUS "`${SRC_FBS}`: add generation of binary (.bfbs) schema")
+ get_filename_component(SRC_FBS_DIR ${SRC_FBS} PATH)
+ string(REGEX REPLACE "\\.fbs$" ".bfbs" GEN_BINARY_SCHEMA ${SRC_FBS})
+ # For details about flags see generate_code.py
+ add_custom_command(
+ OUTPUT ${GEN_BINARY_SCHEMA}
+ COMMAND "${FLATBUFFERS_FLATC_EXECUTABLE}"
+ -b --schema --bfbs-comments --bfbs-builtins
+ --bfbs-filenames ${SRC_FBS_DIR}
+ -I "${CMAKE_CURRENT_SOURCE_DIR}/tests/include_test"
+ -o "${SRC_FBS_DIR}"
+ "${CMAKE_CURRENT_SOURCE_DIR}/${SRC_FBS}"
+ DEPENDS flatc
+ COMMENT "Run generation: '${GEN_BINARY_SCHEMA}'")
+ register_generated_output(${GEN_BINARY_SCHEMA})
+endfunction()
+
+function(compile_flatbuffers_schema_to_embedded_binary SRC_FBS OPT)
+ if(FLATBUFFERS_BUILD_LEGACY)
+ set(OPT ${OPT};--cpp-std c++0x)
+ else()
+ # --cpp-std is defined by flatc default settings.
+ endif()
+ message(STATUS "`${SRC_FBS}`: add generation of C++ embedded binary schema code with '${OPT}'")
+ get_filename_component(SRC_FBS_DIR ${SRC_FBS} PATH)
+ string(REGEX REPLACE "\\.fbs$" "_bfbs_generated.h" GEN_BFBS_HEADER ${SRC_FBS})
+ # For details about flags see generate_code.py
+ add_custom_command(
+ OUTPUT ${GEN_BFBS_HEADER}
+ COMMAND "${FLATBUFFERS_FLATC_EXECUTABLE}"
+ --cpp --gen-mutable --gen-object-api --reflect-names
+ --cpp-ptr-type flatbuffers::unique_ptr # Used to test with C++98 STLs
+ ${OPT}
+ --bfbs-comments --bfbs-builtins --bfbs-gen-embed
+ --bfbs-filenames ${SRC_FBS_DIR}
+ -I "${CMAKE_CURRENT_SOURCE_DIR}/tests/include_test"
+ -o "${SRC_FBS_DIR}"
+ "${CMAKE_CURRENT_SOURCE_DIR}/${SRC_FBS}"
+ DEPENDS flatc
+ COMMENT "Run generation: '${GEN_BFBS_HEADER}'")
+ register_generated_output(${GEN_BFBS_HEADER})
+endfunction()
+
+# Look if we have python 3.5 installed so that we can run the generate code
+# python script after flatc is built.
+find_package(PythonInterp 3.5)
+
+if(PYTHONINTERP_FOUND AND
+ # Skip doing this if the MSVC version is below VS 12.
+ # https://cmake.org/cmake/help/latest/variable/MSVC_VERSION.html
+ (NOT MSVC OR MSVC_VERSION GREATER 1800))
+ set(GENERATION_SCRIPT ${PYTHON_EXECUTABLE} scripts/generate_code.py)
+ if(FLATBUFFERS_BUILD_LEGACY)
+ # Need to set --cpp-std c++-0x options
+ set(GENERATION_SCRIPT ${GENERATION_SCRIPT} --cpp-0x)
+ endif()
+ if(FLATBUFFERS_SKIP_MONSTER_EXTRA)
+ set(GENERATION_SCRIPT ${GENERATION_SCRIPT} --skip-monster-extra)
+ endif()
+ add_custom_command(
+ TARGET flatc
+ POST_BUILD
+ COMMAND ${GENERATION_SCRIPT} --flatc "${FLATBUFFERS_FLATC_EXECUTABLE}"
+ WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
+ COMMENT "Running ${GENERATION_SCRIPT}..."
+ VERBATIM)
+else()
+ message("No Python3 interpreter found! Unable to generate files automatically.")
+endif()
+
+if(FLATBUFFERS_BUILD_TESTS)
+ file(COPY "${CMAKE_CURRENT_SOURCE_DIR}/tests" DESTINATION "${CMAKE_CURRENT_BINARY_DIR}")
+ file(COPY "${CMAKE_CURRENT_SOURCE_DIR}/samples" DESTINATION "${CMAKE_CURRENT_BINARY_DIR}")
+
+ # TODO Add (monster_test.fbs monsterdata_test.json)->monsterdata_test.mon
+ compile_flatbuffers_schema_to_cpp(tests/monster_test.fbs)
+ compile_flatbuffers_schema_to_binary(tests/monster_test.fbs)
+ compile_flatbuffers_schema_to_cpp_opt(tests/namespace_test/namespace_test1.fbs "--no-includes;--gen-compare;--gen-name-strings")
+ compile_flatbuffers_schema_to_cpp_opt(tests/namespace_test/namespace_test2.fbs "--no-includes;--gen-compare;--gen-name-strings")
+ compile_flatbuffers_schema_to_cpp_opt(tests/union_vector/union_vector.fbs "--no-includes;--gen-compare;--gen-name-strings")
+ compile_flatbuffers_schema_to_cpp(tests/optional_scalars.fbs)
+ compile_flatbuffers_schema_to_cpp_opt(tests/native_type_test.fbs "")
+ compile_flatbuffers_schema_to_cpp_opt(tests/arrays_test.fbs "--scoped-enums;--gen-compare")
+ compile_flatbuffers_schema_to_binary(tests/arrays_test.fbs)
+ compile_flatbuffers_schema_to_embedded_binary(tests/monster_test.fbs "--no-includes;--gen-compare")
+ if(NOT (MSVC AND (MSVC_VERSION LESS 1900)))
+ compile_flatbuffers_schema_to_cpp(tests/monster_extra.fbs) # Test floating-point NAN/INF.
+ endif()
+ include_directories(${CMAKE_CURRENT_BINARY_DIR}/tests)
+ add_executable(flattests ${FlatBuffers_Tests_SRCS})
+ add_dependencies(flattests generated_code)
+ set_property(TARGET flattests
+ PROPERTY COMPILE_DEFINITIONS FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
+ FLATBUFFERS_DEBUG_VERIFICATION_FAILURE=1)
+ if(FLATBUFFERS_CODE_SANITIZE)
+ add_fsanitize_to_target(flattests ${FLATBUFFERS_CODE_SANITIZE})
+ endif()
+
+ compile_flatbuffers_schema_to_cpp(samples/monster.fbs)
+ compile_flatbuffers_schema_to_binary(samples/monster.fbs)
+ include_directories(${CMAKE_CURRENT_BINARY_DIR}/samples)
+ add_executable(flatsamplebinary ${FlatBuffers_Sample_Binary_SRCS})
+ add_dependencies(flatsamplebinary generated_code)
+ add_executable(flatsampletext ${FlatBuffers_Sample_Text_SRCS})
+ add_dependencies(flatsampletext generated_code)
+ add_executable(flatsamplebfbs ${FlatBuffers_Sample_BFBS_SRCS})
+ add_dependencies(flatsamplebfbs generated_code)
+
+ if(FLATBUFFERS_BUILD_CPP17)
+ # Don't generate header for flattests_cpp17 target.
+ # This target uses "generated_cpp17/monster_test_generated.h"
+ # produced by direct call of generate_code.py script.
+ add_executable(flattests_cpp17 ${FlatBuffers_Tests_CPP17_SRCS})
+ add_dependencies(flattests_cpp17 generated_code)
+ target_compile_features(flattests_cpp17 PRIVATE cxx_std_17)
+ target_compile_definitions(flattests_cpp17 PRIVATE
+ FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
+ FLATBUFFERS_DEBUG_VERIFICATION_FAILURE=1
+ )
+ if(FLATBUFFERS_CODE_SANITIZE)
+ add_fsanitize_to_target(flattests_cpp17 ${FLATBUFFERS_CODE_SANITIZE})
+ endif()
+ endif(FLATBUFFERS_BUILD_CPP17)
+endif()
+
+if(FLATBUFFERS_BUILD_GRPCTEST)
+ if(CMAKE_COMPILER_IS_GNUCXX)
+ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unused-parameter -Wno-shadow")
+ endif()
+ if(NOT GRPC_INSTALL_PATH)
+ message(SEND_ERROR "GRPC_INSTALL_PATH variable is not defined. See grpc/README.md")
+ endif()
+ if(NOT PROTOBUF_DOWNLOAD_PATH)
+ message(SEND_ERROR "PROTOBUF_DOWNLOAD_PATH variable is not defined. See grpc/README.md")
+ endif()
+ INCLUDE_DIRECTORIES(${GRPC_INSTALL_PATH}/include)
+ INCLUDE_DIRECTORIES(${PROTOBUF_DOWNLOAD_PATH}/src)
+ find_package(Threads REQUIRED)
+ list(APPEND CMAKE_PREFIX_PATH ${GRPC_INSTALL_PATH})
+ find_package(absl CONFIG REQUIRED)
+ find_package(protobuf CONFIG REQUIRED)
+ find_package(gRPC CONFIG REQUIRED)
+ add_executable(grpctest ${FlatBuffers_GRPCTest_SRCS})
+ add_dependencies(grpctest generated_code)
+ target_link_libraries(grpctest PRIVATE gRPC::grpc++_unsecure gRPC::grpc_unsecure gRPC::gpr pthread dl)
+ if(FLATBUFFERS_CODE_SANITIZE AND NOT WIN32)
+ # GRPC test has problems with alignment and will fail under ASAN/UBSAN.
+ # add_fsanitize_to_target(grpctest ${FLATBUFFERS_CODE_SANITIZE})
+ endif()
+endif()
+
+
+if(FLATBUFFERS_INSTALL)
+ include(GNUInstallDirs)
+
+ install(DIRECTORY include/flatbuffers DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
+
+ set(FB_CMAKE_DIR "${CMAKE_INSTALL_LIBDIR}/cmake/flatbuffers")
+
+ configure_file(CMake/FlatbuffersConfigVersion.cmake.in FlatbuffersConfigVersion.cmake @ONLY)
+ install(
+ FILES "CMake/FlatbuffersConfig.cmake" "${CMAKE_CURRENT_BINARY_DIR}/FlatbuffersConfigVersion.cmake"
+ DESTINATION ${FB_CMAKE_DIR}
+ )
+
+ if(FLATBUFFERS_BUILD_FLATLIB)
+ if(CMAKE_VERSION VERSION_LESS 3.0)
+ install(
+ TARGETS flatbuffers EXPORT FlatbuffersTargets
+ ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
+ )
+ else()
+ install(
+ TARGETS flatbuffers EXPORT FlatbuffersTargets
+ ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
+ INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
+ )
+ endif()
+
+ install(EXPORT FlatbuffersTargets
+ FILE FlatbuffersTargets.cmake
+ NAMESPACE flatbuffers::
+ DESTINATION ${FB_CMAKE_DIR}
+ )
+ endif()
+
+ if(FLATBUFFERS_BUILD_FLATC)
+ install(
+ TARGETS flatc EXPORT FlatcTargets
+ RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
+ )
+
+ install(
+ EXPORT FlatcTargets
+ FILE FlatcTargets.cmake
+ NAMESPACE flatbuffers::
+ DESTINATION ${FB_CMAKE_DIR}
+ )
+ endif()
+
+ if(FLATBUFFERS_BUILD_SHAREDLIB)
+ if(CMAKE_VERSION VERSION_LESS 3.0)
+ install(
+ TARGETS flatbuffers_shared EXPORT FlatbuffersSharedTargets
+ ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
+ RUNTIME DESTINATION ${CMAKE_INSTALL_LIBDIR}
+ LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
+ )
+ else()
+ install(
+ TARGETS flatbuffers_shared EXPORT FlatbuffersSharedTargets
+ ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
+ RUNTIME DESTINATION ${CMAKE_INSTALL_LIBDIR}
+ LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
+ INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
+ )
+ endif()
+
+ install(
+ EXPORT FlatbuffersSharedTargets
+ FILE FlatbuffersSharedTargets.cmake
+ NAMESPACE flatbuffers::
+ DESTINATION ${FB_CMAKE_DIR}
+ )
+ endif()
+
+ if(FLATBUFFERS_BUILD_SHAREDLIB OR FLATBUFFERS_BUILD_FLATLIB)
+ configure_file(CMake/flatbuffers.pc.in flatbuffers.pc @ONLY)
+ install(
+ FILES "${CMAKE_CURRENT_BINARY_DIR}/flatbuffers.pc"
+ DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig
+ )
+ endif()
+endif()
+
+if(FLATBUFFERS_BUILD_TESTS)
+ enable_testing()
+
+ add_test(NAME flattests COMMAND flattests)
+ if(FLATBUFFERS_BUILD_CPP17)
+ add_test(NAME flattests_cpp17 COMMAND flattests_cpp17)
+ endif()
+ if(FLATBUFFERS_BUILD_GRPCTEST)
+ add_test(NAME grpctest COMMAND grpctest)
+ endif()
+endif()
+
+# This target is sync-barrier.
+# Other generate-dependent targets can depend on 'generated_code' only.
+get_generated_output(fbs_generated)
+if(fbs_generated)
+ # message(STATUS "Add generated_code target with files:${fbs_generated}")
+ add_custom_target(generated_code
+ DEPENDS ${fbs_generated}
+ COMMENT "All generated files were updated.")
+endif()
+
+include(CMake/BuildFlatBuffers.cmake)
+
+if(UNIX)
+ # Use of CPack only supported on Linux systems.
+ if(FLATBUFFERS_PACKAGE_DEBIAN)
+ include(CMake/PackageDebian.cmake)
+ include(CPack)
+ endif()
+ if (FLATBUFFERS_PACKAGE_REDHAT)
+ include(CMake/PackageRedhat.cmake)
+ include(CPack)
+ endif()
+endif()
+
+# Include for running Google Benchmarks.
+if(FLATBUFFERS_BUILD_BENCHMARKS AND CMAKE_VERSION VERSION_GREATER 3.13)
+ add_subdirectory(benchmarks)
+endif()
+
+# Add FlatBuffers::FlatBuffers interface, needed for FetchContent_Declare
+add_library(FlatBuffers INTERFACE)
+add_library(FlatBuffers::FlatBuffers ALIAS FlatBuffers)
+target_include_directories(
+ FlatBuffers
+ INTERFACE $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
+ $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}/include>)
\ No newline at end of file
diff --git a/CMake/Version.cmake b/CMake/Version.cmake
index 329a8cc..4825d18 100644
--- a/CMake/Version.cmake
+++ b/CMake/Version.cmake
@@ -1,12 +1,12 @@
-set(VERSION_MAJOR 1)
-set(VERSION_MINOR 12)
-set(VERSION_PATCH 0)
+set(VERSION_MAJOR 2)
+set(VERSION_MINOR 0)
+set(VERSION_PATCH 6)
set(VERSION_COMMIT 0)
find_program(GIT git)
-if(GIT)
+if(GIT AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/.git")
execute_process(
- COMMAND ${GIT} describe
+ COMMAND ${GIT} describe --tags
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
OUTPUT_VARIABLE GIT_DESCRIBE_DIRTY
OUTPUT_STRIP_TRAILING_WHITESPACE
@@ -25,4 +25,4 @@
message(WARNING "git is not found")
endif()
-message("Proceeding with version: ${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}.${VERSION_COMMIT}")
+message(STATUS "Proceeding with version: ${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}.${VERSION_COMMIT}")
diff --git a/CMake/flatbuffers.pc.in b/CMake/flatbuffers.pc.in
new file mode 100644
index 0000000..110770a
--- /dev/null
+++ b/CMake/flatbuffers.pc.in
@@ -0,0 +1,9 @@
+libdir=@CMAKE_INSTALL_FULL_LIBDIR@
+includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@
+
+Name: FlatBuffers
+Description: Memory Efficient Serialization Library
+Version: @VERSION_MAJOR@.@VERSION_MINOR@.@VERSION_PATCH@
+
+Libs: -L${libdir} -lflatbuffers
+Cflags: -I${includedir}
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 6e2b32b..9bf07fe 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1,9 +1,35 @@
-cmake_minimum_required(VERSION 2.8.12)
+# This is the legacy minimum version flatbuffers supported for a while.
+cmake_minimum_required(VERSION 2.8.12...3.22.1)
+
+# CMake version 3.16 is the 'de-facto' minimum version for flatbuffers. If the
+# current cmake is older than this, warn the user and include the legacy file to
+# provide some level of support.
+if(CMAKE_VERSION VERSION_LESS 3.16)
+ message(WARNING "Using cmake version ${CMAKE_VERSION} which is older than "
+ "our target version of 3.16. This will use the legacy CMakeLists.txt that "
+ "supports version 2.8.12 and higher, but not actively maintained. Consider "
+ "upgrading cmake to a newer version, as this may become a fatal error in the "
+ "future.")
+ # Use the legacy version of CMakeLists.txt
+ include(CMake/CMakeLists_legacy.cmake.in)
+ return()
+endif()
+
+# Attempt to read the current version of flatbuffers by looking at the latest tag.
+include(CMake/Version.cmake)
+
+if (POLICY CMP0048)
+ cmake_policy(SET CMP0048 NEW)
+ project(FlatBuffers
+ DESCRIPTION "Flatbuffers serialization library"
+ VERSION ${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}
+ LANGUAGES CXX)
+else()
+ project(FlatBuffers)
+endif (POLICY CMP0048)
+
# generate compile_commands.json
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
-include(CheckCXXSymbolExists)
-
-project(FlatBuffers)
# NOTE: Code coverage only works on Linux & OSX.
option(FLATBUFFERS_CODE_COVERAGE "Enable the code coverage build option." OFF)
@@ -16,6 +42,8 @@
option(FLATBUFFERS_STATIC_FLATC "Build flatbuffers compiler with -static flag"
OFF)
option(FLATBUFFERS_BUILD_FLATHASH "Enable the build of flathash" ON)
+option(FLATBUFFERS_BUILD_BENCHMARKS "Enable the build of flatbenchmark."
+ OFF)
option(FLATBUFFERS_BUILD_GRPCTEST "Enable the build of grpctest" OFF)
option(FLATBUFFERS_BUILD_SHAREDLIB
"Enable the build of the flatbuffers shared library"
@@ -43,6 +71,12 @@
Only work if CMake supports 'target_precompile_headers'. \"
This can speed up compilation time."
OFF)
+option(FLATBUFFERS_SKIP_MONSTER_EXTRA
+ "Skip generating monster_extra.fbs that contains non-supported numerical\"
+ types." OFF)
+option(FLATBUFFERS_OSX_BUILD_UNIVERSAL
+ "Enable the build for multiple architectures on OS X (arm64, x86_64)."
+ ON)
if(NOT FLATBUFFERS_BUILD_FLATC AND FLATBUFFERS_BUILD_TESTS)
message(WARNING
@@ -58,6 +92,8 @@
# Auto-detect locale-narrow 'strtod_l' and 'strtoull_l' functions.
if(NOT DEFINED FLATBUFFERS_LOCALE_INDEPENDENT)
+ include(CheckCXXSymbolExists)
+
set(FLATBUFFERS_LOCALE_INDEPENDENT 0)
if(MSVC)
check_cxx_symbol_exists(_strtof_l stdlib.h FLATBUFFERS_HAS_STRTOF_L)
@@ -73,17 +109,31 @@
add_definitions(-DFLATBUFFERS_LOCALE_INDEPENDENT=$<BOOL:${FLATBUFFERS_LOCALE_INDEPENDENT}>)
set(FlatBuffers_Library_SRCS
+ include/flatbuffers/allocator.h
+ include/flatbuffers/array.h
include/flatbuffers/base.h
+ include/flatbuffers/bfbs_generator.h
+ include/flatbuffers/buffer.h
+ include/flatbuffers/buffer_ref.h
+ include/flatbuffers/default_allocator.h
+ include/flatbuffers/detached_buffer.h
+ include/flatbuffers/flatbuffer_builder.h
include/flatbuffers/flatbuffers.h
+ include/flatbuffers/flexbuffers.h
include/flatbuffers/hash.h
include/flatbuffers/idl.h
- include/flatbuffers/util.h
+ include/flatbuffers/minireflect.h
include/flatbuffers/reflection.h
include/flatbuffers/reflection_generated.h
- include/flatbuffers/stl_emulation.h
- include/flatbuffers/flexbuffers.h
include/flatbuffers/registry.h
- include/flatbuffers/minireflect.h
+ include/flatbuffers/stl_emulation.h
+ include/flatbuffers/string.h
+ include/flatbuffers/struct.h
+ include/flatbuffers/table.h
+ include/flatbuffers/util.h
+ include/flatbuffers/vector.h
+ include/flatbuffers/vector_downward.h
+ include/flatbuffers/verifier.h
src/idl_parser.cpp
src/idl_gen_text.cpp
src/reflection.cpp
@@ -98,7 +148,7 @@
src/idl_gen_kotlin.cpp
src/idl_gen_go.cpp
src/idl_gen_java.cpp
- src/idl_gen_js_ts.cpp
+ src/idl_gen_ts.cpp
src/idl_gen_php.cpp
src/idl_gen_python.cpp
src/idl_gen_lobster.cpp
@@ -110,7 +160,10 @@
src/idl_gen_swift.cpp
src/flatc.cpp
src/flatc_main.cpp
+ src/bfbs_gen.h
+ src/bfbs_gen_lua.h
include/flatbuffers/code_generators.h
+ src/bfbs_gen_lua.cpp
src/code_generators.cpp
grpc/src/compiler/schema_interface.h
grpc/src/compiler/cpp_generator.h
@@ -120,7 +173,6 @@
grpc/src/compiler/java_generator.h
grpc/src/compiler/java_generator.cc
grpc/src/compiler/python_generator.h
- grpc/src/compiler/python_private_generator.h
grpc/src/compiler/python_generator.cc
grpc/src/compiler/swift_generator.h
grpc/src/compiler/swift_generator.cc
@@ -221,18 +273,7 @@
# do not apply any global settings if the toolchain
# is being configured externally
message(STATUS "Using toolchain file: ${CMAKE_TOOLCHAIN_FILE}.")
-elseif(APPLE)
- set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -stdlib=libc++")
- set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -pedantic -Werror -Wextra -Wno-unused-parameter")
- set(FLATBUFFERS_PRIVATE_CXX_FLAGS "-Wold-style-cast")
elseif(CMAKE_COMPILER_IS_GNUCXX)
- if(CYGWIN)
- set(CMAKE_CXX_FLAGS
- "${CMAKE_CXX_FLAGS} -std=gnu++11")
- else(CYGWIN)
- set(CMAKE_CXX_FLAGS
- "${CMAKE_CXX_FLAGS} -std=c++0x")
- endif(CYGWIN)
set(CMAKE_CXX_FLAGS
"${CMAKE_CXX_FLAGS} -Wall -pedantic -Werror -Wextra -Werror=shadow")
set(FLATBUFFERS_PRIVATE_CXX_FLAGS "-Wold-style-cast")
@@ -250,9 +291,27 @@
set(CMAKE_CXX_FLAGS
"${CMAKE_CXX_FLAGS} -fsigned-char")
+# MSVC **MUST** come before the Clang check, as clang-cl is flagged by CMake as "MSVC", but it still textually
+# matches as Clang in its Compiler Id :)
+# Note: in CMake >= 3.14 we can check CMAKE_CXX_COMPILER_FRONTEND_VARIANT STREQUAL "GNU" or "MSVC" to differentiate...
+elseif(MSVC)
+ # Visual Studio pedantic build settings
+ # warning C4512: assignment operator could not be generated
+ # warning C4316: object allocated on the heap may not be aligned
+ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /W4 /WX /wd4512 /wd4316")
+
+ if(${CMAKE_CXX_COMPILER_ID} MATCHES "Clang")
+ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /D_CRT_SECURE_NO_WARNINGS")
+ endif()
+
elseif(${CMAKE_CXX_COMPILER_ID} MATCHES "Clang")
- set(CMAKE_CXX_FLAGS
- "${CMAKE_CXX_FLAGS} -std=c++0x -Wall -pedantic -Werror -Wextra -Wno-unused-parameter")
+ if(APPLE)
+ if(FLATBUFFERS_OSX_BUILD_UNIVERSAL)
+ set(CMAKE_OSX_ARCHITECTURES "arm64;x86_64")
+ endif()
+ endif()
+
+ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -pedantic -Werror -Wextra -Wno-unused-parameter")
set(FLATBUFFERS_PRIVATE_CXX_FLAGS "-Wold-style-cast")
if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 3.8)
list(APPEND FLATBUFFERS_PRIVATE_CXX_FLAGS "-Wimplicit-fallthrough" "-Wextra-semi" "-Werror=unused-private-field") # enable warning
@@ -274,16 +333,15 @@
set(CMAKE_CXX_FLAGS
"${CMAKE_CXX_FLAGS} -fsigned-char")
-elseif(MSVC)
- # Visual Studio pedantic build settings
- # warning C4512: assignment operator could not be generated
- # warning C4316: object allocated on the heap may not be aligned
- set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /W4 /WX /wd4512 /wd4316")
-
- # multi-core build.
- add_definitions("/MP")
endif()
+# Append FLATBUFFERS_CXX_FLAGS to CMAKE_CXX_FLAGS.
+if(DEFINED FLATBUFFERS_CXX_FLAGS AND NOT EXISTS "${CMAKE_TOOLCHAIN_FILE}")
+ message(STATUS "extend CXX_FLAGS with ${FLATBUFFERS_CXX_FLAGS}")
+ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${FLATBUFFERS_CXX_FLAGS}")
+endif()
+message(STATUS "CMAKE_CXX_FLAGS: ${CMAKE_CXX_FLAGS}")
+
if(FLATBUFFERS_CODE_COVERAGE)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g -fprofile-arcs -ftest-coverage")
set(CMAKE_EXE_LINKER_FLAGS
@@ -325,11 +383,6 @@
endif()
endfunction()
-if(BIICODE)
- include(biicode/cmake/biicode.cmake)
- return()
-endif()
-
include_directories(include)
include_directories(grpc)
@@ -339,6 +392,7 @@
target_include_directories(flatbuffers INTERFACE
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>)
target_compile_options(flatbuffers PRIVATE "${FLATBUFFERS_PRIVATE_CXX_FLAGS}")
+ target_compile_features(flatbuffers PUBLIC cxx_std_11)
if(FLATBUFFERS_ENABLE_PCH)
add_pch_to_target(flatbuffers include/flatbuffers/pch/pch.h)
endif()
@@ -350,6 +404,7 @@
add_pch_to_target(flatc include/flatbuffers/pch/flatc_pch.h)
endif()
target_compile_options(flatc PRIVATE "${FLATBUFFERS_PRIVATE_CXX_FLAGS}")
+ target_compile_features(flatc PUBLIC cxx_std_11)
if(FLATBUFFERS_CODE_SANITIZE AND NOT WIN32)
add_fsanitize_to_target(flatc ${FLATBUFFERS_CODE_SANITIZE})
endif()
@@ -367,17 +422,18 @@
if(FLATBUFFERS_BUILD_FLATHASH)
add_executable(flathash ${FlatHash_SRCS})
+ target_compile_features(flathash PUBLIC cxx_std_11)
endif()
if(FLATBUFFERS_BUILD_SHAREDLIB)
add_library(flatbuffers_shared SHARED ${FlatBuffers_Library_SRCS})
-
+ target_compile_features(flatbuffers_shared PUBLIC cxx_std_11)
# Shared object version: "major.minor.micro"
# - micro updated every release when there is no API/ABI changes
# - minor updated when there are additions in API/ABI
# - major (ABI number) updated when there are changes in ABI (or removals)
- set(FlatBuffers_Library_SONAME_MAJOR "1")
- set(FlatBuffers_Library_SONAME_FULL "${FlatBuffers_Library_SONAME_MAJOR}.12.0")
+ set(FlatBuffers_Library_SONAME_MAJOR ${VERSION_MAJOR})
+ set(FlatBuffers_Library_SONAME_FULL "${FlatBuffers_Library_SONAME_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}")
set_target_properties(flatbuffers_shared PROPERTIES OUTPUT_NAME flatbuffers
SOVERSION "${FlatBuffers_Library_SONAME_MAJOR}"
VERSION "${FlatBuffers_Library_SONAME_FULL}")
@@ -432,11 +488,12 @@
message(STATUS "`${SRC_FBS}`: add generation of binary (.bfbs) schema")
get_filename_component(SRC_FBS_DIR ${SRC_FBS} PATH)
string(REGEX REPLACE "\\.fbs$" ".bfbs" GEN_BINARY_SCHEMA ${SRC_FBS})
- # For details about flags see generate_code.bat(sh)
+ # For details about flags see generate_code.py
add_custom_command(
OUTPUT ${GEN_BINARY_SCHEMA}
COMMAND "${FLATBUFFERS_FLATC_EXECUTABLE}"
-b --schema --bfbs-comments --bfbs-builtins
+ --bfbs-filenames ${SRC_FBS_DIR}
-I "${CMAKE_CURRENT_SOURCE_DIR}/tests/include_test"
-o "${SRC_FBS_DIR}"
"${CMAKE_CURRENT_SOURCE_DIR}/${SRC_FBS}"
@@ -454,7 +511,7 @@
message(STATUS "`${SRC_FBS}`: add generation of C++ embedded binary schema code with '${OPT}'")
get_filename_component(SRC_FBS_DIR ${SRC_FBS} PATH)
string(REGEX REPLACE "\\.fbs$" "_bfbs_generated.h" GEN_BFBS_HEADER ${SRC_FBS})
- # For details about flags see generate_code.bat(sh)
+ # For details about flags see generate_code.py
add_custom_command(
OUTPUT ${GEN_BFBS_HEADER}
COMMAND "${FLATBUFFERS_FLATC_EXECUTABLE}"
@@ -462,6 +519,7 @@
--cpp-ptr-type flatbuffers::unique_ptr # Used to test with C++98 STLs
${OPT}
--bfbs-comments --bfbs-builtins --bfbs-gen-embed
+ --bfbs-filenames ${SRC_FBS_DIR}
-I "${CMAKE_CURRENT_SOURCE_DIR}/tests/include_test"
-o "${SRC_FBS_DIR}"
"${CMAKE_CURRENT_SOURCE_DIR}/${SRC_FBS}"
@@ -477,9 +535,9 @@
# TODO Add (monster_test.fbs monsterdata_test.json)->monsterdata_test.mon
compile_flatbuffers_schema_to_cpp(tests/monster_test.fbs)
compile_flatbuffers_schema_to_binary(tests/monster_test.fbs)
- compile_flatbuffers_schema_to_cpp(tests/namespace_test/namespace_test1.fbs)
- compile_flatbuffers_schema_to_cpp(tests/namespace_test/namespace_test2.fbs)
- compile_flatbuffers_schema_to_cpp(tests/union_vector/union_vector.fbs)
+ compile_flatbuffers_schema_to_cpp_opt(tests/namespace_test/namespace_test1.fbs "--no-includes;--gen-compare;--gen-name-strings")
+ compile_flatbuffers_schema_to_cpp_opt(tests/namespace_test/namespace_test2.fbs "--no-includes;--gen-compare;--gen-name-strings")
+ compile_flatbuffers_schema_to_cpp_opt(tests/union_vector/union_vector.fbs "--no-includes;--gen-compare;--gen-name-strings")
compile_flatbuffers_schema_to_cpp(tests/optional_scalars.fbs)
compile_flatbuffers_schema_to_cpp_opt(tests/native_type_test.fbs "")
compile_flatbuffers_schema_to_cpp_opt(tests/arrays_test.fbs "--scoped-enums;--gen-compare")
@@ -490,6 +548,7 @@
endif()
include_directories(${CMAKE_CURRENT_BINARY_DIR}/tests)
add_executable(flattests ${FlatBuffers_Tests_SRCS})
+ target_compile_features(flattests PUBLIC cxx_std_11)
add_dependencies(flattests generated_code)
set_property(TARGET flattests
PROPERTY COMPILE_DEFINITIONS FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
@@ -502,16 +561,19 @@
compile_flatbuffers_schema_to_binary(samples/monster.fbs)
include_directories(${CMAKE_CURRENT_BINARY_DIR}/samples)
add_executable(flatsamplebinary ${FlatBuffers_Sample_Binary_SRCS})
+ target_compile_features(flatsamplebinary PUBLIC cxx_std_11)
add_dependencies(flatsamplebinary generated_code)
add_executable(flatsampletext ${FlatBuffers_Sample_Text_SRCS})
+ target_compile_features(flatsampletext PUBLIC cxx_std_11)
add_dependencies(flatsampletext generated_code)
add_executable(flatsamplebfbs ${FlatBuffers_Sample_BFBS_SRCS})
+ target_compile_features(flatsamplebfbs PUBLIC cxx_std_11)
add_dependencies(flatsamplebfbs generated_code)
if(FLATBUFFERS_BUILD_CPP17)
# Don't generate header for flattests_cpp17 target.
# This target uses "generated_cpp17/monster_test_generated.h"
- # produced by direct call of generate_code.bat(sh) script.
+ # produced by direct call of generate_code.py script.
add_executable(flattests_cpp17 ${FlatBuffers_Tests_CPP17_SRCS})
add_dependencies(flattests_cpp17 generated_code)
target_compile_features(flattests_cpp17 PRIVATE cxx_std_17)
@@ -537,17 +599,21 @@
endif()
INCLUDE_DIRECTORIES(${GRPC_INSTALL_PATH}/include)
INCLUDE_DIRECTORIES(${PROTOBUF_DOWNLOAD_PATH}/src)
- LINK_DIRECTORIES(${GRPC_INSTALL_PATH}/lib)
+ find_package(Threads REQUIRED)
+ list(APPEND CMAKE_PREFIX_PATH ${GRPC_INSTALL_PATH})
+ find_package(absl CONFIG REQUIRED)
+ find_package(protobuf CONFIG REQUIRED)
+ find_package(gRPC CONFIG REQUIRED)
add_executable(grpctest ${FlatBuffers_GRPCTest_SRCS})
add_dependencies(grpctest generated_code)
- target_link_libraries(grpctest PRIVATE grpc++_unsecure grpc_unsecure gpr pthread dl)
+ target_compile_features(grpctest PRIVATE cxx_std_11)
+ target_link_libraries(grpctest PRIVATE gRPC::grpc++_unsecure gRPC::grpc_unsecure gRPC::gpr pthread dl)
if(FLATBUFFERS_CODE_SANITIZE AND NOT WIN32)
# GRPC test has problems with alignment and will fail under ASAN/UBSAN.
# add_fsanitize_to_target(grpctest ${FLATBUFFERS_CODE_SANITIZE})
endif()
endif()
-include(CMake/Version.cmake)
if(FLATBUFFERS_INSTALL)
include(GNUInstallDirs)
@@ -563,18 +629,11 @@
)
if(FLATBUFFERS_BUILD_FLATLIB)
- if(CMAKE_VERSION VERSION_LESS 3.0)
- install(
- TARGETS flatbuffers EXPORT FlatbuffersTargets
- ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
- )
- else()
- install(
- TARGETS flatbuffers EXPORT FlatbuffersTargets
- ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
- INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
- )
- endif()
+ install(
+ TARGETS flatbuffers EXPORT FlatbuffersTargets
+ ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
+ INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
+ )
install(EXPORT FlatbuffersTargets
FILE FlatbuffersTargets.cmake
@@ -598,30 +657,29 @@
endif()
if(FLATBUFFERS_BUILD_SHAREDLIB)
- if(CMAKE_VERSION VERSION_LESS 3.0)
- install(
- TARGETS flatbuffers_shared EXPORT FlatbuffersSharedTargets
- ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
- RUNTIME DESTINATION ${CMAKE_INSTALL_LIBDIR}
- LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
- )
- else()
- install(
- TARGETS flatbuffers_shared EXPORT FlatbuffersSharedTargets
- ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
- RUNTIME DESTINATION ${CMAKE_INSTALL_LIBDIR}
- LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
- INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
- )
- endif()
+ install(
+ TARGETS flatbuffers_shared EXPORT FlatbuffersSharedTargets
+ ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
+ RUNTIME DESTINATION ${CMAKE_INSTALL_LIBDIR}
+ LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
+ INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
+ )
- install(
+ install(
EXPORT FlatbuffersSharedTargets
FILE FlatbuffersSharedTargets.cmake
NAMESPACE flatbuffers::
DESTINATION ${FB_CMAKE_DIR}
)
endif()
+
+ if(FLATBUFFERS_BUILD_SHAREDLIB OR FLATBUFFERS_BUILD_FLATLIB)
+ configure_file(CMake/flatbuffers.pc.in flatbuffers.pc @ONLY)
+ install(
+ FILES "${CMAKE_CURRENT_BINARY_DIR}/flatbuffers.pc"
+ DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig
+ )
+ endif()
endif()
if(FLATBUFFERS_BUILD_TESTS)
@@ -659,3 +717,16 @@
include(CPack)
endif()
endif()
+
+# Include for running Google Benchmarks.
+if(FLATBUFFERS_BUILD_BENCHMARKS)
+ add_subdirectory(benchmarks)
+endif()
+
+# Add FlatBuffers::FlatBuffers interface, needed for FetchContent_Declare
+add_library(FlatBuffers INTERFACE)
+add_library(FlatBuffers::FlatBuffers ALIAS FlatBuffers)
+target_include_directories(
+ FlatBuffers
+ INTERFACE $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
+ $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}/include>)
\ No newline at end of file
diff --git a/Formatters.md b/Formatters.md
new file mode 100644
index 0000000..877c5f2
--- /dev/null
+++ b/Formatters.md
@@ -0,0 +1,22 @@
+# Format Guidelines
+
+If you are interesting in contributing to the flatbuffers project, please take a second to read this document. Each language has it's own set of rules, that are defined in their respective formatter/linter documents.
+
+# Notes
+
+- Run the linter on the language you are working on before making a Pull Request.
+- DONT format/lint the generated code.
+
+# Languages
+
+## C++
+
+C++ uses `clang-format` as it's formatter. Run the following script `sh scripts/clang-format-git.sh`, and it should style the C++ code according to [google style guide](https://google.github.io/styleguide/cppguide.html).
+
+## Swift
+
+Swift uses swiftformat as it's formatter. Take a look at [how to install here](https://github.com/nicklockwood/SwiftFormat/blob/master/README.md#how-do-i-install-it). Run the following command `swiftformat --config swift.swiftformat .` in the root directory of the project
+
+## Typescript
+
+Typescript uses eslint as it's linter. Take a look at [how to install here](https://eslint.org/docs/user-guide/getting-started). Run the following command `eslint ts/** --ext .ts` in the root directory of the project
\ No newline at end of file
diff --git a/SECURITY.md b/SECURITY.md
new file mode 100644
index 0000000..c61f66f
--- /dev/null
+++ b/SECURITY.md
@@ -0,0 +1,11 @@
+# Security Policy
+
+## Reporting a Vulnerability
+
+To report a security issue, please use http://g.co/vulnz. We use
+http://g.co/vulnz for our intake, and do coordination and disclosure here on
+GitHub (including using GitHub Security Advisory). The Google Security Team will
+respond within 5 working days of your report on g.co/vulnz.
+
+Select the `I want to report a technical security or an abuse risk related bug
+in a Google product (SQLi, XSS, etc.)` option and complete the form.
diff --git a/WORKSPACE b/WORKSPACE
index d856cc6..f030e86 100644
--- a/WORKSPACE
+++ b/WORKSPACE
@@ -18,14 +18,10 @@
go_register_toolchains()
##### Protobuf
-_PROTOBUF_VERSION = "3.6.1"
+_PROTOBUF_VERSION = "3.15.2"
http_archive(
name = "com_google_protobuf",
- patch_args = ["-p1"],
- patches = [
- "//bazel:protobuf_deps_3_6_1.patch",
- ],
strip_prefix = "protobuf-" + _PROTOBUF_VERSION,
urls = [
"https://github.com/protocolbuffers/protobuf/archive/v" + _PROTOBUF_VERSION + ".tar.gz",
@@ -33,15 +29,10 @@
)
##### GRPC
-_GRPC_VERSION = "1.15.1"
+_GRPC_VERSION = "1.42.0"
http_archive(
name = "com_github_grpc_grpc",
- patch_args = ["-p1"],
- patches = [
- "//bazel:grpc_deps_1_15_1.patch",
- "//bazel:grpc_deps_1_15_1_02.patch",
- ],
strip_prefix = "grpc-" + _GRPC_VERSION,
urls = ["https://github.com/grpc/grpc/archive/v" + _GRPC_VERSION + ".tar.gz"],
)
@@ -49,3 +40,31 @@
load("@com_github_grpc_grpc//bazel:grpc_deps.bzl", "grpc_deps")
grpc_deps()
+
+load("@com_github_grpc_grpc//bazel:grpc_extra_deps.bzl", "grpc_extra_deps")
+
+grpc_extra_deps()
+
+http_archive(
+ name = "build_bazel_rules_nodejs",
+ sha256 = "965ee2492a2b087cf9e0f2ca472aeaf1be2eb650e0cfbddf514b9a7d3ea4b02a",
+ urls = ["https://github.com/bazelbuild/rules_nodejs/releases/download/5.2.0/rules_nodejs-5.2.0.tar.gz"],
+)
+
+load("@build_bazel_rules_nodejs//:repositories.bzl", "build_bazel_rules_nodejs_dependencies")
+
+build_bazel_rules_nodejs_dependencies()
+
+load("@build_bazel_rules_nodejs//:index.bzl", "node_repositories", "yarn_install")
+
+node_repositories()
+
+yarn_install(
+ name = "npm",
+ exports_directories_only = False,
+ # Unfreeze to add/remove packages.
+ frozen_lockfile = True,
+ package_json = "//:package.json",
+ symlink_node_modules = False,
+ yarn_lock = "//:yarn.lock",
+)
diff --git a/android/AndroidManifest.xml b/android/AndroidManifest.xml
index 846fd13..c755e6d 100644
--- a/android/AndroidManifest.xml
+++ b/android/AndroidManifest.xml
@@ -1,20 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (c) 2013 Google, Inc.
-
- This software is provided 'as-is', without any express or implied
- warranty. In no event will the authors be held liable for any damages
- arising from the use of this software.
- Permission is granted to anyone to use this software for any purpose,
- including commercial applications, and to alter it and redistribute it
- freely, subject to the following restrictions:
- 1. The origin of this software must not be misrepresented; you must not
- claim that you wrote the original software. If you use this software
- in a product, an acknowledgment in the product documentation would be
- appreciated but is not required.
- 2. Altered source versions must be plainly marked as such, and must not be
- misrepresented as being the original software.
- 3. This notice may not be removed or altered from any source distribution.
- -->
<!-- BEGIN_INCLUDE(manifest) -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.FlatBufferTest">
diff --git a/android/app/build.gradle b/android/app/build.gradle
index 3ee9ba2..dba6624 100644
--- a/android/app/build.gradle
+++ b/android/app/build.gradle
@@ -48,7 +48,11 @@
standardOutput = new ByteArrayOutputStream()
errorOutput = new ByteArrayOutputStream()
- commandLine 'flatc', '-o', outputCppDir, '--cpp', "${fbsFiles.join(" ")}"
+ def commandLineArgs = ['flatc', '-o', outputCppDir, '--cpp']
+ fbsFiles.forEach{
+ commandLineArgs.add(it.path)
+ }
+ commandLine commandLineArgs
doFirst {
delete "$outputCppDir/"
@@ -70,7 +74,11 @@
standardOutput = new ByteArrayOutputStream()
errorOutput = new ByteArrayOutputStream()
- commandLine 'flatc', '-o', outputKotlinDir, '--kotlin', "${fbsFiles.join(" ")}"
+ def commandLineArgs = ['flatc', '-o', outputKotlinDir, '--kotlin']
+ fbsFiles.forEach{
+ commandLineArgs.add(it.path)
+ }
+ commandLine commandLineArgs
doFirst {
delete "$outputKotlinDir/"
@@ -93,16 +101,6 @@
flavorDimensions "stl-variant"
productFlavors {
- stlport {
- dimension "stl-variant"
- applicationIdSuffix ".stlport"
- versionNameSuffix "-stlport"
- externalNativeBuild {
- ndkBuild {
- arguments "APP_STL=stlport_static"
- }
- }
- }
gnustl {
dimension "stl-variant"
applicationIdSuffix ".gnustl"
@@ -131,6 +129,6 @@
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.3.2'
implementation 'androidx.appcompat:appcompat:1.2.0'
- implementation 'com.google.flatbuffers:flatbuffers-java:1.12.0'
+ implementation 'com.google.flatbuffers:flatbuffers-java:2.0.0'
}
diff --git a/android/app/src/main/cpp/flatbuffers/CMakeLists.txt b/android/app/src/main/cpp/flatbuffers/CMakeLists.txt
index f32b0bb..0e5f3e9 100644
--- a/android/app/src/main/cpp/flatbuffers/CMakeLists.txt
+++ b/android/app/src/main/cpp/flatbuffers/CMakeLists.txt
@@ -15,17 +15,31 @@
"${CMAKE_CXX_FLAGS} -fsigned-char")
set(FlatBuffers_Library_SRCS
+ ${FLATBUFFERS_SRC}/include/flatbuffers/allocator.h
+ ${FLATBUFFERS_SRC}/include/flatbuffers/array.h
${FLATBUFFERS_SRC}/include/flatbuffers/base.h
+ ${FLATBUFFERS_SRC}/include/flatbuffers/bfbs_generator.h
+ ${FLATBUFFERS_SRC}/include/flatbuffers/buffer.h
+ ${FLATBUFFERS_SRC}/include/flatbuffers/buffer_ref.h
+ ${FLATBUFFERS_SRC}/include/flatbuffers/default_allocator.h
+ ${FLATBUFFERS_SRC}/include/flatbuffers/detached_buffer.h
+ ${FLATBUFFERS_SRC}/include/flatbuffers/flatbuffer_builder.h
${FLATBUFFERS_SRC}/include/flatbuffers/flatbuffers.h
+ ${FLATBUFFERS_SRC}/include/flatbuffers/flexbuffers.h
${FLATBUFFERS_SRC}/include/flatbuffers/hash.h
${FLATBUFFERS_SRC}/include/flatbuffers/idl.h
- ${FLATBUFFERS_SRC}/include/flatbuffers/util.h
+ ${FLATBUFFERS_SRC}/include/flatbuffers/minireflect.h
${FLATBUFFERS_SRC}/include/flatbuffers/reflection.h
${FLATBUFFERS_SRC}/include/flatbuffers/reflection_generated.h
- ${FLATBUFFERS_SRC}/include/flatbuffers/stl_emulation.h
- ${FLATBUFFERS_SRC}/include/flatbuffers/flexbuffers.h
${FLATBUFFERS_SRC}/include/flatbuffers/registry.h
- ${FLATBUFFERS_SRC}/include/flatbuffers/minireflect.h
+ ${FLATBUFFERS_SRC}/include/flatbuffers/stl_emulation.h
+ ${FLATBUFFERS_SRC}/include/flatbuffers/string.h
+ ${FLATBUFFERS_SRC}/include/flatbuffers/struct.h
+ ${FLATBUFFERS_SRC}/include/flatbuffers/table.h
+ ${FLATBUFFERS_SRC}/include/flatbuffers/util.h
+ ${FLATBUFFERS_SRC}/include/flatbuffers/vector.h
+ ${FLATBUFFERS_SRC}/include/flatbuffers/vector_downward.h
+ ${FLATBUFFERS_SRC}/include/flatbuffers/verifier.h
${FLATBUFFERS_SRC}/src/idl_parser.cpp
${FLATBUFFERS_SRC}/src/idl_gen_text.cpp
${FLATBUFFERS_SRC}/src/reflection.cpp
diff --git a/android/app/src/main/java/generated/com/fbs/app/Animal.kt b/android/app/src/main/java/generated/com/fbs/app/Animal.kt
index 82cb37d..89da646 100644
--- a/android/app/src/main/java/generated/com/fbs/app/Animal.kt
+++ b/android/app/src/main/java/generated/com/fbs/app/Animal.kt
@@ -37,7 +37,7 @@
return if(o != 0) bb.getShort(o + bb_pos).toUShort() else 0u
}
companion object {
- fun validateVersion() = Constants.FLATBUFFERS_1_12_0()
+ fun validateVersion() = Constants.FLATBUFFERS_2_0_0()
fun getRootAsAnimal(_bb: ByteBuffer): Animal = getRootAsAnimal(_bb, Animal())
fun getRootAsAnimal(_bb: ByteBuffer, obj: Animal): Animal {
_bb.order(ByteOrder.LITTLE_ENDIAN)
diff --git a/appveyor.yml b/appveyor.yml
deleted file mode 100644
index 9806fe4..0000000
--- a/appveyor.yml
+++ /dev/null
@@ -1,128 +0,0 @@
-branches:
- only:
- - master
-
-environment:
-
- global:
- # Workaround for https://github.com/conda/conda-build/issues/636
- PYTHONIOENCODING: UTF-8
- CONDA_INSTALL_LOCN: "C:\\Miniconda35-x64"
- CMAKE_OPTIONS: ""
- CPP_TEST_OPTIONS: ""
-
- matrix:
- - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2015
- CMAKE_VS_VERSION: "10 2010"
- CMAKE_OPTIONS: "-DFLATBUFFERS_BUILD_LEGACY=1"
- CPP_TEST_OPTIONS: "--std-cpp c++0x"
- MONSTER_EXTRA: "skip"
-
- - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2015
- CMAKE_VS_VERSION: "12 2013"
- MONSTER_EXTRA: "skip"
-
- - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2015
- CMAKE_VS_VERSION: "14 2015"
- MONSTER_EXTRA: ""
-
- - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017
- CMAKE_VS_VERSION: "15 2017"
- CMAKE_OPTIONS: "-DFLATBUFFERS_ENABLE_PCH=1"
- MONSTER_EXTRA: ""
-
- - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019
- CMAKE_VS_VERSION: "16 2019"
- CMAKE_OPTIONS: "-DFLATBUFFERS_ENABLE_PCH=1"
- MONSTER_EXTRA: ""
-
-platform:
- - x86
- - x64
-
-configuration:
- - Debug
- - Release
-
-before_build:
- - set MONSTER_EXTRA=%MONSTER_EXTRA%
- - cmake . -G"Visual Studio %CMAKE_VS_VERSION%" -DFLATBUFFERS_CODE_SANITIZE=1 %CMAKE_OPTIONS%
- # This cuts down on a lot of noise generated by xamarin warnings.
- - if exist "C:\Program Files (x86)\MSBuild\14.0\Microsoft.Common.targets\ImportAfter\Xamarin.Common.targets" del "C:\Program Files (x86)\MSBuild\14.0\Microsoft.Common.targets\ImportAfter\Xamarin.Common.targets"
- - if exist "C:\Program Files (x86)\MSBuild\15.0\Microsoft.Common.targets\ImportAfter\Xamarin.Common.targets" del "C:\Program Files (x86)\MSBuild\15.0\Microsoft.Common.targets\ImportAfter\Xamarin.Common.targets"
- - if exist "C:\Program Files (x86)\MSBuild\16.0\Microsoft.Common.targets\ImportAfter\Xamarin.Common.targets" del "C:\Program Files (x86)\MSBuild\16.0\Microsoft.Common.targets\ImportAfter\Xamarin.Common.targets"
-
-build:
- project: ALL_BUILD.vcxproj
- verbosity: minimal
-
-after_build:
- - python conan/appveyor/install.py
- - python conan/appveyor/build.py
-
-install:
- - set PATH=%CONDA_INSTALL_LOCN%;%CONDA_INSTALL_LOCN%\scripts;%PATH%;
- - curl -sSf -o rustup-init.exe https://win.rustup.rs/
- - rustup-init.exe -y
- - set PATH=%PATH%;C:\Users\appveyor\.cargo\bin
- - rustc -V
- - cargo -V
-
-test_script:
- - call .appveyor\check-generate-code.bat -b %CONFIGURATION%
- - "cd tests"
- - rem "Building all code"
- - generate_code.bat -b %CONFIGURATION% %CPP_TEST_OPTIONS%
- - 7z a GeneratedMyGameCode.zip MyGame\
- - rem "---------------- C++ -----------------"
- - "cd .."
- - "%CONFIGURATION%\\flattests.exe"
- - "cd tests"
- - rem "---------------- Java -----------------"
- - "java -version"
- - "JavaTest.bat"
- - rem "---------------- Rust ----------------"
- - "RustTest.bat"
- - rem "---------------- JS -----------------"
- - "node --version"
- - "..\\%CONFIGURATION%\\flatc -b -I include_test monster_test.fbs unicode_test.json"
- - "npm install"
- - "npm run pretest"
- - "node JavaScriptTest ./monster_test_generated"
- - rem "-------------- Python ---------------"
- - where python
- - python --version
- - where pip
- - pip --version
- - where conda
- - conda --version
- - rem "installing flatbuffers python library"
- - pip install ../python
- - rem "testing without installing Numpy"
- - python py_test.py 0 0 0
- - rem "testing after installing Numpy - disabled"
- # FIXME: This has a LOT of unnecessary dependencies and makes the tests fail
- # with timeouts.
- # - conda install --yes numpy
- # - python py_test.py 0 0 0
- - rem "---------------- C# -----------------"
- # Have to compile this here rather than in "build" above because AppVeyor only
- # supports building one project??
- - "cd FlatBuffers.Test"
- - "dotnet new sln"
- - "dotnet sln add FlatBuffers.Test.csproj"
- - "nuget restore"
- - "mkdir .tmp"
- - "msbuild.exe /property:Configuration=Release;OutputPath=.tmp /verbosity:minimal FlatBuffers.Test.csproj"
- - ".tmp\\FlatBuffers.Test.exe"
- # Run tests with UNSAFE_BYTEBUFFER
- - "msbuild.exe /property:Configuration=Release;UnsafeByteBuffer=true;OutputPath=.tmp /verbosity:minimal FlatBuffers.Test.csproj"
- - ".tmp\\FlatBuffers.Test.exe"
- # TODO: add more languages.
- - "cd ..\\.."
-
-artifacts:
- - path: $(CONFIGURATION)\flatc.exe
- name: flatc.exe
- - path: tests\GeneratedMyGameCode.zip
- name: GeneratedMyGameCode.zip
diff --git a/bazel/BUILD b/bazel/BUILD.bazel
similarity index 100%
rename from bazel/BUILD
rename to bazel/BUILD.bazel
diff --git a/bazel/grpc_deps_1_15_1.patch b/bazel/grpc_deps_1_15_1.patch
deleted file mode 100644
index c5d0101..0000000
--- a/bazel/grpc_deps_1_15_1.patch
+++ /dev/null
@@ -1,155 +0,0 @@
-diff --git a/bazel/grpc_deps.bzl b/bazel/grpc_deps.bzl
-index 4096720569..ea411b577d 100644
---- a/bazel/grpc_deps.bzl
-+++ b/bazel/grpc_deps.bzl
-@@ -1,5 +1,10 @@
- """Load dependencies needed to compile and test the grpc library as a 3rd-party consumer."""
-
-+# native.http_archive has been deprecated in newer bazel version. In order to work with
-+# grpc 1.15.1, the version flatbuffers is currently replying on. We need to apply this patch
-+# when importing the grpc dependency.
-+load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
-+
- def grpc_deps():
- """Loads dependencies need to compile and test the grpc library."""
-
-@@ -99,14 +104,14 @@ def grpc_deps():
- )
-
- if "boringssl" not in native.existing_rules():
-- native.http_archive(
-+ http_archive(
- name = "boringssl",
- # on the chromium-stable-with-bazel branch
- url = "https://boringssl.googlesource.com/boringssl/+archive/dcd3e6e6ecddf059adb48fca45bc7346a108bdd9.tar.gz",
- )
-
- if "com_github_madler_zlib" not in native.existing_rules():
-- native.new_http_archive(
-+ http_archive(
- name = "com_github_madler_zlib",
- build_file = "@com_github_grpc_grpc//third_party:zlib.BUILD",
- strip_prefix = "zlib-cacf7f1d4e3d44d871b605da3b647f07d718623f",
-@@ -114,14 +119,14 @@ def grpc_deps():
- )
-
- if "com_google_protobuf" not in native.existing_rules():
-- native.http_archive(
-+ http_archive(
- name = "com_google_protobuf",
- strip_prefix = "protobuf-48cb18e5c419ddd23d9badcfe4e9df7bde1979b2",
- url = "https://github.com/google/protobuf/archive/48cb18e5c419ddd23d9badcfe4e9df7bde1979b2.tar.gz",
- )
-
- if "com_github_nanopb_nanopb" not in native.existing_rules():
-- native.new_http_archive(
-+ http_archive(
- name = "com_github_nanopb_nanopb",
- build_file = "@com_github_grpc_grpc//third_party:nanopb.BUILD",
- strip_prefix = "nanopb-f8ac463766281625ad710900479130c7fcb4d63b",
-@@ -129,7 +134,7 @@ def grpc_deps():
- )
-
- if "com_github_google_googletest" not in native.existing_rules():
-- native.new_http_archive(
-+ http_archive(
- name = "com_github_google_googletest",
- build_file = "@com_github_grpc_grpc//third_party:gtest.BUILD",
- strip_prefix = "googletest-ec44c6c1675c25b9827aacd08c02433cccde7780",
-@@ -137,14 +142,14 @@ def grpc_deps():
- )
-
- if "com_github_gflags_gflags" not in native.existing_rules():
-- native.http_archive(
-+ http_archive(
- name = "com_github_gflags_gflags",
- strip_prefix = "gflags-30dbc81fb5ffdc98ea9b14b1918bfe4e8779b26e",
- url = "https://github.com/gflags/gflags/archive/30dbc81fb5ffdc98ea9b14b1918bfe4e8779b26e.tar.gz",
- )
-
- if "com_github_google_benchmark" not in native.existing_rules():
-- native.new_http_archive(
-+ http_archive(
- name = "com_github_google_benchmark",
- build_file = "@com_github_grpc_grpc//third_party:benchmark.BUILD",
- strip_prefix = "benchmark-9913418d323e64a0111ca0da81388260c2bbe1e9",
-@@ -152,7 +157,7 @@ def grpc_deps():
- )
-
- if "com_github_cares_cares" not in native.existing_rules():
-- native.new_http_archive(
-+ http_archive(
- name = "com_github_cares_cares",
- build_file = "@com_github_grpc_grpc//third_party:cares/cares.BUILD",
- strip_prefix = "c-ares-3be1924221e1326df520f8498d704a5c4c8d0cce",
-@@ -160,14 +165,14 @@ def grpc_deps():
- )
-
- if "com_google_absl" not in native.existing_rules():
-- native.http_archive(
-+ http_archive(
- name = "com_google_absl",
- strip_prefix = "abseil-cpp-cd95e71df6eaf8f2a282b1da556c2cf1c9b09207",
- url = "https://github.com/abseil/abseil-cpp/archive/cd95e71df6eaf8f2a282b1da556c2cf1c9b09207.tar.gz",
- )
-
- if "com_github_bazelbuild_bazeltoolchains" not in native.existing_rules():
-- native.http_archive(
-+ http_archive(
- name = "com_github_bazelbuild_bazeltoolchains",
- strip_prefix = "bazel-toolchains-cdea5b8675914d0a354d89f108de5d28e54e0edc",
- urls = [
-@@ -178,7 +183,7 @@ def grpc_deps():
- )
-
- if "io_opencensus_cpp" not in native.existing_rules():
-- native.http_archive(
-+ http_archive(
- name = "io_opencensus_cpp",
- strip_prefix = "opencensus-cpp-fdf0f308b1631bb4a942e32ba5d22536a6170274",
- url = "https://github.com/census-instrumentation/opencensus-cpp/archive/fdf0f308b1631bb4a942e32ba5d22536a6170274.tar.gz",
-@@ -200,7 +205,7 @@ def grpc_test_only_deps():
- )
-
- if "com_github_twisted_twisted" not in native.existing_rules():
-- native.new_http_archive(
-+ http_archive(
- name = "com_github_twisted_twisted",
- strip_prefix = "twisted-twisted-17.5.0",
- url = "https://github.com/twisted/twisted/archive/twisted-17.5.0.zip",
-@@ -208,7 +213,7 @@ def grpc_test_only_deps():
- )
-
- if "com_github_yaml_pyyaml" not in native.existing_rules():
-- native.new_http_archive(
-+ http_archive(
- name = "com_github_yaml_pyyaml",
- strip_prefix = "pyyaml-3.12",
- url = "https://github.com/yaml/pyyaml/archive/3.12.zip",
-@@ -216,7 +221,7 @@ def grpc_test_only_deps():
- )
-
- if "com_github_twisted_incremental" not in native.existing_rules():
-- native.new_http_archive(
-+ http_archive(
- name = "com_github_twisted_incremental",
- strip_prefix = "incremental-incremental-17.5.0",
- url = "https://github.com/twisted/incremental/archive/incremental-17.5.0.zip",
-@@ -224,7 +229,7 @@ def grpc_test_only_deps():
- )
-
- if "com_github_zopefoundation_zope_interface" not in native.existing_rules():
-- native.new_http_archive(
-+ http_archive(
- name = "com_github_zopefoundation_zope_interface",
- strip_prefix = "zope.interface-4.4.3",
- url = "https://github.com/zopefoundation/zope.interface/archive/4.4.3.zip",
-@@ -232,7 +237,7 @@ def grpc_test_only_deps():
- )
-
- if "com_github_twisted_constantly" not in native.existing_rules():
-- native.new_http_archive(
-+ http_archive(
- name = "com_github_twisted_constantly",
- strip_prefix = "constantly-15.1.0",
- url = "https://github.com/twisted/constantly/archive/15.1.0.zip",
diff --git a/bazel/grpc_deps_1_15_1_02.patch b/bazel/grpc_deps_1_15_1_02.patch
deleted file mode 100644
index 328134e..0000000
--- a/bazel/grpc_deps_1_15_1_02.patch
+++ /dev/null
@@ -1,48 +0,0 @@
-diff --git a/bazel/cc_grpc_library.bzl b/bazel/cc_grpc_library.bzl
-index 3288565714..6bfcd653f5 100644
---- a/bazel/cc_grpc_library.bzl
-+++ b/bazel/cc_grpc_library.bzl
-@@ -1,6 +1,6 @@
- """Generates and compiles C++ grpc stubs from proto_library rules."""
-
--load("//:bazel/generate_cc.bzl", "generate_cc")
-+load("//bazel:generate_cc.bzl", "generate_cc")
-
- def cc_grpc_library(name, srcs, deps, proto_only, well_known_protos, generate_mocks = False, use_external = False, **kwargs):
- """Generates C++ grpc classes from a .proto file.
-diff --git a/bazel/generate_cc.bzl b/bazel/generate_cc.bzl
-index ae747aa42c..2f14071f92 100644
---- a/bazel/generate_cc.bzl
-+++ b/bazel/generate_cc.bzl
-@@ -83,7 +83,7 @@ _generate_cc = rule(
- attrs = {
- "srcs": attr.label_list(
- mandatory = True,
-- non_empty = True,
-+ allow_empty = False,
- providers = ["proto"],
- ),
- "plugin": attr.label(
-diff --git a/bazel/grpc_build_system.bzl b/bazel/grpc_build_system.bzl
-index 73147bf3ac..e8c392aa93 100644
---- a/bazel/grpc_build_system.bzl
-+++ b/bazel/grpc_build_system.bzl
-@@ -24,6 +24,9 @@
- #
-
- # The set of pollers to test against if a test exercises polling
-+
-+load("//bazel:cc_grpc_library.bzl", "cc_grpc_library")
-+
- POLLERS = ['epollex', 'epollsig', 'epoll1', 'poll', 'poll-cv']
-
- def if_not_windows(a):
-@@ -95,8 +98,6 @@ def grpc_proto_plugin(name, srcs = [], deps = []):
- deps = deps,
- )
-
--load("//:bazel/cc_grpc_library.bzl", "cc_grpc_library")
--
- def grpc_proto_library(name, srcs = [], deps = [], well_known_protos = False,
- has_services = True, use_external = False, generate_mocks = False):
- cc_grpc_library(
diff --git a/bazel/protobuf_deps_3_6_1.patch b/bazel/protobuf_deps_3_6_1.patch
deleted file mode 100644
index 1c85062..0000000
--- a/bazel/protobuf_deps_3_6_1.patch
+++ /dev/null
@@ -1,24 +0,0 @@
-diff --git a/protobuf.bzl b/protobuf.bzl
-index 78f19c621..3b6d183b9 100644
---- a/protobuf.bzl
-+++ b/protobuf.bzl
-@@ -130,7 +130,7 @@ proto_gen = rule(
- "protoc": attr.label(
- cfg = "host",
- executable = True,
-- single_file = True,
-+ allow_single_file = True,
- mandatory = True,
- ),
- "plugin": attr.label(
-@@ -266,8 +266,8 @@ def internal_gen_well_known_protos_java(srcs):
- Args:
- srcs: the well known protos
- """
-- root = Label("%s//protobuf_java" % (REPOSITORY_NAME)).workspace_root
-- pkg = PACKAGE_NAME + "/" if PACKAGE_NAME else ""
-+ root = Label("%s//protobuf_java" % (native.repository_name())).workspace_root
-+ pkg = native.package_name() + "/" if native.package_name() else ""
- if root == "":
- include = " -I%ssrc " % pkg
- else:
diff --git a/benchmarks/CMakeLists.txt b/benchmarks/CMakeLists.txt
new file mode 100644
index 0000000..8d49c35
--- /dev/null
+++ b/benchmarks/CMakeLists.txt
@@ -0,0 +1,81 @@
+# Setup for running Google Benchmarks (https://github.com/google/benchmark) on
+# flatbuffers. This requires both that benchmark library and its depenency gtest
+# to build. Instead of including them here or doing a submodule, this uses
+# FetchContent (https://cmake.org/cmake/help/latest/module/FetchContent.html) to
+# grab the dependencies at config time. This requires CMake 3.14 or higher.
+cmake_minimum_required(VERSION 3.14)
+include(FetchContent)
+
+# No particular reason for the specific GIT_TAGs for the following repos, they
+# were just the latest releases when this was added.
+FetchContent_Declare(
+ googletest
+ GIT_REPOSITORY https://github.com/google/googletest.git
+ GIT_TAG e2239ee6043f73722e7aa812a459f54a28552929 # release-1.11.0
+)
+FetchContent_Declare(
+ googlebenchmark
+ GIT_REPOSITORY https://github.com/google/benchmark.git
+ GIT_TAG f91b6b42b1b9854772a90ae9501464a161707d1e # v1.6.0
+)
+
+# For Windows: Prevent overriding the parent project's compiler/linker
+# settings.
+set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
+FetchContent_MakeAvailable(
+ googletest
+ googlebenchmark
+)
+
+set(CPP_BENCH_DIR cpp)
+set(CPP_FB_BENCH_DIR ${CPP_BENCH_DIR}/flatbuffers)
+set(CPP_RAW_BENCH_DIR ${CPP_BENCH_DIR}/raw)
+set(CPP_BENCH_FBS ${CPP_FB_BENCH_DIR}/bench.fbs)
+set(CPP_BENCH_FB_GEN ${CPP_FB_BENCH_DIR}/bench_generated.h)
+
+set(FlatBenchmark_SRCS
+ ${CPP_BENCH_DIR}/benchmark_main.cpp
+ ${CPP_FB_BENCH_DIR}/fb_bench.cpp
+ ${CPP_RAW_BENCH_DIR}/raw_bench.cpp
+ ${CPP_BENCH_FB_GEN}
+)
+
+# Generate the flatbuffers benchmark code from the flatbuffers schema using
+# flatc itself, thus it depends on flatc. This also depends on the C++ runtime
+# flatbuffers and the schema file itself, so it should auto-generated at the
+# correct times.
+add_custom_command(
+ OUTPUT ${CPP_BENCH_FB_GEN}
+ COMMAND
+ "${FLATBUFFERS_FLATC_EXECUTABLE}"
+ --cpp
+ -o ${CPP_FB_BENCH_DIR}
+ ${CPP_BENCH_FBS}
+ DEPENDS
+ flatc
+ flatbuffers
+ ${CPP_BENCH_FBS}
+ COMMENT "Run Flatbuffers Benchmark Codegen: ${CPP_BENCH_FB_GEN}"
+ VERBATIM)
+
+# The main flatbuffers benchmark executable
+add_executable(flatbenchmark ${FlatBenchmark_SRCS})
+
+# Benchmark requires C++11
+target_compile_features(flatbenchmark PUBLIC
+ cxx_std_11
+)
+
+# Set the output directory to the root binary directory
+set_target_properties(flatbenchmark
+ PROPERTIES RUNTIME_OUTPUT_DIRECTORY
+ "${CMAKE_BINARY_DIR}"
+)
+
+# The includes of the benchmark files are fully qualified from flatbuffers root.
+target_include_directories(flatbenchmark PUBLIC ${CMAKE_SOURCE_DIR})
+
+target_link_libraries(flatbenchmark
+ benchmark::benchmark_main # _main to use their entry point
+ gtest # Link to gtest so we can also assert in the benchmarks
+)
\ No newline at end of file
diff --git a/benchmarks/cpp/bench.h b/benchmarks/cpp/bench.h
new file mode 100644
index 0000000..ad4baeb
--- /dev/null
+++ b/benchmarks/cpp/bench.h
@@ -0,0 +1,19 @@
+#ifndef BENCHMARKS_CPP_BENCH_H_
+#define BENCHMARKS_CPP_BENCH_H_
+
+#include <cstdint>
+
+struct Bench {
+ virtual ~Bench() {}
+
+ inline void Add(int64_t value) { sum += value; }
+
+ virtual uint8_t *Encode(void *buf, int64_t &len) = 0;
+ virtual void *Decode(void *buf, int64_t len) = 0;
+ virtual int64_t Use(void *decoded) = 0;
+ virtual void Dealloc(void *decoded) = 0;
+
+ int64_t sum = 0;
+};
+
+#endif // BENCHMARKS_CPP_BENCH_H_
\ No newline at end of file
diff --git a/benchmarks/cpp/benchmark_main.cpp b/benchmarks/cpp/benchmark_main.cpp
new file mode 100644
index 0000000..63807a5
--- /dev/null
+++ b/benchmarks/cpp/benchmark_main.cpp
@@ -0,0 +1,96 @@
+#include <benchmark/benchmark.h>
+#include <gtest/gtest.h>
+
+#include "benchmarks/cpp/bench.h"
+#include "benchmarks/cpp/flatbuffers/fb_bench.h"
+#include "benchmarks/cpp/raw/raw_bench.h"
+
+static inline void Encode(benchmark::State &state,
+ std::unique_ptr<Bench> &bench, uint8_t *buffer) {
+ int64_t length;
+ for (auto _ : state) {
+ bench->Encode(buffer, length);
+ benchmark::DoNotOptimize(length);
+ }
+}
+
+static inline void Decode(benchmark::State &state,
+ std::unique_ptr<Bench> &bench, uint8_t *buffer) {
+ int64_t length;
+ uint8_t *encoded = bench->Encode(buffer, length);
+
+ for (auto _ : state) {
+ void *decoded = bench->Decode(encoded, length);
+ benchmark::DoNotOptimize(decoded);
+ }
+}
+
+static inline void Use(benchmark::State &state, std::unique_ptr<Bench> &bench,
+ uint8_t *buffer, int64_t check_sum) {
+ int64_t length;
+ uint8_t *encoded = bench->Encode(buffer, length);
+ void *decoded = bench->Decode(encoded, length);
+
+ int64_t sum = 0;
+
+ for (auto _ : state) { sum = bench->Use(decoded); }
+
+ EXPECT_EQ(sum, check_sum);
+}
+
+static void BM_Flatbuffers_Encode(benchmark::State &state) {
+ const int64_t kBufferLength = 1024;
+ uint8_t buffer[kBufferLength];
+
+ StaticAllocator allocator(&buffer[0]);
+ std::unique_ptr<Bench> bench = NewFlatBuffersBench(kBufferLength, &allocator);
+ Encode(state, bench, buffer);
+}
+BENCHMARK(BM_Flatbuffers_Encode);
+
+static void BM_Flatbuffers_Decode(benchmark::State &state) {
+ const int64_t kBufferLength = 1024;
+ uint8_t buffer[kBufferLength];
+
+ StaticAllocator allocator(&buffer[0]);
+ std::unique_ptr<Bench> bench = NewFlatBuffersBench(kBufferLength, &allocator);
+ Decode(state, bench, buffer);
+}
+BENCHMARK(BM_Flatbuffers_Decode);
+
+static void BM_Flatbuffers_Use(benchmark::State &state) {
+ const int64_t kBufferLength = 1024;
+ uint8_t buffer[kBufferLength];
+
+ StaticAllocator allocator(&buffer[0]);
+ std::unique_ptr<Bench> bench = NewFlatBuffersBench(kBufferLength, &allocator);
+ Use(state, bench, buffer, 218812692406581874);
+}
+BENCHMARK(BM_Flatbuffers_Use);
+
+static void BM_Raw_Encode(benchmark::State &state) {
+ const int64_t kBufferLength = 1024;
+ uint8_t buffer[kBufferLength];
+
+ std::unique_ptr<Bench> bench = NewRawBench();
+ Encode(state, bench, buffer);
+}
+BENCHMARK(BM_Raw_Encode);
+
+static void BM_Raw_Decode(benchmark::State &state) {
+ const int64_t kBufferLength = 1024;
+ uint8_t buffer[kBufferLength];
+
+ std::unique_ptr<Bench> bench = NewRawBench();
+ Decode(state, bench, buffer);
+}
+BENCHMARK(BM_Raw_Decode);
+
+static void BM_Raw_Use(benchmark::State &state) {
+ const int64_t kBufferLength = 1024;
+ uint8_t buffer[kBufferLength];
+
+ std::unique_ptr<Bench> bench = NewRawBench();
+ Use(state, bench, buffer, 218812692406581874);
+}
+BENCHMARK(BM_Raw_Use);
diff --git a/benchmarks/cpp/flatbuffers/bench.fbs b/benchmarks/cpp/flatbuffers/bench.fbs
new file mode 100644
index 0000000..8e5f3ff
--- /dev/null
+++ b/benchmarks/cpp/flatbuffers/bench.fbs
@@ -0,0 +1,52 @@
+// Copyright 2021 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.
+
+
+// trying to represent a typical mix of datatypes:
+// 1 array of 3 elements, each element: 1 string, 3 nested objects, 9 scalars
+// root element has the array, additional string and an enum
+
+namespace benchmarks_flatbuffers;
+
+enum Enum : short { Apples, Pears, Bananas}
+
+struct Foo {
+ id:ulong;
+ count:short;
+ prefix:byte;
+ length:uint;
+}
+
+struct Bar {
+ parent:Foo;
+ time:int;
+ ratio:float;
+ size:ushort;
+}
+
+table FooBar {
+ sibling:Bar;
+ name:string;
+ rating:double;
+ postfix:ubyte;
+}
+
+table FooBarContainer {
+ list:[FooBar]; // 3 copies of the above
+ initialized:bool;
+ fruit:Enum;
+ location:string;
+}
+
+root_type FooBarContainer;
diff --git a/benchmarks/cpp/flatbuffers/bench_generated.h b/benchmarks/cpp/flatbuffers/bench_generated.h
new file mode 100644
index 0000000..9d207c5
--- /dev/null
+++ b/benchmarks/cpp/flatbuffers/bench_generated.h
@@ -0,0 +1,347 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+
+#ifndef FLATBUFFERS_GENERATED_BENCH_BENCHMARKS_FLATBUFFERS_H_
+#define FLATBUFFERS_GENERATED_BENCH_BENCHMARKS_FLATBUFFERS_H_
+
+#include "flatbuffers/flatbuffers.h"
+
+namespace benchmarks_flatbuffers {
+
+struct Foo;
+
+struct Bar;
+
+struct FooBar;
+struct FooBarBuilder;
+
+struct FooBarContainer;
+struct FooBarContainerBuilder;
+
+enum Enum : int16_t {
+ Enum_Apples = 0,
+ Enum_Pears = 1,
+ Enum_Bananas = 2,
+ Enum_MIN = Enum_Apples,
+ Enum_MAX = Enum_Bananas
+};
+
+inline const Enum (&EnumValuesEnum())[3] {
+ static const Enum values[] = {
+ Enum_Apples,
+ Enum_Pears,
+ Enum_Bananas
+ };
+ return values;
+}
+
+inline const char * const *EnumNamesEnum() {
+ static const char * const names[4] = {
+ "Apples",
+ "Pears",
+ "Bananas",
+ nullptr
+ };
+ return names;
+}
+
+inline const char *EnumNameEnum(Enum e) {
+ if (flatbuffers::IsOutRange(e, Enum_Apples, Enum_Bananas)) return "";
+ const size_t index = static_cast<size_t>(e);
+ return EnumNamesEnum()[index];
+}
+
+FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(8) Foo FLATBUFFERS_FINAL_CLASS {
+ private:
+ uint64_t id_;
+ int16_t count_;
+ int8_t prefix_;
+ int8_t padding0__;
+ uint32_t length_;
+
+ public:
+ Foo()
+ : id_(0),
+ count_(0),
+ prefix_(0),
+ padding0__(0),
+ length_(0) {
+ (void)padding0__;
+ }
+ Foo(uint64_t _id, int16_t _count, int8_t _prefix, uint32_t _length)
+ : id_(flatbuffers::EndianScalar(_id)),
+ count_(flatbuffers::EndianScalar(_count)),
+ prefix_(flatbuffers::EndianScalar(_prefix)),
+ padding0__(0),
+ length_(flatbuffers::EndianScalar(_length)) {
+ (void)padding0__;
+ }
+ uint64_t id() const {
+ return flatbuffers::EndianScalar(id_);
+ }
+ int16_t count() const {
+ return flatbuffers::EndianScalar(count_);
+ }
+ int8_t prefix() const {
+ return flatbuffers::EndianScalar(prefix_);
+ }
+ uint32_t length() const {
+ return flatbuffers::EndianScalar(length_);
+ }
+};
+FLATBUFFERS_STRUCT_END(Foo, 16);
+
+FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(8) Bar FLATBUFFERS_FINAL_CLASS {
+ private:
+ benchmarks_flatbuffers::Foo parent_;
+ int32_t time_;
+ float ratio_;
+ uint16_t size_;
+ int16_t padding0__; int32_t padding1__;
+
+ public:
+ Bar()
+ : parent_(),
+ time_(0),
+ ratio_(0),
+ size_(0),
+ padding0__(0),
+ padding1__(0) {
+ (void)padding0__;
+ (void)padding1__;
+ }
+ Bar(const benchmarks_flatbuffers::Foo &_parent, int32_t _time, float _ratio, uint16_t _size)
+ : parent_(_parent),
+ time_(flatbuffers::EndianScalar(_time)),
+ ratio_(flatbuffers::EndianScalar(_ratio)),
+ size_(flatbuffers::EndianScalar(_size)),
+ padding0__(0),
+ padding1__(0) {
+ (void)padding0__;
+ (void)padding1__;
+ }
+ const benchmarks_flatbuffers::Foo &parent() const {
+ return parent_;
+ }
+ int32_t time() const {
+ return flatbuffers::EndianScalar(time_);
+ }
+ float ratio() const {
+ return flatbuffers::EndianScalar(ratio_);
+ }
+ uint16_t size() const {
+ return flatbuffers::EndianScalar(size_);
+ }
+};
+FLATBUFFERS_STRUCT_END(Bar, 32);
+
+struct FooBar FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
+ typedef FooBarBuilder Builder;
+ enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE {
+ VT_SIBLING = 4,
+ VT_NAME = 6,
+ VT_RATING = 8,
+ VT_POSTFIX = 10
+ };
+ const benchmarks_flatbuffers::Bar *sibling() const {
+ return GetStruct<const benchmarks_flatbuffers::Bar *>(VT_SIBLING);
+ }
+ const flatbuffers::String *name() const {
+ return GetPointer<const flatbuffers::String *>(VT_NAME);
+ }
+ double rating() const {
+ return GetField<double>(VT_RATING, 0.0);
+ }
+ uint8_t postfix() const {
+ return GetField<uint8_t>(VT_POSTFIX, 0);
+ }
+ bool Verify(flatbuffers::Verifier &verifier) const {
+ return VerifyTableStart(verifier) &&
+ VerifyField<benchmarks_flatbuffers::Bar>(verifier, VT_SIBLING) &&
+ VerifyOffset(verifier, VT_NAME) &&
+ verifier.VerifyString(name()) &&
+ VerifyField<double>(verifier, VT_RATING) &&
+ VerifyField<uint8_t>(verifier, VT_POSTFIX) &&
+ verifier.EndTable();
+ }
+};
+
+struct FooBarBuilder {
+ typedef FooBar Table;
+ flatbuffers::FlatBufferBuilder &fbb_;
+ flatbuffers::uoffset_t start_;
+ void add_sibling(const benchmarks_flatbuffers::Bar *sibling) {
+ fbb_.AddStruct(FooBar::VT_SIBLING, sibling);
+ }
+ void add_name(flatbuffers::Offset<flatbuffers::String> name) {
+ fbb_.AddOffset(FooBar::VT_NAME, name);
+ }
+ void add_rating(double rating) {
+ fbb_.AddElement<double>(FooBar::VT_RATING, rating, 0.0);
+ }
+ void add_postfix(uint8_t postfix) {
+ fbb_.AddElement<uint8_t>(FooBar::VT_POSTFIX, postfix, 0);
+ }
+ explicit FooBarBuilder(flatbuffers::FlatBufferBuilder &_fbb)
+ : fbb_(_fbb) {
+ start_ = fbb_.StartTable();
+ }
+ flatbuffers::Offset<FooBar> Finish() {
+ const auto end = fbb_.EndTable(start_);
+ auto o = flatbuffers::Offset<FooBar>(end);
+ return o;
+ }
+};
+
+inline flatbuffers::Offset<FooBar> CreateFooBar(
+ flatbuffers::FlatBufferBuilder &_fbb,
+ const benchmarks_flatbuffers::Bar *sibling = nullptr,
+ flatbuffers::Offset<flatbuffers::String> name = 0,
+ double rating = 0.0,
+ uint8_t postfix = 0) {
+ FooBarBuilder builder_(_fbb);
+ builder_.add_rating(rating);
+ builder_.add_name(name);
+ builder_.add_sibling(sibling);
+ builder_.add_postfix(postfix);
+ return builder_.Finish();
+}
+
+inline flatbuffers::Offset<FooBar> CreateFooBarDirect(
+ flatbuffers::FlatBufferBuilder &_fbb,
+ const benchmarks_flatbuffers::Bar *sibling = nullptr,
+ const char *name = nullptr,
+ double rating = 0.0,
+ uint8_t postfix = 0) {
+ auto name__ = name ? _fbb.CreateString(name) : 0;
+ return benchmarks_flatbuffers::CreateFooBar(
+ _fbb,
+ sibling,
+ name__,
+ rating,
+ postfix);
+}
+
+struct FooBarContainer FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
+ typedef FooBarContainerBuilder Builder;
+ enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE {
+ VT_LIST = 4,
+ VT_INITIALIZED = 6,
+ VT_FRUIT = 8,
+ VT_LOCATION = 10
+ };
+ const flatbuffers::Vector<flatbuffers::Offset<benchmarks_flatbuffers::FooBar>> *list() const {
+ return GetPointer<const flatbuffers::Vector<flatbuffers::Offset<benchmarks_flatbuffers::FooBar>> *>(VT_LIST);
+ }
+ bool initialized() const {
+ return GetField<uint8_t>(VT_INITIALIZED, 0) != 0;
+ }
+ benchmarks_flatbuffers::Enum fruit() const {
+ return static_cast<benchmarks_flatbuffers::Enum>(GetField<int16_t>(VT_FRUIT, 0));
+ }
+ const flatbuffers::String *location() const {
+ return GetPointer<const flatbuffers::String *>(VT_LOCATION);
+ }
+ bool Verify(flatbuffers::Verifier &verifier) const {
+ return VerifyTableStart(verifier) &&
+ VerifyOffset(verifier, VT_LIST) &&
+ verifier.VerifyVector(list()) &&
+ verifier.VerifyVectorOfTables(list()) &&
+ VerifyField<uint8_t>(verifier, VT_INITIALIZED) &&
+ VerifyField<int16_t>(verifier, VT_FRUIT) &&
+ VerifyOffset(verifier, VT_LOCATION) &&
+ verifier.VerifyString(location()) &&
+ verifier.EndTable();
+ }
+};
+
+struct FooBarContainerBuilder {
+ typedef FooBarContainer Table;
+ flatbuffers::FlatBufferBuilder &fbb_;
+ flatbuffers::uoffset_t start_;
+ void add_list(flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<benchmarks_flatbuffers::FooBar>>> list) {
+ fbb_.AddOffset(FooBarContainer::VT_LIST, list);
+ }
+ void add_initialized(bool initialized) {
+ fbb_.AddElement<uint8_t>(FooBarContainer::VT_INITIALIZED, static_cast<uint8_t>(initialized), 0);
+ }
+ void add_fruit(benchmarks_flatbuffers::Enum fruit) {
+ fbb_.AddElement<int16_t>(FooBarContainer::VT_FRUIT, static_cast<int16_t>(fruit), 0);
+ }
+ void add_location(flatbuffers::Offset<flatbuffers::String> location) {
+ fbb_.AddOffset(FooBarContainer::VT_LOCATION, location);
+ }
+ explicit FooBarContainerBuilder(flatbuffers::FlatBufferBuilder &_fbb)
+ : fbb_(_fbb) {
+ start_ = fbb_.StartTable();
+ }
+ flatbuffers::Offset<FooBarContainer> Finish() {
+ const auto end = fbb_.EndTable(start_);
+ auto o = flatbuffers::Offset<FooBarContainer>(end);
+ return o;
+ }
+};
+
+inline flatbuffers::Offset<FooBarContainer> CreateFooBarContainer(
+ flatbuffers::FlatBufferBuilder &_fbb,
+ flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<benchmarks_flatbuffers::FooBar>>> list = 0,
+ bool initialized = false,
+ benchmarks_flatbuffers::Enum fruit = benchmarks_flatbuffers::Enum_Apples,
+ flatbuffers::Offset<flatbuffers::String> location = 0) {
+ FooBarContainerBuilder builder_(_fbb);
+ builder_.add_location(location);
+ builder_.add_list(list);
+ builder_.add_fruit(fruit);
+ builder_.add_initialized(initialized);
+ return builder_.Finish();
+}
+
+inline flatbuffers::Offset<FooBarContainer> CreateFooBarContainerDirect(
+ flatbuffers::FlatBufferBuilder &_fbb,
+ const std::vector<flatbuffers::Offset<benchmarks_flatbuffers::FooBar>> *list = nullptr,
+ bool initialized = false,
+ benchmarks_flatbuffers::Enum fruit = benchmarks_flatbuffers::Enum_Apples,
+ const char *location = nullptr) {
+ auto list__ = list ? _fbb.CreateVector<flatbuffers::Offset<benchmarks_flatbuffers::FooBar>>(*list) : 0;
+ auto location__ = location ? _fbb.CreateString(location) : 0;
+ return benchmarks_flatbuffers::CreateFooBarContainer(
+ _fbb,
+ list__,
+ initialized,
+ fruit,
+ location__);
+}
+
+inline const benchmarks_flatbuffers::FooBarContainer *GetFooBarContainer(const void *buf) {
+ return flatbuffers::GetRoot<benchmarks_flatbuffers::FooBarContainer>(buf);
+}
+
+inline const benchmarks_flatbuffers::FooBarContainer *GetSizePrefixedFooBarContainer(const void *buf) {
+ return flatbuffers::GetSizePrefixedRoot<benchmarks_flatbuffers::FooBarContainer>(buf);
+}
+
+inline bool VerifyFooBarContainerBuffer(
+ flatbuffers::Verifier &verifier) {
+ return verifier.VerifyBuffer<benchmarks_flatbuffers::FooBarContainer>(nullptr);
+}
+
+inline bool VerifySizePrefixedFooBarContainerBuffer(
+ flatbuffers::Verifier &verifier) {
+ return verifier.VerifySizePrefixedBuffer<benchmarks_flatbuffers::FooBarContainer>(nullptr);
+}
+
+inline void FinishFooBarContainerBuffer(
+ flatbuffers::FlatBufferBuilder &fbb,
+ flatbuffers::Offset<benchmarks_flatbuffers::FooBarContainer> root) {
+ fbb.Finish(root);
+}
+
+inline void FinishSizePrefixedFooBarContainerBuffer(
+ flatbuffers::FlatBufferBuilder &fbb,
+ flatbuffers::Offset<benchmarks_flatbuffers::FooBarContainer> root) {
+ fbb.FinishSizePrefixed(root);
+}
+
+} // namespace benchmarks_flatbuffers
+
+#endif // FLATBUFFERS_GENERATED_BENCH_BENCHMARKS_FLATBUFFERS_H_
diff --git a/benchmarks/cpp/flatbuffers/fb_bench.cpp b/benchmarks/cpp/flatbuffers/fb_bench.cpp
new file mode 100644
index 0000000..2bbb9a5
--- /dev/null
+++ b/benchmarks/cpp/flatbuffers/fb_bench.cpp
@@ -0,0 +1,80 @@
+#include "benchmarks/cpp/flatbuffers/fb_bench.h"
+
+#include <cstdint>
+#include <memory>
+
+#include "benchmarks/cpp/bench.h"
+#include "benchmarks/cpp/flatbuffers/bench_generated.h"
+#include "flatbuffers/flatbuffers.h"
+
+using namespace flatbuffers;
+using namespace benchmarks_flatbuffers;
+
+namespace {
+
+struct FlatBufferBench : Bench {
+ explicit FlatBufferBench(int64_t initial_size, Allocator *allocator)
+ : fbb(initial_size, allocator, false) {}
+
+ uint8_t *Encode(void *, int64_t &len) {
+ fbb.Clear();
+
+ const int kVectorLength = 3;
+ Offset<FooBar> vec[kVectorLength];
+
+ for (int i = 0; i < kVectorLength; ++i) {
+ Foo foo(0xABADCAFEABADCAFE + i, 10000 + i, '@' + i, 1000000 + i);
+ Bar bar(foo, 123456 + i, 3.14159f + i, 10000 + i);
+ auto name = fbb.CreateString("Hello, World!");
+ auto foobar =
+ CreateFooBar(fbb, &bar, name, 3.1415432432445543543 + i, '!' + i);
+ vec[i] = foobar;
+ }
+ auto location = fbb.CreateString("http://google.com/flatbuffers/");
+ auto foobarvec = fbb.CreateVector(vec, kVectorLength);
+ auto foobarcontainer =
+ CreateFooBarContainer(fbb, foobarvec, true, Enum_Bananas, location);
+ fbb.Finish(foobarcontainer);
+
+ len = fbb.GetSize();
+ return fbb.GetBufferPointer();
+ }
+
+ int64_t Use(void *decoded) {
+ sum = 0;
+ auto foobarcontainer = GetFooBarContainer(decoded);
+ sum = 0;
+ Add(foobarcontainer->initialized());
+ Add(foobarcontainer->location()->Length());
+ Add(foobarcontainer->fruit());
+ for (unsigned int i = 0; i < foobarcontainer->list()->Length(); i++) {
+ auto foobar = foobarcontainer->list()->Get(i);
+ Add(foobar->name()->Length());
+ Add(foobar->postfix());
+ Add(static_cast<int64_t>(foobar->rating()));
+ auto bar = foobar->sibling();
+ Add(static_cast<int64_t>(bar->ratio()));
+ Add(bar->size());
+ Add(bar->time());
+ auto &foo = bar->parent();
+ Add(foo.count());
+ Add(foo.id());
+ Add(foo.length());
+ Add(foo.prefix());
+ }
+ return sum;
+ }
+
+ void *Decode(void *buffer, int64_t) { return buffer; }
+ void Dealloc(void *) override{};
+
+ FlatBufferBuilder fbb;
+};
+
+} // namespace
+
+std::unique_ptr<Bench> NewFlatBuffersBench(int64_t initial_size,
+ Allocator *allocator) {
+ return std::unique_ptr<FlatBufferBench>(
+ new FlatBufferBench(initial_size, allocator));
+}
diff --git a/benchmarks/cpp/flatbuffers/fb_bench.h b/benchmarks/cpp/flatbuffers/fb_bench.h
new file mode 100644
index 0000000..ffb5f54
--- /dev/null
+++ b/benchmarks/cpp/flatbuffers/fb_bench.h
@@ -0,0 +1,23 @@
+#ifndef BENCHMARKS_CPP_FLATBUFFERS_FB_BENCH_H_
+#define BENCHMARKS_CPP_FLATBUFFERS_FB_BENCH_H_
+
+#include <cstdint>
+#include <memory>
+
+#include "benchmarks/cpp/bench.h"
+#include "include/flatbuffers/flatbuffers.h"
+
+struct StaticAllocator : public flatbuffers::Allocator {
+ explicit StaticAllocator(uint8_t *buffer) : buffer_(buffer) {}
+
+ uint8_t *allocate(size_t) override { return buffer_; }
+
+ void deallocate(uint8_t *, size_t) override {}
+
+ uint8_t *buffer_;
+};
+
+std::unique_ptr<Bench> NewFlatBuffersBench(
+ int64_t initial_size = 1024, flatbuffers::Allocator *allocator = nullptr);
+
+#endif // BENCHMARKS_CPP_FLATBUFFERS_FB_BENCH_H_
\ No newline at end of file
diff --git a/benchmarks/cpp/raw/raw_bench.cpp b/benchmarks/cpp/raw/raw_bench.cpp
new file mode 100644
index 0000000..810cb1f
--- /dev/null
+++ b/benchmarks/cpp/raw/raw_bench.cpp
@@ -0,0 +1,109 @@
+#include "benchmarks/cpp/raw/raw_bench.h"
+
+#include <cstdint>
+#include <cstring>
+#include <memory>
+
+#include "benchmarks/cpp/bench.h"
+
+namespace {
+const int64_t kStringLength = 32;
+const int64_t kVectorLength = 3;
+
+enum Enum { Apples, Pears, Bananas };
+
+struct Foo {
+ int64_t id;
+ short count;
+ char prefix;
+ int length;
+};
+
+struct Bar {
+ Foo parent;
+ int time;
+ float ratio;
+ unsigned short size;
+};
+
+struct FooBar {
+ Bar sibling;
+ // We have to stick this in, otherwise strlen() will make it slower than
+ // FlatBuffers:
+ int name_len;
+ char name[kStringLength];
+ double rating;
+ unsigned char postfix;
+};
+
+struct FooBarContainer {
+ FooBar list[kVectorLength]; // 3 copies of the above
+ bool initialized;
+ Enum fruit;
+ int location_len;
+ char location[kStringLength];
+};
+
+struct RawBench : Bench {
+ uint8_t *Encode(void *buf, int64_t &len) {
+ FooBarContainer *fbc = new (buf) FooBarContainer;
+ strcpy(fbc->location, "http://google.com/flatbuffers/"); // Unsafe eek!
+ fbc->location_len = (int)strlen(fbc->location);
+ fbc->fruit = Bananas;
+ fbc->initialized = true;
+ for (int i = 0; i < kVectorLength; i++) {
+ // We add + i to not make these identical copies for a more realistic
+ // compression test.
+ auto &foobar = fbc->list[i];
+ foobar.rating = 3.1415432432445543543 + i;
+ foobar.postfix = '!' + i;
+ strcpy(foobar.name, "Hello, World!");
+ foobar.name_len = (int)strlen(foobar.name);
+ auto &bar = foobar.sibling;
+ bar.ratio = 3.14159f + i;
+ bar.size = 10000 + i;
+ bar.time = 123456 + i;
+ auto &foo = bar.parent;
+ foo.id = 0xABADCAFEABADCAFE + i;
+ foo.count = 10000 + i;
+ foo.length = 1000000 + i;
+ foo.prefix = '@' + i;
+ }
+
+ len = sizeof(FooBarContainer);
+ return reinterpret_cast<uint8_t *>(fbc);
+ };
+
+ int64_t Use(void *decoded) {
+ auto foobarcontainer = reinterpret_cast<FooBarContainer *>(decoded);
+ sum = 0;
+ Add(foobarcontainer->initialized);
+ Add(foobarcontainer->location_len);
+ Add(foobarcontainer->fruit);
+ for (unsigned int i = 0; i < kVectorLength; i++) {
+ auto foobar = &foobarcontainer->list[i];
+ Add(foobar->name_len);
+ Add(foobar->postfix);
+ Add(static_cast<int64_t>(foobar->rating));
+ auto bar = &foobar->sibling;
+ Add(static_cast<int64_t>(bar->ratio));
+ Add(bar->size);
+ Add(bar->time);
+ auto &foo = bar->parent;
+ Add(foo.count);
+ Add(foo.id);
+ Add(foo.length);
+ Add(foo.prefix);
+ }
+ return sum;
+ }
+
+ void *Decode(void *buf, int64_t) { return buf; }
+ void Dealloc(void *) override{};
+};
+
+} // namespace
+
+std::unique_ptr<Bench> NewRawBench() {
+ return std::unique_ptr<RawBench>(new RawBench());
+}
diff --git a/benchmarks/cpp/raw/raw_bench.h b/benchmarks/cpp/raw/raw_bench.h
new file mode 100644
index 0000000..68bb278
--- /dev/null
+++ b/benchmarks/cpp/raw/raw_bench.h
@@ -0,0 +1,10 @@
+#ifndef BENCHMARKS_CPP_RAW_RAW_BENCH_H_
+#define BENCHMARKS_CPP_RAW_RAW_BENCH_H_
+
+#include <memory>
+
+#include "benchmarks/cpp/bench.h"
+
+std::unique_ptr<Bench> NewRawBench();
+
+#endif // BENCHMARKS_CPP_RAW_RAW_BENCH_H_
\ No newline at end of file
diff --git a/build_defs.bzl b/build_defs.bzl
index 88792be..d27da1f 100644
--- a/build_defs.bzl
+++ b/build_defs.bzl
@@ -5,6 +5,8 @@
Rules for building C++ flatbuffers with Bazel.
"""
+load("@build_bazel_rules_nodejs//:index.bzl", "js_library")
+load("@npm//@bazel/typescript:index.bzl", "ts_project")
load("@rules_cc//cc:defs.bzl", "cc_library")
flatc_path = "@com_github_google_flatbuffers//:flatc"
@@ -13,6 +15,7 @@
"./",
"$(GENDIR)",
"$(BINDIR)",
+ "$(execpath @com_github_google_flatbuffers//:flatc).runfiles/com_github_google_flatbuffers",
]
DEFAULT_FLATC_ARGS = [
@@ -24,6 +27,15 @@
"--cpp-ptr-type flatbuffers::unique_ptr",
]
+DEFAULT_FLATC_TS_ARGS = [
+ "--gen-object-api",
+ "--gen-mutable",
+ "--reflect-names",
+ "--gen-name-strings",
+ "--ts-flat-files",
+ "--keep-prefix",
+]
+
def flatbuffer_library_public(
name,
srcs,
@@ -37,6 +49,7 @@
reflection_visibility = None,
compatible_with = None,
restricted_to = None,
+ target_compatible_with = None,
output_to_bindir = False):
"""Generates code files for reading/writing the given flatbuffers in the requested language using the public compiler.
@@ -58,6 +71,8 @@
built for, in addition to default-supported environments.
restricted_to: Optional, The list of environments this rule can be built
for, instead of default-supported environments.
+ target_compatible_with: Optional, The list of target platform constraints
+ to use.
output_to_bindir: Passed to genrule for output to bin directory.
@@ -92,6 +107,7 @@
tools = [flatc_path],
cmd = genrule_cmd,
compatible_with = compatible_with,
+ target_compatible_with = target_compatible_with,
restricted_to = restricted_to,
message = "Generating flatbuffer files for %s:" % (name),
)
@@ -120,8 +136,10 @@
tools = [flatc_path],
compatible_with = compatible_with,
restricted_to = restricted_to,
+ target_compatible_with = target_compatible_with,
cmd = reflection_genrule_cmd,
message = "Generating flatbuffer reflection binary for %s:" % (name),
+ visibility = reflection_visibility,
)
native.filegroup(
name = "%s_out" % reflection_name,
@@ -136,15 +154,18 @@
srcs,
srcs_filegroup_name = "",
out_prefix = "",
+ deps = [],
includes = [],
include_paths = DEFAULT_INCLUDE_PATHS,
+ cc_include_paths = [],
flatc_args = DEFAULT_FLATC_ARGS,
visibility = None,
compatible_with = None,
restricted_to = None,
+ target_compatible_with = None,
srcs_filegroup_visibility = None,
gen_reflections = False):
- '''A cc_library with the generated reader/writers for the given flatbuffer definitions.
+ """A cc_library with the generated reader/writers for the given flatbuffer definitions.
Args:
name: Rule name.
@@ -154,9 +175,12 @@
flatbuffer_cc_library that depends on this one's schemas.
out_prefix: Prepend this path to the front of all generated files. Usually
is a directory name.
+ deps: Optional, list of other flatbuffer_cc_library's to depend on. Cannot be specified
+ alongside includes.
includes: Optional, list of filegroups of schemas that the srcs depend on.
- ** SEE REMARKS BELOW **
+ Use of this is discouraged, and may be deprecated.
include_paths: Optional, list of paths the includes files can be found in.
+ cc_include_paths: Optional, list of paths to add to the cc_library includes attribute.
flatc_args: Optional list of additional arguments to pass to flatc
(e.g. --gen-mutable).
visibility: The visibility of the generated cc_library. By default, use the
@@ -169,6 +193,8 @@
for, in addition to default-supported environments.
restricted_to: Optional, The list of environments this rule can be built
for, instead of default-supported environments.
+ target_compatible_with: Optional, The list of target platform constraints
+ to use.
This produces:
filegroup([name]_srcs): all generated .h files.
@@ -177,41 +203,17 @@
parameter, if they depend on the schemas in this library.
Fileset([name]_reflection): (Optional) all generated reflection binaries.
cc_library([name]): library with sources and flatbuffers deps.
-
- Remarks:
- ** Because the genrule used to call flatc does not have any trivial way of
- computing the output list of files transitively generated by includes and
- --gen-includes (the default) being defined for flatc, the --gen-includes
- flag will not work as expected. The way around this is to add a dependency
- to the flatbuffer_cc_library defined alongside the flatc included Fileset.
- For example you might define:
-
- flatbuffer_cc_library(
- name = "my_fbs",
- srcs = [ "schemas/foo.fbs" ],
- includes = [ "//third_party/bazz:bazz_fbs_includes" ],
- )
-
- In which foo.fbs includes a few files from the Fileset defined at
- //third_party/bazz:bazz_fbs_includes. When compiling the library that
- includes foo_generated.h, and therefore has my_fbs as a dependency, it
- will fail to find any of the bazz *_generated.h files unless you also
- add bazz's flatbuffer_cc_library to your own dependency list, e.g.:
-
- cc_library(
- name = "my_lib",
- deps = [
- ":my_fbs",
- "//third_party/bazz:bazz_fbs"
- ],
- )
-
- Happy dependent Flatbuffering!
- '''
+ """
output_headers = [
- (out_prefix + "%s_generated.h") % (s.replace(".fbs", "").split("/")[-1])
+ (out_prefix + "%s_generated.h") % (s.replace(".fbs", "").split("/")[-1].split(":")[-1])
for s in srcs
]
+ if deps and includes:
+ # There is no inherent reason we couldn't support both, but this discourages
+ # use of includes without good reason.
+ fail("Cannot specify both deps and include in flatbuffer_cc_library.")
+ if deps:
+ includes = [d + "_includes" for d in deps]
reflection_name = "%s_reflection" % name if gen_reflections else ""
srcs_lib = "%s_srcs" % (name)
@@ -226,6 +228,7 @@
flatc_args = flatc_args,
compatible_with = compatible_with,
restricted_to = restricted_to,
+ target_compatible_with = target_compatible_with,
reflection_name = reflection_name,
reflection_visibility = visibility,
)
@@ -242,10 +245,12 @@
],
deps = [
"@com_github_google_flatbuffers//:runtime_cc",
- ],
- includes = [],
+ "@com_github_google_flatbuffers//:flatbuffers",
+ ] + deps,
+ includes = cc_include_paths,
compatible_with = compatible_with,
restricted_to = restricted_to,
+ target_compatible_with = target_compatible_with,
linkstatic = 1,
visibility = visibility,
)
@@ -254,8 +259,96 @@
# Flatbuffer set.
native.filegroup(
name = srcs_filegroup_name if srcs_filegroup_name else "%s_includes" % (name),
- srcs = srcs,
+ srcs = srcs + includes,
compatible_with = compatible_with,
restricted_to = restricted_to,
visibility = srcs_filegroup_visibility if srcs_filegroup_visibility != None else visibility,
)
+
+def flatbuffer_ts_library(
+ name,
+ srcs,
+ compatible_with = None,
+ target_compatible_with = None,
+ deps = [],
+ include_paths = DEFAULT_INCLUDE_PATHS,
+ flatc_args = DEFAULT_FLATC_TS_ARGS,
+ visibility = None,
+ restricted_to = None,
+ include_reflection = True):
+ """Generates a ts_library rule for a given flatbuffer definition.
+
+ Args:
+ name: Name of the generated ts_library rule.
+ srcs: Source .fbs file(s).
+ deps: Other flatbuffer_ts_library's to depend on. Note that currently
+ you must specify all your transitive dependencies manually.
+ include_paths: Optional, list of paths the includes files can be found in.
+ flatc_args: Optional list of additional arguments to pass to flatc
+ (e.g. --gen-mutable).
+ visibility: The visibility of the generated cc_library. By default, use the
+ default visibility of the project.
+ compatible_with: Optional, The list of environments this rule can be built
+ for, in addition to default-supported environments.
+ restricted_to: Optional, The list of environments this rule can be built
+ for, instead of default-supported environments.
+ target_compatible_with: Optional, The list of target platform constraints
+ to use.
+ include_reflection: Optional, Whether to depend on the flatbuffer
+ reflection library automatically. Only really relevant for the
+ target that builds the reflection library itself.
+ """
+ srcs_lib = "%s_srcs" % (name)
+ outs = ["%s_generated.ts" % (s.replace(".fbs", "").split("/")[-1]) for s in srcs]
+ includes = [d + "_includes" for d in deps]
+ flatbuffer_library_public(
+ name = srcs_lib,
+ srcs = srcs,
+ outs = outs,
+ language_flag = "--ts",
+ includes = includes,
+ include_paths = include_paths,
+ flatc_args = flatc_args,
+ compatible_with = compatible_with,
+ restricted_to = restricted_to,
+ target_compatible_with = target_compatible_with,
+ )
+ ts_project(
+ name = name + "_ts",
+ srcs = outs,
+ declaration = True,
+ visibility = visibility,
+ compatible_with = compatible_with,
+ restricted_to = restricted_to,
+ target_compatible_with = target_compatible_with,
+ tsconfig = {
+ "compilerOptions": {
+ "declaration": True,
+ "lib": [
+ "ES2015",
+ "ES2020.BigInt",
+ "DOM",
+ ],
+ "module": "commonjs",
+ "moduleResolution": "node",
+ "strict": True,
+ "types": ["node"],
+ },
+ },
+ deps = deps + ["//ts:flatbuffers"] + (["//reflection:reflection_ts_fbs"] if include_reflection else []),
+ )
+ js_library(
+ name = name,
+ visibility = visibility,
+ compatible_with = compatible_with,
+ restricted_to = restricted_to,
+ target_compatible_with = target_compatible_with,
+ deps = [name + "_ts"],
+ )
+ native.filegroup(
+ name = "%s_includes" % (name),
+ srcs = srcs + includes,
+ compatible_with = compatible_with,
+ restricted_to = restricted_to,
+ visibility = visibility,
+ )
diff --git a/conan/build.py b/conan/build.py
index 5545631..9a85718 100644
--- a/conan/build.py
+++ b/conan/build.py
@@ -6,16 +6,6 @@
from cpt.packager import ConanMultiPackager
-def set_appveyor_environment():
- if os.getenv("APPVEYOR") is not None:
- compiler_version = os.getenv("CMAKE_VS_VERSION").split(" ")[0].replace('"', '')
- os.environ["CONAN_VISUAL_VERSIONS"] = compiler_version
- os.environ["CONAN_STABLE_BRANCH_PATTERN"] = "master"
- ci_platform = os.getenv("Platform").replace('"', '')
- ci_platform = "x86" if ci_platform == "x86" else "x86_64"
- os.environ["CONAN_ARCHS"] = ci_platform
- os.environ["CONAN_BUILD_TYPES"] = os.getenv("Configuration").replace('"', '')
-
def get_branch():
try:
@@ -56,7 +46,6 @@
stable_branch_pattern = os.getenv("CONAN_STABLE_BRANCH_PATTERN", r"v\d+\.\d+\.\d+.*")
test_folder = os.getenv("CPT_TEST_FOLDER", os.path.join("conan", "test_package"))
upload_only_when_stable = os.getenv("CONAN_UPLOAD_ONLY_WHEN_STABLE", True)
- set_appveyor_environment()
builder = ConanMultiPackager(reference=get_reference(username),
username=username,
diff --git a/dart/CHANGELOG.md b/dart/CHANGELOG.md
index 5e2d2de..a582e2e 100644
--- a/dart/CHANGELOG.md
+++ b/dart/CHANGELOG.md
@@ -1,4 +1,22 @@
-# CHANGELOG
+## 2.0.5
+
+- switch to null safety (#6696)
+- add Object APIs (pack/unpack) (#6682, #6723, #6846)
+- add custom builder buffer allocator support (#6711)
+- add `Builder.size()` - finished buffer size (#6403)
+- make `writeString()` argument non-nullable (#6737)
+- make tables fixed size (expect the number of fields when creating) (#6735)
+- make table deduplication optional (param `deduplicateTables`) (#6734)
+- change `Builder.reset()` to reuse an existing buffer (#6661)
+- change table building to assert() instead of exceptions (#6754)
+- optimize `writeString()` for ASCII (param `asciiOptimization`) (#6736)
+- change `StringReader` to make ASCII optimization optional (param `asciiOptimization`) (#6758)
+- change `[byte]` and `[ubyte]` representation to `dart:typed_data` `Int8List` and `Uint8List` (#6839)
+- rename `lowFinish()` to `buffer` getter (#6712)
+- fix `Builder._writeString()` - always write trailing zero byte (#6390)
+- fix `Builder.reset()` - clear vTables (#6386)
+- make sure added padding is zeroed, same as in C++ (#6716)
+- many performance improvements (#6755)
## 1.9.2
@@ -11,4 +29,4 @@
## 1.9.0
-- Initial release, supports Dart 1.x and many dev versions of Dart 2.x
\ No newline at end of file
+- Initial release, supports Dart 1.x and many dev versions of Dart 2.x
diff --git a/dart/LICENSE b/dart/LICENSE
index b2ae013..c02ca2f 100644
--- a/dart/LICENSE
+++ b/dart/LICENSE
@@ -1,35 +1,3 @@
-The code in lib/flat_buffers.dart is based on code that was releases under the
-following license:
-
-Copyright 2012, the Dart project authors. All rights reserved.
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are
-met:
- * Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
- * Redistributions in binary form must reproduce the above
- copyright notice, this list of conditions and the following
- disclaimer in the documentation and/or other materials provided
- with the distribution.
- * Neither the name of Google Inc. nor the names of its
- contributors may be used to endorse or promote products derived
- from this software without specific prior written permission.
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-To the extent permissible, the changes to that code and the other assets in
-this package are licensed under the Apache2 license:
-
-
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
diff --git a/dart/README.md b/dart/README.md
index 11bc0c4..123cdc3 100644
--- a/dart/README.md
+++ b/dart/README.md
@@ -1,13 +1,23 @@
# FlatBuffers for Dart
-This package is used to read and write FlatBuffer files in Dart.
+This package is used to read and write [FlatBuffers](https://google.github.io/flatbuffers/).
-Most consumers will want to use the [`flatc`](https://github.com/google/flatbuffers)
-compiler to generate Dart code from a FlatBuffers IDL schema. For example, the
-`monster_my_game.sample_generated.dart` was generated with `flatc` from
-`monster.fbs` in the example folder. The generated classes can be used to read
-or write binary files that are interoperable with other languages and platforms
-supported by FlatBuffers, as illustrated in the `example.dart` in the
+Most consumers will want to use the [`flatc` - FlatBuffer compiler](https://github.com/google/flatbuffers) binary for your platform.
+You can find it in the `generator/{Platform}` directory of the [released package archive](https://pub.dev/packages/flat_buffers/versions/2.0.5.tar.gz).
+
+The FlatBuffer compiler `flatc` reads a FlatBuffers IDL schema and generates Dart code.
+The generated classes can be used to read or write binary data/files that are interoperable with
+other languages and platforms supported by FlatBuffers, as illustrated in the `example.dart` in the
examples folder.
-Additional documentation and examples are available [at the FlatBuffers site](https://google.github.io/flatbuffers/index.html)
\ No newline at end of file
+For more details and documentation, head over to the official site and read the
+[Tutorial](https://google.github.io/flatbuffers/flatbuffers_guide_tutorial.html) and how to
+[use FlatBuffers in Dart](https://google.github.io/flatbuffers/flatbuffers_guide_use_dart.html).
+
+## Dart 2.0 notes
+Version 2.0.5 ships with it's own custom build of `flatc` because this is an extraordinary release to catch-up
+with FlatBuffers for other platforms. This generator can only generate dart code (to avoid generating code for other platforms which isn't released yet).
+On the other hand, the generated code still produces standard binary FlatBuffers compatible with other languages.
+In other words: only `flatc --dart ...` works with this generator, but your app will be able to produce and read standard binary (`Uint8List`) FlatBuffers that are fully compotible with other languages supporting FlatBuffers (e.g. Java, C++, ...).
+
+In the future a common `flatc` binary for all platforms would be shipped through GitHub release page instead.
diff --git a/dart/analysis_options.yaml b/dart/analysis_options.yaml
new file mode 100644
index 0000000..572dd23
--- /dev/null
+++ b/dart/analysis_options.yaml
@@ -0,0 +1 @@
+include: package:lints/recommended.yaml
diff --git a/dart/example/example.dart b/dart/example/example.dart
index d95bb31..d397bbb 100644
--- a/dart/example/example.dart
+++ b/dart/example/example.dart
@@ -15,7 +15,7 @@
*/
import 'package:flat_buffers/flat_buffers.dart' as fb;
-import './monster_my_game.sample_generated.dart' as myGame;
+import './monster_my_game.sample_generated.dart' as my_game;
// Example how to use FlatBuffers to create and read binary buffers.
@@ -25,27 +25,27 @@
}
void builderTest() {
- final builder = new fb.Builder(initialSize: 1024);
- final int weaponOneName = builder.writeString("Sword");
+ final builder = fb.Builder(initialSize: 1024);
+ final int? weaponOneName = builder.writeString("Sword");
final int weaponOneDamage = 3;
- final int weaponTwoName = builder.writeString("Axe");
+ final int? weaponTwoName = builder.writeString("Axe");
final int weaponTwoDamage = 5;
- final swordBuilder = new myGame.WeaponBuilder(builder)
+ final swordBuilder = my_game.WeaponBuilder(builder)
..begin()
..addNameOffset(weaponOneName)
..addDamage(weaponOneDamage);
final int sword = swordBuilder.finish();
- final axeBuilder = new myGame.WeaponBuilder(builder)
+ final axeBuilder = my_game.WeaponBuilder(builder)
..begin()
..addNameOffset(weaponTwoName)
..addDamage(weaponTwoDamage);
final int axe = axeBuilder.finish();
// Serialize a name for our monster, called "Orc".
- final int name = builder.writeString('Orc');
+ final int? name = builder.writeString('Orc');
// Create a list representing the inventory of the Orc. Each number
// could correspond to an item that can be claimed after he is slain.
@@ -54,7 +54,7 @@
final weapons = builder.writeList([sword, axe]);
// Struct builders are very easy to reuse.
- final vec3Builder = new myGame.Vec3Builder(builder);
+ final vec3Builder = my_game.Vec3Builder(builder);
vec3Builder.finish(4.0, 5.0, 6.0);
vec3Builder.finish(1.0, 2.0, 3.0);
@@ -62,21 +62,21 @@
final int hp = 300;
final int mana = 150;
- final monster = new myGame.MonsterBuilder(builder)
+ final monster = my_game.MonsterBuilder(builder)
..begin()
..addNameOffset(name)
..addInventoryOffset(inventory)
..addWeaponsOffset(weapons)
- ..addEquippedType(myGame.EquipmentTypeId.Weapon)
+ ..addEquippedType(my_game.EquipmentTypeId.Weapon)
..addEquippedOffset(axe)
..addHp(hp)
..addMana(mana)
..addPos(vec3Builder.finish(1.0, 2.0, 3.0))
- ..addColor(myGame.Color.Red);
+ ..addColor(my_game.Color.Red);
final int monsteroff = monster.finish();
- final buffer = builder.finish(monsteroff);
- if (verify(buffer)) {
+ builder.finish(monsteroff);
+ if (verify(builder.buffer)) {
print(
"The FlatBuffer was successfully created with a builder and verified!");
}
@@ -85,17 +85,17 @@
void objectBuilderTest() {
// Create the builder here so we can use it for both weapons and equipped
// the actual data will only be written to the buffer once.
- var axe = new myGame.WeaponObjectBuilder(name: 'Axe', damage: 5);
+ var axe = my_game.WeaponObjectBuilder(name: 'Axe', damage: 5);
- var monsterBuilder = new myGame.MonsterObjectBuilder(
- pos: new myGame.Vec3ObjectBuilder(x: 1.0, y: 2.0, z: 3.0),
+ var monsterBuilder = my_game.MonsterObjectBuilder(
+ pos: my_game.Vec3ObjectBuilder(x: 1.0, y: 2.0, z: 3.0),
mana: 150,
hp: 300,
name: 'Orc',
inventory: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
- color: myGame.Color.Red,
- weapons: [new myGame.WeaponObjectBuilder(name: 'Sword', damage: 3), axe],
- equippedType: myGame.EquipmentTypeId.Weapon,
+ color: my_game.Color.Red,
+ weapons: [my_game.WeaponObjectBuilder(name: 'Sword', damage: 3), axe],
+ equippedType: my_game.EquipmentTypeId.Weapon,
equipped: axe,
);
@@ -114,7 +114,7 @@
bool verify(List<int> buffer) {
// Get access to the root:
- var monster = new myGame.Monster(buffer);
+ var monster = my_game.Monster(buffer);
// Get and test some scalar types from the FlatBuffer.
assert(monster.hp == 80);
@@ -122,31 +122,29 @@
assert(monster.name == "MyMonster");
// Get and test a field of the FlatBuffer's `struct`.
- var pos = monster.pos;
- assert(pos != null);
+ var pos = monster.pos!;
assert(pos.z == 3.0);
// Get a test an element from the `inventory` FlatBuffer's `vector`.
- var inv = monster.inventory;
- assert(inv != null);
+ var inv = monster.inventory!;
assert(inv.length == 10);
assert(inv[9] == 9);
// Get and test the `weapons` FlatBuffers's `vector`.
- var expected_weapon_names = ["Sword", "Axe"];
- var expected_weapon_damages = [3, 5];
- var weps = monster.weapons;
+ var expectedWeaponNames = ["Sword", "Axe"];
+ var expectedWeaponDamages = [3, 5];
+ var weps = monster.weapons!;
for (int i = 0; i < weps.length; i++) {
- assert(weps[i].name == expected_weapon_names[i]);
- assert(weps[i].damage == expected_weapon_damages[i]);
+ assert(weps[i].name == expectedWeaponNames[i]);
+ assert(weps[i].damage == expectedWeaponDamages[i]);
}
// Get and test the `Equipment` union (`equipped` field).
- assert(monster.equippedType.value == myGame.EquipmentTypeId.Weapon.value);
- assert(monster.equippedType == myGame.EquipmentTypeId.Weapon);
+ assert(monster.equippedType!.value == my_game.EquipmentTypeId.Weapon.value);
+ assert(monster.equippedType == my_game.EquipmentTypeId.Weapon);
- assert(monster.equipped is myGame.Weapon);
- var equipped = monster.equipped as myGame.Weapon;
+ assert(monster.equipped is my_game.Weapon);
+ var equipped = monster.equipped as my_game.Weapon;
assert(equipped.name == "Axe");
assert(equipped.damage == 5);
diff --git a/dart/example/monster_my_game.sample_generated.dart b/dart/example/monster_my_game.sample_generated.dart
index 2c7c10d..ba0a81f 100644
--- a/dart/example/monster_my_game.sample_generated.dart
+++ b/dart/example/monster_my_game.sample_generated.dart
@@ -1,5 +1,5 @@
// automatically generated by the FlatBuffers compiler, do not modify
-// ignore_for_file: unused_import, non_constant_identifier_names
+// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable
library my_game.sample;
@@ -12,23 +12,29 @@
const Color._(this.value);
factory Color.fromValue(int value) {
- if (value == null) return null;
- if (!values.containsKey(value)) {
- throw new StateError('Invalid value $value for bit flag enum Color');
+ final result = values[value];
+ if (result == null) {
+ throw StateError('Invalid value $value for bit flag enum Color');
}
- return values[value];
+ return result;
}
+ static Color? _createOrNull(int? value) =>
+ value == null ? null : Color.fromValue(value);
+
static const int minValue = 0;
static const int maxValue = 2;
static bool containsValue(int value) => values.containsKey(value);
- static const Color Red = const Color._(0);
- static const Color Green = const Color._(1);
- static const Color Blue = const Color._(2);
- static get values => {0: Red,1: Green,2: Blue,};
+ static const Color Red = Color._(0);
+ static const Color Green = Color._(1);
+ static const Color Blue = Color._(2);
+ static const Map<int, Color> values = {
+ 0: Red,
+ 1: Green,
+ 2: Blue};
- static const fb.Reader<Color> reader = const _ColorReader();
+ static const fb.Reader<Color> reader = _ColorReader();
@override
String toString() {
@@ -44,7 +50,7 @@
@override
Color read(fb.BufferContext bc, int offset) =>
- new Color.fromValue(const fb.Int8Reader().read(bc, offset));
+ Color.fromValue(const fb.Int8Reader().read(bc, offset));
}
class EquipmentTypeId {
@@ -52,22 +58,27 @@
const EquipmentTypeId._(this.value);
factory EquipmentTypeId.fromValue(int value) {
- if (value == null) return null;
- if (!values.containsKey(value)) {
- throw new StateError('Invalid value $value for bit flag enum EquipmentTypeId');
+ final result = values[value];
+ if (result == null) {
+ throw StateError('Invalid value $value for bit flag enum EquipmentTypeId');
}
- return values[value];
+ return result;
}
+ static EquipmentTypeId? _createOrNull(int? value) =>
+ value == null ? null : EquipmentTypeId.fromValue(value);
+
static const int minValue = 0;
static const int maxValue = 1;
static bool containsValue(int value) => values.containsKey(value);
- static const EquipmentTypeId NONE = const EquipmentTypeId._(0);
- static const EquipmentTypeId Weapon = const EquipmentTypeId._(1);
- static get values => {0: NONE,1: Weapon,};
+ static const EquipmentTypeId NONE = EquipmentTypeId._(0);
+ static const EquipmentTypeId Weapon = EquipmentTypeId._(1);
+ static const Map<int, EquipmentTypeId> values = {
+ 0: NONE,
+ 1: Weapon};
- static const fb.Reader<EquipmentTypeId> reader = const _EquipmentTypeIdReader();
+ static const fb.Reader<EquipmentTypeId> reader = _EquipmentTypeIdReader();
@override
String toString() {
@@ -83,13 +94,13 @@
@override
EquipmentTypeId read(fb.BufferContext bc, int offset) =>
- new EquipmentTypeId.fromValue(const fb.Uint8Reader().read(bc, offset));
+ EquipmentTypeId.fromValue(const fb.Uint8Reader().read(bc, offset));
}
class Vec3 {
Vec3._(this._bc, this._bcOffset);
- static const fb.Reader<Vec3> reader = const _Vec3Reader();
+ static const fb.Reader<Vec3> reader = _Vec3Reader();
final fb.BufferContext _bc;
final int _bcOffset;
@@ -112,13 +123,11 @@
@override
Vec3 createObject(fb.BufferContext bc, int offset) =>
- new Vec3._(bc, offset);
+ Vec3._(bc, offset);
}
class Vec3Builder {
- Vec3Builder(this.fbBuilder) {
- assert(fbBuilder != null);
- }
+ Vec3Builder(this.fbBuilder);
final fb.Builder fbBuilder;
@@ -137,9 +146,9 @@
final double _z;
Vec3ObjectBuilder({
- double x,
- double y,
- double z,
+ required double x,
+ required double y,
+ required double z,
})
: _x = x,
_y = y,
@@ -147,10 +156,7 @@
/// Finish building, and store into the [fbBuilder].
@override
- int finish(
- fb.Builder fbBuilder) {
- assert(fbBuilder != null);
-
+ int finish(fb.Builder fbBuilder) {
fbBuilder.putFloat32(_z);
fbBuilder.putFloat32(_y);
fbBuilder.putFloat32(_x);
@@ -159,39 +165,39 @@
/// Convenience method to serialize to byte list.
@override
- Uint8List toBytes([String fileIdentifier]) {
- fb.Builder fbBuilder = new fb.Builder();
- int offset = finish(fbBuilder);
- return fbBuilder.finish(offset, fileIdentifier);
+ Uint8List toBytes([String? fileIdentifier]) {
+ final fbBuilder = fb.Builder(deduplicateTables: false);
+ fbBuilder.finish(finish(fbBuilder), fileIdentifier);
+ return fbBuilder.buffer;
}
}
class Monster {
Monster._(this._bc, this._bcOffset);
factory Monster(List<int> bytes) {
- fb.BufferContext rootRef = new fb.BufferContext.fromBytes(bytes);
+ final rootRef = fb.BufferContext.fromBytes(bytes);
return reader.read(rootRef, 0);
}
- static const fb.Reader<Monster> reader = const _MonsterReader();
+ static const fb.Reader<Monster> reader = _MonsterReader();
final fb.BufferContext _bc;
final int _bcOffset;
- Vec3 get pos => Vec3.reader.vTableGet(_bc, _bcOffset, 4, null);
+ Vec3? get pos => Vec3.reader.vTableGetNullable(_bc, _bcOffset, 4);
int get mana => const fb.Int16Reader().vTableGet(_bc, _bcOffset, 6, 150);
int get hp => const fb.Int16Reader().vTableGet(_bc, _bcOffset, 8, 100);
- String get name => const fb.StringReader().vTableGet(_bc, _bcOffset, 10, null);
- List<int> get inventory => const fb.ListReader<int>(const fb.Uint8Reader()).vTableGet(_bc, _bcOffset, 14, null);
- Color get color => new Color.fromValue(const fb.Int8Reader().vTableGet(_bc, _bcOffset, 16, 2));
- List<Weapon> get weapons => const fb.ListReader<Weapon>(Weapon.reader).vTableGet(_bc, _bcOffset, 18, null);
- EquipmentTypeId get equippedType => new EquipmentTypeId.fromValue(const fb.Uint8Reader().vTableGet(_bc, _bcOffset, 20, null));
+ String? get name => const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 10);
+ List<int>? get inventory => const fb.Uint8ListReader().vTableGetNullable(_bc, _bcOffset, 14);
+ Color get color => Color.fromValue(const fb.Int8Reader().vTableGet(_bc, _bcOffset, 16, 2));
+ List<Weapon>? get weapons => const fb.ListReader<Weapon>(Weapon.reader).vTableGetNullable(_bc, _bcOffset, 18);
+ EquipmentTypeId? get equippedType => EquipmentTypeId._createOrNull(const fb.Uint8Reader().vTableGetNullable(_bc, _bcOffset, 20));
dynamic get equipped {
switch (equippedType?.value) {
- case 1: return Weapon.reader.vTableGet(_bc, _bcOffset, 22, null);
+ case 1: return Weapon.reader.vTableGetNullable(_bc, _bcOffset, 22);
default: return null;
}
}
- List<Vec3> get path => const fb.ListReader<Vec3>(Vec3.reader).vTableGet(_bc, _bcOffset, 24, null);
+ List<Vec3>? get path => const fb.ListReader<Vec3>(Vec3.reader).vTableGetNullable(_bc, _bcOffset, 24);
@override
String toString() {
@@ -204,57 +210,55 @@
@override
Monster createObject(fb.BufferContext bc, int offset) =>
- new Monster._(bc, offset);
+ Monster._(bc, offset);
}
class MonsterBuilder {
- MonsterBuilder(this.fbBuilder) {
- assert(fbBuilder != null);
- }
+ MonsterBuilder(this.fbBuilder);
final fb.Builder fbBuilder;
void begin() {
- fbBuilder.startTable();
+ fbBuilder.startTable(10);
}
int addPos(int offset) {
fbBuilder.addStruct(0, offset);
return fbBuilder.offset;
}
- int addMana(int mana) {
+ int addMana(int? mana) {
fbBuilder.addInt16(1, mana);
return fbBuilder.offset;
}
- int addHp(int hp) {
+ int addHp(int? hp) {
fbBuilder.addInt16(2, hp);
return fbBuilder.offset;
}
- int addNameOffset(int offset) {
+ int addNameOffset(int? offset) {
fbBuilder.addOffset(3, offset);
return fbBuilder.offset;
}
- int addInventoryOffset(int offset) {
+ int addInventoryOffset(int? offset) {
fbBuilder.addOffset(5, offset);
return fbBuilder.offset;
}
- int addColor(Color color) {
+ int addColor(Color? color) {
fbBuilder.addInt8(6, color?.value);
return fbBuilder.offset;
}
- int addWeaponsOffset(int offset) {
+ int addWeaponsOffset(int? offset) {
fbBuilder.addOffset(7, offset);
return fbBuilder.offset;
}
- int addEquippedType(EquipmentTypeId equippedType) {
+ int addEquippedType(EquipmentTypeId? equippedType) {
fbBuilder.addUint8(8, equippedType?.value);
return fbBuilder.offset;
}
- int addEquippedOffset(int offset) {
+ int addEquippedOffset(int? offset) {
fbBuilder.addOffset(9, offset);
return fbBuilder.offset;
}
- int addPathOffset(int offset) {
+ int addPathOffset(int? offset) {
fbBuilder.addOffset(10, offset);
return fbBuilder.offset;
}
@@ -265,28 +269,28 @@
}
class MonsterObjectBuilder extends fb.ObjectBuilder {
- final Vec3ObjectBuilder _pos;
- final int _mana;
- final int _hp;
- final String _name;
- final List<int> _inventory;
- final Color _color;
- final List<WeaponObjectBuilder> _weapons;
- final EquipmentTypeId _equippedType;
+ final Vec3ObjectBuilder? _pos;
+ final int? _mana;
+ final int? _hp;
+ final String? _name;
+ final List<int>? _inventory;
+ final Color? _color;
+ final List<WeaponObjectBuilder>? _weapons;
+ final EquipmentTypeId? _equippedType;
final dynamic _equipped;
- final List<Vec3ObjectBuilder> _path;
+ final List<Vec3ObjectBuilder>? _path;
MonsterObjectBuilder({
- Vec3ObjectBuilder pos,
- int mana,
- int hp,
- String name,
- List<int> inventory,
- Color color,
- List<WeaponObjectBuilder> weapons,
- EquipmentTypeId equippedType,
+ Vec3ObjectBuilder? pos,
+ int? mana,
+ int? hp,
+ String? name,
+ List<int>? inventory,
+ Color? color,
+ List<WeaponObjectBuilder>? weapons,
+ EquipmentTypeId? equippedType,
dynamic equipped,
- List<Vec3ObjectBuilder> path,
+ List<Vec3ObjectBuilder>? path,
})
: _pos = pos,
_mana = mana,
@@ -301,69 +305,54 @@
/// Finish building, and store into the [fbBuilder].
@override
- int finish(
- fb.Builder fbBuilder) {
- assert(fbBuilder != null);
- final int nameOffset = fbBuilder.writeString(_name);
- final int inventoryOffset = _inventory?.isNotEmpty == true
- ? fbBuilder.writeListUint8(_inventory)
- : null;
- final int weaponsOffset = _weapons?.isNotEmpty == true
- ? fbBuilder.writeList(_weapons.map((b) => b.getOrCreateOffset(fbBuilder)).toList())
- : null;
- final int equippedOffset = _equipped?.getOrCreateOffset(fbBuilder);
- final int pathOffset = _path?.isNotEmpty == true
- ? fbBuilder.writeListOfStructs(_path)
- : null;
-
- fbBuilder.startTable();
+ int finish(fb.Builder fbBuilder) {
+ final int? nameOffset = _name == null ? null
+ : fbBuilder.writeString(_name!);
+ final int? inventoryOffset = _inventory == null ? null
+ : fbBuilder.writeListUint8(_inventory!);
+ final int? weaponsOffset = _weapons == null ? null
+ : fbBuilder.writeList(_weapons!.map((b) => b.getOrCreateOffset(fbBuilder)).toList());
+ final int? equippedOffset = _equipped?.getOrCreateOffset(fbBuilder);
+ final int? pathOffset = _path == null ? null
+ : fbBuilder.writeListOfStructs(_path!);
+ fbBuilder.startTable(10);
if (_pos != null) {
- fbBuilder.addStruct(0, _pos.finish(fbBuilder));
+ fbBuilder.addStruct(0, _pos!.finish(fbBuilder));
}
fbBuilder.addInt16(1, _mana);
fbBuilder.addInt16(2, _hp);
- if (nameOffset != null) {
- fbBuilder.addOffset(3, nameOffset);
- }
- if (inventoryOffset != null) {
- fbBuilder.addOffset(5, inventoryOffset);
- }
+ fbBuilder.addOffset(3, nameOffset);
+ fbBuilder.addOffset(5, inventoryOffset);
fbBuilder.addInt8(6, _color?.value);
- if (weaponsOffset != null) {
- fbBuilder.addOffset(7, weaponsOffset);
- }
+ fbBuilder.addOffset(7, weaponsOffset);
fbBuilder.addUint8(8, _equippedType?.value);
- if (equippedOffset != null) {
- fbBuilder.addOffset(9, equippedOffset);
- }
- if (pathOffset != null) {
- fbBuilder.addOffset(10, pathOffset);
- }
+ fbBuilder.addOffset(9, equippedOffset);
+ fbBuilder.addOffset(10, pathOffset);
return fbBuilder.endTable();
}
/// Convenience method to serialize to byte list.
@override
- Uint8List toBytes([String fileIdentifier]) {
- fb.Builder fbBuilder = new fb.Builder();
- int offset = finish(fbBuilder);
- return fbBuilder.finish(offset, fileIdentifier);
+ Uint8List toBytes([String? fileIdentifier]) {
+ final fbBuilder = fb.Builder(deduplicateTables: false);
+ fbBuilder.finish(finish(fbBuilder), fileIdentifier);
+ return fbBuilder.buffer;
}
}
class Weapon {
Weapon._(this._bc, this._bcOffset);
factory Weapon(List<int> bytes) {
- fb.BufferContext rootRef = new fb.BufferContext.fromBytes(bytes);
+ final rootRef = fb.BufferContext.fromBytes(bytes);
return reader.read(rootRef, 0);
}
- static const fb.Reader<Weapon> reader = const _WeaponReader();
+ static const fb.Reader<Weapon> reader = _WeaponReader();
final fb.BufferContext _bc;
final int _bcOffset;
- String get name => const fb.StringReader().vTableGet(_bc, _bcOffset, 4, null);
- int get damage => const fb.Int16Reader().vTableGet(_bc, _bcOffset, 6, null);
+ String? get name => const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 4);
+ int get damage => const fb.Int16Reader().vTableGet(_bc, _bcOffset, 6, 0);
@override
String toString() {
@@ -376,25 +365,23 @@
@override
Weapon createObject(fb.BufferContext bc, int offset) =>
- new Weapon._(bc, offset);
+ Weapon._(bc, offset);
}
class WeaponBuilder {
- WeaponBuilder(this.fbBuilder) {
- assert(fbBuilder != null);
- }
+ WeaponBuilder(this.fbBuilder);
final fb.Builder fbBuilder;
void begin() {
- fbBuilder.startTable();
+ fbBuilder.startTable(2);
}
- int addNameOffset(int offset) {
+ int addNameOffset(int? offset) {
fbBuilder.addOffset(0, offset);
return fbBuilder.offset;
}
- int addDamage(int damage) {
+ int addDamage(int? damage) {
fbBuilder.addInt16(1, damage);
return fbBuilder.offset;
}
@@ -405,36 +392,32 @@
}
class WeaponObjectBuilder extends fb.ObjectBuilder {
- final String _name;
- final int _damage;
+ final String? _name;
+ final int? _damage;
WeaponObjectBuilder({
- String name,
- int damage,
+ String? name,
+ int? damage,
})
: _name = name,
_damage = damage;
/// Finish building, and store into the [fbBuilder].
@override
- int finish(
- fb.Builder fbBuilder) {
- assert(fbBuilder != null);
- final int nameOffset = fbBuilder.writeString(_name);
-
- fbBuilder.startTable();
- if (nameOffset != null) {
- fbBuilder.addOffset(0, nameOffset);
- }
+ int finish(fb.Builder fbBuilder) {
+ final int? nameOffset = _name == null ? null
+ : fbBuilder.writeString(_name!);
+ fbBuilder.startTable(2);
+ fbBuilder.addOffset(0, nameOffset);
fbBuilder.addInt16(1, _damage);
return fbBuilder.endTable();
}
/// Convenience method to serialize to byte list.
@override
- Uint8List toBytes([String fileIdentifier]) {
- fb.Builder fbBuilder = new fb.Builder();
- int offset = finish(fbBuilder);
- return fbBuilder.finish(offset, fileIdentifier);
+ Uint8List toBytes([String? fileIdentifier]) {
+ final fbBuilder = fb.Builder(deduplicateTables: false);
+ fbBuilder.finish(finish(fbBuilder), fileIdentifier);
+ return fbBuilder.buffer;
}
}
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
+ }
+}
diff --git a/dart/lib/src/builder.dart b/dart/lib/src/builder.dart
index 5ce46dc..a0d47ed 100644
--- a/dart/lib/src/builder.dart
+++ b/dart/lib/src/builder.dart
@@ -5,38 +5,27 @@
/// The main builder class for creation of a FlexBuffer.
class Builder {
- ByteData _buffer;
- List<_StackValue> _stack;
- List<_StackPointer> _stackPointers;
- int _offset;
- bool _finished;
- Map<String, _StackValue> _stringCache;
- Map<String, _StackValue> _keyCache;
- Map<_KeysHash, _StackValue> _keyVectorCache;
- Map<int, _StackValue> _indirectIntCache;
- Map<double, _StackValue> _indirectDoubleCache;
+ final ByteData _buffer;
+ List<_StackValue> _stack = [];
+ List<_StackPointer> _stackPointers = [];
+ int _offset = 0;
+ bool _finished = false;
+ final Map<String, _StackValue> _stringCache = {};
+ final Map<String, _StackValue> _keyCache = {};
+ final Map<_KeysHash, _StackValue> _keyVectorCache = {};
+ final Map<int, _StackValue> _indirectIntCache = {};
+ final Map<double, _StackValue> _indirectDoubleCache = {};
/// Instantiate the builder if you intent to gradually build up the buffer by calling
/// add... methods and calling [finish] to receive the the resulting byte array.
///
/// The default size of internal buffer is set to 2048. Provide a different value in order to avoid buffer copies.
- Builder({int size = 2048}) {
- _buffer = ByteData(size);
- _stack = [];
- _stackPointers = [];
- _offset = 0;
- _finished = false;
- _stringCache = {};
- _keyCache = {};
- _keyVectorCache = {};
- _indirectIntCache = {};
- _indirectDoubleCache = {};
- }
+ Builder({int size = 2048}) : _buffer = ByteData(size);
/// Use this method in order to turn an object into a FlexBuffer directly.
///
/// Use the manual instantiation of the [Builder] and gradual addition of values, if performance is more important than convenience.
- static ByteBuffer buildFromObject(Object value) {
+ static ByteBuffer buildFromObject(Object? value) {
final builder = Builder();
builder._add(value);
final buffer = builder.finish();
@@ -45,7 +34,7 @@
return byteData.buffer;
}
- void _add(Object value) {
+ void _add(Object? value) {
if (value == null) {
addNull();
} else if (value is bool) {
@@ -81,32 +70,32 @@
/// Specifically useful when building up a vector where values can be null.
void addNull() {
_integrityCheckOnValueAddition();
- _stack.add(_StackValue.WithNull());
+ _stack.add(_StackValue.withNull());
}
/// Adds a string value.
void addInt(int value) {
_integrityCheckOnValueAddition();
- _stack.add(_StackValue.WithInt(value));
+ _stack.add(_StackValue.withInt(value));
}
/// Adds a bool value.
void addBool(bool value) {
_integrityCheckOnValueAddition();
- _stack.add(_StackValue.WithBool(value));
+ _stack.add(_StackValue.withBool(value));
}
/// Adds a double value.
void addDouble(double value) {
_integrityCheckOnValueAddition();
- _stack.add(_StackValue.WithDouble(value));
+ _stack.add(_StackValue.withDouble(value));
}
/// Adds a string value.
void addString(String value) {
_integrityCheckOnValueAddition();
if (_stringCache.containsKey(value)) {
- _stack.add(_stringCache[value]);
+ _stack.add(_stringCache[value]!);
return;
}
final utf8String = utf8.encode(value);
@@ -118,7 +107,8 @@
final newOffset = _newOffset(length + 1);
_pushBuffer(utf8String);
_offset = newOffset;
- final stackValue = _StackValue.WithOffset(stringOffset, ValueType.String, bitWidth);
+ final stackValue =
+ _StackValue.withOffset(stringOffset, ValueType.String, bitWidth);
_stack.add(stackValue);
_stringCache[value] = stackValue;
}
@@ -129,7 +119,7 @@
void addKey(String value) {
_integrityCheckOnKeyAddition();
if (_keyCache.containsKey(value)) {
- _stack.add(_keyCache[value]);
+ _stack.add(_keyCache[value]!);
return;
}
final utf8String = utf8.encode(value);
@@ -138,7 +128,8 @@
final newOffset = _newOffset(length + 1);
_pushBuffer(utf8String);
_offset = newOffset;
- final stackValue = _StackValue.WithOffset(keyOffset, ValueType.Key, BitWidth.width8);
+ final stackValue =
+ _StackValue.withOffset(keyOffset, ValueType.Key, BitWidth.width8);
_stack.add(stackValue);
_keyCache[value] = stackValue;
}
@@ -156,7 +147,8 @@
final newOffset = _newOffset(length);
_pushBuffer(value.asUint8List());
_offset = newOffset;
- final stackValue = _StackValue.WithOffset(blobOffset, ValueType.Blob, bitWidth);
+ final stackValue =
+ _StackValue.withOffset(blobOffset, ValueType.Blob, bitWidth);
_stack.add(stackValue);
}
@@ -169,15 +161,16 @@
void addIntIndirectly(int value, {bool cache = false}) {
_integrityCheckOnValueAddition();
if (_indirectIntCache.containsKey(value)) {
- _stack.add(_indirectIntCache[value]);
+ _stack.add(_indirectIntCache[value]!);
return;
}
- final stackValue = _StackValue.WithInt(value);
+ final stackValue = _StackValue.withInt(value);
final byteWidth = _align(stackValue.width);
final newOffset = _newOffset(byteWidth);
final valueOffset = _offset;
_pushBuffer(stackValue.asU8List(stackValue.width));
- final stackOffset = _StackValue.WithOffset(valueOffset, ValueType.IndirectInt, stackValue.width);
+ final stackOffset = _StackValue.withOffset(
+ valueOffset, ValueType.IndirectInt, stackValue.width);
_stack.add(stackOffset);
_offset = newOffset;
if (cache) {
@@ -193,15 +186,16 @@
void addDoubleIndirectly(double value, {bool cache = false}) {
_integrityCheckOnValueAddition();
if (cache && _indirectDoubleCache.containsKey(value)) {
- _stack.add(_indirectDoubleCache[value]);
+ _stack.add(_indirectDoubleCache[value]!);
return;
}
- final stackValue = _StackValue.WithDouble(value);
+ final stackValue = _StackValue.withDouble(value);
final byteWidth = _align(stackValue.width);
final newOffset = _newOffset(byteWidth);
final valueOffset = _offset;
_pushBuffer(stackValue.asU8List(stackValue.width));
- final stackOffset = _StackValue.WithOffset(valueOffset, ValueType.IndirectFloat, stackValue.width);
+ final stackOffset = _StackValue.withOffset(
+ valueOffset, ValueType.IndirectFloat, stackValue.width);
_stack.add(stackOffset);
_offset = newOffset;
if (cache) {
@@ -258,8 +252,10 @@
tmp._offset = _offset;
tmp._stack = List.from(_stack);
tmp._stackPointers = List.from(_stackPointers);
- tmp._buffer.buffer.asUint8List().setAll(0, _buffer.buffer.asUint8List(0, _offset));
- for (var i = 0; i < tmp._stackPointers.length; i++){
+ tmp._buffer.buffer
+ .asUint8List()
+ .setAll(0, _buffer.buffer.asUint8List(0, _offset));
+ for (var i = 0; i < tmp._stackPointers.length; i++) {
tmp.end();
}
final buffer = tmp.finish();
@@ -267,14 +263,15 @@
bd.buffer.asUint8List().setAll(0, buffer);
return bd.buffer;
}
-
+
void _integrityCheckOnValueAddition() {
if (_finished) {
throw StateError('Adding values after finish is prohibited');
}
if (_stackPointers.isNotEmpty && _stackPointers.last.isVector == false) {
if (_stack.last.type != ValueType.Key) {
- throw StateError('Adding value to a map before adding a key is prohibited');
+ throw StateError(
+ 'Adding value to a map before adding a key is prohibited');
}
}
}
@@ -290,7 +287,8 @@
void _finish() {
if (_stack.length != 1) {
- throw StateError('Stack has to be exactly 1, but is ${_stack.length}. You have to end all started vectors and maps, before calling [finish]');
+ throw StateError(
+ 'Stack has to be exactly 1, but is ${_stack.length}. You have to end all started vectors and maps, before calling [finish]');
}
final value = _stack[0];
final byteWidth = _align(value.elementWidth(_offset, 0));
@@ -299,8 +297,9 @@
_writeUInt(byteWidth, 1);
_finished = true;
}
-
- _StackValue _createVector(int start, int vecLength, int step, [_StackValue keys]) {
+
+ _StackValue _createVector(int start, int vecLength, int step,
+ [_StackValue? keys]) {
var bitWidth = BitWidthUtil.uwidth(vecLength);
var prefixElements = 1;
if (keys != null) {
@@ -327,7 +326,9 @@
}
}
final byteWidth = _align(bitWidth);
- final fix = typed & ValueTypeUtils.isNumber(vectorType) && vecLength >= 2 && vecLength <= 4;
+ final fix = typed & ValueTypeUtils.isNumber(vectorType) &&
+ vecLength >= 2 &&
+ vecLength <= 4;
if (keys != null) {
_writeStackValue(keys, byteWidth);
_writeUInt(1 << keys.width.index, byteWidth);
@@ -345,13 +346,14 @@
}
}
if (keys != null) {
- return _StackValue.WithOffset(vecOffset, ValueType.Map, bitWidth);
+ return _StackValue.withOffset(vecOffset, ValueType.Map, bitWidth);
}
if (typed) {
- final vType = ValueTypeUtils.toTypedVector(vectorType, fix ? vecLength : 0);
- return _StackValue.WithOffset(vecOffset, vType, bitWidth);
+ final vType =
+ ValueTypeUtils.toTypedVector(vectorType, fix ? vecLength : 0);
+ return _StackValue.withOffset(vecOffset, vType, bitWidth);
}
- return _StackValue.WithOffset(vecOffset, ValueType.Vector, bitWidth);
+ return _StackValue.withOffset(vecOffset, ValueType.Vector, bitWidth);
}
void _endVector(_StackPointer pointer) {
@@ -363,12 +365,13 @@
void _sortKeysAndEndMap(_StackPointer pointer) {
if (((_stack.length - pointer.stackPosition) & 1) == 1) {
- throw StateError('The stack needs to hold key value pairs (even number of elements). Check if you combined [addKey] with add... method calls properly.');
+ throw StateError(
+ 'The stack needs to hold key value pairs (even number of elements). Check if you combined [addKey] with add... method calls properly.');
}
var sorted = true;
for (var i = pointer.stackPosition; i < _stack.length - 2; i += 2) {
- if (_shouldFlip(_stack[i], _stack[i+2])) {
+ if (_shouldFlip(_stack[i], _stack[i + 2])) {
sorted = false;
break;
}
@@ -394,36 +397,38 @@
}
_endMap(pointer);
}
-
+
void _endMap(_StackPointer pointer) {
final vecLength = (_stack.length - pointer.stackPosition) >> 1;
final offsets = <int>[];
for (var i = pointer.stackPosition; i < _stack.length; i += 2) {
- offsets.add(_stack[i].offset);
+ offsets.add(_stack[i].offset!);
}
final keysHash = _KeysHash(offsets);
- var keysStackValue;
+ _StackValue? keysStackValue;
if (_keyVectorCache.containsKey(keysHash)) {
keysStackValue = _keyVectorCache[keysHash];
} else {
keysStackValue = _createVector(pointer.stackPosition, vecLength, 2);
_keyVectorCache[keysHash] = keysStackValue;
}
- final vec = _createVector(pointer.stackPosition + 1, vecLength, 2, keysStackValue);
+ final vec =
+ _createVector(pointer.stackPosition + 1, vecLength, 2, keysStackValue);
_stack.removeRange(pointer.stackPosition, _stack.length);
_stack.add(vec);
}
bool _shouldFlip(_StackValue v1, _StackValue v2) {
if (v1.type != ValueType.Key || v2.type != ValueType.Key) {
- throw StateError('Stack values are not keys $v1 | $v2. Check if you combined [addKey] with add... method calls properly.');
+ throw StateError(
+ 'Stack values are not keys $v1 | $v2. Check if you combined [addKey] with add... method calls properly.');
}
- var c1, c2;
+ late int c1, c2;
var index = 0;
do {
- c1 = _buffer.getUint8(v1.offset + index);
- c2 = _buffer.getUint8(v2.offset + index);
+ c1 = _buffer.getUint8(v1.offset! + index);
+ c2 = _buffer.getUint8(v2.offset! + index);
if (c2 < c1) return true;
if (c1 < c2) return false;
index += 1;
@@ -440,11 +445,12 @@
void _writeStackValue(_StackValue value, int byteWidth) {
final newOffset = _newOffset(byteWidth);
if (value.isOffset) {
- final relativeOffset = _offset - value.offset;
+ final relativeOffset = _offset - value.offset!;
if (byteWidth == 8 || relativeOffset < (1 << (byteWidth * 8))) {
_writeUInt(relativeOffset, byteWidth);
} else {
- throw StateError('Unexpected size $byteWidth. This might be a bug. Please create an issue https://github.com/google/flatbuffers/issues/new');
+ throw StateError(
+ 'Unexpected size $byteWidth. This might be a bug. Please create an issue https://github.com/google/flatbuffers/issues/new');
}
} else {
_pushBuffer(value.asU8List(BitWidthUtil.fromByteWidth(byteWidth)));
@@ -467,16 +473,13 @@
}
if (prevSize < size) {
final newBuf = ByteData(size);
- newBuf.buffer
- .asUint8List()
- .setAll(0, _buffer.buffer.asUint8List());
+ newBuf.buffer.asUint8List().setAll(0, _buffer.buffer.asUint8List());
}
return newOffset;
}
void _pushInt(int value, BitWidth width) {
switch (width) {
-
case BitWidth.width8:
_buffer.setInt8(_offset, value);
break;
@@ -494,7 +497,6 @@
void _pushUInt(int value, BitWidth width) {
switch (width) {
-
case BitWidth.width8:
_buffer.setUint8(_offset, value);
break;
@@ -516,37 +518,39 @@
}
class _StackValue {
- Object _value;
- int _offset;
- ValueType _type;
- BitWidth _width;
- _StackValue.WithNull() {
- _type = ValueType.Null;
- _width = BitWidth.width8;
- }
- _StackValue.WithInt(int value) {
- _type = value != null ? ValueType.Int : ValueType.Null;
- _width = BitWidthUtil.width(value);
- _value = value;
- }
- _StackValue.WithBool(bool value) {
- _type = value != null ? ValueType.Bool : ValueType.Null;
- _width = BitWidth.width8;
- _value = value;
- }
- _StackValue.WithDouble(double value) {
- _type = value != null ? ValueType.Float : ValueType.Null;
- _width = BitWidthUtil.width(value);
- _value = value;
- }
- _StackValue.WithOffset(int value, ValueType type, BitWidth width) {
- _offset = value;
- _type = type;
- _width = width;
- }
+ late Object _value;
+ int? _offset;
+ final ValueType _type;
+ final BitWidth _width;
+
+ _StackValue.withNull()
+ : _type = ValueType.Null,
+ _width = BitWidth.width8;
+
+ _StackValue.withInt(int value)
+ : _type = ValueType.Int,
+ _width = BitWidthUtil.width(value),
+ _value = value;
+
+ _StackValue.withBool(bool value)
+ : _type = ValueType.Bool,
+ _width = BitWidth.width8,
+ _value = value;
+
+ _StackValue.withDouble(double value)
+ : _type = ValueType.Float,
+ _width = BitWidthUtil.width(value),
+ _value = value;
+
+ _StackValue.withOffset(int value, ValueType type, BitWidth width)
+ : _offset = value,
+ _type = type,
+ _width = width;
BitWidth storedWidth({BitWidth width = BitWidth.width8}) {
- return ValueTypeUtils.isInline(_type) ? BitWidthUtil.max(_width, width) : _width;
+ return ValueTypeUtils.isInline(_type)
+ ? BitWidthUtil.max(_width, width)
+ : _width;
}
int storedPackedType({BitWidth width = BitWidth.width8}) {
@@ -555,16 +559,19 @@
BitWidth elementWidth(int size, int index) {
if (ValueTypeUtils.isInline(_type)) return _width;
- for(var i = 0; i < 4; i++) {
+ final offset = _offset!;
+ for (var i = 0; i < 4; i++) {
final width = 1 << i;
- final offsetLoc = size + BitWidthUtil.paddingSize(size, width) + index * width;
- final offset = offsetLoc - _offset;
- final bitWidth = BitWidthUtil.uwidth(offset);
+ final bitWidth = BitWidthUtil.uwidth(size +
+ BitWidthUtil.paddingSize(size, width) +
+ index * width -
+ offset);
if (1 << bitWidth.index == width) {
return bitWidth;
}
}
- throw StateError('Element is of unknown. Size: $size at index: $index. This might be a bug. Please create an issue https://github.com/google/flatbuffers/issues/new');
+ throw StateError(
+ 'Element is of unknown. Size: $size at index: $index. This might be a bug. Please create an issue https://github.com/google/flatbuffers/issues/new');
}
List<int> asU8List(BitWidth width) {
@@ -572,30 +579,30 @@
if (_type == ValueType.Float) {
if (width == BitWidth.width32) {
final result = ByteData(4);
- result.setFloat32(0, _value, Endian.little);
+ result.setFloat32(0, _value as double, Endian.little);
return result.buffer.asUint8List();
} else {
final result = ByteData(8);
- result.setFloat64(0, _value, Endian.little);
+ result.setFloat64(0, _value as double, Endian.little);
return result.buffer.asUint8List();
}
} else {
- switch(width) {
+ switch (width) {
case BitWidth.width8:
final result = ByteData(1);
- result.setInt8(0, _value);
+ result.setInt8(0, _value as int);
return result.buffer.asUint8List();
case BitWidth.width16:
final result = ByteData(2);
- result.setInt16(0, _value, Endian.little);
+ result.setInt16(0, _value as int, Endian.little);
return result.buffer.asUint8List();
case BitWidth.width32:
final result = ByteData(4);
- result.setInt32(0, _value, Endian.little);
+ result.setInt32(0, _value as int, Endian.little);
return result.buffer.asUint8List();
case BitWidth.width64:
final result = ByteData(8);
- result.setInt64(0, _value, Endian.little);
+ result.setInt64(0, _value as int, Endian.little);
return result.buffer.asUint8List();
}
}
@@ -607,11 +614,12 @@
}
if (_type == ValueType.Bool) {
final result = ByteData(1);
- result.setInt8(0, _value ? 1 : 0);
+ result.setInt8(0, _value as bool ? 1 : 0);
return result.buffer.asUint8List();
}
- throw StateError('Unexpected type: $_type. This might be a bug. Please create an issue https://github.com/google/flatbuffers/issues/new');
+ throw StateError(
+ 'Unexpected type: $_type. This might be a bug. Please create an issue https://github.com/google/flatbuffers/issues/new');
}
ValueType get type {
@@ -625,7 +633,8 @@
bool get isOffset {
return !ValueTypeUtils.isInline(_type);
}
- int get offset => _offset;
+
+ int? get offset => _offset;
bool get isFloat32 {
return _type == ValueType.Float && _width == BitWidth.width32;
@@ -635,6 +644,7 @@
class _StackPointer {
int stackPosition;
bool isVector;
+
_StackPointer(this.stackPosition, this.isVector);
}
diff --git a/dart/lib/src/reference.dart b/dart/lib/src/reference.dart
index 3954f06..e52d0b7 100644
--- a/dart/lib/src/reference.dart
+++ b/dart/lib/src/reference.dart
@@ -11,14 +11,15 @@
final int _offset;
final BitWidth _parentWidth;
final String _path;
- int _byteWidth;
- ValueType _valueType;
- int _length;
+ final int _byteWidth;
+ final ValueType _valueType;
+ int? _length;
- Reference._(this._buffer, this._offset, this._parentWidth, int packedType, this._path) {
- _byteWidth = 1 << (packedType & 3);
- _valueType = ValueTypeUtils.fromInt(packedType >> 2);
- }
+ Reference._(
+ this._buffer, this._offset, this._parentWidth, int packedType, this._path,
+ [int? byteWidth, ValueType? valueType])
+ : _byteWidth = byteWidth ?? 1 << (packedType & 3),
+ _valueType = valueType ?? ValueTypeUtils.fromInt(packedType >> 2);
/// Use this method to access the root value of a FlexBuffer.
static Reference fromBuffer(ByteBuffer buffer) {
@@ -30,31 +31,44 @@
final byteWidth = byteData.getUint8(len - 1);
final packedType = byteData.getUint8(len - 2);
final offset = len - byteWidth - 2;
- return Reference._(ByteData.view(buffer), offset, BitWidthUtil.fromByteWidth(byteWidth), packedType, "/");
+ return Reference._(ByteData.view(buffer), offset,
+ BitWidthUtil.fromByteWidth(byteWidth), packedType, "/");
}
/// Returns true if the underlying value is null.
bool get isNull => _valueType == ValueType.Null;
+
/// Returns true if the underlying value can be represented as [num].
- bool get isNum => ValueTypeUtils.isNumber(_valueType) || ValueTypeUtils.isIndirectNumber(_valueType);
+ bool get isNum =>
+ ValueTypeUtils.isNumber(_valueType) ||
+ ValueTypeUtils.isIndirectNumber(_valueType);
+
/// Returns true if the underlying value was encoded as a float (direct or indirect).
- bool get isDouble => _valueType == ValueType.Float || _valueType == ValueType.IndirectFloat;
+ bool get isDouble =>
+ _valueType == ValueType.Float || _valueType == ValueType.IndirectFloat;
+
/// Returns true if the underlying value was encoded as an int or uint (direct or indirect).
bool get isInt => isNum && !isDouble;
+
/// Returns true if the underlying value was encoded as a string or a key.
- bool get isString => _valueType == ValueType.String || _valueType == ValueType.Key;
+ bool get isString =>
+ _valueType == ValueType.String || _valueType == ValueType.Key;
+
/// Returns true if the underlying value was encoded as a bool.
bool get isBool => _valueType == ValueType.Bool;
+
/// Returns true if the underlying value was encoded as a blob.
bool get isBlob => _valueType == ValueType.Blob;
+
/// Returns true if the underlying value points to a vector.
bool get isVector => ValueTypeUtils.isAVector(_valueType);
+
/// Returns true if the underlying value points to a map.
bool get isMap => _valueType == ValueType.Map;
/// If this [isBool], returns the bool value. Otherwise, returns null.
- bool get boolValue {
- if(_valueType == ValueType.Bool) {
+ bool? get boolValue {
+ if (_valueType == ValueType.Bool) {
return _readInt(_offset, _parentWidth) != 0;
}
return null;
@@ -63,7 +77,7 @@
/// Returns an [int], if the underlying value can be represented as an int.
///
/// Otherwise returns [null].
- int get intValue {
+ int? get intValue {
if (_valueType == ValueType.Int) {
return _readInt(_offset, _parentWidth);
}
@@ -82,7 +96,7 @@
/// Returns [double], if the underlying value [isDouble].
///
/// Otherwise returns [null].
- double get doubleValue {
+ double? get doubleValue {
if (_valueType == ValueType.Float) {
return _readFloat(_offset, _parentWidth);
}
@@ -95,12 +109,12 @@
/// Returns [num], if the underlying value is numeric, be it int uint, or float (direct or indirect).
///
/// Otherwise returns [null].
- num get numValue => doubleValue ?? intValue;
+ num? get numValue => doubleValue ?? intValue;
/// Returns [String] value or null otherwise.
- ///
- /// This method performers a utf8 decoding, as FlexBuffers format stores strings in utf8 encoding.
- String get stringValue {
+ ///
+ /// This method performers a utf8 decoding, as FlexBuffers format stores strings in utf8 encoding.
+ String? get stringValue {
if (_valueType == ValueType.String || _valueType == ValueType.Key) {
return utf8.decode(_buffer.buffer.asUint8List(_indirect, length));
}
@@ -108,7 +122,7 @@
}
/// Returns [Uint8List] value or null otherwise.
- Uint8List get blobValue {
+ Uint8List? get blobValue {
if (_valueType == ValueType.Blob) {
return _buffer.buffer.asUint8List(_indirect, length);
}
@@ -122,22 +136,31 @@
Reference operator [](Object key) {
if (key is int && ValueTypeUtils.isAVector(_valueType)) {
final index = key;
- if(index >= length || index < 0) {
- throw ArgumentError('Key: [$key] is not applicable on: $_path of: $_valueType length: $length');
+ if (index >= length || index < 0) {
+ throw ArgumentError(
+ 'Key: [$key] is not applicable on: $_path of: $_valueType length: $length');
}
final elementOffset = _indirect + index * _byteWidth;
- final reference = Reference._(_buffer, elementOffset, BitWidthUtil.fromByteWidth(_byteWidth), 0, "$_path[$index]");
- reference._byteWidth = 1;
+ int packedType = 0;
+ int? byteWidth;
+ ValueType? valueType;
if (ValueTypeUtils.isTypedVector(_valueType)) {
- reference._valueType = ValueTypeUtils.typedVectorElementType(_valueType);
- return reference;
+ byteWidth = 1;
+ valueType = ValueTypeUtils.typedVectorElementType(_valueType);
+ } else if (ValueTypeUtils.isFixedTypedVector(_valueType)) {
+ byteWidth = 1;
+ valueType = ValueTypeUtils.fixedTypedVectorElementType(_valueType);
+ } else {
+ packedType = _buffer.getUint8(_indirect + length * _byteWidth + index);
}
- if(ValueTypeUtils.isFixedTypedVector(_valueType)) {
- reference._valueType = ValueTypeUtils.fixedTypedVectorElementType(_valueType);
- return reference;
- }
- final packedType = _buffer.getUint8(_indirect + length * _byteWidth + index);
- return Reference._(_buffer, elementOffset, BitWidthUtil.fromByteWidth(_byteWidth), packedType, "$_path[$index]");
+ return Reference._(
+ _buffer,
+ elementOffset,
+ BitWidthUtil.fromByteWidth(_byteWidth),
+ packedType,
+ "$_path[$index]",
+ byteWidth,
+ valueType);
}
if (key is String && _valueType == ValueType.Map) {
final index = _keyIndex(key);
@@ -145,13 +168,14 @@
return _valueForIndexWithKey(index, key);
}
}
- throw ArgumentError('Key: [$key] is not applicable on: $_path of: $_valueType');
+ throw ArgumentError(
+ 'Key: [$key] is not applicable on: $_path of: $_valueType');
}
/// Get an iterable if the underlying flexBuffer value is a vector.
/// Otherwise throws an exception.
Iterable<Reference> get vectorIterable {
- if(isVector == false) {
+ if (isVector == false) {
throw UnsupportedError('Value is not a vector. It is: $_valueType');
}
return _VectorIterator(this);
@@ -160,7 +184,7 @@
/// Get an iterable for keys if the underlying flexBuffer value is a map.
/// Otherwise throws an exception.
Iterable<String> get mapKeyIterable {
- if(isMap == false) {
+ if (isMap == false) {
throw UnsupportedError('Value is not a map. It is: $_valueType');
}
return _MapKeyIterator(this);
@@ -169,7 +193,7 @@
/// Get an iterable for values if the underlying flexBuffer value is a map.
/// Otherwise throws an exception.
Iterable<Reference> get mapValueIterable {
- if(isMap == false) {
+ if (isMap == false) {
throw UnsupportedError('Value is not a map. It is: $_valueType');
}
return _MapValueIterator(this);
@@ -181,59 +205,62 @@
/// If the underlying value is a vector, or map, the length reflects number of elements / element pairs.
/// If the values is a string or a blob, the length reflects a number of bytes the value occupies (strings are encoded in utf8 format).
int get length {
- if (_length != null) {
- return _length;
- }
- // needs to be checked before more generic isAVector
- if(ValueTypeUtils.isFixedTypedVector(_valueType)) {
- _length = ValueTypeUtils.fixedTypedVectorElementSize(_valueType);
- } else if(_valueType == ValueType.Blob || ValueTypeUtils.isAVector(_valueType) || _valueType == ValueType.Map){
- _length = _readUInt(_indirect - _byteWidth, BitWidthUtil.fromByteWidth(_byteWidth));
- } else if (_valueType == ValueType.Null) {
- _length = 0;
- } else if (_valueType == ValueType.String) {
- final indirect = _indirect;
- var size_byte_width = _byteWidth;
- var size = _readUInt(indirect - size_byte_width, BitWidthUtil.fromByteWidth(size_byte_width));
- while (_buffer.getInt8(indirect + size) != 0) {
- size_byte_width <<= 1;
- size = _readUInt(indirect - size_byte_width, BitWidthUtil.fromByteWidth(size_byte_width));
+ if (_length == null) {
+ // needs to be checked before more generic isAVector
+ if (ValueTypeUtils.isFixedTypedVector(_valueType)) {
+ _length = ValueTypeUtils.fixedTypedVectorElementSize(_valueType);
+ } else if (_valueType == ValueType.Blob ||
+ ValueTypeUtils.isAVector(_valueType) ||
+ _valueType == ValueType.Map) {
+ _length = _readUInt(
+ _indirect - _byteWidth, BitWidthUtil.fromByteWidth(_byteWidth));
+ } else if (_valueType == ValueType.Null) {
+ _length = 0;
+ } else if (_valueType == ValueType.String) {
+ final indirect = _indirect;
+ var sizeByteWidth = _byteWidth;
+ var size = _readUInt(indirect - sizeByteWidth,
+ BitWidthUtil.fromByteWidth(sizeByteWidth));
+ while (_buffer.getInt8(indirect + size) != 0) {
+ sizeByteWidth <<= 1;
+ size = _readUInt(indirect - sizeByteWidth,
+ BitWidthUtil.fromByteWidth(sizeByteWidth));
+ }
+ _length = size;
+ } else if (_valueType == ValueType.Key) {
+ final indirect = _indirect;
+ var size = 1;
+ while (_buffer.getInt8(indirect + size) != 0) {
+ size += 1;
+ }
+ _length = size;
+ } else {
+ _length = 1;
}
- _length = size;
- } else if (_valueType == ValueType.Key) {
- final indirect = _indirect;
- var size = 1;
- while (_buffer.getInt8(indirect + size) != 0) {
- size += 1;
- }
- _length = size;
- } else {
- _length = 1;
}
- return _length;
+ return _length!;
}
-
/// Returns a minified JSON representation of the underlying FlexBuffer value.
///
/// This method involves materializing the entire object tree, which may be
/// expensive. It is more efficient to work with [Reference] and access only the needed data.
/// Blob values are represented as base64 encoded string.
String get json {
- if(_valueType == ValueType.Bool) {
- return boolValue ? 'true' : 'false';
+ if (_valueType == ValueType.Bool) {
+ return boolValue! ? 'true' : 'false';
}
if (_valueType == ValueType.Null) {
return 'null';
}
- if(ValueTypeUtils.isNumber(_valueType)) {
+ if (ValueTypeUtils.isNumber(_valueType)) {
return jsonEncode(numValue);
}
if (_valueType == ValueType.String) {
return jsonEncode(stringValue);
}
if (_valueType == ValueType.Blob) {
- return jsonEncode(base64Encode(blobValue));
+ return jsonEncode(base64Encode(blobValue!));
}
if (ValueTypeUtils.isAVector(_valueType)) {
final result = StringBuffer();
@@ -261,7 +288,8 @@
result.write('}');
return result.toString();
}
- throw UnsupportedError('Type: $_valueType is not supported for JSON conversion');
+ throw UnsupportedError(
+ 'Type: $_valueType is not supported for JSON conversion');
}
/// Computes the indirect offset of the value.
@@ -316,16 +344,20 @@
}
void _validateOffset(int offset, BitWidth width) {
- if (_offset < 0 || _buffer.lengthInBytes <= offset + width.index || offset & (BitWidthUtil.toByteWidth(width) - 1) != 0) {
+ if (_offset < 0 ||
+ _buffer.lengthInBytes <= offset + width.index ||
+ offset & (BitWidthUtil.toByteWidth(width) - 1) != 0) {
throw StateError('Bad offset: $offset, width: $width');
}
}
- int _keyIndex(String key) {
+ int? _keyIndex(String key) {
final input = utf8.encode(key);
final keysVectorOffset = _indirect - _byteWidth * 3;
- final indirectOffset = keysVectorOffset - _readUInt(keysVectorOffset, BitWidthUtil.fromByteWidth(_byteWidth));
- final byteWidth = _readUInt(keysVectorOffset + _byteWidth, BitWidthUtil.fromByteWidth(_byteWidth));
+ final indirectOffset = keysVectorOffset -
+ _readUInt(keysVectorOffset, BitWidthUtil.fromByteWidth(_byteWidth));
+ final byteWidth = _readUInt(
+ keysVectorOffset + _byteWidth, BitWidthUtil.fromByteWidth(_byteWidth));
var low = 0;
var high = length - 1;
while (low <= high) {
@@ -341,9 +373,10 @@
return null;
}
- int _diffKeys(List<int> input, int index, int indirect_offset, int byteWidth) {
- final keyOffset = indirect_offset + index * byteWidth;
- final keyIndirectOffset = keyOffset - _readUInt(keyOffset, BitWidthUtil.fromByteWidth(byteWidth));
+ int _diffKeys(List<int> input, int index, int indirectOffset, int byteWidth) {
+ final keyOffset = indirectOffset + index * byteWidth;
+ final keyIndirectOffset =
+ keyOffset - _readUInt(keyOffset, BitWidthUtil.fromByteWidth(byteWidth));
for (var i = 0; i < input.length; i++) {
final dif = input[i] - _buffer.getUint8(keyIndirectOffset + i);
if (dif != 0) {
@@ -357,38 +390,42 @@
final indirect = _indirect;
final elementOffset = indirect + index * _byteWidth;
final packedType = _buffer.getUint8(indirect + length * _byteWidth + index);
- return Reference._(_buffer, elementOffset, BitWidthUtil.fromByteWidth(_byteWidth), packedType, "$_path/$key");
+ return Reference._(_buffer, elementOffset,
+ BitWidthUtil.fromByteWidth(_byteWidth), packedType, "$_path/$key");
}
Reference _valueForIndex(int index) {
final indirect = _indirect;
final elementOffset = indirect + index * _byteWidth;
final packedType = _buffer.getUint8(indirect + length * _byteWidth + index);
- return Reference._(_buffer, elementOffset, BitWidthUtil.fromByteWidth(_byteWidth), packedType, "$_path/[$index]");
+ return Reference._(_buffer, elementOffset,
+ BitWidthUtil.fromByteWidth(_byteWidth), packedType, "$_path/[$index]");
}
String _keyForIndex(int index) {
final keysVectorOffset = _indirect - _byteWidth * 3;
- final indirectOffset = keysVectorOffset - _readUInt(keysVectorOffset, BitWidthUtil.fromByteWidth(_byteWidth));
- final byteWidth = _readUInt(keysVectorOffset + _byteWidth, BitWidthUtil.fromByteWidth(_byteWidth));
+ final indirectOffset = keysVectorOffset -
+ _readUInt(keysVectorOffset, BitWidthUtil.fromByteWidth(_byteWidth));
+ final byteWidth = _readUInt(
+ keysVectorOffset + _byteWidth, BitWidthUtil.fromByteWidth(_byteWidth));
final keyOffset = indirectOffset + index * byteWidth;
- final keyIndirectOffset = keyOffset - _readUInt(keyOffset, BitWidthUtil.fromByteWidth(byteWidth));
+ final keyIndirectOffset =
+ keyOffset - _readUInt(keyOffset, BitWidthUtil.fromByteWidth(byteWidth));
var length = 0;
while (_buffer.getUint8(keyIndirectOffset + length) != 0) {
length += 1;
}
return utf8.decode(_buffer.buffer.asUint8List(keyIndirectOffset, length));
}
-
}
-class _VectorIterator with IterableMixin<Reference> implements Iterator<Reference> {
+class _VectorIterator
+ with IterableMixin<Reference>
+ implements Iterator<Reference> {
final Reference _vector;
- int index;
+ int index = -1;
- _VectorIterator(this._vector) {
- index = -1;
- }
+ _VectorIterator(this._vector);
@override
Reference get current => _vector[index];
@@ -405,11 +442,9 @@
class _MapKeyIterator with IterableMixin<String> implements Iterator<String> {
final Reference _map;
- int index;
+ int index = -1;
- _MapKeyIterator(this._map) {
- index = -1;
- }
+ _MapKeyIterator(this._map);
@override
String get current => _map._keyForIndex(index);
@@ -424,13 +459,13 @@
Iterator<String> get iterator => this;
}
-class _MapValueIterator with IterableMixin<Reference> implements Iterator<Reference> {
+class _MapValueIterator
+ with IterableMixin<Reference>
+ implements Iterator<Reference> {
final Reference _map;
- int index;
+ int index = -1;
- _MapValueIterator(this._map) {
- index = -1;
- }
+ _MapValueIterator(this._map);
@override
Reference get current => _map._valueForIndex(index);
diff --git a/dart/lib/src/types.dart b/dart/lib/src/types.dart
index 8aed272..f9eefd8 100644
--- a/dart/lib/src/types.dart
+++ b/dart/lib/src/types.dart
@@ -1,17 +1,13 @@
import 'dart:typed_data';
/// Represents the number of bits a value occupies.
-enum BitWidth {
- width8,
- width16,
- width32,
- width64
-}
+enum BitWidth { width8, width16, width32, width64 }
class BitWidthUtil {
static int toByteWidth(BitWidth self) {
return 1 << self.index;
}
+
static BitWidth width(num value) {
if (value.toInt() == value) {
var v = value.toInt().abs();
@@ -20,8 +16,11 @@
if (v >> 31 == 0) return BitWidth.width32;
return BitWidth.width64;
}
- return value == _toF32(value) ? BitWidth.width32 : BitWidth.width64;
+ return value == _toF32(value as double)
+ ? BitWidth.width32
+ : BitWidth.width64;
}
+
static BitWidth uwidth(num value) {
if (value.toInt() == value) {
var v = value.toInt().abs();
@@ -30,8 +29,11 @@
if (v >> 32 == 0) return BitWidth.width32;
return BitWidth.width64;
}
- return value == _toF32(value) ? BitWidth.width32 : BitWidth.width64;
+ return value == _toF32(value as double)
+ ? BitWidth.width32
+ : BitWidth.width64;
}
+
static BitWidth fromByteWidth(int value) {
if (value == 1) {
return BitWidth.width8;
@@ -45,11 +47,13 @@
if (value == 8) {
return BitWidth.width64;
}
- throw Exception('Unexpected value ${value}');
+ throw Exception('Unexpected value $value');
}
+
static int paddingSize(int bufSize, int scalarSize) {
return (~bufSize + 1) & (scalarSize - 1);
}
+
static double _toF32(double value) {
var bdata = ByteData(4);
bdata.setFloat32(0, value);
@@ -66,15 +70,36 @@
/// Represents all internal FlexBuffer types.
enum ValueType {
- Null, Int, UInt, Float,
- Key, String, IndirectInt, IndirectUInt, IndirectFloat,
- Map, Vector, VectorInt, VectorUInt, VectorFloat, VectorKey,
- @Deprecated('VectorString is deprecated due to a flaw in the binary format (https://github.com/google/flatbuffers/issues/5627)')
+ Null,
+ Int,
+ UInt,
+ Float,
+ Key,
+ String,
+ IndirectInt,
+ IndirectUInt,
+ IndirectFloat,
+ Map,
+ Vector,
+ VectorInt,
+ VectorUInt,
+ VectorFloat,
+ VectorKey,
+ @Deprecated(
+ 'VectorString is deprecated due to a flaw in the binary format (https://github.com/google/flatbuffers/issues/5627)')
VectorString,
- VectorInt2, VectorUInt2, VectorFloat2,
- VectorInt3, VectorUInt3, VectorFloat3,
- VectorInt4, VectorUInt4, VectorFloat4,
- Blob, Bool, VectorBool
+ VectorInt2,
+ VectorUInt2,
+ VectorFloat2,
+ VectorInt3,
+ VectorUInt3,
+ VectorFloat3,
+ VectorInt4,
+ VectorUInt4,
+ VectorFloat4,
+ Blob,
+ Bool,
+ VectorBool
}
class ValueTypeUtils {
@@ -89,71 +114,70 @@
}
static bool isInline(ValueType self) {
- return self == ValueType.Bool
- || toInt(self) <= toInt(ValueType.Float);
+ return self == ValueType.Bool || toInt(self) <= toInt(ValueType.Float);
}
static bool isNumber(ValueType self) {
- return toInt(self) >= toInt(ValueType.Int)
- && toInt(self) <= toInt(ValueType.Float);
+ return toInt(self) >= toInt(ValueType.Int) &&
+ toInt(self) <= toInt(ValueType.Float);
}
static bool isIndirectNumber(ValueType self) {
- return toInt(self) >= toInt(ValueType.IndirectInt)
- && toInt(self) <= toInt(ValueType.IndirectFloat);
+ return toInt(self) >= toInt(ValueType.IndirectInt) &&
+ toInt(self) <= toInt(ValueType.IndirectFloat);
}
static bool isTypedVectorElement(ValueType self) {
return self == ValueType.Bool ||
- (
- toInt(self) >= toInt(ValueType.Int)
- && toInt(self) <= toInt(ValueType.String)
- );
+ (toInt(self) >= toInt(ValueType.Int) &&
+ toInt(self) <= toInt(ValueType.String));
}
static bool isTypedVector(ValueType self) {
return self == ValueType.VectorBool ||
- (
- toInt(self) >= toInt(ValueType.VectorInt)
- && toInt(self) <= toInt(ValueType.VectorString)
- );
+ (toInt(self) >= toInt(ValueType.VectorInt) &&
+ toInt(self) <= toInt(ValueType.VectorString));
}
static bool isFixedTypedVector(ValueType self) {
- return (
- toInt(self) >= toInt(ValueType.VectorInt2)
- && toInt(self) <= toInt(ValueType.VectorFloat4)
- );
+ return (toInt(self) >= toInt(ValueType.VectorInt2) &&
+ toInt(self) <= toInt(ValueType.VectorFloat4));
}
static bool isAVector(ValueType self) {
- return (
- isTypedVector(self) || isFixedTypedVector(self) || self == ValueType.Vector
- );
+ return (isTypedVector(self) ||
+ isFixedTypedVector(self) ||
+ self == ValueType.Vector);
}
static ValueType toTypedVector(ValueType self, int length) {
if (length == 0) {
- return ValueTypeUtils.fromInt(toInt(self) - toInt(ValueType.Int) + toInt(ValueType.VectorInt));
+ return ValueTypeUtils.fromInt(
+ toInt(self) - toInt(ValueType.Int) + toInt(ValueType.VectorInt));
}
if (length == 2) {
- return ValueTypeUtils.fromInt(toInt(self) - toInt(ValueType.Int) + toInt(ValueType.VectorInt2));
+ return ValueTypeUtils.fromInt(
+ toInt(self) - toInt(ValueType.Int) + toInt(ValueType.VectorInt2));
}
if (length == 3) {
- return ValueTypeUtils.fromInt(toInt(self) - toInt(ValueType.Int) + toInt(ValueType.VectorInt3));
+ return ValueTypeUtils.fromInt(
+ toInt(self) - toInt(ValueType.Int) + toInt(ValueType.VectorInt3));
}
if (length == 4) {
- return ValueTypeUtils.fromInt(toInt(self) - toInt(ValueType.Int) + toInt(ValueType.VectorInt4));
+ return ValueTypeUtils.fromInt(
+ toInt(self) - toInt(ValueType.Int) + toInt(ValueType.VectorInt4));
}
throw Exception('unexpected length ' + length.toString());
}
static ValueType typedVectorElementType(ValueType self) {
- return ValueTypeUtils.fromInt(toInt(self) - toInt(ValueType.VectorInt) + toInt(ValueType.Int));
+ return ValueTypeUtils.fromInt(
+ toInt(self) - toInt(ValueType.VectorInt) + toInt(ValueType.Int));
}
static ValueType fixedTypedVectorElementType(ValueType self) {
- return ValueTypeUtils.fromInt((toInt(self) - toInt(ValueType.VectorInt2)) % 3 + toInt(ValueType.Int));
+ return ValueTypeUtils.fromInt(
+ (toInt(self) - toInt(ValueType.VectorInt2)) % 3 + toInt(ValueType.Int));
}
static int fixedTypedVectorElementSize(ValueType self) {
diff --git a/dart/publish.sh b/dart/publish.sh
index 167a4a3..bda43ba 100755
--- a/dart/publish.sh
+++ b/dart/publish.sh
@@ -17,12 +17,20 @@
# Note to pub consumers: this file is used to assist with publishing the
# pub package from the flatbuffers repository and is not meant for general use.
# As pub does not currently provide a way to exclude files, it is included here.
+set -e
-command -v pub >/dev/null 2>&1 || { echo >&2 "Require `pub` but it's not installed. Aborting."; exit 1; }
+command -v dart >/dev/null 2>&1 || { echo >&2 "Require `dart` but it's not installed. Aborting."; exit 1; }
-cp ../samples/monster.fbs example/
-cp ../tests/monster_test.fbs test/
-pub publish
+pushd ../tests
+./DartTest.sh
+popd
+
+pushd ../samples
+./dart_sample.sh
+popd
+
+dart pub publish
rm example/monster.fbs
-rm test/monster_test.fbs
\ No newline at end of file
+rm test/*.fbs
+rm -rf test/sub
diff --git a/dart/pubspec.yaml b/dart/pubspec.yaml
index 78a7bf1..ae86570 100644
--- a/dart/pubspec.yaml
+++ b/dart/pubspec.yaml
@@ -1,20 +1,15 @@
name: flat_buffers
-version: 1.12.0
-description: >
- FlatBuffers reading and writing library for Dart. Use the flatc compiler to
- generate Dart classes for a FlatBuffers schema, and this library to assist with
- reading and writing the binary format.
-
- Based on original work by Konstantin Scheglov and Paul Berry of the Dart SDK team.
-authors:
-- Dan Field <dfield@gmail.com>
-- Konstantin Scheglov
-- Paul Berry
+version: 2.0.5
+description: FlatBuffers reading and writing library for Dart. Based on original work by Konstantin Scheglov and Paul Berry of the Dart SDK team.
homepage: https://github.com/google/flatbuffers
documentation: https://google.github.io/flatbuffers/index.html
-dev_dependencies:
- test: ^1.3.0
- test_reflective_loader: ^0.1.4
- path: ^1.5.1
+
environment:
- sdk: '>=2.0.0-dev.28.0 <3.0.0'
\ No newline at end of file
+ sdk: '>=2.12.0 <3.0.0'
+
+dev_dependencies:
+ test: ^1.17.7
+ test_reflective_loader: ^0.2.0
+ path: ^1.8.0
+ lints: ^1.0.1
+
diff --git a/dart/test/flat_buffers_test.dart b/dart/test/flat_buffers_test.dart
index be500f2..8cee6b2 100644
--- a/dart/test/flat_buffers_test.dart
+++ b/dart/test/flat_buffers_test.dart
@@ -12,10 +12,12 @@
import 'package:test_reflective_loader/test_reflective_loader.dart';
import './monster_test_my_game.example_generated.dart' as example;
+import './monster_test_my_game.example2_generated.dart' as example2;
main() {
defineReflectiveSuite(() {
defineReflectiveTests(BuilderTest);
+ defineReflectiveTests(ObjectAPITest);
defineReflectiveTests(CheckOtherLangaugesData);
defineReflectiveTests(GeneratorTest);
});
@@ -28,34 +30,35 @@
@reflectiveTest
class CheckOtherLangaugesData {
test_cppData() async {
- List<int> data = await new io.File(path.join(
- path.dirname(io.Platform.script.path),
+ List<int> data = await io.File(path.join(
+ path.context.current,
+ 'test',
'monsterdata_test.mon',
)).readAsBytes();
- example.Monster mon = new example.Monster(data);
+ example.Monster mon = example.Monster(data);
expect(mon.hp, 80);
expect(mon.mana, 150);
expect(mon.name, 'MyMonster');
- expect(mon.pos.x, 1.0);
- expect(mon.pos.y, 2.0);
- expect(mon.pos.z, 3.0);
- expect(mon.pos.test1, 3.0);
- expect(mon.pos.test2.value, 2.0);
- expect(mon.pos.test3.a, 5);
- expect(mon.pos.test3.b, 6);
- expect(mon.testType.value, example.AnyTypeId.Monster.value);
+ expect(mon.pos!.x, 1.0);
+ expect(mon.pos!.y, 2.0);
+ expect(mon.pos!.z, 3.0);
+ expect(mon.pos!.test1, 3.0);
+ expect(mon.pos!.test2.value, 2.0);
+ expect(mon.pos!.test3.a, 5);
+ expect(mon.pos!.test3.b, 6);
+ expect(mon.testType!.value, example.AnyTypeId.Monster.value);
expect(mon.test is example.Monster, true);
final monster2 = mon.test as example.Monster;
expect(monster2.name, "Fred");
- expect(mon.inventory.length, 5);
- expect(mon.inventory.reduce((cur, next) => cur + next), 10);
- expect(mon.test4.length, 2);
- expect(
- mon.test4[0].a + mon.test4[0].b + mon.test4[1].a + mon.test4[1].b, 100);
- expect(mon.testarrayofstring.length, 2);
- expect(mon.testarrayofstring[0], "test1");
- expect(mon.testarrayofstring[1], "test2");
+ expect(mon.inventory!.length, 5);
+ expect(mon.inventory!.reduce((cur, next) => cur + next), 10);
+ final test4 = mon.test4!;
+ expect(test4.length, 2);
+ expect(test4[0].a + test4[0].b + test4[1].a + test4[1].b, 100);
+ expect(mon.testarrayofstring!.length, 2);
+ expect(mon.testarrayofstring![0], "test1");
+ expect(mon.testarrayofstring![1], "test2");
// this will fail if accessing any field fails.
expect(
@@ -65,7 +68,7 @@
'mana: 150, hp: 80, name: MyMonster, inventory: [0, 1, 2, 3, 4], '
'color: Color{value: 8}, testType: AnyTypeId{value: 1}, '
'test: Monster{pos: null, mana: 150, hp: 100, name: Fred, '
- 'inventory: null, color: Color{value: 8}, testType: AnyTypeId{value: 0}, '
+ 'inventory: null, color: Color{value: 8}, testType: null, '
'test: null, test4: null, testarrayofstring: null, '
'testarrayoftables: null, enemy: null, testnestedflatbuffer: null, '
'testempty: null, testbool: false, testhashs32Fnv1: 0, '
@@ -79,13 +82,16 @@
'vectorOfWeakReferences: null, vectorOfStrongReferrables: null, '
'coOwningReference: 0, vectorOfCoOwningReferences: null, '
'nonOwningReference: 0, vectorOfNonOwningReferences: null, '
- 'anyUniqueType: AnyUniqueAliasesTypeId{value: 0}, anyUnique: null, '
- 'anyAmbiguousType: AnyAmbiguousAliasesTypeId{value: 0}, '
- 'anyAmbiguous: null, vectorOfEnums: null, signedEnum: Race{value: -1}}, '
+ 'anyUniqueType: null, anyUnique: null, anyAmbiguousType: null, '
+ 'anyAmbiguous: null, vectorOfEnums: null, signedEnum: Race{value: -1}, '
+ 'testrequirednestedflatbuffer: null, scalarKeySortedTables: null, '
+ 'nativeInline: null, '
+ 'longEnumNonEnumDefault: LongEnum{value: 0}, '
+ 'longEnumNormalDefault: LongEnum{value: 2}}, '
'test4: [Test{a: 10, b: 20}, Test{a: 30, b: 40}], '
'testarrayofstring: [test1, test2], testarrayoftables: null, '
'enemy: Monster{pos: null, mana: 150, hp: 100, name: Fred, '
- 'inventory: null, color: Color{value: 8}, testType: AnyTypeId{value: 0}, '
+ 'inventory: null, color: Color{value: 8}, testType: null, '
'test: null, test4: null, testarrayofstring: null, '
'testarrayoftables: null, enemy: null, testnestedflatbuffer: null, '
'testempty: null, testbool: false, testhashs32Fnv1: 0, '
@@ -99,9 +105,12 @@
'vectorOfWeakReferences: null, vectorOfStrongReferrables: null, '
'coOwningReference: 0, vectorOfCoOwningReferences: null, '
'nonOwningReference: 0, vectorOfNonOwningReferences: null, '
- 'anyUniqueType: AnyUniqueAliasesTypeId{value: 0}, anyUnique: null, '
- 'anyAmbiguousType: AnyAmbiguousAliasesTypeId{value: 0}, '
- 'anyAmbiguous: null, vectorOfEnums: null, signedEnum: Race{value: -1}}, '
+ 'anyUniqueType: null, anyUnique: null, anyAmbiguousType: null, '
+ 'anyAmbiguous: null, vectorOfEnums: null, signedEnum: Race{value: -1}, '
+ 'testrequirednestedflatbuffer: null, scalarKeySortedTables: null, '
+ 'nativeInline: null, '
+ 'longEnumNonEnumDefault: LongEnum{value: 0}, '
+ 'longEnumNormalDefault: LongEnum{value: 2}}, '
'testnestedflatbuffer: null, testempty: null, testbool: true, '
'testhashs32Fnv1: -579221183, testhashu32Fnv1: 3715746113, '
'testhashs64Fnv1: 7930699090847568257, '
@@ -110,7 +119,9 @@
'testhashs64Fnv1a: 4898026182817603057, '
'testhashu64Fnv1a: 4898026182817603057, '
'testarrayofbools: [true, false, true], testf: 3.14159, testf2: 3.0, '
- 'testf3: 0.0, testarrayofstring2: null, testarrayofsortedstruct: null, '
+ 'testf3: 0.0, testarrayofstring2: null, testarrayofsortedstruct: ['
+ 'Ability{id: 0, distance: 45}, Ability{id: 1, distance: 21}, '
+ 'Ability{id: 5, distance: 12}], '
'flex: null, test5: [Test{a: 10, b: 20}, Test{a: 30, b: 40}], '
'vectorOfLongs: [1, 100, 10000, 1000000, 100000000], '
'vectorOfDoubles: [-1.7976931348623157e+308, 0.0, 1.7976931348623157e+308], '
@@ -119,21 +130,46 @@
'vectorOfStrongReferrables: null, coOwningReference: 0, '
'vectorOfCoOwningReferences: null, nonOwningReference: 0, '
'vectorOfNonOwningReferences: null, '
- 'anyUniqueType: AnyUniqueAliasesTypeId{value: 0}, anyUnique: null, '
- 'anyAmbiguousType: AnyAmbiguousAliasesTypeId{value: 0}, '
- 'anyAmbiguous: null, vectorOfEnums: null, signedEnum: Race{value: -1}}',
+ 'anyUniqueType: null, anyUnique: null, '
+ 'anyAmbiguousType: null, '
+ 'anyAmbiguous: null, vectorOfEnums: null, signedEnum: Race{value: -1}, '
+ 'testrequirednestedflatbuffer: null, scalarKeySortedTables: [Stat{id: '
+ 'miss, val: 0, count: 0}, Stat{id: hit, val: 10, count: 1}], '
+ 'nativeInline: Test{a: 1, b: 2}, '
+ 'longEnumNonEnumDefault: LongEnum{value: 0}, '
+ 'longEnumNormalDefault: LongEnum{value: 2}}',
);
}
}
+/// Test a custom, fixed-memory allocator (no actual allocations performed)
+class CustomAllocator extends Allocator {
+ final _memory = ByteData(10 * 1024);
+ int _used = 0;
+
+ Uint8List buffer(int size) => _memory.buffer.asUint8List(_used - size, size);
+
+ @override
+ ByteData allocate(int size) {
+ if (size > _memory.lengthInBytes) {
+ throw UnsupportedError('Trying to allocate too much');
+ }
+ _used = size;
+ return ByteData.sublistView(_memory, 0, size);
+ }
+
+ @override
+ void deallocate(ByteData _) {}
+}
+
@reflectiveTest
class BuilderTest {
- void test_monsterBuilder() {
- final fbBuilder = new Builder();
+ void test_monsterBuilder([Builder? builder]) {
+ final fbBuilder = builder ?? Builder();
final str = fbBuilder.writeString('MyMonster');
fbBuilder.writeString('test1');
- fbBuilder.writeString('test2');
+ fbBuilder.writeString('test2', asciiOptimization: true);
final testArrayOfString = fbBuilder.endStructVector(2);
final fred = fbBuilder.writeString('Fred');
@@ -141,12 +177,12 @@
final List<int> treasure = [0, 1, 2, 3, 4];
final inventory = fbBuilder.writeListUint8(treasure);
- final monBuilder = new example.MonsterBuilder(fbBuilder)
+ final monBuilder = example.MonsterBuilder(fbBuilder)
..begin()
..addNameOffset(fred);
final mon2 = monBuilder.finish();
- final testBuilder = new example.TestBuilder(fbBuilder);
+ final testBuilder = example.TestBuilder(fbBuilder);
testBuilder.finish(10, 20);
testBuilder.finish(30, 40);
final test4 = fbBuilder.endStructVector(2);
@@ -154,7 +190,7 @@
monBuilder
..begin()
..addPos(
- new example.Vec3Builder(fbBuilder).finish(
+ example.Vec3Builder(fbBuilder).finish(
1.0,
2.0,
3.0,
@@ -174,50 +210,51 @@
fbBuilder.finish(mon);
}
- void test_error_addInt32_withoutStartTable() {
- Builder builder = new Builder();
+ void test_error_addInt32_withoutStartTable([Builder? builder]) {
+ builder ??= Builder();
expect(() {
- builder.addInt32(0, 0);
- }, throwsStateError);
+ builder!.addInt32(0, 0);
+ }, throwsA(isA<AssertionError>()));
}
void test_error_addOffset_withoutStartTable() {
- Builder builder = new Builder();
+ Builder builder = Builder();
expect(() {
builder.addOffset(0, 0);
- }, throwsStateError);
+ }, throwsA(isA<AssertionError>()));
}
void test_error_endTable_withoutStartTable() {
- Builder builder = new Builder();
+ Builder builder = Builder();
expect(() {
builder.endTable();
- }, throwsStateError);
+ }, throwsA(isA<AssertionError>()));
}
void test_error_startTable_duringTable() {
- Builder builder = new Builder();
- builder.startTable();
+ Builder builder = Builder();
+ builder.startTable(0);
expect(() {
- builder.startTable();
- }, throwsStateError);
+ builder.startTable(0);
+ }, throwsA(isA<AssertionError>()));
}
void test_error_writeString_duringTable() {
- Builder builder = new Builder();
- builder.startTable();
+ Builder builder = Builder();
+ builder.startTable(1);
expect(() {
builder.writeString('12345');
- }, throwsStateError);
+ }, throwsA(isA<AssertionError>()));
}
void test_file_identifier() {
Uint8List byteList;
{
- Builder builder = new Builder(initialSize: 0);
- builder.startTable();
+ Builder builder = Builder(initialSize: 0);
+ builder.startTable(0);
int offset = builder.endTable();
- byteList = builder.finish(offset, 'Az~ÿ');
+ builder.finish(offset, 'Az~ÿ');
+ byteList = builder.buffer;
}
// Convert byteList to a ByteData so that we can read data from it.
ByteData byteData = byteList.buffer.asByteData(byteList.offsetInBytes);
@@ -240,31 +277,46 @@
}
void test_low() {
- Builder builder = new Builder(initialSize: 0);
- expect((builder..putUint8(1)).lowFinish(), [1]);
- expect((builder..putUint32(2)).lowFinish(), [2, 0, 0, 0, 0, 0, 0, 1]);
- expect((builder..putUint8(3)).lowFinish(),
- [0, 0, 0, 3, 2, 0, 0, 0, 0, 0, 0, 1]);
- expect((builder..putUint8(4)).lowFinish(),
- [0, 0, 4, 3, 2, 0, 0, 0, 0, 0, 0, 1]);
- expect((builder..putUint8(5)).lowFinish(),
- [0, 5, 4, 3, 2, 0, 0, 0, 0, 0, 0, 1]);
- expect((builder..putUint32(6)).lowFinish(),
+ final allocator = CustomAllocator();
+ final builder = Builder(initialSize: 0, allocator: allocator);
+
+ builder.putUint8(1);
+ expect(allocator.buffer(builder.size()), [1]);
+
+ builder.putUint32(2);
+ expect(allocator.buffer(builder.size()), [2, 0, 0, 0, 0, 0, 0, 1]);
+
+ builder.putUint8(3);
+ expect(
+ allocator.buffer(builder.size()), [0, 0, 0, 3, 2, 0, 0, 0, 0, 0, 0, 1]);
+
+ builder.putUint8(4);
+ expect(
+ allocator.buffer(builder.size()), [0, 0, 4, 3, 2, 0, 0, 0, 0, 0, 0, 1]);
+
+ builder.putUint8(5);
+ expect(
+ allocator.buffer(builder.size()), [0, 5, 4, 3, 2, 0, 0, 0, 0, 0, 0, 1]);
+
+ builder.putUint32(6);
+ expect(allocator.buffer(builder.size()),
[6, 0, 0, 0, 0, 5, 4, 3, 2, 0, 0, 0, 0, 0, 0, 1]);
}
void test_table_default() {
List<int> byteList;
{
- Builder builder = new Builder(initialSize: 0);
- builder.startTable();
+ final builder = Builder(initialSize: 0, allocator: CustomAllocator());
+ builder.startTable(2);
builder.addInt32(0, 10, 10);
builder.addInt32(1, 20, 10);
int offset = builder.endTable();
- byteList = builder.finish(offset);
+ builder.finish(offset);
+ byteList = builder.buffer;
+ expect(builder.size(), byteList.length);
}
// read and verify
- BufferContext buffer = new BufferContext.fromBytes(byteList);
+ BufferContext buffer = BufferContext.fromBytes(byteList);
int objectOffset = buffer.derefObject(0);
// was not written, so uses the new default value
expect(
@@ -278,15 +330,16 @@
20);
}
- void test_table_format() {
+ void test_table_format([Builder? builder]) {
Uint8List byteList;
{
- Builder builder = new Builder(initialSize: 0);
- builder.startTable();
+ builder ??= Builder(initialSize: 0);
+ builder.startTable(3);
builder.addInt32(0, 10);
builder.addInt32(1, 20);
builder.addInt32(2, 30);
- byteList = builder.finish(builder.endTable());
+ builder.finish(builder.endTable());
+ byteList = builder.buffer;
}
// Convert byteList to a ByteData so that we can read data from it.
ByteData byteData = byteList.buffer.asByteData(byteList.offsetInBytes);
@@ -315,30 +368,37 @@
String unicodeString = 'Проба пера';
List<int> byteList;
{
- Builder builder = new Builder(initialSize: 0);
- int latinStringOffset = builder.writeString(latinString);
- int unicodeStringOffset = builder.writeString(unicodeString);
- builder.startTable();
+ Builder builder = Builder(initialSize: 0);
+ int? latinStringOffset =
+ builder.writeString(latinString, asciiOptimization: true);
+ int? unicodeStringOffset =
+ builder.writeString(unicodeString, asciiOptimization: true);
+ builder.startTable(2);
builder.addOffset(0, latinStringOffset);
builder.addOffset(1, unicodeStringOffset);
int offset = builder.endTable();
- byteList = builder.finish(offset);
+ builder.finish(offset);
+ byteList = builder.buffer;
}
// read and verify
- BufferContext buf = new BufferContext.fromBytes(byteList);
+ BufferContext buf = BufferContext.fromBytes(byteList);
int objectOffset = buf.derefObject(0);
- expect(const StringReader().vTableGet(buf, objectOffset, indexToField(0)),
+ expect(
+ const StringReader()
+ .vTableGetNullable(buf, objectOffset, indexToField(0)),
latinString);
- expect(const StringReader().vTableGet(buf, objectOffset, indexToField(1)),
+ expect(
+ const StringReader(asciiOptimization: true)
+ .vTableGetNullable(buf, objectOffset, indexToField(1)),
unicodeString);
}
- void test_table_types() {
+ void test_table_types([Builder? builder]) {
List<int> byteList;
{
- Builder builder = new Builder(initialSize: 0);
- int stringOffset = builder.writeString('12345');
- builder.startTable();
+ builder ??= Builder(initialSize: 0);
+ int? stringOffset = builder.writeString('12345');
+ builder.startTable(7);
builder.addBool(0, true);
builder.addInt8(1, 10);
builder.addInt32(2, 20);
@@ -347,24 +407,39 @@
builder.addUint32(5, 0x9ABCDEF0);
builder.addUint8(6, 0x9A);
int offset = builder.endTable();
- byteList = builder.finish(offset);
+ builder.finish(offset);
+ byteList = builder.buffer;
}
// read and verify
- BufferContext buf = new BufferContext.fromBytes(byteList);
+ BufferContext buf = BufferContext.fromBytes(byteList);
int objectOffset = buf.derefObject(0);
expect(
- const BoolReader().vTableGet(buf, objectOffset, indexToField(0)), true);
+ const BoolReader()
+ .vTableGetNullable(buf, objectOffset, indexToField(0)),
+ true);
expect(
- const Int8Reader().vTableGet(buf, objectOffset, indexToField(1)), 10);
+ const Int8Reader()
+ .vTableGetNullable(buf, objectOffset, indexToField(1)),
+ 10);
expect(
- const Int32Reader().vTableGet(buf, objectOffset, indexToField(2)), 20);
- expect(const StringReader().vTableGet(buf, objectOffset, indexToField(3)),
+ const Int32Reader()
+ .vTableGetNullable(buf, objectOffset, indexToField(2)),
+ 20);
+ expect(
+ const StringReader()
+ .vTableGetNullable(buf, objectOffset, indexToField(3)),
'12345');
expect(
- const Int32Reader().vTableGet(buf, objectOffset, indexToField(4)), 40);
- expect(const Uint32Reader().vTableGet(buf, objectOffset, indexToField(5)),
+ const Int32Reader()
+ .vTableGetNullable(buf, objectOffset, indexToField(4)),
+ 40);
+ expect(
+ const Uint32Reader()
+ .vTableGetNullable(buf, objectOffset, indexToField(5)),
0x9ABCDEF0);
- expect(const Uint8Reader().vTableGet(buf, objectOffset, indexToField(6)),
+ expect(
+ const Uint8Reader()
+ .vTableGetNullable(buf, objectOffset, indexToField(6)),
0x9A);
}
@@ -373,12 +448,13 @@
// write
List<int> byteList;
{
- Builder builder = new Builder(initialSize: 0);
+ Builder builder = Builder(initialSize: 0);
int offset = builder.writeListUint32(values);
- byteList = builder.finish(offset);
+ builder.finish(offset);
+ byteList = builder.buffer;
}
// read and verify
- BufferContext buf = new BufferContext.fromBytes(byteList);
+ BufferContext buf = BufferContext.fromBytes(byteList);
List<int> items = const Uint32ListReader().read(buf, 0);
expect(items, hasLength(4));
expect(items, orderedEquals(values));
@@ -389,16 +465,17 @@
// write
List<int> byteList;
{
- Builder builder = new Builder(initialSize: 0);
- List<bool> values = new List<bool>.filled(len, false);
+ Builder builder = Builder(initialSize: 0);
+ List<bool> values = List<bool>.filled(len, false);
for (int bit in trueBits) {
values[bit] = true;
}
int offset = builder.writeListBool(values);
- byteList = builder.finish(offset);
+ builder.finish(offset);
+ byteList = builder.buffer;
}
// read and verify
- BufferContext buf = new BufferContext.fromBytes(byteList);
+ BufferContext buf = BufferContext.fromBytes(byteList);
List<bool> items = const BoolListReader().read(buf, 0);
expect(items, hasLength(len));
for (int i = 0; i < items.length; i++) {
@@ -417,25 +494,26 @@
verifyListBooleans(33, <int>[1, 2, 24, 25, 31, 32]);
verifyListBooleans(63, <int>[]);
verifyListBooleans(63, <int>[0, 1, 2, 61, 62]);
- verifyListBooleans(63, new List<int>.generate(63, (i) => i));
+ verifyListBooleans(63, List<int>.generate(63, (i) => i));
verifyListBooleans(64, <int>[]);
verifyListBooleans(64, <int>[0, 1, 2, 61, 62, 63]);
verifyListBooleans(64, <int>[1, 2, 62]);
verifyListBooleans(64, <int>[0, 1, 2, 63]);
- verifyListBooleans(64, new List<int>.generate(64, (i) => i));
+ verifyListBooleans(64, List<int>.generate(64, (i) => i));
verifyListBooleans(100, <int>[0, 3, 30, 60, 90, 99]);
}
void test_writeList_ofInt32() {
List<int> byteList;
{
- Builder builder = new Builder(initialSize: 0);
+ Builder builder = Builder(initialSize: 0);
int offset = builder.writeListInt32(<int>[1, 2, 3, 4, 5]);
- byteList = builder.finish(offset);
+ builder.finish(offset);
+ byteList = builder.buffer;
}
// read and verify
- BufferContext buf = new BufferContext.fromBytes(byteList);
- List<int> items = const ListReader<int>(const Int32Reader()).read(buf, 0);
+ BufferContext buf = BufferContext.fromBytes(byteList);
+ List<int> items = const ListReader<int>(Int32Reader()).read(buf, 0);
expect(items, hasLength(5));
expect(items, orderedEquals(<int>[1, 2, 3, 4, 5]));
}
@@ -445,13 +523,14 @@
// write
List<int> byteList;
{
- Builder builder = new Builder(initialSize: 0);
+ Builder builder = Builder(initialSize: 0);
int offset = builder.writeListFloat64(values);
- byteList = builder.finish(offset);
+ builder.finish(offset);
+ byteList = builder.buffer;
}
// read and verify
- BufferContext buf = new BufferContext.fromBytes(byteList);
+ BufferContext buf = BufferContext.fromBytes(byteList);
List<double> items = const Float64ListReader().read(buf, 0);
expect(items, hasLength(values.length));
@@ -465,12 +544,13 @@
// write
List<int> byteList;
{
- Builder builder = new Builder(initialSize: 0);
+ Builder builder = Builder(initialSize: 0);
int offset = builder.writeListFloat32(values);
- byteList = builder.finish(offset);
+ builder.finish(offset);
+ byteList = builder.buffer;
}
// read and verify
- BufferContext buf = new BufferContext.fromBytes(byteList);
+ BufferContext buf = BufferContext.fromBytes(byteList);
List<double> items = const Float32ListReader().read(buf, 0);
expect(items, hasLength(5));
for (int i = 0; i < values.length; i++) {
@@ -478,14 +558,14 @@
}
}
- void test_writeList_ofObjects() {
+ void test_writeList_ofObjects([Builder? builder]) {
List<int> byteList;
{
- Builder builder = new Builder(initialSize: 0);
+ builder ??= Builder(initialSize: 0);
// write the object #1
int object1;
{
- builder.startTable();
+ builder.startTable(2);
builder.addInt32(0, 10);
builder.addInt32(1, 20);
object1 = builder.endTable();
@@ -493,19 +573,20 @@
// write the object #1
int object2;
{
- builder.startTable();
+ builder.startTable(2);
builder.addInt32(0, 100);
builder.addInt32(1, 200);
object2 = builder.endTable();
}
// write the list
int offset = builder.writeList([object1, object2]);
- byteList = builder.finish(offset);
+ builder.finish(offset);
+ byteList = builder.buffer;
}
// read and verify
- BufferContext buf = new BufferContext.fromBytes(byteList);
+ BufferContext buf = BufferContext.fromBytes(byteList);
List<TestPointImpl> items =
- const ListReader<TestPointImpl>(const TestPointReader()).read(buf, 0);
+ const ListReader<TestPointImpl>(TestPointReader()).read(buf, 0);
expect(items, hasLength(2));
expect(items[0].x, 10);
expect(items[0].y, 20);
@@ -516,36 +597,37 @@
void test_writeList_ofStrings_asRoot() {
List<int> byteList;
{
- Builder builder = new Builder(initialSize: 0);
- int str1 = builder.writeString('12345');
- int str2 = builder.writeString('ABC');
+ Builder builder = Builder(initialSize: 0);
+ int? str1 = builder.writeString('12345');
+ int? str2 = builder.writeString('ABC');
int offset = builder.writeList([str1, str2]);
- byteList = builder.finish(offset);
+ builder.finish(offset);
+ byteList = builder.buffer;
}
// read and verify
- BufferContext buf = new BufferContext.fromBytes(byteList);
- List<String> items =
- const ListReader<String>(const StringReader()).read(buf, 0);
+ BufferContext buf = BufferContext.fromBytes(byteList);
+ List<String> items = const ListReader<String>(StringReader()).read(buf, 0);
expect(items, hasLength(2));
expect(items, contains('12345'));
expect(items, contains('ABC'));
}
- void test_writeList_ofStrings_inObject() {
+ void test_writeList_ofStrings_inObject([Builder? builder]) {
List<int> byteList;
{
- Builder builder = new Builder(initialSize: 0);
+ builder ??= Builder(initialSize: 0);
int listOffset = builder.writeList(
[builder.writeString('12345'), builder.writeString('ABC')]);
- builder.startTable();
+ builder.startTable(1);
builder.addOffset(0, listOffset);
int offset = builder.endTable();
- byteList = builder.finish(offset);
+ builder.finish(offset);
+ byteList = builder.buffer;
}
// read and verify
- BufferContext buf = new BufferContext.fromBytes(byteList);
- StringListWrapperImpl reader = new StringListWrapperReader().read(buf, 0);
- List<String> items = reader.items;
+ BufferContext buf = BufferContext.fromBytes(byteList);
+ StringListWrapperImpl reader = StringListWrapperReader().read(buf, 0);
+ List<String>? items = reader.items;
expect(items, hasLength(2));
expect(items, contains('12345'));
expect(items, contains('ABC'));
@@ -554,12 +636,13 @@
void test_writeList_ofUint32() {
List<int> byteList;
{
- Builder builder = new Builder(initialSize: 0);
+ Builder builder = Builder(initialSize: 0);
int offset = builder.writeListUint32(<int>[1, 2, 0x9ABCDEF0]);
- byteList = builder.finish(offset);
+ builder.finish(offset);
+ byteList = builder.buffer;
}
// read and verify
- BufferContext buf = new BufferContext.fromBytes(byteList);
+ BufferContext buf = BufferContext.fromBytes(byteList);
List<int> items = const Uint32ListReader().read(buf, 0);
expect(items, hasLength(3));
expect(items, orderedEquals(<int>[1, 2, 0x9ABCDEF0]));
@@ -568,12 +651,13 @@
void test_writeList_ofUint16() {
List<int> byteList;
{
- Builder builder = new Builder(initialSize: 0);
+ Builder builder = Builder(initialSize: 0);
int offset = builder.writeListUint16(<int>[1, 2, 60000]);
- byteList = builder.finish(offset);
+ builder.finish(offset);
+ byteList = builder.buffer;
}
// read and verify
- BufferContext buf = new BufferContext.fromBytes(byteList);
+ BufferContext buf = BufferContext.fromBytes(byteList);
List<int> items = const Uint16ListReader().read(buf, 0);
expect(items, hasLength(3));
expect(items, orderedEquals(<int>[1, 2, 60000]));
@@ -582,15 +666,188 @@
void test_writeList_ofUint8() {
List<int> byteList;
{
- Builder builder = new Builder(initialSize: 0);
- int offset = builder.writeListUint8(<int>[1, 2, 3, 4, 0x9A]);
- byteList = builder.finish(offset);
+ Builder builder = Builder(initialSize: 0);
+ int offset = builder.writeListUint8(<int>[1, 2, 3, 4, 0x9A, 0xFA]);
+ builder.finish(offset);
+ byteList = builder.buffer;
}
// read and verify
- BufferContext buf = new BufferContext.fromBytes(byteList);
- List<int> items = const Uint8ListReader().read(buf, 0);
- expect(items, hasLength(5));
- expect(items, orderedEquals(<int>[1, 2, 3, 4, 0x9A]));
+ BufferContext buf = BufferContext.fromBytes(byteList);
+ const buffOffset = 8; // 32-bit offset to the list, + 32-bit length
+ for (final lazy in [true, false]) {
+ List<int> items = Uint8ListReader(lazy: lazy).read(buf, 0);
+ expect(items, hasLength(6));
+ expect(items, orderedEquals(<int>[1, 2, 3, 4, 0x9A, 0xFA]));
+
+ // overwrite the buffer to verify the laziness
+ buf.buffer.setUint8(buffOffset + 1, 99);
+ expect(items, orderedEquals(<int>[1, lazy ? 99 : 2, 3, 4, 0x9A, 0xFA]));
+
+ // restore the previous value for the next loop
+ buf.buffer.setUint8(buffOffset + 1, 2);
+ }
+ }
+
+ void test_reset() {
+ // We'll run a selection of tests , reusing the builder between them.
+ final testCases = <void Function(Builder?)>[
+ test_monsterBuilder,
+ test_error_addInt32_withoutStartTable,
+ test_table_format,
+ test_table_types,
+ test_writeList_ofObjects,
+ test_writeList_ofStrings_inObject
+ ];
+
+ // Execute all test cases in all permutations of their order.
+ // To do that, we generate permutations of test case indexes.
+ final testCasesPermutations =
+ _permutationsOf(List.generate(testCases.length, (index) => index));
+ expect(testCasesPermutations.length, _factorial(testCases.length));
+
+ for (var indexes in testCasesPermutations) {
+ // print the order so failures are reproducible
+ printOnFailure('Running reset() test cases in order: $indexes');
+
+ Builder? builder;
+ for (var index in indexes) {
+ if (builder == null) {
+ // Initial size small enough so at least one test case increases it.
+ // On the other hand, it's large enough so that some test cases don't.
+ builder = Builder(initialSize: 32);
+ } else {
+ builder.reset();
+ }
+ testCases[index](builder);
+ }
+ }
+ }
+
+ // Generate permutations of the given list
+ List<List<T>> _permutationsOf<T>(List<T> source) {
+ final result = <List<T>>[];
+
+ void permutate(List<T> items, int startAt) {
+ for (var i = startAt; i < items.length; i++) {
+ List<T> permutation = items.toList(growable: false);
+ permutation[i] = items[startAt];
+ permutation[startAt] = items[i];
+
+ // add the current list upon reaching the end
+ if (startAt == items.length - 1) {
+ result.add(items);
+ } else {
+ permutate(permutation, startAt + 1);
+ }
+ }
+ }
+
+ permutate(source, 0);
+ return result;
+ }
+
+ // a very simple implementation of n!
+ int _factorial(int n) {
+ var result = 1;
+ for (var i = 2; i <= n; i++) {
+ result *= i;
+ }
+ return result;
+ }
+}
+
+@reflectiveTest
+class ObjectAPITest {
+ void test_tableStat() {
+ final object1 = example.StatT(count: 3, id: "foo", val: 4);
+ expect(object1 is Packable, isTrue);
+ final fbb = Builder();
+ fbb.finish(object1.pack(fbb));
+ final object2 = example.Stat(fbb.buffer).unpack();
+ expect(object2.count, object1.count);
+ expect(object2.id, object1.id);
+ expect(object2.val, object1.val);
+ expect(object2.toString(), object1.toString());
+ }
+
+ void test_tableMonster() {
+ final monster = example.MonsterT()
+ ..pos = example.Vec3T(
+ x: 1,
+ y: 2,
+ z: 3,
+ test1: 4.0,
+ test2: example.Color.Red,
+ test3: example.TestT(a: 1, b: 2))
+ ..mana = 2
+ ..name = 'Monstrous'
+ ..inventory = [24, 42]
+ ..color = example.Color.Green
+ // TODO be smarter for unions and automatically set the `type` field?
+ ..testType = example.AnyTypeId.MyGame_Example2_Monster
+ ..test = example2.MonsterT()
+ ..test4 = [example.TestT(a: 3, b: 4), example.TestT(a: 5, b: 6)]
+ ..testarrayofstring = ["foo", "bar"]
+ ..testarrayoftables = [example.MonsterT(name: 'Oof')]
+ ..enemy = example.MonsterT(name: 'Enemy')
+ ..testarrayofbools = [false, true, false]
+ ..testf = 42.24
+ ..testarrayofsortedstruct = [
+ example.AbilityT(id: 1, distance: 5),
+ example.AbilityT(id: 3, distance: 7)
+ ]
+ ..vectorOfLongs = [5, 6, 7]
+ ..vectorOfDoubles = [8.9, 9.0, 10.1, 11.2]
+ ..anyAmbiguousType = example.AnyAmbiguousAliasesTypeId.M2
+ ..anyAmbiguous = null
+ ..vectorOfEnums = [example.Color.Blue, example.Color.Green]
+ ..signedEnum = example.Race.None;
+
+ final fbBuilder = Builder();
+ final offset = monster.pack(fbBuilder);
+ expect(offset, isNonZero);
+ fbBuilder.finish(offset);
+ final data = fbBuilder.buffer;
+
+ // TODO currently broken because of struct builder issue, see #6688
+ // final monster2 = example.Monster(data); // Monster (reader)
+ // expect(
+ // // map Monster => MonsterT, Vec3 => Vec3T, ...
+ // monster2.toString().replaceAllMapped(
+ // RegExp('([a-zA-z0-9]+){'), (match) => match.group(1) + 'T{'),
+ // monster.toString());
+ //
+ // final monster3 = monster2.unpack(); // MonsterT
+ // expect(monster3.toString(), monster.toString());
+ }
+
+ void test_Lists() {
+ // Ensure unpack() reads lists eagerly by reusing the same builder and
+ // overwriting data. Why: because standard reader reads lists lazily...
+ final fbb = Builder();
+
+ final object1 = example.TypeAliasesT(v8: [1, 2, 3], vf64: [5, 6]);
+ fbb.finish(object1.pack(fbb));
+ final object1Read = example.TypeAliases(fbb.buffer).unpack();
+
+ // overwrite the original buffer by writing to the same builder
+ fbb.reset();
+ final object2 = example.TypeAliasesT(v8: [7, 8, 9], vf64: [10, 11]);
+ fbb.finish(object2.pack(fbb));
+ final object2Read = example.TypeAliases(fbb.buffer).unpack();
+
+ // this is fine even with lazy lists:
+ expect(object2.toString(), object2Read.toString());
+
+ // this fails with lazy lists:
+ expect(object1.toString(), object1Read.toString());
+
+ // empty list must be serialized as such (were stored NULL before v2.0)
+ fbb.reset();
+ final object3 = example.TypeAliasesT(v8: [], vf64: null);
+ fbb.finish(object3.pack(fbb));
+ final object3Read = example.TypeAliases(fbb.buffer).unpack();
+ expect(object3.toString(), object3Read.toString());
}
}
@@ -600,8 +857,8 @@
StringListWrapperImpl(this.bp, this.offset);
- List<String> get items => const ListReader<String>(const StringReader())
- .vTableGet(bp, offset, indexToField(0));
+ List<String>? get items => const ListReader<String>(StringReader())
+ .vTableGetNullable(bp, offset, indexToField(0));
}
class StringListWrapperReader extends TableReader<StringListWrapperImpl> {
@@ -609,7 +866,7 @@
@override
StringListWrapperImpl createObject(BufferContext object, int offset) {
- return new StringListWrapperImpl(object, offset);
+ return StringListWrapperImpl(object, offset);
}
}
@@ -629,7 +886,7 @@
@override
TestPointImpl createObject(BufferContext object, int offset) {
- return new TestPointImpl(object, offset);
+ return TestPointImpl(object, offset);
}
}
@@ -639,7 +896,9 @@
expect(example.Color.values, same(example.Color.values));
expect(example.Race.values, same(example.Race.values));
expect(example.AnyTypeId.values, same(example.AnyTypeId.values));
- expect(example.AnyUniqueAliasesTypeId.values, same(example.AnyUniqueAliasesTypeId.values));
- expect(example.AnyAmbiguousAliasesTypeId.values, same(example.AnyAmbiguousAliasesTypeId.values));
+ expect(example.AnyUniqueAliasesTypeId.values,
+ same(example.AnyUniqueAliasesTypeId.values));
+ expect(example.AnyAmbiguousAliasesTypeId.values,
+ same(example.AnyAmbiguousAliasesTypeId.values));
}
}
diff --git a/dart/test/flex_builder_test.dart b/dart/test/flex_builder_test.dart
index 5a1c1a8..66e6638 100644
--- a/dart/test/flex_builder_test.dart
+++ b/dart/test/flex_builder_test.dart
@@ -58,18 +58,18 @@
{
var flx = Builder();
flx.addString('hello 😱');
- expect(flx.finish(), [10, 104, 101, 108, 108, 111, 32, 240, 159, 152, 177, 0, 11, 20, 1]);
+ expect(flx.finish(),
+ [10, 104, 101, 108, 108, 111, 32, 240, 159, 152, 177, 0, 11, 20, 1]);
}
});
- test('build vector', (){
+ test('build vector', () {
{
var flx = Builder()
..startVector()
..addInt(1)
..addInt(2)
- ..end()
- ;
+ ..end();
expect(flx.finish(), [1, 2, 2, 64, 1]);
}
{
@@ -77,8 +77,7 @@
..startVector()
..addInt(-1)
..addInt(256)
- ..end()
- ;
+ ..end();
expect(flx.finish(), [255, 255, 0, 1, 4, 65, 1]);
}
{
@@ -86,8 +85,7 @@
..startVector()
..addInt(-45)
..addInt(256000)
- ..end()
- ;
+ ..end();
expect(flx.finish(), [211, 255, 255, 255, 0, 232, 3, 0, 8, 66, 1]);
}
{
@@ -95,9 +93,28 @@
..startVector()
..addDouble(1.1)
..addDouble(-256)
- ..end()
- ;
- expect(flx.finish(), [154, 153, 153, 153, 153, 153, 241, 63, 0, 0, 0, 0, 0, 0, 112, 192, 16, 75, 1]);
+ ..end();
+ expect(flx.finish(), [
+ 154,
+ 153,
+ 153,
+ 153,
+ 153,
+ 153,
+ 241,
+ 63,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 112,
+ 192,
+ 16,
+ 75,
+ 1
+ ]);
}
{
var flx = Builder()
@@ -105,8 +122,7 @@
..addInt(1)
..addInt(2)
..addInt(4)
- ..end()
- ;
+ ..end();
expect(flx.finish(), [1, 2, 4, 3, 76, 1]);
}
{
@@ -115,19 +131,17 @@
..addInt(-1)
..addInt(256)
..addInt(4)
- ..end()
- ;
+ ..end();
expect(flx.finish(), [255, 255, 0, 1, 4, 0, 6, 77, 1]);
}
{
var flx = Builder()
..startVector()
- ..startVector()
- ..addInt(61)
- ..end()
- ..addInt(64)
+ ..startVector()
+ ..addInt(61)
..end()
- ;
+ ..addInt(64)
+ ..end();
expect(flx.finish(), [1, 61, 2, 2, 64, 44, 4, 4, 40, 1]);
}
{
@@ -136,9 +150,31 @@
..addString('foo')
..addString('bar')
..addString('baz')
- ..end()
- ;
- expect(flx.finish(), [3, 102, 111, 111, 0, 3, 98, 97, 114, 0, 3, 98, 97, 122, 0, 3, 15, 11, 7, 3, 60, 1]);
+ ..end();
+ expect(flx.finish(), [
+ 3,
+ 102,
+ 111,
+ 111,
+ 0,
+ 3,
+ 98,
+ 97,
+ 114,
+ 0,
+ 3,
+ 98,
+ 97,
+ 122,
+ 0,
+ 3,
+ 15,
+ 11,
+ 7,
+ 3,
+ 60,
+ 1
+ ]);
}
{
var flx = Builder()
@@ -149,9 +185,34 @@
..addString('foo')
..addString('bar')
..addString('baz')
- ..end()
- ;
- expect(flx.finish(), [3, 102, 111, 111, 0, 3, 98, 97, 114, 0, 3, 98, 97, 122, 0, 6, 15, 11, 7, 18, 14, 10, 6, 60, 1]);
+ ..end();
+ expect(flx.finish(), [
+ 3,
+ 102,
+ 111,
+ 111,
+ 0,
+ 3,
+ 98,
+ 97,
+ 114,
+ 0,
+ 3,
+ 98,
+ 97,
+ 122,
+ 0,
+ 6,
+ 15,
+ 11,
+ 7,
+ 18,
+ 14,
+ 10,
+ 6,
+ 60,
+ 1
+ ]);
}
{
var flx = Builder()
@@ -159,8 +220,7 @@
..addBool(true)
..addBool(false)
..addBool(true)
- ..end()
- ;
+ ..end();
expect(flx.finish(), [3, 1, 0, 1, 3, 144, 1]);
}
{
@@ -171,29 +231,83 @@
..addInt(-5)
..addDouble(1.3)
..addBool(true)
- ..end()
- ;
+ ..end();
expect(flx.finish(), [
- 3, 102, 111, 111, 0, 0, 0, 0,
- 5, 0, 0, 0, 0, 0, 0, 0,
- 15, 0, 0, 0, 0, 0, 0, 0,
- 1, 0, 0, 0, 0, 0, 0, 0,
- 251, 255, 255, 255, 255, 255, 255, 255,
- 205, 204, 204, 204, 204, 204, 244, 63,
- 1, 0, 0, 0, 0, 0, 0, 0,
- 20, 4, 4, 15, 104, 45, 43, 1]);
+ 3,
+ 102,
+ 111,
+ 111,
+ 0,
+ 0,
+ 0,
+ 0,
+ 5,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 15,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 1,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 251,
+ 255,
+ 255,
+ 255,
+ 255,
+ 255,
+ 255,
+ 255,
+ 205,
+ 204,
+ 204,
+ 204,
+ 204,
+ 204,
+ 244,
+ 63,
+ 1,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 20,
+ 4,
+ 4,
+ 15,
+ 104,
+ 45,
+ 43,
+ 1
+ ]);
}
});
- test('build map', ()
- {
+ test('build map', () {
{
var flx = Builder()
..startMap()
..addKey('a')
..addInt(12)
- ..end()
- ;
+ ..end();
expect(flx.finish(), [97, 0, 1, 3, 1, 1, 1, 12, 4, 2, 36, 1]);
}
{
@@ -203,105 +317,270 @@
..addInt(12)
..addKey('')
..addInt(45)
- ..end()
- ;
- expect(flx.finish(), [97, 0, 0, 2, 2, 5, 2, 1, 2, 45, 12, 4, 4, 4, 36, 1]);
+ ..end();
+ expect(
+ flx.finish(), [97, 0, 0, 2, 2, 5, 2, 1, 2, 45, 12, 4, 4, 4, 36, 1]);
}
{
var flx = Builder()
..startVector()
- ..startMap()
- ..addKey('something')
- ..addInt(12)
- ..end()
- ..startMap()
- ..addKey('something')
- ..addInt(45)
- ..end()
+ ..startMap()
+ ..addKey('something')
+ ..addInt(12)
..end()
- ;
- expect(flx.finish(), [115, 111, 109, 101, 116, 104, 105, 110, 103, 0,
- 1, 11, 1, 1, 1, 12, 4, 6, 1, 1, 45, 4, 2, 8, 4, 36, 36, 4, 40, 1]);
+ ..startMap()
+ ..addKey('something')
+ ..addInt(45)
+ ..end()
+ ..end();
+ expect(flx.finish(), [
+ 115,
+ 111,
+ 109,
+ 101,
+ 116,
+ 104,
+ 105,
+ 110,
+ 103,
+ 0,
+ 1,
+ 11,
+ 1,
+ 1,
+ 1,
+ 12,
+ 4,
+ 6,
+ 1,
+ 1,
+ 45,
+ 4,
+ 2,
+ 8,
+ 4,
+ 36,
+ 36,
+ 4,
+ 40,
+ 1
+ ]);
}
});
- test('build blob', ()
- {
+ test('build blob', () {
{
- var flx = Builder()
- ..addBlob(Uint8List.fromList([1, 2, 3]).buffer)
- ;
+ var flx = Builder()..addBlob(Uint8List.fromList([1, 2, 3]).buffer);
expect(flx.finish(), [3, 1, 2, 3, 3, 100, 1]);
}
});
- test('build from object', (){
- expect(Builder.buildFromObject(Uint8List.fromList([1, 2, 3]).buffer).asUint8List(), [3, 1, 2, 3, 3, 100, 1]);
+ test('build from object', () {
+ expect(
+ Builder.buildFromObject(Uint8List.fromList([1, 2, 3]).buffer)
+ .asUint8List(),
+ [3, 1, 2, 3, 3, 100, 1]);
expect(Builder.buildFromObject(null).asUint8List(), [0, 0, 1]);
expect(Builder.buildFromObject(true).asUint8List(), [1, 104, 1]);
expect(Builder.buildFromObject(false).asUint8List(), [0, 104, 1]);
expect(Builder.buildFromObject(25).asUint8List(), [25, 4, 1]);
expect(Builder.buildFromObject(-250).asUint8List(), [6, 255, 5, 2]);
- expect(Builder.buildFromObject(-2.50).asUint8List(), [0, 0, 32, 192, 14, 4]);
- expect(Builder.buildFromObject('Maxim').asUint8List(), [5, 77, 97, 120, 105, 109, 0, 6, 20, 1]);
- expect(Builder.buildFromObject([1, 3.3, 'max', true, null, false]).asUint8List(), [
- 3, 109, 97, 120, 0, 0, 0, 0,
- 6, 0, 0, 0, 0, 0, 0, 0,
- 1, 0, 0, 0, 0, 0, 0, 0,
- 102, 102, 102, 102, 102, 102, 10, 64,
- 31, 0, 0, 0, 0, 0, 0, 0,
- 1, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 4, 15, 20, 104, 0, 104, 54, 43, 1
- ]);
- expect(Builder.buildFromObject([{'something':12}, {'something': 45}]).asUint8List(), [
- 115, 111, 109, 101, 116, 104, 105, 110, 103, 0,
- 1, 11, 1, 1, 1, 12, 4, 6, 1, 1, 45, 4, 2, 8, 4, 36, 36, 4, 40, 1
- ]);
+ expect(
+ Builder.buildFromObject(-2.50).asUint8List(), [0, 0, 32, 192, 14, 4]);
+ expect(Builder.buildFromObject('Maxim').asUint8List(),
+ [5, 77, 97, 120, 105, 109, 0, 6, 20, 1]);
+ expect(
+ Builder.buildFromObject([1, 3.3, 'max', true, null, false])
+ .asUint8List(),
+ [
+ 3,
+ 109,
+ 97,
+ 120,
+ 0,
+ 0,
+ 0,
+ 0,
+ 6,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 1,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 102,
+ 102,
+ 102,
+ 102,
+ 102,
+ 102,
+ 10,
+ 64,
+ 31,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 1,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 4,
+ 15,
+ 20,
+ 104,
+ 0,
+ 104,
+ 54,
+ 43,
+ 1
+ ]);
+ expect(
+ Builder.buildFromObject([
+ {'something': 12},
+ {'something': 45}
+ ]).asUint8List(),
+ [
+ 115,
+ 111,
+ 109,
+ 101,
+ 116,
+ 104,
+ 105,
+ 110,
+ 103,
+ 0,
+ 1,
+ 11,
+ 1,
+ 1,
+ 1,
+ 12,
+ 4,
+ 6,
+ 1,
+ 1,
+ 45,
+ 4,
+ 2,
+ 8,
+ 4,
+ 36,
+ 36,
+ 4,
+ 40,
+ 1
+ ]);
});
- test('add double indirectly', (){
- var flx = Builder()
- ..addDoubleIndirectly(0.1)
- ;
+ test('add double indirectly', () {
+ var flx = Builder()..addDoubleIndirectly(0.1);
expect(flx.finish(), [154, 153, 153, 153, 153, 153, 185, 63, 8, 35, 1]);
});
- test('add double indirectly to vector with cache', (){
+ test('add double indirectly to vector with cache', () {
var flx = Builder()
..startVector()
..addDoubleIndirectly(0.1, cache: true)
..addDoubleIndirectly(0.1, cache: true)
..addDoubleIndirectly(0.1, cache: true)
..addDoubleIndirectly(0.1, cache: true)
- ..end()
- ;
- expect(flx.finish(), [154, 153, 153, 153, 153, 153, 185, 63,
- 4, 9, 10, 11, 12, 35, 35, 35, 35, 8, 40, 1]);
+ ..end();
+ expect(flx.finish(), [
+ 154,
+ 153,
+ 153,
+ 153,
+ 153,
+ 153,
+ 185,
+ 63,
+ 4,
+ 9,
+ 10,
+ 11,
+ 12,
+ 35,
+ 35,
+ 35,
+ 35,
+ 8,
+ 40,
+ 1
+ ]);
});
- test('add int indirectly', (){
- var flx = Builder()
- ..addIntIndirectly(2345234523452345)
- ;
+ test('add int indirectly', () {
+ var flx = Builder()..addIntIndirectly(2345234523452345);
expect(flx.finish(), [185, 115, 175, 118, 250, 84, 8, 0, 8, 27, 1]);
});
- test('add int indirectly to vector with cache', (){
+ test('add int indirectly to vector with cache', () {
var flx = Builder()
..startVector()
..addIntIndirectly(2345234523452345, cache: true)
..addIntIndirectly(2345234523452345, cache: true)
..addIntIndirectly(2345234523452345, cache: true)
..addIntIndirectly(2345234523452345, cache: true)
- ..end()
- ;
- expect(flx.finish(), [185, 115, 175, 118, 250, 84, 8, 0,
- 4, 9, 10, 11, 12, 27, 27, 27, 27, 8, 40, 1]);
+ ..end();
+ expect(flx.finish(), [
+ 185,
+ 115,
+ 175,
+ 118,
+ 250,
+ 84,
+ 8,
+ 0,
+ 4,
+ 9,
+ 10,
+ 11,
+ 12,
+ 27,
+ 27,
+ 27,
+ 27,
+ 8,
+ 40,
+ 1
+ ]);
});
- test('snapshot', (){
+ test('snapshot', () {
var flx = Builder();
flx.startVector();
flx.addInt(12);
@@ -312,4 +591,3 @@
expect(flx.snapshot().asUint8List(), [12, 24, 45, 3, 76, 1]);
});
}
-
diff --git a/dart/test/flex_reader_test.dart b/dart/test/flex_reader_test.dart
index ec30367..875b1c1 100644
--- a/dart/test/flex_reader_test.dart
+++ b/dart/test/flex_reader_test.dart
@@ -21,55 +21,68 @@
expect(Reference.fromBuffer(b([255, 251, 5, 2])).intValue, -1025);
expect(Reference.fromBuffer(b([1, 4, 9, 2])).intValue, 1025);
expect(Reference.fromBuffer(b([255, 255, 255, 127, 6, 4])).intValue,
- 2147483647);
+ 2147483647);
+ expect(Reference.fromBuffer(b([0, 0, 0, 128, 6, 4])).intValue, -2147483648);
expect(
- Reference.fromBuffer(b([0, 0, 0, 128, 6, 4])).intValue, -2147483648);
+ Reference.fromBuffer(b([255, 255, 255, 255, 0, 0, 0, 0, 7, 8]))
+ .intValue,
+ 4294967295);
expect(
- Reference.fromBuffer(b([255, 255, 255, 255, 0, 0, 0, 0, 7, 8]))
- .intValue,
- 4294967295);
- expect(
- Reference.fromBuffer(b([255, 255, 255, 255, 255, 255, 255, 127, 7, 8]))
- .intValue,
- 9223372036854775807);
+ Reference.fromBuffer(b([255, 255, 255, 255, 255, 255, 255, 127, 7, 8]))
+ .intValue,
+ 9223372036854775807);
expect(Reference.fromBuffer(b([0, 0, 0, 0, 0, 0, 0, 128, 7, 8])).intValue,
- -9223372036854775808);
+ -9223372036854775808);
// Dart does not really support UInt64
// expect(FlxValue.fromBuffer(b([255, 255, 255, 255, 255, 255, 255, 255, 11, 8])).intValue, 18446744073709551615);
});
test('double value', () {
expect(Reference.fromBuffer(b([0, 0, 144, 64, 14, 4])).doubleValue, 4.5);
expect(Reference.fromBuffer(b([205, 204, 204, 61, 14, 4])).doubleValue,
- closeTo(.1, .001));
+ closeTo(.1, .001));
expect(
- Reference.fromBuffer(b([154, 153, 153, 153, 153, 153, 185, 63, 15, 8]))
- .doubleValue,
- .1);
+ Reference.fromBuffer(b([154, 153, 153, 153, 153, 153, 185, 63, 15, 8]))
+ .doubleValue,
+ .1);
});
test('num value', () {
expect(Reference.fromBuffer(b([0, 0, 144, 64, 14, 4])).numValue, 4.5);
expect(Reference.fromBuffer(b([205, 204, 204, 61, 14, 4])).numValue,
- closeTo(.1, .001));
+ closeTo(.1, .001));
expect(
- Reference.fromBuffer(b([154, 153, 153, 153, 153, 153, 185, 63, 15, 8]))
- .numValue,
- .1);
+ Reference.fromBuffer(b([154, 153, 153, 153, 153, 153, 185, 63, 15, 8]))
+ .numValue,
+ .1);
expect(Reference.fromBuffer(b([255, 251, 5, 2])).numValue, -1025);
});
test('string value', () {
expect(
- Reference.fromBuffer(b([5, 77, 97, 120, 105, 109, 0, 6, 20, 1]))
- .stringValue,
- 'Maxim');
+ Reference.fromBuffer(b([5, 77, 97, 120, 105, 109, 0, 6, 20, 1]))
+ .stringValue,
+ 'Maxim');
expect(
- Reference.fromBuffer(b([
- 10, 104, 101, 108, 108, 111, 32, 240, 159, 152, 177, 0, 11, 20, 1
- ])).stringValue,
- 'hello 😱');
+ Reference.fromBuffer(b([
+ 10,
+ 104,
+ 101,
+ 108,
+ 108,
+ 111,
+ 32,
+ 240,
+ 159,
+ 152,
+ 177,
+ 0,
+ 11,
+ 20,
+ 1
+ ])).stringValue,
+ 'hello 😱');
});
test('blob value', () {
expect(
- Reference.fromBuffer(b([3, 1, 2, 3, 3, 100, 1])).blobValue, [1, 2, 3]);
+ Reference.fromBuffer(b([3, 1, 2, 3, 3, 100, 1])).blobValue, [1, 2, 3]);
});
test('bool vector', () {
var flx = Reference.fromBuffer(b([3, 1, 0, 1, 3, 144, 1]));
@@ -81,27 +94,92 @@
testNumbers([3, 1, 2, 3, 3, 44, 1], [1, 2, 3]);
testNumbers([3, 255, 2, 3, 3, 44, 1], [-1, 2, 3]);
testNumbers([3, 0, 1, 0, 43, 2, 3, 0, 6, 45, 1], [1, 555, 3]);
- testNumbers(
- [3, 0, 0, 0, 1, 0, 0, 0, 204, 216, 0, 0, 3, 0, 0, 0, 12, 46, 1],
- [1, 55500, 3]);
+ testNumbers([3, 0, 0, 0, 1, 0, 0, 0, 204, 216, 0, 0, 3, 0, 0, 0, 12, 46, 1],
+ [1, 55500, 3]);
testNumbers([
- 3, 0, 0, 0, 0, 0, 0, 0,
- 1, 0, 0, 0, 0, 0, 0, 0,
- 172, 128, 94, 239, 12, 0, 0, 0,
- 3, 0, 0, 0, 0, 0, 0, 0,
- 24, 47, 1
- ], [1, 55555555500, 3
+ 3,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 1,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 172,
+ 128,
+ 94,
+ 239,
+ 12,
+ 0,
+ 0,
+ 0,
+ 3,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 24,
+ 47,
+ 1
+ ], [
+ 1,
+ 55555555500,
+ 3
]);
testNumbers(
- [3, 0, 0, 0, 0, 0, 192, 63, 0, 0, 32, 64, 0, 0, 96, 64, 12, 54, 1],
- [1.5, 2.5, 3.5]);
+ [3, 0, 0, 0, 0, 0, 192, 63, 0, 0, 32, 64, 0, 0, 96, 64, 12, 54, 1],
+ [1.5, 2.5, 3.5]);
testNumbers([
- 3, 0, 0, 0, 0, 0, 0, 0,
- 154, 153, 153, 153, 153, 153, 241, 63,
- 154, 153, 153, 153, 153, 153, 1, 64,
- 102, 102, 102, 102, 102, 102, 10, 64,
- 24, 55, 1
- ], [1.1, 2.2, 3.3
+ 3,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 154,
+ 153,
+ 153,
+ 153,
+ 153,
+ 153,
+ 241,
+ 63,
+ 154,
+ 153,
+ 153,
+ 153,
+ 153,
+ 153,
+ 1,
+ 64,
+ 102,
+ 102,
+ 102,
+ 102,
+ 102,
+ 102,
+ 10,
+ 64,
+ 24,
+ 55,
+ 1
+ ], [
+ 1.1,
+ 2.2,
+ 3.3
]);
});
test('number vector, fixed type', () {
@@ -109,11 +187,28 @@
testNumbers([255, 255, 0, 1, 4, 65, 1], [-1, 256]);
testNumbers([211, 255, 255, 255, 0, 232, 3, 0, 8, 66, 1], [-45, 256000]);
testNumbers([
- 211, 255, 255, 255, 255, 255, 255, 255,
- 255, 255, 255, 255, 255, 255, 255, 127,
- 16, 67, 1
+ 211,
+ 255,
+ 255,
+ 255,
+ 255,
+ 255,
+ 255,
+ 255,
+ 255,
+ 255,
+ 255,
+ 255,
+ 255,
+ 255,
+ 255,
+ 127,
+ 16,
+ 67,
+ 1
], [
- -45, 9223372036854775807
+ -45,
+ 9223372036854775807
]);
testNumbers([1, 2, 2, 68, 1], [1, 2]);
@@ -122,85 +217,326 @@
testNumbers([205, 204, 140, 63, 0, 0, 0, 192, 8, 74, 1], [1.1, -2]);
testNumbers([
- 154, 153, 153, 153, 153, 153, 241, 63,
- 0, 0, 0, 0, 0, 0, 112, 192,
- 16, 75, 1
+ 154,
+ 153,
+ 153,
+ 153,
+ 153,
+ 153,
+ 241,
+ 63,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 112,
+ 192,
+ 16,
+ 75,
+ 1
], [
- 1.1, -256
+ 1.1,
+ -256
]);
testNumbers([211, 255, 255, 255, 0, 232, 3, 0, 4, 0, 0, 0, 12, 78, 1],
- [-45, 256000, 4]);
+ [-45, 256000, 4]);
testNumbers([
- 211, 255, 255, 255, 255, 255, 255, 255,
- 255, 255, 255, 255, 255, 255, 255, 127,
- 4, 0, 0, 0, 0, 0, 0, 0,
- 9, 0, 0, 0, 0, 0, 0, 0,
- 32, 91, 1
+ 211,
+ 255,
+ 255,
+ 255,
+ 255,
+ 255,
+ 255,
+ 255,
+ 255,
+ 255,
+ 255,
+ 255,
+ 255,
+ 255,
+ 255,
+ 127,
+ 4,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 9,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 32,
+ 91,
+ 1
], [
- -45, 9223372036854775807, 4, 9
+ -45,
+ 9223372036854775807,
+ 4,
+ 9
]);
testNumbers([
- 45, 0, 0, 0, 0, 0, 0, 0,
- 255, 255, 255, 255, 255, 255, 255, 127,
- 4, 0, 0, 0, 0, 0, 0, 0,
- 9, 0, 0, 0, 0, 0, 0, 0,
- 32, 95, 1
+ 45,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 255,
+ 255,
+ 255,
+ 255,
+ 255,
+ 255,
+ 255,
+ 127,
+ 4,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 9,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 32,
+ 95,
+ 1
], [
- 45, 9223372036854775807, 4, 9
+ 45,
+ 9223372036854775807,
+ 4,
+ 9
]);
testNumbers([
- 154, 153, 153, 153, 153, 153, 241, 63,
- 0, 0, 0, 0, 0, 0, 112, 64,
- 0, 0, 0, 0, 0, 0, 16, 64,
- 24, 87, 1
+ 154,
+ 153,
+ 153,
+ 153,
+ 153,
+ 153,
+ 241,
+ 63,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 112,
+ 64,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 16,
+ 64,
+ 24,
+ 87,
+ 1
], [
- 1.1, 256, 4
+ 1.1,
+ 256,
+ 4
]);
testNumbers([
- 154, 153, 153, 153, 153, 153, 241, 63,
- 0, 0, 0, 0, 0, 0, 112, 64,
- 0, 0, 0, 0, 0, 0, 16, 64,
- 0, 0, 0, 0, 0, 0, 34, 64,
- 32, 99, 1
+ 154,
+ 153,
+ 153,
+ 153,
+ 153,
+ 153,
+ 241,
+ 63,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 112,
+ 64,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 16,
+ 64,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 34,
+ 64,
+ 32,
+ 99,
+ 1
], [
- 1.1, 256, 4, 9
+ 1.1,
+ 256,
+ 4,
+ 9
]);
});
test('string vector', () {
testStrings([
- 3, 102, 111, 111, 0,
- 3, 98, 97, 114, 0,
- 3, 98, 97, 122, 0,
- 3, 15, 11, 7,
- 3, 60, 1
+ 3,
+ 102,
+ 111,
+ 111,
+ 0,
+ 3,
+ 98,
+ 97,
+ 114,
+ 0,
+ 3,
+ 98,
+ 97,
+ 122,
+ 0,
+ 3,
+ 15,
+ 11,
+ 7,
+ 3,
+ 60,
+ 1
], [
- 'foo', 'bar', 'baz'
+ 'foo',
+ 'bar',
+ 'baz'
]);
testStrings([
- 3, 102, 111, 111, 0,
- 3, 98, 97, 114, 0,
- 3, 98, 97, 122, 0,
- 6, 15, 11, 7, 18, 14, 10,
- 6, 60, 1
+ 3,
+ 102,
+ 111,
+ 111,
+ 0,
+ 3,
+ 98,
+ 97,
+ 114,
+ 0,
+ 3,
+ 98,
+ 97,
+ 122,
+ 0,
+ 6,
+ 15,
+ 11,
+ 7,
+ 18,
+ 14,
+ 10,
+ 6,
+ 60,
+ 1
], [
- 'foo', 'bar', 'baz', 'foo', 'bar', 'baz'
+ 'foo',
+ 'bar',
+ 'baz',
+ 'foo',
+ 'bar',
+ 'baz'
]);
});
test('mixed vector', () {
var flx = Reference.fromBuffer(b([
- 3, 102, 111, 111, 0, 0, 0, 0,
- 5, 0, 0, 0, 0, 0, 0, 0,
- 15, 0, 0, 0, 0, 0, 0, 0,
- 1, 0, 0, 0, 0, 0, 0, 0,
- 251, 255, 255, 255, 255, 255, 255, 255,
- 205, 204, 204, 204, 204, 204, 244, 63,
- 1, 0, 0, 0, 0, 0, 0, 0,
- 20, 4, 4, 15, 104, 45, 43, 1
+ 3,
+ 102,
+ 111,
+ 111,
+ 0,
+ 0,
+ 0,
+ 0,
+ 5,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 15,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 1,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 251,
+ 255,
+ 255,
+ 255,
+ 255,
+ 255,
+ 255,
+ 255,
+ 205,
+ 204,
+ 204,
+ 204,
+ 204,
+ 204,
+ 244,
+ 63,
+ 1,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 20,
+ 4,
+ 4,
+ 15,
+ 104,
+ 45,
+ 43,
+ 1
]));
expect(flx.length, 5);
expect(flx[0].stringValue, 'foo');
@@ -216,7 +552,8 @@
expect(flx['a'].numValue, 12);
});
test('two value map', () {
- var flx = Reference.fromBuffer(b([0, 97, 0, 2, 4, 4, 2, 1, 2, 45, 12, 4, 4, 4, 36, 1]));
+ var flx = Reference.fromBuffer(
+ b([0, 97, 0, 2, 4, 4, 2, 1, 2, 45, 12, 4, 4, 4, 36, 1]));
expect(flx.length, 2);
expect(flx['a'].numValue, 12);
expect(flx[''].numValue, 45);
@@ -239,45 +576,239 @@
expect(flx['address']['zip'].stringValue, '12345');
expect(flx['address']['countryCode'].stringValue, 'XX');
- expect(() => flx['address']['country'].stringValue,
- throwsA(predicate((e) => e is ArgumentError && e.message == 'Key: [country] is not applicable on: //address of: ValueType.Map')));
- expect(() => flx['address']['countryCode'][0],
- throwsA(predicate((e) => e is ArgumentError && e.message == 'Key: [0] is not applicable on: //address/countryCode of: ValueType.String')));
- expect(() => flx[1],
- throwsA(predicate((e) => e is ArgumentError && e.message == 'Key: [1] is not applicable on: / of: ValueType.Map')));
- expect(() => flx['flags'][4],
- throwsA(predicate((e) => e is ArgumentError && e.message == 'Key: [4] is not applicable on: //flags of: ValueType.VectorBool length: 4')));
- expect(() => flx['flags'][-1],
- throwsA(predicate((e) => e is ArgumentError && e.message == 'Key: [-1] is not applicable on: //flags of: ValueType.VectorBool length: 4')));
+ expect(
+ () => flx['address']['country'].stringValue,
+ throwsA(predicate((dynamic e) =>
+ e is ArgumentError &&
+ e.message ==
+ 'Key: [country] is not applicable on: //address of: ValueType.Map')));
+ expect(
+ () => flx['address']['countryCode'][0],
+ throwsA(predicate((dynamic e) =>
+ e is ArgumentError &&
+ e.message ==
+ 'Key: [0] is not applicable on: //address/countryCode of: ValueType.String')));
+ expect(
+ () => flx[1],
+ throwsA(predicate((dynamic e) =>
+ e is ArgumentError &&
+ e.message ==
+ 'Key: [1] is not applicable on: / of: ValueType.Map')));
+ expect(
+ () => flx['flags'][4],
+ throwsA(predicate((dynamic e) =>
+ e is ArgumentError &&
+ e.message ==
+ 'Key: [4] is not applicable on: //flags of: ValueType.VectorBool length: 4')));
+ expect(
+ () => flx['flags'][-1],
+ throwsA(predicate((dynamic e) =>
+ e is ArgumentError &&
+ e.message ==
+ 'Key: [-1] is not applicable on: //flags of: ValueType.VectorBool length: 4')));
});
test('complex map to json', () {
var flx = complexMap();
- expect(flx.json, '{"address":{"city":"Bla","countryCode":"XX","zip":"12345"},"age":35,"flags":[true,false,true,true],"name":"Maxim","weight":72.5}');
+ expect(flx.json,
+ '{"address":{"city":"Bla","countryCode":"XX","zip":"12345"},"age":35,"flags":[true,false,true,true],"name":"Maxim","weight":72.5}');
});
test('complex map iterators', () {
var flx = complexMap();
- expect(flx.mapKeyIterable.map((e) => e).toList(), ['address', 'age', 'flags', 'name', 'weight']);
- expect(flx.mapValueIterable.map((e) => e.json).toList(), [flx['address'].json, flx['age'].json, flx['flags'].json, flx['name'].json, flx['weight'].json]);
- expect(flx['flags'].vectorIterable.map((e) => e.boolValue).toList(), [true, false, true, true]);
+ expect(flx.mapKeyIterable.map((e) => e).toList(),
+ ['address', 'age', 'flags', 'name', 'weight']);
+ expect(flx.mapValueIterable.map((e) => e.json).toList(), [
+ flx['address'].json,
+ flx['age'].json,
+ flx['flags'].json,
+ flx['name'].json,
+ flx['weight'].json
+ ]);
+ expect(flx['flags'].vectorIterable.map((e) => e.boolValue).toList(),
+ [true, false, true, true]);
});
- test('bug where offest were stored as int instead of uint', (){
- const data = [99, 104, 97, 110, 110, 101, 108, 115, 95, 105, 110, 0,
- 100, 105, 108, 97, 116, 105, 111, 110, 95, 104, 101, 105, 103, 104, 116, 95, 102, 97, 99, 116, 111, 114, 0,
- 100, 105, 108, 97, 116, 105, 111, 110, 95, 119, 105, 100, 116, 104, 95, 102, 97, 99, 116, 111, 114, 0,
- 102, 117, 115, 101, 100, 95, 97, 99, 116, 105, 118, 97, 116, 105, 111, 110, 95, 102, 117, 110, 99, 116, 105, 111, 110, 0,
- 112, 97, 100, 95, 118, 97, 108, 117, 101, 115, 0, 112, 97, 100, 100, 105, 110, 103, 0,
- 115, 116, 114, 105, 100, 101, 95, 104, 101, 105, 103, 104, 116, 0,
- 115, 116, 114, 105, 100, 101, 95, 119, 105, 100, 116, 104, 0,
- 8, 130, 119, 97, 76, 51, 41, 34, 21, 8, 1, 8, 64, 1, 1, 1, 1, 0, 1, 1, 4, 4, 4, 4, 4, 4, 4, 4, 16, 36, 1];
+ test('bug where offest were stored as int instead of uint', () {
+ const data = [
+ 99,
+ 104,
+ 97,
+ 110,
+ 110,
+ 101,
+ 108,
+ 115,
+ 95,
+ 105,
+ 110,
+ 0,
+ 100,
+ 105,
+ 108,
+ 97,
+ 116,
+ 105,
+ 111,
+ 110,
+ 95,
+ 104,
+ 101,
+ 105,
+ 103,
+ 104,
+ 116,
+ 95,
+ 102,
+ 97,
+ 99,
+ 116,
+ 111,
+ 114,
+ 0,
+ 100,
+ 105,
+ 108,
+ 97,
+ 116,
+ 105,
+ 111,
+ 110,
+ 95,
+ 119,
+ 105,
+ 100,
+ 116,
+ 104,
+ 95,
+ 102,
+ 97,
+ 99,
+ 116,
+ 111,
+ 114,
+ 0,
+ 102,
+ 117,
+ 115,
+ 101,
+ 100,
+ 95,
+ 97,
+ 99,
+ 116,
+ 105,
+ 118,
+ 97,
+ 116,
+ 105,
+ 111,
+ 110,
+ 95,
+ 102,
+ 117,
+ 110,
+ 99,
+ 116,
+ 105,
+ 111,
+ 110,
+ 0,
+ 112,
+ 97,
+ 100,
+ 95,
+ 118,
+ 97,
+ 108,
+ 117,
+ 101,
+ 115,
+ 0,
+ 112,
+ 97,
+ 100,
+ 100,
+ 105,
+ 110,
+ 103,
+ 0,
+ 115,
+ 116,
+ 114,
+ 105,
+ 100,
+ 101,
+ 95,
+ 104,
+ 101,
+ 105,
+ 103,
+ 104,
+ 116,
+ 0,
+ 115,
+ 116,
+ 114,
+ 105,
+ 100,
+ 101,
+ 95,
+ 119,
+ 105,
+ 100,
+ 116,
+ 104,
+ 0,
+ 8,
+ 130,
+ 119,
+ 97,
+ 76,
+ 51,
+ 41,
+ 34,
+ 21,
+ 8,
+ 1,
+ 8,
+ 64,
+ 1,
+ 1,
+ 1,
+ 1,
+ 0,
+ 1,
+ 1,
+ 4,
+ 4,
+ 4,
+ 4,
+ 4,
+ 4,
+ 4,
+ 4,
+ 16,
+ 36,
+ 1
+ ];
var flx = Reference.fromBuffer(b(data));
- expect(flx.json, '{"channels_in":64,"dilation_height_factor":1,"dilation_width_factor":1,"fused_activation_function":1,"pad_values":1,"padding":0,"stride_height":1,"stride_width":1}');
- const object = {"channels_in":64,"dilation_height_factor":1,"dilation_width_factor":1,"fused_activation_function":1,"pad_values":1,"padding":0,"stride_height":1,"stride_width":1};
+ expect(flx.json,
+ '{"channels_in":64,"dilation_height_factor":1,"dilation_width_factor":1,"fused_activation_function":1,"pad_values":1,"padding":0,"stride_height":1,"stride_width":1}');
+ const object = {
+ "channels_in": 64,
+ "dilation_height_factor": 1,
+ "dilation_width_factor": 1,
+ "fused_activation_function": 1,
+ "pad_values": 1,
+ "padding": 0,
+ "stride_height": 1,
+ "stride_width": 1
+ };
var data1 = Builder.buildFromObject(object).asUint8List();
expect(data1.length, data.length);
var flx1 = Reference.fromBuffer(b(data1));
- expect(flx1.json, '{"channels_in":64,"dilation_height_factor":1,"dilation_width_factor":1,"fused_activation_function":1,"pad_values":1,"padding":0,"stride_height":1,"stride_width":1}');
+ expect(flx1.json,
+ '{"channels_in":64,"dilation_height_factor":1,"dilation_width_factor":1,"fused_activation_function":1,"pad_values":1,"padding":0,"stride_height":1,"stride_width":1}');
});
}
@@ -302,7 +833,7 @@
}
}
-Reference complexMap(){
+Reference complexMap() {
// {
// "age": 35,
// "flags": [True, False, True, True],
@@ -315,20 +846,145 @@
// }
// }
return Reference.fromBuffer(b([
- 97, 100, 100, 114, 101, 115, 115, 0,
- 99, 105, 116, 121, 0, 3, 66, 108, 97, 0,
- 99, 111, 117, 110, 116, 114, 121, 67, 111, 100, 101, 0,
- 2, 88, 88, 0,
- 122, 105, 112, 0,
- 5, 49, 50, 51, 52, 53, 0,
- 3, 38, 29, 14, 3, 1, 3, 38, 22, 15, 20, 20, 20,
- 97, 103, 101, 0,
- 102, 108, 97, 103, 115, 0,
- 4, 1, 0, 1, 1,
- 110, 97, 109, 101, 0,
- 5, 77, 97, 120, 105, 109, 0,
- 119, 101, 105, 103, 104, 116, 0,
- 5, 93, 36, 33, 23, 12, 0, 0, 7, 0, 0, 0, 1, 0, 0, 0, 5, 0, 0, 0, 60, 0, 0, 0, 35, 0, 0, 0, 51, 0, 0, 0, 45,
- 0, 0, 0, 0, 0, 145, 66, 36, 4, 144, 20, 14, 25, 38, 1
+ 97,
+ 100,
+ 100,
+ 114,
+ 101,
+ 115,
+ 115,
+ 0,
+ 99,
+ 105,
+ 116,
+ 121,
+ 0,
+ 3,
+ 66,
+ 108,
+ 97,
+ 0,
+ 99,
+ 111,
+ 117,
+ 110,
+ 116,
+ 114,
+ 121,
+ 67,
+ 111,
+ 100,
+ 101,
+ 0,
+ 2,
+ 88,
+ 88,
+ 0,
+ 122,
+ 105,
+ 112,
+ 0,
+ 5,
+ 49,
+ 50,
+ 51,
+ 52,
+ 53,
+ 0,
+ 3,
+ 38,
+ 29,
+ 14,
+ 3,
+ 1,
+ 3,
+ 38,
+ 22,
+ 15,
+ 20,
+ 20,
+ 20,
+ 97,
+ 103,
+ 101,
+ 0,
+ 102,
+ 108,
+ 97,
+ 103,
+ 115,
+ 0,
+ 4,
+ 1,
+ 0,
+ 1,
+ 1,
+ 110,
+ 97,
+ 109,
+ 101,
+ 0,
+ 5,
+ 77,
+ 97,
+ 120,
+ 105,
+ 109,
+ 0,
+ 119,
+ 101,
+ 105,
+ 103,
+ 104,
+ 116,
+ 0,
+ 5,
+ 93,
+ 36,
+ 33,
+ 23,
+ 12,
+ 0,
+ 0,
+ 7,
+ 0,
+ 0,
+ 0,
+ 1,
+ 0,
+ 0,
+ 0,
+ 5,
+ 0,
+ 0,
+ 0,
+ 60,
+ 0,
+ 0,
+ 0,
+ 35,
+ 0,
+ 0,
+ 0,
+ 51,
+ 0,
+ 0,
+ 0,
+ 45,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 145,
+ 66,
+ 36,
+ 4,
+ 144,
+ 20,
+ 14,
+ 25,
+ 38,
+ 1
]));
}
diff --git a/dart/test/flex_types_test.dart b/dart/test/flex_types_test.dart
index 16235f6..76ce070 100644
--- a/dart/test/flex_types_test.dart
+++ b/dart/test/flex_types_test.dart
@@ -48,69 +48,116 @@
expect(ValueTypeUtils.isFixedTypedVector(ValueType.VectorInt), isFalse);
});
test('to typed vector', () {
- expect(ValueTypeUtils.toTypedVector(ValueType.Int,0), equals(ValueType.VectorInt));
- expect(ValueTypeUtils.toTypedVector(ValueType.UInt,0), equals(ValueType.VectorUInt));
- expect(ValueTypeUtils.toTypedVector(ValueType.Bool,0), equals(ValueType.VectorBool));
- expect(ValueTypeUtils.toTypedVector(ValueType.Float,0), equals(ValueType.VectorFloat));
- expect(ValueTypeUtils.toTypedVector(ValueType.Key,0), equals(ValueType.VectorKey));
- expect(ValueTypeUtils.toTypedVector(ValueType.String,0), equals(ValueType.VectorString));
+ expect(ValueTypeUtils.toTypedVector(ValueType.Int, 0),
+ equals(ValueType.VectorInt));
+ expect(ValueTypeUtils.toTypedVector(ValueType.UInt, 0),
+ equals(ValueType.VectorUInt));
+ expect(ValueTypeUtils.toTypedVector(ValueType.Bool, 0),
+ equals(ValueType.VectorBool));
+ expect(ValueTypeUtils.toTypedVector(ValueType.Float, 0),
+ equals(ValueType.VectorFloat));
+ expect(ValueTypeUtils.toTypedVector(ValueType.Key, 0),
+ equals(ValueType.VectorKey));
+ expect(ValueTypeUtils.toTypedVector(ValueType.String, 0),
+ equals(ValueType.VectorString));
- expect(ValueTypeUtils.toTypedVector(ValueType.Int,2), equals(ValueType.VectorInt2));
- expect(ValueTypeUtils.toTypedVector(ValueType.UInt,2), equals(ValueType.VectorUInt2));
- expect(ValueTypeUtils.toTypedVector(ValueType.Float,2), equals(ValueType.VectorFloat2));
+ expect(ValueTypeUtils.toTypedVector(ValueType.Int, 2),
+ equals(ValueType.VectorInt2));
+ expect(ValueTypeUtils.toTypedVector(ValueType.UInt, 2),
+ equals(ValueType.VectorUInt2));
+ expect(ValueTypeUtils.toTypedVector(ValueType.Float, 2),
+ equals(ValueType.VectorFloat2));
- expect(ValueTypeUtils.toTypedVector(ValueType.Int,3), equals(ValueType.VectorInt3));
- expect(ValueTypeUtils.toTypedVector(ValueType.UInt,3), equals(ValueType.VectorUInt3));
- expect(ValueTypeUtils.toTypedVector(ValueType.Float,3), equals(ValueType.VectorFloat3));
+ expect(ValueTypeUtils.toTypedVector(ValueType.Int, 3),
+ equals(ValueType.VectorInt3));
+ expect(ValueTypeUtils.toTypedVector(ValueType.UInt, 3),
+ equals(ValueType.VectorUInt3));
+ expect(ValueTypeUtils.toTypedVector(ValueType.Float, 3),
+ equals(ValueType.VectorFloat3));
- expect(ValueTypeUtils.toTypedVector(ValueType.Int,4), equals(ValueType.VectorInt4));
- expect(ValueTypeUtils.toTypedVector(ValueType.UInt,4), equals(ValueType.VectorUInt4));
- expect(ValueTypeUtils.toTypedVector(ValueType.Float,4), equals(ValueType.VectorFloat4));
+ expect(ValueTypeUtils.toTypedVector(ValueType.Int, 4),
+ equals(ValueType.VectorInt4));
+ expect(ValueTypeUtils.toTypedVector(ValueType.UInt, 4),
+ equals(ValueType.VectorUInt4));
+ expect(ValueTypeUtils.toTypedVector(ValueType.Float, 4),
+ equals(ValueType.VectorFloat4));
});
test('typed vector element type', () {
- expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorInt), equals(ValueType.Int));
- expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorUInt), equals(ValueType.UInt));
- expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorFloat), equals(ValueType.Float));
- expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorString), equals(ValueType.String));
- expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorKey), equals(ValueType.Key));
- expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorBool), equals(ValueType.Bool));
+ expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorInt),
+ equals(ValueType.Int));
+ expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorUInt),
+ equals(ValueType.UInt));
+ expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorFloat),
+ equals(ValueType.Float));
+ expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorString),
+ equals(ValueType.String));
+ expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorKey),
+ equals(ValueType.Key));
+ expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorBool),
+ equals(ValueType.Bool));
});
test('fixed typed vector element type', () {
- expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorInt2), equals(ValueType.Int));
- expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorInt3), equals(ValueType.Int));
- expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorInt4), equals(ValueType.Int));
+ expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorInt2),
+ equals(ValueType.Int));
+ expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorInt3),
+ equals(ValueType.Int));
+ expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorInt4),
+ equals(ValueType.Int));
- expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorUInt2), equals(ValueType.UInt));
- expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorUInt3), equals(ValueType.UInt));
- expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorUInt4), equals(ValueType.UInt));
+ expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorUInt2),
+ equals(ValueType.UInt));
+ expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorUInt3),
+ equals(ValueType.UInt));
+ expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorUInt4),
+ equals(ValueType.UInt));
- expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorFloat2), equals(ValueType.Float));
- expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorFloat3), equals(ValueType.Float));
- expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorFloat4), equals(ValueType.Float));
+ expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorFloat2),
+ equals(ValueType.Float));
+ expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorFloat3),
+ equals(ValueType.Float));
+ expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorFloat4),
+ equals(ValueType.Float));
});
test('fixed typed vector element size', () {
- expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorInt2), equals(2));
- expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorInt3), equals(3));
- expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorInt4), equals(4));
+ expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorInt2),
+ equals(2));
+ expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorInt3),
+ equals(3));
+ expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorInt4),
+ equals(4));
- expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorUInt2), equals(2));
- expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorUInt3), equals(3));
- expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorUInt4), equals(4));
+ expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorUInt2),
+ equals(2));
+ expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorUInt3),
+ equals(3));
+ expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorUInt4),
+ equals(4));
- expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorFloat2), equals(2));
- expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorFloat3), equals(3));
- expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorFloat4), equals(4));
+ expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorFloat2),
+ equals(2));
+ expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorFloat3),
+ equals(3));
+ expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorFloat4),
+ equals(4));
});
test('packed type', () {
- expect(ValueTypeUtils.packedType(ValueType.Null, BitWidth.width8), equals(0));
- expect(ValueTypeUtils.packedType(ValueType.Null, BitWidth.width16), equals(1));
- expect(ValueTypeUtils.packedType(ValueType.Null, BitWidth.width32), equals(2));
- expect(ValueTypeUtils.packedType(ValueType.Null, BitWidth.width64), equals(3));
+ expect(
+ ValueTypeUtils.packedType(ValueType.Null, BitWidth.width8), equals(0));
+ expect(
+ ValueTypeUtils.packedType(ValueType.Null, BitWidth.width16), equals(1));
+ expect(
+ ValueTypeUtils.packedType(ValueType.Null, BitWidth.width32), equals(2));
+ expect(
+ ValueTypeUtils.packedType(ValueType.Null, BitWidth.width64), equals(3));
- expect(ValueTypeUtils.packedType(ValueType.Int, BitWidth.width8), equals(4));
- expect(ValueTypeUtils.packedType(ValueType.Int, BitWidth.width16), equals(5));
- expect(ValueTypeUtils.packedType(ValueType.Int, BitWidth.width32), equals(6));
- expect(ValueTypeUtils.packedType(ValueType.Int, BitWidth.width64), equals(7));
+ expect(
+ ValueTypeUtils.packedType(ValueType.Int, BitWidth.width8), equals(4));
+ expect(
+ ValueTypeUtils.packedType(ValueType.Int, BitWidth.width16), equals(5));
+ expect(
+ ValueTypeUtils.packedType(ValueType.Int, BitWidth.width32), equals(6));
+ expect(
+ ValueTypeUtils.packedType(ValueType.Int, BitWidth.width64), equals(7));
});
test('bit width', () {
expect(BitWidthUtil.width(0), BitWidth.width8);
diff --git a/dart/test/monster_test.fbs b/dart/test/monster_test.fbs
new file mode 100644
index 0000000..fdd5acf
--- /dev/null
+++ b/dart/test/monster_test.fbs
@@ -0,0 +1,154 @@
+// test schema file
+
+include "include_test1.fbs";
+
+namespace MyGame;
+
+table InParentNamespace {}
+
+namespace MyGame.Example2;
+
+table Monster {} // Test having same name as below, but in different namespace.
+
+namespace MyGame.Example;
+
+attribute "priority";
+
+/// Composite components of Monster color.
+enum Color:ubyte (bit_flags) {
+ Red = 0, // color Red = (1u << 0)
+ /// \brief color Green
+ /// Green is bit_flag with value (1u << 1)
+ Green,
+ /// \brief color Blue (1u << 3)
+ Blue = 3,
+}
+
+enum Race:byte {
+ None = -1,
+ Human = 0,
+ Dwarf,
+ Elf,
+}
+
+union Any { Monster, TestSimpleTableWithEnum, MyGame.Example2.Monster }
+
+union AnyUniqueAliases { M: Monster, TS: TestSimpleTableWithEnum, M2: MyGame.Example2.Monster }
+union AnyAmbiguousAliases { M1: Monster, M2: Monster, M3: Monster }
+
+struct Test { a:short; b:byte; }
+
+table TestSimpleTableWithEnum (csharp_partial, private) {
+ color: Color = Green;
+}
+
+struct Vec3 (force_align: 8) {
+ x:float;
+ y:float;
+ z:float;
+ test1:double;
+ test2:Color;
+ test3:Test;
+}
+
+struct Ability {
+ id:uint(key);
+ distance:uint;
+}
+
+struct StructOfStructs {
+ a: Ability;
+ b: Test;
+ c: Ability;
+}
+
+table Stat {
+ id:string;
+ val:long;
+ count:ushort (key);
+}
+
+table Referrable {
+ id:ulong(key, hash:"fnv1a_64");
+}
+
+/// an example documentation comment: "monster object"
+table Monster {
+ pos:Vec3 (id: 0);
+ hp:short = 100 (id: 2);
+ mana:short = 150 (id: 1);
+ name:string (id: 3, key);
+ color:Color = Blue (id: 6);
+ inventory:[ubyte] (id: 5);
+ friendly:bool = false (deprecated, priority: 1, id: 4);
+ /// an example documentation comment: this will end up in the generated code
+ /// multiline too
+ testarrayoftables:[Monster] (id: 11);
+ testarrayofstring:[string] (id: 10);
+ testarrayofstring2:[string] (id: 28);
+ testarrayofbools:[bool] (id: 24);
+ testarrayofsortedstruct:[Ability] (id: 29);
+ enemy:MyGame.Example.Monster (id:12); // Test referring by full namespace.
+ test:Any (id: 8);
+ test4:[Test] (id: 9);
+ test5:[Test] (id: 31);
+ testnestedflatbuffer:[ubyte] (id:13, nested_flatbuffer: "Monster");
+ testempty:Stat (id:14);
+ testbool:bool (id:15);
+ testhashs32_fnv1:int (id:16, hash:"fnv1_32");
+ testhashu32_fnv1:uint (id:17, hash:"fnv1_32");
+ testhashs64_fnv1:long (id:18, hash:"fnv1_64");
+ testhashu64_fnv1:ulong (id:19, hash:"fnv1_64");
+ testhashs32_fnv1a:int (id:20, hash:"fnv1a_32");
+ testhashu32_fnv1a:uint (id:21, hash:"fnv1a_32", cpp_type:"Stat");
+ testhashs64_fnv1a:long (id:22, hash:"fnv1a_64");
+ testhashu64_fnv1a:ulong (id:23, hash:"fnv1a_64");
+ testf:float = 3.14159 (id:25);
+ testf2:float = 3 (id:26);
+ testf3:float (id:27);
+ flex:[ubyte] (id:30, flexbuffer);
+ vector_of_longs:[long] (id:32);
+ vector_of_doubles:[double] (id:33);
+ parent_namespace_test:InParentNamespace (id:34);
+ vector_of_referrables:[Referrable](id:35);
+ single_weak_reference:ulong(id:36, hash:"fnv1a_64", cpp_type:"ReferrableT");
+ vector_of_weak_references:[ulong](id:37, hash:"fnv1a_64", cpp_type:"ReferrableT");
+ vector_of_strong_referrables:[Referrable](id:38, cpp_ptr_type:"default_ptr_type"); //was shared_ptr
+ co_owning_reference:ulong(id:39, hash:"fnv1a_64", cpp_type:"ReferrableT", cpp_ptr_type:"naked"); //was shared_ptr as well
+ vector_of_co_owning_references:[ulong](id:40, hash:"fnv1a_64", cpp_type:"ReferrableT", cpp_ptr_type:"default_ptr_type", cpp_ptr_type_get:".get()"); //was shared_ptr
+ non_owning_reference:ulong(id:41, hash:"fnv1a_64", cpp_type:"ReferrableT", cpp_ptr_type:"naked", cpp_ptr_type_get:""); //was weak_ptr
+ vector_of_non_owning_references:[ulong](id:42, hash:"fnv1a_64", cpp_type:"ReferrableT", cpp_ptr_type:"naked", cpp_ptr_type_get:""); //was weak_ptr
+ any_unique:AnyUniqueAliases(id:44);
+ any_ambiguous:AnyAmbiguousAliases (id:46);
+ vector_of_enums:[Color] (id:47);
+ signed_enum:Race = None (id:48);
+ testrequirednestedflatbuffer:[ubyte] (id:49, nested_flatbuffer: "Monster");
+ scalar_key_sorted_tables:[Stat] (id: 50);
+}
+
+table TypeAliases {
+ i8:int8;
+ u8:uint8;
+ i16:int16;
+ u16:uint16;
+ i32:int32;
+ u32:uint32;
+ i64:int64;
+ u64:uint64;
+ f32:float32;
+ f64:float64;
+ v8:[int8];
+ vf64:[float64];
+}
+
+rpc_service MonsterStorage {
+ Store(Monster):Stat (streaming: "none");
+ Retrieve(Stat):Monster (streaming: "server", idempotent);
+ GetMaxHitPoint(Monster):Stat (streaming: "client");
+ GetMinMaxHitPoints(Monster):Stat (streaming: "bidi");
+}
+
+root_type Monster;
+
+file_identifier "MONS";
+file_extension "mon";
diff --git a/dart/test/monster_test_my_game.example2_generated.dart b/dart/test/monster_test_my_game.example2_generated.dart
index eed14bc..24ccf72 100644
--- a/dart/test/monster_test_my_game.example2_generated.dart
+++ b/dart/test/monster_test_my_game.example2_generated.dart
@@ -1,5 +1,5 @@
// automatically generated by the FlatBuffers compiler, do not modify
-// ignore_for_file: unused_import, unused_field, unused_local_variable
+// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable
library my_game.example2;
@@ -12,11 +12,11 @@
class Monster {
Monster._(this._bc, this._bcOffset);
factory Monster(List<int> bytes) {
- fb.BufferContext rootRef = new fb.BufferContext.fromBytes(bytes);
+ final rootRef = fb.BufferContext.fromBytes(bytes);
return reader.read(rootRef, 0);
}
- static const fb.Reader<Monster> reader = const _MonsterReader();
+ static const fb.Reader<Monster> reader = _MonsterReader();
final fb.BufferContext _bc;
final int _bcOffset;
@@ -26,6 +26,26 @@
String toString() {
return 'Monster{}';
}
+
+ MonsterT unpack() => MonsterT();
+
+ static int pack(fb.Builder fbBuilder, MonsterT? object) {
+ if (object == null) return 0;
+ return object.pack(fbBuilder);
+ }
+}
+
+class MonsterT implements fb.Packable {
+ @override
+ int pack(fb.Builder fbBuilder) {
+ fbBuilder.startTable(0);
+ return fbBuilder.endTable();
+ }
+
+ @override
+ String toString() {
+ return 'MonsterT{}';
+ }
}
class _MonsterReader extends fb.TableReader<Monster> {
@@ -33,7 +53,7 @@
@override
Monster createObject(fb.BufferContext bc, int offset) =>
- new Monster._(bc, offset);
+ Monster._(bc, offset);
}
class MonsterObjectBuilder extends fb.ObjectBuilder {
@@ -42,19 +62,16 @@
/// Finish building, and store into the [fbBuilder].
@override
- int finish(
- fb.Builder fbBuilder) {
- assert(fbBuilder != null);
-
- fbBuilder.startTable();
+ int finish(fb.Builder fbBuilder) {
+ fbBuilder.startTable(0);
return fbBuilder.endTable();
}
/// Convenience method to serialize to byte list.
@override
- Uint8List toBytes([String fileIdentifier]) {
- fb.Builder fbBuilder = new fb.Builder();
- int offset = finish(fbBuilder);
- return fbBuilder.finish(offset, fileIdentifier);
+ Uint8List toBytes([String? fileIdentifier]) {
+ final fbBuilder = fb.Builder(deduplicateTables: false);
+ fbBuilder.finish(finish(fbBuilder), fileIdentifier);
+ return fbBuilder.buffer;
}
}
diff --git a/dart/test/monster_test_my_game.example_generated.dart b/dart/test/monster_test_my_game.example_generated.dart
index 7921892..8db82e3 100644
--- a/dart/test/monster_test_my_game.example_generated.dart
+++ b/dart/test/monster_test_my_game.example_generated.dart
@@ -1,5 +1,5 @@
// automatically generated by the FlatBuffers compiler, do not modify
-// ignore_for_file: unused_import, unused_field, unused_local_variable
+// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable
library my_game.example;
@@ -15,26 +15,32 @@
const Color._(this.value);
factory Color.fromValue(int value) {
- if (value == null) value = 0;
- if (!values.containsKey(value)) {
- throw new StateError('Invalid value $value for bit flag enum Color');
+ final result = values[value];
+ if (result == null) {
+ throw StateError('Invalid value $value for bit flag enum Color');
}
- return values[value];
+ return result;
}
+ static Color? _createOrNull(int? value) =>
+ value == null ? null : Color.fromValue(value);
+
static bool containsValue(int value) => values.containsKey(value);
- static const Color Red = const Color._(1);
+ static const Color Red = Color._(1);
/// \brief color Green
/// Green is bit_flag with value (1u << 1)
- static const Color Green = const Color._(2);
+ static const Color Green = Color._(2);
/// \brief color Blue (1u << 3)
- static const Color Blue = const Color._(8);
- static const values = {1: Red,2: Green,8: Blue,};
+ static const Color Blue = Color._(8);
+ static const Map<int, Color> values = {
+ 1: Red,
+ 2: Green,
+ 8: Blue};
- static const fb.Reader<Color> reader = const _ColorReader();
+ static const fb.Reader<Color> reader = _ColorReader();
@override
String toString() {
@@ -50,7 +56,7 @@
@override
Color read(fb.BufferContext bc, int offset) =>
- new Color.fromValue(const fb.Uint8Reader().read(bc, offset));
+ Color.fromValue(const fb.Uint8Reader().read(bc, offset));
}
class Race {
@@ -58,24 +64,31 @@
const Race._(this.value);
factory Race.fromValue(int value) {
- if (value == null) value = 0;
- if (!values.containsKey(value)) {
- throw new StateError('Invalid value $value for bit flag enum Race');
+ final result = values[value];
+ if (result == null) {
+ throw StateError('Invalid value $value for bit flag enum Race');
}
- return values[value];
+ return result;
}
+ static Race? _createOrNull(int? value) =>
+ value == null ? null : Race.fromValue(value);
+
static const int minValue = -1;
static const int maxValue = 2;
static bool containsValue(int value) => values.containsKey(value);
- static const Race None = const Race._(-1);
- static const Race Human = const Race._(0);
- static const Race Dwarf = const Race._(1);
- static const Race Elf = const Race._(2);
- static const values = {-1: None,0: Human,1: Dwarf,2: Elf,};
+ static const Race None = Race._(-1);
+ static const Race Human = Race._(0);
+ static const Race Dwarf = Race._(1);
+ static const Race Elf = Race._(2);
+ static const Map<int, Race> values = {
+ -1: None,
+ 0: Human,
+ 1: Dwarf,
+ 2: Elf};
- static const fb.Reader<Race> reader = const _RaceReader();
+ static const fb.Reader<Race> reader = _RaceReader();
@override
String toString() {
@@ -91,7 +104,7 @@
@override
Race read(fb.BufferContext bc, int offset) =>
- new Race.fromValue(const fb.Int8Reader().read(bc, offset));
+ Race.fromValue(const fb.Int8Reader().read(bc, offset));
}
class AnyTypeId {
@@ -99,24 +112,31 @@
const AnyTypeId._(this.value);
factory AnyTypeId.fromValue(int value) {
- if (value == null) value = 0;
- if (!values.containsKey(value)) {
- throw new StateError('Invalid value $value for bit flag enum AnyTypeId');
+ final result = values[value];
+ if (result == null) {
+ throw StateError('Invalid value $value for bit flag enum AnyTypeId');
}
- return values[value];
+ return result;
}
+ static AnyTypeId? _createOrNull(int? value) =>
+ value == null ? null : AnyTypeId.fromValue(value);
+
static const int minValue = 0;
static const int maxValue = 3;
static bool containsValue(int value) => values.containsKey(value);
- static const AnyTypeId NONE = const AnyTypeId._(0);
- static const AnyTypeId Monster = const AnyTypeId._(1);
- static const AnyTypeId TestSimpleTableWithEnum = const AnyTypeId._(2);
- static const AnyTypeId MyGame_Example2_Monster = const AnyTypeId._(3);
- static const values = {0: NONE,1: Monster,2: TestSimpleTableWithEnum,3: MyGame_Example2_Monster,};
+ static const AnyTypeId NONE = AnyTypeId._(0);
+ static const AnyTypeId Monster = AnyTypeId._(1);
+ static const AnyTypeId TestSimpleTableWithEnum = AnyTypeId._(2);
+ static const AnyTypeId MyGame_Example2_Monster = AnyTypeId._(3);
+ static const Map<int, AnyTypeId> values = {
+ 0: NONE,
+ 1: Monster,
+ 2: TestSimpleTableWithEnum,
+ 3: MyGame_Example2_Monster};
- static const fb.Reader<AnyTypeId> reader = const _AnyTypeIdReader();
+ static const fb.Reader<AnyTypeId> reader = _AnyTypeIdReader();
@override
String toString() {
@@ -132,7 +152,7 @@
@override
AnyTypeId read(fb.BufferContext bc, int offset) =>
- new AnyTypeId.fromValue(const fb.Uint8Reader().read(bc, offset));
+ AnyTypeId.fromValue(const fb.Uint8Reader().read(bc, offset));
}
class AnyUniqueAliasesTypeId {
@@ -140,24 +160,31 @@
const AnyUniqueAliasesTypeId._(this.value);
factory AnyUniqueAliasesTypeId.fromValue(int value) {
- if (value == null) value = 0;
- if (!values.containsKey(value)) {
- throw new StateError('Invalid value $value for bit flag enum AnyUniqueAliasesTypeId');
+ final result = values[value];
+ if (result == null) {
+ throw StateError('Invalid value $value for bit flag enum AnyUniqueAliasesTypeId');
}
- return values[value];
+ return result;
}
+ static AnyUniqueAliasesTypeId? _createOrNull(int? value) =>
+ value == null ? null : AnyUniqueAliasesTypeId.fromValue(value);
+
static const int minValue = 0;
static const int maxValue = 3;
static bool containsValue(int value) => values.containsKey(value);
- static const AnyUniqueAliasesTypeId NONE = const AnyUniqueAliasesTypeId._(0);
- static const AnyUniqueAliasesTypeId M = const AnyUniqueAliasesTypeId._(1);
- static const AnyUniqueAliasesTypeId TS = const AnyUniqueAliasesTypeId._(2);
- static const AnyUniqueAliasesTypeId M2 = const AnyUniqueAliasesTypeId._(3);
- static const values = {0: NONE,1: M,2: TS,3: M2,};
+ static const AnyUniqueAliasesTypeId NONE = AnyUniqueAliasesTypeId._(0);
+ static const AnyUniqueAliasesTypeId M = AnyUniqueAliasesTypeId._(1);
+ static const AnyUniqueAliasesTypeId TS = AnyUniqueAliasesTypeId._(2);
+ static const AnyUniqueAliasesTypeId M2 = AnyUniqueAliasesTypeId._(3);
+ static const Map<int, AnyUniqueAliasesTypeId> values = {
+ 0: NONE,
+ 1: M,
+ 2: TS,
+ 3: M2};
- static const fb.Reader<AnyUniqueAliasesTypeId> reader = const _AnyUniqueAliasesTypeIdReader();
+ static const fb.Reader<AnyUniqueAliasesTypeId> reader = _AnyUniqueAliasesTypeIdReader();
@override
String toString() {
@@ -173,7 +200,7 @@
@override
AnyUniqueAliasesTypeId read(fb.BufferContext bc, int offset) =>
- new AnyUniqueAliasesTypeId.fromValue(const fb.Uint8Reader().read(bc, offset));
+ AnyUniqueAliasesTypeId.fromValue(const fb.Uint8Reader().read(bc, offset));
}
class AnyAmbiguousAliasesTypeId {
@@ -181,24 +208,31 @@
const AnyAmbiguousAliasesTypeId._(this.value);
factory AnyAmbiguousAliasesTypeId.fromValue(int value) {
- if (value == null) value = 0;
- if (!values.containsKey(value)) {
- throw new StateError('Invalid value $value for bit flag enum AnyAmbiguousAliasesTypeId');
+ final result = values[value];
+ if (result == null) {
+ throw StateError('Invalid value $value for bit flag enum AnyAmbiguousAliasesTypeId');
}
- return values[value];
+ return result;
}
+ static AnyAmbiguousAliasesTypeId? _createOrNull(int? value) =>
+ value == null ? null : AnyAmbiguousAliasesTypeId.fromValue(value);
+
static const int minValue = 0;
static const int maxValue = 3;
static bool containsValue(int value) => values.containsKey(value);
- static const AnyAmbiguousAliasesTypeId NONE = const AnyAmbiguousAliasesTypeId._(0);
- static const AnyAmbiguousAliasesTypeId M1 = const AnyAmbiguousAliasesTypeId._(1);
- static const AnyAmbiguousAliasesTypeId M2 = const AnyAmbiguousAliasesTypeId._(2);
- static const AnyAmbiguousAliasesTypeId M3 = const AnyAmbiguousAliasesTypeId._(3);
- static const values = {0: NONE,1: M1,2: M2,3: M3,};
+ static const AnyAmbiguousAliasesTypeId NONE = AnyAmbiguousAliasesTypeId._(0);
+ static const AnyAmbiguousAliasesTypeId M1 = AnyAmbiguousAliasesTypeId._(1);
+ static const AnyAmbiguousAliasesTypeId M2 = AnyAmbiguousAliasesTypeId._(2);
+ static const AnyAmbiguousAliasesTypeId M3 = AnyAmbiguousAliasesTypeId._(3);
+ static const Map<int, AnyAmbiguousAliasesTypeId> values = {
+ 0: NONE,
+ 1: M1,
+ 2: M2,
+ 3: M3};
- static const fb.Reader<AnyAmbiguousAliasesTypeId> reader = const _AnyAmbiguousAliasesTypeIdReader();
+ static const fb.Reader<AnyAmbiguousAliasesTypeId> reader = _AnyAmbiguousAliasesTypeIdReader();
@override
String toString() {
@@ -214,13 +248,13 @@
@override
AnyAmbiguousAliasesTypeId read(fb.BufferContext bc, int offset) =>
- new AnyAmbiguousAliasesTypeId.fromValue(const fb.Uint8Reader().read(bc, offset));
+ AnyAmbiguousAliasesTypeId.fromValue(const fb.Uint8Reader().read(bc, offset));
}
class Test {
Test._(this._bc, this._bcOffset);
- static const fb.Reader<Test> reader = const _TestReader();
+ static const fb.Reader<Test> reader = _TestReader();
final fb.BufferContext _bc;
final int _bcOffset;
@@ -232,6 +266,37 @@
String toString() {
return 'Test{a: $a, b: $b}';
}
+
+ TestT unpack() => TestT(
+ a: a,
+ b: b);
+
+ static int pack(fb.Builder fbBuilder, TestT? object) {
+ if (object == null) return 0;
+ return object.pack(fbBuilder);
+ }
+}
+
+class TestT implements fb.Packable {
+ int a;
+ int b;
+
+ TestT({
+ required this.a,
+ required this.b});
+
+ @override
+ int pack(fb.Builder fbBuilder) {
+ fbBuilder.pad(1);
+ fbBuilder.putInt8(b);
+ fbBuilder.putInt16(a);
+ return fbBuilder.offset;
+ }
+
+ @override
+ String toString() {
+ return 'TestT{a: $a, b: $b}';
+ }
}
class _TestReader extends fb.StructReader<Test> {
@@ -242,13 +307,11 @@
@override
Test createObject(fb.BufferContext bc, int offset) =>
- new Test._(bc, offset);
+ Test._(bc, offset);
}
class TestBuilder {
- TestBuilder(this.fbBuilder) {
- assert(fbBuilder != null);
- }
+ TestBuilder(this.fbBuilder);
final fb.Builder fbBuilder;
@@ -266,18 +329,15 @@
final int _b;
TestObjectBuilder({
- int a,
- int b,
+ required int a,
+ required int b,
})
: _a = a,
_b = b;
/// Finish building, and store into the [fbBuilder].
@override
- int finish(
- fb.Builder fbBuilder) {
- assert(fbBuilder != null);
-
+ int finish(fb.Builder fbBuilder) {
fbBuilder.pad(1);
fbBuilder.putInt8(_b);
fbBuilder.putInt16(_a);
@@ -286,30 +346,57 @@
/// Convenience method to serialize to byte list.
@override
- Uint8List toBytes([String fileIdentifier]) {
- fb.Builder fbBuilder = new fb.Builder();
- int offset = finish(fbBuilder);
- return fbBuilder.finish(offset, fileIdentifier);
+ Uint8List toBytes([String? fileIdentifier]) {
+ final fbBuilder = fb.Builder(deduplicateTables: false);
+ fbBuilder.finish(finish(fbBuilder), fileIdentifier);
+ return fbBuilder.buffer;
}
}
class TestSimpleTableWithEnum {
TestSimpleTableWithEnum._(this._bc, this._bcOffset);
factory TestSimpleTableWithEnum(List<int> bytes) {
- fb.BufferContext rootRef = new fb.BufferContext.fromBytes(bytes);
+ final rootRef = fb.BufferContext.fromBytes(bytes);
return reader.read(rootRef, 0);
}
- static const fb.Reader<TestSimpleTableWithEnum> reader = const _TestSimpleTableWithEnumReader();
+ static const fb.Reader<TestSimpleTableWithEnum> reader = _TestSimpleTableWithEnumReader();
final fb.BufferContext _bc;
final int _bcOffset;
- Color get color => new Color.fromValue(const fb.Uint8Reader().vTableGet(_bc, _bcOffset, 4, 2));
+ Color get color => Color.fromValue(const fb.Uint8Reader().vTableGet(_bc, _bcOffset, 4, 2));
@override
String toString() {
return 'TestSimpleTableWithEnum{color: $color}';
}
+
+ TestSimpleTableWithEnumT unpack() => TestSimpleTableWithEnumT(
+ color: color);
+
+ static int pack(fb.Builder fbBuilder, TestSimpleTableWithEnumT? object) {
+ if (object == null) return 0;
+ return object.pack(fbBuilder);
+ }
+}
+
+class TestSimpleTableWithEnumT implements fb.Packable {
+ Color color;
+
+ TestSimpleTableWithEnumT({
+ this.color = Color.Green});
+
+ @override
+ int pack(fb.Builder fbBuilder) {
+ fbBuilder.startTable(1);
+ fbBuilder.addUint8(0, color.value);
+ return fbBuilder.endTable();
+ }
+
+ @override
+ String toString() {
+ return 'TestSimpleTableWithEnumT{color: $color}';
+ }
}
class _TestSimpleTableWithEnumReader extends fb.TableReader<TestSimpleTableWithEnum> {
@@ -317,21 +404,19 @@
@override
TestSimpleTableWithEnum createObject(fb.BufferContext bc, int offset) =>
- new TestSimpleTableWithEnum._(bc, offset);
+ TestSimpleTableWithEnum._(bc, offset);
}
class TestSimpleTableWithEnumBuilder {
- TestSimpleTableWithEnumBuilder(this.fbBuilder) {
- assert(fbBuilder != null);
- }
+ TestSimpleTableWithEnumBuilder(this.fbBuilder);
final fb.Builder fbBuilder;
void begin() {
- fbBuilder.startTable();
+ fbBuilder.startTable(1);
}
- int addColor(Color color) {
+ int addColor(Color? color) {
fbBuilder.addUint8(0, color?.value);
return fbBuilder.offset;
}
@@ -342,36 +427,33 @@
}
class TestSimpleTableWithEnumObjectBuilder extends fb.ObjectBuilder {
- final Color _color;
+ final Color? _color;
TestSimpleTableWithEnumObjectBuilder({
- Color color,
+ Color? color,
})
: _color = color;
/// Finish building, and store into the [fbBuilder].
@override
- int finish(
- fb.Builder fbBuilder) {
- assert(fbBuilder != null);
-
- fbBuilder.startTable();
+ int finish(fb.Builder fbBuilder) {
+ fbBuilder.startTable(1);
fbBuilder.addUint8(0, _color?.value);
return fbBuilder.endTable();
}
/// Convenience method to serialize to byte list.
@override
- Uint8List toBytes([String fileIdentifier]) {
- fb.Builder fbBuilder = new fb.Builder();
- int offset = finish(fbBuilder);
- return fbBuilder.finish(offset, fileIdentifier);
+ Uint8List toBytes([String? fileIdentifier]) {
+ final fbBuilder = fb.Builder(deduplicateTables: false);
+ fbBuilder.finish(finish(fbBuilder), fileIdentifier);
+ return fbBuilder.buffer;
}
}
class Vec3 {
Vec3._(this._bc, this._bcOffset);
- static const fb.Reader<Vec3> reader = const _Vec3Reader();
+ static const fb.Reader<Vec3> reader = _Vec3Reader();
final fb.BufferContext _bc;
final int _bcOffset;
@@ -380,13 +462,62 @@
double get y => const fb.Float32Reader().read(_bc, _bcOffset + 4);
double get z => const fb.Float32Reader().read(_bc, _bcOffset + 8);
double get test1 => const fb.Float64Reader().read(_bc, _bcOffset + 16);
- Color get test2 => new Color.fromValue(const fb.Uint8Reader().read(_bc, _bcOffset + 24));
+ Color get test2 => Color.fromValue(const fb.Uint8Reader().read(_bc, _bcOffset + 24));
Test get test3 => Test.reader.read(_bc, _bcOffset + 26);
@override
String toString() {
return 'Vec3{x: $x, y: $y, z: $z, test1: $test1, test2: $test2, test3: $test3}';
}
+
+ Vec3T unpack() => Vec3T(
+ x: x,
+ y: y,
+ z: z,
+ test1: test1,
+ test2: test2,
+ test3: test3.unpack());
+
+ static int pack(fb.Builder fbBuilder, Vec3T? object) {
+ if (object == null) return 0;
+ return object.pack(fbBuilder);
+ }
+}
+
+class Vec3T implements fb.Packable {
+ double x;
+ double y;
+ double z;
+ double test1;
+ Color test2;
+ TestT test3;
+
+ Vec3T({
+ required this.x,
+ required this.y,
+ required this.z,
+ required this.test1,
+ required this.test2,
+ required this.test3});
+
+ @override
+ int pack(fb.Builder fbBuilder) {
+ fbBuilder.pad(2);
+ test3.pack(fbBuilder);
+ fbBuilder.pad(1);
+ fbBuilder.putUint8(test2.value);
+ fbBuilder.putFloat64(test1);
+ fbBuilder.pad(4);
+ fbBuilder.putFloat32(z);
+ fbBuilder.putFloat32(y);
+ fbBuilder.putFloat32(x);
+ return fbBuilder.offset;
+ }
+
+ @override
+ String toString() {
+ return 'Vec3T{x: $x, y: $y, z: $z, test1: $test1, test2: $test2, test3: $test3}';
+ }
}
class _Vec3Reader extends fb.StructReader<Vec3> {
@@ -397,13 +528,11 @@
@override
Vec3 createObject(fb.BufferContext bc, int offset) =>
- new Vec3._(bc, offset);
+ Vec3._(bc, offset);
}
class Vec3Builder {
- Vec3Builder(this.fbBuilder) {
- assert(fbBuilder != null);
- }
+ Vec3Builder(this.fbBuilder);
final fb.Builder fbBuilder;
@@ -411,7 +540,7 @@
fbBuilder.pad(2);
test3();
fbBuilder.pad(1);
- fbBuilder.putUint8(test2?.value);
+ fbBuilder.putUint8(test2.value);
fbBuilder.putFloat64(test1);
fbBuilder.pad(4);
fbBuilder.putFloat32(z);
@@ -431,12 +560,12 @@
final TestObjectBuilder _test3;
Vec3ObjectBuilder({
- double x,
- double y,
- double z,
- double test1,
- Color test2,
- TestObjectBuilder test3,
+ required double x,
+ required double y,
+ required double z,
+ required double test1,
+ required Color test2,
+ required TestObjectBuilder test3,
})
: _x = x,
_y = y,
@@ -447,14 +576,11 @@
/// Finish building, and store into the [fbBuilder].
@override
- int finish(
- fb.Builder fbBuilder) {
- assert(fbBuilder != null);
-
+ int finish(fb.Builder fbBuilder) {
fbBuilder.pad(2);
_test3.finish(fbBuilder);
fbBuilder.pad(1);
- fbBuilder.putUint8(_test2?.value);
+ fbBuilder.putUint8(_test2.value);
fbBuilder.putFloat64(_test1);
fbBuilder.pad(4);
fbBuilder.putFloat32(_z);
@@ -465,16 +591,16 @@
/// Convenience method to serialize to byte list.
@override
- Uint8List toBytes([String fileIdentifier]) {
- fb.Builder fbBuilder = new fb.Builder();
- int offset = finish(fbBuilder);
- return fbBuilder.finish(offset, fileIdentifier);
+ Uint8List toBytes([String? fileIdentifier]) {
+ final fbBuilder = fb.Builder(deduplicateTables: false);
+ fbBuilder.finish(finish(fbBuilder), fileIdentifier);
+ return fbBuilder.buffer;
}
}
class Ability {
Ability._(this._bc, this._bcOffset);
- static const fb.Reader<Ability> reader = const _AbilityReader();
+ static const fb.Reader<Ability> reader = _AbilityReader();
final fb.BufferContext _bc;
final int _bcOffset;
@@ -486,6 +612,36 @@
String toString() {
return 'Ability{id: $id, distance: $distance}';
}
+
+ AbilityT unpack() => AbilityT(
+ id: id,
+ distance: distance);
+
+ static int pack(fb.Builder fbBuilder, AbilityT? object) {
+ if (object == null) return 0;
+ return object.pack(fbBuilder);
+ }
+}
+
+class AbilityT implements fb.Packable {
+ int id;
+ int distance;
+
+ AbilityT({
+ required this.id,
+ required this.distance});
+
+ @override
+ int pack(fb.Builder fbBuilder) {
+ fbBuilder.putUint32(distance);
+ fbBuilder.putUint32(id);
+ return fbBuilder.offset;
+ }
+
+ @override
+ String toString() {
+ return 'AbilityT{id: $id, distance: $distance}';
+ }
}
class _AbilityReader extends fb.StructReader<Ability> {
@@ -496,13 +652,11 @@
@override
Ability createObject(fb.BufferContext bc, int offset) =>
- new Ability._(bc, offset);
+ Ability._(bc, offset);
}
class AbilityBuilder {
- AbilityBuilder(this.fbBuilder) {
- assert(fbBuilder != null);
- }
+ AbilityBuilder(this.fbBuilder);
final fb.Builder fbBuilder;
@@ -519,18 +673,15 @@
final int _distance;
AbilityObjectBuilder({
- int id,
- int distance,
+ required int id,
+ required int distance,
})
: _id = id,
_distance = distance;
/// Finish building, and store into the [fbBuilder].
@override
- int finish(
- fb.Builder fbBuilder) {
- assert(fbBuilder != null);
-
+ int finish(fb.Builder fbBuilder) {
fbBuilder.putUint32(_distance);
fbBuilder.putUint32(_id);
return fbBuilder.offset;
@@ -538,25 +689,133 @@
/// Convenience method to serialize to byte list.
@override
- Uint8List toBytes([String fileIdentifier]) {
- fb.Builder fbBuilder = new fb.Builder();
- int offset = finish(fbBuilder);
- return fbBuilder.finish(offset, fileIdentifier);
+ Uint8List toBytes([String? fileIdentifier]) {
+ final fbBuilder = fb.Builder(deduplicateTables: false);
+ fbBuilder.finish(finish(fbBuilder), fileIdentifier);
+ return fbBuilder.buffer;
+ }
+}
+class StructOfStructs {
+ StructOfStructs._(this._bc, this._bcOffset);
+
+ static const fb.Reader<StructOfStructs> reader = _StructOfStructsReader();
+
+ final fb.BufferContext _bc;
+ final int _bcOffset;
+
+ Ability get a => Ability.reader.read(_bc, _bcOffset + 0);
+ Test get b => Test.reader.read(_bc, _bcOffset + 8);
+ Ability get c => Ability.reader.read(_bc, _bcOffset + 12);
+
+ @override
+ String toString() {
+ return 'StructOfStructs{a: $a, b: $b, c: $c}';
+ }
+
+ StructOfStructsT unpack() => StructOfStructsT(
+ a: a.unpack(),
+ b: b.unpack(),
+ c: c.unpack());
+
+ static int pack(fb.Builder fbBuilder, StructOfStructsT? object) {
+ if (object == null) return 0;
+ return object.pack(fbBuilder);
+ }
+}
+
+class StructOfStructsT implements fb.Packable {
+ AbilityT a;
+ TestT b;
+ AbilityT c;
+
+ StructOfStructsT({
+ required this.a,
+ required this.b,
+ required this.c});
+
+ @override
+ int pack(fb.Builder fbBuilder) {
+ c.pack(fbBuilder);
+ b.pack(fbBuilder);
+ a.pack(fbBuilder);
+ return fbBuilder.offset;
+ }
+
+ @override
+ String toString() {
+ return 'StructOfStructsT{a: $a, b: $b, c: $c}';
+ }
+}
+
+class _StructOfStructsReader extends fb.StructReader<StructOfStructs> {
+ const _StructOfStructsReader();
+
+ @override
+ int get size => 20;
+
+ @override
+ StructOfStructs createObject(fb.BufferContext bc, int offset) =>
+ StructOfStructs._(bc, offset);
+}
+
+class StructOfStructsBuilder {
+ StructOfStructsBuilder(this.fbBuilder);
+
+ final fb.Builder fbBuilder;
+
+ int finish(fb.StructBuilder a, fb.StructBuilder b, fb.StructBuilder c) {
+ c();
+ b();
+ a();
+ return fbBuilder.offset;
+ }
+
+}
+
+class StructOfStructsObjectBuilder extends fb.ObjectBuilder {
+ final AbilityObjectBuilder _a;
+ final TestObjectBuilder _b;
+ final AbilityObjectBuilder _c;
+
+ StructOfStructsObjectBuilder({
+ required AbilityObjectBuilder a,
+ required TestObjectBuilder b,
+ required AbilityObjectBuilder c,
+ })
+ : _a = a,
+ _b = b,
+ _c = c;
+
+ /// Finish building, and store into the [fbBuilder].
+ @override
+ int finish(fb.Builder fbBuilder) {
+ _c.finish(fbBuilder);
+ _b.finish(fbBuilder);
+ _a.finish(fbBuilder);
+ return fbBuilder.offset;
+ }
+
+ /// Convenience method to serialize to byte list.
+ @override
+ Uint8List toBytes([String? fileIdentifier]) {
+ final fbBuilder = fb.Builder(deduplicateTables: false);
+ fbBuilder.finish(finish(fbBuilder), fileIdentifier);
+ return fbBuilder.buffer;
}
}
class Stat {
Stat._(this._bc, this._bcOffset);
factory Stat(List<int> bytes) {
- fb.BufferContext rootRef = new fb.BufferContext.fromBytes(bytes);
+ final rootRef = fb.BufferContext.fromBytes(bytes);
return reader.read(rootRef, 0);
}
- static const fb.Reader<Stat> reader = const _StatReader();
+ static const fb.Reader<Stat> reader = _StatReader();
final fb.BufferContext _bc;
final int _bcOffset;
- String get id => const fb.StringReader().vTableGet(_bc, _bcOffset, 4, null);
+ String? get id => const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 4);
int get val => const fb.Int64Reader().vTableGet(_bc, _bcOffset, 6, 0);
int get count => const fb.Uint16Reader().vTableGet(_bc, _bcOffset, 8, 0);
@@ -564,6 +823,43 @@
String toString() {
return 'Stat{id: $id, val: $val, count: $count}';
}
+
+ StatT unpack() => StatT(
+ id: id,
+ val: val,
+ count: count);
+
+ static int pack(fb.Builder fbBuilder, StatT? object) {
+ if (object == null) return 0;
+ return object.pack(fbBuilder);
+ }
+}
+
+class StatT implements fb.Packable {
+ String? id;
+ int val;
+ int count;
+
+ StatT({
+ this.id,
+ this.val = 0,
+ this.count = 0});
+
+ @override
+ int pack(fb.Builder fbBuilder) {
+ final int? idOffset = id == null ? null
+ : fbBuilder.writeString(id!);
+ fbBuilder.startTable(3);
+ fbBuilder.addOffset(0, idOffset);
+ fbBuilder.addInt64(1, val);
+ fbBuilder.addUint16(2, count);
+ return fbBuilder.endTable();
+ }
+
+ @override
+ String toString() {
+ return 'StatT{id: $id, val: $val, count: $count}';
+ }
}
class _StatReader extends fb.TableReader<Stat> {
@@ -571,29 +867,27 @@
@override
Stat createObject(fb.BufferContext bc, int offset) =>
- new Stat._(bc, offset);
+ Stat._(bc, offset);
}
class StatBuilder {
- StatBuilder(this.fbBuilder) {
- assert(fbBuilder != null);
- }
+ StatBuilder(this.fbBuilder);
final fb.Builder fbBuilder;
void begin() {
- fbBuilder.startTable();
+ fbBuilder.startTable(3);
}
- int addIdOffset(int offset) {
+ int addIdOffset(int? offset) {
fbBuilder.addOffset(0, offset);
return fbBuilder.offset;
}
- int addVal(int val) {
+ int addVal(int? val) {
fbBuilder.addInt64(1, val);
return fbBuilder.offset;
}
- int addCount(int count) {
+ int addCount(int? count) {
fbBuilder.addUint16(2, count);
return fbBuilder.offset;
}
@@ -604,14 +898,14 @@
}
class StatObjectBuilder extends fb.ObjectBuilder {
- final String _id;
- final int _val;
- final int _count;
+ final String? _id;
+ final int? _val;
+ final int? _count;
StatObjectBuilder({
- String id,
- int val,
- int count,
+ String? id,
+ int? val,
+ int? count,
})
: _id = id,
_val = val,
@@ -619,15 +913,11 @@
/// Finish building, and store into the [fbBuilder].
@override
- int finish(
- fb.Builder fbBuilder) {
- assert(fbBuilder != null);
- final int idOffset = fbBuilder.writeString(_id);
-
- fbBuilder.startTable();
- if (idOffset != null) {
- fbBuilder.addOffset(0, idOffset);
- }
+ int finish(fb.Builder fbBuilder) {
+ final int? idOffset = _id == null ? null
+ : fbBuilder.writeString(_id!);
+ fbBuilder.startTable(3);
+ fbBuilder.addOffset(0, idOffset);
fbBuilder.addInt64(1, _val);
fbBuilder.addUint16(2, _count);
return fbBuilder.endTable();
@@ -635,20 +925,20 @@
/// Convenience method to serialize to byte list.
@override
- Uint8List toBytes([String fileIdentifier]) {
- fb.Builder fbBuilder = new fb.Builder();
- int offset = finish(fbBuilder);
- return fbBuilder.finish(offset, fileIdentifier);
+ Uint8List toBytes([String? fileIdentifier]) {
+ final fbBuilder = fb.Builder(deduplicateTables: false);
+ fbBuilder.finish(finish(fbBuilder), fileIdentifier);
+ return fbBuilder.buffer;
}
}
class Referrable {
Referrable._(this._bc, this._bcOffset);
factory Referrable(List<int> bytes) {
- fb.BufferContext rootRef = new fb.BufferContext.fromBytes(bytes);
+ final rootRef = fb.BufferContext.fromBytes(bytes);
return reader.read(rootRef, 0);
}
- static const fb.Reader<Referrable> reader = const _ReferrableReader();
+ static const fb.Reader<Referrable> reader = _ReferrableReader();
final fb.BufferContext _bc;
final int _bcOffset;
@@ -659,6 +949,33 @@
String toString() {
return 'Referrable{id: $id}';
}
+
+ ReferrableT unpack() => ReferrableT(
+ id: id);
+
+ static int pack(fb.Builder fbBuilder, ReferrableT? object) {
+ if (object == null) return 0;
+ return object.pack(fbBuilder);
+ }
+}
+
+class ReferrableT implements fb.Packable {
+ int id;
+
+ ReferrableT({
+ this.id = 0});
+
+ @override
+ int pack(fb.Builder fbBuilder) {
+ fbBuilder.startTable(1);
+ fbBuilder.addUint64(0, id);
+ return fbBuilder.endTable();
+ }
+
+ @override
+ String toString() {
+ return 'ReferrableT{id: $id}';
+ }
}
class _ReferrableReader extends fb.TableReader<Referrable> {
@@ -666,21 +983,19 @@
@override
Referrable createObject(fb.BufferContext bc, int offset) =>
- new Referrable._(bc, offset);
+ Referrable._(bc, offset);
}
class ReferrableBuilder {
- ReferrableBuilder(this.fbBuilder) {
- assert(fbBuilder != null);
- }
+ ReferrableBuilder(this.fbBuilder);
final fb.Builder fbBuilder;
void begin() {
- fbBuilder.startTable();
+ fbBuilder.startTable(1);
}
- int addId(int id) {
+ int addId(int? id) {
fbBuilder.addUint64(0, id);
return fbBuilder.offset;
}
@@ -691,68 +1006,65 @@
}
class ReferrableObjectBuilder extends fb.ObjectBuilder {
- final int _id;
+ final int? _id;
ReferrableObjectBuilder({
- int id,
+ int? id,
})
: _id = id;
/// Finish building, and store into the [fbBuilder].
@override
- int finish(
- fb.Builder fbBuilder) {
- assert(fbBuilder != null);
-
- fbBuilder.startTable();
+ int finish(fb.Builder fbBuilder) {
+ fbBuilder.startTable(1);
fbBuilder.addUint64(0, _id);
return fbBuilder.endTable();
}
/// Convenience method to serialize to byte list.
@override
- Uint8List toBytes([String fileIdentifier]) {
- fb.Builder fbBuilder = new fb.Builder();
- int offset = finish(fbBuilder);
- return fbBuilder.finish(offset, fileIdentifier);
+ Uint8List toBytes([String? fileIdentifier]) {
+ final fbBuilder = fb.Builder(deduplicateTables: false);
+ fbBuilder.finish(finish(fbBuilder), fileIdentifier);
+ return fbBuilder.buffer;
}
}
/// an example documentation comment: "monster object"
class Monster {
Monster._(this._bc, this._bcOffset);
factory Monster(List<int> bytes) {
- fb.BufferContext rootRef = new fb.BufferContext.fromBytes(bytes);
+ final rootRef = fb.BufferContext.fromBytes(bytes);
return reader.read(rootRef, 0);
}
- static const fb.Reader<Monster> reader = const _MonsterReader();
+ static const fb.Reader<Monster> reader = _MonsterReader();
final fb.BufferContext _bc;
final int _bcOffset;
- Vec3 get pos => Vec3.reader.vTableGet(_bc, _bcOffset, 4, null);
+ Vec3? get pos => Vec3.reader.vTableGetNullable(_bc, _bcOffset, 4);
int get mana => const fb.Int16Reader().vTableGet(_bc, _bcOffset, 6, 150);
int get hp => const fb.Int16Reader().vTableGet(_bc, _bcOffset, 8, 100);
- String get name => const fb.StringReader().vTableGet(_bc, _bcOffset, 10, null);
- List<int> get inventory => const fb.ListReader<int>(const fb.Uint8Reader()).vTableGet(_bc, _bcOffset, 14, null);
- Color get color => new Color.fromValue(const fb.Uint8Reader().vTableGet(_bc, _bcOffset, 16, 8));
- AnyTypeId get testType => new AnyTypeId.fromValue(const fb.Uint8Reader().vTableGet(_bc, _bcOffset, 18, 0));
+ String? get name => const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 10);
+ List<int>? get inventory => const fb.Uint8ListReader().vTableGetNullable(_bc, _bcOffset, 14);
+ Color get color => Color.fromValue(const fb.Uint8Reader().vTableGet(_bc, _bcOffset, 16, 8));
+ AnyTypeId? get testType => AnyTypeId._createOrNull(const fb.Uint8Reader().vTableGetNullable(_bc, _bcOffset, 18));
dynamic get test {
switch (testType?.value) {
- case 1: return Monster.reader.vTableGet(_bc, _bcOffset, 20, null);
- case 2: return TestSimpleTableWithEnum.reader.vTableGet(_bc, _bcOffset, 20, null);
- case 3: return my_game_example2.Monster.reader.vTableGet(_bc, _bcOffset, 20, null);
+ case 1: return Monster.reader.vTableGetNullable(_bc, _bcOffset, 20);
+ case 2: return TestSimpleTableWithEnum.reader.vTableGetNullable(_bc, _bcOffset, 20);
+ case 3: return my_game_example2.Monster.reader.vTableGetNullable(_bc, _bcOffset, 20);
default: return null;
}
}
- List<Test> get test4 => const fb.ListReader<Test>(Test.reader).vTableGet(_bc, _bcOffset, 22, null);
- List<String> get testarrayofstring => const fb.ListReader<String>(const fb.StringReader()).vTableGet(_bc, _bcOffset, 24, null);
+ List<Test>? get test4 => const fb.ListReader<Test>(Test.reader).vTableGetNullable(_bc, _bcOffset, 22);
+ List<String>? get testarrayofstring => const fb.ListReader<String>(fb.StringReader()).vTableGetNullable(_bc, _bcOffset, 24);
/// an example documentation comment: this will end up in the generated code
/// multiline too
- List<Monster> get testarrayoftables => const fb.ListReader<Monster>(Monster.reader).vTableGet(_bc, _bcOffset, 26, null);
- Monster get enemy => Monster.reader.vTableGet(_bc, _bcOffset, 28, null);
- List<int> get testnestedflatbuffer => const fb.ListReader<int>(const fb.Uint8Reader()).vTableGet(_bc, _bcOffset, 30, null);
- Stat get testempty => Stat.reader.vTableGet(_bc, _bcOffset, 32, null);
+ List<Monster>? get testarrayoftables => const fb.ListReader<Monster>(Monster.reader).vTableGetNullable(_bc, _bcOffset, 26);
+ Monster? get enemy => Monster.reader.vTableGetNullable(_bc, _bcOffset, 28);
+ List<int>? get testnestedflatbuffer => const fb.Uint8ListReader().vTableGetNullable(_bc, _bcOffset, 30);
+ Stat? get testempty => Stat.reader.vTableGetNullable(_bc, _bcOffset, 32);
bool get testbool => const fb.BoolReader().vTableGet(_bc, _bcOffset, 34, false);
int get testhashs32Fnv1 => const fb.Int32Reader().vTableGet(_bc, _bcOffset, 36, 0);
int get testhashu32Fnv1 => const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 38, 0);
@@ -762,49 +1074,336 @@
int get testhashu32Fnv1a => const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 46, 0);
int get testhashs64Fnv1a => const fb.Int64Reader().vTableGet(_bc, _bcOffset, 48, 0);
int get testhashu64Fnv1a => const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 50, 0);
- List<bool> get testarrayofbools => const fb.ListReader<bool>(const fb.BoolReader()).vTableGet(_bc, _bcOffset, 52, null);
+ List<bool>? get testarrayofbools => const fb.ListReader<bool>(fb.BoolReader()).vTableGetNullable(_bc, _bcOffset, 52);
double get testf => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 54, 3.14159);
double get testf2 => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 56, 3.0);
double get testf3 => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 58, 0.0);
- List<String> get testarrayofstring2 => const fb.ListReader<String>(const fb.StringReader()).vTableGet(_bc, _bcOffset, 60, null);
- List<Ability> get testarrayofsortedstruct => const fb.ListReader<Ability>(Ability.reader).vTableGet(_bc, _bcOffset, 62, null);
- List<int> get flex => const fb.ListReader<int>(const fb.Uint8Reader()).vTableGet(_bc, _bcOffset, 64, null);
- List<Test> get test5 => const fb.ListReader<Test>(Test.reader).vTableGet(_bc, _bcOffset, 66, null);
- List<int> get vectorOfLongs => const fb.ListReader<int>(const fb.Int64Reader()).vTableGet(_bc, _bcOffset, 68, null);
- List<double> get vectorOfDoubles => const fb.ListReader<double>(const fb.Float64Reader()).vTableGet(_bc, _bcOffset, 70, null);
- my_game.InParentNamespace get parentNamespaceTest => my_game.InParentNamespace.reader.vTableGet(_bc, _bcOffset, 72, null);
- List<Referrable> get vectorOfReferrables => const fb.ListReader<Referrable>(Referrable.reader).vTableGet(_bc, _bcOffset, 74, null);
+ List<String>? get testarrayofstring2 => const fb.ListReader<String>(fb.StringReader()).vTableGetNullable(_bc, _bcOffset, 60);
+ List<Ability>? get testarrayofsortedstruct => const fb.ListReader<Ability>(Ability.reader).vTableGetNullable(_bc, _bcOffset, 62);
+ List<int>? get flex => const fb.Uint8ListReader().vTableGetNullable(_bc, _bcOffset, 64);
+ List<Test>? get test5 => const fb.ListReader<Test>(Test.reader).vTableGetNullable(_bc, _bcOffset, 66);
+ List<int>? get vectorOfLongs => const fb.ListReader<int>(fb.Int64Reader()).vTableGetNullable(_bc, _bcOffset, 68);
+ List<double>? get vectorOfDoubles => const fb.ListReader<double>(fb.Float64Reader()).vTableGetNullable(_bc, _bcOffset, 70);
+ my_game.InParentNamespace? get parentNamespaceTest => my_game.InParentNamespace.reader.vTableGetNullable(_bc, _bcOffset, 72);
+ List<Referrable>? get vectorOfReferrables => const fb.ListReader<Referrable>(Referrable.reader).vTableGetNullable(_bc, _bcOffset, 74);
int get singleWeakReference => const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 76, 0);
- List<int> get vectorOfWeakReferences => const fb.ListReader<int>(const fb.Uint64Reader()).vTableGet(_bc, _bcOffset, 78, null);
- List<Referrable> get vectorOfStrongReferrables => const fb.ListReader<Referrable>(Referrable.reader).vTableGet(_bc, _bcOffset, 80, null);
+ List<int>? get vectorOfWeakReferences => const fb.ListReader<int>(fb.Uint64Reader()).vTableGetNullable(_bc, _bcOffset, 78);
+ List<Referrable>? get vectorOfStrongReferrables => const fb.ListReader<Referrable>(Referrable.reader).vTableGetNullable(_bc, _bcOffset, 80);
int get coOwningReference => const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 82, 0);
- List<int> get vectorOfCoOwningReferences => const fb.ListReader<int>(const fb.Uint64Reader()).vTableGet(_bc, _bcOffset, 84, null);
+ List<int>? get vectorOfCoOwningReferences => const fb.ListReader<int>(fb.Uint64Reader()).vTableGetNullable(_bc, _bcOffset, 84);
int get nonOwningReference => const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 86, 0);
- List<int> get vectorOfNonOwningReferences => const fb.ListReader<int>(const fb.Uint64Reader()).vTableGet(_bc, _bcOffset, 88, null);
- AnyUniqueAliasesTypeId get anyUniqueType => new AnyUniqueAliasesTypeId.fromValue(const fb.Uint8Reader().vTableGet(_bc, _bcOffset, 90, 0));
+ List<int>? get vectorOfNonOwningReferences => const fb.ListReader<int>(fb.Uint64Reader()).vTableGetNullable(_bc, _bcOffset, 88);
+ AnyUniqueAliasesTypeId? get anyUniqueType => AnyUniqueAliasesTypeId._createOrNull(const fb.Uint8Reader().vTableGetNullable(_bc, _bcOffset, 90));
dynamic get anyUnique {
switch (anyUniqueType?.value) {
- case 1: return Monster.reader.vTableGet(_bc, _bcOffset, 92, null);
- case 2: return TestSimpleTableWithEnum.reader.vTableGet(_bc, _bcOffset, 92, null);
- case 3: return my_game_example2.Monster.reader.vTableGet(_bc, _bcOffset, 92, null);
+ case 1: return Monster.reader.vTableGetNullable(_bc, _bcOffset, 92);
+ case 2: return TestSimpleTableWithEnum.reader.vTableGetNullable(_bc, _bcOffset, 92);
+ case 3: return my_game_example2.Monster.reader.vTableGetNullable(_bc, _bcOffset, 92);
default: return null;
}
}
- AnyAmbiguousAliasesTypeId get anyAmbiguousType => new AnyAmbiguousAliasesTypeId.fromValue(const fb.Uint8Reader().vTableGet(_bc, _bcOffset, 94, 0));
+ AnyAmbiguousAliasesTypeId? get anyAmbiguousType => AnyAmbiguousAliasesTypeId._createOrNull(const fb.Uint8Reader().vTableGetNullable(_bc, _bcOffset, 94));
dynamic get anyAmbiguous {
switch (anyAmbiguousType?.value) {
- case 1: return Monster.reader.vTableGet(_bc, _bcOffset, 96, null);
- case 2: return Monster.reader.vTableGet(_bc, _bcOffset, 96, null);
- case 3: return Monster.reader.vTableGet(_bc, _bcOffset, 96, null);
+ case 1: return Monster.reader.vTableGetNullable(_bc, _bcOffset, 96);
+ case 2: return Monster.reader.vTableGetNullable(_bc, _bcOffset, 96);
+ case 3: return Monster.reader.vTableGetNullable(_bc, _bcOffset, 96);
default: return null;
}
}
- List<Color> get vectorOfEnums => const fb.ListReader<Color>(Color.reader).vTableGet(_bc, _bcOffset, 98, null);
- Race get signedEnum => new Race.fromValue(const fb.Int8Reader().vTableGet(_bc, _bcOffset, 100, -1));
+ List<Color>? get vectorOfEnums => const fb.ListReader<Color>(Color.reader).vTableGetNullable(_bc, _bcOffset, 98);
+ Race get signedEnum => Race.fromValue(const fb.Int8Reader().vTableGet(_bc, _bcOffset, 100, -1));
+ List<int>? get testrequirednestedflatbuffer => const fb.Uint8ListReader().vTableGetNullable(_bc, _bcOffset, 102);
+ List<Stat>? get scalarKeySortedTables => const fb.ListReader<Stat>(Stat.reader).vTableGetNullable(_bc, _bcOffset, 104);
@override
String toString() {
- return 'Monster{pos: $pos, mana: $mana, hp: $hp, name: $name, inventory: $inventory, color: $color, testType: $testType, test: $test, test4: $test4, testarrayofstring: $testarrayofstring, testarrayoftables: $testarrayoftables, enemy: $enemy, testnestedflatbuffer: $testnestedflatbuffer, testempty: $testempty, testbool: $testbool, testhashs32Fnv1: $testhashs32Fnv1, testhashu32Fnv1: $testhashu32Fnv1, testhashs64Fnv1: $testhashs64Fnv1, testhashu64Fnv1: $testhashu64Fnv1, testhashs32Fnv1a: $testhashs32Fnv1a, testhashu32Fnv1a: $testhashu32Fnv1a, testhashs64Fnv1a: $testhashs64Fnv1a, testhashu64Fnv1a: $testhashu64Fnv1a, testarrayofbools: $testarrayofbools, testf: $testf, testf2: $testf2, testf3: $testf3, testarrayofstring2: $testarrayofstring2, testarrayofsortedstruct: $testarrayofsortedstruct, flex: $flex, test5: $test5, vectorOfLongs: $vectorOfLongs, vectorOfDoubles: $vectorOfDoubles, parentNamespaceTest: $parentNamespaceTest, vectorOfReferrables: $vectorOfReferrables, singleWeakReference: $singleWeakReference, vectorOfWeakReferences: $vectorOfWeakReferences, vectorOfStrongReferrables: $vectorOfStrongReferrables, coOwningReference: $coOwningReference, vectorOfCoOwningReferences: $vectorOfCoOwningReferences, nonOwningReference: $nonOwningReference, vectorOfNonOwningReferences: $vectorOfNonOwningReferences, anyUniqueType: $anyUniqueType, anyUnique: $anyUnique, anyAmbiguousType: $anyAmbiguousType, anyAmbiguous: $anyAmbiguous, vectorOfEnums: $vectorOfEnums, signedEnum: $signedEnum}';
+ return 'Monster{pos: $pos, mana: $mana, hp: $hp, name: $name, inventory: $inventory, color: $color, testType: $testType, test: $test, test4: $test4, testarrayofstring: $testarrayofstring, testarrayoftables: $testarrayoftables, enemy: $enemy, testnestedflatbuffer: $testnestedflatbuffer, testempty: $testempty, testbool: $testbool, testhashs32Fnv1: $testhashs32Fnv1, testhashu32Fnv1: $testhashu32Fnv1, testhashs64Fnv1: $testhashs64Fnv1, testhashu64Fnv1: $testhashu64Fnv1, testhashs32Fnv1a: $testhashs32Fnv1a, testhashu32Fnv1a: $testhashu32Fnv1a, testhashs64Fnv1a: $testhashs64Fnv1a, testhashu64Fnv1a: $testhashu64Fnv1a, testarrayofbools: $testarrayofbools, testf: $testf, testf2: $testf2, testf3: $testf3, testarrayofstring2: $testarrayofstring2, testarrayofsortedstruct: $testarrayofsortedstruct, flex: $flex, test5: $test5, vectorOfLongs: $vectorOfLongs, vectorOfDoubles: $vectorOfDoubles, parentNamespaceTest: $parentNamespaceTest, vectorOfReferrables: $vectorOfReferrables, singleWeakReference: $singleWeakReference, vectorOfWeakReferences: $vectorOfWeakReferences, vectorOfStrongReferrables: $vectorOfStrongReferrables, coOwningReference: $coOwningReference, vectorOfCoOwningReferences: $vectorOfCoOwningReferences, nonOwningReference: $nonOwningReference, vectorOfNonOwningReferences: $vectorOfNonOwningReferences, anyUniqueType: $anyUniqueType, anyUnique: $anyUnique, anyAmbiguousType: $anyAmbiguousType, anyAmbiguous: $anyAmbiguous, vectorOfEnums: $vectorOfEnums, signedEnum: $signedEnum, testrequirednestedflatbuffer: $testrequirednestedflatbuffer, scalarKeySortedTables: $scalarKeySortedTables}';
+ }
+
+ MonsterT unpack() => MonsterT(
+ pos: pos?.unpack(),
+ mana: mana,
+ hp: hp,
+ name: name,
+ inventory: const fb.Uint8ListReader(lazy: false).vTableGetNullable(_bc, _bcOffset, 14),
+ color: color,
+ testType: testType,
+ test: test,
+ test4: test4?.map((e) => e.unpack()).toList(),
+ testarrayofstring: const fb.ListReader<String>(fb.StringReader(), lazy: false).vTableGetNullable(_bc, _bcOffset, 24),
+ testarrayoftables: testarrayoftables?.map((e) => e.unpack()).toList(),
+ enemy: enemy?.unpack(),
+ testnestedflatbuffer: const fb.Uint8ListReader(lazy: false).vTableGetNullable(_bc, _bcOffset, 30),
+ testempty: testempty?.unpack(),
+ testbool: testbool,
+ testhashs32Fnv1: testhashs32Fnv1,
+ testhashu32Fnv1: testhashu32Fnv1,
+ testhashs64Fnv1: testhashs64Fnv1,
+ testhashu64Fnv1: testhashu64Fnv1,
+ testhashs32Fnv1a: testhashs32Fnv1a,
+ testhashu32Fnv1a: testhashu32Fnv1a,
+ testhashs64Fnv1a: testhashs64Fnv1a,
+ testhashu64Fnv1a: testhashu64Fnv1a,
+ testarrayofbools: const fb.ListReader<bool>(fb.BoolReader(), lazy: false).vTableGetNullable(_bc, _bcOffset, 52),
+ testf: testf,
+ testf2: testf2,
+ testf3: testf3,
+ testarrayofstring2: const fb.ListReader<String>(fb.StringReader(), lazy: false).vTableGetNullable(_bc, _bcOffset, 60),
+ testarrayofsortedstruct: testarrayofsortedstruct?.map((e) => e.unpack()).toList(),
+ flex: const fb.Uint8ListReader(lazy: false).vTableGetNullable(_bc, _bcOffset, 64),
+ test5: test5?.map((e) => e.unpack()).toList(),
+ vectorOfLongs: const fb.ListReader<int>(fb.Int64Reader(), lazy: false).vTableGetNullable(_bc, _bcOffset, 68),
+ vectorOfDoubles: const fb.ListReader<double>(fb.Float64Reader(), lazy: false).vTableGetNullable(_bc, _bcOffset, 70),
+ parentNamespaceTest: parentNamespaceTest?.unpack(),
+ vectorOfReferrables: vectorOfReferrables?.map((e) => e.unpack()).toList(),
+ singleWeakReference: singleWeakReference,
+ vectorOfWeakReferences: const fb.ListReader<int>(fb.Uint64Reader(), lazy: false).vTableGetNullable(_bc, _bcOffset, 78),
+ vectorOfStrongReferrables: vectorOfStrongReferrables?.map((e) => e.unpack()).toList(),
+ coOwningReference: coOwningReference,
+ vectorOfCoOwningReferences: const fb.ListReader<int>(fb.Uint64Reader(), lazy: false).vTableGetNullable(_bc, _bcOffset, 84),
+ nonOwningReference: nonOwningReference,
+ vectorOfNonOwningReferences: const fb.ListReader<int>(fb.Uint64Reader(), lazy: false).vTableGetNullable(_bc, _bcOffset, 88),
+ anyUniqueType: anyUniqueType,
+ anyUnique: anyUnique,
+ anyAmbiguousType: anyAmbiguousType,
+ anyAmbiguous: anyAmbiguous,
+ vectorOfEnums: const fb.ListReader<Color>(Color.reader, lazy: false).vTableGetNullable(_bc, _bcOffset, 98),
+ signedEnum: signedEnum,
+ testrequirednestedflatbuffer: const fb.Uint8ListReader(lazy: false).vTableGetNullable(_bc, _bcOffset, 102),
+ scalarKeySortedTables: scalarKeySortedTables?.map((e) => e.unpack()).toList());
+
+ static int pack(fb.Builder fbBuilder, MonsterT? object) {
+ if (object == null) return 0;
+ return object.pack(fbBuilder);
+ }
+}
+
+/// an example documentation comment: "monster object"
+class MonsterT implements fb.Packable {
+ Vec3T? pos;
+ int mana;
+ int hp;
+ String? name;
+ List<int>? inventory;
+ Color color;
+ AnyTypeId? testType;
+ dynamic test;
+ List<TestT>? test4;
+ List<String>? testarrayofstring;
+ /// an example documentation comment: this will end up in the generated code
+ /// multiline too
+ List<MonsterT>? testarrayoftables;
+ MonsterT? enemy;
+ List<int>? testnestedflatbuffer;
+ StatT? testempty;
+ bool testbool;
+ int testhashs32Fnv1;
+ int testhashu32Fnv1;
+ int testhashs64Fnv1;
+ int testhashu64Fnv1;
+ int testhashs32Fnv1a;
+ int testhashu32Fnv1a;
+ int testhashs64Fnv1a;
+ int testhashu64Fnv1a;
+ List<bool>? testarrayofbools;
+ double testf;
+ double testf2;
+ double testf3;
+ List<String>? testarrayofstring2;
+ List<AbilityT>? testarrayofsortedstruct;
+ List<int>? flex;
+ List<TestT>? test5;
+ List<int>? vectorOfLongs;
+ List<double>? vectorOfDoubles;
+ my_game.InParentNamespaceT? parentNamespaceTest;
+ List<ReferrableT>? vectorOfReferrables;
+ int singleWeakReference;
+ List<int>? vectorOfWeakReferences;
+ List<ReferrableT>? vectorOfStrongReferrables;
+ int coOwningReference;
+ List<int>? vectorOfCoOwningReferences;
+ int nonOwningReference;
+ List<int>? vectorOfNonOwningReferences;
+ AnyUniqueAliasesTypeId? anyUniqueType;
+ dynamic anyUnique;
+ AnyAmbiguousAliasesTypeId? anyAmbiguousType;
+ dynamic anyAmbiguous;
+ List<Color>? vectorOfEnums;
+ Race signedEnum;
+ List<int>? testrequirednestedflatbuffer;
+ List<StatT>? scalarKeySortedTables;
+
+ MonsterT({
+ this.pos,
+ this.mana = 150,
+ this.hp = 100,
+ this.name,
+ this.inventory,
+ this.color = Color.Blue,
+ this.testType,
+ this.test,
+ this.test4,
+ this.testarrayofstring,
+ this.testarrayoftables,
+ this.enemy,
+ this.testnestedflatbuffer,
+ this.testempty,
+ this.testbool = false,
+ this.testhashs32Fnv1 = 0,
+ this.testhashu32Fnv1 = 0,
+ this.testhashs64Fnv1 = 0,
+ this.testhashu64Fnv1 = 0,
+ this.testhashs32Fnv1a = 0,
+ this.testhashu32Fnv1a = 0,
+ this.testhashs64Fnv1a = 0,
+ this.testhashu64Fnv1a = 0,
+ this.testarrayofbools,
+ this.testf = 3.14159,
+ this.testf2 = 3.0,
+ this.testf3 = 0.0,
+ this.testarrayofstring2,
+ this.testarrayofsortedstruct,
+ this.flex,
+ this.test5,
+ this.vectorOfLongs,
+ this.vectorOfDoubles,
+ this.parentNamespaceTest,
+ this.vectorOfReferrables,
+ this.singleWeakReference = 0,
+ this.vectorOfWeakReferences,
+ this.vectorOfStrongReferrables,
+ this.coOwningReference = 0,
+ this.vectorOfCoOwningReferences,
+ this.nonOwningReference = 0,
+ this.vectorOfNonOwningReferences,
+ this.anyUniqueType,
+ this.anyUnique,
+ this.anyAmbiguousType,
+ this.anyAmbiguous,
+ this.vectorOfEnums,
+ this.signedEnum = Race.None,
+ this.testrequirednestedflatbuffer,
+ this.scalarKeySortedTables});
+
+ @override
+ int pack(fb.Builder fbBuilder) {
+ final int? nameOffset = name == null ? null
+ : fbBuilder.writeString(name!);
+ final int? inventoryOffset = inventory == null ? null
+ : fbBuilder.writeListUint8(inventory!);
+ final int? testOffset = test?.pack(fbBuilder);
+ int? test4Offset;
+ if (test4 != null) {
+ for (var e in test4!) { e.pack(fbBuilder); }
+ test4Offset = fbBuilder.endStructVector(test4!.length);
+ }
+ final int? testarrayofstringOffset = testarrayofstring == null ? null
+ : fbBuilder.writeList(testarrayofstring!.map(fbBuilder.writeString).toList());
+ final int? testarrayoftablesOffset = testarrayoftables == null ? null
+ : fbBuilder.writeList(testarrayoftables!.map((b) => b.pack(fbBuilder)).toList());
+ final int? enemyOffset = enemy?.pack(fbBuilder);
+ final int? testnestedflatbufferOffset = testnestedflatbuffer == null ? null
+ : fbBuilder.writeListUint8(testnestedflatbuffer!);
+ final int? testemptyOffset = testempty?.pack(fbBuilder);
+ final int? testarrayofboolsOffset = testarrayofbools == null ? null
+ : fbBuilder.writeListBool(testarrayofbools!);
+ final int? testarrayofstring2Offset = testarrayofstring2 == null ? null
+ : fbBuilder.writeList(testarrayofstring2!.map(fbBuilder.writeString).toList());
+ int? testarrayofsortedstructOffset;
+ if (testarrayofsortedstruct != null) {
+ for (var e in testarrayofsortedstruct!) { e.pack(fbBuilder); }
+ testarrayofsortedstructOffset = fbBuilder.endStructVector(testarrayofsortedstruct!.length);
+ }
+ final int? flexOffset = flex == null ? null
+ : fbBuilder.writeListUint8(flex!);
+ int? test5Offset;
+ if (test5 != null) {
+ for (var e in test5!) { e.pack(fbBuilder); }
+ test5Offset = fbBuilder.endStructVector(test5!.length);
+ }
+ final int? vectorOfLongsOffset = vectorOfLongs == null ? null
+ : fbBuilder.writeListInt64(vectorOfLongs!);
+ final int? vectorOfDoublesOffset = vectorOfDoubles == null ? null
+ : fbBuilder.writeListFloat64(vectorOfDoubles!);
+ final int? parentNamespaceTestOffset = parentNamespaceTest?.pack(fbBuilder);
+ final int? vectorOfReferrablesOffset = vectorOfReferrables == null ? null
+ : fbBuilder.writeList(vectorOfReferrables!.map((b) => b.pack(fbBuilder)).toList());
+ final int? vectorOfWeakReferencesOffset = vectorOfWeakReferences == null ? null
+ : fbBuilder.writeListUint64(vectorOfWeakReferences!);
+ final int? vectorOfStrongReferrablesOffset = vectorOfStrongReferrables == null ? null
+ : fbBuilder.writeList(vectorOfStrongReferrables!.map((b) => b.pack(fbBuilder)).toList());
+ final int? vectorOfCoOwningReferencesOffset = vectorOfCoOwningReferences == null ? null
+ : fbBuilder.writeListUint64(vectorOfCoOwningReferences!);
+ final int? vectorOfNonOwningReferencesOffset = vectorOfNonOwningReferences == null ? null
+ : fbBuilder.writeListUint64(vectorOfNonOwningReferences!);
+ final int? anyUniqueOffset = anyUnique?.pack(fbBuilder);
+ final int? anyAmbiguousOffset = anyAmbiguous?.pack(fbBuilder);
+ final int? vectorOfEnumsOffset = vectorOfEnums == null ? null
+ : fbBuilder.writeListUint8(vectorOfEnums!.map((f) => f.value).toList());
+ final int? testrequirednestedflatbufferOffset = testrequirednestedflatbuffer == null ? null
+ : fbBuilder.writeListUint8(testrequirednestedflatbuffer!);
+ final int? scalarKeySortedTablesOffset = scalarKeySortedTables == null ? null
+ : fbBuilder.writeList(scalarKeySortedTables!.map((b) => b.pack(fbBuilder)).toList());
+ fbBuilder.startTable(50);
+ if (pos != null) {
+ fbBuilder.addStruct(0, pos!.pack(fbBuilder));
+ }
+ fbBuilder.addInt16(1, mana);
+ fbBuilder.addInt16(2, hp);
+ fbBuilder.addOffset(3, nameOffset);
+ fbBuilder.addOffset(5, inventoryOffset);
+ fbBuilder.addUint8(6, color.value);
+ fbBuilder.addUint8(7, testType?.value);
+ fbBuilder.addOffset(8, testOffset);
+ fbBuilder.addOffset(9, test4Offset);
+ fbBuilder.addOffset(10, testarrayofstringOffset);
+ fbBuilder.addOffset(11, testarrayoftablesOffset);
+ fbBuilder.addOffset(12, enemyOffset);
+ fbBuilder.addOffset(13, testnestedflatbufferOffset);
+ fbBuilder.addOffset(14, testemptyOffset);
+ fbBuilder.addBool(15, testbool);
+ fbBuilder.addInt32(16, testhashs32Fnv1);
+ fbBuilder.addUint32(17, testhashu32Fnv1);
+ fbBuilder.addInt64(18, testhashs64Fnv1);
+ fbBuilder.addUint64(19, testhashu64Fnv1);
+ fbBuilder.addInt32(20, testhashs32Fnv1a);
+ fbBuilder.addUint32(21, testhashu32Fnv1a);
+ fbBuilder.addInt64(22, testhashs64Fnv1a);
+ fbBuilder.addUint64(23, testhashu64Fnv1a);
+ fbBuilder.addOffset(24, testarrayofboolsOffset);
+ fbBuilder.addFloat32(25, testf);
+ fbBuilder.addFloat32(26, testf2);
+ fbBuilder.addFloat32(27, testf3);
+ fbBuilder.addOffset(28, testarrayofstring2Offset);
+ fbBuilder.addOffset(29, testarrayofsortedstructOffset);
+ fbBuilder.addOffset(30, flexOffset);
+ fbBuilder.addOffset(31, test5Offset);
+ fbBuilder.addOffset(32, vectorOfLongsOffset);
+ fbBuilder.addOffset(33, vectorOfDoublesOffset);
+ fbBuilder.addOffset(34, parentNamespaceTestOffset);
+ fbBuilder.addOffset(35, vectorOfReferrablesOffset);
+ fbBuilder.addUint64(36, singleWeakReference);
+ fbBuilder.addOffset(37, vectorOfWeakReferencesOffset);
+ fbBuilder.addOffset(38, vectorOfStrongReferrablesOffset);
+ fbBuilder.addUint64(39, coOwningReference);
+ fbBuilder.addOffset(40, vectorOfCoOwningReferencesOffset);
+ fbBuilder.addUint64(41, nonOwningReference);
+ fbBuilder.addOffset(42, vectorOfNonOwningReferencesOffset);
+ fbBuilder.addUint8(43, anyUniqueType?.value);
+ fbBuilder.addOffset(44, anyUniqueOffset);
+ fbBuilder.addUint8(45, anyAmbiguousType?.value);
+ fbBuilder.addOffset(46, anyAmbiguousOffset);
+ fbBuilder.addOffset(47, vectorOfEnumsOffset);
+ fbBuilder.addInt8(48, signedEnum.value);
+ fbBuilder.addOffset(49, testrequirednestedflatbufferOffset);
+ fbBuilder.addOffset(50, scalarKeySortedTablesOffset);
+ return fbBuilder.endTable();
+ }
+
+ @override
+ String toString() {
+ return 'MonsterT{pos: $pos, mana: $mana, hp: $hp, name: $name, inventory: $inventory, color: $color, testType: $testType, test: $test, test4: $test4, testarrayofstring: $testarrayofstring, testarrayoftables: $testarrayoftables, enemy: $enemy, testnestedflatbuffer: $testnestedflatbuffer, testempty: $testempty, testbool: $testbool, testhashs32Fnv1: $testhashs32Fnv1, testhashu32Fnv1: $testhashu32Fnv1, testhashs64Fnv1: $testhashs64Fnv1, testhashu64Fnv1: $testhashu64Fnv1, testhashs32Fnv1a: $testhashs32Fnv1a, testhashu32Fnv1a: $testhashu32Fnv1a, testhashs64Fnv1a: $testhashs64Fnv1a, testhashu64Fnv1a: $testhashu64Fnv1a, testarrayofbools: $testarrayofbools, testf: $testf, testf2: $testf2, testf3: $testf3, testarrayofstring2: $testarrayofstring2, testarrayofsortedstruct: $testarrayofsortedstruct, flex: $flex, test5: $test5, vectorOfLongs: $vectorOfLongs, vectorOfDoubles: $vectorOfDoubles, parentNamespaceTest: $parentNamespaceTest, vectorOfReferrables: $vectorOfReferrables, singleWeakReference: $singleWeakReference, vectorOfWeakReferences: $vectorOfWeakReferences, vectorOfStrongReferrables: $vectorOfStrongReferrables, coOwningReference: $coOwningReference, vectorOfCoOwningReferences: $vectorOfCoOwningReferences, nonOwningReference: $nonOwningReference, vectorOfNonOwningReferences: $vectorOfNonOwningReferences, anyUniqueType: $anyUniqueType, anyUnique: $anyUnique, anyAmbiguousType: $anyAmbiguousType, anyAmbiguous: $anyAmbiguous, vectorOfEnums: $vectorOfEnums, signedEnum: $signedEnum, testrequirednestedflatbuffer: $testrequirednestedflatbuffer, scalarKeySortedTables: $scalarKeySortedTables}';
}
}
@@ -813,212 +1412,218 @@
@override
Monster createObject(fb.BufferContext bc, int offset) =>
- new Monster._(bc, offset);
+ Monster._(bc, offset);
}
class MonsterBuilder {
- MonsterBuilder(this.fbBuilder) {
- assert(fbBuilder != null);
- }
+ MonsterBuilder(this.fbBuilder);
final fb.Builder fbBuilder;
void begin() {
- fbBuilder.startTable();
+ fbBuilder.startTable(50);
}
int addPos(int offset) {
fbBuilder.addStruct(0, offset);
return fbBuilder.offset;
}
- int addMana(int mana) {
+ int addMana(int? mana) {
fbBuilder.addInt16(1, mana);
return fbBuilder.offset;
}
- int addHp(int hp) {
+ int addHp(int? hp) {
fbBuilder.addInt16(2, hp);
return fbBuilder.offset;
}
- int addNameOffset(int offset) {
+ int addNameOffset(int? offset) {
fbBuilder.addOffset(3, offset);
return fbBuilder.offset;
}
- int addInventoryOffset(int offset) {
+ int addInventoryOffset(int? offset) {
fbBuilder.addOffset(5, offset);
return fbBuilder.offset;
}
- int addColor(Color color) {
+ int addColor(Color? color) {
fbBuilder.addUint8(6, color?.value);
return fbBuilder.offset;
}
- int addTestType(AnyTypeId testType) {
+ int addTestType(AnyTypeId? testType) {
fbBuilder.addUint8(7, testType?.value);
return fbBuilder.offset;
}
- int addTestOffset(int offset) {
+ int addTestOffset(int? offset) {
fbBuilder.addOffset(8, offset);
return fbBuilder.offset;
}
- int addTest4Offset(int offset) {
+ int addTest4Offset(int? offset) {
fbBuilder.addOffset(9, offset);
return fbBuilder.offset;
}
- int addTestarrayofstringOffset(int offset) {
+ int addTestarrayofstringOffset(int? offset) {
fbBuilder.addOffset(10, offset);
return fbBuilder.offset;
}
- int addTestarrayoftablesOffset(int offset) {
+ int addTestarrayoftablesOffset(int? offset) {
fbBuilder.addOffset(11, offset);
return fbBuilder.offset;
}
- int addEnemyOffset(int offset) {
+ int addEnemyOffset(int? offset) {
fbBuilder.addOffset(12, offset);
return fbBuilder.offset;
}
- int addTestnestedflatbufferOffset(int offset) {
+ int addTestnestedflatbufferOffset(int? offset) {
fbBuilder.addOffset(13, offset);
return fbBuilder.offset;
}
- int addTestemptyOffset(int offset) {
+ int addTestemptyOffset(int? offset) {
fbBuilder.addOffset(14, offset);
return fbBuilder.offset;
}
- int addTestbool(bool testbool) {
+ int addTestbool(bool? testbool) {
fbBuilder.addBool(15, testbool);
return fbBuilder.offset;
}
- int addTesthashs32Fnv1(int testhashs32Fnv1) {
+ int addTesthashs32Fnv1(int? testhashs32Fnv1) {
fbBuilder.addInt32(16, testhashs32Fnv1);
return fbBuilder.offset;
}
- int addTesthashu32Fnv1(int testhashu32Fnv1) {
+ int addTesthashu32Fnv1(int? testhashu32Fnv1) {
fbBuilder.addUint32(17, testhashu32Fnv1);
return fbBuilder.offset;
}
- int addTesthashs64Fnv1(int testhashs64Fnv1) {
+ int addTesthashs64Fnv1(int? testhashs64Fnv1) {
fbBuilder.addInt64(18, testhashs64Fnv1);
return fbBuilder.offset;
}
- int addTesthashu64Fnv1(int testhashu64Fnv1) {
+ int addTesthashu64Fnv1(int? testhashu64Fnv1) {
fbBuilder.addUint64(19, testhashu64Fnv1);
return fbBuilder.offset;
}
- int addTesthashs32Fnv1a(int testhashs32Fnv1a) {
+ int addTesthashs32Fnv1a(int? testhashs32Fnv1a) {
fbBuilder.addInt32(20, testhashs32Fnv1a);
return fbBuilder.offset;
}
- int addTesthashu32Fnv1a(int testhashu32Fnv1a) {
+ int addTesthashu32Fnv1a(int? testhashu32Fnv1a) {
fbBuilder.addUint32(21, testhashu32Fnv1a);
return fbBuilder.offset;
}
- int addTesthashs64Fnv1a(int testhashs64Fnv1a) {
+ int addTesthashs64Fnv1a(int? testhashs64Fnv1a) {
fbBuilder.addInt64(22, testhashs64Fnv1a);
return fbBuilder.offset;
}
- int addTesthashu64Fnv1a(int testhashu64Fnv1a) {
+ int addTesthashu64Fnv1a(int? testhashu64Fnv1a) {
fbBuilder.addUint64(23, testhashu64Fnv1a);
return fbBuilder.offset;
}
- int addTestarrayofboolsOffset(int offset) {
+ int addTestarrayofboolsOffset(int? offset) {
fbBuilder.addOffset(24, offset);
return fbBuilder.offset;
}
- int addTestf(double testf) {
+ int addTestf(double? testf) {
fbBuilder.addFloat32(25, testf);
return fbBuilder.offset;
}
- int addTestf2(double testf2) {
+ int addTestf2(double? testf2) {
fbBuilder.addFloat32(26, testf2);
return fbBuilder.offset;
}
- int addTestf3(double testf3) {
+ int addTestf3(double? testf3) {
fbBuilder.addFloat32(27, testf3);
return fbBuilder.offset;
}
- int addTestarrayofstring2Offset(int offset) {
+ int addTestarrayofstring2Offset(int? offset) {
fbBuilder.addOffset(28, offset);
return fbBuilder.offset;
}
- int addTestarrayofsortedstructOffset(int offset) {
+ int addTestarrayofsortedstructOffset(int? offset) {
fbBuilder.addOffset(29, offset);
return fbBuilder.offset;
}
- int addFlexOffset(int offset) {
+ int addFlexOffset(int? offset) {
fbBuilder.addOffset(30, offset);
return fbBuilder.offset;
}
- int addTest5Offset(int offset) {
+ int addTest5Offset(int? offset) {
fbBuilder.addOffset(31, offset);
return fbBuilder.offset;
}
- int addVectorOfLongsOffset(int offset) {
+ int addVectorOfLongsOffset(int? offset) {
fbBuilder.addOffset(32, offset);
return fbBuilder.offset;
}
- int addVectorOfDoublesOffset(int offset) {
+ int addVectorOfDoublesOffset(int? offset) {
fbBuilder.addOffset(33, offset);
return fbBuilder.offset;
}
- int addParentNamespaceTestOffset(int offset) {
+ int addParentNamespaceTestOffset(int? offset) {
fbBuilder.addOffset(34, offset);
return fbBuilder.offset;
}
- int addVectorOfReferrablesOffset(int offset) {
+ int addVectorOfReferrablesOffset(int? offset) {
fbBuilder.addOffset(35, offset);
return fbBuilder.offset;
}
- int addSingleWeakReference(int singleWeakReference) {
+ int addSingleWeakReference(int? singleWeakReference) {
fbBuilder.addUint64(36, singleWeakReference);
return fbBuilder.offset;
}
- int addVectorOfWeakReferencesOffset(int offset) {
+ int addVectorOfWeakReferencesOffset(int? offset) {
fbBuilder.addOffset(37, offset);
return fbBuilder.offset;
}
- int addVectorOfStrongReferrablesOffset(int offset) {
+ int addVectorOfStrongReferrablesOffset(int? offset) {
fbBuilder.addOffset(38, offset);
return fbBuilder.offset;
}
- int addCoOwningReference(int coOwningReference) {
+ int addCoOwningReference(int? coOwningReference) {
fbBuilder.addUint64(39, coOwningReference);
return fbBuilder.offset;
}
- int addVectorOfCoOwningReferencesOffset(int offset) {
+ int addVectorOfCoOwningReferencesOffset(int? offset) {
fbBuilder.addOffset(40, offset);
return fbBuilder.offset;
}
- int addNonOwningReference(int nonOwningReference) {
+ int addNonOwningReference(int? nonOwningReference) {
fbBuilder.addUint64(41, nonOwningReference);
return fbBuilder.offset;
}
- int addVectorOfNonOwningReferencesOffset(int offset) {
+ int addVectorOfNonOwningReferencesOffset(int? offset) {
fbBuilder.addOffset(42, offset);
return fbBuilder.offset;
}
- int addAnyUniqueType(AnyUniqueAliasesTypeId anyUniqueType) {
+ int addAnyUniqueType(AnyUniqueAliasesTypeId? anyUniqueType) {
fbBuilder.addUint8(43, anyUniqueType?.value);
return fbBuilder.offset;
}
- int addAnyUniqueOffset(int offset) {
+ int addAnyUniqueOffset(int? offset) {
fbBuilder.addOffset(44, offset);
return fbBuilder.offset;
}
- int addAnyAmbiguousType(AnyAmbiguousAliasesTypeId anyAmbiguousType) {
+ int addAnyAmbiguousType(AnyAmbiguousAliasesTypeId? anyAmbiguousType) {
fbBuilder.addUint8(45, anyAmbiguousType?.value);
return fbBuilder.offset;
}
- int addAnyAmbiguousOffset(int offset) {
+ int addAnyAmbiguousOffset(int? offset) {
fbBuilder.addOffset(46, offset);
return fbBuilder.offset;
}
- int addVectorOfEnumsOffset(int offset) {
+ int addVectorOfEnumsOffset(int? offset) {
fbBuilder.addOffset(47, offset);
return fbBuilder.offset;
}
- int addSignedEnum(Race signedEnum) {
+ int addSignedEnum(Race? signedEnum) {
fbBuilder.addInt8(48, signedEnum?.value);
return fbBuilder.offset;
}
+ int addTestrequirednestedflatbufferOffset(int? offset) {
+ fbBuilder.addOffset(49, offset);
+ return fbBuilder.offset;
+ }
+ int addScalarKeySortedTablesOffset(int? offset) {
+ fbBuilder.addOffset(50, offset);
+ return fbBuilder.offset;
+ }
int finish() {
return fbBuilder.endTable();
@@ -1026,104 +1631,108 @@
}
class MonsterObjectBuilder extends fb.ObjectBuilder {
- final Vec3ObjectBuilder _pos;
- final int _mana;
- final int _hp;
- final String _name;
- final List<int> _inventory;
- final Color _color;
- final AnyTypeId _testType;
+ final Vec3ObjectBuilder? _pos;
+ final int? _mana;
+ final int? _hp;
+ final String? _name;
+ final List<int>? _inventory;
+ final Color? _color;
+ final AnyTypeId? _testType;
final dynamic _test;
- final List<TestObjectBuilder> _test4;
- final List<String> _testarrayofstring;
- final List<MonsterObjectBuilder> _testarrayoftables;
- final MonsterObjectBuilder _enemy;
- final List<int> _testnestedflatbuffer;
- final StatObjectBuilder _testempty;
- final bool _testbool;
- final int _testhashs32Fnv1;
- final int _testhashu32Fnv1;
- final int _testhashs64Fnv1;
- final int _testhashu64Fnv1;
- final int _testhashs32Fnv1a;
- final int _testhashu32Fnv1a;
- final int _testhashs64Fnv1a;
- final int _testhashu64Fnv1a;
- final List<bool> _testarrayofbools;
- final double _testf;
- final double _testf2;
- final double _testf3;
- final List<String> _testarrayofstring2;
- final List<AbilityObjectBuilder> _testarrayofsortedstruct;
- final List<int> _flex;
- final List<TestObjectBuilder> _test5;
- final List<int> _vectorOfLongs;
- final List<double> _vectorOfDoubles;
- final my_game.InParentNamespaceObjectBuilder _parentNamespaceTest;
- final List<ReferrableObjectBuilder> _vectorOfReferrables;
- final int _singleWeakReference;
- final List<int> _vectorOfWeakReferences;
- final List<ReferrableObjectBuilder> _vectorOfStrongReferrables;
- final int _coOwningReference;
- final List<int> _vectorOfCoOwningReferences;
- final int _nonOwningReference;
- final List<int> _vectorOfNonOwningReferences;
- final AnyUniqueAliasesTypeId _anyUniqueType;
+ final List<TestObjectBuilder>? _test4;
+ final List<String>? _testarrayofstring;
+ final List<MonsterObjectBuilder>? _testarrayoftables;
+ final MonsterObjectBuilder? _enemy;
+ final List<int>? _testnestedflatbuffer;
+ final StatObjectBuilder? _testempty;
+ final bool? _testbool;
+ final int? _testhashs32Fnv1;
+ final int? _testhashu32Fnv1;
+ final int? _testhashs64Fnv1;
+ final int? _testhashu64Fnv1;
+ final int? _testhashs32Fnv1a;
+ final int? _testhashu32Fnv1a;
+ final int? _testhashs64Fnv1a;
+ final int? _testhashu64Fnv1a;
+ final List<bool>? _testarrayofbools;
+ final double? _testf;
+ final double? _testf2;
+ final double? _testf3;
+ final List<String>? _testarrayofstring2;
+ final List<AbilityObjectBuilder>? _testarrayofsortedstruct;
+ final List<int>? _flex;
+ final List<TestObjectBuilder>? _test5;
+ final List<int>? _vectorOfLongs;
+ final List<double>? _vectorOfDoubles;
+ final my_game.InParentNamespaceObjectBuilder? _parentNamespaceTest;
+ final List<ReferrableObjectBuilder>? _vectorOfReferrables;
+ final int? _singleWeakReference;
+ final List<int>? _vectorOfWeakReferences;
+ final List<ReferrableObjectBuilder>? _vectorOfStrongReferrables;
+ final int? _coOwningReference;
+ final List<int>? _vectorOfCoOwningReferences;
+ final int? _nonOwningReference;
+ final List<int>? _vectorOfNonOwningReferences;
+ final AnyUniqueAliasesTypeId? _anyUniqueType;
final dynamic _anyUnique;
- final AnyAmbiguousAliasesTypeId _anyAmbiguousType;
+ final AnyAmbiguousAliasesTypeId? _anyAmbiguousType;
final dynamic _anyAmbiguous;
- final List<Color> _vectorOfEnums;
- final Race _signedEnum;
+ final List<Color>? _vectorOfEnums;
+ final Race? _signedEnum;
+ final List<int>? _testrequirednestedflatbuffer;
+ final List<StatObjectBuilder>? _scalarKeySortedTables;
MonsterObjectBuilder({
- Vec3ObjectBuilder pos,
- int mana,
- int hp,
- String name,
- List<int> inventory,
- Color color,
- AnyTypeId testType,
+ Vec3ObjectBuilder? pos,
+ int? mana,
+ int? hp,
+ String? name,
+ List<int>? inventory,
+ Color? color,
+ AnyTypeId? testType,
dynamic test,
- List<TestObjectBuilder> test4,
- List<String> testarrayofstring,
- List<MonsterObjectBuilder> testarrayoftables,
- MonsterObjectBuilder enemy,
- List<int> testnestedflatbuffer,
- StatObjectBuilder testempty,
- bool testbool,
- int testhashs32Fnv1,
- int testhashu32Fnv1,
- int testhashs64Fnv1,
- int testhashu64Fnv1,
- int testhashs32Fnv1a,
- int testhashu32Fnv1a,
- int testhashs64Fnv1a,
- int testhashu64Fnv1a,
- List<bool> testarrayofbools,
- double testf,
- double testf2,
- double testf3,
- List<String> testarrayofstring2,
- List<AbilityObjectBuilder> testarrayofsortedstruct,
- List<int> flex,
- List<TestObjectBuilder> test5,
- List<int> vectorOfLongs,
- List<double> vectorOfDoubles,
- my_game.InParentNamespaceObjectBuilder parentNamespaceTest,
- List<ReferrableObjectBuilder> vectorOfReferrables,
- int singleWeakReference,
- List<int> vectorOfWeakReferences,
- List<ReferrableObjectBuilder> vectorOfStrongReferrables,
- int coOwningReference,
- List<int> vectorOfCoOwningReferences,
- int nonOwningReference,
- List<int> vectorOfNonOwningReferences,
- AnyUniqueAliasesTypeId anyUniqueType,
+ List<TestObjectBuilder>? test4,
+ List<String>? testarrayofstring,
+ List<MonsterObjectBuilder>? testarrayoftables,
+ MonsterObjectBuilder? enemy,
+ List<int>? testnestedflatbuffer,
+ StatObjectBuilder? testempty,
+ bool? testbool,
+ int? testhashs32Fnv1,
+ int? testhashu32Fnv1,
+ int? testhashs64Fnv1,
+ int? testhashu64Fnv1,
+ int? testhashs32Fnv1a,
+ int? testhashu32Fnv1a,
+ int? testhashs64Fnv1a,
+ int? testhashu64Fnv1a,
+ List<bool>? testarrayofbools,
+ double? testf,
+ double? testf2,
+ double? testf3,
+ List<String>? testarrayofstring2,
+ List<AbilityObjectBuilder>? testarrayofsortedstruct,
+ List<int>? flex,
+ List<TestObjectBuilder>? test5,
+ List<int>? vectorOfLongs,
+ List<double>? vectorOfDoubles,
+ my_game.InParentNamespaceObjectBuilder? parentNamespaceTest,
+ List<ReferrableObjectBuilder>? vectorOfReferrables,
+ int? singleWeakReference,
+ List<int>? vectorOfWeakReferences,
+ List<ReferrableObjectBuilder>? vectorOfStrongReferrables,
+ int? coOwningReference,
+ List<int>? vectorOfCoOwningReferences,
+ int? nonOwningReference,
+ List<int>? vectorOfNonOwningReferences,
+ AnyUniqueAliasesTypeId? anyUniqueType,
dynamic anyUnique,
- AnyAmbiguousAliasesTypeId anyAmbiguousType,
+ AnyAmbiguousAliasesTypeId? anyAmbiguousType,
dynamic anyAmbiguous,
- List<Color> vectorOfEnums,
- Race signedEnum,
+ List<Color>? vectorOfEnums,
+ Race? signedEnum,
+ List<int>? testrequirednestedflatbuffer,
+ List<StatObjectBuilder>? scalarKeySortedTables,
})
: _pos = pos,
_mana = mana,
@@ -1172,110 +1781,78 @@
_anyAmbiguousType = anyAmbiguousType,
_anyAmbiguous = anyAmbiguous,
_vectorOfEnums = vectorOfEnums,
- _signedEnum = signedEnum;
+ _signedEnum = signedEnum,
+ _testrequirednestedflatbuffer = testrequirednestedflatbuffer,
+ _scalarKeySortedTables = scalarKeySortedTables;
/// Finish building, and store into the [fbBuilder].
@override
- int finish(
- fb.Builder fbBuilder) {
- assert(fbBuilder != null);
- final int nameOffset = fbBuilder.writeString(_name);
- final int inventoryOffset = _inventory?.isNotEmpty == true
- ? fbBuilder.writeListUint8(_inventory)
- : null;
- final int testOffset = _test?.getOrCreateOffset(fbBuilder);
- final int test4Offset = _test4?.isNotEmpty == true
- ? fbBuilder.writeListOfStructs(_test4)
- : null;
- final int testarrayofstringOffset = _testarrayofstring?.isNotEmpty == true
- ? fbBuilder.writeList(_testarrayofstring.map((b) => fbBuilder.writeString(b)).toList())
- : null;
- final int testarrayoftablesOffset = _testarrayoftables?.isNotEmpty == true
- ? fbBuilder.writeList(_testarrayoftables.map((b) => b.getOrCreateOffset(fbBuilder)).toList())
- : null;
- final int enemyOffset = _enemy?.getOrCreateOffset(fbBuilder);
- final int testnestedflatbufferOffset = _testnestedflatbuffer?.isNotEmpty == true
- ? fbBuilder.writeListUint8(_testnestedflatbuffer)
- : null;
- final int testemptyOffset = _testempty?.getOrCreateOffset(fbBuilder);
- final int testarrayofboolsOffset = _testarrayofbools?.isNotEmpty == true
- ? fbBuilder.writeListBool(_testarrayofbools)
- : null;
- final int testarrayofstring2Offset = _testarrayofstring2?.isNotEmpty == true
- ? fbBuilder.writeList(_testarrayofstring2.map((b) => fbBuilder.writeString(b)).toList())
- : null;
- final int testarrayofsortedstructOffset = _testarrayofsortedstruct?.isNotEmpty == true
- ? fbBuilder.writeListOfStructs(_testarrayofsortedstruct)
- : null;
- final int flexOffset = _flex?.isNotEmpty == true
- ? fbBuilder.writeListUint8(_flex)
- : null;
- final int test5Offset = _test5?.isNotEmpty == true
- ? fbBuilder.writeListOfStructs(_test5)
- : null;
- final int vectorOfLongsOffset = _vectorOfLongs?.isNotEmpty == true
- ? fbBuilder.writeListInt64(_vectorOfLongs)
- : null;
- final int vectorOfDoublesOffset = _vectorOfDoubles?.isNotEmpty == true
- ? fbBuilder.writeListFloat64(_vectorOfDoubles)
- : null;
- final int parentNamespaceTestOffset = _parentNamespaceTest?.getOrCreateOffset(fbBuilder);
- final int vectorOfReferrablesOffset = _vectorOfReferrables?.isNotEmpty == true
- ? fbBuilder.writeList(_vectorOfReferrables.map((b) => b.getOrCreateOffset(fbBuilder)).toList())
- : null;
- final int vectorOfWeakReferencesOffset = _vectorOfWeakReferences?.isNotEmpty == true
- ? fbBuilder.writeListUint64(_vectorOfWeakReferences)
- : null;
- final int vectorOfStrongReferrablesOffset = _vectorOfStrongReferrables?.isNotEmpty == true
- ? fbBuilder.writeList(_vectorOfStrongReferrables.map((b) => b.getOrCreateOffset(fbBuilder)).toList())
- : null;
- final int vectorOfCoOwningReferencesOffset = _vectorOfCoOwningReferences?.isNotEmpty == true
- ? fbBuilder.writeListUint64(_vectorOfCoOwningReferences)
- : null;
- final int vectorOfNonOwningReferencesOffset = _vectorOfNonOwningReferences?.isNotEmpty == true
- ? fbBuilder.writeListUint64(_vectorOfNonOwningReferences)
- : null;
- final int anyUniqueOffset = _anyUnique?.getOrCreateOffset(fbBuilder);
- final int anyAmbiguousOffset = _anyAmbiguous?.getOrCreateOffset(fbBuilder);
- final int vectorOfEnumsOffset = _vectorOfEnums?.isNotEmpty == true
- ? fbBuilder.writeListUint8(_vectorOfEnums.map((f) => f.value))
- : null;
-
- fbBuilder.startTable();
+ int finish(fb.Builder fbBuilder) {
+ final int? nameOffset = _name == null ? null
+ : fbBuilder.writeString(_name!);
+ final int? inventoryOffset = _inventory == null ? null
+ : fbBuilder.writeListUint8(_inventory!);
+ final int? testOffset = _test?.getOrCreateOffset(fbBuilder);
+ final int? test4Offset = _test4 == null ? null
+ : fbBuilder.writeListOfStructs(_test4!);
+ final int? testarrayofstringOffset = _testarrayofstring == null ? null
+ : fbBuilder.writeList(_testarrayofstring!.map(fbBuilder.writeString).toList());
+ final int? testarrayoftablesOffset = _testarrayoftables == null ? null
+ : fbBuilder.writeList(_testarrayoftables!.map((b) => b.getOrCreateOffset(fbBuilder)).toList());
+ final int? enemyOffset = _enemy?.getOrCreateOffset(fbBuilder);
+ final int? testnestedflatbufferOffset = _testnestedflatbuffer == null ? null
+ : fbBuilder.writeListUint8(_testnestedflatbuffer!);
+ final int? testemptyOffset = _testempty?.getOrCreateOffset(fbBuilder);
+ final int? testarrayofboolsOffset = _testarrayofbools == null ? null
+ : fbBuilder.writeListBool(_testarrayofbools!);
+ final int? testarrayofstring2Offset = _testarrayofstring2 == null ? null
+ : fbBuilder.writeList(_testarrayofstring2!.map(fbBuilder.writeString).toList());
+ final int? testarrayofsortedstructOffset = _testarrayofsortedstruct == null ? null
+ : fbBuilder.writeListOfStructs(_testarrayofsortedstruct!);
+ final int? flexOffset = _flex == null ? null
+ : fbBuilder.writeListUint8(_flex!);
+ final int? test5Offset = _test5 == null ? null
+ : fbBuilder.writeListOfStructs(_test5!);
+ final int? vectorOfLongsOffset = _vectorOfLongs == null ? null
+ : fbBuilder.writeListInt64(_vectorOfLongs!);
+ final int? vectorOfDoublesOffset = _vectorOfDoubles == null ? null
+ : fbBuilder.writeListFloat64(_vectorOfDoubles!);
+ final int? parentNamespaceTestOffset = _parentNamespaceTest?.getOrCreateOffset(fbBuilder);
+ final int? vectorOfReferrablesOffset = _vectorOfReferrables == null ? null
+ : fbBuilder.writeList(_vectorOfReferrables!.map((b) => b.getOrCreateOffset(fbBuilder)).toList());
+ final int? vectorOfWeakReferencesOffset = _vectorOfWeakReferences == null ? null
+ : fbBuilder.writeListUint64(_vectorOfWeakReferences!);
+ final int? vectorOfStrongReferrablesOffset = _vectorOfStrongReferrables == null ? null
+ : fbBuilder.writeList(_vectorOfStrongReferrables!.map((b) => b.getOrCreateOffset(fbBuilder)).toList());
+ final int? vectorOfCoOwningReferencesOffset = _vectorOfCoOwningReferences == null ? null
+ : fbBuilder.writeListUint64(_vectorOfCoOwningReferences!);
+ final int? vectorOfNonOwningReferencesOffset = _vectorOfNonOwningReferences == null ? null
+ : fbBuilder.writeListUint64(_vectorOfNonOwningReferences!);
+ final int? anyUniqueOffset = _anyUnique?.getOrCreateOffset(fbBuilder);
+ final int? anyAmbiguousOffset = _anyAmbiguous?.getOrCreateOffset(fbBuilder);
+ final int? vectorOfEnumsOffset = _vectorOfEnums == null ? null
+ : fbBuilder.writeListUint8(_vectorOfEnums!.map((f) => f.value).toList());
+ final int? testrequirednestedflatbufferOffset = _testrequirednestedflatbuffer == null ? null
+ : fbBuilder.writeListUint8(_testrequirednestedflatbuffer!);
+ final int? scalarKeySortedTablesOffset = _scalarKeySortedTables == null ? null
+ : fbBuilder.writeList(_scalarKeySortedTables!.map((b) => b.getOrCreateOffset(fbBuilder)).toList());
+ fbBuilder.startTable(50);
if (_pos != null) {
- fbBuilder.addStruct(0, _pos.finish(fbBuilder));
+ fbBuilder.addStruct(0, _pos!.finish(fbBuilder));
}
fbBuilder.addInt16(1, _mana);
fbBuilder.addInt16(2, _hp);
- if (nameOffset != null) {
- fbBuilder.addOffset(3, nameOffset);
- }
- if (inventoryOffset != null) {
- fbBuilder.addOffset(5, inventoryOffset);
- }
+ fbBuilder.addOffset(3, nameOffset);
+ fbBuilder.addOffset(5, inventoryOffset);
fbBuilder.addUint8(6, _color?.value);
fbBuilder.addUint8(7, _testType?.value);
- if (testOffset != null) {
- fbBuilder.addOffset(8, testOffset);
- }
- if (test4Offset != null) {
- fbBuilder.addOffset(9, test4Offset);
- }
- if (testarrayofstringOffset != null) {
- fbBuilder.addOffset(10, testarrayofstringOffset);
- }
- if (testarrayoftablesOffset != null) {
- fbBuilder.addOffset(11, testarrayoftablesOffset);
- }
- if (enemyOffset != null) {
- fbBuilder.addOffset(12, enemyOffset);
- }
- if (testnestedflatbufferOffset != null) {
- fbBuilder.addOffset(13, testnestedflatbufferOffset);
- }
- if (testemptyOffset != null) {
- fbBuilder.addOffset(14, testemptyOffset);
- }
+ fbBuilder.addOffset(8, testOffset);
+ fbBuilder.addOffset(9, test4Offset);
+ fbBuilder.addOffset(10, testarrayofstringOffset);
+ fbBuilder.addOffset(11, testarrayoftablesOffset);
+ fbBuilder.addOffset(12, enemyOffset);
+ fbBuilder.addOffset(13, testnestedflatbufferOffset);
+ fbBuilder.addOffset(14, testemptyOffset);
fbBuilder.addBool(15, _testbool);
fbBuilder.addInt32(16, _testhashs32Fnv1);
fbBuilder.addUint32(17, _testhashu32Fnv1);
@@ -1285,82 +1862,52 @@
fbBuilder.addUint32(21, _testhashu32Fnv1a);
fbBuilder.addInt64(22, _testhashs64Fnv1a);
fbBuilder.addUint64(23, _testhashu64Fnv1a);
- if (testarrayofboolsOffset != null) {
- fbBuilder.addOffset(24, testarrayofboolsOffset);
- }
+ fbBuilder.addOffset(24, testarrayofboolsOffset);
fbBuilder.addFloat32(25, _testf);
fbBuilder.addFloat32(26, _testf2);
fbBuilder.addFloat32(27, _testf3);
- if (testarrayofstring2Offset != null) {
- fbBuilder.addOffset(28, testarrayofstring2Offset);
- }
- if (testarrayofsortedstructOffset != null) {
- fbBuilder.addOffset(29, testarrayofsortedstructOffset);
- }
- if (flexOffset != null) {
- fbBuilder.addOffset(30, flexOffset);
- }
- if (test5Offset != null) {
- fbBuilder.addOffset(31, test5Offset);
- }
- if (vectorOfLongsOffset != null) {
- fbBuilder.addOffset(32, vectorOfLongsOffset);
- }
- if (vectorOfDoublesOffset != null) {
- fbBuilder.addOffset(33, vectorOfDoublesOffset);
- }
- if (parentNamespaceTestOffset != null) {
- fbBuilder.addOffset(34, parentNamespaceTestOffset);
- }
- if (vectorOfReferrablesOffset != null) {
- fbBuilder.addOffset(35, vectorOfReferrablesOffset);
- }
+ fbBuilder.addOffset(28, testarrayofstring2Offset);
+ fbBuilder.addOffset(29, testarrayofsortedstructOffset);
+ fbBuilder.addOffset(30, flexOffset);
+ fbBuilder.addOffset(31, test5Offset);
+ fbBuilder.addOffset(32, vectorOfLongsOffset);
+ fbBuilder.addOffset(33, vectorOfDoublesOffset);
+ fbBuilder.addOffset(34, parentNamespaceTestOffset);
+ fbBuilder.addOffset(35, vectorOfReferrablesOffset);
fbBuilder.addUint64(36, _singleWeakReference);
- if (vectorOfWeakReferencesOffset != null) {
- fbBuilder.addOffset(37, vectorOfWeakReferencesOffset);
- }
- if (vectorOfStrongReferrablesOffset != null) {
- fbBuilder.addOffset(38, vectorOfStrongReferrablesOffset);
- }
+ fbBuilder.addOffset(37, vectorOfWeakReferencesOffset);
+ fbBuilder.addOffset(38, vectorOfStrongReferrablesOffset);
fbBuilder.addUint64(39, _coOwningReference);
- if (vectorOfCoOwningReferencesOffset != null) {
- fbBuilder.addOffset(40, vectorOfCoOwningReferencesOffset);
- }
+ fbBuilder.addOffset(40, vectorOfCoOwningReferencesOffset);
fbBuilder.addUint64(41, _nonOwningReference);
- if (vectorOfNonOwningReferencesOffset != null) {
- fbBuilder.addOffset(42, vectorOfNonOwningReferencesOffset);
- }
+ fbBuilder.addOffset(42, vectorOfNonOwningReferencesOffset);
fbBuilder.addUint8(43, _anyUniqueType?.value);
- if (anyUniqueOffset != null) {
- fbBuilder.addOffset(44, anyUniqueOffset);
- }
+ fbBuilder.addOffset(44, anyUniqueOffset);
fbBuilder.addUint8(45, _anyAmbiguousType?.value);
- if (anyAmbiguousOffset != null) {
- fbBuilder.addOffset(46, anyAmbiguousOffset);
- }
- if (vectorOfEnumsOffset != null) {
- fbBuilder.addOffset(47, vectorOfEnumsOffset);
- }
+ fbBuilder.addOffset(46, anyAmbiguousOffset);
+ fbBuilder.addOffset(47, vectorOfEnumsOffset);
fbBuilder.addInt8(48, _signedEnum?.value);
+ fbBuilder.addOffset(49, testrequirednestedflatbufferOffset);
+ fbBuilder.addOffset(50, scalarKeySortedTablesOffset);
return fbBuilder.endTable();
}
/// Convenience method to serialize to byte list.
@override
- Uint8List toBytes([String fileIdentifier]) {
- fb.Builder fbBuilder = new fb.Builder();
- int offset = finish(fbBuilder);
- return fbBuilder.finish(offset, fileIdentifier);
+ Uint8List toBytes([String? fileIdentifier]) {
+ final fbBuilder = fb.Builder(deduplicateTables: false);
+ fbBuilder.finish(finish(fbBuilder), fileIdentifier);
+ return fbBuilder.buffer;
}
}
class TypeAliases {
TypeAliases._(this._bc, this._bcOffset);
factory TypeAliases(List<int> bytes) {
- fb.BufferContext rootRef = new fb.BufferContext.fromBytes(bytes);
+ final rootRef = fb.BufferContext.fromBytes(bytes);
return reader.read(rootRef, 0);
}
- static const fb.Reader<TypeAliases> reader = const _TypeAliasesReader();
+ static const fb.Reader<TypeAliases> reader = _TypeAliasesReader();
final fb.BufferContext _bc;
final int _bcOffset;
@@ -1375,13 +1922,88 @@
int get u64 => const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 18, 0);
double get f32 => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 20, 0.0);
double get f64 => const fb.Float64Reader().vTableGet(_bc, _bcOffset, 22, 0.0);
- List<int> get v8 => const fb.ListReader<int>(const fb.Int8Reader()).vTableGet(_bc, _bcOffset, 24, null);
- List<double> get vf64 => const fb.ListReader<double>(const fb.Float64Reader()).vTableGet(_bc, _bcOffset, 26, null);
+ List<int>? get v8 => const fb.Int8ListReader().vTableGetNullable(_bc, _bcOffset, 24);
+ List<double>? get vf64 => const fb.ListReader<double>(fb.Float64Reader()).vTableGetNullable(_bc, _bcOffset, 26);
@override
String toString() {
return 'TypeAliases{i8: $i8, u8: $u8, i16: $i16, u16: $u16, i32: $i32, u32: $u32, i64: $i64, u64: $u64, f32: $f32, f64: $f64, v8: $v8, vf64: $vf64}';
}
+
+ TypeAliasesT unpack() => TypeAliasesT(
+ i8: i8,
+ u8: u8,
+ i16: i16,
+ u16: u16,
+ i32: i32,
+ u32: u32,
+ i64: i64,
+ u64: u64,
+ f32: f32,
+ f64: f64,
+ v8: const fb.Int8ListReader(lazy: false).vTableGetNullable(_bc, _bcOffset, 24),
+ vf64: const fb.ListReader<double>(fb.Float64Reader(), lazy: false).vTableGetNullable(_bc, _bcOffset, 26));
+
+ static int pack(fb.Builder fbBuilder, TypeAliasesT? object) {
+ if (object == null) return 0;
+ return object.pack(fbBuilder);
+ }
+}
+
+class TypeAliasesT implements fb.Packable {
+ int i8;
+ int u8;
+ int i16;
+ int u16;
+ int i32;
+ int u32;
+ int i64;
+ int u64;
+ double f32;
+ double f64;
+ List<int>? v8;
+ List<double>? vf64;
+
+ TypeAliasesT({
+ this.i8 = 0,
+ this.u8 = 0,
+ this.i16 = 0,
+ this.u16 = 0,
+ this.i32 = 0,
+ this.u32 = 0,
+ this.i64 = 0,
+ this.u64 = 0,
+ this.f32 = 0.0,
+ this.f64 = 0.0,
+ this.v8,
+ this.vf64});
+
+ @override
+ int pack(fb.Builder fbBuilder) {
+ final int? v8Offset = v8 == null ? null
+ : fbBuilder.writeListInt8(v8!);
+ final int? vf64Offset = vf64 == null ? null
+ : fbBuilder.writeListFloat64(vf64!);
+ fbBuilder.startTable(12);
+ fbBuilder.addInt8(0, i8);
+ fbBuilder.addUint8(1, u8);
+ fbBuilder.addInt16(2, i16);
+ fbBuilder.addUint16(3, u16);
+ fbBuilder.addInt32(4, i32);
+ fbBuilder.addUint32(5, u32);
+ fbBuilder.addInt64(6, i64);
+ fbBuilder.addUint64(7, u64);
+ fbBuilder.addFloat32(8, f32);
+ fbBuilder.addFloat64(9, f64);
+ fbBuilder.addOffset(10, v8Offset);
+ fbBuilder.addOffset(11, vf64Offset);
+ return fbBuilder.endTable();
+ }
+
+ @override
+ String toString() {
+ return 'TypeAliasesT{i8: $i8, u8: $u8, i16: $i16, u16: $u16, i32: $i32, u32: $u32, i64: $i64, u64: $u64, f32: $f32, f64: $f64, v8: $v8, vf64: $vf64}';
+ }
}
class _TypeAliasesReader extends fb.TableReader<TypeAliases> {
@@ -1389,65 +2011,63 @@
@override
TypeAliases createObject(fb.BufferContext bc, int offset) =>
- new TypeAliases._(bc, offset);
+ TypeAliases._(bc, offset);
}
class TypeAliasesBuilder {
- TypeAliasesBuilder(this.fbBuilder) {
- assert(fbBuilder != null);
- }
+ TypeAliasesBuilder(this.fbBuilder);
final fb.Builder fbBuilder;
void begin() {
- fbBuilder.startTable();
+ fbBuilder.startTable(12);
}
- int addI8(int i8) {
+ int addI8(int? i8) {
fbBuilder.addInt8(0, i8);
return fbBuilder.offset;
}
- int addU8(int u8) {
+ int addU8(int? u8) {
fbBuilder.addUint8(1, u8);
return fbBuilder.offset;
}
- int addI16(int i16) {
+ int addI16(int? i16) {
fbBuilder.addInt16(2, i16);
return fbBuilder.offset;
}
- int addU16(int u16) {
+ int addU16(int? u16) {
fbBuilder.addUint16(3, u16);
return fbBuilder.offset;
}
- int addI32(int i32) {
+ int addI32(int? i32) {
fbBuilder.addInt32(4, i32);
return fbBuilder.offset;
}
- int addU32(int u32) {
+ int addU32(int? u32) {
fbBuilder.addUint32(5, u32);
return fbBuilder.offset;
}
- int addI64(int i64) {
+ int addI64(int? i64) {
fbBuilder.addInt64(6, i64);
return fbBuilder.offset;
}
- int addU64(int u64) {
+ int addU64(int? u64) {
fbBuilder.addUint64(7, u64);
return fbBuilder.offset;
}
- int addF32(double f32) {
+ int addF32(double? f32) {
fbBuilder.addFloat32(8, f32);
return fbBuilder.offset;
}
- int addF64(double f64) {
+ int addF64(double? f64) {
fbBuilder.addFloat64(9, f64);
return fbBuilder.offset;
}
- int addV8Offset(int offset) {
+ int addV8Offset(int? offset) {
fbBuilder.addOffset(10, offset);
return fbBuilder.offset;
}
- int addVf64Offset(int offset) {
+ int addVf64Offset(int? offset) {
fbBuilder.addOffset(11, offset);
return fbBuilder.offset;
}
@@ -1458,32 +2078,32 @@
}
class TypeAliasesObjectBuilder extends fb.ObjectBuilder {
- final int _i8;
- final int _u8;
- final int _i16;
- final int _u16;
- final int _i32;
- final int _u32;
- final int _i64;
- final int _u64;
- final double _f32;
- final double _f64;
- final List<int> _v8;
- final List<double> _vf64;
+ final int? _i8;
+ final int? _u8;
+ final int? _i16;
+ final int? _u16;
+ final int? _i32;
+ final int? _u32;
+ final int? _i64;
+ final int? _u64;
+ final double? _f32;
+ final double? _f64;
+ final List<int>? _v8;
+ final List<double>? _vf64;
TypeAliasesObjectBuilder({
- int i8,
- int u8,
- int i16,
- int u16,
- int i32,
- int u32,
- int i64,
- int u64,
- double f32,
- double f64,
- List<int> v8,
- List<double> vf64,
+ int? i8,
+ int? u8,
+ int? i16,
+ int? u16,
+ int? i32,
+ int? u32,
+ int? i64,
+ int? u64,
+ double? f32,
+ double? f64,
+ List<int>? v8,
+ List<double>? vf64,
})
: _i8 = i8,
_u8 = u8,
@@ -1500,17 +2120,12 @@
/// Finish building, and store into the [fbBuilder].
@override
- int finish(
- fb.Builder fbBuilder) {
- assert(fbBuilder != null);
- final int v8Offset = _v8?.isNotEmpty == true
- ? fbBuilder.writeListInt8(_v8)
- : null;
- final int vf64Offset = _vf64?.isNotEmpty == true
- ? fbBuilder.writeListFloat64(_vf64)
- : null;
-
- fbBuilder.startTable();
+ int finish(fb.Builder fbBuilder) {
+ final int? v8Offset = _v8 == null ? null
+ : fbBuilder.writeListInt8(_v8!);
+ final int? vf64Offset = _vf64 == null ? null
+ : fbBuilder.writeListFloat64(_vf64!);
+ fbBuilder.startTable(12);
fbBuilder.addInt8(0, _i8);
fbBuilder.addUint8(1, _u8);
fbBuilder.addInt16(2, _i16);
@@ -1521,20 +2136,16 @@
fbBuilder.addUint64(7, _u64);
fbBuilder.addFloat32(8, _f32);
fbBuilder.addFloat64(9, _f64);
- if (v8Offset != null) {
- fbBuilder.addOffset(10, v8Offset);
- }
- if (vf64Offset != null) {
- fbBuilder.addOffset(11, vf64Offset);
- }
+ fbBuilder.addOffset(10, v8Offset);
+ fbBuilder.addOffset(11, vf64Offset);
return fbBuilder.endTable();
}
/// Convenience method to serialize to byte list.
@override
- Uint8List toBytes([String fileIdentifier]) {
- fb.Builder fbBuilder = new fb.Builder();
- int offset = finish(fbBuilder);
- return fbBuilder.finish(offset, fileIdentifier);
+ Uint8List toBytes([String? fileIdentifier]) {
+ final fbBuilder = fb.Builder(deduplicateTables: false);
+ fbBuilder.finish(finish(fbBuilder), fileIdentifier);
+ return fbBuilder.buffer;
}
}
diff --git a/dart/test/monster_test_my_game_generated.dart b/dart/test/monster_test_my_game_generated.dart
index abd538c..70e256c 100644
--- a/dart/test/monster_test_my_game_generated.dart
+++ b/dart/test/monster_test_my_game_generated.dart
@@ -1,5 +1,5 @@
// automatically generated by the FlatBuffers compiler, do not modify
-// ignore_for_file: unused_import, unused_field, unused_local_variable
+// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable
library my_game;
@@ -12,11 +12,11 @@
class InParentNamespace {
InParentNamespace._(this._bc, this._bcOffset);
factory InParentNamespace(List<int> bytes) {
- fb.BufferContext rootRef = new fb.BufferContext.fromBytes(bytes);
+ final rootRef = fb.BufferContext.fromBytes(bytes);
return reader.read(rootRef, 0);
}
- static const fb.Reader<InParentNamespace> reader = const _InParentNamespaceReader();
+ static const fb.Reader<InParentNamespace> reader = _InParentNamespaceReader();
final fb.BufferContext _bc;
final int _bcOffset;
@@ -26,6 +26,26 @@
String toString() {
return 'InParentNamespace{}';
}
+
+ InParentNamespaceT unpack() => InParentNamespaceT();
+
+ static int pack(fb.Builder fbBuilder, InParentNamespaceT? object) {
+ if (object == null) return 0;
+ return object.pack(fbBuilder);
+ }
+}
+
+class InParentNamespaceT implements fb.Packable {
+ @override
+ int pack(fb.Builder fbBuilder) {
+ fbBuilder.startTable(0);
+ return fbBuilder.endTable();
+ }
+
+ @override
+ String toString() {
+ return 'InParentNamespaceT{}';
+ }
}
class _InParentNamespaceReader extends fb.TableReader<InParentNamespace> {
@@ -33,7 +53,7 @@
@override
InParentNamespace createObject(fb.BufferContext bc, int offset) =>
- new InParentNamespace._(bc, offset);
+ InParentNamespace._(bc, offset);
}
class InParentNamespaceObjectBuilder extends fb.ObjectBuilder {
@@ -42,19 +62,16 @@
/// Finish building, and store into the [fbBuilder].
@override
- int finish(
- fb.Builder fbBuilder) {
- assert(fbBuilder != null);
-
- fbBuilder.startTable();
+ int finish(fb.Builder fbBuilder) {
+ fbBuilder.startTable(0);
return fbBuilder.endTable();
}
/// Convenience method to serialize to byte list.
@override
- Uint8List toBytes([String fileIdentifier]) {
- fb.Builder fbBuilder = new fb.Builder();
- int offset = finish(fbBuilder);
- return fbBuilder.finish(offset, fileIdentifier);
+ Uint8List toBytes([String? fileIdentifier]) {
+ final fbBuilder = fb.Builder(deduplicateTables: false);
+ fbBuilder.finish(finish(fbBuilder), fileIdentifier);
+ return fbBuilder.buffer;
}
}
diff --git a/dart/test/monsterdata_test.mon b/dart/test/monsterdata_test.mon
new file mode 100644
index 0000000..cd52947
--- /dev/null
+++ b/dart/test/monsterdata_test.mon
Binary files differ
diff --git a/docs/source/Building.md b/docs/source/Building.md
index ad9e972..d7e9ca3 100644
--- a/docs/source/Building.md
+++ b/docs/source/Building.md
@@ -29,6 +29,27 @@
*Note that you MUST be in the root of the FlatBuffers distribution when you
run 'flattests' or `flatsampletext`, or it will fail to load its files.*
+### Make all warnings into errors
+
+By default all Flatbuffers `cmake` targets are build with `-Werror` flag.
+With this flag (or `/WX` for MSVC) C++ compiler will treat all warnings as errors.
+Additionally `-Wall -pedantic -Wextra` (or `/W4` form MSVC) flags are set.
+These flags minimize the number of possible defects in code and keep code highly portable.
+Using these flags is considered good practice but sometimes it can break dependent projects
+if a compiler is upgraded or a toolset is changed.
+Usually, newer compiler versions add new compile-time diagnostics that were unavailable before.
+These new diagnostic warnings could stop the build process if `-Werror` flag is set.
+
+It is possible to cancel `warnings as errors` flag at `cmake` configuration stage using
+`FLATBUFFERS_CXX_FLAGS` option. Compilation flags declared in `FLATBUFFERS_CXX_FLAGS` will be
+appended to the project-level `CMAKE_CXX_FLAGS` variable.
+Examples:
+
+- GCC and Clang: `cmake . -D FLATBUFFERS_CXX_FLAGS="-Wno-error"`
+- MSVC: `cmake . -D FLATBUFFERS_CXX_FLAGS="/WX-"`
+- MSVC: `cmake . -D FLATBUFFERS_CXX_FLAGS="/Wv <compiler.version>"`
+
+
## Building with VCPKG
You can download and install flatbuffers using the [vcpkg](https://github.com/Microsoft/vcpkg/) dependency manager:
@@ -100,14 +121,3 @@
set(FLATBUFFERS_MAX_PARSING_DEPTH 16)
```
to `CMakeLists.txt` file before `add_subdirectory(${FLATBUFFERS_SRC_DIR})` line.
-
-#### For Google Play apps
-
-For applications on Google Play that integrate this library, usage is tracked.
-This tracking is done automatically using the embedded version string
-(flatbuffer_version_string), and helps us continue to optimize it.
-Aside from consuming a few extra bytes in your application binary, it shouldn't
-affect your application at all. We use this information to let us know if
-FlatBuffers is useful and if we should continue to invest in it. Since this is
-open source, you are free to remove the version string but we would appreciate
-if you would leave it in.
diff --git a/docs/source/CUsage.md b/docs/source/CUsage.md
index 9aafa6f..bd1ec15 100644
--- a/docs/source/CUsage.md
+++ b/docs/source/CUsage.md
@@ -7,7 +7,7 @@
online via a C library. It can also generate buffer verifiers and fast
JSON parsers, printers.
-Great care has been taken to ensure compatibily with the main `flatc`
+Great care has been taken to ensure compatibility with the main `flatc`
project.
## General Documention
diff --git a/docs/source/Compiler.md b/docs/source/Compiler.md
index 973c411..242506a 100644
--- a/docs/source/Compiler.md
+++ b/docs/source/Compiler.md
@@ -79,7 +79,7 @@
- `--allow-non-utf8` : Pass non-UTF-8 input through parser and emit nonstandard
\x escapes in JSON. (Default is to raise parse error on non-UTF-8 input.)
-- `--natural-utf8` : Output strings with UTF-8 as human-readable strings.
+- `--natural-utf8` : Output strings with UTF-8 as human-readable strings.
By default, UTF-8 characters are printed as \uXXXX escapes."
- `--defaults-json` : Output fields whose value is equal to the default value
@@ -101,7 +101,7 @@
- `--gen-mutable` : Generate additional non-const accessors for mutating
FlatBuffers in-place.
-- `--gen-onefile` : Generate single output file for C# and Go.
+- `--gen-onefile` : Generate single output file for C#, Go, and Python.
- `--gen-name-strings` : Generate type name functions for C++.
@@ -142,23 +142,14 @@
- `--cpp-std CPP_STD` : Generate a C++ code using features of selected C++ standard.
Supported `CPP_STD` values:
- * `c++0x` - generate code compatible with old compilers (VS2010).
- * `c++11` - use C++11 code generator (default);
+ * `c++0x` - generate code compatible with old compilers (VS2010),
+ * `c++11` - use C++11 code generator (default),
+ * `c++17` - use C++17 features in generated code (experimental).
- `--object-prefix` : Customise class prefix for C++ object-based API.
- `--object-suffix` : Customise class suffix for C++ object-based API.
-- `--no-js-exports` : Removes Node.js style export lines (useful for JS)
-
-- `--goog-js-export` : Uses goog.exportsSymbol and goog.exportsProperty
- instead of Node.js style exporting. Needed for compatibility with the
- Google closure compiler (useful for JS).
-
-- `--es6-js-export` : Generates ECMAScript v6 style export definitions
- instead of Node.js style exporting. Useful when integrating flatbuffers
- with modern Javascript projects.
-
- `--go-namespace` : Generate the overrided namespace in Golang.
- `--go-import` : Generate the overrided import for flatbuffers in Golang.
@@ -206,12 +197,6 @@
- `--keep-prefix` : Keep original prefix of schema include statement.
-- `--no-fb-import` : Don't include flatbuffers import statement for TypeScript.
-
-- `--no-ts-reexport` : Don't re-export imported dependencies for TypeScript.
-
-- `--short-names` : Use short function names for JS and TypeScript.
-
- `--reflect-types` : Add minimal type reflection to code generation.
- `--reflect-names` : Add minimal type/name reflection.
@@ -228,5 +213,16 @@
- `--force-empty-vectors` : When serializing from object API representation, force
vectors to empty rather than null.
+- `--flexbuffers` : Used with "binary" and "json" options, it generates
+ data using schema-less FlexBuffers.
+
+- `--no-warnings` : Inhibit all warning messages.
+
+- `--cs-global-alias` : Prepend `global::` to all user generated csharp classes and structs.
+
+- `--json-nested-bytes` : Allow a nested_flatbuffer field to be parsed as a
+ vector of bytes in JSON, which is unsafe unless checked by a verifier
+ afterwards.
+
NOTE: short-form options for generators are deprecated, use the long form
whenever possible.
diff --git a/docs/source/CppUsage.md b/docs/source/CppUsage.md
index 2333f48..82d6f15 100644
--- a/docs/source/CppUsage.md
+++ b/docs/source/CppUsage.md
@@ -56,7 +56,7 @@
First, include the library and generated code. Then read the file into
a `char *` array, which you pass to `GetMonster()`.
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
+```cpp
#include "flatbuffers/flatbuffers.h"
#include "monster_test_generate.h"
#include <iostream> // C++ header file for printing
@@ -73,18 +73,18 @@
infile.close();
auto monster = GetMonster(data);
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+```
`monster` is of type `Monster *`, and points to somewhere *inside* your
-buffer (root object pointers are not the same as `buffer_pointer` !).
+buffer (root object pointers are not the same as `buffer_pointer` \!).
If you look in your generated header, you'll see it has
convenient accessors for all fields, e.g. `hp()`, `mana()`, etc:
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
- std::cout << "hp : " << monster->hp() << std::endl; // `80`
- std::cout << "mana : " << monster->mana() << std::endl; // default value of `150`
- std::cout << "name : " << monster->name()->c_str() << std::endl; // "MyMonster"
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+```cpp
+ std::cout << "hp : " << monster->hp() << std::endl; // '80'
+ std::cout << "mana : " << monster->mana() << std::endl; // default value of '150'
+ std::cout << "name : " << monster->name()->c_str() << std::endl; // "MyMonster"
+```
*Note: That we never stored a `mana` value, so it will return the default.*
@@ -96,7 +96,7 @@
Specifically, `CreateXxxDirect` functions and `Pack` functions for object
based API (see below) will use `CreateSharedString` to create strings.
-## Object based API. {#flatbuffers_cpp_object_based_api}
+## Object based API {#flatbuffers_cpp_object_based_api}
FlatBuffers is all about memory efficiency, which is why its base API is written
around using as little as possible of it. This does make the API clumsier
@@ -109,7 +109,7 @@
To use:
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
+```cpp
// Autogenerated class from table Monster.
MonsterT monsterobj;
@@ -123,7 +123,7 @@
// Serialize into new flatbuffer.
FlatBufferBuilder fbb;
fbb.Finish(Monster::Pack(fbb, &monsterobj));
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+```
The following attributes are specific to the object-based API code generation:
@@ -133,27 +133,30 @@
This attribute changes the member declaration to use the type directly
rather than wrapped in a unique_ptr.
-- `native_default`: "value" (on a field): For members that are declared
+- `native_default("value")` (on a field): For members that are declared
"native_inline", the value specified with this attribute will be included
verbatim in the class constructor initializer list for this member.
-- `native_custom_alloc`:"custom_allocator" (on a table or struct): When using the
+- `native_custom_alloc("custom_allocator")` (on a table or struct): When using the
object-based API all generated NativeTables that are allocated when unpacking
your flatbuffer will use "custom allocator". The allocator is also used by
any std::vector that appears in a table defined with `native_custom_alloc`.
This can be used to provide allocation from a pool for example, for faster
unpacking when using the object-based API.
- Minimal Example:
+Minimal Example:
- schema:
+schema:
+```cpp
table mytable(native_custom_alloc:"custom_allocator") {
...
}
+```
- with custom_allocator defined before flatbuffers.h is included, as:
+with `custom_allocator` defined before `flatbuffers.h` is included, as:
+```cpp
template <typename T> struct custom_allocator : public std::allocator<T> {
typedef T *pointer;
@@ -172,51 +175,77 @@
}
custom_allocator() throw() {}
+
template <class U>
custom_allocator(const custom_allocator<U>&) throw() {}
};
+```
-- `native_type`' "type" (on a struct): In some cases, a more optimal C++ data
- type exists for a given struct. For example, the following schema:
+- `native_type("type")` (on a struct): In some cases, a more optimal C++ data
+type exists for a given struct. For example, the following schema:
- struct Vec2 {
- x: float;
- y: float;
- }
+```cpp
+ struct Vec2 {
+ x: float;
+ y: float;
+ }
+```
- generates the following Object-Based API class:
+generates the following Object-Based API class:
- struct Vec2T : flatbuffers::NativeTable {
- float x;
- float y;
- };
+```cpp
+ struct Vec2T : flatbuffers::NativeTable {
+ float x;
+ float y;
+ };
+```
- However, it can be useful to instead use a user-defined C++ type since it
- can provide more functionality, eg.
+However, it can be useful to instead use a user-defined C++ type since it
+can provide more functionality, eg.
- struct vector2 {
- float x = 0, y = 0;
- vector2 operator+(vector2 rhs) const { ... }
- vector2 operator-(vector2 rhs) const { ... }
- float length() const { ... }
- // etc.
- };
+```cpp
+ struct vector2 {
+ float x = 0, y = 0;
+ vector2 operator+(vector2 rhs) const { ... }
+ vector2 operator-(vector2 rhs) const { ... }
+ float length() const { ... }
+ // etc.
+ };
+```
- The `native_type` attribute will replace the usage of the generated class
- with the given type. So, continuing with the example, the generated
- code would use |vector2| in place of |Vec2T| for all generated code.
+The `native_type` attribute will replace the usage of the generated class
+with the given type. So, continuing with the example, the generated
+code would use `vector2` in place of `Vec2T` for all generated code of
+the Object-Based API.
- However, becuase the native_type is unknown to flatbuffers, the user must
- provide the following functions to aide in the serialization process:
+However, because the `native_type` is unknown to flatbuffers, the user must
+provide the following functions to aide in the serialization process:
- namespace flatbuffers {
- FlatbufferStruct Pack(const native_type& obj);
- native_type UnPack(const FlatbufferStruct& obj);
- }
+```cpp
+ namespace flatbuffers {
+ Vec2 Pack(const vector2& obj);
+ vector2 UnPack(const Vec2& obj);
+ }
+```
-Finally, the following top-level attribute
+- `native_type_pack_name("name")` (on a struct when `native_type` is
+ specified, too): when you want to use the same `native_type` multiple times
+ (e. g. with different precision) you must make the names of the Pack/UnPack
+ functions unique, otherwise you will run into compile errors. This attribute
+ appends a name to the expected Pack/UnPack functions. So when you
+ specify `native_type_pack_name("Vec2")` in the above example you now need to
+ implement these serialization functions instead:
-- `native_include`: "path" (at file level): Because the `native_type` attribute
+```cpp
+ namespace flatbuffers {
+ Vec2 PackVec2(const vector2& obj);
+ vector2 UnPackVec2(const Vec2& obj);
+ }
+```
+
+Finally, the following top-level attributes:
+
+- `native_include("path")` (at file level): Because the `native_type` attribute
can be used to introduce types that are unknown to flatbuffers, it may be
necessary to include "external" header files in the generated code. This
attribute can be used to directly add an #include directive to the top of
@@ -225,7 +254,7 @@
- `force_align`: this attribute may not be respected in the object API,
depending on the aligned of the allocator used with `new`.
-# External references.
+# External references
An additional feature of the object API is the ability to allow you to load
multiple independent FlatBuffers, and have them refer to eachothers objects
@@ -244,7 +273,7 @@
When you call `UnPack` (or `Create`), you'll need a function that maps from
hash to the object (see `resolver_function_t` for details).
-# Using different pointer types.
+# Using different pointer types
By default the object tree is built out of `std::unique_ptr`, but you can
influence this either globally (using the `--cpp-ptr-type` argument to
@@ -255,13 +284,13 @@
pointer type specified by the `--cpp-ptr-type` argument to `flatc` from a
flatbuffer field set the `cpp_ptr_type` attribute to `default_ptr_type`.
-# Using different string type.
+# Using different string type
By default the object tree is built out of `std::string`, but you can
influence this either globally (using the `--cpp-str-type` argument to
`flatc`) or per field using the `cpp_str_type` attribute.
-The type must support T::c_str(), T::length() and T::empty() as member functions.
+The type must support `T::c_str()`, `T::length()` and `T::empty()` as member functions.
Further, the type must be constructible from std::string, as by default a
std::string instance is constructed and then used to initialize the custom
@@ -270,7 +299,7 @@
per field attribute `cpp_str_flex_ctor` can be used to change this behavior,
so that the custom string type is constructed by passing the pointer and
length of the FlatBuffers String. The custom string class will require a
-constructor in the following format: custom_str_class(const char *, size_t).
+constructor in the following format: `custom_str_class(const char *, size_t)`.
Please note that the character array is not guaranteed to be NULL terminated,
you should always use the provided size to determine end of string.
@@ -281,7 +310,7 @@
even allows you to change sizes of strings and vectors in-place.
The way this works is very elegant; there is actually a FlatBuffer schema that
-describes schemas (!) which you can find in `reflection/reflection.fbs`.
+describes schemas (\!) which you can find in `reflection/reflection.fbs`.
The compiler, `flatc`, can write out any schemas it has just parsed as a binary
FlatBuffer, corresponding to this meta-schema.
@@ -299,7 +328,7 @@
## Mini Reflection
A more limited form of reflection is available for direct inclusion in
-generated code, which doesn't any (binary) schema access at all. It was designed
+generated code, which doesn't do any (binary) schema access at all. It was designed
to keep the overhead of reflection as low as possible (on the order of 2-6
bytes per field added to your executable), but doesn't contain all the
information the (binary) schema contains.
@@ -390,9 +419,9 @@
Each root type will have a verification function generated for it,
e.g. for `Monster`, you can call:
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
+```cpp
bool ok = VerifyMonsterBuffer(Verifier(buf, len));
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+```
if `ok` is true, the buffer is safe to read.
@@ -458,15 +487,15 @@
convenient `LoadFile()` utility function in `flatbuffers/util.h` if you
wish). Construct a parser:
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
+```cpp
flatbuffers::Parser parser;
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+```
Now you can parse any number of text files in sequence:
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
+```cpp
parser.Parse(text_file.c_str());
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+```
This works similarly to how the command-line compiler works: a sequence
of files parsed by the same `Parser` object allow later files to
@@ -498,7 +527,7 @@
a FlatBuffer is contained in a FlatBufferBuilder instance, and no memory
outside of it is touched. To make this thread safe, either do not
share instances of FlatBufferBuilder between threads (recommended), or
-manually wrap it in synchronisation primites. There's no automatic way to
+manually wrap it in synchronisation primitives. There's no automatic way to
accomplish this, by design, as we feel multithreaded construction
of a single buffer will be rare, and synchronisation overhead would be costly.
diff --git a/docs/source/CsharpUsage.md b/docs/source/CsharpUsage.md
index 83f4842..abfcbf6 100644
--- a/docs/source/CsharpUsage.md
+++ b/docs/source/CsharpUsage.md
@@ -180,7 +180,8 @@
An additional feature of the object API is the ability to allow you to
serialize & deserialize a JSON text.
To use Json Serialization, add `--cs-gen-json-serializer` option to `flatc` and
-add `Newtonsoft.Json` nuget package to csproj.
+add `Newtonsoft.Json` nuget package to csproj. This requires explicitly setting
+the `--gen-object-api` option as well.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cs}
// Deserialize MonsterT from json
@@ -192,7 +193,7 @@
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Limitation
- * `hash` attribute currentry not supported.
+ * `hash` attribute currently not supported.
* NuGet package Dependency
* [Newtonsoft.Json](https://github.com/JamesNK/Newtonsoft.Json)
diff --git a/docs/source/DartUsage.md b/docs/source/DartUsage.md
index 6670cc5..515a644 100644
--- a/docs/source/DartUsage.md
+++ b/docs/source/DartUsage.md
@@ -105,4 +105,27 @@
not currently an option in Flutter - follow [this issue](https://github.com/flutter/flutter/issues/7053)
for the latest).
-<br>
+## Object based API
+
+FlatBuffers is all about memory efficiency, which is why its base API is written
+around using as little as possible of it. This does make the API clumsier
+(requiring pre-order construction of all data, and making mutation harder).
+
+For times when efficiency is less important a more convenient object based API
+can be used (through `--gen-object-api`) that is able to unpack & pack a FlatBuffer
+into objects and lists, allowing for convenient construction, access and mutation.
+
+To use:
+
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.dart}
+ // Deserialize from buffer into object.
+ MonsterT monster = Monster(flatbuffer).unpack();
+
+ // Update object directly like a Dart class instance.
+ print(monster.Name);
+ monster.Name = "Bob"; // Change the name.
+
+ // Serialize into new flatbuffer.
+ final fbb = Builder();
+ fbb.Finish(monster.pack(fbb));
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
diff --git a/docs/source/FlatBuffers.md b/docs/source/FlatBuffers.md
index 2a2133f..bbd2cb0 100644
--- a/docs/source/FlatBuffers.md
+++ b/docs/source/FlatBuffers.md
@@ -64,8 +64,8 @@
with the primary difference being that FlatBuffers does not need a parsing/
unpacking step to a secondary representation before you can
access data, often coupled with per-object memory allocation. The code
-is an order of magnitude bigger, too. Protocol Buffers has neither optional
-text import/export nor schema language features like unions.
+is an order of magnitude bigger, too. Protocol Buffers has no optional
+text import/export.
### But all the cool kids use JSON!
diff --git a/docs/source/IntermediateRepresentation.md b/docs/source/IntermediateRepresentation.md
new file mode 100644
index 0000000..f4eb075
--- /dev/null
+++ b/docs/source/IntermediateRepresentation.md
@@ -0,0 +1,35 @@
+# Flatbuffers Intermediate Representation {#intermediate_representation}
+
+We use [reflection.fbs](https://github.com/google/flatbuffers/blob/master/reflection/reflection.fbs)
+as our intermediate representation. `flatc` parses `.fbs` files, checks them for
+errors and stores the resulting data in this IR, outputting `.bfbs` files.
+Since this IR is a Flatbuffer, you can load and use it at runtime for runtime
+reflection purposes.
+
+There are some quirks:
+- Tables and Structs are serialized as `Object`s.
+- Unions and Enums are serialized as `Enum`s.
+- It is the responsibility of the code generator to check the `advanced_features`
+ field of `Schema`. These mark the presence of new, backwards incompatible,
+ schema features. Code generators must error if generating a schema with
+ unrecognized advanced features.
+- Filenames are relative to a "project root" denoted by "//" in the path. This
+ may be specified in flatc with `--bfbs-filenames=$PROJECT_ROOT`, or it will be
+ inferred to be the directory containing the first provided schema file.
+
+
+## Invocation
+You can invoke it like so
+```{.sh}
+flatc -b --schema ${your_fbs_files}
+```
+This generates `.bfbs` (binary flatbuffer schema) files.
+
+Some information is not included by default. See the `--bfbs-filenames` and
+`--bfbs-comments` flags. These may be necessary for code-generators, so they can
+add documentation and maybe name generated files (depending on the generator).
+
+
+TODO(cneo): Flags to output bfbs as flexbuffers or json.
+
+TODO(cneo): Tutorial for building a flatc plugin.
diff --git a/docs/source/Internals.md b/docs/source/Internals.md
index 389a8f9..591f040 100644
--- a/docs/source/Internals.md
+++ b/docs/source/Internals.md
@@ -85,10 +85,12 @@
They start with an `soffset_t` to a vtable. This is a signed version of
`uoffset_t`, since vtables may be stored anywhere relative to the object.
-This offset is substracted (not added) from the object start to arrive at
+This offset is subtracted (not added) from the object start to arrive at
the vtable start. This offset is followed by all the
fields as aligned scalars (or offsets). Unlike structs, not all fields
-need to be present. There is no set order and layout.
+need to be present. There is no set order and layout. A table may contain
+field offsets that point to the same value if the user explicitly
+serializes the same offset twice.
To be able to access fields regardless of these uncertainties, we go
through a vtable of offsets. Vtables are shared between any objects that
@@ -111,13 +113,21 @@
default value is return. Otherwise, the entry is used as offset to the
field to be read.
+### Unions
+
+Unions are encoded as the combination of two fields: an enum representing the
+union choice and the offset to the actual element. FlatBuffers reserves the
+enumeration constant `NONE` (encoded as 0) to mean that the union field is not
+set.
+
### Strings and Vectors
Strings are simply a vector of bytes, and are always
null-terminated. Vectors are stored as contiguous aligned scalar
elements prefixed by a 32bit element count (not including any
null termination). Neither is stored inline in their parent, but are referred to
-by offset.
+by offset. A vector may consist of more than one offset pointing to the same
+value if the user explicitly serializes the same offset twice.
### Construction
@@ -346,6 +356,9 @@
bytes (one per element of the vector), which are always following the vector,
and are always a uint8_t even if the vector is made up of bigger scalars.
+A vector may include more than one offset pointing to the same value if the
+user explicitly serializes the same offset twice.
+
### Types
A type byte is made up of 2 components (see flexbuffers.h for exact values):
@@ -422,7 +435,7 @@
values *have* to be stored in sorted order (as determined by `strcmp`), such
that lookups can be made using binary search.
-The reason the key vector is a seperate structure from the value vector is
+The reason the key vector is a separate structure from the value vector is
such that it can be shared between multiple value vectors, and also to
allow it to be treated as its own individual vector in code.
diff --git a/docs/source/JavaScriptUsage.md b/docs/source/JavaScriptUsage.md
index c321c95..64764e2 100644
--- a/docs/source/JavaScriptUsage.md
+++ b/docs/source/JavaScriptUsage.md
@@ -16,43 +16,31 @@
## FlatBuffers JavaScript library code location
-The code for the FlatBuffers JavaScript library can be found at
-`flatbuffers/js`. You can browse the library code on the [FlatBuffers
-GitHub page](https://github.com/google/flatbuffers/tree/master/js).
+The generated code for the FlatBuffers JavaScript library can be found at
+https://www.npmjs.com/package/flatbuffers. To use it from sources:
-## Testing the FlatBuffers JavaScript library
+1. Run `npm run compile` from the main folder to generate JS files from TS.
+1. In your project, install it as a normal dependency, using the flatbuffers
+folder as the source.
-The code to test the JavaScript library can be found at `flatbuffers/tests`.
-The test code itself is located in [JavaScriptTest.js](https://github.com/
-google/flatbuffers/blob/master/tests/JavaScriptTest.js).
-
-To run the tests, use the [JavaScriptTest.sh](https://github.com/google/
-flatbuffers/blob/master/tests/JavaScriptTest.sh) shell script.
-
-*Note: The JavaScript test file requires [Node.js](https://nodejs.org/en/).*
-
-## Using the FlatBuffers JavaScript libary
+## Using the FlatBuffers JavaScript library
*Note: See [Tutorial](@ref flatbuffers_guide_tutorial) for a more in-depth
-example of how to use FlatBuffers in JavaScript.*
+example of how to use FlatBuffers.*
-FlatBuffers supports both reading and writing FlatBuffers in JavaScript.
+Due to the complexity related with large amounts of JS flavors and module types,
+native JS support has been replaced in 2.0 by transpilation from TypeScript.
-To use FlatBuffers in your own code, first generate JavaScript classes from your
-schema with the `--js` option to `flatc`. Then you can include both FlatBuffers
-and the generated code to read or write a FlatBuffer.
+Please look at [TypeScript usage](@ref flatbuffers_guide_use_typescript) and
+transpile your sources to desired JS flavor. The minimal steps to get up and
+running with JS are:
-For example, here is how you would read a FlatBuffer binary file in Javascript:
-First, include the library and generated code. Then read the file into an
-`Uint8Array`. Make a `flatbuffers.ByteBuffer` out of the `Uint8Array`, and pass
-the ByteBuffer to the `getRootAsMonster` function.
-
-*Note: Both JavaScript module loaders (e.g. Node.js) and browser-based
-HTML/JavaScript code segments are shown below in the following snippet:*
+1. Generate TS files from `*.fbs` by using the `--ts` option.
+1. Transpile resulting TS files to desired JS flavor using `tsc` (see
+ https://www.typescriptlang.org/download for installation instructions).
~~~{.js}
- // Note: These require functions are specific to JavaScript module loaders
- // (namely, Node.js). See below for a browser-based example.
+ // Note: These require functions are an example - use your desired module flavor.
var fs = require('fs');
var flatbuffers = require('../flatbuffers').flatbuffers;
@@ -65,7 +53,7 @@
//--------------------------------------------------------------------------//
- // Note: This code is specific to browser-based HTML/JavaScript. See above
+ // Note: This code is an example of browser-based HTML/JavaScript. See above
// for the code using JavaScript module loaders (e.g. Node.js).
<script src="../js/flatbuffers.js"></script>
<script src="monster_generated.js"></script>
diff --git a/docs/source/LobsterUsage.md b/docs/source/LobsterUsage.md
index 9d69caf..723966b 100644
--- a/docs/source/LobsterUsage.md
+++ b/docs/source/LobsterUsage.md
@@ -71,7 +71,7 @@
makes use of native support for writing binary values, and access of vtables.
Both generated code and the runtime library are therefore small and fast.
-Actual speed will depend on wether you use Lobster as bytecode VM or compiled to
+Actual speed will depend on whether you use Lobster as bytecode VM or compiled to
C++.
## Text Parsing
diff --git a/docs/source/LuaUsage.md b/docs/source/LuaUsage.md
index 75b1f3b..43c370f 100644
--- a/docs/source/LuaUsage.md
+++ b/docs/source/LuaUsage.md
@@ -29,8 +29,8 @@
To run the tests, use the [LuaTest.sh](https://github.com/google/flatbuffers/
blob/master/tests/LuaTest.sh) shell script.
-*Note: This script requires [Lua 5.3](https://www.lua.org/) to be
-installed.*
+*Note: This script requires [Lua 5.3](https://www.lua.org/) and
+[LuaJIT](http://luajit.org/) to be installed.*
## Using the FlatBuffers Lua library
diff --git a/docs/source/RustUsage.md b/docs/source/RustUsage.md
index 6819117..9e959a9 100644
--- a/docs/source/RustUsage.md
+++ b/docs/source/RustUsage.md
@@ -36,7 +36,7 @@
[integration_test.rs](https://github.com/google/flatbuffers/blob/master/tests/rust_usage_test/tests/integration_test.rs)
This test file requires `flatc` to be present. To review how to build the project,
-please read the [Building](@ref flatbuffers_guide_building) documenation.
+please read the [Building](@ref flatbuffers_guide_building) documentation.
To run the tests, execute `RustTest.sh` from the `flatbuffers/tests` directory.
For example, on [Linux](https://en.wikipedia.org/wiki/Linux), you would simply
diff --git a/docs/source/Schemas.md b/docs/source/Schemas.md
index 06c0f5c..10ed260 100644
--- a/docs/source/Schemas.md
+++ b/docs/source/Schemas.md
@@ -211,9 +211,11 @@
open-ended way, for example for use as files, see the file identification
feature below.
-There is an experimental support only in C++ for a vector of unions
-(and types). In the example IDL file above, use [Any] to add a
-vector of Any to Monster table.
+There is an experimental support only in C++ for a vector of unions (and
+types). In the example IDL file above, use [Any] to add a vector of Any to
+Monster table. There is also experimental support for other types besides
+tables in unions, in particular structs and strings. There's no direct support
+for scalars in unions, but they can be wrapped in a struct at no space cost.
### Namespaces
@@ -237,9 +239,9 @@
### Root type
-This declares what you consider to be the root table (or struct) of the
-serialized data. This is particularly important for parsing JSON data,
-which doesn't include object type information.
+This declares what you consider to be the root table of the serialized
+data. This is particularly important for parsing JSON data, which doesn't
+include object type information.
### File identification and extension
@@ -488,7 +490,7 @@
tempted to use a dictionary.
Similarly, strings as values should only be used when they are
-truely open-ended. If you can, always use an enum instead.
+truly open-ended. If you can, always use an enum instead.
FlatBuffers doesn't have inheritance, so the way to represent a set
of related data structures is a union. Unions do have a cost however,
@@ -590,7 +592,7 @@
table { b:int; }
-NOT ok. We can only remove a field by deprecation, regardless of wether we use
+NOT ok. We can only remove a field by deprecation, regardless of whether we use
explicit ids or not.
table { a:uint; b:uint; }
@@ -635,10 +637,14 @@
Some `FlatBufferBuilder` implementations have an option called `force_defaults`
that circumvents this "not writing defaults" behavior you can then use
`IsFieldPresent` to query presence.
-
+/
Another option that works in all languages is to wrap a scalar field in a
struct. This way it will return null if it is not present. This will be slightly
less ergonomic but structs don't take up any more space than the scalar they
represent.
[Interface Definition Language]: https://en.wikipedia.org/wiki/Interface_description_language
+
+## Writing your own code generator.
+
+See [our intermediate representation](@ref intermediate_representation).
diff --git a/docs/source/Support.md b/docs/source/Support.md
index 4cac209..3436a6f 100644
--- a/docs/source/Support.md
+++ b/docs/source/Support.md
@@ -25,7 +25,7 @@
Simple mutation | Yes | Yes | Yes | Yes | No | No | No | No | No | No | No | No | Yes
Reflection | Yes | No | No | No | No | No | No | Basic | No | No | No | No | No
Buffer verifier | Yes | No | No | No | No | No | No | Yes | No | No | No | No | No
-Native Object API | Yes | No | Yes | Yes | Yes | Yes | Yes | No | No | No | No | No | No
+Native Object API | Yes | No | Yes | Yes | Yes | Yes | Yes | No | No | Yes | No | No | No
Optional Scalars | Yes | Yes | Yes | No | No | Yes | Yes | Yes | No | No | Yes | Yes | Yes
Flexbuffers | Yes | Yes | ? | ? | ? | ? | ? | ? | ? | ? | ? | Yes | ?
Testing: basic | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | ? | Yes | Yes | Yes | Yes
diff --git a/docs/source/SwiftUsage.md b/docs/source/SwiftUsage.md
index d5640f6..1c438f2 100644
--- a/docs/source/SwiftUsage.md
+++ b/docs/source/SwiftUsage.md
@@ -64,7 +64,8 @@
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.swift}
let hp = monster.hp
- let pos = monster.pos
+ let pos = monster.pos // uses native swift structs
+ let pos = monster.mutablePos // uses flatbuffers structs
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -76,8 +77,10 @@
if !monster.mutate(hp: 10) {
fatalError("couldn't mutate")
}
- // mutate a struct field
- let vec = monster.pos.mutate(z: 4)
+ // mutate a struct field using flatbuffers struct
+ // DONT use monster.pos to mutate since swift copy on write
+ // will not mutate the value in the buffer
+ let vec = monster.mutablePos.mutate(z: 4)
// This mutation will fail because the mana field is not available in
// the buffer. It should be set when creating the buffer.
diff --git a/docs/source/Tutorial.md b/docs/source/Tutorial.md
index 419ea09..f633425 100644
--- a/docs/source/Tutorial.md
+++ b/docs/source/Tutorial.md
@@ -130,7 +130,7 @@
[sample_binary.py](https://github.com/google/flatbuffers/blob/master/samples/sample_binary.py)
</div>
<div class="language-javascript">
-[samplebinary.js](https://github.com/google/flatbuffers/blob/master/samples/samplebinary.js)
+No sample binary is provided, since JS needs to be transpiled from TypeScript. Please see TypeScript support.
</div>
<div class="language-typescript">
<em>none yet</em>
@@ -231,7 +231,7 @@
`uint`, or `float`) will be given a default of `0` while strings and tables will
be given a default of `null`. Another thing to note is the line `friendly:bool =
false (deprecated);`. Since you cannot delete fields from a `table` (to support
-backwards compatability), you can set fields as `deprecated`, which will prevent
+backwards compatibility), you can set fields as `deprecated`, which will prevent
the generation of accessors for this field in the generated code. Be careful
when using `deprecated`, however, as it may break legacy code that used this
accessor.
@@ -321,7 +321,9 @@
<div class="language-javascript">
~~~{.sh}
cd flatbuffers/samples
- ./../flatc --js monster.fbs
+ ./../flatc --ts monster.fbs
+ # customize your TS -> JS transpilation
+ tsc monster_generated.ts
~~~
</div>
<div class="language-typescript">
@@ -439,8 +441,7 @@
</div>
<div class="language-javascript">
~~~{.js}
- // The following code is for JavaScript module loaders (e.g. Node.js). See
- // below for a browser-based HTML/JavaScript example of including the library.
+ // The following code is an example - use your desired module flavor by transpiling from TS.
var flatbuffers = require('/js/flatbuffers').flatbuffers;
var MyGame = require('./monster_generated').MyGame; // Generated by `flatc`.
@@ -544,10 +545,10 @@
import Flatbuffers
// typealiases for convenience
- typealias Monster = MyGame1.Sample.Monster
- typealias Weapon = MyGame1.Sample.Weapon
- typealias Color = MyGame1.Sample.Color
- typealias Vec3 = MyGame1.Sample.Vec3
+ typealias Monster = MyGame1_Sample_Monster
+ typealias Weapon = MyGame1_Sample_Weapon
+ typealias Color = MyGame1_Sample_Color
+ typealias Vec3 = MyGame1_Sample_Vec3
~~~
</div>
@@ -741,16 +742,16 @@
weapon_two = builder.CreateString('Axe')
# Create the first `Weapon` ('Sword').
- MyGame.Sample.Weapon.WeaponStart(builder)
- MyGame.Sample.Weapon.WeaponAddName(builder, weapon_one)
- MyGame.Sample.Weapon.WeaponAddDamage(builder, 3)
- sword = MyGame.Sample.Weapon.WeaponEnd(builder)
+ MyGame.Sample.Weapon.Start(builder)
+ MyGame.Sample.Weapon.AddName(builder, weapon_one)
+ MyGame.Sample.Weapon.AddDamage(builder, 3)
+ sword = MyGame.Sample.Weapon.End(builder)
# Create the second `Weapon` ('Axe').
- MyGame.Sample.Weapon.WeaponStart(builder)
- MyGame.Sample.Weapon.WeaponAddName(builder, weapon_two)
- MyGame.Sample.Weapon.WeaponAddDamage(builder, 5)
- axe = MyGame.Sample.Weapon.WeaponEnd(builder)
+ MyGame.Sample.Weapon.Start(builder)
+ MyGame.Sample.Weapon.AddName(builder, weapon_two)
+ MyGame.Sample.Weapon.AddDamage(builder, 5)
+ axe = MyGame.Sample.Weapon.End(builder)
~~~
</div>
<div class="language-javascript">
@@ -1014,10 +1015,10 @@
# Create a `vector` representing the inventory of the Orc. Each number
# could correspond to an item that can be claimed after he is slain.
# Note: Since we prepend the bytes, this loop iterates in reverse.
- MyGame.Sample.Monster.MonsterStartInventoryVector(builder, 10)
+ MyGame.Sample.Monster.StartInventoryVector(builder, 10)
for i in reversed(range(0, 10)):
builder.PrependByte(i)
- inv = builder.EndVector(10)
+ inv = builder.EndVector()
~~~
</div>
<div class="language-javascript">
@@ -1089,7 +1090,7 @@
</div>
<div class="language-lua">
~~~{.py}
- -- Serialize a name for our mosnter, called 'orc'
+ -- Serialize a name for our monster, called 'orc'
local name = builder:CreateString("Orc")
-- Create a `vector` representing the inventory of the Orc. Each number
@@ -1204,10 +1205,10 @@
~~~{.py}
# Create a FlatBuffer vector and prepend the weapons.
# Note: Since we prepend the data, prepend them in reverse order.
- MyGame.Sample.Monster.MonsterStartWeaponsVector(builder, 2)
+ MyGame.Sample.Monster.StartWeaponsVector(builder, 2)
builder.PrependUOffsetTRelative(axe)
builder.PrependUOffsetTRelative(sword)
- weapons = builder.EndVector(2)
+ weapons = builder.EndVector()
~~~
</div>
<div class="language-javascript">
@@ -1333,10 +1334,10 @@
</div>
<div class="language-python">
~~~{.py}
- MyGame.Sample.Monster.MonsterStartPathVector(builder, 2)
+ MyGame.Sample.Monster.StartPathVector(builder, 2)
MyGame.Sample.Vec3.CreateVec3(builder, 1.0, 2.0, 3.0)
MyGame.Sample.Vec3.CreateVec3(builder, 4.0, 5.0, 6.0)
- path = builder.EndVector(2)
+ path = builder.EndVector()
~~~
</div>
<div class="language-javascript">
@@ -1420,10 +1421,21 @@
<div class="language-swift">
~~~{.swift}
//
- Monster.startVectorOfvec3(2, in: &fbb)
- MyGame_Example_Vec3.createVec3(builder: &fbb, x: 1, y: 2, z: 3)
- MyGame_Example_Vec3.createVec3(builder: &fbb, x: 4, y: 5, z: 6)
- let points = fbb.endVectorOfStructs(count: size)
+ let points = fbb.createVector(ofStructs: [
+ Vec3(x: 1, y: 2, z: 3),
+ Vec3(x: 4, y: 5, z: 6)
+ ])
+
+ // OR
+ var vec3 = [
+ Vec3(x: 1, y: 2, z: 3),
+ Vec3(x: 4, y: 5, z: 6)
+ ]
+ Monster.startVectorOfVec3(2, in: &fbb)
+ for i in obj {
+ _ = create(struct: i)
+ }
+ let points = fbb.endVector(len: size)
~~~
</div>
@@ -1513,21 +1525,21 @@
</div>
<div class="language-python">
~~~{.py}
- # Create our monster by using `MonsterStart()` and `MonsterEnd()`.
- MyGame.Sample.Monster.MonsterStart(builder)
- MyGame.Sample.Monster.MonsterAddPos(builder,
+ # Create our monster by using `Monster.Start()` and `Monster.End()`.
+ MyGame.Sample.Monster.Start(builder)
+ MyGame.Sample.Monster.AddPos(builder,
MyGame.Sample.Vec3.CreateVec3(builder, 1.0, 2.0, 3.0))
- MyGame.Sample.Monster.MonsterAddHp(builder, 300)
- MyGame.Sample.Monster.MonsterAddName(builder, name)
- MyGame.Sample.Monster.MonsterAddInventory(builder, inv)
- MyGame.Sample.Monster.MonsterAddColor(builder,
+ MyGame.Sample.Monster.AddHp(builder, 300)
+ MyGame.Sample.Monster.AddName(builder, name)
+ MyGame.Sample.Monster.AddInventory(builder, inv)
+ MyGame.Sample.Monster.AddColor(builder,
MyGame.Sample.Color.Color().Red)
- MyGame.Sample.Monster.MonsterAddWeapons(builder, weapons)
- MyGame.Sample.Monster.MonsterAddEquippedType(
+ MyGame.Sample.Monster.AddWeapons(builder, weapons)
+ MyGame.Sample.Monster.AddEquippedType(
builder, MyGame.Sample.Equipment.Equipment().Weapon)
- MyGame.Sample.Monster.MonsterAddEquipped(builder, axe)
- MyGame.Sample.Monster.MonsterAddPath(builder, path)
- orc = MyGame.Sample.Monster.MonsterEnd(builder)
+ MyGame.Sample.Monster.AddEquipped(builder, axe)
+ MyGame.Sample.Monster.AddPath(builder, path)
+ orc = MyGame.Sample.Monster.End(builder)
~~~
</div>
<div class="language-javascript">
@@ -1702,17 +1714,16 @@
</div>
<div class="language-swift">
~~~{.swift}
- let start = Monster.startMonster(&builder)
- let posStruct = MyGame_Example_Vec3.createVec3(builder: &builder, x: 1, y: 2, z: 3)
- Monster.add(pos: pos, &builder)
- Monster.add(hp: 300, &builder)
- Monster.add(name: name, &builder)
- Monster.addVectorOf(inventory: inventoryOffset, &builder)
- Monster.add(color: .red, &builder)
- Monster.addVectorOf(weapons: weaponsOffset, &builder)
- Monster.add(equippedType: .weapon, &builder)
- Monster.add(equipped: axe, &builder)
- var orc = Monster.endMonster(&builder, start: start)
+ let orc = Monster.createMonster(
+ &builder,
+ pos: MyGame_Sample_Vec3(x: 1, y: 2, z: 3),
+ hp: 300,
+ nameOffset: name,
+ inventoryVectorOffset: inventoryOffset,
+ color: .red,
+ weaponsVectorOffset: weaponsOffset,
+ equippedType: .weapon,
+ equippedOffset: axe)
~~~
</div>
@@ -1780,6 +1791,21 @@
~~~
</div>
+<div class="language-swift">
+~~~{.swift}
+ let start = Monster.startMonster(&builder)
+ Monster.add(pos: Vec3(x: 1, y: 2, z: 3), &builder)
+ Monster.add(hp: 300, &builder)
+ Monster.add(name: name, &builder)
+ Monster.addVectorOf(inventory: inventoryOffset, &builder)
+ Monster.add(color: .red, &builder)
+ Monster.addVectorOf(weapons: weaponsOffset, &builder)
+ Monster.add(equippedType: .weapon, &builder)
+ Monster.add(equipped: axe, &builder)
+ var orc = Monster.endMonster(&builder, start: start)
+~~~
+</div>
+
Before finishing the serialization, let's take a quick look at FlatBuffer
`union Equipped`. There are two parts to each FlatBuffer `union`. The first is
a hidden field `_type` that is generated to hold the type of `table` referred
@@ -1794,7 +1820,7 @@
<div class="language-cpp">
~~~{.cpp}
monster_builder.add_equipped_type(Equipment_Weapon); // Union type
- monster_builder.add_equipped(axe); // Union data
+ monster_builder.add_equipped(axe.Union()); // Union data
~~~
</div>
<div class="language-java">
@@ -1823,9 +1849,9 @@
</div>
<div class="language-python">
~~~{.py}
- MyGame.Sample.Monster.MonsterAddEquippedType( # Union type
+ MyGame.Sample.Monster.AddEquippedType( # Union type
builder, MyGame.Sample.Equipment.Equipment().Weapon)
- MyGame.Sample.Monster.MonsterAddEquipped(builder, axe) # Union data
+ MyGame.Sample.Monster.AddEquipped(builder, axe) # Union data
~~~
</div>
<div class="language-javascript">
@@ -2199,14 +2225,13 @@
</div>
<div class="language-javascript">
~~~{.js}
- // The following code is for JavaScript module loaders (e.g. Node.js). See
- // below for a browser-based HTML/JavaScript example of including the library.
+ // The following code is an example - use your desired module flavor by transpiling from TS.
var flatbuffers = require('/js/flatbuffers').flatbuffers;
var MyGame = require('./monster_generated').MyGame; // Generated by `flatc`.
//--------------------------------------------------------------------------//
- // The following code is for browser-based HTML/JavaScript. Use the above code
+ // The following code an example for browser-based HTML/JavaScript. Use the above code
// for JavaScript module loaders (e.g. Node.js).
<script src="../js/flatbuffers.js"></script>
<script src="monster_generated.js"></script> // Generated by `flatc`.
@@ -2357,7 +2382,7 @@
buf = /* the data you just read, in an object of type "bytearray" */
// Get an accessor to the root object inside the buffer.
- monster = MyGame.Sample.Monster.Monster.GetRootAsMonster(buf, 0)
+ monster = MyGame.Sample.Monster.Monster.GetRootAs(buf, 0)
# Note: We use `0` for the offset here, which is typical for most buffers
# you would read. If you wanted to read from the `builder.Bytes` directly,
@@ -2945,7 +2970,7 @@
<div class="language-cpp">
~~~{.cpp}
- auto union_type = monster.equipped_type();
+ auto union_type = monster->equipped_type();
if (union_type == Equipment_Weapon) {
auto weapon = static_cast<const Weapon*>(monster->equipped()); // Requires `static_cast`
@@ -3239,7 +3264,8 @@
~~~{.swift}
let monster = Monster.getRootAsMonster(bb: ByteBuffer(bytes: buf))
monster.mutate(hp: 10) // mutates a value in a table
- monster.pos.mutate(z: 4) // mutates a value in a struct
+ /// to mutate structs in swift you have to use the mutable accessors
+ monster.mutablePos.mutate(z: 4) // mutates a value in a struct
monster.mutate(inventory: 6, at index: 0) // mutates a value in an Scalar array
~~~
</div>
@@ -3366,6 +3392,125 @@
## Advanced Features for Each Language
+### Vector of Unions
+
+Some languages support storing unions directly in a vector.
+
+~~~
+// File found in tests/union_vector/union_vector.fbs
+namespace Example.VectorOfUnions;
+
+// Demonstrates the ability to have vectors of unions, and also to
+// store structs and strings in unions.
+
+table Attacker {
+ sword_attack_damage: int;
+}
+
+struct Rapunzel {
+ hair_length: int;
+}
+
+struct BookReader {
+ books_read: int;
+}
+
+union Character {
+ MuLan: Attacker, // Can have name be different from type.
+ Rapunzel, // Or just both the same, as before.
+ Belle: BookReader,
+ BookFan: BookReader,
+ Other: string,
+ Unused: string
+}
+
+table Movie {
+ main_character: Character;
+ characters: [Character];
+}
+~~~
+
+#### Creating
+
+Analagously to how a union adds two fields to a table a vector of unions creates two different vectors:
+one for the union data and one for the data types.
+
+<div class="language-cpp">
+C++ supports vectors of unions, but it isn't currently documented.
+</div>
+<div class="language-typescript">
+Typescript supports vectors of unions, but it isn't currently documented.
+</div>
+<div class="language-php">
+PHP supports vectors of unions, but it isn't currently documented.
+</div>
+<div class="language-java">
+Java supports vectors of unions, but it isn't currently documented.
+</div>
+<div class="language-csharp">
+~~~{.cs}
+using FlatBuffers;
+using Example.VectorOfUnions;
+
+var fbb = new FlatBufferBuilder(100);
+
+var characterTypes = new[]
+{
+ Character.MuLan,
+ Character.Belle,
+ Character.Other,
+};
+var characterTypesOffset = Movie.CreateCharactersTypeVector(fbb, characterTypes);
+
+var characters = new[]
+{
+ Attacker.CreateAttacker(fbb, 10).Value,
+ BookReader.CreateBookReader(fbb, 20).Value,
+ fbb.CreateSharedString("Chip").Value,
+};
+var charactersOffset = Movie.CreateCharactersVector(fbb, characters);
+
+var movieOffset = Movie.CreateMovie(
+ fbb,
+ Character.Rapunzel,
+ rapunzel,
+ characterTypesOffset,
+ charactersOffset);
+Movie.FinishMovieBuffer(fbb, movieOffset);
+~~~
+</div>
+<div class="language-kotlin">
+Kotlin supports vectors of unions, but it isn't currently documented.
+</div>
+<div class="language-swift">
+Swift supports vectors of unions, but it isn't currently documented.
+</div>
+
+#### Reading
+<div class="language-csharp">
+~~~{.cs}
+var movie = Movie.GetRootAsMovie(fbb.DataBuffer);
+
+for (var i = 0; i <= movie.CharactersLength; i++)
+{
+ if (movie.CharactersType(i) == Character.MuLan)
+ {
+ var mulanSwordDamage = movie.Characters<Attacker>(i).Value.SwordAttackDamage;
+ }
+ else if (movie.CharactersType(i) == Character.Belle)
+ {
+ var belleBooksRead = movie.Characters<BookReader>(i).Value.BooksRead;
+ }
+ else if (movie.CharactersType(i) == Character.Other)
+ {
+ var otherStr = movie.CharactersAsString(i);
+ }
+}
+~~~
+</div>
+
+### Further Reading
+
Each language has a dedicated `Use in XXX` page in the Programmer's Guide
to cover the nuances of FlatBuffers in that language.
diff --git a/docs/source/TypeScriptUsage.md b/docs/source/TypeScriptUsage.md
index 0b9739e..a1acaeb 100644
--- a/docs/source/TypeScriptUsage.md
+++ b/docs/source/TypeScriptUsage.md
@@ -17,7 +17,7 @@
## FlatBuffers TypeScript library code location
The code for the FlatBuffers TypeScript library can be found at
-`flatbuffers/js` with typings available at `@types/flatbuffers`.
+https://www.npmjs.com/package/flatbuffers.
## Testing the FlatBuffers TypeScript library
@@ -26,7 +26,7 @@
*Note: The TypeScript test file requires [Node.js](https://nodejs.org/en/).*
-## Using the FlatBuffers TypeScript libary
+## Using the FlatBuffers TypeScript library
*Note: See [Tutorial](@ref flatbuffers_guide_tutorial) for a more in-depth
example of how to use FlatBuffers in TypeScript.*
@@ -43,7 +43,7 @@
the ByteBuffer to the `getRootAsMonster` function.
~~~{.ts}
- // note: import flatbuffers with your desired import method
+ import * as flatbuffers from 'flatbuffers';
import { MyGame } from './monster_generated';
@@ -70,8 +70,6 @@
can be used (through `--gen-object-api`) that is able to unpack & pack a
FlatBuffer into objects and standard TS types.
-**When using the obj based API, the flatbuffers import need to be in the global namespace if you don't have `--no-fb-import` enabled** since creating default values require accessing the `flatbuffers.js` file.
-
To use:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.ts}
diff --git a/docs/source/WhitePaper.md b/docs/source/WhitePaper.md
index e504ada..dbad2cb 100644
--- a/docs/source/WhitePaper.md
+++ b/docs/source/WhitePaper.md
@@ -20,7 +20,7 @@
If it would be possible to do serialization with no temporary objects,
no additional allocation, no copying, and good locality, this could be
of great value. The reason serialization systems usually don't manage
-this is because it goes counter to forwards/backwards compatability, and
+this is because it goes counter to forwards/backwards compatibility, and
platform specifics like endianness and alignment.
FlatBuffers is what you get if you try anyway.
@@ -64,7 +64,7 @@
between multiple tables with the same layout), and contains information
where fields for this particular kind of instance of vtable are stored.
The vtable may also indicate that the field is not present (because this
-FlatBuffer was written with an older version of the software, of simply
+FlatBuffer was written with an older version of the software, or simply
because the information was not necessary for this instance, or deemed
deprecated), in which case a default value is returned.
diff --git a/docs/source/doxyfile b/docs/source/doxyfile
index 3a5bd98..8cf9000 100644
--- a/docs/source/doxyfile
+++ b/docs/source/doxyfile
@@ -768,6 +768,7 @@
"WhitePaper.md" \
"FlexBuffers.md" \
"Internals.md" \
+ "IntermediateRepresentation.md" \
"Grammar.md" \
"../../CONTRIBUTING.md" \
"Tutorial.md" \
diff --git a/docs/source/doxygen_layout.xml b/docs/source/doxygen_layout.xml
index e1a6b81..28dd065 100644
--- a/docs/source/doxygen_layout.xml
+++ b/docs/source/doxygen_layout.xml
@@ -66,6 +66,8 @@
title="FlatBuffers white paper"/>
<tab type="user" url="@ref flatbuffers_internals"
title="FlatBuffers internals"/>
+ <tab type="user" url="@ref intermediate_representation"
+ title="Intermediate Representation"/>
<tab type="user" url="@ref flatbuffers_grammar"
title="Grammar of the schema language"/>
<tab type="usergroup" url="" title="API Reference">
diff --git a/go/encode.go b/go/encode.go
index 72d4f3a..a2a5798 100644
--- a/go/encode.go
+++ b/go/encode.go
@@ -118,7 +118,7 @@
// GetUOffsetT decodes a little-endian UOffsetT from a byte slice.
func GetUOffsetT(buf []byte) UOffsetT {
- return UOffsetT(GetInt32(buf))
+ return UOffsetT(GetUint32(buf))
}
// GetSOffsetT decodes a little-endian SOffsetT from a byte slice.
diff --git a/grpc/BUILD b/grpc/BUILD.bazel
similarity index 100%
rename from grpc/BUILD
rename to grpc/BUILD.bazel
diff --git a/grpc/README.md b/grpc/README.md
index 685003f..f46258f 100644
--- a/grpc/README.md
+++ b/grpc/README.md
@@ -32,9 +32,8 @@
### Linux
-1. `ln -s ${GRPC_INSTALL_PATH}/lib/libgrpc++_unsecure.so.6 ${GRPC_INSTALL_PATH}/lib/libgrpc++_unsecure.so.1`
-2. `export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:${GRPC_INSTALL_PATH}/lib`
-3. `make test ARGS=-V`
+1. `export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:${GRPC_INSTALL_PATH}/lib`
+2. `make test ARGS=-V`
For Bazel users:
diff --git a/grpc/boringssl.patch b/grpc/boringssl.patch
new file mode 100644
index 0000000..632499e
--- /dev/null
+++ b/grpc/boringssl.patch
@@ -0,0 +1,13 @@
+diff --git a/CMakeLists.txt b/CMakeLists.txt
+index 1645a264a..12f8ca999 100644
+--- a/CMakeLists.txt
++++ b/CMakeLists.txt
+@@ -635,6 +635,8 @@ add_library(
+ src/ssl/tls_record.cc
+ )
+
++target_link_libraries(ssl crypto)
++
+ add_executable(
+ bssl
+
diff --git a/grpc/build_grpc.sh b/grpc/build_grpc.sh
index 3c0c27e..49c5a60 100755
--- a/grpc/build_grpc.sh
+++ b/grpc/build_grpc.sh
@@ -1,17 +1,20 @@
#!/bin/bash
-grpc_1_15_1_githash=1a60e6971f428323245a930031ad267bb3142ba4
+grpc_1_39_0_githash=58602e20a3f3e48f24a4114c757099b25b947f7b
function build_grpc () {
git clone https://github.com/grpc/grpc.git google/grpc
cd google/grpc
- git checkout ${grpc_1_15_1_githash}
+ git checkout ${grpc_1_39_0_githash}
git submodule update --init
- make
- make install prefix=`pwd`/install
- if [ ! -f ${GRPC_INSTALL_PATH}/lib/libgrpc++_unsecure.so.1 ]; then
- ln -s ${GRPC_INSTALL_PATH}/lib/libgrpc++_unsecure.so.6 ${GRPC_INSTALL_PATH}/lib/libgrpc++_unsecure.so.1
- fi
+ # Apply boringssl build patch
+ cd third_party/boringssl-with-bazel
+ git apply ../../../../grpc/boringssl.patch
+ cd ../..
+ mkdir ../grpc_build
+ cd ../grpc_build
+ cmake ../grpc -DgRPC_INSTALL=ON -DgRPC_BUILD_TESTS=OFF -DABSL_ENABLE_INSTALL=ON -DBUILD_SHARED_LIBS=ON -DCMAKE_INSTALL_PREFIX=`pwd`/../grpc/install
+ cmake --build . --target install ${JOBS:+-j$JOBS}
cd ../..
}
diff --git a/grpc/examples/README.md b/grpc/examples/README.md
new file mode 100644
index 0000000..c821218
--- /dev/null
+++ b/grpc/examples/README.md
@@ -0,0 +1,35 @@
+## Languages known issues
+
+### Python
+
+- Assert the type required in your server/client since python is able to receive `Bytes array` or `utf8 strings`.
+
+```python
+def SayHello(self, request, context):
+ # request might be a byte array or a utf8 string
+
+ r = HelloRequest.HelloRequest().GetRootAs(request, 0)
+ reply = "Unknown"
+ if r.Name():
+ reply = r.Name()
+ # Issues might happen if type checking isnt present.
+ # thus encoding it as a `reply.decode('UTF-8')`
+ return build_reply("welcome " + reply.decode('UTF-8'))
+
+```
+
+This can be prevented by making sure all the requests coming to/from python are `Bytes array`
+
+```python
+def say_hello(stub, builder):
+ hello_request = bytes(builder.Output())
+ reply = stub.SayHello(hello_request)
+ r = HelloReply.HelloReply.GetRootAs(reply)
+ print(r.Message())
+```
+
+### Go
+
+- Always requires the `content-type` of the payload to be set to `application/grpc+flatbuffers`
+
+example: `.SayHello(ctx, b, grpc.CallContentSubtype("flatbuffers"))`
\ No newline at end of file
diff --git a/grpc/examples/generate.sh b/grpc/examples/generate.sh
new file mode 100755
index 0000000..0f051da
--- /dev/null
+++ b/grpc/examples/generate.sh
@@ -0,0 +1,71 @@
+#!/bin/bash
+#
+# Copyright 2021 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.
+
+set -e
+
+current_dir=`pwd`
+
+cd ../..
+
+main_dir=`pwd`
+
+cd ${current_dir}
+
+# Looks for flatc within the root dir & debug
+if [ -e ${main_dir}/flatc ]; then
+ alias fbc='${main_dir}/flatc'
+elif [ -e ${main_dir}/Debug/flatc ]; then
+ alias fbc='${main_dir}/Debug/flatc'
+else
+ echo 'flatc' could not be found. Make sure to build FlatBuffers from the \
+ $rootdir directory.
+ exit 1
+fi
+
+generator="--grpc $current_dir/greeter.fbs"
+
+# Regenerate Go lang code
+cd go
+
+cd greeter
+fbc --bfbs-filenames ../.. --go ${generator}
+
+cd ${current_dir}
+
+# Regenerate Python code
+cd python
+
+cd greeter
+
+fbc --bfbs-filenames ../.. --python ${generator}
+
+cd ${current_dir}
+
+# Regenerate Swift code
+cd swift
+
+cd Greeter/Sources/Model
+fbc --bfbs-filenames ../../../.. --swift --gen-json-emit ${generator}
+
+cd ${current_dir}
+
+# Regenerate Typescript code
+cd ts
+
+cd greeter/src
+fbc --bfbs-filenames ../../.. --ts ${generator}
+
+cd ${current_dir}
diff --git a/grpc/examples/go/format.sh b/grpc/examples/go/format.sh
new file mode 100644
index 0000000..a7ee9e3
--- /dev/null
+++ b/grpc/examples/go/format.sh
@@ -0,0 +1,36 @@
+#!/bin/bash
+#
+# Copyright 2021 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.
+
+set -e
+
+
+format_greeter() {
+ cd greeter
+
+ # Format client
+ cd client
+ gofmt -w .
+ cd ..
+
+ # Format server
+ cd server
+ gofmt -w .
+ cd ..
+
+ cd ..
+}
+
+format_greeter
\ No newline at end of file
diff --git a/grpc/examples/go/greeter/.gitignore b/grpc/examples/go/greeter/.gitignore
new file mode 100644
index 0000000..535db5e
--- /dev/null
+++ b/grpc/examples/go/greeter/.gitignore
@@ -0,0 +1,2 @@
+**/server
+**/client
\ No newline at end of file
diff --git a/grpc/examples/go/greeter/README.md b/grpc/examples/go/greeter/README.md
new file mode 100644
index 0000000..3390508
--- /dev/null
+++ b/grpc/examples/go/greeter/README.md
@@ -0,0 +1,25 @@
+# Go Greeter example
+
+## Project Structure
+
+ .
+ ├── server # Server module
+ ├── client # Client module
+ ├── models # Flatbuffers models & main grpc code.
+ └── README.md
+
+## How to run Server:
+
+- `cd server`
+
+- `go clean`
+
+- `go run main.go`
+
+## How to run Client:
+
+- `cd client`
+
+- `go clean`
+
+- `go run main.go --name NAME`
\ No newline at end of file
diff --git a/grpc/examples/go/greeter/client/go.mod b/grpc/examples/go/greeter/client/go.mod
new file mode 100644
index 0000000..19689dd
--- /dev/null
+++ b/grpc/examples/go/greeter/client/go.mod
@@ -0,0 +1,11 @@
+module github.com/google/flatbuffers/grpc/examples/go/greeter/client
+
+go 1.15
+
+replace github.com/google/flatbuffers/grpc/examples/go/greeter/models v0.0.0 => ../models
+
+require (
+ github.com/google/flatbuffers v1.12.0
+ github.com/google/flatbuffers/grpc/examples/go/greeter/models v0.0.0
+ google.golang.org/grpc v1.35.0
+)
diff --git a/grpc/examples/go/greeter/client/main.go b/grpc/examples/go/greeter/client/main.go
new file mode 100644
index 0000000..4993576
--- /dev/null
+++ b/grpc/examples/go/greeter/client/main.go
@@ -0,0 +1,74 @@
+package main
+
+import (
+ "context"
+ "flag"
+ "fmt"
+ "io"
+ "log"
+ "time"
+
+ flatbuffers "github.com/google/flatbuffers/go"
+ models "github.com/google/flatbuffers/grpc/examples/go/greeter/models"
+ "google.golang.org/grpc"
+)
+
+var (
+ addr = "3000"
+ name = flag.String("name", "Flatbuffers", "name to be sent to server :D")
+)
+
+func printSayHello(client models.GreeterClient, name string) {
+ log.Printf("Name to be sent (%s)", name)
+ b := flatbuffers.NewBuilder(0)
+ i := b.CreateString(name)
+ models.HelloRequestStart(b)
+ models.HelloRequestAddName(b, i)
+ b.Finish(models.HelloRequestEnd(b))
+
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ request, err := client.SayHello(ctx, b, grpc.CallContentSubtype("flatbuffers"))
+ if err != nil {
+ log.Fatalf("%v.SayHello(_) = _, %v: ", client, err)
+ }
+ log.Printf("server said %q", request.Message())
+}
+
+func printSayManyHello(client models.GreeterClient, name string) {
+ log.Printf("Name to be sent (%s)", name)
+ b := flatbuffers.NewBuilder(0)
+ i := b.CreateString(name)
+ models.HelloRequestStart(b)
+ models.HelloRequestAddName(b, i)
+ b.Finish(models.HelloRequestEnd(b))
+
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ stream, err := client.SayManyHellos(ctx, b, grpc.CallContentSubtype("flatbuffers"))
+ if err != nil {
+ log.Fatalf("%v.SayManyHellos(_) = _, %v", client, err)
+ }
+ for {
+ request, err := stream.Recv()
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ log.Fatalf("%v.SayManyHellos(_) = _, %v", client, err)
+ }
+ log.Printf("server said %q", request.Message())
+ }
+}
+
+func main() {
+ flag.Parse()
+ conn, err := grpc.Dial(fmt.Sprintf("localhost:%d", 3000), grpc.WithInsecure(), grpc.WithCodec(flatbuffers.FlatbuffersCodec{}))
+ if err != nil {
+ log.Fatalf("fail to dial: %v", err)
+ }
+ defer conn.Close()
+ client := models.NewGreeterClient(conn)
+ printSayHello(client, *name)
+ printSayManyHello(client, *name)
+}
diff --git a/grpc/examples/go/greeter/models/Greeter_grpc.go b/grpc/examples/go/greeter/models/Greeter_grpc.go
new file mode 100644
index 0000000..9a2405c
--- /dev/null
+++ b/grpc/examples/go/greeter/models/Greeter_grpc.go
@@ -0,0 +1,158 @@
+//Generated by gRPC Go plugin
+//If you make any local changes, they will be lost
+//source: greeter
+
+package models
+
+import (
+ context "context"
+ flatbuffers "github.com/google/flatbuffers/go"
+ grpc "google.golang.org/grpc"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/status"
+)
+
+// Client API for Greeter service
+type GreeterClient interface {
+ SayHello(ctx context.Context, in *flatbuffers.Builder,
+ opts ...grpc.CallOption) (*HelloReply, error)
+ SayManyHellos(ctx context.Context, in *flatbuffers.Builder,
+ opts ...grpc.CallOption) (Greeter_SayManyHellosClient, error)
+}
+
+type greeterClient struct {
+ cc grpc.ClientConnInterface
+}
+
+func NewGreeterClient(cc grpc.ClientConnInterface) GreeterClient {
+ return &greeterClient{cc}
+}
+
+func (c *greeterClient) SayHello(ctx context.Context, in *flatbuffers.Builder,
+ opts ...grpc.CallOption) (*HelloReply, error) {
+ out := new(HelloReply)
+ err := c.cc.Invoke(ctx, "/models.Greeter/SayHello", in, out, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *greeterClient) SayManyHellos(ctx context.Context, in *flatbuffers.Builder,
+ opts ...grpc.CallOption) (Greeter_SayManyHellosClient, error) {
+ stream, err := c.cc.NewStream(ctx, &_Greeter_serviceDesc.Streams[0], "/models.Greeter/SayManyHellos", opts...)
+ if err != nil {
+ return nil, err
+ }
+ x := &greeterSayManyHellosClient{stream}
+ if err := x.ClientStream.SendMsg(in); err != nil {
+ return nil, err
+ }
+ if err := x.ClientStream.CloseSend(); err != nil {
+ return nil, err
+ }
+ return x, nil
+}
+
+type Greeter_SayManyHellosClient interface {
+ Recv() (*HelloReply, error)
+ grpc.ClientStream
+}
+
+type greeterSayManyHellosClient struct {
+ grpc.ClientStream
+}
+
+func (x *greeterSayManyHellosClient) Recv() (*HelloReply, error) {
+ m := new(HelloReply)
+ if err := x.ClientStream.RecvMsg(m); err != nil {
+ return nil, err
+ }
+ return m, nil
+}
+
+// Server API for Greeter service
+type GreeterServer interface {
+ SayHello(context.Context, *HelloRequest) (*flatbuffers.Builder, error)
+ SayManyHellos(*HelloRequest, Greeter_SayManyHellosServer) error
+ mustEmbedUnimplementedGreeterServer()
+}
+
+type UnimplementedGreeterServer struct {
+}
+
+func (UnimplementedGreeterServer) SayHello(context.Context, *HelloRequest) (*flatbuffers.Builder, error) {
+ return nil, status.Errorf(codes.Unimplemented, "method SayHello not implemented")
+}
+
+func (UnimplementedGreeterServer) SayManyHellos(*HelloRequest, Greeter_SayManyHellosServer) error {
+ return status.Errorf(codes.Unimplemented, "method SayManyHellos not implemented")
+}
+
+func (UnimplementedGreeterServer) mustEmbedUnimplementedGreeterServer() {}
+
+type UnsafeGreeterServer interface {
+ mustEmbedUnimplementedGreeterServer()
+}
+
+func RegisterGreeterServer(s grpc.ServiceRegistrar, srv GreeterServer) {
+ s.RegisterService(&_Greeter_serviceDesc, srv)
+}
+
+func _Greeter_SayHello_Handler(srv interface{}, ctx context.Context,
+ dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(HelloRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(GreeterServer).SayHello(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/models.Greeter/SayHello",
+ }
+
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(GreeterServer).SayHello(ctx, req.(*HelloRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+func _Greeter_SayManyHellos_Handler(srv interface{}, stream grpc.ServerStream) error {
+ m := new(HelloRequest)
+ if err := stream.RecvMsg(m); err != nil {
+ return err
+ }
+ return srv.(GreeterServer).SayManyHellos(m, &greeterSayManyHellosServer{stream})
+}
+
+type Greeter_SayManyHellosServer interface {
+ Send(*flatbuffers.Builder) error
+ grpc.ServerStream
+}
+
+type greeterSayManyHellosServer struct {
+ grpc.ServerStream
+}
+
+func (x *greeterSayManyHellosServer) Send(m *flatbuffers.Builder) error {
+ return x.ServerStream.SendMsg(m)
+}
+
+var _Greeter_serviceDesc = grpc.ServiceDesc{
+ ServiceName: "models.Greeter",
+ HandlerType: (*GreeterServer)(nil),
+ Methods: []grpc.MethodDesc{
+ {
+ MethodName: "SayHello",
+ Handler: _Greeter_SayHello_Handler,
+ },
+ },
+ Streams: []grpc.StreamDesc{
+ {
+ StreamName: "SayManyHellos",
+ Handler: _Greeter_SayManyHellos_Handler,
+ ServerStreams: true,
+ },
+ },
+}
diff --git a/grpc/examples/go/greeter/models/HelloReply.go b/grpc/examples/go/greeter/models/HelloReply.go
new file mode 100644
index 0000000..bb5db40
--- /dev/null
+++ b/grpc/examples/go/greeter/models/HelloReply.go
@@ -0,0 +1,52 @@
+// Code generated by the FlatBuffers compiler. DO NOT EDIT.
+
+package models
+
+import (
+ flatbuffers "github.com/google/flatbuffers/go"
+)
+
+type HelloReply struct {
+ _tab flatbuffers.Table
+}
+
+func GetRootAsHelloReply(buf []byte, offset flatbuffers.UOffsetT) *HelloReply {
+ n := flatbuffers.GetUOffsetT(buf[offset:])
+ x := &HelloReply{}
+ x.Init(buf, n+offset)
+ return x
+}
+
+func GetSizePrefixedRootAsHelloReply(buf []byte, offset flatbuffers.UOffsetT) *HelloReply {
+ n := flatbuffers.GetUOffsetT(buf[offset+flatbuffers.SizeUint32:])
+ x := &HelloReply{}
+ x.Init(buf, n+offset+flatbuffers.SizeUint32)
+ return x
+}
+
+func (rcv *HelloReply) Init(buf []byte, i flatbuffers.UOffsetT) {
+ rcv._tab.Bytes = buf
+ rcv._tab.Pos = i
+}
+
+func (rcv *HelloReply) Table() flatbuffers.Table {
+ return rcv._tab
+}
+
+func (rcv *HelloReply) Message() []byte {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(4))
+ if o != 0 {
+ return rcv._tab.ByteVector(o + rcv._tab.Pos)
+ }
+ return nil
+}
+
+func HelloReplyStart(builder *flatbuffers.Builder) {
+ builder.StartObject(1)
+}
+func HelloReplyAddMessage(builder *flatbuffers.Builder, message flatbuffers.UOffsetT) {
+ builder.PrependUOffsetTSlot(0, flatbuffers.UOffsetT(message), 0)
+}
+func HelloReplyEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT {
+ return builder.EndObject()
+}
diff --git a/grpc/examples/go/greeter/models/HelloRequest.go b/grpc/examples/go/greeter/models/HelloRequest.go
new file mode 100644
index 0000000..52feab9
--- /dev/null
+++ b/grpc/examples/go/greeter/models/HelloRequest.go
@@ -0,0 +1,52 @@
+// Code generated by the FlatBuffers compiler. DO NOT EDIT.
+
+package models
+
+import (
+ flatbuffers "github.com/google/flatbuffers/go"
+)
+
+type HelloRequest struct {
+ _tab flatbuffers.Table
+}
+
+func GetRootAsHelloRequest(buf []byte, offset flatbuffers.UOffsetT) *HelloRequest {
+ n := flatbuffers.GetUOffsetT(buf[offset:])
+ x := &HelloRequest{}
+ x.Init(buf, n+offset)
+ return x
+}
+
+func GetSizePrefixedRootAsHelloRequest(buf []byte, offset flatbuffers.UOffsetT) *HelloRequest {
+ n := flatbuffers.GetUOffsetT(buf[offset+flatbuffers.SizeUint32:])
+ x := &HelloRequest{}
+ x.Init(buf, n+offset+flatbuffers.SizeUint32)
+ return x
+}
+
+func (rcv *HelloRequest) Init(buf []byte, i flatbuffers.UOffsetT) {
+ rcv._tab.Bytes = buf
+ rcv._tab.Pos = i
+}
+
+func (rcv *HelloRequest) Table() flatbuffers.Table {
+ return rcv._tab
+}
+
+func (rcv *HelloRequest) Name() []byte {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(4))
+ if o != 0 {
+ return rcv._tab.ByteVector(o + rcv._tab.Pos)
+ }
+ return nil
+}
+
+func HelloRequestStart(builder *flatbuffers.Builder) {
+ builder.StartObject(1)
+}
+func HelloRequestAddName(builder *flatbuffers.Builder, name flatbuffers.UOffsetT) {
+ builder.PrependUOffsetTSlot(0, flatbuffers.UOffsetT(name), 0)
+}
+func HelloRequestEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT {
+ return builder.EndObject()
+}
diff --git a/grpc/examples/go/greeter/models/go.mod b/grpc/examples/go/greeter/models/go.mod
new file mode 100644
index 0000000..01976de
--- /dev/null
+++ b/grpc/examples/go/greeter/models/go.mod
@@ -0,0 +1,8 @@
+module github.com/google/flatbuffers/grpc/examples/go/greeter/models
+
+go 1.15
+
+require (
+ github.com/google/flatbuffers v1.12.0
+ google.golang.org/grpc v1.35.0
+)
diff --git a/grpc/examples/go/greeter/server/go.mod b/grpc/examples/go/greeter/server/go.mod
new file mode 100644
index 0000000..a5bbd9b
--- /dev/null
+++ b/grpc/examples/go/greeter/server/go.mod
@@ -0,0 +1,11 @@
+module github.com/google/flatbuffers/grpc/examples/go/greeter/server
+
+go 1.15
+
+replace github.com/google/flatbuffers/grpc/examples/go/greeter/models v0.0.0 => ../models
+
+require (
+ github.com/google/flatbuffers v1.12.0
+ github.com/google/flatbuffers/grpc/examples/go/greeter/models v0.0.0
+ google.golang.org/grpc v1.39.0-dev
+)
diff --git a/grpc/examples/go/greeter/server/main.go b/grpc/examples/go/greeter/server/main.go
new file mode 100644
index 0000000..a5bb3a44
--- /dev/null
+++ b/grpc/examples/go/greeter/server/main.go
@@ -0,0 +1,77 @@
+package main
+
+import (
+ "context"
+ "fmt"
+ "log"
+ "net"
+
+ flatbuffers "github.com/google/flatbuffers/go"
+ models "github.com/google/flatbuffers/grpc/examples/go/greeter/models"
+ "google.golang.org/grpc"
+)
+
+var (
+ greetings = [...]string{"Hi", "Hallo", "Ciao"}
+)
+
+type greeterServer struct {
+ models.UnimplementedGreeterServer
+}
+
+func (s *greeterServer) SayHello(ctx context.Context, request *models.HelloRequest) (*flatbuffers.Builder, error) {
+ v := request.Name()
+ var m string
+ if v == nil {
+ m = "Unknown"
+ } else {
+ m = string(v)
+ }
+ b := flatbuffers.NewBuilder(0)
+ idx := b.CreateString("welcome " + m)
+ models.HelloReplyStart(b)
+ models.HelloReplyAddMessage(b, idx)
+ b.Finish(models.HelloReplyEnd(b))
+ return b, nil
+}
+
+func (s *greeterServer) SayManyHellos(request *models.HelloRequest, stream models.Greeter_SayManyHellosServer) error {
+ v := request.Name()
+ var m string
+ if v == nil {
+ m = "Unknown"
+ } else {
+ m = string(v)
+ }
+ b := flatbuffers.NewBuilder(0)
+
+ for _, greeting := range greetings {
+ idx := b.CreateString(greeting + " " + m)
+ models.HelloReplyStart(b)
+ models.HelloReplyAddMessage(b, idx)
+ b.Finish(models.HelloReplyEnd(b))
+ if err := stream.Send(b); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func newServer() *greeterServer {
+ s := &greeterServer{}
+ return s
+}
+
+func main() {
+ lis, err := net.Listen("tcp", fmt.Sprintf("localhost:%d", 3000))
+ if err != nil {
+ log.Fatalf("failed to listen: %v", err)
+ }
+ codec := &flatbuffers.FlatbuffersCodec{}
+ grpcServer := grpc.NewServer(grpc.ForceServerCodec(codec))
+ models.RegisterGreeterServer(grpcServer, newServer())
+ if err := grpcServer.Serve(lis); err != nil {
+ fmt.Print(err)
+ panic(err)
+ }
+}
diff --git a/grpc/examples/greeter.fbs b/grpc/examples/greeter.fbs
new file mode 100644
index 0000000..651fb67
--- /dev/null
+++ b/grpc/examples/greeter.fbs
@@ -0,0 +1,14 @@
+namespace models;
+
+table HelloReply {
+ message:string;
+}
+
+table HelloRequest {
+ name:string;
+}
+
+rpc_service Greeter {
+ SayHello(HelloRequest):HelloReply;
+ SayManyHellos(HelloRequest):HelloReply (streaming: "server");
+}
diff --git a/grpc/examples/python/greeter/README.md b/grpc/examples/python/greeter/README.md
new file mode 100644
index 0000000..fcf310c
--- /dev/null
+++ b/grpc/examples/python/greeter/README.md
@@ -0,0 +1,12 @@
+# Python Greeter example
+
+## Prerequisite
+
+- You need to have grpc python installed on your device `pip install grpcio`
+## How to run Server:
+
+- `python server.py ${PORT}`
+
+## How to run Client:
+
+- `python client.py ${PORT} ${NAME}`
\ No newline at end of file
diff --git a/grpc/examples/python/greeter/client.py b/grpc/examples/python/greeter/client.py
new file mode 100644
index 0000000..d2d7184
--- /dev/null
+++ b/grpc/examples/python/greeter/client.py
@@ -0,0 +1,40 @@
+import sys
+import argparse
+import grpc
+
+sys.path.insert(0, '../../../../../flatbuffers/python')
+
+import flatbuffers
+from models import HelloReply, HelloRequest, greeter_grpc_fb
+
+parser = argparse.ArgumentParser()
+parser.add_argument("port", help="server port to connect to", default=3000)
+parser.add_argument("name", help="name to be sent to server", default="flatbuffers")
+
+def say_hello(stub, hello_request):
+ reply = stub.SayHello(hello_request)
+ r = HelloReply.HelloReply.GetRootAs(reply)
+ print(r.Message())
+
+def say_many_hellos(stub, hello_request):
+ greetings = stub.SayManyHellos(hello_request)
+ for greeting in greetings:
+ r = HelloReply.HelloReply.GetRootAs(greeting)
+ print(r.Message())
+
+def main():
+ args = parser.parse_args()
+
+ with grpc.insecure_channel('localhost:' + args.port) as channel:
+ builder = flatbuffers.Builder()
+ ind = builder.CreateString(args.name)
+ HelloRequest.HelloRequestStart(builder)
+ HelloRequest.HelloRequestAddName(builder, ind)
+ root = HelloRequest.HelloRequestEnd(builder)
+ builder.Finish(root)
+ output = bytes(builder.Output())
+ stub = greeter_grpc_fb.GreeterStub(channel)
+ say_hello(stub, output)
+ say_many_hellos(stub, output)
+
+main()
\ No newline at end of file
diff --git a/grpc/examples/python/greeter/models/HelloReply.py b/grpc/examples/python/greeter/models/HelloReply.py
new file mode 100644
index 0000000..301c84d
--- /dev/null
+++ b/grpc/examples/python/greeter/models/HelloReply.py
@@ -0,0 +1,42 @@
+# automatically generated by the FlatBuffers compiler, do not modify
+
+# namespace: models
+
+import flatbuffers
+from flatbuffers.compat import import_numpy
+np = import_numpy()
+
+class HelloReply(object):
+ __slots__ = ['_tab']
+
+ @classmethod
+ def GetRootAs(cls, buf, offset=0):
+ n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
+ x = HelloReply()
+ x.Init(buf, n + offset)
+ return x
+
+ @classmethod
+ def GetRootAsHelloReply(cls, buf, offset=0):
+ """This method is deprecated. Please switch to GetRootAs."""
+ return cls.GetRootAs(buf, offset)
+ # HelloReply
+ def Init(self, buf, pos):
+ self._tab = flatbuffers.table.Table(buf, pos)
+
+ # HelloReply
+ def Message(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
+ if o != 0:
+ return self._tab.String(o + self._tab.Pos)
+ return None
+
+def HelloReplyStart(builder): builder.StartObject(1)
+def Start(builder):
+ return HelloReplyStart(builder)
+def HelloReplyAddMessage(builder, message): builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(message), 0)
+def AddMessage(builder, message):
+ return HelloReplyAddMessage(builder, message)
+def HelloReplyEnd(builder): return builder.EndObject()
+def End(builder):
+ return HelloReplyEnd(builder)
\ No newline at end of file
diff --git a/grpc/examples/python/greeter/models/HelloRequest.py b/grpc/examples/python/greeter/models/HelloRequest.py
new file mode 100644
index 0000000..122568f
--- /dev/null
+++ b/grpc/examples/python/greeter/models/HelloRequest.py
@@ -0,0 +1,42 @@
+# automatically generated by the FlatBuffers compiler, do not modify
+
+# namespace: models
+
+import flatbuffers
+from flatbuffers.compat import import_numpy
+np = import_numpy()
+
+class HelloRequest(object):
+ __slots__ = ['_tab']
+
+ @classmethod
+ def GetRootAs(cls, buf, offset=0):
+ n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
+ x = HelloRequest()
+ x.Init(buf, n + offset)
+ return x
+
+ @classmethod
+ def GetRootAsHelloRequest(cls, buf, offset=0):
+ """This method is deprecated. Please switch to GetRootAs."""
+ return cls.GetRootAs(buf, offset)
+ # HelloRequest
+ def Init(self, buf, pos):
+ self._tab = flatbuffers.table.Table(buf, pos)
+
+ # HelloRequest
+ def Name(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
+ if o != 0:
+ return self._tab.String(o + self._tab.Pos)
+ return None
+
+def HelloRequestStart(builder): builder.StartObject(1)
+def Start(builder):
+ return HelloRequestStart(builder)
+def HelloRequestAddName(builder, name): builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(name), 0)
+def AddName(builder, name):
+ return HelloRequestAddName(builder, name)
+def HelloRequestEnd(builder): return builder.EndObject()
+def End(builder):
+ return HelloRequestEnd(builder)
\ No newline at end of file
diff --git a/grpc/BUILD b/grpc/examples/python/greeter/models/__init__.py
similarity index 100%
copy from grpc/BUILD
copy to grpc/examples/python/greeter/models/__init__.py
diff --git a/grpc/examples/python/greeter/models/greeter_grpc_fb.py b/grpc/examples/python/greeter/models/greeter_grpc_fb.py
new file mode 100644
index 0000000..b9f8a4e
--- /dev/null
+++ b/grpc/examples/python/greeter/models/greeter_grpc_fb.py
@@ -0,0 +1,52 @@
+# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
+
+import grpc
+
+class GreeterStub(object):
+ """ Interface exported by the server. """
+
+ def __init__(self, channel):
+ """ Constructor.
+
+ Args:
+ channel: A grpc.Channel.
+ """
+
+ self.SayHello = channel.unary_unary(
+ "/models.Greeter/SayHello"
+ )
+
+ self.SayManyHellos = channel.unary_stream(
+ "/models.Greeter/SayManyHellos"
+ )
+
+
+class GreeterServicer(object):
+ """ Interface exported by the server. """
+
+ def SayHello(self, request, context):
+ context.set_code(grpc.StatusCode.UNIMPLEMENTED)
+ context.set_details('Method not implemented!')
+ raise NotImplementedError('Method not implemented!')
+
+
+ def SayManyHellos(self, request, context):
+ context.set_code(grpc.StatusCode.UNIMPLEMENTED)
+ context.set_details('Method not implemented!')
+ raise NotImplementedError('Method not implemented!')
+
+
+
+def add_GreeterServicer_to_server(servicer, server):
+ rpc_method_handlers = {
+ 'SayHello': grpc.unary_unary_rpc_method_handler(
+ servicer.SayHello
+ ),
+ 'SayManyHellos': grpc.unary_stream_rpc_method_handler(
+ servicer.SayManyHellos
+ ),
+ }
+ generic_handler = grpc.method_handlers_generic_handler(
+ 'models.Greeter', rpc_method_handlers)
+ server.add_generic_rpc_handlers((generic_handler,))
+
diff --git a/grpc/examples/python/greeter/server.py b/grpc/examples/python/greeter/server.py
new file mode 100644
index 0000000..acca880
--- /dev/null
+++ b/grpc/examples/python/greeter/server.py
@@ -0,0 +1,57 @@
+from concurrent import futures
+import sys
+import argparse
+import grpc
+
+sys.path.insert(0, '../../../../../flatbuffers/python')
+
+import flatbuffers
+from models import HelloReply, HelloRequest, greeter_grpc_fb
+
+parser = argparse.ArgumentParser()
+parser.add_argument("port", help="server on port", default=3000)
+
+def build_reply(message):
+ builder = flatbuffers.Builder()
+ ind = builder.CreateString(message)
+ HelloReply.HelloReplyStart(builder)
+ HelloReply.HelloReplyAddMessage(builder, ind)
+ root = HelloReply.HelloReplyEnd(builder)
+ builder.Finish(root)
+ return bytes(builder.Output())
+
+class GreeterServicer(greeter_grpc_fb.GreeterServicer):
+
+ def __init__(self):
+ self.greetings = ["Hi", "Hallo", "Ciao"]
+
+ def SayHello(self, request, context):
+ r = HelloRequest.HelloRequest().GetRootAs(request, 0)
+ reply = "Unknown"
+ if r.Name():
+ reply = r.Name()
+ return build_reply("welcome " + reply.decode('UTF-8'))
+
+ def SayManyHellos(self, request, context):
+ r = HelloRequest.HelloRequest().GetRootAs(request, 0)
+ reply = "Unknown"
+ if r.Name():
+ reply = r.Name()
+
+ for greeting in self.greetings:
+ print(type(reply))
+ yield build_reply(greeting + " " + reply.decode('UTF-8'))
+
+
+def serve():
+ args = parser.parse_args()
+ server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
+ greeter_grpc_fb.add_GreeterServicer_to_server(
+ GreeterServicer(), server
+ )
+ server.add_insecure_port('[::]:' + args.port)
+ server.start()
+ server.wait_for_termination()
+
+if __name__ == '__main__':
+ serve()
\ No newline at end of file
diff --git a/grpc/examples/swift/Greeter/Package.swift b/grpc/examples/swift/Greeter/Package.swift
new file mode 100644
index 0000000..5e6fb68
--- /dev/null
+++ b/grpc/examples/swift/Greeter/Package.swift
@@ -0,0 +1,58 @@
+// swift-tools-version:5.1
+/*
+ * Copyright 2020 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.
+ */
+
+import PackageDescription
+
+let package = Package(
+ name: "Greeter",
+ platforms: [
+ .iOS(.v11),
+ .macOS(.v10_14),
+ ],
+ dependencies: [
+ .package(path: "../../../../swift"),
+ .package(url: "https://github.com/grpc/grpc-swift.git", from: "1.0.0"),
+ ],
+ targets: [
+ // Targets are the basic building blocks of a package. A target can define a module or a test suite.
+ // Targets can depend on other targets in this package, and on products in packages which this package depends on.
+ .target(
+ name: "Model",
+ dependencies: [
+ "GRPC",
+ "FlatBuffers",
+ ],
+ path: "Sources/Model"),
+
+ // Client for the Greeter example
+ .target(
+ name: "Client",
+ dependencies: [
+ "GRPC",
+ "Model",
+ ],
+ path: "Sources/client"),
+
+ // Server for the Greeter example
+ .target(
+ name: "Server",
+ dependencies: [
+ "GRPC",
+ "Model",
+ ],
+ path: "Sources/server"),
+ ])
diff --git a/tests/FlatBuffers.GRPC.Swift/README.md b/grpc/examples/swift/Greeter/README.md
similarity index 100%
rename from tests/FlatBuffers.GRPC.Swift/README.md
rename to grpc/examples/swift/Greeter/README.md
diff --git a/grpc/examples/swift/Greeter/Sources/Model/greeter.grpc.swift b/grpc/examples/swift/Greeter/Sources/Model/greeter.grpc.swift
new file mode 100644
index 0000000..0f29f19
--- /dev/null
+++ b/grpc/examples/swift/Greeter/Sources/Model/greeter.grpc.swift
@@ -0,0 +1,145 @@
+// Generated GRPC code for FlatBuffers swift!
+/// The following code is generated by the Flatbuffers library which might not be in sync with grpc-swift
+/// in case of an issue please open github issue, though it would be maintained
+
+// swiftlint:disable all
+// swiftformat:disable all
+
+import Foundation
+import GRPC
+import NIO
+import NIOHTTP1
+import FlatBuffers
+
+public protocol GRPCFlatBufPayload: GRPCPayload, FlatBufferGRPCMessage {}
+public extension GRPCFlatBufPayload {
+ init(serializedByteBuffer: inout NIO.ByteBuffer) throws {
+ self.init(byteBuffer: FlatBuffers.ByteBuffer(contiguousBytes: serializedByteBuffer.readableBytesView, count: serializedByteBuffer.readableBytes))
+ }
+ func serialize(into buffer: inout NIO.ByteBuffer) throws {
+ let buf = UnsafeRawBufferPointer(start: self.rawPointer, count: Int(self.size))
+ buffer.writeBytes(buf)
+ }
+}
+extension Message: GRPCFlatBufPayload {}
+
+/// Usage: instantiate models_GreeterServiceClient, then call methods of this protocol to make API calls.
+public protocol models_GreeterClientProtocol: GRPCClient {
+
+ var serviceName: String { get }
+
+ var interceptors: models_GreeterClientInterceptorFactoryProtocol? { get }
+
+ func SayHello(
+ _ request: Message<models_HelloRequest>
+ , callOptions: CallOptions?
+ ) -> UnaryCall<Message<models_HelloRequest>, Message<models_HelloReply>>
+
+ func SayManyHellos(
+ _ request: Message<models_HelloRequest>
+ , callOptions: CallOptions?,
+ handler: @escaping (Message<models_HelloReply>) -> Void
+ ) -> ServerStreamingCall<Message<models_HelloRequest>, Message<models_HelloReply>>
+
+}
+
+extension models_GreeterClientProtocol {
+
+ public var serviceName: String { "models.Greeter" }
+
+ public func SayHello(
+ _ request: Message<models_HelloRequest>
+ , callOptions: CallOptions? = nil
+ ) -> UnaryCall<Message<models_HelloRequest>, Message<models_HelloReply>> {
+ return self.makeUnaryCall(
+ path: "/models.Greeter/SayHello",
+ request: request,
+ callOptions: callOptions ?? self.defaultCallOptions,
+ interceptors: self.interceptors?.makeSayHelloInterceptors() ?? []
+ )
+ }
+
+ public func SayManyHellos(
+ _ request: Message<models_HelloRequest>
+ , callOptions: CallOptions? = nil,
+ handler: @escaping (Message<models_HelloReply>) -> Void
+ ) -> ServerStreamingCall<Message<models_HelloRequest>, Message<models_HelloReply>> {
+ return self.makeServerStreamingCall(
+ path: "/models.Greeter/SayManyHellos",
+ request: request,
+ callOptions: callOptions ?? self.defaultCallOptions,
+ interceptors: self.interceptors?.makeSayManyHellosInterceptors() ?? [],
+ handler: handler
+ )
+ }
+}
+
+public protocol models_GreeterClientInterceptorFactoryProtocol {
+ /// - Returns: Interceptors to use when invoking 'SayHello'.
+ func makeSayHelloInterceptors() -> [ClientInterceptor<Message<models_HelloRequest>, Message<models_HelloReply>>]
+
+ /// - Returns: Interceptors to use when invoking 'SayManyHellos'.
+ func makeSayManyHellosInterceptors() -> [ClientInterceptor<Message<models_HelloRequest>, Message<models_HelloReply>>]
+
+}
+
+public final class models_GreeterServiceClient: models_GreeterClientProtocol {
+ public let channel: GRPCChannel
+ public var defaultCallOptions: CallOptions
+ public var interceptors: models_GreeterClientInterceptorFactoryProtocol?
+
+ public init(
+ channel: GRPCChannel,
+ defaultCallOptions: CallOptions = CallOptions(),
+ interceptors: models_GreeterClientInterceptorFactoryProtocol? = nil
+ ) {
+ self.channel = channel
+ self.defaultCallOptions = defaultCallOptions
+ self.interceptors = interceptors
+ }
+}
+
+public protocol models_GreeterProvider: CallHandlerProvider {
+ var interceptors: models_GreeterServerInterceptorFactoryProtocol? { get }
+ func SayHello(request: Message<models_HelloRequest>, context: StatusOnlyCallContext) -> EventLoopFuture<Message<models_HelloReply>>
+ func SayManyHellos(request: Message<models_HelloRequest>, context: StreamingResponseCallContext<Message<models_HelloReply>>) -> EventLoopFuture<GRPCStatus>
+}
+
+public extension models_GreeterProvider {
+
+ var serviceName: Substring { return "models.Greeter" }
+
+ func handle(method name: Substring, context: CallHandlerContext) -> GRPCServerHandlerProtocol? {
+ switch name {
+ case "SayHello":
+ return UnaryServerHandler(
+ context: context,
+ requestDeserializer: GRPCPayloadDeserializer<Message<models_HelloRequest>>(),
+ responseSerializer: GRPCPayloadSerializer<Message<models_HelloReply>>(),
+ interceptors: self.interceptors?.makeSayHelloInterceptors() ?? [],
+ userFunction: self.SayHello(request:context:))
+
+ case "SayManyHellos":
+ return ServerStreamingServerHandler(
+ context: context,
+ requestDeserializer: GRPCPayloadDeserializer<Message<models_HelloRequest>>(),
+ responseSerializer: GRPCPayloadSerializer<Message<models_HelloReply>>(),
+ interceptors: self.interceptors?.makeSayManyHellosInterceptors() ?? [],
+ userFunction: self.SayManyHellos(request:context:))
+
+ default: return nil;
+ }
+ }
+
+}
+
+public protocol models_GreeterServerInterceptorFactoryProtocol {
+ /// - Returns: Interceptors to use when handling 'SayHello'.
+ /// Defaults to calling `self.makeInterceptors()`.
+ func makeSayHelloInterceptors() -> [ServerInterceptor<Message<models_HelloRequest>, Message<models_HelloReply>>]
+
+ /// - Returns: Interceptors to use when handling 'SayManyHellos'.
+ /// Defaults to calling `self.makeInterceptors()`.
+ func makeSayManyHellosInterceptors() -> [ServerInterceptor<Message<models_HelloRequest>, Message<models_HelloReply>>]
+
+}
diff --git a/grpc/examples/swift/Greeter/Sources/Model/greeter_generated.swift b/grpc/examples/swift/Greeter/Sources/Model/greeter_generated.swift
new file mode 100644
index 0000000..a7c420b
--- /dev/null
+++ b/grpc/examples/swift/Greeter/Sources/Model/greeter_generated.swift
@@ -0,0 +1,104 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+// swiftlint:disable all
+// swiftformat:disable all
+
+import FlatBuffers
+
+public struct models_HelloReply: FlatBufferObject, Verifiable {
+
+ static func validateVersion() { FlatBuffersVersion_2_0_0() }
+ public var __buffer: ByteBuffer! { return _accessor.bb }
+ private var _accessor: Table
+
+ public static func getRootAsHelloReply(bb: ByteBuffer) -> models_HelloReply { return models_HelloReply(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) }
+
+ private init(_ t: Table) { _accessor = t }
+ public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) }
+
+ private enum VTOFFSET: VOffset {
+ case message = 4
+ var v: Int32 { Int32(self.rawValue) }
+ var p: VOffset { self.rawValue }
+ }
+
+ public var message: String? { let o = _accessor.offset(VTOFFSET.message.v); return o == 0 ? nil : _accessor.string(at: o) }
+ public var messageSegmentArray: [UInt8]? { return _accessor.getVector(at: VTOFFSET.message.v) }
+ public static func startHelloReply(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) }
+ public static func add(message: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: message, at: VTOFFSET.message.p) }
+ public static func endHelloReply(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end }
+ public static func createHelloReply(
+ _ fbb: inout FlatBufferBuilder,
+ messageOffset message: Offset = Offset()
+ ) -> Offset {
+ let __start = models_HelloReply.startHelloReply(&fbb)
+ models_HelloReply.add(message: message, &fbb)
+ return models_HelloReply.endHelloReply(&fbb, start: __start)
+ }
+
+ public static func verify<T>(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable {
+ var _v = try verifier.visitTable(at: position)
+ try _v.visit(field: VTOFFSET.message.p, fieldName: "message", required: false, type: ForwardOffset<String>.self)
+ _v.finish()
+ }
+}
+
+extension models_HelloReply: Encodable {
+
+ enum CodingKeys: String, CodingKey {
+ case message = "message"
+ }
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encodeIfPresent(message, forKey: .message)
+ }
+}
+
+public struct models_HelloRequest: FlatBufferObject, Verifiable {
+
+ static func validateVersion() { FlatBuffersVersion_2_0_0() }
+ public var __buffer: ByteBuffer! { return _accessor.bb }
+ private var _accessor: Table
+
+ public static func getRootAsHelloRequest(bb: ByteBuffer) -> models_HelloRequest { return models_HelloRequest(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) }
+
+ private init(_ t: Table) { _accessor = t }
+ public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) }
+
+ private enum VTOFFSET: VOffset {
+ case name = 4
+ var v: Int32 { Int32(self.rawValue) }
+ var p: VOffset { self.rawValue }
+ }
+
+ public var name: String? { let o = _accessor.offset(VTOFFSET.name.v); return o == 0 ? nil : _accessor.string(at: o) }
+ public var nameSegmentArray: [UInt8]? { return _accessor.getVector(at: VTOFFSET.name.v) }
+ public static func startHelloRequest(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) }
+ public static func add(name: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: name, at: VTOFFSET.name.p) }
+ public static func endHelloRequest(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end }
+ public static func createHelloRequest(
+ _ fbb: inout FlatBufferBuilder,
+ nameOffset name: Offset = Offset()
+ ) -> Offset {
+ let __start = models_HelloRequest.startHelloRequest(&fbb)
+ models_HelloRequest.add(name: name, &fbb)
+ return models_HelloRequest.endHelloRequest(&fbb, start: __start)
+ }
+
+ public static func verify<T>(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable {
+ var _v = try verifier.visitTable(at: position)
+ try _v.visit(field: VTOFFSET.name.p, fieldName: "name", required: false, type: ForwardOffset<String>.self)
+ _v.finish()
+ }
+}
+
+extension models_HelloRequest: Encodable {
+
+ enum CodingKeys: String, CodingKey {
+ case name = "name"
+ }
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encodeIfPresent(name, forKey: .name)
+ }
+}
+
diff --git a/grpc/examples/swift/Greeter/Sources/client/main.swift b/grpc/examples/swift/Greeter/Sources/client/main.swift
new file mode 100644
index 0000000..168b071
--- /dev/null
+++ b/grpc/examples/swift/Greeter/Sources/client/main.swift
@@ -0,0 +1,107 @@
+/*
+ * Copyright 2021 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.
+ */
+
+import FlatBuffers
+import GRPC
+import Logging
+import Model
+import NIO
+
+// Quieten the logs.
+LoggingSystem.bootstrap {
+ var handler = StreamLogHandler.standardOutput(label: $0)
+ handler.logLevel = .critical
+ return handler
+}
+
+func greet(name: String, client greeter: models_GreeterServiceClient) {
+ // Form the request with the name, if one was provided.
+ var builder = FlatBufferBuilder()
+ let nameOff = builder.create(string: name)
+ let root = models_HelloRequest.createHelloRequest(
+ &builder,
+ nameOffset: nameOff)
+ builder.finish(offset: root)
+
+ // Make the RPC call to the server.
+ let sayHello = greeter
+ .SayHello(Message<models_HelloRequest>(builder: &builder))
+
+ // wait() on the response to stop the program from exiting before the response is received.
+ do {
+ let response = try sayHello.response.wait()
+ print("Greeter SayHello received: \(response.object.message ?? "Unknown")")
+ } catch {
+ print("Greeter failed: \(error)")
+ }
+
+ let surname = builder.create(string: name)
+ let manyRoot = models_HelloRequest.createHelloRequest(
+ &builder,
+ nameOffset: surname)
+ builder.finish(offset: manyRoot)
+
+ let call = greeter.SayManyHellos(Message(builder: &builder)) { message in
+ print(
+ "Greeter SayManyHellos received: \(message.object.message ?? "Unknown")")
+ }
+
+ let status = try! call.status.recover { _ in .processingError }.wait()
+ if status.code != .ok {
+ print("RPC failed: \(status)")
+ }
+}
+
+func main(args: [String]) {
+ // arg0 (dropped) is the program name. We expect arg1 to be the port, and arg2 (optional) to be
+ // the name sent in the request.
+ let arg1 = args.dropFirst(1).first
+ let arg2 = args.dropFirst(2).first
+
+ switch (arg1.flatMap(Int.init), arg2) {
+ case (.none, _):
+ print("Usage: PORT [NAME]")
+ exit(1)
+
+ case let (.some(port), name):
+ // Setup an `EventLoopGroup` for the connection to run on.
+ //
+ // See: https://github.com/apple/swift-nio#eventloops-and-eventloopgroups
+ let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
+
+ // Make sure the group is shutdown when we're done with it.
+ defer {
+ try! group.syncShutdownGracefully()
+ }
+
+ // Configure the channel, we're not using TLS so the connection is `insecure`.
+ let channel = ClientConnection.insecure(group: group)
+ .connect(host: "localhost", port: port)
+
+ // Close the connection when we're done with it.
+ defer {
+ try! channel.close().wait()
+ }
+
+ // Provide the connection to the generated client.
+ let greeter = models_GreeterServiceClient(channel: channel)
+
+ // Do the greeting.
+ greet(name: name ?? "FlatBuffers!", client: greeter)
+ }
+}
+
+main(args: CommandLine.arguments)
diff --git a/grpc/examples/swift/Greeter/Sources/server/main.swift b/grpc/examples/swift/Greeter/Sources/server/main.swift
new file mode 100644
index 0000000..fca623f
--- /dev/null
+++ b/grpc/examples/swift/Greeter/Sources/server/main.swift
@@ -0,0 +1,96 @@
+/*
+ * Copyright 2021 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.
+ */
+
+import FlatBuffers
+import GRPC
+import Logging
+import Model
+import NIO
+
+class Greeter: models_GreeterProvider {
+
+ var interceptors: models_GreeterServerInterceptorFactoryProtocol?
+
+ let greetings: [String]
+
+ init() {
+ greetings = ["Hi", "Hallo", "Ciao"]
+ }
+
+ func SayHello(
+ request: Message<models_HelloRequest>,
+ context: StatusOnlyCallContext)
+ -> EventLoopFuture<Message<models_HelloReply>>
+ {
+ let recipient = request.object.name ?? "Stranger"
+
+ var builder = FlatBufferBuilder()
+ let off = builder.create(string: "Hello \(recipient)")
+ let root = models_HelloReply.createHelloReply(&builder, messageOffset: off)
+ builder.finish(offset: root)
+ return context.eventLoop
+ .makeSucceededFuture(Message<models_HelloReply>(builder: &builder))
+ }
+
+ func SayManyHellos(
+ request: Message<models_HelloRequest>,
+ context: StreamingResponseCallContext<Message<models_HelloReply>>)
+ -> EventLoopFuture<GRPCStatus>
+ {
+ for name in greetings {
+ var builder = FlatBufferBuilder()
+ let off = builder
+ .create(string: "\(name) \(request.object.name ?? "Unknown")")
+ let root = models_HelloReply.createHelloReply(
+ &builder,
+ messageOffset: off)
+ builder.finish(offset: root)
+ _ = context.sendResponse(Message<models_HelloReply>(builder: &builder))
+ }
+ return context.eventLoop.makeSucceededFuture(.ok)
+ }
+}
+
+// Quieten the logs.
+LoggingSystem.bootstrap {
+ var handler = StreamLogHandler.standardOutput(label: $0)
+ handler.logLevel = .critical
+ return handler
+}
+
+let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
+defer {
+ try! group.syncShutdownGracefully()
+}
+
+// Create some configuration for the server:
+let configuration = Server.Configuration(
+ target: .hostAndPort("localhost", 0),
+ eventLoopGroup: group,
+ serviceProviders: [Greeter()])
+
+// Start the server and print its address once it has started.
+let server = Server.start(configuration: configuration)
+server.map {
+ $0.channel.localAddress
+}.whenSuccess { address in
+ print("server started on port \(address!.port!)")
+}
+
+// Wait on the server's `onClose` future to stop the program from exiting.
+_ = try server.flatMap {
+ $0.onClose
+}.wait()
diff --git a/grpc/examples/ts/greeter/README.md b/grpc/examples/ts/greeter/README.md
new file mode 100644
index 0000000..5c7b380
--- /dev/null
+++ b/grpc/examples/ts/greeter/README.md
@@ -0,0 +1,13 @@
+# TS Greeter example
+
+The following is an example on how to run the TS grpc server. Make sure that you have `Typescript` installed
+
+you would need to run `npm run build` or simply use `npm install && tsc`
+
+## How to run Server:
+
+- `npm run server`
+
+## How to run Client:
+
+- `npm run client 3000`
\ No newline at end of file
diff --git a/grpc/examples/ts/greeter/package.json b/grpc/examples/ts/greeter/package.json
new file mode 100644
index 0000000..324bd38
--- /dev/null
+++ b/grpc/examples/ts/greeter/package.json
@@ -0,0 +1,14 @@
+{
+ "name": "flatbuffers-js-grpc",
+ "version": "1.0.0",
+ "author": "mustii@mmk.one",
+ "scripts": {
+ "build": "npm install && tsc",
+ "client": "node dist/client.js",
+ "server": "node dist/server.js"
+ },
+ "dependencies": {
+ "@grpc/grpc-js": "^1.3.2",
+ "flatbuffers": "^2.0.0"
+ }
+}
diff --git a/grpc/examples/ts/greeter/src/client.ts b/grpc/examples/ts/greeter/src/client.ts
new file mode 100644
index 0000000..62444f1
--- /dev/null
+++ b/grpc/examples/ts/greeter/src/client.ts
@@ -0,0 +1,34 @@
+import * as grpc from '@grpc/grpc-js';
+import * as flatbuffers from 'flatbuffers';
+import { HelloReply } from './models/hello-reply';
+import { HelloRequest } from './models/hello-request';
+import { GreeterClient } from './greeter_grpc';
+
+async function main(PORT: Number, name: string) {
+ const client = new GreeterClient(`localhost:${PORT}`, grpc.credentials.createInsecure());
+ const builder = new flatbuffers.Builder();
+ const offset = builder.createString(name);
+ const root = HelloRequest.createHelloRequest(builder, offset);
+ builder.finish(root);
+ const buffer = HelloRequest.getRootAsHelloRequest(new flatbuffers.ByteBuffer(builder.asUint8Array()));
+
+ client.SayHello(buffer, (err, response) => {
+ console.log(response.message());
+ });
+
+ const data = client.SayManyHellos(buffer, null);
+
+ data.on('data', (data) => {
+ console.log(data.message());
+ });
+}
+
+const args = process.argv.slice(2)
+const PORT = Number(args[0]);
+const name: string = args[1] ?? "flatbuffers";
+
+if (PORT) {
+ main(PORT, name);
+} else {
+ throw new Error("Requires a valid port number.")
+}
\ No newline at end of file
diff --git a/grpc/examples/ts/greeter/src/greeter.ts b/grpc/examples/ts/greeter/src/greeter.ts
new file mode 100644
index 0000000..5e62d99
--- /dev/null
+++ b/grpc/examples/ts/greeter/src/greeter.ts
@@ -0,0 +1,2 @@
+export { HelloReply } from './models/hello-reply';
+export { HelloRequest } from './models/hello-request';
diff --git a/grpc/examples/ts/greeter/src/greeter_grpc.d.ts b/grpc/examples/ts/greeter/src/greeter_grpc.d.ts
new file mode 100644
index 0000000..657df5b
--- /dev/null
+++ b/grpc/examples/ts/greeter/src/greeter_grpc.d.ts
@@ -0,0 +1,56 @@
+// Generated GRPC code for FlatBuffers TS *** DO NOT EDIT ***
+import * as flatbuffers from 'flatbuffers';
+import { HelloReply as models_HelloReply } from './models/hello-reply';
+import { HelloRequest as models_HelloRequest } from './models/hello-request';
+
+import * as grpc from '@grpc/grpc-js';
+
+interface IGreeterService extends grpc.ServiceDefinition<grpc.UntypedServiceImplementation> {
+ SayHello: IGreeterService_ISayHello;
+ SayManyHellos: IGreeterService_ISayManyHellos;
+}
+interface IGreeterService_ISayHello extends grpc.MethodDefinition<models_HelloRequest, models_HelloReply> {
+ path: string; // /models.Greeter/SayHello
+ requestStream: boolean; // false
+ responseStream: boolean; // false
+ requestSerialize: grpc.serialize<models_HelloRequest>;
+ requestDeserialize: grpc.deserialize<models_HelloRequest>;
+ responseSerialize: grpc.serialize<models_HelloReply>;
+ responseDeserialize: grpc.deserialize<models_HelloReply>;
+}
+
+interface IGreeterService_ISayManyHellos extends grpc.MethodDefinition<models_HelloRequest, models_HelloReply> {
+ path: string; // /models.Greeter/SayManyHellos
+ requestStream: boolean; // false
+ responseStream: boolean; // true
+ requestSerialize: grpc.serialize<models_HelloRequest>;
+ requestDeserialize: grpc.deserialize<models_HelloRequest>;
+ responseSerialize: grpc.serialize<models_HelloReply>;
+ responseDeserialize: grpc.deserialize<models_HelloReply>;
+}
+
+
+export const GreeterService: IGreeterService;
+
+export interface IGreeterServer extends grpc.UntypedServiceImplementation {
+ SayHello: grpc.handleUnaryCall<models_HelloRequest, models_HelloReply>;
+ SayManyHellos: grpc.handleServerStreamingCall<models_HelloRequest, models_HelloReply>;
+}
+
+export interface IGreeterClient {
+ SayHello(request: models_HelloRequest, callback: (error: grpc.ServiceError | null, response: models_HelloReply) => void): grpc.ClientUnaryCall;
+ SayHello(request: models_HelloRequest, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: models_HelloReply) => void): grpc.ClientUnaryCall;
+ SayHello(request: models_HelloRequest, metadata: grpc.Metadata, options: Partial<grpc.CallOptions>, callback: (error: grpc.ServiceError | null, response: models_HelloReply) => void): grpc.ClientUnaryCall;
+ SayManyHellos(request: models_HelloRequest, metadata: grpc.Metadata): grpc.ClientReadableStream<models_HelloReply>;
+ SayManyHellos(request: models_HelloRequest, options: Partial<grpc.CallOptions>): grpc.ClientReadableStream<models_HelloReply>;
+}
+
+export class GreeterClient extends grpc.Client implements IGreeterClient {
+ constructor(address: string, credentials: grpc.ChannelCredentials, options?: object);
+ public SayHello(request: models_HelloRequest, callback: (error: grpc.ServiceError | null, response: models_HelloReply) => void): grpc.ClientUnaryCall;
+ public SayHello(request: models_HelloRequest, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: models_HelloReply) => void): grpc.ClientUnaryCall;
+ public SayHello(request: models_HelloRequest, metadata: grpc.Metadata, options: Partial<grpc.CallOptions>, callback: (error: grpc.ServiceError | null, response: models_HelloReply) => void): grpc.ClientUnaryCall;
+ public SayManyHellos(request: models_HelloRequest, metadata: grpc.Metadata): grpc.ClientReadableStream<models_HelloReply>;
+ public SayManyHellos(request: models_HelloRequest, options: Partial<grpc.CallOptions>): grpc.ClientReadableStream<models_HelloReply>;
+}
+
diff --git a/grpc/examples/ts/greeter/src/greeter_grpc.js b/grpc/examples/ts/greeter/src/greeter_grpc.js
new file mode 100644
index 0000000..242e686
--- /dev/null
+++ b/grpc/examples/ts/greeter/src/greeter_grpc.js
@@ -0,0 +1,56 @@
+// Generated GRPC code for FlatBuffers TS *** DO NOT EDIT ***
+import * as flatbuffers from 'flatbuffers';
+import { HelloReply as models_HelloReply } from './models/hello-reply';
+import { HelloRequest as models_HelloRequest } from './models/hello-request';
+
+var grpc = require('@grpc/grpc-js');
+
+function serialize_models_HelloReply(buffer_args) {
+ if (!(buffer_args instanceof models_HelloReply)) {
+ throw new Error('Expected argument of type HelloReply');
+ }
+ return Buffer.from(buffer_args.serialize());
+}
+
+function deserialize_models_HelloReply(buffer) {
+ return models_HelloReply.getRootAsHelloReply(new flatbuffers.ByteBuffer(buffer))
+}
+
+
+function serialize_models_HelloRequest(buffer_args) {
+ if (!(buffer_args instanceof models_HelloRequest)) {
+ throw new Error('Expected argument of type HelloRequest');
+ }
+ return Buffer.from(buffer_args.serialize());
+}
+
+function deserialize_models_HelloRequest(buffer) {
+ return models_HelloRequest.getRootAsHelloRequest(new flatbuffers.ByteBuffer(buffer))
+}
+
+
+var GreeterService = exports.GreeterService = {
+ SayHello: {
+ path: '/models.Greeter/SayHello',
+ requestStream: false,
+ responseStream: false,
+ requestType: flatbuffers.ByteBuffer,
+ responseType: models_HelloReply,
+ requestSerialize: serialize_models_HelloRequest,
+ requestDeserialize: deserialize_models_HelloRequest,
+ responseSerialize: serialize_models_HelloReply,
+ responseDeserialize: deserialize_models_HelloReply,
+ },
+ SayManyHellos: {
+ path: '/models.Greeter/SayManyHellos',
+ requestStream: false,
+ responseStream: true,
+ requestType: flatbuffers.ByteBuffer,
+ responseType: models_HelloReply,
+ requestSerialize: serialize_models_HelloRequest,
+ requestDeserialize: deserialize_models_HelloRequest,
+ responseSerialize: serialize_models_HelloReply,
+ responseDeserialize: deserialize_models_HelloReply,
+ },
+};
+exports.GreeterClient = grpc.makeGenericClientConstructor(GreeterService);
diff --git a/grpc/examples/ts/greeter/src/models/hello-reply.ts b/grpc/examples/ts/greeter/src/models/hello-reply.ts
new file mode 100644
index 0000000..e68f7a4
--- /dev/null
+++ b/grpc/examples/ts/greeter/src/models/hello-reply.ts
@@ -0,0 +1,58 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+import * as flatbuffers from 'flatbuffers';
+
+
+
+export class HelloReply {
+ bb: flatbuffers.ByteBuffer|null = null;
+ bb_pos = 0;
+__init(i:number, bb:flatbuffers.ByteBuffer):HelloReply {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+}
+
+static getRootAsHelloReply(bb:flatbuffers.ByteBuffer, obj?:HelloReply):HelloReply {
+ return (obj || new HelloReply()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+}
+
+static getSizePrefixedRootAsHelloReply(bb:flatbuffers.ByteBuffer, obj?:HelloReply):HelloReply {
+ bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new HelloReply()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+}
+
+message():string|null
+message(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null
+message(optionalEncoding?:any):string|Uint8Array|null {
+ const offset = this.bb!.__offset(this.bb_pos, 4);
+ return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
+}
+
+static startHelloReply(builder:flatbuffers.Builder) {
+ builder.startObject(1);
+}
+
+static addMessage(builder:flatbuffers.Builder, messageOffset:flatbuffers.Offset) {
+ builder.addFieldOffset(0, messageOffset, 0);
+}
+
+static endHelloReply(builder:flatbuffers.Builder):flatbuffers.Offset {
+ const offset = builder.endObject();
+ return offset;
+}
+
+static createHelloReply(builder:flatbuffers.Builder, messageOffset:flatbuffers.Offset):flatbuffers.Offset {
+ HelloReply.startHelloReply(builder);
+ HelloReply.addMessage(builder, messageOffset);
+ return HelloReply.endHelloReply(builder);
+}
+
+serialize():Uint8Array {
+ return this.bb!.bytes();
+}
+
+static deserialize(buffer: Uint8Array):HelloReply {
+ return HelloReply.getRootAsHelloReply(new flatbuffers.ByteBuffer(buffer))
+}
+}
diff --git a/grpc/examples/ts/greeter/src/models/hello-request.ts b/grpc/examples/ts/greeter/src/models/hello-request.ts
new file mode 100644
index 0000000..3718167
--- /dev/null
+++ b/grpc/examples/ts/greeter/src/models/hello-request.ts
@@ -0,0 +1,58 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+import * as flatbuffers from 'flatbuffers';
+
+
+
+export class HelloRequest {
+ bb: flatbuffers.ByteBuffer|null = null;
+ bb_pos = 0;
+__init(i:number, bb:flatbuffers.ByteBuffer):HelloRequest {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+}
+
+static getRootAsHelloRequest(bb:flatbuffers.ByteBuffer, obj?:HelloRequest):HelloRequest {
+ return (obj || new HelloRequest()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+}
+
+static getSizePrefixedRootAsHelloRequest(bb:flatbuffers.ByteBuffer, obj?:HelloRequest):HelloRequest {
+ bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new HelloRequest()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+}
+
+name():string|null
+name(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null
+name(optionalEncoding?:any):string|Uint8Array|null {
+ const offset = this.bb!.__offset(this.bb_pos, 4);
+ return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
+}
+
+static startHelloRequest(builder:flatbuffers.Builder) {
+ builder.startObject(1);
+}
+
+static addName(builder:flatbuffers.Builder, nameOffset:flatbuffers.Offset) {
+ builder.addFieldOffset(0, nameOffset, 0);
+}
+
+static endHelloRequest(builder:flatbuffers.Builder):flatbuffers.Offset {
+ const offset = builder.endObject();
+ return offset;
+}
+
+static createHelloRequest(builder:flatbuffers.Builder, nameOffset:flatbuffers.Offset):flatbuffers.Offset {
+ HelloRequest.startHelloRequest(builder);
+ HelloRequest.addName(builder, nameOffset);
+ return HelloRequest.endHelloRequest(builder);
+}
+
+serialize():Uint8Array {
+ return this.bb!.bytes();
+}
+
+static deserialize(buffer: Uint8Array):HelloRequest {
+ return HelloRequest.getRootAsHelloRequest(new flatbuffers.ByteBuffer(buffer))
+}
+}
diff --git a/grpc/examples/ts/greeter/src/server.ts b/grpc/examples/ts/greeter/src/server.ts
new file mode 100644
index 0000000..a3f2eee
--- /dev/null
+++ b/grpc/examples/ts/greeter/src/server.ts
@@ -0,0 +1,49 @@
+import * as grpc from '@grpc/grpc-js';
+import * as flatbuffers from 'flatbuffers';
+import { HelloReply } from './models/hello-reply';
+import { HelloRequest } from './models/hello-request';
+import { IGreeterServer, GreeterService } from './greeter_grpc';
+
+const greeter: IGreeterServer = {
+ SayHello(call: grpc.ServerUnaryCall<HelloRequest, HelloReply>, callback: grpc.sendUnaryData<HelloReply>): void {
+ console.log(`SayHello ${call.request.name()}`);
+ const builder = new flatbuffers.Builder();
+ const offset = builder.createString(`welcome ${call.request.name()}`);
+ const root = HelloReply.createHelloReply(builder, offset);
+ builder.finish(root);
+ callback(null, HelloReply.getRootAsHelloReply(new flatbuffers.ByteBuffer(builder.asUint8Array())));
+ },
+ async SayManyHellos(call: grpc.ServerWritableStream<HelloRequest, HelloReply>): Promise<void> {
+ const name = call.request.name();
+ console.log(`${call.request.name()} saying hi in different langagues`);
+ ['Hi', 'Hallo', 'Ciao'].forEach(element => {
+ const builder = new flatbuffers.Builder();
+ const offset = builder.createString(`${element} ${name}`);
+ const root = HelloReply.createHelloReply(builder, offset);
+ builder.finish(root);
+ call.write(HelloReply.getRootAsHelloReply(new flatbuffers.ByteBuffer(builder.asUint8Array())))
+ });
+ call.end();
+ }
+}
+
+function serve(): void {
+ const PORT = 3000;
+ const server = new grpc.Server();
+ server.addService(GreeterService, greeter);
+ console.log(`Listening on ${PORT}`);
+ server.bindAsync(
+ `localhost:${PORT}`,
+ grpc.ServerCredentials.createInsecure(),
+ (err: Error | null, port: number) => {
+ if (err) {
+ console.error(`Server error: ${err.message}`);
+ } else {
+ console.log(`Server bound on port: ${port}`);
+ server.start();
+ }
+ }
+ );
+}
+
+serve();
\ No newline at end of file
diff --git a/grpc/flatbuffers-js-grpc/tsconfig.json b/grpc/examples/ts/greeter/tsconfig.json
similarity index 100%
rename from grpc/flatbuffers-js-grpc/tsconfig.json
rename to grpc/examples/ts/greeter/tsconfig.json
diff --git a/grpc/flatbuffers-java-grpc/pom.xml b/grpc/flatbuffers-java-grpc/pom.xml
index 17814f6..f7d4176 100644
--- a/grpc/flatbuffers-java-grpc/pom.xml
+++ b/grpc/flatbuffers-java-grpc/pom.xml
@@ -6,7 +6,7 @@
<parent>
<groupId>com.google.flatbuffers</groupId>
<artifactId>flatbuffers-parent</artifactId>
- <version>1.12.0</version>
+ <version>2.0.3</version>
</parent>
<artifactId>flatbuffers-java-grpc</artifactId>
<name>${project.artifactId}</name>
@@ -24,7 +24,7 @@
</developer>
</developers>
<properties>
- <gRPC.version>1.12.0</gRPC.version>
+ <gRPC.version>1.36.0</gRPC.version>
</properties>
<dependencies>
<dependency>
diff --git a/grpc/flatbuffers-js-grpc/package.json b/grpc/flatbuffers-js-grpc/package.json
deleted file mode 100644
index d827049..0000000
--- a/grpc/flatbuffers-js-grpc/package.json
+++ /dev/null
@@ -1,9 +0,0 @@
-{
- "name": "flatbuffers-js-grpc",
- "version": "1.0.0",
- "author": "mustii@mmk.one",
- "dependencies": {
- "flatbuffers": "^1.12.0",
- "grpc": "^1.24.3"
- }
-}
diff --git a/grpc/flatbuffers-js-grpc/src/client.ts b/grpc/flatbuffers-js-grpc/src/client.ts
deleted file mode 100644
index 00d1009..0000000
--- a/grpc/flatbuffers-js-grpc/src/client.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import grpc from 'grpc';
-import { HelloRequest } from './greeter_generated';
-import { GreeterClient } from './greeter_grpc';
-import { flatbuffers } from 'flatbuffers';
-
-async function main() {
- const _server = new GreeterClient('localhost:3000', grpc.credentials.createInsecure());
- const builder = new flatbuffers.Builder();
- const offset = builder.createString('mustii');
- const root = HelloRequest.createHelloRequest(builder, offset);
- builder.finish(root);
- const buffer = HelloRequest.getRootAsHelloRequest(new flatbuffers.ByteBuffer(builder.asUint8Array()));
-
- _server.SayHello(buffer, (err, response) => {
- console.log(response.message());
- });
-
- const data = _server.SayManyHellos(buffer, null);
-
- data.on('data', (data) => {
- console.log(data.message());
- });
- data.on('end', (data) => {
- console.log('end');
- });
-}
-
-main();
\ No newline at end of file
diff --git a/grpc/flatbuffers-js-grpc/src/greeter.fbs b/grpc/flatbuffers-js-grpc/src/greeter.fbs
deleted file mode 100644
index b510884..0000000
--- a/grpc/flatbuffers-js-grpc/src/greeter.fbs
+++ /dev/null
@@ -1,12 +0,0 @@
-table HelloReply {
- message:string;
-}
-
-table HelloRequest {
- name:string;
-}
-
-rpc_service Greeter {
- SayHello(HelloRequest):HelloReply;
- SayManyHellos(HelloRequest):HelloReply (streaming: "server");
-}
diff --git a/grpc/flatbuffers-js-grpc/src/greeter_generated.ts b/grpc/flatbuffers-js-grpc/src/greeter_generated.ts
deleted file mode 100644
index 87113f9..0000000
--- a/grpc/flatbuffers-js-grpc/src/greeter_generated.ts
+++ /dev/null
@@ -1,174 +0,0 @@
-// automatically generated by the FlatBuffers compiler, do not modify
-
-/**
- * @constructor
- */
-export class HelloReply {
- bb: flatbuffers.ByteBuffer|null = null;
-
- bb_pos:number = 0;
-/**
- * @param number i
- * @param flatbuffers.ByteBuffer bb
- * @returns HelloReply
- */
-__init(i:number, bb:flatbuffers.ByteBuffer):HelloReply {
- this.bb_pos = i;
- this.bb = bb;
- return this;
-};
-
-/**
- * @param flatbuffers.ByteBuffer bb
- * @param HelloReply= obj
- * @returns HelloReply
- */
-static getRootAsHelloReply(bb:flatbuffers.ByteBuffer, obj?:HelloReply):HelloReply {
- return (obj || new HelloReply()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param flatbuffers.ByteBuffer bb
- * @param HelloReply= obj
- * @returns HelloReply
- */
-static getSizePrefixedRootAsHelloReply(bb:flatbuffers.ByteBuffer, obj?:HelloReply):HelloReply {
- bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
- return (obj || new HelloReply()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param flatbuffers.Encoding= optionalEncoding
- * @returns string|Uint8Array|null
- */
-message():string|null
-message(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null
-message(optionalEncoding?:any):string|Uint8Array|null {
- var offset = this.bb!.__offset(this.bb_pos, 4);
- return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
-};
-
-/**
- * @param flatbuffers.Builder builder
- */
-static startHelloReply(builder:flatbuffers.Builder) {
- builder.startObject(1);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Offset messageOffset
- */
-static addMessage(builder:flatbuffers.Builder, messageOffset:flatbuffers.Offset) {
- builder.addFieldOffset(0, messageOffset, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @returns flatbuffers.Offset
- */
-static endHelloReply(builder:flatbuffers.Builder):flatbuffers.Offset {
- var offset = builder.endObject();
- return offset;
-};
-
-static createHelloReply(builder:flatbuffers.Builder, messageOffset:flatbuffers.Offset):flatbuffers.Offset {
- HelloReply.startHelloReply(builder);
- HelloReply.addMessage(builder, messageOffset);
- return HelloReply.endHelloReply(builder);
-}
-
-serialize():Uint8Array {
- return this.bb!.bytes();
-}
-
-static deserialize(buffer: Uint8Array):HelloReply {
- return HelloReply.getRootAsHelloReply(new flatbuffers.ByteBuffer(buffer))
-}
-}
-/**
- * @constructor
- */
-export class HelloRequest {
- bb: flatbuffers.ByteBuffer|null = null;
-
- bb_pos:number = 0;
-/**
- * @param number i
- * @param flatbuffers.ByteBuffer bb
- * @returns HelloRequest
- */
-__init(i:number, bb:flatbuffers.ByteBuffer):HelloRequest {
- this.bb_pos = i;
- this.bb = bb;
- return this;
-};
-
-/**
- * @param flatbuffers.ByteBuffer bb
- * @param HelloRequest= obj
- * @returns HelloRequest
- */
-static getRootAsHelloRequest(bb:flatbuffers.ByteBuffer, obj?:HelloRequest):HelloRequest {
- return (obj || new HelloRequest()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param flatbuffers.ByteBuffer bb
- * @param HelloRequest= obj
- * @returns HelloRequest
- */
-static getSizePrefixedRootAsHelloRequest(bb:flatbuffers.ByteBuffer, obj?:HelloRequest):HelloRequest {
- bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
- return (obj || new HelloRequest()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param flatbuffers.Encoding= optionalEncoding
- * @returns string|Uint8Array|null
- */
-name():string|null
-name(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null
-name(optionalEncoding?:any):string|Uint8Array|null {
- var offset = this.bb!.__offset(this.bb_pos, 4);
- return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
-};
-
-/**
- * @param flatbuffers.Builder builder
- */
-static startHelloRequest(builder:flatbuffers.Builder) {
- builder.startObject(1);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Offset nameOffset
- */
-static addName(builder:flatbuffers.Builder, nameOffset:flatbuffers.Offset) {
- builder.addFieldOffset(0, nameOffset, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @returns flatbuffers.Offset
- */
-static endHelloRequest(builder:flatbuffers.Builder):flatbuffers.Offset {
- var offset = builder.endObject();
- return offset;
-};
-
-static createHelloRequest(builder:flatbuffers.Builder, nameOffset:flatbuffers.Offset):flatbuffers.Offset {
- HelloRequest.startHelloRequest(builder);
- HelloRequest.addName(builder, nameOffset);
- return HelloRequest.endHelloRequest(builder);
-}
-
-serialize():Uint8Array {
- return this.bb!.bytes();
-}
-
-static deserialize(buffer: Uint8Array):HelloRequest {
- return HelloRequest.getRootAsHelloRequest(new flatbuffers.ByteBuffer(buffer))
-}
-}
diff --git a/grpc/flatbuffers-js-grpc/src/greeter_grpc.d.ts b/grpc/flatbuffers-js-grpc/src/greeter_grpc.d.ts
deleted file mode 100644
index acd4c2f..0000000
--- a/grpc/flatbuffers-js-grpc/src/greeter_grpc.d.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-// Generated GRPC code for FlatBuffers TS *** DO NOT EDIT ***
-import { flatbuffers } from 'flatbuffers';
-import * as Greeter_fbs from './greeter_generated';
-
-import * as grpc from 'grpc';
-
-interface IGreeterService extends grpc.ServiceDefinition<grpc.UntypedServiceImplementation> {
- SayHello: IGreeterService_ISayHello;
- SayManyHellos: IGreeterService_ISayManyHellos;
-}
-interface IGreeterService_ISayHello extends grpc.MethodDefinition<Greeter_fbs.HelloRequest, Greeter_fbs.HelloReply> {
- path: string; // /Greeter/SayHello
- requestStream: boolean; // false
- responseStream: boolean; // false
- requestSerialize: grpc.serialize<Greeter_fbs.HelloRequest>;
- requestDeserialize: grpc.deserialize<Greeter_fbs.HelloRequest>;
- responseSerialize: grpc.serialize<Greeter_fbs.HelloReply>;
- responseDeserialize: grpc.deserialize<Greeter_fbs.HelloReply>;
-}
-
-interface IGreeterService_ISayManyHellos extends grpc.MethodDefinition<Greeter_fbs.HelloRequest, Greeter_fbs.HelloReply> {
- path: string; // /Greeter/SayManyHellos
- requestStream: boolean; // false
- responseStream: boolean; // true
- requestSerialize: grpc.serialize<Greeter_fbs.HelloRequest>;
- requestDeserialize: grpc.deserialize<Greeter_fbs.HelloRequest>;
- responseSerialize: grpc.serialize<Greeter_fbs.HelloReply>;
- responseDeserialize: grpc.deserialize<Greeter_fbs.HelloReply>;
-}
-
-
-export const GreeterService: IGreeterService;
-
-export interface IGreeterServer {
- SayHello: grpc.handleUnaryCall<Greeter_fbs.HelloRequest, Greeter_fbs.HelloReply>;
- SayManyHellos: grpc.handleServerStreamingCall<Greeter_fbs.HelloRequest, Greeter_fbs.HelloReply>;
-}
-
-export interface IGreeterClient {
- SayHello(request: Greeter_fbs.HelloRequest, callback: (error: grpc.ServiceError | null, response: Greeter_fbs.HelloReply) => void): grpc.ClientUnaryCall;
- SayHello(request: Greeter_fbs.HelloRequest, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: Greeter_fbs.HelloReply) => void): grpc.ClientUnaryCall;
- SayHello(request: Greeter_fbs.HelloRequest, metadata: grpc.Metadata, options: Partial<grpc.CallOptions>, callback: (error: grpc.ServiceError | null, response: Greeter_fbs.HelloReply) => void): grpc.ClientUnaryCall;
- SayManyHellos(request: Greeter_fbs.HelloRequest, metadata: grpc.Metadata): grpc.ClientReadableStream<Greeter_fbs.HelloReply>;
- SayManyHellos(request: Greeter_fbs.HelloRequest, options: Partial<grpc.CallOptions>): grpc.ClientReadableStream<Greeter_fbs.HelloReply>;
-}
-
-export class GreeterClient extends grpc.Client implements IGreeterClient {
- constructor(address: string, credentials: grpc.ChannelCredentials, options?: object); public SayHello(request: Greeter_fbs.HelloRequest, callback: (error: grpc.ServiceError | null, response: Greeter_fbs.HelloReply) => void): grpc.ClientUnaryCall;
- public SayHello(request: Greeter_fbs.HelloRequest, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: Greeter_fbs.HelloReply) => void): grpc.ClientUnaryCall;
- public SayHello(request: Greeter_fbs.HelloRequest, metadata: grpc.Metadata, options: Partial<grpc.CallOptions>, callback: (error: grpc.ServiceError | null, response: Greeter_fbs.HelloReply) => void): grpc.ClientUnaryCall;
- public SayManyHellos(request: Greeter_fbs.HelloRequest, metadata: grpc.Metadata): grpc.ClientReadableStream<Greeter_fbs.HelloReply>;
- public SayManyHellos(request: Greeter_fbs.HelloRequest, options: Partial<grpc.CallOptions>): grpc.ClientReadableStream<Greeter_fbs.HelloReply>;
-}
-
diff --git a/grpc/flatbuffers-js-grpc/src/greeter_grpc.js b/grpc/flatbuffers-js-grpc/src/greeter_grpc.js
deleted file mode 100644
index a184ba1..0000000
--- a/grpc/flatbuffers-js-grpc/src/greeter_grpc.js
+++ /dev/null
@@ -1,55 +0,0 @@
-// Generated GRPC code for FlatBuffers TS *** DO NOT EDIT ***
-import { flatbuffers } from 'flatbuffers';
-import * as Greeter_fbs from './greeter_generated';
-
-var grpc = require('grpc');
-
-function serialize_HelloReply(buffer_args) {
- if (!(buffer_args instanceof Greeter_fbs.HelloReply)) {
- throw new Error('Expected argument of type Greeter_fbs.HelloReply');
- }
- return buffer_args.serialize();
-}
-
-function deserialize_HelloReply(buffer) {
- return Greeter_fbs.HelloReply.getRootAsHelloReply(new flatbuffers.ByteBuffer(buffer))
-}
-
-
-function serialize_HelloRequest(buffer_args) {
- if (!(buffer_args instanceof Greeter_fbs.HelloRequest)) {
- throw new Error('Expected argument of type Greeter_fbs.HelloRequest');
- }
- return buffer_args.serialize();
-}
-
-function deserialize_HelloRequest(buffer) {
- return Greeter_fbs.HelloRequest.getRootAsHelloRequest(new flatbuffers.ByteBuffer(buffer))
-}
-
-
-var GreeterService = exports.GreeterService = {
- SayHello: {
- path: '/Greeter/SayHello',
- requestStream: false,
- responseStream: false,
- requestType: flatbuffers.ByteBuffer,
- responseType: Greeter_fbs.HelloReply,
- requestSerialize: serialize_HelloRequest,
- requestDeserialize: deserialize_HelloRequest,
- responseSerialize: serialize_HelloReply,
- responseDeserialize: deserialize_HelloReply,
- },
- SayManyHellos: {
- path: '/Greeter/SayManyHellos',
- requestStream: false,
- responseStream: true,
- requestType: flatbuffers.ByteBuffer,
- responseType: Greeter_fbs.HelloReply,
- requestSerialize: serialize_HelloRequest,
- requestDeserialize: deserialize_HelloRequest,
- responseSerialize: serialize_HelloReply,
- responseDeserialize: deserialize_HelloReply,
- },
-};
-exports.GreeterClient = grpc.makeGenericClientConstructor(GreeterService);
diff --git a/grpc/flatbuffers-js-grpc/src/server.ts b/grpc/flatbuffers-js-grpc/src/server.ts
deleted file mode 100644
index 47c2f89..0000000
--- a/grpc/flatbuffers-js-grpc/src/server.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-import grpc from 'grpc';
-import { HelloReply, HelloRequest } from './greeter_generated';
-import { IGreeterServer, GreeterService } from './greeter_grpc';
-import { flatbuffers } from 'flatbuffers';
-
-class GreeterServer implements IGreeterServer {
-
- SayHello(call: grpc.ServerUnaryCall<HelloRequest>, callback: grpc.sendUnaryData<HelloReply>): void {
- console.log(`${call.request.name()}`);
- const builder = new flatbuffers.Builder();
- const offset = builder.createString(`welcome ${call.request.name()}`);
- const root = HelloReply.createHelloReply(builder, offset);
- builder.finish(root);
- callback(null, HelloReply.getRootAsHelloReply(new flatbuffers.ByteBuffer(builder.asUint8Array())));
- }
-
- async SayManyHellos(call: grpc.ServerWritableStream<HelloRequest>): Promise<void> {
- const name = call.request.name();
- console.log(`${call.request.name()} saying hi in different langagues`);
- ['Hi', 'Hallo', 'Ciao'].forEach(element => {
- const builder = new flatbuffers.Builder();
- const offset = builder.createString(`${element} ${name}`);
- const root = HelloReply.createHelloReply(builder, offset);
- builder.finish(root);
- call.write(HelloReply.getRootAsHelloReply(new flatbuffers.ByteBuffer(builder.asUint8Array())))
- });
- call.end();
- }
-}
-
-function serve(): void {
- const PORT = 3000;
- const server = new grpc.Server();
- server.addService<IGreeterServer>(GreeterService, new GreeterServer());
- console.log(`Listening on ${PORT}`);
- server.bind(`localhost:${PORT}`, grpc.ServerCredentials.createInsecure());
- server.start();
-}
-
-serve();
\ No newline at end of file
diff --git a/grpc/pom.xml b/grpc/pom.xml
index 1eaf8d9..a0608ae 100644
--- a/grpc/pom.xml
+++ b/grpc/pom.xml
@@ -4,7 +4,7 @@
<groupId>com.google.flatbuffers</groupId>
<artifactId>flatbuffers-parent</artifactId>
<packaging>pom</packaging>
- <version>1.12.0</version>
+ <version>2.0.3</version>
<name>flatbuffers-parent</name>
<description>parent pom for flatbuffers java artifacts</description>
<properties>
diff --git a/grpc/samples/greeter/Makefile b/grpc/samples/greeter/Makefile
index 3746705..910483c 100644
--- a/grpc/samples/greeter/Makefile
+++ b/grpc/samples/greeter/Makefile
@@ -4,11 +4,11 @@
.PHONY: all
all: server client
-greeter_generated.h: greeter.fbs
+greeter_generated: greeter.fbs
flatc --grpc --cpp $<
-server: server.cpp greeter.grpc.fb.cc greeter_generated.h greeter.grpc.fb.h
+server: greeter_generated server.cpp greeter.grpc.fb.cc greeter.grpc.fb.h
g++ -std=c++11 -O2 $(CXXFLAGS) $(LDFLAGS) -lgpr -lgrpc -lgrpc++ server.cpp greeter.grpc.fb.cc -o $@
-client: client.cpp greeter.grpc.fb.cc greeter_generated.h greeter.grpc.fb.h
+client: greeter_generated client.cpp greeter.grpc.fb.cc greeter.grpc.fb.h
g++ -std=c++11 -O2 $(CXXFLAGS) $(LDFLAGS) -lgpr -lgrpc -lgrpc++ client.cpp greeter.grpc.fb.cc -o $@
diff --git a/grpc/samples/greeter/client.cpp b/grpc/samples/greeter/client.cpp
index 2e42f8f..0e4f348 100644
--- a/grpc/samples/greeter/client.cpp
+++ b/grpc/samples/greeter/client.cpp
@@ -1,7 +1,7 @@
#include "greeter.grpc.fb.h"
#include "greeter_generated.h"
-#include <grpc++/grpc++.h>
+#include <grpcpp/grpcpp.h>
#include <iostream>
#include <memory>
diff --git a/grpc/samples/greeter/server.cpp b/grpc/samples/greeter/server.cpp
index db44259..ac38fa9 100644
--- a/grpc/samples/greeter/server.cpp
+++ b/grpc/samples/greeter/server.cpp
@@ -1,7 +1,7 @@
#include "greeter.grpc.fb.h"
#include "greeter_generated.h"
-#include <grpc++/grpc++.h>
+#include <grpcpp/grpcpp.h>
#include <iostream>
#include <memory>
diff --git a/grpc/src/compiler/BUILD b/grpc/src/compiler/BUILD
deleted file mode 100644
index 23fe540..0000000
--- a/grpc/src/compiler/BUILD
+++ /dev/null
@@ -1,123 +0,0 @@
-load("@rules_cc//cc:defs.bzl", "cc_library")
-
-package(
- default_visibility = ["//visibility:public"],
-)
-
-filegroup(
- name = "common_headers",
- srcs = [
- "config.h",
- "schema_interface.h",
- ],
-)
-
-cc_library(
- name = "cpp_generator",
- srcs = [
- "cpp_generator.cc",
- ],
- hdrs = [
- "cpp_generator.h",
- ":common_headers",
- ],
- include_prefix = "src/compiler",
- strip_include_prefix = "/grpc/src/compiler",
- deps = [
- "//:flatbuffers",
- ],
-)
-
-cc_library(
- name = "go_generator",
- srcs = [
- "go_generator.cc",
- ],
- hdrs = [
- "go_generator.h",
- ":common_headers",
- ],
- include_prefix = "src/compiler",
- strip_include_prefix = "/grpc/src/compiler",
- deps = [
- "//:flatbuffers",
- ],
-)
-
-cc_library(
- name = "java_generator",
- srcs = [
- "java_generator.cc",
- ],
- hdrs = [
- "java_generator.h",
- ":common_headers",
- ],
- include_prefix = "src/compiler",
- strip_include_prefix = "/grpc/src/compiler",
- deps = [
- "//:flatbuffers",
- ],
-)
-
-cc_library(
- name = "python_generator",
- hdrs = [
- "python_generator.h",
- ],
- include_prefix = "src/compiler",
- strip_include_prefix = "/grpc/src/compiler",
- deps = [
- ":python_generator_private",
- ],
-)
-
-cc_library(
- name = "python_generator_private",
- srcs = [
- "python_generator.cc",
- ],
- hdrs = [
- "python_generator.h",
- "python_private_generator.h",
- ":common_headers",
- ],
- include_prefix = "src/compiler",
- strip_include_prefix = "/grpc/src/compiler",
- visibility = ["//visibility:private"],
- deps = [
- "//:flatbuffers",
- ],
-)
-
-cc_library(
- name = "swift_generator",
- srcs = [
- "swift_generator.cc",
- ],
- hdrs = [
- "swift_generator.h",
- ":common_headers",
- ],
- include_prefix = "src/compiler",
- strip_include_prefix = "/grpc/src/compiler",
- deps = [
- "//:flatbuffers",
- ],
-)
-
-cc_library(
- name = "ts_generator",
- srcs = [
- "ts_generator.cc",
- ],
- hdrs = [
- "ts_generator.h",
- ":common_headers",
- ],
- include_prefix = "src/compiler",
- strip_include_prefix = "/grpc/src/compiler",
- deps = [
- "//:flatbuffers",
- ],
-)
\ No newline at end of file
diff --git a/grpc/src/compiler/BUILD.bazel b/grpc/src/compiler/BUILD.bazel
new file mode 100644
index 0000000..544885e
--- /dev/null
+++ b/grpc/src/compiler/BUILD.bazel
@@ -0,0 +1,121 @@
+load("@rules_cc//cc:defs.bzl", "cc_library")
+
+package(
+ default_visibility = ["//visibility:public"],
+)
+
+filegroup(
+ name = "common_headers",
+ srcs = [
+ "schema_interface.h",
+ ],
+)
+
+cc_library(
+ name = "cpp_generator",
+ srcs = [
+ "cpp_generator.cc",
+ ],
+ hdrs = [
+ "cpp_generator.h",
+ ":common_headers",
+ ],
+ include_prefix = "src/compiler",
+ strip_include_prefix = "/grpc/src/compiler",
+ deps = [
+ "//:flatbuffers",
+ ],
+)
+
+cc_library(
+ name = "go_generator",
+ srcs = [
+ "go_generator.cc",
+ ],
+ hdrs = [
+ "go_generator.h",
+ ":common_headers",
+ ],
+ include_prefix = "src/compiler",
+ strip_include_prefix = "/grpc/src/compiler",
+ deps = [
+ "//:flatbuffers",
+ ],
+)
+
+cc_library(
+ name = "java_generator",
+ srcs = [
+ "java_generator.cc",
+ ],
+ hdrs = [
+ "java_generator.h",
+ ":common_headers",
+ ],
+ include_prefix = "src/compiler",
+ strip_include_prefix = "/grpc/src/compiler",
+ deps = [
+ "//:flatbuffers",
+ ],
+)
+
+cc_library(
+ name = "python_generator",
+ hdrs = [
+ "python_generator.h",
+ ],
+ include_prefix = "src/compiler",
+ strip_include_prefix = "/grpc/src/compiler",
+ deps = [
+ ":python_generator_private",
+ ],
+)
+
+cc_library(
+ name = "python_generator_private",
+ srcs = [
+ "python_generator.cc",
+ ],
+ hdrs = [
+ "python_generator.h",
+ ":common_headers",
+ ],
+ include_prefix = "src/compiler",
+ strip_include_prefix = "/grpc/src/compiler",
+ visibility = ["//visibility:private"],
+ deps = [
+ "//:flatbuffers",
+ ],
+)
+
+cc_library(
+ name = "swift_generator",
+ srcs = [
+ "swift_generator.cc",
+ ],
+ hdrs = [
+ "swift_generator.h",
+ ":common_headers",
+ ],
+ include_prefix = "src/compiler",
+ strip_include_prefix = "/grpc/src/compiler",
+ deps = [
+ "//:flatbuffers",
+ ],
+)
+
+cc_library(
+ name = "ts_generator",
+ srcs = [
+ "ts_generator.cc",
+ ],
+ hdrs = [
+ "ts_generator.h",
+ ":common_headers",
+ ],
+ include_prefix = "src/compiler",
+ strip_include_prefix = "/grpc/src/compiler",
+ deps = [
+ "//:flatbuffers",
+ ],
+)
diff --git a/grpc/src/compiler/config.h b/grpc/src/compiler/config.h
deleted file mode 100644
index 4adc594..0000000
--- a/grpc/src/compiler/config.h
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- *
- * Copyright 2015, Google Inc.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#ifndef SRC_COMPILER_CONFIG_H
-#define SRC_COMPILER_CONFIG_H
-
-// This file is here only because schema_interface.h, which is copied from gRPC,
-// includes it. There is nothing for Flatbuffers to configure.
-
-#endif // SRC_COMPILER_CONFIG_H
diff --git a/grpc/src/compiler/cpp_generator.cc b/grpc/src/compiler/cpp_generator.cc
index 6cfd22e..69dcf59 100644
--- a/grpc/src/compiler/cpp_generator.cc
+++ b/grpc/src/compiler/cpp_generator.cc
@@ -1,51 +1,17 @@
-/*
- *
- * Copyright 2015, Google Inc.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
+#include "src/compiler/cpp_generator.h"
#include <map>
-
-#include "src/compiler/cpp_generator.h"
-#include "flatbuffers/util.h"
-
#include <sstream>
+#include "flatbuffers/util.h"
+
namespace grpc_cpp_generator {
namespace {
grpc::string message_header_ext() { return "_generated.h"; }
grpc::string service_header_ext() { return ".grpc.fb.h"; }
-template <class T>
-grpc::string as_string(T x) {
+template<class T> grpc::string as_string(T x) {
std::ostringstream out;
out << x;
return out.str();
@@ -76,10 +42,7 @@
}
} // namespace
-template <class T, size_t N>
-T *array_end(T (&array)[N]) {
- return array + N;
-}
+template<class T, size_t N> T *array_end(T (&array)[N]) { return array + N; }
void PrintIncludes(grpc_generator::Printer *printer,
const std::vector<grpc::string> &headers,
@@ -92,9 +55,7 @@
auto &s = params.grpc_search_path;
if (!s.empty()) {
vars["l"] += s;
- if (s[s.size() - 1] != '/') {
- vars["l"] += '/';
- }
+ if (s[s.size() - 1] != '/') { vars["l"] += '/'; }
}
for (auto i = headers.begin(); i != headers.end(); i++) {
@@ -114,7 +75,7 @@
vars["filename"] = file->filename();
vars["filename_identifier"] = FilenameIdentifier(file->filename());
vars["filename_base"] = file->filename_without_ext();
- vars["message_header_ext"] = message_header_ext();
+ vars["message_header_ext"] = file->message_header_ext();
printer->Print(vars, "// Generated by the gRPC C++ plugin.\n");
printer->Print(vars,
@@ -144,15 +105,16 @@
std::map<grpc::string, grpc::string> vars;
static const char *headers_strs[] = {
- "grpc++/impl/codegen/async_stream.h",
- "grpc++/impl/codegen/async_unary_call.h",
- "grpc++/impl/codegen/method_handler_impl.h",
- "grpc++/impl/codegen/proto_utils.h",
- "grpc++/impl/codegen/rpc_method.h",
- "grpc++/impl/codegen/service_type.h",
- "grpc++/impl/codegen/status.h",
- "grpc++/impl/codegen/stub_options.h",
- "grpc++/impl/codegen/sync_stream.h"};
+ "grpcpp/impl/codegen/async_stream.h",
+ "grpcpp/impl/codegen/async_unary_call.h",
+ "grpcpp/impl/codegen/method_handler.h",
+ "grpcpp/impl/codegen/proto_utils.h",
+ "grpcpp/impl/codegen/rpc_method.h",
+ "grpcpp/impl/codegen/service_type.h",
+ "grpcpp/impl/codegen/status.h",
+ "grpcpp/impl/codegen/stub_options.h",
+ "grpcpp/impl/codegen/sync_stream.h"
+ };
std::vector<grpc::string> headers(headers_strs, array_end(headers_strs));
PrintIncludes(printer.get(), headers, params);
printer->Print(vars, "\n");
@@ -187,8 +149,8 @@
grpc::string prefix;
grpc::string method_params; // extra arguments to method
grpc::string raw_args; // extra arguments to raw version of method
- } async_prefixes[] = {{"Async", ", void* tag", ", tag"},
- {"PrepareAsync", "", ""}};
+ } async_prefixes[] = { { "Async", ", void* tag", ", tag" },
+ { "PrepareAsync", "", "" } };
if (is_public) {
if (method->NoStreaming()) {
@@ -196,8 +158,9 @@
*vars,
"virtual ::grpc::Status $Method$(::grpc::ClientContext* context, "
"const $Request$& request, $Response$* response) = 0;\n");
- for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
- auto& async_prefix = async_prefixes[i];
+ for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
+ i++) {
+ auto &async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
printer->Print(
*vars,
@@ -228,8 +191,9 @@
"($Method$Raw(context, response));\n");
printer->Outdent();
printer->Print("}\n");
- for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
- auto& async_prefix = async_prefixes[i];
+ for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
+ i++) {
+ auto &async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
@@ -262,8 +226,9 @@
"($Method$Raw(context, request));\n");
printer->Outdent();
printer->Print("}\n");
- for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
- auto& async_prefix = async_prefixes[i];
+ for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
+ i++) {
+ auto &async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
@@ -295,8 +260,9 @@
"$Method$Raw(context));\n");
printer->Outdent();
printer->Print("}\n");
- for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
- auto& async_prefix = async_prefixes[i];
+ for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
+ i++) {
+ auto &async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
@@ -318,8 +284,9 @@
}
} else {
if (method->NoStreaming()) {
- for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
- auto& async_prefix = async_prefixes[i];
+ for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
+ i++) {
+ auto &async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
printer->Print(
*vars,
@@ -334,8 +301,9 @@
"virtual ::grpc::ClientWriterInterface< $Request$>*"
" $Method$Raw("
"::grpc::ClientContext* context, $Response$* response) = 0;\n");
- for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
- auto& async_prefix = async_prefixes[i];
+ for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
+ i++) {
+ auto &async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
printer->Print(
@@ -351,8 +319,9 @@
"virtual ::grpc::ClientReaderInterface< $Response$>* "
"$Method$Raw("
"::grpc::ClientContext* context, const $Request$& request) = 0;\n");
- for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
- auto& async_prefix = async_prefixes[i];
+ for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
+ i++) {
+ auto &async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
printer->Print(
@@ -367,8 +336,9 @@
"virtual ::grpc::ClientReaderWriterInterface< $Request$, "
"$Response$>* "
"$Method$Raw(::grpc::ClientContext* context) = 0;\n");
- for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
- auto& async_prefix = async_prefixes[i];
+ for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
+ i++) {
+ auto &async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
printer->Print(
@@ -393,8 +363,8 @@
grpc::string prefix;
grpc::string method_params; // extra arguments to method
grpc::string raw_args; // extra arguments to raw version of method
- } async_prefixes[] = {{"Async", ", void* tag", ", tag"},
- {"PrepareAsync", "", ""}};
+ } async_prefixes[] = { { "Async", ", void* tag", ", tag" },
+ { "PrepareAsync", "", "" } };
if (is_public) {
if (method->NoStreaming()) {
@@ -402,8 +372,9 @@
*vars,
"::grpc::Status $Method$(::grpc::ClientContext* context, "
"const $Request$& request, $Response$* response) override;\n");
- for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
- auto& async_prefix = async_prefixes[i];
+ for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
+ i++) {
+ auto &async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
printer->Print(
*vars,
@@ -431,8 +402,9 @@
"($Method$Raw(context, response));\n");
printer->Outdent();
printer->Print("}\n");
- for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
- auto& async_prefix = async_prefixes[i];
+ for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
+ i++) {
+ auto &async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
@@ -463,8 +435,9 @@
"($Method$Raw(context, request));\n");
printer->Outdent();
printer->Print("}\n");
- for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
- auto& async_prefix = async_prefixes[i];
+ for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
+ i++) {
+ auto &async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
@@ -494,8 +467,9 @@
"$Method$Raw(context));\n");
printer->Outdent();
printer->Print("}\n");
- for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
- auto& async_prefix = async_prefixes[i];
+ for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
+ i++) {
+ auto &async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
@@ -516,8 +490,9 @@
}
} else {
if (method->NoStreaming()) {
- for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
- auto& async_prefix = async_prefixes[i];
+ for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
+ i++) {
+ auto &async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
printer->Print(
*vars,
@@ -531,8 +506,9 @@
"::grpc::ClientWriter< $Request$>* $Method$Raw("
"::grpc::ClientContext* context, $Response$* response) "
"override;\n");
- for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
- auto& async_prefix = async_prefixes[i];
+ for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
+ i++) {
+ auto &async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
@@ -547,8 +523,9 @@
"::grpc::ClientReader< $Response$>* $Method$Raw("
"::grpc::ClientContext* context, const $Request$& request)"
" override;\n");
- for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
- auto& async_prefix = async_prefixes[i];
+ for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
+ i++) {
+ auto &async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
@@ -562,8 +539,9 @@
printer->Print(*vars,
"::grpc::ClientReaderWriter< $Request$, $Response$>* "
"$Method$Raw(::grpc::ClientContext* context) override;\n");
- for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
- auto& async_prefix = async_prefixes[i];
+ for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
+ i++) {
+ auto &async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
@@ -630,7 +608,8 @@
"class WithAsyncMethod_$Method$ : public BaseClass {\n");
printer->Print(
" private:\n"
- " void BaseClassMustBeDerivedFromService(const Service *service) {}\n");
+ " void BaseClassMustBeDerivedFromService(const Service */*service*/) "
+ "{}\n");
printer->Print(" public:\n");
printer->Indent();
printer->Print(*vars,
@@ -646,8 +625,8 @@
*vars,
"// disable synchronous version of this method\n"
"::grpc::Status $Method$("
- "::grpc::ServerContext* context, const $Request$* request, "
- "$Response$* response) final override {\n"
+ "::grpc::ServerContext* /*context*/, const $Request$* /*request*/, "
+ "$Response$* /*response*/) final override {\n"
" abort();\n"
" return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n"
"}\n");
@@ -667,8 +646,8 @@
*vars,
"// disable synchronous version of this method\n"
"::grpc::Status $Method$("
- "::grpc::ServerContext* context, "
- "::grpc::ServerReader< $Request$>* reader, "
+ "::grpc::ServerContext* /*context*/, "
+ "::grpc::ServerReader< $Request$>* /*reader*/, "
"$Response$* response) final override {\n"
" abort();\n"
" return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n"
@@ -689,8 +668,8 @@
*vars,
"// disable synchronous version of this method\n"
"::grpc::Status $Method$("
- "::grpc::ServerContext* context, const $Request$* request, "
- "::grpc::ServerWriter< $Response$>* writer) final override "
+ "::grpc::ServerContext* /*context*/, const $Request$* /*request*/, "
+ "::grpc::ServerWriter< $Response$>* /*writer*/) final override "
"{\n"
" abort();\n"
" return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n"
@@ -712,8 +691,8 @@
*vars,
"// disable synchronous version of this method\n"
"::grpc::Status $Method$("
- "::grpc::ServerContext* context, "
- "::grpc::ServerReaderWriter< $Response$, $Request$>* stream) "
+ "::grpc::ServerContext* /*context*/, "
+ "::grpc::ServerReaderWriter< $Response$, $Request$>* /*stream*/) "
"final override {\n"
" abort();\n"
" return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n"
@@ -747,7 +726,7 @@
"public BaseClass {\n");
printer->Print(
" private:\n"
- " void BaseClassMustBeDerivedFromService(const Service *service) "
+ " void BaseClassMustBeDerivedFromService(const Service */*service*/) "
"{}\n");
printer->Print(" public:\n");
printer->Indent();
@@ -768,8 +747,8 @@
*vars,
"// disable regular version of this method\n"
"::grpc::Status $Method$("
- "::grpc::ServerContext* context, const $Request$* request, "
- "$Response$* response) final override {\n"
+ "::grpc::ServerContext* /*context*/, const $Request$* /*request*/, "
+ "$Response$* /*response*/) final override {\n"
" abort();\n"
" return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n"
"}\n");
@@ -798,8 +777,8 @@
"public BaseClass {\n");
printer->Print(
" private:\n"
- " void BaseClassMustBeDerivedFromService(const Service *service) "
- "{}\n");
+ " void BaseClassMustBeDerivedFromService(const Service */*service*/) "
+ "{ }\n");
printer->Print(" public:\n");
printer->Indent();
printer->Print(
@@ -820,8 +799,8 @@
*vars,
"// disable regular version of this method\n"
"::grpc::Status $Method$("
- "::grpc::ServerContext* context, const $Request$* request, "
- "::grpc::ServerWriter< $Response$>* writer) final override "
+ "::grpc::ServerContext* /*context*/, const $Request$* /*request*/, "
+ "::grpc::ServerWriter< $Response$>* /*writer*/) final override "
"{\n"
" abort();\n"
" return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n"
@@ -849,7 +828,8 @@
"class WithGenericMethod_$Method$ : public BaseClass {\n");
printer->Print(
" private:\n"
- " void BaseClassMustBeDerivedFromService(const Service *service) {}\n");
+ " void BaseClassMustBeDerivedFromService(const Service */*service*/) "
+ "{}\n");
printer->Print(" public:\n");
printer->Indent();
printer->Print(*vars,
@@ -865,8 +845,8 @@
*vars,
"// disable synchronous version of this method\n"
"::grpc::Status $Method$("
- "::grpc::ServerContext* context, const $Request$* request, "
- "$Response$* response) final override {\n"
+ "::grpc::ServerContext* /*context*/, const $Request$* /*request*/, "
+ "$Response$* /*response*/) final override {\n"
" abort();\n"
" return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n"
"}\n");
@@ -875,9 +855,9 @@
*vars,
"// disable synchronous version of this method\n"
"::grpc::Status $Method$("
- "::grpc::ServerContext* context, "
- "::grpc::ServerReader< $Request$>* reader, "
- "$Response$* response) final override {\n"
+ "::grpc::ServerContext* /*context*/, "
+ "::grpc::ServerReader< $Request$>* /*reader*/, "
+ "$Response$* /*response*/) final override {\n"
" abort();\n"
" return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n"
"}\n");
@@ -886,8 +866,8 @@
*vars,
"// disable synchronous version of this method\n"
"::grpc::Status $Method$("
- "::grpc::ServerContext* context, const $Request$* request, "
- "::grpc::ServerWriter< $Response$>* writer) final override "
+ "::grpc::ServerContext* /*context*/, const $Request$* /*request*/, "
+ "::grpc::ServerWriter< $Response$>* /*writer*/) final override "
"{\n"
" abort();\n"
" return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n"
@@ -897,8 +877,8 @@
*vars,
"// disable synchronous version of this method\n"
"::grpc::Status $Method$("
- "::grpc::ServerContext* context, "
- "::grpc::ServerReaderWriter< $Response$, $Request$>* stream) "
+ "::grpc::ServerContext* /*context*/, "
+ "::grpc::ServerReaderWriter< $Response$, $Request$>* /*stream*/) "
"final override {\n"
" abort();\n"
" return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n"
@@ -1001,9 +981,7 @@
printer->Print(*vars, "WithAsyncMethod_$method_name$<");
}
printer->Print("Service");
- for (int i = 0; i < service->method_count(); ++i) {
- printer->Print(" >");
- }
+ for (int i = 0; i < service->method_count(); ++i) { printer->Print(" >"); }
printer->Print(" AsyncService;\n");
// Server side - Generic
@@ -1028,9 +1006,7 @@
}
printer->Print("Service");
for (int i = 0; i < service->method_count(); ++i) {
- if (service->method(i)->NoStreaming()) {
- printer->Print(" >");
- }
+ if (service->method(i)->NoStreaming()) { printer->Print(" >"); }
}
printer->Print(" StreamedUnaryService;\n");
@@ -1052,9 +1028,7 @@
printer->Print("Service");
for (int i = 0; i < service->method_count(); ++i) {
auto method = service->method(i);
- if (ServerOnlyStreaming(method.get())) {
- printer->Print(" >");
- }
+ if (ServerOnlyStreaming(method.get())) { printer->Print(" >"); }
}
printer->Print(" SplitStreamedService;\n");
@@ -1095,9 +1069,7 @@
// Package string is empty or ends with a dot. It is used to fully qualify
// method names.
vars["Package"] = file->package();
- if (!file->package().empty()) {
- vars["Package"].append(".");
- }
+ if (!file->package().empty()) { vars["Package"].append("."); }
if (!params.services_namespace.empty()) {
vars["services_namespace"] = params.services_namespace;
@@ -1155,8 +1127,8 @@
vars["filename"] = file->filename();
vars["filename_base"] = file->filename_without_ext();
- vars["message_header_ext"] = message_header_ext();
- vars["service_header_ext"] = service_header_ext();
+ vars["message_header_ext"] = file->message_header_ext();
+ vars["service_header_ext"] = file->service_header_ext();
printer->Print(vars, "// Generated by the gRPC C++ plugin.\n");
printer->Print(vars,
@@ -1179,14 +1151,15 @@
std::map<grpc::string, grpc::string> vars;
static const char *headers_strs[] = {
- "grpc++/impl/codegen/async_stream.h",
- "grpc++/impl/codegen/async_unary_call.h",
- "grpc++/impl/codegen/channel_interface.h",
- "grpc++/impl/codegen/client_unary_call.h",
- "grpc++/impl/codegen/method_handler_impl.h",
- "grpc++/impl/codegen/rpc_service_method.h",
- "grpc++/impl/codegen/service_type.h",
- "grpc++/impl/codegen/sync_stream.h"};
+ "grpcpp/impl/codegen/async_stream.h",
+ "grpcpp/impl/codegen/async_unary_call.h",
+ "grpcpp/impl/codegen/channel_interface.h",
+ "grpcpp/impl/codegen/client_unary_call.h",
+ "grpcpp/impl/codegen/method_handler.h",
+ "grpcpp/impl/codegen/rpc_service_method.h",
+ "grpcpp/impl/codegen/service_type.h",
+ "grpcpp/impl/codegen/sync_stream.h"
+ };
std::vector<grpc::string> headers(headers_strs, array_end(headers_strs));
PrintIncludes(printer.get(), headers, params);
@@ -1215,8 +1188,8 @@
grpc::string start; // bool literal expressed as string
grpc::string method_params; // extra arguments to method
grpc::string create_args; // extra arguments to creator
- } async_prefixes[] = {{"Async", "true", ", void* tag", ", tag"},
- {"PrepareAsync", "false", "", ", nullptr"}};
+ } async_prefixes[] = { { "Async", "true", ", void* tag", ", tag" },
+ { "PrepareAsync", "false", "", ", nullptr" } };
if (method->NoStreaming()) {
printer->Print(*vars,
"::grpc::Status $ns$$Service$::Stub::$Method$("
@@ -1226,8 +1199,9 @@
" return ::grpc::internal::BlockingUnaryCall"
"(channel_.get(), rpcmethod_$Method$_, "
"context, request, response);\n}\n\n");
- for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
- auto& async_prefix = async_prefixes[i];
+ for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
+ i++) {
+ auto &async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncStart"] = async_prefix.start;
printer->Print(*vars,
@@ -1257,8 +1231,9 @@
"rpcmethod_$Method$_, "
"context, response);\n"
"}\n\n");
- for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
- auto& async_prefix = async_prefixes[i];
+ for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
+ i++) {
+ auto &async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncStart"] = async_prefix.start;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
@@ -1289,8 +1264,9 @@
"rpcmethod_$Method$_, "
"context, request);\n"
"}\n\n");
- for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
- auto& async_prefix = async_prefixes[i];
+ for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
+ i++) {
+ auto &async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncStart"] = async_prefix.start;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
@@ -1321,8 +1297,9 @@
"rpcmethod_$Method$_, "
"context);\n"
"}\n\n");
- for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
- auto& async_prefix = async_prefixes[i];
+ for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
+ i++) {
+ auto &async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncStart"] = async_prefix.start;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
@@ -1351,13 +1328,11 @@
(*vars)["Request"] = method->input_type_name();
(*vars)["Response"] = method->output_type_name();
if (method->NoStreaming()) {
- printer->Print(*vars,
- "::grpc::Status $ns$$Service$::Service::$Method$("
- "::grpc::ServerContext* context, "
- "const $Request$* request, $Response$* response) {\n");
- printer->Print(" (void) context;\n");
- printer->Print(" (void) request;\n");
- printer->Print(" (void) response;\n");
+ printer->Print(
+ *vars,
+ "::grpc::Status $ns$$Service$::Service::$Method$("
+ "::grpc::ServerContext* /*context*/, "
+ "const $Request$* /*request*/, $Response$* /*response*/) {\n");
printer->Print(
" return ::grpc::Status("
"::grpc::StatusCode::UNIMPLEMENTED, \"\");\n");
@@ -1365,12 +1340,9 @@
} else if (ClientOnlyStreaming(method)) {
printer->Print(*vars,
"::grpc::Status $ns$$Service$::Service::$Method$("
- "::grpc::ServerContext* context, "
- "::grpc::ServerReader< $Request$>* reader, "
- "$Response$* response) {\n");
- printer->Print(" (void) context;\n");
- printer->Print(" (void) reader;\n");
- printer->Print(" (void) response;\n");
+ "::grpc::ServerContext* /*context*/, "
+ "::grpc::ServerReader< $Request$>* /*reader*/, "
+ "$Response$* /*response*/) {\n");
printer->Print(
" return ::grpc::Status("
"::grpc::StatusCode::UNIMPLEMENTED, \"\");\n");
@@ -1378,12 +1350,9 @@
} else if (ServerOnlyStreaming(method)) {
printer->Print(*vars,
"::grpc::Status $ns$$Service$::Service::$Method$("
- "::grpc::ServerContext* context, "
- "const $Request$* request, "
- "::grpc::ServerWriter< $Response$>* writer) {\n");
- printer->Print(" (void) context;\n");
- printer->Print(" (void) request;\n");
- printer->Print(" (void) writer;\n");
+ "::grpc::ServerContext* /*context*/, "
+ "const $Request$* /*request*/, "
+ "::grpc::ServerWriter< $Response$>* /*writer*/) {\n");
printer->Print(
" return ::grpc::Status("
"::grpc::StatusCode::UNIMPLEMENTED, \"\");\n");
@@ -1391,11 +1360,9 @@
} else if (method->BidiStreaming()) {
printer->Print(*vars,
"::grpc::Status $ns$$Service$::Service::$Method$("
- "::grpc::ServerContext* context, "
+ "::grpc::ServerContext* /*context*/, "
"::grpc::ServerReaderWriter< $Response$, $Request$>* "
- "stream) {\n");
- printer->Print(" (void) context;\n");
- printer->Print(" (void) stream;\n");
+ "/*stream*/) {\n");
printer->Print(
" return ::grpc::Status("
"::grpc::StatusCode::UNIMPLEMENTED, \"\");\n");
@@ -1421,7 +1388,7 @@
printer->Print(*vars,
"std::unique_ptr< $ns$$Service$::Stub> $ns$$Service$::NewStub("
"const std::shared_ptr< ::grpc::ChannelInterface>& channel, "
- "const ::grpc::StubOptions& options) {\n"
+ "const ::grpc::StubOptions& /*options*/) {\n"
" std::unique_ptr< $ns$$Service$::Stub> stub(new "
"$ns$$Service$::Stub(channel));\n"
" return stub;\n"
@@ -1530,9 +1497,7 @@
// Package string is empty or ends with a dot. It is used to fully qualify
// method names.
vars["Package"] = file->package();
- if (!file->package().empty()) {
- vars["Package"].append(".");
- }
+ if (!file->package().empty()) { vars["Package"].append("."); }
if (!params.services_namespace.empty()) {
vars["ns"] = params.services_namespace + "::";
vars["prefix"] = params.services_namespace;
@@ -1604,9 +1569,9 @@
std::map<grpc::string, grpc::string> vars;
static const char *headers_strs[] = {
- "grpc++/impl/codegen/async_stream.h",
- "grpc++/impl/codegen/sync_stream.h",
- "gmock/gmock.h",
+ "grpcpp/impl/codegen/async_stream.h",
+ "grpcpp/impl/codegen/sync_stream.h",
+ "gmock/gmock.h",
};
std::vector<grpc::string> headers(headers_strs, array_end(headers_strs));
PrintIncludes(printer.get(), headers, params);
@@ -1636,15 +1601,17 @@
grpc::string prefix;
grpc::string method_params; // extra arguments to method
int extra_method_param_count;
- } async_prefixes[] = {{"Async", ", void* tag", 1}, {"PrepareAsync", "", 0}};
+ } async_prefixes[] = { { "Async", ", void* tag", 1 },
+ { "PrepareAsync", "", 0 } };
if (method->NoStreaming()) {
printer->Print(
*vars,
"MOCK_METHOD3($Method$, ::grpc::Status(::grpc::ClientContext* context, "
"const $Request$& request, $Response$* response));\n");
- for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
- auto& async_prefix = async_prefixes[i];
+ for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
+ i++) {
+ auto &async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
printer->Print(
*vars,
@@ -1659,12 +1626,13 @@
"MOCK_METHOD2($Method$Raw, "
"::grpc::ClientWriterInterface< $Request$>*"
"(::grpc::ClientContext* context, $Response$* response));\n");
- for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
- auto& async_prefix = async_prefixes[i];
+ for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
+ i++) {
+ auto &async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
(*vars)["MockArgs"] =
- flatbuffers::NumToString(3 + async_prefix.extra_method_param_count);
+ flatbuffers::NumToString(3 + async_prefix.extra_method_param_count);
printer->Print(*vars,
"MOCK_METHOD$MockArgs$($AsyncPrefix$$Method$Raw, "
"::grpc::ClientAsyncWriterInterface< $Request$>*"
@@ -1677,8 +1645,9 @@
"MOCK_METHOD2($Method$Raw, "
"::grpc::ClientReaderInterface< $Response$>*"
"(::grpc::ClientContext* context, const $Request$& request));\n");
- for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
- auto& async_prefix = async_prefixes[i];
+ for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
+ i++) {
+ auto &async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
(*vars)["MockArgs"] =
@@ -1696,8 +1665,9 @@
"MOCK_METHOD1($Method$Raw, "
"::grpc::ClientReaderWriterInterface< $Request$, $Response$>*"
"(::grpc::ClientContext* context));\n");
- for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
- auto& async_prefix = async_prefixes[i];
+ for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
+ i++) {
+ auto &async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
(*vars)["MockArgs"] =
@@ -1738,9 +1708,7 @@
// Package string is empty or ends with a dot. It is used to fully qualify
// method names.
vars["Package"] = file->package();
- if (!file->package().empty()) {
- vars["Package"].append(".");
- }
+ if (!file->package().empty()) { vars["Package"].append("."); }
if (!params.services_namespace.empty()) {
vars["services_namespace"] = params.services_namespace;
diff --git a/grpc/src/compiler/cpp_generator.h b/grpc/src/compiler/cpp_generator.h
index 6119ebe..16aa97a 100644
--- a/grpc/src/compiler/cpp_generator.h
+++ b/grpc/src/compiler/cpp_generator.h
@@ -1,36 +1,3 @@
-/*
- *
- * Copyright 2015, Google Inc.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
#ifndef GRPC_INTERNAL_COMPILER_CPP_GENERATOR_H
#define GRPC_INTERNAL_COMPILER_CPP_GENERATOR_H
@@ -41,12 +8,11 @@
#include <memory>
#include <vector>
-#include "src/compiler/config.h"
#include "src/compiler/schema_interface.h"
#ifndef GRPC_CUSTOM_STRING
-#include <string>
-#define GRPC_CUSTOM_STRING std::string
+# include <string>
+# define GRPC_CUSTOM_STRING std::string
#endif
namespace grpc {
diff --git a/grpc/src/compiler/go_generator.cc b/grpc/src/compiler/go_generator.cc
index 604828d..9ba2e65 100644
--- a/grpc/src/compiler/go_generator.cc
+++ b/grpc/src/compiler/go_generator.cc
@@ -1,47 +1,13 @@
-/*
- *
- * Copyright 2015, Google Inc.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation AN/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#include <map>
-#include <cctype>
-#include <sstream>
-
#include "src/compiler/go_generator.h"
-template <class T>
-grpc::string as_string(T x) {
- std::ostringstream out;
- out << x;
- return out.str();
+#include <cctype>
+#include <map>
+#include <sstream>
+
+template<class T> grpc::string as_string(T x) {
+ std::ostringstream out;
+ out << x;
+ return out.str();
}
inline bool ClientOnlyStreaming(const grpc_generator::Method *method) {
@@ -56,391 +22,484 @@
// Returns string with first letter to lowerCase
grpc::string unexportName(grpc::string s) {
- if (s.empty())
- return s;
- s[0] = static_cast<char>(std::tolower(s[0]));
- return s;
+ if (s.empty()) return s;
+ s[0] = static_cast<char>(std::tolower(s[0]));
+ return s;
}
// Returns string with first letter to uppercase
grpc::string exportName(grpc::string s) {
- if (s.empty())
- return s;
- s[0] = static_cast<char>(std::toupper(s[0]));
- return s;
+ if (s.empty()) return s;
+ s[0] = static_cast<char>(std::toupper(s[0]));
+ return s;
+}
+
+void GenerateError(grpc_generator::Printer *printer,
+ std::map<grpc::string, grpc::string> vars,
+ const bool multiple_return = true) {
+ printer->Print(vars, "if $Error_Check$ {\n");
+ printer->Indent();
+ vars["Return"] = multiple_return ? "nil, err" : "err";
+ printer->Print(vars, "return $Return$\n");
+ printer->Outdent();
+ printer->Print("}\n");
}
// Generates imports for the service
-void GenerateImports(grpc_generator::File *file, grpc_generator::Printer *printer,
+void GenerateImports(grpc_generator::File *file,
+ grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> vars) {
- vars["filename"] = file->filename();
- printer->Print("//Generated by gRPC Go plugin\n");
- printer->Print("//If you make any local changes, they will be lost\n");
- printer->Print(vars, "//source: $filename$\n\n");
- printer->Print(vars, "package $Package$\n\n");
- if (file->additional_headers() != "") {
- printer->Print(file->additional_headers().c_str());
- printer->Print("\n\n");
- }
- printer->Print("import (\n");
- printer->Indent();
- printer->Print(vars, "$context$ \"context\"\n");
- printer->Print(vars, "$grpc$ \"google.golang.org/grpc\"\n");
- printer->Outdent();
- printer->Print(")\n\n");
+ vars["filename"] = file->filename();
+ printer->Print("//Generated by gRPC Go plugin\n");
+ printer->Print("//If you make any local changes, they will be lost\n");
+ printer->Print(vars, "//source: $filename$\n\n");
+ printer->Print(vars, "package $Package$\n\n");
+ printer->Print("import (\n");
+ printer->Indent();
+ printer->Print(vars, "$context$ \"context\"\n");
+ printer->Print("flatbuffers \"github.com/google/flatbuffers/go\"\n");
+ printer->Print(vars, "$grpc$ \"google.golang.org/grpc\"\n");
+ printer->Print("\"google.golang.org/grpc/codes\"\n");
+ printer->Print("\"google.golang.org/grpc/status\"\n");
+ printer->Outdent();
+ printer->Print(")\n\n");
}
// Generates Server method signature source
-void GenerateServerMethodSignature(const grpc_generator::Method *method, grpc_generator::Printer *printer,
+void GenerateServerMethodSignature(const grpc_generator::Method *method,
+ grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> vars) {
- vars["Method"] = exportName(method->name());
- vars["Request"] = method->get_input_type_name();
- vars["Response"] = (vars["CustomMethodIO"] == "") ? method->get_output_type_name() : vars["CustomMethodIO"];
- if (method->NoStreaming()) {
- printer->Print(vars, "$Method$($context$.Context, *$Request$) (*$Response$, error)");
- } else if (ServerOnlyStreaming(method)) {
- printer->Print(vars, "$Method$(*$Request$, $Service$_$Method$Server) error");
- } else {
- printer->Print(vars, "$Method$($Service$_$Method$Server) error");
- }
+ vars["Method"] = exportName(method->name());
+ vars["Request"] = method->get_input_type_name();
+ vars["Response"] = (vars["CustomMethodIO"] == "")
+ ? method->get_output_type_name()
+ : vars["CustomMethodIO"];
+ if (method->NoStreaming()) {
+ printer->Print(
+ vars,
+ "$Method$($context$.Context, *$Request$) (*$Response$, error)$Ending$");
+ } else if (ServerOnlyStreaming(method)) {
+ printer->Print(
+ vars, "$Method$(*$Request$, $Service$_$Method$Server) error$Ending$");
+ } else {
+ printer->Print(vars, "$Method$($Service$_$Method$Server) error$Ending$");
+ }
}
-void GenerateServerMethod(const grpc_generator::Method *method, grpc_generator::Printer *printer,
+void GenerateServerMethod(const grpc_generator::Method *method,
+ grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> vars) {
- vars["Method"] = exportName(method->name());
- vars["Request"] = method->get_input_type_name();
- vars["Response"] = (vars["CustomMethodIO"] == "") ? method->get_output_type_name() : vars["CustomMethodIO"];
- vars["FullMethodName"] = "/" + vars["ServicePrefix"] + "." + vars["Service"] + "/" + vars["Method"];
- vars["Handler"] = "_" + vars["Service"] + "_" + vars["Method"] + "_Handler";
- if (method->NoStreaming()) {
- printer->Print(vars, "func $Handler$(srv interface{}, ctx $context$.Context,\n\tdec func(interface{}) error, interceptor $grpc$.UnaryServerInterceptor) (interface{}, error) {\n");
- printer->Indent();
- printer->Print(vars, "in := new($Request$)\n");
- printer->Print("if err := dec(in); err != nil { return nil, err }\n");
- printer->Print(vars, "if interceptor == nil { return srv.($Service$Server).$Method$(ctx, in) }\n");
- printer->Print(vars, "info := &$grpc$.UnaryServerInfo{\n");
- printer->Indent();
- printer->Print("Server: srv,\n");
- printer->Print(vars, "FullMethod: \"$FullMethodName$\",\n");
- printer->Outdent();
- printer->Print("}\n\n");
- printer->Print(vars, "handler := func(ctx $context$.Context, req interface{}) (interface{}, error) {\n");
- printer->Indent();
- printer->Print(vars, "return srv.($Service$Server).$Method$(ctx, req.(* $Request$))\n");
- printer->Outdent();
- printer->Print("}\n");
- printer->Print("return interceptor(ctx, in, info, handler)\n");
- printer->Outdent();
- printer->Print("}\n\n");
- return;
- }
- vars["StreamType"] = vars["ServiceUnexported"] + vars["Method"] + "Server";
- printer->Print(vars, "func $Handler$(srv interface{}, stream $grpc$.ServerStream) error {\n");
- printer->Indent();
- if (ServerOnlyStreaming(method)) {
- printer->Print(vars, "m := new($Request$)\n");
- printer->Print(vars, "if err := stream.RecvMsg(m); err != nil { return err }\n");
- printer->Print(vars, "return srv.($Service$Server).$Method$(m, &$StreamType${stream})\n");
- } else {
- printer->Print(vars, "return srv.($Service$Server).$Method$(&$StreamType${stream})\n");
- }
- printer->Outdent();
- printer->Print("}\n\n");
+ vars["Method"] = exportName(method->name());
+ vars["Request"] = method->get_input_type_name();
+ vars["Response"] = (vars["CustomMethodIO"] == "")
+ ? method->get_output_type_name()
+ : vars["CustomMethodIO"];
+ vars["FullMethodName"] =
+ "/" + vars["ServicePrefix"] + vars["Service"] + "/" + vars["Method"];
+ vars["Handler"] = "_" + vars["Service"] + "_" + vars["Method"] + "_Handler";
+ if (method->NoStreaming()) {
+ printer->Print(
+ vars,
+ "func $Handler$(srv interface{}, ctx $context$.Context,\n\tdec "
+ "func(interface{}) error, interceptor $grpc$.UnaryServerInterceptor) "
+ "(interface{}, error) {\n");
+ printer->Indent();
+ printer->Print(vars, "in := new($Request$)\n");
+ vars["Error_Check"] = "err := dec(in); err != nil";
+ GenerateError(printer, vars);
+ printer->Print("if interceptor == nil {\n");
+ printer->Indent();
+ printer->Print(vars, "return srv.($Service$Server).$Method$(ctx, in)\n");
+ printer->Outdent();
+ printer->Print("}\n");
+ printer->Print(vars, "info := &$grpc$.UnaryServerInfo{\n");
+ printer->Indent();
+ printer->Print("Server: srv,\n");
+ printer->Print(vars, "FullMethod: \"$FullMethodName$\",\n");
+ printer->Outdent();
+ printer->Print("}\n");
+ printer->Outdent();
+ printer->Print("\n");
+ printer->Indent();
+ printer->Print(vars,
+ "handler := func(ctx $context$.Context, req interface{}) "
+ "(interface{}, error) {\n");
+ printer->Indent();
+ printer->Print(
+ vars, "return srv.($Service$Server).$Method$(ctx, req.(*$Request$))\n");
+ printer->Outdent();
+ printer->Print("}\n");
+ printer->Print("return interceptor(ctx, in, info, handler)\n");
+ printer->Outdent();
+ printer->Print("}\n");
+ return;
+ }
+ vars["StreamType"] = vars["ServiceUnexported"] + vars["Method"] + "Server";
+ printer->Print(
+ vars,
+ "func $Handler$(srv interface{}, stream $grpc$.ServerStream) error {\n");
+ printer->Indent();
+ if (ServerOnlyStreaming(method)) {
+ printer->Print(vars, "m := new($Request$)\n");
+ vars["Error_Check"] = "err := stream.RecvMsg(m); err != nil";
+ GenerateError(printer, vars, false);
+ printer->Print(
+ vars,
+ "return srv.($Service$Server).$Method$(m, &$StreamType${stream})\n");
+ } else {
+ printer->Print(
+ vars, "return srv.($Service$Server).$Method$(&$StreamType${stream})\n");
+ }
+ printer->Outdent();
+ printer->Print("}\n\n");
- bool genSend = method->BidiStreaming() || ServerOnlyStreaming(method);
- bool genRecv = method->BidiStreaming() || ClientOnlyStreaming(method);
- bool genSendAndClose = ClientOnlyStreaming(method);
+ bool genSend = method->BidiStreaming() || ServerOnlyStreaming(method);
+ bool genRecv = method->BidiStreaming() || ClientOnlyStreaming(method);
+ bool genSendAndClose = ClientOnlyStreaming(method);
- printer->Print(vars, "type $Service$_$Method$Server interface { \n");
- printer->Indent();
- if (genSend) {
- printer->Print(vars, "Send(* $Response$) error\n");
- }
- if (genRecv) {
- printer->Print(vars, "Recv() (* $Request$, error)\n");
- }
- if (genSendAndClose) {
- printer->Print(vars, "SendAndClose(* $Response$) error\n");
- }
- printer->Print(vars, "$grpc$.ServerStream\n");
- printer->Outdent();
- printer->Print("}\n\n");
+ printer->Print(vars, "type $Service$_$Method$Server interface {\n");
+ printer->Indent();
+ if (genSend) { printer->Print(vars, "Send(*$Response$) error\n"); }
+ if (genRecv) { printer->Print(vars, "Recv() (*$Request$, error)\n"); }
+ if (genSendAndClose) {
+ printer->Print(vars, "SendAndClose(*$Response$) error\n");
+ }
+ printer->Print(vars, "$grpc$.ServerStream\n");
+ printer->Outdent();
+ printer->Print("}\n\n");
- printer->Print(vars, "type $StreamType$ struct {\n");
- printer->Indent();
- printer->Print(vars, "$grpc$.ServerStream\n");
- printer->Outdent();
- printer->Print("}\n\n");
+ printer->Print(vars, "type $StreamType$ struct {\n");
+ printer->Indent();
+ printer->Print(vars, "$grpc$.ServerStream\n");
+ printer->Outdent();
+ printer->Print("}\n\n");
- if (genSend) {
- printer->Print(vars, "func (x *$StreamType$) Send(m *$Response$) error {\n");
- printer->Indent();
- printer->Print("return x.ServerStream.SendMsg(m)\n");
- printer->Outdent();
- printer->Print("}\n\n");
- }
- if (genRecv) {
- printer->Print(vars, "func (x *$StreamType$) Recv() (*$Request$, error) {\n");
- printer->Indent();
- printer->Print(vars, "m := new($Request$)\n");
- printer->Print("if err := x.ServerStream.RecvMsg(m); err != nil { return nil, err }\n");
- printer->Print("return m, nil\n");
- printer->Outdent();
- printer->Print("}\n\n");
- }
- if (genSendAndClose) {
- printer->Print(vars, "func (x *$StreamType$) SendAndClose(m *$Response$) error {\n");
- printer->Indent();
- printer->Print("return x.ServerStream.SendMsg(m)\n");
- printer->Outdent();
- printer->Print("}\n\n");
- }
-
+ if (genSend) {
+ printer->Print(vars,
+ "func (x *$StreamType$) Send(m *$Response$) error {\n");
+ printer->Indent();
+ printer->Print("return x.ServerStream.SendMsg(m)\n");
+ printer->Outdent();
+ printer->Print("}\n\n");
+ }
+ if (genRecv) {
+ printer->Print(vars,
+ "func (x *$StreamType$) Recv() (*$Request$, error) {\n");
+ printer->Indent();
+ printer->Print(vars, "m := new($Request$)\n");
+ vars["Error_Check"] = "err := x.ServerStream.RecvMsg(m); err != nil";
+ GenerateError(printer, vars);
+ printer->Print("return m, nil\n");
+ printer->Outdent();
+ printer->Print("}\n\n");
+ }
+ if (genSendAndClose) {
+ printer->Print(
+ vars, "func (x *$StreamType$) SendAndClose(m *$Response$) error {\n");
+ printer->Indent();
+ printer->Print("return x.ServerStream.SendMsg(m)\n");
+ printer->Outdent();
+ printer->Print("}\n\n");
+ }
}
// Generates Client method signature source
-void GenerateClientMethodSignature(const grpc_generator::Method *method, grpc_generator::Printer *printer,
+void GenerateClientMethodSignature(const grpc_generator::Method *method,
+ grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> vars) {
- vars["Method"] = exportName(method->name());
- vars["Request"] = ", in *" + ((vars["CustomMethodIO"] == "") ? method->get_input_type_name() : vars["CustomMethodIO"]);
- if (ClientOnlyStreaming(method) || method->BidiStreaming()) {
- vars["Request"] = "";
- }
- vars["Response"] = "* " + method->get_output_type_name();
- if (ClientOnlyStreaming(method) || method->BidiStreaming() || ServerOnlyStreaming(method)) {
- vars["Response"] = vars["Service"] + "_" + vars["Method"] + "Client" ;
- }
- printer->Print(vars, "$Method$(ctx $context$.Context$Request$, \n\topts... $grpc$.CallOption) ($Response$, error)");
+ vars["Method"] = exportName(method->name());
+ vars["Request"] =
+ ", in *" + ((vars["CustomMethodIO"] == "") ? method->get_input_type_name()
+ : vars["CustomMethodIO"]);
+ if (ClientOnlyStreaming(method) || method->BidiStreaming()) {
+ vars["Request"] = "";
+ }
+ vars["Response"] = "*" + method->get_output_type_name();
+ if (ClientOnlyStreaming(method) || method->BidiStreaming() ||
+ ServerOnlyStreaming(method)) {
+ vars["Response"] = vars["Service"] + "_" + vars["Method"] + "Client";
+ }
+ printer->Print(vars,
+ "$Method$(ctx $context$.Context$Request$,\n\topts "
+ "...$grpc$.CallOption) ($Response$, error)$Ending$");
}
// Generates Client method source
-void GenerateClientMethod(const grpc_generator::Method *method, grpc_generator::Printer *printer,
+void GenerateClientMethod(const grpc_generator::Method *method,
+ grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> vars) {
- printer->Print(vars, "func (c *$ServiceUnexported$Client) ");
- GenerateClientMethodSignature(method, printer, vars);
- printer->Print(" {\n");
- printer->Indent();
- vars["Method"] = exportName(method->name());
- vars["Request"] = (vars["CustomMethodIO"] == "") ? method->get_input_type_name() : vars["CustomMethodIO"];
- vars["Response"] = method->get_output_type_name();
- vars["FullMethodName"] = "/" + vars["ServicePrefix"] + "." + vars["Service"] + "/" + vars["Method"];
- if (method->NoStreaming()) {
- printer->Print(vars, "out := new($Response$)\n");
- printer->Print(vars, "err := $grpc$.Invoke(ctx, \"$FullMethodName$\", in, out, c.cc, opts...)\n");
- printer->Print("if err != nil { return nil, err }\n");
- printer->Print("return out, nil\n");
- printer->Outdent();
- printer->Print("}\n\n");
- return;
- }
- vars["StreamType"] = vars["ServiceUnexported"] + vars["Method"] + "Client";
- printer->Print(vars, "stream, err := $grpc$.NewClientStream(ctx, &$MethodDesc$, c.cc, \"$FullMethodName$\", opts...)\n");
- printer->Print("if err != nil { return nil, err }\n");
+ printer->Print(vars, "func (c *$ServiceUnexported$Client) ");
+ vars["Ending"] = " {\n";
+ GenerateClientMethodSignature(method, printer, vars);
+ printer->Indent();
+ vars["Method"] = exportName(method->name());
+ vars["Request"] = (vars["CustomMethodIO"] == "")
+ ? method->get_input_type_name()
+ : vars["CustomMethodIO"];
+ vars["Response"] = method->get_output_type_name();
+ vars["FullMethodName"] =
+ "/" + vars["ServicePrefix"] + vars["Service"] + "/" + vars["Method"];
+ if (method->NoStreaming()) {
+ printer->Print(vars, "out := new($Response$)\n");
+ printer->Print(
+ vars,
+ "err := c.cc.Invoke(ctx, \"$FullMethodName$\", in, out, opts...)\n");
+ vars["Error_Check"] = "err != nil";
+ GenerateError(printer, vars);
+ printer->Print("return out, nil\n");
+ printer->Outdent();
+ printer->Print("}\n\n");
+ return;
+ }
+ vars["StreamType"] = vars["ServiceUnexported"] + vars["Method"] + "Client";
+ printer->Print(vars,
+ "stream, err := c.cc.NewStream(ctx, &$MethodDesc$, "
+ "\"$FullMethodName$\", opts...)\n");
+ vars["Error_Check"] = "err != nil";
+ GenerateError(printer, vars);
- printer->Print(vars, "x := &$StreamType${stream}\n");
- if (ServerOnlyStreaming(method)) {
- printer->Print("if err := x.ClientStream.SendMsg(in); err != nil { return nil, err }\n");
- printer->Print("if err := x.ClientStream.CloseSend(); err != nil { return nil, err }\n");
- }
- printer->Print("return x,nil\n");
- printer->Outdent();
- printer->Print("}\n\n");
+ printer->Print(vars, "x := &$StreamType${stream}\n");
+ if (ServerOnlyStreaming(method)) {
+ vars["Error_Check"] = "err := x.ClientStream.SendMsg(in); err != nil";
+ GenerateError(printer, vars);
+ vars["Error_Check"] = "err := x.ClientStream.CloseSend(); err != nil";
+ GenerateError(printer, vars);
+ }
+ printer->Print("return x, nil\n");
+ printer->Outdent();
+ printer->Print("}\n\n");
- bool genSend = method->BidiStreaming() || ClientOnlyStreaming(method);
- bool genRecv = method->BidiStreaming() || ServerOnlyStreaming(method);
- bool genCloseAndRecv = ClientOnlyStreaming(method);
+ bool genSend = method->BidiStreaming() || ClientOnlyStreaming(method);
+ bool genRecv = method->BidiStreaming() || ServerOnlyStreaming(method);
+ bool genCloseAndRecv = ClientOnlyStreaming(method);
- //Stream interface
- printer->Print(vars, "type $Service$_$Method$Client interface {\n");
- printer->Indent();
- if (genSend) {
- printer->Print(vars, "Send(*$Request$) error\n");
- }
- if (genRecv) {
- printer->Print(vars, "Recv() (*$Response$, error)\n");
- }
- if (genCloseAndRecv) {
- printer->Print(vars, "CloseAndRecv() (*$Response$, error)\n");
- }
- printer->Print(vars, "$grpc$.ClientStream\n");
- printer->Outdent();
- printer->Print("}\n\n");
+ // Stream interface
+ printer->Print(vars, "type $Service$_$Method$Client interface {\n");
+ printer->Indent();
+ if (genSend) { printer->Print(vars, "Send(*$Request$) error\n"); }
+ if (genRecv) { printer->Print(vars, "Recv() (*$Response$, error)\n"); }
+ if (genCloseAndRecv) {
+ printer->Print(vars, "CloseAndRecv() (*$Response$, error)\n");
+ }
+ printer->Print(vars, "$grpc$.ClientStream\n");
+ printer->Outdent();
+ printer->Print("}\n\n");
- //Stream Client
- printer->Print(vars, "type $StreamType$ struct{\n");
- printer->Indent();
- printer->Print(vars, "$grpc$.ClientStream\n");
- printer->Outdent();
- printer->Print("}\n\n");
+ // Stream Client
+ printer->Print(vars, "type $StreamType$ struct {\n");
+ printer->Indent();
+ printer->Print(vars, "$grpc$.ClientStream\n");
+ printer->Outdent();
+ printer->Print("}\n\n");
- if (genSend) {
- printer->Print(vars, "func (x *$StreamType$) Send(m *$Request$) error {\n");
- printer->Indent();
- printer->Print("return x.ClientStream.SendMsg(m)\n");
- printer->Outdent();
- printer->Print("}\n\n");
- }
+ if (genSend) {
+ printer->Print(vars, "func (x *$StreamType$) Send(m *$Request$) error {\n");
+ printer->Indent();
+ printer->Print("return x.ClientStream.SendMsg(m)\n");
+ printer->Outdent();
+ printer->Print("}\n\n");
+ }
- if (genRecv) {
- printer->Print(vars, "func (x *$StreamType$) Recv() (*$Response$, error) {\n");
- printer->Indent();
- printer->Print(vars, "m := new($Response$)\n");
- printer->Print("if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err }\n");
- printer->Print("return m, nil\n");
- printer->Outdent();
- printer->Print("}\n\n");
- }
+ if (genRecv) {
+ printer->Print(vars,
+ "func (x *$StreamType$) Recv() (*$Response$, error) {\n");
+ printer->Indent();
+ printer->Print(vars, "m := new($Response$)\n");
+ vars["Error_Check"] = "err := x.ClientStream.RecvMsg(m); err != nil";
+ GenerateError(printer, vars);
+ printer->Print("return m, nil\n");
+ printer->Outdent();
+ printer->Print("}\n\n");
+ }
- if (genCloseAndRecv) {
- printer->Print(vars, "func (x *$StreamType$) CloseAndRecv() (*$Response$, error) {\n");
- printer->Indent();
- printer->Print("if err := x.ClientStream.CloseSend(); err != nil { return nil, err }\n");
- printer->Print(vars, "m := new ($Response$)\n");
- printer->Print("if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err }\n");
- printer->Print("return m, nil\n");
- printer->Outdent();
- printer->Print("}\n\n");
- }
+ if (genCloseAndRecv) {
+ printer->Print(
+ vars, "func (x *$StreamType$) CloseAndRecv() (*$Response$, error) {\n");
+ printer->Indent();
+ vars["Error_Check"] = "err := x.ClientStream.CloseSend(); err != nil";
+ GenerateError(printer, vars);
+ printer->Print(vars, "m := new($Response$)\n");
+ vars["Error_Check"] = "err := x.ClientStream.RecvMsg(m); err != nil";
+ GenerateError(printer, vars);
+ printer->Print("return m, nil\n");
+ printer->Outdent();
+ printer->Print("}\n\n");
+ }
}
// Generates client API for the service
-void GenerateService(const grpc_generator::Service *service, grpc_generator::Printer* printer,
+void GenerateService(const grpc_generator::Service *service,
+ grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> vars) {
- vars["Service"] = exportName(service->name());
- // Client Interface
- printer->Print(vars, "// Client API for $Service$ service\n");
- printer->Print(vars, "type $Service$Client interface{\n");
- printer->Indent();
- for (int i = 0; i < service->method_count(); i++) {
- GenerateClientMethodSignature(service->method(i).get(), printer, vars);
- printer->Print("\n");
- }
- printer->Outdent();
- printer->Print("}\n\n");
+ vars["Service"] = exportName(service->name());
+ // Client Interface
+ printer->Print(vars, "// Client API for $Service$ service\n");
+ printer->Print(vars, "type $Service$Client interface {\n");
+ printer->Indent();
+ vars["Ending"] = "\n";
+ for (int i = 0; i < service->method_count(); i++) {
+ GenerateClientMethodSignature(service->method(i).get(), printer, vars);
+ }
+ printer->Outdent();
+ printer->Print("}\n\n");
- // Client structure
- vars["ServiceUnexported"] = unexportName(vars["Service"]);
- printer->Print(vars, "type $ServiceUnexported$Client struct {\n");
- printer->Indent();
- printer->Print(vars, "cc *$grpc$.ClientConn\n");
- printer->Outdent();
- printer->Print("}\n\n");
+ // Client structure
+ vars["ServiceUnexported"] = unexportName(vars["Service"]);
+ printer->Print(vars, "type $ServiceUnexported$Client struct {\n");
+ printer->Indent();
+ printer->Print(vars, "cc $grpc$.ClientConnInterface\n");
+ printer->Outdent();
+ printer->Print("}\n\n");
- // NewClient
- printer->Print(vars, "func New$Service$Client(cc *$grpc$.ClientConn) $Service$Client {\n");
- printer->Indent();
- printer->Print(vars, "return &$ServiceUnexported$Client{cc}");
- printer->Outdent();
- printer->Print("\n}\n\n");
+ // NewClient
+ printer->Print(vars,
+ "func New$Service$Client(cc $grpc$.ClientConnInterface) "
+ "$Service$Client {\n");
+ printer->Indent();
+ printer->Print(vars, "return &$ServiceUnexported$Client{cc}");
+ printer->Outdent();
+ printer->Print("\n}\n\n");
- int unary_methods = 0, streaming_methods = 0;
- vars["ServiceDesc"] = "_" + vars["Service"] + "_serviceDesc";
- for (int i = 0; i < service->method_count(); i++) {
- auto method = service->method(i);
- if (method->NoStreaming()) {
- vars["MethodDesc"] = vars["ServiceDesc"] + ".Method[" + as_string(unary_methods) + "]";
- unary_methods++;
- } else {
- vars["MethodDesc"] = vars["ServiceDesc"] + ".Streams[" + as_string(streaming_methods) + "]";
- streaming_methods++;
- }
- GenerateClientMethod(method.get(), printer, vars);
- }
+ int unary_methods = 0, streaming_methods = 0;
+ vars["ServiceDesc"] = "_" + vars["Service"] + "_serviceDesc";
+ for (int i = 0; i < service->method_count(); i++) {
+ auto method = service->method(i);
+ if (method->NoStreaming()) {
+ vars["MethodDesc"] =
+ vars["ServiceDesc"] + ".Method[" + as_string(unary_methods) + "]";
+ unary_methods++;
+ } else {
+ vars["MethodDesc"] = vars["ServiceDesc"] + ".Streams[" +
+ as_string(streaming_methods) + "]";
+ streaming_methods++;
+ }
+ GenerateClientMethod(method.get(), printer, vars);
+ }
- //Server Interface
- printer->Print(vars, "// Server API for $Service$ service\n");
- printer->Print(vars, "type $Service$Server interface {\n");
- printer->Indent();
- for (int i = 0; i < service->method_count(); i++) {
- GenerateServerMethodSignature(service->method(i).get(), printer, vars);
- printer->Print("\n");
- }
- printer->Outdent();
- printer->Print("}\n\n");
+ // Server Interface
+ printer->Print(vars, "// Server API for $Service$ service\n");
+ printer->Print(vars, "type $Service$Server interface {\n");
+ printer->Indent();
+ vars["Ending"] = "\n";
+ for (int i = 0; i < service->method_count(); i++) {
+ GenerateServerMethodSignature(service->method(i).get(), printer, vars);
+ }
+ printer->Print(vars, "mustEmbedUnimplemented$Service$Server()\n");
+ printer->Outdent();
+ printer->Print("}\n\n");
- // Server registration.
- printer->Print(vars, "func Register$Service$Server(s *$grpc$.Server, srv $Service$Server) {\n");
- printer->Indent();
- printer->Print(vars, "s.RegisterService(&$ServiceDesc$, srv)\n");
- printer->Outdent();
- printer->Print("}\n\n");
+ printer->Print(vars, "type Unimplemented$Service$Server struct {\n");
+ printer->Print("}\n\n");
- for (int i = 0; i < service->method_count(); i++) {
- GenerateServerMethod(service->method(i).get(), printer, vars);
- printer->Print("\n");
- }
+ vars["Ending"] = " {\n";
+ for (int i = 0; i < service->method_count(); i++) {
+ auto method = service->method(i);
+ vars["Method"] = exportName(method->name());
+ vars["Nil"] = method->NoStreaming() ? "nil, " : "";
+ printer->Print(vars, "func (Unimplemented$Service$Server) ");
+ GenerateServerMethodSignature(method.get(), printer, vars);
+ printer->Indent();
+ printer->Print(vars,
+ "return $Nil$status.Errorf(codes.Unimplemented, \"method "
+ "$Method$ not implemented\")\n");
+ printer->Outdent();
+ printer->Print("}\n");
+ printer->Print("\n");
+ }
+ printer->Print(vars,
+ "func (Unimplemented$Service$Server) "
+ "mustEmbedUnimplemented$Service$Server() {}");
+ printer->Print("\n\n");
- //Service Descriptor
- printer->Print(vars, "var $ServiceDesc$ = $grpc$.ServiceDesc{\n");
- printer->Indent();
- printer->Print(vars, "ServiceName: \"$ServicePrefix$.$Service$\",\n");
- printer->Print(vars, "HandlerType: (*$Service$Server)(nil),\n");
- printer->Print(vars, "Methods: []$grpc$.MethodDesc{\n");
- printer->Indent();
- for (int i = 0; i < service->method_count(); i++) {
- auto method = service->method(i);
- vars["Method"] = method->name();
- vars["Handler"] = "_" + vars["Service"] + "_" + vars["Method"] + "_Handler";
- if (method->NoStreaming()) {
- printer->Print("{\n");
- printer->Indent();
- printer->Print(vars, "MethodName: \"$Method$\",\n");
- printer->Print(vars, "Handler: $Handler$, \n");
- printer->Outdent();
- printer->Print("},\n");
- }
- }
- printer->Outdent();
- printer->Print("},\n");
- printer->Print(vars, "Streams: []$grpc$.StreamDesc{\n");
- printer->Indent();
- for (int i = 0; i < service->method_count(); i++) {
- auto method = service->method(i);
- vars["Method"] = method->name();
- vars["Handler"] = "_" + vars["Service"] + "_" + vars["Method"] + "_Handler";
- if (!method->NoStreaming()) {
- printer->Print("{\n");
- printer->Indent();
- printer->Print(vars, "StreamName: \"$Method$\",\n");
- printer->Print(vars, "Handler: $Handler$, \n");
- if (ClientOnlyStreaming(method.get())) {
- printer->Print("ClientStreams: true,\n");
- } else if (ServerOnlyStreaming(method.get())) {
- printer->Print("ServerStreams: true,\n");
- } else {
- printer->Print("ServerStreams: true,\n");
- printer->Print("ClientStreams: true,\n");
- }
- printer->Outdent();
- printer->Print("},\n");
- }
- }
- printer->Outdent();
- printer->Print("},\n");
- printer->Outdent();
- printer->Print("}\n\n");
+ printer->Print(vars, "type Unsafe$Service$Server interface {\n");
+ printer->Indent();
+ printer->Print(vars, "mustEmbedUnimplemented$Service$Server()\n");
+ printer->Outdent();
+ printer->Print("}\n\n");
+ // Server registration.
+ printer->Print(vars,
+ "func Register$Service$Server(s $grpc$.ServiceRegistrar, srv "
+ "$Service$Server) {\n");
+ printer->Indent();
+ printer->Print(vars, "s.RegisterService(&$ServiceDesc$, srv)\n");
+ printer->Outdent();
+ printer->Print("}\n\n");
+ for (int i = 0; i < service->method_count(); i++) {
+ GenerateServerMethod(service->method(i).get(), printer, vars);
+ }
+
+ // Service Descriptor
+ printer->Print(vars, "var $ServiceDesc$ = $grpc$.ServiceDesc{\n");
+ printer->Indent();
+ printer->Print(vars, "ServiceName: \"$ServicePrefix$$Service$\",\n");
+ printer->Print(vars, "HandlerType: (*$Service$Server)(nil),\n");
+ printer->Print(vars, "Methods: []$grpc$.MethodDesc{\n");
+ printer->Indent();
+ for (int i = 0; i < service->method_count(); i++) {
+ auto method = service->method(i);
+ vars["Method"] = exportName(method->name());
+ vars["Handler"] = "_" + vars["Service"] + "_" + vars["Method"] + "_Handler";
+ if (method->NoStreaming()) {
+ printer->Print("{\n");
+ printer->Indent();
+ printer->Print(vars, "MethodName: \"$Method$\",\n");
+ printer->Print(vars, "Handler: $Handler$,\n");
+ printer->Outdent();
+ printer->Print("},\n");
+ }
+ }
+ printer->Outdent();
+ printer->Print("},\n");
+ printer->Print(vars, "Streams: []$grpc$.StreamDesc{\n");
+ printer->Indent();
+ for (int i = 0; i < service->method_count(); i++) {
+ auto method = service->method(i);
+ vars["Method"] = exportName(method->name());
+ vars["Handler"] = "_" + vars["Service"] + "_" + vars["Method"] + "_Handler";
+ if (!method->NoStreaming()) {
+ printer->Print("{\n");
+ printer->Indent();
+ printer->Print(vars, "StreamName: \"$Method$\",\n");
+ printer->Print(vars, "Handler: $Handler$,\n");
+ if (ClientOnlyStreaming(method.get())) {
+ printer->Print("ClientStreams: true,\n");
+ } else if (ServerOnlyStreaming(method.get())) {
+ printer->Print("ServerStreams: true,\n");
+ } else {
+ printer->Print("ServerStreams: true,\n");
+ printer->Print("ClientStreams: true,\n");
+ }
+ printer->Outdent();
+ printer->Print("},\n");
+ }
+ }
+ printer->Outdent();
+ printer->Print("},\n");
+ printer->Outdent();
+ printer->Print("}\n");
}
-
// Returns source for the service
grpc::string GenerateServiceSource(grpc_generator::File *file,
const grpc_generator::Service *service,
grpc_go_generator::Parameters *parameters) {
- grpc::string out;
- auto p = file->CreatePrinter(&out);
- auto printer = p.get();
- std::map<grpc::string, grpc::string> vars;
- vars["Package"] = parameters->package_name;
- vars["ServicePrefix"] = parameters->service_prefix;
- vars["grpc"] = "grpc";
- vars["context"] = "context";
- GenerateImports(file, printer, vars);
- if (parameters->custom_method_io_type != "") {
- vars["CustomMethodIO"] = parameters->custom_method_io_type;
- }
- GenerateService(service, printer, vars);
- return out;
+ grpc::string out;
+ auto p = file->CreatePrinter(&out, '\t');
+ p->SetIndentationSize(1);
+ auto printer = p.get();
+ std::map<grpc::string, grpc::string> vars;
+ vars["Package"] = parameters->package_name;
+ vars["ServicePrefix"] = parameters->service_prefix;
+ if (!parameters->service_prefix.empty()) vars["ServicePrefix"].append(".");
+ vars["grpc"] = "grpc";
+ vars["context"] = "context";
+ GenerateImports(file, printer, vars);
+ if (parameters->custom_method_io_type != "") {
+ vars["CustomMethodIO"] = parameters->custom_method_io_type;
+ }
+ GenerateService(service, printer, vars);
+ return out;
}
-}// Namespace grpc_go_generator
+} // Namespace grpc_go_generator
diff --git a/grpc/src/compiler/go_generator.h b/grpc/src/compiler/go_generator.h
index baa94e0..766e100 100644
--- a/grpc/src/compiler/go_generator.h
+++ b/grpc/src/compiler/go_generator.h
@@ -1,40 +1,8 @@
-/*
- *
- * Copyright 2015, Google Inc.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
#ifndef GRPC_INTERNAL_COMPILER_GO_GENERATOR_H
#define GRPC_INTERNAL_COMPILER_GO_GENERATOR_H
-//go generator is used to generate GRPC code for serialization system, such as flatbuffers
+// go generator is used to generate GRPC code for serialization system, such as
+// flatbuffers
#include <memory>
#include <vector>
@@ -43,14 +11,15 @@
namespace grpc_go_generator {
struct Parameters {
- //Defines the custom parameter types for methods
- //eg: flatbuffers uses flatbuffers.Builder as input for the client and output for the server
+ // Defines the custom parameter types for methods
+ // eg: flatbuffers uses flatbuffers.Builder as input for the client and output
+ // for the server
grpc::string custom_method_io_type;
- //Package name for the service
+ // Package name for the service
grpc::string package_name;
- //Prefix for RPC Calls
+ // Prefix for RPC Calls
grpc::string service_prefix;
};
@@ -59,6 +28,6 @@
const grpc_generator::Service *service,
grpc_go_generator::Parameters *parameters);
-}
+} // namespace grpc_go_generator
#endif // GRPC_INTERNAL_COMPILER_GO_GENERATOR_H
diff --git a/grpc/src/compiler/java_generator.cc b/grpc/src/compiler/java_generator.cc
index d2cf5cc..98f8788 100644
--- a/grpc/src/compiler/java_generator.cc
+++ b/grpc/src/compiler/java_generator.cc
@@ -23,21 +23,18 @@
#include <utility>
#include <vector>
-// just to get flatbuffer_version_string()
-#include <flatbuffers/flatbuffers.h>
-#include <flatbuffers/util.h>
+#include "flatbuffers/util.h"
#define to_string flatbuffers::NumToString
// Stringify helpers used solely to cast GRPC_VERSION
#ifndef STR
-#define STR(s) #s
+# define STR(s) # s
#endif
#ifndef XSTR
-#define XSTR(s) STR(s)
+# define XSTR(s) STR(s)
#endif
-
typedef grpc_generator::Printer Printer;
typedef std::map<grpc::string, grpc::string> VARS;
typedef grpc_generator::Service ServiceDescriptor;
@@ -48,12 +45,11 @@
namespace grpc_java_generator {
typedef std::string string;
// Generates imports for the service
-void GenerateImports(grpc_generator::File* file,
- grpc_generator::Printer* printer, VARS& vars) {
+void GenerateImports(grpc_generator::File *file,
+ grpc_generator::Printer *printer, VARS &vars) {
vars["filename"] = file->filename();
- printer->Print(
- vars,
- "//Generated by flatc compiler (version $flatc_version$)\n");
+ printer->Print(vars,
+ "//Generated by flatc compiler (version $flatc_version$)\n");
printer->Print("//If you make any local changes, they will be lost\n");
printer->Print(vars, "//source: $filename$.fbs\n\n");
printer->Print(vars, "package $Package$;\n\n");
@@ -67,7 +63,7 @@
// Adjust a method name prefix identifier to follow the JavaBean spec:
// - decapitalize the first letter
// - remove embedded underscores & capitalize the following letter
-static string MixedLower(const string& word) {
+static string MixedLower(const string &word) {
string w;
w += static_cast<string::value_type>(tolower(word[0]));
bool after_underscore = false;
@@ -87,7 +83,7 @@
// - An underscore is inserted where a lower case letter is followed by an
// upper case letter.
// - All letters are converted to upper case
-static string ToAllUpperCase(const string& word) {
+static string ToAllUpperCase(const string &word) {
string w;
for (size_t i = 0; i < word.length(); ++i) {
w += static_cast<string::value_type>(toupper(word[i]));
@@ -98,47 +94,47 @@
return w;
}
-static inline string LowerMethodName(const MethodDescriptor* method) {
+static inline string LowerMethodName(const MethodDescriptor *method) {
return MixedLower(method->name());
}
-static inline string MethodPropertiesFieldName(const MethodDescriptor* method) {
+static inline string MethodPropertiesFieldName(const MethodDescriptor *method) {
return "METHOD_" + ToAllUpperCase(method->name());
}
static inline string MethodPropertiesGetterName(
- const MethodDescriptor* method) {
+ const MethodDescriptor *method) {
return MixedLower("get_" + method->name() + "_method");
}
-static inline string MethodIdFieldName(const MethodDescriptor* method) {
+static inline string MethodIdFieldName(const MethodDescriptor *method) {
return "METHODID_" + ToAllUpperCase(method->name());
}
-static inline string JavaClassName(VARS& vars, const string& name) {
+static inline string JavaClassName(VARS &vars, const string &name) {
// string name = google::protobuf::compiler::java::ClassName(desc);
return vars["Package"] + name;
}
-static inline string ServiceClassName(const string& service_name) {
+static inline string ServiceClassName(const string &service_name) {
return service_name + "Grpc";
}
// TODO(nmittler): Remove once protobuf includes javadoc methods in
// distribution.
-template <typename ITR>
-static void GrpcSplitStringToIteratorUsing(const string& full,
- const char* delim, ITR& result) {
+template<typename ITR>
+static void GrpcSplitStringToIteratorUsing(const string &full,
+ const char *delim, ITR &result) {
// Optimize the common case where delim is a single character.
if (delim[0] != '\0' && delim[1] == '\0') {
char c = delim[0];
- const char* p = full.data();
- const char* end = p + full.size();
+ const char *p = full.data();
+ const char *end = p + full.size();
while (p != end) {
if (*p == c) {
++p;
} else {
- const char* start = p;
+ const char *start = p;
while (++p != end && *p != c)
;
*result++ = string(start, p - start);
@@ -160,13 +156,13 @@
}
}
-static void GrpcSplitStringUsing(const string& full, const char* delim,
- std::vector<string>* result) {
+static void GrpcSplitStringUsing(const string &full, const char *delim,
+ std::vector<string> *result) {
std::back_insert_iterator<std::vector<string>> it(*result);
GrpcSplitStringToIteratorUsing(full, delim, it);
}
-static std::vector<string> GrpcSplit(const string& full, const char* delim) {
+static std::vector<string> GrpcSplit(const string &full, const char *delim) {
std::vector<string> result;
GrpcSplitStringUsing(full, delim, &result);
return result;
@@ -174,7 +170,7 @@
// TODO(nmittler): Remove once protobuf includes javadoc methods in
// distribution.
-static string GrpcEscapeJavadoc(const string& input) {
+static string GrpcEscapeJavadoc(const string &input) {
string result;
result.reserve(input.size() * 2);
@@ -221,9 +217,7 @@
// Java interprets Unicode escape sequences anywhere!
result.append("\");
break;
- default:
- result.push_back(c);
- break;
+ default: result.push_back(c); break;
}
prev = c;
@@ -232,7 +226,7 @@
return result;
}
-static std::vector<string> GrpcGetDocLines(const string& comments) {
+static std::vector<string> GrpcGetDocLines(const string &comments) {
if (!comments.empty()) {
// TODO(kenton): Ideally we should parse the comment text as Markdown and
// write it back as HTML, but this requires a Markdown parser. For now
@@ -243,27 +237,23 @@
string escapedComments = GrpcEscapeJavadoc(comments);
std::vector<string> lines = GrpcSplit(escapedComments, "\n");
- while (!lines.empty() && lines.back().empty()) {
- lines.pop_back();
- }
+ while (!lines.empty() && lines.back().empty()) { lines.pop_back(); }
return lines;
}
return std::vector<string>();
}
static std::vector<string> GrpcGetDocLinesForDescriptor(
- const DescriptorType* descriptor) {
+ const DescriptorType *descriptor) {
return descriptor->GetAllComments();
// return GrpcGetDocLines(descriptor->GetLeadingComments("///"));
}
-static void GrpcWriteDocCommentBody(Printer* printer, VARS& vars,
- const std::vector<string>& lines,
+static void GrpcWriteDocCommentBody(Printer *printer, VARS &vars,
+ const std::vector<string> &lines,
bool surroundWithPreTag) {
if (!lines.empty()) {
- if (surroundWithPreTag) {
- printer->Print(" * <pre>\n");
- }
+ if (surroundWithPreTag) { printer->Print(" * <pre>\n"); }
for (size_t i = 0; i < lines.size(); i++) {
// Most lines should start with a space. Watch out for lines that start
@@ -277,73 +267,72 @@
}
}
- if (surroundWithPreTag) {
- printer->Print(" * </pre>\n");
- }
+ if (surroundWithPreTag) { printer->Print(" * </pre>\n"); }
}
}
-static void GrpcWriteDocComment(Printer* printer, VARS& vars,
- const string& comments) {
+static void GrpcWriteDocComment(Printer *printer, VARS &vars,
+ const string &comments) {
printer->Print("/**\n");
std::vector<string> lines = GrpcGetDocLines(comments);
GrpcWriteDocCommentBody(printer, vars, lines, false);
printer->Print(" */\n");
}
-static void GrpcWriteServiceDocComment(Printer* printer, VARS& vars,
- const ServiceDescriptor* service) {
+static void GrpcWriteServiceDocComment(Printer *printer, VARS &vars,
+ const ServiceDescriptor *service) {
printer->Print("/**\n");
std::vector<string> lines = GrpcGetDocLinesForDescriptor(service);
GrpcWriteDocCommentBody(printer, vars, lines, true);
printer->Print(" */\n");
}
-void GrpcWriteMethodDocComment(Printer* printer, VARS& vars,
- const MethodDescriptor* method) {
+void GrpcWriteMethodDocComment(Printer *printer, VARS &vars,
+ const MethodDescriptor *method) {
printer->Print("/**\n");
std::vector<string> lines = GrpcGetDocLinesForDescriptor(method);
GrpcWriteDocCommentBody(printer, vars, lines, true);
printer->Print(" */\n");
}
-//outputs static singleton extractor for type stored in "extr_type" and "extr_type_name" vars
-static void PrintTypeExtractor(Printer* p, VARS& vars) {
- p->Print(
- vars,
- "private static volatile FlatbuffersUtils.FBExtactor<$extr_type$> "
- "extractorOf$extr_type_name$;\n"
- "private static FlatbuffersUtils.FBExtactor<$extr_type$> "
- "getExtractorOf$extr_type_name$() {\n"
- " if (extractorOf$extr_type_name$ != null) return "
- "extractorOf$extr_type_name$;\n"
- " synchronized ($service_class_name$.class) {\n"
- " if (extractorOf$extr_type_name$ != null) return "
- "extractorOf$extr_type_name$;\n"
- " extractorOf$extr_type_name$ = new "
- "FlatbuffersUtils.FBExtactor<$extr_type$>() {\n"
- " public $extr_type$ extract (ByteBuffer buffer) {\n"
- " return "
- "$extr_type$.getRootAs$extr_type_name$(buffer);\n"
- " }\n"
- " };\n"
- " return extractorOf$extr_type_name$;\n"
- " }\n"
- "}\n\n");
+// outputs static singleton extractor for type stored in "extr_type" and
+// "extr_type_name" vars
+static void PrintTypeExtractor(Printer *p, VARS &vars) {
+ p->Print(vars,
+ "private static volatile FlatbuffersUtils.FBExtactor<$extr_type$> "
+ "extractorOf$extr_type_name$;\n"
+ "private static FlatbuffersUtils.FBExtactor<$extr_type$> "
+ "getExtractorOf$extr_type_name$() {\n"
+ " if (extractorOf$extr_type_name$ != null) return "
+ "extractorOf$extr_type_name$;\n"
+ " synchronized ($service_class_name$.class) {\n"
+ " if (extractorOf$extr_type_name$ != null) return "
+ "extractorOf$extr_type_name$;\n"
+ " extractorOf$extr_type_name$ = new "
+ "FlatbuffersUtils.FBExtactor<$extr_type$>() {\n"
+ " public $extr_type$ extract (ByteBuffer buffer) {\n"
+ " return "
+ "$extr_type$.getRootAs$extr_type_name$(buffer);\n"
+ " }\n"
+ " };\n"
+ " return extractorOf$extr_type_name$;\n"
+ " }\n"
+ "}\n\n");
}
-static void PrintMethodFields(Printer* p, VARS& vars,
- const ServiceDescriptor* service) {
+static void PrintMethodFields(Printer *p, VARS &vars,
+ const ServiceDescriptor *service) {
p->Print("// Static method descriptors that strictly reflect the proto.\n");
vars["service_name"] = service->name();
- //set of names of rpc input- and output- types that were already encountered.
- //this is needed to avoid duplicating type extractor since it's possible that
- //the same type is used as an input or output type of more than a single RPC method
+ // set of names of rpc input- and output- types that were already encountered.
+ // this is needed to avoid duplicating type extractor since it's possible that
+ // the same type is used as an input or output type of more than a single RPC
+ // method
std::set<std::string> encounteredTypes;
for (int i = 0; i < service->method_count(); ++i) {
auto method = service->method(i);
- vars["arg_in_id"] = to_string(2L * i); //trying to make msvc 10 happy
+ vars["arg_in_id"] = to_string(2L * i); // trying to make msvc 10 happy
vars["arg_out_id"] = to_string(2L * i + 1);
vars["method_name"] = method->name();
vars["input_type_name"] = method->get_input_type_name();
@@ -353,8 +342,10 @@
vars["method_field_name"] = MethodPropertiesFieldName(method.get());
vars["method_new_field_name"] = MethodPropertiesGetterName(method.get());
vars["method_method_name"] = MethodPropertiesGetterName(method.get());
- bool client_streaming = method->ClientStreaming() || method->BidiStreaming();
- bool server_streaming = method->ServerStreaming() || method->BidiStreaming();
+ bool client_streaming =
+ method->ClientStreaming() || method->BidiStreaming();
+ bool server_streaming =
+ method->ServerStreaming() || method->BidiStreaming();
if (client_streaming) {
if (server_streaming) {
vars["method_type"] = "BIDI_STREAMING";
@@ -394,32 +385,32 @@
}
p->Print(
- vars,
- "@$ExperimentalApi$(\"https://github.com/grpc/grpc-java/issues/"
- "1901\")\n"
- "public static $MethodDescriptor$<$input_type$,\n"
- " $output_type$> $method_method_name$() {\n"
- " $MethodDescriptor$<$input_type$, $output_type$> "
- "$method_new_field_name$;\n"
- " if (($method_new_field_name$ = "
- "$service_class_name$.$method_new_field_name$) == null) {\n"
- " synchronized ($service_class_name$.class) {\n"
- " if (($method_new_field_name$ = "
- "$service_class_name$.$method_new_field_name$) == null) {\n"
- " $service_class_name$.$method_new_field_name$ = "
- "$method_new_field_name$ = \n"
- " $MethodDescriptor$.<$input_type$, "
- "$output_type$>newBuilder()\n"
- " .setType($MethodType$.$method_type$)\n"
- " .setFullMethodName(generateFullMethodName(\n"
- " \"$Package$$service_name$\", \"$method_name$\"))\n"
- " .setSampledToLocalTracing(true)\n"
- " .setRequestMarshaller(FlatbuffersUtils.marshaller(\n"
- " $input_type$.class, "
- "getExtractorOf$input_type_name$()))\n"
- " .setResponseMarshaller(FlatbuffersUtils.marshaller(\n"
- " $output_type$.class, "
- "getExtractorOf$output_type_name$()))\n");
+ vars,
+ "@$ExperimentalApi$(\"https://github.com/grpc/grpc-java/issues/"
+ "1901\")\n"
+ "public static $MethodDescriptor$<$input_type$,\n"
+ " $output_type$> $method_method_name$() {\n"
+ " $MethodDescriptor$<$input_type$, $output_type$> "
+ "$method_new_field_name$;\n"
+ " if (($method_new_field_name$ = "
+ "$service_class_name$.$method_new_field_name$) == null) {\n"
+ " synchronized ($service_class_name$.class) {\n"
+ " if (($method_new_field_name$ = "
+ "$service_class_name$.$method_new_field_name$) == null) {\n"
+ " $service_class_name$.$method_new_field_name$ = "
+ "$method_new_field_name$ = \n"
+ " $MethodDescriptor$.<$input_type$, "
+ "$output_type$>newBuilder()\n"
+ " .setType($MethodType$.$method_type$)\n"
+ " .setFullMethodName(generateFullMethodName(\n"
+ " \"$Package$$service_name$\", \"$method_name$\"))\n"
+ " .setSampledToLocalTracing(true)\n"
+ " .setRequestMarshaller(FlatbuffersUtils.marshaller(\n"
+ " $input_type$.class, "
+ "getExtractorOf$input_type_name$()))\n"
+ " .setResponseMarshaller(FlatbuffersUtils.marshaller(\n"
+ " $output_type$.class, "
+ "getExtractorOf$output_type_name$()))\n");
// vars["proto_method_descriptor_supplier"] = service->name() +
// "MethodDescriptorSupplier";
@@ -451,11 +442,11 @@
enum CallType { ASYNC_CALL = 0, BLOCKING_CALL = 1, FUTURE_CALL = 2 };
-static void PrintBindServiceMethodBody(Printer* p, VARS& vars,
- const ServiceDescriptor* service);
+static void PrintBindServiceMethodBody(Printer *p, VARS &vars,
+ const ServiceDescriptor *service);
// Prints a client interface or implementation class, or a server interface.
-static void PrintStub(Printer* p, VARS& vars, const ServiceDescriptor* service,
+static void PrintStub(Printer *p, VARS &vars, const ServiceDescriptor *service,
StubType type) {
const string service_name = service->name();
vars["service_name"] = service_name;
@@ -476,7 +467,7 @@
break;
case BLOCKING_CLIENT_INTERFACE:
interface = true;
- FLATBUFFERS_FALLTHROUGH(); // fall thru
+ FLATBUFFERS_FALLTHROUGH(); // fall thru
case BLOCKING_CLIENT_IMPL:
call_type = BLOCKING_CALL;
stub_name += "BlockingStub";
@@ -484,7 +475,7 @@
break;
case FUTURE_CLIENT_INTERFACE:
interface = true;
- FLATBUFFERS_FALLTHROUGH(); // fall thru
+ FLATBUFFERS_FALLTHROUGH(); // fall thru
case FUTURE_CLIENT_IMPL:
call_type = FUTURE_CALL;
stub_name += "FutureStub";
@@ -501,9 +492,7 @@
vars["client_name"] = client_name;
// Class head
- if (!interface) {
- GrpcWriteServiceDocComment(p, vars, service);
- }
+ if (!interface) { GrpcWriteServiceDocComment(p, vars, service); }
if (impl_base) {
p->Print(vars,
"public static abstract class $abstract_name$ implements "
@@ -546,8 +535,10 @@
vars["output_type"] = JavaClassName(vars, method->get_output_type_name());
vars["lower_method_name"] = LowerMethodName(&*method);
vars["method_method_name"] = MethodPropertiesGetterName(&*method);
- bool client_streaming = method->ClientStreaming() || method->BidiStreaming();
- bool server_streaming = method->ServerStreaming() || method->BidiStreaming();
+ bool client_streaming =
+ method->ClientStreaming() || method->BidiStreaming();
+ bool server_streaming =
+ method->ServerStreaming() || method->BidiStreaming();
if (call_type == BLOCKING_CALL && client_streaming) {
// Blocking client interface with client streaming is not available
@@ -563,9 +554,7 @@
p->Print("\n");
// TODO(nmittler): Replace with WriteMethodDocComment once included by the
// protobuf distro.
- if (!interface) {
- GrpcWriteMethodDocComment(p, vars, &*method);
- }
+ if (!interface) { GrpcWriteMethodDocComment(p, vars, &*method); }
p->Print("public ");
switch (call_type) {
case BLOCKING_CALL:
@@ -630,8 +619,7 @@
"responseObserver);\n");
}
break;
- default:
- break;
+ default: break;
}
} else if (!interface) {
switch (call_type) {
@@ -706,15 +694,15 @@
}
static bool CompareMethodClientStreaming(
- const std::unique_ptr<const grpc_generator::Method>& method1,
- const std::unique_ptr<const grpc_generator::Method>& method2) {
+ const std::unique_ptr<const grpc_generator::Method> &method1,
+ const std::unique_ptr<const grpc_generator::Method> &method2) {
return method1->ClientStreaming() < method2->ClientStreaming();
}
// Place all method invocations into a single class to reduce memory footprint
// on Android.
-static void PrintMethodHandlerClass(Printer* p, VARS& vars,
- const ServiceDescriptor* service) {
+static void PrintMethodHandlerClass(Printer *p, VARS &vars,
+ const ServiceDescriptor *service) {
// Sort method ids based on ClientStreaming() so switch tables are compact.
std::vector<std::unique_ptr<const grpc_generator::Method>> sorted_methods(
service->method_count());
@@ -724,7 +712,7 @@
stable_sort(sorted_methods.begin(), sorted_methods.end(),
CompareMethodClientStreaming);
for (size_t i = 0; i < sorted_methods.size(); i++) {
- auto& method = sorted_methods[i];
+ auto &method = sorted_methods[i];
vars["method_id"] = to_string(i);
vars["method_id_name"] = MethodIdFieldName(&*method);
p->Print(vars,
@@ -757,9 +745,7 @@
for (int i = 0; i < service->method_count(); ++i) {
auto method = service->method(i);
- if (method->ClientStreaming() || method->BidiStreaming()) {
- continue;
- }
+ if (method->ClientStreaming() || method->BidiStreaming()) { continue; }
vars["method_id_name"] = MethodIdFieldName(&*method);
vars["lower_method_name"] = LowerMethodName(&*method);
vars["input_type"] = JavaClassName(vars, method->get_input_type_name());
@@ -791,9 +777,7 @@
for (int i = 0; i < service->method_count(); ++i) {
auto method = service->method(i);
- if (!(method->ClientStreaming() || method->BidiStreaming())) {
- continue;
- }
+ if (!(method->ClientStreaming() || method->BidiStreaming())) { continue; }
vars["method_id_name"] = MethodIdFieldName(&*method);
vars["lower_method_name"] = LowerMethodName(&*method);
vars["input_type"] = JavaClassName(vars, method->get_input_type_name());
@@ -818,8 +802,8 @@
p->Print("}\n\n");
}
-static void PrintGetServiceDescriptorMethod(Printer* p, VARS& vars,
- const ServiceDescriptor* service) {
+static void PrintGetServiceDescriptorMethod(Printer *p, VARS &vars,
+ const ServiceDescriptor *service) {
vars["service_name"] = service->name();
// vars["proto_base_descriptor_supplier"] = service->name() +
// "BaseDescriptorSupplier"; vars["proto_file_descriptor_supplier"] =
@@ -911,8 +895,8 @@
p->Print("}\n");
}
-static void PrintBindServiceMethodBody(Printer* p, VARS& vars,
- const ServiceDescriptor* service) {
+static void PrintBindServiceMethodBody(Printer *p, VARS &vars,
+ const ServiceDescriptor *service) {
vars["service_name"] = service->name();
p->Indent();
p->Print(vars,
@@ -927,8 +911,10 @@
vars["input_type"] = JavaClassName(vars, method->get_input_type_name());
vars["output_type"] = JavaClassName(vars, method->get_output_type_name());
vars["method_id_name"] = MethodIdFieldName(&*method);
- bool client_streaming = method->ClientStreaming() || method->BidiStreaming();
- bool server_streaming = method->ServerStreaming() || method->BidiStreaming();
+ bool client_streaming =
+ method->ClientStreaming() || method->BidiStreaming();
+ bool server_streaming =
+ method->ServerStreaming() || method->BidiStreaming();
if (client_streaming) {
if (server_streaming) {
vars["calls_method"] = "asyncBidiStreamingCall";
@@ -962,8 +948,8 @@
p->Outdent();
}
-static void PrintService(Printer* p, VARS& vars,
- const ServiceDescriptor* service,
+static void PrintService(Printer *p, VARS &vars,
+ const ServiceDescriptor *service,
bool disable_version) {
vars["service_name"] = service->name();
vars["service_class_name"] = ServiceClassName(service->name());
@@ -1043,7 +1029,7 @@
p->Print("}\n");
}
-void PrintStaticImports(Printer* p) {
+void PrintStaticImports(Printer *p) {
p->Print(
"import java.nio.ByteBuffer;\n"
"import static "
@@ -1076,8 +1062,8 @@
"io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall;\n\n");
}
-void GenerateService(const grpc_generator::Service* service,
- grpc_generator::Printer* printer, VARS& vars,
+void GenerateService(const grpc_generator::Service *service,
+ grpc_generator::Printer *printer, VARS &vars,
bool disable_version) {
// All non-generated classes must be referred by fully qualified names to
// avoid collision with generated classes.
@@ -1113,8 +1099,8 @@
}
grpc::string GenerateServiceSource(
- grpc_generator::File* file, const grpc_generator::Service* service,
- grpc_java_generator::Parameters* parameters) {
+ grpc_generator::File *file, const grpc_generator::Service *service,
+ grpc_java_generator::Parameters *parameters) {
grpc::string out;
auto printer = file->CreatePrinter(&out);
VARS vars;
diff --git a/grpc/src/compiler/python_generator.cc b/grpc/src/compiler/python_generator.cc
index 3fcf7ea..8108db4 100644
--- a/grpc/src/compiler/python_generator.cc
+++ b/grpc/src/compiler/python_generator.cc
@@ -16,608 +16,133 @@
*
*/
-#include <algorithm>
-#include <cassert>
-#include <cctype>
-#include <cstring>
-#include <fstream>
-#include <iostream>
#include <map>
-#include <memory>
-#include <ostream>
-#include <set>
#include <sstream>
-#include <tuple>
-#include <vector>
#include "flatbuffers/util.h"
#include "src/compiler/python_generator.h"
-#include "src/compiler/python_private_generator.h"
-
-using std::make_pair;
-using std::map;
-using std::pair;
-using std::replace;
-using std::tuple;
-using std::vector;
-using std::set;
namespace grpc_python_generator {
-grpc::string generator_file_name;
+grpc::string GenerateMethodType(const grpc_generator::Method *method) {
-typedef map<grpc::string, grpc::string> StringMap;
-typedef vector<grpc::string> StringVector;
-typedef tuple<grpc::string, grpc::string> StringPair;
-typedef set<StringPair> StringPairSet;
+ if (method->NoStreaming())
+ return "unary_unary";
-// Provides RAII indentation handling. Use as:
-// {
-// IndentScope raii_my_indent_var_name_here(my_py_printer);
-// // constructor indented my_py_printer
-// ...
-// // destructor called at end of scope, un-indenting my_py_printer
-// }
-class IndentScope {
- public:
- explicit IndentScope(grpc_generator::Printer* printer) : printer_(printer) {
- printer_->Indent();
+ if (method->ServerStreaming())
+ return "unary_stream";
+
+ if (method->ClientStreaming())
+ return "stream_unary";
+
+ return "stream_stream";
+}
+
+grpc::string GenerateMethodInput(const grpc_generator::Method *method) {
+
+ if (method->NoStreaming() || method->ServerStreaming())
+ return "self, request, context";
+
+ return "self, request_iterator, context";
+}
+
+void GenerateStub(const grpc_generator::Service *service,
+ grpc_generator::Printer *printer,
+ std::map<grpc::string, grpc::string> *dictonary) {
+ auto vars = *dictonary;
+ printer->Print(vars, "class $ServiceName$Stub(object):\n");
+ printer->Indent();
+ printer->Print("\"\"\" Interface exported by the server. \"\"\"");
+ printer->Print("\n\n");
+ printer->Print("def __init__(self, channel):\n");
+ printer->Indent();
+ printer->Print("\"\"\" Constructor. \n\n");
+ printer->Print("Args: \n");
+ printer->Print("channel: A grpc.Channel. \n");
+ printer->Print("\"\"\"\n\n");
+
+ for (int j = 0; j < service->method_count(); j++) {
+ auto method = service->method(j);
+ vars["MethodName"] = method->name();
+ vars["MethodType"] = GenerateMethodType(&*method);
+ printer->Print(vars, "self.$MethodName$ = channel.$MethodType$(\n");
+ printer->Indent();
+ printer->Print(vars, "\"/$PATH$$ServiceName$/$MethodName$\"\n");
+ printer->Print(")\n");
+ printer->Outdent();
+ printer->Print("\n");
}
-
- ~IndentScope() { printer_->Outdent(); }
-
- private:
- grpc_generator::Printer* printer_;
-};
-
-inline grpc::string StringReplace(grpc::string str, const grpc::string& from,
- const grpc::string& to, bool replace_all) {
- size_t pos = 0;
-
- do {
- pos = str.find(from, pos);
- if (pos == grpc::string::npos) {
- break;
- }
- str.replace(pos, from.length(), to);
- pos += to.length();
- } while (replace_all);
-
- return str;
+ printer->Outdent();
+ printer->Outdent();
+ printer->Print("\n");
}
-inline grpc::string StringReplace(grpc::string str, const grpc::string& from,
- const grpc::string& to) {
- return StringReplace(str, from, to, true);
-}
+void GenerateServicer(const grpc_generator::Service *service,
+ grpc_generator::Printer *printer,
+ std::map<grpc::string, grpc::string> *dictonary) {
+ auto vars = *dictonary;
+ printer->Print(vars, "class $ServiceName$Servicer(object):\n");
+ printer->Indent();
+ printer->Print("\"\"\" Interface exported by the server. \"\"\"");
+ printer->Print("\n\n");
-grpc::string ModuleName(const grpc::string& filename,
- const grpc::string& import_prefix) {
- grpc::string basename = flatbuffers::StripExtension(filename);
- basename = StringReplace(basename, "-", "_");
- basename = StringReplace(basename, "/", ".");
- return import_prefix + basename + "_fb";
-}
-
-grpc::string ModuleAlias(const grpc::string& filename,
- const grpc::string& import_prefix) {
- grpc::string module_name = ModuleName(filename, import_prefix);
- // We can't have dots in the module name, so we replace each with _dot_.
- // But that could lead to a collision between a.b and a_dot_b, so we also
- // duplicate each underscore.
- module_name = StringReplace(module_name, "_", "__");
- module_name = StringReplace(module_name, ".", "_dot_");
- return module_name;
-}
-
-PrivateGenerator::PrivateGenerator(const GeneratorConfiguration& config_,
- const grpc_generator::File* file_)
- : config(config_), file(file_) {}
-
-void PrivateGenerator::PrintBetaServicer(const grpc_generator::Service* service,
- grpc_generator::Printer* out) {
- StringMap service_dict;
- service_dict["Service"] = service->name();
- out->Print("\n\n");
- out->Print(service_dict, "class Beta$Service$Servicer(object):\n");
- {
- IndentScope raii_class_indent(out);
- out->Print(
- "\"\"\"The Beta API is deprecated for 0.15.0 and later.\n"
- "\nIt is recommended to use the GA API (classes and functions in this\n"
- "file not marked beta) for all further purposes. This class was "
- "generated\n"
- "only to ease transition from grpcio<0.15.0 to "
- "grpcio>=0.15.0.\"\"\"\n");
- for (int i = 0; i < service->method_count(); ++i) {
- auto method = service->method(i);
- grpc::string arg_name =
- method->ClientStreaming() ? "request_iterator" : "request";
- StringMap method_dict;
- method_dict["Method"] = method->name();
- method_dict["ArgName"] = arg_name;
- out->Print(method_dict, "def $Method$(self, $ArgName$, context):\n");
- {
- IndentScope raii_method_indent(out);
- out->Print("context.code(beta_interfaces.StatusCode.UNIMPLEMENTED)\n");
- }
- }
+ for (int j = 0; j < service->method_count(); j++) {
+ auto method = service->method(j);
+ vars["MethodName"] = method->name();
+ vars["MethodInput"] = GenerateMethodInput(&*method);
+ printer->Print(vars, "def $MethodName$($MethodInput$):\n");
+ printer->Indent();
+ printer->Print("context.set_code(grpc.StatusCode.UNIMPLEMENTED)\n");
+ printer->Print("context.set_details('Method not implemented!')\n");
+ printer->Print("raise NotImplementedError('Method not implemented!')\n");
+ printer->Outdent();
+ printer->Print("\n\n");
}
+ printer->Outdent();
+ printer->Print("\n");
+
}
-void PrivateGenerator::PrintBetaStub(const grpc_generator::Service* service,
- grpc_generator::Printer* out) {
- StringMap service_dict;
- service_dict["Service"] = service->name();
- out->Print("\n\n");
- out->Print(service_dict, "class Beta$Service$Stub(object):\n");
- {
- IndentScope raii_class_indent(out);
- out->Print(
- "\"\"\"The Beta API is deprecated for 0.15.0 and later.\n"
- "\nIt is recommended to use the GA API (classes and functions in this\n"
- "file not marked beta) for all further purposes. This class was "
- "generated\n"
- "only to ease transition from grpcio<0.15.0 to "
- "grpcio>=0.15.0.\"\"\"\n");
- for (int i = 0; i < service->method_count(); ++i) {
- auto method = service->method(i);
- grpc::string arg_name =
- method->ClientStreaming() ? "request_iterator" : "request";
- StringMap method_dict;
- method_dict["Method"] = method->name();
- method_dict["ArgName"] = arg_name;
- out->Print(method_dict,
- "def $Method$(self, $ArgName$, timeout, metadata=None, "
- "with_call=False, protocol_options=None):\n");
- {
- IndentScope raii_method_indent(out);
- out->Print("raise NotImplementedError()\n");
- }
- if (!method->ServerStreaming()) {
- out->Print(method_dict, "$Method$.future = None\n");
- }
- }
+void GenerateRegister(const grpc_generator::Service *service,
+ grpc_generator::Printer *printer,
+ std::map<grpc::string, grpc::string> *dictonary) {
+ auto vars = *dictonary;
+ printer->Print(vars, "def add_$ServiceName$Servicer_to_server(servicer, server):\n");
+ printer->Indent();
+ printer->Print("rpc_method_handlers = {\n");
+ printer->Indent();
+ for (int j = 0; j < service->method_count(); j++) {
+ auto method = service->method(j);
+ vars["MethodName"] = method->name();
+ vars["MethodType"] = GenerateMethodType(&*method);
+ printer->Print(vars, "'$MethodName$': grpc.$MethodType$_rpc_method_handler(\n");
+ printer->Indent();
+ printer->Print(vars, "servicer.$MethodName$\n");
+ printer->Outdent();
+ printer->Print("),\n");
}
+ printer->Outdent();
+ printer->Print("}\n");
+ printer->Print(vars, "generic_handler = grpc.method_handlers_generic_handler(\n");
+ printer->Indent();
+ printer->Print(vars, "'$PATH$$ServiceName$', rpc_method_handlers)\n");
+ printer->Outdent();
+ printer->Print("server.add_generic_rpc_handlers((generic_handler,))");
+ printer->Outdent();
+ printer->Print("\n");
}
-void PrivateGenerator::PrintBetaServerFactory(
- const grpc::string& package_qualified_service_name,
- const grpc_generator::Service* service, grpc_generator::Printer* out) {
- StringMap service_dict;
- service_dict["Service"] = service->name();
- out->Print("\n\n");
- out->Print(service_dict,
- "def beta_create_$Service$_server(servicer, pool=None, "
- "pool_size=None, default_timeout=None, maximum_timeout=None):\n");
- {
- IndentScope raii_create_server_indent(out);
- out->Print(
- "\"\"\"The Beta API is deprecated for 0.15.0 and later.\n"
- "\nIt is recommended to use the GA API (classes and functions in this\n"
- "file not marked beta) for all further purposes. This function was\n"
- "generated only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0"
- "\"\"\"\n");
- StringMap method_implementation_constructors;
- StringMap input_message_modules_and_classes;
- StringMap output_message_modules_and_classes;
- for (int i = 0; i < service->method_count(); ++i) {
- auto method = service->method(i);
- const grpc::string method_implementation_constructor =
- grpc::string(method->ClientStreaming() ? "stream_" : "unary_") +
- grpc::string(method->ServerStreaming() ? "stream_" : "unary_") +
- "inline";
- grpc::string input_message_module_and_class = method->get_fb_builder();
- grpc::string output_message_module_and_class = method->get_fb_builder();
- method_implementation_constructors.insert(
- make_pair(method->name(), method_implementation_constructor));
- input_message_modules_and_classes.insert(
- make_pair(method->name(), input_message_module_and_class));
- output_message_modules_and_classes.insert(
- make_pair(method->name(), output_message_module_and_class));
- }
- StringMap method_dict;
- method_dict["PackageQualifiedServiceName"] = package_qualified_service_name;
-// out->Print("request_deserializers = {\n");
-// for (StringMap::iterator name_and_input_module_class_pair =
-// input_message_modules_and_classes.begin();
-// name_and_input_module_class_pair !=
-// input_message_modules_and_classes.end();
-// name_and_input_module_class_pair++) {
-// method_dict["MethodName"] = name_and_input_module_class_pair->first;
-// method_dict["InputTypeModuleAndClass"] =
-// name_and_input_module_class_pair->second;
-// IndentScope raii_indent(out);
-// out->Print(method_dict,
-// "(\'$PackageQualifiedServiceName$\', \'$MethodName$\'): "
-// "$InputTypeModuleAndClass$.FromString,\n");
-// }
-// out->Print("}\n");
-// out->Print("response_serializers = {\n");
-// for (StringMap::iterator name_and_output_module_class_pair =
-// output_message_modules_and_classes.begin();
-// name_and_output_module_class_pair !=
-// output_message_modules_and_classes.end();
-// name_and_output_module_class_pair++) {
-// method_dict["MethodName"] = name_and_output_module_class_pair->first;
-// method_dict["OutputTypeModuleAndClass"] =
-// name_and_output_module_class_pair->second;
-// IndentScope raii_indent(out);
-// out->Print(method_dict,
-// "(\'$PackageQualifiedServiceName$\', \'$MethodName$\'): "
-// "$OutputTypeModuleAndClass$.SerializeToString,\n");
-// }
-// out->Print("}\n");
- out->Print("method_implementations = {\n");
- for (StringMap::iterator name_and_implementation_constructor =
- method_implementation_constructors.begin();
- name_and_implementation_constructor !=
- method_implementation_constructors.end();
- name_and_implementation_constructor++) {
- method_dict["Method"] = name_and_implementation_constructor->first;
- method_dict["Constructor"] = name_and_implementation_constructor->second;
- IndentScope raii_descriptions_indent(out);
- const grpc::string method_name =
- name_and_implementation_constructor->first;
- out->Print(method_dict,
- "(\'$PackageQualifiedServiceName$\', \'$Method$\'): "
- "face_utilities.$Constructor$(servicer.$Method$),\n");
- }
- out->Print("}\n");
- out->Print(
- "server_options = beta_implementations.server_options("
- "thread_pool=pool, thread_pool_size=pool_size, "
- "default_timeout=default_timeout, "
- "maximum_timeout=maximum_timeout)\n");
- out->Print(
- "return beta_implementations.server(method_implementations, "
- "options=server_options)\n");
- //"request_deserializers=request_deserializers, "
- //"response_serializers=response_serializers, "
- }
-}
-
-void PrivateGenerator::PrintBetaStubFactory(
- const grpc::string& package_qualified_service_name,
- const grpc_generator::Service* service, grpc_generator::Printer* out) {
- StringMap dict;
- dict["Service"] = service->name();
- out->Print("\n\n");
- out->Print(dict,
- "def beta_create_$Service$_stub(channel, host=None,"
- " metadata_transformer=None, pool=None, pool_size=None):\n");
- {
- IndentScope raii_create_server_indent(out);
- out->Print(
- "\"\"\"The Beta API is deprecated for 0.15.0 and later.\n"
- "\nIt is recommended to use the GA API (classes and functions in this\n"
- "file not marked beta) for all further purposes. This function was\n"
- "generated only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0"
- "\"\"\"\n");
- StringMap method_cardinalities;
- StringMap input_message_modules_and_classes;
- StringMap output_message_modules_and_classes;
- for (int i = 0; i < service->method_count(); ++i) {
- auto method = service->method(i);
- const grpc::string method_cardinality =
- grpc::string(method->ClientStreaming() ? "STREAM" : "UNARY") +
- "_" +
- grpc::string(method->ServerStreaming() ? "STREAM" : "UNARY");
- grpc::string input_message_module_and_class = method->get_fb_builder();
- grpc::string output_message_module_and_class = method->get_fb_builder();
- method_cardinalities.insert(
- make_pair(method->name(), method_cardinality));
- input_message_modules_and_classes.insert(
- make_pair(method->name(), input_message_module_and_class));
- output_message_modules_and_classes.insert(
- make_pair(method->name(), output_message_module_and_class));
- }
- StringMap method_dict;
- method_dict["PackageQualifiedServiceName"] = package_qualified_service_name;
-// out->Print("request_serializers = {\n");
-// for (StringMap::iterator name_and_input_module_class_pair =
-// input_message_modules_and_classes.begin();
-// name_and_input_module_class_pair !=
-// input_message_modules_and_classes.end();
-// name_and_input_module_class_pair++) {
-// method_dict["MethodName"] = name_and_input_module_class_pair->first;
-// method_dict["InputTypeModuleAndClass"] =
-// name_and_input_module_class_pair->second;
-// IndentScope raii_indent(out);
-// out->Print(method_dict,
-// "(\'$PackageQualifiedServiceName$\', \'$MethodName$\'): "
-// "$InputTypeModuleAndClass$.SerializeToString,\n");
-// }
-// out->Print("}\n");
-// out->Print("response_deserializers = {\n");
-// for (StringMap::iterator name_and_output_module_class_pair =
-// output_message_modules_and_classes.begin();
-// name_and_output_module_class_pair !=
-// output_message_modules_and_classes.end();
-// name_and_output_module_class_pair++) {
-// method_dict["MethodName"] = name_and_output_module_class_pair->first;
-// method_dict["OutputTypeModuleAndClass"] =
-// name_and_output_module_class_pair->second;
-// IndentScope raii_indent(out);
-// out->Print(method_dict,
-// "(\'$PackageQualifiedServiceName$\', \'$MethodName$\'): "
-// "$OutputTypeModuleAndClass$.FromString,\n");
-// }
-// out->Print("}\n");
- out->Print("cardinalities = {\n");
- for (StringMap::iterator name_and_cardinality =
- method_cardinalities.begin();
- name_and_cardinality != method_cardinalities.end();
- name_and_cardinality++) {
- method_dict["Method"] = name_and_cardinality->first;
- method_dict["Cardinality"] = name_and_cardinality->second;
- IndentScope raii_descriptions_indent(out);
- out->Print(method_dict,
- "\'$Method$\': cardinality.Cardinality.$Cardinality$,\n");
- }
- out->Print("}\n");
- out->Print(
- "stub_options = beta_implementations.stub_options("
- "host=host, metadata_transformer=metadata_transformer, "
- "thread_pool=pool, thread_pool_size=pool_size)\n");
- out->Print(method_dict,
- "return beta_implementations.dynamic_stub(channel, "
- "\'$PackageQualifiedServiceName$\', "
- "cardinalities, options=stub_options)\n");
- // "request_serializers=request_serializers, "
- //"response_deserializers=response_deserializers, "
- }
-}
-
-void PrivateGenerator::PrintStub(
- const grpc::string& package_qualified_service_name,
- const grpc_generator::Service* service, grpc_generator::Printer* out) {
- StringMap dict;
- dict["Service"] = service->name();
- out->Print("\n\n");
- out->Print(dict, "class $Service$Stub(object):\n");
- {
- IndentScope raii_class_indent(out);
- out->Print("\n");
- out->Print("def __init__(self, channel):\n");
- {
- IndentScope raii_init_indent(out);
- out->Print("\"\"\"Constructor.\n");
- out->Print("\n");
- out->Print("Args:\n");
- {
- IndentScope raii_args_indent(out);
- out->Print("channel: A grpc.Channel.\n");
- }
- out->Print("\"\"\"\n");
- for (int i = 0; i < service->method_count(); ++i) {
- auto method = service->method(i);
- grpc::string multi_callable_constructor =
- grpc::string(method->ClientStreaming() ? "stream" : "unary") +
- "_" +
- grpc::string(method->ServerStreaming() ? "stream" : "unary");
- grpc::string request_module_and_class = method->get_fb_builder();
- grpc::string response_module_and_class = method->get_fb_builder();
- StringMap method_dict;
- method_dict["Method"] = method->name();
- method_dict["MultiCallableConstructor"] = multi_callable_constructor;
- out->Print(method_dict,
- "self.$Method$ = channel.$MultiCallableConstructor$(\n");
- {
- method_dict["PackageQualifiedService"] =
- package_qualified_service_name;
- method_dict["RequestModuleAndClass"] = request_module_and_class;
- method_dict["ResponseModuleAndClass"] = response_module_and_class;
- IndentScope raii_first_attribute_indent(out);
- IndentScope raii_second_attribute_indent(out);
- out->Print(method_dict, "'/$PackageQualifiedService$/$Method$',\n");
- out->Print(method_dict,"\n");
- out->Print(
- method_dict,"\n");
- out->Print(")\n");
- }
- }
- }
- }
-}
-
-void PrivateGenerator::PrintServicer(const grpc_generator::Service* service,
- grpc_generator::Printer* out) {
- StringMap service_dict;
- service_dict["Service"] = service->name();
- out->Print("\n\n");
- out->Print(service_dict, "class $Service$Servicer(object):\n");
- {
- IndentScope raii_class_indent(out);
- for (int i = 0; i < service->method_count(); ++i) {
- auto method = service->method(i);
- grpc::string arg_name =
- method->ClientStreaming() ? "request_iterator" : "request";
- StringMap method_dict;
- method_dict["Method"] = method->name();
- method_dict["ArgName"] = arg_name;
- out->Print("\n");
- out->Print(method_dict, "def $Method$(self, $ArgName$, context):\n");
- {
- IndentScope raii_method_indent(out);
- out->Print("context.set_code(grpc.StatusCode.UNIMPLEMENTED)\n");
- out->Print("context.set_details('Method not implemented!')\n");
- out->Print("raise NotImplementedError('Method not implemented!')\n");
- }
- }
- }
-}
-
-void PrivateGenerator::PrintAddServicerToServer(
- const grpc::string& package_qualified_service_name,
- const grpc_generator::Service* service, grpc_generator::Printer* out) {
- StringMap service_dict;
- service_dict["Service"] = service->name();
- out->Print("\n\n");
- out->Print(service_dict,
- "def add_$Service$Servicer_to_server(servicer, server):\n");
- {
- IndentScope raii_class_indent(out);
- out->Print("rpc_method_handlers = {\n");
- {
- IndentScope raii_dict_first_indent(out);
- IndentScope raii_dict_second_indent(out);
- for (int i = 0; i < service->method_count(); ++i) {
- auto method = service->method(i);
- grpc::string method_handler_constructor =
- grpc::string(method->ClientStreaming() ? "stream" : "unary") +
- "_" +
- grpc::string(method->ServerStreaming() ? "stream" : "unary") +
- "_rpc_method_handler";
- grpc::string request_module_and_class = method->get_fb_builder();
- grpc::string response_module_and_class = method->get_fb_builder();
- StringMap method_dict;
- method_dict["Method"] = method->name();
- method_dict["MethodHandlerConstructor"] = method_handler_constructor;
- method_dict["RequestModuleAndClass"] = request_module_and_class;
- method_dict["ResponseModuleAndClass"] = response_module_and_class;
- out->Print(method_dict,
- "'$Method$': grpc.$MethodHandlerConstructor$(\n");
- {
- IndentScope raii_call_first_indent(out);
- IndentScope raii_call_second_indent(out);
- out->Print(method_dict, "servicer.$Method$,\n");
- out->Print(
- method_dict,"\n");
- out->Print(
- method_dict,
- "\n");
- }
- out->Print("),\n");
- }
- }
- StringMap method_dict;
- method_dict["PackageQualifiedServiceName"] = package_qualified_service_name;
- out->Print("}\n");
- out->Print("generic_handler = grpc.method_handlers_generic_handler(\n");
- {
- IndentScope raii_call_first_indent(out);
- IndentScope raii_call_second_indent(out);
- out->Print(method_dict,
- "'$PackageQualifiedServiceName$', rpc_method_handlers)\n");
- }
- out->Print("server.add_generic_rpc_handlers((generic_handler,))\n");
- }
-}
-
-void PrivateGenerator::PrintBetaPreamble(grpc_generator::Printer* out) {
- StringMap var;
- var["Package"] = config.beta_package_root;
- out->Print(var,
- "from $Package$ import implementations as beta_implementations\n");
- out->Print(var, "from $Package$ import interfaces as beta_interfaces\n");
- out->Print("from grpc.framework.common import cardinality\n");
- out->Print(
- "from grpc.framework.interfaces.face import utilities as "
- "face_utilities\n");
-}
-
-void PrivateGenerator::PrintPreamble(grpc_generator::Printer* out) {
- StringMap var;
- var["Package"] = config.grpc_package_root;
- out->Print(var, "import $Package$\n");
- out->Print("\n");
- StringPairSet imports_set;
- for (int i = 0; i < file->service_count(); ++i) {
- auto service = file->service(i);
- for (int j = 0; j < service->method_count(); ++j) {
- auto method = service.get()->method(j);
-
- grpc::string input_type_file_name = method->get_fb_builder();
- grpc::string input_module_name =
- ModuleName(input_type_file_name, config.import_prefix);
- grpc::string input_module_alias =
- ModuleAlias(input_type_file_name, config.import_prefix);
- imports_set.insert(
- std::make_tuple(input_module_name, input_module_alias));
-
- grpc::string output_type_file_name = method->get_fb_builder();
- grpc::string output_module_name =
- ModuleName(output_type_file_name, config.import_prefix);
- grpc::string output_module_alias =
- ModuleAlias(output_type_file_name, config.import_prefix);
- imports_set.insert(
- std::make_tuple(output_module_name, output_module_alias));
- }
- }
-
- for (StringPairSet::iterator it = imports_set.begin();
- it != imports_set.end(); ++it) {
- var["ModuleName"] = std::get<0>(*it);
- var["ModuleAlias"] = std::get<1>(*it);
- out->Print(var, "import $ModuleName$ as $ModuleAlias$\n");
- }
-}
-
-void PrivateGenerator::PrintGAServices(grpc_generator::Printer* out) {
- grpc::string package = file->package();
- if (!package.empty()) {
- package = package.append(".");
- }
-
- out->Print(file->additional_headers().c_str());
-
- for (int i = 0; i < file->service_count(); ++i) {
- auto service = file->service(i);
-
- grpc::string package_qualified_service_name = package + service->name();
- PrintStub(package_qualified_service_name, service.get(), out);
- PrintServicer(service.get(), out);
- PrintAddServicerToServer(package_qualified_service_name, service.get(),
- out);
- }
-}
-
-void PrivateGenerator::PrintBetaServices(grpc_generator::Printer* out) {
- grpc::string package = file->package();
- if (!package.empty()) {
- package = package.append(".");
- }
- for (int i = 0; i < file->service_count(); ++i) {
- auto service = file->service(i);
-
- grpc::string package_qualified_service_name = package + service->name();
- PrintBetaServicer(service.get(), out);
- PrintBetaStub(service.get(), out);
- PrintBetaServerFactory(package_qualified_service_name, service.get(), out);
- PrintBetaStubFactory(package_qualified_service_name, service.get(), out);
- }
-}
-
-grpc::string PrivateGenerator::GetGrpcServices() {
+grpc::string Generate(grpc_generator::File *file,
+ const grpc_generator::Service *service) {
grpc::string output;
- {
- // Scope the output stream so it closes and finalizes output to the string.
- auto out = file->CreatePrinter(&output);
- out->Print(
- "# Generated by the gRPC Python protocol compiler plugin. "
- "DO NOT EDIT!\n");
- StringMap var;
- var["Package"] = config.grpc_package_root;
- out->Print(var, "import $Package$\n");
- PrintGAServices(out.get());
- out->Print("try:\n");
- {
- IndentScope raii_dict_try_indent(out.get());
- out->Print(
- "# THESE ELEMENTS WILL BE DEPRECATED.\n"
- "# Please use the generated *_pb2_grpc.py files instead.\n");
- out->Print(var, "import $Package$\n");
- PrintBetaPreamble(out.get());
- PrintGAServices(out.get());
- PrintBetaServices(out.get());
- }
- out->Print("except ImportError:\n");
- {
- IndentScope raii_dict_except_indent(out.get());
- out->Print("pass");
- }
- }
+ std::map<grpc::string, grpc::string> vars;
+ vars["PATH"] = file->package();
+ if (!file->package().empty()) { vars["PATH"].append("."); }
+ vars["ServiceName"] = service->name();
+ auto printer = file->CreatePrinter(&output);
+ GenerateStub(service, &*printer, &vars);
+ GenerateServicer(service, &*printer, &vars);
+ GenerateRegister(service, &*printer, &vars);
return output;
}
diff --git a/grpc/src/compiler/python_generator.h b/grpc/src/compiler/python_generator.h
index d92cb02..40d29aa 100644
--- a/grpc/src/compiler/python_generator.h
+++ b/grpc/src/compiler/python_generator.h
@@ -25,16 +25,8 @@
namespace grpc_python_generator {
-// Data pertaining to configuration of the generator with respect to anything
-// that may be used internally at Google.
-struct GeneratorConfiguration {
- grpc::string grpc_package_root;
- // TODO(https://github.com/grpc/grpc/issues/8622): Drop this.
- grpc::string beta_package_root;
- // TODO(https://github.com/google/protobuf/issues/888): Drop this.
- grpc::string import_prefix;
-};
-
+grpc::string Generate(grpc_generator::File *file,
+ const grpc_generator::Service *service);
} // namespace grpc_python_generator
#endif // GRPC_INTERNAL_COMPILER_PYTHON_GENERATOR_H
diff --git a/grpc/src/compiler/python_private_generator.h b/grpc/src/compiler/python_private_generator.h
deleted file mode 100644
index 30ba0d7..0000000
--- a/grpc/src/compiler/python_private_generator.h
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- *
- * Copyright 2015 gRPC authors.
- *
- * 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 GRPC_INTERNAL_COMPILER_PYTHON_PRIVATE_GENERATOR_H
-#define GRPC_INTERNAL_COMPILER_PYTHON_PRIVATE_GENERATOR_H
-
-#include <iostream>
-#include <vector>
-
-#include "src/compiler/python_generator.h"
-#include "src/compiler/schema_interface.h"
-
-namespace grpc_python_generator {
-
-// Tucks all generator state in an anonymous namespace away from
-// PythonGrpcGenerator and the header file, mostly to encourage future changes
-// to not require updates to the grpcio-tools C++ code part. Assumes that it is
-// only ever used from a single thread.
-struct PrivateGenerator {
- const GeneratorConfiguration& config;
- const grpc_generator::File* file;
-
- PrivateGenerator(const GeneratorConfiguration& config,
- const grpc_generator::File* file);
-
- grpc::string GetGrpcServices();
-
- private:
- void PrintPreamble(grpc_generator::Printer* out);
- void PrintBetaPreamble(grpc_generator::Printer* out);
- void PrintGAServices(grpc_generator::Printer* out);
- void PrintBetaServices(grpc_generator::Printer* out);
-
- void PrintAddServicerToServer(
- const grpc::string& package_qualified_service_name,
- const grpc_generator::Service* service, grpc_generator::Printer* out);
- void PrintServicer(const grpc_generator::Service* service,
- grpc_generator::Printer* out);
- void PrintStub(const grpc::string& package_qualified_service_name,
- const grpc_generator::Service* service,
- grpc_generator::Printer* out);
-
- void PrintBetaServicer(const grpc_generator::Service* service,
- grpc_generator::Printer* out);
- void PrintBetaServerFactory(
- const grpc::string& package_qualified_service_name,
- const grpc_generator::Service* service, grpc_generator::Printer* out);
- void PrintBetaStub(const grpc_generator::Service* service,
- grpc_generator::Printer* out);
- void PrintBetaStubFactory(const grpc::string& package_qualified_service_name,
- const grpc_generator::Service* service,
- grpc_generator::Printer* out);
-};
-
-} // namespace grpc_python_generator
-
-#endif // GRPC_INTERNAL_COMPILER_PYTHON_PRIVATE_GENERATOR_H
diff --git a/grpc/src/compiler/schema_interface.h b/grpc/src/compiler/schema_interface.h
index c03ffe7..e42e3e3 100644
--- a/grpc/src/compiler/schema_interface.h
+++ b/grpc/src/compiler/schema_interface.h
@@ -19,11 +19,10 @@
#ifndef GRPC_INTERNAL_COMPILER_SCHEMA_INTERFACE_H
#define GRPC_INTERNAL_COMPILER_SCHEMA_INTERFACE_H
+#include <map>
#include <memory>
#include <vector>
-#include "src/compiler/config.h"
-
#ifndef GRPC_CUSTOM_STRING
# include <string>
# define GRPC_CUSTOM_STRING std::string
@@ -93,6 +92,7 @@
virtual void Print(const std::map<grpc::string, grpc::string> &vars,
const char *template_string) = 0;
virtual void Print(const char *string) = 0;
+ virtual void SetIndentationSize(const size_t size) = 0;
virtual void Indent() = 0;
virtual void Outdent() = 0;
};
@@ -107,11 +107,14 @@
virtual grpc::string package() const = 0;
virtual std::vector<grpc::string> package_parts() const = 0;
virtual grpc::string additional_headers() const = 0;
+ virtual std::string message_header_ext() const = 0;
+ virtual std::string service_header_ext() const = 0;
virtual int service_count() const = 0;
virtual std::unique_ptr<const Service> service(int i) const = 0;
- virtual std::unique_ptr<Printer> CreatePrinter(grpc::string *str) const = 0;
+ virtual std::unique_ptr<Printer> CreatePrinter(
+ grpc::string *str, const char indentation_type = ' ') const = 0;
};
} // namespace grpc_generator
diff --git a/grpc/src/compiler/swift_generator.cc b/grpc/src/compiler/swift_generator.cc
index 95e8858..403a803 100644
--- a/grpc/src/compiler/swift_generator.cc
+++ b/grpc/src/compiler/swift_generator.cc
@@ -29,118 +29,208 @@
namespace grpc_swift_generator {
-std::string WrapInNameSpace(const std::vector<std::string> &components, const grpc::string &name) {
+std::string WrapInNameSpace(const std::vector<std::string> &components,
+ const grpc::string &name) {
std::string qualified_name;
for (auto it = components.begin(); it != components.end(); ++it)
qualified_name += *it + "_";
return qualified_name + name;
}
-grpc::string GenerateMessage(const std::vector<std::string> &components, const grpc::string &name) {
+grpc::string GenerateMessage(const std::vector<std::string> &components,
+ const grpc::string &name) {
return "Message<" + WrapInNameSpace(components, name) + ">";
}
// MARK: - Client
-grpc::string GenerateClientFuncName(const grpc_generator::Method *method) {
+void GenerateClientFuncName(const grpc_generator::Method *method,
+ grpc_generator::Printer *printer,
+ std::map<grpc::string, grpc::string> *dictonary) {
+ auto vars = *dictonary;
if (method->NoStreaming()) {
- return "$GenAccess$ func $MethodName$(_ request: $Input$"
- ", callOptions: CallOptions?$isNil$) -> UnaryCall<$Input$,$Output$>";
- }
-
- if (method->ClientStreaming()) {
- return "$GenAccess$ func $MethodName$"
- "(callOptions: CallOptions?$isNil$) -> "
- "ClientStreamingCall<$Input$,$Output$>";
+ printer->Print(vars,
+ " $GenAccess$func $MethodName$(\n"
+ " _ request: $Input$\n"
+ " , callOptions: CallOptions?$isNil$\n"
+ " ) -> UnaryCall<$Input$, $Output$>");
+ return;
}
if (method->ServerStreaming()) {
- return "$GenAccess$ func $MethodName$(_ request: $Input$"
- ", callOptions: CallOptions?$isNil$, handler: @escaping ($Output$"
- ") -> Void) -> ServerStreamingCall<$Input$, $Output$>";
+ printer->Print(vars,
+ " $GenAccess$func $MethodName$(\n"
+ " _ request: $Input$\n"
+ " , callOptions: CallOptions?$isNil$,\n"
+ " handler: @escaping ($Output$) -> Void\n"
+ " ) -> ServerStreamingCall<$Input$, $Output$>");
+ return;
}
- return "$GenAccess$ func $MethodName$"
- "(callOptions: CallOptions?$isNil$, handler: @escaping ($Output$"
- ") -> Void) -> BidirectionalStreamingCall<$Input$, $Output$>";
+
+ if (method->ClientStreaming()) {
+ printer->Print(vars,
+ " $GenAccess$func $MethodName$(\n"
+ " callOptions: CallOptions?$isNil$\n"
+ " ) -> ClientStreamingCall<$Input$, $Output$>");
+ return;
+ }
+
+ printer->Print(vars,
+ " $GenAccess$func $MethodName$(\n"
+ " callOptions: CallOptions?$isNil$,\n"
+ " handler: @escaping ($Output$ ) -> Void\n"
+ " ) -> BidirectionalStreamingCall<$Input$, $Output$>");
}
-grpc::string GenerateClientFuncBody(const grpc_generator::Method *method) {
+void GenerateClientFuncBody(const grpc_generator::Method *method,
+ grpc_generator::Printer *printer,
+ std::map<grpc::string, grpc::string> *dictonary) {
+ auto vars = *dictonary;
+ vars["Interceptor"] =
+ "interceptors: self.interceptors?.make$MethodName$Interceptors() ?? []";
if (method->NoStreaming()) {
- return "return self.makeUnaryCall(path: "
- "\"/$PATH$$ServiceName$/$MethodName$\", request: request, "
- "callOptions: callOptions ?? self.defaultCallOptions)";
- }
-
- if (method->ClientStreaming()) {
- return "return self.makeClientStreamingCall(path: "
- "\"/$PATH$$ServiceName$/$MethodName$\", callOptions: callOptions ?? "
- "self.defaultCallOptions)";
+ printer->Print(
+ vars,
+ " return self.makeUnaryCall(\n"
+ " path: \"/$PATH$$ServiceName$/$MethodName$\",\n"
+ " request: request,\n"
+ " callOptions: callOptions ?? self.defaultCallOptions,\n"
+ " $Interceptor$\n"
+ " )\n");
+ return;
}
if (method->ServerStreaming()) {
- return "return self.makeServerStreamingCall(path: "
- "\"/$PATH$$ServiceName$/$MethodName$\", request: request, "
- "callOptions: callOptions ?? self.defaultCallOptions, handler: "
- "handler)";
+ printer->Print(
+ vars,
+ " return self.makeServerStreamingCall(\n"
+ " path: \"/$PATH$$ServiceName$/$MethodName$\",\n"
+ " request: request,\n"
+ " callOptions: callOptions ?? self.defaultCallOptions,\n"
+ " $Interceptor$,\n"
+ " handler: handler\n"
+ " )\n");
+ return;
}
- return "return self.makeBidirectionalStreamingCall(path: "
- "\"/$PATH$$ServiceName$/$MethodName$\", callOptions: callOptions ?? "
- "self.defaultCallOptions, handler: handler)";
+
+ if (method->ClientStreaming()) {
+ printer->Print(
+ vars,
+ " return self.makeClientStreamingCall(\n"
+ " path: \"/$PATH$$ServiceName$/$MethodName$\",\n"
+ " callOptions: callOptions ?? self.defaultCallOptions,\n"
+ " $Interceptor$\n"
+ " )\n");
+ return;
+ }
+ printer->Print(vars,
+ " return self.makeBidirectionalStreamingCall(\n"
+ " path: \"/$PATH$$ServiceName$/$MethodName$\",\n"
+ " callOptions: callOptions ?? self.defaultCallOptions,\n"
+ " $Interceptor$,\n"
+ " handler: handler\n"
+ " )\n");
}
void GenerateClientProtocol(const grpc_generator::Service *service,
grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> *dictonary) {
auto vars = *dictonary;
- printer->Print(vars, "$ACCESS$ protocol $ServiceQualifiedName$Service {\n");
+ printer->Print(
+ vars,
+ "$ACCESS$ protocol $ServiceQualifiedName$ClientProtocol: GRPCClient {");
+ printer->Print("\n\n");
+ printer->Print(" var serviceName: String { get }");
+ printer->Print("\n\n");
+ printer->Print(
+ vars,
+ " var interceptors: "
+ "$ServiceQualifiedName$ClientInterceptorFactoryProtocol? { get }");
+ printer->Print("\n\n");
+
vars["GenAccess"] = "";
for (auto it = 0; it < service->method_count(); it++) {
auto method = service->method(it);
- vars["Input"] = GenerateMessage(method->get_input_namespace_parts(), method->get_input_type_name());
- vars["Output"] = GenerateMessage(method->get_output_namespace_parts(), method->get_output_type_name());
+ vars["Input"] = GenerateMessage(method->get_input_namespace_parts(),
+ method->get_input_type_name());
+ vars["Output"] = GenerateMessage(method->get_output_namespace_parts(),
+ method->get_output_type_name());
vars["MethodName"] = method->name();
vars["isNil"] = "";
- printer->Print(" ");
- auto func = GenerateClientFuncName(method.get());
- printer->Print(vars, func.c_str());
+ GenerateClientFuncName(method.get(), &*printer, &vars);
+ printer->Print("\n\n");
+ }
+ printer->Print("}\n\n");
+
+ printer->Print(vars, "extension $ServiceQualifiedName$ClientProtocol {");
+ printer->Print("\n\n");
+ printer->Print(vars,
+ " $ACCESS$ var serviceName: String { "
+ "\"$PATH$$ServiceName$\" }\n");
+
+ vars["GenAccess"] = service->is_internal() ? "internal " : "public ";
+ for (auto it = 0; it < service->method_count(); it++) {
+ auto method = service->method(it);
+ vars["Input"] = GenerateMessage(method->get_input_namespace_parts(),
+ method->get_input_type_name());
+ vars["Output"] = GenerateMessage(method->get_output_namespace_parts(),
+ method->get_output_type_name());
+ vars["MethodName"] = method->name();
+ vars["isNil"] = " = nil";
printer->Print("\n");
+ GenerateClientFuncName(method.get(), &*printer, &vars);
+ printer->Print(" {\n");
+ GenerateClientFuncBody(method.get(), &*printer, &vars);
+ printer->Print(" }\n");
+ }
+ printer->Print("}\n\n");
+
+ printer->Print(vars,
+ "$ACCESS$ protocol "
+ "$ServiceQualifiedName$ClientInterceptorFactoryProtocol {\n");
+
+ for (auto it = 0; it < service->method_count(); it++) {
+ auto method = service->method(it);
+ vars["Input"] = GenerateMessage(method->get_input_namespace_parts(),
+ method->get_input_type_name());
+ vars["Output"] = GenerateMessage(method->get_output_namespace_parts(),
+ method->get_output_type_name());
+ vars["MethodName"] = method->name();
+ printer->Print(
+ vars,
+ " /// - Returns: Interceptors to use when invoking '$MethodName$'.\n");
+ printer->Print(vars,
+ " func make$MethodName$Interceptors() -> "
+ "[ClientInterceptor<$Input$, $Output$>]\n\n");
}
printer->Print("}\n\n");
}
-void GenerateClientClass(const grpc_generator::Service *service,
- grpc_generator::Printer *printer,
+void GenerateClientClass(grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> *dictonary) {
auto vars = *dictonary;
printer->Print(vars,
- "$ACCESS$ final class $ServiceQualifiedName$ServiceClient: GRPCClient, "
- "$ServiceQualifiedName$Service {\n");
+ "$ACCESS$ final class $ServiceQualifiedName$ServiceClient: "
+ "$ServiceQualifiedName$ClientProtocol {\n");
printer->Print(vars, " $ACCESS$ let channel: GRPCChannel\n");
printer->Print(vars, " $ACCESS$ var defaultCallOptions: CallOptions\n");
- printer->Print("\n");
printer->Print(vars,
- " $ACCESS$ init(channel: GRPCChannel, "
- "defaultCallOptions: CallOptions = CallOptions()) {\n");
+ " $ACCESS$ var interceptors: "
+ "$ServiceQualifiedName$ClientInterceptorFactoryProtocol?\n");
+ printer->Print("\n");
+ printer->Print(
+ vars,
+ " $ACCESS$ init(\n"
+ " channel: GRPCChannel,\n"
+ " defaultCallOptions: CallOptions = CallOptions(),\n"
+ " interceptors: "
+ "$ServiceQualifiedName$ClientInterceptorFactoryProtocol? = nil\n"
+ " ) {\n");
printer->Print(" self.channel = channel\n");
printer->Print(" self.defaultCallOptions = defaultCallOptions\n");
+ printer->Print(" self.interceptors = interceptors\n");
printer->Print(" }");
printer->Print("\n");
- vars["GenAccess"] = service->is_internal() ? "internal" : "public";
- for (auto it = 0; it < service->method_count(); it++) {
- auto method = service->method(it);
- vars["Input"] = GenerateMessage(method->get_input_namespace_parts(), method->get_input_type_name());
- vars["Output"] = GenerateMessage(method->get_output_namespace_parts(), method->get_output_type_name());
- vars["MethodName"] = method->name();
- vars["isNil"] = " = nil";
- printer->Print("\n ");
- auto func = GenerateClientFuncName(method.get());
- printer->Print(vars, func.c_str());
- printer->Print(" {\n");
- auto body = GenerateClientFuncBody(method.get());
- printer->Print(" ");
- printer->Print(vars, body.c_str());
- printer->Print("\n }\n");
- }
printer->Print("}\n");
}
@@ -148,7 +238,7 @@
grpc::string GenerateServerFuncName(const grpc_generator::Method *method) {
if (method->NoStreaming()) {
- return "func $MethodName$(_ request: $Input$"
+ return "func $MethodName$(request: $Input$"
", context: StatusOnlyCallContext) -> EventLoopFuture<$Output$>";
}
@@ -169,43 +259,44 @@
grpc::string GenerateServerExtensionBody(const grpc_generator::Method *method) {
grpc::string start = " case \"$MethodName$\":\n ";
+ grpc::string interceptors =
+ " interceptors: self.interceptors?.make$MethodName$Interceptors() "
+ "?? [],\n";
if (method->NoStreaming()) {
return start +
- "return CallHandlerFactory.makeUnary(callHandlerContext: callHandlerContext) { "
- "context in"
- "\n "
- "return { request in"
- "\n "
- "self.$MethodName$(request, context: context)"
- "\n }"
- "\n }";
- }
- if (method->ClientStreaming()) {
- return start +
- "return CallHandlerFactory.makeClientStreaming(callHandlerContext: "
- "callHandlerContext) { context in"
- "\n "
- "self.$MethodName$(context: context)"
- "\n }";
+ "return UnaryServerHandler(\n"
+ " context: context,\n"
+ " requestDeserializer: GRPCPayloadDeserializer<$Input$>(),\n"
+ " responseSerializer: GRPCPayloadSerializer<$Output$>(),\n" +
+ interceptors +
+ " userFunction: self.$MethodName$(request:context:))\n";
}
if (method->ServerStreaming()) {
return start +
- "return CallHandlerFactory.makeServerStreaming(callHandlerContext: "
- "callHandlerContext) { context in"
- "\n "
- "return { request in"
- "\n "
- "self.$MethodName$(request: request, context: context)"
- "\n }"
- "\n }";
+ "return ServerStreamingServerHandler(\n"
+ " context: context,\n"
+ " requestDeserializer: GRPCPayloadDeserializer<$Input$>(),\n"
+ " responseSerializer: GRPCPayloadSerializer<$Output$>(),\n" +
+ interceptors +
+ " userFunction: self.$MethodName$(request:context:))\n";
+ }
+ if (method->ClientStreaming()) {
+ return start +
+ "return ClientStreamingServerHandler(\n"
+ " context: context,\n"
+ " requestDeserializer: GRPCPayloadDeserializer<$Input$>(),\n"
+ " responseSerializer: GRPCPayloadSerializer<$Output$>(),\n" +
+ interceptors +
+ " observerFactory: self.$MethodName$(context:))\n";
}
if (method->BidiStreaming()) {
return start +
- "return CallHandlerFactory.makeBidirectionalStreaming(callHandlerContext: "
- "callHandlerContext) { context in"
- "\n "
- "self.$MethodName$(context: context)"
- "\n }";
+ "return BidirectionalStreamingServerHandler(\n"
+ " context: context,\n"
+ " requestDeserializer: GRPCPayloadDeserializer<$Input$>(),\n"
+ " responseSerializer: GRPCPayloadSerializer<$Output$>(),\n" +
+ interceptors +
+ " observerFactory: self.$MethodName$(context:))\n";
}
return "";
}
@@ -214,12 +305,19 @@
grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> *dictonary) {
auto vars = *dictonary;
+ printer->Print(vars,
+ "$ACCESS$ protocol $ServiceQualifiedName$Provider: "
+ "CallHandlerProvider {\n");
printer->Print(
- vars, "$ACCESS$ protocol $ServiceQualifiedName$Provider: CallHandlerProvider {\n");
+ vars,
+ " var interceptors: "
+ "$ServiceQualifiedName$ServerInterceptorFactoryProtocol? { get }\n");
for (auto it = 0; it < service->method_count(); it++) {
auto method = service->method(it);
- vars["Input"] = GenerateMessage(method->get_input_namespace_parts(), method->get_input_type_name());
- vars["Output"] = GenerateMessage(method->get_output_namespace_parts(), method->get_output_type_name());
+ vars["Input"] = GenerateMessage(method->get_input_namespace_parts(),
+ method->get_input_type_name());
+ vars["Output"] = GenerateMessage(method->get_output_namespace_parts(),
+ method->get_output_type_name());
vars["MethodName"] = method->name();
printer->Print(" ");
auto func = GenerateServerFuncName(method.get());
@@ -235,13 +333,15 @@
"\"$PATH$$ServiceName$\" }\n");
printer->Print("\n");
printer->Print(
- " func handleMethod(_ methodName: Substring, callHandlerContext: "
- "CallHandlerContext) -> GRPCCallHandler? {\n");
- printer->Print(" switch methodName {\n");
+ " func handle(method name: Substring, context: "
+ "CallHandlerContext) -> GRPCServerHandlerProtocol? {\n");
+ printer->Print(" switch name {\n");
for (auto it = 0; it < service->method_count(); it++) {
auto method = service->method(it);
- vars["Input"] = GenerateMessage(method->get_input_namespace_parts(), method->get_input_type_name());
- vars["Output"] = GenerateMessage(method->get_output_namespace_parts(), method->get_output_type_name());
+ vars["Input"] = GenerateMessage(method->get_input_namespace_parts(),
+ method->get_input_type_name());
+ vars["Output"] = GenerateMessage(method->get_output_namespace_parts(),
+ method->get_output_type_name());
vars["MethodName"] = method->name();
auto body = GenerateServerExtensionBody(method.get());
printer->Print(vars, body.c_str());
@@ -250,6 +350,26 @@
printer->Print(" default: return nil;\n");
printer->Print(" }\n");
printer->Print(" }\n\n");
+ printer->Print("}\n\n");
+
+ printer->Print(vars,
+ "$ACCESS$ protocol "
+ "$ServiceQualifiedName$ServerInterceptorFactoryProtocol {\n");
+ for (auto it = 0; it < service->method_count(); it++) {
+ auto method = service->method(it);
+ vars["Input"] = GenerateMessage(method->get_input_namespace_parts(),
+ method->get_input_type_name());
+ vars["Output"] = GenerateMessage(method->get_output_namespace_parts(),
+ method->get_output_type_name());
+ vars["MethodName"] = method->name();
+ printer->Print(
+ vars,
+ " /// - Returns: Interceptors to use when handling '$MethodName$'.\n"
+ " /// Defaults to calling `self.makeInterceptors()`.\n");
+ printer->Print(vars,
+ " func make$MethodName$Interceptors() -> "
+ "[ServerInterceptor<$Input$, $Output$>]\n\n");
+ }
printer->Print("}");
}
@@ -259,15 +379,17 @@
std::map<grpc::string, grpc::string> vars;
vars["PATH"] = file->package();
if (!file->package().empty()) { vars["PATH"].append("."); }
- vars["ServiceQualifiedName"] = WrapInNameSpace(service->namespace_parts(), service->name());
+ vars["ServiceQualifiedName"] =
+ WrapInNameSpace(service->namespace_parts(), service->name());
vars["ServiceName"] = service->name();
vars["ACCESS"] = service->is_internal() ? "internal" : "public";
auto printer = file->CreatePrinter(&output);
- printer->Print(vars,
- "/// Usage: instantiate $ServiceQualifiedName$ServiceClient, then call "
- "methods of this protocol to make API calls.\n");
+ printer->Print(
+ vars,
+ "/// Usage: instantiate $ServiceQualifiedName$ServiceClient, then call "
+ "methods of this protocol to make API calls.\n");
GenerateClientProtocol(service, &*printer, &vars);
- GenerateClientClass(service, &*printer, &vars);
+ GenerateClientClass(&*printer, &vars);
printer->Print("\n");
GenerateServerProtocol(service, &*printer, &vars);
return output;
diff --git a/grpc/src/compiler/swift_generator.h b/grpc/src/compiler/swift_generator.h
index 1639cb0..2a226fa 100644
--- a/grpc/src/compiler/swift_generator.h
+++ b/grpc/src/compiler/swift_generator.h
@@ -1,40 +1,22 @@
/*
+ * Copyright 2020 Google Inc. All rights reserved.
*
- * Copyright 2020, 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
*
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
+ * 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.
*/
#include <memory>
#include <vector>
-#include "src/compiler/config.h"
#include "src/compiler/schema_interface.h"
#ifndef GRPC_CUSTOM_STRING
diff --git a/grpc/src/compiler/ts_generator.cc b/grpc/src/compiler/ts_generator.cc
index fe9731d..3c3daf0 100644
--- a/grpc/src/compiler/ts_generator.cc
+++ b/grpc/src/compiler/ts_generator.cc
@@ -21,31 +21,84 @@
* be maintained according to the Swift-grpc repository
*/
+#include "src/compiler/ts_generator.h"
+
#include <map>
#include <sstream>
#include "flatbuffers/util.h"
#include "src/compiler/schema_interface.h"
-#include "src/compiler/ts_generator.h"
namespace grpc_ts_generator {
+grpc::string GenerateNamespace(const std::vector<std::string> ns,
+ const std::string filename,
+ const bool include_separator) {
+ grpc::string path = "";
+ if (include_separator) path += ".";
+
+ for (auto it = ns.begin(); it < ns.end(); it++) {
+ if (include_separator) path += "/";
+ path += include_separator
+ ? flatbuffers::ConvertCase(*it, flatbuffers::Case::kDasher,
+ flatbuffers::Case::kUpperCamel)
+ : *it + "_";
+ }
+
+ if (include_separator) path += "/";
+ path += include_separator
+ ? flatbuffers::ConvertCase(filename, flatbuffers::Case::kDasher,
+ flatbuffers::Case::kUpperCamel)
+ : filename;
+ return path;
+}
+
// MARK: - Shared code
-void GenerateImports(grpc_generator::Printer *printer,
+void GenerateImports(const grpc_generator::Service *service,
+ grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> *dictonary,
const bool grpc_var_import) {
auto vars = *dictonary;
printer->Print(
"// Generated GRPC code for FlatBuffers TS *** DO NOT EDIT ***\n");
- printer->Print("import { flatbuffers } from 'flatbuffers';\n");
- printer->Print(vars,
- "import * as $FBSFile$ from './$Filename$_generated';\n");
+ printer->Print("import * as flatbuffers from 'flatbuffers';\n");
+
+ std::set<grpc::string> generated_imports;
+
+ for (auto it = 0; it < service->method_count(); it++) {
+ auto method = service->method(it);
+ auto output = method->get_output_type_name();
+ auto input = method->get_input_type_name();
+ auto input_namespace = method->get_input_namespace_parts();
+
+ vars["OUTPUT"] = output;
+ vars["INPUT"] = input;
+
+ if (generated_imports.find(output) == generated_imports.end()) {
+ generated_imports.insert(output);
+ vars["OUTPUT_DIR"] =
+ GenerateNamespace(method->get_output_namespace_parts(), output, true);
+ vars["Output_alias"] = GenerateNamespace(
+ method->get_output_namespace_parts(), output, false);
+ printer->Print(
+ vars, "import { $OUTPUT$ as $Output_alias$ } from '$OUTPUT_DIR$';\n");
+ }
+ if (generated_imports.find(input) == generated_imports.end()) {
+ generated_imports.insert(input);
+ vars["INPUT_DIR"] =
+ GenerateNamespace(method->get_output_namespace_parts(), input, true);
+ vars["Input_alias"] =
+ GenerateNamespace(method->get_output_namespace_parts(), input, false);
+ printer->Print(
+ vars, "import { $INPUT$ as $Input_alias$ } from '$INPUT_DIR$';\n");
+ }
+ }
printer->Print("\n");
if (grpc_var_import)
- printer->Print("var grpc = require('grpc');\n");
+ printer->Print("var grpc = require('@grpc/grpc-js');\n");
else
- printer->Print("import * as grpc from 'grpc';\n");
+ printer->Print("import * as grpc from '@grpc/grpc-js';\n");
printer->Print("\n");
}
@@ -68,13 +121,13 @@
auto vars = *dictonary;
printer->Print(vars, "function serialize_$Type$(buffer_args) {\n");
printer->Indent();
- printer->Print(vars, "if (!(buffer_args instanceof $FBSFile$.$Type$)) {\n");
+ printer->Print(vars, "if (!(buffer_args instanceof $Type$)) {\n");
printer->Indent();
- printer->Print(
- vars, "throw new Error('Expected argument of type $FBSFile$.$Type$');\n");
+ printer->Print(vars,
+ "throw new Error('Expected argument of type $VALUE$');\n");
printer->Outdent();
printer->Print("}\n");
- printer->Print(vars, "return buffer_args.serialize();\n");
+ printer->Print(vars, "return Buffer.from(buffer_args.serialize());\n");
printer->Outdent();
printer->Print("}\n\n");
}
@@ -86,7 +139,7 @@
printer->Print(vars, "function deserialize_$Type$(buffer) {\n");
printer->Indent();
printer->Print(vars,
- "return $FBSFile$.$Type$.getRootAs$Type$(new "
+ "return $Type$.getRootAs$VALUE$(new "
"flatbuffers.ByteBuffer(buffer))\n");
printer->Outdent();
printer->Print("}\n\n");
@@ -106,14 +159,18 @@
if (generated_functions.find(output) == generated_functions.end()) {
generated_functions.insert(output);
- vars["Type"] = output;
+ vars["VALUE"] = output;
+ vars["Type"] = GenerateNamespace(method->get_output_namespace_parts(),
+ output, false);
GenerateSerializeMethod(printer, &vars);
GenerateDeserializeMethod(printer, &vars);
}
printer->Print("\n");
if (generated_functions.find(input) == generated_functions.end()) {
generated_functions.insert(input);
- vars["Type"] = input;
+ vars["VALUE"] = input;
+ vars["Type"] =
+ GenerateNamespace(method->get_input_namespace_parts(), input, false);
GenerateSerializeMethod(printer, &vars);
GenerateDeserializeMethod(printer, &vars);
}
@@ -131,18 +188,20 @@
for (auto it = 0; it < service->method_count(); it++) {
auto method = service->method(it);
vars["MethodName"] = method->name();
- vars["Output"] = method->get_output_type_name();
- vars["Input"] = method->get_input_type_name();
+ vars["OUTPUT"] = GenerateNamespace(method->get_output_namespace_parts(),
+ method->get_output_type_name(), false);
+ vars["INPUT"] = GenerateNamespace(method->get_input_namespace_parts(),
+ method->get_input_type_name(), false);
printer->Print(vars, "$MethodName$: {\n");
printer->Indent();
printer->Print(vars, "path: '/$PATH$$ServiceName$/$MethodName$',\n");
GetStreamType(printer, &*method, &vars);
printer->Print(vars, "requestType: flatbuffers.ByteBuffer,\n");
- printer->Print(vars, "responseType: $FBSFile$.$Output$,\n");
- printer->Print(vars, "requestSerialize: serialize_$Input$,\n");
- printer->Print(vars, "requestDeserialize: deserialize_$Input$,\n");
- printer->Print(vars, "responseSerialize: serialize_$Output$,\n");
- printer->Print(vars, "responseDeserialize: deserialize_$Output$,\n");
+ printer->Print(vars, "responseType: $OUTPUT$,\n");
+ printer->Print(vars, "requestSerialize: serialize_$INPUT$,\n");
+ printer->Print(vars, "requestDeserialize: deserialize_$INPUT$,\n");
+ printer->Print(vars, "responseSerialize: serialize_$OUTPUT$,\n");
+ printer->Print(vars, "responseDeserialize: deserialize_$OUTPUT$,\n");
printer->Outdent();
printer->Print("},\n");
}
@@ -168,7 +227,7 @@
vars["Filename"] = filename;
auto printer = file->CreatePrinter(&output);
- GenerateImports(&*printer, &vars, true);
+ GenerateImports(service, &*printer, &vars, true);
GenerateMethods(service, &*printer, &vars);
GenerateService(service, &*printer, &vars);
return output;
@@ -179,22 +238,17 @@
void FillInterface(grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> *dictonary) {
auto vars = *dictonary;
- printer->Print(
- vars,
- "interface I$ServiceName$Service_I$MethodName$ extends "
- "grpc.MethodDefinition<$FBSFile$.$INPUT$, $FBSFile$.$OUTPUT$> {\n");
+ printer->Print(vars,
+ "interface I$ServiceName$Service_I$MethodName$ extends "
+ "grpc.MethodDefinition<$INPUT$, $OUTPUT$> {\n");
printer->Indent();
printer->Print(vars, "path: string; // /$PATH$$ServiceName$/$MethodName$\n");
printer->Print(vars, "requestStream: boolean; // $ClientStreaming$\n");
printer->Print(vars, "responseStream: boolean; // $ServerStreaming$\n");
- printer->Print(vars,
- "requestSerialize: grpc.serialize<$FBSFile$.$INPUT$>;\n");
- printer->Print(vars,
- "requestDeserialize: grpc.deserialize<$FBSFile$.$INPUT$>;\n");
- printer->Print(vars,
- "responseSerialize: grpc.serialize<$FBSFile$.$OUTPUT$>;\n");
- printer->Print(
- vars, "responseDeserialize: grpc.deserialize<$FBSFile$.$OUTPUT$>;\n");
+ printer->Print(vars, "requestSerialize: grpc.serialize<$INPUT$>;\n");
+ printer->Print(vars, "requestDeserialize: grpc.deserialize<$INPUT$>;\n");
+ printer->Print(vars, "responseSerialize: grpc.serialize<$OUTPUT$>;\n");
+ printer->Print(vars, "responseDeserialize: grpc.deserialize<$OUTPUT$>;\n");
printer->Outdent();
printer->Print("}\n");
}
@@ -212,8 +266,10 @@
vars["ClientStreaming"] = client_streaming ? "true" : "false";
vars["ServerStreaming"] = server_streaming ? "true" : "false";
vars["MethodName"] = method->name();
- vars["INPUT"] = method->get_input_type_name();
- vars["OUTPUT"] = method->get_output_type_name();
+ vars["OUTPUT"] = GenerateNamespace(method->get_output_namespace_parts(),
+ method->get_output_type_name(), false);
+ vars["INPUT"] = GenerateNamespace(method->get_input_namespace_parts(),
+ method->get_input_type_name(), false);
FillInterface(printer, &vars);
printer->Print("\n");
}
@@ -223,37 +279,39 @@
const grpc_generator::Service *service, grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> *dictonary) {
auto vars = *dictonary;
- printer->Print(vars, "export interface I$ServiceName$Server {\n");
+ printer->Print(vars,
+ "export interface I$ServiceName$Server extends "
+ "grpc.UntypedServiceImplementation {\n");
printer->Indent();
for (auto it = 0; it < service->method_count(); it++) {
auto method = service->method(it);
vars["Name"] = method->name();
- vars["INPUT"] = method->get_input_type_name();
- vars["OUTPUT"] = method->get_output_type_name();
+ vars["OUTPUT"] = GenerateNamespace(method->get_output_namespace_parts(),
+ method->get_output_type_name(), false);
+ vars["INPUT"] = GenerateNamespace(method->get_input_namespace_parts(),
+ method->get_input_type_name(), false);
if (method->BidiStreaming()) {
printer->Print(vars,
- "$Name$: grpc.handleBidiStreamingCall<$FBSFile$.$INPUT$, "
- "$FBSFile$.$OUTPUT$>;\n");
+ "$Name$: grpc.handleBidiStreamingCall<$INPUT$, "
+ "$OUTPUT$>;\n");
continue;
}
if (method->NoStreaming()) {
printer->Print(vars,
- "$Name$: grpc.handleUnaryCall<$FBSFile$.$INPUT$, "
- "$FBSFile$.$OUTPUT$>;\n");
+ "$Name$: grpc.handleUnaryCall<$INPUT$, "
+ "$OUTPUT$>;\n");
continue;
}
if (method->ClientStreaming()) {
- printer->Print(
- vars,
- "$Name$: grpc.handleClientStreamingCall<$FBSFile$.$INPUT$, "
- "$FBSFile$.$OUTPUT$>;\n");
+ printer->Print(vars,
+ "$Name$: grpc.handleClientStreamingCall<$INPUT$, "
+ "$OUTPUT$>;\n");
continue;
}
if (method->ServerStreaming()) {
- printer->Print(
- vars,
- "$Name$: grpc.handleServerStreamingCall<$FBSFile$.$INPUT$, "
- "$FBSFile$.$OUTPUT$>;\n");
+ printer->Print(vars,
+ "$Name$: grpc.handleServerStreamingCall<$INPUT$, "
+ "$OUTPUT$>;\n");
continue;
}
}
@@ -294,10 +352,10 @@
grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> *dictonary) {
auto vars = *dictonary;
- grpc::string main = "$ISPUBLIC$$MethodName$(request: $FBSFile$.$INPUT$, ";
+ grpc::string main = "$ISPUBLIC$$MethodName$(request: $INPUT$, ";
grpc::string callback =
"callback: (error: grpc.ServiceError | null, response: "
- "$FBSFile$.$OUTPUT$) => void): grpc.ClientUnaryCall;\n";
+ "$OUTPUT$) => void): grpc.ClientUnaryCall;\n";
auto meta_data = GenerateMetaData() + ", ";
auto options = GenerateOptions() + ", ";
printer->Print(vars, (main + callback).c_str());
@@ -312,8 +370,8 @@
grpc::string main = "$ISPUBLIC$$MethodName$(";
grpc::string callback =
"callback: (error: grpc.ServiceError | null, response: "
- "$FBSFile$.$INPUT$) => void): "
- "grpc.ClientWritableStream<$FBSFile$.$OUTPUT$>;\n";
+ "$INPUT$) => void): "
+ "grpc.ClientWritableStream<$OUTPUT$>;\n";
auto meta_data = GenerateMetaData() + ", ";
auto options = GenerateOptions() + ", ";
printer->Print(vars, (main + callback).c_str());
@@ -326,9 +384,8 @@
grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> *dictonary) {
auto vars = *dictonary;
- grpc::string main = "$ISPUBLIC$$MethodName$(request: $FBSFile$.$INPUT$, ";
- grpc::string end_function =
- "): grpc.ClientReadableStream<$FBSFile$.$OUTPUT$>;\n";
+ grpc::string main = "$ISPUBLIC$$MethodName$(request: $INPUT$, ";
+ grpc::string end_function = "): grpc.ClientReadableStream<$OUTPUT$>;\n";
auto meta_data = GenerateMetaData();
auto options = GenerateOptions();
printer->Print(vars, (main + meta_data + end_function).c_str());
@@ -341,7 +398,7 @@
auto vars = *dictonary;
grpc::string main = "$ISPUBLIC$$MethodName$(";
grpc::string end_function =
- "): grpc.ClientDuplexStream<$FBSFile$.$INPUT$, $FBSFile$.$OUTPUT$>;\n";
+ "): grpc.ClientDuplexStream<$INPUT$, $OUTPUT$>;\n";
auto meta_data = GenerateMetaData();
auto options = GenerateOptions();
printer->Print(vars, (main + end_function).c_str());
@@ -360,8 +417,10 @@
for (auto it = 0; it < service->method_count(); it++) {
auto method = service->method(it);
vars["MethodName"] = method->name();
- vars["INPUT"] = method->get_input_type_name();
- vars["OUTPUT"] = method->get_output_type_name();
+ vars["OUTPUT"] = GenerateNamespace(method->get_output_namespace_parts(),
+ method->get_output_type_name(), false);
+ vars["INPUT"] = GenerateNamespace(method->get_input_namespace_parts(),
+ method->get_input_type_name(), false);
vars["ISPUBLIC"] = "";
if (method->NoStreaming()) {
@@ -397,12 +456,14 @@
printer->Indent();
printer->Print(
"constructor(address: string, credentials: grpc.ChannelCredentials, "
- "options?: object);");
+ "options?: object);\n");
for (auto it = 0; it < service->method_count(); it++) {
auto method = service->method(it);
vars["MethodName"] = method->name();
- vars["INPUT"] = method->get_input_type_name();
- vars["OUTPUT"] = method->get_output_type_name();
+ vars["OUTPUT"] = GenerateNamespace(method->get_output_namespace_parts(),
+ method->get_output_type_name(), false);
+ vars["INPUT"] = GenerateNamespace(method->get_input_namespace_parts(),
+ method->get_input_type_name(), false);
vars["ISPUBLIC"] = "public ";
if (method->NoStreaming()) {
GenerateUnaryClientInterface(printer, &vars);
@@ -444,7 +505,7 @@
vars["Filename"] = filename;
auto printer = file->CreatePrinter(&output);
- GenerateImports(&*printer, &vars, false);
+ GenerateImports(service, &*printer, &vars, false);
GenerateMainInterface(service, &*printer, &vars);
printer->Print("\n");
GenerateClientInterface(service, &*printer, &vars);
diff --git a/grpc/src/compiler/ts_generator.h b/grpc/src/compiler/ts_generator.h
index a33bb3c..a356659 100644
--- a/grpc/src/compiler/ts_generator.h
+++ b/grpc/src/compiler/ts_generator.h
@@ -1,41 +1,7 @@
-/*
- *
- * Copyright 2020, Google Inc.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
#include <memory>
-#include <vector>
#include <set>
+#include <vector>
-#include "src/compiler/config.h"
#include "src/compiler/schema_interface.h"
#ifndef GRPC_CUSTOM_STRING
@@ -58,4 +24,3 @@
const grpc_generator::Service *service,
const grpc::string &filename);
} // namespace grpc_ts_generator
-
diff --git a/grpc/tests/go_test.go b/grpc/tests/go_test.go
index 1268169..7c94feb 100644
--- a/grpc/tests/go_test.go
+++ b/grpc/tests/go_test.go
@@ -1,16 +1,20 @@
package testing
import (
- "../../tests/MyGame/Example"
+ flatbuffers "github.com/google/flatbuffers/go"
+ "github.com/google/flatbuffers/tests/MyGame/Example"
"context"
"net"
"testing"
"google.golang.org/grpc"
+ "google.golang.org/grpc/encoding"
)
-type server struct{}
+type server struct {
+ Example.UnimplementedMonsterStorageServer
+}
// test used to send and receive in grpc methods
var test = "Flatbuffers"
@@ -63,8 +67,12 @@
if err != nil {
t.Fatalf("Retrieve client failed: %v", err)
}
- if string(out.Name()) != test {
- t.Errorf("RetrieveClient failed: expected=%s, got=%s\n", test, out.Name())
+ monster, err := out.Recv()
+ if err != nil {
+ t.Fatalf("Recv failed: %v", err)
+ }
+ if string(monster.Name()) != test {
+ t.Errorf("RetrieveClient failed: expected=%s, got=%s\n", test, monster.Name())
t.Fail()
}
}
@@ -75,7 +83,7 @@
t.Fatalf("Failed to listen: %v", err)
}
ser := grpc.NewServer()
- encoding.RegisterCodec(flatbuffers.FlatbuffersCodec{})
+ encoding.RegisterCodec(flatbuffers.FlatbuffersCodec{})
Example.RegisterMonsterStorageServer(ser, &server{})
go func() {
if err := ser.Serve(lis); err != nil {
diff --git a/grpc/tests/grpctest.cpp b/grpc/tests/grpctest.cpp
index decf5e5..6991b7e 100644
--- a/grpc/tests/grpctest.cpp
+++ b/grpc/tests/grpctest.cpp
@@ -14,8 +14,9 @@
* limitations under the License.
*/
-#include <grpc++/grpc++.h>
+#include <grpcpp/grpcpp.h>
+#include <condition_variable>
#include <thread>
#include "monster_test.grpc.fb.h"
diff --git a/grpc/tests/grpctest.py b/grpc/tests/grpctest.py
index 1c5e92f..9cfeda6 100644
--- a/grpc/tests/grpctest.py
+++ b/grpc/tests/grpctest.py
@@ -126,16 +126,16 @@
Monster.MonsterStartInventoryVector(b, len(test_inventory))
for i in range(0, len(test_inventory)):
b.PrependByte(test_inventory[i])
- inv = b.EndVector(len(test_inventory))
+ inv = b.EndVector()
Monster.MonsterStartTest4Vector(b, 2)
Test.CreateTest(b, 10, 20)
Test.CreateTest(b, 30, 40)
- test4 = b.EndVector(2)
+ test4 = b.EndVector()
Monster.MonsterStartTestarrayofstringVector(b, 1)
b.PrependUOffsetTRelative(test1)
- test_array_of_string = b.EndVector(1)
+ test_array_of_string = b.EndVector()
Monster.MonsterStart(b)
diff --git a/grpc/tests/message_builder_test.cpp b/grpc/tests/message_builder_test.cpp
index 3ce33a9..8af0c21 100644
--- a/grpc/tests/message_builder_test.cpp
+++ b/grpc/tests/message_builder_test.cpp
@@ -28,7 +28,7 @@
auto root_offset1 = populate1(dst);
dst.Finish(root_offset1);
size_t size, offset;
- grpc_slice slice;
+ ::grpc::Slice slice;
dst.ReleaseRaw(size, offset, slice);
flatbuffers::FlatBufferBuilder src;
auto root_offset2 = populate2(src);
@@ -39,7 +39,6 @@
TEST_EQ(dst.GetSize(), src_size);
TEST_ASSERT(release_n_verify(dst, m2_name(), m2_color()));
TEST_EQ(src.GetSize(), 0);
- grpc_slice_unref(slice);
}
template<class SrcBuilder>
@@ -82,10 +81,9 @@
auto root_offset1 = populate1(mb);
mb.Finish(root_offset1);
size_t size, offset;
- grpc_slice slice;
+ ::grpc::Slice slice;
const uint8_t *buf = mb.ReleaseRaw(size, offset, slice);
TEST_ASSERT_FUNC(verify(buf, offset, m1_name(), m1_color()));
- grpc_slice_unref(slice);
}
}
@@ -146,10 +144,9 @@
auto root_offset1 = populate1(dst);
dst.Finish(root_offset1);
size_t size, offset;
- grpc_slice slice = grpc_empty_slice();
+ ::grpc::Slice slice;
const uint8_t *buf = dst.ReleaseRaw(size, offset, slice);
TEST_ASSERT_FUNC(verify(buf, offset, m1_name(), m1_color()));
- grpc_slice_unref(slice);
SrcBuilder src;
dst = std::move(src);
diff --git a/grpc/tests/pom.xml b/grpc/tests/pom.xml
index 26e7624..5aca387 100644
--- a/grpc/tests/pom.xml
+++ b/grpc/tests/pom.xml
@@ -4,13 +4,13 @@
<parent>
<groupId>com.google.flatbuffers</groupId>
<artifactId>flatbuffers-parent</artifactId>
- <version>1.12.0</version>
+ <version>2.0.3</version>
</parent>
<artifactId>grpc-test</artifactId>
<description>Example/Test project demonstrating usage of flatbuffers with GRPC-Java instead of protobufs
</description>
<properties>
- <gRPC.version>1.12.0</gRPC.version>
+ <gRPC.version>2.0.3</gRPC.version>
</properties>
<dependencies>
<dependency>
diff --git a/include/flatbuffers/allocator.h b/include/flatbuffers/allocator.h
new file mode 100644
index 0000000..f4ef22d
--- /dev/null
+++ b/include/flatbuffers/allocator.h
@@ -0,0 +1,68 @@
+/*
+ * Copyright 2021 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_ALLOCATOR_H_
+#define FLATBUFFERS_ALLOCATOR_H_
+
+#include "flatbuffers/base.h"
+
+namespace flatbuffers {
+
+// Allocator interface. This is flatbuffers-specific and meant only for
+// `vector_downward` usage.
+class Allocator {
+ public:
+ virtual ~Allocator() {}
+
+ // Allocate `size` bytes of memory.
+ virtual uint8_t *allocate(size_t size) = 0;
+
+ // Deallocate `size` bytes of memory at `p` allocated by this allocator.
+ virtual void deallocate(uint8_t *p, size_t size) = 0;
+
+ // Reallocate `new_size` bytes of memory, replacing the old region of size
+ // `old_size` at `p`. In contrast to a normal realloc, this grows downwards,
+ // and is intended specifcally for `vector_downward` use.
+ // `in_use_back` and `in_use_front` indicate how much of `old_size` is
+ // actually in use at each end, and needs to be copied.
+ virtual uint8_t *reallocate_downward(uint8_t *old_p, size_t old_size,
+ size_t new_size, size_t in_use_back,
+ size_t in_use_front) {
+ FLATBUFFERS_ASSERT(new_size > old_size); // vector_downward only grows
+ uint8_t *new_p = allocate(new_size);
+ memcpy_downward(old_p, old_size, new_p, new_size, in_use_back,
+ in_use_front);
+ deallocate(old_p, old_size);
+ return new_p;
+ }
+
+ protected:
+ // Called by `reallocate_downward` to copy memory from `old_p` of `old_size`
+ // to `new_p` of `new_size`. Only memory of size `in_use_front` and
+ // `in_use_back` will be copied from the front and back of the old memory
+ // allocation.
+ void memcpy_downward(uint8_t *old_p, size_t old_size, uint8_t *new_p,
+ size_t new_size, size_t in_use_back,
+ size_t in_use_front) {
+ memcpy(new_p + new_size - in_use_back, old_p + old_size - in_use_back,
+ in_use_back);
+ memcpy(new_p, old_p, in_use_front);
+ }
+};
+
+} // namespace flatbuffers
+
+#endif // FLATBUFFERS_ALLOCATOR_H_
\ No newline at end of file
diff --git a/include/flatbuffers/array.h b/include/flatbuffers/array.h
new file mode 100644
index 0000000..d4b73fc
--- /dev/null
+++ b/include/flatbuffers/array.h
@@ -0,0 +1,243 @@
+/*
+ * Copyright 2021 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_ARRAY_H_
+#define FLATBUFFERS_ARRAY_H_
+
+#include "flatbuffers/base.h"
+#include "flatbuffers/stl_emulation.h"
+#include "flatbuffers/vector.h"
+
+namespace flatbuffers {
+
+// This is used as a helper type for accessing arrays.
+template<typename T, uint16_t length> class Array {
+ // Array<T> can carry only POD data types (scalars or structs).
+ typedef typename flatbuffers::bool_constant<flatbuffers::is_scalar<T>::value>
+ scalar_tag;
+ typedef
+ typename flatbuffers::conditional<scalar_tag::value, T, const T *>::type
+ IndirectHelperType;
+
+ public:
+ typedef uint16_t size_type;
+ typedef typename IndirectHelper<IndirectHelperType>::return_type return_type;
+ typedef VectorIterator<T, return_type> const_iterator;
+ typedef VectorReverseIterator<const_iterator> const_reverse_iterator;
+
+ // If T is a LE-scalar or a struct (!scalar_tag::value).
+ static FLATBUFFERS_CONSTEXPR bool is_span_observable =
+ (scalar_tag::value && (FLATBUFFERS_LITTLEENDIAN || sizeof(T) == 1)) ||
+ !scalar_tag::value;
+
+ FLATBUFFERS_CONSTEXPR uint16_t size() const { return length; }
+
+ return_type Get(uoffset_t i) const {
+ FLATBUFFERS_ASSERT(i < size());
+ return IndirectHelper<IndirectHelperType>::Read(Data(), i);
+ }
+
+ return_type operator[](uoffset_t i) const { return Get(i); }
+
+ // If this is a Vector of enums, T will be its storage type, not the enum
+ // type. This function makes it convenient to retrieve value with enum
+ // type E.
+ template<typename E> E GetEnum(uoffset_t i) const {
+ return static_cast<E>(Get(i));
+ }
+
+ const_iterator begin() const { return const_iterator(Data(), 0); }
+ const_iterator end() const { return const_iterator(Data(), size()); }
+
+ const_reverse_iterator rbegin() const {
+ return const_reverse_iterator(end());
+ }
+ const_reverse_iterator rend() const {
+ return const_reverse_iterator(begin());
+ }
+
+ const_iterator cbegin() const { return begin(); }
+ const_iterator cend() const { return end(); }
+
+ const_reverse_iterator crbegin() const { return rbegin(); }
+ const_reverse_iterator crend() const { return rend(); }
+
+ // Get a mutable pointer to elements inside this array.
+ // This method used to mutate arrays of structs followed by a @p Mutate
+ // operation. For primitive types use @p Mutate directly.
+ // @warning Assignments and reads to/from the dereferenced pointer are not
+ // automatically converted to the correct endianness.
+ typename flatbuffers::conditional<scalar_tag::value, void, T *>::type
+ GetMutablePointer(uoffset_t i) const {
+ FLATBUFFERS_ASSERT(i < size());
+ return const_cast<T *>(&data()[i]);
+ }
+
+ // Change elements if you have a non-const pointer to this object.
+ void Mutate(uoffset_t i, const T &val) { MutateImpl(scalar_tag(), i, val); }
+
+ // The raw data in little endian format. Use with care.
+ const uint8_t *Data() const { return data_; }
+
+ uint8_t *Data() { return data_; }
+
+ // Similarly, but typed, much like std::vector::data
+ const T *data() const { return reinterpret_cast<const T *>(Data()); }
+ T *data() { return reinterpret_cast<T *>(Data()); }
+
+ // Copy data from a span with endian conversion.
+ // If this Array and the span overlap, the behavior is undefined.
+ void CopyFromSpan(flatbuffers::span<const T, length> src) {
+ const auto p1 = reinterpret_cast<const uint8_t *>(src.data());
+ const auto p2 = Data();
+ FLATBUFFERS_ASSERT(!(p1 >= p2 && p1 < (p2 + length)) &&
+ !(p2 >= p1 && p2 < (p1 + length)));
+ (void)p1;
+ (void)p2;
+ CopyFromSpanImpl(flatbuffers::bool_constant<is_span_observable>(), src);
+ }
+
+ protected:
+ void MutateImpl(flatbuffers::true_type, uoffset_t i, const T &val) {
+ FLATBUFFERS_ASSERT(i < size());
+ WriteScalar(data() + i, val);
+ }
+
+ void MutateImpl(flatbuffers::false_type, uoffset_t i, const T &val) {
+ *(GetMutablePointer(i)) = val;
+ }
+
+ void CopyFromSpanImpl(flatbuffers::true_type,
+ flatbuffers::span<const T, length> src) {
+ // Use std::memcpy() instead of std::copy() to avoid performance 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::false_type,
+ flatbuffers::span<const T, length> src) {
+ for (size_type k = 0; k < length; k++) { Mutate(k, src[k]); }
+ }
+
+ // This class is only used to access pre-existing data. Don't ever
+ // try to construct these manually.
+ // 'constexpr' allows us to use 'size()' at compile time.
+ // @note Must not use 'FLATBUFFERS_CONSTEXPR' here, as const is not allowed on
+ // a constructor.
+#if defined(__cpp_constexpr)
+ constexpr Array();
+#else
+ Array();
+#endif
+
+ uint8_t data_[length * sizeof(T)];
+
+ private:
+ // This class is a pointer. Copying will therefore create an invalid object.
+ // Private and unimplemented copy constructor.
+ Array(const Array &);
+ Array &operator=(const Array &);
+};
+
+// Specialization for Array[struct] with access using Offset<void> pointer.
+// This specialization used by idl_gen_text.cpp.
+template<typename T, uint16_t length> class Array<Offset<T>, length> {
+ static_assert(flatbuffers::is_same<T, void>::value, "unexpected type T");
+
+ public:
+ typedef const void *return_type;
+
+ const uint8_t *Data() const { return data_; }
+
+ // Make idl_gen_text.cpp::PrintContainer happy.
+ return_type operator[](uoffset_t) const {
+ FLATBUFFERS_ASSERT(false);
+ return nullptr;
+ }
+
+ private:
+ // This class is only used to access pre-existing data.
+ Array();
+ Array(const Array &);
+ Array &operator=(const Array &);
+
+ uint8_t data_[1];
+};
+
+template<class U, uint16_t N>
+FLATBUFFERS_CONSTEXPR_CPP11 flatbuffers::span<U, N> make_span(Array<U, N> &arr)
+ FLATBUFFERS_NOEXCEPT {
+ static_assert(
+ Array<U, N>::is_span_observable,
+ "wrong type U, only plain struct, LE-scalar, or byte types are allowed");
+ return span<U, N>(arr.data(), N);
+}
+
+template<class U, uint16_t N>
+FLATBUFFERS_CONSTEXPR_CPP11 flatbuffers::span<const U, N> make_span(
+ const Array<U, N> &arr) FLATBUFFERS_NOEXCEPT {
+ static_assert(
+ Array<U, N>::is_span_observable,
+ "wrong type U, only plain struct, LE-scalar, or byte types are allowed");
+ return span<const U, N>(arr.data(), N);
+}
+
+template<class U, uint16_t N>
+FLATBUFFERS_CONSTEXPR_CPP11 flatbuffers::span<uint8_t, sizeof(U) * N>
+make_bytes_span(Array<U, N> &arr) FLATBUFFERS_NOEXCEPT {
+ static_assert(Array<U, N>::is_span_observable,
+ "internal error, Array<T> might hold only scalars or structs");
+ return span<uint8_t, sizeof(U) * N>(arr.Data(), sizeof(U) * N);
+}
+
+template<class U, uint16_t N>
+FLATBUFFERS_CONSTEXPR_CPP11 flatbuffers::span<const uint8_t, sizeof(U) * N>
+make_bytes_span(const Array<U, N> &arr) FLATBUFFERS_NOEXCEPT {
+ static_assert(Array<U, N>::is_span_observable,
+ "internal error, Array<T> might hold only scalars or structs");
+ return span<const uint8_t, sizeof(U) * N>(arr.Data(), sizeof(U) * N);
+}
+
+// Cast a raw T[length] to a raw flatbuffers::Array<T, length>
+// without endian conversion. Use with care.
+// TODO: move these Cast-methods to `internal` namespace.
+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);
+}
+
+} // namespace flatbuffers
+
+#endif // FLATBUFFERS_ARRAY_H_
diff --git a/include/flatbuffers/base.h b/include/flatbuffers/base.h
index 95b788e..458ac3f 100644
--- a/include/flatbuffers/base.h
+++ b/include/flatbuffers/base.h
@@ -50,10 +50,6 @@
#include <unistd.h>
#endif
-#ifdef _STLPORT_VERSION
- #define FLATBUFFERS_CPP98_STL
-#endif
-
#ifdef __ANDROID__
#include <android/api-level.h>
#endif
@@ -142,9 +138,9 @@
#endif
#endif // !defined(FLATBUFFERS_LITTLEENDIAN)
-#define FLATBUFFERS_VERSION_MAJOR 1
-#define FLATBUFFERS_VERSION_MINOR 12
-#define FLATBUFFERS_VERSION_REVISION 0
+#define FLATBUFFERS_VERSION_MAJOR 2
+#define FLATBUFFERS_VERSION_MINOR 0
+#define FLATBUFFERS_VERSION_REVISION 6
#define FLATBUFFERS_STRING_EXPAND(X) #X
#define FLATBUFFERS_STRING(X) FLATBUFFERS_STRING_EXPAND(X)
namespace flatbuffers {
@@ -197,10 +193,15 @@
#if (!defined(_MSC_VER) || _MSC_FULL_VER >= 180020827) && \
(!defined(__GNUC__) || (__GNUC__ * 100 + __GNUC_MINOR__ >= 404)) || \
defined(__clang__)
- #define FLATBUFFERS_DEFAULT_DECLARATION
- #define FLATBUFFERS_DELETE_FUNC(func) func = delete;
+ #define FLATBUFFERS_DELETE_FUNC(func) func = delete
#else
- #define FLATBUFFERS_DELETE_FUNC(func) private: func;
+ #define FLATBUFFERS_DELETE_FUNC(func) private: func
+#endif
+
+#if (!defined(_MSC_VER) || _MSC_VER >= 1900) && \
+ (!defined(__GNUC__) || (__GNUC__ * 100 + __GNUC_MINOR__ >= 409)) || \
+ defined(__clang__)
+ #define FLATBUFFERS_DEFAULT_DECLARATION
#endif
// Check if we can use template aliases
@@ -242,6 +243,11 @@
#endif // __has_include
#endif // !FLATBUFFERS_HAS_STRING_VIEW
+#ifndef FLATBUFFERS_GENERAL_HEAP_ALLOC_OK
+ // Allow heap allocations to be used
+ #define FLATBUFFERS_GENERAL_HEAP_ALLOC_OK 1
+#endif // !FLATBUFFERS_GENERAL_HEAP_ALLOC_OK
+
#ifndef FLATBUFFERS_HAS_NEW_STRTOD
// Modern (C++11) strtod and strtof functions are available for use.
// 1) nan/inf strings as argument of strtod;
@@ -284,7 +290,7 @@
#if ((__cplusplus >= 201703L) \
|| (defined(_MSVC_LANG) && (_MSVC_LANG >= 201703L)))
// All attributes unknown to an implementation are ignored without causing an error.
- #define FLATBUFFERS_ATTRIBUTE(attr) [[attr]]
+ #define FLATBUFFERS_ATTRIBUTE(attr) attr
#define FLATBUFFERS_FALLTHROUGH() [[fallthrough]]
#else
@@ -325,6 +331,14 @@
// We support aligning the contents of buffers up to this size.
#define FLATBUFFERS_MAX_ALIGNMENT 16
+/// @brief The length of a FlatBuffer file header.
+static const size_t kFileIdentifierLength = 4;
+
+inline bool VerifyAlignmentRequirements(size_t align, size_t min_align = 1) {
+ return (min_align <= align) && (align <= (FLATBUFFERS_MAX_ALIGNMENT)) &&
+ (align & (align - 1)) == 0; // must be power of 2
+}
+
#if defined(_MSC_VER)
#pragma warning(disable: 4351) // C4351: new behavior: elements of array ... will be default initialized
#pragma warning(push)
@@ -423,5 +437,38 @@
return ((~buf_size) + 1) & (scalar_size - 1);
}
+// Generic 'operator==' with conditional specialisations.
+// T e - new value of a scalar field.
+// T def - default of scalar (is known at compile-time).
+template<typename T> inline bool IsTheSameAs(T e, T def) { return e == def; }
+
+#if defined(FLATBUFFERS_NAN_DEFAULTS) && \
+ defined(FLATBUFFERS_HAS_NEW_STRTOD) && (FLATBUFFERS_HAS_NEW_STRTOD > 0)
+// Like `operator==(e, def)` with weak NaN if T=(float|double).
+template<typename T> inline bool IsFloatTheSameAs(T e, T def) {
+ return (e == def) || ((def != def) && (e != e));
+}
+template<> inline bool IsTheSameAs<float>(float e, float def) {
+ return IsFloatTheSameAs(e, def);
+}
+template<> inline bool IsTheSameAs<double>(double e, double def) {
+ return IsFloatTheSameAs(e, def);
+}
+#endif
+
+// Check 'v' is out of closed range [low; high].
+// Workaround for GCC warning [-Werror=type-limits]:
+// comparison is always true due to limited range of data type.
+template<typename T>
+inline bool IsOutRange(const T &v, const T &low, const T &high) {
+ return (v < low) || (high < v);
+}
+
+// Check 'v' is in closed range [low; high].
+template<typename T>
+inline bool IsInRange(const T &v, const T &low, const T &high) {
+ return !IsOutRange(v, low, high);
+}
+
} // namespace flatbuffers
#endif // FLATBUFFERS_BASE_H_
diff --git a/include/flatbuffers/bfbs_generator.h b/include/flatbuffers/bfbs_generator.h
new file mode 100644
index 0000000..08faeb3
--- /dev/null
+++ b/include/flatbuffers/bfbs_generator.h
@@ -0,0 +1,43 @@
+/*
+ * Copyright 2021 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_BFBS_GENERATOR_H_
+#define FLATBUFFERS_BFBS_GENERATOR_H_
+
+#include <cstdint>
+
+namespace flatbuffers {
+
+enum GeneratorStatus {
+ OK,
+ FAILED,
+ FAILED_VERIFICATION,
+};
+
+// A Flatbuffer Code Generator that receives a binary serialized reflection.fbs
+// and generates code from it.
+class BfbsGenerator {
+ public:
+ virtual ~BfbsGenerator() {}
+
+ // Generate code from the provided `buffer` of given `length`. The buffer is
+ // a serialized reflection.fbs.
+ virtual GeneratorStatus Generate(const uint8_t *buffer, int64_t length) = 0;
+};
+
+} // namespace flatbuffers
+
+#endif // FLATBUFFERS_BFBS_GENERATOR_H_
diff --git a/include/flatbuffers/buffer.h b/include/flatbuffers/buffer.h
new file mode 100644
index 0000000..e8d2ce9
--- /dev/null
+++ b/include/flatbuffers/buffer.h
@@ -0,0 +1,142 @@
+/*
+ * Copyright 2021 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_BUFFER_H_
+#define FLATBUFFERS_BUFFER_H_
+
+#include "flatbuffers/base.h"
+
+namespace flatbuffers {
+
+// Wrapper for uoffset_t to allow safe template specialization.
+// Value is allowed to be 0 to indicate a null object (see e.g. AddOffset).
+template<typename T> struct Offset {
+ uoffset_t o;
+ Offset() : o(0) {}
+ Offset(uoffset_t _o) : o(_o) {}
+ Offset<void> Union() const { return Offset<void>(o); }
+ bool IsNull() const { return !o; }
+};
+
+inline void EndianCheck() {
+ int endiantest = 1;
+ // If this fails, see FLATBUFFERS_LITTLEENDIAN above.
+ FLATBUFFERS_ASSERT(*reinterpret_cast<char *>(&endiantest) ==
+ FLATBUFFERS_LITTLEENDIAN);
+ (void)endiantest;
+}
+
+template<typename T> FLATBUFFERS_CONSTEXPR size_t AlignOf() {
+ // clang-format off
+ #ifdef _MSC_VER
+ return __alignof(T);
+ #else
+ #ifndef alignof
+ return __alignof__(T);
+ #else
+ return alignof(T);
+ #endif
+ #endif
+ // clang-format on
+}
+
+// Lexicographically compare two strings (possibly containing nulls), and
+// return true if the first is less than the second.
+static inline bool StringLessThan(const char *a_data, uoffset_t a_size,
+ const char *b_data, uoffset_t b_size) {
+ const auto cmp = memcmp(a_data, b_data, (std::min)(a_size, b_size));
+ return cmp == 0 ? a_size < b_size : cmp < 0;
+}
+
+// When we read serialized data from memory, in the case of most scalars,
+// we want to just read T, but in the case of Offset, we want to actually
+// perform the indirection and return a pointer.
+// The template specialization below does just that.
+// It is wrapped in a struct since function templates can't overload on the
+// return type like this.
+// The typedef is for the convenience of callers of this function
+// (avoiding the need for a trailing return decltype)
+template<typename T> struct IndirectHelper {
+ typedef T return_type;
+ typedef T mutable_return_type;
+ static const size_t element_stride = sizeof(T);
+ static return_type Read(const uint8_t *p, uoffset_t i) {
+ return EndianScalar((reinterpret_cast<const T *>(p))[i]);
+ }
+};
+template<typename T> struct IndirectHelper<Offset<T>> {
+ typedef const T *return_type;
+ typedef T *mutable_return_type;
+ static const size_t element_stride = sizeof(uoffset_t);
+ static return_type Read(const uint8_t *p, uoffset_t i) {
+ p += i * sizeof(uoffset_t);
+ return reinterpret_cast<return_type>(p + ReadScalar<uoffset_t>(p));
+ }
+};
+template<typename T> struct IndirectHelper<const T *> {
+ typedef const T *return_type;
+ typedef T *mutable_return_type;
+ static const size_t element_stride = sizeof(T);
+ static return_type Read(const uint8_t *p, uoffset_t i) {
+ return reinterpret_cast<const T *>(p + i * sizeof(T));
+ }
+};
+
+/// @brief Get a pointer to the the file_identifier section of the buffer.
+/// @return Returns a const char pointer to the start of the file_identifier
+/// characters in the buffer. The returned char * has length
+/// 'flatbuffers::FlatBufferBuilder::kFileIdentifierLength'.
+/// This function is UNDEFINED for FlatBuffers whose schema does not include
+/// a file_identifier (likely points at padding or the start of a the root
+/// vtable).
+inline const char *GetBufferIdentifier(const void *buf,
+ bool size_prefixed = false) {
+ return reinterpret_cast<const char *>(buf) +
+ ((size_prefixed) ? 2 * sizeof(uoffset_t) : sizeof(uoffset_t));
+}
+
+// Helper to see if the identifier in a buffer has the expected value.
+inline bool BufferHasIdentifier(const void *buf, const char *identifier,
+ bool size_prefixed = false) {
+ return strncmp(GetBufferIdentifier(buf, size_prefixed), identifier,
+ flatbuffers::kFileIdentifierLength) == 0;
+}
+
+/// @cond FLATBUFFERS_INTERNAL
+// Helpers to get a typed pointer to the root object contained in the buffer.
+template<typename T> T *GetMutableRoot(void *buf) {
+ EndianCheck();
+ return reinterpret_cast<T *>(
+ reinterpret_cast<uint8_t *>(buf) +
+ EndianScalar(*reinterpret_cast<uoffset_t *>(buf)));
+}
+
+template<typename T> T *GetMutableSizePrefixedRoot(void *buf) {
+ return GetMutableRoot<T>(reinterpret_cast<uint8_t *>(buf) +
+ sizeof(uoffset_t));
+}
+
+template<typename T> const T *GetRoot(const void *buf) {
+ return GetMutableRoot<T>(const_cast<void *>(buf));
+}
+
+template<typename T> const T *GetSizePrefixedRoot(const void *buf) {
+ return GetRoot<T>(reinterpret_cast<const uint8_t *>(buf) + sizeof(uoffset_t));
+}
+
+} // namespace flatbuffers
+
+#endif // FLATBUFFERS_BUFFER_H_
\ No newline at end of file
diff --git a/include/flatbuffers/buffer_ref.h b/include/flatbuffers/buffer_ref.h
new file mode 100644
index 0000000..ce30207
--- /dev/null
+++ b/include/flatbuffers/buffer_ref.h
@@ -0,0 +1,53 @@
+/*
+ * Copyright 2021 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_BUFFER_REF_H_
+#define FLATBUFFERS_BUFFER_REF_H_
+
+#include "flatbuffers/base.h"
+#include "flatbuffers/verifier.h"
+
+namespace flatbuffers {
+
+// Convenient way to bundle a buffer and its length, to pass it around
+// typed by its root.
+// A BufferRef does not own its buffer.
+struct BufferRefBase {}; // for std::is_base_of
+
+template<typename T> struct BufferRef : BufferRefBase {
+ BufferRef() : buf(nullptr), len(0), must_free(false) {}
+ BufferRef(uint8_t *_buf, uoffset_t _len)
+ : buf(_buf), len(_len), must_free(false) {}
+
+ ~BufferRef() {
+ if (must_free) free(buf);
+ }
+
+ const T *GetRoot() const { return flatbuffers::GetRoot<T>(buf); }
+
+ bool Verify() {
+ Verifier verifier(buf, len);
+ return verifier.VerifyBuffer<T>(nullptr);
+ }
+
+ uint8_t *buf;
+ uoffset_t len;
+ bool must_free;
+};
+
+} // namespace flatbuffers
+
+#endif // FLATBUFFERS_BUFFER_REF_H_
\ No newline at end of file
diff --git a/include/flatbuffers/code_generators.h b/include/flatbuffers/code_generators.h
index d64ab03..71ad0df 100644
--- a/include/flatbuffers/code_generators.h
+++ b/include/flatbuffers/code_generators.h
@@ -94,7 +94,8 @@
virtual bool generate() = 0;
static std::string NamespaceDir(const Parser &parser, const std::string &path,
- const Namespace &ns);
+ const Namespace &ns,
+ const bool dasherize = false);
std::string GeneratedFileName(const std::string &path,
const std::string &file_name,
@@ -116,7 +117,8 @@
BaseGenerator &operator=(const BaseGenerator &);
BaseGenerator(const BaseGenerator &);
- std::string NamespaceDir(const Namespace &ns) const;
+ std::string NamespaceDir(const Namespace &ns,
+ const bool dasherize = false) const;
static const char *FlatBuffersGeneratedWarning();
diff --git a/include/flatbuffers/default_allocator.h b/include/flatbuffers/default_allocator.h
new file mode 100644
index 0000000..8b173af
--- /dev/null
+++ b/include/flatbuffers/default_allocator.h
@@ -0,0 +1,64 @@
+/*
+ * Copyright 2021 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_DEFAULT_ALLOCATOR_H_
+#define FLATBUFFERS_DEFAULT_ALLOCATOR_H_
+
+#include "flatbuffers/allocator.h"
+#include "flatbuffers/base.h"
+
+namespace flatbuffers {
+
+// DefaultAllocator uses new/delete to allocate memory regions
+class DefaultAllocator : public Allocator {
+ public:
+ uint8_t *allocate(size_t size) FLATBUFFERS_OVERRIDE {
+ return new uint8_t[size];
+ }
+
+ void deallocate(uint8_t *p, size_t) FLATBUFFERS_OVERRIDE { delete[] p; }
+
+ static void dealloc(void *p, size_t) { delete[] static_cast<uint8_t *>(p); }
+};
+
+// These functions allow for a null allocator to mean use the default allocator,
+// as used by DetachedBuffer and vector_downward below.
+// This is to avoid having a statically or dynamically allocated default
+// allocator, or having to move it between the classes that may own it.
+inline uint8_t *Allocate(Allocator *allocator, size_t size) {
+ return allocator ? allocator->allocate(size)
+ : DefaultAllocator().allocate(size);
+}
+
+inline void Deallocate(Allocator *allocator, uint8_t *p, size_t size) {
+ if (allocator)
+ allocator->deallocate(p, size);
+ else
+ DefaultAllocator().deallocate(p, size);
+}
+
+inline uint8_t *ReallocateDownward(Allocator *allocator, uint8_t *old_p,
+ size_t old_size, size_t new_size,
+ size_t in_use_back, size_t in_use_front) {
+ return allocator ? allocator->reallocate_downward(old_p, old_size, new_size,
+ in_use_back, in_use_front)
+ : DefaultAllocator().reallocate_downward(
+ old_p, old_size, new_size, in_use_back, in_use_front);
+}
+
+} // namespace flatbuffers
+
+#endif // FLATBUFFERS_DEFAULT_ALLOCATOR_H_
\ No newline at end of file
diff --git a/include/flatbuffers/detached_buffer.h b/include/flatbuffers/detached_buffer.h
new file mode 100644
index 0000000..760a088
--- /dev/null
+++ b/include/flatbuffers/detached_buffer.h
@@ -0,0 +1,114 @@
+/*
+ * Copyright 2021 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_DETACHED_BUFFER_H_
+#define FLATBUFFERS_DETACHED_BUFFER_H_
+
+#include "flatbuffers/allocator.h"
+#include "flatbuffers/base.h"
+#include "flatbuffers/default_allocator.h"
+
+namespace flatbuffers {
+
+// DetachedBuffer is a finished flatbuffer memory region, detached from its
+// builder. The original memory region and allocator are also stored so that
+// the DetachedBuffer can manage the memory lifetime.
+class DetachedBuffer {
+ public:
+ DetachedBuffer()
+ : allocator_(nullptr),
+ own_allocator_(false),
+ buf_(nullptr),
+ reserved_(0),
+ cur_(nullptr),
+ size_(0) {}
+
+ DetachedBuffer(Allocator *allocator, bool own_allocator, uint8_t *buf,
+ size_t reserved, uint8_t *cur, size_t sz)
+ : allocator_(allocator),
+ own_allocator_(own_allocator),
+ buf_(buf),
+ reserved_(reserved),
+ cur_(cur),
+ size_(sz) {}
+
+ DetachedBuffer(DetachedBuffer &&other)
+ : allocator_(other.allocator_),
+ own_allocator_(other.own_allocator_),
+ buf_(other.buf_),
+ reserved_(other.reserved_),
+ cur_(other.cur_),
+ size_(other.size_) {
+ other.reset();
+ }
+
+ DetachedBuffer &operator=(DetachedBuffer &&other) {
+ if (this == &other) return *this;
+
+ destroy();
+
+ allocator_ = other.allocator_;
+ own_allocator_ = other.own_allocator_;
+ buf_ = other.buf_;
+ reserved_ = other.reserved_;
+ cur_ = other.cur_;
+ size_ = other.size_;
+
+ other.reset();
+
+ return *this;
+ }
+
+ ~DetachedBuffer() { destroy(); }
+
+ const uint8_t *data() const { return cur_; }
+
+ uint8_t *data() { return cur_; }
+
+ size_t size() const { return size_; }
+
+ // These may change access mode, leave these at end of public section
+ FLATBUFFERS_DELETE_FUNC(DetachedBuffer(const DetachedBuffer &other));
+ FLATBUFFERS_DELETE_FUNC(
+ DetachedBuffer &operator=(const DetachedBuffer &other));
+
+ protected:
+ Allocator *allocator_;
+ bool own_allocator_;
+ uint8_t *buf_;
+ size_t reserved_;
+ uint8_t *cur_;
+ size_t size_;
+
+ inline void destroy() {
+ if (buf_) Deallocate(allocator_, buf_, reserved_);
+ if (own_allocator_ && allocator_) { delete allocator_; }
+ reset();
+ }
+
+ inline void reset() {
+ allocator_ = nullptr;
+ own_allocator_ = false;
+ buf_ = nullptr;
+ reserved_ = 0;
+ cur_ = nullptr;
+ size_ = 0;
+ }
+};
+
+} // namespace flatbuffers
+
+#endif // FLATBUFFERS_DETACHED_BUFFER_H_
diff --git a/include/flatbuffers/flatbuffer_builder.h b/include/flatbuffers/flatbuffer_builder.h
new file mode 100644
index 0000000..9994193
--- /dev/null
+++ b/include/flatbuffers/flatbuffer_builder.h
@@ -0,0 +1,1197 @@
+/*
+ * Copyright 2021 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_FLATBUFFER_BUILDER_H_
+#define FLATBUFFERS_FLATBUFFER_BUILDER_H_
+
+#include <functional>
+
+#include "flatbuffers/allocator.h"
+#include "flatbuffers/array.h"
+#include "flatbuffers/base.h"
+#include "flatbuffers/buffer_ref.h"
+#include "flatbuffers/default_allocator.h"
+#include "flatbuffers/detached_buffer.h"
+#include "flatbuffers/stl_emulation.h"
+#include "flatbuffers/string.h"
+#include "flatbuffers/struct.h"
+#include "flatbuffers/table.h"
+#include "flatbuffers/vector.h"
+#include "flatbuffers/vector_downward.h"
+#include "flatbuffers/verifier.h"
+
+namespace flatbuffers {
+
+// Converts a Field ID to a virtual table offset.
+inline voffset_t FieldIndexToOffset(voffset_t field_id) {
+ // Should correspond to what EndTable() below builds up.
+ const int fixed_fields = 2; // Vtable size and Object Size.
+ return static_cast<voffset_t>((field_id + fixed_fields) * sizeof(voffset_t));
+}
+
+template<typename T, typename Alloc = std::allocator<T>>
+const T *data(const std::vector<T, Alloc> &v) {
+ // Eventually the returned pointer gets passed down to memcpy, so
+ // we need it to be non-null to avoid undefined behavior.
+ static uint8_t t;
+ return v.empty() ? reinterpret_cast<const T *>(&t) : &v.front();
+}
+template<typename T, typename Alloc = std::allocator<T>>
+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();
+}
+
+/// @addtogroup flatbuffers_cpp_api
+/// @{
+/// @class FlatBufferBuilder
+/// @brief Helper class to hold data needed in creation of a FlatBuffer.
+/// To serialize data, you typically call one of the `Create*()` functions in
+/// the generated code, which in turn call a sequence of `StartTable`/
+/// `PushElement`/`AddElement`/`EndTable`, or the builtin `CreateString`/
+/// `CreateVector` functions. Do this is depth-first order to build up a tree to
+/// the root. `Finish()` wraps up the buffer ready for transport.
+class FlatBufferBuilder {
+ public:
+ /// @brief Default constructor for FlatBufferBuilder.
+ /// @param[in] initial_size The initial size of the buffer, in bytes. Defaults
+ /// to `1024`.
+ /// @param[in] allocator An `Allocator` to use. If null will use
+ /// `DefaultAllocator`.
+ /// @param[in] own_allocator Whether the builder/vector should own the
+ /// allocator. Defaults to / `false`.
+ /// @param[in] buffer_minalign Force the buffer to be aligned to the given
+ /// minimum alignment upon reallocation. Only needed if you intend to store
+ /// types with custom alignment AND you wish to read the buffer in-place
+ /// directly after creation.
+ explicit FlatBufferBuilder(
+ size_t initial_size = 1024, Allocator *allocator = nullptr,
+ bool own_allocator = false,
+ size_t buffer_minalign = AlignOf<largest_scalar_t>())
+ : buf_(initial_size, allocator, own_allocator, buffer_minalign),
+ num_field_loc(0),
+ max_voffset_(0),
+ nested(false),
+ finished(false),
+ minalign_(1),
+ force_defaults_(false),
+ dedup_vtables_(true),
+ string_pool(nullptr) {
+ EndianCheck();
+ }
+
+ /// @brief Move constructor for FlatBufferBuilder.
+ FlatBufferBuilder(FlatBufferBuilder &&other)
+ : buf_(1024, nullptr, false, AlignOf<largest_scalar_t>()),
+ num_field_loc(0),
+ max_voffset_(0),
+ nested(false),
+ finished(false),
+ minalign_(1),
+ force_defaults_(false),
+ dedup_vtables_(true),
+ string_pool(nullptr) {
+ EndianCheck();
+ // Default construct and swap idiom.
+ // Lack of delegating constructors in vs2010 makes it more verbose than
+ // needed.
+ Swap(other);
+ }
+
+ /// @brief Move assignment operator for FlatBufferBuilder.
+ FlatBufferBuilder &operator=(FlatBufferBuilder &&other) {
+ // Move construct a temporary and swap idiom
+ FlatBufferBuilder temp(std::move(other));
+ Swap(temp);
+ return *this;
+ }
+
+ void Swap(FlatBufferBuilder &other) {
+ using std::swap;
+ buf_.swap(other.buf_);
+ swap(num_field_loc, other.num_field_loc);
+ swap(max_voffset_, other.max_voffset_);
+ swap(nested, other.nested);
+ swap(finished, other.finished);
+ swap(minalign_, other.minalign_);
+ swap(force_defaults_, other.force_defaults_);
+ swap(dedup_vtables_, other.dedup_vtables_);
+ swap(string_pool, other.string_pool);
+ }
+
+ ~FlatBufferBuilder() {
+ if (string_pool) delete string_pool;
+ }
+
+ void Reset() {
+ Clear(); // clear builder state
+ buf_.reset(); // deallocate buffer
+ }
+
+ /// @brief Reset all the state in this FlatBufferBuilder so it can be reused
+ /// to construct another buffer.
+ void Clear() {
+ ClearOffsets();
+ buf_.clear();
+ nested = false;
+ finished = false;
+ minalign_ = 1;
+ if (string_pool) string_pool->clear();
+ }
+
+ /// @brief The current size of the serialized buffer, counting from the end.
+ /// @return Returns an `uoffset_t` with the current size of the buffer.
+ uoffset_t GetSize() const { return buf_.size(); }
+
+ /// @brief Get the serialized buffer (after you call `Finish()`).
+ /// @return Returns an `uint8_t` pointer to the FlatBuffer data inside the
+ /// buffer.
+ uint8_t *GetBufferPointer() const {
+ Finished();
+ return buf_.data();
+ }
+
+ /// @brief Get the serialized buffer (after you call `Finish()`) as a span.
+ /// @return Returns a constructed flatbuffers::span that is a view over the
+ /// FlatBuffer data inside the buffer.
+ flatbuffers::span<uint8_t> GetBufferSpan() const {
+ Finished();
+ return flatbuffers::span<uint8_t>(buf_.data(), buf_.size());
+ }
+
+ /// @brief Get a pointer to an unfinished buffer.
+ /// @return Returns a `uint8_t` pointer to the unfinished buffer.
+ uint8_t *GetCurrentBufferPointer() const { return buf_.data(); }
+
+ /// @brief Get the released pointer to the serialized buffer.
+ /// @warning Do NOT attempt to use this FlatBufferBuilder afterwards!
+ /// @return A `FlatBuffer` that owns the buffer and its allocator and
+ /// behaves similar to a `unique_ptr` with a deleter.
+ FLATBUFFERS_ATTRIBUTE([[deprecated("use Release() instead")]])
+ DetachedBuffer ReleaseBufferPointer() {
+ Finished();
+ return buf_.release();
+ }
+
+ /// @brief Get the released DetachedBuffer.
+ /// @return A `DetachedBuffer` that owns the buffer and its allocator.
+ DetachedBuffer Release() {
+ Finished();
+ return buf_.release();
+ }
+
+ /// @brief Get the released pointer to the serialized buffer.
+ /// @param size The size of the memory block containing
+ /// the serialized `FlatBuffer`.
+ /// @param offset The offset from the released pointer where the finished
+ /// `FlatBuffer` starts.
+ /// @return A raw pointer to the start of the memory block containing
+ /// the serialized `FlatBuffer`.
+ /// @remark If the allocator is owned, it gets deleted when the destructor is
+ /// called..
+ uint8_t *ReleaseRaw(size_t &size, size_t &offset) {
+ Finished();
+ return buf_.release_raw(size, offset);
+ }
+
+ /// @brief get the minimum alignment this buffer needs to be accessed
+ /// properly. This is only known once all elements have been written (after
+ /// you call Finish()). You can use this information if you need to embed
+ /// a FlatBuffer in some other buffer, such that you can later read it
+ /// without first having to copy it into its own buffer.
+ size_t GetBufferMinAlignment() const {
+ Finished();
+ return minalign_;
+ }
+
+ /// @cond FLATBUFFERS_INTERNAL
+ void Finished() const {
+ // If you get this assert, you're attempting to get access a buffer
+ // which hasn't been finished yet. Be sure to call
+ // FlatBufferBuilder::Finish with your root table.
+ // If you really need to access an unfinished buffer, call
+ // GetCurrentBufferPointer instead.
+ FLATBUFFERS_ASSERT(finished);
+ }
+ /// @endcond
+
+ /// @brief In order to save space, fields that are set to their default value
+ /// don't get serialized into the buffer.
+ /// @param[in] fd When set to `true`, always serializes default values that
+ /// are set. Optional fields which are not set explicitly, will still not be
+ /// serialized.
+ void ForceDefaults(bool fd) { force_defaults_ = fd; }
+
+ /// @brief By default vtables are deduped in order to save space.
+ /// @param[in] dedup When set to `true`, dedup vtables.
+ void DedupVtables(bool dedup) { dedup_vtables_ = dedup; }
+
+ /// @cond FLATBUFFERS_INTERNAL
+ void Pad(size_t num_bytes) { buf_.fill(num_bytes); }
+
+ void TrackMinAlign(size_t elem_size) {
+ if (elem_size > minalign_) minalign_ = elem_size;
+ }
+
+ void Align(size_t elem_size) {
+ TrackMinAlign(elem_size);
+ buf_.fill(PaddingBytes(buf_.size(), elem_size));
+ }
+
+ void PushFlatBuffer(const uint8_t *bytes, size_t size) {
+ PushBytes(bytes, size);
+ finished = true;
+ }
+
+ void PushBytes(const uint8_t *bytes, size_t size) { buf_.push(bytes, size); }
+
+ void PopBytes(size_t amount) { buf_.pop(amount); }
+
+ template<typename T> void AssertScalarT() {
+ // The code assumes power of 2 sizes and endian-swap-ability.
+ static_assert(flatbuffers::is_scalar<T>::value, "T must be a scalar type");
+ }
+
+ // Write a single aligned scalar to the buffer
+ template<typename T> uoffset_t PushElement(T element) {
+ AssertScalarT<T>();
+ Align(sizeof(T));
+ buf_.push_small(EndianScalar(element));
+ return GetSize();
+ }
+
+ template<typename T> uoffset_t PushElement(Offset<T> off) {
+ // Special case for offsets: see ReferTo below.
+ return PushElement(ReferTo(off.o));
+ }
+
+ // When writing fields, we track where they are, so we can create correct
+ // vtables later.
+ void TrackField(voffset_t field, uoffset_t off) {
+ FieldLoc fl = { off, field };
+ buf_.scratch_push_small(fl);
+ num_field_loc++;
+ if (field > max_voffset_) { max_voffset_ = field; }
+ }
+
+ // Like PushElement, but additionally tracks the field this represents.
+ template<typename T> void AddElement(voffset_t field, T e, T def) {
+ // We don't serialize values equal to the default.
+ if (IsTheSameAs(e, def) && !force_defaults_) return;
+ TrackField(field, PushElement(e));
+ }
+
+ template<typename T> void AddElement(voffset_t field, T e) {
+ TrackField(field, PushElement(e));
+ }
+
+ template<typename T> void AddOffset(voffset_t field, Offset<T> off) {
+ if (off.IsNull()) return; // Don't store.
+ AddElement(field, ReferTo(off.o), static_cast<uoffset_t>(0));
+ }
+
+ template<typename T> void AddStruct(voffset_t field, const T *structptr) {
+ if (!structptr) return; // Default, don't store.
+ Align(AlignOf<T>());
+ buf_.push_small(*structptr);
+ TrackField(field, GetSize());
+ }
+
+ void AddStructOffset(voffset_t field, uoffset_t off) {
+ TrackField(field, off);
+ }
+
+ // Offsets initially are relative to the end of the buffer (downwards).
+ // This function converts them to be relative to the current location
+ // in the buffer (when stored here), pointing upwards.
+ uoffset_t ReferTo(uoffset_t off) {
+ // Align to ensure GetSize() below is correct.
+ Align(sizeof(uoffset_t));
+ // Offset must refer to something already in buffer.
+ const uoffset_t size = GetSize();
+ FLATBUFFERS_ASSERT(off && off <= size);
+ return size - off + static_cast<uoffset_t>(sizeof(uoffset_t));
+ }
+
+ void NotNested() {
+ // If you hit this, you're trying to construct a Table/Vector/String
+ // during the construction of its parent table (between the MyTableBuilder
+ // and table.Finish().
+ // Move the creation of these sub-objects to above the MyTableBuilder to
+ // not get this assert.
+ // Ignoring this assert may appear to work in simple cases, but the reason
+ // it is here is that storing objects in-line may cause vtable offsets
+ // to not fit anymore. It also leads to vtable duplication.
+ FLATBUFFERS_ASSERT(!nested);
+ // If you hit this, fields were added outside the scope of a table.
+ FLATBUFFERS_ASSERT(!num_field_loc);
+ }
+
+ // From generated code (or from the parser), we call StartTable/EndTable
+ // with a sequence of AddElement calls in between.
+ uoffset_t StartTable() {
+ NotNested();
+ nested = true;
+ return GetSize();
+ }
+
+ // This finishes one serialized object by generating the vtable if it's a
+ // table, comparing it against existing vtables, and writing the
+ // resulting vtable offset.
+ uoffset_t EndTable(uoffset_t start) {
+ // If you get this assert, a corresponding StartTable wasn't called.
+ FLATBUFFERS_ASSERT(nested);
+ // Write the vtable offset, which is the start of any Table.
+ // We fill it's value later.
+ auto vtableoffsetloc = PushElement<soffset_t>(0);
+ // Write a vtable, which consists entirely of voffset_t elements.
+ // It starts with the number of offsets, followed by a type id, followed
+ // by the offsets themselves. In reverse:
+ // Include space for the last offset and ensure empty tables have a
+ // minimum size.
+ max_voffset_ =
+ (std::max)(static_cast<voffset_t>(max_voffset_ + sizeof(voffset_t)),
+ FieldIndexToOffset(0));
+ buf_.fill_big(max_voffset_);
+ auto table_object_size = vtableoffsetloc - start;
+ // Vtable use 16bit offsets.
+ FLATBUFFERS_ASSERT(table_object_size < 0x10000);
+ WriteScalar<voffset_t>(buf_.data() + sizeof(voffset_t),
+ static_cast<voffset_t>(table_object_size));
+ WriteScalar<voffset_t>(buf_.data(), max_voffset_);
+ // Write the offsets into the table
+ for (auto it = buf_.scratch_end() - num_field_loc * sizeof(FieldLoc);
+ it < buf_.scratch_end(); it += sizeof(FieldLoc)) {
+ auto field_location = reinterpret_cast<FieldLoc *>(it);
+ auto pos = static_cast<voffset_t>(vtableoffsetloc - field_location->off);
+ // If this asserts, it means you've set a field twice.
+ FLATBUFFERS_ASSERT(
+ !ReadScalar<voffset_t>(buf_.data() + field_location->id));
+ WriteScalar<voffset_t>(buf_.data() + field_location->id, pos);
+ }
+ ClearOffsets();
+ auto vt1 = reinterpret_cast<voffset_t *>(buf_.data());
+ auto vt1_size = ReadScalar<voffset_t>(vt1);
+ auto vt_use = GetSize();
+ // See if we already have generated a vtable with this exact same
+ // layout before. If so, make it point to the old one, remove this one.
+ if (dedup_vtables_) {
+ for (auto it = buf_.scratch_data(); it < buf_.scratch_end();
+ it += sizeof(uoffset_t)) {
+ auto vt_offset_ptr = reinterpret_cast<uoffset_t *>(it);
+ auto vt2 = reinterpret_cast<voffset_t *>(buf_.data_at(*vt_offset_ptr));
+ auto vt2_size = ReadScalar<voffset_t>(vt2);
+ if (vt1_size != vt2_size || 0 != memcmp(vt2, vt1, vt1_size)) continue;
+ vt_use = *vt_offset_ptr;
+ buf_.pop(GetSize() - vtableoffsetloc);
+ break;
+ }
+ }
+ // If this is a new vtable, remember it.
+ if (vt_use == GetSize()) { buf_.scratch_push_small(vt_use); }
+ // Fill the vtable offset we created above.
+ // The offset points from the beginning of the object to where the
+ // vtable is stored.
+ // Offsets default direction is downward in memory for future format
+ // flexibility (storing all vtables at the start of the file).
+ WriteScalar(buf_.data_at(vtableoffsetloc),
+ static_cast<soffset_t>(vt_use) -
+ static_cast<soffset_t>(vtableoffsetloc));
+
+ nested = false;
+ return vtableoffsetloc;
+ }
+
+ FLATBUFFERS_ATTRIBUTE([[deprecated("call the version above instead")]])
+ uoffset_t EndTable(uoffset_t start, voffset_t /*numfields*/) {
+ return EndTable(start);
+ }
+
+ // This checks a required field has been set in a given table that has
+ // just been constructed.
+ template<typename T> void Required(Offset<T> table, voffset_t field);
+
+ uoffset_t StartStruct(size_t alignment) {
+ Align(alignment);
+ return GetSize();
+ }
+
+ uoffset_t EndStruct() { return GetSize(); }
+
+ void ClearOffsets() {
+ buf_.scratch_pop(num_field_loc * sizeof(FieldLoc));
+ num_field_loc = 0;
+ max_voffset_ = 0;
+ }
+
+ // Aligns such that when "len" bytes are written, an object can be written
+ // after it with "alignment" without padding.
+ void PreAlign(size_t len, size_t alignment) {
+ TrackMinAlign(alignment);
+ buf_.fill(PaddingBytes(GetSize() + len, alignment));
+ }
+ template<typename T> void PreAlign(size_t len) {
+ AssertScalarT<T>();
+ PreAlign(len, sizeof(T));
+ }
+ /// @endcond
+
+ /// @brief Store a string in the buffer, which can contain any binary data.
+ /// @param[in] str A const char pointer to the data to be stored as a string.
+ /// @param[in] len The number of bytes that should be stored from `str`.
+ /// @return Returns the offset in the buffer where the string starts.
+ Offset<String> CreateString(const char *str, size_t len) {
+ NotNested();
+ PreAlign<uoffset_t>(len + 1); // Always 0-terminated.
+ buf_.fill(1);
+ PushBytes(reinterpret_cast<const uint8_t *>(str), len);
+ PushElement(static_cast<uoffset_t>(len));
+ return Offset<String>(GetSize());
+ }
+
+ /// @brief Store a string in the buffer, which is null-terminated.
+ /// @param[in] str A const char pointer to a C-string to add to the buffer.
+ /// @return Returns the offset in the buffer where the string starts.
+ Offset<String> CreateString(const char *str) {
+ return CreateString(str, strlen(str));
+ }
+
+ /// @brief Store a string in the buffer, which is null-terminated.
+ /// @param[in] str A char pointer to a C-string to add to the buffer.
+ /// @return Returns the offset in the buffer where the string starts.
+ Offset<String> CreateString(char *str) {
+ return CreateString(str, strlen(str));
+ }
+
+ /// @brief Store a string in the buffer, which can contain any binary data.
+ /// @param[in] str A const reference to a std::string to store in the buffer.
+ /// @return Returns the offset in the buffer where the string starts.
+ Offset<String> CreateString(const std::string &str) {
+ return CreateString(str.c_str(), str.length());
+ }
+
+ // clang-format off
+ #ifdef FLATBUFFERS_HAS_STRING_VIEW
+ /// @brief Store a string in the buffer, which can contain any binary data.
+ /// @param[in] str A const string_view to copy in to the buffer.
+ /// @return Returns the offset in the buffer where the string starts.
+ Offset<String> CreateString(flatbuffers::string_view str) {
+ return CreateString(str.data(), str.size());
+ }
+ #endif // FLATBUFFERS_HAS_STRING_VIEW
+ // clang-format on
+
+ /// @brief Store a string in the buffer, which can contain any binary data.
+ /// @param[in] str A const pointer to a `String` struct to add to the buffer.
+ /// @return Returns the offset in the buffer where the string starts
+ Offset<String> CreateString(const String *str) {
+ return str ? CreateString(str->c_str(), str->size()) : 0;
+ }
+
+ /// @brief Store a string in the buffer, which can contain any binary data.
+ /// @param[in] str A const reference to a std::string like type with support
+ /// of T::c_str() and T::length() to store in the buffer.
+ /// @return Returns the offset in the buffer where the string starts.
+ template<typename T> Offset<String> CreateString(const T &str) {
+ return CreateString(str.c_str(), str.length());
+ }
+
+ /// @brief Store a string in the buffer, which can contain any binary data.
+ /// If a string with this exact contents has already been serialized before,
+ /// instead simply returns the offset of the existing string. This uses a map
+ /// stored on the heap, but only stores the numerical offsets.
+ /// @param[in] str A const char pointer to the data to be stored as a string.
+ /// @param[in] len The number of bytes that should be stored from `str`.
+ /// @return Returns the offset in the buffer where the string starts.
+ Offset<String> CreateSharedString(const char *str, size_t len) {
+ FLATBUFFERS_ASSERT(FLATBUFFERS_GENERAL_HEAP_ALLOC_OK);
+ if (!string_pool)
+ string_pool = new StringOffsetMap(StringOffsetCompare(buf_));
+ auto size_before_string = buf_.size();
+ // Must first serialize the string, since the set is all offsets into
+ // buffer.
+ auto off = CreateString(str, len);
+ auto it = string_pool->find(off);
+ // If it exists we reuse existing serialized data!
+ if (it != string_pool->end()) {
+ // We can remove the string we serialized.
+ buf_.pop(buf_.size() - size_before_string);
+ return *it;
+ }
+ // Record this string for future use.
+ string_pool->insert(off);
+ return off;
+ }
+
+#ifdef FLATBUFFERS_HAS_STRING_VIEW
+ /// @brief Store a string in the buffer, which can contain any binary data.
+ /// If a string with this exact contents has already been serialized before,
+ /// instead simply returns the offset of the existing string. This uses a map
+ /// stored on the heap, but only stores the numerical offsets.
+ /// @param[in] str A const std::string_view to store in the buffer.
+ /// @return Returns the offset in the buffer where the string starts
+ Offset<String> CreateSharedString(const flatbuffers::string_view str) {
+ return CreateSharedString(str.data(), str.size());
+ }
+#else
+ /// @brief Store a string in the buffer, which null-terminated.
+ /// If a string with this exact contents has already been serialized before,
+ /// instead simply returns the offset of the existing string. This uses a map
+ /// stored on the heap, but only stores the numerical offsets.
+ /// @param[in] str A const char pointer to a C-string to add to the buffer.
+ /// @return Returns the offset in the buffer where the string starts.
+ Offset<String> CreateSharedString(const char *str) {
+ return CreateSharedString(str, strlen(str));
+ }
+
+ /// @brief Store a string in the buffer, which can contain any binary data.
+ /// If a string with this exact contents has already been serialized before,
+ /// instead simply returns the offset of the existing string. This uses a map
+ /// stored on the heap, but only stores the numerical offsets.
+ /// @param[in] str A const reference to a std::string to store in the buffer.
+ /// @return Returns the offset in the buffer where the string starts.
+ Offset<String> CreateSharedString(const std::string &str) {
+ return CreateSharedString(str.c_str(), str.length());
+ }
+#endif
+
+ /// @brief Store a string in the buffer, which can contain any binary data.
+ /// If a string with this exact contents has already been serialized before,
+ /// instead simply returns the offset of the existing string. This uses a map
+ /// stored on the heap, but only stores the numerical offsets.
+ /// @param[in] str A const pointer to a `String` struct to add to the buffer.
+ /// @return Returns the offset in the buffer where the string starts
+ Offset<String> CreateSharedString(const String *str) {
+ return CreateSharedString(str->c_str(), str->size());
+ }
+
+ /// @cond FLATBUFFERS_INTERNAL
+ uoffset_t EndVector(size_t len) {
+ FLATBUFFERS_ASSERT(nested); // Hit if no corresponding StartVector.
+ nested = false;
+ return PushElement(static_cast<uoffset_t>(len));
+ }
+
+ void StartVector(size_t len, size_t elemsize) {
+ NotNested();
+ nested = true;
+ PreAlign<uoffset_t>(len * elemsize);
+ PreAlign(len * elemsize, elemsize); // Just in case elemsize > uoffset_t.
+ }
+
+ // Call this right before StartVector/CreateVector if you want to force the
+ // alignment to be something different than what the element size would
+ // normally dictate.
+ // This is useful when storing a nested_flatbuffer in a vector of bytes,
+ // or when storing SIMD floats, etc.
+ void ForceVectorAlignment(size_t len, size_t elemsize, size_t alignment) {
+ FLATBUFFERS_ASSERT(VerifyAlignmentRequirements(alignment));
+ PreAlign(len * elemsize, alignment);
+ }
+
+ // Similar to ForceVectorAlignment but for String fields.
+ void ForceStringAlignment(size_t len, size_t alignment) {
+ FLATBUFFERS_ASSERT(VerifyAlignmentRequirements(alignment));
+ PreAlign((len + 1) * sizeof(char), alignment);
+ }
+
+ /// @endcond
+
+ /// @brief Serialize an array into a FlatBuffer `vector`.
+ /// @tparam T The data type of the array elements.
+ /// @param[in] v A pointer to the array of type `T` to serialize into the
+ /// buffer as a `vector`.
+ /// @param[in] len The number of elements to serialize.
+ /// @return Returns a typed `Offset` into the serialized data indicating
+ /// where the vector is stored.
+ template<typename T> Offset<Vector<T>> CreateVector(const T *v, size_t len) {
+ // If this assert hits, you're specifying a template argument that is
+ // causing the wrong overload to be selected, remove it.
+ AssertScalarT<T>();
+ StartVector(len, sizeof(T));
+ if (len == 0) { return Offset<Vector<T>>(EndVector(len)); }
+ // clang-format off
+ #if FLATBUFFERS_LITTLEENDIAN
+ PushBytes(reinterpret_cast<const uint8_t *>(v), len * sizeof(T));
+ #else
+ if (sizeof(T) == 1) {
+ PushBytes(reinterpret_cast<const uint8_t *>(v), len);
+ } else {
+ for (auto i = len; i > 0; ) {
+ PushElement(v[--i]);
+ }
+ }
+ #endif
+ // clang-format on
+ return Offset<Vector<T>>(EndVector(len));
+ }
+
+ /// @brief Serialize an array like object into a FlatBuffer `vector`.
+ /// @tparam T The data type of the array elements.
+ /// @tparam C The type of the array.
+ /// @param[in] array A reference to an array like object of type `T` to
+ /// serialize into the buffer as a `vector`.
+ /// @return Returns a typed `Offset` into the serialized data indicating
+ /// where the vector is stored.
+ template<typename T, class C> Offset<Vector<T>> CreateVector(const C &array) {
+ return CreateVector(array.data(), array.size());
+ }
+
+ template<typename T>
+ Offset<Vector<Offset<T>>> CreateVector(const Offset<T> *v, size_t len) {
+ StartVector(len, sizeof(Offset<T>));
+ for (auto i = len; i > 0;) { PushElement(v[--i]); }
+ return Offset<Vector<Offset<T>>>(EndVector(len));
+ }
+
+ /// @brief Serialize a `std::vector` into a FlatBuffer `vector`.
+ /// @tparam T The data type of the `std::vector` elements.
+ /// @param v A const reference to the `std::vector` to serialize into the
+ /// buffer as a `vector`.
+ /// @return Returns a typed `Offset` into the serialized data indicating
+ /// where the vector is stored.
+ template<typename T, typename Alloc = std::allocator<T>>
+ Offset<Vector<T>> CreateVector(const std::vector<T, Alloc> &v) {
+ return CreateVector(data(v), v.size());
+ }
+
+ // vector<bool> may be implemented using a bit-set, so we can't access it as
+ // an array. Instead, read elements manually.
+ // Background: https://isocpp.org/blog/2012/11/on-vectorbool
+ Offset<Vector<uint8_t>> CreateVector(const std::vector<bool> &v) {
+ StartVector(v.size(), sizeof(uint8_t));
+ for (auto i = v.size(); i > 0;) {
+ PushElement(static_cast<uint8_t>(v[--i]));
+ }
+ return Offset<Vector<uint8_t>>(EndVector(v.size()));
+ }
+
+ /// @brief Serialize values returned by a function into a FlatBuffer `vector`.
+ /// This is a convenience function that takes care of iteration for you.
+ /// @tparam T The data type of the `std::vector` elements.
+ /// @param f A function that takes the current iteration 0..vector_size-1 and
+ /// returns any type that you can construct a FlatBuffers vector out of.
+ /// @return Returns a typed `Offset` into the serialized data indicating
+ /// where the vector is stored.
+ template<typename T>
+ Offset<Vector<T>> CreateVector(size_t vector_size,
+ const std::function<T(size_t i)> &f) {
+ FLATBUFFERS_ASSERT(FLATBUFFERS_GENERAL_HEAP_ALLOC_OK);
+ std::vector<T> elems(vector_size);
+ for (size_t i = 0; i < vector_size; i++) elems[i] = f(i);
+ return CreateVector(elems);
+ }
+
+ /// @brief Serialize values returned by a function into a FlatBuffer `vector`.
+ /// This is a convenience function that takes care of iteration for you. This
+ /// uses a vector stored on the heap to store the intermediate results of the
+ /// iteration.
+ /// @tparam T The data type of the `std::vector` elements.
+ /// @param f A function that takes the current iteration 0..vector_size-1,
+ /// and the state parameter returning any type that you can construct a
+ /// FlatBuffers vector out of.
+ /// @param state State passed to f.
+ /// @return Returns a typed `Offset` into the serialized data indicating
+ /// where the vector is stored.
+ template<typename T, typename F, typename S>
+ Offset<Vector<T>> CreateVector(size_t vector_size, F f, S *state) {
+ FLATBUFFERS_ASSERT(FLATBUFFERS_GENERAL_HEAP_ALLOC_OK);
+ std::vector<T> elems(vector_size);
+ for (size_t i = 0; i < vector_size; i++) elems[i] = f(i, state);
+ return CreateVector(elems);
+ }
+
+ /// @brief Serialize a `std::vector<std::string>` into a FlatBuffer `vector`.
+ /// This is a convenience function for a common case.
+ /// @param v A const reference to the `std::vector` to serialize into the
+ /// buffer as a `vector`.
+ /// @return Returns a typed `Offset` into the serialized data indicating
+ /// where the vector is stored.
+ template<typename Alloc = std::allocator<std::string>>
+ Offset<Vector<Offset<String>>> CreateVectorOfStrings(
+ const std::vector<std::string, Alloc> &v) {
+ return CreateVectorOfStrings(v.cbegin(), v.cend());
+ }
+
+ /// @brief Serialize a collection of Strings into a FlatBuffer `vector`.
+ /// This is a convenience function for a common case.
+ /// @param begin The begining iterator of the collection
+ /// @param end The ending iterator of the collection
+ /// @return Returns a typed `Offset` into the serialized data indicating
+ /// where the vector is stored.
+ template<class It>
+ Offset<Vector<Offset<String>>> CreateVectorOfStrings(It begin, It end) {
+ auto size = std::distance(begin, end);
+ auto scratch_buffer_usage = size * sizeof(Offset<String>);
+ // If there is not enough space to store the offsets, there definitely won't
+ // be enough space to store all the strings. So ensuring space for the
+ // scratch region is OK, for it it fails, it would have failed later.
+ buf_.ensure_space(scratch_buffer_usage);
+ for (auto it = begin; it != end; ++it) {
+ buf_.scratch_push_small(CreateString(*it));
+ }
+ StartVector(size, sizeof(Offset<String>));
+ for (auto i = 1; i <= size; i++) {
+ // Note we re-evaluate the buf location each iteration to account for any
+ // underlying buffer resizing that may occur.
+ PushElement(*reinterpret_cast<Offset<String> *>(
+ buf_.scratch_end() - i * sizeof(Offset<String>)));
+ }
+ buf_.scratch_pop(scratch_buffer_usage);
+ return Offset<Vector<Offset<String>>>(EndVector(size));
+ }
+
+ /// @brief Serialize an array of structs into a FlatBuffer `vector`.
+ /// @tparam T The data type of the struct array elements.
+ /// @param[in] v A pointer to the array of type `T` to serialize into the
+ /// buffer as a `vector`.
+ /// @param[in] len The number of elements to serialize.
+ /// @return Returns a typed `Offset` into the serialized data indicating
+ /// where the vector is stored.
+ template<typename T>
+ Offset<Vector<const T *>> CreateVectorOfStructs(const T *v, size_t len) {
+ StartVector(len * sizeof(T) / AlignOf<T>(), AlignOf<T>());
+ if (len > 0) {
+ PushBytes(reinterpret_cast<const uint8_t *>(v), sizeof(T) * len);
+ }
+ return Offset<Vector<const T *>>(EndVector(len));
+ }
+
+ /// @brief Serialize an array of native structs into a FlatBuffer `vector`.
+ /// @tparam T The data type of the struct array elements.
+ /// @tparam S The data type of the native struct array elements.
+ /// @param[in] v A pointer to the array of type `S` to serialize into the
+ /// buffer as a `vector`.
+ /// @param[in] len The number of elements to serialize.
+ /// @param[in] pack_func Pointer to a function to convert the native struct
+ /// to the FlatBuffer struct.
+ /// @return Returns a typed `Offset` into the serialized data indicating
+ /// where the vector is stored.
+ template<typename T, typename S>
+ Offset<Vector<const T *>> CreateVectorOfNativeStructs(
+ const S *v, size_t len, T (*const pack_func)(const S &)) {
+ FLATBUFFERS_ASSERT(pack_func);
+ auto structs = StartVectorOfStructs<T>(len);
+ for (size_t i = 0; i < len; i++) { structs[i] = pack_func(v[i]); }
+ return EndVectorOfStructs<T>(len);
+ }
+
+ /// @brief Serialize an array of native structs into a FlatBuffer `vector`.
+ /// @tparam T The data type of the struct array elements.
+ /// @tparam S The data type of the native struct array elements.
+ /// @param[in] v A pointer to the array of type `S` to serialize into the
+ /// buffer as a `vector`.
+ /// @param[in] len The number of elements to serialize.
+ /// @return Returns a typed `Offset` into the serialized data indicating
+ /// where the vector is stored.
+ template<typename T, typename S>
+ Offset<Vector<const T *>> CreateVectorOfNativeStructs(const S *v,
+ size_t len) {
+ extern T Pack(const S &);
+ return CreateVectorOfNativeStructs(v, len, Pack);
+ }
+
+ /// @brief Serialize an array of structs into a FlatBuffer `vector`.
+ /// @tparam T The data type of the struct array elements.
+ /// @param[in] filler A function that takes the current iteration
+ /// 0..vector_size-1 and a pointer to the struct that must be filled.
+ /// @return Returns a typed `Offset` into the serialized data indicating
+ /// where the vector is stored.
+ /// This is mostly useful when flatbuffers are generated with mutation
+ /// accessors.
+ template<typename T>
+ Offset<Vector<const T *>> CreateVectorOfStructs(
+ size_t vector_size, const std::function<void(size_t i, T *)> &filler) {
+ T *structs = StartVectorOfStructs<T>(vector_size);
+ for (size_t i = 0; i < vector_size; i++) {
+ filler(i, structs);
+ structs++;
+ }
+ return EndVectorOfStructs<T>(vector_size);
+ }
+
+ /// @brief Serialize an array of structs into a FlatBuffer `vector`.
+ /// @tparam T The data type of the struct array elements.
+ /// @param[in] f A function that takes the current iteration 0..vector_size-1,
+ /// a pointer to the struct that must be filled and the state argument.
+ /// @param[in] state Arbitrary state to pass to f.
+ /// @return Returns a typed `Offset` into the serialized data indicating
+ /// where the vector is stored.
+ /// This is mostly useful when flatbuffers are generated with mutation
+ /// accessors.
+ template<typename T, typename F, typename S>
+ Offset<Vector<const T *>> CreateVectorOfStructs(size_t vector_size, F f,
+ S *state) {
+ T *structs = StartVectorOfStructs<T>(vector_size);
+ for (size_t i = 0; i < vector_size; i++) {
+ f(i, structs, state);
+ structs++;
+ }
+ return EndVectorOfStructs<T>(vector_size);
+ }
+
+ /// @brief Serialize a `std::vector` of structs into a FlatBuffer `vector`.
+ /// @tparam T The data type of the `std::vector` struct elements.
+ /// @param[in] v A const reference to the `std::vector` of structs to
+ /// serialize into the buffer as a `vector`.
+ /// @return Returns a typed `Offset` into the serialized data indicating
+ /// where the vector is stored.
+ template<typename T, typename Alloc = std::allocator<T>>
+ Offset<Vector<const T *>> CreateVectorOfStructs(
+ const std::vector<T, Alloc> &v) {
+ return CreateVectorOfStructs(data(v), v.size());
+ }
+
+ /// @brief Serialize a `std::vector` of native structs into a FlatBuffer
+ /// `vector`.
+ /// @tparam T The data type of the `std::vector` struct elements.
+ /// @tparam S The data type of the `std::vector` native struct elements.
+ /// @param[in] v A const reference to the `std::vector` of structs to
+ /// serialize into the buffer as a `vector`.
+ /// @param[in] pack_func Pointer to a function to convert the native struct
+ /// to the FlatBuffer struct.
+ /// @return Returns a typed `Offset` into the serialized data indicating
+ /// where the vector is stored.
+ template<typename T, typename S, typename Alloc = std::allocator<T>>
+ Offset<Vector<const T *>> CreateVectorOfNativeStructs(
+ const std::vector<S, Alloc> &v, T (*const pack_func)(const S &)) {
+ return CreateVectorOfNativeStructs<T, S>(data(v), v.size(), pack_func);
+ }
+
+ /// @brief Serialize a `std::vector` of native structs into a FlatBuffer
+ /// `vector`.
+ /// @tparam T The data type of the `std::vector` struct elements.
+ /// @tparam S The data type of the `std::vector` native struct elements.
+ /// @param[in] v A const reference to the `std::vector` of structs to
+ /// serialize into the buffer as a `vector`.
+ /// @return Returns a typed `Offset` into the serialized data indicating
+ /// where the vector is stored.
+ template<typename T, typename S, typename Alloc = std::allocator<S>>
+ Offset<Vector<const T *>> CreateVectorOfNativeStructs(
+ const std::vector<S, Alloc> &v) {
+ return CreateVectorOfNativeStructs<T, S>(data(v), v.size());
+ }
+
+ /// @cond FLATBUFFERS_INTERNAL
+ template<typename T> struct StructKeyComparator {
+ bool operator()(const T &a, const T &b) const {
+ return a.KeyCompareLessThan(&b);
+ }
+ };
+ /// @endcond
+
+ /// @brief Serialize a `std::vector` of structs into a FlatBuffer `vector`
+ /// in sorted order.
+ /// @tparam T The data type of the `std::vector` struct elements.
+ /// @param[in] v A const reference to the `std::vector` of structs to
+ /// serialize into the buffer as a `vector`.
+ /// @return Returns a typed `Offset` into the serialized data indicating
+ /// where the vector is stored.
+ template<typename T, typename Alloc = std::allocator<T>>
+ Offset<Vector<const T *>> CreateVectorOfSortedStructs(
+ std::vector<T, Alloc> *v) {
+ return CreateVectorOfSortedStructs(data(*v), v->size());
+ }
+
+ /// @brief Serialize a `std::vector` of native structs into a FlatBuffer
+ /// `vector` in sorted order.
+ /// @tparam T The data type of the `std::vector` struct elements.
+ /// @tparam S The data type of the `std::vector` native struct elements.
+ /// @param[in] v A const reference to the `std::vector` of structs to
+ /// serialize into the buffer as a `vector`.
+ /// @return Returns a typed `Offset` into the serialized data indicating
+ /// where the vector is stored.
+ template<typename T, typename S, typename Alloc = std::allocator<T>>
+ Offset<Vector<const T *>> CreateVectorOfSortedNativeStructs(
+ std::vector<S, Alloc> *v) {
+ return CreateVectorOfSortedNativeStructs<T, S>(data(*v), v->size());
+ }
+
+ /// @brief Serialize an array of structs into a FlatBuffer `vector` in sorted
+ /// order.
+ /// @tparam T The data type of the struct array elements.
+ /// @param[in] v A pointer to the array of type `T` to serialize into the
+ /// buffer as a `vector`.
+ /// @param[in] len The number of elements to serialize.
+ /// @return Returns a typed `Offset` into the serialized data indicating
+ /// where the vector is stored.
+ template<typename T>
+ Offset<Vector<const T *>> CreateVectorOfSortedStructs(T *v, size_t len) {
+ std::stable_sort(v, v + len, StructKeyComparator<T>());
+ return CreateVectorOfStructs(v, len);
+ }
+
+ /// @brief Serialize an array of native structs into a FlatBuffer `vector` in
+ /// sorted order.
+ /// @tparam T The data type of the struct array elements.
+ /// @tparam S The data type of the native struct array elements.
+ /// @param[in] v A pointer to the array of type `S` to serialize into the
+ /// buffer as a `vector`.
+ /// @param[in] len The number of elements to serialize.
+ /// @return Returns a typed `Offset` into the serialized data indicating
+ /// where the vector is stored.
+ template<typename T, typename S>
+ Offset<Vector<const T *>> CreateVectorOfSortedNativeStructs(S *v,
+ size_t len) {
+ extern T Pack(const S &);
+ auto structs = StartVectorOfStructs<T>(len);
+ for (size_t i = 0; i < len; i++) { structs[i] = Pack(v[i]); }
+ std::stable_sort(structs, structs + len, StructKeyComparator<T>());
+ return EndVectorOfStructs<T>(len);
+ }
+
+ /// @cond FLATBUFFERS_INTERNAL
+ template<typename T> struct TableKeyComparator {
+ TableKeyComparator(vector_downward &buf) : buf_(buf) {}
+ TableKeyComparator(const TableKeyComparator &other) : buf_(other.buf_) {}
+ bool operator()(const Offset<T> &a, const Offset<T> &b) const {
+ auto table_a = reinterpret_cast<T *>(buf_.data_at(a.o));
+ auto table_b = reinterpret_cast<T *>(buf_.data_at(b.o));
+ return table_a->KeyCompareLessThan(table_b);
+ }
+ vector_downward &buf_;
+
+ private:
+ FLATBUFFERS_DELETE_FUNC(
+ TableKeyComparator &operator=(const TableKeyComparator &other));
+ };
+ /// @endcond
+
+ /// @brief Serialize an array of `table` offsets as a `vector` in the buffer
+ /// in sorted order.
+ /// @tparam T The data type that the offset refers to.
+ /// @param[in] v An array of type `Offset<T>` that contains the `table`
+ /// offsets to store in the buffer in sorted order.
+ /// @param[in] len The number of elements to store in the `vector`.
+ /// @return Returns a typed `Offset` into the serialized data indicating
+ /// where the vector is stored.
+ template<typename T>
+ Offset<Vector<Offset<T>>> CreateVectorOfSortedTables(Offset<T> *v,
+ size_t len) {
+ std::stable_sort(v, v + len, TableKeyComparator<T>(buf_));
+ return CreateVector(v, len);
+ }
+
+ /// @brief Serialize an array of `table` offsets as a `vector` in the buffer
+ /// in sorted order.
+ /// @tparam T The data type that the offset refers to.
+ /// @param[in] v An array of type `Offset<T>` that contains the `table`
+ /// offsets to store in the buffer in sorted order.
+ /// @return Returns a typed `Offset` into the serialized data indicating
+ /// where the vector is stored.
+ template<typename T, typename Alloc = std::allocator<T>>
+ Offset<Vector<Offset<T>>> CreateVectorOfSortedTables(
+ std::vector<Offset<T>, Alloc> *v) {
+ return CreateVectorOfSortedTables(data(*v), v->size());
+ }
+
+ /// @brief Specialized version of `CreateVector` for non-copying use cases.
+ /// Write the data any time later to the returned buffer pointer `buf`.
+ /// @param[in] len The number of elements to store in the `vector`.
+ /// @param[in] elemsize The size of each element in the `vector`.
+ /// @param[out] buf A pointer to a `uint8_t` pointer that can be
+ /// written to at a later time to serialize the data into a `vector`
+ /// in the buffer.
+ uoffset_t CreateUninitializedVector(size_t len, size_t elemsize,
+ uint8_t **buf) {
+ NotNested();
+ StartVector(len, elemsize);
+ buf_.make_space(len * elemsize);
+ auto vec_start = GetSize();
+ auto vec_end = EndVector(len);
+ *buf = buf_.data_at(vec_start);
+ return vec_end;
+ }
+
+ /// @brief Specialized version of `CreateVector` for non-copying use cases.
+ /// Write the data any time later to the returned buffer pointer `buf`.
+ /// @tparam T The data type of the data that will be stored in the buffer
+ /// as a `vector`.
+ /// @param[in] len The number of elements to store in the `vector`.
+ /// @param[out] buf A pointer to a pointer of type `T` that can be
+ /// written to at a later time to serialize the data into a `vector`
+ /// in the buffer.
+ template<typename T>
+ Offset<Vector<T>> CreateUninitializedVector(size_t len, T **buf) {
+ AssertScalarT<T>();
+ return CreateUninitializedVector(len, sizeof(T),
+ reinterpret_cast<uint8_t **>(buf));
+ }
+
+ template<typename T>
+ Offset<Vector<const T *>> CreateUninitializedVectorOfStructs(size_t len,
+ T **buf) {
+ return CreateUninitializedVector(len, sizeof(T),
+ reinterpret_cast<uint8_t **>(buf));
+ }
+
+ // @brief Create a vector of scalar type T given as input a vector of scalar
+ // type U, useful with e.g. pre "enum class" enums, or any existing scalar
+ // data of the wrong type.
+ template<typename T, typename U>
+ Offset<Vector<T>> CreateVectorScalarCast(const U *v, size_t len) {
+ AssertScalarT<T>();
+ AssertScalarT<U>();
+ StartVector(len, sizeof(T));
+ for (auto i = len; i > 0;) { PushElement(static_cast<T>(v[--i])); }
+ return Offset<Vector<T>>(EndVector(len));
+ }
+
+ /// @brief Write a struct by itself, typically to be part of a union.
+ template<typename T> Offset<const T *> CreateStruct(const T &structobj) {
+ NotNested();
+ Align(AlignOf<T>());
+ buf_.push_small(structobj);
+ return Offset<const T *>(GetSize());
+ }
+
+ /// @brief Finish serializing a buffer by writing the root offset.
+ /// @param[in] file_identifier If a `file_identifier` is given, the buffer
+ /// will be prefixed with a standard FlatBuffers file header.
+ template<typename T>
+ void Finish(Offset<T> root, const char *file_identifier = nullptr) {
+ Finish(root.o, file_identifier, false);
+ }
+
+ /// @brief Finish a buffer with a 32 bit size field pre-fixed (size of the
+ /// buffer following the size field). These buffers are NOT compatible
+ /// with standard buffers created by Finish, i.e. you can't call GetRoot
+ /// on them, you have to use GetSizePrefixedRoot instead.
+ /// All >32 bit quantities in this buffer will be aligned when the whole
+ /// size pre-fixed buffer is aligned.
+ /// These kinds of buffers are useful for creating a stream of FlatBuffers.
+ template<typename T>
+ void FinishSizePrefixed(Offset<T> root,
+ const char *file_identifier = nullptr) {
+ Finish(root.o, file_identifier, true);
+ }
+
+ void SwapBufAllocator(FlatBufferBuilder &other) {
+ buf_.swap_allocator(other.buf_);
+ }
+
+ /// @brief The length of a FlatBuffer file header.
+ static const size_t kFileIdentifierLength =
+ ::flatbuffers::kFileIdentifierLength;
+
+ protected:
+ // You shouldn't really be copying instances of this class.
+ FlatBufferBuilder(const FlatBufferBuilder &);
+ FlatBufferBuilder &operator=(const FlatBufferBuilder &);
+
+ void Finish(uoffset_t root, const char *file_identifier, bool size_prefix) {
+ NotNested();
+ buf_.clear_scratch();
+ // This will cause the whole buffer to be aligned.
+ PreAlign((size_prefix ? sizeof(uoffset_t) : 0) + sizeof(uoffset_t) +
+ (file_identifier ? kFileIdentifierLength : 0),
+ minalign_);
+ if (file_identifier) {
+ FLATBUFFERS_ASSERT(strlen(file_identifier) == kFileIdentifierLength);
+ PushBytes(reinterpret_cast<const uint8_t *>(file_identifier),
+ kFileIdentifierLength);
+ }
+ PushElement(ReferTo(root)); // Location of root.
+ if (size_prefix) { PushElement(GetSize()); }
+ finished = true;
+ }
+
+ struct FieldLoc {
+ uoffset_t off;
+ voffset_t id;
+ };
+
+ vector_downward buf_;
+
+ // Accumulating offsets of table members while it is being built.
+ // We store these in the scratch pad of buf_, after the vtable offsets.
+ uoffset_t num_field_loc;
+ // Track how much of the vtable is in use, so we can output the most compact
+ // possible vtable.
+ voffset_t max_voffset_;
+
+ // Ensure objects are not nested.
+ bool nested;
+
+ // Ensure the buffer is finished before it is being accessed.
+ bool finished;
+
+ size_t minalign_;
+
+ bool force_defaults_; // Serialize values equal to their defaults anyway.
+
+ bool dedup_vtables_;
+
+ struct StringOffsetCompare {
+ StringOffsetCompare(const vector_downward &buf) : buf_(&buf) {}
+ bool operator()(const Offset<String> &a, const Offset<String> &b) const {
+ auto stra = reinterpret_cast<const String *>(buf_->data_at(a.o));
+ auto strb = reinterpret_cast<const String *>(buf_->data_at(b.o));
+ return StringLessThan(stra->data(), stra->size(), strb->data(),
+ strb->size());
+ }
+ const vector_downward *buf_;
+ };
+
+ // For use with CreateSharedString. Instantiated on first use only.
+ typedef std::set<Offset<String>, StringOffsetCompare> StringOffsetMap;
+ StringOffsetMap *string_pool;
+
+ private:
+ // Allocates space for a vector of structures.
+ // Must be completed with EndVectorOfStructs().
+ template<typename T> T *StartVectorOfStructs(size_t vector_size) {
+ StartVector(vector_size * sizeof(T) / AlignOf<T>(), AlignOf<T>());
+ return reinterpret_cast<T *>(buf_.make_space(vector_size * sizeof(T)));
+ }
+
+ // End the vector of structures in the flatbuffers.
+ // Vector should have previously be started with StartVectorOfStructs().
+ template<typename T>
+ Offset<Vector<const T *>> EndVectorOfStructs(size_t vector_size) {
+ return Offset<Vector<const T *>>(EndVector(vector_size));
+ }
+};
+/// @}
+
+/// Helpers to get a typed pointer to objects that are currently being built.
+/// @warning Creating new objects will lead to reallocations and invalidates
+/// the pointer!
+template<typename T>
+T *GetMutableTemporaryPointer(FlatBufferBuilder &fbb, Offset<T> offset) {
+ return reinterpret_cast<T *>(fbb.GetCurrentBufferPointer() + fbb.GetSize() -
+ offset.o);
+}
+
+template<typename T>
+const T *GetTemporaryPointer(FlatBufferBuilder &fbb, Offset<T> offset) {
+ return GetMutableTemporaryPointer<T>(fbb, offset);
+}
+
+template<typename T>
+void FlatBufferBuilder::Required(Offset<T> table, voffset_t field) {
+ auto table_ptr = reinterpret_cast<const Table *>(buf_.data_at(table.o));
+ bool ok = table_ptr->GetOptionalFieldOffset(field) != 0;
+ // If this fails, the caller will show what field needs to be set.
+ FLATBUFFERS_ASSERT(ok);
+ (void)ok;
+}
+
+} // namespace flatbuffers
+
+#endif // FLATBUFFERS_VECTOR_DOWNWARD_H_
diff --git a/include/flatbuffers/flatbuffers.h b/include/flatbuffers/flatbuffers.h
index 1f25d4e..6421788 100644
--- a/include/flatbuffers/flatbuffers.h
+++ b/include/flatbuffers/flatbuffers.h
@@ -17,2628 +17,23 @@
#ifndef FLATBUFFERS_H_
#define FLATBUFFERS_H_
+// TODO: These includes are for mitigating the pains of users editing their
+// source because they relied on flatbuffers.h to include everything for them.
+#include "flatbuffers/array.h"
#include "flatbuffers/base.h"
+#include "flatbuffers/buffer.h"
+#include "flatbuffers/buffer_ref.h"
+#include "flatbuffers/detached_buffer.h"
+#include "flatbuffers/flatbuffer_builder.h"
#include "flatbuffers/stl_emulation.h"
-
-#ifndef FLATBUFFERS_CPP98_STL
- #include <functional>
-#endif
-
-#if defined(FLATBUFFERS_NAN_DEFAULTS)
-# include <cmath>
-#endif
+#include "flatbuffers/string.h"
+#include "flatbuffers/struct.h"
+#include "flatbuffers/table.h"
+#include "flatbuffers/vector.h"
+#include "flatbuffers/vector_downward.h"
+#include "flatbuffers/verifier.h"
namespace flatbuffers {
-// Generic 'operator==' with conditional specialisations.
-// T e - new value of a scalar field.
-// T def - default of scalar (is known at compile-time).
-template<typename T> inline bool IsTheSameAs(T e, T def) { return e == def; }
-
-#if defined(FLATBUFFERS_NAN_DEFAULTS) && \
- defined(FLATBUFFERS_HAS_NEW_STRTOD) && (FLATBUFFERS_HAS_NEW_STRTOD > 0)
-// Like `operator==(e, def)` with weak NaN if T=(float|double).
-template<typename T> inline bool IsFloatTheSameAs(T e, T def) {
- return (e == def) || ((def != def) && (e != e));
-}
-template<> inline bool IsTheSameAs<float>(float e, float def) {
- return IsFloatTheSameAs(e, def);
-}
-template<> inline bool IsTheSameAs<double>(double e, double def) {
- return IsFloatTheSameAs(e, def);
-}
-#endif
-
-// Check 'v' is out of closed range [low; high].
-// Workaround for GCC warning [-Werror=type-limits]:
-// comparison is always true due to limited range of data type.
-template<typename T>
-inline bool IsOutRange(const T &v, const T &low, const T &high) {
- return (v < low) || (high < v);
-}
-
-// Check 'v' is in closed range [low; high].
-template<typename T>
-inline bool IsInRange(const T &v, const T &low, const T &high) {
- return !IsOutRange(v, low, high);
-}
-
-// Wrapper for uoffset_t to allow safe template specialization.
-// Value is allowed to be 0 to indicate a null object (see e.g. AddOffset).
-template<typename T> struct Offset {
- uoffset_t o;
- Offset() : o(0) {}
- Offset(uoffset_t _o) : o(_o) {}
- Offset<void> Union() const { return Offset<void>(o); }
- bool IsNull() const { return !o; }
-};
-
-inline void EndianCheck() {
- int endiantest = 1;
- // If this fails, see FLATBUFFERS_LITTLEENDIAN above.
- FLATBUFFERS_ASSERT(*reinterpret_cast<char *>(&endiantest) ==
- FLATBUFFERS_LITTLEENDIAN);
- (void)endiantest;
-}
-
-template<typename T> FLATBUFFERS_CONSTEXPR size_t AlignOf() {
- // clang-format off
- #ifdef _MSC_VER
- return __alignof(T);
- #else
- #ifndef alignof
- return __alignof__(T);
- #else
- return alignof(T);
- #endif
- #endif
- // clang-format on
-}
-
-// When we read serialized data from memory, in the case of most scalars,
-// we want to just read T, but in the case of Offset, we want to actually
-// perform the indirection and return a pointer.
-// The template specialization below does just that.
-// It is wrapped in a struct since function templates can't overload on the
-// return type like this.
-// The typedef is for the convenience of callers of this function
-// (avoiding the need for a trailing return decltype)
-template<typename T> struct IndirectHelper {
- typedef T return_type;
- typedef T mutable_return_type;
- static const size_t element_stride = sizeof(T);
- static return_type Read(const uint8_t *p, uoffset_t i) {
- return EndianScalar((reinterpret_cast<const T *>(p))[i]);
- }
-};
-template<typename T> struct IndirectHelper<Offset<T>> {
- typedef const T *return_type;
- typedef T *mutable_return_type;
- static const size_t element_stride = sizeof(uoffset_t);
- static return_type Read(const uint8_t *p, uoffset_t i) {
- p += i * sizeof(uoffset_t);
- return reinterpret_cast<return_type>(p + ReadScalar<uoffset_t>(p));
- }
-};
-template<typename T> struct IndirectHelper<const T *> {
- typedef const T *return_type;
- typedef T *mutable_return_type;
- static const size_t element_stride = sizeof(T);
- static return_type Read(const uint8_t *p, uoffset_t i) {
- return reinterpret_cast<const T *>(p + i * sizeof(T));
- }
-};
-
-// An STL compatible iterator implementation for Vector below, effectively
-// calling Get() for every element.
-template<typename T, typename IT> struct VectorIterator {
- typedef std::random_access_iterator_tag iterator_category;
- typedef IT value_type;
- typedef ptrdiff_t difference_type;
- typedef IT *pointer;
- typedef IT &reference;
-
- VectorIterator(const uint8_t *data, uoffset_t i)
- : data_(data + IndirectHelper<T>::element_stride * i) {}
- VectorIterator(const VectorIterator &other) : data_(other.data_) {}
- VectorIterator() : data_(nullptr) {}
-
- VectorIterator &operator=(const VectorIterator &other) {
- data_ = other.data_;
- return *this;
- }
-
- // clang-format off
- #if !defined(FLATBUFFERS_CPP98_STL)
- VectorIterator &operator=(VectorIterator &&other) {
- data_ = other.data_;
- return *this;
- }
- #endif // !defined(FLATBUFFERS_CPP98_STL)
- // clang-format on
-
- bool operator==(const VectorIterator &other) const {
- return data_ == other.data_;
- }
-
- bool operator<(const VectorIterator &other) const {
- return data_ < other.data_;
- }
-
- bool operator!=(const VectorIterator &other) const {
- return data_ != other.data_;
- }
-
- difference_type operator-(const VectorIterator &other) const {
- return (data_ - other.data_) / IndirectHelper<T>::element_stride;
- }
-
- IT operator*() const { return IndirectHelper<T>::Read(data_, 0); }
-
- IT operator->() const { return IndirectHelper<T>::Read(data_, 0); }
-
- VectorIterator &operator++() {
- data_ += IndirectHelper<T>::element_stride;
- return *this;
- }
-
- VectorIterator operator++(int) {
- VectorIterator temp(data_, 0);
- data_ += IndirectHelper<T>::element_stride;
- return temp;
- }
-
- VectorIterator operator+(const uoffset_t &offset) const {
- return VectorIterator(data_ + offset * IndirectHelper<T>::element_stride,
- 0);
- }
-
- VectorIterator &operator+=(const uoffset_t &offset) {
- data_ += offset * IndirectHelper<T>::element_stride;
- return *this;
- }
-
- VectorIterator &operator--() {
- data_ -= IndirectHelper<T>::element_stride;
- return *this;
- }
-
- VectorIterator operator--(int) {
- VectorIterator temp(data_, 0);
- data_ -= IndirectHelper<T>::element_stride;
- return temp;
- }
-
- VectorIterator operator-(const uoffset_t &offset) const {
- return VectorIterator(data_ - offset * IndirectHelper<T>::element_stride,
- 0);
- }
-
- VectorIterator &operator-=(const uoffset_t &offset) {
- data_ -= offset * IndirectHelper<T>::element_stride;
- return *this;
- }
-
- private:
- const uint8_t *data_;
-};
-
-template<typename Iterator>
-struct VectorReverseIterator : public std::reverse_iterator<Iterator> {
- explicit VectorReverseIterator(Iterator iter)
- : std::reverse_iterator<Iterator>(iter) {}
-
- typename Iterator::value_type operator*() const {
- return *(std::reverse_iterator<Iterator>::current);
- }
-
- typename Iterator::value_type operator->() const {
- return *(std::reverse_iterator<Iterator>::current);
- }
-};
-
-struct String;
-
-// This is used as a helper type for accessing vectors.
-// Vector::data() assumes the vector elements start after the length field.
-template<typename T> class Vector {
- public:
- typedef VectorIterator<T, typename IndirectHelper<T>::mutable_return_type>
- iterator;
- typedef VectorIterator<T, typename IndirectHelper<T>::return_type>
- const_iterator;
- typedef VectorReverseIterator<iterator> reverse_iterator;
- typedef VectorReverseIterator<const_iterator> const_reverse_iterator;
-
- uoffset_t size() const { return EndianScalar(length_); }
-
- // Deprecated: use size(). Here for backwards compatibility.
- FLATBUFFERS_ATTRIBUTE(deprecated("use size() instead"))
- uoffset_t Length() const { return size(); }
-
- typedef typename IndirectHelper<T>::return_type return_type;
- typedef typename IndirectHelper<T>::mutable_return_type mutable_return_type;
-
- return_type Get(uoffset_t i) const {
- FLATBUFFERS_ASSERT(i < size());
- return IndirectHelper<T>::Read(Data(), i);
- }
-
- return_type operator[](uoffset_t i) const { return Get(i); }
-
- // If this is a Vector of enums, T will be its storage type, not the enum
- // type. This function makes it convenient to retrieve value with enum
- // type E.
- template<typename E> E GetEnum(uoffset_t i) const {
- return static_cast<E>(Get(i));
- }
-
- // If this a vector of unions, this does the cast for you. There's no check
- // to make sure this is the right type!
- template<typename U> const U *GetAs(uoffset_t i) const {
- return reinterpret_cast<const U *>(Get(i));
- }
-
- // If this a vector of unions, this does the cast for you. There's no check
- // to make sure this is actually a string!
- const String *GetAsString(uoffset_t i) const {
- return reinterpret_cast<const String *>(Get(i));
- }
-
- const void *GetStructFromOffset(size_t o) const {
- return reinterpret_cast<const void *>(Data() + o);
- }
-
- iterator begin() { return iterator(Data(), 0); }
- const_iterator begin() const { return const_iterator(Data(), 0); }
-
- iterator end() { return iterator(Data(), size()); }
- const_iterator end() const { return const_iterator(Data(), size()); }
-
- reverse_iterator rbegin() { return reverse_iterator(end() - 1); }
- const_reverse_iterator rbegin() const {
- return const_reverse_iterator(end() - 1);
- }
-
- reverse_iterator rend() { return reverse_iterator(begin() - 1); }
- const_reverse_iterator rend() const {
- return const_reverse_iterator(begin() - 1);
- }
-
- const_iterator cbegin() const { return begin(); }
-
- const_iterator cend() const { return end(); }
-
- const_reverse_iterator crbegin() const { return rbegin(); }
-
- const_reverse_iterator crend() const { return rend(); }
-
- // Change elements if you have a non-const pointer to this object.
- // Scalars only. See reflection.h, and the documentation.
- void Mutate(uoffset_t i, const T &val) {
- FLATBUFFERS_ASSERT(i < size());
- WriteScalar(data() + i, val);
- }
-
- // Change an element of a vector of tables (or strings).
- // "val" points to the new table/string, as you can obtain from
- // e.g. reflection::AddFlatBuffer().
- void MutateOffset(uoffset_t i, const uint8_t *val) {
- FLATBUFFERS_ASSERT(i < size());
- static_assert(sizeof(T) == sizeof(uoffset_t), "Unrelated types");
- WriteScalar(data() + i,
- static_cast<uoffset_t>(val - (Data() + i * sizeof(uoffset_t))));
- }
-
- // Get a mutable pointer to tables/strings inside this vector.
- mutable_return_type GetMutableObject(uoffset_t i) const {
- FLATBUFFERS_ASSERT(i < size());
- return const_cast<mutable_return_type>(IndirectHelper<T>::Read(Data(), i));
- }
-
- // The raw data in little endian format. Use with care.
- const uint8_t *Data() const {
- return reinterpret_cast<const uint8_t *>(&length_ + 1);
- }
-
- uint8_t *Data() { return reinterpret_cast<uint8_t *>(&length_ + 1); }
-
- // Similarly, but typed, much like std::vector::data
- const T *data() const { return reinterpret_cast<const T *>(Data()); }
- T *data() { return reinterpret_cast<T *>(Data()); }
-
- template<typename K> return_type LookupByKey(K key) const {
- void *search_result = std::bsearch(
- &key, Data(), size(), IndirectHelper<T>::element_stride, KeyCompare<K>);
-
- if (!search_result) {
- return nullptr; // Key not found.
- }
-
- const uint8_t *element = reinterpret_cast<const uint8_t *>(search_result);
-
- return IndirectHelper<T>::Read(element, 0);
- }
-
- protected:
- // This class is only used to access pre-existing data. Don't ever
- // try to construct these manually.
- Vector();
-
- uoffset_t length_;
-
- private:
- // This class is a pointer. Copying will therefore create an invalid object.
- // Private and unimplemented copy constructor.
- Vector(const Vector &);
- Vector &operator=(const Vector &);
-
- template<typename K> static int KeyCompare(const void *ap, const void *bp) {
- const K *key = reinterpret_cast<const K *>(ap);
- const uint8_t *data = reinterpret_cast<const uint8_t *>(bp);
- auto table = IndirectHelper<T>::Read(data, 0);
-
- // std::bsearch compares with the operands transposed, so we negate the
- // result here.
- return -table->KeyCompareWithValue(*key);
- }
-};
-
-// Represent a vector much like the template above, but in this case we
-// don't know what the element types are (used with reflection.h).
-class VectorOfAny {
- public:
- uoffset_t size() const { return EndianScalar(length_); }
-
- const uint8_t *Data() const {
- return reinterpret_cast<const uint8_t *>(&length_ + 1);
- }
- uint8_t *Data() { return reinterpret_cast<uint8_t *>(&length_ + 1); }
-
- protected:
- VectorOfAny();
-
- uoffset_t length_;
-
- private:
- VectorOfAny(const VectorOfAny &);
- VectorOfAny &operator=(const VectorOfAny &);
-};
-
-#ifndef FLATBUFFERS_CPP98_STL
-template<typename T, typename U>
-Vector<Offset<T>> *VectorCast(Vector<Offset<U>> *ptr) {
- static_assert(std::is_base_of<T, U>::value, "Unrelated types");
- return reinterpret_cast<Vector<Offset<T>> *>(ptr);
-}
-
-template<typename T, typename U>
-const Vector<Offset<T>> *VectorCast(const Vector<Offset<U>> *ptr) {
- static_assert(std::is_base_of<T, U>::value, "Unrelated types");
- return reinterpret_cast<const Vector<Offset<T>> *>(ptr);
-}
-#endif
-
-// Convenient helper function to get the length of any vector, regardless
-// of whether it is null or not (the field is not set).
-template<typename T> static inline size_t VectorLength(const Vector<T> *v) {
- return v ? v->size() : 0;
-}
-
-// This is used as a helper type for accessing arrays.
-template<typename T, uint16_t length> class Array {
- typedef
- typename flatbuffers::integral_constant<bool,
- flatbuffers::is_scalar<T>::value>
- scalar_tag;
- typedef
- typename flatbuffers::conditional<scalar_tag::value, T, const T *>::type
- IndirectHelperType;
-
- public:
- typedef uint16_t size_type;
- typedef typename IndirectHelper<IndirectHelperType>::return_type return_type;
- typedef VectorIterator<T, return_type> const_iterator;
- typedef VectorReverseIterator<const_iterator> const_reverse_iterator;
-
- FLATBUFFERS_CONSTEXPR uint16_t size() const { return length; }
-
- return_type Get(uoffset_t i) const {
- FLATBUFFERS_ASSERT(i < size());
- return IndirectHelper<IndirectHelperType>::Read(Data(), i);
- }
-
- return_type operator[](uoffset_t i) const { return Get(i); }
-
- // If this is a Vector of enums, T will be its storage type, not the enum
- // type. This function makes it convenient to retrieve value with enum
- // type E.
- template<typename E> E GetEnum(uoffset_t i) const {
- return static_cast<E>(Get(i));
- }
-
- const_iterator begin() const { return const_iterator(Data(), 0); }
- const_iterator end() const { return const_iterator(Data(), size()); }
-
- const_reverse_iterator rbegin() const {
- return const_reverse_iterator(end());
- }
- const_reverse_iterator rend() const { return const_reverse_iterator(end()); }
-
- const_iterator cbegin() const { return begin(); }
- const_iterator cend() const { return end(); }
-
- const_reverse_iterator crbegin() const { return rbegin(); }
- const_reverse_iterator crend() const { return rend(); }
-
- // Get a mutable pointer to elements inside this array.
- // This method used to mutate arrays of structs followed by a @p Mutate
- // operation. For primitive types use @p Mutate directly.
- // @warning Assignments and reads to/from the dereferenced pointer are not
- // automatically converted to the correct endianness.
- typename flatbuffers::conditional<scalar_tag::value, void, T *>::type
- GetMutablePointer(uoffset_t i) const {
- FLATBUFFERS_ASSERT(i < size());
- return const_cast<T *>(&data()[i]);
- }
-
- // Change elements if you have a non-const pointer to this object.
- void Mutate(uoffset_t i, const T &val) { MutateImpl(scalar_tag(), i, val); }
-
- // The raw data in little endian format. Use with care.
- const uint8_t *Data() const { return data_; }
-
- uint8_t *Data() { return data_; }
-
- // Similarly, but typed, much like std::vector::data
- const T *data() const { return reinterpret_cast<const T *>(Data()); }
- T *data() { return reinterpret_cast<T *>(Data()); }
-
- // Copy data from a span with endian conversion.
- // If this Array and the span overlap, the behavior is undefined.
- void CopyFromSpan(flatbuffers::span<const T, length> src) {
- const auto p1 = reinterpret_cast<const uint8_t *>(src.data());
- const auto p2 = Data();
- FLATBUFFERS_ASSERT(!(p1 >= p2 && p1 < (p2 + length)) &&
- !(p2 >= p1 && p2 < (p1 + length)));
- (void)p1;
- (void)p2;
-
- CopyFromSpanImpl(
- flatbuffers::integral_constant<bool,
- !scalar_tag::value || sizeof(T) == 1 || FLATBUFFERS_LITTLEENDIAN>(),
- src);
- }
-
- protected:
- void MutateImpl(flatbuffers::integral_constant<bool, true>, uoffset_t i,
- const T &val) {
- FLATBUFFERS_ASSERT(i < size());
- WriteScalar(data() + i, val);
- }
-
- void MutateImpl(flatbuffers::integral_constant<bool, false>, uoffset_t i,
- const T &val) {
- *(GetMutablePointer(i)) = val;
- }
-
- void CopyFromSpanImpl(flatbuffers::integral_constant<bool, true>,
- flatbuffers::span<const T, length> src) {
- // Use std::memcpy() instead of std::copy() to avoid preformance degradation
- // due to aliasing if T is char or unsigned char.
- // The size is known at compile time, so memcpy would be inlined.
- std::memcpy(data(), src.data(), length * sizeof(T));
- }
-
- // Copy data from flatbuffers::span with endian conversion.
- void CopyFromSpanImpl(flatbuffers::integral_constant<bool, false>,
- flatbuffers::span<const T, length> src) {
- for (size_type k = 0; k < length; k++) { Mutate(k, src[k]); }
- }
-
- // This class is only used to access pre-existing data. Don't ever
- // try to construct these manually.
- // 'constexpr' allows us to use 'size()' at compile time.
- // @note Must not use 'FLATBUFFERS_CONSTEXPR' here, as const is not allowed on
- // a constructor.
-#if defined(__cpp_constexpr)
- constexpr Array();
-#else
- Array();
-#endif
-
- uint8_t data_[length * sizeof(T)];
-
- private:
- // This class is a pointer. Copying will therefore create an invalid object.
- // Private and unimplemented copy constructor.
- Array(const Array &);
- Array &operator=(const Array &);
-};
-
-// Specialization for Array[struct] with access using Offset<void> pointer.
-// This specialization used by idl_gen_text.cpp.
-template<typename T, uint16_t length> class Array<Offset<T>, length> {
- static_assert(flatbuffers::is_same<T, void>::value, "unexpected type T");
-
- public:
- typedef const void *return_type;
-
- const uint8_t *Data() const { return data_; }
-
- // Make idl_gen_text.cpp::PrintContainer happy.
- return_type operator[](uoffset_t) const {
- FLATBUFFERS_ASSERT(false);
- return nullptr;
- }
-
- private:
- // This class is only used to access pre-existing data.
- Array();
- Array(const Array &);
- Array &operator=(const Array &);
-
- uint8_t data_[1];
-};
-
-// Cast a raw T[length] to a raw flatbuffers::Array<T, length>
-// without endian conversion. Use with care.
-template<typename T, uint16_t length>
-Array<T, length>& CastToArray(T (&arr)[length]) {
- return *reinterpret_cast<Array<T, length> *>(arr);
-}
-
-template<typename T, uint16_t length>
-const Array<T, length>& CastToArray(const T (&arr)[length]) {
- return *reinterpret_cast<const Array<T, length> *>(arr);
-}
-
-template<typename E, typename T, uint16_t length>
-Array<E, length> &CastToArrayOfEnum(T (&arr)[length]) {
- static_assert(sizeof(E) == sizeof(T), "invalid enum type E");
- return *reinterpret_cast<Array<E, length> *>(arr);
-}
-
-template<typename E, typename T, uint16_t length>
-const Array<E, length> &CastToArrayOfEnum(const T (&arr)[length]) {
- static_assert(sizeof(E) == sizeof(T), "invalid enum type E");
- return *reinterpret_cast<const Array<E, length> *>(arr);
-}
-
-// Lexicographically compare two strings (possibly containing nulls), and
-// return true if the first is less than the second.
-static inline bool StringLessThan(const char *a_data, uoffset_t a_size,
- const char *b_data, uoffset_t b_size) {
- const auto cmp = memcmp(a_data, b_data, (std::min)(a_size, b_size));
- return cmp == 0 ? a_size < b_size : cmp < 0;
-}
-
-struct String : public Vector<char> {
- const char *c_str() const { return reinterpret_cast<const char *>(Data()); }
- std::string str() const { return std::string(c_str(), size()); }
-
- // clang-format off
- #ifdef FLATBUFFERS_HAS_STRING_VIEW
- flatbuffers::string_view string_view() const {
- return flatbuffers::string_view(c_str(), size());
- }
- #endif // FLATBUFFERS_HAS_STRING_VIEW
- // clang-format on
-
- bool operator<(const String &o) const {
- return StringLessThan(this->data(), this->size(), o.data(), o.size());
- }
-};
-
-// Convenience function to get std::string from a String returning an empty
-// string on null pointer.
-static inline std::string GetString(const String *str) {
- return str ? str->str() : "";
-}
-
-// Convenience function to get char* from a String returning an empty string on
-// null pointer.
-static inline const char *GetCstring(const String *str) {
- return str ? str->c_str() : "";
-}
-
-#ifdef FLATBUFFERS_HAS_STRING_VIEW
-// Convenience function to get string_view from a String returning an empty
-// string_view on null pointer.
-static inline flatbuffers::string_view GetStringView(const String *str) {
- return str ? str->string_view() : flatbuffers::string_view();
-}
-#endif // FLATBUFFERS_HAS_STRING_VIEW
-
-// Allocator interface. This is flatbuffers-specific and meant only for
-// `vector_downward` usage.
-class Allocator {
- public:
- virtual ~Allocator() {}
-
- // Allocate `size` bytes of memory.
- virtual uint8_t *allocate(size_t size) = 0;
-
- // Deallocate `size` bytes of memory at `p` allocated by this allocator.
- virtual void deallocate(uint8_t *p, size_t size) = 0;
-
- // Reallocate `new_size` bytes of memory, replacing the old region of size
- // `old_size` at `p`. In contrast to a normal realloc, this grows downwards,
- // and is intended specifcally for `vector_downward` use.
- // `in_use_back` and `in_use_front` indicate how much of `old_size` is
- // actually in use at each end, and needs to be copied.
- virtual uint8_t *reallocate_downward(uint8_t *old_p, size_t old_size,
- size_t new_size, size_t in_use_back,
- size_t in_use_front) {
- FLATBUFFERS_ASSERT(new_size > old_size); // vector_downward only grows
- uint8_t *new_p = allocate(new_size);
- memcpy_downward(old_p, old_size, new_p, new_size, in_use_back,
- in_use_front);
- deallocate(old_p, old_size);
- return new_p;
- }
-
- protected:
- // Called by `reallocate_downward` to copy memory from `old_p` of `old_size`
- // to `new_p` of `new_size`. Only memory of size `in_use_front` and
- // `in_use_back` will be copied from the front and back of the old memory
- // allocation.
- void memcpy_downward(uint8_t *old_p, size_t old_size, uint8_t *new_p,
- size_t new_size, size_t in_use_back,
- size_t in_use_front) {
- memcpy(new_p + new_size - in_use_back, old_p + old_size - in_use_back,
- in_use_back);
- memcpy(new_p, old_p, in_use_front);
- }
-};
-
-// DefaultAllocator uses new/delete to allocate memory regions
-class DefaultAllocator : public Allocator {
- public:
- uint8_t *allocate(size_t size) FLATBUFFERS_OVERRIDE {
- return new uint8_t[size];
- }
-
- void deallocate(uint8_t *p, size_t) FLATBUFFERS_OVERRIDE { delete[] p; }
-
- static void dealloc(void *p, size_t) { delete[] static_cast<uint8_t *>(p); }
-};
-
-// These functions allow for a null allocator to mean use the default allocator,
-// as used by DetachedBuffer and vector_downward below.
-// This is to avoid having a statically or dynamically allocated default
-// allocator, or having to move it between the classes that may own it.
-inline uint8_t *Allocate(Allocator *allocator, size_t size) {
- return allocator ? allocator->allocate(size)
- : DefaultAllocator().allocate(size);
-}
-
-inline void Deallocate(Allocator *allocator, uint8_t *p, size_t size) {
- if (allocator)
- allocator->deallocate(p, size);
- else
- DefaultAllocator().deallocate(p, size);
-}
-
-inline uint8_t *ReallocateDownward(Allocator *allocator, uint8_t *old_p,
- size_t old_size, size_t new_size,
- size_t in_use_back, size_t in_use_front) {
- return allocator ? allocator->reallocate_downward(old_p, old_size, new_size,
- in_use_back, in_use_front)
- : DefaultAllocator().reallocate_downward(
- old_p, old_size, new_size, in_use_back, in_use_front);
-}
-
-// DetachedBuffer is a finished flatbuffer memory region, detached from its
-// builder. The original memory region and allocator are also stored so that
-// the DetachedBuffer can manage the memory lifetime.
-class DetachedBuffer {
- public:
- DetachedBuffer()
- : allocator_(nullptr),
- own_allocator_(false),
- buf_(nullptr),
- reserved_(0),
- cur_(nullptr),
- size_(0) {}
-
- DetachedBuffer(Allocator *allocator, bool own_allocator, uint8_t *buf,
- size_t reserved, uint8_t *cur, size_t sz)
- : allocator_(allocator),
- own_allocator_(own_allocator),
- buf_(buf),
- reserved_(reserved),
- cur_(cur),
- size_(sz) {}
-
- // clang-format off
- #if !defined(FLATBUFFERS_CPP98_STL)
- // clang-format on
- DetachedBuffer(DetachedBuffer &&other)
- : allocator_(other.allocator_),
- own_allocator_(other.own_allocator_),
- buf_(other.buf_),
- reserved_(other.reserved_),
- cur_(other.cur_),
- size_(other.size_) {
- other.reset();
- }
- // clang-format off
- #endif // !defined(FLATBUFFERS_CPP98_STL)
- // clang-format on
-
- // clang-format off
- #if !defined(FLATBUFFERS_CPP98_STL)
- // clang-format on
- DetachedBuffer &operator=(DetachedBuffer &&other) {
- if (this == &other) return *this;
-
- destroy();
-
- allocator_ = other.allocator_;
- own_allocator_ = other.own_allocator_;
- buf_ = other.buf_;
- reserved_ = other.reserved_;
- cur_ = other.cur_;
- size_ = other.size_;
-
- other.reset();
-
- return *this;
- }
- // clang-format off
- #endif // !defined(FLATBUFFERS_CPP98_STL)
- // clang-format on
-
- ~DetachedBuffer() { destroy(); }
-
- const uint8_t *data() const { return cur_; }
-
- uint8_t *data() { return cur_; }
-
- size_t size() const { return size_; }
-
- // clang-format off
- #if 0 // disabled for now due to the ordering of classes in this header
- template <class T>
- bool Verify() const {
- Verifier verifier(data(), size());
- return verifier.Verify<T>(nullptr);
- }
-
- template <class T>
- const T* GetRoot() const {
- return flatbuffers::GetRoot<T>(data());
- }
-
- template <class T>
- T* GetRoot() {
- return flatbuffers::GetRoot<T>(data());
- }
- #endif
- // clang-format on
-
- // clang-format off
- #if !defined(FLATBUFFERS_CPP98_STL)
- // clang-format on
- // These may change access mode, leave these at end of public section
- FLATBUFFERS_DELETE_FUNC(DetachedBuffer(const DetachedBuffer &other))
- FLATBUFFERS_DELETE_FUNC(
- DetachedBuffer &operator=(const DetachedBuffer &other))
- // clang-format off
- #endif // !defined(FLATBUFFERS_CPP98_STL)
- // clang-format on
-
- protected:
- Allocator *allocator_;
- bool own_allocator_;
- uint8_t *buf_;
- size_t reserved_;
- uint8_t *cur_;
- size_t size_;
-
- inline void destroy() {
- if (buf_) Deallocate(allocator_, buf_, reserved_);
- if (own_allocator_ && allocator_) { delete allocator_; }
- reset();
- }
-
- inline void reset() {
- allocator_ = nullptr;
- own_allocator_ = false;
- buf_ = nullptr;
- reserved_ = 0;
- cur_ = nullptr;
- size_ = 0;
- }
-};
-
-// This is a minimal replication of std::vector<uint8_t> functionality,
-// except growing from higher to lower addresses. i.e push_back() inserts data
-// in the lowest address in the vector.
-// Since this vector leaves the lower part unused, we support a "scratch-pad"
-// that can be stored there for temporary data, to share the allocated space.
-// Essentially, this supports 2 std::vectors in a single buffer.
-class vector_downward {
- public:
- explicit vector_downward(size_t initial_size, Allocator *allocator,
- bool own_allocator, size_t buffer_minalign)
- : allocator_(allocator),
- own_allocator_(own_allocator),
- initial_size_(initial_size),
- buffer_minalign_(buffer_minalign),
- reserved_(0),
- buf_(nullptr),
- cur_(nullptr),
- scratch_(nullptr) {}
-
- // clang-format off
- #if !defined(FLATBUFFERS_CPP98_STL)
- vector_downward(vector_downward &&other)
- #else
- vector_downward(vector_downward &other)
- #endif // defined(FLATBUFFERS_CPP98_STL)
- // clang-format on
- : allocator_(other.allocator_),
- own_allocator_(other.own_allocator_),
- initial_size_(other.initial_size_),
- buffer_minalign_(other.buffer_minalign_),
- reserved_(other.reserved_),
- buf_(other.buf_),
- cur_(other.cur_),
- scratch_(other.scratch_) {
- // No change in other.allocator_
- // No change in other.initial_size_
- // No change in other.buffer_minalign_
- other.own_allocator_ = false;
- other.reserved_ = 0;
- other.buf_ = nullptr;
- other.cur_ = nullptr;
- other.scratch_ = nullptr;
- }
-
- // clang-format off
- #if !defined(FLATBUFFERS_CPP98_STL)
- // clang-format on
- vector_downward &operator=(vector_downward &&other) {
- // Move construct a temporary and swap idiom
- vector_downward temp(std::move(other));
- swap(temp);
- return *this;
- }
- // clang-format off
- #endif // defined(FLATBUFFERS_CPP98_STL)
- // clang-format on
-
- ~vector_downward() {
- clear_buffer();
- clear_allocator();
- }
-
- void reset() {
- clear_buffer();
- clear();
- }
-
- void clear() {
- if (buf_) {
- cur_ = buf_ + reserved_;
- } else {
- reserved_ = 0;
- cur_ = nullptr;
- }
- clear_scratch();
- }
-
- void clear_scratch() { scratch_ = buf_; }
-
- void clear_allocator() {
- if (own_allocator_ && allocator_) { delete allocator_; }
- allocator_ = nullptr;
- own_allocator_ = false;
- }
-
- void clear_buffer() {
- if (buf_) Deallocate(allocator_, buf_, reserved_);
- buf_ = nullptr;
- }
-
- // Relinquish the pointer to the caller.
- uint8_t *release_raw(size_t &allocated_bytes, size_t &offset) {
- auto *buf = buf_;
- allocated_bytes = reserved_;
- offset = static_cast<size_t>(cur_ - buf_);
-
- // release_raw only relinquishes the buffer ownership.
- // Does not deallocate or reset the allocator. Destructor will do that.
- buf_ = nullptr;
- clear();
- return buf;
- }
-
- // Relinquish the pointer to the caller.
- DetachedBuffer release() {
- // allocator ownership (if any) is transferred to DetachedBuffer.
- DetachedBuffer fb(allocator_, own_allocator_, buf_, reserved_, cur_,
- size());
- if (own_allocator_) {
- allocator_ = nullptr;
- own_allocator_ = false;
- }
- buf_ = nullptr;
- clear();
- return fb;
- }
-
- size_t ensure_space(size_t len) {
- FLATBUFFERS_ASSERT(cur_ >= scratch_ && scratch_ >= buf_);
- if (len > static_cast<size_t>(cur_ - scratch_)) { reallocate(len); }
- // Beyond this, signed offsets may not have enough range:
- // (FlatBuffers > 2GB not supported).
- FLATBUFFERS_ASSERT(size() < FLATBUFFERS_MAX_BUFFER_SIZE);
- return len;
- }
-
- inline uint8_t *make_space(size_t len) {
- size_t space = ensure_space(len);
- cur_ -= space;
- return cur_;
- }
-
- // Returns nullptr if using the DefaultAllocator.
- Allocator *get_custom_allocator() { return allocator_; }
-
- uoffset_t size() const {
- return static_cast<uoffset_t>(reserved_ - static_cast<size_t>(cur_ - buf_));
- }
-
- uoffset_t scratch_size() const {
- return static_cast<uoffset_t>(scratch_ - buf_);
- }
-
- size_t capacity() const { return reserved_; }
-
- uint8_t *data() const {
- FLATBUFFERS_ASSERT(cur_);
- return cur_;
- }
-
- uint8_t *scratch_data() const {
- FLATBUFFERS_ASSERT(buf_);
- return buf_;
- }
-
- uint8_t *scratch_end() const {
- FLATBUFFERS_ASSERT(scratch_);
- return scratch_;
- }
-
- uint8_t *data_at(size_t offset) const { return buf_ + reserved_ - offset; }
-
- void push(const uint8_t *bytes, size_t num) {
- if (num > 0) { memcpy(make_space(num), bytes, num); }
- }
-
- // Specialized version of push() that avoids memcpy call for small data.
- template<typename T> void push_small(const T &little_endian_t) {
- make_space(sizeof(T));
- *reinterpret_cast<T *>(cur_) = little_endian_t;
- }
-
- template<typename T> void scratch_push_small(const T &t) {
- ensure_space(sizeof(T));
- *reinterpret_cast<T *>(scratch_) = t;
- scratch_ += sizeof(T);
- }
-
- // fill() is most frequently called with small byte counts (<= 4),
- // which is why we're using loops rather than calling memset.
- void fill(size_t zero_pad_bytes) {
- make_space(zero_pad_bytes);
- for (size_t i = 0; i < zero_pad_bytes; i++) cur_[i] = 0;
- }
-
- // Version for when we know the size is larger.
- // Precondition: zero_pad_bytes > 0
- void fill_big(size_t zero_pad_bytes) {
- memset(make_space(zero_pad_bytes), 0, zero_pad_bytes);
- }
-
- void pop(size_t bytes_to_remove) { cur_ += bytes_to_remove; }
- void scratch_pop(size_t bytes_to_remove) { scratch_ -= bytes_to_remove; }
-
- void swap(vector_downward &other) {
- using std::swap;
- swap(allocator_, other.allocator_);
- swap(own_allocator_, other.own_allocator_);
- swap(initial_size_, other.initial_size_);
- swap(buffer_minalign_, other.buffer_minalign_);
- swap(reserved_, other.reserved_);
- swap(buf_, other.buf_);
- swap(cur_, other.cur_);
- swap(scratch_, other.scratch_);
- }
-
- void swap_allocator(vector_downward &other) {
- using std::swap;
- swap(allocator_, other.allocator_);
- swap(own_allocator_, other.own_allocator_);
- }
-
- private:
- // You shouldn't really be copying instances of this class.
- FLATBUFFERS_DELETE_FUNC(vector_downward(const vector_downward &))
- FLATBUFFERS_DELETE_FUNC(vector_downward &operator=(const vector_downward &))
-
- Allocator *allocator_;
- bool own_allocator_;
- size_t initial_size_;
- size_t buffer_minalign_;
- size_t reserved_;
- uint8_t *buf_;
- uint8_t *cur_; // Points at location between empty (below) and used (above).
- uint8_t *scratch_; // Points to the end of the scratchpad in use.
-
- void reallocate(size_t len) {
- auto old_reserved = reserved_;
- auto old_size = size();
- auto old_scratch_size = scratch_size();
- reserved_ +=
- (std::max)(len, old_reserved ? old_reserved / 2 : initial_size_);
- reserved_ = (reserved_ + buffer_minalign_ - 1) & ~(buffer_minalign_ - 1);
- if (buf_) {
- buf_ = ReallocateDownward(allocator_, buf_, old_reserved, reserved_,
- old_size, old_scratch_size);
- } else {
- buf_ = Allocate(allocator_, reserved_);
- }
- cur_ = buf_ + reserved_ - old_size;
- scratch_ = buf_ + old_scratch_size;
- }
-};
-
-// Converts a Field ID to a virtual table offset.
-inline voffset_t FieldIndexToOffset(voffset_t field_id) {
- // Should correspond to what EndTable() below builds up.
- const int fixed_fields = 2; // Vtable size and Object Size.
- return static_cast<voffset_t>((field_id + fixed_fields) * sizeof(voffset_t));
-}
-
-template<typename T, typename Alloc>
-const T *data(const std::vector<T, Alloc> &v) {
- // Eventually the returned pointer gets passed down to memcpy, so
- // we need it to be non-null to avoid undefined behavior.
- static uint8_t t;
- return v.empty() ? reinterpret_cast<const T *>(&t) : &v.front();
-}
-template<typename T, typename Alloc> T *data(std::vector<T, Alloc> &v) {
- // Eventually the returned pointer gets passed down to memcpy, so
- // we need it to be non-null to avoid undefined behavior.
- static uint8_t t;
- return v.empty() ? reinterpret_cast<T *>(&t) : &v.front();
-}
-
-/// @endcond
-
-/// @addtogroup flatbuffers_cpp_api
-/// @{
-/// @class FlatBufferBuilder
-/// @brief Helper class to hold data needed in creation of a FlatBuffer.
-/// To serialize data, you typically call one of the `Create*()` functions in
-/// the generated code, which in turn call a sequence of `StartTable`/
-/// `PushElement`/`AddElement`/`EndTable`, or the builtin `CreateString`/
-/// `CreateVector` functions. Do this is depth-first order to build up a tree to
-/// the root. `Finish()` wraps up the buffer ready for transport.
-class FlatBufferBuilder {
- public:
- /// @brief Default constructor for FlatBufferBuilder.
- /// @param[in] initial_size The initial size of the buffer, in bytes. Defaults
- /// to `1024`.
- /// @param[in] allocator An `Allocator` to use. If null will use
- /// `DefaultAllocator`.
- /// @param[in] own_allocator Whether the builder/vector should own the
- /// allocator. Defaults to / `false`.
- /// @param[in] buffer_minalign Force the buffer to be aligned to the given
- /// minimum alignment upon reallocation. Only needed if you intend to store
- /// types with custom alignment AND you wish to read the buffer in-place
- /// directly after creation.
- explicit FlatBufferBuilder(
- size_t initial_size = 1024, Allocator *allocator = nullptr,
- bool own_allocator = false,
- size_t buffer_minalign = AlignOf<largest_scalar_t>())
- : buf_(initial_size, allocator, own_allocator, buffer_minalign),
- num_field_loc(0),
- max_voffset_(0),
- nested(false),
- finished(false),
- minalign_(1),
- force_defaults_(false),
- dedup_vtables_(true),
- string_pool(nullptr) {
- EndianCheck();
- }
-
- // clang-format off
- /// @brief Move constructor for FlatBufferBuilder.
- #if !defined(FLATBUFFERS_CPP98_STL)
- FlatBufferBuilder(FlatBufferBuilder &&other)
- #else
- FlatBufferBuilder(FlatBufferBuilder &other)
- #endif // #if !defined(FLATBUFFERS_CPP98_STL)
- : buf_(1024, nullptr, false, AlignOf<largest_scalar_t>()),
- num_field_loc(0),
- max_voffset_(0),
- nested(false),
- finished(false),
- minalign_(1),
- force_defaults_(false),
- dedup_vtables_(true),
- string_pool(nullptr) {
- EndianCheck();
- // Default construct and swap idiom.
- // Lack of delegating constructors in vs2010 makes it more verbose than needed.
- Swap(other);
- }
- // clang-format on
-
- // clang-format off
- #if !defined(FLATBUFFERS_CPP98_STL)
- // clang-format on
- /// @brief Move assignment operator for FlatBufferBuilder.
- FlatBufferBuilder &operator=(FlatBufferBuilder &&other) {
- // Move construct a temporary and swap idiom
- FlatBufferBuilder temp(std::move(other));
- Swap(temp);
- return *this;
- }
- // clang-format off
- #endif // defined(FLATBUFFERS_CPP98_STL)
- // clang-format on
-
- void Swap(FlatBufferBuilder &other) {
- using std::swap;
- buf_.swap(other.buf_);
- swap(num_field_loc, other.num_field_loc);
- swap(max_voffset_, other.max_voffset_);
- swap(nested, other.nested);
- swap(finished, other.finished);
- swap(minalign_, other.minalign_);
- swap(force_defaults_, other.force_defaults_);
- swap(dedup_vtables_, other.dedup_vtables_);
- swap(string_pool, other.string_pool);
- }
-
- ~FlatBufferBuilder() {
- if (string_pool) delete string_pool;
- }
-
- void Reset() {
- Clear(); // clear builder state
- buf_.reset(); // deallocate buffer
- }
-
- /// @brief Reset all the state in this FlatBufferBuilder so it can be reused
- /// to construct another buffer.
- void Clear() {
- ClearOffsets();
- buf_.clear();
- nested = false;
- finished = false;
- minalign_ = 1;
- if (string_pool) string_pool->clear();
- }
-
- /// @brief The current size of the serialized buffer, counting from the end.
- /// @return Returns an `uoffset_t` with the current size of the buffer.
- uoffset_t GetSize() const { return buf_.size(); }
-
- /// @brief Get the serialized buffer (after you call `Finish()`).
- /// @return Returns an `uint8_t` pointer to the FlatBuffer data inside the
- /// buffer.
- uint8_t *GetBufferPointer() const {
- Finished();
- return buf_.data();
- }
-
- /// @brief Get the serialized buffer (after you call `Finish()`) as a span.
- /// @return Returns a constructed flatbuffers::span that is a view over the
- /// FlatBuffer data inside the buffer.
- flatbuffers::span<uint8_t> GetBufferSpan() const {
- Finished();
- return flatbuffers::span<uint8_t>(buf_.data(), buf_.size());
- }
-
- /// @brief Get a pointer to an unfinished buffer.
- /// @return Returns a `uint8_t` pointer to the unfinished buffer.
- uint8_t *GetCurrentBufferPointer() const { return buf_.data(); }
-
- /// @brief Get the released pointer to the serialized buffer.
- /// @warning Do NOT attempt to use this FlatBufferBuilder afterwards!
- /// @return A `FlatBuffer` that owns the buffer and its allocator and
- /// behaves similar to a `unique_ptr` with a deleter.
- FLATBUFFERS_ATTRIBUTE(deprecated("use Release() instead"))
- DetachedBuffer ReleaseBufferPointer() {
- Finished();
- return buf_.release();
- }
-
- /// @brief Get the released DetachedBuffer.
- /// @return A `DetachedBuffer` that owns the buffer and its allocator.
- DetachedBuffer Release() {
- Finished();
- return buf_.release();
- }
-
- /// @brief Get the released pointer to the serialized buffer.
- /// @param size The size of the memory block containing
- /// the serialized `FlatBuffer`.
- /// @param offset The offset from the released pointer where the finished
- /// `FlatBuffer` starts.
- /// @return A raw pointer to the start of the memory block containing
- /// the serialized `FlatBuffer`.
- /// @remark If the allocator is owned, it gets deleted when the destructor is
- /// called..
- uint8_t *ReleaseRaw(size_t &size, size_t &offset) {
- Finished();
- return buf_.release_raw(size, offset);
- }
-
- /// @brief get the minimum alignment this buffer needs to be accessed
- /// properly. This is only known once all elements have been written (after
- /// you call Finish()). You can use this information if you need to embed
- /// a FlatBuffer in some other buffer, such that you can later read it
- /// without first having to copy it into its own buffer.
- size_t GetBufferMinAlignment() const {
- Finished();
- return minalign_;
- }
-
- /// @cond FLATBUFFERS_INTERNAL
- void Finished() const {
- // If you get this assert, you're attempting to get access a buffer
- // which hasn't been finished yet. Be sure to call
- // FlatBufferBuilder::Finish with your root table.
- // If you really need to access an unfinished buffer, call
- // GetCurrentBufferPointer instead.
- FLATBUFFERS_ASSERT(finished);
- }
- /// @endcond
-
- /// @brief In order to save space, fields that are set to their default value
- /// don't get serialized into the buffer.
- /// @param[in] fd When set to `true`, always serializes default values that
- /// are set. Optional fields which are not set explicitly, will still not be
- /// serialized.
- void ForceDefaults(bool fd) { force_defaults_ = fd; }
-
- /// @brief By default vtables are deduped in order to save space.
- /// @param[in] dedup When set to `true`, dedup vtables.
- void DedupVtables(bool dedup) { dedup_vtables_ = dedup; }
-
- /// @cond FLATBUFFERS_INTERNAL
- void Pad(size_t num_bytes) { buf_.fill(num_bytes); }
-
- void TrackMinAlign(size_t elem_size) {
- if (elem_size > minalign_) minalign_ = elem_size;
- }
-
- void Align(size_t elem_size) {
- TrackMinAlign(elem_size);
- buf_.fill(PaddingBytes(buf_.size(), elem_size));
- }
-
- void PushFlatBuffer(const uint8_t *bytes, size_t size) {
- PushBytes(bytes, size);
- finished = true;
- }
-
- void PushBytes(const uint8_t *bytes, size_t size) { buf_.push(bytes, size); }
-
- void PopBytes(size_t amount) { buf_.pop(amount); }
-
- template<typename T> void AssertScalarT() {
- // The code assumes power of 2 sizes and endian-swap-ability.
- static_assert(flatbuffers::is_scalar<T>::value, "T must be a scalar type");
- }
-
- // Write a single aligned scalar to the buffer
- template<typename T> uoffset_t PushElement(T element) {
- AssertScalarT<T>();
- T litle_endian_element = EndianScalar(element);
- Align(sizeof(T));
- buf_.push_small(litle_endian_element);
- return GetSize();
- }
-
- template<typename T> uoffset_t PushElement(Offset<T> off) {
- // Special case for offsets: see ReferTo below.
- return PushElement(ReferTo(off.o));
- }
-
- // When writing fields, we track where they are, so we can create correct
- // vtables later.
- void TrackField(voffset_t field, uoffset_t off) {
- FieldLoc fl = { off, field };
- buf_.scratch_push_small(fl);
- num_field_loc++;
- max_voffset_ = (std::max)(max_voffset_, field);
- }
-
- // Like PushElement, but additionally tracks the field this represents.
- template<typename T> void AddElement(voffset_t field, T e, T def) {
- // We don't serialize values equal to the default.
- if (IsTheSameAs(e, def) && !force_defaults_) return;
- auto off = PushElement(e);
- TrackField(field, off);
- }
-
- template<typename T> void AddElement(voffset_t field, T e) {
- auto off = PushElement(e);
- TrackField(field, off);
- }
-
- template<typename T> void AddOffset(voffset_t field, Offset<T> off) {
- if (off.IsNull()) return; // Don't store.
- AddElement(field, ReferTo(off.o), static_cast<uoffset_t>(0));
- }
-
- template<typename T> void AddStruct(voffset_t field, const T *structptr) {
- if (!structptr) return; // Default, don't store.
- Align(AlignOf<T>());
- buf_.push_small(*structptr);
- TrackField(field, GetSize());
- }
-
- void AddStructOffset(voffset_t field, uoffset_t off) {
- TrackField(field, off);
- }
-
- // Offsets initially are relative to the end of the buffer (downwards).
- // This function converts them to be relative to the current location
- // in the buffer (when stored here), pointing upwards.
- uoffset_t ReferTo(uoffset_t off) {
- // Align to ensure GetSize() below is correct.
- Align(sizeof(uoffset_t));
- // Offset must refer to something already in buffer.
- FLATBUFFERS_ASSERT(off && off <= GetSize());
- return GetSize() - off + static_cast<uoffset_t>(sizeof(uoffset_t));
- }
-
- void NotNested() {
- // If you hit this, you're trying to construct a Table/Vector/String
- // during the construction of its parent table (between the MyTableBuilder
- // and table.Finish().
- // Move the creation of these sub-objects to above the MyTableBuilder to
- // not get this assert.
- // Ignoring this assert may appear to work in simple cases, but the reason
- // it is here is that storing objects in-line may cause vtable offsets
- // to not fit anymore. It also leads to vtable duplication.
- FLATBUFFERS_ASSERT(!nested);
- // If you hit this, fields were added outside the scope of a table.
- FLATBUFFERS_ASSERT(!num_field_loc);
- }
-
- // From generated code (or from the parser), we call StartTable/EndTable
- // with a sequence of AddElement calls in between.
- uoffset_t StartTable() {
- NotNested();
- nested = true;
- return GetSize();
- }
-
- // This finishes one serialized object by generating the vtable if it's a
- // table, comparing it against existing vtables, and writing the
- // resulting vtable offset.
- uoffset_t EndTable(uoffset_t start) {
- // If you get this assert, a corresponding StartTable wasn't called.
- FLATBUFFERS_ASSERT(nested);
- // Write the vtable offset, which is the start of any Table.
- // We fill it's value later.
- auto vtableoffsetloc = PushElement<soffset_t>(0);
- // Write a vtable, which consists entirely of voffset_t elements.
- // It starts with the number of offsets, followed by a type id, followed
- // by the offsets themselves. In reverse:
- // Include space for the last offset and ensure empty tables have a
- // minimum size.
- max_voffset_ =
- (std::max)(static_cast<voffset_t>(max_voffset_ + sizeof(voffset_t)),
- FieldIndexToOffset(0));
- buf_.fill_big(max_voffset_);
- auto table_object_size = vtableoffsetloc - start;
- // Vtable use 16bit offsets.
- FLATBUFFERS_ASSERT(table_object_size < 0x10000);
- WriteScalar<voffset_t>(buf_.data() + sizeof(voffset_t),
- static_cast<voffset_t>(table_object_size));
- WriteScalar<voffset_t>(buf_.data(), max_voffset_);
- // Write the offsets into the table
- for (auto it = buf_.scratch_end() - num_field_loc * sizeof(FieldLoc);
- it < buf_.scratch_end(); it += sizeof(FieldLoc)) {
- auto field_location = reinterpret_cast<FieldLoc *>(it);
- auto pos = static_cast<voffset_t>(vtableoffsetloc - field_location->off);
- // If this asserts, it means you've set a field twice.
- FLATBUFFERS_ASSERT(
- !ReadScalar<voffset_t>(buf_.data() + field_location->id));
- WriteScalar<voffset_t>(buf_.data() + field_location->id, pos);
- }
- ClearOffsets();
- auto vt1 = reinterpret_cast<voffset_t *>(buf_.data());
- auto vt1_size = ReadScalar<voffset_t>(vt1);
- auto vt_use = GetSize();
- // See if we already have generated a vtable with this exact same
- // layout before. If so, make it point to the old one, remove this one.
- if (dedup_vtables_) {
- for (auto it = buf_.scratch_data(); it < buf_.scratch_end();
- it += sizeof(uoffset_t)) {
- auto vt_offset_ptr = reinterpret_cast<uoffset_t *>(it);
- auto vt2 = reinterpret_cast<voffset_t *>(buf_.data_at(*vt_offset_ptr));
- auto vt2_size = ReadScalar<voffset_t>(vt2);
- if (vt1_size != vt2_size || 0 != memcmp(vt2, vt1, vt1_size)) continue;
- vt_use = *vt_offset_ptr;
- buf_.pop(GetSize() - vtableoffsetloc);
- break;
- }
- }
- // If this is a new vtable, remember it.
- if (vt_use == GetSize()) { buf_.scratch_push_small(vt_use); }
- // Fill the vtable offset we created above.
- // The offset points from the beginning of the object to where the
- // vtable is stored.
- // Offsets default direction is downward in memory for future format
- // flexibility (storing all vtables at the start of the file).
- WriteScalar(buf_.data_at(vtableoffsetloc),
- static_cast<soffset_t>(vt_use) -
- static_cast<soffset_t>(vtableoffsetloc));
-
- nested = false;
- return vtableoffsetloc;
- }
-
- FLATBUFFERS_ATTRIBUTE(deprecated("call the version above instead"))
- uoffset_t EndTable(uoffset_t start, voffset_t /*numfields*/) {
- return EndTable(start);
- }
-
- // This checks a required field has been set in a given table that has
- // just been constructed.
- template<typename T> void Required(Offset<T> table, voffset_t field);
-
- uoffset_t StartStruct(size_t alignment) {
- Align(alignment);
- return GetSize();
- }
-
- uoffset_t EndStruct() { return GetSize(); }
-
- void ClearOffsets() {
- buf_.scratch_pop(num_field_loc * sizeof(FieldLoc));
- num_field_loc = 0;
- max_voffset_ = 0;
- }
-
- // Aligns such that when "len" bytes are written, an object can be written
- // after it with "alignment" without padding.
- void PreAlign(size_t len, size_t alignment) {
- TrackMinAlign(alignment);
- buf_.fill(PaddingBytes(GetSize() + len, alignment));
- }
- template<typename T> void PreAlign(size_t len) {
- AssertScalarT<T>();
- PreAlign(len, sizeof(T));
- }
- /// @endcond
-
- /// @brief Store a string in the buffer, which can contain any binary data.
- /// @param[in] str A const char pointer to the data to be stored as a string.
- /// @param[in] len The number of bytes that should be stored from `str`.
- /// @return Returns the offset in the buffer where the string starts.
- Offset<String> CreateString(const char *str, size_t len) {
- NotNested();
- PreAlign<uoffset_t>(len + 1); // Always 0-terminated.
- buf_.fill(1);
- PushBytes(reinterpret_cast<const uint8_t *>(str), len);
- PushElement(static_cast<uoffset_t>(len));
- return Offset<String>(GetSize());
- }
-
- /// @brief Store a string in the buffer, which is null-terminated.
- /// @param[in] str A const char pointer to a C-string to add to the buffer.
- /// @return Returns the offset in the buffer where the string starts.
- Offset<String> CreateString(const char *str) {
- return CreateString(str, strlen(str));
- }
-
- /// @brief Store a string in the buffer, which is null-terminated.
- /// @param[in] str A char pointer to a C-string to add to the buffer.
- /// @return Returns the offset in the buffer where the string starts.
- Offset<String> CreateString(char *str) {
- return CreateString(str, strlen(str));
- }
-
- /// @brief Store a string in the buffer, which can contain any binary data.
- /// @param[in] str A const reference to a std::string to store in the buffer.
- /// @return Returns the offset in the buffer where the string starts.
- Offset<String> CreateString(const std::string &str) {
- return CreateString(str.c_str(), str.length());
- }
-
- // clang-format off
- #ifdef FLATBUFFERS_HAS_STRING_VIEW
- /// @brief Store a string in the buffer, which can contain any binary data.
- /// @param[in] str A const string_view to copy in to the buffer.
- /// @return Returns the offset in the buffer where the string starts.
- Offset<String> CreateString(flatbuffers::string_view str) {
- return CreateString(str.data(), str.size());
- }
- #endif // FLATBUFFERS_HAS_STRING_VIEW
- // clang-format on
-
- /// @brief Store a string in the buffer, which can contain any binary data.
- /// @param[in] str A const pointer to a `String` struct to add to the buffer.
- /// @return Returns the offset in the buffer where the string starts
- Offset<String> CreateString(const String *str) {
- return str ? CreateString(str->c_str(), str->size()) : 0;
- }
-
- /// @brief Store a string in the buffer, which can contain any binary data.
- /// @param[in] str A const reference to a std::string like type with support
- /// of T::c_str() and T::length() to store in the buffer.
- /// @return Returns the offset in the buffer where the string starts.
- template<typename T> Offset<String> CreateString(const T &str) {
- return CreateString(str.c_str(), str.length());
- }
-
- /// @brief Store a string in the buffer, which can contain any binary data.
- /// If a string with this exact contents has already been serialized before,
- /// instead simply returns the offset of the existing string.
- /// @param[in] str A const char pointer to the data to be stored as a string.
- /// @param[in] len The number of bytes that should be stored from `str`.
- /// @return Returns the offset in the buffer where the string starts.
- Offset<String> CreateSharedString(const char *str, size_t len) {
- if (!string_pool)
- string_pool = new StringOffsetMap(StringOffsetCompare(buf_));
- auto size_before_string = buf_.size();
- // Must first serialize the string, since the set is all offsets into
- // buffer.
- auto off = CreateString(str, len);
- auto it = string_pool->find(off);
- // If it exists we reuse existing serialized data!
- if (it != string_pool->end()) {
- // We can remove the string we serialized.
- buf_.pop(buf_.size() - size_before_string);
- return *it;
- }
- // Record this string for future use.
- string_pool->insert(off);
- return off;
- }
-
- /// @brief Store a string in the buffer, which null-terminated.
- /// If a string with this exact contents has already been serialized before,
- /// instead simply returns the offset of the existing string.
- /// @param[in] str A const char pointer to a C-string to add to the buffer.
- /// @return Returns the offset in the buffer where the string starts.
- Offset<String> CreateSharedString(const char *str) {
- return CreateSharedString(str, strlen(str));
- }
-
- /// @brief Store a string in the buffer, which can contain any binary data.
- /// If a string with this exact contents has already been serialized before,
- /// instead simply returns the offset of the existing string.
- /// @param[in] str A const reference to a std::string to store in the buffer.
- /// @return Returns the offset in the buffer where the string starts.
- Offset<String> CreateSharedString(const std::string &str) {
- return CreateSharedString(str.c_str(), str.length());
- }
-
- /// @brief Store a string in the buffer, which can contain any binary data.
- /// If a string with this exact contents has already been serialized before,
- /// instead simply returns the offset of the existing string.
- /// @param[in] str A const pointer to a `String` struct to add to the buffer.
- /// @return Returns the offset in the buffer where the string starts
- Offset<String> CreateSharedString(const String *str) {
- return CreateSharedString(str->c_str(), str->size());
- }
-
- /// @cond FLATBUFFERS_INTERNAL
- uoffset_t EndVector(size_t len) {
- FLATBUFFERS_ASSERT(nested); // Hit if no corresponding StartVector.
- nested = false;
- return PushElement(static_cast<uoffset_t>(len));
- }
-
- void StartVector(size_t len, size_t elemsize) {
- NotNested();
- nested = true;
- PreAlign<uoffset_t>(len * elemsize);
- PreAlign(len * elemsize, elemsize); // Just in case elemsize > uoffset_t.
- }
-
- // Call this right before StartVector/CreateVector if you want to force the
- // alignment to be something different than what the element size would
- // normally dictate.
- // This is useful when storing a nested_flatbuffer in a vector of bytes,
- // or when storing SIMD floats, etc.
- void ForceVectorAlignment(size_t len, size_t elemsize, size_t alignment) {
- PreAlign(len * elemsize, alignment);
- }
-
- // Similar to ForceVectorAlignment but for String fields.
- void ForceStringAlignment(size_t len, size_t alignment) {
- PreAlign((len + 1) * sizeof(char), alignment);
- }
-
- /// @endcond
-
- /// @brief Serialize an array into a FlatBuffer `vector`.
- /// @tparam T The data type of the array elements.
- /// @param[in] v A pointer to the array of type `T` to serialize into the
- /// buffer as a `vector`.
- /// @param[in] len The number of elements to serialize.
- /// @return Returns a typed `Offset` into the serialized data indicating
- /// where the vector is stored.
- template<typename T> Offset<Vector<T>> CreateVector(const T *v, size_t len) {
- // If this assert hits, you're specifying a template argument that is
- // causing the wrong overload to be selected, remove it.
- AssertScalarT<T>();
- StartVector(len, sizeof(T));
- if (len == 0) {
- return Offset<Vector<T>>(EndVector(len));
- }
- // clang-format off
- #if FLATBUFFERS_LITTLEENDIAN
- PushBytes(reinterpret_cast<const uint8_t *>(v), len * sizeof(T));
- #else
- if (sizeof(T) == 1) {
- PushBytes(reinterpret_cast<const uint8_t *>(v), len);
- } else {
- for (auto i = len; i > 0; ) {
- PushElement(v[--i]);
- }
- }
- #endif
- // clang-format on
- return Offset<Vector<T>>(EndVector(len));
- }
-
- template<typename T>
- Offset<Vector<Offset<T>>> CreateVector(const Offset<T> *v, size_t len) {
- StartVector(len, sizeof(Offset<T>));
- for (auto i = len; i > 0;) { PushElement(v[--i]); }
- return Offset<Vector<Offset<T>>>(EndVector(len));
- }
-
- /// @brief Serialize a `std::vector` into a FlatBuffer `vector`.
- /// @tparam T The data type of the `std::vector` elements.
- /// @param v A const reference to the `std::vector` to serialize into the
- /// buffer as a `vector`.
- /// @return Returns a typed `Offset` into the serialized data indicating
- /// where the vector is stored.
- template<typename T> Offset<Vector<T>> CreateVector(const std::vector<T> &v) {
- return CreateVector(data(v), v.size());
- }
-
- // vector<bool> may be implemented using a bit-set, so we can't access it as
- // an array. Instead, read elements manually.
- // Background: https://isocpp.org/blog/2012/11/on-vectorbool
- Offset<Vector<uint8_t>> CreateVector(const std::vector<bool> &v) {
- StartVector(v.size(), sizeof(uint8_t));
- for (auto i = v.size(); i > 0;) {
- PushElement(static_cast<uint8_t>(v[--i]));
- }
- return Offset<Vector<uint8_t>>(EndVector(v.size()));
- }
-
- // clang-format off
- #ifndef FLATBUFFERS_CPP98_STL
- /// @brief Serialize values returned by a function into a FlatBuffer `vector`.
- /// This is a convenience function that takes care of iteration for you.
- /// @tparam T The data type of the `std::vector` elements.
- /// @param f A function that takes the current iteration 0..vector_size-1 and
- /// returns any type that you can construct a FlatBuffers vector out of.
- /// @return Returns a typed `Offset` into the serialized data indicating
- /// where the vector is stored.
- template<typename T> Offset<Vector<T>> CreateVector(size_t vector_size,
- const std::function<T (size_t i)> &f) {
- std::vector<T> elems(vector_size);
- for (size_t i = 0; i < vector_size; i++) elems[i] = f(i);
- return CreateVector(elems);
- }
- #endif
- // clang-format on
-
- /// @brief Serialize values returned by a function into a FlatBuffer `vector`.
- /// This is a convenience function that takes care of iteration for you.
- /// @tparam T The data type of the `std::vector` elements.
- /// @param f A function that takes the current iteration 0..vector_size-1,
- /// and the state parameter returning any type that you can construct a
- /// FlatBuffers vector out of.
- /// @param state State passed to f.
- /// @return Returns a typed `Offset` into the serialized data indicating
- /// where the vector is stored.
- template<typename T, typename F, typename S>
- Offset<Vector<T>> CreateVector(size_t vector_size, F f, S *state) {
- std::vector<T> elems(vector_size);
- for (size_t i = 0; i < vector_size; i++) elems[i] = f(i, state);
- return CreateVector(elems);
- }
-
- /// @brief Serialize a `std::vector<std::string>` into a FlatBuffer `vector`.
- /// This is a convenience function for a common case.
- /// @param v A const reference to the `std::vector` to serialize into the
- /// buffer as a `vector`.
- /// @return Returns a typed `Offset` into the serialized data indicating
- /// where the vector is stored.
- Offset<Vector<Offset<String>>> CreateVectorOfStrings(
- const std::vector<std::string> &v) {
- std::vector<Offset<String>> offsets(v.size());
- for (size_t i = 0; i < v.size(); i++) offsets[i] = CreateString(v[i]);
- return CreateVector(offsets);
- }
-
- /// @brief Serialize an array of structs into a FlatBuffer `vector`.
- /// @tparam T The data type of the struct array elements.
- /// @param[in] v A pointer to the array of type `T` to serialize into the
- /// buffer as a `vector`.
- /// @param[in] len The number of elements to serialize.
- /// @return Returns a typed `Offset` into the serialized data indicating
- /// where the vector is stored.
- template<typename T>
- Offset<Vector<const T *>> CreateVectorOfStructs(const T *v, size_t len) {
- StartVector(len * sizeof(T) / AlignOf<T>(), AlignOf<T>());
- PushBytes(reinterpret_cast<const uint8_t *>(v), sizeof(T) * len);
- return Offset<Vector<const T *>>(EndVector(len));
- }
-
- /// @brief Serialize an array of native structs into a FlatBuffer `vector`.
- /// @tparam T The data type of the struct array elements.
- /// @tparam S The data type of the native struct array elements.
- /// @param[in] v A pointer to the array of type `S` to serialize into the
- /// buffer as a `vector`.
- /// @param[in] len The number of elements to serialize.
- /// @return Returns a typed `Offset` into the serialized data indicating
- /// where the vector is stored.
- template<typename T, typename S>
- Offset<Vector<const T *>> CreateVectorOfNativeStructs(const S *v,
- size_t len) {
- extern T Pack(const S &);
- std::vector<T> vv(len);
- std::transform(v, v + len, vv.begin(), Pack);
- return CreateVectorOfStructs<T>(data(vv), vv.size());
- }
-
- // clang-format off
- #ifndef FLATBUFFERS_CPP98_STL
- /// @brief Serialize an array of structs into a FlatBuffer `vector`.
- /// @tparam T The data type of the struct array elements.
- /// @param[in] filler A function that takes the current iteration 0..vector_size-1
- /// and a pointer to the struct that must be filled.
- /// @return Returns a typed `Offset` into the serialized data indicating
- /// where the vector is stored.
- /// This is mostly useful when flatbuffers are generated with mutation
- /// accessors.
- template<typename T> Offset<Vector<const T *>> CreateVectorOfStructs(
- size_t vector_size, const std::function<void(size_t i, T *)> &filler) {
- T* structs = StartVectorOfStructs<T>(vector_size);
- for (size_t i = 0; i < vector_size; i++) {
- filler(i, structs);
- structs++;
- }
- return EndVectorOfStructs<T>(vector_size);
- }
- #endif
- // clang-format on
-
- /// @brief Serialize an array of structs into a FlatBuffer `vector`.
- /// @tparam T The data type of the struct array elements.
- /// @param[in] f A function that takes the current iteration 0..vector_size-1,
- /// a pointer to the struct that must be filled and the state argument.
- /// @param[in] state Arbitrary state to pass to f.
- /// @return Returns a typed `Offset` into the serialized data indicating
- /// where the vector is stored.
- /// This is mostly useful when flatbuffers are generated with mutation
- /// accessors.
- template<typename T, typename F, typename S>
- Offset<Vector<const T *>> CreateVectorOfStructs(size_t vector_size, F f,
- S *state) {
- T *structs = StartVectorOfStructs<T>(vector_size);
- for (size_t i = 0; i < vector_size; i++) {
- f(i, structs, state);
- structs++;
- }
- return EndVectorOfStructs<T>(vector_size);
- }
-
- /// @brief Serialize a `std::vector` of structs into a FlatBuffer `vector`.
- /// @tparam T The data type of the `std::vector` struct elements.
- /// @param[in] v A const reference to the `std::vector` of structs to
- /// serialize into the buffer as a `vector`.
- /// @return Returns a typed `Offset` into the serialized data indicating
- /// where the vector is stored.
- template<typename T, typename Alloc>
- Offset<Vector<const T *>> CreateVectorOfStructs(
- const std::vector<T, Alloc> &v) {
- return CreateVectorOfStructs(data(v), v.size());
- }
-
- /// @brief Serialize a `std::vector` of native structs into a FlatBuffer
- /// `vector`.
- /// @tparam T The data type of the `std::vector` struct elements.
- /// @tparam S The data type of the `std::vector` native struct elements.
- /// @param[in] v A const reference to the `std::vector` of structs to
- /// serialize into the buffer as a `vector`.
- /// @return Returns a typed `Offset` into the serialized data indicating
- /// where the vector is stored.
- template<typename T, typename S>
- Offset<Vector<const T *>> CreateVectorOfNativeStructs(
- const std::vector<S> &v) {
- return CreateVectorOfNativeStructs<T, S>(data(v), v.size());
- }
-
- /// @cond FLATBUFFERS_INTERNAL
- template<typename T> struct StructKeyComparator {
- bool operator()(const T &a, const T &b) const {
- return a.KeyCompareLessThan(&b);
- }
-
- FLATBUFFERS_DELETE_FUNC(
- StructKeyComparator &operator=(const StructKeyComparator &))
- };
- /// @endcond
-
- /// @brief Serialize a `std::vector` of structs into a FlatBuffer `vector`
- /// in sorted order.
- /// @tparam T The data type of the `std::vector` struct elements.
- /// @param[in] v A const reference to the `std::vector` of structs to
- /// serialize into the buffer as a `vector`.
- /// @return Returns a typed `Offset` into the serialized data indicating
- /// where the vector is stored.
- template<typename T>
- Offset<Vector<const T *>> CreateVectorOfSortedStructs(std::vector<T> *v) {
- return CreateVectorOfSortedStructs(data(*v), v->size());
- }
-
- /// @brief Serialize a `std::vector` of native structs into a FlatBuffer
- /// `vector` in sorted order.
- /// @tparam T The data type of the `std::vector` struct elements.
- /// @tparam S The data type of the `std::vector` native struct elements.
- /// @param[in] v A const reference to the `std::vector` of structs to
- /// serialize into the buffer as a `vector`.
- /// @return Returns a typed `Offset` into the serialized data indicating
- /// where the vector is stored.
- template<typename T, typename S>
- Offset<Vector<const T *>> CreateVectorOfSortedNativeStructs(
- std::vector<S> *v) {
- return CreateVectorOfSortedNativeStructs<T, S>(data(*v), v->size());
- }
-
- /// @brief Serialize an array of structs into a FlatBuffer `vector` in sorted
- /// order.
- /// @tparam T The data type of the struct array elements.
- /// @param[in] v A pointer to the array of type `T` to serialize into the
- /// buffer as a `vector`.
- /// @param[in] len The number of elements to serialize.
- /// @return Returns a typed `Offset` into the serialized data indicating
- /// where the vector is stored.
- template<typename T>
- Offset<Vector<const T *>> CreateVectorOfSortedStructs(T *v, size_t len) {
- std::sort(v, v + len, StructKeyComparator<T>());
- return CreateVectorOfStructs(v, len);
- }
-
- /// @brief Serialize an array of native structs into a FlatBuffer `vector` in
- /// sorted order.
- /// @tparam T The data type of the struct array elements.
- /// @tparam S The data type of the native struct array elements.
- /// @param[in] v A pointer to the array of type `S` to serialize into the
- /// buffer as a `vector`.
- /// @param[in] len The number of elements to serialize.
- /// @return Returns a typed `Offset` into the serialized data indicating
- /// where the vector is stored.
- template<typename T, typename S>
- Offset<Vector<const T *>> CreateVectorOfSortedNativeStructs(S *v,
- size_t len) {
- extern T Pack(const S &);
- typedef T (*Pack_t)(const S &);
- std::vector<T> vv(len);
- std::transform(v, v + len, vv.begin(), static_cast<Pack_t &>(Pack));
- return CreateVectorOfSortedStructs<T>(vv, len);
- }
-
- /// @cond FLATBUFFERS_INTERNAL
- template<typename T> struct TableKeyComparator {
- TableKeyComparator(vector_downward &buf) : buf_(buf) {}
- TableKeyComparator(const TableKeyComparator &other) : buf_(other.buf_) {}
- bool operator()(const Offset<T> &a, const Offset<T> &b) const {
- auto table_a = reinterpret_cast<T *>(buf_.data_at(a.o));
- auto table_b = reinterpret_cast<T *>(buf_.data_at(b.o));
- return table_a->KeyCompareLessThan(table_b);
- }
- vector_downward &buf_;
-
- private:
- FLATBUFFERS_DELETE_FUNC(TableKeyComparator &operator=(const TableKeyComparator &other))
- };
- /// @endcond
-
- /// @brief Serialize an array of `table` offsets as a `vector` in the buffer
- /// in sorted order.
- /// @tparam T The data type that the offset refers to.
- /// @param[in] v An array of type `Offset<T>` that contains the `table`
- /// offsets to store in the buffer in sorted order.
- /// @param[in] len The number of elements to store in the `vector`.
- /// @return Returns a typed `Offset` into the serialized data indicating
- /// where the vector is stored.
- template<typename T>
- Offset<Vector<Offset<T>>> CreateVectorOfSortedTables(Offset<T> *v,
- size_t len) {
- std::sort(v, v + len, TableKeyComparator<T>(buf_));
- return CreateVector(v, len);
- }
-
- /// @brief Serialize an array of `table` offsets as a `vector` in the buffer
- /// in sorted order.
- /// @tparam T The data type that the offset refers to.
- /// @param[in] v An array of type `Offset<T>` that contains the `table`
- /// offsets to store in the buffer in sorted order.
- /// @return Returns a typed `Offset` into the serialized data indicating
- /// where the vector is stored.
- template<typename T>
- Offset<Vector<Offset<T>>> CreateVectorOfSortedTables(
- std::vector<Offset<T>> *v) {
- return CreateVectorOfSortedTables(data(*v), v->size());
- }
-
- /// @brief Specialized version of `CreateVector` for non-copying use cases.
- /// Write the data any time later to the returned buffer pointer `buf`.
- /// @param[in] len The number of elements to store in the `vector`.
- /// @param[in] elemsize The size of each element in the `vector`.
- /// @param[out] buf A pointer to a `uint8_t` pointer that can be
- /// written to at a later time to serialize the data into a `vector`
- /// in the buffer.
- uoffset_t CreateUninitializedVector(size_t len, size_t elemsize,
- uint8_t **buf) {
- NotNested();
- StartVector(len, elemsize);
- buf_.make_space(len * elemsize);
- auto vec_start = GetSize();
- auto vec_end = EndVector(len);
- *buf = buf_.data_at(vec_start);
- return vec_end;
- }
-
- /// @brief Specialized version of `CreateVector` for non-copying use cases.
- /// Write the data any time later to the returned buffer pointer `buf`.
- /// @tparam T The data type of the data that will be stored in the buffer
- /// as a `vector`.
- /// @param[in] len The number of elements to store in the `vector`.
- /// @param[out] buf A pointer to a pointer of type `T` that can be
- /// written to at a later time to serialize the data into a `vector`
- /// in the buffer.
- template<typename T>
- Offset<Vector<T>> CreateUninitializedVector(size_t len, T **buf) {
- AssertScalarT<T>();
- return CreateUninitializedVector(len, sizeof(T),
- reinterpret_cast<uint8_t **>(buf));
- }
-
- template<typename T>
- Offset<Vector<const T *>> CreateUninitializedVectorOfStructs(size_t len,
- T **buf) {
- return CreateUninitializedVector(len, sizeof(T),
- reinterpret_cast<uint8_t **>(buf));
- }
-
- // @brief Create a vector of scalar type T given as input a vector of scalar
- // type U, useful with e.g. pre "enum class" enums, or any existing scalar
- // data of the wrong type.
- template<typename T, typename U>
- Offset<Vector<T>> CreateVectorScalarCast(const U *v, size_t len) {
- AssertScalarT<T>();
- AssertScalarT<U>();
- StartVector(len, sizeof(T));
- for (auto i = len; i > 0;) { PushElement(static_cast<T>(v[--i])); }
- return Offset<Vector<T>>(EndVector(len));
- }
-
- /// @brief Write a struct by itself, typically to be part of a union.
- template<typename T> Offset<const T *> CreateStruct(const T &structobj) {
- NotNested();
- Align(AlignOf<T>());
- buf_.push_small(structobj);
- return Offset<const T *>(GetSize());
- }
-
- /// @brief The length of a FlatBuffer file header.
- static const size_t kFileIdentifierLength = 4;
-
- /// @brief Finish serializing a buffer by writing the root offset.
- /// @param[in] file_identifier If a `file_identifier` is given, the buffer
- /// will be prefixed with a standard FlatBuffers file header.
- template<typename T>
- void Finish(Offset<T> root, const char *file_identifier = nullptr) {
- Finish(root.o, file_identifier, false);
- }
-
- /// @brief Finish a buffer with a 32 bit size field pre-fixed (size of the
- /// buffer following the size field). These buffers are NOT compatible
- /// with standard buffers created by Finish, i.e. you can't call GetRoot
- /// on them, you have to use GetSizePrefixedRoot instead.
- /// All >32 bit quantities in this buffer will be aligned when the whole
- /// size pre-fixed buffer is aligned.
- /// These kinds of buffers are useful for creating a stream of FlatBuffers.
- template<typename T>
- void FinishSizePrefixed(Offset<T> root,
- const char *file_identifier = nullptr) {
- Finish(root.o, file_identifier, true);
- }
-
- void SwapBufAllocator(FlatBufferBuilder &other) {
- buf_.swap_allocator(other.buf_);
- }
-
- protected:
- // You shouldn't really be copying instances of this class.
- FlatBufferBuilder(const FlatBufferBuilder &);
- FlatBufferBuilder &operator=(const FlatBufferBuilder &);
-
- void Finish(uoffset_t root, const char *file_identifier, bool size_prefix) {
- NotNested();
- buf_.clear_scratch();
- // This will cause the whole buffer to be aligned.
- PreAlign((size_prefix ? sizeof(uoffset_t) : 0) + sizeof(uoffset_t) +
- (file_identifier ? kFileIdentifierLength : 0),
- minalign_);
- if (file_identifier) {
- FLATBUFFERS_ASSERT(strlen(file_identifier) == kFileIdentifierLength);
- PushBytes(reinterpret_cast<const uint8_t *>(file_identifier),
- kFileIdentifierLength);
- }
- PushElement(ReferTo(root)); // Location of root.
- if (size_prefix) { PushElement(GetSize()); }
- finished = true;
- }
-
- struct FieldLoc {
- uoffset_t off;
- voffset_t id;
- };
-
- vector_downward buf_;
-
- // Accumulating offsets of table members while it is being built.
- // We store these in the scratch pad of buf_, after the vtable offsets.
- uoffset_t num_field_loc;
- // Track how much of the vtable is in use, so we can output the most compact
- // possible vtable.
- voffset_t max_voffset_;
-
- // Ensure objects are not nested.
- bool nested;
-
- // Ensure the buffer is finished before it is being accessed.
- bool finished;
-
- size_t minalign_;
-
- bool force_defaults_; // Serialize values equal to their defaults anyway.
-
- bool dedup_vtables_;
-
- struct StringOffsetCompare {
- StringOffsetCompare(const vector_downward &buf) : buf_(&buf) {}
- bool operator()(const Offset<String> &a, const Offset<String> &b) const {
- auto stra = reinterpret_cast<const String *>(buf_->data_at(a.o));
- auto strb = reinterpret_cast<const String *>(buf_->data_at(b.o));
- return StringLessThan(stra->data(), stra->size(), strb->data(),
- strb->size());
- }
- const vector_downward *buf_;
- };
-
- // For use with CreateSharedString. Instantiated on first use only.
- typedef std::set<Offset<String>, StringOffsetCompare> StringOffsetMap;
- StringOffsetMap *string_pool;
-
- private:
- // Allocates space for a vector of structures.
- // Must be completed with EndVectorOfStructs().
- template<typename T> T *StartVectorOfStructs(size_t vector_size) {
- StartVector(vector_size * sizeof(T) / AlignOf<T>(), AlignOf<T>());
- return reinterpret_cast<T *>(buf_.make_space(vector_size * sizeof(T)));
- }
-
- // End the vector of structues in the flatbuffers.
- // Vector should have previously be started with StartVectorOfStructs().
- template<typename T>
- Offset<Vector<const T *>> EndVectorOfStructs(size_t vector_size) {
- return Offset<Vector<const T *>>(EndVector(vector_size));
- }
-};
-/// @}
-
-/// @cond FLATBUFFERS_INTERNAL
-// Helpers to get a typed pointer to the root object contained in the buffer.
-template<typename T> T *GetMutableRoot(void *buf) {
- EndianCheck();
- return reinterpret_cast<T *>(
- reinterpret_cast<uint8_t *>(buf) +
- EndianScalar(*reinterpret_cast<uoffset_t *>(buf)));
-}
-
-template<typename T> const T *GetRoot(const void *buf) {
- return GetMutableRoot<T>(const_cast<void *>(buf));
-}
-
-template<typename T> const T *GetSizePrefixedRoot(const void *buf) {
- return GetRoot<T>(reinterpret_cast<const uint8_t *>(buf) + sizeof(uoffset_t));
-}
-
-/// Helpers to get a typed pointer to objects that are currently being built.
-/// @warning Creating new objects will lead to reallocations and invalidates
-/// the pointer!
-template<typename T>
-T *GetMutableTemporaryPointer(FlatBufferBuilder &fbb, Offset<T> offset) {
- return reinterpret_cast<T *>(fbb.GetCurrentBufferPointer() + fbb.GetSize() -
- offset.o);
-}
-
-template<typename T>
-const T *GetTemporaryPointer(FlatBufferBuilder &fbb, Offset<T> offset) {
- return GetMutableTemporaryPointer<T>(fbb, offset);
-}
-
-/// @brief Get a pointer to the the file_identifier section of the buffer.
-/// @return Returns a const char pointer to the start of the file_identifier
-/// characters in the buffer. The returned char * has length
-/// 'flatbuffers::FlatBufferBuilder::kFileIdentifierLength'.
-/// This function is UNDEFINED for FlatBuffers whose schema does not include
-/// a file_identifier (likely points at padding or the start of a the root
-/// vtable).
-inline const char *GetBufferIdentifier(const void *buf,
- bool size_prefixed = false) {
- return reinterpret_cast<const char *>(buf) +
- ((size_prefixed) ? 2 * sizeof(uoffset_t) : sizeof(uoffset_t));
-}
-
-// Helper to see if the identifier in a buffer has the expected value.
-inline bool BufferHasIdentifier(const void *buf, const char *identifier,
- bool size_prefixed = false) {
- return strncmp(GetBufferIdentifier(buf, size_prefixed), identifier,
- FlatBufferBuilder::kFileIdentifierLength) == 0;
-}
-
-// Helper class to verify the integrity of a FlatBuffer
-class Verifier FLATBUFFERS_FINAL_CLASS {
- public:
- Verifier(const uint8_t *buf, size_t buf_len, uoffset_t _max_depth = 64,
- uoffset_t _max_tables = 1000000, bool _check_alignment = true)
- : buf_(buf),
- size_(buf_len),
- depth_(0),
- max_depth_(_max_depth),
- num_tables_(0),
- max_tables_(_max_tables),
- upper_bound_(0),
- check_alignment_(_check_alignment) {
- FLATBUFFERS_ASSERT(size_ < FLATBUFFERS_MAX_BUFFER_SIZE);
- }
-
- // Central location where any verification failures register.
- bool Check(bool ok) const {
- // clang-format off
- #ifdef FLATBUFFERS_DEBUG_VERIFICATION_FAILURE
- FLATBUFFERS_ASSERT(ok);
- #endif
- #ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
- if (!ok)
- upper_bound_ = 0;
- #endif
- // clang-format on
- return ok;
- }
-
- // Verify any range within the buffer.
- bool Verify(size_t elem, size_t elem_len) const {
- // clang-format off
- #ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
- auto upper_bound = elem + elem_len;
- if (upper_bound_ < upper_bound)
- upper_bound_ = upper_bound;
- #endif
- // clang-format on
- return Check(elem_len < size_ && elem <= size_ - elem_len);
- }
-
- template<typename T> bool VerifyAlignment(size_t elem) const {
- return Check((elem & (sizeof(T) - 1)) == 0 || !check_alignment_);
- }
-
- // Verify a range indicated by sizeof(T).
- template<typename T> bool Verify(size_t elem) const {
- return VerifyAlignment<T>(elem) && Verify(elem, sizeof(T));
- }
-
- bool VerifyFromPointer(const uint8_t *p, size_t len) {
- auto o = static_cast<size_t>(p - buf_);
- return Verify(o, len);
- }
-
- // Verify relative to a known-good base pointer.
- bool Verify(const uint8_t *base, voffset_t elem_off, size_t elem_len) const {
- return Verify(static_cast<size_t>(base - buf_) + elem_off, elem_len);
- }
-
- template<typename T>
- bool Verify(const uint8_t *base, voffset_t elem_off) const {
- return Verify(static_cast<size_t>(base - buf_) + elem_off, sizeof(T));
- }
-
- // Verify a pointer (may be NULL) of a table type.
- template<typename T> bool VerifyTable(const T *table) {
- return !table || table->Verify(*this);
- }
-
- // Verify a pointer (may be NULL) of any vector type.
- template<typename T> bool VerifyVector(const Vector<T> *vec) const {
- return !vec || VerifyVectorOrString(reinterpret_cast<const uint8_t *>(vec),
- sizeof(T));
- }
-
- // Verify a pointer (may be NULL) of a vector to struct.
- template<typename T> bool VerifyVector(const Vector<const T *> *vec) const {
- return VerifyVector(reinterpret_cast<const Vector<T> *>(vec));
- }
-
- // Verify a pointer (may be NULL) to string.
- bool VerifyString(const String *str) const {
- size_t end;
- return !str || (VerifyVectorOrString(reinterpret_cast<const uint8_t *>(str),
- 1, &end) &&
- Verify(end, 1) && // Must have terminator
- Check(buf_[end] == '\0')); // Terminating byte must be 0.
- }
-
- // Common code between vectors and strings.
- bool VerifyVectorOrString(const uint8_t *vec, size_t elem_size,
- size_t *end = nullptr) const {
- auto veco = static_cast<size_t>(vec - buf_);
- // Check we can read the size field.
- if (!Verify<uoffset_t>(veco)) return false;
- // Check the whole array. If this is a string, the byte past the array
- // must be 0.
- auto size = ReadScalar<uoffset_t>(vec);
- auto max_elems = FLATBUFFERS_MAX_BUFFER_SIZE / elem_size;
- if (!Check(size < max_elems))
- return false; // Protect against byte_size overflowing.
- auto byte_size = sizeof(size) + elem_size * size;
- if (end) *end = veco + byte_size;
- return Verify(veco, byte_size);
- }
-
- // Special case for string contents, after the above has been called.
- bool VerifyVectorOfStrings(const Vector<Offset<String>> *vec) const {
- if (vec) {
- for (uoffset_t i = 0; i < vec->size(); i++) {
- if (!VerifyString(vec->Get(i))) return false;
- }
- }
- return true;
- }
-
- // Special case for table contents, after the above has been called.
- template<typename T> bool VerifyVectorOfTables(const Vector<Offset<T>> *vec) {
- if (vec) {
- for (uoffset_t i = 0; i < vec->size(); i++) {
- if (!vec->Get(i)->Verify(*this)) return false;
- }
- }
- return true;
- }
-
- __supress_ubsan__("unsigned-integer-overflow") bool VerifyTableStart(
- const uint8_t *table) {
- // Check the vtable offset.
- auto tableo = static_cast<size_t>(table - buf_);
- if (!Verify<soffset_t>(tableo)) return false;
- // This offset may be signed, but doing the subtraction unsigned always
- // gives the result we want.
- auto vtableo = tableo - static_cast<size_t>(ReadScalar<soffset_t>(table));
- // Check the vtable size field, then check vtable fits in its entirety.
- return VerifyComplexity() && Verify<voffset_t>(vtableo) &&
- VerifyAlignment<voffset_t>(ReadScalar<voffset_t>(buf_ + vtableo)) &&
- Verify(vtableo, ReadScalar<voffset_t>(buf_ + vtableo));
- }
-
- template<typename T>
- bool VerifyBufferFromStart(const char *identifier, size_t start) {
- if (identifier && !Check((size_ >= 2 * sizeof(flatbuffers::uoffset_t) &&
- BufferHasIdentifier(buf_ + start, identifier)))) {
- return false;
- }
-
- // Call T::Verify, which must be in the generated code for this type.
- auto o = VerifyOffset(start);
- return o && reinterpret_cast<const T *>(buf_ + start + o)->Verify(*this)
- // clang-format off
- #ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
- && GetComputedSize()
- #endif
- ;
- // clang-format on
- }
-
- // Verify this whole buffer, starting with root type T.
- template<typename T> bool VerifyBuffer() { return VerifyBuffer<T>(nullptr); }
-
- template<typename T> bool VerifyBuffer(const char *identifier) {
- return VerifyBufferFromStart<T>(identifier, 0);
- }
-
- template<typename T> bool VerifySizePrefixedBuffer(const char *identifier) {
- return Verify<uoffset_t>(0U) &&
- ReadScalar<uoffset_t>(buf_) == size_ - sizeof(uoffset_t) &&
- VerifyBufferFromStart<T>(identifier, sizeof(uoffset_t));
- }
-
- uoffset_t VerifyOffset(size_t start) const {
- if (!Verify<uoffset_t>(start)) return 0;
- auto o = ReadScalar<uoffset_t>(buf_ + start);
- // May not point to itself.
- if (!Check(o != 0)) return 0;
- // Can't wrap around / buffers are max 2GB.
- if (!Check(static_cast<soffset_t>(o) >= 0)) return 0;
- // Must be inside the buffer to create a pointer from it (pointer outside
- // buffer is UB).
- if (!Verify(start + o, 1)) return 0;
- return o;
- }
-
- uoffset_t VerifyOffset(const uint8_t *base, voffset_t start) const {
- return VerifyOffset(static_cast<size_t>(base - buf_) + start);
- }
-
- // Called at the start of a table to increase counters measuring data
- // structure depth and amount, and possibly bails out with false if
- // limits set by the constructor have been hit. Needs to be balanced
- // with EndTable().
- bool VerifyComplexity() {
- depth_++;
- num_tables_++;
- return Check(depth_ <= max_depth_ && num_tables_ <= max_tables_);
- }
-
- // Called at the end of a table to pop the depth count.
- bool EndTable() {
- depth_--;
- return true;
- }
-
- // Returns the message size in bytes
- size_t GetComputedSize() const {
- // clang-format off
- #ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
- uintptr_t size = upper_bound_;
- // Align the size to uoffset_t
- size = (size - 1 + sizeof(uoffset_t)) & ~(sizeof(uoffset_t) - 1);
- return (size > size_) ? 0 : size;
- #else
- // Must turn on FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE for this to work.
- (void)upper_bound_;
- FLATBUFFERS_ASSERT(false);
- return 0;
- #endif
- // clang-format on
- }
-
- private:
- const uint8_t *buf_;
- size_t size_;
- uoffset_t depth_;
- uoffset_t max_depth_;
- uoffset_t num_tables_;
- uoffset_t max_tables_;
- mutable size_t upper_bound_;
- bool check_alignment_;
-};
-
-// Convenient way to bundle a buffer and its length, to pass it around
-// typed by its root.
-// A BufferRef does not own its buffer.
-struct BufferRefBase {}; // for std::is_base_of
-template<typename T> struct BufferRef : BufferRefBase {
- BufferRef() : buf(nullptr), len(0), must_free(false) {}
- BufferRef(uint8_t *_buf, uoffset_t _len)
- : buf(_buf), len(_len), must_free(false) {}
-
- ~BufferRef() {
- if (must_free) free(buf);
- }
-
- const T *GetRoot() const { return flatbuffers::GetRoot<T>(buf); }
-
- bool Verify() {
- Verifier verifier(buf, len);
- return verifier.VerifyBuffer<T>(nullptr);
- }
-
- uint8_t *buf;
- uoffset_t len;
- bool must_free;
-};
-
-// "structs" are flat structures that do not have an offset table, thus
-// always have all members present and do not support forwards/backwards
-// compatible extensions.
-
-class Struct FLATBUFFERS_FINAL_CLASS {
- public:
- template<typename T> T GetField(uoffset_t o) const {
- return ReadScalar<T>(&data_[o]);
- }
-
- template<typename T> T GetStruct(uoffset_t o) const {
- return reinterpret_cast<T>(&data_[o]);
- }
-
- const uint8_t *GetAddressOf(uoffset_t o) const { return &data_[o]; }
- uint8_t *GetAddressOf(uoffset_t o) { return &data_[o]; }
-
- private:
- // private constructor & copy constructor: you obtain instances of this
- // class by pointing to existing data only
- Struct();
- Struct(const Struct &);
- Struct &operator=(const Struct &);
-
- uint8_t data_[1];
-};
-
-// "tables" use an offset table (possibly shared) that allows fields to be
-// omitted and added at will, but uses an extra indirection to read.
-class Table {
- public:
- const uint8_t *GetVTable() const {
- return data_ - ReadScalar<soffset_t>(data_);
- }
-
- // This gets the field offset for any of the functions below it, or 0
- // if the field was not present.
- voffset_t GetOptionalFieldOffset(voffset_t field) const {
- // The vtable offset is always at the start.
- auto vtable = GetVTable();
- // The first element is the size of the vtable (fields + type id + itself).
- auto vtsize = ReadScalar<voffset_t>(vtable);
- // If the field we're accessing is outside the vtable, we're reading older
- // data, so it's the same as if the offset was 0 (not present).
- return field < vtsize ? ReadScalar<voffset_t>(vtable + field) : 0;
- }
-
- template<typename T> T GetField(voffset_t field, T defaultval) const {
- auto field_offset = GetOptionalFieldOffset(field);
- return field_offset ? ReadScalar<T>(data_ + field_offset) : defaultval;
- }
-
- template<typename P> P GetPointer(voffset_t field) {
- auto field_offset = GetOptionalFieldOffset(field);
- auto p = data_ + field_offset;
- return field_offset ? reinterpret_cast<P>(p + ReadScalar<uoffset_t>(p))
- : nullptr;
- }
- template<typename P> P GetPointer(voffset_t field) const {
- return const_cast<Table *>(this)->GetPointer<P>(field);
- }
-
- template<typename P> P GetStruct(voffset_t field) const {
- auto field_offset = GetOptionalFieldOffset(field);
- auto p = const_cast<uint8_t *>(data_ + field_offset);
- return field_offset ? reinterpret_cast<P>(p) : nullptr;
- }
-
- template<typename Raw, typename Face>
- flatbuffers::Optional<Face> GetOptional(voffset_t field) const {
- auto field_offset = GetOptionalFieldOffset(field);
- auto p = data_ + field_offset;
- return field_offset ? Optional<Face>(static_cast<Face>(ReadScalar<Raw>(p)))
- : Optional<Face>();
- }
-
- template<typename T> bool SetField(voffset_t field, T val, T def) {
- auto field_offset = GetOptionalFieldOffset(field);
- if (!field_offset) return IsTheSameAs(val, def);
- WriteScalar(data_ + field_offset, val);
- return true;
- }
- template<typename T> bool SetField(voffset_t field, T val) {
- auto field_offset = GetOptionalFieldOffset(field);
- if (!field_offset) return false;
- WriteScalar(data_ + field_offset, val);
- return true;
- }
-
- bool SetPointer(voffset_t field, const uint8_t *val) {
- auto field_offset = GetOptionalFieldOffset(field);
- if (!field_offset) return false;
- WriteScalar(data_ + field_offset,
- static_cast<uoffset_t>(val - (data_ + field_offset)));
- return true;
- }
-
- uint8_t *GetAddressOf(voffset_t field) {
- auto field_offset = GetOptionalFieldOffset(field);
- return field_offset ? data_ + field_offset : nullptr;
- }
- const uint8_t *GetAddressOf(voffset_t field) const {
- return const_cast<Table *>(this)->GetAddressOf(field);
- }
-
- bool CheckField(voffset_t field) const {
- return GetOptionalFieldOffset(field) != 0;
- }
-
- // Verify the vtable of this table.
- // Call this once per table, followed by VerifyField once per field.
- bool VerifyTableStart(Verifier &verifier) const {
- return verifier.VerifyTableStart(data_);
- }
-
- // Verify a particular field.
- template<typename T>
- bool VerifyField(const Verifier &verifier, voffset_t field) const {
- // Calling GetOptionalFieldOffset should be safe now thanks to
- // VerifyTable().
- auto field_offset = GetOptionalFieldOffset(field);
- // Check the actual field.
- return !field_offset || verifier.Verify<T>(data_, field_offset);
- }
-
- // VerifyField for required fields.
- template<typename T>
- bool VerifyFieldRequired(const Verifier &verifier, voffset_t field) const {
- auto field_offset = GetOptionalFieldOffset(field);
- return verifier.Check(field_offset != 0) &&
- verifier.Verify<T>(data_, field_offset);
- }
-
- // Versions for offsets.
- bool VerifyOffset(const Verifier &verifier, voffset_t field) const {
- auto field_offset = GetOptionalFieldOffset(field);
- return !field_offset || verifier.VerifyOffset(data_, field_offset);
- }
-
- bool VerifyOffsetRequired(const Verifier &verifier, voffset_t field) const {
- auto field_offset = GetOptionalFieldOffset(field);
- return verifier.Check(field_offset != 0) &&
- verifier.VerifyOffset(data_, field_offset);
- }
-
- private:
- // private constructor & copy constructor: you obtain instances of this
- // class by pointing to existing data only
- Table();
- Table(const Table &other);
- Table &operator=(const Table &);
-
- uint8_t data_[1];
-};
-
-// This specialization allows avoiding warnings like:
-// MSVC C4800: type: forcing value to bool 'true' or 'false'.
-template<>
-inline flatbuffers::Optional<bool> Table::GetOptional<uint8_t, bool>(
- voffset_t field) const {
- auto field_offset = GetOptionalFieldOffset(field);
- auto p = data_ + field_offset;
- return field_offset ? Optional<bool>(ReadScalar<uint8_t>(p) != 0)
- : Optional<bool>();
-}
-
-template<typename T>
-void FlatBufferBuilder::Required(Offset<T> table, voffset_t field) {
- auto table_ptr = reinterpret_cast<const Table *>(buf_.data_at(table.o));
- bool ok = table_ptr->GetOptionalFieldOffset(field) != 0;
- // If this fails, the caller will show what field needs to be set.
- FLATBUFFERS_ASSERT(ok);
- (void)ok;
-}
/// @brief This can compute the start of a FlatBuffer from a root pointer, i.e.
/// it is the opposite transformation of GetRoot().
@@ -2661,7 +56,7 @@
// file_identifier, and alignment padding) to see which points to the root.
// None of the other values can "impersonate" the root since they will either
// be 0 or four ASCII characters.
- static_assert(FlatBufferBuilder::kFileIdentifierLength == sizeof(uoffset_t),
+ static_assert(flatbuffers::kFileIdentifierLength == sizeof(uoffset_t),
"file_identifier is assumed to be the same size as uoffset_t");
for (auto possible_roots = FLATBUFFERS_MAX_ALIGNMENT / sizeof(uoffset_t) + 1;
possible_roots; possible_roots--) {
@@ -2697,16 +92,9 @@
/// if you wish. The resolver does the opposite lookup, for when the object
/// is being serialized again.
typedef uint64_t hash_value_t;
-// clang-format off
-#ifdef FLATBUFFERS_CPP98_STL
- typedef void (*resolver_function_t)(void **pointer_adr, hash_value_t hash);
- typedef hash_value_t (*rehasher_function_t)(void *pointer);
-#else
- typedef std::function<void (void **pointer_adr, hash_value_t hash)>
- resolver_function_t;
- typedef std::function<hash_value_t (void *pointer)> rehasher_function_t;
-#endif
-// clang-format on
+typedef std::function<void(void **pointer_adr, hash_value_t hash)>
+ resolver_function_t;
+typedef std::function<hash_value_t(void *pointer)> rehasher_function_t;
// Helper function to test if a field is present, using any of the field
// enums in the generated code.
@@ -2763,7 +151,7 @@
// Minimal reflection via code generation.
// Besides full-fat reflection (see reflection.h) and parsing/printing by
-// loading schemas (see idl.h), we can also have code generation for mimimal
+// loading schemas (see idl.h), we can also have code generation for minimal
// reflection data which allows pretty-printing and other uses without needing
// a schema or a parser.
// Generate code with --reflect-types (types only) or --reflect-names (names
@@ -2812,9 +200,12 @@
// bitfields is otherwise implementation-defined and causes warnings on older
// GCC compilers.
struct TypeCode {
- unsigned short base_type : 4; // ElementaryType
- unsigned short is_repeating : 1; // Either vector (in table) or array (in struct)
- signed short sequence_ref : 11; // Index into type_refs below, or -1 for none.
+ // ElementaryType
+ unsigned short base_type : 4;
+ // Either vector (in table) or array (in struct)
+ unsigned short is_repeating : 1;
+ // Index into type_refs below, or -1 for none.
+ signed short sequence_ref : 11;
};
static_assert(sizeof(TypeCode) == 2, "TypeCode");
@@ -2835,27 +226,13 @@
};
// String which identifies the current version of FlatBuffers.
-// flatbuffer_version_string is used by Google developers to identify which
-// applications uploaded to Google Play are using this library. This allows
-// the development team at Google to determine the popularity of the library.
-// How it works: Applications that are uploaded to the Google Play Store are
-// scanned for this version string. We track which applications are using it
-// to measure popularity. You are free to remove it (of course) but we would
-// appreciate if you left it in.
+inline const char *flatbuffers_version_string() {
+ return "FlatBuffers " FLATBUFFERS_STRING(FLATBUFFERS_VERSION_MAJOR) "."
+ FLATBUFFERS_STRING(FLATBUFFERS_VERSION_MINOR) "."
+ FLATBUFFERS_STRING(FLATBUFFERS_VERSION_REVISION);
+}
-// Weak linkage is culled by VS & doesn't work on cygwin.
// clang-format off
-#if !defined(_WIN32) && !defined(__CYGWIN__)
-
-extern volatile __attribute__((weak)) const char *flatbuffer_version_string;
-volatile __attribute__((weak)) const char *flatbuffer_version_string =
- "FlatBuffers "
- FLATBUFFERS_STRING(FLATBUFFERS_VERSION_MAJOR) "."
- FLATBUFFERS_STRING(FLATBUFFERS_VERSION_MINOR) "."
- FLATBUFFERS_STRING(FLATBUFFERS_VERSION_REVISION);
-
-#endif // !defined(_WIN32) && !defined(__CYGWIN__)
-
#define FLATBUFFERS_DEFINE_BITMASK_OPERATORS(E, T)\
inline E operator | (E lhs, E rhs){\
return E(T(lhs) | T(rhs));\
diff --git a/include/flatbuffers/flatc.h b/include/flatbuffers/flatc.h
index 5e2709e..3dba5e1 100644
--- a/include/flatbuffers/flatc.h
+++ b/include/flatbuffers/flatc.h
@@ -21,6 +21,7 @@
#include <limits>
#include <string>
+#include "flatbuffers/bfbs_generator.h"
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
@@ -30,6 +31,13 @@
extern void LogCompilerWarn(const std::string &warn);
extern void LogCompilerError(const std::string &err);
+struct FlatCOption {
+ std::string short_opt;
+ std::string long_opt;
+ std::string parameter;
+ std::string description;
+};
+
class FlatCompiler {
public:
// Output generator for the various programming languages and formats we
@@ -41,16 +49,18 @@
typedef std::string (*MakeRuleFn)(const flatbuffers::Parser &parser,
const std::string &path,
const std::string &file_name);
+ typedef bool (*ParsingCompletedFn)(const flatbuffers::Parser &parser,
+ const std::string &output_path);
GenerateFn generate;
- const char *generator_opt_short;
- const char *generator_opt_long;
const char *lang_name;
bool schema_only;
GenerateFn generateGRPC;
flatbuffers::IDLOptions::Language lang;
- const char *generator_help;
+ FlatCOption option;
MakeRuleFn make_rule;
+ BfbsGenerator *bfbs_generator;
+ ParsingCompletedFn parsing_completed;
};
typedef void (*WarnFn)(const FlatCompiler *flatc, const std::string &warn,
@@ -77,6 +87,7 @@
int Compile(int argc, const char **argv);
+ std::string GetShortUsageString(const char *program_name) const;
std::string GetUsageString(const char *program_name) const;
private:
diff --git a/include/flatbuffers/flexbuffers.h b/include/flatbuffers/flexbuffers.h
index f2088b3..b4b0332 100644
--- a/include/flatbuffers/flexbuffers.h
+++ b/include/flatbuffers/flexbuffers.h
@@ -53,7 +53,7 @@
FBT_INT = 1,
FBT_UINT = 2,
FBT_FLOAT = 3,
- // Types above stored inline, types below store an offset.
+ // Types above stored inline, types below (except FBT_BOOL) store an offset.
FBT_KEY = 4,
FBT_STRING = 5,
FBT_INDIRECT_INT = 6,
@@ -81,6 +81,8 @@
FBT_BOOL = 26,
FBT_VECTOR_BOOL =
36, // To Allow the same type of conversion of type to vector type
+
+ FBT_MAX_TYPE = 37
};
inline bool IsInline(Type t) { return t <= FBT_FLOAT || t == FBT_BOOL; }
@@ -155,7 +157,8 @@
// constant, which here it isn't. Test if memcpy is still faster than
// the conditionals in ReadSizedScalar. Can also use inline asm.
// clang-format off
- #if defined(_MSC_VER) && (defined(_M_X64) || defined _M_IX86)
+ #if defined(_MSC_VER) && defined(_M_X64) && !defined(_M_ARM64EC)
+ // This is 64-bit Windows only, __movsb does not work on 32-bit Windows.
uint64_t u = 0;
__movsb(reinterpret_cast<uint8_t *>(&u),
reinterpret_cast<const uint8_t *>(data), byte_width);
@@ -319,8 +322,8 @@
return data_ == FixedTypedVector::EmptyFixedTypedVector().data_;
}
- Type ElementType() { return type_; }
- uint8_t size() { return len_; }
+ Type ElementType() const { return type_; }
+ uint8_t size() const { return len_; }
private:
Type type_;
@@ -368,10 +371,7 @@
class Reference {
public:
Reference()
- : data_(nullptr),
- parent_width_(0),
- byte_width_(BIT_WIDTH_8),
- type_(FBT_NULL) {}
+ : data_(nullptr), parent_width_(0), byte_width_(0), type_(FBT_NULL) {}
Reference(const uint8_t *data, uint8_t parent_width, uint8_t byte_width,
Type type)
@@ -572,7 +572,23 @@
auto keys = m.Keys();
auto vals = m.Values();
for (size_t i = 0; i < keys.size(); i++) {
- keys[i].ToString(true, keys_quoted, s);
+ bool kq = keys_quoted;
+ if (!kq) {
+ // FlexBuffers keys may contain arbitrary characters, only allow
+ // unquoted if it looks like an "identifier":
+ const char *p = keys[i].AsKey();
+ if (!flatbuffers::is_alpha(*p) && *p != '_') {
+ kq = true;
+ } else {
+ while (*++p) {
+ if (!flatbuffers::is_alnum(*p) && *p != '_') {
+ kq = true;
+ break;
+ }
+ }
+ }
+ }
+ keys[i].ToString(true, kq, s);
s += ": ";
vals[i].ToString(true, keys_quoted, s);
if (i < keys.size() - 1) s += ", ";
@@ -756,6 +772,8 @@
return false;
}
+ friend class Verifier;
+
const uint8_t *data_;
uint8_t parent_width_;
uint8_t byte_width_;
@@ -850,6 +868,7 @@
case 2: comp = KeyCompare<uint16_t>; break;
case 4: comp = KeyCompare<uint32_t>; break;
case 8: comp = KeyCompare<uint64_t>; break;
+ default: FLATBUFFERS_ASSERT(false); return Reference();
}
auto res = std::bsearch(key, keys.data_, keys.size(), keys.byte_width_, comp);
if (!res) return Reference(nullptr, 1, NullPackedType());
@@ -872,7 +891,7 @@
}
inline Reference GetRoot(const std::vector<uint8_t> &buffer) {
- return GetRoot(flatbuffers::vector_data(buffer), buffer.size());
+ return GetRoot(buffer.data(), buffer.size());
}
// Flags that configure how the Builder behaves.
@@ -1068,7 +1087,16 @@
return CreateBlob(data, len, 0, FBT_BLOB);
}
size_t Blob(const std::vector<uint8_t> &v) {
- return CreateBlob(flatbuffers::vector_data(v), v.size(), 0, FBT_BLOB);
+ return CreateBlob(v.data(), v.size(), 0, FBT_BLOB);
+ }
+
+ void Blob(const char *key, const void *data, size_t len) {
+ Key(key);
+ Blob(data, len);
+ }
+ void Blob(const char *key, const std::vector<uint8_t> &v) {
+ Key(key);
+ Blob(v);
}
// TODO(wvo): support all the FlexBuffer types (like flexbuffers::String),
@@ -1086,7 +1114,7 @@
return stack_.size();
}
- // TODO(wvo): allow this to specify an aligment greater than the natural
+ // TODO(wvo): allow this to specify an alignment greater than the natural
// alignment.
size_t EndVector(size_t start, bool typed, bool fixed) {
auto vec = CreateVector(start, stack_.size() - start, 1, typed, fixed);
@@ -1121,27 +1149,24 @@
// step automatically when appliccable, and encourage people to write in
// sorted fashion.
// std::sort is typically already a lot faster on sorted data though.
- auto dict =
- reinterpret_cast<TwoValue *>(flatbuffers::vector_data(stack_) + start);
- std::sort(dict, dict + len,
- [&](const TwoValue &a, const TwoValue &b) -> bool {
- auto as = reinterpret_cast<const char *>(
- flatbuffers::vector_data(buf_) + a.key.u_);
- auto bs = reinterpret_cast<const char *>(
- flatbuffers::vector_data(buf_) + b.key.u_);
- auto comp = strcmp(as, bs);
- // We want to disallow duplicate keys, since this results in a
- // map where values cannot be found.
- // But we can't assert here (since we don't want to fail on
- // random JSON input) or have an error mechanism.
- // Instead, we set has_duplicate_keys_ in the builder to
- // signal this.
- // TODO: Have to check for pointer equality, as some sort
- // implementation apparently call this function with the same
- // element?? Why?
- if (!comp && &a != &b) has_duplicate_keys_ = true;
- return comp < 0;
- });
+ auto dict = reinterpret_cast<TwoValue *>(stack_.data() + start);
+ std::sort(
+ dict, dict + len, [&](const TwoValue &a, const TwoValue &b) -> bool {
+ auto as = reinterpret_cast<const char *>(buf_.data() + a.key.u_);
+ auto bs = reinterpret_cast<const char *>(buf_.data() + b.key.u_);
+ auto comp = strcmp(as, bs);
+ // We want to disallow duplicate keys, since this results in a
+ // map where values cannot be found.
+ // But we can't assert here (since we don't want to fail on
+ // random JSON input) or have an error mechanism.
+ // Instead, we set has_duplicate_keys_ in the builder to
+ // signal this.
+ // TODO: Have to check for pointer equality, as some sort
+ // implementation apparently call this function with the same
+ // element?? Why?
+ if (!comp && &a != &b) has_duplicate_keys_ = true;
+ return comp < 0;
+ });
// First create a vector out of all keys.
// TODO(wvo): if kBuilderFlagShareKeyVectors is true, see if we can share
// the first vector.
@@ -1195,7 +1220,7 @@
Vector(elems, len);
}
template<typename T> void Vector(const std::vector<T> &vec) {
- Vector(flatbuffers::vector_data(vec), vec.size());
+ Vector(vec.data(), vec.size());
}
template<typename F> size_t TypedVector(F f) {
@@ -1397,12 +1422,10 @@
template<typename T> static Type GetScalarType() {
static_assert(flatbuffers::is_scalar<T>::value, "Unrelated types");
- return flatbuffers::is_floating_point<T>::value
- ? FBT_FLOAT
- : flatbuffers::is_same<T, bool>::value
- ? FBT_BOOL
- : (flatbuffers::is_unsigned<T>::value ? FBT_UINT
- : FBT_INT);
+ return flatbuffers::is_floating_point<T>::value ? FBT_FLOAT
+ : flatbuffers::is_same<T, bool>::value
+ ? FBT_BOOL
+ : (flatbuffers::is_unsigned<T>::value ? FBT_UINT : FBT_INT);
}
public:
@@ -1552,9 +1575,9 @@
}
}
}
- // If you get this assert, your fixed types are not one of:
+ // If you get this assert, your typed types are not one of:
// Int / UInt / Float / Key.
- FLATBUFFERS_ASSERT(!fixed || IsTypedVectorElementType(vector_type));
+ FLATBUFFERS_ASSERT(!typed || IsTypedVectorElementType(vector_type));
auto byte_width = Align(bit_width);
// Write vector. First the keys width/offset if available, and size.
if (keys) {
@@ -1597,10 +1620,8 @@
struct KeyOffsetCompare {
explicit KeyOffsetCompare(const std::vector<uint8_t> &buf) : buf_(&buf) {}
bool operator()(size_t a, size_t b) const {
- auto stra =
- reinterpret_cast<const char *>(flatbuffers::vector_data(*buf_) + a);
- auto strb =
- reinterpret_cast<const char *>(flatbuffers::vector_data(*buf_) + b);
+ auto stra = reinterpret_cast<const char *>(buf_->data() + a);
+ auto strb = reinterpret_cast<const char *>(buf_->data() + b);
return strcmp(stra, strb) < 0;
}
const std::vector<uint8_t> *buf_;
@@ -1611,11 +1632,10 @@
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);
- auto strb = reinterpret_cast<const char *>(
- flatbuffers::vector_data(*buf_) + b.first);
- return strncmp(stra, strb, (std::min)(a.second, b.second) + 1) < 0;
+ auto stra = buf_->data() + a.first;
+ auto strb = buf_->data() + b.first;
+ auto cr = memcmp(stra, strb, (std::min)(a.second, b.second) + 1);
+ return cr < 0 || (cr == 0 && a.second < b.second);
}
const std::vector<uint8_t> *buf_;
};
@@ -1625,8 +1645,249 @@
KeyOffsetMap key_pool;
StringOffsetMap string_pool;
+
+ friend class Verifier;
};
+// Helper class to verify the integrity of a FlexBuffer
+class Verifier FLATBUFFERS_FINAL_CLASS {
+ public:
+ Verifier(const uint8_t *buf, size_t buf_len,
+ // Supplying this vector likely results in faster verification
+ // of larger buffers with many shared keys/strings, but
+ // comes at the cost of using additional memory the same size of
+ // the buffer being verified, so it is by default off.
+ std::vector<uint8_t> *reuse_tracker = nullptr,
+ bool _check_alignment = true, size_t max_depth = 64)
+ : buf_(buf),
+ size_(buf_len),
+ depth_(0),
+ max_depth_(max_depth),
+ num_vectors_(0),
+ max_vectors_(buf_len),
+ check_alignment_(_check_alignment),
+ reuse_tracker_(reuse_tracker) {
+ FLATBUFFERS_ASSERT(size_ < FLATBUFFERS_MAX_BUFFER_SIZE);
+ if (reuse_tracker_) {
+ reuse_tracker_->clear();
+ reuse_tracker_->resize(size_, PackedType(BIT_WIDTH_8, FBT_NULL));
+ }
+ }
+
+ private:
+ // Central location where any verification failures register.
+ bool Check(bool ok) const {
+ // clang-format off
+ #ifdef FLATBUFFERS_DEBUG_VERIFICATION_FAILURE
+ FLATBUFFERS_ASSERT(ok);
+ #endif
+ // clang-format on
+ return ok;
+ }
+
+ // Verify any range within the buffer.
+ bool VerifyFrom(size_t elem, size_t elem_len) const {
+ return Check(elem_len < size_ && elem <= size_ - elem_len);
+ }
+ bool VerifyBefore(size_t elem, size_t elem_len) const {
+ return Check(elem_len <= elem);
+ }
+
+ bool VerifyFromPointer(const uint8_t *p, size_t len) {
+ auto o = static_cast<size_t>(p - buf_);
+ return VerifyFrom(o, len);
+ }
+ bool VerifyBeforePointer(const uint8_t *p, size_t len) {
+ auto o = static_cast<size_t>(p - buf_);
+ return VerifyBefore(o, len);
+ }
+
+ bool VerifyByteWidth(size_t width) {
+ return Check(width == 1 || width == 2 || width == 4 || width == 8);
+ }
+
+ bool VerifyType(int type) { return Check(type >= 0 && type < FBT_MAX_TYPE); }
+
+ bool VerifyOffset(uint64_t off, const uint8_t *p) {
+ return Check(off <= static_cast<uint64_t>(size_)) &&
+ off <= static_cast<uint64_t>(p - buf_);
+ }
+
+ bool VerifyAlignment(const uint8_t *p, size_t size) const {
+ auto o = static_cast<size_t>(p - buf_);
+ return Check((o & (size - 1)) == 0 || !check_alignment_);
+ }
+
+// Macro, since we want to escape from parent function & use lazy args.
+#define FLEX_CHECK_VERIFIED(P, PACKED_TYPE) \
+ if (reuse_tracker_) { \
+ auto packed_type = PACKED_TYPE; \
+ auto existing = (*reuse_tracker_)[P - buf_]; \
+ if (existing == packed_type) return true; \
+ /* Fail verification if already set with different type! */ \
+ if (!Check(existing == 0)) return false; \
+ (*reuse_tracker_)[P - buf_] = packed_type; \
+ }
+
+ bool VerifyVector(Reference r, const uint8_t *p, Type elem_type) {
+ // Any kind of nesting goes thru this function, so guard against that
+ // here, both with simple nesting checks, and the reuse tracker if on.
+ depth_++;
+ num_vectors_++;
+ if (!Check(depth_ <= max_depth_ && num_vectors_ <= max_vectors_))
+ return false;
+ auto size_byte_width = r.byte_width_;
+ FLEX_CHECK_VERIFIED(p,
+ PackedType(Builder::WidthB(size_byte_width), r.type_));
+ if (!VerifyBeforePointer(p, size_byte_width)) return false;
+ auto sized = Sized(p, size_byte_width);
+ auto num_elems = sized.size();
+ auto elem_byte_width = r.type_ == FBT_STRING || r.type_ == FBT_BLOB
+ ? uint8_t(1)
+ : r.byte_width_;
+ auto max_elems = SIZE_MAX / elem_byte_width;
+ if (!Check(num_elems < max_elems))
+ return false; // Protect against byte_size overflowing.
+ auto byte_size = num_elems * elem_byte_width;
+ if (!VerifyFromPointer(p, byte_size)) return false;
+ if (elem_type == FBT_NULL) {
+ // Verify type bytes after the vector.
+ if (!VerifyFromPointer(p + byte_size, num_elems)) return false;
+ auto v = Vector(p, size_byte_width);
+ for (size_t i = 0; i < num_elems; i++)
+ if (!VerifyRef(v[i])) return false;
+ } else if (elem_type == FBT_KEY) {
+ auto v = TypedVector(p, elem_byte_width, FBT_KEY);
+ for (size_t i = 0; i < num_elems; i++)
+ if (!VerifyRef(v[i])) return false;
+ } else {
+ FLATBUFFERS_ASSERT(IsInline(elem_type));
+ }
+ depth_--;
+ return true;
+ }
+
+ bool VerifyKeys(const uint8_t *p, uint8_t byte_width) {
+ // The vector part of the map has already been verified.
+ const size_t num_prefixed_fields = 3;
+ if (!VerifyBeforePointer(p, byte_width * num_prefixed_fields)) return false;
+ p -= byte_width * num_prefixed_fields;
+ auto off = ReadUInt64(p, byte_width);
+ if (!VerifyOffset(off, p)) return false;
+ auto key_byte_with =
+ static_cast<uint8_t>(ReadUInt64(p + byte_width, byte_width));
+ if (!VerifyByteWidth(key_byte_with)) return false;
+ return VerifyVector(Reference(p, byte_width, key_byte_with, FBT_VECTOR_KEY),
+ p - off, FBT_KEY);
+ }
+
+ bool VerifyKey(const uint8_t *p) {
+ FLEX_CHECK_VERIFIED(p, PackedType(BIT_WIDTH_8, FBT_KEY));
+ while (p < buf_ + size_)
+ if (*p++) return true;
+ return false;
+ }
+
+#undef FLEX_CHECK_VERIFIED
+
+ bool VerifyTerminator(const String &s) {
+ return VerifyFromPointer(reinterpret_cast<const uint8_t *>(s.c_str()),
+ s.size() + 1);
+ }
+
+ bool VerifyRef(Reference r) {
+ // r.parent_width_ and r.data_ already verified.
+ if (!VerifyByteWidth(r.byte_width_) || !VerifyType(r.type_)) {
+ return false;
+ }
+ if (IsInline(r.type_)) {
+ // Inline scalars, don't require further verification.
+ return true;
+ }
+ // All remaining types are an offset.
+ auto off = ReadUInt64(r.data_, r.parent_width_);
+ if (!VerifyOffset(off, r.data_)) return false;
+ auto p = r.Indirect();
+ if (!VerifyAlignment(p, r.byte_width_)) return false;
+ switch (r.type_) {
+ case FBT_INDIRECT_INT:
+ case FBT_INDIRECT_UINT:
+ case FBT_INDIRECT_FLOAT: return VerifyFromPointer(p, r.byte_width_);
+ case FBT_KEY: return VerifyKey(p);
+ case FBT_MAP:
+ return VerifyVector(r, p, FBT_NULL) && VerifyKeys(p, r.byte_width_);
+ case FBT_VECTOR: return VerifyVector(r, p, FBT_NULL);
+ case FBT_VECTOR_INT: return VerifyVector(r, p, FBT_INT);
+ case FBT_VECTOR_BOOL:
+ case FBT_VECTOR_UINT: return VerifyVector(r, p, FBT_UINT);
+ case FBT_VECTOR_FLOAT: return VerifyVector(r, p, FBT_FLOAT);
+ case FBT_VECTOR_KEY: return VerifyVector(r, p, FBT_KEY);
+ case FBT_VECTOR_STRING_DEPRECATED:
+ // Use of FBT_KEY here intentional, see elsewhere.
+ return VerifyVector(r, p, FBT_KEY);
+ case FBT_BLOB: return VerifyVector(r, p, FBT_UINT);
+ case FBT_STRING:
+ return VerifyVector(r, p, FBT_UINT) &&
+ VerifyTerminator(String(p, r.byte_width_));
+ case FBT_VECTOR_INT2:
+ case FBT_VECTOR_UINT2:
+ case FBT_VECTOR_FLOAT2:
+ case FBT_VECTOR_INT3:
+ case FBT_VECTOR_UINT3:
+ case FBT_VECTOR_FLOAT3:
+ case FBT_VECTOR_INT4:
+ case FBT_VECTOR_UINT4:
+ case FBT_VECTOR_FLOAT4: {
+ uint8_t len = 0;
+ auto vtype = ToFixedTypedVectorElementType(r.type_, &len);
+ if (!VerifyType(vtype)) return false;
+ return VerifyFromPointer(p, r.byte_width_ * len);
+ }
+ default: return false;
+ }
+ }
+
+ public:
+ bool VerifyBuffer() {
+ if (!Check(size_ >= 3)) return false;
+ auto end = buf_ + size_;
+ auto byte_width = *--end;
+ auto packed_type = *--end;
+ return VerifyByteWidth(byte_width) && Check(end - buf_ >= byte_width) &&
+ VerifyRef(Reference(end - byte_width, byte_width, packed_type));
+ }
+
+ private:
+ const uint8_t *buf_;
+ size_t size_;
+ size_t depth_;
+ const size_t max_depth_;
+ size_t num_vectors_;
+ const size_t max_vectors_;
+ bool check_alignment_;
+ std::vector<uint8_t> *reuse_tracker_;
+};
+
+// Utility function that contructs the Verifier for you, see above for
+// parameters.
+inline bool VerifyBuffer(const uint8_t *buf, size_t buf_len,
+ std::vector<uint8_t> *reuse_tracker = nullptr) {
+ Verifier verifier(buf, buf_len, reuse_tracker);
+ return verifier.VerifyBuffer();
+}
+
+#ifdef FLATBUFFERS_H_
+// This is a verifier utility function that works together with the
+// FlatBuffers verifier, which should only be present if flatbuffer.h
+// has been included (which it typically is in generated code).
+inline bool VerifyNestedFlexBuffer(const flatbuffers::Vector<uint8_t> *nv,
+ flatbuffers::Verifier &verifier) {
+ if (!nv) return true;
+ return verifier.Check(flexbuffers::VerifyBuffer(
+ nv->data(), nv->size(), verifier.GetFlexReuseTracker()));
+}
+#endif
+
} // namespace flexbuffers
#if defined(_MSC_VER)
diff --git a/include/flatbuffers/grpc.h b/include/flatbuffers/grpc.h
index bd24c50..5d15bc5 100644
--- a/include/flatbuffers/grpc.h
+++ b/include/flatbuffers/grpc.h
@@ -20,8 +20,9 @@
// Helper functionality to glue FlatBuffers and GRPC.
#include "flatbuffers/flatbuffers.h"
-#include "grpc++/support/byte_buffer.h"
#include "grpc/byte_buffer_reader.h"
+#include "grpcpp/support/byte_buffer.h"
+#include "grpcpp/support/slice.h"
namespace flatbuffers {
namespace grpc {
@@ -32,33 +33,23 @@
// is refcounted and ownership is be managed automatically.
template<class T> class Message {
public:
- Message() : slice_(grpc_empty_slice()) {}
+ Message() {}
- Message(grpc_slice slice, bool add_ref)
- : slice_(add_ref ? grpc_slice_ref(slice) : slice) {}
+ Message(::grpc::Slice slice) : slice_(slice) {}
Message &operator=(const Message &other) = delete;
- Message(Message &&other) : slice_(other.slice_) {
- other.slice_ = grpc_empty_slice();
- }
+ Message(Message &&other) = default;
Message(const Message &other) = delete;
- Message &operator=(Message &&other) {
- grpc_slice_unref(slice_);
- slice_ = other.slice_;
- other.slice_ = grpc_empty_slice();
- return *this;
- }
+ Message &operator=(Message &&other) = default;
- ~Message() { grpc_slice_unref(slice_); }
+ const uint8_t *mutable_data() const { return slice_.begin(); }
- const uint8_t *mutable_data() const { return GRPC_SLICE_START_PTR(slice_); }
+ const uint8_t *data() const { return slice_.begin(); }
- const uint8_t *data() const { return GRPC_SLICE_START_PTR(slice_); }
-
- size_t size() const { return GRPC_SLICE_LENGTH(slice_); }
+ size_t size() const { return slice_.size(); }
bool Verify() const {
Verifier verifier(data(), size());
@@ -70,10 +61,10 @@
const T *GetRoot() const { return flatbuffers::GetRoot<T>(data()); }
// This is only intended for serializer use, or if you know what you're doing
- const grpc_slice &BorrowSlice() const { return slice_; }
+ const ::grpc::Slice &BorrowSlice() const { return slice_; }
private:
- grpc_slice slice_;
+ ::grpc::Slice slice_;
};
class MessageBuilder;
@@ -83,12 +74,12 @@
// efficient to transfer buffers to gRPC.
class SliceAllocator : public Allocator {
public:
- SliceAllocator() : slice_(grpc_empty_slice()) {}
+ SliceAllocator() {}
SliceAllocator(const SliceAllocator &other) = delete;
SliceAllocator &operator=(const SliceAllocator &other) = delete;
- SliceAllocator(SliceAllocator &&other) : slice_(grpc_empty_slice()) {
+ SliceAllocator(SliceAllocator &&other) {
// default-construct and swap idiom
swap(other);
}
@@ -105,45 +96,43 @@
swap(slice_, other.slice_);
}
- virtual ~SliceAllocator() { grpc_slice_unref(slice_); }
+ virtual ~SliceAllocator() {}
virtual uint8_t *allocate(size_t size) override {
- FLATBUFFERS_ASSERT(GRPC_SLICE_IS_EMPTY(slice_));
- slice_ = grpc_slice_malloc(size);
- return GRPC_SLICE_START_PTR(slice_);
+ FLATBUFFERS_ASSERT(slice_.size() == 0);
+ slice_ = ::grpc::Slice(size);
+ return const_cast<uint8_t *>(slice_.begin());
}
virtual void deallocate(uint8_t *p, size_t size) override {
- FLATBUFFERS_ASSERT(p == GRPC_SLICE_START_PTR(slice_));
- FLATBUFFERS_ASSERT(size == GRPC_SLICE_LENGTH(slice_));
- grpc_slice_unref(slice_);
- slice_ = grpc_empty_slice();
+ FLATBUFFERS_ASSERT(p == slice_.begin());
+ FLATBUFFERS_ASSERT(size == slice_.size());
+ slice_ = ::grpc::Slice();
}
virtual uint8_t *reallocate_downward(uint8_t *old_p, size_t old_size,
size_t new_size, size_t in_use_back,
size_t in_use_front) override {
- FLATBUFFERS_ASSERT(old_p == GRPC_SLICE_START_PTR(slice_));
- FLATBUFFERS_ASSERT(old_size == GRPC_SLICE_LENGTH(slice_));
+ FLATBUFFERS_ASSERT(old_p == slice_.begin());
+ FLATBUFFERS_ASSERT(old_size == slice_.size());
FLATBUFFERS_ASSERT(new_size > old_size);
- grpc_slice old_slice = slice_;
- grpc_slice new_slice = grpc_slice_malloc(new_size);
- uint8_t *new_p = GRPC_SLICE_START_PTR(new_slice);
+ ::grpc::Slice old_slice = slice_;
+ ::grpc::Slice new_slice = ::grpc::Slice(new_size);
+ uint8_t *new_p = const_cast<uint8_t *>(new_slice.begin());
memcpy_downward(old_p, old_size, new_p, new_size, in_use_back,
in_use_front);
slice_ = new_slice;
- grpc_slice_unref(old_slice);
return new_p;
}
private:
- grpc_slice &get_slice(uint8_t *p, size_t size) {
- FLATBUFFERS_ASSERT(p == GRPC_SLICE_START_PTR(slice_));
- FLATBUFFERS_ASSERT(size == GRPC_SLICE_LENGTH(slice_));
+ ::grpc::Slice &get_slice(uint8_t *p, size_t size) {
+ FLATBUFFERS_ASSERT(p == slice_.begin());
+ FLATBUFFERS_ASSERT(size == slice_.size());
return slice_;
}
- grpc_slice slice_;
+ ::grpc::Slice slice_;
friend class MessageBuilder;
};
@@ -184,9 +173,9 @@
if (buf_.capacity()) {
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);
+ slice_allocator_.slice_ = ::grpc::Slice(buf, capacity, dealloc);
} else {
- slice_allocator_.slice_ = grpc_empty_slice();
+ slice_allocator_.slice_ = ::grpc::Slice();
}
}
@@ -221,10 +210,10 @@
// Releases the ownership of the buffer pointer.
// Returns the size, offset, and the original grpc_slice that
// allocated the buffer. Also see grpc_slice_unref().
- uint8_t *ReleaseRaw(size_t &size, size_t &offset, grpc_slice &slice) {
+ uint8_t *ReleaseRaw(size_t &size, size_t &offset, ::grpc::Slice &slice) {
uint8_t *buf = FlatBufferBuilder::ReleaseRaw(size, offset);
slice = slice_allocator_.slice_;
- slice_allocator_.slice_ = grpc_empty_slice();
+ slice_allocator_.slice_ = ::grpc::Slice();
return buf;
}
@@ -247,11 +236,11 @@
auto begin = msg_data - buf_data;
auto end = begin + msg_size;
// Get the slice we are working with (no refcount change)
- grpc_slice slice = slice_allocator_.get_slice(buf_data, buf_size);
+ ::grpc::Slice slice = slice_allocator_.get_slice(buf_data, buf_size);
// Extract a subslice of the existing slice (increment refcount)
- grpc_slice subslice = grpc_slice_sub(slice, begin, end);
+ ::grpc::Slice subslice = slice.sub(begin, end);
// Wrap the subslice in a `Message<T>`, but don't increment refcount
- Message<T> msg(subslice, false);
+ Message<T> msg(subslice);
return msg;
}
@@ -273,45 +262,26 @@
template<class T> class SerializationTraits<flatbuffers::grpc::Message<T>> {
public:
static grpc::Status Serialize(const flatbuffers::grpc::Message<T> &msg,
- 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 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
- // `grpc_byte_buffer`, incrementing the refcount in the process.
- *buffer = grpc_raw_byte_buffer_create(slice, 1);
+ ByteBuffer *buffer, bool *own_buffer) {
+ // Package the single slice into a `ByteBuffer`,
+ // incrementing the refcount in the process.
+ *buffer = ByteBuffer(&msg.BorrowSlice(), 1);
*own_buffer = true;
return grpc::Status::OK;
}
// Deserialize by pulling the
- static grpc::Status Deserialize(grpc_byte_buffer *buffer,
+ static grpc::Status Deserialize(ByteBuffer *buf,
flatbuffers::grpc::Message<T> *msg) {
- if (!buffer) {
- return ::grpc::Status(::grpc::StatusCode::INTERNAL, "No payload");
+ Slice slice;
+ if (!buf->TrySingleSlice(&slice).ok()) {
+ if (!buf->DumpToSingleSlice(&slice).ok()) {
+ buf->Clear();
+ return ::grpc::Status(::grpc::StatusCode::INTERNAL, "No payload");
+ }
}
- // Check if this is a single uncompressed slice.
- if ((buffer->type == GRPC_BB_RAW) &&
- (buffer->data.raw.compression == GRPC_COMPRESS_NONE) &&
- (buffer->data.raw.slice_buffer.count == 1)) {
- // If it is, then we can reference the `grpc_slice` directly.
- grpc_slice slice = buffer->data.raw.slice_buffer.slices[0];
- // We wrap a `Message<T>` around the slice, incrementing the refcount.
- *msg = flatbuffers::grpc::Message<T>(slice, true);
- } else {
- // Otherwise, we need to use `grpc_byte_buffer_reader_readall` to read
- // `buffer` into a single contiguous `grpc_slice`. The gRPC reader gives
- // us back a new slice with the refcount already incremented.
- grpc_byte_buffer_reader reader;
- 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 don't increment refcount
- *msg = flatbuffers::grpc::Message<T>(slice, false);
- }
- grpc_byte_buffer_destroy(buffer);
+ *msg = flatbuffers::grpc::Message<T>(slice);
+ buf->Clear();
#if FLATBUFFERS_GRPC_DISABLE_AUTO_VERIFICATION
return ::grpc::Status::OK;
#else
diff --git a/include/flatbuffers/idl.h b/include/flatbuffers/idl.h
index 6afdc7a..260061f 100644
--- a/include/flatbuffers/idl.h
+++ b/include/flatbuffers/idl.h
@@ -17,6 +17,7 @@
#ifndef FLATBUFFERS_IDL_H_
#define FLATBUFFERS_IDL_H_
+#include <functional>
#include <map>
#include <memory>
#include <stack>
@@ -27,15 +28,11 @@
#include "flatbuffers/hash.h"
#include "flatbuffers/reflection.h"
-#if !defined(FLATBUFFERS_CPP98_STL)
-# include <functional>
-#endif // !defined(FLATBUFFERS_CPP98_STL)
-
// This file defines the data types representing a parsed IDL (Interface
// Definition Language) / schema file.
// Limits maximum depth of nested objects.
-// Prevents stack overflow while parse flatbuffers or json.
+// Prevents stack overflow while parse scheme, or json, or flexbuffer.
#if !defined(FLATBUFFERS_MAX_PARSING_DEPTH)
# define FLATBUFFERS_MAX_PARSING_DEPTH 64
#endif
@@ -75,8 +72,8 @@
// - Go type.
// - C# / .Net type.
// - Python type.
-// - Rust type.
// - Kotlin type.
+// - Rust type.
// using these macros, we can now write code dealing with types just once, e.g.
@@ -207,7 +204,7 @@
}
bool Add(const std::string &name, T *e) {
- vector_emplace_back(&vec, e);
+ vec.emplace_back(e);
auto it = dict.find(name);
if (it != dict.end()) return true;
dict[name] = e;
@@ -266,7 +263,8 @@
defined_namespace(nullptr),
serialized_location(0),
index(-1),
- refcount(1) {}
+ refcount(1),
+ declaration_file(nullptr) {}
flatbuffers::Offset<
flatbuffers::Vector<flatbuffers::Offset<reflection::KeyValue>>>
@@ -286,17 +284,17 @@
uoffset_t serialized_location;
int index; // Inside the vector it is stored.
int refcount;
+ const std::string *declaration_file;
};
struct FieldDef : public Definition {
FieldDef()
: deprecated(false),
- required(false),
key(false),
shared(false),
native_inline(false),
flexbuffer(false),
- optional(false),
+ presence(kDefault),
nested_flatbuffer(NULL),
padding(0) {}
@@ -306,21 +304,41 @@
bool Deserialize(Parser &parser, const reflection::Field *field);
bool IsScalarOptional() const {
- return IsScalar(value.type.base_type) && optional;
+ return IsScalar(value.type.base_type) && IsOptional();
}
+ bool IsOptional() const { return presence == kOptional; }
+ bool IsRequired() const { return presence == kRequired; }
+ bool IsDefault() const { return presence == kDefault; }
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.
- bool required; // Field must always be present.
bool key; // Field functions as a key for creating sorted vectors.
bool shared; // Field will be using string pooling (i.e. CreateSharedString)
// as default serialization behavior if field is a string.
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).
+
+ enum Presence {
+ // Field must always be present.
+ kRequired,
+ // Non-presence should be signalled to and controlled by users.
+ kOptional,
+ // Non-presence is hidden from users.
+ // Implementations may omit writing default values.
+ kDefault,
+ };
+ Presence static MakeFieldPresence(bool optional, bool required) {
+ FLATBUFFERS_ASSERT(!(required && optional));
+ // clang-format off
+ return required ? FieldDef::kRequired
+ : optional ? FieldDef::kOptional
+ : FieldDef::kDefault;
+ // clang-format on
+ }
+ Presence presence;
+
StructDef *nested_flatbuffer; // This field contains nested FlatBuffer data.
size_t padding; // Bytes to always pad after this field.
};
@@ -450,6 +468,10 @@
return type.enum_def != nullptr && type.enum_def->is_union;
}
+inline bool IsUnionType(const Type &type) {
+ return IsUnion(type) && IsInteger(type.base_type);
+}
+
inline bool IsVector(const Type &type) {
return type.base_type == BASE_TYPE_VECTOR;
}
@@ -517,13 +539,13 @@
// Container of options that may apply to any of the source/text generators.
struct IDLOptions {
+ // field case style options for C++
+ enum CaseStyle { CaseStyle_Unchanged = 0, CaseStyle_Upper, CaseStyle_Lower };
+
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;
- bool use_ES6_js_export_format;
bool output_default_scalars_in_json;
int indent_step;
bool output_enum_identifiers;
@@ -542,10 +564,12 @@
std::string cpp_object_api_pointer_type;
std::string cpp_object_api_string_type;
bool cpp_object_api_string_flexible_constructor;
+ CaseStyle cpp_object_api_field_case_style;
bool cpp_direct_copy;
bool gen_nullable;
bool java_checkerframework;
bool gen_generated;
+ bool gen_json_coders;
std::string object_prefix;
std::string object_suffix;
bool union_value_namespacing;
@@ -556,11 +580,8 @@
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;
- bool reexport_ts_modules;
- bool js_ts_short_names;
bool protobuf_ascii_alike;
bool size_prefixed;
std::string root_type;
@@ -569,9 +590,18 @@
bool cs_gen_json_serializer;
std::vector<std::string> cpp_includes;
std::string cpp_std;
+ bool cpp_static_reflection;
std::string proto_namespace_suffix;
std::string filename_suffix;
std::string filename_extension;
+ bool no_warnings;
+ bool warnings_as_errors;
+ std::string project_root;
+ bool cs_global_alias;
+ bool json_nested_flatbuffers;
+ bool json_nested_flexbuffers;
+ bool json_nested_legacy_flatbuffers;
+ bool ts_flat_file;
// Possible options for the more general generator below.
enum Language {
@@ -579,7 +609,6 @@
kCSharp = 1 << 1,
kGo = 1 << 2,
kCpp = 1 << 3,
- kJs = 1 << 4,
kPython = 1 << 5,
kPhp = 1 << 6,
kJson = 1 << 7,
@@ -595,8 +624,6 @@
kMAX
};
- Language lang;
-
enum MiniReflect { kNone, kTypes, kTypesAndNames };
MiniReflect mini_reflect;
@@ -604,6 +631,12 @@
// If set, require all fields in a table to be explicitly numbered.
bool require_explicit_ids;
+ // If set, implement serde::Serialize for generated Rust types
+ bool rust_serialize;
+
+ // If set, generate rust types in individual files with a root module file.
+ bool rust_module_root_file;
+
// The corresponding language bit will be set if a language is included
// for code generation.
unsigned long lang_to_generate;
@@ -620,9 +653,6 @@
: 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),
output_default_scalars_in_json(false),
indent_step(2),
output_enum_identifiers(true),
@@ -640,10 +670,12 @@
gen_compare(false),
cpp_object_api_pointer_type("std::unique_ptr"),
cpp_object_api_string_flexible_constructor(false),
+ cpp_object_api_field_case_style(CaseStyle_Unchanged),
cpp_direct_copy(true),
gen_nullable(false),
java_checkerframework(false),
gen_generated(false),
+ gen_json_coders(false),
object_suffix("T"),
union_value_namespacing(true),
allow_non_utf8(false),
@@ -652,19 +684,26 @@
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),
+ cpp_static_reflection(false),
filename_suffix("_generated"),
filename_extension(),
- lang(IDLOptions::kJava),
+ no_warnings(false),
+ warnings_as_errors(false),
+ project_root(""),
+ cs_global_alias(false),
+ json_nested_flatbuffers(true),
+ json_nested_flexbuffers(true),
+ json_nested_legacy_flatbuffers(false),
+ ts_flat_file(false),
mini_reflect(IDLOptions::kNone),
require_explicit_ids(false),
+ rust_serialize(false),
+ rust_module_root_file(false),
lang_to_generate(0),
set_empty_strings_to_null(true),
set_empty_vectors_to_null(true) {}
@@ -764,9 +803,11 @@
root_struct_def_(nullptr),
opts(options),
uses_flexbuffers_(false),
+ has_warning_(false),
+ advanced_features_(0),
source_(nullptr),
- anonymous_counter(0),
- recurse_protection_counter(0) {
+ anonymous_counter_(0),
+ parse_depth_counter_(0) {
if (opts.force_defaults) { builder_.ForceDefaults(true); }
// Start out with the empty namespace being current.
empty_namespace_ = new Namespace();
@@ -793,6 +834,7 @@
known_attributes_["native_inline"] = true;
known_attributes_["native_custom_alloc"] = true;
known_attributes_["native_type"] = true;
+ known_attributes_["native_type_pack_name"] = true;
known_attributes_["native_default"] = true;
known_attributes_["flexbuffer"] = true;
known_attributes_["private"] = true;
@@ -804,11 +846,6 @@
}
}
-#ifdef FLATBUFFERS_DEFAULT_DECLARATION
- Parser(Parser&&) = default;
- Parser& operator=(Parser&&) = default;
-#endif
-
// Parse the string containing either schema or JSON data, which will
// populate the SymbolTable's or the FlatBufferBuilder above.
// include_paths is used to resolve any include statements, and typically
@@ -859,6 +896,7 @@
flexbuffers::Builder *builder);
StructDef *LookupStruct(const std::string &id) const;
+ StructDef *LookupStructThruParentNamespaces(const std::string &id) const;
std::string UnqualifiedName(const std::string &fullQualifiedName);
@@ -870,6 +908,8 @@
static bool SupportsOptionalScalars(const flatbuffers::IDLOptions &opts);
private:
+ class ParseDepthGuard;
+
void Message(const std::string &msg);
void Warning(const std::string &msg);
FLATBUFFERS_CHECKED_ERROR ParseHexNum(int nibbles, uint64_t *val);
@@ -926,14 +966,15 @@
StructDef *LookupCreateStruct(const std::string &name,
bool create_if_new = true,
bool definition = false);
- FLATBUFFERS_CHECKED_ERROR ParseEnum(bool is_union, EnumDef **dest);
+ FLATBUFFERS_CHECKED_ERROR ParseEnum(bool is_union, EnumDef **dest,
+ const char *filename);
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,
EnumDef **dest);
- FLATBUFFERS_CHECKED_ERROR ParseDecl();
- FLATBUFFERS_CHECKED_ERROR ParseService();
+ FLATBUFFERS_CHECKED_ERROR ParseDecl(const char *filename);
+ FLATBUFFERS_CHECKED_ERROR ParseService(const char *filename);
FLATBUFFERS_CHECKED_ERROR ParseProtoFields(StructDef *struct_def,
bool isextend, bool inside_oneof);
FLATBUFFERS_CHECKED_ERROR ParseProtoOption();
@@ -942,6 +983,8 @@
FLATBUFFERS_CHECKED_ERROR ParseProtoCurliesOrIdent();
FLATBUFFERS_CHECKED_ERROR ParseTypeFromProtoType(Type *type);
FLATBUFFERS_CHECKED_ERROR SkipAnyJsonValue();
+ FLATBUFFERS_CHECKED_ERROR ParseFlexBufferNumericConstant(
+ flexbuffers::Builder *builder);
FLATBUFFERS_CHECKED_ERROR ParseFlexBufferValue(flexbuffers::Builder *builder);
FLATBUFFERS_CHECKED_ERROR StartParseFile(const char *source,
const char *source_filename);
@@ -956,15 +999,20 @@
FLATBUFFERS_CHECKED_ERROR CheckClash(std::vector<FieldDef *> &fields,
StructDef *struct_def,
const char *suffix, BaseType baseType);
+ FLATBUFFERS_CHECKED_ERROR ParseAlignAttribute(
+ const std::string &align_constant, size_t min_align, size_t *align);
bool SupportsAdvancedUnionFeatures() const;
bool SupportsAdvancedArrayFeatures() const;
bool SupportsOptionalScalars() const;
+ bool SupportsDefaultVectorsAndStrings() const;
Namespace *UniqueNamespace(Namespace *ns);
FLATBUFFERS_CHECKED_ERROR RecurseError();
template<typename F> CheckedError Recurse(F f);
+ const std::string &GetPooledString(const std::string &s) const;
+
public:
SymbolTable<Type> types_;
SymbolTable<StructDef> structs_;
@@ -982,7 +1030,7 @@
std::string file_identifier_;
std::string file_extension_;
- std::map<std::string, std::string> included_files_;
+ std::map<uint64_t, std::string> included_files_;
std::map<std::string, std::set<std::string>> files_included_per_file_;
std::vector<std::string> native_included_files_;
@@ -990,6 +1038,9 @@
IDLOptions opts;
bool uses_flexbuffers_;
+ bool has_warning_;
+
+ uint64_t advanced_features_;
private:
const char *source_;
@@ -998,16 +1049,16 @@
std::vector<std::pair<Value, FieldDef *>> field_stack_;
- int anonymous_counter;
- int recurse_protection_counter;
+ // TODO(cneo): Refactor parser to use string_cache more often to save
+ // on memory usage.
+ mutable std::set<std::string> string_cache_;
+
+ int anonymous_counter_;
+ int parse_depth_counter_; // stack-overflow guard
};
// Utility functions for multiple generators:
-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,
@@ -1054,8 +1105,8 @@
// 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);
+extern bool GenerateTS(const Parser &parser, const std::string &path,
+ const std::string &file_name);
// Generate Go files from the definitions in the Parser object.
// See idl_gen_go.cpp.
@@ -1107,10 +1158,10 @@
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);
+// Generate a make rule for the generated TypeScript code.
+// See idl_gen_ts.cpp.
+extern std::string TSMakeRule(const Parser &parser, const std::string &path,
+ const std::string &file_name);
// Generate a make rule for the generated C++ header.
// See idl_gen_cpp.cpp.
@@ -1129,9 +1180,10 @@
// 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);
+extern std::string CSharpMakeRule(const Parser &parser, const std::string &path,
+ const std::string &file_name);
+extern std::string JavaMakeRule(const Parser &parser, const std::string &path,
+ const std::string &file_name);
// Generate a make rule for the generated text (JSON) files.
// See idl_gen_text.cpp.
@@ -1169,7 +1221,10 @@
const std::string &file_name);
extern bool GenerateTSGRPC(const Parser &parser, const std::string &path,
- const std::string &file_name);
+ const std::string &file_name);
+
+extern bool GenerateRustModuleRootFile(const Parser &parser,
+ const std::string &path);
} // namespace flatbuffers
#endif // FLATBUFFERS_IDL_H_
diff --git a/include/flatbuffers/reflection.h b/include/flatbuffers/reflection.h
index 70d9971..8e700f0 100644
--- a/include/flatbuffers/reflection.h
+++ b/include/flatbuffers/reflection.h
@@ -21,7 +21,7 @@
// file) is needed to generate this header in the first place.
// Should normally not be a problem since it can be generated by the
// previous version of flatc whenever this code needs to change.
-// See reflection/generate_code.sh
+// See scripts/generate_code.py for generation.
#include "flatbuffers/reflection_generated.h"
// Helper functionality for reflection.
@@ -47,29 +47,31 @@
inline size_t GetTypeSize(reflection::BaseType base_type) {
// This needs to correspond to the BaseType enum.
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, // 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.");
+ "Size of sizes[] array does not match the count of BaseType "
+ "enum values.");
return sizes[base_type];
}
@@ -377,12 +379,12 @@
public:
pointer_inside_vector(T *ptr, std::vector<U> &vec)
: offset_(reinterpret_cast<uint8_t *>(ptr) -
- reinterpret_cast<uint8_t *>(flatbuffers::vector_data(vec))),
+ reinterpret_cast<uint8_t *>(vec.data())),
vec_(vec) {}
T *operator*() const {
- return reinterpret_cast<T *>(
- reinterpret_cast<uint8_t *>(flatbuffers::vector_data(vec_)) + offset_);
+ return reinterpret_cast<T *>(reinterpret_cast<uint8_t *>(vec_.data()) +
+ offset_);
}
T *operator->() const { return operator*(); }
@@ -410,7 +412,7 @@
FLATBUFFERS_ASSERT(type_field);
auto union_type = GetFieldI<uint8_t>(table, *type_field);
auto enumval = enumdef->values()->LookupByKey(union_type);
- return *enumval->object();
+ return *schema.objects()->Get(enumval->union_type()->index());
}
// Changes the contents of a string inside a FlatBuffer. FlatBuffer must
diff --git a/include/flatbuffers/reflection_generated.h b/include/flatbuffers/reflection_generated.h
index b98afd6..dcb0f7e 100644
--- a/include/flatbuffers/reflection_generated.h
+++ b/include/flatbuffers/reflection_generated.h
@@ -32,6 +32,9 @@
struct Service;
struct ServiceBuilder;
+struct SchemaFile;
+struct SchemaFileBuilder;
+
struct Schema;
struct SchemaBuilder;
@@ -114,13 +117,54 @@
return EnumNamesBaseType()[index];
}
+/// New schema language features that are not supported by old code generators.
+enum AdvancedFeatures {
+ AdvancedArrayFeatures = 1ULL,
+ AdvancedUnionFeatures = 2ULL,
+ OptionalScalars = 4ULL,
+ DefaultVectorsAndStrings = 8ULL
+};
+
+inline const AdvancedFeatures (&EnumValuesAdvancedFeatures())[4] {
+ static const AdvancedFeatures values[] = {
+ AdvancedArrayFeatures,
+ AdvancedUnionFeatures,
+ OptionalScalars,
+ DefaultVectorsAndStrings
+ };
+ return values;
+}
+
+inline const char * const *EnumNamesAdvancedFeatures() {
+ static const char * const names[9] = {
+ "AdvancedArrayFeatures",
+ "AdvancedUnionFeatures",
+ "",
+ "OptionalScalars",
+ "",
+ "",
+ "",
+ "DefaultVectorsAndStrings",
+ nullptr
+ };
+ return names;
+}
+
+inline const char *EnumNameAdvancedFeatures(AdvancedFeatures e) {
+ if (flatbuffers::IsOutRange(e, AdvancedArrayFeatures, DefaultVectorsAndStrings)) return "";
+ const size_t index = static_cast<size_t>(e) - static_cast<size_t>(AdvancedArrayFeatures);
+ return EnumNamesAdvancedFeatures()[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,
VT_INDEX = 8,
- VT_FIXED_LENGTH = 10
+ VT_FIXED_LENGTH = 10,
+ VT_BASE_SIZE = 12,
+ VT_ELEMENT_SIZE = 14
};
reflection::BaseType base_type() const {
return static_cast<reflection::BaseType>(GetField<int8_t>(VT_BASE_TYPE, 0));
@@ -134,12 +178,22 @@
uint16_t fixed_length() const {
return GetField<uint16_t>(VT_FIXED_LENGTH, 0);
}
+ /// The size (octets) of the `base_type` field.
+ uint32_t base_size() const {
+ return GetField<uint32_t>(VT_BASE_SIZE, 4);
+ }
+ /// The size (octets) of the `element` field, if present.
+ uint32_t element_size() const {
+ return GetField<uint32_t>(VT_ELEMENT_SIZE, 0);
+ }
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
- VerifyField<int8_t>(verifier, VT_BASE_TYPE) &&
- VerifyField<int8_t>(verifier, VT_ELEMENT) &&
- VerifyField<int32_t>(verifier, VT_INDEX) &&
- VerifyField<uint16_t>(verifier, VT_FIXED_LENGTH) &&
+ VerifyField<int8_t>(verifier, VT_BASE_TYPE, 1) &&
+ VerifyField<int8_t>(verifier, VT_ELEMENT, 1) &&
+ VerifyField<int32_t>(verifier, VT_INDEX, 4) &&
+ VerifyField<uint16_t>(verifier, VT_FIXED_LENGTH, 2) &&
+ VerifyField<uint32_t>(verifier, VT_BASE_SIZE, 4) &&
+ VerifyField<uint32_t>(verifier, VT_ELEMENT_SIZE, 4) &&
verifier.EndTable();
}
};
@@ -160,6 +214,12 @@
void add_fixed_length(uint16_t fixed_length) {
fbb_.AddElement<uint16_t>(Type::VT_FIXED_LENGTH, fixed_length, 0);
}
+ void add_base_size(uint32_t base_size) {
+ fbb_.AddElement<uint32_t>(Type::VT_BASE_SIZE, base_size, 4);
+ }
+ void add_element_size(uint32_t element_size) {
+ fbb_.AddElement<uint32_t>(Type::VT_ELEMENT_SIZE, element_size, 0);
+ }
explicit TypeBuilder(flatbuffers::FlatBufferBuilder &_fbb)
: fbb_(_fbb) {
start_ = fbb_.StartTable();
@@ -176,8 +236,12 @@
reflection::BaseType base_type = reflection::None,
reflection::BaseType element = reflection::None,
int32_t index = -1,
- uint16_t fixed_length = 0) {
+ uint16_t fixed_length = 0,
+ uint32_t base_size = 4,
+ uint32_t element_size = 0) {
TypeBuilder builder_(_fbb);
+ builder_.add_element_size(element_size);
+ builder_.add_base_size(base_size);
builder_.add_index(index);
builder_.add_fixed_length(fixed_length);
builder_.add_element(element);
@@ -197,8 +261,8 @@
bool KeyCompareLessThan(const KeyValue *o) const {
return *key() < *o->key();
}
- int KeyCompareWithValue(const char *val) const {
- return strcmp(key()->c_str(), val);
+ int KeyCompareWithValue(const char *_key) const {
+ return strcmp(key()->c_str(), _key);
}
const flatbuffers::String *value() const {
return GetPointer<const flatbuffers::String *>(VT_VALUE);
@@ -262,7 +326,6 @@
enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE {
VT_NAME = 4,
VT_VALUE = 6,
- VT_OBJECT = 8,
VT_UNION_TYPE = 10,
VT_DOCUMENTATION = 12
};
@@ -275,11 +338,8 @@
bool KeyCompareLessThan(const EnumVal *o) const {
return value() < o->value();
}
- int KeyCompareWithValue(int64_t val) const {
- return static_cast<int>(value() > val) - static_cast<int>(value() < val);
- }
- const reflection::Object *object() const {
- return GetPointer<const reflection::Object *>(VT_OBJECT);
+ int KeyCompareWithValue(int64_t _value) const {
+ return static_cast<int>(value() > _value) - static_cast<int>(value() < _value);
}
const reflection::Type *union_type() const {
return GetPointer<const reflection::Type *>(VT_UNION_TYPE);
@@ -291,9 +351,7 @@
return VerifyTableStart(verifier) &&
VerifyOffsetRequired(verifier, VT_NAME) &&
verifier.VerifyString(name()) &&
- VerifyField<int64_t>(verifier, VT_VALUE) &&
- VerifyOffset(verifier, VT_OBJECT) &&
- verifier.VerifyTable(object()) &&
+ VerifyField<int64_t>(verifier, VT_VALUE, 8) &&
VerifyOffset(verifier, VT_UNION_TYPE) &&
verifier.VerifyTable(union_type()) &&
VerifyOffset(verifier, VT_DOCUMENTATION) &&
@@ -313,9 +371,6 @@
void add_value(int64_t value) {
fbb_.AddElement<int64_t>(EnumVal::VT_VALUE, value, 0);
}
- void add_object(flatbuffers::Offset<reflection::Object> object) {
- fbb_.AddOffset(EnumVal::VT_OBJECT, object);
- }
void add_union_type(flatbuffers::Offset<reflection::Type> union_type) {
fbb_.AddOffset(EnumVal::VT_UNION_TYPE, union_type);
}
@@ -338,14 +393,12 @@
flatbuffers::FlatBufferBuilder &_fbb,
flatbuffers::Offset<flatbuffers::String> name = 0,
int64_t value = 0,
- flatbuffers::Offset<reflection::Object> object = 0,
flatbuffers::Offset<reflection::Type> union_type = 0,
flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>> documentation = 0) {
EnumValBuilder builder_(_fbb);
builder_.add_value(value);
builder_.add_documentation(documentation);
builder_.add_union_type(union_type);
- builder_.add_object(object);
builder_.add_name(name);
return builder_.Finish();
}
@@ -354,7 +407,6 @@
flatbuffers::FlatBufferBuilder &_fbb,
const char *name = nullptr,
int64_t value = 0,
- flatbuffers::Offset<reflection::Object> object = 0,
flatbuffers::Offset<reflection::Type> union_type = 0,
const std::vector<flatbuffers::Offset<flatbuffers::String>> *documentation = nullptr) {
auto name__ = name ? _fbb.CreateString(name) : 0;
@@ -363,7 +415,6 @@
_fbb,
name__,
value,
- object,
union_type,
documentation__);
}
@@ -376,7 +427,8 @@
VT_IS_UNION = 8,
VT_UNDERLYING_TYPE = 10,
VT_ATTRIBUTES = 12,
- VT_DOCUMENTATION = 14
+ VT_DOCUMENTATION = 14,
+ VT_DECLARATION_FILE = 16
};
const flatbuffers::String *name() const {
return GetPointer<const flatbuffers::String *>(VT_NAME);
@@ -384,8 +436,8 @@
bool KeyCompareLessThan(const Enum *o) const {
return *name() < *o->name();
}
- int KeyCompareWithValue(const char *val) const {
- return strcmp(name()->c_str(), val);
+ int KeyCompareWithValue(const char *_name) const {
+ return strcmp(name()->c_str(), _name);
}
const flatbuffers::Vector<flatbuffers::Offset<reflection::EnumVal>> *values() const {
return GetPointer<const flatbuffers::Vector<flatbuffers::Offset<reflection::EnumVal>> *>(VT_VALUES);
@@ -402,6 +454,10 @@
const flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>> *documentation() const {
return GetPointer<const flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>> *>(VT_DOCUMENTATION);
}
+ /// File that this Enum is declared in.
+ const flatbuffers::String *declaration_file() const {
+ return GetPointer<const flatbuffers::String *>(VT_DECLARATION_FILE);
+ }
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
VerifyOffsetRequired(verifier, VT_NAME) &&
@@ -409,7 +465,7 @@
VerifyOffsetRequired(verifier, VT_VALUES) &&
verifier.VerifyVector(values()) &&
verifier.VerifyVectorOfTables(values()) &&
- VerifyField<uint8_t>(verifier, VT_IS_UNION) &&
+ VerifyField<uint8_t>(verifier, VT_IS_UNION, 1) &&
VerifyOffsetRequired(verifier, VT_UNDERLYING_TYPE) &&
verifier.VerifyTable(underlying_type()) &&
VerifyOffset(verifier, VT_ATTRIBUTES) &&
@@ -418,6 +474,8 @@
VerifyOffset(verifier, VT_DOCUMENTATION) &&
verifier.VerifyVector(documentation()) &&
verifier.VerifyVectorOfStrings(documentation()) &&
+ VerifyOffset(verifier, VT_DECLARATION_FILE) &&
+ verifier.VerifyString(declaration_file()) &&
verifier.EndTable();
}
};
@@ -444,6 +502,9 @@
void add_documentation(flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>> documentation) {
fbb_.AddOffset(Enum::VT_DOCUMENTATION, documentation);
}
+ void add_declaration_file(flatbuffers::Offset<flatbuffers::String> declaration_file) {
+ fbb_.AddOffset(Enum::VT_DECLARATION_FILE, declaration_file);
+ }
explicit EnumBuilder(flatbuffers::FlatBufferBuilder &_fbb)
: fbb_(_fbb) {
start_ = fbb_.StartTable();
@@ -465,8 +526,10 @@
bool is_union = false,
flatbuffers::Offset<reflection::Type> underlying_type = 0,
flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<reflection::KeyValue>>> attributes = 0,
- flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>> documentation = 0) {
+ flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>> documentation = 0,
+ flatbuffers::Offset<flatbuffers::String> declaration_file = 0) {
EnumBuilder builder_(_fbb);
+ builder_.add_declaration_file(declaration_file);
builder_.add_documentation(documentation);
builder_.add_attributes(attributes);
builder_.add_underlying_type(underlying_type);
@@ -483,11 +546,13 @@
bool is_union = false,
flatbuffers::Offset<reflection::Type> underlying_type = 0,
std::vector<flatbuffers::Offset<reflection::KeyValue>> *attributes = nullptr,
- const std::vector<flatbuffers::Offset<flatbuffers::String>> *documentation = nullptr) {
+ const std::vector<flatbuffers::Offset<flatbuffers::String>> *documentation = nullptr,
+ const char *declaration_file = nullptr) {
auto name__ = name ? _fbb.CreateString(name) : 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;
+ auto declaration_file__ = declaration_file ? _fbb.CreateString(declaration_file) : 0;
return reflection::CreateEnum(
_fbb,
name__,
@@ -495,7 +560,8 @@
is_union,
underlying_type,
attributes__,
- documentation__);
+ documentation__,
+ declaration_file__);
}
struct Field FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
@@ -512,7 +578,8 @@
VT_KEY = 20,
VT_ATTRIBUTES = 22,
VT_DOCUMENTATION = 24,
- VT_OPTIONAL = 26
+ VT_OPTIONAL = 26,
+ VT_PADDING = 28
};
const flatbuffers::String *name() const {
return GetPointer<const flatbuffers::String *>(VT_NAME);
@@ -520,8 +587,8 @@
bool KeyCompareLessThan(const Field *o) const {
return *name() < *o->name();
}
- int KeyCompareWithValue(const char *val) const {
- return strcmp(name()->c_str(), val);
+ int KeyCompareWithValue(const char *_name) const {
+ return strcmp(name()->c_str(), _name);
}
const reflection::Type *type() const {
return GetPointer<const reflection::Type *>(VT_TYPE);
@@ -556,26 +623,31 @@
bool optional() const {
return GetField<uint8_t>(VT_OPTIONAL, 0) != 0;
}
+ /// Number of padding octets to always add after this field. Structs only.
+ uint16_t padding() const {
+ return GetField<uint16_t>(VT_PADDING, 0);
+ }
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
VerifyOffsetRequired(verifier, VT_NAME) &&
verifier.VerifyString(name()) &&
VerifyOffsetRequired(verifier, VT_TYPE) &&
verifier.VerifyTable(type()) &&
- VerifyField<uint16_t>(verifier, VT_ID) &&
- VerifyField<uint16_t>(verifier, VT_OFFSET) &&
- VerifyField<int64_t>(verifier, VT_DEFAULT_INTEGER) &&
- VerifyField<double>(verifier, VT_DEFAULT_REAL) &&
- VerifyField<uint8_t>(verifier, VT_DEPRECATED) &&
- VerifyField<uint8_t>(verifier, VT_REQUIRED) &&
- VerifyField<uint8_t>(verifier, VT_KEY) &&
+ VerifyField<uint16_t>(verifier, VT_ID, 2) &&
+ VerifyField<uint16_t>(verifier, VT_OFFSET, 2) &&
+ VerifyField<int64_t>(verifier, VT_DEFAULT_INTEGER, 8) &&
+ VerifyField<double>(verifier, VT_DEFAULT_REAL, 8) &&
+ VerifyField<uint8_t>(verifier, VT_DEPRECATED, 1) &&
+ VerifyField<uint8_t>(verifier, VT_REQUIRED, 1) &&
+ VerifyField<uint8_t>(verifier, VT_KEY, 1) &&
VerifyOffset(verifier, VT_ATTRIBUTES) &&
verifier.VerifyVector(attributes()) &&
verifier.VerifyVectorOfTables(attributes()) &&
VerifyOffset(verifier, VT_DOCUMENTATION) &&
verifier.VerifyVector(documentation()) &&
verifier.VerifyVectorOfStrings(documentation()) &&
- VerifyField<uint8_t>(verifier, VT_OPTIONAL) &&
+ VerifyField<uint8_t>(verifier, VT_OPTIONAL, 1) &&
+ VerifyField<uint16_t>(verifier, VT_PADDING, 2) &&
verifier.EndTable();
}
};
@@ -620,6 +692,9 @@
void add_optional(bool optional) {
fbb_.AddElement<uint8_t>(Field::VT_OPTIONAL, static_cast<uint8_t>(optional), 0);
}
+ void add_padding(uint16_t padding) {
+ fbb_.AddElement<uint16_t>(Field::VT_PADDING, padding, 0);
+ }
explicit FieldBuilder(flatbuffers::FlatBufferBuilder &_fbb)
: fbb_(_fbb) {
start_ = fbb_.StartTable();
@@ -646,7 +721,8 @@
bool key = false,
flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<reflection::KeyValue>>> attributes = 0,
flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>> documentation = 0,
- bool optional = false) {
+ bool optional = false,
+ uint16_t padding = 0) {
FieldBuilder builder_(_fbb);
builder_.add_default_real(default_real);
builder_.add_default_integer(default_integer);
@@ -654,6 +730,7 @@
builder_.add_attributes(attributes);
builder_.add_type(type);
builder_.add_name(name);
+ builder_.add_padding(padding);
builder_.add_offset(offset);
builder_.add_id(id);
builder_.add_optional(optional);
@@ -676,7 +753,8 @@
bool key = false,
std::vector<flatbuffers::Offset<reflection::KeyValue>> *attributes = nullptr,
const std::vector<flatbuffers::Offset<flatbuffers::String>> *documentation = nullptr,
- bool optional = false) {
+ bool optional = false,
+ uint16_t padding = 0) {
auto name__ = name ? _fbb.CreateString(name) : 0;
auto attributes__ = attributes ? _fbb.CreateVectorOfSortedTables<reflection::KeyValue>(attributes) : 0;
auto documentation__ = documentation ? _fbb.CreateVector<flatbuffers::Offset<flatbuffers::String>>(*documentation) : 0;
@@ -693,7 +771,8 @@
key,
attributes__,
documentation__,
- optional);
+ optional,
+ padding);
}
struct Object FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
@@ -705,7 +784,8 @@
VT_MINALIGN = 10,
VT_BYTESIZE = 12,
VT_ATTRIBUTES = 14,
- VT_DOCUMENTATION = 16
+ VT_DOCUMENTATION = 16,
+ VT_DECLARATION_FILE = 18
};
const flatbuffers::String *name() const {
return GetPointer<const flatbuffers::String *>(VT_NAME);
@@ -713,8 +793,8 @@
bool KeyCompareLessThan(const Object *o) const {
return *name() < *o->name();
}
- int KeyCompareWithValue(const char *val) const {
- return strcmp(name()->c_str(), val);
+ int KeyCompareWithValue(const char *_name) const {
+ return strcmp(name()->c_str(), _name);
}
const flatbuffers::Vector<flatbuffers::Offset<reflection::Field>> *fields() const {
return GetPointer<const flatbuffers::Vector<flatbuffers::Offset<reflection::Field>> *>(VT_FIELDS);
@@ -734,6 +814,10 @@
const flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>> *documentation() const {
return GetPointer<const flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>> *>(VT_DOCUMENTATION);
}
+ /// File that this Object is declared in.
+ const flatbuffers::String *declaration_file() const {
+ return GetPointer<const flatbuffers::String *>(VT_DECLARATION_FILE);
+ }
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
VerifyOffsetRequired(verifier, VT_NAME) &&
@@ -741,15 +825,17 @@
VerifyOffsetRequired(verifier, VT_FIELDS) &&
verifier.VerifyVector(fields()) &&
verifier.VerifyVectorOfTables(fields()) &&
- VerifyField<uint8_t>(verifier, VT_IS_STRUCT) &&
- VerifyField<int32_t>(verifier, VT_MINALIGN) &&
- VerifyField<int32_t>(verifier, VT_BYTESIZE) &&
+ VerifyField<uint8_t>(verifier, VT_IS_STRUCT, 1) &&
+ VerifyField<int32_t>(verifier, VT_MINALIGN, 4) &&
+ VerifyField<int32_t>(verifier, VT_BYTESIZE, 4) &&
VerifyOffset(verifier, VT_ATTRIBUTES) &&
verifier.VerifyVector(attributes()) &&
verifier.VerifyVectorOfTables(attributes()) &&
VerifyOffset(verifier, VT_DOCUMENTATION) &&
verifier.VerifyVector(documentation()) &&
verifier.VerifyVectorOfStrings(documentation()) &&
+ VerifyOffset(verifier, VT_DECLARATION_FILE) &&
+ verifier.VerifyString(declaration_file()) &&
verifier.EndTable();
}
};
@@ -779,6 +865,9 @@
void add_documentation(flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>> documentation) {
fbb_.AddOffset(Object::VT_DOCUMENTATION, documentation);
}
+ void add_declaration_file(flatbuffers::Offset<flatbuffers::String> declaration_file) {
+ fbb_.AddOffset(Object::VT_DECLARATION_FILE, declaration_file);
+ }
explicit ObjectBuilder(flatbuffers::FlatBufferBuilder &_fbb)
: fbb_(_fbb) {
start_ = fbb_.StartTable();
@@ -800,8 +889,10 @@
int32_t minalign = 0,
int32_t bytesize = 0,
flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<reflection::KeyValue>>> attributes = 0,
- flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>> documentation = 0) {
+ flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>> documentation = 0,
+ flatbuffers::Offset<flatbuffers::String> declaration_file = 0) {
ObjectBuilder builder_(_fbb);
+ builder_.add_declaration_file(declaration_file);
builder_.add_documentation(documentation);
builder_.add_attributes(attributes);
builder_.add_bytesize(bytesize);
@@ -820,11 +911,13 @@
int32_t minalign = 0,
int32_t bytesize = 0,
std::vector<flatbuffers::Offset<reflection::KeyValue>> *attributes = nullptr,
- const std::vector<flatbuffers::Offset<flatbuffers::String>> *documentation = nullptr) {
+ const std::vector<flatbuffers::Offset<flatbuffers::String>> *documentation = nullptr,
+ const char *declaration_file = nullptr) {
auto name__ = name ? _fbb.CreateString(name) : 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;
+ auto declaration_file__ = declaration_file ? _fbb.CreateString(declaration_file) : 0;
return reflection::CreateObject(
_fbb,
name__,
@@ -833,7 +926,8 @@
minalign,
bytesize,
attributes__,
- documentation__);
+ documentation__,
+ declaration_file__);
}
struct RPCCall FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
@@ -851,8 +945,8 @@
bool KeyCompareLessThan(const RPCCall *o) const {
return *name() < *o->name();
}
- int KeyCompareWithValue(const char *val) const {
- return strcmp(name()->c_str(), val);
+ int KeyCompareWithValue(const char *_name) const {
+ return strcmp(name()->c_str(), _name);
}
const reflection::Object *request() const {
return GetPointer<const reflection::Object *>(VT_REQUEST);
@@ -958,7 +1052,8 @@
VT_NAME = 4,
VT_CALLS = 6,
VT_ATTRIBUTES = 8,
- VT_DOCUMENTATION = 10
+ VT_DOCUMENTATION = 10,
+ VT_DECLARATION_FILE = 12
};
const flatbuffers::String *name() const {
return GetPointer<const flatbuffers::String *>(VT_NAME);
@@ -966,8 +1061,8 @@
bool KeyCompareLessThan(const Service *o) const {
return *name() < *o->name();
}
- int KeyCompareWithValue(const char *val) const {
- return strcmp(name()->c_str(), val);
+ int KeyCompareWithValue(const char *_name) const {
+ return strcmp(name()->c_str(), _name);
}
const flatbuffers::Vector<flatbuffers::Offset<reflection::RPCCall>> *calls() const {
return GetPointer<const flatbuffers::Vector<flatbuffers::Offset<reflection::RPCCall>> *>(VT_CALLS);
@@ -978,6 +1073,10 @@
const flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>> *documentation() const {
return GetPointer<const flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>> *>(VT_DOCUMENTATION);
}
+ /// File that this Service is declared in.
+ const flatbuffers::String *declaration_file() const {
+ return GetPointer<const flatbuffers::String *>(VT_DECLARATION_FILE);
+ }
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
VerifyOffsetRequired(verifier, VT_NAME) &&
@@ -991,6 +1090,8 @@
VerifyOffset(verifier, VT_DOCUMENTATION) &&
verifier.VerifyVector(documentation()) &&
verifier.VerifyVectorOfStrings(documentation()) &&
+ VerifyOffset(verifier, VT_DECLARATION_FILE) &&
+ verifier.VerifyString(declaration_file()) &&
verifier.EndTable();
}
};
@@ -1011,6 +1112,9 @@
void add_documentation(flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>> documentation) {
fbb_.AddOffset(Service::VT_DOCUMENTATION, documentation);
}
+ void add_declaration_file(flatbuffers::Offset<flatbuffers::String> declaration_file) {
+ fbb_.AddOffset(Service::VT_DECLARATION_FILE, declaration_file);
+ }
explicit ServiceBuilder(flatbuffers::FlatBufferBuilder &_fbb)
: fbb_(_fbb) {
start_ = fbb_.StartTable();
@@ -1028,8 +1132,10 @@
flatbuffers::Offset<flatbuffers::String> name = 0,
flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<reflection::RPCCall>>> calls = 0,
flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<reflection::KeyValue>>> attributes = 0,
- flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>> documentation = 0) {
+ flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>> documentation = 0,
+ flatbuffers::Offset<flatbuffers::String> declaration_file = 0) {
ServiceBuilder builder_(_fbb);
+ builder_.add_declaration_file(declaration_file);
builder_.add_documentation(documentation);
builder_.add_attributes(attributes);
builder_.add_calls(calls);
@@ -1042,17 +1148,98 @@
const char *name = 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) {
+ const std::vector<flatbuffers::Offset<flatbuffers::String>> *documentation = nullptr,
+ const char *declaration_file = nullptr) {
auto name__ = name ? _fbb.CreateString(name) : 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;
+ auto declaration_file__ = declaration_file ? _fbb.CreateString(declaration_file) : 0;
return reflection::CreateService(
_fbb,
name__,
calls__,
attributes__,
- documentation__);
+ documentation__,
+ declaration_file__);
+}
+
+/// File specific information.
+/// Symbols declared within a file may be recovered by iterating over all
+/// symbols and examining the `declaration_file` field.
+struct SchemaFile FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
+ typedef SchemaFileBuilder Builder;
+ enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE {
+ VT_FILENAME = 4,
+ VT_INCLUDED_FILENAMES = 6
+ };
+ /// Filename, relative to project root.
+ const flatbuffers::String *filename() const {
+ return GetPointer<const flatbuffers::String *>(VT_FILENAME);
+ }
+ bool KeyCompareLessThan(const SchemaFile *o) const {
+ return *filename() < *o->filename();
+ }
+ int KeyCompareWithValue(const char *_filename) const {
+ return strcmp(filename()->c_str(), _filename);
+ }
+ /// Names of included files, relative to project root.
+ const flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>> *included_filenames() const {
+ return GetPointer<const flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>> *>(VT_INCLUDED_FILENAMES);
+ }
+ bool Verify(flatbuffers::Verifier &verifier) const {
+ return VerifyTableStart(verifier) &&
+ VerifyOffsetRequired(verifier, VT_FILENAME) &&
+ verifier.VerifyString(filename()) &&
+ VerifyOffset(verifier, VT_INCLUDED_FILENAMES) &&
+ verifier.VerifyVector(included_filenames()) &&
+ verifier.VerifyVectorOfStrings(included_filenames()) &&
+ verifier.EndTable();
+ }
+};
+
+struct SchemaFileBuilder {
+ typedef SchemaFile Table;
+ flatbuffers::FlatBufferBuilder &fbb_;
+ flatbuffers::uoffset_t start_;
+ void add_filename(flatbuffers::Offset<flatbuffers::String> filename) {
+ fbb_.AddOffset(SchemaFile::VT_FILENAME, filename);
+ }
+ void add_included_filenames(flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>> included_filenames) {
+ fbb_.AddOffset(SchemaFile::VT_INCLUDED_FILENAMES, included_filenames);
+ }
+ explicit SchemaFileBuilder(flatbuffers::FlatBufferBuilder &_fbb)
+ : fbb_(_fbb) {
+ start_ = fbb_.StartTable();
+ }
+ flatbuffers::Offset<SchemaFile> Finish() {
+ const auto end = fbb_.EndTable(start_);
+ auto o = flatbuffers::Offset<SchemaFile>(end);
+ fbb_.Required(o, SchemaFile::VT_FILENAME);
+ return o;
+ }
+};
+
+inline flatbuffers::Offset<SchemaFile> CreateSchemaFile(
+ flatbuffers::FlatBufferBuilder &_fbb,
+ flatbuffers::Offset<flatbuffers::String> filename = 0,
+ flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>> included_filenames = 0) {
+ SchemaFileBuilder builder_(_fbb);
+ builder_.add_included_filenames(included_filenames);
+ builder_.add_filename(filename);
+ return builder_.Finish();
+}
+
+inline flatbuffers::Offset<SchemaFile> CreateSchemaFileDirect(
+ flatbuffers::FlatBufferBuilder &_fbb,
+ const char *filename = nullptr,
+ const std::vector<flatbuffers::Offset<flatbuffers::String>> *included_filenames = nullptr) {
+ auto filename__ = filename ? _fbb.CreateString(filename) : 0;
+ auto included_filenames__ = included_filenames ? _fbb.CreateVector<flatbuffers::Offset<flatbuffers::String>>(*included_filenames) : 0;
+ return reflection::CreateSchemaFile(
+ _fbb,
+ filename__,
+ included_filenames__);
}
struct Schema FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
@@ -1063,7 +1250,9 @@
VT_FILE_IDENT = 8,
VT_FILE_EXT = 10,
VT_ROOT_TABLE = 12,
- VT_SERVICES = 14
+ VT_SERVICES = 14,
+ VT_ADVANCED_FEATURES = 16,
+ VT_FBS_FILES = 18
};
const flatbuffers::Vector<flatbuffers::Offset<reflection::Object>> *objects() const {
return GetPointer<const flatbuffers::Vector<flatbuffers::Offset<reflection::Object>> *>(VT_OBJECTS);
@@ -1083,6 +1272,14 @@
const flatbuffers::Vector<flatbuffers::Offset<reflection::Service>> *services() const {
return GetPointer<const flatbuffers::Vector<flatbuffers::Offset<reflection::Service>> *>(VT_SERVICES);
}
+ reflection::AdvancedFeatures advanced_features() const {
+ return static_cast<reflection::AdvancedFeatures>(GetField<uint64_t>(VT_ADVANCED_FEATURES, 0));
+ }
+ /// All the files used in this compilation. Files are relative to where
+ /// flatc was invoked.
+ const flatbuffers::Vector<flatbuffers::Offset<reflection::SchemaFile>> *fbs_files() const {
+ return GetPointer<const flatbuffers::Vector<flatbuffers::Offset<reflection::SchemaFile>> *>(VT_FBS_FILES);
+ }
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
VerifyOffsetRequired(verifier, VT_OBJECTS) &&
@@ -1100,6 +1297,10 @@
VerifyOffset(verifier, VT_SERVICES) &&
verifier.VerifyVector(services()) &&
verifier.VerifyVectorOfTables(services()) &&
+ VerifyField<uint64_t>(verifier, VT_ADVANCED_FEATURES, 8) &&
+ VerifyOffset(verifier, VT_FBS_FILES) &&
+ verifier.VerifyVector(fbs_files()) &&
+ verifier.VerifyVectorOfTables(fbs_files()) &&
verifier.EndTable();
}
};
@@ -1126,6 +1327,12 @@
void add_services(flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<reflection::Service>>> services) {
fbb_.AddOffset(Schema::VT_SERVICES, services);
}
+ void add_advanced_features(reflection::AdvancedFeatures advanced_features) {
+ fbb_.AddElement<uint64_t>(Schema::VT_ADVANCED_FEATURES, static_cast<uint64_t>(advanced_features), 0);
+ }
+ void add_fbs_files(flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<reflection::SchemaFile>>> fbs_files) {
+ fbb_.AddOffset(Schema::VT_FBS_FILES, fbs_files);
+ }
explicit SchemaBuilder(flatbuffers::FlatBufferBuilder &_fbb)
: fbb_(_fbb) {
start_ = fbb_.StartTable();
@@ -1146,8 +1353,12 @@
flatbuffers::Offset<flatbuffers::String> file_ident = 0,
flatbuffers::Offset<flatbuffers::String> file_ext = 0,
flatbuffers::Offset<reflection::Object> root_table = 0,
- flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<reflection::Service>>> services = 0) {
+ flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<reflection::Service>>> services = 0,
+ reflection::AdvancedFeatures advanced_features = static_cast<reflection::AdvancedFeatures>(0),
+ flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<reflection::SchemaFile>>> fbs_files = 0) {
SchemaBuilder builder_(_fbb);
+ builder_.add_advanced_features(advanced_features);
+ builder_.add_fbs_files(fbs_files);
builder_.add_services(services);
builder_.add_root_table(root_table);
builder_.add_file_ext(file_ext);
@@ -1164,12 +1375,15 @@
const char *file_ident = nullptr,
const char *file_ext = nullptr,
flatbuffers::Offset<reflection::Object> root_table = 0,
- std::vector<flatbuffers::Offset<reflection::Service>> *services = nullptr) {
+ std::vector<flatbuffers::Offset<reflection::Service>> *services = nullptr,
+ reflection::AdvancedFeatures advanced_features = static_cast<reflection::AdvancedFeatures>(0),
+ std::vector<flatbuffers::Offset<reflection::SchemaFile>> *fbs_files = 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.CreateVectorOfSortedTables<reflection::Service>(services) : 0;
+ auto fbs_files__ = fbs_files ? _fbb.CreateVectorOfSortedTables<reflection::SchemaFile>(fbs_files) : 0;
return reflection::CreateSchema(
_fbb,
objects__,
@@ -1177,7 +1391,9 @@
file_ident__,
file_ext__,
root_table,
- services__);
+ services__,
+ advanced_features,
+ fbs_files__);
}
inline const reflection::Schema *GetSchema(const void *buf) {
@@ -1197,6 +1413,11 @@
buf, SchemaIdentifier());
}
+inline bool SizePrefixedSchemaBufferHasIdentifier(const void *buf) {
+ return flatbuffers::BufferHasIdentifier(
+ buf, SchemaIdentifier(), true);
+}
+
inline bool VerifySchemaBuffer(
flatbuffers::Verifier &verifier) {
return verifier.VerifyBuffer<reflection::Schema>(SchemaIdentifier());
diff --git a/include/flatbuffers/registry.h b/include/flatbuffers/registry.h
index 9ea425b..e8bb8f5 100644
--- a/include/flatbuffers/registry.h
+++ b/include/flatbuffers/registry.h
@@ -17,6 +17,7 @@
#ifndef FLATBUFFERS_REGISTRY_H_
#define FLATBUFFERS_REGISTRY_H_
+#include "flatbuffers/base.h"
#include "flatbuffers/idl.h"
namespace flatbuffers {
@@ -40,13 +41,13 @@
bool FlatBufferToText(const uint8_t *flatbuf, size_t len, std::string *dest) {
// Get the identifier out of the buffer.
// If the buffer is truncated, exit.
- if (len < sizeof(uoffset_t) + FlatBufferBuilder::kFileIdentifierLength) {
+ if (len < sizeof(uoffset_t) + kFileIdentifierLength) {
lasterror_ = "buffer truncated";
return false;
}
std::string ident(
reinterpret_cast<const char *>(flatbuf) + sizeof(uoffset_t),
- FlatBufferBuilder::kFileIdentifierLength);
+ kFileIdentifierLength);
// Load and parse the schema.
Parser parser;
if (!LoadSchema(ident, &parser)) return false;
@@ -103,7 +104,7 @@
}
// Parse schema.
parser->opts = opts_;
- if (!parser->Parse(schematext.c_str(), vector_data(include_paths_),
+ if (!parser->Parse(schematext.c_str(), include_paths_.data(),
schema.path_.c_str())) {
lasterror_ = parser->error_;
return false;
diff --git a/include/flatbuffers/stl_emulation.h b/include/flatbuffers/stl_emulation.h
index 66bd620..75d13b2 100644
--- a/include/flatbuffers/stl_emulation.h
+++ b/include/flatbuffers/stl_emulation.h
@@ -26,14 +26,6 @@
#include <memory>
#include <limits>
-#if defined(_STLPORT_VERSION) && !defined(FLATBUFFERS_CPP98_STL)
- #define FLATBUFFERS_CPP98_STL
-#endif // defined(_STLPORT_VERSION) && !defined(FLATBUFFERS_CPP98_STL)
-
-#if defined(FLATBUFFERS_CPP98_STL)
- #include <cctype>
-#endif // defined(FLATBUFFERS_CPP98_STL)
-
// Detect C++17 compatible compiler.
// __cplusplus >= 201703L - a compiler has support of 'static inline' variables.
#if defined(FLATBUFFERS_USE_STD_OPTIONAL) \
@@ -55,7 +47,7 @@
#endif
#else
// Disable non-trivial ctors if FLATBUFFERS_SPAN_MINIMAL defined.
- #if !defined(FLATBUFFERS_TEMPLATES_ALIASES) || defined(FLATBUFFERS_CPP98_STL)
+ #if !defined(FLATBUFFERS_TEMPLATES_ALIASES)
#define FLATBUFFERS_SPAN_MINIMAL
#else
// Enable implicit construction of a span<T,N> from a std::array<T,N>.
@@ -63,131 +55,32 @@
#endif
#endif // defined(FLATBUFFERS_USE_STD_SPAN)
-// This header provides backwards compatibility for C++98 STLs like stlport.
+// This header provides backwards compatibility for older versions of the STL.
namespace flatbuffers {
-// Retrieve ::back() from a string in a way that is compatible with pre C++11
-// STLs (e.g stlport).
-inline char& string_back(std::string &value) {
- return value[value.length() - 1];
-}
-
-inline char string_back(const std::string &value) {
- return value[value.length() - 1];
-}
-
-// Helper method that retrieves ::data() from a vector in a way that is
-// compatible with pre C++11 STLs (e.g stlport).
-template <typename T> inline T *vector_data(std::vector<T> &vector) {
- // In some debug environments, operator[] does bounds checking, so &vector[0]
- // can't be used.
- return vector.empty() ? nullptr : &vector[0];
-}
-
-template <typename T> inline const T *vector_data(
- const std::vector<T> &vector) {
- return vector.empty() ? nullptr : &vector[0];
-}
-
-template <typename T, typename V>
-inline void vector_emplace_back(std::vector<T> *vector, V &&data) {
- #if defined(FLATBUFFERS_CPP98_STL)
- vector->push_back(data);
- #else
- vector->emplace_back(std::forward<V>(data));
- #endif // defined(FLATBUFFERS_CPP98_STL)
-}
-
-#ifndef FLATBUFFERS_CPP98_STL
- #if defined(FLATBUFFERS_TEMPLATES_ALIASES)
- template <typename T>
- using numeric_limits = std::numeric_limits<T>;
- #else
- template <typename T> class numeric_limits :
- public std::numeric_limits<T> {};
- #endif // defined(FLATBUFFERS_TEMPLATES_ALIASES)
+#if defined(FLATBUFFERS_TEMPLATES_ALIASES)
+ template <typename T>
+ using numeric_limits = std::numeric_limits<T>;
#else
template <typename T> class numeric_limits :
- public std::numeric_limits<T> {
- public:
- // Android NDK fix.
- static T lowest() {
- return std::numeric_limits<T>::min();
- }
- };
-
- template <> class numeric_limits<float> :
- public std::numeric_limits<float> {
- public:
- static float lowest() { return -FLT_MAX; }
- };
-
- template <> class numeric_limits<double> :
- public std::numeric_limits<double> {
- public:
- static double lowest() { return -DBL_MAX; }
- };
-
- template <> class numeric_limits<unsigned long long> {
- public:
- static unsigned long long min() { return 0ULL; }
- static unsigned long long max() { return ~0ULL; }
- static unsigned long long lowest() {
- return numeric_limits<unsigned long long>::min();
- }
- };
-
- template <> class numeric_limits<long long> {
- public:
- static long long min() {
- return static_cast<long long>(1ULL << ((sizeof(long long) << 3) - 1));
- }
- static long long max() {
- return static_cast<long long>(
- (1ULL << ((sizeof(long long) << 3) - 1)) - 1);
- }
- static long long lowest() {
- return numeric_limits<long long>::min();
- }
- };
-#endif // FLATBUFFERS_CPP98_STL
+ public std::numeric_limits<T> {};
+#endif // defined(FLATBUFFERS_TEMPLATES_ALIASES)
#if defined(FLATBUFFERS_TEMPLATES_ALIASES)
- #ifndef FLATBUFFERS_CPP98_STL
- template <typename T> using is_scalar = std::is_scalar<T>;
- 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>;
- template <typename T, typename U> using is_same = std::tr1::is_same<T,U>;
- 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!");
- using type = T;
- };
- template<> struct make_unsigned<char> { using type = unsigned char; };
- template<> struct make_unsigned<short> { using type = unsigned short; };
- template<> struct make_unsigned<int> { using type = unsigned int; };
- 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
+ template <typename T> using is_scalar = std::is_scalar<T>;
+ 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>;
+ template <bool B>
+ using bool_constant = integral_constant<bool, B>;
+ using true_type = std::true_type;
+ using false_type = std::false_type;
#else
// MSVC 2010 doesn't support C++11 aliases.
template <typename T> struct is_scalar : public std::is_scalar<T> {};
@@ -201,126 +94,39 @@
struct conditional : public std::conditional<B, T, F> {};
template<class T, T v>
struct integral_constant : public std::integral_constant<T, v> {};
+ template <bool B>
+ struct bool_constant : public integral_constant<bool, B> {};
+ typedef bool_constant<true> true_type;
+ typedef bool_constant<false> false_type;
#endif // defined(FLATBUFFERS_TEMPLATES_ALIASES)
-#ifndef FLATBUFFERS_CPP98_STL
- #if defined(FLATBUFFERS_TEMPLATES_ALIASES)
- template <class T> using unique_ptr = std::unique_ptr<T>;
- #else
- // 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 implementation (see below)
- // for C++98 STL implementations.
- template <class T> class unique_ptr : public std::unique_ptr<T> {
- public:
- unique_ptr() {}
- explicit unique_ptr(T* p) : std::unique_ptr<T>(p) {}
- unique_ptr(std::unique_ptr<T>&& u) { *this = std::move(u); }
- unique_ptr(unique_ptr&& u) { *this = std::move(u); }
- unique_ptr& operator=(std::unique_ptr<T>&& u) {
- std::unique_ptr<T>::reset(u.release());
- return *this;
- }
- unique_ptr& operator=(unique_ptr&& u) {
- std::unique_ptr<T>::reset(u.release());
- return *this;
- }
- unique_ptr& operator=(T* p) {
- return std::unique_ptr<T>::operator=(p);
- }
- };
- #endif // defined(FLATBUFFERS_TEMPLATES_ALIASES)
+#if defined(FLATBUFFERS_TEMPLATES_ALIASES)
+ template <class T> using unique_ptr = std::unique_ptr<T>;
#else
- // Very limited implementation of unique_ptr.
- // This is provided simply to allow the C++ code generated from the default
- // settings to function in C++98 environments with no modifications.
- template <class T> class unique_ptr {
- public:
- typedef T element_type;
-
- unique_ptr() : ptr_(nullptr) {}
- explicit unique_ptr(T* p) : ptr_(p) {}
- unique_ptr(unique_ptr&& u) : ptr_(nullptr) { reset(u.release()); }
- unique_ptr(const unique_ptr& u) : ptr_(nullptr) {
- reset(const_cast<unique_ptr*>(&u)->release());
- }
- ~unique_ptr() { reset(); }
-
- unique_ptr& operator=(const unique_ptr& u) {
- reset(const_cast<unique_ptr*>(&u)->release());
+ // 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 implementation (see below)
+ // for C++98 STL implementations.
+ template <class T> class unique_ptr : public std::unique_ptr<T> {
+ public:
+ unique_ptr() {}
+ explicit unique_ptr(T* p) : std::unique_ptr<T>(p) {}
+ unique_ptr(std::unique_ptr<T>&& u) { *this = std::move(u); }
+ unique_ptr(unique_ptr&& u) { *this = std::move(u); }
+ unique_ptr& operator=(std::unique_ptr<T>&& u) {
+ std::unique_ptr<T>::reset(u.release());
return *this;
}
-
unique_ptr& operator=(unique_ptr&& u) {
- reset(u.release());
+ std::unique_ptr<T>::reset(u.release());
return *this;
}
-
unique_ptr& operator=(T* p) {
- reset(p);
- return *this;
+ return std::unique_ptr<T>::operator=(p);
}
-
- const T& operator*() const { return *ptr_; }
- T* operator->() const { return ptr_; }
- T* get() const noexcept { return ptr_; }
- explicit operator bool() const { return ptr_ != nullptr; }
-
- // modifiers
- T* release() {
- T* value = ptr_;
- ptr_ = nullptr;
- return value;
- }
-
- void reset(T* p = nullptr) {
- T* value = ptr_;
- ptr_ = p;
- if (value) delete value;
- }
-
- void swap(unique_ptr& u) {
- T* temp_ptr = ptr_;
- ptr_ = u.ptr_;
- u.ptr_ = temp_ptr;
- }
-
- private:
- T* ptr_;
};
-
- template <class T> bool operator==(const unique_ptr<T>& x,
- const unique_ptr<T>& y) {
- return x.get() == y.get();
- }
-
- template <class T, class D> bool operator==(const unique_ptr<T>& x,
- const D* y) {
- return static_cast<D*>(x.get()) == y;
- }
-
- 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
+#endif // defined(FLATBUFFERS_TEMPLATES_ALIASES)
#ifdef FLATBUFFERS_USE_STD_OPTIONAL
template<class T>
@@ -489,6 +295,32 @@
int, void>::type;
};
+ template<typename T>
+ struct SpanIterator {
+ // TODO: upgrade to std::random_access_iterator_tag.
+ using iterator_category = std::forward_iterator_tag;
+ using difference_type = std::ptrdiff_t;
+ using value_type = typename std::remove_cv<T>::type;
+ using reference = T&;
+ using pointer = T*;
+
+ // Convince MSVC compiler that this iterator is trusted (it is verified).
+ #ifdef _MSC_VER
+ using _Unchecked_type = pointer;
+ #endif // _MSC_VER
+
+ SpanIterator(pointer ptr) : ptr_(ptr) {}
+ reference operator*() const { return *ptr_; }
+ pointer operator->() { return ptr_; }
+ SpanIterator& operator++() { ptr_++; return *this; }
+ SpanIterator operator++(int) { auto tmp = *this; ++(*this); return tmp; }
+
+ friend bool operator== (const SpanIterator& lhs, const SpanIterator& rhs) { return lhs.ptr_ == rhs.ptr_; }
+ friend bool operator!= (const SpanIterator& lhs, const SpanIterator& rhs) { return lhs.ptr_ != rhs.ptr_; }
+
+ private:
+ pointer ptr_;
+ };
} // namespace internal
#endif // !defined(FLATBUFFERS_SPAN_MINIMAL)
@@ -528,6 +360,17 @@
return data_;
}
+ #if !defined(FLATBUFFERS_SPAN_MINIMAL)
+ using Iterator = internal::SpanIterator<T>;
+ using ConstIterator = internal::SpanIterator<const T>;
+
+ Iterator begin() const { return Iterator(data()); }
+ Iterator end() const { return Iterator(data() + size()); }
+
+ ConstIterator cbegin() const { return ConstIterator(data()); }
+ ConstIterator cend() const { return ConstIterator(data() + size()); }
+ #endif
+
// 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 {
@@ -621,47 +464,46 @@
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)
+#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 // !defined(FLATBUFFERS_SPAN_MINIMAL)
+
} // namespace flatbuffers
#endif // FLATBUFFERS_STL_EMULATION_H_
diff --git a/include/flatbuffers/string.h b/include/flatbuffers/string.h
new file mode 100644
index 0000000..3db95fc
--- /dev/null
+++ b/include/flatbuffers/string.h
@@ -0,0 +1,64 @@
+/*
+ * Copyright 2021 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_STRING_H_
+#define FLATBUFFERS_STRING_H_
+
+#include "flatbuffers/base.h"
+#include "flatbuffers/vector.h"
+
+namespace flatbuffers {
+
+struct String : public Vector<char> {
+ const char *c_str() const { return reinterpret_cast<const char *>(Data()); }
+ std::string str() const { return std::string(c_str(), size()); }
+
+ // clang-format off
+ #ifdef FLATBUFFERS_HAS_STRING_VIEW
+ flatbuffers::string_view string_view() const {
+ return flatbuffers::string_view(c_str(), size());
+ }
+ #endif // FLATBUFFERS_HAS_STRING_VIEW
+ // clang-format on
+
+ bool operator<(const String &o) const {
+ return StringLessThan(this->data(), this->size(), o.data(), o.size());
+ }
+};
+
+// Convenience function to get std::string from a String returning an empty
+// string on null pointer.
+static inline std::string GetString(const String *str) {
+ return str ? str->str() : "";
+}
+
+// Convenience function to get char* from a String returning an empty string on
+// null pointer.
+static inline const char *GetCstring(const String *str) {
+ return str ? str->c_str() : "";
+}
+
+#ifdef FLATBUFFERS_HAS_STRING_VIEW
+// Convenience function to get string_view from a String returning an empty
+// string_view on null pointer.
+static inline flatbuffers::string_view GetStringView(const String *str) {
+ return str ? str->string_view() : flatbuffers::string_view();
+}
+#endif // FLATBUFFERS_HAS_STRING_VIEW
+
+} // namespace flatbuffers
+
+#endif // FLATBUFFERS_STRING_H_
\ No newline at end of file
diff --git a/include/flatbuffers/struct.h b/include/flatbuffers/struct.h
new file mode 100644
index 0000000..d8753c8
--- /dev/null
+++ b/include/flatbuffers/struct.h
@@ -0,0 +1,53 @@
+/*
+ * Copyright 2021 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_STRUCT_H_
+#define FLATBUFFERS_STRUCT_H_
+
+#include "flatbuffers/base.h"
+
+namespace flatbuffers {
+
+// "structs" are flat structures that do not have an offset table, thus
+// always have all members present and do not support forwards/backwards
+// compatible extensions.
+
+class Struct FLATBUFFERS_FINAL_CLASS {
+ public:
+ template<typename T> T GetField(uoffset_t o) const {
+ return ReadScalar<T>(&data_[o]);
+ }
+
+ template<typename T> T GetStruct(uoffset_t o) const {
+ return reinterpret_cast<T>(&data_[o]);
+ }
+
+ const uint8_t *GetAddressOf(uoffset_t o) const { return &data_[o]; }
+ uint8_t *GetAddressOf(uoffset_t o) { return &data_[o]; }
+
+ private:
+ // private constructor & copy constructor: you obtain instances of this
+ // class by pointing to existing data only
+ Struct();
+ Struct(const Struct &);
+ Struct &operator=(const Struct &);
+
+ uint8_t data_[1];
+};
+
+} // namespace flatbuffers
+
+#endif // FLATBUFFERS_STRUCT_H_
\ No newline at end of file
diff --git a/include/flatbuffers/table.h b/include/flatbuffers/table.h
new file mode 100644
index 0000000..11b2924
--- /dev/null
+++ b/include/flatbuffers/table.h
@@ -0,0 +1,168 @@
+/*
+ * Copyright 2021 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_TABLE_H_
+#define FLATBUFFERS_TABLE_H_
+
+#include "flatbuffers/base.h"
+#include "flatbuffers/verifier.h"
+
+namespace flatbuffers {
+
+// "tables" use an offset table (possibly shared) that allows fields to be
+// omitted and added at will, but uses an extra indirection to read.
+class Table {
+ public:
+ const uint8_t *GetVTable() const {
+ return data_ - ReadScalar<soffset_t>(data_);
+ }
+
+ // This gets the field offset for any of the functions below it, or 0
+ // if the field was not present.
+ voffset_t GetOptionalFieldOffset(voffset_t field) const {
+ // The vtable offset is always at the start.
+ auto vtable = GetVTable();
+ // The first element is the size of the vtable (fields + type id + itself).
+ auto vtsize = ReadScalar<voffset_t>(vtable);
+ // If the field we're accessing is outside the vtable, we're reading older
+ // data, so it's the same as if the offset was 0 (not present).
+ return field < vtsize ? ReadScalar<voffset_t>(vtable + field) : 0;
+ }
+
+ template<typename T> T GetField(voffset_t field, T defaultval) const {
+ auto field_offset = GetOptionalFieldOffset(field);
+ return field_offset ? ReadScalar<T>(data_ + field_offset) : defaultval;
+ }
+
+ template<typename P> P GetPointer(voffset_t field) {
+ auto field_offset = GetOptionalFieldOffset(field);
+ auto p = data_ + field_offset;
+ return field_offset ? reinterpret_cast<P>(p + ReadScalar<uoffset_t>(p))
+ : nullptr;
+ }
+ template<typename P> P GetPointer(voffset_t field) const {
+ return const_cast<Table *>(this)->GetPointer<P>(field);
+ }
+
+ template<typename P> P GetStruct(voffset_t field) const {
+ auto field_offset = GetOptionalFieldOffset(field);
+ auto p = const_cast<uint8_t *>(data_ + field_offset);
+ return field_offset ? reinterpret_cast<P>(p) : nullptr;
+ }
+
+ template<typename Raw, typename Face>
+ flatbuffers::Optional<Face> GetOptional(voffset_t field) const {
+ auto field_offset = GetOptionalFieldOffset(field);
+ auto p = data_ + field_offset;
+ return field_offset ? Optional<Face>(static_cast<Face>(ReadScalar<Raw>(p)))
+ : Optional<Face>();
+ }
+
+ template<typename T> bool SetField(voffset_t field, T val, T def) {
+ auto field_offset = GetOptionalFieldOffset(field);
+ if (!field_offset) return IsTheSameAs(val, def);
+ WriteScalar(data_ + field_offset, val);
+ return true;
+ }
+ template<typename T> bool SetField(voffset_t field, T val) {
+ auto field_offset = GetOptionalFieldOffset(field);
+ if (!field_offset) return false;
+ WriteScalar(data_ + field_offset, val);
+ return true;
+ }
+
+ bool SetPointer(voffset_t field, const uint8_t *val) {
+ auto field_offset = GetOptionalFieldOffset(field);
+ if (!field_offset) return false;
+ WriteScalar(data_ + field_offset,
+ static_cast<uoffset_t>(val - (data_ + field_offset)));
+ return true;
+ }
+
+ uint8_t *GetAddressOf(voffset_t field) {
+ auto field_offset = GetOptionalFieldOffset(field);
+ return field_offset ? data_ + field_offset : nullptr;
+ }
+ const uint8_t *GetAddressOf(voffset_t field) const {
+ return const_cast<Table *>(this)->GetAddressOf(field);
+ }
+
+ bool CheckField(voffset_t field) const {
+ return GetOptionalFieldOffset(field) != 0;
+ }
+
+ // Verify the vtable of this table.
+ // Call this once per table, followed by VerifyField once per field.
+ bool VerifyTableStart(Verifier &verifier) const {
+ return verifier.VerifyTableStart(data_);
+ }
+
+ // Verify a particular field.
+ template<typename T>
+ bool VerifyField(const Verifier &verifier, voffset_t field,
+ size_t align) const {
+ // Calling GetOptionalFieldOffset should be safe now thanks to
+ // VerifyTable().
+ auto field_offset = GetOptionalFieldOffset(field);
+ // Check the actual field.
+ return !field_offset || verifier.VerifyField<T>(data_, field_offset, align);
+ }
+
+ // VerifyField for required fields.
+ template<typename T>
+ bool VerifyFieldRequired(const Verifier &verifier, voffset_t field,
+ size_t align) const {
+ auto field_offset = GetOptionalFieldOffset(field);
+ return verifier.Check(field_offset != 0) &&
+ verifier.VerifyField<T>(data_, field_offset, align);
+ }
+
+ // Versions for offsets.
+ bool VerifyOffset(const Verifier &verifier, voffset_t field) const {
+ auto field_offset = GetOptionalFieldOffset(field);
+ return !field_offset || verifier.VerifyOffset(data_, field_offset);
+ }
+
+ bool VerifyOffsetRequired(const Verifier &verifier, voffset_t field) const {
+ auto field_offset = GetOptionalFieldOffset(field);
+ return verifier.Check(field_offset != 0) &&
+ verifier.VerifyOffset(data_, field_offset);
+ }
+
+ private:
+ // private constructor & copy constructor: you obtain instances of this
+ // class by pointing to existing data only
+ Table();
+ Table(const Table &other);
+ Table &operator=(const Table &);
+
+ uint8_t data_[1];
+};
+
+// This specialization allows avoiding warnings like:
+// MSVC C4800: type: forcing value to bool 'true' or 'false'.
+template<>
+inline flatbuffers::Optional<bool> Table::GetOptional<uint8_t, bool>(
+ voffset_t field) const {
+ auto field_offset = GetOptionalFieldOffset(field);
+ auto p = data_ + field_offset;
+ return field_offset ? Optional<bool>(ReadScalar<uint8_t>(p) != 0)
+ : Optional<bool>();
+}
+
+} // namespace flatbuffers
+
+#endif // FLATBUFFERS_TABLE_H_
diff --git a/include/flatbuffers/util.h b/include/flatbuffers/util.h
index 2aafa48..2e0ce73 100644
--- a/include/flatbuffers/util.h
+++ b/include/flatbuffers/util.h
@@ -17,19 +17,20 @@
#ifndef FLATBUFFERS_UTIL_H_
#define FLATBUFFERS_UTIL_H_
+#include <ctype.h>
#include <errno.h>
#include "flatbuffers/base.h"
#include "flatbuffers/stl_emulation.h"
#ifndef FLATBUFFERS_PREFER_PRINTF
+# include <iomanip>
# include <sstream>
#else // FLATBUFFERS_PREFER_PRINTF
# include <float.h>
# include <stdio.h>
#endif // FLATBUFFERS_PREFER_PRINTF
-#include <iomanip>
#include <string>
namespace flatbuffers {
@@ -51,6 +52,9 @@
return check_ascii_range(c & 0xDF, 'a' & 0xDF, 'z' & 0xDF);
}
+// Check for uppercase alpha
+inline bool is_alpha_upper(char c) { return check_ascii_range(c, 'A', 'Z'); }
+
// Check (case-insensitive) that `c` is equal to alpha.
inline bool is_alpha_char(char c, char alpha) {
FLATBUFFERS_ASSERT(is_alpha(alpha));
@@ -91,7 +95,7 @@
// Count a single 0 left of the dot for fractional numbers
if (-1 < t && t < 1) digit_count++;
// Count digits until fractional part
- T eps = std::numeric_limits<float>::epsilon();
+ T eps = std::numeric_limits<T>::epsilon();
while (t <= (-1 + eps) || (1 - eps) <= t) {
t /= 10;
digit_count++;
@@ -142,20 +146,6 @@
template<> inline std::string NumToString<char>(char t) {
return NumToString(static_cast<int>(t));
}
-#if defined(FLATBUFFERS_CPP98_STL)
-template<> inline std::string NumToString<long long>(long long t) {
- char buf[21]; // (log((1 << 63) - 1) / log(10)) + 2
- snprintf(buf, sizeof(buf), "%lld", t);
- return std::string(buf);
-}
-
-template<>
-inline std::string NumToString<unsigned long long>(unsigned long long t) {
- char buf[22]; // (log((1 << 63) - 1) / log(10)) + 1
- snprintf(buf, sizeof(buf), "%llu", t);
- return std::string(buf);
-}
-#endif // defined(FLATBUFFERS_CPP98_STL)
// Special versions for floats/doubles.
template<typename T> std::string FloatToString(T t, int precision) {
@@ -332,6 +322,9 @@
// - If the converted value falls out of range of corresponding return type, a
// range error occurs. In this case value MAX(T)/MIN(T) is returned.
template<typename T> inline bool StringToNumber(const char *s, T *val) {
+ // Assert on `unsigned long` and `signed long` on LP64.
+ // If it is necessary, it could be solved with flatbuffers::enable_if<B,T>.
+ static_assert(sizeof(T) < sizeof(int64_t), "unexpected type T");
FLATBUFFERS_ASSERT(s && val);
int64_t i64;
// The errno check isn't needed, will return MAX/MIN on overflow.
@@ -462,6 +455,7 @@
// Replaces any '\\' separators with '/'
std::string PosixPath(const char *path);
+std::string PosixPath(const std::string &path);
// This function ensure a directory exists, by recursively
// creating dirs for any parts of the path that don't exist yet.
@@ -471,6 +465,10 @@
// Returns the input path if the absolute path couldn't be resolved.
std::string AbsolutePath(const std::string &filepath);
+// Returns files relative to the --project_root path, prefixed with `//`.
+std::string RelativeToRootPath(const std::string &project,
+ const std::string &filepath);
+
// To and from UTF-8 unicode conversion functions
// Convert a unicode code point into a UTF-8 representation by appending it
@@ -687,6 +685,30 @@
// MSVC specific: Send all assert reports to STDOUT to prevent CI hangs.
void SetupDefaultCRTReportMode();
+enum class Case {
+ kUnknown = 0,
+ // TheQuickBrownFox
+ kUpperCamel = 1,
+ // theQuickBrownFox
+ kLowerCamel = 2,
+ // the_quick_brown_fox
+ kSnake = 3,
+ // THE_QUICK_BROWN_FOX
+ kScreamingSnake = 4,
+ // THEQUICKBROWNFOX
+ kAllUpper = 5,
+ // thequickbrownfox
+ kAllLower = 6,
+ // the-quick-brown-fox
+ kDasher = 7,
+ // THEQuiCKBr_ownFox (or whatever you want, we won't change it)
+ kKeep = 8,
+};
+
+// Convert the `input` string of case `input_case` to the specified `output_case`.
+std::string ConvertCase(const std::string &input, Case output_case,
+ Case input_case = Case::kSnake);
+
} // namespace flatbuffers
#endif // FLATBUFFERS_UTIL_H_
diff --git a/include/flatbuffers/vector.h b/include/flatbuffers/vector.h
new file mode 100644
index 0000000..f8a5d88
--- /dev/null
+++ b/include/flatbuffers/vector.h
@@ -0,0 +1,370 @@
+/*
+ * Copyright 2021 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_VECTOR_H_
+#define FLATBUFFERS_VECTOR_H_
+
+#include "flatbuffers/base.h"
+#include "flatbuffers/buffer.h"
+
+namespace flatbuffers {
+
+struct String;
+
+// An STL compatible iterator implementation for Vector below, effectively
+// calling Get() for every element.
+template<typename T, typename IT> struct VectorIterator {
+ typedef std::random_access_iterator_tag iterator_category;
+ typedef IT value_type;
+ typedef ptrdiff_t difference_type;
+ typedef IT *pointer;
+ typedef IT &reference;
+
+ VectorIterator(const uint8_t *data, uoffset_t i)
+ : data_(data + IndirectHelper<T>::element_stride * i) {}
+ VectorIterator(const VectorIterator &other) : data_(other.data_) {}
+ VectorIterator() : data_(nullptr) {}
+
+ VectorIterator &operator=(const VectorIterator &other) {
+ data_ = other.data_;
+ return *this;
+ }
+
+ VectorIterator &operator=(VectorIterator &&other) {
+ data_ = other.data_;
+ return *this;
+ }
+
+ bool operator==(const VectorIterator &other) const {
+ return data_ == other.data_;
+ }
+
+ bool operator<(const VectorIterator &other) const {
+ return data_ < other.data_;
+ }
+
+ bool operator!=(const VectorIterator &other) const {
+ return data_ != other.data_;
+ }
+
+ difference_type operator-(const VectorIterator &other) const {
+ return (data_ - other.data_) / IndirectHelper<T>::element_stride;
+ }
+
+ // Note: return type is incompatible with the standard
+ // `reference operator*()`.
+ IT operator*() const { return IndirectHelper<T>::Read(data_, 0); }
+
+ // Note: return type is incompatible with the standard
+ // `pointer operator->()`.
+ IT operator->() const { return IndirectHelper<T>::Read(data_, 0); }
+
+ VectorIterator &operator++() {
+ data_ += IndirectHelper<T>::element_stride;
+ return *this;
+ }
+
+ VectorIterator operator++(int) {
+ VectorIterator temp(data_, 0);
+ data_ += IndirectHelper<T>::element_stride;
+ return temp;
+ }
+
+ VectorIterator operator+(const uoffset_t &offset) const {
+ return VectorIterator(data_ + offset * IndirectHelper<T>::element_stride,
+ 0);
+ }
+
+ VectorIterator &operator+=(const uoffset_t &offset) {
+ data_ += offset * IndirectHelper<T>::element_stride;
+ return *this;
+ }
+
+ VectorIterator &operator--() {
+ data_ -= IndirectHelper<T>::element_stride;
+ return *this;
+ }
+
+ VectorIterator operator--(int) {
+ VectorIterator temp(data_, 0);
+ data_ -= IndirectHelper<T>::element_stride;
+ return temp;
+ }
+
+ VectorIterator operator-(const uoffset_t &offset) const {
+ return VectorIterator(data_ - offset * IndirectHelper<T>::element_stride,
+ 0);
+ }
+
+ VectorIterator &operator-=(const uoffset_t &offset) {
+ data_ -= offset * IndirectHelper<T>::element_stride;
+ return *this;
+ }
+
+ private:
+ const uint8_t *data_;
+};
+
+template<typename Iterator>
+struct VectorReverseIterator : public std::reverse_iterator<Iterator> {
+ explicit VectorReverseIterator(Iterator iter)
+ : std::reverse_iterator<Iterator>(iter) {}
+
+ // Note: return type is incompatible with the standard
+ // `reference operator*()`.
+ typename Iterator::value_type operator*() const {
+ auto tmp = std::reverse_iterator<Iterator>::current;
+ return *--tmp;
+ }
+
+ // Note: return type is incompatible with the standard
+ // `pointer operator->()`.
+ typename Iterator::value_type operator->() const {
+ auto tmp = std::reverse_iterator<Iterator>::current;
+ return *--tmp;
+ }
+};
+
+// This is used as a helper type for accessing vectors.
+// Vector::data() assumes the vector elements start after the length field.
+template<typename T> class Vector {
+ public:
+ typedef VectorIterator<T, typename IndirectHelper<T>::mutable_return_type>
+ iterator;
+ typedef VectorIterator<T, typename IndirectHelper<T>::return_type>
+ const_iterator;
+ typedef VectorReverseIterator<iterator> reverse_iterator;
+ typedef VectorReverseIterator<const_iterator> const_reverse_iterator;
+
+ typedef typename flatbuffers::bool_constant<flatbuffers::is_scalar<T>::value>
+ scalar_tag;
+
+ static FLATBUFFERS_CONSTEXPR bool is_span_observable =
+ scalar_tag::value && (FLATBUFFERS_LITTLEENDIAN || sizeof(T) == 1);
+
+ uoffset_t size() const { return EndianScalar(length_); }
+
+ // Deprecated: use size(). Here for backwards compatibility.
+ FLATBUFFERS_ATTRIBUTE([[deprecated("use size() instead")]])
+ uoffset_t Length() const { return size(); }
+
+ typedef typename IndirectHelper<T>::return_type return_type;
+ typedef typename IndirectHelper<T>::mutable_return_type mutable_return_type;
+ typedef return_type value_type;
+
+ return_type Get(uoffset_t i) const {
+ FLATBUFFERS_ASSERT(i < size());
+ return IndirectHelper<T>::Read(Data(), i);
+ }
+
+ return_type operator[](uoffset_t i) const { return Get(i); }
+
+ // If this is a Vector of enums, T will be its storage type, not the enum
+ // type. This function makes it convenient to retrieve value with enum
+ // type E.
+ template<typename E> E GetEnum(uoffset_t i) const {
+ return static_cast<E>(Get(i));
+ }
+
+ // If this a vector of unions, this does the cast for you. There's no check
+ // to make sure this is the right type!
+ template<typename U> const U *GetAs(uoffset_t i) const {
+ return reinterpret_cast<const U *>(Get(i));
+ }
+
+ // If this a vector of unions, this does the cast for you. There's no check
+ // to make sure this is actually a string!
+ const String *GetAsString(uoffset_t i) const {
+ return reinterpret_cast<const String *>(Get(i));
+ }
+
+ const void *GetStructFromOffset(size_t o) const {
+ return reinterpret_cast<const void *>(Data() + o);
+ }
+
+ iterator begin() { return iterator(Data(), 0); }
+ const_iterator begin() const { return const_iterator(Data(), 0); }
+
+ iterator end() { return iterator(Data(), size()); }
+ const_iterator end() const { return const_iterator(Data(), size()); }
+
+ reverse_iterator rbegin() { return reverse_iterator(end()); }
+ const_reverse_iterator rbegin() const {
+ return const_reverse_iterator(end());
+ }
+
+ reverse_iterator rend() { return reverse_iterator(begin()); }
+ const_reverse_iterator rend() const {
+ return const_reverse_iterator(begin());
+ }
+
+ const_iterator cbegin() const { return begin(); }
+
+ const_iterator cend() const { return end(); }
+
+ const_reverse_iterator crbegin() const { return rbegin(); }
+
+ const_reverse_iterator crend() const { return rend(); }
+
+ // Change elements if you have a non-const pointer to this object.
+ // Scalars only. See reflection.h, and the documentation.
+ void Mutate(uoffset_t i, const T &val) {
+ FLATBUFFERS_ASSERT(i < size());
+ WriteScalar(data() + i, val);
+ }
+
+ // Change an element of a vector of tables (or strings).
+ // "val" points to the new table/string, as you can obtain from
+ // e.g. reflection::AddFlatBuffer().
+ void MutateOffset(uoffset_t i, const uint8_t *val) {
+ FLATBUFFERS_ASSERT(i < size());
+ static_assert(sizeof(T) == sizeof(uoffset_t), "Unrelated types");
+ WriteScalar(data() + i,
+ static_cast<uoffset_t>(val - (Data() + i * sizeof(uoffset_t))));
+ }
+
+ // Get a mutable pointer to tables/strings inside this vector.
+ mutable_return_type GetMutableObject(uoffset_t i) const {
+ FLATBUFFERS_ASSERT(i < size());
+ return const_cast<mutable_return_type>(IndirectHelper<T>::Read(Data(), i));
+ }
+
+ // The raw data in little endian format. Use with care.
+ const uint8_t *Data() const {
+ return reinterpret_cast<const uint8_t *>(&length_ + 1);
+ }
+
+ uint8_t *Data() { return reinterpret_cast<uint8_t *>(&length_ + 1); }
+
+ // Similarly, but typed, much like std::vector::data
+ const T *data() const { return reinterpret_cast<const T *>(Data()); }
+ T *data() { return reinterpret_cast<T *>(Data()); }
+
+ template<typename K> return_type LookupByKey(K key) const {
+ void *search_result = std::bsearch(
+ &key, Data(), size(), IndirectHelper<T>::element_stride, KeyCompare<K>);
+
+ if (!search_result) {
+ return nullptr; // Key not found.
+ }
+
+ const uint8_t *element = reinterpret_cast<const uint8_t *>(search_result);
+
+ return IndirectHelper<T>::Read(element, 0);
+ }
+
+ template<typename K> mutable_return_type MutableLookupByKey(K key) {
+ return const_cast<mutable_return_type>(LookupByKey(key));
+ }
+
+ protected:
+ // This class is only used to access pre-existing data. Don't ever
+ // try to construct these manually.
+ Vector();
+
+ uoffset_t length_;
+
+ private:
+ // This class is a pointer. Copying will therefore create an invalid object.
+ // Private and unimplemented copy constructor.
+ Vector(const Vector &);
+ Vector &operator=(const Vector &);
+
+ template<typename K> static int KeyCompare(const void *ap, const void *bp) {
+ const K *key = reinterpret_cast<const K *>(ap);
+ const uint8_t *data = reinterpret_cast<const uint8_t *>(bp);
+ auto table = IndirectHelper<T>::Read(data, 0);
+
+ // std::bsearch compares with the operands transposed, so we negate the
+ // result here.
+ return -table->KeyCompareWithValue(*key);
+ }
+};
+
+template<class U>
+FLATBUFFERS_CONSTEXPR_CPP11 flatbuffers::span<U> make_span(Vector<U> &vec)
+ FLATBUFFERS_NOEXCEPT {
+ static_assert(Vector<U>::is_span_observable,
+ "wrong type U, only LE-scalar, or byte types are allowed");
+ return span<U>(vec.data(), vec.size());
+}
+
+template<class U>
+FLATBUFFERS_CONSTEXPR_CPP11 flatbuffers::span<const U> make_span(
+ const Vector<U> &vec) FLATBUFFERS_NOEXCEPT {
+ static_assert(Vector<U>::is_span_observable,
+ "wrong type U, only LE-scalar, or byte types are allowed");
+ return span<const U>(vec.data(), vec.size());
+}
+
+template<class U>
+FLATBUFFERS_CONSTEXPR_CPP11 flatbuffers::span<uint8_t> make_bytes_span(
+ Vector<U> &vec) FLATBUFFERS_NOEXCEPT {
+ static_assert(Vector<U>::scalar_tag::value,
+ "wrong type U, only LE-scalar, or byte types are allowed");
+ return span<uint8_t>(vec.Data(), vec.size() * sizeof(U));
+}
+
+template<class U>
+FLATBUFFERS_CONSTEXPR_CPP11 flatbuffers::span<const uint8_t> make_bytes_span(
+ const Vector<U> &vec) FLATBUFFERS_NOEXCEPT {
+ static_assert(Vector<U>::scalar_tag::value,
+ "wrong type U, only LE-scalar, or byte types are allowed");
+ return span<const uint8_t>(vec.Data(), vec.size() * sizeof(U));
+}
+
+// Represent a vector much like the template above, but in this case we
+// don't know what the element types are (used with reflection.h).
+class VectorOfAny {
+ public:
+ uoffset_t size() const { return EndianScalar(length_); }
+
+ const uint8_t *Data() const {
+ return reinterpret_cast<const uint8_t *>(&length_ + 1);
+ }
+ uint8_t *Data() { return reinterpret_cast<uint8_t *>(&length_ + 1); }
+
+ protected:
+ VectorOfAny();
+
+ uoffset_t length_;
+
+ private:
+ VectorOfAny(const VectorOfAny &);
+ VectorOfAny &operator=(const VectorOfAny &);
+};
+
+template<typename T, typename U>
+Vector<Offset<T>> *VectorCast(Vector<Offset<U>> *ptr) {
+ static_assert(std::is_base_of<T, U>::value, "Unrelated types");
+ return reinterpret_cast<Vector<Offset<T>> *>(ptr);
+}
+
+template<typename T, typename U>
+const Vector<Offset<T>> *VectorCast(const Vector<Offset<U>> *ptr) {
+ static_assert(std::is_base_of<T, U>::value, "Unrelated types");
+ return reinterpret_cast<const Vector<Offset<T>> *>(ptr);
+}
+
+// Convenient helper function to get the length of any vector, regardless
+// of whether it is null or not (the field is not set).
+template<typename T> static inline size_t VectorLength(const Vector<T> *v) {
+ return v ? v->size() : 0;
+}
+
+} // namespace flatbuffers
+
+#endif // FLATBUFFERS_VERIFIER_H_
diff --git a/include/flatbuffers/vector_downward.h b/include/flatbuffers/vector_downward.h
new file mode 100644
index 0000000..3391391
--- /dev/null
+++ b/include/flatbuffers/vector_downward.h
@@ -0,0 +1,271 @@
+/*
+ * Copyright 2021 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_VECTOR_DOWNWARD_H_
+#define FLATBUFFERS_VECTOR_DOWNWARD_H_
+
+#include "flatbuffers/base.h"
+#include "flatbuffers/default_allocator.h"
+#include "flatbuffers/detached_buffer.h"
+
+namespace flatbuffers {
+
+// This is a minimal replication of std::vector<uint8_t> functionality,
+// except growing from higher to lower addresses. i.e push_back() inserts data
+// in the lowest address in the vector.
+// Since this vector leaves the lower part unused, we support a "scratch-pad"
+// that can be stored there for temporary data, to share the allocated space.
+// Essentially, this supports 2 std::vectors in a single buffer.
+class vector_downward {
+ public:
+ explicit vector_downward(size_t initial_size, Allocator *allocator,
+ bool own_allocator, size_t buffer_minalign)
+ : allocator_(allocator),
+ own_allocator_(own_allocator),
+ initial_size_(initial_size),
+ buffer_minalign_(buffer_minalign),
+ reserved_(0),
+ size_(0),
+ buf_(nullptr),
+ cur_(nullptr),
+ scratch_(nullptr) {}
+
+ vector_downward(vector_downward &&other)
+ // clang-format on
+ : allocator_(other.allocator_),
+ own_allocator_(other.own_allocator_),
+ initial_size_(other.initial_size_),
+ buffer_minalign_(other.buffer_minalign_),
+ reserved_(other.reserved_),
+ size_(other.size_),
+ buf_(other.buf_),
+ cur_(other.cur_),
+ scratch_(other.scratch_) {
+ // No change in other.allocator_
+ // No change in other.initial_size_
+ // No change in other.buffer_minalign_
+ other.own_allocator_ = false;
+ other.reserved_ = 0;
+ other.buf_ = nullptr;
+ other.cur_ = nullptr;
+ other.scratch_ = nullptr;
+ }
+
+ vector_downward &operator=(vector_downward &&other) {
+ // Move construct a temporary and swap idiom
+ vector_downward temp(std::move(other));
+ swap(temp);
+ return *this;
+ }
+
+ ~vector_downward() {
+ clear_buffer();
+ clear_allocator();
+ }
+
+ void reset() {
+ clear_buffer();
+ clear();
+ }
+
+ void clear() {
+ if (buf_) {
+ cur_ = buf_ + reserved_;
+ } else {
+ reserved_ = 0;
+ cur_ = nullptr;
+ }
+ size_ = 0;
+ clear_scratch();
+ }
+
+ void clear_scratch() { scratch_ = buf_; }
+
+ void clear_allocator() {
+ if (own_allocator_ && allocator_) { delete allocator_; }
+ allocator_ = nullptr;
+ own_allocator_ = false;
+ }
+
+ void clear_buffer() {
+ if (buf_) Deallocate(allocator_, buf_, reserved_);
+ buf_ = nullptr;
+ }
+
+ // Relinquish the pointer to the caller.
+ uint8_t *release_raw(size_t &allocated_bytes, size_t &offset) {
+ auto *buf = buf_;
+ allocated_bytes = reserved_;
+ offset = static_cast<size_t>(cur_ - buf_);
+
+ // release_raw only relinquishes the buffer ownership.
+ // Does not deallocate or reset the allocator. Destructor will do that.
+ buf_ = nullptr;
+ clear();
+ return buf;
+ }
+
+ // Relinquish the pointer to the caller.
+ DetachedBuffer release() {
+ // allocator ownership (if any) is transferred to DetachedBuffer.
+ DetachedBuffer fb(allocator_, own_allocator_, buf_, reserved_, cur_,
+ size());
+ if (own_allocator_) {
+ allocator_ = nullptr;
+ own_allocator_ = false;
+ }
+ buf_ = nullptr;
+ clear();
+ return fb;
+ }
+
+ size_t ensure_space(size_t len) {
+ FLATBUFFERS_ASSERT(cur_ >= scratch_ && scratch_ >= buf_);
+ if (len > static_cast<size_t>(cur_ - scratch_)) { reallocate(len); }
+ // Beyond this, signed offsets may not have enough range:
+ // (FlatBuffers > 2GB not supported).
+ FLATBUFFERS_ASSERT(size() < FLATBUFFERS_MAX_BUFFER_SIZE);
+ return len;
+ }
+
+ inline uint8_t *make_space(size_t len) {
+ if (len) {
+ ensure_space(len);
+ cur_ -= len;
+ size_ += static_cast<uoffset_t>(len);
+ }
+ return cur_;
+ }
+
+ // Returns nullptr if using the DefaultAllocator.
+ Allocator *get_custom_allocator() { return allocator_; }
+
+ inline uoffset_t size() const { return size_; }
+
+ uoffset_t scratch_size() const {
+ return static_cast<uoffset_t>(scratch_ - buf_);
+ }
+
+ size_t capacity() const { return reserved_; }
+
+ uint8_t *data() const {
+ FLATBUFFERS_ASSERT(cur_);
+ return cur_;
+ }
+
+ uint8_t *scratch_data() const {
+ FLATBUFFERS_ASSERT(buf_);
+ return buf_;
+ }
+
+ uint8_t *scratch_end() const {
+ FLATBUFFERS_ASSERT(scratch_);
+ return scratch_;
+ }
+
+ uint8_t *data_at(size_t offset) const { return buf_ + reserved_ - offset; }
+
+ void push(const uint8_t *bytes, size_t num) {
+ if (num > 0) { memcpy(make_space(num), bytes, num); }
+ }
+
+ // Specialized version of push() that avoids memcpy call for small data.
+ template<typename T> void push_small(const T &little_endian_t) {
+ make_space(sizeof(T));
+ *reinterpret_cast<T *>(cur_) = little_endian_t;
+ }
+
+ template<typename T> void scratch_push_small(const T &t) {
+ ensure_space(sizeof(T));
+ *reinterpret_cast<T *>(scratch_) = t;
+ scratch_ += sizeof(T);
+ }
+
+ // fill() is most frequently called with small byte counts (<= 4),
+ // which is why we're using loops rather than calling memset.
+ void fill(size_t zero_pad_bytes) {
+ make_space(zero_pad_bytes);
+ for (size_t i = 0; i < zero_pad_bytes; i++) cur_[i] = 0;
+ }
+
+ // Version for when we know the size is larger.
+ // Precondition: zero_pad_bytes > 0
+ void fill_big(size_t zero_pad_bytes) {
+ memset(make_space(zero_pad_bytes), 0, zero_pad_bytes);
+ }
+
+ void pop(size_t bytes_to_remove) {
+ cur_ += bytes_to_remove;
+ size_ -= static_cast<uoffset_t>(bytes_to_remove);
+ }
+
+ void scratch_pop(size_t bytes_to_remove) { scratch_ -= bytes_to_remove; }
+
+ void swap(vector_downward &other) {
+ using std::swap;
+ swap(allocator_, other.allocator_);
+ swap(own_allocator_, other.own_allocator_);
+ swap(initial_size_, other.initial_size_);
+ swap(buffer_minalign_, other.buffer_minalign_);
+ swap(reserved_, other.reserved_);
+ swap(size_, other.size_);
+ swap(buf_, other.buf_);
+ swap(cur_, other.cur_);
+ swap(scratch_, other.scratch_);
+ }
+
+ void swap_allocator(vector_downward &other) {
+ using std::swap;
+ swap(allocator_, other.allocator_);
+ swap(own_allocator_, other.own_allocator_);
+ }
+
+ private:
+ // You shouldn't really be copying instances of this class.
+ FLATBUFFERS_DELETE_FUNC(vector_downward(const vector_downward &));
+ FLATBUFFERS_DELETE_FUNC(vector_downward &operator=(const vector_downward &));
+
+ Allocator *allocator_;
+ bool own_allocator_;
+ size_t initial_size_;
+ size_t buffer_minalign_;
+ size_t reserved_;
+ uoffset_t size_;
+ uint8_t *buf_;
+ uint8_t *cur_; // Points at location between empty (below) and used (above).
+ uint8_t *scratch_; // Points to the end of the scratchpad in use.
+
+ void reallocate(size_t len) {
+ auto old_reserved = reserved_;
+ auto old_size = size();
+ auto old_scratch_size = scratch_size();
+ reserved_ +=
+ (std::max)(len, old_reserved ? old_reserved / 2 : initial_size_);
+ reserved_ = (reserved_ + buffer_minalign_ - 1) & ~(buffer_minalign_ - 1);
+ if (buf_) {
+ buf_ = ReallocateDownward(allocator_, buf_, old_reserved, reserved_,
+ old_size, old_scratch_size);
+ } else {
+ buf_ = Allocate(allocator_, reserved_);
+ }
+ cur_ = buf_ + reserved_ - old_size;
+ scratch_ = buf_ + old_scratch_size;
+ }
+};
+
+} // namespace flatbuffers
+
+#endif // FLATBUFFERS_VECTOR_DOWNWARD_H_
diff --git a/include/flatbuffers/verifier.h b/include/flatbuffers/verifier.h
new file mode 100644
index 0000000..4512d45
--- /dev/null
+++ b/include/flatbuffers/verifier.h
@@ -0,0 +1,283 @@
+/*
+ * Copyright 2021 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_VERIFIER_H_
+#define FLATBUFFERS_VERIFIER_H_
+
+#include "flatbuffers/base.h"
+#include "flatbuffers/util.h"
+#include "flatbuffers/vector.h"
+
+namespace flatbuffers {
+
+// Helper class to verify the integrity of a FlatBuffer
+class Verifier FLATBUFFERS_FINAL_CLASS {
+ public:
+ Verifier(const uint8_t *buf, size_t buf_len, uoffset_t _max_depth = 64,
+ uoffset_t _max_tables = 1000000, bool _check_alignment = true)
+ : buf_(buf),
+ size_(buf_len),
+ depth_(0),
+ max_depth_(_max_depth),
+ num_tables_(0),
+ max_tables_(_max_tables),
+ upper_bound_(0),
+ check_alignment_(_check_alignment),
+ flex_reuse_tracker_(nullptr) {
+ FLATBUFFERS_ASSERT(size_ < FLATBUFFERS_MAX_BUFFER_SIZE);
+ }
+
+ // Central location where any verification failures register.
+ bool Check(bool ok) const {
+ // clang-format off
+ #ifdef FLATBUFFERS_DEBUG_VERIFICATION_FAILURE
+ FLATBUFFERS_ASSERT(ok);
+ #endif
+ #ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
+ if (!ok)
+ upper_bound_ = 0;
+ #endif
+ // clang-format on
+ return ok;
+ }
+
+ // Verify any range within the buffer.
+ bool Verify(size_t elem, size_t elem_len) const {
+ // clang-format off
+ #ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
+ auto upper_bound = elem + elem_len;
+ if (upper_bound_ < upper_bound)
+ upper_bound_ = upper_bound;
+ #endif
+ // clang-format on
+ return Check(elem_len < size_ && elem <= size_ - elem_len);
+ }
+
+ bool VerifyAlignment(size_t elem, size_t align) const {
+ return Check((elem & (align - 1)) == 0 || !check_alignment_);
+ }
+
+ // Verify a range indicated by sizeof(T).
+ template<typename T> bool Verify(size_t elem) const {
+ return VerifyAlignment(elem, sizeof(T)) && 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 VerifyFieldStruct(const uint8_t *base, voffset_t elem_off,
+ size_t elem_len, size_t align) const {
+ auto f = static_cast<size_t>(base - buf_) + elem_off;
+ return VerifyAlignment(f, align) && Verify(f, elem_len);
+ }
+
+ template<typename T>
+ bool VerifyField(const uint8_t *base, voffset_t elem_off,
+ size_t align) const {
+ auto f = static_cast<size_t>(base - buf_) + elem_off;
+ return VerifyAlignment(f, align) && Verify(f, sizeof(T));
+ }
+
+ // Verify a pointer (may be NULL) of a table type.
+ template<typename T> bool VerifyTable(const T *table) {
+ return !table || table->Verify(*this);
+ }
+
+ // Verify a pointer (may be NULL) of any vector type.
+ template<typename T> bool VerifyVector(const Vector<T> *vec) const {
+ return !vec || VerifyVectorOrString(reinterpret_cast<const uint8_t *>(vec),
+ sizeof(T));
+ }
+
+ // Verify a pointer (may be NULL) of a vector to struct.
+ template<typename T> bool VerifyVector(const Vector<const T *> *vec) const {
+ return VerifyVector(reinterpret_cast<const Vector<T> *>(vec));
+ }
+
+ // Verify a pointer (may be NULL) to string.
+ bool VerifyString(const String *str) const {
+ size_t end;
+ return !str || (VerifyVectorOrString(reinterpret_cast<const uint8_t *>(str),
+ 1, &end) &&
+ Verify(end, 1) && // Must have terminator
+ Check(buf_[end] == '\0')); // Terminating byte must be 0.
+ }
+
+ // Common code between vectors and strings.
+ bool VerifyVectorOrString(const uint8_t *vec, size_t elem_size,
+ size_t *end = nullptr) const {
+ auto veco = static_cast<size_t>(vec - buf_);
+ // Check we can read the size field.
+ if (!Verify<uoffset_t>(veco)) return false;
+ // Check the whole array. If this is a string, the byte past the array
+ // must be 0.
+ auto size = ReadScalar<uoffset_t>(vec);
+ auto max_elems = FLATBUFFERS_MAX_BUFFER_SIZE / elem_size;
+ if (!Check(size < max_elems))
+ return false; // Protect against byte_size overflowing.
+ auto byte_size = sizeof(size) + elem_size * size;
+ if (end) *end = veco + byte_size;
+ return Verify(veco, byte_size);
+ }
+
+ // Special case for string contents, after the above has been called.
+ bool VerifyVectorOfStrings(const Vector<Offset<String>> *vec) const {
+ if (vec) {
+ for (uoffset_t i = 0; i < vec->size(); i++) {
+ if (!VerifyString(vec->Get(i))) return false;
+ }
+ }
+ return true;
+ }
+
+ // Special case for table contents, after the above has been called.
+ template<typename T> bool VerifyVectorOfTables(const Vector<Offset<T>> *vec) {
+ if (vec) {
+ for (uoffset_t i = 0; i < vec->size(); i++) {
+ if (!vec->Get(i)->Verify(*this)) return false;
+ }
+ }
+ return true;
+ }
+
+ __supress_ubsan__("unsigned-integer-overflow") bool VerifyTableStart(
+ const uint8_t *table) {
+ // Check the vtable offset.
+ auto tableo = static_cast<size_t>(table - buf_);
+ if (!Verify<soffset_t>(tableo)) return false;
+ // This offset may be signed, but doing the subtraction unsigned always
+ // gives the result we want.
+ auto vtableo = tableo - static_cast<size_t>(ReadScalar<soffset_t>(table));
+ // Check the vtable size field, then check vtable fits in its entirety.
+ return VerifyComplexity() && Verify<voffset_t>(vtableo) &&
+ VerifyAlignment(ReadScalar<voffset_t>(buf_ + vtableo),
+ sizeof(voffset_t)) &&
+ Verify(vtableo, ReadScalar<voffset_t>(buf_ + vtableo));
+ }
+
+ template<typename T>
+ bool VerifyBufferFromStart(const char *identifier, size_t start) {
+ if (identifier && !Check((size_ >= 2 * sizeof(flatbuffers::uoffset_t) &&
+ BufferHasIdentifier(buf_ + start, identifier)))) {
+ return false;
+ }
+
+ // Call T::Verify, which must be in the generated code for this type.
+ auto o = VerifyOffset(start);
+ return o && reinterpret_cast<const T *>(buf_ + start + o)->Verify(*this)
+ // clang-format off
+ #ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
+ && GetComputedSize()
+ #endif
+ ;
+ // clang-format on
+ }
+
+ template<typename T>
+ bool VerifyNestedFlatBuffer(const Vector<uint8_t> *buf,
+ const char *identifier) {
+ if (!buf) return true;
+ Verifier nested_verifier(buf->data(), buf->size());
+ return nested_verifier.VerifyBuffer<T>(identifier);
+ }
+
+ // Verify this whole buffer, starting with root type T.
+ template<typename T> bool VerifyBuffer() { return VerifyBuffer<T>(nullptr); }
+
+ template<typename T> bool VerifyBuffer(const char *identifier) {
+ return VerifyBufferFromStart<T>(identifier, 0);
+ }
+
+ template<typename T> bool VerifySizePrefixedBuffer(const char *identifier) {
+ return Verify<uoffset_t>(0U) &&
+ ReadScalar<uoffset_t>(buf_) == size_ - sizeof(uoffset_t) &&
+ VerifyBufferFromStart<T>(identifier, sizeof(uoffset_t));
+ }
+
+ uoffset_t VerifyOffset(size_t start) const {
+ if (!Verify<uoffset_t>(start)) return 0;
+ auto o = ReadScalar<uoffset_t>(buf_ + start);
+ // May not point to itself.
+ if (!Check(o != 0)) return 0;
+ // Can't wrap around / buffers are max 2GB.
+ if (!Check(static_cast<soffset_t>(o) >= 0)) return 0;
+ // Must be inside the buffer to create a pointer from it (pointer outside
+ // buffer is UB).
+ if (!Verify(start + o, 1)) return 0;
+ return o;
+ }
+
+ uoffset_t VerifyOffset(const uint8_t *base, voffset_t start) const {
+ return VerifyOffset(static_cast<size_t>(base - buf_) + start);
+ }
+
+ // Called at the start of a table to increase counters measuring data
+ // structure depth and amount, and possibly bails out with false if
+ // limits set by the constructor have been hit. Needs to be balanced
+ // with EndTable().
+ bool VerifyComplexity() {
+ depth_++;
+ num_tables_++;
+ return Check(depth_ <= max_depth_ && num_tables_ <= max_tables_);
+ }
+
+ // Called at the end of a table to pop the depth count.
+ bool EndTable() {
+ depth_--;
+ return true;
+ }
+
+ // Returns the message size in bytes
+ size_t GetComputedSize() const {
+ // clang-format off
+ #ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
+ uintptr_t size = upper_bound_;
+ // Align the size to uoffset_t
+ size = (size - 1 + sizeof(uoffset_t)) & ~(sizeof(uoffset_t) - 1);
+ return (size > size_) ? 0 : size;
+ #else
+ // Must turn on FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE for this to work.
+ (void)upper_bound_;
+ FLATBUFFERS_ASSERT(false);
+ return 0;
+ #endif
+ // clang-format on
+ }
+
+ std::vector<uint8_t> *GetFlexReuseTracker() { return flex_reuse_tracker_; }
+
+ void SetFlexReuseTracker(std::vector<uint8_t> *rt) {
+ flex_reuse_tracker_ = rt;
+ }
+
+ private:
+ const uint8_t *buf_;
+ size_t size_;
+ uoffset_t depth_;
+ uoffset_t max_depth_;
+ uoffset_t num_tables_;
+ uoffset_t max_tables_;
+ mutable size_t upper_bound_;
+ bool check_alignment_;
+ std::vector<uint8_t> *flex_reuse_tracker_;
+};
+
+} // namespace flatbuffers
+
+#endif // FLATBUFFERS_VERIFIER_H_
diff --git a/java/com/google/flatbuffers/Constants.java b/java/com/google/flatbuffers/Constants.java
index 0623b94..0c0920f 100644
--- a/java/com/google/flatbuffers/Constants.java
+++ b/java/com/google/flatbuffers/Constants.java
@@ -46,7 +46,7 @@
Changes to the Java implementation need to be sure to change
the version here and in the code generator on every possible
incompatible change */
- public static void FLATBUFFERS_1_12_0() {}
+ public static void FLATBUFFERS_2_0_0() {}
}
/// @endcond
diff --git a/java/com/google/flatbuffers/FlexBuffers.java b/java/com/google/flatbuffers/FlexBuffers.java
index 8263f9a..75a0595 100644
--- a/java/com/google/flatbuffers/FlexBuffers.java
+++ b/java/com/google/flatbuffers/FlexBuffers.java
@@ -655,7 +655,7 @@
Sized(ReadBuf buff, int end, int byteWidth) {
super(buff, end, byteWidth);
- size = readInt(bb, end - byteWidth, byteWidth);
+ size = (int) readUInt(bb, end - byteWidth, byteWidth);
}
public int size() {
@@ -788,7 +788,12 @@
if (io == other.length) {
// in our buffer we have an additional \0 byte
// but this does not exist in regular Java strings, so we return now
- return c1 - c2;
+ int cmp = c1 - c2;
+ if (cmp != 0 || bb.get(ia) == '\0') {
+ return cmp;
+ } else {
+ return 1;
+ }
}
}
while (c1 == c2);
@@ -961,7 +966,12 @@
if (l2 == other.length) {
// in our buffer we have an additional \0 byte
// but this does not exist in regular Java strings, so we return now
- return c1 - c2;
+ int cmp = c1 - c2;
+ if (cmp != 0 || bb.get(l1) == '\0') {
+ return cmp;
+ } else {
+ return 1;
+ }
}
}
while (c1 == c2);
diff --git a/java/com/google/flatbuffers/FlexBuffersBuilder.java b/java/com/google/flatbuffers/FlexBuffersBuilder.java
index dc0df96..7f41bb6 100644
--- a/java/com/google/flatbuffers/FlexBuffersBuilder.java
+++ b/java/com/google/flatbuffers/FlexBuffersBuilder.java
@@ -452,8 +452,8 @@
* Finishes a vector, but writing the information in the buffer
* @param key key used to store element in map
* @param start reference for begining of the vector. Returned by {@link startVector()}
- * @param typed boolean indicating wether vector is typed
- * @param fixed boolean indicating wether vector is fixed
+ * @param typed boolean indicating whether vector is typed
+ * @param fixed boolean indicating whether vector is fixed
* @return Reference to the vector
*/
public int endVector(String key, int start, boolean typed, boolean fixed) {
@@ -763,7 +763,7 @@
// Compute relative offset.
long offset = offsetLoc - iValue;
// Does it fit?
- int bitWidth = widthUInBits((int) offset);
+ int bitWidth = widthUInBits(offset);
if (((1L) << bitWidth) == byteWidth)
return bitWidth;
}
diff --git a/java/com/google/flatbuffers/Utf8Safe.java b/java/com/google/flatbuffers/Utf8Safe.java
index 523e3f1..060379f 100644
--- a/java/com/google/flatbuffers/Utf8Safe.java
+++ b/java/com/google/flatbuffers/Utf8Safe.java
@@ -1,33 +1,3 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
package com.google.flatbuffers;
import java.nio.ByteBuffer;
diff --git a/kotlin/benchmark/build.gradle.kts b/kotlin/benchmark/build.gradle.kts
new file mode 100644
index 0000000..2294e4c
--- /dev/null
+++ b/kotlin/benchmark/build.gradle.kts
@@ -0,0 +1,111 @@
+import org.jetbrains.kotlin.ir.backend.js.compile
+
+plugins {
+ kotlin("multiplatform") version "1.4.20"
+ id("org.jetbrains.kotlin.plugin.allopen") version "1.4.20"
+ id("org.jetbrains.kotlinx.benchmark") version "0.3.0"
+ id("io.morethan.jmhreport") version "0.9.0"
+ id("de.undercouch.download") version "4.1.1"
+}
+
+// allOpen plugin is needed for the benchmark annotations.
+// for more infomation, see https://github.com/Kotlin/kotlinx-benchmark#gradle-plugin
+allOpen {
+ annotation("org.openjdk.jmh.annotations.State")
+}
+
+group = "com.google.flatbuffers.jmh"
+version = "2.0.0-SNAPSHOT"
+
+// This plugin generates a static html page with the aggregation
+// of all benchmarks ran. very useful visualization tool.
+jmhReport {
+ val baseFolder = project.file("build/reports/benchmarks/main").absolutePath
+ val lastFolder = project.file(baseFolder).list()?.sortedArray()?.lastOrNull() ?: ""
+ jmhResultPath = "$baseFolder/$lastFolder/jvm.json"
+ jmhReportOutput = "$baseFolder/$lastFolder"
+}
+
+// For now we benchmark on JVM only
+benchmark {
+ configurations {
+ this.getByName("main") {
+ iterations = 5
+ iterationTime = 300
+ iterationTimeUnit = "ms"
+ // uncomment for benchmarking JSON op only
+ // include(".*JsonBenchmark.*")
+ }
+ }
+ targets {
+ register("jvm")
+ }
+}
+
+kotlin {
+ jvm {
+ withJava()
+ compilations.all {
+ kotlinOptions {
+ jvmTarget = JavaVersion.VERSION_1_8.toString()
+ }
+ }
+ }
+
+ sourceSets {
+
+ all {
+ languageSettings.enableLanguageFeature("InlineClasses")
+ languageSettings.useExperimentalAnnotation("kotlin.ExperimentalUnsignedTypes")
+ }
+
+ val commonTest by getting {
+ dependencies {
+ implementation(kotlin("test-common"))
+ implementation(kotlin("test-annotations-common"))
+ }
+ }
+ val jvmTest by getting {
+ dependencies {
+ implementation(kotlin("test-junit"))
+ }
+ }
+ val jvmMain by getting {
+ dependencies {
+ implementation("org.jetbrains.kotlinx:kotlinx-benchmark-runtime:0.3.0")
+ implementation(kotlin("stdlib-common"))
+ implementation(project(":flatbuffers-kotlin"))
+ implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
+ implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.4.1")
+
+ //moshi
+ implementation("com.squareup.moshi:moshi-kotlin:1.11.0")
+
+ //gson
+ implementation("com.google.code.gson:gson:2.8.5")
+ }
+ }
+
+ /* Targets configuration omitted.
+ * To find out how to configure the targets, please follow the link:
+ * https://kotlinlang.org/docs/reference/building-mpp-with-gradle.html#setting-up-targets
+ */
+ targets {
+ targetFromPreset(presets.getAt("jvm"))
+ }
+ }
+}
+
+// This task download all JSON files used for benchmarking
+tasks.register<de.undercouch.gradle.tasks.download.Download>("downloadMultipleFiles") {
+ // We are downloading json benchmark samples from serdes-rs project.
+ // see: https://github.com/serde-rs/json-benchmark/blob/master/data
+ val baseUrl = "https://github.com/serde-rs/json-benchmark/raw/master/data/"
+ src(listOf("$baseUrl/canada.json", "$baseUrl/twitter.json", "$baseUrl/citm_catalog.json"))
+ dest(File("${project.projectDir.absolutePath}/src/jvmMain/resources"))
+ overwrite(false)
+}
+
+project.tasks.named("compileKotlinJvm") {
+ dependsOn("downloadMultipleFiles")
+}
diff --git a/kotlin/benchmark/src/jvmMain/java b/kotlin/benchmark/src/jvmMain/java
new file mode 120000
index 0000000..2260196
--- /dev/null
+++ b/kotlin/benchmark/src/jvmMain/java
@@ -0,0 +1 @@
+../../../../java/
\ No newline at end of file
diff --git a/kotlin/benchmark/src/jvmMain/kotlin/com/google/flatbuffers/kotlin/benchmark/FlexBuffersBenchmark.kt b/kotlin/benchmark/src/jvmMain/kotlin/com/google/flatbuffers/kotlin/benchmark/FlexBuffersBenchmark.kt
new file mode 100644
index 0000000..ade57d9
--- /dev/null
+++ b/kotlin/benchmark/src/jvmMain/kotlin/com/google/flatbuffers/kotlin/benchmark/FlexBuffersBenchmark.kt
@@ -0,0 +1,198 @@
+/*
+ * Copyright 2021 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.
+ */
+package com.google.flatbuffers.kotlin.benchmark
+
+import com.google.flatbuffers.ArrayReadWriteBuf
+import com.google.flatbuffers.FlexBuffers
+import com.google.flatbuffers.FlexBuffersBuilder.BUILDER_FLAG_SHARE_ALL
+import com.google.flatbuffers.kotlin.FlexBuffersBuilder
+import com.google.flatbuffers.kotlin.getRoot
+import kotlinx.benchmark.Blackhole
+import org.openjdk.jmh.annotations.Benchmark
+import org.openjdk.jmh.annotations.BenchmarkMode
+import org.openjdk.jmh.annotations.Measurement
+import org.openjdk.jmh.annotations.Mode
+import org.openjdk.jmh.annotations.OutputTimeUnit
+import org.openjdk.jmh.annotations.Scope
+import org.openjdk.jmh.annotations.Setup
+import org.openjdk.jmh.annotations.State
+import java.util.concurrent.TimeUnit
+
+@State(Scope.Benchmark)
+@BenchmarkMode(Mode.AverageTime)
+@OutputTimeUnit(TimeUnit.NANOSECONDS)
+@Measurement(iterations = 20, time = 1, timeUnit = TimeUnit.NANOSECONDS)
+class FlexBuffersBenchmark {
+
+ var initialCapacity = 1024
+ var value: Double = 0.0
+ val stringKey = Array(500) { "Ḧ̵̘́ȩ̵̐myFairlyBigKey$it" }
+ val stringValue = Array(500) { "Ḧ̵̘́ȩ̵̐myFairlyBigValue$it" }
+ val bigIntArray = IntArray(5000) { it }
+
+ @Setup
+ fun setUp() {
+ value = 3.0
+ }
+
+ @Benchmark
+ fun mapKotlin(blackhole: Blackhole) {
+ val kBuilder = FlexBuffersBuilder(initialCapacity, FlexBuffersBuilder.SHARE_KEYS_AND_STRINGS)
+ kBuilder.putMap {
+ this["hello"] = "world"
+ this["int"] = 10
+ this["float"] = 12.3
+ this["intarray"] = bigIntArray
+ this.putMap("myMap") {
+ this["cool"] = "beans"
+ }
+ }
+ val ref = getRoot(kBuilder.finish())
+ val map = ref.toMap()
+ blackhole.consume(map.size)
+ blackhole.consume(map["hello"].toString())
+ blackhole.consume(map["int"].toInt())
+ blackhole.consume(map["float"].toDouble())
+ blackhole.consume(map["intarray"].toIntArray())
+ blackhole.consume(ref["myMap"]["cool"].toString())
+ blackhole.consume(ref["invalid_key"].isNull)
+ }
+
+ @Benchmark
+ fun mapJava(blackhole: Blackhole) {
+ val jBuilder = com.google.flatbuffers.FlexBuffersBuilder(ArrayReadWriteBuf(initialCapacity), BUILDER_FLAG_SHARE_ALL)
+ val startMap = jBuilder.startMap()
+ jBuilder.putString("hello", "world")
+ jBuilder.putInt("int", 10)
+ jBuilder.putFloat("float", 12.3)
+
+ val startVec = jBuilder.startVector()
+ bigIntArray.forEach { jBuilder.putInt(it) }
+ jBuilder.endVector("intarray", startVec, true, false)
+
+ val startInnerMap = jBuilder.startMap()
+ jBuilder.putString("cool", "beans")
+ jBuilder.endMap("myMap", startInnerMap)
+
+ jBuilder.endMap(null, startMap)
+ val ref = FlexBuffers.getRoot(jBuilder.finish())
+ val map = ref.asMap()
+ blackhole.consume(map.size())
+ blackhole.consume(map.get("hello").toString())
+ blackhole.consume(map.get("int").asInt())
+ blackhole.consume(map.get("float").asFloat())
+ val vec = map.get("intarray").asVector()
+ blackhole.consume(IntArray(vec.size()) { vec.get(it).asInt() })
+
+ blackhole.consume(ref.asMap()["myMap"].asMap()["cool"].toString())
+ blackhole.consume(ref.asMap()["invalid_key"].isNull)
+ }
+
+ @Benchmark
+ fun intArrayKotlin(blackhole: Blackhole) {
+ val kBuilder = FlexBuffersBuilder(initialCapacity, FlexBuffersBuilder.SHARE_KEYS_AND_STRINGS)
+ kBuilder.put(bigIntArray)
+ val root = getRoot(kBuilder.finish())
+ blackhole.consume(root.toIntArray())
+ }
+
+ @Benchmark
+ fun intArrayJava(blackhole: Blackhole) {
+ val jBuilder = com.google.flatbuffers.FlexBuffersBuilder(ArrayReadWriteBuf(initialCapacity), BUILDER_FLAG_SHARE_ALL)
+ val v = jBuilder.startVector()
+ bigIntArray.forEach { jBuilder.putInt(it) }
+ jBuilder.endVector(null, v, true, false)
+ jBuilder.finish()
+ val root = FlexBuffers.getRoot(jBuilder.buffer)
+ val vec = root.asVector()
+ blackhole.consume(
+ IntArray(vec.size()) {
+ vec[it].asInt()
+ }
+ )
+ }
+
+ @Benchmark
+ fun stringArrayKotlin(blackhole: Blackhole) {
+ val kBuilder = FlexBuffersBuilder(initialCapacity, FlexBuffersBuilder.SHARE_KEYS_AND_STRINGS)
+ kBuilder.putVector { stringValue.forEach { kBuilder.put(it) } }
+ kBuilder.finish()
+ val root = getRoot(kBuilder.buffer)
+ val vec = root.toVector()
+ blackhole.consume(Array(vec.size) { vec[it].toString() })
+ }
+
+ @Benchmark
+ fun stringArrayJava(blackhole: Blackhole) {
+ val jBuilder = com.google.flatbuffers.FlexBuffersBuilder(ArrayReadWriteBuf(initialCapacity), BUILDER_FLAG_SHARE_ALL)
+ val v = jBuilder.startVector()
+ stringValue.forEach { jBuilder.putString(it) }
+ jBuilder.endVector(null, v, false, false)
+ jBuilder.finish()
+ val root = FlexBuffers.getRoot(jBuilder.buffer)
+ val vec = root.asVector()
+ blackhole.consume(Array(vec.size()) { vec[it].toString() })
+ }
+
+ @Benchmark
+ fun stringMapKotlin(blackhole: Blackhole) {
+ val kBuilder = FlexBuffersBuilder(initialCapacity, FlexBuffersBuilder.SHARE_KEYS_AND_STRINGS)
+ val pos = kBuilder.startMap()
+ for (i in stringKey.indices) {
+ kBuilder[stringKey[i]] = stringValue[i]
+ }
+ kBuilder.endMap(pos)
+ val ref = getRoot(kBuilder.finish())
+ val map = ref.toMap()
+ val keys = map.keys
+
+ for (key in keys) {
+ blackhole.consume(map[key.toString()].toString())
+ }
+ }
+
+ @Benchmark
+ fun stringMapBytIndexKotlin(blackhole: Blackhole) {
+ val kBuilder = FlexBuffersBuilder(initialCapacity, FlexBuffersBuilder.SHARE_KEYS_AND_STRINGS)
+ val pos = kBuilder.startMap()
+ for (i in stringKey.indices) {
+ kBuilder[stringKey[i]] = stringValue[i]
+ }
+ kBuilder.endMap(pos)
+ val ref = getRoot(kBuilder.finish())
+ val map = ref.toMap()
+ for (index in 0 until map.size) {
+ blackhole.consume(map[index].toString())
+ }
+ }
+
+ @Benchmark
+ fun stringMapJava(blackhole: Blackhole) {
+ val jBuilder = com.google.flatbuffers.FlexBuffersBuilder(ArrayReadWriteBuf(initialCapacity), BUILDER_FLAG_SHARE_ALL)
+ val v = jBuilder.startMap()
+ for (i in stringKey.indices) {
+ jBuilder.putString(stringKey[i], stringValue[i])
+ }
+ jBuilder.endMap(null, v)
+ val ref = FlexBuffers.getRoot(jBuilder.finish())
+ val map = ref.asMap()
+ val keyVec = map.keys()
+ for (i in 0 until keyVec.size()) {
+ val s = keyVec[i].toString()
+ blackhole.consume(map[s].toString())
+ }
+ }
+}
diff --git a/kotlin/benchmark/src/jvmMain/kotlin/com/google/flatbuffers/kotlin/benchmark/JsonBenchmark.kt b/kotlin/benchmark/src/jvmMain/kotlin/com/google/flatbuffers/kotlin/benchmark/JsonBenchmark.kt
new file mode 100644
index 0000000..7d2ae50
--- /dev/null
+++ b/kotlin/benchmark/src/jvmMain/kotlin/com/google/flatbuffers/kotlin/benchmark/JsonBenchmark.kt
@@ -0,0 +1,121 @@
+/*
+ * Copyright 2021 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.
+ */
+package com.google.flatbuffers.kotlin.benchmark
+
+import com.google.flatbuffers.kotlin.ArrayReadBuffer
+import com.google.flatbuffers.kotlin.JSONParser
+import com.google.flatbuffers.kotlin.Reference
+import com.google.flatbuffers.kotlin.toJson
+import com.google.gson.Gson
+import com.google.gson.JsonObject
+import com.google.gson.JsonParser
+import com.squareup.moshi.Moshi
+import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
+import kotlinx.benchmark.Blackhole
+import okio.Buffer
+import org.openjdk.jmh.annotations.Benchmark
+import org.openjdk.jmh.annotations.BenchmarkMode
+import org.openjdk.jmh.annotations.Measurement
+import org.openjdk.jmh.annotations.Mode
+import org.openjdk.jmh.annotations.OutputTimeUnit
+import org.openjdk.jmh.annotations.Scope
+import org.openjdk.jmh.annotations.State
+import java.io.ByteArrayInputStream
+import java.io.InputStreamReader
+import java.util.concurrent.TimeUnit
+
+@State(Scope.Benchmark)
+@BenchmarkMode(Mode.AverageTime)
+@OutputTimeUnit(TimeUnit.MICROSECONDS)
+@Measurement(iterations = 100, time = 1, timeUnit = TimeUnit.MICROSECONDS)
+class JsonBenchmark {
+
+ final val moshi = Moshi.Builder()
+ .addLast(KotlinJsonAdapterFactory())
+ .build()
+ final val moshiAdapter = moshi.adapter(Map::class.java)
+
+ final val gson = Gson()
+ final val gsonParser = JsonParser()
+
+ val fbParser = JSONParser()
+
+ final val twitterData = this.javaClass.classLoader.getResourceAsStream("twitter.json")!!.readBytes()
+ final val canadaData = this.javaClass.classLoader.getResourceAsStream("canada.json")!!.readBytes()
+ final val citmData = this.javaClass.classLoader.getResourceAsStream("citm_catalog.json")!!.readBytes()
+
+ val fbCitmRef = JSONParser().parse(ArrayReadBuffer(citmData))
+ val moshiCitmRef = moshi.adapter(Map::class.java).fromJson(citmData.decodeToString())
+ val gsonCitmRef = gsonParser.parse(citmData.decodeToString())
+
+ fun readFlexBuffers(data: ByteArray): Reference = fbParser.parse(ArrayReadBuffer(data))
+
+ fun readMoshi(data: ByteArray): Map<*, *>? {
+ val buffer = Buffer().write(data)
+ return moshiAdapter.fromJson(buffer)
+ }
+
+ fun readGson(data: ByteArray): JsonObject {
+ val parser = JsonParser()
+ val jsonReader = InputStreamReader(ByteArrayInputStream(data))
+ return parser.parse(jsonReader).asJsonObject
+ }
+
+ // TWITTER
+ @Benchmark
+ fun readTwitterFlexBuffers(hole: Blackhole? = null) = hole?.consume(readFlexBuffers(twitterData))
+ @Benchmark
+ fun readTwitterMoshi(hole: Blackhole?) = hole?.consume(readMoshi(twitterData))
+ @Benchmark
+ fun readTwitterGson(hole: Blackhole?) = hole?.consume(readGson(twitterData))
+
+ @Benchmark
+ fun roundTripTwitterFlexBuffers(hole: Blackhole? = null) = hole?.consume(readFlexBuffers(twitterData).toJson())
+ @Benchmark
+ fun roundTripTwitterMoshi(hole: Blackhole?) = hole?.consume(moshiAdapter.toJson(readMoshi(twitterData)))
+ @Benchmark
+ fun roundTripTwitterGson(hole: Blackhole?) = hole?.consume(gson.toJson(readGson(twitterData)))
+
+ // CITM
+ @Benchmark
+ fun readCITMFlexBuffers(hole: Blackhole? = null) = hole?.consume(readFlexBuffers(citmData))
+ @Benchmark
+ fun readCITMMoshi(hole: Blackhole?) = hole?.consume(moshiAdapter.toJson(readMoshi(citmData)))
+ @Benchmark
+ fun readCITMGson(hole: Blackhole?) = hole?.consume(gson.toJson(readGson(citmData)))
+
+ @Benchmark
+ fun roundTripCITMFlexBuffers(hole: Blackhole? = null) = hole?.consume(readFlexBuffers(citmData).toJson())
+ @Benchmark
+ fun roundTripCITMMoshi(hole: Blackhole?) = hole?.consume(moshiAdapter.toJson(readMoshi(citmData)))
+ @Benchmark
+ fun roundTripCITMGson(hole: Blackhole?) = hole?.consume(gson.toJson(readGson(citmData)))
+
+ @Benchmark
+ fun writeCITMFlexBuffers(hole: Blackhole? = null) = hole?.consume(fbCitmRef.toJson())
+ @Benchmark
+ fun writeCITMMoshi(hole: Blackhole?) = hole?.consume(moshiAdapter.toJson(moshiCitmRef))
+ @Benchmark
+ fun writeCITMGson(hole: Blackhole?) = hole?.consume(gson.toJson(gsonCitmRef))
+
+ // CANADA
+ @Benchmark
+ fun readCanadaFlexBuffers(hole: Blackhole? = null) = hole?.consume(readFlexBuffers(canadaData))
+ @Benchmark
+ fun readCanadaMoshi(hole: Blackhole?) = hole?.consume(readMoshi(canadaData))
+ @Benchmark
+ fun readCanadaGson(hole: Blackhole?) = hole?.consume(readGson(canadaData))
+}
diff --git a/kotlin/benchmark/src/jvmMain/kotlin/com/google/flatbuffers/kotlin/benchmark/UTF8Benchmark.kt b/kotlin/benchmark/src/jvmMain/kotlin/com/google/flatbuffers/kotlin/benchmark/UTF8Benchmark.kt
new file mode 100644
index 0000000..6fa2882
--- /dev/null
+++ b/kotlin/benchmark/src/jvmMain/kotlin/com/google/flatbuffers/kotlin/benchmark/UTF8Benchmark.kt
@@ -0,0 +1,235 @@
+/*
+ * Copyright 2021 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.
+ */
+package com.google.flatbuffers.kotlin.benchmark
+
+import com.google.flatbuffers.kotlin.ArrayReadWriteBuffer
+import com.google.flatbuffers.kotlin.Key
+import com.google.flatbuffers.kotlin.Utf8
+import kotlinx.benchmark.Blackhole
+import org.openjdk.jmh.annotations.Benchmark
+import org.openjdk.jmh.annotations.BenchmarkMode
+import org.openjdk.jmh.annotations.Measurement
+import org.openjdk.jmh.annotations.Mode
+import org.openjdk.jmh.annotations.OutputTimeUnit
+import org.openjdk.jmh.annotations.Scope
+import org.openjdk.jmh.annotations.Setup
+import org.openjdk.jmh.annotations.State
+import java.nio.ByteBuffer
+import java.util.concurrent.TimeUnit
+import kotlin.random.Random
+
+@State(Scope.Benchmark)
+@BenchmarkMode(Mode.AverageTime)
+@OutputTimeUnit(TimeUnit.MICROSECONDS)
+@Measurement(iterations = 100, time = 1, timeUnit = TimeUnit.MICROSECONDS)
+class UTF8Benchmark {
+
+ private final val sampleSize = 5000
+ private final val stringSize = 25
+ final var sampleSmallUtf8 = (0..sampleSize).map { populateUTF8(stringSize) }.toList()
+ final var sampleSmallUtf8Decoded = sampleSmallUtf8.map { it.encodeToByteArray() }.toList()
+ final var sampleSmallAscii = (0..sampleSize).map { populateAscii(stringSize) }.toList()
+ final var sampleSmallAsciiDecoded = sampleSmallAscii.map { it.encodeToByteArray() }.toList()
+
+ @Setup
+ fun setUp() {
+ }
+
+ @Benchmark
+ fun encodeUtf8KotlinStandard(blackhole: Blackhole) {
+ for (i in sampleSmallUtf8) {
+ blackhole.consume(i.encodeToByteArray())
+ }
+ }
+ @Benchmark
+ fun encodeUtf8KotlinFlatbuffers(blackhole: Blackhole) {
+ for (i in sampleSmallUtf8) {
+ val byteArray = ByteArray((i.length * 4))
+ blackhole.consume(Utf8.encodeUtf8Array(i, byteArray, 0, byteArray.size))
+ }
+ }
+ @Benchmark
+ fun encodeUtf8JavaFlatbuffers(blackhole: Blackhole) {
+ val javaUtf8 = com.google.flatbuffers.Utf8.getDefault()
+ for (i in sampleSmallUtf8) {
+ val byteBuffer = ByteBuffer.wrap(ByteArray(i.length * 4))
+ blackhole.consume(javaUtf8.encodeUtf8(i, byteBuffer))
+ }
+ }
+
+ @Benchmark
+ fun decodeUtf8KotlinStandard(blackhole: Blackhole) {
+ for (ary in sampleSmallUtf8Decoded) {
+ blackhole.consume(ary.decodeToString())
+ }
+ }
+
+ @Benchmark
+ fun decodeUtf8KotlinFlatbuffers(blackhole: Blackhole) {
+ for (ary in sampleSmallUtf8Decoded) {
+ blackhole.consume(Utf8.decodeUtf8Array(ary, 0, ary.size))
+ }
+ }
+
+ @Benchmark
+ fun decodeUtf8JavaFlatbuffers(blackhole: Blackhole) {
+ val javaUtf8 = com.google.flatbuffers.Utf8.getDefault()
+ for (ary in sampleSmallUtf8Decoded) {
+ val byteBuffer = ByteBuffer.wrap(ary)
+ blackhole.consume(javaUtf8.decodeUtf8(byteBuffer, 0, ary.size))
+ }
+ }
+
+ // ASCII TESTS
+
+ @Benchmark
+ fun encodeAsciiKotlinStandard(blackhole: Blackhole) {
+ for (i in sampleSmallAscii) {
+ blackhole.consume(i.encodeToByteArray())
+ }
+ }
+ @Benchmark
+ fun encodeAsciiKotlinFlatbuffers(blackhole: Blackhole) {
+ for (i in sampleSmallAscii) {
+ val byteArray = ByteArray(i.length) // Utf8.encodedLength(i))
+ blackhole.consume(Utf8.encodeUtf8Array(i, byteArray, 0, byteArray.size))
+ }
+ }
+ @Benchmark
+ fun encodeAsciiJavaFlatbuffers(blackhole: Blackhole) {
+ val javaUtf8 = com.google.flatbuffers.Utf8.getDefault()
+ for (i in sampleSmallAscii) {
+ val byteBuffer = ByteBuffer.wrap(ByteArray(i.length))
+ blackhole.consume(javaUtf8.encodeUtf8(i, byteBuffer))
+ }
+ }
+
+ @Benchmark
+ fun decodeAsciiKotlinStandard(blackhole: Blackhole) {
+
+ for (ary in sampleSmallAsciiDecoded) {
+ String(ary)
+ blackhole.consume(ary.decodeToString())
+ }
+ }
+
+ @Benchmark
+ fun decodeAsciiKotlinFlatbuffers(blackhole: Blackhole) {
+ for (ary in sampleSmallAsciiDecoded) {
+ blackhole.consume(Utf8.decodeUtf8Array(ary, 0, ary.size))
+ }
+ }
+
+ @Benchmark
+ fun decodeAsciiJavaFlatbuffers(blackhole: Blackhole) {
+ val javaUtf8 = com.google.flatbuffers.Utf8.getDefault()
+ for (ary in sampleSmallAsciiDecoded) {
+ val byteBuffer = ByteBuffer.wrap(ary)
+ blackhole.consume(javaUtf8.decodeUtf8(byteBuffer, 0, ary.size))
+ }
+ }
+
+ @Benchmark
+ fun readAllCharsString(blackhole: Blackhole) {
+ for (ary in sampleSmallAsciiDecoded) {
+ val key = Utf8.decodeUtf8Array(ary, 0, ary.size)
+ for (i in key.indices) {
+ blackhole.consume(key[i])
+ }
+ }
+ }
+
+ @Benchmark
+ fun readAllCharsCharSequence(blackhole: Blackhole) {
+ for (ary in sampleSmallAsciiDecoded) {
+ val key = Key(ArrayReadWriteBuffer(ary), 0, ary.size)
+ for (i in 0 until key.sizeInChars) {
+ blackhole.consume(key[i])
+ }
+ }
+ }
+
+ fun populateAscii(size: Int): String {
+ val data = ByteArray(size)
+ for (i in data.indices) {
+ data[i] = Random.nextInt(0, 127).toByte()
+ }
+
+ return String(data, 0, data.size)
+ }
+
+ // generate a string having at least length N
+ // can exceed by up to 3 chars, returns the actual length
+ fun populateUTF8(size: Int): String {
+ val data = ByteArray(size + 3)
+ var i = 0
+ while (i < size) {
+ val w = Random.nextInt() and 0xFF
+ when {
+ w < 0x80 -> data[i++] = 0x20; // w;
+ w < 0xE0 -> {
+ data[i++] = (0xC2 + Random.nextInt() % (0xDF - 0xC2 + 1)).toByte()
+ data[i++] = (0x80 + Random.nextInt() % (0xBF - 0x80 + 1)).toByte()
+ }
+ w == 0xE0 -> {
+ data[i++] = w.toByte()
+ data[i++] = (0xA0 + Random.nextInt() % (0xBF - 0xA0 + 1)).toByte()
+ data[i++] = (0x80 + Random.nextInt() % (0xBF - 0x80 + 1)).toByte()
+ }
+ w <= 0xEC -> {
+ data[i++] = w.toByte()
+ data[i++] = (0x80 + Random.nextInt() % (0xBF - 0x80 + 1)).toByte()
+ data[i++] = (0x80 + Random.nextInt() % (0xBF - 0x80 + 1)).toByte()
+ }
+ w == 0xED -> {
+ data[i++] = w.toByte()
+ data[i++] = (0x80 + Random.nextInt() % (0x9F - 0x80 + 1)).toByte()
+ data[i++] = (0x80 + Random.nextInt() % (0xBF - 0x80 + 1)).toByte()
+ }
+ w <= 0xEF -> {
+ data[i++] = w.toByte()
+ data[i++] = (0x80 + Random.nextInt() % (0xBF - 0x80 + 1)).toByte()
+ data[i++] = (0x80 + Random.nextInt() % (0xBF - 0x80 + 1)).toByte()
+ }
+ w < 0xF0 -> {
+ data[i++] = (0xF1 + Random.nextInt() % (0xF3 - 0xF1 + 1)).toByte()
+ data[i++] = (0x80 + Random.nextInt() % (0xBF - 0x80 + 1)).toByte()
+ data[i++] = (0x80 + Random.nextInt() % (0xBF - 0x80 + 1)).toByte()
+ data[i++] = (0x80 + Random.nextInt() % (0xBF - 0x80 + 1)).toByte()
+ }
+ w == 0xF0 -> {
+ data[i++] = w.toByte()
+ data[i++] = (0x90 + Random.nextInt() % (0xBF - 0x90 + 1)).toByte()
+ data[i++] = (0x80 + Random.nextInt() % (0xBF - 0x80 + 1)).toByte()
+ data[i++] = (0x80 + Random.nextInt() % (0xBF - 0x80 + 1)).toByte()
+ }
+ w <= 0xF3 -> {
+ data[i++] = (0xF1 + Random.nextInt() % (0xF3 - 0xF1 + 1)).toByte()
+ data[i++] = (0x80 + Random.nextInt() % (0xBF - 0x80 + 1)).toByte()
+ data[i++] = (0x80 + Random.nextInt() % (0xBF - 0x80 + 1)).toByte()
+ data[i++] = (0x80 + Random.nextInt() % (0xBF - 0x80 + 1)).toByte()
+ }
+ w == 0xF4 -> {
+ data[i++] = w.toByte()
+ data[i++] = (0x80 + Random.nextInt() % (0x8F - 0x80 + 1)).toByte()
+ data[i++] = (0x80 + Random.nextInt() % (0xBF - 0x80 + 1)).toByte()
+ data[i++] = (0x80 + Random.nextInt() % (0xBF - 0x80 + 1)).toByte()
+ }
+ }
+ }
+ return String(data, 0, i)
+ }
+}
diff --git a/kotlin/build.gradle.kts b/kotlin/build.gradle.kts
new file mode 100644
index 0000000..455ee0d
--- /dev/null
+++ b/kotlin/build.gradle.kts
@@ -0,0 +1,40 @@
+plugins {
+ id("com.diffplug.spotless") version "5.8.2"
+}
+
+group = "com.google.flatbuffers"
+version = "2.0.0-SNAPSHOT"
+
+subprojects {
+
+ repositories {
+ maven { setUrl("https://plugins.gradle.org/m2/") }
+ mavenCentral()
+ }
+}
+
+buildscript {
+ repositories {
+ maven { setUrl("https://plugins.gradle.org/m2/") }
+ gradlePluginPortal()
+ mavenCentral()
+ }
+}
+
+// plugin used to enforce code style
+spotless {
+ val klintConfig = mapOf("indent_size" to "2", "continuation_indent_size" to "2")
+ kotlin {
+ target("**/*.kt")
+ ktlint("0.40.0").userData(klintConfig)
+ trimTrailingWhitespace()
+ indentWithSpaces()
+ endWithNewline()
+ licenseHeaderFile("$rootDir/spotless/spotless.kt").updateYearWithLatest(false)
+ targetExclude("**/spotless.kt", "**/build/**")
+ }
+ kotlinGradle {
+ target("*.gradle.kts")
+ ktlint().userData(klintConfig)
+ }
+}
diff --git a/kotlin/flatbuffers-kotlin/build.gradle.kts b/kotlin/flatbuffers-kotlin/build.gradle.kts
new file mode 100644
index 0000000..b74807e
--- /dev/null
+++ b/kotlin/flatbuffers-kotlin/build.gradle.kts
@@ -0,0 +1,97 @@
+plugins {
+ kotlin("multiplatform") version "1.4.20"
+}
+
+group = "com.google.flatbuffers.kotlin"
+version = "2.0.0-SNAPSHOT"
+
+kotlin {
+ explicitApi()
+ jvm()
+ js {
+ browser {
+ binaries.executable()
+ testTask {
+ useKarma {
+ useChromeHeadless()
+ }
+ }
+ }
+ }
+ macosX64()
+ iosArm32()
+ iosArm64()
+ iosX64()
+
+ sourceSets {
+ val commonMain by getting {
+ dependencies {
+ implementation(kotlin("stdlib-common"))
+ }
+ }
+
+ val commonTest by getting {
+ dependencies {
+ implementation(kotlin("test-common"))
+ implementation(kotlin("test-annotations-common"))
+ }
+ }
+ val jvmTest by getting {
+ dependencies {
+ implementation(kotlin("test-junit"))
+ }
+ }
+ val jvmMain by getting {
+ kotlin.srcDir("java")
+ dependencies {
+ implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.4.1")
+ }
+ }
+
+ val jsMain by getting {
+ dependsOn(commonMain)
+ }
+ val jsTest by getting {
+ dependsOn(commonTest)
+ dependencies {
+ implementation(kotlin("test-js"))
+ }
+ }
+ val nativeMain by creating {
+ dependsOn(commonMain)
+ }
+ val nativeTest by creating {
+ dependsOn(commonMain)
+ }
+ val macosX64Main by getting {
+ dependsOn(nativeMain)
+ }
+
+ val iosArm32Main by getting {
+ dependsOn(nativeMain)
+ }
+ val iosArm64Main by getting {
+ dependsOn(nativeMain)
+ }
+ val iosX64Main by getting {
+ dependsOn(nativeMain)
+ }
+
+ all {
+ languageSettings.enableLanguageFeature("InlineClasses")
+ languageSettings.useExperimentalAnnotation("kotlin.ExperimentalUnsignedTypes")
+ }
+ }
+
+ /* Targets configuration omitted.
+ * To find out how to configure the targets, please follow the link:
+ * https://kotlinlang.org/docs/reference/building-mpp-with-gradle.html#setting-up-targets */
+ targets {
+ targetFromPreset(presets.getAt("jvm"))
+ targetFromPreset(presets.getAt("js"))
+ targetFromPreset(presets.getAt("macosX64"))
+ targetFromPreset(presets.getAt("iosArm32"))
+ targetFromPreset(presets.getAt("iosArm64"))
+ targetFromPreset(presets.getAt("iosX64"))
+ }
+}
diff --git a/kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/Buffers.kt b/kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/Buffers.kt
new file mode 100644
index 0000000..9851d90
--- /dev/null
+++ b/kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/Buffers.kt
@@ -0,0 +1,489 @@
+/*
+ * Copyright 2021 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.
+ */
+package com.google.flatbuffers.kotlin
+
+import kotlin.math.max
+import kotlin.math.min
+
+/**
+ * Represent a chunk of data, where FlexBuffers will be read from.
+ */
+public interface ReadBuffer {
+
+ /**
+ * Scan through the buffer for first byte matching value.
+ * @param value to be match
+ * @param start inclusive initial position to start searching
+ * @param end exclusive final position of the search
+ * @return position of a match or -1
+ */
+ public fun findFirst(value: Byte, start: Int, end: Int = limit): Int
+
+ /**
+ * Read boolean from the buffer. Booleans as stored as a single byte
+ * @param index position of the element in [ReadBuffer]
+ * @return [Boolean] element
+ */
+ public fun getBoolean(index: Int): Boolean
+
+ /**
+ * Read a [Byte] from the buffer.
+ * @param index position of the element in [ReadBuffer]
+ * @return a byte
+ */
+ public operator fun get(index: Int): Byte
+
+ /**
+ * Read a [UByte] from the buffer.
+ * @param index position of the element in [ReadBuffer]
+ * @return a [UByte]
+ */
+ public fun getUByte(index: Int): UByte
+
+ /**
+ * Read a [Short] from the buffer.
+ * @param index position of the element in [ReadBuffer]
+ * @return a [Short]
+ */
+ public fun getShort(index: Int): Short
+
+ /**
+ * Read a [UShort] from the buffer.
+ * @param index position of the element in [ReadBuffer]
+ * @return a [UShort]
+ */
+ public fun getUShort(index: Int): UShort
+
+ /**
+ * Read a [Int] from the buffer.
+ * @param index position of the element in [ReadBuffer]
+ * @return an [Int]
+ */
+ public fun getInt(index: Int): Int
+
+ /**
+ * Read a [UInt] from the buffer.
+ * @param index position of the element in [ReadBuffer]
+ * @return an [UInt]
+ */
+ public fun getUInt(index: Int): UInt
+
+ /**
+ * Read a [Long] from the buffer.
+ * @param index position of the element in [ReadBuffer]
+ * @return a [Long]
+ */
+ public fun getLong(index: Int): Long
+
+ /**
+ * Read a [ULong] from the buffer.
+ * @param index position of the element in [ReadBuffer]
+ * @return a [ULong]
+ */
+ public fun getULong(index: Int): ULong
+
+ /**
+ * Read a 32-bit float from the buffer.
+ * @param index position of the element in [ReadBuffer]
+ * @return a float
+ */
+ public fun getFloat(index: Int): Float
+
+ /**
+ * Read a 64-bit float from the buffer.
+ * @param index position of the element in [ReadBuffer]
+ * @return a double
+ */
+ public fun getDouble(index: Int): Double
+
+ /**
+ * Read an UTF-8 string from the buffer.
+ * @param start initial element of the string
+ * @param size size of the string in bytes.
+ * @return a `String`
+ */
+ public fun getString(start: Int, size: Int): String
+
+ /**
+ * Expose [ReadBuffer] as an array of bytes.
+ * This method is meant to be as efficient as possible, so for a array-backed [ReadBuffer], it should
+ * return its own internal data. In case access to internal data is not possible,
+ * a copy of the data into an array of bytes might occur.
+ * @return [ReadBuffer] as an array of bytes
+ */
+ public fun data(): ByteArray
+
+ /**
+ * Creates a new [ReadBuffer] point to a region of the current buffer, starting at [start] with size [size].
+ * @param start starting position of the [ReadBuffer]
+ * @param size in bytes of the [ReadBuffer]
+ * @return [ReadBuffer] slice.
+ */
+ public fun slice(start: Int, size: Int): ReadBuffer
+
+ /**
+ * Defines the size of the message in the buffer. It also determines last position that buffer
+ * can be read. Last byte to be accessed is in position `limit() -1`.
+ * @return indicate last position
+ */
+ public val limit: Int
+}
+
+/**
+ * Interface to represent a read-write buffers. This interface will be used to access and write FlexBuffer messages.
+ */
+public interface ReadWriteBuffer : ReadBuffer {
+ /**
+ * Clears (resets) the buffer so that it can be reused. Write position will be set to the start.
+ */
+ public fun clear()
+
+ /**
+ * Put a [Boolean] into the buffer at [writePosition] . Booleans as stored as single byte.
+ * Write position will be incremented.
+ * @return [Boolean] element
+ */
+ public fun put(value: Boolean)
+
+ /**
+ * Put an array of bytes into the buffer at [writePosition]. Write position will be incremented.
+ * @param value the data to be copied
+ * @param start initial position on value to be copied
+ * @param length amount of bytes to be copied
+ */
+ public fun put(value: ByteArray, start: Int, length: Int)
+
+ /**
+ * Write a [Byte] into the buffer at [writePosition]. Write position will be incremented.
+ */
+ public fun put(value: Byte)
+
+ /**
+ * Write a [UByte] into the buffer at [writePosition]. Write position will be incremented.
+ */
+ public fun put(value: UByte)
+
+ /**
+ * Write a [Short] into in the buffer at [writePosition]. Write position will be incremented.
+ */
+ public fun put(value: Short)
+
+ /**
+ * Writea [UShort] into in the buffer at [writePosition]. Write position will be incremented.
+ */
+ public fun put(value: UShort)
+
+ /**
+ * Write a [Int] in the buffer at [writePosition]. Write position will be incremented.
+ */
+ public fun put(value: Int)
+
+ /**
+ * Write a [UInt] into in the buffer at [writePosition]. Write position will be incremented.
+ */
+ public fun put(value: UInt)
+
+ /**
+ * Write a [Long] into in the buffer at [writePosition]. Write position will be
+ * incremented.
+ */
+ public fun put(value: Long)
+
+ /**
+ * Write a [ULong] into in the buffer at [writePosition]. Write position will be
+ * incremented.
+ */
+ public fun put(value: ULong)
+
+ /**
+ * Write a 32-bit [Float] into the buffer at [writePosition]. Write position will be
+ * incremented.
+ */
+ public fun put(value: Float)
+
+ /**
+ * Write a 64-bit [Double] into the buffer at [writePosition]. Write position will be
+ * incremented.
+ */
+ public fun put(value: Double)
+
+ /**
+ * Write a [String] encoded as UTF-8 into the buffer at [writePosition]. Write position will be incremented.
+ * @return size in bytes of the encoded string
+ */
+ public fun put(value: String, encodedLength: Int = -1): Int
+
+ /**
+ * Write an array of bytes into the buffer.
+ * @param dstIndex initial position where [src] will be copied into.
+ * @param src the data to be copied.
+ * @param srcStart initial position on [src] that will be copied.
+ * @param srcLength amount of bytes to be copied
+ */
+ public operator fun set(dstIndex: Int, src: ByteArray, srcStart: Int, srcLength: Int)
+
+ /**
+ * Write [Boolean] into a given position [index] on the buffer. Booleans as stored as single byte.
+ * @param index position of the element in buffer
+ */
+ public operator fun set(index: Int, value: Boolean)
+
+ /**
+ * Write [Byte] into a given position [index] on the buffer.
+ * @param index position of the element in the buffer
+ */
+ public operator fun set(index: Int, value: Byte)
+
+ /**
+ * Write [UByte] into a given position [index] on the buffer.
+ * @param index position of the element in the buffer
+ */
+ public operator fun set(index: Int, value: UByte)
+
+ /**
+ Short
+ * @param index position of the element in [ReadBuffer]
+ */
+ public fun set(index: Int, value: Short)
+
+ /**
+ * Write [UShort] into a given position [index] on the buffer.
+ * @param index position of the element in [ReadBuffer]
+ */
+ public fun set(index: Int, value: UShort)
+
+ /**
+ * Write [Int] into a given position [index] on the buffer.
+ * @param index position of the element in [ReadBuffer]
+ */
+ public fun set(index: Int, value: Int)
+
+ /**
+ * Write [UInt] into a given position [index] on the buffer.
+ * @param index position of the element in [ReadBuffer]
+ */
+ public fun set(index: Int, value: UInt)
+
+ /**
+ * Write [Long] into a given position [index] on the buffer.
+ * @param index position of the element in [ReadBuffer]
+ */
+ public fun set(index: Int, value: Long)
+
+ /**
+ * Write [ULong] into a given position [index] on the buffer.
+ * @param index position of the element in [ReadBuffer]
+ */
+ public fun set(index: Int, value: ULong)
+
+ /**
+ * Write [Float] into a given position [index] on the buffer.
+ * @param index position of the element in [ReadBuffer]
+ */
+ public fun set(index: Int, value: Float)
+
+ /**
+ * Write [Double] into a given position [index] on the buffer.
+ * @param index position of the element in [ReadBuffer]
+ */
+ public fun set(index: Int, value: Double)
+
+ /**
+ * Current position of the buffer to be written. It will be automatically updated on [put] operations.
+ */
+ public var writePosition: Int
+
+ /**
+ * Defines the size of the message in the buffer. It also determines last position that buffer
+ * can be read or write. Last byte to be accessed is in position `limit() -1`.
+ * @return indicate last position
+ */
+ override val limit: Int
+
+ /**
+ * Request capacity of the buffer. In case buffer is already larger
+ * than the requested, this method will just return true. Otherwise
+ * It might try to resize the buffer. In case of being unable to allocate
+ * enough memory, an exception will be thrown.
+ */
+ public fun requestCapacity(capacity: Int)
+}
+
+public open class ArrayReadBuffer(protected var buffer: ByteArray, override val limit: Int = buffer.size) : ReadBuffer {
+
+ override fun findFirst(value: Byte, start: Int, end: Int): Int {
+ val e = min(end, limit)
+ val s = max(0, start)
+ for (i in s until e) if (buffer[i] == value) return i
+ return -1
+ }
+
+ override fun getBoolean(index: Int): Boolean = buffer[index] != 0.toByte()
+
+ override operator fun get(index: Int): Byte = buffer[index]
+
+ override fun getUByte(index: Int): UByte = buffer.getUByte(index)
+
+ override fun getShort(index: Int): Short = buffer.getShort(index)
+
+ override fun getUShort(index: Int): UShort = buffer.getUShort(index)
+
+ override fun getInt(index: Int): Int = buffer.getInt(index)
+
+ override fun getUInt(index: Int): UInt = buffer.getUInt(index)
+
+ override fun getLong(index: Int): Long = buffer.getLong(index)
+
+ override fun getULong(index: Int): ULong = buffer.getULong(index)
+
+ override fun getFloat(index: Int): Float = buffer.getFloat(index)
+
+ override fun getDouble(index: Int): Double = buffer.getDouble(index)
+
+ override fun getString(start: Int, size: Int): String = buffer.decodeToString(start, start + size)
+
+ override fun data(): ByteArray = buffer
+
+ override fun slice(start: Int, size: Int): ReadBuffer = ArrayReadBuffer(buffer, limit)
+}
+/**
+ * Implements `[ReadWriteBuffer]` using [ByteArray] as backing buffer. Using array of bytes are
+ * usually faster than `ByteBuffer`.
+ *
+ * This class is not thread-safe, meaning that
+ * it must operate on a single thread. Operating from
+ * multiple thread leads into a undefined behavior
+ *
+ * All operations assumes Little Endian byte order.
+ */
+public class ArrayReadWriteBuffer(
+ buffer: ByteArray,
+ override var writePosition: Int = 0
+) : ArrayReadBuffer(buffer, writePosition), ReadWriteBuffer {
+
+ public constructor(initialCapacity: Int = 10) : this(ByteArray(initialCapacity))
+
+ override val limit: Int get() = writePosition
+
+ override fun clear(): Unit = run { writePosition = 0 }
+
+ override fun put(value: Boolean) {
+ set(writePosition, value)
+ writePosition++
+ }
+
+ override fun put(value: ByteArray, start: Int, length: Int) {
+ set(writePosition, value, start, length)
+ writePosition += length
+ }
+
+ override fun put(value: Byte) {
+ set(writePosition, value)
+ writePosition++
+ }
+
+ override fun put(value: UByte) {
+ set(writePosition, value)
+ writePosition++
+ }
+
+ override fun put(value: Short) {
+ set(writePosition, value)
+ writePosition += 2
+ }
+
+ override fun put(value: UShort) {
+ set(writePosition, value)
+ writePosition += 2
+ }
+
+ override fun put(value: Int) {
+ set(writePosition, value)
+ writePosition += 4
+ }
+
+ override fun put(value: UInt) {
+ set(writePosition, value)
+ writePosition += 4
+ }
+
+ override fun put(value: Long) {
+ set(writePosition, value)
+ writePosition += 8
+ }
+
+ override fun put(value: ULong) {
+ set(writePosition, value)
+ writePosition += 8
+ }
+
+ override fun put(value: Float) {
+ set(writePosition, value)
+ writePosition += 4
+ }
+
+ override fun put(value: Double) {
+ set(writePosition, value)
+ writePosition += 8
+ }
+
+ override fun put(value: String, encodedLength: Int): Int {
+ val length = if (encodedLength != -1) encodedLength else Utf8.encodedLength(value)
+ withCapacity(writePosition + length) {
+ writePosition = setString(writePosition, value)
+ }
+ return length
+ }
+
+ override fun set(index: Int, value: Boolean) {
+ set(index, if (value) 1.toByte() else 0.toByte())
+ }
+
+ override operator fun set(dstIndex: Int, src: ByteArray, srcStart: Int, srcLength: Int) {
+ withCapacity(dstIndex + (srcLength + srcStart)) {
+ src.copyInto(buffer, dstIndex, srcStart, srcStart + srcLength)
+ }
+ }
+
+ override operator fun set(index: Int, value: Byte): Unit = withCapacity(index + 1) { set(index, value) }
+ override operator fun set(index: Int, value: UByte): Unit = withCapacity(index + 1) { setUByte(index, value) }
+ override operator fun set(index: Int, value: Short): Unit = withCapacity(index + 2) { setShort(index, value) }
+ override operator fun set(index: Int, value: UShort): Unit = withCapacity(index + 2) { setUShort(index, value) }
+ override operator fun set(index: Int, value: Int): Unit = withCapacity(index + 4) { setInt(index, value) }
+ override operator fun set(index: Int, value: UInt): Unit = withCapacity(index + 4) { setUInt(index, value) }
+ override operator fun set(index: Int, value: Long): Unit = withCapacity(index + 8) { setLong(index, value) }
+ override operator fun set(index: Int, value: ULong): Unit = withCapacity(index + 8) { setULong(index, value) }
+ override operator fun set(index: Int, value: Float): Unit = withCapacity(index + 4) { setFloat(index, value) }
+ override operator fun set(index: Int, value: Double): Unit = withCapacity(index + 8) { setDouble(index, value) }
+
+ override fun requestCapacity(capacity: Int) {
+ if (capacity < 0) error("Capacity may not be negative (likely a previous int overflow)")
+
+ if (buffer.size >= capacity) return
+ // implemented in the same growing fashion as ArrayList
+ val oldCapacity = buffer.size
+ var newCapacity = oldCapacity + (oldCapacity shr 1)
+ if (newCapacity < capacity) { // Note: this also catches newCapacity int overflow
+ newCapacity = capacity
+ }
+ buffer = buffer.copyOf(newCapacity)
+ }
+
+ private inline fun withCapacity(size: Int, crossinline action: ByteArray.() -> Unit) {
+ requestCapacity(size)
+ buffer.action()
+ }
+}
diff --git a/kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/ByteArray.kt b/kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/ByteArray.kt
new file mode 100644
index 0000000..68fd0f3
--- /dev/null
+++ b/kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/ByteArray.kt
@@ -0,0 +1,146 @@
+/*
+ * Copyright 2021 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.
+ */
+@file:Suppress("NOTHING_TO_INLINE")
+package com.google.flatbuffers.kotlin
+
+import kotlin.experimental.and
+
+internal fun ByteArray.getString(index: Int, size: Int): String = Utf8.decodeUtf8Array(this, index, size)
+
+internal fun ByteArray.setString(index: Int, value: String): Int =
+ Utf8.encodeUtf8Array(value, this, index, this.size - index)
+
+// List of functions that needs to be implemented on all platforms.
+internal expect inline fun ByteArray.getUByte(index: Int): UByte
+internal expect inline fun ByteArray.getShort(index: Int): Short
+internal expect inline fun ByteArray.getUShort(index: Int): UShort
+internal expect inline fun ByteArray.getInt(index: Int): Int
+internal expect inline fun ByteArray.getUInt(index: Int): UInt
+internal expect inline fun ByteArray.getLong(index: Int): Long
+internal expect inline fun ByteArray.getULong(index: Int): ULong
+internal expect inline fun ByteArray.getFloat(index: Int): Float
+internal expect inline fun ByteArray.getDouble(index: Int): Double
+
+internal expect inline fun ByteArray.setUByte(index: Int, value: UByte)
+internal expect inline fun ByteArray.setShort(index: Int, value: Short)
+internal expect inline fun ByteArray.setUShort(index: Int, value: UShort)
+internal expect inline fun ByteArray.setInt(index: Int, value: Int)
+internal expect inline fun ByteArray.setUInt(index: Int, value: UInt)
+internal expect inline fun ByteArray.setLong(index: Int, value: Long)
+internal expect inline fun ByteArray.setULong(index: Int, value: ULong)
+internal expect inline fun ByteArray.setFloat(index: Int, value: Float)
+internal expect inline fun ByteArray.setDouble(index: Int, value: Double)
+
+/**
+ * This implementation uses Little Endian order.
+ */
+public object ByteArrayOps {
+ public inline fun getUByte(ary: ByteArray, index: Int): UByte = ary[index].toUByte()
+ public inline fun getShort(ary: ByteArray, index: Int): Short {
+ return (ary[index + 1].toInt() shl 8 or (ary[index].toInt() and 0xff)).toShort()
+ }
+
+ public inline fun getUShort(ary: ByteArray, index: Int): UShort = getShort(ary, index).toUShort()
+
+ public inline fun getInt(ary: ByteArray, index: Int): Int {
+ return (
+ (ary[index + 3].toInt() shl 24) or
+ ((ary[index + 2].toInt() and 0xff) shl 16) or
+ ((ary[index + 1].toInt() and 0xff) shl 8) or
+ ((ary[index].toInt() and 0xff))
+ )
+ }
+
+ public inline fun getUInt(ary: ByteArray, index: Int): UInt = getInt(ary, index).toUInt()
+
+ public inline fun getLong(ary: ByteArray, index: Int): Long {
+ var idx = index
+ return ary[idx++].toLong() and 0xff or
+ (ary[idx++].toLong() and 0xff shl 8) or
+ (ary[idx++].toLong() and 0xff shl 16) or
+ (ary[idx++].toLong() and 0xff shl 24) or
+ (ary[idx++].toLong() and 0xff shl 32) or
+ (ary[idx++].toLong() and 0xff shl 40) or
+ (ary[idx++].toLong() and 0xff shl 48) or
+ (ary[idx].toLong() shl 56)
+ }
+
+ public inline fun getULong(ary: ByteArray, index: Int): ULong = getLong(ary, index).toULong()
+
+ public inline fun setUByte(ary: ByteArray, index: Int, value: UByte) {
+ ary[index] = value.toByte()
+ }
+ public inline fun setShort(ary: ByteArray, index: Int, value: Short) {
+ var idx = index
+ ary[idx++] = (value and 0xff).toByte()
+ ary[idx] = (value.toInt() shr 8 and 0xff).toByte()
+ }
+
+ public inline fun setUShort(ary: ByteArray, index: Int, value: UShort): Unit = setShort(ary, index, value.toShort())
+
+ public inline fun setInt(ary: ByteArray, index: Int, value: Int) {
+ var idx = index
+ ary[idx++] = (value and 0xff).toByte()
+ ary[idx++] = (value shr 8 and 0xff).toByte()
+ ary[idx++] = (value shr 16 and 0xff).toByte()
+ ary[idx] = (value shr 24 and 0xff).toByte()
+ }
+
+ public inline fun setUInt(ary: ByteArray, index: Int, value: UInt): Unit = setInt(ary, index, value.toInt())
+
+ public inline fun setLong(ary: ByteArray, index: Int, value: Long) {
+ var idx = index
+ var i = value.toInt()
+ ary[idx++] = (i and 0xff).toByte()
+ ary[idx++] = (i shr 8 and 0xff).toByte()
+ ary[idx++] = (i shr 16 and 0xff).toByte()
+ ary[idx++] = (i shr 24 and 0xff).toByte()
+ i = (value shr 32).toInt()
+ ary[idx++] = (i and 0xff).toByte()
+ ary[idx++] = (i shr 8 and 0xff).toByte()
+ ary[idx++] = (i shr 16 and 0xff).toByte()
+ ary[idx] = (i shr 24 and 0xff).toByte()
+ }
+
+ public inline fun setULong(ary: ByteArray, index: Int, value: ULong): Unit = setLong(ary, index, value.toLong())
+
+ public inline fun setFloat(ary: ByteArray, index: Int, value: Float) {
+ var idx = index
+ val iValue: Int = value.toRawBits()
+ ary[idx++] = (iValue and 0xff).toByte()
+ ary[idx++] = (iValue shr 8 and 0xff).toByte()
+ ary[idx++] = (iValue shr 16 and 0xff).toByte()
+ ary[idx] = (iValue shr 24 and 0xff).toByte()
+ }
+
+ public inline fun setDouble(ary: ByteArray, index: Int, value: Double) {
+ var idx = index
+ val lValue: Long = value.toRawBits()
+ var i = lValue.toInt()
+ ary[idx++] = (i and 0xff).toByte()
+ ary[idx++] = (i shr 8 and 0xff).toByte()
+ ary[idx++] = (i shr 16 and 0xff).toByte()
+ ary[idx++] = (i shr 24 and 0xff).toByte()
+ i = (lValue shr 32).toInt()
+ ary[idx++] = (i and 0xff).toByte()
+ ary[idx++] = (i shr 8 and 0xff).toByte()
+ ary[idx++] = (i shr 16 and 0xff).toByte()
+ ary[idx] = (i shr 24 and 0xff).toByte()
+ }
+
+ public inline fun getFloat(ary: ByteArray, index: Int): Float = Float.fromBits(getInt(ary, index))
+ public inline fun getDouble(ary: ByteArray, index: Int): Double = Double.fromBits(getLong(ary, index))
+}
diff --git a/kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/FlexBuffers.kt b/kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/FlexBuffers.kt
new file mode 100644
index 0000000..a22dd13
--- /dev/null
+++ b/kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/FlexBuffers.kt
@@ -0,0 +1,905 @@
+/*
+ * Copyright 2021 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.
+ */
+@file:Suppress("NOTHING_TO_INLINE")
+@file:JvmName("FlexBuffers")
+package com.google.flatbuffers.kotlin
+
+import kotlin.jvm.JvmName
+
+/**
+ * Reads a FlexBuffer message in ReadBuf and returns [Reference] to
+ * the root element.
+ * @param buffer ReadBuf containing FlexBuffer message
+ * @return [Reference] to the root object
+ */
+public fun getRoot(buffer: ReadBuffer): Reference {
+ var end: Int = buffer.limit
+ val byteWidth = buffer[--end].toInt()
+ val packetType = buffer[--end].toInt()
+ end -= byteWidth // The root data item.
+ return Reference(buffer, end, ByteWidth(byteWidth), packetType)
+}
+
+/**
+ * Represents an generic element in the buffer. It can be specialized into scalar types, using for example,
+ * [Reference.toInt], or casted into Flexbuffer object types, like [Reference.toMap] or [Reference.toBlob].
+ */
+@Suppress("NOTHING_TO_INLINE")
+public class Reference internal constructor(
+ internal val buffer: ReadBuffer,
+ internal val end: Int,
+ internal val parentWidth: ByteWidth,
+ internal val byteWidth: ByteWidth,
+ internal val type: FlexBufferType
+) {
+
+ internal constructor(bb: ReadBuffer, end: Int, parentWidth: ByteWidth, packedType: Int) :
+ this(bb, end, parentWidth, ByteWidth(1 shl (packedType and 3)), FlexBufferType((packedType shr 2)))
+
+ /**
+ * Checks whether the element is null type
+ * @return true if null type
+ */
+ public val isNull: Boolean get() = type == T_NULL
+
+ /**
+ * Checks whether the element is boolean type
+ * @return true if boolean type
+ */
+ public val isBoolean: Boolean get() = type == T_BOOL
+
+ /**
+ * Checks whether the element type is numeric (signed/unsigned integers and floats)
+ * @return true if numeric type
+ */
+ public val isNumeric: Boolean get() = isIntOrUInt || isFloat
+
+ /**
+ * Checks whether the element type is signed or unsigned integers
+ * @return true if an integer type
+ */
+ public val isIntOrUInt: Boolean get() = isInt || isUInt
+
+ /**
+ * Checks whether the element type is float
+ * @return true if a float type
+ */
+ public val isFloat: Boolean get() = type == T_FLOAT || type == T_INDIRECT_FLOAT
+
+ /**
+ * Checks whether the element type is signed integer
+ * @return true if a signed integer type
+ */
+ public val isInt: Boolean get() = type == T_INT || type == T_INDIRECT_INT
+
+ /**
+ * Checks whether the element type is signed integer
+ * @return true if a signed integer type
+ */
+ public val isUInt: Boolean get() = type == T_UINT || type == T_INDIRECT_UINT
+
+ /**
+ * Checks whether the element type is string
+ * @return true if a string type
+ */
+ public val isString: Boolean get() = type == T_STRING
+
+ /**
+ * Checks whether the element type is key
+ * @return true if a key type
+ */
+ public val isKey: Boolean get() = type == T_KEY
+
+ /**
+ * Checks whether the element type is vector or a map. [TypedVector] are considered different types and will return
+ * false.
+ * @return true if a vector type
+ */
+ public val isVector: Boolean get() = type == T_VECTOR || type == T_MAP
+
+ /**
+ * Checks whether the element type is typed vector
+ * @return true if a typed vector type
+ */
+ public val isTypedVector: Boolean get() = type.isTypedVector()
+
+ /**
+ * Checks whether the element type is a map
+ * @return true if a map type
+ */
+ public val isMap: Boolean get() = type == T_MAP
+
+ /**
+ * Checks whether the element type is a blob
+ * @return true if a blob type
+ */
+ public val isBlob: Boolean get() = type == T_BLOB
+
+ /**
+ * Assumes [Reference] as a [Vector] and returns a [Reference] at index [index].
+ */
+ public operator fun get(index: Int): Reference = toVector()[index]
+
+ /**
+ * Assumes [Reference] as a [Map] and returns a [Reference] for the value at key [key].
+ */
+ public operator fun get(key: String): Reference = toMap()[key]
+
+ /**
+ * Returns element as a [Boolean].
+ * If element type is not boolean, it will be casted to integer and compared against 0
+ * @return element as [Boolean]
+ */
+ public fun toBoolean(): Boolean = if (isBoolean) buffer.getBoolean(end) else toUInt() != 0u
+
+ /**
+ * Returns element as [Byte].
+ * For vector types, it will return size of the vector.
+ * For String type, it will be parsed as integer.
+ * Unsigned elements will become signed (with possible overflow).
+ * Float elements will be casted to [Byte].
+ * @return [Byte] or 0 if fail to convert element to integer.
+ */
+ public fun toByte(): Byte = toULong().toByte()
+
+ /**
+ * Returns element as [Short].
+ * For vector types, it will return size of the vector.
+ * For String type, it will type to be parsed as integer.
+ * Unsigned elements will become signed (with possible overflow).
+ * Float elements will be casted to [Short]
+ * @return [Short] or 0 if fail to convert element to integer.
+ */
+ public fun toShort(): Short = toULong().toShort()
+
+ /**
+ * Returns element as [Int].
+ * For vector types, it will return size of the vector.
+ * For String type, it will type to be parsed as integer.
+ * Unsigned elements will become signed (with possible overflow).
+ * Float elements will be casted to [Int]
+ * @return [Int] or 0 if fail to convert element to integer.
+ */
+ public fun toInt(): Int = toULong().toInt()
+
+ /**
+ * Returns element as [Long].
+ * For vector types, it will return size of the vector
+ * For String type, it will type to be parsed as integer
+ * Unsigned elements will become negative
+ * Float elements will be casted to integer
+ * @return [Long] integer or 0 if fail to convert element to long.
+ */
+ public fun toLong(): Long = toULong().toLong()
+
+ /**
+ * Returns element as [UByte].
+ * For vector types, it will return size of the vector.
+ * For String type, it will type to be parsed as integer.
+ * Negative elements will become unsigned counterpart.
+ * Float elements will be casted to [UByte]
+ * @return [UByte] or 0 if fail to convert element to integer.
+ */
+ public fun toUByte(): UByte = toULong().toUByte()
+
+ /**
+ * Returns element as [UShort].
+ * For vector types, it will return size of the vector.
+ * For String type, it will type to be parsed as integer.
+ * Negative elements will become unsigned counterpart.
+ * Float elements will be casted to [UShort]
+ * @return [UShort] or 0 if fail to convert element to integer.
+ */
+ public fun toUShort(): UShort = toULong().toUShort()
+
+ /**
+ * Returns element as [UInt].
+ * For vector types, it will return size of the vector.
+ * For String type, it will type to be parsed as integer.
+ * Negative elements will become unsigned counterpart.
+ * Float elements will be casted to [UInt]
+ * @return [UInt] or 0 if fail to convert element to integer.
+ */
+ public fun toUInt(): UInt = toULong().toUInt()
+
+ /**
+ * Returns element as [ULong] integer.
+ * For vector types, it will return size of the vector
+ * For String type, it will type to be parsed as integer
+ * Negative elements will become unsigned counterpart.
+ * Float elements will be casted to integer
+ * @return [ULong] integer or 0 if fail to convert element to long.
+ */
+ public fun toULong(): ULong = resolve { pos: Int, width: ByteWidth ->
+ when (type) {
+ T_INDIRECT_INT, T_INDIRECT_UINT, T_INT, T_BOOL, T_UINT -> buffer.readULong(pos, width)
+ T_FLOAT, T_INDIRECT_FLOAT -> buffer.readFloat(pos, width).toULong()
+ T_STRING -> toString().toULong()
+ T_VECTOR -> toVector().size.toULong()
+ else -> 0UL
+ }
+ }
+
+ /**
+ * Returns element as [Float].
+ * For vector types, it will return size of the vector
+ * For String type, it will type to be parsed as [Float]
+ * Float elements will be casted to integer
+ * @return [Float] integer or 0 if fail to convert element to long.
+ */
+ public fun toFloat(): Float = resolve { pos: Int, width: ByteWidth ->
+ when (type) {
+ T_INDIRECT_FLOAT, T_FLOAT -> buffer.readFloat(pos, width).toFloat()
+ T_INT -> buffer.readInt(end, parentWidth).toFloat()
+ T_UINT, T_BOOL -> buffer.readUInt(end, parentWidth).toFloat()
+ T_INDIRECT_INT -> buffer.readInt(pos, width).toFloat()
+ T_INDIRECT_UINT -> buffer.readUInt(pos, width).toFloat()
+ T_NULL -> 0.0f
+ T_STRING -> toString().toFloat()
+ T_VECTOR -> toVector().size.toFloat()
+ else -> 0f
+ }
+ }
+
+ /**
+ * Returns element as [Double].
+ * For vector types, it will return size of the vector
+ * For String type, it will type to be parsed as [Double]
+ * @return [Float] integer or 0 if fail to convert element to long.
+ */
+ public fun toDouble(): Double = resolve { pos: Int, width: ByteWidth ->
+ when (type) {
+ T_INDIRECT_FLOAT, T_FLOAT -> buffer.readFloat(pos, width)
+ T_INT -> buffer.readInt(pos, width).toDouble()
+ T_UINT, T_BOOL -> buffer.readUInt(pos, width).toDouble()
+ T_INDIRECT_INT -> buffer.readInt(pos, width).toDouble()
+ T_INDIRECT_UINT -> buffer.readUInt(pos, width).toDouble()
+ T_NULL -> 0.0
+ T_STRING -> toString().toDouble()
+ T_VECTOR -> toVector().size.toDouble()
+ else -> 0.0
+ }
+ }
+
+ /**
+ * Returns element as [Key] or invalid key.
+ */
+ public fun toKey(): Key = when (type) {
+ T_KEY -> Key(buffer, buffer.indirect(end, parentWidth))
+ else -> nullKey()
+ }
+ /**
+ * Returns element as a [String]
+ * @return element as [String] or empty [String] if fail
+ */
+ override fun toString(): String = when (type) {
+ T_STRING -> {
+ val start = buffer.indirect(end, parentWidth)
+ val size = buffer.readULong(start - byteWidth, byteWidth).toInt()
+ buffer.getString(start, size)
+ }
+ T_KEY -> buffer.getKeyString(buffer.indirect(end, parentWidth))
+ T_MAP -> "{ ${toMap().entries.joinToString(", ") { "${it.key}: ${it.value}"}} }"
+ T_VECTOR, T_VECTOR_BOOL, T_VECTOR_FLOAT, T_VECTOR_INT,
+ T_VECTOR_UINT, T_VECTOR_KEY, T_VECTOR_STRING_DEPRECATED -> "[ ${toVector().joinToString(", ") { it.toString() }} ]"
+ T_INT -> toLong().toString()
+ T_UINT -> toULong().toString()
+ T_FLOAT -> toDouble().toString()
+ else -> "${type.typeToString()}(end=$end)"
+ }
+
+ /**
+ * Returns element as a [ByteArray], converting scalar types when possible.
+ * @return element as [ByteArray] or empty [ByteArray] if fail.
+ */
+ public fun toByteArray(): ByteArray {
+ val vec = TypedVector(type.toElementTypedVector(), buffer, buffer.indirect(end, parentWidth), byteWidth)
+ return when (type) {
+ T_VECTOR_INT -> ByteArray(vec.size) { vec.getInt(it).toByte() }
+ T_VECTOR_UINT -> ByteArray(vec.size) { vec.getUInt(it).toByte() }
+ T_VECTOR -> ByteArray(vec.size) { vec[it].toByte() }
+ T_VECTOR_FLOAT -> ByteArray(vec.size) { vec.getFloat(it).toInt().toByte() }
+ else -> ByteArray(0)
+ }
+ }
+
+ /**
+ * Returns element as a [ByteArray], converting scalar types when possible.
+ * @return element as [ByteArray] or empty [ByteArray] if fail.
+ */
+ public fun toShortArray(): ShortArray {
+ val vec = TypedVector(type.toElementTypedVector(), buffer, buffer.indirect(end, parentWidth), byteWidth)
+ return when (type) {
+ T_VECTOR_INT -> ShortArray(vec.size) { vec.getInt(it).toShort() }
+ T_VECTOR_UINT -> ShortArray(vec.size) { vec.getUInt(it).toShort() }
+ T_VECTOR -> ShortArray(vec.size) { vec[it].toShort() }
+ T_VECTOR_FLOAT -> ShortArray(vec.size) { vec.getFloat(it).toInt().toShort() }
+ else -> ShortArray(0)
+ }
+ }
+
+ /**
+ * Returns element as a [IntArray], converting scalar types when possible.
+ * @return element as [IntArray] or empty [IntArray] if fail.
+ */
+ public fun toIntArray(): IntArray {
+ val vec = TypedVector(type.toElementTypedVector(), buffer, buffer.indirect(end, parentWidth), byteWidth)
+ return when (type) {
+ T_VECTOR_INT -> IntArray(vec.size) { vec.getInt(it).toInt() }
+ T_VECTOR_UINT -> IntArray(vec.size) { vec.getUInt(it).toInt() }
+ T_VECTOR -> IntArray(vec.size) { vec[it].toInt() }
+ T_VECTOR_FLOAT -> IntArray(vec.size) { vec.getFloat(it).toInt() }
+ else -> IntArray(0)
+ }
+ }
+
+ /**
+ * Returns element as a [LongArray], converting scalar types when possible.
+ * @return element as [LongArray] or empty [LongArray] if fail.
+ */
+ public fun toLongArray(): LongArray {
+ val vec = TypedVector(type.toElementTypedVector(), buffer, buffer.indirect(end, parentWidth), byteWidth)
+ return when (type) {
+ T_VECTOR_INT -> LongArray(vec.size) { vec.getInt(it) }
+ T_VECTOR_UINT -> LongArray(vec.size) { vec.getInt(it) }
+ T_VECTOR -> LongArray(vec.size) { vec[it].toLong() }
+ T_VECTOR_FLOAT -> LongArray(vec.size) { vec.getFloat(it).toLong() }
+ else -> LongArray(0)
+ }
+ }
+
+ /**
+ * Returns element as a [UByteArray], converting scalar types when possible.
+ * @return element as [UByteArray] or empty [UByteArray] if fail.
+ */
+ public fun toUByteArray(): UByteArray {
+ val vec = TypedVector(type.toElementTypedVector(), buffer, buffer.indirect(end, parentWidth), byteWidth)
+ return when (type) {
+ T_VECTOR_INT -> UByteArray(vec.size) { vec.getInt(it).toUByte() }
+ T_VECTOR_UINT -> UByteArray(vec.size) { vec.getUInt(it).toUByte() }
+ T_VECTOR -> UByteArray(vec.size) { vec[it].toUByte() }
+ T_VECTOR_FLOAT -> UByteArray(vec.size) { vec.getFloat(it).toInt().toUByte() }
+ else -> UByteArray(0)
+ }
+ }
+
+ /**
+ * Returns element as a [UIntArray], converting scalar types when possible.
+ * @return element as [UIntArray] or empty [UIntArray] if fail.
+ */
+ public fun toUShortArray(): UShortArray {
+ val vec = TypedVector(type.toElementTypedVector(), buffer, buffer.indirect(end, parentWidth), byteWidth)
+ return when (type) {
+ T_VECTOR_INT -> UShortArray(vec.size) { vec.getInt(it).toUShort() }
+ T_VECTOR_UINT -> UShortArray(vec.size) { vec.getUInt(it).toUShort() }
+ T_VECTOR -> UShortArray(vec.size) { vec[it].toUShort() }
+ T_VECTOR_FLOAT -> UShortArray(vec.size) { vec.getFloat(it).toUInt().toUShort() }
+ else -> UShortArray(0)
+ }
+ }
+
+ /**
+ * Returns element as a [UIntArray], converting scalar types when possible.
+ * @return element as [UIntArray] or empty [UIntArray] if fail.
+ */
+ public fun toUIntArray(): UIntArray {
+ val vec = TypedVector(type.toElementTypedVector(), buffer, buffer.indirect(end, parentWidth), byteWidth)
+ return when (type) {
+ T_VECTOR_INT -> UIntArray(vec.size) { vec.getInt(it).toUInt() }
+ T_VECTOR_UINT -> UIntArray(vec.size) { vec.getUInt(it).toUInt() }
+ T_VECTOR -> UIntArray(vec.size) { vec[it].toUInt() }
+ T_VECTOR_FLOAT -> UIntArray(vec.size) { vec.getFloat(it).toUInt() }
+ else -> UIntArray(0)
+ }
+ }
+
+ /**
+ * Returns element as a [ULongArray], converting scalar types when possible.
+ * @return element as [ULongArray] or empty [ULongArray] if fail.
+ */
+ public fun toULongArray(): ULongArray {
+ val vec = TypedVector(type.toElementTypedVector(), buffer, buffer.indirect(end, parentWidth), byteWidth)
+ return when (type) {
+ T_VECTOR_INT -> ULongArray(vec.size) { vec.getUInt(it) }
+ T_VECTOR_UINT -> ULongArray(vec.size) { vec.getUInt(it) }
+ T_VECTOR -> ULongArray(vec.size) { vec[it].toULong() }
+ T_VECTOR_FLOAT -> ULongArray(vec.size) { vec.getFloat(it).toULong() }
+ else -> ULongArray(0)
+ }
+ }
+
+ /**
+ * Returns element as a [FloatArray], converting scalar types when possible.
+ * @return element as [FloatArray] or empty [FloatArray] if fail.
+ */
+ public fun toFloatArray(): FloatArray {
+ val vec = TypedVector(type.toElementTypedVector(), buffer, buffer.indirect(end, parentWidth), byteWidth)
+ return when (type) {
+ T_VECTOR_FLOAT -> FloatArray(vec.size) { vec.getFloat(it).toFloat() }
+ T_VECTOR_INT -> FloatArray(vec.size) { vec.getInt(it).toFloat() }
+ T_VECTOR_UINT -> FloatArray(vec.size) { vec.getUInt(it).toFloat() }
+ T_VECTOR -> FloatArray(vec.size) { vec[it].toFloat() }
+ else -> FloatArray(0)
+ }
+ }
+
+ /**
+ * Returns element as a [DoubleArray], converting scalar types when possible.
+ * @return element as [DoubleArray] or empty [DoubleArray] if fail.
+ */
+ public fun toDoubleArray(): DoubleArray {
+ val vec = TypedVector(type.toElementTypedVector(), buffer, buffer.indirect(end, parentWidth), byteWidth)
+ return when (type) {
+ T_VECTOR_FLOAT -> DoubleArray(vec.size) { vec[it].toDouble() }
+ T_VECTOR_INT -> DoubleArray(vec.size) { vec[it].toDouble() }
+ T_VECTOR_UINT -> DoubleArray(vec.size) { vec[it].toDouble() }
+ T_VECTOR -> DoubleArray(vec.size) { vec[it].toDouble() }
+ else -> DoubleArray(0)
+ }
+ }
+
+ /**
+ * Returns element as a [Vector]
+ * @return element as [Vector] or empty [Vector] if fail
+ */
+ public fun toVector(): Vector {
+ return when {
+ isVector -> Vector(buffer, buffer.indirect(end, parentWidth), byteWidth)
+ isTypedVector -> TypedVector(type.toElementTypedVector(), buffer, buffer.indirect(end, parentWidth), byteWidth)
+ else -> emptyVector()
+ }
+ }
+
+ /**
+ * Returns element as a [Blob]
+ * @return element as [Blob] or empty [Blob] if fail
+ */
+ public fun toBlob(): Blob {
+ return when (type) {
+ T_BLOB, T_STRING -> Blob(buffer, buffer.indirect(end, parentWidth), byteWidth)
+ else -> emptyBlob()
+ }
+ }
+
+ /**
+ * Returns element as a [Map].
+ * @return element as [Map] or empty [Map] if fail
+ */
+ public fun toMap(): Map = when (type) {
+ T_MAP -> Map(buffer, buffer.indirect(end, parentWidth), byteWidth)
+ else -> emptyMap()
+ }
+
+ private inline fun <T> resolve(crossinline block: (pos: Int, width: ByteWidth) -> T): T {
+ return if (type.isIndirectScalar()) {
+ block(buffer.indirect(end, byteWidth), byteWidth)
+ } else {
+ block(end, parentWidth)
+ }
+ }
+
+ override fun equals(other: Any?): Boolean {
+ if (this === other) return true
+ if (other == null || this::class != other::class) return false
+ other as Reference
+ if (buffer != other.buffer ||
+ end != other.end ||
+ parentWidth != other.parentWidth ||
+ byteWidth != other.byteWidth ||
+ type != other.type
+ ) return false
+ return true
+ }
+
+ override fun hashCode(): Int {
+ var result = buffer.hashCode()
+ result = 31 * result + end
+ result = 31 * result + parentWidth.value
+ result = 31 * result + byteWidth.value
+ result = 31 * result + type.hashCode()
+ return result
+ }
+}
+
+/**
+ * Represents any element that has a size property to it, like: [Map], [Vector] and [TypedVector].
+ */
+public open class Sized internal constructor(
+ public val buffer: ReadBuffer,
+ public val end: Int,
+ public val byteWidth: ByteWidth
+) {
+ public open val size: Int = buffer.readSize(end, byteWidth)
+}
+
+/**
+ * Represent an array of bytes in the buffer.
+ */
+public open class Blob internal constructor(
+ buffer: ReadBuffer,
+ end: Int,
+ byteWidth: ByteWidth
+) : Sized(buffer, end, byteWidth) {
+ /**
+ * Return [Blob] as [ReadBuffer]
+ * @return blob as [ReadBuffer]
+ */
+ public fun data(): ReadBuffer = buffer.slice(end, size)
+
+ /**
+ * Copy [Blob] into a [ByteArray]
+ * @return A [ByteArray] containing the blob data.
+ */
+ public fun toByteArray(): ByteArray {
+ val result = ByteArray(size)
+ for (i in 0 until size) {
+ result[i] = buffer[end + i]
+ }
+ return result
+ }
+
+ /**
+ * Return individual byte at a given position
+ * @param pos position of the byte to be read
+ */
+ public operator fun get(pos: Int): Byte {
+ if (pos !in 0..size) error("$pos index out of bounds. Should be in range 0..$size")
+ return buffer[end + pos]
+ }
+
+ override fun toString(): String = buffer.getString(end, size)
+}
+
+/**
+ * [Vector] represents an array of elements in the buffer. The element can be of any type.
+ */
+public open class Vector internal constructor(
+ buffer: ReadBuffer,
+ end: Int,
+ byteWidth: ByteWidth
+) : Collection<Reference>,
+ Sized(buffer, end, byteWidth) {
+
+ /**
+ * Returns a [Reference] from the [Vector] at position [index]. Returns a null reference
+ * @param index position in the vector.
+ * @return [Reference] for a key or a null [Reference] if not found.
+ */
+ public open operator fun get(index: Int): Reference {
+ if (index >= size) return nullReference()
+ val packedType = buffer[(end + size * byteWidth.value + index)].toInt()
+ val objEnd = end + index * byteWidth
+ return Reference(buffer, objEnd, byteWidth, packedType)
+ }
+
+ // overrides from Collection<Reference>
+
+ override fun contains(element: Reference): Boolean = find { it == element } != null
+
+ override fun containsAll(elements: Collection<Reference>): Boolean {
+ elements.forEach { if (!contains(it)) return false }
+ return true
+ }
+
+ override fun isEmpty(): Boolean = size == 0
+
+ override fun iterator(): Iterator<Reference> = object : Iterator<Reference> {
+ var position = 0
+ override fun hasNext(): Boolean = position != size
+ override fun next(): Reference = get(position++)
+ }
+}
+
+/**
+ * [TypedVector] represents an array of scalar elements of the same type in the buffer.
+ */
+public open class TypedVector(
+ private val elementType: FlexBufferType,
+ buffer: ReadBuffer,
+ end: Int,
+ byteWidth: ByteWidth
+) : Vector(buffer, end, byteWidth) {
+
+ /**
+ * Returns a [Reference] from the [TypedVector] at position [index]. Returns a null reference
+ * @param index position in the vector.
+ * @return [Reference] for a key or a null [Reference] if not found.
+ */
+ override operator fun get(index: Int): Reference {
+ if (index >= size) return nullReference()
+ val childPos: Int = end + index * byteWidth
+ return Reference(buffer, childPos, byteWidth, ByteWidth(1), elementType)
+ }
+
+ private inline fun <T> resolveAt(index: Int, crossinline block: (Int, ByteWidth) -> T): T {
+ val childPos: Int = end + index * byteWidth
+ return block(childPos, byteWidth)
+ }
+
+ internal fun getBoolean(index: Int): Boolean = resolveAt(index) { pos: Int, _: ByteWidth -> buffer.getBoolean(pos) }
+ internal fun getInt(index: Int): Long = resolveAt(index) { pos: Int, width: ByteWidth -> buffer.readLong(pos, width) }
+ internal fun getUInt(index: Int): ULong = resolveAt(index) { pos: Int, width: ByteWidth -> buffer.readULong(pos, width) }
+ internal fun getFloat(index: Int): Double = resolveAt(index) { pos: Int, width: ByteWidth -> buffer.readFloat(pos, width) }
+}
+
+/**
+ * Represents a key element in the buffer. Keys are
+ * used to reference objects in a [Map]
+ */
+public data class Key(
+ public val buffer: ReadBuffer,
+ public val start: Int,
+ public val end: Int = buffer.findFirst(ZeroByte, start)
+) {
+
+ val sizeInBytes: Int = end - start
+
+ private val codePoint = CharArray(2)
+
+ val sizeInChars: Int
+ get() {
+ var count = 0
+ var i = start
+ while (i < end) {
+ val size = codePointSizeInBytes(i)
+ i += size
+ count += if (size == 4) 2 else 1
+ }
+ return count
+ }
+
+ public operator fun get(index: Int): Char {
+ var count = 0
+ var i = start
+ var size = 0
+ // we loop over the bytes to find the right position for the "char" at index i
+ while (i < end && count < index) {
+ size = codePointSizeInBytes(i)
+ i += size
+ // 4 bytes utf8 are 2 chars wide, the rest is on char.
+ count += if (size == 4) 2 else 1
+ }
+ return when {
+ count == index -> {
+ Utf8.decodeUtf8CodePoint(buffer, i, codePoint)
+ codePoint[0]
+ }
+ count == index + 1 && size == 4 -> {
+ Utf8.decodeUtf8CodePoint(buffer, i - size, codePoint)
+ codePoint[1]
+ }
+ else -> error("Invalid count=$count, index=$index")
+ }
+ }
+
+ private inline fun codePointSizeInBytes(pos: Int): Int {
+ val b = buffer[pos]
+ return when {
+ Utf8.isOneByte(b) -> 1
+ Utf8.isTwoBytes(b) -> 2
+ Utf8.isThreeBytes(b) -> 3
+ else -> 4
+ }
+ }
+
+ override fun toString(): String = if (sizeInBytes > 0) buffer.getString(start, sizeInBytes) else ""
+
+ /**
+ * Checks whether Key is invalid or not.
+ */
+ public fun isInvalid(): Boolean = sizeInBytes <= 0
+}
+
+/**
+ * A Map class that provide support to access Key-Value data from Flexbuffers.
+ */
+public class Map internal constructor(buffer: ReadBuffer, end: Int, byteWidth: ByteWidth) :
+ Sized(buffer, end, byteWidth),
+ kotlin.collections.Map<Key, Reference> {
+
+ // used for accessing the key vector elements
+ private var keyVectorEnd: Int
+ private var keyVectorByteWidth: ByteWidth
+ init {
+ val keysOffset = end - (3 * byteWidth) // 3 is number of prefixed fields
+ keyVectorEnd = buffer.indirect(keysOffset, byteWidth)
+ keyVectorByteWidth = ByteWidth(buffer.readInt(keysOffset + byteWidth, byteWidth))
+ }
+
+ /**
+ * Returns a [Reference] from the [Map] at position [index]. Returns a null reference
+ * @param index position in the map
+ * @return [Reference] for a key or a null [Reference] if not found.
+ */
+ public operator fun get(index: Int): Reference {
+ if (index >= size) return nullReference()
+ val packedPos = end + size * byteWidth + index
+ val packedType = buffer[packedPos].toInt()
+ val objEnd = end + index * byteWidth
+ return Reference(buffer, objEnd, byteWidth, packedType)
+ }
+
+ /**
+ * Returns a [Reference] from the [Map] for a given [String] [key].
+ * @param key access key to element on map
+ * @return [Reference] for a key or a null [Reference] if not found.
+ */
+ public operator fun get(key: String): Reference {
+ val index: Int = binarySearch(key)
+ return if (index in 0 until size) {
+ get(index)
+ } else nullReference()
+ }
+
+ /**
+ * Returns a [Reference] from the [Map] for a given [Key] [key].
+ * @param key access key to element on map
+ * @return [Reference] for a key or a null [Reference] if not found.
+ */
+ override operator fun get(key: Key): Reference {
+ val index = binarySearch(key)
+ return if (index in 0 until size) {
+ get(index)
+ } else nullReference()
+ }
+
+ /**
+ * Checks whether the map contains a [key].
+ * @param key [String]
+ * @return true if key is found in the map, otherwise false.
+ */
+ public operator fun contains(key: String): Boolean = binarySearch(key) >= 0
+
+ /**
+ * Returns a [Key] for a given position [index] in the [Map].
+ * @param index of the key in the map
+ * @return a Key for the given index. Out of bounds indexes returns invalid keys.
+ */
+ public fun keyAt(index: Int): Key {
+ val childPos: Int = keyVectorEnd + index * keyVectorByteWidth
+ return Key(buffer, buffer.indirect(childPos, keyVectorByteWidth))
+ }
+
+ /**
+ * Returns a [Key] as [String] for a given position [index] in the [Map].
+ * @param index of the key in the map
+ * @return a Key for the given index. Out of bounds indexes returns empty string.
+ */
+ public fun keyAsString(index: Int): String {
+ val childPos: Int = keyVectorEnd + index * keyVectorByteWidth
+ val start = buffer.indirect(childPos, keyVectorByteWidth)
+ val end = buffer.findFirst(ZeroByte, start)
+ return if (end > start) buffer.getString(start, end - start) else ""
+ }
+
+ // Overrides from kotlin.collections.Map<Key, Reference>
+
+ public data class Entry(override val key: Key, override val value: Reference) :
+ kotlin.collections.Map.Entry<Key, Reference>
+
+ override val entries: Set<kotlin.collections.Map.Entry<Key, Reference>>
+ get() = keys.map { Entry(it, get(it.toString())) }.toSet()
+
+ override val keys: Set<Key>
+ get() {
+ val set = LinkedHashSet<Key>(size)
+ for (i in 0 until size) {
+ val key = keyAt(i)
+ set.add(key)
+ }
+ return set
+ }
+
+ /**
+ * Returns a [Vector] for accessing all values in the [Map].
+ * @return [Vector] of values.
+ */
+ override val values: Collection<Reference>
+ get() = Vector(buffer, end, byteWidth)
+
+ override fun containsKey(key: Key): Boolean {
+ for (i in 0 until size) {
+ if (key == keyAt(i))
+ return true
+ }
+ return false
+ }
+
+ override fun containsValue(value: Reference): Boolean = values.contains(value)
+
+ override fun isEmpty(): Boolean = size == 0
+
+ // Performs a binary search on a key vector and return index of the key in key vector
+ private fun binarySearch(searchedKey: String) = binarySearch { compareCharSequence(it, searchedKey) }
+ // Performs a binary search on a key vector and return index of the key in key vector
+ private fun binarySearch(key: Key): Int = binarySearch { compareKeys(it, key.start) }
+
+ private inline fun binarySearch(crossinline comparisonBlock: (Int) -> Int): Int {
+ var low = 0
+ var high = size - 1
+ while (low <= high) {
+ val mid = low + high ushr 1
+ val keyPos: Int = buffer.indirect(keyVectorEnd + mid * keyVectorByteWidth, keyVectorByteWidth)
+ val cmp: Int = comparisonBlock(keyPos)
+ if (cmp < 0) low = mid + 1 else if (cmp > 0) high = mid - 1 else return mid // key found
+ }
+ return -(low + 1) // key not found
+ }
+
+ // compares a CharSequence against a T_KEY
+ private fun compareKeys(start: Int, other: Int): Int {
+ var bufferPos = start
+ var otherPos = other
+ val limit: Int = buffer.limit
+ var c1: Byte = ZeroByte
+ var c2: Byte = ZeroByte
+ while (otherPos < limit) {
+ c1 = buffer[bufferPos++]
+ c2 = buffer[otherPos++]
+ when {
+ c1 == ZeroByte -> return c1 - c2
+ c1 != c2 -> return c1 - c2
+ }
+ }
+ return c1 - c2
+ }
+
+ // compares a CharSequence against a [CharSequence]
+ private fun compareCharSequence(start: Int, other: CharSequence): Int {
+ var bufferPos = start
+ var otherPos = 0
+ val limit: Int = buffer.limit
+ val otherLimit = other.length
+ // special loop for ASCII characters. Most of keys should be ASCII only, so this
+ // loop should be optimized for that.
+ // breaks if a multi-byte character is found
+ while (otherPos < otherLimit) {
+ val c2 = other[otherPos]
+ // not a single byte codepoint
+ if (c2.toInt() >= 0x80) {
+ break
+ }
+ val b: Byte = buffer[bufferPos]
+ when {
+ b == ZeroByte -> return -c2.toInt()
+ b < 0 -> break
+ b != c2.toByte() -> return b - c2.toByte()
+ }
+ ++bufferPos
+ ++otherPos
+ }
+ if (bufferPos < limit)
+ return 0
+
+ val comparisonBuffer = ByteArray(4)
+ while (bufferPos < limit) {
+ val sizeInBuff = Utf8.encodeUtf8CodePoint(other, otherPos, comparisonBuffer)
+ if (sizeInBuff == 0) {
+ return buffer[bufferPos].toInt()
+ }
+ for (i in 0 until sizeInBuff) {
+ val bufferByte: Byte = buffer[bufferPos++]
+ val otherByte: Byte = comparisonBuffer[i]
+ when {
+ bufferByte == ZeroByte -> return -otherByte
+ bufferByte != otherByte -> return bufferByte - otherByte
+ }
+ }
+ otherPos += if (sizeInBuff == 4) 2 else 1
+ }
+ return 0
+ }
+}
diff --git a/kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/FlexBuffersBuilder.kt b/kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/FlexBuffersBuilder.kt
new file mode 100644
index 0000000..a4cd9d3
--- /dev/null
+++ b/kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/FlexBuffersBuilder.kt
@@ -0,0 +1,771 @@
+/*
+ * Copyright 2021 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.
+ */
+@file:Suppress("NOTHING_TO_INLINE")
+
+package com.google.flatbuffers.kotlin
+
+public class FlexBuffersBuilder(
+ public val buffer: ReadWriteBuffer,
+ private val shareFlag: Int = SHARE_KEYS
+) {
+
+ public constructor(initialCapacity: Int = 1024, shareFlag: Int = SHARE_KEYS) :
+ this(ArrayReadWriteBuffer(initialCapacity), shareFlag)
+
+ private val stringValuePool: HashMap<String, Value> = HashMap()
+ private val stringKeyPool: HashMap<String, Int> = HashMap()
+ private val stack: MutableList<Value> = mutableListOf()
+ private var finished: Boolean = false
+
+ /**
+ * Reset the FlexBuffersBuilder by purging all data that it holds. Buffer might
+ * keep its capacity after a reset.
+ */
+ public fun clear() {
+ buffer.clear()
+ stringValuePool.clear()
+ stringKeyPool.clear()
+ stack.clear()
+ finished = false
+ }
+
+ /**
+ * Finish writing the message into the buffer. After that no other element must
+ * be inserted into the buffer. Also, you must call this function before start using the
+ * FlexBuffer message
+ * @return [ReadBuffer] containing the FlexBuffer message
+ */
+ public fun finish(): ReadBuffer {
+ // If you hit this assert, you likely have objects that were never included
+ // in a parent. You need to have exactly one root to finish a buffer.
+ // Check your Start/End calls are matched, and all objects are inside
+ // some other object.
+ if (stack.size != 1) error("There is must be only on object as root. Current ${stack.size}.")
+ // Write root value.
+ val byteWidth = align(stack[0].elemWidth(buffer.writePosition, 0))
+ writeAny(stack[0], byteWidth)
+ // Write root type.
+ buffer.put(stack[0].storedPackedType())
+ // Write root size. Normally determined by parent, but root has no parent :)
+ buffer.put(byteWidth.value.toByte())
+ this.finished = true
+ return buffer // TODO: make a read-only shallow copy
+ }
+
+ /**
+ * Insert a single [Boolean] into the buffer
+ * @param value true or false
+ */
+ public fun put(value: Boolean): Unit = run { this[null] = value }
+
+ /**
+ * Insert a null reference into the buffer. A key must be present if element is inserted into a map.
+ */
+ public fun putNull(key: String? = null): Unit =
+ run { stack.add(Value(T_NULL, putKey(key), W_8, 0UL)) }
+
+ /**
+ * Insert a single [Boolean] into the buffer. A key must be present if element is inserted into a map.
+ */
+ public operator fun set(key: String? = null, value: Boolean): Unit =
+ run { stack.add(Value(T_BOOL, putKey(key), W_8, if (value) 1UL else 0UL)) }
+
+ /**
+ * Insert a single [Byte] into the buffer
+ */
+ public fun put(value: Byte): Unit = set(null, value.toLong())
+
+ /**
+ * Insert a single [Byte] into the buffer. A key must be present if element is inserted into a map.
+ */
+ public operator fun set(key: String? = null, value: Byte): Unit = set(key, value.toLong())
+
+ /**
+ * Insert a single [Short] into the buffer.
+ */
+ public fun put(value: Short): Unit = set(null, value.toLong())
+
+ /**
+ * Insert a single [Short] into the buffer. A key must be present if element is inserted into a map.
+ */
+ public inline operator fun set(key: String? = null, value: Short): Unit = set(key, value.toLong())
+
+ /**
+ * Insert a single [Int] into the buffer.
+ */
+ public fun put(value: Int): Unit = set(null, value.toLong())
+
+ /**
+ * Insert a single [Int] into the buffer. A key must be present if element is inserted into a map.
+ */
+ public inline operator fun set(key: String? = null, value: Int): Unit = set(key, value.toLong())
+
+ /**
+ * Insert a single [Long] into the buffer.
+ */
+ public fun put(value: Long): Unit = set(null, value)
+
+ /**
+ * Insert a single [Long] into the buffer. A key must be present if element is inserted into a map.
+ */
+ public operator fun set(key: String? = null, value: Long): Unit =
+ run { stack.add(Value(T_INT, putKey(key), value.toULong().widthInUBits(), value.toULong())) }
+
+ /**
+ * Insert a single [UByte] into the buffer
+ */
+ public fun put(value: UByte): Unit = set(null, value.toULong())
+
+ /**
+ * Insert a single [UByte] into the buffer. A key must be present if element is inserted into a map.
+ */
+ public inline operator fun set(key: String? = null, value: UByte): Unit = set(key, value.toULong())
+
+ /**
+ * Insert a single [UShort] into the buffer.
+ */
+ public fun put(value: UShort): Unit = set(null, value.toULong())
+
+ /**
+ * Insert a single [UShort] into the buffer. A key must be present if element is inserted into a map.
+ */
+ private inline operator fun set(key: String? = null, value: UShort): Unit = set(key, value.toULong())
+
+ /**
+ * Insert a single [UInt] into the buffer.
+ */
+ public fun put(value: UInt): Unit = set(null, value.toULong())
+
+ /**
+ * Insert a single [UInt] into the buffer. A key must be present if element is inserted into a map.
+ */
+ private inline operator fun set(key: String? = null, value: UInt): Unit = set(key, value.toULong())
+
+ /**
+ * Insert a single [ULong] into the buffer.
+ */
+ public fun put(value: ULong): Unit = set(null, value)
+
+ /**
+ * Insert a single [ULong] into the buffer. A key must be present if element is inserted into a map.
+ */
+ public operator fun set(key: String? = null, value: ULong): Unit =
+ run { stack.add(Value(T_UINT, putKey(key), value.widthInUBits(), value)) }
+
+ /**
+ * Insert a single [Float] into the buffer.
+ */
+ public fun put(value: Float): Unit = run { this[null] = value }
+
+ /**
+ * Insert a single [Float] into the buffer. A key must be present if element is inserted into a map.
+ */
+ public operator fun set(key: String? = null, value: Float): Unit =
+ run { stack.add(Value(T_FLOAT, putKey(key), W_32, dValue = value.toDouble())) }
+
+ /**
+ * Insert a single [Double] into the buffer.
+ */
+ public fun put(value: Double): Unit = run { this[null] = value }
+
+ /**
+ * Insert a single [Double] into the buffer. A key must be present if element is inserted into a map.
+ */
+ public operator fun set(key: String? = null, value: Double): Unit =
+ run { stack.add(Value(T_FLOAT, putKey(key), W_64, dValue = value)) }
+
+ /**
+ * Insert a single [String] into the buffer.
+ */
+ public fun put(value: String): Int = set(null, value)
+
+ /**
+ * Insert a single [String] into the buffer. A key must be present if element is inserted into a map.
+ */
+ public operator fun set(key: String? = null, value: String): Int {
+ val iKey = putKey(key)
+ val holder = if (shareFlag and SHARE_STRINGS != 0) {
+ stringValuePool.getOrPut(value) { writeString(iKey, value).also { stringValuePool[value] = it } }.copy(key = iKey)
+ } else {
+ writeString(iKey, value)
+ }
+ stack.add(holder)
+ return holder.iValue.toInt()
+ }
+
+ /**
+ * Adds a [ByteArray] into the message as a [Blob].
+ * @param value byte array
+ * @return position in buffer as the start of byte array
+ */
+ public fun put(value: ByteArray): Int = set(null, value)
+
+ /**
+ * Adds a [ByteArray] into the message as a [Blob]. A key must be present if element is inserted into a map.
+ * @param value byte array
+ * @return position in buffer as the start of byte array
+ */
+ public operator fun set(key: String? = null, value: ByteArray): Int {
+ val element = writeBlob(putKey(key), value, T_BLOB, false)
+ stack.add(element)
+ return element.iValue.toInt()
+ }
+
+ /**
+ * Adds a [IntArray] into the message as a typed vector of fixed size.
+ * @param value [IntArray]
+ * @return position in buffer as the start of byte array
+ */
+ public fun put(value: IntArray): Int = set(null, value)
+
+ /**
+ * Adds a [IntArray] into the message as a typed vector of fixed size.
+ * A key must be present if element is inserted into a map.
+ * @param value [IntArray]
+ * @return position in buffer as the start of byte array
+ */
+ public operator fun set(key: String? = null, value: IntArray): Int =
+ setTypedVector(key, value.size, T_VECTOR_INT, value.widthInUBits()) { writeIntArray(value, it) }
+
+ /**
+ * Adds a [ShortArray] into the message as a typed vector of fixed size.
+ * @param value [ShortArray]
+ * @return position in buffer as the start of byte array
+ */
+ public fun put(value: ShortArray): Int = set(null, value)
+
+ /**
+ * Adds a [ShortArray] into the message as a typed vector of fixed size.
+ * A key must be present if element is inserted into a map.
+ * @param value [ShortArray]
+ * @return position in buffer as the start of byte array
+ */
+ public operator fun set(key: String? = null, value: ShortArray): Int =
+ setTypedVector(key, value.size, T_VECTOR_INT, value.widthInUBits()) { writeIntArray(value, it) }
+
+ /**
+ * Adds a [LongArray] into the message as a typed vector of fixed size.
+ * @param value [LongArray]
+ * @return position in buffer as the start of byte array
+ */
+ public fun put(value: LongArray): Int = set(null, value)
+
+ /**
+ * Adds a [LongArray] into the message as a typed vector of fixed size.
+ * A key must be present if element is inserted into a map.
+ * @param value [LongArray]
+ * @return position in buffer as the start of byte array
+ */
+ public operator fun set(key: String? = null, value: LongArray): Int =
+ setTypedVector(key, value.size, T_VECTOR_INT, value.widthInUBits()) { writeIntArray(value, it) }
+
+ /**
+ * Adds a [FloatArray] into the message as a typed vector of fixed size.
+ * @param value [FloatArray]
+ * @return position in buffer as the start of byte array
+ */
+ public fun put(value: FloatArray): Int = set(null, value)
+
+ /**
+ * Adds a [FloatArray] into the message as a typed vector of fixed size.
+ * A key must be present if element is inserted into a map.
+ * @param value [FloatArray]
+ * @return position in buffer as the start of byte array
+ */
+ public operator fun set(key: String? = null, value: FloatArray): Int =
+ setTypedVector(key, value.size, T_VECTOR_FLOAT, W_32) { writeFloatArray(value) }
+
+ /**
+ * Adds a [DoubleArray] into the message as a typed vector of fixed size.
+ * @param value [DoubleArray]
+ * @return position in buffer as the start of byte array
+ */
+ public fun put(value: DoubleArray): Int = set(null, value)
+
+ /**
+ * Adds a [DoubleArray] into the message as a typed vector of fixed size.
+ * A key must be present if element is inserted into a map.
+ * @param value [DoubleArray]
+ * @return position in buffer as the start of byte array
+ */
+ public operator fun set(key: String? = null, value: DoubleArray): Int =
+ setTypedVector(key, value.size, T_VECTOR_FLOAT, W_64) { writeFloatArray(value) }
+
+ /**
+ * Adds a [UByteArray] into the message as a typed vector of fixed size.
+ * @param value [UByteArray]
+ * @return position in buffer as the start of byte array
+ */
+ public fun put(value: UByteArray): Int = set(null, value)
+
+ /**
+ * Adds a [UByteArray] into the message as a typed vector of fixed size.
+ * A key must be present if element is inserted into a map.
+ * @param value [UByteArray]
+ * @return position in buffer as the start of byte array
+ */
+ public operator fun set(key: String? = null, value: UByteArray): Int =
+ setTypedVec(key) { value.forEach { put(it) } }
+
+ /**
+ * Adds a [UShortArray] into the message as a typed vector of fixed size.
+ * @param value [UShortArray]
+ * @return position in buffer as the start of byte array
+ */
+ public fun put(value: UShortArray): Int = set(null, value)
+
+ /**
+ * Adds a [UShortArray] into the message as a typed vector of fixed size.
+ * A key must be present if element is inserted into a map.
+ * @param value [UShortArray]
+ * @return position in buffer as the start of byte array
+ */
+ public operator fun set(key: String? = null, value: UShortArray): Int =
+ setTypedVec(key) { value.forEach { put(it) } }
+
+ /**
+ * Adds a [UIntArray] into the message as a typed vector of fixed size.
+ * @param value [UIntArray]
+ * @return position in buffer as the start of byte array
+ */
+ public fun put(value: UIntArray): Int = set(null, value)
+
+ /**
+ * Adds a [UIntArray] into the message as a typed vector of fixed size.
+ * A key must be present if element is inserted into a map.
+ * @param value [UIntArray]
+ * @return position in buffer as the start of byte array
+ */
+ public fun set(key: String? = null, value: UIntArray): Int =
+ setTypedVec(key) { value.forEach { put(it) } }
+
+ /**
+ * Adds a [ULongArray] into the message as a typed vector of fixed size.
+ * @param value [ULongArray]
+ * @return position in buffer as the start of byte array
+ */
+ public fun put(value: ULongArray): Int = set(null, value)
+
+ /**
+ * Adds a [ULongArray] into the message as a typed vector of fixed size.
+ * A key must be present if element is inserted into a map.
+ * @param value [ULongArray]
+ * @return position in buffer as the start of byte array
+ */
+ public operator fun set(key: String? = null, value: ULongArray): Int =
+ setTypedVec(key) { value.forEach { put(it) } }
+
+ /**
+ * Creates a new vector will all elements inserted in [block].
+ * @param block where elements will be inserted
+ * @return position in buffer as the start of byte array
+ */
+ public inline fun putVector(crossinline block: FlexBuffersBuilder.() -> Unit): Int {
+ val pos = startVector()
+ this.block()
+ return endVector(pos)
+ }
+
+ /**
+ * Creates a new typed vector will all elements inserted in [block].
+ * @param block where elements will be inserted
+ * @return position in buffer as the start of byte array
+ */
+ public inline fun putTypedVector(crossinline block: FlexBuffersBuilder.() -> Unit): Int {
+ val pos = startVector()
+ this.block()
+ return endTypedVector(pos)
+ }
+
+ /**
+ * Helper function to return position for starting a new vector.
+ */
+ public fun startVector(): Int = stack.size
+
+ /**
+ * Finishes a vector element. The initial position of the vector must be passed
+ * @param position position at the start of the vector
+ */
+ public fun endVector(position: Int): Int = endVector(null, position)
+
+ /**
+ * Finishes a vector element. The initial position of the vector must be passed
+ * @param position position at the start of the vector
+ */
+ public fun endVector(key: String? = null, position: Int): Int =
+ endAnyVector(position) { createVector(putKey(key), position, stack.size - position) }
+ /**
+ * Finishes a typed vector element. The initial position of the vector must be passed
+ * @param position position at the start of the vector
+ */
+ public fun endTypedVector(position: Int): Int = endTypedVector(position, null)
+
+ /**
+ * Helper function to return position for starting a new vector.
+ */
+ public fun startMap(): Int = stack.size
+
+ /**
+ * Creates a new map will all elements inserted in [block].
+ * @param block where elements will be inserted
+ * @return position in buffer as the start of byte array
+ */
+ public inline fun putMap(key: String? = null, crossinline block: FlexBuffersBuilder.() -> Unit): Int {
+ val pos = startMap()
+ this.block()
+ return endMap(pos, key)
+ }
+
+ /**
+ * Finishes a map, but writing the information in the buffer
+ * @param key key used to store element in map
+ * @return Reference to the map
+ */
+ public fun endMap(start: Int, key: String? = null): Int {
+ stack.subList(start, stack.size).sortWith(keyComparator)
+ val length = stack.size - start
+ val keys = createKeyVector(start, length)
+ val vec = putMap(putKey(key), start, length, keys)
+ // Remove temp elements and return map.
+ while (stack.size > start) {
+ stack.removeAt(stack.size - 1)
+ }
+ stack.add(vec)
+ return vec.iValue.toInt()
+ }
+
+ private inline fun setTypedVector(
+ key: String? = null,
+ length: Int,
+ vecType: FlexBufferType,
+ bitWidth: BitWidth,
+ crossinline writeBlock: (ByteWidth) -> Unit
+ ): Int {
+ val keyPos = putKey(key)
+ val byteWidth = align(bitWidth)
+ // Write vector. First the keys width/offset if available, and size.
+ // write the size
+ writeInt(length, byteWidth)
+
+ // Then the actual data.
+ val vloc: Int = buffer.writePosition
+ writeBlock(byteWidth)
+ stack.add(Value(vecType, keyPos, bitWidth, vloc.toULong()))
+ return vloc
+ }
+
+ private inline fun setTypedVec(key: String? = null, crossinline block: FlexBuffersBuilder.() -> Unit): Int {
+ val pos = startVector()
+ this.block()
+ return endTypedVector(pos, key)
+ }
+
+ public fun endTypedVector(position: Int, key: String? = null): Int =
+ endAnyVector(position) { createTypedVector(putKey(key), position, stack.size - position) }
+
+ private inline fun endAnyVector(start: Int, crossinline creationBlock: () -> Value): Int {
+ val vec = creationBlock()
+ // Remove temp elements and return vector.
+ while (stack.size > start) {
+ stack.removeLast()
+ }
+ stack.add(vec)
+ return vec.iValue.toInt()
+ }
+
+ private inline fun putKey(key: String? = null): Int {
+ if (key == null) return -1
+ return if ((shareFlag and SHARE_KEYS) != 0) {
+ stringKeyPool.getOrPut(key) {
+ val pos: Int = buffer.writePosition
+ buffer.put(key)
+ buffer.put(ZeroByte)
+ pos
+ }
+ } else {
+ val pos: Int = buffer.writePosition
+ buffer.put(key)
+ buffer.put(ZeroByte)
+ pos
+ }
+ }
+
+ private fun writeAny(toWrite: Value, byteWidth: ByteWidth) = when (toWrite.type) {
+ T_NULL, T_BOOL, T_INT, T_UINT -> writeInt(toWrite.iValue, byteWidth)
+ T_FLOAT -> writeDouble(toWrite.dValue, byteWidth)
+ else -> writeOffset(toWrite.iValue.toInt(), byteWidth)
+ }
+
+ private fun writeString(key: Int, s: String): Value {
+ val size = Utf8.encodedLength(s)
+ val bitWidth = size.toULong().widthInUBits()
+ val byteWidth = align(bitWidth)
+
+ writeInt(size, byteWidth)
+
+ val sloc: Int = buffer.writePosition
+ if (size > 0)
+ buffer.put(s, size)
+ buffer.put(ZeroByte)
+ return Value(T_STRING, key, bitWidth, sloc.toULong())
+ }
+
+ private fun writeDouble(toWrite: Double, byteWidth: ByteWidth): Unit = when (byteWidth.value) {
+ 4 -> buffer.put(toWrite.toFloat())
+ 8 -> buffer.put(toWrite)
+ else -> Unit
+ }
+
+ private fun writeOffset(toWrite: Int, byteWidth: ByteWidth) {
+ val relativeOffset = (buffer.writePosition - toWrite)
+ if (byteWidth.value != 8 && relativeOffset >= 1L shl byteWidth.value * 8) error("invalid offset $relativeOffset, writer pos ${buffer.writePosition}")
+ writeInt(relativeOffset, byteWidth)
+ }
+
+ private inline fun writeBlob(key: Int, blob: ByteArray, type: FlexBufferType, trailing: Boolean): Value {
+ val bitWidth = blob.size.toULong().widthInUBits()
+ val byteWidth = align(bitWidth)
+
+ writeInt(blob.size, byteWidth)
+
+ val sloc: Int = buffer.writePosition
+ buffer.put(blob, 0, blob.size)
+ if (trailing) {
+ buffer.put(ZeroByte)
+ }
+ return Value(type, key, bitWidth, sloc.toULong())
+ }
+
+ private fun writeIntArray(value: IntArray, byteWidth: ByteWidth) =
+ writeIntegerArray(0, value.size, byteWidth) { value[it].toULong() }
+
+ private fun writeIntArray(value: ShortArray, byteWidth: ByteWidth) =
+ writeIntegerArray(0, value.size, byteWidth) { value[it].toULong() }
+
+ private fun writeIntArray(value: LongArray, byteWidth: ByteWidth) =
+ writeIntegerArray(0, value.size, byteWidth) { value[it].toULong() }
+
+ private fun writeFloatArray(value: FloatArray) {
+ val byteWidth = Float.SIZE_BYTES
+ // since we know we are writing an array, we can avoid multiple copy/growth of the buffer by requesting
+ // the right size on the spot
+ buffer.requestCapacity(buffer.writePosition + (value.size * byteWidth))
+ value.forEach { buffer.put(it) }
+ }
+
+ private fun writeFloatArray(value: DoubleArray) {
+ val byteWidth = Double.SIZE_BYTES
+ // since we know we are writing an array, we can avoid multiple copy/growth of the buffer by requesting
+ // the right size on the spot
+ buffer.requestCapacity(buffer.writePosition + (value.size * byteWidth))
+ value.forEach { buffer.put(it) }
+ }
+
+ private inline fun writeIntegerArray(
+ start: Int,
+ size: Int,
+ byteWidth: ByteWidth,
+ crossinline valueBlock: (Int) -> ULong
+ ) {
+ // since we know we are writing an array, we can avoid multiple copy/growth of the buffer by requesting
+ // the right size on the spot
+ buffer.requestCapacity(buffer.writePosition + (size * byteWidth))
+ return when (byteWidth.value) {
+ 1 -> for (i in start until start + size) {
+ buffer.put(valueBlock(i).toUByte())
+ }
+ 2 -> for (i in start until start + size) {
+ buffer.put(valueBlock(i).toUShort())
+ }
+ 4 -> for (i in start until start + size) {
+ buffer.put(valueBlock(i).toUInt())
+ }
+ 8 -> for (i in start until start + size) {
+ buffer.put(valueBlock(i))
+ }
+ else -> Unit
+ }
+ }
+
+ private fun writeInt(value: Int, byteWidth: ByteWidth) = when (byteWidth.value) {
+ 1 -> buffer.put(value.toUByte())
+ 2 -> buffer.put(value.toUShort())
+ 4 -> buffer.put(value.toUInt())
+ 8 -> buffer.put(value.toULong())
+ else -> Unit
+ }
+
+ private fun writeInt(value: ULong, byteWidth: ByteWidth) = when (byteWidth.value) {
+ 1 -> buffer.put(value.toUByte())
+ 2 -> buffer.put(value.toUShort())
+ 4 -> buffer.put(value.toUInt())
+ 8 -> buffer.put(value)
+ else -> Unit
+ }
+
+ // Align to prepare for writing a scalar with a certain size.
+ // returns the amounts of bytes needed to be written.
+ private fun align(alignment: BitWidth): ByteWidth {
+ val byteWidth = 1 shl alignment.value
+ var padBytes = paddingBytes(buffer.writePosition, byteWidth)
+ while (padBytes-- != 0) {
+ buffer.put(ZeroByte)
+ }
+ return ByteWidth(byteWidth)
+ }
+
+ private fun calculateKeyVectorBitWidth(start: Int, length: Int): BitWidth {
+ val bitWidth = length.toULong().widthInUBits()
+ var width = bitWidth
+ val prefixElems = 1
+ // Check bit widths and types for all elements.
+ for (i in start until stack.size) {
+ val elemWidth = elemWidth(T_KEY, W_8, stack[i].key.toLong(), buffer.writePosition, i + prefixElems)
+ width = width.max(elemWidth)
+ }
+ return width
+ }
+
+ private fun createKeyVector(start: Int, length: Int): Value {
+ // Figure out smallest bit width we can store this vector with.
+ val bitWidth = calculateKeyVectorBitWidth(start, length)
+ val byteWidth = align(bitWidth)
+ // Write vector. First the keys width/offset if available, and size.
+ writeInt(length, byteWidth)
+ // Then the actual data.
+ val vloc = buffer.writePosition.toULong()
+ for (i in start until stack.size) {
+ val pos = stack[i].key
+ if (pos == -1) error("invalid position $pos for key")
+ writeOffset(stack[i].key, byteWidth)
+ }
+ // Then the types.
+ return Value(T_VECTOR_KEY, -1, bitWidth, vloc)
+ }
+
+ private inline fun createVector(key: Int, start: Int, length: Int, keys: Value? = null): Value {
+ return createAnyVector(key, start, length, T_VECTOR, keys) {
+ // add types since we are not creating a typed vector.
+ for (i in start until stack.size) {
+ buffer.put(stack[i].storedPackedType(it))
+ }
+ }
+ }
+
+ private fun putMap(key: Int, start: Int, length: Int, keys: Value? = null): Value {
+ return createAnyVector(key, start, length, T_MAP, keys) {
+ // add types since we are not creating a typed vector.
+ for (i in start until stack.size) {
+ buffer.put(stack[i].storedPackedType(it))
+ }
+ }
+ }
+
+ private inline fun createTypedVector(key: Int, start: Int, length: Int, keys: Value? = null): Value {
+ // We assume the callers of this method guarantees all elements are of the same type.
+ val elementType: FlexBufferType = stack[start].type
+ for (i in start + 1 until length) {
+ if (elementType != stack[i].type) error("TypedVector does not support array of different element types")
+ }
+ if (!elementType.isTypedVectorElementType()) error("TypedVector does not support this element type")
+ return createAnyVector(key, start, length, elementType.toTypedVector(), keys)
+ }
+
+ private inline fun createAnyVector(
+ key: Int,
+ start: Int,
+ length: Int,
+ type: FlexBufferType,
+ keys: Value? = null,
+ crossinline typeBlock: (BitWidth) -> Unit = {}
+ ): Value {
+ // Figure out smallest bit width we can store this vector with.
+ var bitWidth = W_8.max(length.toULong().widthInUBits())
+ var prefixElems = 1
+ if (keys != null) {
+ // If this vector is part of a map, we will pre-fix an offset to the keys
+ // to this vector.
+ bitWidth = bitWidth.max(keys.elemWidth(buffer.writePosition, 0))
+ prefixElems += 2
+ }
+ // Check bit widths and types for all elements.
+ for (i in start until stack.size) {
+ val elemWidth = stack[i].elemWidth(buffer.writePosition, i + prefixElems)
+ bitWidth = bitWidth.max(elemWidth)
+ }
+ val byteWidth = align(bitWidth)
+ // Write vector. First the keys width/offset if available, and size.
+ if (keys != null) {
+ writeOffset(keys.iValue.toInt(), byteWidth)
+ writeInt(1 shl keys.minBitWidth.value, byteWidth)
+ }
+ // write the size
+ writeInt(length, byteWidth)
+
+ // Then the actual data.
+ val vloc: Int = buffer.writePosition
+ for (i in start until stack.size) {
+ writeAny(stack[i], byteWidth)
+ }
+
+ // Optionally you can introduce the types for non-typed vector
+ typeBlock(bitWidth)
+ return Value(type, key, bitWidth, vloc.toULong())
+ }
+
+ // A lambda to sort map keys
+ internal val keyComparator = object : Comparator<Value> {
+ override fun compare(a: Value, b: Value): Int {
+ var ia: Int = a.key
+ var io: Int = b.key
+ var c1: Byte
+ var c2: Byte
+ do {
+ c1 = buffer[ia]
+ c2 = buffer[io]
+ if (c1.toInt() == 0) return c1 - c2
+ ia++
+ io++
+ } while (c1 == c2)
+ return c1 - c2
+ }
+ }
+
+ public companion object {
+ /**
+ * No keys or strings will be shared
+ */
+ public const val SHARE_NONE: Int = 0
+
+ /**
+ * Keys will be shared between elements. Identical keys will only be serialized once, thus possibly saving space.
+ * But serialization performance might be slower and consumes more memory.
+ */
+ public const val SHARE_KEYS: Int = 1
+
+ /**
+ * Strings will be shared between elements. Identical strings will only be serialized once, thus possibly saving space.
+ * But serialization performance might be slower and consumes more memory. This is ideal if you expect many repeated
+ * strings on the message.
+ */
+ public const val SHARE_STRINGS: Int = 2
+
+ /**
+ * Strings and keys will be shared between elements.
+ */
+ public const val SHARE_KEYS_AND_STRINGS: Int = 3
+ }
+}
diff --git a/kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/FlexBuffersInternals.kt b/kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/FlexBuffersInternals.kt
new file mode 100644
index 0000000..15d0027
--- /dev/null
+++ b/kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/FlexBuffersInternals.kt
@@ -0,0 +1,251 @@
+/*
+ * Copyright 2021 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.
+ */
+@file:Suppress("NOTHING_TO_INLINE")
+
+package com.google.flatbuffers.kotlin
+
+public inline class BitWidth(public val value: Int) {
+ public inline fun max(other: BitWidth): BitWidth = if (this.value >= other.value) this else other
+}
+
+public inline class ByteWidth(public val value: Int)
+
+public inline class FlexBufferType(public val value: Int) {
+ public operator fun minus(other: FlexBufferType): FlexBufferType = FlexBufferType(this.value - other.value)
+ public operator fun plus(other: FlexBufferType): FlexBufferType = FlexBufferType(this.value + other.value)
+ public operator fun compareTo(other: FlexBufferType): Int = this.value - other.value
+}
+
+internal operator fun Int.times(width: ByteWidth): Int = this * width.value
+internal operator fun Int.minus(width: ByteWidth): Int = this - width.value
+internal operator fun Int.plus(width: ByteWidth): Int = this + width.value
+internal operator fun Int.minus(type: FlexBufferType): Int = this - type.value
+
+// Returns a Key string from the buffer starting at index [start]. Key Strings are stored as
+// C-Strings, ending with '\0'. If zero byte not found returns empty string.
+internal inline fun ReadBuffer.getKeyString(start: Int): String {
+ val i = findFirst(0.toByte(), start)
+ return if (i >= 0) getString(start, i - start) else ""
+}
+
+// read unsigned int with size byteWidth and return as a 64-bit integer
+internal inline fun ReadBuffer.readULong(end: Int, byteWidth: ByteWidth): ULong {
+ return when (byteWidth.value) {
+ 1 -> this.getUByte(end).toULong()
+ 2 -> this.getUShort(end).toULong()
+ 4 -> this.getUInt(end).toULong()
+ 8 -> this.getULong(end)
+ else -> error("invalid byte width $byteWidth for scalar unsigned integer")
+ }
+}
+
+internal inline fun ReadBuffer.readFloat(end: Int, byteWidth: ByteWidth): Double {
+ return when (byteWidth.value) {
+ 4 -> this.getFloat(end).toDouble()
+ 8 -> this.getDouble(end)
+ else -> error("invalid byte width $byteWidth for floating point scalar") // we should never reach here
+ }
+}
+// return position on the [ReadBuffer] of the element that the offset is pointing to
+// we assume all offset fits on a int, since ReadBuffer operates with that assumption
+internal inline fun ReadBuffer.indirect(offset: Int, byteWidth: ByteWidth): Int = offset - readInt(offset, byteWidth)
+// returns the size of an array-like element from [ReadBuffer].
+internal inline fun ReadBuffer.readSize(end: Int, byteWidth: ByteWidth) = readInt(end - byteWidth, byteWidth)
+internal inline fun ReadBuffer.readUInt(end: Int, byteWidth: ByteWidth): UInt = readULong(end, byteWidth).toUInt()
+internal inline fun ReadBuffer.readInt(end: Int, byteWidth: ByteWidth): Int = readULong(end, byteWidth).toInt()
+internal inline fun ReadBuffer.readLong(end: Int, byteWidth: ByteWidth): Long = readULong(end, byteWidth).toLong()
+
+internal fun IntArray.widthInUBits(): BitWidth = arrayWidthInUBits(this.size) { this[it].toULong().widthInUBits() }
+internal fun ShortArray.widthInUBits(): BitWidth = arrayWidthInUBits(this.size) { this[it].toULong().widthInUBits() }
+internal fun LongArray.widthInUBits(): BitWidth = arrayWidthInUBits(this.size) { this[it].toULong().widthInUBits() }
+
+private inline fun arrayWidthInUBits(size: Int, crossinline elemWidthBlock: (Int) -> BitWidth): BitWidth {
+ // Figure out smallest bit width we can store this vector with.
+ var bitWidth = W_8.max(size.toULong().widthInUBits())
+ // Check bit widths and types for all elements.
+ for (i in 0 until size) {
+ // since we know its inline types we can just assume elmentWidth to be the value width in bits.
+ bitWidth = bitWidth.max(elemWidthBlock(i))
+ }
+ return bitWidth
+}
+
+internal fun ULong.widthInUBits(): BitWidth = when {
+ this <= MAX_UBYTE_ULONG -> W_8
+ this <= UShort.MAX_VALUE -> W_16
+ this <= UInt.MAX_VALUE -> W_32
+ else -> W_64
+}
+
+// returns the number of bytes needed for padding the scalar of size scalarSize.
+internal inline fun paddingBytes(bufSize: Int, scalarSize: Int): Int = bufSize.inv() + 1 and scalarSize - 1
+
+internal inline fun FlexBufferType.isInline(): Boolean = this.value <= T_FLOAT.value || this == T_BOOL
+
+internal fun FlexBufferType.isScalar(): Boolean = when (this) {
+ T_INT, T_UINT, T_FLOAT, T_BOOL -> true
+ else -> false
+}
+
+internal fun FlexBufferType.isIndirectScalar(): Boolean = when (this) {
+ T_INDIRECT_INT, T_INDIRECT_UINT, T_INDIRECT_FLOAT -> true
+ else -> false
+}
+
+internal fun FlexBufferType.isTypedVector(): Boolean =
+ this >= T_VECTOR_INT && this <= T_VECTOR_STRING_DEPRECATED || this == T_VECTOR_BOOL
+
+internal fun FlexBufferType.isTypedVectorElementType(): Boolean = (this.value in T_INT.value..T_KEY.value) || this == T_BOOL
+
+// returns the typed vector of a given scalar type.
+internal fun FlexBufferType.toTypedVector(): FlexBufferType = (this - T_INT) + T_VECTOR_INT
+// returns the element type of a given typed vector.
+internal fun FlexBufferType.toElementTypedVector(): FlexBufferType = this - T_VECTOR_INT + T_INT
+
+// Holds information about the elements inserted on the buffer.
+internal data class Value(
+ var type: FlexBufferType = T_INT,
+ var key: Int = -1,
+ var minBitWidth: BitWidth = W_8,
+ var iValue: ULong = 0UL, // integer value
+ var dValue: Double = 0.0 // TODO(paulovap): maybe we can keep floating type on iValue as well.
+) { // float value
+
+ inline fun storedPackedType(parentBitWidth: BitWidth = W_8): Byte = packedType(storedWidth(parentBitWidth), type)
+
+ private inline fun packedType(bitWidth: BitWidth, type: FlexBufferType): Byte = (bitWidth.value or (type.value shl 2)).toByte()
+
+ private inline fun storedWidth(parentBitWidth: BitWidth): BitWidth =
+ if (type.isInline()) minBitWidth.max(parentBitWidth) else minBitWidth
+
+ fun elemWidth(bufSize: Int, elemIndex: Int): BitWidth =
+ elemWidth(type, minBitWidth, iValue.toLong(), bufSize, elemIndex)
+}
+
+internal fun elemWidth(
+ type: FlexBufferType,
+ minBitWidth: BitWidth,
+ iValue: Long,
+ bufSize: Int,
+ elemIndex: Int
+): BitWidth {
+ if (type.isInline()) return minBitWidth
+
+ // We have an absolute offset, but want to store a relative offset
+ // elem_index elements beyond the current buffer end. Since whether
+ // the relative offset fits in a certain byte_width depends on
+ // the size of the elements before it (and their alignment), we have
+ // to test for each size in turn.
+ // Original implementation checks for largest scalar
+ // which is long unsigned int
+ var byteWidth = 1
+ while (byteWidth <= 32) {
+ // Where are we going to write this offset?
+ val offsetLoc: Int = bufSize + paddingBytes(bufSize, byteWidth) + elemIndex * byteWidth
+ // Compute relative offset.
+ val offset: Int = offsetLoc - iValue.toInt()
+ // Does it fit?
+ val bitWidth = offset.toULong().widthInUBits()
+ if (1 shl bitWidth.value == byteWidth) return bitWidth
+ byteWidth *= 2
+ }
+ return W_64
+}
+
+// For debugging purposes, convert type to a human-readable string.
+internal fun FlexBufferType.typeToString(): String = when (this) {
+ T_NULL -> "Null"
+ T_INT -> "Int"
+ T_UINT -> "UInt"
+ T_FLOAT -> "Float"
+ T_KEY -> "Key"
+ T_STRING -> "String"
+ T_INDIRECT_INT -> "IndirectInt"
+ T_INDIRECT_UINT -> "IndirectUInt"
+ T_INDIRECT_FLOAT -> "IndirectFloat"
+ T_MAP -> "Map"
+ T_VECTOR -> "Vector"
+ T_VECTOR_INT -> "IntVector"
+ T_VECTOR_UINT -> "UIntVector"
+ T_VECTOR_FLOAT -> "FloatVector"
+ T_VECTOR_KEY -> "KeyVector"
+ T_VECTOR_STRING_DEPRECATED -> "StringVectorDeprecated"
+ T_VECTOR_INT2 -> "Int2Vector"
+ T_VECTOR_UINT2 -> "UInt2Vector"
+ T_VECTOR_FLOAT2 -> "Float2Vector"
+ T_VECTOR_INT3 -> "Int3Vector"
+ T_VECTOR_UINT3 -> "UInt3Vector"
+ T_VECTOR_FLOAT3 -> "Float3Vector"
+ T_VECTOR_INT4 -> "Int4Vector"
+ T_VECTOR_UINT4 -> "UInt4Vector"
+ T_VECTOR_FLOAT4 -> "Float4Vector"
+ T_BLOB -> "BlobVector"
+ T_BOOL -> "BoolVector"
+ T_VECTOR_BOOL -> "BoolVector"
+ else -> "UnknownType"
+}
+
+// Few repeated values used in hot path is cached here
+internal val emptyBuffer = ArrayReadWriteBuffer(1)
+internal fun emptyBlob() = Blob(emptyBuffer, 1, ByteWidth(1))
+internal fun emptyVector() = Vector(emptyBuffer, 1, ByteWidth(1))
+internal fun emptyMap() = Map(ArrayReadWriteBuffer(3), 3, ByteWidth(1))
+internal fun nullReference() = Reference(emptyBuffer, 1, ByteWidth(0), T_NULL.value)
+internal fun nullKey() = Key(emptyBuffer, 1)
+
+internal const val ZeroByte = 0.toByte()
+internal const val MAX_UBYTE_ULONG = 255UL
+internal const val MAX_UBYTE = 255
+internal const val MAX_USHORT = 65535
+
+// value bit width possible sizes
+internal val W_8 = BitWidth(0)
+internal val W_16 = BitWidth(1)
+internal val W_32 = BitWidth(2)
+internal val W_64 = BitWidth(3)
+
+// These are used as the upper 6 bits of a type field to indicate the actual type.
+internal val T_INVALID = FlexBufferType(-1)
+internal val T_NULL = FlexBufferType(0)
+internal val T_INT = FlexBufferType(1)
+internal val T_UINT = FlexBufferType(2)
+internal val T_FLOAT = FlexBufferType(3) // Types above stored inline, types below are stored in an offset.
+internal val T_KEY = FlexBufferType(4)
+internal val T_STRING = FlexBufferType(5)
+internal val T_INDIRECT_INT = FlexBufferType(6)
+internal val T_INDIRECT_UINT = FlexBufferType(7)
+internal val T_INDIRECT_FLOAT = FlexBufferType(8)
+internal val T_MAP = FlexBufferType(9)
+internal val T_VECTOR = FlexBufferType(10) // Untyped.
+internal val T_VECTOR_INT = FlexBufferType(11) // Typed any size = stores no type table).
+internal val T_VECTOR_UINT = FlexBufferType(12)
+internal val T_VECTOR_FLOAT = FlexBufferType(13)
+internal val T_VECTOR_KEY = FlexBufferType(14)
+// DEPRECATED, use FBT_VECTOR or FBT_VECTOR_KEY instead.
+// more info on https://github.com/google/flatbuffers/issues/5627.
+internal val T_VECTOR_STRING_DEPRECATED = FlexBufferType(15)
+internal val T_VECTOR_INT2 = FlexBufferType(16) // Typed tuple = no type table; no size field).
+internal val T_VECTOR_UINT2 = FlexBufferType(17)
+internal val T_VECTOR_FLOAT2 = FlexBufferType(18)
+internal val T_VECTOR_INT3 = FlexBufferType(19) // Typed triple = no type table; no size field).
+internal val T_VECTOR_UINT3 = FlexBufferType(20)
+internal val T_VECTOR_FLOAT3 = FlexBufferType(21)
+internal val T_VECTOR_INT4 = FlexBufferType(22) // Typed quad = no type table; no size field).
+internal val T_VECTOR_UINT4 = FlexBufferType(23)
+internal val T_VECTOR_FLOAT4 = FlexBufferType(24)
+internal val T_BLOB = FlexBufferType(25)
+internal val T_BOOL = FlexBufferType(26)
+internal val T_VECTOR_BOOL = FlexBufferType(36) // To Allow the same type of conversion of type to vector type
diff --git a/kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/JSON.kt b/kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/JSON.kt
new file mode 100644
index 0000000..ee20138
--- /dev/null
+++ b/kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/JSON.kt
@@ -0,0 +1,828 @@
+/*
+ * Copyright 2021 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.
+ */
+@file:Suppress("NOTHING_TO_INLINE")
+
+package com.google.flatbuffers.kotlin
+
+import com.google.flatbuffers.kotlin.FlexBuffersBuilder.Companion.SHARE_KEYS_AND_STRINGS
+import kotlin.experimental.and
+import kotlin.math.pow
+
+/**
+ * Returns a minified version of this FlexBuffer as a JSON.
+ */
+public fun Reference.toJson(): String = ArrayReadWriteBuffer(1024).let {
+ toJson(it)
+ val data = it.data() // it.getString(0, it.writePosition)
+ return data.decodeToString(0, it.writePosition)
+}
+
+/**
+ * Returns a minified version of this FlexBuffer as a JSON.
+ * @param out [ReadWriteBuffer] the JSON will be written.
+ */
+public fun Reference.toJson(out: ReadWriteBuffer) {
+ when (type) {
+ T_STRING -> {
+ val start = buffer.indirect(end, parentWidth)
+ val size = buffer.readULong(start - byteWidth, byteWidth).toInt()
+ out.jsonEscape(buffer, start, size)
+ }
+ T_KEY -> {
+ val start = buffer.indirect(end, parentWidth)
+ val end = buffer.findFirst(0.toByte(), start)
+ out.jsonEscape(buffer, start, end - start)
+ }
+ T_BLOB -> {
+ val blob = toBlob()
+ out.jsonEscape(out, blob.end, blob.size)
+ }
+ T_INT -> out.put(toLong().toString())
+ T_UINT -> out.put(toULong().toString())
+ T_FLOAT -> out.put(toDouble().toString())
+ T_NULL -> out.put("null")
+ T_BOOL -> out.put(toBoolean().toString())
+ T_MAP -> toMap().toJson(out)
+ T_VECTOR, T_VECTOR_BOOL, T_VECTOR_FLOAT, T_VECTOR_INT,
+ T_VECTOR_UINT, T_VECTOR_KEY, T_VECTOR_STRING_DEPRECATED -> toVector().toJson(out)
+ else -> error("Unable to convert type ${type.typeToString()} to JSON")
+ }
+}
+
+/**
+ * Returns a minified version of this FlexBuffer as a JSON.
+ */
+public fun Map.toJson(): String = ArrayReadWriteBuffer(1024).let { toJson(it); it.toString() }
+
+/**
+ * Returns a minified version of this FlexBuffer as a JSON.
+ * @param out [ReadWriteBuffer] the JSON will be written.
+ */
+public fun Map.toJson(out: ReadWriteBuffer) {
+ out.put('{'.toByte())
+ // key values pairs
+ for (i in 0 until size) {
+ val key = keyAt(i)
+ out.jsonEscape(buffer, key.start, key.sizeInBytes)
+ out.put(':'.toByte())
+ get(i).toJson(out)
+ if (i != size - 1) {
+ out.put(','.toByte())
+ }
+ }
+ // close bracket
+ out.put('}'.toByte())
+}
+
+/**
+ * Returns a minified version of this FlexBuffer as a JSON.
+ */
+public fun Vector.toJson(): String = ArrayReadWriteBuffer(1024).let { toJson(it); it.toString() }
+
+/**
+ * Returns a minified version of this FlexBuffer as a JSON.
+ * @param out that the JSON is being concatenated.
+ */
+public fun Vector.toJson(out: ReadWriteBuffer) {
+ out.put('['.toByte())
+ for (i in 0 until size) {
+ get(i).toJson(out)
+ if (i != size - 1) {
+ out.put(','.toByte())
+ }
+ }
+ out.put(']'.toByte())
+}
+
+/**
+ * JSONParser class is used to parse a JSON as FlexBuffers. Calling [JSONParser.parse] fiils [output]
+ * and returns a [Reference] ready to be used.
+ */
+public class JSONParser(public var output: FlexBuffersBuilder = FlexBuffersBuilder(1024, SHARE_KEYS_AND_STRINGS)) {
+ private var readPos = 0
+ private var scopes = ScopeStack()
+
+ /**
+ * Parse a json as [String] and returns a [Reference] to a FlexBuffer.
+ */
+ public fun parse(data: String): Reference = parse(ArrayReadBuffer(data.encodeToByteArray()))
+
+ /**
+ * Parse a json as [ByteArray] and returns a [Reference] to a FlexBuffer.
+ */
+ public fun parse(data: ByteArray): Reference = parse(ArrayReadBuffer(data))
+
+ /**
+ * Parse a json as [ReadBuffer] and returns a [Reference] to a FlexBuffer.
+ */
+ public fun parse(data: ReadBuffer): Reference {
+ reset()
+ parseValue(data, nextToken(data), null)
+ if (readPos < data.limit) {
+ val tok = skipWhitespace(data)
+ if (tok != CHAR_EOF) {
+ makeError(data, "Extraneous charaters after parse has finished", tok)
+ }
+ }
+ output.finish()
+ return getRoot(output.buffer)
+ }
+
+ private fun parseValue(data: ReadBuffer, token: Token, key: String? = null): FlexBufferType {
+ return when (token) {
+ TOK_BEGIN_OBJECT -> parseObject(data, key)
+ TOK_BEGIN_ARRAY -> parseArray(data, key)
+ TOK_TRUE -> T_BOOL.also { output[key] = true }
+ TOK_FALSE -> T_BOOL.also { output[key] = false }
+ TOK_NULL -> T_NULL.also { output.putNull(key) }
+ TOK_BEGIN_QUOTE -> parseString(data, key)
+ TOK_NUMBER -> parseNumber(data, data.data(), key)
+ else -> makeError(data, "Unexpected Character while parsing", 'x'.toByte())
+ }
+ }
+
+ private fun parseObject(data: ReadBuffer, key: String? = null): FlexBufferType {
+ this.scopes.push(SCOPE_OBJ_EMPTY)
+
+ val fPos = output.startMap()
+ val limit = data.limit
+ while (readPos <= limit) {
+ when (val tok = nextToken(data)) {
+ TOK_END_OBJECT -> {
+ this.scopes.pop()
+ output.endMap(fPos, key); return T_MAP
+ }
+ TOK_BEGIN_QUOTE -> {
+ val childKey = readString(data)
+ parseValue(data, nextToken(data), childKey)
+ }
+ else -> makeError(data, "Expecting start of object key", tok)
+ }
+ }
+ makeError(data, "Unable to parse the object", "x".toByte())
+ }
+
+ private fun parseArray(data: ReadBuffer, key: String? = null): FlexBufferType {
+ this.scopes.push(SCOPE_ARRAY_EMPTY)
+ val fPos = output.startVector()
+ var elementType = T_INVALID
+ var multiType = false
+ val limit = data.limit
+
+ while (readPos <= limit) {
+ when (val tok = nextToken(data)) {
+ TOK_END_ARRAY -> {
+ this.scopes.pop()
+ return if (!multiType && elementType.isScalar()) {
+ output.endTypedVector(fPos, key)
+ elementType.toElementTypedVector()
+ } else {
+ output.endVector(key, fPos)
+ T_VECTOR
+ }
+ }
+
+ else -> {
+ val newType = parseValue(data, tok, null)
+
+ if (elementType == T_INVALID) {
+ elementType = newType
+ } else if (newType != elementType) {
+ multiType = true
+ }
+ }
+ }
+ }
+ makeError(data, "Unable to parse the array")
+ }
+
+ private fun parseNumber(data: ReadBuffer, array: ByteArray, key: String?): FlexBufferType {
+ val ary = array
+ var cursor = readPos
+ var c = data[readPos++]
+ var useDouble = false
+ val limit = ary.size
+ var sign = 1
+ var double: Double
+ var long = 0L
+ var digits = 0
+
+ if (c == CHAR_MINUS) {
+ cursor++
+ checkEOF(data, cursor)
+ c = ary[cursor]
+ sign = -1
+ }
+
+ // peek first byte
+ when (c) {
+ CHAR_0 -> {
+ cursor++
+ if (cursor != limit) {
+ c = ary[cursor]
+ }
+ }
+ !in CHAR_0..CHAR_9 -> makeError(data, "Invalid Number", c)
+ else -> {
+ do {
+ val digit = c - CHAR_0
+ // double = 10.0 * double + digit
+ long = 10 * long + digit
+ digits++
+ cursor++
+ if (cursor == limit) break
+ c = ary[cursor]
+ } while (c in CHAR_0..CHAR_9)
+ }
+ }
+
+ var exponent = 0
+ // If we find '.' we need to convert to double
+ if (c == CHAR_DOT) {
+ useDouble = true
+ checkEOF(data, cursor)
+ c = ary[++cursor]
+ if (c < CHAR_0 || c > CHAR_9) {
+ makeError(data, "Invalid Number", c)
+ }
+ do {
+ // double = double * 10 + (tok - CHAR_0)
+ long = 10 * long + (c - CHAR_0)
+ digits++
+ --exponent
+ cursor++
+ if (cursor == limit) break
+ c = ary[cursor]
+ } while (c in CHAR_0..CHAR_9)
+ }
+
+ // If we find 'e' we need to convert to double
+ if (c == CHAR_e || c == CHAR_E) {
+ useDouble = true
+ ++cursor
+ checkEOF(data, cursor)
+ c = ary[cursor]
+ var negativeExponent = false
+ if (c == CHAR_MINUS) {
+ ++cursor
+ checkEOF(data, cursor)
+ negativeExponent = true
+ c = ary[cursor]
+ } else if (c == CHAR_PLUS) {
+ ++cursor
+ checkEOF(data, cursor)
+ c = ary[cursor]
+ }
+ if (c < CHAR_0 || c > CHAR_9) {
+ makeError(data, "Missing exponent", c)
+ }
+ var exp = 0
+ do {
+ val digit = c - CHAR_0
+ exp = 10 * exp + digit
+ ++cursor
+ if (cursor == limit) break
+ c = ary[cursor]
+ } while (c in CHAR_0..CHAR_9)
+
+ exponent += if (negativeExponent) -exp else exp
+ }
+
+ if (digits > 17 || exponent < -19 || exponent > 19) {
+ // if the float number is not simple enough
+ // we use language's Double parsing, which is slower but
+ // produce more expected results for extreme numbers.
+ val firstPos = readPos - 1
+ val str = data.getString(firstPos, cursor - firstPos)
+ if (useDouble) {
+ double = str.toDouble()
+ output[key] = double
+ } else {
+ long = str.toLong()
+ output[key] = long
+ }
+ } else {
+ // this happens on single numbers outside any object
+ // or array
+ if (useDouble || exponent != 0) {
+ double = if (long == 0L) 0.0 else long.toDouble() * 10.0.pow(exponent)
+ double *= sign
+ output[key] = double
+ } else {
+ long *= sign
+ output[key] = long
+ }
+ }
+ readPos = cursor
+ return if (useDouble) T_FLOAT else T_INT
+ }
+
+ private fun parseString(data: ReadBuffer, key: String?): FlexBufferType {
+ output[key] = readString(data)
+ return T_STRING
+ }
+
+ private fun readString(data: ReadBuffer): String {
+ val limit = data.limit
+ if (data is ArrayReadBuffer) {
+ val ary = data.data()
+ // enables range check elimination
+ return readString(data, limit) { ary[it] }
+ }
+ return readString(data, limit) { data[it] }
+ }
+
+ private inline fun readString(data: ReadBuffer, limit: Int, crossinline fetch: (Int) -> Byte): String {
+ var cursorPos = readPos
+ var foundEscape = false
+ var currentChar: Byte = 0
+ // we loop over every 4 bytes until find any non-plain char
+ while (limit - cursorPos >= 4) {
+ currentChar = fetch(cursorPos)
+ if (!isPlainStringChar(currentChar)) {
+ foundEscape = true
+ break
+ }
+ currentChar = fetch(cursorPos + 1)
+ if (!isPlainStringChar(currentChar)) {
+ cursorPos += 1
+ foundEscape = true
+ break
+ }
+ currentChar = fetch(cursorPos + 2)
+ if (!isPlainStringChar(currentChar)) {
+ cursorPos += 2
+ foundEscape = true
+ break
+ }
+ currentChar = fetch(cursorPos + 3)
+ if (!isPlainStringChar(currentChar)) {
+ cursorPos += 3
+ foundEscape = true
+ break
+ }
+ cursorPos += 4
+ }
+ if (!foundEscape) {
+ // if non-plain string char is not found we loop over
+ // the remaining bytes
+ while (true) {
+ if (cursorPos >= limit) {
+ error("Unexpected end of string")
+ }
+ currentChar = fetch(cursorPos)
+ if (!isPlainStringChar(currentChar)) {
+ break
+ }
+ ++cursorPos
+ }
+ }
+ if (currentChar == CHAR_DOUBLE_QUOTE) {
+ val str = data.getString(readPos, cursorPos - readPos)
+ readPos = cursorPos + 1
+ return str
+ }
+ if (currentChar in 0..0x1f) {
+ error("Illegal Codepoint")
+ } else {
+ // backslash or >0x7f
+ return readStringSlow(data, currentChar, cursorPos)
+ }
+ }
+
+ private fun readStringSlow(data: ReadBuffer, first: Byte, lastPos: Int): String {
+ var cursorPos = lastPos
+
+ var endOfString = lastPos
+ while (true) {
+ val pos = data.findFirst(CHAR_DOUBLE_QUOTE, endOfString)
+ when {
+ pos == -1 -> makeError(data, "Unexpected EOF, missing end of string '\"'", first)
+ data[pos - 1] == CHAR_BACKSLASH && data[pos - 2] != CHAR_BACKSLASH -> {
+ // here we are checking for double quotes preceded by backslash. eg \"
+ // we have to look past pos -2 to make sure that the backlash is not
+ // part of a previous escape, eg "\\"
+ endOfString = pos + 1
+ }
+ else -> {
+ endOfString = pos; break
+ }
+ }
+ }
+ // copy everything before the escape
+ val builder = StringBuilder(data.getString(readPos, lastPos - readPos))
+ while (true) {
+ when (val pos = data.findFirst(CHAR_BACKSLASH, cursorPos, endOfString)) {
+ -1 -> {
+ val doubleQuotePos = data.findFirst(CHAR_DOUBLE_QUOTE, cursorPos)
+ if (doubleQuotePos == -1) makeError(data, "Reached EOF before enclosing string", first)
+ val rest = data.getString(cursorPos, doubleQuotePos - cursorPos)
+ builder.append(rest)
+ readPos = doubleQuotePos + 1
+ return builder.toString()
+ }
+
+ else -> {
+ // we write everything up to \
+ builder.append(data.getString(cursorPos, pos - cursorPos))
+ val c = data[pos + 1]
+ builder.append(readEscapedChar(data, c, pos))
+ cursorPos = pos + if (c == CHAR_u) 6 else 2
+ }
+ }
+ }
+ }
+
+ private inline fun isPlainStringChar(c: Byte): Boolean {
+ val flags = parseFlags
+ // return c in 0x20..0x7f && c != 0x22.toByte() && c != 0x5c.toByte()
+ return (flags[c.toInt() and 0xFF] and 1) != 0.toByte()
+ }
+
+ private inline fun isWhitespace(c: Byte): Boolean {
+ val flags = parseFlags
+ // return c == '\r'.toByte() || c == '\n'.toByte() || c == '\t'.toByte() || c == ' '.toByte()
+ return (flags[c.toInt() and 0xFF] and 2) != 0.toByte()
+ }
+
+ private fun reset() {
+ readPos = 0
+ output.clear()
+ scopes.reset()
+ }
+
+ private fun nextToken(data: ReadBuffer): Token {
+ val scope = this.scopes.last
+
+ when (scope) {
+ SCOPE_ARRAY_EMPTY -> this.scopes.last = SCOPE_ARRAY_FILLED
+ SCOPE_ARRAY_FILLED -> {
+ when (val c = skipWhitespace(data)) {
+ CHAR_CLOSE_ARRAY -> return TOK_END_ARRAY
+ CHAR_COMMA -> Unit
+ else -> makeError(data, "Unfinished Array", c)
+ }
+ }
+ SCOPE_OBJ_EMPTY, SCOPE_OBJ_FILLED -> {
+ this.scopes.last = SCOPE_OBJ_KEY
+ // Look for a comma before the next element.
+ if (scope == SCOPE_OBJ_FILLED) {
+ when (val c = skipWhitespace(data)) {
+ CHAR_CLOSE_OBJECT -> return TOK_END_OBJECT
+ CHAR_COMMA -> Unit
+ else -> makeError(data, "Unfinished Object", c)
+ }
+ }
+ return when (val c = skipWhitespace(data)) {
+ CHAR_DOUBLE_QUOTE -> TOK_BEGIN_QUOTE
+ CHAR_CLOSE_OBJECT -> if (scope != SCOPE_OBJ_FILLED) {
+ TOK_END_OBJECT
+ } else {
+ makeError(data, "Expected Key", c)
+ }
+ else -> {
+ makeError(data, "Expected Key/Value", c)
+ }
+ }
+ }
+ SCOPE_OBJ_KEY -> {
+ this.scopes.last = SCOPE_OBJ_FILLED
+ when (val c = skipWhitespace(data)) {
+ CHAR_COLON -> Unit
+ else -> makeError(data, "Expect ${CHAR_COLON.print()}", c)
+ }
+ }
+ SCOPE_DOC_EMPTY -> this.scopes.last = SCOPE_DOC_FILLED
+ SCOPE_DOC_FILLED -> {
+ val c = skipWhitespace(data)
+ if (c != CHAR_EOF)
+ makeError(data, "Root object already finished", c)
+ return TOK_EOF
+ }
+ }
+
+ val c = skipWhitespace(data)
+ when (c) {
+ CHAR_CLOSE_ARRAY -> if (scope == SCOPE_ARRAY_EMPTY) return TOK_END_ARRAY
+ CHAR_COLON -> makeError(data, "Unexpected character", c)
+ CHAR_DOUBLE_QUOTE -> return TOK_BEGIN_QUOTE
+ CHAR_OPEN_ARRAY -> return TOK_BEGIN_ARRAY
+ CHAR_OPEN_OBJECT -> return TOK_BEGIN_OBJECT
+ CHAR_t -> {
+ checkEOF(data, readPos + 2)
+ // 0x65757274 is equivalent to ['t', 'r', 'u', 'e' ] as a 4 byte Int
+ if (data.getInt(readPos - 1) != 0x65757274) {
+ makeError(data, "Expecting keyword \"true\"", c)
+ }
+ readPos += 3
+ return TOK_TRUE
+ }
+ CHAR_n -> {
+ checkEOF(data, readPos + 2)
+ // 0x6c6c756e is equivalent to ['n', 'u', 'l', 'l' ] as a 4 byte Int
+ if (data.getInt(readPos - 1) != 0x6c6c756e) {
+ makeError(data, "Expecting keyword \"null\"", c)
+ }
+ readPos += 3
+ return TOK_NULL
+ }
+ CHAR_f -> {
+ checkEOF(data, readPos + 3)
+ // 0x65736c61 is equivalent to ['a', 'l', 's', 'e' ] as a 4 byte Int
+ if (data.getInt(readPos) != 0x65736c61) {
+ makeError(data, "Expecting keyword \"false\"", c)
+ }
+ readPos += 4
+ return TOK_FALSE
+ }
+ CHAR_0, CHAR_1, CHAR_2, CHAR_3, CHAR_4, CHAR_5,
+ CHAR_6, CHAR_7, CHAR_8, CHAR_9, CHAR_MINUS -> return TOK_NUMBER.also {
+ readPos-- // rewind one position so we don't lose first digit
+ }
+ }
+ makeError(data, "Expecting element", c)
+ }
+
+ // keeps increasing [readPos] until finds a non-whitespace byte
+ private inline fun skipWhitespace(data: ReadBuffer): Byte {
+ val limit = data.limit
+ if (data is ArrayReadBuffer) {
+ // enables range check elimination
+ val ary = data.data()
+ return skipWhitespace(limit) { ary[it] }
+ }
+ return skipWhitespace(limit) { data[it] }
+ }
+
+ private inline fun skipWhitespace(limit: Int, crossinline fetch: (Int) -> Byte): Byte {
+ var pos = readPos
+ while (pos < limit) {
+ val d = fetch(pos++)
+ if (!isWhitespace(d)) {
+ readPos = pos
+ return d
+ }
+ }
+ readPos = limit
+ return CHAR_EOF
+ }
+
+ // byte1 is expected to be first char before `\`
+ private fun readEscapedChar(data: ReadBuffer, byte1: Byte, cursorPos: Int): Char {
+ return when (byte1) {
+ CHAR_u -> {
+ checkEOF(data, cursorPos + 1 + 4)
+ var result: Char = 0.toChar()
+ var i = cursorPos + 2 // cursorPos is on '\\', cursorPos + 1 is 'u'
+ val end = i + 4
+ while (i < end) {
+ val part: Byte = data[i]
+ result = (result.toInt() shl 4).toChar()
+ result += when (part) {
+ in CHAR_0..CHAR_9 -> part - CHAR_0
+ in CHAR_a..CHAR_f -> part - CHAR_a + 10
+ in CHAR_A..CHAR_F -> part - CHAR_A + 10
+ else -> makeError(data, "Invalid utf8 escaped character", -1)
+ }
+ i++
+ }
+ result
+ }
+ CHAR_b -> '\b'
+ CHAR_t -> '\t'
+ CHAR_r -> '\r'
+ CHAR_n -> '\n'
+ CHAR_f -> 12.toChar() // '\f'
+ CHAR_DOUBLE_QUOTE, CHAR_BACKSLASH, CHAR_FORWARDSLASH -> byte1.toChar()
+ else -> makeError(data, "Invalid escape sequence.", byte1)
+ }
+ }
+
+ private fun Byte.print(): String = when (this) {
+ in 0x21..0x7E -> "'${this.toChar()}'" // visible ascii chars
+ CHAR_EOF -> "EOF"
+ else -> "'0x${this.toString(16)}'"
+ }
+
+ private inline fun makeError(data: ReadBuffer, msg: String, tok: Byte? = null): Nothing {
+ val (line, column) = calculateErrorPosition(data, readPos)
+ if (tok != null) {
+ error("Error At ($line, $column): $msg, got ${tok.print()}")
+ } else {
+ error("Error At ($line, $column): $msg")
+ }
+ }
+
+ private inline fun makeError(data: ReadBuffer, msg: String, tok: Token): Nothing {
+ val (line, column) = calculateErrorPosition(data, readPos)
+ error("Error At ($line, $column): $msg, got ${tok.print()}")
+ }
+
+ private inline fun checkEOF(data: ReadBuffer, pos: Int) {
+ if (pos >= data.limit)
+ makeError(data, "Unexpected end of file", -1)
+ }
+
+ private fun calculateErrorPosition(data: ReadBuffer, endPos: Int): Pair<Int, Int> {
+ var line = 1
+ var column = 1
+ var current = 0
+ while (current < endPos - 1) {
+ if (data[current++] == CHAR_NEWLINE) {
+ ++line
+ column = 1
+ } else {
+ ++column
+ }
+ }
+ return Pair(line, column)
+ }
+}
+
+internal inline fun Int.toPaddedHex(): String = "\\u${this.toString(16).padStart(4, '0')}"
+
+private inline fun ReadWriteBuffer.jsonEscape(data: ReadBuffer, start: Int, size: Int) {
+ val replacements = JSON_ESCAPE_CHARS
+ put(CHAR_DOUBLE_QUOTE)
+ var last = start
+ val length: Int = size
+ val ary = data.data()
+ for (i in start until start + length) {
+ val c = ary[i].toUByte()
+ var replacement: ByteArray?
+ if (c.toInt() < 128) {
+ replacement = replacements[c.toInt()]
+ if (replacement == null) {
+ continue
+ }
+ } else {
+ continue
+ }
+ if (last < i) {
+ put(ary, last, i - last)
+ }
+ put(replacement, 0, replacement.size)
+ last = i + 1
+ }
+ if (last < (last + length)) {
+ put(ary, last, (start + length) - last)
+ }
+ put(CHAR_DOUBLE_QUOTE)
+}
+
+// Following escape strategy defined in RFC7159.
+private val JSON_ESCAPE_CHARS: Array<ByteArray?> = arrayOfNulls<ByteArray>(128).apply {
+ this['\n'.toInt()] = "\\n".encodeToByteArray()
+ this['\t'.toInt()] = "\\t".encodeToByteArray()
+ this['\r'.toInt()] = "\\r".encodeToByteArray()
+ this['\b'.toInt()] = "\\b".encodeToByteArray()
+ this[0x0c] = "\\f".encodeToByteArray()
+ this['"'.toInt()] = "\\\"".encodeToByteArray()
+ this['\\'.toInt()] = "\\\\".encodeToByteArray()
+ for (i in 0..0x1f) {
+ this[i] = "\\u${i.toPaddedHex()}".encodeToByteArray()
+ }
+}
+
+// Scope is used to the define current space that the scanner is operating.
+private inline class Scope(val id: Int)
+private val SCOPE_DOC_EMPTY = Scope(0)
+private val SCOPE_DOC_FILLED = Scope(1)
+private val SCOPE_OBJ_EMPTY = Scope(2)
+private val SCOPE_OBJ_KEY = Scope(3)
+private val SCOPE_OBJ_FILLED = Scope(4)
+private val SCOPE_ARRAY_EMPTY = Scope(5)
+private val SCOPE_ARRAY_FILLED = Scope(6)
+
+// Keeps the stack state of the scopes being scanned. Currently defined to have a
+// max stack size of 22, as per tests cases defined in http://json.org/JSON_checker/
+private class ScopeStack(
+ private val ary: IntArray = IntArray(22) { SCOPE_DOC_EMPTY.id },
+ var lastPos: Int = 0
+) {
+ var last: Scope
+ get() = Scope(ary[lastPos])
+ set(x) {
+ ary[lastPos] = x.id
+ }
+
+ fun reset() {
+ lastPos = 0
+ ary[0] = SCOPE_DOC_EMPTY.id
+ }
+
+ fun pop(): Scope {
+ // println("Popping: ${last.print()}")
+ return Scope(ary[lastPos--])
+ }
+
+ fun push(scope: Scope): Scope {
+ if (lastPos == ary.size - 1)
+ error("Too much nesting reached. Max nesting is ${ary.size} levels")
+ // println("PUSHING : ${scope.print()}")
+ ary[++lastPos] = scope.id
+ return scope
+ }
+}
+
+private inline class Token(val id: Int) {
+ fun print(): String = when (this) {
+ TOK_EOF -> "TOK_EOF"
+ TOK_NONE -> "TOK_NONE"
+ TOK_BEGIN_OBJECT -> "TOK_BEGIN_OBJECT"
+ TOK_END_OBJECT -> "TOK_END_OBJECT"
+ TOK_BEGIN_ARRAY -> "TOK_BEGIN_ARRAY"
+ TOK_END_ARRAY -> "TOK_END_ARRAY"
+ TOK_NUMBER -> "TOK_NUMBER"
+ TOK_TRUE -> "TOK_TRUE"
+ TOK_FALSE -> "TOK_FALSE"
+ TOK_NULL -> "TOK_NULL"
+ TOK_BEGIN_QUOTE -> "TOK_BEGIN_QUOTE"
+ else -> this.toString()
+ }
+}
+
+private val TOK_EOF = Token(-1)
+private val TOK_NONE = Token(0)
+private val TOK_BEGIN_OBJECT = Token(1)
+private val TOK_END_OBJECT = Token(2)
+private val TOK_BEGIN_ARRAY = Token(3)
+private val TOK_END_ARRAY = Token(4)
+private val TOK_NUMBER = Token(5)
+private val TOK_TRUE = Token(6)
+private val TOK_FALSE = Token(7)
+private val TOK_NULL = Token(8)
+private val TOK_BEGIN_QUOTE = Token(9)
+
+private const val CHAR_NEWLINE = '\n'.toByte()
+private const val CHAR_OPEN_OBJECT = '{'.toByte()
+private const val CHAR_COLON = ':'.toByte()
+private const val CHAR_CLOSE_OBJECT = '}'.toByte()
+private const val CHAR_OPEN_ARRAY = '['.toByte()
+private const val CHAR_CLOSE_ARRAY = ']'.toByte()
+private const val CHAR_DOUBLE_QUOTE = '"'.toByte()
+private const val CHAR_BACKSLASH = '\\'.toByte()
+private const val CHAR_FORWARDSLASH = '/'.toByte()
+private const val CHAR_f = 'f'.toByte()
+private const val CHAR_a = 'a'.toByte()
+private const val CHAR_r = 'r'.toByte()
+private const val CHAR_t = 't'.toByte()
+private const val CHAR_n = 'n'.toByte()
+private const val CHAR_b = 'b'.toByte()
+private const val CHAR_e = 'e'.toByte()
+private const val CHAR_E = 'E'.toByte()
+private const val CHAR_u = 'u'.toByte()
+private const val CHAR_A = 'A'.toByte()
+private const val CHAR_F = 'F'.toByte()
+private const val CHAR_EOF = (-1).toByte()
+private const val CHAR_COMMA = ','.toByte()
+private const val CHAR_0 = '0'.toByte()
+private const val CHAR_1 = '1'.toByte()
+private const val CHAR_2 = '2'.toByte()
+private const val CHAR_3 = '3'.toByte()
+private const val CHAR_4 = '4'.toByte()
+private const val CHAR_5 = '5'.toByte()
+private const val CHAR_6 = '6'.toByte()
+private const val CHAR_7 = '7'.toByte()
+private const val CHAR_8 = '8'.toByte()
+private const val CHAR_9 = '9'.toByte()
+private const val CHAR_MINUS = '-'.toByte()
+private const val CHAR_PLUS = '+'.toByte()
+private const val CHAR_DOT = '.'.toByte()
+
+// This template utilizes the One Definition Rule to create global arrays in a
+// header. As seen in:
+// https://github.com/chadaustin/sajson/blob/master/include/sajson.h
+// bit 0 (1) - set if: plain ASCII string character
+// bit 1 (2) - set if: whitespace
+// bit 4 (0x10) - set if: 0-9 e E .
+private val parseFlags = byteArrayOf(
+// 0 1 2 3 4 5 6 7 8 9 A B C D E F
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 0, 0, 2, 0, 0, // 0
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 1
+ 3, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0x11, 1, // 2
+ 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 1, 1, 1, 1, 1, 1, // 3
+ 1, 1, 1, 1, 1, 0x11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, // 5
+ 1, 1, 1, 1, 1, 0x11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7
+
+ // 128-255
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
+)
diff --git a/kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/Utf8.kt b/kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/Utf8.kt
new file mode 100644
index 0000000..4b02cc5
--- /dev/null
+++ b/kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/Utf8.kt
@@ -0,0 +1,416 @@
+/*
+ * Copyright 2021 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.
+ */
+@file:Suppress("NOTHING_TO_INLINE")
+package com.google.flatbuffers.kotlin
+
+public object Utf8 {
+ /**
+ * Returns the number of bytes in the UTF-8-encoded form of `sequence`. For a string,
+ * this method is equivalent to `string.getBytes(UTF_8).length`, but is more efficient in
+ * both time and space.
+ *
+ * @throws IllegalArgumentException if `sequence` contains ill-formed UTF-16 (unpaired
+ * surrogates)
+ */
+ private fun computeEncodedLength(sequence: CharSequence): Int {
+ // Warning to maintainers: this implementation is highly optimized.
+ val utf16Length = sequence.length
+ var utf8Length = utf16Length
+ var i = 0
+
+ // This loop optimizes for pure ASCII.
+ while (i < utf16Length && sequence[i].toInt() < 0x80) {
+ i++
+ }
+
+ // This loop optimizes for chars less than 0x800.
+ while (i < utf16Length) {
+ val c = sequence[i]
+ if (c.toInt() < 0x800) {
+ utf8Length += 0x7f - c.toInt() ushr 31 // branch free!
+ } else {
+ utf8Length += encodedLengthGeneral(sequence, i)
+ break
+ }
+ i++
+ }
+ if (utf8Length < utf16Length) {
+ // Necessary and sufficient condition for overflow because of maximum 3x expansion
+ error("UTF-8 length does not fit in int: ${(utf8Length + (1L shl 32))}")
+ }
+ return utf8Length
+ }
+
+ private fun encodedLengthGeneral(sequence: CharSequence, start: Int): Int {
+ val utf16Length = sequence.length
+ var utf8Length = 0
+ var i = start
+ while (i < utf16Length) {
+ val c = sequence[i]
+ if (c.toInt() < 0x800) {
+ utf8Length += 0x7f - c.toInt() ushr 31 // branch free!
+ } else {
+ utf8Length += 2
+ if (c.isSurrogate()) {
+ // Check that we have a well-formed surrogate pair.
+ val cp: Int = codePointAt(sequence, i)
+ if (cp < MIN_SUPPLEMENTARY_CODE_POINT) {
+ errorSurrogate(i, utf16Length)
+ }
+ i++
+ }
+ }
+ i++
+ }
+ return utf8Length
+ }
+
+ /**
+ * Returns the number of bytes in the UTF-8-encoded form of `sequence`. For a string,
+ * this method is equivalent to `string.getBytes(UTF_8).length`, but is more efficient in
+ * both time and space.
+ *
+ * @throws IllegalArgumentException if `sequence` contains ill-formed UTF-16 (unpaired
+ * surrogates)
+ */
+ public fun encodedLength(sequence: CharSequence): Int = computeEncodedLength(sequence)
+
+ /**
+ * Returns whether this is a single-byte codepoint (i.e., ASCII) with the form '0XXXXXXX'.
+ */
+ public inline fun isOneByte(b: Byte): Boolean = b >= 0
+
+ /**
+ * Returns whether this is a two-byte codepoint with the form 110xxxxx 0xC0..0xDF.
+ */
+ public inline fun isTwoBytes(b: Byte): Boolean = b < 0xE0.toByte()
+
+ /**
+ * Returns whether this is a three-byte codepoint with the form 1110xxxx 0xE0..0xEF.
+ */
+ public inline fun isThreeBytes(b: Byte): Boolean = b < 0xF0.toByte()
+
+ /**
+ * Returns whether this is a four-byte codepoint with the form 11110xxx 0xF0..0xF4.
+ */
+ public inline fun isFourByte(b: Byte): Boolean = b < 0xF8.toByte()
+
+ public fun handleOneByte(byte1: Byte, resultArr: CharArray, resultPos: Int) {
+ resultArr[resultPos] = byte1.toChar()
+ }
+
+ public fun handleTwoBytes(
+ byte1: Byte,
+ byte2: Byte,
+ resultArr: CharArray,
+ resultPos: Int
+ ) {
+ // Simultaneously checks for illegal trailing-byte in leading position (<= '11000000') and
+ // overlong 2-byte, '11000001'.
+ if (byte1 < 0xC2.toByte()) {
+ error("Invalid UTF-8: Illegal leading byte in 2 bytes utf")
+ }
+ if (isNotTrailingByte(byte2)) {
+ error("Invalid UTF-8: Illegal trailing byte in 2 bytes utf")
+ }
+ resultArr[resultPos] = (byte1.toInt() and 0x1F shl 6 or trailingByteValue(byte2)).toChar()
+ }
+
+ public fun handleThreeBytes(
+ byte1: Byte,
+ byte2: Byte,
+ byte3: Byte,
+ resultArr: CharArray,
+ resultPos: Int
+ ) {
+ if (isNotTrailingByte(byte2) || // overlong? 5 most significant bits must not all be zero
+ byte1 == 0xE0.toByte() && byte2 < 0xA0.toByte() || // check for illegal surrogate codepoints
+ byte1 == 0xED.toByte() && byte2 >= 0xA0.toByte() ||
+ isNotTrailingByte(byte3)
+ ) {
+ error("Invalid UTF-8")
+ }
+ resultArr[resultPos] =
+ (byte1.toInt() and 0x0F shl 12 or (trailingByteValue(byte2) shl 6) or trailingByteValue(byte3)).toChar()
+ }
+
+ public fun handleFourBytes(
+ byte1: Byte,
+ byte2: Byte,
+ byte3: Byte,
+ byte4: Byte,
+ resultArr: CharArray,
+ resultPos: Int
+ ) {
+ if (isNotTrailingByte(byte2) || // Check that 1 <= plane <= 16. Tricky optimized form of:
+ // valid 4-byte leading byte?
+ // if (byte1 > (byte) 0xF4 ||
+ // overlong? 4 most significant bits must not all be zero
+ // byte1 == (byte) 0xF0 && byte2 < (byte) 0x90 ||
+ // codepoint larger than the highest code point (U+10FFFF)?
+ // byte1 == (byte) 0xF4 && byte2 > (byte) 0x8F)
+ (byte1.toInt() shl 28) + (byte2 - 0x90.toByte()) shr 30 != 0 || isNotTrailingByte(byte3) ||
+ isNotTrailingByte(byte4)
+ ) {
+ error("Invalid UTF-8")
+ }
+ val codepoint: Int = (
+ byte1.toInt() and 0x07 shl 18
+ or (trailingByteValue(byte2) shl 12)
+ or (trailingByteValue(byte3) shl 6)
+ or trailingByteValue(byte4)
+ )
+ resultArr[resultPos] = highSurrogate(codepoint)
+ resultArr[resultPos + 1] = lowSurrogate(codepoint)
+ }
+
+ /**
+ * Returns whether the byte is not a valid continuation of the form '10XXXXXX'.
+ */
+ private fun isNotTrailingByte(b: Byte): Boolean = b > 0xBF.toByte()
+
+ /**
+ * Returns the actual value of the trailing byte (removes the prefix '10') for composition.
+ */
+ private fun trailingByteValue(b: Byte): Int = b.toInt() and 0x3F
+
+ private fun highSurrogate(codePoint: Int): Char =
+ (
+ Char.MIN_HIGH_SURROGATE - (MIN_SUPPLEMENTARY_CODE_POINT ushr 10) +
+ (codePoint ushr 10)
+ )
+
+ private fun lowSurrogate(codePoint: Int): Char = (Char.MIN_LOW_SURROGATE + (codePoint and 0x3ff))
+
+ /**
+ * Encode a [CharSequence] UTF8 codepoint into a byte array.
+ * @param `in` CharSequence to be encoded
+ * @param start start position of the first char in the codepoint
+ * @param out byte array of 4 bytes to be filled
+ * @return return the amount of bytes occupied by the codepoint
+ */
+ public fun encodeUtf8CodePoint(input: CharSequence, start: Int, out: ByteArray): Int {
+ // utf8 codepoint needs at least 4 bytes
+ val inLength = input.length
+ if (start >= inLength) {
+ return 0
+ }
+ val c = input[start]
+ return if (c.toInt() < 0x80) {
+ // One byte (0xxx xxxx)
+ out[0] = c.toByte()
+ 1
+ } else if (c.toInt() < 0x800) {
+ // Two bytes (110x xxxx 10xx xxxx)
+ out[0] = (0xC0 or (c.toInt() ushr 6)).toByte()
+ out[1] = (0x80 or (0x3F and c.toInt())).toByte()
+ 2
+ } else if (c < Char.MIN_SURROGATE || Char.MAX_SURROGATE < c) {
+ // Three bytes (1110 xxxx 10xx xxxx 10xx xxxx)
+ // Maximum single-char code point is 0xFFFF, 16 bits.
+ out[0] = (0xE0 or (c.toInt() ushr 12)).toByte()
+ out[1] = (0x80 or (0x3F and (c.toInt() ushr 6))).toByte()
+ out[2] = (0x80 or (0x3F and c.toInt())).toByte()
+ 3
+ } else {
+ // Four bytes (1111 xxxx 10xx xxxx 10xx xxxx 10xx xxxx)
+ // Minimum code point represented by a surrogate pair is 0x10000, 17 bits, four UTF-8
+ // bytes
+ val low: Char = input[start + 1]
+ if (start + 1 == inLength || !(c.isHighSurrogate() and low.isLowSurrogate())) {
+ errorSurrogate(start, inLength)
+ }
+ val codePoint: Int = toCodePoint(c, low)
+ out[0] = (0xF shl 4 or (codePoint ushr 18)).toByte()
+ out[1] = (0x80 or (0x3F and (codePoint ushr 12))).toByte()
+ out[2] = (0x80 or (0x3F and (codePoint ushr 6))).toByte()
+ out[3] = (0x80 or (0x3F and codePoint)).toByte()
+ 4
+ }
+ }
+
+ // Decodes a code point starting at index into out. Out parameter
+ // should have at least 2 chars.
+ public fun decodeUtf8CodePoint(bytes: ReadBuffer, index: Int, out: CharArray) {
+ // Bitwise OR combines the sign bits so any negative value fails the check.
+ val b1 = bytes[index]
+ when {
+ isOneByte(b1) -> handleOneByte(b1, out, 0)
+ isTwoBytes(b1) -> handleTwoBytes(b1, bytes[index + 1], out, 0)
+ isThreeBytes(b1) -> handleThreeBytes(b1, bytes[index + 1], bytes[index + 2], out, 0)
+ else -> handleFourBytes(b1, bytes[index + 1], bytes[index + 2], bytes[index + 3], out, 0)
+ }
+ }
+
+ public fun decodeUtf8Array(bytes: ByteArray, index: Int = 0, size: Int = bytes.size): String {
+ // Bitwise OR combines the sign bits so any negative value fails the check.
+ if (index or size or bytes.size - index - size < 0) {
+ error("buffer length=${bytes.size}, index=$index, size=$size")
+ }
+ var offset = index
+ val limit = offset + size
+
+ // The longest possible resulting String is the same as the number of input bytes, when it is
+ // all ASCII. For other cases, this over-allocates and we will truncate in the end.
+ val resultArr = CharArray(size)
+ var resultPos = 0
+
+ // Optimize for 100% ASCII (Hotspot loves small simple top-level loops like this).
+ // This simple loop stops when we encounter a byte >= 0x80 (i.e. non-ASCII).
+ while (offset < limit) {
+ val b = bytes[offset]
+ if (!isOneByte(b)) {
+ break
+ }
+ offset++
+ handleOneByte(b, resultArr, resultPos++)
+ }
+ while (offset < limit) {
+ val byte1 = bytes[offset++]
+ if (isOneByte(byte1)) {
+ handleOneByte(byte1, resultArr, resultPos++)
+ // It's common for there to be multiple ASCII characters in a run mixed in, so add an
+ // extra optimized loop to take care of these runs.
+ while (offset < limit) {
+ val b = bytes[offset]
+ if (!isOneByte(b)) {
+ break
+ }
+ offset++
+ handleOneByte(b, resultArr, resultPos++)
+ }
+ } else if (isTwoBytes(byte1)) {
+ if (offset >= limit) {
+ error("Invalid UTF-8")
+ }
+ handleTwoBytes(
+ byte1, /* byte2 */
+ bytes[offset++], resultArr, resultPos++
+ )
+ } else if (isThreeBytes(byte1)) {
+ if (offset >= limit - 1) {
+ error("Invalid UTF-8")
+ }
+ handleThreeBytes(
+ byte1, /* byte2 */
+ bytes[offset++], /* byte3 */
+ bytes[offset++],
+ resultArr,
+ resultPos++
+ )
+ } else {
+ if (offset >= limit - 2) {
+ error("Invalid UTF-8")
+ }
+ handleFourBytes(
+ byte1, /* byte2 */
+ bytes[offset++], /* byte3 */
+ bytes[offset++], /* byte4 */
+ bytes[offset++],
+ resultArr,
+ resultPos++
+ )
+ // 4-byte case requires two chars.
+ resultPos++
+ }
+ }
+ return resultArr.concatToString(0, resultPos)
+ }
+
+ public fun encodeUtf8Array(input: CharSequence, out: ByteArray, offset: Int = 0, length: Int = out.size - offset): Int {
+ val utf16Length = input.length
+ var j = offset
+ var i = 0
+ val limit = offset + length
+ // Designed to take advantage of
+ // https://wikis.oracle.com/display/HotSpotInternals/RangeCheckElimination
+
+ if (utf16Length == 0)
+ return 0
+ var cc: Char = input[i]
+ while (i < utf16Length && i + j < limit && input[i].also { cc = it }.toInt() < 0x80) {
+ out[j + i] = cc.toByte()
+ i++
+ }
+ if (i == utf16Length) {
+ return j + utf16Length
+ }
+ j += i
+ var c: Char
+ while (i < utf16Length) {
+ c = input[i]
+ if (c.toInt() < 0x80 && j < limit) {
+ out[j++] = c.toByte()
+ } else if (c.toInt() < 0x800 && j <= limit - 2) { // 11 bits, two UTF-8 bytes
+ out[j++] = (0xF shl 6 or (c.toInt() ushr 6)).toByte()
+ out[j++] = (0x80 or (0x3F and c.toInt())).toByte()
+ } else if ((c < Char.MIN_SURROGATE || Char.MAX_SURROGATE < c) && j <= limit - 3) {
+ // Maximum single-char code point is 0xFFFF, 16 bits, three UTF-8 bytes
+ out[j++] = (0xF shl 5 or (c.toInt() ushr 12)).toByte()
+ out[j++] = (0x80 or (0x3F and (c.toInt() ushr 6))).toByte()
+ out[j++] = (0x80 or (0x3F and c.toInt())).toByte()
+ } else if (j <= limit - 4) {
+ // Minimum code point represented by a surrogate pair is 0x10000, 17 bits,
+ // four UTF-8 bytes
+ var low: Char = Char.MIN_VALUE
+ if (i + 1 == input.length ||
+ !isSurrogatePair(c, input[++i].also { low = it })
+ ) {
+ errorSurrogate(i - 1, utf16Length)
+ }
+ val codePoint: Int = toCodePoint(c, low)
+ out[j++] = (0xF shl 4 or (codePoint ushr 18)).toByte()
+ out[j++] = (0x80 or (0x3F and (codePoint ushr 12))).toByte()
+ out[j++] = (0x80 or (0x3F and (codePoint ushr 6))).toByte()
+ out[j++] = (0x80 or (0x3F and codePoint)).toByte()
+ } else {
+ // If we are surrogates and we're not a surrogate pair, always throw an
+ // UnpairedSurrogateException instead of an ArrayOutOfBoundsException.
+ if (Char.MIN_SURROGATE <= c && c <= Char.MAX_SURROGATE &&
+ (i + 1 == input.length || !isSurrogatePair(c, input[i + 1]))
+ ) {
+ errorSurrogate(i, utf16Length)
+ }
+ error("Failed writing character ${c.toShort().toString(radix = 16)} at index $j")
+ }
+ i++
+ }
+ return j
+ }
+
+ public fun codePointAt(seq: CharSequence, position: Int): Int {
+ var index = position
+ val c1 = seq[index]
+ if (c1.isHighSurrogate() && ++index < seq.length) {
+ val c2 = seq[index]
+ if (c2.isLowSurrogate()) {
+ return toCodePoint(c1, c2)
+ }
+ }
+ return c1.toInt()
+ }
+
+ private fun isSurrogatePair(high: Char, low: Char) = high.isHighSurrogate() and low.isLowSurrogate()
+
+ private fun toCodePoint(high: Char, low: Char): Int = (high.toInt() shl 10) + low.toInt() +
+ (MIN_SUPPLEMENTARY_CODE_POINT - (Char.MIN_HIGH_SURROGATE.toInt() shl 10) - Char.MIN_LOW_SURROGATE.toInt())
+
+ private fun errorSurrogate(i: Int, utf16Length: Int): Unit =
+ error("Unpaired surrogate at index $i of $utf16Length length")
+
+ // The minimum value of Unicode supplementary code point, constant `U+10000`.
+ private const val MIN_SUPPLEMENTARY_CODE_POINT = 0x010000
+}
diff --git a/kotlin/flatbuffers-kotlin/src/commonTest/kotlin/com/google/flatbuffers/kotlin/ByteArrayTest.kt b/kotlin/flatbuffers-kotlin/src/commonTest/kotlin/com/google/flatbuffers/kotlin/ByteArrayTest.kt
new file mode 100644
index 0000000..560b0f3
--- /dev/null
+++ b/kotlin/flatbuffers-kotlin/src/commonTest/kotlin/com/google/flatbuffers/kotlin/ByteArrayTest.kt
@@ -0,0 +1,198 @@
+/*
+ * Copyright 2021 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.
+ */
+package com.google.flatbuffers.kotlin
+
+import kotlin.test.Test
+import kotlin.test.assertEquals
+import kotlin.test.assertTrue
+
+class ByteArrayTest {
+
+ @Test
+ fun testByte() {
+ val testSet = arrayOf(
+ 67.toByte() to byteArrayOf(67),
+ Byte.MIN_VALUE to byteArrayOf(-128),
+ Byte.MAX_VALUE to byteArrayOf(127),
+ 0.toByte() to byteArrayOf(0)
+ )
+ val data = ByteArray(1)
+ testSet.forEach {
+ data[0] = it.first
+ assertArrayEquals(data, it.second)
+ assertEquals(it.first, data[0])
+ }
+ }
+
+ @Test
+ fun testShort() {
+ val testSet = arrayOf(
+ 6712.toShort() to byteArrayOf(56, 26),
+ Short.MIN_VALUE to byteArrayOf(0, -128),
+ Short.MAX_VALUE to byteArrayOf(-1, 127),
+ 0.toShort() to byteArrayOf(0, 0,)
+ )
+
+ val data = ByteArray(Short.SIZE_BYTES)
+ testSet.forEach {
+ data.setShort(0, it.first)
+ assertArrayEquals(data, it.second)
+ assertEquals(it.first, data.getShort(0))
+ }
+ }
+
+ @Test
+ fun testInt() {
+ val testSet = arrayOf(
+ 33333500 to byteArrayOf(-4, -96, -4, 1),
+ Int.MIN_VALUE to byteArrayOf(0, 0, 0, -128),
+ Int.MAX_VALUE to byteArrayOf(-1, -1, -1, 127),
+ 0 to byteArrayOf(0, 0, 0, 0)
+ )
+ val data = ByteArray(Int.SIZE_BYTES)
+ testSet.forEach {
+ data.setInt(0, it.first)
+ assertArrayEquals(data, it.second)
+ assertEquals(it.first, data.getInt(0))
+ }
+ }
+
+ @Test
+ fun testLong() {
+ val testSet = arrayOf(
+ 1234567123122890123L to byteArrayOf(-117, -91, 29, -23, 65, 16, 34, 17),
+ -1L to byteArrayOf(-1, -1, -1, -1, -1, -1, -1, -1),
+ Long.MIN_VALUE to byteArrayOf(0, 0, 0, 0, 0, 0, 0, -128),
+ Long.MAX_VALUE to byteArrayOf(-1, -1, -1, -1, -1, -1, -1, 127),
+ 0L to byteArrayOf(0, 0, 0, 0, 0, 0, 0, 0)
+ )
+ val data = ByteArray(Long.SIZE_BYTES)
+ testSet.forEach {
+ data.setLong(0, it.first)
+ assertArrayEquals(data, it.second)
+ assertEquals(it.first, data.getLong(0))
+ }
+ }
+
+ @Test
+ fun testULong() {
+ val testSet = arrayOf(
+ 1234567123122890123UL to byteArrayOf(-117, -91, 29, -23, 65, 16, 34, 17),
+ ULong.MIN_VALUE to byteArrayOf(0, 0, 0, 0, 0, 0, 0, 0),
+ (-1L).toULong() to byteArrayOf(-1, -1, -1, -1, -1, -1, -1, -1),
+ 0UL to byteArrayOf(0, 0, 0, 0, 0, 0, 0, 0)
+ )
+ val data = ByteArray(ULong.SIZE_BYTES)
+ testSet.forEach {
+ data.setULong(0, it.first)
+ assertArrayEquals(it.second, data)
+ assertEquals(it.first, data.getULong(0))
+ }
+ }
+
+ @Test
+ fun testFloat() {
+ val testSet = arrayOf(
+ 3545.56337f to byteArrayOf(4, -103, 93, 69),
+ Float.MIN_VALUE to byteArrayOf(1, 0, 0, 0),
+ Float.MAX_VALUE to byteArrayOf(-1, -1, 127, 127),
+ 0f to byteArrayOf(0, 0, 0, 0)
+ )
+ val data = ByteArray(Float.SIZE_BYTES)
+ testSet.forEach {
+ data.setFloat(0, it.first)
+ assertArrayEquals(data, it.second)
+ }
+ }
+
+ @Test
+ fun testDouble() {
+ val testSet = arrayOf(
+ 123456.523423423412 to byteArrayOf(88, 61, -15, 95, 8, 36, -2, 64),
+ Double.MIN_VALUE to byteArrayOf(1, 0, 0, 0, 0, 0, 0, 0),
+ Double.MAX_VALUE to byteArrayOf(-1, -1, -1, -1, -1, -1, -17, 127),
+ 0.0 to byteArrayOf(0, 0, 0, 0, 0, 0, 0, 0)
+ )
+ val data = ByteArray(Long.SIZE_BYTES)
+ testSet.forEach {
+ data.setDouble(0, it.first)
+ assertArrayEquals(data, it.second)
+ assertEquals(it.first, data.getDouble(0))
+ }
+ }
+
+ @Test
+ fun testString() {
+ val testSet = "∮ E⋅da = Q"
+ val encoded = testSet.encodeToByteArray()
+ val data = ByteArray(encoded.size)
+ data.setString(0, testSet)
+ assertArrayEquals(encoded, data)
+ assertEquals(testSet, data.getString(0, encoded.size))
+ }
+}
+
+fun <T> assertArrayEquals(expected: Array<out T>, actual: Array<out T>) =
+ assertTrue(expected contentEquals actual, arrayFailMessage(expected, actual))
+
+fun assertArrayEquals(expected: IntArray, actual: IntArray) =
+ assertTrue(expected contentEquals actual, arrayFailMessage(expected, actual))
+
+fun assertArrayEquals(expected: ShortArray, actual: ShortArray) =
+ assertTrue(expected contentEquals actual, arrayFailMessage(expected, actual))
+
+fun assertArrayEquals(expected: LongArray, actual: LongArray) =
+ assertTrue(expected contentEquals actual, arrayFailMessage(expected, actual))
+
+fun assertArrayEquals(expected: ByteArray, actual: ByteArray) =
+ assertTrue(expected contentEquals actual, arrayFailMessage(expected, actual))
+
+fun assertArrayEquals(expected: DoubleArray, actual: DoubleArray) =
+ assertTrue(expected contentEquals actual, arrayFailMessage(expected, actual))
+
+fun assertArrayEquals(expected: FloatArray, actual: FloatArray) =
+ assertTrue(expected contentEquals actual, arrayFailMessage(expected, actual))
+
+fun <T> arrayFailMessage(expected: Array<out T>, actual: Array<out T>): String =
+ failMessage(expected.contentToString(), actual.contentToString())
+
+fun arrayFailMessage(expected: IntArray, actual: IntArray): String =
+ failMessage(expected.contentToString(), actual.contentToString())
+
+fun arrayFailMessage(expected: ShortArray, actual: ShortArray): String =
+ failMessage(expected.contentToString(), actual.contentToString())
+
+fun arrayFailMessage(expected: LongArray, actual: LongArray): String =
+ failMessage(expected.contentToString(), actual.contentToString())
+
+fun failMessage(expected: String, actual: String): String =
+ "Expected: $expected\nActual: $actual"
+
+fun arrayFailMessage(expected: FloatArray, actual: FloatArray): String {
+ return "Expected: ${expected.contentToString()}\nActual: ${actual.contentToString()}"
+}
+
+fun arrayFailMessage(expected: DoubleArray, actual: DoubleArray): String {
+ return "Expected: ${expected.contentToString()}\nActual: ${actual.contentToString()}"
+}
+
+fun arrayFailMessage(expected: BooleanArray, actual: BooleanArray): String {
+ return "Expected: ${expected.contentToString()}\nActual: ${actual.contentToString()}"
+}
+
+fun arrayFailMessage(expected: ByteArray, actual: ByteArray): String {
+ return "Expected: ${expected.contentToString()}\nActual: ${actual.contentToString()}"
+}
diff --git a/kotlin/flatbuffers-kotlin/src/commonTest/kotlin/com/google/flatbuffers/kotlin/FlexBuffersTest.kt b/kotlin/flatbuffers-kotlin/src/commonTest/kotlin/com/google/flatbuffers/kotlin/FlexBuffersTest.kt
new file mode 100644
index 0000000..71820b6
--- /dev/null
+++ b/kotlin/flatbuffers-kotlin/src/commonTest/kotlin/com/google/flatbuffers/kotlin/FlexBuffersTest.kt
@@ -0,0 +1,301 @@
+/*
+ * Copyright 2021 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.
+ */
+package com.google.flatbuffers.kotlin
+
+import com.google.flatbuffers.kotlin.FlexBuffersBuilder.Companion.SHARE_NONE
+import kotlin.random.Random
+import kotlin.test.Test
+import kotlin.test.assertEquals
+
+class FlexBuffersTest {
+ @Test
+ fun testWriteInt() {
+ val values = listOf(
+ Byte.MAX_VALUE.toLong() to 3,
+ Short.MAX_VALUE.toLong() to 4,
+ Int.MAX_VALUE.toLong() to 6,
+ Long.MAX_VALUE to 10
+ )
+ val builder = FlexBuffersBuilder()
+ values.forEach {
+ builder.clear()
+ builder.put(it.first)
+ val data = builder.finish()
+ val ref = getRoot(data)
+ // although we put a long, it is shrink to a byte
+ assertEquals(it.second, data.limit)
+ assertEquals(it.first, ref.toLong())
+ }
+ }
+
+ @Test
+ fun testWriteUInt() {
+ val values = listOf(
+ UByte.MAX_VALUE.toULong() to 3,
+ UShort.MAX_VALUE.toULong() to 4,
+ UInt.MAX_VALUE.toULong() to 6,
+ ULong.MAX_VALUE to 10
+ )
+ val builder = FlexBuffersBuilder()
+ values.forEach {
+ builder.clear()
+ builder.put(it.first)
+ val data = builder.finish()
+ val ref = getRoot(data)
+ // although we put a long, it is shrink to a byte
+ assertEquals(it.second, data.limit)
+ assertEquals(it.first, ref.toULong())
+ }
+ }
+
+ @Test
+ fun testWriteString() {
+ val text = "Ḧ̵̘́ȩ̵̐l̶̿͜l̶͚͝o̷̦̚ ̷̫̊w̴̤͊ö̸̞́r̴͎̾l̷͚̐d̶̰̍"
+ val builder = FlexBuffersBuilder()
+ builder.put(text)
+ val data = builder.finish()
+ val ref = getRoot(data)
+ assertEquals(text, ref.toString())
+ }
+
+ @Test
+ fun testInt8Array() {
+ val ary = intArrayOf(1, 2, 3, 4)
+ val builder = FlexBuffersBuilder()
+ builder.put(intArrayOf(1, 2, 3, 4))
+ val data = builder.finish()
+ val ref = getRoot(data)
+ // although we put a long, it is shrink to a byte
+ assertEquals(8, data.limit)
+ assertArrayEquals(ary, ref.toIntArray())
+ }
+
+ @Test
+ fun testShortArray() {
+ val builder = FlexBuffersBuilder(ArrayReadWriteBuffer(20))
+ val numbers = ShortArray(10) { it.toShort() }
+ builder.put(numbers)
+ val data = builder.finish()
+ val ref = getRoot(data)
+ assertArrayEquals(numbers, ref.toShortArray())
+ }
+
+ @Test
+ fun testHugeArray() {
+ val builder = FlexBuffersBuilder()
+ val numbers = IntArray(1024) { it }
+ builder.put(numbers)
+ val data = builder.finish()
+ val ref = getRoot(data)
+ assertArrayEquals(numbers, ref.toIntArray())
+ }
+
+ @Test
+ fun testFloatArray() {
+ val builder = FlexBuffersBuilder()
+ val numbers = FloatArray(1024) { it * 0.05f }
+ builder.put(numbers)
+ val data = builder.finish()
+ val ref = getRoot(data)
+ assertArrayEquals(numbers, ref.toFloatArray())
+ }
+
+ @Test
+ fun testDoubleArray() {
+ val builder = FlexBuffersBuilder()
+ val numbers = DoubleArray(1024) { it * 0.0005 }
+ builder.put(numbers)
+ val data = builder.finish()
+ val ref = getRoot(data)
+ assertArrayEquals(numbers, ref.toDoubleArray())
+ }
+
+ @Test
+ fun testLongArray() {
+ val ary: LongArray = longArrayOf(0, Short.MIN_VALUE.toLong(), Int.MAX_VALUE.toLong(), Long.MAX_VALUE)
+ val builder = FlexBuffersBuilder()
+ builder.put(ary)
+ val data = builder.finish()
+ val ref = getRoot(data)
+ // although we put a long, it is shrink to a byte
+ assertArrayEquals(ary, ref.toLongArray())
+ }
+
+ @Test
+ fun testStringArray() {
+ val ary = Array(5) { "Hello world number: $it" }
+ val builder = FlexBuffersBuilder(ArrayReadWriteBuffer(20), SHARE_NONE)
+ builder.putVector {
+ ary.forEach { put(it) }
+ }
+ val data = builder.finish()
+ val vec = getRoot(data).toVector()
+ // although we put a long, it is shrink to a byte
+ assertEquals(5, vec.size)
+ val stringAry = vec.map { it.toString() }.toTypedArray()
+ // although we put a long, it is shrink to a byte
+ assertArrayEquals(ary, stringAry)
+ }
+
+ @Test
+ fun testBlobArray() {
+ val ary = ByteArray(1000) { Random.nextInt().toByte() }
+ val builder = FlexBuffersBuilder()
+ builder.put(ary)
+ val data = builder.finish()
+ val blob = getRoot(data).toBlob()
+ // although we put a long, it is shrink to a byte
+ assertArrayEquals(ary, blob.toByteArray())
+ for (i in 0 until blob.size) {
+ assertEquals(ary[i], blob[i])
+ }
+ }
+
+ @Test
+ fun testArrays() {
+ val builder = FlexBuffersBuilder()
+ val ary: Array<String> = Array(5) { "Hello world number: $it" }
+ val numbers = IntArray(10) { it }
+ val doubles = DoubleArray(10) { it * 0.35 }
+
+ // add 3 level array of arrays in the following way
+ // [ [ "..", ...] [ "..", ..., [ "..", ...] ] ]
+ val vec = builder.startVector()
+
+ // [0, 1, 2, 3 ,4 ,5 ,6 ,7 ,8, 9]
+ val vec1 = builder.startVector()
+ numbers.forEach { builder.put(it) }
+ builder.endTypedVector(vec1)
+
+ // [0, 2, 4, 6 , 8, 10, 12, 14, 16, 18]
+ builder.putTypedVector { doubles.forEach { put(it) } }
+
+ // nested array
+ // [ "He..", "He..", "He..", "He..", "He..", [ "He..", "He..", "He..", "He..", "He.." ] ]
+ val vec3 = builder.startVector()
+ ary.forEach { builder.put(it) }
+ builder.putVector { ary.forEach { put("inner: $it") } }
+ builder.endVector(vec3)
+
+ builder.endVector(vec)
+
+ val data = builder.finish()
+ val ref = getRoot(data)
+ val vecRef = getRoot(data).toVector()
+ // although we put a long, it is shrink to a byte
+ assertEquals(3, vecRef.size)
+
+ assertArrayEquals(numbers, vecRef[0].toVector().map { it.toInt() }.toIntArray())
+ assertArrayEquals(doubles, ref[1].toDoubleArray())
+ assertEquals("Hello world number: 4", vecRef[2][4].toString())
+ assertEquals("inner: Hello world number: 4", vecRef[2][5][4].toString())
+ assertEquals("inner: Hello world number: 4", ref[2][5][4].toString())
+ }
+
+ @Test
+ fun testMap() {
+ val builder = FlexBuffersBuilder(shareFlag = FlexBuffersBuilder.SHARE_KEYS_AND_STRINGS)
+ builder.putVector {
+ put(10)
+ putMap {
+ this["chello"] = "world"
+ this["aint"] = 10
+ this["bfloat"] = 12.3
+ }
+ put("aString")
+ }
+
+ val ref = getRoot(builder.finish())
+ val map = ref.toVector()
+ assertEquals(3, map.size)
+ assertEquals(10, map[0].toInt())
+ assertEquals("aString", map[2].toString())
+ assertEquals("world", map[1]["chello"].toString())
+ assertEquals(10, map[1]["aint"].toInt())
+ assertEquals(12.3, map[1]["bfloat"].toDouble())
+ }
+
+ @Test
+ fun testMultiMap() {
+ val builder = FlexBuffersBuilder(shareFlag = FlexBuffersBuilder.SHARE_KEYS_AND_STRINGS)
+ builder.putMap {
+ this["hello"] = "world"
+ this["int"] = 10
+ this["float"] = 12.3
+ this["intarray"] = intArrayOf(1, 2, 3, 4, 5)
+ this.putMap("myMap") {
+ this["cool"] = "beans"
+ }
+ }
+
+ val ref = getRoot(builder.finish())
+ val map = ref.toMap()
+ assertEquals(5, map.size)
+ assertEquals("world", map["hello"].toString())
+ assertEquals(10, map["int"].toInt())
+ assertEquals(12.3, map["float"].toDouble())
+ assertArrayEquals(intArrayOf(1, 2, 3, 4, 5), map["intarray"].toIntArray())
+ assertEquals("beans", ref["myMap"]["cool"].toString())
+ assertEquals(true, "myMap" in map)
+ assertEquals(true, "cool" in map["myMap"].toMap())
+
+ // testing null values
+ assertEquals(true, ref["invalid_key"].isNull)
+
+ val keys = map.keys.toTypedArray()
+ arrayOf("hello", "int", "float", "intarray", "myMap").sortedArray().forEachIndexed { i: Int, it: String ->
+ assertEquals(it, keys[i].toString())
+ }
+ }
+
+ @Test
+ fun testBigStringMap() {
+ val builder = FlexBuffersBuilder(shareFlag = FlexBuffersBuilder.SHARE_KEYS_AND_STRINGS)
+
+ val stringKey = Array(10000) { "Ḧ̵̘́ȩ̵̐myFairlyBigKey$it" }
+ val stringValue = Array(10000) { "Ḧ̵̘́ȩ̵̐myFairlyBigValue$it" }
+ val hashMap = mutableMapOf<String, String>()
+ val pos = builder.startMap()
+ for (i in stringKey.indices) {
+ builder[stringKey[i]] = stringValue[i]
+ hashMap[stringKey[i]] = stringValue[i]
+ }
+ builder.endMap(pos)
+ val ref = getRoot(builder.finish())
+ val map = ref.toMap()
+ val sortedKeys = stringKey.sortedArray()
+ val size = map.size
+ for (i in 0 until size) {
+ assertEquals(sortedKeys[i], map.keyAsString(i))
+ assertEquals(sortedKeys[i], map.keyAt(i).toString())
+ assertEquals(hashMap[sortedKeys[i]], map[map.keyAt(i)].toString())
+ }
+ }
+
+ @Test
+ fun testKeysAccess() {
+ for (i in 1 until 1000) {
+ val utf8String = "ሰማይ አይታረስ ንጉሥ አይከሰስ።$i"
+ val bytes = ByteArray(Utf8.encodedLength(utf8String))
+ val pos = Utf8.encodeUtf8Array(utf8String, bytes)
+ val key = Key(ArrayReadWriteBuffer(bytes), 0, pos)
+ assertEquals(utf8String.length, key.sizeInChars)
+ for (j in utf8String.indices) {
+ assertEquals(utf8String[j], key[j])
+ }
+ }
+ }
+}
diff --git a/kotlin/flatbuffers-kotlin/src/commonTest/kotlin/com/google/flatbuffers/kotlin/JSONTest.kt b/kotlin/flatbuffers-kotlin/src/commonTest/kotlin/com/google/flatbuffers/kotlin/JSONTest.kt
new file mode 100644
index 0000000..0375bb5
--- /dev/null
+++ b/kotlin/flatbuffers-kotlin/src/commonTest/kotlin/com/google/flatbuffers/kotlin/JSONTest.kt
@@ -0,0 +1,427 @@
+/*
+ * Copyright 2021 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.
+ */
+package com.google.flatbuffers.kotlin
+
+import kotlin.test.Test
+import kotlin.test.assertEquals
+import kotlin.test.assertTrue
+
+class JSONTest {
+
+ @Test
+ fun parse2Test() {
+ val dataStr = """
+ { "myKey" : [1, "yay"] }
+ """.trimIndent()
+ val data = dataStr.encodeToByteArray()
+ val buffer = ArrayReadWriteBuffer(data, writePosition = data.size)
+ val parser = JSONParser()
+ val root = parser.parse(buffer)
+ println(root.toJson())
+ }
+
+ @Test
+ fun parseSample() {
+ val dataStr = """
+ {
+ "ary" : [1, 2, 3],
+ "boolean_false": false,
+"boolean_true": true, "double": 1.2E33,
+ "hello":"world"
+ ,"interesting": "value",
+
+ "null_value": null,
+
+
+ "object" : {
+ "field1": "hello"
+ }
+ }
+ """
+ val data = dataStr.encodeToByteArray()
+ val root = JSONParser().parse(ArrayReadWriteBuffer(data, writePosition = data.size))
+ println(root.toJson())
+ val map = root.toMap()
+
+ assertEquals(8, map.size)
+ assertEquals("world", map["hello"].toString())
+ assertEquals("value", map["interesting"].toString())
+ assertEquals(12e32, map["double"].toDouble())
+ assertArrayEquals(intArrayOf(1, 2, 3), map["ary"].toIntArray())
+ assertEquals(true, map["boolean_true"].toBoolean())
+ assertEquals(false, map["boolean_false"].toBoolean())
+ assertEquals(true, map["null_value"].isNull)
+ assertEquals("hello", map["object"]["field1"].toString())
+
+ val obj = map["object"]
+ assertEquals(true, obj.isMap)
+ assertEquals("{\"field1\":\"hello\"}", obj.toJson())
+ // TODO: Kotlin Double.toString() produce different strings dependending on the platform, so on JVM
+ // is 1.2E33, while on js is 1.2e+33. For now we are disabling this test.
+ //
+ // val minified = data.filterNot { it == ' '.toByte() || it == '\n'.toByte() }.toByteArray().decodeToString()
+ // assertEquals(minified, root.toJson())
+ }
+
+ @Test
+ fun testDoubles() {
+ val values = arrayOf(
+ "-0.0",
+ "1.0",
+ "1.7976931348613157",
+ "0.0",
+ "-0.5",
+ "3.141592653589793",
+ "2.718281828459045E-3",
+ "2.2250738585072014E-308",
+ "4.9E-15",
+ )
+ val parser = JSONParser()
+ assertEquals(-0.0, parser.parse(values[0]).toDouble())
+ assertEquals(1.0, parser.parse(values[1]).toDouble())
+ assertEquals(1.7976931348613157, parser.parse(values[2]).toDouble())
+ assertEquals(0.0, parser.parse(values[3]).toDouble())
+ assertEquals(-0.5, parser.parse(values[4]).toDouble())
+ assertEquals(3.141592653589793, parser.parse(values[5]).toDouble())
+ assertEquals(2.718281828459045e-3, parser.parse(values[6]).toDouble())
+ assertEquals(2.2250738585072014E-308, parser.parse(values[7]).toDouble())
+ assertEquals(4.9E-15, parser.parse(values[8]).toDouble())
+ }
+
+ @Test
+ fun testInts() {
+ val values = arrayOf(
+ "-0",
+ "0",
+ "-1",
+ "${Int.MAX_VALUE}",
+ "${Int.MIN_VALUE}",
+ "${Long.MAX_VALUE}",
+ "${Long.MIN_VALUE}",
+ )
+ val parser = JSONParser()
+
+ assertEquals(parser.parse(values[0]).toInt(), 0)
+ assertEquals(parser.parse(values[1]).toInt(), 0)
+ assertEquals(parser.parse(values[2]).toInt(), -1)
+ assertEquals(parser.parse(values[3]).toInt(), Int.MAX_VALUE)
+ assertEquals(parser.parse(values[4]).toInt(), Int.MIN_VALUE)
+ assertEquals(parser.parse(values[5]).toLong(), Long.MAX_VALUE)
+ assertEquals(parser.parse(values[6]).toLong(), Long.MIN_VALUE)
+ }
+
+ @Test
+ fun testBooleansAndNull() {
+ val values = arrayOf(
+ "true",
+ "false",
+ "null"
+ )
+ val parser = JSONParser()
+
+ assertEquals(true, parser.parse(values[0]).toBoolean())
+ assertEquals(false, parser.parse(values[1]).toBoolean())
+ assertEquals(true, parser.parse(values[2]).isNull)
+ }
+
+ @Test
+ fun testStrings() {
+ val values = arrayOf(
+ "\"\"",
+ "\"a\"",
+ "\"hello world\"",
+ "\"\\\"\\\\\\/\\b\\f\\n\\r\\t cool\"",
+ "\"\\u0000\"",
+ "\"\\u0021\"",
+ "\"hell\\u24AC\\n\\ro wor \\u0021 ld\"",
+ "\"\\/_\\\\_\\\"_\\uCAFE\\uBABE\\uAB98\\uFCDE\\ubcda\\uef4A\\b\\n\\r\\t`1~!@#\$%^&*()_+-=[]{}|;:',./<>?\"",
+ )
+ val parser = JSONParser()
+
+ // empty
+ var ref = parser.parse(values[0])
+ assertEquals(true, ref.isString)
+ assertEquals("", ref.toString())
+ // a
+ ref = parser.parse(values[1])
+ assertEquals(true, ref.isString)
+ assertEquals("a", ref.toString())
+ // hello world
+ ref = parser.parse(values[2])
+ assertEquals(true, ref.isString)
+ assertEquals("hello world", ref.toString())
+ // "\\\"\\\\\\/\\b\\f\\n\\r\\t\""
+ ref = parser.parse(values[3])
+ assertEquals(true, ref.isString)
+ assertEquals("\"\\/\b${12.toChar()}\n\r\t cool", ref.toString())
+ // 0
+ ref = parser.parse(values[4])
+ assertEquals(true, ref.isString)
+ assertEquals(0.toChar().toString(), ref.toString())
+ // u0021
+ ref = parser.parse(values[5])
+ assertEquals(true, ref.isString)
+ assertEquals(0x21.toChar().toString(), ref.toString())
+ // "\"hell\\u24AC\\n\\ro wor \\u0021 ld\"",
+ ref = parser.parse(values[6])
+ assertEquals(true, ref.isString)
+ assertEquals("hell${0x24AC.toChar()}\n\ro wor ${0x21.toChar()} ld", ref.toString())
+
+ ref = parser.parse(values[7])
+ println(ref.toJson())
+ assertEquals(true, ref.isString)
+ assertEquals("/_\\_\"_쫾몾ꮘﳞ볚\b\n\r\t`1~!@#$%^&*()_+-=[]{}|;:',./<>?", ref.toString())
+ }
+
+ @Test
+ fun testUnicode() {
+ // took from test/unicode_test.json
+ val data = """
+ {
+ "name": "unicode_test",
+ "testarrayofstring": [
+ "Цлїςσδε",
+ "フムアムカモケモ",
+ "フムヤムカモケモ",
+ "㊀㊁㊂㊃㊄",
+ "☳☶☲",
+ "𡇙𝌆"
+ ],
+ "testarrayoftables": [
+ {
+ "name": "Цлїςσδε"
+ },
+ {
+ "name": "☳☶☲"
+ },
+ {
+ "name": "フムヤムカモケモ"
+ },
+ {
+ "name": "㊀㊁㊂㊃㊄"
+ },
+ {
+ "name": "フムアムカモケモ"
+ },
+ {
+ "name": "𡇙𝌆"
+ }
+ ]
+ }
+ """.trimIndent()
+ val parser = JSONParser()
+ val ref = parser.parse(data)
+
+ // name
+ assertEquals(3, ref.toMap().size)
+ assertEquals("unicode_test", ref["name"].toString())
+ // testarrayofstring
+ assertEquals(6, ref["testarrayofstring"].toVector().size)
+ assertEquals("Цлїςσδε", ref["testarrayofstring"][0].toString())
+ assertEquals("フムアムカモケモ", ref["testarrayofstring"][1].toString())
+ assertEquals("フムヤムカモケモ", ref["testarrayofstring"][2].toString())
+ assertEquals("㊀㊁㊂㊃㊄", ref["testarrayofstring"][3].toString())
+ assertEquals("☳☶☲", ref["testarrayofstring"][4].toString())
+ assertEquals("𡇙𝌆", ref["testarrayofstring"][5].toString())
+ // testarrayoftables
+ assertEquals(6, ref["testarrayoftables"].toVector().size)
+ assertEquals("Цлїςσδε", ref["testarrayoftables"][0]["name"].toString())
+ assertEquals("☳☶☲", ref["testarrayoftables"][1]["name"].toString())
+ assertEquals("フムヤムカモケモ", ref["testarrayoftables"][2]["name"].toString())
+ assertEquals("㊀㊁㊂㊃㊄", ref["testarrayoftables"][3]["name"].toString())
+ assertEquals("フムアムカモケモ", ref["testarrayoftables"][4]["name"].toString())
+ assertEquals("𡇙𝌆", ref["testarrayoftables"][5]["name"].toString())
+ }
+
+ @Test
+ fun testArrays() {
+ val values = arrayOf(
+ "[]",
+ "[1]",
+ "[0,1, 2,3 , 4 ]",
+ "[1.0, 2.2250738585072014E-308, 4.9E-320]",
+ "[1.0, 2, \"hello world\"] ",
+ "[ 1.1, 2, [ \"hello\" ] ]",
+ "[[[1]]]"
+ )
+ val parser = JSONParser()
+
+ // empty
+ var ref = parser.parse(values[0])
+ assertEquals(true, ref.isVector)
+ assertEquals(0, parser.parse(values[0]).toVector().size)
+ // single
+ ref = parser.parse(values[1])
+ assertEquals(true, ref.isTypedVector)
+ assertEquals(1, ref[0].toInt())
+ // ints
+ ref = parser.parse(values[2])
+ assertEquals(true, ref.isTypedVector)
+ assertEquals(T_VECTOR_INT, ref.type)
+ assertEquals(5, ref.toVector().size)
+ for (i in 0..4) {
+ assertEquals(i, ref[i].toInt())
+ }
+ // floats
+ ref = parser.parse(values[3])
+ assertEquals(true, ref.isTypedVector)
+ assertEquals(T_VECTOR_FLOAT, ref.type)
+ assertEquals(3, ref.toVector().size)
+ assertEquals(1.0, ref[0].toDouble())
+ assertEquals(2.2250738585072014E-308, ref[1].toDouble())
+ assertEquals(4.9E-320, ref[2].toDouble())
+ // mixed
+ ref = parser.parse(values[4])
+ assertEquals(false, ref.isTypedVector)
+ assertEquals(T_VECTOR, ref.type)
+ assertEquals(1.0, ref[0].toDouble())
+ assertEquals(2, ref[1].toInt())
+ assertEquals("hello world", ref[2].toString())
+ // nester array
+ ref = parser.parse(values[5])
+ assertEquals(false, ref.isTypedVector)
+ assertEquals(T_VECTOR, ref.type)
+ assertEquals(1.1, ref[0].toDouble())
+ assertEquals(2, ref[1].toInt())
+ assertEquals("hello", ref[2][0].toString())
+ }
+
+ /**
+ * Several test cases provided by json.org
+ * For more details, see: http://json.org/JSON_checker/, with only
+ * one exception. Single strings are considered accepted, whereas on
+ * the test suit is should fail.
+ */
+ @Test
+ fun testParseMustFail() {
+ val failList = listOf(
+ "[\"Unclosed array\"",
+ "{unquoted_key: \"keys must be quoted\"}",
+ "[\"extra comma\",]",
+ "[\"double extra comma\",,]",
+ "[ , \"<-- missing value\"]",
+ "[\"Comma after the close\"],",
+ "[\"Extra close\"]]",
+ "{\"Extra comma\": true,}",
+ "{\"Extra value after close\": true} \"misplaced quoted value\"",
+ "{\"Illegal expression\": 1 + 2}",
+ "{\"Illegal invocation\": alert()}",
+ "{\"Numbers cannot have leading zeroes\": 013}",
+ "{\"Numbers cannot be hex\": 0x14}",
+ "[\"Illegal backslash escape: \\x15\"]",
+ "[\\naked]",
+ "[\"Illegal backslash escape: \\017\"]",
+ "[[[[[[[[[[[[[[[[[[[[[[[\"Too deep\"]]]]]]]]]]]]]]]]]]]]]]]",
+ "{\"Missing colon\" null}",
+ "{\"Double colon\":: null}",
+ "{\"Comma instead of colon\", null}",
+ "[\"Colon instead of comma\": false]",
+ "[\"Bad value\", truth]",
+ "['single quote']",
+ "[\"\ttab\tcharacter\tin\tstring\t\"]",
+ "[\"tab\\ character\\ in\\ string\\ \"]",
+ "[\"line\nbreak\"]",
+ "[\"line\\\nbreak\"]",
+ "[0e]",
+ "[0e+]",
+ "[0e+-1]",
+ "{\"Comma instead if closing brace\": true,",
+ "[\"mismatch\"}"
+ )
+ for (data in failList) {
+ try {
+ JSONParser().parse(ArrayReadBuffer(data.encodeToByteArray()))
+ assertTrue(false, "SHOULD NOT PASS: $data")
+ } catch (e: IllegalStateException) {
+ println("FAIL $e")
+ }
+ }
+ }
+
+ @Test
+ fun testParseMustPass() {
+ val passList = listOf(
+ "[\n" +
+ " \"JSON Test Pattern pass1\",\n" +
+ " {\"object with 1 member\":[\"array with 1 element\"]},\n" +
+ " {},\n" +
+ " [],\n" +
+ " -42,\n" +
+ " true,\n" +
+ " false,\n" +
+ " null,\n" +
+ " {\n" +
+ " \"integer\": 1234567890,\n" +
+ " \"real\": -9876.543210,\n" +
+ " \"e\": 0.123456789e-12,\n" +
+ " \"E\": 1.234567890E+34,\n" +
+ " \"\": 23456789012E66,\n" +
+ " \"zero\": 0,\n" +
+ " \"one\": 1,\n" +
+ " \"space\": \" \",\n" +
+ " \"quote\": \"\\\"\",\n" +
+ " \"backslash\": \"\\\\\",\n" +
+ " \"controls\": \"\\b\\f\\n\\r\\t\",\n" +
+ " \"slash\": \"/ & \\/\",\n" +
+ " \"alpha\": \"abcdefghijklmnopqrstuvwyz\",\n" +
+ " \"ALPHA\": \"ABCDEFGHIJKLMNOPQRSTUVWYZ\",\n" +
+ " \"digit\": \"0123456789\",\n" +
+ " \"0123456789\": \"digit\",\n" +
+ " \"special\": \"`1~!@#\$%^&*()_+-={':[,]}|;.</>?\",\n" +
+ " \"hex\": \"\\u0123\\u4567\\u89AB\\uCDEF\\uabcd\\uef4A\",\n" +
+ " \"true\": true,\n" +
+ " \"false\": false,\n" +
+ " \"null\": null,\n" +
+ " \"array\":[ ],\n" +
+ " \"object\":{ },\n" +
+ " \"address\": \"50 St. James Street\",\n" +
+ " \"url\": \"http://www.JSON.org/\",\n" +
+ " \"comment\": \"// /* <!-- --\",\n" +
+ " \"# -- --> */\": \" \",\n" +
+ " \" s p a c e d \" :[1,2 , 3\n" +
+ "\n" +
+ ",\n" +
+ "\n" +
+ "4 , 5 , 6 ,7 ],\"compact\":[1,2,3,4,5,6,7],\n" +
+ " \"jsontext\": \"{\\\"object with 1 member\\\":[\\\"array with 1 element\\\"]}\",\n" +
+ " \"quotes\": \"" \\u0022 %22 0x22 034 "\",\n" +
+ " \"\\/\\\\\\\"\\uCAFE\\uBABE\\uAB98\\uFCDE\\ubcda\\uef4A\\b\\f\\n\\r\\t`1~!@#\$%^&*()_+-=[]{}|;:',./<>?\"\n" +
+ ": \"A key can be any string\"\n" +
+ " },\n" +
+ " 0.5 ,98.6\n" +
+ ",\n" +
+ "99.44\n" +
+ ",\n" +
+ "\n" +
+ "1066,\n" +
+ "1e1,\n" +
+ "0.1e1,\n" +
+ "1e-1,\n" +
+ "1e00,2e+00,2e-00\n" +
+ ",\"rosebud\"]",
+ "{\n" +
+ " \"JSON Test Pattern pass3\": {\n" +
+ " \"The outermost value\": \"must be an object or array.\",\n" +
+ " \"In this test\": \"It is an object.\"\n" +
+ " }\n" +
+ "}",
+ "[[[[[[[[[[[[[[[[[[[\"Not too deep\"]]]]]]]]]]]]]]]]]]]",
+ )
+ for (data in passList) {
+ JSONParser().parse(ArrayReadBuffer(data.encodeToByteArray()))
+ }
+ }
+}
diff --git a/kotlin/flatbuffers-kotlin/src/jsMain/kotlin/com/google/flatbuffers/kotlin/ByteArray.kt b/kotlin/flatbuffers-kotlin/src/jsMain/kotlin/com/google/flatbuffers/kotlin/ByteArray.kt
new file mode 100644
index 0000000..99c6b51
--- /dev/null
+++ b/kotlin/flatbuffers-kotlin/src/jsMain/kotlin/com/google/flatbuffers/kotlin/ByteArray.kt
@@ -0,0 +1,41 @@
+/*
+ * Copyright 2021 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.
+ */
+@file:Suppress("NOTHING_TO_INLINE")
+
+package com.google.flatbuffers.kotlin
+
+/**
+ * This implementation uses Little Endian order.
+ */
+public actual inline fun ByteArray.getUByte(index: Int): UByte = ByteArrayOps.getUByte(this, index)
+public actual inline fun ByteArray.getShort(index: Int): Short = ByteArrayOps.getShort(this, index)
+public actual inline fun ByteArray.getUShort(index: Int): UShort = ByteArrayOps.getUShort(this, index)
+public actual inline fun ByteArray.getInt(index: Int): Int = ByteArrayOps.getInt(this, index)
+public actual inline fun ByteArray.getUInt(index: Int): UInt = ByteArrayOps.getUInt(this, index)
+public actual inline fun ByteArray.getLong(index: Int): Long = ByteArrayOps.getLong(this, index)
+public actual inline fun ByteArray.getULong(index: Int): ULong = ByteArrayOps.getULong(this, index)
+public actual inline fun ByteArray.getFloat(index: Int): Float = ByteArrayOps.getFloat(this, index)
+public actual inline fun ByteArray.getDouble(index: Int): Double = ByteArrayOps.getDouble(this, index)
+
+public actual inline fun ByteArray.setUByte(index: Int, value: UByte): Unit = ByteArrayOps.setUByte(this, index, value)
+public actual inline fun ByteArray.setShort(index: Int, value: Short): Unit = ByteArrayOps.setShort(this, index, value)
+public actual inline fun ByteArray.setUShort(index: Int, value: UShort): Unit = ByteArrayOps.setUShort(this, index, value)
+public actual inline fun ByteArray.setInt(index: Int, value: Int): Unit = ByteArrayOps.setInt(this, index, value)
+public actual inline fun ByteArray.setUInt(index: Int, value: UInt): Unit = ByteArrayOps.setUInt(this, index, value)
+public actual inline fun ByteArray.setLong(index: Int, value: Long): Unit = ByteArrayOps.setLong(this, index, value)
+public actual inline fun ByteArray.setULong(index: Int, value: ULong): Unit = ByteArrayOps.setULong(this, index, value)
+public actual inline fun ByteArray.setFloat(index: Int, value: Float): Unit = ByteArrayOps.setFloat(this, index, value)
+public actual inline fun ByteArray.setDouble(index: Int, value: Double): Unit = ByteArrayOps.setDouble(this, index, value)
diff --git a/kotlin/flatbuffers-kotlin/src/jvmMain/kotlin/com/google/flatbuffers/kotlin/ByteArray.kt b/kotlin/flatbuffers-kotlin/src/jvmMain/kotlin/com/google/flatbuffers/kotlin/ByteArray.kt
new file mode 100644
index 0000000..7e5d376
--- /dev/null
+++ b/kotlin/flatbuffers-kotlin/src/jvmMain/kotlin/com/google/flatbuffers/kotlin/ByteArray.kt
@@ -0,0 +1,42 @@
+/*
+ * Copyright 2021 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.
+ */
+@file:JvmName("JVMByteArray")
+@file:Suppress("NOTHING_TO_INLINE")
+
+package com.google.flatbuffers.kotlin
+
+/**
+ * This implementation uses Little Endian order.
+ */
+public actual inline fun ByteArray.getUByte(index: Int): UByte = ByteArrayOps.getUByte(this, index)
+public actual inline fun ByteArray.getShort(index: Int): Short = ByteArrayOps.getShort(this, index)
+public actual inline fun ByteArray.getUShort(index: Int): UShort = ByteArrayOps.getUShort(this, index)
+public actual inline fun ByteArray.getInt(index: Int): Int = ByteArrayOps.getInt(this, index)
+public actual inline fun ByteArray.getUInt(index: Int): UInt = ByteArrayOps.getUInt(this, index)
+public actual inline fun ByteArray.getLong(index: Int): Long = ByteArrayOps.getLong(this, index)
+public actual inline fun ByteArray.getULong(index: Int): ULong = ByteArrayOps.getULong(this, index)
+public actual inline fun ByteArray.getFloat(index: Int): Float = ByteArrayOps.getFloat(this, index)
+public actual inline fun ByteArray.getDouble(index: Int): Double = ByteArrayOps.getDouble(this, index)
+
+public actual inline fun ByteArray.setUByte(index: Int, value: UByte): Unit = ByteArrayOps.setUByte(this, index, value)
+public actual inline fun ByteArray.setShort(index: Int, value: Short): Unit = ByteArrayOps.setShort(this, index, value)
+public actual inline fun ByteArray.setUShort(index: Int, value: UShort): Unit = ByteArrayOps.setUShort(this, index, value)
+public actual inline fun ByteArray.setInt(index: Int, value: Int): Unit = ByteArrayOps.setInt(this, index, value)
+public actual inline fun ByteArray.setUInt(index: Int, value: UInt): Unit = ByteArrayOps.setUInt(this, index, value)
+public actual inline fun ByteArray.setLong(index: Int, value: Long): Unit = ByteArrayOps.setLong(this, index, value)
+public actual inline fun ByteArray.setULong(index: Int, value: ULong): Unit = ByteArrayOps.setULong(this, index, value)
+public actual inline fun ByteArray.setFloat(index: Int, value: Float): Unit = ByteArrayOps.setFloat(this, index, value)
+public actual inline fun ByteArray.setDouble(index: Int, value: Double): Unit = ByteArrayOps.setDouble(this, index, value)
diff --git a/kotlin/flatbuffers-kotlin/src/jvmTest/kotlin/com/google/flatbuffers/kotlin/Utf8Test.kt b/kotlin/flatbuffers-kotlin/src/jvmTest/kotlin/com/google/flatbuffers/kotlin/Utf8Test.kt
new file mode 100644
index 0000000..96b9c0a
--- /dev/null
+++ b/kotlin/flatbuffers-kotlin/src/jvmTest/kotlin/com/google/flatbuffers/kotlin/Utf8Test.kt
@@ -0,0 +1,35 @@
+/*
+ * Copyright 2021 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.
+ */
+package com.google.flatbuffers.kotlin
+
+import org.junit.Test
+import kotlin.test.assertEquals
+
+class Utf8Test {
+
+ @Test
+ fun testUtf8EncodingDecoding() {
+ val utf8Lines = String(this.javaClass.classLoader.getResourceAsStream("utf8_sample.txt")!!.readBytes())
+ .split("\n")
+ .filter { it.trim().isNotEmpty() }
+
+ val utf8Bytes = utf8Lines.map { s -> ByteArray(Utf8.encodedLength(s)).also { Utf8.encodeUtf8Array(s, it) } }
+ utf8Bytes.indices.forEach {
+ assertArrayEquals(utf8Lines[it].encodeToByteArray(), utf8Bytes[it])
+ assertEquals(utf8Lines[it], Utf8.decodeUtf8Array(utf8Bytes[it]))
+ }
+ }
+}
diff --git a/kotlin/flatbuffers-kotlin/src/jvmTest/resources/utf8_sample.txt b/kotlin/flatbuffers-kotlin/src/jvmTest/resources/utf8_sample.txt
new file mode 100644
index 0000000..4fea69b
--- /dev/null
+++ b/kotlin/flatbuffers-kotlin/src/jvmTest/resources/utf8_sample.txt
@@ -0,0 +1,201 @@
+Markus Kuhn <http://www.cl.cam.ac.uk/~mgk25/> - 2015-08-28 - CC BY 4.0
+UTF-8 encoded sample plain-text file
+‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
+Markus Kuhn [ˈmaʳkʊs kuːn] <mkuhn@acm.org> — 1999-08-20
+
+The ASCII compatible UTF-8 encoding of ISO 10646 and Unicode
+plain-text files is defined in RFC 2279 and in ISO 10646-1 Annex R.
+
+
+Using Unicode/UTF-8, you can write in emails and source code things such as
+
+Mathematics and Sciences:
+
+ ∮ E⋅da = Q, n → ∞, ∑ f(i) = ∏ g(i), ∀x∈ℝ: ⌈x⌉ = −⌊−x⌋, α ∧ ¬β = ¬(¬α ∨ β),
+
+ ℕ ⊆ ℕ₀ ⊂ ℤ ⊂ ℚ ⊂ ℝ ⊂ ℂ, ⊥ < a ≠ b ≡ c ≤ d ≪ ⊤ ⇒ (A ⇔ B),
+
+ 2H₂ + O₂ ⇌ 2H₂O, R = 4.7 kΩ, ⌀ 200 mm
+
+Linguistics and dictionaries:
+
+ ði ıntəˈnæʃənəl fəˈnɛtık əsoʊsiˈeıʃn
+ Y [ˈʏpsilɔn], Yen [jɛn], Yoga [ˈjoːgɑ]
+
+APL:
+
+ ((V⍳V)=⍳⍴V)/V←,V ⌷←⍳→⍴∆∇⊃‾⍎⍕⌈
+
+Nicer typography in plain text files:
+
+ ╔══════════════════════════════════════════╗
+ ║ ║
+ ║ • ‘single’ and “double” quotes ║
+ ║ ║
+ ║ • Curly apostrophes: “We’ve been here” ║
+ ║ ║
+ ║ • Latin-1 apostrophe and accents: '´` ║
+ ║ ║
+ ║ • ‚deutsche‘ „Anführungszeichen“ ║
+ ║ ║
+ ║ • †, ‡, ‰, •, 3–4, —, −5/+5, ™, … ║
+ ║ ║
+ ║ • ASCII safety test: 1lI|, 0OD, 8B ║
+ ║ ╭─────────╮ ║
+ ║ • the euro symbol: │ 14.95 € │ ║
+ ║ ╰─────────╯ ║
+ ╚══════════════════════════════════════════╝
+
+Greek (in Polytonic):
+
+ The Greek anthem:
+
+ Σὲ γνωρίζω ἀπὸ τὴν κόψη
+ τοῦ σπαθιοῦ τὴν τρομερή,
+ σὲ γνωρίζω ἀπὸ τὴν ὄψη
+ ποὺ μὲ βία μετράει τὴ γῆ.
+
+ ᾿Απ᾿ τὰ κόκκαλα βγαλμένη
+ τῶν ῾Ελλήνων τὰ ἱερά
+ καὶ σὰν πρῶτα ἀνδρειωμένη
+ χαῖρε, ὦ χαῖρε, ᾿Ελευθεριά!
+
+ From a speech of Demosthenes in the 4th century BC:
+
+ Οὐχὶ ταὐτὰ παρίσταταί μοι γιγνώσκειν, ὦ ἄνδρες ᾿Αθηναῖοι,
+ ὅταν τ᾿ εἰς τὰ πράγματα ἀποβλέψω καὶ ὅταν πρὸς τοὺς
+ λόγους οὓς ἀκούω· τοὺς μὲν γὰρ λόγους περὶ τοῦ
+ τιμωρήσασθαι Φίλιππον ὁρῶ γιγνομένους, τὰ δὲ πράγματ᾿
+ εἰς τοῦτο προήκοντα, ὥσθ᾿ ὅπως μὴ πεισόμεθ᾿ αὐτοὶ
+ πρότερον κακῶς σκέψασθαι δέον. οὐδέν οὖν ἄλλο μοι δοκοῦσιν
+ οἱ τὰ τοιαῦτα λέγοντες ἢ τὴν ὑπόθεσιν, περὶ ἧς βουλεύεσθαι,
+ οὐχὶ τὴν οὖσαν παριστάντες ὑμῖν ἁμαρτάνειν. ἐγὼ δέ, ὅτι μέν
+ ποτ᾿ ἐξῆν τῇ πόλει καὶ τὰ αὑτῆς ἔχειν ἀσφαλῶς καὶ Φίλιππον
+ τιμωρήσασθαι, καὶ μάλ᾿ ἀκριβῶς οἶδα· ἐπ᾿ ἐμοῦ γάρ, οὐ πάλαι
+ γέγονεν ταῦτ᾿ ἀμφότερα· νῦν μέντοι πέπεισμαι τοῦθ᾿ ἱκανὸν
+ προλαβεῖν ἡμῖν εἶναι τὴν πρώτην, ὅπως τοὺς συμμάχους
+ σώσομεν. ἐὰν γὰρ τοῦτο βεβαίως ὑπάρξῃ, τότε καὶ περὶ τοῦ
+ τίνα τιμωρήσεταί τις καὶ ὃν τρόπον ἐξέσται σκοπεῖν· πρὶν δὲ
+ τὴν ἀρχὴν ὀρθῶς ὑποθέσθαι, μάταιον ἡγοῦμαι περὶ τῆς
+ τελευτῆς ὁντινοῦν ποιεῖσθαι λόγον.
+
+ Δημοσθένους, Γ´ ᾿Ολυνθιακὸς
+
+Georgian:
+
+ From a Unicode conference invitation:
+
+ გთხოვთ ახლავე გაიაროთ რეგისტრაცია Unicode-ის მეათე საერთაშორისო
+ კონფერენციაზე დასასწრებად, რომელიც გაიმართება 10-12 მარტს,
+ ქ. მაინცში, გერმანიაში. კონფერენცია შეჰკრებს ერთად მსოფლიოს
+ ექსპერტებს ისეთ დარგებში როგორიცაა ინტერნეტი და Unicode-ი,
+ ინტერნაციონალიზაცია და ლოკალიზაცია, Unicode-ის გამოყენება
+ ოპერაციულ სისტემებსა, და გამოყენებით პროგრამებში, შრიფტებში,
+ ტექსტების დამუშავებასა და მრავალენოვან კომპიუტერულ სისტემებში.
+
+Russian:
+
+ From a Unicode conference invitation:
+
+ Зарегистрируйтесь сейчас на Десятую Международную Конференцию по
+ Unicode, которая состоится 10-12 марта 1997 года в Майнце в Германии.
+ Конференция соберет широкий круг экспертов по вопросам глобального
+ Интернета и Unicode, локализации и интернационализации, воплощению и
+ применению Unicode в различных операционных системах и программных
+ приложениях, шрифтах, верстке и многоязычных компьютерных системах.
+
+Thai (UCS Level 2):
+
+ Excerpt from a poetry on The Romance of The Three Kingdoms (a Chinese
+ classic 'San Gua'):
+
+ [----------------------------|------------------------]
+ ๏ แผ่นดินฮั่นเสื่อมโทรมแสนสังเวช พระปกเกศกองบู๊กู้ขึ้นใหม่
+ สิบสองกษัตริย์ก่อนหน้าแลถัดไป สององค์ไซร้โง่เขลาเบาปัญญา
+ ทรงนับถือขันทีเป็นที่พึ่ง บ้านเมืองจึงวิปริตเป็นนักหนา
+ โฮจิ๋นเรียกทัพทั่วหัวเมืองมา หมายจะฆ่ามดชั่วตัวสำคัญ
+ เหมือนขับไสไล่เสือจากเคหา รับหมาป่าเข้ามาเลยอาสัญ
+ ฝ่ายอ้องอุ้นยุแยกให้แตกกัน ใช้สาวนั้นเป็นชนวนชื่นชวนใจ
+ พลันลิฉุยกุยกีกลับก่อเหตุ ช่างอาเพศจริงหนาฟ้าร้องไห้
+ ต้องรบราฆ่าฟันจนบรรลัย ฤๅหาใครค้ำชูกู้บรรลังก์ ฯ
+
+ (The above is a two-column text. If combining characters are handled
+ correctly, the lines of the second column should be aligned with the
+ | character above.)
+
+Ethiopian:
+
+ Proverbs in the Amharic language:
+
+ ሰማይ አይታረስ ንጉሥ አይከሰስ።
+ ብላ ካለኝ እንደአባቴ በቆመጠኝ።
+ ጌጥ ያለቤቱ ቁምጥና ነው።
+ ደሀ በሕልሙ ቅቤ ባይጠጣ ንጣት በገደለው።
+ የአፍ ወለምታ በቅቤ አይታሽም።
+ አይጥ በበላ ዳዋ ተመታ።
+ ሲተረጉሙ ይደረግሙ።
+ ቀስ በቀስ፥ ዕንቁላል በእግሩ ይሄዳል።
+ ድር ቢያብር አንበሳ ያስር።
+ ሰው እንደቤቱ እንጅ እንደ ጉረቤቱ አይተዳደርም።
+ እግዜር የከፈተውን ጉሮሮ ሳይዘጋው አይድርም።
+ የጎረቤት ሌባ፥ ቢያዩት ይስቅ ባያዩት ያጠልቅ።
+ ሥራ ከመፍታት ልጄን ላፋታት።
+ ዓባይ ማደሪያ የለው፥ ግንድ ይዞ ይዞራል።
+ የእስላም አገሩ መካ የአሞራ አገሩ ዋርካ።
+ ተንጋሎ ቢተፉ ተመልሶ ባፉ።
+ ወዳጅህ ማር ቢሆን ጨርስህ አትላሰው።
+ እግርህን በፍራሽህ ልክ ዘርጋ።
+
+Runes:
+
+ ᚻᛖ ᚳᚹᚫᚦ ᚦᚫᛏ ᚻᛖ ᛒᚢᛞᛖ ᚩᚾ ᚦᚫᛗ ᛚᚪᚾᛞᛖ ᚾᚩᚱᚦᚹᛖᚪᚱᛞᚢᛗ ᚹᛁᚦ ᚦᚪ ᚹᛖᛥᚫ
+
+ (Old English, which transcribed into Latin reads 'He cwaeth that he
+ bude thaem lande northweardum with tha Westsae.' and means 'He said
+ that he lived in the northern land near the Western Sea.')
+
+Braille:
+
+ ⡌⠁⠧⠑ ⠼⠁⠒ ⡍⠜⠇⠑⠹⠰⠎ ⡣⠕⠌
+
+ ⡍⠜⠇⠑⠹ ⠺⠁⠎ ⠙⠑⠁⠙⠒ ⠞⠕ ⠃⠑⠛⠔ ⠺⠊⠹⠲ ⡹⠻⠑ ⠊⠎ ⠝⠕ ⠙⠳⠃⠞
+ ⠱⠁⠞⠑⠧⠻ ⠁⠃⠳⠞ ⠹⠁⠞⠲ ⡹⠑ ⠗⠑⠛⠊⠌⠻ ⠕⠋ ⠙⠊⠎ ⠃⠥⠗⠊⠁⠇ ⠺⠁⠎
+ ⠎⠊⠛⠝⠫ ⠃⠹ ⠹⠑ ⠊⠇⠻⠛⠹⠍⠁⠝⠂ ⠹⠑ ⠊⠇⠻⠅⠂ ⠹⠑ ⠥⠝⠙⠻⠞⠁⠅⠻⠂
+ ⠁⠝⠙ ⠹⠑ ⠡⠊⠑⠋ ⠍⠳⠗⠝⠻⠲ ⡎⠊⠗⠕⠕⠛⠑ ⠎⠊⠛⠝⠫ ⠊⠞⠲ ⡁⠝⠙
+ ⡎⠊⠗⠕⠕⠛⠑⠰⠎ ⠝⠁⠍⠑ ⠺⠁⠎ ⠛⠕⠕⠙ ⠥⠏⠕⠝ ⠰⡡⠁⠝⠛⠑⠂ ⠋⠕⠗ ⠁⠝⠹⠹⠔⠛ ⠙⠑
+ ⠡⠕⠎⠑ ⠞⠕ ⠏⠥⠞ ⠙⠊⠎ ⠙⠁⠝⠙ ⠞⠕⠲
+
+ ⡕⠇⠙ ⡍⠜⠇⠑⠹ ⠺⠁⠎ ⠁⠎ ⠙⠑⠁⠙ ⠁⠎ ⠁ ⠙⠕⠕⠗⠤⠝⠁⠊⠇⠲
+
+ ⡍⠔⠙⠖ ⡊ ⠙⠕⠝⠰⠞ ⠍⠑⠁⠝ ⠞⠕ ⠎⠁⠹ ⠹⠁⠞ ⡊ ⠅⠝⠪⠂ ⠕⠋ ⠍⠹
+ ⠪⠝ ⠅⠝⠪⠇⠫⠛⠑⠂ ⠱⠁⠞ ⠹⠻⠑ ⠊⠎ ⠏⠜⠞⠊⠊⠥⠇⠜⠇⠹ ⠙⠑⠁⠙ ⠁⠃⠳⠞
+ ⠁ ⠙⠕⠕⠗⠤⠝⠁⠊⠇⠲ ⡊ ⠍⠊⠣⠞ ⠙⠁⠧⠑ ⠃⠑⠲ ⠔⠊⠇⠔⠫⠂ ⠍⠹⠎⠑⠇⠋⠂ ⠞⠕
+ ⠗⠑⠛⠜⠙ ⠁ ⠊⠕⠋⠋⠔⠤⠝⠁⠊⠇ ⠁⠎ ⠹⠑ ⠙⠑⠁⠙⠑⠌ ⠏⠊⠑⠊⠑ ⠕⠋ ⠊⠗⠕⠝⠍⠕⠝⠛⠻⠹
+ ⠔ ⠹⠑ ⠞⠗⠁⠙⠑⠲ ⡃⠥⠞ ⠹⠑ ⠺⠊⠎⠙⠕⠍ ⠕⠋ ⠳⠗ ⠁⠝⠊⠑⠌⠕⠗⠎
+ ⠊⠎ ⠔ ⠹⠑ ⠎⠊⠍⠊⠇⠑⠆ ⠁⠝⠙ ⠍⠹ ⠥⠝⠙⠁⠇⠇⠪⠫ ⠙⠁⠝⠙⠎
+ ⠩⠁⠇⠇ ⠝⠕⠞ ⠙⠊⠌⠥⠗⠃ ⠊⠞⠂ ⠕⠗ ⠹⠑ ⡊⠳⠝⠞⠗⠹⠰⠎ ⠙⠕⠝⠑ ⠋⠕⠗⠲ ⡹⠳
+ ⠺⠊⠇⠇ ⠹⠻⠑⠋⠕⠗⠑ ⠏⠻⠍⠊⠞ ⠍⠑ ⠞⠕ ⠗⠑⠏⠑⠁⠞⠂ ⠑⠍⠏⠙⠁⠞⠊⠊⠁⠇⠇⠹⠂ ⠹⠁⠞
+ ⡍⠜⠇⠑⠹ ⠺⠁⠎ ⠁⠎ ⠙⠑⠁⠙ ⠁⠎ ⠁ ⠙⠕⠕⠗⠤⠝⠁⠊⠇⠲
+
+ (The first couple of paragraphs of "A Christmas Carol" by Dickens)
+
+Compact font selection example text:
+
+ ABCDEFGHIJKLMNOPQRSTUVWXYZ /0123456789
+ abcdefghijklmnopqrstuvwxyz £©µÀÆÖÞßéöÿ
+ –—‘“”„†•…‰™œŠŸž€ ΑΒΓΔΩαβγδω АБВГДабвгд
+ ∀∂∈ℝ∧∪≡∞ ↑↗↨↻⇣ ┐┼╔╘░►☺♀ fi�⑀₂ἠḂӥẄɐː⍎אԱა
+
+Greetings in various languages:
+
+ Hello world, Καλημέρα κόσμε, コンニチハ
+
+Box drawing alignment tests: █
+ ▉
+ ╔══╦══╗ ┌──┬──┐ ╭──┬──╮ ╭──┬──╮ ┏━━┳━━┓ ┎┒┏┑ ╷ ╻ ┏┯┓ ┌┰┐ ▊ ╱╲╱╲╳╳╳
+ ║┌─╨─┐║ │╔═╧═╗│ │╒═╪═╕│ │╓─╁─╖│ ┃┌─╂─┐┃ ┗╃╄┙ ╶┼╴╺╋╸┠┼┨ ┝╋┥ ▋ ╲╱╲╱╳╳╳
+ ║│╲ ╱│║ │║ ║│ ││ │ ││ │║ ┃ ║│ ┃│ ╿ │┃ ┍╅╆┓ ╵ ╹ ┗┷┛ └┸┘ ▌ ╱╲╱╲╳╳╳
+ ╠╡ ╳ ╞╣ ├╢ ╟┤ ├┼─┼─┼┤ ├╫─╂─╫┤ ┣┿╾┼╼┿┫ ┕┛┖┚ ┌┄┄┐ ╎ ┏┅┅┓ ┋ ▍ ╲╱╲╱╳╳╳
+ ║│╱ ╲│║ │║ ║│ ││ │ ││ │║ ┃ ║│ ┃│ ╽ │┃ ░░▒▒▓▓██ ┊ ┆ ╎ ╏ ┇ ┋ ▎
+ ║└─╥─┘║ │╚═╤═╝│ │╘═╪═╛│ │╙─╀─╜│ ┃└─╂─┘┃ ░░▒▒▓▓██ ┊ ┆ ╎ ╏ ┇ ┋ ▏
+ ╚══╩══╝ └──┴──┘ ╰──┴──╯ ╰──┴──╯ ┗━━┻━━┛ └╌╌┘ ╎ ┗╍╍┛ ┋ ▁▂▃▄▅▆▇█
diff --git a/kotlin/flatbuffers-kotlin/src/nativeMain/kotlin/com/google/flatbuffers/kotlin/ByteArray.kt b/kotlin/flatbuffers-kotlin/src/nativeMain/kotlin/com/google/flatbuffers/kotlin/ByteArray.kt
new file mode 100644
index 0000000..e9dc087
--- /dev/null
+++ b/kotlin/flatbuffers-kotlin/src/nativeMain/kotlin/com/google/flatbuffers/kotlin/ByteArray.kt
@@ -0,0 +1,41 @@
+/*
+ * Copyright 2021 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.
+ */
+@file:Suppress("NOTHING_TO_INLINE")
+package com.google.flatbuffers.kotlin
+
+/**
+ * This implementation assumes that of native macOSX64 the byte order of the implementation is Little Endian.
+ */
+
+public actual inline fun ByteArray.getUByte(index: Int): UByte = getUByteAt(index)
+public actual inline fun ByteArray.getShort(index: Int): Short = getShortAt(index)
+public actual inline fun ByteArray.getUShort(index: Int): UShort = getUShortAt(index)
+public actual inline fun ByteArray.getInt(index: Int): Int = getIntAt(index)
+public actual inline fun ByteArray.getUInt(index: Int): UInt = getUIntAt(index)
+public actual inline fun ByteArray.getLong(index: Int): Long = getLongAt(index)
+public actual inline fun ByteArray.getULong(index: Int): ULong = getULongAt(index)
+
+public actual inline fun ByteArray.setUByte(index: Int, value: UByte): Unit = setUByteAt(index, value)
+public actual inline fun ByteArray.setShort(index: Int, value: Short): Unit = setShortAt(index, value)
+public actual inline fun ByteArray.setUShort(index: Int, value: UShort): Unit = setUShortAt(index, value)
+public actual inline fun ByteArray.setInt(index: Int, value: Int): Unit = setIntAt(index, value)
+public actual inline fun ByteArray.setUInt(index: Int, value: UInt): Unit = setUIntAt(index, value)
+public actual inline fun ByteArray.setLong(index: Int, value: Long): Unit = setLongAt(index, value)
+public actual inline fun ByteArray.setULong(index: Int, value: ULong): Unit = setULongAt(index, value)
+public actual inline fun ByteArray.setFloat(index: Int, value: Float): Unit = setFloatAt(index, value)
+public actual inline fun ByteArray.setDouble(index: Int, value: Double): Unit = setDoubleAt(index, value)
+public actual inline fun ByteArray.getFloat(index: Int): Float = Float.fromBits(getIntAt(index))
+public actual inline fun ByteArray.getDouble(index: Int): Double = Double.fromBits(getLongAt(index))
diff --git a/kotlin/gradle/wrapper/gradle-wrapper.jar b/kotlin/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 0000000..62d4c05
--- /dev/null
+++ b/kotlin/gradle/wrapper/gradle-wrapper.jar
Binary files differ
diff --git a/kotlin/gradle/wrapper/gradle-wrapper.properties b/kotlin/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 0000000..8faf39d
--- /dev/null
+++ b/kotlin/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,9 @@
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-6.3-bin.zip
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
+# Remove kotlin MPP warning
+kotlin.mpp.stability.nowarn=true
+# Needed to share source among different targets
+kotlin.mpp.enableGranularSourceSetsMetadata=true
diff --git a/kotlin/gradlew b/kotlin/gradlew
new file mode 100755
index 0000000..fbd7c51
--- /dev/null
+++ b/kotlin/gradlew
@@ -0,0 +1,185 @@
+#!/usr/bin/env sh
+
+#
+# Copyright 2015 the original author or authors.
+#
+# 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
+#
+# https://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.
+#
+
+##############################################################################
+##
+## Gradle start up script for UN*X
+##
+##############################################################################
+
+# Attempt to set APP_HOME
+# Resolve links: $0 may be a link
+PRG="$0"
+# Need this for relative symlinks.
+while [ -h "$PRG" ] ; do
+ ls=`ls -ld "$PRG"`
+ link=`expr "$ls" : '.*-> \(.*\)$'`
+ if expr "$link" : '/.*' > /dev/null; then
+ PRG="$link"
+ else
+ PRG=`dirname "$PRG"`"/$link"
+ fi
+done
+SAVED="`pwd`"
+cd "`dirname \"$PRG\"`/" >/dev/null
+APP_HOME="`pwd -P`"
+cd "$SAVED" >/dev/null
+
+APP_NAME="Gradle"
+APP_BASE_NAME=`basename "$0"`
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD="maximum"
+
+warn () {
+ echo "$*"
+}
+
+die () {
+ echo
+ echo "$*"
+ echo
+ exit 1
+}
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+nonstop=false
+case "`uname`" in
+ CYGWIN* )
+ cygwin=true
+ ;;
+ Darwin* )
+ darwin=true
+ ;;
+ MINGW* )
+ msys=true
+ ;;
+ NONSTOP* )
+ nonstop=true
+ ;;
+esac
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+ # IBM's JDK on AIX uses strange locations for the executables
+ JAVACMD="$JAVA_HOME/jre/sh/java"
+ else
+ JAVACMD="$JAVA_HOME/bin/java"
+ fi
+ if [ ! -x "$JAVACMD" ] ; then
+ die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+else
+ JAVACMD="java"
+ which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+fi
+
+# Increase the maximum file descriptors if we can.
+if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
+ MAX_FD_LIMIT=`ulimit -H -n`
+ if [ $? -eq 0 ] ; then
+ if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
+ MAX_FD="$MAX_FD_LIMIT"
+ fi
+ ulimit -n $MAX_FD
+ if [ $? -ne 0 ] ; then
+ warn "Could not set maximum file descriptor limit: $MAX_FD"
+ fi
+ else
+ warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
+ fi
+fi
+
+# For Darwin, add options to specify how the application appears in the dock
+if $darwin; then
+ GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
+fi
+
+# For Cygwin or MSYS, switch paths to Windows format before running java
+if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
+ APP_HOME=`cygpath --path --mixed "$APP_HOME"`
+ CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
+
+ JAVACMD=`cygpath --unix "$JAVACMD"`
+
+ # We build the pattern for arguments to be converted via cygpath
+ ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
+ SEP=""
+ for dir in $ROOTDIRSRAW ; do
+ ROOTDIRS="$ROOTDIRS$SEP$dir"
+ SEP="|"
+ done
+ OURCYGPATTERN="(^($ROOTDIRS))"
+ # Add a user-defined pattern to the cygpath arguments
+ if [ "$GRADLE_CYGPATTERN" != "" ] ; then
+ OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
+ fi
+ # Now convert the arguments - kludge to limit ourselves to /bin/sh
+ i=0
+ for arg in "$@" ; do
+ CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
+ CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
+
+ if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
+ eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
+ else
+ eval `echo args$i`="\"$arg\""
+ fi
+ i=`expr $i + 1`
+ done
+ case $i in
+ 0) set -- ;;
+ 1) set -- "$args0" ;;
+ 2) set -- "$args0" "$args1" ;;
+ 3) set -- "$args0" "$args1" "$args2" ;;
+ 4) set -- "$args0" "$args1" "$args2" "$args3" ;;
+ 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
+ 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
+ 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
+ 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
+ 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
+ esac
+fi
+
+# Escape application args
+save () {
+ for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
+ echo " "
+}
+APP_ARGS=`save "$@"`
+
+# Collect all arguments for the java command, following the shell quoting and substitution rules
+eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
+
+exec "$JAVACMD" "$@"
diff --git a/kotlin/gradlew.bat b/kotlin/gradlew.bat
new file mode 100644
index 0000000..5093609
--- /dev/null
+++ b/kotlin/gradlew.bat
@@ -0,0 +1,104 @@
+@rem
+@rem Copyright 2015 the original author or authors.
+@rem
+@rem Licensed under the Apache License, Version 2.0 (the "License");
+@rem you may not use this file except in compliance with the License.
+@rem You may obtain a copy of the License at
+@rem
+@rem https://www.apache.org/licenses/LICENSE-2.0
+@rem
+@rem Unless required by applicable law or agreed to in writing, software
+@rem distributed under the License is distributed on an "AS IS" BASIS,
+@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@rem See the License for the specific language governing permissions and
+@rem limitations under the License.
+@rem
+
+@if "%DEBUG%" == "" @echo off
+@rem ##########################################################################
+@rem
+@rem Gradle startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables with windows NT shell
+if "%OS%"=="Windows_NT" setlocal
+
+set DIRNAME=%~dp0
+if "%DIRNAME%" == "" set DIRNAME=.
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Resolve any "." and ".." in APP_HOME to make it shorter.
+for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if "%ERRORLEVEL%" == "0" goto init
+
+echo.
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto init
+
+echo.
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:init
+@rem Get command-line arguments, handling Windows variants
+
+if not "%OS%" == "Windows_NT" goto win9xME_args
+
+:win9xME_args
+@rem Slurp the command line arguments.
+set CMD_LINE_ARGS=
+set _SKIP=2
+
+:win9xME_args_slurp
+if "x%~1" == "x" goto execute
+
+set CMD_LINE_ARGS=%*
+
+:execute
+@rem Setup the command line
+
+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
+
+
+@rem Execute Gradle
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
+
+:end
+@rem End local scope for the variables with windows NT shell
+if "%ERRORLEVEL%"=="0" goto mainEnd
+
+:fail
+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
+rem the _cmd.exe /c_ return code!
+if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
+exit /b 1
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega
diff --git a/kotlin/settings.gradle b/kotlin/settings.gradle
new file mode 100644
index 0000000..a30971c
--- /dev/null
+++ b/kotlin/settings.gradle
@@ -0,0 +1,10 @@
+pluginManagement {
+ repositories {
+ mavenCentral()
+ gradlePluginPortal()
+ }
+}
+
+
+rootProject.name = 'flatbuffers-kotlin'
+include 'flatbuffers-kotlin', "benchmark"
diff --git a/kotlin/spotless/spotless.kt b/kotlin/spotless/spotless.kt
new file mode 100644
index 0000000..6363ca0
--- /dev/null
+++ b/kotlin/spotless/spotless.kt
@@ -0,0 +1,15 @@
+/*
+ * Copyright $YEAR 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.
+ */
diff --git a/lobster/flatbuffers.lobster b/lobster/flatbuffers.lobster
index 8b04c87..1199e50 100644
--- a/lobster/flatbuffers.lobster
+++ b/lobster/flatbuffers.lobster
@@ -175,25 +175,30 @@
while current_vtable.length <= slotnum: current_vtable.push(0)
current_vtable[slotnum] = head
- def __Finish(root_table:offset, size_prefix:int):
+ def __Finish(root_table:offset, size_prefix:int, file_identifier:string?):
// Finish finalizes a buffer, pointing to the given root_table
assert not finished
assert not nested
var prep_size = sz_32
+ if file_identifier:
+ prep_size += sz_32
if size_prefix:
prep_size += sz_32
Prep(minalign, prep_size)
+ if file_identifier:
+ assert file_identifier.length == 4
+ buf, head = buf.write_substring_back(head, file_identifier, false)
PrependUOffsetTRelative(root_table)
if size_prefix:
PrependInt32(head)
finished = true
return Start()
- def Finish(root_table:offset):
- return __Finish(root_table, false)
+ def Finish(root_table:offset, file_identifier:string? = nil):
+ return __Finish(root_table, false, file_identifier)
- def FinishSizePrefixed(root_table:offset):
- return __Finish(root_table, true)
+ def FinishSizePrefixed(root_table:offset, file_identifier:string? = nil):
+ return __Finish(root_table, true, file_identifier)
def PrependBool(x):
buf, head = buf.write_int8_le_back(head, x)
@@ -299,3 +304,9 @@
// elsewhere.
assert x.o == head
Slot(v)
+
+def has_identifier(buf:string, file_identifier:string):
+ assert file_identifier.length == 4
+ return buf.length >= 8 and buf.substring(4, 4) == file_identifier
+
+
diff --git a/lua/flatbuffers/binaryarray.lua b/lua/flatbuffers/binaryarray.lua
index bf728cd..4d72375 100644
--- a/lua/flatbuffers/binaryarray.lua
+++ b/lua/flatbuffers/binaryarray.lua
@@ -1,3 +1,9 @@
+local compat = require("flatbuffers.compat")
+-- locals for slightly faster access
+local string_pack = compat.string_pack
+local string_unpack = compat.string_unpack
+
+
local m = {} -- the module table
local mt = {} -- the module metatable
@@ -44,7 +50,10 @@
-- updated the startPos based on the size of the
-- value
while startPos < endPos do
- local v = d[startPos] or '/0'
+ local v = d[startPos]
+ if not v or v == "" then
+ v = '/0'
+ end
table.insert(b, v)
startPos = startPos + #v
end
@@ -104,19 +113,15 @@
self.data[position] = value
end
--- locals for slightly faster access
-local sunpack = string.unpack
-local spack = string.pack
-
-- Pack the data into a binary representation
function m.Pack(fmt, ...)
- return spack(fmt, ...)
+ return string_pack(fmt, ...)
end
-- Unpack the data from a binary representation in
-- a Lua value
function m.Unpack(fmt, s, pos)
- return sunpack(fmt, s.str, pos + 1)
+ return string_unpack(fmt, s.str, pos + 1)
end
-- Return the binary array module
diff --git a/lua/flatbuffers/builder.lua b/lua/flatbuffers/builder.lua
index 4a0c4f6..25e0032 100644
--- a/lua/flatbuffers/builder.lua
+++ b/lua/flatbuffers/builder.lua
@@ -1,6 +1,7 @@
local N = require("flatbuffers.numTypes")
local ba = require("flatbuffers.binaryarray")
local compat = require("flatbuffers.compat")
+local string_unpack = compat.string_unpack
local m = {}
@@ -34,7 +35,7 @@
end
for i, elem in ipairs(a) do
- local x = string.unpack(VOffsetT.packFmt, b, 1 + (i - 1) * 2)
+ local x = string_unpack(VOffsetT.packFmt, b, 1 + (i - 1) * 2)
if x ~= 0 or elem ~= 0 then
local y = objectStart - elem
if x ~= y then
@@ -69,7 +70,7 @@
self.minalign = 1
self.currentVTable = nil
self.objectEnd = nil
- self.head = #self.bytes -- place the head at the end of the binary array
+ self.head = self.bytes.size -- place the head at the end of the binary array
-- clear vtables instead of making a new table
local vtable = self.vtables
@@ -117,9 +118,9 @@
while i >= 1 do
local vt2Offset = self.vtables[i]
- local vt2Start = #self.bytes - vt2Offset
+ local vt2Start = self.bytes.size - vt2Offset
local vt2lenstr = self.bytes:Slice(vt2Start, vt2Start+1)
- local vt2Len = string.unpack(VOffsetT.packFmt, vt2lenstr, 1)
+ local vt2Len = string_unpack(VOffsetT.packFmt, vt2lenstr, 1)
local metadata = VtableMetadataFields * 2
local vt2End = vt2Start + vt2Len
@@ -153,12 +154,12 @@
vBytes = vBytes * 2
self:PrependVOffsetT(vBytes)
- local objectStart = #self.bytes - objectOffset
+ local objectStart = self.bytes.size - objectOffset
self.bytes:Set(SOffsetT:Pack(self:Offset() - objectOffset),objectStart)
table.insert(self.vtables, self:Offset())
else
- local objectStart = #self.bytes - objectOffset
+ local objectStart = self.bytes.size - objectOffset
self.head = objectStart
self.bytes:Set(SOffsetT:Pack(exisitingVTable - objectOffset),self.head)
end
@@ -174,7 +175,7 @@
end
local function growByteBuffer(self, desiredSize)
- local s = #self.bytes
+ local s = self.bytes.size
assert(s < MAX_BUFFER_SIZE, "Flat Buffers cannot grow buffer beyond 2 gigabytes")
local newsize = s
repeat
@@ -190,7 +191,7 @@
end
function mt:Offset()
- return #self.bytes - self.head
+ return self.bytes.size - self.head
end
function mt:Pad(n)
@@ -209,15 +210,15 @@
local h = self.head
- local k = #self.bytes - h + additionalBytes
- local alignsize = ((~k) + 1) & (size - 1) -- getAlignSize(k, size)
+ local k = self.bytes.size - h + additionalBytes
+ local alignsize = getAlignSize(k, size)
local desiredSize = alignsize + size + additionalBytes
while self.head < desiredSize do
- local oldBufSize = #self.bytes
+ local oldBufSize = self.bytes.size
growByteBuffer(self, desiredSize)
- local updatedHead = self.head + #self.bytes - oldBufSize
+ local updatedHead = self.head + self.bytes.size - oldBufSize
self.head = updatedHead
end
@@ -300,7 +301,7 @@
self:Prep(self.minalign, sizePrefix and 8 or 4)
self:PrependUOffsetTRelative(rootTable)
if sizePrefix then
- local size = #self.bytes - self.head
+ local size = self.bytes.size - self.head
Int32:EnforceNumber(size)
self:PrependInt32(size)
end
diff --git a/lua/flatbuffers/compat.lua b/lua/flatbuffers/compat.lua
index 89c992b..1296c33 100644
--- a/lua/flatbuffers/compat.lua
+++ b/lua/flatbuffers/compat.lua
@@ -1,17 +1,15 @@
-local m = {}
-
-local getAlignSize
-if _VERSION == "Lua 5.3" then
- getAlignSize = function(k, size)
- return ((~k) + 1) & (size - 1)
- end
-else
- getAlignSize = function(self, size, additionalBytes)
- local alignsize = bit32.bnot(#self.bytes-self:Head() + additionalBytes) + 1
- return bit32.band(alignsize,(size - 1))
- end
-end
-
-m.GetAlignSize = getAlignSize
-
-return m
\ No newline at end of file
+local compats = {
+ ["Lua 5.1"] = function()
+ -- Check if Lua JIT is installed first
+ local ok = pcall(require, "jit")
+ if not ok then
+ return require("flatbuffers.compat_5_1")
+ else
+ return require("flatbuffers.compat_luajit")
+ end
+ end,
+ ["Lua 5.2"] = function() return require("flatbuffers.compat_5_1") end,
+ ["Lua 5.3"] = function() return require("flatbuffers.compat_5_3") end,
+ ["Lua 5.4"] = function() return require("flatbuffers.compat_5_3") end,
+}
+return assert(compats[_VERSION], "Unsupported Lua Version: ".._VERSION)()
\ No newline at end of file
diff --git a/lua/flatbuffers/compat_5_1.lua b/lua/flatbuffers/compat_5_1.lua
new file mode 100644
index 0000000..8c5e432
--- /dev/null
+++ b/lua/flatbuffers/compat_5_1.lua
@@ -0,0 +1,21 @@
+local m = {}
+local ok, bit = pcall(require, "bit32")
+assert(ok, "The Bit32 library must be installed")
+assert(pcall(require, "compat53"), "The Compat 5.3 library must be installed")
+
+m.GetAlignSize = function(k, size)
+ return bit.band(bit.bnot(k) + 1,(size - 1))
+end
+
+if not table.unpack then
+ table.unpack = unpack
+end
+
+if not table.pack then
+ table.pack = pack
+end
+
+m.string_pack = string.pack
+m.string_unpack = string.unpack
+
+return m
diff --git a/lua/flatbuffers/compat_5_3.lua b/lua/flatbuffers/compat_5_3.lua
new file mode 100644
index 0000000..762bf07
--- /dev/null
+++ b/lua/flatbuffers/compat_5_3.lua
@@ -0,0 +1,14 @@
+-- We need to put it into a separate file to avoid syntax error like `unexpected symbol near '~'`
+local m = {}
+
+
+m.GetAlignSize = function(k, size)
+ return ((~k) + 1) & (size - 1)
+end
+
+
+m.string_pack = string.pack
+m.string_unpack = string.unpack
+
+
+return m
diff --git a/lua/flatbuffers/compat_luajit.lua b/lua/flatbuffers/compat_luajit.lua
new file mode 100644
index 0000000..1ad9bd1
--- /dev/null
+++ b/lua/flatbuffers/compat_luajit.lua
@@ -0,0 +1,213 @@
+local bit = require("bit")
+local ffi = require("ffi")
+local band = bit.band
+local bnot = bit.bnot
+
+
+local m = {}
+local Uint8Bound = 256 -- bound is the max uintN + 1
+local Uint16Bound = 65536
+local Uint32Bound = 4294967296
+
+if not table.unpack then
+ table.unpack = unpack
+end
+
+if not table.pack then
+ table.pack = pack
+end
+
+m.GetAlignSize = function(k, size)
+ return band((bnot(k) + 1), (size - 1))
+end
+
+
+local function pack_I1(n)
+ return string.char(n)
+end
+local function pack_i1(n)
+ if n < 0 then
+ n = Uint8Bound + n
+ end
+ return pack_I1(n)
+end
+
+local function unpack_I1(n, pos)
+ return string.byte(n, pos)
+end
+local function unpack_i1(n, pos)
+ local res = unpack_I1(n, pos)
+ if res >= Uint8Bound / 2 then
+ return res - Uint8Bound
+ end
+ return res
+end
+
+local b2 = ffi.new("unsigned char[2]")
+local function pack_I2(n)
+ for i = 0, 1 do
+ b2[i] = bit.band(n, 255)
+ n = bit.rshift(n, 8)
+ end
+ return ffi.string(b2, 2)
+end
+local function pack_i2(n)
+ if n < 0 then
+ n = Uint16Bound + n
+ end
+ return pack_I2(n)
+end
+
+local function unpack_I2(n, pos)
+ local a, b = string.byte(n, pos, pos + 1)
+ return b * Uint8Bound + a
+end
+local function unpack_i2(n, pos)
+ local res = unpack_I2(n, pos)
+ if res >= Uint16Bound / 2 then
+ return res - Uint16Bound
+ end
+ return res
+end
+
+local b4 = ffi.new("unsigned char[4]")
+local function pack_I4(n)
+ for i = 0, 3 do
+ b4[i] = bit.band(n, 255)
+ n = bit.rshift(n, 8)
+ end
+ return ffi.string(b4, 4)
+end
+local function pack_i4(n)
+ if n < 0 then
+ n = Uint32Bound + n
+ end
+ return pack_I4(n)
+end
+
+local function unpack_I4(n, pos)
+ local a, b, c, d = string.byte(n, pos, pos + 3)
+ return Uint8Bound * (Uint8Bound * ((Uint8Bound * d) + c) + b) + a
+end
+local function unpack_i4(n, pos)
+ local res = unpack_I4(n, pos)
+ if res >= Uint32Bound / 2 then
+ return res - Uint32Bound
+ end
+ return res
+end
+
+local b8 = ffi.new("unsigned char[8]")
+local function pack_I8(n)
+ n = ffi.cast("unsigned long long", n)
+ local hi = math.floor(tonumber(n / Uint32Bound))
+ local li = n % Uint32Bound
+ for i = 0, 3 do
+ b8[i] = bit.band(li, 255)
+ li = bit.rshift(li, 8)
+ end
+ for i = 4, 7 do
+ b8[i] = bit.band(hi, 255)
+ hi = bit.rshift(hi, 8)
+ end
+ return ffi.string(b8, 8)
+end
+local function pack_i8(n)
+ n = ffi.cast("signed long long", n)
+ return pack_I8(n)
+end
+
+local function unpack_I8(n, pos)
+ local a, b, c, d = string.byte(n, pos, pos + 3)
+ local li = Uint8Bound * (Uint8Bound * ((Uint8Bound * d) + c) + b) + a
+ local a, b, c, d = string.byte(n, pos + 4, pos + 7)
+ local hi = Uint8Bound * (Uint8Bound * ((Uint8Bound * d) + c) + b) + a
+ return ffi.cast("unsigned long long", hi) * Uint32Bound + li
+end
+local function unpack_i8(n, pos)
+ local res = unpack_I8(n, pos)
+ return ffi.cast("signed long long", res)
+end
+
+local bf = ffi.new("float[1]")
+local function pack_f(n)
+ bf[0] = n
+ return ffi.string(bf, 4)
+end
+
+local function unpack_f(n, pos)
+ ffi.copy(bf, ffi.cast("char *", n) + pos - 1, 4)
+ return tonumber(bf[0])
+end
+
+local bd = ffi.new("double[1]")
+local function pack_d(n)
+ bd[0] = n
+ return ffi.string(bd, 8)
+end
+
+local function unpack_d(n, pos)
+ ffi.copy(bd, ffi.cast("char *", n) + pos - 1, 8)
+ return tonumber(bd[0])
+end
+
+
+m.string_pack = function(fmt, i, ...)
+ if fmt == "<I1" then
+ return pack_I1(i)
+ elseif fmt == "<I2" then
+ return pack_I2(i)
+ elseif fmt == "<I4" then
+ return pack_I4(i)
+ elseif fmt == "<I8" then
+ return pack_I8(i)
+ elseif fmt == "<i1" then
+ return pack_i1(i)
+ elseif fmt == "<i2" then
+ return pack_i2(i)
+ elseif fmt == "<i4" then
+ return pack_i4(i)
+ elseif fmt == "<i8" then
+ return pack_i8(i)
+ elseif fmt == "<f" then
+ return pack_f(i)
+ elseif fmt == "<d" then
+ return pack_d(i)
+ else
+ error(string.format("FIXME: support fmt %s", fmt))
+ end
+end
+
+
+m.string_unpack = function(fmt, s, pos)
+ if not pos then
+ pos = 1
+ end
+
+ if fmt == "<I1" then
+ return unpack_I1(s, pos)
+ elseif fmt == "<I2" then
+ return unpack_I2(s, pos)
+ elseif fmt == "<I4" then
+ return unpack_I4(s, pos)
+ elseif fmt == "<I8" then
+ return unpack_I8(s, pos)
+ elseif fmt == "<i1" then
+ return unpack_i1(s, pos)
+ elseif fmt == "<i2" then
+ return unpack_i2(s, pos)
+ elseif fmt == "<i4" then
+ return unpack_i4(s, pos)
+ elseif fmt == "<i8" then
+ return unpack_i8(s, pos)
+ elseif fmt == "<f" then
+ return unpack_f(s, pos)
+ elseif fmt == "<d" then
+ return unpack_d(s, pos)
+ else
+ error(string.format("FIXME: support fmt %s", fmt))
+ end
+end
+
+
+return m
diff --git a/lua/flatbuffers/numTypes.lua b/lua/flatbuffers/numTypes.lua
index 01f4199..289fa59 100644
--- a/lua/flatbuffers/numTypes.lua
+++ b/lua/flatbuffers/numTypes.lua
@@ -73,7 +73,7 @@
ValidNumber = function(self, n) return true end, -- anything is a valid boolean in Lua
EnforceNumber = function(self, n) end, -- anything is a valid boolean in Lua
EnforceNumbers = function(self, a, b) end, -- anything is a valid boolean in Lua
- EnforceNumberAndPack = function(self, n) return self:Pack(value) end,
+ EnforceNumberAndPack = function(self, n) return self:Pack(n) end,
}
local uint8_mt =
diff --git a/lua/flatbuffers/view.lua b/lua/flatbuffers/view.lua
index fde15c3..433f25c 100644
--- a/lua/flatbuffers/view.lua
+++ b/lua/flatbuffers/view.lua
@@ -1,3 +1,7 @@
+local compat = require("flatbuffers.compat")
+local string_unpack = compat.string_unpack
+
+
local m = {}
local mt = {}
@@ -12,13 +16,12 @@
end
end
-local unpack = string.unpack
local function unPackUoffset(bytes, off)
- return unpack("<I4", bytes.str, off + 1)
+ return string_unpack("<I4", bytes.str, off + 1)
end
local function unPackVoffset(bytes, off)
- return unpack("<I2", bytes.str, off + 1)
+ return string_unpack("<I2", bytes.str, off + 1)
end
function m.New(buf, pos)
@@ -73,6 +76,17 @@
return off + self:Get(N.UOffsetT, off) + 4
end
+function mt:VectorAsString(off, start, stop)
+ local o = self:Offset(off)
+ if o ~= 0 then
+ start = start or 1
+ stop = stop or self:VectorLen(o)
+ local a = self:Vector(o) + start - 1
+ return self.bytes:Slice(a, a + stop - start + 1)
+ end
+ return nil
+end
+
function mt:Union(t2, off)
assert(getmetatable(t2) == mt_name)
enforceOffset(off)
diff --git a/net/FlatBuffers/FlatBufferConstants.cs b/net/FlatBuffers/FlatBufferConstants.cs
index 1d4c5dc..473f79a 100644
--- a/net/FlatBuffers/FlatBufferConstants.cs
+++ b/net/FlatBuffers/FlatBufferConstants.cs
@@ -32,6 +32,6 @@
Changes to the C# implementation need to be sure to change
the version here and in the code generator on every possible
incompatible change */
- public static void FLATBUFFERS_1_12_0() {}
+ public static void FLATBUFFERS_2_0_0() {}
}
}
diff --git a/net/FlatBuffers/FlatBuffers.csproj b/net/FlatBuffers/FlatBuffers.csproj
index 54cba5a..a2b8bfb 100644
--- a/net/FlatBuffers/FlatBuffers.csproj
+++ b/net/FlatBuffers/FlatBuffers.csproj
@@ -1,4 +1,4 @@
-<Project Sdk="Microsoft.NET.Sdk">
+<Project Sdk="Microsoft.NET.Sdk" ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<TargetFrameworks>netstandard2.1;netstandard2.0;net46</TargetFrameworks>
diff --git a/package.json b/package.json
index 0ff0bd8..41bc51b 100644
--- a/package.json
+++ b/package.json
@@ -1,26 +1,24 @@
{
"name": "flatbuffers",
- "version": "1.12.0",
+ "version": "2.0.6",
"description": "Memory Efficient Serialization Library",
"files": [
- "js/*.js",
- "js/*.d.ts",
- "mjs/*.js",
- "mjs/*.d.ts",
- "ts/*.ts"
+ "js/**/*.js",
+ "js/**/*.d.ts",
+ "mjs/**/*.js",
+ "mjs/**/*.d.ts",
+ "ts/**/*.ts"
],
- "main": "js/flatbuffers.js",
- "module": "mjs/index.mjs",
+ "main": "js/index.js",
+ "module": "mjs/index.js",
"directories": {
"doc": "docs",
"test": "tests"
},
"scripts": {
- "test": "cd tests && ./JavaScriptTest.sh",
- "compile-ts": "tsc && tsc -p tsconfig.mjs.json",
- "pretest": "npm run compile-ts",
- "append-esm-export": "sed \"s/this.flatbuffers = flatbuffers;/export { flatbuffers };/\" js/flatbuffers.js > js/flatbuffers.mjs",
- "prepublishOnly": "npm run compile-ts && npm run append-esm-export"
+ "test": "npm run compile && cd tests && ./TypeScriptTest.sh",
+ "compile": "tsc && tsc -p tsconfig.mjs.json",
+ "prepublishOnly": "npm install --only=dev && npm run compile"
},
"repository": {
"type": "git",
@@ -37,9 +35,11 @@
"homepage": "https://google.github.io/flatbuffers/",
"dependencies": {},
"devDependencies": {
- "@typescript-eslint/eslint-plugin": "^4.1.0",
- "@typescript-eslint/parser": "^4.1.0",
- "eslint": "^7.8.1",
- "typescript": "^4.0.2"
+ "@bazel/typescript": "^5.2.0",
+ "@types/node": "17.0.21",
+ "@typescript-eslint/eslint-plugin": "^4.12.0",
+ "@typescript-eslint/parser": "^4.12.0",
+ "eslint": "^7.17.0",
+ "typescript": "^4.5.5"
}
}
diff --git a/pom.xml b/pom.xml
index b915338..aa318d0 100644
--- a/pom.xml
+++ b/pom.xml
@@ -3,7 +3,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.google.flatbuffers</groupId>
<artifactId>flatbuffers-java</artifactId>
- <version>1.12.0</version>
+ <version>2.0.3</version>
<packaging>bundle</packaging>
<name>FlatBuffers Java API</name>
<description>
@@ -42,103 +42,112 @@
</distributionManagement>
<build>
<sourceDirectory>java</sourceDirectory>
- <plugins>
- <plugin>
- <artifactId>maven-compiler-plugin</artifactId>
- <configuration>
- <source>1.8</source>
- <target>1.8</target>
- </configuration>
- <version>3.2</version>
- </plugin>
- <plugin>
- <artifactId>maven-surefire-plugin</artifactId>
- <configuration>
- <includes>
- <include>**/*Test.java</include>
- </includes>
- </configuration>
- <version>2.18.1</version>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-source-plugin</artifactId>
- <version>2.3</version>
- <executions>
- <execution>
- <id>attach-sources</id>
- <goals>
- <goal>jar</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-javadoc-plugin</artifactId>
- <version>2.9.1</version>
- <configuration>
- <additionalparam>-Xdoclint:none</additionalparam>
- <additionalOptions>-Xdoclint:none</additionalOptions>
- </configuration>
- <executions>
- <execution>
- <id>attach-javadocs</id>
- <goals>
- <goal>jar</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- <version>3.0.1</version>
- <extensions>true</extensions>
- </plugin>
- <plugin>
- <groupId>org.sonatype.plugins</groupId>
- <artifactId>nexus-staging-maven-plugin</artifactId>
- <version>1.6.7</version>
- <extensions>true</extensions>
- <configuration>
- <serverId>ossrh</serverId>
- <nexusUrl>https://oss.sonatype.org/</nexusUrl>
- <autoReleaseAfterClose>true</autoReleaseAfterClose>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-gpg-plugin</artifactId>
- <version>1.6</version>
- <executions>
- <execution>
- <id>sign-artifacts</id>
- <phase>verify</phase>
- <goals>
- <goal>sign</goal>
- </goals>
- <configuration>
- <gpgArguments>
- <arg>--pinentry-mode</arg>
- <arg>loopback</arg>
- </gpgArguments>
- </configuration>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-release-plugin</artifactId>
- <version>2.5.3</version>
- <configuration>
- <autoVersionSubmodules>true</autoVersionSubmodules>
- <useReleaseProfile>false</useReleaseProfile>
- <releaseProfiles>release</releaseProfiles>
- <goals>deploy</goals>
- </configuration>
- </plugin>
- </plugins>
</build>
+ <profiles>
+ <profile>
+ <id>jdk9</id>
+ <activation>
+ <jdk>[1.9,)</jdk>
+ </activation>
+ <build>
+ <plugins>
+ <plugin>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <configuration>
+ <release>8</release>
+ </configuration>
+ <version>3.8.1</version>
+ </plugin>
+ <plugin>
+ <artifactId>maven-surefire-plugin</artifactId>
+ <configuration>
+ <includes>
+ <include>**/*Test.java</include>
+ </includes>
+ </configuration>
+ <version>2.22.2</version>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-source-plugin</artifactId>
+ <version>3.2.1</version>
+ <executions>
+ <execution>
+ <id>attach-sources</id>
+ <goals>
+ <goal>jar</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-javadoc-plugin</artifactId>
+ <version>3.3.0</version>
+ <configuration>
+ <additionalparam>-Xdoclint:none</additionalparam>
+ <additionalOptions>-Xdoclint:none</additionalOptions>
+ </configuration>
+ <executions>
+ <execution>
+ <id>attach-javadocs</id>
+ <goals>
+ <goal>jar</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>maven-bundle-plugin</artifactId>
+ <version>5.1.2</version>
+ <extensions>true</extensions>
+ </plugin>
+ <plugin>
+ <groupId>org.sonatype.plugins</groupId>
+ <artifactId>nexus-staging-maven-plugin</artifactId>
+ <version>1.6.8</version>
+ <extensions>true</extensions>
+ <configuration>
+ <serverId>ossrh</serverId>
+ <nexusUrl>https://oss.sonatype.org/</nexusUrl>
+ <autoReleaseAfterClose>true</autoReleaseAfterClose>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-gpg-plugin</artifactId>
+ <version>3.0.1</version>
+ <executions>
+ <execution>
+ <id>sign-artifacts</id>
+ <phase>verify</phase>
+ <goals>
+ <goal>sign</goal>
+ </goals>
+ <configuration>
+ <gpgArguments>
+ <arg>--pinentry-mode</arg>
+ <arg>loopback</arg>
+ </gpgArguments>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-release-plugin</artifactId>
+ <version>2.5.3</version>
+ <configuration>
+ <autoVersionSubmodules>true</autoVersionSubmodules>
+ <useReleaseProfile>false</useReleaseProfile>
+ <releaseProfiles>release</releaseProfiles>
+ <goals>deploy</goals>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+ </profile>
+ </profiles>
</project>
diff --git a/python/flatbuffers/builder.py b/python/flatbuffers/builder.py
index f9448b0..3f0cf4e 100644
--- a/python/flatbuffers/builder.py
+++ b/python/flatbuffers/builder.py
@@ -103,7 +103,7 @@
## @cond FLATBUFFERS_INTENRAL
__slots__ = ("Bytes", "current_vtable", "head", "minalign", "objectEnd",
- "vtables", "nested", "forceDefaults", "finished")
+ "vtables", "nested", "forceDefaults", "finished", "vectorNumElems")
"""Maximum buffer size constant, in bytes.
@@ -113,7 +113,7 @@
MAX_BUFFER_SIZE = 2**31
## @endcond
- def __init__(self, initialSize):
+ def __init__(self, initialSize=1024):
"""Initializes a Builder of size `initial_size`.
The internal buffer is grown as needed.
@@ -371,12 +371,13 @@
self.assertNotNested()
self.nested = True
+ self.vectorNumElems = numElems
self.Prep(N.Uint32Flags.bytewidth, elemSize*numElems)
self.Prep(alignment, elemSize*numElems) # In case alignment > int.
return self.Offset()
## @endcond
- def EndVector(self, vectorNumElems):
+ def EndVector(self):
"""EndVector writes data necessary to finish vector construction."""
self.assertNested()
@@ -384,7 +385,8 @@
self.nested = False
## @endcond
# we already made space for this, so write without PrependUint32
- self.PlaceUOffsetT(vectorNumElems)
+ self.PlaceUOffsetT(self.vectorNumElems)
+ self.vectorNumElems = None
return self.Offset()
def CreateString(self, s, encoding='utf-8', errors='strict'):
@@ -411,7 +413,8 @@
## @endcond
self.Bytes[self.Head():self.Head()+l] = x
- return self.EndVector(len(x))
+ self.vectorNumElems = len(x)
+ return self.EndVector()
def CreateByteVector(self, x):
"""CreateString writes a byte vector."""
@@ -432,7 +435,8 @@
## @endcond
self.Bytes[self.Head():self.Head()+l] = x
- return self.EndVector(len(x))
+ self.vectorNumElems = len(x)
+ return self.EndVector()
def CreateNumpyVector(self, x):
"""CreateNumpyVector writes a numpy array into the buffer."""
@@ -467,7 +471,8 @@
# tobytes ensures c_contiguous ordering
self.Bytes[self.Head():self.Head()+l] = x_lend.tobytes(order='C')
- return self.EndVector(x.size)
+ self.vectorNumElems = x.size
+ return self.EndVector()
## @cond FLATBUFFERS_INTERNAL
def assertNested(self):
diff --git a/python/flatbuffers/compat.py b/python/flatbuffers/compat.py
index 2fc9cca..0244c97 100644
--- a/python/flatbuffers/compat.py
+++ b/python/flatbuffers/compat.py
@@ -16,7 +16,6 @@
compatibility helpers for numpy. """
import sys
-import imp
PY2 = sys.version_info[0] == 2
PY26 = sys.version_info[0:2] == (2, 6)
@@ -26,12 +25,14 @@
PY34 = sys.version_info[0:2] >= (3, 4)
if PY3:
+ import importlib.machinery
string_types = (str,)
binary_types = (bytes,bytearray)
range_func = range
memoryview_type = memoryview
struct_bool_decl = "?"
else:
+ import imp
string_types = (unicode,)
if PY26 or PY27:
binary_types = (str,bytearray)
@@ -52,11 +53,15 @@
Returns the numpy module if it exists on the system,
otherwise returns None.
"""
- try:
- imp.find_module('numpy')
- numpy_exists = True
- except ImportError:
- numpy_exists = False
+ if PY3:
+ numpy_exists = (
+ importlib.machinery.PathFinder.find_spec('numpy') is not None)
+ else:
+ try:
+ imp.find_module('numpy')
+ numpy_exists = True
+ except ImportError:
+ numpy_exists = False
if numpy_exists:
# We do this outside of try/except block in case numpy exists
diff --git a/python/flatbuffers/reflection/AdvancedFeatures.py b/python/flatbuffers/reflection/AdvancedFeatures.py
new file mode 100644
index 0000000..1c55258
--- /dev/null
+++ b/python/flatbuffers/reflection/AdvancedFeatures.py
@@ -0,0 +1,10 @@
+# automatically generated by the FlatBuffers compiler, do not modify
+
+# namespace: reflection
+
+# New schema language features that are not supported by old code generators.
+class AdvancedFeatures(object):
+ AdvancedArrayFeatures = 1
+ AdvancedUnionFeatures = 2
+ OptionalScalars = 4
+ DefaultVectorsAndStrings = 8
diff --git a/python/flatbuffers/reflection/BaseType.py b/python/flatbuffers/reflection/BaseType.py
new file mode 100644
index 0000000..2665b4a
--- /dev/null
+++ b/python/flatbuffers/reflection/BaseType.py
@@ -0,0 +1,24 @@
+# automatically generated by the FlatBuffers compiler, do not modify
+
+# namespace: reflection
+
+class BaseType(object):
+ None_ = 0
+ UType = 1
+ Bool = 2
+ Byte = 3
+ UByte = 4
+ Short = 5
+ UShort = 6
+ Int = 7
+ UInt = 8
+ Long = 9
+ ULong = 10
+ Float = 11
+ Double = 12
+ String = 13
+ Vector = 14
+ Obj = 15
+ Union = 16
+ Array = 17
+ MaxBaseType = 18
diff --git a/python/flatbuffers/reflection/Enum.py b/python/flatbuffers/reflection/Enum.py
new file mode 100644
index 0000000..b27e410
--- /dev/null
+++ b/python/flatbuffers/reflection/Enum.py
@@ -0,0 +1,169 @@
+# automatically generated by the FlatBuffers compiler, do not modify
+
+# namespace: reflection
+
+import flatbuffers
+from flatbuffers.compat import import_numpy
+np = import_numpy()
+
+class Enum(object):
+ __slots__ = ['_tab']
+
+ @classmethod
+ def GetRootAs(cls, buf, offset=0):
+ n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
+ x = Enum()
+ x.Init(buf, n + offset)
+ return x
+
+ @classmethod
+ def GetRootAsEnum(cls, buf, offset=0):
+ """This method is deprecated. Please switch to GetRootAs."""
+ return cls.GetRootAs(buf, offset)
+ @classmethod
+ def EnumBufferHasIdentifier(cls, buf, offset, size_prefixed=False):
+ return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x42\x46\x42\x53", size_prefixed=size_prefixed)
+
+ # Enum
+ def Init(self, buf, pos):
+ self._tab = flatbuffers.table.Table(buf, pos)
+
+ # Enum
+ def Name(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
+ if o != 0:
+ return self._tab.String(o + self._tab.Pos)
+ return None
+
+ # Enum
+ def Values(self, j):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6))
+ if o != 0:
+ x = self._tab.Vector(o)
+ x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4
+ x = self._tab.Indirect(x)
+ from reflection.EnumVal import EnumVal
+ obj = EnumVal()
+ obj.Init(self._tab.Bytes, x)
+ return obj
+ return None
+
+ # Enum
+ def ValuesLength(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6))
+ if o != 0:
+ return self._tab.VectorLen(o)
+ return 0
+
+ # Enum
+ def ValuesIsNone(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6))
+ return o == 0
+
+ # Enum
+ def IsUnion(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8))
+ if o != 0:
+ return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos))
+ return False
+
+ # Enum
+ def UnderlyingType(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10))
+ if o != 0:
+ x = self._tab.Indirect(o + self._tab.Pos)
+ from reflection.Type import Type
+ obj = Type()
+ obj.Init(self._tab.Bytes, x)
+ return obj
+ return None
+
+ # Enum
+ def Attributes(self, j):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12))
+ if o != 0:
+ x = self._tab.Vector(o)
+ x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4
+ x = self._tab.Indirect(x)
+ from reflection.KeyValue import KeyValue
+ obj = KeyValue()
+ obj.Init(self._tab.Bytes, x)
+ return obj
+ return None
+
+ # Enum
+ def AttributesLength(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12))
+ if o != 0:
+ return self._tab.VectorLen(o)
+ return 0
+
+ # Enum
+ def AttributesIsNone(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12))
+ return o == 0
+
+ # Enum
+ def Documentation(self, j):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14))
+ if o != 0:
+ a = self._tab.Vector(o)
+ return self._tab.String(a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4))
+ return ""
+
+ # Enum
+ def DocumentationLength(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14))
+ if o != 0:
+ return self._tab.VectorLen(o)
+ return 0
+
+ # Enum
+ def DocumentationIsNone(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14))
+ return o == 0
+
+ # File that this Enum is declared in.
+ # Enum
+ def DeclarationFile(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(16))
+ if o != 0:
+ return self._tab.String(o + self._tab.Pos)
+ return None
+
+def EnumStart(builder): builder.StartObject(7)
+def Start(builder):
+ return EnumStart(builder)
+def EnumAddName(builder, name): builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(name), 0)
+def AddName(builder, name):
+ return EnumAddName(builder, name)
+def EnumAddValues(builder, values): builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(values), 0)
+def AddValues(builder, values):
+ return EnumAddValues(builder, values)
+def EnumStartValuesVector(builder, numElems): return builder.StartVector(4, numElems, 4)
+def StartValuesVector(builder, numElems):
+ return EnumStartValuesVector(builder, numElems)
+def EnumAddIsUnion(builder, isUnion): builder.PrependBoolSlot(2, isUnion, 0)
+def AddIsUnion(builder, isUnion):
+ return EnumAddIsUnion(builder, isUnion)
+def EnumAddUnderlyingType(builder, underlyingType): builder.PrependUOffsetTRelativeSlot(3, flatbuffers.number_types.UOffsetTFlags.py_type(underlyingType), 0)
+def AddUnderlyingType(builder, underlyingType):
+ return EnumAddUnderlyingType(builder, underlyingType)
+def EnumAddAttributes(builder, attributes): builder.PrependUOffsetTRelativeSlot(4, flatbuffers.number_types.UOffsetTFlags.py_type(attributes), 0)
+def AddAttributes(builder, attributes):
+ return EnumAddAttributes(builder, attributes)
+def EnumStartAttributesVector(builder, numElems): return builder.StartVector(4, numElems, 4)
+def StartAttributesVector(builder, numElems):
+ return EnumStartAttributesVector(builder, numElems)
+def EnumAddDocumentation(builder, documentation): builder.PrependUOffsetTRelativeSlot(5, flatbuffers.number_types.UOffsetTFlags.py_type(documentation), 0)
+def AddDocumentation(builder, documentation):
+ return EnumAddDocumentation(builder, documentation)
+def EnumStartDocumentationVector(builder, numElems): return builder.StartVector(4, numElems, 4)
+def StartDocumentationVector(builder, numElems):
+ return EnumStartDocumentationVector(builder, numElems)
+def EnumAddDeclarationFile(builder, declarationFile): builder.PrependUOffsetTRelativeSlot(6, flatbuffers.number_types.UOffsetTFlags.py_type(declarationFile), 0)
+def AddDeclarationFile(builder, declarationFile):
+ return EnumAddDeclarationFile(builder, declarationFile)
+def EnumEnd(builder): return builder.EndObject()
+def End(builder):
+ return EnumEnd(builder)
\ No newline at end of file
diff --git a/python/flatbuffers/reflection/EnumVal.py b/python/flatbuffers/reflection/EnumVal.py
new file mode 100644
index 0000000..62a32dc
--- /dev/null
+++ b/python/flatbuffers/reflection/EnumVal.py
@@ -0,0 +1,96 @@
+# automatically generated by the FlatBuffers compiler, do not modify
+
+# namespace: reflection
+
+import flatbuffers
+from flatbuffers.compat import import_numpy
+np = import_numpy()
+
+class EnumVal(object):
+ __slots__ = ['_tab']
+
+ @classmethod
+ def GetRootAs(cls, buf, offset=0):
+ n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
+ x = EnumVal()
+ x.Init(buf, n + offset)
+ return x
+
+ @classmethod
+ def GetRootAsEnumVal(cls, buf, offset=0):
+ """This method is deprecated. Please switch to GetRootAs."""
+ return cls.GetRootAs(buf, offset)
+ @classmethod
+ def EnumValBufferHasIdentifier(cls, buf, offset, size_prefixed=False):
+ return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x42\x46\x42\x53", size_prefixed=size_prefixed)
+
+ # EnumVal
+ def Init(self, buf, pos):
+ self._tab = flatbuffers.table.Table(buf, pos)
+
+ # EnumVal
+ def Name(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
+ if o != 0:
+ return self._tab.String(o + self._tab.Pos)
+ return None
+
+ # EnumVal
+ def Value(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Int64Flags, o + self._tab.Pos)
+ return 0
+
+ # EnumVal
+ def UnionType(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10))
+ if o != 0:
+ x = self._tab.Indirect(o + self._tab.Pos)
+ from reflection.Type import Type
+ obj = Type()
+ obj.Init(self._tab.Bytes, x)
+ return obj
+ return None
+
+ # EnumVal
+ def Documentation(self, j):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12))
+ if o != 0:
+ a = self._tab.Vector(o)
+ return self._tab.String(a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4))
+ return ""
+
+ # EnumVal
+ def DocumentationLength(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12))
+ if o != 0:
+ return self._tab.VectorLen(o)
+ return 0
+
+ # EnumVal
+ def DocumentationIsNone(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12))
+ return o == 0
+
+def EnumValStart(builder): builder.StartObject(5)
+def Start(builder):
+ return EnumValStart(builder)
+def EnumValAddName(builder, name): builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(name), 0)
+def AddName(builder, name):
+ return EnumValAddName(builder, name)
+def EnumValAddValue(builder, value): builder.PrependInt64Slot(1, value, 0)
+def AddValue(builder, value):
+ return EnumValAddValue(builder, value)
+def EnumValAddUnionType(builder, unionType): builder.PrependUOffsetTRelativeSlot(3, flatbuffers.number_types.UOffsetTFlags.py_type(unionType), 0)
+def AddUnionType(builder, unionType):
+ return EnumValAddUnionType(builder, unionType)
+def EnumValAddDocumentation(builder, documentation): builder.PrependUOffsetTRelativeSlot(4, flatbuffers.number_types.UOffsetTFlags.py_type(documentation), 0)
+def AddDocumentation(builder, documentation):
+ return EnumValAddDocumentation(builder, documentation)
+def EnumValStartDocumentationVector(builder, numElems): return builder.StartVector(4, numElems, 4)
+def StartDocumentationVector(builder, numElems):
+ return EnumValStartDocumentationVector(builder, numElems)
+def EnumValEnd(builder): return builder.EndObject()
+def End(builder):
+ return EnumValEnd(builder)
\ No newline at end of file
diff --git a/python/flatbuffers/reflection/Field.py b/python/flatbuffers/reflection/Field.py
new file mode 100644
index 0000000..01b5280
--- /dev/null
+++ b/python/flatbuffers/reflection/Field.py
@@ -0,0 +1,208 @@
+# automatically generated by the FlatBuffers compiler, do not modify
+
+# namespace: reflection
+
+import flatbuffers
+from flatbuffers.compat import import_numpy
+np = import_numpy()
+
+class Field(object):
+ __slots__ = ['_tab']
+
+ @classmethod
+ def GetRootAs(cls, buf, offset=0):
+ n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
+ x = Field()
+ x.Init(buf, n + offset)
+ return x
+
+ @classmethod
+ def GetRootAsField(cls, buf, offset=0):
+ """This method is deprecated. Please switch to GetRootAs."""
+ return cls.GetRootAs(buf, offset)
+ @classmethod
+ def FieldBufferHasIdentifier(cls, buf, offset, size_prefixed=False):
+ return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x42\x46\x42\x53", size_prefixed=size_prefixed)
+
+ # Field
+ def Init(self, buf, pos):
+ self._tab = flatbuffers.table.Table(buf, pos)
+
+ # Field
+ def Name(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
+ if o != 0:
+ return self._tab.String(o + self._tab.Pos)
+ return None
+
+ # Field
+ def Type(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6))
+ if o != 0:
+ x = self._tab.Indirect(o + self._tab.Pos)
+ from reflection.Type import Type
+ obj = Type()
+ obj.Init(self._tab.Bytes, x)
+ return obj
+ return None
+
+ # Field
+ def Id(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Uint16Flags, o + self._tab.Pos)
+ return 0
+
+ # Field
+ def Offset(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Uint16Flags, o + self._tab.Pos)
+ return 0
+
+ # Field
+ def DefaultInteger(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Int64Flags, o + self._tab.Pos)
+ return 0
+
+ # Field
+ def DefaultReal(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Float64Flags, o + self._tab.Pos)
+ return 0.0
+
+ # Field
+ def Deprecated(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(16))
+ if o != 0:
+ return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos))
+ return False
+
+ # Field
+ def Required(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(18))
+ if o != 0:
+ return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos))
+ return False
+
+ # Field
+ def Key(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(20))
+ if o != 0:
+ return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos))
+ return False
+
+ # Field
+ def Attributes(self, j):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(22))
+ if o != 0:
+ x = self._tab.Vector(o)
+ x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4
+ x = self._tab.Indirect(x)
+ from reflection.KeyValue import KeyValue
+ obj = KeyValue()
+ obj.Init(self._tab.Bytes, x)
+ return obj
+ return None
+
+ # Field
+ def AttributesLength(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(22))
+ if o != 0:
+ return self._tab.VectorLen(o)
+ return 0
+
+ # Field
+ def AttributesIsNone(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(22))
+ return o == 0
+
+ # Field
+ def Documentation(self, j):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(24))
+ if o != 0:
+ a = self._tab.Vector(o)
+ return self._tab.String(a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4))
+ return ""
+
+ # Field
+ def DocumentationLength(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(24))
+ if o != 0:
+ return self._tab.VectorLen(o)
+ return 0
+
+ # Field
+ def DocumentationIsNone(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(24))
+ return o == 0
+
+ # Field
+ def Optional(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(26))
+ if o != 0:
+ return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos))
+ return False
+
+ # Number of padding octets to always add after this field. Structs only.
+ # Field
+ def Padding(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(28))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Uint16Flags, o + self._tab.Pos)
+ return 0
+
+def FieldStart(builder): builder.StartObject(13)
+def Start(builder):
+ return FieldStart(builder)
+def FieldAddName(builder, name): builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(name), 0)
+def AddName(builder, name):
+ return FieldAddName(builder, name)
+def FieldAddType(builder, type): builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(type), 0)
+def AddType(builder, type):
+ return FieldAddType(builder, type)
+def FieldAddId(builder, id): builder.PrependUint16Slot(2, id, 0)
+def AddId(builder, id):
+ return FieldAddId(builder, id)
+def FieldAddOffset(builder, offset): builder.PrependUint16Slot(3, offset, 0)
+def AddOffset(builder, offset):
+ return FieldAddOffset(builder, offset)
+def FieldAddDefaultInteger(builder, defaultInteger): builder.PrependInt64Slot(4, defaultInteger, 0)
+def AddDefaultInteger(builder, defaultInteger):
+ return FieldAddDefaultInteger(builder, defaultInteger)
+def FieldAddDefaultReal(builder, defaultReal): builder.PrependFloat64Slot(5, defaultReal, 0.0)
+def AddDefaultReal(builder, defaultReal):
+ return FieldAddDefaultReal(builder, defaultReal)
+def FieldAddDeprecated(builder, deprecated): builder.PrependBoolSlot(6, deprecated, 0)
+def AddDeprecated(builder, deprecated):
+ return FieldAddDeprecated(builder, deprecated)
+def FieldAddRequired(builder, required): builder.PrependBoolSlot(7, required, 0)
+def AddRequired(builder, required):
+ return FieldAddRequired(builder, required)
+def FieldAddKey(builder, key): builder.PrependBoolSlot(8, key, 0)
+def AddKey(builder, key):
+ return FieldAddKey(builder, key)
+def FieldAddAttributes(builder, attributes): builder.PrependUOffsetTRelativeSlot(9, flatbuffers.number_types.UOffsetTFlags.py_type(attributes), 0)
+def AddAttributes(builder, attributes):
+ return FieldAddAttributes(builder, attributes)
+def FieldStartAttributesVector(builder, numElems): return builder.StartVector(4, numElems, 4)
+def StartAttributesVector(builder, numElems):
+ return FieldStartAttributesVector(builder, numElems)
+def FieldAddDocumentation(builder, documentation): builder.PrependUOffsetTRelativeSlot(10, flatbuffers.number_types.UOffsetTFlags.py_type(documentation), 0)
+def AddDocumentation(builder, documentation):
+ return FieldAddDocumentation(builder, documentation)
+def FieldStartDocumentationVector(builder, numElems): return builder.StartVector(4, numElems, 4)
+def StartDocumentationVector(builder, numElems):
+ return FieldStartDocumentationVector(builder, numElems)
+def FieldAddOptional(builder, optional): builder.PrependBoolSlot(11, optional, 0)
+def AddOptional(builder, optional):
+ return FieldAddOptional(builder, optional)
+def FieldAddPadding(builder, padding): builder.PrependUint16Slot(12, padding, 0)
+def AddPadding(builder, padding):
+ return FieldAddPadding(builder, padding)
+def FieldEnd(builder): return builder.EndObject()
+def End(builder):
+ return FieldEnd(builder)
\ No newline at end of file
diff --git a/python/flatbuffers/reflection/KeyValue.py b/python/flatbuffers/reflection/KeyValue.py
new file mode 100644
index 0000000..dde37df
--- /dev/null
+++ b/python/flatbuffers/reflection/KeyValue.py
@@ -0,0 +1,56 @@
+# automatically generated by the FlatBuffers compiler, do not modify
+
+# namespace: reflection
+
+import flatbuffers
+from flatbuffers.compat import import_numpy
+np = import_numpy()
+
+class KeyValue(object):
+ __slots__ = ['_tab']
+
+ @classmethod
+ def GetRootAs(cls, buf, offset=0):
+ n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
+ x = KeyValue()
+ x.Init(buf, n + offset)
+ return x
+
+ @classmethod
+ def GetRootAsKeyValue(cls, buf, offset=0):
+ """This method is deprecated. Please switch to GetRootAs."""
+ return cls.GetRootAs(buf, offset)
+ @classmethod
+ def KeyValueBufferHasIdentifier(cls, buf, offset, size_prefixed=False):
+ return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x42\x46\x42\x53", size_prefixed=size_prefixed)
+
+ # KeyValue
+ def Init(self, buf, pos):
+ self._tab = flatbuffers.table.Table(buf, pos)
+
+ # KeyValue
+ def Key(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
+ if o != 0:
+ return self._tab.String(o + self._tab.Pos)
+ return None
+
+ # KeyValue
+ def Value(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6))
+ if o != 0:
+ return self._tab.String(o + self._tab.Pos)
+ return None
+
+def KeyValueStart(builder): builder.StartObject(2)
+def Start(builder):
+ return KeyValueStart(builder)
+def KeyValueAddKey(builder, key): builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(key), 0)
+def AddKey(builder, key):
+ return KeyValueAddKey(builder, key)
+def KeyValueAddValue(builder, value): builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(value), 0)
+def AddValue(builder, value):
+ return KeyValueAddValue(builder, value)
+def KeyValueEnd(builder): return builder.EndObject()
+def End(builder):
+ return KeyValueEnd(builder)
\ No newline at end of file
diff --git a/python/flatbuffers/reflection/Object.py b/python/flatbuffers/reflection/Object.py
new file mode 100644
index 0000000..598927c
--- /dev/null
+++ b/python/flatbuffers/reflection/Object.py
@@ -0,0 +1,175 @@
+# automatically generated by the FlatBuffers compiler, do not modify
+
+# namespace: reflection
+
+import flatbuffers
+from flatbuffers.compat import import_numpy
+np = import_numpy()
+
+class Object(object):
+ __slots__ = ['_tab']
+
+ @classmethod
+ def GetRootAs(cls, buf, offset=0):
+ n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
+ x = Object()
+ x.Init(buf, n + offset)
+ return x
+
+ @classmethod
+ def GetRootAsObject(cls, buf, offset=0):
+ """This method is deprecated. Please switch to GetRootAs."""
+ return cls.GetRootAs(buf, offset)
+ @classmethod
+ def ObjectBufferHasIdentifier(cls, buf, offset, size_prefixed=False):
+ return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x42\x46\x42\x53", size_prefixed=size_prefixed)
+
+ # Object
+ def Init(self, buf, pos):
+ self._tab = flatbuffers.table.Table(buf, pos)
+
+ # Object
+ def Name(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
+ if o != 0:
+ return self._tab.String(o + self._tab.Pos)
+ return None
+
+ # Object
+ def Fields(self, j):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6))
+ if o != 0:
+ x = self._tab.Vector(o)
+ x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4
+ x = self._tab.Indirect(x)
+ from reflection.Field import Field
+ obj = Field()
+ obj.Init(self._tab.Bytes, x)
+ return obj
+ return None
+
+ # Object
+ def FieldsLength(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6))
+ if o != 0:
+ return self._tab.VectorLen(o)
+ return 0
+
+ # Object
+ def FieldsIsNone(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6))
+ return o == 0
+
+ # Object
+ def IsStruct(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8))
+ if o != 0:
+ return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos))
+ return False
+
+ # Object
+ def Minalign(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos)
+ return 0
+
+ # Object
+ def Bytesize(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos)
+ return 0
+
+ # Object
+ def Attributes(self, j):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14))
+ if o != 0:
+ x = self._tab.Vector(o)
+ x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4
+ x = self._tab.Indirect(x)
+ from reflection.KeyValue import KeyValue
+ obj = KeyValue()
+ obj.Init(self._tab.Bytes, x)
+ return obj
+ return None
+
+ # Object
+ def AttributesLength(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14))
+ if o != 0:
+ return self._tab.VectorLen(o)
+ return 0
+
+ # Object
+ def AttributesIsNone(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14))
+ return o == 0
+
+ # Object
+ def Documentation(self, j):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(16))
+ if o != 0:
+ a = self._tab.Vector(o)
+ return self._tab.String(a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4))
+ return ""
+
+ # Object
+ def DocumentationLength(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(16))
+ if o != 0:
+ return self._tab.VectorLen(o)
+ return 0
+
+ # Object
+ def DocumentationIsNone(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(16))
+ return o == 0
+
+ # File that this Object is declared in.
+ # Object
+ def DeclarationFile(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(18))
+ if o != 0:
+ return self._tab.String(o + self._tab.Pos)
+ return None
+
+def ObjectStart(builder): builder.StartObject(8)
+def Start(builder):
+ return ObjectStart(builder)
+def ObjectAddName(builder, name): builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(name), 0)
+def AddName(builder, name):
+ return ObjectAddName(builder, name)
+def ObjectAddFields(builder, fields): builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(fields), 0)
+def AddFields(builder, fields):
+ return ObjectAddFields(builder, fields)
+def ObjectStartFieldsVector(builder, numElems): return builder.StartVector(4, numElems, 4)
+def StartFieldsVector(builder, numElems):
+ return ObjectStartFieldsVector(builder, numElems)
+def ObjectAddIsStruct(builder, isStruct): builder.PrependBoolSlot(2, isStruct, 0)
+def AddIsStruct(builder, isStruct):
+ return ObjectAddIsStruct(builder, isStruct)
+def ObjectAddMinalign(builder, minalign): builder.PrependInt32Slot(3, minalign, 0)
+def AddMinalign(builder, minalign):
+ return ObjectAddMinalign(builder, minalign)
+def ObjectAddBytesize(builder, bytesize): builder.PrependInt32Slot(4, bytesize, 0)
+def AddBytesize(builder, bytesize):
+ return ObjectAddBytesize(builder, bytesize)
+def ObjectAddAttributes(builder, attributes): builder.PrependUOffsetTRelativeSlot(5, flatbuffers.number_types.UOffsetTFlags.py_type(attributes), 0)
+def AddAttributes(builder, attributes):
+ return ObjectAddAttributes(builder, attributes)
+def ObjectStartAttributesVector(builder, numElems): return builder.StartVector(4, numElems, 4)
+def StartAttributesVector(builder, numElems):
+ return ObjectStartAttributesVector(builder, numElems)
+def ObjectAddDocumentation(builder, documentation): builder.PrependUOffsetTRelativeSlot(6, flatbuffers.number_types.UOffsetTFlags.py_type(documentation), 0)
+def AddDocumentation(builder, documentation):
+ return ObjectAddDocumentation(builder, documentation)
+def ObjectStartDocumentationVector(builder, numElems): return builder.StartVector(4, numElems, 4)
+def StartDocumentationVector(builder, numElems):
+ return ObjectStartDocumentationVector(builder, numElems)
+def ObjectAddDeclarationFile(builder, declarationFile): builder.PrependUOffsetTRelativeSlot(7, flatbuffers.number_types.UOffsetTFlags.py_type(declarationFile), 0)
+def AddDeclarationFile(builder, declarationFile):
+ return ObjectAddDeclarationFile(builder, declarationFile)
+def ObjectEnd(builder): return builder.EndObject()
+def End(builder):
+ return ObjectEnd(builder)
\ No newline at end of file
diff --git a/python/flatbuffers/reflection/RPCCall.py b/python/flatbuffers/reflection/RPCCall.py
new file mode 100644
index 0000000..9fdbf46
--- /dev/null
+++ b/python/flatbuffers/reflection/RPCCall.py
@@ -0,0 +1,131 @@
+# automatically generated by the FlatBuffers compiler, do not modify
+
+# namespace: reflection
+
+import flatbuffers
+from flatbuffers.compat import import_numpy
+np = import_numpy()
+
+class RPCCall(object):
+ __slots__ = ['_tab']
+
+ @classmethod
+ def GetRootAs(cls, buf, offset=0):
+ n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
+ x = RPCCall()
+ x.Init(buf, n + offset)
+ return x
+
+ @classmethod
+ def GetRootAsRPCCall(cls, buf, offset=0):
+ """This method is deprecated. Please switch to GetRootAs."""
+ return cls.GetRootAs(buf, offset)
+ @classmethod
+ def RPCCallBufferHasIdentifier(cls, buf, offset, size_prefixed=False):
+ return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x42\x46\x42\x53", size_prefixed=size_prefixed)
+
+ # RPCCall
+ def Init(self, buf, pos):
+ self._tab = flatbuffers.table.Table(buf, pos)
+
+ # RPCCall
+ def Name(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
+ if o != 0:
+ return self._tab.String(o + self._tab.Pos)
+ return None
+
+ # RPCCall
+ def Request(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6))
+ if o != 0:
+ x = self._tab.Indirect(o + self._tab.Pos)
+ from reflection.Object import Object
+ obj = Object()
+ obj.Init(self._tab.Bytes, x)
+ return obj
+ return None
+
+ # RPCCall
+ def Response(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8))
+ if o != 0:
+ x = self._tab.Indirect(o + self._tab.Pos)
+ from reflection.Object import Object
+ obj = Object()
+ obj.Init(self._tab.Bytes, x)
+ return obj
+ return None
+
+ # RPCCall
+ def Attributes(self, j):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10))
+ if o != 0:
+ x = self._tab.Vector(o)
+ x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4
+ x = self._tab.Indirect(x)
+ from reflection.KeyValue import KeyValue
+ obj = KeyValue()
+ obj.Init(self._tab.Bytes, x)
+ return obj
+ return None
+
+ # RPCCall
+ def AttributesLength(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10))
+ if o != 0:
+ return self._tab.VectorLen(o)
+ return 0
+
+ # RPCCall
+ def AttributesIsNone(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10))
+ return o == 0
+
+ # RPCCall
+ def Documentation(self, j):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12))
+ if o != 0:
+ a = self._tab.Vector(o)
+ return self._tab.String(a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4))
+ return ""
+
+ # RPCCall
+ def DocumentationLength(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12))
+ if o != 0:
+ return self._tab.VectorLen(o)
+ return 0
+
+ # RPCCall
+ def DocumentationIsNone(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12))
+ return o == 0
+
+def RPCCallStart(builder): builder.StartObject(5)
+def Start(builder):
+ return RPCCallStart(builder)
+def RPCCallAddName(builder, name): builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(name), 0)
+def AddName(builder, name):
+ return RPCCallAddName(builder, name)
+def RPCCallAddRequest(builder, request): builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(request), 0)
+def AddRequest(builder, request):
+ return RPCCallAddRequest(builder, request)
+def RPCCallAddResponse(builder, response): builder.PrependUOffsetTRelativeSlot(2, flatbuffers.number_types.UOffsetTFlags.py_type(response), 0)
+def AddResponse(builder, response):
+ return RPCCallAddResponse(builder, response)
+def RPCCallAddAttributes(builder, attributes): builder.PrependUOffsetTRelativeSlot(3, flatbuffers.number_types.UOffsetTFlags.py_type(attributes), 0)
+def AddAttributes(builder, attributes):
+ return RPCCallAddAttributes(builder, attributes)
+def RPCCallStartAttributesVector(builder, numElems): return builder.StartVector(4, numElems, 4)
+def StartAttributesVector(builder, numElems):
+ return RPCCallStartAttributesVector(builder, numElems)
+def RPCCallAddDocumentation(builder, documentation): builder.PrependUOffsetTRelativeSlot(4, flatbuffers.number_types.UOffsetTFlags.py_type(documentation), 0)
+def AddDocumentation(builder, documentation):
+ return RPCCallAddDocumentation(builder, documentation)
+def RPCCallStartDocumentationVector(builder, numElems): return builder.StartVector(4, numElems, 4)
+def StartDocumentationVector(builder, numElems):
+ return RPCCallStartDocumentationVector(builder, numElems)
+def RPCCallEnd(builder): return builder.EndObject()
+def End(builder):
+ return RPCCallEnd(builder)
\ No newline at end of file
diff --git a/python/flatbuffers/reflection/Schema.py b/python/flatbuffers/reflection/Schema.py
new file mode 100644
index 0000000..df2f072
--- /dev/null
+++ b/python/flatbuffers/reflection/Schema.py
@@ -0,0 +1,206 @@
+# automatically generated by the FlatBuffers compiler, do not modify
+
+# namespace: reflection
+
+import flatbuffers
+from flatbuffers.compat import import_numpy
+np = import_numpy()
+
+class Schema(object):
+ __slots__ = ['_tab']
+
+ @classmethod
+ def GetRootAs(cls, buf, offset=0):
+ n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
+ x = Schema()
+ x.Init(buf, n + offset)
+ return x
+
+ @classmethod
+ def GetRootAsSchema(cls, buf, offset=0):
+ """This method is deprecated. Please switch to GetRootAs."""
+ return cls.GetRootAs(buf, offset)
+ @classmethod
+ def SchemaBufferHasIdentifier(cls, buf, offset, size_prefixed=False):
+ return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x42\x46\x42\x53", size_prefixed=size_prefixed)
+
+ # Schema
+ def Init(self, buf, pos):
+ self._tab = flatbuffers.table.Table(buf, pos)
+
+ # Schema
+ def Objects(self, j):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
+ if o != 0:
+ x = self._tab.Vector(o)
+ x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4
+ x = self._tab.Indirect(x)
+ from reflection.Object import Object
+ obj = Object()
+ obj.Init(self._tab.Bytes, x)
+ return obj
+ return None
+
+ # Schema
+ def ObjectsLength(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
+ if o != 0:
+ return self._tab.VectorLen(o)
+ return 0
+
+ # Schema
+ def ObjectsIsNone(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
+ return o == 0
+
+ # Schema
+ def Enums(self, j):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6))
+ if o != 0:
+ x = self._tab.Vector(o)
+ x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4
+ x = self._tab.Indirect(x)
+ from reflection.Enum import Enum
+ obj = Enum()
+ obj.Init(self._tab.Bytes, x)
+ return obj
+ return None
+
+ # Schema
+ def EnumsLength(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6))
+ if o != 0:
+ return self._tab.VectorLen(o)
+ return 0
+
+ # Schema
+ def EnumsIsNone(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6))
+ return o == 0
+
+ # Schema
+ def FileIdent(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8))
+ if o != 0:
+ return self._tab.String(o + self._tab.Pos)
+ return None
+
+ # Schema
+ def FileExt(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10))
+ if o != 0:
+ return self._tab.String(o + self._tab.Pos)
+ return None
+
+ # Schema
+ def RootTable(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12))
+ if o != 0:
+ x = self._tab.Indirect(o + self._tab.Pos)
+ from reflection.Object import Object
+ obj = Object()
+ obj.Init(self._tab.Bytes, x)
+ return obj
+ return None
+
+ # Schema
+ def Services(self, j):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14))
+ if o != 0:
+ x = self._tab.Vector(o)
+ x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4
+ x = self._tab.Indirect(x)
+ from reflection.Service import Service
+ obj = Service()
+ obj.Init(self._tab.Bytes, x)
+ return obj
+ return None
+
+ # Schema
+ def ServicesLength(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14))
+ if o != 0:
+ return self._tab.VectorLen(o)
+ return 0
+
+ # Schema
+ def ServicesIsNone(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14))
+ return o == 0
+
+ # Schema
+ def AdvancedFeatures(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(16))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Uint64Flags, o + self._tab.Pos)
+ return 0
+
+ # All the files used in this compilation. Files are relative to where
+ # flatc was invoked.
+ # Schema
+ def FbsFiles(self, j):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(18))
+ if o != 0:
+ x = self._tab.Vector(o)
+ x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4
+ x = self._tab.Indirect(x)
+ from reflection.SchemaFile import SchemaFile
+ obj = SchemaFile()
+ obj.Init(self._tab.Bytes, x)
+ return obj
+ return None
+
+ # Schema
+ def FbsFilesLength(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(18))
+ if o != 0:
+ return self._tab.VectorLen(o)
+ return 0
+
+ # Schema
+ def FbsFilesIsNone(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(18))
+ return o == 0
+
+def SchemaStart(builder): builder.StartObject(8)
+def Start(builder):
+ return SchemaStart(builder)
+def SchemaAddObjects(builder, objects): builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(objects), 0)
+def AddObjects(builder, objects):
+ return SchemaAddObjects(builder, objects)
+def SchemaStartObjectsVector(builder, numElems): return builder.StartVector(4, numElems, 4)
+def StartObjectsVector(builder, numElems):
+ return SchemaStartObjectsVector(builder, numElems)
+def SchemaAddEnums(builder, enums): builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(enums), 0)
+def AddEnums(builder, enums):
+ return SchemaAddEnums(builder, enums)
+def SchemaStartEnumsVector(builder, numElems): return builder.StartVector(4, numElems, 4)
+def StartEnumsVector(builder, numElems):
+ return SchemaStartEnumsVector(builder, numElems)
+def SchemaAddFileIdent(builder, fileIdent): builder.PrependUOffsetTRelativeSlot(2, flatbuffers.number_types.UOffsetTFlags.py_type(fileIdent), 0)
+def AddFileIdent(builder, fileIdent):
+ return SchemaAddFileIdent(builder, fileIdent)
+def SchemaAddFileExt(builder, fileExt): builder.PrependUOffsetTRelativeSlot(3, flatbuffers.number_types.UOffsetTFlags.py_type(fileExt), 0)
+def AddFileExt(builder, fileExt):
+ return SchemaAddFileExt(builder, fileExt)
+def SchemaAddRootTable(builder, rootTable): builder.PrependUOffsetTRelativeSlot(4, flatbuffers.number_types.UOffsetTFlags.py_type(rootTable), 0)
+def AddRootTable(builder, rootTable):
+ return SchemaAddRootTable(builder, rootTable)
+def SchemaAddServices(builder, services): builder.PrependUOffsetTRelativeSlot(5, flatbuffers.number_types.UOffsetTFlags.py_type(services), 0)
+def AddServices(builder, services):
+ return SchemaAddServices(builder, services)
+def SchemaStartServicesVector(builder, numElems): return builder.StartVector(4, numElems, 4)
+def StartServicesVector(builder, numElems):
+ return SchemaStartServicesVector(builder, numElems)
+def SchemaAddAdvancedFeatures(builder, advancedFeatures): builder.PrependUint64Slot(6, advancedFeatures, 0)
+def AddAdvancedFeatures(builder, advancedFeatures):
+ return SchemaAddAdvancedFeatures(builder, advancedFeatures)
+def SchemaAddFbsFiles(builder, fbsFiles): builder.PrependUOffsetTRelativeSlot(7, flatbuffers.number_types.UOffsetTFlags.py_type(fbsFiles), 0)
+def AddFbsFiles(builder, fbsFiles):
+ return SchemaAddFbsFiles(builder, fbsFiles)
+def SchemaStartFbsFilesVector(builder, numElems): return builder.StartVector(4, numElems, 4)
+def StartFbsFilesVector(builder, numElems):
+ return SchemaStartFbsFilesVector(builder, numElems)
+def SchemaEnd(builder): return builder.EndObject()
+def End(builder):
+ return SchemaEnd(builder)
\ No newline at end of file
diff --git a/python/flatbuffers/reflection/SchemaFile.py b/python/flatbuffers/reflection/SchemaFile.py
new file mode 100644
index 0000000..890fd3b
--- /dev/null
+++ b/python/flatbuffers/reflection/SchemaFile.py
@@ -0,0 +1,77 @@
+# automatically generated by the FlatBuffers compiler, do not modify
+
+# namespace: reflection
+
+import flatbuffers
+from flatbuffers.compat import import_numpy
+np = import_numpy()
+
+# File specific information.
+# Symbols declared within a file may be recovered by iterating over all
+# symbols and examining the `declaration_file` field.
+class SchemaFile(object):
+ __slots__ = ['_tab']
+
+ @classmethod
+ def GetRootAs(cls, buf, offset=0):
+ n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
+ x = SchemaFile()
+ x.Init(buf, n + offset)
+ return x
+
+ @classmethod
+ def GetRootAsSchemaFile(cls, buf, offset=0):
+ """This method is deprecated. Please switch to GetRootAs."""
+ return cls.GetRootAs(buf, offset)
+ @classmethod
+ def SchemaFileBufferHasIdentifier(cls, buf, offset, size_prefixed=False):
+ return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x42\x46\x42\x53", size_prefixed=size_prefixed)
+
+ # SchemaFile
+ def Init(self, buf, pos):
+ self._tab = flatbuffers.table.Table(buf, pos)
+
+ # Filename, relative to project root.
+ # SchemaFile
+ def Filename(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
+ if o != 0:
+ return self._tab.String(o + self._tab.Pos)
+ return None
+
+ # Names of included files, relative to project root.
+ # SchemaFile
+ def IncludedFilenames(self, j):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6))
+ if o != 0:
+ a = self._tab.Vector(o)
+ return self._tab.String(a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4))
+ return ""
+
+ # SchemaFile
+ def IncludedFilenamesLength(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6))
+ if o != 0:
+ return self._tab.VectorLen(o)
+ return 0
+
+ # SchemaFile
+ def IncludedFilenamesIsNone(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6))
+ return o == 0
+
+def SchemaFileStart(builder): builder.StartObject(2)
+def Start(builder):
+ return SchemaFileStart(builder)
+def SchemaFileAddFilename(builder, filename): builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(filename), 0)
+def AddFilename(builder, filename):
+ return SchemaFileAddFilename(builder, filename)
+def SchemaFileAddIncludedFilenames(builder, includedFilenames): builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(includedFilenames), 0)
+def AddIncludedFilenames(builder, includedFilenames):
+ return SchemaFileAddIncludedFilenames(builder, includedFilenames)
+def SchemaFileStartIncludedFilenamesVector(builder, numElems): return builder.StartVector(4, numElems, 4)
+def StartIncludedFilenamesVector(builder, numElems):
+ return SchemaFileStartIncludedFilenamesVector(builder, numElems)
+def SchemaFileEnd(builder): return builder.EndObject()
+def End(builder):
+ return SchemaFileEnd(builder)
\ No newline at end of file
diff --git a/python/flatbuffers/reflection/Service.py b/python/flatbuffers/reflection/Service.py
new file mode 100644
index 0000000..d4f1a6a
--- /dev/null
+++ b/python/flatbuffers/reflection/Service.py
@@ -0,0 +1,145 @@
+# automatically generated by the FlatBuffers compiler, do not modify
+
+# namespace: reflection
+
+import flatbuffers
+from flatbuffers.compat import import_numpy
+np = import_numpy()
+
+class Service(object):
+ __slots__ = ['_tab']
+
+ @classmethod
+ def GetRootAs(cls, buf, offset=0):
+ n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
+ x = Service()
+ x.Init(buf, n + offset)
+ return x
+
+ @classmethod
+ def GetRootAsService(cls, buf, offset=0):
+ """This method is deprecated. Please switch to GetRootAs."""
+ return cls.GetRootAs(buf, offset)
+ @classmethod
+ def ServiceBufferHasIdentifier(cls, buf, offset, size_prefixed=False):
+ return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x42\x46\x42\x53", size_prefixed=size_prefixed)
+
+ # Service
+ def Init(self, buf, pos):
+ self._tab = flatbuffers.table.Table(buf, pos)
+
+ # Service
+ def Name(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
+ if o != 0:
+ return self._tab.String(o + self._tab.Pos)
+ return None
+
+ # Service
+ def Calls(self, j):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6))
+ if o != 0:
+ x = self._tab.Vector(o)
+ x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4
+ x = self._tab.Indirect(x)
+ from reflection.RPCCall import RPCCall
+ obj = RPCCall()
+ obj.Init(self._tab.Bytes, x)
+ return obj
+ return None
+
+ # Service
+ def CallsLength(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6))
+ if o != 0:
+ return self._tab.VectorLen(o)
+ return 0
+
+ # Service
+ def CallsIsNone(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6))
+ return o == 0
+
+ # Service
+ def Attributes(self, j):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8))
+ if o != 0:
+ x = self._tab.Vector(o)
+ x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4
+ x = self._tab.Indirect(x)
+ from reflection.KeyValue import KeyValue
+ obj = KeyValue()
+ obj.Init(self._tab.Bytes, x)
+ return obj
+ return None
+
+ # Service
+ def AttributesLength(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8))
+ if o != 0:
+ return self._tab.VectorLen(o)
+ return 0
+
+ # Service
+ def AttributesIsNone(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8))
+ return o == 0
+
+ # Service
+ def Documentation(self, j):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10))
+ if o != 0:
+ a = self._tab.Vector(o)
+ return self._tab.String(a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4))
+ return ""
+
+ # Service
+ def DocumentationLength(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10))
+ if o != 0:
+ return self._tab.VectorLen(o)
+ return 0
+
+ # Service
+ def DocumentationIsNone(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10))
+ return o == 0
+
+ # File that this Service is declared in.
+ # Service
+ def DeclarationFile(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12))
+ if o != 0:
+ return self._tab.String(o + self._tab.Pos)
+ return None
+
+def ServiceStart(builder): builder.StartObject(5)
+def Start(builder):
+ return ServiceStart(builder)
+def ServiceAddName(builder, name): builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(name), 0)
+def AddName(builder, name):
+ return ServiceAddName(builder, name)
+def ServiceAddCalls(builder, calls): builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(calls), 0)
+def AddCalls(builder, calls):
+ return ServiceAddCalls(builder, calls)
+def ServiceStartCallsVector(builder, numElems): return builder.StartVector(4, numElems, 4)
+def StartCallsVector(builder, numElems):
+ return ServiceStartCallsVector(builder, numElems)
+def ServiceAddAttributes(builder, attributes): builder.PrependUOffsetTRelativeSlot(2, flatbuffers.number_types.UOffsetTFlags.py_type(attributes), 0)
+def AddAttributes(builder, attributes):
+ return ServiceAddAttributes(builder, attributes)
+def ServiceStartAttributesVector(builder, numElems): return builder.StartVector(4, numElems, 4)
+def StartAttributesVector(builder, numElems):
+ return ServiceStartAttributesVector(builder, numElems)
+def ServiceAddDocumentation(builder, documentation): builder.PrependUOffsetTRelativeSlot(3, flatbuffers.number_types.UOffsetTFlags.py_type(documentation), 0)
+def AddDocumentation(builder, documentation):
+ return ServiceAddDocumentation(builder, documentation)
+def ServiceStartDocumentationVector(builder, numElems): return builder.StartVector(4, numElems, 4)
+def StartDocumentationVector(builder, numElems):
+ return ServiceStartDocumentationVector(builder, numElems)
+def ServiceAddDeclarationFile(builder, declarationFile): builder.PrependUOffsetTRelativeSlot(4, flatbuffers.number_types.UOffsetTFlags.py_type(declarationFile), 0)
+def AddDeclarationFile(builder, declarationFile):
+ return ServiceAddDeclarationFile(builder, declarationFile)
+def ServiceEnd(builder): return builder.EndObject()
+def End(builder):
+ return ServiceEnd(builder)
\ No newline at end of file
diff --git a/python/flatbuffers/reflection/Type.py b/python/flatbuffers/reflection/Type.py
new file mode 100644
index 0000000..d606ab9
--- /dev/null
+++ b/python/flatbuffers/reflection/Type.py
@@ -0,0 +1,98 @@
+# automatically generated by the FlatBuffers compiler, do not modify
+
+# namespace: reflection
+
+import flatbuffers
+from flatbuffers.compat import import_numpy
+np = import_numpy()
+
+class Type(object):
+ __slots__ = ['_tab']
+
+ @classmethod
+ def GetRootAs(cls, buf, offset=0):
+ n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
+ x = Type()
+ x.Init(buf, n + offset)
+ return x
+
+ @classmethod
+ def GetRootAsType(cls, buf, offset=0):
+ """This method is deprecated. Please switch to GetRootAs."""
+ return cls.GetRootAs(buf, offset)
+ @classmethod
+ def TypeBufferHasIdentifier(cls, buf, offset, size_prefixed=False):
+ return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x42\x46\x42\x53", size_prefixed=size_prefixed)
+
+ # Type
+ def Init(self, buf, pos):
+ self._tab = flatbuffers.table.Table(buf, pos)
+
+ # Type
+ def BaseType(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos)
+ return 0
+
+ # Type
+ def Element(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos)
+ return 0
+
+ # Type
+ def Index(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos)
+ return -1
+
+ # Type
+ def FixedLength(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Uint16Flags, o + self._tab.Pos)
+ return 0
+
+ # The size (octets) of the `base_type` field.
+ # Type
+ def BaseSize(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Uint32Flags, o + self._tab.Pos)
+ return 4
+
+ # The size (octets) of the `element` field, if present.
+ # Type
+ def ElementSize(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Uint32Flags, o + self._tab.Pos)
+ return 0
+
+def TypeStart(builder): builder.StartObject(6)
+def Start(builder):
+ return TypeStart(builder)
+def TypeAddBaseType(builder, baseType): builder.PrependInt8Slot(0, baseType, 0)
+def AddBaseType(builder, baseType):
+ return TypeAddBaseType(builder, baseType)
+def TypeAddElement(builder, element): builder.PrependInt8Slot(1, element, 0)
+def AddElement(builder, element):
+ return TypeAddElement(builder, element)
+def TypeAddIndex(builder, index): builder.PrependInt32Slot(2, index, -1)
+def AddIndex(builder, index):
+ return TypeAddIndex(builder, index)
+def TypeAddFixedLength(builder, fixedLength): builder.PrependUint16Slot(3, fixedLength, 0)
+def AddFixedLength(builder, fixedLength):
+ return TypeAddFixedLength(builder, fixedLength)
+def TypeAddBaseSize(builder, baseSize): builder.PrependUint32Slot(4, baseSize, 4)
+def AddBaseSize(builder, baseSize):
+ return TypeAddBaseSize(builder, baseSize)
+def TypeAddElementSize(builder, elementSize): builder.PrependUint32Slot(5, elementSize, 0)
+def AddElementSize(builder, elementSize):
+ return TypeAddElementSize(builder, elementSize)
+def TypeEnd(builder): return builder.EndObject()
+def End(builder):
+ return TypeEnd(builder)
\ No newline at end of file
diff --git a/bazel/BUILD b/python/flatbuffers/reflection/__init__.py
similarity index 100%
copy from bazel/BUILD
copy to python/flatbuffers/reflection/__init__.py
diff --git a/readme.md b/readme.md
index 7cccfa1..649cf24 100644
--- a/readme.md
+++ b/readme.md
@@ -1,11 +1,11 @@
 FlatBuffers
===========
-[](https://travis-ci.org/google/flatbuffers)
-[](https://ci.appveyor.com/project/gwvo/flatbuffers)
+
[](https://gitter.im/google/flatbuffers?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[](https:///discord.gg/6qgKs3R)
[](https://twitter.com/wvo)
+[](https://twitter.com/dbaileychess)
**FlatBuffers** is a cross platform serialization library architected for
@@ -44,6 +44,10 @@
*To contribute to this project,* see [CONTRIBUTING][].
+## Security
+
+Please see our [Security Policy](SECURITY.md) for reporting vulnerabilities.
+
## Licensing
*Flatbuffers* is licensed under the Apache License, Version 2.0. See [LICENSE][] for the full license text.
diff --git a/reflection/BUILD.bazel b/reflection/BUILD.bazel
new file mode 100644
index 0000000..7948e12
--- /dev/null
+++ b/reflection/BUILD.bazel
@@ -0,0 +1,14 @@
+load("//:build_defs.bzl", "flatbuffer_ts_library")
+
+filegroup(
+ name = "reflection_fbs_schema",
+ srcs = ["reflection.fbs"],
+ visibility = ["//visibility:public"],
+)
+
+flatbuffer_ts_library(
+ name = "reflection_ts_fbs",
+ srcs = ["reflection.fbs"],
+ include_reflection = False,
+ visibility = ["//visibility:public"],
+)
diff --git a/reflection/generate_code.bat b/reflection/generate_code.bat
deleted file mode 100644
index 7b0f4d8..0000000
--- a/reflection/generate_code.bat
+++ /dev/null
@@ -1,18 +0,0 @@
-:: Copyright 2015 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.
-
-set buildtype=Release
-if "%1"=="-b" set buildtype=%2
-
-..\%buildtype%\flatc.exe --cpp --cpp-std c++0x --no-prefix -o ../include/flatbuffers reflection.fbs || exit /b 1
diff --git a/reflection/generate_code.sh b/reflection/generate_code.sh
deleted file mode 100755
index 694baa2..0000000
--- a/reflection/generate_code.sh
+++ /dev/null
@@ -1,31 +0,0 @@
-#!/bin/bash
-#
-# Copyright 2016 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.
-set -e
-
-tempDir="../include/flatbuffers/.tmp"
-originalFile="../include/flatbuffers/reflection_generated.h"
-newFile="$tempDir/reflection_generated.h"
-
-../flatc -c --cpp-std c++0x --no-prefix -o $tempDir reflection.fbs
-
-if [ -f "$newFile" ]; then
- if ! cmp -s "$originalFile" "$newFile"; then
- mv $newFile $originalFile
- else
- rm $newFile
- fi
- rmdir $tempDir
-fi
diff --git a/reflection/reflection.fbs b/reflection/reflection.fbs
index d9e2dc4..c3665eb 100644
--- a/reflection/reflection.fbs
+++ b/reflection/reflection.fbs
@@ -38,6 +38,10 @@
// If base_type == Union, UnionType, or integral derived
// from an enum, index into "enums" below.
fixed_length:uint16 = 0; // Only if base_type == Array.
+ /// The size (octets) of the `base_type` field.
+ base_size:uint = 4; // 4 Is a common size due to offsets being that size.
+ /// The size (octets) of the `element` field, if present.
+ element_size:uint = 0;
}
table KeyValue {
@@ -48,7 +52,7 @@
table EnumVal {
name:string (required);
value:long (key);
- object:Object; // Will be deprecated in favor of union_type in the future.
+ object:Object (deprecated);
union_type:Type;
documentation:[string];
}
@@ -60,6 +64,8 @@
underlying_type:Type (required);
attributes:[KeyValue];
documentation:[string];
+ /// File that this Enum is declared in.
+ declaration_file: string;
}
table Field {
@@ -75,6 +81,8 @@
attributes:[KeyValue];
documentation:[string];
optional:bool = false;
+ /// Number of padding octets to always add after this field. Structs only.
+ padding:uint16 = 0;
}
table Object { // Used for both tables and structs.
@@ -85,6 +93,8 @@
bytesize:int; // For structs.
attributes:[KeyValue];
documentation:[string];
+ /// File that this Object is declared in.
+ declaration_file: string;
}
table RPCCall {
@@ -100,6 +110,26 @@
calls:[RPCCall];
attributes:[KeyValue];
documentation:[string];
+ /// File that this Service is declared in.
+ declaration_file: string;
+}
+
+/// New schema language features that are not supported by old code generators.
+enum AdvancedFeatures : ulong (bit_flags) {
+ AdvancedArrayFeatures,
+ AdvancedUnionFeatures,
+ OptionalScalars,
+ DefaultVectorsAndStrings,
+}
+
+/// File specific information.
+/// Symbols declared within a file may be recovered by iterating over all
+/// symbols and examining the `declaration_file` field.
+table SchemaFile {
+ /// Filename, relative to project root.
+ filename:string (required, key);
+ /// Names of included files, relative to project root.
+ included_filenames:[string];
}
table Schema {
@@ -109,6 +139,10 @@
file_ext:string;
root_table:Object;
services:[Service]; // Sorted.
+ advanced_features:AdvancedFeatures;
+ /// All the files used in this compilation. Files are relative to where
+ /// flatc was invoked.
+ fbs_files:[SchemaFile]; // Sorted.
}
root_type Schema;
diff --git a/rust/flatbuffers/Cargo.toml b/rust/flatbuffers/Cargo.toml
index 460c552..8bf8c08 100644
--- a/rust/flatbuffers/Cargo.toml
+++ b/rust/flatbuffers/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "flatbuffers"
-version = "0.7.0"
+version = "2.1.1"
edition = "2018"
authors = ["Robert Winslow <hello@rwinslow.com>", "FlatBuffers Maintainers"]
license = "Apache-2.0"
@@ -9,7 +9,18 @@
repository = "https://github.com/google/flatbuffers"
keywords = ["flatbuffers", "serialization", "zero-copy"]
categories = ["encoding", "data-structures", "memory-management"]
+rust = "1.51"
+
+[features]
+default = ["thiserror"]
+no_std = ["core2", "thiserror_core2"]
+serialize = ["serde"]
[dependencies]
-smallvec = "1.0"
-bitflags = "1.2"
+smallvec = "1.6.1"
+bitflags = "1.2.1"
+serde = { version = "1.0", optional = true }
+thiserror = { version = "1.0.30", optional = true }
+core2 = { version = "0.4.0", optional = true }
+# This version is compliant with mainline 1.0.30
+thiserror_core2 = { version = "2.0.0", default-features = false, optional = true }
diff --git a/rust/flatbuffers/README.md b/rust/flatbuffers/README.md
new file mode 100644
index 0000000..4d7a5be
--- /dev/null
+++ b/rust/flatbuffers/README.md
@@ -0,0 +1,15 @@
+# Flatbuffers
+
+FlatBuffers is a cross platform serialization library architected for maximum
+memory efficiency. It allows you to directly access serialized data without
+parsing/unpacking it first, while still having great forwards/backwards
+compatibility. It was originally created at Google for game development and
+other performance-critical applications.
+
+## See our
+* [Tutorial](https://google.github.io/flatbuffers/flatbuffers_guide_tutorial.html)
+* [Landing Page](https://google.github.io/flatbuffers/)
+* [Rust sample binary](https://github.com/google/flatbuffers/blob/master/samples/sample_binary.rs)
+* [Schema**less** format, Flexbuffers](https://crates.io/crates/flexbuffers)
+* [Github](https://github.com/google/flatbuffers)
+
diff --git a/rust/flatbuffers/src/array.rs b/rust/flatbuffers/src/array.rs
new file mode 100644
index 0000000..2ce2e47
--- /dev/null
+++ b/rust/flatbuffers/src/array.rs
@@ -0,0 +1,154 @@
+/*
+ * Copyright 2021 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.
+ */
+
+use crate::follow::Follow;
+use crate::vector::VectorIter;
+use crate::EndianScalar;
+use core::fmt::{Debug, Formatter, Result};
+use core::marker::PhantomData;
+use core::mem::size_of;
+
+#[derive(Copy, Clone)]
+pub struct Array<'a, T: 'a, const N: usize>(&'a [u8], PhantomData<T>);
+
+impl<'a, T: 'a, const N: usize> Debug for Array<'a, T, N>
+where
+ T: 'a + Follow<'a>,
+ <T as Follow<'a>>::Inner: Debug,
+{
+ fn fmt(&self, f: &mut Formatter) -> Result {
+ f.debug_list().entries(self.iter()).finish()
+ }
+}
+
+#[allow(clippy::len_without_is_empty)]
+#[allow(clippy::from_over_into)] // TODO(caspern): Go from From to Into.
+impl<'a, T: 'a, const N: usize> Array<'a, T, N> {
+ #[inline(always)]
+ pub fn new(buf: &'a [u8]) -> Self {
+ assert!(size_of::<T>() * N == buf.len());
+
+ Array {
+ 0: buf,
+ 1: PhantomData,
+ }
+ }
+
+ #[inline(always)]
+ pub const fn len(&self) -> usize {
+ N
+ }
+ pub fn as_ptr(&self) -> *const u8 {
+ self.0.as_ptr()
+ }
+}
+
+impl<'a, T: Follow<'a> + 'a, const N: usize> Array<'a, T, N> {
+ #[inline(always)]
+ pub fn get(&self, idx: usize) -> T::Inner {
+ assert!(idx < N);
+ let sz = size_of::<T>();
+ T::follow(self.0, sz * idx)
+ }
+
+ #[inline(always)]
+ pub fn iter(&self) -> VectorIter<'a, T> {
+ VectorIter::from_slice(self.0, self.len())
+ }
+}
+
+impl<'a, T: Follow<'a> + Debug, const N: usize> Into<[T::Inner; N]> for Array<'a, T, N> {
+ #[inline(always)]
+ fn into(self) -> [T::Inner; N] {
+ array_init(|i| self.get(i))
+ }
+}
+
+// TODO(caspern): Implement some future safe version of SafeSliceAccess.
+
+/// Implement Follow for all possible Arrays that have Follow-able elements.
+impl<'a, T: Follow<'a> + 'a, const N: usize> Follow<'a> for Array<'a, T, N> {
+ type Inner = Array<'a, T, N>;
+ #[inline(always)]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ Array::new(&buf[loc..loc + N * size_of::<T>()])
+ }
+}
+
+pub fn emplace_scalar_array<T: EndianScalar, const N: usize>(
+ buf: &mut [u8],
+ loc: usize,
+ src: &[T; N],
+) {
+ let mut buf_ptr = buf[loc..].as_mut_ptr();
+ for item in src.iter() {
+ let item_le = item.to_little_endian();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ &item_le as *const T as *const u8,
+ buf_ptr,
+ size_of::<T>(),
+ );
+ buf_ptr = buf_ptr.add(size_of::<T>());
+ }
+ }
+}
+
+impl<'a, T: Follow<'a> + 'a, const N: usize> IntoIterator for Array<'a, T, N> {
+ type Item = T::Inner;
+ type IntoIter = VectorIter<'a, T>;
+ #[inline]
+ fn into_iter(self) -> Self::IntoIter {
+ self.iter()
+ }
+}
+
+#[inline]
+pub fn array_init<F, T, const N: usize>(mut initializer: F) -> [T; N]
+where
+ F: FnMut(usize) -> T,
+{
+ let mut array: core::mem::MaybeUninit<[T; N]> = core::mem::MaybeUninit::uninit();
+ let mut ptr_i = array.as_mut_ptr() as *mut T;
+
+ unsafe {
+ for i in 0..N {
+ let value_i = initializer(i);
+ ptr_i.write(value_i);
+ ptr_i = ptr_i.add(1);
+ }
+ array.assume_init()
+ }
+}
+
+#[cfg(feature="serialize")]
+impl<'a, T: 'a, const N: usize> serde::ser::Serialize for Array<'a, T, N>
+where
+ T: 'a + Follow<'a>,
+ <T as Follow<'a>>::Inner: serde::ser::Serialize,
+{
+ fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
+ where
+ S: serde::ser::Serializer,
+ {
+ use serde::ser::SerializeSeq;
+ let mut seq = serializer.serialize_seq(Some(self.len()))?;
+ for element in self.iter() {
+ seq.serialize_element(&element)?;
+ }
+ seq.end()
+ }
+}
diff --git a/rust/flatbuffers/src/builder.rs b/rust/flatbuffers/src/builder.rs
index a3c15f2..8a8b58c 100644
--- a/rust/flatbuffers/src/builder.rs
+++ b/rust/flatbuffers/src/builder.rs
@@ -16,11 +16,13 @@
extern crate smallvec;
-use std::cmp::max;
-use std::iter::{DoubleEndedIterator, ExactSizeIterator};
-use std::marker::PhantomData;
-use std::ptr::write_bytes;
-use std::slice::from_raw_parts;
+use core::cmp::max;
+use core::iter::{DoubleEndedIterator, ExactSizeIterator};
+use core::marker::PhantomData;
+use core::ptr::write_bytes;
+use core::slice::from_raw_parts;
+#[cfg(feature = "no_std")]
+use alloc::{vec, vec::Vec};
use crate::endian_scalar::{emplace_scalar, read_scalar_at};
use crate::primitives::*;
@@ -54,6 +56,7 @@
min_align: usize,
force_defaults: bool,
+ strings_pool: Vec<WIPOffset<&'fbb str>>,
_phantom: PhantomData<&'fbb ()>,
}
@@ -61,24 +64,32 @@
impl<'fbb> FlatBufferBuilder<'fbb> {
/// Create a FlatBufferBuilder that is ready for writing.
pub fn new() -> Self {
- Self::new_with_capacity(0)
+ Self::with_capacity(0)
}
-
+ #[deprecated(note = "replaced with `with_capacity`", since = "0.8.5")]
+ pub fn new_with_capacity(size: usize) -> Self {
+ Self::with_capacity(size)
+ }
/// Create a FlatBufferBuilder that is ready for writing, with a
/// ready-to-use capacity of the provided size.
///
/// The maximum valid value is `FLATBUFFERS_MAX_BUFFER_SIZE`.
- pub fn new_with_capacity(size: usize) -> Self {
+ pub fn with_capacity(size: usize) -> Self {
+ Self::from_vec(vec![0; size])
+ }
+ /// Create a FlatBufferBuilder that is ready for writing, reusing
+ /// an existing vector.
+ pub fn from_vec(buffer: Vec<u8>) -> Self {
// we need to check the size here because we create the backing buffer
// directly, bypassing the typical way of using grow_owned_buf:
assert!(
- size <= FLATBUFFERS_MAX_BUFFER_SIZE,
+ buffer.len() <= FLATBUFFERS_MAX_BUFFER_SIZE,
"cannot initialize buffer bigger than 2 gigabytes"
);
-
+ let head = buffer.len();
FlatBufferBuilder {
- owned_buf: vec![0u8; size],
- head: size,
+ owned_buf: buffer,
+ head,
field_locs: Vec::new(),
written_vtable_revpos: Vec::new(),
@@ -88,6 +99,7 @@
min_align: 0,
force_defaults: false,
+ strings_pool: Vec::new(),
_phantom: PhantomData,
}
@@ -121,6 +133,7 @@
self.finished = false;
self.min_align = 0;
+ self.strings_pool.clear();
}
/// Destroy the FlatBufferBuilder, returning its internal byte vector
@@ -235,6 +248,43 @@
WIPOffset::new(o.value())
}
+ #[inline]
+ pub fn create_shared_string<'a: 'b, 'b>(&'a mut self, s: &'b str) -> WIPOffset<&'fbb str> {
+ self.assert_not_nested(
+ "create_shared_string can not be called when a table or vector is under construction",
+ );
+
+ // Saves a ref to owned_buf since rust doesnt like us refrencing it
+ // in the binary_search_by code.
+ let buf = &self.owned_buf;
+
+ let found = self.strings_pool.binary_search_by(|offset| {
+ let ptr = offset.value() as usize;
+ // Gets The pointer to the size of the string
+ let str_memory = &buf[buf.len() - ptr..];
+ // Gets the size of the written string from buffer
+ let size =
+ u32::from_le_bytes([str_memory[0], str_memory[1], str_memory[2], str_memory[3]])
+ as usize;
+ // Size of the string size
+ let string_size: usize = 4;
+ // Fetches actual string bytes from index of string after string size
+ // to the size of string plus string size
+ let iter = str_memory[string_size..size + string_size].iter();
+ // Compares bytes of fetched string and current writable string
+ iter.cloned().cmp(s.bytes())
+ });
+
+ match found {
+ Ok(index) => self.strings_pool[index],
+ Err(index) => {
+ let address = WIPOffset::new(self.create_byte_string(s.as_bytes()).value());
+ self.strings_pool.insert(index, address);
+ address
+ }
+ }
+ }
+
/// Create a utf8 string.
///
/// The wire format represents this as a zero-terminated byte vector.
@@ -367,11 +417,21 @@
}
/// Get the byte slice for the data that has been written after a call to
/// one of the `finish` functions.
+ /// # Panics
+ /// Panics if the buffer is not finished.
#[inline]
pub fn finished_data(&self) -> &[u8] {
self.assert_finished("finished_bytes cannot be called when the buffer is not yet finished");
&self.owned_buf[self.head..]
}
+ /// Returns a mutable view of a finished buffer and location of where the flatbuffer starts.
+ /// Note that modifying the flatbuffer data may corrupt it.
+ /// # Panics
+ /// Panics if the flatbuffer is not finished.
+ #[inline]
+ pub fn mut_finished_buffer(&mut self) -> (&mut [u8], usize) {
+ (&mut self.owned_buf, self.head)
+ }
/// Assert that a field is present in the just-finished Table.
///
/// This is somewhat low-level and is mostly used by the generated code.
@@ -435,7 +495,7 @@
// Write the vtable offset, which is the start of any Table.
// We fill its value later.
let object_revloc_to_vtable: WIPOffset<VTableWIPOffset> =
- WIPOffset::new(self.push::<UOffsetT>(0xF0F0_F0F0 as UOffsetT).value());
+ WIPOffset::new(self.push::<UOffsetT>(0xF0F0_F0F0).value());
// Layout of the data this function will create when a new vtable is
// needed.
@@ -496,39 +556,37 @@
// serialize every FieldLoc to the vtable:
for &fl in self.field_locs.iter() {
let pos: VOffsetT = (object_revloc_to_vtable.value() - fl.off) as VOffsetT;
- debug_assert_eq!(
- vtfw.get_field_offset(fl.id),
- 0,
- "tried to write a vtable field multiple times"
- );
vtfw.write_field_offset(fl.id, pos);
}
}
- let dup_vt_use = {
- let this_vt = VTable::init(&self.owned_buf[..], self.head);
- self.find_duplicate_stored_vtable_revloc(this_vt)
- };
-
- let vt_use = match dup_vt_use {
- Some(n) => {
+ let new_vt_bytes = &self.owned_buf[vt_start_pos..vt_end_pos];
+ let found = self.written_vtable_revpos.binary_search_by(|old_vtable_revpos: &UOffsetT| {
+ let old_vtable_pos = self.owned_buf.len() - *old_vtable_revpos as usize;
+ let old_vtable = VTable::init(&self.owned_buf, old_vtable_pos);
+ new_vt_bytes.cmp(old_vtable.as_bytes())
+ });
+ let final_vtable_revpos = match found {
+ Ok(i) => {
+ // The new vtable is a duplicate so clear it.
VTableWriter::init(&mut self.owned_buf[vt_start_pos..vt_end_pos]).clear();
self.head += vtable_byte_len;
- n
+ self.written_vtable_revpos[i]
}
- None => {
- let new_vt_use = self.used_space() as UOffsetT;
- self.written_vtable_revpos.push(new_vt_use);
- new_vt_use
+ Err(i) => {
+ // This is a new vtable. Add it to the cache.
+ let new_vt_revpos = self.used_space() as UOffsetT;
+ self.written_vtable_revpos.insert(i, new_vt_revpos);
+ new_vt_revpos
}
};
-
- {
- let n = self.head + self.used_space() - object_revloc_to_vtable.value() as usize;
- let saw = read_scalar_at::<UOffsetT>(&self.owned_buf, n);
- debug_assert_eq!(saw, 0xF0F0_F0F0);
+ // Write signed offset from table to its vtable.
+ let table_pos = self.owned_buf.len() - object_revloc_to_vtable.value() as usize;
+ let tmp_soffset_to_vt = unsafe { read_scalar_at::<UOffsetT>(&self.owned_buf, table_pos) };
+ debug_assert_eq!(tmp_soffset_to_vt, 0xF0F0_F0F0);
+ unsafe {
emplace_scalar::<SOffsetT>(
- &mut self.owned_buf[n..n + SIZE_SOFFSET],
- vt_use as SOffsetT - object_revloc_to_vtable.value() as SOffsetT,
+ &mut self.owned_buf[table_pos..table_pos + SIZE_SOFFSET],
+ final_vtable_revpos as SOffsetT - object_revloc_to_vtable.value() as SOffsetT
);
}
@@ -537,20 +595,6 @@
object_revloc_to_vtable
}
- #[inline]
- fn find_duplicate_stored_vtable_revloc(&self, needle: VTable) -> Option<UOffsetT> {
- for &revloc in self.written_vtable_revpos.iter().rev() {
- let o = VTable::init(
- &self.owned_buf[..],
- self.head + self.used_space() - revloc as usize,
- );
- if needle == o {
- return Some(revloc);
- }
- }
- None
- }
-
// Only call this when you know it is safe to double the size of the buffer.
#[inline]
fn grow_owned_buf(&mut self) {
@@ -685,23 +729,21 @@
// could be empty (e.g. for empty tables, or for all-default values).
debug_assert!(
self.nested,
- format!(
- "incorrect FlatBufferBuilder usage: {} must be called while in a nested state",
- fn_name
- )
+ "incorrect FlatBufferBuilder usage: {} must be called while in a nested state",
+ fn_name
);
}
#[inline]
fn assert_not_nested(&self, msg: &'static str) {
- debug_assert!(!self.nested, msg);
+ debug_assert!(!self.nested, "{}", msg);
}
#[inline]
fn assert_finished(&self, msg: &'static str) {
- debug_assert!(self.finished, msg);
+ debug_assert!(self.finished, "{}", msg);
}
#[inline]
fn assert_not_finished(&self, msg: &'static str) {
- debug_assert!(!self.finished, msg);
+ debug_assert!(!self.finished, "{}", msg);
}
}
@@ -725,6 +767,6 @@
impl<'fbb> Default for FlatBufferBuilder<'fbb> {
fn default() -> Self {
- Self::new_with_capacity(0)
+ Self::with_capacity(0)
}
}
diff --git a/rust/flatbuffers/src/endian_scalar.rs b/rust/flatbuffers/src/endian_scalar.rs
index df0b384..5f50cf1 100644
--- a/rust/flatbuffers/src/endian_scalar.rs
+++ b/rust/flatbuffers/src/endian_scalar.rs
@@ -13,8 +13,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+#![allow(clippy::wrong_self_convention)]
-use std::mem::size_of;
+use core::mem::size_of;
/// Trait for values that must be stored in little-endian byte order, but
/// might be represented in memory as big-endian. Every type that implements
@@ -148,32 +149,36 @@
/// Place an EndianScalar into the provided mutable byte slice. Performs
/// endian conversion, if necessary.
+/// # Safety
+/// Caller must ensure `s.len() > size_of::<T>()`
+/// and `x` does not overlap with `s`.
#[inline]
-pub fn emplace_scalar<T: EndianScalar>(s: &mut [u8], x: T) {
- let sz = size_of::<T>();
- let mut_ptr = (&mut s[..sz]).as_mut_ptr() as *mut T;
- let val = x.to_little_endian();
- unsafe {
- *mut_ptr = val;
- }
+pub unsafe fn emplace_scalar<T: EndianScalar>(s: &mut [u8], x: T) {
+ let x_le = x.to_little_endian();
+ core::ptr::copy_nonoverlapping(
+ &x_le as *const T as *const u8,
+ s.as_mut_ptr() as *mut u8,
+ size_of::<T>(),
+ );
}
/// Read an EndianScalar from the provided byte slice at the specified location.
/// Performs endian conversion, if necessary.
+/// # Safety
+/// Caller must ensure `s.len() > loc + size_of::<T>()`.
#[inline]
-pub fn read_scalar_at<T: EndianScalar>(s: &[u8], loc: usize) -> T {
- let buf = &s[loc..loc + size_of::<T>()];
- read_scalar(buf)
+pub unsafe fn read_scalar_at<T: EndianScalar>(s: &[u8], loc: usize) -> T {
+ read_scalar(&s[loc..])
}
/// Read an EndianScalar from the provided byte slice. Performs endian
/// conversion, if necessary.
+/// # Safety
+/// Caller must ensure `s.len() > size_of::<T>()`.
#[inline]
-pub fn read_scalar<T: EndianScalar>(s: &[u8]) -> T {
- let sz = size_of::<T>();
-
- let p = (&s[..sz]).as_ptr() as *const T;
- let x = unsafe { *p };
-
- x.from_little_endian()
+pub unsafe fn read_scalar<T: EndianScalar>(s: &[u8]) -> T {
+ let mut mem = core::mem::MaybeUninit::<T>::uninit();
+ // Since [u8] has alignment 1, we copy it into T which may have higher alignment.
+ core::ptr::copy_nonoverlapping(s.as_ptr(), mem.as_mut_ptr() as *mut u8, size_of::<T>());
+ mem.assume_init().from_little_endian()
}
diff --git a/rust/flatbuffers/src/follow.rs b/rust/flatbuffers/src/follow.rs
index 8dd70da..d1d6483 100644
--- a/rust/flatbuffers/src/follow.rs
+++ b/rust/flatbuffers/src/follow.rs
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-use std::marker::PhantomData;
+use core::marker::PhantomData;
/// Follow is a trait that allows us to access FlatBuffers in a declarative,
/// type safe, and fast way. They compile down to almost no code (after
@@ -27,16 +27,9 @@
/// Writing a new Follow implementation primarily involves deciding whether
/// you want to return data (of the type Self::Inner) or do you want to
/// continue traversing the FlatBuffer.
-pub trait Follow<'a> {
+pub trait Follow<'buf> {
type Inner;
- fn follow(buf: &'a [u8], loc: usize) -> Self::Inner;
-}
-
-/// Execute a follow as a top-level function.
-#[allow(dead_code)]
-#[inline]
-pub fn lifted_follow<'a, T: Follow<'a>>(buf: &'a [u8], loc: usize) -> T::Inner {
- T::follow(buf, loc)
+ fn follow(buf: &'buf [u8], loc: usize) -> Self::Inner;
}
/// FollowStart wraps a Follow impl in a struct type. This can make certain
diff --git a/rust/flatbuffers/src/get_root.rs b/rust/flatbuffers/src/get_root.rs
new file mode 100644
index 0000000..3305efa
--- /dev/null
+++ b/rust/flatbuffers/src/get_root.rs
@@ -0,0 +1,107 @@
+/*
+ * Copyright 2020 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.
+ */
+
+use crate::{
+ Follow, ForwardsUOffset, InvalidFlatbuffer, SkipSizePrefix, Verifiable, Verifier,
+ VerifierOptions,
+};
+
+/// Gets the root of the Flatbuffer, verifying it first with default options.
+/// Note that verification is an experimental feature and may not be maximally performant or
+/// catch every error (though that is the goal). See the `_unchecked` variants for previous
+/// behavior.
+pub fn root<'buf, T>(data: &'buf [u8]) -> Result<T::Inner, InvalidFlatbuffer>
+where
+ T: 'buf + Follow<'buf> + Verifiable,
+{
+ let opts = VerifierOptions::default();
+ root_with_opts::<T>(&opts, data)
+}
+
+#[inline]
+/// Gets the root of the Flatbuffer, verifying it first with given options.
+/// Note that verification is an experimental feature and may not be maximally performant or
+/// catch every error (though that is the goal). See the `_unchecked` variants for previous
+/// behavior.
+pub fn root_with_opts<'opts, 'buf, T>(
+ opts: &'opts VerifierOptions,
+ data: &'buf [u8],
+) -> Result<T::Inner, InvalidFlatbuffer>
+where
+ T: 'buf + Follow<'buf> + Verifiable,
+{
+ let mut v = Verifier::new(opts, data);
+ <ForwardsUOffset<T>>::run_verifier(&mut v, 0)?;
+ Ok(unsafe { root_unchecked::<T>(data) })
+}
+
+#[inline]
+/// Gets the root of a size prefixed Flatbuffer, verifying it first with default options.
+/// Note that verification is an experimental feature and may not be maximally performant or
+/// catch every error (though that is the goal). See the `_unchecked` variants for previous
+/// behavior.
+pub fn size_prefixed_root<'buf, T>(data: &'buf [u8]) -> Result<T::Inner, InvalidFlatbuffer>
+where
+ T: 'buf + Follow<'buf> + Verifiable,
+{
+ let opts = VerifierOptions::default();
+ size_prefixed_root_with_opts::<T>(&opts, data)
+}
+
+#[inline]
+/// Gets the root of a size prefixed Flatbuffer, verifying it first with given options.
+/// Note that verification is an experimental feature and may not be maximally performant or
+/// catch every error (though that is the goal). See the `_unchecked` variants for previous
+/// behavior.
+pub fn size_prefixed_root_with_opts<'opts, 'buf, T>(
+ opts: &'opts VerifierOptions,
+ data: &'buf [u8],
+) -> Result<T::Inner, InvalidFlatbuffer>
+where
+ T: 'buf + Follow<'buf> + Verifiable,
+{
+ let mut v = Verifier::new(opts, data);
+ <SkipSizePrefix<ForwardsUOffset<T>>>::run_verifier(&mut v, 0)?;
+ Ok(unsafe { size_prefixed_root_unchecked::<T>(data) })
+}
+
+#[inline]
+/// Gets root for a trusted Flatbuffer.
+/// # Safety
+/// Flatbuffers accessors do not perform validation checks before accessing. Unlike the other
+/// `root` functions, this does not validate the flatbuffer before returning the accessor. Users
+/// must trust `data` contains a valid flatbuffer (e.g. b/c it was built by your software). Reading
+/// unchecked buffers may cause panics or even UB.
+pub unsafe fn root_unchecked<'buf, T>(data: &'buf [u8]) -> T::Inner
+where
+ T: Follow<'buf> + 'buf,
+{
+ <ForwardsUOffset<T>>::follow(data, 0)
+}
+
+#[inline]
+/// Gets root for a trusted, size prefixed, Flatbuffer.
+/// # Safety
+/// Flatbuffers accessors do not perform validation checks before accessing. Unlike the other
+/// `root` functions, this does not validate the flatbuffer before returning the accessor. Users
+/// must trust `data` contains a valid flatbuffer (e.g. b/c it was built by your software). Reading
+/// unchecked buffers may cause panics or even UB.
+pub unsafe fn size_prefixed_root_unchecked<'buf, T>(data: &'buf [u8]) -> T::Inner
+where
+ T: Follow<'buf> + 'buf,
+{
+ <SkipSizePrefix<ForwardsUOffset<T>>>::follow(data, 0)
+}
diff --git a/rust/flatbuffers/src/lib.rs b/rust/flatbuffers/src/lib.rs
index 3abd33b..bc114e6 100644
--- a/rust/flatbuffers/src/lib.rs
+++ b/rust/flatbuffers/src/lib.rs
@@ -19,26 +19,34 @@
//! A library for memory-efficient serialization of data.
//!
//! This crate provides runtime support for the FlatBuffers format in the Rust programming language.
-//! To use this crate, first generate code with the `flatc` compiler, as described here: https://google.github.io/flatbuffers/
+//! To use this crate, first generate code with the `flatc` compiler, as described here: <https://google.github.io/flatbuffers/>
//! Then, include that code into your project.
//! Finally, add this crate to your `Cargo.toml`.
//!
//! At this time, Rust support is experimental, and APIs may change between minor versions.
//!
-//! At this time, to generate Rust code, you will need the latest `master` version of `flatc`, available from here: https://github.com/google/flatbuffers
+//! At this time, to generate Rust code, you will need the latest `master` version of `flatc`, available from here: <https://github.com/google/flatbuffers>
//! (On OSX, you can install FlatBuffers from `HEAD` with the Homebrew package manager.)
+#![cfg_attr(feature = "no_std", no_std)]
+
+#[cfg(feature = "no_std")]
+extern crate alloc;
+
+mod array;
mod builder;
mod endian_scalar;
mod follow;
+mod get_root;
mod primitives;
mod push;
mod table;
mod vector;
+mod verifier;
mod vtable;
mod vtable_writer;
-pub use bitflags;
+pub use crate::array::{array_init, emplace_scalar_array, Array};
pub use crate::builder::FlatBufferBuilder;
pub use crate::endian_scalar::{
byte_swap_f32, byte_swap_f64, emplace_scalar, read_scalar, read_scalar_at, EndianScalar,
@@ -46,9 +54,15 @@
pub use crate::follow::{Follow, FollowStart};
pub use crate::primitives::*;
pub use crate::push::Push;
-pub use crate::table::{buffer_has_identifier, get_root, get_size_prefixed_root, Table};
+pub use crate::table::{buffer_has_identifier, Table};
pub use crate::vector::{follow_cast_ref, SafeSliceAccess, Vector, VectorIter};
+pub use crate::verifier::{
+ ErrorTraceDetail, InvalidFlatbuffer, SimpleToVerifyInSlice, Verifiable, Verifier,
+ VerifierOptions,
+};
pub use crate::vtable::field_index_to_field_offset;
+pub use bitflags;
+pub use get_root::*;
// TODO(rw): Unify `create_vector` and `create_vector_direct` by using
// `Into<Vector<...>>`.
diff --git a/rust/flatbuffers/src/primitives.rs b/rust/flatbuffers/src/primitives.rs
index 350e984..72764b2 100644
--- a/rust/flatbuffers/src/primitives.rs
+++ b/rust/flatbuffers/src/primitives.rs
@@ -14,9 +14,9 @@
* limitations under the License.
*/
-use std::marker::PhantomData;
-use std::mem::size_of;
-use std::ops::Deref;
+use core::marker::PhantomData;
+use core::mem::size_of;
+use core::ops::Deref;
use crate::endian_scalar::{emplace_scalar, read_scalar, read_scalar_at};
use crate::follow::Follow;
@@ -93,6 +93,8 @@
}
}
+impl<T> Eq for WIPOffset<T> {}
+
impl<T> PartialEq for WIPOffset<T> {
fn eq(&self, o: &WIPOffset<T>) -> bool {
self.value() == o.value()
@@ -135,7 +137,9 @@
#[inline(always)]
fn push(&self, dst: &mut [u8], rest: &[u8]) {
let n = (SIZE_UOFFSET + rest.len() - self.value() as usize) as UOffsetT;
- emplace_scalar::<UOffsetT>(dst, n);
+ unsafe {
+ emplace_scalar::<UOffsetT>(dst, n);
+ }
}
}
@@ -177,7 +181,7 @@
#[inline(always)]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
let slice = &buf[loc..loc + SIZE_UOFFSET];
- let off = read_scalar::<u32>(slice) as usize;
+ let off = unsafe { read_scalar::<u32>(slice) as usize };
T::follow(buf, loc + off)
}
}
@@ -198,7 +202,7 @@
#[inline(always)]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
let slice = &buf[loc..loc + SIZE_VOFFSET];
- let off = read_scalar::<VOffsetT>(slice) as usize;
+ let off = unsafe { read_scalar::<VOffsetT>(slice) as usize };
T::follow(buf, loc + off)
}
}
@@ -228,7 +232,7 @@
#[inline(always)]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
let slice = &buf[loc..loc + SIZE_SOFFSET];
- let off = read_scalar::<SOffsetT>(slice);
+ let off = unsafe { read_scalar::<SOffsetT>(slice) };
T::follow(buf, (loc as SOffsetT - off) as usize)
}
}
@@ -291,7 +295,7 @@
type Inner = bool;
#[inline(always)]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
- read_scalar_at::<u8>(buf, loc) != 0
+ unsafe { read_scalar_at::<u8>(buf, loc) != 0 }
}
}
@@ -306,7 +310,7 @@
type Inner = $ty;
#[inline(always)]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
- read_scalar_at::<$ty>(buf, loc)
+ unsafe { read_scalar_at::<$ty>(buf, loc) }
}
}
};
diff --git a/rust/flatbuffers/src/push.rs b/rust/flatbuffers/src/push.rs
index c461372..8bb8fe9 100644
--- a/rust/flatbuffers/src/push.rs
+++ b/rust/flatbuffers/src/push.rs
@@ -14,8 +14,8 @@
* limitations under the License.
*/
-use std::cmp::max;
-use std::mem::{align_of, size_of};
+use core::cmp::max;
+use core::mem::{align_of, size_of};
use crate::endian_scalar::emplace_scalar;
@@ -61,7 +61,9 @@
#[inline]
fn push(&self, dst: &mut [u8], _rest: &[u8]) {
- emplace_scalar::<$ty>(dst, *self);
+ unsafe {
+ emplace_scalar::<$ty>(dst, *self);
+ }
}
}
};
diff --git a/rust/flatbuffers/src/table.rs b/rust/flatbuffers/src/table.rs
index 46728cd..cfb8559 100644
--- a/rust/flatbuffers/src/table.rs
+++ b/rust/flatbuffers/src/table.rs
@@ -56,14 +56,6 @@
}
#[inline]
-pub fn get_root<'a, T: Follow<'a> + 'a>(data: &'a [u8]) -> T::Inner {
- <ForwardsUOffset<T>>::follow(data, 0)
-}
-#[inline]
-pub fn get_size_prefixed_root<'a, T: Follow<'a> + 'a>(data: &'a [u8]) -> T::Inner {
- <SkipSizePrefix<ForwardsUOffset<T>>>::follow(data, 0)
-}
-#[inline]
pub fn buffer_has_identifier(data: &[u8], ident: &str, size_prefixed: bool) -> bool {
assert_eq!(ident.len(), FILE_IDENTIFIER_LENGTH);
diff --git a/rust/flatbuffers/src/vector.rs b/rust/flatbuffers/src/vector.rs
index 5236ea1..da04ef6 100644
--- a/rust/flatbuffers/src/vector.rs
+++ b/rust/flatbuffers/src/vector.rs
@@ -14,12 +14,12 @@
* limitations under the License.
*/
-use std::iter::{DoubleEndedIterator, ExactSizeIterator, FusedIterator};
-use std::marker::PhantomData;
-use std::mem::size_of;
-use std::slice::from_raw_parts;
-use std::str::from_utf8_unchecked;
-use std::fmt::{Debug, Result, Formatter};
+use core::fmt::{Debug, Formatter, Result};
+use core::iter::{DoubleEndedIterator, ExactSizeIterator, FusedIterator};
+use core::marker::PhantomData;
+use core::mem::size_of;
+use core::slice::from_raw_parts;
+use core::str::from_utf8_unchecked;
use crate::endian_scalar::read_scalar_at;
#[cfg(target_endian = "little")]
@@ -29,17 +29,28 @@
pub struct Vector<'a, T: 'a>(&'a [u8], usize, PhantomData<T>);
+impl<'a, T: 'a> Default for Vector<'a, T> {
+ fn default() -> Self {
+ // Static, length 0 vector.
+ // Note that derived default causes UB due to issues in read_scalar_at /facepalm.
+ Self(
+ &[0; core::mem::size_of::<UOffsetT>()],
+ 0,
+ Default::default(),
+ )
+ }
+}
+
impl<'a, T> Debug for Vector<'a, T>
where
T: 'a + Follow<'a>,
- <T as Follow<'a>>::Inner : Debug
+ <T as Follow<'a>>::Inner: Debug,
{
fn fmt(&self, f: &mut Formatter) -> Result {
f.debug_list().entries(self.iter()).finish()
}
}
-
// We cannot use derive for these two impls, as it would only implement Copy
// and Clone for `T: Copy` and `T: Clone` respectively. However `Vector<'a, T>`
// can always be copied, no matter that `T` you have.
@@ -62,7 +73,7 @@
#[inline(always)]
pub fn len(&self) -> usize {
- read_scalar_at::<UOffsetT>(&self.0, self.1) as usize
+ unsafe { read_scalar_at::<UOffsetT>(self.0, self.1) as usize }
}
#[inline(always)]
pub fn is_empty(&self) -> bool {
@@ -73,7 +84,7 @@
impl<'a, T: Follow<'a> + 'a> Vector<'a, T> {
#[inline(always)]
pub fn get(&self, idx: usize) -> T::Inner {
- debug_assert!(idx < read_scalar_at::<u32>(&self.0, self.1) as usize);
+ assert!(idx < self.len() as usize);
let sz = size_of::<T>();
debug_assert!(sz > 0);
T::follow(self.0, self.1 as usize + SIZE_UOFFSET + sz * idx)
@@ -81,7 +92,7 @@
#[inline(always)]
pub fn iter(&self) -> VectorIter<'a, T> {
- VectorIter::new(*self)
+ VectorIter::from_vector(*self)
}
}
@@ -92,7 +103,7 @@
let loc = self.1;
let sz = size_of::<T>();
debug_assert!(sz > 0);
- let len = read_scalar_at::<UOffsetT>(&buf, loc) as usize;
+ let len = unsafe { read_scalar_at::<UOffsetT>(buf, loc) } as usize;
let data_buf = &buf[loc + SIZE_UOFFSET..loc + SIZE_UOFFSET + len * sz];
let ptr = data_buf.as_ptr() as *const T;
let s: &'a [T] = unsafe { from_raw_parts(ptr, len) };
@@ -104,6 +115,8 @@
impl SafeSliceAccess for i8 {}
impl SafeSliceAccess for bool {}
+// TODO(caspern): Get rid of this. Conditional compliation is unnecessary complexity.
+// Vectors of primitives just don't work on big endian machines!!!
#[cfg(target_endian = "little")]
mod le_safe_slice_impls {
impl super::SafeSliceAccess for u16 {}
@@ -131,7 +144,7 @@
impl<'a> Follow<'a> for &'a str {
type Inner = &'a str;
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
- let len = read_scalar_at::<UOffsetT>(&buf, loc) as usize;
+ let len = unsafe { read_scalar_at::<UOffsetT>(buf, loc) } as usize;
let slice = &buf[loc + SIZE_UOFFSET..loc + SIZE_UOFFSET + len];
unsafe { from_utf8_unchecked(slice) }
}
@@ -141,7 +154,7 @@
fn follow_slice_helper<T>(buf: &[u8], loc: usize) -> &[T] {
let sz = size_of::<T>();
debug_assert!(sz > 0);
- let len = read_scalar_at::<UOffsetT>(&buf, loc) as usize;
+ let len = unsafe { read_scalar_at::<UOffsetT>(buf, loc) as usize };
let data_buf = &buf[loc + SIZE_UOFFSET..loc + SIZE_UOFFSET + len * sz];
let ptr = data_buf.as_ptr() as *const T;
let s: &[T] = unsafe { from_raw_parts(ptr, len) };
@@ -176,7 +189,7 @@
impl<'a, T: 'a> VectorIter<'a, T> {
#[inline]
- pub fn new(inner: Vector<'a, T>) -> Self {
+ pub fn from_vector(inner: Vector<'a, T>) -> Self {
VectorIter {
buf: inner.0,
// inner.1 is the location of the data for the vector.
@@ -187,6 +200,16 @@
phantom: PhantomData,
}
}
+
+ #[inline]
+ pub fn from_slice(buf: &'a [u8], items_num: usize) -> Self {
+ VectorIter {
+ buf,
+ loc: 0,
+ remaining: items_num,
+ phantom: PhantomData,
+ }
+ }
}
impl<'a, T: Follow<'a> + 'a> Clone for VectorIter<'a, T> {
@@ -285,3 +308,22 @@
self.iter()
}
}
+
+#[cfg(feature="serialize")]
+impl<'a, T> serde::ser::Serialize for Vector<'a, T>
+where
+ T: 'a + Follow<'a>,
+ <T as Follow<'a>>::Inner: serde::ser::Serialize,
+{
+ fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
+ where
+ S: serde::ser::Serializer,
+ {
+ use serde::ser::SerializeSeq;
+ let mut seq = serializer.serialize_seq(Some(self.len()))?;
+ for element in self {
+ seq.serialize_element(&element)?;
+ }
+ seq.end()
+ }
+}
diff --git a/rust/flatbuffers/src/verifier.rs b/rust/flatbuffers/src/verifier.rs
new file mode 100644
index 0000000..d5e31df
--- /dev/null
+++ b/rust/flatbuffers/src/verifier.rs
@@ -0,0 +1,574 @@
+#[cfg(feature = "no_std")]
+use alloc::vec::Vec;
+use core::ops::Range;
+use core::option::Option;
+use crate::follow::Follow;
+use crate::{ForwardsUOffset, SOffsetT, SkipSizePrefix, UOffsetT, VOffsetT, Vector, SIZE_UOFFSET};
+
+#[cfg(feature="no_std")]
+extern crate thiserror_core2 as thiserror;
+use thiserror::Error;
+
+/// Traces the location of data errors. Not populated for Dos detecting errors.
+/// Useful for MissingRequiredField and Utf8Error in particular, though
+/// the other errors should not be producible by correct flatbuffers implementations.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum ErrorTraceDetail {
+ VectorElement {
+ index: usize,
+ position: usize,
+ },
+ TableField {
+ field_name: &'static str,
+ position: usize,
+ },
+ UnionVariant {
+ variant: &'static str,
+ position: usize,
+ },
+}
+#[derive(PartialEq, Eq, Default, Debug, Clone)]
+pub struct ErrorTrace(Vec<ErrorTraceDetail>);
+impl core::convert::AsRef<[ErrorTraceDetail]> for ErrorTrace {
+ #[inline]
+ fn as_ref(&self) -> &[ErrorTraceDetail] {
+ &self.0
+ }
+}
+
+/// Describes how a flatuffer is invalid and, for data errors, roughly where. No extra tracing
+/// information is given for DoS detecting errors since it will probably be a lot.
+#[derive(Clone, Error, Debug, PartialEq, Eq)]
+pub enum InvalidFlatbuffer {
+ #[error("Missing required field `{required}`.\n{error_trace}")]
+ MissingRequiredField {
+ required: &'static str,
+ error_trace: ErrorTrace,
+ },
+ #[error(
+ "Union exactly one of union discriminant (`{field_type}`) and value \
+ (`{field}`) are present.\n{error_trace}"
+ )]
+ InconsistentUnion {
+ field: &'static str,
+ field_type: &'static str,
+ error_trace: ErrorTrace,
+ },
+ #[error("Utf8 error for string in {range:?}: {error}\n{error_trace}")]
+ Utf8Error {
+ #[source]
+ error: core::str::Utf8Error,
+ range: Range<usize>,
+ error_trace: ErrorTrace,
+ },
+ #[error("String in range [{}, {}) is missing its null terminator.\n{error_trace}",
+ range.start, range.end)]
+ MissingNullTerminator {
+ range: Range<usize>,
+ error_trace: ErrorTrace,
+ },
+ #[error("Type `{unaligned_type}` at position {position} is unaligned.\n{error_trace}")]
+ Unaligned {
+ position: usize,
+ unaligned_type: &'static str,
+ error_trace: ErrorTrace,
+ },
+ #[error("Range [{}, {}) is out of bounds.\n{error_trace}", range.start, range.end)]
+ RangeOutOfBounds {
+ range: Range<usize>,
+ error_trace: ErrorTrace,
+ },
+ #[error(
+ "Signed offset at position {position} has value {soffset} which points out of bounds.\
+ \n{error_trace}"
+ )]
+ SignedOffsetOutOfBounds {
+ soffset: SOffsetT,
+ position: usize,
+ error_trace: ErrorTrace,
+ },
+ // Dos detecting errors. These do not get error traces since it will probably be very large.
+ #[error("Too many tables.")]
+ TooManyTables,
+ #[error("Apparent size too large.")]
+ ApparentSizeTooLarge,
+ #[error("Nested table depth limit reached.")]
+ DepthLimitReached,
+}
+
+impl core::fmt::Display for ErrorTrace {
+ fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
+ use ErrorTraceDetail::*;
+ for e in self.0.iter() {
+ match e {
+ VectorElement { index, position } => {
+ writeln!(
+ f,
+ "\twhile verifying vector element {:?} at position {:?}",
+ index, position
+ )?;
+ }
+ TableField {
+ field_name,
+ position,
+ } => {
+ writeln!(
+ f,
+ "\twhile verifying table field `{}` at position {:?}",
+ field_name, position
+ )?;
+ }
+ UnionVariant { variant, position } => {
+ writeln!(
+ f,
+ "\t while verifying union variant `{}` at position {:?}",
+ variant, position
+ )?;
+ }
+ }
+ }
+ Ok(())
+ }
+}
+
+pub type Result<T> = core::result::Result<T, InvalidFlatbuffer>;
+
+impl InvalidFlatbuffer {
+ fn new_range_oob<T>(start: usize, end: usize) -> Result<T> {
+ Err(Self::RangeOutOfBounds {
+ range: Range { start, end },
+ error_trace: Default::default(),
+ })
+ }
+ fn new_inconsistent_union<T>(field: &'static str, field_type: &'static str) -> Result<T> {
+ Err(Self::InconsistentUnion {
+ field,
+ field_type,
+ error_trace: Default::default(),
+ })
+ }
+ fn new_missing_required<T>(required: &'static str) -> Result<T> {
+ Err(Self::MissingRequiredField {
+ required,
+ error_trace: Default::default(),
+ })
+ }
+}
+
+/// Records the path to the verifier detail if the error is a data error and not a DoS error.
+fn append_trace<T>(mut res: Result<T>, d: ErrorTraceDetail) -> Result<T> {
+ if let Err(e) = res.as_mut() {
+ use InvalidFlatbuffer::*;
+ if let MissingRequiredField { error_trace, .. }
+ | Unaligned { error_trace, .. }
+ | RangeOutOfBounds { error_trace, .. }
+ | InconsistentUnion { error_trace, .. }
+ | Utf8Error { error_trace, .. }
+ | MissingNullTerminator { error_trace, .. }
+ | SignedOffsetOutOfBounds { error_trace, .. } = e
+ {
+ error_trace.0.push(d)
+ }
+ }
+ res
+}
+
+/// Adds a TableField trace detail if `res` is a data error.
+fn trace_field<T>(res: Result<T>, field_name: &'static str, position: usize) -> Result<T> {
+ append_trace(
+ res,
+ ErrorTraceDetail::TableField {
+ field_name,
+ position,
+ },
+ )
+}
+/// Adds a TableField trace detail if `res` is a data error.
+fn trace_elem<T>(res: Result<T>, index: usize, position: usize) -> Result<T> {
+ append_trace(res, ErrorTraceDetail::VectorElement { index, position })
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct VerifierOptions {
+ /// Maximum depth of nested tables allowed in a valid flatbuffer.
+ pub max_depth: usize,
+ /// Maximum number of tables allowed in a valid flatbuffer.
+ pub max_tables: usize,
+ /// Maximum "apparent" size of the message if the Flatbuffer object DAG is expanded into a
+ /// tree.
+ pub max_apparent_size: usize,
+ /// Ignore errors where a string is missing its null terminator.
+ /// This is mostly a problem if the message will be sent to a client using old c-strings.
+ pub ignore_missing_null_terminator: bool,
+ // probably want an option to ignore utf8 errors since strings come from c++
+ // options to error un-recognized enums and unions? possible footgun.
+ // Ignore nested flatbuffers, etc?
+}
+impl Default for VerifierOptions {
+ fn default() -> Self {
+ Self {
+ max_depth: 64,
+ max_tables: 1_000_000,
+ // size_ might do something different.
+ max_apparent_size: 1 << 31,
+ ignore_missing_null_terminator: false,
+ }
+ }
+}
+
+/// Carries the verification state. Should not be reused between tables.
+#[derive(Debug)]
+pub struct Verifier<'opts, 'buf> {
+ buffer: &'buf [u8],
+ opts: &'opts VerifierOptions,
+ depth: usize,
+ num_tables: usize,
+ apparent_size: usize,
+}
+impl<'opts, 'buf> Verifier<'opts, 'buf> {
+ pub fn new(opts: &'opts VerifierOptions, buffer: &'buf [u8]) -> Self {
+ Self {
+ opts,
+ buffer,
+ depth: 0,
+ num_tables: 0,
+ apparent_size: 0,
+ }
+ }
+ /// Resets verifier internal state.
+ #[inline]
+ pub fn reset(&mut self) {
+ self.depth = 0;
+ self.num_tables = 0;
+ self.num_tables = 0;
+ }
+ /// Checks `pos` is aligned to T's alignment. This does not mean `buffer[pos]` is aligned w.r.t
+ /// memory since `buffer: &[u8]` has alignment 1.
+ ///
+ /// ### WARNING
+ /// This does not work for flatbuffers-structs as they have alignment 1 according to
+ /// `core::mem::align_of` but are meant to have higher alignment within a Flatbuffer w.r.t.
+ /// `buffer[0]`. TODO(caspern).
+ #[inline]
+ fn is_aligned<T>(&self, pos: usize) -> Result<()> {
+ if pos % core::mem::align_of::<T>() == 0 {
+ Ok(())
+ } else {
+ Err(InvalidFlatbuffer::Unaligned {
+ unaligned_type: core::any::type_name::<T>(),
+ position: pos,
+ error_trace: Default::default(),
+ })
+ }
+ }
+ #[inline]
+ fn range_in_buffer(&mut self, pos: usize, size: usize) -> Result<()> {
+ let end = pos.saturating_add(size);
+ if end > self.buffer.len() {
+ return InvalidFlatbuffer::new_range_oob(pos, end);
+ }
+ self.apparent_size += size;
+ if self.apparent_size > self.opts.max_apparent_size {
+ return Err(InvalidFlatbuffer::ApparentSizeTooLarge);
+ }
+ Ok(())
+ }
+ /// Check that there really is a T in there.
+ #[inline]
+ pub fn in_buffer<T>(&mut self, pos: usize) -> Result<()> {
+ self.is_aligned::<T>(pos)?;
+ self.range_in_buffer(pos, core::mem::size_of::<T>())
+ }
+ #[inline]
+ fn get_u16(&mut self, pos: usize) -> Result<u16> {
+ self.in_buffer::<u16>(pos)?;
+ Ok(u16::from_le_bytes([self.buffer[pos], self.buffer[pos + 1]]))
+ }
+ #[inline]
+ fn get_uoffset(&mut self, pos: usize) -> Result<UOffsetT> {
+ self.in_buffer::<u32>(pos)?;
+ Ok(u32::from_le_bytes([
+ self.buffer[pos],
+ self.buffer[pos + 1],
+ self.buffer[pos + 2],
+ self.buffer[pos + 3],
+ ]))
+ }
+ #[inline]
+ fn deref_soffset(&mut self, pos: usize) -> Result<usize> {
+ self.in_buffer::<SOffsetT>(pos)?;
+ let offset = SOffsetT::from_le_bytes([
+ self.buffer[pos],
+ self.buffer[pos + 1],
+ self.buffer[pos + 2],
+ self.buffer[pos + 3],
+ ]);
+
+ // signed offsets are subtracted.
+ let derefed = if offset > 0 {
+ pos.checked_sub(offset.abs() as usize)
+ } else {
+ pos.checked_add(offset.abs() as usize)
+ };
+ if let Some(x) = derefed {
+ if x < self.buffer.len() {
+ return Ok(x);
+ }
+ }
+ Err(InvalidFlatbuffer::SignedOffsetOutOfBounds {
+ soffset: offset,
+ position: pos,
+ error_trace: Default::default(),
+ })
+ }
+ #[inline]
+ pub fn visit_table<'ver>(
+ &'ver mut self,
+ table_pos: usize,
+ ) -> Result<TableVerifier<'ver, 'opts, 'buf>> {
+ let vtable_pos = self.deref_soffset(table_pos)?;
+ let vtable_len = self.get_u16(vtable_pos)? as usize;
+ self.is_aligned::<VOffsetT>(vtable_pos.saturating_add(vtable_len))?; // i.e. vtable_len is even.
+ self.range_in_buffer(vtable_pos, vtable_len)?;
+ // Check bounds.
+ self.num_tables += 1;
+ if self.num_tables > self.opts.max_tables {
+ return Err(InvalidFlatbuffer::TooManyTables);
+ }
+ self.depth += 1;
+ if self.depth > self.opts.max_depth {
+ return Err(InvalidFlatbuffer::DepthLimitReached);
+ }
+ Ok(TableVerifier {
+ pos: table_pos,
+ vtable: vtable_pos,
+ vtable_len,
+ verifier: self,
+ })
+ }
+
+ /// Runs the union variant's type's verifier assuming the variant is at the given position,
+ /// tracing the error.
+ pub fn verify_union_variant<T: Verifiable>(
+ &mut self,
+ variant: &'static str,
+ position: usize,
+ ) -> Result<()> {
+ let res = T::run_verifier(self, position);
+ append_trace(res, ErrorTraceDetail::UnionVariant { variant, position })
+ }
+}
+
+// Cache table metadata in usize so we don't have to cast types or jump around so much.
+// We will visit every field anyway.
+pub struct TableVerifier<'ver, 'opts, 'buf> {
+ // Absolute position of table in buffer
+ pos: usize,
+ // Absolute position of vtable in buffer.
+ vtable: usize,
+ // Length of vtable.
+ vtable_len: usize,
+ // Verifier struct which holds the surrounding state and options.
+ verifier: &'ver mut Verifier<'opts, 'buf>,
+}
+impl<'ver, 'opts, 'buf> TableVerifier<'ver, 'opts, 'buf> {
+ fn deref(&mut self, field: VOffsetT) -> Result<Option<usize>> {
+ let field = field as usize;
+ if field < self.vtable_len {
+ let field_offset = self.verifier.get_u16(self.vtable.saturating_add(field))?;
+ if field_offset > 0 {
+ // Field is present.
+ let field_pos = self.pos.saturating_add(field_offset as usize);
+ return Ok(Some(field_pos));
+ }
+ }
+ Ok(None)
+ }
+
+ #[inline]
+ pub fn visit_field<T: Verifiable>(
+ mut self,
+ field_name: &'static str,
+ field: VOffsetT,
+ required: bool,
+ ) -> Result<Self> {
+ if let Some(field_pos) = self.deref(field)? {
+ trace_field(
+ T::run_verifier(self.verifier, field_pos),
+ field_name,
+ field_pos,
+ )?;
+ return Ok(self);
+ }
+ if required {
+ InvalidFlatbuffer::new_missing_required(field_name)
+ } else {
+ Ok(self)
+ }
+ }
+ #[inline]
+ /// Union verification is complicated. The schemas passes this function the metadata of the
+ /// union's key (discriminant) and value fields, and a callback. The function verifies and
+ /// reads the key, then invokes the callback to perform data-dependent verification.
+ pub fn visit_union<Key, UnionVerifier>(
+ mut self,
+ key_field_name: &'static str,
+ key_field_voff: VOffsetT,
+ val_field_name: &'static str,
+ val_field_voff: VOffsetT,
+ required: bool,
+ verify_union: UnionVerifier,
+ ) -> Result<Self>
+ where
+ Key: Follow<'buf> + Verifiable,
+ UnionVerifier:
+ (core::ops::FnOnce(<Key as Follow<'buf>>::Inner, &mut Verifier, usize) -> Result<()>),
+ // NOTE: <Key as Follow<'buf>>::Inner == Key
+ {
+ // TODO(caspern): how to trace vtable errors?
+ let val_pos = self.deref(val_field_voff)?;
+ let key_pos = self.deref(key_field_voff)?;
+ match (key_pos, val_pos) {
+ (None, None) => {
+ if required {
+ InvalidFlatbuffer::new_missing_required(val_field_name)
+ } else {
+ Ok(self)
+ }
+ }
+ (Some(k), Some(v)) => {
+ trace_field(Key::run_verifier(self.verifier, k), key_field_name, k)?;
+ let discriminant = Key::follow(self.verifier.buffer, k);
+ trace_field(
+ verify_union(discriminant, self.verifier, v),
+ val_field_name,
+ v,
+ )?;
+ Ok(self)
+ }
+ _ => InvalidFlatbuffer::new_inconsistent_union(key_field_name, val_field_name),
+ }
+ }
+ pub fn finish(self) -> &'ver mut Verifier<'opts, 'buf> {
+ self.verifier.depth -= 1;
+ self.verifier
+ }
+}
+
+// Needs to be implemented for Tables and maybe structs.
+// Unions need some special treatment.
+pub trait Verifiable {
+ /// Runs the verifier for this type, assuming its at position `pos` in the verifier's buffer.
+ /// Should not need to be called directly.
+ fn run_verifier(v: &mut Verifier, pos: usize) -> Result<()>;
+}
+
+// Verify the uoffset and then pass verifier to the type being pointed to.
+impl<T: Verifiable> Verifiable for ForwardsUOffset<T> {
+ #[inline]
+ fn run_verifier(v: &mut Verifier, pos: usize) -> Result<()> {
+ let offset = v.get_uoffset(pos)? as usize;
+ let next_pos = offset.saturating_add(pos);
+ T::run_verifier(v, next_pos)
+ }
+}
+
+/// Checks and returns the range containing the flatbuffers vector.
+fn verify_vector_range<T>(v: &mut Verifier, pos: usize) -> Result<core::ops::Range<usize>> {
+ let len = v.get_uoffset(pos)? as usize;
+ let start = pos.saturating_add(SIZE_UOFFSET);
+ v.is_aligned::<T>(start)?;
+ let size = len.saturating_mul(core::mem::size_of::<T>());
+ let end = start.saturating_add(size);
+ v.range_in_buffer(start, size)?;
+ Ok(core::ops::Range { start, end })
+}
+
+pub trait SimpleToVerifyInSlice {}
+impl SimpleToVerifyInSlice for bool {}
+impl SimpleToVerifyInSlice for i8 {}
+impl SimpleToVerifyInSlice for u8 {}
+impl SimpleToVerifyInSlice for i16 {}
+impl SimpleToVerifyInSlice for u16 {}
+impl SimpleToVerifyInSlice for i32 {}
+impl SimpleToVerifyInSlice for u32 {}
+impl SimpleToVerifyInSlice for f32 {}
+impl SimpleToVerifyInSlice for i64 {}
+impl SimpleToVerifyInSlice for u64 {}
+impl SimpleToVerifyInSlice for f64 {}
+
+impl<T: SimpleToVerifyInSlice> Verifiable for Vector<'_, T> {
+ fn run_verifier(v: &mut Verifier, pos: usize) -> Result<()> {
+ verify_vector_range::<T>(v, pos)?;
+ Ok(())
+ }
+}
+
+impl<T: Verifiable> Verifiable for SkipSizePrefix<T> {
+ #[inline]
+ fn run_verifier(v: &mut Verifier, pos: usize) -> Result<()> {
+ T::run_verifier(v, pos.saturating_add(crate::SIZE_SIZEPREFIX))
+ }
+}
+
+impl<T: Verifiable> Verifiable for Vector<'_, ForwardsUOffset<T>> {
+ #[inline]
+ fn run_verifier(v: &mut Verifier, pos: usize) -> Result<()> {
+ let range = verify_vector_range::<ForwardsUOffset<T>>(v, pos)?;
+ let size = core::mem::size_of::<ForwardsUOffset<T>>();
+ for (i, element_pos) in range.step_by(size).enumerate() {
+ trace_elem(
+ <ForwardsUOffset<T>>::run_verifier(v, element_pos),
+ i,
+ element_pos,
+ )?;
+ }
+ Ok(())
+ }
+}
+
+impl<'a> Verifiable for &'a str {
+ #[inline]
+ fn run_verifier(v: &mut Verifier, pos: usize) -> Result<()> {
+ let range = verify_vector_range::<u8>(v, pos)?;
+ let has_null_terminator = v.buffer.get(range.end).map(|&b| b == 0).unwrap_or(false);
+ let s = core::str::from_utf8(&v.buffer[range.clone()]);
+ if let Err(error) = s {
+ return Err(InvalidFlatbuffer::Utf8Error {
+ error,
+ range,
+ error_trace: Default::default(),
+ });
+ }
+ if !v.opts.ignore_missing_null_terminator && !has_null_terminator {
+ return Err(InvalidFlatbuffer::MissingNullTerminator {
+ range,
+ error_trace: Default::default(),
+ });
+ }
+ Ok(())
+ }
+}
+
+// Verify VectorOfTables, Unions, Arrays, Structs...
+macro_rules! impl_verifiable_for {
+ ($T: ty) => {
+ impl Verifiable for $T {
+ #[inline]
+ fn run_verifier<'opts, 'buf>(v: &mut Verifier<'opts, 'buf>, pos: usize) -> Result<()> {
+ v.in_buffer::<$T>(pos)
+ }
+ }
+ };
+}
+impl_verifiable_for!(bool);
+impl_verifiable_for!(u8);
+impl_verifiable_for!(i8);
+impl_verifiable_for!(u16);
+impl_verifiable_for!(i16);
+impl_verifiable_for!(u32);
+impl_verifiable_for!(i32);
+impl_verifiable_for!(f32);
+impl_verifiable_for!(u64);
+impl_verifiable_for!(i64);
+impl_verifiable_for!(f64);
diff --git a/rust/flatbuffers/src/vtable.rs b/rust/flatbuffers/src/vtable.rs
index 98fb1e2..bbb7190 100644
--- a/rust/flatbuffers/src/vtable.rs
+++ b/rust/flatbuffers/src/vtable.rs
@@ -40,10 +40,10 @@
(self.num_bytes() / SIZE_VOFFSET) - 2
}
pub fn num_bytes(&self) -> usize {
- read_scalar_at::<VOffsetT>(self.buf, self.loc) as usize
+ unsafe { read_scalar_at::<VOffsetT>(self.buf, self.loc) as usize }
}
pub fn object_inline_num_bytes(&self) -> usize {
- let n = read_scalar_at::<VOffsetT>(self.buf, self.loc + SIZE_VOFFSET);
+ let n = unsafe { read_scalar_at::<VOffsetT>(self.buf, self.loc + SIZE_VOFFSET) };
n as usize
}
pub fn get_field(&self, idx: usize) -> VOffsetT {
@@ -51,17 +51,19 @@
if idx > self.num_fields() {
return 0;
}
- read_scalar_at::<VOffsetT>(
- self.buf,
- self.loc + SIZE_VOFFSET + SIZE_VOFFSET + SIZE_VOFFSET * idx,
- )
+ unsafe {
+ read_scalar_at::<VOffsetT>(
+ self.buf,
+ self.loc + SIZE_VOFFSET + SIZE_VOFFSET + SIZE_VOFFSET * idx,
+ )
+ }
}
pub fn get(&self, byte_loc: VOffsetT) -> VOffsetT {
// TODO(rw): distinguish between None and 0?
if byte_loc as usize >= self.num_bytes() {
return 0;
}
- read_scalar_at::<VOffsetT>(self.buf, self.loc + byte_loc as usize)
+ unsafe { read_scalar_at::<VOffsetT>(self.buf, self.loc + byte_loc as usize) }
}
pub fn as_bytes(&self) -> &[u8] {
let len = self.num_bytes();
diff --git a/rust/flatbuffers/src/vtable_writer.rs b/rust/flatbuffers/src/vtable_writer.rs
index 57380bd..9b61dac 100644
--- a/rust/flatbuffers/src/vtable_writer.rs
+++ b/rust/flatbuffers/src/vtable_writer.rs
@@ -14,9 +14,9 @@
* limitations under the License.
*/
-use std::ptr::write_bytes;
+use core::ptr::write_bytes;
-use crate::endian_scalar::{emplace_scalar, read_scalar_at};
+use crate::endian_scalar::emplace_scalar;
use crate::primitives::*;
/// VTableWriter compartmentalizes actions needed to create a vtable.
@@ -40,24 +40,18 @@
/// to the provided value.
#[inline(always)]
pub fn write_vtable_byte_length(&mut self, n: VOffsetT) {
- emplace_scalar::<VOffsetT>(&mut self.buf[..SIZE_VOFFSET], n);
+ unsafe {
+ emplace_scalar::<VOffsetT>(&mut self.buf[..SIZE_VOFFSET], n);
+ }
debug_assert_eq!(n as usize, self.buf.len());
}
/// Writes an object length (in bytes) into the vtable.
#[inline(always)]
pub fn write_object_inline_size(&mut self, n: VOffsetT) {
- emplace_scalar::<VOffsetT>(&mut self.buf[SIZE_VOFFSET..2 * SIZE_VOFFSET], n);
- }
-
- /// Gets an object field offset from the vtable. Only used for debugging.
- ///
- /// Note that this expects field offsets (which are like pointers), not
- /// field ids (which are like array indices).
- #[inline(always)]
- pub fn get_field_offset(&self, vtable_offset: VOffsetT) -> VOffsetT {
- let idx = vtable_offset as usize;
- read_scalar_at::<VOffsetT>(&self.buf, idx)
+ unsafe {
+ emplace_scalar::<VOffsetT>(&mut self.buf[SIZE_VOFFSET..2 * SIZE_VOFFSET], n);
+ }
}
/// Writes an object field offset into the vtable.
@@ -67,7 +61,9 @@
#[inline(always)]
pub fn write_field_offset(&mut self, vtable_offset: VOffsetT, object_data_offset: VOffsetT) {
let idx = vtable_offset as usize;
- emplace_scalar::<VOffsetT>(&mut self.buf[idx..idx + SIZE_VOFFSET], object_data_offset);
+ unsafe {
+ emplace_scalar::<VOffsetT>(&mut self.buf[idx..idx + SIZE_VOFFSET], object_data_offset);
+ }
}
/// Clears all data in this VTableWriter. Used to cleanly undo a
diff --git a/rust/flexbuffers/Cargo.toml b/rust/flexbuffers/Cargo.toml
index 44737a0..e4fa6fa 100644
--- a/rust/flexbuffers/Cargo.toml
+++ b/rust/flexbuffers/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "flexbuffers"
-version = "0.2.1"
+version = "2.0.0"
authors = ["Casper Neo <cneo@google.com>", "FlatBuffers Maintainers"]
edition = "2018"
license = "Apache-2.0"
@@ -20,10 +20,9 @@
# You basically never need this to be true unless reading data from old binaries.
deserialize_human_readable = []
-
[dependencies]
-serde = "1.0"
-serde_derive = "1.0"
-byteorder = "1.3.2"
-num_enum = "0.5.0"
+serde = "1.0.119"
+serde_derive = "1.0.119"
+byteorder = "1.4.2"
+num_enum = "0.5.1"
bitflags = "1.2.1"
diff --git a/rust/flexbuffers/src/buffer.rs b/rust/flexbuffers/src/buffer.rs
new file mode 100644
index 0000000..4643cb8
--- /dev/null
+++ b/rust/flexbuffers/src/buffer.rs
@@ -0,0 +1,80 @@
+use std::ops::{Deref, Range};
+
+/// The underlying buffer that is used by a flexbuffer Reader.
+///
+/// This allows for custom buffer implementations as long as they can be viewed as a &[u8].
+pub trait Buffer: Deref<Target = [u8]> + Sized {
+ // The `BufferString` allows for a buffer to return a custom string which will have the
+ // lifetime of the underlying buffer. A simple `std::str::from_utf8` wouldn't work since that
+ // returns a &str, which is then owned by the callee (cannot be returned from a function).
+ //
+ // Example: During deserialization a `BufferString` is returned, allowing the deserializer
+ // to "borrow" the given str - b/c there is a "lifetime" guarantee, so to speak, from the
+ // underlying buffer.
+ /// A BufferString which will live at least as long as the Buffer itself.
+ ///
+ /// Deref's to UTF-8 `str`, and only generated from the `buffer_str` function Result.
+ type BufferString: Deref<Target = str> + Sized + serde::ser::Serialize;
+
+ /// This method returns an instance of type Self. This allows for lifetimes to be tracked
+ /// in cases of deserialization.
+ ///
+ /// It also lets custom buffers manage reference counts.
+ ///
+ /// Returns None if:
+ /// - range start is greater than end
+ /// - range end is out of bounds
+ ///
+ /// This operation should be fast -> O(1), ideally with no heap allocations.
+ fn slice(&self, range: Range<usize>) -> Option<Self>;
+
+ /// Creates a shallow copy of the given buffer, similar to `slice`.
+ ///
+ /// This operation should be fast -> O(1), ideally with no heap allocations.
+ #[inline]
+ fn shallow_copy(&self) -> Self {
+ self.slice(0..self.len()).unwrap()
+ }
+
+ /// Creates an empty instance of a `Buffer`. This is different than `Default` b/c it
+ /// guarantees that the buffer instance will have length zero.
+ ///
+ /// Most impls shold be able to implement this via `Default`.
+ fn empty() -> Self;
+
+ /// Based off of the `empty` function, allows override for optimization purposes.
+ #[inline]
+ fn empty_str() -> Self::BufferString {
+ Self::empty().buffer_str().unwrap()
+ }
+
+ /// Attempts to convert the given buffer to a custom string type.
+ ///
+ /// This should fail if the type does not have valid UTF-8 bytes, and must be zero copy.
+ fn buffer_str(&self) -> Result<Self::BufferString, std::str::Utf8Error>;
+}
+
+impl<'de> Buffer for &'de [u8] {
+ type BufferString = &'de str;
+
+ #[inline]
+ fn slice(&self, range: Range<usize>) -> Option<Self> {
+ self.get(range)
+ }
+
+ #[inline]
+ fn empty() -> Self {
+ &[]
+ }
+
+ /// Based off of the `empty` function, allows override for optimization purposes.
+ #[inline]
+ fn empty_str() -> Self::BufferString {
+ &""
+ }
+
+ #[inline]
+ fn buffer_str(&self) -> Result<Self::BufferString, std::str::Utf8Error> {
+ std::str::from_utf8(self)
+ }
+}
diff --git a/rust/flexbuffers/src/builder/map.rs b/rust/flexbuffers/src/builder/map.rs
index 1635f64..18d7687 100644
--- a/rust/flexbuffers/src/builder/map.rs
+++ b/rust/flexbuffers/src/builder/map.rs
@@ -97,8 +97,7 @@
// preferred over custom sorting or adding another dependency. By construction, this part
// of the values stack must be alternating (key, value) pairs. The public API must not be
// able to trigger the above debug_assets that protect this unsafe usage.
- let pairs: &mut [[Value; 2]] =
- unsafe { std::slice::from_raw_parts_mut(raw_pairs, pairs_len) };
+ let pairs: &mut [[Value; 2]] = unsafe { std::slice::from_raw_parts_mut(raw_pairs, pairs_len) };
#[rustfmt::skip]
pairs.sort_unstable_by(|[key1, _], [key2, _]| {
if let Value::Key(a1) = *key1 {
diff --git a/rust/flexbuffers/src/builder/mod.rs b/rust/flexbuffers/src/builder/mod.rs
index e71acd0..97838c2 100644
--- a/rust/flexbuffers/src/builder/mod.rs
+++ b/rust/flexbuffers/src/builder/mod.rs
@@ -32,10 +32,11 @@
fn $push_name<T, S>(&mut self, xs: S)
where
T: Into<$scalar> + Copy,
- S: AsRef<[T]>
+ S: AsRef<[T]>,
{
let mut value = Value::$new_vec(xs.as_ref().len());
- let mut width = xs.as_ref()
+ let mut width = xs
+ .as_ref()
.iter()
.map(|x| BitWidth::from((*x).into()))
.max()
@@ -56,7 +57,7 @@
value.set_child_width_or_panic(width);
self.values.push(value);
}
- }
+ };
}
macro_rules! push_indirect {
($push_name: ident, $scalar: ty, $Direct: ident, $Indirect: ident) => {
@@ -65,15 +66,13 @@
let child_width = x.width_or_child_width();
let address = self.buffer.len();
store_value(&mut self.buffer, x, child_width);
- self.values.push(
- Value::Reference {
- address,
- child_width,
- fxb_type: FlexBufferType::$Indirect,
- }
- );
+ self.values.push(Value::Reference {
+ address,
+ child_width,
+ fxb_type: FlexBufferType::$Indirect,
+ });
}
- }
+ };
}
bitflags! {
@@ -242,9 +241,7 @@
let address = self.buffer.len();
for &b in xs.iter() {
self.buffer.push(b as u8);
- for _ in 0..width as u8 {
- self.buffer.push(0); // Well this seems wasteful.
- }
+ self.buffer.resize(self.buffer.len() + width as usize, 0);
}
self.values.push(Value::Reference {
fxb_type: FlexBufferType::VectorBool,
diff --git a/rust/flexbuffers/src/builder/push.rs b/rust/flexbuffers/src/builder/push.rs
index d22b47f..5cb584d 100644
--- a/rust/flexbuffers/src/builder/push.rs
+++ b/rust/flexbuffers/src/builder/push.rs
@@ -14,9 +14,9 @@
use crate::builder::Builder;
use crate::private::Sealed;
-use crate::{Blob, IndirectFloat, IndirectInt, IndirectUInt};
+use crate::{Blob, Buffer, IndirectFloat, IndirectInt, IndirectUInt};
-impl<'a> Sealed for Blob<'a> {}
+impl<B: Buffer> Sealed for Blob<B> {}
impl Sealed for () {}
// TODO: String interning
@@ -44,9 +44,10 @@
builder.push_null();
}
}
-impl<'a> Pushable for Blob<'a> {
+
+impl<B: Buffer> Pushable for Blob<B> {
fn push_to_builder(self, builder: &mut Builder) {
- builder.push_blob(self.0);
+ builder.push_blob(&self.0);
}
}
diff --git a/rust/flexbuffers/src/builder/ser.rs b/rust/flexbuffers/src/builder/ser.rs
index 8e483ba..7ef7757 100644
--- a/rust/flexbuffers/src/builder/ser.rs
+++ b/rust/flexbuffers/src/builder/ser.rs
@@ -36,6 +36,10 @@
pub fn take_buffer(&mut self) -> Vec<u8> {
self.builder.take_buffer()
}
+ pub fn reset(&mut self) {
+ self.builder.reset();
+ self.nesting.clear();
+ }
fn finish_if_not_nested(&mut self) -> Result<(), Error> {
if self.nesting.is_empty() {
assert_eq!(self.builder.values.len(), 1);
diff --git a/rust/flexbuffers/src/builder/value.rs b/rust/flexbuffers/src/builder/value.rs
index f230c34..88ff7b9 100644
--- a/rust/flexbuffers/src/builder/value.rs
+++ b/rust/flexbuffers/src/builder/value.rs
@@ -129,9 +129,10 @@
!self.is_inline()
}
pub fn is_key(&self) -> bool {
- match self {
- Value::Key(_) => true,
- _ => false,
+ if let Value::Key(_) = self {
+ true
+ } else {
+ false
}
}
pub fn is_typed_vector_or_map(&self) -> bool {
diff --git a/rust/flexbuffers/src/flexbuffer_type.rs b/rust/flexbuffers/src/flexbuffer_type.rs
index 5b57de8..eda5195 100644
--- a/rust/flexbuffers/src/flexbuffer_type.rs
+++ b/rust/flexbuffers/src/flexbuffer_type.rs
@@ -134,7 +134,7 @@
/// Returns true if called on a map, vector, typed vector, or fixed length typed vector.
pub fn is_vector(self) -> bool {
let d = self as u8;
- 9 <= d && d < 25 || self == VectorBool
+ (9..25).contains(&d) || self == VectorBool
}
/// True iff the binary format stores the length.
/// This applies to Blob, String, Maps, and Vectors of variable length.
diff --git a/rust/flexbuffers/src/lib.rs b/rust/flexbuffers/src/lib.rs
index 20983b7..2935190 100644
--- a/rust/flexbuffers/src/lib.rs
+++ b/rust/flexbuffers/src/lib.rs
@@ -28,6 +28,10 @@
// Serializable structs are Pushable
// Serde with maps - field names and type names.
+// Until flat/flexbuffers is on Rust v1.42, we cannot use the previously unstable matches! macro.
+#![allow(clippy::unknown_clippy_lints)]
+#![allow(clippy::match_like_matches_macro)]
+
#[macro_use]
extern crate bitflags;
extern crate byteorder;
@@ -37,10 +41,13 @@
extern crate serde;
mod bitwidth;
+mod buffer;
mod builder;
mod flexbuffer_type;
mod reader;
+
pub use bitwidth::BitWidth;
+pub use buffer::Buffer;
pub use builder::Error as SerializationError;
pub use builder::{
singleton, Builder, BuilderOptions, FlexbufferSerializer, MapBuilder, Pushable, VectorBuilder,
@@ -60,17 +67,32 @@
x.serialize(&mut s)?;
Ok(s.take_buffer())
}
+
/// Deserialize a type from a flexbuffer.
pub fn from_slice<'de, T: Deserialize<'de>>(buf: &'de [u8]) -> Result<T, DeserializationError> {
let r = Reader::get_root(buf)?;
T::deserialize(r)
}
+/// Deserialize a type from a flexbuffer.
+pub fn from_buffer<'de, T: Deserialize<'de>, B: Buffer>(
+ buf: &'de B,
+) -> Result<T, DeserializationError> {
+ let r = Reader::get_root(buf as &'de [u8])?;
+ T::deserialize(r)
+}
+
/// This struct, when pushed will be serialized as a `FlexBufferType::Blob`.
///
/// A `Blob` is a variable width `length` followed by that many bytes of data.
-#[derive(Debug, Copy, Clone, PartialEq, Eq)]
-pub struct Blob<'a>(pub &'a [u8]);
+#[derive(Debug, PartialEq, Eq)]
+pub struct Blob<B>(pub B);
+
+impl<B: Buffer> Clone for Blob<B> {
+ fn clone(&self) -> Self {
+ Blob(self.0.shallow_copy())
+ }
+}
/// This struct, when pushed, will be serialized as a `FlexBufferType::IndirectUInt`.
///
diff --git a/rust/flexbuffers/src/reader/de.rs b/rust/flexbuffers/src/reader/de.rs
index 8cc3b6e..ed2b815 100644
--- a/rust/flexbuffers/src/reader/de.rs
+++ b/rust/flexbuffers/src/reader/de.rs
@@ -35,6 +35,7 @@
}
}
}
+
impl serde::de::Error for DeserializationError {
fn custom<T>(msg: T) -> Self
where
@@ -43,14 +44,16 @@
Self::Serde(format!("{}", msg))
}
}
+
impl std::convert::From<super::Error> for DeserializationError {
fn from(e: super::Error) -> Self {
Self::Reader(e)
}
}
-impl<'de> SeqAccess<'de> for ReaderIterator<'de> {
+impl<'de> SeqAccess<'de> for ReaderIterator<&'de [u8]> {
type Error = DeserializationError;
+
fn next_element_seed<T>(
&mut self,
seed: T,
@@ -64,6 +67,7 @@
Ok(None)
}
}
+
fn size_hint(&self) -> Option<usize> {
Some(self.len())
}
@@ -71,12 +75,13 @@
struct EnumReader<'de> {
variant: &'de str,
- value: Option<Reader<'de>>,
+ value: Option<Reader<&'de [u8]>>,
}
impl<'de> EnumAccess<'de> for EnumReader<'de> {
type Error = DeserializationError;
- type Variant = Reader<'de>;
+ type Variant = Reader<&'de [u8]>;
+
fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error>
where
V: DeserializeSeed<'de>,
@@ -87,9 +92,10 @@
}
struct MapAccessor<'de> {
- keys: ReaderIterator<'de>,
- vals: ReaderIterator<'de>,
+ keys: ReaderIterator<&'de [u8]>,
+ vals: ReaderIterator<&'de [u8]>,
}
+
impl<'de> MapAccess<'de> for MapAccessor<'de> {
type Error = DeserializationError;
@@ -103,6 +109,7 @@
Ok(None)
}
}
+
fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error>
where
V: DeserializeSeed<'de>,
@@ -112,17 +119,20 @@
}
}
-impl<'de> VariantAccess<'de> for Reader<'de> {
+impl<'de> VariantAccess<'de> for Reader<&'de [u8]> {
type Error = DeserializationError;
+
fn unit_variant(self) -> Result<(), Self::Error> {
Ok(())
}
+
fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Self::Error>
where
T: DeserializeSeed<'de>,
{
seed.deserialize(self)
}
+
// Tuple variants have an internally tagged representation. They are vectors where Index 0 is
// the discriminant and index N is field N-1.
fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error>
@@ -131,6 +141,7 @@
{
visitor.visit_seq(self.as_vector().iter())
}
+
// Struct variants have an internally tagged representation. They are vectors where Index 0 is
// the discriminant and index N is field N-1.
fn struct_variant<V>(
@@ -149,7 +160,7 @@
}
}
-impl<'de> Deserializer<'de> for crate::Reader<'de> {
+impl<'de> Deserializer<'de> for Reader<&'de [u8]> {
type Error = DeserializationError;
fn is_human_readable(&self) -> bool {
cfg!(deserialize_human_readable)
@@ -188,22 +199,26 @@
(ty, bw) => unreachable!("TODO deserialize_any {:?} {:?}.", ty, bw),
}
}
+
serde::forward_to_deserialize_any! {
bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 str unit unit_struct bytes
ignored_any map identifier struct tuple tuple_struct seq string
}
+
fn deserialize_char<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
visitor.visit_char(self.as_u8() as char)
}
+
fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
visitor.visit_byte_buf(self.get_blob()?.0.to_vec())
}
+
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
@@ -214,6 +229,7 @@
visitor.visit_some(self)
}
}
+
fn deserialize_newtype_struct<V>(
self,
_name: &'static str,
@@ -224,6 +240,7 @@
{
visitor.visit_newtype_struct(self)
}
+
fn deserialize_enum<V>(
self,
_name: &'static str,
diff --git a/rust/flexbuffers/src/reader/iter.rs b/rust/flexbuffers/src/reader/iter.rs
index 8e06171..267a01f 100644
--- a/rust/flexbuffers/src/reader/iter.rs
+++ b/rust/flexbuffers/src/reader/iter.rs
@@ -12,19 +12,20 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-use super::{Reader, VectorReader};
+use crate::{Buffer, Reader, VectorReader};
use std::iter::{DoubleEndedIterator, ExactSizeIterator, FusedIterator, Iterator};
/// Iterates over a flexbuffer vector, typed vector, or map. Yields [Readers](struct.Reader.html).
///
/// If any error occurs, the Reader is defaulted to a Null flexbuffer Reader.
-pub struct ReaderIterator<'de> {
- pub(super) reader: VectorReader<'de>,
+pub struct ReaderIterator<B> {
+ pub(super) reader: VectorReader<B>,
pub(super) front: usize,
end: usize,
}
-impl<'de> ReaderIterator<'de> {
- pub(super) fn new(reader: VectorReader<'de>) -> Self {
+
+impl<B: Buffer> ReaderIterator<B> {
+ pub(super) fn new(reader: VectorReader<B>) -> Self {
let end = reader.len();
ReaderIterator {
reader,
@@ -33,8 +34,9 @@
}
}
}
-impl<'de> Iterator for ReaderIterator<'de> {
- type Item = Reader<'de>;
+
+impl<B: Buffer> Iterator for ReaderIterator<B> {
+ type Item = Reader<B>;
fn next(&mut self) -> Option<Self::Item> {
if self.front < self.end {
let r = self.reader.idx(self.front);
@@ -49,7 +51,8 @@
(remaining, Some(remaining))
}
}
-impl<'de> DoubleEndedIterator for ReaderIterator<'de> {
+
+impl<B: Buffer> DoubleEndedIterator for ReaderIterator<B> {
fn next_back(&mut self) -> Option<Self::Item> {
if self.front < self.end {
self.end -= 1;
@@ -59,5 +62,6 @@
}
}
}
-impl<'de> ExactSizeIterator for ReaderIterator<'de> {}
-impl<'de> FusedIterator for ReaderIterator<'de> {}
+
+impl<B: Buffer> ExactSizeIterator for ReaderIterator<B> {}
+impl<B: Buffer> FusedIterator for ReaderIterator<B> {}
diff --git a/rust/flexbuffers/src/reader/map.rs b/rust/flexbuffers/src/reader/map.rs
index cdf59e0..7d6ada8 100644
--- a/rust/flexbuffers/src/reader/map.rs
+++ b/rust/flexbuffers/src/reader/map.rs
@@ -14,6 +14,7 @@
use super::{deref_offset, unpack_type, Error, Reader, ReaderIterator, VectorReader};
use crate::BitWidth;
+use crate::Buffer;
use std::cmp::Ordering;
use std::iter::{DoubleEndedIterator, ExactSizeIterator, FusedIterator, Iterator};
@@ -22,9 +23,8 @@
/// MapReaders may be indexed with strings or usizes. `index` returns a result type,
/// which may indicate failure due to a missing key or bad data, `idx` returns an Null Reader in
/// cases of error.
-#[derive(Default, Clone)]
-pub struct MapReader<'de> {
- pub(super) buffer: &'de [u8],
+pub struct MapReader<B> {
+ pub(super) buffer: B,
pub(super) values_address: usize,
pub(super) keys_address: usize,
pub(super) values_width: BitWidth,
@@ -32,8 +32,30 @@
pub(super) length: usize,
}
+impl<B: Buffer> Clone for MapReader<B> {
+ fn clone(&self) -> Self {
+ MapReader {
+ buffer: self.buffer.shallow_copy(),
+ ..*self
+ }
+ }
+}
+
+impl<B: Buffer> Default for MapReader<B> {
+ fn default() -> Self {
+ MapReader {
+ buffer: B::empty(),
+ values_address: usize::default(),
+ keys_address: usize::default(),
+ values_width: BitWidth::default(),
+ keys_width: BitWidth::default(),
+ length: usize::default(),
+ }
+ }
+}
+
// manual implementation of Debug because buffer slice can't be automatically displayed
-impl<'de> std::fmt::Debug for MapReader<'de> {
+impl<B: Buffer> std::fmt::Debug for MapReader<B> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// skips buffer field
f.debug_struct("MapReader")
@@ -46,15 +68,17 @@
}
}
-impl<'de> MapReader<'de> {
+impl<B: Buffer> MapReader<B> {
/// Returns the number of key/value pairs are in the map.
pub fn len(&self) -> usize {
self.length
}
+
/// Returns true if the map has zero key/value pairs.
pub fn is_empty(&self) -> bool {
self.length == 0
}
+
// Using &CStr will eagerly compute the length of the key. &str needs length info AND utf8
// validation. This version is faster than both.
fn lazy_strcmp(&self, key_addr: usize, key: &str) -> Ordering {
@@ -62,6 +86,7 @@
let k = self.buffer[key_addr..].iter().take_while(|&&b| b != b'\0');
k.cmp(key.as_bytes().iter())
}
+
/// Returns the index of a given key in the map.
pub fn index_key(&self, key: &str) -> Option<usize> {
let (mut low, mut high) = (0, self.length);
@@ -69,7 +94,7 @@
let i = (low + high) / 2;
let key_offset_address = self.keys_address + i * self.keys_width.n_bytes();
let key_address =
- deref_offset(self.buffer, key_offset_address, self.keys_width).ok()?;
+ deref_offset(&self.buffer, key_offset_address, self.keys_width).ok()?;
match self.lazy_strcmp(key_address, key) {
Ordering::Equal => return Some(i),
Ordering::Less => low = if i == low { i + 1 } else { i },
@@ -78,15 +103,18 @@
}
None
}
+
/// Index into a map with a key or usize.
- pub fn index<I: MapReaderIndexer>(&self, i: I) -> Result<Reader<'de>, Error> {
+ pub fn index<I: MapReaderIndexer>(&self, i: I) -> Result<Reader<B>, Error> {
i.index_map_reader(self)
}
+
/// Index into a map with a key or usize. If any errors occur a Null reader is returned.
- pub fn idx<I: MapReaderIndexer>(&self, i: I) -> Reader<'de> {
+ pub fn idx<I: MapReaderIndexer>(&self, i: I) -> Reader<B> {
i.index_map_reader(self).unwrap_or_default()
}
- fn usize_index(&self, i: usize) -> Result<Reader<'de>, Error> {
+
+ fn usize_index(&self, i: usize) -> Result<Reader<B>, Error> {
if i >= self.length {
return Err(Error::IndexOutOfBounds);
}
@@ -98,22 +126,24 @@
.ok_or(Error::FlexbufferOutOfBounds)
.and_then(|&b| unpack_type(b))?;
Reader::new(
- &self.buffer,
+ self.buffer.shallow_copy(),
data_address,
fxb_type,
width,
self.values_width,
)
}
- fn key_index(&self, k: &str) -> Result<Reader<'de>, Error> {
+
+ fn key_index(&self, k: &str) -> Result<Reader<B>, Error> {
let i = self.index_key(k).ok_or(Error::KeyNotFound)?;
self.usize_index(i)
}
+
/// Iterate over the values of the map.
- pub fn iter_values(&self) -> ReaderIterator<'de> {
+ pub fn iter_values(&self) -> ReaderIterator<B> {
ReaderIterator::new(VectorReader {
reader: Reader {
- buffer: self.buffer,
+ buffer: self.buffer.shallow_copy(),
fxb_type: crate::FlexBufferType::Map,
width: self.values_width,
address: self.values_address,
@@ -121,17 +151,19 @@
length: self.length,
})
}
+
/// Iterate over the keys of the map.
pub fn iter_keys(
&self,
- ) -> impl Iterator<Item = &'de str> + DoubleEndedIterator + ExactSizeIterator + FusedIterator
+ ) -> impl Iterator<Item = B::BufferString> + DoubleEndedIterator + ExactSizeIterator + FusedIterator
{
self.keys_vector().iter().map(|k| k.as_str())
}
- pub fn keys_vector(&self) -> VectorReader<'de> {
+
+ pub fn keys_vector(&self) -> VectorReader<B> {
VectorReader {
reader: Reader {
- buffer: self.buffer,
+ buffer: self.buffer.shallow_copy(),
fxb_type: crate::FlexBufferType::VectorKey,
width: self.keys_width,
address: self.keys_address,
@@ -140,18 +172,21 @@
}
}
}
+
pub trait MapReaderIndexer {
- fn index_map_reader<'de>(self, r: &MapReader<'de>) -> Result<Reader<'de>, Error>;
+ fn index_map_reader<B: Buffer>(self, r: &MapReader<B>) -> Result<Reader<B>, Error>;
}
+
impl MapReaderIndexer for usize {
#[inline]
- fn index_map_reader<'de>(self, r: &MapReader<'de>) -> Result<Reader<'de>, Error> {
+ fn index_map_reader<B: Buffer>(self, r: &MapReader<B>) -> Result<Reader<B>, Error> {
r.usize_index(self)
}
}
+
impl MapReaderIndexer for &str {
#[inline]
- fn index_map_reader<'de>(self, r: &MapReader<'de>) -> Result<Reader<'de>, Error> {
+ fn index_map_reader<B: Buffer>(self, r: &MapReader<B>) -> Result<Reader<B>, Error> {
r.key_index(self)
}
}
diff --git a/rust/flexbuffers/src/reader/mod.rs b/rust/flexbuffers/src/reader/mod.rs
index 4a3f472..c6f51d0 100644
--- a/rust/flexbuffers/src/reader/mod.rs
+++ b/rust/flexbuffers/src/reader/mod.rs
@@ -14,7 +14,7 @@
use crate::bitwidth::BitWidth;
use crate::flexbuffer_type::FlexBufferType;
-use crate::Blob;
+use crate::{Blob, Buffer};
use std::convert::{TryFrom, TryInto};
use std::fmt;
use std::ops::Rem;
@@ -22,6 +22,7 @@
mod de;
mod iter;
mod map;
+mod serialize;
mod vector;
pub use de::DeserializationError;
pub use iter::ReaderIterator;
@@ -143,16 +144,37 @@
/// - The `as_T` methods will try their best to return to a value of type `T`
/// (by casting or even parsing a string if necessary) but ultimately returns `T::default` if it
/// fails. This behavior is analogous to that of flexbuffers C++.
-#[derive(Default, Clone)]
-pub struct Reader<'de> {
+pub struct Reader<B> {
fxb_type: FlexBufferType,
width: BitWidth,
address: usize,
- buffer: &'de [u8],
+ buffer: B,
+}
+
+impl<B: Buffer> Clone for Reader<B> {
+ fn clone(&self) -> Self {
+ Reader {
+ fxb_type: self.fxb_type,
+ width: self.width,
+ address: self.address,
+ buffer: self.buffer.shallow_copy(),
+ }
+ }
+}
+
+impl<B: Buffer> Default for Reader<B> {
+ fn default() -> Self {
+ Reader {
+ fxb_type: FlexBufferType::default(),
+ width: BitWidth::default(),
+ address: usize::default(),
+ buffer: B::empty(),
+ }
+ }
}
// manual implementation of Debug because buffer slice can't be automatically displayed
-impl<'de> std::fmt::Debug for Reader<'de> {
+impl<B> std::fmt::Debug for Reader<B> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// skips buffer field
f.debug_struct("Reader")
@@ -163,13 +185,12 @@
}
}
-
macro_rules! try_cast_fn {
($name: ident, $full_width: ident, $Ty: ident) => {
pub fn $name(&self) -> $Ty {
self.$full_width().try_into().unwrap_or_default()
}
- }
+ };
}
fn safe_sub(a: usize, b: usize) -> Result<usize, Error> {
@@ -181,16 +202,16 @@
safe_sub(address, off)
}
-impl<'de> Reader<'de> {
+impl<B: Buffer> Reader<B> {
fn new(
- buffer: &'de [u8],
+ buffer: B,
mut address: usize,
mut fxb_type: FlexBufferType,
width: BitWidth,
parent_width: BitWidth,
) -> Result<Self, Error> {
if fxb_type.is_reference() {
- address = deref_offset(buffer, address, parent_width)?;
+ address = deref_offset(&buffer, address, parent_width)?;
// Indirects were dereferenced.
if let Some(t) = fxb_type.to_direct() {
fxb_type = t;
@@ -203,9 +224,10 @@
buffer,
})
}
+
/// Parses the flexbuffer from the given buffer. Assumes the flexbuffer root is the last byte
/// of the buffer.
- pub fn get_root(buffer: &'de [u8]) -> Result<Self, Error> {
+ pub fn get_root(buffer: B) -> Result<Self, Error> {
let end = buffer.len();
if end < 3 {
return Err(Error::FlexbufferOutOfBounds);
@@ -218,21 +240,34 @@
let address = safe_sub(end - 2, root_width.n_bytes())?;
Self::new(buffer, address, fxb_type, width, root_width)
}
+
+ /// Convenience function to get the underlying buffer. By using `shallow_copy`, this preserves
+ /// the lifetime that the underlying buffer has.
+ pub fn buffer(&self) -> B {
+ self.buffer.shallow_copy()
+ }
+
/// Returns the FlexBufferType of this Reader.
pub fn flexbuffer_type(&self) -> FlexBufferType {
self.fxb_type
}
+
/// Returns the bitwidth of this Reader.
pub fn bitwidth(&self) -> BitWidth {
self.width
}
+
/// Returns the length of the Flexbuffer. If the type has no length, or if an error occurs,
/// 0 is returned.
pub fn length(&self) -> usize {
if let Some(len) = self.fxb_type.fixed_length_vector_length() {
len
} else if self.fxb_type.has_length_slot() && self.address >= self.width.n_bytes() {
- read_usize(self.buffer, self.address - self.width.n_bytes(), self.width)
+ read_usize(
+ &self.buffer,
+ self.address - self.width.n_bytes(),
+ self.width,
+ )
} else {
0
}
@@ -240,11 +275,13 @@
/// Returns true if the flexbuffer is aligned to 8 bytes. This guarantees, for valid
/// flexbuffers, that the data is correctly aligned in memory and slices can be read directly
/// e.g. with `get_f64s` or `get_i16s`.
+ #[inline]
pub fn is_aligned(&self) -> bool {
(self.buffer.as_ptr() as usize).rem(8) == 0
}
- as_default!(as_vector, get_vector, VectorReader<'de>);
- as_default!(as_map, get_map, MapReader<'de>);
+
+ as_default!(as_vector, get_vector, VectorReader<B>);
+ as_default!(as_map, get_map, MapReader<B>);
fn expect_type(&self, ty: FlexBufferType) -> Result<(), Error> {
if self.fxb_type == ty {
@@ -266,11 +303,16 @@
})
}
}
- /// Directly reads a slice of type `T`where `T` is one of `u8,u16,u32,u64,i8,i16,i32,i64,f32,f64`.
+
+ /// Directly reads a slice of type `T` where `T` is one of `u8,u16,u32,u64,i8,i16,i32,i64,f32,f64`.
/// Returns Err if the type, bitwidth, or memory alignment does not match. Since the bitwidth is
/// dynamic, its better to use a VectorReader unless you know your data and performance is critical.
#[cfg(target_endian = "little")]
- pub fn get_slice<T: ReadLE>(&self) -> Result<&'de [T], Error> {
+ #[deprecated(
+ since = "0.3.0",
+ note = "This function is unsafe - if this functionality is needed use `Reader::buffer::align_to`"
+ )]
+ pub fn get_slice<T: ReadLE>(&self) -> Result<&[T], Error> {
if self.flexbuffer_type().typed_vector_type() != T::VECTOR_TYPE.typed_vector_type() {
self.expect_type(T::VECTOR_TYPE)?;
}
@@ -278,10 +320,11 @@
self.expect_bw(T::WIDTH)?;
}
let end = self.address + self.length() * std::mem::size_of::<T>();
- let slice = &self
+ let slice: &[u8] = self
.buffer
.get(self.address..end)
.ok_or(Error::FlexbufferOutOfBounds)?;
+
// `align_to` is required because the point of this function is to directly hand back a
// slice of scalars. This can fail because Rust's default allocator is not 16byte aligned
// (though in practice this only happens for small buffers).
@@ -293,6 +336,8 @@
}
}
+ /// Returns the value of the reader if it is a boolean.
+ /// Otherwise Returns error.
pub fn get_bool(&self) -> Result<bool, Error> {
self.expect_type(FlexBufferType::Bool)?;
Ok(
@@ -301,30 +346,53 @@
.any(|&b| b != 0),
)
}
- pub fn get_key(&self) -> Result<&'de str, Error> {
+
+ /// Gets the length of the key if this type is a key.
+ ///
+ /// Otherwise, returns an error.
+ #[inline]
+ fn get_key_len(&self) -> Result<usize, Error> {
self.expect_type(FlexBufferType::Key)?;
let (length, _) = self.buffer[self.address..]
.iter()
.enumerate()
.find(|(_, &b)| b == b'\0')
.unwrap_or((0, &0));
- let bytes = &self.buffer[self.address..self.address + length];
- Ok(std::str::from_utf8(bytes)?)
+ Ok(length)
}
- pub fn get_blob(&self) -> Result<Blob<'de>, Error> {
+
+ /// Retrieves the string value up until the first `\0` character.
+ pub fn get_key(&self) -> Result<B::BufferString, Error> {
+ let bytes = self
+ .buffer
+ .slice(self.address..self.address + self.get_key_len()?)
+ .ok_or(Error::IndexOutOfBounds)?;
+ Ok(bytes.buffer_str()?)
+ }
+
+ pub fn get_blob(&self) -> Result<Blob<B>, Error> {
self.expect_type(FlexBufferType::Blob)?;
Ok(Blob(
- &self.buffer[self.address..self.address + self.length()],
+ self.buffer
+ .slice(self.address..self.address + self.length())
+ .ok_or(Error::IndexOutOfBounds)?,
))
}
- pub fn as_blob(&self) -> Blob<'de> {
- self.get_blob().unwrap_or(Blob(&[]))
+
+ pub fn as_blob(&self) -> Blob<B> {
+ self.get_blob().unwrap_or(Blob(B::empty()))
}
- pub fn get_str(&self) -> Result<&'de str, Error> {
+
+ /// Retrieves str pointer, errors if invalid UTF-8, or the provided index
+ /// is out of bounds.
+ pub fn get_str(&self) -> Result<B::BufferString, Error> {
self.expect_type(FlexBufferType::String)?;
- let bytes = &self.buffer[self.address..self.address + self.length()];
- Ok(std::str::from_utf8(bytes)?)
+ let bytes = self
+ .buffer
+ .slice(self.address..self.address + self.length());
+ Ok(bytes.ok_or(Error::ReadUsizeOverflowed)?.buffer_str()?)
}
+
fn get_map_info(&self) -> Result<(usize, BitWidth), Error> {
self.expect_type(FlexBufferType::Map)?;
if 3 * self.width.n_bytes() >= self.address {
@@ -333,17 +401,18 @@
let keys_offset_address = self.address - 3 * self.width.n_bytes();
let keys_width = {
let kw_addr = self.address - 2 * self.width.n_bytes();
- let kw = read_usize(self.buffer, kw_addr, self.width);
+ let kw = read_usize(&self.buffer, kw_addr, self.width);
BitWidth::from_nbytes(kw).ok_or(Error::InvalidMapKeysVectorWidth)
}?;
Ok((keys_offset_address, keys_width))
}
- pub fn get_map(&self) -> Result<MapReader<'de>, Error> {
+
+ pub fn get_map(&self) -> Result<MapReader<B>, Error> {
let (keys_offset_address, keys_width) = self.get_map_info()?;
- let keys_address = deref_offset(self.buffer, keys_offset_address, self.width)?;
+ let keys_address = deref_offset(&self.buffer, keys_offset_address, self.width)?;
// TODO(cneo): Check that vectors length equals keys length.
Ok(MapReader {
- buffer: self.buffer,
+ buffer: self.buffer.shallow_copy(),
values_address: self.address,
values_width: self.width,
keys_address,
@@ -351,6 +420,7 @@
length: self.length(),
})
}
+
/// Tries to read a FlexBufferType::UInt. Returns Err if the type is not a UInt or if the
/// address is out of bounds.
pub fn get_u64(&self) -> Result<u64, Error> {
@@ -443,7 +513,7 @@
FlexBufferType::Float => self.get_f64().unwrap_or_default() as u64,
FlexBufferType::String => {
if let Ok(s) = self.get_str() {
- if let Ok(f) = u64::from_str(s) {
+ if let Ok(f) = u64::from_str(&s) {
return f;
}
}
@@ -470,7 +540,7 @@
FlexBufferType::Float => self.get_f64().unwrap_or_default() as i64,
FlexBufferType::String => {
if let Ok(s) = self.get_str() {
- if let Ok(f) = i64::from_str(s) {
+ if let Ok(f) = i64::from_str(&s) {
return f;
}
}
@@ -493,7 +563,7 @@
FlexBufferType::Float => self.get_f64().unwrap_or_default(),
FlexBufferType::String => {
if let Ok(s) = self.get_str() {
- if let Ok(f) = f64::from_str(s) {
+ if let Ok(f) = f64::from_str(&s) {
return f;
}
}
@@ -508,14 +578,15 @@
}
/// Returns empty string if you're not trying to read a string.
- pub fn as_str(&self) -> &'de str {
+ pub fn as_str(&self) -> B::BufferString {
match self.fxb_type {
- FlexBufferType::String => self.get_str().unwrap_or_default(),
- FlexBufferType::Key => self.get_key().unwrap_or_default(),
- _ => "",
+ FlexBufferType::String => self.get_str().unwrap_or(B::empty_str()),
+ FlexBufferType::Key => self.get_key().unwrap_or(B::empty_str()),
+ _ => B::empty_str(),
}
}
- pub fn get_vector(&self) -> Result<VectorReader<'de>, Error> {
+
+ pub fn get_vector(&self) -> Result<VectorReader<B>, Error> {
if !self.fxb_type.is_vector() {
self.expect_type(FlexBufferType::Vector)?;
};
@@ -526,7 +597,7 @@
}
}
-impl<'de> fmt::Display for Reader<'de> {
+impl<B: Buffer> fmt::Display for Reader<B> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use FlexBufferType::*;
match self.flexbuffer_type() {
@@ -534,7 +605,7 @@
UInt => write!(f, "{}", self.as_u64()),
Int => write!(f, "{}", self.as_i64()),
Float => write!(f, "{}", self.as_f64()),
- Key | String => write!(f, "{:?}", self.as_str()),
+ Key | String => write!(f, "{:?}", &self.as_str() as &str),
Bool => write!(f, "{}", self.as_bool()),
Blob => write!(f, "blob"),
Map => {
@@ -542,9 +613,9 @@
let m = self.as_map();
let mut pairs = m.iter_keys().zip(m.iter_values());
if let Some((k, v)) = pairs.next() {
- write!(f, "{:?}: {}", k, v)?;
+ write!(f, "{:?}: {}", &k as &str, v)?;
for (k, v) in pairs {
- write!(f, ", {:?}: {}", k, v)?;
+ write!(f, ", {:?}: {}", &k as &str, v)?;
}
}
write!(f, "}}")
@@ -570,6 +641,7 @@
let bits = <u32>::from_le_bytes(bytes);
<f32>::from_bits(bits)
}
+
fn f64_from_le_bytes(bytes: [u8; 8]) -> f64 {
let bits = <u64>::from_le_bytes(bytes);
<f64>::from_bits(bits)
diff --git a/rust/flexbuffers/src/reader/serialize.rs b/rust/flexbuffers/src/reader/serialize.rs
new file mode 100644
index 0000000..b129da1
--- /dev/null
+++ b/rust/flexbuffers/src/reader/serialize.rs
@@ -0,0 +1,76 @@
+// Copyright 2021 Google LLC
+//
+// 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
+//
+// https://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.
+
+use crate::reader::Reader;
+use crate::Buffer;
+use crate::{BitWidth::*, FlexBufferType::*};
+use serde::ser;
+use serde::ser::{SerializeMap, SerializeSeq};
+
+impl<B: Buffer> ser::Serialize for &Reader<B> {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: ser::Serializer,
+ {
+ #[allow(deprecated)]
+ match (self.flexbuffer_type(), self.bitwidth()) {
+ (Null, _) => serializer.serialize_unit(),
+ (Int, W8) | (IndirectInt, W8) => serializer.serialize_i8(self.as_i8()),
+ (Int, W16) | (IndirectInt, W16) => serializer.serialize_i16(self.as_i16()),
+ (Int, W32) | (IndirectInt, W32) => serializer.serialize_i32(self.as_i32()),
+ (Int, W64) | (IndirectInt, W64) => serializer.serialize_i64(self.as_i64()),
+ (UInt, W8) | (IndirectUInt, W8) => serializer.serialize_u8(self.as_u8()),
+ (UInt, W16) | (IndirectUInt, W16) => serializer.serialize_u16(self.as_u16()),
+ (UInt, W32) | (IndirectUInt, W32) => serializer.serialize_u32(self.as_u32()),
+ (UInt, W64) | (IndirectUInt, W64) => serializer.serialize_u64(self.as_u64()),
+ (Float, W32) | (IndirectFloat, W32) => serializer.serialize_f32(self.as_f32()),
+ (Float, _) | (IndirectFloat, _) => serializer.serialize_f64(self.as_f64()),
+ (Bool, _) => serializer.serialize_bool(self.as_bool()),
+ (Key, _) | (String, _) => serializer.serialize_str(&self.as_str()),
+ (Map, _) => {
+ let m = self.as_map();
+ let mut map_serializer = serializer.serialize_map(Some(m.len()))?;
+ for (k, v) in m.iter_keys().zip(m.iter_values()) {
+ map_serializer.serialize_key(&&k)?;
+ map_serializer.serialize_value(&&v)?;
+ }
+ map_serializer.end()
+ }
+ (Vector, _)
+ | (VectorInt, _)
+ | (VectorUInt, _)
+ | (VectorFloat, _)
+ | (VectorKey, _)
+ | (VectorString, _)
+ | (VectorBool, _)
+ | (VectorInt2, _)
+ | (VectorUInt2, _)
+ | (VectorFloat2, _)
+ | (VectorInt3, _)
+ | (VectorUInt3, _)
+ | (VectorFloat3, _)
+ | (VectorInt4, _)
+ | (VectorUInt4, _)
+ | (VectorFloat4, _) => {
+ let v = self.as_vector();
+ let mut seq_serializer = serializer.serialize_seq(Some(v.len()))?;
+ for x in v.iter() {
+ seq_serializer.serialize_element(&&x)?;
+ }
+ seq_serializer.end()
+ }
+ (Blob, _) => serializer.serialize_bytes(&self.as_blob().0),
+ }
+ }
+}
diff --git a/rust/flexbuffers/src/reader/vector.rs b/rust/flexbuffers/src/reader/vector.rs
index 8ba8fe5..6b97e10 100644
--- a/rust/flexbuffers/src/reader/vector.rs
+++ b/rust/flexbuffers/src/reader/vector.rs
@@ -13,22 +13,39 @@
// limitations under the License.
use super::{unpack_type, Error, Reader, ReaderIterator};
-use crate::{BitWidth, FlexBufferType};
+use crate::{BitWidth, Buffer, FlexBufferType};
-#[derive(Default, Clone)]
/// Allows indexing on any flexbuffer vector type, (heterogenous vector, typed vector, or fixed
/// length typed vector).
///
/// VectorReaders may be indexed with usize, `index` returns a result type
/// which may indicate failure due to indexing out of bounds or bad data. `idx` returns a
/// Null Reader in the event of any failure.
-pub struct VectorReader<'de> {
- pub(super) reader: Reader<'de>,
+pub struct VectorReader<B> {
+ pub(super) reader: Reader<B>,
// Cache the length because read_usize can be slow.
pub(super) length: usize,
}
-impl<'de> VectorReader<'de> {
+impl<B: Buffer> Clone for VectorReader<B> {
+ fn clone(&self) -> Self {
+ VectorReader {
+ reader: self.reader.clone(),
+ ..*self
+ }
+ }
+}
+
+impl<B: Buffer> Default for VectorReader<B> {
+ fn default() -> Self {
+ VectorReader {
+ reader: Reader::default(),
+ length: usize::default(),
+ }
+ }
+}
+
+impl<B: Buffer> VectorReader<B> {
/// Returns the number of elements in the vector.
pub fn len(&self) -> usize {
self.length
@@ -50,25 +67,26 @@
}
}
/// Index into a flexbuffer vector. Any errors are defaulted to Null Readers.
- pub fn idx(&self, i: usize) -> Reader<'de> {
+ pub fn idx(&self, i: usize) -> Reader<B> {
self.index(i).unwrap_or_default()
}
/// Index into a flexbuffer.
- pub fn index(&self, i: usize) -> Result<Reader<'de>, Error> {
+ pub fn index(&self, i: usize) -> Result<Reader<B>, Error> {
if i >= self.length {
return Err(Error::IndexOutOfBounds);
}
let (fxb_type, bw) = self.get_elem_type(i)?;
let data_address = self.reader.address + self.reader.width.n_bytes() * i;
Reader::new(
- self.reader.buffer,
+ self.reader.buffer.shallow_copy(),
data_address,
fxb_type,
bw,
self.reader.width,
)
}
- pub fn iter(&self) -> ReaderIterator<'de> {
+
+ pub fn iter(&self) -> ReaderIterator<B> {
ReaderIterator::new(self.clone())
}
}
diff --git a/samples/dart_sample.sh b/samples/dart_sample.sh
index 5616066..4032679 100755
--- a/samples/dart_sample.sh
+++ b/samples/dart_sample.sh
@@ -1,4 +1,5 @@
#!/bin/bash
+set -euo
#
# Copyright 2018 Dan Field. All rights reserved.
#
@@ -27,14 +28,12 @@
exit 1
fi
-cd ../dart/example
-
# Run `flatc`. Note: This requires you to compile using `cmake` from the
# root `/flatbuffers` directory.
-if [ -e ../../flatc ]; then
- ../../flatc --dart ../../samples/monster.fbs
-elif [ -e ../../Debug/flatc ]; then
- ../../Debug/flatc --dart ../../samples/monster.fbs
+if [ -e ../flatc ]; then
+ ../flatc --dart -o ../dart/example/ monster.fbs
+elif [ -e ../Debug/flatc ]; then
+ ../Debug/flatc --dart -o ../dart/example/ monster.fbs
else
echo 'flatc' could not be found. Make sure to build FlatBuffers from the \
$rootdir directory.
@@ -44,9 +43,7 @@
echo Running the Dart sample.
# Execute the sample.
-dart example.dart
+dart ../dart/example/example.dart
-# Cleanup temporary files.
-git checkout monster_my_game.sample_generated.dart
-
-cd ../../samples
+# Copy the source schema so it is distributed when published to pub.dev
+cp monster.fbs ../dart/example/
\ No newline at end of file
diff --git a/samples/monster.bfbs b/samples/monster.bfbs
index 7e1790c..99a93f5 100644
--- a/samples/monster.bfbs
+++ b/samples/monster.bfbs
Binary files differ
diff --git a/samples/monster_generated.h b/samples/monster_generated.h
index 8afde1e..5eef0f2 100644
--- a/samples/monster_generated.h
+++ b/samples/monster_generated.h
@@ -32,7 +32,7 @@
inline const flatbuffers::TypeTable *WeaponTypeTable();
-enum Color {
+enum Color : int8_t {
Color_Red = 0,
Color_Green = 1,
Color_Blue = 2,
@@ -65,7 +65,7 @@
return EnumNamesColor()[index];
}
-enum Equipment {
+enum Equipment : uint8_t {
Equipment_NONE = 0,
Equipment_Weapon = 1,
Equipment_MIN = Equipment_NONE,
@@ -103,6 +103,14 @@
static const Equipment enum_value = Equipment_Weapon;
};
+template<typename T> struct EquipmentUnionTraits {
+ static const Equipment enum_value = Equipment_NONE;
+};
+
+template<> struct EquipmentUnionTraits<MyGame::Sample::WeaponT> {
+ static const Equipment enum_value = Equipment_Weapon;
+};
+
struct EquipmentUnion {
Equipment type;
void *value;
@@ -120,17 +128,15 @@
void Reset();
-#ifndef FLATBUFFERS_CPP98_STL
template <typename T>
void Set(T&& val) {
- using RT = typename std::remove_reference<T>::type;
+ typedef typename std::remove_reference<T>::type RT;
Reset();
- type = EquipmentTraits<typename RT::TableType>::enum_value;
+ type = EquipmentUnionTraits<RT>::enum_value;
if (type != Equipment_NONE) {
value = new RT(std::forward<T>(val));
}
}
-#endif // FLATBUFFERS_CPP98_STL
static void *UnPack(const void *obj, Equipment type, const flatbuffers::resolver_function_t *resolver);
flatbuffers::Offset<void> Pack(flatbuffers::FlatBufferBuilder &_fbb, const flatbuffers::rehasher_function_t *_rehasher = nullptr) const;
@@ -224,40 +230,21 @@
struct MonsterT : public flatbuffers::NativeTable {
typedef Monster TableType;
- flatbuffers::unique_ptr<MyGame::Sample::Vec3> pos;
- int16_t mana;
- int16_t hp;
- std::string name;
- std::vector<uint8_t> inventory;
- MyGame::Sample::Color color;
- std::vector<flatbuffers::unique_ptr<MyGame::Sample::WeaponT>> weapons;
- MyGame::Sample::EquipmentUnion equipped;
- std::vector<MyGame::Sample::Vec3> path;
- MonsterT()
- : mana(150),
- hp(100),
- color(MyGame::Sample::Color_Blue) {
- }
+ flatbuffers::unique_ptr<MyGame::Sample::Vec3> pos{};
+ int16_t mana = 150;
+ int16_t hp = 100;
+ std::string name{};
+ std::vector<uint8_t> inventory{};
+ MyGame::Sample::Color color = MyGame::Sample::Color_Blue;
+ std::vector<flatbuffers::unique_ptr<MyGame::Sample::WeaponT>> weapons{};
+ MyGame::Sample::EquipmentUnion equipped{};
+ std::vector<MyGame::Sample::Vec3> path{};
+ MonsterT() = default;
+ MonsterT(const MonsterT &o);
+ MonsterT(MonsterT&&) FLATBUFFERS_NOEXCEPT = default;
+ MonsterT &operator=(MonsterT o) FLATBUFFERS_NOEXCEPT;
};
-inline bool operator==(const MonsterT &lhs, const MonsterT &rhs) {
- return
- (lhs.pos == rhs.pos) &&
- (lhs.mana == rhs.mana) &&
- (lhs.hp == rhs.hp) &&
- (lhs.name == rhs.name) &&
- (lhs.inventory == rhs.inventory) &&
- (lhs.color == rhs.color) &&
- (lhs.weapons == rhs.weapons) &&
- (lhs.equipped == rhs.equipped) &&
- (lhs.path == rhs.path);
-}
-
-inline bool operator!=(const MonsterT &lhs, const MonsterT &rhs) {
- return !(lhs == rhs);
-}
-
-
struct Monster FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
typedef MonsterT NativeTableType;
typedef MonsterBuilder Builder;
@@ -285,13 +272,13 @@
int16_t mana() const {
return GetField<int16_t>(VT_MANA, 150);
}
- bool mutate_mana(int16_t _mana) {
+ bool mutate_mana(int16_t _mana = 150) {
return SetField<int16_t>(VT_MANA, _mana, 150);
}
int16_t hp() const {
return GetField<int16_t>(VT_HP, 100);
}
- bool mutate_hp(int16_t _hp) {
+ bool mutate_hp(int16_t _hp = 100) {
return SetField<int16_t>(VT_HP, _hp, 100);
}
const flatbuffers::String *name() const {
@@ -309,7 +296,7 @@
MyGame::Sample::Color color() const {
return static_cast<MyGame::Sample::Color>(GetField<int8_t>(VT_COLOR, 2));
}
- bool mutate_color(MyGame::Sample::Color _color) {
+ bool mutate_color(MyGame::Sample::Color _color = static_cast<MyGame::Sample::Color>(2)) {
return SetField<int8_t>(VT_COLOR, static_cast<int8_t>(_color), 2);
}
const flatbuffers::Vector<flatbuffers::Offset<MyGame::Sample::Weapon>> *weapons() const {
@@ -339,18 +326,18 @@
}
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
- VerifyField<MyGame::Sample::Vec3>(verifier, VT_POS) &&
- VerifyField<int16_t>(verifier, VT_MANA) &&
- VerifyField<int16_t>(verifier, VT_HP) &&
+ VerifyField<MyGame::Sample::Vec3>(verifier, VT_POS, 4) &&
+ VerifyField<int16_t>(verifier, VT_MANA, 2) &&
+ VerifyField<int16_t>(verifier, VT_HP, 2) &&
VerifyOffset(verifier, VT_NAME) &&
verifier.VerifyString(name()) &&
VerifyOffset(verifier, VT_INVENTORY) &&
verifier.VerifyVector(inventory()) &&
- VerifyField<int8_t>(verifier, VT_COLOR) &&
+ VerifyField<int8_t>(verifier, VT_COLOR, 1) &&
VerifyOffset(verifier, VT_WEAPONS) &&
verifier.VerifyVector(weapons()) &&
verifier.VerifyVectorOfTables(weapons()) &&
- VerifyField<uint8_t>(verifier, VT_EQUIPPED_TYPE) &&
+ VerifyField<uint8_t>(verifier, VT_EQUIPPED_TYPE, 1) &&
VerifyOffset(verifier, VT_EQUIPPED) &&
VerifyEquipment(verifier, equipped(), equipped_type()) &&
VerifyOffset(verifier, VT_PATH) &&
@@ -413,7 +400,7 @@
inline flatbuffers::Offset<Monster> CreateMonster(
flatbuffers::FlatBufferBuilder &_fbb,
- const MyGame::Sample::Vec3 *pos = 0,
+ const MyGame::Sample::Vec3 *pos = nullptr,
int16_t mana = 150,
int16_t hp = 100,
flatbuffers::Offset<flatbuffers::String> name = 0,
@@ -439,7 +426,7 @@
inline flatbuffers::Offset<Monster> CreateMonsterDirect(
flatbuffers::FlatBufferBuilder &_fbb,
- const MyGame::Sample::Vec3 *pos = 0,
+ const MyGame::Sample::Vec3 *pos = nullptr,
int16_t mana = 150,
int16_t hp = 100,
const char *name = nullptr,
@@ -471,24 +458,10 @@
struct WeaponT : public flatbuffers::NativeTable {
typedef Weapon TableType;
- std::string name;
- int16_t damage;
- WeaponT()
- : damage(0) {
- }
+ std::string name{};
+ int16_t damage = 0;
};
-inline bool operator==(const WeaponT &lhs, const WeaponT &rhs) {
- return
- (lhs.name == rhs.name) &&
- (lhs.damage == rhs.damage);
-}
-
-inline bool operator!=(const WeaponT &lhs, const WeaponT &rhs) {
- return !(lhs == rhs);
-}
-
-
struct Weapon FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
typedef WeaponT NativeTableType;
typedef WeaponBuilder Builder;
@@ -508,14 +481,14 @@
int16_t damage() const {
return GetField<int16_t>(VT_DAMAGE, 0);
}
- bool mutate_damage(int16_t _damage) {
+ bool mutate_damage(int16_t _damage = 0) {
return SetField<int16_t>(VT_DAMAGE, _damage, 0);
}
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
VerifyOffset(verifier, VT_NAME) &&
verifier.VerifyString(name()) &&
- VerifyField<int16_t>(verifier, VT_DAMAGE) &&
+ VerifyField<int16_t>(verifier, VT_DAMAGE, 2) &&
verifier.EndTable();
}
WeaponT *UnPack(const flatbuffers::resolver_function_t *_resolver = nullptr) const;
@@ -567,8 +540,53 @@
flatbuffers::Offset<Weapon> CreateWeapon(flatbuffers::FlatBufferBuilder &_fbb, const WeaponT *_o, const flatbuffers::rehasher_function_t *_rehasher = nullptr);
+
+inline bool operator==(const MonsterT &lhs, const MonsterT &rhs) {
+ return
+ ((lhs.pos == rhs.pos) || (lhs.pos && rhs.pos && *lhs.pos == *rhs.pos)) &&
+ (lhs.mana == rhs.mana) &&
+ (lhs.hp == rhs.hp) &&
+ (lhs.name == rhs.name) &&
+ (lhs.inventory == rhs.inventory) &&
+ (lhs.color == rhs.color) &&
+ (lhs.weapons == rhs.weapons) &&
+ (lhs.equipped == rhs.equipped) &&
+ (lhs.path == rhs.path);
+}
+
+inline bool operator!=(const MonsterT &lhs, const MonsterT &rhs) {
+ return !(lhs == rhs);
+}
+
+
+inline MonsterT::MonsterT(const MonsterT &o)
+ : pos((o.pos) ? new MyGame::Sample::Vec3(*o.pos) : nullptr),
+ mana(o.mana),
+ hp(o.hp),
+ name(o.name),
+ inventory(o.inventory),
+ color(o.color),
+ equipped(o.equipped),
+ path(o.path) {
+ weapons.reserve(o.weapons.size());
+ for (const auto &weapons_ : o.weapons) { weapons.emplace_back((weapons_) ? new MyGame::Sample::WeaponT(*weapons_) : nullptr); }
+}
+
+inline MonsterT &MonsterT::operator=(MonsterT o) FLATBUFFERS_NOEXCEPT {
+ std::swap(pos, o.pos);
+ std::swap(mana, o.mana);
+ std::swap(hp, o.hp);
+ std::swap(name, o.name);
+ std::swap(inventory, o.inventory);
+ std::swap(color, o.color);
+ std::swap(weapons, o.weapons);
+ std::swap(equipped, o.equipped);
+ std::swap(path, o.path);
+ return *this;
+}
+
inline MonsterT *Monster::UnPack(const flatbuffers::resolver_function_t *_resolver) const {
- flatbuffers::unique_ptr<MyGame::Sample::MonsterT> _o = flatbuffers::unique_ptr<MyGame::Sample::MonsterT>(new MonsterT());
+ auto _o = std::unique_ptr<MonsterT>(new MonsterT());
UnPackTo(_o.get(), _resolver);
return _o.release();
}
@@ -582,7 +600,7 @@
{ auto _e = name(); if (_e) _o->name = _e->str(); }
{ auto _e = inventory(); if (_e) { _o->inventory.resize(_e->size()); std::copy(_e->begin(), _e->end(), _o->inventory.begin()); } }
{ auto _e = color(); _o->color = _e; }
- { auto _e = weapons(); if (_e) { _o->weapons.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->weapons[_i] = flatbuffers::unique_ptr<MyGame::Sample::WeaponT>(_e->Get(_i)->UnPack(_resolver)); } } }
+ { auto _e = weapons(); if (_e) { _o->weapons.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { if(_o->weapons[_i]) { _e->Get(_i)->UnPackTo(_o->weapons[_i].get(), _resolver); } else { _o->weapons[_i] = flatbuffers::unique_ptr<MyGame::Sample::WeaponT>(_e->Get(_i)->UnPack(_resolver)); }; } } }
{ auto _e = equipped_type(); _o->equipped.type = _e; }
{ auto _e = equipped(); if (_e) _o->equipped.value = MyGame::Sample::EquipmentUnion::UnPack(_e, equipped_type(), _resolver); }
{ auto _e = path(); if (_e) { _o->path.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->path[_i] = *_e->Get(_i); } } }
@@ -620,8 +638,20 @@
_path);
}
+
+inline bool operator==(const WeaponT &lhs, const WeaponT &rhs) {
+ return
+ (lhs.name == rhs.name) &&
+ (lhs.damage == rhs.damage);
+}
+
+inline bool operator!=(const WeaponT &lhs, const WeaponT &rhs) {
+ return !(lhs == rhs);
+}
+
+
inline WeaponT *Weapon::UnPack(const flatbuffers::resolver_function_t *_resolver) const {
- flatbuffers::unique_ptr<MyGame::Sample::WeaponT> _o = flatbuffers::unique_ptr<MyGame::Sample::WeaponT>(new WeaponT());
+ auto _o = std::unique_ptr<WeaponT>(new WeaponT());
UnPackTo(_o.get(), _resolver);
return _o.release();
}
@@ -675,6 +705,7 @@
}
inline void *EquipmentUnion::UnPack(const void *obj, Equipment type, const flatbuffers::resolver_function_t *resolver) {
+ (void)resolver;
switch (type) {
case Equipment_Weapon: {
auto ptr = reinterpret_cast<const MyGame::Sample::Weapon *>(obj);
@@ -685,6 +716,7 @@
}
inline flatbuffers::Offset<void> EquipmentUnion::Pack(flatbuffers::FlatBufferBuilder &_fbb, const flatbuffers::rehasher_function_t *_rehasher) const {
+ (void)_rehasher;
switch (type) {
case Equipment_Weapon: {
auto ptr = reinterpret_cast<const MyGame::Sample::WeaponT *>(value);
@@ -840,6 +872,10 @@
return flatbuffers::GetMutableRoot<Monster>(buf);
}
+inline MyGame::Sample::Monster *GetMutableSizePrefixedMonster(void *buf) {
+ return flatbuffers::GetMutableSizePrefixedRoot<MyGame::Sample::Monster>(buf);
+}
+
inline bool VerifyMonsterBuffer(
flatbuffers::Verifier &verifier) {
return verifier.VerifyBuffer<MyGame::Sample::Monster>(nullptr);
diff --git a/samples/monster_generated.lobster b/samples/monster_generated.lobster
index 702cdd4..310f74d 100644
--- a/samples/monster_generated.lobster
+++ b/samples/monster_generated.lobster
@@ -44,7 +44,7 @@
def name():
return buf_.flatbuffers_field_string(pos_, 10)
def inventory(i:int):
- return buf_.read_int8_le(buf_.flatbuffers_field_vector(pos_, 14) + i * 1)
+ return buf_.read_uint8_le(buf_.flatbuffers_field_vector(pos_, 14) + i * 1)
def inventory_length():
return buf_.flatbuffers_field_vector_len(pos_, 14)
def color():
@@ -54,7 +54,7 @@
def weapons_length():
return buf_.flatbuffers_field_vector_len(pos_, 18)
def equipped_type():
- return Equipment(buf_.flatbuffers_field_int8(pos_, 20, 0))
+ return Equipment(buf_.flatbuffers_field_uint8(pos_, 20, 0))
def equipped_as_Weapon():
return MyGame_Sample_Weapon { buf_, buf_.flatbuffers_field_table(pos_, 22) }
def path(i:int):
diff --git a/samples/monster_generated.rs b/samples/monster_generated.rs
deleted file mode 100644
index e352b75..0000000
--- a/samples/monster_generated.rs
+++ /dev/null
@@ -1,587 +0,0 @@
-// automatically generated by the FlatBuffers compiler, do not modify
-
-
-#![allow(unused_imports, dead_code)]
-
-use std::mem;
-use std::cmp::Ordering;
-
-extern crate flatbuffers;
-use self::flatbuffers::EndianScalar;
-
-#[allow(unused_imports, dead_code)]
-pub mod my_game {
-
- use std::mem;
- use std::cmp::Ordering;
-
- extern crate flatbuffers;
- use self::flatbuffers::EndianScalar;
-#[allow(unused_imports, dead_code)]
-pub mod sample {
-
- use std::mem;
- use std::cmp::Ordering;
-
- extern crate flatbuffers;
- use self::flatbuffers::EndianScalar;
-
-#[deprecated(since = "1.13", note = "Use associated constants instead. This will no longer be generated in 2021.")]
-pub const ENUM_MIN_COLOR: i8 = 0;
-#[deprecated(since = "1.13", note = "Use associated constants instead. This will no longer be generated in 2021.")]
-pub const ENUM_MAX_COLOR: i8 = 2;
-#[deprecated(since = "1.13", note = "Use associated constants instead. This will no longer be generated in 2021.")]
-#[allow(non_camel_case_types)]
-pub const ENUM_VALUES_COLOR: [Color; 3] = [
- Color::Red,
- Color::Green,
- Color::Blue,
-];
-
-#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
-#[repr(transparent)]
-pub struct Color(pub i8);
-#[allow(non_upper_case_globals)]
-impl Color {
- pub const Red: Self = Self(0);
- pub const Green: Self = Self(1);
- pub const Blue: Self = Self(2);
-
- pub const ENUM_MIN: i8 = 0;
- pub const ENUM_MAX: i8 = 2;
- pub const ENUM_VALUES: &'static [Self] = &[
- Self::Red,
- Self::Green,
- Self::Blue,
- ];
- /// Returns the variant's name or "" if unknown.
- pub fn variant_name(self) -> Option<&'static str> {
- match self {
- Self::Red => Some("Red"),
- Self::Green => Some("Green"),
- Self::Blue => Some("Blue"),
- _ => None,
- }
- }
-}
-impl std::fmt::Debug for Color {
- fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
- if let Some(name) = self.variant_name() {
- f.write_str(name)
- } else {
- f.write_fmt(format_args!("<UNKNOWN {:?}>", self.0))
- }
- }
-}
-impl<'a> flatbuffers::Follow<'a> for Color {
- type Inner = Self;
- #[inline]
- fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
- Self(flatbuffers::read_scalar_at::<i8>(buf, loc))
- }
-}
-
-impl flatbuffers::Push for Color {
- type Output = Color;
- #[inline]
- fn push(&self, dst: &mut [u8], _rest: &[u8]) {
- flatbuffers::emplace_scalar::<i8>(dst, self.0);
- }
-}
-
-impl flatbuffers::EndianScalar for Color {
- #[inline]
- fn to_little_endian(self) -> Self {
- Self(i8::to_le(self.0))
- }
- #[inline]
- fn from_little_endian(self) -> Self {
- Self(i8::from_le(self.0))
- }
-}
-
-#[deprecated(since = "1.13", note = "Use associated constants instead. This will no longer be generated in 2021.")]
-pub const ENUM_MIN_EQUIPMENT: u8 = 0;
-#[deprecated(since = "1.13", note = "Use associated constants instead. This will no longer be generated in 2021.")]
-pub const ENUM_MAX_EQUIPMENT: u8 = 1;
-#[deprecated(since = "1.13", note = "Use associated constants instead. This will no longer be generated in 2021.")]
-#[allow(non_camel_case_types)]
-pub const ENUM_VALUES_EQUIPMENT: [Equipment; 2] = [
- Equipment::NONE,
- Equipment::Weapon,
-];
-
-#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
-#[repr(transparent)]
-pub struct Equipment(pub u8);
-#[allow(non_upper_case_globals)]
-impl Equipment {
- pub const NONE: Self = Self(0);
- pub const Weapon: Self = Self(1);
-
- pub const ENUM_MIN: u8 = 0;
- pub const ENUM_MAX: u8 = 1;
- pub const ENUM_VALUES: &'static [Self] = &[
- Self::NONE,
- Self::Weapon,
- ];
- /// Returns the variant's name or "" if unknown.
- pub fn variant_name(self) -> Option<&'static str> {
- match self {
- Self::NONE => Some("NONE"),
- Self::Weapon => Some("Weapon"),
- _ => None,
- }
- }
-}
-impl std::fmt::Debug for Equipment {
- fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
- if let Some(name) = self.variant_name() {
- f.write_str(name)
- } else {
- f.write_fmt(format_args!("<UNKNOWN {:?}>", self.0))
- }
- }
-}
-impl<'a> flatbuffers::Follow<'a> for Equipment {
- type Inner = Self;
- #[inline]
- fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
- Self(flatbuffers::read_scalar_at::<u8>(buf, loc))
- }
-}
-
-impl flatbuffers::Push for Equipment {
- type Output = Equipment;
- #[inline]
- fn push(&self, dst: &mut [u8], _rest: &[u8]) {
- flatbuffers::emplace_scalar::<u8>(dst, self.0);
- }
-}
-
-impl flatbuffers::EndianScalar for Equipment {
- #[inline]
- fn to_little_endian(self) -> Self {
- Self(u8::to_le(self.0))
- }
- #[inline]
- fn from_little_endian(self) -> Self {
- Self(u8::from_le(self.0))
- }
-}
-
-pub struct EquipmentUnionTableOffset {}
-// struct Vec3, aligned to 4
-#[repr(C, align(4))]
-#[derive(Clone, Copy, PartialEq)]
-pub struct Vec3 {
- x_: f32,
- y_: f32,
- z_: f32,
-} // pub struct Vec3
-impl std::fmt::Debug for Vec3 {
- fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
- f.debug_struct("Vec3")
- .field("x", &self.x())
- .field("y", &self.y())
- .field("z", &self.z())
- .finish()
- }
-}
-
-impl flatbuffers::SafeSliceAccess for Vec3 {}
-impl<'a> flatbuffers::Follow<'a> for Vec3 {
- type Inner = &'a Vec3;
- #[inline]
- fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
- <&'a Vec3>::follow(buf, loc)
- }
-}
-impl<'a> flatbuffers::Follow<'a> for &'a Vec3 {
- type Inner = &'a Vec3;
- #[inline]
- fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
- flatbuffers::follow_cast_ref::<Vec3>(buf, loc)
- }
-}
-impl<'b> flatbuffers::Push for Vec3 {
- type Output = Vec3;
- #[inline]
- fn push(&self, dst: &mut [u8], _rest: &[u8]) {
- let src = unsafe {
- ::std::slice::from_raw_parts(self as *const Vec3 as *const u8, Self::size())
- };
- dst.copy_from_slice(src);
- }
-}
-impl<'b> flatbuffers::Push for &'b Vec3 {
- type Output = Vec3;
-
- #[inline]
- fn push(&self, dst: &mut [u8], _rest: &[u8]) {
- let src = unsafe {
- ::std::slice::from_raw_parts(*self as *const Vec3 as *const u8, Self::size())
- };
- dst.copy_from_slice(src);
- }
-}
-
-
-impl Vec3 {
- pub fn new(_x: f32, _y: f32, _z: f32) -> Self {
- Vec3 {
- x_: _x.to_little_endian(),
- y_: _y.to_little_endian(),
- z_: _z.to_little_endian(),
-
- }
- }
- pub fn x(&self) -> f32 {
- self.x_.from_little_endian()
- }
- pub fn y(&self) -> f32 {
- self.y_.from_little_endian()
- }
- pub fn z(&self) -> f32 {
- self.z_.from_little_endian()
- }
-}
-
-pub enum MonsterOffset {}
-#[derive(Copy, Clone, PartialEq)]
-
-pub struct Monster<'a> {
- pub _tab: flatbuffers::Table<'a>,
-}
-
-impl<'a> flatbuffers::Follow<'a> for Monster<'a> {
- type Inner = Monster<'a>;
- #[inline]
- fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
- Self { _tab: flatbuffers::Table { buf, loc } }
- }
-}
-
-impl<'a> Monster<'a> {
- #[inline]
- pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
- Monster {
- _tab: table,
- }
- }
- #[allow(unused_mut)]
- pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
- _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
- args: &'args MonsterArgs<'args>) -> flatbuffers::WIPOffset<Monster<'bldr>> {
- let mut builder = MonsterBuilder::new(_fbb);
- if let Some(x) = args.path { builder.add_path(x); }
- if let Some(x) = args.equipped { builder.add_equipped(x); }
- if let Some(x) = args.weapons { builder.add_weapons(x); }
- if let Some(x) = args.inventory { builder.add_inventory(x); }
- if let Some(x) = args.name { builder.add_name(x); }
- if let Some(x) = args.pos { builder.add_pos(x); }
- builder.add_hp(args.hp);
- builder.add_mana(args.mana);
- builder.add_equipped_type(args.equipped_type);
- builder.add_color(args.color);
- builder.finish()
- }
-
- pub const VT_POS: flatbuffers::VOffsetT = 4;
- pub const VT_MANA: flatbuffers::VOffsetT = 6;
- pub const VT_HP: flatbuffers::VOffsetT = 8;
- pub const VT_NAME: flatbuffers::VOffsetT = 10;
- pub const VT_INVENTORY: flatbuffers::VOffsetT = 14;
- pub const VT_COLOR: flatbuffers::VOffsetT = 16;
- pub const VT_WEAPONS: flatbuffers::VOffsetT = 18;
- pub const VT_EQUIPPED_TYPE: flatbuffers::VOffsetT = 20;
- pub const VT_EQUIPPED: flatbuffers::VOffsetT = 22;
- pub const VT_PATH: flatbuffers::VOffsetT = 24;
-
- #[inline]
- pub fn pos(&self) -> Option<&'a Vec3> {
- self._tab.get::<Vec3>(Monster::VT_POS, None)
- }
- #[inline]
- pub fn mana(&self) -> i16 {
- self._tab.get::<i16>(Monster::VT_MANA, Some(150)).unwrap()
- }
- #[inline]
- pub fn hp(&self) -> i16 {
- self._tab.get::<i16>(Monster::VT_HP, Some(100)).unwrap()
- }
- #[inline]
- pub fn name(&self) -> Option<&'a str> {
- self._tab.get::<flatbuffers::ForwardsUOffset<&str>>(Monster::VT_NAME, None)
- }
- #[inline]
- pub fn inventory(&self) -> Option<&'a [u8]> {
- self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, u8>>>(Monster::VT_INVENTORY, None).map(|v| v.safe_slice())
- }
- #[inline]
- pub fn color(&self) -> Color {
- self._tab.get::<Color>(Monster::VT_COLOR, Some(Color::Blue)).unwrap()
- }
- #[inline]
- pub fn weapons(&self) -> Option<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Weapon<'a>>>> {
- self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<flatbuffers::ForwardsUOffset<Weapon<'a>>>>>(Monster::VT_WEAPONS, None)
- }
- #[inline]
- pub fn equipped_type(&self) -> Equipment {
- self._tab.get::<Equipment>(Monster::VT_EQUIPPED_TYPE, Some(Equipment::NONE)).unwrap()
- }
- #[inline]
- pub fn equipped(&self) -> Option<flatbuffers::Table<'a>> {
- self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Table<'a>>>(Monster::VT_EQUIPPED, None)
- }
- #[inline]
- pub fn path(&self) -> Option<&'a [Vec3]> {
- self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<Vec3>>>(Monster::VT_PATH, None).map(|v| v.safe_slice() )
- }
- #[inline]
- #[allow(non_snake_case)]
- pub fn equipped_as_weapon(&self) -> Option<Weapon<'a>> {
- if self.equipped_type() == Equipment::Weapon {
- self.equipped().map(Weapon::init_from_table)
- } else {
- None
- }
- }
-
-}
-
-pub struct MonsterArgs<'a> {
- pub pos: Option<&'a Vec3>,
- pub mana: i16,
- pub hp: i16,
- pub name: Option<flatbuffers::WIPOffset<&'a str>>,
- pub inventory: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, u8>>>,
- pub color: Color,
- pub weapons: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Weapon<'a>>>>>,
- pub equipped_type: Equipment,
- pub equipped: Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>,
- pub path: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, Vec3>>>,
-}
-impl<'a> Default for MonsterArgs<'a> {
- #[inline]
- fn default() -> Self {
- MonsterArgs {
- pos: None,
- mana: 150,
- hp: 100,
- name: None,
- inventory: None,
- color: Color::Blue,
- weapons: None,
- equipped_type: Equipment::NONE,
- equipped: None,
- path: None,
- }
- }
-}
-pub struct MonsterBuilder<'a: 'b, 'b> {
- fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
- start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
-}
-impl<'a: 'b, 'b> MonsterBuilder<'a, 'b> {
- #[inline]
- pub fn add_pos(&mut self, pos: &Vec3) {
- self.fbb_.push_slot_always::<&Vec3>(Monster::VT_POS, pos);
- }
- #[inline]
- pub fn add_mana(&mut self, mana: i16) {
- self.fbb_.push_slot::<i16>(Monster::VT_MANA, mana, 150);
- }
- #[inline]
- pub fn add_hp(&mut self, hp: i16) {
- self.fbb_.push_slot::<i16>(Monster::VT_HP, hp, 100);
- }
- #[inline]
- pub fn add_name(&mut self, name: flatbuffers::WIPOffset<&'b str>) {
- self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_NAME, name);
- }
- #[inline]
- pub fn add_inventory(&mut self, inventory: flatbuffers::WIPOffset<flatbuffers::Vector<'b , u8>>) {
- self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_INVENTORY, inventory);
- }
- #[inline]
- pub fn add_color(&mut self, color: Color) {
- self.fbb_.push_slot::<Color>(Monster::VT_COLOR, color, Color::Blue);
- }
- #[inline]
- pub fn add_weapons(&mut self, weapons: flatbuffers::WIPOffset<flatbuffers::Vector<'b , flatbuffers::ForwardsUOffset<Weapon<'b >>>>) {
- self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_WEAPONS, weapons);
- }
- #[inline]
- pub fn add_equipped_type(&mut self, equipped_type: Equipment) {
- self.fbb_.push_slot::<Equipment>(Monster::VT_EQUIPPED_TYPE, equipped_type, Equipment::NONE);
- }
- #[inline]
- pub fn add_equipped(&mut self, equipped: flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>) {
- self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_EQUIPPED, equipped);
- }
- #[inline]
- pub fn add_path(&mut self, path: flatbuffers::WIPOffset<flatbuffers::Vector<'b , Vec3>>) {
- self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_PATH, path);
- }
- #[inline]
- pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> MonsterBuilder<'a, 'b> {
- let start = _fbb.start_table();
- MonsterBuilder {
- fbb_: _fbb,
- start_: start,
- }
- }
- #[inline]
- pub fn finish(self) -> flatbuffers::WIPOffset<Monster<'a>> {
- let o = self.fbb_.end_table(self.start_);
- flatbuffers::WIPOffset::new(o.value())
- }
-}
-
-impl std::fmt::Debug for Monster<'_> {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- let mut ds = f.debug_struct("Monster");
- ds.field("pos", &self.pos());
- ds.field("mana", &self.mana());
- ds.field("hp", &self.hp());
- ds.field("name", &self.name());
- ds.field("inventory", &self.inventory());
- ds.field("color", &self.color());
- ds.field("weapons", &self.weapons());
- ds.field("equipped_type", &self.equipped_type());
- match self.equipped_type() {
- Equipment::Weapon => {
- if let Some(x) = self.equipped_as_weapon() {
- ds.field("equipped", &x)
- } else {
- ds.field("equipped", &"InvalidFlatbuffer: Union discriminant does not match value.")
- }
- },
- _ => {
- let x: Option<()> = None;
- ds.field("equipped", &x)
- },
- };
- ds.field("path", &self.path());
- ds.finish()
- }
-}
-pub enum WeaponOffset {}
-#[derive(Copy, Clone, PartialEq)]
-
-pub struct Weapon<'a> {
- pub _tab: flatbuffers::Table<'a>,
-}
-
-impl<'a> flatbuffers::Follow<'a> for Weapon<'a> {
- type Inner = Weapon<'a>;
- #[inline]
- fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
- Self { _tab: flatbuffers::Table { buf, loc } }
- }
-}
-
-impl<'a> Weapon<'a> {
- #[inline]
- pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
- Weapon {
- _tab: table,
- }
- }
- #[allow(unused_mut)]
- pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
- _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
- args: &'args WeaponArgs<'args>) -> flatbuffers::WIPOffset<Weapon<'bldr>> {
- let mut builder = WeaponBuilder::new(_fbb);
- if let Some(x) = args.name { builder.add_name(x); }
- builder.add_damage(args.damage);
- builder.finish()
- }
-
- pub const VT_NAME: flatbuffers::VOffsetT = 4;
- pub const VT_DAMAGE: flatbuffers::VOffsetT = 6;
-
- #[inline]
- pub fn name(&self) -> Option<&'a str> {
- self._tab.get::<flatbuffers::ForwardsUOffset<&str>>(Weapon::VT_NAME, None)
- }
- #[inline]
- pub fn damage(&self) -> i16 {
- self._tab.get::<i16>(Weapon::VT_DAMAGE, Some(0)).unwrap()
- }
-}
-
-pub struct WeaponArgs<'a> {
- pub name: Option<flatbuffers::WIPOffset<&'a str>>,
- pub damage: i16,
-}
-impl<'a> Default for WeaponArgs<'a> {
- #[inline]
- fn default() -> Self {
- WeaponArgs {
- name: None,
- damage: 0,
- }
- }
-}
-pub struct WeaponBuilder<'a: 'b, 'b> {
- fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
- start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
-}
-impl<'a: 'b, 'b> WeaponBuilder<'a, 'b> {
- #[inline]
- pub fn add_name(&mut self, name: flatbuffers::WIPOffset<&'b str>) {
- self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Weapon::VT_NAME, name);
- }
- #[inline]
- pub fn add_damage(&mut self, damage: i16) {
- self.fbb_.push_slot::<i16>(Weapon::VT_DAMAGE, damage, 0);
- }
- #[inline]
- pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> WeaponBuilder<'a, 'b> {
- let start = _fbb.start_table();
- WeaponBuilder {
- fbb_: _fbb,
- start_: start,
- }
- }
- #[inline]
- pub fn finish(self) -> flatbuffers::WIPOffset<Weapon<'a>> {
- let o = self.fbb_.end_table(self.start_);
- flatbuffers::WIPOffset::new(o.value())
- }
-}
-
-impl std::fmt::Debug for Weapon<'_> {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- let mut ds = f.debug_struct("Weapon");
- ds.field("name", &self.name());
- ds.field("damage", &self.damage());
- ds.finish()
- }
-}
-#[inline]
-pub fn get_root_as_monster<'a>(buf: &'a [u8]) -> Monster<'a> {
- flatbuffers::get_root::<Monster<'a>>(buf)
-}
-
-#[inline]
-pub fn get_size_prefixed_root_as_monster<'a>(buf: &'a [u8]) -> Monster<'a> {
- flatbuffers::get_size_prefixed_root::<Monster<'a>>(buf)
-}
-
-#[inline]
-pub fn finish_monster_buffer<'a, 'b>(
- fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,
- root: flatbuffers::WIPOffset<Monster<'a>>) {
- fbb.finish(root, None);
-}
-
-#[inline]
-pub fn finish_size_prefixed_monster_buffer<'a, 'b>(fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>, root: flatbuffers::WIPOffset<Monster<'a>>) {
- fbb.finish_size_prefixed(root, None);
-}
-} // pub mod Sample
-} // pub mod MyGame
-
diff --git a/samples/monster_generated.swift b/samples/monster_generated.swift
new file mode 100644
index 0000000..b3b6f05
--- /dev/null
+++ b/samples/monster_generated.swift
@@ -0,0 +1,200 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+// swiftlint:disable all
+// swiftformat:disable all
+
+import FlatBuffers
+
+public enum MyGame_Sample_Color: Int8, Enum {
+ public typealias T = Int8
+ public static var byteSize: Int { return MemoryLayout<Int8>.size }
+ public var value: Int8 { return self.rawValue }
+ case red = 0
+ case green = 1
+ case blue = 2
+
+
+ public static var max: MyGame_Sample_Color { return .blue }
+ public static var min: MyGame_Sample_Color { return .red }
+}
+
+public enum MyGame_Sample_Equipment: UInt8, Enum {
+ public typealias T = UInt8
+ public static var byteSize: Int { return MemoryLayout<UInt8>.size }
+ public var value: UInt8 { return self.rawValue }
+ case none_ = 0
+ case weapon = 1
+
+
+ public static var max: MyGame_Sample_Equipment { return .weapon }
+ public static var min: MyGame_Sample_Equipment { return .none_ }
+}
+
+public struct MyGame_Sample_Vec3: NativeStruct {
+
+ static func validateVersion() { FlatBuffersVersion_2_0_0() }
+
+ private var _x: Float32
+ private var _y: Float32
+ private var _z: Float32
+
+ public init(x: Float32, y: Float32, z: Float32) {
+ _x = x
+ _y = y
+ _z = z
+ }
+
+ public init() {
+ _x = 0.0
+ _y = 0.0
+ _z = 0.0
+ }
+
+ public var x: Float32 { _x }
+ public var y: Float32 { _y }
+ public var z: Float32 { _z }
+}
+
+public struct MyGame_Sample_Vec3_Mutable: FlatBufferObject {
+
+ static func validateVersion() { FlatBuffersVersion_2_0_0() }
+ public var __buffer: ByteBuffer! { return _accessor.bb }
+ private var _accessor: Struct
+
+ public init(_ bb: ByteBuffer, o: Int32) { _accessor = Struct(bb: bb, position: o) }
+
+ public var x: Float32 { return _accessor.readBuffer(of: Float32.self, at: 0) }
+ @discardableResult public func mutate(x: Float32) -> Bool { return _accessor.mutate(x, index: 0) }
+ public var y: Float32 { return _accessor.readBuffer(of: Float32.self, at: 4) }
+ @discardableResult public func mutate(y: Float32) -> Bool { return _accessor.mutate(y, index: 4) }
+ public var z: Float32 { return _accessor.readBuffer(of: Float32.self, at: 8) }
+ @discardableResult public func mutate(z: Float32) -> Bool { return _accessor.mutate(z, index: 8) }
+}
+
+public struct MyGame_Sample_Monster: FlatBufferObject {
+
+ static func validateVersion() { FlatBuffersVersion_2_0_0() }
+ public var __buffer: ByteBuffer! { return _accessor.bb }
+ private var _accessor: Table
+
+ public static func getRootAsMonster(bb: ByteBuffer) -> MyGame_Sample_Monster { return MyGame_Sample_Monster(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) }
+
+ private init(_ t: Table) { _accessor = t }
+ public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) }
+
+ private enum VTOFFSET: VOffset {
+ case pos = 4
+ case mana = 6
+ case hp = 8
+ case name = 10
+ case inventory = 14
+ case color = 16
+ case weapons = 18
+ case equippedType = 20
+ case equipped = 22
+ case path = 24
+ var v: Int32 { Int32(self.rawValue) }
+ var p: VOffset { self.rawValue }
+ }
+
+ public var pos: MyGame_Sample_Vec3? { let o = _accessor.offset(VTOFFSET.pos.v); return o == 0 ? nil : _accessor.readBuffer(of: MyGame_Sample_Vec3.self, at: o) }
+ public var mutablePos: MyGame_Sample_Vec3_Mutable? { let o = _accessor.offset(VTOFFSET.pos.v); return o == 0 ? nil : MyGame_Sample_Vec3_Mutable(_accessor.bb, o: o + _accessor.postion) }
+ public var mana: Int16 { let o = _accessor.offset(VTOFFSET.mana.v); return o == 0 ? 150 : _accessor.readBuffer(of: Int16.self, at: o) }
+ @discardableResult public func mutate(mana: Int16) -> Bool {let o = _accessor.offset(VTOFFSET.mana.v); return _accessor.mutate(mana, index: o) }
+ public var hp: Int16 { let o = _accessor.offset(VTOFFSET.hp.v); return o == 0 ? 100 : _accessor.readBuffer(of: Int16.self, at: o) }
+ @discardableResult public func mutate(hp: Int16) -> Bool {let o = _accessor.offset(VTOFFSET.hp.v); return _accessor.mutate(hp, index: o) }
+ public var name: String? { let o = _accessor.offset(VTOFFSET.name.v); return o == 0 ? nil : _accessor.string(at: o) }
+ public var nameSegmentArray: [UInt8]? { return _accessor.getVector(at: VTOFFSET.name.v) }
+ public var inventoryCount: Int32 { let o = _accessor.offset(VTOFFSET.inventory.v); return o == 0 ? 0 : _accessor.vector(count: o) }
+ public func inventory(at index: Int32) -> UInt8 { let o = _accessor.offset(VTOFFSET.inventory.v); return o == 0 ? 0 : _accessor.directRead(of: UInt8.self, offset: _accessor.vector(at: o) + index * 1) }
+ public var inventory: [UInt8] { return _accessor.getVector(at: VTOFFSET.inventory.v) ?? [] }
+ public func mutate(inventory: UInt8, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.inventory.v); return _accessor.directMutate(inventory, index: _accessor.vector(at: o) + index * 1) }
+ public var color: MyGame_Sample_Color { let o = _accessor.offset(VTOFFSET.color.v); return o == 0 ? .blue : MyGame_Sample_Color(rawValue: _accessor.readBuffer(of: Int8.self, at: o)) ?? .blue }
+ @discardableResult public func mutate(color: MyGame_Sample_Color) -> Bool {let o = _accessor.offset(VTOFFSET.color.v); return _accessor.mutate(color.rawValue, index: o) }
+ public var weaponsCount: Int32 { let o = _accessor.offset(VTOFFSET.weapons.v); return o == 0 ? 0 : _accessor.vector(count: o) }
+ public func weapons(at index: Int32) -> MyGame_Sample_Weapon? { let o = _accessor.offset(VTOFFSET.weapons.v); return o == 0 ? nil : MyGame_Sample_Weapon(_accessor.bb, o: _accessor.indirect(_accessor.vector(at: o) + index * 4)) }
+ public var equippedType: MyGame_Sample_Equipment { let o = _accessor.offset(VTOFFSET.equippedType.v); return o == 0 ? .none_ : MyGame_Sample_Equipment(rawValue: _accessor.readBuffer(of: UInt8.self, at: o)) ?? .none_ }
+ public func equipped<T: FlatbuffersInitializable>(type: T.Type) -> T? { let o = _accessor.offset(VTOFFSET.equipped.v); return o == 0 ? nil : _accessor.union(o) }
+ public var pathCount: Int32 { let o = _accessor.offset(VTOFFSET.path.v); return o == 0 ? 0 : _accessor.vector(count: o) }
+ public func path(at index: Int32) -> MyGame_Sample_Vec3? { let o = _accessor.offset(VTOFFSET.path.v); return o == 0 ? nil : _accessor.directRead(of: MyGame_Sample_Vec3.self, offset: _accessor.vector(at: o) + index * 12) }
+ public func mutablePath(at index: Int32) -> MyGame_Sample_Vec3_Mutable? { let o = _accessor.offset(VTOFFSET.path.v); return o == 0 ? nil : MyGame_Sample_Vec3_Mutable(_accessor.bb, o: _accessor.vector(at: o) + index * 12) }
+ public static func startMonster(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 11) }
+ public static func add(pos: MyGame_Sample_Vec3?, _ fbb: inout FlatBufferBuilder) { guard let pos = pos else { return }; fbb.create(struct: pos, position: VTOFFSET.pos.p) }
+ public static func add(mana: Int16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: mana, def: 150, at: VTOFFSET.mana.p) }
+ public static func add(hp: Int16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: hp, def: 100, at: VTOFFSET.hp.p) }
+ public static func add(name: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: name, at: VTOFFSET.name.p) }
+ public static func addVectorOf(inventory: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: inventory, at: VTOFFSET.inventory.p) }
+ public static func add(color: MyGame_Sample_Color, _ fbb: inout FlatBufferBuilder) { fbb.add(element: color.rawValue, def: 2, at: VTOFFSET.color.p) }
+ public static func addVectorOf(weapons: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: weapons, at: VTOFFSET.weapons.p) }
+ public static func add(equippedType: MyGame_Sample_Equipment, _ fbb: inout FlatBufferBuilder) { fbb.add(element: equippedType.rawValue, def: 0, at: VTOFFSET.equippedType.p) }
+ public static func add(equipped: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: equipped, at: VTOFFSET.equipped.p) }
+ public static func addVectorOf(path: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: path, at: VTOFFSET.path.p) }
+ public static func startVectorOfPath(_ size: Int, in builder: inout FlatBufferBuilder) {
+ builder.startVector(size * MemoryLayout<MyGame_Sample_Vec3>.size, elementSize: MemoryLayout<MyGame_Sample_Vec3>.alignment)
+ }
+ public static func endMonster(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end }
+ public static func createMonster(
+ _ fbb: inout FlatBufferBuilder,
+ pos: MyGame_Sample_Vec3? = nil,
+ mana: Int16 = 150,
+ hp: Int16 = 100,
+ nameOffset name: Offset = Offset(),
+ inventoryVectorOffset inventory: Offset = Offset(),
+ color: MyGame_Sample_Color = .blue,
+ weaponsVectorOffset weapons: Offset = Offset(),
+ equippedType: MyGame_Sample_Equipment = .none_,
+ equippedOffset equipped: Offset = Offset(),
+ pathVectorOffset path: Offset = Offset()
+ ) -> Offset {
+ let __start = MyGame_Sample_Monster.startMonster(&fbb)
+ MyGame_Sample_Monster.add(pos: pos, &fbb)
+ MyGame_Sample_Monster.add(mana: mana, &fbb)
+ MyGame_Sample_Monster.add(hp: hp, &fbb)
+ MyGame_Sample_Monster.add(name: name, &fbb)
+ MyGame_Sample_Monster.addVectorOf(inventory: inventory, &fbb)
+ MyGame_Sample_Monster.add(color: color, &fbb)
+ MyGame_Sample_Monster.addVectorOf(weapons: weapons, &fbb)
+ MyGame_Sample_Monster.add(equippedType: equippedType, &fbb)
+ MyGame_Sample_Monster.add(equipped: equipped, &fbb)
+ MyGame_Sample_Monster.addVectorOf(path: path, &fbb)
+ return MyGame_Sample_Monster.endMonster(&fbb, start: __start)
+ }
+}
+
+public struct MyGame_Sample_Weapon: FlatBufferObject {
+
+ static func validateVersion() { FlatBuffersVersion_2_0_0() }
+ public var __buffer: ByteBuffer! { return _accessor.bb }
+ private var _accessor: Table
+
+ public static func getRootAsWeapon(bb: ByteBuffer) -> MyGame_Sample_Weapon { return MyGame_Sample_Weapon(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) }
+
+ private init(_ t: Table) { _accessor = t }
+ public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) }
+
+ private enum VTOFFSET: VOffset {
+ case name = 4
+ case damage = 6
+ var v: Int32 { Int32(self.rawValue) }
+ var p: VOffset { self.rawValue }
+ }
+
+ public var name: String? { let o = _accessor.offset(VTOFFSET.name.v); return o == 0 ? nil : _accessor.string(at: o) }
+ public var nameSegmentArray: [UInt8]? { return _accessor.getVector(at: VTOFFSET.name.v) }
+ public var damage: Int16 { let o = _accessor.offset(VTOFFSET.damage.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int16.self, at: o) }
+ @discardableResult public func mutate(damage: Int16) -> Bool {let o = _accessor.offset(VTOFFSET.damage.v); return _accessor.mutate(damage, index: o) }
+ public static func startWeapon(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 2) }
+ public static func add(name: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: name, at: VTOFFSET.name.p) }
+ public static func add(damage: Int16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: damage, def: 0, at: VTOFFSET.damage.p) }
+ public static func endWeapon(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end }
+ public static func createWeapon(
+ _ fbb: inout FlatBufferBuilder,
+ nameOffset name: Offset = Offset(),
+ damage: Int16 = 0
+ ) -> Offset {
+ let __start = MyGame_Sample_Weapon.startWeapon(&fbb)
+ MyGame_Sample_Weapon.add(name: name, &fbb)
+ MyGame_Sample_Weapon.add(damage: damage, &fbb)
+ return MyGame_Sample_Weapon.endWeapon(&fbb, start: __start)
+ }
+}
+
diff --git a/samples/rust_generated/mod.rs b/samples/rust_generated/mod.rs
new file mode 100644
index 0000000..8560153
--- /dev/null
+++ b/samples/rust_generated/mod.rs
@@ -0,0 +1,17 @@
+// Automatically generated by the Flatbuffers compiler. Do not modify.
+pub mod my_game {
+ use super::*;
+ pub mod sample {
+ use super::*;
+ mod color_generated;
+ pub use self::color_generated::*;
+ mod equipment_generated;
+ pub use self::equipment_generated::*;
+ mod vec_3_generated;
+ pub use self::vec_3_generated::*;
+ mod monster_generated;
+ pub use self::monster_generated::*;
+ mod weapon_generated;
+ pub use self::weapon_generated::*;
+ } // sample
+} // my_game
diff --git a/samples/rust_generated/my_game/sample/color_generated.rs b/samples/rust_generated/my_game/sample/color_generated.rs
new file mode 100644
index 0000000..1ef1d31
--- /dev/null
+++ b/samples/rust_generated/my_game/sample/color_generated.rs
@@ -0,0 +1,97 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+pub const ENUM_MIN_COLOR: i8 = 0;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+pub const ENUM_MAX_COLOR: i8 = 2;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+#[allow(non_camel_case_types)]
+pub const ENUM_VALUES_COLOR: [Color; 3] = [
+ Color::Red,
+ Color::Green,
+ Color::Blue,
+];
+
+#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
+#[repr(transparent)]
+pub struct Color(pub i8);
+#[allow(non_upper_case_globals)]
+impl Color {
+ pub const Red: Self = Self(0);
+ pub const Green: Self = Self(1);
+ pub const Blue: Self = Self(2);
+
+ pub const ENUM_MIN: i8 = 0;
+ pub const ENUM_MAX: i8 = 2;
+ pub const ENUM_VALUES: &'static [Self] = &[
+ Self::Red,
+ Self::Green,
+ Self::Blue,
+ ];
+ /// Returns the variant's name or "" if unknown.
+ pub fn variant_name(self) -> Option<&'static str> {
+ match self {
+ Self::Red => Some("Red"),
+ Self::Green => Some("Green"),
+ Self::Blue => Some("Blue"),
+ _ => None,
+ }
+ }
+}
+impl std::fmt::Debug for Color {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ if let Some(name) = self.variant_name() {
+ f.write_str(name)
+ } else {
+ f.write_fmt(format_args!("<UNKNOWN {:?}>", self.0))
+ }
+ }
+}
+impl<'a> flatbuffers::Follow<'a> for Color {
+ type Inner = Self;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ let b = unsafe {
+ flatbuffers::read_scalar_at::<i8>(buf, loc)
+ };
+ Self(b)
+ }
+}
+
+impl flatbuffers::Push for Color {
+ type Output = Color;
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ unsafe { flatbuffers::emplace_scalar::<i8>(dst, self.0); }
+ }
+}
+
+impl flatbuffers::EndianScalar for Color {
+ #[inline]
+ fn to_little_endian(self) -> Self {
+ let b = i8::to_le(self.0);
+ Self(b)
+ }
+ #[inline]
+ #[allow(clippy::wrong_self_convention)]
+ fn from_little_endian(self) -> Self {
+ let b = i8::from_le(self.0);
+ Self(b)
+ }
+}
+
+impl<'a> flatbuffers::Verifiable for Color {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ i8::run_verifier(v, pos)
+ }
+}
+
+impl flatbuffers::SimpleToVerifyInSlice for Color {}
diff --git a/samples/rust_generated/my_game/sample/equipment_generated.rs b/samples/rust_generated/my_game/sample/equipment_generated.rs
new file mode 100644
index 0000000..919958a
--- /dev/null
+++ b/samples/rust_generated/my_game/sample/equipment_generated.rs
@@ -0,0 +1,142 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+pub const ENUM_MIN_EQUIPMENT: u8 = 0;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+pub const ENUM_MAX_EQUIPMENT: u8 = 1;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+#[allow(non_camel_case_types)]
+pub const ENUM_VALUES_EQUIPMENT: [Equipment; 2] = [
+ Equipment::NONE,
+ Equipment::Weapon,
+];
+
+#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
+#[repr(transparent)]
+pub struct Equipment(pub u8);
+#[allow(non_upper_case_globals)]
+impl Equipment {
+ pub const NONE: Self = Self(0);
+ pub const Weapon: Self = Self(1);
+
+ pub const ENUM_MIN: u8 = 0;
+ pub const ENUM_MAX: u8 = 1;
+ pub const ENUM_VALUES: &'static [Self] = &[
+ Self::NONE,
+ Self::Weapon,
+ ];
+ /// Returns the variant's name or "" if unknown.
+ pub fn variant_name(self) -> Option<&'static str> {
+ match self {
+ Self::NONE => Some("NONE"),
+ Self::Weapon => Some("Weapon"),
+ _ => None,
+ }
+ }
+}
+impl std::fmt::Debug for Equipment {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ if let Some(name) = self.variant_name() {
+ f.write_str(name)
+ } else {
+ f.write_fmt(format_args!("<UNKNOWN {:?}>", self.0))
+ }
+ }
+}
+impl<'a> flatbuffers::Follow<'a> for Equipment {
+ type Inner = Self;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ let b = unsafe {
+ flatbuffers::read_scalar_at::<u8>(buf, loc)
+ };
+ Self(b)
+ }
+}
+
+impl flatbuffers::Push for Equipment {
+ type Output = Equipment;
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ unsafe { flatbuffers::emplace_scalar::<u8>(dst, self.0); }
+ }
+}
+
+impl flatbuffers::EndianScalar for Equipment {
+ #[inline]
+ fn to_little_endian(self) -> Self {
+ let b = u8::to_le(self.0);
+ Self(b)
+ }
+ #[inline]
+ #[allow(clippy::wrong_self_convention)]
+ fn from_little_endian(self) -> Self {
+ let b = u8::from_le(self.0);
+ Self(b)
+ }
+}
+
+impl<'a> flatbuffers::Verifiable for Equipment {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ u8::run_verifier(v, pos)
+ }
+}
+
+impl flatbuffers::SimpleToVerifyInSlice for Equipment {}
+pub struct EquipmentUnionTableOffset {}
+
+#[allow(clippy::upper_case_acronyms)]
+#[non_exhaustive]
+#[derive(Debug, Clone, PartialEq)]
+pub enum EquipmentT {
+ NONE,
+ Weapon(Box<WeaponT>),
+}
+impl Default for EquipmentT {
+ fn default() -> Self {
+ Self::NONE
+ }
+}
+impl EquipmentT {
+ pub fn equipment_type(&self) -> Equipment {
+ match self {
+ Self::NONE => Equipment::NONE,
+ Self::Weapon(_) => Equipment::Weapon,
+ }
+ }
+ pub fn pack(&self, fbb: &mut flatbuffers::FlatBufferBuilder) -> Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>> {
+ match self {
+ Self::NONE => None,
+ Self::Weapon(v) => Some(v.pack(fbb).as_union_value()),
+ }
+ }
+ /// If the union variant matches, return the owned WeaponT, setting the union to NONE.
+ pub fn take_weapon(&mut self) -> Option<Box<WeaponT>> {
+ if let Self::Weapon(_) = self {
+ let v = std::mem::replace(self, Self::NONE);
+ if let Self::Weapon(w) = v {
+ Some(w)
+ } else {
+ unreachable!()
+ }
+ } else {
+ None
+ }
+ }
+ /// If the union variant matches, return a reference to the WeaponT.
+ pub fn as_weapon(&self) -> Option<&WeaponT> {
+ if let Self::Weapon(v) = self { Some(v.as_ref()) } else { None }
+ }
+ /// If the union variant matches, return a mutable reference to the WeaponT.
+ pub fn as_weapon_mut(&mut self) -> Option<&mut WeaponT> {
+ if let Self::Weapon(v) = self { Some(v.as_mut()) } else { None }
+ }
+}
diff --git a/samples/rust_generated/my_game/sample/monster_generated.rs b/samples/rust_generated/my_game/sample/monster_generated.rs
new file mode 100644
index 0000000..c156225
--- /dev/null
+++ b/samples/rust_generated/my_game/sample/monster_generated.rs
@@ -0,0 +1,445 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+pub enum MonsterOffset {}
+#[derive(Copy, Clone, PartialEq)]
+
+pub struct Monster<'a> {
+ pub _tab: flatbuffers::Table<'a>,
+}
+
+impl<'a> flatbuffers::Follow<'a> for Monster<'a> {
+ type Inner = Monster<'a>;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ Self { _tab: flatbuffers::Table { buf, loc } }
+ }
+}
+
+impl<'a> Monster<'a> {
+ pub const VT_POS: flatbuffers::VOffsetT = 4;
+ pub const VT_MANA: flatbuffers::VOffsetT = 6;
+ pub const VT_HP: flatbuffers::VOffsetT = 8;
+ pub const VT_NAME: flatbuffers::VOffsetT = 10;
+ pub const VT_INVENTORY: flatbuffers::VOffsetT = 14;
+ pub const VT_COLOR: flatbuffers::VOffsetT = 16;
+ pub const VT_WEAPONS: flatbuffers::VOffsetT = 18;
+ pub const VT_EQUIPPED_TYPE: flatbuffers::VOffsetT = 20;
+ pub const VT_EQUIPPED: flatbuffers::VOffsetT = 22;
+ pub const VT_PATH: flatbuffers::VOffsetT = 24;
+
+ pub const fn get_fully_qualified_name() -> &'static str {
+ "MyGame.Sample.Monster"
+ }
+
+ #[inline]
+ pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
+ Monster { _tab: table }
+ }
+ #[allow(unused_mut)]
+ pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
+ _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
+ args: &'args MonsterArgs<'args>
+ ) -> flatbuffers::WIPOffset<Monster<'bldr>> {
+ let mut builder = MonsterBuilder::new(_fbb);
+ if let Some(x) = args.path { builder.add_path(x); }
+ if let Some(x) = args.equipped { builder.add_equipped(x); }
+ if let Some(x) = args.weapons { builder.add_weapons(x); }
+ if let Some(x) = args.inventory { builder.add_inventory(x); }
+ if let Some(x) = args.name { builder.add_name(x); }
+ if let Some(x) = args.pos { builder.add_pos(x); }
+ builder.add_hp(args.hp);
+ builder.add_mana(args.mana);
+ builder.add_equipped_type(args.equipped_type);
+ builder.add_color(args.color);
+ builder.finish()
+ }
+
+ pub fn unpack(&self) -> MonsterT {
+ let pos = self.pos().map(|x| {
+ x.unpack()
+ });
+ let mana = self.mana();
+ let hp = self.hp();
+ let name = self.name().map(|x| {
+ x.to_string()
+ });
+ let inventory = self.inventory().map(|x| {
+ x.to_vec()
+ });
+ let color = self.color();
+ let weapons = self.weapons().map(|x| {
+ x.iter().map(|t| t.unpack()).collect()
+ });
+ let equipped = match self.equipped_type() {
+ Equipment::NONE => EquipmentT::NONE,
+ Equipment::Weapon => EquipmentT::Weapon(Box::new(
+ self.equipped_as_weapon()
+ .expect("Invalid union table, expected `Equipment::Weapon`.")
+ .unpack()
+ )),
+ _ => EquipmentT::NONE,
+ };
+ let path = self.path().map(|x| {
+ x.iter().map(|t| t.unpack()).collect()
+ });
+ MonsterT {
+ pos,
+ mana,
+ hp,
+ name,
+ inventory,
+ color,
+ weapons,
+ equipped,
+ path,
+ }
+ }
+
+ #[inline]
+ pub fn pos(&self) -> Option<&'a Vec3> {
+ self._tab.get::<Vec3>(Monster::VT_POS, None)
+ }
+ #[inline]
+ pub fn mana(&self) -> i16 {
+ self._tab.get::<i16>(Monster::VT_MANA, Some(150)).unwrap()
+ }
+ #[inline]
+ pub fn hp(&self) -> i16 {
+ self._tab.get::<i16>(Monster::VT_HP, Some(100)).unwrap()
+ }
+ #[inline]
+ pub fn name(&self) -> Option<&'a str> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<&str>>(Monster::VT_NAME, None)
+ }
+ #[inline]
+ pub fn inventory(&self) -> Option<&'a [u8]> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, u8>>>(Monster::VT_INVENTORY, None).map(|v| v.safe_slice())
+ }
+ #[inline]
+ pub fn color(&self) -> Color {
+ self._tab.get::<Color>(Monster::VT_COLOR, Some(Color::Blue)).unwrap()
+ }
+ #[inline]
+ pub fn weapons(&self) -> Option<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Weapon<'a>>>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Weapon>>>>(Monster::VT_WEAPONS, None)
+ }
+ #[inline]
+ pub fn equipped_type(&self) -> Equipment {
+ self._tab.get::<Equipment>(Monster::VT_EQUIPPED_TYPE, Some(Equipment::NONE)).unwrap()
+ }
+ #[inline]
+ pub fn equipped(&self) -> Option<flatbuffers::Table<'a>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Table<'a>>>(Monster::VT_EQUIPPED, None)
+ }
+ #[inline]
+ pub fn path(&self) -> Option<&'a [Vec3]> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, Vec3>>>(Monster::VT_PATH, None).map(|v| v.safe_slice())
+ }
+ #[inline]
+ #[allow(non_snake_case)]
+ pub fn equipped_as_weapon(&self) -> Option<Weapon<'a>> {
+ if self.equipped_type() == Equipment::Weapon {
+ self.equipped().map(Weapon::init_from_table)
+ } else {
+ None
+ }
+ }
+
+}
+
+impl flatbuffers::Verifiable for Monster<'_> {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ v.visit_table(pos)?
+ .visit_field::<Vec3>("pos", Self::VT_POS, false)?
+ .visit_field::<i16>("mana", Self::VT_MANA, false)?
+ .visit_field::<i16>("hp", Self::VT_HP, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<&str>>("name", Self::VT_NAME, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, u8>>>("inventory", Self::VT_INVENTORY, false)?
+ .visit_field::<Color>("color", Self::VT_COLOR, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, flatbuffers::ForwardsUOffset<Weapon>>>>("weapons", Self::VT_WEAPONS, false)?
+ .visit_union::<Equipment, _>("equipped_type", Self::VT_EQUIPPED_TYPE, "equipped", Self::VT_EQUIPPED, false, |key, v, pos| {
+ match key {
+ Equipment::Weapon => v.verify_union_variant::<flatbuffers::ForwardsUOffset<Weapon>>("Equipment::Weapon", pos),
+ _ => Ok(()),
+ }
+ })?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, Vec3>>>("path", Self::VT_PATH, false)?
+ .finish();
+ Ok(())
+ }
+}
+pub struct MonsterArgs<'a> {
+ pub pos: Option<&'a Vec3>,
+ pub mana: i16,
+ pub hp: i16,
+ pub name: Option<flatbuffers::WIPOffset<&'a str>>,
+ pub inventory: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, u8>>>,
+ pub color: Color,
+ pub weapons: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Weapon<'a>>>>>,
+ pub equipped_type: Equipment,
+ pub equipped: Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>,
+ pub path: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, Vec3>>>,
+}
+impl<'a> Default for MonsterArgs<'a> {
+ #[inline]
+ fn default() -> Self {
+ MonsterArgs {
+ pos: None,
+ mana: 150,
+ hp: 100,
+ name: None,
+ inventory: None,
+ color: Color::Blue,
+ weapons: None,
+ equipped_type: Equipment::NONE,
+ equipped: None,
+ path: None,
+ }
+ }
+}
+
+pub struct MonsterBuilder<'a: 'b, 'b> {
+ fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
+ start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
+}
+impl<'a: 'b, 'b> MonsterBuilder<'a, 'b> {
+ #[inline]
+ pub fn add_pos(&mut self, pos: &Vec3) {
+ self.fbb_.push_slot_always::<&Vec3>(Monster::VT_POS, pos);
+ }
+ #[inline]
+ pub fn add_mana(&mut self, mana: i16) {
+ self.fbb_.push_slot::<i16>(Monster::VT_MANA, mana, 150);
+ }
+ #[inline]
+ pub fn add_hp(&mut self, hp: i16) {
+ self.fbb_.push_slot::<i16>(Monster::VT_HP, hp, 100);
+ }
+ #[inline]
+ pub fn add_name(&mut self, name: flatbuffers::WIPOffset<&'b str>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_NAME, name);
+ }
+ #[inline]
+ pub fn add_inventory(&mut self, inventory: flatbuffers::WIPOffset<flatbuffers::Vector<'b , u8>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_INVENTORY, inventory);
+ }
+ #[inline]
+ pub fn add_color(&mut self, color: Color) {
+ self.fbb_.push_slot::<Color>(Monster::VT_COLOR, color, Color::Blue);
+ }
+ #[inline]
+ pub fn add_weapons(&mut self, weapons: flatbuffers::WIPOffset<flatbuffers::Vector<'b , flatbuffers::ForwardsUOffset<Weapon<'b >>>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_WEAPONS, weapons);
+ }
+ #[inline]
+ pub fn add_equipped_type(&mut self, equipped_type: Equipment) {
+ self.fbb_.push_slot::<Equipment>(Monster::VT_EQUIPPED_TYPE, equipped_type, Equipment::NONE);
+ }
+ #[inline]
+ pub fn add_equipped(&mut self, equipped: flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_EQUIPPED, equipped);
+ }
+ #[inline]
+ pub fn add_path(&mut self, path: flatbuffers::WIPOffset<flatbuffers::Vector<'b , Vec3>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_PATH, path);
+ }
+ #[inline]
+ pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> MonsterBuilder<'a, 'b> {
+ let start = _fbb.start_table();
+ MonsterBuilder {
+ fbb_: _fbb,
+ start_: start,
+ }
+ }
+ #[inline]
+ pub fn finish(self) -> flatbuffers::WIPOffset<Monster<'a>> {
+ let o = self.fbb_.end_table(self.start_);
+ flatbuffers::WIPOffset::new(o.value())
+ }
+}
+
+impl std::fmt::Debug for Monster<'_> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let mut ds = f.debug_struct("Monster");
+ ds.field("pos", &self.pos());
+ ds.field("mana", &self.mana());
+ ds.field("hp", &self.hp());
+ ds.field("name", &self.name());
+ ds.field("inventory", &self.inventory());
+ ds.field("color", &self.color());
+ ds.field("weapons", &self.weapons());
+ ds.field("equipped_type", &self.equipped_type());
+ match self.equipped_type() {
+ Equipment::Weapon => {
+ if let Some(x) = self.equipped_as_weapon() {
+ ds.field("equipped", &x)
+ } else {
+ ds.field("equipped", &"InvalidFlatbuffer: Union discriminant does not match value.")
+ }
+ },
+ _ => {
+ let x: Option<()> = None;
+ ds.field("equipped", &x)
+ },
+ };
+ ds.field("path", &self.path());
+ ds.finish()
+ }
+}
+#[non_exhaustive]
+#[derive(Debug, Clone, PartialEq)]
+pub struct MonsterT {
+ pub pos: Option<Vec3T>,
+ pub mana: i16,
+ pub hp: i16,
+ pub name: Option<String>,
+ pub inventory: Option<Vec<u8>>,
+ pub color: Color,
+ pub weapons: Option<Vec<WeaponT>>,
+ pub equipped: EquipmentT,
+ pub path: Option<Vec<Vec3T>>,
+}
+impl Default for MonsterT {
+ fn default() -> Self {
+ Self {
+ pos: None,
+ mana: 150,
+ hp: 100,
+ name: None,
+ inventory: None,
+ color: Color::Blue,
+ weapons: None,
+ equipped: EquipmentT::NONE,
+ path: None,
+ }
+ }
+}
+impl MonsterT {
+ pub fn pack<'b>(
+ &self,
+ _fbb: &mut flatbuffers::FlatBufferBuilder<'b>
+ ) -> flatbuffers::WIPOffset<Monster<'b>> {
+ let pos_tmp = self.pos.as_ref().map(|x| x.pack());
+ let pos = pos_tmp.as_ref();
+ let mana = self.mana;
+ let hp = self.hp;
+ let name = self.name.as_ref().map(|x|{
+ _fbb.create_string(x)
+ });
+ let inventory = self.inventory.as_ref().map(|x|{
+ _fbb.create_vector(x)
+ });
+ let color = self.color;
+ let weapons = self.weapons.as_ref().map(|x|{
+ let w: Vec<_> = x.iter().map(|t| t.pack(_fbb)).collect();_fbb.create_vector(&w)
+ });
+ let equipped_type = self.equipped.equipment_type();
+ let equipped = self.equipped.pack(_fbb);
+ let path = self.path.as_ref().map(|x|{
+ let w: Vec<_> = x.iter().map(|t| t.pack()).collect();_fbb.create_vector(&w)
+ });
+ Monster::create(_fbb, &MonsterArgs{
+ pos,
+ mana,
+ hp,
+ name,
+ inventory,
+ color,
+ weapons,
+ equipped_type,
+ equipped,
+ path,
+ })
+ }
+}
+#[inline]
+#[deprecated(since="2.0.0", note="Deprecated in favor of `root_as...` methods.")]
+pub fn get_root_as_monster<'a>(buf: &'a [u8]) -> Monster<'a> {
+ unsafe { flatbuffers::root_unchecked::<Monster<'a>>(buf) }
+}
+
+#[inline]
+#[deprecated(since="2.0.0", note="Deprecated in favor of `root_as...` methods.")]
+pub fn get_size_prefixed_root_as_monster<'a>(buf: &'a [u8]) -> Monster<'a> {
+ unsafe { flatbuffers::size_prefixed_root_unchecked::<Monster<'a>>(buf) }
+}
+
+#[inline]
+/// Verifies that a buffer of bytes contains a `Monster`
+/// and returns it.
+/// Note that verification is still experimental and may not
+/// catch every error, or be maximally performant. For the
+/// previous, unchecked, behavior use
+/// `root_as_monster_unchecked`.
+pub fn root_as_monster(buf: &[u8]) -> Result<Monster, flatbuffers::InvalidFlatbuffer> {
+ flatbuffers::root::<Monster>(buf)
+}
+#[inline]
+/// Verifies that a buffer of bytes contains a size prefixed
+/// `Monster` and returns it.
+/// Note that verification is still experimental and may not
+/// catch every error, or be maximally performant. For the
+/// previous, unchecked, behavior use
+/// `size_prefixed_root_as_monster_unchecked`.
+pub fn size_prefixed_root_as_monster(buf: &[u8]) -> Result<Monster, flatbuffers::InvalidFlatbuffer> {
+ flatbuffers::size_prefixed_root::<Monster>(buf)
+}
+#[inline]
+/// Verifies, with the given options, that a buffer of bytes
+/// contains a `Monster` and returns it.
+/// Note that verification is still experimental and may not
+/// catch every error, or be maximally performant. For the
+/// previous, unchecked, behavior use
+/// `root_as_monster_unchecked`.
+pub fn root_as_monster_with_opts<'b, 'o>(
+ opts: &'o flatbuffers::VerifierOptions,
+ buf: &'b [u8],
+) -> Result<Monster<'b>, flatbuffers::InvalidFlatbuffer> {
+ flatbuffers::root_with_opts::<Monster<'b>>(opts, buf)
+}
+#[inline]
+/// Verifies, with the given verifier options, that a buffer of
+/// bytes contains a size prefixed `Monster` and returns
+/// it. Note that verification is still experimental and may not
+/// catch every error, or be maximally performant. For the
+/// previous, unchecked, behavior use
+/// `root_as_monster_unchecked`.
+pub fn size_prefixed_root_as_monster_with_opts<'b, 'o>(
+ opts: &'o flatbuffers::VerifierOptions,
+ buf: &'b [u8],
+) -> Result<Monster<'b>, flatbuffers::InvalidFlatbuffer> {
+ flatbuffers::size_prefixed_root_with_opts::<Monster<'b>>(opts, buf)
+}
+#[inline]
+/// Assumes, without verification, that a buffer of bytes contains a Monster and returns it.
+/// # Safety
+/// Callers must trust the given bytes do indeed contain a valid `Monster`.
+pub unsafe fn root_as_monster_unchecked(buf: &[u8]) -> Monster {
+ flatbuffers::root_unchecked::<Monster>(buf)
+}
+#[inline]
+/// Assumes, without verification, that a buffer of bytes contains a size prefixed Monster and returns it.
+/// # Safety
+/// Callers must trust the given bytes do indeed contain a valid size prefixed `Monster`.
+pub unsafe fn size_prefixed_root_as_monster_unchecked(buf: &[u8]) -> Monster {
+ flatbuffers::size_prefixed_root_unchecked::<Monster>(buf)
+}
+#[inline]
+pub fn finish_monster_buffer<'a, 'b>(
+ fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,
+ root: flatbuffers::WIPOffset<Monster<'a>>) {
+ fbb.finish(root, None);
+}
+
+#[inline]
+pub fn finish_size_prefixed_monster_buffer<'a, 'b>(fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>, root: flatbuffers::WIPOffset<Monster<'a>>) {
+ fbb.finish_size_prefixed(root, None);
+}
diff --git a/samples/rust_generated/my_game/sample/vec_3_generated.rs b/samples/rust_generated/my_game/sample/vec_3_generated.rs
new file mode 100644
index 0000000..a1647d5
--- /dev/null
+++ b/samples/rust_generated/my_game/sample/vec_3_generated.rs
@@ -0,0 +1,185 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+// struct Vec3, aligned to 4
+#[repr(transparent)]
+#[derive(Clone, Copy, PartialEq)]
+pub struct Vec3(pub [u8; 12]);
+impl Default for Vec3 {
+ fn default() -> Self {
+ Self([0; 12])
+ }
+}
+impl std::fmt::Debug for Vec3 {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ f.debug_struct("Vec3")
+ .field("x", &self.x())
+ .field("y", &self.y())
+ .field("z", &self.z())
+ .finish()
+ }
+}
+
+impl flatbuffers::SimpleToVerifyInSlice for Vec3 {}
+impl flatbuffers::SafeSliceAccess for Vec3 {}
+impl<'a> flatbuffers::Follow<'a> for Vec3 {
+ type Inner = &'a Vec3;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ <&'a Vec3>::follow(buf, loc)
+ }
+}
+impl<'a> flatbuffers::Follow<'a> for &'a Vec3 {
+ type Inner = &'a Vec3;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ flatbuffers::follow_cast_ref::<Vec3>(buf, loc)
+ }
+}
+impl<'b> flatbuffers::Push for Vec3 {
+ type Output = Vec3;
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ let src = unsafe {
+ ::std::slice::from_raw_parts(self as *const Vec3 as *const u8, Self::size())
+ };
+ dst.copy_from_slice(src);
+ }
+}
+impl<'b> flatbuffers::Push for &'b Vec3 {
+ type Output = Vec3;
+
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ let src = unsafe {
+ ::std::slice::from_raw_parts(*self as *const Vec3 as *const u8, Self::size())
+ };
+ dst.copy_from_slice(src);
+ }
+}
+
+impl<'a> flatbuffers::Verifiable for Vec3 {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ v.in_buffer::<Self>(pos)
+ }
+}
+
+impl<'a> Vec3 {
+ #[allow(clippy::too_many_arguments)]
+ pub fn new(
+ x: f32,
+ y: f32,
+ z: f32,
+ ) -> Self {
+ let mut s = Self([0; 12]);
+ s.set_x(x);
+ s.set_y(y);
+ s.set_z(z);
+ s
+ }
+
+ pub const fn get_fully_qualified_name() -> &'static str {
+ "MyGame.Sample.Vec3"
+ }
+
+ pub fn x(&self) -> f32 {
+ let mut mem = core::mem::MaybeUninit::<f32>::uninit();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ self.0[0..].as_ptr(),
+ mem.as_mut_ptr() as *mut u8,
+ core::mem::size_of::<f32>(),
+ );
+ mem.assume_init()
+ }.from_little_endian()
+ }
+
+ pub fn set_x(&mut self, x: f32) {
+ let x_le = x.to_little_endian();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ &x_le as *const f32 as *const u8,
+ self.0[0..].as_mut_ptr(),
+ core::mem::size_of::<f32>(),
+ );
+ }
+ }
+
+ pub fn y(&self) -> f32 {
+ let mut mem = core::mem::MaybeUninit::<f32>::uninit();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ self.0[4..].as_ptr(),
+ mem.as_mut_ptr() as *mut u8,
+ core::mem::size_of::<f32>(),
+ );
+ mem.assume_init()
+ }.from_little_endian()
+ }
+
+ pub fn set_y(&mut self, x: f32) {
+ let x_le = x.to_little_endian();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ &x_le as *const f32 as *const u8,
+ self.0[4..].as_mut_ptr(),
+ core::mem::size_of::<f32>(),
+ );
+ }
+ }
+
+ pub fn z(&self) -> f32 {
+ let mut mem = core::mem::MaybeUninit::<f32>::uninit();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ self.0[8..].as_ptr(),
+ mem.as_mut_ptr() as *mut u8,
+ core::mem::size_of::<f32>(),
+ );
+ mem.assume_init()
+ }.from_little_endian()
+ }
+
+ pub fn set_z(&mut self, x: f32) {
+ let x_le = x.to_little_endian();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ &x_le as *const f32 as *const u8,
+ self.0[8..].as_mut_ptr(),
+ core::mem::size_of::<f32>(),
+ );
+ }
+ }
+
+ pub fn unpack(&self) -> Vec3T {
+ Vec3T {
+ x: self.x(),
+ y: self.y(),
+ z: self.z(),
+ }
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Default)]
+pub struct Vec3T {
+ pub x: f32,
+ pub y: f32,
+ pub z: f32,
+}
+impl Vec3T {
+ pub fn pack(&self) -> Vec3 {
+ Vec3::new(
+ self.x,
+ self.y,
+ self.z,
+ )
+ }
+}
+
diff --git a/samples/rust_generated/my_game/sample/weapon_generated.rs b/samples/rust_generated/my_game/sample/weapon_generated.rs
new file mode 100644
index 0000000..50a678b
--- /dev/null
+++ b/samples/rust_generated/my_game/sample/weapon_generated.rs
@@ -0,0 +1,157 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+pub enum WeaponOffset {}
+#[derive(Copy, Clone, PartialEq)]
+
+pub struct Weapon<'a> {
+ pub _tab: flatbuffers::Table<'a>,
+}
+
+impl<'a> flatbuffers::Follow<'a> for Weapon<'a> {
+ type Inner = Weapon<'a>;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ Self { _tab: flatbuffers::Table { buf, loc } }
+ }
+}
+
+impl<'a> Weapon<'a> {
+ pub const VT_NAME: flatbuffers::VOffsetT = 4;
+ pub const VT_DAMAGE: flatbuffers::VOffsetT = 6;
+
+ pub const fn get_fully_qualified_name() -> &'static str {
+ "MyGame.Sample.Weapon"
+ }
+
+ #[inline]
+ pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
+ Weapon { _tab: table }
+ }
+ #[allow(unused_mut)]
+ pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
+ _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
+ args: &'args WeaponArgs<'args>
+ ) -> flatbuffers::WIPOffset<Weapon<'bldr>> {
+ let mut builder = WeaponBuilder::new(_fbb);
+ if let Some(x) = args.name { builder.add_name(x); }
+ builder.add_damage(args.damage);
+ builder.finish()
+ }
+
+ pub fn unpack(&self) -> WeaponT {
+ let name = self.name().map(|x| {
+ x.to_string()
+ });
+ let damage = self.damage();
+ WeaponT {
+ name,
+ damage,
+ }
+ }
+
+ #[inline]
+ pub fn name(&self) -> Option<&'a str> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<&str>>(Weapon::VT_NAME, None)
+ }
+ #[inline]
+ pub fn damage(&self) -> i16 {
+ self._tab.get::<i16>(Weapon::VT_DAMAGE, Some(0)).unwrap()
+ }
+}
+
+impl flatbuffers::Verifiable for Weapon<'_> {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ v.visit_table(pos)?
+ .visit_field::<flatbuffers::ForwardsUOffset<&str>>("name", Self::VT_NAME, false)?
+ .visit_field::<i16>("damage", Self::VT_DAMAGE, false)?
+ .finish();
+ Ok(())
+ }
+}
+pub struct WeaponArgs<'a> {
+ pub name: Option<flatbuffers::WIPOffset<&'a str>>,
+ pub damage: i16,
+}
+impl<'a> Default for WeaponArgs<'a> {
+ #[inline]
+ fn default() -> Self {
+ WeaponArgs {
+ name: None,
+ damage: 0,
+ }
+ }
+}
+
+pub struct WeaponBuilder<'a: 'b, 'b> {
+ fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
+ start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
+}
+impl<'a: 'b, 'b> WeaponBuilder<'a, 'b> {
+ #[inline]
+ pub fn add_name(&mut self, name: flatbuffers::WIPOffset<&'b str>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Weapon::VT_NAME, name);
+ }
+ #[inline]
+ pub fn add_damage(&mut self, damage: i16) {
+ self.fbb_.push_slot::<i16>(Weapon::VT_DAMAGE, damage, 0);
+ }
+ #[inline]
+ pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> WeaponBuilder<'a, 'b> {
+ let start = _fbb.start_table();
+ WeaponBuilder {
+ fbb_: _fbb,
+ start_: start,
+ }
+ }
+ #[inline]
+ pub fn finish(self) -> flatbuffers::WIPOffset<Weapon<'a>> {
+ let o = self.fbb_.end_table(self.start_);
+ flatbuffers::WIPOffset::new(o.value())
+ }
+}
+
+impl std::fmt::Debug for Weapon<'_> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let mut ds = f.debug_struct("Weapon");
+ ds.field("name", &self.name());
+ ds.field("damage", &self.damage());
+ ds.finish()
+ }
+}
+#[non_exhaustive]
+#[derive(Debug, Clone, PartialEq)]
+pub struct WeaponT {
+ pub name: Option<String>,
+ pub damage: i16,
+}
+impl Default for WeaponT {
+ fn default() -> Self {
+ Self {
+ name: None,
+ damage: 0,
+ }
+ }
+}
+impl WeaponT {
+ pub fn pack<'b>(
+ &self,
+ _fbb: &mut flatbuffers::FlatBufferBuilder<'b>
+ ) -> flatbuffers::WIPOffset<Weapon<'b>> {
+ let name = self.name.as_ref().map(|x|{
+ _fbb.create_string(x)
+ });
+ let damage = self.damage;
+ Weapon::create(_fbb, &WeaponArgs{
+ name,
+ damage,
+ })
+ }
+}
diff --git a/samples/sample_binary.lobster b/samples/sample_binary.lobster
index cd7adab..3c4851d 100644
--- a/samples/sample_binary.lobster
+++ b/samples/sample_binary.lobster
@@ -54,7 +54,7 @@
.end()
// Finish the buffer!
-b.Finish(orc)
+b.Finish(orc, "MONS")
// We now have a FlatBuffer that we could store on disk or send over a network.
diff --git a/samples/sample_binary.py b/samples/sample_binary.py
index 96711fb..cd250a9 100644
--- a/samples/sample_binary.py
+++ b/samples/sample_binary.py
@@ -55,13 +55,13 @@
# Note: Since we prepend the bytes, this loop iterates in reverse order.
for i in reversed(range(0, 10)):
builder.PrependByte(i)
- inv = builder.EndVector(10)
+ inv = builder.EndVector()
MyGame.Sample.Monster.MonsterStartWeaponsVector(builder, 2)
# Note: Since we prepend the data, prepend the weapons in reverse order.
builder.PrependUOffsetTRelative(axe)
builder.PrependUOffsetTRelative(sword)
- weapons = builder.EndVector(2)
+ weapons = builder.EndVector()
pos = MyGame.Sample.Vec3.CreateVec3(builder, 1.0, 2.0, 3.0)
diff --git a/samples/sample_binary.rs b/samples/sample_binary.rs
index 6fb987e..2f010b8 100644
--- a/samples/sample_binary.rs
+++ b/samples/sample_binary.rs
@@ -18,21 +18,21 @@
extern crate flatbuffers;
// import the generated code
-#[path = "./monster_generated.rs"]
-mod monster_generated;
-pub use monster_generated::my_game::sample::{get_root_as_monster,
- Color, Equipment,
+#[allow(dead_code, unused_imports)]
+#[allow(clippy::approx_constant)] // We use low precision PI as a default value.
+mod rust_generated;
+pub use rust_generated::my_game::sample::{Color, Equipment,
Monster, MonsterArgs,
Vec3,
Weapon, WeaponArgs};
// Example how to use FlatBuffers to create and read binary buffers.
-
+#[allow(clippy::float_cmp)]
fn main() {
// Build up a serialized buffer algorithmically.
// Initialize it with a capacity of 1024 bytes.
- let mut builder = flatbuffers::FlatBufferBuilder::new_with_capacity(1024);
+ let mut builder = flatbuffers::FlatBufferBuilder::with_capacity(1024);
// Serialize some weapons for the Monster: A 'sword' and an 'axe'.
let weapon_one_name = builder.create_string("Sword");
@@ -71,7 +71,7 @@
// Create the monster using the `Monster::create` helper function. This
// function accepts a `MonsterArgs` struct, which supplies all of the data
// needed to build a `Monster`. To supply empty/default fields, just use the
- // Rust built-in `Default::default()` function, as demononstrated below.
+ // Rust built-in `Default::default()` function, as demonstrated below.
let orc = Monster::create(&mut builder, &MonsterArgs{
pos: Some(&Vec3::new(1.0f32, 2.0f32, 3.0f32)),
mana: 150,
@@ -98,7 +98,7 @@
let buf = builder.finished_data(); // Of type `&[u8]`
// Get access to the root:
- let monster = get_root_as_monster(buf);
+ let monster = flatbuffers::root::<Monster>(buf).unwrap();
// Get and test some scalar types from the FlatBuffer.
let hp = monster.hp();
diff --git a/samples/sample_binary.swift b/samples/sample_binary.swift
index 46ab99b..889bc98 100644
--- a/samples/sample_binary.swift
+++ b/samples/sample_binary.swift
@@ -1,5 +1,5 @@
/*
- * Copyright 2020 Google Inc. All rights reserved.
+ * Copyright 2021 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.
@@ -16,10 +16,10 @@
import FlatBuffers
-typealias Monster = MyGame.Sample.Monster
-typealias Weapon = MyGame.Sample.Weapon
-typealias Color = MyGame.Sample.Color
-typealias Vec3 = MyGame.Sample.Vec3
+typealias Monster = MyGame_Sample_Monster
+typealias Weapon = MyGame_Sample_Weapon
+typealias Color = MyGame_Sample_Color
+typealias Vec3 = MyGame_Sample_Vec3
func main() {
let expectedDMG: [Int16] = [3, 5]
@@ -43,18 +43,17 @@
let inventoryOffset = builder.createVector(inventory)
let weaponsOffset = builder.createVector(ofOffsets: [sword, axe])
- let pos = MyGame.Sample.createVec3(x: 1, y: 2, z: 3)
let orc = Monster.createMonster(
&builder,
- structOfPos: pos,
+ pos: MyGame_Sample_Vec3(x: 1, y: 2, z: 3),
hp: 300,
- offsetOfName: name,
- vectorOfInventory: inventoryOffset,
+ nameOffset: name,
+ inventoryVectorOffset: inventoryOffset,
color: .red,
- vectorOfWeapons: weaponsOffset,
+ weaponsVectorOffset: weaponsOffset,
equippedType: .weapon,
- offsetOfEquipped: axe)
+ equippedOffset: axe)
builder.finish(offset: orc)
let buf = builder.sizedByteArray
@@ -65,6 +64,7 @@
assert(monster.name == "Orc")
assert(monster.color == MyGame.Sample.Color.red)
assert(monster.pos != nil)
+ assert(monster.mutablePos != nil)
for i in 0..<monster.inventoryCount {
assert(i == monster.inventory(at: i))
}
diff --git a/samples/sample_flexbuffers.rs b/samples/sample_flexbuffers.rs
index efe02c3..074a200 100644
--- a/samples/sample_flexbuffers.rs
+++ b/samples/sample_flexbuffers.rs
@@ -16,7 +16,6 @@
use flexbuffers::{BitWidth, Builder, Reader, ReaderError};
-
// In this Example we're creating a monster that corresponds to the following JSON:
// {
// "coins": [5, 10, 25, 25, 25, 100],
@@ -31,6 +30,7 @@
// {"damage": 15, "name": "great axe"},
// {"damage": 5, "name": "hammer"}]
// }
+#[allow(clippy::float_cmp)]
fn main() {
// Create a new Flexbuffer builder.
let mut builder = Builder::default();
@@ -148,24 +148,6 @@
.iter()
.map(|r| r.as_u8())
.eq(vec![5, 10, 25, 25, 25, 100].into_iter()));
- // For very speed sensitive applications, you can directly read the slice if all of the
- // following are true:
- //
- // * The provided data buffer contains a valid flexbuffer.
- // * You correctly specify the flexbuffer type and width.
- // * The host machine is little endian.
- // * The provided data buffer itself is aligned in memory to 8 bytes.
- //
- // Vec<u8> has alignment 1 so special care is needed to get your buffer's alignment to 8.
- #[cfg(target_endian = "little")]
- {
- if monster_coins.is_aligned() {
- assert_eq!(
- monster_coins.get_slice::<i8>().unwrap(),
- &[5, 10, 25, 25, 25, 100]
- );
- }
- }
// Build the answer to life the universe and everything. Reusing a builder resets it. The
// reused internals won't need to reallocate leading to a potential 2x speedup.
diff --git a/samples/samplebinary.js b/samples/samplebinary.js
deleted file mode 100644
index 9c8c908..0000000
--- a/samples/samplebinary.js
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * Copyright 2015 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.
- */
-
-// To run, use the `javascript_sample.sh` script.
-
-var assert = require('assert');
-var flatbuffers = require('../js/flatbuffers').flatbuffers;
-var MyGame = require('./monster_generated').MyGame;
-
-// Example how to use FlatBuffers to create and read binary buffers.
-function main() {
- var builder = new flatbuffers.Builder(0);
-
- // Create some weapons for our Monster ('Sword' and 'Axe').
- var weaponOne = builder.createString('Sword');
- var weaponTwo = builder.createString('Axe');
-
- MyGame.Sample.Weapon.startWeapon(builder);
- MyGame.Sample.Weapon.addName(builder, weaponOne);
- MyGame.Sample.Weapon.addDamage(builder, 3);
- var sword = MyGame.Sample.Weapon.endWeapon(builder);
-
- MyGame.Sample.Weapon.startWeapon(builder);
- MyGame.Sample.Weapon.addName(builder, weaponTwo);
- MyGame.Sample.Weapon.addDamage(builder, 5);
- var axe = MyGame.Sample.Weapon.endWeapon(builder);
-
- // Serialize the FlatBuffer data.
- var name = builder.createString('Orc');
-
- var treasure = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
- var inv = MyGame.Sample.Monster.createInventoryVector(builder, treasure);
-
- var weaps = [sword, axe];
- var weapons = MyGame.Sample.Monster.createWeaponsVector(builder, weaps);
-
- var pos = MyGame.Sample.Vec3.createVec3(builder, 1.0, 2.0, 3.0);
-
- MyGame.Sample.Monster.startMonster(builder);
- MyGame.Sample.Monster.addPos(builder, pos);
- MyGame.Sample.Monster.addHp(builder, 300);
- MyGame.Sample.Monster.addColor(builder, MyGame.Sample.Color.Red)
- MyGame.Sample.Monster.addName(builder, name);
- MyGame.Sample.Monster.addInventory(builder, inv);
- MyGame.Sample.Monster.addWeapons(builder, weapons);
- MyGame.Sample.Monster.addEquippedType(builder, MyGame.Sample.Equipment.Weapon);
- MyGame.Sample.Monster.addEquipped(builder, weaps[1]);
- var orc = MyGame.Sample.Monster.endMonster(builder);
-
- builder.finish(orc); // You may also call 'MyGame.Example.Monster.finishMonsterBuffer(builder, orc);'.
-
- // We now have a FlatBuffer that can be stored on disk or sent over a network.
-
- // ...Code to store to disk or send over a network goes here...
-
- // Instead, we are going to access it right away, as if we just received it.
-
- var buf = builder.dataBuffer();
-
- // Get access to the root:
- var monster = MyGame.Sample.Monster.getRootAsMonster(buf);
-
- // Note: We did not set the `mana` field explicitly, so we get back the default value.
- assert.equal(monster.mana(), 150);
- assert.equal(monster.hp(), 300);
- assert.equal(monster.name(), 'Orc');
- assert.equal(monster.color(), MyGame.Sample.Color.Red);
- assert.equal(monster.pos().x(), 1.0);
- assert.equal(monster.pos().y(), 2.0);
- assert.equal(monster.pos().z(), 3.0);
-
- // Get and test the `inventory` FlatBuffer `vector`.
- for (var i = 0; i < monster.inventoryLength(); i++) {
- assert.equal(monster.inventory(i), i);
- }
-
- // Get and test the `weapons` FlatBuffer `vector` of `table`s.
- var expectedWeaponNames = ['Sword', 'Axe'];
- var expectedWeaponDamages = [3, 5];
- for (var i = 0; i < monster.weaponsLength(); i++) {
- assert.equal(monster.weapons(i).name(), expectedWeaponNames[i]);
- assert.equal(monster.weapons(i).damage(), expectedWeaponDamages[i]);
- }
-
- // Get and test the `equipped` FlatBuffer `union`.
- assert.equal(monster.equippedType(), MyGame.Sample.Equipment.Weapon);
- assert.equal(monster.equipped(new MyGame.Sample.Weapon()).name(), 'Axe');
- assert.equal(monster.equipped(new MyGame.Sample.Weapon()).damage(), 5);
-
- console.log('The FlatBuffer was successfully created and verified!');
-}
-
-main();
diff --git a/scripts/check-grpc-generated-code.sh b/scripts/check-grpc-generated-code.sh
new file mode 100755
index 0000000..4541be1
--- /dev/null
+++ b/scripts/check-grpc-generated-code.sh
@@ -0,0 +1,32 @@
+#!/bin/bash
+#
+# Copyright 2021 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.
+set -e
+
+echo "Checks generated grpc code"
+cd grpc/examples
+sh generate.sh
+cd ..
+
+if ! git diff --quiet; then
+ echo >&2
+ echo "ERROR: ********************************************************" >&2
+ echo "ERROR: The following differences were found after running the" >&2
+ echo "ERROR: grpc/example/generate.sh script. Maybe you forgot to run" >&2
+ echo "ERROR: it after making changes in a generator or schema?" >&2
+ echo "ERROR: ********************************************************" >&2
+ echo >&2
+ git diff --binary --exit-code
+fi
diff --git a/scripts/check_generate_code.py b/scripts/check_generate_code.py
new file mode 100755
index 0000000..038dc4e
--- /dev/null
+++ b/scripts/check_generate_code.py
@@ -0,0 +1,63 @@
+#!/usr/bin/env python3
+#
+# Copyright 2021 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.
+
+import platform
+import subprocess
+import sys
+from pathlib import Path
+
+# Get the path where this script is located so we can invoke the script from
+# any directory and have the paths work correctly.
+script_path = Path(__file__).parent.resolve()
+
+# Get the root path as an absolute path, so all derived paths are absolute.
+root_path = script_path.parent.absolute()
+
+result = subprocess.run(["git", "diff", "--quiet"], cwd=root_path)
+
+if result.returncode != 0:
+ print(
+ "\n"
+ "ERROR: *********************************************************\n"
+ "ERROR: * The following differences were found after building. *\n"
+ "ERROR: * Perhaps there is a difference in the flags for the. *\n"
+ "ERROR: * CMakeLists.txt vs the script/generate_code.py script? *\n"
+ "ERROR: *********************************************************\n"
+ )
+ subprocess.run(["git", "diff", "--binary", "--exit-code"], cwd=root_path)
+ sys.exit(result.returncode)
+
+# Rung the generate_code.py script, forwarding arguments
+gen_cmd = ["scripts/generate_code.py"] + sys.argv[1:]
+if platform.system() == "Windows":
+ gen_cmd = ["py"] + gen_cmd
+subprocess.run(gen_cmd, cwd=root_path)
+
+result = subprocess.run(["git", "diff", "--quiet"], cwd=root_path)
+
+if result.returncode != 0:
+ print(
+ "\n"
+ "ERROR: ********************************************************\n"
+ "ERROR: * The following differences were found after running *\n"
+ "ERROR: * the script/generate_code.py script. Maybe you forgot *\n"
+ "ERROR: * to run it after making changes in a generator? *\n"
+ "ERROR: ********************************************************\n"
+ )
+ subprocess.run(["git", "diff", "--binary", "--exit-code"], cwd=root_path)
+ sys.exit(result.returncode)
+
+sys.exit(0)
diff --git a/scripts/clang-format-all.sh b/scripts/clang-format-all.sh
new file mode 100755
index 0000000..d8aa7be
--- /dev/null
+++ b/scripts/clang-format-all.sh
@@ -0,0 +1,6 @@
+# Running it twice corrects some bugs in clang-format.
+for run in {1..2}
+do
+ clang-format -i include/flatbuffers/* src/*.cpp tests/*.cpp samples/*.cpp grpc/src/compiler/schema_interface.h grpc/tests/*.cpp
+done
+git checkout include/flatbuffers/reflection_generated.h
diff --git a/scripts/clang-format-git.sh b/scripts/clang-format-git.sh
new file mode 100755
index 0000000..b962d61
--- /dev/null
+++ b/scripts/clang-format-git.sh
@@ -0,0 +1,6 @@
+# Running it twice corrects some bugs in clang-format.
+for run in {1..2}
+do
+ git clang-format HEAD^ -- include/flatbuffers/* src/*.cpp tests/*.cpp samples/*.cpp grpc/src/compiler/schema_interface.h grpc/tests/*.cpp -f
+done
+git checkout include/flatbuffers/reflection_generated.h
diff --git a/scripts/generate_code.py b/scripts/generate_code.py
new file mode 100755
index 0000000..9871c0d
--- /dev/null
+++ b/scripts/generate_code.py
@@ -0,0 +1,453 @@
+#!/usr/bin/env python3
+#
+# Copyright 2021 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.
+
+import argparse
+import filecmp
+import glob
+import platform
+import shutil
+import subprocess
+import sys
+from pathlib import Path
+
+parser = argparse.ArgumentParser()
+parser.add_argument(
+ "--flatc",
+ help="path of the Flat C compiler relative to the root directory",
+)
+parser.add_argument("--cpp-0x", action="store_true", help="use --cpp-std c++ox")
+parser.add_argument(
+ "--skip-monster-extra",
+ action="store_true",
+ help="skip generating tests involving monster_extra.fbs",
+)
+parser.add_argument(
+ "--skip-gen-reflection",
+ action="store_true",
+ help="skip generating the reflection.fbs files",
+)
+args = parser.parse_args()
+
+# Get the path where this script is located so we can invoke the script from
+# any directory and have the paths work correctly.
+script_path = Path(__file__).parent.resolve()
+
+# Get the root path as an absolute path, so all derived paths are absolute.
+root_path = script_path.parent.absolute()
+
+# Get the location of the flatc executable, reading from the first command line
+# argument or defaulting to default names.
+flatc_exe = Path(
+ ("flatc" if not platform.system() == "Windows" else "flatc.exe")
+ if not args.flatc
+ else args.flatc
+)
+
+# Find and assert flatc compiler is present.
+if root_path in flatc_exe.parents:
+ flatc_exe = flatc_exe.relative_to(root_path)
+flatc_path = Path(root_path, flatc_exe)
+assert flatc_path.exists(), "Cannot find the flatc compiler " + str(flatc_path)
+
+# Specify the other paths that will be referenced
+tests_path = Path(root_path, "tests")
+samples_path = Path(root_path, "samples")
+reflection_path = Path(root_path, "reflection")
+
+# Execute the flatc compiler with the specified parameters
+def flatc(
+ options, schema, prefix=None, include=None, data=None, cwd=tests_path
+):
+ cmd = [str(flatc_path)] + options
+ if prefix:
+ cmd += ["-o"] + [prefix]
+ if include:
+ cmd += ["-I"] + [include]
+ cmd += [schema] if isinstance(schema, str) else schema
+ if data:
+ cmd += [data] if isinstance(data, str) else data
+ result = subprocess.run(cmd, cwd=str(cwd), check=True)
+
+
+# Generate the code for flatbuffers reflection schema
+def flatc_reflection(options, location, target):
+ full_options = ["--no-prefix"] + options
+ temp_dir = ".tmp"
+ flatc(
+ full_options,
+ prefix=temp_dir,
+ schema="reflection.fbs",
+ cwd=reflection_path,
+ )
+ new_reflection_path = Path(reflection_path, temp_dir, target)
+ original_reflection_path = Path(root_path, location, target)
+ if not filecmp.cmp(str(new_reflection_path), str(original_reflection_path)):
+ shutil.rmtree(str(original_reflection_path))
+ shutil.move(str(new_reflection_path), str(original_reflection_path))
+ shutil.rmtree(str(Path(reflection_path, temp_dir)))
+
+
+# Glob a pattern relative to file path
+def glob(path, pattern):
+ return [str(p) for p in path.glob(pattern)]
+
+
+# flatc options that are shared
+BASE_OPTS = ["--reflect-names", "--gen-mutable", "--gen-object-api"]
+NO_INCL_OPTS = BASE_OPTS + ["--no-includes"]
+
+# Language specific options
+CS_OPTS = ["--csharp", "--cs-gen-json-serializer"]
+CPP_OPTS = [
+ "--cpp",
+ "--gen-compare",
+ "--cpp-ptr-type",
+ "flatbuffers::unique_ptr",
+] + (["--cpp-std", "c++0x"] if args.cpp_0x else [])
+
+CPP_17_OPTS = NO_INCL_OPTS + [
+ "--cpp",
+ "--cpp-std",
+ "c++17",
+ "--cpp-static-reflection",
+ "--gen-object-api",
+]
+RUST_OPTS = BASE_OPTS + ["--rust", "--gen-all", "--gen-name-strings", "--rust-module-root-file"]
+RUST_SERIALIZE_OPTS = BASE_OPTS + [
+ "--rust",
+ "--gen-all",
+ "--gen-name-strings",
+ "--rust-serialize",
+ "--rust-module-root-file",
+]
+TS_OPTS = ["--ts", "--gen-name-strings"]
+LOBSTER_OPTS = ["--lobster"]
+SWIFT_OPTS = ["--swift", "--gen-json-emit", "--bfbs-filenames", str(tests_path)]
+JAVA_OPTS = ["--java"]
+KOTLIN_OPTS = ["--kotlin"]
+PHP_OPTS = ["--php"]
+DART_OPTS = ["--dart"]
+PYTHON_OPTS = ["--python"]
+BINARY_OPTS = ["-b", "--schema", "--bfbs-comments", "--bfbs-builtins"]
+
+# Basic Usage
+
+flatc(
+ NO_INCL_OPTS
+ + CPP_OPTS
+ + CS_OPTS
+ + TS_OPTS
+ + [
+ "--binary",
+ "--java",
+ "--kotlin",
+ "--dart",
+ "--go",
+ "--lobster",
+ "--php",
+ ],
+ schema="monster_test.fbs",
+ include="include_test",
+ data="monsterdata_test.json",
+)
+
+flatc(
+ ["--lua", "--bfbs-filenames", str(tests_path)],
+ schema="monster_test.fbs",
+ include="include_test",
+)
+
+flatc(
+ NO_INCL_OPTS + CPP_OPTS + ["--grpc"],
+ schema="monster_test.fbs",
+ include="include_test",
+ data="monsterdata_test.json",
+)
+
+flatc(
+ RUST_OPTS,
+ schema="monster_test.fbs",
+ include="include_test",
+ prefix="monster_test",
+ data="monsterdata_test.json",
+)
+
+flatc(
+ RUST_SERIALIZE_OPTS,
+ schema="monster_test.fbs",
+ include="include_test",
+ prefix="monster_test_serialize",
+ data="monsterdata_test.json",
+)
+
+flatc(
+ options=BASE_OPTS + ["--python"],
+ schema="monster_test.fbs",
+ include="include_test",
+ data="monsterdata_test.json",
+)
+
+flatc(
+ options=BASE_OPTS + ["--python", "--gen-onefile"],
+ schema="monster_test.fbs",
+ include="include_test",
+ data="monsterdata_test.json",
+)
+
+# For Rust we currently generate two independent schemas, with namespace_test2
+# duplicating the types in namespace_test1
+flatc(
+ RUST_OPTS,
+ prefix="namespace_test",
+ schema=[
+ "namespace_test/namespace_test1.fbs",
+ "namespace_test/namespace_test2.fbs",
+ ],
+)
+
+flatc(
+ BASE_OPTS
+ + CPP_OPTS
+ + CS_OPTS
+ + TS_OPTS
+ + JAVA_OPTS
+ + KOTLIN_OPTS
+ + PHP_OPTS,
+ prefix="union_vector",
+ schema="union_vector/union_vector.fbs",
+)
+
+flatc(
+ BASE_OPTS + TS_OPTS + ["--gen-name-strings", "--gen-mutable"],
+ include="include_test",
+ schema="monster_test.fbs",
+)
+
+flatc(
+ BASE_OPTS + TS_OPTS + ["-b"],
+ include="include_test",
+ schema="monster_test.fbs",
+ data="unicode_test.json",
+)
+
+flatc(
+ BASE_OPTS + TS_OPTS + ["--gen-name-strings"],
+ prefix="union_vector",
+ schema="union_vector/union_vector.fbs",
+)
+
+flatc(
+ RUST_OPTS,
+ prefix="include_test1",
+ include="include_test",
+ schema="include_test/include_test1.fbs",
+)
+
+flatc(
+ RUST_OPTS,
+ prefix="include_test2",
+ include="include_test",
+ schema="include_test/sub/include_test2.fbs",
+)
+
+flatc(
+ BINARY_OPTS + ["--bfbs-filenames", str(tests_path)],
+ include="include_test",
+ schema="monster_test.fbs",
+)
+
+flatc(
+ CPP_OPTS
+ + NO_INCL_OPTS
+ + [
+ "--bfbs-comments",
+ "--bfbs-builtins",
+ "--bfbs-gen-embed",
+ "--bfbs-filenames",
+ str(tests_path),
+ ],
+ include="include_test",
+ schema="monster_test.fbs",
+)
+
+flatc(
+ BINARY_OPTS + ["--bfbs-filenames", str(tests_path)],
+ include="include_test",
+ schema="arrays_test.fbs",
+)
+
+flatc(
+ ["--jsonschema", "--schema"],
+ include="include_test",
+ schema="monster_test.fbs",
+)
+
+if not args.skip_monster_extra:
+ flatc(
+ CPP_OPTS
+ + CS_OPTS
+ + NO_INCL_OPTS
+ + JAVA_OPTS
+ + KOTLIN_OPTS
+ + PYTHON_OPTS,
+ schema="monster_extra.fbs",
+ data="monsterdata_extra.json",
+ )
+
+ flatc(
+ DART_OPTS + ["--gen-object-api"],
+ schema="monster_extra.fbs",
+ )
+
+flatc(
+ CPP_OPTS
+ + CS_OPTS
+ + NO_INCL_OPTS
+ + JAVA_OPTS
+ + ["--jsonschema", "--scoped-enums"],
+ schema="arrays_test.fbs",
+)
+
+flatc(
+ RUST_OPTS,
+ prefix="arrays_test",
+ schema="arrays_test.fbs",
+)
+
+flatc(
+ BASE_OPTS + PYTHON_OPTS,
+ schema="arrays_test.fbs",
+)
+
+
+# Optional Scalars
+optional_scalars_schema = "optional_scalars.fbs"
+flatc(
+ ["--java", "--kotlin", "--lobster", "--ts"], schema=optional_scalars_schema
+)
+
+flatc(["--csharp", "--gen-object-api"], schema=optional_scalars_schema)
+
+flatc(RUST_OPTS, prefix="optional_scalars", schema=optional_scalars_schema)
+
+flatc(NO_INCL_OPTS + CPP_OPTS, schema=optional_scalars_schema)
+
+# Generate string/vector default code for tests
+flatc(RUST_OPTS, prefix="more_defaults", schema="more_defaults.fbs")
+
+# Generate the schema evolution tests
+flatc(
+ CPP_OPTS + ["--scoped-enums"],
+ prefix="evolution_test",
+ schema=glob(tests_path, "evolution_test/evolution_v*.fbs"),
+)
+
+# Generate the keywords tests
+flatc(BASE_OPTS + CS_OPTS, schema="keyword_test.fbs")
+flatc(RUST_OPTS, prefix="keyword_test", schema="keyword_test.fbs")
+flatc(
+ BASE_OPTS + CS_OPTS + ["--cs-global-alias", "--gen-onefile"],
+ prefix="nested_namespace_test",
+ schema=glob(tests_path, "nested_namespace_test/nested_namespace_test*.fbs"),
+)
+
+# Swift Tests
+swift_prefix = "FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests"
+flatc(
+ SWIFT_OPTS + NO_INCL_OPTS + ["--grpc"],
+ schema="monster_test.fbs",
+ include="include_test",
+ prefix=swift_prefix,
+)
+flatc(
+ SWIFT_OPTS + BASE_OPTS,
+ schema="union_vector/union_vector.fbs",
+ prefix=swift_prefix,
+)
+flatc(SWIFT_OPTS, schema="optional_scalars.fbs", prefix=swift_prefix)
+flatc(
+ SWIFT_OPTS + ["--gen-object-api"],
+ schema="more_defaults.fbs",
+ prefix=swift_prefix,
+)
+flatc(
+ SWIFT_OPTS + BASE_OPTS,
+ schema="MutatingBool.fbs",
+ prefix=swift_prefix,
+)
+
+# --filename-suffix and --filename-ext tests
+flatc(
+ CPP_OPTS
+ + NO_INCL_OPTS
+ + ["--filename-suffix", "_suffix", "--filename-ext", "hpp"],
+ include="include_test",
+ schema="monster_test.fbs",
+)
+orig_monster_file = Path(tests_path, "monster_test_generated.h")
+new_monster_file = Path(tests_path, "monster_test_suffix.hpp")
+assert (
+ new_monster_file.exists()
+), "filename suffix option did not produce a file"
+assert filecmp.cmp(
+ str(orig_monster_file), str(new_monster_file)
+), "filename suffix option did not produce identical results"
+new_monster_file.unlink()
+
+# Flag c++17 requires Clang6, GCC7, MSVC2017 (_MSC_VER >= 1914) or higher.
+cpp_17_prefix = "cpp17/generated_cpp17"
+flatc(
+ CPP_17_OPTS,
+ schema="monster_test.fbs",
+ include="include_test",
+ prefix=cpp_17_prefix,
+)
+flatc(
+ CPP_17_OPTS,
+ schema="optional_scalars.fbs",
+ prefix=cpp_17_prefix,
+)
+flatc(
+ CPP_17_OPTS,
+ schema="union_vector/union_vector.fbs",
+ prefix=cpp_17_prefix,
+)
+
+# Sample files
+samples_schema = "monster.fbs"
+flatc(
+ BASE_OPTS + CPP_OPTS + LOBSTER_OPTS, schema=samples_schema, cwd=samples_path
+)
+flatc(
+ RUST_OPTS, prefix="rust_generated", schema=samples_schema, cwd=samples_path
+)
+flatc(
+ BINARY_OPTS + ["--bfbs-filenames", str(samples_path)],
+ schema=samples_schema,
+ cwd=samples_path,
+)
+
+# Reflection
+
+# Skip generating the reflection if told too, as we run this script after
+# building flatc which uses the reflection_generated.h itself.
+if not args.skip_gen_reflection:
+ # C++ Reflection
+ flatc_reflection(["-c", "--cpp-std", "c++0x"], "include/flatbuffers",
+ "reflection_generated.h")
+
+# Python Reflection
+flatc_reflection(["-p"], "python/flatbuffers", "reflection")
diff --git a/snap/snapcraft.yaml b/snap/snapcraft.yaml
index c0bc939..98640c3 100644
--- a/snap/snapcraft.yaml
+++ b/snap/snapcraft.yaml
@@ -1,6 +1,6 @@
name: flatbuffers
base: core18
-version: git
+adopt-info: flatc
summary: FlatBuffers compiler
description: |
FlatBuffers compiler
@@ -26,10 +26,24 @@
- -DCMAKE_BUILD_TYPE=Release
build-packages:
- g++
+ - git
+ override-pull: |
+ snapcraftctl pull
+ tag=$(git describe --tags --abbrev=0)
+ count=$(git rev-list $tag.. --count)
+ if [ "$count" = 0 ];
+ then
+ version=$tag
+ else
+ hash=$(git rev-parse --short HEAD)
+ version=$tag+git$count.$hash
+ fi
+ snapcraftctl set-version $version
+
apps:
flatc:
- command: flatc
+ command: bin/flatc
plugs:
- home
- removable-media
diff --git a/src/BUILD b/src/BUILD
deleted file mode 100644
index 471d5da..0000000
--- a/src/BUILD
+++ /dev/null
@@ -1,76 +0,0 @@
-package(
- default_visibility = ["//visibility:private"],
-)
-
-load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library")
-
-# Public flatc library to compile flatbuffer files at runtime.
-cc_library(
- name = "flatbuffers",
- srcs = [
- "code_generators.cpp",
- "idl_gen_fbs.cpp",
- "idl_gen_text.cpp",
- "idl_parser.cpp",
- "reflection.cpp",
- "util.cpp",
- ],
- hdrs = ["//:public_headers"],
- strip_include_prefix = "/include",
- visibility = ["//:__pkg__"],
-)
-
-# Public flatc compiler library.
-cc_library(
- name = "flatc_library",
- srcs = [
- "flatc.cpp",
- ],
- hdrs = [
- "//:flatc_headers",
- ],
- strip_include_prefix = "/include",
- visibility = ["//:__pkg__"],
- deps = [
- ":flatbuffers",
- ],
-)
-
-# Public flatc compiler.
-cc_library(
- name = "flatc",
- srcs = [
- "flatc_main.cpp",
- "idl_gen_cpp.cpp",
- "idl_gen_csharp.cpp",
- "idl_gen_dart.cpp",
- "idl_gen_go.cpp",
- "idl_gen_grpc.cpp",
- "idl_gen_java.cpp",
- "idl_gen_js_ts.cpp",
- "idl_gen_json_schema.cpp",
- "idl_gen_kotlin.cpp",
- "idl_gen_lobster.cpp",
- "idl_gen_lua.cpp",
- "idl_gen_php.cpp",
- "idl_gen_python.cpp",
- "idl_gen_rust.cpp",
- "idl_gen_swift.cpp",
- "idl_gen_text.cpp",
- "util.cpp",
- ],
- hdrs = [
- "//:flatc_headers",
- ],
- strip_include_prefix = "/include",
- visibility = ["//:__pkg__"],
- deps = [
- ":flatc_library",
- "//grpc/src/compiler:cpp_generator",
- "//grpc/src/compiler:go_generator",
- "//grpc/src/compiler:java_generator",
- "//grpc/src/compiler:python_generator",
- "//grpc/src/compiler:swift_generator",
- "//grpc/src/compiler:ts_generator",
- ],
-)
diff --git a/src/BUILD.bazel b/src/BUILD.bazel
new file mode 100644
index 0000000..d8bbfcd
--- /dev/null
+++ b/src/BUILD.bazel
@@ -0,0 +1,93 @@
+# @unused
+load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library")
+
+package(
+ default_visibility = ["//visibility:private"],
+)
+
+# Public flatc library to compile flatbuffer files at runtime.
+cc_library(
+ name = "flatbuffers",
+ srcs = [
+ "code_generators.cpp",
+ "idl_gen_fbs.cpp",
+ "idl_gen_text.cpp",
+ "idl_parser.cpp",
+ "reflection.cpp",
+ "util.cpp",
+ ],
+ hdrs = ["//:public_headers"],
+ linkopts = select({
+ # TODO: Bazel uses `clang` instead of `clang++` to link
+ # C++ code on BSD. Temporarily adding these linker flags while
+ # we wait for Bazel to resolve
+ # https://github.com/bazelbuild/bazel/issues/12023.
+ "//:platform_freebsd": ["-lm"],
+ "//:platform_openbsd": ["-lm"],
+ "//conditions:default": [],
+ }),
+ strip_include_prefix = "/include",
+ visibility = ["//:__pkg__"],
+)
+
+# Public flatc compiler library.
+cc_library(
+ name = "flatc_library",
+ srcs = [
+ "bfbs_gen.h",
+ "bfbs_gen_lua.cpp",
+ "bfbs_gen_lua.h",
+ "flatc.cpp",
+ ],
+ hdrs = [
+ "//:flatc_headers",
+ ],
+ strip_include_prefix = "/include",
+ visibility = ["//:__pkg__"],
+ deps = [
+ ":flatbuffers",
+ ],
+)
+
+# Public flatc compiler.
+cc_library(
+ name = "flatc",
+ srcs = [
+ "bfbs_gen.h",
+ "bfbs_gen_lua.cpp",
+ "bfbs_gen_lua.h",
+ "flatc_main.cpp",
+ "idl_gen_cpp.cpp",
+ "idl_gen_csharp.cpp",
+ "idl_gen_dart.cpp",
+ "idl_gen_go.cpp",
+ "idl_gen_grpc.cpp",
+ "idl_gen_java.cpp",
+ "idl_gen_json_schema.cpp",
+ "idl_gen_kotlin.cpp",
+ "idl_gen_lobster.cpp",
+ "idl_gen_lua.cpp",
+ "idl_gen_php.cpp",
+ "idl_gen_python.cpp",
+ "idl_gen_rust.cpp",
+ "idl_gen_swift.cpp",
+ "idl_gen_text.cpp",
+ "idl_gen_ts.cpp",
+ "namer.h",
+ "util.cpp",
+ ],
+ hdrs = [
+ "//:flatc_headers",
+ ],
+ strip_include_prefix = "/include",
+ visibility = ["//:__pkg__"],
+ deps = [
+ ":flatc_library",
+ "//grpc/src/compiler:cpp_generator",
+ "//grpc/src/compiler:go_generator",
+ "//grpc/src/compiler:java_generator",
+ "//grpc/src/compiler:python_generator",
+ "//grpc/src/compiler:swift_generator",
+ "//grpc/src/compiler:ts_generator",
+ ],
+)
diff --git a/src/bfbs_gen.h b/src/bfbs_gen.h
new file mode 100644
index 0000000..12aafb3
--- /dev/null
+++ b/src/bfbs_gen.h
@@ -0,0 +1,210 @@
+/*
+ * Copyright 2021 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_BFBS_GEN_H_
+#define FLATBUFFERS_BFBS_GEN_H_
+
+#include <cstdint>
+
+#include "flatbuffers/bfbs_generator.h"
+#include "flatbuffers/reflection_generated.h"
+
+namespace flatbuffers {
+
+void ForAllEnums(
+ const flatbuffers::Vector<flatbuffers::Offset<reflection::Enum>> *enums,
+ std::function<void(const reflection::Enum *)> func) {
+ for (auto it = enums->cbegin(); it != enums->cend(); ++it) { func(*it); }
+}
+
+void ForAllObjects(
+ const flatbuffers::Vector<flatbuffers::Offset<reflection::Object>> *objects,
+ std::function<void(const reflection::Object *)> func) {
+ for (auto it = objects->cbegin(); it != objects->cend(); ++it) { func(*it); }
+}
+
+void ForAllEnumValues(const reflection::Enum *enum_def,
+ std::function<void(const reflection::EnumVal *)> func) {
+ for (auto it = enum_def->values()->cbegin(); it != enum_def->values()->cend();
+ ++it) {
+ func(*it);
+ }
+}
+
+void ForAllDocumentation(
+ const flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>
+ *documentation,
+ std::function<void(const flatbuffers::String *)> func) {
+ if (!documentation) { return; }
+ for (auto it = documentation->cbegin(); it != documentation->cend(); ++it) {
+ func(*it);
+ }
+}
+
+// Maps the field index into object->fields() to the field's ID (the ith element
+// in the return vector).
+static std::vector<uint32_t> FieldIdToIndex(const reflection::Object *object) {
+ std::vector<uint32_t> field_index_by_id;
+ field_index_by_id.resize(object->fields()->size());
+
+ // Create the mapping of field ID to the index into the vector.
+ for (uint32_t i = 0; i < object->fields()->size(); ++i) {
+ auto field = object->fields()->Get(i);
+ field_index_by_id[field->id()] = i;
+ }
+
+ return field_index_by_id;
+}
+
+static bool IsStructOrTable(const reflection::BaseType base_type) {
+ return base_type == reflection::Obj;
+}
+
+static bool IsScalar(const reflection::BaseType base_type) {
+ return base_type >= reflection::UType && base_type <= reflection::Double;
+}
+
+static bool IsFloatingPoint(const reflection::BaseType base_type) {
+ return base_type == reflection::Float || base_type == reflection::Double;
+}
+
+static bool IsBool(const reflection::BaseType base_type) {
+ return base_type == reflection::Bool;
+}
+
+static bool IsSingleByte(const reflection::BaseType base_type) {
+ return base_type >= reflection::UType && base_type <= reflection::UByte;
+}
+
+static bool IsVector(const reflection::BaseType base_type) {
+ return base_type == reflection::Vector;
+}
+
+static std::string Denamespace(const flatbuffers::String *name,
+ std::string &ns) {
+ const size_t pos = name->str().find_last_of('.');
+ if (pos == std::string::npos) {
+ ns = "";
+ return name->str();
+ }
+ ns = name->str().substr(0, pos);
+ return name->str().substr(pos + 1);
+}
+
+static std::string Denamespace(const flatbuffers::String *name) {
+ std::string ns;
+ return Denamespace(name, ns);
+}
+
+// A concrete base Flatbuffer Generator that specific language generators can
+// derive from.
+class BaseBfbsGenerator : public BfbsGenerator {
+ public:
+ virtual ~BaseBfbsGenerator() {}
+ BaseBfbsGenerator() : schema_(nullptr) {}
+
+ virtual GeneratorStatus GenerateFromSchema(
+ const reflection::Schema *schema) = 0;
+
+ //
+ virtual uint64_t SupportedAdvancedFeatures() const = 0;
+
+ // Override of the Generator::generate method that does the initial
+ // deserialization and verification steps.
+ GeneratorStatus Generate(const uint8_t *buffer,
+ int64_t length) FLATBUFFERS_OVERRIDE {
+ flatbuffers::Verifier verifier(buffer, static_cast<size_t>(length));
+ if (!reflection::VerifySchemaBuffer(verifier)) {
+ return FAILED_VERIFICATION;
+ }
+
+ // Store the root schema since there are cases where leaf nodes refer to
+ // things in the root schema (e.g., indexing the objects).
+ schema_ = reflection::GetSchema(buffer);
+
+ const uint64_t advance_features = schema_->advanced_features();
+ if (advance_features > SupportedAdvancedFeatures()) {
+ return FAILED_VERIFICATION;
+ }
+
+ GeneratorStatus status = GenerateFromSchema(schema_);
+ schema_ = nullptr;
+ return status;
+ }
+
+ protected:
+ const reflection::Object *GetObject(const reflection::Type *type) const {
+ if (type->index() >= 0 && IsStructOrTable(type->base_type())) {
+ return GetObjectByIndex(type->index());
+ }
+ return nullptr;
+ }
+
+ const reflection::Enum *GetEnum(const reflection::Type *type) const {
+ // TODO(derekbailey): it would be better to have a explicit list of allowed
+ // base types, instead of negating Obj types.
+ if (type->index() >= 0 && !IsStructOrTable(type->base_type())) {
+ return GetEnumByIndex(type->index());
+ }
+ return nullptr;
+ }
+
+ // Used to get a object that is reference by index. (e.g.
+ // reflection::Type::index). Returns nullptr if no object is available.
+ const reflection::Object *GetObjectByIndex(int32_t index) const {
+ if (!schema_ || index < 0 ||
+ index >= static_cast<int32_t>(schema_->objects()->size())) {
+ return nullptr;
+ }
+ return schema_->objects()->Get(index);
+ }
+
+ // Used to get a enum that is reference by index. (e.g.
+ // reflection::Type::index). Returns nullptr if no enum is available.
+ const reflection::Enum *GetEnumByIndex(int32_t index) const {
+ if (!schema_ || index < 0 ||
+ index >= static_cast<int32_t>(schema_->enums()->size())) {
+ return nullptr;
+ }
+ return schema_->enums()->Get(index);
+ }
+
+ void ForAllFields(const reflection::Object *object, bool reverse,
+ std::function<void(const reflection::Field *)> func) const {
+ const std::vector<uint32_t> field_to_id_map = FieldIdToIndex(object);
+ for (size_t i = 0; i < field_to_id_map.size(); ++i) {
+ func(object->fields()->Get(
+ field_to_id_map[reverse ? field_to_id_map.size() - (i + 1) : i]));
+ }
+ }
+
+ bool IsTable(const reflection::Type *type, bool use_element = false) const {
+ return !IsStruct(type, use_element);
+ }
+
+ bool IsStruct(const reflection::Type *type, bool use_element = false) const {
+ const reflection::BaseType base_type =
+ use_element ? type->element() : type->base_type();
+ return IsStructOrTable(base_type) &&
+ GetObjectByIndex(type->index())->is_struct();
+ }
+
+ const reflection::Schema *schema_;
+};
+
+} // namespace flatbuffers
+
+#endif // FLATBUFFERS_BFBS_GEN_H_
\ No newline at end of file
diff --git a/src/bfbs_gen_lua.cpp b/src/bfbs_gen_lua.cpp
new file mode 100644
index 0000000..868bb14
--- /dev/null
+++ b/src/bfbs_gen_lua.cpp
@@ -0,0 +1,628 @@
+/*
+ * Copyright 2021 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.
+ */
+
+#include "bfbs_gen_lua.h"
+
+#include <cstdint>
+#include <map>
+#include <memory>
+#include <string>
+#include <unordered_set>
+#include <vector>
+
+// Ensure no includes to flatc internals. bfbs_gen.h and generator.h are OK.
+#include "bfbs_gen.h"
+#include "flatbuffers/bfbs_generator.h"
+
+// The intermediate representation schema.
+#include "flatbuffers/reflection_generated.h"
+
+namespace flatbuffers {
+namespace {
+
+// To reduce typing
+namespace r = ::reflection;
+
+class LuaBfbsGenerator : public BaseBfbsGenerator {
+ public:
+ explicit LuaBfbsGenerator(const std::string &flatc_version)
+ : BaseBfbsGenerator(),
+ keywords_(),
+ requires_(),
+ current_obj_(nullptr),
+ current_enum_(nullptr),
+ flatc_version_(flatc_version) {
+ static const char *const keywords[] = {
+ "and", "break", "do", "else", "elseif", "end", "false", "for",
+ "function", "goto", "if", "in", "local", "nil", "not", "or",
+ "repeat", "return", "then", "true", "until", "while"
+ };
+ keywords_.insert(std::begin(keywords), std::end(keywords));
+ }
+
+ GeneratorStatus GenerateFromSchema(const r::Schema *schema)
+ FLATBUFFERS_OVERRIDE {
+ if (!GenerateEnums(schema->enums())) { return FAILED; }
+ if (!GenerateObjects(schema->objects(), schema->root_table())) {
+ return FAILED;
+ }
+ return OK;
+ }
+
+ uint64_t SupportedAdvancedFeatures() const FLATBUFFERS_OVERRIDE {
+ return 0xF;
+ }
+
+ protected:
+ bool GenerateEnums(
+ const flatbuffers::Vector<flatbuffers::Offset<r::Enum>> *enums) {
+ ForAllEnums(enums, [&](const r::Enum *enum_def) {
+ std::string code;
+
+ StartCodeBlock(enum_def);
+
+ std::string ns;
+ const std::string enum_name =
+ NormalizeName(Denamespace(enum_def->name(), ns));
+
+ GenerateDocumentation(enum_def->documentation(), "", code);
+ code += "local " + enum_name + " = {\n";
+
+ ForAllEnumValues(enum_def, [&](const reflection::EnumVal *enum_val) {
+ GenerateDocumentation(enum_val->documentation(), " ", code);
+ code += " " + NormalizeName(enum_val->name()) + " = " +
+ NumToString(enum_val->value()) + ",\n";
+ });
+ code += "}\n";
+ code += "\n";
+
+ EmitCodeBlock(code, enum_name, ns, enum_def->declaration_file()->str());
+ });
+ return true;
+ }
+
+ bool GenerateObjects(
+ const flatbuffers::Vector<flatbuffers::Offset<r::Object>> *objects,
+ const r::Object *root_object) {
+ ForAllObjects(objects, [&](const r::Object *object) {
+ std::string code;
+
+ StartCodeBlock(object);
+
+ // Register the main flatbuffers module.
+ RegisterRequires("flatbuffers", "flatbuffers");
+
+ std::string ns;
+ const std::string object_name =
+ NormalizeName(Denamespace(object->name(), ns));
+
+ GenerateDocumentation(object->documentation(), "", code);
+
+ code += "local " + object_name + " = {}\n";
+ code += "local mt = {}\n";
+ code += "\n";
+ code += "function " + object_name + ".New()\n";
+ code += " local o = {}\n";
+ code += " setmetatable(o, {__index = mt})\n";
+ code += " return o\n";
+ code += "end\n";
+ code += "\n";
+
+ if (object == root_object) {
+ code += "function " + object_name + ".GetRootAs" + object_name +
+ "(buf, offset)\n";
+ code += " if type(buf) == \"string\" then\n";
+ code += " buf = flatbuffers.binaryArray.New(buf)\n";
+ code += " end\n";
+ code += "\n";
+ code += " local n = flatbuffers.N.UOffsetT:Unpack(buf, offset)\n";
+ code += " local o = " + object_name + ".New()\n";
+ code += " o:Init(buf, n + offset)\n";
+ code += " return o\n";
+ code += "end\n";
+ code += "\n";
+ }
+
+ // Generates a init method that receives a pre-existing accessor object,
+ // so that objects can be reused.
+
+ code += "function mt:Init(buf, pos)\n";
+ code += " self.view = flatbuffers.view.New(buf, pos)\n";
+ code += "end\n";
+ code += "\n";
+
+ // Create all the field accessors.
+ ForAllFields(object, /*reverse=*/false, [&](const r::Field *field) {
+ // Skip writing deprecated fields altogether.
+ if (field->deprecated()) { return; }
+
+ const std::string field_name = NormalizeName(field->name());
+ const std::string field_name_camel_case =
+ ConvertCase(field_name, Case::kUpperCamel);
+ const r::BaseType base_type = field->type()->base_type();
+
+ // Generate some fixed strings so we don't repeat outselves later.
+ const std::string getter_signature =
+ "function mt:" + field_name_camel_case + "()\n";
+ const std::string offset_prefix = "local o = self.view:Offset(" +
+ NumToString(field->offset()) + ")\n";
+ const std::string offset_prefix_2 = "if o ~= 0 then\n";
+
+ GenerateDocumentation(field->documentation(), "", code);
+
+ if (IsScalar(base_type)) {
+ code += getter_signature;
+
+ if (object->is_struct()) {
+ // TODO(derekbailey): it would be nice to modify the view:Get to
+ // just pass in the offset and not have to add it its own
+ // self.view.pos.
+ code += " return " + GenerateGetter(field->type()) +
+ "self.view.pos + " + NumToString(field->offset()) + ")\n";
+ } else {
+ // Table accessors
+ code += " " + offset_prefix;
+ code += " " + offset_prefix_2;
+
+ std::string getter =
+ GenerateGetter(field->type()) + "self.view.pos + o)";
+ if (IsBool(base_type)) { getter = "(" + getter + " ~=0)"; }
+ code += " return " + getter + "\n";
+ code += " end\n";
+ code += " return " + DefaultValue(field) + "\n";
+ }
+ code += "end\n";
+ code += "\n";
+ } else {
+ switch (base_type) {
+ case r::String: {
+ code += getter_signature;
+ code += " " + offset_prefix;
+ code += " " + offset_prefix_2;
+ code += " return " + GenerateGetter(field->type()) +
+ "self.view.pos + o)\n";
+ code += " end\n";
+ code += "end\n";
+ code += "\n";
+ break;
+ }
+ case r::Obj: {
+ if (object->is_struct()) {
+ code += "function mt:" + field_name_camel_case + "(obj)\n";
+ code += " obj:Init(self.view.bytes, self.view.pos + " +
+ NumToString(field->offset()) + ")\n";
+ code += " return obj\n";
+ code += "end\n";
+ code += "\n";
+ } else {
+ code += getter_signature;
+ code += " " + offset_prefix;
+ code += " " + offset_prefix_2;
+
+ const r::Object *field_object = GetObject(field->type());
+ if (!field_object) {
+ // TODO(derekbailey): this is an error condition. we
+ // should report it better.
+ return;
+ }
+ code += " local x = " +
+ std::string(
+ field_object->is_struct()
+ ? "self.view.pos + o\n"
+ : "self.view:Indirect(self.view.pos + o)\n");
+ const std::string require_name = RegisterRequires(field);
+ code += " local obj = " + require_name + ".New()\n";
+ code += " obj:Init(self.view.bytes, x)\n";
+ code += " return obj\n";
+ code += " end\n";
+ code += "end\n";
+ code += "\n";
+ }
+ break;
+ }
+ case r::Union: {
+ code += getter_signature;
+ code += " " + offset_prefix;
+ code += " " + offset_prefix_2;
+ code +=
+ " local obj = "
+ "flatbuffers.view.New(flatbuffers.binaryArray.New("
+ "0), 0)\n";
+ code += " " + GenerateGetter(field->type()) + "obj, o)\n";
+ code += " return obj\n";
+ code += " end\n";
+ code += "end\n";
+ code += "\n";
+ break;
+ }
+ case r::Array:
+ case r::Vector: {
+ const r::BaseType vector_base_type = field->type()->element();
+ int32_t element_size = field->type()->element_size();
+ code += "function mt:" + field_name_camel_case + "(j)\n";
+ code += " " + offset_prefix;
+ code += " " + offset_prefix_2;
+
+ if (IsStructOrTable(vector_base_type)) {
+ code += " local x = self.view:Vector(o)\n";
+ code +=
+ " x = x + ((j-1) * " + NumToString(element_size) + ")\n";
+ if (IsTable(field->type(), /*use_element=*/true)) {
+ code += " x = self.view:Indirect(x)\n";
+ } else {
+ // Vector of structs are inline, so we need to query the
+ // size of the struct.
+ const reflection::Object *obj =
+ GetObjectByIndex(field->type()->index());
+ element_size = obj->bytesize();
+ }
+
+ // Include the referenced type, thus we need to make sure
+ // we set `use_element` to true.
+ const std::string require_name =
+ RegisterRequires(field, /*use_element=*/true);
+ code += " local obj = " + require_name + ".New()\n";
+ code += " obj:Init(self.view.bytes, x)\n";
+ code += " return obj\n";
+ } else {
+ code += " local a = self.view:Vector(o)\n";
+ code += " return " + GenerateGetter(field->type()) +
+ "a + ((j-1) * " + NumToString(element_size) + "))\n";
+ }
+ code += " end\n";
+ // Only generate a default value for those types that are
+ // supported.
+ if (!IsStructOrTable(vector_base_type)) {
+ code +=
+ " return " +
+ std::string(vector_base_type == r::String ? "''\n" : "0\n");
+ }
+ code += "end\n";
+ code += "\n";
+
+ // If the vector is composed of single byte values, we
+ // generate a helper function to get it as a byte string in
+ // Lua.
+ if (IsSingleByte(vector_base_type)) {
+ code += "function mt:" + field_name_camel_case +
+ "AsString(start, stop)\n";
+ code += " return self.view:VectorAsString(" +
+ NumToString(field->offset()) + ", start, stop)\n";
+ code += "end\n";
+ code += "\n";
+ }
+
+ // We also make a new accessor to query just the length of the
+ // vector.
+ code += "function mt:" + field_name_camel_case + "Length()\n";
+ code += " " + offset_prefix;
+ code += " " + offset_prefix_2;
+ code += " return self.view:VectorLen(o)\n";
+ code += " end\n";
+ code += " return 0\n";
+ code += "end\n";
+ code += "\n";
+ break;
+ }
+ default: {
+ return;
+ }
+ }
+ }
+ return;
+ });
+
+ // Create all the builders
+ if (object->is_struct()) {
+ code += "function " + object_name + ".Create" + object_name +
+ "(builder" + GenerateStructBuilderArgs(object) + ")\n";
+ code += AppendStructBuilderBody(object);
+ code += " return builder:Offset()\n";
+ code += "end\n";
+ code += "\n";
+ } else {
+ // Table builders
+ code += "function " + object_name + ".Start(builder)\n";
+ code += " builder:StartObject(" +
+ NumToString(object->fields()->size()) + ")\n";
+ code += "end\n";
+ code += "\n";
+
+ ForAllFields(object, /*reverse=*/false, [&](const r::Field *field) {
+ if (field->deprecated()) { return; }
+
+ const std::string field_name = NormalizeName(field->name());
+
+ code += "function " + object_name + ".Add" +
+ ConvertCase(field_name, Case::kUpperCamel) + "(builder, " +
+ ConvertCase(field_name, Case::kLowerCamel) + ")\n";
+ code += " builder:Prepend" + GenerateMethod(field) + "Slot(" +
+ NumToString(field->id()) + ", " +
+ ConvertCase(field_name, Case::kLowerCamel) + ", " +
+ DefaultValue(field) + ")\n";
+ code += "end\n";
+ code += "\n";
+
+ if (IsVector(field->type()->base_type())) {
+ code += "function " + object_name + ".Start" +
+ ConvertCase(field_name, Case::kUpperCamel) +
+ "Vector(builder, numElems)\n";
+
+ const int32_t element_size = field->type()->element_size();
+ int32_t alignment = 0;
+ if (IsStruct(field->type(), /*use_element=*/true)) {
+ alignment = GetObjectByIndex(field->type()->index())->minalign();
+ } else {
+ alignment = element_size;
+ }
+
+ code += " return builder:StartVector(" +
+ NumToString(element_size) + ", numElems, " +
+ NumToString(alignment) + ")\n";
+ code += "end\n";
+ code += "\n";
+ }
+ });
+
+ code += "function " + object_name + ".End(builder)\n";
+ code += " return builder:EndObject()\n";
+ code += "end\n";
+ code += "\n";
+ }
+
+ EmitCodeBlock(code, object_name, ns, object->declaration_file()->str());
+ });
+ return true;
+ }
+
+ private:
+ void GenerateDocumentation(
+ const flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>
+ *documentation,
+ std::string indent, std::string &code) const {
+ flatbuffers::ForAllDocumentation(
+ documentation, [&](const flatbuffers::String *str) {
+ code += indent + "--" + str->str() + "\n";
+ });
+ }
+
+ std::string GenerateStructBuilderArgs(const r::Object *object,
+ std::string prefix = "") const {
+ std::string signature;
+ ForAllFields(object, /*reverse=*/false, [&](const r::Field *field) {
+ if (IsStructOrTable(field->type()->base_type())) {
+ const r::Object *field_object = GetObject(field->type());
+ signature += GenerateStructBuilderArgs(
+ field_object, prefix + NormalizeName(field->name()) + "_");
+ } else {
+ signature +=
+ ", " + prefix +
+ ConvertCase(NormalizeName(field->name()), Case::kLowerCamel);
+ }
+ });
+ return signature;
+ }
+
+ std::string AppendStructBuilderBody(const r::Object *object,
+ std::string prefix = "") const {
+ std::string code;
+ code += " builder:Prep(" + NumToString(object->minalign()) + ", " +
+ NumToString(object->bytesize()) + ")\n";
+
+ // We need to reverse the order we iterate over, since we build the
+ // buffer backwards.
+ ForAllFields(object, /*reverse=*/true, [&](const r::Field *field) {
+ const int32_t num_padding_bytes = field->padding();
+ if (num_padding_bytes) {
+ code += " builder:Pad(" + NumToString(num_padding_bytes) + ")\n";
+ }
+ if (IsStructOrTable(field->type()->base_type())) {
+ const r::Object *field_object = GetObject(field->type());
+ code += AppendStructBuilderBody(
+ field_object, prefix + NormalizeName(field->name()) + "_");
+ } else {
+ code += " builder:Prepend" + GenerateMethod(field) + "(" + prefix +
+ ConvertCase(NormalizeName(field->name()), Case::kLowerCamel) +
+ ")\n";
+ }
+ });
+
+ return code;
+ }
+
+ std::string GenerateMethod(const r::Field *field) const {
+ const r::BaseType base_type = field->type()->base_type();
+ if (IsScalar(base_type)) {
+ return ConvertCase(GenerateType(base_type), Case::kUpperCamel);
+ }
+ if (IsStructOrTable(base_type)) { return "Struct"; }
+ return "UOffsetTRelative";
+ }
+
+ std::string GenerateGetter(const r::Type *type,
+ bool element_type = false) const {
+ switch (element_type ? type->element() : type->base_type()) {
+ case r::String: return "self.view:String(";
+ case r::Union: return "self.view:Union(";
+ case r::Vector: return GenerateGetter(type, true);
+ default:
+ return "self.view:Get(flatbuffers.N." +
+ ConvertCase(GenerateType(type, element_type),
+ Case::kUpperCamel) +
+ ", ";
+ }
+ }
+
+ std::string GenerateType(const r::Type *type,
+ bool element_type = false) const {
+ const r::BaseType base_type =
+ element_type ? type->element() : type->base_type();
+ if (IsScalar(base_type)) { return GenerateType(base_type); }
+ switch (base_type) {
+ case r::String: return "string";
+ case r::Vector: return GenerateGetter(type, true);
+ case r::Obj: {
+ const r::Object *obj = GetObject(type);
+ return NormalizeName(Denamespace(obj->name()));
+ };
+ default: return "*flatbuffers.Table";
+ }
+ }
+
+ std::string GenerateType(const r::BaseType base_type) const {
+ // Need to override the default naming to match the Lua runtime libraries.
+ // TODO(derekbailey): make overloads in the runtime libraries to avoid this.
+ switch (base_type) {
+ case r::None: return "uint8";
+ case r::UType: return "uint8";
+ case r::Byte: return "int8";
+ case r::UByte: return "uint8";
+ case r::Short: return "int16";
+ case r::UShort: return "uint16";
+ case r::Int: return "int32";
+ case r::UInt: return "uint32";
+ case r::Long: return "int64";
+ case r::ULong: return "uint64";
+ case r::Float: return "Float32";
+ case r::Double: return "Float64";
+ default: return r::EnumNameBaseType(base_type);
+ }
+ }
+
+ std::string DefaultValue(const r::Field *field) const {
+ const r::BaseType base_type = field->type()->base_type();
+ if (IsFloatingPoint(base_type)) {
+ return NumToString(field->default_real());
+ }
+ if (IsBool(base_type)) {
+ return field->default_integer() ? "true" : "false";
+ }
+ if (IsScalar(base_type)) { return NumToString((field->default_integer())); }
+ // represents offsets
+ return "0";
+ }
+
+ std::string NormalizeName(const std::string name) const {
+ return keywords_.find(name) == keywords_.end() ? name : "_" + name;
+ }
+
+ std::string NormalizeName(const flatbuffers::String *name) const {
+ return NormalizeName(name->str());
+ }
+
+ void StartCodeBlock(const reflection::Enum *enum_def) {
+ current_enum_ = enum_def;
+ current_obj_ = nullptr;
+ requires_.clear();
+ }
+
+ void StartCodeBlock(const reflection::Object *object) {
+ current_obj_ = object;
+ current_enum_ = nullptr;
+ requires_.clear();
+ }
+
+ std::string RegisterRequires(const r::Field *field,
+ bool use_element = false) {
+ std::string type_name;
+
+ const r::BaseType type =
+ use_element ? field->type()->element() : field->type()->base_type();
+
+ if (IsStructOrTable(type)) {
+ const r::Object *object = GetObjectByIndex(field->type()->index());
+ if (object == current_obj_) { return Denamespace(object->name()); }
+ type_name = object->name()->str();
+ } else {
+ const r::Enum *enum_def = GetEnumByIndex(field->type()->index());
+ if (enum_def == current_enum_) { return Denamespace(enum_def->name()); }
+ type_name = enum_def->name()->str();
+ }
+
+ // Prefix with double __ to avoid name clashing, since these are defined
+ // at the top of the file and have lexical scoping. Replace '.' with '_'
+ // so it can be a legal identifier.
+ std::string name = "__" + type_name;
+ std::replace(name.begin(), name.end(), '.', '_');
+
+ return RegisterRequires(name, type_name);
+ }
+
+ std::string RegisterRequires(const std::string &local_name,
+ const std::string &requires_name) {
+ requires_[local_name] = requires_name;
+ return local_name;
+ }
+
+ void EmitCodeBlock(const std::string &code_block, const std::string &name,
+ const std::string &ns,
+ const std::string &declaring_file) const {
+ const std::string root_type = schema_->root_table()->name()->str();
+ const std::string root_file =
+ schema_->root_table()->declaration_file()->str();
+ const std::string full_qualified_name = ns.empty() ? name : ns + "." + name;
+
+ std::string code = "--[[ " + full_qualified_name + "\n\n";
+ code +=
+ " Automatically generated by the FlatBuffers compiler, do not "
+ "modify.\n";
+ code += " Or modify. I'm a message, not a cop.\n";
+ code += "\n";
+ code += " flatc version: " + flatc_version_ + "\n";
+ code += "\n";
+ code += " Declared by : " + declaring_file + "\n";
+ code += " Rooting type : " + root_type + " (" + root_file + ")\n";
+ code += "\n--]]\n\n";
+
+ if (!requires_.empty()) {
+ for (auto it = requires_.cbegin(); it != requires_.cend(); ++it) {
+ code += "local " + it->first + " = require('" + it->second + "')\n";
+ }
+ code += "\n";
+ }
+
+ code += code_block;
+ code += "return " + name;
+
+ // Namespaces are '.' deliminted, so replace it with the path separator.
+ std::string path = ns;
+
+ if (path.empty()) {
+ path = ".";
+ } else {
+ std::replace(path.begin(), path.end(), '.', '/');
+ }
+
+ // TODO(derekbailey): figure out a save file without depending on util.h
+ EnsureDirExists(path);
+ const std::string file_name = path + "/" + name + ".lua";
+ SaveFile(file_name.c_str(), code, false);
+ }
+
+ std::unordered_set<std::string> keywords_;
+ std::map<std::string, std::string> requires_;
+ const r::Object *current_obj_;
+ const r::Enum *current_enum_;
+ const std::string flatc_version_;
+};
+} // namespace
+
+std::unique_ptr<BfbsGenerator> NewLuaBfbsGenerator(
+ const std::string &flatc_version) {
+ return std::unique_ptr<LuaBfbsGenerator>(new LuaBfbsGenerator(flatc_version));
+}
+
+} // namespace flatbuffers
\ No newline at end of file
diff --git a/src/bfbs_gen_lua.h b/src/bfbs_gen_lua.h
new file mode 100644
index 0000000..6861282
--- /dev/null
+++ b/src/bfbs_gen_lua.h
@@ -0,0 +1,33 @@
+/*
+ * Copyright 2021 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_BFBS_GEN_LUA_H_
+#define FLATBUFFERS_BFBS_GEN_LUA_H_
+
+#include <memory>
+#include <string>
+
+#include "flatbuffers/bfbs_generator.h"
+
+namespace flatbuffers {
+
+// Constructs a new Lua Code generator.
+std::unique_ptr<BfbsGenerator> NewLuaBfbsGenerator(
+ const std::string &flatc_version);
+
+} // namespace flatbuffers
+
+#endif // FLATBUFFERS_BFBS_GEN_LUA_H_
\ No newline at end of file
diff --git a/src/clang-format-all.sh b/src/clang-format-all.sh
deleted file mode 100644
index 3fd9e33..0000000
--- a/src/clang-format-all.sh
+++ /dev/null
@@ -1,6 +0,0 @@
-# Running it twice corrects some bugs in clang-format.
-for run in {1..2}
-do
- clang-format -i -style=file include/flatbuffers/* src/*.cpp tests/*.cpp samples/*.cpp grpc/src/compiler/schema_interface.h grpc/tests/*.cpp
-done
-git checkout include/flatbuffers/reflection_generated.h
diff --git a/src/clang-format-git.sh b/src/clang-format-git.sh
deleted file mode 100644
index 0611cbb..0000000
--- a/src/clang-format-git.sh
+++ /dev/null
@@ -1,6 +0,0 @@
-# Running it twice corrects some bugs in clang-format.
-for run in {1..2}
-do
- git clang-format HEAD^ -- include/flatbuffers/* src/*.cpp tests/*.cpp samples/*.cpp grpc/src/compiler/schema_interface.h grpc/tests/*.cpp
-done
-git checkout include/flatbuffers/reflection_generated.h
diff --git a/src/code_generators.cpp b/src/code_generators.cpp
index 46d65f7..269687d 100644
--- a/src/code_generators.cpp
+++ b/src/code_generators.cpp
@@ -60,7 +60,7 @@
// Update the text to everything after the }}.
text = text.substr(end + 2);
}
- if (!text.empty() && string_back(text) == '\\') {
+ if (!text.empty() && text.back() == '\\') {
text.pop_back();
ignore_ident_ = true;
stream_ << text;
@@ -84,20 +84,24 @@
std::string BaseGenerator::NamespaceDir(const Parser &parser,
const std::string &path,
- const Namespace &ns) {
+ const Namespace &ns,
+ const bool dasherize) {
EnsureDirExists(path);
if (parser.opts.one_file) return path;
std::string namespace_dir = path; // Either empty or ends in separator.
auto &namespaces = ns.components;
for (auto it = namespaces.begin(); it != namespaces.end(); ++it) {
- namespace_dir += *it + kPathSeparator;
+ namespace_dir +=
+ !dasherize ? *it : ConvertCase(*it, Case::kDasher, Case::kUpperCamel);
+ namespace_dir += kPathSeparator;
EnsureDirExists(namespace_dir);
}
return namespace_dir;
}
-std::string BaseGenerator::NamespaceDir(const Namespace &ns) const {
- return BaseGenerator::NamespaceDir(parser_, path_, ns);
+std::string BaseGenerator::NamespaceDir(const Namespace &ns,
+ const bool dasherize) const {
+ return BaseGenerator::NamespaceDir(parser_, path_, ns, dasherize);
}
std::string BaseGenerator::FullNamespace(const char *separator,
@@ -295,14 +299,10 @@
return this->NaN(static_cast<double>(v));
}
-std::string JavaCSharpMakeRule(const Parser &parser, const std::string &path,
+std::string JavaCSharpMakeRule(const bool java, const Parser &parser,
+ const std::string &path,
const std::string &file_name) {
- FLATBUFFERS_ASSERT(parser.opts.lang == IDLOptions::kJava ||
- parser.opts.lang == IDLOptions::kCSharp);
-
- std::string file_extension =
- (parser.opts.lang == IDLOptions::kJava) ? ".java" : ".cs";
-
+ const std::string file_extension = java ? ".java" : ".cs";
std::string make_rule;
for (auto it = parser.enums_.vec.begin(); it != parser.enums_.vec.end();
@@ -331,6 +331,15 @@
return make_rule;
}
+std::string JavaMakeRule(const Parser &parser, const std::string &path,
+ const std::string &file_name) {
+ return JavaCSharpMakeRule(true, parser, path, file_name);
+}
+std::string CSharpMakeRule(const Parser &parser, const std::string &path,
+ const std::string &file_name) {
+ return JavaCSharpMakeRule(false, parser, path, file_name);
+}
+
std::string BinaryFileName(const Parser &parser, const std::string &path,
const std::string &file_name) {
auto ext = parser.file_extension_.length() ? parser.file_extension_ : "bin";
diff --git a/src/flatc.cpp b/src/flatc.cpp
index 1233ff9..3b2ef9f 100644
--- a/src/flatc.cpp
+++ b/src/flatc.cpp
@@ -17,6 +17,9 @@
#include "flatbuffers/flatc.h"
#include <list>
+#include <sstream>
+
+#include "flatbuffers/util.h"
namespace flatbuffers {
@@ -56,129 +59,274 @@
params_.error_fn(this, err, usage, show_exe_name);
}
+const static FlatCOption options[] = {
+ { "o", "", "PATH", "Prefix PATH to all generated files." },
+ { "I", "", "PATH", "Search for includes in the specified path." },
+ { "M", "", "", "Print make rules for generated files." },
+ { "", "version", "", "Print the version number of flatc and exit." },
+ { "h", "help", "", "Prints this help text and exit." },
+ { "", "strict-json", "",
+ "Strict JSON: field names must be / will be quoted, no trailing commas in "
+ "tables/vectors." },
+ { "", "allow-non-utf8", "",
+ "Pass non-UTF-8 input through parser and emit nonstandard \\x escapes in "
+ "JSON. (Default is to raise parse error on non-UTF-8 input.)" },
+ { "", "natural-utf8", "",
+ "Output strings with UTF-8 as human-readable strings. By default, UTF-8 "
+ "characters are printed as \\uXXXX escapes." },
+ { "", "defaults-json", "",
+ "Output fields whose value is the default when writing JSON" },
+ { "", "unknown-json", "",
+ "Allow fields in JSON that are not defined in the schema. These fields "
+ "will be discared when generating binaries." },
+ { "", "no-prefix", "",
+ "Don't prefix enum values with the enum type in C++." },
+ { "", "scoped-enums", "",
+ "Use C++11 style scoped and strongly typed enums. Also implies "
+ "--no-prefix." },
+ { "", "gen-inclues", "",
+ "(deprecated), this is the default behavior. If the original behavior is "
+ "required (no include statements) use --no-includes." },
+ { "", "no-includes", "",
+ "Don't generate include statements for included schemas the generated "
+ "file depends on (C++, Python, Proto-to-Fbs)." },
+ { "", "gen-mutable", "",
+ "Generate accessors that can mutate buffers in-place." },
+ { "", "gen-onefile", "",
+ "Generate a single output file for C#, Go, Java, Kotlin and Python. "
+ "Implies --no-include." },
+ { "", "gen-name-strings", "",
+ "Generate type name functions for C++ and Rust." },
+ { "", "gen-object-api", "", "Generate an additional object-based API." },
+ { "", "gen-compare", "", "Generate operator== for object-based API types." },
+ { "", "gen-nullable", "",
+ "Add Clang _Nullable for C++ pointer. or @Nullable for Java" },
+ { "", "java-checkerframe", "", "Add @Pure for Java." },
+ { "", "gen-generated", "", "Add @Generated annotation for Java." },
+ { "", "gen-jvmstatic", "",
+ "Add @JvmStatic annotation for Kotlin methods in companion object for "
+ "interop from Java to Kotlin." },
+ { "", "gen-all", "",
+ "Generate not just code for the current schema files, but for all files it "
+ "includes as well. If the language uses a single file for output (by "
+ "default the case for C++ and JS), all code will end up in this one "
+ "file." },
+ { "", "gen-json-emit", "",
+ "Generates encoding code which emits Flatbuffers into JSON" },
+ { "", "cpp-include", "", "Adds an #include in generated file." },
+ { "", "cpp-ptr-type", "T",
+ "Set object API pointer type (default std::unique_ptr)." },
+ { "", "cpp-str-type", "T",
+ "Set object API string type (default std::string). T::c_str(), T::length() "
+ "and T::empty() must be supported. The custom type also needs to be "
+ "constructible from std::string (see the --cpp-str-flex-ctor option to "
+ "change this behavior)" },
+ { "", "cpp-str-flex-ctor", "",
+ "Don't construct custom string types by passing std::string from "
+ "Flatbuffers, but (char* + length)." },
+ { "", "cpp-field-case-style", "STYLE",
+ "Generate C++ fields using selected case style. Supported STYLE values: * "
+ "'unchanged' - leave unchanged (default) * 'upper' - schema snake_case "
+ "emits UpperCamel; * 'lower' - schema snake_case emits lowerCamel." },
+ { "", "cpp-std", "CPP_STD",
+ "Generate a C++ code using features of selected C++ standard. Supported "
+ "CPP_STD values: * 'c++0x' - generate code compatible with old compilers; "
+ "'c++11' - use C++11 code generator (default); * 'c++17' - use C++17 "
+ "features in generated code (experimental)." },
+ { "", "cpp-static-reflection", "",
+ "When using C++17, generate extra code to provide compile-time (static) "
+ "reflection of Flatbuffers types. Requires --cpp-std to be \"c++17\" or "
+ "higher." },
+ { "", "object-prefix", "PREFIX",
+ "Customize class prefix for C++ object-based API." },
+ { "", "object-suffix", "SUFFIX",
+ "Customize class suffix for C++ object-based API. Default Value is "
+ "\"T\"." },
+ { "", "go-namespace", "", "Generate the overriding namespace in Golang." },
+ { "", "go-import", "IMPORT",
+ "Generate the overriding import for flatbuffers in Golang (default is "
+ "\"github.com/google/flatbuffers/go\")." },
+ { "", "raw-binary", "",
+ "Allow binaries without file_identifier to be read. This may crash flatc "
+ "given a mismatched schema." },
+ { "", "size-prefixed", "", "Input binaries are size prefixed buffers." },
+ { "", "proto", "", "Input is a .proto, translate to .fbs." },
+ { "", "proto-namespace-suffix", "SUFFIX",
+ "Add this namespace to any flatbuffers generated from protobufs." },
+ { "", "oneof-union", "", "Translate .proto oneofs to flatbuffer unions." },
+ { "", "grpc", "", "Generate GRPC interfaces for the specified languages." },
+ { "", "schema", "", "Serialize schemas instead of JSON (use with -b)." },
+ { "", "bfbs-filenames", "PATH",
+ "Sets the root path where reflection filenames in reflection.fbs are "
+ "relative to. The 'root' is denoted with `//`. E.g. if PATH=/a/b/c "
+ "then /a/d/e.fbs will be serialized as //../d/e.fbs. (PATH defaults to the "
+ "directory of the first provided schema file." },
+ { "", "bfbs-comments", "", "Add doc comments to the binary schema files." },
+ { "", "bfbs-builtins", "",
+ "Add builtin attributes to the binary schema files." },
+ { "", "bfbs-gen-embed", "",
+ "Generate code to embed the bfbs schema to the source." },
+ { "", "conform", "FILE",
+ "Specify a schema the following schemas should be an evolution of. Gives "
+ "errors if not." },
+ { "", "conform-includes", "PATH",
+ "Include path for the schema given with --conform PATH" },
+ { "", "filename-suffix", "SUFFIX",
+ "The suffix appended to the generated file names (Default is "
+ "'_generated')." },
+ { "", "filename-ext", "EXT",
+ "The extension appended to the generated file names. Default is "
+ "language-specific (e.g., '.h' for C++)" },
+ { "", "include-prefix", "PATH",
+ "Prefix this PATH to any generated include statements." },
+ { "", "keep-prefix", "",
+ "Keep original prefix of schema include statement." },
+ { "", "reflect-types", "",
+ "Add minimal type reflection to code generation." },
+ { "", "reflect-names", "", "Add minimal type/name reflection." },
+ { "", "rust-serialize", "",
+ "Implement serde::Serialize on generated Rust types." },
+ { "", "rust-module-root-file", "",
+ "Generate rust code in individual files with a module root file." },
+ { "", "root-type", "T", "Select or override the default root_type." },
+ { "", "require-explicit-ids", "",
+ "When parsing schemas, require explicit ids (id: x)." },
+ { "", "force-defaults", "",
+ "Emit default values in binary output from JSON" },
+ { "", "force-empty", "",
+ "When serializing from object API representation, force strings and "
+ "vectors to empty rather than null." },
+ { "", "force-empty-vectors", "",
+ "When serializing from object API representation, force vectors to empty "
+ "rather than null." },
+ { "", "flexbuffers", "",
+ "Used with \"binary\" and \"json\" options, it generates data using "
+ "schema-less FlexBuffers." },
+ { "", "no-warnings", "", "Inhibit all warnings messages." },
+ { "", "warning-as-errors", "", "Treat all warnings as errors." },
+ { "", "cs-global-alias", "",
+ "Prepend \"global::\" to all user generated csharp classes and "
+ "structs." },
+ { "", "cs-gen-json-serializer", "",
+ "Allows (de)serialization of JSON text in the Object API. (requires "
+ "--gen-object-api)." },
+ { "", "json-nested-bytes", "",
+ "Allow a nested_flatbuffer field to be parsed as a vector of bytes"
+ "in JSON, which is unsafe unless checked by a verifier afterwards." },
+ { "", "ts-flat-files", "",
+ "Only generated one typescript file per .fbs file." },
+};
+
+static void AppendTextWrappedString(std::stringstream &ss, std::string &text,
+ size_t max_col, size_t start_col) {
+ size_t max_line_length = max_col - start_col;
+
+ if (text.length() > max_line_length) {
+ size_t ideal_break_location = text.rfind(' ', max_line_length);
+ size_t length = std::min(max_line_length, ideal_break_location);
+ ss << text.substr(0, length) << "\n";
+ ss << std::string(start_col, ' ');
+ std::string rest_of_description = text.substr(
+ ((ideal_break_location < max_line_length || text.at(length) == ' ')
+ ? length + 1
+ : length));
+ AppendTextWrappedString(ss, rest_of_description, max_col, start_col);
+ } else {
+ ss << text;
+ }
+}
+
+static void AppendOption(std::stringstream &ss, const FlatCOption &option,
+ size_t max_col, size_t min_col_for_description) {
+ size_t chars = 2;
+ ss << " ";
+ if (!option.short_opt.empty()) {
+ chars += 2 + option.short_opt.length();
+ ss << "-" << option.short_opt;
+ if (!option.long_opt.empty()) {
+ chars++;
+ ss << ",";
+ }
+ ss << " ";
+ }
+ if (!option.long_opt.empty()) {
+ chars += 3 + option.long_opt.length();
+ ss << "--" << option.long_opt << " ";
+ }
+ if (!option.parameter.empty()) {
+ chars += 1 + option.parameter.length();
+ ss << option.parameter << " ";
+ }
+ size_t start_of_description = chars;
+ if (start_of_description > min_col_for_description) {
+ ss << "\n";
+ start_of_description = min_col_for_description;
+ ss << std::string(start_of_description, ' ');
+ } else {
+ while (start_of_description < min_col_for_description) {
+ ss << " ";
+ start_of_description++;
+ }
+ }
+ if (!option.description.empty()) {
+ std::string description = option.description;
+ AppendTextWrappedString(ss, description, max_col, start_of_description);
+ }
+ ss << "\n";
+}
+
+static void AppendShortOption(std::stringstream &ss,
+ const FlatCOption &option) {
+ if (!option.short_opt.empty()) {
+ ss << "-" << option.short_opt;
+ if (!option.long_opt.empty()) { ss << "|"; }
+ }
+ if (!option.long_opt.empty()) { ss << "--" << option.long_opt; }
+}
+
+std::string FlatCompiler::GetShortUsageString(const char *program_name) const {
+ std::stringstream ss;
+ ss << "Usage: " << program_name << " [";
+ for (size_t i = 0; i < params_.num_generators; ++i) {
+ const Generator &g = params_.generators[i];
+ AppendShortOption(ss, g.option);
+ ss << ", ";
+ }
+ for (const FlatCOption &option : options) {
+ AppendShortOption(ss, option);
+ ss << ", ";
+ }
+ ss.seekp(-2, ss.cur);
+ ss << "]... FILE... [-- FILE...]";
+ std::string help = ss.str();
+ std::stringstream ss_textwrap;
+ AppendTextWrappedString(ss_textwrap, help, 80, 0);
+ return ss_textwrap.str();
+}
+
std::string FlatCompiler::GetUsageString(const char *program_name) const {
std::stringstream ss;
ss << "Usage: " << program_name << " [OPTION]... FILE... [-- FILE...]\n";
for (size_t i = 0; i < params_.num_generators; ++i) {
const Generator &g = params_.generators[i];
-
- std::stringstream full_name;
- full_name << std::setw(16) << std::left << g.generator_opt_long;
- const char *name = g.generator_opt_short ? g.generator_opt_short : " ";
- const char *help = g.generator_help;
-
- ss << " " << full_name.str() << " " << name << " " << help << ".\n";
+ AppendOption(ss, g.option, 80, 25);
}
- // clang-format off
- // Output width
- // 12345678901234567890123456789012345678901234567890123456789012345678901234567890
- ss <<
- " -o PATH Prefix PATH to all generated files.\n"
- " -I PATH Search for includes in the specified path.\n"
- " -M Print make rules for generated files.\n"
- " --version Print the version number of flatc and exit.\n"
- " --strict-json Strict JSON: field names must be / will be quoted,\n"
- " no trailing commas in tables/vectors.\n"
- " --allow-non-utf8 Pass non-UTF-8 input through parser and emit nonstandard\n"
- " \\x escapes in JSON. (Default is to raise parse error on\n"
- " non-UTF-8 input.)\n"
- " --natural-utf8 Output strings with UTF-8 as human-readable strings.\n"
- " By default, UTF-8 characters are printed as \\uXXXX escapes.\n"
- " --defaults-json Output fields whose value is the default when\n"
- " writing JSON\n"
- " --unknown-json Allow fields in JSON that are not defined in the\n"
- " schema. These fields will be discared when generating\n"
- " binaries.\n"
- " --no-prefix Don\'t prefix enum values with the enum type in C++.\n"
- " --scoped-enums Use C++11 style scoped and strongly typed enums.\n"
- " also implies --no-prefix.\n"
- " --gen-includes (deprecated), this is the default behavior.\n"
- " If the original behavior is required (no include\n"
- " statements) use --no-includes.\n"
- " --no-includes Don\'t generate include statements for included\n"
- " schemas the generated file depends on (C++ / Python).\n"
- " --gen-mutable Generate accessors that can mutate buffers in-place.\n"
- " --gen-onefile Generate single output file for C# and Go.\n"
- " --gen-name-strings Generate type name functions for C++ and Rust.\n"
- " --gen-object-api Generate an additional object-based API.\n"
- " --gen-compare Generate operator== for object-based API types.\n"
- " --gen-nullable Add Clang _Nullable for C++ pointer. or @Nullable for Java\n"
- " --java-checkerframe work Add @Pure for Java.\n"
- " --gen-generated Add @Generated annotation for Java\n"
- " --gen-jvmstatic Add @JvmStatic annotation for Kotlin methods\n"
- " in companion object for interop from Java to Kotlin.\n"
- " --gen-all Generate not just code for the current schema files,\n"
- " but for all files it includes as well.\n"
- " If the language uses a single file for output (by default\n"
- " the case for C++ and JS), all code will end up in this one\n"
- " file.\n"
- " --cpp-include Adds an #include in generated file.\n"
- " --cpp-ptr-type T Set object API pointer type (default std::unique_ptr).\n"
- " --cpp-str-type T Set object API string type (default std::string).\n"
- " T::c_str(), T::length() and T::empty() must be supported.\n"
- " The custom type also needs to be constructible from std::string\n"
- " (see the --cpp-str-flex-ctor option to change this behavior).\n"
- " --cpp-str-flex-ctor Don't construct custom string types by passing std::string\n"
- " from Flatbuffers, but (char* + length).\n"
- " --cpp-std CPP_STD Generate a C++ code using features of selected C++ standard.\n"
- " Supported CPP_STD values:\n"
- " * 'c++0x' - generate code compatible with old compilers;\n"
- " * 'c++11' - use C++11 code generator (default);\n"
- " * 'c++17' - use C++17 features in generated code (experimental).\n"
- " --object-prefix Customise class prefix for C++ object-based API.\n"
- " --object-suffix Customise class suffix for C++ object-based API.\n"
- " Default value is \"T\".\n"
- " --no-js-exports Removes Node.js style export lines in JS.\n"
- " --goog-js-export Uses goog.exports* for closure compiler exporting in JS.\n"
- " --es6-js-export Uses ECMAScript 6 export style lines in JS.\n"
- " --go-namespace Generate the overrided namespace in Golang.\n"
- " --go-import Generate the overrided import for flatbuffers in Golang\n"
- " (default is \"github.com/google/flatbuffers/go\").\n"
- " --raw-binary Allow binaries without file_indentifier to be read.\n"
- " This may crash flatc given a mismatched schema.\n"
- " --size-prefixed Input binaries are size prefixed buffers.\n"
- " --proto Input is a .proto, translate to .fbs.\n"
- " --proto-namespace-suffix Add this namespace to any flatbuffers generated\n"
- " SUFFIX from protobufs.\n"
- " --oneof-union Translate .proto oneofs to flatbuffer unions.\n"
- " --grpc Generate GRPC interfaces for the specified languages.\n"
- " --schema Serialize schemas instead of JSON (use with -b).\n"
- " --bfbs-comments Add doc comments to the binary schema files.\n"
- " --bfbs-builtins Add builtin attributes to the binary schema files.\n"
- " --bfbs-gen-embed Generate code to embed the bfbs schema to the source.\n"
- " --conform FILE Specify a schema the following schemas should be\n"
- " an evolution of. Gives errors if not.\n"
- " --conform-includes Include path for the schema given with --conform PATH\n"
- " --filename-suffix The suffix appended to the generated file names.\n"
- " Default is '_generated'.\n"
- " --filename-ext The extension appended to the generated file names.\n"
- " Default is language-specific (e.g., '.h' for C++)\n"
- " --include-prefix Prefix this path to any generated include statements.\n"
- " PATH\n"
- " --keep-prefix Keep original prefix of schema include statement.\n"
- " --no-fb-import Don't include flatbuffers import statement for TypeScript.\n"
- " --no-ts-reexport Don't re-export imported dependencies for TypeScript.\n"
- " --short-names Use short function names for JS and TypeScript.\n"
- " --reflect-types Add minimal type reflection to code generation.\n"
- " --reflect-names Add minimal type/name reflection.\n"
- " --root-type T Select or override the default root_type\n"
- " --require-explicit-ids When parsing schemas, require explicit ids (id: x).\n"
- " --force-defaults Emit default values in binary output from JSON\n"
- " --force-empty When serializing from object API representation,\n"
- " force strings and vectors to empty rather than null.\n"
- " --force-empty-vectors When serializing from object API representation,\n"
- " force vectors to empty rather than null.\n"
- " --flexbuffers Used with \"binary\" and \"json\" options, it generates\n"
- " data using schema-less FlexBuffers.\n"
- "FILEs may be schemas (must end in .fbs), binary schemas (must end in .bfbs),\n"
- "or JSON files (conforming to preceding schema). FILEs after the -- must be\n"
- "binary flatbuffer format files.\n"
- "Output files are named using the base file name of the input,\n"
- "and written to the current directory or the path given by -o.\n"
- "example: " << program_name << " -c -b schema1.fbs schema2.fbs data.json\n";
- // 12345678901234567890123456789012345678901234567890123456789012345678901234567890
- // clang-format on
+ ss << "\n";
+ for (const FlatCOption &option : options) {
+ AppendOption(ss, option, 80, 25);
+ }
+ ss << "\n";
+
+ std::string files_description =
+ "FILEs may be schemas (must end in .fbs), binary schemas (must end in "
+ ".bfbs) or JSON files (conforming to preceding schema). FILEs after the "
+ "-- must be binary flatbuffer format files. Output files are named using "
+ "the base file name of the input, and written to the current directory "
+ "or the path given by -o. example: " +
+ std::string(program_name) + " -c -b schema1.fbs schema2.fbs data.json";
+ AppendTextWrappedString(ss, files_description, 80, 0);
+ ss << "\n";
return ss.str();
}
@@ -187,6 +335,8 @@
return 0;
}
+ if (argc <= 1) { Error("Need to provide at least one argument."); }
+
flatbuffers::IDLOptions opts;
std::string output_path;
@@ -195,6 +345,7 @@
bool raw_binary = false;
bool schema_binary = false;
bool grpc_enabled = false;
+ bool requires_bfbs = false;
std::vector<std::string> filenames;
std::list<std::string> include_directories_storage;
std::vector<const char *> include_directories;
@@ -203,7 +354,9 @@
size_t binary_files_from = std::numeric_limits<size_t>::max();
std::string conform_to_schema;
- for (int argi = 0; argi < argc; argi++) {
+ const char *program_name = argv[0];
+
+ for (int argi = 1; argi < argc; argi++) {
std::string arg = argv[argi];
if (arg[0] == '-') {
if (filenames.size() && arg[1] != '-')
@@ -218,6 +371,11 @@
flatbuffers::PosixPath(argv[argi]));
include_directories.push_back(
include_directories_storage.back().c_str());
+ } else if (arg == "--bfbs-filenames") {
+ if (++argi > argc) Error("missing path following: " + arg, true);
+ opts.project_root = argv[argi];
+ if (!DirExists(opts.project_root.c_str()))
+ Error(arg + " is not a directory: " + opts.project_root);
} else if (arg == "--conform") {
if (++argi >= argc) Error("missing path following: " + arg, true);
conform_to_schema = flatbuffers::PosixPath(argv[argi]);
@@ -239,14 +397,6 @@
opts.allow_non_utf8 = true;
} else if (arg == "--natural-utf8") {
opts.natural_utf8 = true;
- } else if (arg == "--no-js-exports") {
- opts.skip_js_exports = true;
- } else if (arg == "--goog-js-export") {
- opts.use_goog_js_export_format = true;
- opts.use_ES6_js_export_format = false;
- } else if (arg == "--es6-js-export") {
- opts.use_goog_js_export_format = false;
- opts.use_ES6_js_export_format = true;
} else if (arg == "--go-namespace") {
if (++argi >= argc) Error("missing golang namespace" + arg, true);
opts.go_namespace = argv[argi];
@@ -285,12 +435,25 @@
opts.cpp_object_api_string_flexible_constructor = true;
} else if (arg == "--no-cpp-direct-copy") {
opts.cpp_direct_copy = false;
+ } else if (arg == "--cpp-field-case-style") {
+ if (++argi >= argc) Error("missing case style following: " + arg, true);
+ if (!strcmp(argv[argi], "unchanged"))
+ opts.cpp_object_api_field_case_style =
+ IDLOptions::CaseStyle_Unchanged;
+ else if (!strcmp(argv[argi], "upper"))
+ opts.cpp_object_api_field_case_style = IDLOptions::CaseStyle_Upper;
+ else if (!strcmp(argv[argi], "lower"))
+ opts.cpp_object_api_field_case_style = IDLOptions::CaseStyle_Lower;
+ else
+ Error("unknown case style: " + std::string(argv[argi]), true);
} else if (arg == "--gen-nullable") {
opts.gen_nullable = true;
} else if (arg == "--java-checkerframework") {
opts.java_checkerframework = true;
} else if (arg == "--gen-generated") {
opts.gen_generated = true;
+ } else if (arg == "--gen-json-emit") {
+ opts.gen_json_coders = true;
} else if (arg == "--object-prefix") {
if (++argi >= argc) Error("missing prefix following: " + arg, true);
opts.object_prefix = argv[argi];
@@ -300,7 +463,6 @@
} else if (arg == "--gen-all") {
opts.generate_all = true;
opts.include_dependence_headers = false;
- opts.reexport_ts_modules = false;
} else if (arg == "--gen-includes") {
// Deprecated, remove this option some time in the future.
Warn("warning: --gen-includes is deprecated (it is now default)\n");
@@ -308,6 +470,7 @@
opts.include_dependence_headers = false;
} else if (arg == "--gen-onefile") {
opts.one_file = true;
+ opts.include_dependence_headers = false;
} else if (arg == "--raw-binary") {
raw_binary = true;
} else if (arg == "--size-prefixed") {
@@ -328,6 +491,9 @@
} else if (arg == "--version") {
printf("flatc version %s\n", FLATC_VERSION());
exit(0);
+ } else if (arg == "--help" || arg == "-h") {
+ printf("%s\n", GetUsageString(program_name).c_str());
+ exit(0);
} else if (arg == "--grpc") {
grpc_enabled = true;
} else if (arg == "--bfbs-comments") {
@@ -336,16 +502,14 @@
opts.binary_schema_builtins = true;
} else if (arg == "--bfbs-gen-embed") {
opts.binary_schema_gen_embed = true;
- } else if (arg == "--no-fb-import") {
- opts.skip_flatbuffers_import = true;
- } else if (arg == "--no-ts-reexport") {
- opts.reexport_ts_modules = false;
- } else if (arg == "--short-names") {
- opts.js_ts_short_names = true;
} else if (arg == "--reflect-types") {
opts.mini_reflect = IDLOptions::kTypes;
} else if (arg == "--reflect-names") {
opts.mini_reflect = IDLOptions::kTypesAndNames;
+ } else if (arg == "--rust-serialize") {
+ opts.rust_serialize = true;
+ } else if (arg == "--rust-module-root-file") {
+ opts.rust_module_root_file = true;
} else if (arg == "--require-explicit-ids") {
opts.require_explicit_ids = true;
} else if (arg == "--root-type") {
@@ -372,22 +536,40 @@
opts.use_flexbuffers = true;
} else if (arg == "--gen-jvmstatic") {
opts.gen_jvmstatic = true;
+ } else if (arg == "--no-warnings") {
+ opts.no_warnings = true;
+ } else if (arg == "--warnings-as-errors") {
+ opts.warnings_as_errors = true;
} else if (arg == "--cpp-std") {
if (++argi >= argc)
Error("missing C++ standard specification" + arg, true);
opts.cpp_std = argv[argi];
+ } else if (arg.rfind("--cpp-std=", 0) == 0) {
+ opts.cpp_std = arg.substr(std::string("--cpp-std=").size());
+ } else if (arg == "--cpp-static-reflection") {
+ opts.cpp_static_reflection = true;
+ } else if (arg == "--cs-global-alias") {
+ opts.cs_global_alias = true;
+ } else if (arg == "--json-nested-bytes") {
+ opts.json_nested_legacy_flatbuffers = true;
+ } else if (arg == "--ts-flat-files") {
+ opts.ts_flat_file = true;
} else {
for (size_t i = 0; i < params_.num_generators; ++i) {
- if (arg == params_.generators[i].generator_opt_long ||
- (params_.generators[i].generator_opt_short &&
- arg == params_.generators[i].generator_opt_short)) {
+ if (arg == "--" + params_.generators[i].option.long_opt ||
+ arg == "-" + params_.generators[i].option.short_opt) {
generator_enabled[i] = true;
any_generator = true;
opts.lang_to_generate |= params_.generators[i].lang;
+ if (params_.generators[i].bfbs_generator) {
+ opts.binary_schema_comments = true;
+ requires_bfbs = true;
+ }
goto found;
}
}
Error("unknown commandline argument: " + arg, true);
+
found:;
}
} else {
@@ -404,6 +586,16 @@
Error("no options: specify at least one generator.", true);
}
+ if (opts.cs_gen_json_serializer && !opts.generate_object_based_api) {
+ Error(
+ "--cs-gen-json-serializer requires --gen-object-api to be set as "
+ "well.");
+ }
+
+ if (opts.ts_flat_file && opts.generate_all) {
+ Error("Combining --ts-flat-file and --gen-all is not supported.");
+ }
+
flatbuffers::Parser conform_parser;
if (!conform_to_schema.empty()) {
std::string contents;
@@ -431,8 +623,11 @@
bool is_binary =
static_cast<size_t>(file_it - filenames.begin()) >= binary_files_from;
auto ext = flatbuffers::GetExtension(filename);
- auto is_schema = ext == "fbs" || ext == "proto";
- auto is_binary_schema = ext == reflection::SchemaExtension();
+ const bool is_schema = ext == "fbs" || ext == "proto";
+ if (is_schema && opts.project_root.empty()) {
+ opts.project_root = StripFileName(filename);
+ }
+ const bool is_binary_schema = ext == reflection::SchemaExtension();
if (is_binary) {
parser->builder_.Clear();
parser->builder_.PushFlatBuffer(
@@ -464,20 +659,24 @@
contents.length() != strlen(contents.c_str())) {
Error("input file appears to be binary: " + filename, true);
}
- if (is_schema) {
+ if (is_schema || is_binary_schema) {
// If we're processing multiple schemas, make sure to start each
// one from scratch. If it depends on previous schemas it must do
// so explicitly using an include.
parser.reset(new flatbuffers::Parser(opts));
}
+ // Try to parse the file contents (binary schema/flexbuffer/textual
+ // schema)
if (is_binary_schema) {
LoadBinarySchema(*parser.get(), filename, contents);
- }
- if (opts.use_flexbuffers) {
+ } else if (opts.use_flexbuffers) {
if (opts.lang_to_generate == IDLOptions::kJson) {
- parser->flex_root_ = flexbuffers::GetRoot(
- reinterpret_cast<const uint8_t *>(contents.c_str()),
- contents.size());
+ auto data = reinterpret_cast<const uint8_t *>(contents.c_str());
+ auto size = contents.size();
+ std::vector<uint8_t> reuse_tracker;
+ if (!flexbuffers::VerifyBuffer(data, size, &reuse_tracker))
+ Error("flexbuffers file failed to verify: " + filename, false);
+ parser->flex_root_ = flexbuffers::GetRoot(data, size);
} else {
parser->flex_builder_.Clear();
ParseFile(*parser.get(), filename, contents, include_directories);
@@ -494,7 +693,7 @@
}
if ((is_schema || is_binary_schema) && !conform_to_schema.empty()) {
auto err = parser->ConformTo(conform_parser);
- if (!err.empty()) Error("schemas don\'t conform: " + err);
+ if (!err.empty()) Error("schemas don\'t conform: " + err, false);
}
if (schema_binary || opts.binary_schema_gen_embed) {
parser->Serialize();
@@ -503,21 +702,42 @@
parser->file_extension_ = reflection::SchemaExtension();
}
}
-
std::string filebase =
flatbuffers::StripPath(flatbuffers::StripExtension(filename));
+ // If one of the generators uses bfbs, serialize the parser and get
+ // the serialized buffer and length.
+ const uint8_t *bfbs_buffer = nullptr;
+ int64_t bfbs_length = 0;
+ if (requires_bfbs) {
+ parser->Serialize();
+ bfbs_buffer = parser->builder_.GetBufferPointer();
+ bfbs_length = parser->builder_.GetSize();
+ }
+
for (size_t i = 0; i < params_.num_generators; ++i) {
- parser->opts.lang = params_.generators[i].lang;
if (generator_enabled[i]) {
if (!print_make_rules) {
flatbuffers::EnsureDirExists(output_path);
- if ((!params_.generators[i].schema_only ||
- (is_schema || is_binary_schema)) &&
- !params_.generators[i].generate(*parser.get(), output_path,
- filebase)) {
- Error(std::string("Unable to generate ") +
- params_.generators[i].lang_name + " for " + filebase);
+
+ // Prefer bfbs generators if present.
+ if (params_.generators[i].bfbs_generator) {
+ const GeneratorStatus status =
+ params_.generators[i].bfbs_generator->Generate(bfbs_buffer,
+ bfbs_length);
+ if (status != OK) {
+ Error(std::string("Unable to generate ") +
+ params_.generators[i].lang_name + " for " + filebase +
+ " using bfbs generator.");
+ }
+ } else {
+ if ((!params_.generators[i].schema_only ||
+ (is_schema || is_binary_schema)) &&
+ !params_.generators[i].generate(*parser.get(), output_path,
+ filebase)) {
+ Error(std::string("Unable to generate ") +
+ params_.generators[i].lang_name + " for " + filebase);
+ }
}
} else {
if (params_.generators[i].make_rule == nullptr) {
@@ -559,6 +779,19 @@
// in any files coming up next.
parser->MarkGenerated();
}
+
+ // Once all the files have been parsed, run any generators Parsing Completed
+ // function for final generation.
+ for (size_t i = 0; i < params_.num_generators; ++i) {
+ if (generator_enabled[i] &&
+ params_.generators[i].parsing_completed != nullptr) {
+ if (!params_.generators[i].parsing_completed(*parser, output_path)) {
+ Error("failed running parsing completed for " +
+ std::string(params_.generators[i].lang_name));
+ }
+ }
+ }
+
return 0;
}
diff --git a/src/flatc_main.cpp b/src/flatc_main.cpp
index c942bda..abcab24 100644
--- a/src/flatc_main.cpp
+++ b/src/flatc_main.cpp
@@ -14,6 +14,11 @@
* limitations under the License.
*/
+#include <cstdio>
+#include <memory>
+
+#include "bfbs_gen_lua.h"
+#include "flatbuffers/base.h"
#include "flatbuffers/flatc.h"
#include "flatbuffers/util.h"
@@ -23,16 +28,16 @@
const std::string &warn, bool show_exe_name) {
(void)flatc;
if (show_exe_name) { printf("%s: ", g_program_name); }
- printf("warning: %s\n", warn.c_str());
+ fprintf(stderr, "\nwarning:\n %s\n\n", warn.c_str());
}
static void Error(const flatbuffers::FlatCompiler *flatc,
const std::string &err, bool usage, bool show_exe_name) {
if (show_exe_name) { printf("%s: ", g_program_name); }
- printf("error: %s\n", err.c_str());
if (usage && flatc) {
- printf("%s", flatc->GetUsageString(g_program_name).c_str());
+ fprintf(stderr, "%s\n", flatc->GetShortUsageString(g_program_name).c_str());
}
+ fprintf(stderr, "\nerror:\n %s\n\n", err.c_str());
exit(1);
}
@@ -50,66 +55,96 @@
// Prevent Appveyor-CI hangs.
flatbuffers::SetupDefaultCRTReportMode();
+ const std::string flatbuffers_version(flatbuffers::FLATBUFFERS_VERSION());
+
+ std::unique_ptr<flatbuffers::BfbsGenerator> bfbs_gen_lua =
+ flatbuffers::NewLuaBfbsGenerator(flatbuffers_version);
+
g_program_name = argv[0];
const flatbuffers::FlatCompiler::Generator generators[] = {
- { flatbuffers::GenerateBinary, "-b", "--binary", "binary", false, nullptr,
+ { flatbuffers::GenerateBinary, "binary", false, nullptr,
flatbuffers::IDLOptions::kBinary,
- "Generate wire format binaries for any data definitions",
- flatbuffers::BinaryMakeRule },
- { flatbuffers::GenerateTextFile, "-t", "--json", "text", false, nullptr,
+ flatbuffers::FlatCOption{
+ "b", "binary", "",
+ "Generate wire format binaries for any data definitions" },
+ flatbuffers::BinaryMakeRule, nullptr, nullptr },
+ { flatbuffers::GenerateTextFile, "text", false, nullptr,
flatbuffers::IDLOptions::kJson,
- "Generate text output for any data definitions",
- flatbuffers::TextMakeRule },
- { flatbuffers::GenerateCPP, "-c", "--cpp", "C++", true,
- flatbuffers::GenerateCppGRPC, flatbuffers::IDLOptions::kCpp,
- "Generate C++ headers for tables/structs", flatbuffers::CPPMakeRule },
- { flatbuffers::GenerateGo, "-g", "--go", "Go", true,
- flatbuffers::GenerateGoGRPC, flatbuffers::IDLOptions::kGo,
- "Generate Go files for tables/structs", nullptr },
- { flatbuffers::GenerateJava, "-j", "--java", "Java", true,
- flatbuffers::GenerateJavaGRPC, flatbuffers::IDLOptions::kJava,
- "Generate Java classes for tables/structs",
- flatbuffers::JavaCSharpMakeRule },
- { flatbuffers::GenerateJSTS, "-s", "--js", "JavaScript", true, nullptr,
- flatbuffers::IDLOptions::kJs,
- "Generate JavaScript code for tables/structs",
- flatbuffers::JSTSMakeRule },
- { flatbuffers::GenerateDart, "-d", "--dart", "Dart", true, nullptr,
+ flatbuffers::FlatCOption{
+ "t", "json", "", "Generate text output for any data definitions" },
+
+ flatbuffers::TextMakeRule, nullptr, nullptr },
+ { flatbuffers::GenerateCPP, "C++", true, flatbuffers::GenerateCppGRPC,
+ flatbuffers::IDLOptions::kCpp,
+ flatbuffers::FlatCOption{ "c", "cpp", "",
+ "Generate C++ headers for tables/structs" },
+ flatbuffers::CPPMakeRule, nullptr, nullptr },
+ { flatbuffers::GenerateGo, "Go", true, flatbuffers::GenerateGoGRPC,
+ flatbuffers::IDLOptions::kGo,
+ flatbuffers::FlatCOption{ "g", "go", "",
+ "Generate Go files for tables/structs" },
+ nullptr, nullptr, nullptr },
+ { flatbuffers::GenerateJava, "Java", true, flatbuffers::GenerateJavaGRPC,
+ flatbuffers::IDLOptions::kJava,
+ flatbuffers::FlatCOption{ "j", "java", "",
+ "Generate Java classes for tables/structs" },
+ flatbuffers::JavaMakeRule, nullptr, nullptr },
+ { flatbuffers::GenerateDart, "Dart", true, nullptr,
flatbuffers::IDLOptions::kDart,
- "Generate Dart classes for tables/structs", flatbuffers::DartMakeRule },
- { flatbuffers::GenerateJSTS, "-T", "--ts", "TypeScript", true,
- flatbuffers::GenerateTSGRPC, flatbuffers::IDLOptions::kTs,
- "Generate TypeScript code for tables/structs",
- flatbuffers::JSTSMakeRule },
- { flatbuffers::GenerateCSharp, "-n", "--csharp", "C#", true, nullptr,
+ flatbuffers::FlatCOption{ "d", "dart", "",
+ "Generate Dart classes for tables/structs" },
+ flatbuffers::DartMakeRule, nullptr, nullptr },
+ { flatbuffers::GenerateTS, "TypeScript", true, flatbuffers::GenerateTSGRPC,
+ flatbuffers::IDLOptions::kTs,
+ flatbuffers::FlatCOption{ "T", "ts", "",
+ "Generate TypeScript code for tables/structs" },
+ flatbuffers::TSMakeRule, nullptr, nullptr },
+ { flatbuffers::GenerateCSharp, "C#", true, nullptr,
flatbuffers::IDLOptions::kCSharp,
- "Generate C# classes for tables/structs",
- flatbuffers::JavaCSharpMakeRule },
- { flatbuffers::GeneratePython, "-p", "--python", "Python", true,
+ flatbuffers::FlatCOption{ "n", "csharp", "",
+ "Generate C# classes for tables/structs" },
+ flatbuffers::CSharpMakeRule, nullptr, nullptr },
+ { flatbuffers::GeneratePython, "Python", true,
flatbuffers::GeneratePythonGRPC, flatbuffers::IDLOptions::kPython,
- "Generate Python files for tables/structs", nullptr },
- { flatbuffers::GenerateLobster, nullptr, "--lobster", "Lobster", true,
- nullptr, flatbuffers::IDLOptions::kLobster,
- "Generate Lobster files for tables/structs", nullptr },
- { flatbuffers::GenerateLua, "-l", "--lua", "Lua", true, nullptr,
- flatbuffers::IDLOptions::kLua, "Generate Lua files for tables/structs",
- nullptr },
- { flatbuffers::GenerateRust, "-r", "--rust", "Rust", true, nullptr,
- flatbuffers::IDLOptions::kRust, "Generate Rust files for tables/structs",
- flatbuffers::RustMakeRule },
- { flatbuffers::GeneratePhp, nullptr, "--php", "PHP", true, nullptr,
- flatbuffers::IDLOptions::kPhp, "Generate PHP files for tables/structs",
- nullptr },
- { flatbuffers::GenerateKotlin, nullptr, "--kotlin", "Kotlin", true, nullptr,
+ flatbuffers::FlatCOption{ "p", "python", "",
+ "Generate Python files for tables/structs" },
+ nullptr, nullptr, nullptr },
+ { flatbuffers::GenerateLobster, "Lobster", true, nullptr,
+ flatbuffers::IDLOptions::kLobster,
+ flatbuffers::FlatCOption{ "", "lobster", "",
+ "Generate Lobster files for tables/structs" },
+ nullptr, nullptr, nullptr },
+ { flatbuffers::GenerateLua, "Lua", true, nullptr,
+ flatbuffers::IDLOptions::kLua,
+ flatbuffers::FlatCOption{ "l", "lua", "",
+ "Generate Lua files for tables/structs" },
+ nullptr, bfbs_gen_lua.get(), nullptr },
+ { flatbuffers::GenerateRust, "Rust", true, nullptr,
+ flatbuffers::IDLOptions::kRust,
+ flatbuffers::FlatCOption{ "r", "rust", "",
+ "Generate Rust files for tables/structs" },
+ flatbuffers::RustMakeRule, nullptr,
+ flatbuffers::GenerateRustModuleRootFile },
+ { flatbuffers::GeneratePhp, "PHP", true, nullptr,
+ flatbuffers::IDLOptions::kPhp,
+ flatbuffers::FlatCOption{ "", "php", "",
+ "Generate PHP files for tables/structs" },
+ nullptr, nullptr, nullptr },
+ { flatbuffers::GenerateKotlin, "Kotlin", true, nullptr,
flatbuffers::IDLOptions::kKotlin,
- "Generate Kotlin classes for tables/structs", nullptr },
- { flatbuffers::GenerateJsonSchema, nullptr, "--jsonschema", "JsonSchema",
- true, nullptr, flatbuffers::IDLOptions::kJsonSchema,
- "Generate Json schema", nullptr },
- { flatbuffers::GenerateSwift, nullptr, "--swift", "swift", true,
- flatbuffers::GenerateSwiftGRPC, flatbuffers::IDLOptions::kSwift,
- "Generate Swift files for tables/structs", nullptr },
+ flatbuffers::FlatCOption{ "", "kotlin", "",
+ "Generate Kotlin classes for tables/structs" },
+ nullptr, nullptr, nullptr },
+ { flatbuffers::GenerateJsonSchema, "JsonSchema", true, nullptr,
+ flatbuffers::IDLOptions::kJsonSchema,
+ flatbuffers::FlatCOption{ "", "jsonschema", "", "Generate Json schema" },
+ nullptr, nullptr, nullptr },
+ { flatbuffers::GenerateSwift, "swift", true, flatbuffers::GenerateSwiftGRPC,
+ flatbuffers::IDLOptions::kSwift,
+ flatbuffers::FlatCOption{ "", "swift", "",
+ "Generate Swift files for tables/structs" },
+ nullptr, nullptr, nullptr },
};
flatbuffers::FlatCompiler::InitParams params;
@@ -119,5 +154,5 @@
params.error_fn = Error;
flatbuffers::FlatCompiler flatc(params);
- return flatc.Compile(argc - 1, argv + 1);
+ return flatc.Compile(argc, argv);
}
diff --git a/src/idl_gen_cpp.cpp b/src/idl_gen_cpp.cpp
index a56dad9..dfd9525 100644
--- a/src/idl_gen_cpp.cpp
+++ b/src/idl_gen_cpp.cpp
@@ -1,4 +1,4 @@
- /*
+/*
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -233,6 +233,30 @@
return keywords_.find(name) == keywords_.end() ? name : name + "_";
}
+ std::string Name(const FieldDef &field) const {
+ // the union type field suffix is immutable.
+ static size_t union_suffix_len = strlen(UnionTypeFieldSuffix());
+ const bool is_union_type = field.value.type.base_type == BASE_TYPE_UTYPE;
+ // early return if no case transformation required
+ if (opts_.cpp_object_api_field_case_style ==
+ IDLOptions::CaseStyle_Unchanged)
+ return EscapeKeyword(field.name);
+ std::string name = field.name;
+ // do not change the case style of the union type field suffix
+ if (is_union_type) {
+ FLATBUFFERS_ASSERT(name.length() > union_suffix_len);
+ name.erase(name.length() - union_suffix_len, union_suffix_len);
+ }
+ if (opts_.cpp_object_api_field_case_style == IDLOptions::CaseStyle_Upper)
+ name = ConvertCase(name, Case::kUpperCamel);
+ else if (opts_.cpp_object_api_field_case_style ==
+ IDLOptions::CaseStyle_Lower)
+ name = ConvertCase(name, Case::kLowerCamel);
+ // restore the union field type suffix
+ if (is_union_type) name.append(UnionTypeFieldSuffix(), union_suffix_len);
+ return EscapeKeyword(name);
+ }
+
std::string Name(const Definition &def) const {
return EscapeKeyword(def.name);
}
@@ -259,6 +283,9 @@
code_ += "#pragma clang system_header\n\n";
}
+ code_ += "#include \"flatbuffers/flatbuffers.h\"";
+ code_ += "";
+
SetNameSpace(struct_def.defined_namespace);
auto name = Name(struct_def);
code_.SetValue("STRUCT_NAME", name);
@@ -481,6 +508,17 @@
code_ += " return flatbuffers::GetMutableRoot<{{STRUCT_NAME}}>(buf);";
code_ += "}";
code_ += "";
+
+ code_ += "inline \\";
+ code_ +=
+ "{{CPP_NAME}} "
+ "*{{NULLABLE_EXT}}GetMutableSizePrefixed{{STRUCT_NAME}}(void "
+ "*buf) {";
+ code_ +=
+ " return "
+ "flatbuffers::GetMutableSizePrefixedRoot<{{CPP_NAME}}>(buf);";
+ code_ += "}";
+ code_ += "";
}
if (parser_.file_identifier_.length()) {
@@ -497,6 +535,16 @@
code_ += " buf, {{STRUCT_NAME}}Identifier());";
code_ += "}";
code_ += "";
+
+ // Check if a size-prefixed buffer has the identifier.
+ code_ += "inline \\";
+ code_ +=
+ "bool SizePrefixed{{STRUCT_NAME}}BufferHasIdentifier(const void "
+ "*buf) {";
+ code_ += " return flatbuffers::BufferHasIdentifier(";
+ code_ += " buf, {{STRUCT_NAME}}Identifier(), true);";
+ code_ += "}";
+ code_ += "";
}
// The root verifier.
@@ -550,8 +598,7 @@
if (opts_.generate_object_based_api) {
// A convenient root unpack function.
- auto native_name =
- NativeName(WrapInNameSpace(struct_def), &struct_def, opts_);
+ auto native_name = WrapNativeNameInNameSpace(struct_def, opts_);
code_.SetValue("UNPACK_RETURN",
GenTypeNativePtr(native_name, nullptr, false));
code_.SetValue("UNPACK_TYPE",
@@ -624,8 +671,9 @@
}
bool VectorElementUserFacing(const Type &type) const {
- return opts_.g_cpp_std >= cpp::CPP_STD_17 && opts_.g_only_fixed_enums &&
- IsEnum(type);
+ return (opts_.scoped_enums && IsEnum(type)) ||
+ (opts_.g_cpp_std >= cpp::CPP_STD_17 && opts_.g_only_fixed_enums &&
+ IsEnum(type));
}
void GenComment(const std::vector<std::string> &dc, const char *prefix = "") {
@@ -709,6 +757,12 @@
: name;
}
+ std::string WrapNativeNameInNameSpace(const StructDef &struct_def,
+ const IDLOptions &opts) {
+ return WrapInNameSpace(struct_def.defined_namespace,
+ NativeName(Name(struct_def), &struct_def, opts));
+ }
+
const std::string &PtrType(const FieldDef *field) {
auto attr = field ? field->attributes.Lookup("cpp_ptr_type") : nullptr;
return attr ? attr->constant : opts_.cpp_object_api_pointer_type;
@@ -759,7 +813,7 @@
}
std::string GenTypeNative(const Type &type, bool invector,
- const FieldDef &field) {
+ const FieldDef &field, bool forcopy = false) {
switch (type.base_type) {
case BASE_TYPE_STRING: {
return NativeString(&field);
@@ -780,14 +834,14 @@
if (IsStruct(type)) {
auto native_type = type.struct_def->attributes.Lookup("native_type");
if (native_type) { type_name = native_type->constant; }
- if (invector || field.native_inline) {
+ if (invector || field.native_inline || forcopy) {
return type_name;
} else {
return GenTypeNativePtr(type_name, &field, false);
}
} else {
- return GenTypeNativePtr(NativeName(type_name, type.struct_def, opts_),
- &field, false);
+ const auto nn = WrapNativeNameInNameSpace(*type.struct_def, opts_);
+ return forcopy ? nn : GenTypeNativePtr(nn, &field, false);
}
}
case BASE_TYPE_UNION: {
@@ -878,16 +932,16 @@
return name.substr(0, name.size() - strlen(UnionTypeFieldSuffix()));
}
- std::string GetUnionElement(const EnumVal &ev, bool wrap, bool actual_type,
- bool native_type = false) {
+ std::string GetUnionElement(const EnumVal &ev, bool native_type,
+ const IDLOptions &opts) {
if (ev.union_type.base_type == BASE_TYPE_STRUCT) {
- auto name = actual_type ? ev.union_type.struct_def->name : Name(ev);
- return wrap ? WrapInNameSpace(ev.union_type.struct_def->defined_namespace,
- name)
- : name;
+ auto name = ev.union_type.struct_def->name;
+ if (native_type) {
+ name = NativeName(name, ev.union_type.struct_def, opts);
+ }
+ return WrapInNameSpace(ev.union_type.struct_def->defined_namespace, name);
} else if (IsString(ev.union_type)) {
- return actual_type ? (native_type ? "std::string" : "flatbuffers::String")
- : Name(ev);
+ return native_type ? "std::string" : "flatbuffers::String";
} else {
FLATBUFFERS_ASSERT(false);
return Name(ev);
@@ -901,10 +955,12 @@
}
std::string UnionVectorVerifySignature(const EnumDef &enum_def) {
- return "bool Verify" + Name(enum_def) + "Vector" +
+ auto name = Name(enum_def);
+ auto type = opts_.scoped_enums ? name : "uint8_t";
+ return "bool Verify" + name + "Vector" +
"(flatbuffers::Verifier &verifier, " +
"const flatbuffers::Vector<flatbuffers::Offset<void>> *values, " +
- "const flatbuffers::Vector<uint8_t> *types)";
+ "const flatbuffers::Vector<" + type + "> *types)";
}
std::string UnionUnPackSignature(const EnumDef &enum_def, bool inclass) {
@@ -1003,10 +1059,9 @@
? bt - BASE_TYPE_UTYPE + ET_UTYPE
: ET_SEQUENCE;
int ref_idx = -1;
- std::string ref_name =
- type.struct_def
- ? WrapInNameSpace(*type.struct_def)
- : type.enum_def ? WrapInNameSpace(*type.enum_def) : "";
+ std::string ref_name = type.struct_def ? WrapInNameSpace(*type.struct_def)
+ : type.enum_def ? WrapInNameSpace(*type.enum_def)
+ : "";
if (!ref_name.empty()) {
auto rit = type_refs.begin();
for (; rit != type_refs.end(); ++rit) {
@@ -1258,7 +1313,7 @@
if (it == enum_def.Vals().begin()) {
code_ += "template<typename T> struct {{ENUM_NAME}}Traits {";
} else {
- auto name = GetUnionElement(ev, true, true);
+ auto name = GetUnionElement(ev, false, opts_);
code_ += "template<> struct {{ENUM_NAME}}Traits<" + name + "> {";
}
@@ -1270,11 +1325,30 @@
}
if (opts_.generate_object_based_api && enum_def.is_union) {
- // Generate a union type
+ // Generate a union type and a trait type for it.
code_.SetValue("NAME", Name(enum_def));
FLATBUFFERS_ASSERT(enum_def.Lookup("NONE"));
code_.SetValue("NONE", GetEnumValUse(enum_def, *enum_def.Lookup("NONE")));
+ if (!enum_def.uses_multiple_type_instances) {
+ for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end();
+ ++it) {
+ const auto &ev = **it;
+
+ if (it == enum_def.Vals().begin()) {
+ code_ += "template<typename T> struct {{NAME}}UnionTraits {";
+ } else {
+ auto name = GetUnionElement(ev, true, opts_);
+ code_ += "template<> struct {{NAME}}UnionTraits<" + name + "> {";
+ }
+
+ auto value = GetEnumValUse(enum_def, ev);
+ code_ += " static const {{ENUM_NAME}} enum_value = " + value + ";";
+ code_ += "};";
+ code_ += "";
+ }
+ }
+
code_ += "struct {{NAME}}Union {";
code_ += " {{NAME}} type;";
code_ += " void *value;";
@@ -1298,18 +1372,15 @@
code_ += " void Reset();";
code_ += "";
if (!enum_def.uses_multiple_type_instances) {
- code_ += "#ifndef FLATBUFFERS_CPP98_STL";
code_ += " template <typename T>";
code_ += " void Set(T&& val) {";
- code_ += " using RT = typename std::remove_reference<T>::type;";
+ code_ += " typedef typename std::remove_reference<T>::type RT;";
code_ += " Reset();";
- code_ +=
- " type = {{NAME}}Traits<typename RT::TableType>::enum_value;";
+ code_ += " type = {{NAME}}UnionTraits<RT>::enum_value;";
code_ += " if (type != {{NONE}}) {";
code_ += " value = new RT(std::forward<T>(val));";
code_ += " }";
code_ += " }";
- code_ += "#endif // FLATBUFFERS_CPP98_STL";
code_ += "";
}
code_ += " " + UnionUnPackSignature(enum_def, true) + ";";
@@ -1321,9 +1392,7 @@
const auto &ev = **it;
if (ev.IsZero()) { continue; }
- const auto native_type =
- NativeName(GetUnionElement(ev, true, true, true),
- ev.union_type.struct_def, opts_);
+ const auto native_type = GetUnionElement(ev, true, opts_);
code_.SetValue("NATIVE_TYPE", native_type);
code_.SetValue("NATIVE_NAME", Name(ev));
code_.SetValue("NATIVE_ID", GetEnumValUse(enum_def, ev));
@@ -1355,9 +1424,7 @@
const auto &ev = **it;
code_.SetValue("NATIVE_ID", GetEnumValUse(enum_def, ev));
if (ev.IsNonZero()) {
- const auto native_type =
- NativeName(GetUnionElement(ev, true, true, true),
- ev.union_type.struct_def, opts_);
+ const auto native_type = GetUnionElement(ev, true, opts_);
code_.SetValue("NATIVE_TYPE", native_type);
code_ += " case {{NATIVE_ID}}: {";
code_ +=
@@ -1411,15 +1478,17 @@
code_.SetValue("LABEL", GetEnumValUse(enum_def, ev));
if (ev.IsNonZero()) {
- code_.SetValue("TYPE", GetUnionElement(ev, true, true));
+ code_.SetValue("TYPE", GetUnionElement(ev, false, opts_));
code_ += " case {{LABEL}}: {";
auto getptr =
" auto ptr = reinterpret_cast<const {{TYPE}} *>(obj);";
if (ev.union_type.base_type == BASE_TYPE_STRUCT) {
if (ev.union_type.struct_def->fixed) {
+ code_.SetValue("ALIGN",
+ NumToString(ev.union_type.struct_def->minalign));
code_ +=
- " return verifier.Verify<{{TYPE}}>(static_cast<const "
- "uint8_t *>(obj), 0);";
+ " return verifier.VerifyField<{{TYPE}}>("
+ "static_cast<const uint8_t *>(obj), 0, {{ALIGN}});";
} else {
code_ += getptr;
code_ += " return verifier.VerifyTable(ptr);";
@@ -1459,6 +1528,7 @@
if (opts_.generate_object_based_api) {
// Generate union Unpack() and Pack() functions.
code_ += "inline " + UnionUnPackSignature(enum_def, false) + " {";
+ code_ += " (void)resolver;";
code_ += " switch (type) {";
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end();
++it) {
@@ -1466,7 +1536,7 @@
if (ev.IsZero()) { continue; }
code_.SetValue("LABEL", GetEnumValUse(enum_def, ev));
- code_.SetValue("TYPE", GetUnionElement(ev, true, true));
+ code_.SetValue("TYPE", GetUnionElement(ev, false, opts_));
code_ += " case {{LABEL}}: {";
code_ += " auto ptr = reinterpret_cast<const {{TYPE}} *>(obj);";
if (ev.union_type.base_type == BASE_TYPE_STRUCT) {
@@ -1489,6 +1559,7 @@
code_ += "";
code_ += "inline " + UnionPackSignature(enum_def, false) + " {";
+ code_ += " (void)_rehasher;";
code_ += " switch (type) {";
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end();
++it) {
@@ -1496,15 +1567,14 @@
if (ev.IsZero()) { continue; }
code_.SetValue("LABEL", GetEnumValUse(enum_def, ev));
- code_.SetValue("TYPE", NativeName(GetUnionElement(ev, true, true, true),
- ev.union_type.struct_def, opts_));
- code_.SetValue("NAME", GetUnionElement(ev, false, true));
+ code_.SetValue("TYPE", GetUnionElement(ev, true, opts_));
code_ += " case {{LABEL}}: {";
code_ += " auto ptr = reinterpret_cast<const {{TYPE}} *>(value);";
if (ev.union_type.base_type == BASE_TYPE_STRUCT) {
if (ev.union_type.struct_def->fixed) {
code_ += " return _fbb.CreateStruct(*ptr).Union();";
} else {
+ code_.SetValue("NAME", ev.union_type.struct_def->name);
code_ +=
" return Create{{NAME}}(_fbb, ptr, _rehasher).Union();";
}
@@ -1530,11 +1600,12 @@
const auto &ev = **it;
if (ev.IsZero()) { continue; }
code_.SetValue("LABEL", GetEnumValUse(enum_def, ev));
- code_.SetValue("TYPE", NativeName(GetUnionElement(ev, true, true, true),
- ev.union_type.struct_def, opts_));
+ code_.SetValue("TYPE", GetUnionElement(ev, true, opts_));
code_ += " case {{LABEL}}: {";
bool copyable = true;
- if (ev.union_type.base_type == BASE_TYPE_STRUCT) {
+ if (opts_.g_cpp_std < cpp::CPP_STD_11 &&
+ ev.union_type.base_type == BASE_TYPE_STRUCT &&
+ !ev.union_type.struct_def->fixed) {
// Don't generate code to copy if table is not copyable.
// TODO(wvo): make tables copyable instead.
for (auto fit = ev.union_type.struct_def->fields.vec.begin();
@@ -1575,8 +1646,7 @@
const auto &ev = **it;
if (ev.IsZero()) { continue; }
code_.SetValue("LABEL", GetEnumValUse(enum_def, ev));
- code_.SetValue("TYPE", NativeName(GetUnionElement(ev, true, true, true),
- ev.union_type.struct_def, opts_));
+ code_.SetValue("TYPE", GetUnionElement(ev, true, opts_));
code_ += " case {{LABEL}}: {";
code_ += " auto ptr = reinterpret_cast<{{TYPE}} *>(value);";
code_ += " delete ptr;";
@@ -1621,7 +1691,7 @@
if (!opts_.generate_name_strings) { return; }
auto fullname = struct_def.defined_namespace->GetFullyQualifiedName(name);
code_.SetValue("NAME", fullname);
- code_.SetValue("CONSTEXPR", "FLATBUFFERS_CONSTEXPR");
+ code_.SetValue("CONSTEXPR", "FLATBUFFERS_CONSTEXPR_CPP11");
code_ += " static {{CONSTEXPR}} const char *GetFullyQualifiedName() {";
code_ += " return \"{{NAME}}\";";
code_ += " }";
@@ -1659,6 +1729,8 @@
} else {
return "0";
}
+ } else if (IsStruct(type) && (field.value.constant == "0")) {
+ return "nullptr";
} else {
return GenDefaultConstant(field);
}
@@ -1735,13 +1807,50 @@
}
}
+ // Returns true if `struct_def` needs a copy constructor and assignment
+ // operator because it has one or more table members, struct members with a
+ // custom cpp_type and non-naked pointer type, or vector members of those.
+ bool NeedsCopyCtorAssignOp(const StructDef &struct_def) {
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++it) {
+ const auto &field = **it;
+ const auto &type = field.value.type;
+ if (field.deprecated) continue;
+ if (type.base_type == BASE_TYPE_STRUCT) {
+ const auto cpp_type = field.attributes.Lookup("cpp_type");
+ const auto cpp_ptr_type = field.attributes.Lookup("cpp_ptr_type");
+ const bool is_ptr = !(IsStruct(type) && field.native_inline) ||
+ (cpp_type && cpp_ptr_type->constant != "naked");
+ if (is_ptr) { return true; }
+ } else if (IsVector(type)) {
+ const auto vec_type = type.VectorType();
+ if (vec_type.base_type == BASE_TYPE_UTYPE) continue;
+ const auto cpp_type = field.attributes.Lookup("cpp_type");
+ const auto cpp_ptr_type = field.attributes.Lookup("cpp_ptr_type");
+ const bool is_ptr =
+ (vec_type.base_type == BASE_TYPE_STRUCT && !IsStruct(vec_type)) ||
+ (cpp_type && cpp_ptr_type->constant != "naked");
+ if (is_ptr) { return true; }
+ }
+ }
+ return false;
+ }
+
// Generate the default constructor for this struct. Properly initialize all
// scalar members with default values.
void GenDefaultConstructor(const StructDef &struct_def) {
code_.SetValue("NATIVE_NAME",
NativeName(Name(struct_def), &struct_def, opts_));
- // In >= C++11, default member initializers are generated.
- if (opts_.g_cpp_std >= cpp::CPP_STD_11) { return; }
+ // In >= C++11, default member initializers are generated. To allow for
+ // aggregate initialization, do not emit a default constructor at all, with
+ // the exception of types that need a copy/move ctors and assignment
+ // operators.
+ if (opts_.g_cpp_std >= cpp::CPP_STD_11) {
+ if (NeedsCopyCtorAssignOp(struct_def)) {
+ code_ += " {{NATIVE_NAME}}() = default;";
+ }
+ return;
+ }
std::string initializer_list;
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
@@ -1785,6 +1894,126 @@
code_ += " }";
}
+ // Generate the >= C++11 copy/move constructor and assignment operator
+ // declarations if required. Tables that are default-copyable do not get
+ // user-provided copy/move constructors and assignment operators so they
+ // remain aggregates.
+ void GenCopyMoveCtorAndAssigOpDecls(const StructDef &struct_def) {
+ if (opts_.g_cpp_std < cpp::CPP_STD_11) return;
+ if (!NeedsCopyCtorAssignOp(struct_def)) return;
+ code_.SetValue("NATIVE_NAME",
+ NativeName(Name(struct_def), &struct_def, opts_));
+ code_ += " {{NATIVE_NAME}}(const {{NATIVE_NAME}} &o);";
+ code_ +=
+ " {{NATIVE_NAME}}({{NATIVE_NAME}}&&) FLATBUFFERS_NOEXCEPT = "
+ "default;";
+ code_ +=
+ " {{NATIVE_NAME}} &operator=({{NATIVE_NAME}} o) FLATBUFFERS_NOEXCEPT;";
+ }
+
+ // Generate the >= C++11 copy constructor and assignment operator definitions.
+ void GenCopyCtorAssignOpDefs(const StructDef &struct_def) {
+ if (opts_.g_cpp_std < cpp::CPP_STD_11) return;
+ if (!NeedsCopyCtorAssignOp(struct_def)) return;
+ std::string initializer_list;
+ std::string vector_copies;
+ std::string swaps;
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++it) {
+ const auto &field = **it;
+ const auto &type = field.value.type;
+ if (field.deprecated || type.base_type == BASE_TYPE_UTYPE) continue;
+ if (type.base_type == BASE_TYPE_STRUCT) {
+ if (!initializer_list.empty()) { initializer_list += ",\n "; }
+ const auto cpp_type = field.attributes.Lookup("cpp_type");
+ const auto cpp_ptr_type = field.attributes.Lookup("cpp_ptr_type");
+ auto type_name = (cpp_type) ? cpp_type->constant
+ : GenTypeNative(type, /*invector*/ false,
+ field, /*forcopy*/ true);
+ const bool is_ptr = !(IsStruct(type) && field.native_inline) ||
+ (cpp_type && cpp_ptr_type->constant != "naked");
+ CodeWriter cw;
+ cw.SetValue("FIELD", Name(field));
+ cw.SetValue("TYPE", type_name);
+ if (is_ptr) {
+ cw +=
+ "{{FIELD}}((o.{{FIELD}}) ? new {{TYPE}}(*o.{{FIELD}}) : "
+ "nullptr)\\";
+ initializer_list += cw.ToString();
+ } else {
+ cw += "{{FIELD}}(o.{{FIELD}})\\";
+ initializer_list += cw.ToString();
+ }
+ } else if (IsVector(type)) {
+ const auto vec_type = type.VectorType();
+ if (vec_type.base_type == BASE_TYPE_UTYPE) continue;
+ const auto cpp_type = field.attributes.Lookup("cpp_type");
+ const auto cpp_ptr_type = field.attributes.Lookup("cpp_ptr_type");
+ const auto type_name = (cpp_type)
+ ? cpp_type->constant
+ : GenTypeNative(vec_type, /*invector*/ true,
+ field, /*forcopy*/ true);
+ const bool is_ptr =
+ (vec_type.base_type == BASE_TYPE_STRUCT && !IsStruct(vec_type)) ||
+ (cpp_type && cpp_ptr_type->constant != "naked");
+ CodeWriter cw(" ");
+ cw.SetValue("FIELD", Name(field));
+ cw.SetValue("TYPE", type_name);
+ if (is_ptr) {
+ // Use emplace_back to construct the potentially-smart pointer element
+ // from a raw pointer to a new-allocated copy.
+ cw.IncrementIdentLevel();
+ cw += "{{FIELD}}.reserve(o.{{FIELD}}.size());";
+ cw +=
+ "for (const auto &{{FIELD}}_ : o.{{FIELD}}) { "
+ "{{FIELD}}.emplace_back(({{FIELD}}_) ? new {{TYPE}}(*{{FIELD}}_) "
+ ": nullptr); }";
+ vector_copies += cw.ToString();
+ } else {
+ // For non-pointer elements, use std::vector's copy constructor in the
+ // initializer list. This will yield better performance than an insert
+ // range loop for trivially-copyable element types.
+ if (!initializer_list.empty()) { initializer_list += ",\n "; }
+ cw += "{{FIELD}}(o.{{FIELD}})\\";
+ initializer_list += cw.ToString();
+ }
+ } else {
+ if (!initializer_list.empty()) { initializer_list += ",\n "; }
+ CodeWriter cw;
+ cw.SetValue("FIELD", Name(field));
+ cw += "{{FIELD}}(o.{{FIELD}})\\";
+ initializer_list += cw.ToString();
+ }
+ {
+ if (!swaps.empty()) { swaps += "\n "; }
+ CodeWriter cw;
+ cw.SetValue("FIELD", Name(field));
+ cw += "std::swap({{FIELD}}, o.{{FIELD}});\\";
+ swaps += cw.ToString();
+ }
+ }
+ if (!initializer_list.empty()) {
+ initializer_list = "\n : " + initializer_list;
+ }
+ if (!swaps.empty()) { swaps = " " + swaps; }
+
+ code_.SetValue("NATIVE_NAME",
+ NativeName(Name(struct_def), &struct_def, opts_));
+ code_.SetValue("INIT_LIST", initializer_list);
+ code_.SetValue("VEC_COPY", vector_copies);
+ code_.SetValue("SWAPS", swaps);
+
+ code_ +=
+ "inline {{NATIVE_NAME}}::{{NATIVE_NAME}}(const {{NATIVE_NAME}} &o)"
+ "{{INIT_LIST}} {";
+ code_ += "{{VEC_COPY}}}\n";
+ code_ +=
+ "inline {{NATIVE_NAME}} &{{NATIVE_NAME}}::operator="
+ "({{NATIVE_NAME}} o) FLATBUFFERS_NOEXCEPT {";
+ code_ += "{{SWAPS}}";
+ code_ += " return *this;\n}\n";
+ }
+
void GenCompareOperator(const StructDef &struct_def,
std::string accessSuffix = "") {
std::string compare_op;
@@ -1797,7 +2026,18 @@
field.value.type.element != BASE_TYPE_UTYPE)) {
if (!compare_op.empty()) { compare_op += " &&\n "; }
auto accessor = Name(field) + accessSuffix;
- compare_op += "(lhs." + accessor + " == rhs." + accessor + ")";
+ if (struct_def.fixed || field.native_inline ||
+ field.value.type.base_type != BASE_TYPE_STRUCT) {
+ compare_op += "(lhs." + accessor + " == rhs." + accessor + ")";
+ } else {
+ // Deep compare of std::unique_ptr. Null is not equal to empty.
+ std::string both_null =
+ "(lhs." + accessor + " == rhs." + accessor + ")";
+ std::string not_null_and_equal = "(lhs." + accessor + " && rhs." +
+ accessor + " && *lhs." + accessor +
+ " == *rhs." + accessor + ")";
+ compare_op += "(" + both_null + " || " + not_null_and_equal + ")";
+ }
}
}
@@ -1862,21 +2102,33 @@
}
GenOperatorNewDelete(struct_def);
GenDefaultConstructor(struct_def);
+ GenCopyMoveCtorAndAssigOpDecls(struct_def);
code_ += "};";
- if (opts_.gen_compare) GenCompareOperator(struct_def);
code_ += "";
}
+ void GenNativeTablePost(const StructDef &struct_def) {
+ if (opts_.gen_compare) {
+ const auto native_name = NativeName(Name(struct_def), &struct_def, opts_);
+ code_.SetValue("STRUCT_NAME", Name(struct_def));
+ code_.SetValue("NATIVE_NAME", native_name);
+ GenCompareOperator(struct_def);
+ code_ += "";
+ }
+ }
+
// Generate the code to call the appropriate Verify function(s) for a field.
void GenVerifyCall(const FieldDef &field, const char *prefix) {
code_.SetValue("PRE", prefix);
code_.SetValue("NAME", Name(field));
- code_.SetValue("REQUIRED", field.required ? "Required" : "");
+ code_.SetValue("REQUIRED", field.IsRequired() ? "Required" : "");
code_.SetValue("SIZE", GenTypeSize(field.value.type));
code_.SetValue("OFFSET", GenFieldOffsetName(field));
if (IsScalar(field.value.type.base_type) || IsStruct(field.value.type)) {
+ code_.SetValue("ALIGN", NumToString(InlineAlignment(field.value.type)));
code_ +=
- "{{PRE}}VerifyField{{REQUIRED}}<{{SIZE}}>(verifier, {{OFFSET}})\\";
+ "{{PRE}}VerifyField{{REQUIRED}}<{{SIZE}}>(verifier, "
+ "{{OFFSET}}, {{ALIGN}})\\";
} else {
code_ += "{{PRE}}VerifyOffset{{REQUIRED}}(verifier, {{OFFSET}})\\";
}
@@ -1923,6 +2175,19 @@
}
default: break;
}
+
+ auto nfn = GetNestedFlatBufferName(field);
+ if (!nfn.empty()) {
+ code_.SetValue("CPP_NAME", nfn);
+ // FIXME: file_identifier.
+ code_ +=
+ "{{PRE}}verifier.VerifyNestedFlatBuffer<{{CPP_NAME}}>"
+ "({{NAME}}(), nullptr)\\";
+ } else if (field.flexbuffer) {
+ code_ +=
+ "{{PRE}}flexbuffers::VerifyNestedFlexBuffer"
+ "({{NAME}}(), verifier)\\";
+ }
break;
}
default: {
@@ -1946,8 +2211,8 @@
code_ += " }";
if (is_string) {
- code_ += " int KeyCompareWithValue(const char *val) const {";
- code_ += " return strcmp({{FIELD_NAME}}()->c_str(), val);";
+ code_ += " int KeyCompareWithValue(const char *_{{FIELD_NAME}}) const {";
+ code_ += " return strcmp({{FIELD_NAME}}()->c_str(), _{{FIELD_NAME}});";
code_ += " }";
} else {
FLATBUFFERS_ASSERT(IsScalar(field.value.type.base_type));
@@ -1958,10 +2223,11 @@
}
// Returns {field<val: -1, field==val: 0, field>val: +1}.
code_.SetValue("KEY_TYPE", type);
- code_ += " int KeyCompareWithValue({{KEY_TYPE}} val) const {";
code_ +=
- " return static_cast<int>({{FIELD_NAME}}() > val) - "
- "static_cast<int>({{FIELD_NAME}}() < val);";
+ " int KeyCompareWithValue({{KEY_TYPE}} _{{FIELD_NAME}}) const {";
+ code_ +=
+ " return static_cast<int>({{FIELD_NAME}}() > _{{FIELD_NAME}}) - "
+ "static_cast<int>({{FIELD_NAME}}() < _{{FIELD_NAME}});";
code_ += " }";
}
}
@@ -1978,7 +2244,7 @@
for (auto u_it = u->Vals().begin(); u_it != u->Vals().end(); ++u_it) {
auto &ev = **u_it;
if (ev.union_type.base_type == BASE_TYPE_NONE) { continue; }
- auto full_struct_name = GetUnionElement(ev, true, true);
+ auto full_struct_name = GetUnionElement(ev, false, opts_);
// @TODO: Mby make this decisions more universal? How?
code_.SetValue("U_GET_TYPE",
@@ -2042,6 +2308,131 @@
if (type.base_type == BASE_TYPE_UNION) { GenTableUnionAsGetters(field); }
}
+ void GenTableFieldType(const FieldDef &field) {
+ const auto &type = field.value.type;
+ const auto offset_str = GenFieldOffsetName(field);
+ if (!field.IsScalarOptional()) {
+ std::string afterptr = " *" + NullableExtension();
+ code_.SetValue("FIELD_TYPE",
+ GenTypeGet(type, "", "const ", afterptr.c_str(), true));
+ code_ += " {{FIELD_TYPE}}\\";
+ } else {
+ code_.SetValue("FIELD_TYPE", GenOptionalDecl(type));
+ code_ += " {{FIELD_TYPE}}\\";
+ }
+ }
+
+ void GenStructFieldType(const FieldDef &field) {
+ const auto is_array = IsArray(field.value.type);
+ std::string field_type =
+ GenTypeGet(field.value.type, "", is_array ? "" : "const ",
+ is_array ? "" : " &", true);
+ code_.SetValue("FIELD_TYPE", field_type);
+ code_ += " {{FIELD_TYPE}}\\";
+ }
+
+ void GenFieldTypeHelper(const StructDef &struct_def) {
+ if (struct_def.fields.vec.empty()) { return; }
+ code_ += " template<size_t Index>";
+ code_ += " using FieldType = \\";
+ code_ += "decltype(std::declval<type>().get_field<Index>());";
+ }
+
+ void GenIndexBasedFieldGetter(const StructDef &struct_def) {
+ if (struct_def.fields.vec.empty()) { return; }
+ code_ += " template<size_t Index>";
+ code_ += " auto get_field() const {";
+
+ size_t index = 0;
+ bool need_else = false;
+ // Generate one index-based getter for each field.
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++it) {
+ const auto &field = **it;
+ if (field.deprecated) {
+ // Deprecated fields won't be accessible.
+ continue;
+ }
+ code_.SetValue("FIELD_NAME", Name(field));
+ code_.SetValue("FIELD_INDEX",
+ std::to_string(static_cast<long long>(index++)));
+ if (need_else) {
+ code_ += " else \\";
+ } else {
+ code_ += " \\";
+ }
+ need_else = true;
+ code_ += "if constexpr (Index == {{FIELD_INDEX}}) \\";
+ code_ += "return {{FIELD_NAME}}();";
+ }
+ code_ += " else static_assert(Index != Index, \"Invalid Field Index\");";
+ code_ += " }";
+ }
+
+ // Sample for Vec3:
+ //
+ // static constexpr std::array<const char *, 3> field_names = {
+ // "x",
+ // "y",
+ // "z"
+ // };
+ //
+ void GenFieldNames(const StructDef &struct_def) {
+ code_ += " static constexpr std::array<\\";
+ code_ += "const char *, fields_number> field_names = {\\";
+ if (struct_def.fields.vec.empty()) {
+ code_ += "};";
+ return;
+ }
+ code_ += "";
+ // Generate the field_names elements.
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++it) {
+ const auto &field = **it;
+ if (field.deprecated) {
+ // Deprecated fields won't be accessible.
+ continue;
+ }
+ code_.SetValue("FIELD_NAME", Name(field));
+ code_ += " \"{{FIELD_NAME}}\"\\";
+ if (it + 1 != struct_def.fields.vec.end()) { code_ += ","; }
+ }
+ code_ += "\n };";
+ }
+
+ void GenFieldsNumber(const StructDef &struct_def) {
+ const auto non_deprecated_field_count = std::count_if(
+ struct_def.fields.vec.begin(), struct_def.fields.vec.end(),
+ [](const FieldDef *field) { return !field->deprecated; });
+ code_.SetValue(
+ "FIELD_COUNT",
+ std::to_string(static_cast<long long>(non_deprecated_field_count)));
+ code_ += " static constexpr size_t fields_number = {{FIELD_COUNT}};";
+ }
+
+ void GenTraitsStruct(const StructDef &struct_def) {
+ code_.SetValue(
+ "FULLY_QUALIFIED_NAME",
+ struct_def.defined_namespace->GetFullyQualifiedName(Name(struct_def)));
+ code_ += "struct {{STRUCT_NAME}}::Traits {";
+ code_ += " using type = {{STRUCT_NAME}};";
+ if (!struct_def.fixed) {
+ // We have a table and not a struct.
+ code_ += " static auto constexpr Create = Create{{STRUCT_NAME}};";
+ }
+ if (opts_.cpp_static_reflection) {
+ code_ += " static constexpr auto name = \"{{STRUCT_NAME}}\";";
+ code_ +=
+ " static constexpr auto fully_qualified_name = "
+ "\"{{FULLY_QUALIFIED_NAME}}\";";
+ GenFieldsNumber(struct_def);
+ GenFieldNames(struct_def);
+ GenFieldTypeHelper(struct_def);
+ }
+ code_ += "};";
+ code_ += "";
+ }
+
void GenTableFieldSetter(const FieldDef &field) {
const auto &type = field.value.type;
const bool is_scalar = IsScalar(type.base_type);
@@ -2057,15 +2448,25 @@
code_.SetValue("FIELD_VALUE",
GenUnderlyingCast(field, false, "_" + Name(field)));
- code_ +=
- " bool mutate_{{FIELD_NAME}}({{FIELD_TYPE}} "
- "_{{FIELD_NAME}}) {";
+ code_ += " bool mutate_{{FIELD_NAME}}({{FIELD_TYPE}} _{{FIELD_NAME}}\\";
if (false == field.IsScalarOptional()) {
code_.SetValue("DEFAULT_VALUE", GenDefaultConstant(field));
+ code_.SetValue(
+ "INTERFACE_DEFAULT_VALUE",
+ GenUnderlyingCast(field, true, GenDefaultConstant(field)));
+
+ // GenUnderlyingCast for a bool field generates 0 != 0
+ // So the type has to be checked and the appropriate default chosen
+ if (IsBool(field.value.type.base_type)) {
+ code_ += " = {{DEFAULT_VALUE}}) {";
+ } else {
+ code_ += " = {{INTERFACE_DEFAULT_VALUE}}) {";
+ }
code_ +=
" return {{SET_FN}}({{OFFSET_NAME}}, {{FIELD_VALUE}}, "
"{{DEFAULT_VALUE}});";
} else {
+ code_ += ") {";
code_ += " return {{SET_FN}}({{OFFSET_NAME}}, {{FIELD_VALUE}});";
}
code_ += " }";
@@ -2083,6 +2484,21 @@
}
}
+ std::string GetNestedFlatBufferName(const FieldDef &field) {
+ auto nested = field.attributes.Lookup("nested_flatbuffer");
+ if (!nested) return "";
+ std::string qualified_name = nested->constant;
+ auto nested_root = parser_.LookupStruct(nested->constant);
+ if (nested_root == nullptr) {
+ qualified_name =
+ parser_.current_namespace_->GetFullyQualifiedName(nested->constant);
+ nested_root = parser_.LookupStruct(qualified_name);
+ }
+ FLATBUFFERS_ASSERT(nested_root); // Guaranteed to exist by parser.
+ (void)nested_root;
+ return TranslateNameSpace(qualified_name);
+ }
+
// Generate an accessor struct, builder structs & function for a table.
void GenTable(const StructDef &struct_def) {
if (opts_.generate_object_based_api) { GenNativeTable(struct_def); }
@@ -2146,19 +2562,9 @@
GenTableFieldGetter(field);
if (opts_.mutable_buffer) { GenTableFieldSetter(field); }
- auto nested = field.attributes.Lookup("nested_flatbuffer");
- if (nested) {
- std::string qualified_name = nested->constant;
- auto nested_root = parser_.LookupStruct(nested->constant);
- if (nested_root == nullptr) {
- qualified_name = parser_.current_namespace_->GetFullyQualifiedName(
- nested->constant);
- nested_root = parser_.LookupStruct(qualified_name);
- }
- FLATBUFFERS_ASSERT(nested_root); // Guaranteed to exist by parser.
- (void)nested_root;
- code_.SetValue("CPP_NAME", TranslateNameSpace(qualified_name));
-
+ auto nfn = GetNestedFlatBufferName(field);
+ if (!nfn.empty()) {
+ code_.SetValue("CPP_NAME", nfn);
code_ += " const {{CPP_NAME}} *{{FIELD_NAME}}_nested_root() const {";
code_ +=
" return "
@@ -2182,6 +2588,8 @@
if (field.key) { GenKeyFieldMethods(field); }
}
+ if (opts_.cpp_static_reflection) { GenIndexBasedFieldGetter(struct_def); }
+
// Generate a verifier function that can check a buffer from an untrusted
// source will never cause reads outside the buffer.
code_ += " bool Verify(flatbuffers::Verifier &verifier) const {";
@@ -2223,7 +2631,7 @@
auto &ev = **u_it;
if (ev.union_type.base_type == BASE_TYPE_NONE) { continue; }
- auto full_struct_name = GetUnionElement(ev, true, true);
+ auto full_struct_name = GetUnionElement(ev, false, opts_);
code_.SetValue(
"U_ELEMENT_TYPE",
@@ -2340,7 +2748,7 @@
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
const auto &field = **it;
- if (!field.deprecated && field.required) {
+ if (!field.deprecated && field.IsRequired()) {
code_.SetValue("FIELD_NAME", Name(field));
code_.SetValue("OFFSET_NAME", GenFieldOffsetName(field));
code_ += " fbb_.Required(o, {{STRUCT_NAME}}::{{OFFSET_NAME}});";
@@ -2389,13 +2797,7 @@
// Definition for type traits for this table type. This allows querying var-
// ious compile-time traits of the table.
- if (opts_.g_cpp_std >= cpp::CPP_STD_17) {
- code_ += "struct {{STRUCT_NAME}}::Traits {";
- code_ += " using type = {{STRUCT_NAME}};";
- code_ += " static auto constexpr Create = Create{{STRUCT_NAME}};";
- code_ += "};";
- code_ += "";
- }
+ if (opts_.g_cpp_std >= cpp::CPP_STD_17) { GenTraitsStruct(struct_def); }
// Generate a CreateXDirect function with vector types as parameters
if (opts_.cpp_direct_copy && has_string_or_vector_fields) {
@@ -2462,8 +2864,7 @@
if (!field.deprecated) {
code_.SetValue("FIELD_NAME", Name(field));
code_ += ",\n {{FIELD_NAME}}\\";
- if (IsString(field.value.type) ||
- IsVector(field.value.type)) {
+ if (IsString(field.value.type) || IsVector(field.value.type)) {
code_ += "__\\";
}
}
@@ -2495,20 +2896,26 @@
}
}
case BASE_TYPE_STRUCT: {
- const auto name = WrapInNameSpace(*type.struct_def);
if (IsStruct(type)) {
- auto native_type = type.struct_def->attributes.Lookup("native_type");
+ const auto &struct_attrs = type.struct_def->attributes;
+ const auto native_type = struct_attrs.Lookup("native_type");
if (native_type) {
- return "flatbuffers::UnPack(*" + val + ")";
+ std::string unpack_call = "flatbuffers::UnPack";
+ const auto pack_name = struct_attrs.Lookup("native_type_pack_name");
+ if (pack_name) { unpack_call += pack_name->constant; }
+ unpack_call += "(*" + val + ")";
+ return unpack_call;
} else if (invector || afield.native_inline) {
return "*" + val;
} else {
+ const auto name = WrapInNameSpace(*type.struct_def);
const auto ptype = GenTypeNativePtr(name, &afield, true);
return ptype + "(new " + name + "(*" + val + "))";
}
} else {
const auto ptype = GenTypeNativePtr(
- NativeName(name, type.struct_def, opts_), &afield, true);
+ WrapNativeNameInNameSpace(*type.struct_def, opts_), &afield,
+ true);
return ptype + "(" + val + "->UnPack(_resolver))";
}
}
@@ -2551,9 +2958,7 @@
WrapInNameSpace(*field.value.type.enum_def) + ">(";
}
indexing += "_e->Get(_i)";
- if (field.value.type.enum_def) {
- indexing += ")";
- }
+ if (field.value.type.enum_def) { indexing += ")"; }
if (field.value.type.element == BASE_TYPE_BOOL) {
indexing += " != 0";
}
@@ -2593,9 +2998,19 @@
code += "/* else do nothing */";
}
} else {
+ const bool is_pointer =
+ field.value.type.VectorType().base_type == BASE_TYPE_STRUCT &&
+ !IsStruct(field.value.type.VectorType());
+ if (is_pointer) {
+ code += "if(_o->" + name + "[_i]" + ") { ";
+ code += indexing + "->UnPackTo(_o->" + name +
+ "[_i].get(), _resolver);";
+ code += " } else { ";
+ }
code += "_o->" + name + "[_i]" + access + " = ";
code += GenUnpackVal(field.value.type.VectorType(), indexing, true,
field);
+ if (is_pointer) { code += "; }"; }
}
code += "; } }";
}
@@ -2642,8 +3057,17 @@
} else {
// Generate code for assigning the value, of the form:
// _o->field = value;
+ const bool is_pointer =
+ field.value.type.base_type == BASE_TYPE_STRUCT &&
+ !IsStruct(field.value.type);
+ if (is_pointer) {
+ code += "{ if(_o->" + Name(field) + ") { ";
+ code += "_e->UnPackTo(_o->" + Name(field) + ".get(), _resolver);";
+ code += " } else { ";
+ }
code += "_o->" + Name(field) + " = ";
code += GenUnpackVal(field.value.type, "_e", false, field) + ";";
+ if (is_pointer) { code += " } }"; }
}
break;
}
@@ -2687,7 +3111,7 @@
// in _o->field before attempting to access it. If there isn't,
// depending on set_empty_strings_to_null either set it to 0 or an empty
// string.
- if (!field.required) {
+ if (!field.IsRequired()) {
auto empty_value = opts_.set_empty_strings_to_null
? "0"
: "_fbb.CreateSharedString(\"\")";
@@ -2725,15 +3149,24 @@
}
case BASE_TYPE_STRUCT: {
if (IsStruct(vector_type)) {
- auto native_type =
- field.value.type.struct_def->attributes.Lookup("native_type");
+ const auto &struct_attrs =
+ field.value.type.struct_def->attributes;
+ const auto native_type = struct_attrs.Lookup("native_type");
if (native_type) {
code += "_fbb.CreateVectorOfNativeStructs<";
- code += WrapInNameSpace(*vector_type.struct_def) + ">";
+ code += WrapInNameSpace(*vector_type.struct_def) + ", " +
+ native_type->constant + ">";
+ code += "(" + value;
+ const auto pack_name =
+ struct_attrs.Lookup("native_type_pack_name");
+ if (pack_name) {
+ code += ", flatbuffers::Pack" + pack_name->constant;
+ }
+ code += ")";
} else {
code += "_fbb.CreateVectorOfStructs";
+ code += "(" + value + ")";
}
- code += "(" + value + ")";
} else {
code += "_fbb.CreateVector<flatbuffers::Offset<";
code += WrapInNameSpace(*vector_type.struct_def) + ">> ";
@@ -2762,10 +3195,15 @@
}
case BASE_TYPE_UTYPE: {
value = StripUnionType(value);
- code += "_fbb.CreateVector<uint8_t>(" + value +
- ".size(), [](size_t i, _VectorArgs *__va) { "
- "return static_cast<uint8_t>(__va->_" +
- value + "[i].type); }, &_va)";
+ auto type = opts_.scoped_enums ? Name(*field.value.type.enum_def)
+ : "uint8_t";
+ auto enum_value = "__va->_" + value + "[i].type";
+ if (!opts_.scoped_enums)
+ enum_value = "static_cast<uint8_t>(" + enum_value + ")";
+
+ code += "_fbb.CreateVector<" + type + ">(" + value +
+ ".size(), [](size_t i, _VectorArgs *__va) { return " +
+ enum_value + "; }, &_va)";
break;
}
default: {
@@ -2796,7 +3234,7 @@
// If set_empty_vectors_to_null option is enabled, for optional fields,
// check to see if there actually is any data in _o->field before
// attempting to access it.
- if (opts_.set_empty_vectors_to_null && !field.required) {
+ if (opts_.set_empty_vectors_to_null && !field.IsRequired()) {
code = value + ".size() ? " + code + " : 0";
}
break;
@@ -2808,10 +3246,14 @@
}
case BASE_TYPE_STRUCT: {
if (IsStruct(field.value.type)) {
- auto native_type =
- field.value.type.struct_def->attributes.Lookup("native_type");
+ const auto &struct_attribs = field.value.type.struct_def->attributes;
+ const auto native_type = struct_attribs.Lookup("native_type");
if (native_type) {
- code += "flatbuffers::Pack(" + value + ")";
+ code += "flatbuffers::Pack";
+ const auto pack_name =
+ struct_attribs.Lookup("native_type_pack_name");
+ if (pack_name) { code += pack_name->constant; }
+ code += "(" + value + ")";
} else if (field.native_inline) {
code += "&" + value;
} else {
@@ -2836,18 +3278,22 @@
// Generate code for tables that needs to come after the regular definition.
void GenTablePost(const StructDef &struct_def) {
+ if (opts_.generate_object_based_api) { GenNativeTablePost(struct_def); }
+
code_.SetValue("STRUCT_NAME", Name(struct_def));
code_.SetValue("NATIVE_NAME",
NativeName(Name(struct_def), &struct_def, opts_));
if (opts_.generate_object_based_api) {
+ // Generate the >= C++11 copy ctor and assignment operator definitions.
+ GenCopyCtorAssignOpDefs(struct_def);
+
// Generate the X::UnPack() method.
code_ +=
"inline " + TableUnPackSignature(struct_def, false, opts_) + " {";
if (opts_.g_cpp_std == cpp::CPP_STD_X0) {
- auto native_name =
- NativeName(WrapInNameSpace(struct_def), &struct_def, parser_.opts);
+ auto native_name = WrapNativeNameInNameSpace(struct_def, parser_.opts);
code_.SetValue("POINTER_TYPE",
GenTypeNativePtr(native_name, nullptr, false));
code_ +=
@@ -3172,6 +3618,8 @@
code_ += "";
code_ += " public:";
+ if (opts_.g_cpp_std >= cpp::CPP_STD_17) { code_ += " struct Traits;"; }
+
// Make TypeTable accessible via the generated struct.
if (opts_.mini_reflect != IDLOptions::kNone) {
code_ +=
@@ -3257,12 +3705,19 @@
}
code_.SetValue("NATIVE_NAME", Name(struct_def));
GenOperatorNewDelete(struct_def);
+
+ if (opts_.cpp_static_reflection) { GenIndexBasedFieldGetter(struct_def); }
+
code_ += "};";
code_.SetValue("STRUCT_BYTE_SIZE", NumToString(struct_def.bytesize));
code_ += "FLATBUFFERS_STRUCT_END({{STRUCT_NAME}}, {{STRUCT_BYTE_SIZE}});";
if (opts_.gen_compare) GenCompareOperator(struct_def, "()");
code_ += "";
+
+ // Definition for type traits for this table type. This allows querying var-
+ // ious compile-time traits of the table.
+ if (opts_.g_cpp_std >= cpp::CPP_STD_17) { GenTraitsStruct(struct_def); }
}
// Set up the correct namespace. Only open a namespace if the existing one is
@@ -3312,7 +3767,7 @@
cpp::IDLOptionsCpp opts(parser.opts);
// The '--cpp_std' argument could be extended (like ASAN):
// Example: "flatc --cpp_std c++17:option1:option2".
- auto cpp_std = !opts.cpp_std.empty() ? opts.cpp_std : "C++0X";
+ auto cpp_std = !opts.cpp_std.empty() ? opts.cpp_std : "C++11";
std::transform(cpp_std.begin(), cpp_std.end(), cpp_std.begin(), CharToUpper);
if (cpp_std == "C++0X") {
opts.g_cpp_std = cpp::CPP_STD_X0;
@@ -3335,6 +3790,13 @@
// The opts.scoped_enums has priority.
opts.g_only_fixed_enums |= opts.scoped_enums;
+ if (opts.cpp_static_reflection && opts.g_cpp_std < cpp::CPP_STD_17) {
+ LogCompilerError(
+ "--cpp-static-reflection requires using --cpp-std at \"C++17\" or "
+ "higher.");
+ return false;
+ }
+
cpp::CppGenerator generator(parser, path, file_name, opts);
return generator.generate();
}
diff --git a/src/idl_gen_csharp.cpp b/src/idl_gen_csharp.cpp
index d2f14f0..cb605de 100644
--- a/src/idl_gen_csharp.cpp
+++ b/src/idl_gen_csharp.cpp
@@ -16,15 +16,13 @@
// independent from idl_parser, since this code is not needed for most clients
+#include <unordered_set>
+
#include "flatbuffers/code_generators.h"
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
-#if defined(FLATBUFFERS_CPP98_STL)
-# include <cctype>
-#endif // defined(FLATBUFFERS_CPP98_STL)
-
namespace flatbuffers {
static TypedFloatConstantGenerator CSharpFloatGen("Double.", "Single.", "NaN",
@@ -46,8 +44,100 @@
public:
CSharpGenerator(const Parser &parser, const std::string &path,
const std::string &file_name)
- : BaseGenerator(parser, path, file_name, "", ".", "cs"),
- cur_name_space_(nullptr) {}
+ : BaseGenerator(parser, path, file_name,
+ parser.opts.cs_global_alias ? "global::" : "", ".", "cs"),
+ cur_name_space_(nullptr) {
+ // clang-format off
+
+ // List of keywords retrieved from here:
+ // https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/
+
+ // One per line to ease comparisons to that list are easier
+
+ static const char *const keywords[] = {
+ "abstract",
+ "as",
+ "base",
+ "bool",
+ "break",
+ "byte",
+ "case",
+ "catch",
+ "char",
+ "checked",
+ "class",
+ "const",
+ "continue",
+ "decimal",
+ "default",
+ "delegate",
+ "do",
+ "double",
+ "else",
+ "enum",
+ "event",
+ "explicit",
+ "extern",
+ "false",
+ "finally",
+ "fixed",
+ "float",
+ "for",
+ "foreach",
+ "goto",
+ "if",
+ "implicit",
+ "in",
+ "int",
+ "interface",
+ "internal",
+ "is",
+ "lock",
+ "long",
+ "namespace",
+ "new",
+ "null",
+ "object",
+ "operator",
+ "out",
+ "override",
+ "params",
+ "private",
+ "protected",
+ "public",
+ "readonly",
+ "ref",
+ "return",
+ "sbyte",
+ "sealed",
+ "short",
+ "sizeof",
+ "stackalloc",
+ "static",
+ "string",
+ "struct",
+ "switch",
+ "this",
+ "throw",
+ "true",
+ "try",
+ "typeof",
+ "uint",
+ "ulong",
+ "unchecked",
+ "unsafe",
+ "ushort",
+ "using",
+ "virtual",
+ "void",
+ "volatile",
+ "while",
+ nullptr,
+ // clang-format on
+ };
+
+ for (auto kw = keywords; *kw; kw++) keywords_.insert(*kw);
+ }
CSharpGenerator &operator=(const CSharpGenerator &);
@@ -65,7 +155,7 @@
one_file_code += enumcode;
} else {
if (!SaveType(enum_def.name, *enum_def.defined_namespace, enumcode,
- false))
+ false, parser_.opts))
return false;
}
}
@@ -81,22 +171,45 @@
one_file_code += declcode;
} else {
if (!SaveType(struct_def.name, *struct_def.defined_namespace, declcode,
- true))
+ true, parser_.opts))
return false;
}
}
if (parser_.opts.one_file) {
return SaveType(file_name_, *parser_.current_namespace_, one_file_code,
- true);
+ true, parser_.opts);
}
return true;
}
+ private:
+ std::unordered_set<std::string> keywords_;
+
+ std::string EscapeKeyword(const std::string &name) const {
+ return keywords_.find(name) == keywords_.end() ? name : "@" + name;
+ }
+
+ std::string Name(const FieldDef &field) const {
+ std::string name = ConvertCase(field.name, Case::kUpperCamel);
+ return EscapeKeyword(name);
+ }
+
+ std::string Name(const Definition &def) const {
+ return EscapeKeyword(def.name);
+ }
+
+ std::string NamespacedName(const Definition &def) const {
+ return WrapInNameSpace(def.defined_namespace, Name(def));
+ }
+
+ std::string Name(const EnumVal &ev) const { return EscapeKeyword(ev.name); }
+
// Save out the generated code for a single class while adding
// declaration boilerplate.
bool SaveType(const std::string &defname, const Namespace &ns,
- const std::string &classcode, bool needs_includes) const {
+ const std::string &classcode, bool needs_includes,
+ const IDLOptions &options) const {
if (!classcode.length()) return true;
std::string code =
@@ -117,7 +230,10 @@
}
code += classcode;
if (!namespace_name.empty()) { code += "\n}\n"; }
- auto filename = NamespaceDir(ns) + defname + ".cs";
+ auto filename = NamespaceDir(ns) + defname;
+ if (options.one_file) { filename += options.filename_suffix; }
+ filename +=
+ options.filename_extension.empty() ? ".cs" : options.filename_extension;
return SaveFile(filename.c_str(), code, false);
}
@@ -134,9 +250,9 @@
// clang-format on
if (enableLangOverrides) {
- if (IsEnum(type)) return WrapInNameSpace(*type.enum_def);
+ if (IsEnum(type)) return NamespacedName(*type.enum_def);
if (type.base_type == BASE_TYPE_STRUCT) {
- return "Offset<" + WrapInNameSpace(*type.struct_def) + ">";
+ return "Offset<" + NamespacedName(*type.struct_def) + ">";
}
}
@@ -151,7 +267,7 @@
switch (type.base_type) {
case BASE_TYPE_STRING: return "string";
case BASE_TYPE_VECTOR: return GenTypeGet(type.VectorType());
- case BASE_TYPE_STRUCT: return WrapInNameSpace(*type.struct_def);
+ case BASE_TYPE_STRUCT: return NamespacedName(*type.struct_def);
case BASE_TYPE_UNION: return "TTable";
default: return "Table";
}
@@ -165,12 +281,12 @@
}
std::string GenOffsetType(const StructDef &struct_def) const {
- return "Offset<" + WrapInNameSpace(struct_def) + ">";
+ return "Offset<" + NamespacedName(struct_def) + ">";
}
std::string GenOffsetConstruct(const StructDef &struct_def,
const std::string &variable_name) const {
- return "new Offset<" + WrapInNameSpace(struct_def) + ">(" + variable_name +
+ return "new Offset<" + NamespacedName(struct_def) + ">(" + variable_name +
")";
}
@@ -179,7 +295,7 @@
if (IsSeries(type)) {
return DestinationCast(type.VectorType());
} else {
- if (IsEnum(type)) return "(" + WrapInNameSpace(*type.enum_def) + ")";
+ if (IsEnum(type)) return "(" + NamespacedName(*type.enum_def) + ")";
}
return "";
}
@@ -190,17 +306,19 @@
// would be cast down to int before being put onto the buffer. In C#, one cast
// directly cast an Enum to its underlying type, which is essential before
// putting it onto the buffer.
- std::string SourceCast(const Type &type) const {
+ std::string SourceCast(const Type &type,
+ const bool isOptional = false) const {
if (IsSeries(type)) {
return SourceCast(type.VectorType());
} else {
- if (IsEnum(type)) return "(" + GenTypeBasic(type, false) + ")";
+ if (IsEnum(type))
+ return "(" + GenTypeBasic(type, false) + (isOptional ? "?" : "") + ")";
}
return "";
}
- std::string SourceCastBasic(const Type &type) const {
- return IsScalar(type.base_type) ? SourceCast(type) : "";
+ std::string SourceCastBasic(const Type &type, const bool isOptional) const {
+ return IsScalar(type.base_type) ? SourceCast(type, isOptional) : "";
}
std::string GenEnumDefaultValue(const FieldDef &field) const {
@@ -208,7 +326,7 @@
FLATBUFFERS_ASSERT(value.type.enum_def);
auto &enum_def = *value.type.enum_def;
auto enum_val = enum_def.FindByValue(value.constant);
- return enum_val ? (WrapInNameSpace(enum_def) + "." + enum_val->name)
+ return enum_val ? (NamespacedName(enum_def) + "." + Name(*enum_val))
: value.constant;
}
@@ -252,7 +370,7 @@
switch (value.type.base_type) {
case BASE_TYPE_STRING: return "default(StringOffset)";
case BASE_TYPE_STRUCT:
- return "default(Offset<" + WrapInNameSpace(*value.type.struct_def) +
+ return "default(Offset<" + NamespacedName(*value.type.struct_def) +
">)";
case BASE_TYPE_VECTOR: return "default(VectorOffset)";
default: break;
@@ -293,14 +411,14 @@
} else {
code += "public ";
}
- code += "enum " + enum_def.name;
+ code += "enum " + Name(enum_def);
code += " : " + GenTypeBasic(enum_def.underlying_type, false);
code += "\n{\n";
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
auto &ev = **it;
GenComment(ev.doc_comment, code_ptr, &comment_config, " ");
code += " ";
- code += ev.name + " = ";
+ code += Name(ev) + " = ";
code += enum_def.ToString(ev);
code += ",\n";
}
@@ -334,7 +452,7 @@
if (type.base_type == BASE_TYPE_BOOL) {
getter = "0!=" + getter;
} else if (GenTypeBasic(type, false) != "byte") {
- getter += MakeCamel(GenTypeBasic(type, false));
+ getter += ConvertCase(GenTypeBasic(type, false), Case::kUpperCamel);
}
return getter;
}
@@ -350,7 +468,7 @@
auto dest_cast = DestinationCast(type);
auto getter = data_buffer + ".Get";
if (GenTypeBasic(type, false) != "byte") {
- getter += MakeCamel(GenTypeBasic(type, false));
+ getter += ConvertCase(GenTypeBasic(type, false), Case::kUpperCamel);
}
getter = dest_cast + getter + "(" + GenOffsetGetter(key_field, num) + ")" +
dest_mask;
@@ -364,7 +482,7 @@
std::string setter = "__p.bb.Put";
if (GenTypeBasic(type, false) != "byte" &&
type.base_type != BASE_TYPE_BOOL) {
- setter += MakeCamel(GenTypeBasic(type, false));
+ setter += ConvertCase(GenTypeBasic(type, false), Case::kUpperCamel);
}
return setter;
} else {
@@ -374,8 +492,9 @@
// Returns the method name for use with add/put calls.
std::string GenMethod(const Type &type) const {
- return IsScalar(type.base_type) ? MakeCamel(GenTypeBasic(type, false))
- : (IsStruct(type) ? "Struct" : "Offset");
+ return IsScalar(type.base_type)
+ ? ConvertCase(GenTypeBasic(type, false), Case::kUpperCamel)
+ : (IsStruct(type) ? "Struct" : "Offset");
}
// Recursively generate arguments for a constructor, to deal with nested
@@ -395,7 +514,8 @@
// don't clash, and to make it obvious these arguments are constructing
// a nested struct, prefix the name with the field name.
GenStructArgs(*field_type.struct_def, code_ptr,
- (nameprefix + (field.name + "_")).c_str(), array_cnt);
+ (nameprefix + (EscapeKeyword(field.name) + "_")).c_str(),
+ array_cnt);
} else {
code += ", ";
code += GenTypeBasic(type);
@@ -407,7 +527,7 @@
}
code += " ";
code += nameprefix;
- code += MakeCamel(field.name, true);
+ code += Name(field);
}
}
}
@@ -454,7 +574,7 @@
code += indent + " builder.Put";
code += GenMethod(type) + "(";
code += SourceCast(type);
- auto argname = nameprefix + MakeCamel(field.name, true);
+ auto argname = nameprefix + Name(field);
code += argname;
size_t array_cnt = index + (IsArray(field_type) ? 1 : 0);
if (array_cnt > 0) {
@@ -553,7 +673,7 @@
// Force compile time error if not using the same version runtime.
code += " public static void ValidateVersion() {";
code += " FlatBufferConstants.";
- code += "FLATBUFFERS_1_12_0(); ";
+ code += "FLATBUFFERS_2_0_0(); ";
code += "}\n";
// Generate a special accessor for the table that when used as the root
@@ -618,7 +738,8 @@
std::string dest_mask = "";
std::string dest_cast = DestinationCast(field.value.type);
std::string src_cast = SourceCast(field.value.type);
- std::string field_name_camel = MakeCamel(field.name, true);
+ std::string field_name_camel = Name(field);
+ if (field_name_camel == struct_def.name) { field_name_camel += "_"; }
std::string method_start =
" public " + type_name_dest + optional + " " + field_name_camel;
std::string obj = "(new " + type_name + "())";
@@ -745,8 +866,7 @@
HasUnionStringValue(*vectortype.enum_def)) {
code += member_suffix;
code += "}\n";
- code += " public string " + MakeCamel(field.name, true) +
- "AsString(int j)";
+ code += " public string " + Name(field) + "AsString(int j)";
code += offset_prefix + GenGetter(Type(BASE_TYPE_STRING));
code += "(" + index + ") : null";
}
@@ -759,8 +879,7 @@
if (HasUnionStringValue(*field.value.type.enum_def)) {
code += member_suffix;
code += "}\n";
- code += " public string " + MakeCamel(field.name, true) +
- "AsString()";
+ code += " public string " + Name(field) + "AsString()";
code += offset_prefix + GenGetter(Type(BASE_TYPE_STRING));
code += "(o + __p.bb_pos) : null";
}
@@ -795,7 +914,7 @@
code += member_suffix;
code += "}\n";
if (IsVector(field.value.type)) {
- code += " public int " + MakeCamel(field.name, true);
+ code += " public int " + Name(field);
code += "Length";
code += " { get";
code += offset_prefix;
@@ -810,9 +929,9 @@
for (auto kit = fields.begin(); kit != fields.end(); ++kit) {
auto &key_field = **kit;
if (key_field.key) {
- auto qualified_name = WrapInNameSpace(sd);
+ auto qualified_name = NamespacedName(sd);
code += " public " + qualified_name + "? ";
- code += MakeCamel(field.name, true) + "ByKey(";
+ code += Name(field) + "ByKey(";
code += GenTypeGet(key_field.value.type) + " key)";
code += offset_prefix;
code += qualified_name + ".__lookup_by_key(";
@@ -831,7 +950,7 @@
code += "#if ENABLE_SPAN_T\n";
code += " public Span<" + GenTypeBasic(field.value.type.VectorType()) +
"> Get";
- code += MakeCamel(field.name, true);
+ code += Name(field);
code += "Bytes() { return ";
code += "__p.__vector_as_span<" +
GenTypeBasic(field.value.type.VectorType()) + ">(";
@@ -841,7 +960,7 @@
code += "); }\n";
code += "#else\n";
code += " public ArraySegment<byte>? Get";
- code += MakeCamel(field.name, true);
+ code += Name(field);
code += "Bytes() { return ";
code += "__p.__vector_as_arraysegment(";
code += NumToString(field.value.offset);
@@ -852,7 +971,7 @@
code += " public ";
code += GenTypeBasic(field.value.type.VectorType());
code += "[] Get";
- code += MakeCamel(field.name, true);
+ code += Name(field);
code += "Array() { ";
if (IsEnum(field.value.type.VectorType())) {
// Since __vector_as_array does not work for enum types,
@@ -881,9 +1000,9 @@
}
// generate object accessors if is nested_flatbuffer
if (field.nested_flatbuffer) {
- auto nested_type_name = WrapInNameSpace(*field.nested_flatbuffer);
+ auto nested_type_name = NamespacedName(*field.nested_flatbuffer);
auto nested_method_name =
- MakeCamel(field.name, true) + "As" + field.nested_flatbuffer->name;
+ Name(field) + "As" + field.nested_flatbuffer->name;
auto get_nested_method_name = nested_method_name;
get_nested_method_name = "Get" + nested_method_name;
conditional_cast = "(" + nested_type_name + "?)";
@@ -904,15 +1023,16 @@
is_series ? field.value.type.VectorType() : field.value.type;
// Boolean parameters have to be explicitly converted to byte
// representation.
- auto setter_parameter = underlying_type.base_type == BASE_TYPE_BOOL
- ? "(byte)(" + field.name + " ? 1 : 0)"
- : field.name;
- auto mutator_prefix = MakeCamel("mutate", true);
+ auto setter_parameter =
+ underlying_type.base_type == BASE_TYPE_BOOL
+ ? "(byte)(" + EscapeKeyword(field.name) + " ? 1 : 0)"
+ : EscapeKeyword(field.name);
+ auto mutator_prefix = "Mutate";
// A vector mutator also needs the index of the vector element it should
// mutate.
auto mutator_params = (is_series ? "(int j, " : "(") +
- GenTypeGet(underlying_type) + " " + field.name +
- ") { ";
+ GenTypeGet(underlying_type) + " " +
+ EscapeKeyword(field.name) + ") { ";
auto setter_index =
is_series
? "__p." +
@@ -926,7 +1046,7 @@
if (IsScalar(underlying_type.base_type) && !IsUnion(field.value.type)) {
code += " public ";
code += struct_def.fixed ? "void " : "bool ";
- code += mutator_prefix + MakeCamel(field.name, true);
+ code += mutator_prefix + Name(field);
code += mutator_params;
if (struct_def.fixed) {
code += GenSetter(underlying_type) + "(" + setter_index + ", ";
@@ -942,9 +1062,10 @@
}
if (parser_.opts.java_primitive_has_method &&
IsScalar(field.value.type.base_type) && !struct_def.fixed) {
- auto vt_offset_constant = " public static final int VT_" +
- MakeScreamingCamel(field.name) + " = " +
- NumToString(field.value.offset) + ";";
+ auto vt_offset_constant =
+ " public static final int VT_" +
+ ConvertCase(field.name, Case::kScreamingSnake) + " = " +
+ NumToString(field.value.offset) + ";";
code += vt_offset_constant;
code += "\n";
@@ -1002,13 +1123,13 @@
field.value.type.struct_def->defined_namespace,
GenTypeName_ObjectAPI(field.value.type.struct_def->name, opts));
code += " ";
- code += field.name;
+ code += EscapeKeyword(field.name);
code += " = null";
} else {
code += GenTypeBasic(field.value.type);
if (field.IsScalarOptional()) { code += "?"; }
code += " ";
- code += field.name;
+ code += EscapeKeyword(field.name);
if (!IsScalar(field.value.type.base_type)) code += "Offset";
code += " = ";
@@ -1028,13 +1149,13 @@
size == SizeOf(field.value.type.base_type))) {
code += " " + struct_def.name + ".";
code += "Add";
- code += MakeCamel(field.name) + "(builder, ";
+ code += Name(field) + "(builder, ";
if (IsStruct(field.value.type) &&
opts.generate_object_based_api) {
code += GenTypePointer(field.value.type) + ".Pack(builder, " +
- field.name + ")";
+ EscapeKeyword(field.name) + ")";
} else {
- code += field.name;
+ code += EscapeKeyword(field.name);
if (!IsScalar(field.value.type.base_type)) code += "Offset";
}
@@ -1062,17 +1183,17 @@
if (field.deprecated) continue;
if (field.key) key_field = &field;
code += " public static void Add";
- code += MakeCamel(field.name);
+ code += Name(field);
code += "(FlatBufferBuilder builder, ";
code += GenTypeBasic(field.value.type);
- auto argname = MakeCamel(field.name, false);
+ auto argname = ConvertCase(field.name, Case::kLowerCamel);
if (!IsScalar(field.value.type.base_type)) argname += "Offset";
if (field.IsScalarOptional()) { code += "?"; }
- code += " " + argname + ") { builder.Add";
+ code += " " + EscapeKeyword(argname) + ") { builder.Add";
code += GenMethod(field.value.type) + "(";
code += NumToString(it - struct_def.fields.vec.begin()) + ", ";
- code += SourceCastBasic(field.value.type);
- code += argname;
+ code += SourceCastBasic(field.value.type, field.IsScalarOptional());
+ code += EscapeKeyword(argname);
if (!IsScalar(field.value.type.base_type) &&
field.value.type.base_type != BASE_TYPE_UNION) {
code += ".Value";
@@ -1093,7 +1214,7 @@
field_has_create_set.insert(&field);
code += " public static VectorOffset ";
code += "Create";
- code += MakeCamel(field.name);
+ code += Name(field);
code += "Vector(FlatBufferBuilder builder, ";
code += GenTypeBasic(vector_type) + "[] data) ";
code += "{ builder.StartVector(";
@@ -1105,7 +1226,11 @@
code += "Add";
code += GenMethod(vector_type);
code += "(";
- code += SourceCastBasic(vector_type);
+ // At the moment there is no support of the type Vector with
+ // optional enum, e.g. if we have enum type SomeEnum there is no way
+ // to define `SomeEmum?[] enums` in FlatBuffer schema, so isOptional
+ // = false
+ code += SourceCastBasic(vector_type, false);
code += "data[i]";
if (vector_type.base_type == BASE_TYPE_STRUCT ||
IsString(vector_type))
@@ -1115,7 +1240,7 @@
code += " public static VectorOffset ";
code += "Create";
- code += MakeCamel(field.name);
+ code += Name(field);
code += "VectorBlock(FlatBufferBuilder builder, ";
code += GenTypeBasic(vector_type) + "[] data) ";
code += "{ builder.StartVector(";
@@ -1127,7 +1252,7 @@
// Generate a method to start a vector, data to be added manually
// after.
code += " public static void Start";
- code += MakeCamel(field.name);
+ code += Name(field);
code += "Vector(FlatBufferBuilder builder, int numElems) ";
code += "{ builder.StartVector(";
code += NumToString(elem_size);
@@ -1142,7 +1267,7 @@
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
- if (!field.deprecated && field.required) {
+ if (!field.deprecated && field.IsRequired()) {
code += " builder.Required(o, ";
code += NumToString(field.value.offset);
code += "); // " + field.name + "\n";
@@ -1215,7 +1340,7 @@
GenPackUnPack_ObjectAPI(struct_def, code_ptr, opts, struct_has_create,
field_has_create_set);
}
- code += "};\n\n";
+ code += "}\n\n";
if (opts.generate_object_based_api) {
GenStruct_ObjectAPI(struct_def, code_ptr, opts);
@@ -1305,19 +1430,27 @@
code += " }\n\n";
// As<T>
code += " public T As<T>() where T : class { return this.Value as T; }\n";
- // As
+ // As, From
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
auto &ev = **it;
if (ev.union_type.base_type == BASE_TYPE_NONE) continue;
auto type_name = GenTypeGet_ObjectAPI(ev.union_type, opts);
- if (ev.union_type.base_type == BASE_TYPE_STRUCT &&
- ev.union_type.struct_def->attributes.Lookup("private")) {
- code += " internal ";
- } else {
- code += " public ";
- }
- code += type_name + " As" + ev.name + "() { return this.As<" + type_name +
- ">(); }\n";
+ std::string accessibility =
+ (ev.union_type.base_type == BASE_TYPE_STRUCT &&
+ ev.union_type.struct_def->attributes.Lookup("private"))
+ ? "internal"
+ : "public";
+ // As
+ code += " " + accessibility + " " + type_name + " As" + ev.name +
+ "() { return this.As<" + type_name + ">(); }\n";
+ // From
+ auto lower_ev_name = ev.name;
+ std::transform(lower_ev_name.begin(), lower_ev_name.end(),
+ lower_ev_name.begin(), CharToLower);
+ code += " " + accessibility + " static " + union_name + " From" +
+ ev.name + "(" + type_name + " _" + lower_ev_name +
+ ") { return new " + union_name + "{ Type = " + Name(enum_def) +
+ "." + Name(ev) + ", Value = _" + lower_ev_name + " }; }\n";
}
code += "\n";
// Pack()
@@ -1329,7 +1462,7 @@
if (ev.union_type.base_type == BASE_TYPE_NONE) {
code += " default: return 0;\n";
} else {
- code += " case " + enum_def.name + "." + ev.name + ": return ";
+ code += " case " + Name(enum_def) + "." + Name(ev) + ": return ";
if (IsString(ev.union_type)) {
code += "builder.CreateString(_o.As" + ev.name + "()).Value;\n";
} else {
@@ -1414,7 +1547,7 @@
code += " default: break;\n";
} else {
auto type_name = GenTypeGet_ObjectAPI(ev.union_type, opts);
- code += " case " + enum_def.name + "." + ev.name +
+ code += " case " + Name(enum_def) + "." + Name(ev) +
": _o.Value = serializer.Deserialize<" + type_name +
">(reader); break;\n";
}
@@ -1450,7 +1583,7 @@
} else {
code += indent + varialbe_name + " = new ";
}
- code += WrapInNameSpace(enum_def) + "Union();\n";
+ code += NamespacedName(enum_def) + "Union();\n";
code += indent + varialbe_name + ".Type = this." + camel_name + "Type" +
type_suffix + ";\n";
code +=
@@ -1461,7 +1594,7 @@
if (ev.union_type.base_type == BASE_TYPE_NONE) {
code += indent + " default: break;\n";
} else {
- code += indent + " case " + WrapInNameSpace(enum_def) + "." + ev.name +
+ code += indent + " case " + NamespacedName(enum_def) + "." + ev.name +
":\n";
code += indent + " " + varialbe_name + ".Value = this." + camel_name;
if (IsString(ev.union_type)) {
@@ -1499,7 +1632,7 @@
it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
if (field.deprecated) continue;
- auto camel_name = MakeCamel(field.name);
+ auto camel_name = Name(field);
auto start = " _o." + camel_name + " = ";
switch (field.value.type.base_type) {
case BASE_TYPE_STRUCT: {
@@ -1573,7 +1706,7 @@
it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
if (field.deprecated) continue;
- auto camel_name = MakeCamel(field.name);
+ auto camel_name = Name(field);
// pre
switch (field.value.type.base_type) {
case BASE_TYPE_STRUCT: {
@@ -1627,12 +1760,12 @@
break;
case BASE_TYPE_UTYPE:
property_name = camel_name.substr(0, camel_name.size() - 4);
- array_type = WrapInNameSpace(*field.value.type.enum_def);
+ array_type = NamespacedName(*field.value.type.enum_def);
to_array = "_o." + property_name + "[_j].Type";
break;
case BASE_TYPE_UNION:
array_type = "int";
- to_array = WrapInNameSpace(*field.value.type.enum_def) +
+ to_array = NamespacedName(*field.value.type.enum_def) +
"Union.Pack(builder, _o." + property_name + "[_j])";
break;
default: gen_for_loop = false; break;
@@ -1687,7 +1820,7 @@
}
case BASE_TYPE_UNION: {
code += " var _" + field.name + "_type = _o." + camel_name +
- " == null ? " + WrapInNameSpace(*field.value.type.enum_def) +
+ " == null ? " + NamespacedName(*field.value.type.enum_def) +
".NONE : " + "_o." + camel_name + ".Type;\n";
code +=
" var _" + field.name + " = _o." + camel_name +
@@ -1706,7 +1839,7 @@
it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
if (field.deprecated) continue;
- auto camel_name = MakeCamel(field.name);
+ auto camel_name = Name(field);
switch (field.value.type.base_type) {
case BASE_TYPE_STRUCT: {
if (struct_def.fixed) {
@@ -1760,7 +1893,7 @@
it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
if (field.deprecated) continue;
- auto camel_name = MakeCamel(field.name);
+ auto camel_name = Name(field);
switch (field.value.type.base_type) {
case BASE_TYPE_STRUCT: {
if (field.value.type.struct_def->fixed) {
@@ -1856,7 +1989,7 @@
}
code += "] = _o";
for (size_t i = 0, j = 0; i < array_lengths.size(); ++i) {
- code += "." + MakeCamel(array_lengths[i].name);
+ code += "." + ConvertCase(array_lengths[i].name, Case::kUpperCamel);
if (array_lengths[i].length <= 0) continue;
code += "[idx" + NumToString(j++) + "]";
}
@@ -1867,7 +2000,7 @@
} else {
code += "_o";
for (size_t i = 0; i < array_lengths.size(); ++i) {
- code += "." + MakeCamel(array_lengths[i].name);
+ code += "." + ConvertCase(array_lengths[i].name, Case::kUpperCamel);
}
code += ";";
}
@@ -1910,13 +2043,13 @@
type_name.replace(type_name.length() - type_name_length,
type_name_length, new_type_name);
} else if (type.element == BASE_TYPE_UNION) {
- type_name = WrapInNameSpace(*type.enum_def) + "Union";
+ type_name = NamespacedName(*type.enum_def) + "Union";
}
break;
}
case BASE_TYPE_UNION: {
- type_name = WrapInNameSpace(*type.enum_def) + "Union";
+ type_name = NamespacedName(*type.enum_def) + "Union";
break;
}
default: break;
@@ -1959,10 +2092,11 @@
if (field.value.type.base_type == BASE_TYPE_UTYPE) continue;
if (field.value.type.element == BASE_TYPE_UTYPE) continue;
auto type_name = GenTypeGet_ObjectAPI(field.value.type, opts);
- auto camel_name = MakeCamel(field.name, true);
+ if (field.IsScalarOptional()) type_name += "?";
+ auto camel_name = Name(field);
if (opts.cs_gen_json_serializer) {
if (IsUnion(field.value.type)) {
- auto utype_name = WrapInNameSpace(*field.value.type.enum_def);
+ auto utype_name = NamespacedName(*field.value.type.enum_def);
code +=
" [Newtonsoft.Json.JsonProperty(\"" + field.name + "_type\")]\n";
if (IsVector(field.value.type)) {
@@ -2025,7 +2159,7 @@
if (field.deprecated) continue;
if (field.value.type.base_type == BASE_TYPE_UTYPE) continue;
if (field.value.type.element == BASE_TYPE_UTYPE) continue;
- code += " this." + MakeCamel(field.name) + " = ";
+ code += " this." + Name(field) + " = ";
auto type_name = GenTypeGet_ObjectAPI(field.value.type, opts);
if (IsScalar(field.value.type.base_type)) {
code += GenDefaultValue(field) + ";\n";
diff --git a/src/idl_gen_dart.cpp b/src/idl_gen_dart.cpp
index eec05a7..ff2c1a5 100644
--- a/src/idl_gen_dart.cpp
+++ b/src/idl_gen_dart.cpp
@@ -63,7 +63,7 @@
code.clear();
code = code + "// " + FlatBuffersGeneratedWarning() + "\n";
code = code +
- "// ignore_for_file: unused_import, unused_field, "
+ "// ignore_for_file: unused_import, unused_field, unused_element, "
"unused_local_variable\n\n";
if (!kv->first.empty()) { code += "library " + kv->first + ";\n\n"; }
@@ -154,10 +154,12 @@
static std::string EscapeKeyword(const std::string &name) {
for (size_t i = 0; i < sizeof(keywords) / sizeof(keywords[0]); i++) {
- if (name == keywords[i]) { return MakeCamel(name + "_", false); }
+ if (name == keywords[i]) {
+ return ConvertCase(name + "_", Case::kLowerCamel);
+ }
}
- return MakeCamel(name, false);
+ return ConvertCase(name, Case::kLowerCamel);
}
void GenerateEnums(namespace_code_map *namespace_code) {
@@ -225,23 +227,34 @@
GenDocComment(enum_def.doc_comment, &code, "");
auto name = enum_def.is_union ? enum_def.name + "TypeId" : enum_def.name;
- auto is_bit_flags = enum_def.attributes.Lookup("bit_flags");
+ const bool is_bit_flags =
+ enum_def.attributes.Lookup("bit_flags") != nullptr;
+ // The flatbuffer schema language allows bit flag enums to potentially have
+ // a default value of zero, even if it's not a valid enum value...
+ const bool permit_zero = is_bit_flags;
code += "class " + name + " {\n";
code += " final int value;\n";
code += " const " + name + "._(this.value);\n\n";
code += " factory " + name + ".fromValue(int value) {\n";
- code += " if (value == null) value = 0;\n";
-
- code += " if (!values.containsKey(value)) {\n";
- code +=
- " throw new StateError('Invalid value $value for bit flag enum ";
+ code += " final result = values[value];\n";
+ code += " if (result == null) {\n";
+ if (permit_zero) {
+ code += " if (value == 0) {\n";
+ code += " return " + name + "._(0);\n";
+ code += " } else {\n";
+ }
+ code += " throw StateError('Invalid value $value for bit flag enum ";
code += name + "');\n";
+ if (permit_zero) { code += " }\n"; }
code += " }\n";
- code += " return values[value];\n";
+ code += " return result;\n";
code += " }\n\n";
+ code += " static " + name + "? _createOrNull(int? value) => \n";
+ code += " value == null ? null : " + name + ".fromValue(value);\n\n";
+
// this is meaningless for bit_flags
// however, note that unlike "regular" dart enums this enum can still have
// holes.
@@ -263,19 +276,20 @@
if (it != enum_def.Vals().begin()) { code += '\n'; }
GenDocComment(ev.doc_comment, &code, "", " ");
}
- code += " static const " + name + " " + ev.name + " = ";
- code += "const " + name + "._(" + enum_def.ToString(ev) + ");\n";
+ code += " static const " + name + " " + ev.name + " = " + name + "._(" +
+ enum_def.ToString(ev) + ");\n";
}
- code += " static const values = {";
+ code += " static const Map<int, " + name + "> values = {\n";
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
auto &ev = **it;
- code += enum_def.ToString(ev) + ": " + ev.name + ",";
+ if (it != enum_def.Vals().begin()) code += ",\n";
+ code += " " + enum_def.ToString(ev) + ": " + ev.name;
}
code += "};\n\n";
- code += " static const " + _kFb + ".Reader<" + name +
- "> reader = const _" + name + "Reader();\n\n";
+ code += " static const " + _kFb + ".Reader<" + name + "> reader = _" +
+ name + "Reader();\n\n";
code += " @override\n";
code += " String toString() {\n";
code += " return '" + name + "{value: $value}';\n";
@@ -298,7 +312,7 @@
code += " @override\n";
code +=
" " + name + " read(" + _kFb + ".BufferContext bc, int offset) =>\n";
- code += " new " + name + ".fromValue(const " + _kFb + "." +
+ code += " " + name + ".fromValue(const " + _kFb + "." +
GenType(enum_def.underlying_type) + "Reader().read(bc, offset));\n";
code += "}\n\n";
}
@@ -327,30 +341,41 @@
std::string GenReaderTypeName(const Type &type, Namespace *current_namespace,
const FieldDef &def,
- bool parent_is_vector = false) {
+ bool parent_is_vector = false, bool lazy = true,
+ bool constConstruct = true) {
+ std::string prefix = (constConstruct ? "const " : "") + _kFb;
if (type.base_type == BASE_TYPE_BOOL) {
- return "const " + _kFb + ".BoolReader()";
+ return prefix + ".BoolReader()";
} else if (IsVector(type)) {
- return "const " + _kFb + ".ListReader<" +
+ if (!type.VectorType().enum_def) {
+ if (type.VectorType().base_type == BASE_TYPE_CHAR) {
+ return prefix + ".Int8ListReader(" + (lazy ? ")" : "lazy: false)");
+ }
+ if (type.VectorType().base_type == BASE_TYPE_UCHAR) {
+ return prefix + ".Uint8ListReader(" + (lazy ? ")" : "lazy: false)");
+ }
+ }
+ return prefix + ".ListReader<" +
GenDartTypeName(type.VectorType(), current_namespace, def) + ">(" +
- GenReaderTypeName(type.VectorType(), current_namespace, def,
- true) +
- ")";
+ GenReaderTypeName(type.VectorType(), current_namespace, def, true,
+ true, false) +
+ (lazy ? ")" : ", lazy: false)");
} else if (IsString(type)) {
- return "const " + _kFb + ".StringReader()";
+ return prefix + ".StringReader()";
}
if (IsScalar(type.base_type)) {
if (type.enum_def && parent_is_vector) {
return GenDartTypeName(type, current_namespace, def) + ".reader";
}
- return "const " + _kFb + "." + GenType(type) + "Reader()";
+ return prefix + "." + GenType(type) + "Reader()";
} else {
return GenDartTypeName(type, current_namespace, def) + ".reader";
}
}
std::string GenDartTypeName(const Type &type, Namespace *current_namespace,
- const FieldDef &def, bool addBuilder = false) {
+ const FieldDef &def,
+ std::string struct_type_suffix = "") {
if (type.enum_def) {
if (type.enum_def->is_union && type.base_type != BASE_TYPE_UNION) {
return type.enum_def->name + "TypeId";
@@ -375,18 +400,26 @@
case BASE_TYPE_DOUBLE: return "double";
case BASE_TYPE_STRING: return "String";
case BASE_TYPE_STRUCT:
- return MaybeWrapNamespace(
- type.struct_def->name + (addBuilder ? "ObjectBuilder" : ""),
- current_namespace, def);
+ return MaybeWrapNamespace(type.struct_def->name + struct_type_suffix,
+ current_namespace, def);
case BASE_TYPE_VECTOR:
return "List<" +
GenDartTypeName(type.VectorType(), current_namespace, def,
- addBuilder) +
+ struct_type_suffix) +
">";
default: assert(0); return "dynamic";
}
}
+ std::string GenDartTypeName(const Type &type, Namespace *current_namespace,
+ const FieldDef &def, bool nullable,
+ std::string struct_type_suffix) {
+ std::string typeName =
+ GenDartTypeName(type, current_namespace, def, struct_type_suffix);
+ if (nullable && typeName != "dynamic") typeName += "?";
+ return typeName;
+ }
+
static const std::string MaybeWrapNamespace(const std::string &type_name,
Namespace *current_ns,
const FieldDef &field) {
@@ -432,15 +465,15 @@
code += " " + object_name + "._(this._bc, this._bcOffset);\n";
if (!struct_def.fixed) {
code += " factory " + object_name + "(List<int> bytes) {\n";
- code += " " + _kFb + ".BufferContext rootRef = new " + _kFb +
- ".BufferContext.fromBytes(bytes);\n";
+ code +=
+ " final rootRef = " + _kFb + ".BufferContext.fromBytes(bytes);\n";
code += " return reader.read(rootRef, 0);\n";
code += " }\n";
}
code += "\n";
code += " static const " + _kFb + ".Reader<" + object_name +
- "> reader = const " + reader_name + "();\n\n";
+ "> reader = " + reader_name + "();\n\n";
code += " final " + _kFb + ".BufferContext _bc;\n";
code += " final int _bcOffset;\n\n";
@@ -456,8 +489,23 @@
GenImplementationGetters(struct_def, non_deprecated_fields, &code);
+ if (parser_.opts.generate_object_based_api) {
+ code +=
+ "\n" + GenStructObjectAPIUnpack(struct_def, non_deprecated_fields);
+
+ code += "\n static int pack(fb.Builder fbBuilder, " + struct_def.name +
+ "T? object) {\n";
+ code += " if (object == null) return 0;\n";
+ code += " return object.pack(fbBuilder);\n";
+ code += " }\n";
+ }
+
code += "}\n\n";
+ if (parser_.opts.generate_object_based_api) {
+ code += GenStructObjectAPI(struct_def, non_deprecated_fields);
+ }
+
GenReader(struct_def, &reader_name, &reader_code);
GenBuilder(struct_def, non_deprecated_fields, &builder_name, &builder_code);
GenObjectBuilder(struct_def, non_deprecated_fields, &object_builder_name,
@@ -469,6 +517,122 @@
(*namespace_code)[object_namespace] += code;
}
+ // Generate an accessor struct with constructor for a flatbuffers struct.
+ std::string GenStructObjectAPI(
+ const StructDef &struct_def,
+ const std::vector<std::pair<int, FieldDef *>> &non_deprecated_fields) {
+ std::string code;
+ GenDocComment(struct_def.doc_comment, &code, "");
+
+ std::string class_name = struct_def.name + "T";
+ code += "class " + class_name + " implements " + _kFb + ".Packable {\n";
+
+ std::string constructor_args;
+ for (auto it = non_deprecated_fields.begin();
+ it != non_deprecated_fields.end(); ++it) {
+ const FieldDef &field = *it->second;
+
+ std::string field_name = ConvertCase(field.name, Case::kLowerCamel);
+ std::string defaultValue = getDefaultValue(field.value);
+ std::string type_name =
+ GenDartTypeName(field.value.type, struct_def.defined_namespace, field,
+ defaultValue.empty() && !struct_def.fixed, "T");
+
+ GenDocComment(field.doc_comment, &code, "", " ");
+ code += " " + type_name + " " + field_name + ";\n";
+
+ if (!constructor_args.empty()) constructor_args += ",\n";
+ constructor_args += " ";
+ constructor_args += (struct_def.fixed ? "required " : "");
+ constructor_args += "this." + field_name;
+ if (!struct_def.fixed && !defaultValue.empty()) {
+ if (IsEnum(field.value.type)) {
+ auto &enum_def = *field.value.type.enum_def;
+ if (auto val = enum_def.FindByValue(defaultValue)) {
+ constructor_args += " = " + enum_def.name + "." + val->name;
+ } else {
+ constructor_args +=
+ " = const " + enum_def.name + "._(" + defaultValue + ")";
+ }
+ } else {
+ constructor_args += " = " + defaultValue;
+ }
+ }
+ }
+
+ if (!constructor_args.empty()) {
+ code += "\n " + class_name + "({\n" + constructor_args + "});\n\n";
+ }
+
+ code += GenStructObjectAPIPack(struct_def, non_deprecated_fields);
+ code += "\n";
+ code += GenToString(class_name, non_deprecated_fields);
+
+ code += "}\n\n";
+ return code;
+ }
+
+ // Generate function `StructNameT unpack()`
+ std::string GenStructObjectAPIUnpack(
+ const StructDef &struct_def,
+ const std::vector<std::pair<int, FieldDef *>> &non_deprecated_fields) {
+ std::string constructor_args;
+ for (auto it = non_deprecated_fields.begin();
+ it != non_deprecated_fields.end(); ++it) {
+ const FieldDef &field = *it->second;
+
+ std::string field_name = ConvertCase(field.name, Case::kLowerCamel);
+ if (!constructor_args.empty()) constructor_args += ",\n";
+ constructor_args += " " + field_name + ": ";
+
+ const Type &type = field.value.type;
+ std::string defaultValue = getDefaultValue(field.value);
+ bool isNullable = defaultValue.empty() && !struct_def.fixed;
+ std::string nullableValueAccessOperator = isNullable ? "?" : "";
+ if (type.base_type == BASE_TYPE_STRUCT) {
+ constructor_args +=
+ field_name + nullableValueAccessOperator + ".unpack()";
+ } else if (type.base_type == BASE_TYPE_VECTOR) {
+ if (type.VectorType().base_type == BASE_TYPE_STRUCT) {
+ constructor_args += field_name + nullableValueAccessOperator +
+ ".map((e) => e.unpack()).toList()";
+ } else {
+ constructor_args +=
+ GenReaderTypeName(field.value.type, struct_def.defined_namespace,
+ field, false, false);
+ constructor_args += ".vTableGet";
+ std::string offset = NumToString(field.value.offset);
+ constructor_args +=
+ isNullable
+ ? "Nullable(_bc, _bcOffset, " + offset + ")"
+ : "(_bc, _bcOffset, " + offset + ", " + defaultValue + ")";
+ }
+ } else {
+ constructor_args += field_name;
+ }
+ }
+
+ std::string class_name = struct_def.name + "T";
+ std::string code = " " + class_name + " unpack() => " + class_name + "(";
+ if (!constructor_args.empty()) code += "\n" + constructor_args;
+ code += ");\n";
+ return code;
+ }
+
+ // Generate function `StructNameT pack()`
+ std::string GenStructObjectAPIPack(
+ const StructDef &struct_def,
+ const std::vector<std::pair<int, FieldDef *>> &non_deprecated_fields) {
+ std::string code;
+
+ code += " @override\n";
+ code += " int pack(fb.Builder fbBuilder) {\n";
+ code += GenObjectBuilderImplementation(struct_def, non_deprecated_fields,
+ false, true);
+ code += " }\n";
+ return code;
+ }
+
std::string NamespaceAliasFromUnionType(Namespace *root_namespace,
const Type &type) {
const std::vector<std::string> qualified_name_parts =
@@ -510,9 +674,12 @@
auto pair = *it;
auto &field = *pair.second;
- std::string field_name = MakeCamel(field.name, false);
- std::string type_name = GenDartTypeName(
- field.value.type, struct_def.defined_namespace, field, false);
+ std::string field_name = ConvertCase(field.name, Case::kLowerCamel);
+ std::string defaultValue = getDefaultValue(field.value);
+ bool isNullable = defaultValue.empty() && !struct_def.fixed;
+ std::string type_name =
+ GenDartTypeName(field.value.type, struct_def.defined_namespace, field,
+ isNullable, "");
GenDocComment(field.doc_comment, &code, "", " ");
@@ -528,8 +695,8 @@
auto enum_name = NamespaceAliasFromUnionType(
enum_def.defined_namespace, ev.union_type);
code += " case " + enum_def.ToString(ev) + ": return " +
- enum_name + ".reader.vTableGet(_bc, _bcOffset, " +
- NumToString(field.value.offset) + ", null);\n";
+ enum_name + ".reader.vTableGetNullable(_bc, _bcOffset, " +
+ NumToString(field.value.offset) + ");\n";
}
code += " default: return null;\n";
code += " }\n";
@@ -538,10 +705,9 @@
code += " => ";
if (field.value.type.enum_def &&
field.value.type.base_type != BASE_TYPE_VECTOR) {
- code += "new " +
- GenDartTypeName(field.value.type,
+ code += GenDartTypeName(field.value.type,
struct_def.defined_namespace, field) +
- ".fromValue(";
+ (isNullable ? "._createOrNull(" : ".fromValue(");
}
code += GenReaderTypeName(field.value.type,
@@ -550,33 +716,13 @@
code +=
".read(_bc, _bcOffset + " + NumToString(field.value.offset) + ")";
} else {
- code += ".vTableGet(_bc, _bcOffset, " +
- NumToString(field.value.offset) + ", ";
- if (!field.value.constant.empty() && field.value.constant != "0") {
- if (IsBool(field.value.type.base_type)) {
- code += "true";
- } else if (field.value.constant == "nan" ||
- field.value.constant == "+nan" ||
- field.value.constant == "-nan") {
- code += "double.nan";
- } else if (field.value.constant == "inf" ||
- field.value.constant == "+inf") {
- code += "double.infinity";
- } else if (field.value.constant == "-inf") {
- code += "double.negativeInfinity";
- } else {
- code += field.value.constant;
- }
+ code += ".vTableGet";
+ std::string offset = NumToString(field.value.offset);
+ if (isNullable) {
+ code += "Nullable(_bc, _bcOffset, " + offset + ")";
} else {
- if (IsBool(field.value.type.base_type)) {
- code += "false";
- } else if (IsScalar(field.value.type.base_type)) {
- code += "0";
- } else {
- code += "null";
- }
+ code += "(_bc, _bcOffset, " + offset + ", " + defaultValue + ")";
}
- code += ")";
}
if (field.value.type.enum_def &&
field.value.type.base_type != BASE_TYPE_VECTOR) {
@@ -587,20 +733,50 @@
}
code += "\n";
+ code += GenToString(struct_def.name, non_deprecated_fields);
+ }
+ std::string GenToString(
+ const std::string &object_name,
+ const std::vector<std::pair<int, FieldDef *>> &non_deprecated_fields) {
+ std::string code;
code += " @override\n";
code += " String toString() {\n";
- code += " return '" + struct_def.name + "{";
+ code += " return '" + object_name + "{";
for (auto it = non_deprecated_fields.begin();
it != non_deprecated_fields.end(); ++it) {
auto pair = *it;
auto &field = *pair.second;
- code +=
- MakeCamel(field.name, false) + ": $" + MakeCamel(field.name, false);
+ code += ConvertCase(field.name, Case::kLowerCamel) + ": $" +
+ ConvertCase(field.name, Case::kLowerCamel);
if (it != non_deprecated_fields.end() - 1) { code += ", "; }
}
code += "}';\n";
code += " }\n";
+ return code;
+ }
+
+ std::string getDefaultValue(const Value &value) const {
+ if (!value.constant.empty() && value.constant != "0") {
+ if (IsBool(value.type.base_type)) {
+ return "true";
+ } else if (value.constant == "nan" || value.constant == "+nan" ||
+ value.constant == "-nan") {
+ return "double.nan";
+ } else if (value.constant == "inf" || value.constant == "+inf") {
+ return "double.infinity";
+ } else if (value.constant == "-inf") {
+ return "double.negativeInfinity";
+ } else {
+ return value.constant;
+ }
+ } else if (IsBool(value.type.base_type)) {
+ return "false";
+ } else if (IsScalar(value.type.base_type) && !IsUnion(value.type)) {
+ return "0";
+ } else {
+ return "";
+ }
}
void GenReader(const StructDef &struct_def, std::string *reader_name_ptr,
@@ -624,7 +800,7 @@
}
code += " @override\n";
code += " " + impl_name +
- " createObject(fb.BufferContext bc, int offset) => \n new " +
+ " createObject(fb.BufferContext bc, int offset) => \n " +
impl_name + "._(bc, offset);\n";
code += "}\n\n";
}
@@ -637,9 +813,7 @@
auto &builder_name = *builder_name_ptr;
code += "class " + builder_name + " {\n";
- code += " " + builder_name + "(this.fbBuilder) {\n";
- code += " assert(fbBuilder != null);\n";
- code += " }\n\n";
+ code += " " + builder_name + "(this.fbBuilder);\n\n";
code += " final " + _kFb + ".Builder fbBuilder;\n\n";
if (struct_def.fixed) {
@@ -688,7 +862,7 @@
} else {
code += " fbBuilder.put" + GenType(field.value.type) + "(";
code += field.name;
- if (field.value.type.enum_def) { code += "?.value"; }
+ if (field.value.type.enum_def) { code += ".value"; }
code += ");\n";
}
}
@@ -703,7 +877,8 @@
auto &code = *code_ptr;
code += " void begin() {\n";
- code += " fbBuilder.startTable();\n";
+ code += " fbBuilder.startTable(" +
+ NumToString(struct_def.fields.vec.size()) + ");\n";
code += " }\n\n";
for (auto it = non_deprecated_fields.begin();
@@ -713,21 +888,23 @@
auto offset = pair.first;
if (IsScalar(field.value.type.base_type)) {
- code += " int add" + MakeCamel(field.name) + "(";
+ code += " int add" + ConvertCase(field.name, Case::kUpperCamel) + "(";
code += GenDartTypeName(field.value.type, struct_def.defined_namespace,
field);
- code += " " + MakeCamel(field.name, false) + ") {\n";
+ code += "? " + ConvertCase(field.name, Case::kLowerCamel) + ") {\n";
code += " fbBuilder.add" + GenType(field.value.type) + "(" +
NumToString(offset) + ", ";
- code += MakeCamel(field.name, false);
+ code += ConvertCase(field.name, Case::kLowerCamel);
if (field.value.type.enum_def) { code += "?.value"; }
code += ");\n";
} else if (IsStruct(field.value.type)) {
- code += " int add" + MakeCamel(field.name) + "(int offset) {\n";
+ code += " int add" + ConvertCase(field.name, Case::kUpperCamel) +
+ "(int offset) {\n";
code +=
" fbBuilder.addStruct(" + NumToString(offset) + ", offset);\n";
} else {
- code += " int add" + MakeCamel(field.name) + "Offset(int offset) {\n";
+ code += " int add" + ConvertCase(field.name, Case::kUpperCamel) +
+ "Offset(int? offset) {\n";
code +=
" fbBuilder.addOffset(" + NumToString(offset) + ", offset);\n";
}
@@ -756,8 +933,8 @@
code += " final " +
GenDartTypeName(field.value.type, struct_def.defined_namespace,
- field, true) +
- " _" + MakeCamel(field.name, false) + ";\n";
+ field, !struct_def.fixed, "ObjectBuilder") +
+ " _" + ConvertCase(field.name, Case::kLowerCamel) + ";\n";
}
code += "\n";
code += " " + builder_name + "(";
@@ -769,10 +946,11 @@
auto pair = *it;
auto &field = *pair.second;
- code += " " +
+ code += " ";
+ code += (struct_def.fixed ? "required " : "") +
GenDartTypeName(field.value.type, struct_def.defined_namespace,
- field, true) +
- " " + MakeCamel(field.name, false) + ",\n";
+ field, !struct_def.fixed, "ObjectBuilder") +
+ " " + ConvertCase(field.name, Case::kLowerCamel) + ",\n";
}
code += " })\n";
code += " : ";
@@ -781,8 +959,8 @@
auto pair = *it;
auto &field = *pair.second;
- code += "_" + MakeCamel(field.name, false) + " = " +
- MakeCamel(field.name, false);
+ code += "_" + ConvertCase(field.name, Case::kLowerCamel) + " = " +
+ ConvertCase(field.name, Case::kLowerCamel);
if (it == non_deprecated_fields.end() - 1) {
code += ";\n\n";
} else {
@@ -795,75 +973,102 @@
code += " /// Finish building, and store into the [fbBuilder].\n";
code += " @override\n";
- code += " int finish(\n";
- code += " " + _kFb + ".Builder fbBuilder) {\n";
- code += " assert(fbBuilder != null);\n";
-
- for (auto it = non_deprecated_fields.begin();
- it != non_deprecated_fields.end(); ++it) {
- auto pair = *it;
- auto &field = *pair.second;
-
- if (IsScalar(field.value.type.base_type) || IsStruct(field.value.type))
- continue;
-
- code += " final int " + MakeCamel(field.name, false) + "Offset";
- if (IsVector(field.value.type)) {
- code +=
- " = _" + MakeCamel(field.name, false) + "?.isNotEmpty == true\n";
- code += " ? fbBuilder.writeList";
- switch (field.value.type.VectorType().base_type) {
- case BASE_TYPE_STRING:
- code += "(_" + MakeCamel(field.name, false) +
- ".map((b) => fbBuilder.writeString(b)).toList())";
- break;
- case BASE_TYPE_STRUCT:
- if (field.value.type.struct_def->fixed) {
- code += "OfStructs(_" + MakeCamel(field.name, false) + ")";
- } else {
- code += "(_" + MakeCamel(field.name, false) +
- ".map((b) => b.getOrCreateOffset(fbBuilder)).toList())";
- }
- break;
- default:
- code += GenType(field.value.type.VectorType()) + "(_" +
- MakeCamel(field.name, false);
- if (field.value.type.enum_def) { code += ".map((f) => f.value)"; }
- code += ")";
- }
- code += "\n : null;\n";
- } else if (IsString(field.value.type)) {
- code += " = fbBuilder.writeString(_" + MakeCamel(field.name, false) +
- ");\n";
- } else {
- code += " = _" + MakeCamel(field.name, false) +
- "?.getOrCreateOffset(fbBuilder);\n";
- }
- }
-
- code += "\n";
- if (struct_def.fixed) {
- StructObjectBuilderBody(non_deprecated_fields, code_ptr);
- } else {
- TableObjectBuilderBody(non_deprecated_fields, code_ptr);
- }
+ code += " int finish(" + _kFb + ".Builder fbBuilder) {\n";
+ code += GenObjectBuilderImplementation(struct_def, non_deprecated_fields);
code += " }\n\n";
code += " /// Convenience method to serialize to byte list.\n";
code += " @override\n";
- code += " Uint8List toBytes([String fileIdentifier]) {\n";
- code += " " + _kFb + ".Builder fbBuilder = new ";
- code += _kFb + ".Builder();\n";
- code += " int offset = finish(fbBuilder);\n";
- code += " return fbBuilder.finish(offset, fileIdentifier);\n";
+ code += " Uint8List toBytes([String? fileIdentifier]) {\n";
+ code += " final fbBuilder = " + _kFb +
+ ".Builder(deduplicateTables: false);\n";
+ code += " fbBuilder.finish(finish(fbBuilder), fileIdentifier);\n";
+ code += " return fbBuilder.buffer;\n";
code += " }\n";
code += "}\n";
}
- void StructObjectBuilderBody(
- std::vector<std::pair<int, FieldDef *>> non_deprecated_fields,
- std::string *code_ptr, bool prependUnderscore = true) {
- auto &code = *code_ptr;
+ std::string GenObjectBuilderImplementation(
+ const StructDef &struct_def,
+ const std::vector<std::pair<int, FieldDef *>> &non_deprecated_fields,
+ bool prependUnderscore = true, bool pack = false) {
+ std::string code;
+ for (auto it = non_deprecated_fields.begin();
+ it != non_deprecated_fields.end(); ++it) {
+ const FieldDef &field = *it->second;
+
+ if (IsScalar(field.value.type.base_type) || IsStruct(field.value.type))
+ continue;
+
+ std::string offset_name =
+ ConvertCase(field.name, Case::kLowerCamel) + "Offset";
+ std::string field_name = (prependUnderscore ? "_" : "") +
+ ConvertCase(field.name, Case::kLowerCamel);
+
+ // custom handling for fixed-sized struct in pack()
+ if (pack && IsVector(field.value.type) &&
+ field.value.type.VectorType().base_type == BASE_TYPE_STRUCT &&
+ field.value.type.struct_def->fixed) {
+ code += " int? " + offset_name + ";\n";
+ code += " if (" + field_name + " != null) {\n";
+ code +=
+ " for (var e in " + field_name + "!) { e.pack(fbBuilder); }\n";
+ code += " " + ConvertCase(field.name, Case::kLowerCamel) +
+ "Offset = fbBuilder.endStructVector(" + field_name +
+ "!.length);\n";
+ code += " }\n";
+ continue;
+ }
+
+ code += " final int? " + offset_name;
+ if (IsVector(field.value.type)) {
+ code += " = " + field_name + " == null ? null\n";
+ code += " : fbBuilder.writeList";
+ switch (field.value.type.VectorType().base_type) {
+ case BASE_TYPE_STRING:
+ code +=
+ "(" + field_name + "!.map(fbBuilder.writeString).toList());\n";
+ break;
+ case BASE_TYPE_STRUCT:
+ if (field.value.type.struct_def->fixed) {
+ code += "OfStructs(" + field_name + "!);\n";
+ } else {
+ code += "(" + field_name + "!.map((b) => b." +
+ (pack ? "pack" : "getOrCreateOffset") +
+ "(fbBuilder)).toList());\n";
+ }
+ break;
+ default:
+ code +=
+ GenType(field.value.type.VectorType()) + "(" + field_name + "!";
+ if (field.value.type.enum_def) {
+ code += ".map((f) => f.value).toList()";
+ }
+ code += ");\n";
+ }
+ } else if (IsString(field.value.type)) {
+ code += " = " + field_name + " == null ? null\n";
+ code += " : fbBuilder.writeString(" + field_name + "!);\n";
+ } else {
+ code += " = " + field_name + "?." +
+ (pack ? "pack" : "getOrCreateOffset") + "(fbBuilder);\n";
+ }
+ }
+
+ if (struct_def.fixed) {
+ code += StructObjectBuilderBody(non_deprecated_fields, prependUnderscore,
+ pack);
+ } else {
+ code += TableObjectBuilderBody(struct_def, non_deprecated_fields,
+ prependUnderscore, pack);
+ }
+ return code;
+ }
+
+ std::string StructObjectBuilderBody(
+ const std::vector<std::pair<int, FieldDef *>> &non_deprecated_fields,
+ bool prependUnderscore = true, bool pack = false) {
+ std::string code;
for (auto it = non_deprecated_fields.rbegin();
it != non_deprecated_fields.rend(); ++it) {
@@ -877,24 +1082,27 @@
if (IsStruct(field.value.type)) {
code += " ";
if (prependUnderscore) { code += "_"; }
- code += field.name + ".finish(fbBuilder);\n";
+ code += field.name + (pack ? ".pack" : ".finish") + "(fbBuilder);\n";
} else {
code += " fbBuilder.put" + GenType(field.value.type) + "(";
if (prependUnderscore) { code += "_"; }
code += field.name;
- if (field.value.type.enum_def) { code += "?.value"; }
+ if (field.value.type.enum_def) { code += ".value"; }
code += ");\n";
}
}
code += " return fbBuilder.offset;\n";
+ return code;
}
- void TableObjectBuilderBody(
- std::vector<std::pair<int, FieldDef *>> non_deprecated_fields,
- std::string *code_ptr, bool prependUnderscore = true) {
- std::string &code = *code_ptr;
- code += " fbBuilder.startTable();\n";
+ std::string TableObjectBuilderBody(
+ const StructDef &struct_def,
+ const std::vector<std::pair<int, FieldDef *>> &non_deprecated_fields,
+ bool prependUnderscore = true, bool pack = false) {
+ std::string code;
+ code += " fbBuilder.startTable(" +
+ NumToString(struct_def.fields.vec.size()) + ");\n";
for (auto it = non_deprecated_fields.begin();
it != non_deprecated_fields.end(); ++it) {
@@ -902,29 +1110,29 @@
auto &field = *pair.second;
auto offset = pair.first;
+ std::string field_name = (prependUnderscore ? "_" : "") +
+ ConvertCase(field.name, Case::kLowerCamel);
+
if (IsScalar(field.value.type.base_type)) {
code += " fbBuilder.add" + GenType(field.value.type) + "(" +
- NumToString(offset) + ", ";
- if (prependUnderscore) { code += "_"; }
- code += MakeCamel(field.name, false);
- if (field.value.type.enum_def) { code += "?.value"; }
+ NumToString(offset) + ", " + field_name;
+ if (field.value.type.enum_def) {
+ bool isNullable = getDefaultValue(field.value).empty();
+ code += (isNullable || !pack) ? "?.value" : ".value";
+ }
code += ");\n";
} else if (IsStruct(field.value.type)) {
- code += " if (";
- if (prependUnderscore) { code += "_"; }
- code += MakeCamel(field.name, false) + " != null) {\n";
- code += " fbBuilder.addStruct(" + NumToString(offset) + ", ";
- code += "_" + MakeCamel(field.name, false) + ".finish(fbBuilder));\n";
+ code += " if (" + field_name + " != null) {\n";
+ code += " fbBuilder.addStruct(" + NumToString(offset) + ", " +
+ field_name + (pack ? "!.pack" : "!.finish") + "(fbBuilder));\n";
code += " }\n";
} else {
- code +=
- " if (" + MakeCamel(field.name, false) + "Offset != null) {\n";
- code += " fbBuilder.addOffset(" + NumToString(offset) + ", " +
- MakeCamel(field.name, false) + "Offset);\n";
- code += " }\n";
+ code += " fbBuilder.addOffset(" + NumToString(offset) + ", " +
+ ConvertCase(field.name, Case::kLowerCamel) + "Offset);\n";
}
}
code += " return fbBuilder.endTable();\n";
+ return code;
}
};
} // namespace dart
@@ -937,8 +1145,6 @@
std::string DartMakeRule(const Parser &parser, const std::string &path,
const std::string &file_name) {
- assert(parser.opts.lang <= IDLOptions::kMAX);
-
auto filebase =
flatbuffers::StripPath(flatbuffers::StripExtension(file_name));
dart::DartGenerator generator(parser, path, file_name);
diff --git a/src/idl_gen_fbs.cpp b/src/idl_gen_fbs.cpp
index e6c8a4a..35c1a7d 100644
--- a/src/idl_gen_fbs.cpp
+++ b/src/idl_gen_fbs.cpp
@@ -136,7 +136,7 @@
GenComment(field.doc_comment, &schema, nullptr, " ");
schema += " " + field.name + ":" + GenType(field.value.type);
if (field.value.constant != "0") schema += " = " + field.value.constant;
- if (field.required) schema += " (required)";
+ if (field.IsRequired()) schema += " (required)";
schema += ";\n";
}
}
diff --git a/src/idl_gen_go.cpp b/src/idl_gen_go.cpp
index 68cc01f..306a022 100644
--- a/src/idl_gen_go.cpp
+++ b/src/idl_gen_go.cpp
@@ -23,6 +23,7 @@
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
+#include "namer.h"
#ifdef _WIN32
# include <direct.h>
@@ -38,20 +39,39 @@
namespace go {
// see https://golang.org/ref/spec#Keywords
-static const char *const g_golang_keywords[] = {
- "break", "default", "func", "interface", "select", "case", "defer",
- "go", "map", "struct", "chan", "else", "goto", "package",
- "switch", "const", "fallthrough", "if", "range", "type", "continue",
- "for", "import", "return", "var",
-};
+std::set<std::string> GoKeywords() {
+ return {
+ "break", "default", "func", "interface", "select",
+ "case", "defer", "go", "map", "struct",
+ "chan", "else", "goto", "package", "switch",
+ "const", "fallthrough", "if", "range", "type",
+ "continue", "for", "import", "return", "var",
+ };
+}
-static std::string GoIdentity(const std::string &name) {
- for (size_t i = 0;
- i < sizeof(g_golang_keywords) / sizeof(g_golang_keywords[0]); i++) {
- if (name == g_golang_keywords[i]) { return MakeCamel(name + "_", false); }
- }
-
- return MakeCamel(name, false);
+Namer::Config GoDefaultConfig() {
+ // Note that the functions with user defined types in the name use
+ // upper camel case for all but the user defined type itself, which is keep
+ // cased. Despite being a function, we interpret it as a Type.
+ return { /*types=*/Case::kKeep,
+ /*constants=*/Case::kUnknown,
+ /*methods=*/Case::kUpperCamel,
+ /*functions=*/Case::kUpperCamel,
+ /*fields=*/Case::kUpperCamel,
+ /*variables=*/Case::kLowerCamel,
+ /*variants=*/Case::kKeep,
+ /*enum_variant_seperator=*/"", // I.e. Concatenate.
+ /*namespaces=*/Case::kKeep,
+ /*namespace_seperator=*/"__",
+ /*object_prefix=*/"",
+ /*object_suffix=*/"T",
+ /*keyword_prefix=*/"",
+ /*keyword_suffix=*/"_",
+ /*filenames=*/Case::kKeep,
+ /*directories=*/Case::kKeep,
+ /*output_path=*/"",
+ /*filename_suffix=*/"",
+ /*filename_extension=*/".go" };
}
class GoGenerator : public BaseGenerator {
@@ -60,7 +80,9 @@
const std::string &file_name, const std::string &go_namespace)
: BaseGenerator(parser, path, file_name, "" /* not used*/,
"" /* not used */, "go"),
- cur_name_space_(nullptr) {
+ cur_name_space_(nullptr),
+ namer_({ GoDefaultConfig().WithFlagOptions(parser.opts, path),
+ GoKeywords() }) {
std::istringstream iss(go_namespace);
std::string component;
while (std::getline(iss, component, '.')) {
@@ -118,6 +140,7 @@
private:
Namespace go_namespace_;
Namespace *cur_name_space_;
+ const Namer namer_;
struct NamespacePtrLess {
bool operator()(const Namespace *a, const Namespace *b) const {
@@ -137,7 +160,7 @@
void BeginClass(const StructDef &struct_def, std::string *code_ptr) {
std::string &code = *code_ptr;
- code += "type " + struct_def.name + " struct {\n\t";
+ code += "type " + namer_.Type(struct_def.name) + " struct {\n\t";
// _ is reserved in flatbuffers field names, so no chance of name conflict:
code += "_tab ";
@@ -148,7 +171,7 @@
// Construct the name of the type for this enum.
std::string GetEnumTypeName(const EnumDef &enum_def) {
return WrapInNameSpaceAndTrack(enum_def.defined_namespace,
- GoIdentity(enum_def.name));
+ namer_.Type(enum_def.name));
}
// Create a type for the enum values.
@@ -169,8 +192,7 @@
size_t max_name_length, std::string *code_ptr) {
std::string &code = *code_ptr;
code += "\t";
- code += enum_def.name;
- code += ev.name;
+ code += namer_.EnumVariant(enum_def.name, ev.name);
code += " ";
code += std::string(max_name_length - ev.name.length(), ' ');
code += GetEnumTypeName(enum_def);
@@ -197,8 +219,7 @@
size_t max_name_length, std::string *code_ptr) {
std::string &code = *code_ptr;
code += "\t";
- code += enum_def.name;
- code += ev.name;
+ code += namer_.EnumVariant(enum_def.name, ev.name);
code += ": ";
code += std::string(max_name_length - ev.name.length(), ' ');
code += "\"";
@@ -215,8 +236,9 @@
// Generate String() method on enum type.
void EnumStringer(const EnumDef &enum_def, std::string *code_ptr) {
std::string &code = *code_ptr;
- code += "func (v " + enum_def.name + ") String() string {\n";
- code += "\tif s, ok := EnumNames" + enum_def.name + "[v]; ok {\n";
+ const std::string enum_type = namer_.Type(enum_def.name);
+ code += "func (v " + enum_type + ") String() string {\n";
+ code += "\tif s, ok := EnumNames" + enum_type + "[v]; ok {\n";
code += "\t\treturn s\n";
code += "\t}\n";
code += "\treturn \"" + enum_def.name;
@@ -228,7 +250,7 @@
void BeginEnumValues(const EnumDef &enum_def, std::string *code_ptr) {
std::string &code = *code_ptr;
code += "var EnumValues";
- code += enum_def.name;
+ code += namer_.Type(enum_def.name);
code += " = map[string]" + GetEnumTypeName(enum_def) + "{\n";
}
@@ -240,8 +262,7 @@
code += ev.name;
code += "\": ";
code += std::string(max_name_length - ev.name.length(), ' ');
- code += enum_def.name;
- code += ev.name;
+ code += namer_.EnumVariant(enum_def.name, ev.name);
code += ",\n";
}
@@ -255,20 +276,22 @@
void NewRootTypeFromBuffer(const StructDef &struct_def,
std::string *code_ptr) {
std::string &code = *code_ptr;
- std::string size_prefix[] = { "", "SizePrefixed" };
+ const std::string size_prefix[] = { "", "SizePrefixed" };
+ const std::string struct_type = namer_.Type(struct_def.name);
for (int i = 0; i < 2; i++) {
- code += "func Get" + size_prefix[i] + "RootAs";
- code += struct_def.name;
+ code += "func Get" + size_prefix[i] + "RootAs" + struct_type;
code += "(buf []byte, offset flatbuffers.UOffsetT) ";
- code += "*" + struct_def.name + "";
+ code += "*" + struct_type + "";
code += " {\n";
if (i == 0) {
code += "\tn := flatbuffers.GetUOffsetT(buf[offset:])\n";
} else {
- code += "\tn := flatbuffers.GetUOffsetT(buf[offset+flatbuffers.SizeUint32:])\n";
+ code +=
+ "\tn := "
+ "flatbuffers.GetUOffsetT(buf[offset+flatbuffers.SizeUint32:])\n";
}
- code += "\tx := &" + struct_def.name + "{}\n";
+ code += "\tx := &" + struct_type + "{}\n";
if (i == 0) {
code += "\tx.Init(buf, n+offset)\n";
} else {
@@ -313,7 +336,7 @@
std::string &code = *code_ptr;
GenReceiver(struct_def, code_ptr);
- code += " " + MakeCamel(field.name) + "Length(";
+ code += " " + namer_.Function(field.name) + "Length(";
code += ") int " + OffsetPrefix(field);
code += "\t\treturn rcv._tab.VectorLen(o)\n\t}\n";
code += "\treturn 0\n}\n\n";
@@ -325,7 +348,7 @@
std::string &code = *code_ptr;
GenReceiver(struct_def, code_ptr);
- code += " " + MakeCamel(field.name) + "Bytes(";
+ code += " " + namer_.Function(field.name) + "Bytes(";
code += ") []byte " + OffsetPrefix(field);
code += "\t\treturn rcv._tab.ByteVector(o + rcv._tab.Pos)\n\t}\n";
code += "\treturn nil\n}\n\n";
@@ -337,7 +360,7 @@
std::string &code = *code_ptr;
std::string getter = GenGetter(field.value.type);
GenReceiver(struct_def, code_ptr);
- code += " " + MakeCamel(field.name);
+ code += " " + namer_.Function(field.name);
code += "() " + TypeName(field) + " {\n";
code += "\treturn " +
CastToEnum(field.value.type,
@@ -352,10 +375,18 @@
std::string &code = *code_ptr;
std::string getter = GenGetter(field.value.type);
GenReceiver(struct_def, code_ptr);
- code += " " + MakeCamel(field.name);
+ code += " " + namer_.Function(field.name);
code += "() " + TypeName(field) + " ";
- code += OffsetPrefix(field) + "\t\treturn ";
+ code += OffsetPrefix(field);
+ if (field.IsScalarOptional()) {
+ code += "\t\tv := ";
+ } else {
+ code += "\t\treturn ";
+ }
code += CastToEnum(field.value.type, getter + "(o + rcv._tab.Pos)");
+ if (field.IsScalarOptional()) {
+ code += "\n\t\treturn &v";
+ }
code += "\n\t}\n";
code += "\treturn " + GenConstant(field) + "\n";
code += "}\n\n";
@@ -367,7 +398,7 @@
const FieldDef &field, std::string *code_ptr) {
std::string &code = *code_ptr;
GenReceiver(struct_def, code_ptr);
- code += " " + MakeCamel(field.name);
+ code += " " + namer_.Function(field.name);
code += "(obj *" + TypeName(field);
code += ") *" + TypeName(field);
code += " {\n";
@@ -386,7 +417,7 @@
std::string *code_ptr) {
std::string &code = *code_ptr;
GenReceiver(struct_def, code_ptr);
- code += " " + MakeCamel(field.name);
+ code += " " + namer_.Function(field.name);
code += "(obj *";
code += TypeName(field);
code += ") *" + TypeName(field) + " " + OffsetPrefix(field);
@@ -408,7 +439,7 @@
std::string *code_ptr) {
std::string &code = *code_ptr;
GenReceiver(struct_def, code_ptr);
- code += " " + MakeCamel(field.name);
+ code += " " + namer_.Function(field.name);
code += "() " + TypeName(field) + " ";
code += OffsetPrefix(field) + "\t\treturn " + GenGetter(field.value.type);
code += "(o + rcv._tab.Pos)\n\t}\n\treturn nil\n";
@@ -420,7 +451,7 @@
std::string *code_ptr) {
std::string &code = *code_ptr;
GenReceiver(struct_def, code_ptr);
- code += " " + MakeCamel(field.name) + "(";
+ code += " " + namer_.Function(field.name) + "(";
code += "obj " + GenTypePointer(field.value.type) + ") bool ";
code += OffsetPrefix(field);
code += "\t\t" + GenGetter(field.value.type);
@@ -436,7 +467,7 @@
auto vectortype = field.value.type.VectorType();
GenReceiver(struct_def, code_ptr);
- code += " " + MakeCamel(field.name);
+ code += " " + namer_.Function(field.name);
code += "(obj *" + TypeName(field);
code += ", j int) bool " + OffsetPrefix(field);
code += "\t\tx := rcv._tab.Vector(o)\n";
@@ -459,7 +490,7 @@
auto vectortype = field.value.type.VectorType();
GenReceiver(struct_def, code_ptr);
- code += " " + MakeCamel(field.name);
+ code += " " + namer_.Function(field.name);
code += "(j int) " + TypeName(field) + " ";
code += OffsetPrefix(field);
code += "\t\ta := rcv._tab.Vector(o)\n";
@@ -507,7 +538,7 @@
} else {
std::string &code = *code_ptr;
code += std::string(", ") + nameprefix;
- code += GoIdentity(field.name);
+ code += namer_.Variable(field.name);
code += " " + TypeName(field);
}
}
@@ -537,7 +568,7 @@
} else {
code += "\tbuilder.Prepend" + GenMethod(field) + "(";
code += CastToBaseType(field.value.type,
- nameprefix + GoIdentity(field.name)) +
+ nameprefix + namer_.Variable(field.name)) +
")\n";
}
}
@@ -552,7 +583,7 @@
// Get the value of a table's starting offset.
void GetStartOfTable(const StructDef &struct_def, std::string *code_ptr) {
std::string &code = *code_ptr;
- code += "func " + struct_def.name + "Start";
+ code += "func " + namer_.Type(struct_def.name) + "Start";
code += "(builder *flatbuffers.Builder) {\n";
code += "\tbuilder.StartObject(";
code += NumToString(struct_def.fields.vec.size());
@@ -563,35 +594,46 @@
void BuildFieldOfTable(const StructDef &struct_def, const FieldDef &field,
const size_t offset, std::string *code_ptr) {
std::string &code = *code_ptr;
- code += "func " + struct_def.name + "Add" + MakeCamel(field.name);
+ const std::string field_var = namer_.Variable(field.name);
+ code += "func " + namer_.Type(struct_def.name) + "Add" +
+ namer_.Function(field.name);
code += "(builder *flatbuffers.Builder, ";
- code += GoIdentity(field.name) + " ";
+ code += field_var + " ";
if (!IsScalar(field.value.type.base_type) && (!struct_def.fixed)) {
code += "flatbuffers.UOffsetT";
} else {
- code += TypeName(field);
+ code += GenTypeGet(field.value.type);
}
- code += ") {\n";
- code += "\tbuilder.Prepend";
- code += GenMethod(field) + "Slot(";
- code += NumToString(offset) + ", ";
- if (!IsScalar(field.value.type.base_type) && (!struct_def.fixed)) {
- code += "flatbuffers.UOffsetT";
+ code += ") {\n\t";
+ code += "builder.Prepend";
+ code += GenMethod(field);
+ if (field.IsScalarOptional()) {
code += "(";
- code += GoIdentity(field.name) + ")";
} else {
- code += CastToBaseType(field.value.type, GoIdentity(field.name));
+ code += "Slot(" + NumToString(offset) + ", ";
}
- code += ", " + GenConstant(field);
- code += ")\n}\n";
+ if (!IsScalar(field.value.type.base_type) && (!struct_def.fixed)) {
+ code += "flatbuffers.UOffsetT";
+ code += "(" + field_var + ")";
+ } else {
+ code += CastToBaseType(field.value.type, field_var);
+ }
+ if (field.IsScalarOptional()) {
+ code += ")\n";
+ code += "\tbuilder.Slot(" + NumToString(offset);
+ } else {
+ code += ", " + GenConstant(field);
+ }
+ code += ")\n";
+ code += "}\n";
}
// Set the value of one of the members of a table's vector.
void BuildVectorOfTable(const StructDef &struct_def, const FieldDef &field,
std::string *code_ptr) {
std::string &code = *code_ptr;
- code += "func " + struct_def.name + "Start";
- code += MakeCamel(field.name);
+ code += "func " + namer_.Type(struct_def.name) + "Start";
+ code += namer_.Function(field.name);
code += "Vector(builder *flatbuffers.Builder, numElems int) ";
code += "flatbuffers.UOffsetT {\n\treturn builder.StartVector(";
auto vector_type = field.value.type.VectorType();
@@ -605,7 +647,7 @@
// Get the offset of the end of a table.
void GetEndOffsetOnTable(const StructDef &struct_def, std::string *code_ptr) {
std::string &code = *code_ptr;
- code += "func " + struct_def.name + "End";
+ code += "func " + namer_.Type(struct_def.name) + "End";
code += "(builder *flatbuffers.Builder) flatbuffers.UOffsetT ";
code += "{\n\treturn builder.EndObject()\n}\n";
}
@@ -613,7 +655,7 @@
// Generate the receiver for function signatures.
void GenReceiver(const StructDef &struct_def, std::string *code_ptr) {
std::string &code = *code_ptr;
- code += "func (rcv *" + struct_def.name + ")";
+ code += "func (rcv *" + namer_.Type(struct_def.name) + ")";
}
// Generate a struct field getter, conditioned on its child type(s).
@@ -663,11 +705,11 @@
void MutateScalarFieldOfStruct(const StructDef &struct_def,
const FieldDef &field, std::string *code_ptr) {
std::string &code = *code_ptr;
- std::string type = MakeCamel(GenTypeBasic(field.value.type));
- std::string setter = "rcv._tab.Mutate" + type;
+ std::string setter =
+ "rcv._tab.Mutate" + namer_.Method(GenTypeBasic(field.value.type));
GenReceiver(struct_def, code_ptr);
- code += " Mutate" + MakeCamel(field.name);
- code += "(n " + TypeName(field) + ") bool {\n\treturn " + setter;
+ code += " Mutate" + namer_.Function(field.name);
+ code += "(n " + GenTypeGet(field.value.type) + ") bool {\n\treturn " + setter;
code += "(rcv._tab.Pos+flatbuffers.UOffsetT(";
code += NumToString(field.value.offset) + "), ";
code += CastToBaseType(field.value.type, "n") + ")\n}\n\n";
@@ -677,11 +719,11 @@
void MutateScalarFieldOfTable(const StructDef &struct_def,
const FieldDef &field, std::string *code_ptr) {
std::string &code = *code_ptr;
- std::string type = MakeCamel(GenTypeBasic(field.value.type));
- std::string setter = "rcv._tab.Mutate" + type + "Slot";
+ std::string setter = "rcv._tab.Mutate" +
+ namer_.Method(GenTypeBasic(field.value.type)) + "Slot";
GenReceiver(struct_def, code_ptr);
- code += " Mutate" + MakeCamel(field.name);
- code += "(n " + TypeName(field) + ") bool {\n\treturn ";
+ code += " Mutate" + namer_.Function(field.name);
+ code += "(n " + GenTypeGet(field.value.type) + ") bool {\n\treturn ";
code += setter + "(" + NumToString(field.value.offset) + ", ";
code += CastToBaseType(field.value.type, "n") + ")\n";
code += "}\n\n";
@@ -693,10 +735,10 @@
std::string *code_ptr) {
std::string &code = *code_ptr;
auto vectortype = field.value.type.VectorType();
- std::string type = MakeCamel(GenTypeBasic(vectortype));
- std::string setter = "rcv._tab.Mutate" + type;
+ std::string setter =
+ "rcv._tab.Mutate" + namer_.Method(GenTypeBasic(vectortype));
GenReceiver(struct_def, code_ptr);
- code += " Mutate" + MakeCamel(field.name);
+ code += " Mutate" + namer_.Function(field.name);
code += "(j int, n " + TypeName(field) + ") bool ";
code += OffsetPrefix(field);
code += "\t\ta := rcv._tab.Vector(o)\n";
@@ -799,8 +841,11 @@
field.value.type.enum_def != nullptr &&
field.value.type.enum_def->is_union)
continue;
- code += "\t" + MakeCamel(field.name) + " " +
- NativeType(field.value.type) + "\n";
+ code += "\t" + namer_.Field(field.name) + " ";
+ if (field.IsScalarOptional()) {
+ code += "*";
+ }
+ code += NativeType(field.value.type) + "\n";
}
code += "}\n\n";
@@ -816,7 +861,7 @@
void GenNativeUnion(const EnumDef &enum_def, std::string *code_ptr) {
std::string &code = *code_ptr;
code += "type " + NativeName(enum_def) + " struct {\n";
- code += "\tType " + enum_def.name + "\n";
+ code += "\tType " + namer_.Type(enum_def.name) + "\n";
code += "\tValue interface{}\n";
code += "}\n\n";
}
@@ -832,7 +877,7 @@
++it2) {
const EnumVal &ev = **it2;
if (ev.IsZero()) continue;
- code += "\tcase " + enum_def.name + ev.name + ":\n";
+ code += "\tcase " + namer_.EnumVariant(enum_def.name, ev.name) + ":\n";
code += "\t\treturn t.Value.(" + NativeType(ev.union_type) +
").Pack(builder)\n";
}
@@ -844,7 +889,7 @@
void GenNativeUnionUnPack(const EnumDef &enum_def, std::string *code_ptr) {
std::string &code = *code_ptr;
- code += "func (rcv " + enum_def.name +
+ code += "func (rcv " + namer_.Type(enum_def.name) +
") UnPack(table flatbuffers.Table) *" + NativeName(enum_def) +
" {\n";
code += "\tswitch rcv {\n";
@@ -853,13 +898,14 @@
++it2) {
const EnumVal &ev = **it2;
if (ev.IsZero()) continue;
- code += "\tcase " + enum_def.name + ev.name + ":\n";
+ code += "\tcase " + namer_.EnumVariant(enum_def.name, ev.name) + ":\n";
code += "\t\tx := " + ev.union_type.struct_def->name + "{_tab: table}\n";
code += "\t\treturn &" +
WrapInNameSpaceAndTrack(enum_def.defined_namespace,
NativeName(enum_def)) +
- "{ Type: " + enum_def.name + ev.name + ", Value: x.UnPack() }\n";
+ "{ Type: " + namer_.EnumVariant(enum_def.name, ev.name) +
+ ", Value: x.UnPack() }\n";
}
code += "\t}\n";
code += "\treturn nil\n";
@@ -868,6 +914,7 @@
void GenNativeTablePack(const StructDef &struct_def, std::string *code_ptr) {
std::string &code = *code_ptr;
+ const std::string struct_type = namer_.Type(struct_def.name);
code += "func (t *" + NativeName(struct_def) +
") Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT {\n";
@@ -878,53 +925,56 @@
if (field.deprecated) continue;
if (IsScalar(field.value.type.base_type)) continue;
- std::string offset = MakeCamel(field.name, false) + "Offset";
+ const std::string field_field = namer_.Field(field.name);
+ const std::string field_var = namer_.Variable(field.name);
+ const std::string offset = field_var + "Offset";
if (IsString(field.value.type)) {
- code += "\t" + offset + " := builder.CreateString(t." +
- MakeCamel(field.name) + ")\n";
+ code +=
+ "\t" + offset + " := builder.CreateString(t." + field_field + ")\n";
} else if (IsVector(field.value.type) &&
field.value.type.element == BASE_TYPE_UCHAR &&
field.value.type.enum_def == nullptr) {
code += "\t" + offset + " := flatbuffers.UOffsetT(0)\n";
- code += "\tif t." + MakeCamel(field.name) + " != nil {\n";
+ code += "\tif t." + field_field + " != nil {\n";
code += "\t\t" + offset + " = builder.CreateByteString(t." +
- MakeCamel(field.name) + ")\n";
+ field_field + ")\n";
code += "\t}\n";
} else if (IsVector(field.value.type)) {
code += "\t" + offset + " := flatbuffers.UOffsetT(0)\n";
- code += "\tif t." + MakeCamel(field.name) + " != nil {\n";
- std::string length = MakeCamel(field.name, false) + "Length";
- std::string offsets = MakeCamel(field.name, false) + "Offsets";
- code += "\t\t" + length + " := len(t." + MakeCamel(field.name) + ")\n";
+ code += "\tif t." + field_field + " != nil {\n";
+ std::string length = field_var + "Length";
+ std::string offsets = field_var + "Offsets";
+ code += "\t\t" + length + " := len(t." + field_field + ")\n";
if (field.value.type.element == BASE_TYPE_STRING) {
code += "\t\t" + offsets + " := make([]flatbuffers.UOffsetT, " +
length + ")\n";
code += "\t\tfor j := 0; j < " + length + "; j++ {\n";
code += "\t\t\t" + offsets + "[j] = builder.CreateString(t." +
- MakeCamel(field.name) + "[j])\n";
+ field_field + "[j])\n";
code += "\t\t}\n";
} else if (field.value.type.element == BASE_TYPE_STRUCT &&
!field.value.type.struct_def->fixed) {
code += "\t\t" + offsets + " := make([]flatbuffers.UOffsetT, " +
length + ")\n";
code += "\t\tfor j := 0; j < " + length + "; j++ {\n";
- code += "\t\t\t" + offsets + "[j] = t." + MakeCamel(field.name) +
+ code += "\t\t\t" + offsets + "[j] = t." + field_field +
"[j].Pack(builder)\n";
code += "\t\t}\n";
}
- code += "\t\t" + struct_def.name + "Start" + MakeCamel(field.name) +
+ code += "\t\t" + struct_type + "Start" + namer_.Function(field.name) +
"Vector(builder, " + length + ")\n";
code += "\t\tfor j := " + length + " - 1; j >= 0; j-- {\n";
if (IsScalar(field.value.type.element)) {
code += "\t\t\tbuilder.Prepend" +
- MakeCamel(GenTypeBasic(field.value.type.VectorType())) + "(" +
+ namer_.Method(GenTypeBasic(field.value.type.VectorType())) +
+ "(" +
CastToBaseType(field.value.type.VectorType(),
- "t." + MakeCamel(field.name) + "[j]") +
+ "t." + field_field + "[j]") +
")\n";
} else if (field.value.type.element == BASE_TYPE_STRUCT &&
field.value.type.struct_def->fixed) {
- code += "\t\t\tt." + MakeCamel(field.name) + "[j].Pack(builder)\n";
+ code += "\t\t\tt." + field_field + "[j].Pack(builder)\n";
} else {
code += "\t\t\tbuilder.PrependUOffsetT(" + offsets + "[j])\n";
}
@@ -933,90 +983,98 @@
code += "\t}\n";
} else if (field.value.type.base_type == BASE_TYPE_STRUCT) {
if (field.value.type.struct_def->fixed) continue;
- code += "\t" + offset + " := t." + MakeCamel(field.name) +
- ".Pack(builder)\n";
+ code += "\t" + offset + " := t." + field_field + ".Pack(builder)\n";
} else if (field.value.type.base_type == BASE_TYPE_UNION) {
- code += "\t" + offset + " := t." + MakeCamel(field.name) +
- ".Pack(builder)\n";
+ code += "\t" + offset + " := t." + field_field + ".Pack(builder)\n";
code += "\t\n";
} else {
FLATBUFFERS_ASSERT(0);
}
}
- code += "\t" + struct_def.name + "Start(builder)\n";
+ code += "\t" + struct_type + "Start(builder)\n";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
const FieldDef &field = **it;
if (field.deprecated) continue;
+ const std::string field_field = namer_.Field(field.name);
+ const std::string field_fn = namer_.Function(field.name);
+ const std::string offset = namer_.Variable(field.name) + "Offset";
- std::string offset = MakeCamel(field.name, false) + "Offset";
if (IsScalar(field.value.type.base_type)) {
+ std::string prefix;
+ if (field.IsScalarOptional()) {
+ code += "\tif t." + field_field + " != nil {\n\t";
+ prefix = "*";
+ }
if (field.value.type.enum_def == nullptr ||
!field.value.type.enum_def->is_union) {
- code += "\t" + struct_def.name + "Add" + MakeCamel(field.name) +
- "(builder, t." + MakeCamel(field.name) + ")\n";
+ code += "\t" + struct_type + "Add" + field_fn + "(builder, " +
+ prefix + "t." + field_field + ")\n";
+ }
+ if (field.IsScalarOptional()) {
+ code += "\t}\n";
}
} else {
if (field.value.type.base_type == BASE_TYPE_STRUCT &&
field.value.type.struct_def->fixed) {
- code += "\t" + offset + " := t." + MakeCamel(field.name) +
- ".Pack(builder)\n";
+ code += "\t" + offset + " := t." + field_field + ".Pack(builder)\n";
} else if (field.value.type.enum_def != nullptr &&
field.value.type.enum_def->is_union) {
- code += "\tif t." + MakeCamel(field.name) + " != nil {\n";
- code += "\t\t" + struct_def.name + "Add" +
- MakeCamel(field.name + UnionTypeFieldSuffix()) +
- "(builder, t." + MakeCamel(field.name) + ".Type)\n";
+ code += "\tif t." + field_field + " != nil {\n";
+ code += "\t\t" + struct_type + "Add" +
+ namer_.Method(field.name + UnionTypeFieldSuffix()) +
+ "(builder, t." + field_field + ".Type)\n";
code += "\t}\n";
}
- code += "\t" + struct_def.name + "Add" + MakeCamel(field.name) +
- "(builder, " + offset + ")\n";
+ code += "\t" + struct_type + "Add" + field_fn + "(builder, " + offset +
+ ")\n";
}
}
- code += "\treturn " + struct_def.name + "End(builder)\n";
+ code += "\treturn " + struct_type + "End(builder)\n";
code += "}\n\n";
}
void GenNativeTableUnPack(const StructDef &struct_def,
std::string *code_ptr) {
std::string &code = *code_ptr;
+ const std::string struct_type = namer_.Type(struct_def.name);
- code += "func (rcv *" + struct_def.name + ") UnPackTo(t *" +
+ code += "func (rcv *" + struct_type + ") UnPackTo(t *" +
NativeName(struct_def) + ") {\n";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
const FieldDef &field = **it;
if (field.deprecated) continue;
- std::string field_name_camel = MakeCamel(field.name);
- std::string length = MakeCamel(field.name, false) + "Length";
+ const std::string field_field = namer_.Field(field.name);
+ const std::string field_var = namer_.Variable(field.name);
+ const std::string length = field_var + "Length";
if (IsScalar(field.value.type.base_type)) {
if (field.value.type.enum_def != nullptr &&
field.value.type.enum_def->is_union)
continue;
- code +=
- "\tt." + field_name_camel + " = rcv." + field_name_camel + "()\n";
+ code += "\tt." + field_field + " = rcv." + field_field + "()\n";
} else if (IsString(field.value.type)) {
- code += "\tt." + field_name_camel + " = string(rcv." +
- field_name_camel + "())\n";
+ code += "\tt." + field_field + " = string(rcv." + field_field + "())\n";
} else if (IsVector(field.value.type) &&
field.value.type.element == BASE_TYPE_UCHAR &&
field.value.type.enum_def == nullptr) {
- code += "\tt." + field_name_camel + " = rcv." + field_name_camel +
- "Bytes()\n";
+ code += "\tt." + field_field + " = rcv." + field_field + "Bytes()\n";
} else if (IsVector(field.value.type)) {
- code += "\t" + length + " := rcv." + field_name_camel + "Length()\n";
- code += "\tt." + field_name_camel + " = make(" +
+ code += "\t" + length + " := rcv." + field_field + "Length()\n";
+ code += "\tt." + field_field + " = make(" +
NativeType(field.value.type) + ", " + length + ")\n";
code += "\tfor j := 0; j < " + length + "; j++ {\n";
if (field.value.type.element == BASE_TYPE_STRUCT) {
- code += "\t\tx := " + field.value.type.struct_def->name + "{}\n";
- code += "\t\trcv." + field_name_camel + "(&x, j)\n";
+ code += "\t\tx := " +
+ WrapInNameSpaceAndTrack(*field.value.type.struct_def) +
+ "{}\n";
+ code += "\t\trcv." + field_field + "(&x, j)\n";
}
- code += "\t\tt." + field_name_camel + "[j] = ";
+ code += "\t\tt." + field_field + "[j] = ";
if (IsScalar(field.value.type.element)) {
- code += "rcv." + field_name_camel + "(j)";
+ code += "rcv." + field_field + "(j)";
} else if (field.value.type.element == BASE_TYPE_STRING) {
- code += "string(rcv." + field_name_camel + "(j))";
+ code += "string(rcv." + field_field + "(j))";
} else if (field.value.type.element == BASE_TYPE_STRUCT) {
code += "x.UnPack()";
} else {
@@ -1026,16 +1084,16 @@
code += "\n";
code += "\t}\n";
} else if (field.value.type.base_type == BASE_TYPE_STRUCT) {
- code += "\tt." + field_name_camel + " = rcv." + field_name_camel +
- "(nil).UnPack()\n";
- } else if (field.value.type.base_type == BASE_TYPE_UNION) {
- std::string field_table = MakeCamel(field.name, false) + "Table";
- code += "\t" + field_table + " := flatbuffers.Table{}\n";
code +=
- "\tif rcv." + MakeCamel(field.name) + "(&" + field_table + ") {\n";
- code += "\t\tt." + field_name_camel + " = rcv." +
- MakeCamel(field.name + UnionTypeFieldSuffix()) + "().UnPack(" +
- field_table + ")\n";
+ "\tt." + field_field + " = rcv." + field_field + "(nil).UnPack()\n";
+ } else if (field.value.type.base_type == BASE_TYPE_UNION) {
+ const std::string field_table = field_var + "Table";
+ code += "\t" + field_table + " := flatbuffers.Table{}\n";
+ code += "\tif rcv." + namer_.Method(field.name) + "(&" + field_table +
+ ") {\n";
+ code += "\t\tt." + field_field + " = rcv." +
+ namer_.Method(field.name + UnionTypeFieldSuffix()) +
+ "().UnPack(" + field_table + ")\n";
code += "\t}\n";
} else {
FLATBUFFERS_ASSERT(0);
@@ -1043,7 +1101,7 @@
}
code += "}\n\n";
- code += "func (rcv *" + struct_def.name + ") UnPack() *" +
+ code += "func (rcv *" + struct_type + ") UnPack() *" +
NativeName(struct_def) + " {\n";
code += "\tif rcv == nil { return nil }\n";
code += "\tt := &" + NativeName(struct_def) + "{}\n";
@@ -1058,7 +1116,7 @@
code += "func (t *" + NativeName(struct_def) +
") Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT {\n";
code += "\tif t == nil { return 0 }\n";
- code += "\treturn Create" + struct_def.name + "(builder";
+ code += "\treturn Create" + namer_.Type(struct_def.name) + "(builder";
StructPackArgs(struct_def, "", code_ptr);
code += ")\n";
code += "}\n";
@@ -1072,10 +1130,10 @@
const FieldDef &field = **it;
if (field.value.type.base_type == BASE_TYPE_STRUCT) {
StructPackArgs(*field.value.type.struct_def,
- (nameprefix + MakeCamel(field.name) + ".").c_str(),
+ (nameprefix + namer_.Field(field.name) + ".").c_str(),
code_ptr);
} else {
- code += std::string(", t.") + nameprefix + MakeCamel(field.name);
+ code += std::string(", t.") + nameprefix + namer_.Field(field.name);
}
}
}
@@ -1084,22 +1142,22 @@
std::string *code_ptr) {
std::string &code = *code_ptr;
- code += "func (rcv *" + struct_def.name + ") UnPackTo(t *" +
+ code += "func (rcv *" + namer_.Type(struct_def.name) + ") UnPackTo(t *" +
NativeName(struct_def) + ") {\n";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
const FieldDef &field = **it;
if (field.value.type.base_type == BASE_TYPE_STRUCT) {
- code += "\tt." + MakeCamel(field.name) + " = rcv." +
- MakeCamel(field.name) + "(nil).UnPack()\n";
+ code += "\tt." + namer_.Field(field.name) + " = rcv." +
+ namer_.Method(field.name) + "(nil).UnPack()\n";
} else {
- code += "\tt." + MakeCamel(field.name) + " = rcv." +
- MakeCamel(field.name) + "()\n";
+ code += "\tt." + namer_.Field(field.name) + " = rcv." +
+ namer_.Method(field.name) + "()\n";
}
}
code += "}\n\n";
- code += "func (rcv *" + struct_def.name + ") UnPack() *" +
+ code += "func (rcv *" + namer_.Type(struct_def.name) + ") UnPack() *" +
NativeName(struct_def) + " {\n";
code += "\tif rcv == nil { return nil }\n";
code += "\tt := &" + NativeName(struct_def) + "{}\n";
@@ -1148,14 +1206,14 @@
case BASE_TYPE_STRING: return "rcv._tab.ByteVector";
case BASE_TYPE_UNION: return "rcv._tab.Union";
case BASE_TYPE_VECTOR: return GenGetter(type.VectorType());
- default: return "rcv._tab.Get" + MakeCamel(GenTypeBasic(type));
+ default: return "rcv._tab.Get" + namer_.Function(GenTypeBasic(type));
}
}
// Returns the method name for use with add/put calls.
std::string GenMethod(const FieldDef &field) {
return IsScalar(field.value.type.base_type)
- ? MakeCamel(GenTypeBasic(field.value.type))
+ ? namer_.Method(GenTypeBasic(field.value.type))
: (IsStruct(field.value.type) ? "Struct" : "UOffsetT");
}
@@ -1188,7 +1246,11 @@
}
std::string TypeName(const FieldDef &field) {
- return GenTypeGet(field.value.type);
+ std::string prefix;
+ if (field.IsScalarOptional()) {
+ prefix = "*";
+ }
+ return prefix + GenTypeGet(field.value.type);
}
// If type is an enum, returns value with a cast to the enum type, otherwise
@@ -1212,6 +1274,9 @@
}
std::string GenConstant(const FieldDef &field) {
+ if (field.IsScalarOptional()) {
+ return "nil";
+ }
switch (field.value.type.base_type) {
case BASE_TYPE_BOOL:
return field.value.constant == "0" ? "false" : "true";
@@ -1219,14 +1284,12 @@
}
}
- std::string NativeName(const StructDef &struct_def) {
- return parser_.opts.object_prefix + struct_def.name +
- parser_.opts.object_suffix;
+ std::string NativeName(const StructDef &struct_def) const {
+ return namer_.ObjectType(struct_def.name);
}
- std::string NativeName(const EnumDef &enum_def) {
- return parser_.opts.object_prefix + enum_def.name +
- parser_.opts.object_suffix;
+ std::string NativeName(const EnumDef &enum_def) const {
+ return namer_.ObjectType(enum_def.name);
}
std::string NativeType(const Type &type) {
@@ -1303,34 +1366,20 @@
while (code.length() > 2 && code.substr(code.length() - 2) == "\n\n") {
code.pop_back();
}
- std::string filename = NamespaceDir(ns) + def.name + ".go";
+ std::string filename = namer_.Directories(ns.components) +
+ namer_.File(def.name, SkipFile::Suffix);
return SaveFile(filename.c_str(), code, false);
}
// Create the full name of the imported namespace (format: A__B__C).
- std::string NamespaceImportName(const Namespace *ns) {
- std::string s = "";
- for (auto it = ns->components.begin(); it != ns->components.end(); ++it) {
- if (s.size() == 0) {
- s += *it;
- } else {
- s += "__" + *it;
- }
- }
- return s;
+ std::string NamespaceImportName(const Namespace *ns) const {
+ return namer_.Namespace(ns->components);
}
// Create the full path for the imported namespace (format: A/B/C).
- std::string NamespaceImportPath(const Namespace *ns) {
- std::string s = "";
- for (auto it = ns->components.begin(); it != ns->components.end(); ++it) {
- if (s.size() == 0) {
- s += *it;
- } else {
- s += "/" + *it;
- }
- }
- return s;
+ std::string NamespaceImportPath(const Namespace *ns) const {
+ return namer_.Directories(ns->components,
+ SkipDir::OutputPathAndTrailingPathSeparator);
}
// Ensure that a type is prefixed with its go package import name if it is
@@ -1340,9 +1389,7 @@
if (CurrentNameSpace() == ns) return name;
tracked_imported_namespaces_.insert(ns);
-
- std::string import_name = NamespaceImportName(ns);
- return import_name + "." + name;
+ return NamespaceImportName(ns) + "." + name;
}
std::string WrapInNameSpaceAndTrack(const Definition &def) {
diff --git a/src/idl_gen_grpc.cpp b/src/idl_gen_grpc.cpp
index 394ebe3..6894ffb 100644
--- a/src/idl_gen_grpc.cpp
+++ b/src/idl_gen_grpc.cpp
@@ -24,7 +24,6 @@
#include "src/compiler/go_generator.h"
#include "src/compiler/java_generator.h"
#include "src/compiler/python_generator.h"
-#include "src/compiler/python_private_generator.h"
#include "src/compiler/swift_generator.h"
#include "src/compiler/ts_generator.h"
@@ -146,7 +145,12 @@
class FlatBufPrinter : public grpc_generator::Printer {
public:
- FlatBufPrinter(std::string *str) : str_(str), escape_char_('$'), indent_(0) {}
+ FlatBufPrinter(std::string *str, const char indentation_type)
+ : str_(str),
+ escape_char_('$'),
+ indent_(0),
+ indentation_size_(2),
+ indentation_type_(indentation_type) {}
void Print(const std::map<std::string, std::string> &vars,
const char *string_template) {
@@ -173,7 +177,7 @@
// Add this string, but for each part separated by \n, add indentation.
for (;;) {
// Current indentation.
- str_->insert(str_->end(), indent_ * 2, ' ');
+ str_->insert(str_->end(), indent_ * indentation_size_, indentation_type_);
// See if this contains more than one line.
const char *lf = strchr(s, '\n');
if (lf) {
@@ -187,17 +191,24 @@
}
}
+ void SetIndentationSize(const size_t size) {
+ FLATBUFFERS_ASSERT(str_->empty());
+ indentation_size_ = size;
+ }
+
void Indent() { indent_++; }
void Outdent() {
+ FLATBUFFERS_ASSERT(indent_ > 0);
indent_--;
- FLATBUFFERS_ASSERT(indent_ >= 0);
}
private:
std::string *str_;
char escape_char_;
- int indent_;
+ size_t indent_;
+ size_t indentation_size_;
+ char indentation_type_;
};
class FlatBufFile : public grpc_generator::File {
@@ -231,7 +242,9 @@
return StripExtension(file_name_);
}
- std::string message_header_ext() const { return "_generated.h"; }
+ std::string message_header_ext() const {
+ return parser_.opts.filename_suffix + ".h";
+ }
std::string service_header_ext() const { return ".grpc.fb.h"; }
@@ -277,8 +290,9 @@
}
std::unique_ptr<grpc_generator::Printer> CreatePrinter(
- std::string *str) const {
- return std::unique_ptr<grpc_generator::Printer>(new FlatBufPrinter(str));
+ std::string *str, const char indentation_type = ' ') const {
+ return std::unique_ptr<grpc_generator::Printer>(
+ new FlatBufPrinter(str, indentation_type));
}
private:
@@ -399,6 +413,45 @@
return JavaGRPCGenerator(parser, path, file_name).generate();
}
+class PythonGRPCGenerator : public flatbuffers::BaseGenerator {
+ private:
+ CodeWriter code_;
+
+ public:
+ PythonGRPCGenerator(const Parser &parser, const std::string &filename)
+ : BaseGenerator(parser, "", filename, "", "" /*Unused*/, "swift") {}
+
+ bool generate() {
+ code_.Clear();
+ code_ +=
+ "# Generated by the gRPC Python protocol compiler plugin. "
+ "DO NOT EDIT!\n";
+ code_ += "import grpc\n";
+
+ FlatBufFile file(parser_, file_name_, FlatBufFile::kLanguagePython);
+
+ for (int i = 0; i < file.service_count(); i++) {
+ auto service = file.service(i);
+ code_ += grpc_python_generator::Generate(&file, service.get());
+ }
+ const auto final_code = code_.ToString();
+ const auto filename = GenerateFileName();
+ return SaveFile(filename.c_str(), final_code, false);
+ }
+
+ std::string GenerateFileName() {
+ std::string namespace_dir;
+ auto &namespaces = parser_.namespaces_.back()->components;
+ for (auto it = namespaces.begin(); it != namespaces.end(); ++it) {
+ if (it != namespaces.begin()) namespace_dir += kPathSeparator;
+ namespace_dir += *it;
+ }
+ std::string grpc_py_filename = namespace_dir;
+ if (!namespace_dir.empty()) grpc_py_filename += kPathSeparator;
+ return grpc_py_filename + file_name_ + "_grpc_fb.py";
+ }
+};
+
bool GeneratePythonGRPC(const Parser &parser, const std::string & /*path*/,
const std::string &file_name) {
int nservices = 0;
@@ -408,28 +461,7 @@
}
if (!nservices) return true;
- grpc_python_generator::GeneratorConfiguration config;
- config.grpc_package_root = "grpc";
- config.beta_package_root = "grpc.beta";
- config.import_prefix = "";
-
- FlatBufFile fbfile(parser, file_name, FlatBufFile::kLanguagePython);
-
- grpc_python_generator::PrivateGenerator generator(config, &fbfile);
-
- std::string code = generator.GetGrpcServices();
- std::string namespace_dir;
- auto &namespaces = parser.namespaces_.back()->components;
- for (auto it = namespaces.begin(); it != namespaces.end(); ++it) {
- if (it != namespaces.begin()) namespace_dir += kPathSeparator;
- namespace_dir += *it;
- }
-
- std::string grpc_py_filename = namespace_dir;
- if (!namespace_dir.empty()) grpc_py_filename += kPathSeparator;
- grpc_py_filename += file_name + "_grpc_fb.py";
-
- return flatbuffers::SaveFile(grpc_py_filename.c_str(), code, false);
+ return PythonGRPCGenerator(parser, file_name).generate();
}
class SwiftGRPCGenerator : public flatbuffers::BaseGenerator {
diff --git a/src/idl_gen_java.cpp b/src/idl_gen_java.cpp
index c51f7bc..ee09391 100644
--- a/src/idl_gen_java.cpp
+++ b/src/idl_gen_java.cpp
@@ -21,10 +21,6 @@
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
-#if defined(FLATBUFFERS_CPP98_STL)
-# include <cctype>
-#endif // defined(FLATBUFFERS_CPP98_STL)
-
namespace flatbuffers {
namespace java {
@@ -39,6 +35,11 @@
};
class JavaGenerator : public BaseGenerator {
+ struct FieldArrayLength {
+ std::string name;
+ int length;
+ };
+
public:
JavaGenerator(const Parser &parser, const std::string &path,
const std::string &file_name)
@@ -63,6 +64,19 @@
/* needs_includes= */ false))
return false;
}
+
+ if (parser_.opts.generate_object_based_api && enum_def.is_union) {
+ enumcode = "";
+ GenEnum_ObjectAPI(enum_def, &enumcode, parser_.opts);
+ auto class_name = enum_def.name + "Union";
+ if (parser_.opts.one_file) {
+ one_file_code += enumcode;
+ } else {
+ if (!SaveType(class_name, *enum_def.defined_namespace, enumcode,
+ /* needs_includes= */ false))
+ return false;
+ }
+ }
}
for (auto it = parser_.structs_.vec.begin();
@@ -71,7 +85,7 @@
auto &struct_def = **it;
if (!parser_.opts.one_file)
cur_name_space_ = struct_def.defined_namespace;
- GenStruct(struct_def, &declcode);
+ GenStruct(struct_def, &declcode, parser_.opts);
if (parser_.opts.one_file) {
one_file_code += declcode;
} else {
@@ -79,6 +93,19 @@
/* needs_includes= */ true))
return false;
}
+
+ if (parser_.opts.generate_object_based_api) {
+ declcode = "";
+ GenStruct_ObjectAPI(struct_def, &declcode, parser_.opts);
+ auto class_name = GenTypeName_ObjectAPI(struct_def.name, parser_.opts);
+ if (parser_.opts.one_file) {
+ one_file_code += declcode;
+ } else {
+ if (!SaveType(class_name, *struct_def.defined_namespace, declcode,
+ /* needs_includes= */ true))
+ return false;
+ }
+ }
}
if (parser_.opts.one_file) {
@@ -231,11 +258,11 @@
} else {
if (castFromDest) {
if (type.base_type == BASE_TYPE_UINT)
- return "(int)";
+ return "(int) ";
else if (type.base_type == BASE_TYPE_USHORT)
- return "(short)";
+ return "(short) ";
else if (type.base_type == BASE_TYPE_UCHAR)
- return "(byte)";
+ return "(byte) ";
}
}
return "";
@@ -304,6 +331,7 @@
// That, and Java Enums are expensive, and not universally liked.
GenComment(enum_def.doc_comment, code_ptr, &comment_config);
+ code += "@SuppressWarnings(\"unused\")\n";
if (enum_def.attributes.Lookup("private")) {
// For Java, we leave the enum unmarked to indicate package-private
} else {
@@ -316,14 +344,14 @@
auto &ev = **it;
GenComment(ev.doc_comment, code_ptr, &comment_config, " ");
code += " public static final ";
- code += GenTypeBasic(enum_def.underlying_type);
+ code += GenTypeBasic(DestinationType(enum_def.underlying_type, false));
code += " ";
code += ev.name + " = ";
code += enum_def.ToString(ev);
code += ";\n";
}
- // Generate a generate string table for enum values.
+ // Generate a string table for enum values.
// Problem is, if values are very sparse that could generate really big
// tables. Ideally in that case we generate a map lookup instead, but for
// the moment we simply don't output a table at all.
@@ -331,7 +359,9 @@
// Average distance between values above which we consider a table
// "too sparse". Change at will.
static const uint64_t kMaxSparseness = 5;
- if (range / static_cast<uint64_t>(enum_def.size()) < kMaxSparseness) {
+ if (range / static_cast<uint64_t>(enum_def.size()) < kMaxSparseness &&
+ GenTypeBasic(DestinationType(enum_def.underlying_type, false)) !=
+ "long") {
code += "\n public static final String";
code += "[] names = { ";
auto val = enum_def.Vals().front();
@@ -345,7 +375,7 @@
code += "};\n\n";
code += " public static ";
code += "String";
- code += " " + MakeCamel("name", false);
+ code += " name";
code += "(int e) { return names[e";
if (enum_def.MinValue()->IsNonZero())
code += " - " + enum_def.MinValue()->name;
@@ -369,7 +399,7 @@
if (type.base_type == BASE_TYPE_BOOL) {
getter = "0!=" + getter;
} else if (GenTypeBasic(type) != "byte") {
- getter += MakeCamel(GenTypeBasic(type));
+ getter += ConvertCase(GenTypeBasic(type), Case::kUpperCamel);
}
return getter;
}
@@ -385,7 +415,7 @@
auto dest_cast = DestinationCast(type);
auto getter = data_buffer + ".get";
if (GenTypeBasic(type) != "byte") {
- getter += MakeCamel(GenTypeBasic(type));
+ getter += ConvertCase(GenTypeBasic(type), Case::kUpperCamel);
}
getter = dest_cast + getter + "(" + GenOffsetGetter(key_field, num) + ")" +
dest_mask;
@@ -398,7 +428,7 @@
if (IsScalar(type.base_type)) {
std::string setter = "bb.put";
if (GenTypeBasic(type) != "byte" && type.base_type != BASE_TYPE_BOOL) {
- setter += MakeCamel(GenTypeBasic(type));
+ setter += ConvertCase(GenTypeBasic(type), Case::kUpperCamel);
}
return setter;
} else {
@@ -408,8 +438,9 @@
// Returns the method name for use with add/put calls.
std::string GenMethod(const Type &type) const {
- return IsScalar(type.base_type) ? MakeCamel(GenTypeBasic(type))
- : (IsStruct(type) ? "Struct" : "Offset");
+ return IsScalar(type.base_type)
+ ? ConvertCase(GenTypeBasic(type), Case::kUpperCamel)
+ : (IsStruct(type) ? "Struct" : "Offset");
}
// Recursively generate arguments for a constructor, to deal with nested
@@ -433,11 +464,11 @@
(nameprefix + (field.name + "_")).c_str(), array_cnt);
} else {
code += ", ";
- code += GenTypeBasic(type);
+ code += GenTypeNameDest(field.value.type);
for (size_t i = 0; i < array_cnt; i++) code += "[]";
code += " ";
code += nameprefix;
- code += MakeCamel(field.name, false);
+ code += ConvertCase(field.name, Case::kLowerCamel);
}
}
}
@@ -484,7 +515,8 @@
code += indent + " builder.put";
code += GenMethod(type) + "(";
code += SourceCast(type);
- auto argname = nameprefix + MakeCamel(field.name, false);
+ auto argname =
+ nameprefix + ConvertCase(field.name, Case::kLowerCamel);
code += argname;
size_t array_cnt = index + (IsArray(field_type) ? 1 : 0);
for (size_t i = 0; in_array && i < array_cnt; i++) {
@@ -560,7 +592,8 @@
return key_getter;
}
- void GenStruct(StructDef &struct_def, std::string *code_ptr) const {
+ void GenStruct(StructDef &struct_def, std::string *code_ptr,
+ const IDLOptions &opts) const {
if (struct_def.generated) return;
std::string &code = *code_ptr;
@@ -591,7 +624,7 @@
// Force compile time error if not using the same version runtime.
code += " public static void ValidateVersion() {";
code += " Constants.";
- code += "FLATBUFFERS_1_12_0(); ";
+ code += "FLATBUFFERS_2_0_0(); ";
code += "}\n";
// Generate a special accessor for the table that when used as the root
@@ -649,9 +682,9 @@
std::string src_cast = SourceCast(field.value.type);
std::string method_start =
" public " +
- (field.required ? "" : GenNullableAnnotation(field.value.type)) +
+ (field.IsRequired() ? "" : GenNullableAnnotation(field.value.type)) +
GenPureAnnotation(field.value.type) + type_name_dest + optional +
- " " + MakeCamel(field.name, false);
+ " " + ConvertCase(field.name, Case::kLowerCamel);
std::string obj = "obj";
// Most field accessors need to retrieve and test the field offset first,
@@ -665,15 +698,15 @@
if (field.value.type.base_type == BASE_TYPE_STRUCT) {
// Calls the accessor that takes an accessor object with a new object.
code += method_start + "() { return ";
- code += MakeCamel(field.name, false);
+ code += ConvertCase(field.name, Case::kLowerCamel);
code += "(new ";
code += type_name + "()); }\n";
- } else if (IsVector(field.value.type) &&
+ } else if (IsSeries(field.value.type) &&
field.value.type.element == BASE_TYPE_STRUCT) {
// Accessors for vectors of structs also take accessor objects, this
// generates a variant without that argument.
code += method_start + "(int j) { return ";
- code += MakeCamel(field.name, false);
+ code += ConvertCase(field.name, Case::kLowerCamel);
code += "(new " + type_name + "(), j); }\n";
}
@@ -773,7 +806,7 @@
code += member_suffix;
code += "}\n";
if (IsVector(field.value.type)) {
- code += " public int " + MakeCamel(field.name, false);
+ code += " public int " + ConvertCase(field.name, Case::kLowerCamel);
code += "Length";
code += "()";
code += offset_prefix;
@@ -790,7 +823,7 @@
if (key_field.key) {
auto qualified_name = WrapInNameSpace(sd);
code += " public " + qualified_name + " ";
- code += MakeCamel(field.name, false) + "ByKey(";
+ code += ConvertCase(field.name, Case::kLowerCamel) + "ByKey(";
code += GenTypeNameDest(key_field.value.type) + " key)";
code += offset_prefix;
code += qualified_name + ".__lookup_by_key(";
@@ -799,7 +832,7 @@
code += "bb) : null; ";
code += "}\n";
code += " public " + qualified_name + " ";
- code += MakeCamel(field.name, false) + "ByKey(";
+ code += ConvertCase(field.name, Case::kLowerCamel) + "ByKey(";
code += qualified_name + " obj, ";
code += GenTypeNameDest(key_field.value.type) + " key)";
code += offset_prefix;
@@ -817,7 +850,8 @@
std::string vector_type_name;
const auto &element_base_type = field.value.type.VectorType().base_type;
if (IsScalar(element_base_type)) {
- vector_type_name = MakeCamel(type_name, true) + "Vector";
+ vector_type_name =
+ ConvertCase(type_name, Case::kUpperCamel) + "Vector";
} else if (element_base_type == BASE_TYPE_STRING) {
vector_type_name = "StringVector";
} else if (element_base_type == BASE_TYPE_UNION) {
@@ -825,12 +859,12 @@
} else {
vector_type_name = type_name + ".Vector";
}
- auto vector_method_start = GenNullableAnnotation(field.value.type) +
- " public " + vector_type_name + optional +
- " " + MakeCamel(field.name, false) +
- "Vector";
+ auto vector_method_start =
+ GenNullableAnnotation(field.value.type) + " public " +
+ vector_type_name + optional + " " +
+ ConvertCase(field.name, Case::kLowerCamel) + "Vector";
code += vector_method_start + "() { return ";
- code += MakeCamel(field.name, false) + "Vector";
+ code += ConvertCase(field.name, Case::kLowerCamel) + "Vector";
code += "(new " + vector_type_name + "()); }\n";
code += vector_method_start + "(" + vector_type_name + " obj)";
code += offset_prefix + conditional_cast + obj + ".__assign(";
@@ -846,7 +880,7 @@
IsScalar(field.value.type.VectorType().base_type)) ||
IsString(field.value.type)) {
code += " public ByteBuffer ";
- code += MakeCamel(field.name, false);
+ code += ConvertCase(field.name, Case::kLowerCamel);
code += "AsByteBuffer() { return ";
code += "__vector_as_bytebuffer(";
code += NumToString(field.value.offset) + ", ";
@@ -855,7 +889,7 @@
: InlineSize(field.value.type.VectorType()));
code += "); }\n";
code += " public ByteBuffer ";
- code += MakeCamel(field.name, false);
+ code += ConvertCase(field.name, Case::kLowerCamel);
code += "InByteBuffer(ByteBuffer _bb) { return ";
code += "__vector_in_bytebuffer(_bb, ";
code += NumToString(field.value.offset) + ", ";
@@ -867,8 +901,8 @@
// generate object accessors if is nested_flatbuffer
if (field.nested_flatbuffer) {
auto nested_type_name = WrapInNameSpace(*field.nested_flatbuffer);
- auto nested_method_name =
- MakeCamel(field.name, false) + "As" + field.nested_flatbuffer->name;
+ auto nested_method_name = ConvertCase(field.name, Case::kLowerCamel) +
+ "As" + field.nested_flatbuffer->name;
auto get_nested_method_name = nested_method_name;
code += " public " + nested_type_name + " ";
code += nested_method_name + "() { return ";
@@ -894,7 +928,7 @@
auto setter_parameter = underlying_type.base_type == BASE_TYPE_BOOL
? "(byte)(" + field.name + " ? 1 : 0)"
: field.name;
- auto mutator_prefix = MakeCamel("mutate", false);
+ auto mutator_prefix = "mutate";
// A vector mutator also needs the index of the vector element it should
// mutate.
auto mutator_params = (is_series ? "(int j, " : "(") +
@@ -912,7 +946,7 @@
if (IsScalar(underlying_type.base_type) && !IsUnion(field.value.type)) {
code += " public ";
code += struct_def.fixed ? "void " : "boolean ";
- code += mutator_prefix + MakeCamel(field.name, true);
+ code += mutator_prefix + ConvertCase(field.name, Case::kUpperCamel);
code += mutator_params;
if (struct_def.fixed) {
code += GenSetter(underlying_type) + "(" + setter_index + ", ";
@@ -928,17 +962,21 @@
}
if (parser_.opts.java_primitive_has_method &&
IsScalar(field.value.type.base_type) && !struct_def.fixed) {
- auto vt_offset_constant = " public static final int VT_" +
- MakeScreamingCamel(field.name) + " = " +
- NumToString(field.value.offset) + ";";
+ auto vt_offset_constant =
+ " public static final int VT_" +
+ ConvertCase(field.name, Case::kScreamingSnake) + " = " +
+ NumToString(field.value.offset) + ";";
code += vt_offset_constant;
code += "\n";
}
}
code += "\n";
+ auto struct_has_create = false;
+ std::set<flatbuffers::FieldDef *> field_has_create_set;
flatbuffers::FieldDef *key_field = nullptr;
if (struct_def.fixed) {
+ struct_has_create = true;
// create a struct constructor function
code += " public static " + GenOffsetType() + " ";
code += "create";
@@ -968,6 +1006,7 @@
// JVM specifications restrict default constructor params to be < 255.
// Longs and doubles take up 2 units, so we set the limit to be < 127.
if (has_no_struct_fields && num_fields && num_fields < 127) {
+ struct_has_create = true;
// Generate a table constructor of the form:
// public static int createName(FlatBufferBuilder builder, args...)
code += " public static " + GenOffsetType() + " ";
@@ -976,11 +1015,12 @@
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
+ auto field_name = ConvertCase(field.name, Case::kLowerCamel);
if (field.deprecated) continue;
code += ",\n ";
code += GenTypeBasic(DestinationType(field.value.type, false));
code += " ";
- code += field.name;
+ code += field_name;
if (!IsScalar(field.value.type.base_type)) code += "Offset";
}
code += ") {\n builder.";
@@ -991,12 +1031,14 @@
for (auto it = struct_def.fields.vec.rbegin();
it != struct_def.fields.vec.rend(); ++it) {
auto &field = **it;
+ auto field_name = ConvertCase(field.name, Case::kLowerCamel);
+ auto method_name = ConvertCase(field.name, Case::kUpperCamel);
if (!field.deprecated &&
(!struct_def.sortbysize ||
size == SizeOf(field.value.type.base_type))) {
code += " " + struct_def.name + ".";
code += "add";
- code += MakeCamel(field.name) + "(builder, " + field.name;
+ code += method_name + "(builder, " + field_name;
if (!IsScalar(field.value.type.base_type)) code += "Offset";
code += ");\n";
}
@@ -1022,10 +1064,10 @@
if (field.deprecated) continue;
if (field.key) key_field = &field;
code += " public static void add";
- code += MakeCamel(field.name);
+ code += ConvertCase(field.name, Case::kUpperCamel);
code += "(FlatBufferBuilder builder, ";
code += GenTypeBasic(DestinationType(field.value.type, false));
- auto argname = MakeCamel(field.name, false);
+ auto argname = ConvertCase(field.name, Case::kLowerCamel);
if (!IsScalar(field.value.type.base_type)) argname += "Offset";
code += " " + argname + ") { builder.add";
code += GenMethod(field.value.type) + "(";
@@ -1041,27 +1083,29 @@
auto alignment = InlineAlignment(vector_type);
auto elem_size = InlineSize(vector_type);
if (!IsStruct(vector_type)) {
+ field_has_create_set.insert(&field);
// generate a method to create a vector from a java array.
if ((vector_type.base_type == BASE_TYPE_CHAR ||
vector_type.base_type == BASE_TYPE_UCHAR)) {
// Handle byte[] and ByteBuffers separately for Java
code += " public static " + GenVectorOffsetType() + " ";
code += "create";
- code += MakeCamel(field.name);
+ code += ConvertCase(field.name, Case::kUpperCamel);
code += "Vector(FlatBufferBuilder builder, byte[] data) ";
code += "{ return builder.createByteVector(data); }\n";
code += " public static " + GenVectorOffsetType() + " ";
code += "create";
- code += MakeCamel(field.name);
+ code += ConvertCase(field.name, Case::kUpperCamel);
code += "Vector(FlatBufferBuilder builder, ByteBuffer data) ";
code += "{ return builder.createByteVector(data); }\n";
} else {
code += " public static " + GenVectorOffsetType() + " ";
code += "create";
- code += MakeCamel(field.name);
+ code += ConvertCase(field.name, Case::kUpperCamel);
code += "Vector(FlatBufferBuilder builder, ";
- code += GenTypeBasic(vector_type) + "[] data) ";
+ code += GenTypeBasic(DestinationType(vector_type, false)) +
+ "[] data) ";
code += "{ builder.startVector(";
code += NumToString(elem_size);
code += ", data.length, ";
@@ -1071,7 +1115,7 @@
code += "add";
code += GenMethod(vector_type);
code += "(";
- code += SourceCastBasic(vector_type, false);
+ code += SourceCastBasic(vector_type);
code += "data[i]";
code += "); return ";
code += "builder.endVector(); }\n";
@@ -1080,7 +1124,7 @@
// Generate a method to start a vector, data to be added manually
// after.
code += " public static void start";
- code += MakeCamel(field.name);
+ code += ConvertCase(field.name, Case::kUpperCamel);
code += "Vector(FlatBufferBuilder builder, int numElems) ";
code += "{ builder.startVector(";
code += NumToString(elem_size);
@@ -1095,7 +1139,7 @@
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
- if (!field.deprecated && field.required) {
+ if (!field.deprecated && field.IsRequired()) {
code += " builder.required(o, ";
code += NumToString(field.value.offset);
code += "); // " + field.name + "\n";
@@ -1157,13 +1201,16 @@
code += " }\n";
}
GenVectorAccessObject(struct_def, code_ptr);
- code += "}";
- code += "\n\n";
+ if (opts.generate_object_based_api) {
+ GenPackUnPack_ObjectAPI(struct_def, code_ptr, opts, struct_has_create,
+ field_has_create_set);
+ }
+ code += "}\n\n";
}
std::string GenOptionalScalarCheck(FieldDef &field) const {
if (!field.IsScalarOptional()) return "";
- return " public boolean has" + MakeCamel(field.name, true) +
+ return " public boolean has" + ConvertCase(field.name, Case::kUpperCamel) +
"() { return 0 != __offset(" + NumToString(field.value.offset) +
"); }\n";
}
@@ -1229,6 +1276,867 @@
code += " }\n";
}
+ std::string GenGetterFuncName_ObjectAPI(const std::string &field_name) const {
+ return "get" + ConvertCase(field_name, Case::kUpperCamel);
+ }
+
+ void GenEnum_ObjectAPI(EnumDef &enum_def, std::string *code_ptr,
+ const IDLOptions &opts) const {
+ auto &code = *code_ptr;
+ if (enum_def.generated) return;
+ code += "import com.google.flatbuffers.FlatBufferBuilder;\n\n";
+
+ if (!enum_def.attributes.Lookup("private")) { code += "public "; }
+ auto union_name = enum_def.name + "Union";
+ auto union_type =
+ GenTypeBasic(DestinationType(enum_def.underlying_type, false));
+ code += "class " + union_name + " {\n";
+ // Type
+ code += " private " + union_type + " type;\n";
+ // Value
+ code += " private Object value;\n";
+ code += "\n";
+ // getters and setters
+ code += " public " + union_type + " getType() { return type; }\n\n";
+ code += " public void setType(" + union_type +
+ " type) { this.type = type; }\n\n";
+ code += " public Object getValue() { return value; }\n\n";
+ code += " public void setValue(Object value) { this.value = value; }\n\n";
+ // Constructor
+ code += " public " + union_name + "() {\n";
+ code += " this.type = " + enum_def.name + "." +
+ enum_def.Vals()[0]->name + ";\n";
+ code += " this.value = null;\n";
+ code += " }\n\n";
+ // As
+ for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
+ auto &ev = **it;
+ if (ev.union_type.base_type == BASE_TYPE_NONE) continue;
+ auto type_name = GenTypeGet_ObjectAPI(ev.union_type, opts, false, true);
+ if (ev.union_type.base_type == BASE_TYPE_STRUCT &&
+ ev.union_type.struct_def->attributes.Lookup("private")) {
+ code += " ";
+ } else {
+ code += " public ";
+ }
+ code += type_name + " as" + ev.name + "() { return (" + type_name +
+ ") value; }\n";
+ }
+ code += "\n";
+ // pack()
+ code += " public static int pack(FlatBufferBuilder builder, " +
+ union_name + " _o) {\n";
+ code += " switch (_o.type) {\n";
+ for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
+ auto &ev = **it;
+ if (ev.union_type.base_type == BASE_TYPE_NONE) {
+ continue;
+ } else {
+ code += " case " + enum_def.name + "." + ev.name + ": return ";
+ if (IsString(ev.union_type)) {
+ code += "builder.createString(_o.as" + ev.name + "());\n";
+ } else {
+ code += GenTypeGet(ev.union_type) + ".pack(builder, _o.as" + ev.name +
+ "());\n";
+ }
+ }
+ }
+ code += " default: return 0;\n";
+ code += " }\n";
+ code += " }\n";
+ code += "}\n\n";
+ }
+
+ std::string GenSetterFuncName_ObjectAPI(const std::string &field_name) const {
+ return "set" + ConvertCase(field_name, Case::kUpperCamel);
+ }
+
+ std::string GenTypeName_ObjectAPI(const std::string &name,
+ const IDLOptions &opts) const {
+ return opts.object_prefix + name + opts.object_suffix;
+ }
+
+ void GenUnionUnPack_ObjectAPI(const EnumDef &enum_def, std::string *code_ptr,
+ const std::string &type_name,
+ const std::string &camel_name,
+ bool is_vector) const {
+ auto &code = *code_ptr;
+
+ std::string variable_type = type_name;
+ std::string variable_name =
+ "_o" + ConvertCase(camel_name, Case::kUpperCamel);
+ std::string type_params = "";
+ std::string value_params = "";
+ std::string func_suffix = "()";
+ std::string indent = " ";
+ if (is_vector) {
+ variable_type = type_name.substr(0, type_name.length() - 2);
+ variable_name += "Element";
+ type_params = "_j";
+ value_params = ", _j";
+ func_suffix = "(_j)";
+ indent = " ";
+ }
+ code += indent + variable_type + " " + variable_name + " = new " +
+ variable_type + "();\n";
+ code += indent +
+ GenTypeBasic(DestinationType(enum_def.underlying_type, false)) +
+ " " + variable_name + "Type = " + camel_name + "Type(" +
+ type_params + ");\n";
+ code += indent + variable_name + ".setType(" + variable_name + "Type);\n";
+ code += indent + "Table " + variable_name + "Value;\n";
+ code += indent + "switch (" + variable_name + "Type) {\n";
+ for (auto eit = enum_def.Vals().begin(); eit != enum_def.Vals().end();
+ ++eit) {
+ auto &ev = **eit;
+ if (ev.union_type.base_type == BASE_TYPE_NONE) {
+ continue;
+ } else {
+ if (ev.union_type.base_type == BASE_TYPE_STRING ||
+ (ev.union_type.base_type == BASE_TYPE_STRUCT &&
+ ev.union_type.struct_def->fixed)) {
+ continue; // This branch is due to bad implemantation of Unions in
+ // Java which doesn't handle non Table types. Should be
+ // deleted when issue #6561 is fixed.
+ }
+ code += indent + " case " + WrapInNameSpace(enum_def) + "." + ev.name +
+ ":\n";
+ auto actual_type = GenTypeGet(ev.union_type);
+ code += indent + " " + variable_name + "Value = " + camel_name +
+ "(new " + actual_type + "()" + value_params + ");\n";
+ code += indent + " " + variable_name + ".setValue(" + variable_name +
+ "Value != null ? ((" + actual_type + ") " + variable_name +
+ "Value).unpack() : null);\n";
+ code += indent + " break;\n";
+ }
+ }
+ code += indent + " default: break;\n";
+ code += indent + "}\n";
+ if (is_vector) {
+ code += indent + "_o" + ConvertCase(camel_name, Case::kUpperCamel) +
+ "[_j] = " + variable_name + ";\n";
+ }
+ }
+
+ void GenPackUnPack_ObjectAPI(
+ StructDef &struct_def, std::string *code_ptr, const IDLOptions &opts,
+ bool struct_has_create,
+ const std::set<FieldDef *> &field_has_create) const {
+ auto &code = *code_ptr;
+ auto struct_name = GenTypeName_ObjectAPI(struct_def.name, opts);
+ // unpack()
+ code += " public " + struct_name + " unpack() {\n";
+ code += " " + struct_name + " _o = new " + struct_name + "();\n";
+ code += " unpackTo(_o);\n";
+ code += " return _o;\n";
+ code += " }\n";
+ // unpackTo()
+ code += " public void unpackTo(" + struct_name + " _o) {\n";
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++it) {
+ auto &field = **it;
+ if (field.deprecated) continue;
+ if (field.value.type.base_type == BASE_TYPE_UTYPE) continue;
+ if (field.value.type.element == BASE_TYPE_UTYPE) continue;
+ auto camel_name = ConvertCase(field.name, Case::kLowerCamel);
+ auto camel_name_with_first = ConvertCase(field.name, Case::kUpperCamel);
+ auto type_name =
+ GenTypeGet_ObjectAPI(field.value.type, opts, false, true);
+ if (field.IsScalarOptional())
+ type_name = ConvertPrimitiveTypeToObjectWrapper_ObjectAPI(type_name);
+ auto start = " " + type_name + " _o" + camel_name_with_first + " = ";
+ auto call_setter = true;
+ switch (field.value.type.base_type) {
+ case BASE_TYPE_STRUCT: {
+ auto fixed = struct_def.fixed && field.value.type.struct_def->fixed;
+ if (fixed) {
+ code += " " + camel_name + "().unpackTo(_o.get" +
+ camel_name_with_first + "());\n";
+ } else {
+ code += " if (" + camel_name + "() != null) ";
+ if (field.value.type.struct_def->fixed) {
+ code += camel_name + "().unpackTo(_o.get" +
+ camel_name_with_first + "());\n";
+ } else {
+ code += "_o." + GenSetterFuncName_ObjectAPI(field.name) + "(" +
+ camel_name + "().unpack());\n";
+ }
+ code += " else _o." + GenSetterFuncName_ObjectAPI(field.name) +
+ "(null);\n";
+ }
+ call_setter = false;
+ break;
+ }
+ case BASE_TYPE_ARRAY: {
+ auto length_str = NumToString(field.value.type.fixed_length);
+ auto unpack_method =
+ field.value.type.struct_def == nullptr ? "" : ".unpack()";
+ code +=
+ start + "_o." + GenGetterFuncName_ObjectAPI(field.name) + "();\n";
+ code += " for (int _j = 0; _j < " + length_str + "; ++_j) { _o" +
+ camel_name_with_first + "[_j] = " + camel_name + "(_j)" +
+ unpack_method + "; }\n";
+ call_setter = false;
+ break;
+ }
+ case BASE_TYPE_VECTOR:
+ if (field.value.type.element == BASE_TYPE_UNION) {
+ code += start + "new " +
+ GenConcreteTypeGet_ObjectAPI(field.value.type, opts)
+ .substr(0, type_name.length() - 1) +
+ camel_name + "Length()];\n";
+ code += " for (int _j = 0; _j < " + camel_name +
+ "Length(); ++_j) {\n";
+ GenUnionUnPack_ObjectAPI(*field.value.type.enum_def, code_ptr,
+ type_name, camel_name, true);
+ code += " }\n";
+ } else if (field.value.type.element != BASE_TYPE_UTYPE) {
+ auto fixed = field.value.type.struct_def == nullptr;
+ code += start + "new " +
+ GenConcreteTypeGet_ObjectAPI(field.value.type, opts)
+ .substr(0, type_name.length() - 1) +
+ camel_name + "Length()];\n";
+ code +=
+ " for (int _j = 0; _j < " + camel_name + "Length(); ++_j) {";
+ code += "_o" + camel_name_with_first + "[_j] = ";
+ if (fixed) {
+ code += camel_name + "(_j)";
+ } else {
+ code += "(" + camel_name + "(_j) != null ? " + camel_name +
+ "(_j).unpack() : null)";
+ }
+ code += ";}\n";
+ }
+ break;
+ case BASE_TYPE_UTYPE: break;
+ case BASE_TYPE_UNION: {
+ GenUnionUnPack_ObjectAPI(*field.value.type.enum_def, code_ptr,
+ type_name, camel_name, false);
+ break;
+ }
+ default: {
+ if (field.IsScalarOptional()) {
+ code += start + "has" + camel_name_with_first + "() ? " +
+ camel_name + "() : null;\n";
+ } else {
+ code += start + camel_name + "();\n";
+ }
+ break;
+ }
+ }
+ if (call_setter) {
+ code += " _o." + GenSetterFuncName_ObjectAPI(field.name) + "(_o" +
+ camel_name_with_first + ");\n";
+ }
+ }
+ code += " }\n";
+ // pack()
+ code += " public static " + GenOffsetType() +
+ " pack(FlatBufferBuilder builder, " + struct_name + " _o) {\n";
+ code += " if (_o == null) return 0;\n";
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++it) {
+ auto &field = **it;
+ if (field.deprecated) continue;
+ auto camel_name = ConvertCase(field.name, Case::kLowerCamel);
+ auto camel_name_with_first = ConvertCase(field.name, Case::kUpperCamel);
+ // pre
+ switch (field.value.type.base_type) {
+ case BASE_TYPE_STRUCT: {
+ if (!field.value.type.struct_def->fixed) {
+ code += " " + GenOffsetType() + " _" + field.name + " = _o." +
+ GenGetterFuncName_ObjectAPI(field.name) +
+ "() == null ? 0 : " + GenTypeGet(field.value.type) +
+ ".pack(builder, _o." +
+ GenGetterFuncName_ObjectAPI(field.name) + "());\n";
+ } else if (struct_def.fixed && struct_has_create) {
+ std::vector<FieldArrayLength> array_lengths;
+ FieldArrayLength tmp_array_length = {
+ field.name,
+ field.value.type.fixed_length,
+ };
+ array_lengths.push_back(tmp_array_length);
+ GenStructPackDecl_ObjectAPI(*field.value.type.struct_def, code_ptr,
+ array_lengths);
+ }
+ break;
+ }
+ case BASE_TYPE_STRING: {
+ std::string create_string = "createString";
+ code += " int _" + camel_name + " = _o." +
+ GenGetterFuncName_ObjectAPI(field.name) +
+ "() == null ? 0 : "
+ "builder." +
+ create_string + "(_o." +
+ GenGetterFuncName_ObjectAPI(field.name) + "());\n";
+ break;
+ }
+ case BASE_TYPE_VECTOR: {
+ if (field_has_create.find(&field) != field_has_create.end()) {
+ auto property_name = camel_name;
+ auto gen_for_loop = true;
+ std::string array_name = "__" + camel_name;
+ std::string array_type = "";
+ std::string element_type = "";
+ std::string to_array = "";
+ switch (field.value.type.element) {
+ case BASE_TYPE_STRING: {
+ std::string create_string = "createString";
+ array_type = "int";
+ element_type = "String";
+ to_array += "builder." + create_string + "(_e)";
+ break;
+ }
+ case BASE_TYPE_STRUCT:
+ array_type = "int";
+ element_type =
+ GenTypeGet_ObjectAPI(field.value.type, opts, true, true);
+ ;
+ to_array = GenTypeGet(field.value.type) + ".pack(builder, _e)";
+ break;
+ case BASE_TYPE_UTYPE:
+ property_name = camel_name.substr(0, camel_name.size() - 4);
+ array_type = GenTypeBasic(DestinationType(
+ field.value.type.enum_def->underlying_type, false));
+ element_type = field.value.type.enum_def->name + "Union";
+ to_array = "_o." + GenGetterFuncName_ObjectAPI(property_name) +
+ "()[_j].getType()";
+ break;
+ case BASE_TYPE_UNION:
+ array_type = "int";
+ element_type =
+ WrapInNameSpace(*field.value.type.enum_def) + "Union";
+ to_array = WrapInNameSpace(*field.value.type.enum_def) +
+ "Union.pack(builder, _o." +
+ GenGetterFuncName_ObjectAPI(property_name) +
+ "()[_j])";
+ break;
+ case BASE_TYPE_UCHAR: // TODO this branch of the switch is due to
+ // inconsistent behavior in unsigned byte.
+ // Read further at Issue #6574.
+ array_type = "byte";
+ element_type = "int";
+ to_array = "(byte) _e";
+ break;
+ default:
+ gen_for_loop = false;
+ array_name =
+ "_o." + GenGetterFuncName_ObjectAPI(property_name) + "()";
+ array_type = GenTypeNameDest(field.value.type);
+ element_type = array_type;
+ to_array = "_e";
+ break;
+ }
+ code += " int _" + camel_name + " = 0;\n";
+ code += " if (_o." + GenGetterFuncName_ObjectAPI(property_name) +
+ "() != null) {\n";
+ if (gen_for_loop) {
+ code += " " + array_type + "[] " + array_name + " = new " +
+ array_type + "[_o." +
+ GenGetterFuncName_ObjectAPI(property_name) +
+ "().length];\n";
+ code += " int _j = 0;\n";
+ code += " for (" + element_type + " _e : _o." +
+ GenGetterFuncName_ObjectAPI(property_name) + "()) { ";
+ code += array_name + "[_j] = " + to_array + "; _j++;}\n";
+ }
+ code += " _" + camel_name + " = create" +
+ camel_name_with_first + "Vector(builder, " + array_name +
+ ");\n";
+ code += " }\n";
+ } else {
+ auto type_name = GenTypeGet(field.value.type);
+ auto element_type_name =
+ GenTypeGet_ObjectAPI(field.value.type, opts, true, true);
+ auto pack_method =
+ field.value.type.struct_def == nullptr
+ ? "builder.add" + GenMethod(field.value.type.VectorType()) +
+ "(_o" + camel_name_with_first + "[_j]);"
+ : type_name + ".pack(builder, _o" + camel_name_with_first +
+ "[_j]);";
+ code += " int _" + camel_name + " = 0;\n";
+ code += " " + element_type_name + "[] _o" +
+ camel_name_with_first + " = _o." +
+ GenGetterFuncName_ObjectAPI(field.name) + "();\n";
+ code += " if (_o" + camel_name_with_first + " != null) {\n";
+ code += " start" + camel_name_with_first +
+ "Vector(builder, _o" + camel_name_with_first +
+ ".length);\n";
+ code += " for (int _j = _o" + camel_name_with_first +
+ ".length - 1; _j >=0; _j--) { ";
+ code += pack_method + "}\n";
+ code += " _" + camel_name + " = builder.endVector();\n";
+ code += " }\n";
+ }
+ break;
+ }
+ case BASE_TYPE_ARRAY: {
+ if (field.value.type.struct_def != nullptr) {
+ std::vector<FieldArrayLength> array_lengths;
+ FieldArrayLength tmp_array_length = {
+ field.name,
+ field.value.type.fixed_length,
+ };
+ array_lengths.push_back(tmp_array_length);
+ GenStructPackDecl_ObjectAPI(*field.value.type.struct_def, code_ptr,
+ array_lengths);
+ } else {
+ code += " " +
+ GenTypeGet_ObjectAPI(field.value.type, opts, false, true) +
+ " _" + camel_name + " = _o." +
+ GenGetterFuncName_ObjectAPI(field.name) + "();\n";
+ }
+ break;
+ }
+ case BASE_TYPE_UNION: {
+ code +=
+ " " +
+ GenTypeBasic(DestinationType(
+ field.value.type.enum_def->underlying_type, false)) +
+ " _" + camel_name + "Type = _o.get" + camel_name_with_first +
+ "() == null ? " + WrapInNameSpace(*field.value.type.enum_def) +
+ ".NONE : " + "_o.get" + camel_name_with_first + "().getType();\n";
+ code += " " + GenOffsetType() + " _" + camel_name + " = _o.get" +
+ camel_name_with_first + "() == null ? 0 : " +
+ WrapInNameSpace(*field.value.type.enum_def) +
+ "Union.pack(builder, _o.get" + camel_name_with_first +
+ "());\n";
+ break;
+ }
+ default: break;
+ }
+ }
+ if (struct_has_create) {
+ // Create
+ code += " return create" + struct_def.name + "(\n";
+ code += " builder";
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++it) {
+ auto &field = **it;
+ if (field.deprecated) continue;
+ auto camel_name = ConvertCase(field.name, Case::kLowerCamel);
+ switch (field.value.type.base_type) {
+ case BASE_TYPE_STRUCT: {
+ if (struct_def.fixed) {
+ GenStructPackCall_ObjectAPI(*field.value.type.struct_def,
+ code_ptr,
+ " _" + camel_name + "_");
+ } else {
+ code += ",\n";
+ if (field.value.type.struct_def->fixed) {
+ if (opts.generate_object_based_api)
+ code += " _o." + camel_name;
+ else
+ // Seems like unreachable code
+ code += " " + GenTypeGet(field.value.type) +
+ ".Pack(builder, _o." + camel_name + ")";
+ } else {
+ code += " _" + field.name;
+ }
+ }
+ break;
+ }
+ case BASE_TYPE_ARRAY: {
+ if (field.value.type.struct_def != nullptr) {
+ GenStructPackCall_ObjectAPI(*field.value.type.struct_def,
+ code_ptr,
+ " _" + camel_name + "_");
+ } else {
+ code += ",\n";
+ code += " _" + camel_name;
+ }
+ break;
+ }
+ case BASE_TYPE_UNION: FLATBUFFERS_FALLTHROUGH(); // fall thru
+ case BASE_TYPE_UTYPE: FLATBUFFERS_FALLTHROUGH(); // fall thru
+ case BASE_TYPE_STRING: FLATBUFFERS_FALLTHROUGH(); // fall thru
+ case BASE_TYPE_VECTOR: {
+ code += ",\n";
+ code += " _" + camel_name;
+ break;
+ }
+ default: // scalar
+ code += ",\n";
+ code +=
+ " _o." + GenGetterFuncName_ObjectAPI(field.name) + "()";
+ break;
+ }
+ }
+ code += ");\n";
+ } else {
+ // Start, End
+ code += " start" + struct_def.name + "(builder);\n";
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++it) {
+ auto &field = **it;
+ if (field.deprecated) continue;
+ auto camel_name = ConvertCase(field.name, Case::kLowerCamel);
+ auto camel_name_with_first = ConvertCase(field.name, Case::kUpperCamel);
+ switch (field.value.type.base_type) {
+ case BASE_TYPE_STRUCT: {
+ if (field.value.type.struct_def->fixed) {
+ code += " add" + camel_name_with_first + "(builder, " +
+ GenTypeGet(field.value.type) + ".pack(builder, _o." +
+ GenGetterFuncName_ObjectAPI(field.name) + "()));\n";
+ } else {
+ code += " add" + camel_name_with_first + "(builder, _" +
+ field.name + ");\n";
+ }
+ break;
+ }
+ case BASE_TYPE_STRING: FLATBUFFERS_FALLTHROUGH(); // fall thru
+ case BASE_TYPE_ARRAY: FLATBUFFERS_FALLTHROUGH(); // fall thru
+ case BASE_TYPE_VECTOR: {
+ code += " add" + camel_name_with_first + "(builder, _" +
+ camel_name + ");\n";
+ break;
+ }
+ case BASE_TYPE_UTYPE: break;
+ case BASE_TYPE_UNION: {
+ code += " add" + camel_name_with_first + "Type(builder, _" +
+ camel_name + "Type);\n";
+ code += " add" + camel_name_with_first + "(builder, _" +
+ camel_name + ");\n";
+ break;
+ }
+ // scalar
+ default: {
+ if (field.IsScalarOptional()) {
+ code += " if (_o." + GenGetterFuncName_ObjectAPI(field.name) +
+ "() != null) { add" + camel_name_with_first +
+ "(builder, _o." +
+ GenGetterFuncName_ObjectAPI(field.name) + "()); }\n";
+ } else {
+ code += " add" + camel_name_with_first + "(builder, _o." +
+ GenGetterFuncName_ObjectAPI(field.name) + "());\n";
+ }
+ break;
+ }
+ }
+ }
+ code += " return end" + struct_def.name + "(builder);\n";
+ }
+ code += " }\n";
+ }
+
+ void GenStructPackDecl_ObjectAPI(
+ const StructDef &struct_def, std::string *code_ptr,
+ std::vector<FieldArrayLength> &array_lengths) const {
+ auto &code = *code_ptr;
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++it) {
+ auto &field = **it;
+ auto is_array = IsArray(field.value.type);
+ const auto &field_type =
+ is_array ? field.value.type.VectorType() : field.value.type;
+ FieldArrayLength tmp_array_length = {
+ field.name,
+ field_type.fixed_length,
+ };
+ array_lengths.push_back(tmp_array_length);
+ if (field_type.struct_def != nullptr) {
+ GenStructPackDecl_ObjectAPI(*field_type.struct_def, code_ptr,
+ array_lengths);
+ } else {
+ std::vector<FieldArrayLength> array_only_lengths;
+ for (size_t i = 0; i < array_lengths.size(); ++i) {
+ if (array_lengths[i].length > 0) {
+ array_only_lengths.push_back(array_lengths[i]);
+ }
+ }
+ std::string name;
+ for (size_t i = 0; i < array_lengths.size(); ++i) {
+ name += "_" + ConvertCase(array_lengths[i].name, Case::kLowerCamel);
+ }
+ code += " " + GenTypeBasic(field_type);
+ if (array_only_lengths.size() > 0) {
+ for (size_t i = 0; i < array_only_lengths.size(); ++i) {
+ code += "[]";
+ }
+ code += " " + name + " = ";
+ code += "new " + GenTypeBasic(field_type) + "[";
+ for (size_t i = 0; i < array_only_lengths.size(); ++i) {
+ if (i != 0) { code += "]["; }
+ code += NumToString(array_only_lengths[i].length);
+ }
+ code += "];\n";
+ code += " ";
+ // initialize array
+ for (size_t i = 0; i < array_only_lengths.size(); ++i) {
+ auto idx = "idx" + NumToString(i);
+ code += "for (int " + idx + " = 0; " + idx + " < " +
+ NumToString(array_only_lengths[i].length) + "; ++" + idx +
+ ") {";
+ }
+ for (size_t i = 0; i < array_only_lengths.size(); ++i) {
+ auto idx = "idx" + NumToString(i);
+ if (i == 0) {
+ code += name + "[" + idx;
+ } else {
+ code += "][" + idx;
+ }
+ }
+ code += "] = _o";
+ for (size_t i = 0, j = 0; i < array_lengths.size(); ++i) {
+ code +=
+ "." + GenGetterFuncName_ObjectAPI(array_lengths[i].name) + "()";
+ if (array_lengths[i].length <= 0) continue;
+ code += "[idx" + NumToString(j++) + "]";
+ }
+ code += ";";
+ for (size_t i = 0; i < array_only_lengths.size(); ++i) {
+ code += "}";
+ }
+ } else {
+ code += " " + name + " = ";
+ code += "_o";
+ for (size_t i = 0; i < array_lengths.size(); ++i) {
+ code +=
+ "." + GenGetterFuncName_ObjectAPI(array_lengths[i].name) + "()";
+ }
+ code += ";";
+ }
+ code += "\n";
+ }
+ array_lengths.pop_back();
+ }
+ }
+
+ void GenStructPackCall_ObjectAPI(const StructDef &struct_def,
+ std::string *code_ptr,
+ std::string prefix) const {
+ auto &code = *code_ptr;
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++it) {
+ auto &field = **it;
+ const auto &field_type = field.value.type;
+ if (field_type.struct_def != nullptr) {
+ GenStructPackCall_ObjectAPI(
+ *field_type.struct_def, code_ptr,
+ prefix + ConvertCase(field.name, Case::kLowerCamel) + "_");
+ } else {
+ code += ",\n";
+ code += prefix + ConvertCase(field.name, Case::kLowerCamel);
+ }
+ }
+ }
+
+ std::string ConvertPrimitiveTypeToObjectWrapper_ObjectAPI(
+ std::string type_name) const {
+ if (type_name == "boolean")
+ return "Boolean";
+ else if (type_name == "byte")
+ return "Byte";
+ else if (type_name == "char")
+ return "Character";
+ else if (type_name == "short")
+ return "Short";
+ else if (type_name == "int")
+ return "Integer";
+ else if (type_name == "long")
+ return "Long";
+ else if (type_name == "float")
+ return "Float";
+ else if (type_name == "double")
+ return "Double";
+ return type_name;
+ }
+
+ std::string GenTypeGet_ObjectAPI(flatbuffers::Type type,
+ const IDLOptions &opts, bool vectorelem,
+ bool wrap_in_namespace) const {
+ auto type_name = GenTypeNameDest(type);
+ // Replace to ObjectBaseAPI Type Name
+ switch (type.base_type) {
+ case BASE_TYPE_STRUCT: FLATBUFFERS_FALLTHROUGH(); // fall thru
+ case BASE_TYPE_ARRAY: FLATBUFFERS_FALLTHROUGH(); // fall thru
+ case BASE_TYPE_VECTOR: {
+ if (type.struct_def != nullptr) {
+ auto type_name_length = type.struct_def->name.length();
+ auto new_type_name =
+ GenTypeName_ObjectAPI(type.struct_def->name, opts);
+ type_name.replace(type_name.length() - type_name_length,
+ type_name_length, new_type_name);
+ } else if (type.element == BASE_TYPE_UNION) {
+ if (wrap_in_namespace) {
+ type_name = WrapInNameSpace(*type.enum_def) + "Union";
+ } else {
+ type_name = type.enum_def->name + "Union";
+ }
+ }
+ break;
+ }
+
+ case BASE_TYPE_UNION: {
+ if (wrap_in_namespace) {
+ type_name = WrapInNameSpace(*type.enum_def) + "Union";
+ } else {
+ type_name = type.enum_def->name + "Union";
+ }
+ break;
+ }
+ default: break;
+ }
+ if (vectorelem) { return type_name; }
+ switch (type.base_type) {
+ case BASE_TYPE_ARRAY: FLATBUFFERS_FALLTHROUGH(); // fall thru
+ case BASE_TYPE_VECTOR: {
+ type_name = type_name + "[]";
+ break;
+ }
+ default: break;
+ }
+ return type_name;
+ }
+
+ std::string GenConcreteTypeGet_ObjectAPI(flatbuffers::Type type,
+ const IDLOptions &opts) const {
+ auto type_name = GenTypeNameDest(type);
+ // Replace to ObjectBaseAPI Type Name
+ switch (type.base_type) {
+ case BASE_TYPE_STRUCT: FLATBUFFERS_FALLTHROUGH(); // fall thru
+ case BASE_TYPE_ARRAY: FLATBUFFERS_FALLTHROUGH(); // fall thru
+ case BASE_TYPE_VECTOR: {
+ if (type.struct_def != nullptr) {
+ auto type_name_length = type.struct_def->name.length();
+ auto new_type_name =
+ GenTypeName_ObjectAPI(type.struct_def->name, opts);
+ type_name.replace(type_name.length() - type_name_length,
+ type_name_length, new_type_name);
+ } else if (type.element == BASE_TYPE_UNION) {
+ type_name = WrapInNameSpace(*type.enum_def) + "Union";
+ }
+ break;
+ }
+
+ case BASE_TYPE_UNION: {
+ type_name = WrapInNameSpace(*type.enum_def) + "Union";
+ break;
+ }
+ default: break;
+ }
+
+ switch (type.base_type) {
+ case BASE_TYPE_ARRAY: FLATBUFFERS_FALLTHROUGH(); // fall thru
+ case BASE_TYPE_VECTOR: {
+ type_name = type_name + "[]";
+ break;
+ }
+ default: break;
+ }
+ return type_name;
+ }
+
+ void GenStruct_ObjectAPI(StructDef &struct_def, std::string *code_ptr,
+ const IDLOptions &opts) const {
+ if (struct_def.generated) return;
+ auto &code = *code_ptr;
+ if (struct_def.attributes.Lookup("private")) {
+ // For Java, we leave the enum unmarked to indicate package-private
+ } else {
+ code += "public ";
+ }
+
+ auto class_name = GenTypeName_ObjectAPI(struct_def.name, opts);
+ code += "class " + class_name;
+ code += " {\n";
+ // Generate Properties
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++it) {
+ auto &field = **it;
+ if (field.deprecated) continue;
+ if (field.value.type.base_type == BASE_TYPE_UTYPE) continue;
+ if (field.value.type.element == BASE_TYPE_UTYPE) continue;
+ auto type_name =
+ GenTypeGet_ObjectAPI(field.value.type, opts, false, true);
+ if (field.IsScalarOptional())
+ type_name = ConvertPrimitiveTypeToObjectWrapper_ObjectAPI(type_name);
+ auto camel_name = ConvertCase(field.name, Case::kLowerCamel);
+ code += " private " + type_name + " " + camel_name + ";\n";
+ }
+ // Generate Java getters and setters
+ code += "\n";
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++it) {
+ auto &field = **it;
+ if (field.deprecated) continue;
+ if (field.value.type.base_type == BASE_TYPE_UTYPE) continue;
+ if (field.value.type.element == BASE_TYPE_UTYPE) continue;
+ auto type_name =
+ GenTypeGet_ObjectAPI(field.value.type, opts, false, true);
+ if (field.IsScalarOptional())
+ type_name = ConvertPrimitiveTypeToObjectWrapper_ObjectAPI(type_name);
+ auto camel_name = ConvertCase(field.name, Case::kLowerCamel);
+ code += " public " + type_name + " " +
+ GenGetterFuncName_ObjectAPI(field.name) + "() { return " +
+ camel_name + "; }\n\n";
+ std::string array_validation = "";
+ if (field.value.type.base_type == BASE_TYPE_ARRAY) {
+ array_validation =
+ "if (" + camel_name + " != null && " + camel_name +
+ ".length == " + NumToString(field.value.type.fixed_length) + ") ";
+ }
+ code += " public void " + GenSetterFuncName_ObjectAPI(field.name) + "(" +
+ type_name + " " + camel_name + ") { " + array_validation +
+ "this." + camel_name + " = " + camel_name + "; }\n\n";
+ }
+ // Generate Constructor
+ code += "\n";
+ code += " public " + class_name + "() {\n";
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++it) {
+ auto &field = **it;
+ if (field.deprecated) continue;
+ if (field.value.type.base_type == BASE_TYPE_UTYPE) continue;
+ if (field.value.type.element == BASE_TYPE_UTYPE) continue;
+ code += " this." + ConvertCase(field.name, Case::kLowerCamel) + " = ";
+ auto type_name =
+ GenTypeGet_ObjectAPI(field.value.type, opts, false, true);
+ if (IsScalar(field.value.type.base_type)) {
+ if (field.IsScalarOptional()) {
+ code += "null;\n";
+ } else {
+ code += GenDefaultValue(field) + ";\n";
+ }
+ } else {
+ switch (field.value.type.base_type) {
+ case BASE_TYPE_STRUCT: {
+ if (IsStruct(field.value.type)) {
+ code += "new " + type_name + "();\n";
+ } else {
+ code += "null;\n";
+ }
+ break;
+ }
+ case BASE_TYPE_ARRAY: {
+ code += "new " + type_name.substr(0, type_name.length() - 1) +
+ NumToString(field.value.type.fixed_length) + "];\n";
+ break;
+ }
+ default: {
+ code += "null;\n";
+ break;
+ }
+ }
+ }
+ }
+ code += " }\n";
+ if (parser_.root_struct_def_ == &struct_def) {
+ code += " public static " + class_name +
+ " deserializeFromBinary(byte[] fbBuffer) {\n";
+ code += " return " + struct_def.name + ".getRootAs" + struct_def.name +
+ "(ByteBuffer.wrap(fbBuffer)).unpack();\n";
+ code += " }\n";
+ code += " public byte[] serializeToBinary() {\n";
+ code += " FlatBufferBuilder fbb = new FlatBufferBuilder();\n";
+ code += " " + struct_def.name + ".finish" + struct_def.name +
+ "Buffer(fbb, " + struct_def.name + ".pack(fbb, this));\n";
+ code += " return fbb.sizedByteArray();\n";
+ code += " }\n";
+ }
+ code += "}\n\n";
+ }
+
// This tracks the current namespace used to determine if a type need to be
// prefixed by its namespace
const Namespace *cur_name_space_;
diff --git a/src/idl_gen_js_ts.cpp b/src/idl_gen_js_ts.cpp
deleted file mode 100644
index 0240f51..0000000
--- a/src/idl_gen_js_ts.cpp
+++ /dev/null
@@ -1,2171 +0,0 @@
-/*
- * Copyright 2014 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.
- */
-
-// independent from idl_parser, since this code is not needed for most clients
-#include <algorithm>
-#include <cassert>
-#include <unordered_map>
-#include <unordered_set>
-
-#include "flatbuffers/code_generators.h"
-#include "flatbuffers/flatbuffers.h"
-#include "flatbuffers/idl.h"
-#include "flatbuffers/util.h"
-
-namespace flatbuffers {
-
-struct JsTsLanguageParameters {
- IDLOptions::Language language;
- std::string file_extension;
-};
-
-struct ReexportDescription {
- std::string symbol;
- std::string source_namespace;
- std::string target_namespace;
-};
-
-enum AnnotationType { kParam = 0, kType = 1, kReturns = 2 };
-
-const JsTsLanguageParameters &GetJsLangParams(IDLOptions::Language lang) {
- static JsTsLanguageParameters js_language_parameters[] = {
- {
- IDLOptions::kJs,
- ".js",
- },
- {
- IDLOptions::kTs,
- ".ts",
- },
- };
-
- if (lang == IDLOptions::kJs) {
- return js_language_parameters[0];
- } else {
- FLATBUFFERS_ASSERT(lang == IDLOptions::kTs);
- return js_language_parameters[1];
- }
-}
-
-namespace jsts {
-// Iterate through all definitions we haven't generate code for (enums, structs,
-// and tables) and output them to a single file.
-class JsTsGenerator : public BaseGenerator {
- public:
- typedef std::unordered_set<std::string> imported_fileset;
- typedef std::unordered_multimap<std::string, ReexportDescription>
- reexport_map;
-
- JsTsGenerator(const Parser &parser, const std::string &path,
- const std::string &file_name)
- : BaseGenerator(parser, path, file_name, "", ".",
- parser.opts.lang == IDLOptions::kJs ? "js" : "ts"),
- lang_(GetJsLangParams(parser_.opts.lang)) {}
- // Iterate through all definitions we haven't generate code for (enums,
- // structs, and tables) and output them to a single file.
- bool generate() {
- imported_fileset imported_files;
- reexport_map reexports;
-
- std::string enum_code, struct_code, import_code, exports_code, code;
- generateEnums(&enum_code, &exports_code, reexports, imported_files);
- generateStructs(&struct_code, &exports_code, imported_files);
- generateImportDependencies(&import_code, imported_files);
- generateReexports(&import_code, reexports, imported_files);
-
- code = code + "// " + FlatBuffersGeneratedWarning() + "\n\n";
-
- // Generate code for all the namespace declarations.
- GenNamespaces(&code, &exports_code);
-
- // Output the main declaration code from above.
- code += import_code;
-
- code += enum_code;
- code += struct_code;
-
- if (lang_.language == IDLOptions::kJs && !exports_code.empty() &&
- !parser_.opts.skip_js_exports) {
- if (parser_.opts.use_ES6_js_export_format)
- code += "// Exports for ECMAScript6 Modules\n";
- else
- code += "// Exports for Node.js and RequireJS\n";
- code += exports_code;
- }
-
- return SaveFile(GeneratedFileName(path_, file_name_, parser_.opts).c_str(),
- code, false);
- }
-
- private:
- JsTsLanguageParameters lang_;
-
- // Generate code for imports
- void generateImportDependencies(std::string *code_ptr,
- const imported_fileset &imported_files) {
- std::string &code = *code_ptr;
- for (auto it = imported_files.begin(); it != imported_files.end(); ++it) {
- const auto &file = *it;
- const auto basename =
- flatbuffers::StripPath(flatbuffers::StripExtension(file));
- if (basename != file_name_) { code += GenPrefixedImport(file, basename); }
- }
- }
-
- // Generate reexports, which might not have been explicitly imported using the
- // "export import" trick
- void generateReexports(std::string *code_ptr, const reexport_map &reexports,
- imported_fileset imported_files) {
- if (!parser_.opts.reexport_ts_modules ||
- lang_.language != IDLOptions::kTs) {
- return;
- }
-
- std::unordered_set<std::string> imported;
-
- std::string &code = *code_ptr;
- for (auto it = reexports.begin(); it != reexports.end(); ++it) {
- const auto &file = *it;
- const auto basename =
- flatbuffers::StripPath(flatbuffers::StripExtension(file.first));
- if (basename != file_name_ &&
- imported.find(file.second.symbol) == imported.end()) {
- if (imported_files.find(file.first) == imported_files.end()) {
- code += GenPrefixedImport(file.first, basename);
- imported_files.emplace(file.first);
- }
-
- if (!file.second.target_namespace.empty()) {
- code += "export namespace " + file.second.target_namespace + " { \n";
- }
- code += "export import " + file.second.symbol + " = ";
- code += GenFileNamespacePrefix(file.first) + ".";
- if (!file.second.source_namespace.empty()) {
- code += file.second.source_namespace + ".";
- }
- code += file.second.symbol + ";\n";
- if (!file.second.target_namespace.empty()) { code += "}\n"; }
-
- imported.emplace(file.second.symbol);
- }
- }
- }
-
- // Generate code for all enums.
- void generateEnums(std::string *enum_code_ptr, std::string *exports_code_ptr,
- reexport_map &reexports,
- imported_fileset &imported_files) {
- for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end();
- ++it) {
- auto &enum_def = **it;
- GenEnum(enum_def, enum_code_ptr, exports_code_ptr, reexports,
- imported_files, false);
- GenEnum(enum_def, enum_code_ptr, exports_code_ptr, reexports,
- imported_files, true);
- }
- }
-
- // Generate code for all structs.
- void generateStructs(std::string *decl_code_ptr,
- std::string *exports_code_ptr,
- imported_fileset &imported_files) {
- for (auto it = parser_.structs_.vec.begin();
- it != parser_.structs_.vec.end(); ++it) {
- auto &struct_def = **it;
- GenStruct(parser_, struct_def, decl_code_ptr, exports_code_ptr,
- imported_files);
- }
- }
- void GenNamespaces(std::string *code_ptr, std::string *exports_ptr) {
- if (lang_.language == IDLOptions::kTs &&
- parser_.opts.skip_flatbuffers_import) {
- return;
- }
-
- std::set<std::string> namespaces;
-
- for (auto it = parser_.namespaces_.begin(); it != parser_.namespaces_.end();
- ++it) {
- std::string namespace_so_far;
-
- // Gather all parent namespaces for this namespace
- for (auto component = (*it)->components.begin();
- component != (*it)->components.end(); ++component) {
- if (!namespace_so_far.empty()) { namespace_so_far += '.'; }
- namespace_so_far += *component;
- namespaces.insert(namespace_so_far);
- }
- }
-
- // Make sure parent namespaces come before child namespaces
- std::vector<std::string> sorted_namespaces(namespaces.begin(),
- namespaces.end());
- std::sort(sorted_namespaces.begin(), sorted_namespaces.end());
-
- // Emit namespaces in a form that Closure Compiler can optimize
- std::string &code = *code_ptr;
- std::string &exports = *exports_ptr;
-
- if (lang_.language == IDLOptions::kTs) {
- code += "import * as flatbuffers from 'flatbuffers';\n";
- }
-
- for (auto it = sorted_namespaces.begin(); it != sorted_namespaces.end();
- ++it) {
- if (lang_.language == IDLOptions::kTs) {
- if (it->find('.') == std::string::npos) { break; }
- } else {
- code += "/**\n * @const\n * @namespace\n */\n";
- if (it->find('.') == std::string::npos) {
- code += "var ";
- if (parser_.opts.use_goog_js_export_format) {
- exports += "goog.exportSymbol('" + *it + "', " + *it + ");\n";
- } else if (parser_.opts.use_ES6_js_export_format) {
- exports += "export {" + *it + "};\n";
- } else {
- exports += "this." + *it + " = " + *it + ";\n";
- }
- }
- code += *it + " = " + *it + " || {};\n\n";
- }
- }
- }
-
- // Generate a documentation comment, if available.
- static void GenDocComment(const std::vector<std::string> &dc,
- std::string *code_ptr,
- const std::string &extra_lines,
- const char *indent = nullptr) {
- if (dc.empty() && extra_lines.empty()) {
- // Don't output empty comment blocks with 0 lines of comment content.
- return;
- }
-
- std::string &code = *code_ptr;
- if (indent) code += indent;
- code += "/**\n";
- for (auto it = dc.begin(); it != dc.end(); ++it) {
- if (indent) code += indent;
- code += " *" + *it + "\n";
- }
- if (!extra_lines.empty()) {
- if (!dc.empty()) {
- if (indent) code += indent;
- code += " *\n";
- }
- if (indent) code += indent;
- std::string::size_type start = 0;
- for (;;) {
- auto end = extra_lines.find('\n', start);
- if (end != std::string::npos) {
- code += " * " + extra_lines.substr(start, end - start) + "\n";
- start = end + 1;
- } else {
- code += " * " + extra_lines.substr(start) + "\n";
- break;
- }
- }
- }
- if (indent) code += indent;
- code += " */\n";
- }
-
- static void GenDocComment(std::string *code_ptr,
- const std::string &extra_lines) {
- GenDocComment(std::vector<std::string>(), code_ptr, extra_lines);
- }
-
- std::string GenTypeAnnotation(AnnotationType annotation_type,
- const std::string &type_name,
- const std::string &arg_name,
- bool include_newline = true) {
- std::string result = "";
- switch (annotation_type) {
- case kParam: {
- result += "@param";
- break;
- }
- case kType: {
- if (lang_.language != IDLOptions::kTs) {
- result += "@type";
- } else {
- return "";
- }
- break;
- }
- case kReturns: {
- result += "@returns";
- break;
- }
- }
- switch (lang_.language) {
- case IDLOptions::kTs: {
- result += " " + type_name;
- break;
- }
- default: {
- result += " {" + type_name + "}";
- }
- }
- if (!arg_name.empty()) { result += " " + arg_name; }
- if (include_newline) { result += "\n"; }
-
- return result;
- }
-
- // Generate an enum declaration and an enum string lookup table.
- void GenEnum(EnumDef &enum_def, std::string *code_ptr,
- std::string *exports_ptr, reexport_map &reexports,
- imported_fileset &imported_files, bool reverse) {
- if (enum_def.generated) return;
- if (reverse && lang_.language == IDLOptions::kTs) return; // FIXME.
- std::string &code = *code_ptr;
- std::string &exports = *exports_ptr;
- GenDocComment(enum_def.doc_comment, code_ptr,
- reverse ? "@enum {string}" : "@enum {number}");
- std::string ns = GetNameSpace(enum_def);
- std::string enum_def_name = enum_def.name + (reverse ? "Name" : "");
- if (lang_.language == IDLOptions::kTs) {
- if (!ns.empty()) { code += "export namespace " + ns + "{\n"; }
- code += "export enum " + enum_def.name + "{\n";
- } else {
- if (enum_def.defined_namespace->components.empty()) {
- code += "var ";
- if (parser_.opts.use_goog_js_export_format) {
- exports += "goog.exportSymbol('" + enum_def_name + "', " +
- enum_def.name + ");\n";
- } else if (parser_.opts.use_ES6_js_export_format) {
- exports += "export {" + enum_def_name + "};\n";
- } else {
- exports += "this." + enum_def_name + " = " + enum_def_name + ";\n";
- }
- }
- code += WrapInNameSpace(enum_def) + (reverse ? "Name" : "") + " = {\n";
- }
- for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
- auto &ev = **it;
- if (!ev.doc_comment.empty()) {
- if (it != enum_def.Vals().begin()) { code += '\n'; }
- GenDocComment(ev.doc_comment, code_ptr, "", " ");
- }
-
- // Generate mapping between EnumName: EnumValue(int)
- if (reverse) {
- code += " '" + enum_def.ToString(ev) + "'";
- code += lang_.language == IDLOptions::kTs ? "= " : ": ";
- code += "'" + ev.name + "'";
- } else {
- code += " " + ev.name;
- code += lang_.language == IDLOptions::kTs ? "= " : ": ";
- code += enum_def.ToString(ev);
- }
-
- code += (it + 1) != enum_def.Vals().end() ? ",\n" : "\n";
-
- if (ev.union_type.struct_def) {
- ReexportDescription desc = { ev.union_type.struct_def->name,
- GetNameSpace(*ev.union_type.struct_def),
- GetNameSpace(enum_def) };
- reexports.insert(
- std::make_pair(ev.union_type.struct_def->file, std::move(desc)));
- }
- }
- code += "};";
-
- if (lang_.language == IDLOptions::kTs) {
- if (enum_def.is_union) {
- code += GenUnionConvFunc(enum_def.underlying_type, imported_files);
- }
- if (!ns.empty()) { code += "\n}"; }
- }
-
- code += "\n\n";
- }
-
- static std::string GenType(const Type &type) {
- switch (type.base_type) {
- case BASE_TYPE_BOOL:
- case BASE_TYPE_CHAR: return "Int8";
- case BASE_TYPE_UTYPE:
- case BASE_TYPE_UCHAR: return "Uint8";
- case BASE_TYPE_SHORT: return "Int16";
- case BASE_TYPE_USHORT: return "Uint16";
- case BASE_TYPE_INT: return "Int32";
- case BASE_TYPE_UINT: return "Uint32";
- case BASE_TYPE_LONG: return "Int64";
- case BASE_TYPE_ULONG: return "Uint64";
- case BASE_TYPE_FLOAT: return "Float32";
- case BASE_TYPE_DOUBLE: return "Float64";
- case BASE_TYPE_STRING: return "String";
- case BASE_TYPE_VECTOR: return GenType(type.VectorType());
- case BASE_TYPE_STRUCT: return type.struct_def->name;
- default: return "Table";
- }
- }
-
- std::string GenGetter(const Type &type, const std::string &arguments) {
- switch (type.base_type) {
- case BASE_TYPE_STRING: return GenBBAccess() + ".__string" + arguments;
- case BASE_TYPE_STRUCT: return GenBBAccess() + ".__struct" + arguments;
- case BASE_TYPE_UNION:
- if (!UnionHasStringType(*type.enum_def) ||
- lang_.language == IDLOptions::kJs) {
- return GenBBAccess() + ".__union" + arguments;
- }
- return GenBBAccess() + ".__union_with_string" + arguments;
- case BASE_TYPE_VECTOR: return GenGetter(type.VectorType(), arguments);
- default: {
- auto getter =
- GenBBAccess() + ".read" + MakeCamel(GenType(type)) + arguments;
- if (type.base_type == BASE_TYPE_BOOL) { getter = "!!" + getter; }
- if (type.enum_def) {
- getter = "/** " +
- GenTypeAnnotation(kType, WrapInNameSpace(*type.enum_def), "",
- false) +
- " */ (" + getter + ")";
- }
- return getter;
- }
- }
- }
-
- std::string GenBBAccess() const {
- return lang_.language == IDLOptions::kTs ? "this.bb!" : "this.bb";
- }
-
- std::string GenDefaultValue(const FieldDef &field, const std::string &context) {
- if (field.IsScalarOptional()) {
- return "null";
- }
-
- const auto &value = field.value;
- if (value.type.enum_def && value.type.base_type != BASE_TYPE_UNION &&
- value.type.base_type != BASE_TYPE_VECTOR) {
- if (auto val = value.type.enum_def->FindByValue(value.constant)) {
- if (lang_.language == IDLOptions::kTs) {
- return GenPrefixedTypeName(WrapInNameSpace(*value.type.enum_def),
- value.type.enum_def->file) +
- "." + val->name;
- } else {
- return WrapInNameSpace(*value.type.enum_def) + "." + val->name;
- }
- } else {
- return "/** " +
- GenTypeAnnotation(kType, WrapInNameSpace(*value.type.enum_def),
- "", false) +
- "} */ (" + value.constant + ")";
- }
- }
-
- switch (value.type.base_type) {
- case BASE_TYPE_BOOL: return value.constant == "0" ? "false" : "true";
-
- case BASE_TYPE_STRING:
- case BASE_TYPE_UNION:
- case BASE_TYPE_STRUCT: {
- return "null";
- }
-
- case BASE_TYPE_VECTOR: return "[]";
-
- case BASE_TYPE_LONG:
- case BASE_TYPE_ULONG: {
- int64_t constant = StringToInt(value.constant.c_str());
- return context + ".createLong(" +
- NumToString(static_cast<int32_t>(constant)) + ", " +
- NumToString(static_cast<int32_t>(constant >> 32)) + ")";
- }
-
- default: return value.constant;
- }
- }
-
- std::string GenTypeName(const Type &type, bool input,
- bool allowNull = false) {
- if (!input) {
- if (IsString(type) || type.base_type == BASE_TYPE_STRUCT) {
- std::string name;
- if (IsString(type)) {
- name = "string|Uint8Array";
- } else {
- name = WrapInNameSpace(*type.struct_def);
- }
- return (allowNull) ? (name + "|null") : (name);
- }
- }
-
- switch (type.base_type) {
- case BASE_TYPE_BOOL: return (allowNull) ? ("boolean|null") : ("boolean");
- case BASE_TYPE_LONG:
- case BASE_TYPE_ULONG: return (allowNull) ? ("flatbuffers.Long|null") : ("flatbuffers.Long");
- default:
- if (IsScalar(type.base_type)) {
- if (type.enum_def) {
- const auto enum_name = WrapInNameSpace(*type.enum_def);
- return (allowNull) ? (enum_name + "|null") : (enum_name);
- }
-
- return (allowNull) ? ("number|null") : ("number");
- }
- return "flatbuffers.Offset";
- }
- }
-
- // Returns the method name for use with add/put calls.
- static std::string GenWriteMethod(const Type &type) {
- // Forward to signed versions since unsigned versions don't exist
- switch (type.base_type) {
- case BASE_TYPE_UTYPE:
- case BASE_TYPE_UCHAR: return GenWriteMethod(Type(BASE_TYPE_CHAR));
- case BASE_TYPE_USHORT: return GenWriteMethod(Type(BASE_TYPE_SHORT));
- case BASE_TYPE_UINT: return GenWriteMethod(Type(BASE_TYPE_INT));
- case BASE_TYPE_ULONG: return GenWriteMethod(Type(BASE_TYPE_LONG));
- default: break;
- }
-
- return IsScalar(type.base_type) ? MakeCamel(GenType(type))
- : (IsStruct(type) ? "Struct" : "Offset");
- }
-
- template<typename T> static std::string MaybeAdd(T value) {
- return value != 0 ? " + " + NumToString(value) : "";
- }
-
- template<typename T> static std::string MaybeScale(T value) {
- return value != 1 ? " * " + NumToString(value) : "";
- }
-
- static std::string GenFileNamespacePrefix(const std::string &file) {
- return "NS" + std::to_string(HashFnv1a<uint64_t>(file.c_str()));
- }
-
- std::string GenPrefixedImport(const std::string &full_file_name,
- const std::string &base_name) {
- // Either keep the include path as it was
- // or use only the base_name + kGeneratedFileNamePostfix
- std::string path;
- if (parser_.opts.keep_include_path) {
- auto it = parser_.included_files_.find(full_file_name);
- FLATBUFFERS_ASSERT(it != parser_.included_files_.end());
- path = flatbuffers::StripExtension(it->second) +
- parser_.opts.filename_suffix;
- } else {
- path = base_name + parser_.opts.filename_suffix;
- }
-
- // Add the include prefix and make the path always relative
- path = flatbuffers::ConCatPathFileName(parser_.opts.include_prefix, path);
- path = std::string(".") + kPathSeparator + path;
-
- return "import * as " + GenFileNamespacePrefix(full_file_name) +
- " from \"" + path + "\";\n";
- }
-
- // Adds a source-dependent prefix, for of import * statements.
- std::string GenPrefixedTypeName(const std::string &typeName,
- const std::string &file) {
- const auto basename =
- flatbuffers::StripPath(flatbuffers::StripExtension(file));
- if (basename == file_name_ || parser_.opts.generate_all) {
- return typeName;
- }
- return GenFileNamespacePrefix(file) + "." + typeName;
- }
-
- void GenStructArgs(const StructDef &struct_def, std::string *annotations,
- std::string *arguments, const std::string &nameprefix) {
- for (auto it = struct_def.fields.vec.begin();
- it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
- if (IsStruct(field.value.type)) {
- // Generate arguments for a struct inside a struct. To ensure names
- // don't clash, and to make it obvious these arguments are constructing
- // a nested struct, prefix the name with the field name.
- GenStructArgs(*field.value.type.struct_def, annotations, arguments,
- nameprefix + field.name + "_");
- } else {
- *annotations +=
- GenTypeAnnotation(kParam, GenTypeName(field.value.type, true, field.optional),
- nameprefix + field.name);
- if (lang_.language == IDLOptions::kTs) {
- *arguments += ", " + nameprefix + field.name + ": " +
- GenTypeName(field.value.type, true, field.optional);
- } else {
- *arguments += ", " + nameprefix + field.name;
- }
- }
- }
- }
-
- static void GenStructBody(const StructDef &struct_def, std::string *body,
- const std::string &nameprefix) {
- *body += " builder.prep(";
- *body += NumToString(struct_def.minalign) + ", ";
- *body += NumToString(struct_def.bytesize) + ");\n";
-
- for (auto it = struct_def.fields.vec.rbegin();
- it != struct_def.fields.vec.rend(); ++it) {
- auto &field = **it;
- if (field.padding) {
- *body += " builder.pad(" + NumToString(field.padding) + ");\n";
- }
- if (IsStruct(field.value.type)) {
- // Generate arguments for a struct inside a struct. To ensure names
- // don't clash, and to make it obvious these arguments are constructing
- // a nested struct, prefix the name with the field name.
- GenStructBody(*field.value.type.struct_def, body,
- nameprefix + field.name + "_");
- } else {
- *body += " builder.write" + GenWriteMethod(field.value.type) + "(";
- if (field.value.type.base_type == BASE_TYPE_BOOL) { *body += "+"; }
- *body += nameprefix + field.name + ");\n";
- }
- }
- }
-
- std::string GenerateNewExpression(const std::string &object_name) {
- return "new " + object_name +
- (lang_.language == IDLOptions::kTs ? "()" : "");
- }
-
- void GenerateRootAccessor(StructDef &struct_def, std::string *code_ptr,
- std::string &code, std::string &object_name,
- bool size_prefixed) {
- if (!struct_def.fixed) {
- GenDocComment(code_ptr,
- GenTypeAnnotation(kParam, "flatbuffers.ByteBuffer", "bb") +
- GenTypeAnnotation(kParam, object_name + "=", "obj") +
- GenTypeAnnotation(kReturns, object_name, "", false));
- std::string sizePrefixed("SizePrefixed");
- if (lang_.language == IDLOptions::kTs) {
- code += "static get" + (size_prefixed ? sizePrefixed : "") + "Root" +
- Verbose(struct_def, "As");
- code += "(bb:flatbuffers.ByteBuffer, obj?:" + object_name +
- "):" + object_name + " {\n";
- } else {
- code += object_name + ".get" + (size_prefixed ? sizePrefixed : "") +
- "Root" + Verbose(struct_def, "As");
- code += " = function(bb, obj) {\n";
- }
- if (size_prefixed) {
- code +=
- " bb.setPosition(bb.position() + "
- "flatbuffers.SIZE_PREFIX_LENGTH);\n";
- }
- code += " return (obj || " + GenerateNewExpression(object_name);
- code += ").__init(bb.readInt32(bb.position()) + bb.position(), bb);\n";
- code += "};\n\n";
- }
- }
-
- void GenerateFinisher(StructDef &struct_def, std::string *code_ptr,
- std::string &code, std::string &object_name,
- bool size_prefixed) {
- if (parser_.root_struct_def_ == &struct_def) {
- std::string sizePrefixed("SizePrefixed");
- GenDocComment(
- code_ptr,
- GenTypeAnnotation(kParam, "flatbuffers.Builder", "builder") +
- GenTypeAnnotation(kParam, "flatbuffers.Offset", "offset", false));
-
- if (lang_.language == IDLOptions::kTs) {
- code += "static finish" + (size_prefixed ? sizePrefixed : "") +
- Verbose(struct_def) + "Buffer";
- code += "(builder:flatbuffers.Builder, offset:flatbuffers.Offset) {\n";
- } else {
- code += object_name + ".finish" + (size_prefixed ? sizePrefixed : "") +
- Verbose(struct_def) + "Buffer";
- code += " = function(builder, offset) {\n";
- }
-
- code += " builder.finish(offset";
- if (!parser_.file_identifier_.empty()) {
- code += ", '" + parser_.file_identifier_ + "'";
- }
- if (size_prefixed) {
- if (parser_.file_identifier_.empty()) { code += ", undefined"; }
- code += ", true";
- }
- code += ");\n";
- code += "};\n\n";
- }
- }
-
- static std::string GetObjApiClassName(const StructDef &sd,
- const IDLOptions &opts) {
- return GetObjApiClassName(sd.name, opts);
- }
-
- static std::string GetObjApiClassName(const std::string &name,
- const IDLOptions &opts) {
- return opts.object_prefix + name + opts.object_suffix;
- }
-
- bool UnionHasStringType(const EnumDef &union_enum) {
- return std::any_of(union_enum.Vals().begin(), union_enum.Vals().end(),
- [](const EnumVal *ev) {
- return !(ev->IsZero()) &&
- (IsString(ev->union_type));
- });
- }
-
- std::string GenUnionGenericTypeTS(const EnumDef &union_enum) {
- return std::string("T") + (UnionHasStringType(union_enum) ? "|string" : "");
- }
-
- std::string GenUnionTypeTS(const EnumDef &union_enum,
- imported_fileset &imported_files) {
- std::string ret;
- std::set<std::string> type_list;
-
- for (auto it = union_enum.Vals().begin(); it != union_enum.Vals().end();
- ++it) {
- const auto &ev = **it;
- if (ev.IsZero()) { continue; }
-
- std::string type = "";
- if (IsString(ev.union_type)) {
- type = "string"; // no need to wrap string type in namespace
- } else if (ev.union_type.base_type == BASE_TYPE_STRUCT) {
- if (!parser_.opts.generate_all) {
- imported_files.insert(ev.union_type.struct_def->file);
- }
-
- type = GenPrefixedTypeName(WrapInNameSpace(*(ev.union_type.struct_def)),
- ev.union_type.struct_def->file);
- } else {
- FLATBUFFERS_ASSERT(false);
- }
- type_list.insert(type);
- }
-
- for (auto it = type_list.begin(); it != type_list.end(); ++it) {
- ret += *it + ((std::next(it) == type_list.end()) ? "" : "|");
- }
-
- return ret;
- }
-
- // Generate a TS union type based on a union's enum
- std::string GenObjApiUnionTypeTS(const IDLOptions &opts,
- const EnumDef &union_enum) {
- std::string ret = "";
- std::set<std::string> type_list;
-
- for (auto it = union_enum.Vals().begin(); it != union_enum.Vals().end();
- ++it) {
- const auto &ev = **it;
- if (ev.IsZero()) { continue; }
-
- std::string type = "";
- if (IsString(ev.union_type)) {
- type = "string"; // no need to wrap string type in namespace
- } else if (ev.union_type.base_type == BASE_TYPE_STRUCT) {
- type = GenPrefixedTypeName(
- GetObjApiClassName(WrapInNameSpace(*(ev.union_type.struct_def)),
- opts),
- union_enum.file);
- } else {
- FLATBUFFERS_ASSERT(false);
- }
- type_list.insert(type);
- }
-
- size_t totalPrinted = 0;
- for (auto it = type_list.begin(); it != type_list.end(); ++it) {
- ++totalPrinted;
- ret += *it + ((totalPrinted == type_list.size()) ? "" : "|");
- }
-
- return ret;
- }
-
- std::string GenUnionConvFuncName(const EnumDef &enum_def) {
- return "unionTo" + enum_def.name;
- }
-
- std::string GenUnionListConvFuncName(const EnumDef &enum_def) {
- return "unionListTo" + enum_def.name;
- }
-
- std::string GenUnionConvFunc(const Type &union_type,
- imported_fileset &imported_files) {
- if (union_type.enum_def) {
- const auto &enum_def = *union_type.enum_def;
-
- const auto valid_union_type = GenUnionTypeTS(enum_def, imported_files);
- const auto valid_union_type_with_null = valid_union_type + "|null";
-
- auto ret = "\n\nexport function " + GenUnionConvFuncName(enum_def) +
- "(\n type: " + enum_def.name +
- ",\n accessor: (obj:" + valid_union_type + ") => " +
- valid_union_type_with_null +
- "\n): " + valid_union_type_with_null + " {\n";
-
- if (!parser_.opts.generate_all) {
- imported_files.insert(union_type.enum_def->file);
- }
-
- const auto enum_type = GenPrefixedTypeName(
- WrapInNameSpace(*(union_type.enum_def)), union_type.enum_def->file);
- const auto &union_enum = *(union_type.enum_def);
-
- const auto union_enum_loop = [&](const std::string &accessor_str) {
- ret += " switch(" + enum_type + "[type]) {\n";
- ret += " case 'NONE': return null; \n";
-
- for (auto it = union_enum.Vals().begin(); it != union_enum.Vals().end();
- ++it) {
- const auto &ev = **it;
- if (ev.IsZero()) { continue; }
-
- ret += " case '" + ev.name + "': ";
-
- if (IsString(ev.union_type)) {
- ret += "return " + accessor_str + "'') as string;";
- } else if (ev.union_type.base_type == BASE_TYPE_STRUCT) {
- const auto type = GenPrefixedTypeName(
- WrapInNameSpace(*(ev.union_type.struct_def)),
- ev.union_type.struct_def->file);
- ret += "return " + accessor_str + "new " + type + "())! as " +
- type + ";";
- } else {
- FLATBUFFERS_ASSERT(false);
- }
- ret += "\n";
- }
-
- ret += " default: return null;\n";
- ret += " }\n";
- };
-
- union_enum_loop("accessor(");
- ret += "}";
-
- ret += "\n\nexport function " + GenUnionListConvFuncName(enum_def) +
- "(\n type: " + enum_def.name +
- ", \n accessor: (index: number, obj:" + valid_union_type +
- ") => " + valid_union_type_with_null +
- ", \n index: number\n): " + valid_union_type_with_null + " {\n";
- union_enum_loop("accessor(index, ");
- ret += "}";
-
- return ret;
- }
- FLATBUFFERS_ASSERT(0);
- return "";
- }
-
- // Used for generating a short function that returns the correct class
- // based on union enum type. Assume the context is inside the non object api
- // type
- std::string GenUnionValTS(const std::string &field_name,
- const Type &union_type,
- const bool is_array = false) {
- if (union_type.enum_def) {
- const auto &enum_def = *union_type.enum_def;
- const auto enum_type =
- GenPrefixedTypeName(WrapInNameSpace(enum_def), enum_def.file);
- const std::string union_accessor = "this." + field_name;
-
- const auto union_has_string = UnionHasStringType(enum_def);
- const auto field_binded_method = "this." + field_name + ".bind(this)";
-
- std::string ret;
-
- if (!is_array) {
- const auto conversion_function =
- GenPrefixedTypeName(WrapInNameSpace(enum_def.defined_namespace,
- GenUnionConvFuncName(enum_def)),
- enum_def.file);
- const auto target_enum = "this." + field_name + "Type()";
-
- ret = "(() => {\n";
- ret += " let temp = " + conversion_function + "(" + target_enum +
- ", " + field_binded_method + ");\n";
- ret += " if(temp === null) { return null; }\n";
- ret += union_has_string
- ? " if(typeof temp === 'string') { return temp; }\n"
- : "";
- ret += " return temp.unpack()\n";
- ret += " })()";
- } else {
- const auto conversion_function = GenPrefixedTypeName(
- WrapInNameSpace(enum_def.defined_namespace,
- GenUnionListConvFuncName(enum_def)),
- enum_def.file);
- const auto target_enum_accesor = "this." + field_name + "Type";
- const auto target_enum_length = target_enum_accesor + "Length()";
-
- ret = "(() => {\n";
- ret += " let ret = [];\n";
- ret += " for(let targetEnumIndex = 0; targetEnumIndex < " +
- target_enum_length +
- "; "
- "++targetEnumIndex) {\n";
- ret += " let targetEnum = " + target_enum_accesor +
- "(targetEnumIndex);\n";
- ret += " if(targetEnum === null || " + enum_type +
- "[targetEnum!] === 'NONE') { "
- "continue; }\n\n";
- ret += " let temp = " + conversion_function + "(targetEnum, " +
- field_binded_method + ", targetEnumIndex);\n";
- ret += " if(temp === null) { continue; }\n";
- ret += union_has_string ? " if(typeof temp === 'string') { "
- "ret.push(temp); continue; }\n"
- : "";
- ret += " ret.push(temp.unpack());\n";
- ret += " }\n";
- ret += " return ret;\n";
- ret += " })()";
- }
-
- return ret;
- }
-
- FLATBUFFERS_ASSERT(0);
- return "";
- }
-
- static std::string GenNullCheckConditional(const std::string &nullCheckVar,
- const std::string &trueVal,
- const std::string &falseVal = "null") {
- return "(" + nullCheckVar + " !== null ? " + trueVal + " : " + falseVal +
- ")";
- }
-
- std::string GenStructMemberValueTS(const StructDef &struct_def,
- const std::string &prefix,
- const std::string &delimiter,
- const bool nullCheck = true) {
- std::string ret;
- for (auto it = struct_def.fields.vec.begin();
- it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
-
- const auto curr_member_accessor =
- prefix + "." + MakeCamel(field.name, false);
- if (IsStruct(field.value.type)) {
- ret += GenStructMemberValueTS(*field.value.type.struct_def,
- curr_member_accessor, delimiter);
- } else {
- if (nullCheck) {
- ret +=
- "(" + prefix + " === null ? 0 : " + curr_member_accessor + "!)";
- } else {
- ret += curr_member_accessor;
- }
- }
-
- if (std::next(it) != struct_def.fields.vec.end()) { ret += delimiter; }
- }
-
- return ret;
- }
-
- void GenObjApi(const Parser &parser, StructDef &struct_def,
- std::string &obj_api_unpack_func, std::string &obj_api_class,
- imported_fileset &imported_files) {
- const auto class_name = GetObjApiClassName(struct_def, parser.opts);
-
- std::string unpack_func =
- "\n/**\n * " + GenTypeAnnotation(kReturns, class_name, "") +
- " */\nunpack(): " + class_name + " {\n return new " + class_name +
- "(" + (struct_def.fields.vec.empty() ? "" : "\n");
- std::string unpack_to_func =
- "/**\n * " + GenTypeAnnotation(kParam, class_name, "_o") +
- " */\nunpackTo(_o: " + class_name + "): void {" +
- +(struct_def.fields.vec.empty() ? "" : "\n");
-
- std::string constructor_annotation = "/**\n * @constructor";
- constructor_annotation += (struct_def.fields.vec.empty() ? "" : "\n");
- std::string constructor_func = "constructor(";
- constructor_func += (struct_def.fields.vec.empty() ? "" : "\n");
-
- const auto has_create =
- struct_def.fixed || CanCreateFactoryMethod(struct_def);
-
- std::string pack_func_prototype =
- "/**\n * " +
- GenTypeAnnotation(kParam, "flatbuffers.Builder", "builder") + " * " +
- GenTypeAnnotation(kReturns, "flatbuffers.Offset", "") +
- " */\npack(builder:flatbuffers.Builder): flatbuffers.Offset {\n";
-
- std::string pack_func_offset_decl;
- std::string pack_func_create_call;
-
- const auto struct_name =
- GenPrefixedTypeName(WrapInNameSpace(struct_def), struct_def.file);
-
- if (has_create) {
- pack_func_create_call = " return " + struct_name + ".create" +
- Verbose(struct_def) + "(builder" +
- (struct_def.fields.vec.empty() ? "" : ",\n ");
- } else {
- pack_func_create_call = " " + struct_name + ".start(builder);\n";
- }
-
- if (struct_def.fixed) {
- // when packing struct, nested struct's members instead of the struct's
- // offset are used
- pack_func_create_call +=
- GenStructMemberValueTS(struct_def, "this", ",\n ", false) + "\n ";
- }
-
- for (auto it = struct_def.fields.vec.begin();
- it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
- if (field.deprecated) continue;
-
- const auto field_name = MakeCamel(field.name, false);
- const std::string field_binded_method =
- "this." + field_name + ".bind(this)";
-
- std::string field_val;
- std::string field_type;
- // a string that declares a variable containing the
- // offset for things that can't be generated inline
- // empty otw
- std::string field_offset_decl;
- // a string that contains values for things that can be created inline or
- // the variable name from field_offset_decl
- std::string field_offset_val;
- const auto field_default_val =
- GenDefaultValue(field, "flatbuffers");
-
- // Emit a scalar field
- const auto is_string = IsString(field.value.type);
- if (IsScalar(field.value.type.base_type) || is_string) {
- const auto has_null_default = is_string || HasNullDefault(field);
-
- if (field.value.type.enum_def) {
- if (!parser_.opts.generate_all) {
- imported_files.insert(field.value.type.enum_def->file);
- }
-
- field_type +=
- GenPrefixedTypeName(GenTypeName(field.value.type, false, has_null_default),
- field.value.type.enum_def->file);
- } else {
- field_type += GenTypeName(field.value.type, false, has_null_default);
- }
- field_val = "this." + field_name + "()";
-
- if (field.value.type.base_type != BASE_TYPE_STRING) {
- field_offset_val = "this." + field_name;
- } else {
- field_offset_decl = GenNullCheckConditional(
- "this." + field_name,
- "builder.createString(this." + field_name + "!)", "0");
- }
- }
-
- // Emit an object field
- else {
- auto is_vector = false;
- switch (field.value.type.base_type) {
- case BASE_TYPE_STRUCT: {
- const auto &sd = *field.value.type.struct_def;
- field_type += GenPrefixedTypeName(
- WrapInNameSpace(sd.defined_namespace,
- GetObjApiClassName(sd, parser.opts)),
- field.value.type.struct_def->file);
-
- const std::string field_accessor = "this." + field_name + "()";
- field_val = GenNullCheckConditional(field_accessor,
- field_accessor + "!.unpack()");
- field_offset_val = GenNullCheckConditional(
- "this." + field_name, "this." + field_name + "!.pack(builder)",
- "0");
-
- break;
- }
-
- case BASE_TYPE_VECTOR: {
- auto vectortype = field.value.type.VectorType();
- auto vectortypename = GenTypeName(vectortype, false);
- is_vector = true;
-
- field_type = "(";
-
- switch (vectortype.base_type) {
- case BASE_TYPE_STRUCT: {
- const auto &sd = *field.value.type.struct_def;
- field_type += GenPrefixedTypeName(
- WrapInNameSpace(sd.defined_namespace,
- GetObjApiClassName(sd, parser.opts)),
- field.value.type.struct_def->file);
- field_type += ")[]";
-
- field_val = GenBBAccess() + ".createObjList(" +
- field_binded_method + ", this." + field_name +
- "Length())";
-
- if (sd.fixed) {
- field_offset_decl =
- "builder.createStructOffsetList(this." + field_name +
- ", " +
- GenPrefixedTypeName(WrapInNameSpace(struct_def),
- struct_def.file) +
- ".start" + MakeCamel(field_name) + "Vector)";
- } else {
- field_offset_decl =
- GenPrefixedTypeName(WrapInNameSpace(struct_def),
- struct_def.file) +
- ".create" + MakeCamel(field_name) +
- "Vector(builder, builder.createObjectOffsetList(" +
- "this." + field_name + "))";
- }
-
- break;
- }
-
- case BASE_TYPE_STRING: {
- field_type += "string)[]";
- field_val = GenBBAccess() + ".createStringList(" +
- field_binded_method + ", this." + field_name +
- "Length())";
- field_offset_decl =
- GenPrefixedTypeName(WrapInNameSpace(struct_def),
- struct_def.file) +
- ".create" + MakeCamel(field_name) +
- "Vector(builder, builder.createObjectOffsetList(" +
- "this." + field_name + "))";
- break;
- }
-
- case BASE_TYPE_UNION: {
- field_type +=
- GenObjApiUnionTypeTS(parser.opts, *(vectortype.enum_def));
- field_type += ")[]";
- field_val = GenUnionValTS(field_name, vectortype, true);
-
- field_offset_decl =
- GenPrefixedTypeName(WrapInNameSpace(struct_def),
- struct_def.file) +
- ".create" + MakeCamel(field_name) +
- "Vector(builder, builder.createObjectOffsetList(" +
- "this." + field_name + "))";
-
- break;
- }
- default: {
- if (vectortype.enum_def) {
- if (!parser_.opts.generate_all) {
- imported_files.insert(vectortype.enum_def->file);
- }
-
- field_type +=
- GenPrefixedTypeName(GenTypeName(vectortype, false, HasNullDefault(field)),
- vectortype.enum_def->file);
- } else {
- field_type += vectortypename;
- }
- field_type += ")[]";
- field_val = GenBBAccess() + ".createScalarList(" +
- field_binded_method + ", this." + field_name +
- "Length())";
-
- field_offset_decl =
- GenPrefixedTypeName(WrapInNameSpace(struct_def),
- struct_def.file) +
- ".create" + MakeCamel(field_name) +
- "Vector(builder, this." + field_name + ")";
-
- break;
- }
- }
-
- break;
- }
-
- case BASE_TYPE_UNION: {
- if (!parser_.opts.generate_all) {
- imported_files.insert(field.value.type.enum_def->file);
- }
-
- field_type +=
- GenObjApiUnionTypeTS(parser.opts, *(field.value.type.enum_def));
-
- field_val = GenUnionValTS(field_name, field.value.type);
- field_offset_decl =
- "builder.createObjectOffset(this." + field_name + ")";
- break;
- }
-
- default: FLATBUFFERS_ASSERT(0); break;
- }
-
- // length 0 vector is simply empty instead of null
- field_type += is_vector ? "" : "|null";
- }
-
- if (!field_offset_decl.empty()) {
- field_offset_decl =
- " const " + field_name + " = " + field_offset_decl + ";";
- }
- if (field_offset_val.empty()) { field_offset_val = field_name; }
-
- unpack_func += " " + field_val;
- unpack_to_func += " _o." + field_name + " = " + field_val + ";";
-
- constructor_annotation +=
- " * " + GenTypeAnnotation(kParam, field_type, field_name, false);
- constructor_func += " public " + field_name + ": " + field_type + " = " +
- field_default_val;
-
- if (!struct_def.fixed) {
- if (!field_offset_decl.empty()) {
- pack_func_offset_decl += field_offset_decl + "\n";
- }
-
- if (has_create) {
- pack_func_create_call += field_offset_val;
- } else {
- pack_func_create_call += " " + struct_name + ".add" +
- MakeCamel(field.name) + "(builder, " +
- field_offset_val + ");\n";
- }
- }
-
- if (std::next(it) != struct_def.fields.vec.end()) {
- constructor_annotation += "\n";
- constructor_func += ",\n";
-
- if (!struct_def.fixed && has_create) {
- pack_func_create_call += ",\n ";
- }
-
- unpack_func += ",\n";
- unpack_to_func += "\n";
- } else {
- constructor_func += "\n";
- if (!struct_def.fixed) {
- pack_func_offset_decl += (pack_func_offset_decl.empty() ? "" : "\n");
- pack_func_create_call += "\n ";
- }
-
- unpack_func += "\n ";
- unpack_to_func += "\n";
- }
- }
-
- constructor_annotation += "\n */\n";
- constructor_func += "){};\n\n";
-
- if (has_create) {
- pack_func_create_call += ");";
- } else {
- pack_func_create_call += "return " + struct_name + ".end(builder);";
- }
-
- obj_api_class = "\nexport class " +
- GetObjApiClassName(struct_def, parser.opts) + " {\n";
-
- obj_api_class += constructor_annotation + constructor_func;
-
- obj_api_class += pack_func_prototype + pack_func_offset_decl +
- pack_func_create_call + "\n};";
-
- obj_api_class += "\n}\n";
-
- unpack_func += ");\n};";
- unpack_to_func += "};\n";
-
- obj_api_unpack_func = unpack_func + "\n\n" + unpack_to_func;
- }
-
- static bool CanCreateFactoryMethod(const StructDef &struct_def) {
- // to preserve backwards compatibility, we allow the first field to be a
- // struct
- return struct_def.fields.vec.size() < 2 ||
- std::all_of(std::begin(struct_def.fields.vec) + 1,
- std::end(struct_def.fields.vec),
- [](const FieldDef *f) -> bool {
- FLATBUFFERS_ASSERT(f != nullptr);
- return f->value.type.base_type != BASE_TYPE_STRUCT;
- });
- }
-
- // Generate an accessor struct with constructor for a flatbuffers struct.
- void GenStruct(const Parser &parser, StructDef &struct_def,
- std::string *code_ptr, std::string *exports_ptr,
- imported_fileset &imported_files) {
- if (struct_def.generated) return;
- std::string &code = *code_ptr;
- std::string &exports = *exports_ptr;
-
- std::string object_name;
- std::string object_namespace = GetNameSpace(struct_def);
-
- // Emit constructor
- if (lang_.language == IDLOptions::kTs) {
- object_name = struct_def.name;
- GenDocComment(struct_def.doc_comment, code_ptr, "@constructor");
- if (!object_namespace.empty()) {
- code += "export namespace " + object_namespace + "{\n";
- }
- code += "export class " + struct_def.name;
- code += " {\n";
- if (lang_.language != IDLOptions::kTs) {
- code += " /**\n";
- code +=
- " * " + GenTypeAnnotation(kType, "flatbuffers.ByteBuffer", "");
- code += " */\n";
- }
- code += " bb: flatbuffers.ByteBuffer|null = null;\n";
- code += "\n";
- if (lang_.language != IDLOptions::kTs) {
- code += " /**\n";
- code += " * " + GenTypeAnnotation(kType, "number", "");
- code += " */\n";
- }
- code += " bb_pos:number = 0;\n";
- } else {
- bool isStatement = struct_def.defined_namespace->components.empty();
- object_name = WrapInNameSpace(struct_def);
- GenDocComment(struct_def.doc_comment, code_ptr, "@constructor");
- if (isStatement) {
- if (parser_.opts.use_goog_js_export_format) {
- exports += "goog.exportSymbol('" + struct_def.name + "', " +
- struct_def.name + ");\n";
- } else if (parser_.opts.use_ES6_js_export_format) {
- exports += "export {" + struct_def.name + "};\n";
- } else {
- exports +=
- "this." + struct_def.name + " = " + struct_def.name + ";\n";
- }
- code += "function " + object_name;
- } else {
- code += object_name + " = function";
- }
- code += "() {\n";
- code += " /**\n";
- code += " * " + GenTypeAnnotation(kType, "flatbuffers.ByteBuffer", "");
- code += " */\n";
- code += " this.bb = null;\n";
- code += "\n";
- code += " /**\n";
- code += " * " + GenTypeAnnotation(kType, "number", "");
- code += " */\n";
- code += " this.bb_pos = 0;\n";
- code += isStatement ? "}\n\n" : "};\n\n";
- }
-
- // Generate the __init method that sets the field in a pre-existing
- // accessor object. This is to allow object reuse.
- code += "/**\n";
- code += " * " + GenTypeAnnotation(kParam, "number", "i");
- code += " * " + GenTypeAnnotation(kParam, "flatbuffers.ByteBuffer", "bb");
- code += " * " + GenTypeAnnotation(kReturns, object_name, "");
- code += " */\n";
-
- if (lang_.language == IDLOptions::kTs) {
- code +=
- "__init(i:number, bb:flatbuffers.ByteBuffer):" + object_name + " {\n";
- } else {
- code += object_name + ".prototype.__init = function(i, bb) {\n";
- }
-
- code += " this.bb_pos = i;\n";
- code += " this.bb = bb;\n";
- code += " return this;\n";
- code += "};\n\n";
-
- // Generate special accessors for the table that when used as the root of a
- // FlatBuffer
- GenerateRootAccessor(struct_def, code_ptr, code, object_name, false);
- GenerateRootAccessor(struct_def, code_ptr, code, object_name, true);
-
- // Generate the identifier check method
- if (!struct_def.fixed && parser_.root_struct_def_ == &struct_def &&
- !parser_.file_identifier_.empty()) {
- GenDocComment(code_ptr,
- GenTypeAnnotation(kParam, "flatbuffers.ByteBuffer", "bb") +
- GenTypeAnnotation(kReturns, "boolean", "", false));
- if (lang_.language == IDLOptions::kTs) {
- code +=
- "static bufferHasIdentifier(bb:flatbuffers.ByteBuffer):boolean "
- "{\n";
- } else {
- code += object_name + ".bufferHasIdentifier = function(bb) {\n";
- }
-
- code += " return bb.__has_identifier('" + parser_.file_identifier_;
- code += "');\n};\n\n";
- }
-
- // Emit field accessors
- for (auto it = struct_def.fields.vec.begin();
- it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
- if (field.deprecated) continue;
- auto offset_prefix =
- " var offset = " + GenBBAccess() + ".__offset(this.bb_pos, " +
- NumToString(field.value.offset) + ");\n return offset ? ";
-
- // Emit a scalar field
- const auto is_string = IsString(field.value.type);
- if (IsScalar(field.value.type.base_type) || is_string) {
- const auto has_null_default = is_string || HasNullDefault(field);
-
- GenDocComment(
- field.doc_comment, code_ptr,
- std::string(is_string
- ? GenTypeAnnotation(kParam, "flatbuffers.Encoding=",
- "optionalEncoding")
- : "") +
- GenTypeAnnotation(kReturns,
- GenTypeName(field.value.type, false, has_null_default),
- "", false));
- if (lang_.language == IDLOptions::kTs) {
- std::string prefix = MakeCamel(field.name, false) + "(";
- if (is_string) {
- code += prefix + "):string|null\n";
- code += prefix + "optionalEncoding:flatbuffers.Encoding" +
- "):" + GenTypeName(field.value.type, false, true) + "\n";
- code += prefix + "optionalEncoding?:any";
- } else {
- code += prefix;
- }
- if (field.value.type.enum_def) {
- code +=
- "):" +
- GenPrefixedTypeName(GenTypeName(field.value.type, false, field.optional),
- field.value.type.enum_def->file) +
- " {\n";
-
- if (!parser_.opts.generate_all) {
- imported_files.insert(field.value.type.enum_def->file);
- }
- } else {
- code += "):" + GenTypeName(field.value.type, false, has_null_default) + " {\n";
- }
- } else {
- code += object_name + ".prototype." + MakeCamel(field.name, false);
- code += " = function(";
- if (is_string) {
- code += "optionalEncoding";
- }
- code += ") {\n";
- }
-
- if (struct_def.fixed) {
- code +=
- " return " +
- GenGetter(field.value.type,
- "(this.bb_pos" + MaybeAdd(field.value.offset) + ")") +
- ";\n";
- } else {
- std::string index = "this.bb_pos + offset";
- if (is_string) {
- index += ", optionalEncoding";
- }
- code += offset_prefix +
- GenGetter(field.value.type, "(" + index + ")") + " : " +
- GenDefaultValue(field, GenBBAccess());
- code += ";\n";
- }
- }
-
- // Emit an object field
- else {
- switch (field.value.type.base_type) {
- case BASE_TYPE_STRUCT: {
- auto type = WrapInNameSpace(*field.value.type.struct_def);
- GenDocComment(
- field.doc_comment, code_ptr,
- GenTypeAnnotation(kParam, type + "=", "obj") +
- GenTypeAnnotation(kReturns, type + "|null", "", false));
- if (lang_.language == IDLOptions::kTs) {
- type =
- GenPrefixedTypeName(type, field.value.type.struct_def->file);
- code += MakeCamel(field.name, false);
- code += "(obj?:" + type + "):" + type + "|null {\n";
- } else {
- code +=
- object_name + ".prototype." + MakeCamel(field.name, false);
- code += " = function(obj) {\n";
- }
-
- if (struct_def.fixed) {
- code += " return (obj || " + GenerateNewExpression(type);
- code += ").__init(this.bb_pos";
- code +=
- MaybeAdd(field.value.offset) + ", " + GenBBAccess() + ");\n";
- } else {
- code += offset_prefix + "(obj || " + GenerateNewExpression(type) +
- ").__init(";
- code += field.value.type.struct_def->fixed
- ? "this.bb_pos + offset"
- : GenBBAccess() + ".__indirect(this.bb_pos + offset)";
- code += ", " + GenBBAccess() + ") : null;\n";
- }
-
- if (lang_.language == IDLOptions::kTs &&
- !parser_.opts.generate_all) {
- imported_files.insert(field.value.type.struct_def->file);
- }
-
- break;
- }
-
- case BASE_TYPE_VECTOR: {
- auto vectortype = field.value.type.VectorType();
- auto vectortypename = GenTypeName(vectortype, false);
-
- if (vectortype.enum_def) {
- vectortypename = GenPrefixedTypeName(vectortypename,
- vectortype.enum_def->file);
- }
-
- auto inline_size = InlineSize(vectortype);
- auto index = GenBBAccess() +
- ".__vector(this.bb_pos + offset) + index" +
- MaybeScale(inline_size);
- std::string args = GenTypeAnnotation(kParam, "number", "index");
- std::string ret_type;
- bool is_union = false;
- switch (vectortype.base_type) {
- case BASE_TYPE_STRUCT:
- args += GenTypeAnnotation(kParam, vectortypename + "=", "obj");
- ret_type = vectortypename;
- break;
- case BASE_TYPE_STRING:
- args += GenTypeAnnotation(
- kParam, "flatbuffers.Encoding=", "optionalEncoding");
- ret_type = vectortypename;
- break;
- case BASE_TYPE_UNION:
- args += GenTypeAnnotation(kParam, "flatbuffers.Table=", "obj");
- ret_type = "?flatbuffers.Table";
- is_union = true;
- break;
- default: ret_type = vectortypename;
- }
- GenDocComment(
- field.doc_comment, code_ptr,
- args + GenTypeAnnotation(kReturns, ret_type, "", false));
- if (lang_.language == IDLOptions::kTs) {
- std::string prefix = MakeCamel(field.name, false);
- if (is_union) { prefix += "<T extends flatbuffers.Table>"; }
- prefix += "(index: number";
- if (is_union) {
- const auto union_type =
- GenUnionGenericTypeTS(*(field.value.type.enum_def));
-
- vectortypename = union_type;
- code += prefix + ", obj:" + union_type;
- } else if (vectortype.base_type == BASE_TYPE_STRUCT) {
- vectortypename = GenPrefixedTypeName(
- vectortypename, vectortype.struct_def->file);
- code += prefix + ", obj?:" + vectortypename;
-
- if (!parser_.opts.generate_all) {
- imported_files.insert(vectortype.struct_def->file);
- }
- } else if (IsString(vectortype)) {
- code += prefix + "):string\n";
- code += prefix + ",optionalEncoding:flatbuffers.Encoding" +
- "):" + vectortypename + "\n";
- code += prefix + ",optionalEncoding?:any";
- } else {
- code += prefix;
-
- if (vectortype.enum_def && !parser_.opts.generate_all) {
- imported_files.insert(vectortype.enum_def->file);
- }
- }
- code += "):" + vectortypename + "|null {\n";
- } else {
- code +=
- object_name + ".prototype." + MakeCamel(field.name, false);
- code += " = function(index";
- if (vectortype.base_type == BASE_TYPE_STRUCT || is_union) {
- code += ", obj";
- } else if (IsString(vectortype)) {
- code += ", optionalEncoding";
- }
- code += ") {\n";
- }
-
- if (vectortype.base_type == BASE_TYPE_STRUCT) {
- code += offset_prefix + "(obj || " +
- GenerateNewExpression(vectortypename);
- code += ").__init(";
- code += vectortype.struct_def->fixed
- ? index
- : GenBBAccess() + ".__indirect(" + index + ")";
- code += ", " + GenBBAccess() + ")";
- } else {
- if (is_union) {
- index = "obj, " + index;
- } else if (IsString(vectortype)) {
- index += ", optionalEncoding";
- }
- code += offset_prefix + GenGetter(vectortype, "(" + index + ")");
- }
- code += " : ";
- if (field.value.type.element == BASE_TYPE_BOOL) {
- code += "false";
- } else if (field.value.type.element == BASE_TYPE_LONG ||
- field.value.type.element == BASE_TYPE_ULONG) {
- code += GenBBAccess() + ".createLong(0, 0)";
- } else if (IsScalar(field.value.type.element)) {
- if (field.value.type.enum_def) {
- code += "/** " +
- GenTypeAnnotation(
- kType, WrapInNameSpace(*field.value.type.enum_def),
- "", false) +
- " */ (" + field.value.constant + ")";
- } else {
- code += "0";
- }
- } else {
- code += "null";
- }
- code += ";\n";
- break;
- }
-
- case BASE_TYPE_UNION:
- GenDocComment(
- field.doc_comment, code_ptr,
- GenTypeAnnotation(kParam, "flatbuffers.Table", "obj") +
- GenTypeAnnotation(kReturns, "?flatbuffers.Table", "",
- false));
- if (lang_.language == IDLOptions::kTs) {
- code += MakeCamel(field.name, false);
-
- const auto &union_enum = *(field.value.type.enum_def);
- const auto union_type = GenUnionGenericTypeTS(union_enum);
- code += "<T extends flatbuffers.Table>(obj:" + union_type +
- "):" + union_type +
- "|null "
- "{\n";
- } else {
- code +=
- object_name + ".prototype." + MakeCamel(field.name, false);
- code += " = function(obj) {\n";
- }
-
- code += offset_prefix +
- GenGetter(field.value.type, "(obj, this.bb_pos + offset)") +
- " : null;\n";
- break;
-
- default: FLATBUFFERS_ASSERT(0);
- }
- }
- code += "};\n\n";
-
- if (parser_.opts.use_goog_js_export_format) {
- exports += "goog.exportProperty(" + object_name + ".prototype, '" +
- MakeCamel(field.name, false) + "', " + object_name +
- ".prototype." + MakeCamel(field.name, false) + ");\n";
- }
-
- // Adds the mutable scalar value to the output
- if (IsScalar(field.value.type.base_type) && parser.opts.mutable_buffer &&
- !IsUnion(field.value.type)) {
- std::string annotations = GenTypeAnnotation(
- kParam, GenTypeName(field.value.type, true), "value");
- GenDocComment(
- code_ptr,
- annotations + GenTypeAnnotation(kReturns, "boolean", "", false));
-
- if (lang_.language == IDLOptions::kTs) {
- std::string type;
- if (field.value.type.enum_def) {
- if (!parser_.opts.generate_all) {
- imported_files.insert(field.value.type.enum_def->file);
- }
-
- type = GenPrefixedTypeName(GenTypeName(field.value.type, true),
- field.value.type.enum_def->file);
- } else {
- type = GenTypeName(field.value.type, true);
- }
-
- code += "mutate_" + field.name + "(value:" + type + "):boolean {\n";
- } else {
- code += object_name + ".prototype.mutate_" + field.name +
- " = function(value) {\n";
- }
-
- if (struct_def.fixed) {
- code += " " + GenBBAccess() + ".write" +
- MakeCamel(GenType(field.value.type)) + "(this.bb_pos + " +
- NumToString(field.value.offset) + ", ";
- } else {
- code += " var offset = " + GenBBAccess() +
- ".__offset(this.bb_pos, " + NumToString(field.value.offset) +
- ");\n\n";
- code += " if (offset === 0) {\n";
- code += " return false;\n";
- code += " }\n\n";
-
- // special case for bools, which are treated as uint8
- code += " " + GenBBAccess() + ".write" +
- MakeCamel(GenType(field.value.type)) +
- "(this.bb_pos + offset, ";
- if (field.value.type.base_type == BASE_TYPE_BOOL &&
- lang_.language == IDLOptions::kTs) {
- code += "+";
- }
- }
-
- code += "value);\n";
- code += " return true;\n";
- code += "};\n\n";
-
- if (parser_.opts.use_goog_js_export_format) {
- exports += "goog.exportProperty(" + object_name +
- ".prototype, 'mutate_" + field.name + "', " + object_name +
- ".prototype.mutate_" + field.name + ");\n";
- }
- }
-
- // Emit vector helpers
- if (IsVector(field.value.type)) {
- // Emit a length helper
- GenDocComment(code_ptr,
- GenTypeAnnotation(kReturns, "number", "", false));
- if (lang_.language == IDLOptions::kTs) {
- code += MakeCamel(field.name, false);
- code += "Length():number {\n" + offset_prefix;
- } else {
- code += object_name + ".prototype." + MakeCamel(field.name, false);
- code += "Length = function() {\n" + offset_prefix;
- }
-
- code +=
- GenBBAccess() + ".__vector_len(this.bb_pos + offset) : 0;\n};\n\n";
-
- if (parser_.opts.use_goog_js_export_format) {
- exports += "goog.exportProperty(" + object_name + ".prototype, '" +
- MakeCamel(field.name, false) + "Length', " + object_name +
- ".prototype." + MakeCamel(field.name, false) +
- "Length);\n";
- }
-
- // For scalar types, emit a typed array helper
- auto vectorType = field.value.type.VectorType();
- if (IsScalar(vectorType.base_type) && !IsLong(vectorType.base_type)) {
- GenDocComment(code_ptr, GenTypeAnnotation(
- kReturns, GenType(vectorType) + "Array",
- "", false));
-
- if (lang_.language == IDLOptions::kTs) {
- code += MakeCamel(field.name, false);
- code += "Array():" + GenType(vectorType) + "Array|null {\n" +
- offset_prefix;
- } else {
- code += object_name + ".prototype." + MakeCamel(field.name, false);
- code += "Array = function() {\n" + offset_prefix;
- }
-
- code += "new " + GenType(vectorType) + "Array(" + GenBBAccess() +
- ".bytes().buffer, " + GenBBAccess() +
- ".bytes().byteOffset + " + GenBBAccess() +
- ".__vector(this.bb_pos + offset), " + GenBBAccess() +
- ".__vector_len(this.bb_pos + offset)) : null;\n};\n\n";
-
- if (parser_.opts.use_goog_js_export_format) {
- exports += "goog.exportProperty(" + object_name + ".prototype, '" +
- MakeCamel(field.name, false) + "Array', " + object_name +
- ".prototype." + MakeCamel(field.name, false) +
- "Array);\n";
- }
- }
- }
- }
-
- // Emit the fully qualified name
- if (parser_.opts.generate_name_strings) {
- GenDocComment(code_ptr, GenTypeAnnotation(kReturns, "string", "", false));
- if (lang_.language == IDLOptions::kTs) {
- code += "static getFullyQualifiedName():string {\n";
- } else {
- code += object_name + ".getFullyQualifiedName = function() {\n";
- }
- code += " return '" + WrapInNameSpace(struct_def) + "';\n";
- code += "}\n\n";
- }
-
- // Emit the size of the struct.
- if (struct_def.fixed) {
- GenDocComment(code_ptr, GenTypeAnnotation(kReturns, "number", "", false));
- if (lang_.language == IDLOptions::kTs) {
- code += "static sizeOf():number {\n";
- } else {
- code += object_name + ".sizeOf = function() {\n";
- }
- code += " return " + NumToString(struct_def.bytesize) + ";\n";
- code += "}\n\n";
- }
-
- // Emit a factory constructor
- if (struct_def.fixed) {
- std::string annotations =
- GenTypeAnnotation(kParam, "flatbuffers.Builder", "builder");
- std::string arguments;
- GenStructArgs(struct_def, &annotations, &arguments, "");
- GenDocComment(code_ptr, annotations + GenTypeAnnotation(
- kReturns, "flatbuffers.Offset",
- "", false));
-
- if (lang_.language == IDLOptions::kTs) {
- code += "static create" + Verbose(struct_def) +
- "(builder:flatbuffers.Builder";
- code += arguments + "):flatbuffers.Offset {\n";
- } else {
- code += object_name + ".create" + Verbose(struct_def);
- code += " = function(builder";
- code += arguments + ") {\n";
- }
-
- GenStructBody(struct_def, &code, "");
- code += " return builder.offset();\n};\n\n";
- } else {
- // Generate a method to start building a new object
- GenDocComment(code_ptr, GenTypeAnnotation(kParam, "flatbuffers.Builder",
- "builder", false));
-
- if (lang_.language == IDLOptions::kTs) {
- code += "static start" + Verbose(struct_def) +
- "(builder:flatbuffers.Builder) {\n";
- } else {
- code += object_name + ".start" + Verbose(struct_def);
- code += " = function(builder) {\n";
- }
-
- code += " builder.startObject(" +
- NumToString(struct_def.fields.vec.size()) + ");\n";
- code += "};\n\n";
-
- // Generate a set of static methods that allow table construction
- for (auto it = struct_def.fields.vec.begin();
- it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
- if (field.deprecated) continue;
- const auto argname = GetArgName(field);
-
- // Generate the field insertion method
- GenDocComment(
- code_ptr,
- GenTypeAnnotation(kParam, "flatbuffers.Builder", "builder") +
- GenTypeAnnotation(kParam, GenTypeName(field.value.type, true),
- argname, false));
-
- if (lang_.language == IDLOptions::kTs) {
- code += "static add" + MakeCamel(field.name);
- code += "(builder:flatbuffers.Builder, " + argname + ":" +
- GetArgType(field, false) + ") {\n";
- } else {
- code += object_name + ".add" + MakeCamel(field.name);
- code += " = function(builder, " + argname + ") {\n";
- }
-
- code += " builder.addField" + GenWriteMethod(field.value.type) + "(";
- code += NumToString(it - struct_def.fields.vec.begin()) + ", ";
- if (field.value.type.base_type == BASE_TYPE_BOOL) { code += "+"; }
- code += argname + ", ";
- if (!IsScalar(field.value.type.base_type)) {
- code += "0";
- } else if (HasNullDefault(field)) {
- if (IsLong(field.value.type.base_type)) {
- code += "builder.createLong(0, 0)";
- } else {
- code += "0";
- }
- } else {
- if (field.value.type.base_type == BASE_TYPE_BOOL) { code += "+"; }
- code += GenDefaultValue(field, "builder");
- }
- code += ");\n};\n\n";
-
- if (IsVector(field.value.type)) {
- auto vector_type = field.value.type.VectorType();
- auto alignment = InlineAlignment(vector_type);
- auto elem_size = InlineSize(vector_type);
-
- // Generate a method to create a vector from a JavaScript array
- if (!IsStruct(vector_type)) {
- GenDocComment(
- code_ptr,
- GenTypeAnnotation(kParam, "flatbuffers.Builder", "builder") +
- GenTypeAnnotation(
- kParam,
- "Array.<" + GenTypeName(vector_type, true) + ">",
- "data") +
- GenTypeAnnotation(kReturns, "flatbuffers.Offset", "",
- false));
-
- if (lang_.language == IDLOptions::kTs) {
- const std::string sig_begin =
- "static create" + MakeCamel(field.name) +
- "Vector(builder:flatbuffers.Builder, data:";
- const std::string sig_end = "):flatbuffers.Offset";
- std::string type = GenTypeName(vector_type, true) + "[]";
- if (type == "number[]") {
- const auto &array_type = GenType(vector_type);
- // the old type should be deprecated in the future
- std::string type_old = "number[]|Uint8Array";
- std::string type_new = "number[]|" + array_type + "Array";
- if (type_old == type_new) {
- type = type_new;
- } else {
- // add function overloads
- code += sig_begin + type_new + sig_end + ";\n";
- code +=
- "/**\n * @deprecated This Uint8Array overload will "
- "be removed in the future.\n */\n";
- code += sig_begin + type_old + sig_end + ";\n";
- type = type_new + "|Uint8Array";
- }
- } else {
- if (vector_type.enum_def) {
- if (!parser_.opts.generate_all) {
- imported_files.insert(vector_type.enum_def->file);
- }
-
- type = GenPrefixedTypeName(type, vector_type.enum_def->file);
- }
- }
- code += sig_begin + type + sig_end + " {\n";
- } else {
- code += object_name + ".create" + MakeCamel(field.name);
- code += "Vector = function(builder, data) {\n";
- }
-
- code += " builder.startVector(" + NumToString(elem_size);
- code += ", data.length, " + NumToString(alignment) + ");\n";
- code += " for (var i = data.length - 1; i >= 0; i--) {\n";
- code += " builder.add" + GenWriteMethod(vector_type) + "(";
- if (vector_type.base_type == BASE_TYPE_BOOL) { code += "+"; }
- code += "data[i]);\n";
- code += " }\n";
- code += " return builder.endVector();\n";
- code += "};\n\n";
- }
-
- // Generate a method to start a vector, data to be added manually
- // after
- GenDocComment(
- code_ptr,
- GenTypeAnnotation(kParam, "flatbuffers.Builder", "builder") +
- GenTypeAnnotation(kParam, "number", "numElems", false));
-
- if (lang_.language == IDLOptions::kTs) {
- code += "static start" + MakeCamel(field.name);
- code += "Vector(builder:flatbuffers.Builder, numElems:number) {\n";
- } else {
- code += object_name + ".start" + MakeCamel(field.name);
- code += "Vector = function(builder, numElems) {\n";
- }
-
- code += " builder.startVector(" + NumToString(elem_size);
- code += ", numElems, " + NumToString(alignment) + ");\n";
- code += "};\n\n";
- }
- }
-
- // Generate a method to stop building a new object
- GenDocComment(
- code_ptr,
- GenTypeAnnotation(kParam, "flatbuffers.Builder", "builder") +
- GenTypeAnnotation(kReturns, "flatbuffers.Offset", "", false));
-
- if (lang_.language == IDLOptions::kTs) {
- code += "static end" + Verbose(struct_def);
- code += "(builder:flatbuffers.Builder):flatbuffers.Offset {\n";
- } else {
- code += object_name + ".end" + Verbose(struct_def);
- code += " = function(builder) {\n";
- }
-
- code += " var offset = builder.endObject();\n";
- for (auto it = struct_def.fields.vec.begin();
- it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
- if (!field.deprecated && field.required) {
- code += " builder.requiredField(offset, ";
- code += NumToString(field.value.offset);
- code += "); // " + field.name + "\n";
- }
- }
- code += " return offset;\n";
- code += "};\n\n";
-
- // Generate the methods to complete buffer construction
- GenerateFinisher(struct_def, code_ptr, code, object_name, false);
- GenerateFinisher(struct_def, code_ptr, code, object_name, true);
-
- // Generate a convenient CreateX function
- if (CanCreateFactoryMethod(struct_def)) {
- if (lang_.language == IDLOptions::kJs) {
- std::string paramDoc =
- GenTypeAnnotation(kParam, "flatbuffers.Builder", "builder");
- for (auto it = struct_def.fields.vec.begin();
- it != struct_def.fields.vec.end(); ++it) {
- const auto &field = **it;
- if (field.deprecated) continue;
- paramDoc +=
- GenTypeAnnotation(kParam, GetArgType(field, true), GetArgName(field));
- }
- paramDoc +=
- GenTypeAnnotation(kReturns, "flatbuffers.Offset", "", false);
-
- GenDocComment(code_ptr, paramDoc);
- }
-
- if (lang_.language == IDLOptions::kTs) {
- code += "static create" + Verbose(struct_def);
- code += "(builder:flatbuffers.Builder";
- } else {
- code += object_name + ".create" + Verbose(struct_def);
- code += " = function(builder";
- }
- for (auto it = struct_def.fields.vec.begin();
- it != struct_def.fields.vec.end(); ++it) {
- const auto &field = **it;
- if (field.deprecated) continue;
-
- if (lang_.language == IDLOptions::kTs) {
- code += ", " + GetArgName(field) + ":" + GetArgType(field, true);
- } else {
- code += ", " + GetArgName(field);
- }
- }
-
- if (lang_.language == IDLOptions::kTs) {
- code += "):flatbuffers.Offset {\n";
- code += " " + struct_def.name + ".start" + Verbose(struct_def) +
- "(builder);\n";
- } else {
- code += ") {\n";
- code += " " + object_name + ".start" + Verbose(struct_def) +
- "(builder);\n";
- }
-
- std::string methodPrefix =
- lang_.language == IDLOptions::kTs ? struct_def.name : object_name;
- for (auto it = struct_def.fields.vec.begin();
- it != struct_def.fields.vec.end(); ++it) {
- const auto &field = **it;
- if (field.deprecated) continue;
-
- const auto arg_name = GetArgName(field);
-
- if (field.IsScalarOptional()) {
- code += " if (" + arg_name + " !== null)\n ";
- }
-
- code += " " + methodPrefix + ".add" + MakeCamel(field.name) + "(";
- code += "builder, " + arg_name + ");\n";
- }
-
- code += " return " + methodPrefix + ".end" + Verbose(struct_def) +
- "(builder);\n";
- code += "}\n";
- if (lang_.language == IDLOptions::kJs) code += "\n";
- }
- }
-
- if (!struct_def.fixed && parser_.services_.vec.size() != 0 &&
- lang_.language == IDLOptions::kTs) {
- auto name = Verbose(struct_def, "");
- code += "\n";
- code += "serialize():Uint8Array {\n";
- code += " return this.bb!.bytes();\n";
- code += "}\n";
-
- code += "\n";
- code += "static deserialize(buffer: Uint8Array):"+ name +" {\n";
- code += " return " + name + ".getRootAs" + name +
- "(new flatbuffers.ByteBuffer(buffer))\n";
- code += "}\n";
- }
-
- if (lang_.language == IDLOptions::kTs) {
- if (parser_.opts.generate_object_based_api) {
- std::string obj_api_class;
- std::string obj_api_unpack_func;
- GenObjApi(parser_, struct_def, obj_api_unpack_func, obj_api_class,
- imported_files);
-
- code += obj_api_unpack_func + "}\n" + obj_api_class;
- } else {
- code += "}\n";
- }
- if (!object_namespace.empty()) { code += "}\n"; }
- }
- }
-
- static bool HasNullDefault(const FieldDef &field) {
- return field.optional && field.value.constant == "null";
- }
-
- std::string GetArgType(const FieldDef &field, bool allowNull) {
- auto type_name = GenTypeName(field.value.type, true, allowNull && field.optional);
-
- if (field.value.type.enum_def) {
- if (IsScalar(field.value.type.base_type)) {
- return GenPrefixedTypeName(type_name, field.value.type.enum_def->file);
- }
- }
-
- return type_name;
- }
-
- static std::string GetArgName(const FieldDef &field) {
- auto argname = MakeCamel(field.name, false);
- if (!IsScalar(field.value.type.base_type)) { argname += "Offset"; }
-
- return argname;
- }
-
- std::string Verbose(const StructDef &struct_def, const char *prefix = "") {
- return parser_.opts.js_ts_short_names ? "" : prefix + struct_def.name;
- }
-}; // namespace jsts
-} // namespace jsts
-
-bool GenerateJSTS(const Parser &parser, const std::string &path,
- const std::string &file_name) {
- jsts::JsTsGenerator generator(parser, path, file_name);
- return generator.generate();
-}
-
-std::string JSTSMakeRule(const Parser &parser, const std::string &path,
- const std::string &file_name) {
- FLATBUFFERS_ASSERT(parser.opts.lang <= IDLOptions::kMAX);
-
- std::string filebase =
- flatbuffers::StripPath(flatbuffers::StripExtension(file_name));
- jsts::JsTsGenerator generator(parser, path, file_name);
- std::string make_rule =
- generator.GeneratedFileName(path, filebase, parser.opts) + ": ";
-
- auto included_files = parser.GetIncludedFilesRecursive(file_name);
- for (auto it = included_files.begin(); it != included_files.end(); ++it) {
- make_rule += " " + *it;
- }
- return make_rule;
-}
-
-} // namespace flatbuffers
diff --git a/src/idl_gen_json_schema.cpp b/src/idl_gen_json_schema.cpp
index 76540d1..9ea37ae 100644
--- a/src/idl_gen_json_schema.cpp
+++ b/src/idl_gen_json_schema.cpp
@@ -49,10 +49,10 @@
return "\"type\" : \"integer\", \"minimum\" : " +
NumToString(std::numeric_limits<int8_t>::min()) +
", \"maximum\" : " +
- NumToString(std::numeric_limits<int8_t>::max()) + "\"";
+ NumToString(std::numeric_limits<int8_t>::max());
case BASE_TYPE_UCHAR:
return "\"type\" : \"integer\", \"minimum\" : 0, \"maximum\" :" +
- NumToString(std::numeric_limits<uint8_t>::max()) + "\"";
+ NumToString(std::numeric_limits<uint8_t>::max());
case BASE_TYPE_SHORT:
return "\"type\" : \"integer\", \"minimum\" : " +
NumToString(std::numeric_limits<int16_t>::min()) +
@@ -166,9 +166,45 @@
return std::string(num_spaces, ' ');
}
+ std::string PrepareDescription(
+ const std::vector<std::string> &comment_lines) {
+ std::string comment;
+ for (auto line_iterator = comment_lines.cbegin();
+ line_iterator != comment_lines.cend(); ++line_iterator) {
+ const auto &comment_line = *line_iterator;
+
+ // remove leading and trailing spaces from comment line
+ const auto start = std::find_if(comment_line.begin(), comment_line.end(),
+ [](char c) { return !isspace(c); });
+ const auto end =
+ std::find_if(comment_line.rbegin(), comment_line.rend(), [](char c) {
+ return !isspace(c);
+ }).base();
+ if (start < end) {
+ comment.append(start, end);
+ } else {
+ comment.append(comment_line);
+ }
+
+ if (line_iterator + 1 != comment_lines.cend()) comment.append("\n");
+ }
+ if (!comment.empty()) {
+ std::string description;
+ if (EscapeString(comment.c_str(), comment.length(), &description, true,
+ true)) {
+ return description;
+ }
+ return "";
+ }
+ return "";
+ }
+
bool generate() {
code_ = "";
- if (parser_.root_struct_def_ == nullptr) { return false; }
+ if (parser_.root_struct_def_ == nullptr) {
+ std::cerr << "Error: Binary schema not generated, no root struct found\n";
+ return false;
+ }
code_ += "{" + NewLine();
code_ += Indent(1) +
"\"$schema\": \"https://json-schema.org/draft/2019-09/schema\"," +
@@ -193,21 +229,12 @@
const auto &structure = *s;
code_ += Indent(2) + "\"" + GenFullName(structure) + "\" : {" + NewLine();
code_ += Indent(3) + GenType("object") + "," + NewLine();
- std::string comment;
const auto &comment_lines = structure->doc_comment;
- for (auto comment_line = comment_lines.cbegin();
- comment_line != comment_lines.cend(); ++comment_line) {
- comment.append(*comment_line);
+ auto comment = PrepareDescription(comment_lines);
+ if (comment != "") {
+ code_ += Indent(3) + "\"description\" : " + comment + "," + NewLine();
}
- if (!comment.empty()) {
- std::string description;
- if (!EscapeString(comment.c_str(), comment.length(), &description, true,
- true)) {
- return false;
- }
- code_ +=
- Indent(3) + "\"description\" : " + description + "," + NewLine();
- }
+
code_ += Indent(3) + "\"properties\" : {" + NewLine();
const auto &properties = structure->fields.vec;
@@ -223,13 +250,19 @@
std::string deprecated_info = "";
if (property->deprecated) {
deprecated_info =
- "," + NewLine() + Indent(8) + "\"deprecated\" : true,";
+ "," + NewLine() + Indent(8) + "\"deprecated\" : true";
}
std::string typeLine = Indent(4) + "\"" + property->name + "\"";
typeLine += " : {" + NewLine() + Indent(8);
typeLine += GenType(property->value.type);
typeLine += arrayInfo;
typeLine += deprecated_info;
+ auto description = PrepareDescription(property->doc_comment);
+ if (description != "") {
+ typeLine +=
+ "," + NewLine() + Indent(8) + "\"description\" : " + description;
+ }
+
typeLine += NewLine() + Indent(7) + "}";
if (property != properties.back()) { typeLine.append(","); }
code_ += typeLine + NewLine();
@@ -239,7 +272,7 @@
std::vector<FieldDef *> requiredProperties;
std::copy_if(properties.begin(), properties.end(),
back_inserter(requiredProperties),
- [](FieldDef const *prop) { return prop->required; });
+ [](FieldDef const *prop) { return prop->IsRequired(); });
if (!requiredProperties.empty()) {
auto required_string(Indent(3) + "\"required\" : [");
for (auto req_prop = requiredProperties.cbegin();
@@ -268,8 +301,7 @@
}
bool save() const {
- const auto file_path =
- GeneratedFileName(path_, file_name_, parser_.opts);
+ const auto file_path = GeneratedFileName(path_, file_name_, parser_.opts);
return SaveFile(file_path.c_str(), code_, false);
}
diff --git a/src/idl_gen_kotlin.cpp b/src/idl_gen_kotlin.cpp
index ed85b2c..fc55aeb 100644
--- a/src/idl_gen_kotlin.cpp
+++ b/src/idl_gen_kotlin.cpp
@@ -23,9 +23,6 @@
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
-#if defined(FLATBUFFERS_CPP98_STL)
-# include <cctype>
-#endif // defined(FLATBUFFERS_CPP98_STL)
namespace flatbuffers {
@@ -49,10 +46,12 @@
// Escape Keywords
static std::string Esc(const std::string &name) {
for (size_t i = 0; i < sizeof(keywords) / sizeof(keywords[0]); i++) {
- if (name == keywords[i]) { return MakeCamel(name + "_", false); }
+ if (name == keywords[i]) {
+ return ConvertCase(name + "_", Case::kLowerCamel);
+ }
}
- return MakeCamel(name, false);
+ return ConvertCase(name, Case::kLowerCamel);
}
class KotlinGenerator : public BaseGenerator {
@@ -262,7 +261,6 @@
GenerateComment(enum_def.doc_comment, writer, &comment_config);
writer += "@Suppress(\"unused\")";
- writer += "@ExperimentalUnsignedTypes";
writer += "class " + Esc(enum_def.name) + " private constructor() {";
writer.IncrementIdentLevel();
@@ -341,7 +339,8 @@
case BASE_TYPE_UTYPE: return bb_var_name + ".get";
case BASE_TYPE_BOOL: return "0.toByte() != " + bb_var_name + ".get";
default:
- return bb_var_name + ".get" + MakeCamel(GenTypeBasic(type.base_type));
+ return bb_var_name + ".get" +
+ ConvertCase(GenTypeBasic(type.base_type), Case::kUpperCamel);
}
}
@@ -361,7 +360,9 @@
case BASE_TYPE_BOOL:
case BASE_TYPE_NONE:
case BASE_TYPE_UTYPE: return "bb.put";
- default: return "bb.put" + MakeCamel(GenTypeBasic(type.base_type));
+ default:
+ return "bb.put" +
+ ConvertCase(GenTypeBasic(type.base_type), Case::kUpperCamel);
}
}
return "";
@@ -398,7 +399,7 @@
(nameprefix + (field.name + "_")).c_str());
} else {
writer += std::string(", ") + nameprefix + "\\";
- writer += MakeCamel(field.name) + ": \\";
+ writer += ConvertCase(field.name, Case::kUpperCamel) + ": \\";
writer += GenTypeBasic(field.value.type.base_type) + "\\";
}
}
@@ -425,7 +426,8 @@
(nameprefix + (field.name + "_")).c_str());
} else {
writer.SetValue("type", GenMethod(field.value.type));
- writer.SetValue("argname", nameprefix + MakeCamel(field.name, false));
+ writer.SetValue("argname", nameprefix + ConvertCase(Esc(field.name),
+ Case::kLowerCamel));
writer.SetValue("cast", CastToSigned(field.value.type));
writer += "builder.put{{type}}({{argname}}{{cast}})";
}
@@ -463,7 +465,6 @@
writer.SetValue("superclass", fixed ? "Struct" : "Table");
writer += "@Suppress(\"unused\")";
- writer += "@ExperimentalUnsignedTypes";
writer += "class {{struct_name}} : {{superclass}}() {\n";
writer.IncrementIdentLevel();
@@ -494,7 +495,7 @@
// runtime.
GenerateFunOneLine(
writer, "validateVersion", "", "",
- [&]() { writer += "Constants.FLATBUFFERS_1_12_0()"; },
+ [&]() { writer += "Constants.FLATBUFFERS_2_0_0()"; },
options.gen_jvmstatic);
GenerateGetRootAsAccessors(Esc(struct_def.name), writer, options);
@@ -646,7 +647,7 @@
writer.IncrementIdentLevel();
for (auto it = field_vec.begin(); it != field_vec.end(); ++it) {
auto &field = **it;
- if (field.deprecated || !field.required) { continue; }
+ if (field.deprecated || !field.IsRequired()) { continue; }
writer.SetValue("offset", NumToString(field.value.offset));
writer += "builder.required(o, {{offset}})";
}
@@ -660,7 +661,8 @@
void GenerateCreateVectorField(FieldDef &field, CodeWriter &writer,
const IDLOptions options) const {
auto vector_type = field.value.type.VectorType();
- auto method_name = "create" + MakeCamel(Esc(field.name)) + "Vector";
+ auto method_name =
+ "create" + ConvertCase(Esc(field.name), Case::kUpperCamel) + "Vector";
auto params = "builder: FlatBufferBuilder, data: " +
GenTypeBasic(vector_type.base_type) + "Array";
writer.SetValue("size", NumToString(InlineSize(vector_type)));
@@ -692,8 +694,9 @@
writer.SetValue("align", NumToString(InlineAlignment(vector_type)));
GenerateFunOneLine(
- writer, "start" + MakeCamel(Esc(field.name) + "Vector", true), params,
- "",
+ writer,
+ "start" + ConvertCase(Esc(field.name) + "Vector", Case::kUpperCamel),
+ params, "",
[&]() {
writer += "builder.startVector({{size}}, numElems, {{align}})";
},
@@ -703,14 +706,16 @@
void GenerateAddField(std::string field_pos, FieldDef &field,
CodeWriter &writer, const IDLOptions options) const {
auto field_type = GenTypeBasic(field.value.type.base_type);
- auto secondArg = MakeCamel(Esc(field.name), false) + ": " + field_type;
+ auto secondArg =
+ ConvertCase(Esc(field.name), Case::kLowerCamel) + ": " + field_type;
GenerateFunOneLine(
- writer, "add" + MakeCamel(Esc(field.name), true),
+ writer, "add" + ConvertCase(Esc(field.name), Case::kUpperCamel),
"builder: FlatBufferBuilder, " + secondArg, "",
[&]() {
auto method = GenMethod(field.value.type);
- writer.SetValue("field_name", MakeCamel(Esc(field.name), false));
+ writer.SetValue("field_name",
+ ConvertCase(Esc(field.name), Case::kLowerCamel));
writer.SetValue("method_name", method);
writer.SetValue("pos", field_pos);
writer.SetValue("default", GenFBBDefaultValue(field));
@@ -801,7 +806,7 @@
for (auto it = fields_vec.begin(); it != fields_vec.end(); ++it) {
auto &field = **it;
if (field.deprecated) continue;
- params << ", " << MakeCamel(Esc(field.name), false);
+ params << ", " << ConvertCase(Esc(field.name), Case::kLowerCamel);
if (!IsScalar(field.value.type.base_type)) {
params << "Offset: ";
} else {
@@ -827,10 +832,11 @@
auto base_type_size = SizeOf(field.value.type.base_type);
if (!field.deprecated &&
(!sortbysize || size == base_type_size)) {
- writer.SetValue("camel_field_name",
- MakeCamel(Esc(field.name), true));
- writer.SetValue("field_name",
- MakeCamel(Esc(field.name), false));
+ writer.SetValue(
+ "camel_field_name",
+ ConvertCase(Esc(field.name), Case::kUpperCamel));
+ writer.SetValue("field_name", ConvertCase(Esc(field.name),
+ Case::kLowerCamel));
// we wrap on null check for scalar optionals
writer += field.IsScalarOptional()
@@ -857,7 +863,7 @@
// Check if a buffer has the identifier.
if (parser_.root_struct_def_ != &struct_def || !file_identifier.length())
return;
- auto name = MakeCamel(Esc(struct_def.name), false);
+ auto name = ConvertCase(Esc(struct_def.name), Case::kLowerCamel);
GenerateFunOneLine(
writer, name + "BufferHasIdentifier", "_bb: ByteBuffer", "Boolean",
[&]() {
@@ -876,7 +882,7 @@
GenerateComment(field.doc_comment, writer, &comment_config);
- auto field_name = MakeCamel(Esc(field.name), false);
+ auto field_name = ConvertCase(Esc(field.name), Case::kLowerCamel);
auto field_type = GenTypeGet(field.value.type);
auto field_default_value = GenDefaultValue(field);
auto return_type = GetterReturnType(field);
@@ -1047,7 +1053,8 @@
auto &kfield = **kit;
if (kfield.key) {
auto qualified_name = WrapInNameSpace(sd);
- auto name = MakeCamel(Esc(field.name), false) + "ByKey";
+ auto name =
+ ConvertCase(Esc(field.name), Case::kLowerCamel) + "ByKey";
auto params = "key: " + GenTypeGet(kfield.value.type);
auto rtype = qualified_name + "?";
GenerateFun(writer, name, params, rtype, [&]() {
@@ -1140,7 +1147,7 @@
auto underlying_type = value_base_type == BASE_TYPE_VECTOR
? value_type.VectorType()
: value_type;
- auto name = "mutate" + MakeCamel(Esc(field.name), true);
+ auto name = "mutate" + ConvertCase(Esc(field.name), Case::kUpperCamel);
auto size = NumToString(InlineSize(underlying_type));
auto params = Esc(field.name) + ": " + GenTypeGet(underlying_type);
// A vector mutator also needs the index of the vector element it should
@@ -1343,8 +1350,8 @@
out << StructConstructorParams(*field.value.type.struct_def,
prefix + (Esc(field.name) + "_"));
} else {
- out << ", " << prefix << MakeCamel(Esc(field.name), false) << ": "
- << GenTypeBasic(field.value.type.base_type);
+ out << ", " << prefix << ConvertCase(Esc(field.name), Case::kLowerCamel)
+ << ": " << GenTypeBasic(field.value.type.base_type);
}
}
return out.str();
diff --git a/src/idl_gen_lobster.cpp b/src/idl_gen_lobster.cpp
index 4ebf8ca..c1e78ad 100644
--- a/src/idl_gen_lobster.cpp
+++ b/src/idl_gen_lobster.cpp
@@ -60,7 +60,10 @@
std::string GenTypeName(const Type &type) {
auto bits = NumToString(SizeOf(type.base_type) * 8);
- if (IsInteger(type.base_type)) return "int" + bits;
+ if (IsInteger(type.base_type)) {
+ if (IsUnsigned(type.base_type)) return "uint" + bits;
+ else return "int" + bits;
+ }
if (IsFloat(type.base_type)) return "float" + bits;
if (IsString(type)) return "string";
if (type.base_type == BASE_TYPE_STRUCT) return "table";
@@ -78,7 +81,7 @@
// Returns the method name for use with add/put calls.
std::string GenMethod(const Type &type) {
return IsScalar(type.base_type)
- ? MakeCamel(GenTypeBasic(type))
+ ? ConvertCase(GenTypeBasic(type), Case::kUpperCamel)
: (IsStruct(type) ? "Struct" : "UOffsetTRelative");
}
@@ -110,13 +113,13 @@
offsets + ")";
} else {
- auto defval = field.optional ? "0" : field.value.constant;
+ auto defval = field.IsOptional() ? "0" : field.value.constant;
acc = "buf_.flatbuffers_field_" + GenTypeName(field.value.type) +
"(pos_, " + offsets + ", " + defval + ")";
}
if (field.value.type.enum_def)
acc = NormalizedName(*field.value.type.enum_def) + "(" + acc + ")";
- if (field.optional)
+ if (field.IsOptional())
acc += ", buf_.flatbuffers_field_present(pos_, " + offsets + ")";
code += def + "():\n return " + acc + "\n";
return;
@@ -201,7 +204,7 @@
NormalizedName(field) + ":" + LobsterType(field.value.type) +
"):\n b_.Prepend" + GenMethod(field.value.type) + "Slot(" +
NumToString(offset) + ", " + NormalizedName(field);
- if (IsScalar(field.value.type.base_type) && !field.optional)
+ if (IsScalar(field.value.type.base_type) && !field.IsOptional())
code += ", " + field.value.constant;
code += ")\n return this\n";
}
@@ -212,7 +215,7 @@
if (field.deprecated) continue;
if (IsVector(field.value.type)) {
code += "def " + NormalizedName(struct_def) + "Start" +
- MakeCamel(NormalizedName(field)) +
+ ConvertCase(NormalizedName(field), Case::kUpperCamel) +
"Vector(b_:flatbuffers_builder, n_:int):\n b_.StartVector(";
auto vector_type = field.value.type.VectorType();
auto alignment = InlineAlignment(vector_type);
@@ -222,7 +225,7 @@
if (vector_type.base_type != BASE_TYPE_STRUCT ||
!vector_type.struct_def->fixed) {
code += "def " + NormalizedName(struct_def) + "Create" +
- MakeCamel(NormalizedName(field)) +
+ ConvertCase(NormalizedName(field), Case::kUpperCamel) +
"Vector(b_:flatbuffers_builder, v_:[" +
LobsterType(vector_type) + "]):\n b_.StartVector(" +
NumToString(elem_size) + ", v_.length, " +
diff --git a/src/idl_gen_lua.cpp b/src/idl_gen_lua.cpp
index 9788485..7be0015 100644
--- a/src/idl_gen_lua.cpp
+++ b/src/idl_gen_lua.cpp
@@ -124,6 +124,10 @@
code += "function " + NormalizedName(struct_def) + ".GetRootAs" +
NormalizedName(struct_def) + "(buf, offset)\n";
+ code += std::string(Indent) + "if type(buf) == \"string\" then\n";
+ code += std::string(Indent) + Indent +
+ "buf = flatbuffers.binaryArray.New(buf)\n";
+ code += std::string(Indent) + "end\n";
code += std::string(Indent) +
"local n = flatbuffers.N.UOffsetT:Unpack(buf, offset)\n";
code += std::string(Indent) + "local o = " + NormalizedName(struct_def) +
@@ -150,7 +154,8 @@
std::string &code = *code_ptr;
GenReceiver(struct_def, code_ptr);
- code += MakeCamel(NormalizedName(field)) + "Length()\n";
+ code +=
+ ConvertCase(NormalizedName(field), Case::kUpperCamel) + "Length()\n";
code += OffsetPrefix(field);
code +=
std::string(Indent) + Indent + "return " + SelfData + ":VectorLen(o)\n";
@@ -165,7 +170,7 @@
std::string &code = *code_ptr;
std::string getter = GenGetter(field.value.type);
GenReceiver(struct_def, code_ptr);
- code += MakeCamel(NormalizedName(field));
+ code += ConvertCase(NormalizedName(field), Case::kUpperCamel);
code += "()\n";
code += std::string(Indent) + "return " + getter;
code += std::string(SelfDataPos) + " + " + NumToString(field.value.offset) +
@@ -179,7 +184,7 @@
std::string &code = *code_ptr;
std::string getter = GenGetter(field.value.type);
GenReceiver(struct_def, code_ptr);
- code += MakeCamel(NormalizedName(field));
+ code += ConvertCase(NormalizedName(field), Case::kUpperCamel);
code += "()\n";
code += OffsetPrefix(field);
getter += std::string("o + ") + SelfDataPos + ")";
@@ -203,7 +208,7 @@
const FieldDef &field, std::string *code_ptr) {
std::string &code = *code_ptr;
GenReceiver(struct_def, code_ptr);
- code += MakeCamel(NormalizedName(field));
+ code += ConvertCase(NormalizedName(field), Case::kUpperCamel);
code += "(obj)\n";
code += std::string(Indent) + "obj:Init(" + SelfDataBytes + ", " +
SelfDataPos + " + ";
@@ -218,7 +223,7 @@
std::string *code_ptr) {
std::string &code = *code_ptr;
GenReceiver(struct_def, code_ptr);
- code += MakeCamel(NormalizedName(field));
+ code += ConvertCase(NormalizedName(field), Case::kUpperCamel);
code += "()\n";
code += OffsetPrefix(field);
if (field.value.type.struct_def->fixed) {
@@ -242,7 +247,7 @@
std::string *code_ptr) {
std::string &code = *code_ptr;
GenReceiver(struct_def, code_ptr);
- code += MakeCamel(NormalizedName(field));
+ code += ConvertCase(NormalizedName(field), Case::kUpperCamel);
code += "()\n";
code += OffsetPrefix(field);
code +=
@@ -257,7 +262,7 @@
std::string *code_ptr) {
std::string &code = *code_ptr;
GenReceiver(struct_def, code_ptr);
- code += MakeCamel(NormalizedName(field)) + "()\n";
+ code += ConvertCase(NormalizedName(field), Case::kUpperCamel) + "()\n";
code += OffsetPrefix(field);
// TODO(rw): this works and is not the good way to it:
@@ -288,7 +293,7 @@
auto vectortype = field.value.type.VectorType();
GenReceiver(struct_def, code_ptr);
- code += MakeCamel(NormalizedName(field));
+ code += ConvertCase(NormalizedName(field), Case::kUpperCamel);
code += "(j)\n";
code += OffsetPrefix(field);
code +=
@@ -317,7 +322,7 @@
auto vectortype = field.value.type.VectorType();
GenReceiver(struct_def, code_ptr);
- code += MakeCamel(NormalizedName(field));
+ code += ConvertCase(NormalizedName(field), Case::kUpperCamel);
code += "(j)\n";
code += OffsetPrefix(field);
code +=
@@ -335,6 +340,18 @@
code += EndFunc;
}
+ // Access a byte/ubyte vector as a string
+ void AccessByteVectorAsString(const StructDef &struct_def,
+ const FieldDef &field, std::string *code_ptr) {
+ std::string &code = *code_ptr;
+ GenReceiver(struct_def, code_ptr);
+ code += ConvertCase(NormalizedName(field), Case::kUpperCamel);
+ code += "AsString(start, stop)\n";
+ code += std::string(Indent) + "return " + SelfData + ":VectorAsString(" +
+ NumToString(field.value.offset) + ", start, stop)\n";
+ code += EndFunc;
+ }
+
// Begin the creator function signature.
void BeginBuilderArgs(const StructDef &struct_def, std::string *code_ptr) {
std::string &code = *code_ptr;
@@ -361,7 +378,7 @@
} else {
std::string &code = *code_ptr;
code += std::string(", ") + nameprefix;
- code += MakeCamel(NormalizedName(field), false);
+ code += ConvertCase(NormalizedName(field), Case::kLowerCamel);
}
}
}
@@ -393,7 +410,8 @@
} else {
code +=
std::string(Indent) + "builder:Prepend" + GenMethod(field) + "(";
- code += nameprefix + MakeCamel(NormalizedName(field), false) + ")\n";
+ code += nameprefix +
+ ConvertCase(NormalizedName(field), Case::kLowerCamel) + ")\n";
}
}
}
@@ -419,9 +437,9 @@
const size_t offset, std::string *code_ptr) {
std::string &code = *code_ptr;
code += "function " + NormalizedName(struct_def) + ".Add" +
- MakeCamel(NormalizedName(field));
+ ConvertCase(NormalizedName(field), Case::kUpperCamel);
code += "(builder, ";
- code += MakeCamel(NormalizedName(field), false);
+ code += ConvertCase(NormalizedName(field), Case::kLowerCamel);
code += ") ";
code += "builder:Prepend";
code += GenMethod(field) + "Slot(";
@@ -430,9 +448,9 @@
// if (!IsScalar(field.value.type.base_type) && (!struct_def.fixed)) {
// code += "flatbuffers.N.UOffsetTFlags.py_type";
// code += "(";
- // code += MakeCamel(NormalizedName(field), false) + ")";
+ // code += ConvertCase(NormalizedName(field), Case::kLowerCamel) + ")";
// } else {
- code += MakeCamel(NormalizedName(field), false);
+ code += ConvertCase(NormalizedName(field), Case::kLowerCamel);
// }
code += ", " + field.value.constant;
code += ") end\n";
@@ -443,7 +461,7 @@
std::string *code_ptr) {
std::string &code = *code_ptr;
code += "function " + NormalizedName(struct_def) + ".Start";
- code += MakeCamel(NormalizedName(field));
+ code += ConvertCase(NormalizedName(field), Case::kUpperCamel);
code += "Vector(builder, numElems) return builder:StartVector(";
auto vector_type = field.value.type.VectorType();
auto alignment = InlineAlignment(vector_type);
@@ -495,6 +513,10 @@
GetMemberOfVectorOfStruct(struct_def, field, code_ptr);
} else {
GetMemberOfVectorOfNonStruct(struct_def, field, code_ptr);
+ if (vectortype.base_type == BASE_TYPE_CHAR ||
+ vectortype.base_type == BASE_TYPE_UCHAR) {
+ AccessByteVectorAsString(struct_def, field, code_ptr);
+ }
}
break;
}
@@ -583,14 +605,14 @@
case BASE_TYPE_VECTOR: return GenGetter(type.VectorType());
default:
return std::string(SelfData) + ":Get(flatbuffers.N." +
- MakeCamel(GenTypeGet(type)) + ", ";
+ ConvertCase(GenTypeGet(type), Case::kUpperCamel) + ", ";
}
}
// Returns the method name for use with add/put calls.
std::string GenMethod(const FieldDef &field) {
return IsScalar(field.value.type.base_type)
- ? MakeCamel(GenTypeBasic(field.value.type))
+ ? ConvertCase(GenTypeBasic(field.value.type), Case::kUpperCamel)
: (IsStruct(field.value.type) ? "Struct" : "UOffsetTRelative");
}
diff --git a/src/idl_gen_php.cpp b/src/idl_gen_php.cpp
index b986fe3..5896935 100644
--- a/src/idl_gen_php.cpp
+++ b/src/idl_gen_php.cpp
@@ -181,7 +181,7 @@
code += Indent + " * @return int\n";
code += Indent + " */\n";
code += Indent + "public function get";
- code += MakeCamel(field.name) + "Length()\n";
+ code += ConvertCase(field.name, Case::kUpperCamel) + "Length()\n";
code += Indent + "{\n";
code += Indent + Indent + "$o = $this->__offset(";
code += NumToString(field.value.offset) + ");\n";
@@ -198,7 +198,7 @@
code += Indent + " * @return string\n";
code += Indent + " */\n";
code += Indent + "public function get";
- code += MakeCamel(field.name) + "Bytes()\n";
+ code += ConvertCase(field.name, Case::kUpperCamel) + "Bytes()\n";
code += Indent + "{\n";
code += Indent + Indent + "return $this->__vector_as_bytes(";
code += NumToString(field.value.offset) + ");\n";
@@ -216,12 +216,12 @@
code += GenTypeGet(field.value.type) + "\n";
code += Indent + " */\n";
code += Indent + "public function " + getter;
- code += MakeCamel(field.name) + "()\n";
+ code += ConvertCase(field.name, Case::kUpperCamel) + "()\n";
code += Indent + "{\n";
code += Indent + Indent + "return ";
code += "$this->bb->get";
- code += MakeCamel(GenTypeGet(field.value.type));
+ code += ConvertCase(GenTypeGet(field.value.type), Case::kUpperCamel);
code += "($this->bb_pos + ";
code += NumToString(field.value.offset) + ")";
code += ";\n";
@@ -237,14 +237,15 @@
code += Indent + " * @return " + GenTypeGet(field.value.type) + "\n";
code += Indent + " */\n";
code += Indent + "public function get";
- code += MakeCamel(field.name);
+ code += ConvertCase(field.name, Case::kUpperCamel);
code += "()\n";
code += Indent + "{\n";
code += Indent + Indent + "$o = $this->__offset(" +
NumToString(field.value.offset) + ");\n" + Indent + Indent +
"return $o != 0 ? ";
code += "$this->bb->get";
- code += MakeCamel(GenTypeGet(field.value.type)) + "($o + $this->bb_pos)";
+ code += ConvertCase(GenTypeGet(field.value.type), Case::kUpperCamel) +
+ "($o + $this->bb_pos)";
code += " : " + GenDefaultValue(field.value) + ";\n";
code += Indent + "}\n\n";
}
@@ -258,7 +259,7 @@
code += Indent + " * @return " + GenTypeGet(field.value.type) + "\n";
code += Indent + " */\n";
code += Indent + "public function get";
- code += MakeCamel(field.name) + "()\n";
+ code += ConvertCase(field.name, Case::kUpperCamel) + "()\n";
code += Indent + "{\n";
code += Indent + Indent + "$obj = new ";
code += GenTypeGet(field.value.type) + "();\n";
@@ -274,11 +275,12 @@
std::string &code = *code_ptr;
code += Indent + "public function get";
- code += MakeCamel(field.name);
+ code += ConvertCase(field.name, Case::kUpperCamel);
code += "()\n";
code += Indent + "{\n";
code += Indent + Indent + "$obj = new ";
- code += MakeCamel(GenTypeGet(field.value.type)) + "();\n";
+ code +=
+ ConvertCase(GenTypeGet(field.value.type), Case::kUpperCamel) + "();\n";
code += Indent + Indent + "$o = $this->__offset(" +
NumToString(field.value.offset) + ");\n";
code += Indent + Indent;
@@ -296,7 +298,7 @@
void GetStringField(const FieldDef &field, std::string *code_ptr) {
std::string &code = *code_ptr;
code += Indent + "public function get";
- code += MakeCamel(field.name);
+ code += ConvertCase(field.name, Case::kUpperCamel);
code += "()\n";
code += Indent + "{\n";
code += Indent + Indent + "$o = $this->__offset(" +
@@ -315,7 +317,7 @@
code += Indent + " * @return" + GenTypeBasic(field.value.type) + "\n";
code += Indent + " */\n";
code += Indent + "public function get";
- code += MakeCamel(field.name) + "($obj)\n";
+ code += ConvertCase(field.name, Case::kUpperCamel) + "($obj)\n";
code += Indent + "{\n";
code += Indent + Indent + "$o = $this->__offset(" +
NumToString(field.value.offset) + ");\n";
@@ -334,13 +336,14 @@
code += Indent + " * @return" + GenTypeBasic(field.value.type) + "\n";
code += Indent + " */\n";
code += Indent + "public function get";
- code += MakeCamel(field.name);
+ code += ConvertCase(field.name, Case::kUpperCamel);
code += "($j)\n";
code += Indent + "{\n";
code += Indent + Indent + "$o = $this->__offset(" +
NumToString(field.value.offset) + ");\n";
code += Indent + Indent + "$obj = new ";
- code += MakeCamel(GenTypeGet(field.value.type)) + "();\n";
+ code +=
+ ConvertCase(GenTypeGet(field.value.type), Case::kUpperCamel) + "();\n";
switch (field.value.type.base_type) {
case BASE_TYPE_STRUCT:
@@ -395,7 +398,7 @@
code += Indent + " * @return " + GenTypeGet(field.value.type) + "\n";
code += Indent + " */\n";
code += Indent + "public function get";
- code += MakeCamel(field.name);
+ code += ConvertCase(field.name, Case::kUpperCamel);
code += "($j)\n";
code += Indent + "{\n";
code += Indent + Indent + "$o = $this->__offset(" +
@@ -408,7 +411,7 @@
code += GenDefaultValue(field.value) + ";\n";
} else {
code += Indent + Indent + "return $o != 0 ? $this->bb->get";
- code += MakeCamel(GenTypeGet(field.value.type));
+ code += ConvertCase(GenTypeGet(field.value.type), Case::kUpperCamel);
code += "($this->__vector($o) + $j * ";
code += NumToString(InlineSize(vectortype)) + ") : ";
code += GenDefaultValue(field.value) + ";\n";
@@ -427,7 +430,7 @@
code += Indent + " * @return " + GenTypeGet(field.value.type) + "\n";
code += Indent + " */\n";
code += Indent + "public function get";
- code += MakeCamel(field.name);
+ code += ConvertCase(field.name, Case::kUpperCamel);
code += "($j, $obj)\n";
code += Indent + "{\n";
code += Indent + Indent + "$o = $this->__offset(" +
@@ -455,7 +458,7 @@
} else {
std::string &code = *code_ptr;
code += std::string(", $") + nameprefix;
- code += MakeCamel(field.name, false);
+ code += ConvertCase(field.name, Case::kLowerCamel);
}
}
}
@@ -480,7 +483,8 @@
(nameprefix + (field.name + "_")).c_str(), code_ptr);
} else {
code += Indent + Indent + "$builder->put" + GenMethod(field) + "($";
- code += nameprefix + MakeCamel(field.name, false) + ");\n";
+ code +=
+ nameprefix + ConvertCase(field.name, Case::kLowerCamel) + ");\n";
}
}
}
@@ -528,7 +532,8 @@
if (field.deprecated) continue;
code += Indent + Indent + "self::add";
- code += MakeCamel(field.name) + "($builder, $" + field.name + ");\n";
+ code += ConvertCase(field.name, Case::kUpperCamel) + "($builder, $" +
+ field.name + ");\n";
}
code += Indent + Indent + "$o = $builder->endObject();\n";
@@ -536,7 +541,7 @@
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
- if (!field.deprecated && field.required) {
+ if (!field.deprecated && field.IsRequired()) {
code += Indent + Indent + "$builder->required($o, ";
code += NumToString(field.value.offset);
code += "); // " + field.name + "\n";
@@ -557,16 +562,16 @@
code += Indent + " * @return void\n";
code += Indent + " */\n";
code += Indent + "public static function ";
- code += "add" + MakeCamel(field.name);
+ code += "add" + ConvertCase(field.name, Case::kUpperCamel);
code += "(FlatBufferBuilder $builder, ";
- code += "$" + MakeCamel(field.name, false);
+ code += "$" + ConvertCase(field.name, Case::kLowerCamel);
code += ")\n";
code += Indent + "{\n";
code += Indent + Indent + "$builder->add";
code += GenMethod(field) + "X(";
code += NumToString(offset) + ", ";
- code += "$" + MakeCamel(field.name, false);
+ code += "$" + ConvertCase(field.name, Case::kLowerCamel);
code += ", ";
if (field.value.type.base_type == BASE_TYPE_BOOL) {
@@ -591,7 +596,7 @@
code += Indent + " * @return int vector offset\n";
code += Indent + " */\n";
code += Indent + "public static function create";
- code += MakeCamel(field.name);
+ code += ConvertCase(field.name, Case::kUpperCamel);
code += "Vector(FlatBufferBuilder $builder, array $data)\n";
code += Indent + "{\n";
code += Indent + Indent + "$builder->startVector(";
@@ -603,7 +608,8 @@
if (IsScalar(field.value.type.VectorType().base_type)) {
code += Indent + Indent + Indent;
code += "$builder->put";
- code += MakeCamel(GenTypeBasic(field.value.type.VectorType()));
+ code += ConvertCase(GenTypeBasic(field.value.type.VectorType()),
+ Case::kUpperCamel);
code += "($data[$i]);\n";
} else {
code += Indent + Indent + Indent;
@@ -619,7 +625,7 @@
code += Indent + " * @return void\n";
code += Indent + " */\n";
code += Indent + "public static function start";
- code += MakeCamel(field.name);
+ code += ConvertCase(field.name, Case::kUpperCamel);
code += "Vector(FlatBufferBuilder $builder, $numElems)\n";
code += Indent + "{\n";
code += Indent + Indent + "$builder->startVector(";
@@ -645,7 +651,7 @@
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
- if (!field.deprecated && field.required) {
+ if (!field.deprecated && field.IsRequired()) {
code += Indent + Indent + "$builder->required($o, ";
code += NumToString(field.value.offset);
code += "); // " + field.name + "\n";
@@ -726,7 +732,7 @@
if (field.value.type.base_type == BASE_TYPE_UNION) {
std::string &code = *code_ptr;
code += Indent + "public static function add";
- code += MakeCamel(field.name);
+ code += ConvertCase(field.name, Case::kUpperCamel);
code += "(FlatBufferBuilder $builder, $offset)\n";
code += Indent + "{\n";
code += Indent + Indent + "$builder->addOffsetX(";
@@ -735,9 +741,7 @@
} else {
BuildFieldOfTable(field, offset, code_ptr);
}
- if (IsVector(field.value.type)) {
- BuildVectorOfTable(field, code_ptr);
- }
+ if (IsVector(field.value.type)) { BuildVectorOfTable(field, code_ptr); }
}
GetEndOffsetOnTable(struct_def, code_ptr);
@@ -855,7 +859,7 @@
// Returns the method name for use with add/put calls.
static std::string GenMethod(const FieldDef &field) {
return IsScalar(field.value.type.base_type)
- ? MakeCamel(GenTypeBasic(field.value.type))
+ ? ConvertCase(GenTypeBasic(field.value.type), Case::kUpperCamel)
: (IsStruct(field.value.type) ? "Struct" : "Offset");
}
diff --git a/src/idl_gen_python.cpp b/src/idl_gen_python.cpp
index 1260673..8426b6e 100644
--- a/src/idl_gen_python.cpp
+++ b/src/idl_gen_python.cpp
@@ -26,10 +26,42 @@
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
+#include "namer.h"
namespace flatbuffers {
namespace python {
+std::set<std::string> PythonKeywords() {
+ return { "False", "None", "True", "and", "as", "assert",
+ "break", "class", "continue", "def", "del", "elif",
+ "else", "except", "finally", "for", "from", "global",
+ "if", "import", "in", "is", "lambda", "nonlocal",
+ "not", "or", "pass", "raise", "return", "try",
+ "while", "with", "yield" };
+}
+
+Namer::Config PythonDefaultConfig() {
+ return { /*types=*/Case::kKeep,
+ /*constants=*/Case::kScreamingSnake,
+ /*methods=*/Case::kUpperCamel,
+ /*functions=*/Case::kUpperCamel,
+ /*fields=*/Case::kLowerCamel,
+ /*variable=*/Case::kLowerCamel,
+ /*variants=*/Case::kKeep,
+ /*enum_variant_seperator=*/".",
+ /*namespaces=*/Case::kKeep, // Packages in python.
+ /*namespace_seperator=*/".",
+ /*object_prefix=*/"",
+ /*object_suffix=*/"T",
+ /*keyword_prefix=*/"",
+ /*keyword_suffix=*/"_",
+ /*filenames=*/Case::kKeep,
+ /*directories=*/Case::kKeep,
+ /*output_path=*/"",
+ /*filename_suffix=*/"",
+ /*filename_extension=*/".py" };
+}
+
// Hardcode spaces per indentation.
const CommentConfig def_comment = { nullptr, "#", nullptr };
const std::string Indent = " ";
@@ -40,20 +72,13 @@
const std::string &file_name)
: BaseGenerator(parser, path, file_name, "" /* not used */,
"" /* not used */, "py"),
- float_const_gen_("float('nan')", "float('inf')", "float('-inf')") {
- static const char *const keywords[] = {
- "False", "None", "True", "and", "as", "assert", "break",
- "class", "continue", "def", "del", "elif", "else", "except",
- "finally", "for", "from", "global", "if", "import", "in",
- "is", "lambda", "nonlocal", "not", "or", "pass", "raise",
- "return", "try", "while", "with", "yield"
- };
- keywords_.insert(std::begin(keywords), std::end(keywords));
- }
+ float_const_gen_("float('nan')", "float('inf')", "float('-inf')"),
+ namer_({ PythonDefaultConfig().WithFlagOptions(parser.opts, path),
+ PythonKeywords() }) {}
// Most field accessors need to retrieve and test the field offset first,
// this is the prefix code for that.
- std::string OffsetPrefix(const FieldDef &field) {
+ std::string OffsetPrefix(const FieldDef &field) const {
return "\n" + Indent + Indent +
"o = flatbuffers.number_types.UOffsetTFlags.py_type" +
"(self._tab.Offset(" + NumToString(field.value.offset) + "))\n" +
@@ -61,85 +86,64 @@
}
// Begin a class declaration.
- void BeginClass(const StructDef &struct_def, std::string *code_ptr) {
+ void BeginClass(const StructDef &struct_def, std::string *code_ptr) const {
auto &code = *code_ptr;
- code += "class " + NormalizedName(struct_def) + "(object):\n";
+ code += "class " + namer_.Type(struct_def.name) + "(object):\n";
code += Indent + "__slots__ = ['_tab']";
code += "\n\n";
}
// Begin enum code with a class declaration.
- void BeginEnum(const std::string &class_name, std::string *code_ptr) {
+ void BeginEnum(const EnumDef &enum_def, std::string *code_ptr) const {
auto &code = *code_ptr;
- code += "class " + class_name + "(object):\n";
- }
-
- std::string EscapeKeyword(const std::string &name) const {
- return keywords_.find(name) == keywords_.end() ? name : name + "_";
- }
-
- std::string NormalizedName(const Definition &definition) const {
- return EscapeKeyword(definition.name);
- }
-
- std::string NormalizedName(const EnumVal &ev) const {
- return EscapeKeyword(ev.name);
- }
-
- // Converts the name of a definition into upper Camel format.
- std::string MakeUpperCamel(const Definition &definition) const {
- return MakeCamel(NormalizedName(definition), true);
- }
-
- // Converts the name of a definition into lower Camel format.
- std::string MakeLowerCamel(const Definition &definition) const {
- auto name = MakeCamel(NormalizedName(definition), false);
- name[0] = CharToLower(name[0]);
- return name;
+ code += "class " + namer_.Type(enum_def.name) + "(object):\n";
}
// Starts a new line and then indents.
- std::string GenIndents(int num) {
+ std::string GenIndents(int num) const {
return "\n" + std::string(num * Indent.length(), ' ');
}
// A single enum member.
void EnumMember(const EnumDef &enum_def, const EnumVal &ev,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code = *code_ptr;
code += Indent;
- code += NormalizedName(ev);
+ code += namer_.Variant(ev.name);
code += " = ";
code += enum_def.ToString(ev) + "\n";
}
- // End enum code.
- void EndEnum(std::string *code_ptr) {
- auto &code = *code_ptr;
- code += "\n";
- }
-
// Initialize a new struct or table from existing data.
void NewRootTypeFromBuffer(const StructDef &struct_def,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code = *code_ptr;
+ const std::string struct_type = namer_.Type(struct_def.name);
code += Indent + "@classmethod\n";
code += Indent + "def GetRootAs";
- code += NormalizedName(struct_def);
- code += "(cls, buf, offset):";
+ code += "(cls, buf, offset=0):";
code += "\n";
code += Indent + Indent;
code += "n = flatbuffers.encode.Get";
code += "(flatbuffers.packer.uoffset, buf, offset)\n";
- code += Indent + Indent + "x = " + NormalizedName(struct_def) + "()\n";
+ code += Indent + Indent + "x = " + struct_type + "()\n";
code += Indent + Indent + "x.Init(buf, n + offset)\n";
code += Indent + Indent + "return x\n";
code += "\n";
+
+ // Add an alias with the old name
+ code += Indent + "@classmethod\n";
+ code += Indent + "def GetRootAs" + struct_type + "(cls, buf, offset=0):\n";
+ code +=
+ Indent + Indent +
+ "\"\"\"This method is deprecated. Please switch to GetRootAs.\"\"\"\n";
+ code += Indent + Indent + "return cls.GetRootAs(buf, offset)\n";
}
// Initialize an existing object with other data, to avoid an allocation.
- void InitializeExisting(const StructDef &struct_def, std::string *code_ptr) {
+ void InitializeExisting(const StructDef &struct_def,
+ std::string *code_ptr) const {
auto &code = *code_ptr;
GenReceiver(struct_def, code_ptr);
@@ -150,11 +154,11 @@
// Get the length of a vector.
void GetVectorLen(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code = *code_ptr;
GenReceiver(struct_def, code_ptr);
- code += MakeCamel(NormalizedName(field)) + "Length(self";
+ code += namer_.Method(field.name) + "Length(self";
code += "):" + OffsetPrefix(field);
code += Indent + Indent + Indent + "return self._tab.VectorLen(o)\n";
code += Indent + Indent + "return 0\n\n";
@@ -162,11 +166,11 @@
// Determines whether a vector is none or not.
void GetVectorIsNone(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code = *code_ptr;
GenReceiver(struct_def, code_ptr);
- code += MakeCamel(NormalizedName(field)) + "IsNone(self";
+ code += namer_.Method(field.name) + "IsNone(self";
code += "):";
code += GenIndents(2) +
"o = flatbuffers.number_types.UOffsetTFlags.py_type" +
@@ -177,11 +181,12 @@
// Get the value of a struct's scalar.
void GetScalarFieldOfStruct(const StructDef &struct_def,
- const FieldDef &field, std::string *code_ptr) {
+ const FieldDef &field,
+ std::string *code_ptr) const {
auto &code = *code_ptr;
std::string getter = GenGetter(field.value.type);
GenReceiver(struct_def, code_ptr);
- code += MakeCamel(NormalizedName(field));
+ code += namer_.Method(field.name);
code += "(self): return " + getter;
code += "self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(";
code += NumToString(field.value.offset) + "))\n";
@@ -189,11 +194,11 @@
// Get the value of a table's scalar.
void GetScalarFieldOfTable(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code = *code_ptr;
std::string getter = GenGetter(field.value.type);
GenReceiver(struct_def, code_ptr);
- code += MakeCamel(NormalizedName(field));
+ code += namer_.Method(field.name);
code += "(self):";
code += OffsetPrefix(field);
getter += "o + self._tab.Pos)";
@@ -214,10 +219,11 @@
// Get a struct by initializing an existing struct.
// Specific to Struct.
void GetStructFieldOfStruct(const StructDef &struct_def,
- const FieldDef &field, std::string *code_ptr) {
+ const FieldDef &field,
+ std::string *code_ptr) const {
auto &code = *code_ptr;
GenReceiver(struct_def, code_ptr);
- code += MakeCamel(NormalizedName(field));
+ code += namer_.Method(field.name);
code += "(self, obj):\n";
code += Indent + Indent + "obj.Init(self._tab.Bytes, self._tab.Pos + ";
code += NumToString(field.value.offset) + ")";
@@ -226,11 +232,11 @@
// Get the value of a fixed size array.
void GetArrayOfStruct(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code = *code_ptr;
const auto vec_type = field.value.type.VectorType();
GenReceiver(struct_def, code_ptr);
- code += MakeCamel(NormalizedName(field));
+ code += namer_.Method(field.name);
if (IsStruct(vec_type)) {
code += "(self, obj, i):\n";
code += Indent + Indent + "obj.Init(self._tab.Bytes, self._tab.Pos + ";
@@ -251,10 +257,10 @@
// Get a struct by initializing an existing struct.
// Specific to Table.
void GetStructFieldOfTable(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code = *code_ptr;
GenReceiver(struct_def, code_ptr);
- code += MakeCamel(NormalizedName(field));
+ code += namer_.Method(field.name);
code += "(self):";
code += OffsetPrefix(field);
if (field.value.type.struct_def->fixed) {
@@ -276,10 +282,10 @@
// Get the value of a string.
void GetStringField(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code = *code_ptr;
GenReceiver(struct_def, code_ptr);
- code += MakeCamel(NormalizedName(field));
+ code += namer_.Method(field.name);
code += "(self):";
code += OffsetPrefix(field);
code += Indent + Indent + Indent + "return " + GenGetter(field.value.type);
@@ -289,10 +295,10 @@
// Get the value of a union from an object.
void GetUnionField(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code = *code_ptr;
GenReceiver(struct_def, code_ptr);
- code += MakeCamel(NormalizedName(field)) + "(self):";
+ code += namer_.Method(field.name) + "(self):";
code += OffsetPrefix(field);
// TODO(rw): this works and is not the good way to it:
@@ -313,27 +319,33 @@
// Generate the package reference when importing a struct or enum from its
// module.
- std::string GenPackageReference(const Type &type) {
- Namespace *namespaces;
+ std::string GenPackageReference(const Type &type) const {
if (type.struct_def) {
- namespaces = type.struct_def->defined_namespace;
+ return GenPackageReference(*type.struct_def);
} else if (type.enum_def) {
- namespaces = type.enum_def->defined_namespace;
+ return GenPackageReference(*type.enum_def);
} else {
return "." + GenTypeGet(type);
}
-
- return namespaces->GetFullyQualifiedName(GenTypeGet(type));
+ }
+ std::string GenPackageReference(const EnumDef &enum_def) const {
+ return namer_.NamespacedType(enum_def.defined_namespace->components,
+ enum_def.name);
+ }
+ std::string GenPackageReference(const StructDef &struct_def) const {
+ return namer_.NamespacedType(struct_def.defined_namespace->components,
+ struct_def.name);
}
// Get the value of a vector's struct member.
void GetMemberOfVectorOfStruct(const StructDef &struct_def,
- const FieldDef &field, std::string *code_ptr) {
+ const FieldDef &field,
+ std::string *code_ptr) const {
auto &code = *code_ptr;
auto vectortype = field.value.type.VectorType();
GenReceiver(struct_def, code_ptr);
- code += MakeCamel(NormalizedName(field));
+ code += namer_.Method(field.name);
code += "(self, j):" + OffsetPrefix(field);
code += Indent + Indent + Indent + "x = self._tab.Vector(o)\n";
code += Indent + Indent + Indent;
@@ -357,12 +369,12 @@
// argument to conveniently set the zero value for the result.
void GetMemberOfVectorOfNonStruct(const StructDef &struct_def,
const FieldDef &field,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code = *code_ptr;
auto vectortype = field.value.type.VectorType();
GenReceiver(struct_def, code_ptr);
- code += MakeCamel(NormalizedName(field));
+ code += namer_.Method(field.name);
code += "(self, j):";
code += OffsetPrefix(field);
code += Indent + Indent + Indent + "a = self._tab.Vector(o)\n";
@@ -382,7 +394,7 @@
// than iterating over the vector element by element.
void GetVectorOfNonStructAsNumpy(const StructDef &struct_def,
const FieldDef &field,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code = *code_ptr;
auto vectortype = field.value.type.VectorType();
@@ -391,13 +403,13 @@
if (!(IsScalar(vectortype.base_type))) { return; }
GenReceiver(struct_def, code_ptr);
- code += MakeCamel(NormalizedName(field)) + "AsNumpy(self):";
+ code += namer_.Method(field.name) + "AsNumpy(self):";
code += OffsetPrefix(field);
code += Indent + Indent + Indent;
code += "return ";
code += "self._tab.GetVectorAsNumpy(flatbuffers.number_types.";
- code += MakeCamel(GenTypeGet(field.value.type));
+ code += namer_.Method(GenTypeGet(field.value.type));
code += "Flags, o)\n";
if (IsString(vectortype)) {
@@ -408,12 +420,51 @@
code += "\n";
}
+ std::string NestedFlatbufferType(std::string unqualified_name) const {
+ StructDef* nested_root = parser_.LookupStruct(unqualified_name);
+ std::string qualified_name;
+ if (nested_root == nullptr) {
+ qualified_name = namer_.NamespacedType(
+ parser_.current_namespace_->components, unqualified_name);
+ // Double check qualified name just to be sure it exists.
+ nested_root = parser_.LookupStruct(qualified_name);
+ }
+ FLATBUFFERS_ASSERT(nested_root); // Guaranteed to exist by parser.
+ return qualified_name;
+ }
+
+ // Returns a nested flatbuffer as itself.
+ void GetVectorAsNestedFlatbuffer(const StructDef &struct_def,
+ const FieldDef &field,
+ std::string *code_ptr) const {
+ auto nested = field.attributes.Lookup("nested_flatbuffer");
+ if (!nested) { return; } // There is no nested flatbuffer.
+
+ const std::string unqualified_name = nested->constant;
+ const std::string qualified_name = NestedFlatbufferType(unqualified_name);
+
+ auto &code = *code_ptr;
+ GenReceiver(struct_def, code_ptr);
+ code += namer_.Method(field.name) + "NestedRoot(self):";
+
+ code += OffsetPrefix(field);
+
+ code += Indent + Indent + Indent;
+ code += "from " + qualified_name + " import " + unqualified_name + "\n";
+ code += Indent + Indent + Indent + "return " + unqualified_name;
+ code += ".GetRootAs" + unqualified_name;
+ code += "(self._tab.Bytes, self._tab.Vector(o))\n";
+ code += Indent + Indent + "return 0\n";
+ code += "\n";
+ }
+
// Begin the creator function signature.
- void BeginBuilderArgs(const StructDef &struct_def, std::string *code_ptr) {
+ void BeginBuilderArgs(const StructDef &struct_def,
+ std::string *code_ptr) const {
auto &code = *code_ptr;
code += "\n";
- code += "def Create" + NormalizedName(struct_def);
+ code += "def Create" + namer_.Type(struct_def.name);
code += "(builder";
}
@@ -423,7 +474,7 @@
const std::string nameprefix,
const std::string namesuffix, bool has_field_name,
const std::string fieldname_suffix,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
@@ -436,21 +487,21 @@
// a nested struct, prefix the name with the field name.
auto subprefix = nameprefix;
if (has_field_name) {
- subprefix += NormalizedName(field) + fieldname_suffix;
+ subprefix += namer_.Field(field.name) + fieldname_suffix;
}
StructBuilderArgs(*field.value.type.struct_def, subprefix, namesuffix,
has_field_name, fieldname_suffix, code_ptr);
} else {
auto &code = *code_ptr;
code += std::string(", ") + nameprefix;
- if (has_field_name) { code += MakeCamel(NormalizedName(field), false); }
+ if (has_field_name) { code += namer_.Field(field.name); }
code += namesuffix;
}
}
}
// End the creator function signature.
- void EndBuilderArgs(std::string *code_ptr) {
+ void EndBuilderArgs(std::string *code_ptr) const {
auto &code = *code_ptr;
code += "):\n";
}
@@ -459,7 +510,7 @@
// padding.
void StructBuilderBody(const StructDef &struct_def, const char *nameprefix,
std::string *code_ptr, size_t index = 0,
- bool in_array = false) {
+ bool in_array = false) const {
auto &code = *code_ptr;
std::string indent(index * 4, ' ');
code +=
@@ -475,9 +526,10 @@
code +=
indent + " builder.Pad(" + NumToString(field.padding) + ")\n";
if (IsStruct(field_type)) {
- StructBuilderBody(*field_type.struct_def,
- (nameprefix + (NormalizedName(field) + "_")).c_str(),
- code_ptr, index, in_array);
+ StructBuilderBody(
+ *field_type.struct_def,
+ (nameprefix + (namer_.Field(field.name) + "_")).c_str(), code_ptr,
+ index, in_array);
} else {
const auto index_var = "_idx" + NumToString(index);
if (IsArray(field_type)) {
@@ -489,12 +541,12 @@
if (IsStruct(type)) {
StructBuilderBody(
*field_type.struct_def,
- (nameprefix + (NormalizedName(field) + "_")).c_str(), code_ptr,
+ (nameprefix + (namer_.Field(field.name) + "_")).c_str(), code_ptr,
index + 1, in_array);
} else {
code += IsArray(field_type) ? " " : "";
code += indent + " builder.Prepend" + GenMethod(field) + "(";
- code += nameprefix + MakeCamel(NormalizedName(field), false);
+ code += nameprefix + namer_.Variable(field.name);
size_t array_cnt = index + (IsArray(field_type) ? 1 : 0);
for (size_t i = 0; in_array && i < array_cnt; i++) {
code += "[_idx" + NumToString(i) + "-1]";
@@ -505,53 +557,76 @@
}
}
- void EndBuilderBody(std::string *code_ptr) {
+ void EndBuilderBody(std::string *code_ptr) const {
auto &code = *code_ptr;
code += " return builder.Offset()\n";
}
// Get the value of a table's starting offset.
- void GetStartOfTable(const StructDef &struct_def, std::string *code_ptr) {
+ void GetStartOfTable(const StructDef &struct_def,
+ std::string *code_ptr) const {
auto &code = *code_ptr;
- code += "def " + NormalizedName(struct_def) + "Start";
- code += "(builder): ";
+ const auto struct_type = namer_.Type(struct_def.name);
+ // Generate method with struct name.
+ code += "def " + struct_type + "Start(builder): ";
code += "builder.StartObject(";
code += NumToString(struct_def.fields.vec.size());
code += ")\n";
+
+ if (!parser_.opts.one_file) {
+ // Generate method without struct name.
+ code += "def Start(builder):\n";
+ code += Indent + "return " + struct_type + "Start(builder)\n";
+ }
}
// Set the value of a table's field.
void BuildFieldOfTable(const StructDef &struct_def, const FieldDef &field,
- const size_t offset, std::string *code_ptr) {
+ const size_t offset, std::string *code_ptr) const {
auto &code = *code_ptr;
- code += "def " + NormalizedName(struct_def) + "Add" +
- MakeCamel(NormalizedName(field));
+ const std::string field_var = namer_.Variable(field.name);
+ const std::string field_method = namer_.Method(field.name);
+
+ // Generate method with struct name.
+ code += "def " + namer_.Type(struct_def.name) + "Add" + field_method;
code += "(builder, ";
- code += MakeCamel(NormalizedName(field), false);
+ code += field_var;
code += "): ";
code += "builder.Prepend";
code += GenMethod(field) + "Slot(";
code += NumToString(offset) + ", ";
if (!IsScalar(field.value.type.base_type) && (!struct_def.fixed)) {
code += "flatbuffers.number_types.UOffsetTFlags.py_type";
- code += "(";
- code += MakeCamel(NormalizedName(field), false) + ")";
+ code += "(" + field_var + ")";
} else {
- code += MakeCamel(NormalizedName(field), false);
+ code += field_var;
}
code += ", ";
code += IsFloat(field.value.type.base_type)
? float_const_gen_.GenFloatConstant(field)
: field.value.constant;
code += ")\n";
+
+ if (!parser_.opts.one_file) {
+ // Generate method without struct name.
+ code += "def Add" + field_method + "(builder, " + field_var + "):\n";
+ code += Indent + "return " + namer_.Type(struct_def.name) + "Add" +
+ field_method;
+ code += "(builder, ";
+ code += field_var;
+ code += ")\n";
+ }
}
// Set the value of one of the members of a table's vector.
void BuildVectorOfTable(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code = *code_ptr;
- code += "def " + NormalizedName(struct_def) + "Start";
- code += MakeCamel(NormalizedName(field));
+ const std::string struct_type = namer_.Type(struct_def.name);
+ const std::string field_method = namer_.Method(field.name);
+
+ // Generate method with struct name.
+ code += "def " + struct_type + "Start" + field_method;
code += "Vector(builder, numElems): return builder.StartVector(";
auto vector_type = field.value.type.VectorType();
auto alignment = InlineAlignment(vector_type);
@@ -559,26 +634,79 @@
code += NumToString(elem_size);
code += ", numElems, " + NumToString(alignment);
code += ")\n";
+
+ if (!parser_.opts.one_file) {
+ // Generate method without struct name.
+ code += "def Start" + field_method + "Vector(builder, numElems):\n";
+ code += Indent + "return " + struct_type + "Start";
+ code += field_method + "Vector(builder, numElems)\n";
+ }
+ }
+
+ // Set the value of one of the members of a table's vector and fills in the
+ // elements from a bytearray. This is for simplifying the use of nested
+ // flatbuffers.
+ void BuildVectorOfTableFromBytes(const StructDef &struct_def,
+ const FieldDef &field,
+ std::string *code_ptr) const {
+ auto nested = field.attributes.Lookup("nested_flatbuffer");
+ if (!nested) { return; } // There is no nested flatbuffer.
+
+ auto &code = *code_ptr;
+ const std::string field_method = namer_.Method(field.name);
+ const std::string struct_type = namer_.Type(struct_def.name);
+
+ // Generate method with struct and field name.
+ code += "def " + struct_type + "Make" + field_method;
+ code += "VectorFromBytes(builder, bytes):\n";
+ code += Indent + "builder.StartVector(";
+ auto vector_type = field.value.type.VectorType();
+ auto alignment = InlineAlignment(vector_type);
+ auto elem_size = InlineSize(vector_type);
+ code += NumToString(elem_size);
+ code += ", len(bytes), " + NumToString(alignment);
+ code += ")\n";
+ code += Indent + "builder.head = builder.head - len(bytes)\n";
+ code += Indent + "builder.Bytes[builder.head : builder.head + len(bytes)]";
+ code += " = bytes\n";
+ code += Indent + "return builder.EndVector()\n";
+
+ if (!parser_.opts.one_file) {
+ // Generate method without struct and field name.
+ code += "def Make" + field_method + "VectorFromBytes(builder, bytes):\n";
+ code += Indent + "return " + struct_type + "Make" + field_method +
+ "VectorFromBytes(builder, bytes)\n";
+ }
}
// Get the offset of the end of a table.
- void GetEndOffsetOnTable(const StructDef &struct_def, std::string *code_ptr) {
+ void GetEndOffsetOnTable(const StructDef &struct_def,
+ std::string *code_ptr) const {
auto &code = *code_ptr;
- code += "def " + NormalizedName(struct_def) + "End";
+
+ // Generate method with struct name.
+ code += "def " + namer_.Type(struct_def.name) + "End";
code += "(builder): ";
code += "return builder.EndObject()\n";
+
+ if (!parser_.opts.one_file) {
+ // Generate method without struct name.
+ code += "def End(builder):\n";
+ code +=
+ Indent + "return " + namer_.Type(struct_def.name) + "End(builder)";
+ }
}
// Generate the receiver for function signatures.
- void GenReceiver(const StructDef &struct_def, std::string *code_ptr) {
+ void GenReceiver(const StructDef &struct_def, std::string *code_ptr) const {
auto &code = *code_ptr;
- code += Indent + "# " + NormalizedName(struct_def) + "\n";
+ code += Indent + "# " + namer_.Type(struct_def.name) + "\n";
code += Indent + "def ";
}
// Generate a struct field, conditioned on its child type(s).
void GenStructAccessor(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
GenComment(field.doc_comment, code_ptr, &def_comment, Indent.c_str());
if (IsScalar(field.value.type.base_type)) {
if (struct_def.fixed) {
@@ -607,6 +735,7 @@
} else {
GetMemberOfVectorOfNonStruct(struct_def, field, code_ptr);
GetVectorOfNonStructAsNumpy(struct_def, field, code_ptr);
+ GetVectorAsNestedFlatbuffer(struct_def, field, code_ptr);
}
break;
}
@@ -621,7 +750,8 @@
}
// Generate struct sizeof.
- void GenStructSizeOf(const StructDef &struct_def, std::string *code_ptr) {
+ void GenStructSizeOf(const StructDef &struct_def,
+ std::string *code_ptr) const {
auto &code = *code_ptr;
code += Indent + "@classmethod\n";
code += Indent + "def SizeOf(cls):\n";
@@ -631,7 +761,8 @@
}
// Generate table constructors, conditioned on its members' types.
- void GenTableBuilders(const StructDef &struct_def, std::string *code_ptr) {
+ void GenTableBuilders(const StructDef &struct_def,
+ std::string *code_ptr) const {
GetStartOfTable(struct_def, code_ptr);
for (auto it = struct_def.fields.vec.begin();
@@ -643,6 +774,7 @@
BuildFieldOfTable(struct_def, field, offset, code_ptr);
if (IsVector(field.value.type)) {
BuildVectorOfTable(struct_def, field, code_ptr);
+ BuildVectorOfTableFromBytes(struct_def, field, code_ptr);
}
}
@@ -651,7 +783,7 @@
// Generate function to check for proper file identifier
void GenHasFileIdentifier(const StructDef &struct_def,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code = *code_ptr;
std::string escapedID;
// In the event any of file_identifier characters are special(NULL, \, etc),
@@ -663,7 +795,7 @@
}
code += Indent + "@classmethod\n";
- code += Indent + "def " + NormalizedName(struct_def);
+ code += Indent + "def " + namer_.Type(struct_def.name);
code += "BufferHasIdentifier(cls, buf, offset, size_prefixed=False):";
code += "\n";
code += Indent + Indent;
@@ -674,7 +806,7 @@
}
// Generates struct or table methods.
- void GenStruct(const StructDef &struct_def, std::string *code_ptr) {
+ void GenStruct(const StructDef &struct_def, std::string *code_ptr) const {
if (struct_def.generated) return;
GenComment(struct_def.doc_comment, code_ptr, &def_comment);
@@ -712,23 +844,24 @@
}
void GenReceiverForObjectAPI(const StructDef &struct_def,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code = *code_ptr;
- code += GenIndents(1) + "# " + NormalizedName(struct_def) + "T";
+ code += GenIndents(1) + "# " + namer_.ObjectType(struct_def.name);
code += GenIndents(1) + "def ";
}
void BeginClassForObjectAPI(const StructDef &struct_def,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code = *code_ptr;
code += "\n";
- code += "class " + NormalizedName(struct_def) + "T(object):";
+ code += "class " + namer_.ObjectType(struct_def.name) + "(object):";
code += "\n";
}
// Gets the accoresponding python builtin type of a BaseType for scalars and
// string.
- std::string GetBasePythonTypeForScalarAndString(const BaseType &base_type) {
+ std::string GetBasePythonTypeForScalarAndString(
+ const BaseType &base_type) const {
if (IsBool(base_type)) {
return "bool";
} else if (IsFloat(base_type)) {
@@ -743,7 +876,7 @@
}
}
- std::string GetDefaultValue(const FieldDef &field) {
+ std::string GetDefaultValue(const FieldDef &field) const {
BaseType base_type = field.value.type.base_type;
if (IsBool(base_type)) {
return field.value.constant == "0" ? "False" : "True";
@@ -759,7 +892,7 @@
void GenUnionInit(const FieldDef &field, std::string *field_types_ptr,
std::set<std::string> *import_list,
- std::set<std::string> *import_typing_list) {
+ std::set<std::string> *import_typing_list) const {
// Gets all possible types in the union.
import_typing_list->insert("Union");
auto &field_types = *field_types_ptr;
@@ -774,7 +907,7 @@
std::string field_type;
switch (ev.union_type.base_type) {
case BASE_TYPE_STRUCT:
- field_type = GenTypeGet(ev.union_type) + "T";
+ field_type = namer_.ObjectType(ev.union_type.struct_def->name);
if (parser_.opts.include_dependence_headers) {
auto package_reference = GenPackageReference(ev.union_type);
field_type = package_reference + "." + field_type;
@@ -794,45 +927,43 @@
// Gets the import lists for the union.
if (parser_.opts.include_dependence_headers) {
- // The package reference is generated based on enum_def, instead
- // of struct_def in field.type. That's why GenPackageReference() is
- // not used.
- Namespace *namespaces = field.value.type.enum_def->defined_namespace;
- auto package_reference = namespaces->GetFullyQualifiedName(
- MakeUpperCamel(*(field.value.type.enum_def)));
- auto union_name = MakeUpperCamel(*(field.value.type.enum_def));
+ const auto package_reference =
+ GenPackageReference(*field.value.type.enum_def);
import_list->insert("import " + package_reference);
}
}
- void GenStructInit(const FieldDef &field, std::string *field_type_ptr,
+ void GenStructInit(const FieldDef &field, std::string *out_ptr,
std::set<std::string> *import_list,
- std::set<std::string> *import_typing_list) {
+ std::set<std::string> *import_typing_list) const {
import_typing_list->insert("Optional");
- auto &field_type = *field_type_ptr;
+ auto &output = *out_ptr;
+ const Type &type = field.value.type;
+ const std::string object_type = namer_.ObjectType(type.struct_def->name);
if (parser_.opts.include_dependence_headers) {
- auto package_reference = GenPackageReference(field.value.type);
- field_type = package_reference + "." + TypeName(field) + "T]";
+ auto package_reference = GenPackageReference(type);
+ output = package_reference + "." + object_type + "]";
import_list->insert("import " + package_reference);
} else {
- field_type = TypeName(field) + "T]";
+ output = object_type + "]";
}
- field_type = "Optional[" + field_type;
+ output = "Optional[" + output;
}
void GenVectorInit(const FieldDef &field, std::string *field_type_ptr,
std::set<std::string> *import_list,
- std::set<std::string> *import_typing_list) {
+ std::set<std::string> *import_typing_list) const {
import_typing_list->insert("List");
auto &field_type = *field_type_ptr;
- auto base_type = field.value.type.VectorType().base_type;
+ const Type &vector_type = field.value.type.VectorType();
+ const BaseType base_type = vector_type.base_type;
if (base_type == BASE_TYPE_STRUCT) {
- field_type = GenTypeGet(field.value.type.VectorType()) + "T]";
+ const std::string object_type =
+ namer_.ObjectType(GenTypeGet(vector_type));
+ field_type = object_type + "]";
if (parser_.opts.include_dependence_headers) {
- auto package_reference =
- GenPackageReference(field.value.type.VectorType());
- field_type = package_reference + "." +
- GenTypeGet(field.value.type.VectorType()) + "T]";
+ auto package_reference = GenPackageReference(vector_type);
+ field_type = package_reference + "." + object_type + "]";
import_list->insert("import " + package_reference);
}
field_type = "List[" + field_type;
@@ -843,7 +974,7 @@
}
void GenInitialize(const StructDef &struct_def, std::string *code_ptr,
- std::set<std::string> *import_list) {
+ std::set<std::string> *import_list) const {
std::string code;
std::set<std::string> import_typing_list;
for (auto it = struct_def.fields.vec.begin();
@@ -874,11 +1005,11 @@
break;
}
- auto default_value = GetDefaultValue(field);
+ const auto default_value = GetDefaultValue(field);
// Wrties the init statement.
- auto field_instance_name = MakeLowerCamel(field);
- code += GenIndents(2) + "self." + field_instance_name + " = " +
- default_value + " # type: " + field_type;
+ const auto field_field = namer_.Field(field.name);
+ code += GenIndents(2) + "self." + field_field + " = " + default_value +
+ " # type: " + field_type;
}
// Writes __init__ method.
@@ -914,46 +1045,44 @@
}
// Removes the import of the struct itself, if applied.
- auto package_reference =
- struct_def.defined_namespace->GetFullyQualifiedName(
- MakeUpperCamel(struct_def));
- auto struct_import = "import " + package_reference;
+ auto struct_import = "import " + GenPackageReference(struct_def);
import_list->erase(struct_import);
}
- void InitializeFromBuf(const StructDef &struct_def, std::string *code_ptr) {
+ void InitializeFromBuf(const StructDef &struct_def,
+ std::string *code_ptr) const {
auto &code = *code_ptr;
- auto instance_name = MakeLowerCamel(struct_def);
- auto struct_name = NormalizedName(struct_def);
+ const auto struct_var = namer_.Variable(struct_def.name);
+ const auto struct_type = namer_.Type(struct_def.name);
code += GenIndents(1) + "@classmethod";
code += GenIndents(1) + "def InitFromBuf(cls, buf, pos):";
- code += GenIndents(2) + instance_name + " = " + struct_name + "()";
- code += GenIndents(2) + instance_name + ".Init(buf, pos)";
- code += GenIndents(2) + "return cls.InitFromObj(" + instance_name + ")";
+ code += GenIndents(2) + struct_var + " = " + struct_type + "()";
+ code += GenIndents(2) + struct_var + ".Init(buf, pos)";
+ code += GenIndents(2) + "return cls.InitFromObj(" + struct_var + ")";
code += "\n";
}
void InitializeFromObjForObject(const StructDef &struct_def,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code = *code_ptr;
- auto instance_name = MakeLowerCamel(struct_def);
- auto struct_name = NormalizedName(struct_def);
+ const auto struct_var = namer_.Variable(struct_def.name);
+ const auto struct_object = namer_.ObjectType(struct_def.name);
code += GenIndents(1) + "@classmethod";
- code += GenIndents(1) + "def InitFromObj(cls, " + instance_name + "):";
- code += GenIndents(2) + "x = " + struct_name + "T()";
- code += GenIndents(2) + "x._UnPack(" + instance_name + ")";
+ code += GenIndents(1) + "def InitFromObj(cls, " + struct_var + "):";
+ code += GenIndents(2) + "x = " + struct_object + "()";
+ code += GenIndents(2) + "x._UnPack(" + struct_var + ")";
code += GenIndents(2) + "return x";
code += "\n";
}
void GenUnPackForStruct(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code = *code_ptr;
- auto struct_instance_name = MakeLowerCamel(struct_def);
- auto field_instance_name = MakeLowerCamel(field);
- auto field_accessor_name = MakeUpperCamel(field);
+ const auto struct_var = namer_.Variable(struct_def.name);
+ const auto field_field = namer_.Field(field.name);
+ const auto field_method = namer_.Method(field.name);
auto field_type = TypeName(field);
if (parser_.opts.include_dependence_headers) {
@@ -961,16 +1090,14 @@
field_type = package_reference + "." + TypeName(field);
}
- code += GenIndents(2) + "if " + struct_instance_name + "." +
- field_accessor_name + "(";
+ code += GenIndents(2) + "if " + struct_var + "." + field_method + "(";
// if field is a struct, we need to create an instance for it first.
if (struct_def.fixed && field.value.type.base_type == BASE_TYPE_STRUCT) {
code += field_type + "()";
}
code += ") is not None:";
- code += GenIndents(3) + "self." + field_instance_name + " = " + field_type +
- "T.InitFromObj(" + struct_instance_name + "." +
- field_accessor_name + "(";
+ code += GenIndents(3) + "self." + field_field + " = " + field_type +
+ "T.InitFromObj(" + struct_var + "." + field_method + "(";
// A struct's accessor requires a struct buf instance.
if (struct_def.fixed && field.value.type.base_type == BASE_TYPE_STRUCT) {
code += field_type + "()";
@@ -979,82 +1106,81 @@
}
void GenUnPackForUnion(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code = *code_ptr;
- auto field_instance_name = MakeLowerCamel(field);
- auto field_accessor_name = MakeUpperCamel(field);
- auto struct_instance_name = MakeLowerCamel(struct_def);
- auto union_name = MakeUpperCamel(*(field.value.type.enum_def));
+ const auto field_field = namer_.Field(field.name);
+ const auto field_method = namer_.Method(field.name);
+ const auto struct_var = namer_.Variable(struct_def.name);
+ const EnumDef &enum_def = *field.value.type.enum_def;
+ auto union_type = namer_.Namespace(enum_def.name);
if (parser_.opts.include_dependence_headers) {
- Namespace *namespaces = field.value.type.enum_def->defined_namespace;
- auto package_reference = namespaces->GetFullyQualifiedName(
- MakeUpperCamel(*(field.value.type.enum_def)));
- union_name = package_reference + "." + union_name;
+ union_type = GenPackageReference(enum_def) + "." + union_type;
}
- code += GenIndents(2) + "self." + field_instance_name + " = " + union_name +
- "Creator(" + "self." + field_instance_name + "Type, " +
- struct_instance_name + "." + field_accessor_name + "())";
+ code += GenIndents(2) + "self." + field_field + " = " + union_type +
+ "Creator(" + "self." + field_field + "Type, " + struct_var + "." +
+ field_method + "())";
}
void GenUnPackForStructVector(const StructDef &struct_def,
- const FieldDef &field, std::string *code_ptr) {
+ const FieldDef &field,
+ std::string *code_ptr) const {
auto &code = *code_ptr;
- auto field_instance_name = MakeLowerCamel(field);
- auto field_accessor_name = MakeUpperCamel(field);
- auto struct_instance_name = MakeLowerCamel(struct_def);
+ const auto field_field = namer_.Field(field.name);
+ const auto field_method = namer_.Method(field.name);
+ const auto struct_var = namer_.Variable(struct_def.name);
- code += GenIndents(2) + "if not " + struct_instance_name + "." +
- field_accessor_name + "IsNone():";
- code += GenIndents(3) + "self." + field_instance_name + " = []";
- code += GenIndents(3) + "for i in range(" + struct_instance_name + "." +
- field_accessor_name + "Length()):";
+ code += GenIndents(2) + "if not " + struct_var + "." + field_method +
+ "IsNone():";
+ code += GenIndents(3) + "self." + field_field + " = []";
+ code += GenIndents(3) + "for i in range(" + struct_var + "." +
+ field_method + "Length()):";
- auto field_type_name = TypeName(field);
- auto one_instance = field_type_name + "_";
+ auto field_type = TypeName(field);
+ auto one_instance = field_type + "_";
one_instance[0] = CharToLower(one_instance[0]);
if (parser_.opts.include_dependence_headers) {
auto package_reference = GenPackageReference(field.value.type);
- field_type_name = package_reference + "." + TypeName(field);
+ field_type = package_reference + "." + TypeName(field);
}
- code += GenIndents(4) + "if " + struct_instance_name + "." +
- field_accessor_name + "(i) is None:";
- code += GenIndents(5) + "self." + field_instance_name + ".append(None)";
+ code += GenIndents(4) + "if " + struct_var + "." + field_method +
+ "(i) is None:";
+ code += GenIndents(5) + "self." + field_field + ".append(None)";
code += GenIndents(4) + "else:";
- code += GenIndents(5) + one_instance + " = " + field_type_name +
- "T.InitFromObj(" + struct_instance_name + "." +
- field_accessor_name + "(i))";
- code += GenIndents(5) + "self." + field_instance_name + ".append(" +
- one_instance + ")";
+ code += GenIndents(5) + one_instance + " = " + field_type +
+ "T.InitFromObj(" + struct_var + "." + field_method + "(i))";
+ code +=
+ GenIndents(5) + "self." + field_field + ".append(" + one_instance + ")";
}
void GenUnpackforScalarVectorHelper(const StructDef &struct_def,
const FieldDef &field,
- std::string *code_ptr, int indents) {
+ std::string *code_ptr,
+ int indents) const {
auto &code = *code_ptr;
- auto field_instance_name = MakeLowerCamel(field);
- auto field_accessor_name = MakeUpperCamel(field);
- auto struct_instance_name = MakeLowerCamel(struct_def);
+ const auto field_field = namer_.Field(field.name);
+ const auto field_method = namer_.Method(field.name);
+ const auto struct_var = namer_.Variable(struct_def.name);
- code += GenIndents(indents) + "self." + field_instance_name + " = []";
- code += GenIndents(indents) + "for i in range(" + struct_instance_name +
- "." + field_accessor_name + "Length()):";
- code += GenIndents(indents + 1) + "self." + field_instance_name +
- ".append(" + struct_instance_name + "." + field_accessor_name +
- "(i))";
+ code += GenIndents(indents) + "self." + field_field + " = []";
+ code += GenIndents(indents) + "for i in range(" + struct_var + "." +
+ field_method + "Length()):";
+ code += GenIndents(indents + 1) + "self." + field_field + ".append(" +
+ struct_var + "." + field_method + "(i))";
}
void GenUnPackForScalarVector(const StructDef &struct_def,
- const FieldDef &field, std::string *code_ptr) {
+ const FieldDef &field,
+ std::string *code_ptr) const {
auto &code = *code_ptr;
- auto field_instance_name = MakeLowerCamel(field);
- auto field_accessor_name = MakeUpperCamel(field);
- auto struct_instance_name = MakeLowerCamel(struct_def);
+ const auto field_field = namer_.Field(field.name);
+ const auto field_method = namer_.Method(field.name);
+ const auto struct_var = namer_.Variable(struct_def.name);
- code += GenIndents(2) + "if not " + struct_instance_name + "." +
- field_accessor_name + "IsNone():";
+ code += GenIndents(2) + "if not " + struct_var + "." + field_method +
+ "IsNone():";
// String does not have the AsNumpy method.
if (!(IsScalar(field.value.type.VectorType().base_type))) {
@@ -1067,23 +1193,23 @@
// If numpy exists, use the AsNumpy method to optimize the unpack speed.
code += GenIndents(3) + "else:";
- code += GenIndents(4) + "self." + field_instance_name + " = " +
- struct_instance_name + "." + field_accessor_name + "AsNumpy()";
+ code += GenIndents(4) + "self." + field_field + " = " + struct_var + "." +
+ field_method + "AsNumpy()";
}
void GenUnPackForScalar(const StructDef &struct_def, const FieldDef &field,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code = *code_ptr;
- auto field_instance_name = MakeLowerCamel(field);
- auto field_accessor_name = MakeUpperCamel(field);
- auto struct_instance_name = MakeLowerCamel(struct_def);
+ const auto field_field = namer_.Field(field.name);
+ const auto field_method = namer_.Method(field.name);
+ const auto struct_var = namer_.Variable(struct_def.name);
- code += GenIndents(2) + "self." + field_instance_name + " = " +
- struct_instance_name + "." + field_accessor_name + "()";
+ code += GenIndents(2) + "self." + field_field + " = " + struct_var + "." +
+ field_method + "()";
}
// Generates the UnPack method for the object class.
- void GenUnPack(const StructDef &struct_def, std::string *code_ptr) {
+ void GenUnPack(const StructDef &struct_def, std::string *code_ptr) const {
std::string code;
// Items that needs to be imported. No duplicate modules will be imported.
std::set<std::string> import_list;
@@ -1122,12 +1248,11 @@
// Writes import statements and code into the generated file.
auto &code_base = *code_ptr;
- auto struct_instance_name = MakeLowerCamel(struct_def);
- auto struct_name = MakeUpperCamel(struct_def);
+ const auto struct_var = namer_.Variable(struct_def.name);
GenReceiverForObjectAPI(struct_def, code_ptr);
- code_base += "_UnPack(self, " + struct_instance_name + "):";
- code_base += GenIndents(2) + "if " + struct_instance_name + " is None:";
+ code_base += "_UnPack(self, " + struct_var + "):";
+ code_base += GenIndents(2) + "if " + struct_var + " is None:";
code_base += GenIndents(3) + "return";
// Write the import statements.
@@ -1141,13 +1266,14 @@
code_base += "\n";
}
- void GenPackForStruct(const StructDef &struct_def, std::string *code_ptr) {
+ void GenPackForStruct(const StructDef &struct_def,
+ std::string *code_ptr) const {
auto &code = *code_ptr;
- auto struct_name = MakeUpperCamel(struct_def);
+ const auto struct_fn = namer_.Function(struct_def.name);
GenReceiverForObjectAPI(struct_def, code_ptr);
code += "Pack(self, builder):";
- code += GenIndents(2) + "return Create" + struct_name + "(builder";
+ code += GenIndents(2) + "return Create" + struct_fn + "(builder";
StructBuilderArgs(struct_def,
/* nameprefix = */ "self.",
@@ -1160,67 +1286,61 @@
void GenPackForStructVectorField(const StructDef &struct_def,
const FieldDef &field,
std::string *code_prefix_ptr,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code_prefix = *code_prefix_ptr;
auto &code = *code_ptr;
- auto field_instance_name = MakeLowerCamel(field);
- auto struct_name = NormalizedName(struct_def);
- auto field_accessor_name = MakeUpperCamel(field);
+ const auto field_field = namer_.Field(field.name);
+ const auto struct_type = namer_.Type(struct_def.name);
+ const auto field_method = namer_.Method(field.name);
// Creates the field.
- code_prefix +=
- GenIndents(2) + "if self." + field_instance_name + " is not None:";
+ code_prefix += GenIndents(2) + "if self." + field_field + " is not None:";
if (field.value.type.struct_def->fixed) {
- code_prefix += GenIndents(3) + struct_name + "Start" +
- field_accessor_name + "Vector(builder, len(self." +
- field_instance_name + "))";
+ code_prefix += GenIndents(3) + struct_type + "Start" + field_method +
+ "Vector(builder, len(self." + field_field + "))";
code_prefix += GenIndents(3) + "for i in reversed(range(len(self." +
- field_instance_name + "))):";
+ field_field + "))):";
code_prefix +=
- GenIndents(4) + "self." + field_instance_name + "[i].Pack(builder)";
- code_prefix += GenIndents(3) + field_instance_name +
- " = builder.EndVector(len(self." + field_instance_name +
- "))";
+ GenIndents(4) + "self." + field_field + "[i].Pack(builder)";
+ code_prefix += GenIndents(3) + field_field + " = builder.EndVector()";
} else {
// If the vector is a struct vector, we need to first build accessor for
// each struct element.
- code_prefix += GenIndents(3) + field_instance_name + "list = []";
+ code_prefix += GenIndents(3) + field_field + "list = []";
code_prefix += GenIndents(3);
- code_prefix += "for i in range(len(self." + field_instance_name + ")):";
- code_prefix += GenIndents(4) + field_instance_name + "list.append(self." +
- field_instance_name + "[i].Pack(builder))";
+ code_prefix += "for i in range(len(self." + field_field + ")):";
+ code_prefix += GenIndents(4) + field_field + "list.append(self." +
+ field_field + "[i].Pack(builder))";
- code_prefix += GenIndents(3) + struct_name + "Start" +
- field_accessor_name + "Vector(builder, len(self." +
- field_instance_name + "))";
+ code_prefix += GenIndents(3) + struct_type + "Start" + field_method +
+ "Vector(builder, len(self." + field_field + "))";
code_prefix += GenIndents(3) + "for i in reversed(range(len(self." +
- field_instance_name + "))):";
+ field_field + "))):";
code_prefix += GenIndents(4) + "builder.PrependUOffsetTRelative" + "(" +
- field_instance_name + "list[i])";
- code_prefix += GenIndents(3) + field_instance_name +
- " = builder.EndVector(len(self." + field_instance_name +
- "))";
+ field_field + "list[i])";
+ code_prefix += GenIndents(3) + field_field + " = builder.EndVector()";
}
// Adds the field into the struct.
- code += GenIndents(2) + "if self." + field_instance_name + " is not None:";
- code += GenIndents(3) + struct_name + "Add" + field_accessor_name +
- "(builder, " + field_instance_name + ")";
+ code += GenIndents(2) + "if self." + field_field + " is not None:";
+ code += GenIndents(3) + struct_type + "Add" + field_method + "(builder, " +
+ field_field + ")";
}
void GenPackForScalarVectorFieldHelper(const StructDef &struct_def,
const FieldDef &field,
- std::string *code_ptr, int indents) {
+ std::string *code_ptr,
+ int indents) const {
auto &code = *code_ptr;
- auto field_instance_name = MakeLowerCamel(field);
- auto field_accessor_name = MakeUpperCamel(field);
- auto struct_name = NormalizedName(struct_def);
- auto vectortype = field.value.type.VectorType();
+ const auto field_field = namer_.Field(field.name);
+ const auto field_method = namer_.Method(field.name);
+ const auto struct_type = namer_.Type(struct_def.name);
+ const auto vectortype = field.value.type.VectorType();
- code += GenIndents(indents) + struct_name + "Start" + field_accessor_name +
- "Vector(builder, len(self." + field_instance_name + "))";
+ code += GenIndents(indents) + struct_type + "Start" + field_method +
+ "Vector(builder, len(self." + field_field + "))";
code += GenIndents(indents) + "for i in reversed(range(len(self." +
- field_instance_name + "))):";
+ field_field + "))):";
code += GenIndents(indents + 1) + "builder.Prepend";
std::string type_name;
@@ -1245,120 +1365,109 @@
void GenPackForScalarVectorField(const StructDef &struct_def,
const FieldDef &field,
std::string *code_prefix_ptr,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code = *code_ptr;
auto &code_prefix = *code_prefix_ptr;
- auto field_instance_name = MakeLowerCamel(field);
- auto field_accessor_name = MakeUpperCamel(field);
- auto struct_name = NormalizedName(struct_def);
+ const auto field_field = namer_.Field(field.name);
+ const auto field_method = namer_.Method(field.name);
+ const auto struct_type = namer_.Type(struct_def.name);
// Adds the field into the struct.
- code += GenIndents(2) + "if self." + field_instance_name + " is not None:";
- code += GenIndents(3) + struct_name + "Add" + field_accessor_name +
- "(builder, " + field_instance_name + ")";
+ code += GenIndents(2) + "if self." + field_field + " is not None:";
+ code += GenIndents(3) + struct_type + "Add" + field_method + "(builder, " +
+ field_field + ")";
// Creates the field.
- code_prefix +=
- GenIndents(2) + "if self." + field_instance_name + " is not None:";
+ code_prefix += GenIndents(2) + "if self." + field_field + " is not None:";
// If the vector is a string vector, we need to first build accessor for
// each string element. And this generated code, needs to be
// placed ahead of code_prefix.
auto vectortype = field.value.type.VectorType();
if (IsString(vectortype)) {
- code_prefix += GenIndents(3) + MakeLowerCamel(field) + "list = []";
- code_prefix += GenIndents(3) + "for i in range(len(self." +
- field_instance_name + ")):";
- code_prefix += GenIndents(4) + MakeLowerCamel(field) +
- "list.append(builder.CreateString(self." +
- field_instance_name + "[i]))";
+ code_prefix += GenIndents(3) + field_field + "list = []";
+ code_prefix +=
+ GenIndents(3) + "for i in range(len(self." + field_field + ")):";
+ code_prefix += GenIndents(4) + field_field +
+ "list.append(builder.CreateString(self." + field_field +
+ "[i]))";
GenPackForScalarVectorFieldHelper(struct_def, field, code_prefix_ptr, 3);
- code_prefix += "(" + MakeLowerCamel(field) + "list[i])";
- code_prefix += GenIndents(3) + field_instance_name +
- " = builder.EndVector(len(self." + field_instance_name +
- "))";
+ code_prefix += "(" + field_field + "list[i])";
+ code_prefix += GenIndents(3) + field_field + " = builder.EndVector()";
return;
}
code_prefix += GenIndents(3) + "if np is not None and type(self." +
- field_instance_name + ") is np.ndarray:";
- code_prefix += GenIndents(4) + field_instance_name +
- " = builder.CreateNumpyVector(self." + field_instance_name +
- ")";
+ field_field + ") is np.ndarray:";
+ code_prefix += GenIndents(4) + field_field +
+ " = builder.CreateNumpyVector(self." + field_field + ")";
code_prefix += GenIndents(3) + "else:";
GenPackForScalarVectorFieldHelper(struct_def, field, code_prefix_ptr, 4);
- code_prefix += "(self." + field_instance_name + "[i])";
- code_prefix += GenIndents(4) + field_instance_name +
- " = builder.EndVector(len(self." + field_instance_name +
- "))";
+ code_prefix += "(self." + field_field + "[i])";
+ code_prefix += GenIndents(4) + field_field + " = builder.EndVector()";
}
void GenPackForStructField(const StructDef &struct_def, const FieldDef &field,
std::string *code_prefix_ptr,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code_prefix = *code_prefix_ptr;
auto &code = *code_ptr;
- auto field_instance_name = MakeLowerCamel(field);
-
- auto field_accessor_name = MakeUpperCamel(field);
- auto struct_name = NormalizedName(struct_def);
+ const auto field_field = namer_.Field(field.name);
+ const auto field_method = namer_.Method(field.name);
+ const auto struct_type = namer_.Type(struct_def.name);
if (field.value.type.struct_def->fixed) {
// Pure struct fields need to be created along with their parent
// structs.
- code +=
- GenIndents(2) + "if self." + field_instance_name + " is not None:";
- code += GenIndents(3) + field_instance_name + " = self." +
- field_instance_name + ".Pack(builder)";
+ code += GenIndents(2) + "if self." + field_field + " is not None:";
+ code += GenIndents(3) + field_field + " = self." + field_field +
+ ".Pack(builder)";
} else {
// Tables need to be created before their parent structs are created.
- code_prefix +=
- GenIndents(2) + "if self." + field_instance_name + " is not None:";
- code_prefix += GenIndents(3) + field_instance_name + " = self." +
- field_instance_name + ".Pack(builder)";
- code +=
- GenIndents(2) + "if self." + field_instance_name + " is not None:";
+ code_prefix += GenIndents(2) + "if self." + field_field + " is not None:";
+ code_prefix += GenIndents(3) + field_field + " = self." + field_field +
+ ".Pack(builder)";
+ code += GenIndents(2) + "if self." + field_field + " is not None:";
}
- code += GenIndents(3) + struct_name + "Add" + field_accessor_name +
- "(builder, " + field_instance_name + ")";
+ code += GenIndents(3) + struct_type + "Add" + field_method + "(builder, " +
+ field_field + ")";
}
void GenPackForUnionField(const StructDef &struct_def, const FieldDef &field,
std::string *code_prefix_ptr,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code_prefix = *code_prefix_ptr;
auto &code = *code_ptr;
- auto field_instance_name = MakeLowerCamel(field);
-
- auto field_accessor_name = MakeUpperCamel(field);
- auto struct_name = NormalizedName(struct_def);
+ const auto field_field = namer_.Field(field.name);
+ const auto field_method = namer_.Method(field.name);
+ const auto struct_type = namer_.Type(struct_def.name);
// TODO(luwa): TypeT should be moved under the None check as well.
- code_prefix +=
- GenIndents(2) + "if self." + field_instance_name + " is not None:";
- code_prefix += GenIndents(3) + field_instance_name + " = self." +
- field_instance_name + ".Pack(builder)";
- code += GenIndents(2) + "if self." + field_instance_name + " is not None:";
- code += GenIndents(3) + struct_name + "Add" + field_accessor_name +
- "(builder, " + field_instance_name + ")";
+ code_prefix += GenIndents(2) + "if self." + field_field + " is not None:";
+ code_prefix += GenIndents(3) + field_field + " = self." + field_field +
+ ".Pack(builder)";
+ code += GenIndents(2) + "if self." + field_field + " is not None:";
+ code += GenIndents(3) + struct_type + "Add" + field_method + "(builder, " +
+ field_field + ")";
}
- void GenPackForTable(const StructDef &struct_def, std::string *code_ptr) {
+ void GenPackForTable(const StructDef &struct_def,
+ std::string *code_ptr) const {
auto &code_base = *code_ptr;
std::string code, code_prefix;
- auto struct_instance_name = MakeLowerCamel(struct_def);
- auto struct_name = NormalizedName(struct_def);
+ const auto struct_var = namer_.Variable(struct_def.name);
+ const auto struct_type = namer_.Type(struct_def.name);
GenReceiverForObjectAPI(struct_def, code_ptr);
code_base += "Pack(self, builder):";
- code += GenIndents(2) + struct_name + "Start(builder)";
+ code += GenIndents(2) + struct_type + "Start(builder)";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
if (field.deprecated) continue;
- auto field_accessor_name = MakeUpperCamel(field);
- auto field_instance_name = MakeLowerCamel(field);
+ const auto field_method = namer_.Method(field.name);
+ const auto field_field = namer_.Field(field.name);
switch (field.value.type.base_type) {
case BASE_TYPE_STRUCT: {
@@ -1383,37 +1492,34 @@
break;
}
case BASE_TYPE_STRING: {
- code_prefix += GenIndents(2) + "if self." + field_instance_name +
- " is not None:";
- code_prefix += GenIndents(3) + field_instance_name +
- " = builder.CreateString(self." + field_instance_name +
- ")";
- code += GenIndents(2) + "if self." + field_instance_name +
- " is not None:";
- code += GenIndents(3) + struct_name + "Add" + field_accessor_name +
- "(builder, " + field_instance_name + ")";
+ code_prefix +=
+ GenIndents(2) + "if self." + field_field + " is not None:";
+ code_prefix += GenIndents(3) + field_field +
+ " = builder.CreateString(self." + field_field + ")";
+ code += GenIndents(2) + "if self." + field_field + " is not None:";
+ code += GenIndents(3) + struct_type + "Add" + field_method +
+ "(builder, " + field_field + ")";
break;
}
default:
// Generates code for scalar values. If the value equals to the
// default value, builder will automatically ignore it. So we don't
// need to check the value ahead.
- code += GenIndents(2) + struct_name + "Add" + field_accessor_name +
- "(builder, self." + field_instance_name + ")";
+ code += GenIndents(2) + struct_type + "Add" + field_method +
+ "(builder, self." + field_field + ")";
break;
}
}
- code += GenIndents(2) + struct_instance_name + " = " + struct_name +
- "End(builder)";
- code += GenIndents(2) + "return " + struct_instance_name;
+ code += GenIndents(2) + struct_var + " = " + struct_type + "End(builder)";
+ code += GenIndents(2) + "return " + struct_var;
code_base += code_prefix + code;
code_base += "\n";
}
void GenStructForObjectAPI(const StructDef &struct_def,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
if (struct_def.generated) return;
std::set<std::string> import_list;
@@ -1447,14 +1553,14 @@
}
void GenUnionCreatorForStruct(const EnumDef &enum_def, const EnumVal &ev,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code = *code_ptr;
- auto union_name = NormalizedName(enum_def);
- auto field_name = NormalizedName(ev);
- auto field_type = GenTypeGet(ev.union_type) + "T";
+ const auto union_type = namer_.Type(enum_def.name);
+ const auto variant = namer_.Variant(ev.name);
+ auto field_type = namer_.ObjectType(GenTypeGet(ev.union_type));
- code += GenIndents(1) + "if unionType == " + union_name + "()." +
- field_name + ":";
+ code += GenIndents(1) + "if unionType == " + union_type + "()." +
+ variant + ":";
if (parser_.opts.include_dependence_headers) {
auto package_reference = GenPackageReference(ev.union_type);
code += GenIndents(2) + "import " + package_reference;
@@ -1465,25 +1571,27 @@
}
void GenUnionCreatorForString(const EnumDef &enum_def, const EnumVal &ev,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code = *code_ptr;
- auto union_name = NormalizedName(enum_def);
- auto field_name = NormalizedName(ev);
+ const auto union_type = namer_.Type(enum_def.name);
+ const auto variant = namer_.Variant(ev.name);
- code += GenIndents(1) + "if unionType == " + union_name + "()." +
- field_name + ":";
+ code += GenIndents(1) + "if unionType == " + union_type + "()." +
+ variant + ":";
code += GenIndents(2) + "tab = Table(table.Bytes, table.Pos)";
code += GenIndents(2) + "union = tab.String(table.Pos)";
code += GenIndents(2) + "return union";
}
// Creates an union object based on union type.
- void GenUnionCreator(const EnumDef &enum_def, std::string *code_ptr) {
+ void GenUnionCreator(const EnumDef &enum_def, std::string *code_ptr) const {
+ if (enum_def.generated) return;
+
auto &code = *code_ptr;
- auto union_name = MakeUpperCamel(enum_def);
+ const auto enum_fn = namer_.Function(enum_def.name);
code += "\n";
- code += "def " + union_name + "Creator(unionType, table):";
+ code += "def " + enum_fn + "Creator(unionType, table):";
code += GenIndents(1) + "from flatbuffers.table import Table";
code += GenIndents(1) + "if not isinstance(table, Table):";
code += GenIndents(2) + "return None";
@@ -1506,39 +1614,38 @@
}
// Generate enum declarations.
- void GenEnum(const EnumDef &enum_def, std::string *code_ptr) {
+ void GenEnum(const EnumDef &enum_def, std::string *code_ptr) const {
if (enum_def.generated) return;
GenComment(enum_def.doc_comment, code_ptr, &def_comment);
- BeginEnum(NormalizedName(enum_def), code_ptr);
+ BeginEnum(enum_def, code_ptr);
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
auto &ev = **it;
GenComment(ev.doc_comment, code_ptr, &def_comment, Indent.c_str());
EnumMember(enum_def, ev, code_ptr);
}
- EndEnum(code_ptr);
}
// Returns the function name that is able to read a value of the given type.
- std::string GenGetter(const Type &type) {
+ std::string GenGetter(const Type &type) const {
switch (type.base_type) {
case BASE_TYPE_STRING: return "self._tab.String(";
case BASE_TYPE_UNION: return "self._tab.Union(";
case BASE_TYPE_VECTOR: return GenGetter(type.VectorType());
default:
return "self._tab.Get(flatbuffers.number_types." +
- MakeCamel(GenTypeGet(type)) + "Flags, ";
+ namer_.Method(GenTypeGet(type)) + "Flags, ";
}
}
// Returns the method name for use with add/put calls.
- std::string GenMethod(const FieldDef &field) {
+ std::string GenMethod(const FieldDef &field) const {
return (IsScalar(field.value.type.base_type) || IsArray(field.value.type))
- ? MakeCamel(GenTypeBasic(field.value.type))
+ ? namer_.Method(GenTypeBasic(field.value.type))
: (IsStruct(field.value.type) ? "Struct" : "UOffsetTRelative");
}
- std::string GenTypeBasic(const Type &type) {
+ std::string GenTypeBasic(const Type &type) const {
// clang-format off
static const char *ctypename[] = {
#define FLATBUFFERS_TD(ENUM, IDLTYPE, \
@@ -1552,7 +1659,7 @@
: type.base_type];
}
- std::string GenTypePointer(const Type &type) {
+ std::string GenTypePointer(const Type &type) const {
switch (type.base_type) {
case BASE_TYPE_STRING: return "string";
case BASE_TYPE_VECTOR: return GenTypeGet(type.VectorType());
@@ -1563,16 +1670,17 @@
}
}
- std::string GenTypeGet(const Type &type) {
+ std::string GenTypeGet(const Type &type) const {
return IsScalar(type.base_type) ? GenTypeBasic(type) : GenTypePointer(type);
}
- std::string TypeName(const FieldDef &field) {
+ std::string TypeName(const FieldDef &field) const {
return GenTypeGet(field.value.type);
}
// Create a struct with a builder and the struct's arguments.
- void GenStructBuilder(const StructDef &struct_def, std::string *code_ptr) {
+ void GenStructBuilder(const StructDef &struct_def,
+ std::string *code_ptr) const {
BeginBuilderArgs(struct_def, code_ptr);
StructBuilderArgs(struct_def,
/* nameprefix = */ "",
@@ -1586,13 +1694,21 @@
}
bool generate() {
- if (!generateEnums()) return false;
- if (!generateStructs()) return false;
+ std::string one_file_code;
+ if (!generateEnums(&one_file_code)) return false;
+ if (!generateStructs(&one_file_code)) return false;
+
+ if (parser_.opts.one_file) {
+ // Legacy file format uses keep casing.
+ return SaveType(file_name_ + "_generated.py", *parser_.current_namespace_,
+ one_file_code, true);
+ }
+
return true;
}
private:
- bool generateEnums() {
+ bool generateEnums(std::string *one_file_code) const {
for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end();
++it) {
auto &enum_def = **it;
@@ -1601,12 +1717,19 @@
if (parser_.opts.generate_object_based_api & enum_def.is_union) {
GenUnionCreator(enum_def, &enumcode);
}
- if (!SaveType(enum_def, enumcode, false)) return false;
+
+ if (parser_.opts.one_file && !enumcode.empty()) {
+ *one_file_code += enumcode + "\n\n";
+ } else {
+ if (!SaveType(namer_.File(enum_def.name, SkipFile::Suffix),
+ *enum_def.defined_namespace, enumcode, false))
+ return false;
+ }
}
return true;
}
- bool generateStructs() {
+ bool generateStructs(std::string *one_file_code) const {
for (auto it = parser_.structs_.vec.begin();
it != parser_.structs_.vec.end(); ++it) {
auto &struct_def = **it;
@@ -1615,14 +1738,21 @@
if (parser_.opts.generate_object_based_api) {
GenStructForObjectAPI(struct_def, &declcode);
}
- if (!SaveType(struct_def, declcode, true)) return false;
+
+ if (parser_.opts.one_file && !declcode.empty()) {
+ *one_file_code += declcode + "\n\n";
+ } else {
+ if (!SaveType(namer_.File(struct_def.name, SkipFile::Suffix),
+ *struct_def.defined_namespace, declcode, true))
+ return false;
+ }
}
return true;
}
// Begin by declaring namespace and imports.
void BeginFile(const std::string &name_space_name, const bool needs_imports,
- std::string *code_ptr) {
+ std::string *code_ptr) const {
auto &code = *code_ptr;
code = code + "# " + FlatBuffersGeneratedWarning() + "\n\n";
code += "# namespace: " + name_space_name + "\n\n";
@@ -1634,30 +1764,32 @@
}
// Save out the generated code for a Python Table type.
- bool SaveType(const Definition &def, const std::string &classcode,
- bool needs_imports) {
+ bool SaveType(const std::string &defname, const Namespace &ns,
+ const std::string &classcode, bool needs_imports) const {
if (!classcode.length()) return true;
- std::string namespace_dir = path_;
- auto &namespaces = def.defined_namespace->components;
- for (auto it = namespaces.begin(); it != namespaces.end(); ++it) {
- if (it != namespaces.begin()) namespace_dir += kPathSeparator;
- namespace_dir += *it;
- std::string init_py_filename = namespace_dir + "/__init__.py";
- SaveFile(init_py_filename.c_str(), "", false);
+ std::string code = "";
+ BeginFile(LastNamespacePart(ns), needs_imports, &code);
+ code += classcode;
+
+ const std::string directories =
+ parser_.opts.one_file ? path_ : namer_.Directories(ns.components);
+ EnsureDirExists(directories);
+
+ for (size_t i = path_.size() + 1; i != std::string::npos;
+ i = directories.find(kPathSeparator, i + 1)) {
+ const std::string init_py =
+ directories.substr(0, i) + kPathSeparator + "__init__.py";
+ SaveFile(init_py.c_str(), "", false);
}
- std::string code = "";
- BeginFile(LastNamespacePart(*def.defined_namespace), needs_imports, &code);
- code += classcode;
- std::string filename =
- NamespaceDir(*def.defined_namespace) + NormalizedName(def) + ".py";
+ const std::string filename = directories + defname;
return SaveFile(filename.c_str(), code, false);
}
private:
- std::unordered_set<std::string> keywords_;
const SimpleFloatConstantGenerator float_const_gen_;
+ const Namer namer_;
};
} // namespace python
diff --git a/src/idl_gen_rust.cpp b/src/idl_gen_rust.cpp
index 3995a7f..17853a0 100644
--- a/src/idl_gen_rust.cpp
+++ b/src/idl_gen_rust.cpp
@@ -20,35 +20,119 @@
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
+#include "namer.h"
namespace flatbuffers {
-// Convert a camelCaseIdentifier or CamelCaseIdentifier to a
-// snake_case_indentifier.
-std::string MakeSnakeCase(const std::string &in) {
- std::string s;
- for (size_t i = 0; i < in.length(); i++) {
- if (i == 0) {
- s += CharToLower(in[0]);
- } else if (in[i] == '_') {
- s += '_';
- } else if (!islower(in[i])) {
- // Prevent duplicate underscores for Upper_Snake_Case strings
- // and UPPERCASE strings.
- if (islower(in[i - 1])) { s += '_'; }
- s += CharToLower(in[i]);
- } else {
- s += in[i];
- }
- }
- return s;
+Namer::Config RustDefaultConfig() {
+ // Historical note: We've been using "keep" casing since the original
+ // implementation, presumably because Flatbuffers schema style and Rust style
+ // roughly align. We are not going to enforce proper casing since its an
+ // unnecessary breaking change.
+ return { /*types=*/Case::kKeep,
+ /*constants=*/Case::kScreamingSnake,
+ /*methods=*/Case::kSnake,
+ /*functions=*/Case::kSnake,
+ /*fields=*/Case::kKeep,
+ /*variables=*/Case::kUnknown, // Unused.
+ /*variants=*/Case::kKeep,
+ /*enum_variant_seperator=*/"::",
+ /*namespaces=*/Case::kSnake,
+ /*namespace_seperator=*/"::",
+ /*object_prefix=*/"",
+ /*object_suffix=*/"T",
+ /*keyword_prefix=*/"",
+ /*keyword_suffix=*/"_",
+ /*filenames=*/Case::kSnake,
+ /*directories=*/Case::kSnake,
+ /*output_path=*/"",
+ /*filename_suffix=*/"_generated",
+ /*filename_extension=*/".rs" };
}
-// Convert a string to all uppercase.
-std::string MakeUpper(const std::string &in) {
- std::string s;
- for (size_t i = 0; i < in.length(); i++) { s += CharToUpper(in[i]); }
- return s;
+std::set<std::string> RustKeywords() {
+ return {
+ // https://doc.rust-lang.org/book/second-edition/appendix-01-keywords.html
+ "as",
+ "break",
+ "const",
+ "continue",
+ "crate",
+ "else",
+ "enum",
+ "extern",
+ "false",
+ "fn",
+ "for",
+ "if",
+ "impl",
+ "in",
+ "let",
+ "loop",
+ "match",
+ "mod",
+ "move",
+ "mut",
+ "pub",
+ "ref",
+ "return",
+ "Self",
+ "self",
+ "static",
+ "struct",
+ "super",
+ "trait",
+ "true",
+ "type",
+ "unsafe",
+ "use",
+ "where",
+ "while",
+ // future possible keywords
+ "abstract",
+ "alignof",
+ "become",
+ "box",
+ "do",
+ "final",
+ "macro",
+ "offsetof",
+ "override",
+ "priv",
+ "proc",
+ "pure",
+ "sizeof",
+ "typeof",
+ "unsized",
+ "virtual",
+ "yield",
+ // other rust terms we should not use
+ "std",
+ "usize",
+ "isize",
+ "u8",
+ "i8",
+ "u16",
+ "i16",
+ "u32",
+ "i32",
+ "u64",
+ "i64",
+ "u128",
+ "i128",
+ "f32",
+ "f64",
+ // Terms that we use ourselves
+ "follow",
+ "push",
+ "size",
+ "alignment",
+ "to_little_endian",
+ "from_little_endian",
+ "ENUM_MAX",
+ "ENUM_MIN",
+ "ENUM_VALUES",
+ };
}
// Encapsulate all logical field types in this enum. This allows us to write
@@ -81,6 +165,10 @@
ftVectorOfTable = 14,
ftVectorOfString = 15,
ftVectorOfUnionValue = 16,
+
+ ftArrayOfBuiltin = 17,
+ ftArrayOfEnum = 18,
+ ftArrayOfStruct = 19,
};
// Convert a Type to a FullType (exhaustive).
@@ -127,6 +215,23 @@
FLATBUFFERS_ASSERT(false && "vector of vectors are unsupported");
}
}
+ } else if (IsArray(type)) {
+ switch (GetFullType(type.VectorType())) {
+ case ftInteger:
+ case ftFloat:
+ case ftBool: {
+ return ftArrayOfBuiltin;
+ }
+ case ftStruct: {
+ return ftArrayOfStruct;
+ }
+ case ftEnumKey: {
+ return ftArrayOfEnum;
+ }
+ default: {
+ FLATBUFFERS_ASSERT(false && "Unsupported type for fixed array");
+ }
+ }
} else if (type.enum_def != nullptr) {
if (type.enum_def->is_union) {
if (type.base_type == BASE_TYPE_UNION) {
@@ -157,30 +262,78 @@
return ftBool;
}
-// If the second parameter is false then wrap the first with Option<...>
-std::string WrapInOptionIfNotRequired(std::string s, bool required) {
- if (required) {
- return s;
- } else {
- return "Option<" + s + ">";
- }
-}
-
-// If the second parameter is false then add .unwrap()
-std::string AddUnwrapIfRequired(std::string s, bool required) {
- if (required) {
- return s + ".unwrap()";
- } else {
- return s;
- }
-}
-
bool IsBitFlagsEnum(const EnumDef &enum_def) {
return enum_def.attributes.Lookup("bit_flags") != nullptr;
}
-bool IsBitFlagsEnum(const FieldDef &field) {
- EnumDef* ed = field.value.type.enum_def;
- return ed && IsBitFlagsEnum(*ed);
+
+// TableArgs make required non-scalars "Option<_>".
+// TODO(cneo): Rework how we do defaults and stuff.
+bool IsOptionalToBuilder(const FieldDef &field) {
+ return field.IsOptional() || !IsScalar(field.value.type.base_type);
+}
+
+bool GenerateRustModuleRootFile(const Parser &parser,
+ const std::string &output_dir) {
+ if (!parser.opts.rust_module_root_file) {
+ // Don't generate a root file when generating one file. This isn't an error
+ // so return true.
+ return true;
+ }
+ Namer namer(RustDefaultConfig().WithFlagOptions(parser.opts, output_dir),
+ RustKeywords());
+ // We gather the symbols into a tree of namespaces (which are rust mods) and
+ // generate a file that gathers them all.
+ struct Module {
+ std::map<std::string, Module> sub_modules;
+ std::vector<std::string> generated_files;
+ // Add a symbol into the tree.
+ void Insert(const Namer &namer, const Definition *s) {
+ const Definition &symbol = *s;
+ Module *current_module = this;
+ for (auto it = symbol.defined_namespace->components.begin();
+ it != symbol.defined_namespace->components.end(); it++) {
+ std::string ns_component = namer.Namespace(*it);
+ current_module = ¤t_module->sub_modules[ns_component];
+ }
+ current_module->generated_files.push_back(
+ namer.File(symbol.name, SkipFile::Extension));
+ }
+ // Recursively create the importer file.
+ void GenerateImports(CodeWriter &code) {
+ for (auto it = sub_modules.begin(); it != sub_modules.end(); it++) {
+ code += "pub mod " + it->first + " {";
+ code.IncrementIdentLevel();
+ code += "use super::*;";
+ it->second.GenerateImports(code);
+ code.DecrementIdentLevel();
+ code += "} // " + it->first;
+ }
+ for (auto it = generated_files.begin(); it != generated_files.end();
+ it++) {
+ code += "mod " + *it + ";";
+ code += "pub use self::" + *it + "::*;";
+ }
+ }
+ };
+ Module root_module;
+ for (auto it = parser.enums_.vec.begin(); it != parser.enums_.vec.end();
+ it++) {
+ root_module.Insert(namer, *it);
+ }
+ for (auto it = parser.structs_.vec.begin(); it != parser.structs_.vec.end();
+ it++) {
+ root_module.Insert(namer, *it);
+ }
+ CodeWriter code(" ");
+ // TODO(caspern): Move generated warning out of BaseGenerator.
+ code +=
+ "// Automatically generated by the Flatbuffers compiler. "
+ "Do not modify.";
+ root_module.GenerateImports(code);
+ const bool success =
+ SaveFile((output_dir + "mod.rs").c_str(), code.ToString(), false);
+ code.Clear();
+ return success;
}
namespace rust {
@@ -190,50 +343,79 @@
RustGenerator(const Parser &parser, const std::string &path,
const std::string &file_name)
: BaseGenerator(parser, path, file_name, "", "::", "rs"),
- cur_name_space_(nullptr) {
- const char *keywords[] = {
- // list taken from:
- // https://doc.rust-lang.org/book/second-edition/appendix-01-keywords.html
- //
- // we write keywords one per line so that we can easily compare them with
- // changes to that webpage in the future.
-
- // currently-used keywords
- "as", "break", "const", "continue", "crate", "else", "enum", "extern",
- "false", "fn", "for", "if", "impl", "in", "let", "loop", "match", "mod",
- "move", "mut", "pub", "ref", "return", "Self", "self", "static", "struct",
- "super", "trait", "true", "type", "unsafe", "use", "where", "while",
-
- // future possible keywords
- "abstract", "alignof", "become", "box", "do", "final", "macro",
- "offsetof", "override", "priv", "proc", "pure", "sizeof", "typeof",
- "unsized", "virtual", "yield",
-
- // other rust terms we should not use
- "std", "usize", "isize", "u8", "i8", "u16", "i16", "u32", "i32", "u64",
- "i64", "u128", "i128", "f32", "f64",
-
- // These are terms the code generator can implement on types.
- //
- // In Rust, the trait resolution rules (as described at
- // https://github.com/rust-lang/rust/issues/26007) mean that, as long
- // as we impl table accessors as inherent methods, we'll never create
- // conflicts with these keywords. However, that's a fairly nuanced
- // implementation detail, and how we implement methods could change in
- // the future. as a result, we proactively block these out as reserved
- // words.
- "follow", "push", "size", "alignment", "to_little_endian",
- "from_little_endian", nullptr,
-
- // used by Enum constants
- "ENUM_MAX", "ENUM_MIN", "ENUM_VALUES",
- };
- for (auto kw = keywords; *kw; kw++) keywords_.insert(*kw);
+ cur_name_space_(nullptr),
+ namer_({ RustDefaultConfig().WithFlagOptions(parser.opts, path),
+ RustKeywords() }) {
+ // TODO: Namer flag overrides should be in flatc or flatc_main.
+ code_.SetPadding(" ");
}
+ bool generate() {
+ if (!parser_.opts.rust_module_root_file) {
+ return GenerateOneFile();
+ } else {
+ return GenerateIndividualFiles();
+ }
+ }
+
+ template<typename T>
+ bool GenerateSymbols(const SymbolTable<T> &symbols,
+ std::function<void(const T &)> gen_symbol) {
+ for (auto it = symbols.vec.begin(); it != symbols.vec.end(); it++) {
+ const T &symbol = **it;
+ if (symbol.generated) continue;
+ code_.Clear();
+ code_ += "// " + std::string(FlatBuffersGeneratedWarning());
+ code_ += "extern crate flatbuffers;";
+ code_ += "use std::mem;";
+ code_ += "use std::cmp::Ordering;";
+ if (parser_.opts.rust_serialize) {
+ code_ += "extern crate serde;";
+ code_ +=
+ "use self::serde::ser::{Serialize, Serializer, SerializeStruct};";
+ }
+ code_ += "use self::flatbuffers::{EndianScalar, Follow};";
+ code_ += "use super::*;";
+ cur_name_space_ = symbol.defined_namespace;
+ gen_symbol(symbol);
+
+ const std::string directories =
+ namer_.Directories(symbol.defined_namespace->components);
+ EnsureDirExists(directories);
+ const std::string file_path = directories + namer_.File(symbol.name);
+ const bool save_success =
+ SaveFile(file_path.c_str(), code_.ToString(), /*binary=*/false);
+ if (!save_success) return false;
+ }
+ return true;
+ }
+
+ bool GenerateIndividualFiles() {
+ code_.Clear();
+ // Don't bother with imports. Use absolute paths everywhere.
+ return GenerateSymbols<EnumDef>(
+ parser_.enums_, [&](const EnumDef &e) { this->GenEnum(e); }) &&
+ GenerateSymbols<StructDef>(
+ parser_.structs_, [&](const StructDef &s) {
+ if (s.fixed) {
+ this->GenStruct(s);
+ } else {
+ this->GenTable(s);
+ if (this->parser_.opts.generate_object_based_api) {
+ this->GenTableObject(s);
+ }
+ }
+ if (this->parser_.root_struct_def_ == &s) {
+ this->GenRootTableFuncs(s);
+ }
+ });
+ }
+
+ // Generates code organized by .fbs files. This is broken legacy behavior
+ // that does not work with multiple fbs files with shared namespaces.
// Iterate through all definitions we haven't generated code for (enums,
// structs, and tables) and output them to a single file.
- bool generate() {
+ bool GenerateOneFile() {
code_.Clear();
code_ += "// " + std::string(FlatBuffersGeneratedWarning()) + "\n\n";
@@ -257,8 +439,7 @@
for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end();
++it) {
const auto &enum_def = **it;
- if (enum_def.defined_namespace != ns) { continue; }
- if (!enum_def.generated) {
+ if (enum_def.defined_namespace == ns && !enum_def.generated) {
SetNameSpace(enum_def.defined_namespace);
GenEnum(enum_def);
}
@@ -268,8 +449,8 @@
for (auto it = parser_.structs_.vec.begin();
it != parser_.structs_.vec.end(); ++it) {
const auto &struct_def = **it;
- if (struct_def.defined_namespace != ns) { continue; }
- if (struct_def.fixed && !struct_def.generated) {
+ if (struct_def.defined_namespace == ns && struct_def.fixed &&
+ !struct_def.generated) {
SetNameSpace(struct_def.defined_namespace);
GenStruct(struct_def);
}
@@ -279,10 +460,13 @@
for (auto it = parser_.structs_.vec.begin();
it != parser_.structs_.vec.end(); ++it) {
const auto &struct_def = **it;
- if (struct_def.defined_namespace != ns) { continue; }
- if (!struct_def.fixed && !struct_def.generated) {
+ if (struct_def.defined_namespace == ns && !struct_def.fixed &&
+ !struct_def.generated) {
SetNameSpace(struct_def.defined_namespace);
GenTable(struct_def);
+ if (parser_.opts.generate_object_based_api) {
+ GenTableObject(struct_def);
+ }
}
}
@@ -304,8 +488,6 @@
private:
CodeWriter code_;
- std::set<std::string> keywords_;
-
// This tracks the current namespace so we can insert namespace declarations.
const Namespace *cur_name_space_;
@@ -344,18 +526,13 @@
return false;
}
- std::string EscapeKeyword(const std::string &name) const {
- return keywords_.find(name) == keywords_.end() ? name : name + "_";
+ std::string NamespacedNativeName(const Definition &def) {
+ return WrapInNameSpace(def.defined_namespace, namer_.ObjectType(def.name));
}
- std::string Name(const Definition &def) const {
- return EscapeKeyword(def.name);
- }
-
- std::string Name(const EnumVal &ev) const { return EscapeKeyword(ev.name); }
-
std::string WrapInNameSpace(const Definition &def) const {
- return WrapInNameSpace(def.defined_namespace, Name(def));
+ return WrapInNameSpace(def.defined_namespace,
+ namer_.EscapeKeyword(def.name));
}
std::string WrapInNameSpace(const Namespace *ns,
const std::string &name) const {
@@ -364,19 +541,6 @@
return prefix + name;
}
- // Determine the namespace traversal needed from the Rust crate root.
- // This may be useful in the future for referring to included files, but is
- // currently unused.
- std::string GetAbsoluteNamespaceTraversal(const Namespace *dst) const {
- std::stringstream stream;
-
- stream << "::";
- for (auto d = dst->components.begin(); d != dst->components.end(); ++d) {
- stream << MakeSnakeCase(*d) + "::";
- }
- return stream.str();
- }
-
// Determine the relative namespace traversal needed to reference one
// namespace from another namespace. This is useful because it does not force
// the user to have a particular file layout. (If we output absolute
@@ -394,32 +558,25 @@
// example: f(A, D::E) -> super::D::E
// does not include leaf object (typically a struct type).
- size_t i = 0;
std::stringstream stream;
-
- auto s = src->components.begin();
- auto d = dst->components.begin();
- for (;;) {
- if (s == src->components.end()) { break; }
- if (d == dst->components.end()) { break; }
- if (*s != *d) { break; }
- ++s;
- ++d;
- ++i;
- }
-
- for (; s != src->components.end(); ++s) { stream << "super::"; }
- for (; d != dst->components.end(); ++d) {
- stream << MakeSnakeCase(*d) + "::";
- }
+ size_t common = 0;
+ std::vector<std::string> s, d;
+ if (src) s = src->components;
+ if (dst) d = dst->components;
+ while (common < s.size() && common < d.size() && s[common] == d[common])
+ common++;
+ // If src namespace is empty, this must be an absolute path.
+ for (size_t i = common; i < s.size(); i++) stream << "super::";
+ for (size_t i = common; i < d.size(); i++)
+ stream << namer_.Namespace(d[i]) + "::";
return stream.str();
}
// Generate a comment from the schema.
void GenComment(const std::vector<std::string> &dc, const char *prefix = "") {
- std::string text;
- ::flatbuffers::GenComment(dc, &text, nullptr, prefix);
- code_ += text + "\\";
+ for (auto it = dc.begin(); it != dc.end(); it++) {
+ code_ += std::string(prefix) + "///" + *it;
+ }
}
// Return a Rust type from the table in idl.h.
@@ -486,6 +643,12 @@
case ftUnionKey: {
return GetTypeBasic(type);
}
+ case ftArrayOfBuiltin:
+ case ftArrayOfEnum:
+ case ftArrayOfStruct: {
+ return "[" + GetTypeGet(type.VectorType()) + "; " +
+ NumToString(type.fixed_length) + "]";
+ }
case ftTable: {
return WrapInNameSpace(type.struct_def->defined_namespace,
type.struct_def->name) +
@@ -499,36 +662,38 @@
}
std::string GetEnumValue(const EnumDef &enum_def,
- const EnumVal &enum_val) const {
- return Name(enum_def) + "::" + Name(enum_val);
+ const EnumVal &enum_val) const {
+ return namer_.EnumVariant(enum_def.name, enum_val.name);
}
// 1 suffix since old C++ can't figure out the overload.
void ForAllEnumValues1(const EnumDef &enum_def,
- std::function<void(const EnumVal&)> cb) {
+ std::function<void(const EnumVal &)> cb) {
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
const auto &ev = **it;
- code_.SetValue("VARIANT", Name(ev));
+ code_.SetValue("VARIANT", namer_.Variant(ev.name));
code_.SetValue("VALUE", enum_def.ToString(ev));
+ code_.IncrementIdentLevel();
cb(ev);
+ code_.DecrementIdentLevel();
}
}
void ForAllEnumValues(const EnumDef &enum_def, std::function<void()> cb) {
- std::function<void(const EnumVal&)> wrapped = [&](const EnumVal& unused) {
- (void) unused;
- cb();
- };
- ForAllEnumValues1(enum_def, wrapped);
+ std::function<void(const EnumVal &)> wrapped = [&](const EnumVal &unused) {
+ (void)unused;
+ cb();
+ };
+ ForAllEnumValues1(enum_def, wrapped);
}
// Generate an enum declaration,
// an enum string lookup table,
// an enum match function,
// and an enum array of values
void GenEnum(const EnumDef &enum_def) {
- code_.SetValue("ENUM_NAME", Name(enum_def));
+ code_.SetValue("ENUM_TY", namer_.Type(enum_def.name));
code_.SetValue("BASE_TYPE", GetEnumTypeForDecl(enum_def.underlying_type));
- code_.SetValue("ENUM_NAME_SNAKE", MakeSnakeCase(Name(enum_def)));
- code_.SetValue("ENUM_NAME_CAPS", MakeUpper(MakeSnakeCase(Name(enum_def))));
+ code_.SetValue("ENUM_NAMESPACE", namer_.Namespace(enum_def.name));
+ code_.SetValue("ENUM_CONSTANT", namer_.Constant(enum_def.name));
const EnumVal *minv = enum_def.MinValue();
const EnumVal *maxv = enum_def.MaxValue();
FLATBUFFERS_ASSERT(minv && maxv);
@@ -536,193 +701,381 @@
code_.SetValue("ENUM_MAX_BASE_VALUE", enum_def.ToString(*maxv));
if (IsBitFlagsEnum(enum_def)) {
- // Defer to the convenient and canonical bitflags crate. We declare it in a
- // module to #allow camel case constants in a smaller scope. This matches
- // Flatbuffers c-modeled enums where variants are associated constants but
- // in camel case.
+ // Defer to the convenient and canonical bitflags crate. We declare it in
+ // a module to #allow camel case constants in a smaller scope. This
+ // matches Flatbuffers c-modeled enums where variants are associated
+ // constants but in camel case.
code_ += "#[allow(non_upper_case_globals)]";
- code_ += "mod bitflags_{{ENUM_NAME_SNAKE}} {";
+ code_ += "mod bitflags_{{ENUM_NAMESPACE}} {";
code_ += " flatbuffers::bitflags::bitflags! {";
GenComment(enum_def.doc_comment, " ");
- code_ += " pub struct {{ENUM_NAME}}: {{BASE_TYPE}} {";
- ForAllEnumValues1(enum_def, [&](const EnumVal &ev){
- this->GenComment(ev.doc_comment, " ");
- code_ += " const {{VARIANT}} = {{VALUE}};";
+ code_ += " #[derive(Default)]";
+ code_ += " pub struct {{ENUM_TY}}: {{BASE_TYPE}} {";
+ ForAllEnumValues1(enum_def, [&](const EnumVal &ev) {
+ this->GenComment(ev.doc_comment, " ");
+ code_ += " const {{VARIANT}} = {{VALUE}};";
});
code_ += " }";
code_ += " }";
code_ += "}";
- code_ += "pub use self::bitflags_{{ENUM_NAME_SNAKE}}::{{ENUM_NAME}};";
+ code_ += "pub use self::bitflags_{{ENUM_NAMESPACE}}::{{ENUM_TY}};";
code_ += "";
- // Generate Follow and Push so we can serialize and stuff.
- code_ += "impl<'a> flatbuffers::Follow<'a> for {{ENUM_NAME}} {";
- code_ += " type Inner = Self;";
- code_ += " #[inline]";
- code_ += " fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {";
- code_ += " let bits = flatbuffers::read_scalar_at::<{{BASE_TYPE}}>(buf, loc);";
- code_ += " unsafe { Self::from_bits_unchecked(bits) }";
- code_ += " }";
- code_ += "}";
+ code_.SetValue("FROM_BASE", "unsafe { Self::from_bits_unchecked(b) }");
+ code_.SetValue("INTO_BASE", "self.bits()");
+ } else {
+ // Normal, c-modelled enums.
+ // Deprecated associated constants;
+ const std::string deprecation_warning =
+ "#[deprecated(since = \"2.0.0\", note = \"Use associated constants"
+ " instead. This will no longer be generated in 2021.\")]";
+ code_ += deprecation_warning;
+ code_ +=
+ "pub const ENUM_MIN_{{ENUM_CONSTANT}}: {{BASE_TYPE}}"
+ " = {{ENUM_MIN_BASE_VALUE}};";
+ code_ += deprecation_warning;
+ code_ +=
+ "pub const ENUM_MAX_{{ENUM_CONSTANT}}: {{BASE_TYPE}}"
+ " = {{ENUM_MAX_BASE_VALUE}};";
+ auto num_fields = NumToString(enum_def.size());
+ code_ += deprecation_warning;
+ code_ += "#[allow(non_camel_case_types)]";
+ code_ += "pub const ENUM_VALUES_{{ENUM_CONSTANT}}: [{{ENUM_TY}}; " +
+ num_fields + "] = [";
+ ForAllEnumValues1(enum_def, [&](const EnumVal &ev) {
+ code_ += namer_.EnumVariant(enum_def.name, ev.name) + ",";
+ });
+ code_ += "];";
code_ += "";
- code_ += "impl flatbuffers::Push for {{ENUM_NAME}} {";
- code_ += " type Output = {{ENUM_NAME}};";
- code_ += " #[inline]";
- code_ += " fn push(&self, dst: &mut [u8], _rest: &[u8]) {";
- code_ += " flatbuffers::emplace_scalar::<{{BASE_TYPE}}>"
- "(dst, self.bits());";
+
+ GenComment(enum_def.doc_comment);
+ // Derive Default to be 0. flatc enforces this when the enum
+ // is put into a struct, though this isn't documented behavior, it is
+ // needed to derive defaults in struct objects.
+ code_ +=
+ "#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, "
+ "Default)]";
+ code_ += "#[repr(transparent)]";
+ code_ += "pub struct {{ENUM_TY}}(pub {{BASE_TYPE}});";
+ code_ += "#[allow(non_upper_case_globals)]";
+ code_ += "impl {{ENUM_TY}} {";
+ ForAllEnumValues1(enum_def, [&](const EnumVal &ev) {
+ this->GenComment(ev.doc_comment);
+ code_ += "pub const {{VARIANT}}: Self = Self({{VALUE}});";
+ });
+ code_ += "";
+ // Generate Associated constants
+ code_ += " pub const ENUM_MIN: {{BASE_TYPE}} = {{ENUM_MIN_BASE_VALUE}};";
+ code_ += " pub const ENUM_MAX: {{BASE_TYPE}} = {{ENUM_MAX_BASE_VALUE}};";
+ code_ += " pub const ENUM_VALUES: &'static [Self] = &[";
+ ForAllEnumValues(enum_def, [&]() { code_ += " Self::{{VARIANT}},"; });
+ code_ += " ];";
+ code_ += " /// Returns the variant's name or \"\" if unknown.";
+ code_ += " pub fn variant_name(self) -> Option<&'static str> {";
+ code_ += " match self {";
+ ForAllEnumValues(enum_def, [&]() {
+ code_ += " Self::{{VARIANT}} => Some(\"{{VARIANT}}\"),";
+ });
+ code_ += " _ => None,";
code_ += " }";
- code_ += "}";
- code_ += "";
- code_ += "impl flatbuffers::EndianScalar for {{ENUM_NAME}} {";
- code_ += " #[inline]";
- code_ += " fn to_little_endian(self) -> Self {";
- code_ += " let bits = {{BASE_TYPE}}::to_le(self.bits());";
- code_ += " unsafe { Self::from_bits_unchecked(bits) }";
- code_ += " }";
- code_ += " #[inline]";
- code_ += " fn from_little_endian(self) -> Self {";
- code_ += " let bits = {{BASE_TYPE}}::from_le(self.bits());";
- code_ += " unsafe { Self::from_bits_unchecked(bits) }";
code_ += " }";
code_ += "}";
- code_ += "";
- return;
+
+ // Generate Debug. Unknown variants are printed like "<UNKNOWN 42>".
+ code_ += "impl std::fmt::Debug for {{ENUM_TY}} {";
+ code_ +=
+ " fn fmt(&self, f: &mut std::fmt::Formatter) ->"
+ " std::fmt::Result {";
+ code_ += " if let Some(name) = self.variant_name() {";
+ code_ += " f.write_str(name)";
+ code_ += " } else {";
+ code_ += " f.write_fmt(format_args!(\"<UNKNOWN {:?}>\", self.0))";
+ code_ += " }";
+ code_ += " }";
+ code_ += "}";
+
+ code_.SetValue("FROM_BASE", "Self(b)");
+ code_.SetValue("INTO_BASE", "self.0");
}
- // Deprecated associated constants;
- code_ += "#[deprecated(since = \"1.13\", note = \"Use associated constants"
- " instead. This will no longer be generated in 2021.\")]";
- code_ += "pub const ENUM_MIN_{{ENUM_NAME_CAPS}}: {{BASE_TYPE}}"
- " = {{ENUM_MIN_BASE_VALUE}};";
- code_ += "#[deprecated(since = \"1.13\", note = \"Use associated constants"
- " instead. This will no longer be generated in 2021.\")]";
- code_ += "pub const ENUM_MAX_{{ENUM_NAME_CAPS}}: {{BASE_TYPE}}"
- " = {{ENUM_MAX_BASE_VALUE}};";
- auto num_fields = NumToString(enum_def.size());
- code_ += "#[deprecated(since = \"1.13\", note = \"Use associated constants"
- " instead. This will no longer be generated in 2021.\")]";
- code_ += "#[allow(non_camel_case_types)]";
- code_ += "pub const ENUM_VALUES_{{ENUM_NAME_CAPS}}: [{{ENUM_NAME}}; " +
- num_fields + "] = [";
- ForAllEnumValues1(enum_def, [&](const EnumVal &ev){
- code_ += " " + GetEnumValue(enum_def, ev) + ",";
- });
- code_ += "];";
- code_ += "";
-
- GenComment(enum_def.doc_comment);
- code_ +=
- "#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]";
- code_ += "#[repr(transparent)]";
- code_ += "pub struct {{ENUM_NAME}}(pub {{BASE_TYPE}});";
- code_ += "#[allow(non_upper_case_globals)]";
- code_ += "impl {{ENUM_NAME}} {";
- ForAllEnumValues1(enum_def, [&](const EnumVal &ev){
- this->GenComment(ev.doc_comment, " ");
- code_ += " pub const {{VARIANT}}: Self = Self({{VALUE}});";
- });
- code_ += "";
- // Generate Associated constants
- code_ += " pub const ENUM_MIN: {{BASE_TYPE}} = {{ENUM_MIN_BASE_VALUE}};";
- code_ += " pub const ENUM_MAX: {{BASE_TYPE}} = {{ENUM_MAX_BASE_VALUE}};";
- code_ += " pub const ENUM_VALUES: &'static [Self] = &[";
- ForAllEnumValues(enum_def, [&](){
- code_ += " Self::{{VARIANT}},";
- });
- code_ += " ];";
- code_ += " /// Returns the variant's name or \"\" if unknown.";
- code_ += " pub fn variant_name(self) -> Option<&'static str> {";
- code_ += " match self {";
- ForAllEnumValues(enum_def, [&](){
- code_ += " Self::{{VARIANT}} => Some(\"{{VARIANT}}\"),";
- });
- code_ += " _ => None,";
- code_ += " }";
- code_ += " }";
- code_ += "}";
-
- // Generate Debug. Unknown variants are printed like "<UNKNOWN 42>".
- code_ += "impl std::fmt::Debug for {{ENUM_NAME}} {";
- code_ += " fn fmt(&self, f: &mut std::fmt::Formatter) ->"
- " std::fmt::Result {";
- code_ += " if let Some(name) = self.variant_name() {";
- code_ += " f.write_str(name)";
- code_ += " } else {";
- code_ += " f.write_fmt(format_args!(\"<UNKNOWN {:?}>\", self.0))";
- code_ += " }";
- code_ += " }";
- code_ += "}";
+ // Implement serde::Serialize
+ if (parser_.opts.rust_serialize) {
+ code_ += "impl Serialize for {{ENUM_TY}} {";
+ code_ +=
+ " fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>";
+ code_ += " where";
+ code_ += " S: Serializer,";
+ code_ += " {";
+ if (IsBitFlagsEnum(enum_def)) {
+ code_ += " serializer.serialize_u32(self.bits() as u32)";
+ } else {
+ code_ +=
+ " serializer.serialize_unit_variant(\"{{ENUM_TY}}\", self.0 "
+ "as "
+ "u32, self.variant_name().unwrap())";
+ }
+ code_ += " }";
+ code_ += "}";
+ code_ += "";
+ }
// Generate Follow and Push so we can serialize and stuff.
- code_ += "impl<'a> flatbuffers::Follow<'a> for {{ENUM_NAME}} {";
+ code_ += "impl<'a> flatbuffers::Follow<'a> for {{ENUM_TY}} {";
code_ += " type Inner = Self;";
code_ += " #[inline]";
code_ += " fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {";
- code_ += " Self(flatbuffers::read_scalar_at::<{{BASE_TYPE}}>(buf, loc))";
+ code_ += " let b = unsafe {";
+ code_ += " flatbuffers::read_scalar_at::<{{BASE_TYPE}}>(buf, loc)";
+ code_ += " };";
+ code_ += " {{FROM_BASE}}";
code_ += " }";
code_ += "}";
code_ += "";
- code_ += "impl flatbuffers::Push for {{ENUM_NAME}} {";
- code_ += " type Output = {{ENUM_NAME}};";
+ code_ += "impl flatbuffers::Push for {{ENUM_TY}} {";
+ code_ += " type Output = {{ENUM_TY}};";
code_ += " #[inline]";
code_ += " fn push(&self, dst: &mut [u8], _rest: &[u8]) {";
- code_ += " flatbuffers::emplace_scalar::<{{BASE_TYPE}}>"
- "(dst, self.0);";
+ code_ +=
+ " unsafe { flatbuffers::emplace_scalar::<{{BASE_TYPE}}>"
+ "(dst, {{INTO_BASE}}); }";
code_ += " }";
code_ += "}";
code_ += "";
- code_ += "impl flatbuffers::EndianScalar for {{ENUM_NAME}} {";
+ code_ += "impl flatbuffers::EndianScalar for {{ENUM_TY}} {";
code_ += " #[inline]";
code_ += " fn to_little_endian(self) -> Self {";
- code_ += " Self({{BASE_TYPE}}::to_le(self.0))";
+ code_ += " let b = {{BASE_TYPE}}::to_le({{INTO_BASE}});";
+ code_ += " {{FROM_BASE}}";
code_ += " }";
code_ += " #[inline]";
+ code_ += " #[allow(clippy::wrong_self_convention)]";
code_ += " fn from_little_endian(self) -> Self {";
- code_ += " Self({{BASE_TYPE}}::from_le(self.0))";
+ code_ += " let b = {{BASE_TYPE}}::from_le({{INTO_BASE}});";
+ code_ += " {{FROM_BASE}}";
code_ += " }";
code_ += "}";
code_ += "";
+ // Generate verifier - deferring to the base type.
+ code_ += "impl<'a> flatbuffers::Verifiable for {{ENUM_TY}} {";
+ code_ += " #[inline]";
+ code_ += " fn run_verifier(";
+ code_ += " v: &mut flatbuffers::Verifier, pos: usize";
+ code_ += " ) -> Result<(), flatbuffers::InvalidFlatbuffer> {";
+ code_ += " use self::flatbuffers::Verifiable;";
+ code_ += " {{BASE_TYPE}}::run_verifier(v, pos)";
+ code_ += " }";
+ code_ += "}";
+ code_ += "";
+ // Enums are basically integers.
+ code_ += "impl flatbuffers::SimpleToVerifyInSlice for {{ENUM_TY}} {}";
+
if (enum_def.is_union) {
- // Generate tyoesafe offset(s) for unions
- code_.SetValue("NAME", Name(enum_def));
- code_.SetValue("UNION_OFFSET_NAME", Name(enum_def) + "UnionTableOffset");
- code_ += "pub struct {{UNION_OFFSET_NAME}} {}";
+ // Generate typesafe offset(s) for unions
+ code_.SetValue("UNION_TYPE", namer_.Type(enum_def.name));
+ code_ += "pub struct {{UNION_TYPE}}UnionTableOffset {}";
+ code_ += "";
+ if (parser_.opts.generate_object_based_api) { GenUnionObject(enum_def); }
}
}
+ // TODO(cneo): dedup Object versions from non object versions.
+ void ForAllUnionObjectVariantsBesidesNone(const EnumDef &enum_def,
+ std::function<void()> cb) {
+ for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
+ auto &enum_val = **it;
+ if (enum_val.union_type.base_type == BASE_TYPE_NONE) continue;
+ code_.SetValue("VARIANT_NAME", namer_.Variant(enum_val.name));
+ // For legacy reasons, enum variants are Keep case while enum native
+ // variants are UpperCamel case.
+ code_.SetValue(
+ "NATIVE_VARIANT",
+ ConvertCase(namer_.EscapeKeyword(enum_val.name), Case::kUpperCamel));
+ code_.SetValue("U_ELEMENT_NAME", namer_.Method(enum_val.name));
+ code_.SetValue("U_ELEMENT_TABLE_TYPE",
+ NamespacedNativeName(*enum_val.union_type.struct_def));
+ code_.IncrementIdentLevel();
+ cb();
+ code_.DecrementIdentLevel();
+ }
+ }
+ void GenUnionObject(const EnumDef &enum_def) {
+ code_.SetValue("ENUM_TY", namer_.Type(enum_def.name));
+ code_.SetValue("ENUM_FN", namer_.Function(enum_def.name));
+ code_.SetValue("ENUM_OTY", namer_.ObjectType(enum_def.name));
+
+ // Generate native union.
+ code_ += "#[allow(clippy::upper_case_acronyms)]"; // NONE's spelling is
+ // intended.
+ code_ += "#[non_exhaustive]";
+ code_ += "#[derive(Debug, Clone, PartialEq)]";
+ code_ += "pub enum {{ENUM_OTY}} {";
+ code_ += " NONE,";
+ ForAllUnionObjectVariantsBesidesNone(enum_def, [&] {
+ code_ += "{{NATIVE_VARIANT}}(Box<{{U_ELEMENT_TABLE_TYPE}}>),";
+ });
+ code_ += "}";
+ // Generate Default (NONE).
+ code_ += "impl Default for {{ENUM_OTY}} {";
+ code_ += " fn default() -> Self {";
+ code_ += " Self::NONE";
+ code_ += " }";
+ code_ += "}";
+
+ // Generate native union methods.
+ code_ += "impl {{ENUM_OTY}} {";
+
+ // Get flatbuffers union key.
+ // TODO(cneo): add docstrings?
+ code_ += " pub fn {{ENUM_FN}}_type(&self) -> {{ENUM_TY}} {";
+ code_ += " match self {";
+ code_ += " Self::NONE => {{ENUM_TY}}::NONE,";
+ ForAllUnionObjectVariantsBesidesNone(enum_def, [&] {
+ code_ +=
+ " Self::{{NATIVE_VARIANT}}(_) => {{ENUM_TY}}::"
+ "{{VARIANT_NAME}},";
+ });
+ code_ += " }";
+ code_ += " }";
+ // Pack flatbuffers union value
+ code_ +=
+ " pub fn pack(&self, fbb: &mut flatbuffers::FlatBufferBuilder)"
+ " -> Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>"
+ " {";
+ code_ += " match self {";
+ code_ += " Self::NONE => None,";
+ ForAllUnionObjectVariantsBesidesNone(enum_def, [&] {
+ code_ += " Self::{{NATIVE_VARIANT}}(v) => \\";
+ code_ += "Some(v.pack(fbb).as_union_value()),";
+ });
+ code_ += " }";
+ code_ += " }";
+
+ // Generate some accessors;
+ ForAllUnionObjectVariantsBesidesNone(enum_def, [&] {
+ // Move accessor.
+ code_ +=
+ "/// If the union variant matches, return the owned "
+ "{{U_ELEMENT_TABLE_TYPE}}, setting the union to NONE.";
+ code_ +=
+ "pub fn take_{{U_ELEMENT_NAME}}(&mut self) -> "
+ "Option<Box<{{U_ELEMENT_TABLE_TYPE}}>> {";
+ code_ += " if let Self::{{NATIVE_VARIANT}}(_) = self {";
+ code_ += " let v = std::mem::replace(self, Self::NONE);";
+ code_ += " if let Self::{{NATIVE_VARIANT}}(w) = v {";
+ code_ += " Some(w)";
+ code_ += " } else {";
+ code_ += " unreachable!()";
+ code_ += " }";
+ code_ += " } else {";
+ code_ += " None";
+ code_ += " }";
+ code_ += "}";
+ // Immutable reference accessor.
+ code_ +=
+ "/// If the union variant matches, return a reference to the "
+ "{{U_ELEMENT_TABLE_TYPE}}.";
+ code_ +=
+ "pub fn as_{{U_ELEMENT_NAME}}(&self) -> "
+ "Option<&{{U_ELEMENT_TABLE_TYPE}}> {";
+ code_ +=
+ " if let Self::{{NATIVE_VARIANT}}(v) = self "
+ "{ Some(v.as_ref()) } else { None }";
+ code_ += "}";
+ // Mutable reference accessor.
+ code_ +=
+ "/// If the union variant matches, return a mutable reference"
+ " to the {{U_ELEMENT_TABLE_TYPE}}.";
+ code_ +=
+ "pub fn as_{{U_ELEMENT_NAME}}_mut(&mut self) -> "
+ "Option<&mut {{U_ELEMENT_TABLE_TYPE}}> {";
+ code_ +=
+ " if let Self::{{NATIVE_VARIANT}}(v) = self "
+ "{ Some(v.as_mut()) } else { None }";
+ code_ += "}";
+ });
+ code_ += "}"; // End union methods impl.
+ }
+
std::string GetFieldOffsetName(const FieldDef &field) {
- return "VT_" + MakeUpper(Name(field));
+ // FIXME: VT_FIELD_NAME is not screaming snake case by legacy mistake.
+ // but changing this is probably a breaking change.
+ return "VT_" +
+ ConvertCase(namer_.EscapeKeyword(field.name), Case::kAllUpper);
}
- std::string GetDefaultScalarValue(const FieldDef &field) {
+ enum DefaultContext { kBuilder, kAccessor, kObject };
+ std::string GetDefaultValue(const FieldDef &field,
+ const DefaultContext context) {
+ if (context == kBuilder) {
+ // Builders and Args structs model nonscalars "optional" even if they're
+ // required or have defaults according to the schema. I guess its because
+ // WIPOffset is not nullable.
+ if (!IsScalar(field.value.type.base_type) || field.IsOptional()) {
+ return "None";
+ }
+ } else {
+ // This for defaults in objects.
+ // Unions have a NONE variant instead of using Rust's None.
+ if (field.IsOptional() && !IsUnion(field.value.type)) { return "None"; }
+ }
switch (GetFullType(field.value.type)) {
case ftInteger:
case ftFloat: {
- return field.optional ? "None" : field.value.constant;
+ return field.value.constant;
}
case ftBool: {
- return field.optional ? "None"
- : field.value.constant == "0" ? "false" : "true";
+ return field.value.constant == "0" ? "false" : "true";
}
case ftUnionKey:
case ftEnumKey: {
- if (field.optional) {
- return "None";
- }
auto ev = field.value.type.enum_def->FindByValue(field.value.constant);
- assert(ev);
- return WrapInNameSpace(field.value.type.enum_def->defined_namespace,
- GetEnumValue(*field.value.type.enum_def, *ev));
+ if (!ev) return "Default::default()"; // Bitflags enum.
+ return WrapInNameSpace(
+ field.value.type.enum_def->defined_namespace,
+ namer_.EnumVariant(field.value.type.enum_def->name, ev->name));
+ }
+ case ftUnionValue: {
+ return ObjectFieldType(field, true) + "::NONE";
+ }
+ case ftString: {
+ // Required fields do not have defaults defined by the schema, but we
+ // need one for Rust's Default trait so we use empty string. The usual
+ // value of field.value.constant is `0`, which is non-sensical except
+ // maybe to c++ (nullptr == 0).
+ // TODO: Escape strings?
+ const std::string defval =
+ field.IsRequired() ? "\"\"" : "\"" + field.value.constant + "\"";
+ if (context == kObject) return defval + ".to_string()";
+ if (context == kAccessor) return "&" + defval;
+ FLATBUFFERS_ASSERT(false);
+ return "INVALID_CODE_GENERATION";
}
- // All pointer-ish types have a default value of None, because they are
- // wrapped in Option.
- default: {
- return "None";
+ case ftArrayOfStruct:
+ case ftArrayOfEnum:
+ case ftArrayOfBuiltin:
+ case ftVectorOfBool:
+ case ftVectorOfFloat:
+ case ftVectorOfInteger:
+ case ftVectorOfString:
+ case ftVectorOfStruct:
+ case ftVectorOfTable:
+ case ftVectorOfEnumKey:
+ case ftVectorOfUnionValue:
+ case ftStruct:
+ case ftTable: {
+ // We only support empty vectors which matches the defaults for
+ // &[T] and Vec<T> anyway.
+ //
+ // For required structs and tables fields, we defer to their object API
+ // defaults. This works so long as there's nothing recursive happening,
+ // but `table Infinity { i: Infinity (required); }` does compile.
+ return "Default::default()";
}
}
+ FLATBUFFERS_ASSERT(false);
+ return "INVALID_CODE_GENERATION";
}
// Create the return type for fields in the *BuilderArgs structs that are
@@ -739,30 +1092,38 @@
std::string TableBuilderArgsDefnType(const FieldDef &field,
const std::string &lifetime) {
const Type &type = field.value.type;
+ auto WrapOption = [&](std::string s) {
+ return IsOptionalToBuilder(field) ? "Option<" + s + ">" : s;
+ };
+ auto WrapVector = [&](std::string ty) {
+ return WrapOption("flatbuffers::WIPOffset<flatbuffers::Vector<" +
+ lifetime + ", " + ty + ">>");
+ };
+ auto WrapUOffsetsVector = [&](std::string ty) {
+ return WrapVector("flatbuffers::ForwardsUOffset<" + ty + ">");
+ };
switch (GetFullType(type)) {
case ftInteger:
case ftFloat:
case ftBool: {
- const auto typname = GetTypeBasic(type);
- return field.optional ? "Option<" + typname + ">" : typname;
+ return WrapOption(GetTypeBasic(type));
}
case ftStruct: {
const auto typname = WrapInNameSpace(*type.struct_def);
- return "Option<&" + lifetime + " " + typname + ">";
+ return WrapOption("&" + lifetime + " " + typname);
}
case ftTable: {
const auto typname = WrapInNameSpace(*type.struct_def);
- return "Option<flatbuffers::WIPOffset<" + typname + "<" + lifetime +
- ">>>";
+ return WrapOption("flatbuffers::WIPOffset<" + typname + "<" + lifetime +
+ ">>");
}
case ftString: {
- return "Option<flatbuffers::WIPOffset<&" + lifetime + " str>>";
+ return WrapOption("flatbuffers::WIPOffset<&" + lifetime + " str>");
}
case ftEnumKey:
case ftUnionKey: {
- const auto typname = WrapInNameSpace(*type.enum_def);
- return field.optional ? "Option<" + typname + ">" : typname;
+ return WrapOption(WrapInNameSpace(*type.enum_def));
}
case ftUnionValue: {
return "Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>";
@@ -772,41 +1133,121 @@
case ftVectorOfBool:
case ftVectorOfFloat: {
const auto typname = GetTypeBasic(type.VectorType());
- return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime +
- ", " + typname + ">>>";
+ return WrapVector(typname);
}
case ftVectorOfEnumKey: {
const auto typname = WrapInNameSpace(*type.enum_def);
- return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime +
- ", " + typname + ">>>";
+ return WrapVector(typname);
}
case ftVectorOfStruct: {
const auto typname = WrapInNameSpace(*type.struct_def);
- return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime +
- ", " + typname + ">>>";
+ return WrapVector(typname);
}
case ftVectorOfTable: {
const auto typname = WrapInNameSpace(*type.struct_def);
- return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime +
- ", flatbuffers::ForwardsUOffset<" + typname + "<" + lifetime +
- ">>>>>";
+ return WrapUOffsetsVector(typname + "<" + lifetime + ">");
}
case ftVectorOfString: {
- return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime +
- ", flatbuffers::ForwardsUOffset<&" + lifetime + " str>>>>";
+ return WrapUOffsetsVector("&" + lifetime + " str");
}
case ftVectorOfUnionValue: {
- const auto typname =
- WrapInNameSpace(*type.enum_def) + "UnionTableOffset";
- return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime +
- ", flatbuffers::ForwardsUOffset<"
- "flatbuffers::Table<" +
- lifetime + ">>>>";
+ return WrapUOffsetsVector("flatbuffers::Table<" + lifetime + ">");
+ }
+ case ftArrayOfEnum:
+ case ftArrayOfStruct:
+ case ftArrayOfBuiltin: {
+ FLATBUFFERS_ASSERT(false && "arrays are not supported within tables");
+ return "ARRAYS_NOT_SUPPORTED_IN_TABLES";
}
}
return "INVALID_CODE_GENERATION"; // for return analysis
}
+ std::string ObjectFieldType(const FieldDef &field, bool in_a_table) {
+ const Type &type = field.value.type;
+ std::string ty;
+ switch (GetFullType(type)) {
+ case ftInteger:
+ case ftBool:
+ case ftFloat: {
+ ty = GetTypeBasic(type);
+ break;
+ }
+ case ftString: {
+ ty = "String";
+ break;
+ }
+ case ftStruct: {
+ ty = NamespacedNativeName(*type.struct_def);
+ break;
+ }
+ case ftTable: {
+ // Since Tables can contain themselves, Box is required to avoid
+ // infinite types.
+ ty = "Box<" + NamespacedNativeName(*type.struct_def) + ">";
+ break;
+ }
+ case ftUnionKey: {
+ // There is no native "UnionKey", natively, unions are rust enums with
+ // newtype-struct-variants.
+ return "INVALID_CODE_GENERATION";
+ }
+ case ftUnionValue: {
+ ty = NamespacedNativeName(*type.enum_def);
+ break;
+ }
+ case ftEnumKey: {
+ ty = WrapInNameSpace(*type.enum_def);
+ break;
+ }
+ // Vectors are in tables and are optional
+ case ftVectorOfEnumKey: {
+ ty = "Vec<" + WrapInNameSpace(*type.VectorType().enum_def) + ">";
+ break;
+ }
+ case ftVectorOfInteger:
+ case ftVectorOfBool:
+ case ftVectorOfFloat: {
+ ty = "Vec<" + GetTypeBasic(type.VectorType()) + ">";
+ break;
+ }
+ case ftVectorOfString: {
+ ty = "Vec<String>";
+ break;
+ }
+ case ftVectorOfTable:
+ case ftVectorOfStruct: {
+ ty = NamespacedNativeName(*type.VectorType().struct_def);
+ ty = "Vec<" + ty + ">";
+ break;
+ }
+ case ftVectorOfUnionValue: {
+ FLATBUFFERS_ASSERT(false && "vectors of unions are not yet supported");
+ return "INVALID_CODE_GENERATION"; // OH NO!
+ }
+ case ftArrayOfEnum: {
+ ty = "[" + WrapInNameSpace(*type.VectorType().enum_def) + "; " +
+ NumToString(type.fixed_length) + "]";
+ break;
+ }
+ case ftArrayOfStruct: {
+ ty = "[" + NamespacedNativeName(*type.VectorType().struct_def) + "; " +
+ NumToString(type.fixed_length) + "]";
+ break;
+ }
+ case ftArrayOfBuiltin: {
+ ty = "[" + GetTypeBasic(type.VectorType()) + "; " +
+ NumToString(type.fixed_length) + "]";
+ break;
+ }
+ }
+ if (in_a_table && !IsUnion(type) && field.IsOptional()) {
+ return "Option<" + ty + ">";
+ } else {
+ return ty;
+ }
+ }
+
std::string TableBuilderArgsAddFuncType(const FieldDef &field,
const std::string &lifetime) {
const Type &type = field.value.type;
@@ -844,7 +1285,8 @@
", flatbuffers::ForwardsUOffset<flatbuffers::Table<" + lifetime +
">>>";
}
- case ftEnumKey: {
+ case ftEnumKey:
+ case ftUnionKey: {
const auto typname = WrapInNameSpace(*type.enum_def);
return typname;
}
@@ -864,13 +1306,24 @@
case ftString: {
return "flatbuffers::WIPOffset<&" + lifetime + " str>";
}
- case ftUnionKey: {
- const auto typname = WrapInNameSpace(*type.enum_def);
- return typname;
- }
case ftUnionValue: {
return "flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>";
}
+ case ftArrayOfBuiltin: {
+ const auto typname = GetTypeBasic(type.VectorType());
+ return "flatbuffers::Array<" + lifetime + ", " + typname + ", " +
+ NumToString(type.fixed_length) + ">";
+ }
+ case ftArrayOfEnum: {
+ const auto typname = WrapInNameSpace(*type.enum_def);
+ return "flatbuffers::Array<" + lifetime + ", " + typname + ", " +
+ NumToString(type.fixed_length) + ">";
+ }
+ case ftArrayOfStruct: {
+ const auto typname = WrapInNameSpace(*type.struct_def);
+ return "flatbuffers::Array<" + lifetime + ", " + typname + ", " +
+ NumToString(type.fixed_length) + ">";
+ }
}
return "INVALID_CODE_GENERATION"; // for return analysis
@@ -884,16 +1337,16 @@
case ftBool:
case ftFloat: {
const auto typname = GetTypeBasic(field.value.type);
- return (field.optional ? "self.fbb_.push_slot_always::<"
- : "self.fbb_.push_slot::<") +
+ return (field.IsOptional() ? "self.fbb_.push_slot_always::<"
+ : "self.fbb_.push_slot::<") +
typname + ">";
}
case ftEnumKey:
case ftUnionKey: {
const auto underlying_typname = GetTypeBasic(type);
- return (field.optional ?
- "self.fbb_.push_slot_always::<" :
- "self.fbb_.push_slot::<") + underlying_typname + ">";
+ return (field.IsOptional() ? "self.fbb_.push_slot_always::<"
+ : "self.fbb_.push_slot::<") +
+ underlying_typname + ">";
}
case ftStruct: {
@@ -918,6 +1371,12 @@
case ftVectorOfUnionValue: {
return "self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>";
}
+ case ftArrayOfEnum:
+ case ftArrayOfStruct:
+ case ftArrayOfBuiltin: {
+ FLATBUFFERS_ASSERT(false && "arrays are not supported within tables");
+ return "ARRAYS_NOT_SUPPORTED_IN_TABLES";
+ }
}
return "INVALID_CODE_GENERATION"; // for return analysis
}
@@ -925,73 +1384,64 @@
std::string GenTableAccessorFuncReturnType(const FieldDef &field,
const std::string &lifetime) {
const Type &type = field.value.type;
+ const auto WrapOption = [&](std::string s) {
+ return field.IsOptional() ? "Option<" + s + ">" : s;
+ };
switch (GetFullType(field.value.type)) {
case ftInteger:
case ftFloat:
case ftBool: {
- const auto typname = GetTypeBasic(type);
- return field.optional ? "Option<" + typname + ">" : typname;
+ return WrapOption(GetTypeBasic(type));
}
case ftStruct: {
const auto typname = WrapInNameSpace(*type.struct_def);
- return WrapInOptionIfNotRequired("&" + lifetime + " " + typname,
- field.required);
+ return WrapOption("&" + lifetime + " " + typname);
}
case ftTable: {
const auto typname = WrapInNameSpace(*type.struct_def);
- return WrapInOptionIfNotRequired(typname + "<" + lifetime + ">",
- field.required);
+ return WrapOption(typname + "<" + lifetime + ">");
}
case ftEnumKey:
case ftUnionKey: {
- const auto typname = WrapInNameSpace(*type.enum_def);
- return field.optional ? "Option<" + typname + ">" : typname;
+ return WrapOption(WrapInNameSpace(*type.enum_def));
}
case ftUnionValue: {
- return WrapInOptionIfNotRequired("flatbuffers::Table<" + lifetime + ">",
- field.required);
+ return WrapOption("flatbuffers::Table<" + lifetime + ">");
}
case ftString: {
- return WrapInOptionIfNotRequired("&" + lifetime + " str",
- field.required);
+ return WrapOption("&" + lifetime + " str");
}
case ftVectorOfInteger:
case ftVectorOfBool:
case ftVectorOfFloat: {
const auto typname = GetTypeBasic(type.VectorType());
- if (IsOneByte(type.VectorType().base_type)) {
- return WrapInOptionIfNotRequired(
- "&" + lifetime + " [" + typname + "]", field.required);
- }
- return WrapInOptionIfNotRequired(
- "flatbuffers::Vector<" + lifetime + ", " + typname + ">",
- field.required);
+ const auto vector_type =
+ IsOneByte(type.VectorType().base_type)
+ ? "&" + lifetime + " [" + typname + "]"
+ : "flatbuffers::Vector<" + lifetime + ", " + typname + ">";
+ return WrapOption(vector_type);
}
case ftVectorOfEnumKey: {
const auto typname = WrapInNameSpace(*type.enum_def);
- return WrapInOptionIfNotRequired(
- "flatbuffers::Vector<" + lifetime + ", " + typname + ">",
- field.required);
+ return WrapOption("flatbuffers::Vector<" + lifetime + ", " + typname +
+ ">");
}
case ftVectorOfStruct: {
const auto typname = WrapInNameSpace(*type.struct_def);
- return WrapInOptionIfNotRequired("&" + lifetime + " [" + typname + "]",
- field.required);
+ return WrapOption("&" + lifetime + " [" + typname + "]");
}
case ftVectorOfTable: {
const auto typname = WrapInNameSpace(*type.struct_def);
- return WrapInOptionIfNotRequired("flatbuffers::Vector<" + lifetime +
- ", flatbuffers::ForwardsUOffset<" +
- typname + "<" + lifetime + ">>>",
- field.required);
+ return WrapOption("flatbuffers::Vector<" + lifetime +
+ ", flatbuffers::ForwardsUOffset<" + typname + "<" +
+ lifetime + ">>>");
}
case ftVectorOfString: {
- return WrapInOptionIfNotRequired(
- "flatbuffers::Vector<" + lifetime +
- ", flatbuffers::ForwardsUOffset<&" + lifetime + " str>>",
- field.required);
+ return WrapOption("flatbuffers::Vector<" + lifetime +
+ ", flatbuffers::ForwardsUOffset<&" + lifetime +
+ " str>>");
}
case ftVectorOfUnionValue: {
FLATBUFFERS_ASSERT(false && "vectors of unions are not yet supported");
@@ -999,177 +1449,166 @@
// Into trait to convert tables to typesafe union values.
return "INVALID_CODE_GENERATION"; // for return analysis
}
+ case ftArrayOfEnum:
+ case ftArrayOfStruct:
+ case ftArrayOfBuiltin: {
+ FLATBUFFERS_ASSERT(false && "arrays are not supported within tables");
+ return "ARRAYS_NOT_SUPPORTED_IN_TABLES";
+ }
}
return "INVALID_CODE_GENERATION"; // for return analysis
}
- std::string GenTableAccessorFuncBody(const FieldDef &field,
- const std::string &lifetime,
- const std::string &offset_prefix) {
- const std::string offset_name =
- offset_prefix + "::" + GetFieldOffsetName(field);
- const Type &type = field.value.type;
+ std::string FollowType(const Type &type, const std::string &lifetime) {
+ // IsVector... This can be made iterative?
- switch (GetFullType(field.value.type)) {
+ const auto WrapForwardsUOffset = [](std::string ty) -> std::string {
+ return "flatbuffers::ForwardsUOffset<" + ty + ">";
+ };
+ const auto WrapVector = [&](std::string ty) -> std::string {
+ return "flatbuffers::Vector<" + lifetime + ", " + ty + ">";
+ };
+ const auto WrapArray = [&](std::string ty, uint16_t length) -> std::string {
+ return "flatbuffers::Array<" + lifetime + ", " + ty + ", " +
+ NumToString(length) + ">";
+ };
+ switch (GetFullType(type)) {
case ftInteger:
case ftFloat:
case ftBool: {
- const auto typname = GetTypeBasic(type);
- if (field.optional) {
- return "self._tab.get::<" + typname + ">(" + offset_name + ", None)";
- } else {
- const auto default_value = GetDefaultScalarValue(field);
- return "self._tab.get::<" + typname + ">(" + offset_name + ", Some(" +
- default_value + ")).unwrap()";
- }
+ return GetTypeBasic(type);
}
case ftStruct: {
- const auto typname = WrapInNameSpace(*type.struct_def);
- return AddUnwrapIfRequired(
- "self._tab.get::<" + typname + ">(" + offset_name + ", None)",
- field.required);
- }
- case ftTable: {
- const auto typname = WrapInNameSpace(*type.struct_def);
- return AddUnwrapIfRequired(
- "self._tab.get::<flatbuffers::ForwardsUOffset<" + typname + "<" +
- lifetime + ">>>(" + offset_name + ", None)",
- field.required);
- }
- case ftUnionValue: {
- return AddUnwrapIfRequired(
- "self._tab.get::<flatbuffers::ForwardsUOffset<"
- "flatbuffers::Table<" +
- lifetime + ">>>(" + offset_name + ", None)",
- field.required);
+ return WrapInNameSpace(*type.struct_def);
}
case ftUnionKey:
case ftEnumKey: {
- const std::string typname = WrapInNameSpace(*type.enum_def);
- const std::string default_value = GetDefaultScalarValue(field);
- if (field.optional) {
- return "self._tab.get::<" + typname + ">(" + offset_name + ", None)";
- } else {
- return "self._tab.get::<" + typname + ">(" + offset_name + ", Some(" +
- default_value + ")).unwrap()";
- }
+ return WrapInNameSpace(*type.enum_def);
+ }
+ case ftTable: {
+ const auto typname = WrapInNameSpace(*type.struct_def);
+ return WrapForwardsUOffset(typname);
+ }
+ case ftUnionValue: {
+ return WrapForwardsUOffset("flatbuffers::Table<" + lifetime + ">");
}
case ftString: {
- return AddUnwrapIfRequired(
- "self._tab.get::<flatbuffers::ForwardsUOffset<&str>>(" +
- offset_name + ", None)",
- field.required);
+ return WrapForwardsUOffset("&str");
}
-
case ftVectorOfInteger:
case ftVectorOfBool:
case ftVectorOfFloat: {
const auto typname = GetTypeBasic(type.VectorType());
- std::string s =
- "self._tab.get::<flatbuffers::ForwardsUOffset<"
- "flatbuffers::Vector<" +
- lifetime + ", " + typname + ">>>(" + offset_name + ", None)";
- // single-byte values are safe to slice
- if (IsOneByte(type.VectorType().base_type)) {
- s += ".map(|v| v.safe_slice())";
- }
- return AddUnwrapIfRequired(s, field.required);
+ return WrapForwardsUOffset(WrapVector(typname));
}
case ftVectorOfEnumKey: {
- const auto typname = WrapInNameSpace(*type.enum_def);
- return AddUnwrapIfRequired(
- "self._tab.get::<flatbuffers::ForwardsUOffset<"
- "flatbuffers::Vector<" +
- lifetime + ", " + typname + ">>>(" + offset_name + ", None)",
- field.required);
+ const auto typname = WrapInNameSpace(*type.VectorType().enum_def);
+ return WrapForwardsUOffset(WrapVector(typname));
}
case ftVectorOfStruct: {
const auto typname = WrapInNameSpace(*type.struct_def);
- return AddUnwrapIfRequired(
- "self._tab.get::<flatbuffers::ForwardsUOffset<"
- "flatbuffers::Vector<" +
- typname + ">>>(" + offset_name +
- ", None).map(|v| v.safe_slice() )",
- field.required);
+ return WrapForwardsUOffset(WrapVector(typname));
}
case ftVectorOfTable: {
const auto typname = WrapInNameSpace(*type.struct_def);
- return AddUnwrapIfRequired(
- "self._tab.get::<flatbuffers::ForwardsUOffset<"
- "flatbuffers::Vector<flatbuffers::ForwardsUOffset<" +
- typname + "<" + lifetime + ">>>>>(" + offset_name + ", None)",
- field.required);
+ return WrapForwardsUOffset(WrapVector(WrapForwardsUOffset(typname)));
}
case ftVectorOfString: {
- return AddUnwrapIfRequired(
- "self._tab.get::<flatbuffers::ForwardsUOffset<"
- "flatbuffers::Vector<flatbuffers::ForwardsUOffset<&" +
- lifetime + " str>>>>(" + offset_name + ", None)",
- field.required);
+ return WrapForwardsUOffset(
+ WrapVector(WrapForwardsUOffset("&" + lifetime + " str")));
}
case ftVectorOfUnionValue: {
FLATBUFFERS_ASSERT(false && "vectors of unions are not yet supported");
return "INVALID_CODE_GENERATION"; // for return analysis
}
+ case ftArrayOfEnum: {
+ const auto typname = WrapInNameSpace(*type.VectorType().enum_def);
+ return WrapArray(typname, type.fixed_length);
+ }
+ case ftArrayOfStruct: {
+ const auto typname = WrapInNameSpace(*type.struct_def);
+ return WrapArray(typname, type.fixed_length);
+ }
+ case ftArrayOfBuiltin: {
+ const auto typname = GetTypeBasic(type.VectorType());
+ return WrapArray(typname, type.fixed_length);
+ }
}
return "INVALID_CODE_GENERATION"; // for return analysis
}
- bool TableFieldReturnsOption(const FieldDef &field) {
- if (field.optional) return true;
- switch (GetFullType(field.value.type)) {
- case ftInteger:
- case ftFloat:
- case ftBool:
- case ftEnumKey:
- case ftUnionKey: return false;
- default: return true;
- }
+ std::string GenTableAccessorFuncBody(const FieldDef &field,
+ const std::string &lifetime) {
+ const std::string vt_offset = GetFieldOffsetName(field);
+ const std::string typname = FollowType(field.value.type, lifetime);
+ // Default-y fields (scalars so far) are neither optional nor required.
+ const std::string default_value =
+ !(field.IsOptional() || field.IsRequired())
+ ? "Some(" + GetDefaultValue(field, kAccessor) + ")"
+ : "None";
+ const std::string unwrap = field.IsOptional() ? "" : ".unwrap()";
+
+ const auto t = GetFullType(field.value.type);
+
+ // TODO(caspern): Shouldn't 1byte VectorOfEnumKey be slice too?
+ const std::string safe_slice =
+ (t == ftVectorOfStruct ||
+ ((t == ftVectorOfBool || t == ftVectorOfFloat ||
+ t == ftVectorOfInteger) &&
+ IsOneByte(field.value.type.VectorType().base_type)))
+ ? ".map(|v| v.safe_slice())"
+ : "";
+
+ return "self._tab.get::<" + typname + ">({{STRUCT_TY}}::" + vt_offset +
+ ", " + default_value + ")" + safe_slice + unwrap;
}
// Generates a fully-qualified name getter for use with --gen-name-strings
void GenFullyQualifiedNameGetter(const StructDef &struct_def,
const std::string &name) {
- code_ += " pub const fn get_fully_qualified_name() -> &'static str {";
- code_ += " \"" +
- struct_def.defined_namespace->GetFullyQualifiedName(name) + "\"";
- code_ += " }";
+ const std::string fully_qualified_name =
+ struct_def.defined_namespace->GetFullyQualifiedName(name);
+ code_ += " pub const fn get_fully_qualified_name() -> &'static str {";
+ code_ += " \"" + fully_qualified_name + "\"";
+ code_ += " }";
code_ += "";
}
void ForAllUnionVariantsBesidesNone(
- const EnumDef &def,
- std::function<void(const EnumVal &ev)> cb
- ) {
+ const EnumDef &def, std::function<void(const EnumVal &ev)> cb) {
FLATBUFFERS_ASSERT(def.is_union);
for (auto it = def.Vals().begin(); it != def.Vals().end(); ++it) {
- const EnumVal & ev = **it;
+ const EnumVal &ev = **it;
// TODO(cneo): Can variants be deprecated, should we skip them?
if (ev.union_type.base_type == BASE_TYPE_NONE) { continue; }
+ code_.SetValue("U_ELEMENT_ENUM_TYPE",
+ WrapInNameSpace(def.defined_namespace,
+ namer_.EnumVariant(def.name, ev.name)));
code_.SetValue(
- "U_ELEMENT_ENUM_TYPE",
- WrapInNameSpace(def.defined_namespace, GetEnumValue(def, ev)));
- code_.SetValue("U_ELEMENT_TABLE_TYPE",
+ "U_ELEMENT_TABLE_TYPE",
WrapInNameSpace(ev.union_type.struct_def->defined_namespace,
ev.union_type.struct_def->name));
- code_.SetValue("U_ELEMENT_NAME", MakeSnakeCase(Name(ev)));
+ code_.SetValue("U_ELEMENT_NAME", namer_.Function(ev.name));
cb(ev);
}
}
- void ForAllTableFields(
- const StructDef &struct_def,
- std::function<void(const FieldDef&)> cb, bool reversed=false) {
+ void ForAllTableFields(const StructDef &struct_def,
+ std::function<void(const FieldDef &)> cb,
+ bool reversed = false) {
// TODO(cneo): Remove `reversed` overload. It's only here to minimize the
// diff when refactoring to the `ForAllX` helper functions.
- auto go = [&](const FieldDef& field) {
+ auto go = [&](const FieldDef &field) {
if (field.deprecated) return;
code_.SetValue("OFFSET_NAME", GetFieldOffsetName(field));
code_.SetValue("OFFSET_VALUE", NumToString(field.value.offset));
- code_.SetValue("FIELD_NAME", Name(field));
- code_.SetValue("DEFAULT_VALUE", GetDefaultScalarValue(field));
+ code_.SetValue("FIELD", namer_.Field(field.name));
+ code_.SetValue("BLDR_DEF_VAL", GetDefaultValue(field, kBuilder));
+ code_.SetValue("DISCRIMINANT", namer_.Method(field.name) + "_type");
+ code_.IncrementIdentLevel();
cb(field);
+ code_.DecrementIdentLevel();
};
const auto &fields = struct_def.fields.vec;
if (reversed) {
@@ -1181,84 +1620,194 @@
// Generate an accessor struct, builder struct, and create function for a
// table.
void GenTable(const StructDef &struct_def) {
- code_.SetValue("STRUCT_NAME", Name(struct_def));
- code_.SetValue("OFFSET_TYPELABEL", Name(struct_def) + "Offset");
- code_.SetValue("STRUCT_NAME_SNAKECASE", MakeSnakeCase(Name(struct_def)));
+ code_.SetValue("STRUCT_TY", namer_.Type(struct_def.name));
+ code_.SetValue("STRUCT_FN", namer_.Function(struct_def.name));
// Generate an offset type, the base type, the Follow impl, and the
// init_from_table impl.
- code_ += "pub enum {{OFFSET_TYPELABEL}} {}";
+ code_ += "pub enum {{STRUCT_TY}}Offset {}";
code_ += "#[derive(Copy, Clone, PartialEq)]";
code_ += "";
GenComment(struct_def.doc_comment);
- code_ += "pub struct {{STRUCT_NAME}}<'a> {";
+ code_ += "pub struct {{STRUCT_TY}}<'a> {";
code_ += " pub _tab: flatbuffers::Table<'a>,";
code_ += "}";
code_ += "";
- code_ += "impl<'a> flatbuffers::Follow<'a> for {{STRUCT_NAME}}<'a> {";
- code_ += " type Inner = {{STRUCT_NAME}}<'a>;";
- code_ += " #[inline]";
- code_ += " fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {";
- code_ += " Self { _tab: flatbuffers::Table { buf, loc } }";
- code_ += " }";
+ code_ += "impl<'a> flatbuffers::Follow<'a> for {{STRUCT_TY}}<'a> {";
+ code_ += " type Inner = {{STRUCT_TY}}<'a>;";
+ code_ += " #[inline]";
+ code_ += " fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {";
+ code_ += " Self { _tab: flatbuffers::Table { buf, loc } }";
+ code_ += " }";
code_ += "}";
code_ += "";
- code_ += "impl<'a> {{STRUCT_NAME}}<'a> {";
+ code_ += "impl<'a> {{STRUCT_TY}}<'a> {";
+
+ // Generate field id constants.
+ ForAllTableFields(struct_def, [&](const FieldDef &unused) {
+ (void)unused;
+ code_ +=
+ "pub const {{OFFSET_NAME}}: flatbuffers::VOffsetT = "
+ "{{OFFSET_VALUE}};";
+ });
+ code_ += "";
if (parser_.opts.generate_name_strings) {
GenFullyQualifiedNameGetter(struct_def, struct_def.name);
}
- code_ += " #[inline]";
+ code_ += " #[inline]";
code_ +=
- " pub fn init_from_table(table: flatbuffers::Table<'a>) -> "
+ " pub fn init_from_table(table: flatbuffers::Table<'a>) -> "
"Self {";
- code_ += " {{STRUCT_NAME}} {";
- code_ += " _tab: table,";
- code_ += " }";
- code_ += " }";
+ code_ += " {{STRUCT_TY}} { _tab: table }";
+ code_ += " }";
// Generate a convenient create* function that uses the above builder
// to create a table in one function call.
code_.SetValue("MAYBE_US", struct_def.fields.vec.size() == 0 ? "_" : "");
code_.SetValue("MAYBE_LT",
TableBuilderArgsNeedsLifetime(struct_def) ? "<'args>" : "");
- code_ += " #[allow(unused_mut)]";
- code_ += " pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(";
- code_ +=
- " _fbb: "
- "&'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,";
- code_ +=
- " {{MAYBE_US}}args: &'args {{STRUCT_NAME}}Args{{MAYBE_LT}})"
- " -> flatbuffers::WIPOffset<{{STRUCT_NAME}}<'bldr>> {";
+ code_ += " #[allow(unused_mut)]";
+ code_ += " pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(";
+ code_ += " _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,";
+ code_ += " {{MAYBE_US}}args: &'args {{STRUCT_TY}}Args{{MAYBE_LT}}";
+ code_ += " ) -> flatbuffers::WIPOffset<{{STRUCT_TY}}<'bldr>> {";
- code_ += " let mut builder = {{STRUCT_NAME}}Builder::new(_fbb);";
+ code_ += " let mut builder = {{STRUCT_TY}}Builder::new(_fbb);";
for (size_t size = struct_def.sortbysize ? sizeof(largest_scalar_t) : 1;
size; size /= 2) {
- ForAllTableFields(struct_def, [&](const FieldDef &field) {
- if (struct_def.sortbysize && size != SizeOf(field.value.type.base_type))
- return;
- if (TableFieldReturnsOption(field)) {
- code_ +=
- " if let Some(x) = args.{{FIELD_NAME}} "
- "{ builder.add_{{FIELD_NAME}}(x); }";
- } else {
- code_ += " builder.add_{{FIELD_NAME}}(args.{{FIELD_NAME}});";
- }
- }, /*reverse=*/true);
+ ForAllTableFields(
+ struct_def,
+ [&](const FieldDef &field) {
+ if (struct_def.sortbysize &&
+ size != SizeOf(field.value.type.base_type))
+ return;
+ if (IsOptionalToBuilder(field)) {
+ code_ +=
+ " if let Some(x) = args.{{FIELD}} "
+ "{ builder.add_{{FIELD}}(x); }";
+ } else {
+ code_ += " builder.add_{{FIELD}}(args.{{FIELD}});";
+ }
+ },
+ /*reverse=*/true);
}
- code_ += " builder.finish()";
- code_ += " }";
+ code_ += " builder.finish()";
+ code_ += " }";
code_ += "";
+ // Generate Object API Packer function.
+ if (parser_.opts.generate_object_based_api) {
+ // TODO(cneo): Replace more for loops with ForAllX stuff.
+ // TODO(cneo): Manage indentation with IncrementIdentLevel?
+ code_.SetValue("STRUCT_OTY", namer_.ObjectType(struct_def.name));
+ code_ += " pub fn unpack(&self) -> {{STRUCT_OTY}} {";
+ ForAllObjectTableFields(struct_def, [&](const FieldDef &field) {
+ const Type &type = field.value.type;
+ switch (GetFullType(type)) {
+ case ftInteger:
+ case ftBool:
+ case ftFloat:
+ case ftEnumKey: {
+ code_ += " let {{FIELD}} = self.{{FIELD}}();";
+ return;
+ }
+ case ftUnionKey: return;
+ case ftUnionValue: {
+ const auto &enum_def = *type.enum_def;
+ code_.SetValue("ENUM_TY", WrapInNameSpace(enum_def));
+ code_.SetValue("NATIVE_ENUM_NAME", NamespacedNativeName(enum_def));
+ code_ += " let {{FIELD}} = match self.{{FIELD}}_type() {";
+ code_ += " {{ENUM_TY}}::NONE => {{NATIVE_ENUM_NAME}}::NONE,";
+ ForAllUnionObjectVariantsBesidesNone(enum_def, [&] {
+ code_ +=
+ " {{ENUM_TY}}::{{VARIANT_NAME}} => "
+ "{{NATIVE_ENUM_NAME}}::{{NATIVE_VARIANT}}(Box::new(";
+ code_ += " self.{{FIELD}}_as_{{U_ELEMENT_NAME}}()";
+ code_ +=
+ " .expect(\"Invalid union table, "
+ "expected `{{ENUM_TY}}::{{VARIANT_NAME}}`.\")";
+ code_ += " .unpack()";
+ code_ += " )),";
+ });
+ // Maybe we shouldn't throw away unknown discriminants?
+ code_ += " _ => {{NATIVE_ENUM_NAME}}::NONE,";
+ code_ += " };";
+ return;
+ }
+ // The rest of the types need special handling based on if the field
+ // is optional or not.
+ case ftString: {
+ code_.SetValue("EXPR", "x.to_string()");
+ break;
+ }
+ case ftStruct: {
+ code_.SetValue("EXPR", "x.unpack()");
+ break;
+ }
+ case ftTable: {
+ code_.SetValue("EXPR", "Box::new(x.unpack())");
+ break;
+ }
+ case ftVectorOfInteger:
+ case ftVectorOfBool: {
+ if (IsOneByte(type.VectorType().base_type)) {
+ // 1 byte stuff is viewed w/ slice instead of flatbuffer::Vector
+ // and thus needs to be cloned out of the slice.
+ code_.SetValue("EXPR", "x.to_vec()");
+ break;
+ }
+ code_.SetValue("EXPR", "x.into_iter().collect()");
+ break;
+ }
+ case ftVectorOfFloat:
+ case ftVectorOfEnumKey: {
+ code_.SetValue("EXPR", "x.into_iter().collect()");
+ break;
+ }
+ case ftVectorOfString: {
+ code_.SetValue("EXPR", "x.iter().map(|s| s.to_string()).collect()");
+ break;
+ }
+ case ftVectorOfStruct:
+ case ftVectorOfTable: {
+ code_.SetValue("EXPR", "x.iter().map(|t| t.unpack()).collect()");
+ break;
+ }
+ case ftVectorOfUnionValue: {
+ FLATBUFFERS_ASSERT(false && "vectors of unions not yet supported");
+ return;
+ }
+ case ftArrayOfEnum:
+ case ftArrayOfStruct:
+ case ftArrayOfBuiltin: {
+ FLATBUFFERS_ASSERT(false &&
+ "arrays are not supported within tables");
+ return;
+ }
+ }
+ if (field.IsOptional()) {
+ code_ += " let {{FIELD}} = self.{{FIELD}}().map(|x| {";
+ code_ += " {{EXPR}}";
+ code_ += " });";
+ } else {
+ code_ += " let {{FIELD}} = {";
+ code_ += " let x = self.{{FIELD}}();";
+ code_ += " {{EXPR}}";
+ code_ += " };";
+ }
+ });
+ code_ += " {{STRUCT_OTY}} {";
+ ForAllObjectTableFields(struct_def, [&](const FieldDef &field) {
+ if (field.value.type.base_type == BASE_TYPE_UTYPE) return;
+ code_ += " {{FIELD}},";
+ });
+ code_ += " }";
+ code_ += " }";
+ }
- // Generate field id constants.
- ForAllTableFields(struct_def, [&](const FieldDef &unused){
- (void) unused;
- code_ += " pub const {{OFFSET_NAME}}: flatbuffers::VOffsetT = "
- "{{OFFSET_VALUE}};";
- });
if (struct_def.fields.vec.size() > 0) code_ += "";
// Generate the accessors. Each has one of two forms:
@@ -1272,18 +1821,15 @@
// pub fn name(&'a self) -> user_facing_type {
// self._tab.get::<internal_type>(offset, defaultval).unwrap()
// }
- const auto offset_prefix = Name(struct_def);
ForAllTableFields(struct_def, [&](const FieldDef &field) {
code_.SetValue("RETURN_TYPE",
GenTableAccessorFuncReturnType(field, "'a"));
- code_.SetValue("FUNC_BODY",
- GenTableAccessorFuncBody(field, "'a", offset_prefix));
- this->GenComment(field.doc_comment, " ");
- code_ += " #[inline]";
- code_ += " pub fn {{FIELD_NAME}}(&self) -> {{RETURN_TYPE}} {";
- code_ += " {{FUNC_BODY}}";
- code_ += " }";
+ this->GenComment(field.doc_comment);
+ code_ += "#[inline]";
+ code_ += "pub fn {{FIELD}}(&self) -> {{RETURN_TYPE}} {";
+ code_ += " " + GenTableAccessorFuncBody(field, "'a");
+ code_ += "}";
// Generate a comparison function for this field if it is a key.
if (field.key) { GenKeyFieldMethods(field); }
@@ -1301,99 +1847,214 @@
FLATBUFFERS_ASSERT(nested_root); // Guaranteed to exist by parser.
code_.SetValue("NESTED", WrapInNameSpace(*nested_root));
- code_ +=
- " pub fn {{FIELD_NAME}}_nested_flatbuffer(&'a self) -> \\";
- if (field.required) {
+ code_ += "pub fn {{FIELD}}_nested_flatbuffer(&'a self) -> \\";
+ if (field.IsRequired()) {
code_ += "{{NESTED}}<'a> {";
- code_ += " let data = self.{{FIELD_NAME}}();";
- code_ += " use flatbuffers::Follow;";
- code_ += " <flatbuffers::ForwardsUOffset<{{NESTED}}<'a>>>"
- "::follow(data, 0)";
+ code_ += " let data = self.{{FIELD}}();";
+ code_ += " use flatbuffers::Follow;";
+ code_ +=
+ " <flatbuffers::ForwardsUOffset<{{NESTED}}<'a>>>"
+ "::follow(data, 0)";
} else {
code_ += "Option<{{NESTED}}<'a>> {";
- code_ += " self.{{FIELD_NAME}}().map(|data| {";
- code_ += " use flatbuffers::Follow;";
- code_ += " <flatbuffers::ForwardsUOffset<{{NESTED}}<'a>>>"
- "::follow(data, 0)";
- code_ += " })";
+ code_ += " self.{{FIELD}}().map(|data| {";
+ code_ += " use flatbuffers::Follow;";
+ code_ +=
+ " <flatbuffers::ForwardsUOffset<{{NESTED}}<'a>>>"
+ "::follow(data, 0)";
+ code_ += " })";
}
- code_ += " }";
+ code_ += "}";
}
});
// Explicit specializations for union accessors
ForAllTableFields(struct_def, [&](const FieldDef &field) {
if (field.value.type.base_type != BASE_TYPE_UNION) return;
- code_.SetValue("FIELD_TYPE_FIELD_NAME", field.name);
ForAllUnionVariantsBesidesNone(
- *field.value.type.enum_def, [&](const EnumVal &unused){
- (void) unused;
- code_ += " #[inline]";
- code_ += " #[allow(non_snake_case)]";
- code_ +=
- " pub fn {{FIELD_NAME}}_as_{{U_ELEMENT_NAME}}(&self) -> "
- "Option<{{U_ELEMENT_TABLE_TYPE}}<'a>> {";
- // If the user defined schemas name a field that clashes with a
- // language reserved word, flatc will try to escape the field name by
- // appending an underscore. This works well for most cases, except
- // one. When generating union accessors (and referring to them
- // internally within the code generated here), an extra underscore
- // will be appended to the name, causing build failures.
- //
- // This only happens when unions have members that overlap with
- // language reserved words.
- //
- // To avoid this problem the type field name is used unescaped here:
- code_ +=
- " if self.{{FIELD_TYPE_FIELD_NAME}}_type() == "
- "{{U_ELEMENT_ENUM_TYPE}} {";
+ *field.value.type.enum_def, [&](const EnumVal &unused) {
+ (void)unused;
+ code_ += "#[inline]";
+ code_ += "#[allow(non_snake_case)]";
+ code_ +=
+ "pub fn {{FIELD}}_as_{{U_ELEMENT_NAME}}(&self) -> "
+ "Option<{{U_ELEMENT_TABLE_TYPE}}<'a>> {";
+ // If the user defined schemas name a field that clashes with a
+ // language reserved word, flatc will try to escape the field name
+ // by appending an underscore. This works well for most cases,
+ // except one. When generating union accessors (and referring to
+ // them internally within the code generated here), an extra
+ // underscore will be appended to the name, causing build failures.
+ //
+ // This only happens when unions have members that overlap with
+ // language reserved words.
+ //
+ // To avoid this problem the type field name is used unescaped here:
+ code_ +=
+ " if self.{{DISCRIMINANT}}() == {{U_ELEMENT_ENUM_TYPE}} {";
- // The following logic is not tested in the integration test,
- // as of April 10, 2020
- if (field.required) {
- code_ += " let u = self.{{FIELD_NAME}}();";
- code_ += " Some({{U_ELEMENT_TABLE_TYPE}}::init_from_table(u))";
- } else {
- code_ +=
- " self.{{FIELD_NAME}}().map("
- "{{U_ELEMENT_TABLE_TYPE}}::init_from_table)";
- }
- code_ += " } else {";
- code_ += " None";
- code_ += " }";
- code_ += " }";
- code_ += "";
-
- });
+ // The following logic is not tested in the integration test,
+ // as of April 10, 2020
+ if (field.IsRequired()) {
+ code_ += " let u = self.{{FIELD}}();";
+ code_ += " Some({{U_ELEMENT_TABLE_TYPE}}::init_from_table(u))";
+ } else {
+ code_ +=
+ " self.{{FIELD}}().map("
+ "{{U_ELEMENT_TABLE_TYPE}}::init_from_table)";
+ }
+ code_ += " } else {";
+ code_ += " None";
+ code_ += " }";
+ code_ += "}";
+ code_ += "";
+ });
});
code_ += "}"; // End of table impl.
code_ += "";
+ // Generate Verifier;
+ code_ += "impl flatbuffers::Verifiable for {{STRUCT_TY}}<'_> {";
+ code_ += " #[inline]";
+ code_ += " fn run_verifier(";
+ code_ += " v: &mut flatbuffers::Verifier, pos: usize";
+ code_ += " ) -> Result<(), flatbuffers::InvalidFlatbuffer> {";
+ code_ += " use self::flatbuffers::Verifiable;";
+ code_ += " v.visit_table(pos)?\\";
+ // Escape newline and insert it onthe next line so we can end the builder
+ // with a nice semicolon.
+ ForAllTableFields(struct_def, [&](const FieldDef &field) {
+ if (GetFullType(field.value.type) == ftUnionKey) return;
+
+ code_.SetValue("IS_REQ", field.IsRequired() ? "true" : "false");
+ if (GetFullType(field.value.type) != ftUnionValue) {
+ // All types besides unions.
+ code_.SetValue("TY", FollowType(field.value.type, "'_"));
+ code_ +=
+ "\n .visit_field::<{{TY}}>(\"{{FIELD}}\", "
+ "Self::{{OFFSET_NAME}}, {{IS_REQ}})?\\";
+ return;
+ }
+ // Unions.
+ const EnumDef &union_def = *field.value.type.enum_def;
+ code_.SetValue("UNION_TYPE", WrapInNameSpace(union_def));
+ code_.SetValue("UNION_TYPE_OFFSET_NAME",
+ GetFieldOffsetName(field) + "_TYPE");
+ code_ +=
+ "\n .visit_union::<{{UNION_TYPE}}, _>("
+ "\"{{FIELD}}_type\", Self::{{UNION_TYPE_OFFSET_NAME}}, "
+ "\"{{FIELD}}\", Self::{{OFFSET_NAME}}, {{IS_REQ}}, "
+ "|key, v, pos| {";
+ code_ += " match key {";
+ ForAllUnionVariantsBesidesNone(union_def, [&](const EnumVal &unused) {
+ (void)unused;
+ code_ +=
+ " {{U_ELEMENT_ENUM_TYPE}} => v.verify_union_variant::"
+ "<flatbuffers::ForwardsUOffset<{{U_ELEMENT_TABLE_TYPE}}>>("
+ "\"{{U_ELEMENT_ENUM_TYPE}}\", pos),";
+ });
+ code_ += " _ => Ok(()),";
+ code_ += " }";
+ code_ += " })?\\";
+ });
+ code_ += "\n .finish();";
+ code_ += " Ok(())";
+ code_ += " }";
+ code_ += "}";
+
// Generate an args struct:
code_.SetValue("MAYBE_LT",
TableBuilderArgsNeedsLifetime(struct_def) ? "<'a>" : "");
- code_ += "pub struct {{STRUCT_NAME}}Args{{MAYBE_LT}} {";
+ code_ += "pub struct {{STRUCT_TY}}Args{{MAYBE_LT}} {";
ForAllTableFields(struct_def, [&](const FieldDef &field) {
code_.SetValue("PARAM_TYPE", TableBuilderArgsDefnType(field, "'a"));
- code_ += " pub {{FIELD_NAME}}: {{PARAM_TYPE}},";
+ code_ += " pub {{FIELD}}: {{PARAM_TYPE}},";
});
code_ += "}";
// Generate an impl of Default for the *Args type:
- code_ += "impl<'a> Default for {{STRUCT_NAME}}Args{{MAYBE_LT}} {";
- code_ += " #[inline]";
- code_ += " fn default() -> Self {";
- code_ += " {{STRUCT_NAME}}Args {";
+ code_ += "impl<'a> Default for {{STRUCT_TY}}Args{{MAYBE_LT}} {";
+ code_ += " #[inline]";
+ code_ += " fn default() -> Self {";
+ code_ += " {{STRUCT_TY}}Args {";
ForAllTableFields(struct_def, [&](const FieldDef &field) {
- code_ += " {{FIELD_NAME}}: {{DEFAULT_VALUE}},\\";
- code_ += field.required ? " // required field" : "";
+ code_ += " {{FIELD}}: {{BLDR_DEF_VAL}},\\";
+ code_ += field.IsRequired() ? " // required field" : "";
});
- code_ += " }";
code_ += " }";
+ code_ += " }";
code_ += "}";
+ code_ += "";
+
+ // Implement serde::Serialize
+ if (parser_.opts.rust_serialize) {
+ const auto numFields = struct_def.fields.vec.size();
+ code_.SetValue("NUM_FIELDS", NumToString(numFields));
+ code_ += "impl Serialize for {{STRUCT_TY}}<'_> {";
+ code_ +=
+ " fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>";
+ code_ += " where";
+ code_ += " S: Serializer,";
+ code_ += " {";
+ if (numFields == 0) {
+ code_ +=
+ " let s = serializer.serialize_struct(\"{{STRUCT_TY}}\", 0)?;";
+ } else {
+ code_ +=
+ " let mut s = serializer.serialize_struct(\"{{STRUCT_TY}}\", "
+ "{{NUM_FIELDS}})?;";
+ }
+ ForAllTableFields(struct_def, [&](const FieldDef &field) {
+ const Type &type = field.value.type;
+ if (IsUnion(type)) {
+ if (type.base_type == BASE_TYPE_UNION) {
+ const auto &enum_def = *type.enum_def;
+ code_.SetValue("ENUM_TY", WrapInNameSpace(enum_def));
+ code_.SetValue("FIELD", namer_.Field(field.name));
+
+ code_ += " match self.{{FIELD}}_type() {";
+ code_ += " {{ENUM_TY}}::NONE => (),";
+ ForAllUnionObjectVariantsBesidesNone(enum_def, [&] {
+ code_.SetValue("FIELD", namer_.Field(field.name));
+ code_ += " {{ENUM_TY}}::{{VARIANT_NAME}} => {";
+ code_ +=
+ " let f = "
+ "self.{{FIELD}}_as_{{U_ELEMENT_NAME}}()";
+ code_ +=
+ " .expect(\"Invalid union table, expected "
+ "`{{ENUM_TY}}::{{VARIANT_NAME}}`.\");";
+ code_ += " s.serialize_field(\"{{FIELD}}\", &f)?;";
+ code_ += " }";
+ });
+ code_ += " _ => unimplemented!(),";
+ code_ += " }";
+ } else {
+ code_ +=
+ " s.serialize_field(\"{{FIELD}}\", "
+ "&self.{{FIELD}}())?;";
+ }
+ } else {
+ if (field.IsOptional()) {
+ code_ += " if let Some(f) = self.{{FIELD}}() {";
+ code_ += " s.serialize_field(\"{{FIELD}}\", &f)?;";
+ code_ += " } else {";
+ code_ += " s.skip_field(\"{{FIELD}}\")?;";
+ code_ += " }";
+ } else {
+ code_ +=
+ " s.serialize_field(\"{{FIELD}}\", "
+ "&self.{{FIELD}}())?;";
+ }
+ }
+ });
+ code_ += " s.end()";
+ code_ += " }";
+ code_ += "}";
+ code_ += "";
+ }
// Generate a builder struct:
- code_ += "pub struct {{STRUCT_NAME}}Builder<'a: 'b, 'b> {";
+ code_ += "pub struct {{STRUCT_TY}}Builder<'a: 'b, 'b> {";
code_ += " fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,";
code_ +=
" start_: flatbuffers::WIPOffset<"
@@ -1401,7 +2062,7 @@
code_ += "}";
// Generate builder functions:
- code_ += "impl<'a: 'b, 'b> {{STRUCT_NAME}}Builder<'a, 'b> {";
+ code_ += "impl<'a: 'b, 'b> {{STRUCT_TY}}Builder<'a, 'b> {";
ForAllTableFields(struct_def, [&](const FieldDef &field) {
const bool is_scalar = IsScalar(field.value.type.base_type);
std::string offset = GetFieldOffsetName(field);
@@ -1416,30 +2077,32 @@
// fn add_x(x_: type) {
// fbb_.push_slot_always::<type>(offset, x_);
// }
- code_.SetValue("FIELD_OFFSET", Name(struct_def) + "::" + offset);
+ code_.SetValue("FIELD_OFFSET",
+ namer_.Type(struct_def.name) + "::" + offset);
code_.SetValue("FIELD_TYPE", TableBuilderArgsAddFuncType(field, "'b "));
code_.SetValue("FUNC_BODY", TableBuilderArgsAddFuncBody(field));
- code_ += " #[inline]";
- code_ += " pub fn add_{{FIELD_NAME}}(&mut self, {{FIELD_NAME}}: "
- "{{FIELD_TYPE}}) {";
- if (is_scalar && !field.optional) {
+ code_ += "#[inline]";
+ code_ +=
+ "pub fn add_{{FIELD}}(&mut self, {{FIELD}}: "
+ "{{FIELD_TYPE}}) {";
+ if (is_scalar && !field.IsOptional()) {
code_ +=
- " {{FUNC_BODY}}({{FIELD_OFFSET}}, {{FIELD_NAME}}, "
- "{{DEFAULT_VALUE}});";
+ " {{FUNC_BODY}}({{FIELD_OFFSET}}, {{FIELD}}, "
+ "{{BLDR_DEF_VAL}});";
} else {
- code_ += " {{FUNC_BODY}}({{FIELD_OFFSET}}, {{FIELD_NAME}});";
+ code_ += " {{FUNC_BODY}}({{FIELD_OFFSET}}, {{FIELD}});";
}
- code_ += " }";
+ code_ += "}";
});
// Struct initializer (all fields required);
code_ += " #[inline]";
code_ +=
" pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> "
- "{{STRUCT_NAME}}Builder<'a, 'b> {";
+ "{{STRUCT_TY}}Builder<'a, 'b> {";
code_.SetValue("NUM_FIELDS", NumToString(struct_def.fields.vec.size()));
code_ += " let start = _fbb.start_table();";
- code_ += " {{STRUCT_NAME}}Builder {";
+ code_ += " {{STRUCT_TY}}Builder {";
code_ += " fbb_: _fbb,";
code_ += " start_: start,";
code_ += " }";
@@ -1449,53 +2112,56 @@
code_ += " #[inline]";
code_ +=
" pub fn finish(self) -> "
- "flatbuffers::WIPOffset<{{STRUCT_NAME}}<'a>> {";
+ "flatbuffers::WIPOffset<{{STRUCT_TY}}<'a>> {";
code_ += " let o = self.fbb_.end_table(self.start_);";
ForAllTableFields(struct_def, [&](const FieldDef &field) {
- if (!field.required) return;
+ if (!field.IsRequired()) return;
code_ +=
- " self.fbb_.required(o, {{STRUCT_NAME}}::{{OFFSET_NAME}},"
- "\"{{FIELD_NAME}}\");";
+ " self.fbb_.required(o, {{STRUCT_TY}}::{{OFFSET_NAME}},"
+ "\"{{FIELD}}\");";
});
code_ += " flatbuffers::WIPOffset::new(o.value())";
code_ += " }";
code_ += "}";
code_ += "";
- code_ += "impl std::fmt::Debug for {{STRUCT_NAME}}<'_> {";
- code_ += " fn fmt(&self, f: &mut std::fmt::Formatter<'_>"
- ") -> std::fmt::Result {";
- code_ += " let mut ds = f.debug_struct(\"{{STRUCT_NAME}}\");";
+ code_ += "impl std::fmt::Debug for {{STRUCT_TY}}<'_> {";
+ code_ +=
+ " fn fmt(&self, f: &mut std::fmt::Formatter<'_>"
+ ") -> std::fmt::Result {";
+ code_ += " let mut ds = f.debug_struct(\"{{STRUCT_TY}}\");";
ForAllTableFields(struct_def, [&](const FieldDef &field) {
if (GetFullType(field.value.type) == ftUnionValue) {
// Generate a match statement to handle unions properly.
code_.SetValue("KEY_TYPE", GenTableAccessorFuncReturnType(field, ""));
- code_.SetValue("FIELD_TYPE_FIELD_NAME", field.name);
- code_.SetValue("UNION_ERR", "&\"InvalidFlatbuffer: Union discriminant"
- " does not match value.\"");
+ code_.SetValue("UNION_ERR",
+ "&\"InvalidFlatbuffer: Union discriminant"
+ " does not match value.\"");
- code_ += " match self.{{FIELD_NAME}}_type() {";
- ForAllUnionVariantsBesidesNone(*field.value.type.enum_def,
- [&](const EnumVal &unused){
- (void) unused;
- code_ += " {{U_ELEMENT_ENUM_TYPE}} => {";
- code_ += " if let Some(x) = self.{{FIELD_TYPE_FIELD_NAME}}_as_"
- "{{U_ELEMENT_NAME}}() {";
- code_ += " ds.field(\"{{FIELD_NAME}}\", &x)";
- code_ += " } else {";
- code_ += " ds.field(\"{{FIELD_NAME}}\", {{UNION_ERR}})";
- code_ += " }";
- code_ += " },";
- });
- code_ += " _ => { ";
- code_ += " let x: Option<()> = None;";
- code_ += " ds.field(\"{{FIELD_NAME}}\", &x)";
- code_ += " },";
- code_ += " };";
+ code_ += " match self.{{DISCRIMINANT}}() {";
+ ForAllUnionVariantsBesidesNone(
+ *field.value.type.enum_def, [&](const EnumVal &unused) {
+ (void)unused;
+ code_ += " {{U_ELEMENT_ENUM_TYPE}} => {";
+ code_ +=
+ " if let Some(x) = "
+ "self.{{FIELD}}_as_"
+ "{{U_ELEMENT_NAME}}() {";
+ code_ += " ds.field(\"{{FIELD}}\", &x)";
+ code_ += " } else {";
+ code_ += " ds.field(\"{{FIELD}}\", {{UNION_ERR}})";
+ code_ += " }";
+ code_ += " },";
+ });
+ code_ += " _ => {";
+ code_ += " let x: Option<()> = None;";
+ code_ += " ds.field(\"{{FIELD}}\", &x)";
+ code_ += " },";
+ code_ += " };";
} else {
// Most fields.
- code_ += " ds.field(\"{{FIELD_NAME}}\", &self.{{FIELD_NAME}}());";
+ code_ += " ds.field(\"{{FIELD}}\", &self.{{FIELD}}());";
}
});
code_ += " ds.finish()";
@@ -1503,97 +2169,355 @@
code_ += "}";
}
+ void GenTableObject(const StructDef &table) {
+ code_.SetValue("STRUCT_OTY", namer_.ObjectType(table.name));
+ code_.SetValue("STRUCT_TY", namer_.Type(table.name));
+
+ // Generate the native object.
+ code_ += "#[non_exhaustive]";
+ code_ += "#[derive(Debug, Clone, PartialEq)]";
+ code_ += "pub struct {{STRUCT_OTY}} {";
+ ForAllObjectTableFields(table, [&](const FieldDef &field) {
+ // Union objects combine both the union discriminant and value, so we
+ // skip making a field for the discriminant.
+ if (field.value.type.base_type == BASE_TYPE_UTYPE) return;
+ code_ += "pub {{FIELD}}: {{FIELD_OTY}},";
+ });
+ code_ += "}";
+
+ code_ += "impl Default for {{STRUCT_OTY}} {";
+ code_ += " fn default() -> Self {";
+ code_ += " Self {";
+ ForAllObjectTableFields(table, [&](const FieldDef &field) {
+ if (field.value.type.base_type == BASE_TYPE_UTYPE) return;
+ std::string default_value = GetDefaultValue(field, kObject);
+ code_ += " {{FIELD}}: " + default_value + ",";
+ });
+ code_ += " }";
+ code_ += " }";
+ code_ += "}";
+
+ // TODO(cneo): Generate defaults for Native tables. However, since structs
+ // may be required, they, and therefore enums need defaults.
+
+ // Generate pack function.
+ code_ += "impl {{STRUCT_OTY}} {";
+ code_ += " pub fn pack<'b>(";
+ code_ += " &self,";
+ code_ += " _fbb: &mut flatbuffers::FlatBufferBuilder<'b>";
+ code_ += " ) -> flatbuffers::WIPOffset<{{STRUCT_TY}}<'b>> {";
+ // First we generate variables for each field and then later assemble them
+ // using "StructArgs" to more easily manage ownership of the builder.
+ ForAllObjectTableFields(table, [&](const FieldDef &field) {
+ const Type &type = field.value.type;
+ switch (GetFullType(type)) {
+ case ftInteger:
+ case ftBool:
+ case ftFloat:
+ case ftEnumKey: {
+ code_ += " let {{FIELD}} = self.{{FIELD}};";
+ return;
+ }
+ case ftUnionKey: return; // Generate union type with union value.
+ case ftUnionValue: {
+ code_.SetValue("ENUM_METHOD",
+ namer_.Method(field.value.type.enum_def->name));
+ code_ +=
+ " let {{FIELD}}_type = "
+ "self.{{FIELD}}.{{ENUM_METHOD}}_type();";
+ code_ += " let {{FIELD}} = self.{{FIELD}}.pack(_fbb);";
+ return;
+ }
+ // The rest of the types require special casing around optionalness
+ // due to "required" annotation.
+ case ftString: {
+ MapNativeTableField(field, "_fbb.create_string(x)");
+ return;
+ }
+ case ftStruct: {
+ // Hold the struct in a variable so we can reference it.
+ if (field.IsRequired()) {
+ code_ += " let {{FIELD}}_tmp = Some(self.{{FIELD}}.pack());";
+ } else {
+ code_ +=
+ " let {{FIELD}}_tmp = self.{{FIELD}}"
+ ".as_ref().map(|x| x.pack());";
+ }
+ code_ += " let {{FIELD}} = {{FIELD}}_tmp.as_ref();";
+
+ return;
+ }
+ case ftTable: {
+ MapNativeTableField(field, "x.pack(_fbb)");
+ return;
+ }
+ case ftVectorOfEnumKey:
+ case ftVectorOfInteger:
+ case ftVectorOfBool:
+ case ftVectorOfFloat: {
+ MapNativeTableField(field, "_fbb.create_vector(x)");
+ return;
+ }
+ case ftVectorOfStruct: {
+ MapNativeTableField(
+ field,
+ "let w: Vec<_> = x.iter().map(|t| t.pack()).collect();"
+ "_fbb.create_vector(&w)");
+ return;
+ }
+ case ftVectorOfString: {
+ // TODO(cneo): create_vector* should be more generic to avoid
+ // allocations.
+
+ MapNativeTableField(
+ field,
+ "let w: Vec<_> = x.iter().map(|s| s.as_ref()).collect();"
+ "_fbb.create_vector_of_strings(&w)");
+ return;
+ }
+ case ftVectorOfTable: {
+ MapNativeTableField(
+ field,
+ "let w: Vec<_> = x.iter().map(|t| t.pack(_fbb)).collect();"
+ "_fbb.create_vector(&w)");
+ return;
+ }
+ case ftVectorOfUnionValue: {
+ FLATBUFFERS_ASSERT(false && "vectors of unions not yet supported");
+ return;
+ }
+ case ftArrayOfEnum:
+ case ftArrayOfStruct:
+ case ftArrayOfBuiltin: {
+ FLATBUFFERS_ASSERT(false && "arrays are not supported within tables");
+ return;
+ }
+ }
+ });
+ code_ += " {{STRUCT_TY}}::create(_fbb, &{{STRUCT_TY}}Args{";
+ ForAllObjectTableFields(table, [&](const FieldDef &field) {
+ (void)field; // Unused.
+ code_ += " {{FIELD}},";
+ });
+ code_ += " })";
+ code_ += " }";
+ code_ += "}";
+ }
+ void ForAllObjectTableFields(const StructDef &table,
+ std::function<void(const FieldDef &)> cb) {
+ const std::vector<FieldDef *> &v = table.fields.vec;
+ for (auto it = v.begin(); it != v.end(); it++) {
+ const FieldDef &field = **it;
+ if (field.deprecated) continue;
+ code_.SetValue("FIELD", namer_.Field(field.name));
+ code_.SetValue("FIELD_OTY", ObjectFieldType(field, true));
+ code_.IncrementIdentLevel();
+ cb(field);
+ code_.DecrementIdentLevel();
+ }
+ }
+ void MapNativeTableField(const FieldDef &field, const std::string &expr) {
+ if (field.IsOptional()) {
+ code_ += " let {{FIELD}} = self.{{FIELD}}.as_ref().map(|x|{";
+ code_ += " " + expr;
+ code_ += " });";
+ } else {
+ // For some reason Args has optional types for required fields.
+ // TODO(cneo): Fix this... but its a breaking change?
+ code_ += " let {{FIELD}} = Some({";
+ code_ += " let x = &self.{{FIELD}};";
+ code_ += " " + expr;
+ code_ += " });";
+ }
+ }
+
// Generate functions to compare tables and structs by key. This function
// must only be called if the field key is defined.
void GenKeyFieldMethods(const FieldDef &field) {
FLATBUFFERS_ASSERT(field.key);
code_.SetValue("KEY_TYPE", GenTableAccessorFuncReturnType(field, ""));
+ code_.SetValue("REF", IsString(field.value.type) ? "" : "&");
- code_ += " #[inline]";
+ code_ += "#[inline]";
code_ +=
- " pub fn key_compare_less_than(&self, o: &{{STRUCT_NAME}}) -> "
- " bool {";
- code_ += " self.{{FIELD_NAME}}() < o.{{FIELD_NAME}}()";
- code_ += " }";
+ "pub fn key_compare_less_than(&self, o: &{{STRUCT_TY}}) -> "
+ "bool {";
+ code_ += " self.{{FIELD}}() < o.{{FIELD}}()";
+ code_ += "}";
code_ += "";
- code_ += " #[inline]";
+ code_ += "#[inline]";
code_ +=
- " pub fn key_compare_with_value(&self, val: {{KEY_TYPE}}) -> "
- " ::std::cmp::Ordering {";
- code_ += " let key = self.{{FIELD_NAME}}();";
- code_ += " key.cmp(&val)";
- code_ += " }";
+ "pub fn key_compare_with_value(&self, val: {{KEY_TYPE}}) -> "
+ "::std::cmp::Ordering {";
+ code_ += " let key = self.{{FIELD}}();";
+ code_ += " key.cmp({{REF}}val)";
+ code_ += "}";
}
// Generate functions for accessing the root table object. This function
// must only be called if the root table is defined.
void GenRootTableFuncs(const StructDef &struct_def) {
FLATBUFFERS_ASSERT(parser_.root_struct_def_ && "root table not defined");
- auto name = Name(struct_def);
-
- code_.SetValue("STRUCT_NAME", name);
- code_.SetValue("STRUCT_NAME_SNAKECASE", MakeSnakeCase(name));
- code_.SetValue("STRUCT_NAME_CAPS", MakeUpper(MakeSnakeCase(name)));
+ code_.SetValue("STRUCT_TY", namer_.Type(struct_def.name));
+ code_.SetValue("STRUCT_FN", namer_.Function(struct_def.name));
+ code_.SetValue("STRUCT_CONST", namer_.Constant(struct_def.name));
// The root datatype accessors:
code_ += "#[inline]";
code_ +=
- "pub fn get_root_as_{{STRUCT_NAME_SNAKECASE}}<'a>(buf: &'a [u8])"
- " -> {{STRUCT_NAME}}<'a> {";
- code_ += " flatbuffers::get_root::<{{STRUCT_NAME}}<'a>>(buf)";
+ "#[deprecated(since=\"2.0.0\", "
+ "note=\"Deprecated in favor of `root_as...` methods.\")]";
+ code_ +=
+ "pub fn get_root_as_{{STRUCT_FN}}<'a>(buf: &'a [u8])"
+ " -> {{STRUCT_TY}}<'a> {";
+ code_ +=
+ " unsafe { flatbuffers::root_unchecked::<{{STRUCT_TY}}"
+ "<'a>>(buf) }";
code_ += "}";
code_ += "";
code_ += "#[inline]";
code_ +=
- "pub fn get_size_prefixed_root_as_{{STRUCT_NAME_SNAKECASE}}"
- "<'a>(buf: &'a [u8]) -> {{STRUCT_NAME}}<'a> {";
+ "#[deprecated(since=\"2.0.0\", "
+ "note=\"Deprecated in favor of `root_as...` methods.\")]";
code_ +=
- " flatbuffers::get_size_prefixed_root::<{{STRUCT_NAME}}<'a>>"
- "(buf)";
+ "pub fn get_size_prefixed_root_as_{{STRUCT_FN}}"
+ "<'a>(buf: &'a [u8]) -> {{STRUCT_TY}}<'a> {";
+ code_ +=
+ " unsafe { flatbuffers::size_prefixed_root_unchecked::<{{STRUCT_TY}}"
+ "<'a>>(buf) }";
code_ += "}";
code_ += "";
+ // Default verifier root fns.
+ code_ += "#[inline]";
+ code_ += "/// Verifies that a buffer of bytes contains a `{{STRUCT_TY}}`";
+ code_ += "/// and returns it.";
+ code_ += "/// Note that verification is still experimental and may not";
+ code_ += "/// catch every error, or be maximally performant. For the";
+ code_ += "/// previous, unchecked, behavior use";
+ code_ += "/// `root_as_{{STRUCT_FN}}_unchecked`.";
+ code_ +=
+ "pub fn root_as_{{STRUCT_FN}}(buf: &[u8]) "
+ "-> Result<{{STRUCT_TY}}, flatbuffers::InvalidFlatbuffer> {";
+ code_ += " flatbuffers::root::<{{STRUCT_TY}}>(buf)";
+ code_ += "}";
+ code_ += "#[inline]";
+ code_ += "/// Verifies that a buffer of bytes contains a size prefixed";
+ code_ += "/// `{{STRUCT_TY}}` and returns it.";
+ code_ += "/// Note that verification is still experimental and may not";
+ code_ += "/// catch every error, or be maximally performant. For the";
+ code_ += "/// previous, unchecked, behavior use";
+ code_ += "/// `size_prefixed_root_as_{{STRUCT_FN}}_unchecked`.";
+ code_ +=
+ "pub fn size_prefixed_root_as_{{STRUCT_FN}}"
+ "(buf: &[u8]) -> Result<{{STRUCT_TY}}, "
+ "flatbuffers::InvalidFlatbuffer> {";
+ code_ += " flatbuffers::size_prefixed_root::<{{STRUCT_TY}}>(buf)";
+ code_ += "}";
+ // Verifier with options root fns.
+ code_ += "#[inline]";
+ code_ += "/// Verifies, with the given options, that a buffer of bytes";
+ code_ += "/// contains a `{{STRUCT_TY}}` and returns it.";
+ code_ += "/// Note that verification is still experimental and may not";
+ code_ += "/// catch every error, or be maximally performant. For the";
+ code_ += "/// previous, unchecked, behavior use";
+ code_ += "/// `root_as_{{STRUCT_FN}}_unchecked`.";
+ code_ += "pub fn root_as_{{STRUCT_FN}}_with_opts<'b, 'o>(";
+ code_ += " opts: &'o flatbuffers::VerifierOptions,";
+ code_ += " buf: &'b [u8],";
+ code_ +=
+ ") -> Result<{{STRUCT_TY}}<'b>, flatbuffers::InvalidFlatbuffer>"
+ " {";
+ code_ += " flatbuffers::root_with_opts::<{{STRUCT_TY}}<'b>>(opts, buf)";
+ code_ += "}";
+ code_ += "#[inline]";
+ code_ += "/// Verifies, with the given verifier options, that a buffer of";
+ code_ += "/// bytes contains a size prefixed `{{STRUCT_TY}}` and returns";
+ code_ += "/// it. Note that verification is still experimental and may not";
+ code_ += "/// catch every error, or be maximally performant. For the";
+ code_ += "/// previous, unchecked, behavior use";
+ code_ += "/// `root_as_{{STRUCT_FN}}_unchecked`.";
+ code_ +=
+ "pub fn size_prefixed_root_as_{{STRUCT_FN}}_with_opts"
+ "<'b, 'o>(";
+ code_ += " opts: &'o flatbuffers::VerifierOptions,";
+ code_ += " buf: &'b [u8],";
+ code_ +=
+ ") -> Result<{{STRUCT_TY}}<'b>, flatbuffers::InvalidFlatbuffer>"
+ " {";
+ code_ +=
+ " flatbuffers::size_prefixed_root_with_opts::<{{STRUCT_TY}}"
+ "<'b>>(opts, buf)";
+ code_ += "}";
+ // Unchecked root fns.
+ code_ += "#[inline]";
+ code_ +=
+ "/// Assumes, without verification, that a buffer of bytes "
+ "contains a {{STRUCT_TY}} and returns it.";
+ code_ += "/// # Safety";
+ code_ +=
+ "/// Callers must trust the given bytes do indeed contain a valid"
+ " `{{STRUCT_TY}}`.";
+ code_ +=
+ "pub unsafe fn root_as_{{STRUCT_FN}}_unchecked"
+ "(buf: &[u8]) -> {{STRUCT_TY}} {";
+ code_ += " flatbuffers::root_unchecked::<{{STRUCT_TY}}>(buf)";
+ code_ += "}";
+ code_ += "#[inline]";
+ code_ +=
+ "/// Assumes, without verification, that a buffer of bytes "
+ "contains a size prefixed {{STRUCT_TY}} and returns it.";
+ code_ += "/// # Safety";
+ code_ +=
+ "/// Callers must trust the given bytes do indeed contain a valid"
+ " size prefixed `{{STRUCT_TY}}`.";
+ code_ +=
+ "pub unsafe fn size_prefixed_root_as_{{STRUCT_FN}}"
+ "_unchecked(buf: &[u8]) -> {{STRUCT_TY}} {";
+ code_ +=
+ " flatbuffers::size_prefixed_root_unchecked::<{{STRUCT_TY}}>"
+ "(buf)";
+ code_ += "}";
if (parser_.file_identifier_.length()) {
// Declare the identifier
// (no lifetime needed as constants have static lifetimes by default)
- code_ += "pub const {{STRUCT_NAME_CAPS}}_IDENTIFIER: &str\\";
+ code_ += "pub const {{STRUCT_CONST}}_IDENTIFIER: &str\\";
code_ += " = \"" + parser_.file_identifier_ + "\";";
code_ += "";
// Check if a buffer has the identifier.
code_ += "#[inline]";
- code_ += "pub fn {{STRUCT_NAME_SNAKECASE}}_buffer_has_identifier\\";
+ code_ += "pub fn {{STRUCT_FN}}_buffer_has_identifier\\";
code_ += "(buf: &[u8]) -> bool {";
code_ += " flatbuffers::buffer_has_identifier(buf, \\";
- code_ += "{{STRUCT_NAME_CAPS}}_IDENTIFIER, false)";
+ code_ += "{{STRUCT_CONST}}_IDENTIFIER, false)";
code_ += "}";
code_ += "";
code_ += "#[inline]";
- code_ += "pub fn {{STRUCT_NAME_SNAKECASE}}_size_prefixed\\";
+ code_ += "pub fn {{STRUCT_FN}}_size_prefixed\\";
code_ += "_buffer_has_identifier(buf: &[u8]) -> bool {";
code_ += " flatbuffers::buffer_has_identifier(buf, \\";
- code_ += "{{STRUCT_NAME_CAPS}}_IDENTIFIER, true)";
+ code_ += "{{STRUCT_CONST}}_IDENTIFIER, true)";
code_ += "}";
code_ += "";
}
if (parser_.file_extension_.length()) {
// Return the extension
- code_ += "pub const {{STRUCT_NAME_CAPS}}_EXTENSION: &str = \\";
+ code_ += "pub const {{STRUCT_CONST}}_EXTENSION: &str = \\";
code_ += "\"" + parser_.file_extension_ + "\";";
code_ += "";
}
// Finish a buffer with a given root object:
- code_.SetValue("OFFSET_TYPELABEL", Name(struct_def) + "Offset");
code_ += "#[inline]";
- code_ += "pub fn finish_{{STRUCT_NAME_SNAKECASE}}_buffer<'a, 'b>(";
+ code_ += "pub fn finish_{{STRUCT_FN}}_buffer<'a, 'b>(";
code_ += " fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,";
- code_ += " root: flatbuffers::WIPOffset<{{STRUCT_NAME}}<'a>>) {";
+ code_ += " root: flatbuffers::WIPOffset<{{STRUCT_TY}}<'a>>) {";
if (parser_.file_identifier_.length()) {
- code_ += " fbb.finish(root, Some({{STRUCT_NAME_CAPS}}_IDENTIFIER));";
+ code_ += " fbb.finish(root, Some({{STRUCT_CONST}}_IDENTIFIER));";
} else {
code_ += " fbb.finish(root, None);";
}
@@ -1601,14 +2525,14 @@
code_ += "";
code_ += "#[inline]";
code_ +=
- "pub fn finish_size_prefixed_{{STRUCT_NAME_SNAKECASE}}_buffer"
+ "pub fn finish_size_prefixed_{{STRUCT_FN}}_buffer"
"<'a, 'b>("
"fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>, "
- "root: flatbuffers::WIPOffset<{{STRUCT_NAME}}<'a>>) {";
+ "root: flatbuffers::WIPOffset<{{STRUCT_TY}}<'a>>) {";
if (parser_.file_identifier_.length()) {
code_ +=
" fbb.finish_size_prefixed(root, "
- "Some({{STRUCT_NAME_CAPS}}_IDENTIFIER));";
+ "Some({{STRUCT_CONST}}_IDENTIFIER));";
} else {
code_ += " fbb.finish_size_prefixed(root, None);";
}
@@ -1638,16 +2562,24 @@
*code_ptr += "padding" + NumToString((*id)++) + "__: 0,";
}
- void ForAllStructFields(
- const StructDef &struct_def,
- std::function<void(const FieldDef &field)> cb
- ) {
+ void ForAllStructFields(const StructDef &struct_def,
+ std::function<void(const FieldDef &field)> cb) {
+ size_t offset_to_field = 0;
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
const auto &field = **it;
code_.SetValue("FIELD_TYPE", GetTypeGet(field.value.type));
- code_.SetValue("FIELD_NAME", Name(field));
+ code_.SetValue("FIELD_OTY", ObjectFieldType(field, false));
+ code_.SetValue("FIELD", namer_.Field(field.name));
+ code_.SetValue("FIELD_OFFSET", NumToString(offset_to_field));
+ code_.SetValue(
+ "REF",
+ IsStruct(field.value.type) || IsArray(field.value.type) ? "&" : "");
+ code_.IncrementIdentLevel();
cb(field);
+ code_.DecrementIdentLevel();
+ const size_t size = InlineSize(field.value.type);
+ offset_to_field += size + field.padding;
}
}
// Generate an accessor struct with constructor for a flatbuffers struct.
@@ -1657,121 +2589,146 @@
// platforms.
GenComment(struct_def.doc_comment);
code_.SetValue("ALIGN", NumToString(struct_def.minalign));
- code_.SetValue("STRUCT_NAME", Name(struct_def));
+ code_.SetValue("STRUCT_TY", namer_.Type(struct_def.name));
+ code_.SetValue("STRUCT_SIZE", NumToString(struct_def.bytesize));
- code_ += "// struct {{STRUCT_NAME}}, aligned to {{ALIGN}}";
- code_ += "#[repr(C, align({{ALIGN}}))]";
-
+ // We represent Flatbuffers-structs in Rust-u8-arrays since the data may be
+ // of the wrong endianness and alignment 1.
+ //
// PartialEq is useful to derive because we can correctly compare structs
// for equality by just comparing their underlying byte data. This doesn't
// hold for PartialOrd/Ord.
+ code_ += "// struct {{STRUCT_TY}}, aligned to {{ALIGN}}";
+ code_ += "#[repr(transparent)]";
code_ += "#[derive(Clone, Copy, PartialEq)]";
- code_ += "pub struct {{STRUCT_NAME}} {";
-
- int padding_id = 0;
- ForAllStructFields(struct_def, [&](const FieldDef &field) {
- code_ += " {{FIELD_NAME}}_: {{FIELD_TYPE}},";
- if (field.padding) {
- std::string padding;
- GenPadding(field, &padding, &padding_id, PaddingDefinition);
- code_ += padding;
- }
- });
- code_ += "} // pub struct {{STRUCT_NAME}}";
+ code_ += "pub struct {{STRUCT_TY}}(pub [u8; {{STRUCT_SIZE}}]);";
+ code_ += "impl Default for {{STRUCT_TY}} { ";
+ code_ += " fn default() -> Self { ";
+ code_ += " Self([0; {{STRUCT_SIZE}}])";
+ code_ += " }";
+ code_ += "}";
// Debug for structs.
- code_ += "impl std::fmt::Debug for {{STRUCT_NAME}} {";
- code_ += " fn fmt(&self, f: &mut std::fmt::Formatter"
- ") -> std::fmt::Result {";
- code_ += " f.debug_struct(\"{{STRUCT_NAME}}\")";
+ code_ += "impl std::fmt::Debug for {{STRUCT_TY}} {";
+ code_ +=
+ " fn fmt(&self, f: &mut std::fmt::Formatter"
+ ") -> std::fmt::Result {";
+ code_ += " f.debug_struct(\"{{STRUCT_TY}}\")";
ForAllStructFields(struct_def, [&](const FieldDef &unused) {
- (void) unused;
- code_ += " .field(\"{{FIELD_NAME}}\", &self.{{FIELD_NAME}}())";
+ (void)unused;
+ code_ += " .field(\"{{FIELD}}\", &self.{{FIELD}}())";
});
code_ += " .finish()";
code_ += " }";
code_ += "}";
code_ += "";
-
// Generate impls for SafeSliceAccess (because all structs are endian-safe),
// Follow for the value type, Follow for the reference type, Push for the
// value type, and Push for the reference type.
- code_ += "impl flatbuffers::SafeSliceAccess for {{STRUCT_NAME}} {}";
- code_ += "impl<'a> flatbuffers::Follow<'a> for {{STRUCT_NAME}} {";
- code_ += " type Inner = &'a {{STRUCT_NAME}};";
+ code_ += "impl flatbuffers::SimpleToVerifyInSlice for {{STRUCT_TY}} {}";
+ code_ += "impl flatbuffers::SafeSliceAccess for {{STRUCT_TY}} {}";
+ code_ += "impl<'a> flatbuffers::Follow<'a> for {{STRUCT_TY}} {";
+ code_ += " type Inner = &'a {{STRUCT_TY}};";
code_ += " #[inline]";
code_ += " fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {";
- code_ += " <&'a {{STRUCT_NAME}}>::follow(buf, loc)";
+ code_ += " <&'a {{STRUCT_TY}}>::follow(buf, loc)";
code_ += " }";
code_ += "}";
- code_ += "impl<'a> flatbuffers::Follow<'a> for &'a {{STRUCT_NAME}} {";
- code_ += " type Inner = &'a {{STRUCT_NAME}};";
+ code_ += "impl<'a> flatbuffers::Follow<'a> for &'a {{STRUCT_TY}} {";
+ code_ += " type Inner = &'a {{STRUCT_TY}};";
code_ += " #[inline]";
code_ += " fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {";
- code_ += " flatbuffers::follow_cast_ref::<{{STRUCT_NAME}}>(buf, loc)";
+ code_ += " flatbuffers::follow_cast_ref::<{{STRUCT_TY}}>(buf, loc)";
code_ += " }";
code_ += "}";
- code_ += "impl<'b> flatbuffers::Push for {{STRUCT_NAME}} {";
- code_ += " type Output = {{STRUCT_NAME}};";
+ code_ += "impl<'b> flatbuffers::Push for {{STRUCT_TY}} {";
+ code_ += " type Output = {{STRUCT_TY}};";
code_ += " #[inline]";
code_ += " fn push(&self, dst: &mut [u8], _rest: &[u8]) {";
code_ += " let src = unsafe {";
code_ +=
" ::std::slice::from_raw_parts("
- "self as *const {{STRUCT_NAME}} as *const u8, Self::size())";
+ "self as *const {{STRUCT_TY}} as *const u8, Self::size())";
code_ += " };";
code_ += " dst.copy_from_slice(src);";
code_ += " }";
code_ += "}";
- code_ += "impl<'b> flatbuffers::Push for &'b {{STRUCT_NAME}} {";
- code_ += " type Output = {{STRUCT_NAME}};";
+ code_ += "impl<'b> flatbuffers::Push for &'b {{STRUCT_TY}} {";
+ code_ += " type Output = {{STRUCT_TY}};";
code_ += "";
code_ += " #[inline]";
code_ += " fn push(&self, dst: &mut [u8], _rest: &[u8]) {";
code_ += " let src = unsafe {";
code_ +=
" ::std::slice::from_raw_parts("
- "*self as *const {{STRUCT_NAME}} as *const u8, Self::size())";
+ "*self as *const {{STRUCT_TY}} as *const u8, Self::size())";
code_ += " };";
code_ += " dst.copy_from_slice(src);";
code_ += " }";
code_ += "}";
code_ += "";
+
+ // Generate verifier: Structs are simple so presence and alignment are
+ // all that need to be checked.
+ code_ += "impl<'a> flatbuffers::Verifiable for {{STRUCT_TY}} {";
+ code_ += " #[inline]";
+ code_ += " fn run_verifier(";
+ code_ += " v: &mut flatbuffers::Verifier, pos: usize";
+ code_ += " ) -> Result<(), flatbuffers::InvalidFlatbuffer> {";
+ code_ += " use self::flatbuffers::Verifiable;";
+ code_ += " v.in_buffer::<Self>(pos)";
+ code_ += " }";
+ code_ += "}";
code_ += "";
+ // Implement serde::Serialize
+ if (parser_.opts.rust_serialize) {
+ const auto numFields = struct_def.fields.vec.size();
+ code_.SetValue("NUM_FIELDS", NumToString(numFields));
+ code_ += "impl Serialize for {{STRUCT_TY}} {";
+ code_ +=
+ " fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>";
+ code_ += " where";
+ code_ += " S: Serializer,";
+ code_ += " {";
+ if (numFields == 0) {
+ code_ +=
+ " let s = serializer.serialize_struct(\"{{STRUCT_TY}}\", 0)?;";
+ } else {
+ code_ +=
+ " let mut s = serializer.serialize_struct(\"{{STRUCT_TY}}\", "
+ "{{NUM_FIELDS}})?;";
+ }
+ ForAllStructFields(struct_def, [&](const FieldDef &unused) {
+ (void)unused;
+ code_ +=
+ " s.serialize_field(\"{{FIELD}}\", "
+ "&self.{{FIELD}}())?;";
+ });
+ code_ += " s.end()";
+ code_ += " }";
+ code_ += "}";
+ code_ += "";
+ }
+
// Generate a constructor that takes all fields as arguments.
- code_ += "impl {{STRUCT_NAME}} {";
- // TODO(cneo): Stop generating args on one line. Make it simpler.
- bool first_arg = true;
- code_ += " pub fn new(\\";
- ForAllStructFields(struct_def, [&](const FieldDef &field) {
- if (first_arg) first_arg = false; else code_ += ", \\";
- code_.SetValue("REF", IsStruct(field.value.type) ? "&" : "");
- code_ += "_{{FIELD_NAME}}: {{REF}}{{FIELD_TYPE}}\\";
+ code_ += "impl<'a> {{STRUCT_TY}} {";
+ code_ += " #[allow(clippy::too_many_arguments)]";
+ code_ += " pub fn new(";
+ ForAllStructFields(struct_def, [&](const FieldDef &unused) {
+ (void)unused;
+ code_ += " {{FIELD}}: {{REF}}{{FIELD_TYPE}},";
});
- code_ += ") -> Self {";
- code_ += " {{STRUCT_NAME}} {";
-
- ForAllStructFields(struct_def, [&](const FieldDef &field) {
- const bool is_struct = IsStruct(field.value.type);
- code_.SetValue("DEREF", is_struct ? "*" : "");
- code_.SetValue("TO_LE", is_struct ? "" : ".to_little_endian()");
- code_ += " {{FIELD_NAME}}_: {{DEREF}}_{{FIELD_NAME}}{{TO_LE}},";
+ code_ += " ) -> Self {";
+ code_ += " let mut s = Self([0; {{STRUCT_SIZE}}]);";
+ ForAllStructFields(struct_def, [&](const FieldDef &unused) {
+ (void)unused;
+ code_ += " s.set_{{FIELD}}({{FIELD}});";
});
- code_ += "";
-
- // TODO(cneo): Does this padding even work? Why after all the fields?
- padding_id = 0;
- ForAllStructFields(struct_def, [&](const FieldDef &field) {
- if (field.padding) {
- std::string padding;
- GenPadding(field, &padding, &padding_id, PaddingInitializer);
- code_ += " " + padding;
- }
- });
- code_ += " }";
+ code_ += " s";
code_ += " }";
+ code_ += "";
if (parser_.opts.generate_name_strings) {
GenFullyQualifiedNameGetter(struct_def, struct_def.name);
@@ -1779,26 +2736,155 @@
// Generate accessor methods for the struct.
ForAllStructFields(struct_def, [&](const FieldDef &field) {
- const bool is_struct = IsStruct(field.value.type);
- code_.SetValue("REF", is_struct ? "&" : "");
- code_.SetValue("FROM_LE", is_struct ? "" : ".from_little_endian()");
-
- this->GenComment(field.doc_comment, " ");
- code_ += " pub fn {{FIELD_NAME}}(&self) -> {{REF}}{{FIELD_TYPE}} {";
- code_ += " {{REF}}self.{{FIELD_NAME}}_{{FROM_LE}}";
- code_ += " }";
+ this->GenComment(field.doc_comment);
+ // Getter.
+ if (IsStruct(field.value.type)) {
+ code_ += "pub fn {{FIELD}}(&self) -> &{{FIELD_TYPE}} {";
+ code_ +=
+ " unsafe {"
+ " &*(self.0[{{FIELD_OFFSET}}..].as_ptr() as *const"
+ " {{FIELD_TYPE}}) }";
+ } else if (IsArray(field.value.type)) {
+ code_.SetValue("ARRAY_SIZE",
+ NumToString(field.value.type.fixed_length));
+ code_.SetValue("ARRAY_ITEM", GetTypeGet(field.value.type.VectorType()));
+ code_ +=
+ "pub fn {{FIELD}}(&'a self) -> "
+ "flatbuffers::Array<'a, {{ARRAY_ITEM}}, {{ARRAY_SIZE}}> {";
+ code_ += " flatbuffers::Array::follow(&self.0, {{FIELD_OFFSET}})";
+ } else {
+ code_ += "pub fn {{FIELD}}(&self) -> {{FIELD_TYPE}} {";
+ code_ +=
+ " let mut mem = core::mem::MaybeUninit::"
+ "<{{FIELD_TYPE}}>::uninit();";
+ code_ += " unsafe {";
+ code_ += " core::ptr::copy_nonoverlapping(";
+ code_ += " self.0[{{FIELD_OFFSET}}..].as_ptr(),";
+ code_ += " mem.as_mut_ptr() as *mut u8,";
+ code_ += " core::mem::size_of::<{{FIELD_TYPE}}>(),";
+ code_ += " );";
+ code_ += " mem.assume_init()";
+ code_ += " }.from_little_endian()";
+ }
+ code_ += "}\n";
+ // Setter.
+ if (IsStruct(field.value.type)) {
+ code_.SetValue("FIELD_SIZE", NumToString(InlineSize(field.value.type)));
+ code_ += "#[allow(clippy::identity_op)]"; // If FIELD_OFFSET=0.
+ code_ += "pub fn set_{{FIELD}}(&mut self, x: &{{FIELD_TYPE}}) {";
+ code_ +=
+ " self.0[{{FIELD_OFFSET}}..{{FIELD_OFFSET}} + {{FIELD_SIZE}}]"
+ ".copy_from_slice(&x.0)";
+ } else if (IsArray(field.value.type)) {
+ if (GetFullType(field.value.type) == ftArrayOfBuiltin) {
+ code_.SetValue("ARRAY_ITEM",
+ GetTypeGet(field.value.type.VectorType()));
+ code_.SetValue(
+ "ARRAY_ITEM_SIZE",
+ NumToString(InlineSize(field.value.type.VectorType())));
+ code_ +=
+ "pub fn set_{{FIELD}}(&mut self, items: &{{FIELD_TYPE}}) "
+ "{";
+ code_ +=
+ " flatbuffers::emplace_scalar_array(&mut self.0, "
+ "{{FIELD_OFFSET}}, items);";
+ } else {
+ code_.SetValue("FIELD_SIZE",
+ NumToString(InlineSize(field.value.type)));
+ code_ += "pub fn set_{{FIELD}}(&mut self, x: &{{FIELD_TYPE}}) {";
+ code_ += " unsafe {";
+ code_ += " std::ptr::copy(";
+ code_ += " x.as_ptr() as *const u8,";
+ code_ += " self.0.as_mut_ptr().add({{FIELD_OFFSET}}),";
+ code_ += " {{FIELD_SIZE}},";
+ code_ += " );";
+ code_ += " }";
+ }
+ } else {
+ code_ += "pub fn set_{{FIELD}}(&mut self, x: {{FIELD_TYPE}}) {";
+ code_ += " let x_le = x.to_little_endian();";
+ code_ += " unsafe {";
+ code_ += " core::ptr::copy_nonoverlapping(";
+ code_ += " &x_le as *const {{FIELD_TYPE}} as *const u8,";
+ code_ += " self.0[{{FIELD_OFFSET}}..].as_mut_ptr(),";
+ code_ += " core::mem::size_of::<{{FIELD_TYPE}}>(),";
+ code_ += " );";
+ code_ += " }";
+ }
+ code_ += "}\n";
// Generate a comparison function for this field if it is a key.
if (field.key) { GenKeyFieldMethods(field); }
});
- code_ += "}";
+
+ // Generate Object API unpack method.
+ if (parser_.opts.generate_object_based_api) {
+ code_.SetValue("STRUCT_OTY", namer_.ObjectType(struct_def.name));
+ code_ += " pub fn unpack(&self) -> {{STRUCT_OTY}} {";
+ code_ += " {{STRUCT_OTY}} {";
+ ForAllStructFields(struct_def, [&](const FieldDef &field) {
+ if (IsArray(field.value.type)) {
+ if (GetFullType(field.value.type) == ftArrayOfStruct) {
+ code_ +=
+ " {{FIELD}}: { let {{FIELD}} = "
+ "self.{{FIELD}}(); flatbuffers::array_init(|i| "
+ "{{FIELD}}.get(i).unpack()) },";
+ } else {
+ code_ += " {{FIELD}}: self.{{FIELD}}().into(),";
+ }
+ } else {
+ std::string unpack = IsStruct(field.value.type) ? ".unpack()" : "";
+ code_ += " {{FIELD}}: self.{{FIELD}}()" + unpack + ",";
+ }
+ });
+ code_ += " }";
+ code_ += " }";
+ }
+
+ code_ += "}"; // End impl Struct methods.
code_ += "";
+
+ // Generate Struct Object.
+ if (parser_.opts.generate_object_based_api) {
+ // Struct declaration
+ code_ += "#[derive(Debug, Clone, PartialEq, Default)]";
+ code_ += "pub struct {{STRUCT_OTY}} {";
+ ForAllStructFields(struct_def, [&](const FieldDef &field) {
+ (void)field; // unused.
+ code_ += "pub {{FIELD}}: {{FIELD_OTY}},";
+ });
+ code_ += "}";
+ // The `pack` method that turns the native struct into its Flatbuffers
+ // counterpart.
+ code_ += "impl {{STRUCT_OTY}} {";
+ code_ += " pub fn pack(&self) -> {{STRUCT_TY}} {";
+ code_ += " {{STRUCT_TY}}::new(";
+ ForAllStructFields(struct_def, [&](const FieldDef &field) {
+ if (IsStruct(field.value.type)) {
+ code_ += " &self.{{FIELD}}.pack(),";
+ } else if (IsArray(field.value.type)) {
+ if (GetFullType(field.value.type) == ftArrayOfStruct) {
+ code_ +=
+ " &flatbuffers::array_init(|i| "
+ "self.{{FIELD}}[i].pack()),";
+ } else {
+ code_ += " &self.{{FIELD}},";
+ }
+ } else {
+ code_ += " self.{{FIELD}},";
+ }
+ });
+ code_ += " )";
+ code_ += " }";
+ code_ += "}";
+ code_ += "";
+ }
}
void GenNamespaceImports(const int white_spaces) {
- if (white_spaces == 0) {
- code_ += "#![allow(unused_imports, dead_code)]";
- }
+ // DO not use global attributes (i.e. #![...]) since it interferes
+ // with users who include! generated files.
+ // See: https://github.com/google/flatbuffers/issues/6261
std::string indent = std::string(white_spaces, ' ');
code_ += "";
if (!parser_.opts.generate_all) {
@@ -1808,15 +2894,30 @@
auto noext = flatbuffers::StripExtension(it->second);
auto basename = flatbuffers::StripPath(noext);
- code_ += indent + "use crate::" + basename + "_generated::*;";
+ if (parser_.opts.include_prefix.empty()) {
+ code_ += indent + "use crate::" + basename +
+ parser_.opts.filename_suffix + "::*;";
+ } else {
+ auto prefix = parser_.opts.include_prefix;
+ prefix.pop_back();
+
+ code_ += indent + "use crate::" + prefix + "::" + basename +
+ parser_.opts.filename_suffix + "::*;";
+ }
}
}
-
code_ += indent + "use std::mem;";
code_ += indent + "use std::cmp::Ordering;";
code_ += "";
+ if (parser_.opts.rust_serialize) {
+ code_ += indent + "extern crate serde;";
+ code_ +=
+ indent +
+ "use self::serde::ser::{Serialize, Serializer, SerializeStruct};";
+ code_ += "";
+ }
code_ += indent + "extern crate flatbuffers;";
- code_ += indent + "use self::flatbuffers::EndianScalar;";
+ code_ += indent + "use self::flatbuffers::{EndianScalar, Follow};";
}
// Set up the correct namespace. This opens a namespace if the current
@@ -1853,7 +2954,7 @@
// in the previous example, E, then F, then G are opened
for (auto j = common_prefix_size; j != new_size; ++j) {
code_ += "#[allow(unused_imports, dead_code)]";
- code_ += "pub mod " + MakeSnakeCase(ns->components[j]) + " {";
+ code_ += "pub mod " + namer_.Namespace(ns->components[j]) + " {";
// Generate local namespace imports.
GenNamespaceImports(2);
}
@@ -1861,6 +2962,9 @@
cur_name_space_ = ns;
}
+
+ private:
+ Namer namer_;
};
} // namespace rust
diff --git a/src/idl_gen_swift.cpp b/src/idl_gen_swift.cpp
index 084bafe..c3c322f 100644
--- a/src/idl_gen_swift.cpp
+++ b/src/idl_gen_swift.cpp
@@ -127,6 +127,7 @@
"unowned",
"weak",
"willSet",
+ "Void",
nullptr,
};
for (auto kw = keywords; *kw; kw++) keywords_.insert(*kw);
@@ -153,17 +154,7 @@
const auto &struct_def = **it;
if (struct_def.fixed && !struct_def.generated) {
GenStructReader(struct_def);
- if (parser_.opts.generate_object_based_api) {
- GenObjectAPI(struct_def);
- }
- }
- }
-
- for (auto it = parser_.structs_.vec.begin();
- it != parser_.structs_.vec.end(); ++it) {
- const auto &struct_def = **it;
- if (struct_def.fixed && !struct_def.generated) {
- GenStructWriter(struct_def);
+ GenMutableStructReader(struct_def);
}
}
@@ -188,6 +179,168 @@
code_ += "\n// MARK: - {{MARKVALUE}}\n";
}
+ // MARK: - Generating structs
+
+ // Generates the reader for swift
+ void GenStructReader(const StructDef &struct_def) {
+ auto is_private_access = struct_def.attributes.Lookup("private");
+ code_.SetValue("ACCESS_TYPE", is_private_access ? "internal" : "public");
+ GenComment(struct_def.doc_comment);
+ code_.SetValue("STRUCTNAME", NameWrappedInNameSpace(struct_def));
+ code_ +=
+ "{{ACCESS_TYPE}} struct {{STRUCTNAME}}: NativeStruct, Verifiable, "
+ "FlatbuffersInitializable\\";
+ if (parser_.opts.generate_object_based_api) code_ += ", NativeObject\\";
+ code_ += " {";
+ code_ += "";
+ Indent();
+ code_ += ValidateFunc();
+ code_ += "";
+ int padding_id = 0;
+ std::string constructor = "";
+ std::vector<std::string> base_constructor;
+ std::vector<std::string> main_constructor;
+
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++it) {
+ auto &field = **it;
+ if (field.deprecated) continue;
+
+ if (!constructor.empty()) constructor += ", ";
+
+ auto name = Name(field);
+ auto type = GenType(field.value.type);
+ code_.SetValue("VALUENAME", name);
+ if (IsEnum(field.value.type)) {
+ code_.SetValue("BASEVALUE", GenTypeBasic(field.value.type, false));
+ }
+ code_.SetValue("VALUETYPE", type);
+ GenComment(field.doc_comment);
+ std::string valueType =
+ IsEnum(field.value.type) ? "{{BASEVALUE}}" : "{{VALUETYPE}}";
+ code_ += "private var _{{VALUENAME}}: " + valueType;
+ auto accessing_value = IsEnum(field.value.type) ? ".value" : "";
+ auto is_bool = IsBool(field.value.type.base_type);
+ auto base_value = IsStruct(field.value.type) ? (type + "()")
+ : is_bool ? ("0" == field.value.constant ? "false" : "true")
+ : field.value.constant;
+
+ main_constructor.push_back("_" + name + " = " + name + accessing_value);
+ base_constructor.push_back("_" + name + " = " + base_value);
+
+ if (field.padding) { GenPadding(field, &padding_id); }
+ constructor += name + ": " + type;
+ }
+ code_ += "";
+ BuildStructConstructor(struct_def);
+ BuildObjectConstructor(main_constructor, constructor);
+ BuildObjectConstructor(base_constructor, "");
+
+ if (parser_.opts.generate_object_based_api)
+ GenerateObjectAPIStructConstructor(struct_def);
+
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++it) {
+ auto &field = **it;
+ if (field.deprecated) continue;
+ auto name = Name(field);
+ auto type = GenType(field.value.type);
+ code_.SetValue("VALUENAME", name);
+ code_.SetValue("VALUETYPE", type);
+ GenComment(field.doc_comment);
+ if (!IsEnum(field.value.type)) {
+ code_ += GenReaderMainBody() + "_{{VALUENAME}} }";
+ } else if (IsEnum(field.value.type)) {
+ code_ +=
+ GenReaderMainBody() + "{{VALUETYPE}}(rawValue: _{{VALUENAME}})! }";
+ }
+ }
+ code_ += "";
+ code_ +=
+ "public static func verify<T>(_ verifier: inout Verifier, at position: "
+ "Int, of type: T.Type) throws where T: Verifiable {";
+ Indent();
+ code_ +=
+ "try verifier.inBuffer(position: position, of: {{STRUCTNAME}}.self)";
+ Outdent();
+ code_ += "}";
+ Outdent();
+ code_ += "}\n";
+ if (parser_.opts.gen_json_coders) GenerateJSONEncodingAPIs(struct_def);
+ }
+
+ void BuildStructConstructor(const StructDef &struct_def) {
+ code_ += "{{ACCESS_TYPE}} init(_ bb: ByteBuffer, o: Int32) {";
+ Indent();
+ code_ += "let {{ACCESS}} = Struct(bb: bb, position: o)";
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++it) {
+ auto &field = **it;
+ if (field.deprecated) continue;
+ auto name = Name(field);
+ auto type = field.value.type;
+ code_.SetValue("VALUENAME", name);
+ code_.SetValue("VALUETYPE", GenType(type));
+ code_.SetValue("OFFSET", NumToString(field.value.offset));
+ if (IsScalar(type.base_type)) {
+ if (IsEnum(type))
+ code_.SetValue("VALUETYPE", GenTypeBasic(field.value.type, false));
+ code_ +=
+ "_{{VALUENAME}} = {{ACCESS}}.readBuffer(of: {{VALUETYPE}}.self, "
+ "at: {{OFFSET}})";
+ } else {
+ code_ +=
+ "_{{VALUENAME}} = {{VALUETYPE}}({{ACCESS}}.bb, o: "
+ "{{ACCESS}}.postion + {{OFFSET}})";
+ }
+ }
+ Outdent();
+ code_ += "}\n";
+ }
+
+ void GenMutableStructReader(const StructDef &struct_def) {
+ GenObjectHeader(struct_def);
+
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++it) {
+ auto &field = **it;
+ if (field.deprecated) continue;
+ auto offset = NumToString(field.value.offset);
+ auto name = Name(field);
+ auto type = GenType(field.value.type);
+ code_.SetValue("VALUENAME", name);
+ if (IsEnum(field.value.type)) {
+ code_.SetValue("BASEVALUE", GenTypeBasic(field.value.type, false));
+ }
+ code_.SetValue("VALUETYPE", type);
+ code_.SetValue("OFFSET", offset);
+ if (IsScalar(field.value.type.base_type) && !IsEnum(field.value.type)) {
+ code_ +=
+ GenReaderMainBody() + "return " + GenReader("VALUETYPE") + " }";
+ } else if (IsEnum(field.value.type)) {
+ code_.SetValue("BASEVALUE", GenTypeBasic(field.value.type, false));
+ code_ += GenReaderMainBody() + "return " +
+ GenEnumConstructor("{{OFFSET}}") + "?? " +
+ GenEnumDefaultValue(field) + " }";
+ } else if (IsStruct(field.value.type)) {
+ code_.SetValue("VALUETYPE", GenType(field.value.type) + Mutable());
+ code_ += GenReaderMainBody() + "return " +
+ GenConstructor("{{ACCESS}}.postion + {{OFFSET}}");
+ }
+ if (parser_.opts.mutable_buffer && !IsStruct(field.value.type))
+ code_ += GenMutate("{{OFFSET}}", "", IsEnum(field.value.type));
+ }
+
+ if (parser_.opts.generate_object_based_api) {
+ GenerateObjectAPIExtensionHeader(NameWrappedInNameSpace(struct_def));
+ code_ += "return builder.create(struct: obj)";
+ Outdent();
+ code_ += "}";
+ }
+ Outdent();
+ code_ += "}\n";
+ }
+
// Generates the create function for swift
void GenStructWriter(const StructDef &struct_def) {
auto is_private_access = struct_def.attributes.Lookup("private");
@@ -203,12 +356,11 @@
std::string func_header = "";
GenerateStructArgs(struct_def, &func_header, "", "");
code_ += func_header.substr(0, func_header.size() - 2) + "\\";
- code_ += ") -> Offset<UOffset> {";
+ code_ += ") -> Offset {";
Indent();
code_ +=
"builder.createStructOf(size: {{STRUCTNAME}}.size, alignment: "
"{{STRUCTNAME}}.alignment)";
- GenerateStructBody(struct_def, "");
code_ += "return builder.endStruct()";
Outdent();
code_ += "}\n";
@@ -216,27 +368,6 @@
code_ += "}\n";
}
- void GenerateStructBody(const StructDef &struct_def,
- const std::string &nameprefix, int offset = 0) {
- for (auto it = struct_def.fields.vec.begin();
- it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
- if (field.deprecated) continue;
- auto name = nameprefix + Name(field);
- const auto &field_type = field.value.type;
- auto type = GenTypeBasic(field_type, false);
- if (IsStruct(field.value.type)) {
- GenerateStructBody(*field_type.struct_def, (nameprefix + field.name),
- static_cast<int>(field.value.offset));
- } else {
- auto off = NumToString(offset + field.value.offset);
- code_ += "builder.reverseAdd(v: " + name +
- (field_type.enum_def ? ".rawValue" : "") +
- ", postion: " + off + ")";
- }
- }
- }
-
void GenerateStructArgs(const StructDef &struct_def, std::string *code_ptr,
const std::string &nameprefix,
const std::string &object_name,
@@ -275,65 +406,23 @@
}
}
- void GenObjectHeader(const StructDef &struct_def) {
- GenComment(struct_def.doc_comment);
- code_.SetValue("SHORT_STRUCTNAME", Name(struct_def));
- code_.SetValue("STRUCTNAME", NameWrappedInNameSpace(struct_def));
- code_.SetValue("PROTOCOL",
- struct_def.fixed ? "Readable" : "FlatBufferObject");
- code_.SetValue("OBJECTTYPE", struct_def.fixed ? "Struct" : "Table");
- code_ += "{{ACCESS_TYPE}} struct {{STRUCTNAME}}: {{PROTOCOL}}\\";
- if (!struct_def.fixed && parser_.opts.generate_object_based_api)
- code_ += ", ObjectAPI\\";
- code_ += " {\n";
- Indent();
- code_ += ValidateFunc();
- code_ +=
- "{{ACCESS_TYPE}} var __buffer: ByteBuffer! { return {{ACCESS}}.bb }";
- code_ += "private var {{ACCESS}}: {{OBJECTTYPE}}\n";
- if (struct_def.fixed) {
- code_.SetValue("BYTESIZE", NumToString(struct_def.bytesize));
- code_.SetValue("MINALIGN", NumToString(struct_def.minalign));
- code_ += "{{ACCESS_TYPE}} static var size = {{BYTESIZE}}";
- code_ += "{{ACCESS_TYPE}} static var alignment = {{MINALIGN}}";
- } else {
- if (parser_.file_identifier_.length()) {
- code_.SetValue("FILENAME", parser_.file_identifier_);
- code_ +=
- "{{ACCESS_TYPE}} static func finish(_ fbb: inout "
- "FlatBufferBuilder, end: "
- "Offset<UOffset>, prefix: Bool = false) { fbb.finish(offset: end, "
- "fileId: "
- "\"{{FILENAME}}\", addPrefix: prefix) }";
- }
- code_ +=
- "{{ACCESS_TYPE}} static func getRootAs{{SHORT_STRUCTNAME}}(bb: "
- "ByteBuffer) -> "
- "{{STRUCTNAME}} { return {{STRUCTNAME}}(Table(bb: bb, position: "
- "Int32(bb.read(def: UOffset.self, position: bb.reader)) + "
- "Int32(bb.reader))) }\n";
- code_ += "private init(_ t: Table) { {{ACCESS}} = t }";
- }
- code_ +=
- "{{ACCESS_TYPE}} init(_ bb: ByteBuffer, o: Int32) { {{ACCESS}} = "
- "{{OBJECTTYPE}}(bb: "
- "bb, position: o) }";
- code_ += "";
- }
+ // MARK: - Table Generator
// Generates the reader for swift
void GenTable(const StructDef &struct_def) {
auto is_private_access = struct_def.attributes.Lookup("private");
code_.SetValue("ACCESS_TYPE", is_private_access ? "internal" : "public");
-
GenObjectHeader(struct_def);
GenTableAccessors(struct_def);
GenTableReader(struct_def);
GenTableWriter(struct_def);
if (parser_.opts.generate_object_based_api)
GenerateObjectAPITableExtension(struct_def);
+ code_ += "";
+ GenerateVerifier(struct_def);
Outdent();
code_ += "}\n";
+ if (parser_.opts.gen_json_coders) GenerateJSONEncodingAPIs(struct_def);
}
// Generates the reader for swift
@@ -358,51 +447,47 @@
}
}
- void GenerateObjectAPIExtensionHeader() {
- code_ += "\n";
- code_ += "{{ACCESS_TYPE}} mutating func unpack() -> " +
- ObjectAPIName("{{STRUCTNAME}}") + " {";
- Indent();
- code_ += "return " + ObjectAPIName("{{STRUCTNAME}}") + "(&self)";
- Outdent();
- code_ += "}";
- code_ +=
- "{{ACCESS_TYPE}} static func pack(_ builder: inout FlatBufferBuilder, "
- "obj: "
- "inout " +
- ObjectAPIName("{{STRUCTNAME}}") + "?) -> Offset<UOffset> {";
- Indent();
- code_ += "guard var obj = obj else { return Offset<UOffset>() }";
- code_ += "return pack(&builder, obj: &obj)";
- Outdent();
- code_ += "}";
- code_ += "";
- code_ +=
- "{{ACCESS_TYPE}} static func pack(_ builder: inout FlatBufferBuilder, "
- "obj: "
- "inout " +
- ObjectAPIName("{{STRUCTNAME}}") + ") -> Offset<UOffset> {";
- Indent();
- }
+ void GenObjectHeader(const StructDef &struct_def) {
+ GenComment(struct_def.doc_comment);
- void GenerateObjectAPIStructExtension(const StructDef &struct_def) {
- GenerateObjectAPIExtensionHeader();
- std::string code;
- GenerateStructArgs(struct_def, &code, "", "", "obj", true);
- code_ += "return create{{SHORT_STRUCTNAME}}(builder: &builder, \\";
- code_ += code.substr(0, code.size() - 2) + "\\";
- code_ += ")";
- Outdent();
- code_ += "}";
- }
-
- void GenTableReader(const StructDef &struct_def) {
- for (auto it = struct_def.fields.vec.begin();
- it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
- if (field.deprecated) continue;
- GenTableReaderFields(field);
+ code_.SetValue("SHORT_STRUCTNAME", Name(struct_def));
+ code_.SetValue("STRUCTNAME", NameWrappedInNameSpace(struct_def));
+ code_.SetValue("OBJECTTYPE", struct_def.fixed ? "Struct" : "Table");
+ code_.SetValue("MUTABLE", struct_def.fixed ? Mutable() : "");
+ code_ +=
+ "{{ACCESS_TYPE}} struct {{STRUCTNAME}}{{MUTABLE}}: FlatBufferObject\\";
+ if (!struct_def.fixed) code_ += ", Verifiable\\";
+ if (!struct_def.fixed && parser_.opts.generate_object_based_api)
+ code_ += ", ObjectAPIPacker\\";
+ code_ += " {\n";
+ Indent();
+ code_ += ValidateFunc();
+ code_ +=
+ "{{ACCESS_TYPE}} var __buffer: ByteBuffer! { return {{ACCESS}}.bb }";
+ code_ += "private var {{ACCESS}}: {{OBJECTTYPE}}\n";
+ if (!struct_def.fixed) {
+ if (parser_.file_identifier_.length()) {
+ code_.SetValue("FILENAME", parser_.file_identifier_);
+ code_ +=
+ "{{ACCESS_TYPE}} static func finish(_ fbb: inout "
+ "FlatBufferBuilder, end: "
+ "Offset, prefix: Bool = false) { fbb.finish(offset: end, "
+ "fileId: "
+ "\"{{FILENAME}}\", addPrefix: prefix) }";
+ }
+ code_ +=
+ "{{ACCESS_TYPE}} static func getRootAs{{SHORT_STRUCTNAME}}(bb: "
+ "ByteBuffer) -> "
+ "{{STRUCTNAME}} { return {{STRUCTNAME}}(Table(bb: bb, position: "
+ "Int32(bb.read(def: UOffset.self, position: bb.reader)) + "
+ "Int32(bb.reader))) }\n";
+ code_ += "private init(_ t: Table) { {{ACCESS}} = t }";
}
+ code_ +=
+ "{{ACCESS_TYPE}} init(_ bb: ByteBuffer, o: Int32) { {{ACCESS}} = "
+ "{{OBJECTTYPE}}(bb: "
+ "bb, position: o) }";
+ code_ += "";
}
void GenTableWriter(const StructDef &struct_def) {
@@ -423,17 +508,16 @@
auto &field = **it;
if (field.deprecated) continue;
if (field.key) key_field = &field;
- if (field.required)
+ if (field.IsRequired())
require_fields.push_back(NumToString(field.value.offset));
- GenTableWriterFields(field, &create_func_body, &create_func_header,
- should_generate_create);
+ GenTableWriterFields(field, &create_func_body, &create_func_header);
}
code_ +=
"{{ACCESS_TYPE}} static func end{{SHORT_STRUCTNAME}}(_ fbb: inout "
"FlatBufferBuilder, "
"start: "
- "UOffset) -> Offset<UOffset> { let end = Offset<UOffset>(offset: "
+ "UOffset) -> Offset { let end = Offset(offset: "
"fbb.endTable(at: start))\\";
if (require_fields.capacity() != 0) {
std::string fields = "";
@@ -455,7 +539,7 @@
}
code_ += "";
Outdent();
- code_ += ") -> Offset<UOffset> {";
+ code_ += ") -> Offset {";
Indent();
code_ += "let __start = {{STRUCTNAME}}.start{{SHORT_STRUCTNAME}}(&fbb)";
for (auto it = create_func_body.begin(); it < create_func_body.end();
@@ -477,8 +561,8 @@
code_ +=
"{{ACCESS_TYPE}} static func "
- "sortVectorOf{{SHORT_VALUENAME}}(offsets:[Offset<UOffset>], "
- "_ fbb: inout FlatBufferBuilder) -> Offset<UOffset> {";
+ "sortVectorOf{{SHORT_VALUENAME}}(offsets:[Offset], "
+ "_ fbb: inout FlatBufferBuilder) -> Offset {";
Indent();
code_ += spacing + "var off = offsets";
code_ +=
@@ -495,24 +579,22 @@
void GenTableWriterFields(const FieldDef &field,
std::vector<std::string> *create_body,
- std::vector<std::string> *create_header,
- bool &contains_structs) {
+ std::vector<std::string> *create_header) {
std::string builder_string = ", _ fbb: inout FlatBufferBuilder) { ";
auto &create_func_body = *create_body;
auto &create_func_header = *create_header;
auto name = Name(field);
auto type = GenType(field.value.type);
- bool opt_scalar = field.optional && IsScalar(field.value.type.base_type);
+ auto opt_scalar =
+ field.IsOptional() && IsScalar(field.value.type.base_type);
auto nullable_type = opt_scalar ? type + "?" : type;
code_.SetValue("VALUENAME", name);
code_.SetValue("VALUETYPE", nullable_type);
code_.SetValue("OFFSET", name);
code_.SetValue("CONSTANT", field.value.constant);
std::string check_if_vector =
- (IsVector(field.value.type) ||
- IsArray(field.value.type))
- ? "VectorOf("
- : "(";
+ (IsVector(field.value.type) || IsArray(field.value.type)) ? "VectorOf("
+ : "(";
auto body = "add" + check_if_vector + name + ": ";
code_ += "{{ACCESS_TYPE}} static func " + body + "\\";
@@ -526,17 +608,18 @@
code_ +=
"{{VALUETYPE}}" + builder_string + "fbb.add(element: {{VALUENAME}}\\";
- code_ += field.optional ? (optional_enum + "\\")
- : (is_enum + ", def: {{CONSTANT}}\\");
+ code_ += field.IsOptional() ? (optional_enum + "\\")
+ : (is_enum + ", def: {{CONSTANT}}\\");
code_ += ", at: {{TABLEOFFSET}}.{{OFFSET}}.p) }";
auto default_value =
IsEnum(field.value.type)
- ? (field.optional ? "nil" : GenEnumDefaultValue(field))
+ ? (field.IsOptional() ? "nil" : GenEnumDefaultValue(field))
: field.value.constant;
- create_func_header.push_back("" + name + ": " + nullable_type + " = " +
- (field.optional ? "nil" : default_value));
+ create_func_header.push_back(
+ "" + name + ": " + nullable_type + " = " +
+ (field.IsOptional() ? "nil" : default_value));
return;
}
@@ -545,64 +628,69 @@
"0" == field.value.constant ? "false" : "true";
code_.SetValue("CONSTANT", default_value);
- code_.SetValue("VALUETYPE", field.optional ? "Bool?" : "Bool");
+ code_.SetValue("VALUETYPE", field.IsOptional() ? "Bool?" : "Bool");
code_ += "{{VALUETYPE}}" + builder_string +
"fbb.add(element: {{VALUENAME}},\\";
- code_ += field.optional ? "\\" : " def: {{CONSTANT}},";
+ code_ += field.IsOptional() ? "\\" : " def: {{CONSTANT}},";
code_ += " at: {{TABLEOFFSET}}.{{OFFSET}}.p) }";
- create_func_header.push_back(name + ": " + nullable_type + " = " +
- (field.optional ? "nil" : default_value));
+ create_func_header.push_back(
+ name + ": " + nullable_type + " = " +
+ (field.IsOptional() ? "nil" : default_value));
return;
}
if (IsStruct(field.value.type)) {
- contains_structs = false;
- auto struct_type = "Offset<UOffset>?";
- auto camel_case_name = "structOf" + MakeCamel(name, true);
- auto reader_type =
- "fbb.add(structOffset: {{TABLEOFFSET}}.{{OFFSET}}.p) }";
- auto create_struct = "guard {{VALUENAME}} != nil else { return }; ";
- code_ += struct_type + builder_string + create_struct + reader_type;
+ auto create_struct =
+ "guard let {{VALUENAME}} = {{VALUENAME}} else { return };"
+ " fbb.create(struct: {{VALUENAME}}, position: "
+ "{{TABLEOFFSET}}.{{OFFSET}}.p) }";
+ code_ += type + "?" + builder_string + create_struct;
+ /// Optional hard coded since structs are always optional
+ create_func_header.push_back(name + ": " + type + "? = nil");
return;
}
- auto offset_type = IsString(field.value.type)
- ? "Offset<String>"
- : "Offset<UOffset>";
auto camel_case_name =
- (IsVector(field.value.type) ||
- IsArray(field.value.type)
- ? "vectorOf"
- : "offsetOf") +
- MakeCamel(name, true);
+ ConvertCase(name, Case::kLowerCamel) +
+ (IsVector(field.value.type) || IsArray(field.value.type)
+ ? "VectorOffset"
+ : "Offset");
create_func_header.push_back(camel_case_name + " " + name + ": " +
- offset_type + " = Offset()");
+ "Offset = Offset()");
auto reader_type =
IsStruct(field.value.type) && field.value.type.struct_def->fixed
? "structOffset: {{TABLEOFFSET}}.{{OFFSET}}.p) }"
: "offset: {{VALUENAME}}, at: {{TABLEOFFSET}}.{{OFFSET}}.p) }";
- code_ += offset_type + builder_string + "fbb.add(" + reader_type;
+ code_ += "Offset" + builder_string + "fbb.add(" + reader_type;
auto vectortype = field.value.type.VectorType();
if ((vectortype.base_type == BASE_TYPE_STRUCT &&
field.value.type.struct_def->fixed) &&
- (IsVector(field.value.type) ||
- IsArray(field.value.type))) {
+ (IsVector(field.value.type) || IsArray(field.value.type))) {
auto field_name = NameWrappedInNameSpace(*vectortype.struct_def);
- code_ += "public static func startVectorOf" + MakeCamel(name, true) +
+ code_ += "public static func startVectorOf" +
+ ConvertCase(name, Case::kUpperCamel) +
"(_ size: Int, in builder: inout "
"FlatBufferBuilder) {";
Indent();
- code_ += "builder.startVectorOfStructs(count: size, size: " + field_name +
- ".size, "
- "alignment: " +
- field_name + ".alignment)";
+ code_ += "builder.startVector(size * MemoryLayout<" + field_name +
+ ">.size, elementSize: MemoryLayout<" + field_name +
+ ">.alignment)";
Outdent();
code_ += "}";
}
}
+ void GenTableReader(const StructDef &struct_def) {
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++it) {
+ auto &field = **it;
+ if (field.deprecated) continue;
+ GenTableReaderFields(field);
+ }
+ }
+
void GenTableReaderFields(const FieldDef &field) {
auto offset = NumToString(field.value.offset);
auto name = Name(field);
@@ -611,7 +699,8 @@
code_.SetValue("VALUETYPE", type);
code_.SetValue("OFFSET", name);
code_.SetValue("CONSTANT", field.value.constant);
- bool opt_scalar = field.optional && IsScalar(field.value.type.base_type);
+ bool opt_scalar =
+ field.IsOptional() && IsScalar(field.value.type.base_type);
std::string def_Val = opt_scalar ? "nil" : "{{CONSTANT}}";
std::string optional = opt_scalar ? "?" : "";
auto const_string = "return o == 0 ? " + def_Val + " : ";
@@ -626,7 +715,8 @@
if (IsBool(field.value.type.base_type)) {
std::string default_value =
- "0" == field.value.constant ? "false" : "true";
+ field.IsOptional() ? "nil"
+ : ("0" == field.value.constant ? "false" : "true");
code_.SetValue("CONSTANT", default_value);
code_.SetValue("VALUETYPE", "Bool");
code_ += GenReaderMainBody(optional) + "\\";
@@ -638,7 +728,8 @@
}
if (IsEnum(field.value.type)) {
- auto default_value = field.optional ? "nil" : GenEnumDefaultValue(field);
+ auto default_value =
+ field.IsOptional() ? "nil" : GenEnumDefaultValue(field);
code_.SetValue("BASEVALUE", GenTypeBasic(field.value.type, false));
code_ += GenReaderMainBody(optional) + "\\";
code_ += GenOffset() + "return o == 0 ? " + default_value + " : " +
@@ -648,13 +739,19 @@
return;
}
- std::string is_required = field.required ? "!" : "?";
- auto required_reader = field.required ? "return " : const_string;
+ std::string is_required = field.IsRequired() ? "!" : "?";
+ auto required_reader = field.IsRequired() ? "return " : const_string;
if (IsStruct(field.value.type) && field.value.type.struct_def->fixed) {
code_.SetValue("VALUETYPE", GenType(field.value.type));
code_.SetValue("CONSTANT", "nil");
code_ += GenReaderMainBody(is_required) + GenOffset() + required_reader +
+ "{{ACCESS}}.readBuffer(of: {{VALUETYPE}}.self, at: o) }";
+ code_.SetValue("VALUENAME",
+ "mutable" + ConvertCase(name, Case::kUpperCamel));
+ code_.SetValue("VALUETYPE", GenType(field.value.type) + Mutable());
+ code_.SetValue("CONSTANT", "nil");
+ code_ += GenReaderMainBody(is_required) + GenOffset() + required_reader +
GenConstructor("o + {{ACCESS}}.postion");
return;
}
@@ -667,9 +764,10 @@
GenConstructor(GenIndirect("o + {{ACCESS}}.postion"));
break;
- case BASE_TYPE_STRING:
+ case BASE_TYPE_STRING: {
+ auto default_string = "\"" + field.value.constant + "\"";
code_.SetValue("VALUETYPE", GenType(field.value.type));
- code_.SetValue("CONSTANT", "nil");
+ code_.SetValue("CONSTANT", field.IsDefault() ? default_string : "nil");
code_ += GenReaderMainBody(is_required) + GenOffset() +
required_reader + "{{ACCESS}}.string(at: o) }";
code_ += "{{ACCESS_TYPE}} var {{VALUENAME}}SegmentArray: [UInt8]" +
@@ -677,15 +775,14 @@
" { return "
"{{ACCESS}}.getVector(at: {{TABLEOFFSET}}.{{OFFSET}}.v) }";
break;
-
+ }
case BASE_TYPE_ARRAY: FLATBUFFERS_FALLTHROUGH(); // fall thru
- case BASE_TYPE_VECTOR:
- GenTableReaderVectorFields(field, const_string);
- break;
+ case BASE_TYPE_VECTOR: GenTableReaderVectorFields(field); break;
case BASE_TYPE_UNION:
code_.SetValue("CONSTANT", "nil");
code_ +=
- "{{ACCESS_TYPE}} func {{VALUENAME}}<T: FlatBufferObject>(type: "
+ "{{ACCESS_TYPE}} func {{VALUENAME}}<T: "
+ "FlatbuffersInitializable>(type: "
"T.Type) -> T" +
is_required + " { " + GenOffset() + required_reader +
"{{ACCESS}}.union(o) }";
@@ -694,33 +791,33 @@
}
}
- void GenTableReaderVectorFields(const FieldDef &field,
- const std::string &const_string) {
+ void GenTableReaderVectorFields(const FieldDef &field) {
+ std::string const_string = "return o == 0 ? {{CONSTANT}} : ";
auto vectortype = field.value.type.VectorType();
code_.SetValue("SIZE", NumToString(InlineSize(vectortype)));
code_ += "{{ACCESS_TYPE}} var {{VALUENAME}}Count: Int32 { " + GenOffset() +
- const_string + "{{ACCESS}}.vector(count: o) }";
- code_.SetValue("CONSTANT", IsScalar(vectortype.base_type) == true
- ? field.value.constant
- : "nil");
+ "return o == 0 ? 0 : {{ACCESS}}.vector(count: o) }";
+ code_.SetValue("CONSTANT",
+ IsScalar(vectortype.base_type) == true ? "0" : "nil");
auto nullable = IsScalar(vectortype.base_type) == true ? "" : "?";
nullable = IsEnum(vectortype) == true ? "?" : nullable;
+
if (vectortype.base_type != BASE_TYPE_UNION) {
code_ += GenArrayMainBody(nullable) + GenOffset() + "\\";
} else {
code_ +=
- "{{ACCESS_TYPE}} func {{VALUENAME}}<T: FlatBufferObject>(at index: "
+ "{{ACCESS_TYPE}} func {{VALUENAME}}<T: FlatbuffersInitializable>(at "
+ "index: "
"Int32, type: T.Type) -> T? { " +
GenOffset() + "\\";
}
if (IsBool(vectortype.base_type)) {
code_.SetValue("CONSTANT", field.value.offset == 0 ? "false" : "true");
- code_.SetValue("VALUETYPE", "Byte");
+ code_.SetValue("VALUETYPE", "Bool");
}
- if (!IsEnum(vectortype))
- code_ +=
- const_string + (IsBool(vectortype.base_type) ? "0 != " : "") + "\\";
+
+ if (!IsEnum(vectortype)) code_ += const_string + "\\";
if (IsScalar(vectortype.base_type) && !IsEnum(vectortype) &&
!IsBool(field.value.type.base_type)) {
@@ -733,9 +830,18 @@
if (parser_.opts.mutable_buffer) code_ += GenMutateArray();
return;
}
+
if (vectortype.base_type == BASE_TYPE_STRUCT &&
field.value.type.struct_def->fixed) {
- code_ += GenConstructor("{{ACCESS}}.vector(at: o) + index * {{SIZE}}");
+ code_ +=
+ "{{ACCESS}}.directRead(of: {{VALUETYPE}}.self, offset: "
+ "{{ACCESS}}.vector(at: o) + index * {{SIZE}}) }";
+ code_.SetValue("VALUENAME",
+ "mutable" + ConvertCase(Name(field), Case::kUpperCamel));
+ code_.SetValue("VALUETYPE", GenType(field.value.type) + Mutable());
+ code_ += GenArrayMainBody(nullable) + GenOffset() + const_string +
+ GenConstructor("{{ACCESS}}.vector(at: o) + index * {{SIZE}}");
+
return;
}
@@ -778,6 +884,272 @@
}
}
+ void GenerateCodingKeys(const StructDef &struct_def) {
+ code_ += "enum CodingKeys: String, CodingKey {";
+ Indent();
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++it) {
+ auto &field = **it;
+ if (field.deprecated) continue;
+ auto name = Name(field);
+
+ code_.SetValue("RAWVALUENAME", field.name);
+ code_.SetValue("VALUENAME", name);
+ code_ += "case {{VALUENAME}} = \"{{RAWVALUENAME}}\"";
+ }
+ Outdent();
+ code_ += "}";
+ }
+
+ void GenerateEncoderUnionBody(const FieldDef &field) {
+ EnumDef &union_def = *field.value.type.enum_def;
+ auto is_vector = field.value.type.base_type == BASE_TYPE_VECTOR ||
+ field.value.type.base_type == BASE_TYPE_ARRAY;
+ if (field.value.type.base_type == BASE_TYPE_UTYPE ||
+ (is_vector &&
+ field.value.type.VectorType().base_type == BASE_TYPE_UTYPE))
+ return;
+ if (is_vector) {
+ code_ +=
+ "var enumsEncoder = container.nestedUnkeyedContainer(forKey: "
+ ".{{VALUENAME}}Type)";
+ code_ +=
+ "var contentEncoder = container.nestedUnkeyedContainer(forKey: "
+ ".{{VALUENAME}})";
+ code_ += "for index in 0..<{{VALUENAME}}Count {";
+ Indent();
+ code_ +=
+ "guard let type = {{VALUENAME}}Type(at: index) else { continue }";
+ code_ += "try enumsEncoder.encode(type)";
+ code_ += "switch type {";
+ for (auto it = union_def.Vals().begin(); it != union_def.Vals().end();
+ ++it) {
+ const auto &ev = **it;
+
+ auto name = Name(ev);
+ auto type = GenType(ev.union_type);
+ code_.SetValue("KEY", name);
+ code_.SetValue("VALUETYPE", type);
+ if (ev.union_type.base_type == BASE_TYPE_NONE) { continue; }
+ code_ += "case .{{KEY}}:";
+ Indent();
+ code_ += "let _v = {{VALUENAME}}(at: index, type: {{VALUETYPE}}.self)";
+ code_ += "try contentEncoder.encode(_v)";
+ Outdent();
+ }
+ code_ += "default: break;";
+ code_ += "}";
+ Outdent();
+ code_ += "}";
+ return;
+ }
+
+ code_ += "switch {{VALUENAME}}Type {";
+ for (auto it = union_def.Vals().begin(); it != union_def.Vals().end();
+ ++it) {
+ const auto &ev = **it;
+
+ auto name = Name(ev);
+ auto type = GenType(ev.union_type);
+ code_.SetValue("KEY", name);
+ code_.SetValue("VALUETYPE", type);
+ if (ev.union_type.base_type == BASE_TYPE_NONE) { continue; }
+ code_ += "case .{{KEY}}:";
+ Indent();
+ code_ += "let _v = {{VALUENAME}}(type: {{VALUETYPE}}.self)";
+ code_ += "try container.encodeIfPresent(_v, forKey: .{{VALUENAME}})";
+ Outdent();
+ }
+ code_ += "default: break;";
+ code_ += "}";
+ }
+
+ void GenerateEncoderBody(const StructDef &struct_def) {
+ code_ += "var container = encoder.container(keyedBy: CodingKeys.self)";
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++it) {
+ auto &field = **it;
+ if (field.deprecated) continue;
+ auto name = Name(field);
+ auto type = field.value.type;
+
+ auto is_non_union_vector =
+ (field.value.type.base_type == BASE_TYPE_ARRAY ||
+ field.value.type.base_type == BASE_TYPE_VECTOR) &&
+ field.value.type.VectorType().base_type != BASE_TYPE_UTYPE;
+
+ code_.SetValue("RAWVALUENAME", field.name);
+ code_.SetValue("VALUENAME", name);
+ code_.SetValue("CONSTANT", field.value.constant);
+ bool should_indent = true;
+ if (is_non_union_vector) {
+ code_ += "if {{VALUENAME}}Count > 0 {";
+ } else if (IsEnum(type) && !field.IsOptional()) {
+ code_.SetValue("CONSTANT", GenEnumDefaultValue(field));
+ code_ += "if {{VALUENAME}} != {{CONSTANT}} {";
+ } else if (IsScalar(type.base_type) && !IsEnum(type) &&
+ !IsBool(type.base_type) && !field.IsOptional()) {
+ code_ += "if {{VALUENAME}} != {{CONSTANT}} {";
+ } else if (IsBool(type.base_type) && !field.IsOptional()) {
+ std::string default_value =
+ "0" == field.value.constant ? "false" : "true";
+ code_.SetValue("CONSTANT", default_value);
+ code_ += "if {{VALUENAME}} != {{CONSTANT}} {";
+ } else {
+ should_indent = false;
+ }
+ if (should_indent) Indent();
+
+ if (IsUnion(type) && !IsEnum(type)) {
+ GenerateEncoderUnionBody(field);
+ } else if (is_non_union_vector &&
+ (!IsScalar(type.VectorType().base_type) ||
+ IsEnum(type.VectorType()))) {
+ code_ +=
+ "var contentEncoder = container.nestedUnkeyedContainer(forKey: "
+ ".{{VALUENAME}})";
+ code_ += "for index in 0..<{{VALUENAME}}Count {";
+ Indent();
+ code_ += "guard let type = {{VALUENAME}}(at: index) else { continue }";
+ code_ += "try contentEncoder.encode(type)";
+ Outdent();
+ code_ += "}";
+ } else {
+ code_ +=
+ "try container.encodeIfPresent({{VALUENAME}}, forKey: "
+ ".{{VALUENAME}})";
+ }
+ if (should_indent) Outdent();
+
+ if (is_non_union_vector ||
+ (IsScalar(type.base_type) && !field.IsOptional())) {
+ code_ += "}";
+ }
+ }
+ }
+
+ void GenerateJSONEncodingAPIs(const StructDef &struct_def) {
+ code_ += "extension {{STRUCTNAME}}: Encodable {";
+ Indent();
+ code_ += "";
+ if (struct_def.fields.vec.empty() == false) GenerateCodingKeys(struct_def);
+
+ code_ += "public func encode(to encoder: Encoder) throws {";
+ Indent();
+ if (struct_def.fields.vec.empty() == false) GenerateEncoderBody(struct_def);
+ Outdent();
+ code_ += "}";
+ Outdent();
+ code_ += "}";
+ code_ += "";
+ }
+
+ void GenerateVerifier(const StructDef &struct_def) {
+ code_ +=
+ "public static func verify<T>(_ verifier: inout Verifier, at position: "
+ "Int, of type: T.Type) throws where T: Verifiable {";
+ Indent();
+ code_ += "var _v = try verifier.visitTable(at: position)";
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++it) {
+ auto &field = **it;
+ if (field.deprecated) continue;
+ auto offset = NumToString(field.value.offset);
+ auto name = Name(field);
+
+ code_.SetValue("VALUENAME", name);
+ code_.SetValue("VALUETYPE", GenerateVerifierType(field));
+ code_.SetValue("OFFSET", name);
+ code_.SetValue("ISREQUIRED", field.IsRequired() ? "true" : "false");
+
+ if (IsUnion(field.value.type)) {
+ GenerateUnionTypeVerifier(field);
+ continue;
+ }
+
+ code_ +=
+ "try _v.visit(field: {{TABLEOFFSET}}.{{OFFSET}}.p, fieldName: "
+ "\"{{VALUENAME}}\", required: {{ISREQUIRED}}, type: "
+ "{{VALUETYPE}}.self)";
+ }
+ code_ += "_v.finish()";
+ Outdent();
+ code_ += "}";
+ }
+
+ void GenerateUnionTypeVerifier(const FieldDef &field) {
+ auto is_vector = IsVector(field.value.type) || IsArray(field.value.type);
+ if (field.value.type.base_type == BASE_TYPE_UTYPE ||
+ (is_vector &&
+ field.value.type.VectorType().base_type == BASE_TYPE_UTYPE))
+ return;
+ EnumDef &union_def = *field.value.type.enum_def;
+ code_.SetValue("VALUETYPE", NameWrappedInNameSpace(union_def));
+ code_.SetValue("FUNCTION_NAME", is_vector ? "visitUnionVector" : "visit");
+ code_ +=
+ "try _v.{{FUNCTION_NAME}}(unionKey: {{TABLEOFFSET}}.{{OFFSET}}Type.p, "
+ "unionField: {{TABLEOFFSET}}.{{OFFSET}}.p, unionKeyName: "
+ "\"{{VALUENAME}}Type\", fieldName: \"{{VALUENAME}}\", required: "
+ "{{ISREQUIRED}}, completion: { (verifier, key: {{VALUETYPE}}, pos) in";
+ Indent();
+ code_ += "switch key {";
+ for (auto it = union_def.Vals().begin(); it != union_def.Vals().end();
+ ++it) {
+ const auto &ev = **it;
+
+ auto name = Name(ev);
+ auto type = GenType(ev.union_type);
+ code_.SetValue("KEY", name);
+ code_.SetValue("VALUETYPE", type);
+ code_ += "case .{{KEY}}:";
+ Indent();
+ if (ev.union_type.base_type == BASE_TYPE_NONE) {
+ code_ += "break // NOTE - SWIFT doesnt support none";
+ } else if (ev.union_type.base_type == BASE_TYPE_STRING) {
+ code_ +=
+ "try ForwardOffset<String>.verify(&verifier, at: pos, of: "
+ "String.self)";
+ } else {
+ code_.SetValue("MAINTYPE", ev.union_type.struct_def->fixed
+ ? type
+ : "ForwardOffset<" + type + ">");
+ code_ +=
+ "try {{MAINTYPE}}.verify(&verifier, at: pos, of: "
+ "{{VALUETYPE}}.self)";
+ }
+ Outdent();
+ }
+ code_ += "}";
+ Outdent();
+ code_ += "})";
+ }
+
+ std::string GenerateVerifierType(const FieldDef &field) {
+ auto type = field.value.type;
+ auto is_vector = IsVector(type) || IsArray(type);
+
+ if (is_vector) {
+ auto vector_type = field.value.type.VectorType();
+ return "ForwardOffset<Vector<" +
+ GenerateNestedVerifierTypes(vector_type) + ", " +
+ GenType(vector_type) + ">>";
+ }
+
+ return GenerateNestedVerifierTypes(field.value.type);
+ }
+
+ std::string GenerateNestedVerifierTypes(const Type &type) {
+ auto string_type = GenType(type);
+
+ if (IsScalar(type.base_type)) { return string_type; }
+
+ if (IsString(type)) { return "ForwardOffset<" + string_type + ">"; }
+
+ if (type.struct_def && type.struct_def->fixed) { return string_type; }
+
+ return "ForwardOffset<" + string_type + ">";
+ }
+
void GenByKeyFunctions(const FieldDef &key_field) {
code_.SetValue("TYPE", GenType(key_field.value.type));
code_ +=
@@ -788,54 +1160,27 @@
"{{ACCESS}}.vector(at: o), key: key, fbb: {{ACCESS}}.bb) }";
}
- // Generates the reader for swift
- void GenStructReader(const StructDef &struct_def) {
- auto is_private_access = struct_def.attributes.Lookup("private");
- code_.SetValue("ACCESS_TYPE", is_private_access ? "internal" : "public");
-
- GenObjectHeader(struct_def);
- for (auto it = struct_def.fields.vec.begin();
- it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
- if (field.deprecated) continue;
- auto offset = NumToString(field.value.offset);
- auto name = Name(field);
- auto type = GenType(field.value.type);
- code_.SetValue("VALUENAME", name);
- code_.SetValue("VALUETYPE", type);
- code_.SetValue("OFFSET", offset);
- GenComment(field.doc_comment);
- if (IsScalar(field.value.type.base_type) && !IsEnum(field.value.type)) {
- code_ +=
- GenReaderMainBody() + "return " + GenReader("VALUETYPE") + " }";
- if (parser_.opts.mutable_buffer) code_ += GenMutate("{{OFFSET}}", "");
- } else if (IsEnum(field.value.type)) {
- code_.SetValue("BASEVALUE", GenTypeBasic(field.value.type, false));
- code_ += GenReaderMainBody() + "return " +
- GenEnumConstructor("{{OFFSET}}") + "?? " +
- GenEnumDefaultValue(field) + " }";
- } else if (IsStruct(field.value.type)) {
- code_.SetValue("VALUETYPE", GenType(field.value.type));
- code_ += GenReaderMainBody() + "return " +
- GenConstructor("{{ACCESS}}.postion + {{OFFSET}}");
- }
- }
- if (parser_.opts.generate_object_based_api)
- GenerateObjectAPIStructExtension(struct_def);
- Outdent();
- code_ += "}\n";
- }
-
void GenEnum(const EnumDef &enum_def) {
if (enum_def.generated) return;
auto is_private_access = enum_def.attributes.Lookup("private");
+ code_.SetValue("ENUM_TYPE",
+ enum_def.is_union ? "UnionEnum" : "Enum, Verifiable");
code_.SetValue("ACCESS_TYPE", is_private_access ? "internal" : "public");
code_.SetValue("ENUM_NAME", NameWrappedInNameSpace(enum_def));
code_.SetValue("BASE_TYPE", GenTypeBasic(enum_def.underlying_type, false));
GenComment(enum_def.doc_comment);
- code_ += "{{ACCESS_TYPE}} enum {{ENUM_NAME}}: {{BASE_TYPE}}, Enum { ";
+ code_ +=
+ "{{ACCESS_TYPE}} enum {{ENUM_NAME}}: {{BASE_TYPE}}, {{ENUM_TYPE}} {";
Indent();
code_ += "{{ACCESS_TYPE}} typealias T = {{BASE_TYPE}}";
+ if (enum_def.is_union) {
+ code_ += "";
+ code_ += "{{ACCESS_TYPE}} init?(value: T) {";
+ Indent();
+ code_ += "self.init(rawValue: value)";
+ Outdent();
+ code_ += "}\n";
+ }
code_ +=
"{{ACCESS_TYPE}} static var byteSize: Int { return "
"MemoryLayout<{{BASE_TYPE}}>.size "
@@ -850,17 +1195,20 @@
GenComment(ev.doc_comment);
code_ += "case {{KEY}} = {{VALUE}}";
}
- code_ += "\n";
+ code_ += "";
AddMinOrMaxEnumValue(Name(*enum_def.MaxValue()), "max");
AddMinOrMaxEnumValue(Name(*enum_def.MinValue()), "min");
Outdent();
code_ += "}\n";
+ if (parser_.opts.gen_json_coders) EnumEncoder(enum_def);
+ code_ += "";
if (parser_.opts.generate_object_based_api && enum_def.is_union) {
code_ += "{{ACCESS_TYPE}} struct {{ENUM_NAME}}Union {";
Indent();
code_ += "{{ACCESS_TYPE}} var type: {{ENUM_NAME}}";
- code_ += "{{ACCESS_TYPE}} var value: NativeTable?";
- code_ += "{{ACCESS_TYPE}} init(_ v: NativeTable?, type: {{ENUM_NAME}}) {";
+ code_ += "{{ACCESS_TYPE}} var value: NativeObject?";
+ code_ +=
+ "{{ACCESS_TYPE}} init(_ v: NativeObject?, type: {{ENUM_NAME}}) {";
Indent();
code_ += "self.type = type";
code_ += "self.value = v";
@@ -868,7 +1216,7 @@
code_ += "}";
code_ +=
"{{ACCESS_TYPE}} func pack(builder: inout FlatBufferBuilder) -> "
- "Offset<UOffset> {";
+ "Offset {";
Indent();
BuildUnionEnumSwitchCaseWritter(enum_def);
Outdent();
@@ -878,9 +1226,82 @@
}
}
+ void EnumEncoder(const EnumDef &enum_def) {
+ code_ += "extension {{ENUM_NAME}}: Encodable {";
+ Indent();
+ code_ += "{{ACCESS_TYPE}} func encode(to encoder: Encoder) throws {";
+ Indent();
+ code_ += "var container = encoder.singleValueContainer()";
+ code_ += "switch self {";
+ for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
+ const auto &ev = **it;
+ auto name = Name(ev);
+ code_.SetValue("KEY", name);
+ code_.SetValue("RAWKEY", ev.name);
+ code_ += "case .{{KEY}}: try container.encode(\"{{RAWKEY}}\")";
+ }
+ code_ += "}";
+ Outdent();
+ code_ += "}";
+ Outdent();
+ code_ += "}";
+ }
+
+ // MARK: - Object API
+
+ void GenerateObjectAPIExtensionHeader(std::string name) {
+ code_ += "\n";
+ code_ += "{{ACCESS_TYPE}} mutating func unpack() -> " + name + " {";
+ Indent();
+ code_ += "return " + name + "(&self)";
+ Outdent();
+ code_ += "}";
+ code_ +=
+ "{{ACCESS_TYPE}} static func pack(_ builder: inout FlatBufferBuilder, "
+ "obj: "
+ "inout " +
+ name + "?) -> Offset {";
+ Indent();
+ code_ += "guard var obj = obj else { return Offset() }";
+ code_ += "return pack(&builder, obj: &obj)";
+ Outdent();
+ code_ += "}";
+ code_ += "";
+ code_ +=
+ "{{ACCESS_TYPE}} static func pack(_ builder: inout FlatBufferBuilder, "
+ "obj: "
+ "inout " +
+ name + ") -> Offset {";
+ Indent();
+ }
+
+ void GenerateObjectAPIStructConstructor(const StructDef &struct_def) {
+ code_ +=
+ "{{ACCESS_TYPE}} init(_ _t: inout {{STRUCTNAME}}" + Mutable() + ") {";
+ Indent();
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++it) {
+ auto &field = **it;
+ if (field.deprecated) continue;
+
+ auto name = Name(field);
+ auto type = GenType(field.value.type);
+ code_.SetValue("VALUENAME", name);
+ if (IsStruct(field.value.type)) {
+ code_ += "var _v{{VALUENAME}} = _t.{{VALUENAME}}";
+ code_ += "_{{VALUENAME}} = _v{{VALUENAME}}.unpack()";
+ continue;
+ }
+ std::string is_enum = IsEnum(field.value.type) ? ".value" : "";
+ code_ += "_{{VALUENAME}} = _t.{{VALUENAME}}" + is_enum;
+ }
+ Outdent();
+ code_ += "}\n";
+ }
+
void GenObjectAPI(const StructDef &struct_def) {
code_ += "{{ACCESS_TYPE}} class " + ObjectAPIName("{{STRUCTNAME}}") +
- ": NativeTable {\n";
+ ": NativeObject {\n";
std::vector<std::string> buffer_constructor;
std::vector<std::string> base_constructor;
Indent();
@@ -892,10 +1313,9 @@
base_constructor);
}
code_ += "";
- BuildObjectAPIConstructor(
- buffer_constructor,
- "_ _t: inout " + NameWrappedInNameSpace(struct_def));
- BuildObjectAPIConstructor(base_constructor);
+ BuildObjectConstructor(buffer_constructor,
+ "_ _t: inout " + NameWrappedInNameSpace(struct_def));
+ BuildObjectConstructor(base_constructor);
if (!struct_def.fixed)
code_ +=
"{{ACCESS_TYPE}} func serialize() -> ByteBuffer { return "
@@ -906,7 +1326,7 @@
}
void GenerateObjectAPITableExtension(const StructDef &struct_def) {
- GenerateObjectAPIExtensionHeader();
+ GenerateObjectAPIExtensionHeader(ObjectAPIName("{{STRUCTNAME}}"));
std::vector<std::string> unpack_body;
std::string builder = ", &builder)";
for (auto it = struct_def.fields.vec.begin();
@@ -916,8 +1336,7 @@
auto name = Name(field);
auto type = GenType(field.value.type);
std::string check_if_vector =
- (IsVector(field.value.type) ||
- IsArray(field.value.type))
+ (IsVector(field.value.type) || IsArray(field.value.type))
? "VectorOf("
: "(";
std::string body = "add" + check_if_vector + name + ": ";
@@ -944,16 +1363,13 @@
if (field.value.type.struct_def &&
field.value.type.struct_def->fixed) {
// This is a Struct (IsStruct), not a table. We create
- // UnsafeMutableRawPointer in this case.
+ // a native swift object in this case.
std::string code;
GenerateStructArgs(*field.value.type.struct_def, &code, "", "",
"$0", true);
code = code.substr(0, code.size() - 2);
- unpack_body.push_back(
- "{{STRUCTNAME}}." + body + "obj." + name + ".map { " +
- NameWrappedInNameSpace(*field.value.type.struct_def) +
- ".create" + Name(*field.value.type.struct_def) +
- "(builder: &builder, " + code + ") }" + builder);
+ unpack_body.push_back("{{STRUCTNAME}}." + body + "obj." + name +
+ builder);
} else {
code_ += "let __" + name + " = " + type +
".pack(&builder, obj: &obj." + name + ")";
@@ -965,12 +1381,11 @@
case BASE_TYPE_STRING: {
unpack_body.push_back("{{STRUCTNAME}}." + body + "__" + name +
builder);
- if (field.required) {
+ if (field.IsRequired()) {
code_ +=
"let __" + name + " = builder.create(string: obj." + name + ")";
} else {
- BuildingOptionalObjects(name, "String",
- "builder.create(string: s)");
+ BuildingOptionalObjects(name, "builder.create(string: s)");
}
break;
}
@@ -996,7 +1411,7 @@
auto vectortype = field.value.type.VectorType();
switch (vectortype.base_type) {
case BASE_TYPE_UNION: {
- code_ += "var __" + name + "__: [Offset<UOffset>] = []";
+ code_ += "var __" + name + "__: [Offset] = []";
code_ += "for i in obj." + name + " {";
Indent();
code_ += "guard let off = i?.pack(builder: &builder) else { continue }";
@@ -1013,7 +1428,7 @@
case BASE_TYPE_STRUCT: {
if (field.value.type.struct_def &&
!field.value.type.struct_def->fixed) {
- code_ += "var __" + name + "__: [Offset<UOffset>] = []";
+ code_ += "var __" + name + "__: [Offset] = []";
code_ += "for var i in obj." + name + " {";
Indent();
code_ +=
@@ -1023,8 +1438,9 @@
code_ += "let __" + name + " = builder.createVector(ofOffsets: __" +
name + "__)";
} else {
- code_ += "{{STRUCTNAME}}.startVectorOf" + MakeCamel(name, true) +
- "(obj." + name + ".count, in: &builder)";
+ code_ += "{{STRUCTNAME}}.startVectorOf" +
+ ConvertCase(name, Case::kUpperCamel) + "(obj." + name +
+ ".count, in: &builder)";
std::string code;
GenerateStructArgs(*field.value.type.struct_def, &code, "", "", "_o",
true);
@@ -1032,13 +1448,10 @@
code_ += "for i in obj." + name + " {";
Indent();
code_ += "guard let _o = i else { continue }";
- code_ += NameWrappedInNameSpace(*field.value.type.struct_def) +
- ".create" + Name(*field.value.type.struct_def) +
- "(builder: &builder, " + code + ")";
+ code_ += "builder.create(struct: _o)";
Outdent();
code_ += "}";
- code_ += "let __" + name +
- " = builder.endVectorOfStructs(count: obj." + name +
+ code_ += "let __" + name + " = builder.endVector(len: obj." + name +
".count)";
}
break;
@@ -1056,23 +1469,22 @@
}
void BuildingOptionalObjects(const std::string &name,
- const std::string &object_type,
const std::string &body_front) {
- code_ += "let __" + name + ": Offset<" + object_type + ">";
+ code_ += "let __" + name + ": Offset";
code_ += "if let s = obj." + name + " {";
Indent();
code_ += "__" + name + " = " + body_front;
Outdent();
code_ += "} else {";
Indent();
- code_ += "__" + name + " = Offset<" + object_type + ">()";
+ code_ += "__" + name + " = Offset()";
Outdent();
code_ += "}";
code_ += "";
}
- void BuildObjectAPIConstructor(const std::vector<std::string> &body,
- const std::string &header = "") {
+ void BuildObjectConstructor(const std::vector<std::string> &body,
+ const std::string &header = "") {
code_.SetValue("HEADER", header);
code_ += "{{ACCESS_TYPE}} init({{HEADER}}) {";
Indent();
@@ -1089,24 +1501,29 @@
auto type = GenType(field.value.type);
code_.SetValue("VALUENAME", name);
code_.SetValue("VALUETYPE", type);
- std::string is_required = field.required ? "" : "?";
+ std::string is_required = field.IsRequired() ? "" : "?";
switch (field.value.type.base_type) {
case BASE_TYPE_STRUCT: {
type = GenType(field.value.type, true);
code_.SetValue("VALUETYPE", type);
- buffer_constructor.push_back("var __" + name + " = _t." + name);
auto optional =
(field.value.type.struct_def && field.value.type.struct_def->fixed);
std::string question_mark =
- (field.required || (optional && is_fixed) ? "" : "?");
+ (field.IsRequired() || (optional && is_fixed) ? "" : "?");
code_ +=
"{{ACCESS_TYPE}} var {{VALUENAME}}: {{VALUETYPE}}" + question_mark;
- buffer_constructor.push_back("" + name + " = __" + name +
- (field.required ? "!" : question_mark) +
- ".unpack()");
base_constructor.push_back("" + name + " = " + type + "()");
+
+ if (field.value.type.struct_def->fixed) {
+ buffer_constructor.push_back("" + name + " = _t." + name);
+ } else {
+ buffer_constructor.push_back("var __" + name + " = _t." + name);
+ buffer_constructor.push_back(
+ "" + name + " = __" + name +
+ (field.IsRequired() ? "!" : question_mark) + ".unpack()");
+ }
break;
}
case BASE_TYPE_ARRAY: FLATBUFFERS_FALLTHROUGH();
@@ -1118,7 +1535,17 @@
case BASE_TYPE_STRING: {
code_ += "{{ACCESS_TYPE}} var {{VALUENAME}}: String" + is_required;
buffer_constructor.push_back(name + " = _t." + name);
- if (field.required) base_constructor.push_back(name + " = \"\"");
+
+ if (field.IsRequired()) {
+ std::string default_value =
+ field.IsDefault() ? field.value.constant : "";
+ base_constructor.push_back(name + " = \"" + default_value + "\"");
+ break;
+ }
+ if (field.IsDefault() && !field.IsRequired()) {
+ std::string value = field.IsDefault() ? field.value.constant : "nil";
+ base_constructor.push_back(name + " = \"" + value + "\"");
+ }
break;
}
case BASE_TYPE_UTYPE: break;
@@ -1129,12 +1556,12 @@
}
default: {
buffer_constructor.push_back(name + " = _t." + name);
- std::string nullable = field.optional ? "?" : "";
+ std::string nullable = field.IsOptional() ? "?" : "";
if (IsScalar(field.value.type.base_type) &&
!IsBool(field.value.type.base_type) && !IsEnum(field.value.type)) {
code_ +=
"{{ACCESS_TYPE}} var {{VALUENAME}}: {{VALUETYPE}}" + nullable;
- if (!field.optional)
+ if (!field.IsOptional())
base_constructor.push_back(name + " = " + field.value.constant);
break;
}
@@ -1152,7 +1579,7 @@
code_ += "{{ACCESS_TYPE}} var {{VALUENAME}}: Bool" + nullable;
std::string default_value =
"0" == field.value.constant ? "false" : "true";
- if (!field.optional)
+ if (!field.IsOptional())
base_constructor.push_back(name + " = " + default_value);
}
}
@@ -1176,10 +1603,15 @@
case BASE_TYPE_STRUCT: {
code_.SetValue("VALUETYPE", GenType(vectortype, true));
code_ += "{{ACCESS_TYPE}} var {{VALUENAME}}: [{{VALUETYPE}}?]";
- buffer_constructor.push_back(indentation + "var __v_ = _t." + name +
- "(at: index)");
- buffer_constructor.push_back(indentation + name +
- ".append(__v_?.unpack())");
+ if (!vectortype.struct_def->fixed) {
+ buffer_constructor.push_back(indentation + "var __v_ = _t." + name +
+ "(at: index)");
+ buffer_constructor.push_back(indentation + name +
+ ".append(__v_?.unpack())");
+ } else {
+ buffer_constructor.push_back(indentation + name + ".append(_t." +
+ name + "(at: index))");
+ }
break;
}
case BASE_TYPE_ARRAY: FLATBUFFERS_FALLTHROUGH();
@@ -1193,9 +1625,9 @@
}
case BASE_TYPE_UTYPE: break;
default: {
- code_.SetValue("VALUETYPE", (IsString(vectortype)
- ? "String?"
- : GenType(vectortype)));
+ code_.SetValue(
+ "VALUETYPE",
+ (IsString(vectortype) ? "String?" : GenType(vectortype)));
code_ += "{{ACCESS_TYPE}} var {{VALUENAME}}: [{{VALUETYPE}}]";
if (IsEnum(vectortype) && vectortype.base_type != BASE_TYPE_UNION) {
@@ -1223,15 +1655,12 @@
auto field = **it;
auto ev_name = Name(field);
auto type = GenType(field.union_type);
-
- if (field.union_type.base_type == BASE_TYPE_NONE ||
- IsString(field.union_type)) {
- continue;
- }
+ auto is_struct = IsStruct(field.union_type) ? type + Mutable() : type;
+ if (field.union_type.base_type == BASE_TYPE_NONE) { continue; }
code_ += "case ." + ev_name + ":";
Indent();
code_ += "var __obj = value as? " + GenType(field.union_type, true);
- code_ += "return " + type + ".pack(&builder, obj: &__obj)";
+ code_ += "return " + is_struct + ".pack(&builder, obj: &__obj)";
Outdent();
}
code_ += "default: return Offset()";
@@ -1254,19 +1683,18 @@
for (auto it = ev.Vals().begin(); it < ev.Vals().end(); ++it) {
auto field = **it;
auto ev_name = Name(field);
- if (field.union_type.base_type == BASE_TYPE_NONE ||
- IsString(field.union_type)) {
- continue;
- }
+ if (field.union_type.base_type == BASE_TYPE_NONE) { continue; }
+ auto type = IsStruct(field.union_type)
+ ? GenType(field.union_type) + Mutable()
+ : GenType(field.union_type);
buffer_constructor.push_back(indentation + "case ." + ev_name + ":");
buffer_constructor.push_back(
- indentation + " var _v = _t." + name + (is_vector ? "" : "(") +
- vector_reader + (is_vector ? ", " : "") +
- "type: " + GenType(field.union_type) + ".self)");
+ indentation + " var _v = _t." + name + (is_vector ? "" : "(") +
+ vector_reader + (is_vector ? ", " : "") + "type: " + type + ".self)");
auto constructor =
field_name + "Union(_v?.unpack(), type: ." + ev_name + ")";
buffer_constructor.push_back(
- indentation + " " + name +
+ indentation + " " + name +
(is_vector ? ".append(" + constructor + ")" : " = " + constructor));
}
buffer_constructor.push_back(indentation + "default: break");
@@ -1330,6 +1758,19 @@
code_ += "}";
}
+ inline void GenPadding(const FieldDef &field, int *id) {
+ if (field.padding) {
+ for (int i = 0; i < 4; i++) {
+ if (static_cast<int>(field.padding) & (1 << i)) {
+ auto bits = (1 << i) * 8;
+ code_ += "private let padding" + NumToString((*id)++) + "__: UInt" +
+ NumToString(bits) + " = 0";
+ }
+ }
+ FLATBUFFERS_ASSERT(!(field.padding & ~0xF));
+ }
+ }
+
void GenComment(const std::vector<std::string> &dc) {
if (dc.begin() == dc.end()) {
// Don't output empty comment blocks with 0 lines of comment content.
@@ -1377,7 +1818,9 @@
auto &value = field.value;
FLATBUFFERS_ASSERT(value.type.enum_def);
auto &enum_def = *value.type.enum_def;
- auto enum_val = enum_def.FindByValue(value.constant);
+ // Vector of enum defaults are always "[]" which never works.
+ const std::string constant = IsVector(value.type) ? "0" : value.constant;
+ auto enum_val = enum_def.FindByValue(constant);
std::string name;
if (enum_val) {
name = Name(*enum_val);
@@ -1393,7 +1836,7 @@
}
std::string ValidateFunc() {
- return "static func validateVersion() { FlatBuffersVersion_1_12_0() }";
+ return "static func validateVersion() { FlatBuffersVersion_2_0_0() }";
}
std::string GenType(const Type &type,
@@ -1411,14 +1854,14 @@
case BASE_TYPE_VECTOR: return GenType(type.VectorType());
case BASE_TYPE_STRUCT: {
auto &struct_ = *type.struct_def;
- if (should_consider_suffix) {
+ if (should_consider_suffix && !struct_.fixed) {
return WrapInNameSpace(struct_.defined_namespace,
ObjectAPIName(Name(struct_)));
}
return WrapInNameSpace(struct_.defined_namespace, Name(struct_));
}
case BASE_TYPE_UNION:
- default: return "FlatBufferObject";
+ default: return "FlatbuffersInitializable";
}
}
@@ -1463,16 +1906,18 @@
return keywords_.find(name) == keywords_.end() ? name : name + "_";
}
+ std::string Mutable() const { return "_Mutable"; }
+
std::string Name(const EnumVal &ev) const {
auto name = ev.name;
if (isupper(name.front())) {
std::transform(name.begin(), name.end(), name.begin(), CharToLower);
}
- return EscapeKeyword(MakeCamel(name, false));
+ return EscapeKeyword(ConvertCase(name, Case::kLowerCamel));
}
std::string Name(const Definition &def) const {
- return EscapeKeyword(MakeCamel(def.name, false));
+ return EscapeKeyword(ConvertCase(def.name, Case::kLowerCamel));
}
};
} // namespace swift
diff --git a/src/idl_gen_text.cpp b/src/idl_gen_text.cpp
index e4d2182..805e934 100644
--- a/src/idl_gen_text.cpp
+++ b/src/idl_gen_text.cpp
@@ -264,12 +264,18 @@
FLATBUFFERS_ASSERT(IsStruct(fd.value.type) || IsArray(fd.value.type));
val = reinterpret_cast<const Struct *>(table)->GetStruct<const void *>(
fd.value.offset);
- } else if (fd.flexbuffer) {
+ } else if (fd.flexbuffer && opts.json_nested_flexbuffers) {
+ // We could verify this FlexBuffer before access, but since this sits
+ // inside a FlatBuffer that we don't know wether it has been verified or
+ // not, there is little point making this part safer than the parent..
+ // The caller should really be verifying the whole.
+ // If the whole buffer is corrupt, we likely crash before we even get
+ // here.
auto vec = table->GetPointer<const Vector<uint8_t> *>(fd.value.offset);
auto root = flexbuffers::GetRoot(vec->data(), vec->size());
root.ToString(true, opts.strict_json, text);
return true;
- } else if (fd.nested_flatbuffer) {
+ } else if (fd.nested_flatbuffer && opts.json_nested_flatbuffers) {
auto vec = table->GetPointer<const Vector<uint8_t> *>(fd.value.offset);
auto root = GetRoot<Table>(vec->data());
return GenStruct(*fd.nested_flatbuffer, root, indent);
@@ -292,7 +298,7 @@
it != struct_def.fields.vec.end(); ++it) {
FieldDef &fd = **it;
auto is_present = struct_def.fixed || table->CheckField(fd.value.offset);
- auto output_anyway = opts.output_default_scalars_in_json &&
+ auto output_anyway = (opts.output_default_scalars_in_json || fd.key) &&
IsScalar(fd.value.type.base_type) && !fd.deprecated;
if (is_present || output_anyway) {
if (fieldout++) { AddComma(); }
diff --git a/src/idl_gen_ts.cpp b/src/idl_gen_ts.cpp
new file mode 100644
index 0000000..faf4345
--- /dev/null
+++ b/src/idl_gen_ts.cpp
@@ -0,0 +1,1828 @@
+/*
+ * Copyright 2014 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.
+ */
+
+// independent from idl_parser, since this code is not needed for most clients
+#include <algorithm>
+#include <cassert>
+#include <unordered_map>
+#include <unordered_set>
+
+#include "flatbuffers/code_generators.h"
+#include "flatbuffers/flatbuffers.h"
+#include "flatbuffers/idl.h"
+#include "flatbuffers/util.h"
+
+namespace flatbuffers {
+
+struct ImportDefinition {
+ std::string name;
+ std::string import_statement;
+ std::string export_statement;
+ std::string bare_file_path;
+ std::string rel_file_path;
+ const Definition *dependent = nullptr;
+ const Definition *dependency = nullptr;
+};
+
+enum AnnotationType { kParam = 0, kType = 1, kReturns = 2 };
+
+namespace ts {
+// Iterate through all definitions we haven't generate code for (enums, structs,
+// and tables) and output them to a single file.
+class TsGenerator : public BaseGenerator {
+ public:
+ typedef std::map<std::string, ImportDefinition> import_set;
+
+ TsGenerator(const Parser &parser, const std::string &path,
+ const std::string &file_name)
+ : BaseGenerator(parser, path, file_name, "", ".", "ts") {
+ // clang-format off
+
+ // List of keywords retrieved from here:
+ // https://github.com/microsoft/TypeScript/issues/2536
+ // One per line to ease comparisons to that list are easier
+ static const char *const keywords[] = {
+ "argument",
+ "break",
+ "case",
+ "catch",
+ "class",
+ "const",
+ "continue",
+ "debugger",
+ "default",
+ "delete",
+ "do",
+ "else",
+ "enum",
+ "export",
+ "extends",
+ "false",
+ "finally",
+ "for",
+ "function",
+ "if",
+ "import",
+ "in",
+ "instanceof",
+ "new",
+ "null",
+ "Object",
+ "return",
+ "super",
+ "switch",
+ "this",
+ "throw",
+ "true",
+ "try",
+ "typeof",
+ "var",
+ "void",
+ "while",
+ "with",
+ "as",
+ "implements",
+ "interface",
+ "let",
+ "package",
+ "private",
+ "protected",
+ "public",
+ "static",
+ "yield",
+ nullptr,
+ // clang-format on
+ };
+
+ for (auto kw = keywords; *kw; kw++) keywords_.insert(*kw);
+ }
+ bool generate() {
+ if (parser_.opts.ts_flat_file && parser_.opts.generate_all) {
+ // Not implemented; warning message should have beem emitted by flatc.
+ return false;
+ }
+ generateEnums();
+ generateStructs();
+ generateEntry();
+ return true;
+ }
+
+ // Save out the generated code for a single class while adding
+ // declaration boilerplate.
+ bool SaveType(const Definition &definition, const std::string &classcode,
+ import_set &imports, import_set &bare_imports) {
+ if (!classcode.length()) return true;
+
+ std::string code;
+
+ if (!parser_.opts.ts_flat_file) {
+ code += "// " + std::string(FlatBuffersGeneratedWarning()) + "\n\n";
+
+ for (auto it = bare_imports.begin(); it != bare_imports.end(); it++) {
+ code += it->second.import_statement + "\n";
+ }
+ if (!bare_imports.empty()) code += "\n";
+
+ for (auto it = imports.begin(); it != imports.end(); it++) {
+ if (it->second.dependency != &definition) {
+ code += it->second.import_statement + "\n";
+ }
+ }
+ if (!imports.empty()) code += "\n\n";
+ }
+
+ code += classcode;
+ auto filename =
+ NamespaceDir(*definition.defined_namespace, true) +
+ ConvertCase(definition.name, Case::kDasher, Case::kUpperCamel) + ".ts";
+ if (parser_.opts.ts_flat_file) {
+ flat_file_ += code;
+ flat_file_definitions_.insert(&definition);
+ return true;
+ } else {
+ return SaveFile(filename.c_str(), code, false);
+ }
+ }
+
+ private:
+ std::unordered_set<std::string> keywords_;
+
+ std::string EscapeKeyword(const std::string &name) const {
+ return keywords_.find(name) == keywords_.end() ? name : name + "_";
+ }
+
+ import_set imports_all_;
+
+ // The following three members are used when generating typescript code into a
+ // single file rather than creating separate files for each type.
+
+ // flat_file_ contains the aggregated contents of the file prior to being
+ // written to disk.
+ std::string flat_file_;
+ // flat_file_definitions_ tracks which types have been written to flat_file_.
+ std::unordered_set<const Definition *> flat_file_definitions_;
+ // This maps from import names to types to import.
+ std::map<std::string, std::map<std::string, std::string>>
+ flat_file_import_declarations_;
+
+ // Generate code for all enums.
+ void generateEnums() {
+ for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end();
+ ++it) {
+ import_set bare_imports;
+ import_set imports;
+ std::string enumcode;
+ auto &enum_def = **it;
+ GenEnum(enum_def, &enumcode, imports, false);
+ GenEnum(enum_def, &enumcode, imports, true);
+ SaveType(enum_def, enumcode, imports, bare_imports);
+ imports_all_.insert(imports.begin(), imports.end());
+ }
+ }
+
+ // Generate code for all structs.
+ void generateStructs() {
+ for (auto it = parser_.structs_.vec.begin();
+ it != parser_.structs_.vec.end(); ++it) {
+ import_set bare_imports;
+ import_set imports;
+ AddImport(bare_imports, "* as flatbuffers", "flatbuffers");
+ auto &struct_def = **it;
+ std::string declcode;
+ GenStruct(parser_, struct_def, &declcode, imports);
+ SaveType(struct_def, declcode, imports, bare_imports);
+ imports_all_.insert(imports.begin(), imports.end());
+ }
+ }
+
+ // Generate code for a single entry point module.
+ void generateEntry() {
+ std::string code;
+ if (parser_.opts.ts_flat_file) {
+ code += "import * as flatbuffers from 'flatbuffers';\n";
+ for (const auto &it : flat_file_import_declarations_) {
+ // Note that we do end up generating an import for ourselves, which
+ // should generally be harmless.
+ // TODO: Make it so we don't generate a self-import; this will also
+ // require modifying AddImport to ensure that we don't use
+ // namespace-prefixed names anywhere...
+ std::string file = it.first;
+ if (file.empty()) {
+ continue;
+ }
+ std::string noext = flatbuffers::StripExtension(file);
+ std::string basename = flatbuffers::StripPath(noext);
+ std::string include_file = GeneratedFileName(
+ parser_.opts.include_prefix,
+ parser_.opts.keep_include_path ? noext : basename, parser_.opts);
+ // TODO: what is the right behavior when different include flags are
+ // specified here? Should we always be adding the "./" for a relative
+ // path or turn it off if --include-prefix is specified, or something
+ // else?
+ std::string include_name = "./" + flatbuffers::StripExtension(include_file);
+ code += "import {";
+ for (const auto &pair : it.second) {
+ code += EscapeKeyword(pair.first) + " as " +
+ EscapeKeyword(pair.second) + ", ";
+ }
+ code.resize(code.size() - 2);
+ code += "} from '" + include_name + "';\n";
+ }
+ code += "\n\n";
+ code += flat_file_;
+ const std::string filename =
+ GeneratedFileName(path_, file_name_, parser_.opts);
+ SaveFile(filename.c_str(), code, false);
+ } else {
+ for (auto it = imports_all_.begin(); it != imports_all_.end(); it++) {
+ code += it->second.export_statement + "\n";
+ }
+ std::string path = "./" + path_ + file_name_ + ".ts";
+ SaveFile(path.c_str(), code, false);
+ }
+ }
+
+ // Generate a documentation comment, if available.
+ static void GenDocComment(const std::vector<std::string> &dc,
+ std::string *code_ptr,
+ const char *indent = nullptr) {
+ if (dc.empty()) {
+ // Don't output empty comment blocks with 0 lines of comment content.
+ return;
+ }
+
+ std::string &code = *code_ptr;
+ if (indent) code += indent;
+ code += "/**\n";
+ for (auto it = dc.begin(); it != dc.end(); ++it) {
+ if (indent) code += indent;
+ code += " *" + *it + "\n";
+ }
+ if (indent) code += indent;
+ code += " */\n";
+ }
+
+ static void GenDocComment(std::string *code_ptr) {
+ GenDocComment(std::vector<std::string>(), code_ptr);
+ }
+
+ // Generate an enum declaration and an enum string lookup table.
+ void GenEnum(EnumDef &enum_def, std::string *code_ptr, import_set &imports,
+ bool reverse) {
+ if (enum_def.generated) return;
+ if (reverse) return; // FIXME.
+ std::string &code = *code_ptr;
+ GenDocComment(enum_def.doc_comment, code_ptr);
+ code += "export enum " + EscapeKeyword(enum_def.name) + "{\n";
+ for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
+ auto &ev = **it;
+ if (!ev.doc_comment.empty()) {
+ if (it != enum_def.Vals().begin()) { code += '\n'; }
+ GenDocComment(ev.doc_comment, code_ptr, " ");
+ }
+
+ const std::string escaped_name = EscapeKeyword(ev.name);
+
+ // Generate mapping between EnumName: EnumValue(int)
+ if (reverse) {
+ code += " '" + enum_def.ToString(ev) + "'";
+ code += " = ";
+ code += "'" + escaped_name + "'";
+ } else {
+ code += " " + escaped_name;
+ code += " = ";
+ // Unfortunately, because typescript does not support bigint enums,
+ // for 64-bit enums, we instead map the enum names to strings.
+ switch (enum_def.underlying_type.base_type) {
+ case BASE_TYPE_LONG:
+ case BASE_TYPE_ULONG: {
+ code += "'" + enum_def.ToString(ev) + "'";
+ break;
+ }
+ default: code += enum_def.ToString(ev);
+ }
+ }
+
+ code += (it + 1) != enum_def.Vals().end() ? ",\n" : "\n";
+ }
+ code += "}";
+
+ if (enum_def.is_union) {
+ code += GenUnionConvFunc(enum_def.underlying_type, imports);
+ }
+
+ code += "\n\n";
+ }
+
+ static std::string GenType(const Type &type) {
+ switch (type.base_type) {
+ case BASE_TYPE_BOOL:
+ case BASE_TYPE_CHAR: return "Int8";
+ case BASE_TYPE_UTYPE:
+ case BASE_TYPE_UCHAR: return "Uint8";
+ case BASE_TYPE_SHORT: return "Int16";
+ case BASE_TYPE_USHORT: return "Uint16";
+ case BASE_TYPE_INT: return "Int32";
+ case BASE_TYPE_UINT: return "Uint32";
+ case BASE_TYPE_LONG: return "Int64";
+ case BASE_TYPE_ULONG: return "Uint64";
+ case BASE_TYPE_FLOAT: return "Float32";
+ case BASE_TYPE_DOUBLE: return "Float64";
+ case BASE_TYPE_STRING: return "String";
+ case BASE_TYPE_VECTOR: return GenType(type.VectorType());
+ case BASE_TYPE_STRUCT: return type.struct_def->name;
+ default: return "flatbuffers.Table";
+ }
+ }
+
+ std::string GenGetter(const Type &type, const std::string &arguments) {
+ switch (type.base_type) {
+ case BASE_TYPE_STRING: return GenBBAccess() + ".__string" + arguments;
+ case BASE_TYPE_STRUCT: return GenBBAccess() + ".__struct" + arguments;
+ case BASE_TYPE_UNION:
+ if (!UnionHasStringType(*type.enum_def)) {
+ return GenBBAccess() + ".__union" + arguments;
+ }
+ return GenBBAccess() + ".__union_with_string" + arguments;
+ case BASE_TYPE_VECTOR: return GenGetter(type.VectorType(), arguments);
+ default: {
+ auto getter = GenBBAccess() + ".read" +
+ ConvertCase(GenType(type), Case::kUpperCamel) + arguments;
+ if (type.base_type == BASE_TYPE_BOOL) { getter = "!!" + getter; }
+ return getter;
+ }
+ }
+ }
+
+ std::string GenBBAccess() const { return "this.bb!"; }
+
+ std::string GenDefaultValue(const FieldDef &field, import_set &imports) {
+ if (field.IsScalarOptional()) { return "null"; }
+
+ const auto &value = field.value;
+ if (value.type.enum_def && value.type.base_type != BASE_TYPE_UNION &&
+ value.type.base_type != BASE_TYPE_VECTOR) {
+ // If the value is an enum with a 64-bit base type, we have to just
+ // return the bigint value directly since typescript does not support
+ // enums with bigint backing types.
+ switch (value.type.base_type) {
+ case BASE_TYPE_LONG:
+ case BASE_TYPE_ULONG: {
+ return "BigInt('" + value.constant + "')";
+ }
+ default: {
+ if (auto val = value.type.enum_def->FindByValue(value.constant)) {
+ return EscapeKeyword(AddImport(imports, *value.type.enum_def,
+ *value.type.enum_def)) +
+ "." + EscapeKeyword(val->name);
+ } else {
+ return value.constant;
+ }
+ }
+ }
+ }
+
+ switch (value.type.base_type) {
+ case BASE_TYPE_BOOL: return value.constant == "0" ? "false" : "true";
+
+ case BASE_TYPE_STRING:
+ case BASE_TYPE_UNION:
+ case BASE_TYPE_STRUCT: {
+ return "null";
+ }
+
+ case BASE_TYPE_VECTOR: return "[]";
+
+ case BASE_TYPE_LONG:
+ case BASE_TYPE_ULONG: {
+ return "BigInt('" + value.constant + "')";
+ }
+
+ default: return value.constant;
+ }
+ }
+
+ std::string GenTypeName(import_set &imports, const Definition &owner,
+ const Type &type, bool input,
+ bool allowNull = false) {
+ if (!input) {
+ if (IsString(type) || type.base_type == BASE_TYPE_STRUCT) {
+ std::string name;
+ if (IsString(type)) {
+ name = "string|Uint8Array";
+ } else {
+ name = EscapeKeyword(AddImport(imports, owner, *type.struct_def));
+ }
+ return allowNull ? (name + "|null") : name;
+ }
+ }
+
+ switch (type.base_type) {
+ case BASE_TYPE_BOOL: return allowNull ? "boolean|null" : "boolean";
+ case BASE_TYPE_LONG:
+ case BASE_TYPE_ULONG: return allowNull ? "bigint|null" : "bigint";
+ default:
+ if (IsScalar(type.base_type)) {
+ if (type.enum_def) {
+ const auto enum_name = AddImport(imports, owner, *type.enum_def);
+ return allowNull ? (enum_name + "|null") : enum_name;
+ }
+ return allowNull ? "number|null" : "number";
+ }
+ return "flatbuffers.Offset";
+ }
+ }
+
+ // Returns the method name for use with add/put calls.
+ static std::string GenWriteMethod(const Type &type) {
+ // Forward to signed versions since unsigned versions don't exist
+ switch (type.base_type) {
+ case BASE_TYPE_UTYPE:
+ case BASE_TYPE_UCHAR: return GenWriteMethod(Type(BASE_TYPE_CHAR));
+ case BASE_TYPE_USHORT: return GenWriteMethod(Type(BASE_TYPE_SHORT));
+ case BASE_TYPE_UINT: return GenWriteMethod(Type(BASE_TYPE_INT));
+ case BASE_TYPE_ULONG: return GenWriteMethod(Type(BASE_TYPE_LONG));
+ default: break;
+ }
+
+ return IsScalar(type.base_type)
+ ? ConvertCase(GenType(type), Case::kUpperCamel)
+ : (IsStruct(type) ? "Struct" : "Offset");
+ }
+
+ template<typename T> static std::string MaybeAdd(T value) {
+ return value != 0 ? " + " + NumToString(value) : "";
+ }
+
+ template<typename T> static std::string MaybeScale(T value) {
+ return value != 1 ? " * " + NumToString(value) : "";
+ }
+
+ void GenStructArgs(import_set &imports, const StructDef &struct_def,
+ std::string *arguments, const std::string &nameprefix) {
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++it) {
+ auto &field = **it;
+ if (IsStruct(field.value.type)) {
+ // Generate arguments for a struct inside a struct. To ensure names
+ // don't clash, and to make it obvious these arguments are constructing
+ // a nested struct, prefix the name with the field name.
+ GenStructArgs(imports, *field.value.type.struct_def, arguments,
+ nameprefix + field.name + "_");
+ } else {
+ *arguments += ", " + nameprefix + field.name + ": " +
+ GenTypeName(imports, field, field.value.type, true,
+ field.IsOptional());
+ }
+ }
+ }
+
+ static void GenStructBody(const StructDef &struct_def, std::string *body,
+ const std::string &nameprefix) {
+ *body += " builder.prep(";
+ *body += NumToString(struct_def.minalign) + ", ";
+ *body += NumToString(struct_def.bytesize) + ");\n";
+
+ for (auto it = struct_def.fields.vec.rbegin();
+ it != struct_def.fields.vec.rend(); ++it) {
+ auto &field = **it;
+ if (field.padding) {
+ *body += " builder.pad(" + NumToString(field.padding) + ");\n";
+ }
+ if (IsStruct(field.value.type)) {
+ // Generate arguments for a struct inside a struct. To ensure names
+ // don't clash, and to make it obvious these arguments are constructing
+ // a nested struct, prefix the name with the field name.
+ GenStructBody(*field.value.type.struct_def, body,
+ nameprefix + field.name + "_");
+ } else {
+ *body += " builder.write" + GenWriteMethod(field.value.type) + "(";
+ if (field.value.type.base_type == BASE_TYPE_BOOL) { *body += "+"; }
+ *body += nameprefix + field.name + ");\n";
+ }
+ }
+ }
+
+ std::string GenerateNewExpression(const std::string &object_name) {
+ return "new " + EscapeKeyword(object_name) + "()";
+ }
+
+ void GenerateRootAccessor(StructDef &struct_def, std::string *code_ptr,
+ std::string &code, const std::string &object_name,
+ bool size_prefixed) {
+ if (!struct_def.fixed) {
+ GenDocComment(code_ptr);
+ std::string sizePrefixed("SizePrefixed");
+ code += "static get" + (size_prefixed ? sizePrefixed : "") + "Root" +
+ GetPrefixedName(struct_def, "As");
+ code += "(bb:flatbuffers.ByteBuffer, obj?:" + object_name +
+ "):" + object_name + " {\n";
+ if (size_prefixed) {
+ code +=
+ " bb.setPosition(bb.position() + "
+ "flatbuffers.SIZE_PREFIX_LENGTH);\n";
+ }
+ code += " return (obj || " + GenerateNewExpression(object_name);
+ code += ").__init(bb.readInt32(bb.position()) + bb.position(), bb);\n";
+ code += "}\n\n";
+ }
+ }
+
+ void GenerateFinisher(StructDef &struct_def, std::string *code_ptr,
+ std::string &code, bool size_prefixed) {
+ if (parser_.root_struct_def_ == &struct_def) {
+ std::string sizePrefixed("SizePrefixed");
+ GenDocComment(code_ptr);
+
+ code += "static finish" + (size_prefixed ? sizePrefixed : "") +
+ GetPrefixedName(struct_def) + "Buffer";
+ code += "(builder:flatbuffers.Builder, offset:flatbuffers.Offset) {\n";
+ code += " builder.finish(offset";
+ if (!parser_.file_identifier_.empty()) {
+ code += ", '" + parser_.file_identifier_ + "'";
+ }
+ if (size_prefixed) {
+ if (parser_.file_identifier_.empty()) { code += ", undefined"; }
+ code += ", true";
+ }
+ code += ");\n";
+ code += "}\n\n";
+ }
+ }
+
+ static std::string GetObjApiClassName(const StructDef &sd,
+ const IDLOptions &opts) {
+ return GetObjApiClassName(sd.name, opts);
+ }
+
+ static std::string GetObjApiClassName(const std::string &name,
+ const IDLOptions &opts) {
+ return opts.object_prefix + name + opts.object_suffix;
+ }
+
+ bool UnionHasStringType(const EnumDef &union_enum) {
+ return std::any_of(union_enum.Vals().begin(), union_enum.Vals().end(),
+ [](const EnumVal *ev) {
+ return !ev->IsZero() && IsString(ev->union_type);
+ });
+ }
+
+ std::string GenUnionGenericTypeTS(const EnumDef &union_enum) {
+ // TODO: make it work without any
+ // return std::string("T") + (UnionHasStringType(union_enum) ? "|string" :
+ // "");
+ return std::string("any") +
+ (UnionHasStringType(union_enum) ? "|string" : "");
+ }
+
+ std::string GenUnionTypeTS(const EnumDef &union_enum, import_set &imports) {
+ std::string ret;
+ std::set<std::string> type_list;
+
+ for (auto it = union_enum.Vals().begin(); it != union_enum.Vals().end();
+ ++it) {
+ const auto &ev = **it;
+ if (ev.IsZero()) { continue; }
+
+ std::string type = "";
+ if (IsString(ev.union_type)) {
+ type = "string"; // no need to wrap string type in namespace
+ } else if (ev.union_type.base_type == BASE_TYPE_STRUCT) {
+ type = AddImport(imports, union_enum, *ev.union_type.struct_def);
+ } else {
+ FLATBUFFERS_ASSERT(false);
+ }
+ type_list.insert(type);
+ }
+
+ for (auto it = type_list.begin(); it != type_list.end(); ++it) {
+ ret += *it + ((std::next(it) == type_list.end()) ? "" : "|");
+ }
+
+ return ret;
+ }
+
+ std::string AddImport(import_set &imports, const Definition &dependent,
+ const StructDef &dependency) {
+ std::string ns;
+ const auto &depc_comps = dependency.defined_namespace->components;
+ for (auto it = depc_comps.begin(); it != depc_comps.end(); it++) {
+ ns += *it;
+ }
+ std::string unique_name = ns + dependency.name;
+ std::string import_name = dependency.name;
+ std::string long_import_name;
+ if (imports.find(unique_name) != imports.end())
+ return imports.find(unique_name)->second.name;
+ for (auto it = imports.begin(); it != imports.end(); it++) {
+ if (it->second.name == import_name) {
+ long_import_name = ns + import_name;
+ break;
+ }
+ }
+
+ if (parser_.opts.ts_flat_file) {
+ std::string file = dependency.declaration_file == nullptr
+ ? dependency.file
+ : dependency.declaration_file->substr(2);
+ file = RelativeToRootPath(StripFileName(AbsolutePath(dependent.file)),
+ dependency.file).substr(2);
+ long_import_name = ns + import_name;
+ flat_file_import_declarations_[file][import_name] = long_import_name;
+ if (parser_.opts.generate_object_based_api) {
+ flat_file_import_declarations_[file][import_name + "T"] = long_import_name + "T";
+ }
+ }
+
+ std::string import_statement;
+ std::string export_statement;
+ import_statement += "import { ";
+ export_statement += "export { ";
+ std::string symbols_expression;
+ if (long_import_name.empty()) {
+ symbols_expression += EscapeKeyword(import_name);
+ if (parser_.opts.generate_object_based_api)
+ symbols_expression += ", " + import_name + "T";
+ } else {
+ symbols_expression += EscapeKeyword(dependency.name) + " as " +
+ EscapeKeyword(long_import_name);
+ if (parser_.opts.generate_object_based_api)
+ symbols_expression +=
+ ", " + dependency.name + "T as " + long_import_name + "T";
+ }
+ import_statement += symbols_expression + " } from '";
+ export_statement += symbols_expression + " } from '";
+ std::string bare_file_path;
+ std::string rel_file_path;
+ const auto &dep_comps = dependent.defined_namespace->components;
+ for (size_t i = 0; i < dep_comps.size(); i++)
+ rel_file_path += i == 0 ? ".." : (kPathSeparator + std::string(".."));
+ if (dep_comps.size() == 0) rel_file_path += ".";
+ for (auto it = depc_comps.begin(); it != depc_comps.end(); it++)
+ bare_file_path +=
+ kPathSeparator + ConvertCase(*it, Case::kDasher, Case::kUpperCamel);
+ bare_file_path +=
+ kPathSeparator +
+ ConvertCase(dependency.name, Case::kDasher, Case::kUpperCamel);
+ rel_file_path += bare_file_path;
+ import_statement += rel_file_path + "';";
+ export_statement += "." + bare_file_path + "';";
+ ImportDefinition import;
+ import.name = long_import_name.empty() ? import_name : long_import_name;
+ import.bare_file_path = bare_file_path;
+ import.rel_file_path = rel_file_path;
+ import.import_statement = import_statement;
+ import.export_statement = export_statement;
+ import.dependency = &dependency;
+ import.dependent = &dependent;
+ imports.insert(std::make_pair(unique_name, import));
+ return import.name;
+ }
+
+ // TODO: largely (but not identical) duplicated code from above couln't find a
+ // good way to refactor
+ std::string AddImport(import_set &imports, const Definition &dependent,
+ const EnumDef &dependency) {
+ std::string ns;
+ const auto &depc_comps = dependency.defined_namespace->components;
+ for (auto it = depc_comps.begin(); it != depc_comps.end(); it++) {
+ ns += *it;
+ }
+ std::string unique_name = ns + dependency.name;
+ std::string import_name = EscapeKeyword(dependency.name);
+ std::string long_import_name;
+ if (imports.find(unique_name) != imports.end()) {
+ return imports.find(unique_name)->second.name;
+ }
+ for (auto it = imports.begin(); it != imports.end(); it++) {
+ if (it->second.name == import_name) {
+ long_import_name = ns + import_name;
+ break;
+ }
+ }
+
+ if (parser_.opts.ts_flat_file) {
+ std::string file = dependency.declaration_file == nullptr
+ ? dependency.file
+ : dependency.declaration_file->substr(2);
+ file = RelativeToRootPath(StripFileName(AbsolutePath(dependent.file)),
+ dependency.file).substr(2);
+ long_import_name = ns + import_name;
+ flat_file_import_declarations_[file][import_name] = long_import_name;
+ }
+
+ std::string import_statement;
+ std::string export_statement;
+ import_statement += "import { ";
+ export_statement += "export { ";
+ std::string symbols_expression;
+ if (long_import_name.empty())
+ symbols_expression += import_name;
+ else
+ symbols_expression += EscapeKeyword(dependency.name) + " as " +
+ EscapeKeyword(long_import_name);
+ if (dependency.is_union) {
+ symbols_expression += ", unionTo" + import_name;
+ symbols_expression += ", unionListTo" + import_name;
+ }
+ import_statement += symbols_expression + " } from '";
+ export_statement += symbols_expression + " } from '";
+ std::string bare_file_path;
+ std::string rel_file_path;
+ const auto &dep_comps = dependent.defined_namespace->components;
+ for (size_t i = 0; i < dep_comps.size(); i++)
+ rel_file_path += i == 0 ? ".." : (kPathSeparator + std::string(".."));
+ if (dep_comps.size() == 0) rel_file_path += ".";
+ for (auto it = depc_comps.begin(); it != depc_comps.end(); it++)
+ bare_file_path +=
+ kPathSeparator + ConvertCase(*it, Case::kDasher, Case::kUpperCamel);
+ bare_file_path +=
+ kPathSeparator +
+ ConvertCase(dependency.name, Case::kDasher, Case::kUpperCamel);
+ rel_file_path += bare_file_path;
+ import_statement += rel_file_path + "';";
+ export_statement += "." + bare_file_path + "';";
+ ImportDefinition import;
+ import.name = long_import_name.empty() ? import_name : long_import_name;
+ import.bare_file_path = bare_file_path;
+ import.rel_file_path = rel_file_path;
+ import.import_statement = import_statement;
+ import.export_statement = export_statement;
+ import.dependency = &dependency;
+ import.dependent = &dependent;
+ imports.insert(std::make_pair(unique_name, import));
+ return import.name;
+ }
+
+ void AddImport(import_set &imports, std::string import_name,
+ std::string fileName) {
+ ImportDefinition import;
+ import.name = import_name;
+ import.import_statement =
+ "import " + import_name + " from '" + fileName + "';";
+ imports.insert(std::make_pair(import_name, import));
+ }
+
+ // Generate a TS union type based on a union's enum
+ std::string GenObjApiUnionTypeTS(import_set &imports, const IDLOptions &opts,
+ const EnumDef &union_enum) {
+ std::string ret = "";
+ std::set<std::string> type_list;
+
+ for (auto it = union_enum.Vals().begin(); it != union_enum.Vals().end();
+ ++it) {
+ const auto &ev = **it;
+ if (ev.IsZero()) { continue; }
+
+ std::string type = "";
+ if (IsString(ev.union_type)) {
+ type = "string"; // no need to wrap string type in namespace
+ } else if (ev.union_type.base_type == BASE_TYPE_STRUCT) {
+ type = GetObjApiClassName(
+ AddImport(imports, union_enum, *ev.union_type.struct_def), opts);
+ } else {
+ FLATBUFFERS_ASSERT(false);
+ }
+ type_list.insert(type);
+ }
+
+ size_t totalPrinted = 0;
+ for (auto it = type_list.begin(); it != type_list.end(); ++it) {
+ ++totalPrinted;
+ ret += *it + ((totalPrinted == type_list.size()) ? "" : "|");
+ }
+
+ return ret;
+ }
+
+ std::string GenUnionConvFuncName(const EnumDef &enum_def) {
+ return "unionTo" + enum_def.name;
+ }
+
+ std::string GenUnionListConvFuncName(const EnumDef &enum_def) {
+ return "unionListTo" + enum_def.name;
+ }
+
+ std::string GenUnionConvFunc(const Type &union_type, import_set &imports) {
+ if (union_type.enum_def) {
+ const auto &enum_def = *union_type.enum_def;
+
+ const auto valid_union_type = GenUnionTypeTS(enum_def, imports);
+ const auto valid_union_type_with_null = valid_union_type + "|null";
+
+ auto ret = "\n\nexport function " + GenUnionConvFuncName(enum_def) +
+ "(\n type: " + enum_def.name +
+ ",\n accessor: (obj:" + valid_union_type + ") => " +
+ valid_union_type_with_null +
+ "\n): " + valid_union_type_with_null + " {\n";
+
+ const auto enum_type = AddImport(imports, enum_def, enum_def);
+
+ const auto union_enum_loop = [&](const std::string &accessor_str) {
+ ret += " switch(" + enum_type + "[type]) {\n";
+ ret += " case 'NONE': return null; \n";
+
+ for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end();
+ ++it) {
+ const auto &ev = **it;
+ if (ev.IsZero()) { continue; }
+
+ ret += " case '" + ev.name + "': ";
+
+ if (IsString(ev.union_type)) {
+ ret += "return " + accessor_str + "'') as string;";
+ } else if (ev.union_type.base_type == BASE_TYPE_STRUCT) {
+ const auto type =
+ AddImport(imports, enum_def, *ev.union_type.struct_def);
+ ret += "return " + accessor_str + "new " + type + "())! as " +
+ type + ";";
+ } else {
+ FLATBUFFERS_ASSERT(false);
+ }
+ ret += "\n";
+ }
+
+ ret += " default: return null;\n";
+ ret += " }\n";
+ };
+
+ union_enum_loop("accessor(");
+ ret += "}";
+
+ ret += "\n\nexport function " + GenUnionListConvFuncName(enum_def) +
+ "(\n type: " + enum_def.name +
+ ", \n accessor: (index: number, obj:" + valid_union_type +
+ ") => " + valid_union_type_with_null +
+ ", \n index: number\n): " + valid_union_type_with_null + " {\n";
+ union_enum_loop("accessor(index, ");
+ ret += "}";
+
+ return ret;
+ }
+ FLATBUFFERS_ASSERT(0);
+ return "";
+ }
+
+ // Used for generating a short function that returns the correct class
+ // based on union enum type. Assume the context is inside the non object api
+ // type
+ std::string GenUnionValTS(import_set &imports, const std::string &field_name,
+ const Type &union_type,
+ const bool is_array = false) {
+ if (union_type.enum_def) {
+ const auto &enum_def = *union_type.enum_def;
+ const auto enum_type = AddImport(imports, enum_def, enum_def);
+ const std::string union_accessor = "this." + field_name;
+
+ const auto union_has_string = UnionHasStringType(enum_def);
+ const auto field_binded_method = "this." + field_name + ".bind(this)";
+
+ std::string ret;
+
+ if (!is_array) {
+ const auto conversion_function = GenUnionConvFuncName(enum_def);
+ const auto target_enum = "this." + field_name + "Type()";
+
+ ret = "(() => {\n";
+ ret += " let temp = " + conversion_function + "(" + target_enum +
+ ", " + field_binded_method + ");\n";
+ ret += " if(temp === null) { return null; }\n";
+ ret += union_has_string
+ ? " if(typeof temp === 'string') { return temp; }\n"
+ : "";
+ ret += " return temp.unpack()\n";
+ ret += " })()";
+ } else {
+ const auto conversion_function = GenUnionListConvFuncName(enum_def);
+ const auto target_enum_accesor = "this." + field_name + "Type";
+ const auto target_enum_length = target_enum_accesor + "Length()";
+
+ ret = "(() => {\n";
+ ret += " let ret = [];\n";
+ ret += " for(let targetEnumIndex = 0; targetEnumIndex < " +
+ target_enum_length +
+ "; "
+ "++targetEnumIndex) {\n";
+ ret += " let targetEnum = " + target_enum_accesor +
+ "(targetEnumIndex);\n";
+ ret += " if(targetEnum === null || " + enum_type +
+ "[targetEnum!] === 'NONE') { "
+ "continue; }\n\n";
+ ret += " let temp = " + conversion_function + "(targetEnum, " +
+ field_binded_method + ", targetEnumIndex);\n";
+ ret += " if(temp === null) { continue; }\n";
+ ret += union_has_string ? " if(typeof temp === 'string') { "
+ "ret.push(temp); continue; }\n"
+ : "";
+ ret += " ret.push(temp.unpack());\n";
+ ret += " }\n";
+ ret += " return ret;\n";
+ ret += " })()";
+ }
+
+ return ret;
+ }
+
+ FLATBUFFERS_ASSERT(0);
+ return "";
+ }
+
+ static std::string GenNullCheckConditional(
+ const std::string &nullCheckVar, const std::string &trueVal,
+ const std::string &falseVal = "null") {
+ return "(" + nullCheckVar + " !== null ? " + trueVal + " : " + falseVal +
+ ")";
+ }
+
+ std::string GenStructMemberValueTS(const StructDef &struct_def,
+ const std::string &prefix,
+ const std::string &delimiter,
+ const bool nullCheck = true) {
+ std::string ret;
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++it) {
+ auto &field = **it;
+
+ const auto curr_member_accessor =
+ prefix + "." + ConvertCase(field.name, Case::kLowerCamel);
+ if (IsStruct(field.value.type)) {
+ ret += GenStructMemberValueTS(*field.value.type.struct_def,
+ curr_member_accessor, delimiter);
+ } else {
+ if (nullCheck) {
+ ret +=
+ "(" + prefix + " === null ? 0 : " + curr_member_accessor + "!)";
+ } else {
+ ret += curr_member_accessor;
+ }
+ }
+
+ if (std::next(it) != struct_def.fields.vec.end()) { ret += delimiter; }
+ }
+
+ return ret;
+ }
+
+ void GenObjApi(const Parser &parser, StructDef &struct_def,
+ std::string &obj_api_unpack_func, std::string &obj_api_class,
+ import_set &imports) {
+ const auto class_name = GetObjApiClassName(struct_def, parser.opts);
+
+ std::string unpack_func = "\nunpack(): " + class_name +
+ " {\n return new " + class_name + "(" +
+ (struct_def.fields.vec.empty() ? "" : "\n");
+ std::string unpack_to_func = "\nunpackTo(_o: " + class_name + "): void {" +
+ +(struct_def.fields.vec.empty() ? "" : "\n");
+
+ std::string constructor_func = "constructor(";
+ constructor_func += (struct_def.fields.vec.empty() ? "" : "\n");
+
+ const auto has_create =
+ struct_def.fixed || CanCreateFactoryMethod(struct_def);
+
+ std::string pack_func_prototype =
+ "\npack(builder:flatbuffers.Builder): flatbuffers.Offset {\n";
+
+ std::string pack_func_offset_decl;
+ std::string pack_func_create_call;
+
+ const auto struct_name =
+ EscapeKeyword(AddImport(imports, struct_def, struct_def));
+
+ if (has_create) {
+ pack_func_create_call = " return " + struct_name + ".create" +
+ GetPrefixedName(struct_def) + "(builder" +
+ (struct_def.fields.vec.empty() ? "" : ",\n ");
+ } else {
+ pack_func_create_call = " " + struct_name + ".start" +
+ GetPrefixedName(struct_def) + "(builder);\n";
+ }
+
+ if (struct_def.fixed) {
+ // when packing struct, nested struct's members instead of the struct's
+ // offset are used
+ pack_func_create_call +=
+ GenStructMemberValueTS(struct_def, "this", ",\n ", false) + "\n ";
+ }
+
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++it) {
+ auto &field = **it;
+ if (field.deprecated) continue;
+
+ const auto field_name = ConvertCase(field.name, Case::kLowerCamel);
+ const auto field_name_escaped = EscapeKeyword(field_name);
+ const std::string field_binded_method =
+ "this." + field_name + ".bind(this)";
+
+ std::string field_val;
+ std::string field_type;
+ // a string that declares a variable containing the
+ // offset for things that can't be generated inline
+ // empty otw
+ std::string field_offset_decl;
+ // a string that contains values for things that can be created inline or
+ // the variable name from field_offset_decl
+ std::string field_offset_val;
+ const auto field_default_val = GenDefaultValue(field, imports);
+
+ // Emit a scalar field
+ const auto is_string = IsString(field.value.type);
+ if (IsScalar(field.value.type.base_type) || is_string) {
+ const auto has_null_default = is_string || HasNullDefault(field);
+
+ field_type += GenTypeName(imports, field, field.value.type, false,
+ has_null_default);
+ field_val = "this." + field_name + "()";
+
+ if (field.value.type.base_type != BASE_TYPE_STRING) {
+ field_offset_val = "this." + field_name_escaped;
+ } else {
+ field_offset_decl = GenNullCheckConditional(
+ "this." + field_name_escaped,
+ "builder.createString(this." + field_name_escaped + "!)", "0");
+ }
+ }
+
+ // Emit an object field
+ else {
+ auto is_vector = false;
+ switch (field.value.type.base_type) {
+ case BASE_TYPE_STRUCT: {
+ const auto &sd = *field.value.type.struct_def;
+ field_type += GetObjApiClassName(AddImport(imports, struct_def, sd),
+ parser.opts);
+
+ const std::string field_accessor =
+ "this." + field_name_escaped + "()";
+ field_val = GenNullCheckConditional(field_accessor,
+ field_accessor + "!.unpack()");
+ auto packing = GenNullCheckConditional(
+ "this." + field_name_escaped,
+ "this." + field_name_escaped + "!.pack(builder)",
+ "0");
+
+ if (sd.fixed) {
+ field_offset_val = std::move(packing);
+ } else {
+ field_offset_decl = std::move(packing);
+ }
+
+ break;
+ }
+
+ case BASE_TYPE_VECTOR: {
+ auto vectortype = field.value.type.VectorType();
+ auto vectortypename =
+ GenTypeName(imports, struct_def, vectortype, false);
+ is_vector = true;
+
+ field_type = "(";
+
+ switch (vectortype.base_type) {
+ case BASE_TYPE_STRUCT: {
+ const auto &sd = *field.value.type.struct_def;
+ field_type += GetObjApiClassName(sd, parser.opts);
+ field_type += ")[]";
+
+ field_val = GenBBAccess() + ".createObjList(" +
+ field_binded_method + ", this." + field_name +
+ "Length())";
+
+ if (sd.fixed) {
+ field_offset_decl =
+ "builder.createStructOffsetList(this." +
+ field_name_escaped + ", " +
+ EscapeKeyword(
+ AddImport(imports, struct_def, struct_def)) +
+ ".start" + ConvertCase(field_name, Case::kUpperCamel) +
+ "Vector)";
+ } else {
+ field_offset_decl =
+ EscapeKeyword(
+ AddImport(imports, struct_def, struct_def)) +
+ ".create" + ConvertCase(field_name, Case::kUpperCamel) +
+ "Vector(builder, builder.createObjectOffsetList(" +
+ "this." + field_name_escaped + "))";
+ }
+
+ break;
+ }
+
+ case BASE_TYPE_STRING: {
+ field_type += "string)[]";
+ field_val = GenBBAccess() + ".createScalarList(" +
+ field_binded_method + ", this." + field_name +
+ "Length())";
+ field_offset_decl =
+ EscapeKeyword(AddImport(imports, struct_def, struct_def)) +
+ ".create" + ConvertCase(field_name, Case::kUpperCamel) +
+ "Vector(builder, builder.createObjectOffsetList(" +
+ "this." + field_name_escaped + "))";
+ break;
+ }
+
+ case BASE_TYPE_UNION: {
+ field_type += GenObjApiUnionTypeTS(imports, parser.opts,
+ *(vectortype.enum_def));
+ field_type += ")[]";
+ field_val =
+ GenUnionValTS(imports, field_name, vectortype, true);
+
+ field_offset_decl =
+ EscapeKeyword(AddImport(imports, struct_def, struct_def)) +
+ ".create" + ConvertCase(field_name, Case::kUpperCamel) +
+ "Vector(builder, builder.createObjectOffsetList(" +
+ "this." + field_name_escaped + "))";
+
+ break;
+ }
+ default: {
+ if (vectortype.enum_def) {
+ field_type += GenTypeName(imports, struct_def, vectortype,
+ false, HasNullDefault(field));
+ } else {
+ field_type += vectortypename;
+ }
+ field_type += ")[]";
+ field_val = GenBBAccess() + ".createScalarList(" +
+ field_binded_method + ", this." + field_name +
+ "Length())";
+
+ field_offset_decl =
+ EscapeKeyword(AddImport(imports, struct_def, struct_def)) +
+ ".create" + ConvertCase(field_name, Case::kUpperCamel) +
+ "Vector(builder, this." + field_name_escaped + ")";
+
+ break;
+ }
+ }
+
+ break;
+ }
+
+ case BASE_TYPE_UNION: {
+ field_type += GenObjApiUnionTypeTS(imports, parser.opts,
+ *(field.value.type.enum_def));
+
+ field_val = GenUnionValTS(imports, field_name, field.value.type);
+ field_offset_decl =
+ "builder.createObjectOffset(this." + field_name_escaped + ")";
+ break;
+ }
+
+ default: FLATBUFFERS_ASSERT(0); break;
+ }
+
+ // length 0 vector is simply empty instead of null
+ field_type += is_vector ? "" : "|null";
+ }
+
+ if (!field_offset_decl.empty()) {
+ field_offset_decl =
+ " const " + field_name_escaped + " = " + field_offset_decl + ";";
+ }
+ if (field_offset_val.empty()) { field_offset_val = field_name_escaped; }
+
+ unpack_func += " " + field_val;
+ unpack_to_func += " _o." + field_name_escaped + " = " + field_val + ";";
+
+ // FIXME: if field_type and field_name_escaped are identical, then
+ // this generates invalid typescript.
+ constructor_func += " public " + field_name_escaped + ": " + field_type +
+ " = " +
+ field_default_val;
+
+ if (!struct_def.fixed) {
+ if (!field_offset_decl.empty()) {
+ pack_func_offset_decl += field_offset_decl + "\n";
+ }
+
+ if (has_create) {
+ pack_func_create_call += field_offset_val;
+ } else {
+ if (field.IsScalarOptional()) {
+ pack_func_create_call += " if (" + field_offset_val + " !== null)\n ";
+ }
+ pack_func_create_call += " " + struct_name + ".add" +
+ ConvertCase(field.name, Case::kUpperCamel) +
+ "(builder, " + field_offset_val + ");\n";
+ }
+ }
+
+ if (std::next(it) != struct_def.fields.vec.end()) {
+ constructor_func += ",\n";
+
+ if (!struct_def.fixed && has_create) {
+ pack_func_create_call += ",\n ";
+ }
+
+ unpack_func += ",\n";
+ unpack_to_func += "\n";
+ } else {
+ constructor_func += "\n";
+ if (!struct_def.fixed) {
+ pack_func_offset_decl += (pack_func_offset_decl.empty() ? "" : "\n");
+ pack_func_create_call += "\n ";
+ }
+
+ unpack_func += "\n ";
+ unpack_to_func += "\n";
+ }
+ }
+
+ constructor_func += "){}\n\n";
+
+ if (has_create) {
+ pack_func_create_call += ");";
+ } else {
+ pack_func_create_call += "return " + struct_name + ".end" +
+ GetPrefixedName(struct_def) + "(builder);";
+ }
+
+ obj_api_class = "\nexport class " +
+ GetObjApiClassName(struct_def, parser.opts) + " {\n";
+
+ obj_api_class += constructor_func;
+ obj_api_class += pack_func_prototype + pack_func_offset_decl +
+ pack_func_create_call + "\n}";
+
+ obj_api_class += "\n}\n";
+
+ unpack_func += ");\n}";
+ unpack_to_func += "}\n";
+
+ obj_api_unpack_func = unpack_func + "\n\n" + unpack_to_func;
+ }
+
+ static bool CanCreateFactoryMethod(const StructDef &struct_def) {
+ // to preserve backwards compatibility, we allow the first field to be a
+ // struct
+ return struct_def.fields.vec.size() < 2 ||
+ std::all_of(std::begin(struct_def.fields.vec) + 1,
+ std::end(struct_def.fields.vec),
+ [](const FieldDef *f) -> bool {
+ FLATBUFFERS_ASSERT(f != nullptr);
+ return f->value.type.base_type != BASE_TYPE_STRUCT;
+ });
+ }
+
+ // Generate an accessor struct with constructor for a flatbuffers struct.
+ void GenStruct(const Parser &parser, StructDef &struct_def,
+ std::string *code_ptr, import_set &imports) {
+ if (struct_def.generated) return;
+ std::string &code = *code_ptr;
+
+ std::string object_name;
+ std::string object_namespace = GetNameSpace(struct_def);
+
+ // Emit constructor
+ object_name = EscapeKeyword(struct_def.name);
+ GenDocComment(struct_def.doc_comment, code_ptr);
+ code += "export class " + object_name;
+ code += " {\n";
+ code += " bb: flatbuffers.ByteBuffer|null = null;\n";
+ code += " bb_pos = 0;\n";
+
+ // Generate the __init method that sets the field in a pre-existing
+ // accessor object. This is to allow object reuse.
+ code +=
+ "__init(i:number, bb:flatbuffers.ByteBuffer):" + object_name + " {\n";
+ code += " this.bb_pos = i;\n";
+ code += " this.bb = bb;\n";
+ code += " return this;\n";
+ code += "}\n\n";
+
+ // Generate special accessors for the table that when used as the root of a
+ // FlatBuffer
+ GenerateRootAccessor(struct_def, code_ptr, code, object_name, false);
+ GenerateRootAccessor(struct_def, code_ptr, code, object_name, true);
+
+ // Generate the identifier check method
+ if (!struct_def.fixed && parser_.root_struct_def_ == &struct_def &&
+ !parser_.file_identifier_.empty()) {
+ GenDocComment(code_ptr);
+ code +=
+ "static bufferHasIdentifier(bb:flatbuffers.ByteBuffer):boolean "
+ "{\n";
+ code += " return bb.__has_identifier('" + parser_.file_identifier_;
+ code += "');\n}\n\n";
+ }
+
+ // Emit field accessors
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++it) {
+ auto &field = **it;
+ if (field.deprecated) continue;
+ auto offset_prefix =
+ " const offset = " + GenBBAccess() + ".__offset(this.bb_pos, " +
+ NumToString(field.value.offset) + ");\n return offset ? ";
+
+ // Emit a scalar field
+ const auto is_string = IsString(field.value.type);
+ if (IsScalar(field.value.type.base_type) || is_string) {
+ const auto has_null_default = is_string || HasNullDefault(field);
+
+ GenDocComment(field.doc_comment, code_ptr);
+ std::string prefix = ConvertCase(field.name, Case::kLowerCamel) + "(";
+ if (is_string) {
+ code += prefix + "):string|null\n";
+ code +=
+ prefix + "optionalEncoding:flatbuffers.Encoding" + "):" +
+ GenTypeName(imports, struct_def, field.value.type, false, true) +
+ "\n";
+ code += prefix + "optionalEncoding?:any";
+ } else {
+ code += prefix;
+ }
+ if (field.value.type.enum_def) {
+ code += "):" +
+ GenTypeName(imports, struct_def, field.value.type, false,
+ field.IsOptional()) +
+ " {\n";
+ } else {
+ code += "):" +
+ GenTypeName(imports, struct_def, field.value.type, false,
+ has_null_default) +
+ " {\n";
+ }
+
+ if (struct_def.fixed) {
+ code +=
+ " return " +
+ GenGetter(field.value.type,
+ "(this.bb_pos" + MaybeAdd(field.value.offset) + ")") +
+ ";\n";
+ } else {
+ std::string index = "this.bb_pos + offset";
+ if (is_string) { index += ", optionalEncoding"; }
+ code += offset_prefix +
+ GenGetter(field.value.type, "(" + index + ")") + " : " +
+ GenDefaultValue(field, imports);
+ code += ";\n";
+ }
+ }
+
+ // Emit an object field
+ else {
+ switch (field.value.type.base_type) {
+ case BASE_TYPE_STRUCT: {
+ const auto type = EscapeKeyword(
+ AddImport(imports, struct_def, *field.value.type.struct_def));
+ GenDocComment(field.doc_comment, code_ptr);
+ code += ConvertCase(field.name, Case::kLowerCamel);
+ code += "(obj?:" + type + "):" + type + "|null {\n";
+
+ if (struct_def.fixed) {
+ code += " return (obj || " + GenerateNewExpression(type);
+ code += ").__init(this.bb_pos";
+ code +=
+ MaybeAdd(field.value.offset) + ", " + GenBBAccess() + ");\n";
+ } else {
+ code += offset_prefix + "(obj || " + GenerateNewExpression(type) +
+ ").__init(";
+ code += field.value.type.struct_def->fixed
+ ? "this.bb_pos + offset"
+ : GenBBAccess() + ".__indirect(this.bb_pos + offset)";
+ code += ", " + GenBBAccess() + ") : null;\n";
+ }
+
+ break;
+ }
+
+ case BASE_TYPE_VECTOR: {
+ auto vectortype = field.value.type.VectorType();
+ auto vectortypename =
+ GenTypeName(imports, struct_def, vectortype, false);
+ auto inline_size = InlineSize(vectortype);
+ auto index = GenBBAccess() +
+ ".__vector(this.bb_pos + offset) + index" +
+ MaybeScale(inline_size);
+ std::string ret_type;
+ bool is_union = false;
+ switch (vectortype.base_type) {
+ case BASE_TYPE_STRUCT: ret_type = vectortypename; break;
+ case BASE_TYPE_STRING: ret_type = vectortypename; break;
+ case BASE_TYPE_UNION:
+ ret_type = "?flatbuffers.Table";
+ is_union = true;
+ break;
+ default: ret_type = vectortypename;
+ }
+ GenDocComment(field.doc_comment, code_ptr);
+ std::string prefix = ConvertCase(field.name, Case::kLowerCamel);
+ // TODO: make it work without any
+ // if (is_union) { prefix += "<T extends flatbuffers.Table>"; }
+ if (is_union) { prefix += ""; }
+ prefix += "(index: number";
+ if (is_union) {
+ const auto union_type =
+ GenUnionGenericTypeTS(*(field.value.type.enum_def));
+
+ vectortypename = union_type;
+ code += prefix + ", obj:" + union_type;
+ } else if (vectortype.base_type == BASE_TYPE_STRUCT) {
+ code += prefix + ", obj?:" + vectortypename;
+ } else if (IsString(vectortype)) {
+ code += prefix + "):string\n";
+ code += prefix + ",optionalEncoding:flatbuffers.Encoding" +
+ "):" + vectortypename + "\n";
+ code += prefix + ",optionalEncoding?:any";
+ } else {
+ code += prefix;
+ }
+ code += "):" + vectortypename + "|null {\n";
+
+ if (vectortype.base_type == BASE_TYPE_STRUCT) {
+ code += offset_prefix + "(obj || " +
+ GenerateNewExpression(vectortypename);
+ code += ").__init(";
+ code += vectortype.struct_def->fixed
+ ? index
+ : GenBBAccess() + ".__indirect(" + index + ")";
+ code += ", " + GenBBAccess() + ")";
+ } else {
+ if (is_union) {
+ index = "obj, " + index;
+ } else if (IsString(vectortype)) {
+ index += ", optionalEncoding";
+ }
+ code += offset_prefix + GenGetter(vectortype, "(" + index + ")");
+ }
+ code += " : ";
+ if (field.value.type.element == BASE_TYPE_BOOL) {
+ code += "false";
+ } else if (field.value.type.element == BASE_TYPE_LONG ||
+ field.value.type.element == BASE_TYPE_ULONG) {
+ code += "BigInt(0)";
+ } else if (IsScalar(field.value.type.element)) {
+ if (field.value.type.enum_def) {
+ code += field.value.constant;
+ } else {
+ code += "0";
+ }
+ } else {
+ code += "null";
+ }
+ code += ";\n";
+ break;
+ }
+
+ case BASE_TYPE_UNION: {
+ GenDocComment(field.doc_comment, code_ptr);
+ code += ConvertCase(field.name, Case::kLowerCamel);
+
+ const auto &union_enum = *(field.value.type.enum_def);
+ const auto union_type = GenUnionGenericTypeTS(union_enum);
+ code += "<T extends flatbuffers.Table>(obj:" + union_type +
+ "):" + union_type +
+ "|null "
+ "{\n";
+
+ code += offset_prefix +
+ GenGetter(field.value.type, "(obj, this.bb_pos + offset)") +
+ " : null;\n";
+ break;
+ }
+ default: FLATBUFFERS_ASSERT(0);
+ }
+ }
+ code += "}\n\n";
+
+ // Adds the mutable scalar value to the output
+ if (IsScalar(field.value.type.base_type) && parser.opts.mutable_buffer &&
+ !IsUnion(field.value.type)) {
+ std::string type =
+ GenTypeName(imports, struct_def, field.value.type, true);
+
+ code += "mutate_" + field.name + "(value:" + type + "):boolean {\n";
+
+ if (struct_def.fixed) {
+ code += " " + GenBBAccess() + ".write" +
+ ConvertCase(GenType(field.value.type), Case::kUpperCamel) +
+ "(this.bb_pos + " + NumToString(field.value.offset) + ", ";
+ } else {
+ code += " const offset = " + GenBBAccess() +
+ ".__offset(this.bb_pos, " + NumToString(field.value.offset) +
+ ");\n\n";
+ code += " if (offset === 0) {\n";
+ code += " return false;\n";
+ code += " }\n\n";
+
+ // special case for bools, which are treated as uint8
+ code += " " + GenBBAccess() + ".write" +
+ ConvertCase(GenType(field.value.type), Case::kUpperCamel) +
+ "(this.bb_pos + offset, ";
+ if (field.value.type.base_type == BASE_TYPE_BOOL) { code += "+"; }
+ }
+
+ code += "value);\n";
+ code += " return true;\n";
+ code += "}\n\n";
+ }
+
+ // Emit vector helpers
+ if (IsVector(field.value.type)) {
+ // Emit a length helper
+ GenDocComment(code_ptr);
+ code += ConvertCase(field.name, Case::kLowerCamel);
+ code += "Length():number {\n" + offset_prefix;
+
+ code +=
+ GenBBAccess() + ".__vector_len(this.bb_pos + offset) : 0;\n}\n\n";
+
+ // For scalar types, emit a typed array helper
+ auto vectorType = field.value.type.VectorType();
+ if (IsScalar(vectorType.base_type) && !IsLong(vectorType.base_type)) {
+ GenDocComment(code_ptr);
+
+ code += ConvertCase(field.name, Case::kLowerCamel);
+ code += "Array():" + GenType(vectorType) + "Array|null {\n" +
+ offset_prefix;
+
+ code += "new " + GenType(vectorType) + "Array(" + GenBBAccess() +
+ ".bytes().buffer, " + GenBBAccess() +
+ ".bytes().byteOffset + " + GenBBAccess() +
+ ".__vector(this.bb_pos + offset), " + GenBBAccess() +
+ ".__vector_len(this.bb_pos + offset)) : null;\n}\n\n";
+ }
+ }
+ }
+
+ // Emit the fully qualified name
+ if (parser_.opts.generate_name_strings) {
+ GenDocComment(code_ptr);
+ code += "static getFullyQualifiedName():string {\n";
+ code += " return '" + WrapInNameSpace(struct_def) + "';\n";
+ code += "}\n\n";
+ }
+
+ // Emit the size of the struct.
+ if (struct_def.fixed) {
+ GenDocComment(code_ptr);
+ code += "static sizeOf():number {\n";
+ code += " return " + NumToString(struct_def.bytesize) + ";\n";
+ code += "}\n\n";
+ }
+
+ // Emit a factory constructor
+ if (struct_def.fixed) {
+ std::string arguments;
+ GenStructArgs(imports, struct_def, &arguments, "");
+ GenDocComment(code_ptr);
+
+ code += "static create" + GetPrefixedName(struct_def) +
+ "(builder:flatbuffers.Builder";
+ code += arguments + "):flatbuffers.Offset {\n";
+
+ GenStructBody(struct_def, &code, "");
+ code += " return builder.offset();\n}\n\n";
+ } else {
+ // Generate a method to start building a new object
+ GenDocComment(code_ptr);
+
+ code += "static start" + GetPrefixedName(struct_def) +
+ "(builder:flatbuffers.Builder) {\n";
+
+ code += " builder.startObject(" +
+ NumToString(struct_def.fields.vec.size()) + ");\n";
+ code += "}\n\n";
+
+ // Generate a set of static methods that allow table construction
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++it) {
+ auto &field = **it;
+ if (field.deprecated) continue;
+ const auto argname = GetArgName(field);
+
+ // Generate the field insertion method
+ GenDocComment(code_ptr);
+ code += "static add" + ConvertCase(field.name, Case::kUpperCamel);
+ code += "(builder:flatbuffers.Builder, " + argname + ":" +
+ GetArgType(imports, struct_def, field, false) + ") {\n";
+ code += " builder.addField" + GenWriteMethod(field.value.type) + "(";
+ code += NumToString(it - struct_def.fields.vec.begin()) + ", ";
+ if (field.value.type.base_type == BASE_TYPE_BOOL) { code += "+"; }
+ code += argname + ", ";
+ if (!IsScalar(field.value.type.base_type)) {
+ code += "0";
+ } else if (HasNullDefault(field)) {
+ if (IsLong(field.value.type.base_type)) {
+ code += "BigInt(0)";
+ } else {
+ code += "0";
+ }
+ } else {
+ if (field.value.type.base_type == BASE_TYPE_BOOL) { code += "+"; }
+ code += GenDefaultValue(field, imports);
+ }
+ code += ");\n}\n\n";
+
+ if (IsVector(field.value.type)) {
+ auto vector_type = field.value.type.VectorType();
+ auto alignment = InlineAlignment(vector_type);
+ auto elem_size = InlineSize(vector_type);
+
+ // Generate a method to create a vector from a JavaScript array
+ if (!IsStruct(vector_type)) {
+ GenDocComment(code_ptr);
+
+ const std::string sig_begin =
+ "static create" + ConvertCase(field.name, Case::kUpperCamel) +
+ "Vector(builder:flatbuffers.Builder, data:";
+ const std::string sig_end = "):flatbuffers.Offset";
+ std::string type =
+ GenTypeName(imports, struct_def, vector_type, true) + "[]";
+ if (type == "number[]") {
+ const auto &array_type = GenType(vector_type);
+ // the old type should be deprecated in the future
+ std::string type_old = "number[]|Uint8Array";
+ std::string type_new = "number[]|" + array_type + "Array";
+ if (type_old == type_new) {
+ type = type_new;
+ } else {
+ // add function overloads
+ code += sig_begin + type_new + sig_end + ";\n";
+ code +=
+ "/**\n * @deprecated This Uint8Array overload will "
+ "be removed in the future.\n */\n";
+ code += sig_begin + type_old + sig_end + ";\n";
+ type = type_new + "|Uint8Array";
+ }
+ }
+ code += sig_begin + type + sig_end + " {\n";
+ code += " builder.startVector(" + NumToString(elem_size);
+ code += ", data.length, " + NumToString(alignment) + ");\n";
+ code += " for (let i = data.length - 1; i >= 0; i--) {\n";
+ code += " builder.add" + GenWriteMethod(vector_type) + "(";
+ if (vector_type.base_type == BASE_TYPE_BOOL) { code += "+"; }
+ code += "data[i]!);\n";
+ code += " }\n";
+ code += " return builder.endVector();\n";
+ code += "}\n\n";
+ }
+
+ // Generate a method to start a vector, data to be added manually
+ // after
+ GenDocComment(code_ptr);
+
+ code += "static start" + ConvertCase(field.name, Case::kUpperCamel);
+ code += "Vector(builder:flatbuffers.Builder, numElems:number) {\n";
+ code += " builder.startVector(" + NumToString(elem_size);
+ code += ", numElems, " + NumToString(alignment) + ");\n";
+ code += "}\n\n";
+ }
+ }
+
+ // Generate a method to stop building a new object
+ GenDocComment(code_ptr);
+
+ code += "static end" + GetPrefixedName(struct_def);
+ code += "(builder:flatbuffers.Builder):flatbuffers.Offset {\n";
+
+ code += " const offset = builder.endObject();\n";
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++it) {
+ auto &field = **it;
+ if (!field.deprecated && field.IsRequired()) {
+ code += " builder.requiredField(offset, ";
+ code += NumToString(field.value.offset);
+ code += ") // " + field.name + "\n";
+ }
+ }
+ code += " return offset;\n";
+ code += "}\n\n";
+
+ // Generate the methods to complete buffer construction
+ GenerateFinisher(struct_def, code_ptr, code, false);
+ GenerateFinisher(struct_def, code_ptr, code, true);
+
+ // Generate a convenient CreateX function
+ if (CanCreateFactoryMethod(struct_def)) {
+ code += "static create" + GetPrefixedName(struct_def);
+ code += "(builder:flatbuffers.Builder";
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++it) {
+ const auto &field = **it;
+ if (field.deprecated) continue;
+ code += ", " + GetArgName(field) + ":" +
+ GetArgType(imports, struct_def, field, true);
+ }
+
+ code += "):flatbuffers.Offset {\n";
+ code += " " + object_name + ".start" +
+ GetPrefixedName(struct_def) + "(builder);\n";
+
+ std::string methodPrefix = object_name;
+ for (auto it = struct_def.fields.vec.begin();
+ it != struct_def.fields.vec.end(); ++it) {
+ const auto &field = **it;
+ if (field.deprecated) continue;
+
+ const auto arg_name = GetArgName(field);
+
+ if (field.IsScalarOptional()) {
+ code += " if (" + arg_name + " !== null)\n ";
+ }
+
+ code += " " + methodPrefix + ".add" +
+ ConvertCase(field.name, Case::kUpperCamel) + "(";
+ code += "builder, " + arg_name + ");\n";
+ }
+
+ code += " return " + methodPrefix + ".end" +
+ GetPrefixedName(struct_def) + "(builder);\n";
+ code += "}\n";
+ }
+ }
+
+ if (!struct_def.fixed && parser_.services_.vec.size() != 0) {
+ auto name = GetPrefixedName(struct_def, "");
+ code += "\n";
+ code += "serialize():Uint8Array {\n";
+ code += " return this.bb!.bytes();\n";
+ code += "}\n";
+
+ code += "\n";
+ code += "static deserialize(buffer: Uint8Array):" + EscapeKeyword(name) +
+ " {\n";
+ code += " return " +
+ EscapeKeyword(AddImport(imports, struct_def, struct_def)) +
+ ".getRootAs" + name + "(new flatbuffers.ByteBuffer(buffer))\n";
+ code += "}\n";
+ }
+
+ if (parser_.opts.generate_object_based_api) {
+ std::string obj_api_class;
+ std::string obj_api_unpack_func;
+ GenObjApi(parser_, struct_def, obj_api_unpack_func, obj_api_class,
+ imports);
+
+ code += obj_api_unpack_func + "}\n" + obj_api_class;
+ } else {
+ code += "}\n";
+ }
+ }
+
+ static bool HasNullDefault(const FieldDef &field) {
+ return field.IsOptional() && field.value.constant == "null";
+ }
+
+ std::string GetArgType(import_set &imports, const Definition &owner,
+ const FieldDef &field, bool allowNull) {
+ return GenTypeName(imports, owner, field.value.type, true,
+ allowNull && field.IsOptional());
+ }
+
+ std::string GetArgName(const FieldDef &field) {
+ auto argname = ConvertCase(field.name, Case::kLowerCamel);
+ if (!IsScalar(field.value.type.base_type)) {
+ argname += "Offset";
+ } else {
+ argname = EscapeKeyword(argname);
+ }
+ return argname;
+ }
+
+ std::string GetPrefixedName(const StructDef &struct_def,
+ const char *prefix = "") {
+ return prefix + struct_def.name;
+ }
+}; // namespace ts
+} // namespace ts
+
+bool GenerateTS(const Parser &parser, const std::string &path,
+ const std::string &file_name) {
+ ts::TsGenerator generator(parser, path, file_name);
+ return generator.generate();
+}
+
+std::string TSMakeRule(const Parser &parser, const std::string &path,
+ const std::string &file_name) {
+ std::string filebase =
+ flatbuffers::StripPath(flatbuffers::StripExtension(file_name));
+ ts::TsGenerator generator(parser, path, file_name);
+ std::string make_rule =
+ generator.GeneratedFileName(path, filebase, parser.opts) + ": ";
+
+ auto included_files = parser.GetIncludedFilesRecursive(file_name);
+ for (auto it = included_files.begin(); it != included_files.end(); ++it) {
+ make_rule += " " + *it;
+ }
+ return make_rule;
+}
+
+} // namespace flatbuffers
diff --git a/src/idl_parser.cpp b/src/idl_parser.cpp
index 6d916e5..dd106df 100644
--- a/src/idl_parser.cpp
+++ b/src/idl_parser.cpp
@@ -20,6 +20,7 @@
#include <string>
#include <utility>
+#include "flatbuffers/base.h"
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
@@ -92,33 +93,6 @@
return true;
}
-// Convert an underscore_based_indentifier in to camelCase.
-// Also uppercases the first character if first is true.
-std::string MakeCamel(const std::string &in, bool first) {
- std::string s;
- for (size_t i = 0; i < in.length(); i++) {
- if (!i && first)
- s += CharToUpper(in[0]);
- else if (in[i] == '_' && i + 1 < in.length())
- s += CharToUpper(in[++i]);
- else
- s += in[i];
- }
- return s;
-}
-
-// Convert an underscore_based_identifier in to screaming snake case.
-std::string MakeScreamingCamel(const std::string &in) {
- std::string s;
- for (size_t i = 0; i < in.length(); i++) {
- if (in[i] != '_')
- s += CharToUpper(in[i]);
- else
- s += in[i];
- }
- return s;
-}
-
void DeserializeDoc(std::vector<std::string> &doc,
const Vector<Offset<String>> *documentation) {
if (documentation == nullptr) return;
@@ -142,7 +116,12 @@
error_ += ": " + msg;
}
-void Parser::Warning(const std::string &msg) { Message("warning: " + msg); }
+void Parser::Warning(const std::string &msg) {
+ if (!opts.no_warnings) {
+ Message("warning: " + msg);
+ has_warning_ = true; // for opts.warnings_as_errors
+ }
+}
CheckedError Parser::Error(const std::string &msg) {
Message("error: " + msg);
@@ -152,19 +131,39 @@
inline CheckedError NoError() { return CheckedError(false); }
CheckedError Parser::RecurseError() {
- return Error("maximum parsing recursion of " +
- NumToString(FLATBUFFERS_MAX_PARSING_DEPTH) + " reached");
+ return Error("maximum parsing depth " + NumToString(parse_depth_counter_) +
+ " reached");
}
-template<typename F> CheckedError Parser::Recurse(F f) {
- if (recurse_protection_counter >= (FLATBUFFERS_MAX_PARSING_DEPTH))
- return RecurseError();
- recurse_protection_counter++;
- auto ce = f();
- recurse_protection_counter--;
- return ce;
+const std::string &Parser::GetPooledString(const std::string &s) const {
+ return *(string_cache_.insert(s).first);
}
+class Parser::ParseDepthGuard {
+ public:
+ explicit ParseDepthGuard(Parser *parser_not_null)
+ : parser_(*parser_not_null), caller_depth_(parser_.parse_depth_counter_) {
+ FLATBUFFERS_ASSERT(caller_depth_ <= (FLATBUFFERS_MAX_PARSING_DEPTH) &&
+ "Check() must be called to prevent stack overflow");
+ parser_.parse_depth_counter_ += 1;
+ }
+
+ ~ParseDepthGuard() { parser_.parse_depth_counter_ -= 1; }
+
+ CheckedError Check() {
+ return caller_depth_ >= (FLATBUFFERS_MAX_PARSING_DEPTH)
+ ? parser_.RecurseError()
+ : CheckedError(false);
+ }
+
+ FLATBUFFERS_DELETE_FUNC(ParseDepthGuard(const ParseDepthGuard &));
+ FLATBUFFERS_DELETE_FUNC(ParseDepthGuard &operator=(const ParseDepthGuard &));
+
+ private:
+ Parser &parser_;
+ const int caller_depth_;
+};
+
template<typename T> std::string TypeToIntervalString() {
return "[" + NumToString((flatbuffers::numeric_limits<T>::lowest)()) + "; " +
NumToString((flatbuffers::numeric_limits<T>::max)()) + "]";
@@ -172,8 +171,20 @@
// atot: template version of atoi/atof: convert a string to an instance of T.
template<typename T>
-inline CheckedError atot(const char *s, Parser &parser, T *val) {
- auto done = StringToNumber(s, val);
+bool atot_scalar(const char *s, T *val, bool_constant<false>) {
+ return StringToNumber(s, val);
+}
+
+template<typename T>
+bool atot_scalar(const char *s, T *val, bool_constant<true>) {
+ // Normalize NaN parsed from fbs or json to unsigned NaN.
+ if (false == StringToNumber(s, val)) return false;
+ *val = (*val != *val) ? std::fabs(*val) : *val;
+ return true;
+}
+
+template<typename T> CheckedError atot(const char *s, Parser &parser, T *val) {
+ auto done = atot_scalar(s, val, bool_constant<is_floating_point<T>::value>());
if (done) return NoError();
if (0 == *val)
return parser.Error("invalid number: \"" + std::string(s) + "\"");
@@ -195,9 +206,10 @@
if (components.empty() || !max_components) { return name; }
std::string stream_str;
for (size_t i = 0; i < std::min(components.size(), max_components); i++) {
- if (i) { stream_str += '.'; }
- stream_str += std::string(components[i]);
+ stream_str += components[i];
+ stream_str += '.';
}
+ if (!stream_str.empty()) stream_str.pop_back();
if (name.length()) {
stream_str += '.';
stream_str += name;
@@ -205,6 +217,29 @@
return stream_str;
}
+template<typename T>
+T *LookupTableByName(const SymbolTable<T> &table, const std::string &name,
+ const Namespace ¤t_namespace, size_t skip_top) {
+ const auto &components = current_namespace.components;
+ if (table.dict.empty()) return nullptr;
+ if (components.size() < skip_top) return nullptr;
+ const auto N = components.size() - skip_top;
+ std::string full_name;
+ for (size_t i = 0; i < N; i++) {
+ full_name += components[i];
+ full_name += '.';
+ }
+ for (size_t i = N; i > 0; i--) {
+ full_name += name;
+ auto obj = table.Lookup(full_name);
+ if (obj) return obj;
+ auto len = full_name.size() - components[i - 1].size() - 1 - name.size();
+ full_name.resize(len);
+ }
+ FLATBUFFERS_ASSERT(full_name.empty());
+ return table.Lookup(name); // lookup in global namespace
+}
+
// Declare tokens we'll use. Single character tokens are represented by their
// ascii character code (e.g. '{'), others above 256.
// clang-format off
@@ -444,15 +479,19 @@
}
FLATBUFFERS_FALLTHROUGH(); // else fall thru
default:
- const auto has_sign = (c == '+') || (c == '-');
- // '-'/'+' and following identifier - can be a predefined constant like:
- // NAN, INF, PI, etc or it can be a function name like cos/sin/deg.
- if (IsIdentifierStart(c) || (has_sign && IsIdentifierStart(*cursor_))) {
+ if (IsIdentifierStart(c)) {
// Collect all chars of an identifier:
const char *start = cursor_ - 1;
while (IsIdentifierStart(*cursor_) || is_digit(*cursor_)) cursor_++;
attribute_.append(start, cursor_);
- token_ = has_sign ? kTokenStringConstant : kTokenIdentifier;
+ token_ = kTokenIdentifier;
+ return NoError();
+ }
+
+ const auto has_sign = (c == '+') || (c == '-');
+ if (has_sign && IsIdentifierStart(*cursor_)) {
+ // '-'/'+' and following identifier - it could be a predefined
+ // constant. Return the sign in token_, see ParseSingleValue.
return NoError();
}
@@ -544,13 +583,7 @@
EnumDef *Parser::LookupEnum(const std::string &id) {
// Search thru parent namespaces.
- for (int components = static_cast<int>(current_namespace_->components.size());
- components >= 0; components--) {
- auto ed = enums_.Lookup(
- current_namespace_->GetFullyQualifiedName(id, components));
- if (ed) return ed;
- }
- return nullptr;
+ return LookupTableByName(enums_, id, *current_namespace_, 0);
}
StructDef *Parser::LookupStruct(const std::string &id) const {
@@ -559,6 +592,13 @@
return sd;
}
+StructDef *Parser::LookupStructThruParentNamespaces(
+ const std::string &id) const {
+ auto sd = LookupTableByName(structs_, id, *current_namespace_, 1);
+ if (sd) sd->refcount++;
+ return sd;
+}
+
CheckedError Parser::ParseTypeIdent(Type &type) {
std::string id = attribute_;
EXPECT(kTokenIdentifier);
@@ -617,9 +657,11 @@
ECHECK(ParseTypeIdent(type));
}
} else if (token_ == '[') {
+ ParseDepthGuard depth_guard(this);
+ ECHECK(depth_guard.Check());
NEXT();
Type subtype;
- ECHECK(Recurse([&]() { return ParseType(subtype); }));
+ ECHECK(ParseType(subtype));
if (IsSeries(subtype)) {
// We could support this, but it will complicate things, and it's
// easier to work around with a struct around the inner vector.
@@ -704,10 +746,13 @@
if (!struct_def.fixed && IsArray(type))
return Error("fixed-length array in table must be wrapped in struct");
- if (IsArray(type) && !SupportsAdvancedArrayFeatures()) {
- return Error(
- "Arrays are not yet supported in all "
- "the specified programming languages.");
+ if (IsArray(type)) {
+ advanced_features_ |= reflection::AdvancedArrayFeatures;
+ if (!SupportsAdvancedArrayFeatures()) {
+ return Error(
+ "Arrays are not yet supported in all "
+ "the specified programming languages.");
+ }
}
FieldDef *typefield = nullptr;
@@ -717,6 +762,7 @@
ECHECK(AddField(struct_def, name + UnionTypeFieldSuffix(),
type.enum_def->underlying_type, &typefield));
} else if (IsVector(type) && type.element == BASE_TYPE_UNION) {
+ advanced_features_ |= reflection::AdvancedUnionFeatures;
// Only cpp, js and ts supports the union vector feature so far.
if (!SupportsAdvancedUnionFeatures()) {
return Error(
@@ -737,38 +783,23 @@
if (token_ == '=') {
NEXT();
ECHECK(ParseSingleValue(&field->name, field->value, true));
- if (!IsScalar(type.base_type) ||
- (struct_def.fixed && field->value.constant != "0"))
+ if (IsStruct(type) || (struct_def.fixed && field->value.constant != "0"))
return Error(
- "default values currently only supported for scalars in tables");
- }
-
- // Mark the optional scalars. Note that a side effect of ParseSingleValue is
- // fixing field->value.constant to null.
- if (IsScalar(type.base_type)) {
- field->optional = (field->value.constant == "null");
- if (field->optional) {
- if (type.enum_def && type.enum_def->Lookup("null")) {
- FLATBUFFERS_ASSERT(IsInteger(type.base_type));
+ "default values are not supported for struct fields, table fields, "
+ "or in structs.");
+ if (IsString(type) || IsVector(type)) {
+ advanced_features_ |= reflection::DefaultVectorsAndStrings;
+ if (field->value.constant != "0" && !SupportsDefaultVectorsAndStrings()) {
return Error(
- "the default 'null' is reserved for declaring optional scalar "
- "fields, it conflicts with declaration of enum '" +
- type.enum_def->name + "'.");
- }
- if (field->attributes.Lookup("key")) {
- return Error(
- "only a non-optional scalar field can be used as a 'key' field");
- }
- if (!SupportsOptionalScalars()) {
- return Error(
- "Optional scalars are not yet supported in at least one the of "
- "the specified programming languages.");
+ "Default values for strings and vectors are not supported in one "
+ "of the specified programming languages");
}
}
- } else {
- // For nonscalars, only required fields are non-optional.
- // At least until https://github.com/google/flatbuffers/issues/6053
- field->optional = !field->required;
+
+ if (IsVector(type) && field->value.constant != "0" &&
+ field->value.constant != "[]") {
+ return Error("The only supported default for vectors is `[]`.");
+ }
}
// Append .0 if the value has not it (skip hex and scientific floats).
@@ -786,27 +817,6 @@
field->value.constant += ".0";
}
}
- if (type.enum_def) {
- // The type.base_type can only be scalar, union, array or vector.
- // Table, struct or string can't have enum_def.
- // Default value of union and vector in NONE, NULL translated to "0".
- FLATBUFFERS_ASSERT(IsInteger(type.base_type) ||
- (type.base_type == BASE_TYPE_UNION) || IsVector(type) ||
- IsArray(type));
- if (IsVector(type)) {
- // Vector can't use initialization list.
- FLATBUFFERS_ASSERT(field->value.constant == "0");
- } else {
- // All unions should have the NONE ("0") enum value.
- auto in_enum = type.enum_def->attributes.Lookup("bit_flags") ||
- field->IsScalarOptional() ||
- type.enum_def->FindByValue(field->value.constant);
- if (false == in_enum)
- return Error("default value of " + field->value.constant +
- " for field " + name + " is not part of enum " +
- type.enum_def->name);
- }
- }
field->doc_comment = dc;
ECHECK(ParseMetaData(&field->attributes));
@@ -841,6 +851,87 @@
"hashing.");
}
}
+
+ // For historical convenience reasons, string keys are assumed required.
+ // Scalars are kDefault unless otherwise specified.
+ // Nonscalars are kOptional unless required;
+ field->key = field->attributes.Lookup("key") != nullptr;
+ const bool required = field->attributes.Lookup("required") != nullptr ||
+ (IsString(type) && field->key);
+ const bool default_str_or_vec =
+ ((IsString(type) || IsVector(type)) && field->value.constant != "0");
+ const bool optional = IsScalar(type.base_type)
+ ? (field->value.constant == "null")
+ : !(required || default_str_or_vec);
+ if (required && optional) {
+ return Error("Fields cannot be both optional and required.");
+ }
+ field->presence = FieldDef::MakeFieldPresence(optional, required);
+
+ if (required && (struct_def.fixed || IsScalar(type.base_type))) {
+ return Error("only non-scalar fields in tables may be 'required'");
+ }
+ if (field->key) {
+ if (struct_def.has_key) return Error("only one field may be set as 'key'");
+ struct_def.has_key = true;
+ if (!IsScalar(type.base_type) && !IsString(type)) {
+ return Error("'key' field must be string or scalar type");
+ }
+ }
+
+ if (field->IsScalarOptional()) {
+ advanced_features_ |= reflection::OptionalScalars;
+ if (type.enum_def && type.enum_def->Lookup("null")) {
+ FLATBUFFERS_ASSERT(IsInteger(type.base_type));
+ return Error(
+ "the default 'null' is reserved for declaring optional scalar "
+ "fields, it conflicts with declaration of enum '" +
+ type.enum_def->name + "'.");
+ }
+ if (field->attributes.Lookup("key")) {
+ return Error(
+ "only a non-optional scalar field can be used as a 'key' field");
+ }
+ if (!SupportsOptionalScalars()) {
+ return Error(
+ "Optional scalars are not yet supported in at least one of "
+ "the specified programming languages.");
+ }
+ }
+
+ if (type.enum_def) {
+ // Verify the enum's type and default value.
+ const std::string &constant = field->value.constant;
+ if (type.base_type == BASE_TYPE_UNION) {
+ if (constant != "0") { return Error("Union defaults must be NONE"); }
+ } else if (IsVector(type)) {
+ if (constant != "0" && constant != "[]") {
+ return Error("Vector defaults may only be `[]`.");
+ }
+ } else if (IsArray(type)) {
+ if (constant != "0") {
+ return Error("Array defaults are not supported yet.");
+ }
+ } else {
+ if (!IsInteger(type.base_type)) {
+ return Error("Enums must have integer base types");
+ }
+ // Optional and bitflags enums may have default constants that are not
+ // their specified variants.
+ if (!field->IsOptional() &&
+ type.enum_def->attributes.Lookup("bit_flags") == nullptr) {
+ if (type.enum_def->FindByValue(constant) == nullptr) {
+ return Error("default value of `" + constant + "` for " + "field `" +
+ name + "` is not part of enum `" + type.enum_def->name +
+ "`.");
+ }
+ }
+ }
+ }
+
+ if (field->deprecated && struct_def.fixed)
+ return Error("can't deprecate fields in a struct");
+
auto cpp_type = field->attributes.Lookup("cpp_type");
if (cpp_type) {
if (!hash_name)
@@ -854,28 +945,7 @@
field->attributes.Add("cpp_ptr_type", val);
}
}
- if (field->deprecated && struct_def.fixed)
- return Error("can't deprecate fields in a struct");
- field->required = field->attributes.Lookup("required") != nullptr;
- if (field->required && (struct_def.fixed || IsScalar(type.base_type)))
- return Error("only non-scalar fields in tables may be 'required'");
- if (!IsScalar(type.base_type)) {
- // For nonscalars, only required fields are non-optional.
- // At least until https://github.com/google/flatbuffers/issues/6053
- field->optional = !field->required;
- }
-
- field->key = field->attributes.Lookup("key") != nullptr;
- if (field->key) {
- if (struct_def.has_key) return Error("only one field may be set as 'key'");
- struct_def.has_key = true;
- if (!IsScalar(type.base_type)) {
- field->required = true;
- if (type.base_type != BASE_TYPE_STRING)
- return Error("'key' field must be string or scalar type");
- }
- }
field->shared = field->attributes.Lookup("shared") != nullptr;
if (field->shared && field->value.type.base_type != BASE_TYPE_STRING)
return Error("shared can only be defined on strings");
@@ -914,17 +984,28 @@
if (typefield) {
if (!IsScalar(typefield->value.type.base_type)) {
// this is a union vector field
- typefield->required = field->required;
+ typefield->presence = field->presence;
}
// If this field is a union, and it has a manually assigned id,
// the automatically added type field should have an id as well (of N - 1).
auto attr = field->attributes.Lookup("id");
if (attr) {
- auto id = atoi(attr->constant.c_str());
- auto val = new Value();
- val->type = attr->type;
- val->constant = NumToString(id - 1);
- typefield->attributes.Add("id", val);
+ const auto &id_str = attr->constant;
+ voffset_t id = 0;
+ const auto done = !atot(id_str.c_str(), *this, &id).Check();
+ if (done && id > 0) {
+ auto val = new Value();
+ val->type = attr->type;
+ val->constant = NumToString(id - 1);
+ typefield->attributes.Add("id", val);
+ } else {
+ return Error(
+ "a union type effectively adds two fields with non-negative ids, "
+ "its id must be that of the second field (the first field is "
+ "the type field and not explicitly declared in the schema);\n"
+ "field: " +
+ field->name + ", id: " + id_str);
+ }
}
// if this field is a union that is deprecated,
// the automatically added type field should be deprecated as well
@@ -1006,6 +1087,8 @@
}
if (next_name == type_name) {
EXPECT(':');
+ ParseDepthGuard depth_guard(this);
+ ECHECK(depth_guard.Check());
Value type_val = type_field->value;
ECHECK(ParseAnyValue(type_val, type_field, 0, nullptr, 0));
constant = type_val.constant;
@@ -1018,6 +1101,9 @@
}
uint8_t enum_idx;
if (vector_of_union_types) {
+ if (vector_of_union_types->size() <= count)
+ return Error("union types vector smaller than union values vector"
+ " for: " + field->name);
enum_idx = vector_of_union_types->Get(count);
} else {
ECHECK(atot(constant.c_str(), *this, &enum_idx));
@@ -1132,6 +1218,9 @@
CheckedError Parser::ParseTable(const StructDef &struct_def, std::string *value,
uoffset_t *ovalue) {
+ ParseDepthGuard depth_guard(this);
+ ECHECK(depth_guard.Check());
+
size_t fieldn_outer = 0;
auto err = ParseTableDelimiters(
fieldn_outer, &struct_def,
@@ -1167,9 +1256,7 @@
ECHECK(
ParseNestedFlatbuffer(val, field, fieldn, struct_def_inner));
} else {
- ECHECK(Recurse([&]() {
- return ParseAnyValue(val, field, fieldn, struct_def_inner, 0);
- }));
+ ECHECK(ParseAnyValue(val, field, fieldn, struct_def_inner, 0));
}
// Hardcoded insertion-sort with error-check.
// If fields are specified in order, then this loop exits
@@ -1195,7 +1282,7 @@
for (auto field_it = struct_def.fields.vec.begin();
field_it != struct_def.fields.vec.end(); ++field_it) {
auto required_field = *field_it;
- if (!required_field->required) { continue; }
+ if (!required_field->IsRequired()) { continue; }
bool found = false;
for (auto pf_it = field_stack_.end() - fieldn_outer;
pf_it != field_stack_.end(); ++pf_it) {
@@ -1227,7 +1314,7 @@
if (!struct_def.sortbysize ||
size == SizeOf(field_value.type.base_type)) {
switch (field_value.type.base_type) {
-// clang-format off
+ // clang-format off
#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, ...) \
case BASE_TYPE_ ## ENUM: \
builder_.Pad(field->padding); \
@@ -1303,22 +1390,71 @@
return NoError();
}
-static bool CompareType(const uint8_t *a, const uint8_t *b, BaseType ftype) {
- switch (ftype) {
-#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, ...) \
- case BASE_TYPE_##ENUM: return ReadScalar<CTYPE>(a) < ReadScalar<CTYPE>(b);
+static bool CompareSerializedScalars(const uint8_t *a, const uint8_t *b,
+ const FieldDef &key) {
+ switch (key.value.type.base_type) {
+#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, ...) \
+ case BASE_TYPE_##ENUM: { \
+ CTYPE def = static_cast<CTYPE>(0); \
+ if (!a || !b) { StringToNumber(key.value.constant.c_str(), &def); } \
+ const auto av = a ? ReadScalar<CTYPE>(a) : def; \
+ const auto bv = b ? ReadScalar<CTYPE>(b) : def; \
+ return av < bv; \
+ }
FLATBUFFERS_GEN_TYPES_SCALAR(FLATBUFFERS_TD)
#undef FLATBUFFERS_TD
- case BASE_TYPE_STRING:
- // Indirect offset pointer to string pointer.
- a += ReadScalar<uoffset_t>(a);
- b += ReadScalar<uoffset_t>(b);
- return *reinterpret_cast<const String *>(a) <
- *reinterpret_cast<const String *>(b);
- default: return false;
+ default: {
+ FLATBUFFERS_ASSERT(false && "scalar type expected");
+ return false;
+ }
}
}
+static bool CompareTablesByScalarKey(const Offset<Table> *_a,
+ const Offset<Table> *_b,
+ const FieldDef &key) {
+ const voffset_t offset = key.value.offset;
+ // Indirect offset pointer to table pointer.
+ auto a = reinterpret_cast<const uint8_t *>(_a) + ReadScalar<uoffset_t>(_a);
+ auto b = reinterpret_cast<const uint8_t *>(_b) + ReadScalar<uoffset_t>(_b);
+ // Fetch field address from table.
+ a = reinterpret_cast<const Table *>(a)->GetAddressOf(offset);
+ b = reinterpret_cast<const Table *>(b)->GetAddressOf(offset);
+ return CompareSerializedScalars(a, b, key);
+}
+
+static bool CompareTablesByStringKey(const Offset<Table> *_a,
+ const Offset<Table> *_b,
+ const FieldDef &key) {
+ const voffset_t offset = key.value.offset;
+ // Indirect offset pointer to table pointer.
+ auto a = reinterpret_cast<const uint8_t *>(_a) + ReadScalar<uoffset_t>(_a);
+ auto b = reinterpret_cast<const uint8_t *>(_b) + ReadScalar<uoffset_t>(_b);
+ // Fetch field address from table.
+ a = reinterpret_cast<const Table *>(a)->GetAddressOf(offset);
+ b = reinterpret_cast<const Table *>(b)->GetAddressOf(offset);
+ if (a && b) {
+ // Indirect offset pointer to string pointer.
+ a += ReadScalar<uoffset_t>(a);
+ b += ReadScalar<uoffset_t>(b);
+ return *reinterpret_cast<const String *>(a) <
+ *reinterpret_cast<const String *>(b);
+ } else {
+ return a ? true : false;
+ }
+}
+
+static void SwapSerializedTables(Offset<Table> *a, Offset<Table> *b) {
+ // These are serialized offsets, so are relative where they are
+ // stored in memory, so compute the distance between these pointers:
+ ptrdiff_t diff = (b - a) * sizeof(Offset<Table>);
+ FLATBUFFERS_ASSERT(diff >= 0); // Guaranteed by SimpleQsort.
+ auto udiff = static_cast<uoffset_t>(diff);
+ a->o = EndianScalar(ReadScalar<uoffset_t>(a) - udiff);
+ b->o = EndianScalar(ReadScalar<uoffset_t>(b) + udiff);
+ std::swap(*a, *b);
+}
+
// See below for why we need our own sort :(
template<typename T, typename F, typename S>
void SimpleQsort(T *begin, T *end, size_t width, F comparator, S swapper) {
@@ -1339,34 +1475,50 @@
SimpleQsort(r, end, width, comparator, swapper);
}
+CheckedError Parser::ParseAlignAttribute(const std::string &align_constant,
+ size_t min_align, size_t *align) {
+ // Use uint8_t to avoid problems with size_t==`unsigned long` on LP64.
+ uint8_t align_value;
+ if (StringToNumber(align_constant.c_str(), &align_value) &&
+ VerifyAlignmentRequirements(static_cast<size_t>(align_value),
+ min_align)) {
+ *align = align_value;
+ return NoError();
+ }
+ return Error("unexpected force_align value '" + align_constant +
+ "', alignment must be a power of two integer ranging from the "
+ "type\'s natural alignment " +
+ NumToString(min_align) + " to " +
+ NumToString(FLATBUFFERS_MAX_ALIGNMENT));
+}
+
CheckedError Parser::ParseVector(const Type &type, uoffset_t *ovalue,
FieldDef *field, size_t fieldn) {
uoffset_t count = 0;
auto err = ParseVectorDelimiters(count, [&](uoffset_t &) -> CheckedError {
Value val;
val.type = type;
- ECHECK(Recurse([&]() {
- return ParseAnyValue(val, field, fieldn, nullptr, count, true);
- }));
+ ECHECK(ParseAnyValue(val, field, fieldn, nullptr, count, true));
field_stack_.push_back(std::make_pair(val, nullptr));
return NoError();
});
ECHECK(err);
- const auto *force_align = field->attributes.Lookup("force_align");
- const size_t align =
- force_align ? static_cast<size_t>(atoi(force_align->constant.c_str()))
- : 1;
const size_t len = count * InlineSize(type) / InlineAlignment(type);
const size_t elemsize = InlineAlignment(type);
- if (align > 1) { builder_.ForceVectorAlignment(len, elemsize, align); }
+ const auto force_align = field->attributes.Lookup("force_align");
+ if (force_align) {
+ size_t align;
+ ECHECK(ParseAlignAttribute(force_align->constant, 1, &align));
+ if (align > 1) { builder_.ForceVectorAlignment(len, elemsize, align); }
+ }
builder_.StartVector(len, elemsize);
for (uoffset_t i = 0; i < count; i++) {
// start at the back, since we're building the data backwards.
auto &val = field_stack_.back().first;
switch (val.type.base_type) {
-// clang-format off
+ // clang-format off
#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE,...) \
case BASE_TYPE_ ## ENUM: \
if (IsStruct(val.type)) SerializeStruct(*val.type.struct_def, val); \
@@ -1405,23 +1557,21 @@
// globals, making parsing thread-unsafe.
// So for now, we use SimpleQsort above.
// TODO: replace with something better, preferably not recursive.
- voffset_t offset = key->value.offset;
- BaseType ftype = key->value.type.base_type;
if (type.struct_def->fixed) {
+ const voffset_t offset = key->value.offset;
+ const size_t struct_size = type.struct_def->bytesize;
auto v =
reinterpret_cast<VectorOfAny *>(builder_.GetCurrentBufferPointer());
SimpleQsort<uint8_t>(
v->Data(), v->Data() + v->size() * type.struct_def->bytesize,
type.struct_def->bytesize,
- [&](const uint8_t *a, const uint8_t *b) -> bool {
- return CompareType(a + offset, b + offset, ftype);
+ [offset, key](const uint8_t *a, const uint8_t *b) -> bool {
+ return CompareSerializedScalars(a + offset, b + offset, *key);
},
- [&](uint8_t *a, uint8_t *b) {
+ [struct_size](uint8_t *a, uint8_t *b) {
// FIXME: faster?
- for (size_t i = 0; i < type.struct_def->bytesize; i++) {
- std::swap(a[i], b[i]);
- }
+ for (size_t i = 0; i < struct_size; i++) { std::swap(a[i], b[i]); }
});
} else {
auto v = reinterpret_cast<Vector<Offset<Table>> *>(
@@ -1429,29 +1579,21 @@
// Here also can't use std::sort. We do have an iterator type for it,
// but it is non-standard as it will dereference the offsets, and thus
// can't be used to swap elements.
- SimpleQsort<Offset<Table>>(
- v->data(), v->data() + v->size(), 1,
- [&](const Offset<Table> *_a, const Offset<Table> *_b) -> bool {
- // Indirect offset pointer to table pointer.
- auto a = reinterpret_cast<const uint8_t *>(_a) +
- ReadScalar<uoffset_t>(_a);
- auto b = reinterpret_cast<const uint8_t *>(_b) +
- ReadScalar<uoffset_t>(_b);
- // Fetch field address from table.
- a = reinterpret_cast<const Table *>(a)->GetAddressOf(offset);
- b = reinterpret_cast<const Table *>(b)->GetAddressOf(offset);
- return CompareType(a, b, ftype);
- },
- [&](Offset<Table> *a, Offset<Table> *b) {
- // These are serialized offsets, so are relative where they are
- // stored in memory, so compute the distance between these pointers:
- ptrdiff_t diff = (b - a) * sizeof(Offset<Table>);
- FLATBUFFERS_ASSERT(diff >= 0); // Guaranteed by SimpleQsort.
- auto udiff = static_cast<uoffset_t>(diff);
- a->o = EndianScalar(ReadScalar<uoffset_t>(a) - udiff);
- b->o = EndianScalar(ReadScalar<uoffset_t>(b) + udiff);
- std::swap(*a, *b);
- });
+ if (key->value.type.base_type == BASE_TYPE_STRING) {
+ SimpleQsort<Offset<Table>>(
+ v->data(), v->data() + v->size(), 1,
+ [key](const Offset<Table> *_a, const Offset<Table> *_b) -> bool {
+ return CompareTablesByStringKey(_a, _b, *key);
+ },
+ SwapSerializedTables);
+ } else {
+ SimpleQsort<Offset<Table>>(
+ v->data(), v->data() + v->size(), 1,
+ [key](const Offset<Table> *_a, const Offset<Table> *_b) -> bool {
+ return CompareTablesByScalarKey(_a, _b, *key);
+ },
+ SwapSerializedTables);
+ }
}
}
return NoError();
@@ -1464,7 +1606,7 @@
auto length = array.type.fixed_length;
uoffset_t count = 0;
auto err = ParseVectorDelimiters(count, [&](uoffset_t &) -> CheckedError {
- vector_emplace_back(&stack, Value());
+ stack.emplace_back(Value());
auto &val = stack.back();
val.type = type;
if (IsStruct(type)) {
@@ -1508,7 +1650,13 @@
size_t fieldn,
const StructDef *parent_struct_def) {
if (token_ == '[') { // backwards compat for 'legacy' ubyte buffers
- ECHECK(ParseAnyValue(val, field, fieldn, parent_struct_def, 0));
+ if (opts.json_nested_legacy_flatbuffers) {
+ ECHECK(ParseAnyValue(val, field, fieldn, parent_struct_def, 0));
+ } else {
+ return Error(
+ "cannot parse nested_flatbuffer as bytes unless"
+ " --json-nested-bytes is set");
+ }
} else {
auto cursor_at_value_begin = cursor_;
ECHECK(SkipAnyJsonValue());
@@ -1521,7 +1669,7 @@
nested_parser.enums_ = enums_;
nested_parser.opts = opts;
nested_parser.uses_flexbuffers_ = uses_flexbuffers_;
-
+ nested_parser.parse_depth_counter_ = parse_depth_counter_;
// Parse JSON substring into new flatbuffer builder using nested_parser
bool ok = nested_parser.Parse(substring.c_str(), nullptr, nullptr);
@@ -1670,6 +1818,9 @@
#endif
CheckedError Parser::ParseFunction(const std::string *name, Value &e) {
+ ParseDepthGuard depth_guard(this);
+ ECHECK(depth_guard.Check());
+
// Copy name, attribute will be changed on NEXT().
const auto functionname = attribute_;
if (!IsFloat(e.type.base_type)) {
@@ -1680,7 +1831,7 @@
}
NEXT();
EXPECT('(');
- ECHECK(Recurse([&]() { return ParseSingleValue(name, e, false); }));
+ ECHECK(ParseSingleValue(name, e, false));
EXPECT(')');
// calculate with double precision
double x, y = 0.0;
@@ -1712,56 +1863,61 @@
CheckedError Parser::TryTypedValue(const std::string *name, int dtoken,
bool check, Value &e, BaseType req,
bool *destmatch) {
- bool match = dtoken == token_;
- if (match) {
- FLATBUFFERS_ASSERT(*destmatch == false);
- *destmatch = true;
- e.constant = attribute_;
- // Check token match
- if (!check) {
- if (e.type.base_type == BASE_TYPE_NONE) {
- e.type.base_type = req;
- } else {
- return Error(
- std::string("type mismatch: expecting: ") +
- kTypeNames[e.type.base_type] + ", found: " + kTypeNames[req] +
- ", name: " + (name ? *name : "") + ", value: " + e.constant);
- }
+ FLATBUFFERS_ASSERT(*destmatch == false && dtoken == token_);
+ *destmatch = true;
+ e.constant = attribute_;
+ // Check token match
+ if (!check) {
+ if (e.type.base_type == BASE_TYPE_NONE) {
+ e.type.base_type = req;
+ } else {
+ return Error(std::string("type mismatch: expecting: ") +
+ kTypeNames[e.type.base_type] +
+ ", found: " + kTypeNames[req] +
+ ", name: " + (name ? *name : "") + ", value: " + e.constant);
}
- // The exponent suffix of hexadecimal float-point number is mandatory.
- // A hex-integer constant is forbidden as an initializer of float number.
- if ((kTokenFloatConstant != dtoken) && IsFloat(e.type.base_type)) {
- const auto &s = e.constant;
- const auto k = s.find_first_of("0123456789.");
- if ((std::string::npos != k) && (s.length() > (k + 1)) &&
- (s[k] == '0' && is_alpha_char(s[k + 1], 'X')) &&
- (std::string::npos == s.find_first_of("pP", k + 2))) {
- return Error(
- "invalid number, the exponent suffix of hexadecimal "
- "floating-point literals is mandatory: \"" +
- s + "\"");
- }
- }
- NEXT();
}
+ // The exponent suffix of hexadecimal float-point number is mandatory.
+ // A hex-integer constant is forbidden as an initializer of float number.
+ if ((kTokenFloatConstant != dtoken) && IsFloat(e.type.base_type)) {
+ const auto &s = e.constant;
+ const auto k = s.find_first_of("0123456789.");
+ if ((std::string::npos != k) && (s.length() > (k + 1)) &&
+ (s[k] == '0' && is_alpha_char(s[k + 1], 'X')) &&
+ (std::string::npos == s.find_first_of("pP", k + 2))) {
+ return Error(
+ "invalid number, the exponent suffix of hexadecimal "
+ "floating-point literals is mandatory: \"" +
+ s + "\"");
+ }
+ }
+ NEXT();
return NoError();
}
CheckedError Parser::ParseSingleValue(const std::string *name, Value &e,
bool check_now) {
+ if (token_ == '+' || token_ == '-') {
+ const char sign = static_cast<char>(token_);
+ // Get an indentifier: NAN, INF, or function name like cos/sin/deg.
+ NEXT();
+ if (token_ != kTokenIdentifier) return Error("constant name expected");
+ attribute_.insert(0, 1, sign);
+ }
+
const auto in_type = e.type.base_type;
const auto is_tok_ident = (token_ == kTokenIdentifier);
const auto is_tok_string = (token_ == kTokenStringConstant);
- // First see if this could be a conversion function:
+ // First see if this could be a conversion function.
if (is_tok_ident && *cursor_ == '(') { return ParseFunction(name, e); }
// clang-format off
auto match = false;
#define IF_ECHECK_(force, dtoken, check, req) \
- if (!match && ((check) || IsConstTrue(force))) \
- ECHECK(TryTypedValue(name, dtoken, check, e, req, &match))
+ if (!match && ((dtoken) == token_) && ((check) || IsConstTrue(force))) \
+ ECHECK(TryTypedValue(name, dtoken, check, e, req, &match))
#define TRY_ECHECK(dtoken, check, req) IF_ECHECK_(false, dtoken, check, req)
#define FORCE_ECHECK(dtoken, check, req) IF_ECHECK_(true, dtoken, check, req)
// clang-format on
@@ -1806,7 +1962,6 @@
match = true;
}
// Parse a float/integer number from the string.
- if (!match) check_now = true; // Re-pack if parsed from string literal.
// A "scalar-in-string" value needs extra checks.
if (!match && is_tok_string && IsScalar(in_type)) {
// Strip trailing whitespaces from attribute_.
@@ -1835,6 +1990,15 @@
// Integer token can init any scalar (integer of float).
FORCE_ECHECK(kTokenIntegerConstant, IsScalar(in_type), BASE_TYPE_INT);
}
+ // Match empty vectors for default-empty-vectors.
+ if (!match && IsVector(e.type) && token_ == '[') {
+ NEXT();
+ if (token_ != ']') { return Error("Expected `]` in vector default"); }
+ NEXT();
+ match = true;
+ e.constant = "[]";
+ }
+
#undef FORCE_ECHECK
#undef TRY_ECHECK
#undef IF_ECHECK_
@@ -1892,13 +2056,8 @@
}
return struct_def;
}
- if (!definition) {
- // Search thru parent namespaces.
- for (size_t components = current_namespace_->components.size();
- components && !struct_def; components--) {
- struct_def = LookupStruct(
- current_namespace_->GetFullyQualifiedName(name, components - 1));
- }
+ if (!definition && !struct_def) {
+ struct_def = LookupStructThruParentNamespaces(name);
}
if (!struct_def && create_if_new) {
struct_def = new StructDef();
@@ -1978,10 +2137,14 @@
auto &v = vals.vec;
if (IsUInt64())
std::sort(v.begin(), v.end(), [](const EnumVal *e1, const EnumVal *e2) {
+ if (e1->GetAsUInt64() == e2->GetAsUInt64()) {
+ return e1->name < e2->name;
+ }
return e1->GetAsUInt64() < e2->GetAsUInt64();
});
else
std::sort(v.begin(), v.end(), [](const EnumVal *e1, const EnumVal *e2) {
+ if (e1->GetAsInt64() == e2->GetAsInt64()) { return e1->name < e2->name; }
return e1->GetAsInt64() < e2->GetAsInt64();
});
}
@@ -2111,13 +2274,18 @@
bool user_value;
};
-CheckedError Parser::ParseEnum(const bool is_union, EnumDef **dest) {
+CheckedError Parser::ParseEnum(const bool is_union, EnumDef **dest,
+ const char *filename) {
std::vector<std::string> enum_comment = doc_comment_;
NEXT();
std::string enum_name = attribute_;
EXPECT(kTokenIdentifier);
EnumDef *enum_def;
ECHECK(StartEnum(enum_name, is_union, &enum_def));
+ if (filename != nullptr && !opts.project_root.empty()) {
+ enum_def->declaration_file =
+ &GetPooledString(RelativeToRootPath(opts.project_root, filename));
+ }
enum_def->doc_comment = enum_comment;
if (!is_union && !opts.proto_mode) {
// Give specialized error message, since this type spec used to
@@ -2237,14 +2405,18 @@
}
if (dest) *dest = enum_def;
- types_.Add(current_namespace_->GetFullyQualifiedName(enum_def->name),
- new Type(BASE_TYPE_UNION, nullptr, enum_def));
+ const auto qualified_name =
+ current_namespace_->GetFullyQualifiedName(enum_def->name);
+ if (types_.Add(qualified_name, new Type(BASE_TYPE_UNION, nullptr, enum_def)))
+ return Error("datatype already exists: " + qualified_name);
return NoError();
}
CheckedError Parser::StartStruct(const std::string &name, StructDef **dest) {
auto &struct_def = *LookupCreateStruct(name, true, true);
- if (!struct_def.predecl) return Error("datatype already exists: " + name);
+ if (!struct_def.predecl)
+ return Error("datatype already exists: " +
+ current_namespace_->GetFullyQualifiedName(name));
struct_def.predecl = false;
struct_def.name = name;
struct_def.file = file_being_parsed_;
@@ -2280,31 +2452,34 @@
static FLATBUFFERS_CONSTEXPR unsigned long supported_langs =
IDLOptions::kRust | IDLOptions::kSwift | IDLOptions::kLobster |
IDLOptions::kKotlin | IDLOptions::kCpp | IDLOptions::kJava |
- IDLOptions::kCSharp | IDLOptions::kTs | IDLOptions::kJs |
- IDLOptions::kBinary;
+ IDLOptions::kCSharp | IDLOptions::kTs | IDLOptions::kBinary |
+ IDLOptions::kGo;
unsigned long langs = opts.lang_to_generate;
return (langs > 0 && langs < IDLOptions::kMAX) && !(langs & ~supported_langs);
}
-
bool Parser::SupportsOptionalScalars() const {
// Check in general if a language isn't specified.
return opts.lang_to_generate == 0 || SupportsOptionalScalars(opts);
}
+bool Parser::SupportsDefaultVectorsAndStrings() const {
+ static FLATBUFFERS_CONSTEXPR unsigned long supported_langs =
+ IDLOptions::kRust | IDLOptions::kSwift;
+ return !(opts.lang_to_generate & ~supported_langs);
+}
+
bool Parser::SupportsAdvancedUnionFeatures() const {
- return opts.lang_to_generate != 0 &&
- (opts.lang_to_generate &
- ~(IDLOptions::kCpp | IDLOptions::kJs | IDLOptions::kTs |
- IDLOptions::kPhp | IDLOptions::kJava | IDLOptions::kCSharp |
- IDLOptions::kKotlin | IDLOptions::kBinary | IDLOptions::kSwift)) ==
- 0;
+ return (opts.lang_to_generate &
+ ~(IDLOptions::kCpp | IDLOptions::kTs | IDLOptions::kPhp |
+ IDLOptions::kJava | IDLOptions::kCSharp | IDLOptions::kKotlin |
+ IDLOptions::kBinary | IDLOptions::kSwift)) == 0;
}
bool Parser::SupportsAdvancedArrayFeatures() const {
return (opts.lang_to_generate &
~(IDLOptions::kCpp | IDLOptions::kPython | IDLOptions::kJava |
IDLOptions::kCSharp | IDLOptions::kJsonSchema | IDLOptions::kJson |
- IDLOptions::kBinary)) == 0;
+ IDLOptions::kBinary | IDLOptions::kRust)) == 0;
}
Namespace *Parser::UniqueNamespace(Namespace *ns) {
@@ -2339,7 +2514,7 @@
return a_id < b_id;
}
-CheckedError Parser::ParseDecl() {
+CheckedError Parser::ParseDecl(const char *filename) {
std::vector<std::string> dc = doc_comment_;
bool fixed = IsIdent("struct");
if (!fixed && !IsIdent("table")) return Error("declaration expected");
@@ -2350,22 +2525,21 @@
ECHECK(StartStruct(name, &struct_def));
struct_def->doc_comment = dc;
struct_def->fixed = fixed;
+ if (filename && !opts.project_root.empty()) {
+ struct_def->declaration_file =
+ &GetPooledString(RelativeToRootPath(opts.project_root, filename));
+ }
ECHECK(ParseMetaData(&struct_def->attributes));
struct_def->sortbysize =
struct_def->attributes.Lookup("original_order") == nullptr && !fixed;
EXPECT('{');
while (token_ != '}') ECHECK(ParseField(*struct_def));
- auto force_align = struct_def->attributes.Lookup("force_align");
if (fixed) {
+ const auto force_align = struct_def->attributes.Lookup("force_align");
if (force_align) {
- auto align = static_cast<size_t>(atoi(force_align->constant.c_str()));
- if (force_align->type.base_type != BASE_TYPE_INT ||
- align < struct_def->minalign || align > FLATBUFFERS_MAX_ALIGNMENT ||
- align & (align - 1))
- return Error(
- "force_align must be a power of two integer ranging from the"
- "struct\'s natural alignment to " +
- NumToString(FLATBUFFERS_MAX_ALIGNMENT));
+ size_t align;
+ ECHECK(ParseAlignAttribute(force_align->constant, struct_def->minalign,
+ &align));
struct_def->minalign = align;
}
if (!struct_def->bytesize) return Error("size 0 structs not allowed");
@@ -2395,11 +2569,25 @@
// been specified.
std::sort(fields.begin(), fields.end(), compareFieldDefs);
// Verify we have a contiguous set, and reassign vtable offsets.
- for (int i = 0; i < static_cast<int>(fields.size()); i++) {
- if (i != atoi(fields[i]->attributes.Lookup("id")->constant.c_str()))
+ FLATBUFFERS_ASSERT(fields.size() <=
+ flatbuffers::numeric_limits<voffset_t>::max());
+ for (voffset_t i = 0; i < static_cast<voffset_t>(fields.size()); i++) {
+ auto &field = *fields[i];
+ const auto &id_str = field.attributes.Lookup("id")->constant;
+ // Metadata values have a dynamic type, they can be `float`, 'int', or
+ // 'string`.
+ // The FieldIndexToOffset(i) expects the voffset_t so `id` is limited by
+ // this type.
+ voffset_t id = 0;
+ const auto done = !atot(id_str.c_str(), *this, &id).Check();
+ if (!done)
+ return Error("field id\'s must be non-negative number, field: " +
+ field.name + ", id: " + id_str);
+ if (i != id)
return Error("field id\'s must be consecutive from 0, id " +
- NumToString(i) + " missing or set twice");
- fields[i]->value.offset = FieldIndexToOffset(static_cast<voffset_t>(i));
+ NumToString(i) + " missing or set twice, field: " +
+ field.name + ", id: " + id_str);
+ field.value.offset = FieldIndexToOffset(i);
}
}
}
@@ -2412,12 +2600,15 @@
ECHECK(CheckClash(fields, struct_def, "_byte_vector", BASE_TYPE_STRING));
ECHECK(CheckClash(fields, struct_def, "ByteVector", BASE_TYPE_STRING));
EXPECT('}');
- types_.Add(current_namespace_->GetFullyQualifiedName(struct_def->name),
- new Type(BASE_TYPE_STRUCT, struct_def, nullptr));
+ const auto qualified_name =
+ current_namespace_->GetFullyQualifiedName(struct_def->name);
+ if (types_.Add(qualified_name,
+ new Type(BASE_TYPE_STRUCT, struct_def, nullptr)))
+ return Error("datatype already exists: " + qualified_name);
return NoError();
}
-CheckedError Parser::ParseService() {
+CheckedError Parser::ParseService(const char *filename) {
std::vector<std::string> service_comment = doc_comment_;
NEXT();
auto service_name = attribute_;
@@ -2427,6 +2618,10 @@
service_def.file = file_being_parsed_;
service_def.doc_comment = service_comment;
service_def.defined_namespace = current_namespace_;
+ if (filename != nullptr && !opts.project_root.empty()) {
+ service_def.declaration_file =
+ &GetPooledString(RelativeToRootPath(opts.project_root, filename));
+ }
if (services_.Add(current_namespace_->GetFullyQualifiedName(service_name),
&service_def))
return Error("service already exists: " + service_name);
@@ -2542,7 +2737,7 @@
} else if (IsIdent("enum")) {
// These are almost the same, just with different terminator:
EnumDef *enum_def;
- ECHECK(ParseEnum(false, &enum_def));
+ ECHECK(ParseEnum(false, &enum_def, nullptr));
if (Is(';')) NEXT();
// Temp: remove any duplicates, as .fbs files can't handle them.
enum_def->RemoveDuplicates();
@@ -2565,17 +2760,17 @@
return NoError();
}
-CheckedError Parser::StartEnum(const std::string &enum_name, bool is_union,
+CheckedError Parser::StartEnum(const std::string &name, bool is_union,
EnumDef **dest) {
auto &enum_def = *new EnumDef();
- enum_def.name = enum_name;
+ enum_def.name = name;
enum_def.file = file_being_parsed_;
enum_def.doc_comment = doc_comment_;
enum_def.is_union = is_union;
enum_def.defined_namespace = current_namespace_;
- if (enums_.Add(current_namespace_->GetFullyQualifiedName(enum_name),
- &enum_def))
- return Error("enum already exists: " + enum_name);
+ const auto qualified_name = current_namespace_->GetFullyQualifiedName(name);
+ if (enums_.Add(qualified_name, &enum_def))
+ return Error("enum already exists: " + qualified_name);
enum_def.underlying_type.base_type =
is_union ? BASE_TYPE_UTYPE : BASE_TYPE_INT;
enum_def.underlying_type.enum_def = &enum_def;
@@ -2634,11 +2829,11 @@
if (IsIdent("group") || oneof) {
if (!oneof) NEXT();
if (oneof && opts.proto_oneof_union) {
- auto name = MakeCamel(attribute_, true) + "Union";
+ auto name = ConvertCase(attribute_, Case::kUpperCamel) + "Union";
ECHECK(StartEnum(name, true, &oneof_union));
type = Type(BASE_TYPE_UNION, nullptr, oneof_union);
} else {
- auto name = "Anonymous" + NumToString(anonymous_counter++);
+ auto name = "Anonymous" + NumToString(anonymous_counter_++);
ECHECK(StartStruct(name, &anonymous_struct));
type = Type(BASE_TYPE_STRUCT, anonymous_struct);
}
@@ -2674,7 +2869,9 @@
}
if (!field) ECHECK(AddField(*struct_def, name, type, &field));
field->doc_comment = field_comment;
- if (!IsScalar(type.base_type)) field->required = required;
+ if (!IsScalar(type.base_type) && required) {
+ field->presence = FieldDef::kRequired;
+ }
// See if there's a default specified.
if (Is('[')) {
NEXT();
@@ -2811,22 +3008,24 @@
}
CheckedError Parser::SkipAnyJsonValue() {
+ ParseDepthGuard depth_guard(this);
+ ECHECK(depth_guard.Check());
+
switch (token_) {
case '{': {
size_t fieldn_outer = 0;
- return ParseTableDelimiters(
- fieldn_outer, nullptr,
- [&](const std::string &, size_t &fieldn,
- const StructDef *) -> CheckedError {
- ECHECK(Recurse([&]() { return SkipAnyJsonValue(); }));
- fieldn++;
- return NoError();
- });
+ return ParseTableDelimiters(fieldn_outer, nullptr,
+ [&](const std::string &, size_t &fieldn,
+ const StructDef *) -> CheckedError {
+ ECHECK(SkipAnyJsonValue());
+ fieldn++;
+ return NoError();
+ });
}
case '[': {
uoffset_t count = 0;
return ParseVectorDelimiters(count, [&](uoffset_t &) -> CheckedError {
- return Recurse([&]() { return SkipAnyJsonValue(); });
+ return SkipAnyJsonValue();
});
}
case kTokenStringConstant:
@@ -2841,7 +3040,19 @@
return NoError();
}
+CheckedError Parser::ParseFlexBufferNumericConstant(
+ flexbuffers::Builder *builder) {
+ double d;
+ if (!StringToNumber(attribute_.c_str(), &d))
+ return Error("unexpected floating-point constant: " + attribute_);
+ builder->Double(d);
+ return NoError();
+}
+
CheckedError Parser::ParseFlexBufferValue(flexbuffers::Builder *builder) {
+ ParseDepthGuard depth_guard(this);
+ ECHECK(depth_guard.Check());
+
switch (token_) {
case '{': {
auto start = builder->StartMap();
@@ -2885,6 +3096,18 @@
EXPECT(kTokenFloatConstant);
break;
}
+ case '-':
+ case '+': {
+ // `[-+]?(nan|inf|infinity)`, see ParseSingleValue().
+ const auto sign = static_cast<char>(token_);
+ NEXT();
+ if (token_ != kTokenIdentifier)
+ return Error("floating-point constant expected");
+ attribute_.insert(0, 1, sign);
+ ECHECK(ParseFlexBufferNumericConstant(builder));
+ NEXT();
+ break;
+ }
default:
if (IsIdent("true")) {
builder->Bool(true);
@@ -2895,6 +3118,9 @@
} else if (IsIdent("null")) {
builder->Null();
NEXT();
+ } else if (IsIdent("inf") || IsIdent("infinity") || IsIdent("nan")) {
+ ECHECK(ParseFlexBufferNumericConstant(builder));
+ NEXT();
} else
return TokenError();
}
@@ -2903,15 +3129,19 @@
bool Parser::ParseFlexBuffer(const char *source, const char *source_filename,
flexbuffers::Builder *builder) {
+ const auto initial_depth = parse_depth_counter_;
+ (void)initial_depth;
auto ok = !StartParseFile(source, source_filename).Check() &&
!ParseFlexBufferValue(builder).Check();
if (ok) builder->Finish();
+ FLATBUFFERS_ASSERT(initial_depth == parse_depth_counter_);
return ok;
}
bool Parser::Parse(const char *source, const char **include_paths,
const char *source_filename) {
- FLATBUFFERS_ASSERT(0 == recurse_protection_counter);
+ const auto initial_depth = parse_depth_counter_;
+ (void)initial_depth;
bool r;
if (opts.use_flexbuffers) {
@@ -2919,16 +3149,17 @@
} else {
r = !ParseRoot(source, include_paths, source_filename).Check();
}
- FLATBUFFERS_ASSERT(0 == recurse_protection_counter);
+ FLATBUFFERS_ASSERT(initial_depth == parse_depth_counter_);
return r;
}
bool Parser::ParseJson(const char *json, const char *json_filename) {
- FLATBUFFERS_ASSERT(0 == recurse_protection_counter);
+ const auto initial_depth = parse_depth_counter_;
+ (void)initial_depth;
builder_.Clear();
const auto done =
!StartParseFile(json, json_filename).Check() && !DoParseJson().Check();
- FLATBUFFERS_ASSERT(0 == recurse_protection_counter);
+ FLATBUFFERS_ASSERT(initial_depth == parse_depth_counter_);
return done;
}
@@ -3014,7 +3245,7 @@
for (auto val_it = enum_def.Vals().begin();
val_it != enum_def.Vals().end(); ++val_it) {
auto &val = **val_it;
- if (!SupportsAdvancedUnionFeatures() &&
+ if (!(opts.lang_to_generate != 0 && SupportsAdvancedUnionFeatures()) &&
(IsStruct(val.union_type) || IsString(val.union_type)))
return Error(
"only tables can be union elements in the generated language: " +
@@ -3022,16 +3253,38 @@
}
}
}
+ // Parse JSON object only if the scheme has been parsed.
+ if (token_ == '{') { ECHECK(DoParseJson()); }
+ EXPECT(kTokenEof);
return NoError();
}
+// Generate a unique hash for a file based on its name and contents (if any).
+static uint64_t HashFile(const char *source_filename, const char *source) {
+ uint64_t hash = 0;
+
+ if (source_filename)
+ hash = HashFnv1a<uint64_t>(StripPath(source_filename).c_str());
+
+ if (source && *source) hash ^= HashFnv1a<uint64_t>(source);
+
+ return hash;
+}
+
CheckedError Parser::DoParse(const char *source, const char **include_paths,
const char *source_filename,
const char *include_filename) {
+ uint64_t source_hash = 0;
if (source_filename) {
- if (included_files_.find(source_filename) == included_files_.end()) {
- included_files_[source_filename] =
- include_filename ? include_filename : "";
+ // If the file is in-memory, don't include its contents in the hash as we
+ // won't be able to load them later.
+ if (FileExists(source_filename))
+ source_hash = HashFile(source_filename, source);
+ else
+ source_hash = HashFile(source_filename, nullptr);
+
+ if (included_files_.find(source_hash) == included_files_.end()) {
+ included_files_[source_hash] = include_filename ? include_filename : "";
files_included_per_file_[source_filename] = std::set<std::string>();
} else {
return NoError();
@@ -3056,7 +3309,7 @@
ECHECK(ParseProtoDecl());
} else if (IsIdent("native_include")) {
NEXT();
- vector_emplace_back(&native_included_files_, attribute_);
+ native_included_files_.emplace_back(attribute_);
EXPECT(kTokenStringConstant);
EXPECT(';');
} else if (IsIdent("include") || (opts.proto_mode && IsIdent("import"))) {
@@ -3064,22 +3317,32 @@
if (opts.proto_mode && attribute_ == "public") NEXT();
auto name = flatbuffers::PosixPath(attribute_.c_str());
EXPECT(kTokenStringConstant);
- // Look for the file in include_paths.
+ // Look for the file relative to the directory of the current file.
std::string filepath;
- for (auto paths = include_paths; paths && *paths; paths++) {
- filepath = flatbuffers::ConCatPathFileName(*paths, name);
- if (FileExists(filepath.c_str())) break;
+ if (source_filename) {
+ auto source_file_directory =
+ flatbuffers::StripFileName(source_filename);
+ filepath = flatbuffers::ConCatPathFileName(source_file_directory, name);
+ }
+ if (filepath.empty() || !FileExists(filepath.c_str())) {
+ // Look for the file in include_paths.
+ for (auto paths = include_paths; paths && *paths; paths++) {
+ filepath = flatbuffers::ConCatPathFileName(*paths, name);
+ if (FileExists(filepath.c_str())) break;
+ }
}
if (filepath.empty())
return Error("unable to locate include file: " + name);
if (source_filename)
files_included_per_file_[source_filename].insert(filepath);
- if (included_files_.find(filepath) == included_files_.end()) {
+
+ std::string contents;
+ bool file_loaded = LoadFile(filepath.c_str(), true, &contents);
+ if (included_files_.find(HashFile(filepath.c_str(), contents.c_str())) ==
+ included_files_.end()) {
// We found an include file that we have not parsed yet.
- // Load it and parse it.
- std::string contents;
- if (!LoadFile(filepath.c_str(), true, &contents))
- return Error("unable to load include file: " + name);
+ // Parse it.
+ if (!file_loaded) return Error("unable to load include file: " + name);
ECHECK(DoParse(contents.c_str(), include_paths, filepath.c_str(),
name.c_str()));
// We generally do not want to output code for any included files:
@@ -3096,7 +3359,7 @@
// entered into included_files_.
// This is recursive, but only go as deep as the number of include
// statements.
- if (source_filename) { included_files_.erase(source_filename); }
+ included_files_.erase(source_hash);
return DoParse(source, include_paths, source_filename,
include_filename);
}
@@ -3112,11 +3375,11 @@
} else if (IsIdent("namespace")) {
ECHECK(ParseNamespace());
} else if (token_ == '{') {
- ECHECK(DoParseJson());
+ return NoError();
} else if (IsIdent("enum")) {
- ECHECK(ParseEnum(false, nullptr));
+ ECHECK(ParseEnum(false, nullptr, source_filename));
} else if (IsIdent("union")) {
- ECHECK(ParseEnum(true, nullptr));
+ ECHECK(ParseEnum(true, nullptr, source_filename));
} else if (IsIdent("root_type")) {
NEXT();
auto root_type = attribute_;
@@ -3132,9 +3395,9 @@
NEXT();
file_identifier_ = attribute_;
EXPECT(kTokenStringConstant);
- if (file_identifier_.length() != FlatBufferBuilder::kFileIdentifierLength)
+ if (file_identifier_.length() != flatbuffers::kFileIdentifierLength)
return Error("file_identifier must be exactly " +
- NumToString(FlatBufferBuilder::kFileIdentifierLength) +
+ NumToString(flatbuffers::kFileIdentifierLength) +
" characters");
EXPECT(';');
} else if (IsIdent("file_extension")) {
@@ -3155,21 +3418,22 @@
EXPECT(';');
known_attributes_[name] = false;
} else if (IsIdent("rpc_service")) {
- ECHECK(ParseService());
+ ECHECK(ParseService(source_filename));
} else {
- ECHECK(ParseDecl());
+ ECHECK(ParseDecl(source_filename));
}
}
+ if (opts.warnings_as_errors && has_warning_) {
+ return Error("treating warnings as errors, failed due to above warnings");
+ }
return NoError();
}
-CheckedError Parser::DoParseJson()
-{
+CheckedError Parser::DoParseJson() {
if (token_ != '{') {
EXPECT('{');
} else {
- if (!root_struct_def_)
- return Error("no root type set to parse json with");
+ if (!root_struct_def_) return Error("no root type set to parse json with");
if (builder_.GetSize()) {
return Error("cannot have more than one json object in a file");
}
@@ -3181,8 +3445,8 @@
file_identifier_.length() ? file_identifier_.c_str() : nullptr);
} else {
builder_.Finish(Offset<Table>(toff), file_identifier_.length()
- ? file_identifier_.c_str()
- : nullptr);
+ ? file_identifier_.c_str()
+ : nullptr);
}
}
// Check that JSON file doesn't contain more objects or IDL directives.
@@ -3236,31 +3500,63 @@
AssignIndices(structs_.vec);
AssignIndices(enums_.vec);
std::vector<Offset<reflection::Object>> object_offsets;
+ std::set<std::string> files;
for (auto it = structs_.vec.begin(); it != structs_.vec.end(); ++it) {
auto offset = (*it)->Serialize(&builder_, *this);
object_offsets.push_back(offset);
(*it)->serialized_location = offset.o;
+ const std::string *file = (*it)->declaration_file;
+ if (file) files.insert(*file);
}
std::vector<Offset<reflection::Enum>> enum_offsets;
for (auto it = enums_.vec.begin(); it != enums_.vec.end(); ++it) {
auto offset = (*it)->Serialize(&builder_, *this);
enum_offsets.push_back(offset);
- (*it)->serialized_location = offset.o;
+ const std::string *file = (*it)->declaration_file;
+ if (file) files.insert(*file);
}
std::vector<Offset<reflection::Service>> service_offsets;
for (auto it = services_.vec.begin(); it != services_.vec.end(); ++it) {
auto offset = (*it)->Serialize(&builder_, *this);
service_offsets.push_back(offset);
- (*it)->serialized_location = offset.o;
+ const std::string *file = (*it)->declaration_file;
+ if (file) files.insert(*file);
}
- auto objs__ = builder_.CreateVectorOfSortedTables(&object_offsets);
- auto enum__ = builder_.CreateVectorOfSortedTables(&enum_offsets);
- auto fiid__ = builder_.CreateString(file_identifier_);
- auto fext__ = builder_.CreateString(file_extension_);
- auto serv__ = builder_.CreateVectorOfSortedTables(&service_offsets);
- auto schema_offset = reflection::CreateSchema(
+
+ // Create Schemafiles vector of tables.
+ flatbuffers::Offset<
+ flatbuffers::Vector<flatbuffers::Offset<reflection::SchemaFile>>>
+ schema_files__;
+ if (!opts.project_root.empty()) {
+ std::vector<Offset<reflection::SchemaFile>> schema_files;
+ std::vector<Offset<flatbuffers::String>> included_files;
+ for (auto f = files_included_per_file_.begin();
+ f != files_included_per_file_.end(); f++) {
+ const auto filename__ = builder_.CreateSharedString(
+ RelativeToRootPath(opts.project_root, f->first));
+ for (auto i = f->second.begin(); i != f->second.end(); i++) {
+ included_files.push_back(builder_.CreateSharedString(
+ RelativeToRootPath(opts.project_root, *i)));
+ }
+ const auto included_files__ = builder_.CreateVector(included_files);
+ included_files.clear();
+
+ schema_files.push_back(
+ reflection::CreateSchemaFile(builder_, filename__, included_files__));
+ }
+ schema_files__ = builder_.CreateVectorOfSortedTables(&schema_files);
+ }
+
+ const auto objs__ = builder_.CreateVectorOfSortedTables(&object_offsets);
+ const auto enum__ = builder_.CreateVectorOfSortedTables(&enum_offsets);
+ const auto fiid__ = builder_.CreateString(file_identifier_);
+ const auto fext__ = builder_.CreateString(file_extension_);
+ const auto serv__ = builder_.CreateVectorOfSortedTables(&service_offsets);
+ const auto schema_offset = reflection::CreateSchema(
builder_, objs__, enum__, fiid__, fext__,
- (root_struct_def_ ? root_struct_def_->serialized_location : 0), serv__);
+ (root_struct_def_ ? root_struct_def_->serialized_location : 0), serv__,
+ static_cast<reflection::AdvancedFeatures>(advanced_features_),
+ schema_files__);
if (opts.size_prefixed) {
builder_.FinishSizePrefixed(schema_offset, reflection::SchemaIdentifier());
} else {
@@ -3301,16 +3597,18 @@
field_offsets.push_back((*it)->Serialize(
builder, static_cast<uint16_t>(it - fields.vec.begin()), parser));
}
- auto qualified_name = defined_namespace->GetFullyQualifiedName(name);
- auto name__ = builder->CreateString(qualified_name);
- auto flds__ = builder->CreateVectorOfSortedTables(&field_offsets);
- auto attr__ = SerializeAttributes(builder, parser);
- auto docs__ = parser.opts.binary_schema_comments
- ? builder->CreateVectorOfStrings(doc_comment)
- : 0;
- return reflection::CreateObject(*builder, name__, flds__, fixed,
- static_cast<int>(minalign),
- static_cast<int>(bytesize), attr__, docs__);
+ const auto qualified_name = defined_namespace->GetFullyQualifiedName(name);
+ const auto name__ = builder->CreateString(qualified_name);
+ const auto flds__ = builder->CreateVectorOfSortedTables(&field_offsets);
+ const auto attr__ = SerializeAttributes(builder, parser);
+ const auto docs__ = parser.opts.binary_schema_comments
+ ? builder->CreateVectorOfStrings(doc_comment)
+ : 0;
+ std::string decl_file_in_project = declaration_file ? *declaration_file : "";
+ const auto file__ = builder->CreateSharedString(decl_file_in_project);
+ return reflection::CreateObject(
+ *builder, name__, flds__, fixed, static_cast<int>(minalign),
+ static_cast<int>(bytesize), attr__, docs__, file__);
}
bool StructDef::Deserialize(Parser &parser, const reflection::Object *object) {
@@ -3363,8 +3661,8 @@
// Is uint64>max(int64) tested?
IsInteger(value.type.base_type) ? StringToInt(value.constant.c_str()) : 0,
// result may be platform-dependent if underlying is float (not double)
- IsFloat(value.type.base_type) ? d : 0.0, deprecated, required, key,
- attr__, docs__, optional);
+ IsFloat(value.type.base_type) ? d : 0.0, deprecated, IsRequired(), key,
+ attr__, docs__, IsOptional(), static_cast<uint16_t>(padding));
// TODO: value.constant is almost always "0", we could save quite a bit of
// space by sharing it. Same for common values of value.type.
}
@@ -3379,8 +3677,8 @@
} else if (IsFloat(value.type.base_type)) {
value.constant = FloatToString(field->default_real(), 16);
}
- deprecated = field->deprecated();
- required = field->required();
+ presence = FieldDef::MakeFieldPresence(field->optional(), field->required());
+ padding = field->padding();
key = field->key();
if (!DeserializeAttributes(parser, field->attributes())) return false;
// TODO: this should probably be handled by a separate attribute
@@ -3430,14 +3728,17 @@
for (auto it = calls.vec.begin(); it != calls.vec.end(); ++it) {
servicecall_offsets.push_back((*it)->Serialize(builder, parser));
}
- auto qualified_name = defined_namespace->GetFullyQualifiedName(name);
- auto name__ = builder->CreateString(qualified_name);
- auto call__ = builder->CreateVector(servicecall_offsets);
- auto attr__ = SerializeAttributes(builder, parser);
- auto docs__ = parser.opts.binary_schema_comments
- ? builder->CreateVectorOfStrings(doc_comment)
- : 0;
- return reflection::CreateService(*builder, name__, call__, attr__, docs__);
+ const auto qualified_name = defined_namespace->GetFullyQualifiedName(name);
+ const auto name__ = builder->CreateString(qualified_name);
+ const auto call__ = builder->CreateVector(servicecall_offsets);
+ const auto attr__ = SerializeAttributes(builder, parser);
+ const auto docs__ = parser.opts.binary_schema_comments
+ ? builder->CreateVectorOfStrings(doc_comment)
+ : 0;
+ std::string decl_file_in_project = declaration_file ? *declaration_file : "";
+ const auto file__ = builder->CreateSharedString(decl_file_in_project);
+ return reflection::CreateService(*builder, name__, call__, attr__, docs__,
+ file__);
}
bool ServiceDef::Deserialize(Parser &parser,
@@ -3464,16 +3765,18 @@
for (auto it = vals.vec.begin(); it != vals.vec.end(); ++it) {
enumval_offsets.push_back((*it)->Serialize(builder, parser));
}
- auto qualified_name = defined_namespace->GetFullyQualifiedName(name);
- auto name__ = builder->CreateString(qualified_name);
- auto vals__ = builder->CreateVector(enumval_offsets);
- auto type__ = underlying_type.Serialize(builder);
- auto attr__ = SerializeAttributes(builder, parser);
- auto docs__ = parser.opts.binary_schema_comments
- ? builder->CreateVectorOfStrings(doc_comment)
- : 0;
+ const auto qualified_name = defined_namespace->GetFullyQualifiedName(name);
+ const auto name__ = builder->CreateString(qualified_name);
+ const auto vals__ = builder->CreateVector(enumval_offsets);
+ const auto type__ = underlying_type.Serialize(builder);
+ const auto attr__ = SerializeAttributes(builder, parser);
+ const auto docs__ = parser.opts.binary_schema_comments
+ ? builder->CreateVectorOfStrings(doc_comment)
+ : 0;
+ std::string decl_file_in_project = declaration_file ? *declaration_file : "";
+ const auto file__ = builder->CreateSharedString(decl_file_in_project);
return reflection::CreateEnum(*builder, name__, vals__, is_union, type__,
- attr__, docs__);
+ attr__, docs__, file__);
}
bool EnumDef::Deserialize(Parser &parser, const reflection::Enum *_enum) {
@@ -3502,10 +3805,7 @@
auto docs__ = parser.opts.binary_schema_comments
? builder->CreateVectorOfStrings(doc_comment)
: 0;
- return reflection::CreateEnumVal(
- *builder, name__, value,
- union_type.struct_def ? union_type.struct_def->serialized_location : 0,
- type__, docs__);
+ return reflection::CreateEnumVal(*builder, name__, value, type__, docs__);
}
bool EnumVal::Deserialize(const Parser &parser,
@@ -3522,7 +3822,8 @@
*builder, static_cast<reflection::BaseType>(base_type),
static_cast<reflection::BaseType>(element),
struct_def ? struct_def->index : (enum_def ? enum_def->index : -1),
- fixed_length);
+ fixed_length, static_cast<uint32_t>(SizeOf(base_type)),
+ static_cast<uint32_t>(SizeOf(element)));
}
bool Type::Deserialize(const Parser &parser, const reflection::Type *type) {
@@ -3678,6 +3979,16 @@
}
}
}
+ advanced_features_ = schema->advanced_features();
+
+ if (schema->fbs_files())
+ for (auto s = schema->fbs_files()->begin(); s != schema->fbs_files()->end();
+ ++s) {
+ for (auto f = s->included_filenames()->begin();
+ f != s->included_filenames()->end(); ++f) {
+ files_included_per_file_[s->filename()->str()].insert(f->str());
+ }
+ }
return true;
}
diff --git a/src/namer.h b/src/namer.h
new file mode 100644
index 0000000..6c539cb
--- /dev/null
+++ b/src/namer.h
@@ -0,0 +1,217 @@
+#ifndef FLATBUFFERS_NAMER
+#define FLATBUFFERS_NAMER
+
+#include "flatbuffers/idl.h"
+#include "flatbuffers/util.h"
+
+namespace flatbuffers {
+
+// Options for Namer::File.
+enum class SkipFile {
+ None = 0,
+ Suffix = 1,
+ Extension = 2,
+ SuffixAndExtension = 3,
+};
+inline SkipFile operator&(SkipFile a, SkipFile b) {
+ return static_cast<SkipFile>(static_cast<int>(a) & static_cast<int>(b));
+}
+// Options for Namer::Directories
+enum class SkipDir {
+ None = 0,
+ // Skip prefixing the -o $output_path.
+ OutputPath = 1,
+ // Skip trailing path seperator.
+ TrailingPathSeperator = 2,
+ OutputPathAndTrailingPathSeparator = 3,
+};
+inline SkipDir operator&(SkipDir a, SkipDir b) {
+ return static_cast<SkipDir>(static_cast<int>(a) & static_cast<int>(b));
+}
+
+// `Namer` applies style configuration to symbols in generated code. It manages
+// casing, escapes keywords, and object API naming.
+// TODO: Refactor all code generators to use this.
+class Namer {
+ public:
+ struct Config {
+ // Symbols in code.
+
+ // Case style for flatbuffers-defined types.
+ // e.g. `class TableA {}`
+ Case types;
+ // Case style for flatbuffers-defined constants.
+ // e.g. `uint64_t ENUM_A_MAX`;
+ Case constants;
+ // Case style for flatbuffers-defined methods.
+ // e.g. `class TableA { int field_a(); }`
+ Case methods;
+ // Case style for flatbuffers-defined functions.
+ // e.g. `TableA* get_table_a_root()`;
+ Case functions;
+ // Case style for flatbuffers-defined fields.
+ // e.g. `struct Struct { int my_field; }`
+ Case fields;
+ // Case style for flatbuffers-defined variables.
+ // e.g. `int my_variable = 2`
+ Case variables;
+ // Case style for flatbuffers-defined variants.
+ // e.g. `enum class Enum { MyVariant, }`
+ Case variants;
+ // Seperator for qualified enum names.
+ // e.g. `Enum::MyVariant` uses `::`.
+ std::string enum_variant_seperator;
+
+ // Namespaces
+
+ // e.g. `namespace my_namespace {}`
+ Case namespaces;
+ // The seperator between namespaces in a namespace path.
+ std::string namespace_seperator;
+
+ // Object API.
+ // Native versions flatbuffers types have this prefix.
+ // e.g. "" (it's usually empty string)
+ std::string object_prefix;
+ // Native versions flatbuffers types have this suffix.
+ // e.g. "T"
+ std::string object_suffix;
+
+ // Keywords.
+ // Prefix used to escape keywords. It is usually empty string.
+ std::string keyword_prefix;
+ // Suffix used to escape keywords. It is usually "_".
+ std::string keyword_suffix;
+
+ // Files.
+
+ // Case style for filenames. e.g. `foo_bar_generated.rs`
+ Case filenames;
+ // Case style for directories, e.g. `output_files/foo_bar/baz/`
+ Case directories;
+ // The directory within which we will generate files.
+ std::string output_path;
+ // Suffix for generated file names, e.g. "_generated".
+ std::string filename_suffix;
+ // Extension for generated files, e.g. ".cpp" or ".rs".
+ std::string filename_extension;
+
+ // This is a temporary helper function for code generators to call until all
+ // code generators are using `Namer`. After that point, we can centralize
+ // flag-overriding logic into flatc.cpp
+ Config WithFlagOptions(const IDLOptions &opts,
+ const std::string &path) const {
+ Config result = *this;
+ result.object_prefix = opts.object_prefix;
+ result.object_suffix = opts.object_suffix;
+ result.output_path = path;
+ result.filename_suffix = opts.filename_suffix;
+ return result;
+ }
+ };
+ Namer(Config config, std::set<std::string> keywords)
+ : config_(config), keywords_(std::move(keywords)) {}
+
+ std::string Type(const std::string &s) const {
+ return Format(s, config_.types);
+ }
+
+ std::string Method(const std::string &s) const {
+ return Format(s, config_.methods);
+ }
+
+ std::string Constant(const std::string &s) const {
+ return Format(s, config_.constants);
+ }
+
+ std::string Function(const std::string &s) const {
+ return Format(s, config_.functions);
+ }
+
+ std::string Field(const std::string &s) const {
+ return Format(s, config_.fields);
+ }
+
+ std::string Variable(const std::string &s) const {
+ return Format(s, config_.variables);
+ }
+
+ std::string Variant(const std::string &s) const {
+ return Format(s, config_.variants);
+ }
+
+ std::string EnumVariant(const std::string &e, const std::string v) const {
+ return Type(e) + config_.enum_variant_seperator + Variant(v);
+ }
+
+ std::string ObjectType(const std::string &s) const {
+ return config_.object_prefix + Type(s) + config_.object_suffix;
+ }
+
+ std::string Namespace(const std::string &s) const {
+ return Format(s, config_.namespaces);
+ }
+
+ std::string Namespace(const std::vector<std::string> &ns) const {
+ std::string result;
+ for (auto it = ns.begin(); it != ns.end(); it++) {
+ if (it != ns.begin()) result += config_.namespace_seperator;
+ result += Namespace(*it);
+ }
+ return result;
+ }
+
+ std::string NamespacedType(const std::vector<std::string> &ns,
+ const std::string &s) const {
+ return Namespace(ns) + config_.namespace_seperator + Type(s);
+ }
+
+ // Returns `filename` with the right casing, suffix, and extension.
+ std::string File(const std::string &filename,
+ SkipFile skips = SkipFile::None) const {
+ const bool skip_suffix = (skips & SkipFile::Suffix) != SkipFile::None;
+ const bool skip_ext = (skips & SkipFile::Extension) != SkipFile::None;
+ return ConvertCase(filename, config_.filenames, Case::kUpperCamel) +
+ (skip_suffix ? "" : config_.filename_suffix) +
+ (skip_ext ? "" : config_.filename_extension);
+ }
+ // Formats `directories` prefixed with the output_path and joined with the
+ // right seperator. Output path prefixing and the trailing separator may be
+ // skiped using `skips`.
+ // Callers may want to use `EnsureDirExists` with the result.
+ std::string Directories(const std::vector<std::string> &directories,
+ SkipDir skips = SkipDir::None) const {
+ const bool skip_output_path =
+ (skips & SkipDir::OutputPath) != SkipDir::None;
+ const bool skip_trailing_seperator =
+ (skips & SkipDir::TrailingPathSeperator) != SkipDir::None;
+ std::string result = skip_output_path ? "" : config_.output_path;
+ for (auto d = directories.begin(); d != directories.end(); d++) {
+ result += ConvertCase(*d, config_.directories, Case::kUpperCamel);
+ result.push_back(kPathSeparator);
+ }
+ if (skip_trailing_seperator) result.pop_back();
+ return result;
+ }
+
+ std::string EscapeKeyword(const std::string &name) const {
+ if (keywords_.find(name) == keywords_.end()) {
+ return name;
+ } else {
+ return config_.keyword_prefix + name + config_.keyword_suffix;
+ }
+ }
+
+ private:
+ std::string Format(const std::string &s, Case casing) const {
+ // NOTE: If you need to escape keywords after converting case, which would
+ // make more sense than this, make it a config option.
+ return ConvertCase(EscapeKeyword(s), casing, Case::kLowerCamel);
+ }
+ const Config config_;
+ const std::set<std::string> keywords_;
+};
+
+} // namespace flatbuffers
+
+#endif // FLATBUFFERS_NAMER
diff --git a/src/reflection.cpp b/src/reflection.cpp
index 2dedcb4..6bba28c 100644
--- a/src/reflection.cpp
+++ b/src/reflection.cpp
@@ -23,7 +23,7 @@
namespace flatbuffers {
int64_t GetAnyValueI(reflection::BaseType type, const uint8_t *data) {
-// clang-format off
+ // clang-format off
#define FLATBUFFERS_GET(T) static_cast<int64_t>(ReadScalar<T>(data))
switch (type) {
case reflection::UType:
@@ -121,7 +121,7 @@
}
void SetAnyValueI(reflection::BaseType type, uint8_t *data, int64_t val) {
-// clang-format off
+ // clang-format off
#define FLATBUFFERS_SET(T) WriteScalar(data, static_cast<T>(val))
switch (type) {
case reflection::UType:
@@ -180,7 +180,7 @@
std::vector<uint8_t> *flatbuf,
const reflection::Object *root_table = nullptr)
: schema_(schema),
- startptr_(vector_data(*flatbuf) + start),
+ startptr_(flatbuf->data() + start),
delta_(delta),
buf_(*flatbuf),
dag_check_(flatbuf->size() / sizeof(uoffset_t), false) {
@@ -188,8 +188,8 @@
delta_ = (delta_ + mask) & ~mask;
if (!delta_) return; // We can't shrink by less than largest_scalar_t.
// Now change all the offsets by delta_.
- auto root = GetAnyRoot(vector_data(buf_));
- Straddle<uoffset_t, 1>(vector_data(buf_), root, vector_data(buf_));
+ auto root = GetAnyRoot(buf_.data());
+ Straddle<uoffset_t, 1>(buf_.data(), root, buf_.data());
ResizeTable(root_table ? *root_table : *schema.root_table(), root);
// We can now add or remove bytes at start.
if (delta_ > 0)
@@ -217,7 +217,7 @@
// will straddle and which won't.
uint8_t &DagCheck(const void *offsetloc) {
auto dag_idx = reinterpret_cast<const uoffset_t *>(offsetloc) -
- reinterpret_cast<const uoffset_t *>(vector_data(buf_));
+ reinterpret_cast<const uoffset_t *>(buf_.data());
return dag_check_[dag_idx];
}
@@ -309,19 +309,19 @@
const reflection::Object *root_table) {
auto delta = static_cast<int>(val.size()) - static_cast<int>(str->size());
auto str_start = static_cast<uoffset_t>(
- reinterpret_cast<const uint8_t *>(str) - vector_data(*flatbuf));
+ reinterpret_cast<const uint8_t *>(str) - flatbuf->data());
auto start = str_start + static_cast<uoffset_t>(sizeof(uoffset_t));
if (delta) {
// Clear the old string, since we don't want parts of it remaining.
- memset(vector_data(*flatbuf) + start, 0, str->size());
+ memset(flatbuf->data() + start, 0, str->size());
// Different size, we must expand (or contract).
ResizeContext(schema, start, delta, flatbuf, root_table);
// Set the new length.
- WriteScalar(vector_data(*flatbuf) + str_start,
+ WriteScalar(flatbuf->data() + str_start,
static_cast<uoffset_t>(val.size()));
}
// Copy new data. Safe because we created the right amount of space.
- memcpy(vector_data(*flatbuf) + start, val.c_str(), val.size() + 1);
+ memcpy(flatbuf->data() + start, val.c_str(), val.size() + 1);
}
uint8_t *ResizeAnyVector(const reflection::Schema &schema, uoffset_t newsize,
@@ -330,25 +330,26 @@
const reflection::Object *root_table) {
auto delta_elem = static_cast<int>(newsize) - static_cast<int>(num_elems);
auto delta_bytes = delta_elem * static_cast<int>(elem_size);
- auto vec_start =
- reinterpret_cast<const uint8_t *>(vec) - vector_data(*flatbuf);
- auto start = static_cast<uoffset_t>(vec_start + sizeof(uoffset_t) +
- elem_size * num_elems);
+ auto vec_start = reinterpret_cast<const uint8_t *>(vec) - flatbuf->data();
+ auto start = static_cast<uoffset_t>(vec_start) +
+ static_cast<uoffset_t>(sizeof(uoffset_t)) +
+ elem_size * num_elems;
if (delta_bytes) {
if (delta_elem < 0) {
// Clear elements we're throwing away, since some might remain in the
// buffer.
auto size_clear = -delta_elem * elem_size;
- memset(vector_data(*flatbuf) + start - size_clear, 0, size_clear);
+ memset(flatbuf->data() + start - size_clear, 0, size_clear);
}
ResizeContext(schema, start, delta_bytes, flatbuf, root_table);
- WriteScalar(vector_data(*flatbuf) + vec_start, newsize); // Length field.
+ WriteScalar(flatbuf->data() + vec_start, newsize); // Length field.
// Set new elements to 0.. this can be overwritten by the caller.
if (delta_elem > 0) {
- memset(vector_data(*flatbuf) + start, 0, delta_elem * elem_size);
+ memset(flatbuf->data() + start, 0,
+ static_cast<size_t>(delta_elem) * elem_size);
}
}
- return vector_data(*flatbuf) + start;
+ return flatbuf->data() + start;
}
const uint8_t *AddFlatBuffer(std::vector<uint8_t> &flatbuf,
@@ -363,7 +364,7 @@
// Insert the entire FlatBuffer minus the root pointer.
flatbuf.insert(flatbuf.end(), newbuf + sizeof(uoffset_t), newbuf + newlen);
auto root_offset = ReadScalar<uoffset_t>(newbuf) - sizeof(uoffset_t);
- return vector_data(flatbuf) + insertion_point + root_offset;
+ return flatbuf.data() + insertion_point + root_offset;
}
void CopyInline(FlatBufferBuilder &fbb, const reflection::Field &fielddef,
@@ -504,8 +505,9 @@
auto offset = parent_table.GetOptionalFieldOffset(field_offset);
if (required && !offset) { return false; }
- return !offset || v.Verify(reinterpret_cast<const uint8_t *>(&parent_table),
- offset, obj.bytesize());
+ return !offset ||
+ v.VerifyFieldStruct(reinterpret_cast<const uint8_t *>(&parent_table),
+ offset, obj.bytesize(), obj.minalign());
}
bool VerifyVectorOfStructs(flatbuffers::Verifier &v,
@@ -552,7 +554,8 @@
const flatbuffers::Table &table,
const reflection::Field &vec_field) {
FLATBUFFERS_ASSERT(vec_field.type()->base_type() == reflection::Vector);
- if (!table.VerifyField<uoffset_t>(v, vec_field.offset())) return false;
+ if (!table.VerifyField<uoffset_t>(v, vec_field.offset(), sizeof(uoffset_t)))
+ return false;
switch (vec_field.type()->element()) {
case reflection::UType:
@@ -635,33 +638,45 @@
switch (field_def->type()->base_type()) {
case reflection::None: FLATBUFFERS_ASSERT(false); break;
case reflection::UType:
- if (!table->VerifyField<uint8_t>(v, field_def->offset())) return false;
+ if (!table->VerifyField<uint8_t>(v, field_def->offset(),
+ sizeof(uint8_t)))
+ return false;
break;
case reflection::Bool:
case reflection::Byte:
case reflection::UByte:
- if (!table->VerifyField<int8_t>(v, field_def->offset())) return false;
+ if (!table->VerifyField<int8_t>(v, field_def->offset(), sizeof(int8_t)))
+ return false;
break;
case reflection::Short:
case reflection::UShort:
- if (!table->VerifyField<int16_t>(v, field_def->offset())) return false;
+ if (!table->VerifyField<int16_t>(v, field_def->offset(),
+ sizeof(int16_t)))
+ return false;
break;
case reflection::Int:
case reflection::UInt:
- if (!table->VerifyField<int32_t>(v, field_def->offset())) return false;
+ if (!table->VerifyField<int32_t>(v, field_def->offset(),
+ sizeof(int32_t)))
+ return false;
break;
case reflection::Long:
case reflection::ULong:
- if (!table->VerifyField<int64_t>(v, field_def->offset())) return false;
+ if (!table->VerifyField<int64_t>(v, field_def->offset(),
+ sizeof(int64_t)))
+ return false;
break;
case reflection::Float:
- if (!table->VerifyField<float>(v, field_def->offset())) return false;
+ if (!table->VerifyField<float>(v, field_def->offset(), sizeof(float)))
+ return false;
break;
case reflection::Double:
- if (!table->VerifyField<double>(v, field_def->offset())) return false;
+ if (!table->VerifyField<double>(v, field_def->offset(), sizeof(double)))
+ return false;
break;
case reflection::String:
- if (!table->VerifyField<uoffset_t>(v, field_def->offset()) ||
+ if (!table->VerifyField<uoffset_t>(v, field_def->offset(),
+ sizeof(uoffset_t)) ||
!v.VerifyString(flatbuffers::GetFieldS(*table, *field_def))) {
return false;
}
diff --git a/src/util.cpp b/src/util.cpp
index 3670a01..a1ed6c1 100644
--- a/src/util.cpp
+++ b/src/util.cpp
@@ -40,14 +40,17 @@
#endif
// clang-format on
-#include "flatbuffers/base.h"
#include "flatbuffers/util.h"
#include <sys/stat.h>
+
#include <clocale>
#include <cstdlib>
+#include <functional>
#include <fstream>
+#include "flatbuffers/base.h"
+
namespace flatbuffers {
bool FileExistsRaw(const char *name) {
@@ -156,7 +159,7 @@
const std::string &filename) {
std::string filepath = path;
if (filepath.length()) {
- char &filepath_last_character = string_back(filepath);
+ char &filepath_last_character = filepath.back();
if (filepath_last_character == kPathSeparatorWindows) {
filepath_last_character = kPathSeparator;
} else if (filepath_last_character != kPathSeparator) {
@@ -176,6 +179,9 @@
std::replace(p.begin(), p.end(), '\\', '/');
return p;
}
+std::string PosixPath(const std::string &path) {
+ return PosixPath(path.c_str());
+}
void EnsureDirExists(const std::string &filepath) {
auto parent = StripFileName(filepath);
@@ -215,6 +221,36 @@
// clang-format on
}
+std::string RelativeToRootPath(const std::string &project,
+ const std::string &filepath) {
+ std::string absolute_project = PosixPath(AbsolutePath(project));
+ if (absolute_project.back() != '/') absolute_project += "/";
+ std::string absolute_filepath = PosixPath(AbsolutePath(filepath));
+
+ // Find the first character where they disagree.
+ // The previous directory is the lowest common ancestor;
+ const char *a = absolute_project.c_str();
+ const char *b = absolute_filepath.c_str();
+ size_t common_prefix_len = 0;
+ while (*a != '\0' && *b != '\0' && *a == *b) {
+ if (*a == '/') common_prefix_len = a - absolute_project.c_str();
+ a++;
+ b++;
+ }
+ // the number of ../ to prepend to b depends on the number of remaining
+ // directories in A.
+ const char *suffix = absolute_project.c_str() + common_prefix_len;
+ size_t num_up = 0;
+ while (*suffix != '\0')
+ if (*suffix++ == '/') num_up++;
+ num_up--; // last one is known to be '/'.
+ std::string result = "//";
+ for (size_t i = 0; i < num_up; i++) result += "../";
+ result += absolute_filepath.substr(common_prefix_len + 1);
+
+ return result;
+}
+
// Locale-independent code.
#if defined(FLATBUFFERS_LOCALE_INDEPENDENT) && \
(FLATBUFFERS_LOCALE_INDEPENDENT > 0)
@@ -238,8 +274,7 @@
std::string RemoveStringQuotes(const std::string &s) {
auto ch = *s.c_str();
- return ((s.size() >= 2) && (ch == '\"' || ch == '\'') &&
- (ch == string_back(s)))
+ return ((s.size() >= 2) && (ch == '\"' || ch == '\'') && (ch == s.back()))
? s.substr(1, s.length() - 2)
: s;
}
@@ -284,4 +319,130 @@
// clang-format on
}
+namespace {
+
+static std::string ToCamelCase(const std::string &input, bool first) {
+ std::string s;
+ for (size_t i = 0; i < input.length(); i++) {
+ if (!i && first)
+ s += CharToUpper(input[i]);
+ else if (input[i] == '_' && i + 1 < input.length())
+ s += CharToUpper(input[++i]);
+ else
+ s += input[i];
+ }
+ return s;
+}
+
+static std::string ToSnakeCase(const std::string &input, bool screaming) {
+ std::string s;
+ for (size_t i = 0; i < input.length(); i++) {
+ if (i == 0) {
+ s += screaming ? CharToUpper(input[i]) : CharToLower(input[i]);
+ } else if (input[i] == '_') {
+ s += '_';
+ } else if (!islower(input[i])) {
+ // Prevent duplicate underscores for Upper_Snake_Case strings
+ // and UPPERCASE strings.
+ if (islower(input[i - 1])) { s += '_'; }
+ s += screaming ? CharToUpper(input[i]) : CharToLower(input[i]);
+ } else {
+ s += screaming ? CharToUpper(input[i]) : input[i];
+ }
+ }
+ return s;
+}
+
+static std::string ToAll(const std::string &input,
+ std::function<char(const char)> transform) {
+ std::string s;
+ for (size_t i = 0; i < input.length(); i++) { s += transform(input[i]); }
+ return s;
+}
+
+static std::string CamelToSnake(const std::string &input) {
+ std::string s;
+ for (size_t i = 0; i < input.length(); i++) {
+ if (i == 0) {
+ s += CharToLower(input[i]);
+ } else if (input[i] == '_') {
+ s += '_';
+ } else if (!islower(input[i])) {
+ // Prevent duplicate underscores for Upper_Snake_Case strings
+ // and UPPERCASE strings.
+ if (islower(input[i - 1])) { s += '_'; }
+ s += CharToLower(input[i]);
+ } else {
+ s += input[i];
+ }
+ }
+ return s;
+}
+
+static std::string DasherToSnake(const std::string &input) {
+ std::string s;
+ for (size_t i = 0; i < input.length(); i++) {
+ if (input[i] == '-') {
+ s += "_";
+ } else {
+ s += input[i];
+ }
+ }
+ return s;
+}
+
+static std::string ToDasher(const std::string &input) {
+ std::string s;
+ char p = 0;
+ for (size_t i = 0; i < input.length(); i++) {
+ char const &c = input[i];
+ if (c == '_') {
+ if (i > 0 && p != kPathSeparator &&
+ // The following is a special case to ignore digits after a _. This is
+ // because ThisExample3 would be converted to this_example_3 in the
+ // CamelToSnake conversion, and then dasher would do this-example-3,
+ // but it expects this-example3.
+ !(i + 1 < input.length() && isdigit(input[i + 1])))
+ s += "-";
+ } else {
+ s += c;
+ }
+ p = c;
+ }
+ return s;
+}
+
+} // namespace
+
+std::string ConvertCase(const std::string &input, Case output_case,
+ Case input_case) {
+ if (output_case == Case::kKeep) return input;
+ // The output cases expect snake_case inputs, so if we don't have that input
+ // format, try to convert to snake_case.
+ switch (input_case) {
+ case Case::kLowerCamel:
+ case Case::kUpperCamel:
+ return ConvertCase(CamelToSnake(input), output_case);
+ case Case::kDasher: return ConvertCase(DasherToSnake(input), output_case);
+ case Case::kKeep: printf("WARNING: Converting from kKeep case.\n"); break;
+ default:
+ case Case::kSnake:
+ case Case::kScreamingSnake:
+ case Case::kAllLower:
+ case Case::kAllUpper: break;
+ }
+
+ switch (output_case) {
+ case Case::kUpperCamel: return ToCamelCase(input, true);
+ case Case::kLowerCamel: return ToCamelCase(input, false);
+ case Case::kSnake: return input;
+ case Case::kScreamingSnake: return ToSnakeCase(input, true);
+ case Case::kAllUpper: return ToAll(input, CharToUpper);
+ case Case::kAllLower: return ToAll(input, CharToLower);
+ case Case::kDasher: return ToDasher(input);
+ default:
+ case Case::kUnknown: return input;
+ }
+}
+
} // namespace flatbuffers
diff --git a/swift.swiftformat b/swift.swiftformat
index 5574421..b198b92 100644
--- a/swift.swiftformat
+++ b/swift.swiftformat
@@ -1,8 +1,8 @@
--swiftversion 5.1
# format
---allman true
--indent 2
+--maxwidth 80
# options
--self remove # redundantSelf
@@ -17,10 +17,11 @@
--typeattributes prev-line # wrapAttributes
# rules
---rules todos,anyObjectProtocol,redundantParens,redundantReturn,redundantSelf,sortedImports,strongifiedSelf,trailingCommas,trailingSpace,wrapArguments,wrapMultilineStatementBraces,indent,wrapAttributes,void,fileHeader
+--rules wrap,todos,anyObjectProtocol,redundantParens,redundantReturn,redundantSelf,sortedImports,strongifiedSelf,trailingCommas,trailingSpace,wrapArguments,wrapMultilineStatementBraces,indent,wrapAttributes,void,fileHeader
--disable trailingclosures
--exclude **/*_generated.swift
+--exclude **/swift_code_*.swift
--exclude **/*.grpc.swift
--header "/*\n * Copyright {year} Google Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */"
\ No newline at end of file
diff --git a/swift/FlatBuffers.podspec b/swift/FlatBuffers.podspec
index b106b4c..0119529 100644
--- a/swift/FlatBuffers.podspec
+++ b/swift/FlatBuffers.podspec
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'FlatBuffers'
- s.version = '0.8.1'
+ s.version = '2.0.0'
s.summary = 'FlatBuffers: Memory Efficient Serialization Library'
s.description = "FlatBuffers is a cross platform serialization library architected for
diff --git a/swift/Package.swift b/swift/Package.swift
index 5d4c7cc..d2d2d5c 100644
--- a/swift/Package.swift
+++ b/swift/Package.swift
@@ -31,5 +31,6 @@
targets: [
.target(
name: "FlatBuffers",
- dependencies: []),
+ dependencies: [],
+ exclude: ["Documentation.docc/Resources/code/swift"]),
])
diff --git a/swift/Package@swift-5.5.swift b/swift/Package@swift-5.5.swift
new file mode 100644
index 0000000..3cfdcf6
--- /dev/null
+++ b/swift/Package@swift-5.5.swift
@@ -0,0 +1,36 @@
+// swift-tools-version:5.5
+/*
+ * Copyright 2020 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.
+ */
+
+import PackageDescription
+
+let package = Package(
+ name: "FlatBuffers",
+ platforms: [
+ .iOS(.v11),
+ .macOS(.v10_14),
+ ],
+ products: [
+ .library(
+ name: "FlatBuffers",
+ targets: ["FlatBuffers"]),
+ ],
+ targets: [
+ .target(
+ name: "FlatBuffers",
+ dependencies: []),
+ ])
+
diff --git a/swift/README.md b/swift/README.md
index c3060fd..6984fa8 100644
--- a/swift/README.md
+++ b/swift/README.md
@@ -10,8 +10,6 @@
1- To report any error please use the main repository.
-2- `0.6.0` deprecates `add(condition:bool)` for `add(element:bool)`. You can download the [binary here](https://github.com/google/flatbuffers/actions) and select the latest push to master
-
### Contribute
1- Always run `swift test --generate-linuxmain` whenever new test functions are added or removed
\ No newline at end of file
diff --git a/swift/Sources/FlatBuffers/ByteBuffer.swift b/swift/Sources/FlatBuffers/ByteBuffer.swift
index 7df41a7..a07f66a 100644
--- a/swift/Sources/FlatBuffers/ByteBuffer.swift
+++ b/swift/Sources/FlatBuffers/ByteBuffer.swift
@@ -1,5 +1,5 @@
/*
- * Copyright 2020 Google Inc. All rights reserved.
+ * Copyright 2021 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.
@@ -16,6 +16,10 @@
import Foundation
+/// `ByteBuffer` is the interface that stores the data for a `Flatbuffers` object
+/// it allows users to write and read data directly from memory thus the use of its
+/// functions should be used
+@frozen
public struct ByteBuffer {
/// Storage is a container that would hold the memory pointer to solve the issue of
@@ -29,12 +33,16 @@
/// Capacity of UInt8 the buffer can hold
var capacity: Int
+ @usableFromInline
init(count: Int, alignment: Int) {
- memory = UnsafeMutableRawPointer.allocate(byteCount: count, alignment: alignment)
+ memory = UnsafeMutableRawPointer.allocate(
+ byteCount: count,
+ alignment: alignment)
capacity = count
unowned = false
}
+ @usableFromInline
init(memory: UnsafeMutableRawPointer, capacity: Int, unowned: Bool) {
self.memory = memory
self.capacity = capacity
@@ -47,6 +55,7 @@
}
}
+ @usableFromInline
func copy(from ptr: UnsafeRawPointer, count: Int) {
assert(
!unowned,
@@ -54,6 +63,7 @@
memory.copyMemory(from: ptr, byteCount: count)
}
+ @usableFromInline
func initialize(for size: Int) {
assert(
!unowned,
@@ -64,7 +74,7 @@
/// Reallocates the buffer incase the object to be written doesnt fit in the current buffer
/// - Parameter size: Size of the current object
@usableFromInline
- internal func reallocate(_ size: Int, writerSize: Int, alignment: Int) {
+ func reallocate(_ size: Int, writerSize: Int, alignment: Int) {
let currentWritingIndex = capacity &- writerSize
while capacity <= writerSize &+ size {
capacity = capacity << 1
@@ -73,7 +83,9 @@
/// solution take from Apple-NIO
capacity = capacity.convertToPowerofTwo
- let newData = UnsafeMutableRawPointer.allocate(byteCount: capacity, alignment: alignment)
+ let newData = UnsafeMutableRawPointer.allocate(
+ byteCount: capacity,
+ alignment: alignment)
memset(newData, 0, capacity &- writerSize)
memcpy(
newData.advanced(by: capacity &- writerSize),
@@ -89,9 +101,9 @@
/// The size of the elements written to the buffer + their paddings
private var _writerSize: Int = 0
/// Aliginment of the current memory being written to the buffer
- internal var alignment = 1
+ var alignment = 1
/// Current Index which is being used to write to the buffer, it is written from the end to the start of the buffer
- internal var writerIndex: Int { _storage.capacity &- _writerSize }
+ var writerIndex: Int { _storage.capacity &- _writerSize }
/// Reader is the position of the current Writer Index (capacity - size)
public var reader: Int { writerIndex }
@@ -152,7 +164,10 @@
/// Constructor that creates a Flatbuffer from unsafe memory region without copying
/// - Parameter assumingMemoryBound: The unsafe memory region
/// - Parameter capacity: The size of the given memory region
- public init(assumingMemoryBound memory: UnsafeMutableRawPointer, capacity: Int) {
+ public init(
+ assumingMemoryBound memory: UnsafeMutableRawPointer,
+ capacity: Int)
+ {
_storage = Storage(memory: memory, capacity: capacity, unowned: true)
_writerSize = capacity
}
@@ -161,7 +176,7 @@
/// - Parameters:
/// - memory: Current memory of the buffer
/// - count: count of bytes
- internal init(memory: UnsafeMutableRawPointer, count: Int) {
+ init(memory: UnsafeMutableRawPointer, count: Int) {
_storage = Storage(count: count, alignment: alignment)
_storage.copy(from: memory, count: count)
_writerSize = _storage.capacity
@@ -172,7 +187,11 @@
/// - memory: Current memory of the buffer
/// - count: count of bytes
/// - removeBytes: Removes a number of bytes from the current size
- internal init(memory: UnsafeMutableRawPointer, count: Int, removing removeBytes: Int) {
+ init(
+ memory: UnsafeMutableRawPointer,
+ count: Int,
+ removing removeBytes: Int)
+ {
_storage = Storage(count: count, alignment: alignment)
_storage.copy(from: memory, count: count)
_writerSize = removeBytes
@@ -187,7 +206,7 @@
_writerSize = _writerSize &+ (MemoryLayout<UInt8>.size &* padding)
}
- ///Adds an array of type Scalar to the buffer memory
+ /// Adds an array of type Scalar to the buffer memory
/// - Parameter elements: An array of Scalars
@usableFromInline
mutating func push<T: Scalar>(elements: [T]) {
@@ -198,41 +217,16 @@
}
}
- /// A custom type of structs that are padded according to the flatbuffer padding,
+ /// Adds an object of type NativeStruct into the buffer
/// - Parameters:
- /// - value: Pointer to the object in memory
- /// - size: Size of Value being written to the buffer
- @available(
- *,
- deprecated,
- message: "0.9.0 will be removing the following method. Regenerate the code")
- @usableFromInline
- mutating func push(struct value: UnsafeMutableRawPointer, size: Int) {
+ /// - value: Object that will be written to the buffer
+ /// - size: size to subtract from the WriterIndex
+ @inline(__always)
+ mutating func push<T: NativeStruct>(struct value: T, size: Int) {
ensureSpace(size: size)
- memcpy(_storage.memory.advanced(by: writerIndex &- size), value, size)
- defer { value.deallocate() }
- _writerSize = _writerSize &+ size
- }
-
- /// Prepares the buffer to receive a struct of certian size.
- /// The alignment of the memory is already handled since we already called preAlign
- /// - Parameter size: size of the struct
- @usableFromInline
- mutating func prepareBufferToReceiveStruct(of size: Int) {
- ensureSpace(size: size)
- _writerSize = _writerSize &+ size
- }
-
- /// Reverse the input direction to the buffer, since `FlatBuffers` uses a back to front, following method will take current `writerIndex`
- /// and writes front to back into the buffer, respecting the padding & the alignment
- /// - Parameters:
- /// - value: value of type Scalar
- /// - position: position relative to the `writerIndex`
- /// - len: length of the value in terms of bytes
- @usableFromInline
- mutating func reversePush<T: Scalar>(value: T, position: Int, len: Int) {
var v = value
- memcpy(_storage.memory.advanced(by: writerIndex &+ position), &v, len)
+ memcpy(_storage.memory.advanced(by: writerIndex &- size), &v, size)
+ _writerSize = _writerSize &+ size
}
/// Adds an object of type Scalar into the buffer
@@ -253,7 +247,10 @@
@usableFromInline
mutating func push(string str: String, len: Int) {
ensureSpace(size: len)
- if str.utf8.withContiguousStorageIfAvailable({ self.push(bytes: $0, len: len) }) != nil {
+ if str.utf8
+ .withContiguousStorageIfAvailable({ self.push(bytes: $0, len: len) }) !=
+ nil
+ {
} else {
let utf8View = str.utf8
for c in utf8View.reversed() {
@@ -266,8 +263,8 @@
/// - Parameters:
/// - bytes: Pointer to the view
/// - len: Size of string
- @usableFromInline
- mutating internal func push(
+ @inline(__always)
+ mutating func push(
bytes: UnsafeBufferPointer<String.UTF8View.Element>,
len: Int) -> Bool
{
@@ -300,7 +297,7 @@
/// Makes sure that buffer has enouch space for each of the objects that will be written into it
/// - Parameter size: size of object
@discardableResult
- @usableFromInline
+ @inline(__always)
mutating func ensureSpace(size: Int) -> Int {
if size &+ _writerSize > _storage.capacity {
_storage.reallocate(size, writerSize: _writerSize, alignment: alignment)
@@ -311,9 +308,11 @@
/// pops the written VTable if it's already written into the buffer
/// - Parameter size: size of the `VTable`
- @usableFromInline
- mutating internal func pop(_ size: Int) {
- assert((_writerSize &- size) > 0, "New size should NOT be a negative number")
+ @inline(__always)
+ mutating func pop(_ size: Int) {
+ assert(
+ (_writerSize &- size) > 0,
+ "New size should NOT be a negative number")
memset(_storage.memory.advanced(by: writerIndex), 0, _writerSize &- size)
_writerSize = size
}
@@ -335,25 +334,24 @@
/// - def: Type of the object
/// - position: the index of the object in the buffer
public func read<T>(def: T.Type, position: Int) -> T {
- assert(
- position + MemoryLayout<T>.size <= _storage.capacity,
- "Reading out of bounds is illegal")
- return _storage.memory.advanced(by: position).load(as: T.self)
+ _storage.memory.advanced(by: position).load(as: T.self)
}
/// Reads a slice from the memory assuming a type of T
/// - Parameters:
/// - index: index of the object to be read from the buffer
/// - count: count of bytes in memory
+ @inline(__always)
public func readSlice<T>(
- index: Int32,
- count: Int32) -> [T]
+ index: Int,
+ count: Int) -> [T]
{
- let _index = Int(index)
- let _count = Int(count)
- assert(_index + _count <= _storage.capacity, "Reading out of bounds is illegal")
- let start = _storage.memory.advanced(by: _index).assumingMemoryBound(to: T.self)
- let array = UnsafeBufferPointer(start: start, count: _count)
+ assert(
+ index + count <= _storage.capacity,
+ "Reading out of bounds is illegal")
+ let start = _storage.memory.advanced(by: index)
+ .assumingMemoryBound(to: T.self)
+ let array = UnsafeBufferPointer(start: start, count: count)
return Array(array)
}
@@ -363,15 +361,16 @@
/// - count: length of the string
/// - type: Encoding of the string
public func readString(
- at index: Int32,
- count: Int32,
+ at index: Int,
+ count: Int,
type: String.Encoding = .utf8) -> String?
{
- let _index = Int(index)
- let _count = Int(count)
- assert(_index + _count <= _storage.capacity, "Reading out of bounds is illegal")
- let start = _storage.memory.advanced(by: _index).assumingMemoryBound(to: UInt8.self)
- let bufprt = UnsafeBufferPointer(start: start, count: _count)
+ assert(
+ index + count <= _storage.capacity,
+ "Reading out of bounds is illegal")
+ let start = _storage.memory.advanced(by: index)
+ .assumingMemoryBound(to: UInt8.self)
+ let bufprt = UnsafeBufferPointer(start: start, count: count)
return String(bytes: Array(bufprt), encoding: type)
}
@@ -379,12 +378,32 @@
/// - Parameter removeBytes: the amount of bytes to remove from the current Size
public func duplicate(removing removeBytes: Int = 0) -> ByteBuffer {
assert(removeBytes > 0, "Can NOT remove negative bytes")
- assert(removeBytes < _storage.capacity, "Can NOT remove more bytes than the ones allocated")
+ assert(
+ removeBytes < _storage.capacity,
+ "Can NOT remove more bytes than the ones allocated")
return ByteBuffer(
memory: _storage.memory,
count: _storage.capacity,
removing: _writerSize &- removeBytes)
}
+
+ /// Returns the written bytes into the ``ByteBuffer``
+ public var underlyingBytes: [UInt8] {
+ let cp = capacity &- writerIndex
+ let start = memory.advanced(by: writerIndex)
+ .bindMemory(to: UInt8.self, capacity: cp)
+
+ let ptr = UnsafeBufferPointer<UInt8>(start: start, count: cp)
+ return Array(ptr)
+ }
+
+ /// SkipPrefix Skips the first 4 bytes in case one of the following
+ /// functions are called `getPrefixedSizeCheckedRoot` & `getPrefixedSizeRoot`
+ /// which allows us to skip the first 4 bytes instead of recreating the buffer
+ @usableFromInline
+ mutating func skipPrefix() {
+ _writerSize = _writerSize &- MemoryLayout<Int32>.size
+ }
}
extension ByteBuffer: CustomDebugStringConvertible {
diff --git a/swift/Sources/FlatBuffers/Constants.swift b/swift/Sources/FlatBuffers/Constants.swift
index ac541d9..8e643fd 100644
--- a/swift/Sources/FlatBuffers/Constants.swift
+++ b/swift/Sources/FlatBuffers/Constants.swift
@@ -1,5 +1,5 @@
/*
- * Copyright 2020 Google Inc. All rights reserved.
+ * Copyright 2021 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.
@@ -21,7 +21,8 @@
#endif
/// A boolean to see if the system is littleEndian
-let isLitteEndian = CFByteOrderGetCurrent() == Int(CFByteOrderLittleEndian.rawValue)
+let isLitteEndian = CFByteOrderGetCurrent() ==
+ Int(CFByteOrderLittleEndian.rawValue)
/// Constant for the file id length
let FileIdLength = 4
/// Type aliases
@@ -30,16 +31,19 @@
public typealias SOffset = Int32
public typealias VOffset = UInt16
/// Maximum size for a buffer
-public let FlatBufferMaxSize = UInt32.max << ((MemoryLayout<SOffset>.size * 8 - 1) - 1)
+public let FlatBufferMaxSize = UInt32
+ .max << ((MemoryLayout<SOffset>.size * 8 - 1) - 1)
-/// Protocol that confirms all the numbers
+/// Protocol that All Scalars should conform to
///
-/// Scalar is used to confirm all the numbers that can be represented in a FlatBuffer. It's used to write/read from the buffer.
+/// Scalar is used to conform all the numbers that can be represented in a FlatBuffer. It's used to write/read from the buffer.
public protocol Scalar: Equatable {
associatedtype NumericValue
var convertedEndian: NumericValue { get }
}
+extension Scalar where Self: Verifiable {}
+
extension Scalar where Self: FixedWidthInteger {
/// Converts the value from BigEndian to LittleEndian
///
@@ -49,7 +53,7 @@
}
}
-extension Double: Scalar {
+extension Double: Scalar, Verifiable {
public typealias NumericValue = UInt64
public var convertedEndian: UInt64 {
@@ -57,7 +61,7 @@
}
}
-extension Float32: Scalar {
+extension Float32: Scalar, Verifiable {
public typealias NumericValue = UInt32
public var convertedEndian: UInt32 {
@@ -65,7 +69,7 @@
}
}
-extension Bool: Scalar {
+extension Bool: Scalar, Verifiable {
public var convertedEndian: UInt8 {
self == true ? 1 : 0
}
@@ -73,40 +77,40 @@
public typealias NumericValue = UInt8
}
-extension Int: Scalar {
+extension Int: Scalar, Verifiable {
public typealias NumericValue = Int
}
-extension Int8: Scalar {
+extension Int8: Scalar, Verifiable {
public typealias NumericValue = Int8
}
-extension Int16: Scalar {
+extension Int16: Scalar, Verifiable {
public typealias NumericValue = Int16
}
-extension Int32: Scalar {
+extension Int32: Scalar, Verifiable {
public typealias NumericValue = Int32
}
-extension Int64: Scalar {
+extension Int64: Scalar, Verifiable {
public typealias NumericValue = Int64
}
-extension UInt8: Scalar {
+extension UInt8: Scalar, Verifiable {
public typealias NumericValue = UInt8
}
-extension UInt16: Scalar {
+extension UInt16: Scalar, Verifiable {
public typealias NumericValue = UInt16
}
-extension UInt32: Scalar {
+extension UInt32: Scalar, Verifiable {
public typealias NumericValue = UInt32
}
-extension UInt64: Scalar {
+extension UInt64: Scalar, Verifiable {
public typealias NumericValue = UInt64
}
-public func FlatBuffersVersion_1_12_0() {}
+public func FlatBuffersVersion_2_0_0() {}
diff --git a/swift/Sources/FlatBuffers/Documentation.docc/Documentation.md b/swift/Sources/FlatBuffers/Documentation.docc/Documentation.md
new file mode 100644
index 0000000..a151080
--- /dev/null
+++ b/swift/Sources/FlatBuffers/Documentation.docc/Documentation.md
@@ -0,0 +1,22 @@
+# ``FlatBuffers``
+
+FlatBuffers: Memory Efficient Serialization Library
+
+## Overview
+
+- Access to serialized data without parsing/unpacking - What sets FlatBuffers apart is that it represents hierarchical data in a flat binary buffer in such a way that it can still be accessed directly without parsing/unpacking, while also still supporting data structure evolution (forwards/backwards compatibility).
+- Memory efficiency and speed - The only memory needed to access your data is that of the buffer. It requires 0 additional allocations (in C++, other languages may vary). FlatBuffers is also very suitable for use with mmap (or streaming), requiring only part of the buffer to be in memory. Access is close to the speed of raw struct access with only one extra indirection (a kind of vtable) to allow for format evolution and optional fields. It is aimed at projects where spending time and space (many memory allocations) to be able to access or construct serialized data is undesirable, such as in games or any other performance sensitive applications. See the benchmarks for details.
+- Flexible - Optional fields means not only do you get great forwards and backwards compatibility (increasingly important for long-lived games: don't have to update all data with each new version!). It also means you have a lot of choice in what data you write and what data you don't, and how you design data structures.
+- Tiny code footprint - Small amounts of generated code, and just a single small header as the minimum dependency, which is very easy to integrate. Again, see the benchmark section for details.
+- Strongly typed - Errors happen at compile time rather than manually having to write repetitive and error prone run-time checks. Useful code can be generated for you.
+
+## Topics
+
+### Read this first
+
+- <doc:Tutorial_Table_of_Contents>
+
+### Where to start
+
+- ``FlatBufferBuilder``
+- ``ByteBuffer``
diff --git a/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/fbs/monster_step_1.fbs b/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/fbs/monster_step_1.fbs
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/fbs/monster_step_1.fbs
@@ -0,0 +1 @@
+
diff --git a/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/fbs/monster_step_2.fbs b/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/fbs/monster_step_2.fbs
new file mode 100644
index 0000000..a438978
--- /dev/null
+++ b/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/fbs/monster_step_2.fbs
@@ -0,0 +1 @@
+enum Color:byte { red, green, blue }
diff --git a/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/fbs/monster_step_3.fbs b/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/fbs/monster_step_3.fbs
new file mode 100644
index 0000000..d31a29c
--- /dev/null
+++ b/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/fbs/monster_step_3.fbs
@@ -0,0 +1,6 @@
+enum Color:byte { red, green, blue }
+
+struct Vec3 {
+ x:float;
+ y:float;
+}
diff --git a/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/fbs/monster_step_4.fbs b/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/fbs/monster_step_4.fbs
new file mode 100644
index 0000000..51f7bb1
--- /dev/null
+++ b/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/fbs/monster_step_4.fbs
@@ -0,0 +1,12 @@
+enum Color:byte { red, green, blue }
+
+struct Vec3 {
+ x:float;
+ y:float;
+}
+
+table Monster {
+ pos:Vec3;
+ color:Color = Blue;
+}
+
diff --git a/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/fbs/monster_step_5.fbs b/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/fbs/monster_step_5.fbs
new file mode 100644
index 0000000..8d0b729
--- /dev/null
+++ b/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/fbs/monster_step_5.fbs
@@ -0,0 +1,18 @@
+enum Color:byte { red, green, blue }
+
+struct Vec3 {
+ x:float;
+ y:float;
+}
+
+table Monster {
+ pos:Vec3;
+ color:Color = Blue;
+
+ mana:short = 150;
+ hp:short = 100;
+ name:string;
+ equipped:Equipment;
+ weapons:[Weapon];
+ path:[Vec3];
+}
diff --git a/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/fbs/monster_step_6.fbs b/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/fbs/monster_step_6.fbs
new file mode 100644
index 0000000..10c3eaf
--- /dev/null
+++ b/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/fbs/monster_step_6.fbs
@@ -0,0 +1,25 @@
+enum Color:byte { red, green, blue }
+
+union Equipment { Weapon } // Optionally add more tables.
+
+struct Vec3 {
+ x:float;
+ y:float;
+}
+
+table Monster {
+ pos:Vec3;
+ color:Color = Blue;
+
+ mana:short = 150;
+ hp:short = 100;
+ name:string;
+ equipped:Equipment;
+ weapons:[Weapon];
+ path:[Vec3];
+}
+
+table Weapon {
+ name:string;
+ damage:short;
+}
diff --git a/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/fbs/monster_step_7.fbs b/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/fbs/monster_step_7.fbs
new file mode 100644
index 0000000..b4dde6c
--- /dev/null
+++ b/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/fbs/monster_step_7.fbs
@@ -0,0 +1,27 @@
+enum Color:byte { red, green, blue }
+
+union Equipment { Weapon } // Optionally add more tables.
+
+struct Vec3 {
+ x:float;
+ y:float;
+}
+
+table Monster {
+ pos:Vec3;
+ color:Color = Blue;
+
+ mana:short = 150;
+ hp:short = 100;
+ name:string;
+ equipped:Equipment;
+ weapons:[Weapon];
+ path:[Vec3];
+}
+
+table Weapon {
+ name:string;
+ damage:short;
+}
+
+root_type Monster; // flatc --swift monster.fbs
diff --git a/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_1.swift b/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_1.swift
new file mode 100644
index 0000000..fecc4ab
--- /dev/null
+++ b/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_1.swift
@@ -0,0 +1 @@
+import Foundation
diff --git a/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_10.swift b/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_10.swift
new file mode 100644
index 0000000..51d4fbf
--- /dev/null
+++ b/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_10.swift
@@ -0,0 +1,71 @@
+import FlatBuffers
+import Foundation
+
+func run() {
+ // create a `FlatBufferBuilder`, which will be used to serialize objects
+ let builder = FlatBufferBuilder(initialSize: 1024)
+
+ let weapon1Name = builder.create(string: "Sword")
+ let weapon2Name = builder.create(string: "Axe")
+
+ // start creating the weapon by calling startWeapon
+ let weapon1Start = Weapon.startWeapon(&builder)
+ Weapon.add(name: weapon1Name, &builder)
+ Weapon.add(damage: 3, &builder)
+ // end the object by passing the start point for the weapon 1
+ let sword = Weapon.endWeapon(&builder, start: weapon1Start)
+
+ let weapon2Start = Weapon.startWeapon(&builder)
+ Weapon.add(name: weapon2Name, &builder)
+ Weapon.add(damage: 5, &builder)
+ let axe = Weapon.endWeapon(&builder, start: weapon2Start)
+
+ // Create a FlatBuffer `vector` that contains offsets to the sword and axe
+ // we created above.
+ let weaponsOffset = builder.createVector(ofOffsets: [sword, axe])
+
+ // Name of the Monster.
+ let name = builder.create(string: "Orc")
+
+ let pathOffset = fbb.createVector(ofStructs: [
+ Vec3(x: 0, y: 0),
+ Vec3(x: 5, y: 5),
+ ])
+
+ // startVector(len, elementSize: MemoryLayout<Offset>.size)
+ // for o in offsets.reversed() {
+ // push(element: o)
+ // }
+ // endVector(len: len)
+
+ let orc = Monster.createMonster(
+ &builder,
+ pos: Vec3(x: 1, y: 2),
+ hp: 300,
+ nameOffset: name,
+ color: .red,
+ weaponsVectorOffset: weaponsOffset,
+ equippedType: .weapon,
+ equippedOffset: axe,
+ pathOffset: pathOffset)
+
+ // let start = Monster.startMonster(&builder)
+ // Monster.add(pos: Vec3(x: 1, y: 2), &builder)
+ // Monster.add(hp: 300, &builder)
+ // Monster.add(name: name, &builder)
+ // Monster.add(color: .red, &builder)
+ // Monster.addVectorOf(weapons: weaponsOffset, &builder)
+ // Monster.add(equippedType: .weapon, &builder)
+ // Monster.addVectorOf(paths: weaponsOffset, &builder)
+ // Monster.add(equipped: axe, &builder)
+ // var orc = Monster.endMonster(&builder, start: start)
+
+ // Call `finish(offset:)` to instruct the builder that this monster is complete.
+ builder.finish(offset: orc)
+ // This must be called after `finish()`.
+ // `sizedByteArray` returns the finished buf of type [UInt8].
+ let buf = builder.sizedByteArray
+
+ // or you can use to get an object of type Data
+ let bufData = ByteBuffer(data: builder.sizedBuffer)
+}
diff --git a/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_11.swift b/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_11.swift
new file mode 100644
index 0000000..3ed7ea2
--- /dev/null
+++ b/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_11.swift
@@ -0,0 +1,11 @@
+import FlatBuffers
+import Foundation
+
+func run() {
+ // create a ByteBuffer(:) from an [UInt8] or Data()
+ let buf = [] // Get your data
+
+ // Get an accessor to the root object inside the buffer.
+ let monster: Monster = try! getCheckedRoot(byteBuffer: ByteBuffer(bytes: buf))
+ // let monster: Monster = getRoot(byteBuffer: ByteBuffer(bytes: buf))
+}
diff --git a/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_12.swift b/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_12.swift
new file mode 100644
index 0000000..895653e
--- /dev/null
+++ b/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_12.swift
@@ -0,0 +1,19 @@
+import FlatBuffers
+import Foundation
+
+func run() {
+ // create a ByteBuffer(:) from an [UInt8] or Data()
+ let buf = [] // Get your data
+
+ // Get an accessor to the root object inside the buffer.
+ let monster: Monster = try! getCheckedRoot(byteBuffer: ByteBuffer(bytes: buf))
+ // let monster: Monster = getRoot(byteBuffer: ByteBuffer(bytes: buf))
+
+ let hp = monster.hp
+ let mana = monster.mana
+ let name = monster.name // returns an optional string
+
+ let pos = monster.pos
+ let x = pos.x
+ let y = pos.y
+}
diff --git a/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_13.swift b/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_13.swift
new file mode 100644
index 0000000..7aac982
--- /dev/null
+++ b/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_13.swift
@@ -0,0 +1,26 @@
+import FlatBuffers
+import Foundation
+
+func run() {
+ // create a ByteBuffer(:) from an [UInt8] or Data()
+ let buf = [] // Get your data
+
+ // Get an accessor to the root object inside the buffer.
+ let monster: Monster = try! getCheckedRoot(byteBuffer: ByteBuffer(bytes: buf))
+ // let monster: Monster = getRoot(byteBuffer: ByteBuffer(bytes: buf))
+
+ let hp = monster.hp
+ let mana = monster.mana
+ let name = monster.name // returns an optional string
+
+ let pos = monster.pos
+ let x = pos.x
+ let y = pos.y
+
+ // Get and check if the monster has an equipped item
+ if monster.equippedType == .weapon {
+ let _weapon = monster.equipped(type: Weapon.self)
+ let name = _weapon.name // should return "Axe"
+ let dmg = _weapon.damage // should return 5
+ }
+}
diff --git a/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_2.swift b/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_2.swift
new file mode 100644
index 0000000..ddd066e
--- /dev/null
+++ b/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_2.swift
@@ -0,0 +1,2 @@
+import FlatBuffers
+import Foundation
diff --git a/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_3.swift b/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_3.swift
new file mode 100644
index 0000000..bacdaa5
--- /dev/null
+++ b/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_3.swift
@@ -0,0 +1,7 @@
+import FlatBuffers
+import Foundation
+
+func run() {
+ // create a `FlatBufferBuilder`, which will be used to serialize objects
+ let builder = FlatBufferBuilder(initialSize: 1024)
+}
diff --git a/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_4.swift b/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_4.swift
new file mode 100644
index 0000000..8754699
--- /dev/null
+++ b/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_4.swift
@@ -0,0 +1,10 @@
+import FlatBuffers
+import Foundation
+
+func run() {
+ // create a `FlatBufferBuilder`, which will be used to serialize objects
+ let builder = FlatBufferBuilder(initialSize: 1024)
+
+ let weapon1Name = builder.create(string: "Sword")
+ let weapon2Name = builder.create(string: "Axe")
+}
diff --git a/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_5.swift b/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_5.swift
new file mode 100644
index 0000000..12e0d4c
--- /dev/null
+++ b/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_5.swift
@@ -0,0 +1,22 @@
+import FlatBuffers
+import Foundation
+
+func run() {
+ // create a `FlatBufferBuilder`, which will be used to serialize objects
+ let builder = FlatBufferBuilder(initialSize: 1024)
+
+ let weapon1Name = builder.create(string: "Sword")
+ let weapon2Name = builder.create(string: "Axe")
+
+ // start creating the weapon by calling startWeapon
+ let weapon1Start = Weapon.startWeapon(&builder)
+ Weapon.add(name: weapon1Name, &builder)
+ Weapon.add(damage: 3, &builder)
+ // end the object by passing the start point for the weapon 1
+ let sword = Weapon.endWeapon(&builder, start: weapon1Start)
+
+ let weapon2Start = Weapon.startWeapon(&builder)
+ Weapon.add(name: weapon2Name, &builder)
+ Weapon.add(damage: 5, &builder)
+ let axe = Weapon.endWeapon(&builder, start: weapon2Start)
+}
diff --git a/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_6.swift b/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_6.swift
new file mode 100644
index 0000000..bfb4f7e
--- /dev/null
+++ b/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_6.swift
@@ -0,0 +1,26 @@
+import FlatBuffers
+import Foundation
+
+func run() {
+ // create a `FlatBufferBuilder`, which will be used to serialize objects
+ let builder = FlatBufferBuilder(initialSize: 1024)
+
+ let weapon1Name = builder.create(string: "Sword")
+ let weapon2Name = builder.create(string: "Axe")
+
+ // start creating the weapon by calling startWeapon
+ let weapon1Start = Weapon.startWeapon(&builder)
+ Weapon.add(name: weapon1Name, &builder)
+ Weapon.add(damage: 3, &builder)
+ // end the object by passing the start point for the weapon 1
+ let sword = Weapon.endWeapon(&builder, start: weapon1Start)
+
+ let weapon2Start = Weapon.startWeapon(&builder)
+ Weapon.add(name: weapon2Name, &builder)
+ Weapon.add(damage: 5, &builder)
+ let axe = Weapon.endWeapon(&builder, start: weapon2Start)
+
+ // Create a FlatBuffer `vector` that contains offsets to the sword and axe
+ // we created above.
+ let weaponsOffset = builder.createVector(ofOffsets: [sword, axe])
+}
diff --git a/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_7.swift b/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_7.swift
new file mode 100644
index 0000000..97264b0
--- /dev/null
+++ b/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_7.swift
@@ -0,0 +1,29 @@
+import FlatBuffers
+import Foundation
+
+func run() {
+ // create a `FlatBufferBuilder`, which will be used to serialize objects
+ let builder = FlatBufferBuilder(initialSize: 1024)
+
+ let weapon1Name = builder.create(string: "Sword")
+ let weapon2Name = builder.create(string: "Axe")
+
+ // start creating the weapon by calling startWeapon
+ let weapon1Start = Weapon.startWeapon(&builder)
+ Weapon.add(name: weapon1Name, &builder)
+ Weapon.add(damage: 3, &builder)
+ // end the object by passing the start point for the weapon 1
+ let sword = Weapon.endWeapon(&builder, start: weapon1Start)
+
+ let weapon2Start = Weapon.startWeapon(&builder)
+ Weapon.add(name: weapon2Name, &builder)
+ Weapon.add(damage: 5, &builder)
+ let axe = Weapon.endWeapon(&builder, start: weapon2Start)
+
+ // Create a FlatBuffer `vector` that contains offsets to the sword and axe
+ // we created above.
+ let weaponsOffset = builder.createVector(ofOffsets: [sword, axe])
+
+ // Name of the Monster.
+ let name = builder.create(string: "Orc")
+}
diff --git a/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_8.swift b/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_8.swift
new file mode 100644
index 0000000..a0c2819
--- /dev/null
+++ b/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_8.swift
@@ -0,0 +1,40 @@
+import FlatBuffers
+import Foundation
+
+func run() {
+ // create a `FlatBufferBuilder`, which will be used to serialize objects
+ let builder = FlatBufferBuilder(initialSize: 1024)
+
+ let weapon1Name = builder.create(string: "Sword")
+ let weapon2Name = builder.create(string: "Axe")
+
+ // start creating the weapon by calling startWeapon
+ let weapon1Start = Weapon.startWeapon(&builder)
+ Weapon.add(name: weapon1Name, &builder)
+ Weapon.add(damage: 3, &builder)
+ // end the object by passing the start point for the weapon 1
+ let sword = Weapon.endWeapon(&builder, start: weapon1Start)
+
+ let weapon2Start = Weapon.startWeapon(&builder)
+ Weapon.add(name: weapon2Name, &builder)
+ Weapon.add(damage: 5, &builder)
+ let axe = Weapon.endWeapon(&builder, start: weapon2Start)
+
+ // Create a FlatBuffer `vector` that contains offsets to the sword and axe
+ // we created above.
+ let weaponsOffset = builder.createVector(ofOffsets: [sword, axe])
+
+ // Name of the Monster.
+ let name = builder.create(string: "Orc")
+
+ let pathOffset = fbb.createVector(ofStructs: [
+ Vec3(x: 0, y: 0),
+ Vec3(x: 5, y: 5),
+ ])
+
+ // startVector(len, elementSize: MemoryLayout<Offset>.size)
+ // for o in offsets.reversed() {
+ // push(element: o)
+ // }
+ // endVector(len: len)
+}
diff --git a/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_9.swift b/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_9.swift
new file mode 100644
index 0000000..51ce8fd
--- /dev/null
+++ b/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_9.swift
@@ -0,0 +1,62 @@
+import FlatBuffers
+import Foundation
+
+func run() {
+ // create a `FlatBufferBuilder`, which will be used to serialize objects
+ let builder = FlatBufferBuilder(initialSize: 1024)
+
+ let weapon1Name = builder.create(string: "Sword")
+ let weapon2Name = builder.create(string: "Axe")
+
+ // start creating the weapon by calling startWeapon
+ let weapon1Start = Weapon.startWeapon(&builder)
+ Weapon.add(name: weapon1Name, &builder)
+ Weapon.add(damage: 3, &builder)
+ // end the object by passing the start point for the weapon 1
+ let sword = Weapon.endWeapon(&builder, start: weapon1Start)
+
+ let weapon2Start = Weapon.startWeapon(&builder)
+ Weapon.add(name: weapon2Name, &builder)
+ Weapon.add(damage: 5, &builder)
+ let axe = Weapon.endWeapon(&builder, start: weapon2Start)
+
+ // Create a FlatBuffer `vector` that contains offsets to the sword and axe
+ // we created above.
+ let weaponsOffset = builder.createVector(ofOffsets: [sword, axe])
+
+ // Name of the Monster.
+ let name = builder.create(string: "Orc")
+
+ let pathOffset = fbb.createVector(ofStructs: [
+ Vec3(x: 0, y: 0),
+ Vec3(x: 5, y: 5),
+ ])
+
+ // startVector(len, elementSize: MemoryLayout<Offset>.size)
+ // for o in offsets.reversed() {
+ // push(element: o)
+ // }
+ // endVector(len: len)
+
+ let orc = Monster.createMonster(
+ &builder,
+ pos: Vec3(x: 1, y: 2),
+ hp: 300,
+ nameOffset: name,
+ color: .red,
+ weaponsVectorOffset: weaponsOffset,
+ equippedType: .weapon,
+ equippedOffset: axe,
+ pathOffset: pathOffset)
+
+ // let start = Monster.startMonster(&builder)
+ // Monster.add(pos: Vec3(x: 1, y: 2), &builder)
+ // Monster.add(hp: 300, &builder)
+ // Monster.add(name: name, &builder)
+ // Monster.add(color: .red, &builder)
+ // Monster.addVectorOf(weapons: weaponsOffset, &builder)
+ // Monster.add(equippedType: .weapon, &builder)
+ // Monster.addVectorOf(paths: weaponsOffset, &builder)
+ // Monster.add(equipped: axe, &builder)
+ // var orc = Monster.endMonster(&builder, start: start)
+}
diff --git a/swift/Sources/FlatBuffers/Documentation.docc/Resources/images/tutorial_cover_image_1.png b/swift/Sources/FlatBuffers/Documentation.docc/Resources/images/tutorial_cover_image_1.png
new file mode 100644
index 0000000..0e64fe6
--- /dev/null
+++ b/swift/Sources/FlatBuffers/Documentation.docc/Resources/images/tutorial_cover_image_1.png
Binary files differ
diff --git a/swift/Sources/FlatBuffers/Documentation.docc/Tutorials/Tutorial_Table_of_Contents.tutorial b/swift/Sources/FlatBuffers/Documentation.docc/Tutorials/Tutorial_Table_of_Contents.tutorial
new file mode 100644
index 0000000..009116f
--- /dev/null
+++ b/swift/Sources/FlatBuffers/Documentation.docc/Tutorials/Tutorial_Table_of_Contents.tutorial
@@ -0,0 +1,14 @@
+@Tutorials(name: "Starting with FlatBuffers") {
+ @Intro(title: "Starting with FlatBuffers") {
+ FlatBuffers is an efficient cross platform serialization library for C++,
+ C#, C, Go, Java, Kotlin, JavaScript, Lobster, Lua, TypeScript, PHP, Python, Rust and Swift.
+ It was originally created at Google for game development and other performance-critical applications.
+ }
+ @Chapter(name: "Generating your code") {
+ Start by generating your first FlatBuffers objects.
+ @Image(source: tutorial_cover_image_1.png, alt: "A code structure for a base struct in flatbuffers")
+ @TutorialReference(tutorial: "doc:creating_flatbuffer_schema")
+ @TutorialReference(tutorial: "doc:create_your_first_buffer")
+ @TutorialReference(tutorial: "doc:reading_bytebuffer")
+ }
+}
diff --git a/swift/Sources/FlatBuffers/Documentation.docc/Tutorials/create_your_first_buffer.tutorial b/swift/Sources/FlatBuffers/Documentation.docc/Tutorials/create_your_first_buffer.tutorial
new file mode 100644
index 0000000..2f8089f
--- /dev/null
+++ b/swift/Sources/FlatBuffers/Documentation.docc/Tutorials/create_your_first_buffer.tutorial
@@ -0,0 +1,72 @@
+@Tutorial(time: 5) {
+ @Intro(title: "After having our code generated") {
+ After generating the code from the previous section, we will know start creating our monster object.
+ We will create a monster object called orc.
+ }
+
+ @Section(title: "Building your first buffer") {
+ @ContentAndMedia {}
+ @Steps {
+ @Step {
+ Starting with a new file, we will create our very first Flatbuffer.
+ @Code(name: "ViewController.swift", file: "swift_code_1.swift")
+ }
+ @Step {
+ First, we need to import ``FlatBuffers``
+ @Code(name: "ViewController.swift", file: "swift_code_2.swift")
+ }
+ @Step {
+ We need to create an instance of the `FlatBufferBuilder`, which will contain the buffer as it grows.
+ You can pass an initial size of the buffer (here 1024 bytes), which will grow automatically if needed.
+ @Code(name: "ViewController.swift", file: "swift_code_3.swift")
+ }
+ @Step {
+ After creating the builder, we can start serializing our data. Before we make our orc Monster,
+ let's create some Weapons: a Sword and an Axe. However we will start by naming our weapons as `Sword` and `Axe`
+ @Code(name: "ViewController.swift", file: "swift_code_4.swift")
+ }
+ @Step {
+ After naming the weapons, we will create two weapon objects with the damage that the weapon is going to deal.
+ That's done by calling the `start` Method on each table you will be creating, in this case its called `startWeapon`
+ and finished by calling `end`.
+ @Code(name: "ViewController.swift", file: "swift_code_5.swift")
+ }
+ @Step {
+ We will take our (Sword and Axe) serialized data and serialize their offsets as a vector of tables into our `ByteBuffer`.
+ So we can reference them later on from our Monster Object
+ @Code(name: "ViewController.swift", file: "swift_code_6.swift")
+ }
+ @Step {
+ We will add our Monster name as a string value just like we did with the weapons.
+ @Code(name: "ViewController.swift", file: "swift_code_7.swift")
+ }
+
+ @Step {
+ We will create a path that our monster should be using while roaming in its den. To create a vector of paths we would us
+ `createVector(ofStructs: [])` which will take a Native `Swift` struct that has been padded to fit the `FlatBuffers` standards.
+
+ There are usually two ways of creating vectors in `FlatBuffers` which you can see in commented out code.
+ And thus there are multiple convenience methods that will cover all the bases
+ when trying to create a vector so that you dont have to create it with `start` and `end`
+ @Code(name: "ViewController.swift", file: "swift_code_8.swift")
+ }
+
+ @Step {
+ Now to serialize our data into our `Monster` object. Which again there are two ways of doing, by calling the `create` method or
+ by serializing the objects yourself. What we added to our Monster were the `Equipped Type` and the `Equipped` union itself, which
+ allows the Monster to have the `Axe` as his equipped weapon.
+
+ Important: Unlike structs, you should not nest tables or other objects,
+ which is why we created all the `strings/vectors/tables` that this monster refers to before start.
+ If you try to create any of them between start and end, you will get an `assert`.
+ @Code(name: "ViewController.swift", file: "swift_code_9.swift")
+ }
+
+ @Step {
+ Finally you can just finalize the buffer by calling `builder.finish` and get the Byte array from the buffer.
+ @Code(name: "ViewController.swift", file: "swift_code_10.swift")
+ }
+
+ }
+ }
+ }
diff --git a/swift/Sources/FlatBuffers/Documentation.docc/Tutorials/creating_flatbuffer_schema.tutorial b/swift/Sources/FlatBuffers/Documentation.docc/Tutorials/creating_flatbuffer_schema.tutorial
new file mode 100644
index 0000000..0fcd362
--- /dev/null
+++ b/swift/Sources/FlatBuffers/Documentation.docc/Tutorials/creating_flatbuffer_schema.tutorial
@@ -0,0 +1,47 @@
+@Tutorial(time: 2) {
+ @Intro(title: "Creating a schema") {
+ You will need to have the FlatBuffer compiler to be installed on your device
+ }
+
+ @Section(title: "Creating a schema") {
+ @ContentAndMedia {}
+ @Steps {
+ @Step {
+ Start by creating a new empty folder called `monster.fbs`. We want to create a Monster table, that contains
+ position, color, and basic information about the monster.
+ @Code(name: "monster.fbs", file: "monster_step_1.fbs")
+ }
+ @Step {
+ We will start by adding our Color object. We will be using an enumerate, to represent this object
+ @Code(name: "monster.fbs", file: "monster_step_2.fbs")
+ }
+ @Step {
+ We will add a position object and will use a struct to represent that type of data. Where we will need the monsters
+ x and y positions.
+ @Code(name: "monster.fbs", file: "monster_step_3.fbs")
+ }
+ @Step {
+ Then we will be creating our Monster object of type table. This will contain the current position of our
+ monster and its color
+ @Code(name: "monster.fbs", file: "monster_step_4.fbs")
+ }
+ @Step {
+ Our Monster is missing a name, mana, hp, name, equipped Weapon, weapons, and path. We will be adding these
+ fields to our table with a proper data type for each. Example; weapons, and path would be a vector of data.
+ @Code(name: "monster.fbs", file: "monster_step_5.fbs")
+ }
+ @Step {
+ Now we are missing two data types here, `Weapon` and `Equipment`. And since Equipment can be a weapon, we will be using
+ a `Union` enumerate that can contain all the equipment that you would want your monster to have. And the weapon can simply
+ have a name and amount of damage
+ @Code(name: "monster.fbs", file: "monster_step_6.fbs")
+ }
+ @Step {
+ And to finalize our monster table, we can add a root type of type Monster.
+ Then run the command `flatc --swift monster.fbs`
+ Note: Make sure to import the file to your xcode project.
+ @Code(name: "monster.fbs", file: "monster_step_7.fbs")
+ }
+ }
+ }
+ }
diff --git a/swift/Sources/FlatBuffers/Documentation.docc/Tutorials/reading_bytebuffer.tutorial b/swift/Sources/FlatBuffers/Documentation.docc/Tutorials/reading_bytebuffer.tutorial
new file mode 100644
index 0000000..2c4609f
--- /dev/null
+++ b/swift/Sources/FlatBuffers/Documentation.docc/Tutorials/reading_bytebuffer.tutorial
@@ -0,0 +1,27 @@
+@Tutorial(time: 2) {
+ @Intro(title: "Reading ByteBuffers") {
+ After getting our ByteBuffer created, we can now read it.
+ }
+
+ @Section(title: "Reading your first buffer") {
+ @ContentAndMedia {}
+ @Steps {
+ @Step {
+ After fetching the data from disk or network you need to access that data, and that can be done.
+ By simply calling `getCheckedRoot`, which checks if the data is valid before enabling you to read from a corrupt buffer.
+ however, if you are sure that the data is 100% correct you can simply call `getRoot`
+ @Code(name: "ViewController.swift", file: "swift_code_11.swift")
+ }
+ @Step {
+ Now since we have a Monster object, all the fields can be accessed by simply fetching the data. Note, Deprecated fields will not
+ show up
+ @Code(name: "ViewController.swift", file: "swift_code_12.swift")
+ }
+ @Step {
+ And you can access union types as easy as this
+ @Code(name: "ViewController.swift", file: "swift_code_13.swift")
+ }
+ }
+ }
+ }
+
diff --git a/swift/Sources/FlatBuffers/Enum.swift b/swift/Sources/FlatBuffers/Enum.swift
new file mode 100644
index 0000000..efb698b
--- /dev/null
+++ b/swift/Sources/FlatBuffers/Enum.swift
@@ -0,0 +1,55 @@
+/*
+ * Copyright 2021 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.
+ */
+
+import Foundation
+
+/// Enum is a protocol that all flatbuffers enums should conform to
+/// Since it allows us to get the actual `ByteSize` and `Value` from
+/// a swift enum.
+public protocol Enum {
+ /// associatedtype that the type of the enum should conform to
+ associatedtype T: Scalar & Verifiable
+ /// Size of the current associatedtype in the enum
+ static var byteSize: Int { get }
+ /// The current value the enum hosts
+ var value: T { get }
+}
+
+extension Enum where Self: Verifiable {
+
+ /// Verifies that the current value is which the bounds of the buffer, and if
+ /// the current `Value` is aligned properly
+ /// - Parameters:
+ /// - verifier: Verifier that hosts the buffer
+ /// - position: Current position within the buffer
+ /// - type: The type of the object to be verified
+ /// - Throws: Errors coming from `inBuffer` function
+ public static func verify<T>(
+ _ verifier: inout Verifier,
+ at position: Int,
+ of type: T.Type) throws where T: Verifiable
+ {
+ try verifier.inBuffer(position: position, of: type.self)
+ }
+
+}
+
+/// UnionEnum is a Protocol that allows us to create Union type of enums
+/// and their value initializers. Since an `init` was required by
+/// the verifier
+public protocol UnionEnum: Enum {
+ init?(value: T) throws
+}
diff --git a/swift/Sources/FlatBuffers/FlatBufferBuilder.swift b/swift/Sources/FlatBuffers/FlatBufferBuilder.swift
index 71fcab0..5ccc7e4 100644
--- a/swift/Sources/FlatBuffers/FlatBufferBuilder.swift
+++ b/swift/Sources/FlatBuffers/FlatBufferBuilder.swift
@@ -1,5 +1,5 @@
/*
- * Copyright 2020 Google Inc. All rights reserved.
+ * Copyright 2021 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.
@@ -16,19 +16,30 @@
import Foundation
+/// ``FlatBufferBuilder`` builds a `FlatBuffer` through manipulating its internal state.
+///
+/// This is done by creating a ``ByteBuffer`` that hosts the incoming data and
+/// has a hardcoded growth limit of `2GiB` which is set by the Flatbuffers standards.
+///
+/// ```swift
+/// var builder = FlatBufferBuilder()
+/// ```
+/// The builder should be always created as a variable, since it would be passed into the writers
+///
+@frozen
public struct FlatBufferBuilder {
/// Storage for the Vtables used in the buffer are stored in here, so they would be written later in EndTable
@usableFromInline internal var _vtableStorage = VTableStorage()
+ /// Flatbuffer data will be written into
+ @usableFromInline internal var _bb: ByteBuffer
/// Reference Vtables that were already written to the buffer
private var _vtables: [UOffset] = []
- /// Flatbuffer data will be written into
- private var _bb: ByteBuffer
/// A check if the buffer is being written into by a different table
private var isNested = false
/// Dictonary that stores a map of all the strings that were written to the buffer
- private var stringOffsetMap: [String: Offset<String>] = [:]
+ private var stringOffsetMap: [String: Offset] = [:]
/// A check to see if finish(::) was ever called to retreive data object
private var finished = false
/// A check to see if the buffer should serialize Default values
@@ -43,55 +54,76 @@
/// Gives a read access to the buffer's size
public var size: UOffset { _bb.size }
+
/// Data representation of the buffer
+ ///
+ /// Should only be used after ``finish(offset:addPrefix:)`` is called
public var data: Data {
assert(finished, "Data shouldn't be called before finish()")
return Data(
bytes: _bb.memory.advanced(by: _bb.writerIndex),
count: _bb.capacity &- _bb.writerIndex)
}
- /// Get's the fully sized buffer stored in memory
+
+ /// Returns the underlying bytes in the ``ByteBuffer``
+ ///
+ /// Note: This should be used with caution.
public var fullSizedByteArray: [UInt8] {
let ptr = UnsafeBufferPointer(
start: _bb.memory.assumingMemoryBound(to: UInt8.self),
count: _bb.capacity)
return Array(ptr)
}
- /// Returns the written size of the buffer
+
+ /// Returns the written bytes into the ``ByteBuffer``
+ ///
+ /// Should only be used after ``finish(offset:addPrefix:)`` is called
public var sizedByteArray: [UInt8] {
assert(finished, "Data shouldn't be called before finish()")
- let cp = _bb.capacity &- _bb.writerIndex
- let start = _bb.memory.advanced(by: _bb.writerIndex)
- .bindMemory(to: UInt8.self, capacity: cp)
-
- let ptr = UnsafeBufferPointer(start: start, count: cp)
- return Array(ptr)
+ return _bb.underlyingBytes
}
- /// Returns the buffer
+
+ /// Returns the original ``ByteBuffer``
+ ///
+ /// Returns the current buffer that was just created
+ /// with the offsets, and data written to it.
public var buffer: ByteBuffer { _bb }
- /// Returns A sized Buffer from the readable bytes
+ /// Returns a newly created sized ``ByteBuffer``
+ ///
+ /// returns a new buffer that is sized to the data written
+ /// to the main buffer
public var sizedBuffer: ByteBuffer {
assert(finished, "Data shouldn't be called before finish()")
- return ByteBuffer(memory: _bb.memory.advanced(by: _bb.reader), count: Int(_bb.size))
+ return ByteBuffer(
+ memory: _bb.memory.advanced(by: _bb.reader),
+ count: Int(_bb.size))
}
// MARK: - Init
- /// initialize the buffer with a size
+ /// Initialize the buffer with a size
/// - Parameters:
/// - initialSize: Initial size for the buffer
/// - force: Allows default to be serialized into the buffer
- public init(initialSize: Int32 = 1024, serializeDefaults force: Bool = false) {
+ ///
+ /// This initializes a new builder with an initialSize that would initialize
+ /// a new ``ByteBuffer``. ``FlatBufferBuilder`` by default doesnt serialize defaults
+ /// however the builder can be force by passing true for `serializeDefaults`
+ public init(
+ initialSize: Int32 = 1024,
+ serializeDefaults force: Bool = false)
+ {
assert(initialSize > 0, "Size should be greater than zero!")
guard isLitteEndian else {
- fatalError("Reading/Writing a buffer in big endian machine is not supported on swift")
+ fatalError(
+ "Reading/Writing a buffer in big endian machine is not supported on swift")
}
serializeDefaults = force
_bb = ByteBuffer(initialSize: Int(initialSize))
}
- /// Clears the buffer and the builder from it's data
+ /// Clears the builder and the buffer from the written data.
mutating public func clear() {
_minAlignment = 0
isNested = false
@@ -107,11 +139,16 @@
/// - Parameters:
/// - table: offset for the table
/// - fields: Array of all the important fields to be serialized
- mutating public func require(table: Offset<UOffset>, fields: [Int32]) {
+ ///
+ /// *NOTE: Never call this function, this is only supposed to be called
+ /// by the generated code*
+ mutating public func require(table: Offset, fields: [Int32]) {
for field in fields {
let start = _bb.capacity &- Int(table.o)
let startTable = start &- Int(_bb.read(def: Int32.self, position: start))
- let isOkay = _bb.read(def: VOffset.self, position: startTable &+ Int(field)) != 0
+ let isOkay = _bb.read(
+ def: VOffset.self,
+ position: startTable &+ Int(field)) != 0
assert(isOkay, "Flatbuffers requires the following field")
}
}
@@ -121,9 +158,32 @@
/// - offset: Offset of the table
/// - fileId: Takes the fileId
/// - prefix: if false it wont add the size of the buffer
- mutating public func finish<T>(offset: Offset<T>, fileId: String, addPrefix prefix: Bool = false) {
+ ///
+ /// ``finish(offset:fileId:addPrefix:)`` should be called at the end of creating
+ /// a table
+ /// ```swift
+ /// var root = SomeObject
+ /// .createObject(&builder,
+ /// name: nameOffset)
+ /// builder.finish(
+ /// offset: root,
+ /// fileId: "ax1a",
+ /// addPrefix: true)
+ /// ```
+ /// File id would append a file id name at the end of the written bytes before,
+ /// finishing the buffer.
+ ///
+ /// Whereas, if `addPrefix` is true, the written bytes would
+ /// include the size of the current buffer.
+ mutating public func finish(
+ offset: Offset,
+ fileId: String,
+ addPrefix prefix: Bool = false)
+ {
let size = MemoryLayout<UOffset>.size
- preAlign(len: size &+ (prefix ? size : 0) &+ FileIdLength, alignment: _minAlignment)
+ preAlign(
+ len: size &+ (prefix ? size : 0) &+ FileIdLength,
+ alignment: _minAlignment)
assert(fileId.count == FileIdLength, "Flatbuffers requires file id to be 4")
_bb.push(string: fileId, len: 4)
finish(offset: offset, addPrefix: prefix)
@@ -133,7 +193,23 @@
/// - Parameters:
/// - offset: Offset of the table
/// - prefix: if false it wont add the size of the buffer
- mutating public func finish<T>(offset: Offset<T>, addPrefix prefix: Bool = false) {
+ ///
+ /// ``finish(offset:addPrefix:)`` should be called at the end of creating
+ /// a table
+ /// ```swift
+ /// var root = SomeObject
+ /// .createObject(&builder,
+ /// name: nameOffset)
+ /// builder.finish(
+ /// offset: root,
+ /// addPrefix: true)
+ /// ```
+ /// If `addPrefix` is true, the written bytes would
+ /// include the size of the current buffer.
+ mutating public func finish(
+ offset: Offset,
+ addPrefix prefix: Bool = false)
+ {
notNested()
let size = MemoryLayout<UOffset>.size
preAlign(len: size &+ (prefix ? size : 0), alignment: _minAlignment)
@@ -143,10 +219,15 @@
finished = true
}
- /// starttable will let the builder know, that a new object is being serialized.
+ /// ``startTable(with:)`` will let the builder know, that a new object is being serialized.
///
- /// The function will fatalerror if called while there is another object being serialized
+ /// The function will fatalerror if called while there is another object being serialized.
+ /// ```swift
+ /// let start = Monster
+ /// .startMonster(&fbb)
+ /// ```
/// - Parameter numOfFields: Number of elements to be written to the buffer
+ /// - Returns: Offset of the newly started table
mutating public func startTable(with numOfFields: Int) -> UOffset {
notNested()
isNested = true
@@ -154,11 +235,14 @@
return _bb.size
}
- /// Endtable will let the builder know that the object that's written to it is completed
+ /// ``endTable(at:)`` will let the ``FlatBufferBuilder`` know that the
+ /// object that's written to it is completed
///
- /// This would be called after all the elements are serialized, it will add the vtable into the buffer.
- /// it will fatalError in case the object is called without starttable, or the object has exceeded the limit of
- /// 2GB,
+ /// This would be called after all the elements are serialized,
+ /// it will add the current vtable into the ``ByteBuffer``.
+ /// The functions will `fatalError` in case the object is called
+ /// without ``startTable(with:)``, or the object has exceeded the limit of 2GB.
+ ///
/// - Parameter startOffset:Start point of the object written
/// - returns: The root of the table
mutating public func endTable(at startOffset: UOffset) -> UOffset {
@@ -183,7 +267,10 @@
itr = itr &+ _vtableStorage.size
guard loaded.offset != 0 else { continue }
let _index = (_bb.writerIndex &+ Int(loaded.position))
- _bb.write(value: VOffset(vTableOffset &- loaded.offset), index: _index, direct: true)
+ _bb.write(
+ value: VOffset(vTableOffset &- loaded.offset),
+ index: _index,
+ direct: true)
}
_vtableStorage.clear()
@@ -219,7 +306,7 @@
// MARK: - Builds Buffer
- /// asserts to see if the object is not nested
+ /// Asserts to see if the object is not nested
@usableFromInline
mutating internal func notNested() {
assert(!isNested, "Object serialization must not be nested")
@@ -227,7 +314,7 @@
/// Changes the minimuim alignment of the buffer
/// - Parameter size: size of the current alignment
- @usableFromInline
+ @inline(__always)
mutating internal func minAlignment(size: Int) {
if size > _minAlignment {
_minAlignment = size
@@ -238,8 +325,11 @@
/// - Parameters:
/// - bufSize: Current size of the buffer + the offset of the object to be written
/// - elementSize: Element size
- @usableFromInline
- mutating internal func padding(bufSize: UInt32, elementSize: UInt32) -> UInt32 {
+ @inline(__always)
+ mutating internal func padding(
+ bufSize: UInt32,
+ elementSize: UInt32) -> UInt32
+ {
((~bufSize) &+ 1) & (elementSize - 1)
}
@@ -282,9 +372,20 @@
_vtableStorage.add(loc: FieldLoc(offset: offset, position: position))
}
- // MARK: - Vectors
+ // MARK: - Inserting Vectors
- /// Starts a vector of length and Element size
+ /// ``startVector(_:elementSize:)`` creates a new vector within buffer
+ ///
+ /// The function checks if there is a current object being written, if
+ /// the check passes it creates a buffer alignment of `length * elementSize`
+ /// ```swift
+ /// builder.startVector(
+ /// int32Values.count, elementSize: 4)
+ /// ```
+ ///
+ /// - Parameters:
+ /// - len: Length of vector to be created
+ /// - elementSize: Size of object type to be written
mutating public func startVector(_ len: Int, elementSize: Int) {
notNested()
isNested = true
@@ -292,185 +393,268 @@
preAlign(len: len &* elementSize, alignment: elementSize)
}
- /// Ends the vector of at length
+ /// ``endVector(len:)`` ends the currently created vector
///
- /// The current function will fatalError if startVector is called before serializing the vector
+ /// Calling ``endVector(len:)`` requires the length, of the current
+ /// vector. The length would be pushed to indicate the count of numbers
+ /// within the vector. If ``endVector(len:)`` is called without
+ /// ``startVector(_:elementSize:)`` it asserts.
+ ///
+ /// ```swift
+ /// let vectorOffset = builder.
+ /// endVector(len: int32Values.count)
+ /// ```
+ ///
/// - Parameter len: Length of the buffer
- mutating public func endVector(len: Int) -> UOffset {
+ /// - Returns: Returns the current ``Offset`` in the ``ByteBuffer``
+ mutating public func endVector(len: Int) -> Offset {
assert(isNested, "Calling endVector without calling startVector")
isNested = false
- return push(element: Int32(len))
+ return Offset(offset: push(element: Int32(len)))
}
- /// Creates a vector of type Scalar in the buffer
+ /// Creates a vector of type ``Scalar`` into the ``ByteBuffer``
+ ///
+ /// ``createVector(_:)-4swl0`` writes a vector of type Scalars into
+ /// ``ByteBuffer``. This is a convenient method instead of calling,
+ /// ``startVector(_:elementSize:)`` and then ``endVector(len:)``
+ /// ```swift
+ /// let vectorOffset = builder.
+ /// createVector([1, 2, 3, 4])
+ /// ```
+ ///
+ /// The underlying implementation simply calls ``createVector(_:size:)-4lhrv``
+ ///
/// - Parameter elements: elements to be written into the buffer
- /// - returns: Offset of the vector
- mutating public func createVector<T: Scalar>(_ elements: [T]) -> Offset<UOffset> {
+ /// - returns: ``Offset`` of the vector
+ mutating public func createVector<T: Scalar>(_ elements: [T]) -> Offset {
createVector(elements, size: elements.count)
}
/// Creates a vector of type Scalar in the buffer
+ ///
+ /// ``createVector(_:)-4swl0`` writes a vector of type Scalars into
+ /// ``ByteBuffer``. This is a convenient method instead of calling,
+ /// ``startVector(_:elementSize:)`` and then ``endVector(len:)``
+ /// ```swift
+ /// let vectorOffset = builder.
+ /// createVector([1, 2, 3, 4], size: 4)
+ /// ```
+ ///
/// - Parameter elements: Elements to be written into the buffer
/// - Parameter size: Count of elements
- /// - returns: Offset of the vector
- mutating public func createVector<T: Scalar>(_ elements: [T], size: Int) -> Offset<UOffset> {
+ /// - returns: ``Offset`` of the vector
+ mutating public func createVector<T: Scalar>(
+ _ elements: [T],
+ size: Int) -> Offset
+ {
let size = size
startVector(size, elementSize: MemoryLayout<T>.size)
_bb.push(elements: elements)
- return Offset(offset: endVector(len: size))
+ return endVector(len: size)
}
- /// Creates a vector of type Enums in the buffer
+ /// Creates a vector of type ``Enum`` into the ``ByteBuffer``
+ ///
+ /// ``createVector(_:)-9h189`` writes a vector of type ``Enum`` into
+ /// ``ByteBuffer``. This is a convenient method instead of calling,
+ /// ``startVector(_:elementSize:)`` and then ``endVector(len:)``
+ /// ```swift
+ /// let vectorOffset = builder.
+ /// createVector([.swift, .cpp])
+ /// ```
+ ///
+ /// The underlying implementation simply calls ``createVector(_:size:)-7cx6z``
+ ///
/// - Parameter elements: elements to be written into the buffer
- /// - returns: Offset of the vector
- mutating public func createVector<T: Enum>(_ elements: [T]) -> Offset<UOffset> {
+ /// - returns: ``Offset`` of the vector
+ mutating public func createVector<T: Enum>(_ elements: [T]) -> Offset {
createVector(elements, size: elements.count)
}
- /// Creates a vector of type Enums in the buffer
+ /// Creates a vector of type ``Enum`` into the ``ByteBuffer``
+ ///
+ /// ``createVector(_:)-9h189`` writes a vector of type ``Enum`` into
+ /// ``ByteBuffer``. This is a convenient method instead of calling,
+ /// ``startVector(_:elementSize:)`` and then ``endVector(len:)``
+ /// ```swift
+ /// let vectorOffset = builder.
+ /// createVector([.swift, .cpp])
+ /// ```
+ ///
/// - Parameter elements: Elements to be written into the buffer
/// - Parameter size: Count of elements
- /// - returns: Offset of the vector
- mutating public func createVector<T: Enum>(_ elements: [T], size: Int) -> Offset<UOffset> {
+ /// - returns: ``Offset`` of the vector
+ mutating public func createVector<T: Enum>(
+ _ elements: [T],
+ size: Int) -> Offset
+ {
let size = size
startVector(size, elementSize: T.byteSize)
for e in elements.reversed() {
_bb.push(value: e.value, len: T.byteSize)
}
- return Offset(offset: endVector(len: size))
+ return endVector(len: size)
}
- /// Creates a vector of type Offsets in the buffer
- /// - Parameter offsets:Array of offsets of type T
- /// - returns: Offset of the vector
- mutating public func createVector<T>(ofOffsets offsets: [Offset<T>]) -> Offset<UOffset> {
+ /// Creates a vector of already written offsets
+ ///
+ /// ``createVector(ofOffsets:)`` creates a vector of ``Offset`` into
+ /// ``ByteBuffer``. This is a convenient method instead of calling,
+ /// ``startVector(_:elementSize:)`` and then ``endVector(len:)``.
+ ///
+ /// The underlying implementation simply calls ``createVector(ofOffsets:len:)``
+ ///
+ /// ```swift
+ /// let namesOffsets = builder.
+ /// createVector(ofOffsets: [name1, name2])
+ /// ```
+ /// - Parameter offsets: Array of offsets of type ``Offset``
+ /// - returns: ``Offset`` of the vector
+ mutating public func createVector(ofOffsets offsets: [Offset]) -> Offset {
createVector(ofOffsets: offsets, len: offsets.count)
}
- /// Creates a vector of type Offsets in the buffer
- /// - Parameter elements: Array of offsets of type T
+ /// Creates a vector of already written offsets
+ ///
+ /// ``createVector(ofOffsets:)`` creates a vector of ``Offset`` into
+ /// ``ByteBuffer``. This is a convenient method instead of calling,
+ /// ``startVector(_:elementSize:)`` and then ``endVector(len:)``
+ ///
+ /// ```swift
+ /// let namesOffsets = builder.
+ /// createVector(ofOffsets: [name1, name2])
+ /// ```
+ ///
+ /// - Parameter offsets: Array of offsets of type ``Offset``
/// - Parameter size: Count of elements
- /// - returns: Offset of the vector
- mutating public func createVector<T>(ofOffsets offsets: [Offset<T>], len: Int) -> Offset<UOffset> {
- startVector(len, elementSize: MemoryLayout<Offset<T>>.size)
+ /// - returns: ``Offset`` of the vector
+ mutating public func createVector(
+ ofOffsets offsets: [Offset],
+ len: Int) -> Offset
+ {
+ startVector(len, elementSize: MemoryLayout<Offset>.size)
for o in offsets.reversed() {
push(element: o)
}
- return Offset(offset: endVector(len: len))
+ return endVector(len: len)
}
- /// Creates a vector of Strings
- /// - Parameter str: a vector of strings that will be written into the buffer
- /// - returns: Offset of the vector
- mutating public func createVector(ofStrings str: [String]) -> Offset<UOffset> {
- var offsets: [Offset<String>] = []
+ /// Creates a vector of strings
+ ///
+ /// ``createVector(ofStrings:)`` creates a vector of `String` into
+ /// ``ByteBuffer``. This is a convenient method instead of manually
+ /// creating the string offsets, you simply pass it to this function
+ /// and it would write the strings into the ``ByteBuffer``.
+ /// After that it calls ``createVector(ofOffsets:)``
+ ///
+ /// ```swift
+ /// let namesOffsets = builder.
+ /// createVector(ofStrings: ["Name", "surname"])
+ /// ```
+ ///
+ /// - Parameter str: Array of string
+ /// - returns: ``Offset`` of the vector
+ mutating public func createVector(ofStrings str: [String]) -> Offset {
+ var offsets: [Offset] = []
for s in str {
offsets.append(create(string: s))
}
return createVector(ofOffsets: offsets)
}
- /// Creates a vector of Flatbuffer structs.
+ /// Creates a vector of type ``NativeStruct``.
///
- /// The function takes a Type to know what size it is, and alignment
- /// - Parameters:
- /// - structs: An array of UnsafeMutableRawPointer
- /// - type: Type of the struct being written
- /// - returns: Offset of the vector
- @available(
- *,
- deprecated,
- message: "0.9.0 will be removing the following method. Regenerate the code")
- mutating public func createVector<T: Readable>(
- structs: [UnsafeMutableRawPointer],
- type: T.Type) -> Offset<UOffset>
+ /// Any swift struct in the generated code, should confirm to
+ /// ``NativeStruct``. Since the generated swift structs are padded
+ /// to the `FlatBuffers` standards.
+ ///
+ /// ```swift
+ /// let offsets = builder.
+ /// createVector(ofStructs: [NativeStr(num: 1), NativeStr(num: 2)])
+ /// ```
+ ///
+ /// - Parameter structs: A vector of ``NativeStruct``
+ /// - Returns: ``Offset`` of the vector
+ mutating public func createVector<T: NativeStruct>(ofStructs structs: [T])
+ -> Offset
{
- startVector(structs.count &* T.size, elementSize: T.alignment)
+ startVector(
+ structs.count * MemoryLayout<T>.size,
+ elementSize: MemoryLayout<T>.alignment)
for i in structs.reversed() {
- create(struct: i, type: T.self)
+ _ = create(struct: i)
}
- return Offset(offset: endVector(len: structs.count))
- }
-
- /// Starts a vector of struct that considers the size and alignment of the struct
- /// - Parameters:
- /// - count: number of elements to be written
- /// - size: size of struct
- /// - alignment: alignment of the struct
- mutating public func startVectorOfStructs(count: Int, size: Int, alignment: Int) {
- startVector(count &* size, elementSize: alignment)
- }
-
- /// Ends the vector of structs and writtens the current offset
- /// - Parameter count: number of written elements
- /// - Returns: Offset of type UOffset
- mutating public func endVectorOfStructs(count: Int) -> Offset<UOffset> {
- Offset<UOffset>(offset: endVector(len: count))
+ return endVector(len: structs.count)
}
// MARK: - Inserting Structs
- /// Writes a Flatbuffer struct into the buffer
+ /// Writes a ``NativeStruct`` into the ``ByteBuffer``
+ ///
+ /// Adds a native struct that's build and padded according
+ /// to `FlatBuffers` standards. with a predefined position.
+ ///
+ /// ```swift
+ /// let offset = builder.create(
+ /// struct: NativeStr(num: 1),
+ /// position: 10)
+ /// ```
+ ///
/// - Parameters:
- /// - s: Flatbuffer struct
- /// - type: Type of the element to be serialized
- /// - returns: Offset of the Object
- @available(
- *,
- deprecated,
- message: "0.9.0 will be removing the following method. Regenerate the code")
+ /// - s: ``NativeStruct`` to be inserted into the ``ByteBuffer``
+ /// - position: The predefined position of the object
+ /// - Returns: ``Offset`` of written struct
@discardableResult
- mutating public func create<T: Readable>(
- struct s: UnsafeMutableRawPointer,
- type: T.Type) -> Offset<UOffset>
+ mutating public func create<T: NativeStruct>(
+ struct s: T, position: VOffset) -> Offset
{
- let size = T.size
- preAlign(len: size, alignment: T.alignment)
+ let offset = create(struct: s)
+ _vtableStorage.add(loc: FieldLoc(
+ offset: _bb.size,
+ position: VOffset(position)))
+ return offset
+ }
+
+ /// Writes a ``NativeStruct`` into the ``ByteBuffer``
+ ///
+ /// Adds a native struct that's build and padded according
+ /// to `FlatBuffers` standards, directly into the buffer without
+ /// a predefined position.
+ ///
+ /// ```swift
+ /// let offset = builder.create(
+ /// struct: NativeStr(num: 1))
+ /// ```
+ ///
+ /// - Parameters:
+ /// - s: ``NativeStruct`` to be inserted into the ``ByteBuffer``
+ /// - Returns: ``Offset`` of written struct
+ @discardableResult
+ mutating public func create<T: NativeStruct>(
+ struct s: T) -> Offset
+ {
+ let size = MemoryLayout<T>.size
+ preAlign(len: size, alignment: MemoryLayout<T>.alignment)
_bb.push(struct: s, size: size)
return Offset(offset: _bb.size)
}
- /// prepares the ByteBuffer to receive a struct of size and alignment
- /// - Parameters:
- /// - size: size of written struct
- /// - alignment: alignment of written struct
- mutating public func createStructOf(size: Int, alignment: Int) {
- preAlign(len: size, alignment: alignment)
- _bb.prepareBufferToReceiveStruct(of: size)
- }
-
- /// Adds scalars front to back instead of the default behavior of the normal add
- /// - Parameters:
- /// - v: element of type Scalar
- /// - postion: position relative to the `writerIndex`
- mutating public func reverseAdd<T: Scalar>(v: T, postion: Int) {
- _bb.reversePush(
- value: v,
- position: postion,
- len: MemoryLayout<T>.size)
- }
-
- /// Ends the struct and returns the current buffer size
- /// - Returns: Offset of type UOffset
- @discardableResult
- public func endStruct() -> Offset<UOffset> {
- Offset(offset: _bb.size)
- }
-
- /// Adds the offset of a struct into the vTable
- ///
- /// The function fatalErrors if we pass an offset that is out of range
- /// - Parameter o: offset
- mutating public func add(structOffset o: VOffset) {
- _vtableStorage.add(loc: FieldLoc(offset: _bb.size, position: VOffset(o)))
- }
-
// MARK: - Inserting Strings
- /// Insets a string into the buffer using UTF8
+ /// Insets a string into the buffer of type `UTF8`
+ ///
+ /// Adds a swift string into ``ByteBuffer`` by encoding it
+ /// using `UTF8`
+ ///
+ /// ```swift
+ /// let nameOffset = builder
+ /// .create(string: "welcome")
+ /// ```
+ ///
/// - Parameter str: String to be serialized
- /// - returns: The strings offset in the buffer
- mutating public func create(string str: String?) -> Offset<String> {
+ /// - returns: ``Offset`` of inserted string
+ mutating public func create(string str: String?) -> Offset {
guard let str = str else { return Offset() }
let len = str.utf8.count
notNested()
@@ -481,12 +665,26 @@
return Offset(offset: _bb.size)
}
- /// Inserts a shared string to the buffer
+ /// Insets a shared string into the buffer of type `UTF8`
///
- /// The function checks the stringOffsetmap if it's seen a similar string before
+ /// Adds a swift string into ``ByteBuffer`` by encoding it
+ /// using `UTF8`. The function will check if the string,
+ /// is already written to the ``ByteBuffer``
+ ///
+ /// ```swift
+ /// let nameOffset = builder
+ /// .createShared(string: "welcome")
+ ///
+ ///
+ /// let secondOffset = builder
+ /// .createShared(string: "welcome")
+ ///
+ /// assert(nameOffset.o == secondOffset.o)
+ /// ```
+ ///
/// - Parameter str: String to be serialized
- /// - returns: The strings offset in the buffer
- mutating public func createShared(string str: String?) -> Offset<String> {
+ /// - returns: ``Offset`` of inserted string
+ mutating public func createShared(string str: String?) -> Offset {
guard let str = str else { return Offset() }
if let offset = stringOffsetMap[str] {
return offset
@@ -498,37 +696,65 @@
// MARK: - Inseting offsets
- /// Adds the offset of an object into the buffer
+ /// Writes the ``Offset`` of an already written table
+ ///
+ /// Writes the ``Offset`` of a table if not empty into the
+ /// ``ByteBuffer``
+ ///
/// - Parameters:
- /// - offset: Offset of another object to be written
- /// - position: The predefined position of the object
- mutating public func add<T>(offset: Offset<T>, at position: VOffset) {
+ /// - offset: ``Offset`` of another object to be written
+ /// - position: The predefined position of the object
+ mutating public func add(offset: Offset, at position: VOffset) {
if offset.isEmpty { return }
add(element: refer(to: offset.o), def: 0, at: position)
}
- /// Pushes a value of type offset into the buffer
- /// - Parameter o: Offset
- /// - returns: Position of the offset
+ /// Pushes a value of type ``Offset`` into the ``ByteBuffer``
+ /// - Parameter o: ``Offset``
+ /// - returns: Current position of the ``Offset``
@discardableResult
- mutating public func push<T>(element o: Offset<T>) -> UOffset {
+ mutating public func push(element o: Offset) -> UOffset {
push(element: refer(to: o.o))
}
// MARK: - Inserting Scalars to Buffer
- /// Adds a value into the buffer of type Scalar
+ /// Writes a ``Scalar`` value into ``ByteBuffer``
+ ///
+ /// ``add(element:def:at:)`` takes in a default value, and current value
+ /// and the position within the `VTable`. The default value would not
+ /// be serialized if the value is the same as the current value or
+ /// `serializeDefaults` is equal to false.
+ ///
+ /// If serializing defaults is important ``init(initialSize:serializeDefaults:)``,
+ /// passing true for `serializeDefaults` would do the job.
+ ///
+ /// ```swift
+ /// // Adds 10 to the buffer
+ /// builder.add(element: Int(10), def: 1, position 12)
+ /// ```
+ ///
+ /// *NOTE: Never call this manually*
///
/// - Parameters:
/// - element: Element to insert
/// - def: Default value for that element
/// - position: The predefined position of the element
- mutating public func add<T: Scalar>(element: T, def: T, at position: VOffset) {
+ mutating public func add<T: Scalar>(
+ element: T,
+ def: T,
+ at position: VOffset)
+ {
if element == def && !serializeDefaults { return }
track(offset: push(element: element), at: position)
}
- /// Adds a value into the buffer of type optional Scalar
+ /// Writes a optional ``Scalar`` value into ``ByteBuffer``
+ ///
+ /// Takes an optional value to be written into the ``ByteBuffer``
+ ///
+ /// *NOTE: Never call this manually*
+ ///
/// - Parameters:
/// - element: Optional element of type scalar
/// - position: The predefined position of the element
@@ -537,7 +763,10 @@
track(offset: push(element: element), at: position)
}
- /// Pushes the values into the buffer
+ /// Pushes a values of type ``Scalar`` into the ``ByteBuffer``
+ ///
+ /// *NOTE: Never call this manually*
+ ///
/// - Parameter element: Element to insert
/// - returns: Postion of the Element
@discardableResult
@@ -582,12 +811,13 @@
var numOfFields: Int = 0
/// Last written Index
var writtenIndex: Int = 0
- /// the amount of added elements into the buffer
- var addedElements: Int { capacity - (numOfFields &* size) }
/// Creates the memory to store the buffer in
+ @usableFromInline
init() {
- memory = UnsafeMutableRawBufferPointer.allocate(byteCount: 0, alignment: 0)
+ memory = UnsafeMutableRawBufferPointer.allocate(
+ byteCount: 0,
+ alignment: 0)
}
deinit {
@@ -596,6 +826,7 @@
/// Builds a buffer with byte count of fieldloc.size * count of field numbers
/// - Parameter count: number of fields to be written
+ @inline(__always)
func start(count: Int) {
assert(count >= 0, "number of fields should NOT be negative")
let capacity = count &* size
@@ -606,7 +837,9 @@
/// and max offset
/// - Parameter loc: Location of encoded element
func add(loc: FieldLoc) {
- memory.baseAddress?.advanced(by: writtenIndex).storeBytes(of: loc, as: FieldLoc.self)
+ memory.baseAddress?.advanced(by: writtenIndex).storeBytes(
+ of: loc,
+ as: FieldLoc.self)
writtenIndex = writtenIndex &+ size
numOfFields = numOfFields &+ 1
maxOffset = max(loc.position, maxOffset)
@@ -621,16 +854,20 @@
/// Ensure that the buffer has enough space instead of recreating the buffer each time.
/// - Parameter space: space required for the new vtable
+ @inline(__always)
func ensure(space: Int) {
guard space &+ writtenIndex > capacity else { return }
memory.deallocate()
- memory = UnsafeMutableRawBufferPointer.allocate(byteCount: space, alignment: size)
+ memory = UnsafeMutableRawBufferPointer.allocate(
+ byteCount: space,
+ alignment: size)
capacity = space
}
/// Loads an object of type `FieldLoc` from buffer memory
/// - Parameter index: index of element
/// - Returns: a FieldLoc at index
+ @inline(__always)
func load(at index: Int) -> FieldLoc {
memory.load(fromByteOffset: index, as: FieldLoc.self)
}
diff --git a/swift/Sources/FlatBuffers/FlatBufferObject.swift b/swift/Sources/FlatBuffers/FlatBufferObject.swift
index 7536c40..df8ad8d 100644
--- a/swift/Sources/FlatBuffers/FlatBufferObject.swift
+++ b/swift/Sources/FlatBuffers/FlatBufferObject.swift
@@ -1,5 +1,5 @@
/*
- * Copyright 2020 Google Inc. All rights reserved.
+ * Copyright 2021 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.
@@ -16,29 +16,49 @@
import Foundation
-/// FlatbufferObject structures all the Flatbuffers objects
-public protocol FlatBufferObject {
- var __buffer: ByteBuffer! { get }
+/// NativeStruct is a protocol that indicates if the struct is a native `swift` struct
+/// since now we will be serializing native structs into the buffer.
+public protocol NativeStruct {}
+
+/// FlatbuffersInitializable is a protocol that allows any object to be
+/// Initialized from a ByteBuffer
+public protocol FlatbuffersInitializable {
+ /// Any flatbuffers object that confirms to this protocol is going to be
+ /// initializable through this initializer
init(_ bb: ByteBuffer, o: Int32)
}
-public protocol ObjectAPI {
+/// FlatbufferObject structures all the Flatbuffers objects
+public protocol FlatBufferObject: FlatbuffersInitializable {
+ var __buffer: ByteBuffer! { get }
+}
+
+/// ``ObjectAPIPacker`` is a protocol that allows object to pack and unpack from a
+/// ``NativeObject`` to a flatbuffers Object and vice versa.
+public protocol ObjectAPIPacker {
+ /// associatedtype to the object that should be unpacked.
associatedtype T
- static func pack(_ builder: inout FlatBufferBuilder, obj: inout T) -> Offset<UOffset>
+
+ /// ``pack(_:obj:)-3ptws`` tries to pacs the variables of a native Object into the `ByteBuffer` by using
+ /// a FlatBufferBuilder
+ /// - Parameters:
+ /// - builder: FlatBufferBuilder that will host incoming data
+ /// - obj: Object of associatedtype to the current implementer
+ ///
+ /// ``pack(_:obj:)-3ptws`` can be called by passing through an already initialized ``FlatBufferBuilder``
+ /// or it can be called by using the public API that will create a new ``FlatBufferBuilder``
+ static func pack(_ builder: inout FlatBufferBuilder, obj: inout T?) -> Offset
+
+ /// ``pack(_:obj:)-20ipk`` packs the variables of a native Object into the `ByteBuffer` by using
+ /// the FlatBufferBuilder
+ /// - Parameters:
+ /// - builder: FlatBufferBuilder that will host incoming data
+ /// - obj: Object of associatedtype to the current implementer
+ ///
+ /// ``pack(_:obj:)-20ipk`` can be called by passing through an already initialized ``FlatBufferBuilder``
+ /// or it can be called by using the public API that will create a new ``FlatBufferBuilder``
+ static func pack(_ builder: inout FlatBufferBuilder, obj: inout T) -> Offset
+
+ /// ``unpack()`` unpacks a ``FlatBuffers`` object into a Native swift object.
mutating func unpack() -> T
}
-
-/// Readable is structures all the Flatbuffers structs
-///
-/// Readable is a procotol that each Flatbuffer struct should confirm to since
-/// FlatBufferBuilder would require a Type to both create(struct:) and createVector(structs:) functions
-public protocol Readable: FlatBufferObject {
- static var size: Int { get }
- static var alignment: Int { get }
-}
-
-public protocol Enum {
- associatedtype T: Scalar
- static var byteSize: Int { get }
- var value: T { get }
-}
diff --git a/swift/Sources/FlatBuffers/FlatBuffersUtils.swift b/swift/Sources/FlatBuffers/FlatBuffersUtils.swift
index 507ef67..dc5f785 100644
--- a/swift/Sources/FlatBuffers/FlatBuffersUtils.swift
+++ b/swift/Sources/FlatBuffers/FlatBuffersUtils.swift
@@ -1,5 +1,5 @@
/*
- * Copyright 2020 Google Inc. All rights reserved.
+ * Copyright 2021 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.
@@ -16,7 +16,8 @@
import Foundation
-public final class FlatBuffersUtils {
+/// FlatBuffersUtils hosts some utility functions that might be useful
+public enum FlatBuffersUtils {
/// Gets the size of the prefix
/// - Parameter bb: Flatbuffer object
@@ -24,8 +25,12 @@
bb.read(def: Int32.self, position: bb.reader)
}
- /// Removes the prefix by duplicating the Flatbuffer
+ /// Removes the prefix by duplicating the Flatbuffer this call is expensive since its
+ /// creates a new buffer use `readPrefixedSizeCheckedRoot` instead
+ /// unless a completely new buffer is required
/// - Parameter bb: Flatbuffer object
+ ///
+ ///
public static func removeSizePrefix(bb: ByteBuffer) -> ByteBuffer {
bb.duplicate(removing: MemoryLayout<Int32>.size)
}
diff --git a/swift/Sources/FlatBuffers/FlatbuffersErrors.swift b/swift/Sources/FlatBuffers/FlatbuffersErrors.swift
new file mode 100644
index 0000000..74c06b9
--- /dev/null
+++ b/swift/Sources/FlatBuffers/FlatbuffersErrors.swift
@@ -0,0 +1,62 @@
+/*
+ * Copyright 2021 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.
+ */
+
+import Foundation
+
+/// Collection of thrown from the Flatbuffer verifier
+public enum FlatbuffersErrors: Error, Equatable {
+
+ /// Thrown when buffer is bigger than the allowed 2GiB
+ case exceedsMaxSizeAllowed
+ /// Thrown when there is an missaligned pointer at position
+ /// of type
+ case missAlignedPointer(position: Int, type: String)
+ /// Thrown when trying to read a value that goes out of the
+ /// current buffer bounds
+ case outOfBounds(position: UInt, end: Int)
+ /// Thrown when the signed offset is out of the bounds of the
+ /// current buffer
+ case signedOffsetOutOfBounds(offset: Int, position: Int)
+ /// Thrown when a required field doesnt exist within the buffer
+ case requiredFieldDoesntExist(position: VOffset, name: String)
+ /// Thrown when a string is missing its NULL Terminator `\0`,
+ /// this can be disabled in the `VerifierOptions`
+ case missingNullTerminator(position: Int, str: String?)
+ /// Thrown when the verifier has reached the maximum tables allowed,
+ /// this can be disabled in the `VerifierOptions`
+ case maximumTables
+ /// Thrown when the verifier has reached the maximum depth allowed,
+ /// this can be disabled in the `VerifierOptions`
+ case maximumDepth
+ /// Thrown when the verifier is presented with an unknown union case
+ case unknownUnionCase
+ /// thrown when a value for a union is not found within the buffer
+ case valueNotFound(key: Int?, keyName: String, field: Int?, fieldName: String)
+ /// thrown when the size of the keys vector doesnt match fields vector
+ case unionVectorSize(
+ keyVectorSize: Int,
+ fieldVectorSize: Int,
+ unionKeyName: String,
+ fieldName: String)
+ case apparentSizeTooLarge
+
+ public static func == (
+ lhs: FlatbuffersErrors,
+ rhs: FlatbuffersErrors) -> Bool
+ {
+ lhs.localizedDescription == rhs.localizedDescription
+ }
+}
diff --git a/swift/Sources/FlatBuffers/Int+extension.swift b/swift/Sources/FlatBuffers/Int+extension.swift
index ed68ca0..76977ba 100644
--- a/swift/Sources/FlatBuffers/Int+extension.swift
+++ b/swift/Sources/FlatBuffers/Int+extension.swift
@@ -1,5 +1,5 @@
/*
- * Copyright 2020 Google Inc. All rights reserved.
+ * Copyright 2021 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.
diff --git a/swift/Sources/FlatBuffers/Message.swift b/swift/Sources/FlatBuffers/Message.swift
index d1db357..eb0bad9 100644
--- a/swift/Sources/FlatBuffers/Message.swift
+++ b/swift/Sources/FlatBuffers/Message.swift
@@ -1,5 +1,5 @@
/*
- * Copyright 2020 Google Inc. All rights reserved.
+ * Copyright 2021 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.
@@ -14,6 +14,10 @@
* limitations under the License.
*/
+import Foundation
+
+/// FlatBufferGRPCMessage protocol that should allow us to invoke
+/// initializers directly from the GRPC generated code
public protocol FlatBufferGRPCMessage {
/// Raw pointer which would be pointing to the beginning of the readable bytes
@@ -27,17 +31,19 @@
/// Message is a wrapper around Buffers to to able to send Flatbuffers `Buffers` through the
/// GRPC library
-public final class Message<T: FlatBufferObject>: FlatBufferGRPCMessage {
+public struct Message<T: FlatBufferObject>: FlatBufferGRPCMessage {
internal var buffer: ByteBuffer
/// Returns the an object of type T that would be read from the buffer
public var object: T {
T.init(
buffer,
- o: Int32(buffer.read(def: UOffset.self, position: buffer.reader)) + Int32(buffer.reader))
+ o: Int32(buffer.read(def: UOffset.self, position: buffer.reader)) +
+ Int32(buffer.reader))
}
- public var rawPointer: UnsafeMutableRawPointer { buffer.memory.advanced(by: buffer.reader) }
+ public var rawPointer: UnsafeMutableRawPointer {
+ buffer.memory.advanced(by: buffer.reader) }
public var size: Int { Int(buffer.size) }
diff --git a/swift/Sources/FlatBuffers/Mutable.swift b/swift/Sources/FlatBuffers/Mutable.swift
index adcaa1f..f77945c 100644
--- a/swift/Sources/FlatBuffers/Mutable.swift
+++ b/swift/Sources/FlatBuffers/Mutable.swift
@@ -1,5 +1,5 @@
/*
- * Copyright 2020 Google Inc. All rights reserved.
+ * Copyright 2021 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.
@@ -16,17 +16,17 @@
import Foundation
-/// Mutable is a protocol that allows us to mutate Scalar values within the buffer
+/// Mutable is a protocol that allows us to mutate Scalar values within a ``ByteBuffer``
public protocol Mutable {
/// makes Flatbuffer accessed within the Protocol
var bb: ByteBuffer { get }
- /// makes position of the table/struct accessed within the Protocol
+ /// makes position of the ``Table``/``struct`` accessed within the Protocol
var postion: Int32 { get }
}
extension Mutable {
- /// Mutates the memory in the buffer, this is only called from the access function of table and structs
+ /// Mutates the memory in the buffer, this is only called from the access function of ``Table`` and ``struct``
/// - Parameters:
/// - value: New value to be inserted to the buffer
/// - index: index of the Element
@@ -39,7 +39,7 @@
extension Mutable where Self == Table {
- /// Mutates a value by calling mutate with respect to the position in the table
+ /// Mutates a value by calling mutate with respect to the position in a ``Table``
/// - Parameters:
/// - value: New value to be inserted to the buffer
/// - index: index of the Element
diff --git a/swift/Sources/FlatBuffers/NativeObject.swift b/swift/Sources/FlatBuffers/NativeObject.swift
new file mode 100644
index 0000000..bc896e6
--- /dev/null
+++ b/swift/Sources/FlatBuffers/NativeObject.swift
@@ -0,0 +1,53 @@
+/*
+ * Copyright 2021 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.
+ */
+
+import Foundation
+
+/// NativeObject is a protocol that all of the `Object-API` generated code should be
+/// conforming to since it allows developers the ease of use to pack and unpack their
+/// Flatbuffers objects
+public protocol NativeObject {}
+
+extension NativeObject {
+
+ /// Serialize is a helper function that serailizes the data from the Object API to a bytebuffer directly th
+ /// - Parameter type: Type of the Flatbuffer object
+ /// - Returns: returns the encoded sized ByteBuffer
+ public func serialize<T: ObjectAPIPacker>(type: T.Type) -> ByteBuffer
+ where T.T == Self
+ {
+ var builder = FlatBufferBuilder(initialSize: 1024)
+ return serialize(builder: &builder, type: type.self)
+ }
+
+ /// Serialize is a helper function that serailizes the data from the Object API to a bytebuffer directly.
+ ///
+ /// - Parameters:
+ /// - builder: A FlatBufferBuilder
+ /// - type: Type of the Flatbuffer object
+ /// - Returns: returns the encoded sized ByteBuffer
+ /// - Note: The `serialize(builder:type)` can be considered as a function that allows you to create smaller builder instead of the default `1024`.
+ /// It can be considered less expensive in terms of memory allocation
+ public func serialize<T: ObjectAPIPacker>(
+ builder: inout FlatBufferBuilder,
+ type: T.Type) -> ByteBuffer where T.T == Self
+ {
+ var s = self
+ let root = type.pack(&builder, obj: &s)
+ builder.finish(offset: root)
+ return builder.sizedBuffer
+ }
+}
diff --git a/swift/Sources/FlatBuffers/NativeTable.swift b/swift/Sources/FlatBuffers/NativeTable.swift
deleted file mode 100644
index 5c844c1..0000000
--- a/swift/Sources/FlatBuffers/NativeTable.swift
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright 2020 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.
- */
-
-import Foundation
-
-public protocol NativeTable {}
-
-extension NativeTable {
-
- /// Serialize is a helper function that serailizes the data from the Object API to a bytebuffer directly th
- /// - Parameter type: Type of the Flatbuffer object
- /// - Returns: returns the encoded sized ByteBuffer
- public func serialize<T: ObjectAPI>(type: T.Type) -> ByteBuffer where T.T == Self {
- var builder = FlatBufferBuilder(initialSize: 1024)
- return serialize(builder: &builder, type: type.self)
- }
-
- /// Serialize is a helper function that serailizes the data from the Object API to a bytebuffer directly.
- ///
- /// - Parameters:
- /// - builder: A FlatBufferBuilder
- /// - type: Type of the Flatbuffer object
- /// - Returns: returns the encoded sized ByteBuffer
- /// - Note: The `serialize(builder:type)` can be considered as a function that allows you to create smaller builder instead of the default `1024`.
- /// It can be considered less expensive in terms of memory allocation
- public func serialize<T: ObjectAPI>(builder: inout FlatBufferBuilder, type: T.Type) -> ByteBuffer where T.T == Self {
- var s = self
- let root = type.pack(&builder, obj: &s)
- builder.finish(offset: root)
- return builder.sizedBuffer
- }
-}
diff --git a/swift/Sources/FlatBuffers/Offset.swift b/swift/Sources/FlatBuffers/Offset.swift
index 4b42b04..bd3f8a8 100644
--- a/swift/Sources/FlatBuffers/Offset.swift
+++ b/swift/Sources/FlatBuffers/Offset.swift
@@ -1,5 +1,5 @@
/*
- * Copyright 2020 Google Inc. All rights reserved.
+ * Copyright 2021 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.
@@ -17,7 +17,7 @@
import Foundation
/// Offset object for all the Objects that are written into the buffer
-public struct Offset<T> {
+public struct Offset {
/// Offset of the object in the buffer
public var o: UOffset
/// Returns false if the offset is equal to zero
diff --git a/swift/Sources/FlatBuffers/Root.swift b/swift/Sources/FlatBuffers/Root.swift
new file mode 100644
index 0000000..4d883b7
--- /dev/null
+++ b/swift/Sources/FlatBuffers/Root.swift
@@ -0,0 +1,82 @@
+/*
+ * Copyright 2021 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.
+ */
+
+import Foundation
+
+/// Takes in a prefixed sized buffer, where the prefixed size would be skipped.
+/// And would verify that the buffer passed is a valid `Flatbuffers` Object.
+/// - Parameters:
+/// - byteBuffer: Buffer that needs to be checked and read
+/// - options: Verifier options
+/// - Throws: FlatbuffersErrors
+/// - Returns: Returns a valid, checked Flatbuffers object
+///
+/// ``getPrefixedSizeCheckedRoot(byteBuffer:options:)`` would skip the first Bytes in
+/// the ``ByteBuffer`` and verifies the buffer by calling ``getCheckedRoot(byteBuffer:options:)``
+public func getPrefixedSizeCheckedRoot<T: FlatBufferObject & Verifiable>(
+ byteBuffer: inout ByteBuffer,
+ options: VerifierOptions = .init()) throws -> T
+{
+ byteBuffer.skipPrefix()
+ return try getCheckedRoot(byteBuffer: &byteBuffer, options: options)
+}
+
+/// Takes in a prefixed sized buffer, where the prefixed size would be skipped.
+/// Returns a `NON-Checked` flatbuffers object
+/// - Parameter byteBuffer: Buffer that contains data
+/// - Returns: Returns a Flatbuffers object
+///
+/// ``getPrefixedSizeCheckedRoot(byteBuffer:options:)`` would skip the first Bytes in
+/// the ``ByteBuffer`` and then calls ``getRoot(byteBuffer:)``
+public func getPrefixedSizeRoot<T: FlatBufferObject>(byteBuffer: inout ByteBuffer)
+ -> T
+{
+ byteBuffer.skipPrefix()
+ return getRoot(byteBuffer: &byteBuffer)
+
+}
+
+/// Verifies that the buffer passed is a valid `Flatbuffers` Object.
+/// - Parameters:
+/// - byteBuffer: Buffer that needs to be checked and read
+/// - options: Verifier options
+/// - Throws: FlatbuffersErrors
+/// - Returns: Returns a valid, checked Flatbuffers object
+///
+/// ``getCheckedRoot(byteBuffer:options:)`` Takes in a ``ByteBuffer`` and verifies
+/// that by creating a ``Verifier`` and checkes if all the `Bytes` and correctly aligned
+/// and within the ``ByteBuffer`` range.
+public func getCheckedRoot<T: FlatBufferObject & Verifiable>(
+ byteBuffer: inout ByteBuffer,
+ options: VerifierOptions = .init()) throws -> T
+{
+ var verifier = try Verifier(buffer: &byteBuffer, options: options)
+ try ForwardOffset<T>.verify(&verifier, at: 0, of: T.self)
+ return T.init(
+ byteBuffer,
+ o: Int32(byteBuffer.read(def: UOffset.self, position: byteBuffer.reader)) +
+ Int32(byteBuffer.reader))
+}
+
+/// Returns a `NON-Checked` flatbuffers object
+/// - Parameter byteBuffer: Buffer that contains data
+/// - Returns: Returns a Flatbuffers object
+public func getRoot<T: FlatBufferObject>(byteBuffer: inout ByteBuffer) -> T {
+ T.init(
+ byteBuffer,
+ o: Int32(byteBuffer.read(def: UOffset.self, position: byteBuffer.reader)) +
+ Int32(byteBuffer.reader))
+}
diff --git a/swift/Sources/FlatBuffers/String+extension.swift b/swift/Sources/FlatBuffers/String+extension.swift
new file mode 100644
index 0000000..2f3168d
--- /dev/null
+++ b/swift/Sources/FlatBuffers/String+extension.swift
@@ -0,0 +1,109 @@
+/*
+ * Copyright 2021 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.
+ */
+
+import Foundation
+
+extension String: Verifiable {
+
+ /// Verifies that the current value is which the bounds of the buffer, and if
+ /// the current `Value` is aligned properly
+ /// - Parameters:
+ /// - verifier: Verifier that hosts the buffer
+ /// - position: Current position within the buffer
+ /// - type: The type of the object to be verified
+ /// - Throws: Errors coming from `inBuffer`, `missingNullTerminator` and `outOfBounds`
+ public static func verify<T>(
+ _ verifier: inout Verifier,
+ at position: Int,
+ of type: T.Type) throws where T: Verifiable
+ {
+
+ let range = try String.verifyRange(&verifier, at: position, of: UInt8.self)
+ /// Safe &+ since we already check for overflow in verify range
+ let stringLen = range.start &+ range.count
+
+ if stringLen >= verifier.capacity {
+ throw FlatbuffersErrors.outOfBounds(
+ position: UInt(clamping: stringLen.magnitude),
+ end: verifier.capacity)
+ }
+
+ let isNullTerminated = verifier._buffer.read(
+ def: UInt8.self,
+ position: stringLen) == 0
+
+ if !verifier._options._ignoreMissingNullTerminators && !isNullTerminated {
+ let str = verifier._buffer.readString(at: range.start, count: range.count)
+ throw FlatbuffersErrors.missingNullTerminator(
+ position: position,
+ str: str)
+ }
+ }
+}
+
+extension String: FlatbuffersInitializable {
+
+ /// Initailizes a string from a Flatbuffers ByteBuffer
+ /// - Parameters:
+ /// - bb: ByteBuffer containing the readable string
+ /// - o: Current position
+ public init(_ bb: ByteBuffer, o: Int32) {
+ let v = Int(o)
+ let count = bb.read(def: Int32.self, position: v)
+ self = bb.readString(
+ at: MemoryLayout<Int32>.size + v,
+ count: Int(count)) ?? ""
+ }
+}
+
+extension String: ObjectAPIPacker {
+
+ public static func pack(
+ _ builder: inout FlatBufferBuilder,
+ obj: inout String?) -> Offset
+ {
+ guard var obj = obj else { return Offset() }
+ return pack(&builder, obj: &obj)
+ }
+
+ public static func pack(
+ _ builder: inout FlatBufferBuilder,
+ obj: inout String) -> Offset
+ {
+ builder.create(string: obj)
+ }
+
+ public mutating func unpack() -> String {
+ self
+ }
+
+}
+
+extension String: NativeObject {
+
+ public func serialize<T: ObjectAPIPacker>(type: T.Type) -> ByteBuffer
+ where T.T == Self
+ {
+ fatalError("serialize should never be called from string directly")
+ }
+
+ public func serialize<T: ObjectAPIPacker>(
+ builder: inout FlatBufferBuilder,
+ type: T.Type) -> ByteBuffer where T.T == Self
+ {
+ fatalError("serialize should never be called from string directly")
+ }
+}
diff --git a/swift/Sources/FlatBuffers/Struct.swift b/swift/Sources/FlatBuffers/Struct.swift
index 73b3295..ac701d4 100644
--- a/swift/Sources/FlatBuffers/Struct.swift
+++ b/swift/Sources/FlatBuffers/Struct.swift
@@ -1,5 +1,5 @@
/*
- * Copyright 2020 Google Inc. All rights reserved.
+ * Copyright 2021 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.
@@ -16,15 +16,30 @@
import Foundation
+/// Struct is a representation of a mutable `Flatbuffers` struct
+/// since native structs are value types and cant be mutated
+@frozen
public struct Struct {
+
+ /// Hosting Bytebuffer
public private(set) var bb: ByteBuffer
+ /// Current position of the struct
public private(set) var postion: Int32
+ /// Initializer for a mutable flatbuffers struct
+ /// - Parameters:
+ /// - bb: Current hosting Bytebuffer
+ /// - position: Current position for the struct in the ByteBuffer
public init(bb: ByteBuffer, position: Int32 = 0) {
self.bb = bb
postion = position
}
+ /// Reads data from the buffer directly at offset O
+ /// - Parameters:
+ /// - type: Type of data to be read
+ /// - o: Current offset of the data
+ /// - Returns: Data of Type T that conforms to type Scalar
public func readBuffer<T: Scalar>(of type: T.Type, at o: Int32) -> T {
let r = bb.read(def: T.self, position: Int(o + postion))
return r
diff --git a/swift/Sources/FlatBuffers/Table.swift b/swift/Sources/FlatBuffers/Table.swift
index 451398c..ff501fc 100644
--- a/swift/Sources/FlatBuffers/Table.swift
+++ b/swift/Sources/FlatBuffers/Table.swift
@@ -1,5 +1,5 @@
/*
- * Copyright 2020 Google Inc. All rights reserved.
+ * Copyright 2021 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.
@@ -16,26 +16,50 @@
import Foundation
+/// `Table` is a Flatbuffers object that can read,
+/// mutate scalar fields within a valid flatbuffers buffer
+@frozen
public struct Table {
+
+ /// Hosting Bytebuffer
public private(set) var bb: ByteBuffer
+ /// Current position of the table within the buffer
public private(set) var postion: Int32
+ /// Initializer for the table interface to allow generated code to read
+ /// data from memory
+ /// - Parameters:
+ /// - bb: ByteBuffer that stores data
+ /// - position: Current table position
+ /// - Note: This will `CRASH` if read on a big endian machine
public init(bb: ByteBuffer, position: Int32 = 0) {
guard isLitteEndian else {
- fatalError("Reading/Writing a buffer in big endian machine is not supported on swift")
+ fatalError(
+ "Reading/Writing a buffer in big endian machine is not supported on swift")
}
self.bb = bb
postion = position
}
+ /// Gets the offset of the current field within the buffer by reading
+ /// the vtable
+ /// - Parameter o: current offset
+ /// - Returns: offset of field within buffer
public func offset(_ o: Int32) -> Int32 {
let vtable = postion - bb.read(def: Int32.self, position: Int(postion))
- return o < bb.read(def: VOffset.self, position: Int(vtable)) ? Int32(bb.read(
- def: Int16.self,
- position: Int(vtable + o))) : 0
+ return o < bb
+ .read(def: VOffset.self, position: Int(vtable)) ? Int32(bb.read(
+ def: Int16.self,
+ position: Int(vtable + o))) : 0
}
- public func indirect(_ o: Int32) -> Int32 { o + bb.read(def: Int32.self, position: Int(o)) }
+ /// Gets the indirect offset of the current stored object
+ /// (applicable only for object arrays)
+ /// - Parameter o: current offset
+ /// - Returns: offset of field within buffer
+ public func indirect(_ o: Int32) -> Int32 {
+ o + bb.read(def: Int32.self, position: Int(o))
+ }
/// String reads from the buffer with respect to position of the current table.
/// - Parameter offset: Offset of the string
@@ -44,21 +68,22 @@
}
/// Direct string reads from the buffer disregarding the position of the table.
- /// It would be preferable to use string unless the current position of the table is not needed
+ /// It would be preferable to use string unless the current position of the table
+ /// is not needed
/// - Parameter offset: Offset of the string
public func directString(at offset: Int32) -> String? {
var offset = offset
offset += bb.read(def: Int32.self, position: Int(offset))
let count = bb.read(def: Int32.self, position: Int(offset))
- let position = offset + Int32(MemoryLayout<Int32>.size)
- return bb.readString(at: position, count: count)
+ let position = Int(offset) + MemoryLayout<Int32>.size
+ return bb.readString(at: position, count: Int(count))
}
/// Reads from the buffer with respect to the position in the table.
/// - Parameters:
- /// - type: Type of Scalar that needs to be read from the buffer
+ /// - type: Type of Element that needs to be read from the buffer
/// - o: Offset of the Element
- public func readBuffer<T: Scalar>(of type: T.Type, at o: Int32) -> T {
+ public func readBuffer<T>(of type: T.Type, at o: Int32) -> T {
directRead(of: T.self, offset: o + postion)
}
@@ -73,26 +98,37 @@
/// offset: __t.vector(at: offset) + index * 1)
/// ```
/// - Parameters:
- /// - type: Type of Scalar that needs to be read from the buffer
+ /// - type: Type of Element that needs to be read from the buffer
/// - o: Offset of the Element
- public func directRead<T: Scalar>(of type: T.Type, offset o: Int32) -> T {
+ public func directRead<T>(of type: T.Type, offset o: Int32) -> T {
let r = bb.read(def: T.self, position: Int(o))
return r
}
- public func union<T: FlatBufferObject>(_ o: Int32) -> T {
+ /// Returns that current `Union` object at a specific offset
+ /// by adding offset to the current position of table
+ /// - Parameter o: offset
+ /// - Returns: A flatbuffers object
+ public func union<T: FlatbuffersInitializable>(_ o: Int32) -> T {
let o = o + postion
return directUnion(o)
}
- public func directUnion<T: FlatBufferObject>(_ o: Int32) -> T {
+ /// Returns a direct `Union` object at a specific offset
+ /// - Parameter o: offset
+ /// - Returns: A flatbuffers object
+ public func directUnion<T: FlatbuffersInitializable>(_ o: Int32) -> T {
T.init(bb, o: o + bb.read(def: Int32.self, position: Int(o)))
}
+ /// Returns a vector of type T at a specific offset
+ /// This should only be used by `Scalars`
+ /// - Parameter off: Readable offset
+ /// - Returns: Returns a vector of type [T]
public func getVector<T>(at off: Int32) -> [T]? {
let o = offset(off)
guard o != 0 else { return nil }
- return bb.readSlice(index: vector(at: o), count: vector(count: o))
+ return bb.readSlice(index: Int(vector(at: o)), count: Int(vector(count: o)))
}
/// Vector count gets the count of Elements within the array
@@ -113,22 +149,46 @@
o += postion
return o + bb.read(def: Int32.self, position: Int(o)) + 4
}
-}
-extension Table {
+ /// Reading an indirect offset of a table.
+ /// - Parameters:
+ /// - o: position within the buffer
+ /// - fbb: ByteBuffer
+ /// - Returns: table offset
+ static public func indirect(_ o: Int32, _ fbb: ByteBuffer) -> Int32 {
+ o + fbb.read(def: Int32.self, position: Int(o))
+ }
- static public func indirect(_ o: Int32, _ fbb: ByteBuffer) -> Int32 { o + fbb.read(
- def: Int32.self,
- position: Int(o)) }
-
- static public func offset(_ o: Int32, vOffset: Int32, fbb: ByteBuffer) -> Int32 {
+ /// Gets a vtable value according to an table Offset and a field offset
+ /// - Parameters:
+ /// - o: offset relative to entire buffer
+ /// - vOffset: Field offset within a vtable
+ /// - fbb: ByteBuffer
+ /// - Returns: an position of a field
+ static public func offset(
+ _ o: Int32,
+ vOffset: Int32,
+ fbb: ByteBuffer) -> Int32
+ {
let vTable = Int32(fbb.capacity) - o
return vTable + Int32(fbb.read(
def: Int16.self,
- position: Int(vTable + vOffset - fbb.read(def: Int32.self, position: Int(vTable)))))
+ position: Int(vTable + vOffset - fbb.read(
+ def: Int32.self,
+ position: Int(vTable)))))
}
- static public func compare(_ off1: Int32, _ off2: Int32, fbb: ByteBuffer) -> Int32 {
+ /// Compares two objects at offset A and offset B within a ByteBuffer
+ /// - Parameters:
+ /// - off1: first offset to compare
+ /// - off2: second offset to compare
+ /// - fbb: Bytebuffer
+ /// - Returns: returns the difference between
+ static public func compare(
+ _ off1: Int32,
+ _ off2: Int32,
+ fbb: ByteBuffer) -> Int32
+ {
let memorySize = Int32(MemoryLayout<Int32>.size)
let _off1 = off1 + fbb.read(def: Int32.self, position: Int(off1))
let _off2 = off2 + fbb.read(def: Int32.self, position: Int(off2))
@@ -147,7 +207,17 @@
return len1 - len2
}
- static public func compare(_ off1: Int32, _ key: [Byte], fbb: ByteBuffer) -> Int32 {
+ /// Compares two objects at offset A and array of `Bytes` within a ByteBuffer
+ /// - Parameters:
+ /// - off1: Offset to compare to
+ /// - key: bytes array to compare to
+ /// - fbb: Bytebuffer
+ /// - Returns: returns the difference between
+ static public func compare(
+ _ off1: Int32,
+ _ key: [Byte],
+ fbb: ByteBuffer) -> Int32
+ {
let memorySize = Int32(MemoryLayout<Int32>.size)
let _off1 = off1 + fbb.read(def: Int32.self, position: Int(off1))
let len1 = fbb.read(def: Int32.self, position: Int(_off1))
diff --git a/swift/Sources/FlatBuffers/TableVerifier.swift b/swift/Sources/FlatBuffers/TableVerifier.swift
new file mode 100644
index 0000000..42a37f2
--- /dev/null
+++ b/swift/Sources/FlatBuffers/TableVerifier.swift
@@ -0,0 +1,203 @@
+/*
+ * Copyright 2021 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.
+ */
+
+import Foundation
+
+/// `TableVerifier` verifies a table object is within a provided memory.
+/// It checks if all the objects for a specific generated table, are within
+/// the bounds of the buffer, aligned.
+public struct TableVerifier {
+
+ /// position of current table in `ByteBuffer`
+ fileprivate var _position: Int
+
+ /// Current VTable position
+ fileprivate var _vtable: Int
+
+ /// Length of current VTable
+ fileprivate var _vtableLength: Int
+
+ /// `Verifier` object created in the base verifable call.
+ fileprivate var _verifier: Verifier
+
+ /// Creates a `TableVerifier` verifier that allows the Flatbuffer object
+ /// to verify the buffer before accessing any of the data.
+ ///
+ /// - Parameters:
+ /// - position: Current table Position
+ /// - vtable: Current `VTable` position
+ /// - vtableLength: Current `VTable` length
+ /// - verifier: `Verifier` Object that caches the data of the verifiable object
+ internal init(
+ position: Int,
+ vtable: Int,
+ vtableLength: Int,
+ verifier: inout Verifier)
+ {
+ _position = position
+ _vtable = vtable
+ _vtableLength = vtableLength
+ _verifier = verifier
+ }
+
+ /// Dereference the current object position from the `VTable`
+ /// - Parameter field: Current VTable refrence to position.
+ /// - Throws: A `FlatbuffersErrors` incase the voffset is not aligned/outOfBounds/apparentSizeTooLarge
+ /// - Returns: An optional position for current field
+ internal mutating func dereference(_ field: VOffset) throws -> Int? {
+ if field >= _vtableLength {
+ return nil
+ }
+
+ /// Reading the offset for the field needs to be read.
+ let offset: VOffset = try _verifier.getValue(
+ at: Int(clamping: _vtable &+ Int(field)))
+
+ if offset > 0 {
+ return Int(clamping: _position &+ Int(offset))
+ }
+ return nil
+ }
+
+ /// Visits all the fields within the table to validate the integrity
+ /// of the data
+ /// - Parameters:
+ /// - field: voffset of the current field to be read
+ /// - fieldName: fieldname to report data Errors.
+ /// - required: If the field has to be available in the buffer
+ /// - type: Type of field to be read
+ /// - Throws: A `FlatbuffersErrors` where the field is corrupt
+ public mutating func visit<T>(
+ field: VOffset,
+ fieldName: String,
+ required: Bool,
+ type: T.Type) throws where T: Verifiable
+ {
+ let derefValue = try dereference(field)
+
+ if let value = derefValue {
+ try T.verify(&_verifier, at: value, of: T.self)
+ return
+ }
+ if required {
+ throw FlatbuffersErrors.requiredFieldDoesntExist(
+ position: field,
+ name: fieldName)
+ }
+ }
+
+ /// Visits all the fields for a union object within the table to
+ /// validate the integrity of the data
+ /// - Parameters:
+ /// - key: Current Key Voffset
+ /// - field: Current field Voffset
+ /// - unionKeyName: Union key name
+ /// - fieldName: Field key name
+ /// - required: indicates if an object is required to be present
+ /// - completion: Completion is a handler that WILL be called in the generated
+ /// - Throws: A `FlatbuffersErrors` where the field is corrupt
+ public mutating func visit<T>(
+ unionKey key: VOffset,
+ unionField field: VOffset,
+ unionKeyName: String,
+ fieldName: String,
+ required: Bool,
+ completion: @escaping (inout Verifier, T, Int) throws -> Void) throws
+ where T: UnionEnum
+ {
+ let keyPos = try dereference(key)
+ let valPos = try dereference(field)
+
+ if keyPos == nil && valPos == nil {
+ if required {
+ throw FlatbuffersErrors.requiredFieldDoesntExist(
+ position: key,
+ name: unionKeyName)
+ }
+ return
+ }
+
+ if let _key = keyPos,
+ let _val = valPos
+ {
+ /// verifiying that the key is within the buffer
+ try T.T.verify(&_verifier, at: _key, of: T.T.self)
+ guard let _enum = try T.init(value: _verifier._buffer.read(
+ def: T.T.self,
+ position: _key)) else
+ {
+ throw FlatbuffersErrors.unknownUnionCase
+ }
+ /// we are assuming that Unions will always be of type Uint8
+ try completion(
+ &_verifier,
+ _enum,
+ _val)
+ return
+ }
+ throw FlatbuffersErrors.valueNotFound(
+ key: keyPos,
+ keyName: unionKeyName,
+ field: valPos,
+ fieldName: fieldName)
+ }
+
+ /// Visits and validates all the objects within a union vector
+ /// - Parameters:
+ /// - key: Current Key Voffset
+ /// - field: Current field Voffset
+ /// - unionKeyName: Union key name
+ /// - fieldName: Field key name
+ /// - required: indicates if an object is required to be present
+ /// - completion: Completion is a handler that WILL be called in the generated
+ /// - Throws: A `FlatbuffersErrors` where the field is corrupt
+ public mutating func visitUnionVector<T>(
+ unionKey key: VOffset,
+ unionField field: VOffset,
+ unionKeyName: String,
+ fieldName: String,
+ required: Bool,
+ completion: @escaping (inout Verifier, T, Int) throws -> Void) throws
+ where T: UnionEnum
+ {
+ let keyVectorPosition = try dereference(key)
+ let offsetVectorPosition = try dereference(field)
+
+ if let keyPos = keyVectorPosition,
+ let valPos = offsetVectorPosition
+ {
+ try UnionVector<T>.verify(
+ &_verifier,
+ keyPosition: keyPos,
+ fieldPosition: valPos,
+ unionKeyName: unionKeyName,
+ fieldName: fieldName,
+ completion: completion)
+ return
+ }
+ if required {
+ throw FlatbuffersErrors.requiredFieldDoesntExist(
+ position: field,
+ name: fieldName)
+ }
+ }
+
+ /// Finishs the current Table verifier, and subtracts the current
+ /// table from the incremented depth.
+ public mutating func finish() {
+ _verifier.finish()
+ }
+}
diff --git a/swift/Sources/FlatBuffers/VeriferOptions.swift b/swift/Sources/FlatBuffers/VeriferOptions.swift
new file mode 100644
index 0000000..454dd51
--- /dev/null
+++ b/swift/Sources/FlatBuffers/VeriferOptions.swift
@@ -0,0 +1,52 @@
+/*
+ * Copyright 2021 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.
+ */
+
+import Foundation
+
+/// `VerifierOptions` is a set of options to verify a flatbuffer
+public struct VerifierOptions {
+
+ /// Maximum `Apparent` size if the buffer can be expanded into a DAG tree
+ internal var _maxApparentSize: UOffset
+
+ /// Maximum table count allowed in a buffer
+ internal var _maxTableCount: UOffset
+
+ /// Maximum depth allowed in a buffer
+ internal var _maxDepth: UOffset
+
+ /// Ignoring missing null terminals in strings
+ internal var _ignoreMissingNullTerminators: Bool
+
+ /// initializes the set of options for the verifier
+ /// - Parameters:
+ /// - maxDepth: Maximum depth allowed in a buffer
+ /// - maxTableCount: Maximum table count allowed in a buffer
+ /// - maxApparentSize: Maximum `Apparent` size if the buffer can be expanded into a DAG tree
+ /// - ignoreMissingNullTerminators: Ignoring missing null terminals in strings *Currently not supported in swift*
+ public init(
+ maxDepth: UOffset = 64,
+ maxTableCount: UOffset = 1000000,
+ maxApparentSize: UOffset = 1 << 31,
+ ignoreMissingNullTerminators: Bool = false)
+ {
+ _maxDepth = maxDepth
+ _maxTableCount = maxTableCount
+ _maxApparentSize = maxApparentSize
+ _ignoreMissingNullTerminators = ignoreMissingNullTerminators
+ }
+
+}
diff --git a/swift/Sources/FlatBuffers/Verifiable.swift b/swift/Sources/FlatBuffers/Verifiable.swift
new file mode 100644
index 0000000..e601cfc
--- /dev/null
+++ b/swift/Sources/FlatBuffers/Verifiable.swift
@@ -0,0 +1,211 @@
+/*
+ * Copyright 2021 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.
+ */
+
+import Foundation
+
+/// Verifiable is a protocol all swift flatbuffers object should conform to,
+/// since swift is similar to `cpp` and `rust` where the data is read directly
+/// from `unsafeMemory` thus the need to verify if the buffer received is a valid one
+public protocol Verifiable {
+
+ /// Verifies that the current value is which the bounds of the buffer, and if
+ /// the current `Value` is aligned properly
+ /// - Parameters:
+ /// - verifier: Verifier that hosts the buffer
+ /// - position: Current position within the buffer
+ /// - type: The type of the object to be verified
+ /// - Throws: Errors coming from `inBuffer` function
+ static func verify<T>(
+ _ verifier: inout Verifier,
+ at position: Int,
+ of type: T.Type) throws where T: Verifiable
+}
+
+extension Verifiable {
+
+ /// Verifies if the current range to be read is within the bounds of the buffer,
+ /// and if the range is properly aligned
+ /// - Parameters:
+ /// - verifier: Verifier that hosts the buffer
+ /// - position: Current position within the buffer
+ /// - type: The type of the object to be verified
+ /// - Throws: Erros thrown from `isAligned` & `rangeInBuffer`
+ /// - Returns: a tuple of the start position and the count of objects within the range
+ @discardableResult
+ public static func verifyRange<T>(
+ _ verifier: inout Verifier,
+ at position: Int, of type: T.Type) throws -> (start: Int, count: Int)
+ {
+ let len: UOffset = try verifier.getValue(at: position)
+ let intLen = Int(len)
+ let start = Int(clamping: (position &+ MemoryLayout<Int32>.size).magnitude)
+ try verifier.isAligned(position: start, type: type.self)
+ try verifier.rangeInBuffer(position: start, size: intLen)
+ return (start, intLen)
+ }
+}
+
+extension Verifiable where Self: Scalar {
+
+ /// Verifies that the current value is which the bounds of the buffer, and if
+ /// the current `Value` is aligned properly
+ /// - Parameters:
+ /// - verifier: Verifier that hosts the buffer
+ /// - position: Current position within the buffer
+ /// - type: The type of the object to be verified
+ /// - Throws: Errors coming from `inBuffer` function
+ public static func verify<T>(
+ _ verifier: inout Verifier,
+ at position: Int,
+ of type: T.Type) throws where T: Verifiable
+ {
+ try verifier.inBuffer(position: position, of: type.self)
+ }
+}
+
+// MARK: - ForwardOffset
+
+/// ForwardOffset is a container to wrap around the Generic type to be verified
+/// from the flatbuffers object.
+public enum ForwardOffset<U>: Verifiable where U: Verifiable {
+
+ /// Verifies that the current value is which the bounds of the buffer, and if
+ /// the current `Value` is aligned properly
+ /// - Parameters:
+ /// - verifier: Verifier that hosts the buffer
+ /// - position: Current position within the buffer
+ /// - type: The type of the object to be verified
+ /// - Throws: Errors coming from `inBuffer` function
+ public static func verify<T>(
+ _ verifier: inout Verifier,
+ at position: Int,
+ of type: T.Type) throws where T: Verifiable
+ {
+ let offset: UOffset = try verifier.getValue(at: position)
+ let nextOffset = Int(clamping: (Int(offset) &+ position).magnitude)
+ try U.verify(&verifier, at: nextOffset, of: U.self)
+ }
+}
+
+// MARK: - Vector
+
+/// Vector is a container to wrap around the Generic type to be verified
+/// from the flatbuffers object.
+public enum Vector<U, S>: Verifiable where U: Verifiable, S: Verifiable {
+
+ /// Verifies that the current value is which the bounds of the buffer, and if
+ /// the current `Value` is aligned properly
+ /// - Parameters:
+ /// - verifier: Verifier that hosts the buffer
+ /// - position: Current position within the buffer
+ /// - type: The type of the object to be verified
+ /// - Throws: Errors coming from `inBuffer` function
+ public static func verify<T>(
+ _ verifier: inout Verifier,
+ at position: Int,
+ of type: T.Type) throws where T: Verifiable
+ {
+ /// checks if the next verification type S is equal to U of type forwardOffset
+ /// This had to be done since I couldnt find a solution for duplicate call functions
+ /// A fix will be appreciated
+ if U.self is ForwardOffset<S>.Type {
+ let range = try verifyRange(&verifier, at: position, of: UOffset.self)
+ for index in stride(
+ from: range.start,
+ to: Int(clamping: range.start &+ range.count),
+ by: MemoryLayout<UOffset>.size)
+ {
+ try U.verify(&verifier, at: index, of: U.self)
+ }
+ } else {
+ try S.verifyRange(&verifier, at: position, of: S.self)
+ }
+ }
+}
+
+// MARK: - UnionVector
+
+/// UnionVector is a container to wrap around the Generic type to be verified
+/// from the flatbuffers object.
+public enum UnionVector<S> where S: UnionEnum {
+
+ /// Completion handler for the function Verify, that passes the verifier
+ /// enum type and position of union field
+ public typealias Completion = (inout Verifier, S, Int) throws -> Void
+
+ /// Verifies if the current range to be read is within the bounds of the buffer,
+ /// and if the range is properly aligned. It also verifies if the union type is a
+ /// *valid/supported* union type.
+ /// - Parameters:
+ /// - verifier: Verifier that hosts the buffer
+ /// - keyPosition: Current union key position within the buffer
+ /// - fieldPosition: Current union field position within the buffer
+ /// - unionKeyName: Name of key to written if error is presented
+ /// - fieldName: Name of field to written if error is presented
+ /// - completion: Completion is a handler that WILL be called in the generated
+ /// code to verify the actual objects
+ /// - Throws: FlatbuffersErrors
+ public static func verify(
+ _ verifier: inout Verifier,
+ keyPosition: Int,
+ fieldPosition: Int,
+ unionKeyName: String,
+ fieldName: String,
+ completion: @escaping Completion) throws
+ {
+ /// Get offset for union key vectors and offset vectors
+ let keyOffset: UOffset = try verifier.getValue(at: keyPosition)
+ let fieldOffset: UOffset = try verifier.getValue(at: fieldPosition)
+
+ /// Check if values are within the buffer, returns the start position of vectors, and vector counts
+ /// Using &+ is safe since we already verified that the value is within the buffer, where the max is
+ /// going to be 2Gib and swift supports Int64 by default
+ let keysRange = try S.T.verifyRange(
+ &verifier,
+ at: Int(keyOffset) &+ keyPosition,
+ of: S.T.self)
+ let offsetsRange = try UOffset.verifyRange(
+ &verifier,
+ at: Int(fieldOffset) &+ fieldPosition,
+ of: UOffset.self)
+
+ guard keysRange.count == offsetsRange.count else {
+ throw FlatbuffersErrors.unionVectorSize(
+ keyVectorSize: keysRange.count,
+ fieldVectorSize: offsetsRange.count,
+ unionKeyName: unionKeyName,
+ fieldName: fieldName)
+ }
+
+ var count = 0
+ /// Iterate over the vector of keys and offsets.
+ while count < keysRange.count {
+
+ /// index of readable enum value in array
+ let keysIndex = MemoryLayout<S.T>.size * count
+ guard let _enum = try S.init(value: verifier._buffer.read(
+ def: S.T.self,
+ position: keysRange.start + keysIndex)) else
+ {
+ throw FlatbuffersErrors.unknownUnionCase
+ }
+ /// index of readable offset value in array
+ let fieldIndex = MemoryLayout<UOffset>.size * count
+ try completion(&verifier, _enum, offsetsRange.start + fieldIndex)
+ count += 1
+ }
+ }
+}
diff --git a/swift/Sources/FlatBuffers/Verifier.swift b/swift/Sources/FlatBuffers/Verifier.swift
new file mode 100644
index 0000000..6f65ce7
--- /dev/null
+++ b/swift/Sources/FlatBuffers/Verifier.swift
@@ -0,0 +1,203 @@
+/*
+ * Copyright 2021 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.
+ */
+
+import Foundation
+
+/// Verifier that check if the buffer passed into it is a valid,
+/// safe, aligned Flatbuffers object since swift read from `unsafeMemory`
+public struct Verifier {
+
+ /// Flag to check for alignment if true
+ fileprivate let _checkAlignment: Bool
+ /// Capacity of the current buffer
+ fileprivate var _capacity: Int
+ /// Current ApparentSize
+ fileprivate var _apparentSize: UOffset = 0
+ /// Amount of tables present within a buffer
+ fileprivate var _tableCount = 0
+
+ /// Capacity of the buffer
+ internal var capacity: Int { _capacity }
+ /// Current reached depth within the buffer
+ internal var _depth = 0
+ /// Current verifiable ByteBuffer
+ internal var _buffer: ByteBuffer
+ /// Options for verification
+ internal let _options: VerifierOptions
+
+ /// Initializer for the verifier
+ /// - Parameters:
+ /// - buffer: Bytebuffer that is required to be verified
+ /// - options: `VerifierOptions` that set the rule for some of the verification done
+ /// - checkAlignment: If alignment check is required to be preformed
+ /// - Throws: `exceedsMaxSizeAllowed` if capacity of the buffer is more than 2GiB
+ public init(
+ buffer: inout ByteBuffer,
+ options: VerifierOptions = .init(),
+ checkAlignment: Bool = true) throws
+ {
+ guard buffer.capacity < FlatBufferMaxSize else {
+ throw FlatbuffersErrors.exceedsMaxSizeAllowed
+ }
+
+ _buffer = buffer
+ _capacity = buffer.capacity
+ _checkAlignment = checkAlignment
+ _options = options
+ }
+
+ /// Resets the verifier to initial state
+ public mutating func reset() {
+ _depth = 0
+ _tableCount = 0
+ }
+
+ /// Checks if the value of type `T` is aligned properly in the buffer
+ /// - Parameters:
+ /// - position: Current position
+ /// - type: Type of value to check
+ /// - Throws: `missAlignedPointer` if the pointer is not aligned properly
+ public mutating func isAligned<T>(position: Int, type: T.Type) throws {
+
+ /// If check alignment is false this mutating function doesnt continue
+ if !_checkAlignment { return }
+
+ /// advance pointer to position X
+ let ptr = _buffer._storage.memory.advanced(by: position)
+ /// Check if the pointer is aligned
+ if Int(bitPattern: ptr) & (MemoryLayout<T>.alignment &- 1) == 0 {
+ return
+ }
+
+ throw FlatbuffersErrors.missAlignedPointer(
+ position: position,
+ type: String(describing: T.self))
+ }
+
+ /// Checks if the value of Size "X" is within the range of the buffer
+ /// - Parameters:
+ /// - position: Current postion to be read
+ /// - size: `Byte` Size of readable object within the buffer
+ /// - Throws: `outOfBounds` if the value is out of the bounds of the buffer
+ /// and `apparentSizeTooLarge` if the apparent size is bigger than the one specified
+ /// in `VerifierOptions`
+ public mutating func rangeInBuffer(position: Int, size: Int) throws {
+ let end = UInt(clamping: (position &+ size).magnitude)
+ if end > _buffer.capacity {
+ throw FlatbuffersErrors.outOfBounds(position: end, end: capacity)
+ }
+ _apparentSize = _apparentSize &+ UInt32(size)
+ if _apparentSize > _options._maxApparentSize {
+ throw FlatbuffersErrors.apparentSizeTooLarge
+ }
+ }
+
+ /// Validates if a value of type `T` is aligned and within the bounds of
+ /// the buffer
+ /// - Parameters:
+ /// - position: Current readable position
+ /// - type: Type of value to check
+ /// - Throws: FlatbuffersErrors
+ public mutating func inBuffer<T>(position: Int, of type: T.Type) throws {
+ try isAligned(position: position, type: type)
+ try rangeInBuffer(position: position, size: MemoryLayout<T>.size)
+ }
+
+ /// Visits a table at the current position and validates if the table meets
+ /// the rules specified in the `VerifierOptions`
+ /// - Parameter position: Current position to be read
+ /// - Throws: FlatbuffersErrors
+ /// - Returns: A `TableVerifier` at the current readable table
+ public mutating func visitTable(at position: Int) throws -> TableVerifier {
+ let vtablePosition = try derefOffset(position: position)
+ let vtableLength: VOffset = try getValue(at: vtablePosition)
+
+ let length = Int(vtableLength)
+ try isAligned(
+ position: Int(clamping: (vtablePosition + length).magnitude),
+ type: VOffset.self)
+ try rangeInBuffer(position: vtablePosition, size: length)
+
+ _tableCount += 1
+
+ if _tableCount > _options._maxTableCount {
+ throw FlatbuffersErrors.maximumTables
+ }
+
+ _depth += 1
+
+ if _depth > _options._maxDepth {
+ throw FlatbuffersErrors.maximumDepth
+ }
+
+ return TableVerifier(
+ position: position,
+ vtable: vtablePosition,
+ vtableLength: length,
+ verifier: &self)
+ }
+
+ /// Validates if a value of type `T` is within the buffer and returns it
+ /// - Parameter position: Current position to be read
+ /// - Throws: `inBuffer` errors
+ /// - Returns: a value of type `T` usually a `VTable` or a table offset
+ internal mutating func getValue<T>(at position: Int) throws -> T {
+ try inBuffer(position: position, of: T.self)
+ return _buffer.read(def: T.self, position: position)
+ }
+
+ /// derefrences an offset within a vtable to get the position of the field
+ /// in the bytebuffer
+ /// - Parameter position: Current readable position
+ /// - Throws: `inBuffer` errors & `signedOffsetOutOfBounds`
+ /// - Returns: Current readable position for a field
+ @inline(__always)
+ internal mutating func derefOffset(position: Int) throws -> Int {
+ try inBuffer(position: position, of: Int32.self)
+
+ let offset = _buffer.read(def: Int32.self, position: position)
+ // switching to int32 since swift's default Int is int64
+ // this should be safe since we already checked if its within
+ // the buffer
+ let _int32Position = UInt32(position)
+
+ let reportedOverflow: (partialValue: UInt32, overflow: Bool)
+ if offset > 0 {
+ reportedOverflow = _int32Position
+ .subtractingReportingOverflow(offset.magnitude)
+ } else {
+ reportedOverflow = _int32Position
+ .addingReportingOverflow(offset.magnitude)
+ }
+
+ /// since `subtractingReportingOverflow` & `addingReportingOverflow` returns true,
+ /// if there is overflow we return failure
+ if reportedOverflow.overflow || reportedOverflow.partialValue > _buffer
+ .capacity
+ {
+ throw FlatbuffersErrors.signedOffsetOutOfBounds(
+ offset: Int(offset),
+ position: position)
+ }
+
+ return Int(reportedOverflow.partialValue)
+ }
+
+ /// finishes the current iteration of verification on an object
+ internal mutating func finish() {
+ _depth -= 1
+ }
+}
diff --git a/tests/BUILD b/tests/BUILD
deleted file mode 100644
index 203a08c..0000000
--- a/tests/BUILD
+++ /dev/null
@@ -1,152 +0,0 @@
-load("@rules_cc//cc:defs.bzl", "cc_test")
-
-package(default_visibility = ["//visibility:private"])
-
-# Test binary.
-cc_test(
- name = "flatbuffers_test",
- testonly = 1,
- srcs = [
- "evolution_test/evolution_v1_generated.h",
- "evolution_test/evolution_v2_generated.h",
- "monster_test_bfbs_generated.h",
- "namespace_test/namespace_test1_generated.h",
- "namespace_test/namespace_test2_generated.h",
- "native_type_test_impl.cpp",
- "native_type_test_impl.h",
- "test.cpp",
- "test_assert.cpp",
- "test_assert.h",
- "test_builder.cpp",
- "test_builder.h",
- "union_vector/union_vector_generated.h",
- "optional_scalars_generated.h",
- ],
- copts = [
- "-DFLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE",
- "-DBAZEL_TEST_DATA_PATH",
- ],
- data = [
- ":arrays_test.bfbs",
- ":arrays_test.fbs",
- ":arrays_test.golden",
- ":evolution_test/evolution_v1.fbs",
- ":evolution_test/evolution_v1.json",
- ":evolution_test/evolution_v2.fbs",
- ":evolution_test/evolution_v2.json",
- ":include_test/include_test1.fbs",
- ":include_test/sub/include_test2.fbs",
- ":monster_extra.fbs",
- ":monster_test.bfbs",
- ":monster_test.fbs",
- ":monsterdata_extra.json",
- ":monsterdata_test.golden",
- ":monsterdata_test.json",
- ":native_type_test.fbs",
- ":prototest/imported.proto",
- ":prototest/test.golden",
- ":prototest/test.proto",
- ":prototest/test_include.golden",
- ":prototest/test_suffix.golden",
- ":prototest/test_union.golden",
- ":prototest/test_union_include.golden",
- ":prototest/test_union_suffix.golden",
- ":unicode_test.json",
- ":union_vector/union_vector.fbs",
- ":union_vector/union_vector.json",
- ":optional_scalars.fbs",
- ],
- includes = [
- "",
- "include/",
- ],
- deps = [
- ":arrays_test_cc_fbs",
- ":monster_extra_cc_fbs",
- ":monster_test_cc_fbs",
- ":native_type_test_cc_fbs",
- "//:flatbuffers",
- ],
-)
-
-# Test bzl rules
-load("//:build_defs.bzl", "flatbuffer_cc_library")
-
-cc_library(
- name = "test_assert",
- srcs = ["test_assert.cpp"],
- hdrs = ["test_assert.h"],
- visibility = ["//grpc/tests:__subpackages__"],
- deps = ["//:flatbuffers"],
-)
-
-cc_library(
- name = "test_builder",
- srcs = ["test_builder.cpp"],
- hdrs = ["test_builder.h"],
- visibility = ["//grpc/tests:__subpackages__"],
- deps = [
- ":monster_test_grpc",
- ":test_assert",
- "//:flatbuffers",
- ],
-)
-
-cc_library(
- name = "monster_test_grpc",
- srcs = [
- "monster_test.grpc.fb.cc",
- "monster_test.grpc.fb.h",
- "monster_test_generated.h",
- ],
- hdrs = [
- "monster_test.grpc.fb.h",
- "monster_test_generated.h",
- ],
- includes = ["."],
- visibility = ["//grpc/tests:__subpackages__"],
- deps = [
- "//:flatbuffers",
- "@com_github_grpc_grpc//:grpc++",
- ],
-)
-
-flatbuffer_cc_library(
- name = "monster_test_cc_fbs",
- srcs = ["monster_test.fbs"],
- include_paths = ["tests/include_test"],
- includes = [
- "include_test/include_test1.fbs",
- "include_test/sub/include_test2.fbs",
- ],
- visibility = ["//grpc/tests:__subpackages__"],
-)
-
-flatbuffer_cc_library(
- name = "monster_extra_cc_fbs",
- srcs = ["monster_extra.fbs"],
-)
-
-flatbuffer_cc_library(
- name = "arrays_test_cc_fbs",
- srcs = ["arrays_test.fbs"],
- flatc_args = [
- "--gen-object-api",
- "--gen-compare",
- "--no-includes",
- "--gen-mutable",
- "--reflect-names",
- "--cpp-ptr-type flatbuffers::unique_ptr",
- "--scoped-enums",
- ],
-)
-
-flatbuffer_cc_library(
- name = "native_type_test_cc_fbs",
- srcs = ["native_type_test.fbs"],
- flatc_args = [
- "--gen-object-api",
- "--gen-mutable",
- "--cpp-ptr-type flatbuffers::unique_ptr",
- ],
-)
diff --git a/tests/BUILD.bazel b/tests/BUILD.bazel
new file mode 100644
index 0000000..11af9b4
--- /dev/null
+++ b/tests/BUILD.bazel
@@ -0,0 +1,201 @@
+load("@rules_cc//cc:defs.bzl", "cc_test")
+load("//:build_defs.bzl", "flatbuffer_cc_library", "flatbuffer_ts_library")
+
+package(default_visibility = ["//visibility:private"])
+
+# Test binary.
+cc_test(
+ name = "flatbuffers_test",
+ testonly = 1,
+ srcs = [
+ "evolution_test/evolution_v1_generated.h",
+ "evolution_test/evolution_v2_generated.h",
+ "monster_test_bfbs_generated.h",
+ "namespace_test/namespace_test1_generated.h",
+ "namespace_test/namespace_test2_generated.h",
+ "native_type_test_impl.cpp",
+ "native_type_test_impl.h",
+ "optional_scalars_generated.h",
+ "test.cpp",
+ "test_assert.cpp",
+ "test_assert.h",
+ "test_builder.cpp",
+ "test_builder.h",
+ "union_vector/union_vector_generated.h",
+ ],
+ copts = [
+ "-DFLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE",
+ "-DBAZEL_TEST_DATA_PATH",
+ ],
+ data = [
+ ":arrays_test.bfbs",
+ ":arrays_test.fbs",
+ ":arrays_test.golden",
+ ":evolution_test/evolution_v1.fbs",
+ ":evolution_test/evolution_v1.json",
+ ":evolution_test/evolution_v2.fbs",
+ ":evolution_test/evolution_v2.json",
+ ":include_test/include_test1.fbs",
+ ":include_test/sub/include_test2.fbs",
+ ":monster_extra.fbs",
+ ":monster_test.bfbs",
+ ":monster_test.fbs",
+ ":monsterdata_extra.json",
+ ":monsterdata_test.golden",
+ ":monsterdata_test.json",
+ ":name_clash_test/invalid_test1.fbs",
+ ":name_clash_test/invalid_test2.fbs",
+ ":name_clash_test/valid_test1.fbs",
+ ":name_clash_test/valid_test2.fbs",
+ ":native_type_test.fbs",
+ ":optional_scalars.fbs",
+ ":prototest/imported.proto",
+ ":prototest/test.golden",
+ ":prototest/test.proto",
+ ":prototest/test_include.golden",
+ ":prototest/test_suffix.golden",
+ ":prototest/test_union.golden",
+ ":prototest/test_union_include.golden",
+ ":prototest/test_union_suffix.golden",
+ ":unicode_test.json",
+ ":union_vector/union_vector.fbs",
+ ":union_vector/union_vector.json",
+ ],
+ includes = [
+ "",
+ "include/",
+ ],
+ deps = [
+ ":arrays_test_cc_fbs",
+ ":monster_extra_cc_fbs",
+ ":monster_test_cc_fbs",
+ ":native_type_test_cc_fbs",
+ "//:flatbuffers",
+ ],
+)
+
+# Test bzl rules
+
+cc_library(
+ name = "test_assert",
+ srcs = ["test_assert.cpp"],
+ hdrs = ["test_assert.h"],
+ visibility = ["//grpc/tests:__subpackages__"],
+ deps = ["//:flatbuffers"],
+)
+
+cc_library(
+ name = "test_builder",
+ srcs = ["test_builder.cpp"],
+ hdrs = ["test_builder.h"],
+ visibility = ["//grpc/tests:__subpackages__"],
+ deps = [
+ ":monster_test_grpc",
+ ":test_assert",
+ "//:flatbuffers",
+ ],
+)
+
+cc_library(
+ name = "monster_test_grpc",
+ srcs = [
+ "monster_test.grpc.fb.cc",
+ "monster_test.grpc.fb.h",
+ "monster_test_generated.h",
+ ],
+ hdrs = [
+ "monster_test.grpc.fb.h",
+ "monster_test_generated.h",
+ ],
+ includes = ["."],
+ visibility = ["//grpc/tests:__subpackages__"],
+ deps = [
+ "//:flatbuffers",
+ "@com_github_grpc_grpc//:grpc++",
+ ],
+)
+
+flatbuffer_cc_library(
+ name = "include_test_fbs",
+ srcs = [
+ "include_test/include_test1.fbs",
+ "include_test/sub/include_test2.fbs",
+ ],
+ include_paths = ["tests/include_test"],
+)
+
+flatbuffer_cc_library(
+ name = "monster_test_cc_fbs",
+ srcs = ["monster_test.fbs"],
+ include_paths = ["tests/include_test"],
+ visibility = ["//grpc/tests:__subpackages__"],
+ deps = [":include_test_fbs"],
+)
+
+# Test that running without --no-includes works properly (monster_test doesn't
+# work cleanly due to the circular dependency in the include_tests/ files).
+include_test_args = [
+ "--gen-object-api",
+ "--gen-compare",
+ "--gen-mutable",
+ "--reflect-names",
+ "--cpp-ptr-type flatbuffers::unique_ptr",
+ "--force-empty",
+]
+
+flatbuffer_cc_library(
+ name = "included_test_fbs",
+ srcs = ["included_test.fbs"],
+ flatc_args = include_test_args,
+)
+
+flatbuffer_cc_library(
+ name = "includer_test_fbs",
+ srcs = ["includer_test.fbs"],
+ flatc_args = include_test_args,
+ deps = [":included_test_fbs"],
+)
+
+cc_library(
+ name = "include_build_test",
+ srcs = ["include_build_test.cc"],
+ deps = [":includer_test_fbs"],
+)
+
+flatbuffer_cc_library(
+ name = "monster_extra_cc_fbs",
+ srcs = ["monster_extra.fbs"],
+)
+
+flatbuffer_cc_library(
+ name = "arrays_test_cc_fbs",
+ srcs = ["arrays_test.fbs"],
+ flatc_args = [
+ "--gen-object-api",
+ "--gen-compare",
+ "--no-includes",
+ "--gen-mutable",
+ "--reflect-names",
+ "--cpp-ptr-type flatbuffers::unique_ptr",
+ "--scoped-enums",
+ ],
+)
+
+flatbuffer_cc_library(
+ name = "native_type_test_cc_fbs",
+ srcs = ["native_type_test.fbs"],
+ flatc_args = [
+ "--gen-object-api",
+ "--gen-mutable",
+ "--cpp-ptr-type flatbuffers::unique_ptr",
+ ],
+)
+
+flatbuffer_ts_library(
+ name = "typescript_ts_fbs",
+ srcs = ["typescript_keywords.fbs"],
+ deps = [
+ "//tests/test_dir:include_ts_fbs",
+ "//tests/test_dir:typescript_transitive_ts_fbs",
+ ],
+)
diff --git a/tests/DartTest.sh b/tests/DartTest.sh
index 01d21d7..36d1b14 100755
--- a/tests/DartTest.sh
+++ b/tests/DartTest.sh
@@ -16,19 +16,16 @@
pushd "$(dirname $0)" >/dev/null
-command -v pub >/dev/null 2>&1 || { echo >&2 "Dart tests require `pub` but it's not installed. Aborting."; exit 1; }
command -v dart >/dev/null 2>&1 || { echo >&2 "Dart tests require dart to be in path but it's not installed. Aborting."; exit 1; }
# output required files to the dart folder so that pub will be able to
# distribute them and more people can more easily run the dart tests
-../flatc --dart -I include_test -o ../dart/test monster_test.fbs
+../flatc --dart --gen-object-api -I include_test -o ../dart/test monster_test.fbs
cp monsterdata_test.mon ../dart/test
+cp monster_test.fbs ../dart/test
cd ../dart
# update packages
-pub get
+dart pub get
# Execute the sample.
-dart test/flat_buffers_test.dart
-
-# cleanup
-rm ../dart/test/monsterdata_test.mon
+dart test
diff --git a/tests/FlatBuffers.Benchmarks.swift/Sources/FlatBuffers.Benchmarks.swift/main.swift b/tests/FlatBuffers.Benchmarks.swift/Sources/FlatBuffers.Benchmarks.swift/main.swift
index fed3f2d..4949004 100644
--- a/tests/FlatBuffers.Benchmarks.swift/Sources/FlatBuffers.Benchmarks.swift/main.swift
+++ b/tests/FlatBuffers.Benchmarks.swift/Sources/FlatBuffers.Benchmarks.swift/main.swift
@@ -1,5 +1,5 @@
/*
- * Copyright 2020 Google Inc. All rights reserved.
+ * Copyright 2021 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.
@@ -21,7 +21,8 @@
var name: String
var value: Double
- var description: String { "\(String(format: "|\t%@\t\t|\t\t%fs\t|", name, value))"}
+ var description: String {
+ "\(String(format: "|\t%@\t\t|\t\t%fs\t|", name, value))"}
}
func run(name: String, runs: Int, action: () -> Void) -> Benchmark {
@@ -40,7 +41,7 @@
func createDocument(Benchmarks: [Benchmark]) -> String {
let separator = "-------------------------------------"
var document = "\(separator)\n"
- document += "\(String(format: "|\t%@\t\t|\t\t%@\t\t|", "Name", "Scores"))\n"
+ document += "\(String(format: "|\t%@\t\t |\t\t%@\t\t|", "Name", "Scores"))\n"
document += "\(separator)\n"
for i in Benchmarks {
document += "\(i.description) \n"
@@ -87,36 +88,52 @@
var fb = FlatBufferBuilder(initialSize: Int32(rawSize * 1600))
- var offsets: [Offset<UOffset>] = []
+ var offsets: [Offset] = []
for _ in 0..<structCount {
- fb.startVectorOfStructs(count: 5, size: 16, alignment: 8)
+ fb.startVector(
+ 5 * MemoryLayout<AA>.size,
+ elementSize: MemoryLayout<AA>.alignment)
for _ in 0..<5 {
- fb.createStructOf(size: 16, alignment: 8)
- fb.reverseAdd(v: 2.4, postion: 0)
- fb.reverseAdd(v: 2.4, postion: 8)
- fb.endStruct()
+ _ = fb.create(struct: AA(a: 2.4, b: 2.4))
}
- let vector = fb.endVectorOfStructs(count: 5)
+ let vector = fb.endVector(len: 5)
let start = fb.startTable(with: 1)
fb.add(offset: vector, at: 4)
- offsets.append(Offset<UOffset>(offset: fb.endTable(at: start)))
+ offsets.append(Offset(offset: fb.endTable(at: start)))
}
let vector = fb.createVector(ofOffsets: offsets)
let start = fb.startTable(with: 1)
fb.add(offset: vector, at: 4)
- let root = Offset<UOffset>(offset: fb.endTable(at: start))
+ let root = Offset(offset: fb.endTable(at: start))
fb.finish(offset: root)
}
+@usableFromInline
+struct AA: NativeStruct {
+ public init(a: Double, b: Double) {
+ self.a = a
+ self.b = b
+ }
+ var a: Double
+ var b: Double
+
+}
+
func benchmark(numberOfRuns runs: Int) {
var benchmarks: [Benchmark] = []
let str = (0...99).map { _ -> String in "x" }.joined()
- benchmarks.append(run(name: "500_000", runs: runs, action: benchmarkFiveHundredAdds))
+ benchmarks.append(run(
+ name: "500_000",
+ runs: runs,
+ action: benchmarkFiveHundredAdds))
benchmarks.append(run(name: "10 str", runs: runs, action: create10Strings))
let hundredStr = run(name: "100 str", runs: runs) {
create100Strings(str: str)
}
- benchmarks.append(run(name: "3M strc", runs: 1, action: benchmarkThreeMillionStructs))
+ benchmarks.append(run(
+ name: "3M strc",
+ runs: 1,
+ action: benchmarkThreeMillionStructs))
benchmarks.append(hundredStr)
print(createDocument(Benchmarks: benchmarks))
}
diff --git a/tests/FlatBuffers.GRPC.Swift/Package.swift b/tests/FlatBuffers.GRPC.Swift/Package.swift
deleted file mode 100644
index ee9adc2..0000000
--- a/tests/FlatBuffers.GRPC.Swift/Package.swift
+++ /dev/null
@@ -1,58 +0,0 @@
-// swift-tools-version:5.1
-/*
- * Copyright 2020 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.
- */
-
-import PackageDescription
-
-let package = Package(
- name: "FlatBuffers.GRPC.Swift",
- platforms: [
- .iOS(.v11),
- .macOS(.v10_14),
- ],
- dependencies: [
- .package(path: "../../swift"),
- .package(url: "https://github.com/grpc/grpc-swift.git", from: "1.0.0-alpha.19"),
- ],
- targets: [
- // Targets are the basic building blocks of a package. A target can define a module or a test suite.
- // Targets can depend on other targets in this package, and on products in packages which this package depends on.
- .target(
- name: "Model",
- dependencies: [
- "GRPC",
- "FlatBuffers",
- ],
- path: "Sources/Model"),
-
- // Client for the Greeter example
- .target(
- name: "Client",
- dependencies: [
- "GRPC",
- "Model",
- ],
- path: "Sources/client"),
-
- // Server for the Greeter example
- .target(
- name: "Server",
- dependencies: [
- "GRPC",
- "Model",
- ],
- path: "Sources/server"),
- ])
diff --git a/tests/FlatBuffers.GRPC.Swift/Sources/Model/greeter.fbs b/tests/FlatBuffers.GRPC.Swift/Sources/Model/greeter.fbs
deleted file mode 100644
index 811303c..0000000
--- a/tests/FlatBuffers.GRPC.Swift/Sources/Model/greeter.fbs
+++ /dev/null
@@ -1,17 +0,0 @@
-table HelloReply {
- message:string;
-}
-
-table HelloRequest {
- name:string;
-}
-
-table ManyHellosRequest {
- name:string;
- num_greetings:int;
-}
-
-rpc_service Greeter {
- SayHello(HelloRequest):HelloReply;
- SayManyHellos(ManyHellosRequest):HelloReply (streaming: "server");
-}
diff --git a/tests/FlatBuffers.GRPC.Swift/Sources/Model/greeter.grpc.swift b/tests/FlatBuffers.GRPC.Swift/Sources/Model/greeter.grpc.swift
deleted file mode 100644
index e4605e0..0000000
--- a/tests/FlatBuffers.GRPC.Swift/Sources/Model/greeter.grpc.swift
+++ /dev/null
@@ -1,77 +0,0 @@
-// Generated GRPC code for FlatBuffers swift!
-/// The following code is generated by the Flatbuffers library which might not be in sync with grpc-swift
-/// in case of an issue please open github issue, though it would be maintained
-
-// swiftlint:disable all
-// swiftformat:disable all
-
-import Foundation
-import GRPC
-import NIO
-import NIOHTTP1
-import FlatBuffers
-
-public protocol GRPCFlatBufPayload: GRPCPayload, FlatBufferGRPCMessage {}
-public extension GRPCFlatBufPayload {
- init(serializedByteBuffer: inout NIO.ByteBuffer) throws {
- self.init(byteBuffer: FlatBuffers.ByteBuffer(contiguousBytes: serializedByteBuffer.readableBytesView, count: serializedByteBuffer.readableBytes))
- }
- func serialize(into buffer: inout NIO.ByteBuffer) throws {
- let buf = UnsafeRawBufferPointer(start: self.rawPointer, count: Int(self.size))
- buffer.writeBytes(buf)
- }
-}
-extension Message: GRPCFlatBufPayload {}
-
-/// Usage: instantiate GreeterServiceClient, then call methods of this protocol to make API calls.
-public protocol GreeterService {
- func SayHello(_ request: Message<HelloRequest>, callOptions: CallOptions?) -> UnaryCall<Message<HelloRequest>,Message<HelloReply>>
- func SayManyHellos(_ request: Message<ManyHellosRequest>, callOptions: CallOptions?, handler: @escaping (Message<HelloReply>) -> Void) -> ServerStreamingCall<Message<ManyHellosRequest>, Message<HelloReply>>
-}
-
-public final class GreeterServiceClient: GRPCClient, GreeterService {
- public let channel: GRPCChannel
- public var defaultCallOptions: CallOptions
-
- public init(channel: GRPCChannel, defaultCallOptions: CallOptions = CallOptions()) {
- self.channel = channel
- self.defaultCallOptions = defaultCallOptions
- }
-
- public func SayHello(_ request: Message<HelloRequest>, callOptions: CallOptions? = nil) -> UnaryCall<Message<HelloRequest>,Message<HelloReply>> {
- return self.makeUnaryCall(path: "/Greeter/SayHello", request: request, callOptions: callOptions ?? self.defaultCallOptions)
- }
-
- public func SayManyHellos(_ request: Message<ManyHellosRequest>, callOptions: CallOptions? = nil, handler: @escaping (Message<HelloReply>) -> Void) -> ServerStreamingCall<Message<ManyHellosRequest>, Message<HelloReply>> {
- return self.makeServerStreamingCall(path: "/Greeter/SayManyHellos", request: request, callOptions: callOptions ?? self.defaultCallOptions, handler: handler)
- }
-}
-
-public protocol GreeterProvider: CallHandlerProvider {
- func SayHello(_ request: Message<HelloRequest>, context: StatusOnlyCallContext) -> EventLoopFuture<Message<HelloReply>>
- func SayManyHellos(request: Message<ManyHellosRequest>, context: StreamingResponseCallContext<Message<HelloReply>>) -> EventLoopFuture<GRPCStatus>
-}
-
-public extension GreeterProvider {
-
- var serviceName: Substring { return "Greeter" }
-
- func handleMethod(_ methodName: Substring, callHandlerContext: CallHandlerContext) -> GRPCCallHandler? {
- switch methodName {
- case "SayHello":
- return CallHandlerFactory.makeUnary(callHandlerContext: callHandlerContext) { context in
- return { request in
- self.SayHello(request, context: context)
- }
- }
- case "SayManyHellos":
- return CallHandlerFactory.makeServerStreaming(callHandlerContext: callHandlerContext) { context in
- return { request in
- self.SayManyHellos(request: request, context: context)
- }
- }
- default: return nil;
- }
- }
-
-}
diff --git a/tests/FlatBuffers.GRPC.Swift/Sources/Model/greeter_generated.swift b/tests/FlatBuffers.GRPC.Swift/Sources/Model/greeter_generated.swift
deleted file mode 100644
index 07af658..0000000
--- a/tests/FlatBuffers.GRPC.Swift/Sources/Model/greeter_generated.swift
+++ /dev/null
@@ -1,107 +0,0 @@
-// automatically generated by the FlatBuffers compiler, do not modify
-// swiftlint:disable all
-// swiftformat:disable all
-
-import FlatBuffers
-
-public struct HelloReply: FlatBufferObject {
-
- static func validateVersion() { FlatBuffersVersion_1_12_0() }
- public var __buffer: ByteBuffer! { return _accessor.bb }
- private var _accessor: Table
-
- public static func getRootAsHelloReply(bb: ByteBuffer) -> HelloReply { return HelloReply(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) }
-
- private init(_ t: Table) { _accessor = t }
- public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) }
-
- private enum VTOFFSET: VOffset {
- case message = 4
- var v: Int32 { Int32(self.rawValue) }
- var p: VOffset { self.rawValue }
- }
-
- public var message: String? { let o = _accessor.offset(VTOFFSET.message.v); return o == 0 ? nil : _accessor.string(at: o) }
- public var messageSegmentArray: [UInt8]? { return _accessor.getVector(at: VTOFFSET.message.v) }
- public static func startHelloReply(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) }
- public static func add(message: Offset<String>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: message, at: VTOFFSET.message.p) }
- public static func endHelloReply(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset<UOffset> { let end = Offset<UOffset>(offset: fbb.endTable(at: start)); return end }
- public static func createHelloReply(
- _ fbb: inout FlatBufferBuilder,
- offsetOfMessage message: Offset<String> = Offset()
- ) -> Offset<UOffset> {
- let __start = HelloReply.startHelloReply(&fbb)
- HelloReply.add(message: message, &fbb)
- return HelloReply.endHelloReply(&fbb, start: __start)
- }
-}
-
-public struct HelloRequest: FlatBufferObject {
-
- static func validateVersion() { FlatBuffersVersion_1_12_0() }
- public var __buffer: ByteBuffer! { return _accessor.bb }
- private var _accessor: Table
-
- public static func getRootAsHelloRequest(bb: ByteBuffer) -> HelloRequest { return HelloRequest(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) }
-
- private init(_ t: Table) { _accessor = t }
- public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) }
-
- private enum VTOFFSET: VOffset {
- case name = 4
- var v: Int32 { Int32(self.rawValue) }
- var p: VOffset { self.rawValue }
- }
-
- public var name: String? { let o = _accessor.offset(VTOFFSET.name.v); return o == 0 ? nil : _accessor.string(at: o) }
- public var nameSegmentArray: [UInt8]? { return _accessor.getVector(at: VTOFFSET.name.v) }
- public static func startHelloRequest(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) }
- public static func add(name: Offset<String>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: name, at: VTOFFSET.name.p) }
- public static func endHelloRequest(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset<UOffset> { let end = Offset<UOffset>(offset: fbb.endTable(at: start)); return end }
- public static func createHelloRequest(
- _ fbb: inout FlatBufferBuilder,
- offsetOfName name: Offset<String> = Offset()
- ) -> Offset<UOffset> {
- let __start = HelloRequest.startHelloRequest(&fbb)
- HelloRequest.add(name: name, &fbb)
- return HelloRequest.endHelloRequest(&fbb, start: __start)
- }
-}
-
-public struct ManyHellosRequest: FlatBufferObject {
-
- static func validateVersion() { FlatBuffersVersion_1_12_0() }
- public var __buffer: ByteBuffer! { return _accessor.bb }
- private var _accessor: Table
-
- public static func getRootAsManyHellosRequest(bb: ByteBuffer) -> ManyHellosRequest { return ManyHellosRequest(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) }
-
- private init(_ t: Table) { _accessor = t }
- public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) }
-
- private enum VTOFFSET: VOffset {
- case name = 4
- case numGreetings = 6
- var v: Int32 { Int32(self.rawValue) }
- var p: VOffset { self.rawValue }
- }
-
- public var name: String? { let o = _accessor.offset(VTOFFSET.name.v); return o == 0 ? nil : _accessor.string(at: o) }
- public var nameSegmentArray: [UInt8]? { return _accessor.getVector(at: VTOFFSET.name.v) }
- public var numGreetings: Int32 { let o = _accessor.offset(VTOFFSET.numGreetings.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int32.self, at: o) }
- public static func startManyHellosRequest(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 2) }
- public static func add(name: Offset<String>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: name, at: VTOFFSET.name.p) }
- public static func add(numGreetings: Int32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: numGreetings, def: 0, at: VTOFFSET.numGreetings.p) }
- public static func endManyHellosRequest(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset<UOffset> { let end = Offset<UOffset>(offset: fbb.endTable(at: start)); return end }
- public static func createManyHellosRequest(
- _ fbb: inout FlatBufferBuilder,
- offsetOfName name: Offset<String> = Offset(),
- numGreetings: Int32 = 0
- ) -> Offset<UOffset> {
- let __start = ManyHellosRequest.startManyHellosRequest(&fbb)
- ManyHellosRequest.add(name: name, &fbb)
- ManyHellosRequest.add(numGreetings: numGreetings, &fbb)
- return ManyHellosRequest.endManyHellosRequest(&fbb, start: __start)
- }
-}
-
diff --git a/tests/FlatBuffers.GRPC.Swift/Sources/client/main.swift b/tests/FlatBuffers.GRPC.Swift/Sources/client/main.swift
deleted file mode 100644
index db3206c..0000000
--- a/tests/FlatBuffers.GRPC.Swift/Sources/client/main.swift
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * Copyright 2020 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.
- */
-
-import FlatBuffers
-import GRPC
-import Logging
-import Model
-import NIO
-
-// Quieten the logs.
-LoggingSystem.bootstrap {
- var handler = StreamLogHandler.standardOutput(label: $0)
- handler.logLevel = .critical
- return handler
-}
-
-func greet(name: String, client greeter: GreeterServiceClient) {
- // Form the request with the name, if one was provided.
- var builder = FlatBufferBuilder()
- let name = builder.create(string: name)
- let root = HelloRequest.createHelloRequest(&builder, offsetOfName: name)
- builder.finish(offset: root)
-
- // Make the RPC call to the server.
- let sayHello = greeter.SayHello(Message<HelloRequest>(builder: &builder))
-
- // wait() on the response to stop the program from exiting before the response is received.
- do {
- let response = try sayHello.response.wait()
- print("Greeter received: \(response.object.message)")
- } catch {
- print("Greeter failed: \(error)")
- }
-
- let surname = builder.create(string: "Name")
- let manyRoot = ManyHellosRequest.createManyHellosRequest(
- &builder,
- offsetOfName: surname,
- numGreetings: 2)
- builder.finish(offset: manyRoot)
-
- let call = greeter.SayManyHellos(Message(builder: &builder)) { message in
- print(message.object.message)
- }
-
- let status = try! call.status.recover { _ in .processingError }.wait()
- if status.code != .ok {
- print("RPC failed: \(status)")
- }
-}
-
-func main(args: [String]) {
- // arg0 (dropped) is the program name. We expect arg1 to be the port, and arg2 (optional) to be
- // the name sent in the request.
- let arg1 = args.dropFirst(1).first
- let arg2 = args.dropFirst(2).first
-
- switch (arg1.flatMap(Int.init), arg2) {
- case (.none, _):
- print("Usage: PORT [NAME]")
- exit(1)
-
- case let (.some(port), name):
- // Setup an `EventLoopGroup` for the connection to run on.
- //
- // See: https://github.com/apple/swift-nio#eventloops-and-eventloopgroups
- let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
-
- // Make sure the group is shutdown when we're done with it.
- defer {
- try! group.syncShutdownGracefully()
- }
-
- // Configure the channel, we're not using TLS so the connection is `insecure`.
- let channel = ClientConnection.insecure(group: group)
- .connect(host: "localhost", port: port)
-
- // Close the connection when we're done with it.
- defer {
- try! channel.close().wait()
- }
-
- // Provide the connection to the generated client.
- let greeter = GreeterServiceClient(channel: channel)
-
- // Do the greeting.
- greet(name: name ?? "Hello FlatBuffers!", client: greeter)
- }
-}
-
-main(args: CommandLine.arguments)
diff --git a/tests/FlatBuffers.GRPC.Swift/Sources/server/main.swift b/tests/FlatBuffers.GRPC.Swift/Sources/server/main.swift
deleted file mode 100644
index d7aa2b9..0000000
--- a/tests/FlatBuffers.GRPC.Swift/Sources/server/main.swift
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * Copyright 2020 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.
- */
-
-import FlatBuffers
-import GRPC
-import Logging
-import Model
-import NIO
-
-class Greeter: GreeterProvider {
-
- var hellos: [Message<HelloReply>] = []
-
- init() {
- let names = ["Stranger1", "Stranger2", "Stranger4", "Stranger3", "Stranger5", "Stranger6"]
- for name in names {
- var builder = FlatBufferBuilder()
- let off = builder.create(string: name)
- let root = HelloReply.createHelloReply(&builder, offsetOfMessage: off)
- builder.finish(offset: root)
- hellos.append(Message(builder: &builder))
- }
- }
-
- func SayHello(
- _ request: Message<HelloRequest>,
- context: StatusOnlyCallContext) -> EventLoopFuture<Message<HelloReply>>
- {
- let recipient = request.object.name ?? "Stranger"
-
- var builder = FlatBufferBuilder()
- let off = builder.create(string: recipient)
- let root = HelloReply.createHelloReply(&builder, offsetOfMessage: off)
- builder.finish(offset: root)
- return context.eventLoop.makeSucceededFuture(Message<HelloReply>(builder: &builder))
- }
-
- func SayManyHellos(
- request: Message<ManyHellosRequest>,
- context: StreamingResponseCallContext<Message<HelloReply>>) -> EventLoopFuture<GRPCStatus>
- {
- for _ in 0..<Int(request.object.numGreetings) {
- let index = Int.random(in: 0..<hellos.count)
- _ = context.sendResponse(hellos[index])
- }
- return context.eventLoop.makeSucceededFuture(.ok)
- }
-}
-
-// Quieten the logs.
-LoggingSystem.bootstrap {
- var handler = StreamLogHandler.standardOutput(label: $0)
- handler.logLevel = .critical
- return handler
-}
-
-let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
-defer {
- try! group.syncShutdownGracefully()
-}
-
-// Create some configuration for the server:
-let configuration = Server.Configuration(
- target: .hostAndPort("localhost", 0),
- eventLoopGroup: group,
- serviceProviders: [Greeter()])
-
-// Start the server and print its address once it has started.
-let server = Server.start(configuration: configuration)
-server.map {
- $0.channel.localAddress
-}.whenSuccess { address in
- print("server started on port \(address!.port!)")
-}
-
-// Wait on the server's `onClose` future to stop the program from exiting.
-_ = try server.flatMap {
- $0.onClose
-}.wait()
diff --git a/tests/FlatBuffers.Test.Swift/Package.swift b/tests/FlatBuffers.Test.Swift/Package.swift
index 06d03bd..e2a53df 100644
--- a/tests/FlatBuffers.Test.Swift/Package.swift
+++ b/tests/FlatBuffers.Test.Swift/Package.swift
@@ -25,10 +25,12 @@
],
dependencies: [
.package(path: "../../swift/"),
- .package(url: "https://github.com/grpc/grpc-swift.git", from: "1.0.0-alpha.19"),
+ .package(url: "https://github.com/grpc/grpc-swift.git", from: "1.4.1"),
],
targets: [
- .target(name: "SwiftFlatBuffers"),
+ .target(
+ name: "SwiftFlatBuffers",
+ dependencies: ["FlatBuffers"]),
.testTarget(
name: "FlatBuffers.Test.SwiftTests",
dependencies: ["FlatBuffers", "GRPC"]),
diff --git a/tests/FlatBuffers.Test.Swift/Sources/SwiftFlatBuffers/fuzzer.fbs b/tests/FlatBuffers.Test.Swift/Sources/SwiftFlatBuffers/fuzzer.fbs
new file mode 100644
index 0000000..e0356fa
--- /dev/null
+++ b/tests/FlatBuffers.Test.Swift/Sources/SwiftFlatBuffers/fuzzer.fbs
@@ -0,0 +1,32 @@
+enum Color:ubyte (bit_flags) {
+ Red = 0, // color Red = (1u << 0)
+ /// \brief color Green
+ /// Green is bit_flag with value (1u << 1)
+ Green,
+ /// \brief color Blue (1u << 3)
+ Blue = 3,
+}
+
+struct Test { a:short; b:byte; }
+
+struct Vec3 (force_align: 8) {
+ x:float;
+ y:float;
+ z:float;
+ test1:double;
+ test2:Color;
+ test3:Test;
+}
+
+/// an example documentation comment: "monster object"
+table Monster {
+ pos:Vec3 (id: 0);
+ hp:short = 100 (id: 2);
+ mana:short = 150 (id: 1);
+ name:string (id: 3, key);
+ color:Color = Blue (id: 6);
+ inventory:[ubyte] (id: 5);
+ testarrayoftables:[Monster] (id: 4);
+}
+
+root_type Monster;
diff --git a/tests/FlatBuffers.Test.Swift/Sources/SwiftFlatBuffers/fuzzer_generated.swift b/tests/FlatBuffers.Test.Swift/Sources/SwiftFlatBuffers/fuzzer_generated.swift
new file mode 100644
index 0000000..7051380
--- /dev/null
+++ b/tests/FlatBuffers.Test.Swift/Sources/SwiftFlatBuffers/fuzzer_generated.swift
@@ -0,0 +1,336 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+// swiftlint:disable all
+// swiftformat:disable all
+
+import FlatBuffers
+
+public enum Color: UInt8, Enum, Verifiable {
+ public typealias T = UInt8
+ public static var byteSize: Int { return MemoryLayout<UInt8>.size }
+ public var value: UInt8 { return self.rawValue }
+ case red = 1
+ /// \brief color Green
+ /// Green is bit_flag with value (1u << 1)
+ case green = 2
+ /// \brief color Blue (1u << 3)
+ case blue = 8
+
+ public static var max: Color { return .blue }
+ public static var min: Color { return .red }
+}
+
+extension Color: Encodable {
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.singleValueContainer()
+ switch self {
+ case .red: try container.encode("Red")
+ case .green: try container.encode("Green")
+ case .blue: try container.encode("Blue")
+ }
+ }
+}
+
+public struct Test: NativeStruct, Verifiable, FlatbuffersInitializable {
+
+ static func validateVersion() { FlatBuffersVersion_2_0_0() }
+
+ private var _a: Int16
+ private var _b: Int8
+ private let padding0__: UInt8 = 0
+
+ public init(_ bb: ByteBuffer, o: Int32) {
+ let _accessor = Struct(bb: bb, position: o)
+ _a = _accessor.readBuffer(of: Int16.self, at: 0)
+ _b = _accessor.readBuffer(of: Int8.self, at: 2)
+ }
+
+ public init(a: Int16, b: Int8) {
+ _a = a
+ _b = b
+ }
+
+ public init() {
+ _a = 0
+ _b = 0
+ }
+
+ public var a: Int16 { _a }
+ public var b: Int8 { _b }
+
+ public static func verify<T>(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable {
+ try verifier.inBuffer(position: position, of: Test.self)
+ }
+}
+
+extension Test: Encodable {
+
+ enum CodingKeys: String, CodingKey {
+ case a = "a"
+ case b = "b"
+ }
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ if a != 0 {
+ try container.encodeIfPresent(a, forKey: .a)
+ }
+ if b != 0 {
+ try container.encodeIfPresent(b, forKey: .b)
+ }
+ }
+}
+
+public struct Test_Mutable: FlatBufferObject {
+
+ static func validateVersion() { FlatBuffersVersion_2_0_0() }
+ public var __buffer: ByteBuffer! { return _accessor.bb }
+ private var _accessor: Struct
+
+ public init(_ bb: ByteBuffer, o: Int32) { _accessor = Struct(bb: bb, position: o) }
+
+ public var a: Int16 { return _accessor.readBuffer(of: Int16.self, at: 0) }
+ public var b: Int8 { return _accessor.readBuffer(of: Int8.self, at: 2) }
+}
+
+public struct Vec3: NativeStruct, Verifiable, FlatbuffersInitializable {
+
+ static func validateVersion() { FlatBuffersVersion_2_0_0() }
+
+ private var _x: Float32
+ private var _y: Float32
+ private var _z: Float32
+ private let padding0__: UInt32 = 0
+ private var _test1: Double
+ private var _test2: UInt8
+ private let padding1__: UInt8 = 0
+ private var _test3: Test
+ private let padding2__: UInt16 = 0
+
+ public init(_ bb: ByteBuffer, o: Int32) {
+ let _accessor = Struct(bb: bb, position: o)
+ _x = _accessor.readBuffer(of: Float32.self, at: 0)
+ _y = _accessor.readBuffer(of: Float32.self, at: 4)
+ _z = _accessor.readBuffer(of: Float32.self, at: 8)
+ _test1 = _accessor.readBuffer(of: Double.self, at: 16)
+ _test2 = _accessor.readBuffer(of: UInt8.self, at: 24)
+ _test3 = Test(_accessor.bb, o: _accessor.postion + 26)
+ }
+
+ public init(x: Float32, y: Float32, z: Float32, test1: Double, test2: Color, test3: Test) {
+ _x = x
+ _y = y
+ _z = z
+ _test1 = test1
+ _test2 = test2.value
+ _test3 = test3
+ }
+
+ public init() {
+ _x = 0.0
+ _y = 0.0
+ _z = 0.0
+ _test1 = 0.0
+ _test2 = 0
+ _test3 = Test()
+ }
+
+ public var x: Float32 { _x }
+ public var y: Float32 { _y }
+ public var z: Float32 { _z }
+ public var test1: Double { _test1 }
+ public var test2: Color { Color(rawValue: _test2)! }
+ public var test3: Test { _test3 }
+
+ public static func verify<T>(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable {
+ try verifier.inBuffer(position: position, of: Vec3.self)
+ }
+}
+
+extension Vec3: Encodable {
+
+ enum CodingKeys: String, CodingKey {
+ case x = "x"
+ case y = "y"
+ case z = "z"
+ case test1 = "test1"
+ case test2 = "test2"
+ case test3 = "test3"
+ }
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ if x != 0.0 {
+ try container.encodeIfPresent(x, forKey: .x)
+ }
+ if y != 0.0 {
+ try container.encodeIfPresent(y, forKey: .y)
+ }
+ if z != 0.0 {
+ try container.encodeIfPresent(z, forKey: .z)
+ }
+ if test1 != 0.0 {
+ try container.encodeIfPresent(test1, forKey: .test1)
+ }
+ if test2 != .red {
+ try container.encodeIfPresent(test2, forKey: .test2)
+ }
+ try container.encodeIfPresent(test3, forKey: .test3)
+ }
+}
+
+public struct Vec3_Mutable: FlatBufferObject {
+
+ static func validateVersion() { FlatBuffersVersion_2_0_0() }
+ public var __buffer: ByteBuffer! { return _accessor.bb }
+ private var _accessor: Struct
+
+ public init(_ bb: ByteBuffer, o: Int32) { _accessor = Struct(bb: bb, position: o) }
+
+ public var x: Float32 { return _accessor.readBuffer(of: Float32.self, at: 0) }
+ public var y: Float32 { return _accessor.readBuffer(of: Float32.self, at: 4) }
+ public var z: Float32 { return _accessor.readBuffer(of: Float32.self, at: 8) }
+ public var test1: Double { return _accessor.readBuffer(of: Double.self, at: 16) }
+ public var test2: Color { return Color(rawValue: _accessor.readBuffer(of: UInt8.self, at: 24)) ?? .red }
+ public var test3: Test_Mutable { return Test_Mutable(_accessor.bb, o: _accessor.postion + 26) }
+}
+
+/// an example documentation comment: "monster object"
+public struct Monster: FlatBufferObject, Verifiable {
+
+ static func validateVersion() { FlatBuffersVersion_2_0_0() }
+ public var __buffer: ByteBuffer! { return _accessor.bb }
+ private var _accessor: Table
+
+ public static func getRootAsMonster(bb: ByteBuffer) -> Monster { return Monster(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) }
+
+ private init(_ t: Table) { _accessor = t }
+ public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) }
+
+ private enum VTOFFSET: VOffset {
+ case pos = 4
+ case mana = 6
+ case hp = 8
+ case name = 10
+ case testarrayoftables = 12
+ case inventory = 14
+ case color = 16
+ var v: Int32 { Int32(self.rawValue) }
+ var p: VOffset { self.rawValue }
+ }
+
+ public var pos: Vec3? { let o = _accessor.offset(VTOFFSET.pos.v); return o == 0 ? nil : _accessor.readBuffer(of: Vec3.self, at: o) }
+ public var mutablePos: Vec3_Mutable? { let o = _accessor.offset(VTOFFSET.pos.v); return o == 0 ? nil : Vec3_Mutable(_accessor.bb, o: o + _accessor.postion) }
+ public var mana: Int16 { let o = _accessor.offset(VTOFFSET.mana.v); return o == 0 ? 150 : _accessor.readBuffer(of: Int16.self, at: o) }
+ public var hp: Int16 { let o = _accessor.offset(VTOFFSET.hp.v); return o == 0 ? 100 : _accessor.readBuffer(of: Int16.self, at: o) }
+ public var name: String! { let o = _accessor.offset(VTOFFSET.name.v); return _accessor.string(at: o) }
+ public var nameSegmentArray: [UInt8]! { return _accessor.getVector(at: VTOFFSET.name.v) }
+ public var testarrayoftablesCount: Int32 { let o = _accessor.offset(VTOFFSET.testarrayoftables.v); return o == 0 ? 0 : _accessor.vector(count: o) }
+ public func testarrayoftables(at index: Int32) -> Monster? { let o = _accessor.offset(VTOFFSET.testarrayoftables.v); return o == 0 ? nil : Monster(_accessor.bb, o: _accessor.indirect(_accessor.vector(at: o) + index * 4)) }
+ public func testarrayoftablesBy(key: String) -> Monster? { let o = _accessor.offset(VTOFFSET.testarrayoftables.v); return o == 0 ? nil : Monster.lookupByKey(vector: _accessor.vector(at: o), key: key, fbb: _accessor.bb) }
+ public var inventoryCount: Int32 { let o = _accessor.offset(VTOFFSET.inventory.v); return o == 0 ? 0 : _accessor.vector(count: o) }
+ public func inventory(at index: Int32) -> UInt8 { let o = _accessor.offset(VTOFFSET.inventory.v); return o == 0 ? 0 : _accessor.directRead(of: UInt8.self, offset: _accessor.vector(at: o) + index * 1) }
+ public var inventory: [UInt8] { return _accessor.getVector(at: VTOFFSET.inventory.v) ?? [] }
+ public var color: Color { let o = _accessor.offset(VTOFFSET.color.v); return o == 0 ? .blue : Color(rawValue: _accessor.readBuffer(of: UInt8.self, at: o)) ?? .blue }
+ public static func startMonster(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 7) }
+ public static func add(pos: Vec3?, _ fbb: inout FlatBufferBuilder) { guard let pos = pos else { return }; fbb.create(struct: pos, position: VTOFFSET.pos.p) }
+ public static func add(mana: Int16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: mana, def: 150, at: VTOFFSET.mana.p) }
+ public static func add(hp: Int16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: hp, def: 100, at: VTOFFSET.hp.p) }
+ public static func add(name: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: name, at: VTOFFSET.name.p) }
+ public static func addVectorOf(testarrayoftables: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testarrayoftables, at: VTOFFSET.testarrayoftables.p) }
+ public static func addVectorOf(inventory: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: inventory, at: VTOFFSET.inventory.p) }
+ public static func add(color: Color, _ fbb: inout FlatBufferBuilder) { fbb.add(element: color.rawValue, def: 8, at: VTOFFSET.color.p) }
+ public static func endMonster(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); fbb.require(table: end, fields: [10]); return end }
+ public static func createMonster(
+ _ fbb: inout FlatBufferBuilder,
+ pos: Vec3? = nil,
+ mana: Int16 = 150,
+ hp: Int16 = 100,
+ nameOffset name: Offset = Offset(),
+ testarrayoftablesVectorOffset testarrayoftables: Offset = Offset(),
+ inventoryVectorOffset inventory: Offset = Offset(),
+ color: Color = .blue
+ ) -> Offset {
+ let __start = Monster.startMonster(&fbb)
+ Monster.add(pos: pos, &fbb)
+ Monster.add(mana: mana, &fbb)
+ Monster.add(hp: hp, &fbb)
+ Monster.add(name: name, &fbb)
+ Monster.addVectorOf(testarrayoftables: testarrayoftables, &fbb)
+ Monster.addVectorOf(inventory: inventory, &fbb)
+ Monster.add(color: color, &fbb)
+ return Monster.endMonster(&fbb, start: __start)
+ }
+ public static func sortVectorOfMonster(offsets:[Offset], _ fbb: inout FlatBufferBuilder) -> Offset {
+ var off = offsets
+ off.sort { Table.compare(Table.offset(Int32($1.o), vOffset: 10, fbb: fbb.buffer), Table.offset(Int32($0.o), vOffset: 10, fbb: fbb.buffer), fbb: fbb.buffer) < 0 }
+ return fbb.createVector(ofOffsets: off)
+ }
+ fileprivate static func lookupByKey(vector: Int32, key: String, fbb: ByteBuffer) -> Monster? {
+ let key = key.utf8.map { $0 }
+ var span = fbb.read(def: Int32.self, position: Int(vector - 4))
+ var start: Int32 = 0
+ while span != 0 {
+ var middle = span / 2
+ let tableOffset = Table.indirect(vector + 4 * (start + middle), fbb)
+ let comp = Table.compare(Table.offset(Int32(fbb.capacity) - tableOffset, vOffset: 10, fbb: fbb), key, fbb: fbb)
+ if comp > 0 {
+ span = middle
+ } else if comp < 0 {
+ middle += 1
+ start += middle
+ span -= middle
+ } else {
+ return Monster(fbb, o: tableOffset)
+ }
+ }
+ return nil
+ }
+
+ public static func verify<T>(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable {
+ var _v = try verifier.visitTable(at: position)
+ try _v.visit(field: VTOFFSET.pos.p, fieldName: "pos", required: false, type: Vec3.self)
+ try _v.visit(field: VTOFFSET.mana.p, fieldName: "mana", required: false, type: Int16.self)
+ try _v.visit(field: VTOFFSET.hp.p, fieldName: "hp", required: false, type: Int16.self)
+ try _v.visit(field: VTOFFSET.name.p, fieldName: "name", required: true, type: ForwardOffset<String>.self)
+ try _v.visit(field: VTOFFSET.testarrayoftables.p, fieldName: "testarrayoftables", required: false, type: ForwardOffset<Vector<ForwardOffset<Monster>, Monster>>.self)
+ try _v.visit(field: VTOFFSET.inventory.p, fieldName: "inventory", required: false, type: ForwardOffset<Vector<UInt8, UInt8>>.self)
+ try _v.visit(field: VTOFFSET.color.p, fieldName: "color", required: false, type: Color.self)
+ _v.finish()
+ }
+}
+
+extension Monster: Encodable {
+
+ enum CodingKeys: String, CodingKey {
+ case pos = "pos"
+ case mana = "mana"
+ case hp = "hp"
+ case name = "name"
+ case testarrayoftables = "testarrayoftables"
+ case inventory = "inventory"
+ case color = "color"
+ }
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encodeIfPresent(pos, forKey: .pos)
+ if mana != 150 {
+ try container.encodeIfPresent(mana, forKey: .mana)
+ }
+ if hp != 100 {
+ try container.encodeIfPresent(hp, forKey: .hp)
+ }
+ try container.encodeIfPresent(name, forKey: .name)
+ if testarrayoftablesCount > 0 {
+ var contentEncoder = container.nestedUnkeyedContainer(forKey: .testarrayoftables)
+ for index in 0..<testarrayoftablesCount {
+ guard let type = testarrayoftables(at: index) else { continue }
+ try contentEncoder.encode(type)
+ }
+ }
+ if inventoryCount > 0 {
+ try container.encodeIfPresent(inventory, forKey: .inventory)
+ }
+ if color != .blue {
+ try container.encodeIfPresent(color, forKey: .color)
+ }
+ }
+}
+
diff --git a/tests/FlatBuffers.Test.Swift/Sources/SwiftFlatBuffers/main.swift b/tests/FlatBuffers.Test.Swift/Sources/SwiftFlatBuffers/main.swift
index 7a3ff66..86e422c 100644
--- a/tests/FlatBuffers.Test.Swift/Sources/SwiftFlatBuffers/main.swift
+++ b/tests/FlatBuffers.Test.Swift/Sources/SwiftFlatBuffers/main.swift
@@ -1,5 +1,5 @@
/*
- * Copyright 2020 Google Inc. All rights reserved.
+ * Copyright 2021 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.
@@ -14,5 +14,16 @@
* limitations under the License.
*/
-import Foundation
-print("Flatbuffers")
+import FlatBuffers
+
+@_cdecl("LLVMFuzzerTestOneInput")
+public func FuzzFlatbuffers(_ start: UnsafeRawPointer, _ count: Int) -> CInt {
+ let bytes = UnsafeRawBufferPointer(start: start, count: count)
+ do {
+ var buffer = ByteBuffer(contiguousBytes: bytes, count: count)
+ let _: Monster = try getCheckedRoot(byteBuffer: &buffer)
+ } catch {
+ }
+
+ return 0
+}
diff --git a/tests/FlatBuffers.Test.Swift/SwiftTest.sh b/tests/FlatBuffers.Test.Swift/SwiftTest.sh
index 43c82bf..99ab1f1 100755
--- a/tests/FlatBuffers.Test.Swift/SwiftTest.sh
+++ b/tests/FlatBuffers.Test.Swift/SwiftTest.sh
@@ -1,15 +1,26 @@
swift_dir=`pwd`
cd ..
test_dir=`pwd`
-alias fbc='${test_dir}/../debug/flatc'
-
-cd FlatBuffers.GRPC.Swift/Sources/Model
-fbc --swift --grpc greeter.fbs
-cd ${test_dir}
+alias fbc='${test_dir}/../flatc'
+shopt -s expand_aliases
cd ${swift_dir}/Tests/FlatBuffers.Test.SwiftTests
-fbc --swift --gen-mutable --grpc --gen-object-api -I ${test_dir}/include_test ${test_dir}/monster_test.fbs ${test_dir}/union_vector/union_vector.fbs
-fbc --swift ${test_dir}/optional_scalars.fbs
+fbc --swift --gen-mutable --grpc --gen-json-emit --gen-object-api -I ${test_dir}/include_test ${test_dir}/monster_test.fbs ${test_dir}/union_vector/union_vector.fbs
+fbc --swift --gen-json-emit ${test_dir}/optional_scalars.fbs
+fbc --swift --gen-json-emit --gen-object-api ${test_dir}/more_defaults.fbs
+fbc --swift --gen-json-emit --gen-mutable --gen-object-api ${test_dir}/MutatingBool.fbs
cd ${swift_dir}
+
+cd ${swift_dir}/Sources/SwiftFlatBuffers
+# create better fuzzing test file
+fbc --swift --gen-json-emit fuzzer.fbs
+cd ${swift_dir}
+
swift build --build-tests
swift test
+
+if [ $(uname -s) != Darwin ]; then
+ echo fuzzing
+ swift build -c debug -Xswiftc -sanitize=fuzzer,address -Xswiftc -parse-as-library
+ swift build -c release -Xswiftc -sanitize=fuzzer,address -Xswiftc -parse-as-library
+fi
diff --git a/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersMonsterWriterTests.swift b/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersMonsterWriterTests.swift
index f37f2b8..9f02d8d 100644
--- a/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersMonsterWriterTests.swift
+++ b/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersMonsterWriterTests.swift
@@ -1,5 +1,5 @@
/*
- * Copyright 2020 Google Inc. All rights reserved.
+ * Copyright 2021 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.
@@ -26,39 +26,49 @@
class FlatBuffersMonsterWriterTests: XCTestCase {
func testData() {
+ // swiftformat:disable all
let data = Data([48, 0, 0, 0, 77, 79, 78, 83, 0, 0, 0, 0, 36, 0, 72, 0, 40, 0, 0, 0, 38, 0, 32, 0, 0, 0, 28, 0, 0, 0, 27, 0, 20, 0, 16, 0, 12, 0, 4, 0, 0, 0, 0, 0, 0, 0, 11, 0, 36, 0, 0, 0, 164, 0, 0, 0, 0, 0, 0, 1, 60, 0, 0, 0, 68, 0, 0, 0, 76, 0, 0, 0, 0, 0, 0, 1, 88, 0, 0, 0, 120, 0, 0, 0, 0, 0, 80, 0, 0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 64, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 64, 2, 0, 5, 0, 6, 0, 0, 0, 2, 0, 0, 0, 64, 0, 0, 0, 48, 0, 0, 0, 2, 0, 0, 0, 30, 0, 40, 0, 10, 0, 20, 0, 152, 255, 255, 255, 4, 0, 0, 0, 4, 0, 0, 0, 70, 114, 101, 100, 0, 0, 0, 0, 5, 0, 0, 0, 0, 1, 2, 3, 4, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 50, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 49, 0, 0, 0, 9, 0, 0, 0, 77, 121, 77, 111, 110, 115, 116, 101, 114, 0, 0, 0, 3, 0, 0, 0, 20, 0, 0, 0, 36, 0, 0, 0, 4, 0, 0, 0, 240, 255, 255, 255, 32, 0, 0, 0, 248, 255, 255, 255, 36, 0, 0, 0, 12, 0, 8, 0, 0, 0, 0, 0, 0, 0, 4, 0, 12, 0, 0, 0, 28, 0, 0, 0, 5, 0, 0, 0, 87, 105, 108, 109, 97, 0, 0, 0, 6, 0, 0, 0, 66, 97, 114, 110, 101, 121, 0, 0, 5, 0, 0, 0, 70, 114, 111, 100, 111, 0, 0, 0])
+ // swiftformat:enable all
let _data = ByteBuffer(data: data)
- readMonster(fb: _data)
+ readVerifiedMonster(fb: _data)
}
func testReadFromOtherLanguages() {
let path = FileManager.default.currentDirectoryPath
- let url = URL(fileURLWithPath: path, isDirectory: true).appendingPathComponent("monsterdata_test").appendingPathExtension("mon")
+ let url = URL(fileURLWithPath: path, isDirectory: true)
+ .appendingPathComponent("monsterdata_test").appendingPathExtension("mon")
guard let data = try? Data(contentsOf: url) else { return }
let _data = ByteBuffer(data: data)
- readMonster(fb: _data)
+ readVerifiedMonster(fb: _data)
}
func testCreateMonster() {
let bytes = createMonster(withPrefix: false)
+ // swiftformat:disable all
XCTAssertEqual(bytes.sizedByteArray, [48, 0, 0, 0, 77, 79, 78, 83, 0, 0, 0, 0, 36, 0, 72, 0, 40, 0, 0, 0, 38, 0, 32, 0, 0, 0, 28, 0, 0, 0, 27, 0, 20, 0, 16, 0, 12, 0, 4, 0, 0, 0, 0, 0, 0, 0, 11, 0, 36, 0, 0, 0, 164, 0, 0, 0, 0, 0, 0, 1, 60, 0, 0, 0, 68, 0, 0, 0, 76, 0, 0, 0, 0, 0, 0, 1, 88, 0, 0, 0, 120, 0, 0, 0, 0, 0, 80, 0, 0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 64, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 64, 2, 0, 5, 0, 6, 0, 0, 0, 2, 0, 0, 0, 64, 0, 0, 0, 48, 0, 0, 0, 2, 0, 0, 0, 30, 0, 40, 0, 10, 0, 20, 0, 152, 255, 255, 255, 4, 0, 0, 0, 4, 0, 0, 0, 70, 114, 101, 100, 0, 0, 0, 0, 5, 0, 0, 0, 0, 1, 2, 3, 4, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 50, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 49, 0, 0, 0, 9, 0, 0, 0, 77, 121, 77, 111, 110, 115, 116, 101, 114, 0, 0, 0, 3, 0, 0, 0, 20, 0, 0, 0, 36, 0, 0, 0, 4, 0, 0, 0, 240, 255, 255, 255, 32, 0, 0, 0, 248, 255, 255, 255, 36, 0, 0, 0, 12, 0, 8, 0, 0, 0, 0, 0, 0, 0, 4, 0, 12, 0, 0, 0, 28, 0, 0, 0, 5, 0, 0, 0, 87, 105, 108, 109, 97, 0, 0, 0, 6, 0, 0, 0, 66, 97, 114, 110, 101, 121, 0, 0, 5, 0, 0, 0, 70, 114, 111, 100, 111, 0, 0, 0])
- readMonster(fb: bytes.buffer)
+ // swiftformat:enable all
+ let monster = MyGame_Example_Monster.getRootAsMonster(bb: bytes.buffer)
+ readMonster(monster: monster)
mutateMonster(fb: bytes.buffer)
- readMonster(fb: bytes.buffer)
+ readMonster(monster: monster)
}
func testCreateMonsterResizedBuffer() {
let bytes = createMonster(withPrefix: false)
+ // swiftformat:disable all
XCTAssertEqual(bytes.sizedByteArray, [48, 0, 0, 0, 77, 79, 78, 83, 0, 0, 0, 0, 36, 0, 72, 0, 40, 0, 0, 0, 38, 0, 32, 0, 0, 0, 28, 0, 0, 0, 27, 0, 20, 0, 16, 0, 12, 0, 4, 0, 0, 0, 0, 0, 0, 0, 11, 0, 36, 0, 0, 0, 164, 0, 0, 0, 0, 0, 0, 1, 60, 0, 0, 0, 68, 0, 0, 0, 76, 0, 0, 0, 0, 0, 0, 1, 88, 0, 0, 0, 120, 0, 0, 0, 0, 0, 80, 0, 0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 64, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 64, 2, 0, 5, 0, 6, 0, 0, 0, 2, 0, 0, 0, 64, 0, 0, 0, 48, 0, 0, 0, 2, 0, 0, 0, 30, 0, 40, 0, 10, 0, 20, 0, 152, 255, 255, 255, 4, 0, 0, 0, 4, 0, 0, 0, 70, 114, 101, 100, 0, 0, 0, 0, 5, 0, 0, 0, 0, 1, 2, 3, 4, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 50, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 49, 0, 0, 0, 9, 0, 0, 0, 77, 121, 77, 111, 110, 115, 116, 101, 114, 0, 0, 0, 3, 0, 0, 0, 20, 0, 0, 0, 36, 0, 0, 0, 4, 0, 0, 0, 240, 255, 255, 255, 32, 0, 0, 0, 248, 255, 255, 255, 36, 0, 0, 0, 12, 0, 8, 0, 0, 0, 0, 0, 0, 0, 4, 0, 12, 0, 0, 0, 28, 0, 0, 0, 5, 0, 0, 0, 87, 105, 108, 109, 97, 0, 0, 0, 6, 0, 0, 0, 66, 97, 114, 110, 101, 121, 0, 0, 5, 0, 0, 0, 70, 114, 111, 100, 111, 0, 0, 0])
- readMonster(fb: bytes.sizedBuffer)
+ // swiftformat:enable all
+ readVerifiedMonster(fb: bytes.sizedBuffer)
}
func testCreateMonsterPrefixed() {
let bytes = createMonster(withPrefix: true)
+ // swiftformat:disable all
XCTAssertEqual(bytes.sizedByteArray, [44, 1, 0, 0, 44, 0, 0, 0, 77, 79, 78, 83, 36, 0, 72, 0, 40, 0, 0, 0, 38, 0, 32, 0, 0, 0, 28, 0, 0, 0, 27, 0, 20, 0, 16, 0, 12, 0, 4, 0, 0, 0, 0, 0, 0, 0, 11, 0, 36, 0, 0, 0, 164, 0, 0, 0, 0, 0, 0, 1, 60, 0, 0, 0, 68, 0, 0, 0, 76, 0, 0, 0, 0, 0, 0, 1, 88, 0, 0, 0, 120, 0, 0, 0, 0, 0, 80, 0, 0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 64, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 64, 2, 0, 5, 0, 6, 0, 0, 0, 2, 0, 0, 0, 64, 0, 0, 0, 48, 0, 0, 0, 2, 0, 0, 0, 30, 0, 40, 0, 10, 0, 20, 0, 152, 255, 255, 255, 4, 0, 0, 0, 4, 0, 0, 0, 70, 114, 101, 100, 0, 0, 0, 0, 5, 0, 0, 0, 0, 1, 2, 3, 4, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 50, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 49, 0, 0, 0, 9, 0, 0, 0, 77, 121, 77, 111, 110, 115, 116, 101, 114, 0, 0, 0, 3, 0, 0, 0, 20, 0, 0, 0, 36, 0, 0, 0, 4, 0, 0, 0, 240, 255, 255, 255, 32, 0, 0, 0, 248, 255, 255, 255, 36, 0, 0, 0, 12, 0, 8, 0, 0, 0, 0, 0, 0, 0, 4, 0, 12, 0, 0, 0, 28, 0, 0, 0, 5, 0, 0, 0, 87, 105, 108, 109, 97, 0, 0, 0, 6, 0, 0, 0, 66, 97, 114, 110, 101, 121, 0, 0, 5, 0, 0, 0, 70, 114, 111, 100, 111, 0, 0, 0])
+ // swiftformat:enable all
- let newBuf = FlatBuffersUtils.removeSizePrefix(bb: bytes.buffer)
- readMonster(fb: newBuf)
+ var buffer = bytes.buffer
+ readMonster(monster: getPrefixedSizeRoot(byteBuffer: &buffer))
}
func testCreateMonsterUsingCreateMonsterMethodWithNilPos() {
@@ -77,7 +87,15 @@
var fbb = FlatBufferBuilder(initialSize: 1)
let name = fbb.create(string: "Barney")
let mStart = Monster.startMonster(&fbb)
- Monster.add(pos: MyGame_Example_Vec3.createVec3(builder: &fbb, x: 10, test2: .blue), &fbb)
+ Monster.add(
+ pos: MyGame_Example_Vec3(
+ x: 10,
+ y: 0,
+ z: 0,
+ test1: 0,
+ test2: .blue,
+ test3: .init()),
+ &fbb)
Monster.add(name: name, &fbb)
let root = Monster.endMonster(&fbb, start: mStart)
fbb.finish(offset: root)
@@ -88,31 +106,70 @@
}
func testReadMonsterFromUnsafePointerWithoutCopying() {
+ // swiftformat:disable all
var array: [UInt8] = [48, 0, 0, 0, 77, 79, 78, 83, 0, 0, 0, 0, 36, 0, 72, 0, 40, 0, 0, 0, 38, 0, 32, 0, 0, 0, 28, 0, 0, 0, 27, 0, 20, 0, 16, 0, 12, 0, 4, 0, 0, 0, 0, 0, 0, 0, 11, 0, 36, 0, 0, 0, 164, 0, 0, 0, 0, 0, 0, 1, 60, 0, 0, 0, 68, 0, 0, 0, 76, 0, 0, 0, 0, 0, 0, 1, 88, 0, 0, 0, 120, 0, 0, 0, 0, 0, 80, 0, 0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 64, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 64, 2, 0, 5, 0, 6, 0, 0, 0, 2, 0, 0, 0, 64, 0, 0, 0, 48, 0, 0, 0, 2, 0, 0, 0, 30, 0, 40, 0, 10, 0, 20, 0, 152, 255, 255, 255, 4, 0, 0, 0, 4, 0, 0, 0, 70, 114, 101, 100, 0, 0, 0, 0, 5, 0, 0, 0, 0, 1, 2, 3, 4, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 50, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 49, 0, 0, 0, 9, 0, 0, 0, 77, 121, 77, 111, 110, 115, 116, 101, 114, 0, 0, 0, 3, 0, 0, 0, 20, 0, 0, 0, 36, 0, 0, 0, 4, 0, 0, 0, 240, 255, 255, 255, 32, 0, 0, 0, 248, 255, 255, 255, 36, 0, 0, 0, 12, 0, 8, 0, 0, 0, 0, 0, 0, 0, 4, 0, 12, 0, 0, 0, 28, 0, 0, 0, 5, 0, 0, 0, 87, 105, 108, 109, 97, 0, 0, 0, 6, 0, 0, 0, 66, 97, 114, 110, 101, 121, 0, 0, 5, 0, 0, 0, 70, 114, 111, 100, 111, 0, 0, 0]
- let unpacked = array.withUnsafeMutableBytes { (memory) -> MyGame_Example_MonsterT in
- let bytes = ByteBuffer(assumingMemoryBound: memory.baseAddress!, capacity: memory.count)
- var monster = Monster.getRootAsMonster(bb: bytes)
- readFlatbufferMonster(monster: &monster)
- let unpacked = monster.unpack()
- return unpacked
- }
+ // swiftformat:enable all
+ let unpacked = array
+ .withUnsafeMutableBytes { (memory) -> MyGame_Example_MonsterT in
+ let bytes = ByteBuffer(
+ assumingMemoryBound: memory.baseAddress!,
+ capacity: memory.count)
+ var monster = Monster.getRootAsMonster(bb: bytes)
+ readFlatbufferMonster(monster: &monster)
+ let unpacked = monster.unpack()
+ return unpacked
+ }
readObjectApi(monster: unpacked)
}
- func readMonster(fb: ByteBuffer) {
- var monster = Monster.getRootAsMonster(bb: fb)
+ func testArrayOfBools() {
+ let boolArray = [false, true, false, true, false, true, false]
+ var fbb = FlatBufferBuilder(initialSize: 1)
+ let name = fbb.create(string: "Frodo")
+ let bools = fbb.createVector(boolArray)
+ let root = Monster.createMonster(
+ &fbb,
+ nameOffset: name,
+ testarrayofboolsVectorOffset: bools)
+ fbb.finish(offset: root)
+ let monster = Monster.getRootAsMonster(bb: fbb.sizedBuffer)
+
+ let values = monster.testarrayofbools
+
+ XCTAssertEqual(boolArray, values)
+
+ for i in 0..<monster.testarrayofboolsCount {
+ XCTAssertEqual(boolArray[Int(i)], monster.testarrayofbools(at: i))
+ }
+ }
+
+ func readVerifiedMonster(fb: ByteBuffer) {
+ var byteBuffer = fb
+ XCTAssertNoThrow(
+ try readMonster(
+ monster: getCheckedRoot(
+ byteBuffer: &byteBuffer) as MyGame_Example_Monster))
+ }
+
+ func readMonster(monster: Monster) {
+ var monster = monster
readFlatbufferMonster(monster: &monster)
let unpacked: MyGame_Example_MonsterT? = monster.unpack()
readObjectApi(monster: unpacked!)
- guard let buffer = unpacked?.serialize() else { fatalError("Couldnt generate bytebuffer") }
+ guard let buffer = unpacked?.serialize()
+ else { fatalError("Couldnt generate bytebuffer") }
var newMonster = Monster.getRootAsMonster(bb: buffer)
readFlatbufferMonster(monster: &newMonster)
}
func createMonster(withPrefix prefix: Bool) -> FlatBufferBuilder {
var fbb = FlatBufferBuilder(initialSize: 1)
- let names = [fbb.create(string: "Frodo"), fbb.create(string: "Barney"), fbb.create(string: "Wilma")]
- var offsets: [Offset<UOffset>] = []
+ let names = [
+ fbb.create(string: "Frodo"),
+ fbb.create(string: "Barney"),
+ fbb.create(string: "Wilma"),
+ ]
+ var offsets: [Offset] = []
let start1 = Monster.startMonster(&fbb)
Monster.add(name: names[0], &fbb)
offsets.append(Monster.endMonster(&fbb, start: start1))
@@ -136,16 +193,22 @@
Monster.add(name: fred, &fbb)
let mon2 = Monster.endMonster(&fbb, start: mon1Start)
- let size = 2
- Monster.startVectorOfTest4(size, in: &fbb)
- MyGame_Example_Test.createTest(builder: &fbb, a: 10, b: 20)
- MyGame_Example_Test.createTest(builder: &fbb, a: 30, b: 40)
- let test4 = fbb.endVectorOfStructs(count: size)
+ let test4 = fbb.createVector(ofStructs: [
+ MyGame_Example_Test(a: 30, b: 40),
+ MyGame_Example_Test(a: 10, b: 20),
+ ])
let stringTestVector = fbb.createVector(ofOffsets: [test1, test2])
let mStart = Monster.startMonster(&fbb)
- let posStruct = MyGame_Example_Vec3.createVec3(builder: &fbb, x: 1, y: 2, z: 3, test1: 3, test2: .green, test3a: 5, test3b: 6)
- Monster.add(pos: posStruct, &fbb)
+ Monster.add(
+ pos: MyGame_Example_Vec3(
+ x: 1,
+ y: 2,
+ z: 3,
+ test1: 3,
+ test2: .green,
+ test3: .init(a: 5, b: 6)),
+ &fbb)
Monster.add(hp: 80, &fbb)
Monster.add(name: str, &fbb)
Monster.addVectorOf(inventory: inv, &fbb)
@@ -190,7 +253,7 @@
XCTAssertEqual(monster.mutate(inventory: 3, at: 3), true)
XCTAssertEqual(monster.mutate(inventory: 4, at: 4), true)
- let vec = monster.pos
+ let vec = monster.mutablePos
XCTAssertEqual(vec?.x, 1)
XCTAssertTrue(vec?.mutate(x: 55.0) ?? false)
XCTAssertTrue(vec?.mutate(test1: 55) ?? false)
@@ -228,6 +291,7 @@
}
XCTAssertEqual(sum, 10)
XCTAssertEqual(monster.test4Count, 2)
+
let test0 = monster.test4(at: 0)
let test1 = monster.test4(at: 1)
var sum0 = 0
@@ -239,6 +303,19 @@
sum1 = Int(a) + Int(b)
}
XCTAssertEqual(sum0 + sum1, 100)
+
+ let mutableTest0 = monster.mutableTest4(at: 0)
+ let mutableTest1 = monster.mutableTest4(at: 1)
+ var sum2 = 0
+ var sum3 = 0
+ if let a = mutableTest0?.a, let b = mutableTest0?.b {
+ sum2 = Int(a) + Int(b)
+ }
+ if let a = mutableTest1?.a, let b = mutableTest1?.b {
+ sum3 = Int(a) + Int(b)
+ }
+ XCTAssertEqual(sum2 + sum3, 100)
+
XCTAssertEqual(monster.testarrayofstringCount, 2)
XCTAssertEqual(monster.testarrayofstring(at: 0), "test1")
XCTAssertEqual(monster.testarrayofstring(at: 1), "test2")
@@ -295,4 +372,24 @@
XCTAssertEqual(sum0 + sum1, 100)
XCTAssertEqual(monster.testbool, true)
}
+
+ func testEncoding() {
+ let fbb = createMonster(withPrefix: false)
+ var sizedBuffer = fbb.sizedBuffer
+ do {
+ let reader: Monster = try getCheckedRoot(byteBuffer: &sizedBuffer)
+ let encoder = JSONEncoder()
+ encoder.keyEncodingStrategy = .convertToSnakeCase
+ let data = try encoder.encode(reader)
+ XCTAssertEqual(data, jsonData.data(using: .utf8))
+ } catch {
+ XCTFail(error.localizedDescription)
+ }
+ }
+
+ var jsonData: String {
+ """
+ {\"hp\":80,\"inventory\":[0,1,2,3,4],\"test\":{\"name\":\"Fred\"},\"testarrayofstring\":[\"test1\",\"test2\"],\"testarrayoftables\":[{\"name\":\"Barney\"},{\"name\":\"Frodo\"},{\"name\":\"Wilma\"}],\"test4\":[{\"a\":30,\"b\":40},{\"a\":10,\"b\":20}],\"testbool\":true,\"test_type\":\"Monster\",\"pos\":{\"y\":2,\"test3\":{\"a\":5,\"b\":6},\"z\":3,\"x\":1,\"test1\":3,\"test2\":\"Green\"},\"name\":\"MyMonster\"}
+ """
+ }
}
diff --git a/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersStructsTests.swift b/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersStructsTests.swift
index 2c344f0..2032589 100644
--- a/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersStructsTests.swift
+++ b/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersStructsTests.swift
@@ -1,5 +1,5 @@
/*
- * Copyright 2020 Google Inc. All rights reserved.
+ * Copyright 2021 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.
@@ -22,12 +22,13 @@
func testWritingAndMutatingBools() {
var fbb = FlatBufferBuilder()
let start = TestMutatingBool.startTestMutatingBool(&fbb)
- TestMutatingBool.add(b: createProperty(builder: &fbb), &fbb)
+ TestMutatingBool.add(b: Property(property: false), &fbb)
let root = TestMutatingBool.endTestMutatingBool(&fbb, start: start)
fbb.finish(offset: root)
- let testMutatingBool = TestMutatingBool.getRootAsTestMutatingBool(bb: fbb.sizedBuffer)
- let property = testMutatingBool.b
+ let testMutatingBool = TestMutatingBool
+ .getRootAsTestMutatingBool(bb: fbb.sizedBuffer)
+ let property = testMutatingBool.mutableB
XCTAssertEqual(property?.property, false)
property?.mutate(property: false)
XCTAssertEqual(property?.property, false)
@@ -37,23 +38,8 @@
}
-struct Vec: Readable {
- var __buffer: ByteBuffer! { __p.bb }
-
- static var size = 12
- static var alignment = 4
- private var __p: Struct
- init(_ fb: ByteBuffer, o: Int32) { __p = Struct(bb: fb, position: o) }
- var x: Float32 { __p.readBuffer(of: Float32.self, at: 0)}
- var y: Float32 { __p.readBuffer(of: Float32.self, at: 4)}
- var z: Float32 { __p.readBuffer(of: Float32.self, at: 8)}
-}
-
-@discardableResult
-func createVecWrite(builder: inout FlatBufferBuilder, x: Float32, y: Float32, z: Float32) -> Offset<UOffset> {
- builder.createStructOf(size: Vec.size, alignment: Vec.alignment)
- builder.reverseAdd(v: x, postion: 0)
- builder.reverseAdd(v: y, postion: 4)
- builder.reverseAdd(v: z, postion: 8)
- return builder.endStruct()
+struct Vec: NativeStruct {
+ var x: Float32
+ var y: Float32
+ var z: Float32
}
diff --git a/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersTests.swift b/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersTests.swift
index a605600..379e733 100644
--- a/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersTests.swift
+++ b/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersTests.swift
@@ -1,5 +1,5 @@
/*
- * Copyright 2020 Google Inc. All rights reserved.
+ * Copyright 2021 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.
@@ -24,8 +24,8 @@
func testEndian() { XCTAssertEqual(isLitteEndian, true) }
func testOffset() {
- let o = Offset<Int>()
- let b = Offset<Int>(offset: 1)
+ let o = Offset()
+ let b = Offset(offset: 1)
XCTAssertEqual(o.isEmpty, true)
XCTAssertEqual(b.isEmpty, false)
}
@@ -52,22 +52,36 @@
func testCreateFinish() {
var b = FlatBufferBuilder(initialSize: 16)
- let countryOff = Country.createCountry(builder: &b, name: country, log: 200, lan: 100)
+ let countryOff = Country.createCountry(
+ builder: &b,
+ name: country,
+ log: 200,
+ lan: 100)
b.finish(offset: countryOff)
+ // swiftformat:disable all
let v: [UInt8] = [16, 0, 0, 0, 0, 0, 10, 0, 16, 0, 4, 0, 8, 0, 12, 0, 10, 0, 0, 0, 12, 0, 0, 0, 100, 0, 0, 0, 200, 0, 0, 0, 6, 0, 0, 0, 78, 111, 114, 119, 97, 121, 0, 0]
+ // swiftformat:enable all
XCTAssertEqual(b.sizedByteArray, v)
}
func testCreateFinishWithPrefix() {
var b = FlatBufferBuilder(initialSize: 16)
- let countryOff = Country.createCountry(builder: &b, name: country, log: 200, lan: 100)
+ let countryOff = Country.createCountry(
+ builder: &b,
+ name: country,
+ log: 200,
+ lan: 100)
b.finish(offset: countryOff, addPrefix: true)
+ // swiftformat:disable all
let v: [UInt8] = [44, 0, 0, 0, 16, 0, 0, 0, 0, 0, 10, 0, 16, 0, 4, 0, 8, 0, 12, 0, 10, 0, 0, 0, 12, 0, 0, 0, 100, 0, 0, 0, 200, 0, 0, 0, 6, 0, 0, 0, 78, 111, 114, 119, 97, 121, 0, 0]
+ // swiftformat:enable all
XCTAssertEqual(b.sizedByteArray, v)
}
func testReadCountry() {
+ // swiftformat:disable all
let v: [UInt8] = [16, 0, 0, 0, 0, 0, 10, 0, 16, 0, 4, 0, 8, 0, 12, 0, 10, 0, 0, 0, 12, 0, 0, 0, 100, 0, 0, 0, 200, 0, 0, 0, 6, 0, 0, 0, 78, 111, 114, 119, 97, 121, 0, 0]
+ // swiftformat:enable all
let buffer = ByteBuffer(bytes: v)
let c = Country.getRootAsCountry(buffer)
XCTAssertEqual(c.lan, 100)
@@ -94,7 +108,8 @@
justEnum: .one,
maybeEnum: nil)
b.finish(offset: root)
- let scalarTable = optional_scalars_ScalarStuff.getRootAsScalarStuff(bb: b.sizedBuffer)
+ let scalarTable = optional_scalars_ScalarStuff
+ .getRootAsScalarStuff(bb: b.sizedBuffer)
XCTAssertEqual(scalarTable.justI8, 80)
XCTAssertNil(scalarTable.maybeI8)
XCTAssertEqual(scalarTable.maybeBool, true)
@@ -115,14 +130,21 @@
__t = t
}
- var lan: Int32 { let o = __t.offset(6); return o == 0 ? 0 : __t.readBuffer(of: Int32.self, at: o) }
- var log: Int32 { let o = __t.offset(8); return o == 0 ? 0 : __t.readBuffer(of: Int32.self, at: o) }
+ var lan: Int32 { let o = __t.offset(6); return o == 0 ? 0 : __t.readBuffer(
+ of: Int32.self,
+ at: o) }
+ var log: Int32 { let o = __t.offset(8); return o == 0 ? 0 : __t.readBuffer(
+ of: Int32.self,
+ at: o) }
var nameVector: [UInt8]? { __t.getVector(at: 4) }
- var name: String? { let o = __t.offset(4); return o == 0 ? nil : __t.string(at: o) }
+ var name: String? {
+ let o = __t.offset(4); return o == 0 ? nil : __t.string(at: o) }
@inlinable
static func getRootAsCountry(_ bb: ByteBuffer) -> Country {
- Country(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: 0))))
+ Country(Table(
+ bb: bb,
+ position: Int32(bb.read(def: UOffset.self, position: 0))))
}
@inlinable
@@ -130,17 +152,21 @@
builder: inout FlatBufferBuilder,
name: String,
log: Int32,
- lan: Int32) -> Offset<Country>
+ lan: Int32) -> Offset
{
- createCountry(builder: &builder, offset: builder.create(string: name), log: log, lan: lan)
+ createCountry(
+ builder: &builder,
+ offset: builder.create(string: name),
+ log: log,
+ lan: lan)
}
@inlinable
static func createCountry(
builder: inout FlatBufferBuilder,
- offset: Offset<String>,
+ offset: Offset,
log: Int32,
- lan: Int32) -> Offset<Country>
+ lan: Int32) -> Offset
{
let _start = builder.startTable(with: 3)
Country.add(builder: &builder, lng: log)
@@ -150,7 +176,10 @@
}
@inlinable
- static func end(builder: inout FlatBufferBuilder, startOffset: UOffset) -> Offset<Country> {
+ static func end(
+ builder: inout FlatBufferBuilder,
+ startOffset: UOffset) -> Offset
+ {
Offset(offset: builder.endTable(at: startOffset))
}
@@ -160,7 +189,7 @@
}
@inlinable
- static func add(builder: inout FlatBufferBuilder, name: Offset<String>) {
+ static func add(builder: inout FlatBufferBuilder, name: Offset) {
builder.add(offset: name, at: Country.offsets.name)
}
diff --git a/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersUnionTests.swift b/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersUnionTests.swift
index 0802272..eb8a10c 100644
--- a/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersUnionTests.swift
+++ b/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersUnionTests.swift
@@ -1,5 +1,5 @@
/*
- * Copyright 2020 Google Inc. All rights reserved.
+ * Copyright 2021 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.
@@ -34,7 +34,9 @@
equippedOffset: weapon.o)
b.finish(offset: root)
let buffer = b.sizedByteArray
+ // swiftformat:disable all
XCTAssertEqual(buffer, [16, 0, 0, 0, 0, 0, 10, 0, 16, 0, 8, 0, 7, 0, 12, 0, 10, 0, 0, 0, 0, 0, 0, 1, 8, 0, 0, 0, 20, 0, 0, 0, 1, 0, 0, 0, 12, 0, 0, 0, 8, 0, 12, 0, 8, 0, 6, 0, 8, 0, 0, 0, 0, 0, 5, 0, 4, 0, 0, 0, 3, 0, 0, 0, 65, 120, 101, 0])
+ // swiftformat:enable all
let monster = LocalMonster.getRootAsMonster(bb: ByteBuffer(bytes: buffer))
XCTAssertEqual(monster.weapon(at: 0)?.dmg, dmg)
XCTAssertEqual(monster.weapon(at: 0)?.name, str)
@@ -49,19 +51,22 @@
var builder = FlatBufferBuilder(initialSize: 20)
let sword = builder.create(string: "Sword")
let axe = builder.create(string: "Axe")
- let weaponOne = Weapon.createWeapon(builder: &builder, offset: sword, dmg: 3)
+ let weaponOne = Weapon.createWeapon(
+ builder: &builder,
+ offset: sword,
+ dmg: 3)
let weaponTwo = Weapon.createWeapon(builder: &builder, offset: axe, dmg: 5)
let name = builder.create(string: "Orc")
let inventory: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
let inv = builder.createVector(inventory, size: 10)
let weapons = builder.createVector(ofOffsets: [weaponOne, weaponTwo])
- builder.startVectorOfStructs(count: 2, size: Vec.size, alignment: Vec.alignment)
- createVecWrite(builder: &builder, x: 1.0, y: 2.0, z: 3.0)
- createVecWrite(builder: &builder, x: 4.0, y: 5.0, z: 6.0)
- let path = builder.endVectorOfStructs(count: 2)
+ let path = builder.createVector(ofStructs: [
+ Vec(x: 4.0, y: 5.0, z: 6.0),
+ Vec(x: 1.0, y: 2.0, z: 3.0),
+ ])
let orc = FinalMonster.createMonster(
builder: &builder,
- position: createVecWrite(builder: &builder, x: 1.0, y: 2.0, z: 3.0),
+ position: Vec(x: 1, y: 2, z: 3),
hp: 300,
name: name,
inventory: inv,
@@ -71,7 +76,9 @@
equippedOffset: weaponTwo,
path: path)
builder.finish(offset: orc)
- XCTAssertEqual(builder.sizedByteArray, [32, 0, 0, 0, 0, 0, 26, 0, 36, 0, 36, 0, 0, 0, 34, 0, 28, 0, 0, 0, 24, 0, 23, 0, 16, 0, 15, 0, 8, 0, 4, 0, 26, 0, 0, 0, 44, 0, 0, 0, 104, 0, 0, 0, 0, 0, 0, 1, 60, 0, 0, 0, 0, 0, 0, 0, 64, 0, 0, 0, 76, 0, 0, 0, 0, 0, 44, 1, 0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 64, 64, 2, 0, 0, 0, 0, 0, 128, 64, 0, 0, 160, 64, 0, 0, 192, 64, 0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 64, 64, 2, 0, 0, 0, 52, 0, 0, 0, 28, 0, 0, 0, 10, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 3, 0, 0, 0, 79, 114, 99, 0, 244, 255, 255, 255, 0, 0, 5, 0, 24, 0, 0, 0, 8, 0, 12, 0, 8, 0, 6, 0, 8, 0, 0, 0, 0, 0, 3, 0, 12, 0, 0, 0, 3, 0, 0, 0, 65, 120, 101, 0, 5, 0, 0, 0, 83, 119, 111, 114, 100, 0, 0, 0])
+ // swiftformat:disable all
+ XCTAssertEqual(builder.sizedByteArray, [32, 0, 0, 0, 0, 0, 26, 0, 48, 0, 36, 0, 0, 0, 34, 0, 28, 0, 0, 0, 24, 0, 23, 0, 16, 0, 15, 0, 8, 0, 4, 0, 26, 0, 0, 0, 44, 0, 0, 0, 104, 0, 0, 0, 0, 0, 0, 1, 60, 0, 0, 0, 0, 0, 0, 0, 64, 0, 0, 0, 76, 0, 0, 0, 0, 0, 44, 1, 0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 64, 64, 2, 0, 0, 0, 0, 0, 128, 64, 0, 0, 160, 64, 0, 0, 192, 64, 0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 64, 64, 2, 0, 0, 0, 52, 0, 0, 0, 28, 0, 0, 0, 10, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 3, 0, 0, 0, 79, 114, 99, 0, 244, 255, 255, 255, 0, 0, 5, 0, 24, 0, 0, 0, 8, 0, 12, 0, 8, 0, 6, 0, 8, 0, 0, 0, 0, 0, 3, 0, 12, 0, 0, 0, 3, 0, 0, 0, 65, 120, 101, 0, 5, 0, 0, 0, 83, 119, 111, 114, 100, 0, 0, 0])
+ // swiftformat:enable all
}
func testEnumVector() {
@@ -83,7 +90,9 @@
ColorsNameSpace.Monster.add(colors: off, &builder)
let end = ColorsNameSpace.Monster.endMonster(&builder, start: start)
builder.finish(offset: end)
+ // swiftformat:disable all
XCTAssertEqual(builder.sizedByteArray, [12, 0, 0, 0, 0, 0, 6, 0, 8, 0, 4, 0, 6, 0, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, 1, 0, 0, 0])
+ // swiftformat:enable all
let monster = ColorsNameSpace.Monster.getRootAsMonster(bb: builder.buffer)
XCTAssertEqual(monster.colorsCount, 2)
XCTAssertEqual(monster.colors(at: 0), .blue)
@@ -101,13 +110,16 @@
let characterType: [Character] = [.belle, .mulan, .bookfan]
let characters = [
- BookReader.createBookReader(builder: &fb, booksRead: 7),
+ fb.create(struct: BookReader(booksRead: 7)),
attack,
- BookReader.createBookReader(builder: &fb, booksRead: 2),
+ fb.create(struct: BookReader(booksRead: 2)),
]
let types = fb.createVector(characterType)
let characterVector = fb.createVector(ofOffsets: characters)
- let end = Movie.createMovie(&fb, vectorOfCharactersType: types, vectorOfCharacters: characterVector)
+ let end = Movie.createMovie(
+ &fb,
+ charactersTypeVectorOffset: types,
+ charactersVectorOffset: characterVector)
Movie.finish(&fb, end: end)
var movie = Movie.getRootAsMovie(bb: fb.buffer)
@@ -118,22 +130,125 @@
XCTAssertEqual(movie.charactersType(at: i), characterType[Int(i)])
}
- XCTAssertEqual(movie.characters(at: 0, type: BookReader.self)?.booksRead, 7)
- XCTAssertEqual(movie.characters(at: 1, type: Attacker.self)?.swordAttackDamage, swordDmg)
- XCTAssertEqual(movie.characters(at: 2, type: BookReader.self)?.booksRead, 2)
+ XCTAssertEqual(
+ movie.characters(at: 0, type: BookReader_Mutable.self)?.booksRead,
+ 7)
+ XCTAssertEqual(
+ movie.characters(at: 1, type: Attacker.self)?.swordAttackDamage,
+ swordDmg)
+ XCTAssertEqual(
+ movie.characters(at: 2, type: BookReader_Mutable.self)?.booksRead,
+ 2)
var objc: MovieT? = movie.unpack()
- XCTAssertEqual(movie.charactersTypeCount, Int32(objc?.characters.count ?? 0))
- XCTAssertEqual(movie.characters(at: 0, type: BookReader.self)?.booksRead, (objc?.characters[0]?.value as? BookReaderT)?.booksRead)
+ XCTAssertEqual(
+ movie.charactersTypeCount,
+ Int32(objc?.characters.count ?? 0))
+ XCTAssertEqual(
+ movie.characters(at: 0, type: BookReader_Mutable.self)?.booksRead,
+ (objc?.characters[0]?.value as? BookReader)?.booksRead)
fb.clear()
let newMovie = Movie.pack(&fb, obj: &objc)
fb.finish(offset: newMovie)
let packedMovie = Movie.getRootAsMovie(bb: fb.buffer)
- XCTAssertEqual(packedMovie.characters(at: 0, type: BookReader.self)?.booksRead, movie.characters(at: 0, type: BookReader.self)?.booksRead)
- XCTAssertEqual(packedMovie.characters(at: 1, type: Attacker.self)?.swordAttackDamage, movie.characters(at: 1, type: Attacker.self)?.swordAttackDamage)
- XCTAssertEqual(packedMovie.characters(at: 2, type: BookReader.self)?.booksRead, movie.characters(at: 2, type: BookReader.self)?.booksRead)
+ XCTAssertEqual(
+ packedMovie.characters(at: 0, type: BookReader_Mutable.self)?.booksRead,
+ movie.characters(at: 0, type: BookReader_Mutable.self)?.booksRead)
+ XCTAssertEqual(
+ packedMovie.characters(at: 1, type: Attacker.self)?.swordAttackDamage,
+ movie.characters(at: 1, type: Attacker.self)?.swordAttackDamage)
+ XCTAssertEqual(
+ packedMovie.characters(at: 2, type: BookReader_Mutable.self)?.booksRead,
+ movie.characters(at: 2, type: BookReader_Mutable.self)?.booksRead)
+ }
+
+ func testStringUnion() {
+ let string = "Awesome \\\\t\t\nstring!"
+ var fb = FlatBufferBuilder()
+ let stringOffset = fb.create(string: string)
+ let characterType: [Character] = [.bookfan, .other]
+
+ let characters = [
+ fb.create(struct: BookReader(booksRead: 7)),
+ stringOffset,
+ ]
+ let types = fb.createVector(characterType)
+ let characterVector = fb.createVector(ofOffsets: characters)
+
+ let end = Movie.createMovie(
+ &fb,
+ mainCharacterType: .other,
+ mainCharacterOffset: Offset(offset: stringOffset.o),
+ charactersTypeVectorOffset: types,
+ charactersVectorOffset: characterVector)
+ Movie.finish(&fb, end: end)
+
+ var movie = Movie.getRootAsMovie(bb: fb.sizedBuffer)
+ XCTAssertEqual(movie.mainCharacter(type: String.self), string)
+ XCTAssertEqual(
+ movie.characters(at: 0, type: BookReader_Mutable.self)?.booksRead,
+ 7)
+ XCTAssertEqual(movie.characters(at: 1, type: String.self), string)
+
+ var objc: MovieT? = movie.unpack()
+ XCTAssertEqual(objc?.mainCharacter?.value as? String, string)
+ XCTAssertEqual((objc?.characters[0]?.value as? BookReader)?.booksRead, 7)
+ XCTAssertEqual(objc?.characters[1]?.value as? String, string)
+ fb.clear()
+ let newMovie = Movie.pack(&fb, obj: &objc)
+ fb.finish(offset: newMovie)
+
+ let packedMovie = Movie.getRootAsMovie(bb: fb.buffer)
+ XCTAssertEqual(packedMovie.mainCharacter(type: String.self), string)
+ XCTAssertEqual(
+ packedMovie.characters(at: 0, type: BookReader_Mutable.self)?.booksRead,
+ 7)
+ XCTAssertEqual(packedMovie.characters(at: 1, type: String.self), string)
+ }
+
+ func testEncoding() {
+ let string = "Awesome \\\\t\t\nstring!"
+ var fb = FlatBufferBuilder()
+
+ let stringOffset = fb.create(string: string)
+
+ let swordDmg: Int32 = 8
+ let attackStart = Attacker.startAttacker(&fb)
+ Attacker.add(swordAttackDamage: swordDmg, &fb)
+ let attack = Attacker.endAttacker(&fb, start: attackStart)
+
+ let characterType: [Character] = [.belle, .mulan, .bookfan, .other]
+
+ let characters = [
+ fb.create(struct: BookReader(booksRead: 7)),
+ attack,
+ fb.create(struct: BookReader(booksRead: 2)),
+ stringOffset,
+ ]
+ let types = fb.createVector(characterType)
+ let characterVector = fb.createVector(ofOffsets: characters)
+ let end = Movie.createMovie(
+ &fb,
+ charactersTypeVectorOffset: types,
+ charactersVectorOffset: characterVector)
+ Movie.finish(&fb, end: end)
+
+ var sizedBuffer = fb.sizedBuffer
+ do {
+ let reader: Movie = try getCheckedRoot(byteBuffer: &sizedBuffer)
+ let encoder = JSONEncoder()
+ encoder.keyEncodingStrategy = .convertToSnakeCase
+ let data = try encoder.encode(reader)
+ XCTAssertEqual(data, jsonData.data(using: .utf8))
+ } catch {
+ XCTFail(error.localizedDescription)
+ }
+ }
+
+ var jsonData: String {
+ "{\"characters_type\":[\"Belle\",\"MuLan\",\"BookFan\",\"Other\"],\"characters\":[{\"books_read\":7},{\"sword_attack_damage\":8},{\"books_read\":2},\"Awesome \\\\\\\\t\\t\\nstring!\"]}"
}
}
@@ -152,20 +267,32 @@
private var _accessor: Table
static func getRootAsMonster(bb: ByteBuffer) -> Monster { Monster(Table(
bb: bb,
- position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) }
+ position: Int32(bb.read(def: UOffset.self, position: bb.reader)) +
+ Int32(bb.reader))) }
init(_ t: Table) { _accessor = t }
init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) }
- public var colorsCount: Int32 { let o = _accessor.offset(4); return o == 0 ? 0 : _accessor.vector(count: o) }
- public func colors(at index: Int32) -> ColorsNameSpace.RGB? { let o = _accessor.offset(4); return o == 0 ? ColorsNameSpace.RGB(rawValue: 0)! : ColorsNameSpace.RGB(rawValue: _accessor.directRead(
- of: Int32.self,
- offset: _accessor.vector(at: o) + index * 4)) }
- static func startMonster(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) }
- static func add(colors: Offset<UOffset>, _ fbb: inout FlatBufferBuilder) { fbb.add(
+ public var colorsCount: Int32 {
+ let o = _accessor.offset(4); return o == 0 ? 0 : _accessor
+ .vector(count: o) }
+ public func colors(at index: Int32) -> ColorsNameSpace
+ .RGB?
+ { let o = _accessor.offset(4); return o == 0 ? ColorsNameSpace
+ .RGB(rawValue: 0)! : ColorsNameSpace.RGB(rawValue: _accessor.directRead(
+ of: Int32.self,
+ offset: _accessor.vector(at: o) + index * 4)) }
+ static func startMonster(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb
+ .startTable(with: 1) }
+ static func add(colors: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(
offset: colors,
at: 4) }
- static func endMonster(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset<UOffset> { let end = Offset<UOffset>(offset: fbb.endTable(at: start)); return end }
+ static func endMonster(
+ _ fbb: inout FlatBufferBuilder,
+ start: UOffset)
+ -> Offset
+ { let end = Offset(offset: fbb.endTable(at: start)); return end
+ }
}
}
@@ -179,24 +306,27 @@
@inlinable
static func createMonster(
builder: inout FlatBufferBuilder,
- position: Offset<UOffset>,
+ position: Vec,
hp: Int16,
- name: Offset<String>,
- inventory: Offset<UOffset>,
+ name: Offset,
+ inventory: Offset,
color: Color3,
- weapons: Offset<UOffset>,
+ weapons: Offset,
equipment: Equipment = .none,
- equippedOffset: Offset<Weapon>,
- path: Offset<UOffset>) -> Offset<LocalMonster>
+ equippedOffset: Offset,
+ path: Offset) -> Offset
{
let start = builder.startTable(with: 11)
- builder.add(structOffset: 4)
+ builder.create(struct: position, position: 4)
builder.add(element: hp, def: 100, at: 8)
builder.add(offset: name, at: 10)
builder.add(offset: inventory, at: 14)
builder.add(element: color.rawValue, def: Color3.green.rawValue, at: 16)
builder.add(offset: weapons, at: 18)
- builder.add(element: equipment.rawValue, def: Equipment.none.rawValue, at: 20)
+ builder.add(
+ element: equipment.rawValue,
+ def: Equipment.none.rawValue,
+ at: 20)
builder.add(offset: equippedOffset, at: 22)
builder.add(offset: path, at: 24)
return Offset(offset: builder.endTable(at: start))
@@ -210,29 +340,35 @@
init(_ fb: ByteBuffer, o: Int32) { __t = Table(bb: fb, position: o) }
init(_ t: Table) { __t = t }
- func weapon(at index: Int32) -> Weapon? { let o = __t.offset(4); return o == 0 ? nil : Weapon.assign(
- __t.indirect(__t.vector(at: o) + (index * 4)),
- __t.bb) }
+ func weapon(at index: Int32) -> Weapon? { let o = __t
+ .offset(4); return o == 0 ? nil : Weapon.assign(
+ __t.indirect(__t.vector(at: o) + (index * 4)),
+ __t.bb) }
func equiped<T: FlatBufferObject>() -> T? {
let o = __t.offset(8); return o == 0 ? nil : __t.union(o)
}
static func getRootAsMonster(bb: ByteBuffer) -> LocalMonster {
- LocalMonster(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: 0))))
+ LocalMonster(Table(
+ bb: bb,
+ position: Int32(bb.read(def: UOffset.self, position: 0))))
}
@inlinable
static func createMonster(
builder: inout FlatBufferBuilder,
- offset: Offset<UOffset>,
+ offset: Offset,
equipment: Equipment = .none,
- equippedOffset: UOffset) -> Offset<LocalMonster>
+ equippedOffset: UOffset) -> Offset
{
let start = builder.startTable(with: 3)
builder.add(element: equippedOffset, def: 0, at: 8)
builder.add(offset: offset, at: 4)
- builder.add(element: equipment.rawValue, def: Equipment.none.rawValue, at: 6)
+ builder.add(
+ element: equipment.rawValue,
+ def: Equipment.none.rawValue,
+ at: 6)
return Offset(offset: builder.endTable(at: start))
}
}
@@ -247,17 +383,22 @@
init(_ t: Table) { __t = t }
init(_ fb: ByteBuffer, o: Int32) { __t = Table(bb: fb, position: o)}
- var dmg: Int16 { let o = __t.offset(6); return o == 0 ? 0 : __t.readBuffer(of: Int16.self, at: o) }
+ var dmg: Int16 { let o = __t.offset(6); return o == 0 ? 0 : __t.readBuffer(
+ of: Int16.self,
+ at: o) }
var nameVector: [UInt8]? { __t.getVector(at: 4) }
- var name: String? { let o = __t.offset(4); return o == 0 ? nil : __t.string(at: o) }
+ var name: String? {
+ let o = __t.offset(4); return o == 0 ? nil : __t.string(at: o) }
- static func assign(_ i: Int32, _ bb: ByteBuffer) -> Weapon { Weapon(Table(bb: bb, position: i)) }
+ static func assign(_ i: Int32, _ bb: ByteBuffer) -> Weapon { Weapon(Table(
+ bb: bb,
+ position: i)) }
@inlinable
static func createWeapon(
builder: inout FlatBufferBuilder,
- offset: Offset<String>,
- dmg: Int16) -> Offset<Weapon>
+ offset: Offset,
+ dmg: Int16) -> Offset
{
let _start = builder.startTable(with: 2)
Weapon.add(builder: &builder, name: offset)
@@ -266,12 +407,15 @@
}
@inlinable
- static func end(builder: inout FlatBufferBuilder, startOffset: UOffset) -> Offset<Weapon> {
+ static func end(
+ builder: inout FlatBufferBuilder,
+ startOffset: UOffset) -> Offset
+ {
Offset(offset: builder.endTable(at: startOffset))
}
@inlinable
- static func add(builder: inout FlatBufferBuilder, name: Offset<String>) {
+ static func add(builder: inout FlatBufferBuilder, name: Offset) {
builder.add(offset: name, at: Weapon.offsets.name)
}
diff --git a/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersVectorsTests.swift b/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersVectorsTests.swift
index f095eef..4cb245f 100644
--- a/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersVectorsTests.swift
+++ b/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersVectorsTests.swift
@@ -1,5 +1,5 @@
/*
- * Copyright 2020 Google Inc. All rights reserved.
+ * Copyright 2021 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.
@@ -25,12 +25,22 @@
var b = FlatBufferBuilder(initialSize: 20)
let noStr = b.create(string: norway)
let deStr = b.create(string: denmark)
- let n = Country.createCountry(builder: &b, offset: noStr, log: 888, lan: 700)
- let d = Country.createCountry(builder: &b, offset: deStr, log: 200, lan: 100)
+ let n = Country.createCountry(
+ builder: &b,
+ offset: noStr,
+ log: 888,
+ lan: 700)
+ let d = Country.createCountry(
+ builder: &b,
+ offset: deStr,
+ log: 200,
+ lan: 100)
let vector = [n, d]
let vectorOffset = b.createVector(ofOffsets: vector)
b.finish(offset: vectorOffset)
+ // swiftformat:disable all
XCTAssertEqual(b.sizedByteArray, [4, 0, 0, 0, 2, 0, 0, 0, 48, 0, 0, 0, 16, 0, 0, 0, 0, 0, 10, 0, 18, 0, 4, 0, 8, 0, 12, 0, 10, 0, 0, 0, 40, 0, 0, 0, 100, 0, 0, 0, 200, 0, 0, 0, 0, 0, 10, 0, 16, 0, 4, 0, 8, 0, 12, 0, 10, 0, 0, 0, 24, 0, 0, 0, 188, 2, 0, 0, 120, 3, 0, 0, 7, 0, 0, 0, 68, 101, 110, 109, 97, 114, 107, 0, 6, 0, 0, 0, 78, 111, 114, 119, 97, 121, 0, 0])
+ // swiftformat:enable all
}
func testCreateIntArray() {
@@ -38,7 +48,9 @@
var b = FlatBufferBuilder(initialSize: 20)
let o = b.createVector(numbers, size: numbers.count)
b.finish(offset: o)
+ // swiftformat:disable all
XCTAssertEqual(b.sizedByteArray, [4, 0, 0, 0, 5, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0, 5, 0, 0, 0])
+ // swiftformat:enable all
}
func testCreateEmptyIntArray() {
@@ -54,7 +66,9 @@
var b = FlatBufferBuilder(initialSize: 20)
let o = b.createVector(ofStrings: strs)
b.finish(offset: o)
+ // swiftformat:disable all
XCTAssertEqual(b.sizedByteArray, [4, 0, 0, 0, 2, 0, 0, 0, 20, 0, 0, 0, 4, 0, 0, 0, 6, 0, 0, 0, 78, 111, 114, 119, 97, 121, 0, 0, 7, 0, 0, 0, 68, 101, 110, 109, 97, 114, 107, 0])
+ // swiftformat:enable all
}
func testCreateSharedStringVector() {
let norway = "Norway"
@@ -67,7 +81,9 @@
let v = [noStr, deStr, _noStr, _deStr]
let end = b.createVector(ofOffsets: v)
b.finish(offset: end)
+ // swiftformat:disable all
XCTAssertEqual(b.sizedByteArray, [4, 0, 0, 0, 4, 0, 0, 0, 28, 0, 0, 0, 12, 0, 0, 0, 20, 0, 0, 0, 4, 0, 0, 0, 7, 0, 0, 0, 68, 101, 110, 109, 97, 114, 107, 0, 6, 0, 0, 0, 78, 111, 114, 119, 97, 121, 0, 0])
+ // swiftformat:enable all
}
func testReadInt32Array() {
@@ -101,7 +117,9 @@
@inlinable
static func getRootAsNumbers(_ bb: ByteBuffer) -> Numbers {
- Numbers(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: 0))))
+ Numbers(Table(
+ bb: bb,
+ position: Int32(bb.read(def: UOffset.self, position: 0))))
}
var vArrayInt: [Int]? { __t.getVector(at: 4) }
@@ -109,23 +127,35 @@
var vArrayDouble: [Double]? { __t.getVector(at: 4) }
var vArrayFloat: [Float32]? { __t.getVector(at: 4) }
- static func createNumbersVector(b: inout FlatBufferBuilder, array: [Int]) -> Offset<UOffset> {
+ static func createNumbersVector(
+ b: inout FlatBufferBuilder,
+ array: [Int]) -> Offset
+ {
b.createVector(array, size: array.count)
}
- static func createNumbersVector(b: inout FlatBufferBuilder, array: [Int32]) -> Offset<UOffset> {
+ static func createNumbersVector(
+ b: inout FlatBufferBuilder,
+ array: [Int32]) -> Offset
+ {
b.createVector(array, size: array.count)
}
- static func createNumbersVector(b: inout FlatBufferBuilder, array: [Double]) -> Offset<UOffset> {
+ static func createNumbersVector(
+ b: inout FlatBufferBuilder,
+ array: [Double]) -> Offset
+ {
b.createVector(array, size: array.count)
}
- static func createNumbersVector(b: inout FlatBufferBuilder, array: [Float32]) -> Offset<UOffset> {
+ static func createNumbersVector(
+ b: inout FlatBufferBuilder,
+ array: [Float32]) -> Offset
+ {
b.createVector(array, size: array.count)
}
- static func createNumbers(b: inout FlatBufferBuilder, o: Offset<UOffset>) -> Offset<UOffset> {
+ static func createNumbers(b: inout FlatBufferBuilder, o: Offset) -> Offset {
let start = b.startTable(with: 1)
b.add(offset: o, at: 4)
return Offset(offset: b.endTable(at: start))
diff --git a/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/FlatbuffersDoubleTests.swift b/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/FlatbuffersDoubleTests.swift
index 4d6d724..a6e1cb0 100644
--- a/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/FlatbuffersDoubleTests.swift
+++ b/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/FlatbuffersDoubleTests.swift
@@ -1,5 +1,5 @@
/*
- * Copyright 2020 Google Inc. All rights reserved.
+ * Copyright 2021 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.
@@ -23,17 +23,39 @@
func testCreateFinish() {
var b = FlatBufferBuilder(initialSize: 16)
- let countryOff = CountryDouble.createCountry(builder: &b, name: country, log: 200, lan: 100)
+ let countryOff = CountryDouble.createCountry(
+ builder: &b,
+ name: country,
+ log: 200,
+ lan: 100)
b.finish(offset: countryOff)
- let v: [UInt8] = [16, 0, 0, 0, 0, 0, 10, 0, 28, 0, 4, 0, 8, 0, 16, 0, 10, 0, 0, 0, 24, 0, 0, 0, 0, 0, 0, 0, 0, 0, 89, 64, 0, 0, 0, 0, 0, 0, 105, 64, 0, 0, 0, 0, 6, 0, 0, 0, 78, 111, 114, 119, 97, 121, 0, 0]
+ // swiftformat:disable all
+ let v: [UInt8] = [
+ 16, 0, 0, 0, 0, 0, 10, 0, 28, 0, 4, 0, 8, 0, 16, 0, 10,
+ 0, 0, 0, 24, 0, 0, 0, 0, 0, 0, 0, 0, 0, 89, 64, 0, 0, 0,
+ 0, 0, 0, 105, 64, 0, 0, 0, 0, 6, 0, 0, 0, 78, 111, 114, 119,
+ 97, 121, 0, 0
+ ]
+ // swiftformat:enable all
XCTAssertEqual(b.sizedByteArray, v)
}
func testCreateFinishWithPrefix() {
var b = FlatBufferBuilder(initialSize: 16)
- let countryOff = CountryDouble.createCountry(builder: &b, name: country, log: 200, lan: 100)
+ let countryOff = CountryDouble.createCountry(
+ builder: &b,
+ name: country,
+ log: 200,
+ lan: 100)
b.finish(offset: countryOff, addPrefix: true)
- let v: [UInt8] = [60, 0, 0, 0, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 28, 0, 4, 0, 8, 0, 16, 0, 10, 0, 0, 0, 24, 0, 0, 0, 0, 0, 0, 0, 0, 0, 89, 64, 0, 0, 0, 0, 0, 0, 105, 64, 0, 0, 0, 0, 6, 0, 0, 0, 78, 111, 114, 119, 97, 121, 0, 0]
+ // swiftformat:disable all
+ let v: [UInt8] = [
+ 60, 0, 0, 0, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 28
+ , 0, 4, 0, 8, 0, 16, 0, 10, 0, 0, 0, 24, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 89, 64, 0, 0, 0, 0, 0, 0, 105, 64, 0, 0, 0,
+ 0, 6, 0, 0, 0, 78, 111, 114, 119, 97, 121, 0, 0
+ ]
+ // swiftformat:enable all
XCTAssertEqual(b.sizedByteArray, v)
}
}
@@ -55,16 +77,20 @@
builder: inout FlatBufferBuilder,
name: String,
log: Double,
- lan: Double) -> Offset<Country>
+ lan: Double) -> Offset
{
- createCountry(builder: &builder, offset: builder.create(string: name), log: log, lan: lan)
+ createCountry(
+ builder: &builder,
+ offset: builder.create(string: name),
+ log: log,
+ lan: lan)
}
static func createCountry(
builder: inout FlatBufferBuilder,
- offset: Offset<String>,
+ offset: Offset,
log: Double,
- lan: Double) -> Offset<Country>
+ lan: Double) -> Offset
{
let _start = builder.startTable(with: 3)
CountryDouble.add(builder: &builder, lng: log)
@@ -73,7 +99,10 @@
return CountryDouble.end(builder: &builder, startOffset: _start)
}
- static func end(builder: inout FlatBufferBuilder, startOffset: UOffset) -> Offset<Country> {
+ static func end(
+ builder: inout FlatBufferBuilder,
+ startOffset: UOffset) -> Offset
+ {
Offset(offset: builder.endTable(at: startOffset))
}
@@ -81,7 +110,7 @@
add(builder: &builder, name: builder.create(string: name))
}
- static func add(builder: inout FlatBufferBuilder, name: Offset<String>) {
+ static func add(builder: inout FlatBufferBuilder, name: Offset) {
builder.add(offset: name, at: Country.offsets.name)
}
diff --git a/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/FlatbuffersMoreDefaults.swift b/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/FlatbuffersMoreDefaults.swift
new file mode 100644
index 0000000..cd97f25
--- /dev/null
+++ b/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/FlatbuffersMoreDefaults.swift
@@ -0,0 +1,80 @@
+/*
+ * Copyright 2021 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.
+ */
+
+import Foundation
+import XCTest
+@testable import FlatBuffers
+
+class FlatBuffersMoreDefaults: XCTestCase {
+
+ func testFlatbuffersObject() {
+ var fbb = FlatBufferBuilder()
+ let root = MoreDefaults.createMoreDefaults(&fbb)
+ fbb.finish(offset: root)
+ let defaults = MoreDefaults.getRootAsMoreDefaults(bb: fbb.sizedBuffer)
+ XCTAssertEqual(defaults.emptyString, "")
+ XCTAssertEqual(defaults.someString, "some")
+ XCTAssertEqual(defaults.ints, [])
+ XCTAssertEqual(defaults.floats, [])
+ XCTAssertEqual(defaults.bools, [])
+ XCTAssertEqual(defaults.intsCount, 0)
+ XCTAssertEqual(defaults.floatsCount, 0)
+ XCTAssertEqual(defaults.abcsCount, 0)
+ XCTAssertEqual(defaults.boolsCount, 0)
+ }
+
+ func testFlatbuffersObjectAPI() {
+ var fbb = FlatBufferBuilder()
+ let defaults = MoreDefaultsT()
+ XCTAssertEqual(defaults.emptyString, "")
+ XCTAssertEqual(defaults.someString, "some")
+ XCTAssertEqual(defaults.ints, [])
+ XCTAssertEqual(defaults.floats, [])
+ XCTAssertEqual(defaults.abcs, [])
+ XCTAssertEqual(defaults.bools, [])
+
+ let buffer = defaults.serialize(builder: &fbb, type: MoreDefaults.self)
+ let fDefaults = MoreDefaults.getRootAsMoreDefaults(bb: buffer)
+ XCTAssertEqual(fDefaults.emptyString, "")
+ XCTAssertEqual(fDefaults.someString, "some")
+ XCTAssertEqual(fDefaults.ints, [])
+ XCTAssertEqual(fDefaults.floats, [])
+ XCTAssertEqual(fDefaults.intsCount, 0)
+ XCTAssertEqual(fDefaults.floatsCount, 0)
+ XCTAssertEqual(fDefaults.abcsCount, 0)
+ XCTAssertEqual(fDefaults.boolsCount, 0)
+ }
+
+ func testEncoding() {
+ var fbb = FlatBufferBuilder()
+ let root = MoreDefaults.createMoreDefaults(&fbb)
+ fbb.finish(offset: root)
+ var sizedBuffer = fbb.sizedBuffer
+ do {
+ let reader: MoreDefaults = try getCheckedRoot(byteBuffer: &sizedBuffer)
+ let encoder = JSONEncoder()
+ encoder.keyEncodingStrategy = .convertToSnakeCase
+ let data = try encoder.encode(reader)
+ XCTAssertEqual(data, jsonData.data(using: .utf8))
+ } catch {
+ XCTFail(error.localizedDescription)
+ }
+ }
+
+ var jsonData: String {
+ "{\"empty_string\":\"\",\"some_string\":\"some\"}"
+ }
+}
diff --git a/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/FlatbuffersVerifierTests.swift b/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/FlatbuffersVerifierTests.swift
new file mode 100644
index 0000000..750f97b
--- /dev/null
+++ b/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/FlatbuffersVerifierTests.swift
@@ -0,0 +1,243 @@
+/*
+ * Copyright 2021 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.
+ */
+
+import XCTest
+@testable import FlatBuffers
+
+final class FlatbuffersVerifierTests: XCTestCase {
+
+ lazy var validStorage: ByteBuffer.Storage = ByteBuffer.Storage(
+ count: Int(FlatBufferMaxSize) - 1,
+ alignment: 1)
+ lazy var errorStorage: ByteBuffer.Storage = ByteBuffer.Storage(
+ count: Int(FlatBufferMaxSize) + 1,
+ alignment: 1)
+
+ var buffer: ByteBuffer!
+
+ var validFlatbuffersObject: ByteBuffer!
+ var invalidFlatbuffersObject: ByteBuffer!
+
+ override func setUp() {
+ // swiftformat:disable all
+ buffer = ByteBuffer(initialSize: 32)
+ add(buffer: &buffer, v: 4, p: 16)
+ add(buffer: &buffer, v: 4, p: 20)
+
+ validFlatbuffersObject = ByteBuffer(bytes: [48, 0, 0, 0, 77, 79, 78, 83, 0, 0, 0, 0, 36, 0, 72, 0, 40, 0, 0, 0, 38, 0, 32, 0, 0, 0, 28, 0, 0, 0, 27, 0, 20, 0, 16, 0, 12, 0, 4, 0, 0, 0, 0, 0, 0, 0, 11, 0, 36, 0, 0, 0, 164, 0, 0, 0, 0, 0, 0, 1, 60, 0, 0, 0, 68, 0, 0, 0, 76, 0, 0, 0, 0, 0, 0, 1, 88, 0, 0, 0, 120, 0, 0, 0, 0, 0, 80, 0, 0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 64, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 64, 2, 0, 5, 0, 6, 0, 0, 0, 2, 0, 0, 0, 64, 0, 0, 0, 48, 0, 0, 0, 2, 0, 0, 0, 30, 0, 40, 0, 10, 0, 20, 0, 152, 255, 255, 255, 4, 0, 0, 0, 4, 0, 0, 0, 70, 114, 101, 100, 0, 0, 0, 0, 5, 0, 0, 0, 0, 1, 2, 3, 4, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 50, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 49, 0, 0, 0, 9, 0, 0, 0, 77, 121, 77, 111, 110, 115, 116, 101, 114, 0, 0, 0, 3, 0, 0, 0, 20, 0, 0, 0, 36, 0, 0, 0, 4, 0, 0, 0, 240, 255, 255, 255, 32, 0, 0, 0, 248, 255, 255, 255, 36, 0, 0, 0, 12, 0, 8, 0, 0, 0, 0, 0, 0, 0, 4, 0, 12, 0, 0, 0, 28, 0, 0, 0, 5, 0, 0, 0, 87, 105, 108, 109, 97, 0, 0, 0, 6, 0, 0, 0, 66, 97, 114, 110, 101, 121, 0, 0, 5, 0, 0, 0, 70, 114, 111, 100, 111, 0, 0, 0])
+
+ invalidFlatbuffersObject = ByteBuffer(bytes: [0, 48, 0, 0, 0, 77, 79, 78, 83, 0, 0, 0, 0, 36, 0, 72, 0, 40, 0, 0, 0, 38, 0, 32, 0, 0, 0, 28, 0, 0, 0, 27, 0, 20, 0, 16, 0, 12, 0, 4, 0, 0, 0, 0, 0, 0, 0, 11, 0, 36, 0, 0, 0, 164, 0, 0, 0, 0, 0, 0, 1, 60, 0, 0, 0, 68, 0, 0, 0, 76, 0, 0, 0, 0, 0, 0, 1, 88, 0, 0, 0, 120, 0, 0, 0, 0, 0, 80, 0, 0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 64, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 64, 2, 0, 5, 0, 6, 0, 0, 0, 2, 0, 0, 0, 64, 0, 0, 0, 48, 0, 0, 0, 2, 0, 0, 0, 30, 0, 40, 0, 10, 0, 20, 0, 152, 255, 255, 255, 4, 0, 0, 0, 4, 0, 0, 0, 70, 114, 101, 100, 0, 0, 0, 0, 5, 0, 0, 0, 0, 1, 2, 3, 4, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 50, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 49, 0, 0, 0, 9, 0, 0, 0, 77, 121, 77, 111, 110, 115, 116, 101, 114, 0, 0, 0, 3, 0, 0, 0, 20, 0, 0, 0, 36, 0, 0, 0, 4, 0, 0, 0, 240, 255, 255, 255, 32, 0, 0, 0, 248, 255, 255, 255, 36, 0, 0, 0, 12, 0, 8, 0, 0, 0, 0, 0, 0, 0, 4, 0, 12, 0, 0, 0, 28, 0, 0, 0, 5, 0, 0, 0, 87, 105, 108, 109, 97, 0, 0, 0, 6, 0, 0, 0, 66, 97, 114, 110, 101, 121, 0, 0, 5, 0, 0, 0, 70, 114, 111, 100, 111, 0, 0, 0])
+
+ // swiftformat:enable all
+ }
+
+ func testVeriferInitPassing() {
+ var buffer = ByteBuffer(initialSize: 0)
+ buffer._storage = validStorage
+ XCTAssertNoThrow(try Verifier(buffer: &buffer))
+ }
+
+ func testVeriferInitFailing() {
+ var buffer = ByteBuffer(initialSize: 0)
+ buffer._storage = errorStorage
+ XCTAssertThrowsError(try Verifier(buffer: &buffer))
+ }
+
+ func testVerifierCheckAlignment() {
+ var verifier = try! Verifier(buffer: &buffer)
+ do {
+ try verifier.isAligned(position: 20, type: Int.self)
+ } catch {
+ XCTAssertEqual(
+ error as? FlatbuffersErrors,
+ .missAlignedPointer(position: 20, type: "Int"))
+ }
+ XCTAssertNoThrow(try verifier.isAligned(position: 16, type: Int.self))
+
+ var newVerifer = try! Verifier(buffer: &buffer, checkAlignment: false)
+ XCTAssertNoThrow(try newVerifer.isAligned(position: 16, type: Int.self))
+ }
+
+ func testRangeInBuffer() {
+ var verifier = try! Verifier(buffer: &buffer)
+ let size = MemoryLayout<Int64>.size
+ XCTAssertNoThrow(try verifier.rangeInBuffer(position: 24, size: size))
+ XCTAssertThrowsError(try verifier.rangeInBuffer(position: 26, size: size))
+ XCTAssertThrowsError(try verifier.rangeInBuffer(position: 26, size: size))
+ XCTAssertThrowsError(try verifier.rangeInBuffer(position: 30, size: size))
+ XCTAssertThrowsError(try verifier.rangeInBuffer(position: 32, size: size))
+ XCTAssertThrowsError(try verifier.rangeInBuffer(position: 34, size: size))
+
+ verifier = try! Verifier(
+ buffer: &buffer,
+ options: .init(maxDepth: 0, maxTableCount: 0, maxApparentSize: 4))
+ do {
+ try verifier.rangeInBuffer(position: 24, size: size)
+ } catch {
+ XCTAssertEqual(
+ error as! FlatbuffersErrors,
+ .apparentSizeTooLarge)
+ }
+ }
+
+ func testPositionInBuffer() {
+ var verifier = try! Verifier(buffer: &buffer)
+ XCTAssertNoThrow(try verifier.inBuffer(position: 0, of: Int64.self))
+ XCTAssertNoThrow(try verifier.inBuffer(position: 24, of: Int64.self))
+ XCTAssertThrowsError(try verifier.inBuffer(position: -9, of: Int64.self))
+ XCTAssertThrowsError(try verifier.inBuffer(position: 25, of: Int64.self))
+ XCTAssertThrowsError(try verifier.inBuffer(position: 26, of: Int32.self))
+ XCTAssertThrowsError(try verifier.inBuffer(position: 26, of: Int64.self))
+ XCTAssertThrowsError(try verifier.inBuffer(position: 30, of: Int64.self))
+ XCTAssertThrowsError(try verifier.inBuffer(position: 32, of: Int64.self))
+ XCTAssertThrowsError(try verifier.inBuffer(position: 34, of: Int64.self))
+ }
+
+ func testVisitTable() {
+ var verifier = try! Verifier(buffer: &validFlatbuffersObject)
+ XCTAssertNoThrow(try verifier.visitTable(at: 48))
+ verifier.reset()
+ }
+
+ func testTableVerifier() {
+ var verifier = try! Verifier(buffer: &validFlatbuffersObject)
+
+ var tableVerifer = try! verifier.visitTable(at: 48)
+ XCTAssertNoThrow(try tableVerifer.visit(
+ field: 4,
+ fieldName: "Vec",
+ required: false,
+ type: Vec3.self))
+ XCTAssertNoThrow(try tableVerifer.visit(
+ field: 8,
+ fieldName: "hp",
+ required: false,
+ type: Int16.self))
+
+ XCTAssertNoThrow(try tableVerifer.visit(
+ field: 10,
+ fieldName: "name",
+ required: true,
+ type: ForwardOffset<String>.self))
+
+ XCTAssertNoThrow(try tableVerifer.visit(
+ field: 14,
+ fieldName: "inventory",
+ required: false,
+ type: ForwardOffset<Vector<UInt8, UInt8>>.self))
+
+ XCTAssertNoThrow(try tableVerifer.visit(
+ field: 22,
+ fieldName: "test4",
+ required: false,
+ type: ForwardOffset<Vector<MyGame_Example_Test, MyGame_Example_Test>>
+ .self))
+
+ XCTAssertNoThrow(try tableVerifer.visit(
+ field: 24,
+ fieldName: "Vector of strings",
+ required: false,
+ type: ForwardOffset<Vector<ForwardOffset<String>, String>>.self))
+
+ do {
+ try tableVerifer.visit(
+ field: 13,
+ fieldName: "notvalid",
+ required: false,
+ type: Int16.self)
+ } catch {
+ XCTAssertEqual(
+ error as! FlatbuffersErrors,
+ .missAlignedPointer(position: 25, type: "UInt16"))
+ }
+
+ do {
+ try tableVerifer.visit(
+ unionKey: 18,
+ unionField: 20,
+ unionKeyName: "testType",
+ fieldName: "test",
+ required: false,
+ completion: { (verifier, key: MyGame_Example_Any_, pos) in
+ switch key {
+ case .none_:
+ break
+ case .monster:
+ try ForwardOffset<MyGame_Example_Monster>.verify(
+ &verifier,
+ at: pos,
+ of: MyGame_Example_Monster.self)
+
+ case .testsimpletablewithenum:
+ break
+ case .mygameExample2Monster:
+ break
+ }
+ })
+ } catch {
+ XCTAssertEqual(
+ error as! FlatbuffersErrors,
+ .missAlignedPointer(position: 25, type: "UInt16"))
+ }
+ }
+
+ func testVerifyUnionVectors() {
+ // swiftformat:disable all
+ var byteBuffer = ByteBuffer(bytes: [20, 0, 0, 0, 77, 79, 86, 73, 12, 0, 12, 0, 0, 0, 0, 0, 8, 0, 4, 0, 12, 0, 0, 0, 8, 0, 0, 0, 20, 0, 0, 0, 3, 0, 0, 0, 24, 0, 0, 0, 32, 0, 0, 0, 12, 0, 0, 0, 3, 0, 0, 0, 3, 1, 4, 0, 2, 0, 0, 0, 7, 0, 0, 0, 0, 0, 6, 0, 8, 0, 4, 0, 6, 0, 0, 0, 8, 0, 0, 0])
+ // swiftformat:enable all
+ XCTAssertNoThrow(try getCheckedRoot(byteBuffer: &byteBuffer) as Movie)
+ }
+
+ func testFullVerifier() {
+ XCTAssertNoThrow(
+ try getCheckedRoot(
+ byteBuffer: &validFlatbuffersObject) as MyGame_Example_Monster)
+ }
+
+ func testInvalidBuffer() {
+ XCTAssertThrowsError(
+ try getCheckedRoot(
+ byteBuffer: &invalidFlatbuffersObject) as MyGame_Example_Monster)
+ }
+
+ func testValidUnionBuffer() {
+ let string = "Awesome \\\\t\t\nstring!"
+ var fb = FlatBufferBuilder()
+ let stringOffset = fb.create(string: string)
+ let characterType: [Character] = [.bookfan, .other]
+
+ let characters = [
+ fb.create(struct: BookReader(booksRead: 7)),
+ stringOffset,
+ ]
+ let types = fb.createVector(characterType)
+ let characterVector = fb.createVector(ofOffsets: characters)
+
+ let end = Movie.createMovie(
+ &fb,
+ mainCharacterType: .other,
+ mainCharacterOffset: Offset(offset: stringOffset.o),
+ charactersTypeVectorOffset: types,
+ charactersVectorOffset: characterVector)
+ Movie.finish(&fb, end: end)
+ var buf = fb.sizedBuffer
+ XCTAssertNoThrow(try getCheckedRoot(byteBuffer: &buf) as Movie)
+ }
+
+ func add(buffer: inout ByteBuffer, v: Int32, p: Int) {
+ buffer.write(value: v, index: p)
+ }
+}
diff --git a/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/MutatingBool_generated.swift b/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/MutatingBool_generated.swift
index d51f3d9..155080a 100644
--- a/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/MutatingBool_generated.swift
+++ b/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/MutatingBool_generated.swift
@@ -1,47 +1,153 @@
// automatically generated by the FlatBuffers compiler, do not modify
+// swiftlint:disable all
+// swiftformat:disable all
import FlatBuffers
-public struct Property: Readable {
+public struct Property: NativeStruct, Verifiable, FlatbuffersInitializable, NativeObject {
- static func validateVersion() { FlatBuffersVersion_1_12_0() }
- public var __buffer: ByteBuffer! { return _accessor.bb }
- private var _accessor: Struct
+ static func validateVersion() { FlatBuffersVersion_2_0_0() }
- public static var size = 1
- public static var alignment = 1
- public init(_ bb: ByteBuffer, o: Int32) { _accessor = Struct(bb: bb, position: o) }
+ private var _property: Bool
- public var property: Bool { return _accessor.readBuffer(of: Bool.self, at: 0) }
- @discardableResult public func mutate(property: Bool) -> Bool { return _accessor.mutate(property, index: 0) }
+ public init(_ bb: ByteBuffer, o: Int32) {
+ let _accessor = Struct(bb: bb, position: o)
+ _property = _accessor.readBuffer(of: Bool.self, at: 0)
+ }
+
+ public init(property: Bool) {
+ _property = property
+ }
+
+ public init() {
+ _property = false
+ }
+
+ public init(_ _t: inout Property_Mutable) {
+ _property = _t.property
+ }
+
+ public var property: Bool { _property }
+
+ public static func verify<T>(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable {
+ try verifier.inBuffer(position: position, of: Property.self)
+ }
}
-public func createProperty(builder: inout FlatBufferBuilder, property: Bool = false) -> Offset<UOffset> {
- builder.createStructOf(size: Property.size, alignment: Property.alignment)
- builder.reverseAdd(v: property, postion: 0)
- return builder.endStruct()
-}
+extension Property: Encodable {
-public struct TestMutatingBool: FlatBufferObject {
-
- static func validateVersion() { FlatBuffersVersion_1_12_0() }
- public var __buffer: ByteBuffer! { return _accessor.bb }
- private var _accessor: Table
-
- public static func getRootAsTestMutatingBool(bb: ByteBuffer) -> TestMutatingBool { return TestMutatingBool(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) }
-
- private init(_ t: Table) { _accessor = t }
- public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) }
-
- enum VTOFFSET: VOffset {
- case b = 4
- var v: Int32 { Int32(self.rawValue) }
- var p: VOffset { self.rawValue }
+ enum CodingKeys: String, CodingKey {
+ case property = "property"
+ }
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ if property != false {
+ try container.encodeIfPresent(property, forKey: .property)
}
-
- public var b: Property? { let o = _accessor.offset(VTOFFSET.b.v); return o == 0 ? nil : Property(_accessor.bb, o: o + _accessor.postion) }
- public static func startTestMutatingBool(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) }
- public static func add(b: Offset<UOffset>, _ fbb: inout FlatBufferBuilder) { fbb.add(structOffset: VTOFFSET.b.p) }
- public static func endTestMutatingBool(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset<UOffset> { let end = Offset<UOffset>(offset: fbb.endTable(at: start)); return end }
+ }
}
+public struct Property_Mutable: FlatBufferObject {
+
+ static func validateVersion() { FlatBuffersVersion_2_0_0() }
+ public var __buffer: ByteBuffer! { return _accessor.bb }
+ private var _accessor: Struct
+
+ public init(_ bb: ByteBuffer, o: Int32) { _accessor = Struct(bb: bb, position: o) }
+
+ public var property: Bool { return _accessor.readBuffer(of: Bool.self, at: 0) }
+ @discardableResult public func mutate(property: Bool) -> Bool { return _accessor.mutate(property, index: 0) }
+
+
+ public mutating func unpack() -> Property {
+ return Property(&self)
+ }
+ public static func pack(_ builder: inout FlatBufferBuilder, obj: inout Property?) -> Offset {
+ guard var obj = obj else { return Offset() }
+ return pack(&builder, obj: &obj)
+ }
+
+ public static func pack(_ builder: inout FlatBufferBuilder, obj: inout Property) -> Offset {
+ return builder.create(struct: obj)
+ }
+}
+
+public struct TestMutatingBool: FlatBufferObject, Verifiable, ObjectAPIPacker {
+
+ static func validateVersion() { FlatBuffersVersion_2_0_0() }
+ public var __buffer: ByteBuffer! { return _accessor.bb }
+ private var _accessor: Table
+
+ public static func getRootAsTestMutatingBool(bb: ByteBuffer) -> TestMutatingBool { return TestMutatingBool(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) }
+
+ private init(_ t: Table) { _accessor = t }
+ public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) }
+
+ private enum VTOFFSET: VOffset {
+ case b = 4
+ var v: Int32 { Int32(self.rawValue) }
+ var p: VOffset { self.rawValue }
+ }
+
+ public var b: Property? { let o = _accessor.offset(VTOFFSET.b.v); return o == 0 ? nil : _accessor.readBuffer(of: Property.self, at: o) }
+ public var mutableB: Property_Mutable? { let o = _accessor.offset(VTOFFSET.b.v); return o == 0 ? nil : Property_Mutable(_accessor.bb, o: o + _accessor.postion) }
+ public static func startTestMutatingBool(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) }
+ public static func add(b: Property?, _ fbb: inout FlatBufferBuilder) { guard let b = b else { return }; fbb.create(struct: b, position: VTOFFSET.b.p) }
+ public static func endTestMutatingBool(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end }
+ public static func createTestMutatingBool(
+ _ fbb: inout FlatBufferBuilder,
+ b: Property? = nil
+ ) -> Offset {
+ let __start = TestMutatingBool.startTestMutatingBool(&fbb)
+ TestMutatingBool.add(b: b, &fbb)
+ return TestMutatingBool.endTestMutatingBool(&fbb, start: __start)
+ }
+
+
+ public mutating func unpack() -> TestMutatingBoolT {
+ return TestMutatingBoolT(&self)
+ }
+ public static func pack(_ builder: inout FlatBufferBuilder, obj: inout TestMutatingBoolT?) -> Offset {
+ guard var obj = obj else { return Offset() }
+ return pack(&builder, obj: &obj)
+ }
+
+ public static func pack(_ builder: inout FlatBufferBuilder, obj: inout TestMutatingBoolT) -> Offset {
+ let __root = TestMutatingBool.startTestMutatingBool(&builder)
+ TestMutatingBool.add(b: obj.b, &builder)
+ return TestMutatingBool.endTestMutatingBool(&builder, start: __root)
+ }
+
+ public static func verify<T>(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable {
+ var _v = try verifier.visitTable(at: position)
+ try _v.visit(field: VTOFFSET.b.p, fieldName: "b", required: false, type: Property.self)
+ _v.finish()
+ }
+}
+
+extension TestMutatingBool: Encodable {
+
+ enum CodingKeys: String, CodingKey {
+ case b = "b"
+ }
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encodeIfPresent(b, forKey: .b)
+ }
+}
+
+public class TestMutatingBoolT: NativeObject {
+
+ public var b: Property?
+
+ public init(_ _t: inout TestMutatingBool) {
+ b = _t.b
+ }
+
+ public init() {
+ b = Property()
+ }
+
+ public func serialize() -> ByteBuffer { return serialize(type: TestMutatingBool.self) }
+
+}
diff --git a/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/XCTestManifests.swift b/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/XCTestManifests.swift
index 8459ee5..4134762 100644
--- a/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/XCTestManifests.swift
+++ b/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/XCTestManifests.swift
@@ -1,5 +1,5 @@
/*
- * Copyright 2020 Google Inc. All rights reserved.
+ * Copyright 2021 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.
@@ -32,6 +32,7 @@
// `swift test --generate-linuxmain`
// to regenerate.
static let __allTests__FlatBuffersMonsterWriterTests = [
+ ("testArrayOfBools", testArrayOfBools),
("testCreateMonster", testCreateMonster),
("testCreateMonsterPrefixed", testCreateMonsterPrefixed),
("testCreateMonsterResizedBuffer", testCreateMonsterResizedBuffer),
@@ -49,6 +50,16 @@
]
}
+extension FlatBuffersMoreDefaults {
+ // DO NOT MODIFY: This is autogenerated, use:
+ // `swift test --generate-linuxmain`
+ // to regenerate.
+ static let __allTests__FlatBuffersMoreDefaults = [
+ ("testFlatbuffersObject", testFlatbuffersObject),
+ ("testFlatbuffersObjectAPI", testFlatbuffersObjectAPI),
+ ]
+}
+
extension FlatBuffersStructsTests {
// DO NOT MODIFY: This is autogenerated, use:
// `swift test --generate-linuxmain`
@@ -83,6 +94,7 @@
("testCreateMonstor", testCreateMonstor),
("testEndTableFinish", testEndTableFinish),
("testEnumVector", testEnumVector),
+ ("testStringUnion", testStringUnion),
("testUnionVector", testUnionVector),
]
}
@@ -102,14 +114,37 @@
]
}
+extension FlatbuffersVerifierTests {
+ // DO NOT MODIFY: This is autogenerated, use:
+ // `swift test --generate-linuxmain`
+ // to regenerate.
+ static let __allTests__FlatbuffersVerifierTests = [
+ ("testFullVerifier", testFullVerifier),
+ ("testInvalidBuffer", testInvalidBuffer),
+ ("testPositionInBuffer", testPositionInBuffer),
+ ("testRangeInBuffer", testRangeInBuffer),
+ ("testTableVerifier", testTableVerifier),
+ ("testValidUnionBuffer", testValidUnionBuffer),
+ ("testVeriferInitFailing", testVeriferInitFailing),
+ ("testVeriferInitPassing", testVeriferInitPassing),
+ ("testVerifierCheckAlignment", testVerifierCheckAlignment),
+ ("testVerifyUnionVectors", testVerifyUnionVectors),
+ ("testVisitTable", testVisitTable),
+ ]
+}
+
public func __allTests() -> [XCTestCaseEntry] {
[
testCase(FlatBuffersDoubleTests.__allTests__FlatBuffersDoubleTests),
- testCase(FlatBuffersMonsterWriterTests.__allTests__FlatBuffersMonsterWriterTests),
+ testCase(
+ FlatBuffersMonsterWriterTests
+ .__allTests__FlatBuffersMonsterWriterTests),
+ testCase(FlatBuffersMoreDefaults.__allTests__FlatBuffersMoreDefaults),
testCase(FlatBuffersStructsTests.__allTests__FlatBuffersStructsTests),
testCase(FlatBuffersTests.__allTests__FlatBuffersTests),
testCase(FlatBuffersUnionTests.__allTests__FlatBuffersUnionTests),
testCase(FlatBuffersVectors.__allTests__FlatBuffersVectors),
+ testCase(FlatbuffersVerifierTests.__allTests__FlatbuffersVerifierTests),
]
}
#endif
diff --git a/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/monster_test.grpc.swift b/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/monster_test.grpc.swift
index 414a816..b5fd535 100644
--- a/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/monster_test.grpc.swift
+++ b/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/monster_test.grpc.swift
@@ -24,41 +24,121 @@
extension Message: GRPCFlatBufPayload {}
/// Usage: instantiate MyGame_Example_MonsterStorageServiceClient, then call methods of this protocol to make API calls.
-public protocol MyGame_Example_MonsterStorageService {
- func Store(_ request: Message<MyGame_Example_Monster>, callOptions: CallOptions?) -> UnaryCall<Message<MyGame_Example_Monster>,Message<MyGame_Example_Stat>>
- func Retrieve(_ request: Message<MyGame_Example_Stat>, callOptions: CallOptions?, handler: @escaping (Message<MyGame_Example_Monster>) -> Void) -> ServerStreamingCall<Message<MyGame_Example_Stat>, Message<MyGame_Example_Monster>>
- func GetMaxHitPoint(callOptions: CallOptions?) -> ClientStreamingCall<Message<MyGame_Example_Monster>,Message<MyGame_Example_Stat>>
- func GetMinMaxHitPoints(callOptions: CallOptions?, handler: @escaping (Message<MyGame_Example_Stat>) -> Void) -> BidirectionalStreamingCall<Message<MyGame_Example_Monster>, Message<MyGame_Example_Stat>>
+public protocol MyGame_Example_MonsterStorageClientProtocol: GRPCClient {
+
+ var serviceName: String { get }
+
+ var interceptors: MyGame_Example_MonsterStorageClientInterceptorFactoryProtocol? { get }
+
+ func Store(
+ _ request: Message<MyGame_Example_Monster>
+ , callOptions: CallOptions?
+ ) -> UnaryCall<Message<MyGame_Example_Monster>, Message<MyGame_Example_Stat>>
+
+ func Retrieve(
+ _ request: Message<MyGame_Example_Stat>
+ , callOptions: CallOptions?,
+ handler: @escaping (Message<MyGame_Example_Monster>) -> Void
+ ) -> ServerStreamingCall<Message<MyGame_Example_Stat>, Message<MyGame_Example_Monster>>
+
+ func GetMaxHitPoint(
+ callOptions: CallOptions?
+ ) -> ClientStreamingCall<Message<MyGame_Example_Monster>, Message<MyGame_Example_Stat>>
+
+ func GetMinMaxHitPoints(
+ callOptions: CallOptions?,
+ handler: @escaping (Message<MyGame_Example_Stat> ) -> Void
+ ) -> BidirectionalStreamingCall<Message<MyGame_Example_Monster>, Message<MyGame_Example_Stat>>
+
}
-public final class MyGame_Example_MonsterStorageServiceClient: GRPCClient, MyGame_Example_MonsterStorageService {
+extension MyGame_Example_MonsterStorageClientProtocol {
+
+ public var serviceName: String { "MyGame.Example.MonsterStorage" }
+
+ public func Store(
+ _ request: Message<MyGame_Example_Monster>
+ , callOptions: CallOptions? = nil
+ ) -> UnaryCall<Message<MyGame_Example_Monster>, Message<MyGame_Example_Stat>> {
+ return self.makeUnaryCall(
+ path: "/MyGame.Example.MonsterStorage/Store",
+ request: request,
+ callOptions: callOptions ?? self.defaultCallOptions,
+ interceptors: self.interceptors?.makeStoreInterceptors() ?? []
+ )
+ }
+
+ public func Retrieve(
+ _ request: Message<MyGame_Example_Stat>
+ , callOptions: CallOptions? = nil,
+ handler: @escaping (Message<MyGame_Example_Monster>) -> Void
+ ) -> ServerStreamingCall<Message<MyGame_Example_Stat>, Message<MyGame_Example_Monster>> {
+ return self.makeServerStreamingCall(
+ path: "/MyGame.Example.MonsterStorage/Retrieve",
+ request: request,
+ callOptions: callOptions ?? self.defaultCallOptions,
+ interceptors: self.interceptors?.makeRetrieveInterceptors() ?? [],
+ handler: handler
+ )
+ }
+
+ public func GetMaxHitPoint(
+ callOptions: CallOptions? = nil
+ ) -> ClientStreamingCall<Message<MyGame_Example_Monster>, Message<MyGame_Example_Stat>> {
+ return self.makeClientStreamingCall(
+ path: "/MyGame.Example.MonsterStorage/GetMaxHitPoint",
+ callOptions: callOptions ?? self.defaultCallOptions,
+ interceptors: self.interceptors?.makeGetMaxHitPointInterceptors() ?? []
+ )
+ }
+
+ public func GetMinMaxHitPoints(
+ callOptions: CallOptions? = nil,
+ handler: @escaping (Message<MyGame_Example_Stat> ) -> Void
+ ) -> BidirectionalStreamingCall<Message<MyGame_Example_Monster>, Message<MyGame_Example_Stat>> {
+ return self.makeBidirectionalStreamingCall(
+ path: "/MyGame.Example.MonsterStorage/GetMinMaxHitPoints",
+ callOptions: callOptions ?? self.defaultCallOptions,
+ interceptors: self.interceptors?.makeGetMinMaxHitPointsInterceptors() ?? [],
+ handler: handler
+ )
+ }
+}
+
+public protocol MyGame_Example_MonsterStorageClientInterceptorFactoryProtocol {
+ /// - Returns: Interceptors to use when invoking 'Store'.
+ func makeStoreInterceptors() -> [ClientInterceptor<Message<MyGame_Example_Monster>, Message<MyGame_Example_Stat>>]
+
+ /// - Returns: Interceptors to use when invoking 'Retrieve'.
+ func makeRetrieveInterceptors() -> [ClientInterceptor<Message<MyGame_Example_Stat>, Message<MyGame_Example_Monster>>]
+
+ /// - Returns: Interceptors to use when invoking 'GetMaxHitPoint'.
+ func makeGetMaxHitPointInterceptors() -> [ClientInterceptor<Message<MyGame_Example_Monster>, Message<MyGame_Example_Stat>>]
+
+ /// - Returns: Interceptors to use when invoking 'GetMinMaxHitPoints'.
+ func makeGetMinMaxHitPointsInterceptors() -> [ClientInterceptor<Message<MyGame_Example_Monster>, Message<MyGame_Example_Stat>>]
+
+}
+
+public final class MyGame_Example_MonsterStorageServiceClient: MyGame_Example_MonsterStorageClientProtocol {
public let channel: GRPCChannel
public var defaultCallOptions: CallOptions
+ public var interceptors: MyGame_Example_MonsterStorageClientInterceptorFactoryProtocol?
- public init(channel: GRPCChannel, defaultCallOptions: CallOptions = CallOptions()) {
+ public init(
+ channel: GRPCChannel,
+ defaultCallOptions: CallOptions = CallOptions(),
+ interceptors: MyGame_Example_MonsterStorageClientInterceptorFactoryProtocol? = nil
+ ) {
self.channel = channel
self.defaultCallOptions = defaultCallOptions
- }
-
- public func Store(_ request: Message<MyGame_Example_Monster>, callOptions: CallOptions? = nil) -> UnaryCall<Message<MyGame_Example_Monster>,Message<MyGame_Example_Stat>> {
- return self.makeUnaryCall(path: "/MyGame.Example.MonsterStorage/Store", request: request, callOptions: callOptions ?? self.defaultCallOptions)
- }
-
- public func Retrieve(_ request: Message<MyGame_Example_Stat>, callOptions: CallOptions? = nil, handler: @escaping (Message<MyGame_Example_Monster>) -> Void) -> ServerStreamingCall<Message<MyGame_Example_Stat>, Message<MyGame_Example_Monster>> {
- return self.makeServerStreamingCall(path: "/MyGame.Example.MonsterStorage/Retrieve", request: request, callOptions: callOptions ?? self.defaultCallOptions, handler: handler)
- }
-
- public func GetMaxHitPoint(callOptions: CallOptions? = nil) -> ClientStreamingCall<Message<MyGame_Example_Monster>,Message<MyGame_Example_Stat>> {
- return self.makeClientStreamingCall(path: "/MyGame.Example.MonsterStorage/GetMaxHitPoint", callOptions: callOptions ?? self.defaultCallOptions)
- }
-
- public func GetMinMaxHitPoints(callOptions: CallOptions? = nil, handler: @escaping (Message<MyGame_Example_Stat>) -> Void) -> BidirectionalStreamingCall<Message<MyGame_Example_Monster>, Message<MyGame_Example_Stat>> {
- return self.makeBidirectionalStreamingCall(path: "/MyGame.Example.MonsterStorage/GetMinMaxHitPoints", callOptions: callOptions ?? self.defaultCallOptions, handler: handler)
+ self.interceptors = interceptors
}
}
public protocol MyGame_Example_MonsterStorageProvider: CallHandlerProvider {
- func Store(_ request: Message<MyGame_Example_Monster>, context: StatusOnlyCallContext) -> EventLoopFuture<Message<MyGame_Example_Stat>>
+ var interceptors: MyGame_Example_MonsterStorageServerInterceptorFactoryProtocol? { get }
+ func Store(request: Message<MyGame_Example_Monster>, context: StatusOnlyCallContext) -> EventLoopFuture<Message<MyGame_Example_Stat>>
func Retrieve(request: Message<MyGame_Example_Stat>, context: StreamingResponseCallContext<Message<MyGame_Example_Monster>>) -> EventLoopFuture<GRPCStatus>
func GetMaxHitPoint(context: UnaryResponseCallContext<Message<MyGame_Example_Stat>>) -> EventLoopFuture<(StreamEvent<Message<MyGame_Example_Monster>>) -> Void>
func GetMinMaxHitPoints(context: StreamingResponseCallContext<Message<MyGame_Example_Stat>>) -> EventLoopFuture<(StreamEvent<Message<MyGame_Example_Monster>>) -> Void>
@@ -68,30 +148,61 @@
var serviceName: Substring { return "MyGame.Example.MonsterStorage" }
- func handleMethod(_ methodName: Substring, callHandlerContext: CallHandlerContext) -> GRPCCallHandler? {
- switch methodName {
+ func handle(method name: Substring, context: CallHandlerContext) -> GRPCServerHandlerProtocol? {
+ switch name {
case "Store":
- return CallHandlerFactory.makeUnary(callHandlerContext: callHandlerContext) { context in
- return { request in
- self.Store(request, context: context)
- }
- }
+ return UnaryServerHandler(
+ context: context,
+ requestDeserializer: GRPCPayloadDeserializer<Message<MyGame_Example_Monster>>(),
+ responseSerializer: GRPCPayloadSerializer<Message<MyGame_Example_Stat>>(),
+ interceptors: self.interceptors?.makeStoreInterceptors() ?? [],
+ userFunction: self.Store(request:context:))
+
case "Retrieve":
- return CallHandlerFactory.makeServerStreaming(callHandlerContext: callHandlerContext) { context in
- return { request in
- self.Retrieve(request: request, context: context)
- }
- }
+ return ServerStreamingServerHandler(
+ context: context,
+ requestDeserializer: GRPCPayloadDeserializer<Message<MyGame_Example_Stat>>(),
+ responseSerializer: GRPCPayloadSerializer<Message<MyGame_Example_Monster>>(),
+ interceptors: self.interceptors?.makeRetrieveInterceptors() ?? [],
+ userFunction: self.Retrieve(request:context:))
+
case "GetMaxHitPoint":
- return CallHandlerFactory.makeClientStreaming(callHandlerContext: callHandlerContext) { context in
- self.GetMaxHitPoint(context: context)
- }
+ return ClientStreamingServerHandler(
+ context: context,
+ requestDeserializer: GRPCPayloadDeserializer<Message<MyGame_Example_Monster>>(),
+ responseSerializer: GRPCPayloadSerializer<Message<MyGame_Example_Stat>>(),
+ interceptors: self.interceptors?.makeGetMaxHitPointInterceptors() ?? [],
+ observerFactory: self.GetMaxHitPoint(context:))
+
case "GetMinMaxHitPoints":
- return CallHandlerFactory.makeBidirectionalStreaming(callHandlerContext: callHandlerContext) { context in
- self.GetMinMaxHitPoints(context: context)
- }
+ return BidirectionalStreamingServerHandler(
+ context: context,
+ requestDeserializer: GRPCPayloadDeserializer<Message<MyGame_Example_Monster>>(),
+ responseSerializer: GRPCPayloadSerializer<Message<MyGame_Example_Stat>>(),
+ interceptors: self.interceptors?.makeGetMinMaxHitPointsInterceptors() ?? [],
+ observerFactory: self.GetMinMaxHitPoints(context:))
+
default: return nil;
}
}
}
+
+public protocol MyGame_Example_MonsterStorageServerInterceptorFactoryProtocol {
+ /// - Returns: Interceptors to use when handling 'Store'.
+ /// Defaults to calling `self.makeInterceptors()`.
+ func makeStoreInterceptors() -> [ServerInterceptor<Message<MyGame_Example_Monster>, Message<MyGame_Example_Stat>>]
+
+ /// - Returns: Interceptors to use when handling 'Retrieve'.
+ /// Defaults to calling `self.makeInterceptors()`.
+ func makeRetrieveInterceptors() -> [ServerInterceptor<Message<MyGame_Example_Stat>, Message<MyGame_Example_Monster>>]
+
+ /// - Returns: Interceptors to use when handling 'GetMaxHitPoint'.
+ /// Defaults to calling `self.makeInterceptors()`.
+ func makeGetMaxHitPointInterceptors() -> [ServerInterceptor<Message<MyGame_Example_Monster>, Message<MyGame_Example_Stat>>]
+
+ /// - Returns: Interceptors to use when handling 'GetMinMaxHitPoints'.
+ /// Defaults to calling `self.makeInterceptors()`.
+ func makeGetMinMaxHitPointsInterceptors() -> [ServerInterceptor<Message<MyGame_Example_Monster>, Message<MyGame_Example_Stat>>]
+
+}
diff --git a/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/monster_test_generated.swift b/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/monster_test_generated.swift
index b15eddf..c8a0502 100644
--- a/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/monster_test_generated.swift
+++ b/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/monster_test_generated.swift
@@ -5,7 +5,7 @@
import FlatBuffers
/// Composite components of Monster color.
-public enum MyGame_Example_Color: UInt8, Enum {
+public enum MyGame_Example_Color: UInt8, Enum, Verifiable {
public typealias T = UInt8
public static var byteSize: Int { return MemoryLayout<UInt8>.size }
public var value: UInt8 { return self.rawValue }
@@ -15,13 +15,23 @@
case green = 2
/// \brief color Blue (1u << 3)
case blue = 8
-
public static var max: MyGame_Example_Color { return .blue }
public static var min: MyGame_Example_Color { return .red }
}
-public enum MyGame_Example_Race: Int8, Enum {
+extension MyGame_Example_Color: Encodable {
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.singleValueContainer()
+ switch self {
+ case .red: try container.encode("Red")
+ case .green: try container.encode("Green")
+ case .blue: try container.encode("Blue")
+ }
+ }
+}
+
+public enum MyGame_Example_Race: Int8, Enum, Verifiable {
public typealias T = Int8
public static var byteSize: Int { return MemoryLayout<Int8>.size }
public var value: Int8 { return self.rawValue }
@@ -29,34 +39,84 @@
case human = 0
case dwarf = 1
case elf = 2
-
public static var max: MyGame_Example_Race { return .elf }
public static var min: MyGame_Example_Race { return .none_ }
}
-public enum MyGame_Example_Any_: UInt8, Enum {
+extension MyGame_Example_Race: Encodable {
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.singleValueContainer()
+ switch self {
+ case .none_: try container.encode("None")
+ case .human: try container.encode("Human")
+ case .dwarf: try container.encode("Dwarf")
+ case .elf: try container.encode("Elf")
+ }
+ }
+}
+
+public enum MyGame_Example_LongEnum: UInt64, Enum, Verifiable {
+ public typealias T = UInt64
+ public static var byteSize: Int { return MemoryLayout<UInt64>.size }
+ public var value: UInt64 { return self.rawValue }
+ case longone = 2
+ case longtwo = 4
+ case longbig = 1099511627776
+
+ public static var max: MyGame_Example_LongEnum { return .longbig }
+ public static var min: MyGame_Example_LongEnum { return .longone }
+}
+
+extension MyGame_Example_LongEnum: Encodable {
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.singleValueContainer()
+ switch self {
+ case .longone: try container.encode("LongOne")
+ case .longtwo: try container.encode("LongTwo")
+ case .longbig: try container.encode("LongBig")
+ }
+ }
+}
+
+public enum MyGame_Example_Any_: UInt8, UnionEnum {
public typealias T = UInt8
+
+ public init?(value: T) {
+ self.init(rawValue: value)
+ }
+
public static var byteSize: Int { return MemoryLayout<UInt8>.size }
public var value: UInt8 { return self.rawValue }
case none_ = 0
case monster = 1
case testsimpletablewithenum = 2
case mygameExample2Monster = 3
-
public static var max: MyGame_Example_Any_ { return .mygameExample2Monster }
public static var min: MyGame_Example_Any_ { return .none_ }
}
+extension MyGame_Example_Any_: Encodable {
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.singleValueContainer()
+ switch self {
+ case .none_: try container.encode("NONE")
+ case .monster: try container.encode("Monster")
+ case .testsimpletablewithenum: try container.encode("TestSimpleTableWithEnum")
+ case .mygameExample2Monster: try container.encode("MyGame_Example2_Monster")
+ }
+ }
+}
+
public struct MyGame_Example_Any_Union {
public var type: MyGame_Example_Any_
- public var value: NativeTable?
- public init(_ v: NativeTable?, type: MyGame_Example_Any_) {
+ public var value: NativeObject?
+ public init(_ v: NativeObject?, type: MyGame_Example_Any_) {
self.type = type
self.value = v
}
- public func pack(builder: inout FlatBufferBuilder) -> Offset<UOffset> {
+ public func pack(builder: inout FlatBufferBuilder) -> Offset {
switch type {
case .monster:
var __obj = value as? MyGame_Example_MonsterT
@@ -71,28 +131,44 @@
}
}
}
-public enum MyGame_Example_AnyUniqueAliases: UInt8, Enum {
+public enum MyGame_Example_AnyUniqueAliases: UInt8, UnionEnum {
public typealias T = UInt8
+
+ public init?(value: T) {
+ self.init(rawValue: value)
+ }
+
public static var byteSize: Int { return MemoryLayout<UInt8>.size }
public var value: UInt8 { return self.rawValue }
case none_ = 0
case m = 1
case ts = 2
case m2 = 3
-
public static var max: MyGame_Example_AnyUniqueAliases { return .m2 }
public static var min: MyGame_Example_AnyUniqueAliases { return .none_ }
}
+extension MyGame_Example_AnyUniqueAliases: Encodable {
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.singleValueContainer()
+ switch self {
+ case .none_: try container.encode("NONE")
+ case .m: try container.encode("M")
+ case .ts: try container.encode("TS")
+ case .m2: try container.encode("M2")
+ }
+ }
+}
+
public struct MyGame_Example_AnyUniqueAliasesUnion {
public var type: MyGame_Example_AnyUniqueAliases
- public var value: NativeTable?
- public init(_ v: NativeTable?, type: MyGame_Example_AnyUniqueAliases) {
+ public var value: NativeObject?
+ public init(_ v: NativeObject?, type: MyGame_Example_AnyUniqueAliases) {
self.type = type
self.value = v
}
- public func pack(builder: inout FlatBufferBuilder) -> Offset<UOffset> {
+ public func pack(builder: inout FlatBufferBuilder) -> Offset {
switch type {
case .m:
var __obj = value as? MyGame_Example_MonsterT
@@ -107,28 +183,44 @@
}
}
}
-public enum MyGame_Example_AnyAmbiguousAliases: UInt8, Enum {
+public enum MyGame_Example_AnyAmbiguousAliases: UInt8, UnionEnum {
public typealias T = UInt8
+
+ public init?(value: T) {
+ self.init(rawValue: value)
+ }
+
public static var byteSize: Int { return MemoryLayout<UInt8>.size }
public var value: UInt8 { return self.rawValue }
case none_ = 0
case m1 = 1
case m2 = 2
case m3 = 3
-
public static var max: MyGame_Example_AnyAmbiguousAliases { return .m3 }
public static var min: MyGame_Example_AnyAmbiguousAliases { return .none_ }
}
+extension MyGame_Example_AnyAmbiguousAliases: Encodable {
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.singleValueContainer()
+ switch self {
+ case .none_: try container.encode("NONE")
+ case .m1: try container.encode("M1")
+ case .m2: try container.encode("M2")
+ case .m3: try container.encode("M3")
+ }
+ }
+}
+
public struct MyGame_Example_AnyAmbiguousAliasesUnion {
public var type: MyGame_Example_AnyAmbiguousAliases
- public var value: NativeTable?
- public init(_ v: NativeTable?, type: MyGame_Example_AnyAmbiguousAliases) {
+ public var value: NativeObject?
+ public init(_ v: NativeObject?, type: MyGame_Example_AnyAmbiguousAliases) {
self.type = type
self.value = v
}
- public func pack(builder: inout FlatBufferBuilder) -> Offset<UOffset> {
+ public func pack(builder: inout FlatBufferBuilder) -> Offset {
switch type {
case .m1:
var __obj = value as? MyGame_Example_MonsterT
@@ -143,14 +235,66 @@
}
}
}
-public struct MyGame_Example_Test: Readable {
+public struct MyGame_Example_Test: NativeStruct, Verifiable, FlatbuffersInitializable, NativeObject {
- static func validateVersion() { FlatBuffersVersion_1_12_0() }
+ static func validateVersion() { FlatBuffersVersion_2_0_0() }
+
+ private var _a: Int16
+ private var _b: Int8
+ private let padding0__: UInt8 = 0
+
+ public init(_ bb: ByteBuffer, o: Int32) {
+ let _accessor = Struct(bb: bb, position: o)
+ _a = _accessor.readBuffer(of: Int16.self, at: 0)
+ _b = _accessor.readBuffer(of: Int8.self, at: 2)
+ }
+
+ public init(a: Int16, b: Int8) {
+ _a = a
+ _b = b
+ }
+
+ public init() {
+ _a = 0
+ _b = 0
+ }
+
+ public init(_ _t: inout MyGame_Example_Test_Mutable) {
+ _a = _t.a
+ _b = _t.b
+ }
+
+ public var a: Int16 { _a }
+ public var b: Int8 { _b }
+
+ public static func verify<T>(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable {
+ try verifier.inBuffer(position: position, of: MyGame_Example_Test.self)
+ }
+}
+
+extension MyGame_Example_Test: Encodable {
+
+ enum CodingKeys: String, CodingKey {
+ case a = "a"
+ case b = "b"
+ }
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ if a != 0 {
+ try container.encodeIfPresent(a, forKey: .a)
+ }
+ if b != 0 {
+ try container.encodeIfPresent(b, forKey: .b)
+ }
+ }
+}
+
+public struct MyGame_Example_Test_Mutable: FlatBufferObject {
+
+ static func validateVersion() { FlatBuffersVersion_2_0_0() }
public var __buffer: ByteBuffer! { return _accessor.bb }
private var _accessor: Struct
- public static var size = 4
- public static var alignment = 2
public init(_ bb: ByteBuffer, o: Int32) { _accessor = Struct(bb: bb, position: o) }
public var a: Int16 { return _accessor.readBuffer(of: Int16.self, at: 0) }
@@ -159,43 +303,120 @@
@discardableResult public func mutate(b: Int8) -> Bool { return _accessor.mutate(b, index: 2) }
- public mutating func unpack() -> MyGame_Example_TestT {
- return MyGame_Example_TestT(&self)
+ public mutating func unpack() -> MyGame_Example_Test {
+ return MyGame_Example_Test(&self)
}
- public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_TestT?) -> Offset<UOffset> {
- guard var obj = obj else { return Offset<UOffset>() }
+ public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_Test?) -> Offset {
+ guard var obj = obj else { return Offset() }
return pack(&builder, obj: &obj)
}
- public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_TestT) -> Offset<UOffset> {
- return createTest(builder: &builder, a: obj.a, b: obj.b)
+ public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_Test) -> Offset {
+ return builder.create(struct: obj)
}
}
-public class MyGame_Example_TestT: NativeTable {
+public struct MyGame_Example_Vec3: NativeStruct, Verifiable, FlatbuffersInitializable, NativeObject {
- public var a: Int16
- public var b: Int8
+ static func validateVersion() { FlatBuffersVersion_2_0_0() }
- public init(_ _t: inout MyGame_Example_Test) {
- a = _t.a
- b = _t.b
+ private var _x: Float32
+ private var _y: Float32
+ private var _z: Float32
+ private let padding0__: UInt32 = 0
+ private var _test1: Double
+ private var _test2: UInt8
+ private let padding1__: UInt8 = 0
+ private var _test3: MyGame_Example_Test
+ private let padding2__: UInt16 = 0
+
+ public init(_ bb: ByteBuffer, o: Int32) {
+ let _accessor = Struct(bb: bb, position: o)
+ _x = _accessor.readBuffer(of: Float32.self, at: 0)
+ _y = _accessor.readBuffer(of: Float32.self, at: 4)
+ _z = _accessor.readBuffer(of: Float32.self, at: 8)
+ _test1 = _accessor.readBuffer(of: Double.self, at: 16)
+ _test2 = _accessor.readBuffer(of: UInt8.self, at: 24)
+ _test3 = MyGame_Example_Test(_accessor.bb, o: _accessor.postion + 26)
+ }
+
+ public init(x: Float32, y: Float32, z: Float32, test1: Double, test2: MyGame_Example_Color, test3: MyGame_Example_Test) {
+ _x = x
+ _y = y
+ _z = z
+ _test1 = test1
+ _test2 = test2.value
+ _test3 = test3
}
public init() {
- a = 0
- b = 0
+ _x = 0.0
+ _y = 0.0
+ _z = 0.0
+ _test1 = 0.0
+ _test2 = 0
+ _test3 = MyGame_Example_Test()
}
-}
-public struct MyGame_Example_Vec3: Readable {
+ public init(_ _t: inout MyGame_Example_Vec3_Mutable) {
+ _x = _t.x
+ _y = _t.y
+ _z = _t.z
+ _test1 = _t.test1
+ _test2 = _t.test2.value
+ var _vtest3 = _t.test3
+ _test3 = _vtest3.unpack()
+ }
- static func validateVersion() { FlatBuffersVersion_1_12_0() }
+ public var x: Float32 { _x }
+ public var y: Float32 { _y }
+ public var z: Float32 { _z }
+ public var test1: Double { _test1 }
+ public var test2: MyGame_Example_Color { MyGame_Example_Color(rawValue: _test2)! }
+ public var test3: MyGame_Example_Test { _test3 }
+
+ public static func verify<T>(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable {
+ try verifier.inBuffer(position: position, of: MyGame_Example_Vec3.self)
+ }
+}
+
+extension MyGame_Example_Vec3: Encodable {
+
+ enum CodingKeys: String, CodingKey {
+ case x = "x"
+ case y = "y"
+ case z = "z"
+ case test1 = "test1"
+ case test2 = "test2"
+ case test3 = "test3"
+ }
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ if x != 0.0 {
+ try container.encodeIfPresent(x, forKey: .x)
+ }
+ if y != 0.0 {
+ try container.encodeIfPresent(y, forKey: .y)
+ }
+ if z != 0.0 {
+ try container.encodeIfPresent(z, forKey: .z)
+ }
+ if test1 != 0.0 {
+ try container.encodeIfPresent(test1, forKey: .test1)
+ }
+ if test2 != .red {
+ try container.encodeIfPresent(test2, forKey: .test2)
+ }
+ try container.encodeIfPresent(test3, forKey: .test3)
+ }
+}
+
+public struct MyGame_Example_Vec3_Mutable: FlatBufferObject {
+
+ static func validateVersion() { FlatBuffersVersion_2_0_0() }
public var __buffer: ByteBuffer! { return _accessor.bb }
private var _accessor: Struct
- public static var size = 32
- public static var alignment = 8
public init(_ bb: ByteBuffer, o: Int32) { _accessor = Struct(bb: bb, position: o) }
public var x: Float32 { return _accessor.readBuffer(of: Float32.self, at: 0) }
@@ -207,59 +428,82 @@
public var test1: Double { return _accessor.readBuffer(of: Double.self, at: 16) }
@discardableResult public func mutate(test1: Double) -> Bool { return _accessor.mutate(test1, index: 16) }
public var test2: MyGame_Example_Color { return MyGame_Example_Color(rawValue: _accessor.readBuffer(of: UInt8.self, at: 24)) ?? .red }
- public var test3: MyGame_Example_Test { return MyGame_Example_Test(_accessor.bb, o: _accessor.postion + 26) }
+ @discardableResult public func mutate(test2: MyGame_Example_Color) -> Bool { return _accessor.mutate(test2.rawValue, index: 24) }
+ public var test3: MyGame_Example_Test_Mutable { return MyGame_Example_Test_Mutable(_accessor.bb, o: _accessor.postion + 26) }
- public mutating func unpack() -> MyGame_Example_Vec3T {
- return MyGame_Example_Vec3T(&self)
+ public mutating func unpack() -> MyGame_Example_Vec3 {
+ return MyGame_Example_Vec3(&self)
}
- public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_Vec3T?) -> Offset<UOffset> {
- guard var obj = obj else { return Offset<UOffset>() }
+ public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_Vec3?) -> Offset {
+ guard var obj = obj else { return Offset() }
return pack(&builder, obj: &obj)
}
- public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_Vec3T) -> Offset<UOffset> {
- return createVec3(builder: &builder, x: obj.x, y: obj.y, z: obj.z, test1: obj.test1, test2: obj.test2, test3a: obj.test3.a, test3b: obj.test3.b)
+ public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_Vec3) -> Offset {
+ return builder.create(struct: obj)
}
}
-public class MyGame_Example_Vec3T: NativeTable {
+public struct MyGame_Example_Ability: NativeStruct, Verifiable, FlatbuffersInitializable, NativeObject {
- public var x: Float32
- public var y: Float32
- public var z: Float32
- public var test1: Double
- public var test2: MyGame_Example_Color
- public var test3: MyGame_Example_TestT
+ static func validateVersion() { FlatBuffersVersion_2_0_0() }
- public init(_ _t: inout MyGame_Example_Vec3) {
- x = _t.x
- y = _t.y
- z = _t.z
- test1 = _t.test1
- test2 = _t.test2
- var __test3 = _t.test3
- test3 = __test3.unpack()
+ private var _id: UInt32
+ private var _distance: UInt32
+
+ public init(_ bb: ByteBuffer, o: Int32) {
+ let _accessor = Struct(bb: bb, position: o)
+ _id = _accessor.readBuffer(of: UInt32.self, at: 0)
+ _distance = _accessor.readBuffer(of: UInt32.self, at: 4)
+ }
+
+ public init(id: UInt32, distance: UInt32) {
+ _id = id
+ _distance = distance
}
public init() {
- x = 0.0
- y = 0.0
- z = 0.0
- test1 = 0.0
- test2 = .red
- test3 = MyGame_Example_TestT()
+ _id = 0
+ _distance = 0
}
-}
-public struct MyGame_Example_Ability: Readable {
+ public init(_ _t: inout MyGame_Example_Ability_Mutable) {
+ _id = _t.id
+ _distance = _t.distance
+ }
- static func validateVersion() { FlatBuffersVersion_1_12_0() }
+ public var id: UInt32 { _id }
+ public var distance: UInt32 { _distance }
+
+ public static func verify<T>(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable {
+ try verifier.inBuffer(position: position, of: MyGame_Example_Ability.self)
+ }
+}
+
+extension MyGame_Example_Ability: Encodable {
+
+ enum CodingKeys: String, CodingKey {
+ case id = "id"
+ case distance = "distance"
+ }
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ if id != 0 {
+ try container.encodeIfPresent(id, forKey: .id)
+ }
+ if distance != 0 {
+ try container.encodeIfPresent(distance, forKey: .distance)
+ }
+ }
+}
+
+public struct MyGame_Example_Ability_Mutable: FlatBufferObject {
+
+ static func validateVersion() { FlatBuffersVersion_2_0_0() }
public var __buffer: ByteBuffer! { return _accessor.bb }
private var _accessor: Struct
- public static var size = 8
- public static var alignment = 4
public init(_ bb: ByteBuffer, o: Int32) { _accessor = Struct(bb: bb, position: o) }
public var id: UInt32 { return _accessor.readBuffer(of: UInt32.self, at: 0) }
@@ -268,104 +512,147 @@
@discardableResult public func mutate(distance: UInt32) -> Bool { return _accessor.mutate(distance, index: 4) }
- public mutating func unpack() -> MyGame_Example_AbilityT {
- return MyGame_Example_AbilityT(&self)
+ public mutating func unpack() -> MyGame_Example_Ability {
+ return MyGame_Example_Ability(&self)
}
- public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_AbilityT?) -> Offset<UOffset> {
- guard var obj = obj else { return Offset<UOffset>() }
+ public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_Ability?) -> Offset {
+ guard var obj = obj else { return Offset() }
return pack(&builder, obj: &obj)
}
- public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_AbilityT) -> Offset<UOffset> {
- return createAbility(builder: &builder, id: obj.id, distance: obj.distance)
+ public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_Ability) -> Offset {
+ return builder.create(struct: obj)
}
}
-public class MyGame_Example_AbilityT: NativeTable {
+public struct MyGame_Example_StructOfStructs: NativeStruct, Verifiable, FlatbuffersInitializable, NativeObject {
- public var id: UInt32
- public var distance: UInt32
+ static func validateVersion() { FlatBuffersVersion_2_0_0() }
- public init(_ _t: inout MyGame_Example_Ability) {
- id = _t.id
- distance = _t.distance
+ private var _a: MyGame_Example_Ability
+ private var _b: MyGame_Example_Test
+ private var _c: MyGame_Example_Ability
+
+ public init(_ bb: ByteBuffer, o: Int32) {
+ let _accessor = Struct(bb: bb, position: o)
+ _a = MyGame_Example_Ability(_accessor.bb, o: _accessor.postion + 0)
+ _b = MyGame_Example_Test(_accessor.bb, o: _accessor.postion + 8)
+ _c = MyGame_Example_Ability(_accessor.bb, o: _accessor.postion + 12)
+ }
+
+ public init(a: MyGame_Example_Ability, b: MyGame_Example_Test, c: MyGame_Example_Ability) {
+ _a = a
+ _b = b
+ _c = c
}
public init() {
- id = 0
- distance = 0
+ _a = MyGame_Example_Ability()
+ _b = MyGame_Example_Test()
+ _c = MyGame_Example_Ability()
}
-}
-extension MyGame_Example_Test {
- @discardableResult
- public static func createTest(builder: inout FlatBufferBuilder, a: Int16 = 0, b: Int8 = 0) -> Offset<UOffset> {
- builder.createStructOf(size: MyGame_Example_Test.size, alignment: MyGame_Example_Test.alignment)
- builder.reverseAdd(v: a, postion: 0)
- builder.reverseAdd(v: b, postion: 2)
- return builder.endStruct()
+ public init(_ _t: inout MyGame_Example_StructOfStructs_Mutable) {
+ var _va = _t.a
+ _a = _va.unpack()
+ var _vb = _t.b
+ _b = _vb.unpack()
+ var _vc = _t.c
+ _c = _vc.unpack()
}
+ public var a: MyGame_Example_Ability { _a }
+ public var b: MyGame_Example_Test { _b }
+ public var c: MyGame_Example_Ability { _c }
+
+ public static func verify<T>(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable {
+ try verifier.inBuffer(position: position, of: MyGame_Example_StructOfStructs.self)
+ }
}
-extension MyGame_Example_Vec3 {
- @discardableResult
- public static func createVec3(builder: inout FlatBufferBuilder, x: Float32 = 0.0, y: Float32 = 0.0, z: Float32 = 0.0, test1: Double = 0.0, test2: MyGame_Example_Color, test3a: Int16 = 0, test3b: Int8 = 0) -> Offset<UOffset> {
- builder.createStructOf(size: MyGame_Example_Vec3.size, alignment: MyGame_Example_Vec3.alignment)
- builder.reverseAdd(v: x, postion: 0)
- builder.reverseAdd(v: y, postion: 4)
- builder.reverseAdd(v: z, postion: 8)
- builder.reverseAdd(v: test1, postion: 16)
- builder.reverseAdd(v: test2.rawValue, postion: 24)
- builder.reverseAdd(v: test3a, postion: 26)
- builder.reverseAdd(v: test3b, postion: 28)
- return builder.endStruct()
+extension MyGame_Example_StructOfStructs: Encodable {
+
+ enum CodingKeys: String, CodingKey {
+ case a = "a"
+ case b = "b"
+ case c = "c"
+ }
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encodeIfPresent(a, forKey: .a)
+ try container.encodeIfPresent(b, forKey: .b)
+ try container.encodeIfPresent(c, forKey: .c)
+ }
+}
+
+public struct MyGame_Example_StructOfStructs_Mutable: FlatBufferObject {
+
+ static func validateVersion() { FlatBuffersVersion_2_0_0() }
+ public var __buffer: ByteBuffer! { return _accessor.bb }
+ private var _accessor: Struct
+
+ public init(_ bb: ByteBuffer, o: Int32) { _accessor = Struct(bb: bb, position: o) }
+
+ public var a: MyGame_Example_Ability_Mutable { return MyGame_Example_Ability_Mutable(_accessor.bb, o: _accessor.postion + 0) }
+ public var b: MyGame_Example_Test_Mutable { return MyGame_Example_Test_Mutable(_accessor.bb, o: _accessor.postion + 8) }
+ public var c: MyGame_Example_Ability_Mutable { return MyGame_Example_Ability_Mutable(_accessor.bb, o: _accessor.postion + 12) }
+
+
+ public mutating func unpack() -> MyGame_Example_StructOfStructs {
+ return MyGame_Example_StructOfStructs(&self)
+ }
+ public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_StructOfStructs?) -> Offset {
+ guard var obj = obj else { return Offset() }
+ return pack(&builder, obj: &obj)
}
-}
-
-extension MyGame_Example_Ability {
- @discardableResult
- public static func createAbility(builder: inout FlatBufferBuilder, id: UInt32 = 0, distance: UInt32 = 0) -> Offset<UOffset> {
- builder.createStructOf(size: MyGame_Example_Ability.size, alignment: MyGame_Example_Ability.alignment)
- builder.reverseAdd(v: id, postion: 0)
- builder.reverseAdd(v: distance, postion: 4)
- return builder.endStruct()
+ public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_StructOfStructs) -> Offset {
+ return builder.create(struct: obj)
}
-
}
-public struct MyGame_InParentNamespace: FlatBufferObject, ObjectAPI {
+public struct MyGame_InParentNamespace: FlatBufferObject, Verifiable, ObjectAPIPacker {
- static func validateVersion() { FlatBuffersVersion_1_12_0() }
+ static func validateVersion() { FlatBuffersVersion_2_0_0() }
public var __buffer: ByteBuffer! { return _accessor.bb }
private var _accessor: Table
- public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset<UOffset>, prefix: Bool = false) { fbb.finish(offset: end, fileId: "MONS", addPrefix: prefix) }
+ public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset, prefix: Bool = false) { fbb.finish(offset: end, fileId: "MONS", addPrefix: prefix) }
public static func getRootAsInParentNamespace(bb: ByteBuffer) -> MyGame_InParentNamespace { return MyGame_InParentNamespace(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) }
private init(_ t: Table) { _accessor = t }
public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) }
public static func startInParentNamespace(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 0) }
- public static func endInParentNamespace(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset<UOffset> { let end = Offset<UOffset>(offset: fbb.endTable(at: start)); return end }
+ public static func endInParentNamespace(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end }
public mutating func unpack() -> MyGame_InParentNamespaceT {
return MyGame_InParentNamespaceT(&self)
}
- public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_InParentNamespaceT?) -> Offset<UOffset> {
- guard var obj = obj else { return Offset<UOffset>() }
+ public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_InParentNamespaceT?) -> Offset {
+ guard var obj = obj else { return Offset() }
return pack(&builder, obj: &obj)
}
- public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_InParentNamespaceT) -> Offset<UOffset> {
+ public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_InParentNamespaceT) -> Offset {
let __root = MyGame_InParentNamespace.startInParentNamespace(&builder)
return MyGame_InParentNamespace.endInParentNamespace(&builder, start: __root)
}
+
+ public static func verify<T>(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable {
+ var _v = try verifier.visitTable(at: position)
+ _v.finish()
+ }
}
-public class MyGame_InParentNamespaceT: NativeTable {
+extension MyGame_InParentNamespace: Encodable {
+
+ public func encode(to encoder: Encoder) throws {
+ }
+}
+
+public class MyGame_InParentNamespaceT: NativeObject {
public init(_ _t: inout MyGame_InParentNamespace) {
@@ -377,37 +664,48 @@
public func serialize() -> ByteBuffer { return serialize(type: MyGame_InParentNamespace.self) }
}
-public struct MyGame_Example2_Monster: FlatBufferObject, ObjectAPI {
+public struct MyGame_Example2_Monster: FlatBufferObject, Verifiable, ObjectAPIPacker {
- static func validateVersion() { FlatBuffersVersion_1_12_0() }
+ static func validateVersion() { FlatBuffersVersion_2_0_0() }
public var __buffer: ByteBuffer! { return _accessor.bb }
private var _accessor: Table
- public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset<UOffset>, prefix: Bool = false) { fbb.finish(offset: end, fileId: "MONS", addPrefix: prefix) }
+ public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset, prefix: Bool = false) { fbb.finish(offset: end, fileId: "MONS", addPrefix: prefix) }
public static func getRootAsMonster(bb: ByteBuffer) -> MyGame_Example2_Monster { return MyGame_Example2_Monster(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) }
private init(_ t: Table) { _accessor = t }
public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) }
public static func startMonster(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 0) }
- public static func endMonster(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset<UOffset> { let end = Offset<UOffset>(offset: fbb.endTable(at: start)); return end }
+ public static func endMonster(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end }
public mutating func unpack() -> MyGame_Example2_MonsterT {
return MyGame_Example2_MonsterT(&self)
}
- public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example2_MonsterT?) -> Offset<UOffset> {
- guard var obj = obj else { return Offset<UOffset>() }
+ public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example2_MonsterT?) -> Offset {
+ guard var obj = obj else { return Offset() }
return pack(&builder, obj: &obj)
}
- public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example2_MonsterT) -> Offset<UOffset> {
+ public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example2_MonsterT) -> Offset {
let __root = MyGame_Example2_Monster.startMonster(&builder)
return MyGame_Example2_Monster.endMonster(&builder, start: __root)
}
+
+ public static func verify<T>(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable {
+ var _v = try verifier.visitTable(at: position)
+ _v.finish()
+ }
}
-public class MyGame_Example2_MonsterT: NativeTable {
+extension MyGame_Example2_Monster: Encodable {
+
+ public func encode(to encoder: Encoder) throws {
+ }
+}
+
+public class MyGame_Example2_MonsterT: NativeObject {
public init(_ _t: inout MyGame_Example2_Monster) {
@@ -419,13 +717,13 @@
public func serialize() -> ByteBuffer { return serialize(type: MyGame_Example2_Monster.self) }
}
-internal struct MyGame_Example_TestSimpleTableWithEnum: FlatBufferObject, ObjectAPI {
+internal struct MyGame_Example_TestSimpleTableWithEnum: FlatBufferObject, Verifiable, ObjectAPIPacker {
- static func validateVersion() { FlatBuffersVersion_1_12_0() }
+ static func validateVersion() { FlatBuffersVersion_2_0_0() }
internal var __buffer: ByteBuffer! { return _accessor.bb }
private var _accessor: Table
- internal static func finish(_ fbb: inout FlatBufferBuilder, end: Offset<UOffset>, prefix: Bool = false) { fbb.finish(offset: end, fileId: "MONS", addPrefix: prefix) }
+ internal static func finish(_ fbb: inout FlatBufferBuilder, end: Offset, prefix: Bool = false) { fbb.finish(offset: end, fileId: "MONS", addPrefix: prefix) }
internal static func getRootAsTestSimpleTableWithEnum(bb: ByteBuffer) -> MyGame_Example_TestSimpleTableWithEnum { return MyGame_Example_TestSimpleTableWithEnum(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) }
private init(_ t: Table) { _accessor = t }
@@ -441,11 +739,11 @@
@discardableResult internal func mutate(color: MyGame_Example_Color) -> Bool {let o = _accessor.offset(VTOFFSET.color.v); return _accessor.mutate(color.rawValue, index: o) }
internal static func startTestSimpleTableWithEnum(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) }
internal static func add(color: MyGame_Example_Color, _ fbb: inout FlatBufferBuilder) { fbb.add(element: color.rawValue, def: 2, at: VTOFFSET.color.p) }
- internal static func endTestSimpleTableWithEnum(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset<UOffset> { let end = Offset<UOffset>(offset: fbb.endTable(at: start)); return end }
+ internal static func endTestSimpleTableWithEnum(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end }
internal static func createTestSimpleTableWithEnum(
_ fbb: inout FlatBufferBuilder,
color: MyGame_Example_Color = .green
- ) -> Offset<UOffset> {
+ ) -> Offset {
let __start = MyGame_Example_TestSimpleTableWithEnum.startTestSimpleTableWithEnum(&fbb)
MyGame_Example_TestSimpleTableWithEnum.add(color: color, &fbb)
return MyGame_Example_TestSimpleTableWithEnum.endTestSimpleTableWithEnum(&fbb, start: __start)
@@ -455,19 +753,38 @@
internal mutating func unpack() -> MyGame_Example_TestSimpleTableWithEnumT {
return MyGame_Example_TestSimpleTableWithEnumT(&self)
}
- internal static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_TestSimpleTableWithEnumT?) -> Offset<UOffset> {
- guard var obj = obj else { return Offset<UOffset>() }
+ internal static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_TestSimpleTableWithEnumT?) -> Offset {
+ guard var obj = obj else { return Offset() }
return pack(&builder, obj: &obj)
}
- internal static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_TestSimpleTableWithEnumT) -> Offset<UOffset> {
+ internal static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_TestSimpleTableWithEnumT) -> Offset {
let __root = MyGame_Example_TestSimpleTableWithEnum.startTestSimpleTableWithEnum(&builder)
MyGame_Example_TestSimpleTableWithEnum.add(color: obj.color, &builder)
return MyGame_Example_TestSimpleTableWithEnum.endTestSimpleTableWithEnum(&builder, start: __root)
}
+
+ public static func verify<T>(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable {
+ var _v = try verifier.visitTable(at: position)
+ try _v.visit(field: VTOFFSET.color.p, fieldName: "color", required: false, type: MyGame_Example_Color.self)
+ _v.finish()
+ }
}
-internal class MyGame_Example_TestSimpleTableWithEnumT: NativeTable {
+extension MyGame_Example_TestSimpleTableWithEnum: Encodable {
+
+ enum CodingKeys: String, CodingKey {
+ case color = "color"
+ }
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ if color != .green {
+ try container.encodeIfPresent(color, forKey: .color)
+ }
+ }
+}
+
+internal class MyGame_Example_TestSimpleTableWithEnumT: NativeObject {
internal var color: MyGame_Example_Color
@@ -482,13 +799,13 @@
internal func serialize() -> ByteBuffer { return serialize(type: MyGame_Example_TestSimpleTableWithEnum.self) }
}
-public struct MyGame_Example_Stat: FlatBufferObject, ObjectAPI {
+public struct MyGame_Example_Stat: FlatBufferObject, Verifiable, ObjectAPIPacker {
- static func validateVersion() { FlatBuffersVersion_1_12_0() }
+ static func validateVersion() { FlatBuffersVersion_2_0_0() }
public var __buffer: ByteBuffer! { return _accessor.bb }
private var _accessor: Table
- public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset<UOffset>, prefix: Bool = false) { fbb.finish(offset: end, fileId: "MONS", addPrefix: prefix) }
+ public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset, prefix: Bool = false) { fbb.finish(offset: end, fileId: "MONS", addPrefix: prefix) }
public static func getRootAsStat(bb: ByteBuffer) -> MyGame_Example_Stat { return MyGame_Example_Stat(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) }
private init(_ t: Table) { _accessor = t }
@@ -509,38 +826,62 @@
public var count: UInt16 { let o = _accessor.offset(VTOFFSET.count.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt16.self, at: o) }
@discardableResult public func mutate(count: UInt16) -> Bool {let o = _accessor.offset(VTOFFSET.count.v); return _accessor.mutate(count, index: o) }
public static func startStat(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 3) }
- public static func add(id: Offset<String>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: id, at: VTOFFSET.id.p) }
+ public static func add(id: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: id, at: VTOFFSET.id.p) }
public static func add(val: Int64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: val, def: 0, at: VTOFFSET.val.p) }
public static func add(count: UInt16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: count, def: 0, at: VTOFFSET.count.p) }
- public static func endStat(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset<UOffset> { let end = Offset<UOffset>(offset: fbb.endTable(at: start)); return end }
+ public static func endStat(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end }
public static func createStat(
_ fbb: inout FlatBufferBuilder,
- offsetOfId id: Offset<String> = Offset(),
+ idOffset id: Offset = Offset(),
val: Int64 = 0,
count: UInt16 = 0
- ) -> Offset<UOffset> {
+ ) -> Offset {
let __start = MyGame_Example_Stat.startStat(&fbb)
MyGame_Example_Stat.add(id: id, &fbb)
MyGame_Example_Stat.add(val: val, &fbb)
MyGame_Example_Stat.add(count: count, &fbb)
return MyGame_Example_Stat.endStat(&fbb, start: __start)
}
+ public static func sortVectorOfStat(offsets:[Offset], _ fbb: inout FlatBufferBuilder) -> Offset {
+ var off = offsets
+ off.sort { Table.compare(Table.offset(Int32($1.o), vOffset: 8, fbb: fbb.buffer), Table.offset(Int32($0.o), vOffset: 8, fbb: fbb.buffer), fbb: fbb.buffer) < 0 }
+ return fbb.createVector(ofOffsets: off)
+ }
+ fileprivate static func lookupByKey(vector: Int32, key: UInt16, fbb: ByteBuffer) -> MyGame_Example_Stat? {
+ var span = fbb.read(def: Int32.self, position: Int(vector - 4))
+ var start: Int32 = 0
+ while span != 0 {
+ var middle = span / 2
+ let tableOffset = Table.indirect(vector + 4 * (start + middle), fbb)
+ let comp = fbb.read(def: UInt16.self, position: Int(Table.offset(Int32(fbb.capacity) - tableOffset, vOffset: 8, fbb: fbb)))
+ if comp > 0 {
+ span = middle
+ } else if comp < 0 {
+ middle += 1
+ start += middle
+ span -= middle
+ } else {
+ return MyGame_Example_Stat(fbb, o: tableOffset)
+ }
+ }
+ return nil
+ }
public mutating func unpack() -> MyGame_Example_StatT {
return MyGame_Example_StatT(&self)
}
- public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_StatT?) -> Offset<UOffset> {
- guard var obj = obj else { return Offset<UOffset>() }
+ public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_StatT?) -> Offset {
+ guard var obj = obj else { return Offset() }
return pack(&builder, obj: &obj)
}
- public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_StatT) -> Offset<UOffset> {
- let __id: Offset<String>
+ public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_StatT) -> Offset {
+ let __id: Offset
if let s = obj.id {
__id = builder.create(string: s)
} else {
- __id = Offset<String>()
+ __id = Offset()
}
let __root = MyGame_Example_Stat.startStat(&builder)
@@ -549,9 +890,36 @@
MyGame_Example_Stat.add(count: obj.count, &builder)
return MyGame_Example_Stat.endStat(&builder, start: __root)
}
+
+ public static func verify<T>(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable {
+ var _v = try verifier.visitTable(at: position)
+ try _v.visit(field: VTOFFSET.id.p, fieldName: "id", required: false, type: ForwardOffset<String>.self)
+ try _v.visit(field: VTOFFSET.val.p, fieldName: "val", required: false, type: Int64.self)
+ try _v.visit(field: VTOFFSET.count.p, fieldName: "count", required: false, type: UInt16.self)
+ _v.finish()
+ }
}
-public class MyGame_Example_StatT: NativeTable {
+extension MyGame_Example_Stat: Encodable {
+
+ enum CodingKeys: String, CodingKey {
+ case id = "id"
+ case val = "val"
+ case count = "count"
+ }
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encodeIfPresent(id, forKey: .id)
+ if val != 0 {
+ try container.encodeIfPresent(val, forKey: .val)
+ }
+ if count != 0 {
+ try container.encodeIfPresent(count, forKey: .count)
+ }
+ }
+}
+
+public class MyGame_Example_StatT: NativeObject {
public var id: String?
public var val: Int64
@@ -571,13 +939,13 @@
public func serialize() -> ByteBuffer { return serialize(type: MyGame_Example_Stat.self) }
}
-public struct MyGame_Example_Referrable: FlatBufferObject, ObjectAPI {
+public struct MyGame_Example_Referrable: FlatBufferObject, Verifiable, ObjectAPIPacker {
- static func validateVersion() { FlatBuffersVersion_1_12_0() }
+ static func validateVersion() { FlatBuffersVersion_2_0_0() }
public var __buffer: ByteBuffer! { return _accessor.bb }
private var _accessor: Table
- public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset<UOffset>, prefix: Bool = false) { fbb.finish(offset: end, fileId: "MONS", addPrefix: prefix) }
+ public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset, prefix: Bool = false) { fbb.finish(offset: end, fileId: "MONS", addPrefix: prefix) }
public static func getRootAsReferrable(bb: ByteBuffer) -> MyGame_Example_Referrable { return MyGame_Example_Referrable(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) }
private init(_ t: Table) { _accessor = t }
@@ -593,16 +961,16 @@
@discardableResult public func mutate(id: UInt64) -> Bool {let o = _accessor.offset(VTOFFSET.id.v); return _accessor.mutate(id, index: o) }
public static func startReferrable(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) }
public static func add(id: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: id, def: 0, at: VTOFFSET.id.p) }
- public static func endReferrable(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset<UOffset> { let end = Offset<UOffset>(offset: fbb.endTable(at: start)); return end }
+ public static func endReferrable(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end }
public static func createReferrable(
_ fbb: inout FlatBufferBuilder,
id: UInt64 = 0
- ) -> Offset<UOffset> {
+ ) -> Offset {
let __start = MyGame_Example_Referrable.startReferrable(&fbb)
MyGame_Example_Referrable.add(id: id, &fbb)
return MyGame_Example_Referrable.endReferrable(&fbb, start: __start)
}
- public static func sortVectorOfReferrable(offsets:[Offset<UOffset>], _ fbb: inout FlatBufferBuilder) -> Offset<UOffset> {
+ public static func sortVectorOfReferrable(offsets:[Offset], _ fbb: inout FlatBufferBuilder) -> Offset {
var off = offsets
off.sort { Table.compare(Table.offset(Int32($1.o), vOffset: 4, fbb: fbb.buffer), Table.offset(Int32($0.o), vOffset: 4, fbb: fbb.buffer), fbb: fbb.buffer) < 0 }
return fbb.createVector(ofOffsets: off)
@@ -631,19 +999,38 @@
public mutating func unpack() -> MyGame_Example_ReferrableT {
return MyGame_Example_ReferrableT(&self)
}
- public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_ReferrableT?) -> Offset<UOffset> {
- guard var obj = obj else { return Offset<UOffset>() }
+ public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_ReferrableT?) -> Offset {
+ guard var obj = obj else { return Offset() }
return pack(&builder, obj: &obj)
}
- public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_ReferrableT) -> Offset<UOffset> {
+ public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_ReferrableT) -> Offset {
let __root = MyGame_Example_Referrable.startReferrable(&builder)
MyGame_Example_Referrable.add(id: obj.id, &builder)
return MyGame_Example_Referrable.endReferrable(&builder, start: __root)
}
+
+ public static func verify<T>(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable {
+ var _v = try verifier.visitTable(at: position)
+ try _v.visit(field: VTOFFSET.id.p, fieldName: "id", required: false, type: UInt64.self)
+ _v.finish()
+ }
}
-public class MyGame_Example_ReferrableT: NativeTable {
+extension MyGame_Example_Referrable: Encodable {
+
+ enum CodingKeys: String, CodingKey {
+ case id = "id"
+ }
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ if id != 0 {
+ try container.encodeIfPresent(id, forKey: .id)
+ }
+ }
+}
+
+public class MyGame_Example_ReferrableT: NativeObject {
public var id: UInt64
@@ -659,13 +1046,13 @@
}
/// an example documentation comment: "monster object"
-public struct MyGame_Example_Monster: FlatBufferObject, ObjectAPI {
+public struct MyGame_Example_Monster: FlatBufferObject, Verifiable, ObjectAPIPacker {
- static func validateVersion() { FlatBuffersVersion_1_12_0() }
+ static func validateVersion() { FlatBuffersVersion_2_0_0() }
public var __buffer: ByteBuffer! { return _accessor.bb }
private var _accessor: Table
- public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset<UOffset>, prefix: Bool = false) { fbb.finish(offset: end, fileId: "MONS", addPrefix: prefix) }
+ public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset, prefix: Bool = false) { fbb.finish(offset: end, fileId: "MONS", addPrefix: prefix) }
public static func getRootAsMonster(bb: ByteBuffer) -> MyGame_Example_Monster { return MyGame_Example_Monster(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) }
private init(_ t: Table) { _accessor = t }
@@ -721,11 +1108,16 @@
case vectorOfEnums = 98
case signedEnum = 100
case testrequirednestedflatbuffer = 102
+ case scalarKeySortedTables = 104
+ case nativeInline = 106
+ case longEnumNonEnumDefault = 108
+ case longEnumNormalDefault = 110
var v: Int32 { Int32(self.rawValue) }
var p: VOffset { self.rawValue }
}
- public var pos: MyGame_Example_Vec3? { let o = _accessor.offset(VTOFFSET.pos.v); return o == 0 ? nil : MyGame_Example_Vec3(_accessor.bb, o: o + _accessor.postion) }
+ public var pos: MyGame_Example_Vec3? { let o = _accessor.offset(VTOFFSET.pos.v); return o == 0 ? nil : _accessor.readBuffer(of: MyGame_Example_Vec3.self, at: o) }
+ public var mutablePos: MyGame_Example_Vec3_Mutable? { let o = _accessor.offset(VTOFFSET.pos.v); return o == 0 ? nil : MyGame_Example_Vec3_Mutable(_accessor.bb, o: o + _accessor.postion) }
public var mana: Int16 { let o = _accessor.offset(VTOFFSET.mana.v); return o == 0 ? 150 : _accessor.readBuffer(of: Int16.self, at: o) }
@discardableResult public func mutate(mana: Int16) -> Bool {let o = _accessor.offset(VTOFFSET.mana.v); return _accessor.mutate(mana, index: o) }
public var hp: Int16 { let o = _accessor.offset(VTOFFSET.hp.v); return o == 0 ? 100 : _accessor.readBuffer(of: Int16.self, at: o) }
@@ -739,9 +1131,10 @@
public var color: MyGame_Example_Color { let o = _accessor.offset(VTOFFSET.color.v); return o == 0 ? .blue : MyGame_Example_Color(rawValue: _accessor.readBuffer(of: UInt8.self, at: o)) ?? .blue }
@discardableResult public func mutate(color: MyGame_Example_Color) -> Bool {let o = _accessor.offset(VTOFFSET.color.v); return _accessor.mutate(color.rawValue, index: o) }
public var testType: MyGame_Example_Any_ { let o = _accessor.offset(VTOFFSET.testType.v); return o == 0 ? .none_ : MyGame_Example_Any_(rawValue: _accessor.readBuffer(of: UInt8.self, at: o)) ?? .none_ }
- public func test<T: FlatBufferObject>(type: T.Type) -> T? { let o = _accessor.offset(VTOFFSET.test.v); return o == 0 ? nil : _accessor.union(o) }
+ public func test<T: FlatbuffersInitializable>(type: T.Type) -> T? { let o = _accessor.offset(VTOFFSET.test.v); return o == 0 ? nil : _accessor.union(o) }
public var test4Count: Int32 { let o = _accessor.offset(VTOFFSET.test4.v); return o == 0 ? 0 : _accessor.vector(count: o) }
- public func test4(at index: Int32) -> MyGame_Example_Test? { let o = _accessor.offset(VTOFFSET.test4.v); return o == 0 ? nil : MyGame_Example_Test(_accessor.bb, o: _accessor.vector(at: o) + index * 4) }
+ public func test4(at index: Int32) -> MyGame_Example_Test? { let o = _accessor.offset(VTOFFSET.test4.v); return o == 0 ? nil : _accessor.directRead(of: MyGame_Example_Test.self, offset: _accessor.vector(at: o) + index * 4) }
+ public func mutableTest4(at index: Int32) -> MyGame_Example_Test_Mutable? { let o = _accessor.offset(VTOFFSET.test4.v); return o == 0 ? nil : MyGame_Example_Test_Mutable(_accessor.bb, o: _accessor.vector(at: o) + index * 4) }
public var testarrayofstringCount: Int32 { let o = _accessor.offset(VTOFFSET.testarrayofstring.v); return o == 0 ? 0 : _accessor.vector(count: o) }
public func testarrayofstring(at index: Int32) -> String? { let o = _accessor.offset(VTOFFSET.testarrayofstring.v); return o == 0 ? nil : _accessor.directString(at: _accessor.vector(at: o) + index * 4) }
/// an example documentation comment: this will end up in the generated code
@@ -774,9 +1167,9 @@
public var testhashu64Fnv1a: UInt64 { let o = _accessor.offset(VTOFFSET.testhashu64Fnv1a.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt64.self, at: o) }
@discardableResult public func mutate(testhashu64Fnv1a: UInt64) -> Bool {let o = _accessor.offset(VTOFFSET.testhashu64Fnv1a.v); return _accessor.mutate(testhashu64Fnv1a, index: o) }
public var testarrayofboolsCount: Int32 { let o = _accessor.offset(VTOFFSET.testarrayofbools.v); return o == 0 ? 0 : _accessor.vector(count: o) }
- public func testarrayofbools(at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.testarrayofbools.v); return o == 0 ? true : 0 != _accessor.directRead(of: Byte.self, offset: _accessor.vector(at: o) + index * 1) }
- public var testarrayofbools: [Byte] { return _accessor.getVector(at: VTOFFSET.testarrayofbools.v) ?? [] }
- public func mutate(testarrayofbools: Byte, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.testarrayofbools.v); return _accessor.directMutate(testarrayofbools, index: _accessor.vector(at: o) + index * 1) }
+ public func testarrayofbools(at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.testarrayofbools.v); return o == 0 ? true : _accessor.directRead(of: Bool.self, offset: _accessor.vector(at: o) + index * 1) }
+ public var testarrayofbools: [Bool] { return _accessor.getVector(at: VTOFFSET.testarrayofbools.v) ?? [] }
+ public func mutate(testarrayofbools: Bool, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.testarrayofbools.v); return _accessor.directMutate(testarrayofbools, index: _accessor.vector(at: o) + index * 1) }
public var testf: Float32 { let o = _accessor.offset(VTOFFSET.testf.v); return o == 0 ? 3.14159 : _accessor.readBuffer(of: Float32.self, at: o) }
@discardableResult public func mutate(testf: Float32) -> Bool {let o = _accessor.offset(VTOFFSET.testf.v); return _accessor.mutate(testf, index: o) }
public var testf2: Float32 { let o = _accessor.offset(VTOFFSET.testf2.v); return o == 0 ? 3.0 : _accessor.readBuffer(of: Float32.self, at: o) }
@@ -786,13 +1179,15 @@
public var testarrayofstring2Count: Int32 { let o = _accessor.offset(VTOFFSET.testarrayofstring2.v); return o == 0 ? 0 : _accessor.vector(count: o) }
public func testarrayofstring2(at index: Int32) -> String? { let o = _accessor.offset(VTOFFSET.testarrayofstring2.v); return o == 0 ? nil : _accessor.directString(at: _accessor.vector(at: o) + index * 4) }
public var testarrayofsortedstructCount: Int32 { let o = _accessor.offset(VTOFFSET.testarrayofsortedstruct.v); return o == 0 ? 0 : _accessor.vector(count: o) }
- public func testarrayofsortedstruct(at index: Int32) -> MyGame_Example_Ability? { let o = _accessor.offset(VTOFFSET.testarrayofsortedstruct.v); return o == 0 ? nil : MyGame_Example_Ability(_accessor.bb, o: _accessor.vector(at: o) + index * 8) }
+ public func testarrayofsortedstruct(at index: Int32) -> MyGame_Example_Ability? { let o = _accessor.offset(VTOFFSET.testarrayofsortedstruct.v); return o == 0 ? nil : _accessor.directRead(of: MyGame_Example_Ability.self, offset: _accessor.vector(at: o) + index * 8) }
+ public func mutableTestarrayofsortedstruct(at index: Int32) -> MyGame_Example_Ability_Mutable? { let o = _accessor.offset(VTOFFSET.testarrayofsortedstruct.v); return o == 0 ? nil : MyGame_Example_Ability_Mutable(_accessor.bb, o: _accessor.vector(at: o) + index * 8) }
public var flexCount: Int32 { let o = _accessor.offset(VTOFFSET.flex.v); return o == 0 ? 0 : _accessor.vector(count: o) }
public func flex(at index: Int32) -> UInt8 { let o = _accessor.offset(VTOFFSET.flex.v); return o == 0 ? 0 : _accessor.directRead(of: UInt8.self, offset: _accessor.vector(at: o) + index * 1) }
public var flex: [UInt8] { return _accessor.getVector(at: VTOFFSET.flex.v) ?? [] }
public func mutate(flex: UInt8, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.flex.v); return _accessor.directMutate(flex, index: _accessor.vector(at: o) + index * 1) }
public var test5Count: Int32 { let o = _accessor.offset(VTOFFSET.test5.v); return o == 0 ? 0 : _accessor.vector(count: o) }
- public func test5(at index: Int32) -> MyGame_Example_Test? { let o = _accessor.offset(VTOFFSET.test5.v); return o == 0 ? nil : MyGame_Example_Test(_accessor.bb, o: _accessor.vector(at: o) + index * 4) }
+ public func test5(at index: Int32) -> MyGame_Example_Test? { let o = _accessor.offset(VTOFFSET.test5.v); return o == 0 ? nil : _accessor.directRead(of: MyGame_Example_Test.self, offset: _accessor.vector(at: o) + index * 4) }
+ public func mutableTest5(at index: Int32) -> MyGame_Example_Test_Mutable? { let o = _accessor.offset(VTOFFSET.test5.v); return o == 0 ? nil : MyGame_Example_Test_Mutable(_accessor.bb, o: _accessor.vector(at: o) + index * 4) }
public var vectorOfLongsCount: Int32 { let o = _accessor.offset(VTOFFSET.vectorOfLongs.v); return o == 0 ? 0 : _accessor.vector(count: o) }
public func vectorOfLongs(at index: Int32) -> Int64 { let o = _accessor.offset(VTOFFSET.vectorOfLongs.v); return o == 0 ? 0 : _accessor.directRead(of: Int64.self, offset: _accessor.vector(at: o) + index * 8) }
public var vectorOfLongs: [Int64] { return _accessor.getVector(at: VTOFFSET.vectorOfLongs.v) ?? [] }
@@ -827,9 +1222,9 @@
public var vectorOfNonOwningReferences: [UInt64] { return _accessor.getVector(at: VTOFFSET.vectorOfNonOwningReferences.v) ?? [] }
public func mutate(vectorOfNonOwningReferences: UInt64, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.vectorOfNonOwningReferences.v); return _accessor.directMutate(vectorOfNonOwningReferences, index: _accessor.vector(at: o) + index * 8) }
public var anyUniqueType: MyGame_Example_AnyUniqueAliases { let o = _accessor.offset(VTOFFSET.anyUniqueType.v); return o == 0 ? .none_ : MyGame_Example_AnyUniqueAliases(rawValue: _accessor.readBuffer(of: UInt8.self, at: o)) ?? .none_ }
- public func anyUnique<T: FlatBufferObject>(type: T.Type) -> T? { let o = _accessor.offset(VTOFFSET.anyUnique.v); return o == 0 ? nil : _accessor.union(o) }
+ public func anyUnique<T: FlatbuffersInitializable>(type: T.Type) -> T? { let o = _accessor.offset(VTOFFSET.anyUnique.v); return o == 0 ? nil : _accessor.union(o) }
public var anyAmbiguousType: MyGame_Example_AnyAmbiguousAliases { let o = _accessor.offset(VTOFFSET.anyAmbiguousType.v); return o == 0 ? .none_ : MyGame_Example_AnyAmbiguousAliases(rawValue: _accessor.readBuffer(of: UInt8.self, at: o)) ?? .none_ }
- public func anyAmbiguous<T: FlatBufferObject>(type: T.Type) -> T? { let o = _accessor.offset(VTOFFSET.anyAmbiguous.v); return o == 0 ? nil : _accessor.union(o) }
+ public func anyAmbiguous<T: FlatbuffersInitializable>(type: T.Type) -> T? { let o = _accessor.offset(VTOFFSET.anyAmbiguous.v); return o == 0 ? nil : _accessor.union(o) }
public var vectorOfEnumsCount: Int32 { let o = _accessor.offset(VTOFFSET.vectorOfEnums.v); return o == 0 ? 0 : _accessor.vector(count: o) }
public func vectorOfEnums(at index: Int32) -> MyGame_Example_Color? { let o = _accessor.offset(VTOFFSET.vectorOfEnums.v); return o == 0 ? MyGame_Example_Color.red : MyGame_Example_Color(rawValue: _accessor.directRead(of: UInt8.self, offset: _accessor.vector(at: o) + index * 1)) }
public var signedEnum: MyGame_Example_Race { let o = _accessor.offset(VTOFFSET.signedEnum.v); return o == 0 ? .none_ : MyGame_Example_Race(rawValue: _accessor.readBuffer(of: Int8.self, at: o)) ?? .none_ }
@@ -838,24 +1233,33 @@
public func testrequirednestedflatbuffer(at index: Int32) -> UInt8 { let o = _accessor.offset(VTOFFSET.testrequirednestedflatbuffer.v); return o == 0 ? 0 : _accessor.directRead(of: UInt8.self, offset: _accessor.vector(at: o) + index * 1) }
public var testrequirednestedflatbuffer: [UInt8] { return _accessor.getVector(at: VTOFFSET.testrequirednestedflatbuffer.v) ?? [] }
public func mutate(testrequirednestedflatbuffer: UInt8, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.testrequirednestedflatbuffer.v); return _accessor.directMutate(testrequirednestedflatbuffer, index: _accessor.vector(at: o) + index * 1) }
- public static func startMonster(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 50) }
- public static func add(pos: Offset<UOffset>?, _ fbb: inout FlatBufferBuilder) { guard pos != nil else { return }; fbb.add(structOffset: VTOFFSET.pos.p) }
+ public var scalarKeySortedTablesCount: Int32 { let o = _accessor.offset(VTOFFSET.scalarKeySortedTables.v); return o == 0 ? 0 : _accessor.vector(count: o) }
+ public func scalarKeySortedTables(at index: Int32) -> MyGame_Example_Stat? { let o = _accessor.offset(VTOFFSET.scalarKeySortedTables.v); return o == 0 ? nil : MyGame_Example_Stat(_accessor.bb, o: _accessor.indirect(_accessor.vector(at: o) + index * 4)) }
+ public func scalarKeySortedTablesBy(key: UInt16) -> MyGame_Example_Stat? { let o = _accessor.offset(VTOFFSET.scalarKeySortedTables.v); return o == 0 ? nil : MyGame_Example_Stat.lookupByKey(vector: _accessor.vector(at: o), key: key, fbb: _accessor.bb) }
+ public var nativeInline: MyGame_Example_Test? { let o = _accessor.offset(VTOFFSET.nativeInline.v); return o == 0 ? nil : _accessor.readBuffer(of: MyGame_Example_Test.self, at: o) }
+ public var mutableNativeInline: MyGame_Example_Test_Mutable? { let o = _accessor.offset(VTOFFSET.nativeInline.v); return o == 0 ? nil : MyGame_Example_Test_Mutable(_accessor.bb, o: o + _accessor.postion) }
+ public var longEnumNonEnumDefault: MyGame_Example_LongEnum { let o = _accessor.offset(VTOFFSET.longEnumNonEnumDefault.v); return o == 0 ? .longone : MyGame_Example_LongEnum(rawValue: _accessor.readBuffer(of: UInt64.self, at: o)) ?? .longone }
+ @discardableResult public func mutate(longEnumNonEnumDefault: MyGame_Example_LongEnum) -> Bool {let o = _accessor.offset(VTOFFSET.longEnumNonEnumDefault.v); return _accessor.mutate(longEnumNonEnumDefault.rawValue, index: o) }
+ public var longEnumNormalDefault: MyGame_Example_LongEnum { let o = _accessor.offset(VTOFFSET.longEnumNormalDefault.v); return o == 0 ? .longone : MyGame_Example_LongEnum(rawValue: _accessor.readBuffer(of: UInt64.self, at: o)) ?? .longone }
+ @discardableResult public func mutate(longEnumNormalDefault: MyGame_Example_LongEnum) -> Bool {let o = _accessor.offset(VTOFFSET.longEnumNormalDefault.v); return _accessor.mutate(longEnumNormalDefault.rawValue, index: o) }
+ public static func startMonster(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 54) }
+ public static func add(pos: MyGame_Example_Vec3?, _ fbb: inout FlatBufferBuilder) { guard let pos = pos else { return }; fbb.create(struct: pos, position: VTOFFSET.pos.p) }
public static func add(mana: Int16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: mana, def: 150, at: VTOFFSET.mana.p) }
public static func add(hp: Int16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: hp, def: 100, at: VTOFFSET.hp.p) }
- public static func add(name: Offset<String>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: name, at: VTOFFSET.name.p) }
- public static func addVectorOf(inventory: Offset<UOffset>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: inventory, at: VTOFFSET.inventory.p) }
+ public static func add(name: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: name, at: VTOFFSET.name.p) }
+ public static func addVectorOf(inventory: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: inventory, at: VTOFFSET.inventory.p) }
public static func add(color: MyGame_Example_Color, _ fbb: inout FlatBufferBuilder) { fbb.add(element: color.rawValue, def: 8, at: VTOFFSET.color.p) }
public static func add(testType: MyGame_Example_Any_, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testType.rawValue, def: 0, at: VTOFFSET.testType.p) }
- public static func add(test: Offset<UOffset>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: test, at: VTOFFSET.test.p) }
- public static func addVectorOf(test4: Offset<UOffset>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: test4, at: VTOFFSET.test4.p) }
+ public static func add(test: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: test, at: VTOFFSET.test.p) }
+ public static func addVectorOf(test4: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: test4, at: VTOFFSET.test4.p) }
public static func startVectorOfTest4(_ size: Int, in builder: inout FlatBufferBuilder) {
- builder.startVectorOfStructs(count: size, size: MyGame_Example_Test.size, alignment: MyGame_Example_Test.alignment)
+ builder.startVector(size * MemoryLayout<MyGame_Example_Test>.size, elementSize: MemoryLayout<MyGame_Example_Test>.alignment)
}
- public static func addVectorOf(testarrayofstring: Offset<UOffset>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testarrayofstring, at: VTOFFSET.testarrayofstring.p) }
- public static func addVectorOf(testarrayoftables: Offset<UOffset>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testarrayoftables, at: VTOFFSET.testarrayoftables.p) }
- public static func add(enemy: Offset<UOffset>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: enemy, at: VTOFFSET.enemy.p) }
- public static func addVectorOf(testnestedflatbuffer: Offset<UOffset>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testnestedflatbuffer, at: VTOFFSET.testnestedflatbuffer.p) }
- public static func add(testempty: Offset<UOffset>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testempty, at: VTOFFSET.testempty.p) }
+ public static func addVectorOf(testarrayofstring: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testarrayofstring, at: VTOFFSET.testarrayofstring.p) }
+ public static func addVectorOf(testarrayoftables: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testarrayoftables, at: VTOFFSET.testarrayoftables.p) }
+ public static func add(enemy: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: enemy, at: VTOFFSET.enemy.p) }
+ public static func addVectorOf(testnestedflatbuffer: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testnestedflatbuffer, at: VTOFFSET.testnestedflatbuffer.p) }
+ public static func add(testempty: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testempty, at: VTOFFSET.testempty.p) }
public static func add(testbool: Bool, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testbool, def: false,
at: VTOFFSET.testbool.p) }
public static func add(testhashs32Fnv1: Int32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashs32Fnv1, def: 0, at: VTOFFSET.testhashs32Fnv1.p) }
@@ -866,40 +1270,156 @@
public static func add(testhashu32Fnv1a: UInt32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashu32Fnv1a, def: 0, at: VTOFFSET.testhashu32Fnv1a.p) }
public static func add(testhashs64Fnv1a: Int64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashs64Fnv1a, def: 0, at: VTOFFSET.testhashs64Fnv1a.p) }
public static func add(testhashu64Fnv1a: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashu64Fnv1a, def: 0, at: VTOFFSET.testhashu64Fnv1a.p) }
- public static func addVectorOf(testarrayofbools: Offset<UOffset>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testarrayofbools, at: VTOFFSET.testarrayofbools.p) }
+ public static func addVectorOf(testarrayofbools: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testarrayofbools, at: VTOFFSET.testarrayofbools.p) }
public static func add(testf: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testf, def: 3.14159, at: VTOFFSET.testf.p) }
public static func add(testf2: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testf2, def: 3.0, at: VTOFFSET.testf2.p) }
public static func add(testf3: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testf3, def: 0.0, at: VTOFFSET.testf3.p) }
- public static func addVectorOf(testarrayofstring2: Offset<UOffset>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testarrayofstring2, at: VTOFFSET.testarrayofstring2.p) }
- public static func addVectorOf(testarrayofsortedstruct: Offset<UOffset>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testarrayofsortedstruct, at: VTOFFSET.testarrayofsortedstruct.p) }
+ public static func addVectorOf(testarrayofstring2: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testarrayofstring2, at: VTOFFSET.testarrayofstring2.p) }
+ public static func addVectorOf(testarrayofsortedstruct: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testarrayofsortedstruct, at: VTOFFSET.testarrayofsortedstruct.p) }
public static func startVectorOfTestarrayofsortedstruct(_ size: Int, in builder: inout FlatBufferBuilder) {
- builder.startVectorOfStructs(count: size, size: MyGame_Example_Ability.size, alignment: MyGame_Example_Ability.alignment)
+ builder.startVector(size * MemoryLayout<MyGame_Example_Ability>.size, elementSize: MemoryLayout<MyGame_Example_Ability>.alignment)
}
- public static func addVectorOf(flex: Offset<UOffset>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: flex, at: VTOFFSET.flex.p) }
- public static func addVectorOf(test5: Offset<UOffset>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: test5, at: VTOFFSET.test5.p) }
+ public static func addVectorOf(flex: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: flex, at: VTOFFSET.flex.p) }
+ public static func addVectorOf(test5: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: test5, at: VTOFFSET.test5.p) }
public static func startVectorOfTest5(_ size: Int, in builder: inout FlatBufferBuilder) {
- builder.startVectorOfStructs(count: size, size: MyGame_Example_Test.size, alignment: MyGame_Example_Test.alignment)
+ builder.startVector(size * MemoryLayout<MyGame_Example_Test>.size, elementSize: MemoryLayout<MyGame_Example_Test>.alignment)
}
- public static func addVectorOf(vectorOfLongs: Offset<UOffset>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfLongs, at: VTOFFSET.vectorOfLongs.p) }
- public static func addVectorOf(vectorOfDoubles: Offset<UOffset>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfDoubles, at: VTOFFSET.vectorOfDoubles.p) }
- public static func add(parentNamespaceTest: Offset<UOffset>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: parentNamespaceTest, at: VTOFFSET.parentNamespaceTest.p) }
- public static func addVectorOf(vectorOfReferrables: Offset<UOffset>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfReferrables, at: VTOFFSET.vectorOfReferrables.p) }
+ public static func addVectorOf(vectorOfLongs: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfLongs, at: VTOFFSET.vectorOfLongs.p) }
+ public static func addVectorOf(vectorOfDoubles: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfDoubles, at: VTOFFSET.vectorOfDoubles.p) }
+ public static func add(parentNamespaceTest: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: parentNamespaceTest, at: VTOFFSET.parentNamespaceTest.p) }
+ public static func addVectorOf(vectorOfReferrables: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfReferrables, at: VTOFFSET.vectorOfReferrables.p) }
public static func add(singleWeakReference: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: singleWeakReference, def: 0, at: VTOFFSET.singleWeakReference.p) }
- public static func addVectorOf(vectorOfWeakReferences: Offset<UOffset>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfWeakReferences, at: VTOFFSET.vectorOfWeakReferences.p) }
- public static func addVectorOf(vectorOfStrongReferrables: Offset<UOffset>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfStrongReferrables, at: VTOFFSET.vectorOfStrongReferrables.p) }
+ public static func addVectorOf(vectorOfWeakReferences: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfWeakReferences, at: VTOFFSET.vectorOfWeakReferences.p) }
+ public static func addVectorOf(vectorOfStrongReferrables: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfStrongReferrables, at: VTOFFSET.vectorOfStrongReferrables.p) }
public static func add(coOwningReference: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: coOwningReference, def: 0, at: VTOFFSET.coOwningReference.p) }
- public static func addVectorOf(vectorOfCoOwningReferences: Offset<UOffset>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfCoOwningReferences, at: VTOFFSET.vectorOfCoOwningReferences.p) }
+ public static func addVectorOf(vectorOfCoOwningReferences: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfCoOwningReferences, at: VTOFFSET.vectorOfCoOwningReferences.p) }
public static func add(nonOwningReference: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: nonOwningReference, def: 0, at: VTOFFSET.nonOwningReference.p) }
- public static func addVectorOf(vectorOfNonOwningReferences: Offset<UOffset>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfNonOwningReferences, at: VTOFFSET.vectorOfNonOwningReferences.p) }
+ public static func addVectorOf(vectorOfNonOwningReferences: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfNonOwningReferences, at: VTOFFSET.vectorOfNonOwningReferences.p) }
public static func add(anyUniqueType: MyGame_Example_AnyUniqueAliases, _ fbb: inout FlatBufferBuilder) { fbb.add(element: anyUniqueType.rawValue, def: 0, at: VTOFFSET.anyUniqueType.p) }
- public static func add(anyUnique: Offset<UOffset>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: anyUnique, at: VTOFFSET.anyUnique.p) }
+ public static func add(anyUnique: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: anyUnique, at: VTOFFSET.anyUnique.p) }
public static func add(anyAmbiguousType: MyGame_Example_AnyAmbiguousAliases, _ fbb: inout FlatBufferBuilder) { fbb.add(element: anyAmbiguousType.rawValue, def: 0, at: VTOFFSET.anyAmbiguousType.p) }
- public static func add(anyAmbiguous: Offset<UOffset>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: anyAmbiguous, at: VTOFFSET.anyAmbiguous.p) }
- public static func addVectorOf(vectorOfEnums: Offset<UOffset>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfEnums, at: VTOFFSET.vectorOfEnums.p) }
+ public static func add(anyAmbiguous: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: anyAmbiguous, at: VTOFFSET.anyAmbiguous.p) }
+ public static func addVectorOf(vectorOfEnums: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfEnums, at: VTOFFSET.vectorOfEnums.p) }
public static func add(signedEnum: MyGame_Example_Race, _ fbb: inout FlatBufferBuilder) { fbb.add(element: signedEnum.rawValue, def: -1, at: VTOFFSET.signedEnum.p) }
- public static func addVectorOf(testrequirednestedflatbuffer: Offset<UOffset>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testrequirednestedflatbuffer, at: VTOFFSET.testrequirednestedflatbuffer.p) }
- public static func endMonster(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset<UOffset> { let end = Offset<UOffset>(offset: fbb.endTable(at: start)); fbb.require(table: end, fields: [10]); return end }
- public static func sortVectorOfMonster(offsets:[Offset<UOffset>], _ fbb: inout FlatBufferBuilder) -> Offset<UOffset> {
+ public static func addVectorOf(testrequirednestedflatbuffer: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testrequirednestedflatbuffer, at: VTOFFSET.testrequirednestedflatbuffer.p) }
+ public static func addVectorOf(scalarKeySortedTables: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: scalarKeySortedTables, at: VTOFFSET.scalarKeySortedTables.p) }
+ public static func add(nativeInline: MyGame_Example_Test?, _ fbb: inout FlatBufferBuilder) { guard let nativeInline = nativeInline else { return }; fbb.create(struct: nativeInline, position: VTOFFSET.nativeInline.p) }
+ public static func add(longEnumNonEnumDefault: MyGame_Example_LongEnum, _ fbb: inout FlatBufferBuilder) { fbb.add(element: longEnumNonEnumDefault.rawValue, def: 0, at: VTOFFSET.longEnumNonEnumDefault.p) }
+ public static func add(longEnumNormalDefault: MyGame_Example_LongEnum, _ fbb: inout FlatBufferBuilder) { fbb.add(element: longEnumNormalDefault.rawValue, def: 2, at: VTOFFSET.longEnumNormalDefault.p) }
+ public static func endMonster(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); fbb.require(table: end, fields: [10]); return end }
+ public static func createMonster(
+ _ fbb: inout FlatBufferBuilder,
+ pos: MyGame_Example_Vec3? = nil,
+ mana: Int16 = 150,
+ hp: Int16 = 100,
+ nameOffset name: Offset = Offset(),
+ inventoryVectorOffset inventory: Offset = Offset(),
+ color: MyGame_Example_Color = .blue,
+ testType: MyGame_Example_Any_ = .none_,
+ testOffset test: Offset = Offset(),
+ test4VectorOffset test4: Offset = Offset(),
+ testarrayofstringVectorOffset testarrayofstring: Offset = Offset(),
+ testarrayoftablesVectorOffset testarrayoftables: Offset = Offset(),
+ enemyOffset enemy: Offset = Offset(),
+ testnestedflatbufferVectorOffset testnestedflatbuffer: Offset = Offset(),
+ testemptyOffset testempty: Offset = Offset(),
+ testbool: Bool = false,
+ testhashs32Fnv1: Int32 = 0,
+ testhashu32Fnv1: UInt32 = 0,
+ testhashs64Fnv1: Int64 = 0,
+ testhashu64Fnv1: UInt64 = 0,
+ testhashs32Fnv1a: Int32 = 0,
+ testhashu32Fnv1a: UInt32 = 0,
+ testhashs64Fnv1a: Int64 = 0,
+ testhashu64Fnv1a: UInt64 = 0,
+ testarrayofboolsVectorOffset testarrayofbools: Offset = Offset(),
+ testf: Float32 = 3.14159,
+ testf2: Float32 = 3.0,
+ testf3: Float32 = 0.0,
+ testarrayofstring2VectorOffset testarrayofstring2: Offset = Offset(),
+ testarrayofsortedstructVectorOffset testarrayofsortedstruct: Offset = Offset(),
+ flexVectorOffset flex: Offset = Offset(),
+ test5VectorOffset test5: Offset = Offset(),
+ vectorOfLongsVectorOffset vectorOfLongs: Offset = Offset(),
+ vectorOfDoublesVectorOffset vectorOfDoubles: Offset = Offset(),
+ parentNamespaceTestOffset parentNamespaceTest: Offset = Offset(),
+ vectorOfReferrablesVectorOffset vectorOfReferrables: Offset = Offset(),
+ singleWeakReference: UInt64 = 0,
+ vectorOfWeakReferencesVectorOffset vectorOfWeakReferences: Offset = Offset(),
+ vectorOfStrongReferrablesVectorOffset vectorOfStrongReferrables: Offset = Offset(),
+ coOwningReference: UInt64 = 0,
+ vectorOfCoOwningReferencesVectorOffset vectorOfCoOwningReferences: Offset = Offset(),
+ nonOwningReference: UInt64 = 0,
+ vectorOfNonOwningReferencesVectorOffset vectorOfNonOwningReferences: Offset = Offset(),
+ anyUniqueType: MyGame_Example_AnyUniqueAliases = .none_,
+ anyUniqueOffset anyUnique: Offset = Offset(),
+ anyAmbiguousType: MyGame_Example_AnyAmbiguousAliases = .none_,
+ anyAmbiguousOffset anyAmbiguous: Offset = Offset(),
+ vectorOfEnumsVectorOffset vectorOfEnums: Offset = Offset(),
+ signedEnum: MyGame_Example_Race = .none_,
+ testrequirednestedflatbufferVectorOffset testrequirednestedflatbuffer: Offset = Offset(),
+ scalarKeySortedTablesVectorOffset scalarKeySortedTables: Offset = Offset(),
+ nativeInline: MyGame_Example_Test? = nil,
+ longEnumNonEnumDefault: MyGame_Example_LongEnum = .longone,
+ longEnumNormalDefault: MyGame_Example_LongEnum = .longone
+ ) -> Offset {
+ let __start = MyGame_Example_Monster.startMonster(&fbb)
+ MyGame_Example_Monster.add(pos: pos, &fbb)
+ MyGame_Example_Monster.add(mana: mana, &fbb)
+ MyGame_Example_Monster.add(hp: hp, &fbb)
+ MyGame_Example_Monster.add(name: name, &fbb)
+ MyGame_Example_Monster.addVectorOf(inventory: inventory, &fbb)
+ MyGame_Example_Monster.add(color: color, &fbb)
+ MyGame_Example_Monster.add(testType: testType, &fbb)
+ MyGame_Example_Monster.add(test: test, &fbb)
+ MyGame_Example_Monster.addVectorOf(test4: test4, &fbb)
+ MyGame_Example_Monster.addVectorOf(testarrayofstring: testarrayofstring, &fbb)
+ MyGame_Example_Monster.addVectorOf(testarrayoftables: testarrayoftables, &fbb)
+ MyGame_Example_Monster.add(enemy: enemy, &fbb)
+ MyGame_Example_Monster.addVectorOf(testnestedflatbuffer: testnestedflatbuffer, &fbb)
+ MyGame_Example_Monster.add(testempty: testempty, &fbb)
+ MyGame_Example_Monster.add(testbool: testbool, &fbb)
+ MyGame_Example_Monster.add(testhashs32Fnv1: testhashs32Fnv1, &fbb)
+ MyGame_Example_Monster.add(testhashu32Fnv1: testhashu32Fnv1, &fbb)
+ MyGame_Example_Monster.add(testhashs64Fnv1: testhashs64Fnv1, &fbb)
+ MyGame_Example_Monster.add(testhashu64Fnv1: testhashu64Fnv1, &fbb)
+ MyGame_Example_Monster.add(testhashs32Fnv1a: testhashs32Fnv1a, &fbb)
+ MyGame_Example_Monster.add(testhashu32Fnv1a: testhashu32Fnv1a, &fbb)
+ MyGame_Example_Monster.add(testhashs64Fnv1a: testhashs64Fnv1a, &fbb)
+ MyGame_Example_Monster.add(testhashu64Fnv1a: testhashu64Fnv1a, &fbb)
+ MyGame_Example_Monster.addVectorOf(testarrayofbools: testarrayofbools, &fbb)
+ MyGame_Example_Monster.add(testf: testf, &fbb)
+ MyGame_Example_Monster.add(testf2: testf2, &fbb)
+ MyGame_Example_Monster.add(testf3: testf3, &fbb)
+ MyGame_Example_Monster.addVectorOf(testarrayofstring2: testarrayofstring2, &fbb)
+ MyGame_Example_Monster.addVectorOf(testarrayofsortedstruct: testarrayofsortedstruct, &fbb)
+ MyGame_Example_Monster.addVectorOf(flex: flex, &fbb)
+ MyGame_Example_Monster.addVectorOf(test5: test5, &fbb)
+ MyGame_Example_Monster.addVectorOf(vectorOfLongs: vectorOfLongs, &fbb)
+ MyGame_Example_Monster.addVectorOf(vectorOfDoubles: vectorOfDoubles, &fbb)
+ MyGame_Example_Monster.add(parentNamespaceTest: parentNamespaceTest, &fbb)
+ MyGame_Example_Monster.addVectorOf(vectorOfReferrables: vectorOfReferrables, &fbb)
+ MyGame_Example_Monster.add(singleWeakReference: singleWeakReference, &fbb)
+ MyGame_Example_Monster.addVectorOf(vectorOfWeakReferences: vectorOfWeakReferences, &fbb)
+ MyGame_Example_Monster.addVectorOf(vectorOfStrongReferrables: vectorOfStrongReferrables, &fbb)
+ MyGame_Example_Monster.add(coOwningReference: coOwningReference, &fbb)
+ MyGame_Example_Monster.addVectorOf(vectorOfCoOwningReferences: vectorOfCoOwningReferences, &fbb)
+ MyGame_Example_Monster.add(nonOwningReference: nonOwningReference, &fbb)
+ MyGame_Example_Monster.addVectorOf(vectorOfNonOwningReferences: vectorOfNonOwningReferences, &fbb)
+ MyGame_Example_Monster.add(anyUniqueType: anyUniqueType, &fbb)
+ MyGame_Example_Monster.add(anyUnique: anyUnique, &fbb)
+ MyGame_Example_Monster.add(anyAmbiguousType: anyAmbiguousType, &fbb)
+ MyGame_Example_Monster.add(anyAmbiguous: anyAmbiguous, &fbb)
+ MyGame_Example_Monster.addVectorOf(vectorOfEnums: vectorOfEnums, &fbb)
+ MyGame_Example_Monster.add(signedEnum: signedEnum, &fbb)
+ MyGame_Example_Monster.addVectorOf(testrequirednestedflatbuffer: testrequirednestedflatbuffer, &fbb)
+ MyGame_Example_Monster.addVectorOf(scalarKeySortedTables: scalarKeySortedTables, &fbb)
+ MyGame_Example_Monster.add(nativeInline: nativeInline, &fbb)
+ MyGame_Example_Monster.add(longEnumNonEnumDefault: longEnumNonEnumDefault, &fbb)
+ MyGame_Example_Monster.add(longEnumNormalDefault: longEnumNormalDefault, &fbb)
+ return MyGame_Example_Monster.endMonster(&fbb, start: __start)
+ }
+ public static func sortVectorOfMonster(offsets:[Offset], _ fbb: inout FlatBufferBuilder) -> Offset {
var off = offsets
off.sort { Table.compare(Table.offset(Int32($1.o), vOffset: 10, fbb: fbb.buffer), Table.offset(Int32($0.o), vOffset: 10, fbb: fbb.buffer), fbb: fbb.buffer) < 0 }
return fbb.createVector(ofOffsets: off)
@@ -929,23 +1449,23 @@
public mutating func unpack() -> MyGame_Example_MonsterT {
return MyGame_Example_MonsterT(&self)
}
- public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_MonsterT?) -> Offset<UOffset> {
- guard var obj = obj else { return Offset<UOffset>() }
+ public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_MonsterT?) -> Offset {
+ guard var obj = obj else { return Offset() }
return pack(&builder, obj: &obj)
}
- public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_MonsterT) -> Offset<UOffset> {
+ public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_MonsterT) -> Offset {
let __name = builder.create(string: obj.name)
let __inventory = builder.createVector(obj.inventory)
let __test = obj.test?.pack(builder: &builder) ?? Offset()
MyGame_Example_Monster.startVectorOfTest4(obj.test4.count, in: &builder)
for i in obj.test4 {
guard let _o = i else { continue }
- MyGame_Example_Test.createTest(builder: &builder, a: _o.a, b: _o.b)
+ builder.create(struct: _o)
}
- let __test4 = builder.endVectorOfStructs(count: obj.test4.count)
+ let __test4 = builder.endVector(len: obj.test4.count)
let __testarrayofstring = builder.createVector(ofStrings: obj.testarrayofstring.compactMap({ $0 }) )
- var __testarrayoftables__: [Offset<UOffset>] = []
+ var __testarrayoftables__: [Offset] = []
for var i in obj.testarrayoftables {
__testarrayoftables__.append(MyGame_Example_Monster.pack(&builder, obj: &i))
}
@@ -958,26 +1478,26 @@
MyGame_Example_Monster.startVectorOfTestarrayofsortedstruct(obj.testarrayofsortedstruct.count, in: &builder)
for i in obj.testarrayofsortedstruct {
guard let _o = i else { continue }
- MyGame_Example_Ability.createAbility(builder: &builder, id: _o.id, distance: _o.distance)
+ builder.create(struct: _o)
}
- let __testarrayofsortedstruct = builder.endVectorOfStructs(count: obj.testarrayofsortedstruct.count)
+ let __testarrayofsortedstruct = builder.endVector(len: obj.testarrayofsortedstruct.count)
let __flex = builder.createVector(obj.flex)
MyGame_Example_Monster.startVectorOfTest5(obj.test5.count, in: &builder)
for i in obj.test5 {
guard let _o = i else { continue }
- MyGame_Example_Test.createTest(builder: &builder, a: _o.a, b: _o.b)
+ builder.create(struct: _o)
}
- let __test5 = builder.endVectorOfStructs(count: obj.test5.count)
+ let __test5 = builder.endVector(len: obj.test5.count)
let __vectorOfLongs = builder.createVector(obj.vectorOfLongs)
let __vectorOfDoubles = builder.createVector(obj.vectorOfDoubles)
let __parentNamespaceTest = MyGame_InParentNamespace.pack(&builder, obj: &obj.parentNamespaceTest)
- var __vectorOfReferrables__: [Offset<UOffset>] = []
+ var __vectorOfReferrables__: [Offset] = []
for var i in obj.vectorOfReferrables {
__vectorOfReferrables__.append(MyGame_Example_Referrable.pack(&builder, obj: &i))
}
let __vectorOfReferrables = builder.createVector(ofOffsets: __vectorOfReferrables__)
let __vectorOfWeakReferences = builder.createVector(obj.vectorOfWeakReferences)
- var __vectorOfStrongReferrables__: [Offset<UOffset>] = []
+ var __vectorOfStrongReferrables__: [Offset] = []
for var i in obj.vectorOfStrongReferrables {
__vectorOfStrongReferrables__.append(MyGame_Example_Referrable.pack(&builder, obj: &i))
}
@@ -988,8 +1508,13 @@
let __anyAmbiguous = obj.anyAmbiguous?.pack(builder: &builder) ?? Offset()
let __vectorOfEnums = builder.createVector(obj.vectorOfEnums)
let __testrequirednestedflatbuffer = builder.createVector(obj.testrequirednestedflatbuffer)
+ var __scalarKeySortedTables__: [Offset] = []
+ for var i in obj.scalarKeySortedTables {
+ __scalarKeySortedTables__.append(MyGame_Example_Stat.pack(&builder, obj: &i))
+ }
+ let __scalarKeySortedTables = builder.createVector(ofOffsets: __scalarKeySortedTables__)
let __root = MyGame_Example_Monster.startMonster(&builder)
- MyGame_Example_Monster.add(pos: obj.pos.map { MyGame_Example_Vec3.createVec3(builder: &builder, x: $0.x, y: $0.y, z: $0.z, test1: $0.test1, test2: $0.test2, test3a: $0.test3.a, test3b: $0.test3.b) }, &builder)
+ MyGame_Example_Monster.add(pos: obj.pos, &builder)
MyGame_Example_Monster.add(mana: obj.mana, &builder)
MyGame_Example_Monster.add(hp: obj.hp, &builder)
MyGame_Example_Monster.add(name: __name, &builder)
@@ -1047,20 +1572,388 @@
MyGame_Example_Monster.addVectorOf(vectorOfEnums: __vectorOfEnums, &builder)
MyGame_Example_Monster.add(signedEnum: obj.signedEnum, &builder)
MyGame_Example_Monster.addVectorOf(testrequirednestedflatbuffer: __testrequirednestedflatbuffer, &builder)
+ MyGame_Example_Monster.addVectorOf(scalarKeySortedTables: __scalarKeySortedTables, &builder)
+ MyGame_Example_Monster.add(nativeInline: obj.nativeInline, &builder)
+ MyGame_Example_Monster.add(longEnumNonEnumDefault: obj.longEnumNonEnumDefault, &builder)
+ MyGame_Example_Monster.add(longEnumNormalDefault: obj.longEnumNormalDefault, &builder)
return MyGame_Example_Monster.endMonster(&builder, start: __root)
}
+
+ public static func verify<T>(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable {
+ var _v = try verifier.visitTable(at: position)
+ try _v.visit(field: VTOFFSET.pos.p, fieldName: "pos", required: false, type: MyGame_Example_Vec3.self)
+ try _v.visit(field: VTOFFSET.mana.p, fieldName: "mana", required: false, type: Int16.self)
+ try _v.visit(field: VTOFFSET.hp.p, fieldName: "hp", required: false, type: Int16.self)
+ try _v.visit(field: VTOFFSET.name.p, fieldName: "name", required: true, type: ForwardOffset<String>.self)
+ try _v.visit(field: VTOFFSET.inventory.p, fieldName: "inventory", required: false, type: ForwardOffset<Vector<UInt8, UInt8>>.self)
+ try _v.visit(field: VTOFFSET.color.p, fieldName: "color", required: false, type: MyGame_Example_Color.self)
+ try _v.visit(unionKey: VTOFFSET.testType.p, unionField: VTOFFSET.test.p, unionKeyName: "testType", fieldName: "test", required: false, completion: { (verifier, key: MyGame_Example_Any_, pos) in
+ switch key {
+ case .none_:
+ break // NOTE - SWIFT doesnt support none
+ case .monster:
+ try ForwardOffset<MyGame_Example_Monster>.verify(&verifier, at: pos, of: MyGame_Example_Monster.self)
+ case .testsimpletablewithenum:
+ try ForwardOffset<MyGame_Example_TestSimpleTableWithEnum>.verify(&verifier, at: pos, of: MyGame_Example_TestSimpleTableWithEnum.self)
+ case .mygameExample2Monster:
+ try ForwardOffset<MyGame_Example2_Monster>.verify(&verifier, at: pos, of: MyGame_Example2_Monster.self)
+ }
+ })
+ try _v.visit(field: VTOFFSET.test4.p, fieldName: "test4", required: false, type: ForwardOffset<Vector<MyGame_Example_Test, MyGame_Example_Test>>.self)
+ try _v.visit(field: VTOFFSET.testarrayofstring.p, fieldName: "testarrayofstring", required: false, type: ForwardOffset<Vector<ForwardOffset<String>, String>>.self)
+ try _v.visit(field: VTOFFSET.testarrayoftables.p, fieldName: "testarrayoftables", required: false, type: ForwardOffset<Vector<ForwardOffset<MyGame_Example_Monster>, MyGame_Example_Monster>>.self)
+ try _v.visit(field: VTOFFSET.enemy.p, fieldName: "enemy", required: false, type: ForwardOffset<MyGame_Example_Monster>.self)
+ try _v.visit(field: VTOFFSET.testnestedflatbuffer.p, fieldName: "testnestedflatbuffer", required: false, type: ForwardOffset<Vector<UInt8, UInt8>>.self)
+ try _v.visit(field: VTOFFSET.testempty.p, fieldName: "testempty", required: false, type: ForwardOffset<MyGame_Example_Stat>.self)
+ try _v.visit(field: VTOFFSET.testbool.p, fieldName: "testbool", required: false, type: Bool.self)
+ try _v.visit(field: VTOFFSET.testhashs32Fnv1.p, fieldName: "testhashs32Fnv1", required: false, type: Int32.self)
+ try _v.visit(field: VTOFFSET.testhashu32Fnv1.p, fieldName: "testhashu32Fnv1", required: false, type: UInt32.self)
+ try _v.visit(field: VTOFFSET.testhashs64Fnv1.p, fieldName: "testhashs64Fnv1", required: false, type: Int64.self)
+ try _v.visit(field: VTOFFSET.testhashu64Fnv1.p, fieldName: "testhashu64Fnv1", required: false, type: UInt64.self)
+ try _v.visit(field: VTOFFSET.testhashs32Fnv1a.p, fieldName: "testhashs32Fnv1a", required: false, type: Int32.self)
+ try _v.visit(field: VTOFFSET.testhashu32Fnv1a.p, fieldName: "testhashu32Fnv1a", required: false, type: UInt32.self)
+ try _v.visit(field: VTOFFSET.testhashs64Fnv1a.p, fieldName: "testhashs64Fnv1a", required: false, type: Int64.self)
+ try _v.visit(field: VTOFFSET.testhashu64Fnv1a.p, fieldName: "testhashu64Fnv1a", required: false, type: UInt64.self)
+ try _v.visit(field: VTOFFSET.testarrayofbools.p, fieldName: "testarrayofbools", required: false, type: ForwardOffset<Vector<Bool, Bool>>.self)
+ try _v.visit(field: VTOFFSET.testf.p, fieldName: "testf", required: false, type: Float32.self)
+ try _v.visit(field: VTOFFSET.testf2.p, fieldName: "testf2", required: false, type: Float32.self)
+ try _v.visit(field: VTOFFSET.testf3.p, fieldName: "testf3", required: false, type: Float32.self)
+ try _v.visit(field: VTOFFSET.testarrayofstring2.p, fieldName: "testarrayofstring2", required: false, type: ForwardOffset<Vector<ForwardOffset<String>, String>>.self)
+ try _v.visit(field: VTOFFSET.testarrayofsortedstruct.p, fieldName: "testarrayofsortedstruct", required: false, type: ForwardOffset<Vector<MyGame_Example_Ability, MyGame_Example_Ability>>.self)
+ try _v.visit(field: VTOFFSET.flex.p, fieldName: "flex", required: false, type: ForwardOffset<Vector<UInt8, UInt8>>.self)
+ try _v.visit(field: VTOFFSET.test5.p, fieldName: "test5", required: false, type: ForwardOffset<Vector<MyGame_Example_Test, MyGame_Example_Test>>.self)
+ try _v.visit(field: VTOFFSET.vectorOfLongs.p, fieldName: "vectorOfLongs", required: false, type: ForwardOffset<Vector<Int64, Int64>>.self)
+ try _v.visit(field: VTOFFSET.vectorOfDoubles.p, fieldName: "vectorOfDoubles", required: false, type: ForwardOffset<Vector<Double, Double>>.self)
+ try _v.visit(field: VTOFFSET.parentNamespaceTest.p, fieldName: "parentNamespaceTest", required: false, type: ForwardOffset<MyGame_InParentNamespace>.self)
+ try _v.visit(field: VTOFFSET.vectorOfReferrables.p, fieldName: "vectorOfReferrables", required: false, type: ForwardOffset<Vector<ForwardOffset<MyGame_Example_Referrable>, MyGame_Example_Referrable>>.self)
+ try _v.visit(field: VTOFFSET.singleWeakReference.p, fieldName: "singleWeakReference", required: false, type: UInt64.self)
+ try _v.visit(field: VTOFFSET.vectorOfWeakReferences.p, fieldName: "vectorOfWeakReferences", required: false, type: ForwardOffset<Vector<UInt64, UInt64>>.self)
+ try _v.visit(field: VTOFFSET.vectorOfStrongReferrables.p, fieldName: "vectorOfStrongReferrables", required: false, type: ForwardOffset<Vector<ForwardOffset<MyGame_Example_Referrable>, MyGame_Example_Referrable>>.self)
+ try _v.visit(field: VTOFFSET.coOwningReference.p, fieldName: "coOwningReference", required: false, type: UInt64.self)
+ try _v.visit(field: VTOFFSET.vectorOfCoOwningReferences.p, fieldName: "vectorOfCoOwningReferences", required: false, type: ForwardOffset<Vector<UInt64, UInt64>>.self)
+ try _v.visit(field: VTOFFSET.nonOwningReference.p, fieldName: "nonOwningReference", required: false, type: UInt64.self)
+ try _v.visit(field: VTOFFSET.vectorOfNonOwningReferences.p, fieldName: "vectorOfNonOwningReferences", required: false, type: ForwardOffset<Vector<UInt64, UInt64>>.self)
+ try _v.visit(unionKey: VTOFFSET.anyUniqueType.p, unionField: VTOFFSET.anyUnique.p, unionKeyName: "anyUniqueType", fieldName: "anyUnique", required: false, completion: { (verifier, key: MyGame_Example_AnyUniqueAliases, pos) in
+ switch key {
+ case .none_:
+ break // NOTE - SWIFT doesnt support none
+ case .m:
+ try ForwardOffset<MyGame_Example_Monster>.verify(&verifier, at: pos, of: MyGame_Example_Monster.self)
+ case .ts:
+ try ForwardOffset<MyGame_Example_TestSimpleTableWithEnum>.verify(&verifier, at: pos, of: MyGame_Example_TestSimpleTableWithEnum.self)
+ case .m2:
+ try ForwardOffset<MyGame_Example2_Monster>.verify(&verifier, at: pos, of: MyGame_Example2_Monster.self)
+ }
+ })
+ try _v.visit(unionKey: VTOFFSET.anyAmbiguousType.p, unionField: VTOFFSET.anyAmbiguous.p, unionKeyName: "anyAmbiguousType", fieldName: "anyAmbiguous", required: false, completion: { (verifier, key: MyGame_Example_AnyAmbiguousAliases, pos) in
+ switch key {
+ case .none_:
+ break // NOTE - SWIFT doesnt support none
+ case .m1:
+ try ForwardOffset<MyGame_Example_Monster>.verify(&verifier, at: pos, of: MyGame_Example_Monster.self)
+ case .m2:
+ try ForwardOffset<MyGame_Example_Monster>.verify(&verifier, at: pos, of: MyGame_Example_Monster.self)
+ case .m3:
+ try ForwardOffset<MyGame_Example_Monster>.verify(&verifier, at: pos, of: MyGame_Example_Monster.self)
+ }
+ })
+ try _v.visit(field: VTOFFSET.vectorOfEnums.p, fieldName: "vectorOfEnums", required: false, type: ForwardOffset<Vector<MyGame_Example_Color, MyGame_Example_Color>>.self)
+ try _v.visit(field: VTOFFSET.signedEnum.p, fieldName: "signedEnum", required: false, type: MyGame_Example_Race.self)
+ try _v.visit(field: VTOFFSET.testrequirednestedflatbuffer.p, fieldName: "testrequirednestedflatbuffer", required: false, type: ForwardOffset<Vector<UInt8, UInt8>>.self)
+ try _v.visit(field: VTOFFSET.scalarKeySortedTables.p, fieldName: "scalarKeySortedTables", required: false, type: ForwardOffset<Vector<ForwardOffset<MyGame_Example_Stat>, MyGame_Example_Stat>>.self)
+ try _v.visit(field: VTOFFSET.nativeInline.p, fieldName: "nativeInline", required: false, type: MyGame_Example_Test.self)
+ try _v.visit(field: VTOFFSET.longEnumNonEnumDefault.p, fieldName: "longEnumNonEnumDefault", required: false, type: MyGame_Example_LongEnum.self)
+ try _v.visit(field: VTOFFSET.longEnumNormalDefault.p, fieldName: "longEnumNormalDefault", required: false, type: MyGame_Example_LongEnum.self)
+ _v.finish()
+ }
}
-public class MyGame_Example_MonsterT: NativeTable {
+extension MyGame_Example_Monster: Encodable {
- public var pos: MyGame_Example_Vec3T?
+ enum CodingKeys: String, CodingKey {
+ case pos = "pos"
+ case mana = "mana"
+ case hp = "hp"
+ case name = "name"
+ case inventory = "inventory"
+ case color = "color"
+ case testType = "test_type"
+ case test = "test"
+ case test4 = "test4"
+ case testarrayofstring = "testarrayofstring"
+ case testarrayoftables = "testarrayoftables"
+ case enemy = "enemy"
+ case testnestedflatbuffer = "testnestedflatbuffer"
+ case testempty = "testempty"
+ case testbool = "testbool"
+ case testhashs32Fnv1 = "testhashs32_fnv1"
+ case testhashu32Fnv1 = "testhashu32_fnv1"
+ case testhashs64Fnv1 = "testhashs64_fnv1"
+ case testhashu64Fnv1 = "testhashu64_fnv1"
+ case testhashs32Fnv1a = "testhashs32_fnv1a"
+ case testhashu32Fnv1a = "testhashu32_fnv1a"
+ case testhashs64Fnv1a = "testhashs64_fnv1a"
+ case testhashu64Fnv1a = "testhashu64_fnv1a"
+ case testarrayofbools = "testarrayofbools"
+ case testf = "testf"
+ case testf2 = "testf2"
+ case testf3 = "testf3"
+ case testarrayofstring2 = "testarrayofstring2"
+ case testarrayofsortedstruct = "testarrayofsortedstruct"
+ case flex = "flex"
+ case test5 = "test5"
+ case vectorOfLongs = "vector_of_longs"
+ case vectorOfDoubles = "vector_of_doubles"
+ case parentNamespaceTest = "parent_namespace_test"
+ case vectorOfReferrables = "vector_of_referrables"
+ case singleWeakReference = "single_weak_reference"
+ case vectorOfWeakReferences = "vector_of_weak_references"
+ case vectorOfStrongReferrables = "vector_of_strong_referrables"
+ case coOwningReference = "co_owning_reference"
+ case vectorOfCoOwningReferences = "vector_of_co_owning_references"
+ case nonOwningReference = "non_owning_reference"
+ case vectorOfNonOwningReferences = "vector_of_non_owning_references"
+ case anyUniqueType = "any_unique_type"
+ case anyUnique = "any_unique"
+ case anyAmbiguousType = "any_ambiguous_type"
+ case anyAmbiguous = "any_ambiguous"
+ case vectorOfEnums = "vector_of_enums"
+ case signedEnum = "signed_enum"
+ case testrequirednestedflatbuffer = "testrequirednestedflatbuffer"
+ case scalarKeySortedTables = "scalar_key_sorted_tables"
+ case nativeInline = "native_inline"
+ case longEnumNonEnumDefault = "long_enum_non_enum_default"
+ case longEnumNormalDefault = "long_enum_normal_default"
+ }
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encodeIfPresent(pos, forKey: .pos)
+ if mana != 150 {
+ try container.encodeIfPresent(mana, forKey: .mana)
+ }
+ if hp != 100 {
+ try container.encodeIfPresent(hp, forKey: .hp)
+ }
+ try container.encodeIfPresent(name, forKey: .name)
+ if inventoryCount > 0 {
+ try container.encodeIfPresent(inventory, forKey: .inventory)
+ }
+ if color != .blue {
+ try container.encodeIfPresent(color, forKey: .color)
+ }
+ if testType != .none_ {
+ try container.encodeIfPresent(testType, forKey: .testType)
+ }
+ switch testType {
+ case .monster:
+ let _v = test(type: MyGame_Example_Monster.self)
+ try container.encodeIfPresent(_v, forKey: .test)
+ case .testsimpletablewithenum:
+ let _v = test(type: MyGame_Example_TestSimpleTableWithEnum.self)
+ try container.encodeIfPresent(_v, forKey: .test)
+ case .mygameExample2Monster:
+ let _v = test(type: MyGame_Example2_Monster.self)
+ try container.encodeIfPresent(_v, forKey: .test)
+ default: break;
+ }
+ if test4Count > 0 {
+ var contentEncoder = container.nestedUnkeyedContainer(forKey: .test4)
+ for index in 0..<test4Count {
+ guard let type = test4(at: index) else { continue }
+ try contentEncoder.encode(type)
+ }
+ }
+ if testarrayofstringCount > 0 {
+ var contentEncoder = container.nestedUnkeyedContainer(forKey: .testarrayofstring)
+ for index in 0..<testarrayofstringCount {
+ guard let type = testarrayofstring(at: index) else { continue }
+ try contentEncoder.encode(type)
+ }
+ }
+ if testarrayoftablesCount > 0 {
+ var contentEncoder = container.nestedUnkeyedContainer(forKey: .testarrayoftables)
+ for index in 0..<testarrayoftablesCount {
+ guard let type = testarrayoftables(at: index) else { continue }
+ try contentEncoder.encode(type)
+ }
+ }
+ try container.encodeIfPresent(enemy, forKey: .enemy)
+ if testnestedflatbufferCount > 0 {
+ try container.encodeIfPresent(testnestedflatbuffer, forKey: .testnestedflatbuffer)
+ }
+ try container.encodeIfPresent(testempty, forKey: .testempty)
+ if testbool != false {
+ try container.encodeIfPresent(testbool, forKey: .testbool)
+ }
+ if testhashs32Fnv1 != 0 {
+ try container.encodeIfPresent(testhashs32Fnv1, forKey: .testhashs32Fnv1)
+ }
+ if testhashu32Fnv1 != 0 {
+ try container.encodeIfPresent(testhashu32Fnv1, forKey: .testhashu32Fnv1)
+ }
+ if testhashs64Fnv1 != 0 {
+ try container.encodeIfPresent(testhashs64Fnv1, forKey: .testhashs64Fnv1)
+ }
+ if testhashu64Fnv1 != 0 {
+ try container.encodeIfPresent(testhashu64Fnv1, forKey: .testhashu64Fnv1)
+ }
+ if testhashs32Fnv1a != 0 {
+ try container.encodeIfPresent(testhashs32Fnv1a, forKey: .testhashs32Fnv1a)
+ }
+ if testhashu32Fnv1a != 0 {
+ try container.encodeIfPresent(testhashu32Fnv1a, forKey: .testhashu32Fnv1a)
+ }
+ if testhashs64Fnv1a != 0 {
+ try container.encodeIfPresent(testhashs64Fnv1a, forKey: .testhashs64Fnv1a)
+ }
+ if testhashu64Fnv1a != 0 {
+ try container.encodeIfPresent(testhashu64Fnv1a, forKey: .testhashu64Fnv1a)
+ }
+ if testarrayofboolsCount > 0 {
+ try container.encodeIfPresent(testarrayofbools, forKey: .testarrayofbools)
+ }
+ if testf != 3.14159 {
+ try container.encodeIfPresent(testf, forKey: .testf)
+ }
+ if testf2 != 3.0 {
+ try container.encodeIfPresent(testf2, forKey: .testf2)
+ }
+ if testf3 != 0.0 {
+ try container.encodeIfPresent(testf3, forKey: .testf3)
+ }
+ if testarrayofstring2Count > 0 {
+ var contentEncoder = container.nestedUnkeyedContainer(forKey: .testarrayofstring2)
+ for index in 0..<testarrayofstring2Count {
+ guard let type = testarrayofstring2(at: index) else { continue }
+ try contentEncoder.encode(type)
+ }
+ }
+ if testarrayofsortedstructCount > 0 {
+ var contentEncoder = container.nestedUnkeyedContainer(forKey: .testarrayofsortedstruct)
+ for index in 0..<testarrayofsortedstructCount {
+ guard let type = testarrayofsortedstruct(at: index) else { continue }
+ try contentEncoder.encode(type)
+ }
+ }
+ if flexCount > 0 {
+ try container.encodeIfPresent(flex, forKey: .flex)
+ }
+ if test5Count > 0 {
+ var contentEncoder = container.nestedUnkeyedContainer(forKey: .test5)
+ for index in 0..<test5Count {
+ guard let type = test5(at: index) else { continue }
+ try contentEncoder.encode(type)
+ }
+ }
+ if vectorOfLongsCount > 0 {
+ try container.encodeIfPresent(vectorOfLongs, forKey: .vectorOfLongs)
+ }
+ if vectorOfDoublesCount > 0 {
+ try container.encodeIfPresent(vectorOfDoubles, forKey: .vectorOfDoubles)
+ }
+ try container.encodeIfPresent(parentNamespaceTest, forKey: .parentNamespaceTest)
+ if vectorOfReferrablesCount > 0 {
+ var contentEncoder = container.nestedUnkeyedContainer(forKey: .vectorOfReferrables)
+ for index in 0..<vectorOfReferrablesCount {
+ guard let type = vectorOfReferrables(at: index) else { continue }
+ try contentEncoder.encode(type)
+ }
+ }
+ if singleWeakReference != 0 {
+ try container.encodeIfPresent(singleWeakReference, forKey: .singleWeakReference)
+ }
+ if vectorOfWeakReferencesCount > 0 {
+ try container.encodeIfPresent(vectorOfWeakReferences, forKey: .vectorOfWeakReferences)
+ }
+ if vectorOfStrongReferrablesCount > 0 {
+ var contentEncoder = container.nestedUnkeyedContainer(forKey: .vectorOfStrongReferrables)
+ for index in 0..<vectorOfStrongReferrablesCount {
+ guard let type = vectorOfStrongReferrables(at: index) else { continue }
+ try contentEncoder.encode(type)
+ }
+ }
+ if coOwningReference != 0 {
+ try container.encodeIfPresent(coOwningReference, forKey: .coOwningReference)
+ }
+ if vectorOfCoOwningReferencesCount > 0 {
+ try container.encodeIfPresent(vectorOfCoOwningReferences, forKey: .vectorOfCoOwningReferences)
+ }
+ if nonOwningReference != 0 {
+ try container.encodeIfPresent(nonOwningReference, forKey: .nonOwningReference)
+ }
+ if vectorOfNonOwningReferencesCount > 0 {
+ try container.encodeIfPresent(vectorOfNonOwningReferences, forKey: .vectorOfNonOwningReferences)
+ }
+ if anyUniqueType != .none_ {
+ try container.encodeIfPresent(anyUniqueType, forKey: .anyUniqueType)
+ }
+ switch anyUniqueType {
+ case .m:
+ let _v = anyUnique(type: MyGame_Example_Monster.self)
+ try container.encodeIfPresent(_v, forKey: .anyUnique)
+ case .ts:
+ let _v = anyUnique(type: MyGame_Example_TestSimpleTableWithEnum.self)
+ try container.encodeIfPresent(_v, forKey: .anyUnique)
+ case .m2:
+ let _v = anyUnique(type: MyGame_Example2_Monster.self)
+ try container.encodeIfPresent(_v, forKey: .anyUnique)
+ default: break;
+ }
+ if anyAmbiguousType != .none_ {
+ try container.encodeIfPresent(anyAmbiguousType, forKey: .anyAmbiguousType)
+ }
+ switch anyAmbiguousType {
+ case .m1:
+ let _v = anyAmbiguous(type: MyGame_Example_Monster.self)
+ try container.encodeIfPresent(_v, forKey: .anyAmbiguous)
+ case .m2:
+ let _v = anyAmbiguous(type: MyGame_Example_Monster.self)
+ try container.encodeIfPresent(_v, forKey: .anyAmbiguous)
+ case .m3:
+ let _v = anyAmbiguous(type: MyGame_Example_Monster.self)
+ try container.encodeIfPresent(_v, forKey: .anyAmbiguous)
+ default: break;
+ }
+ if vectorOfEnumsCount > 0 {
+ var contentEncoder = container.nestedUnkeyedContainer(forKey: .vectorOfEnums)
+ for index in 0..<vectorOfEnumsCount {
+ guard let type = vectorOfEnums(at: index) else { continue }
+ try contentEncoder.encode(type)
+ }
+ }
+ if signedEnum != .none_ {
+ try container.encodeIfPresent(signedEnum, forKey: .signedEnum)
+ }
+ if testrequirednestedflatbufferCount > 0 {
+ try container.encodeIfPresent(testrequirednestedflatbuffer, forKey: .testrequirednestedflatbuffer)
+ }
+ if scalarKeySortedTablesCount > 0 {
+ var contentEncoder = container.nestedUnkeyedContainer(forKey: .scalarKeySortedTables)
+ for index in 0..<scalarKeySortedTablesCount {
+ guard let type = scalarKeySortedTables(at: index) else { continue }
+ try contentEncoder.encode(type)
+ }
+ }
+ try container.encodeIfPresent(nativeInline, forKey: .nativeInline)
+ if longEnumNonEnumDefault != .longone {
+ try container.encodeIfPresent(longEnumNonEnumDefault, forKey: .longEnumNonEnumDefault)
+ }
+ if longEnumNormalDefault != .longone {
+ try container.encodeIfPresent(longEnumNormalDefault, forKey: .longEnumNormalDefault)
+ }
+ }
+}
+
+public class MyGame_Example_MonsterT: NativeObject {
+
+ public var pos: MyGame_Example_Vec3?
public var mana: Int16
public var hp: Int16
public var name: String
public var inventory: [UInt8]
public var color: MyGame_Example_Color
public var test: MyGame_Example_Any_Union?
- public var test4: [MyGame_Example_TestT?]
+ public var test4: [MyGame_Example_Test?]
public var testarrayofstring: [String?]
public var testarrayoftables: [MyGame_Example_MonsterT?]
public var enemy: MyGame_Example_MonsterT?
@@ -1080,9 +1973,9 @@
public var testf2: Float32
public var testf3: Float32
public var testarrayofstring2: [String?]
- public var testarrayofsortedstruct: [MyGame_Example_AbilityT?]
+ public var testarrayofsortedstruct: [MyGame_Example_Ability?]
public var flex: [UInt8]
- public var test5: [MyGame_Example_TestT?]
+ public var test5: [MyGame_Example_Test?]
public var vectorOfLongs: [Int64]
public var vectorOfDoubles: [Double]
public var parentNamespaceTest: MyGame_InParentNamespaceT?
@@ -1099,10 +1992,13 @@
public var vectorOfEnums: [MyGame_Example_Color]
public var signedEnum: MyGame_Example_Race
public var testrequirednestedflatbuffer: [UInt8]
+ public var scalarKeySortedTables: [MyGame_Example_StatT?]
+ public var nativeInline: MyGame_Example_Test?
+ public var longEnumNonEnumDefault: MyGame_Example_LongEnum
+ public var longEnumNormalDefault: MyGame_Example_LongEnum
public init(_ _t: inout MyGame_Example_Monster) {
- var __pos = _t.pos
- pos = __pos?.unpack()
+ pos = _t.pos
mana = _t.mana
hp = _t.hp
name = _t.name
@@ -1113,20 +2009,19 @@
color = _t.color
switch _t.testType {
case .monster:
- var _v = _t.test(type: MyGame_Example_Monster.self)
- test = MyGame_Example_Any_Union(_v?.unpack(), type: .monster)
+ var _v = _t.test(type: MyGame_Example_Monster.self)
+ test = MyGame_Example_Any_Union(_v?.unpack(), type: .monster)
case .testsimpletablewithenum:
- var _v = _t.test(type: MyGame_Example_TestSimpleTableWithEnum.self)
- test = MyGame_Example_Any_Union(_v?.unpack(), type: .testsimpletablewithenum)
+ var _v = _t.test(type: MyGame_Example_TestSimpleTableWithEnum.self)
+ test = MyGame_Example_Any_Union(_v?.unpack(), type: .testsimpletablewithenum)
case .mygameExample2Monster:
- var _v = _t.test(type: MyGame_Example2_Monster.self)
- test = MyGame_Example_Any_Union(_v?.unpack(), type: .mygameExample2Monster)
+ var _v = _t.test(type: MyGame_Example2_Monster.self)
+ test = MyGame_Example_Any_Union(_v?.unpack(), type: .mygameExample2Monster)
default: break
}
test4 = []
for index in 0..<_t.test4Count {
- var __v_ = _t.test4(at: index)
- test4.append(__v_?.unpack())
+ test4.append(_t.test4(at: index))
}
testarrayofstring = []
for index in 0..<_t.testarrayofstringCount {
@@ -1167,8 +2062,7 @@
}
testarrayofsortedstruct = []
for index in 0..<_t.testarrayofsortedstructCount {
- var __v_ = _t.testarrayofsortedstruct(at: index)
- testarrayofsortedstruct.append(__v_?.unpack())
+ testarrayofsortedstruct.append(_t.testarrayofsortedstruct(at: index))
}
flex = []
for index in 0..<_t.flexCount {
@@ -1176,8 +2070,7 @@
}
test5 = []
for index in 0..<_t.test5Count {
- var __v_ = _t.test5(at: index)
- test5.append(__v_?.unpack())
+ test5.append(_t.test5(at: index))
}
vectorOfLongs = []
for index in 0..<_t.vectorOfLongsCount {
@@ -1216,26 +2109,26 @@
}
switch _t.anyUniqueType {
case .m:
- var _v = _t.anyUnique(type: MyGame_Example_Monster.self)
- anyUnique = MyGame_Example_AnyUniqueAliasesUnion(_v?.unpack(), type: .m)
+ var _v = _t.anyUnique(type: MyGame_Example_Monster.self)
+ anyUnique = MyGame_Example_AnyUniqueAliasesUnion(_v?.unpack(), type: .m)
case .ts:
- var _v = _t.anyUnique(type: MyGame_Example_TestSimpleTableWithEnum.self)
- anyUnique = MyGame_Example_AnyUniqueAliasesUnion(_v?.unpack(), type: .ts)
+ var _v = _t.anyUnique(type: MyGame_Example_TestSimpleTableWithEnum.self)
+ anyUnique = MyGame_Example_AnyUniqueAliasesUnion(_v?.unpack(), type: .ts)
case .m2:
- var _v = _t.anyUnique(type: MyGame_Example2_Monster.self)
- anyUnique = MyGame_Example_AnyUniqueAliasesUnion(_v?.unpack(), type: .m2)
+ var _v = _t.anyUnique(type: MyGame_Example2_Monster.self)
+ anyUnique = MyGame_Example_AnyUniqueAliasesUnion(_v?.unpack(), type: .m2)
default: break
}
switch _t.anyAmbiguousType {
case .m1:
- var _v = _t.anyAmbiguous(type: MyGame_Example_Monster.self)
- anyAmbiguous = MyGame_Example_AnyAmbiguousAliasesUnion(_v?.unpack(), type: .m1)
+ var _v = _t.anyAmbiguous(type: MyGame_Example_Monster.self)
+ anyAmbiguous = MyGame_Example_AnyAmbiguousAliasesUnion(_v?.unpack(), type: .m1)
case .m2:
- var _v = _t.anyAmbiguous(type: MyGame_Example_Monster.self)
- anyAmbiguous = MyGame_Example_AnyAmbiguousAliasesUnion(_v?.unpack(), type: .m2)
+ var _v = _t.anyAmbiguous(type: MyGame_Example_Monster.self)
+ anyAmbiguous = MyGame_Example_AnyAmbiguousAliasesUnion(_v?.unpack(), type: .m2)
case .m3:
- var _v = _t.anyAmbiguous(type: MyGame_Example_Monster.self)
- anyAmbiguous = MyGame_Example_AnyAmbiguousAliasesUnion(_v?.unpack(), type: .m3)
+ var _v = _t.anyAmbiguous(type: MyGame_Example_Monster.self)
+ anyAmbiguous = MyGame_Example_AnyAmbiguousAliasesUnion(_v?.unpack(), type: .m3)
default: break
}
vectorOfEnums = []
@@ -1247,10 +2140,18 @@
for index in 0..<_t.testrequirednestedflatbufferCount {
testrequirednestedflatbuffer.append(_t.testrequirednestedflatbuffer(at: index))
}
+ scalarKeySortedTables = []
+ for index in 0..<_t.scalarKeySortedTablesCount {
+ var __v_ = _t.scalarKeySortedTables(at: index)
+ scalarKeySortedTables.append(__v_?.unpack())
+ }
+ nativeInline = _t.nativeInline
+ longEnumNonEnumDefault = _t.longEnumNonEnumDefault
+ longEnumNormalDefault = _t.longEnumNormalDefault
}
public init() {
- pos = MyGame_Example_Vec3T()
+ pos = MyGame_Example_Vec3()
mana = 150
hp = 100
name = ""
@@ -1293,18 +2194,22 @@
vectorOfEnums = []
signedEnum = .none_
testrequirednestedflatbuffer = []
+ scalarKeySortedTables = []
+ nativeInline = MyGame_Example_Test()
+ longEnumNonEnumDefault = .longone
+ longEnumNormalDefault = .longone
}
public func serialize() -> ByteBuffer { return serialize(type: MyGame_Example_Monster.self) }
}
-public struct MyGame_Example_TypeAliases: FlatBufferObject, ObjectAPI {
+public struct MyGame_Example_TypeAliases: FlatBufferObject, Verifiable, ObjectAPIPacker {
- static func validateVersion() { FlatBuffersVersion_1_12_0() }
+ static func validateVersion() { FlatBuffersVersion_2_0_0() }
public var __buffer: ByteBuffer! { return _accessor.bb }
private var _accessor: Table
- public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset<UOffset>, prefix: Bool = false) { fbb.finish(offset: end, fileId: "MONS", addPrefix: prefix) }
+ public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset, prefix: Bool = false) { fbb.finish(offset: end, fileId: "MONS", addPrefix: prefix) }
public static func getRootAsTypeAliases(bb: ByteBuffer) -> MyGame_Example_TypeAliases { return MyGame_Example_TypeAliases(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) }
private init(_ t: Table) { _accessor = t }
@@ -1366,9 +2271,9 @@
public static func add(u64: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: u64, def: 0, at: VTOFFSET.u64.p) }
public static func add(f32: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: f32, def: 0.0, at: VTOFFSET.f32.p) }
public static func add(f64: Double, _ fbb: inout FlatBufferBuilder) { fbb.add(element: f64, def: 0.0, at: VTOFFSET.f64.p) }
- public static func addVectorOf(v8: Offset<UOffset>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: v8, at: VTOFFSET.v8.p) }
- public static func addVectorOf(vf64: Offset<UOffset>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vf64, at: VTOFFSET.vf64.p) }
- public static func endTypeAliases(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset<UOffset> { let end = Offset<UOffset>(offset: fbb.endTable(at: start)); return end }
+ public static func addVectorOf(v8: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: v8, at: VTOFFSET.v8.p) }
+ public static func addVectorOf(vf64: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vf64, at: VTOFFSET.vf64.p) }
+ public static func endTypeAliases(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end }
public static func createTypeAliases(
_ fbb: inout FlatBufferBuilder,
i8: Int8 = 0,
@@ -1381,9 +2286,9 @@
u64: UInt64 = 0,
f32: Float32 = 0.0,
f64: Double = 0.0,
- vectorOfV8 v8: Offset<UOffset> = Offset(),
- vectorOfVf64 vf64: Offset<UOffset> = Offset()
- ) -> Offset<UOffset> {
+ v8VectorOffset v8: Offset = Offset(),
+ vf64VectorOffset vf64: Offset = Offset()
+ ) -> Offset {
let __start = MyGame_Example_TypeAliases.startTypeAliases(&fbb)
MyGame_Example_TypeAliases.add(i8: i8, &fbb)
MyGame_Example_TypeAliases.add(u8: u8, &fbb)
@@ -1404,12 +2309,12 @@
public mutating func unpack() -> MyGame_Example_TypeAliasesT {
return MyGame_Example_TypeAliasesT(&self)
}
- public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_TypeAliasesT?) -> Offset<UOffset> {
- guard var obj = obj else { return Offset<UOffset>() }
+ public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_TypeAliasesT?) -> Offset {
+ guard var obj = obj else { return Offset() }
return pack(&builder, obj: &obj)
}
- public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_TypeAliasesT) -> Offset<UOffset> {
+ public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_TypeAliasesT) -> Offset {
let __v8 = builder.createVector(obj.v8)
let __vf64 = builder.createVector(obj.vf64)
let __root = MyGame_Example_TypeAliases.startTypeAliases(&builder)
@@ -1427,9 +2332,83 @@
MyGame_Example_TypeAliases.addVectorOf(vf64: __vf64, &builder)
return MyGame_Example_TypeAliases.endTypeAliases(&builder, start: __root)
}
+
+ public static func verify<T>(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable {
+ var _v = try verifier.visitTable(at: position)
+ try _v.visit(field: VTOFFSET.i8.p, fieldName: "i8", required: false, type: Int8.self)
+ try _v.visit(field: VTOFFSET.u8.p, fieldName: "u8", required: false, type: UInt8.self)
+ try _v.visit(field: VTOFFSET.i16.p, fieldName: "i16", required: false, type: Int16.self)
+ try _v.visit(field: VTOFFSET.u16.p, fieldName: "u16", required: false, type: UInt16.self)
+ try _v.visit(field: VTOFFSET.i32.p, fieldName: "i32", required: false, type: Int32.self)
+ try _v.visit(field: VTOFFSET.u32.p, fieldName: "u32", required: false, type: UInt32.self)
+ try _v.visit(field: VTOFFSET.i64.p, fieldName: "i64", required: false, type: Int64.self)
+ try _v.visit(field: VTOFFSET.u64.p, fieldName: "u64", required: false, type: UInt64.self)
+ try _v.visit(field: VTOFFSET.f32.p, fieldName: "f32", required: false, type: Float32.self)
+ try _v.visit(field: VTOFFSET.f64.p, fieldName: "f64", required: false, type: Double.self)
+ try _v.visit(field: VTOFFSET.v8.p, fieldName: "v8", required: false, type: ForwardOffset<Vector<Int8, Int8>>.self)
+ try _v.visit(field: VTOFFSET.vf64.p, fieldName: "vf64", required: false, type: ForwardOffset<Vector<Double, Double>>.self)
+ _v.finish()
+ }
}
-public class MyGame_Example_TypeAliasesT: NativeTable {
+extension MyGame_Example_TypeAliases: Encodable {
+
+ enum CodingKeys: String, CodingKey {
+ case i8 = "i8"
+ case u8 = "u8"
+ case i16 = "i16"
+ case u16 = "u16"
+ case i32 = "i32"
+ case u32 = "u32"
+ case i64 = "i64"
+ case u64 = "u64"
+ case f32 = "f32"
+ case f64 = "f64"
+ case v8 = "v8"
+ case vf64 = "vf64"
+ }
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ if i8 != 0 {
+ try container.encodeIfPresent(i8, forKey: .i8)
+ }
+ if u8 != 0 {
+ try container.encodeIfPresent(u8, forKey: .u8)
+ }
+ if i16 != 0 {
+ try container.encodeIfPresent(i16, forKey: .i16)
+ }
+ if u16 != 0 {
+ try container.encodeIfPresent(u16, forKey: .u16)
+ }
+ if i32 != 0 {
+ try container.encodeIfPresent(i32, forKey: .i32)
+ }
+ if u32 != 0 {
+ try container.encodeIfPresent(u32, forKey: .u32)
+ }
+ if i64 != 0 {
+ try container.encodeIfPresent(i64, forKey: .i64)
+ }
+ if u64 != 0 {
+ try container.encodeIfPresent(u64, forKey: .u64)
+ }
+ if f32 != 0.0 {
+ try container.encodeIfPresent(f32, forKey: .f32)
+ }
+ if f64 != 0.0 {
+ try container.encodeIfPresent(f64, forKey: .f64)
+ }
+ if v8Count > 0 {
+ try container.encodeIfPresent(v8, forKey: .v8)
+ }
+ if vf64Count > 0 {
+ try container.encodeIfPresent(vf64, forKey: .vf64)
+ }
+ }
+}
+
+public class MyGame_Example_TypeAliasesT: NativeObject {
public var i8: Int8
public var u8: UInt8
diff --git a/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/more_defaults_generated.swift b/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/more_defaults_generated.swift
new file mode 100644
index 0000000..3ebaa2a
--- /dev/null
+++ b/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/more_defaults_generated.swift
@@ -0,0 +1,218 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+// swiftlint:disable all
+// swiftformat:disable all
+
+import FlatBuffers
+
+public enum ABC: Int32, Enum, Verifiable {
+ public typealias T = Int32
+ public static var byteSize: Int { return MemoryLayout<Int32>.size }
+ public var value: Int32 { return self.rawValue }
+ case a = 0
+ case b = 1
+ case c = 2
+
+ public static var max: ABC { return .c }
+ public static var min: ABC { return .a }
+}
+
+extension ABC: Encodable {
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.singleValueContainer()
+ switch self {
+ case .a: try container.encode("A")
+ case .b: try container.encode("B")
+ case .c: try container.encode("C")
+ }
+ }
+}
+
+public struct MoreDefaults: FlatBufferObject, Verifiable, ObjectAPIPacker {
+
+ static func validateVersion() { FlatBuffersVersion_2_0_0() }
+ public var __buffer: ByteBuffer! { return _accessor.bb }
+ private var _accessor: Table
+
+ public static func getRootAsMoreDefaults(bb: ByteBuffer) -> MoreDefaults { return MoreDefaults(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) }
+
+ private init(_ t: Table) { _accessor = t }
+ public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) }
+
+ private enum VTOFFSET: VOffset {
+ case ints = 4
+ case floats = 6
+ case emptyString = 8
+ case someString = 10
+ case abcs = 12
+ case bools = 14
+ var v: Int32 { Int32(self.rawValue) }
+ var p: VOffset { self.rawValue }
+ }
+
+ public var intsCount: Int32 { let o = _accessor.offset(VTOFFSET.ints.v); return o == 0 ? 0 : _accessor.vector(count: o) }
+ public func ints(at index: Int32) -> Int32 { let o = _accessor.offset(VTOFFSET.ints.v); return o == 0 ? 0 : _accessor.directRead(of: Int32.self, offset: _accessor.vector(at: o) + index * 4) }
+ public var ints: [Int32] { return _accessor.getVector(at: VTOFFSET.ints.v) ?? [] }
+ public var floatsCount: Int32 { let o = _accessor.offset(VTOFFSET.floats.v); return o == 0 ? 0 : _accessor.vector(count: o) }
+ public func floats(at index: Int32) -> Float32 { let o = _accessor.offset(VTOFFSET.floats.v); return o == 0 ? 0 : _accessor.directRead(of: Float32.self, offset: _accessor.vector(at: o) + index * 4) }
+ public var floats: [Float32] { return _accessor.getVector(at: VTOFFSET.floats.v) ?? [] }
+ public var emptyString: String? { let o = _accessor.offset(VTOFFSET.emptyString.v); return o == 0 ? "" : _accessor.string(at: o) }
+ public var emptyStringSegmentArray: [UInt8]? { return _accessor.getVector(at: VTOFFSET.emptyString.v) }
+ public var someString: String? { let o = _accessor.offset(VTOFFSET.someString.v); return o == 0 ? "some" : _accessor.string(at: o) }
+ public var someStringSegmentArray: [UInt8]? { return _accessor.getVector(at: VTOFFSET.someString.v) }
+ public var abcsCount: Int32 { let o = _accessor.offset(VTOFFSET.abcs.v); return o == 0 ? 0 : _accessor.vector(count: o) }
+ public func abcs(at index: Int32) -> ABC? { let o = _accessor.offset(VTOFFSET.abcs.v); return o == 0 ? ABC.a : ABC(rawValue: _accessor.directRead(of: Int32.self, offset: _accessor.vector(at: o) + index * 4)) }
+ public var boolsCount: Int32 { let o = _accessor.offset(VTOFFSET.bools.v); return o == 0 ? 0 : _accessor.vector(count: o) }
+ public func bools(at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.bools.v); return o == 0 ? true : _accessor.directRead(of: Bool.self, offset: _accessor.vector(at: o) + index * 1) }
+ public var bools: [Bool] { return _accessor.getVector(at: VTOFFSET.bools.v) ?? [] }
+ public static func startMoreDefaults(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 6) }
+ public static func addVectorOf(ints: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: ints, at: VTOFFSET.ints.p) }
+ public static func addVectorOf(floats: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: floats, at: VTOFFSET.floats.p) }
+ public static func add(emptyString: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: emptyString, at: VTOFFSET.emptyString.p) }
+ public static func add(someString: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: someString, at: VTOFFSET.someString.p) }
+ public static func addVectorOf(abcs: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: abcs, at: VTOFFSET.abcs.p) }
+ public static func addVectorOf(bools: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: bools, at: VTOFFSET.bools.p) }
+ public static func endMoreDefaults(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end }
+ public static func createMoreDefaults(
+ _ fbb: inout FlatBufferBuilder,
+ intsVectorOffset ints: Offset = Offset(),
+ floatsVectorOffset floats: Offset = Offset(),
+ emptyStringOffset emptyString: Offset = Offset(),
+ someStringOffset someString: Offset = Offset(),
+ abcsVectorOffset abcs: Offset = Offset(),
+ boolsVectorOffset bools: Offset = Offset()
+ ) -> Offset {
+ let __start = MoreDefaults.startMoreDefaults(&fbb)
+ MoreDefaults.addVectorOf(ints: ints, &fbb)
+ MoreDefaults.addVectorOf(floats: floats, &fbb)
+ MoreDefaults.add(emptyString: emptyString, &fbb)
+ MoreDefaults.add(someString: someString, &fbb)
+ MoreDefaults.addVectorOf(abcs: abcs, &fbb)
+ MoreDefaults.addVectorOf(bools: bools, &fbb)
+ return MoreDefaults.endMoreDefaults(&fbb, start: __start)
+ }
+
+
+ public mutating func unpack() -> MoreDefaultsT {
+ return MoreDefaultsT(&self)
+ }
+ public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MoreDefaultsT?) -> Offset {
+ guard var obj = obj else { return Offset() }
+ return pack(&builder, obj: &obj)
+ }
+
+ public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MoreDefaultsT) -> Offset {
+ let __ints = builder.createVector(obj.ints)
+ let __floats = builder.createVector(obj.floats)
+ let __emptyString: Offset
+ if let s = obj.emptyString {
+ __emptyString = builder.create(string: s)
+ } else {
+ __emptyString = Offset()
+ }
+
+ let __someString: Offset
+ if let s = obj.someString {
+ __someString = builder.create(string: s)
+ } else {
+ __someString = Offset()
+ }
+
+ let __abcs = builder.createVector(obj.abcs)
+ let __bools = builder.createVector(obj.bools)
+ let __root = MoreDefaults.startMoreDefaults(&builder)
+ MoreDefaults.addVectorOf(ints: __ints, &builder)
+ MoreDefaults.addVectorOf(floats: __floats, &builder)
+ MoreDefaults.add(emptyString: __emptyString, &builder)
+ MoreDefaults.add(someString: __someString, &builder)
+ MoreDefaults.addVectorOf(abcs: __abcs, &builder)
+ MoreDefaults.addVectorOf(bools: __bools, &builder)
+ return MoreDefaults.endMoreDefaults(&builder, start: __root)
+ }
+
+ public static func verify<T>(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable {
+ var _v = try verifier.visitTable(at: position)
+ try _v.visit(field: VTOFFSET.ints.p, fieldName: "ints", required: false, type: ForwardOffset<Vector<Int32, Int32>>.self)
+ try _v.visit(field: VTOFFSET.floats.p, fieldName: "floats", required: false, type: ForwardOffset<Vector<Float32, Float32>>.self)
+ try _v.visit(field: VTOFFSET.emptyString.p, fieldName: "emptyString", required: false, type: ForwardOffset<String>.self)
+ try _v.visit(field: VTOFFSET.someString.p, fieldName: "someString", required: false, type: ForwardOffset<String>.self)
+ try _v.visit(field: VTOFFSET.abcs.p, fieldName: "abcs", required: false, type: ForwardOffset<Vector<ABC, ABC>>.self)
+ try _v.visit(field: VTOFFSET.bools.p, fieldName: "bools", required: false, type: ForwardOffset<Vector<Bool, Bool>>.self)
+ _v.finish()
+ }
+}
+
+extension MoreDefaults: Encodable {
+
+ enum CodingKeys: String, CodingKey {
+ case ints = "ints"
+ case floats = "floats"
+ case emptyString = "empty_string"
+ case someString = "some_string"
+ case abcs = "abcs"
+ case bools = "bools"
+ }
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ if intsCount > 0 {
+ try container.encodeIfPresent(ints, forKey: .ints)
+ }
+ if floatsCount > 0 {
+ try container.encodeIfPresent(floats, forKey: .floats)
+ }
+ try container.encodeIfPresent(emptyString, forKey: .emptyString)
+ try container.encodeIfPresent(someString, forKey: .someString)
+ if abcsCount > 0 {
+ var contentEncoder = container.nestedUnkeyedContainer(forKey: .abcs)
+ for index in 0..<abcsCount {
+ guard let type = abcs(at: index) else { continue }
+ try contentEncoder.encode(type)
+ }
+ }
+ if boolsCount > 0 {
+ try container.encodeIfPresent(bools, forKey: .bools)
+ }
+ }
+}
+
+public class MoreDefaultsT: NativeObject {
+
+ public var ints: [Int32]
+ public var floats: [Float32]
+ public var emptyString: String?
+ public var someString: String?
+ public var abcs: [ABC]
+ public var bools: [Bool]
+
+ public init(_ _t: inout MoreDefaults) {
+ ints = []
+ for index in 0..<_t.intsCount {
+ ints.append(_t.ints(at: index))
+ }
+ floats = []
+ for index in 0..<_t.floatsCount {
+ floats.append(_t.floats(at: index))
+ }
+ emptyString = _t.emptyString
+ someString = _t.someString
+ abcs = []
+ for index in 0..<_t.abcsCount {
+ abcs.append(_t.abcs(at: index)!)
+ }
+ bools = []
+ for index in 0..<_t.boolsCount {
+ bools.append(_t.bools(at: index))
+ }
+ }
+
+ public init() {
+ ints = []
+ floats = []
+ emptyString = ""
+ someString = "some"
+ abcs = []
+ bools = []
+ }
+
+ public func serialize() -> ByteBuffer { return serialize(type: MoreDefaults.self) }
+
+}
diff --git a/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/optional_scalars_generated.swift b/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/optional_scalars_generated.swift
index 697edde..0f427c8 100644
--- a/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/optional_scalars_generated.swift
+++ b/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/optional_scalars_generated.swift
@@ -4,26 +4,36 @@
import FlatBuffers
-public enum optional_scalars_OptionalByte: Int8, Enum {
+public enum optional_scalars_OptionalByte: Int8, Enum, Verifiable {
public typealias T = Int8
public static var byteSize: Int { return MemoryLayout<Int8>.size }
public var value: Int8 { return self.rawValue }
case none_ = 0
case one = 1
case two = 2
-
public static var max: optional_scalars_OptionalByte { return .two }
public static var min: optional_scalars_OptionalByte { return .none_ }
}
-public struct optional_scalars_ScalarStuff: FlatBufferObject {
+extension optional_scalars_OptionalByte: Encodable {
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.singleValueContainer()
+ switch self {
+ case .none_: try container.encode("None")
+ case .one: try container.encode("One")
+ case .two: try container.encode("Two")
+ }
+ }
+}
- static func validateVersion() { FlatBuffersVersion_1_12_0() }
+public struct optional_scalars_ScalarStuff: FlatBufferObject, Verifiable {
+
+ static func validateVersion() { FlatBuffersVersion_2_0_0() }
public var __buffer: ByteBuffer! { return _accessor.bb }
private var _accessor: Table
- public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset<UOffset>, prefix: Bool = false) { fbb.finish(offset: end, fileId: "NULL", addPrefix: prefix) }
+ public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset, prefix: Bool = false) { fbb.finish(offset: end, fileId: "NULL", addPrefix: prefix) }
public static func getRootAsScalarStuff(bb: ByteBuffer) -> optional_scalars_ScalarStuff { return optional_scalars_ScalarStuff(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) }
private init(_ t: Table) { _accessor = t }
@@ -101,7 +111,7 @@
public var maybeF64: Double? { let o = _accessor.offset(VTOFFSET.maybeF64.v); return o == 0 ? nil : _accessor.readBuffer(of: Double.self, at: o) }
public var defaultF64: Double { let o = _accessor.offset(VTOFFSET.defaultF64.v); return o == 0 ? 42.0 : _accessor.readBuffer(of: Double.self, at: o) }
public var justBool: Bool { let o = _accessor.offset(VTOFFSET.justBool.v); return o == 0 ? false : 0 != _accessor.readBuffer(of: Byte.self, at: o) }
- public var maybeBool: Bool? { let o = _accessor.offset(VTOFFSET.maybeBool.v); return o == 0 ? true : 0 != _accessor.readBuffer(of: Byte.self, at: o) }
+ public var maybeBool: Bool? { let o = _accessor.offset(VTOFFSET.maybeBool.v); return o == 0 ? nil : 0 != _accessor.readBuffer(of: Byte.self, at: o) }
public var defaultBool: Bool { let o = _accessor.offset(VTOFFSET.defaultBool.v); return o == 0 ? true : 0 != _accessor.readBuffer(of: Byte.self, at: o) }
public var justEnum: optional_scalars_OptionalByte { let o = _accessor.offset(VTOFFSET.justEnum.v); return o == 0 ? .none_ : optional_scalars_OptionalByte(rawValue: _accessor.readBuffer(of: Int8.self, at: o)) ?? .none_ }
public var maybeEnum: optional_scalars_OptionalByte? { let o = _accessor.offset(VTOFFSET.maybeEnum.v); return o == 0 ? nil : optional_scalars_OptionalByte(rawValue: _accessor.readBuffer(of: Int8.self, at: o)) ?? nil }
@@ -145,7 +155,7 @@
public static func add(justEnum: optional_scalars_OptionalByte, _ fbb: inout FlatBufferBuilder) { fbb.add(element: justEnum.rawValue, def: 0, at: VTOFFSET.justEnum.p) }
public static func add(maybeEnum: optional_scalars_OptionalByte?, _ fbb: inout FlatBufferBuilder) { fbb.add(element: maybeEnum?.rawValue, at: VTOFFSET.maybeEnum.p) }
public static func add(defaultEnum: optional_scalars_OptionalByte, _ fbb: inout FlatBufferBuilder) { fbb.add(element: defaultEnum.rawValue, def: 1, at: VTOFFSET.defaultEnum.p) }
- public static func endScalarStuff(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset<UOffset> { let end = Offset<UOffset>(offset: fbb.endTable(at: start)); return end }
+ public static func endScalarStuff(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end }
public static func createScalarStuff(
_ fbb: inout FlatBufferBuilder,
justI8: Int8 = 0,
@@ -184,7 +194,7 @@
justEnum: optional_scalars_OptionalByte = .none_,
maybeEnum: optional_scalars_OptionalByte? = nil,
defaultEnum: optional_scalars_OptionalByte = .one
- ) -> Offset<UOffset> {
+ ) -> Offset {
let __start = optional_scalars_ScalarStuff.startScalarStuff(&fbb)
optional_scalars_ScalarStuff.add(justI8: justI8, &fbb)
optional_scalars_ScalarStuff.add(maybeI8: maybeI8, &fbb)
@@ -224,5 +234,175 @@
optional_scalars_ScalarStuff.add(defaultEnum: defaultEnum, &fbb)
return optional_scalars_ScalarStuff.endScalarStuff(&fbb, start: __start)
}
+
+ public static func verify<T>(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable {
+ var _v = try verifier.visitTable(at: position)
+ try _v.visit(field: VTOFFSET.justI8.p, fieldName: "justI8", required: false, type: Int8.self)
+ try _v.visit(field: VTOFFSET.maybeI8.p, fieldName: "maybeI8", required: false, type: Int8.self)
+ try _v.visit(field: VTOFFSET.defaultI8.p, fieldName: "defaultI8", required: false, type: Int8.self)
+ try _v.visit(field: VTOFFSET.justU8.p, fieldName: "justU8", required: false, type: UInt8.self)
+ try _v.visit(field: VTOFFSET.maybeU8.p, fieldName: "maybeU8", required: false, type: UInt8.self)
+ try _v.visit(field: VTOFFSET.defaultU8.p, fieldName: "defaultU8", required: false, type: UInt8.self)
+ try _v.visit(field: VTOFFSET.justI16.p, fieldName: "justI16", required: false, type: Int16.self)
+ try _v.visit(field: VTOFFSET.maybeI16.p, fieldName: "maybeI16", required: false, type: Int16.self)
+ try _v.visit(field: VTOFFSET.defaultI16.p, fieldName: "defaultI16", required: false, type: Int16.self)
+ try _v.visit(field: VTOFFSET.justU16.p, fieldName: "justU16", required: false, type: UInt16.self)
+ try _v.visit(field: VTOFFSET.maybeU16.p, fieldName: "maybeU16", required: false, type: UInt16.self)
+ try _v.visit(field: VTOFFSET.defaultU16.p, fieldName: "defaultU16", required: false, type: UInt16.self)
+ try _v.visit(field: VTOFFSET.justI32.p, fieldName: "justI32", required: false, type: Int32.self)
+ try _v.visit(field: VTOFFSET.maybeI32.p, fieldName: "maybeI32", required: false, type: Int32.self)
+ try _v.visit(field: VTOFFSET.defaultI32.p, fieldName: "defaultI32", required: false, type: Int32.self)
+ try _v.visit(field: VTOFFSET.justU32.p, fieldName: "justU32", required: false, type: UInt32.self)
+ try _v.visit(field: VTOFFSET.maybeU32.p, fieldName: "maybeU32", required: false, type: UInt32.self)
+ try _v.visit(field: VTOFFSET.defaultU32.p, fieldName: "defaultU32", required: false, type: UInt32.self)
+ try _v.visit(field: VTOFFSET.justI64.p, fieldName: "justI64", required: false, type: Int64.self)
+ try _v.visit(field: VTOFFSET.maybeI64.p, fieldName: "maybeI64", required: false, type: Int64.self)
+ try _v.visit(field: VTOFFSET.defaultI64.p, fieldName: "defaultI64", required: false, type: Int64.self)
+ try _v.visit(field: VTOFFSET.justU64.p, fieldName: "justU64", required: false, type: UInt64.self)
+ try _v.visit(field: VTOFFSET.maybeU64.p, fieldName: "maybeU64", required: false, type: UInt64.self)
+ try _v.visit(field: VTOFFSET.defaultU64.p, fieldName: "defaultU64", required: false, type: UInt64.self)
+ try _v.visit(field: VTOFFSET.justF32.p, fieldName: "justF32", required: false, type: Float32.self)
+ try _v.visit(field: VTOFFSET.maybeF32.p, fieldName: "maybeF32", required: false, type: Float32.self)
+ try _v.visit(field: VTOFFSET.defaultF32.p, fieldName: "defaultF32", required: false, type: Float32.self)
+ try _v.visit(field: VTOFFSET.justF64.p, fieldName: "justF64", required: false, type: Double.self)
+ try _v.visit(field: VTOFFSET.maybeF64.p, fieldName: "maybeF64", required: false, type: Double.self)
+ try _v.visit(field: VTOFFSET.defaultF64.p, fieldName: "defaultF64", required: false, type: Double.self)
+ try _v.visit(field: VTOFFSET.justBool.p, fieldName: "justBool", required: false, type: Bool.self)
+ try _v.visit(field: VTOFFSET.maybeBool.p, fieldName: "maybeBool", required: false, type: Bool.self)
+ try _v.visit(field: VTOFFSET.defaultBool.p, fieldName: "defaultBool", required: false, type: Bool.self)
+ try _v.visit(field: VTOFFSET.justEnum.p, fieldName: "justEnum", required: false, type: optional_scalars_OptionalByte.self)
+ try _v.visit(field: VTOFFSET.maybeEnum.p, fieldName: "maybeEnum", required: false, type: optional_scalars_OptionalByte.self)
+ try _v.visit(field: VTOFFSET.defaultEnum.p, fieldName: "defaultEnum", required: false, type: optional_scalars_OptionalByte.self)
+ _v.finish()
+ }
+}
+
+extension optional_scalars_ScalarStuff: Encodable {
+
+ enum CodingKeys: String, CodingKey {
+ case justI8 = "just_i8"
+ case maybeI8 = "maybe_i8"
+ case defaultI8 = "default_i8"
+ case justU8 = "just_u8"
+ case maybeU8 = "maybe_u8"
+ case defaultU8 = "default_u8"
+ case justI16 = "just_i16"
+ case maybeI16 = "maybe_i16"
+ case defaultI16 = "default_i16"
+ case justU16 = "just_u16"
+ case maybeU16 = "maybe_u16"
+ case defaultU16 = "default_u16"
+ case justI32 = "just_i32"
+ case maybeI32 = "maybe_i32"
+ case defaultI32 = "default_i32"
+ case justU32 = "just_u32"
+ case maybeU32 = "maybe_u32"
+ case defaultU32 = "default_u32"
+ case justI64 = "just_i64"
+ case maybeI64 = "maybe_i64"
+ case defaultI64 = "default_i64"
+ case justU64 = "just_u64"
+ case maybeU64 = "maybe_u64"
+ case defaultU64 = "default_u64"
+ case justF32 = "just_f32"
+ case maybeF32 = "maybe_f32"
+ case defaultF32 = "default_f32"
+ case justF64 = "just_f64"
+ case maybeF64 = "maybe_f64"
+ case defaultF64 = "default_f64"
+ case justBool = "just_bool"
+ case maybeBool = "maybe_bool"
+ case defaultBool = "default_bool"
+ case justEnum = "just_enum"
+ case maybeEnum = "maybe_enum"
+ case defaultEnum = "default_enum"
+ }
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ if justI8 != 0 {
+ try container.encodeIfPresent(justI8, forKey: .justI8)
+ }
+ try container.encodeIfPresent(maybeI8, forKey: .maybeI8)
+ if defaultI8 != 42 {
+ try container.encodeIfPresent(defaultI8, forKey: .defaultI8)
+ }
+ if justU8 != 0 {
+ try container.encodeIfPresent(justU8, forKey: .justU8)
+ }
+ try container.encodeIfPresent(maybeU8, forKey: .maybeU8)
+ if defaultU8 != 42 {
+ try container.encodeIfPresent(defaultU8, forKey: .defaultU8)
+ }
+ if justI16 != 0 {
+ try container.encodeIfPresent(justI16, forKey: .justI16)
+ }
+ try container.encodeIfPresent(maybeI16, forKey: .maybeI16)
+ if defaultI16 != 42 {
+ try container.encodeIfPresent(defaultI16, forKey: .defaultI16)
+ }
+ if justU16 != 0 {
+ try container.encodeIfPresent(justU16, forKey: .justU16)
+ }
+ try container.encodeIfPresent(maybeU16, forKey: .maybeU16)
+ if defaultU16 != 42 {
+ try container.encodeIfPresent(defaultU16, forKey: .defaultU16)
+ }
+ if justI32 != 0 {
+ try container.encodeIfPresent(justI32, forKey: .justI32)
+ }
+ try container.encodeIfPresent(maybeI32, forKey: .maybeI32)
+ if defaultI32 != 42 {
+ try container.encodeIfPresent(defaultI32, forKey: .defaultI32)
+ }
+ if justU32 != 0 {
+ try container.encodeIfPresent(justU32, forKey: .justU32)
+ }
+ try container.encodeIfPresent(maybeU32, forKey: .maybeU32)
+ if defaultU32 != 42 {
+ try container.encodeIfPresent(defaultU32, forKey: .defaultU32)
+ }
+ if justI64 != 0 {
+ try container.encodeIfPresent(justI64, forKey: .justI64)
+ }
+ try container.encodeIfPresent(maybeI64, forKey: .maybeI64)
+ if defaultI64 != 42 {
+ try container.encodeIfPresent(defaultI64, forKey: .defaultI64)
+ }
+ if justU64 != 0 {
+ try container.encodeIfPresent(justU64, forKey: .justU64)
+ }
+ try container.encodeIfPresent(maybeU64, forKey: .maybeU64)
+ if defaultU64 != 42 {
+ try container.encodeIfPresent(defaultU64, forKey: .defaultU64)
+ }
+ if justF32 != 0.0 {
+ try container.encodeIfPresent(justF32, forKey: .justF32)
+ }
+ try container.encodeIfPresent(maybeF32, forKey: .maybeF32)
+ if defaultF32 != 42.0 {
+ try container.encodeIfPresent(defaultF32, forKey: .defaultF32)
+ }
+ if justF64 != 0.0 {
+ try container.encodeIfPresent(justF64, forKey: .justF64)
+ }
+ try container.encodeIfPresent(maybeF64, forKey: .maybeF64)
+ if defaultF64 != 42.0 {
+ try container.encodeIfPresent(defaultF64, forKey: .defaultF64)
+ }
+ if justBool != false {
+ try container.encodeIfPresent(justBool, forKey: .justBool)
+ }
+ try container.encodeIfPresent(maybeBool, forKey: .maybeBool)
+ if defaultBool != true {
+ try container.encodeIfPresent(defaultBool, forKey: .defaultBool)
+ }
+ if justEnum != .none_ {
+ try container.encodeIfPresent(justEnum, forKey: .justEnum)
+ }
+ try container.encodeIfPresent(maybeEnum, forKey: .maybeEnum)
+ if defaultEnum != .one {
+ try container.encodeIfPresent(defaultEnum, forKey: .defaultEnum)
+ }
+ }
}
diff --git a/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/union_vector_generated.swift b/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/union_vector_generated.swift
index 88cb4fb..59ed005 100644
--- a/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/union_vector_generated.swift
+++ b/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/union_vector_generated.swift
@@ -4,8 +4,13 @@
import FlatBuffers
-public enum Character: UInt8, Enum {
+public enum Character: UInt8, UnionEnum {
public typealias T = UInt8
+
+ public init?(value: T) {
+ self.init(rawValue: value)
+ }
+
public static var byteSize: Int { return MemoryLayout<UInt8>.size }
public var value: UInt8 { return self.rawValue }
case none_ = 0
@@ -15,144 +20,315 @@
case bookfan = 4
case other = 5
case unused = 6
-
public static var max: Character { return .unused }
public static var min: Character { return .none_ }
}
+extension Character: Encodable {
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.singleValueContainer()
+ switch self {
+ case .none_: try container.encode("NONE")
+ case .mulan: try container.encode("MuLan")
+ case .rapunzel: try container.encode("Rapunzel")
+ case .belle: try container.encode("Belle")
+ case .bookfan: try container.encode("BookFan")
+ case .other: try container.encode("Other")
+ case .unused: try container.encode("Unused")
+ }
+ }
+}
+
public struct CharacterUnion {
public var type: Character
- public var value: NativeTable?
- public init(_ v: NativeTable?, type: Character) {
+ public var value: NativeObject?
+ public init(_ v: NativeObject?, type: Character) {
self.type = type
self.value = v
}
- public func pack(builder: inout FlatBufferBuilder) -> Offset<UOffset> {
+ public func pack(builder: inout FlatBufferBuilder) -> Offset {
switch type {
case .mulan:
var __obj = value as? AttackerT
return Attacker.pack(&builder, obj: &__obj)
case .rapunzel:
- var __obj = value as? RapunzelT
- return Rapunzel.pack(&builder, obj: &__obj)
+ var __obj = value as? Rapunzel
+ return Rapunzel_Mutable.pack(&builder, obj: &__obj)
case .belle:
- var __obj = value as? BookReaderT
- return BookReader.pack(&builder, obj: &__obj)
+ var __obj = value as? BookReader
+ return BookReader_Mutable.pack(&builder, obj: &__obj)
case .bookfan:
- var __obj = value as? BookReaderT
- return BookReader.pack(&builder, obj: &__obj)
+ var __obj = value as? BookReader
+ return BookReader_Mutable.pack(&builder, obj: &__obj)
+ case .other:
+ var __obj = value as? String
+ return String.pack(&builder, obj: &__obj)
+ case .unused:
+ var __obj = value as? String
+ return String.pack(&builder, obj: &__obj)
default: return Offset()
}
}
}
-public struct Rapunzel: Readable {
+public enum Gadget: UInt8, UnionEnum {
+ public typealias T = UInt8
- static func validateVersion() { FlatBuffersVersion_1_12_0() }
+ public init?(value: T) {
+ self.init(rawValue: value)
+ }
+
+ public static var byteSize: Int { return MemoryLayout<UInt8>.size }
+ public var value: UInt8 { return self.rawValue }
+ case none_ = 0
+ case fallingtub = 1
+ case handfan = 2
+
+ public static var max: Gadget { return .handfan }
+ public static var min: Gadget { return .none_ }
+}
+
+extension Gadget: Encodable {
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.singleValueContainer()
+ switch self {
+ case .none_: try container.encode("NONE")
+ case .fallingtub: try container.encode("FallingTub")
+ case .handfan: try container.encode("HandFan")
+ }
+ }
+}
+
+public struct GadgetUnion {
+ public var type: Gadget
+ public var value: NativeObject?
+ public init(_ v: NativeObject?, type: Gadget) {
+ self.type = type
+ self.value = v
+ }
+ public func pack(builder: inout FlatBufferBuilder) -> Offset {
+ switch type {
+ case .fallingtub:
+ var __obj = value as? FallingTub
+ return FallingTub_Mutable.pack(&builder, obj: &__obj)
+ case .handfan:
+ var __obj = value as? HandFanT
+ return HandFan.pack(&builder, obj: &__obj)
+ default: return Offset()
+ }
+ }
+}
+public struct Rapunzel: NativeStruct, Verifiable, FlatbuffersInitializable, NativeObject {
+
+ static func validateVersion() { FlatBuffersVersion_2_0_0() }
+
+ private var _hairLength: Int32
+
+ public init(_ bb: ByteBuffer, o: Int32) {
+ let _accessor = Struct(bb: bb, position: o)
+ _hairLength = _accessor.readBuffer(of: Int32.self, at: 0)
+ }
+
+ public init(hairLength: Int32) {
+ _hairLength = hairLength
+ }
+
+ public init() {
+ _hairLength = 0
+ }
+
+ public init(_ _t: inout Rapunzel_Mutable) {
+ _hairLength = _t.hairLength
+ }
+
+ public var hairLength: Int32 { _hairLength }
+
+ public static func verify<T>(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable {
+ try verifier.inBuffer(position: position, of: Rapunzel.self)
+ }
+}
+
+extension Rapunzel: Encodable {
+
+ enum CodingKeys: String, CodingKey {
+ case hairLength = "hair_length"
+ }
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ if hairLength != 0 {
+ try container.encodeIfPresent(hairLength, forKey: .hairLength)
+ }
+ }
+}
+
+public struct Rapunzel_Mutable: FlatBufferObject {
+
+ static func validateVersion() { FlatBuffersVersion_2_0_0() }
public var __buffer: ByteBuffer! { return _accessor.bb }
private var _accessor: Struct
- public static var size = 4
- public static var alignment = 4
public init(_ bb: ByteBuffer, o: Int32) { _accessor = Struct(bb: bb, position: o) }
public var hairLength: Int32 { return _accessor.readBuffer(of: Int32.self, at: 0) }
@discardableResult public func mutate(hairLength: Int32) -> Bool { return _accessor.mutate(hairLength, index: 0) }
- public mutating func unpack() -> RapunzelT {
- return RapunzelT(&self)
+ public mutating func unpack() -> Rapunzel {
+ return Rapunzel(&self)
}
- public static func pack(_ builder: inout FlatBufferBuilder, obj: inout RapunzelT?) -> Offset<UOffset> {
- guard var obj = obj else { return Offset<UOffset>() }
+ public static func pack(_ builder: inout FlatBufferBuilder, obj: inout Rapunzel?) -> Offset {
+ guard var obj = obj else { return Offset() }
return pack(&builder, obj: &obj)
}
- public static func pack(_ builder: inout FlatBufferBuilder, obj: inout RapunzelT) -> Offset<UOffset> {
- return createRapunzel(builder: &builder, hairLength: obj.hairLength)
+ public static func pack(_ builder: inout FlatBufferBuilder, obj: inout Rapunzel) -> Offset {
+ return builder.create(struct: obj)
}
}
-public class RapunzelT: NativeTable {
+public struct BookReader: NativeStruct, Verifiable, FlatbuffersInitializable, NativeObject {
- public var hairLength: Int32
+ static func validateVersion() { FlatBuffersVersion_2_0_0() }
- public init(_ _t: inout Rapunzel) {
- hairLength = _t.hairLength
+ private var _booksRead: Int32
+
+ public init(_ bb: ByteBuffer, o: Int32) {
+ let _accessor = Struct(bb: bb, position: o)
+ _booksRead = _accessor.readBuffer(of: Int32.self, at: 0)
+ }
+
+ public init(booksRead: Int32) {
+ _booksRead = booksRead
}
public init() {
- hairLength = 0
+ _booksRead = 0
}
-}
-public struct BookReader: Readable {
+ public init(_ _t: inout BookReader_Mutable) {
+ _booksRead = _t.booksRead
+ }
- static func validateVersion() { FlatBuffersVersion_1_12_0() }
+ public var booksRead: Int32 { _booksRead }
+
+ public static func verify<T>(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable {
+ try verifier.inBuffer(position: position, of: BookReader.self)
+ }
+}
+
+extension BookReader: Encodable {
+
+ enum CodingKeys: String, CodingKey {
+ case booksRead = "books_read"
+ }
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ if booksRead != 0 {
+ try container.encodeIfPresent(booksRead, forKey: .booksRead)
+ }
+ }
+}
+
+public struct BookReader_Mutable: FlatBufferObject {
+
+ static func validateVersion() { FlatBuffersVersion_2_0_0() }
public var __buffer: ByteBuffer! { return _accessor.bb }
private var _accessor: Struct
- public static var size = 4
- public static var alignment = 4
public init(_ bb: ByteBuffer, o: Int32) { _accessor = Struct(bb: bb, position: o) }
public var booksRead: Int32 { return _accessor.readBuffer(of: Int32.self, at: 0) }
@discardableResult public func mutate(booksRead: Int32) -> Bool { return _accessor.mutate(booksRead, index: 0) }
- public mutating func unpack() -> BookReaderT {
- return BookReaderT(&self)
+ public mutating func unpack() -> BookReader {
+ return BookReader(&self)
}
- public static func pack(_ builder: inout FlatBufferBuilder, obj: inout BookReaderT?) -> Offset<UOffset> {
- guard var obj = obj else { return Offset<UOffset>() }
+ public static func pack(_ builder: inout FlatBufferBuilder, obj: inout BookReader?) -> Offset {
+ guard var obj = obj else { return Offset() }
return pack(&builder, obj: &obj)
}
- public static func pack(_ builder: inout FlatBufferBuilder, obj: inout BookReaderT) -> Offset<UOffset> {
- return createBookReader(builder: &builder, booksRead: obj.booksRead)
+ public static func pack(_ builder: inout FlatBufferBuilder, obj: inout BookReader) -> Offset {
+ return builder.create(struct: obj)
}
}
-public class BookReaderT: NativeTable {
+public struct FallingTub: NativeStruct, Verifiable, FlatbuffersInitializable, NativeObject {
- public var booksRead: Int32
+ static func validateVersion() { FlatBuffersVersion_2_0_0() }
- public init(_ _t: inout BookReader) {
- booksRead = _t.booksRead
+ private var _weight: Int32
+
+ public init(_ bb: ByteBuffer, o: Int32) {
+ let _accessor = Struct(bb: bb, position: o)
+ _weight = _accessor.readBuffer(of: Int32.self, at: 0)
+ }
+
+ public init(weight: Int32) {
+ _weight = weight
}
public init() {
- booksRead = 0
+ _weight = 0
}
-}
-extension Rapunzel {
- @discardableResult
- public static func createRapunzel(builder: inout FlatBufferBuilder, hairLength: Int32 = 0) -> Offset<UOffset> {
- builder.createStructOf(size: Rapunzel.size, alignment: Rapunzel.alignment)
- builder.reverseAdd(v: hairLength, postion: 0)
- return builder.endStruct()
+ public init(_ _t: inout FallingTub_Mutable) {
+ _weight = _t.weight
}
+ public var weight: Int32 { _weight }
+
+ public static func verify<T>(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable {
+ try verifier.inBuffer(position: position, of: FallingTub.self)
+ }
}
-extension BookReader {
- @discardableResult
- public static func createBookReader(builder: inout FlatBufferBuilder, booksRead: Int32 = 0) -> Offset<UOffset> {
- builder.createStructOf(size: BookReader.size, alignment: BookReader.alignment)
- builder.reverseAdd(v: booksRead, postion: 0)
- return builder.endStruct()
+extension FallingTub: Encodable {
+
+ enum CodingKeys: String, CodingKey {
+ case weight = "weight"
+ }
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ if weight != 0 {
+ try container.encodeIfPresent(weight, forKey: .weight)
+ }
+ }
+}
+
+public struct FallingTub_Mutable: FlatBufferObject {
+
+ static func validateVersion() { FlatBuffersVersion_2_0_0() }
+ public var __buffer: ByteBuffer! { return _accessor.bb }
+ private var _accessor: Struct
+
+ public init(_ bb: ByteBuffer, o: Int32) { _accessor = Struct(bb: bb, position: o) }
+
+ public var weight: Int32 { return _accessor.readBuffer(of: Int32.self, at: 0) }
+ @discardableResult public func mutate(weight: Int32) -> Bool { return _accessor.mutate(weight, index: 0) }
+
+
+ public mutating func unpack() -> FallingTub {
+ return FallingTub(&self)
+ }
+ public static func pack(_ builder: inout FlatBufferBuilder, obj: inout FallingTub?) -> Offset {
+ guard var obj = obj else { return Offset() }
+ return pack(&builder, obj: &obj)
}
+ public static func pack(_ builder: inout FlatBufferBuilder, obj: inout FallingTub) -> Offset {
+ return builder.create(struct: obj)
+ }
}
-public struct Attacker: FlatBufferObject, ObjectAPI {
+public struct Attacker: FlatBufferObject, Verifiable, ObjectAPIPacker {
- static func validateVersion() { FlatBuffersVersion_1_12_0() }
+ static func validateVersion() { FlatBuffersVersion_2_0_0() }
public var __buffer: ByteBuffer! { return _accessor.bb }
private var _accessor: Table
- public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset<UOffset>, prefix: Bool = false) { fbb.finish(offset: end, fileId: "MOVI", addPrefix: prefix) }
+ public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset, prefix: Bool = false) { fbb.finish(offset: end, fileId: "MOVI", addPrefix: prefix) }
public static func getRootAsAttacker(bb: ByteBuffer) -> Attacker { return Attacker(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) }
private init(_ t: Table) { _accessor = t }
@@ -168,11 +344,11 @@
@discardableResult public func mutate(swordAttackDamage: Int32) -> Bool {let o = _accessor.offset(VTOFFSET.swordAttackDamage.v); return _accessor.mutate(swordAttackDamage, index: o) }
public static func startAttacker(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) }
public static func add(swordAttackDamage: Int32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: swordAttackDamage, def: 0, at: VTOFFSET.swordAttackDamage.p) }
- public static func endAttacker(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset<UOffset> { let end = Offset<UOffset>(offset: fbb.endTable(at: start)); return end }
+ public static func endAttacker(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end }
public static func createAttacker(
_ fbb: inout FlatBufferBuilder,
swordAttackDamage: Int32 = 0
- ) -> Offset<UOffset> {
+ ) -> Offset {
let __start = Attacker.startAttacker(&fbb)
Attacker.add(swordAttackDamage: swordAttackDamage, &fbb)
return Attacker.endAttacker(&fbb, start: __start)
@@ -182,19 +358,38 @@
public mutating func unpack() -> AttackerT {
return AttackerT(&self)
}
- public static func pack(_ builder: inout FlatBufferBuilder, obj: inout AttackerT?) -> Offset<UOffset> {
- guard var obj = obj else { return Offset<UOffset>() }
+ public static func pack(_ builder: inout FlatBufferBuilder, obj: inout AttackerT?) -> Offset {
+ guard var obj = obj else { return Offset() }
return pack(&builder, obj: &obj)
}
- public static func pack(_ builder: inout FlatBufferBuilder, obj: inout AttackerT) -> Offset<UOffset> {
+ public static func pack(_ builder: inout FlatBufferBuilder, obj: inout AttackerT) -> Offset {
let __root = Attacker.startAttacker(&builder)
Attacker.add(swordAttackDamage: obj.swordAttackDamage, &builder)
return Attacker.endAttacker(&builder, start: __root)
}
+
+ public static func verify<T>(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable {
+ var _v = try verifier.visitTable(at: position)
+ try _v.visit(field: VTOFFSET.swordAttackDamage.p, fieldName: "swordAttackDamage", required: false, type: Int32.self)
+ _v.finish()
+ }
}
-public class AttackerT: NativeTable {
+extension Attacker: Encodable {
+
+ enum CodingKeys: String, CodingKey {
+ case swordAttackDamage = "sword_attack_damage"
+ }
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ if swordAttackDamage != 0 {
+ try container.encodeIfPresent(swordAttackDamage, forKey: .swordAttackDamage)
+ }
+ }
+}
+
+public class AttackerT: NativeObject {
public var swordAttackDamage: Int32
@@ -209,13 +404,95 @@
public func serialize() -> ByteBuffer { return serialize(type: Attacker.self) }
}
-public struct Movie: FlatBufferObject, ObjectAPI {
+public struct HandFan: FlatBufferObject, Verifiable, ObjectAPIPacker {
- static func validateVersion() { FlatBuffersVersion_1_12_0() }
+ static func validateVersion() { FlatBuffersVersion_2_0_0() }
public var __buffer: ByteBuffer! { return _accessor.bb }
private var _accessor: Table
- public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset<UOffset>, prefix: Bool = false) { fbb.finish(offset: end, fileId: "MOVI", addPrefix: prefix) }
+ public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset, prefix: Bool = false) { fbb.finish(offset: end, fileId: "MOVI", addPrefix: prefix) }
+ public static func getRootAsHandFan(bb: ByteBuffer) -> HandFan { return HandFan(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) }
+
+ private init(_ t: Table) { _accessor = t }
+ public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) }
+
+ private enum VTOFFSET: VOffset {
+ case length = 4
+ var v: Int32 { Int32(self.rawValue) }
+ var p: VOffset { self.rawValue }
+ }
+
+ public var length: Int32 { let o = _accessor.offset(VTOFFSET.length.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int32.self, at: o) }
+ @discardableResult public func mutate(length: Int32) -> Bool {let o = _accessor.offset(VTOFFSET.length.v); return _accessor.mutate(length, index: o) }
+ public static func startHandFan(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) }
+ public static func add(length: Int32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: length, def: 0, at: VTOFFSET.length.p) }
+ public static func endHandFan(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end }
+ public static func createHandFan(
+ _ fbb: inout FlatBufferBuilder,
+ length: Int32 = 0
+ ) -> Offset {
+ let __start = HandFan.startHandFan(&fbb)
+ HandFan.add(length: length, &fbb)
+ return HandFan.endHandFan(&fbb, start: __start)
+ }
+
+
+ public mutating func unpack() -> HandFanT {
+ return HandFanT(&self)
+ }
+ public static func pack(_ builder: inout FlatBufferBuilder, obj: inout HandFanT?) -> Offset {
+ guard var obj = obj else { return Offset() }
+ return pack(&builder, obj: &obj)
+ }
+
+ public static func pack(_ builder: inout FlatBufferBuilder, obj: inout HandFanT) -> Offset {
+ let __root = HandFan.startHandFan(&builder)
+ HandFan.add(length: obj.length, &builder)
+ return HandFan.endHandFan(&builder, start: __root)
+ }
+
+ public static func verify<T>(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable {
+ var _v = try verifier.visitTable(at: position)
+ try _v.visit(field: VTOFFSET.length.p, fieldName: "length", required: false, type: Int32.self)
+ _v.finish()
+ }
+}
+
+extension HandFan: Encodable {
+
+ enum CodingKeys: String, CodingKey {
+ case length = "length"
+ }
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ if length != 0 {
+ try container.encodeIfPresent(length, forKey: .length)
+ }
+ }
+}
+
+public class HandFanT: NativeObject {
+
+ public var length: Int32
+
+ public init(_ _t: inout HandFan) {
+ length = _t.length
+ }
+
+ public init() {
+ length = 0
+ }
+
+ public func serialize() -> ByteBuffer { return serialize(type: HandFan.self) }
+
+}
+public struct Movie: FlatBufferObject, Verifiable, ObjectAPIPacker {
+
+ static func validateVersion() { FlatBuffersVersion_2_0_0() }
+ public var __buffer: ByteBuffer! { return _accessor.bb }
+ private var _accessor: Table
+
+ public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset, prefix: Bool = false) { fbb.finish(offset: end, fileId: "MOVI", addPrefix: prefix) }
public static func getRootAsMovie(bb: ByteBuffer) -> Movie { return Movie(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) }
private init(_ t: Table) { _accessor = t }
@@ -231,24 +508,24 @@
}
public var mainCharacterType: Character { let o = _accessor.offset(VTOFFSET.mainCharacterType.v); return o == 0 ? .none_ : Character(rawValue: _accessor.readBuffer(of: UInt8.self, at: o)) ?? .none_ }
- public func mainCharacter<T: FlatBufferObject>(type: T.Type) -> T? { let o = _accessor.offset(VTOFFSET.mainCharacter.v); return o == 0 ? nil : _accessor.union(o) }
+ public func mainCharacter<T: FlatbuffersInitializable>(type: T.Type) -> T? { let o = _accessor.offset(VTOFFSET.mainCharacter.v); return o == 0 ? nil : _accessor.union(o) }
public var charactersTypeCount: Int32 { let o = _accessor.offset(VTOFFSET.charactersType.v); return o == 0 ? 0 : _accessor.vector(count: o) }
public func charactersType(at index: Int32) -> Character? { let o = _accessor.offset(VTOFFSET.charactersType.v); return o == 0 ? Character.none_ : Character(rawValue: _accessor.directRead(of: UInt8.self, offset: _accessor.vector(at: o) + index * 1)) }
public var charactersCount: Int32 { let o = _accessor.offset(VTOFFSET.characters.v); return o == 0 ? 0 : _accessor.vector(count: o) }
- public func characters<T: FlatBufferObject>(at index: Int32, type: T.Type) -> T? { let o = _accessor.offset(VTOFFSET.characters.v); return o == 0 ? nil : _accessor.directUnion(_accessor.vector(at: o) + index * 4) }
+ public func characters<T: FlatbuffersInitializable>(at index: Int32, type: T.Type) -> T? { let o = _accessor.offset(VTOFFSET.characters.v); return o == 0 ? nil : _accessor.directUnion(_accessor.vector(at: o) + index * 4) }
public static func startMovie(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 4) }
public static func add(mainCharacterType: Character, _ fbb: inout FlatBufferBuilder) { fbb.add(element: mainCharacterType.rawValue, def: 0, at: VTOFFSET.mainCharacterType.p) }
- public static func add(mainCharacter: Offset<UOffset>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: mainCharacter, at: VTOFFSET.mainCharacter.p) }
- public static func addVectorOf(charactersType: Offset<UOffset>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: charactersType, at: VTOFFSET.charactersType.p) }
- public static func addVectorOf(characters: Offset<UOffset>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: characters, at: VTOFFSET.characters.p) }
- public static func endMovie(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset<UOffset> { let end = Offset<UOffset>(offset: fbb.endTable(at: start)); return end }
+ public static func add(mainCharacter: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: mainCharacter, at: VTOFFSET.mainCharacter.p) }
+ public static func addVectorOf(charactersType: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: charactersType, at: VTOFFSET.charactersType.p) }
+ public static func addVectorOf(characters: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: characters, at: VTOFFSET.characters.p) }
+ public static func endMovie(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end }
public static func createMovie(
_ fbb: inout FlatBufferBuilder,
mainCharacterType: Character = .none_,
- offsetOfMainCharacter mainCharacter: Offset<UOffset> = Offset(),
- vectorOfCharactersType charactersType: Offset<UOffset> = Offset(),
- vectorOfCharacters characters: Offset<UOffset> = Offset()
- ) -> Offset<UOffset> {
+ mainCharacterOffset mainCharacter: Offset = Offset(),
+ charactersTypeVectorOffset charactersType: Offset = Offset(),
+ charactersVectorOffset characters: Offset = Offset()
+ ) -> Offset {
let __start = Movie.startMovie(&fbb)
Movie.add(mainCharacterType: mainCharacterType, &fbb)
Movie.add(mainCharacter: mainCharacter, &fbb)
@@ -261,14 +538,14 @@
public mutating func unpack() -> MovieT {
return MovieT(&self)
}
- public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MovieT?) -> Offset<UOffset> {
- guard var obj = obj else { return Offset<UOffset>() }
+ public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MovieT?) -> Offset {
+ guard var obj = obj else { return Offset() }
return pack(&builder, obj: &obj)
}
- public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MovieT) -> Offset<UOffset> {
+ public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MovieT) -> Offset {
let __mainCharacter = obj.mainCharacter?.pack(builder: &builder) ?? Offset()
- var __characters__: [Offset<UOffset>] = []
+ var __characters__: [Offset] = []
for i in obj.characters {
guard let off = i?.pack(builder: &builder) else { continue }
__characters__.append(off)
@@ -285,9 +562,116 @@
Movie.addVectorOf(characters: __characters, &builder)
return Movie.endMovie(&builder, start: __root)
}
+
+ public static func verify<T>(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable {
+ var _v = try verifier.visitTable(at: position)
+ try _v.visit(unionKey: VTOFFSET.mainCharacterType.p, unionField: VTOFFSET.mainCharacter.p, unionKeyName: "mainCharacterType", fieldName: "mainCharacter", required: false, completion: { (verifier, key: Character, pos) in
+ switch key {
+ case .none_:
+ break // NOTE - SWIFT doesnt support none
+ case .mulan:
+ try ForwardOffset<Attacker>.verify(&verifier, at: pos, of: Attacker.self)
+ case .rapunzel:
+ try Rapunzel.verify(&verifier, at: pos, of: Rapunzel.self)
+ case .belle:
+ try BookReader.verify(&verifier, at: pos, of: BookReader.self)
+ case .bookfan:
+ try BookReader.verify(&verifier, at: pos, of: BookReader.self)
+ case .other:
+ try ForwardOffset<String>.verify(&verifier, at: pos, of: String.self)
+ case .unused:
+ try ForwardOffset<String>.verify(&verifier, at: pos, of: String.self)
+ }
+ })
+ try _v.visitUnionVector(unionKey: VTOFFSET.charactersType.p, unionField: VTOFFSET.characters.p, unionKeyName: "charactersType", fieldName: "characters", required: false, completion: { (verifier, key: Character, pos) in
+ switch key {
+ case .none_:
+ break // NOTE - SWIFT doesnt support none
+ case .mulan:
+ try ForwardOffset<Attacker>.verify(&verifier, at: pos, of: Attacker.self)
+ case .rapunzel:
+ try Rapunzel.verify(&verifier, at: pos, of: Rapunzel.self)
+ case .belle:
+ try BookReader.verify(&verifier, at: pos, of: BookReader.self)
+ case .bookfan:
+ try BookReader.verify(&verifier, at: pos, of: BookReader.self)
+ case .other:
+ try ForwardOffset<String>.verify(&verifier, at: pos, of: String.self)
+ case .unused:
+ try ForwardOffset<String>.verify(&verifier, at: pos, of: String.self)
+ }
+ })
+ _v.finish()
+ }
}
-public class MovieT: NativeTable {
+extension Movie: Encodable {
+
+ enum CodingKeys: String, CodingKey {
+ case mainCharacterType = "main_character_type"
+ case mainCharacter = "main_character"
+ case charactersType = "characters_type"
+ case characters = "characters"
+ }
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ if mainCharacterType != .none_ {
+ try container.encodeIfPresent(mainCharacterType, forKey: .mainCharacterType)
+ }
+ switch mainCharacterType {
+ case .mulan:
+ let _v = mainCharacter(type: Attacker.self)
+ try container.encodeIfPresent(_v, forKey: .mainCharacter)
+ case .rapunzel:
+ let _v = mainCharacter(type: Rapunzel.self)
+ try container.encodeIfPresent(_v, forKey: .mainCharacter)
+ case .belle:
+ let _v = mainCharacter(type: BookReader.self)
+ try container.encodeIfPresent(_v, forKey: .mainCharacter)
+ case .bookfan:
+ let _v = mainCharacter(type: BookReader.self)
+ try container.encodeIfPresent(_v, forKey: .mainCharacter)
+ case .other:
+ let _v = mainCharacter(type: String.self)
+ try container.encodeIfPresent(_v, forKey: .mainCharacter)
+ case .unused:
+ let _v = mainCharacter(type: String.self)
+ try container.encodeIfPresent(_v, forKey: .mainCharacter)
+ default: break;
+ }
+ if charactersCount > 0 {
+ var enumsEncoder = container.nestedUnkeyedContainer(forKey: .charactersType)
+ var contentEncoder = container.nestedUnkeyedContainer(forKey: .characters)
+ for index in 0..<charactersCount {
+ guard let type = charactersType(at: index) else { continue }
+ try enumsEncoder.encode(type)
+ switch type {
+ case .mulan:
+ let _v = characters(at: index, type: Attacker.self)
+ try contentEncoder.encode(_v)
+ case .rapunzel:
+ let _v = characters(at: index, type: Rapunzel.self)
+ try contentEncoder.encode(_v)
+ case .belle:
+ let _v = characters(at: index, type: BookReader.self)
+ try contentEncoder.encode(_v)
+ case .bookfan:
+ let _v = characters(at: index, type: BookReader.self)
+ try contentEncoder.encode(_v)
+ case .other:
+ let _v = characters(at: index, type: String.self)
+ try contentEncoder.encode(_v)
+ case .unused:
+ let _v = characters(at: index, type: String.self)
+ try contentEncoder.encode(_v)
+ default: break;
+ }
+ }
+ }
+ }
+}
+
+public class MovieT: NativeObject {
public var mainCharacter: CharacterUnion?
public var characters: [CharacterUnion?]
@@ -295,34 +679,46 @@
public init(_ _t: inout Movie) {
switch _t.mainCharacterType {
case .mulan:
- var _v = _t.mainCharacter(type: Attacker.self)
- mainCharacter = CharacterUnion(_v?.unpack(), type: .mulan)
+ var _v = _t.mainCharacter(type: Attacker.self)
+ mainCharacter = CharacterUnion(_v?.unpack(), type: .mulan)
case .rapunzel:
- var _v = _t.mainCharacter(type: Rapunzel.self)
- mainCharacter = CharacterUnion(_v?.unpack(), type: .rapunzel)
+ var _v = _t.mainCharacter(type: Rapunzel_Mutable.self)
+ mainCharacter = CharacterUnion(_v?.unpack(), type: .rapunzel)
case .belle:
- var _v = _t.mainCharacter(type: BookReader.self)
- mainCharacter = CharacterUnion(_v?.unpack(), type: .belle)
+ var _v = _t.mainCharacter(type: BookReader_Mutable.self)
+ mainCharacter = CharacterUnion(_v?.unpack(), type: .belle)
case .bookfan:
- var _v = _t.mainCharacter(type: BookReader.self)
- mainCharacter = CharacterUnion(_v?.unpack(), type: .bookfan)
+ var _v = _t.mainCharacter(type: BookReader_Mutable.self)
+ mainCharacter = CharacterUnion(_v?.unpack(), type: .bookfan)
+ case .other:
+ var _v = _t.mainCharacter(type: String.self)
+ mainCharacter = CharacterUnion(_v?.unpack(), type: .other)
+ case .unused:
+ var _v = _t.mainCharacter(type: String.self)
+ mainCharacter = CharacterUnion(_v?.unpack(), type: .unused)
default: break
}
characters = []
for index in 0..<_t.charactersCount {
switch _t.charactersType(at: index) {
case .mulan:
- var _v = _t.characters(at: index, type: Attacker.self)
- characters.append(CharacterUnion(_v?.unpack(), type: .mulan))
+ var _v = _t.characters(at: index, type: Attacker.self)
+ characters.append(CharacterUnion(_v?.unpack(), type: .mulan))
case .rapunzel:
- var _v = _t.characters(at: index, type: Rapunzel.self)
- characters.append(CharacterUnion(_v?.unpack(), type: .rapunzel))
+ var _v = _t.characters(at: index, type: Rapunzel_Mutable.self)
+ characters.append(CharacterUnion(_v?.unpack(), type: .rapunzel))
case .belle:
- var _v = _t.characters(at: index, type: BookReader.self)
- characters.append(CharacterUnion(_v?.unpack(), type: .belle))
+ var _v = _t.characters(at: index, type: BookReader_Mutable.self)
+ characters.append(CharacterUnion(_v?.unpack(), type: .belle))
case .bookfan:
- var _v = _t.characters(at: index, type: BookReader.self)
- characters.append(CharacterUnion(_v?.unpack(), type: .bookfan))
+ var _v = _t.characters(at: index, type: BookReader_Mutable.self)
+ characters.append(CharacterUnion(_v?.unpack(), type: .bookfan))
+ case .other:
+ var _v = _t.characters(at: index, type: String.self)
+ characters.append(CharacterUnion(_v?.unpack(), type: .other))
+ case .unused:
+ var _v = _t.characters(at: index, type: String.self)
+ characters.append(CharacterUnion(_v?.unpack(), type: .unused))
default: break
}
}
diff --git a/tests/FlatBuffers.Test.Swift/Tests/LinuxMain.swift b/tests/FlatBuffers.Test.Swift/Tests/LinuxMain.swift
index 68d7891..d909d07 100644
--- a/tests/FlatBuffers.Test.Swift/Tests/LinuxMain.swift
+++ b/tests/FlatBuffers.Test.Swift/Tests/LinuxMain.swift
@@ -1,5 +1,5 @@
/*
- * Copyright 2020 Google Inc. All rights reserved.
+ * Copyright 2021 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.
diff --git a/tests/FlatBuffers.Test/FlatBuffers.Core.Test.csproj b/tests/FlatBuffers.Test/FlatBuffers.Core.Test.csproj
index bbbd7d8..6cd4e78 100644
--- a/tests/FlatBuffers.Test/FlatBuffers.Core.Test.csproj
+++ b/tests/FlatBuffers.Test/FlatBuffers.Core.Test.csproj
@@ -95,6 +95,9 @@
<Compile Include="..\MyGame\Example\NestedStruct.cs">
<Link>MyGame\Example\NestedStruct.cs</Link>
</Compile>
+ <Compile Include="..\MyGame\Example\LongEnum.cs">
+ <Link>MyGame\Example\LongEnum.cs</Link>
+ </Compile>
<Compile Include="..\MyGame\Example\TestEnum.cs">
<Link>MyGame\Example\TestEnum.cs</Link>
</Compile>
@@ -110,6 +113,9 @@
<Compile Include="..\namespace_test\NamespaceA\NamespaceB\TableInNestedNS.cs">
<Link>NamespaceA\NamespaceB\TableInNestedNS.cs</Link>
</Compile>
+ <Compile Include="..\namespace_test\NamespaceA\NamespaceB\UnionInNestedNS.cs">
+ <Link>NamespaceA\NamespaceB\UnionInNestedNS.cs</Link>
+ </Compile>
<Compile Include="..\namespace_test\NamespaceA\TableInFirstNS.cs">
<Link>NamespaceA\TableInFirstNS.cs</Link>
</Compile>
@@ -134,6 +140,27 @@
<Compile Include="..\optional_scalars\ScalarStuff.cs">
<Link>optional_scalars\ScalarStuff.cs</Link>
</Compile>
+ <Compile Include="..\KeywordTest\ABC.cs">
+ <Link>KeywordTest\ABC.cs</Link>
+ </Compile>
+ <Compile Include="..\KeywordTest\public.cs">
+ <Link>KeywordTest\public.cs</Link>
+ </Compile>
+ <Compile Include="..\KeywordTest\KeywordsInTable.cs">
+ <Link>KeywordTest\KeywordsInTable.cs</Link>
+ </Compile>
+ <Compile Include="..\KeywordTest\KeywordsInUnion.cs">
+ <Link>KeywordTest\KeywordsInUnion.cs</Link>
+ </Compile>
+ <Compile Include="..\nested_namespace_test\nested_namespace_test1_generated.cs">
+ <Link>nested_namespace_test\nested_namespace_test1_generated.cs</Link>
+ </Compile>
+ <Compile Include="..\nested_namespace_test\nested_namespace_test2_generated.cs">
+ <Link>nested_namespace_test\nested_namespace_test2_generated.cs</Link>
+ </Compile>
+ <Compile Include="..\nested_namespace_test\nested_namespace_test3_generated.cs">
+ <Link>nested_namespace_test\nested_namespace_test3_generated.cs</Link>
+ </Compile>
</ItemGroup>
<ItemGroup>
diff --git a/tests/FlatBuffers.Test/FlatBuffers.Test.csproj b/tests/FlatBuffers.Test/FlatBuffers.Test.csproj
index 616ab19..1247599 100644
--- a/tests/FlatBuffers.Test/FlatBuffers.Test.csproj
+++ b/tests/FlatBuffers.Test/FlatBuffers.Test.csproj
@@ -141,6 +141,9 @@
<Compile Include="..\namespace_test\NamespaceA\NamespaceB\TableInNestedNS.cs">
<Link>NamespaceA\NamespaceB\TableInNestedNS.cs</Link>
</Compile>
+ <Compile Include="..\namespace_test\NamespaceA\NamespaceB\UnionInNestedNS.cs">
+ <Link>NamespaceA\NamespaceB\UnionInNestedNS.cs</Link>
+ </Compile>
<Compile Include="..\namespace_test\NamespaceA\TableInFirstNS.cs">
<Link>NamespaceA\TableInFirstNS.cs</Link>
</Compile>
@@ -165,6 +168,27 @@
<Compile Include="..\optional_scalars\ScalarStuff.cs">
<Link>optional_scalars\ScalarStuff.cs</Link>
</Compile>
+ <Compile Include="..\KeywordTest\ABC.cs">
+ <Link>KeywordTest\ABC.cs</Link>
+ </Compile>
+ <Compile Include="..\KeywordTest\public.cs">
+ <Link>KeywordTest\public.cs</Link>
+ </Compile>
+ <Compile Include="..\KeywordTest\KeywordsInTable.cs">
+ <Link>KeywordTest\KeywordsInTable.cs</Link>
+ </Compile>
+ <Compile Include="..\KeywordTest\KeywordsInUnion.cs">
+ <Link>KeywordTest\KeywordsInUnion.cs</Link>
+ </Compile>
+ <Compile Include="..\nested_namespace_test\nested_namespace_test1_generated.cs">
+ <Link>nested_namespace_test\nested_namespace_test1_generated.cs</Link>
+ </Compile>
+ <Compile Include="..\nested_namespace_test\nested_namespace_test2_generated.cs">
+ <Link>nested_namespace_test\nested_namespace_test2_generated.cs</Link>
+ </Compile>
+ <Compile Include="..\nested_namespace_test\nested_namespace_test3_generated.cs">
+ <Link>nested_namespace_test\nested_namespace_test3_generated.cs</Link>
+ </Compile>
<Compile Include="Assert.cs" />
<Compile Include="ByteBufferTests.cs" />
<Compile Include="FlatBufferBuilderTests.cs" />
diff --git a/tests/FlatBuffers.Test/FlatBuffersExampleTests.cs b/tests/FlatBuffers.Test/FlatBuffersExampleTests.cs
index b4093d4..ec3b2ea 100644
--- a/tests/FlatBuffers.Test/FlatBuffersExampleTests.cs
+++ b/tests/FlatBuffers.Test/FlatBuffersExampleTests.cs
@@ -19,6 +19,7 @@
using System.Threading;
using MyGame.Example;
using optional_scalars;
+using KeywordTest;
namespace FlatBuffers.Test
{
@@ -115,13 +116,13 @@
// Dump to output directory so we can inspect later, if needed
#if ENABLE_SPAN_T
var data = fbb.DataBuffer.ToSizedArray();
- string filename = @".tmp/monsterdata_cstest" + (sizePrefix ? "_sp" : "") + ".mon";
+ string filename = @"monsterdata_cstest" + (sizePrefix ? "_sp" : "") + ".mon";
File.WriteAllBytes(filename, data);
#else
using (var ms = fbb.DataBuffer.ToMemoryStream(fbb.DataBuffer.Position, fbb.Offset))
{
var data = ms.ToArray();
- string filename = @".tmp/monsterdata_cstest" + (sizePrefix ? "_sp" : "") + ".mon";
+ string filename = @"monsterdata_cstest" + (sizePrefix ? "_sp" : "") + ".mon";
File.WriteAllBytes(filename, data);
}
#endif
@@ -488,6 +489,26 @@
TestObjectAPI(movie);
}
+ [FlatBuffersTestMethod]
+ public void TestUnionUtility()
+ {
+ var movie = new MovieT
+ {
+ MainCharacter = CharacterUnion.FromRapunzel(new RapunzelT { HairLength = 40 }),
+ Characters = new System.Collections.Generic.List<CharacterUnion>
+ {
+ CharacterUnion.FromMuLan(new AttackerT { SwordAttackDamage = 10 }),
+ CharacterUnion.FromBelle(new BookReaderT { BooksRead = 20 }),
+ CharacterUnion.FromOther("Chip"),
+ },
+ };
+
+ var fbb = new FlatBufferBuilder(100);
+ Movie.FinishMovieBuffer(fbb, Movie.Pack(fbb, movie));
+
+ TestObjectAPI(Movie.GetRootAsMovie(fbb.DataBuffer));
+ }
+
private void AreEqual(Monster a, MonsterT b)
{
Assert.AreEqual(a.Hp, b.Hp);
@@ -1097,5 +1118,39 @@
Assert.AreEqual(OptionalByte.Two, scalarStuff.MaybeEnum);
Assert.AreEqual(OptionalByte.Two, scalarStuff.DefaultEnum);
}
+
+
+ [FlatBuffersTestMethod]
+ public void TestKeywordEscaping() {
+ Assert.AreEqual((int)KeywordTest.@public.NONE, 0);
+
+ Assert.AreEqual((int)KeywordTest.ABC.@void, 0);
+ Assert.AreEqual((int)KeywordTest.ABC.where, 1);
+ Assert.AreEqual((int)KeywordTest.ABC.@stackalloc, 2);
+
+ var fbb = new FlatBufferBuilder(1);
+ var offset = KeywordsInTable.CreateKeywordsInTable(
+ fbb, KeywordTest.ABC.@stackalloc, KeywordTest.@public.NONE);
+ fbb.Finish(offset.Value);
+
+ KeywordsInTable keywordsInTable =
+ KeywordsInTable.GetRootAsKeywordsInTable(fbb.DataBuffer);
+
+ Assert.AreEqual(keywordsInTable.Is, KeywordTest.ABC.@stackalloc);
+ Assert.AreEqual(keywordsInTable.Private, KeywordTest.@public.NONE);
+ }
+
+
+ [FlatBuffersTestMethod]
+ public void AddOptionalEnum_WhenPassNull_ShouldWorkProperly() {
+ var fbb = new FlatBufferBuilder(1);
+ ScalarStuff.StartScalarStuff(fbb);
+ ScalarStuff.AddMaybeEnum(fbb, null);
+ var offset = ScalarStuff.EndScalarStuff(fbb);
+ ScalarStuff.FinishScalarStuffBuffer(fbb, offset);
+
+ ScalarStuff scalarStuff = ScalarStuff.GetRootAsScalarStuff(fbb.DataBuffer);
+ Assert.AreEqual(null, scalarStuff.MaybeEnum);
+ }
}
}
diff --git a/tests/FlatBuffers.Test/NetTest.sh b/tests/FlatBuffers.Test/NetTest.sh
index f8adf29..0c90767 100755
--- a/tests/FlatBuffers.Test/NetTest.sh
+++ b/tests/FlatBuffers.Test/NetTest.sh
@@ -19,12 +19,12 @@
$DOTNET restore -r linux-x64 $PROJ_FILE
# Testing C# on Linux using Mono.
-msbuild -property:Configuration=Release,OutputPath=$TEMP_BIN -verbosity:minimal $PROJ_FILE
+msbuild -property:Configuration=Release,OutputPath=$TEMP_BIN -verbosity:quiet $PROJ_FILE
mono $TEMP_BIN/FlatBuffers.Test.exe
rm -fr $TEMP_BIN
# Repeat with unsafe versions
-msbuild -property:Configuration=Release,UnsafeByteBuffer=true,OutputPath=$TEMP_BIN -verbosity:minimal $PROJ_FILE
+msbuild -property:Configuration=Release,UnsafeByteBuffer=true,OutputPath=$TEMP_BIN -verbosity:quiet $PROJ_FILE
mono $TEMP_BIN/FlatBuffers.Test.exe
rm -fr $TEMP_BIN
@@ -36,17 +36,17 @@
$DOTNET restore -r linux-x64 $CORE_PROJ_FILE
# Testing C# on Linux using .Net Core.
-msbuild -property:Configuration=Release,OutputPath=$TEMP_BIN -verbosity:minimal $CORE_PROJ_FILE
+msbuild -property:Configuration=Release,OutputPath=$TEMP_BIN -verbosity:quiet $CORE_PROJ_FILE
$TEMP_BIN/FlatBuffers.Core.Test.exe
rm -fr $TEMP_BIN
# Repeat with unsafe versions
-msbuild -property:Configuration=Release,UnsafeByteBuffer=true,OutputPath=$TEMP_BIN -verbosity:minimal $CORE_PROJ_FILE
+msbuild -property:Configuration=Release,UnsafeByteBuffer=true,OutputPath=$TEMP_BIN -verbosity:quiet $CORE_PROJ_FILE
$TEMP_BIN/FlatBuffers.Core.Test.exe
rm -fr $TEMP_BIN
# Repeat with SpanT versions
-msbuild -property:Configuration=Release,EnableSpanT=true,OutputPath=$TEMP_BIN -verbosity:minimal $CORE_PROJ_FILE
+msbuild -property:Configuration=Release,EnableSpanT=true,OutputPath=$TEMP_BIN -verbosity:quiet $CORE_PROJ_FILE
$TEMP_BIN/FlatBuffers.Core.Test.exe
rm -fr $TEMP_BIN
diff --git a/tests/GoTest.sh b/tests/GoTest.sh
index 60ef927..9f7ad76 100755
--- a/tests/GoTest.sh
+++ b/tests/GoTest.sh
@@ -19,8 +19,8 @@
go_path=${test_dir}/go_gen
go_src=${go_path}/src
-# Emit Go code for the example schema in the test dir:
-../flatc -g --gen-object-api -I include_test monster_test.fbs
+# Emit Go code for the example schemas in the test dir:
+../flatc -g --gen-object-api -I include_test monster_test.fbs optional_scalars.fbs
# Go requires a particular layout of files in order to link multiple packages.
# Copy flatbuffer Go files to their own package directories to compile the
@@ -29,6 +29,7 @@
mkdir -p ${go_src}/MyGame/Example2
mkdir -p ${go_src}/github.com/google/flatbuffers/go
mkdir -p ${go_src}/flatbuffers_test
+mkdir -p ${go_src}/optional_scalars
cp -a MyGame/*.go ./go_gen/src/MyGame/
cp -a MyGame/Example/*.go ./go_gen/src/MyGame/Example/
@@ -38,6 +39,7 @@
rm ./go_gen/src/MyGame/Example/*_grpc.go
cp -a ../go/* ./go_gen/src/github.com/google/flatbuffers/go
cp -a ./go_test.go ./go_gen/src/flatbuffers_test/
+cp -a optional_scalars/*.go ./go_gen/src/optional_scalars
# Run tests with necessary flags.
# Developers may wish to see more detail by appending the verbosity flag
@@ -47,11 +49,11 @@
# flag -test.bench and the wildcard regexp ".":
# go -test -test.bench=. ...
GOPATH=${go_path} go test flatbuffers_test \
- --test.coverpkg=github.com/google/flatbuffers/go \
+ --coverpkg=github.com/google/flatbuffers/go \
--cpp_data=${test_dir}/monsterdata_test.mon \
--out_data=${test_dir}/monsterdata_go_wire.mon \
- --test.bench=. \
- --test.benchtime=3s \
+ --bench=. \
+ --benchtime=3s \
--fuzz=true \
--fuzz_fields=4 \
--fuzz_objects=10000
diff --git a/tests/JavaScriptFlexBuffersTest.js b/tests/JavaScriptFlexBuffersTest.js
index 11c46c9..d2462c6 100644
--- a/tests/JavaScriptFlexBuffersTest.js
+++ b/tests/JavaScriptFlexBuffersTest.js
@@ -1,9 +1,7 @@
// Run this using JavaScriptTest.sh
-var assert = require('assert');
-var fs = require('fs');
-
-var flexbuffers = require('../js/flexbuffers').flexbuffers;
-global.flexbuffers = flexbuffers;
+import assert from 'assert'
+import fs from 'fs'
+import * as flexbuffers from 'flatbuffers/js/flexbuffers'
function main() {
testSingleValueBuffers();
@@ -16,10 +14,12 @@
testRoundTripWithBuilder();
testDeduplicationOff();
testBugWhereOffestWereStoredAsIntInsteadOfUInt();
+
+ console.log('FlexBuffers test: completed successfully');
}
function testSingleValueBuffers() {
- { // null
+ {
const ref = flexbuffers.toReference(new Uint8Array([0, 0, 1]).buffer);
assert.strictEqual(true, ref.isNull());
}
diff --git a/tests/JavaScriptTest.js b/tests/JavaScriptTest.js
index 2d7afc5..f1fdc69 100644
--- a/tests/JavaScriptTest.js
+++ b/tests/JavaScriptTest.js
@@ -1,13 +1,14 @@
// Run this using JavaScriptTest.sh
-var assert = require('assert');
-var fs = require('fs');
+import assert from 'assert'
+import fs from 'fs'
+import * as flatbuffers from 'flatbuffers'
-var flatbuffers = require('../js/flatbuffers').flatbuffers;
-global.flatbuffers = flatbuffers;
-
-var MyGame = require(process.argv[2]).MyGame;
-
-var isTsTest = !!process.env.FB_TS_TEST;
+import { Monster, MonsterT } from './my-game/example/monster'
+import { Test } from './my-game/example/test'
+import { Stat } from './my-game/example/stat'
+import { Vec3 } from './my-game/example/vec3'
+import { Color } from './my-game/example/color';
+import { Any } from './my-game/example/any';
function main() {
@@ -27,11 +28,8 @@
var fbb = new flatbuffers.Builder(1);
createMonster(fbb);
serializeAndTest(fbb);
+ testObjApiPack(fbb);
- if(isTsTest) {
- testObjApiPack(fbb);
- }
-
// clear the builder, repeat tests
var clearIterations = 100;
var startingCapacity = fbb.bb.capacity();
@@ -39,10 +37,7 @@
fbb.clear();
createMonster(fbb);
serializeAndTest(fbb);
-
- if(isTsTest) {
- testObjApiPack(fbb);
- }
+ testObjApiPack(fbb);
}
// the capacity of our buffer shouldn't increase with the same size payload
assert.strictEqual(fbb.bb.capacity(), startingCapacity);
@@ -52,7 +47,7 @@
fuzzTest1();
testNullStrings();
testSharedStrings();
-
+
console.log('FlatBuffers test: completed successfully');
}
@@ -61,36 +56,42 @@
var str = fbb.createString('MyMonster');
- var inv = MyGame.Example.Monster.createInventoryVector(fbb, [0, 1, 2, 3, 4]);
+ var inv = Monster.createInventoryVector(fbb, [0, 1, 2, 3, 4]);
var fred = fbb.createString('Fred');
- MyGame.Example.Monster.startMonster(fbb);
- MyGame.Example.Monster.addName(fbb, fred);
- var mon2 = MyGame.Example.Monster.endMonster(fbb);
+ Monster.startMonster(fbb);
+ Monster.addName(fbb, fred);
+ var mon2 = Monster.endMonster(fbb);
- MyGame.Example.Monster.startTest4Vector(fbb, 2);
- MyGame.Example.Test.createTest(fbb, 10, 20);
- MyGame.Example.Test.createTest(fbb, 30, 40);
+ Monster.startTest4Vector(fbb, 2);
+ Test.createTest(fbb, 10, 20);
+ Test.createTest(fbb, 30, 40);
var test4 = fbb.endVector();
- var testArrayOfString = MyGame.Example.Monster.createTestarrayofstringVector(fbb, [
+ var testArrayOfString = Monster.createTestarrayofstringVector(fbb, [
fbb.createString('test1'),
fbb.createString('test2')
]);
- MyGame.Example.Monster.startMonster(fbb);
- MyGame.Example.Monster.addPos(fbb, MyGame.Example.Vec3.createVec3(fbb, 1, 2, 3, 3, MyGame.Example.Color.Green, 5, 6));
- MyGame.Example.Monster.addHp(fbb, 80);
- MyGame.Example.Monster.addName(fbb, str);
- MyGame.Example.Monster.addInventory(fbb, inv);
- MyGame.Example.Monster.addTestType(fbb, MyGame.Example.Any.Monster);
- MyGame.Example.Monster.addTest(fbb, mon2);
- MyGame.Example.Monster.addTest4(fbb, test4);
- MyGame.Example.Monster.addTestarrayofstring(fbb, testArrayOfString);
- MyGame.Example.Monster.addTestbool(fbb, true);
- var mon = MyGame.Example.Monster.endMonster(fbb);
+ var testVectorOfLongs = Monster.createVectorOfLongsVector(fbb, [
+ 1n,
+ 101010100n
+ ]);
- MyGame.Example.Monster.finishMonsterBuffer(fbb, mon);
+ Monster.startMonster(fbb);
+ Monster.addPos(fbb, Vec3.createVec3(fbb, 1, 2, 3, 3, Color.Green, 5, 6));
+ Monster.addHp(fbb, 80);
+ Monster.addName(fbb, str);
+ Monster.addInventory(fbb, inv);
+ Monster.addTestType(fbb, Any.Monster);
+ Monster.addTest(fbb, mon2);
+ Monster.addTest4(fbb, test4);
+ Monster.addTestarrayofstring(fbb, testArrayOfString);
+ Monster.addVectorOfLongs(fbb, testVectorOfLongs);
+ Monster.addTestbool(fbb, true);
+ var mon = Monster.endMonster(fbb);
+
+ Monster.finishMonsterBuffer(fbb, mon);
}
function serializeAndTest(fbb) {
@@ -99,7 +100,7 @@
// parser may serialize in a slightly different order than the above
// JavaScript code. They are functionally equivalent though.
- fs.writeFileSync('monsterdata_javascript_wire.mon', new Buffer(fbb.asUint8Array()));
+ fs.writeFileSync('monsterdata_javascript_wire.mon', Buffer.from(fbb.asUint8Array()));
// Tests mutation first. This will verify that we did not trample any other
// part of the byte buffer.
@@ -109,7 +110,7 @@
}
function testMutation(bb) {
- var monster = MyGame.Example.Monster.getRootAsMonster(bb);
+ var monster = Monster.getRootAsMonster(bb);
monster.mutate_hp(120);
assert.strictEqual(monster.hp(), 120);
@@ -126,9 +127,9 @@
function testObjApiPack(fbb) {
fbb.clear();
createMonster(fbb);
- let monster_t = MyGame.Example.Monster.getRootAsMonster(fbb.dataBuffer()).unpack();
+ let monster_t = Monster.getRootAsMonster(fbb.dataBuffer()).unpack();
fbb.clear();
- MyGame.Example.Monster.finishMonsterBuffer(fbb, monster_t.pack(fbb));
+ Monster.finishMonsterBuffer(fbb, monster_t.pack(fbb));
serializeAndTest(fbb);
}
@@ -143,15 +144,15 @@
assert.strictEqual(pos.y, 2);
assert.strictEqual(pos.z, 3);
assert.strictEqual(pos.test1, 3);
- assert.strictEqual(pos.test2, MyGame.Example.Color.Green);
+ assert.strictEqual(pos.test2, Color.Green);
let test3 = pos.test3;
assert.strictEqual(test3.a, 5);
assert.strictEqual(test3.b, 6);
- assert.strictEqual(monster.testType, MyGame.Example.Any.Monster);
+ assert.strictEqual(monster.testType, Any.Monster);
let monster2 = monster.test;
assert.strictEqual(monster2 != null, true);
- assert.strictEqual(monster2 instanceof MyGame.Example.MonsterT, true);
+ assert.strictEqual(monster2 instanceof MonsterT, true);
assert.strictEqual(monster2.name, 'Fred');
assert.strictEqual(monster.inventory.length, 5);
@@ -174,9 +175,9 @@
}
function testBuffer(bb) {
- assert.ok(MyGame.Example.Monster.bufferHasIdentifier(bb));
+ assert.ok(Monster.bufferHasIdentifier(bb));
- var monster = MyGame.Example.Monster.getRootAsMonster(bb);
+ var monster = Monster.getRootAsMonster(bb);
assert.strictEqual(monster.hp(), 80);
assert.strictEqual(monster.mana(), 150); // default
@@ -188,13 +189,13 @@
assert.strictEqual(pos.y(), 2);
assert.strictEqual(pos.z(), 3);
assert.strictEqual(pos.test1(), 3);
- assert.strictEqual(pos.test2(), MyGame.Example.Color.Green);
+ assert.strictEqual(pos.test2(), Color.Green);
var t = pos.test3();
assert.strictEqual(t.a(), 5);
assert.strictEqual(t.b(), 6);
- assert.strictEqual(monster.testType(), MyGame.Example.Any.Monster);
- var monster2 = new MyGame.Example.Monster();
+ assert.strictEqual(monster.testType(), Any.Monster);
+ var monster2 = new Monster();
assert.strictEqual(monster.test(monster2) != null, true);
assert.strictEqual(monster2.name(), 'Fred');
@@ -212,6 +213,12 @@
}
assert.strictEqual(invsum2, 10);
+ let longSum = 0n;
+ for (let idx = 0; idx < monster.vectorOfLongsLength(); ++idx) {
+ longSum += monster.vectorOfLongs(idx);
+ }
+ assert.strictEqual(longSum, 101010101n);
+
var test_0 = monster.test4(0);
var test_1 = monster.test4(1);
assert.strictEqual(monster.test4Length(), 2);
@@ -223,60 +230,57 @@
assert.strictEqual(monster.testbool(), true);
- if(isTsTest) {
- let monster_t = monster.unpack();
- testObjApiUnpack(monster_t);
+ let monster_t = monster.unpack();
+ testObjApiUnpack(monster_t);
- let monster2_t = new MyGame.Example.MonsterT();
- monster.unpackTo(monster2_t);
- testObjApiUnpack(monster2_t);
- }
+ let monster2_t = new MonsterT();
+ monster.unpackTo(monster2_t);
+ testObjApiUnpack(monster2_t);
}
function test64bit() {
var fbb = new flatbuffers.Builder();
var required = fbb.createString('required');
- MyGame.Example.Stat.startStat(fbb);
- var stat2 = MyGame.Example.Stat.endStat(fbb);
+ Stat.startStat(fbb);
+ var stat2 = Stat.endStat(fbb);
- MyGame.Example.Monster.startMonster(fbb);
- MyGame.Example.Monster.addName(fbb, required);
- MyGame.Example.Monster.addTestempty(fbb, stat2);
- var mon2 = MyGame.Example.Monster.endMonster(fbb);
+ Monster.startMonster(fbb);
+ Monster.addName(fbb, required);
+ Monster.addTestempty(fbb, stat2);
+ var mon2 = Monster.endMonster(fbb);
- MyGame.Example.Stat.startStat(fbb);
- // 2541551405100253985 = 0x87654321(low part) + 0x23456789 * 0x100000000(high part);
- MyGame.Example.Stat.addVal(fbb, new flatbuffers.Long(0x87654321, 0x23456789)); // the low part is Uint32
- var stat = MyGame.Example.Stat.endStat(fbb);
+ Stat.startStat(fbb);
+ // 2541551405100253985 = 0x2345678987654321
+ Stat.addVal(fbb, 0x2345678987654321n);
+ var stat = Stat.endStat(fbb);
- MyGame.Example.Monster.startMonster(fbb);
- MyGame.Example.Monster.addName(fbb, required);
- MyGame.Example.Monster.addEnemy(fbb, mon2);
- MyGame.Example.Monster.addTestempty(fbb, stat);
- var mon = MyGame.Example.Monster.endMonster(fbb);
+ Monster.startMonster(fbb);
+ Monster.addName(fbb, required);
+ Monster.addEnemy(fbb, mon2);
+ Monster.addTestempty(fbb, stat);
+ var mon = Monster.endMonster(fbb);
- MyGame.Example.Monster.finishMonsterBuffer(fbb, mon);
+ Monster.finishMonsterBuffer(fbb, mon);
var bytes = fbb.asUint8Array();
////////////////////////////////////////////////////////////////
var bb = new flatbuffers.ByteBuffer(bytes);
- assert.ok(MyGame.Example.Monster.bufferHasIdentifier(bb));
- var mon = MyGame.Example.Monster.getRootAsMonster(bb);
+ assert.ok(Monster.bufferHasIdentifier(bb));
+ var mon = Monster.getRootAsMonster(bb);
var stat = mon.testempty();
assert.strictEqual(stat != null, true);
assert.strictEqual(stat.val() != null, true);
- assert.strictEqual(stat.val().toFloat64(), 2541551405100253985);
+ assert.strictEqual(stat.val(), 2541551405100253985n);
var mon2 = mon.enemy();
assert.strictEqual(mon2 != null, true);
stat = mon2.testempty();
assert.strictEqual(stat != null, true);
assert.strictEqual(stat.val() != null, true);
- assert.strictEqual(stat.val().low, 0); // default value
- assert.strictEqual(stat.val().high, 0);
+ assert.strictEqual(stat.val(), 0n); // default value
}
function testUnicode() {
@@ -285,19 +289,19 @@
// Test reading
function testReadingUnicode(bb) {
- var monster = MyGame.Example.Monster.getRootAsMonster(bb);
+ var monster = Monster.getRootAsMonster(bb);
assert.strictEqual(monster.name(), json.name);
- assert.deepEqual(new Buffer(monster.name(flatbuffers.Encoding.UTF8_BYTES)), new Buffer(json.name));
+ assert.deepEqual(Buffer.from(monster.name(flatbuffers.Encoding.UTF8_BYTES)), Buffer.from(json.name));
assert.strictEqual(monster.testarrayoftablesLength(), json.testarrayoftables.length);
json.testarrayoftables.forEach(function(table, i) {
var value = monster.testarrayoftables(i);
assert.strictEqual(value.name(), table.name);
- assert.deepEqual(new Buffer(value.name(flatbuffers.Encoding.UTF8_BYTES)), new Buffer(table.name));
+ assert.deepEqual(Buffer.from(value.name(flatbuffers.Encoding.UTF8_BYTES)), Buffer.from(table.name));
});
assert.strictEqual(monster.testarrayofstringLength(), json.testarrayofstring.length);
json.testarrayofstring.forEach(function(string, i) {
assert.strictEqual(monster.testarrayofstring(i), string);
- assert.deepEqual(new Buffer(monster.testarrayofstring(i, flatbuffers.Encoding.UTF8_BYTES)), new Buffer(string));
+ assert.deepEqual(Buffer.from(monster.testarrayofstring(i, flatbuffers.Encoding.UTF8_BYTES)), Buffer.from(string));
});
}
testReadingUnicode(new flatbuffers.ByteBuffer(new Uint8Array(correct)));
@@ -306,20 +310,20 @@
var fbb = new flatbuffers.Builder();
var name = fbb.createString(json.name);
var testarrayoftablesOffsets = json.testarrayoftables.map(function(table) {
- var name = fbb.createString(new Uint8Array(new Buffer(table.name)));
- MyGame.Example.Monster.startMonster(fbb);
- MyGame.Example.Monster.addName(fbb, name);
- return MyGame.Example.Monster.endMonster(fbb);
+ var name = fbb.createString(new Uint8Array(Buffer.from(table.name)));
+ Monster.startMonster(fbb);
+ Monster.addName(fbb, name);
+ return Monster.endMonster(fbb);
});
- var testarrayoftablesOffset = MyGame.Example.Monster.createTestarrayoftablesVector(fbb,
+ var testarrayoftablesOffset = Monster.createTestarrayoftablesVector(fbb,
testarrayoftablesOffsets);
- var testarrayofstringOffset = MyGame.Example.Monster.createTestarrayofstringVector(fbb,
+ var testarrayofstringOffset = Monster.createTestarrayofstringVector(fbb,
json.testarrayofstring.map(function(string) { return fbb.createString(string); }));
- MyGame.Example.Monster.startMonster(fbb);
- MyGame.Example.Monster.addTestarrayofstring(fbb, testarrayofstringOffset);
- MyGame.Example.Monster.addTestarrayoftables(fbb, testarrayoftablesOffset);
- MyGame.Example.Monster.addName(fbb, name);
- MyGame.Example.Monster.finishSizePrefixedMonsterBuffer(fbb, MyGame.Example.Monster.endMonster(fbb));
+ Monster.startMonster(fbb);
+ Monster.addTestarrayofstring(fbb, testarrayofstringOffset);
+ Monster.addTestarrayoftables(fbb, testarrayoftablesOffset);
+ Monster.addName(fbb, name);
+ Monster.finishSizePrefixedMonsterBuffer(fbb, Monster.endMonster(fbb));
var bb = new flatbuffers.ByteBuffer(fbb.asUint8Array())
bb.setPosition(4);
testReadingUnicode(bb);
@@ -366,8 +370,8 @@
var ushort_val = 0xFEEE;
var int_val = 0x83333333 | 0;
var uint_val = 0xFDDDDDDD;
- var long_val = new flatbuffers.Long(0x44444444, 0x84444444);
- var ulong_val = new flatbuffers.Long(0xCCCCCCCC, 0xFCCCCCCC);
+ var long_val = BigInt.asIntN(64, 0x8444444444444444n);
+ var ulong_val = BigInt.asUintN(64, 0xFCCCCCCCCCCCCCCCn);
var float_val = new Float32Array([3.14159])[0];
var double_val = 3.14159265359;
@@ -388,16 +392,16 @@
for (var f = 0; f < fields_per_object; f++) {
var choice = lcg_rand() % test_values_max;
switch (choice) {
- case 0: builder.addFieldInt8(f, bool_val, 0); break;
- case 1: builder.addFieldInt8(f, char_val, 0); break;
- case 2: builder.addFieldInt8(f, uchar_val, 0); break;
- case 3: builder.addFieldInt16(f, short_val, 0); break;
+ case 0: builder.addFieldInt8(f, bool_val, 0); break;
+ case 1: builder.addFieldInt8(f, char_val, 0); break;
+ case 2: builder.addFieldInt8(f, uchar_val, 0); break;
+ case 3: builder.addFieldInt16(f, short_val, 0); break;
case 4: builder.addFieldInt16(f, ushort_val, 0); break;
- case 5: builder.addFieldInt32(f, int_val, 0); break;
- case 6: builder.addFieldInt32(f, uint_val, 0); break;
- case 7: builder.addFieldInt64(f, long_val, flatbuffers.Long.ZERO); break;
- case 8: builder.addFieldInt64(f, ulong_val, flatbuffers.Long.ZERO); break;
- case 9: builder.addFieldFloat32(f, float_val, 0); break;
+ case 5: builder.addFieldInt32(f, int_val, 0); break;
+ case 6: builder.addFieldInt32(f, uint_val, 0); break;
+ case 7: builder.addFieldInt64(f, long_val, 0n); break;
+ case 8: builder.addFieldInt64(f, ulong_val, 0n); break;
+ case 9: builder.addFieldFloat32(f, float_val, 0); break;
case 10: builder.addFieldFloat64(f, double_val, 0); break;
}
}
@@ -430,8 +434,8 @@
case 4: assert.strictEqual(view.getUint16(field_offset, true), ushort_val); break;
case 5: assert.strictEqual(view.getInt32(field_offset, true), int_val); break;
case 6: assert.strictEqual(view.getUint32(field_offset, true), uint_val); break;
- case 7: assert.strictEqual(view.getInt32(field_offset, true), long_val.low); assert.strictEqual(view.getInt32(field_offset + 4, true), long_val.high); break;
- case 8: assert.strictEqual(view.getInt32(field_offset, true), ulong_val.low); assert.strictEqual(view.getInt32(field_offset + 4, true), ulong_val.high); break;
+ case 7: assert.strictEqual(view.getBigInt64(field_offset, true), long_val); break;
+ case 8: assert.strictEqual(view.getBigUint64(field_offset, true), ulong_val); break;
case 9: assert.strictEqual(view.getFloat32(field_offset, true), float_val); break;
case 10: assert.strictEqual(view.getFloat64(field_offset, true), double_val); break;
}
diff --git a/tests/JavaScriptTest.sh b/tests/JavaScriptTest.sh
deleted file mode 100755
index 707af71..0000000
--- a/tests/JavaScriptTest.sh
+++ /dev/null
@@ -1,24 +0,0 @@
-#!/bin/sh
-#
-# Copyright 2016 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.
-
-pushd "$(dirname $0)" >/dev/null
-../flatc -b -I include_test monster_test.fbs unicode_test.json
-../flatc --js -o js --gen-name-strings --gen-mutable --no-fb-import -I include_test monster_test.fbs
-node JavaScriptTest ./js/monster_test_generated
-
-../flatc --js --gen-name-strings -o js --no-fb-import union_vector/union_vector.fbs
-node JavaScriptUnionVectorTest ./js/union_vector_generated
-node JavaScriptFlexBuffersTest
diff --git a/tests/JavaScriptUnionVectorTest.js b/tests/JavaScriptUnionVectorTest.js
index f03a327..b80e37f 100644
--- a/tests/JavaScriptUnionVectorTest.js
+++ b/tests/JavaScriptUnionVectorTest.js
@@ -1,16 +1,17 @@
-var assert = require('assert');
+import assert from 'assert'
+import * as flatbuffers from 'flatbuffers'
-var flatbuffers = require('../js/flatbuffers').flatbuffers;
-var Test = require(process.argv[2]);
-
-var isTsTest = !!process.env.FB_TS_TEST;
+import { Character } from './union_vector/character'
+import { BookReader, BookReaderT } from './union_vector/book-reader'
+import { Attacker, AttackerT } from './union_vector/attacker'
+import { Movie, MovieT } from './union_vector/movie'
var charTypes = [
- Test.Character.Belle,
- Test.Character.MuLan,
- Test.Character.BookFan,
+ Character.Belle,
+ Character.MuLan,
+ Character.BookFan,
+ Character.Other
];
-if(isTsTest) { charTypes.push(Test.Character.Other); }
function testMovieBuf(movie) {
assert.strictEqual(movie.charactersTypeLength(), charTypes.length);
@@ -20,19 +21,17 @@
assert.strictEqual(movie.charactersType(i), charTypes[i]);
}
- var bookReader7 = movie.characters(0, new Test.BookReader());
+ var bookReader7 = movie.characters(0, new BookReader());
assert.strictEqual(bookReader7.booksRead(), 7);
- var attacker = movie.characters(1, new Test.Attacker());
+ var attacker = movie.characters(1, new Attacker());
assert.strictEqual(attacker.swordAttackDamage(), 5);
- var bookReader2 = movie.characters(2, new Test.BookReader());
+ var bookReader2 = movie.characters(2, new BookReader());
assert.strictEqual(bookReader2.booksRead(), 2);
- if(isTsTest) {
- var other = movie.characters(3, '');
- assert.strictEqual(other, "I am other");
- }
+ var other = movie.characters(3, '');
+ assert.strictEqual(other, "I am other");
}
function testMovieUnpack(movie) {
@@ -44,58 +43,45 @@
}
var bookReader7 = movie.characters[0];
- assert.strictEqual(bookReader7 instanceof Test.BookReaderT, true);
+ assert.strictEqual(bookReader7 instanceof BookReaderT, true);
assert.strictEqual(bookReader7.booksRead, 7);
-
+
var attacker = movie.characters[1];
- assert.strictEqual(attacker instanceof Test.AttackerT, true);
+ assert.strictEqual(attacker instanceof AttackerT, true);
assert.strictEqual(attacker.swordAttackDamage, 5);
-
+
var bookReader2 = movie.characters[2];
- assert.strictEqual(bookReader2 instanceof Test.BookReaderT, true);
+ assert.strictEqual(bookReader2 instanceof BookReaderT, true);
assert.strictEqual(bookReader2.booksRead, 2);
- if(isTsTest) {
- var other = movie.characters[3];
- assert.strictEqual(other, "I am other");
- }
+ var other = movie.characters[3];
+ assert.strictEqual(other, "I am other");
}
function createMovie(fbb) {
- Test.Attacker.startAttacker(fbb);
- Test.Attacker.addSwordAttackDamage(fbb, 5);
- var attackerOffset = Test.Attacker.endAttacker(fbb);
+ Attacker.startAttacker(fbb);
+ Attacker.addSwordAttackDamage(fbb, 5);
+ var attackerOffset = Attacker.endAttacker(fbb);
- var charTypesOffset = Test.Movie.createCharactersTypeVector(fbb, charTypes);
+ var charTypesOffset = Movie.createCharactersTypeVector(fbb, charTypes);
var charsOffset = 0;
- if(isTsTest) {
- let otherOffset = fbb.createString("I am other");
+ let otherOffset = fbb.createString("I am other");
- charsOffset = Test.Movie.createCharactersVector(
- fbb,
- [
- Test.BookReader.createBookReader(fbb, 7),
- attackerOffset,
- Test.BookReader.createBookReader(fbb, 2),
- otherOffset
- ]
- );
- } else {
- charsOffset = Test.Movie.createCharactersVector(
- fbb,
- [
- Test.BookReader.createBookReader(fbb, 7),
- attackerOffset,
- Test.BookReader.createBookReader(fbb, 2)
- ]
- );
- }
+ charsOffset = Movie.createCharactersVector(
+ fbb,
+ [
+ BookReader.createBookReader(fbb, 7),
+ attackerOffset,
+ BookReader.createBookReader(fbb, 2),
+ otherOffset
+ ]
+ );
- Test.Movie.startMovie(fbb);
- Test.Movie.addCharactersType(fbb, charTypesOffset);
- Test.Movie.addCharacters(fbb, charsOffset);
- Test.Movie.finishMovieBuffer(fbb, Test.Movie.endMovie(fbb))
+ Movie.startMovie(fbb);
+ Movie.addCharactersType(fbb, charTypesOffset);
+ Movie.addCharacters(fbb, charsOffset);
+ Movie.finishMovieBuffer(fbb, Movie.endMovie(fbb))
}
function main() {
@@ -105,22 +91,20 @@
var buf = new flatbuffers.ByteBuffer(fbb.asUint8Array());
- var movie = Test.Movie.getRootAsMovie(buf);
+ var movie = Movie.getRootAsMovie(buf);
testMovieBuf(movie);
- if(isTsTest) {
- testMovieUnpack(movie.unpack());
+ testMovieUnpack(movie.unpack());
- var movie_to = new Test.MovieT();
- movie.unpackTo(movie_to);
- testMovieUnpack(movie_to);
+ var movie_to = new MovieT();
+ movie.unpackTo(movie_to);
+ testMovieUnpack(movie_to);
- fbb.clear();
- Test.Movie.finishMovieBuffer(fbb, movie_to.pack(fbb));
- var unpackBuf = new flatbuffers.ByteBuffer(fbb.asUint8Array());
- testMovieBuf(Test.Movie.getRootAsMovie(unpackBuf));
- }
-
+ fbb.clear();
+ Movie.finishMovieBuffer(fbb, movie_to.pack(fbb));
+ var unpackBuf = new flatbuffers.ByteBuffer(fbb.asUint8Array());
+ testMovieBuf(Movie.getRootAsMovie(unpackBuf));
+
console.log('FlatBuffers union vector test: completed successfully');
}
diff --git a/tests/JavaTest.java b/tests/JavaTest.java
index 23ebb5b..0f2ad12 100644
--- a/tests/JavaTest.java
+++ b/tests/JavaTest.java
@@ -109,6 +109,8 @@
TestScalarOptional();
+ TestPackUnpack(bb);
+
System.out.println("FlatBuffers test: completed successfully");
}
@@ -862,6 +864,27 @@
TestEq((byte)-1, result[3]);
}
+ public static void testSingleElementLongBlob() {
+
+ // verifies blobs of up to 2^16 in length
+ for (int i = 2; i <= 1<<16; i = i<<1) {
+ byte[] input = new byte[i-1];
+ for (int index = 0; index < input.length; index++) {
+ input[index] = (byte)(index % 64);
+ }
+
+ FlexBuffersBuilder builder = new FlexBuffersBuilder();
+ builder.putBlob(input);
+ ByteBuffer b = builder.finish();
+ FlexBuffers.Reference r = FlexBuffers.getRoot(b);
+ byte[] result = r.asBlob().getBytes();
+
+ for (int index = 0; index < input.length; index++) {
+ TestEq((byte)(index % 64), result[index]);
+ }
+ }
+ }
+
public static void testSingleElementUByte() {
FlexBuffersBuilder builder = new FlexBuffersBuilder();
builder.putUInt(0xFF);
@@ -1038,7 +1061,7 @@
FlexBuffersBuilder failBuilder = new FlexBuffersBuilder(ByteBuffer.allocate(1));
failBuilder.putString(someString);
}
-
+
public static void testFlexBuffersUtf8Map() {
FlexBuffersBuilder builder = new FlexBuffersBuilder(ByteBuffer.allocate(512),
FlexBuffersBuilder.BUILDER_FLAG_SHARE_KEYS_AND_STRINGS);
@@ -1074,6 +1097,30 @@
TestEq(m.get(key4).asString(), utf8keys[4]);
}
+ public static void testFlexBuffersMapLookup() {
+ FlexBuffersBuilder builder = new FlexBuffersBuilder(ByteBuffer.allocate(512),
+ FlexBuffersBuilder.BUILDER_FLAG_SHARE_KEYS_AND_STRINGS);
+
+ String key0 = "123";
+ String key1 = "1234";
+ String key2 = "12345";
+ String[] keys = new String[]{key0, key1, key2};
+
+ int map = builder.startMap();
+
+ for (int i=0; i< keys.length; i++) {
+ builder.putString(keys[i], keys[i]); // Testing key and string reuse.
+ }
+ builder.endMap(null, map);
+ builder.finish();
+
+ FlexBuffers.Map m = FlexBuffers.getRoot(builder.getBuffer()).asMap();
+ for (int i=0; i< keys.length; i++) {
+ TestEq(m.get(keys[i]).asString(), keys[i]);
+ TestEq(m.get(keys[i].getBytes(StandardCharsets.UTF_8)).asString(), keys[i]);
+ }
+ }
+
public static void TestFlexBuffers() {
testSingleElementByte();
testSingleElementShort();
@@ -1084,6 +1131,7 @@
testSingleElementSmallString();
testSingleElementBigString();
testSingleElementBlob();
+ testSingleElementLongBlob();
testSingleElementVector();
testSingleFixedTypeVector();
testSingleElementUShort();
@@ -1097,6 +1145,7 @@
testDeprecatedTypedVectorString();
testBuilderGrowth();
testFlexBuffersUtf8Map();
+ testFlexBuffersMapLookup();
}
static void TestVectorOfBytes() {
@@ -1380,6 +1429,122 @@
TestEq(scalarStuff.hasMaybeEnum(), true);
}
+ static void TestObject(MonsterT monster) {
+ TestEq(monster.getHp(), (short) 80);
+ TestEq(monster.getMana(), (short) 150); // default
+
+ TestEq(monster.getName(), "MyMonster");
+ TestEq(monster.getColor(), Color.Blue);
+ // monster.friendly() // can't access, deprecated
+
+ Vec3T pos = monster.getPos();
+ TestEq(pos.getX(), 1.0f);
+ TestEq(pos.getY(), 2.0f);
+ TestEq(pos.getZ(), 3.0f);
+ TestEq(pos.getTest1(), 3.0);
+ // issue: int != byte
+ TestEq(pos.getTest2(), (int) Color.Green);
+ TestT t = pos.getTest3();
+ TestEq(t.getA(), (short) 5);
+ TestEq(t.getB(), (byte) 6);
+
+ TestEq(monster.getTest().getType(), (byte) Any.Monster);
+ MonsterT monster2 = (MonsterT) monster.getTest().getValue();
+ TestEq(monster2 != null, true);
+ TestEq(monster2.getName(), "Fred");
+
+ int[] inv = monster.getInventory();
+ TestEq(inv.length, 5);
+ int[] expInv = {0, 1, 2, 3, 4};
+ for (int i = 0; i < inv.length; i++)
+ TestEq(expInv[i], inv[i]);
+
+ TestT[] test4 = monster.getTest4();
+ TestT test_0 = test4[0];
+ TestT test_1 = test4[1];
+ TestEq(test4.length, 2);
+ TestEq(test_0.getA(), (short) 10);
+ TestEq(test_0.getB(), (byte) 20);
+ TestEq(test_1.getA(), (short) 30);
+ TestEq(test_1.getB(), (byte) 40);
+
+ String[] testarrayofstring = monster.getTestarrayofstring();
+ TestEq(testarrayofstring.length, 2);
+ TestEq(testarrayofstring[0], "test1");
+ TestEq(testarrayofstring[1], "test2");
+
+ MonsterT[] testarrayoftables = monster.getTestarrayoftables();
+ TestEq(testarrayoftables.length, 0);
+
+ MonsterT enemy = monster.getEnemy();
+ TestEq(enemy != null, true);
+ TestEq(enemy.getName(), "Fred");
+
+ int[] testnestedflatbuffer = monster.getTestnestedflatbuffer();
+ TestEq(testnestedflatbuffer.length, 0);
+
+ TestEq(monster.getTestempty() == null, true);
+
+ TestEq(monster.getTestbool(), true);
+
+ boolean[] testarrayofbools = monster.getTestarrayofbools();
+ TestEq(testarrayofbools.length, 3);
+ TestEq(testarrayofbools[0], true);
+ TestEq(testarrayofbools[1], false);
+ TestEq(testarrayofbools[2], true);
+
+ TestEq(monster.getTestf(), 3.14159f);
+ TestEq(monster.getTestf2(), 3.0f);
+ TestEq(monster.getTestf3(), 0.0f);
+ TestEq(monster.getTestf3(), 0.0f);
+
+ AbilityT[] testarrayofsortedstruct = monster.getTestarrayofsortedstruct();
+ TestEq(testarrayofsortedstruct.length, 3);
+ TestEq(testarrayofsortedstruct[0].getId(), (long) 0);
+ TestEq(testarrayofsortedstruct[1].getId(), (long) 1);
+ TestEq(testarrayofsortedstruct[2].getId(), (long) 5);
+ TestEq(testarrayofsortedstruct[0].getDistance(), (long) 45);
+ TestEq(testarrayofsortedstruct[1].getDistance(), (long) 21);
+ TestEq(testarrayofsortedstruct[2].getDistance(), (long) 12);
+
+ int[] flex = monster.getFlex();
+ TestEq(flex.length, 0);
+
+ long[] vectorOfLongs = monster.getVectorOfLongs();
+ TestEq(vectorOfLongs.length, 5);
+ long l = 1;
+ for (int i = 0; i < vectorOfLongs.length; i++) {
+ TestEq(vectorOfLongs[i], l);
+ l *= 100;
+ }
+
+ double[] vectorOfDoubles = monster.getVectorOfDoubles();
+ TestEq(vectorOfDoubles.length, 3);
+ TestEq(vectorOfDoubles[0], -1.7976931348623157E308);
+ TestEq(vectorOfDoubles[1], 0.0);
+ TestEq(vectorOfDoubles[2], 1.7976931348623157E308);
+
+ TestEq(monster.getParentNamespaceTest() == null, true);
+ ReferrableT[] vectorOfReferrables = monster.getVectorOfReferrables();
+ TestEq(vectorOfReferrables.length, 0);
+
+ TestEq(monster.getSignedEnum(), (byte) -1);
+ }
+
+ static void TestPackUnpack(ByteBuffer bb) {
+ Monster m = Monster.getRootAsMonster(bb);
+ MonsterT mObject = m.unpack();
+ TestObject(mObject);
+ FlatBufferBuilder fbb = new FlatBufferBuilder();
+ int monster = Monster.pack(fbb, mObject);
+ Monster.finishMonsterBuffer(fbb, monster);
+ TestBuffer(fbb.dataBuffer());
+
+ byte[] bytes = mObject.serializeToBinary();
+ MonsterT newMonsterT = MonsterT.deserializeFromBinary(bytes);
+ TestObject(newMonsterT);
+ }
+
static <T> void TestEq(T a, T b) {
if ((a == null && a != b) || (a != null && !a.equals(b))) {
System.out.println("" + a.getClass().getName() + " " + b.getClass().getName());
diff --git a/tests/KeywordTest/ABC.cs b/tests/KeywordTest/ABC.cs
new file mode 100644
index 0000000..3d7ceff
--- /dev/null
+++ b/tests/KeywordTest/ABC.cs
@@ -0,0 +1,17 @@
+// <auto-generated>
+// automatically generated by the FlatBuffers compiler, do not modify
+// </auto-generated>
+
+namespace KeywordTest
+{
+
+[Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))]
+public enum ABC : int
+{
+ @void = 0,
+ where = 1,
+ @stackalloc = 2,
+};
+
+
+}
diff --git a/tests/KeywordTest/KeywordsInTable.cs b/tests/KeywordTest/KeywordsInTable.cs
new file mode 100644
index 0000000..495671b
--- /dev/null
+++ b/tests/KeywordTest/KeywordsInTable.cs
@@ -0,0 +1,85 @@
+// <auto-generated>
+// automatically generated by the FlatBuffers compiler, do not modify
+// </auto-generated>
+
+namespace KeywordTest
+{
+
+using global::System;
+using global::System.Collections.Generic;
+using global::FlatBuffers;
+
+public struct KeywordsInTable : IFlatbufferObject
+{
+ private Table __p;
+ public ByteBuffer ByteBuffer { get { return __p.bb; } }
+ public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_2_0_0(); }
+ public static KeywordsInTable GetRootAsKeywordsInTable(ByteBuffer _bb) { return GetRootAsKeywordsInTable(_bb, new KeywordsInTable()); }
+ public static KeywordsInTable GetRootAsKeywordsInTable(ByteBuffer _bb, KeywordsInTable obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); }
+ public void __init(int _i, ByteBuffer _bb) { __p = new Table(_i, _bb); }
+ public KeywordsInTable __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; }
+
+ public KeywordTest.ABC Is { get { int o = __p.__offset(4); return o != 0 ? (KeywordTest.ABC)__p.bb.GetInt(o + __p.bb_pos) : KeywordTest.ABC.@void; } }
+ public bool MutateIs(KeywordTest.ABC @is) { int o = __p.__offset(4); if (o != 0) { __p.bb.PutInt(o + __p.bb_pos, (int)@is); return true; } else { return false; } }
+ public KeywordTest.@public Private { get { int o = __p.__offset(6); return o != 0 ? (KeywordTest.@public)__p.bb.GetInt(o + __p.bb_pos) : KeywordTest.@public.NONE; } }
+ public bool MutatePrivate(KeywordTest.@public @private) { int o = __p.__offset(6); if (o != 0) { __p.bb.PutInt(o + __p.bb_pos, (int)@private); return true; } else { return false; } }
+ public int Type { get { int o = __p.__offset(8); return o != 0 ? __p.bb.GetInt(o + __p.bb_pos) : (int)0; } }
+ public bool MutateType(int type) { int o = __p.__offset(8); if (o != 0) { __p.bb.PutInt(o + __p.bb_pos, type); return true; } else { return false; } }
+
+ public static Offset<KeywordTest.KeywordsInTable> CreateKeywordsInTable(FlatBufferBuilder builder,
+ KeywordTest.ABC @is = KeywordTest.ABC.@void,
+ KeywordTest.@public @private = KeywordTest.@public.NONE,
+ int type = 0) {
+ builder.StartTable(3);
+ KeywordsInTable.AddType(builder, type);
+ KeywordsInTable.AddPrivate(builder, @private);
+ KeywordsInTable.AddIs(builder, @is);
+ return KeywordsInTable.EndKeywordsInTable(builder);
+ }
+
+ public static void StartKeywordsInTable(FlatBufferBuilder builder) { builder.StartTable(3); }
+ public static void AddIs(FlatBufferBuilder builder, KeywordTest.ABC @is) { builder.AddInt(0, (int)@is, 0); }
+ public static void AddPrivate(FlatBufferBuilder builder, KeywordTest.@public @private) { builder.AddInt(1, (int)@private, 0); }
+ public static void AddType(FlatBufferBuilder builder, int type) { builder.AddInt(2, type, 0); }
+ public static Offset<KeywordTest.KeywordsInTable> EndKeywordsInTable(FlatBufferBuilder builder) {
+ int o = builder.EndTable();
+ return new Offset<KeywordTest.KeywordsInTable>(o);
+ }
+ public KeywordsInTableT UnPack() {
+ var _o = new KeywordsInTableT();
+ this.UnPackTo(_o);
+ return _o;
+ }
+ public void UnPackTo(KeywordsInTableT _o) {
+ _o.Is = this.Is;
+ _o.Private = this.Private;
+ _o.Type = this.Type;
+ }
+ public static Offset<KeywordTest.KeywordsInTable> Pack(FlatBufferBuilder builder, KeywordsInTableT _o) {
+ if (_o == null) return default(Offset<KeywordTest.KeywordsInTable>);
+ return CreateKeywordsInTable(
+ builder,
+ _o.Is,
+ _o.Private,
+ _o.Type);
+ }
+}
+
+public class KeywordsInTableT
+{
+ [Newtonsoft.Json.JsonProperty("is")]
+ public KeywordTest.ABC Is { get; set; }
+ [Newtonsoft.Json.JsonProperty("private")]
+ public KeywordTest.@public Private { get; set; }
+ [Newtonsoft.Json.JsonProperty("type")]
+ public int Type { get; set; }
+
+ public KeywordsInTableT() {
+ this.Is = KeywordTest.ABC.@void;
+ this.Private = KeywordTest.@public.NONE;
+ this.Type = 0;
+ }
+}
+
+
+}
diff --git a/tests/KeywordTest/KeywordsInUnion.cs b/tests/KeywordTest/KeywordsInUnion.cs
new file mode 100644
index 0000000..68c050e
--- /dev/null
+++ b/tests/KeywordTest/KeywordsInUnion.cs
@@ -0,0 +1,83 @@
+// <auto-generated>
+// automatically generated by the FlatBuffers compiler, do not modify
+// </auto-generated>
+
+namespace KeywordTest
+{
+
+[Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))]
+public enum KeywordsInUnion : byte
+{
+ NONE = 0,
+ @static = 1,
+ @internal = 2,
+};
+
+public class KeywordsInUnionUnion {
+ public KeywordsInUnion Type { get; set; }
+ public object Value { get; set; }
+
+ public KeywordsInUnionUnion() {
+ this.Type = KeywordsInUnion.NONE;
+ this.Value = null;
+ }
+
+ public T As<T>() where T : class { return this.Value as T; }
+ public KeywordTest.KeywordsInTableT Asstatic() { return this.As<KeywordTest.KeywordsInTableT>(); }
+ public static KeywordsInUnionUnion Fromstatic(KeywordTest.KeywordsInTableT _static) { return new KeywordsInUnionUnion{ Type = KeywordsInUnion.@static, Value = _static }; }
+ public KeywordTest.KeywordsInTableT Asinternal() { return this.As<KeywordTest.KeywordsInTableT>(); }
+ public static KeywordsInUnionUnion Frominternal(KeywordTest.KeywordsInTableT _internal) { return new KeywordsInUnionUnion{ Type = KeywordsInUnion.@internal, Value = _internal }; }
+
+ public static int Pack(FlatBuffers.FlatBufferBuilder builder, KeywordsInUnionUnion _o) {
+ switch (_o.Type) {
+ default: return 0;
+ case KeywordsInUnion.@static: return KeywordTest.KeywordsInTable.Pack(builder, _o.Asstatic()).Value;
+ case KeywordsInUnion.@internal: return KeywordTest.KeywordsInTable.Pack(builder, _o.Asinternal()).Value;
+ }
+ }
+}
+
+public class KeywordsInUnionUnion_JsonConverter : Newtonsoft.Json.JsonConverter {
+ public override bool CanConvert(System.Type objectType) {
+ return objectType == typeof(KeywordsInUnionUnion) || objectType == typeof(System.Collections.Generic.List<KeywordsInUnionUnion>);
+ }
+ public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer) {
+ var _olist = value as System.Collections.Generic.List<KeywordsInUnionUnion>;
+ if (_olist != null) {
+ writer.WriteStartArray();
+ foreach (var _o in _olist) { this.WriteJson(writer, _o, serializer); }
+ writer.WriteEndArray();
+ } else {
+ this.WriteJson(writer, value as KeywordsInUnionUnion, serializer);
+ }
+ }
+ public void WriteJson(Newtonsoft.Json.JsonWriter writer, KeywordsInUnionUnion _o, Newtonsoft.Json.JsonSerializer serializer) {
+ if (_o == null) return;
+ serializer.Serialize(writer, _o.Value);
+ }
+ public override object ReadJson(Newtonsoft.Json.JsonReader reader, System.Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer) {
+ var _olist = existingValue as System.Collections.Generic.List<KeywordsInUnionUnion>;
+ if (_olist != null) {
+ for (var _j = 0; _j < _olist.Count; ++_j) {
+ reader.Read();
+ _olist[_j] = this.ReadJson(reader, _olist[_j], serializer);
+ }
+ reader.Read();
+ return _olist;
+ } else {
+ return this.ReadJson(reader, existingValue as KeywordsInUnionUnion, serializer);
+ }
+ }
+ public KeywordsInUnionUnion ReadJson(Newtonsoft.Json.JsonReader reader, KeywordsInUnionUnion _o, Newtonsoft.Json.JsonSerializer serializer) {
+ if (_o == null) return null;
+ switch (_o.Type) {
+ default: break;
+ case KeywordsInUnion.@static: _o.Value = serializer.Deserialize<KeywordTest.KeywordsInTableT>(reader); break;
+ case KeywordsInUnion.@internal: _o.Value = serializer.Deserialize<KeywordTest.KeywordsInTableT>(reader); break;
+ }
+ return _o;
+ }
+}
+
+
+}
diff --git a/tests/KeywordTest/public.cs b/tests/KeywordTest/public.cs
new file mode 100644
index 0000000..4d7684c
--- /dev/null
+++ b/tests/KeywordTest/public.cs
@@ -0,0 +1,15 @@
+// <auto-generated>
+// automatically generated by the FlatBuffers compiler, do not modify
+// </auto-generated>
+
+namespace KeywordTest
+{
+
+[Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))]
+public enum @public : int
+{
+ NONE = 0,
+};
+
+
+}
diff --git a/tests/LuaTest.bat b/tests/LuaTest.bat
index 2bbf1d0..39c5d8f 100644
--- a/tests/LuaTest.bat
+++ b/tests/LuaTest.bat
@@ -1,6 +1,7 @@
set buildtype=Release
if "%1"=="-b" set buildtype=%2
-..\%buildtype%\flatc.exe --lua -I include_test monster_test.fbs
-
+echo Run with LuaJIT:
+luajit.exe luatest.lua
+echo Run with Lua 5.3:
lua53.exe luatest.lua
\ No newline at end of file
diff --git a/tests/LuaTest.sh b/tests/LuaTest.sh
index eb70e8a..af34b69 100755
--- a/tests/LuaTest.sh
+++ b/tests/LuaTest.sh
@@ -17,6 +17,13 @@
pushd "$(dirname $0)" >/dev/null
test_dir="$(pwd)"
-${test_dir}/../flatc --lua -I include_test monster_test.fbs
+declare -a versions=(luajit lua5.1 lua5.2 lua5.3 lua5.4)
-lua5.3 luatest.lua
+for i in "${versions[@]}"
+do
+ if command -v $i &> /dev/null
+ then
+ echo "[$i]"
+ $i luatest.lua
+ fi
+done
diff --git a/tests/MutatingBool.fbs b/tests/MutatingBool.fbs
new file mode 100644
index 0000000..961db6e
--- /dev/null
+++ b/tests/MutatingBool.fbs
@@ -0,0 +1,8 @@
+
+struct Property {
+ property: bool;
+}
+
+table TestMutatingBool {
+ b: Property;
+}
diff --git a/tests/MyGame/Example/Ability.cs b/tests/MyGame/Example/Ability.cs
index bd49ccd..ae6a5b4 100644
--- a/tests/MyGame/Example/Ability.cs
+++ b/tests/MyGame/Example/Ability.cs
@@ -43,7 +43,7 @@
_o.Id,
_o.Distance);
}
-};
+}
public class AbilityT
{
diff --git a/tests/MyGame/Example/Ability.java b/tests/MyGame/Example/Ability.java
index df5fe71..4eb5ac4 100644
--- a/tests/MyGame/Example/Ability.java
+++ b/tests/MyGame/Example/Ability.java
@@ -13,14 +13,14 @@
public Ability __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; }
public long id() { return (long)bb.getInt(bb_pos + 0) & 0xFFFFFFFFL; }
- public void mutateId(long id) { bb.putInt(bb_pos + 0, (int)id); }
+ public void mutateId(long id) { bb.putInt(bb_pos + 0, (int) id); }
public long distance() { return (long)bb.getInt(bb_pos + 4) & 0xFFFFFFFFL; }
- public void mutateDistance(long distance) { bb.putInt(bb_pos + 4, (int)distance); }
+ public void mutateDistance(long distance) { bb.putInt(bb_pos + 4, (int) distance); }
public static int createAbility(FlatBufferBuilder builder, long id, long distance) {
builder.prep(4, 8);
- builder.putInt((int)distance);
- builder.putInt((int)id);
+ builder.putInt((int) distance);
+ builder.putInt((int) id);
return builder.offset();
}
@@ -30,5 +30,23 @@
public Ability get(int j) { return get(new Ability(), j); }
public Ability get(Ability obj, int j) { return obj.__assign(__element(j), bb); }
}
+ public AbilityT unpack() {
+ AbilityT _o = new AbilityT();
+ unpackTo(_o);
+ return _o;
+ }
+ public void unpackTo(AbilityT _o) {
+ long _oId = id();
+ _o.setId(_oId);
+ long _oDistance = distance();
+ _o.setDistance(_oDistance);
+ }
+ public static int pack(FlatBufferBuilder builder, AbilityT _o) {
+ if (_o == null) return 0;
+ return createAbility(
+ builder,
+ _o.getId(),
+ _o.getDistance());
+ }
}
diff --git a/tests/MyGame/Example/Ability.kt b/tests/MyGame/Example/Ability.kt
index 1b644d6..19a2f56 100644
--- a/tests/MyGame/Example/Ability.kt
+++ b/tests/MyGame/Example/Ability.kt
@@ -7,7 +7,6 @@
import com.google.flatbuffers.*
@Suppress("unused")
-@ExperimentalUnsignedTypes
class Ability : Struct() {
fun __init(_i: Int, _bb: ByteBuffer) {
diff --git a/tests/MyGame/Example/Ability.lua b/tests/MyGame/Example/Ability.lua
index 7fb664a..870ff81 100644
--- a/tests/MyGame/Example/Ability.lua
+++ b/tests/MyGame/Example/Ability.lua
@@ -1,31 +1,43 @@
--- automatically generated by the FlatBuffers compiler, do not modify
+--[[ MyGame.Example.Ability
--- namespace: Example
+ Automatically generated by the FlatBuffers compiler, do not modify.
+ Or modify. I'm a message, not a cop.
+
+ flatc version: 2.0.6
+
+ Declared by : //monster_test.fbs
+ Rooting type : MyGame.Example.Monster (//monster_test.fbs)
+
+--]]
local flatbuffers = require('flatbuffers')
-local Ability = {} -- the module
-local Ability_mt = {} -- the class metatable
+local Ability = {}
+local mt = {}
function Ability.New()
- local o = {}
- setmetatable(o, {__index = Ability_mt})
- return o
-end
-function Ability_mt:Init(buf, pos)
- self.view = flatbuffers.view.New(buf, pos)
-end
-function Ability_mt:Id()
- return self.view:Get(flatbuffers.N.Uint32, self.view.pos + 0)
-end
-function Ability_mt:Distance()
- return self.view:Get(flatbuffers.N.Uint32, self.view.pos + 4)
-end
-function Ability.CreateAbility(builder, id, distance)
- builder:Prep(4, 8)
- builder:PrependUint32(distance)
- builder:PrependUint32(id)
- return builder:Offset()
+ local o = {}
+ setmetatable(o, {__index = mt})
+ return o
end
-return Ability -- return the module
\ No newline at end of file
+function mt:Init(buf, pos)
+ self.view = flatbuffers.view.New(buf, pos)
+end
+
+function mt:Id()
+ return self.view:Get(flatbuffers.N.Uint32, self.view.pos + 0)
+end
+
+function mt:Distance()
+ return self.view:Get(flatbuffers.N.Uint32, self.view.pos + 4)
+end
+
+function Ability.CreateAbility(builder, id, distance)
+ builder:Prep(4, 8)
+ builder:PrependUint32(distance)
+ builder:PrependUint32(id)
+ return builder:Offset()
+end
+
+return Ability
\ No newline at end of file
diff --git a/tests/MyGame/Example/AbilityT.java b/tests/MyGame/Example/AbilityT.java
new file mode 100644
index 0000000..211b7bb
--- /dev/null
+++ b/tests/MyGame/Example/AbilityT.java
@@ -0,0 +1,28 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+package MyGame.Example;
+
+import java.nio.*;
+import java.lang.*;
+import java.util.*;
+import com.google.flatbuffers.*;
+
+public class AbilityT {
+ private long id;
+ private long distance;
+
+ public long getId() { return id; }
+
+ public void setId(long id) { this.id = id; }
+
+ public long getDistance() { return distance; }
+
+ public void setDistance(long distance) { this.distance = distance; }
+
+
+ public AbilityT() {
+ this.id = 0L;
+ this.distance = 0L;
+ }
+}
+
diff --git a/tests/MyGame/Example/Any.cs b/tests/MyGame/Example/Any.cs
index edf98ef..2e1717b 100644
--- a/tests/MyGame/Example/Any.cs
+++ b/tests/MyGame/Example/Any.cs
@@ -25,8 +25,11 @@
public T As<T>() where T : class { return this.Value as T; }
public MyGame.Example.MonsterT AsMonster() { return this.As<MyGame.Example.MonsterT>(); }
+ public static AnyUnion FromMonster(MyGame.Example.MonsterT _monster) { return new AnyUnion{ Type = Any.Monster, Value = _monster }; }
internal MyGame.Example.TestSimpleTableWithEnumT AsTestSimpleTableWithEnum() { return this.As<MyGame.Example.TestSimpleTableWithEnumT>(); }
+ internal static AnyUnion FromTestSimpleTableWithEnum(MyGame.Example.TestSimpleTableWithEnumT _testsimpletablewithenum) { return new AnyUnion{ Type = Any.TestSimpleTableWithEnum, Value = _testsimpletablewithenum }; }
public MyGame.Example2.MonsterT AsMyGame_Example2_Monster() { return this.As<MyGame.Example2.MonsterT>(); }
+ public static AnyUnion FromMyGame_Example2_Monster(MyGame.Example2.MonsterT _mygame_example2_monster) { return new AnyUnion{ Type = Any.MyGame_Example2_Monster, Value = _mygame_example2_monster }; }
public static int Pack(FlatBuffers.FlatBufferBuilder builder, AnyUnion _o) {
switch (_o.Type) {
diff --git a/tests/MyGame/Example/Any.java b/tests/MyGame/Example/Any.java
index 6e4fb76..a42a15a 100644
--- a/tests/MyGame/Example/Any.java
+++ b/tests/MyGame/Example/Any.java
@@ -2,6 +2,7 @@
package MyGame.Example;
+@SuppressWarnings("unused")
public final class Any {
private Any() { }
public static final byte NONE = 0;
diff --git a/tests/MyGame/Example/Any.kt b/tests/MyGame/Example/Any.kt
index f1a4dfe..5a7ecf7 100644
--- a/tests/MyGame/Example/Any.kt
+++ b/tests/MyGame/Example/Any.kt
@@ -3,7 +3,6 @@
package MyGame.Example
@Suppress("unused")
-@ExperimentalUnsignedTypes
class Any_ private constructor() {
companion object {
const val NONE: UByte = 0u
diff --git a/tests/MyGame/Example/Any.lua b/tests/MyGame/Example/Any.lua
index 03225ba..769a224 100644
--- a/tests/MyGame/Example/Any.lua
+++ b/tests/MyGame/Example/Any.lua
@@ -1,12 +1,20 @@
--- automatically generated by the FlatBuffers compiler, do not modify
+--[[ MyGame.Example.Any
--- namespace: Example
+ Automatically generated by the FlatBuffers compiler, do not modify.
+ Or modify. I'm a message, not a cop.
+
+ flatc version: 2.0.6
+
+ Declared by : //monster_test.fbs
+ Rooting type : MyGame.Example.Monster (//monster_test.fbs)
+
+--]]
local Any = {
- NONE = 0,
- Monster = 1,
- TestSimpleTableWithEnum = 2,
- MyGame_Example2_Monster = 3,
+ NONE = 0,
+ Monster = 1,
+ TestSimpleTableWithEnum = 2,
+ MyGame_Example2_Monster = 3,
}
-return Any -- return the module
\ No newline at end of file
+return Any
\ No newline at end of file
diff --git a/tests/MyGame/Example/Any.py b/tests/MyGame/Example/Any.py
index b10d35d..9983689 100644
--- a/tests/MyGame/Example/Any.py
+++ b/tests/MyGame/Example/Any.py
@@ -8,7 +8,6 @@
TestSimpleTableWithEnum = 2
MyGame_Example2_Monster = 3
-
def AnyCreator(unionType, table):
from flatbuffers.table import Table
if not isinstance(table, Table):
diff --git a/tests/MyGame/Example/AnyAmbiguousAliases.cs b/tests/MyGame/Example/AnyAmbiguousAliases.cs
index 07deadc..9253cc9 100644
--- a/tests/MyGame/Example/AnyAmbiguousAliases.cs
+++ b/tests/MyGame/Example/AnyAmbiguousAliases.cs
@@ -25,8 +25,11 @@
public T As<T>() where T : class { return this.Value as T; }
public MyGame.Example.MonsterT AsM1() { return this.As<MyGame.Example.MonsterT>(); }
+ public static AnyAmbiguousAliasesUnion FromM1(MyGame.Example.MonsterT _m1) { return new AnyAmbiguousAliasesUnion{ Type = AnyAmbiguousAliases.M1, Value = _m1 }; }
public MyGame.Example.MonsterT AsM2() { return this.As<MyGame.Example.MonsterT>(); }
+ public static AnyAmbiguousAliasesUnion FromM2(MyGame.Example.MonsterT _m2) { return new AnyAmbiguousAliasesUnion{ Type = AnyAmbiguousAliases.M2, Value = _m2 }; }
public MyGame.Example.MonsterT AsM3() { return this.As<MyGame.Example.MonsterT>(); }
+ public static AnyAmbiguousAliasesUnion FromM3(MyGame.Example.MonsterT _m3) { return new AnyAmbiguousAliasesUnion{ Type = AnyAmbiguousAliases.M3, Value = _m3 }; }
public static int Pack(FlatBuffers.FlatBufferBuilder builder, AnyAmbiguousAliasesUnion _o) {
switch (_o.Type) {
diff --git a/tests/MyGame/Example/AnyAmbiguousAliases.java b/tests/MyGame/Example/AnyAmbiguousAliases.java
index b8a6870..1b97b2c 100644
--- a/tests/MyGame/Example/AnyAmbiguousAliases.java
+++ b/tests/MyGame/Example/AnyAmbiguousAliases.java
@@ -2,6 +2,7 @@
package MyGame.Example;
+@SuppressWarnings("unused")
public final class AnyAmbiguousAliases {
private AnyAmbiguousAliases() { }
public static final byte NONE = 0;
diff --git a/tests/MyGame/Example/AnyAmbiguousAliases.kt b/tests/MyGame/Example/AnyAmbiguousAliases.kt
index cee13c5..c38923b 100644
--- a/tests/MyGame/Example/AnyAmbiguousAliases.kt
+++ b/tests/MyGame/Example/AnyAmbiguousAliases.kt
@@ -3,7 +3,6 @@
package MyGame.Example
@Suppress("unused")
-@ExperimentalUnsignedTypes
class AnyAmbiguousAliases private constructor() {
companion object {
const val NONE: UByte = 0u
diff --git a/tests/MyGame/Example/AnyAmbiguousAliases.lua b/tests/MyGame/Example/AnyAmbiguousAliases.lua
index dbe474b..c0d3407 100644
--- a/tests/MyGame/Example/AnyAmbiguousAliases.lua
+++ b/tests/MyGame/Example/AnyAmbiguousAliases.lua
@@ -1,12 +1,20 @@
--- automatically generated by the FlatBuffers compiler, do not modify
+--[[ MyGame.Example.AnyAmbiguousAliases
--- namespace: Example
+ Automatically generated by the FlatBuffers compiler, do not modify.
+ Or modify. I'm a message, not a cop.
+
+ flatc version: 2.0.6
+
+ Declared by : //monster_test.fbs
+ Rooting type : MyGame.Example.Monster (//monster_test.fbs)
+
+--]]
local AnyAmbiguousAliases = {
- NONE = 0,
- M1 = 1,
- M2 = 2,
- M3 = 3,
+ NONE = 0,
+ M1 = 1,
+ M2 = 2,
+ M3 = 3,
}
-return AnyAmbiguousAliases -- return the module
\ No newline at end of file
+return AnyAmbiguousAliases
\ No newline at end of file
diff --git a/tests/MyGame/Example/AnyAmbiguousAliases.py b/tests/MyGame/Example/AnyAmbiguousAliases.py
index 3fb4830..2225a03 100644
--- a/tests/MyGame/Example/AnyAmbiguousAliases.py
+++ b/tests/MyGame/Example/AnyAmbiguousAliases.py
@@ -8,7 +8,6 @@
M2 = 2
M3 = 3
-
def AnyAmbiguousAliasesCreator(unionType, table):
from flatbuffers.table import Table
if not isinstance(table, Table):
diff --git a/tests/MyGame/Example/AnyAmbiguousAliasesUnion.java b/tests/MyGame/Example/AnyAmbiguousAliasesUnion.java
new file mode 100644
index 0000000..879d581
--- /dev/null
+++ b/tests/MyGame/Example/AnyAmbiguousAliasesUnion.java
@@ -0,0 +1,37 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+package MyGame.Example;
+
+import com.google.flatbuffers.FlatBufferBuilder;
+
+public class AnyAmbiguousAliasesUnion {
+ private byte type;
+ private Object value;
+
+ public byte getType() { return type; }
+
+ public void setType(byte type) { this.type = type; }
+
+ public Object getValue() { return value; }
+
+ public void setValue(Object value) { this.value = value; }
+
+ public AnyAmbiguousAliasesUnion() {
+ this.type = AnyAmbiguousAliases.NONE;
+ this.value = null;
+ }
+
+ public MyGame.Example.MonsterT asM1() { return (MyGame.Example.MonsterT) value; }
+ public MyGame.Example.MonsterT asM2() { return (MyGame.Example.MonsterT) value; }
+ public MyGame.Example.MonsterT asM3() { return (MyGame.Example.MonsterT) value; }
+
+ public static int pack(FlatBufferBuilder builder, AnyAmbiguousAliasesUnion _o) {
+ switch (_o.type) {
+ case AnyAmbiguousAliases.M1: return MyGame.Example.Monster.pack(builder, _o.asM1());
+ case AnyAmbiguousAliases.M2: return MyGame.Example.Monster.pack(builder, _o.asM2());
+ case AnyAmbiguousAliases.M3: return MyGame.Example.Monster.pack(builder, _o.asM3());
+ default: return 0;
+ }
+ }
+}
+
diff --git a/tests/MyGame/Example/AnyUnion.java b/tests/MyGame/Example/AnyUnion.java
new file mode 100644
index 0000000..b012515
--- /dev/null
+++ b/tests/MyGame/Example/AnyUnion.java
@@ -0,0 +1,37 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+package MyGame.Example;
+
+import com.google.flatbuffers.FlatBufferBuilder;
+
+public class AnyUnion {
+ private byte type;
+ private Object value;
+
+ public byte getType() { return type; }
+
+ public void setType(byte type) { this.type = type; }
+
+ public Object getValue() { return value; }
+
+ public void setValue(Object value) { this.value = value; }
+
+ public AnyUnion() {
+ this.type = Any.NONE;
+ this.value = null;
+ }
+
+ public MyGame.Example.MonsterT asMonster() { return (MyGame.Example.MonsterT) value; }
+ MyGame.Example.TestSimpleTableWithEnumT asTestSimpleTableWithEnum() { return (MyGame.Example.TestSimpleTableWithEnumT) value; }
+ public MyGame.Example2.MonsterT asMyGame_Example2_Monster() { return (MyGame.Example2.MonsterT) value; }
+
+ public static int pack(FlatBufferBuilder builder, AnyUnion _o) {
+ switch (_o.type) {
+ case Any.Monster: return MyGame.Example.Monster.pack(builder, _o.asMonster());
+ case Any.TestSimpleTableWithEnum: return MyGame.Example.TestSimpleTableWithEnum.pack(builder, _o.asTestSimpleTableWithEnum());
+ case Any.MyGame_Example2_Monster: return MyGame.Example2.Monster.pack(builder, _o.asMyGame_Example2_Monster());
+ default: return 0;
+ }
+ }
+}
+
diff --git a/tests/MyGame/Example/AnyUniqueAliases.cs b/tests/MyGame/Example/AnyUniqueAliases.cs
index 3594952..ab33276 100644
--- a/tests/MyGame/Example/AnyUniqueAliases.cs
+++ b/tests/MyGame/Example/AnyUniqueAliases.cs
@@ -25,8 +25,11 @@
public T As<T>() where T : class { return this.Value as T; }
public MyGame.Example.MonsterT AsM() { return this.As<MyGame.Example.MonsterT>(); }
+ public static AnyUniqueAliasesUnion FromM(MyGame.Example.MonsterT _m) { return new AnyUniqueAliasesUnion{ Type = AnyUniqueAliases.M, Value = _m }; }
internal MyGame.Example.TestSimpleTableWithEnumT AsTS() { return this.As<MyGame.Example.TestSimpleTableWithEnumT>(); }
+ internal static AnyUniqueAliasesUnion FromTS(MyGame.Example.TestSimpleTableWithEnumT _ts) { return new AnyUniqueAliasesUnion{ Type = AnyUniqueAliases.TS, Value = _ts }; }
public MyGame.Example2.MonsterT AsM2() { return this.As<MyGame.Example2.MonsterT>(); }
+ public static AnyUniqueAliasesUnion FromM2(MyGame.Example2.MonsterT _m2) { return new AnyUniqueAliasesUnion{ Type = AnyUniqueAliases.M2, Value = _m2 }; }
public static int Pack(FlatBuffers.FlatBufferBuilder builder, AnyUniqueAliasesUnion _o) {
switch (_o.Type) {
diff --git a/tests/MyGame/Example/AnyUniqueAliases.java b/tests/MyGame/Example/AnyUniqueAliases.java
index 1f32945..a06423a 100644
--- a/tests/MyGame/Example/AnyUniqueAliases.java
+++ b/tests/MyGame/Example/AnyUniqueAliases.java
@@ -2,6 +2,7 @@
package MyGame.Example;
+@SuppressWarnings("unused")
public final class AnyUniqueAliases {
private AnyUniqueAliases() { }
public static final byte NONE = 0;
diff --git a/tests/MyGame/Example/AnyUniqueAliases.kt b/tests/MyGame/Example/AnyUniqueAliases.kt
index 1902d5d..2db45a6 100644
--- a/tests/MyGame/Example/AnyUniqueAliases.kt
+++ b/tests/MyGame/Example/AnyUniqueAliases.kt
@@ -3,7 +3,6 @@
package MyGame.Example
@Suppress("unused")
-@ExperimentalUnsignedTypes
class AnyUniqueAliases private constructor() {
companion object {
const val NONE: UByte = 0u
diff --git a/tests/MyGame/Example/AnyUniqueAliases.lua b/tests/MyGame/Example/AnyUniqueAliases.lua
index 9bfeb80..0042b93 100644
--- a/tests/MyGame/Example/AnyUniqueAliases.lua
+++ b/tests/MyGame/Example/AnyUniqueAliases.lua
@@ -1,12 +1,20 @@
--- automatically generated by the FlatBuffers compiler, do not modify
+--[[ MyGame.Example.AnyUniqueAliases
--- namespace: Example
+ Automatically generated by the FlatBuffers compiler, do not modify.
+ Or modify. I'm a message, not a cop.
+
+ flatc version: 2.0.6
+
+ Declared by : //monster_test.fbs
+ Rooting type : MyGame.Example.Monster (//monster_test.fbs)
+
+--]]
local AnyUniqueAliases = {
- NONE = 0,
- M = 1,
- TS = 2,
- M2 = 3,
+ NONE = 0,
+ M = 1,
+ TS = 2,
+ M2 = 3,
}
-return AnyUniqueAliases -- return the module
\ No newline at end of file
+return AnyUniqueAliases
\ No newline at end of file
diff --git a/tests/MyGame/Example/AnyUniqueAliases.py b/tests/MyGame/Example/AnyUniqueAliases.py
index cf89fc2..a3ba37e 100644
--- a/tests/MyGame/Example/AnyUniqueAliases.py
+++ b/tests/MyGame/Example/AnyUniqueAliases.py
@@ -8,7 +8,6 @@
TS = 2
M2 = 3
-
def AnyUniqueAliasesCreator(unionType, table):
from flatbuffers.table import Table
if not isinstance(table, Table):
diff --git a/tests/MyGame/Example/AnyUniqueAliasesUnion.java b/tests/MyGame/Example/AnyUniqueAliasesUnion.java
new file mode 100644
index 0000000..71bf491
--- /dev/null
+++ b/tests/MyGame/Example/AnyUniqueAliasesUnion.java
@@ -0,0 +1,37 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+package MyGame.Example;
+
+import com.google.flatbuffers.FlatBufferBuilder;
+
+public class AnyUniqueAliasesUnion {
+ private byte type;
+ private Object value;
+
+ public byte getType() { return type; }
+
+ public void setType(byte type) { this.type = type; }
+
+ public Object getValue() { return value; }
+
+ public void setValue(Object value) { this.value = value; }
+
+ public AnyUniqueAliasesUnion() {
+ this.type = AnyUniqueAliases.NONE;
+ this.value = null;
+ }
+
+ public MyGame.Example.MonsterT asM() { return (MyGame.Example.MonsterT) value; }
+ MyGame.Example.TestSimpleTableWithEnumT asTS() { return (MyGame.Example.TestSimpleTableWithEnumT) value; }
+ public MyGame.Example2.MonsterT asM2() { return (MyGame.Example2.MonsterT) value; }
+
+ public static int pack(FlatBufferBuilder builder, AnyUniqueAliasesUnion _o) {
+ switch (_o.type) {
+ case AnyUniqueAliases.M: return MyGame.Example.Monster.pack(builder, _o.asM());
+ case AnyUniqueAliases.TS: return MyGame.Example.TestSimpleTableWithEnum.pack(builder, _o.asTS());
+ case AnyUniqueAliases.M2: return MyGame.Example2.Monster.pack(builder, _o.asM2());
+ default: return 0;
+ }
+ }
+}
+
diff --git a/tests/MyGame/Example/ArrayStruct.cs b/tests/MyGame/Example/ArrayStruct.cs
index 41c088d..df0e2ac 100644
--- a/tests/MyGame/Example/ArrayStruct.cs
+++ b/tests/MyGame/Example/ArrayStruct.cs
@@ -97,7 +97,7 @@
_o.E,
_f);
}
-};
+}
public class ArrayStructT
{
diff --git a/tests/MyGame/Example/ArrayStruct.java b/tests/MyGame/Example/ArrayStruct.java
index 5c5b3f6..00535b0 100644
--- a/tests/MyGame/Example/ArrayStruct.java
+++ b/tests/MyGame/Example/ArrayStruct.java
@@ -18,6 +18,7 @@
public void mutateB(int j, int b) { bb.putInt(bb_pos + 4 + j * 4, b); }
public byte c() { return bb.get(bb_pos + 64); }
public void mutateC(byte c) { bb.put(bb_pos + 64, c); }
+ public MyGame.Example.NestedStruct d(int j) { return d(new MyGame.Example.NestedStruct(), j); }
public MyGame.Example.NestedStruct d(MyGame.Example.NestedStruct obj, int j) { return obj.__assign(bb_pos + 72 + j * 32, bb); }
public int e() { return bb.getInt(bb_pos + 136); }
public void mutateE(int e) { bb.putInt(bb_pos + 136, e); }
@@ -60,5 +61,48 @@
public ArrayStruct get(int j) { return get(new ArrayStruct(), j); }
public ArrayStruct get(ArrayStruct obj, int j) { return obj.__assign(__element(j), bb); }
}
+ public ArrayStructT unpack() {
+ ArrayStructT _o = new ArrayStructT();
+ unpackTo(_o);
+ return _o;
+ }
+ public void unpackTo(ArrayStructT _o) {
+ float _oA = a();
+ _o.setA(_oA);
+ int[] _oB = _o.getB();
+ for (int _j = 0; _j < 15; ++_j) { _oB[_j] = b(_j); }
+ byte _oC = c();
+ _o.setC(_oC);
+ MyGame.Example.NestedStructT[] _oD = _o.getD();
+ for (int _j = 0; _j < 2; ++_j) { _oD[_j] = d(_j).unpack(); }
+ int _oE = e();
+ _o.setE(_oE);
+ long[] _oF = _o.getF();
+ for (int _j = 0; _j < 2; ++_j) { _oF[_j] = f(_j); }
+ }
+ public static int pack(FlatBufferBuilder builder, ArrayStructT _o) {
+ if (_o == null) return 0;
+ int[] _b = _o.getB();
+ int[][] _d_a = new int[2][2];
+ for (int idx0 = 0; idx0 < 2; ++idx0) {for (int idx1 = 0; idx1 < 2; ++idx1) {_d_a[idx0][idx1] = _o.getD()[idx0].getA()[idx1];}}
+ byte[] _d_b = new byte[2];
+ for (int idx0 = 0; idx0 < 2; ++idx0) {_d_b[idx0] = _o.getD()[idx0].getB();}
+ byte[][] _d_c = new byte[2][2];
+ for (int idx0 = 0; idx0 < 2; ++idx0) {for (int idx1 = 0; idx1 < 2; ++idx1) {_d_c[idx0][idx1] = _o.getD()[idx0].getC()[idx1];}}
+ long[][] _d_d = new long[2][2];
+ for (int idx0 = 0; idx0 < 2; ++idx0) {for (int idx1 = 0; idx1 < 2; ++idx1) {_d_d[idx0][idx1] = _o.getD()[idx0].getD()[idx1];}}
+ long[] _f = _o.getF();
+ return createArrayStruct(
+ builder,
+ _o.getA(),
+ _b,
+ _o.getC(),
+ _d_a,
+ _d_b,
+ _d_c,
+ _d_d,
+ _o.getE(),
+ _f);
+ }
}
diff --git a/tests/MyGame/Example/ArrayStructT.java b/tests/MyGame/Example/ArrayStructT.java
new file mode 100644
index 0000000..bec1394
--- /dev/null
+++ b/tests/MyGame/Example/ArrayStructT.java
@@ -0,0 +1,52 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+package MyGame.Example;
+
+import java.nio.*;
+import java.lang.*;
+import java.util.*;
+import com.google.flatbuffers.*;
+
+public class ArrayStructT {
+ private float a;
+ private int[] b;
+ private byte c;
+ private MyGame.Example.NestedStructT[] d;
+ private int e;
+ private long[] f;
+
+ public float getA() { return a; }
+
+ public void setA(float a) { this.a = a; }
+
+ public int[] getB() { return b; }
+
+ public void setB(int[] b) { if (b != null && b.length == 15) this.b = b; }
+
+ public byte getC() { return c; }
+
+ public void setC(byte c) { this.c = c; }
+
+ public MyGame.Example.NestedStructT[] getD() { return d; }
+
+ public void setD(MyGame.Example.NestedStructT[] d) { if (d != null && d.length == 2) this.d = d; }
+
+ public int getE() { return e; }
+
+ public void setE(int e) { this.e = e; }
+
+ public long[] getF() { return f; }
+
+ public void setF(long[] f) { if (f != null && f.length == 2) this.f = f; }
+
+
+ public ArrayStructT() {
+ this.a = 0.0f;
+ this.b = new int[15];
+ this.c = 0;
+ this.d = new MyGame.Example.NestedStructT[2];
+ this.e = 0;
+ this.f = new long[2];
+ }
+}
+
diff --git a/tests/MyGame/Example/ArrayTable.cs b/tests/MyGame/Example/ArrayTable.cs
index b5b599f..9dc3d45 100644
--- a/tests/MyGame/Example/ArrayTable.cs
+++ b/tests/MyGame/Example/ArrayTable.cs
@@ -13,7 +13,7 @@
{
private Table __p;
public ByteBuffer ByteBuffer { get { return __p.bb; } }
- public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_1_12_0(); }
+ public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_2_0_0(); }
public static ArrayTable GetRootAsArrayTable(ByteBuffer _bb) { return GetRootAsArrayTable(_bb, new ArrayTable()); }
public static ArrayTable GetRootAsArrayTable(ByteBuffer _bb, ArrayTable obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); }
public static bool ArrayTableBufferHasIdentifier(ByteBuffer _bb) { return Table.__has_identifier(_bb, "ARRT"); }
@@ -44,7 +44,7 @@
AddA(builder, MyGame.Example.ArrayStruct.Pack(builder, _o.A));
return EndArrayTable(builder);
}
-};
+}
public class ArrayTableT
{
diff --git a/tests/MyGame/Example/ArrayTable.java b/tests/MyGame/Example/ArrayTable.java
index 41730d3..8e3782b 100644
--- a/tests/MyGame/Example/ArrayTable.java
+++ b/tests/MyGame/Example/ArrayTable.java
@@ -9,7 +9,7 @@
@SuppressWarnings("unused")
public final class ArrayTable extends Table {
- public static void ValidateVersion() { Constants.FLATBUFFERS_1_12_0(); }
+ public static void ValidateVersion() { Constants.FLATBUFFERS_2_0_0(); }
public static ArrayTable getRootAsArrayTable(ByteBuffer _bb) { return getRootAsArrayTable(_bb, new ArrayTable()); }
public static ArrayTable getRootAsArrayTable(ByteBuffer _bb, ArrayTable obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
public static boolean ArrayTableBufferHasIdentifier(ByteBuffer _bb) { return __has_identifier(_bb, "ARRT"); }
@@ -34,5 +34,20 @@
public ArrayTable get(int j) { return get(new ArrayTable(), j); }
public ArrayTable get(ArrayTable obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); }
}
+ public ArrayTableT unpack() {
+ ArrayTableT _o = new ArrayTableT();
+ unpackTo(_o);
+ return _o;
+ }
+ public void unpackTo(ArrayTableT _o) {
+ if (a() != null) a().unpackTo(_o.getA());
+ else _o.setA(null);
+ }
+ public static int pack(FlatBufferBuilder builder, ArrayTableT _o) {
+ if (_o == null) return 0;
+ startArrayTable(builder);
+ addA(builder, MyGame.Example.ArrayStruct.pack(builder, _o.getA()));
+ return endArrayTable(builder);
+ }
}
diff --git a/tests/MyGame/Example/ArrayTable.py b/tests/MyGame/Example/ArrayTable.py
index 83905e6..62d71af 100644
--- a/tests/MyGame/Example/ArrayTable.py
+++ b/tests/MyGame/Example/ArrayTable.py
@@ -10,13 +10,17 @@
__slots__ = ['_tab']
@classmethod
- def GetRootAsArrayTable(cls, buf, offset):
+ def GetRootAs(cls, buf, offset=0):
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
x = ArrayTable()
x.Init(buf, n + offset)
return x
@classmethod
+ def GetRootAsArrayTable(cls, buf, offset=0):
+ """This method is deprecated. Please switch to GetRootAs."""
+ return cls.GetRootAs(buf, offset)
+ @classmethod
def ArrayTableBufferHasIdentifier(cls, buf, offset, size_prefixed=False):
return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x41\x52\x52\x54", size_prefixed=size_prefixed)
@@ -36,9 +40,14 @@
return None
def ArrayTableStart(builder): builder.StartObject(1)
+def Start(builder):
+ return ArrayTableStart(builder)
def ArrayTableAddA(builder, a): builder.PrependStructSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(a), 0)
+def AddA(builder, a):
+ return ArrayTableAddA(builder, a)
def ArrayTableEnd(builder): return builder.EndObject()
-
+def End(builder):
+ return ArrayTableEnd(builder)
import MyGame.Example.ArrayStruct
try:
from typing import Optional
diff --git a/tests/MyGame/Example/ArrayTableT.java b/tests/MyGame/Example/ArrayTableT.java
new file mode 100644
index 0000000..3840b35
--- /dev/null
+++ b/tests/MyGame/Example/ArrayTableT.java
@@ -0,0 +1,30 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+package MyGame.Example;
+
+import java.nio.*;
+import java.lang.*;
+import java.util.*;
+import com.google.flatbuffers.*;
+
+public class ArrayTableT {
+ private MyGame.Example.ArrayStructT a;
+
+ public MyGame.Example.ArrayStructT getA() { return a; }
+
+ public void setA(MyGame.Example.ArrayStructT a) { this.a = a; }
+
+
+ public ArrayTableT() {
+ this.a = new MyGame.Example.ArrayStructT();
+ }
+ public static ArrayTableT deserializeFromBinary(byte[] fbBuffer) {
+ return ArrayTable.getRootAsArrayTable(ByteBuffer.wrap(fbBuffer)).unpack();
+ }
+ public byte[] serializeToBinary() {
+ FlatBufferBuilder fbb = new FlatBufferBuilder();
+ ArrayTable.finishArrayTableBuffer(fbb, ArrayTable.pack(fbb, this));
+ return fbb.sizedByteArray();
+ }
+}
+
diff --git a/tests/MyGame/Example/Color.java b/tests/MyGame/Example/Color.java
index 0563c0a..d86d382 100644
--- a/tests/MyGame/Example/Color.java
+++ b/tests/MyGame/Example/Color.java
@@ -5,18 +5,19 @@
/**
* Composite components of Monster color.
*/
+@SuppressWarnings("unused")
public final class Color {
private Color() { }
- public static final byte Red = 1;
+ public static final int Red = 1;
/**
* \brief color Green
* Green is bit_flag with value (1u << 1)
*/
- public static final byte Green = 2;
+ public static final int Green = 2;
/**
* \brief color Blue (1u << 3)
*/
- public static final byte Blue = 8;
+ public static final int Blue = 8;
public static final String[] names = { "Red", "Green", "", "", "", "", "", "Blue", };
diff --git a/tests/MyGame/Example/Color.kt b/tests/MyGame/Example/Color.kt
index 4c27ba3..0af56e1 100644
--- a/tests/MyGame/Example/Color.kt
+++ b/tests/MyGame/Example/Color.kt
@@ -6,7 +6,6 @@
* Composite components of Monster color.
*/
@Suppress("unused")
-@ExperimentalUnsignedTypes
class Color private constructor() {
companion object {
const val Red: UByte = 1u
diff --git a/tests/MyGame/Example/Color.lua b/tests/MyGame/Example/Color.lua
index d4d2cbc..1909a1b 100644
--- a/tests/MyGame/Example/Color.lua
+++ b/tests/MyGame/Example/Color.lua
@@ -1,15 +1,23 @@
--- automatically generated by the FlatBuffers compiler, do not modify
+--[[ MyGame.Example.Color
--- namespace: Example
+ Automatically generated by the FlatBuffers compiler, do not modify.
+ Or modify. I'm a message, not a cop.
+
+ flatc version: 2.0.6
+
+ Declared by : //monster_test.fbs
+ Rooting type : MyGame.Example.Monster (//monster_test.fbs)
+
+--]]
-- Composite components of Monster color.
local Color = {
- Red = 1,
- -- \brief color Green
- -- Green is bit_flag with value (1u << 1)
- Green = 2,
- -- \brief color Blue (1u << 3)
- Blue = 8,
+ Red = 1,
+ -- \brief color Green
+ -- Green is bit_flag with value (1u << 1)
+ Green = 2,
+ -- \brief color Blue (1u << 3)
+ Blue = 8,
}
-return Color -- return the module
\ No newline at end of file
+return Color
\ No newline at end of file
diff --git a/tests/MyGame/Example/Color.py b/tests/MyGame/Example/Color.py
index 55aa821..4ab9cc9 100644
--- a/tests/MyGame/Example/Color.py
+++ b/tests/MyGame/Example/Color.py
@@ -10,4 +10,3 @@
Green = 2
# \brief color Blue (1u << 3)
Blue = 8
-
diff --git a/tests/MyGame/Example/LongEnum.cs b/tests/MyGame/Example/LongEnum.cs
new file mode 100644
index 0000000..555109c
--- /dev/null
+++ b/tests/MyGame/Example/LongEnum.cs
@@ -0,0 +1,18 @@
+// <auto-generated>
+// automatically generated by the FlatBuffers compiler, do not modify
+// </auto-generated>
+
+namespace MyGame.Example
+{
+
+[Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))]
+[System.FlagsAttribute]
+public enum LongEnum : ulong
+{
+ LongOne = 2,
+ LongTwo = 4,
+ LongBig = 1099511627776,
+};
+
+
+}
diff --git a/tests/MyGame/Example/LongEnum.go b/tests/MyGame/Example/LongEnum.go
new file mode 100644
index 0000000..c7c6432
--- /dev/null
+++ b/tests/MyGame/Example/LongEnum.go
@@ -0,0 +1,32 @@
+// Code generated by the FlatBuffers compiler. DO NOT EDIT.
+
+package Example
+
+import "strconv"
+
+type LongEnum uint64
+
+const (
+ LongEnumLongOne LongEnum = 2
+ LongEnumLongTwo LongEnum = 4
+ LongEnumLongBig LongEnum = 1099511627776
+)
+
+var EnumNamesLongEnum = map[LongEnum]string{
+ LongEnumLongOne: "LongOne",
+ LongEnumLongTwo: "LongTwo",
+ LongEnumLongBig: "LongBig",
+}
+
+var EnumValuesLongEnum = map[string]LongEnum{
+ "LongOne": LongEnumLongOne,
+ "LongTwo": LongEnumLongTwo,
+ "LongBig": LongEnumLongBig,
+}
+
+func (v LongEnum) String() string {
+ if s, ok := EnumNamesLongEnum[v]; ok {
+ return s
+ }
+ return "LongEnum(" + strconv.FormatInt(int64(v), 10) + ")"
+}
diff --git a/tests/MyGame/Example/LongEnum.java b/tests/MyGame/Example/LongEnum.java
new file mode 100644
index 0000000..4640f08
--- /dev/null
+++ b/tests/MyGame/Example/LongEnum.java
@@ -0,0 +1,12 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+package MyGame.Example;
+
+@SuppressWarnings("unused")
+public final class LongEnum {
+ private LongEnum() { }
+ public static final long LongOne = 2;
+ public static final long LongTwo = 4;
+ public static final long LongBig = 1099511627776;
+}
+
diff --git a/tests/MyGame/Example/LongEnum.kt b/tests/MyGame/Example/LongEnum.kt
new file mode 100644
index 0000000..ecb5aab
--- /dev/null
+++ b/tests/MyGame/Example/LongEnum.kt
@@ -0,0 +1,12 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+package MyGame.Example
+
+@Suppress("unused")
+class LongEnum private constructor() {
+ companion object {
+ const val LongOne: ULong = 2UL
+ const val LongTwo: ULong = 4UL
+ const val LongBig: ULong = 1099511627776UL
+ }
+}
diff --git a/tests/MyGame/Example/LongEnum.lua b/tests/MyGame/Example/LongEnum.lua
new file mode 100644
index 0000000..00fb679
--- /dev/null
+++ b/tests/MyGame/Example/LongEnum.lua
@@ -0,0 +1,19 @@
+--[[ MyGame.Example.LongEnum
+
+ Automatically generated by the FlatBuffers compiler, do not modify.
+ Or modify. I'm a message, not a cop.
+
+ flatc version: 2.0.6
+
+ Declared by : //monster_test.fbs
+ Rooting type : MyGame.Example.Monster (//monster_test.fbs)
+
+--]]
+
+local LongEnum = {
+ LongOne = 2,
+ LongTwo = 4,
+ LongBig = 1099511627776,
+}
+
+return LongEnum
\ No newline at end of file
diff --git a/tests/MyGame/Example/LongEnum.php b/tests/MyGame/Example/LongEnum.php
new file mode 100644
index 0000000..900f0d3
--- /dev/null
+++ b/tests/MyGame/Example/LongEnum.php
@@ -0,0 +1,25 @@
+<?php
+// automatically generated by the FlatBuffers compiler, do not modify
+
+namespace MyGame\Example;
+
+class LongEnum
+{
+ const LongOne = 2;
+ const LongTwo = 4;
+ const LongBig = 1099511627776;
+
+ private static $names = array(
+ LongEnum::LongOne=>"LongOne",
+ LongEnum::LongTwo=>"LongTwo",
+ LongEnum::LongBig=>"LongBig",
+ );
+
+ public static function Name($e)
+ {
+ if (!isset(self::$names[$e])) {
+ throw new \Exception();
+ }
+ return self::$names[$e];
+ }
+}
diff --git a/tests/MyGame/Example/LongEnum.py b/tests/MyGame/Example/LongEnum.py
new file mode 100644
index 0000000..f45726a
--- /dev/null
+++ b/tests/MyGame/Example/LongEnum.py
@@ -0,0 +1,8 @@
+# automatically generated by the FlatBuffers compiler, do not modify
+
+# namespace: Example
+
+class LongEnum(object):
+ LongOne = 2
+ LongTwo = 4
+ LongBig = 1099511627776
diff --git a/tests/MyGame/Example/Monster.cs b/tests/MyGame/Example/Monster.cs
index acfb394..4a11389 100644
--- a/tests/MyGame/Example/Monster.cs
+++ b/tests/MyGame/Example/Monster.cs
@@ -14,7 +14,7 @@
{
private Table __p;
public ByteBuffer ByteBuffer { get { return __p.bb; } }
- public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_1_12_0(); }
+ public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_2_0_0(); }
public static Monster GetRootAsMonster(ByteBuffer _bb) { return GetRootAsMonster(_bb, new Monster()); }
public static Monster GetRootAsMonster(ByteBuffer _bb, Monster obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); }
public static bool MonsterBufferHasIdentifier(ByteBuffer _bb) { return Table.__has_identifier(_bb, "MONS"); }
@@ -207,6 +207,14 @@
public byte[] GetTestrequirednestedflatbufferArray() { return __p.__vector_as_array<byte>(102); }
public MyGame.Example.Monster? GetTestrequirednestedflatbufferAsMonster() { int o = __p.__offset(102); return o != 0 ? (MyGame.Example.Monster?)(new MyGame.Example.Monster()).__assign(__p.__indirect(__p.__vector(o)), __p.bb) : null; }
public bool MutateTestrequirednestedflatbuffer(int j, byte testrequirednestedflatbuffer) { int o = __p.__offset(102); if (o != 0) { __p.bb.Put(__p.__vector(o) + j * 1, testrequirednestedflatbuffer); return true; } else { return false; } }
+ public MyGame.Example.Stat? ScalarKeySortedTables(int j) { int o = __p.__offset(104); return o != 0 ? (MyGame.Example.Stat?)(new MyGame.Example.Stat()).__assign(__p.__indirect(__p.__vector(o) + j * 4), __p.bb) : null; }
+ public int ScalarKeySortedTablesLength { get { int o = __p.__offset(104); return o != 0 ? __p.__vector_len(o) : 0; } }
+ public MyGame.Example.Stat? ScalarKeySortedTablesByKey(ushort key) { int o = __p.__offset(104); return o != 0 ? MyGame.Example.Stat.__lookup_by_key(__p.__vector(o), key, __p.bb) : null; }
+ public MyGame.Example.Test? NativeInline { get { int o = __p.__offset(106); return o != 0 ? (MyGame.Example.Test?)(new MyGame.Example.Test()).__assign(o + __p.bb_pos, __p.bb) : null; } }
+ public MyGame.Example.LongEnum LongEnumNonEnumDefault { get { int o = __p.__offset(108); return o != 0 ? (MyGame.Example.LongEnum)__p.bb.GetUlong(o + __p.bb_pos) : 0; } }
+ public bool MutateLongEnumNonEnumDefault(MyGame.Example.LongEnum long_enum_non_enum_default) { int o = __p.__offset(108); if (o != 0) { __p.bb.PutUlong(o + __p.bb_pos, (ulong)long_enum_non_enum_default); return true; } else { return false; } }
+ public MyGame.Example.LongEnum LongEnumNormalDefault { get { int o = __p.__offset(110); return o != 0 ? (MyGame.Example.LongEnum)__p.bb.GetUlong(o + __p.bb_pos) : MyGame.Example.LongEnum.LongOne; } }
+ public bool MutateLongEnumNormalDefault(MyGame.Example.LongEnum long_enum_normal_default) { int o = __p.__offset(110); if (o != 0) { __p.bb.PutUlong(o + __p.bb_pos, (ulong)long_enum_normal_default); return true; } else { return false; } }
public static Offset<MyGame.Example.Monster> CreateMonster(FlatBufferBuilder builder,
MyGame.Example.Vec3T pos = null,
@@ -257,8 +265,14 @@
int any_ambiguousOffset = 0,
VectorOffset vector_of_enumsOffset = default(VectorOffset),
MyGame.Example.Race signed_enum = MyGame.Example.Race.None,
- VectorOffset testrequirednestedflatbufferOffset = default(VectorOffset)) {
- builder.StartTable(50);
+ VectorOffset testrequirednestedflatbufferOffset = default(VectorOffset),
+ VectorOffset scalar_key_sorted_tablesOffset = default(VectorOffset),
+ MyGame.Example.TestT native_inline = null,
+ MyGame.Example.LongEnum long_enum_non_enum_default = 0,
+ MyGame.Example.LongEnum long_enum_normal_default = MyGame.Example.LongEnum.LongOne) {
+ builder.StartTable(54);
+ Monster.AddLongEnumNormalDefault(builder, long_enum_normal_default);
+ Monster.AddLongEnumNonEnumDefault(builder, long_enum_non_enum_default);
Monster.AddNonOwningReference(builder, non_owning_reference);
Monster.AddCoOwningReference(builder, co_owning_reference);
Monster.AddSingleWeakReference(builder, single_weak_reference);
@@ -266,6 +280,8 @@
Monster.AddTesthashs64Fnv1a(builder, testhashs64_fnv1a);
Monster.AddTesthashu64Fnv1(builder, testhashu64_fnv1);
Monster.AddTesthashs64Fnv1(builder, testhashs64_fnv1);
+ Monster.AddNativeInline(builder, MyGame.Example.Test.Pack(builder, native_inline));
+ Monster.AddScalarKeySortedTables(builder, scalar_key_sorted_tablesOffset);
Monster.AddTestrequirednestedflatbuffer(builder, testrequirednestedflatbufferOffset);
Monster.AddVectorOfEnums(builder, vector_of_enumsOffset);
Monster.AddAnyAmbiguous(builder, any_ambiguousOffset);
@@ -311,7 +327,7 @@
return Monster.EndMonster(builder);
}
- public static void StartMonster(FlatBufferBuilder builder) { builder.StartTable(50); }
+ public static void StartMonster(FlatBufferBuilder builder) { builder.StartTable(54); }
public static void AddPos(FlatBufferBuilder builder, Offset<MyGame.Example.Vec3> posOffset) { builder.AddStruct(0, posOffset.Value, 0); }
public static void AddMana(FlatBufferBuilder builder, short mana) { builder.AddShort(1, mana, 150); }
public static void AddHp(FlatBufferBuilder builder, short hp) { builder.AddShort(2, hp, 100); }
@@ -412,6 +428,13 @@
public static VectorOffset CreateTestrequirednestedflatbufferVector(FlatBufferBuilder builder, byte[] data) { builder.StartVector(1, data.Length, 1); for (int i = data.Length - 1; i >= 0; i--) builder.AddByte(data[i]); return builder.EndVector(); }
public static VectorOffset CreateTestrequirednestedflatbufferVectorBlock(FlatBufferBuilder builder, byte[] data) { builder.StartVector(1, data.Length, 1); builder.Add(data); return builder.EndVector(); }
public static void StartTestrequirednestedflatbufferVector(FlatBufferBuilder builder, int numElems) { builder.StartVector(1, numElems, 1); }
+ public static void AddScalarKeySortedTables(FlatBufferBuilder builder, VectorOffset scalarKeySortedTablesOffset) { builder.AddOffset(50, scalarKeySortedTablesOffset.Value, 0); }
+ public static VectorOffset CreateScalarKeySortedTablesVector(FlatBufferBuilder builder, Offset<MyGame.Example.Stat>[] data) { builder.StartVector(4, data.Length, 4); for (int i = data.Length - 1; i >= 0; i--) builder.AddOffset(data[i].Value); return builder.EndVector(); }
+ public static VectorOffset CreateScalarKeySortedTablesVectorBlock(FlatBufferBuilder builder, Offset<MyGame.Example.Stat>[] data) { builder.StartVector(4, data.Length, 4); builder.Add(data); return builder.EndVector(); }
+ public static void StartScalarKeySortedTablesVector(FlatBufferBuilder builder, int numElems) { builder.StartVector(4, numElems, 4); }
+ public static void AddNativeInline(FlatBufferBuilder builder, Offset<MyGame.Example.Test> nativeInlineOffset) { builder.AddStruct(51, nativeInlineOffset.Value, 0); }
+ public static void AddLongEnumNonEnumDefault(FlatBufferBuilder builder, MyGame.Example.LongEnum longEnumNonEnumDefault) { builder.AddUlong(52, (ulong)longEnumNonEnumDefault, 0); }
+ public static void AddLongEnumNormalDefault(FlatBufferBuilder builder, MyGame.Example.LongEnum longEnumNormalDefault) { builder.AddUlong(53, (ulong)longEnumNormalDefault, 2); }
public static Offset<MyGame.Example.Monster> EndMonster(FlatBufferBuilder builder) {
int o = builder.EndTable();
builder.Required(o, 10); // name
@@ -555,6 +578,11 @@
_o.SignedEnum = this.SignedEnum;
_o.Testrequirednestedflatbuffer = new List<byte>();
for (var _j = 0; _j < this.TestrequirednestedflatbufferLength; ++_j) {_o.Testrequirednestedflatbuffer.Add(this.Testrequirednestedflatbuffer(_j));}
+ _o.ScalarKeySortedTables = new List<MyGame.Example.StatT>();
+ for (var _j = 0; _j < this.ScalarKeySortedTablesLength; ++_j) {_o.ScalarKeySortedTables.Add(this.ScalarKeySortedTables(_j).HasValue ? this.ScalarKeySortedTables(_j).Value.UnPack() : null);}
+ _o.NativeInline = this.NativeInline.HasValue ? this.NativeInline.Value.UnPack() : null;
+ _o.LongEnumNonEnumDefault = this.LongEnumNonEnumDefault;
+ _o.LongEnumNormalDefault = this.LongEnumNormalDefault;
}
public static Offset<MyGame.Example.Monster> Pack(FlatBufferBuilder builder, MonsterT _o) {
if (_o == null) return default(Offset<MyGame.Example.Monster>);
@@ -671,6 +699,12 @@
var __testrequirednestedflatbuffer = _o.Testrequirednestedflatbuffer.ToArray();
_testrequirednestedflatbuffer = CreateTestrequirednestedflatbufferVector(builder, __testrequirednestedflatbuffer);
}
+ var _scalar_key_sorted_tables = default(VectorOffset);
+ if (_o.ScalarKeySortedTables != null) {
+ var __scalar_key_sorted_tables = new Offset<MyGame.Example.Stat>[_o.ScalarKeySortedTables.Count];
+ for (var _j = 0; _j < __scalar_key_sorted_tables.Length; ++_j) { __scalar_key_sorted_tables[_j] = MyGame.Example.Stat.Pack(builder, _o.ScalarKeySortedTables[_j]); }
+ _scalar_key_sorted_tables = CreateScalarKeySortedTablesVector(builder, __scalar_key_sorted_tables);
+ }
return CreateMonster(
builder,
_o.Pos,
@@ -721,9 +755,13 @@
_any_ambiguous,
_vector_of_enums,
_o.SignedEnum,
- _testrequirednestedflatbuffer);
+ _testrequirednestedflatbuffer,
+ _scalar_key_sorted_tables,
+ _o.NativeInline,
+ _o.LongEnumNonEnumDefault,
+ _o.LongEnumNormalDefault);
}
-};
+}
public class MonsterT
{
@@ -866,6 +904,14 @@
public MyGame.Example.Race SignedEnum { get; set; }
[Newtonsoft.Json.JsonProperty("testrequirednestedflatbuffer")]
public List<byte> Testrequirednestedflatbuffer { get; set; }
+ [Newtonsoft.Json.JsonProperty("scalar_key_sorted_tables")]
+ public List<MyGame.Example.StatT> ScalarKeySortedTables { get; set; }
+ [Newtonsoft.Json.JsonProperty("native_inline")]
+ public MyGame.Example.TestT NativeInline { get; set; }
+ [Newtonsoft.Json.JsonProperty("long_enum_non_enum_default")]
+ public MyGame.Example.LongEnum LongEnumNonEnumDefault { get; set; }
+ [Newtonsoft.Json.JsonProperty("long_enum_normal_default")]
+ public MyGame.Example.LongEnum LongEnumNormalDefault { get; set; }
public MonsterT() {
this.Pos = new MyGame.Example.Vec3T();
@@ -914,6 +960,10 @@
this.VectorOfEnums = null;
this.SignedEnum = MyGame.Example.Race.None;
this.Testrequirednestedflatbuffer = null;
+ this.ScalarKeySortedTables = null;
+ this.NativeInline = new MyGame.Example.TestT();
+ this.LongEnumNonEnumDefault = 0;
+ this.LongEnumNormalDefault = MyGame.Example.LongEnum.LongOne;
}
public static MonsterT DeserializeFromJson(string jsonText) {
diff --git a/tests/MyGame/Example/Monster.go b/tests/MyGame/Example/Monster.go
index 2ffe926..067be0d 100644
--- a/tests/MyGame/Example/Monster.go
+++ b/tests/MyGame/Example/Monster.go
@@ -56,6 +56,10 @@
VectorOfEnums []Color
SignedEnum Race
Testrequirednestedflatbuffer []byte
+ ScalarKeySortedTables []*StatT
+ NativeInline *TestT
+ LongEnumNonEnumDefault LongEnum
+ LongEnumNormalDefault LongEnum
}
func (t *MonsterT) Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT {
@@ -241,6 +245,19 @@
if t.Testrequirednestedflatbuffer != nil {
testrequirednestedflatbufferOffset = builder.CreateByteString(t.Testrequirednestedflatbuffer)
}
+ scalarKeySortedTablesOffset := flatbuffers.UOffsetT(0)
+ if t.ScalarKeySortedTables != nil {
+ scalarKeySortedTablesLength := len(t.ScalarKeySortedTables)
+ scalarKeySortedTablesOffsets := make([]flatbuffers.UOffsetT, scalarKeySortedTablesLength)
+ for j := 0; j < scalarKeySortedTablesLength; j++ {
+ scalarKeySortedTablesOffsets[j] = t.ScalarKeySortedTables[j].Pack(builder)
+ }
+ MonsterStartScalarKeySortedTablesVector(builder, scalarKeySortedTablesLength)
+ for j := scalarKeySortedTablesLength - 1; j >= 0; j-- {
+ builder.PrependUOffsetT(scalarKeySortedTablesOffsets[j])
+ }
+ scalarKeySortedTablesOffset = builder.EndVector(scalarKeySortedTablesLength)
+ }
MonsterStart(builder)
posOffset := t.Pos.Pack(builder)
MonsterAddPos(builder, posOffset)
@@ -298,6 +315,11 @@
MonsterAddVectorOfEnums(builder, vectorOfEnumsOffset)
MonsterAddSignedEnum(builder, t.SignedEnum)
MonsterAddTestrequirednestedflatbuffer(builder, testrequirednestedflatbufferOffset)
+ MonsterAddScalarKeySortedTables(builder, scalarKeySortedTablesOffset)
+ nativeInlineOffset := t.NativeInline.Pack(builder)
+ MonsterAddNativeInline(builder, nativeInlineOffset)
+ MonsterAddLongEnumNonEnumDefault(builder, t.LongEnumNonEnumDefault)
+ MonsterAddLongEnumNormalDefault(builder, t.LongEnumNormalDefault)
return MonsterEnd(builder)
}
@@ -429,6 +451,16 @@
}
t.SignedEnum = rcv.SignedEnum()
t.Testrequirednestedflatbuffer = rcv.TestrequirednestedflatbufferBytes()
+ scalarKeySortedTablesLength := rcv.ScalarKeySortedTablesLength()
+ t.ScalarKeySortedTables = make([]*StatT, scalarKeySortedTablesLength)
+ for j := 0; j < scalarKeySortedTablesLength; j++ {
+ x := Stat{}
+ rcv.ScalarKeySortedTables(&x, j)
+ t.ScalarKeySortedTables[j] = x.UnPack()
+ }
+ t.NativeInline = rcv.NativeInline(nil).UnPack()
+ t.LongEnumNonEnumDefault = rcv.LongEnumNonEnumDefault()
+ t.LongEnumNormalDefault = rcv.LongEnumNormalDefault()
}
func (rcv *Monster) UnPack() *MonsterT {
@@ -1297,8 +1329,65 @@
return false
}
+func (rcv *Monster) ScalarKeySortedTables(obj *Stat, j int) bool {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(104))
+ if o != 0 {
+ x := rcv._tab.Vector(o)
+ x += flatbuffers.UOffsetT(j) * 4
+ x = rcv._tab.Indirect(x)
+ obj.Init(rcv._tab.Bytes, x)
+ return true
+ }
+ return false
+}
+
+func (rcv *Monster) ScalarKeySortedTablesLength() int {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(104))
+ if o != 0 {
+ return rcv._tab.VectorLen(o)
+ }
+ return 0
+}
+
+func (rcv *Monster) NativeInline(obj *Test) *Test {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(106))
+ if o != 0 {
+ x := o + rcv._tab.Pos
+ if obj == nil {
+ obj = new(Test)
+ }
+ obj.Init(rcv._tab.Bytes, x)
+ return obj
+ }
+ return nil
+}
+
+func (rcv *Monster) LongEnumNonEnumDefault() LongEnum {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(108))
+ if o != 0 {
+ return LongEnum(rcv._tab.GetUint64(o + rcv._tab.Pos))
+ }
+ return 0
+}
+
+func (rcv *Monster) MutateLongEnumNonEnumDefault(n LongEnum) bool {
+ return rcv._tab.MutateUint64Slot(108, uint64(n))
+}
+
+func (rcv *Monster) LongEnumNormalDefault() LongEnum {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(110))
+ if o != 0 {
+ return LongEnum(rcv._tab.GetUint64(o + rcv._tab.Pos))
+ }
+ return 2
+}
+
+func (rcv *Monster) MutateLongEnumNormalDefault(n LongEnum) bool {
+ return rcv._tab.MutateUint64Slot(110, uint64(n))
+}
+
func MonsterStart(builder *flatbuffers.Builder) {
- builder.StartObject(50)
+ builder.StartObject(54)
}
func MonsterAddPos(builder *flatbuffers.Builder, pos flatbuffers.UOffsetT) {
builder.PrependStructSlot(0, flatbuffers.UOffsetT(pos), 0)
@@ -1504,6 +1593,21 @@
func MonsterStartTestrequirednestedflatbufferVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT {
return builder.StartVector(1, numElems, 1)
}
+func MonsterAddScalarKeySortedTables(builder *flatbuffers.Builder, scalarKeySortedTables flatbuffers.UOffsetT) {
+ builder.PrependUOffsetTSlot(50, flatbuffers.UOffsetT(scalarKeySortedTables), 0)
+}
+func MonsterStartScalarKeySortedTablesVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT {
+ return builder.StartVector(4, numElems, 4)
+}
+func MonsterAddNativeInline(builder *flatbuffers.Builder, nativeInline flatbuffers.UOffsetT) {
+ builder.PrependStructSlot(51, flatbuffers.UOffsetT(nativeInline), 0)
+}
+func MonsterAddLongEnumNonEnumDefault(builder *flatbuffers.Builder, longEnumNonEnumDefault LongEnum) {
+ builder.PrependUint64Slot(52, uint64(longEnumNonEnumDefault), 0)
+}
+func MonsterAddLongEnumNormalDefault(builder *flatbuffers.Builder, longEnumNormalDefault LongEnum) {
+ builder.PrependUint64Slot(53, uint64(longEnumNormalDefault), 2)
+}
func MonsterEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT {
return builder.EndObject()
}
diff --git a/tests/MyGame/Example/Monster.java b/tests/MyGame/Example/Monster.java
index c3cd1ca..aeae257 100644
--- a/tests/MyGame/Example/Monster.java
+++ b/tests/MyGame/Example/Monster.java
@@ -12,7 +12,7 @@
*/
@SuppressWarnings("unused")
public final class Monster extends Table {
- public static void ValidateVersion() { Constants.FLATBUFFERS_1_12_0(); }
+ public static void ValidateVersion() { Constants.FLATBUFFERS_2_0_0(); }
public static Monster getRootAsMonster(ByteBuffer _bb) { return getRootAsMonster(_bb, new Monster()); }
public static Monster getRootAsMonster(ByteBuffer _bb, Monster obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
public static boolean MonsterBufferHasIdentifier(ByteBuffer _bb) { return __has_identifier(_bb, "MONS"); }
@@ -34,9 +34,9 @@
public ByteVector inventoryVector(ByteVector obj) { int o = __offset(14); return o != 0 ? obj.__assign(__vector(o), bb) : null; }
public ByteBuffer inventoryAsByteBuffer() { return __vector_as_bytebuffer(14, 1); }
public ByteBuffer inventoryInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 14, 1); }
- public boolean mutateInventory(int j, int inventory) { int o = __offset(14); if (o != 0) { bb.put(__vector(o) + j * 1, (byte)inventory); return true; } else { return false; } }
+ public boolean mutateInventory(int j, int inventory) { int o = __offset(14); if (o != 0) { bb.put(__vector(o) + j * 1, (byte) inventory); return true; } else { return false; } }
public int color() { int o = __offset(16); return o != 0 ? bb.get(o + bb_pos) & 0xFF : 8; }
- public boolean mutateColor(int color) { int o = __offset(16); if (o != 0) { bb.put(o + bb_pos, (byte)color); return true; } else { return false; } }
+ public boolean mutateColor(int color) { int o = __offset(16); if (o != 0) { bb.put(o + bb_pos, (byte) color); return true; } else { return false; } }
public byte testType() { int o = __offset(18); return o != 0 ? bb.get(o + bb_pos) : 0; }
public Table test(Table obj) { int o = __offset(20); return o != 0 ? __union(obj, o + bb_pos) : null; }
public MyGame.Example.Test test4(int j) { return test4(new MyGame.Example.Test(), j); }
@@ -69,7 +69,7 @@
public ByteBuffer testnestedflatbufferInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 30, 1); }
public MyGame.Example.Monster testnestedflatbufferAsMonster() { return testnestedflatbufferAsMonster(new MyGame.Example.Monster()); }
public MyGame.Example.Monster testnestedflatbufferAsMonster(MyGame.Example.Monster obj) { int o = __offset(30); return o != 0 ? obj.__assign(__indirect(__vector(o)), bb) : null; }
- public boolean mutateTestnestedflatbuffer(int j, int testnestedflatbuffer) { int o = __offset(30); if (o != 0) { bb.put(__vector(o) + j * 1, (byte)testnestedflatbuffer); return true; } else { return false; } }
+ public boolean mutateTestnestedflatbuffer(int j, int testnestedflatbuffer) { int o = __offset(30); if (o != 0) { bb.put(__vector(o) + j * 1, (byte) testnestedflatbuffer); return true; } else { return false; } }
public MyGame.Example.Stat testempty() { return testempty(new MyGame.Example.Stat()); }
public MyGame.Example.Stat testempty(MyGame.Example.Stat obj) { int o = __offset(32); return o != 0 ? obj.__assign(__indirect(o + bb_pos), bb) : null; }
public boolean testbool() { int o = __offset(34); return o != 0 ? 0!=bb.get(o + bb_pos) : false; }
@@ -77,7 +77,7 @@
public int testhashs32Fnv1() { int o = __offset(36); return o != 0 ? bb.getInt(o + bb_pos) : 0; }
public boolean mutateTesthashs32Fnv1(int testhashs32_fnv1) { int o = __offset(36); if (o != 0) { bb.putInt(o + bb_pos, testhashs32_fnv1); return true; } else { return false; } }
public long testhashu32Fnv1() { int o = __offset(38); return o != 0 ? (long)bb.getInt(o + bb_pos) & 0xFFFFFFFFL : 0L; }
- public boolean mutateTesthashu32Fnv1(long testhashu32_fnv1) { int o = __offset(38); if (o != 0) { bb.putInt(o + bb_pos, (int)testhashu32_fnv1); return true; } else { return false; } }
+ public boolean mutateTesthashu32Fnv1(long testhashu32_fnv1) { int o = __offset(38); if (o != 0) { bb.putInt(o + bb_pos, (int) testhashu32_fnv1); return true; } else { return false; } }
public long testhashs64Fnv1() { int o = __offset(40); return o != 0 ? bb.getLong(o + bb_pos) : 0L; }
public boolean mutateTesthashs64Fnv1(long testhashs64_fnv1) { int o = __offset(40); if (o != 0) { bb.putLong(o + bb_pos, testhashs64_fnv1); return true; } else { return false; } }
public long testhashu64Fnv1() { int o = __offset(42); return o != 0 ? bb.getLong(o + bb_pos) : 0L; }
@@ -85,7 +85,7 @@
public int testhashs32Fnv1a() { int o = __offset(44); return o != 0 ? bb.getInt(o + bb_pos) : 0; }
public boolean mutateTesthashs32Fnv1a(int testhashs32_fnv1a) { int o = __offset(44); if (o != 0) { bb.putInt(o + bb_pos, testhashs32_fnv1a); return true; } else { return false; } }
public long testhashu32Fnv1a() { int o = __offset(46); return o != 0 ? (long)bb.getInt(o + bb_pos) & 0xFFFFFFFFL : 0L; }
- public boolean mutateTesthashu32Fnv1a(long testhashu32_fnv1a) { int o = __offset(46); if (o != 0) { bb.putInt(o + bb_pos, (int)testhashu32_fnv1a); return true; } else { return false; } }
+ public boolean mutateTesthashu32Fnv1a(long testhashu32_fnv1a) { int o = __offset(46); if (o != 0) { bb.putInt(o + bb_pos, (int) testhashu32_fnv1a); return true; } else { return false; } }
public long testhashs64Fnv1a() { int o = __offset(48); return o != 0 ? bb.getLong(o + bb_pos) : 0L; }
public boolean mutateTesthashs64Fnv1a(long testhashs64_fnv1a) { int o = __offset(48); if (o != 0) { bb.putLong(o + bb_pos, testhashs64_fnv1a); return true; } else { return false; } }
public long testhashu64Fnv1a() { int o = __offset(50); return o != 0 ? bb.getLong(o + bb_pos) : 0L; }
@@ -118,7 +118,7 @@
public ByteVector flexVector(ByteVector obj) { int o = __offset(64); return o != 0 ? obj.__assign(__vector(o), bb) : null; }
public ByteBuffer flexAsByteBuffer() { return __vector_as_bytebuffer(64, 1); }
public ByteBuffer flexInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 64, 1); }
- public boolean mutateFlex(int j, int flex) { int o = __offset(64); if (o != 0) { bb.put(__vector(o) + j * 1, (byte)flex); return true; } else { return false; } }
+ public boolean mutateFlex(int j, int flex) { int o = __offset(64); if (o != 0) { bb.put(__vector(o) + j * 1, (byte) flex); return true; } else { return false; } }
public MyGame.Example.Test test5(int j) { return test5(new MyGame.Example.Test(), j); }
public MyGame.Example.Test test5(MyGame.Example.Test obj, int j) { int o = __offset(66); return o != 0 ? obj.__assign(__vector(o) + j * 4, bb) : null; }
public int test5Length() { int o = __offset(66); return o != 0 ? __vector_len(o) : 0; }
@@ -191,7 +191,7 @@
public ByteVector vectorOfEnumsVector(ByteVector obj) { int o = __offset(98); return o != 0 ? obj.__assign(__vector(o), bb) : null; }
public ByteBuffer vectorOfEnumsAsByteBuffer() { return __vector_as_bytebuffer(98, 1); }
public ByteBuffer vectorOfEnumsInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 98, 1); }
- public boolean mutateVectorOfEnums(int j, int vector_of_enums) { int o = __offset(98); if (o != 0) { bb.put(__vector(o) + j * 1, (byte)vector_of_enums); return true; } else { return false; } }
+ public boolean mutateVectorOfEnums(int j, int vector_of_enums) { int o = __offset(98); if (o != 0) { bb.put(__vector(o) + j * 1, (byte) vector_of_enums); return true; } else { return false; } }
public byte signedEnum() { int o = __offset(100); return o != 0 ? bb.get(o + bb_pos) : -1; }
public boolean mutateSignedEnum(byte signed_enum) { int o = __offset(100); if (o != 0) { bb.put(o + bb_pos, signed_enum); return true; } else { return false; } }
public int testrequirednestedflatbuffer(int j) { int o = __offset(102); return o != 0 ? bb.get(__vector(o) + j * 1) & 0xFF : 0; }
@@ -202,9 +202,22 @@
public ByteBuffer testrequirednestedflatbufferInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 102, 1); }
public MyGame.Example.Monster testrequirednestedflatbufferAsMonster() { return testrequirednestedflatbufferAsMonster(new MyGame.Example.Monster()); }
public MyGame.Example.Monster testrequirednestedflatbufferAsMonster(MyGame.Example.Monster obj) { int o = __offset(102); return o != 0 ? obj.__assign(__indirect(__vector(o)), bb) : null; }
- public boolean mutateTestrequirednestedflatbuffer(int j, int testrequirednestedflatbuffer) { int o = __offset(102); if (o != 0) { bb.put(__vector(o) + j * 1, (byte)testrequirednestedflatbuffer); return true; } else { return false; } }
+ public boolean mutateTestrequirednestedflatbuffer(int j, int testrequirednestedflatbuffer) { int o = __offset(102); if (o != 0) { bb.put(__vector(o) + j * 1, (byte) testrequirednestedflatbuffer); return true; } else { return false; } }
+ public MyGame.Example.Stat scalarKeySortedTables(int j) { return scalarKeySortedTables(new MyGame.Example.Stat(), j); }
+ public MyGame.Example.Stat scalarKeySortedTables(MyGame.Example.Stat obj, int j) { int o = __offset(104); return o != 0 ? obj.__assign(__indirect(__vector(o) + j * 4), bb) : null; }
+ public int scalarKeySortedTablesLength() { int o = __offset(104); return o != 0 ? __vector_len(o) : 0; }
+ public MyGame.Example.Stat scalarKeySortedTablesByKey(int key) { int o = __offset(104); return o != 0 ? MyGame.Example.Stat.__lookup_by_key(null, __vector(o), key, bb) : null; }
+ public MyGame.Example.Stat scalarKeySortedTablesByKey(MyGame.Example.Stat obj, int key) { int o = __offset(104); return o != 0 ? MyGame.Example.Stat.__lookup_by_key(obj, __vector(o), key, bb) : null; }
+ public MyGame.Example.Stat.Vector scalarKeySortedTablesVector() { return scalarKeySortedTablesVector(new MyGame.Example.Stat.Vector()); }
+ public MyGame.Example.Stat.Vector scalarKeySortedTablesVector(MyGame.Example.Stat.Vector obj) { int o = __offset(104); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; }
+ public MyGame.Example.Test nativeInline() { return nativeInline(new MyGame.Example.Test()); }
+ public MyGame.Example.Test nativeInline(MyGame.Example.Test obj) { int o = __offset(106); return o != 0 ? obj.__assign(o + bb_pos, bb) : null; }
+ public long longEnumNonEnumDefault() { int o = __offset(108); return o != 0 ? bb.getLong(o + bb_pos) : 0L; }
+ public boolean mutateLongEnumNonEnumDefault(long long_enum_non_enum_default) { int o = __offset(108); if (o != 0) { bb.putLong(o + bb_pos, long_enum_non_enum_default); return true; } else { return false; } }
+ public long longEnumNormalDefault() { int o = __offset(110); return o != 0 ? bb.getLong(o + bb_pos) : 2L; }
+ public boolean mutateLongEnumNormalDefault(long long_enum_normal_default) { int o = __offset(110); if (o != 0) { bb.putLong(o + bb_pos, long_enum_normal_default); return true; } else { return false; } }
- public static void startMonster(FlatBufferBuilder builder) { builder.startTable(50); }
+ public static void startMonster(FlatBufferBuilder builder) { builder.startTable(54); }
public static void addPos(FlatBufferBuilder builder, int posOffset) { builder.addStruct(0, posOffset, 0); }
public static void addMana(FlatBufferBuilder builder, short mana) { builder.addShort(1, mana, 150); }
public static void addHp(FlatBufferBuilder builder, short hp) { builder.addShort(2, hp, 100); }
@@ -213,7 +226,7 @@
public static int createInventoryVector(FlatBufferBuilder builder, byte[] data) { return builder.createByteVector(data); }
public static int createInventoryVector(FlatBufferBuilder builder, ByteBuffer data) { return builder.createByteVector(data); }
public static void startInventoryVector(FlatBufferBuilder builder, int numElems) { builder.startVector(1, numElems, 1); }
- public static void addColor(FlatBufferBuilder builder, int color) { builder.addByte(6, (byte)color, (byte)8); }
+ public static void addColor(FlatBufferBuilder builder, int color) { builder.addByte(6, (byte) color, (byte) 8); }
public static void addTestType(FlatBufferBuilder builder, byte testType) { builder.addByte(7, testType, 0); }
public static void addTest(FlatBufferBuilder builder, int testOffset) { builder.addOffset(8, testOffset, 0); }
public static void addTest4(FlatBufferBuilder builder, int test4Offset) { builder.addOffset(9, test4Offset, 0); }
@@ -232,11 +245,11 @@
public static void addTestempty(FlatBufferBuilder builder, int testemptyOffset) { builder.addOffset(14, testemptyOffset, 0); }
public static void addTestbool(FlatBufferBuilder builder, boolean testbool) { builder.addBoolean(15, testbool, false); }
public static void addTesthashs32Fnv1(FlatBufferBuilder builder, int testhashs32Fnv1) { builder.addInt(16, testhashs32Fnv1, 0); }
- public static void addTesthashu32Fnv1(FlatBufferBuilder builder, long testhashu32Fnv1) { builder.addInt(17, (int)testhashu32Fnv1, (int)0L); }
+ public static void addTesthashu32Fnv1(FlatBufferBuilder builder, long testhashu32Fnv1) { builder.addInt(17, (int) testhashu32Fnv1, (int) 0L); }
public static void addTesthashs64Fnv1(FlatBufferBuilder builder, long testhashs64Fnv1) { builder.addLong(18, testhashs64Fnv1, 0L); }
public static void addTesthashu64Fnv1(FlatBufferBuilder builder, long testhashu64Fnv1) { builder.addLong(19, testhashu64Fnv1, 0L); }
public static void addTesthashs32Fnv1a(FlatBufferBuilder builder, int testhashs32Fnv1a) { builder.addInt(20, testhashs32Fnv1a, 0); }
- public static void addTesthashu32Fnv1a(FlatBufferBuilder builder, long testhashu32Fnv1a) { builder.addInt(21, (int)testhashu32Fnv1a, (int)0L); }
+ public static void addTesthashu32Fnv1a(FlatBufferBuilder builder, long testhashu32Fnv1a) { builder.addInt(21, (int) testhashu32Fnv1a, (int) 0L); }
public static void addTesthashs64Fnv1a(FlatBufferBuilder builder, long testhashs64Fnv1a) { builder.addLong(22, testhashs64Fnv1a, 0L); }
public static void addTesthashu64Fnv1a(FlatBufferBuilder builder, long testhashu64Fnv1a) { builder.addLong(23, testhashu64Fnv1a, 0L); }
public static void addTestarrayofbools(FlatBufferBuilder builder, int testarrayofboolsOffset) { builder.addOffset(24, testarrayofboolsOffset, 0); }
@@ -294,6 +307,12 @@
public static int createTestrequirednestedflatbufferVector(FlatBufferBuilder builder, byte[] data) { return builder.createByteVector(data); }
public static int createTestrequirednestedflatbufferVector(FlatBufferBuilder builder, ByteBuffer data) { return builder.createByteVector(data); }
public static void startTestrequirednestedflatbufferVector(FlatBufferBuilder builder, int numElems) { builder.startVector(1, numElems, 1); }
+ public static void addScalarKeySortedTables(FlatBufferBuilder builder, int scalarKeySortedTablesOffset) { builder.addOffset(50, scalarKeySortedTablesOffset, 0); }
+ public static int createScalarKeySortedTablesVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); }
+ public static void startScalarKeySortedTablesVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); }
+ public static void addNativeInline(FlatBufferBuilder builder, int nativeInlineOffset) { builder.addStruct(51, nativeInlineOffset, 0); }
+ public static void addLongEnumNonEnumDefault(FlatBufferBuilder builder, long longEnumNonEnumDefault) { builder.addLong(52, longEnumNonEnumDefault, 0L); }
+ public static void addLongEnumNormalDefault(FlatBufferBuilder builder, long longEnumNormalDefault) { builder.addLong(53, longEnumNormalDefault, 2L); }
public static int endMonster(FlatBufferBuilder builder) {
int o = builder.endTable();
builder.required(o, 10); // name
@@ -334,5 +353,376 @@
public Monster getByKey(String key) { return __lookup_by_key(null, __vector(), key, bb); }
public Monster getByKey(Monster obj, String key) { return __lookup_by_key(obj, __vector(), key, bb); }
}
+ public MonsterT unpack() {
+ MonsterT _o = new MonsterT();
+ unpackTo(_o);
+ return _o;
+ }
+ public void unpackTo(MonsterT _o) {
+ if (pos() != null) pos().unpackTo(_o.getPos());
+ else _o.setPos(null);
+ short _oMana = mana();
+ _o.setMana(_oMana);
+ short _oHp = hp();
+ _o.setHp(_oHp);
+ String _oName = name();
+ _o.setName(_oName);
+ int[] _oInventory = new int[inventoryLength()];
+ for (int _j = 0; _j < inventoryLength(); ++_j) {_oInventory[_j] = inventory(_j);}
+ _o.setInventory(_oInventory);
+ int _oColor = color();
+ _o.setColor(_oColor);
+ MyGame.Example.AnyUnion _oTest = new MyGame.Example.AnyUnion();
+ byte _oTestType = testType();
+ _oTest.setType(_oTestType);
+ Table _oTestValue;
+ switch (_oTestType) {
+ case MyGame.Example.Any.Monster:
+ _oTestValue = test(new MyGame.Example.Monster());
+ _oTest.setValue(_oTestValue != null ? ((MyGame.Example.Monster) _oTestValue).unpack() : null);
+ break;
+ case MyGame.Example.Any.TestSimpleTableWithEnum:
+ _oTestValue = test(new MyGame.Example.TestSimpleTableWithEnum());
+ _oTest.setValue(_oTestValue != null ? ((MyGame.Example.TestSimpleTableWithEnum) _oTestValue).unpack() : null);
+ break;
+ case MyGame.Example.Any.MyGame_Example2_Monster:
+ _oTestValue = test(new MyGame.Example2.Monster());
+ _oTest.setValue(_oTestValue != null ? ((MyGame.Example2.Monster) _oTestValue).unpack() : null);
+ break;
+ default: break;
+ }
+ _o.setTest(_oTest);
+ MyGame.Example.TestT[] _oTest4 = new MyGame.Example.TestT[test4Length()];
+ for (int _j = 0; _j < test4Length(); ++_j) {_oTest4[_j] = (test4(_j) != null ? test4(_j).unpack() : null);}
+ _o.setTest4(_oTest4);
+ String[] _oTestarrayofstring = new String[testarrayofstringLength()];
+ for (int _j = 0; _j < testarrayofstringLength(); ++_j) {_oTestarrayofstring[_j] = testarrayofstring(_j);}
+ _o.setTestarrayofstring(_oTestarrayofstring);
+ MyGame.Example.MonsterT[] _oTestarrayoftables = new MyGame.Example.MonsterT[testarrayoftablesLength()];
+ for (int _j = 0; _j < testarrayoftablesLength(); ++_j) {_oTestarrayoftables[_j] = (testarrayoftables(_j) != null ? testarrayoftables(_j).unpack() : null);}
+ _o.setTestarrayoftables(_oTestarrayoftables);
+ if (enemy() != null) _o.setEnemy(enemy().unpack());
+ else _o.setEnemy(null);
+ int[] _oTestnestedflatbuffer = new int[testnestedflatbufferLength()];
+ for (int _j = 0; _j < testnestedflatbufferLength(); ++_j) {_oTestnestedflatbuffer[_j] = testnestedflatbuffer(_j);}
+ _o.setTestnestedflatbuffer(_oTestnestedflatbuffer);
+ if (testempty() != null) _o.setTestempty(testempty().unpack());
+ else _o.setTestempty(null);
+ boolean _oTestbool = testbool();
+ _o.setTestbool(_oTestbool);
+ int _oTesthashs32Fnv1 = testhashs32Fnv1();
+ _o.setTesthashs32Fnv1(_oTesthashs32Fnv1);
+ long _oTesthashu32Fnv1 = testhashu32Fnv1();
+ _o.setTesthashu32Fnv1(_oTesthashu32Fnv1);
+ long _oTesthashs64Fnv1 = testhashs64Fnv1();
+ _o.setTesthashs64Fnv1(_oTesthashs64Fnv1);
+ long _oTesthashu64Fnv1 = testhashu64Fnv1();
+ _o.setTesthashu64Fnv1(_oTesthashu64Fnv1);
+ int _oTesthashs32Fnv1a = testhashs32Fnv1a();
+ _o.setTesthashs32Fnv1a(_oTesthashs32Fnv1a);
+ long _oTesthashu32Fnv1a = testhashu32Fnv1a();
+ _o.setTesthashu32Fnv1a(_oTesthashu32Fnv1a);
+ long _oTesthashs64Fnv1a = testhashs64Fnv1a();
+ _o.setTesthashs64Fnv1a(_oTesthashs64Fnv1a);
+ long _oTesthashu64Fnv1a = testhashu64Fnv1a();
+ _o.setTesthashu64Fnv1a(_oTesthashu64Fnv1a);
+ boolean[] _oTestarrayofbools = new boolean[testarrayofboolsLength()];
+ for (int _j = 0; _j < testarrayofboolsLength(); ++_j) {_oTestarrayofbools[_j] = testarrayofbools(_j);}
+ _o.setTestarrayofbools(_oTestarrayofbools);
+ float _oTestf = testf();
+ _o.setTestf(_oTestf);
+ float _oTestf2 = testf2();
+ _o.setTestf2(_oTestf2);
+ float _oTestf3 = testf3();
+ _o.setTestf3(_oTestf3);
+ String[] _oTestarrayofstring2 = new String[testarrayofstring2Length()];
+ for (int _j = 0; _j < testarrayofstring2Length(); ++_j) {_oTestarrayofstring2[_j] = testarrayofstring2(_j);}
+ _o.setTestarrayofstring2(_oTestarrayofstring2);
+ MyGame.Example.AbilityT[] _oTestarrayofsortedstruct = new MyGame.Example.AbilityT[testarrayofsortedstructLength()];
+ for (int _j = 0; _j < testarrayofsortedstructLength(); ++_j) {_oTestarrayofsortedstruct[_j] = (testarrayofsortedstruct(_j) != null ? testarrayofsortedstruct(_j).unpack() : null);}
+ _o.setTestarrayofsortedstruct(_oTestarrayofsortedstruct);
+ int[] _oFlex = new int[flexLength()];
+ for (int _j = 0; _j < flexLength(); ++_j) {_oFlex[_j] = flex(_j);}
+ _o.setFlex(_oFlex);
+ MyGame.Example.TestT[] _oTest5 = new MyGame.Example.TestT[test5Length()];
+ for (int _j = 0; _j < test5Length(); ++_j) {_oTest5[_j] = (test5(_j) != null ? test5(_j).unpack() : null);}
+ _o.setTest5(_oTest5);
+ long[] _oVectorOfLongs = new long[vectorOfLongsLength()];
+ for (int _j = 0; _j < vectorOfLongsLength(); ++_j) {_oVectorOfLongs[_j] = vectorOfLongs(_j);}
+ _o.setVectorOfLongs(_oVectorOfLongs);
+ double[] _oVectorOfDoubles = new double[vectorOfDoublesLength()];
+ for (int _j = 0; _j < vectorOfDoublesLength(); ++_j) {_oVectorOfDoubles[_j] = vectorOfDoubles(_j);}
+ _o.setVectorOfDoubles(_oVectorOfDoubles);
+ if (parentNamespaceTest() != null) _o.setParentNamespaceTest(parentNamespaceTest().unpack());
+ else _o.setParentNamespaceTest(null);
+ MyGame.Example.ReferrableT[] _oVectorOfReferrables = new MyGame.Example.ReferrableT[vectorOfReferrablesLength()];
+ for (int _j = 0; _j < vectorOfReferrablesLength(); ++_j) {_oVectorOfReferrables[_j] = (vectorOfReferrables(_j) != null ? vectorOfReferrables(_j).unpack() : null);}
+ _o.setVectorOfReferrables(_oVectorOfReferrables);
+ long _oSingleWeakReference = singleWeakReference();
+ _o.setSingleWeakReference(_oSingleWeakReference);
+ long[] _oVectorOfWeakReferences = new long[vectorOfWeakReferencesLength()];
+ for (int _j = 0; _j < vectorOfWeakReferencesLength(); ++_j) {_oVectorOfWeakReferences[_j] = vectorOfWeakReferences(_j);}
+ _o.setVectorOfWeakReferences(_oVectorOfWeakReferences);
+ MyGame.Example.ReferrableT[] _oVectorOfStrongReferrables = new MyGame.Example.ReferrableT[vectorOfStrongReferrablesLength()];
+ for (int _j = 0; _j < vectorOfStrongReferrablesLength(); ++_j) {_oVectorOfStrongReferrables[_j] = (vectorOfStrongReferrables(_j) != null ? vectorOfStrongReferrables(_j).unpack() : null);}
+ _o.setVectorOfStrongReferrables(_oVectorOfStrongReferrables);
+ long _oCoOwningReference = coOwningReference();
+ _o.setCoOwningReference(_oCoOwningReference);
+ long[] _oVectorOfCoOwningReferences = new long[vectorOfCoOwningReferencesLength()];
+ for (int _j = 0; _j < vectorOfCoOwningReferencesLength(); ++_j) {_oVectorOfCoOwningReferences[_j] = vectorOfCoOwningReferences(_j);}
+ _o.setVectorOfCoOwningReferences(_oVectorOfCoOwningReferences);
+ long _oNonOwningReference = nonOwningReference();
+ _o.setNonOwningReference(_oNonOwningReference);
+ long[] _oVectorOfNonOwningReferences = new long[vectorOfNonOwningReferencesLength()];
+ for (int _j = 0; _j < vectorOfNonOwningReferencesLength(); ++_j) {_oVectorOfNonOwningReferences[_j] = vectorOfNonOwningReferences(_j);}
+ _o.setVectorOfNonOwningReferences(_oVectorOfNonOwningReferences);
+ MyGame.Example.AnyUniqueAliasesUnion _oAnyUnique = new MyGame.Example.AnyUniqueAliasesUnion();
+ byte _oAnyUniqueType = anyUniqueType();
+ _oAnyUnique.setType(_oAnyUniqueType);
+ Table _oAnyUniqueValue;
+ switch (_oAnyUniqueType) {
+ case MyGame.Example.AnyUniqueAliases.M:
+ _oAnyUniqueValue = anyUnique(new MyGame.Example.Monster());
+ _oAnyUnique.setValue(_oAnyUniqueValue != null ? ((MyGame.Example.Monster) _oAnyUniqueValue).unpack() : null);
+ break;
+ case MyGame.Example.AnyUniqueAliases.TS:
+ _oAnyUniqueValue = anyUnique(new MyGame.Example.TestSimpleTableWithEnum());
+ _oAnyUnique.setValue(_oAnyUniqueValue != null ? ((MyGame.Example.TestSimpleTableWithEnum) _oAnyUniqueValue).unpack() : null);
+ break;
+ case MyGame.Example.AnyUniqueAliases.M2:
+ _oAnyUniqueValue = anyUnique(new MyGame.Example2.Monster());
+ _oAnyUnique.setValue(_oAnyUniqueValue != null ? ((MyGame.Example2.Monster) _oAnyUniqueValue).unpack() : null);
+ break;
+ default: break;
+ }
+ _o.setAnyUnique(_oAnyUnique);
+ MyGame.Example.AnyAmbiguousAliasesUnion _oAnyAmbiguous = new MyGame.Example.AnyAmbiguousAliasesUnion();
+ byte _oAnyAmbiguousType = anyAmbiguousType();
+ _oAnyAmbiguous.setType(_oAnyAmbiguousType);
+ Table _oAnyAmbiguousValue;
+ switch (_oAnyAmbiguousType) {
+ case MyGame.Example.AnyAmbiguousAliases.M1:
+ _oAnyAmbiguousValue = anyAmbiguous(new MyGame.Example.Monster());
+ _oAnyAmbiguous.setValue(_oAnyAmbiguousValue != null ? ((MyGame.Example.Monster) _oAnyAmbiguousValue).unpack() : null);
+ break;
+ case MyGame.Example.AnyAmbiguousAliases.M2:
+ _oAnyAmbiguousValue = anyAmbiguous(new MyGame.Example.Monster());
+ _oAnyAmbiguous.setValue(_oAnyAmbiguousValue != null ? ((MyGame.Example.Monster) _oAnyAmbiguousValue).unpack() : null);
+ break;
+ case MyGame.Example.AnyAmbiguousAliases.M3:
+ _oAnyAmbiguousValue = anyAmbiguous(new MyGame.Example.Monster());
+ _oAnyAmbiguous.setValue(_oAnyAmbiguousValue != null ? ((MyGame.Example.Monster) _oAnyAmbiguousValue).unpack() : null);
+ break;
+ default: break;
+ }
+ _o.setAnyAmbiguous(_oAnyAmbiguous);
+ int[] _oVectorOfEnums = new int[vectorOfEnumsLength()];
+ for (int _j = 0; _j < vectorOfEnumsLength(); ++_j) {_oVectorOfEnums[_j] = vectorOfEnums(_j);}
+ _o.setVectorOfEnums(_oVectorOfEnums);
+ byte _oSignedEnum = signedEnum();
+ _o.setSignedEnum(_oSignedEnum);
+ int[] _oTestrequirednestedflatbuffer = new int[testrequirednestedflatbufferLength()];
+ for (int _j = 0; _j < testrequirednestedflatbufferLength(); ++_j) {_oTestrequirednestedflatbuffer[_j] = testrequirednestedflatbuffer(_j);}
+ _o.setTestrequirednestedflatbuffer(_oTestrequirednestedflatbuffer);
+ MyGame.Example.StatT[] _oScalarKeySortedTables = new MyGame.Example.StatT[scalarKeySortedTablesLength()];
+ for (int _j = 0; _j < scalarKeySortedTablesLength(); ++_j) {_oScalarKeySortedTables[_j] = (scalarKeySortedTables(_j) != null ? scalarKeySortedTables(_j).unpack() : null);}
+ _o.setScalarKeySortedTables(_oScalarKeySortedTables);
+ if (nativeInline() != null) nativeInline().unpackTo(_o.getNativeInline());
+ else _o.setNativeInline(null);
+ long _oLongEnumNonEnumDefault = longEnumNonEnumDefault();
+ _o.setLongEnumNonEnumDefault(_oLongEnumNonEnumDefault);
+ long _oLongEnumNormalDefault = longEnumNormalDefault();
+ _o.setLongEnumNormalDefault(_oLongEnumNormalDefault);
+ }
+ public static int pack(FlatBufferBuilder builder, MonsterT _o) {
+ if (_o == null) return 0;
+ int _name = _o.getName() == null ? 0 : builder.createString(_o.getName());
+ int _inventory = 0;
+ if (_o.getInventory() != null) {
+ byte[] __inventory = new byte[_o.getInventory().length];
+ int _j = 0;
+ for (int _e : _o.getInventory()) { __inventory[_j] = (byte) _e; _j++;}
+ _inventory = createInventoryVector(builder, __inventory);
+ }
+ byte _testType = _o.getTest() == null ? MyGame.Example.Any.NONE : _o.getTest().getType();
+ int _test = _o.getTest() == null ? 0 : MyGame.Example.AnyUnion.pack(builder, _o.getTest());
+ int _test4 = 0;
+ MyGame.Example.TestT[] _oTest4 = _o.getTest4();
+ if (_oTest4 != null) {
+ startTest4Vector(builder, _oTest4.length);
+ for (int _j = _oTest4.length - 1; _j >=0; _j--) { MyGame.Example.Test.pack(builder, _oTest4[_j]);}
+ _test4 = builder.endVector();
+ }
+ int _testarrayofstring = 0;
+ if (_o.getTestarrayofstring() != null) {
+ int[] __testarrayofstring = new int[_o.getTestarrayofstring().length];
+ int _j = 0;
+ for (String _e : _o.getTestarrayofstring()) { __testarrayofstring[_j] = builder.createString(_e); _j++;}
+ _testarrayofstring = createTestarrayofstringVector(builder, __testarrayofstring);
+ }
+ int _testarrayoftables = 0;
+ if (_o.getTestarrayoftables() != null) {
+ int[] __testarrayoftables = new int[_o.getTestarrayoftables().length];
+ int _j = 0;
+ for (MyGame.Example.MonsterT _e : _o.getTestarrayoftables()) { __testarrayoftables[_j] = MyGame.Example.Monster.pack(builder, _e); _j++;}
+ _testarrayoftables = createTestarrayoftablesVector(builder, __testarrayoftables);
+ }
+ int _enemy = _o.getEnemy() == null ? 0 : MyGame.Example.Monster.pack(builder, _o.getEnemy());
+ int _testnestedflatbuffer = 0;
+ if (_o.getTestnestedflatbuffer() != null) {
+ byte[] __testnestedflatbuffer = new byte[_o.getTestnestedflatbuffer().length];
+ int _j = 0;
+ for (int _e : _o.getTestnestedflatbuffer()) { __testnestedflatbuffer[_j] = (byte) _e; _j++;}
+ _testnestedflatbuffer = createTestnestedflatbufferVector(builder, __testnestedflatbuffer);
+ }
+ int _testempty = _o.getTestempty() == null ? 0 : MyGame.Example.Stat.pack(builder, _o.getTestempty());
+ int _testarrayofbools = 0;
+ if (_o.getTestarrayofbools() != null) {
+ _testarrayofbools = createTestarrayofboolsVector(builder, _o.getTestarrayofbools());
+ }
+ int _testarrayofstring2 = 0;
+ if (_o.getTestarrayofstring2() != null) {
+ int[] __testarrayofstring2 = new int[_o.getTestarrayofstring2().length];
+ int _j = 0;
+ for (String _e : _o.getTestarrayofstring2()) { __testarrayofstring2[_j] = builder.createString(_e); _j++;}
+ _testarrayofstring2 = createTestarrayofstring2Vector(builder, __testarrayofstring2);
+ }
+ int _testarrayofsortedstruct = 0;
+ MyGame.Example.AbilityT[] _oTestarrayofsortedstruct = _o.getTestarrayofsortedstruct();
+ if (_oTestarrayofsortedstruct != null) {
+ startTestarrayofsortedstructVector(builder, _oTestarrayofsortedstruct.length);
+ for (int _j = _oTestarrayofsortedstruct.length - 1; _j >=0; _j--) { MyGame.Example.Ability.pack(builder, _oTestarrayofsortedstruct[_j]);}
+ _testarrayofsortedstruct = builder.endVector();
+ }
+ int _flex = 0;
+ if (_o.getFlex() != null) {
+ byte[] __flex = new byte[_o.getFlex().length];
+ int _j = 0;
+ for (int _e : _o.getFlex()) { __flex[_j] = (byte) _e; _j++;}
+ _flex = createFlexVector(builder, __flex);
+ }
+ int _test5 = 0;
+ MyGame.Example.TestT[] _oTest5 = _o.getTest5();
+ if (_oTest5 != null) {
+ startTest5Vector(builder, _oTest5.length);
+ for (int _j = _oTest5.length - 1; _j >=0; _j--) { MyGame.Example.Test.pack(builder, _oTest5[_j]);}
+ _test5 = builder.endVector();
+ }
+ int _vectorOfLongs = 0;
+ if (_o.getVectorOfLongs() != null) {
+ _vectorOfLongs = createVectorOfLongsVector(builder, _o.getVectorOfLongs());
+ }
+ int _vectorOfDoubles = 0;
+ if (_o.getVectorOfDoubles() != null) {
+ _vectorOfDoubles = createVectorOfDoublesVector(builder, _o.getVectorOfDoubles());
+ }
+ int _parent_namespace_test = _o.getParentNamespaceTest() == null ? 0 : MyGame.InParentNamespace.pack(builder, _o.getParentNamespaceTest());
+ int _vectorOfReferrables = 0;
+ if (_o.getVectorOfReferrables() != null) {
+ int[] __vectorOfReferrables = new int[_o.getVectorOfReferrables().length];
+ int _j = 0;
+ for (MyGame.Example.ReferrableT _e : _o.getVectorOfReferrables()) { __vectorOfReferrables[_j] = MyGame.Example.Referrable.pack(builder, _e); _j++;}
+ _vectorOfReferrables = createVectorOfReferrablesVector(builder, __vectorOfReferrables);
+ }
+ int _vectorOfWeakReferences = 0;
+ if (_o.getVectorOfWeakReferences() != null) {
+ _vectorOfWeakReferences = createVectorOfWeakReferencesVector(builder, _o.getVectorOfWeakReferences());
+ }
+ int _vectorOfStrongReferrables = 0;
+ if (_o.getVectorOfStrongReferrables() != null) {
+ int[] __vectorOfStrongReferrables = new int[_o.getVectorOfStrongReferrables().length];
+ int _j = 0;
+ for (MyGame.Example.ReferrableT _e : _o.getVectorOfStrongReferrables()) { __vectorOfStrongReferrables[_j] = MyGame.Example.Referrable.pack(builder, _e); _j++;}
+ _vectorOfStrongReferrables = createVectorOfStrongReferrablesVector(builder, __vectorOfStrongReferrables);
+ }
+ int _vectorOfCoOwningReferences = 0;
+ if (_o.getVectorOfCoOwningReferences() != null) {
+ _vectorOfCoOwningReferences = createVectorOfCoOwningReferencesVector(builder, _o.getVectorOfCoOwningReferences());
+ }
+ int _vectorOfNonOwningReferences = 0;
+ if (_o.getVectorOfNonOwningReferences() != null) {
+ _vectorOfNonOwningReferences = createVectorOfNonOwningReferencesVector(builder, _o.getVectorOfNonOwningReferences());
+ }
+ byte _anyUniqueType = _o.getAnyUnique() == null ? MyGame.Example.AnyUniqueAliases.NONE : _o.getAnyUnique().getType();
+ int _anyUnique = _o.getAnyUnique() == null ? 0 : MyGame.Example.AnyUniqueAliasesUnion.pack(builder, _o.getAnyUnique());
+ byte _anyAmbiguousType = _o.getAnyAmbiguous() == null ? MyGame.Example.AnyAmbiguousAliases.NONE : _o.getAnyAmbiguous().getType();
+ int _anyAmbiguous = _o.getAnyAmbiguous() == null ? 0 : MyGame.Example.AnyAmbiguousAliasesUnion.pack(builder, _o.getAnyAmbiguous());
+ int _vectorOfEnums = 0;
+ if (_o.getVectorOfEnums() != null) {
+ byte[] __vectorOfEnums = new byte[_o.getVectorOfEnums().length];
+ int _j = 0;
+ for (int _e : _o.getVectorOfEnums()) { __vectorOfEnums[_j] = (byte) _e; _j++;}
+ _vectorOfEnums = createVectorOfEnumsVector(builder, __vectorOfEnums);
+ }
+ int _testrequirednestedflatbuffer = 0;
+ if (_o.getTestrequirednestedflatbuffer() != null) {
+ byte[] __testrequirednestedflatbuffer = new byte[_o.getTestrequirednestedflatbuffer().length];
+ int _j = 0;
+ for (int _e : _o.getTestrequirednestedflatbuffer()) { __testrequirednestedflatbuffer[_j] = (byte) _e; _j++;}
+ _testrequirednestedflatbuffer = createTestrequirednestedflatbufferVector(builder, __testrequirednestedflatbuffer);
+ }
+ int _scalarKeySortedTables = 0;
+ if (_o.getScalarKeySortedTables() != null) {
+ int[] __scalarKeySortedTables = new int[_o.getScalarKeySortedTables().length];
+ int _j = 0;
+ for (MyGame.Example.StatT _e : _o.getScalarKeySortedTables()) { __scalarKeySortedTables[_j] = MyGame.Example.Stat.pack(builder, _e); _j++;}
+ _scalarKeySortedTables = createScalarKeySortedTablesVector(builder, __scalarKeySortedTables);
+ }
+ startMonster(builder);
+ addPos(builder, MyGame.Example.Vec3.pack(builder, _o.getPos()));
+ addMana(builder, _o.getMana());
+ addHp(builder, _o.getHp());
+ addName(builder, _name);
+ addInventory(builder, _inventory);
+ addColor(builder, _o.getColor());
+ addTestType(builder, _testType);
+ addTest(builder, _test);
+ addTest4(builder, _test4);
+ addTestarrayofstring(builder, _testarrayofstring);
+ addTestarrayoftables(builder, _testarrayoftables);
+ addEnemy(builder, _enemy);
+ addTestnestedflatbuffer(builder, _testnestedflatbuffer);
+ addTestempty(builder, _testempty);
+ addTestbool(builder, _o.getTestbool());
+ addTesthashs32Fnv1(builder, _o.getTesthashs32Fnv1());
+ addTesthashu32Fnv1(builder, _o.getTesthashu32Fnv1());
+ addTesthashs64Fnv1(builder, _o.getTesthashs64Fnv1());
+ addTesthashu64Fnv1(builder, _o.getTesthashu64Fnv1());
+ addTesthashs32Fnv1a(builder, _o.getTesthashs32Fnv1a());
+ addTesthashu32Fnv1a(builder, _o.getTesthashu32Fnv1a());
+ addTesthashs64Fnv1a(builder, _o.getTesthashs64Fnv1a());
+ addTesthashu64Fnv1a(builder, _o.getTesthashu64Fnv1a());
+ addTestarrayofbools(builder, _testarrayofbools);
+ addTestf(builder, _o.getTestf());
+ addTestf2(builder, _o.getTestf2());
+ addTestf3(builder, _o.getTestf3());
+ addTestarrayofstring2(builder, _testarrayofstring2);
+ addTestarrayofsortedstruct(builder, _testarrayofsortedstruct);
+ addFlex(builder, _flex);
+ addTest5(builder, _test5);
+ addVectorOfLongs(builder, _vectorOfLongs);
+ addVectorOfDoubles(builder, _vectorOfDoubles);
+ addParentNamespaceTest(builder, _parent_namespace_test);
+ addVectorOfReferrables(builder, _vectorOfReferrables);
+ addSingleWeakReference(builder, _o.getSingleWeakReference());
+ addVectorOfWeakReferences(builder, _vectorOfWeakReferences);
+ addVectorOfStrongReferrables(builder, _vectorOfStrongReferrables);
+ addCoOwningReference(builder, _o.getCoOwningReference());
+ addVectorOfCoOwningReferences(builder, _vectorOfCoOwningReferences);
+ addNonOwningReference(builder, _o.getNonOwningReference());
+ addVectorOfNonOwningReferences(builder, _vectorOfNonOwningReferences);
+ addAnyUniqueType(builder, _anyUniqueType);
+ addAnyUnique(builder, _anyUnique);
+ addAnyAmbiguousType(builder, _anyAmbiguousType);
+ addAnyAmbiguous(builder, _anyAmbiguous);
+ addVectorOfEnums(builder, _vectorOfEnums);
+ addSignedEnum(builder, _o.getSignedEnum());
+ addTestrequirednestedflatbuffer(builder, _testrequirednestedflatbuffer);
+ addScalarKeySortedTables(builder, _scalarKeySortedTables);
+ addNativeInline(builder, MyGame.Example.Test.pack(builder, _o.getNativeInline()));
+ addLongEnumNonEnumDefault(builder, _o.getLongEnumNonEnumDefault());
+ addLongEnumNormalDefault(builder, _o.getLongEnumNormalDefault());
+ return endMonster(builder);
+ }
}
diff --git a/tests/MyGame/Example/Monster.kt b/tests/MyGame/Example/Monster.kt
index 7b15138..1abe05c 100644
--- a/tests/MyGame/Example/Monster.kt
+++ b/tests/MyGame/Example/Monster.kt
@@ -10,7 +10,6 @@
* an example documentation comment: "monster object"
*/
@Suppress("unused")
-@ExperimentalUnsignedTypes
class Monster : Table() {
fun __init(_i: Int, _bb: ByteBuffer) {
@@ -805,18 +804,84 @@
false
}
}
+ fun scalarKeySortedTables(j: Int) : MyGame.Example.Stat? = scalarKeySortedTables(MyGame.Example.Stat(), j)
+ fun scalarKeySortedTables(obj: MyGame.Example.Stat, j: Int) : MyGame.Example.Stat? {
+ val o = __offset(104)
+ return if (o != 0) {
+ obj.__assign(__indirect(__vector(o) + j * 4), bb)
+ } else {
+ null
+ }
+ }
+ val scalarKeySortedTablesLength : Int
+ get() {
+ val o = __offset(104); return if (o != 0) __vector_len(o) else 0
+ }
+ fun scalarKeySortedTablesByKey(key: UShort) : MyGame.Example.Stat? {
+ val o = __offset(104)
+ return if (o != 0) {
+ MyGame.Example.Stat.__lookup_by_key(null, __vector(o), key, bb)
+ } else {
+ null
+ }
+ }
+ fun scalarKeySortedTablesByKey(obj: MyGame.Example.Stat, key: UShort) : MyGame.Example.Stat? {
+ val o = __offset(104)
+ return if (o != 0) {
+ MyGame.Example.Stat.__lookup_by_key(obj, __vector(o), key, bb)
+ } else {
+ null
+ }
+ }
+ val nativeInline : MyGame.Example.Test? get() = nativeInline(MyGame.Example.Test())
+ fun nativeInline(obj: MyGame.Example.Test) : MyGame.Example.Test? {
+ val o = __offset(106)
+ return if (o != 0) {
+ obj.__assign(o + bb_pos, bb)
+ } else {
+ null
+ }
+ }
+ val longEnumNonEnumDefault : ULong
+ get() {
+ val o = __offset(108)
+ return if(o != 0) bb.getLong(o + bb_pos).toULong() else 0UL
+ }
+ fun mutateLongEnumNonEnumDefault(longEnumNonEnumDefault: ULong) : Boolean {
+ val o = __offset(108)
+ return if (o != 0) {
+ bb.putLong(o + bb_pos, longEnumNonEnumDefault.toLong())
+ true
+ } else {
+ false
+ }
+ }
+ val longEnumNormalDefault : ULong
+ get() {
+ val o = __offset(110)
+ return if(o != 0) bb.getLong(o + bb_pos).toULong() else 2UL
+ }
+ fun mutateLongEnumNormalDefault(longEnumNormalDefault: ULong) : Boolean {
+ val o = __offset(110)
+ return if (o != 0) {
+ bb.putLong(o + bb_pos, longEnumNormalDefault.toLong())
+ true
+ } else {
+ false
+ }
+ }
override fun keysCompare(o1: Int, o2: Int, _bb: ByteBuffer) : Int {
return compareStrings(__offset(10, o1, _bb), __offset(10, o2, _bb), _bb)
}
companion object {
- fun validateVersion() = Constants.FLATBUFFERS_1_12_0()
+ fun validateVersion() = Constants.FLATBUFFERS_2_0_0()
fun getRootAsMonster(_bb: ByteBuffer): Monster = getRootAsMonster(_bb, Monster())
fun getRootAsMonster(_bb: ByteBuffer, obj: Monster): Monster {
_bb.order(ByteOrder.LITTLE_ENDIAN)
return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb))
}
fun MonsterBufferHasIdentifier(_bb: ByteBuffer) : Boolean = __has_identifier(_bb, "MONS")
- fun startMonster(builder: FlatBufferBuilder) = builder.startTable(50)
+ fun startMonster(builder: FlatBufferBuilder) = builder.startTable(54)
fun addPos(builder: FlatBufferBuilder, pos: Int) = builder.addStruct(0, pos, 0)
fun addMana(builder: FlatBufferBuilder, mana: Short) = builder.addShort(1, mana, 150)
fun addHp(builder: FlatBufferBuilder, hp: Short) = builder.addShort(2, hp, 100)
@@ -997,6 +1062,18 @@
return builder.endVector()
}
fun startTestrequirednestedflatbufferVector(builder: FlatBufferBuilder, numElems: Int) = builder.startVector(1, numElems, 1)
+ fun addScalarKeySortedTables(builder: FlatBufferBuilder, scalarKeySortedTables: Int) = builder.addOffset(50, scalarKeySortedTables, 0)
+ fun createScalarKeySortedTablesVector(builder: FlatBufferBuilder, data: IntArray) : Int {
+ builder.startVector(4, data.size, 4)
+ for (i in data.size - 1 downTo 0) {
+ builder.addOffset(data[i])
+ }
+ return builder.endVector()
+ }
+ fun startScalarKeySortedTablesVector(builder: FlatBufferBuilder, numElems: Int) = builder.startVector(4, numElems, 4)
+ fun addNativeInline(builder: FlatBufferBuilder, nativeInline: Int) = builder.addStruct(51, nativeInline, 0)
+ fun addLongEnumNonEnumDefault(builder: FlatBufferBuilder, longEnumNonEnumDefault: ULong) = builder.addLong(52, longEnumNonEnumDefault.toLong(), 0)
+ fun addLongEnumNormalDefault(builder: FlatBufferBuilder, longEnumNormalDefault: ULong) = builder.addLong(53, longEnumNormalDefault.toLong(), 2)
fun endMonster(builder: FlatBufferBuilder) : Int {
val o = builder.endTable()
builder.required(o, 10)
diff --git a/tests/MyGame/Example/Monster.lua b/tests/MyGame/Example/Monster.lua
index 78ae4a5..75108e5 100644
--- a/tests/MyGame/Example/Monster.lua
+++ b/tests/MyGame/Example/Monster.lua
@@ -1,618 +1,1006 @@
--- automatically generated by the FlatBuffers compiler, do not modify
+--[[ MyGame.Example.Monster
--- namespace: Example
+ Automatically generated by the FlatBuffers compiler, do not modify.
+ Or modify. I'm a message, not a cop.
+ flatc version: 2.0.6
+
+ Declared by : //monster_test.fbs
+ Rooting type : MyGame.Example.Monster (//monster_test.fbs)
+
+--]]
+
+local __MyGame_Example_Ability = require('MyGame.Example.Ability')
+local __MyGame_Example_Referrable = require('MyGame.Example.Referrable')
+local __MyGame_Example_Stat = require('MyGame.Example.Stat')
+local __MyGame_Example_Test = require('MyGame.Example.Test')
+local __MyGame_Example_Vec3 = require('MyGame.Example.Vec3')
+local __MyGame_InParentNamespace = require('MyGame.InParentNamespace')
local flatbuffers = require('flatbuffers')
-- an example documentation comment: "monster object"
-local Monster = {} -- the module
-local Monster_mt = {} -- the class metatable
+local Monster = {}
+local mt = {}
function Monster.New()
- local o = {}
- setmetatable(o, {__index = Monster_mt})
- return o
+ local o = {}
+ setmetatable(o, {__index = mt})
+ return o
end
+
function Monster.GetRootAsMonster(buf, offset)
- local n = flatbuffers.N.UOffsetT:Unpack(buf, offset)
- local o = Monster.New()
- o:Init(buf, n + offset)
- return o
+ if type(buf) == "string" then
+ buf = flatbuffers.binaryArray.New(buf)
+ end
+
+ local n = flatbuffers.N.UOffsetT:Unpack(buf, offset)
+ local o = Monster.New()
+ o:Init(buf, n + offset)
+ return o
end
-function Monster_mt:Init(buf, pos)
- self.view = flatbuffers.view.New(buf, pos)
+
+function mt:Init(buf, pos)
+ self.view = flatbuffers.view.New(buf, pos)
end
-function Monster_mt:Pos()
- local o = self.view:Offset(4)
- if o ~= 0 then
- local x = o + self.view.pos
- local obj = require('MyGame.Example.Vec3').New()
- obj:Init(self.view.bytes, x)
- return obj
- end
+
+function mt:Pos()
+ local o = self.view:Offset(4)
+ if o ~= 0 then
+ local x = self.view.pos + o
+ local obj = __MyGame_Example_Vec3.New()
+ obj:Init(self.view.bytes, x)
+ return obj
+ end
end
-function Monster_mt:Mana()
- local o = self.view:Offset(6)
- if o ~= 0 then
- return self.view:Get(flatbuffers.N.Int16, o + self.view.pos)
- end
- return 150
+
+function mt:Mana()
+ local o = self.view:Offset(6)
+ if o ~= 0 then
+ return self.view:Get(flatbuffers.N.Int16, self.view.pos + o)
+ end
+ return 150
end
-function Monster_mt:Hp()
- local o = self.view:Offset(8)
- if o ~= 0 then
- return self.view:Get(flatbuffers.N.Int16, o + self.view.pos)
- end
- return 100
+
+function mt:Hp()
+ local o = self.view:Offset(8)
+ if o ~= 0 then
+ return self.view:Get(flatbuffers.N.Int16, self.view.pos + o)
+ end
+ return 100
end
-function Monster_mt:Name()
- local o = self.view:Offset(10)
- if o ~= 0 then
- return self.view:String(o + self.view.pos)
- end
+
+function mt:Name()
+ local o = self.view:Offset(10)
+ if o ~= 0 then
+ return self.view:String(self.view.pos + o)
+ end
end
-function Monster_mt:Inventory(j)
- local o = self.view:Offset(14)
- if o ~= 0 then
- local a = self.view:Vector(o)
- return self.view:Get(flatbuffers.N.Uint8, a + ((j-1) * 1))
- end
- return 0
+
+function mt:Inventory(j)
+ local o = self.view:Offset(14)
+ if o ~= 0 then
+ local a = self.view:Vector(o)
+ return self.view:Get(flatbuffers.N.Uint8, a + ((j-1) * 1))
+ end
+ return 0
end
-function Monster_mt:InventoryLength()
- local o = self.view:Offset(14)
- if o ~= 0 then
- return self.view:VectorLen(o)
- end
- return 0
+
+function mt:InventoryAsString(start, stop)
+ return self.view:VectorAsString(14, start, stop)
end
-function Monster_mt:Color()
- local o = self.view:Offset(16)
- if o ~= 0 then
- return self.view:Get(flatbuffers.N.Uint8, o + self.view.pos)
- end
- return 8
+
+function mt:InventoryLength()
+ local o = self.view:Offset(14)
+ if o ~= 0 then
+ return self.view:VectorLen(o)
+ end
+ return 0
end
-function Monster_mt:TestType()
- local o = self.view:Offset(18)
- if o ~= 0 then
- return self.view:Get(flatbuffers.N.Uint8, o + self.view.pos)
- end
- return 0
+
+function mt:Color()
+ local o = self.view:Offset(16)
+ if o ~= 0 then
+ return self.view:Get(flatbuffers.N.Uint8, self.view.pos + o)
+ end
+ return 8
end
-function Monster_mt:Test()
- local o = self.view:Offset(20)
- if o ~= 0 then
- local obj = flatbuffers.view.New(require('flatbuffers.binaryarray').New(0), 0)
- self.view:Union(obj, o)
- return obj
- end
+
+function mt:TestType()
+ local o = self.view:Offset(18)
+ if o ~= 0 then
+ return self.view:Get(flatbuffers.N.Uint8, self.view.pos + o)
+ end
+ return 0
end
-function Monster_mt:Test4(j)
- local o = self.view:Offset(22)
- if o ~= 0 then
- local x = self.view:Vector(o)
- x = x + ((j-1) * 4)
- local obj = require('MyGame.Example.Test').New()
- obj:Init(self.view.bytes, x)
- return obj
- end
+
+function mt:Test()
+ local o = self.view:Offset(20)
+ if o ~= 0 then
+ local obj = flatbuffers.view.New(flatbuffers.binaryArray.New(0), 0)
+ self.view:Union(obj, o)
+ return obj
+ end
end
-function Monster_mt:Test4Length()
- local o = self.view:Offset(22)
- if o ~= 0 then
- return self.view:VectorLen(o)
- end
- return 0
+
+function mt:Test4(j)
+ local o = self.view:Offset(22)
+ if o ~= 0 then
+ local x = self.view:Vector(o)
+ x = x + ((j-1) * 4)
+ local obj = __MyGame_Example_Test.New()
+ obj:Init(self.view.bytes, x)
+ return obj
+ end
end
-function Monster_mt:Testarrayofstring(j)
- local o = self.view:Offset(24)
- if o ~= 0 then
- local a = self.view:Vector(o)
- return self.view:String(a + ((j-1) * 4))
- end
- return ''
+
+function mt:Test4Length()
+ local o = self.view:Offset(22)
+ if o ~= 0 then
+ return self.view:VectorLen(o)
+ end
+ return 0
end
-function Monster_mt:TestarrayofstringLength()
- local o = self.view:Offset(24)
- if o ~= 0 then
- return self.view:VectorLen(o)
- end
- return 0
+
+function mt:Testarrayofstring(j)
+ local o = self.view:Offset(24)
+ if o ~= 0 then
+ local a = self.view:Vector(o)
+ return self.view:String(a + ((j-1) * 4))
+ end
+ return ''
end
+
+function mt:TestarrayofstringLength()
+ local o = self.view:Offset(24)
+ if o ~= 0 then
+ return self.view:VectorLen(o)
+ end
+ return 0
+end
+
-- an example documentation comment: this will end up in the generated code
-- multiline too
-function Monster_mt:Testarrayoftables(j)
- local o = self.view:Offset(26)
- if o ~= 0 then
- local x = self.view:Vector(o)
- x = x + ((j-1) * 4)
- x = self.view:Indirect(x)
- local obj = require('MyGame.Example.Monster').New()
- obj:Init(self.view.bytes, x)
- return obj
- end
+function mt:Testarrayoftables(j)
+ local o = self.view:Offset(26)
+ if o ~= 0 then
+ local x = self.view:Vector(o)
+ x = x + ((j-1) * 4)
+ x = self.view:Indirect(x)
+ local obj = Monster.New()
+ obj:Init(self.view.bytes, x)
+ return obj
+ end
end
-function Monster_mt:TestarrayoftablesLength()
- local o = self.view:Offset(26)
- if o ~= 0 then
- return self.view:VectorLen(o)
- end
- return 0
-end
-function Monster_mt:Enemy()
- local o = self.view:Offset(28)
- if o ~= 0 then
- local x = self.view:Indirect(o + self.view.pos)
- local obj = require('MyGame.Example.Monster').New()
- obj:Init(self.view.bytes, x)
- return obj
- end
-end
-function Monster_mt:Testnestedflatbuffer(j)
- local o = self.view:Offset(30)
- if o ~= 0 then
- local a = self.view:Vector(o)
- return self.view:Get(flatbuffers.N.Uint8, a + ((j-1) * 1))
- end
- return 0
-end
-function Monster_mt:TestnestedflatbufferLength()
- local o = self.view:Offset(30)
- if o ~= 0 then
- return self.view:VectorLen(o)
- end
- return 0
-end
-function Monster_mt:Testempty()
- local o = self.view:Offset(32)
- if o ~= 0 then
- local x = self.view:Indirect(o + self.view.pos)
- local obj = require('MyGame.Example.Stat').New()
- obj:Init(self.view.bytes, x)
- return obj
- end
-end
-function Monster_mt:Testbool()
- local o = self.view:Offset(34)
- if o ~= 0 then
- return (self.view:Get(flatbuffers.N.Bool, o + self.view.pos) ~= 0)
- end
- return false
-end
-function Monster_mt:Testhashs32Fnv1()
- local o = self.view:Offset(36)
- if o ~= 0 then
- return self.view:Get(flatbuffers.N.Int32, o + self.view.pos)
- end
- return 0
-end
-function Monster_mt:Testhashu32Fnv1()
- local o = self.view:Offset(38)
- if o ~= 0 then
- return self.view:Get(flatbuffers.N.Uint32, o + self.view.pos)
- end
- return 0
-end
-function Monster_mt:Testhashs64Fnv1()
- local o = self.view:Offset(40)
- if o ~= 0 then
- return self.view:Get(flatbuffers.N.Int64, o + self.view.pos)
- end
- return 0
-end
-function Monster_mt:Testhashu64Fnv1()
- local o = self.view:Offset(42)
- if o ~= 0 then
- return self.view:Get(flatbuffers.N.Uint64, o + self.view.pos)
- end
- return 0
-end
-function Monster_mt:Testhashs32Fnv1a()
- local o = self.view:Offset(44)
- if o ~= 0 then
- return self.view:Get(flatbuffers.N.Int32, o + self.view.pos)
- end
- return 0
-end
-function Monster_mt:Testhashu32Fnv1a()
- local o = self.view:Offset(46)
- if o ~= 0 then
- return self.view:Get(flatbuffers.N.Uint32, o + self.view.pos)
- end
- return 0
-end
-function Monster_mt:Testhashs64Fnv1a()
- local o = self.view:Offset(48)
- if o ~= 0 then
- return self.view:Get(flatbuffers.N.Int64, o + self.view.pos)
- end
- return 0
-end
-function Monster_mt:Testhashu64Fnv1a()
- local o = self.view:Offset(50)
- if o ~= 0 then
- return self.view:Get(flatbuffers.N.Uint64, o + self.view.pos)
- end
- return 0
-end
-function Monster_mt:Testarrayofbools(j)
- local o = self.view:Offset(52)
- if o ~= 0 then
- local a = self.view:Vector(o)
- return self.view:Get(flatbuffers.N.Bool, a + ((j-1) * 1))
- end
- return 0
-end
-function Monster_mt:TestarrayofboolsLength()
- local o = self.view:Offset(52)
- if o ~= 0 then
- return self.view:VectorLen(o)
- end
- return 0
-end
-function Monster_mt:Testf()
- local o = self.view:Offset(54)
- if o ~= 0 then
- return self.view:Get(flatbuffers.N.Float32, o + self.view.pos)
- end
- return 3.14159
-end
-function Monster_mt:Testf2()
- local o = self.view:Offset(56)
- if o ~= 0 then
- return self.view:Get(flatbuffers.N.Float32, o + self.view.pos)
- end
- return 3.0
-end
-function Monster_mt:Testf3()
- local o = self.view:Offset(58)
- if o ~= 0 then
- return self.view:Get(flatbuffers.N.Float32, o + self.view.pos)
- end
- return 0.0
-end
-function Monster_mt:Testarrayofstring2(j)
- local o = self.view:Offset(60)
- if o ~= 0 then
- local a = self.view:Vector(o)
- return self.view:String(a + ((j-1) * 4))
- end
- return ''
-end
-function Monster_mt:Testarrayofstring2Length()
- local o = self.view:Offset(60)
- if o ~= 0 then
- return self.view:VectorLen(o)
- end
- return 0
-end
-function Monster_mt:Testarrayofsortedstruct(j)
- local o = self.view:Offset(62)
- if o ~= 0 then
- local x = self.view:Vector(o)
- x = x + ((j-1) * 8)
- local obj = require('MyGame.Example.Ability').New()
- obj:Init(self.view.bytes, x)
- return obj
- end
-end
-function Monster_mt:TestarrayofsortedstructLength()
- local o = self.view:Offset(62)
- if o ~= 0 then
- return self.view:VectorLen(o)
- end
- return 0
-end
-function Monster_mt:Flex(j)
- local o = self.view:Offset(64)
- if o ~= 0 then
- local a = self.view:Vector(o)
- return self.view:Get(flatbuffers.N.Uint8, a + ((j-1) * 1))
- end
- return 0
-end
-function Monster_mt:FlexLength()
- local o = self.view:Offset(64)
- if o ~= 0 then
- return self.view:VectorLen(o)
- end
- return 0
-end
-function Monster_mt:Test5(j)
- local o = self.view:Offset(66)
- if o ~= 0 then
- local x = self.view:Vector(o)
- x = x + ((j-1) * 4)
- local obj = require('MyGame.Example.Test').New()
- obj:Init(self.view.bytes, x)
- return obj
- end
-end
-function Monster_mt:Test5Length()
- local o = self.view:Offset(66)
- if o ~= 0 then
- return self.view:VectorLen(o)
- end
- return 0
-end
-function Monster_mt:VectorOfLongs(j)
- local o = self.view:Offset(68)
- if o ~= 0 then
- local a = self.view:Vector(o)
- return self.view:Get(flatbuffers.N.Int64, a + ((j-1) * 8))
- end
- return 0
-end
-function Monster_mt:VectorOfLongsLength()
- local o = self.view:Offset(68)
- if o ~= 0 then
- return self.view:VectorLen(o)
- end
- return 0
-end
-function Monster_mt:VectorOfDoubles(j)
- local o = self.view:Offset(70)
- if o ~= 0 then
- local a = self.view:Vector(o)
- return self.view:Get(flatbuffers.N.Float64, a + ((j-1) * 8))
- end
- return 0
-end
-function Monster_mt:VectorOfDoublesLength()
- local o = self.view:Offset(70)
- if o ~= 0 then
- return self.view:VectorLen(o)
- end
- return 0
-end
-function Monster_mt:ParentNamespaceTest()
- local o = self.view:Offset(72)
- if o ~= 0 then
- local x = self.view:Indirect(o + self.view.pos)
- local obj = require('MyGame.InParentNamespace').New()
- obj:Init(self.view.bytes, x)
- return obj
- end
-end
-function Monster_mt:VectorOfReferrables(j)
- local o = self.view:Offset(74)
- if o ~= 0 then
- local x = self.view:Vector(o)
- x = x + ((j-1) * 4)
- x = self.view:Indirect(x)
- local obj = require('MyGame.Example.Referrable').New()
- obj:Init(self.view.bytes, x)
- return obj
- end
-end
-function Monster_mt:VectorOfReferrablesLength()
- local o = self.view:Offset(74)
- if o ~= 0 then
- return self.view:VectorLen(o)
- end
- return 0
-end
-function Monster_mt:SingleWeakReference()
- local o = self.view:Offset(76)
- if o ~= 0 then
- return self.view:Get(flatbuffers.N.Uint64, o + self.view.pos)
- end
- return 0
-end
-function Monster_mt:VectorOfWeakReferences(j)
- local o = self.view:Offset(78)
- if o ~= 0 then
- local a = self.view:Vector(o)
- return self.view:Get(flatbuffers.N.Uint64, a + ((j-1) * 8))
- end
- return 0
-end
-function Monster_mt:VectorOfWeakReferencesLength()
- local o = self.view:Offset(78)
- if o ~= 0 then
- return self.view:VectorLen(o)
- end
- return 0
-end
-function Monster_mt:VectorOfStrongReferrables(j)
- local o = self.view:Offset(80)
- if o ~= 0 then
- local x = self.view:Vector(o)
- x = x + ((j-1) * 4)
- x = self.view:Indirect(x)
- local obj = require('MyGame.Example.Referrable').New()
- obj:Init(self.view.bytes, x)
- return obj
- end
-end
-function Monster_mt:VectorOfStrongReferrablesLength()
- local o = self.view:Offset(80)
- if o ~= 0 then
- return self.view:VectorLen(o)
- end
- return 0
-end
-function Monster_mt:CoOwningReference()
- local o = self.view:Offset(82)
- if o ~= 0 then
- return self.view:Get(flatbuffers.N.Uint64, o + self.view.pos)
- end
- return 0
-end
-function Monster_mt:VectorOfCoOwningReferences(j)
- local o = self.view:Offset(84)
- if o ~= 0 then
- local a = self.view:Vector(o)
- return self.view:Get(flatbuffers.N.Uint64, a + ((j-1) * 8))
- end
- return 0
-end
-function Monster_mt:VectorOfCoOwningReferencesLength()
- local o = self.view:Offset(84)
- if o ~= 0 then
- return self.view:VectorLen(o)
- end
- return 0
-end
-function Monster_mt:NonOwningReference()
- local o = self.view:Offset(86)
- if o ~= 0 then
- return self.view:Get(flatbuffers.N.Uint64, o + self.view.pos)
- end
- return 0
-end
-function Monster_mt:VectorOfNonOwningReferences(j)
- local o = self.view:Offset(88)
- if o ~= 0 then
- local a = self.view:Vector(o)
- return self.view:Get(flatbuffers.N.Uint64, a + ((j-1) * 8))
- end
- return 0
-end
-function Monster_mt:VectorOfNonOwningReferencesLength()
- local o = self.view:Offset(88)
- if o ~= 0 then
- return self.view:VectorLen(o)
- end
- return 0
-end
-function Monster_mt:AnyUniqueType()
- local o = self.view:Offset(90)
- if o ~= 0 then
- return self.view:Get(flatbuffers.N.Uint8, o + self.view.pos)
- end
- return 0
-end
-function Monster_mt:AnyUnique()
- local o = self.view:Offset(92)
- if o ~= 0 then
- local obj = flatbuffers.view.New(require('flatbuffers.binaryarray').New(0), 0)
- self.view:Union(obj, o)
- return obj
- end
-end
-function Monster_mt:AnyAmbiguousType()
- local o = self.view:Offset(94)
- if o ~= 0 then
- return self.view:Get(flatbuffers.N.Uint8, o + self.view.pos)
- end
- return 0
-end
-function Monster_mt:AnyAmbiguous()
- local o = self.view:Offset(96)
- if o ~= 0 then
- local obj = flatbuffers.view.New(require('flatbuffers.binaryarray').New(0), 0)
- self.view:Union(obj, o)
- return obj
- end
-end
-function Monster_mt:VectorOfEnums(j)
- local o = self.view:Offset(98)
- if o ~= 0 then
- local a = self.view:Vector(o)
- return self.view:Get(flatbuffers.N.Uint8, a + ((j-1) * 1))
- end
- return 0
-end
-function Monster_mt:VectorOfEnumsLength()
- local o = self.view:Offset(98)
- if o ~= 0 then
- return self.view:VectorLen(o)
- end
- return 0
-end
-function Monster_mt:SignedEnum()
- local o = self.view:Offset(100)
- if o ~= 0 then
- return self.view:Get(flatbuffers.N.Int8, o + self.view.pos)
- end
- return -1
-end
-function Monster_mt:Testrequirednestedflatbuffer(j)
- local o = self.view:Offset(102)
- if o ~= 0 then
- local a = self.view:Vector(o)
- return self.view:Get(flatbuffers.N.Uint8, a + ((j-1) * 1))
- end
- return 0
-end
-function Monster_mt:TestrequirednestedflatbufferLength()
- local o = self.view:Offset(102)
- if o ~= 0 then
- return self.view:VectorLen(o)
- end
- return 0
-end
-function Monster.Start(builder) builder:StartObject(50) end
-function Monster.AddPos(builder, pos) builder:PrependStructSlot(0, pos, 0) end
-function Monster.AddMana(builder, mana) builder:PrependInt16Slot(1, mana, 150) end
-function Monster.AddHp(builder, hp) builder:PrependInt16Slot(2, hp, 100) end
-function Monster.AddName(builder, name) builder:PrependUOffsetTRelativeSlot(3, name, 0) end
-function Monster.AddInventory(builder, inventory) builder:PrependUOffsetTRelativeSlot(5, inventory, 0) end
-function Monster.StartInventoryVector(builder, numElems) return builder:StartVector(1, numElems, 1) end
-function Monster.AddColor(builder, color) builder:PrependUint8Slot(6, color, 8) end
-function Monster.AddTestType(builder, testType) builder:PrependUint8Slot(7, testType, 0) end
-function Monster.AddTest(builder, test) builder:PrependUOffsetTRelativeSlot(8, test, 0) end
-function Monster.AddTest4(builder, test4) builder:PrependUOffsetTRelativeSlot(9, test4, 0) end
-function Monster.StartTest4Vector(builder, numElems) return builder:StartVector(4, numElems, 2) end
-function Monster.AddTestarrayofstring(builder, testarrayofstring) builder:PrependUOffsetTRelativeSlot(10, testarrayofstring, 0) end
-function Monster.StartTestarrayofstringVector(builder, numElems) return builder:StartVector(4, numElems, 4) end
-function Monster.AddTestarrayoftables(builder, testarrayoftables) builder:PrependUOffsetTRelativeSlot(11, testarrayoftables, 0) end
-function Monster.StartTestarrayoftablesVector(builder, numElems) return builder:StartVector(4, numElems, 4) end
-function Monster.AddEnemy(builder, enemy) builder:PrependUOffsetTRelativeSlot(12, enemy, 0) end
-function Monster.AddTestnestedflatbuffer(builder, testnestedflatbuffer) builder:PrependUOffsetTRelativeSlot(13, testnestedflatbuffer, 0) end
-function Monster.StartTestnestedflatbufferVector(builder, numElems) return builder:StartVector(1, numElems, 1) end
-function Monster.AddTestempty(builder, testempty) builder:PrependUOffsetTRelativeSlot(14, testempty, 0) end
-function Monster.AddTestbool(builder, testbool) builder:PrependBoolSlot(15, testbool, 0) end
-function Monster.AddTesthashs32Fnv1(builder, testhashs32Fnv1) builder:PrependInt32Slot(16, testhashs32Fnv1, 0) end
-function Monster.AddTesthashu32Fnv1(builder, testhashu32Fnv1) builder:PrependUint32Slot(17, testhashu32Fnv1, 0) end
-function Monster.AddTesthashs64Fnv1(builder, testhashs64Fnv1) builder:PrependInt64Slot(18, testhashs64Fnv1, 0) end
-function Monster.AddTesthashu64Fnv1(builder, testhashu64Fnv1) builder:PrependUint64Slot(19, testhashu64Fnv1, 0) end
-function Monster.AddTesthashs32Fnv1a(builder, testhashs32Fnv1a) builder:PrependInt32Slot(20, testhashs32Fnv1a, 0) end
-function Monster.AddTesthashu32Fnv1a(builder, testhashu32Fnv1a) builder:PrependUint32Slot(21, testhashu32Fnv1a, 0) end
-function Monster.AddTesthashs64Fnv1a(builder, testhashs64Fnv1a) builder:PrependInt64Slot(22, testhashs64Fnv1a, 0) end
-function Monster.AddTesthashu64Fnv1a(builder, testhashu64Fnv1a) builder:PrependUint64Slot(23, testhashu64Fnv1a, 0) end
-function Monster.AddTestarrayofbools(builder, testarrayofbools) builder:PrependUOffsetTRelativeSlot(24, testarrayofbools, 0) end
-function Monster.StartTestarrayofboolsVector(builder, numElems) return builder:StartVector(1, numElems, 1) end
-function Monster.AddTestf(builder, testf) builder:PrependFloat32Slot(25, testf, 3.14159) end
-function Monster.AddTestf2(builder, testf2) builder:PrependFloat32Slot(26, testf2, 3.0) end
-function Monster.AddTestf3(builder, testf3) builder:PrependFloat32Slot(27, testf3, 0.0) end
-function Monster.AddTestarrayofstring2(builder, testarrayofstring2) builder:PrependUOffsetTRelativeSlot(28, testarrayofstring2, 0) end
-function Monster.StartTestarrayofstring2Vector(builder, numElems) return builder:StartVector(4, numElems, 4) end
-function Monster.AddTestarrayofsortedstruct(builder, testarrayofsortedstruct) builder:PrependUOffsetTRelativeSlot(29, testarrayofsortedstruct, 0) end
-function Monster.StartTestarrayofsortedstructVector(builder, numElems) return builder:StartVector(8, numElems, 4) end
-function Monster.AddFlex(builder, flex) builder:PrependUOffsetTRelativeSlot(30, flex, 0) end
-function Monster.StartFlexVector(builder, numElems) return builder:StartVector(1, numElems, 1) end
-function Monster.AddTest5(builder, test5) builder:PrependUOffsetTRelativeSlot(31, test5, 0) end
-function Monster.StartTest5Vector(builder, numElems) return builder:StartVector(4, numElems, 2) end
-function Monster.AddVectorOfLongs(builder, vectorOfLongs) builder:PrependUOffsetTRelativeSlot(32, vectorOfLongs, 0) end
-function Monster.StartVectorOfLongsVector(builder, numElems) return builder:StartVector(8, numElems, 8) end
-function Monster.AddVectorOfDoubles(builder, vectorOfDoubles) builder:PrependUOffsetTRelativeSlot(33, vectorOfDoubles, 0) end
-function Monster.StartVectorOfDoublesVector(builder, numElems) return builder:StartVector(8, numElems, 8) end
-function Monster.AddParentNamespaceTest(builder, parentNamespaceTest) builder:PrependUOffsetTRelativeSlot(34, parentNamespaceTest, 0) end
-function Monster.AddVectorOfReferrables(builder, vectorOfReferrables) builder:PrependUOffsetTRelativeSlot(35, vectorOfReferrables, 0) end
-function Monster.StartVectorOfReferrablesVector(builder, numElems) return builder:StartVector(4, numElems, 4) end
-function Monster.AddSingleWeakReference(builder, singleWeakReference) builder:PrependUint64Slot(36, singleWeakReference, 0) end
-function Monster.AddVectorOfWeakReferences(builder, vectorOfWeakReferences) builder:PrependUOffsetTRelativeSlot(37, vectorOfWeakReferences, 0) end
-function Monster.StartVectorOfWeakReferencesVector(builder, numElems) return builder:StartVector(8, numElems, 8) end
-function Monster.AddVectorOfStrongReferrables(builder, vectorOfStrongReferrables) builder:PrependUOffsetTRelativeSlot(38, vectorOfStrongReferrables, 0) end
-function Monster.StartVectorOfStrongReferrablesVector(builder, numElems) return builder:StartVector(4, numElems, 4) end
-function Monster.AddCoOwningReference(builder, coOwningReference) builder:PrependUint64Slot(39, coOwningReference, 0) end
-function Monster.AddVectorOfCoOwningReferences(builder, vectorOfCoOwningReferences) builder:PrependUOffsetTRelativeSlot(40, vectorOfCoOwningReferences, 0) end
-function Monster.StartVectorOfCoOwningReferencesVector(builder, numElems) return builder:StartVector(8, numElems, 8) end
-function Monster.AddNonOwningReference(builder, nonOwningReference) builder:PrependUint64Slot(41, nonOwningReference, 0) end
-function Monster.AddVectorOfNonOwningReferences(builder, vectorOfNonOwningReferences) builder:PrependUOffsetTRelativeSlot(42, vectorOfNonOwningReferences, 0) end
-function Monster.StartVectorOfNonOwningReferencesVector(builder, numElems) return builder:StartVector(8, numElems, 8) end
-function Monster.AddAnyUniqueType(builder, anyUniqueType) builder:PrependUint8Slot(43, anyUniqueType, 0) end
-function Monster.AddAnyUnique(builder, anyUnique) builder:PrependUOffsetTRelativeSlot(44, anyUnique, 0) end
-function Monster.AddAnyAmbiguousType(builder, anyAmbiguousType) builder:PrependUint8Slot(45, anyAmbiguousType, 0) end
-function Monster.AddAnyAmbiguous(builder, anyAmbiguous) builder:PrependUOffsetTRelativeSlot(46, anyAmbiguous, 0) end
-function Monster.AddVectorOfEnums(builder, vectorOfEnums) builder:PrependUOffsetTRelativeSlot(47, vectorOfEnums, 0) end
-function Monster.StartVectorOfEnumsVector(builder, numElems) return builder:StartVector(1, numElems, 1) end
-function Monster.AddSignedEnum(builder, signedEnum) builder:PrependInt8Slot(48, signedEnum, -1) end
-function Monster.AddTestrequirednestedflatbuffer(builder, testrequirednestedflatbuffer) builder:PrependUOffsetTRelativeSlot(49, testrequirednestedflatbuffer, 0) end
-function Monster.StartTestrequirednestedflatbufferVector(builder, numElems) return builder:StartVector(1, numElems, 1) end
-function Monster.End(builder) return builder:EndObject() end
-return Monster -- return the module
\ No newline at end of file
+function mt:TestarrayoftablesLength()
+ local o = self.view:Offset(26)
+ if o ~= 0 then
+ return self.view:VectorLen(o)
+ end
+ return 0
+end
+
+function mt:Enemy()
+ local o = self.view:Offset(28)
+ if o ~= 0 then
+ local x = self.view:Indirect(self.view.pos + o)
+ local obj = Monster.New()
+ obj:Init(self.view.bytes, x)
+ return obj
+ end
+end
+
+function mt:Testnestedflatbuffer(j)
+ local o = self.view:Offset(30)
+ if o ~= 0 then
+ local a = self.view:Vector(o)
+ return self.view:Get(flatbuffers.N.Uint8, a + ((j-1) * 1))
+ end
+ return 0
+end
+
+function mt:TestnestedflatbufferAsString(start, stop)
+ return self.view:VectorAsString(30, start, stop)
+end
+
+function mt:TestnestedflatbufferLength()
+ local o = self.view:Offset(30)
+ if o ~= 0 then
+ return self.view:VectorLen(o)
+ end
+ return 0
+end
+
+function mt:Testempty()
+ local o = self.view:Offset(32)
+ if o ~= 0 then
+ local x = self.view:Indirect(self.view.pos + o)
+ local obj = __MyGame_Example_Stat.New()
+ obj:Init(self.view.bytes, x)
+ return obj
+ end
+end
+
+function mt:Testbool()
+ local o = self.view:Offset(34)
+ if o ~= 0 then
+ return (self.view:Get(flatbuffers.N.Bool, self.view.pos + o) ~=0)
+ end
+ return false
+end
+
+function mt:Testhashs32Fnv1()
+ local o = self.view:Offset(36)
+ if o ~= 0 then
+ return self.view:Get(flatbuffers.N.Int32, self.view.pos + o)
+ end
+ return 0
+end
+
+function mt:Testhashu32Fnv1()
+ local o = self.view:Offset(38)
+ if o ~= 0 then
+ return self.view:Get(flatbuffers.N.Uint32, self.view.pos + o)
+ end
+ return 0
+end
+
+function mt:Testhashs64Fnv1()
+ local o = self.view:Offset(40)
+ if o ~= 0 then
+ return self.view:Get(flatbuffers.N.Int64, self.view.pos + o)
+ end
+ return 0
+end
+
+function mt:Testhashu64Fnv1()
+ local o = self.view:Offset(42)
+ if o ~= 0 then
+ return self.view:Get(flatbuffers.N.Uint64, self.view.pos + o)
+ end
+ return 0
+end
+
+function mt:Testhashs32Fnv1a()
+ local o = self.view:Offset(44)
+ if o ~= 0 then
+ return self.view:Get(flatbuffers.N.Int32, self.view.pos + o)
+ end
+ return 0
+end
+
+function mt:Testhashu32Fnv1a()
+ local o = self.view:Offset(46)
+ if o ~= 0 then
+ return self.view:Get(flatbuffers.N.Uint32, self.view.pos + o)
+ end
+ return 0
+end
+
+function mt:Testhashs64Fnv1a()
+ local o = self.view:Offset(48)
+ if o ~= 0 then
+ return self.view:Get(flatbuffers.N.Int64, self.view.pos + o)
+ end
+ return 0
+end
+
+function mt:Testhashu64Fnv1a()
+ local o = self.view:Offset(50)
+ if o ~= 0 then
+ return self.view:Get(flatbuffers.N.Uint64, self.view.pos + o)
+ end
+ return 0
+end
+
+function mt:Testarrayofbools(j)
+ local o = self.view:Offset(52)
+ if o ~= 0 then
+ local a = self.view:Vector(o)
+ return self.view:Get(flatbuffers.N.Bool, a + ((j-1) * 1))
+ end
+ return 0
+end
+
+function mt:TestarrayofboolsAsString(start, stop)
+ return self.view:VectorAsString(52, start, stop)
+end
+
+function mt:TestarrayofboolsLength()
+ local o = self.view:Offset(52)
+ if o ~= 0 then
+ return self.view:VectorLen(o)
+ end
+ return 0
+end
+
+function mt:Testf()
+ local o = self.view:Offset(54)
+ if o ~= 0 then
+ return self.view:Get(flatbuffers.N.Float32, self.view.pos + o)
+ end
+ return 3.14159
+end
+
+function mt:Testf2()
+ local o = self.view:Offset(56)
+ if o ~= 0 then
+ return self.view:Get(flatbuffers.N.Float32, self.view.pos + o)
+ end
+ return 3.0
+end
+
+function mt:Testf3()
+ local o = self.view:Offset(58)
+ if o ~= 0 then
+ return self.view:Get(flatbuffers.N.Float32, self.view.pos + o)
+ end
+ return 0.0
+end
+
+function mt:Testarrayofstring2(j)
+ local o = self.view:Offset(60)
+ if o ~= 0 then
+ local a = self.view:Vector(o)
+ return self.view:String(a + ((j-1) * 4))
+ end
+ return ''
+end
+
+function mt:Testarrayofstring2Length()
+ local o = self.view:Offset(60)
+ if o ~= 0 then
+ return self.view:VectorLen(o)
+ end
+ return 0
+end
+
+function mt:Testarrayofsortedstruct(j)
+ local o = self.view:Offset(62)
+ if o ~= 0 then
+ local x = self.view:Vector(o)
+ x = x + ((j-1) * 4)
+ local obj = __MyGame_Example_Ability.New()
+ obj:Init(self.view.bytes, x)
+ return obj
+ end
+end
+
+function mt:TestarrayofsortedstructLength()
+ local o = self.view:Offset(62)
+ if o ~= 0 then
+ return self.view:VectorLen(o)
+ end
+ return 0
+end
+
+function mt:Flex(j)
+ local o = self.view:Offset(64)
+ if o ~= 0 then
+ local a = self.view:Vector(o)
+ return self.view:Get(flatbuffers.N.Uint8, a + ((j-1) * 1))
+ end
+ return 0
+end
+
+function mt:FlexAsString(start, stop)
+ return self.view:VectorAsString(64, start, stop)
+end
+
+function mt:FlexLength()
+ local o = self.view:Offset(64)
+ if o ~= 0 then
+ return self.view:VectorLen(o)
+ end
+ return 0
+end
+
+function mt:Test5(j)
+ local o = self.view:Offset(66)
+ if o ~= 0 then
+ local x = self.view:Vector(o)
+ x = x + ((j-1) * 4)
+ local obj = __MyGame_Example_Test.New()
+ obj:Init(self.view.bytes, x)
+ return obj
+ end
+end
+
+function mt:Test5Length()
+ local o = self.view:Offset(66)
+ if o ~= 0 then
+ return self.view:VectorLen(o)
+ end
+ return 0
+end
+
+function mt:VectorOfLongs(j)
+ local o = self.view:Offset(68)
+ if o ~= 0 then
+ local a = self.view:Vector(o)
+ return self.view:Get(flatbuffers.N.Int64, a + ((j-1) * 8))
+ end
+ return 0
+end
+
+function mt:VectorOfLongsLength()
+ local o = self.view:Offset(68)
+ if o ~= 0 then
+ return self.view:VectorLen(o)
+ end
+ return 0
+end
+
+function mt:VectorOfDoubles(j)
+ local o = self.view:Offset(70)
+ if o ~= 0 then
+ local a = self.view:Vector(o)
+ return self.view:Get(flatbuffers.N.Float64, a + ((j-1) * 8))
+ end
+ return 0
+end
+
+function mt:VectorOfDoublesLength()
+ local o = self.view:Offset(70)
+ if o ~= 0 then
+ return self.view:VectorLen(o)
+ end
+ return 0
+end
+
+function mt:ParentNamespaceTest()
+ local o = self.view:Offset(72)
+ if o ~= 0 then
+ local x = self.view:Indirect(self.view.pos + o)
+ local obj = __MyGame_InParentNamespace.New()
+ obj:Init(self.view.bytes, x)
+ return obj
+ end
+end
+
+function mt:VectorOfReferrables(j)
+ local o = self.view:Offset(74)
+ if o ~= 0 then
+ local x = self.view:Vector(o)
+ x = x + ((j-1) * 4)
+ x = self.view:Indirect(x)
+ local obj = __MyGame_Example_Referrable.New()
+ obj:Init(self.view.bytes, x)
+ return obj
+ end
+end
+
+function mt:VectorOfReferrablesLength()
+ local o = self.view:Offset(74)
+ if o ~= 0 then
+ return self.view:VectorLen(o)
+ end
+ return 0
+end
+
+function mt:SingleWeakReference()
+ local o = self.view:Offset(76)
+ if o ~= 0 then
+ return self.view:Get(flatbuffers.N.Uint64, self.view.pos + o)
+ end
+ return 0
+end
+
+function mt:VectorOfWeakReferences(j)
+ local o = self.view:Offset(78)
+ if o ~= 0 then
+ local a = self.view:Vector(o)
+ return self.view:Get(flatbuffers.N.Uint64, a + ((j-1) * 8))
+ end
+ return 0
+end
+
+function mt:VectorOfWeakReferencesLength()
+ local o = self.view:Offset(78)
+ if o ~= 0 then
+ return self.view:VectorLen(o)
+ end
+ return 0
+end
+
+function mt:VectorOfStrongReferrables(j)
+ local o = self.view:Offset(80)
+ if o ~= 0 then
+ local x = self.view:Vector(o)
+ x = x + ((j-1) * 4)
+ x = self.view:Indirect(x)
+ local obj = __MyGame_Example_Referrable.New()
+ obj:Init(self.view.bytes, x)
+ return obj
+ end
+end
+
+function mt:VectorOfStrongReferrablesLength()
+ local o = self.view:Offset(80)
+ if o ~= 0 then
+ return self.view:VectorLen(o)
+ end
+ return 0
+end
+
+function mt:CoOwningReference()
+ local o = self.view:Offset(82)
+ if o ~= 0 then
+ return self.view:Get(flatbuffers.N.Uint64, self.view.pos + o)
+ end
+ return 0
+end
+
+function mt:VectorOfCoOwningReferences(j)
+ local o = self.view:Offset(84)
+ if o ~= 0 then
+ local a = self.view:Vector(o)
+ return self.view:Get(flatbuffers.N.Uint64, a + ((j-1) * 8))
+ end
+ return 0
+end
+
+function mt:VectorOfCoOwningReferencesLength()
+ local o = self.view:Offset(84)
+ if o ~= 0 then
+ return self.view:VectorLen(o)
+ end
+ return 0
+end
+
+function mt:NonOwningReference()
+ local o = self.view:Offset(86)
+ if o ~= 0 then
+ return self.view:Get(flatbuffers.N.Uint64, self.view.pos + o)
+ end
+ return 0
+end
+
+function mt:VectorOfNonOwningReferences(j)
+ local o = self.view:Offset(88)
+ if o ~= 0 then
+ local a = self.view:Vector(o)
+ return self.view:Get(flatbuffers.N.Uint64, a + ((j-1) * 8))
+ end
+ return 0
+end
+
+function mt:VectorOfNonOwningReferencesLength()
+ local o = self.view:Offset(88)
+ if o ~= 0 then
+ return self.view:VectorLen(o)
+ end
+ return 0
+end
+
+function mt:AnyUniqueType()
+ local o = self.view:Offset(90)
+ if o ~= 0 then
+ return self.view:Get(flatbuffers.N.Uint8, self.view.pos + o)
+ end
+ return 0
+end
+
+function mt:AnyUnique()
+ local o = self.view:Offset(92)
+ if o ~= 0 then
+ local obj = flatbuffers.view.New(flatbuffers.binaryArray.New(0), 0)
+ self.view:Union(obj, o)
+ return obj
+ end
+end
+
+function mt:AnyAmbiguousType()
+ local o = self.view:Offset(94)
+ if o ~= 0 then
+ return self.view:Get(flatbuffers.N.Uint8, self.view.pos + o)
+ end
+ return 0
+end
+
+function mt:AnyAmbiguous()
+ local o = self.view:Offset(96)
+ if o ~= 0 then
+ local obj = flatbuffers.view.New(flatbuffers.binaryArray.New(0), 0)
+ self.view:Union(obj, o)
+ return obj
+ end
+end
+
+function mt:VectorOfEnums(j)
+ local o = self.view:Offset(98)
+ if o ~= 0 then
+ local a = self.view:Vector(o)
+ return self.view:Get(flatbuffers.N.Uint8, a + ((j-1) * 1))
+ end
+ return 0
+end
+
+function mt:VectorOfEnumsAsString(start, stop)
+ return self.view:VectorAsString(98, start, stop)
+end
+
+function mt:VectorOfEnumsLength()
+ local o = self.view:Offset(98)
+ if o ~= 0 then
+ return self.view:VectorLen(o)
+ end
+ return 0
+end
+
+function mt:SignedEnum()
+ local o = self.view:Offset(100)
+ if o ~= 0 then
+ return self.view:Get(flatbuffers.N.Int8, self.view.pos + o)
+ end
+ return -1
+end
+
+function mt:Testrequirednestedflatbuffer(j)
+ local o = self.view:Offset(102)
+ if o ~= 0 then
+ local a = self.view:Vector(o)
+ return self.view:Get(flatbuffers.N.Uint8, a + ((j-1) * 1))
+ end
+ return 0
+end
+
+function mt:TestrequirednestedflatbufferAsString(start, stop)
+ return self.view:VectorAsString(102, start, stop)
+end
+
+function mt:TestrequirednestedflatbufferLength()
+ local o = self.view:Offset(102)
+ if o ~= 0 then
+ return self.view:VectorLen(o)
+ end
+ return 0
+end
+
+function mt:ScalarKeySortedTables(j)
+ local o = self.view:Offset(104)
+ if o ~= 0 then
+ local x = self.view:Vector(o)
+ x = x + ((j-1) * 4)
+ x = self.view:Indirect(x)
+ local obj = __MyGame_Example_Stat.New()
+ obj:Init(self.view.bytes, x)
+ return obj
+ end
+end
+
+function mt:ScalarKeySortedTablesLength()
+ local o = self.view:Offset(104)
+ if o ~= 0 then
+ return self.view:VectorLen(o)
+ end
+ return 0
+end
+
+function mt:NativeInline()
+ local o = self.view:Offset(106)
+ if o ~= 0 then
+ local x = self.view.pos + o
+ local obj = __MyGame_Example_Test.New()
+ obj:Init(self.view.bytes, x)
+ return obj
+ end
+end
+
+function mt:LongEnumNonEnumDefault()
+ local o = self.view:Offset(108)
+ if o ~= 0 then
+ return self.view:Get(flatbuffers.N.Uint64, self.view.pos + o)
+ end
+ return 0
+end
+
+function mt:LongEnumNormalDefault()
+ local o = self.view:Offset(110)
+ if o ~= 0 then
+ return self.view:Get(flatbuffers.N.Uint64, self.view.pos + o)
+ end
+ return 2
+end
+
+function Monster.Start(builder)
+ builder:StartObject(54)
+end
+
+function Monster.AddPos(builder, pos)
+ builder:PrependStructSlot(0, pos, 0)
+end
+
+function Monster.AddMana(builder, mana)
+ builder:PrependInt16Slot(1, mana, 150)
+end
+
+function Monster.AddHp(builder, hp)
+ builder:PrependInt16Slot(2, hp, 100)
+end
+
+function Monster.AddName(builder, name)
+ builder:PrependUOffsetTRelativeSlot(3, name, 0)
+end
+
+function Monster.AddInventory(builder, inventory)
+ builder:PrependUOffsetTRelativeSlot(5, inventory, 0)
+end
+
+function Monster.StartInventoryVector(builder, numElems)
+ return builder:StartVector(1, numElems, 1)
+end
+
+function Monster.AddColor(builder, color)
+ builder:PrependUint8Slot(6, color, 8)
+end
+
+function Monster.AddTestType(builder, testType)
+ builder:PrependUint8Slot(7, testType, 0)
+end
+
+function Monster.AddTest(builder, test)
+ builder:PrependUOffsetTRelativeSlot(8, test, 0)
+end
+
+function Monster.AddTest4(builder, test4)
+ builder:PrependUOffsetTRelativeSlot(9, test4, 0)
+end
+
+function Monster.StartTest4Vector(builder, numElems)
+ return builder:StartVector(4, numElems, 2)
+end
+
+function Monster.AddTestarrayofstring(builder, testarrayofstring)
+ builder:PrependUOffsetTRelativeSlot(10, testarrayofstring, 0)
+end
+
+function Monster.StartTestarrayofstringVector(builder, numElems)
+ return builder:StartVector(4, numElems, 4)
+end
+
+function Monster.AddTestarrayoftables(builder, testarrayoftables)
+ builder:PrependUOffsetTRelativeSlot(11, testarrayoftables, 0)
+end
+
+function Monster.StartTestarrayoftablesVector(builder, numElems)
+ return builder:StartVector(4, numElems, 4)
+end
+
+function Monster.AddEnemy(builder, enemy)
+ builder:PrependStructSlot(12, enemy, 0)
+end
+
+function Monster.AddTestnestedflatbuffer(builder, testnestedflatbuffer)
+ builder:PrependUOffsetTRelativeSlot(13, testnestedflatbuffer, 0)
+end
+
+function Monster.StartTestnestedflatbufferVector(builder, numElems)
+ return builder:StartVector(1, numElems, 1)
+end
+
+function Monster.AddTestempty(builder, testempty)
+ builder:PrependStructSlot(14, testempty, 0)
+end
+
+function Monster.AddTestbool(builder, testbool)
+ builder:PrependBoolSlot(15, testbool, false)
+end
+
+function Monster.AddTesthashs32Fnv1(builder, testhashs32Fnv1)
+ builder:PrependInt32Slot(16, testhashs32Fnv1, 0)
+end
+
+function Monster.AddTesthashu32Fnv1(builder, testhashu32Fnv1)
+ builder:PrependUint32Slot(17, testhashu32Fnv1, 0)
+end
+
+function Monster.AddTesthashs64Fnv1(builder, testhashs64Fnv1)
+ builder:PrependInt64Slot(18, testhashs64Fnv1, 0)
+end
+
+function Monster.AddTesthashu64Fnv1(builder, testhashu64Fnv1)
+ builder:PrependUint64Slot(19, testhashu64Fnv1, 0)
+end
+
+function Monster.AddTesthashs32Fnv1a(builder, testhashs32Fnv1a)
+ builder:PrependInt32Slot(20, testhashs32Fnv1a, 0)
+end
+
+function Monster.AddTesthashu32Fnv1a(builder, testhashu32Fnv1a)
+ builder:PrependUint32Slot(21, testhashu32Fnv1a, 0)
+end
+
+function Monster.AddTesthashs64Fnv1a(builder, testhashs64Fnv1a)
+ builder:PrependInt64Slot(22, testhashs64Fnv1a, 0)
+end
+
+function Monster.AddTesthashu64Fnv1a(builder, testhashu64Fnv1a)
+ builder:PrependUint64Slot(23, testhashu64Fnv1a, 0)
+end
+
+function Monster.AddTestarrayofbools(builder, testarrayofbools)
+ builder:PrependUOffsetTRelativeSlot(24, testarrayofbools, 0)
+end
+
+function Monster.StartTestarrayofboolsVector(builder, numElems)
+ return builder:StartVector(1, numElems, 1)
+end
+
+function Monster.AddTestf(builder, testf)
+ builder:PrependFloat32Slot(25, testf, 3.14159)
+end
+
+function Monster.AddTestf2(builder, testf2)
+ builder:PrependFloat32Slot(26, testf2, 3.0)
+end
+
+function Monster.AddTestf3(builder, testf3)
+ builder:PrependFloat32Slot(27, testf3, 0.0)
+end
+
+function Monster.AddTestarrayofstring2(builder, testarrayofstring2)
+ builder:PrependUOffsetTRelativeSlot(28, testarrayofstring2, 0)
+end
+
+function Monster.StartTestarrayofstring2Vector(builder, numElems)
+ return builder:StartVector(4, numElems, 4)
+end
+
+function Monster.AddTestarrayofsortedstruct(builder, testarrayofsortedstruct)
+ builder:PrependUOffsetTRelativeSlot(29, testarrayofsortedstruct, 0)
+end
+
+function Monster.StartTestarrayofsortedstructVector(builder, numElems)
+ return builder:StartVector(4, numElems, 4)
+end
+
+function Monster.AddFlex(builder, flex)
+ builder:PrependUOffsetTRelativeSlot(30, flex, 0)
+end
+
+function Monster.StartFlexVector(builder, numElems)
+ return builder:StartVector(1, numElems, 1)
+end
+
+function Monster.AddTest5(builder, test5)
+ builder:PrependUOffsetTRelativeSlot(31, test5, 0)
+end
+
+function Monster.StartTest5Vector(builder, numElems)
+ return builder:StartVector(4, numElems, 2)
+end
+
+function Monster.AddVectorOfLongs(builder, vectorOfLongs)
+ builder:PrependUOffsetTRelativeSlot(32, vectorOfLongs, 0)
+end
+
+function Monster.StartVectorOfLongsVector(builder, numElems)
+ return builder:StartVector(8, numElems, 8)
+end
+
+function Monster.AddVectorOfDoubles(builder, vectorOfDoubles)
+ builder:PrependUOffsetTRelativeSlot(33, vectorOfDoubles, 0)
+end
+
+function Monster.StartVectorOfDoublesVector(builder, numElems)
+ return builder:StartVector(8, numElems, 8)
+end
+
+function Monster.AddParentNamespaceTest(builder, parentNamespaceTest)
+ builder:PrependStructSlot(34, parentNamespaceTest, 0)
+end
+
+function Monster.AddVectorOfReferrables(builder, vectorOfReferrables)
+ builder:PrependUOffsetTRelativeSlot(35, vectorOfReferrables, 0)
+end
+
+function Monster.StartVectorOfReferrablesVector(builder, numElems)
+ return builder:StartVector(4, numElems, 4)
+end
+
+function Monster.AddSingleWeakReference(builder, singleWeakReference)
+ builder:PrependUint64Slot(36, singleWeakReference, 0)
+end
+
+function Monster.AddVectorOfWeakReferences(builder, vectorOfWeakReferences)
+ builder:PrependUOffsetTRelativeSlot(37, vectorOfWeakReferences, 0)
+end
+
+function Monster.StartVectorOfWeakReferencesVector(builder, numElems)
+ return builder:StartVector(8, numElems, 8)
+end
+
+function Monster.AddVectorOfStrongReferrables(builder, vectorOfStrongReferrables)
+ builder:PrependUOffsetTRelativeSlot(38, vectorOfStrongReferrables, 0)
+end
+
+function Monster.StartVectorOfStrongReferrablesVector(builder, numElems)
+ return builder:StartVector(4, numElems, 4)
+end
+
+function Monster.AddCoOwningReference(builder, coOwningReference)
+ builder:PrependUint64Slot(39, coOwningReference, 0)
+end
+
+function Monster.AddVectorOfCoOwningReferences(builder, vectorOfCoOwningReferences)
+ builder:PrependUOffsetTRelativeSlot(40, vectorOfCoOwningReferences, 0)
+end
+
+function Monster.StartVectorOfCoOwningReferencesVector(builder, numElems)
+ return builder:StartVector(8, numElems, 8)
+end
+
+function Monster.AddNonOwningReference(builder, nonOwningReference)
+ builder:PrependUint64Slot(41, nonOwningReference, 0)
+end
+
+function Monster.AddVectorOfNonOwningReferences(builder, vectorOfNonOwningReferences)
+ builder:PrependUOffsetTRelativeSlot(42, vectorOfNonOwningReferences, 0)
+end
+
+function Monster.StartVectorOfNonOwningReferencesVector(builder, numElems)
+ return builder:StartVector(8, numElems, 8)
+end
+
+function Monster.AddAnyUniqueType(builder, anyUniqueType)
+ builder:PrependUint8Slot(43, anyUniqueType, 0)
+end
+
+function Monster.AddAnyUnique(builder, anyUnique)
+ builder:PrependUOffsetTRelativeSlot(44, anyUnique, 0)
+end
+
+function Monster.AddAnyAmbiguousType(builder, anyAmbiguousType)
+ builder:PrependUint8Slot(45, anyAmbiguousType, 0)
+end
+
+function Monster.AddAnyAmbiguous(builder, anyAmbiguous)
+ builder:PrependUOffsetTRelativeSlot(46, anyAmbiguous, 0)
+end
+
+function Monster.AddVectorOfEnums(builder, vectorOfEnums)
+ builder:PrependUOffsetTRelativeSlot(47, vectorOfEnums, 0)
+end
+
+function Monster.StartVectorOfEnumsVector(builder, numElems)
+ return builder:StartVector(1, numElems, 1)
+end
+
+function Monster.AddSignedEnum(builder, signedEnum)
+ builder:PrependInt8Slot(48, signedEnum, -1)
+end
+
+function Monster.AddTestrequirednestedflatbuffer(builder, testrequirednestedflatbuffer)
+ builder:PrependUOffsetTRelativeSlot(49, testrequirednestedflatbuffer, 0)
+end
+
+function Monster.StartTestrequirednestedflatbufferVector(builder, numElems)
+ return builder:StartVector(1, numElems, 1)
+end
+
+function Monster.AddScalarKeySortedTables(builder, scalarKeySortedTables)
+ builder:PrependUOffsetTRelativeSlot(50, scalarKeySortedTables, 0)
+end
+
+function Monster.StartScalarKeySortedTablesVector(builder, numElems)
+ return builder:StartVector(4, numElems, 4)
+end
+
+function Monster.AddNativeInline(builder, nativeInline)
+ builder:PrependStructSlot(51, nativeInline, 0)
+end
+
+function Monster.AddLongEnumNonEnumDefault(builder, longEnumNonEnumDefault)
+ builder:PrependUint64Slot(52, longEnumNonEnumDefault, 0)
+end
+
+function Monster.AddLongEnumNormalDefault(builder, longEnumNormalDefault)
+ builder:PrependUint64Slot(53, longEnumNormalDefault, 2)
+end
+
+function Monster.End(builder)
+ return builder:EndObject()
+end
+
+return Monster
\ No newline at end of file
diff --git a/tests/MyGame/Example/Monster.php b/tests/MyGame/Example/Monster.php
index 21e27dc..5f8ad5a 100644
--- a/tests/MyGame/Example/Monster.php
+++ b/tests/MyGame/Example/Monster.php
@@ -711,21 +711,65 @@
}
/**
+ * @returnVectorOffset
+ */
+ public function getScalarKeySortedTables($j)
+ {
+ $o = $this->__offset(104);
+ $obj = new Stat();
+ return $o != 0 ? $obj->init($this->__indirect($this->__vector($o) + $j * 4), $this->bb) : null;
+ }
+
+ /**
+ * @return int
+ */
+ public function getScalarKeySortedTablesLength()
+ {
+ $o = $this->__offset(104);
+ return $o != 0 ? $this->__vector_len($o) : 0;
+ }
+
+ public function getNativeInline()
+ {
+ $obj = new Test();
+ $o = $this->__offset(106);
+ return $o != 0 ? $obj->init($o + $this->bb_pos, $this->bb) : 0;
+ }
+
+ /**
+ * @return ulong
+ */
+ public function getLongEnumNonEnumDefault()
+ {
+ $o = $this->__offset(108);
+ return $o != 0 ? $this->bb->getUlong($o + $this->bb_pos) : 0;
+ }
+
+ /**
+ * @return ulong
+ */
+ public function getLongEnumNormalDefault()
+ {
+ $o = $this->__offset(110);
+ return $o != 0 ? $this->bb->getUlong($o + $this->bb_pos) : \MyGame\Example\LongEnum::LongOne;
+ }
+
+ /**
* @param FlatBufferBuilder $builder
* @return void
*/
public static function startMonster(FlatBufferBuilder $builder)
{
- $builder->StartObject(50);
+ $builder->StartObject(54);
}
/**
* @param FlatBufferBuilder $builder
* @return Monster
*/
- public static function createMonster(FlatBufferBuilder $builder, $pos, $mana, $hp, $name, $inventory, $color, $test_type, $test, $test4, $testarrayofstring, $testarrayoftables, $enemy, $testnestedflatbuffer, $testempty, $testbool, $testhashs32_fnv1, $testhashu32_fnv1, $testhashs64_fnv1, $testhashu64_fnv1, $testhashs32_fnv1a, $testhashu32_fnv1a, $testhashs64_fnv1a, $testhashu64_fnv1a, $testarrayofbools, $testf, $testf2, $testf3, $testarrayofstring2, $testarrayofsortedstruct, $flex, $test5, $vector_of_longs, $vector_of_doubles, $parent_namespace_test, $vector_of_referrables, $single_weak_reference, $vector_of_weak_references, $vector_of_strong_referrables, $co_owning_reference, $vector_of_co_owning_references, $non_owning_reference, $vector_of_non_owning_references, $any_unique_type, $any_unique, $any_ambiguous_type, $any_ambiguous, $vector_of_enums, $signed_enum, $testrequirednestedflatbuffer)
+ public static function createMonster(FlatBufferBuilder $builder, $pos, $mana, $hp, $name, $inventory, $color, $test_type, $test, $test4, $testarrayofstring, $testarrayoftables, $enemy, $testnestedflatbuffer, $testempty, $testbool, $testhashs32_fnv1, $testhashu32_fnv1, $testhashs64_fnv1, $testhashu64_fnv1, $testhashs32_fnv1a, $testhashu32_fnv1a, $testhashs64_fnv1a, $testhashu64_fnv1a, $testarrayofbools, $testf, $testf2, $testf3, $testarrayofstring2, $testarrayofsortedstruct, $flex, $test5, $vector_of_longs, $vector_of_doubles, $parent_namespace_test, $vector_of_referrables, $single_weak_reference, $vector_of_weak_references, $vector_of_strong_referrables, $co_owning_reference, $vector_of_co_owning_references, $non_owning_reference, $vector_of_non_owning_references, $any_unique_type, $any_unique, $any_ambiguous_type, $any_ambiguous, $vector_of_enums, $signed_enum, $testrequirednestedflatbuffer, $scalar_key_sorted_tables, $native_inline, $long_enum_non_enum_default, $long_enum_normal_default)
{
- $builder->startObject(50);
+ $builder->startObject(54);
self::addPos($builder, $pos);
self::addMana($builder, $mana);
self::addHp($builder, $hp);
@@ -775,6 +819,10 @@
self::addVectorOfEnums($builder, $vector_of_enums);
self::addSignedEnum($builder, $signed_enum);
self::addTestrequirednestedflatbuffer($builder, $testrequirednestedflatbuffer);
+ self::addScalarKeySortedTables($builder, $scalar_key_sorted_tables);
+ self::addNativeInline($builder, $native_inline);
+ self::addLongEnumNonEnumDefault($builder, $long_enum_non_enum_default);
+ self::addLongEnumNormalDefault($builder, $long_enum_normal_default);
$o = $builder->endObject();
$builder->required($o, 10); // name
return $o;
@@ -1713,6 +1761,70 @@
/**
* @param FlatBufferBuilder $builder
+ * @param VectorOffset
+ * @return void
+ */
+ public static function addScalarKeySortedTables(FlatBufferBuilder $builder, $scalarKeySortedTables)
+ {
+ $builder->addOffsetX(50, $scalarKeySortedTables, 0);
+ }
+
+ /**
+ * @param FlatBufferBuilder $builder
+ * @param array offset array
+ * @return int vector offset
+ */
+ public static function createScalarKeySortedTablesVector(FlatBufferBuilder $builder, array $data)
+ {
+ $builder->startVector(4, count($data), 4);
+ for ($i = count($data) - 1; $i >= 0; $i--) {
+ $builder->putOffset($data[$i]);
+ }
+ return $builder->endVector();
+ }
+
+ /**
+ * @param FlatBufferBuilder $builder
+ * @param int $numElems
+ * @return void
+ */
+ public static function startScalarKeySortedTablesVector(FlatBufferBuilder $builder, $numElems)
+ {
+ $builder->startVector(4, $numElems, 4);
+ }
+
+ /**
+ * @param FlatBufferBuilder $builder
+ * @param int
+ * @return void
+ */
+ public static function addNativeInline(FlatBufferBuilder $builder, $nativeInline)
+ {
+ $builder->addStructX(51, $nativeInline, 0);
+ }
+
+ /**
+ * @param FlatBufferBuilder $builder
+ * @param ulong
+ * @return void
+ */
+ public static function addLongEnumNonEnumDefault(FlatBufferBuilder $builder, $longEnumNonEnumDefault)
+ {
+ $builder->addUlongX(52, $longEnumNonEnumDefault, 0);
+ }
+
+ /**
+ * @param FlatBufferBuilder $builder
+ * @param ulong
+ * @return void
+ */
+ public static function addLongEnumNormalDefault(FlatBufferBuilder $builder, $longEnumNormalDefault)
+ {
+ $builder->addUlongX(53, $longEnumNormalDefault, 2);
+ }
+
+ /**
+ * @param FlatBufferBuilder $builder
* @return int table offset
*/
public static function endMonster(FlatBufferBuilder $builder)
diff --git a/tests/MyGame/Example/Monster.py b/tests/MyGame/Example/Monster.py
index 67f6e1b..0044f8d 100644
--- a/tests/MyGame/Example/Monster.py
+++ b/tests/MyGame/Example/Monster.py
@@ -11,13 +11,17 @@
__slots__ = ['_tab']
@classmethod
- def GetRootAsMonster(cls, buf, offset):
+ def GetRootAs(cls, buf, offset=0):
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
x = Monster()
x.Init(buf, n + offset)
return x
@classmethod
+ def GetRootAsMonster(cls, buf, offset=0):
+ """This method is deprecated. Please switch to GetRootAs."""
+ return cls.GetRootAs(buf, offset)
+ @classmethod
def MonsterBufferHasIdentifier(cls, buf, offset, size_prefixed=False):
return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4D\x4F\x4E\x53", size_prefixed=size_prefixed)
@@ -206,6 +210,14 @@
return 0
# Monster
+ def TestnestedflatbufferNestedRoot(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(30))
+ if o != 0:
+ from MyGame.Example.Monster import Monster
+ return Monster.GetRootAsMonster(self._tab.Bytes, self._tab.Vector(o))
+ return 0
+
+ # Monster
def TestnestedflatbufferLength(self):
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(30))
if o != 0:
@@ -735,6 +747,14 @@
return 0
# Monster
+ def TestrequirednestedflatbufferNestedRoot(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(102))
+ if o != 0:
+ from MyGame.Example.Monster import Monster
+ return Monster.GetRootAsMonster(self._tab.Bytes, self._tab.Vector(o))
+ return 0
+
+ # Monster
def TestrequirednestedflatbufferLength(self):
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(102))
if o != 0:
@@ -746,77 +766,295 @@
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(102))
return o == 0
-def MonsterStart(builder): builder.StartObject(50)
-def MonsterAddPos(builder, pos): builder.PrependStructSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(pos), 0)
-def MonsterAddMana(builder, mana): builder.PrependInt16Slot(1, mana, 150)
-def MonsterAddHp(builder, hp): builder.PrependInt16Slot(2, hp, 100)
-def MonsterAddName(builder, name): builder.PrependUOffsetTRelativeSlot(3, flatbuffers.number_types.UOffsetTFlags.py_type(name), 0)
-def MonsterAddInventory(builder, inventory): builder.PrependUOffsetTRelativeSlot(5, flatbuffers.number_types.UOffsetTFlags.py_type(inventory), 0)
-def MonsterStartInventoryVector(builder, numElems): return builder.StartVector(1, numElems, 1)
-def MonsterAddColor(builder, color): builder.PrependUint8Slot(6, color, 8)
-def MonsterAddTestType(builder, testType): builder.PrependUint8Slot(7, testType, 0)
-def MonsterAddTest(builder, test): builder.PrependUOffsetTRelativeSlot(8, flatbuffers.number_types.UOffsetTFlags.py_type(test), 0)
-def MonsterAddTest4(builder, test4): builder.PrependUOffsetTRelativeSlot(9, flatbuffers.number_types.UOffsetTFlags.py_type(test4), 0)
-def MonsterStartTest4Vector(builder, numElems): return builder.StartVector(4, numElems, 2)
-def MonsterAddTestarrayofstring(builder, testarrayofstring): builder.PrependUOffsetTRelativeSlot(10, flatbuffers.number_types.UOffsetTFlags.py_type(testarrayofstring), 0)
-def MonsterStartTestarrayofstringVector(builder, numElems): return builder.StartVector(4, numElems, 4)
-def MonsterAddTestarrayoftables(builder, testarrayoftables): builder.PrependUOffsetTRelativeSlot(11, flatbuffers.number_types.UOffsetTFlags.py_type(testarrayoftables), 0)
-def MonsterStartTestarrayoftablesVector(builder, numElems): return builder.StartVector(4, numElems, 4)
-def MonsterAddEnemy(builder, enemy): builder.PrependUOffsetTRelativeSlot(12, flatbuffers.number_types.UOffsetTFlags.py_type(enemy), 0)
-def MonsterAddTestnestedflatbuffer(builder, testnestedflatbuffer): builder.PrependUOffsetTRelativeSlot(13, flatbuffers.number_types.UOffsetTFlags.py_type(testnestedflatbuffer), 0)
-def MonsterStartTestnestedflatbufferVector(builder, numElems): return builder.StartVector(1, numElems, 1)
-def MonsterAddTestempty(builder, testempty): builder.PrependUOffsetTRelativeSlot(14, flatbuffers.number_types.UOffsetTFlags.py_type(testempty), 0)
-def MonsterAddTestbool(builder, testbool): builder.PrependBoolSlot(15, testbool, 0)
-def MonsterAddTesthashs32Fnv1(builder, testhashs32Fnv1): builder.PrependInt32Slot(16, testhashs32Fnv1, 0)
-def MonsterAddTesthashu32Fnv1(builder, testhashu32Fnv1): builder.PrependUint32Slot(17, testhashu32Fnv1, 0)
-def MonsterAddTesthashs64Fnv1(builder, testhashs64Fnv1): builder.PrependInt64Slot(18, testhashs64Fnv1, 0)
-def MonsterAddTesthashu64Fnv1(builder, testhashu64Fnv1): builder.PrependUint64Slot(19, testhashu64Fnv1, 0)
-def MonsterAddTesthashs32Fnv1a(builder, testhashs32Fnv1a): builder.PrependInt32Slot(20, testhashs32Fnv1a, 0)
-def MonsterAddTesthashu32Fnv1a(builder, testhashu32Fnv1a): builder.PrependUint32Slot(21, testhashu32Fnv1a, 0)
-def MonsterAddTesthashs64Fnv1a(builder, testhashs64Fnv1a): builder.PrependInt64Slot(22, testhashs64Fnv1a, 0)
-def MonsterAddTesthashu64Fnv1a(builder, testhashu64Fnv1a): builder.PrependUint64Slot(23, testhashu64Fnv1a, 0)
-def MonsterAddTestarrayofbools(builder, testarrayofbools): builder.PrependUOffsetTRelativeSlot(24, flatbuffers.number_types.UOffsetTFlags.py_type(testarrayofbools), 0)
-def MonsterStartTestarrayofboolsVector(builder, numElems): return builder.StartVector(1, numElems, 1)
-def MonsterAddTestf(builder, testf): builder.PrependFloat32Slot(25, testf, 3.14159)
-def MonsterAddTestf2(builder, testf2): builder.PrependFloat32Slot(26, testf2, 3.0)
-def MonsterAddTestf3(builder, testf3): builder.PrependFloat32Slot(27, testf3, 0.0)
-def MonsterAddTestarrayofstring2(builder, testarrayofstring2): builder.PrependUOffsetTRelativeSlot(28, flatbuffers.number_types.UOffsetTFlags.py_type(testarrayofstring2), 0)
-def MonsterStartTestarrayofstring2Vector(builder, numElems): return builder.StartVector(4, numElems, 4)
-def MonsterAddTestarrayofsortedstruct(builder, testarrayofsortedstruct): builder.PrependUOffsetTRelativeSlot(29, flatbuffers.number_types.UOffsetTFlags.py_type(testarrayofsortedstruct), 0)
-def MonsterStartTestarrayofsortedstructVector(builder, numElems): return builder.StartVector(8, numElems, 4)
-def MonsterAddFlex(builder, flex): builder.PrependUOffsetTRelativeSlot(30, flatbuffers.number_types.UOffsetTFlags.py_type(flex), 0)
-def MonsterStartFlexVector(builder, numElems): return builder.StartVector(1, numElems, 1)
-def MonsterAddTest5(builder, test5): builder.PrependUOffsetTRelativeSlot(31, flatbuffers.number_types.UOffsetTFlags.py_type(test5), 0)
-def MonsterStartTest5Vector(builder, numElems): return builder.StartVector(4, numElems, 2)
-def MonsterAddVectorOfLongs(builder, vectorOfLongs): builder.PrependUOffsetTRelativeSlot(32, flatbuffers.number_types.UOffsetTFlags.py_type(vectorOfLongs), 0)
-def MonsterStartVectorOfLongsVector(builder, numElems): return builder.StartVector(8, numElems, 8)
-def MonsterAddVectorOfDoubles(builder, vectorOfDoubles): builder.PrependUOffsetTRelativeSlot(33, flatbuffers.number_types.UOffsetTFlags.py_type(vectorOfDoubles), 0)
-def MonsterStartVectorOfDoublesVector(builder, numElems): return builder.StartVector(8, numElems, 8)
-def MonsterAddParentNamespaceTest(builder, parentNamespaceTest): builder.PrependUOffsetTRelativeSlot(34, flatbuffers.number_types.UOffsetTFlags.py_type(parentNamespaceTest), 0)
-def MonsterAddVectorOfReferrables(builder, vectorOfReferrables): builder.PrependUOffsetTRelativeSlot(35, flatbuffers.number_types.UOffsetTFlags.py_type(vectorOfReferrables), 0)
-def MonsterStartVectorOfReferrablesVector(builder, numElems): return builder.StartVector(4, numElems, 4)
-def MonsterAddSingleWeakReference(builder, singleWeakReference): builder.PrependUint64Slot(36, singleWeakReference, 0)
-def MonsterAddVectorOfWeakReferences(builder, vectorOfWeakReferences): builder.PrependUOffsetTRelativeSlot(37, flatbuffers.number_types.UOffsetTFlags.py_type(vectorOfWeakReferences), 0)
-def MonsterStartVectorOfWeakReferencesVector(builder, numElems): return builder.StartVector(8, numElems, 8)
-def MonsterAddVectorOfStrongReferrables(builder, vectorOfStrongReferrables): builder.PrependUOffsetTRelativeSlot(38, flatbuffers.number_types.UOffsetTFlags.py_type(vectorOfStrongReferrables), 0)
-def MonsterStartVectorOfStrongReferrablesVector(builder, numElems): return builder.StartVector(4, numElems, 4)
-def MonsterAddCoOwningReference(builder, coOwningReference): builder.PrependUint64Slot(39, coOwningReference, 0)
-def MonsterAddVectorOfCoOwningReferences(builder, vectorOfCoOwningReferences): builder.PrependUOffsetTRelativeSlot(40, flatbuffers.number_types.UOffsetTFlags.py_type(vectorOfCoOwningReferences), 0)
-def MonsterStartVectorOfCoOwningReferencesVector(builder, numElems): return builder.StartVector(8, numElems, 8)
-def MonsterAddNonOwningReference(builder, nonOwningReference): builder.PrependUint64Slot(41, nonOwningReference, 0)
-def MonsterAddVectorOfNonOwningReferences(builder, vectorOfNonOwningReferences): builder.PrependUOffsetTRelativeSlot(42, flatbuffers.number_types.UOffsetTFlags.py_type(vectorOfNonOwningReferences), 0)
-def MonsterStartVectorOfNonOwningReferencesVector(builder, numElems): return builder.StartVector(8, numElems, 8)
-def MonsterAddAnyUniqueType(builder, anyUniqueType): builder.PrependUint8Slot(43, anyUniqueType, 0)
-def MonsterAddAnyUnique(builder, anyUnique): builder.PrependUOffsetTRelativeSlot(44, flatbuffers.number_types.UOffsetTFlags.py_type(anyUnique), 0)
-def MonsterAddAnyAmbiguousType(builder, anyAmbiguousType): builder.PrependUint8Slot(45, anyAmbiguousType, 0)
-def MonsterAddAnyAmbiguous(builder, anyAmbiguous): builder.PrependUOffsetTRelativeSlot(46, flatbuffers.number_types.UOffsetTFlags.py_type(anyAmbiguous), 0)
-def MonsterAddVectorOfEnums(builder, vectorOfEnums): builder.PrependUOffsetTRelativeSlot(47, flatbuffers.number_types.UOffsetTFlags.py_type(vectorOfEnums), 0)
-def MonsterStartVectorOfEnumsVector(builder, numElems): return builder.StartVector(1, numElems, 1)
-def MonsterAddSignedEnum(builder, signedEnum): builder.PrependInt8Slot(48, signedEnum, -1)
-def MonsterAddTestrequirednestedflatbuffer(builder, testrequirednestedflatbuffer): builder.PrependUOffsetTRelativeSlot(49, flatbuffers.number_types.UOffsetTFlags.py_type(testrequirednestedflatbuffer), 0)
-def MonsterStartTestrequirednestedflatbufferVector(builder, numElems): return builder.StartVector(1, numElems, 1)
-def MonsterEnd(builder): return builder.EndObject()
+ # Monster
+ def ScalarKeySortedTables(self, j):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(104))
+ if o != 0:
+ x = self._tab.Vector(o)
+ x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4
+ x = self._tab.Indirect(x)
+ from MyGame.Example.Stat import Stat
+ obj = Stat()
+ obj.Init(self._tab.Bytes, x)
+ return obj
+ return None
+ # Monster
+ def ScalarKeySortedTablesLength(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(104))
+ if o != 0:
+ return self._tab.VectorLen(o)
+ return 0
+
+ # Monster
+ def ScalarKeySortedTablesIsNone(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(104))
+ return o == 0
+
+ # Monster
+ def NativeInline(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(106))
+ if o != 0:
+ x = o + self._tab.Pos
+ from MyGame.Example.Test import Test
+ obj = Test()
+ obj.Init(self._tab.Bytes, x)
+ return obj
+ return None
+
+ # Monster
+ def LongEnumNonEnumDefault(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(108))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Uint64Flags, o + self._tab.Pos)
+ return 0
+
+ # Monster
+ def LongEnumNormalDefault(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(110))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Uint64Flags, o + self._tab.Pos)
+ return 2
+
+def MonsterStart(builder): builder.StartObject(54)
+def Start(builder):
+ return MonsterStart(builder)
+def MonsterAddPos(builder, pos): builder.PrependStructSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(pos), 0)
+def AddPos(builder, pos):
+ return MonsterAddPos(builder, pos)
+def MonsterAddMana(builder, mana): builder.PrependInt16Slot(1, mana, 150)
+def AddMana(builder, mana):
+ return MonsterAddMana(builder, mana)
+def MonsterAddHp(builder, hp): builder.PrependInt16Slot(2, hp, 100)
+def AddHp(builder, hp):
+ return MonsterAddHp(builder, hp)
+def MonsterAddName(builder, name): builder.PrependUOffsetTRelativeSlot(3, flatbuffers.number_types.UOffsetTFlags.py_type(name), 0)
+def AddName(builder, name):
+ return MonsterAddName(builder, name)
+def MonsterAddInventory(builder, inventory): builder.PrependUOffsetTRelativeSlot(5, flatbuffers.number_types.UOffsetTFlags.py_type(inventory), 0)
+def AddInventory(builder, inventory):
+ return MonsterAddInventory(builder, inventory)
+def MonsterStartInventoryVector(builder, numElems): return builder.StartVector(1, numElems, 1)
+def StartInventoryVector(builder, numElems):
+ return MonsterStartInventoryVector(builder, numElems)
+def MonsterAddColor(builder, color): builder.PrependUint8Slot(6, color, 8)
+def AddColor(builder, color):
+ return MonsterAddColor(builder, color)
+def MonsterAddTestType(builder, testType): builder.PrependUint8Slot(7, testType, 0)
+def AddTestType(builder, testType):
+ return MonsterAddTestType(builder, testType)
+def MonsterAddTest(builder, test): builder.PrependUOffsetTRelativeSlot(8, flatbuffers.number_types.UOffsetTFlags.py_type(test), 0)
+def AddTest(builder, test):
+ return MonsterAddTest(builder, test)
+def MonsterAddTest4(builder, test4): builder.PrependUOffsetTRelativeSlot(9, flatbuffers.number_types.UOffsetTFlags.py_type(test4), 0)
+def AddTest4(builder, test4):
+ return MonsterAddTest4(builder, test4)
+def MonsterStartTest4Vector(builder, numElems): return builder.StartVector(4, numElems, 2)
+def StartTest4Vector(builder, numElems):
+ return MonsterStartTest4Vector(builder, numElems)
+def MonsterAddTestarrayofstring(builder, testarrayofstring): builder.PrependUOffsetTRelativeSlot(10, flatbuffers.number_types.UOffsetTFlags.py_type(testarrayofstring), 0)
+def AddTestarrayofstring(builder, testarrayofstring):
+ return MonsterAddTestarrayofstring(builder, testarrayofstring)
+def MonsterStartTestarrayofstringVector(builder, numElems): return builder.StartVector(4, numElems, 4)
+def StartTestarrayofstringVector(builder, numElems):
+ return MonsterStartTestarrayofstringVector(builder, numElems)
+def MonsterAddTestarrayoftables(builder, testarrayoftables): builder.PrependUOffsetTRelativeSlot(11, flatbuffers.number_types.UOffsetTFlags.py_type(testarrayoftables), 0)
+def AddTestarrayoftables(builder, testarrayoftables):
+ return MonsterAddTestarrayoftables(builder, testarrayoftables)
+def MonsterStartTestarrayoftablesVector(builder, numElems): return builder.StartVector(4, numElems, 4)
+def StartTestarrayoftablesVector(builder, numElems):
+ return MonsterStartTestarrayoftablesVector(builder, numElems)
+def MonsterAddEnemy(builder, enemy): builder.PrependUOffsetTRelativeSlot(12, flatbuffers.number_types.UOffsetTFlags.py_type(enemy), 0)
+def AddEnemy(builder, enemy):
+ return MonsterAddEnemy(builder, enemy)
+def MonsterAddTestnestedflatbuffer(builder, testnestedflatbuffer): builder.PrependUOffsetTRelativeSlot(13, flatbuffers.number_types.UOffsetTFlags.py_type(testnestedflatbuffer), 0)
+def AddTestnestedflatbuffer(builder, testnestedflatbuffer):
+ return MonsterAddTestnestedflatbuffer(builder, testnestedflatbuffer)
+def MonsterStartTestnestedflatbufferVector(builder, numElems): return builder.StartVector(1, numElems, 1)
+def StartTestnestedflatbufferVector(builder, numElems):
+ return MonsterStartTestnestedflatbufferVector(builder, numElems)
+def MonsterMakeTestnestedflatbufferVectorFromBytes(builder, bytes):
+ builder.StartVector(1, len(bytes), 1)
+ builder.head = builder.head - len(bytes)
+ builder.Bytes[builder.head : builder.head + len(bytes)] = bytes
+ return builder.EndVector()
+def MakeTestnestedflatbufferVectorFromBytes(builder, bytes):
+ return MonsterMakeTestnestedflatbufferVectorFromBytes(builder, bytes)
+def MonsterAddTestempty(builder, testempty): builder.PrependUOffsetTRelativeSlot(14, flatbuffers.number_types.UOffsetTFlags.py_type(testempty), 0)
+def AddTestempty(builder, testempty):
+ return MonsterAddTestempty(builder, testempty)
+def MonsterAddTestbool(builder, testbool): builder.PrependBoolSlot(15, testbool, 0)
+def AddTestbool(builder, testbool):
+ return MonsterAddTestbool(builder, testbool)
+def MonsterAddTesthashs32Fnv1(builder, testhashs32Fnv1): builder.PrependInt32Slot(16, testhashs32Fnv1, 0)
+def AddTesthashs32Fnv1(builder, testhashs32Fnv1):
+ return MonsterAddTesthashs32Fnv1(builder, testhashs32Fnv1)
+def MonsterAddTesthashu32Fnv1(builder, testhashu32Fnv1): builder.PrependUint32Slot(17, testhashu32Fnv1, 0)
+def AddTesthashu32Fnv1(builder, testhashu32Fnv1):
+ return MonsterAddTesthashu32Fnv1(builder, testhashu32Fnv1)
+def MonsterAddTesthashs64Fnv1(builder, testhashs64Fnv1): builder.PrependInt64Slot(18, testhashs64Fnv1, 0)
+def AddTesthashs64Fnv1(builder, testhashs64Fnv1):
+ return MonsterAddTesthashs64Fnv1(builder, testhashs64Fnv1)
+def MonsterAddTesthashu64Fnv1(builder, testhashu64Fnv1): builder.PrependUint64Slot(19, testhashu64Fnv1, 0)
+def AddTesthashu64Fnv1(builder, testhashu64Fnv1):
+ return MonsterAddTesthashu64Fnv1(builder, testhashu64Fnv1)
+def MonsterAddTesthashs32Fnv1a(builder, testhashs32Fnv1a): builder.PrependInt32Slot(20, testhashs32Fnv1a, 0)
+def AddTesthashs32Fnv1a(builder, testhashs32Fnv1a):
+ return MonsterAddTesthashs32Fnv1a(builder, testhashs32Fnv1a)
+def MonsterAddTesthashu32Fnv1a(builder, testhashu32Fnv1a): builder.PrependUint32Slot(21, testhashu32Fnv1a, 0)
+def AddTesthashu32Fnv1a(builder, testhashu32Fnv1a):
+ return MonsterAddTesthashu32Fnv1a(builder, testhashu32Fnv1a)
+def MonsterAddTesthashs64Fnv1a(builder, testhashs64Fnv1a): builder.PrependInt64Slot(22, testhashs64Fnv1a, 0)
+def AddTesthashs64Fnv1a(builder, testhashs64Fnv1a):
+ return MonsterAddTesthashs64Fnv1a(builder, testhashs64Fnv1a)
+def MonsterAddTesthashu64Fnv1a(builder, testhashu64Fnv1a): builder.PrependUint64Slot(23, testhashu64Fnv1a, 0)
+def AddTesthashu64Fnv1a(builder, testhashu64Fnv1a):
+ return MonsterAddTesthashu64Fnv1a(builder, testhashu64Fnv1a)
+def MonsterAddTestarrayofbools(builder, testarrayofbools): builder.PrependUOffsetTRelativeSlot(24, flatbuffers.number_types.UOffsetTFlags.py_type(testarrayofbools), 0)
+def AddTestarrayofbools(builder, testarrayofbools):
+ return MonsterAddTestarrayofbools(builder, testarrayofbools)
+def MonsterStartTestarrayofboolsVector(builder, numElems): return builder.StartVector(1, numElems, 1)
+def StartTestarrayofboolsVector(builder, numElems):
+ return MonsterStartTestarrayofboolsVector(builder, numElems)
+def MonsterAddTestf(builder, testf): builder.PrependFloat32Slot(25, testf, 3.14159)
+def AddTestf(builder, testf):
+ return MonsterAddTestf(builder, testf)
+def MonsterAddTestf2(builder, testf2): builder.PrependFloat32Slot(26, testf2, 3.0)
+def AddTestf2(builder, testf2):
+ return MonsterAddTestf2(builder, testf2)
+def MonsterAddTestf3(builder, testf3): builder.PrependFloat32Slot(27, testf3, 0.0)
+def AddTestf3(builder, testf3):
+ return MonsterAddTestf3(builder, testf3)
+def MonsterAddTestarrayofstring2(builder, testarrayofstring2): builder.PrependUOffsetTRelativeSlot(28, flatbuffers.number_types.UOffsetTFlags.py_type(testarrayofstring2), 0)
+def AddTestarrayofstring2(builder, testarrayofstring2):
+ return MonsterAddTestarrayofstring2(builder, testarrayofstring2)
+def MonsterStartTestarrayofstring2Vector(builder, numElems): return builder.StartVector(4, numElems, 4)
+def StartTestarrayofstring2Vector(builder, numElems):
+ return MonsterStartTestarrayofstring2Vector(builder, numElems)
+def MonsterAddTestarrayofsortedstruct(builder, testarrayofsortedstruct): builder.PrependUOffsetTRelativeSlot(29, flatbuffers.number_types.UOffsetTFlags.py_type(testarrayofsortedstruct), 0)
+def AddTestarrayofsortedstruct(builder, testarrayofsortedstruct):
+ return MonsterAddTestarrayofsortedstruct(builder, testarrayofsortedstruct)
+def MonsterStartTestarrayofsortedstructVector(builder, numElems): return builder.StartVector(8, numElems, 4)
+def StartTestarrayofsortedstructVector(builder, numElems):
+ return MonsterStartTestarrayofsortedstructVector(builder, numElems)
+def MonsterAddFlex(builder, flex): builder.PrependUOffsetTRelativeSlot(30, flatbuffers.number_types.UOffsetTFlags.py_type(flex), 0)
+def AddFlex(builder, flex):
+ return MonsterAddFlex(builder, flex)
+def MonsterStartFlexVector(builder, numElems): return builder.StartVector(1, numElems, 1)
+def StartFlexVector(builder, numElems):
+ return MonsterStartFlexVector(builder, numElems)
+def MonsterAddTest5(builder, test5): builder.PrependUOffsetTRelativeSlot(31, flatbuffers.number_types.UOffsetTFlags.py_type(test5), 0)
+def AddTest5(builder, test5):
+ return MonsterAddTest5(builder, test5)
+def MonsterStartTest5Vector(builder, numElems): return builder.StartVector(4, numElems, 2)
+def StartTest5Vector(builder, numElems):
+ return MonsterStartTest5Vector(builder, numElems)
+def MonsterAddVectorOfLongs(builder, vectorOfLongs): builder.PrependUOffsetTRelativeSlot(32, flatbuffers.number_types.UOffsetTFlags.py_type(vectorOfLongs), 0)
+def AddVectorOfLongs(builder, vectorOfLongs):
+ return MonsterAddVectorOfLongs(builder, vectorOfLongs)
+def MonsterStartVectorOfLongsVector(builder, numElems): return builder.StartVector(8, numElems, 8)
+def StartVectorOfLongsVector(builder, numElems):
+ return MonsterStartVectorOfLongsVector(builder, numElems)
+def MonsterAddVectorOfDoubles(builder, vectorOfDoubles): builder.PrependUOffsetTRelativeSlot(33, flatbuffers.number_types.UOffsetTFlags.py_type(vectorOfDoubles), 0)
+def AddVectorOfDoubles(builder, vectorOfDoubles):
+ return MonsterAddVectorOfDoubles(builder, vectorOfDoubles)
+def MonsterStartVectorOfDoublesVector(builder, numElems): return builder.StartVector(8, numElems, 8)
+def StartVectorOfDoublesVector(builder, numElems):
+ return MonsterStartVectorOfDoublesVector(builder, numElems)
+def MonsterAddParentNamespaceTest(builder, parentNamespaceTest): builder.PrependUOffsetTRelativeSlot(34, flatbuffers.number_types.UOffsetTFlags.py_type(parentNamespaceTest), 0)
+def AddParentNamespaceTest(builder, parentNamespaceTest):
+ return MonsterAddParentNamespaceTest(builder, parentNamespaceTest)
+def MonsterAddVectorOfReferrables(builder, vectorOfReferrables): builder.PrependUOffsetTRelativeSlot(35, flatbuffers.number_types.UOffsetTFlags.py_type(vectorOfReferrables), 0)
+def AddVectorOfReferrables(builder, vectorOfReferrables):
+ return MonsterAddVectorOfReferrables(builder, vectorOfReferrables)
+def MonsterStartVectorOfReferrablesVector(builder, numElems): return builder.StartVector(4, numElems, 4)
+def StartVectorOfReferrablesVector(builder, numElems):
+ return MonsterStartVectorOfReferrablesVector(builder, numElems)
+def MonsterAddSingleWeakReference(builder, singleWeakReference): builder.PrependUint64Slot(36, singleWeakReference, 0)
+def AddSingleWeakReference(builder, singleWeakReference):
+ return MonsterAddSingleWeakReference(builder, singleWeakReference)
+def MonsterAddVectorOfWeakReferences(builder, vectorOfWeakReferences): builder.PrependUOffsetTRelativeSlot(37, flatbuffers.number_types.UOffsetTFlags.py_type(vectorOfWeakReferences), 0)
+def AddVectorOfWeakReferences(builder, vectorOfWeakReferences):
+ return MonsterAddVectorOfWeakReferences(builder, vectorOfWeakReferences)
+def MonsterStartVectorOfWeakReferencesVector(builder, numElems): return builder.StartVector(8, numElems, 8)
+def StartVectorOfWeakReferencesVector(builder, numElems):
+ return MonsterStartVectorOfWeakReferencesVector(builder, numElems)
+def MonsterAddVectorOfStrongReferrables(builder, vectorOfStrongReferrables): builder.PrependUOffsetTRelativeSlot(38, flatbuffers.number_types.UOffsetTFlags.py_type(vectorOfStrongReferrables), 0)
+def AddVectorOfStrongReferrables(builder, vectorOfStrongReferrables):
+ return MonsterAddVectorOfStrongReferrables(builder, vectorOfStrongReferrables)
+def MonsterStartVectorOfStrongReferrablesVector(builder, numElems): return builder.StartVector(4, numElems, 4)
+def StartVectorOfStrongReferrablesVector(builder, numElems):
+ return MonsterStartVectorOfStrongReferrablesVector(builder, numElems)
+def MonsterAddCoOwningReference(builder, coOwningReference): builder.PrependUint64Slot(39, coOwningReference, 0)
+def AddCoOwningReference(builder, coOwningReference):
+ return MonsterAddCoOwningReference(builder, coOwningReference)
+def MonsterAddVectorOfCoOwningReferences(builder, vectorOfCoOwningReferences): builder.PrependUOffsetTRelativeSlot(40, flatbuffers.number_types.UOffsetTFlags.py_type(vectorOfCoOwningReferences), 0)
+def AddVectorOfCoOwningReferences(builder, vectorOfCoOwningReferences):
+ return MonsterAddVectorOfCoOwningReferences(builder, vectorOfCoOwningReferences)
+def MonsterStartVectorOfCoOwningReferencesVector(builder, numElems): return builder.StartVector(8, numElems, 8)
+def StartVectorOfCoOwningReferencesVector(builder, numElems):
+ return MonsterStartVectorOfCoOwningReferencesVector(builder, numElems)
+def MonsterAddNonOwningReference(builder, nonOwningReference): builder.PrependUint64Slot(41, nonOwningReference, 0)
+def AddNonOwningReference(builder, nonOwningReference):
+ return MonsterAddNonOwningReference(builder, nonOwningReference)
+def MonsterAddVectorOfNonOwningReferences(builder, vectorOfNonOwningReferences): builder.PrependUOffsetTRelativeSlot(42, flatbuffers.number_types.UOffsetTFlags.py_type(vectorOfNonOwningReferences), 0)
+def AddVectorOfNonOwningReferences(builder, vectorOfNonOwningReferences):
+ return MonsterAddVectorOfNonOwningReferences(builder, vectorOfNonOwningReferences)
+def MonsterStartVectorOfNonOwningReferencesVector(builder, numElems): return builder.StartVector(8, numElems, 8)
+def StartVectorOfNonOwningReferencesVector(builder, numElems):
+ return MonsterStartVectorOfNonOwningReferencesVector(builder, numElems)
+def MonsterAddAnyUniqueType(builder, anyUniqueType): builder.PrependUint8Slot(43, anyUniqueType, 0)
+def AddAnyUniqueType(builder, anyUniqueType):
+ return MonsterAddAnyUniqueType(builder, anyUniqueType)
+def MonsterAddAnyUnique(builder, anyUnique): builder.PrependUOffsetTRelativeSlot(44, flatbuffers.number_types.UOffsetTFlags.py_type(anyUnique), 0)
+def AddAnyUnique(builder, anyUnique):
+ return MonsterAddAnyUnique(builder, anyUnique)
+def MonsterAddAnyAmbiguousType(builder, anyAmbiguousType): builder.PrependUint8Slot(45, anyAmbiguousType, 0)
+def AddAnyAmbiguousType(builder, anyAmbiguousType):
+ return MonsterAddAnyAmbiguousType(builder, anyAmbiguousType)
+def MonsterAddAnyAmbiguous(builder, anyAmbiguous): builder.PrependUOffsetTRelativeSlot(46, flatbuffers.number_types.UOffsetTFlags.py_type(anyAmbiguous), 0)
+def AddAnyAmbiguous(builder, anyAmbiguous):
+ return MonsterAddAnyAmbiguous(builder, anyAmbiguous)
+def MonsterAddVectorOfEnums(builder, vectorOfEnums): builder.PrependUOffsetTRelativeSlot(47, flatbuffers.number_types.UOffsetTFlags.py_type(vectorOfEnums), 0)
+def AddVectorOfEnums(builder, vectorOfEnums):
+ return MonsterAddVectorOfEnums(builder, vectorOfEnums)
+def MonsterStartVectorOfEnumsVector(builder, numElems): return builder.StartVector(1, numElems, 1)
+def StartVectorOfEnumsVector(builder, numElems):
+ return MonsterStartVectorOfEnumsVector(builder, numElems)
+def MonsterAddSignedEnum(builder, signedEnum): builder.PrependInt8Slot(48, signedEnum, -1)
+def AddSignedEnum(builder, signedEnum):
+ return MonsterAddSignedEnum(builder, signedEnum)
+def MonsterAddTestrequirednestedflatbuffer(builder, testrequirednestedflatbuffer): builder.PrependUOffsetTRelativeSlot(49, flatbuffers.number_types.UOffsetTFlags.py_type(testrequirednestedflatbuffer), 0)
+def AddTestrequirednestedflatbuffer(builder, testrequirednestedflatbuffer):
+ return MonsterAddTestrequirednestedflatbuffer(builder, testrequirednestedflatbuffer)
+def MonsterStartTestrequirednestedflatbufferVector(builder, numElems): return builder.StartVector(1, numElems, 1)
+def StartTestrequirednestedflatbufferVector(builder, numElems):
+ return MonsterStartTestrequirednestedflatbufferVector(builder, numElems)
+def MonsterMakeTestrequirednestedflatbufferVectorFromBytes(builder, bytes):
+ builder.StartVector(1, len(bytes), 1)
+ builder.head = builder.head - len(bytes)
+ builder.Bytes[builder.head : builder.head + len(bytes)] = bytes
+ return builder.EndVector()
+def MakeTestrequirednestedflatbufferVectorFromBytes(builder, bytes):
+ return MonsterMakeTestrequirednestedflatbufferVectorFromBytes(builder, bytes)
+def MonsterAddScalarKeySortedTables(builder, scalarKeySortedTables): builder.PrependUOffsetTRelativeSlot(50, flatbuffers.number_types.UOffsetTFlags.py_type(scalarKeySortedTables), 0)
+def AddScalarKeySortedTables(builder, scalarKeySortedTables):
+ return MonsterAddScalarKeySortedTables(builder, scalarKeySortedTables)
+def MonsterStartScalarKeySortedTablesVector(builder, numElems): return builder.StartVector(4, numElems, 4)
+def StartScalarKeySortedTablesVector(builder, numElems):
+ return MonsterStartScalarKeySortedTablesVector(builder, numElems)
+def MonsterAddNativeInline(builder, nativeInline): builder.PrependStructSlot(51, flatbuffers.number_types.UOffsetTFlags.py_type(nativeInline), 0)
+def AddNativeInline(builder, nativeInline):
+ return MonsterAddNativeInline(builder, nativeInline)
+def MonsterAddLongEnumNonEnumDefault(builder, longEnumNonEnumDefault): builder.PrependUint64Slot(52, longEnumNonEnumDefault, 0)
+def AddLongEnumNonEnumDefault(builder, longEnumNonEnumDefault):
+ return MonsterAddLongEnumNonEnumDefault(builder, longEnumNonEnumDefault)
+def MonsterAddLongEnumNormalDefault(builder, longEnumNormalDefault): builder.PrependUint64Slot(53, longEnumNormalDefault, 2)
+def AddLongEnumNormalDefault(builder, longEnumNormalDefault):
+ return MonsterAddLongEnumNormalDefault(builder, longEnumNormalDefault)
+def MonsterEnd(builder): return builder.EndObject()
+def End(builder):
+ return MonsterEnd(builder)
import MyGame.Example.Ability
import MyGame.Example.Any
import MyGame.Example.AnyAmbiguousAliases
@@ -886,6 +1124,10 @@
self.vectorOfEnums = None # type: List[int]
self.signedEnum = -1 # type: int
self.testrequirednestedflatbuffer = None # type: List[int]
+ self.scalarKeySortedTables = None # type: List[MyGame.Example.Stat.StatT]
+ self.nativeInline = None # type: Optional[MyGame.Example.Test.TestT]
+ self.longEnumNonEnumDefault = 0 # type: int
+ self.longEnumNormalDefault = 2 # type: int
@classmethod
def InitFromBuf(cls, buf, pos):
@@ -1070,6 +1312,18 @@
self.testrequirednestedflatbuffer.append(monster.Testrequirednestedflatbuffer(i))
else:
self.testrequirednestedflatbuffer = monster.TestrequirednestedflatbufferAsNumpy()
+ if not monster.ScalarKeySortedTablesIsNone():
+ self.scalarKeySortedTables = []
+ for i in range(monster.ScalarKeySortedTablesLength()):
+ if monster.ScalarKeySortedTables(i) is None:
+ self.scalarKeySortedTables.append(None)
+ else:
+ stat_ = MyGame.Example.Stat.StatT.InitFromObj(monster.ScalarKeySortedTables(i))
+ self.scalarKeySortedTables.append(stat_)
+ if monster.NativeInline() is not None:
+ self.nativeInline = MyGame.Example.Test.TestT.InitFromObj(monster.NativeInline())
+ self.longEnumNonEnumDefault = monster.LongEnumNonEnumDefault()
+ self.longEnumNormalDefault = monster.LongEnumNormalDefault()
# MonsterT
def Pack(self, builder):
@@ -1082,14 +1336,14 @@
MonsterStartInventoryVector(builder, len(self.inventory))
for i in reversed(range(len(self.inventory))):
builder.PrependUint8(self.inventory[i])
- inventory = builder.EndVector(len(self.inventory))
+ inventory = builder.EndVector()
if self.test is not None:
test = self.test.Pack(builder)
if self.test4 is not None:
MonsterStartTest4Vector(builder, len(self.test4))
for i in reversed(range(len(self.test4))):
self.test4[i].Pack(builder)
- test4 = builder.EndVector(len(self.test4))
+ test4 = builder.EndVector()
if self.testarrayofstring is not None:
testarrayofstringlist = []
for i in range(len(self.testarrayofstring)):
@@ -1097,7 +1351,7 @@
MonsterStartTestarrayofstringVector(builder, len(self.testarrayofstring))
for i in reversed(range(len(self.testarrayofstring))):
builder.PrependUOffsetTRelative(testarrayofstringlist[i])
- testarrayofstring = builder.EndVector(len(self.testarrayofstring))
+ testarrayofstring = builder.EndVector()
if self.testarrayoftables is not None:
testarrayoftableslist = []
for i in range(len(self.testarrayoftables)):
@@ -1105,7 +1359,7 @@
MonsterStartTestarrayoftablesVector(builder, len(self.testarrayoftables))
for i in reversed(range(len(self.testarrayoftables))):
builder.PrependUOffsetTRelative(testarrayoftableslist[i])
- testarrayoftables = builder.EndVector(len(self.testarrayoftables))
+ testarrayoftables = builder.EndVector()
if self.enemy is not None:
enemy = self.enemy.Pack(builder)
if self.testnestedflatbuffer is not None:
@@ -1115,7 +1369,7 @@
MonsterStartTestnestedflatbufferVector(builder, len(self.testnestedflatbuffer))
for i in reversed(range(len(self.testnestedflatbuffer))):
builder.PrependUint8(self.testnestedflatbuffer[i])
- testnestedflatbuffer = builder.EndVector(len(self.testnestedflatbuffer))
+ testnestedflatbuffer = builder.EndVector()
if self.testempty is not None:
testempty = self.testempty.Pack(builder)
if self.testarrayofbools is not None:
@@ -1125,7 +1379,7 @@
MonsterStartTestarrayofboolsVector(builder, len(self.testarrayofbools))
for i in reversed(range(len(self.testarrayofbools))):
builder.PrependBool(self.testarrayofbools[i])
- testarrayofbools = builder.EndVector(len(self.testarrayofbools))
+ testarrayofbools = builder.EndVector()
if self.testarrayofstring2 is not None:
testarrayofstring2list = []
for i in range(len(self.testarrayofstring2)):
@@ -1133,12 +1387,12 @@
MonsterStartTestarrayofstring2Vector(builder, len(self.testarrayofstring2))
for i in reversed(range(len(self.testarrayofstring2))):
builder.PrependUOffsetTRelative(testarrayofstring2list[i])
- testarrayofstring2 = builder.EndVector(len(self.testarrayofstring2))
+ testarrayofstring2 = builder.EndVector()
if self.testarrayofsortedstruct is not None:
MonsterStartTestarrayofsortedstructVector(builder, len(self.testarrayofsortedstruct))
for i in reversed(range(len(self.testarrayofsortedstruct))):
self.testarrayofsortedstruct[i].Pack(builder)
- testarrayofsortedstruct = builder.EndVector(len(self.testarrayofsortedstruct))
+ testarrayofsortedstruct = builder.EndVector()
if self.flex is not None:
if np is not None and type(self.flex) is np.ndarray:
flex = builder.CreateNumpyVector(self.flex)
@@ -1146,12 +1400,12 @@
MonsterStartFlexVector(builder, len(self.flex))
for i in reversed(range(len(self.flex))):
builder.PrependUint8(self.flex[i])
- flex = builder.EndVector(len(self.flex))
+ flex = builder.EndVector()
if self.test5 is not None:
MonsterStartTest5Vector(builder, len(self.test5))
for i in reversed(range(len(self.test5))):
self.test5[i].Pack(builder)
- test5 = builder.EndVector(len(self.test5))
+ test5 = builder.EndVector()
if self.vectorOfLongs is not None:
if np is not None and type(self.vectorOfLongs) is np.ndarray:
vectorOfLongs = builder.CreateNumpyVector(self.vectorOfLongs)
@@ -1159,7 +1413,7 @@
MonsterStartVectorOfLongsVector(builder, len(self.vectorOfLongs))
for i in reversed(range(len(self.vectorOfLongs))):
builder.PrependInt64(self.vectorOfLongs[i])
- vectorOfLongs = builder.EndVector(len(self.vectorOfLongs))
+ vectorOfLongs = builder.EndVector()
if self.vectorOfDoubles is not None:
if np is not None and type(self.vectorOfDoubles) is np.ndarray:
vectorOfDoubles = builder.CreateNumpyVector(self.vectorOfDoubles)
@@ -1167,7 +1421,7 @@
MonsterStartVectorOfDoublesVector(builder, len(self.vectorOfDoubles))
for i in reversed(range(len(self.vectorOfDoubles))):
builder.PrependFloat64(self.vectorOfDoubles[i])
- vectorOfDoubles = builder.EndVector(len(self.vectorOfDoubles))
+ vectorOfDoubles = builder.EndVector()
if self.parentNamespaceTest is not None:
parentNamespaceTest = self.parentNamespaceTest.Pack(builder)
if self.vectorOfReferrables is not None:
@@ -1177,7 +1431,7 @@
MonsterStartVectorOfReferrablesVector(builder, len(self.vectorOfReferrables))
for i in reversed(range(len(self.vectorOfReferrables))):
builder.PrependUOffsetTRelative(vectorOfReferrableslist[i])
- vectorOfReferrables = builder.EndVector(len(self.vectorOfReferrables))
+ vectorOfReferrables = builder.EndVector()
if self.vectorOfWeakReferences is not None:
if np is not None and type(self.vectorOfWeakReferences) is np.ndarray:
vectorOfWeakReferences = builder.CreateNumpyVector(self.vectorOfWeakReferences)
@@ -1185,7 +1439,7 @@
MonsterStartVectorOfWeakReferencesVector(builder, len(self.vectorOfWeakReferences))
for i in reversed(range(len(self.vectorOfWeakReferences))):
builder.PrependUint64(self.vectorOfWeakReferences[i])
- vectorOfWeakReferences = builder.EndVector(len(self.vectorOfWeakReferences))
+ vectorOfWeakReferences = builder.EndVector()
if self.vectorOfStrongReferrables is not None:
vectorOfStrongReferrableslist = []
for i in range(len(self.vectorOfStrongReferrables)):
@@ -1193,7 +1447,7 @@
MonsterStartVectorOfStrongReferrablesVector(builder, len(self.vectorOfStrongReferrables))
for i in reversed(range(len(self.vectorOfStrongReferrables))):
builder.PrependUOffsetTRelative(vectorOfStrongReferrableslist[i])
- vectorOfStrongReferrables = builder.EndVector(len(self.vectorOfStrongReferrables))
+ vectorOfStrongReferrables = builder.EndVector()
if self.vectorOfCoOwningReferences is not None:
if np is not None and type(self.vectorOfCoOwningReferences) is np.ndarray:
vectorOfCoOwningReferences = builder.CreateNumpyVector(self.vectorOfCoOwningReferences)
@@ -1201,7 +1455,7 @@
MonsterStartVectorOfCoOwningReferencesVector(builder, len(self.vectorOfCoOwningReferences))
for i in reversed(range(len(self.vectorOfCoOwningReferences))):
builder.PrependUint64(self.vectorOfCoOwningReferences[i])
- vectorOfCoOwningReferences = builder.EndVector(len(self.vectorOfCoOwningReferences))
+ vectorOfCoOwningReferences = builder.EndVector()
if self.vectorOfNonOwningReferences is not None:
if np is not None and type(self.vectorOfNonOwningReferences) is np.ndarray:
vectorOfNonOwningReferences = builder.CreateNumpyVector(self.vectorOfNonOwningReferences)
@@ -1209,7 +1463,7 @@
MonsterStartVectorOfNonOwningReferencesVector(builder, len(self.vectorOfNonOwningReferences))
for i in reversed(range(len(self.vectorOfNonOwningReferences))):
builder.PrependUint64(self.vectorOfNonOwningReferences[i])
- vectorOfNonOwningReferences = builder.EndVector(len(self.vectorOfNonOwningReferences))
+ vectorOfNonOwningReferences = builder.EndVector()
if self.anyUnique is not None:
anyUnique = self.anyUnique.Pack(builder)
if self.anyAmbiguous is not None:
@@ -1221,7 +1475,7 @@
MonsterStartVectorOfEnumsVector(builder, len(self.vectorOfEnums))
for i in reversed(range(len(self.vectorOfEnums))):
builder.PrependUint8(self.vectorOfEnums[i])
- vectorOfEnums = builder.EndVector(len(self.vectorOfEnums))
+ vectorOfEnums = builder.EndVector()
if self.testrequirednestedflatbuffer is not None:
if np is not None and type(self.testrequirednestedflatbuffer) is np.ndarray:
testrequirednestedflatbuffer = builder.CreateNumpyVector(self.testrequirednestedflatbuffer)
@@ -1229,7 +1483,15 @@
MonsterStartTestrequirednestedflatbufferVector(builder, len(self.testrequirednestedflatbuffer))
for i in reversed(range(len(self.testrequirednestedflatbuffer))):
builder.PrependUint8(self.testrequirednestedflatbuffer[i])
- testrequirednestedflatbuffer = builder.EndVector(len(self.testrequirednestedflatbuffer))
+ testrequirednestedflatbuffer = builder.EndVector()
+ if self.scalarKeySortedTables is not None:
+ scalarKeySortedTableslist = []
+ for i in range(len(self.scalarKeySortedTables)):
+ scalarKeySortedTableslist.append(self.scalarKeySortedTables[i].Pack(builder))
+ MonsterStartScalarKeySortedTablesVector(builder, len(self.scalarKeySortedTables))
+ for i in reversed(range(len(self.scalarKeySortedTables))):
+ builder.PrependUOffsetTRelative(scalarKeySortedTableslist[i])
+ scalarKeySortedTables = builder.EndVector()
MonsterStart(builder)
if self.pos is not None:
pos = self.pos.Pack(builder)
@@ -1308,5 +1570,12 @@
MonsterAddSignedEnum(builder, self.signedEnum)
if self.testrequirednestedflatbuffer is not None:
MonsterAddTestrequirednestedflatbuffer(builder, testrequirednestedflatbuffer)
+ if self.scalarKeySortedTables is not None:
+ MonsterAddScalarKeySortedTables(builder, scalarKeySortedTables)
+ if self.nativeInline is not None:
+ nativeInline = self.nativeInline.Pack(builder)
+ MonsterAddNativeInline(builder, nativeInline)
+ MonsterAddLongEnumNonEnumDefault(builder, self.longEnumNonEnumDefault)
+ MonsterAddLongEnumNormalDefault(builder, self.longEnumNormalDefault)
monster = MonsterEnd(builder)
return monster
diff --git a/tests/MyGame/Example/MonsterStorageGrpc.java b/tests/MyGame/Example/MonsterStorageGrpc.java
index 8e468d4..40103ae 100644
--- a/tests/MyGame/Example/MonsterStorageGrpc.java
+++ b/tests/MyGame/Example/MonsterStorageGrpc.java
@@ -1,4 +1,4 @@
-//Generated by flatc compiler (version 1.12.0)
+//Generated by flatc compiler (version 2.0.0)
//If you make any local changes, they will be lost
//source: monster_test.fbs
diff --git a/tests/MyGame/Example/MonsterStorage_grpc.go b/tests/MyGame/Example/MonsterStorage_grpc.go
index deeec29..4d9f104 100644
--- a/tests/MyGame/Example/MonsterStorage_grpc.go
+++ b/tests/MyGame/Example/MonsterStorage_grpc.go
@@ -4,248 +4,299 @@
package Example
-import "github.com/google/flatbuffers/go"
-
import (
- context "context"
- grpc "google.golang.org/grpc"
+ context "context"
+ flatbuffers "github.com/google/flatbuffers/go"
+ grpc "google.golang.org/grpc"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/status"
)
// Client API for MonsterStorage service
-type MonsterStorageClient interface{
- Store(ctx context.Context, in *flatbuffers.Builder,
- opts... grpc.CallOption) (* Stat, error)
- Retrieve(ctx context.Context, in *flatbuffers.Builder,
- opts... grpc.CallOption) (MonsterStorage_RetrieveClient, error)
- GetMaxHitPoint(ctx context.Context,
- opts... grpc.CallOption) (MonsterStorage_GetMaxHitPointClient, error)
- GetMinMaxHitPoints(ctx context.Context,
- opts... grpc.CallOption) (MonsterStorage_GetMinMaxHitPointsClient, error)
+type MonsterStorageClient interface {
+ Store(ctx context.Context, in *flatbuffers.Builder,
+ opts ...grpc.CallOption) (*Stat, error)
+ Retrieve(ctx context.Context, in *flatbuffers.Builder,
+ opts ...grpc.CallOption) (MonsterStorage_RetrieveClient, error)
+ GetMaxHitPoint(ctx context.Context,
+ opts ...grpc.CallOption) (MonsterStorage_GetMaxHitPointClient, error)
+ GetMinMaxHitPoints(ctx context.Context,
+ opts ...grpc.CallOption) (MonsterStorage_GetMinMaxHitPointsClient, error)
}
type monsterStorageClient struct {
- cc *grpc.ClientConn
+ cc grpc.ClientConnInterface
}
-func NewMonsterStorageClient(cc *grpc.ClientConn) MonsterStorageClient {
- return &monsterStorageClient{cc}
+func NewMonsterStorageClient(cc grpc.ClientConnInterface) MonsterStorageClient {
+ return &monsterStorageClient{cc}
}
-func (c *monsterStorageClient) Store(ctx context.Context, in *flatbuffers.Builder,
- opts... grpc.CallOption) (* Stat, error) {
- out := new(Stat)
- err := grpc.Invoke(ctx, "/MyGame.Example.MonsterStorage/Store", in, out, c.cc, opts...)
- if err != nil { return nil, err }
- return out, nil
+func (c *monsterStorageClient) Store(ctx context.Context, in *flatbuffers.Builder,
+ opts ...grpc.CallOption) (*Stat, error) {
+ out := new(Stat)
+ err := c.cc.Invoke(ctx, "/MyGame.Example.MonsterStorage/Store", in, out, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
}
-func (c *monsterStorageClient) Retrieve(ctx context.Context, in *flatbuffers.Builder,
- opts... grpc.CallOption) (MonsterStorage_RetrieveClient, error) {
- stream, err := grpc.NewClientStream(ctx, &_MonsterStorage_serviceDesc.Streams[0], c.cc, "/MyGame.Example.MonsterStorage/Retrieve", opts...)
- if err != nil { return nil, err }
- x := &monsterStorageRetrieveClient{stream}
- if err := x.ClientStream.SendMsg(in); err != nil { return nil, err }
- if err := x.ClientStream.CloseSend(); err != nil { return nil, err }
- return x,nil
+func (c *monsterStorageClient) Retrieve(ctx context.Context, in *flatbuffers.Builder,
+ opts ...grpc.CallOption) (MonsterStorage_RetrieveClient, error) {
+ stream, err := c.cc.NewStream(ctx, &_MonsterStorage_serviceDesc.Streams[0], "/MyGame.Example.MonsterStorage/Retrieve", opts...)
+ if err != nil {
+ return nil, err
+ }
+ x := &monsterStorageRetrieveClient{stream}
+ if err := x.ClientStream.SendMsg(in); err != nil {
+ return nil, err
+ }
+ if err := x.ClientStream.CloseSend(); err != nil {
+ return nil, err
+ }
+ return x, nil
}
type MonsterStorage_RetrieveClient interface {
- Recv() (*Monster, error)
- grpc.ClientStream
+ Recv() (*Monster, error)
+ grpc.ClientStream
}
-type monsterStorageRetrieveClient struct{
- grpc.ClientStream
+type monsterStorageRetrieveClient struct {
+ grpc.ClientStream
}
func (x *monsterStorageRetrieveClient) Recv() (*Monster, error) {
- m := new(Monster)
- if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err }
- return m, nil
+ m := new(Monster)
+ if err := x.ClientStream.RecvMsg(m); err != nil {
+ return nil, err
+ }
+ return m, nil
}
-func (c *monsterStorageClient) GetMaxHitPoint(ctx context.Context,
- opts... grpc.CallOption) (MonsterStorage_GetMaxHitPointClient, error) {
- stream, err := grpc.NewClientStream(ctx, &_MonsterStorage_serviceDesc.Streams[1], c.cc, "/MyGame.Example.MonsterStorage/GetMaxHitPoint", opts...)
- if err != nil { return nil, err }
- x := &monsterStorageGetMaxHitPointClient{stream}
- return x,nil
+func (c *monsterStorageClient) GetMaxHitPoint(ctx context.Context,
+ opts ...grpc.CallOption) (MonsterStorage_GetMaxHitPointClient, error) {
+ stream, err := c.cc.NewStream(ctx, &_MonsterStorage_serviceDesc.Streams[1], "/MyGame.Example.MonsterStorage/GetMaxHitPoint", opts...)
+ if err != nil {
+ return nil, err
+ }
+ x := &monsterStorageGetMaxHitPointClient{stream}
+ return x, nil
}
type MonsterStorage_GetMaxHitPointClient interface {
- Send(*flatbuffers.Builder) error
- CloseAndRecv() (*Stat, error)
- grpc.ClientStream
+ Send(*flatbuffers.Builder) error
+ CloseAndRecv() (*Stat, error)
+ grpc.ClientStream
}
-type monsterStorageGetMaxHitPointClient struct{
- grpc.ClientStream
+type monsterStorageGetMaxHitPointClient struct {
+ grpc.ClientStream
}
func (x *monsterStorageGetMaxHitPointClient) Send(m *flatbuffers.Builder) error {
- return x.ClientStream.SendMsg(m)
+ return x.ClientStream.SendMsg(m)
}
func (x *monsterStorageGetMaxHitPointClient) CloseAndRecv() (*Stat, error) {
- if err := x.ClientStream.CloseSend(); err != nil { return nil, err }
- m := new (Stat)
- if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err }
- return m, nil
+ if err := x.ClientStream.CloseSend(); err != nil {
+ return nil, err
+ }
+ m := new(Stat)
+ if err := x.ClientStream.RecvMsg(m); err != nil {
+ return nil, err
+ }
+ return m, nil
}
-func (c *monsterStorageClient) GetMinMaxHitPoints(ctx context.Context,
- opts... grpc.CallOption) (MonsterStorage_GetMinMaxHitPointsClient, error) {
- stream, err := grpc.NewClientStream(ctx, &_MonsterStorage_serviceDesc.Streams[2], c.cc, "/MyGame.Example.MonsterStorage/GetMinMaxHitPoints", opts...)
- if err != nil { return nil, err }
- x := &monsterStorageGetMinMaxHitPointsClient{stream}
- return x,nil
+func (c *monsterStorageClient) GetMinMaxHitPoints(ctx context.Context,
+ opts ...grpc.CallOption) (MonsterStorage_GetMinMaxHitPointsClient, error) {
+ stream, err := c.cc.NewStream(ctx, &_MonsterStorage_serviceDesc.Streams[2], "/MyGame.Example.MonsterStorage/GetMinMaxHitPoints", opts...)
+ if err != nil {
+ return nil, err
+ }
+ x := &monsterStorageGetMinMaxHitPointsClient{stream}
+ return x, nil
}
type MonsterStorage_GetMinMaxHitPointsClient interface {
- Send(*flatbuffers.Builder) error
- Recv() (*Stat, error)
- grpc.ClientStream
+ Send(*flatbuffers.Builder) error
+ Recv() (*Stat, error)
+ grpc.ClientStream
}
-type monsterStorageGetMinMaxHitPointsClient struct{
- grpc.ClientStream
+type monsterStorageGetMinMaxHitPointsClient struct {
+ grpc.ClientStream
}
func (x *monsterStorageGetMinMaxHitPointsClient) Send(m *flatbuffers.Builder) error {
- return x.ClientStream.SendMsg(m)
+ return x.ClientStream.SendMsg(m)
}
func (x *monsterStorageGetMinMaxHitPointsClient) Recv() (*Stat, error) {
- m := new(Stat)
- if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err }
- return m, nil
+ m := new(Stat)
+ if err := x.ClientStream.RecvMsg(m); err != nil {
+ return nil, err
+ }
+ return m, nil
}
// Server API for MonsterStorage service
type MonsterStorageServer interface {
- Store(context.Context, *Monster) (*flatbuffers.Builder, error)
- Retrieve(*Stat, MonsterStorage_RetrieveServer) error
- GetMaxHitPoint(MonsterStorage_GetMaxHitPointServer) error
- GetMinMaxHitPoints(MonsterStorage_GetMinMaxHitPointsServer) error
+ Store(context.Context, *Monster) (*flatbuffers.Builder, error)
+ Retrieve(*Stat, MonsterStorage_RetrieveServer) error
+ GetMaxHitPoint(MonsterStorage_GetMaxHitPointServer) error
+ GetMinMaxHitPoints(MonsterStorage_GetMinMaxHitPointsServer) error
+ mustEmbedUnimplementedMonsterStorageServer()
}
-func RegisterMonsterStorageServer(s *grpc.Server, srv MonsterStorageServer) {
- s.RegisterService(&_MonsterStorage_serviceDesc, srv)
+type UnimplementedMonsterStorageServer struct {
+}
+
+func (UnimplementedMonsterStorageServer) Store(context.Context, *Monster) (*flatbuffers.Builder, error) {
+ return nil, status.Errorf(codes.Unimplemented, "method Store not implemented")
+}
+
+func (UnimplementedMonsterStorageServer) Retrieve(*Stat, MonsterStorage_RetrieveServer) error {
+ return status.Errorf(codes.Unimplemented, "method Retrieve not implemented")
+}
+
+func (UnimplementedMonsterStorageServer) GetMaxHitPoint(MonsterStorage_GetMaxHitPointServer) error {
+ return status.Errorf(codes.Unimplemented, "method GetMaxHitPoint not implemented")
+}
+
+func (UnimplementedMonsterStorageServer) GetMinMaxHitPoints(MonsterStorage_GetMinMaxHitPointsServer) error {
+ return status.Errorf(codes.Unimplemented, "method GetMinMaxHitPoints not implemented")
+}
+
+func (UnimplementedMonsterStorageServer) mustEmbedUnimplementedMonsterStorageServer() {}
+
+type UnsafeMonsterStorageServer interface {
+ mustEmbedUnimplementedMonsterStorageServer()
+}
+
+func RegisterMonsterStorageServer(s grpc.ServiceRegistrar, srv MonsterStorageServer) {
+ s.RegisterService(&_MonsterStorage_serviceDesc, srv)
}
func _MonsterStorage_Store_Handler(srv interface{}, ctx context.Context,
dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
- in := new(Monster)
- if err := dec(in); err != nil { return nil, err }
- if interceptor == nil { return srv.(MonsterStorageServer).Store(ctx, in) }
- info := &grpc.UnaryServerInfo{
- Server: srv,
- FullMethod: "/MyGame.Example.MonsterStorage/Store",
- }
-
- handler := func(ctx context.Context, req interface{}) (interface{}, error) {
- return srv.(MonsterStorageServer).Store(ctx, req.(* Monster))
- }
- return interceptor(ctx, in, info, handler)
+ in := new(Monster)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(MonsterStorageServer).Store(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/MyGame.Example.MonsterStorage/Store",
+ }
+
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(MonsterStorageServer).Store(ctx, req.(*Monster))
+ }
+ return interceptor(ctx, in, info, handler)
}
-
-
func _MonsterStorage_Retrieve_Handler(srv interface{}, stream grpc.ServerStream) error {
- m := new(Stat)
- if err := stream.RecvMsg(m); err != nil { return err }
- return srv.(MonsterStorageServer).Retrieve(m, &monsterStorageRetrieveServer{stream})
+ m := new(Stat)
+ if err := stream.RecvMsg(m); err != nil {
+ return err
+ }
+ return srv.(MonsterStorageServer).Retrieve(m, &monsterStorageRetrieveServer{stream})
}
-type MonsterStorage_RetrieveServer interface {
- Send(* flatbuffers.Builder) error
- grpc.ServerStream
+type MonsterStorage_RetrieveServer interface {
+ Send(*flatbuffers.Builder) error
+ grpc.ServerStream
}
type monsterStorageRetrieveServer struct {
- grpc.ServerStream
+ grpc.ServerStream
}
func (x *monsterStorageRetrieveServer) Send(m *flatbuffers.Builder) error {
- return x.ServerStream.SendMsg(m)
+ return x.ServerStream.SendMsg(m)
}
-
func _MonsterStorage_GetMaxHitPoint_Handler(srv interface{}, stream grpc.ServerStream) error {
- return srv.(MonsterStorageServer).GetMaxHitPoint(&monsterStorageGetMaxHitPointServer{stream})
+ return srv.(MonsterStorageServer).GetMaxHitPoint(&monsterStorageGetMaxHitPointServer{stream})
}
-type MonsterStorage_GetMaxHitPointServer interface {
- Recv() (* Monster, error)
- SendAndClose(* flatbuffers.Builder) error
- grpc.ServerStream
+type MonsterStorage_GetMaxHitPointServer interface {
+ Recv() (*Monster, error)
+ SendAndClose(*flatbuffers.Builder) error
+ grpc.ServerStream
}
type monsterStorageGetMaxHitPointServer struct {
- grpc.ServerStream
+ grpc.ServerStream
}
func (x *monsterStorageGetMaxHitPointServer) Recv() (*Monster, error) {
- m := new(Monster)
- if err := x.ServerStream.RecvMsg(m); err != nil { return nil, err }
- return m, nil
+ m := new(Monster)
+ if err := x.ServerStream.RecvMsg(m); err != nil {
+ return nil, err
+ }
+ return m, nil
}
func (x *monsterStorageGetMaxHitPointServer) SendAndClose(m *flatbuffers.Builder) error {
- return x.ServerStream.SendMsg(m)
+ return x.ServerStream.SendMsg(m)
}
-
func _MonsterStorage_GetMinMaxHitPoints_Handler(srv interface{}, stream grpc.ServerStream) error {
- return srv.(MonsterStorageServer).GetMinMaxHitPoints(&monsterStorageGetMinMaxHitPointsServer{stream})
+ return srv.(MonsterStorageServer).GetMinMaxHitPoints(&monsterStorageGetMinMaxHitPointsServer{stream})
}
-type MonsterStorage_GetMinMaxHitPointsServer interface {
- Send(* flatbuffers.Builder) error
- Recv() (* Monster, error)
- grpc.ServerStream
+type MonsterStorage_GetMinMaxHitPointsServer interface {
+ Send(*flatbuffers.Builder) error
+ Recv() (*Monster, error)
+ grpc.ServerStream
}
type monsterStorageGetMinMaxHitPointsServer struct {
- grpc.ServerStream
+ grpc.ServerStream
}
func (x *monsterStorageGetMinMaxHitPointsServer) Send(m *flatbuffers.Builder) error {
- return x.ServerStream.SendMsg(m)
+ return x.ServerStream.SendMsg(m)
}
func (x *monsterStorageGetMinMaxHitPointsServer) Recv() (*Monster, error) {
- m := new(Monster)
- if err := x.ServerStream.RecvMsg(m); err != nil { return nil, err }
- return m, nil
+ m := new(Monster)
+ if err := x.ServerStream.RecvMsg(m); err != nil {
+ return nil, err
+ }
+ return m, nil
}
-
var _MonsterStorage_serviceDesc = grpc.ServiceDesc{
- ServiceName: "MyGame.Example.MonsterStorage",
- HandlerType: (*MonsterStorageServer)(nil),
- Methods: []grpc.MethodDesc{
- {
- MethodName: "Store",
- Handler: _MonsterStorage_Store_Handler,
- },
- },
- Streams: []grpc.StreamDesc{
- {
- StreamName: "Retrieve",
- Handler: _MonsterStorage_Retrieve_Handler,
- ServerStreams: true,
- },
- {
- StreamName: "GetMaxHitPoint",
- Handler: _MonsterStorage_GetMaxHitPoint_Handler,
- ClientStreams: true,
- },
- {
- StreamName: "GetMinMaxHitPoints",
- Handler: _MonsterStorage_GetMinMaxHitPoints_Handler,
- ServerStreams: true,
- ClientStreams: true,
- },
- },
+ ServiceName: "MyGame.Example.MonsterStorage",
+ HandlerType: (*MonsterStorageServer)(nil),
+ Methods: []grpc.MethodDesc{
+ {
+ MethodName: "Store",
+ Handler: _MonsterStorage_Store_Handler,
+ },
+ },
+ Streams: []grpc.StreamDesc{
+ {
+ StreamName: "Retrieve",
+ Handler: _MonsterStorage_Retrieve_Handler,
+ ServerStreams: true,
+ },
+ {
+ StreamName: "GetMaxHitPoint",
+ Handler: _MonsterStorage_GetMaxHitPoint_Handler,
+ ClientStreams: true,
+ },
+ {
+ StreamName: "GetMinMaxHitPoints",
+ Handler: _MonsterStorage_GetMinMaxHitPoints_Handler,
+ ServerStreams: true,
+ ClientStreams: true,
+ },
+ },
}
-
diff --git a/tests/MyGame/Example/MonsterT.java b/tests/MyGame/Example/MonsterT.java
new file mode 100644
index 0000000..06804c7
--- /dev/null
+++ b/tests/MyGame/Example/MonsterT.java
@@ -0,0 +1,324 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+package MyGame.Example;
+
+import java.nio.*;
+import java.lang.*;
+import java.util.*;
+import com.google.flatbuffers.*;
+
+public class MonsterT {
+ private MyGame.Example.Vec3T pos;
+ private short mana;
+ private short hp;
+ private String name;
+ private int[] inventory;
+ private int color;
+ private MyGame.Example.AnyUnion test;
+ private MyGame.Example.TestT[] test4;
+ private String[] testarrayofstring;
+ private MyGame.Example.MonsterT[] testarrayoftables;
+ private MyGame.Example.MonsterT enemy;
+ private int[] testnestedflatbuffer;
+ private MyGame.Example.StatT testempty;
+ private boolean testbool;
+ private int testhashs32Fnv1;
+ private long testhashu32Fnv1;
+ private long testhashs64Fnv1;
+ private long testhashu64Fnv1;
+ private int testhashs32Fnv1a;
+ private long testhashu32Fnv1a;
+ private long testhashs64Fnv1a;
+ private long testhashu64Fnv1a;
+ private boolean[] testarrayofbools;
+ private float testf;
+ private float testf2;
+ private float testf3;
+ private String[] testarrayofstring2;
+ private MyGame.Example.AbilityT[] testarrayofsortedstruct;
+ private int[] flex;
+ private MyGame.Example.TestT[] test5;
+ private long[] vectorOfLongs;
+ private double[] vectorOfDoubles;
+ private MyGame.InParentNamespaceT parentNamespaceTest;
+ private MyGame.Example.ReferrableT[] vectorOfReferrables;
+ private long singleWeakReference;
+ private long[] vectorOfWeakReferences;
+ private MyGame.Example.ReferrableT[] vectorOfStrongReferrables;
+ private long coOwningReference;
+ private long[] vectorOfCoOwningReferences;
+ private long nonOwningReference;
+ private long[] vectorOfNonOwningReferences;
+ private MyGame.Example.AnyUniqueAliasesUnion anyUnique;
+ private MyGame.Example.AnyAmbiguousAliasesUnion anyAmbiguous;
+ private int[] vectorOfEnums;
+ private byte signedEnum;
+ private int[] testrequirednestedflatbuffer;
+ private MyGame.Example.StatT[] scalarKeySortedTables;
+ private MyGame.Example.TestT nativeInline;
+ private long longEnumNonEnumDefault;
+ private long longEnumNormalDefault;
+
+ public MyGame.Example.Vec3T getPos() { return pos; }
+
+ public void setPos(MyGame.Example.Vec3T pos) { this.pos = pos; }
+
+ public short getMana() { return mana; }
+
+ public void setMana(short mana) { this.mana = mana; }
+
+ public short getHp() { return hp; }
+
+ public void setHp(short hp) { this.hp = hp; }
+
+ public String getName() { return name; }
+
+ public void setName(String name) { this.name = name; }
+
+ public int[] getInventory() { return inventory; }
+
+ public void setInventory(int[] inventory) { this.inventory = inventory; }
+
+ public int getColor() { return color; }
+
+ public void setColor(int color) { this.color = color; }
+
+ public MyGame.Example.AnyUnion getTest() { return test; }
+
+ public void setTest(MyGame.Example.AnyUnion test) { this.test = test; }
+
+ public MyGame.Example.TestT[] getTest4() { return test4; }
+
+ public void setTest4(MyGame.Example.TestT[] test4) { this.test4 = test4; }
+
+ public String[] getTestarrayofstring() { return testarrayofstring; }
+
+ public void setTestarrayofstring(String[] testarrayofstring) { this.testarrayofstring = testarrayofstring; }
+
+ public MyGame.Example.MonsterT[] getTestarrayoftables() { return testarrayoftables; }
+
+ public void setTestarrayoftables(MyGame.Example.MonsterT[] testarrayoftables) { this.testarrayoftables = testarrayoftables; }
+
+ public MyGame.Example.MonsterT getEnemy() { return enemy; }
+
+ public void setEnemy(MyGame.Example.MonsterT enemy) { this.enemy = enemy; }
+
+ public int[] getTestnestedflatbuffer() { return testnestedflatbuffer; }
+
+ public void setTestnestedflatbuffer(int[] testnestedflatbuffer) { this.testnestedflatbuffer = testnestedflatbuffer; }
+
+ public MyGame.Example.StatT getTestempty() { return testempty; }
+
+ public void setTestempty(MyGame.Example.StatT testempty) { this.testempty = testempty; }
+
+ public boolean getTestbool() { return testbool; }
+
+ public void setTestbool(boolean testbool) { this.testbool = testbool; }
+
+ public int getTesthashs32Fnv1() { return testhashs32Fnv1; }
+
+ public void setTesthashs32Fnv1(int testhashs32Fnv1) { this.testhashs32Fnv1 = testhashs32Fnv1; }
+
+ public long getTesthashu32Fnv1() { return testhashu32Fnv1; }
+
+ public void setTesthashu32Fnv1(long testhashu32Fnv1) { this.testhashu32Fnv1 = testhashu32Fnv1; }
+
+ public long getTesthashs64Fnv1() { return testhashs64Fnv1; }
+
+ public void setTesthashs64Fnv1(long testhashs64Fnv1) { this.testhashs64Fnv1 = testhashs64Fnv1; }
+
+ public long getTesthashu64Fnv1() { return testhashu64Fnv1; }
+
+ public void setTesthashu64Fnv1(long testhashu64Fnv1) { this.testhashu64Fnv1 = testhashu64Fnv1; }
+
+ public int getTesthashs32Fnv1a() { return testhashs32Fnv1a; }
+
+ public void setTesthashs32Fnv1a(int testhashs32Fnv1a) { this.testhashs32Fnv1a = testhashs32Fnv1a; }
+
+ public long getTesthashu32Fnv1a() { return testhashu32Fnv1a; }
+
+ public void setTesthashu32Fnv1a(long testhashu32Fnv1a) { this.testhashu32Fnv1a = testhashu32Fnv1a; }
+
+ public long getTesthashs64Fnv1a() { return testhashs64Fnv1a; }
+
+ public void setTesthashs64Fnv1a(long testhashs64Fnv1a) { this.testhashs64Fnv1a = testhashs64Fnv1a; }
+
+ public long getTesthashu64Fnv1a() { return testhashu64Fnv1a; }
+
+ public void setTesthashu64Fnv1a(long testhashu64Fnv1a) { this.testhashu64Fnv1a = testhashu64Fnv1a; }
+
+ public boolean[] getTestarrayofbools() { return testarrayofbools; }
+
+ public void setTestarrayofbools(boolean[] testarrayofbools) { this.testarrayofbools = testarrayofbools; }
+
+ public float getTestf() { return testf; }
+
+ public void setTestf(float testf) { this.testf = testf; }
+
+ public float getTestf2() { return testf2; }
+
+ public void setTestf2(float testf2) { this.testf2 = testf2; }
+
+ public float getTestf3() { return testf3; }
+
+ public void setTestf3(float testf3) { this.testf3 = testf3; }
+
+ public String[] getTestarrayofstring2() { return testarrayofstring2; }
+
+ public void setTestarrayofstring2(String[] testarrayofstring2) { this.testarrayofstring2 = testarrayofstring2; }
+
+ public MyGame.Example.AbilityT[] getTestarrayofsortedstruct() { return testarrayofsortedstruct; }
+
+ public void setTestarrayofsortedstruct(MyGame.Example.AbilityT[] testarrayofsortedstruct) { this.testarrayofsortedstruct = testarrayofsortedstruct; }
+
+ public int[] getFlex() { return flex; }
+
+ public void setFlex(int[] flex) { this.flex = flex; }
+
+ public MyGame.Example.TestT[] getTest5() { return test5; }
+
+ public void setTest5(MyGame.Example.TestT[] test5) { this.test5 = test5; }
+
+ public long[] getVectorOfLongs() { return vectorOfLongs; }
+
+ public void setVectorOfLongs(long[] vectorOfLongs) { this.vectorOfLongs = vectorOfLongs; }
+
+ public double[] getVectorOfDoubles() { return vectorOfDoubles; }
+
+ public void setVectorOfDoubles(double[] vectorOfDoubles) { this.vectorOfDoubles = vectorOfDoubles; }
+
+ public MyGame.InParentNamespaceT getParentNamespaceTest() { return parentNamespaceTest; }
+
+ public void setParentNamespaceTest(MyGame.InParentNamespaceT parentNamespaceTest) { this.parentNamespaceTest = parentNamespaceTest; }
+
+ public MyGame.Example.ReferrableT[] getVectorOfReferrables() { return vectorOfReferrables; }
+
+ public void setVectorOfReferrables(MyGame.Example.ReferrableT[] vectorOfReferrables) { this.vectorOfReferrables = vectorOfReferrables; }
+
+ public long getSingleWeakReference() { return singleWeakReference; }
+
+ public void setSingleWeakReference(long singleWeakReference) { this.singleWeakReference = singleWeakReference; }
+
+ public long[] getVectorOfWeakReferences() { return vectorOfWeakReferences; }
+
+ public void setVectorOfWeakReferences(long[] vectorOfWeakReferences) { this.vectorOfWeakReferences = vectorOfWeakReferences; }
+
+ public MyGame.Example.ReferrableT[] getVectorOfStrongReferrables() { return vectorOfStrongReferrables; }
+
+ public void setVectorOfStrongReferrables(MyGame.Example.ReferrableT[] vectorOfStrongReferrables) { this.vectorOfStrongReferrables = vectorOfStrongReferrables; }
+
+ public long getCoOwningReference() { return coOwningReference; }
+
+ public void setCoOwningReference(long coOwningReference) { this.coOwningReference = coOwningReference; }
+
+ public long[] getVectorOfCoOwningReferences() { return vectorOfCoOwningReferences; }
+
+ public void setVectorOfCoOwningReferences(long[] vectorOfCoOwningReferences) { this.vectorOfCoOwningReferences = vectorOfCoOwningReferences; }
+
+ public long getNonOwningReference() { return nonOwningReference; }
+
+ public void setNonOwningReference(long nonOwningReference) { this.nonOwningReference = nonOwningReference; }
+
+ public long[] getVectorOfNonOwningReferences() { return vectorOfNonOwningReferences; }
+
+ public void setVectorOfNonOwningReferences(long[] vectorOfNonOwningReferences) { this.vectorOfNonOwningReferences = vectorOfNonOwningReferences; }
+
+ public MyGame.Example.AnyUniqueAliasesUnion getAnyUnique() { return anyUnique; }
+
+ public void setAnyUnique(MyGame.Example.AnyUniqueAliasesUnion anyUnique) { this.anyUnique = anyUnique; }
+
+ public MyGame.Example.AnyAmbiguousAliasesUnion getAnyAmbiguous() { return anyAmbiguous; }
+
+ public void setAnyAmbiguous(MyGame.Example.AnyAmbiguousAliasesUnion anyAmbiguous) { this.anyAmbiguous = anyAmbiguous; }
+
+ public int[] getVectorOfEnums() { return vectorOfEnums; }
+
+ public void setVectorOfEnums(int[] vectorOfEnums) { this.vectorOfEnums = vectorOfEnums; }
+
+ public byte getSignedEnum() { return signedEnum; }
+
+ public void setSignedEnum(byte signedEnum) { this.signedEnum = signedEnum; }
+
+ public int[] getTestrequirednestedflatbuffer() { return testrequirednestedflatbuffer; }
+
+ public void setTestrequirednestedflatbuffer(int[] testrequirednestedflatbuffer) { this.testrequirednestedflatbuffer = testrequirednestedflatbuffer; }
+
+ public MyGame.Example.StatT[] getScalarKeySortedTables() { return scalarKeySortedTables; }
+
+ public void setScalarKeySortedTables(MyGame.Example.StatT[] scalarKeySortedTables) { this.scalarKeySortedTables = scalarKeySortedTables; }
+
+ public MyGame.Example.TestT getNativeInline() { return nativeInline; }
+
+ public void setNativeInline(MyGame.Example.TestT nativeInline) { this.nativeInline = nativeInline; }
+
+ public long getLongEnumNonEnumDefault() { return longEnumNonEnumDefault; }
+
+ public void setLongEnumNonEnumDefault(long longEnumNonEnumDefault) { this.longEnumNonEnumDefault = longEnumNonEnumDefault; }
+
+ public long getLongEnumNormalDefault() { return longEnumNormalDefault; }
+
+ public void setLongEnumNormalDefault(long longEnumNormalDefault) { this.longEnumNormalDefault = longEnumNormalDefault; }
+
+
+ public MonsterT() {
+ this.pos = new MyGame.Example.Vec3T();
+ this.mana = 150;
+ this.hp = 100;
+ this.name = null;
+ this.inventory = null;
+ this.color = 8;
+ this.test = null;
+ this.test4 = null;
+ this.testarrayofstring = null;
+ this.testarrayoftables = null;
+ this.enemy = null;
+ this.testnestedflatbuffer = null;
+ this.testempty = null;
+ this.testbool = false;
+ this.testhashs32Fnv1 = 0;
+ this.testhashu32Fnv1 = 0L;
+ this.testhashs64Fnv1 = 0L;
+ this.testhashu64Fnv1 = 0L;
+ this.testhashs32Fnv1a = 0;
+ this.testhashu32Fnv1a = 0L;
+ this.testhashs64Fnv1a = 0L;
+ this.testhashu64Fnv1a = 0L;
+ this.testarrayofbools = null;
+ this.testf = 3.14159f;
+ this.testf2 = 3.0f;
+ this.testf3 = 0.0f;
+ this.testarrayofstring2 = null;
+ this.testarrayofsortedstruct = null;
+ this.flex = null;
+ this.test5 = null;
+ this.vectorOfLongs = null;
+ this.vectorOfDoubles = null;
+ this.parentNamespaceTest = null;
+ this.vectorOfReferrables = null;
+ this.singleWeakReference = 0L;
+ this.vectorOfWeakReferences = null;
+ this.vectorOfStrongReferrables = null;
+ this.coOwningReference = 0L;
+ this.vectorOfCoOwningReferences = null;
+ this.nonOwningReference = 0L;
+ this.vectorOfNonOwningReferences = null;
+ this.anyUnique = null;
+ this.anyAmbiguous = null;
+ this.vectorOfEnums = null;
+ this.signedEnum = -1;
+ this.testrequirednestedflatbuffer = null;
+ this.scalarKeySortedTables = null;
+ this.nativeInline = new MyGame.Example.TestT();
+ this.longEnumNonEnumDefault = 0L;
+ this.longEnumNormalDefault = 2L;
+ }
+ public static MonsterT deserializeFromBinary(byte[] fbBuffer) {
+ return Monster.getRootAsMonster(ByteBuffer.wrap(fbBuffer)).unpack();
+ }
+ public byte[] serializeToBinary() {
+ FlatBufferBuilder fbb = new FlatBufferBuilder();
+ Monster.finishMonsterBuffer(fbb, Monster.pack(fbb, this));
+ return fbb.sizedByteArray();
+ }
+}
+
diff --git a/tests/MyGame/Example/NestedStruct.cs b/tests/MyGame/Example/NestedStruct.cs
index 13e3498..f323342 100644
--- a/tests/MyGame/Example/NestedStruct.cs
+++ b/tests/MyGame/Example/NestedStruct.cs
@@ -66,7 +66,7 @@
_c,
_d);
}
-};
+}
public class NestedStructT
{
diff --git a/tests/MyGame/Example/NestedStruct.java b/tests/MyGame/Example/NestedStruct.java
index fbfedd8..d3081e6 100644
--- a/tests/MyGame/Example/NestedStruct.java
+++ b/tests/MyGame/Example/NestedStruct.java
@@ -43,5 +43,32 @@
public NestedStruct get(int j) { return get(new NestedStruct(), j); }
public NestedStruct get(NestedStruct obj, int j) { return obj.__assign(__element(j), bb); }
}
+ public NestedStructT unpack() {
+ NestedStructT _o = new NestedStructT();
+ unpackTo(_o);
+ return _o;
+ }
+ public void unpackTo(NestedStructT _o) {
+ int[] _oA = _o.getA();
+ for (int _j = 0; _j < 2; ++_j) { _oA[_j] = a(_j); }
+ byte _oB = b();
+ _o.setB(_oB);
+ byte[] _oC = _o.getC();
+ for (int _j = 0; _j < 2; ++_j) { _oC[_j] = c(_j); }
+ long[] _oD = _o.getD();
+ for (int _j = 0; _j < 2; ++_j) { _oD[_j] = d(_j); }
+ }
+ public static int pack(FlatBufferBuilder builder, NestedStructT _o) {
+ if (_o == null) return 0;
+ int[] _a = _o.getA();
+ byte[] _c = _o.getC();
+ long[] _d = _o.getD();
+ return createNestedStruct(
+ builder,
+ _a,
+ _o.getB(),
+ _c,
+ _d);
+ }
}
diff --git a/tests/MyGame/Example/NestedStructT.java b/tests/MyGame/Example/NestedStructT.java
new file mode 100644
index 0000000..7892462
--- /dev/null
+++ b/tests/MyGame/Example/NestedStructT.java
@@ -0,0 +1,40 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+package MyGame.Example;
+
+import java.nio.*;
+import java.lang.*;
+import java.util.*;
+import com.google.flatbuffers.*;
+
+public class NestedStructT {
+ private int[] a;
+ private byte b;
+ private byte[] c;
+ private long[] d;
+
+ public int[] getA() { return a; }
+
+ public void setA(int[] a) { if (a != null && a.length == 2) this.a = a; }
+
+ public byte getB() { return b; }
+
+ public void setB(byte b) { this.b = b; }
+
+ public byte[] getC() { return c; }
+
+ public void setC(byte[] c) { if (c != null && c.length == 2) this.c = c; }
+
+ public long[] getD() { return d; }
+
+ public void setD(long[] d) { if (d != null && d.length == 2) this.d = d; }
+
+
+ public NestedStructT() {
+ this.a = new int[2];
+ this.b = 0;
+ this.c = new byte[2];
+ this.d = new long[2];
+ }
+}
+
diff --git a/tests/MyGame/Example/Race.java b/tests/MyGame/Example/Race.java
index 0dfd80b..9f20e30 100644
--- a/tests/MyGame/Example/Race.java
+++ b/tests/MyGame/Example/Race.java
@@ -2,6 +2,7 @@
package MyGame.Example;
+@SuppressWarnings("unused")
public final class Race {
private Race() { }
public static final byte None = -1;
diff --git a/tests/MyGame/Example/Race.kt b/tests/MyGame/Example/Race.kt
index 6eb9534..6f770a3 100644
--- a/tests/MyGame/Example/Race.kt
+++ b/tests/MyGame/Example/Race.kt
@@ -3,7 +3,6 @@
package MyGame.Example
@Suppress("unused")
-@ExperimentalUnsignedTypes
class Race private constructor() {
companion object {
const val None: Byte = -1
diff --git a/tests/MyGame/Example/Race.lua b/tests/MyGame/Example/Race.lua
index 646f374..f241870 100644
--- a/tests/MyGame/Example/Race.lua
+++ b/tests/MyGame/Example/Race.lua
@@ -1,12 +1,20 @@
--- automatically generated by the FlatBuffers compiler, do not modify
+--[[ MyGame.Example.Race
--- namespace: Example
+ Automatically generated by the FlatBuffers compiler, do not modify.
+ Or modify. I'm a message, not a cop.
+
+ flatc version: 2.0.6
+
+ Declared by : //monster_test.fbs
+ Rooting type : MyGame.Example.Monster (//monster_test.fbs)
+
+--]]
local Race = {
- None = -1,
- Human = 0,
- Dwarf = 1,
- Elf = 2,
+ None = -1,
+ Human = 0,
+ Dwarf = 1,
+ Elf = 2,
}
-return Race -- return the module
\ No newline at end of file
+return Race
\ No newline at end of file
diff --git a/tests/MyGame/Example/Race.py b/tests/MyGame/Example/Race.py
index a39c6ea..30f3960 100644
--- a/tests/MyGame/Example/Race.py
+++ b/tests/MyGame/Example/Race.py
@@ -7,4 +7,3 @@
Human = 0
Dwarf = 1
Elf = 2
-
diff --git a/tests/MyGame/Example/Referrable.cs b/tests/MyGame/Example/Referrable.cs
index 81394ad..e6f3146 100644
--- a/tests/MyGame/Example/Referrable.cs
+++ b/tests/MyGame/Example/Referrable.cs
@@ -13,7 +13,7 @@
{
private Table __p;
public ByteBuffer ByteBuffer { get { return __p.bb; } }
- public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_1_12_0(); }
+ public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_2_0_0(); }
public static Referrable GetRootAsReferrable(ByteBuffer _bb) { return GetRootAsReferrable(_bb, new Referrable()); }
public static Referrable GetRootAsReferrable(ByteBuffer _bb, Referrable obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); }
public void __init(int _i, ByteBuffer _bb) { __p = new Table(_i, _bb); }
@@ -74,7 +74,7 @@
builder,
_o.Id);
}
-};
+}
public class ReferrableT
{
diff --git a/tests/MyGame/Example/Referrable.java b/tests/MyGame/Example/Referrable.java
index 1f92958..da8dea6 100644
--- a/tests/MyGame/Example/Referrable.java
+++ b/tests/MyGame/Example/Referrable.java
@@ -9,7 +9,7 @@
@SuppressWarnings("unused")
public final class Referrable extends Table {
- public static void ValidateVersion() { Constants.FLATBUFFERS_1_12_0(); }
+ public static void ValidateVersion() { Constants.FLATBUFFERS_2_0_0(); }
public static Referrable getRootAsReferrable(ByteBuffer _bb) { return getRootAsReferrable(_bb, new Referrable()); }
public static Referrable getRootAsReferrable(ByteBuffer _bb, Referrable obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); }
@@ -68,5 +68,20 @@
public Referrable getByKey(long key) { return __lookup_by_key(null, __vector(), key, bb); }
public Referrable getByKey(Referrable obj, long key) { return __lookup_by_key(obj, __vector(), key, bb); }
}
+ public ReferrableT unpack() {
+ ReferrableT _o = new ReferrableT();
+ unpackTo(_o);
+ return _o;
+ }
+ public void unpackTo(ReferrableT _o) {
+ long _oId = id();
+ _o.setId(_oId);
+ }
+ public static int pack(FlatBufferBuilder builder, ReferrableT _o) {
+ if (_o == null) return 0;
+ return createReferrable(
+ builder,
+ _o.getId());
+ }
}
diff --git a/tests/MyGame/Example/Referrable.kt b/tests/MyGame/Example/Referrable.kt
index 2e78c93..7f728a7 100644
--- a/tests/MyGame/Example/Referrable.kt
+++ b/tests/MyGame/Example/Referrable.kt
@@ -7,7 +7,6 @@
import com.google.flatbuffers.*
@Suppress("unused")
-@ExperimentalUnsignedTypes
class Referrable : Table() {
fun __init(_i: Int, _bb: ByteBuffer) {
@@ -37,7 +36,7 @@
return (val_1 - val_2).sign
}
companion object {
- fun validateVersion() = Constants.FLATBUFFERS_1_12_0()
+ fun validateVersion() = Constants.FLATBUFFERS_2_0_0()
fun getRootAsReferrable(_bb: ByteBuffer): Referrable = getRootAsReferrable(_bb, Referrable())
fun getRootAsReferrable(_bb: ByteBuffer, obj: Referrable): Referrable {
_bb.order(ByteOrder.LITTLE_ENDIAN)
diff --git a/tests/MyGame/Example/Referrable.lua b/tests/MyGame/Example/Referrable.lua
index 9b0f5a1..3bd6b0a 100644
--- a/tests/MyGame/Example/Referrable.lua
+++ b/tests/MyGame/Example/Referrable.lua
@@ -1,35 +1,48 @@
--- automatically generated by the FlatBuffers compiler, do not modify
+--[[ MyGame.Example.Referrable
--- namespace: Example
+ Automatically generated by the FlatBuffers compiler, do not modify.
+ Or modify. I'm a message, not a cop.
+
+ flatc version: 2.0.6
+
+ Declared by : //monster_test.fbs
+ Rooting type : MyGame.Example.Monster (//monster_test.fbs)
+
+--]]
local flatbuffers = require('flatbuffers')
-local Referrable = {} -- the module
-local Referrable_mt = {} -- the class metatable
+local Referrable = {}
+local mt = {}
function Referrable.New()
- local o = {}
- setmetatable(o, {__index = Referrable_mt})
- return o
+ local o = {}
+ setmetatable(o, {__index = mt})
+ return o
end
-function Referrable.GetRootAsReferrable(buf, offset)
- local n = flatbuffers.N.UOffsetT:Unpack(buf, offset)
- local o = Referrable.New()
- o:Init(buf, n + offset)
- return o
-end
-function Referrable_mt:Init(buf, pos)
- self.view = flatbuffers.view.New(buf, pos)
-end
-function Referrable_mt:Id()
- local o = self.view:Offset(4)
- if o ~= 0 then
- return self.view:Get(flatbuffers.N.Uint64, o + self.view.pos)
- end
- return 0
-end
-function Referrable.Start(builder) builder:StartObject(1) end
-function Referrable.AddId(builder, id) builder:PrependUint64Slot(0, id, 0) end
-function Referrable.End(builder) return builder:EndObject() end
-return Referrable -- return the module
\ No newline at end of file
+function mt:Init(buf, pos)
+ self.view = flatbuffers.view.New(buf, pos)
+end
+
+function mt:Id()
+ local o = self.view:Offset(4)
+ if o ~= 0 then
+ return self.view:Get(flatbuffers.N.Uint64, self.view.pos + o)
+ end
+ return 0
+end
+
+function Referrable.Start(builder)
+ builder:StartObject(1)
+end
+
+function Referrable.AddId(builder, id)
+ builder:PrependUint64Slot(0, id, 0)
+end
+
+function Referrable.End(builder)
+ return builder:EndObject()
+end
+
+return Referrable
\ No newline at end of file
diff --git a/tests/MyGame/Example/Referrable.py b/tests/MyGame/Example/Referrable.py
index 44bf50f..4b1da6a 100644
--- a/tests/MyGame/Example/Referrable.py
+++ b/tests/MyGame/Example/Referrable.py
@@ -10,13 +10,17 @@
__slots__ = ['_tab']
@classmethod
- def GetRootAsReferrable(cls, buf, offset):
+ def GetRootAs(cls, buf, offset=0):
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
x = Referrable()
x.Init(buf, n + offset)
return x
@classmethod
+ def GetRootAsReferrable(cls, buf, offset=0):
+ """This method is deprecated. Please switch to GetRootAs."""
+ return cls.GetRootAs(buf, offset)
+ @classmethod
def ReferrableBufferHasIdentifier(cls, buf, offset, size_prefixed=False):
return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4D\x4F\x4E\x53", size_prefixed=size_prefixed)
@@ -32,9 +36,14 @@
return 0
def ReferrableStart(builder): builder.StartObject(1)
+def Start(builder):
+ return ReferrableStart(builder)
def ReferrableAddId(builder, id): builder.PrependUint64Slot(0, id, 0)
+def AddId(builder, id):
+ return ReferrableAddId(builder, id)
def ReferrableEnd(builder): return builder.EndObject()
-
+def End(builder):
+ return ReferrableEnd(builder)
class ReferrableT(object):
diff --git a/tests/MyGame/Example/ReferrableT.java b/tests/MyGame/Example/ReferrableT.java
new file mode 100644
index 0000000..3014f04
--- /dev/null
+++ b/tests/MyGame/Example/ReferrableT.java
@@ -0,0 +1,22 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+package MyGame.Example;
+
+import java.nio.*;
+import java.lang.*;
+import java.util.*;
+import com.google.flatbuffers.*;
+
+public class ReferrableT {
+ private long id;
+
+ public long getId() { return id; }
+
+ public void setId(long id) { this.id = id; }
+
+
+ public ReferrableT() {
+ this.id = 0L;
+ }
+}
+
diff --git a/tests/MyGame/Example/Stat.cs b/tests/MyGame/Example/Stat.cs
index 6f19ed4..149b136 100644
--- a/tests/MyGame/Example/Stat.cs
+++ b/tests/MyGame/Example/Stat.cs
@@ -13,7 +13,7 @@
{
private Table __p;
public ByteBuffer ByteBuffer { get { return __p.bb; } }
- public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_1_12_0(); }
+ public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_2_0_0(); }
public static Stat GetRootAsStat(ByteBuffer _bb) { return GetRootAsStat(_bb, new Stat()); }
public static Stat GetRootAsStat(ByteBuffer _bb, Stat obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); }
public void __init(int _i, ByteBuffer _bb) { __p = new Table(_i, _bb); }
@@ -50,6 +50,31 @@
int o = builder.EndTable();
return new Offset<MyGame.Example.Stat>(o);
}
+
+ public static VectorOffset CreateSortedVectorOfStat(FlatBufferBuilder builder, Offset<Stat>[] offsets) {
+ Array.Sort(offsets, (Offset<Stat> o1, Offset<Stat> o2) => builder.DataBuffer.GetUshort(Table.__offset(8, o1.Value, builder.DataBuffer)).CompareTo(builder.DataBuffer.GetUshort(Table.__offset(8, o2.Value, builder.DataBuffer))));
+ return builder.CreateVectorOfTables(offsets);
+ }
+
+ public static Stat? __lookup_by_key(int vectorLocation, ushort key, ByteBuffer bb) {
+ int span = bb.GetInt(vectorLocation - 4);
+ int start = 0;
+ while (span != 0) {
+ int middle = span / 2;
+ int tableOffset = Table.__indirect(vectorLocation + 4 * (start + middle), bb);
+ int comp = bb.GetUshort(Table.__offset(8, bb.Length - tableOffset, bb)).CompareTo(key);
+ if (comp > 0) {
+ span = middle;
+ } else if (comp < 0) {
+ middle++;
+ start += middle;
+ span -= middle;
+ } else {
+ return new Stat().__assign(tableOffset, bb);
+ }
+ }
+ return null;
+ }
public StatT UnPack() {
var _o = new StatT();
this.UnPackTo(_o);
@@ -69,7 +94,7 @@
_o.Val,
_o.Count);
}
-};
+}
public class StatT
{
diff --git a/tests/MyGame/Example/Stat.java b/tests/MyGame/Example/Stat.java
index 116c211..efc2673 100644
--- a/tests/MyGame/Example/Stat.java
+++ b/tests/MyGame/Example/Stat.java
@@ -9,7 +9,7 @@
@SuppressWarnings("unused")
public final class Stat extends Table {
- public static void ValidateVersion() { Constants.FLATBUFFERS_1_12_0(); }
+ public static void ValidateVersion() { Constants.FLATBUFFERS_2_0_0(); }
public static Stat getRootAsStat(ByteBuffer _bb) { return getRootAsStat(_bb, new Stat()); }
public static Stat getRootAsStat(ByteBuffer _bb, Stat obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); }
@@ -21,7 +21,7 @@
public long val() { int o = __offset(6); return o != 0 ? bb.getLong(o + bb_pos) : 0L; }
public boolean mutateVal(long val) { int o = __offset(6); if (o != 0) { bb.putLong(o + bb_pos, val); return true; } else { return false; } }
public int count() { int o = __offset(8); return o != 0 ? bb.getShort(o + bb_pos) & 0xFFFF : 0; }
- public boolean mutateCount(int count) { int o = __offset(8); if (o != 0) { bb.putShort(o + bb_pos, (short)count); return true; } else { return false; } }
+ public boolean mutateCount(int count) { int o = __offset(8); if (o != 0) { bb.putShort(o + bb_pos, (short) count); return true; } else { return false; } }
public static int createStat(FlatBufferBuilder builder,
int idOffset,
@@ -37,17 +37,69 @@
public static void startStat(FlatBufferBuilder builder) { builder.startTable(3); }
public static void addId(FlatBufferBuilder builder, int idOffset) { builder.addOffset(0, idOffset, 0); }
public static void addVal(FlatBufferBuilder builder, long val) { builder.addLong(1, val, 0L); }
- public static void addCount(FlatBufferBuilder builder, int count) { builder.addShort(2, (short)count, (short)0); }
+ public static void addCount(FlatBufferBuilder builder, int count) { builder.addShort(2, (short) count, (short) 0); }
public static int endStat(FlatBufferBuilder builder) {
int o = builder.endTable();
return o;
}
+ @Override
+ protected int keysCompare(Integer o1, Integer o2, ByteBuffer _bb) {
+ int val_1 = _bb.getShort(__offset(8, o1, _bb)) & 0xFFFF;
+ int val_2 = _bb.getShort(__offset(8, o2, _bb)) & 0xFFFF;
+ return val_1 > val_2 ? 1 : val_1 < val_2 ? -1 : 0;
+ }
+
+ public static Stat __lookup_by_key(Stat obj, int vectorLocation, int key, ByteBuffer bb) {
+ int span = bb.getInt(vectorLocation - 4);
+ int start = 0;
+ while (span != 0) {
+ int middle = span / 2;
+ int tableOffset = __indirect(vectorLocation + 4 * (start + middle), bb);
+ int val = bb.getShort(__offset(8, bb.capacity() - tableOffset, bb)) & 0xFFFF;
+ int comp = val > key ? 1 : val < key ? -1 : 0;
+ if (comp > 0) {
+ span = middle;
+ } else if (comp < 0) {
+ middle++;
+ start += middle;
+ span -= middle;
+ } else {
+ return (obj == null ? new Stat() : obj).__assign(tableOffset, bb);
+ }
+ }
+ return null;
+ }
+
public static final class Vector extends BaseVector {
public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; }
public Stat get(int j) { return get(new Stat(), j); }
public Stat get(Stat obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); }
+ public Stat getByKey(int key) { return __lookup_by_key(null, __vector(), key, bb); }
+ public Stat getByKey(Stat obj, int key) { return __lookup_by_key(obj, __vector(), key, bb); }
+ }
+ public StatT unpack() {
+ StatT _o = new StatT();
+ unpackTo(_o);
+ return _o;
+ }
+ public void unpackTo(StatT _o) {
+ String _oId = id();
+ _o.setId(_oId);
+ long _oVal = val();
+ _o.setVal(_oVal);
+ int _oCount = count();
+ _o.setCount(_oCount);
+ }
+ public static int pack(FlatBufferBuilder builder, StatT _o) {
+ if (_o == null) return 0;
+ int _id = _o.getId() == null ? 0 : builder.createString(_o.getId());
+ return createStat(
+ builder,
+ _id,
+ _o.getVal(),
+ _o.getCount());
}
}
diff --git a/tests/MyGame/Example/Stat.kt b/tests/MyGame/Example/Stat.kt
index e72f553..e6cc94c 100644
--- a/tests/MyGame/Example/Stat.kt
+++ b/tests/MyGame/Example/Stat.kt
@@ -7,7 +7,6 @@
import com.google.flatbuffers.*
@Suppress("unused")
-@ExperimentalUnsignedTypes
class Stat : Table() {
fun __init(_i: Int, _bb: ByteBuffer) {
@@ -52,8 +51,13 @@
false
}
}
+ override fun keysCompare(o1: Int, o2: Int, _bb: ByteBuffer) : Int {
+ val val_1 = _bb.getShort(__offset(8, o1, _bb))
+ val val_2 = _bb.getShort(__offset(8, o2, _bb))
+ return (val_1 - val_2).sign
+ }
companion object {
- fun validateVersion() = Constants.FLATBUFFERS_1_12_0()
+ fun validateVersion() = Constants.FLATBUFFERS_2_0_0()
fun getRootAsStat(_bb: ByteBuffer): Stat = getRootAsStat(_bb, Stat())
fun getRootAsStat(_bb: ByteBuffer, obj: Stat): Stat {
_bb.order(ByteOrder.LITTLE_ENDIAN)
@@ -74,5 +78,27 @@
val o = builder.endTable()
return o
}
+ fun __lookup_by_key(obj: Stat?, vectorLocation: Int, key: UShort, bb: ByteBuffer) : Stat? {
+ var span = bb.getInt(vectorLocation - 4)
+ var start = 0
+ while (span != 0) {
+ var middle = span / 2
+ val tableOffset = __indirect(vectorLocation + 4 * (start + middle), bb)
+ val value = bb.getShort(__offset(8, bb.capacity() - tableOffset, bb)).toUShort()
+ val comp = value.compareTo(key)
+ when {
+ comp > 0 -> span = middle
+ comp < 0 -> {
+ middle++
+ start += middle
+ span -= middle
+ }
+ else -> {
+ return (obj ?: Stat()).__assign(tableOffset, bb)
+ }
+ }
+ }
+ return null
+ }
}
}
diff --git a/tests/MyGame/Example/Stat.lua b/tests/MyGame/Example/Stat.lua
index 6999184..f621fd0 100644
--- a/tests/MyGame/Example/Stat.lua
+++ b/tests/MyGame/Example/Stat.lua
@@ -1,50 +1,71 @@
--- automatically generated by the FlatBuffers compiler, do not modify
+--[[ MyGame.Example.Stat
--- namespace: Example
+ Automatically generated by the FlatBuffers compiler, do not modify.
+ Or modify. I'm a message, not a cop.
+
+ flatc version: 2.0.6
+
+ Declared by : //monster_test.fbs
+ Rooting type : MyGame.Example.Monster (//monster_test.fbs)
+
+--]]
local flatbuffers = require('flatbuffers')
-local Stat = {} -- the module
-local Stat_mt = {} -- the class metatable
+local Stat = {}
+local mt = {}
function Stat.New()
- local o = {}
- setmetatable(o, {__index = Stat_mt})
- return o
+ local o = {}
+ setmetatable(o, {__index = mt})
+ return o
end
-function Stat.GetRootAsStat(buf, offset)
- local n = flatbuffers.N.UOffsetT:Unpack(buf, offset)
- local o = Stat.New()
- o:Init(buf, n + offset)
- return o
-end
-function Stat_mt:Init(buf, pos)
- self.view = flatbuffers.view.New(buf, pos)
-end
-function Stat_mt:Id()
- local o = self.view:Offset(4)
- if o ~= 0 then
- return self.view:String(o + self.view.pos)
- end
-end
-function Stat_mt:Val()
- local o = self.view:Offset(6)
- if o ~= 0 then
- return self.view:Get(flatbuffers.N.Int64, o + self.view.pos)
- end
- return 0
-end
-function Stat_mt:Count()
- local o = self.view:Offset(8)
- if o ~= 0 then
- return self.view:Get(flatbuffers.N.Uint16, o + self.view.pos)
- end
- return 0
-end
-function Stat.Start(builder) builder:StartObject(3) end
-function Stat.AddId(builder, id) builder:PrependUOffsetTRelativeSlot(0, id, 0) end
-function Stat.AddVal(builder, val) builder:PrependInt64Slot(1, val, 0) end
-function Stat.AddCount(builder, count) builder:PrependUint16Slot(2, count, 0) end
-function Stat.End(builder) return builder:EndObject() end
-return Stat -- return the module
\ No newline at end of file
+function mt:Init(buf, pos)
+ self.view = flatbuffers.view.New(buf, pos)
+end
+
+function mt:Id()
+ local o = self.view:Offset(4)
+ if o ~= 0 then
+ return self.view:String(self.view.pos + o)
+ end
+end
+
+function mt:Val()
+ local o = self.view:Offset(6)
+ if o ~= 0 then
+ return self.view:Get(flatbuffers.N.Int64, self.view.pos + o)
+ end
+ return 0
+end
+
+function mt:Count()
+ local o = self.view:Offset(8)
+ if o ~= 0 then
+ return self.view:Get(flatbuffers.N.Uint16, self.view.pos + o)
+ end
+ return 0
+end
+
+function Stat.Start(builder)
+ builder:StartObject(3)
+end
+
+function Stat.AddId(builder, id)
+ builder:PrependUOffsetTRelativeSlot(0, id, 0)
+end
+
+function Stat.AddVal(builder, val)
+ builder:PrependInt64Slot(1, val, 0)
+end
+
+function Stat.AddCount(builder, count)
+ builder:PrependUint16Slot(2, count, 0)
+end
+
+function Stat.End(builder)
+ return builder:EndObject()
+end
+
+return Stat
\ No newline at end of file
diff --git a/tests/MyGame/Example/Stat.py b/tests/MyGame/Example/Stat.py
index 7d3362f..3b19a3b 100644
--- a/tests/MyGame/Example/Stat.py
+++ b/tests/MyGame/Example/Stat.py
@@ -10,13 +10,17 @@
__slots__ = ['_tab']
@classmethod
- def GetRootAsStat(cls, buf, offset):
+ def GetRootAs(cls, buf, offset=0):
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
x = Stat()
x.Init(buf, n + offset)
return x
@classmethod
+ def GetRootAsStat(cls, buf, offset=0):
+ """This method is deprecated. Please switch to GetRootAs."""
+ return cls.GetRootAs(buf, offset)
+ @classmethod
def StatBufferHasIdentifier(cls, buf, offset, size_prefixed=False):
return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4D\x4F\x4E\x53", size_prefixed=size_prefixed)
@@ -46,11 +50,20 @@
return 0
def StatStart(builder): builder.StartObject(3)
+def Start(builder):
+ return StatStart(builder)
def StatAddId(builder, id): builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(id), 0)
+def AddId(builder, id):
+ return StatAddId(builder, id)
def StatAddVal(builder, val): builder.PrependInt64Slot(1, val, 0)
+def AddVal(builder, val):
+ return StatAddVal(builder, val)
def StatAddCount(builder, count): builder.PrependUint16Slot(2, count, 0)
+def AddCount(builder, count):
+ return StatAddCount(builder, count)
def StatEnd(builder): return builder.EndObject()
-
+def End(builder):
+ return StatEnd(builder)
class StatT(object):
diff --git a/tests/MyGame/Example/StatT.java b/tests/MyGame/Example/StatT.java
new file mode 100644
index 0000000..67ad13e
--- /dev/null
+++ b/tests/MyGame/Example/StatT.java
@@ -0,0 +1,34 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+package MyGame.Example;
+
+import java.nio.*;
+import java.lang.*;
+import java.util.*;
+import com.google.flatbuffers.*;
+
+public class StatT {
+ private String id;
+ private long val;
+ private int count;
+
+ public String getId() { return id; }
+
+ public void setId(String id) { this.id = id; }
+
+ public long getVal() { return val; }
+
+ public void setVal(long val) { this.val = val; }
+
+ public int getCount() { return count; }
+
+ public void setCount(int count) { this.count = count; }
+
+
+ public StatT() {
+ this.id = null;
+ this.val = 0L;
+ this.count = 0;
+ }
+}
+
diff --git a/tests/MyGame/Example/StructOfStructs.cs b/tests/MyGame/Example/StructOfStructs.cs
new file mode 100644
index 0000000..3a1607d
--- /dev/null
+++ b/tests/MyGame/Example/StructOfStructs.cs
@@ -0,0 +1,83 @@
+// <auto-generated>
+// automatically generated by the FlatBuffers compiler, do not modify
+// </auto-generated>
+
+namespace MyGame.Example
+{
+
+using global::System;
+using global::System.Collections.Generic;
+using global::FlatBuffers;
+
+public struct StructOfStructs : IFlatbufferObject
+{
+ private Struct __p;
+ public ByteBuffer ByteBuffer { get { return __p.bb; } }
+ public void __init(int _i, ByteBuffer _bb) { __p = new Struct(_i, _bb); }
+ public StructOfStructs __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; }
+
+ public MyGame.Example.Ability A { get { return (new MyGame.Example.Ability()).__assign(__p.bb_pos + 0, __p.bb); } }
+ public MyGame.Example.Test B { get { return (new MyGame.Example.Test()).__assign(__p.bb_pos + 8, __p.bb); } }
+ public MyGame.Example.Ability C { get { return (new MyGame.Example.Ability()).__assign(__p.bb_pos + 12, __p.bb); } }
+
+ public static Offset<MyGame.Example.StructOfStructs> CreateStructOfStructs(FlatBufferBuilder builder, uint a_Id, uint a_Distance, short b_A, sbyte b_B, uint c_Id, uint c_Distance) {
+ builder.Prep(4, 20);
+ builder.Prep(4, 8);
+ builder.PutUint(c_Distance);
+ builder.PutUint(c_Id);
+ builder.Prep(2, 4);
+ builder.Pad(1);
+ builder.PutSbyte(b_B);
+ builder.PutShort(b_A);
+ builder.Prep(4, 8);
+ builder.PutUint(a_Distance);
+ builder.PutUint(a_Id);
+ return new Offset<MyGame.Example.StructOfStructs>(builder.Offset);
+ }
+ public StructOfStructsT UnPack() {
+ var _o = new StructOfStructsT();
+ this.UnPackTo(_o);
+ return _o;
+ }
+ public void UnPackTo(StructOfStructsT _o) {
+ _o.A = this.A.UnPack();
+ _o.B = this.B.UnPack();
+ _o.C = this.C.UnPack();
+ }
+ public static Offset<MyGame.Example.StructOfStructs> Pack(FlatBufferBuilder builder, StructOfStructsT _o) {
+ if (_o == null) return default(Offset<MyGame.Example.StructOfStructs>);
+ var _a_id = _o.A.Id;
+ var _a_distance = _o.A.Distance;
+ var _b_a = _o.B.A;
+ var _b_b = _o.B.B;
+ var _c_id = _o.C.Id;
+ var _c_distance = _o.C.Distance;
+ return CreateStructOfStructs(
+ builder,
+ _a_id,
+ _a_distance,
+ _b_a,
+ _b_b,
+ _c_id,
+ _c_distance);
+ }
+}
+
+public class StructOfStructsT
+{
+ [Newtonsoft.Json.JsonProperty("a")]
+ public MyGame.Example.AbilityT A { get; set; }
+ [Newtonsoft.Json.JsonProperty("b")]
+ public MyGame.Example.TestT B { get; set; }
+ [Newtonsoft.Json.JsonProperty("c")]
+ public MyGame.Example.AbilityT C { get; set; }
+
+ public StructOfStructsT() {
+ this.A = new MyGame.Example.AbilityT();
+ this.B = new MyGame.Example.TestT();
+ this.C = new MyGame.Example.AbilityT();
+ }
+}
+
+
+}
diff --git a/tests/MyGame/Example/StructOfStructs.go b/tests/MyGame/Example/StructOfStructs.go
new file mode 100644
index 0000000..35ccfcb
--- /dev/null
+++ b/tests/MyGame/Example/StructOfStructs.go
@@ -0,0 +1,80 @@
+// Code generated by the FlatBuffers compiler. DO NOT EDIT.
+
+package Example
+
+import (
+ flatbuffers "github.com/google/flatbuffers/go"
+)
+
+type StructOfStructsT struct {
+ A *AbilityT
+ B *TestT
+ C *AbilityT
+}
+
+func (t *StructOfStructsT) Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT {
+ if t == nil { return 0 }
+ return CreateStructOfStructs(builder, t.A.Id, t.A.Distance, t.B.A, t.B.B, t.C.Id, t.C.Distance)
+}
+func (rcv *StructOfStructs) UnPackTo(t *StructOfStructsT) {
+ t.A = rcv.A(nil).UnPack()
+ t.B = rcv.B(nil).UnPack()
+ t.C = rcv.C(nil).UnPack()
+}
+
+func (rcv *StructOfStructs) UnPack() *StructOfStructsT {
+ if rcv == nil { return nil }
+ t := &StructOfStructsT{}
+ rcv.UnPackTo(t)
+ return t
+}
+
+type StructOfStructs struct {
+ _tab flatbuffers.Struct
+}
+
+func (rcv *StructOfStructs) Init(buf []byte, i flatbuffers.UOffsetT) {
+ rcv._tab.Bytes = buf
+ rcv._tab.Pos = i
+}
+
+func (rcv *StructOfStructs) Table() flatbuffers.Table {
+ return rcv._tab.Table
+}
+
+func (rcv *StructOfStructs) A(obj *Ability) *Ability {
+ if obj == nil {
+ obj = new(Ability)
+ }
+ obj.Init(rcv._tab.Bytes, rcv._tab.Pos+0)
+ return obj
+}
+func (rcv *StructOfStructs) B(obj *Test) *Test {
+ if obj == nil {
+ obj = new(Test)
+ }
+ obj.Init(rcv._tab.Bytes, rcv._tab.Pos+8)
+ return obj
+}
+func (rcv *StructOfStructs) C(obj *Ability) *Ability {
+ if obj == nil {
+ obj = new(Ability)
+ }
+ obj.Init(rcv._tab.Bytes, rcv._tab.Pos+12)
+ return obj
+}
+
+func CreateStructOfStructs(builder *flatbuffers.Builder, a_id uint32, a_distance uint32, b_a int16, b_b int8, c_id uint32, c_distance uint32) flatbuffers.UOffsetT {
+ builder.Prep(4, 20)
+ builder.Prep(4, 8)
+ builder.PrependUint32(c_distance)
+ builder.PrependUint32(c_id)
+ builder.Prep(2, 4)
+ builder.Pad(1)
+ builder.PrependInt8(b_b)
+ builder.PrependInt16(b_a)
+ builder.Prep(4, 8)
+ builder.PrependUint32(a_distance)
+ builder.PrependUint32(a_id)
+ return builder.Offset()
+}
diff --git a/tests/MyGame/Example/StructOfStructs.java b/tests/MyGame/Example/StructOfStructs.java
new file mode 100644
index 0000000..424a8a2
--- /dev/null
+++ b/tests/MyGame/Example/StructOfStructs.java
@@ -0,0 +1,71 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+package MyGame.Example;
+
+import java.nio.*;
+import java.lang.*;
+import java.util.*;
+import com.google.flatbuffers.*;
+
+@SuppressWarnings("unused")
+public final class StructOfStructs extends Struct {
+ public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); }
+ public StructOfStructs __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; }
+
+ public MyGame.Example.Ability a() { return a(new MyGame.Example.Ability()); }
+ public MyGame.Example.Ability a(MyGame.Example.Ability obj) { return obj.__assign(bb_pos + 0, bb); }
+ public MyGame.Example.Test b() { return b(new MyGame.Example.Test()); }
+ public MyGame.Example.Test b(MyGame.Example.Test obj) { return obj.__assign(bb_pos + 8, bb); }
+ public MyGame.Example.Ability c() { return c(new MyGame.Example.Ability()); }
+ public MyGame.Example.Ability c(MyGame.Example.Ability obj) { return obj.__assign(bb_pos + 12, bb); }
+
+ public static int createStructOfStructs(FlatBufferBuilder builder, long a_id, long a_distance, short b_a, byte b_b, long c_id, long c_distance) {
+ builder.prep(4, 20);
+ builder.prep(4, 8);
+ builder.putInt((int) c_distance);
+ builder.putInt((int) c_id);
+ builder.prep(2, 4);
+ builder.pad(1);
+ builder.putByte(b_b);
+ builder.putShort(b_a);
+ builder.prep(4, 8);
+ builder.putInt((int) a_distance);
+ builder.putInt((int) a_id);
+ return builder.offset();
+ }
+
+ public static final class Vector extends BaseVector {
+ public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; }
+
+ public StructOfStructs get(int j) { return get(new StructOfStructs(), j); }
+ public StructOfStructs get(StructOfStructs obj, int j) { return obj.__assign(__element(j), bb); }
+ }
+ public StructOfStructsT unpack() {
+ StructOfStructsT _o = new StructOfStructsT();
+ unpackTo(_o);
+ return _o;
+ }
+ public void unpackTo(StructOfStructsT _o) {
+ a().unpackTo(_o.getA());
+ b().unpackTo(_o.getB());
+ c().unpackTo(_o.getC());
+ }
+ public static int pack(FlatBufferBuilder builder, StructOfStructsT _o) {
+ if (_o == null) return 0;
+ int _a_id = _o.getA().getId();
+ int _a_distance = _o.getA().getDistance();
+ short _b_a = _o.getB().getA();
+ byte _b_b = _o.getB().getB();
+ int _c_id = _o.getC().getId();
+ int _c_distance = _o.getC().getDistance();
+ return createStructOfStructs(
+ builder,
+ _a_id,
+ _a_distance,
+ _b_a,
+ _b_b,
+ _c_id,
+ _c_distance);
+ }
+}
+
diff --git a/tests/MyGame/Example/StructOfStructs.kt b/tests/MyGame/Example/StructOfStructs.kt
new file mode 100644
index 0000000..56ab9af
--- /dev/null
+++ b/tests/MyGame/Example/StructOfStructs.kt
@@ -0,0 +1,41 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+package MyGame.Example
+
+import java.nio.*
+import kotlin.math.sign
+import com.google.flatbuffers.*
+
+@Suppress("unused")
+class StructOfStructs : Struct() {
+
+ fun __init(_i: Int, _bb: ByteBuffer) {
+ __reset(_i, _bb)
+ }
+ fun __assign(_i: Int, _bb: ByteBuffer) : StructOfStructs {
+ __init(_i, _bb)
+ return this
+ }
+ val a : MyGame.Example.Ability? get() = a(MyGame.Example.Ability())
+ fun a(obj: MyGame.Example.Ability) : MyGame.Example.Ability? = obj.__assign(bb_pos + 0, bb)
+ val b : MyGame.Example.Test? get() = b(MyGame.Example.Test())
+ fun b(obj: MyGame.Example.Test) : MyGame.Example.Test? = obj.__assign(bb_pos + 8, bb)
+ val c : MyGame.Example.Ability? get() = c(MyGame.Example.Ability())
+ fun c(obj: MyGame.Example.Ability) : MyGame.Example.Ability? = obj.__assign(bb_pos + 12, bb)
+ companion object {
+ fun createStructOfStructs(builder: FlatBufferBuilder, a_id: UInt, a_distance: UInt, b_a: Short, b_b: Byte, c_id: UInt, c_distance: UInt) : Int {
+ builder.prep(4, 20)
+ builder.prep(4, 8)
+ builder.putInt(c_distance.toInt())
+ builder.putInt(c_id.toInt())
+ builder.prep(2, 4)
+ builder.pad(1)
+ builder.putByte(b_b)
+ builder.putShort(b_a)
+ builder.prep(4, 8)
+ builder.putInt(a_distance.toInt())
+ builder.putInt(a_id.toInt())
+ return builder.offset()
+ }
+ }
+}
diff --git a/tests/MyGame/Example/StructOfStructs.lua b/tests/MyGame/Example/StructOfStructs.lua
new file mode 100644
index 0000000..7f56b34
--- /dev/null
+++ b/tests/MyGame/Example/StructOfStructs.lua
@@ -0,0 +1,58 @@
+--[[ MyGame.Example.StructOfStructs
+
+ Automatically generated by the FlatBuffers compiler, do not modify.
+ Or modify. I'm a message, not a cop.
+
+ flatc version: 2.0.6
+
+ Declared by : //monster_test.fbs
+ Rooting type : MyGame.Example.Monster (//monster_test.fbs)
+
+--]]
+
+local flatbuffers = require('flatbuffers')
+
+local StructOfStructs = {}
+local mt = {}
+
+function StructOfStructs.New()
+ local o = {}
+ setmetatable(o, {__index = mt})
+ return o
+end
+
+function mt:Init(buf, pos)
+ self.view = flatbuffers.view.New(buf, pos)
+end
+
+function mt:A(obj)
+ obj:Init(self.view.bytes, self.view.pos + 0)
+ return obj
+end
+
+function mt:B(obj)
+ obj:Init(self.view.bytes, self.view.pos + 8)
+ return obj
+end
+
+function mt:C(obj)
+ obj:Init(self.view.bytes, self.view.pos + 12)
+ return obj
+end
+
+function StructOfStructs.CreateStructOfStructs(builder, a_id, a_distance, b_a, b_b, c_id, c_distance)
+ builder:Prep(4, 20)
+ builder:Prep(4, 8)
+ builder:PrependUint32(c_distance)
+ builder:PrependUint32(c_id)
+ builder:Prep(2, 4)
+ builder:Pad(1)
+ builder:PrependInt8(b_b)
+ builder:PrependInt16(b_a)
+ builder:Prep(4, 8)
+ builder:PrependUint32(a_distance)
+ builder:PrependUint32(a_id)
+ return builder:Offset()
+end
+
+return StructOfStructs
\ No newline at end of file
diff --git a/tests/MyGame/Example/StructOfStructs.php b/tests/MyGame/Example/StructOfStructs.php
new file mode 100644
index 0000000..fe5fac3
--- /dev/null
+++ b/tests/MyGame/Example/StructOfStructs.php
@@ -0,0 +1,74 @@
+<?php
+// automatically generated by the FlatBuffers compiler, do not modify
+
+namespace MyGame\Example;
+
+use \Google\FlatBuffers\Struct;
+use \Google\FlatBuffers\Table;
+use \Google\FlatBuffers\ByteBuffer;
+use \Google\FlatBuffers\FlatBufferBuilder;
+
+class StructOfStructs extends Struct
+{
+ /**
+ * @param int $_i offset
+ * @param ByteBuffer $_bb
+ * @return StructOfStructs
+ **/
+ public function init($_i, ByteBuffer $_bb)
+ {
+ $this->bb_pos = $_i;
+ $this->bb = $_bb;
+ return $this;
+ }
+
+ /**
+ * @return Ability
+ */
+ public function getA()
+ {
+ $obj = new Ability();
+ $obj->init($this->bb_pos + 0, $this->bb);
+ return $obj;
+ }
+
+ /**
+ * @return Test
+ */
+ public function getB()
+ {
+ $obj = new Test();
+ $obj->init($this->bb_pos + 8, $this->bb);
+ return $obj;
+ }
+
+ /**
+ * @return Ability
+ */
+ public function getC()
+ {
+ $obj = new Ability();
+ $obj->init($this->bb_pos + 12, $this->bb);
+ return $obj;
+ }
+
+
+ /**
+ * @return int offset
+ */
+ public static function createStructOfStructs(FlatBufferBuilder $builder, $a_id, $a_distance, $b_a, $b_b, $c_id, $c_distance)
+ {
+ $builder->prep(4, 20);
+ $builder->prep(4, 8);
+ $builder->putUint($c_distance);
+ $builder->putUint($c_id);
+ $builder->prep(2, 4);
+ $builder->pad(1);
+ $builder->putSbyte($b_b);
+ $builder->putShort($b_a);
+ $builder->prep(4, 8);
+ $builder->putUint($a_distance);
+ $builder->putUint($a_id);
+ return $builder->offset();
+ }
+}
diff --git a/tests/MyGame/Example/StructOfStructs.py b/tests/MyGame/Example/StructOfStructs.py
new file mode 100644
index 0000000..0dcf3d5
--- /dev/null
+++ b/tests/MyGame/Example/StructOfStructs.py
@@ -0,0 +1,90 @@
+# automatically generated by the FlatBuffers compiler, do not modify
+
+# namespace: Example
+
+import flatbuffers
+from flatbuffers.compat import import_numpy
+np = import_numpy()
+
+class StructOfStructs(object):
+ __slots__ = ['_tab']
+
+ @classmethod
+ def SizeOf(cls):
+ return 20
+
+ # StructOfStructs
+ def Init(self, buf, pos):
+ self._tab = flatbuffers.table.Table(buf, pos)
+
+ # StructOfStructs
+ def A(self, obj):
+ obj.Init(self._tab.Bytes, self._tab.Pos + 0)
+ return obj
+
+ # StructOfStructs
+ def B(self, obj):
+ obj.Init(self._tab.Bytes, self._tab.Pos + 8)
+ return obj
+
+ # StructOfStructs
+ def C(self, obj):
+ obj.Init(self._tab.Bytes, self._tab.Pos + 12)
+ return obj
+
+
+def CreateStructOfStructs(builder, a_id, a_distance, b_a, b_b, c_id, c_distance):
+ builder.Prep(4, 20)
+ builder.Prep(4, 8)
+ builder.PrependUint32(c_distance)
+ builder.PrependUint32(c_id)
+ builder.Prep(2, 4)
+ builder.Pad(1)
+ builder.PrependInt8(b_b)
+ builder.PrependInt16(b_a)
+ builder.Prep(4, 8)
+ builder.PrependUint32(a_distance)
+ builder.PrependUint32(a_id)
+ return builder.Offset()
+
+import MyGame.Example.Ability
+import MyGame.Example.Test
+try:
+ from typing import Optional
+except:
+ pass
+
+class StructOfStructsT(object):
+
+ # StructOfStructsT
+ def __init__(self):
+ self.a = None # type: Optional[MyGame.Example.Ability.AbilityT]
+ self.b = None # type: Optional[MyGame.Example.Test.TestT]
+ self.c = None # type: Optional[MyGame.Example.Ability.AbilityT]
+
+ @classmethod
+ def InitFromBuf(cls, buf, pos):
+ structOfStructs = StructOfStructs()
+ structOfStructs.Init(buf, pos)
+ return cls.InitFromObj(structOfStructs)
+
+ @classmethod
+ def InitFromObj(cls, structOfStructs):
+ x = StructOfStructsT()
+ x._UnPack(structOfStructs)
+ return x
+
+ # StructOfStructsT
+ def _UnPack(self, structOfStructs):
+ if structOfStructs is None:
+ return
+ if structOfStructs.A(MyGame.Example.Ability.Ability()) is not None:
+ self.a = MyGame.Example.Ability.AbilityT.InitFromObj(structOfStructs.A(MyGame.Example.Ability.Ability()))
+ if structOfStructs.B(MyGame.Example.Test.Test()) is not None:
+ self.b = MyGame.Example.Test.TestT.InitFromObj(structOfStructs.B(MyGame.Example.Test.Test()))
+ if structOfStructs.C(MyGame.Example.Ability.Ability()) is not None:
+ self.c = MyGame.Example.Ability.AbilityT.InitFromObj(structOfStructs.C(MyGame.Example.Ability.Ability()))
+
+ # StructOfStructsT
+ def Pack(self, builder):
+ return CreateStructOfStructs(builder, self.a.id, self.a.distance, self.b.a, self.b.b, self.c.id, self.c.distance)
diff --git a/tests/MyGame/Example/StructOfStructsT.java b/tests/MyGame/Example/StructOfStructsT.java
new file mode 100644
index 0000000..47e337a
--- /dev/null
+++ b/tests/MyGame/Example/StructOfStructsT.java
@@ -0,0 +1,34 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+package MyGame.Example;
+
+import java.nio.*;
+import java.lang.*;
+import java.util.*;
+import com.google.flatbuffers.*;
+
+public class StructOfStructsT {
+ private MyGame.Example.AbilityT a;
+ private MyGame.Example.TestT b;
+ private MyGame.Example.AbilityT c;
+
+ public MyGame.Example.AbilityT getA() { return a; }
+
+ public void setA(MyGame.Example.AbilityT a) { this.a = a; }
+
+ public MyGame.Example.TestT getB() { return b; }
+
+ public void setB(MyGame.Example.TestT b) { this.b = b; }
+
+ public MyGame.Example.AbilityT getC() { return c; }
+
+ public void setC(MyGame.Example.AbilityT c) { this.c = c; }
+
+
+ public StructOfStructsT() {
+ this.a = new MyGame.Example.AbilityT();
+ this.b = new MyGame.Example.TestT();
+ this.c = new MyGame.Example.AbilityT();
+ }
+}
+
diff --git a/tests/MyGame/Example/Test.cs b/tests/MyGame/Example/Test.cs
index a6419ed..a805218 100644
--- a/tests/MyGame/Example/Test.cs
+++ b/tests/MyGame/Example/Test.cs
@@ -44,7 +44,7 @@
_o.A,
_o.B);
}
-};
+}
public class TestT
{
diff --git a/tests/MyGame/Example/Test.java b/tests/MyGame/Example/Test.java
index c4ffc41..ce8f903 100644
--- a/tests/MyGame/Example/Test.java
+++ b/tests/MyGame/Example/Test.java
@@ -31,5 +31,23 @@
public Test get(int j) { return get(new Test(), j); }
public Test get(Test obj, int j) { return obj.__assign(__element(j), bb); }
}
+ public TestT unpack() {
+ TestT _o = new TestT();
+ unpackTo(_o);
+ return _o;
+ }
+ public void unpackTo(TestT _o) {
+ short _oA = a();
+ _o.setA(_oA);
+ byte _oB = b();
+ _o.setB(_oB);
+ }
+ public static int pack(FlatBufferBuilder builder, TestT _o) {
+ if (_o == null) return 0;
+ return createTest(
+ builder,
+ _o.getA(),
+ _o.getB());
+ }
}
diff --git a/tests/MyGame/Example/Test.kt b/tests/MyGame/Example/Test.kt
index f2ceed6..eda5742 100644
--- a/tests/MyGame/Example/Test.kt
+++ b/tests/MyGame/Example/Test.kt
@@ -7,7 +7,6 @@
import com.google.flatbuffers.*
@Suppress("unused")
-@ExperimentalUnsignedTypes
class Test : Struct() {
fun __init(_i: Int, _bb: ByteBuffer) {
diff --git a/tests/MyGame/Example/Test.lua b/tests/MyGame/Example/Test.lua
index 154067b..63b566c 100644
--- a/tests/MyGame/Example/Test.lua
+++ b/tests/MyGame/Example/Test.lua
@@ -1,32 +1,44 @@
--- automatically generated by the FlatBuffers compiler, do not modify
+--[[ MyGame.Example.Test
--- namespace: Example
+ Automatically generated by the FlatBuffers compiler, do not modify.
+ Or modify. I'm a message, not a cop.
+
+ flatc version: 2.0.6
+
+ Declared by : //monster_test.fbs
+ Rooting type : MyGame.Example.Monster (//monster_test.fbs)
+
+--]]
local flatbuffers = require('flatbuffers')
-local Test = {} -- the module
-local Test_mt = {} -- the class metatable
+local Test = {}
+local mt = {}
function Test.New()
- local o = {}
- setmetatable(o, {__index = Test_mt})
- return o
-end
-function Test_mt:Init(buf, pos)
- self.view = flatbuffers.view.New(buf, pos)
-end
-function Test_mt:A()
- return self.view:Get(flatbuffers.N.Int16, self.view.pos + 0)
-end
-function Test_mt:B()
- return self.view:Get(flatbuffers.N.Int8, self.view.pos + 2)
-end
-function Test.CreateTest(builder, a, b)
- builder:Prep(2, 4)
- builder:Pad(1)
- builder:PrependInt8(b)
- builder:PrependInt16(a)
- return builder:Offset()
+ local o = {}
+ setmetatable(o, {__index = mt})
+ return o
end
-return Test -- return the module
\ No newline at end of file
+function mt:Init(buf, pos)
+ self.view = flatbuffers.view.New(buf, pos)
+end
+
+function mt:A()
+ return self.view:Get(flatbuffers.N.Int16, self.view.pos + 0)
+end
+
+function mt:B()
+ return self.view:Get(flatbuffers.N.Int8, self.view.pos + 2)
+end
+
+function Test.CreateTest(builder, a, b)
+ builder:Prep(2, 4)
+ builder:Pad(1)
+ builder:PrependInt8(b)
+ builder:PrependInt16(a)
+ return builder:Offset()
+end
+
+return Test
\ No newline at end of file
diff --git a/tests/MyGame/Example/TestEnum.java b/tests/MyGame/Example/TestEnum.java
index 411bf8e..6330cf6 100644
--- a/tests/MyGame/Example/TestEnum.java
+++ b/tests/MyGame/Example/TestEnum.java
@@ -2,6 +2,7 @@
package MyGame.Example;
+@SuppressWarnings("unused")
public final class TestEnum {
private TestEnum() { }
public static final byte A = 0;
diff --git a/tests/MyGame/Example/TestEnum.py b/tests/MyGame/Example/TestEnum.py
index d49f10a..4f5f608 100644
--- a/tests/MyGame/Example/TestEnum.py
+++ b/tests/MyGame/Example/TestEnum.py
@@ -6,4 +6,3 @@
A = 0
B = 1
C = 2
-
diff --git a/tests/MyGame/Example/TestSimpleTableWithEnum.cs b/tests/MyGame/Example/TestSimpleTableWithEnum.cs
index c8ef08e..99a498b 100644
--- a/tests/MyGame/Example/TestSimpleTableWithEnum.cs
+++ b/tests/MyGame/Example/TestSimpleTableWithEnum.cs
@@ -13,7 +13,7 @@
{
private Table __p;
public ByteBuffer ByteBuffer { get { return __p.bb; } }
- public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_1_12_0(); }
+ public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_2_0_0(); }
public static TestSimpleTableWithEnum GetRootAsTestSimpleTableWithEnum(ByteBuffer _bb) { return GetRootAsTestSimpleTableWithEnum(_bb, new TestSimpleTableWithEnum()); }
public static TestSimpleTableWithEnum GetRootAsTestSimpleTableWithEnum(ByteBuffer _bb, TestSimpleTableWithEnum obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); }
public void __init(int _i, ByteBuffer _bb) { __p = new Table(_i, _bb); }
@@ -49,7 +49,7 @@
builder,
_o.Color);
}
-};
+}
internal partial class TestSimpleTableWithEnumT
{
diff --git a/tests/MyGame/Example/TestSimpleTableWithEnum.java b/tests/MyGame/Example/TestSimpleTableWithEnum.java
index 7e72c22..92d0d69 100644
--- a/tests/MyGame/Example/TestSimpleTableWithEnum.java
+++ b/tests/MyGame/Example/TestSimpleTableWithEnum.java
@@ -9,14 +9,14 @@
@SuppressWarnings("unused")
final class TestSimpleTableWithEnum extends Table {
- public static void ValidateVersion() { Constants.FLATBUFFERS_1_12_0(); }
+ public static void ValidateVersion() { Constants.FLATBUFFERS_2_0_0(); }
public static TestSimpleTableWithEnum getRootAsTestSimpleTableWithEnum(ByteBuffer _bb) { return getRootAsTestSimpleTableWithEnum(_bb, new TestSimpleTableWithEnum()); }
public static TestSimpleTableWithEnum getRootAsTestSimpleTableWithEnum(ByteBuffer _bb, TestSimpleTableWithEnum obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); }
public TestSimpleTableWithEnum __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; }
public int color() { int o = __offset(4); return o != 0 ? bb.get(o + bb_pos) & 0xFF : 2; }
- public boolean mutateColor(int color) { int o = __offset(4); if (o != 0) { bb.put(o + bb_pos, (byte)color); return true; } else { return false; } }
+ public boolean mutateColor(int color) { int o = __offset(4); if (o != 0) { bb.put(o + bb_pos, (byte) color); return true; } else { return false; } }
public static int createTestSimpleTableWithEnum(FlatBufferBuilder builder,
int color) {
@@ -26,7 +26,7 @@
}
public static void startTestSimpleTableWithEnum(FlatBufferBuilder builder) { builder.startTable(1); }
- public static void addColor(FlatBufferBuilder builder, int color) { builder.addByte(0, (byte)color, (byte)2); }
+ public static void addColor(FlatBufferBuilder builder, int color) { builder.addByte(0, (byte) color, (byte) 2); }
public static int endTestSimpleTableWithEnum(FlatBufferBuilder builder) {
int o = builder.endTable();
return o;
@@ -38,5 +38,20 @@
public TestSimpleTableWithEnum get(int j) { return get(new TestSimpleTableWithEnum(), j); }
public TestSimpleTableWithEnum get(TestSimpleTableWithEnum obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); }
}
+ public TestSimpleTableWithEnumT unpack() {
+ TestSimpleTableWithEnumT _o = new TestSimpleTableWithEnumT();
+ unpackTo(_o);
+ return _o;
+ }
+ public void unpackTo(TestSimpleTableWithEnumT _o) {
+ int _oColor = color();
+ _o.setColor(_oColor);
+ }
+ public static int pack(FlatBufferBuilder builder, TestSimpleTableWithEnumT _o) {
+ if (_o == null) return 0;
+ return createTestSimpleTableWithEnum(
+ builder,
+ _o.getColor());
+ }
}
diff --git a/tests/MyGame/Example/TestSimpleTableWithEnum.kt b/tests/MyGame/Example/TestSimpleTableWithEnum.kt
index 125f889..64bf7e2 100644
--- a/tests/MyGame/Example/TestSimpleTableWithEnum.kt
+++ b/tests/MyGame/Example/TestSimpleTableWithEnum.kt
@@ -7,7 +7,6 @@
import com.google.flatbuffers.*
@Suppress("unused")
-@ExperimentalUnsignedTypes
class TestSimpleTableWithEnum : Table() {
fun __init(_i: Int, _bb: ByteBuffer) {
@@ -32,7 +31,7 @@
}
}
companion object {
- fun validateVersion() = Constants.FLATBUFFERS_1_12_0()
+ fun validateVersion() = Constants.FLATBUFFERS_2_0_0()
fun getRootAsTestSimpleTableWithEnum(_bb: ByteBuffer): TestSimpleTableWithEnum = getRootAsTestSimpleTableWithEnum(_bb, TestSimpleTableWithEnum())
fun getRootAsTestSimpleTableWithEnum(_bb: ByteBuffer, obj: TestSimpleTableWithEnum): TestSimpleTableWithEnum {
_bb.order(ByteOrder.LITTLE_ENDIAN)
diff --git a/tests/MyGame/Example/TestSimpleTableWithEnum.lua b/tests/MyGame/Example/TestSimpleTableWithEnum.lua
index 32c8251..000e6e1 100644
--- a/tests/MyGame/Example/TestSimpleTableWithEnum.lua
+++ b/tests/MyGame/Example/TestSimpleTableWithEnum.lua
@@ -1,35 +1,48 @@
--- automatically generated by the FlatBuffers compiler, do not modify
+--[[ MyGame.Example.TestSimpleTableWithEnum
--- namespace: Example
+ Automatically generated by the FlatBuffers compiler, do not modify.
+ Or modify. I'm a message, not a cop.
+
+ flatc version: 2.0.6
+
+ Declared by : //monster_test.fbs
+ Rooting type : MyGame.Example.Monster (//monster_test.fbs)
+
+--]]
local flatbuffers = require('flatbuffers')
-local TestSimpleTableWithEnum = {} -- the module
-local TestSimpleTableWithEnum_mt = {} -- the class metatable
+local TestSimpleTableWithEnum = {}
+local mt = {}
function TestSimpleTableWithEnum.New()
- local o = {}
- setmetatable(o, {__index = TestSimpleTableWithEnum_mt})
- return o
+ local o = {}
+ setmetatable(o, {__index = mt})
+ return o
end
-function TestSimpleTableWithEnum.GetRootAsTestSimpleTableWithEnum(buf, offset)
- local n = flatbuffers.N.UOffsetT:Unpack(buf, offset)
- local o = TestSimpleTableWithEnum.New()
- o:Init(buf, n + offset)
- return o
-end
-function TestSimpleTableWithEnum_mt:Init(buf, pos)
- self.view = flatbuffers.view.New(buf, pos)
-end
-function TestSimpleTableWithEnum_mt:Color()
- local o = self.view:Offset(4)
- if o ~= 0 then
- return self.view:Get(flatbuffers.N.Uint8, o + self.view.pos)
- end
- return 2
-end
-function TestSimpleTableWithEnum.Start(builder) builder:StartObject(1) end
-function TestSimpleTableWithEnum.AddColor(builder, color) builder:PrependUint8Slot(0, color, 2) end
-function TestSimpleTableWithEnum.End(builder) return builder:EndObject() end
-return TestSimpleTableWithEnum -- return the module
\ No newline at end of file
+function mt:Init(buf, pos)
+ self.view = flatbuffers.view.New(buf, pos)
+end
+
+function mt:Color()
+ local o = self.view:Offset(4)
+ if o ~= 0 then
+ return self.view:Get(flatbuffers.N.Uint8, self.view.pos + o)
+ end
+ return 2
+end
+
+function TestSimpleTableWithEnum.Start(builder)
+ builder:StartObject(1)
+end
+
+function TestSimpleTableWithEnum.AddColor(builder, color)
+ builder:PrependUint8Slot(0, color, 2)
+end
+
+function TestSimpleTableWithEnum.End(builder)
+ return builder:EndObject()
+end
+
+return TestSimpleTableWithEnum
\ No newline at end of file
diff --git a/tests/MyGame/Example/TestSimpleTableWithEnum.py b/tests/MyGame/Example/TestSimpleTableWithEnum.py
index d91947a..7f18ed2 100644
--- a/tests/MyGame/Example/TestSimpleTableWithEnum.py
+++ b/tests/MyGame/Example/TestSimpleTableWithEnum.py
@@ -10,13 +10,17 @@
__slots__ = ['_tab']
@classmethod
- def GetRootAsTestSimpleTableWithEnum(cls, buf, offset):
+ def GetRootAs(cls, buf, offset=0):
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
x = TestSimpleTableWithEnum()
x.Init(buf, n + offset)
return x
@classmethod
+ def GetRootAsTestSimpleTableWithEnum(cls, buf, offset=0):
+ """This method is deprecated. Please switch to GetRootAs."""
+ return cls.GetRootAs(buf, offset)
+ @classmethod
def TestSimpleTableWithEnumBufferHasIdentifier(cls, buf, offset, size_prefixed=False):
return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4D\x4F\x4E\x53", size_prefixed=size_prefixed)
@@ -32,9 +36,14 @@
return 2
def TestSimpleTableWithEnumStart(builder): builder.StartObject(1)
+def Start(builder):
+ return TestSimpleTableWithEnumStart(builder)
def TestSimpleTableWithEnumAddColor(builder, color): builder.PrependUint8Slot(0, color, 2)
+def AddColor(builder, color):
+ return TestSimpleTableWithEnumAddColor(builder, color)
def TestSimpleTableWithEnumEnd(builder): return builder.EndObject()
-
+def End(builder):
+ return TestSimpleTableWithEnumEnd(builder)
class TestSimpleTableWithEnumT(object):
diff --git a/tests/MyGame/Example/TestSimpleTableWithEnumT.java b/tests/MyGame/Example/TestSimpleTableWithEnumT.java
new file mode 100644
index 0000000..4bfa90e
--- /dev/null
+++ b/tests/MyGame/Example/TestSimpleTableWithEnumT.java
@@ -0,0 +1,22 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+package MyGame.Example;
+
+import java.nio.*;
+import java.lang.*;
+import java.util.*;
+import com.google.flatbuffers.*;
+
+class TestSimpleTableWithEnumT {
+ private int color;
+
+ public int getColor() { return color; }
+
+ public void setColor(int color) { this.color = color; }
+
+
+ public TestSimpleTableWithEnumT() {
+ this.color = 2;
+ }
+}
+
diff --git a/tests/MyGame/Example/TestT.java b/tests/MyGame/Example/TestT.java
new file mode 100644
index 0000000..e100a4c
--- /dev/null
+++ b/tests/MyGame/Example/TestT.java
@@ -0,0 +1,28 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+package MyGame.Example;
+
+import java.nio.*;
+import java.lang.*;
+import java.util.*;
+import com.google.flatbuffers.*;
+
+public class TestT {
+ private short a;
+ private byte b;
+
+ public short getA() { return a; }
+
+ public void setA(short a) { this.a = a; }
+
+ public byte getB() { return b; }
+
+ public void setB(byte b) { this.b = b; }
+
+
+ public TestT() {
+ this.a = 0;
+ this.b = 0;
+ }
+}
+
diff --git a/tests/MyGame/Example/TypeAliases.cs b/tests/MyGame/Example/TypeAliases.cs
index 79ffb07..1801dc8 100644
--- a/tests/MyGame/Example/TypeAliases.cs
+++ b/tests/MyGame/Example/TypeAliases.cs
@@ -13,7 +13,7 @@
{
private Table __p;
public ByteBuffer ByteBuffer { get { return __p.bb; } }
- public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_1_12_0(); }
+ public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_2_0_0(); }
public static TypeAliases GetRootAsTypeAliases(ByteBuffer _bb) { return GetRootAsTypeAliases(_bb, new TypeAliases()); }
public static TypeAliases GetRootAsTypeAliases(ByteBuffer _bb, TypeAliases obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); }
public void __init(int _i, ByteBuffer _bb) { __p = new Table(_i, _bb); }
@@ -158,7 +158,7 @@
_v8,
_vf64);
}
-};
+}
public class TypeAliasesT
{
diff --git a/tests/MyGame/Example/TypeAliases.java b/tests/MyGame/Example/TypeAliases.java
index 1112658..db757cc 100644
--- a/tests/MyGame/Example/TypeAliases.java
+++ b/tests/MyGame/Example/TypeAliases.java
@@ -9,7 +9,7 @@
@SuppressWarnings("unused")
public final class TypeAliases extends Table {
- public static void ValidateVersion() { Constants.FLATBUFFERS_1_12_0(); }
+ public static void ValidateVersion() { Constants.FLATBUFFERS_2_0_0(); }
public static TypeAliases getRootAsTypeAliases(ByteBuffer _bb) { return getRootAsTypeAliases(_bb, new TypeAliases()); }
public static TypeAliases getRootAsTypeAliases(ByteBuffer _bb, TypeAliases obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); }
@@ -18,15 +18,15 @@
public byte i8() { int o = __offset(4); return o != 0 ? bb.get(o + bb_pos) : 0; }
public boolean mutateI8(byte i8) { int o = __offset(4); if (o != 0) { bb.put(o + bb_pos, i8); return true; } else { return false; } }
public int u8() { int o = __offset(6); return o != 0 ? bb.get(o + bb_pos) & 0xFF : 0; }
- public boolean mutateU8(int u8) { int o = __offset(6); if (o != 0) { bb.put(o + bb_pos, (byte)u8); return true; } else { return false; } }
+ public boolean mutateU8(int u8) { int o = __offset(6); if (o != 0) { bb.put(o + bb_pos, (byte) u8); return true; } else { return false; } }
public short i16() { int o = __offset(8); return o != 0 ? bb.getShort(o + bb_pos) : 0; }
public boolean mutateI16(short i16) { int o = __offset(8); if (o != 0) { bb.putShort(o + bb_pos, i16); return true; } else { return false; } }
public int u16() { int o = __offset(10); return o != 0 ? bb.getShort(o + bb_pos) & 0xFFFF : 0; }
- public boolean mutateU16(int u16) { int o = __offset(10); if (o != 0) { bb.putShort(o + bb_pos, (short)u16); return true; } else { return false; } }
+ public boolean mutateU16(int u16) { int o = __offset(10); if (o != 0) { bb.putShort(o + bb_pos, (short) u16); return true; } else { return false; } }
public int i32() { int o = __offset(12); return o != 0 ? bb.getInt(o + bb_pos) : 0; }
public boolean mutateI32(int i32) { int o = __offset(12); if (o != 0) { bb.putInt(o + bb_pos, i32); return true; } else { return false; } }
public long u32() { int o = __offset(14); return o != 0 ? (long)bb.getInt(o + bb_pos) & 0xFFFFFFFFL : 0L; }
- public boolean mutateU32(long u32) { int o = __offset(14); if (o != 0) { bb.putInt(o + bb_pos, (int)u32); return true; } else { return false; } }
+ public boolean mutateU32(long u32) { int o = __offset(14); if (o != 0) { bb.putInt(o + bb_pos, (int) u32); return true; } else { return false; } }
public long i64() { int o = __offset(16); return o != 0 ? bb.getLong(o + bb_pos) : 0L; }
public boolean mutateI64(long i64) { int o = __offset(16); if (o != 0) { bb.putLong(o + bb_pos, i64); return true; } else { return false; } }
public long u64() { int o = __offset(18); return o != 0 ? bb.getLong(o + bb_pos) : 0L; }
@@ -81,11 +81,11 @@
public static void startTypeAliases(FlatBufferBuilder builder) { builder.startTable(12); }
public static void addI8(FlatBufferBuilder builder, byte i8) { builder.addByte(0, i8, 0); }
- public static void addU8(FlatBufferBuilder builder, int u8) { builder.addByte(1, (byte)u8, (byte)0); }
+ public static void addU8(FlatBufferBuilder builder, int u8) { builder.addByte(1, (byte) u8, (byte) 0); }
public static void addI16(FlatBufferBuilder builder, short i16) { builder.addShort(2, i16, 0); }
- public static void addU16(FlatBufferBuilder builder, int u16) { builder.addShort(3, (short)u16, (short)0); }
+ public static void addU16(FlatBufferBuilder builder, int u16) { builder.addShort(3, (short) u16, (short) 0); }
public static void addI32(FlatBufferBuilder builder, int i32) { builder.addInt(4, i32, 0); }
- public static void addU32(FlatBufferBuilder builder, long u32) { builder.addInt(5, (int)u32, (int)0L); }
+ public static void addU32(FlatBufferBuilder builder, long u32) { builder.addInt(5, (int) u32, (int) 0L); }
public static void addI64(FlatBufferBuilder builder, long i64) { builder.addLong(6, i64, 0L); }
public static void addU64(FlatBufferBuilder builder, long u64) { builder.addLong(7, u64, 0L); }
public static void addF32(FlatBufferBuilder builder, float f32) { builder.addFloat(8, f32, 0.0f); }
@@ -108,5 +108,63 @@
public TypeAliases get(int j) { return get(new TypeAliases(), j); }
public TypeAliases get(TypeAliases obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); }
}
+ public TypeAliasesT unpack() {
+ TypeAliasesT _o = new TypeAliasesT();
+ unpackTo(_o);
+ return _o;
+ }
+ public void unpackTo(TypeAliasesT _o) {
+ byte _oI8 = i8();
+ _o.setI8(_oI8);
+ int _oU8 = u8();
+ _o.setU8(_oU8);
+ short _oI16 = i16();
+ _o.setI16(_oI16);
+ int _oU16 = u16();
+ _o.setU16(_oU16);
+ int _oI32 = i32();
+ _o.setI32(_oI32);
+ long _oU32 = u32();
+ _o.setU32(_oU32);
+ long _oI64 = i64();
+ _o.setI64(_oI64);
+ long _oU64 = u64();
+ _o.setU64(_oU64);
+ float _oF32 = f32();
+ _o.setF32(_oF32);
+ double _oF64 = f64();
+ _o.setF64(_oF64);
+ byte[] _oV8 = new byte[v8Length()];
+ for (int _j = 0; _j < v8Length(); ++_j) {_oV8[_j] = v8(_j);}
+ _o.setV8(_oV8);
+ double[] _oVf64 = new double[vf64Length()];
+ for (int _j = 0; _j < vf64Length(); ++_j) {_oVf64[_j] = vf64(_j);}
+ _o.setVf64(_oVf64);
+ }
+ public static int pack(FlatBufferBuilder builder, TypeAliasesT _o) {
+ if (_o == null) return 0;
+ int _v8 = 0;
+ if (_o.getV8() != null) {
+ _v8 = createV8Vector(builder, _o.getV8());
+ }
+ int _vf64 = 0;
+ if (_o.getVf64() != null) {
+ _vf64 = createVf64Vector(builder, _o.getVf64());
+ }
+ return createTypeAliases(
+ builder,
+ _o.getI8(),
+ _o.getU8(),
+ _o.getI16(),
+ _o.getU16(),
+ _o.getI32(),
+ _o.getU32(),
+ _o.getI64(),
+ _o.getU64(),
+ _o.getF32(),
+ _o.getF64(),
+ _v8,
+ _vf64);
+ }
}
diff --git a/tests/MyGame/Example/TypeAliases.kt b/tests/MyGame/Example/TypeAliases.kt
index d279d14..cdc82b5 100644
--- a/tests/MyGame/Example/TypeAliases.kt
+++ b/tests/MyGame/Example/TypeAliases.kt
@@ -7,7 +7,6 @@
import com.google.flatbuffers.*
@Suppress("unused")
-@ExperimentalUnsignedTypes
class TypeAliases : Table() {
fun __init(_i: Int, _bb: ByteBuffer) {
@@ -204,7 +203,7 @@
}
}
companion object {
- fun validateVersion() = Constants.FLATBUFFERS_1_12_0()
+ fun validateVersion() = Constants.FLATBUFFERS_2_0_0()
fun getRootAsTypeAliases(_bb: ByteBuffer): TypeAliases = getRootAsTypeAliases(_bb, TypeAliases())
fun getRootAsTypeAliases(_bb: ByteBuffer, obj: TypeAliases): TypeAliases {
_bb.order(ByteOrder.LITTLE_ENDIAN)
diff --git a/tests/MyGame/Example/TypeAliases.lua b/tests/MyGame/Example/TypeAliases.lua
index 90f569c..111ae3e 100644
--- a/tests/MyGame/Example/TypeAliases.lua
+++ b/tests/MyGame/Example/TypeAliases.lua
@@ -1,141 +1,210 @@
--- automatically generated by the FlatBuffers compiler, do not modify
+--[[ MyGame.Example.TypeAliases
--- namespace: Example
+ Automatically generated by the FlatBuffers compiler, do not modify.
+ Or modify. I'm a message, not a cop.
+
+ flatc version: 2.0.6
+
+ Declared by : //monster_test.fbs
+ Rooting type : MyGame.Example.Monster (//monster_test.fbs)
+
+--]]
local flatbuffers = require('flatbuffers')
-local TypeAliases = {} -- the module
-local TypeAliases_mt = {} -- the class metatable
+local TypeAliases = {}
+local mt = {}
function TypeAliases.New()
- local o = {}
- setmetatable(o, {__index = TypeAliases_mt})
- return o
+ local o = {}
+ setmetatable(o, {__index = mt})
+ return o
end
-function TypeAliases.GetRootAsTypeAliases(buf, offset)
- local n = flatbuffers.N.UOffsetT:Unpack(buf, offset)
- local o = TypeAliases.New()
- o:Init(buf, n + offset)
- return o
-end
-function TypeAliases_mt:Init(buf, pos)
- self.view = flatbuffers.view.New(buf, pos)
-end
-function TypeAliases_mt:I8()
- local o = self.view:Offset(4)
- if o ~= 0 then
- return self.view:Get(flatbuffers.N.Int8, o + self.view.pos)
- end
- return 0
-end
-function TypeAliases_mt:U8()
- local o = self.view:Offset(6)
- if o ~= 0 then
- return self.view:Get(flatbuffers.N.Uint8, o + self.view.pos)
- end
- return 0
-end
-function TypeAliases_mt:I16()
- local o = self.view:Offset(8)
- if o ~= 0 then
- return self.view:Get(flatbuffers.N.Int16, o + self.view.pos)
- end
- return 0
-end
-function TypeAliases_mt:U16()
- local o = self.view:Offset(10)
- if o ~= 0 then
- return self.view:Get(flatbuffers.N.Uint16, o + self.view.pos)
- end
- return 0
-end
-function TypeAliases_mt:I32()
- local o = self.view:Offset(12)
- if o ~= 0 then
- return self.view:Get(flatbuffers.N.Int32, o + self.view.pos)
- end
- return 0
-end
-function TypeAliases_mt:U32()
- local o = self.view:Offset(14)
- if o ~= 0 then
- return self.view:Get(flatbuffers.N.Uint32, o + self.view.pos)
- end
- return 0
-end
-function TypeAliases_mt:I64()
- local o = self.view:Offset(16)
- if o ~= 0 then
- return self.view:Get(flatbuffers.N.Int64, o + self.view.pos)
- end
- return 0
-end
-function TypeAliases_mt:U64()
- local o = self.view:Offset(18)
- if o ~= 0 then
- return self.view:Get(flatbuffers.N.Uint64, o + self.view.pos)
- end
- return 0
-end
-function TypeAliases_mt:F32()
- local o = self.view:Offset(20)
- if o ~= 0 then
- return self.view:Get(flatbuffers.N.Float32, o + self.view.pos)
- end
- return 0.0
-end
-function TypeAliases_mt:F64()
- local o = self.view:Offset(22)
- if o ~= 0 then
- return self.view:Get(flatbuffers.N.Float64, o + self.view.pos)
- end
- return 0.0
-end
-function TypeAliases_mt:V8(j)
- local o = self.view:Offset(24)
- if o ~= 0 then
- local a = self.view:Vector(o)
- return self.view:Get(flatbuffers.N.Int8, a + ((j-1) * 1))
- end
- return 0
-end
-function TypeAliases_mt:V8Length()
- local o = self.view:Offset(24)
- if o ~= 0 then
- return self.view:VectorLen(o)
- end
- return 0
-end
-function TypeAliases_mt:Vf64(j)
- local o = self.view:Offset(26)
- if o ~= 0 then
- local a = self.view:Vector(o)
- return self.view:Get(flatbuffers.N.Float64, a + ((j-1) * 8))
- end
- return 0
-end
-function TypeAliases_mt:Vf64Length()
- local o = self.view:Offset(26)
- if o ~= 0 then
- return self.view:VectorLen(o)
- end
- return 0
-end
-function TypeAliases.Start(builder) builder:StartObject(12) end
-function TypeAliases.AddI8(builder, i8) builder:PrependInt8Slot(0, i8, 0) end
-function TypeAliases.AddU8(builder, u8) builder:PrependUint8Slot(1, u8, 0) end
-function TypeAliases.AddI16(builder, i16) builder:PrependInt16Slot(2, i16, 0) end
-function TypeAliases.AddU16(builder, u16) builder:PrependUint16Slot(3, u16, 0) end
-function TypeAliases.AddI32(builder, i32) builder:PrependInt32Slot(4, i32, 0) end
-function TypeAliases.AddU32(builder, u32) builder:PrependUint32Slot(5, u32, 0) end
-function TypeAliases.AddI64(builder, i64) builder:PrependInt64Slot(6, i64, 0) end
-function TypeAliases.AddU64(builder, u64) builder:PrependUint64Slot(7, u64, 0) end
-function TypeAliases.AddF32(builder, f32) builder:PrependFloat32Slot(8, f32, 0.0) end
-function TypeAliases.AddF64(builder, f64) builder:PrependFloat64Slot(9, f64, 0.0) end
-function TypeAliases.AddV8(builder, v8) builder:PrependUOffsetTRelativeSlot(10, v8, 0) end
-function TypeAliases.StartV8Vector(builder, numElems) return builder:StartVector(1, numElems, 1) end
-function TypeAliases.AddVf64(builder, vf64) builder:PrependUOffsetTRelativeSlot(11, vf64, 0) end
-function TypeAliases.StartVf64Vector(builder, numElems) return builder:StartVector(8, numElems, 8) end
-function TypeAliases.End(builder) return builder:EndObject() end
-return TypeAliases -- return the module
\ No newline at end of file
+function mt:Init(buf, pos)
+ self.view = flatbuffers.view.New(buf, pos)
+end
+
+function mt:I8()
+ local o = self.view:Offset(4)
+ if o ~= 0 then
+ return self.view:Get(flatbuffers.N.Int8, self.view.pos + o)
+ end
+ return 0
+end
+
+function mt:U8()
+ local o = self.view:Offset(6)
+ if o ~= 0 then
+ return self.view:Get(flatbuffers.N.Uint8, self.view.pos + o)
+ end
+ return 0
+end
+
+function mt:I16()
+ local o = self.view:Offset(8)
+ if o ~= 0 then
+ return self.view:Get(flatbuffers.N.Int16, self.view.pos + o)
+ end
+ return 0
+end
+
+function mt:U16()
+ local o = self.view:Offset(10)
+ if o ~= 0 then
+ return self.view:Get(flatbuffers.N.Uint16, self.view.pos + o)
+ end
+ return 0
+end
+
+function mt:I32()
+ local o = self.view:Offset(12)
+ if o ~= 0 then
+ return self.view:Get(flatbuffers.N.Int32, self.view.pos + o)
+ end
+ return 0
+end
+
+function mt:U32()
+ local o = self.view:Offset(14)
+ if o ~= 0 then
+ return self.view:Get(flatbuffers.N.Uint32, self.view.pos + o)
+ end
+ return 0
+end
+
+function mt:I64()
+ local o = self.view:Offset(16)
+ if o ~= 0 then
+ return self.view:Get(flatbuffers.N.Int64, self.view.pos + o)
+ end
+ return 0
+end
+
+function mt:U64()
+ local o = self.view:Offset(18)
+ if o ~= 0 then
+ return self.view:Get(flatbuffers.N.Uint64, self.view.pos + o)
+ end
+ return 0
+end
+
+function mt:F32()
+ local o = self.view:Offset(20)
+ if o ~= 0 then
+ return self.view:Get(flatbuffers.N.Float32, self.view.pos + o)
+ end
+ return 0.0
+end
+
+function mt:F64()
+ local o = self.view:Offset(22)
+ if o ~= 0 then
+ return self.view:Get(flatbuffers.N.Float64, self.view.pos + o)
+ end
+ return 0.0
+end
+
+function mt:V8(j)
+ local o = self.view:Offset(24)
+ if o ~= 0 then
+ local a = self.view:Vector(o)
+ return self.view:Get(flatbuffers.N.Int8, a + ((j-1) * 1))
+ end
+ return 0
+end
+
+function mt:V8AsString(start, stop)
+ return self.view:VectorAsString(24, start, stop)
+end
+
+function mt:V8Length()
+ local o = self.view:Offset(24)
+ if o ~= 0 then
+ return self.view:VectorLen(o)
+ end
+ return 0
+end
+
+function mt:Vf64(j)
+ local o = self.view:Offset(26)
+ if o ~= 0 then
+ local a = self.view:Vector(o)
+ return self.view:Get(flatbuffers.N.Float64, a + ((j-1) * 8))
+ end
+ return 0
+end
+
+function mt:Vf64Length()
+ local o = self.view:Offset(26)
+ if o ~= 0 then
+ return self.view:VectorLen(o)
+ end
+ return 0
+end
+
+function TypeAliases.Start(builder)
+ builder:StartObject(12)
+end
+
+function TypeAliases.AddI8(builder, i8)
+ builder:PrependInt8Slot(0, i8, 0)
+end
+
+function TypeAliases.AddU8(builder, u8)
+ builder:PrependUint8Slot(1, u8, 0)
+end
+
+function TypeAliases.AddI16(builder, i16)
+ builder:PrependInt16Slot(2, i16, 0)
+end
+
+function TypeAliases.AddU16(builder, u16)
+ builder:PrependUint16Slot(3, u16, 0)
+end
+
+function TypeAliases.AddI32(builder, i32)
+ builder:PrependInt32Slot(4, i32, 0)
+end
+
+function TypeAliases.AddU32(builder, u32)
+ builder:PrependUint32Slot(5, u32, 0)
+end
+
+function TypeAliases.AddI64(builder, i64)
+ builder:PrependInt64Slot(6, i64, 0)
+end
+
+function TypeAliases.AddU64(builder, u64)
+ builder:PrependUint64Slot(7, u64, 0)
+end
+
+function TypeAliases.AddF32(builder, f32)
+ builder:PrependFloat32Slot(8, f32, 0.0)
+end
+
+function TypeAliases.AddF64(builder, f64)
+ builder:PrependFloat64Slot(9, f64, 0.0)
+end
+
+function TypeAliases.AddV8(builder, v8)
+ builder:PrependUOffsetTRelativeSlot(10, v8, 0)
+end
+
+function TypeAliases.StartV8Vector(builder, numElems)
+ return builder:StartVector(1, numElems, 1)
+end
+
+function TypeAliases.AddVf64(builder, vf64)
+ builder:PrependUOffsetTRelativeSlot(11, vf64, 0)
+end
+
+function TypeAliases.StartVf64Vector(builder, numElems)
+ return builder:StartVector(8, numElems, 8)
+end
+
+function TypeAliases.End(builder)
+ return builder:EndObject()
+end
+
+return TypeAliases
\ No newline at end of file
diff --git a/tests/MyGame/Example/TypeAliases.py b/tests/MyGame/Example/TypeAliases.py
index 0567212..8b0ea19 100644
--- a/tests/MyGame/Example/TypeAliases.py
+++ b/tests/MyGame/Example/TypeAliases.py
@@ -10,13 +10,17 @@
__slots__ = ['_tab']
@classmethod
- def GetRootAsTypeAliases(cls, buf, offset):
+ def GetRootAs(cls, buf, offset=0):
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
x = TypeAliases()
x.Init(buf, n + offset)
return x
@classmethod
+ def GetRootAsTypeAliases(cls, buf, offset=0):
+ """This method is deprecated. Please switch to GetRootAs."""
+ return cls.GetRootAs(buf, offset)
+ @classmethod
def TypeAliasesBufferHasIdentifier(cls, buf, offset, size_prefixed=False):
return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4D\x4F\x4E\x53", size_prefixed=size_prefixed)
@@ -149,22 +153,53 @@
return o == 0
def TypeAliasesStart(builder): builder.StartObject(12)
+def Start(builder):
+ return TypeAliasesStart(builder)
def TypeAliasesAddI8(builder, i8): builder.PrependInt8Slot(0, i8, 0)
+def AddI8(builder, i8):
+ return TypeAliasesAddI8(builder, i8)
def TypeAliasesAddU8(builder, u8): builder.PrependUint8Slot(1, u8, 0)
+def AddU8(builder, u8):
+ return TypeAliasesAddU8(builder, u8)
def TypeAliasesAddI16(builder, i16): builder.PrependInt16Slot(2, i16, 0)
+def AddI16(builder, i16):
+ return TypeAliasesAddI16(builder, i16)
def TypeAliasesAddU16(builder, u16): builder.PrependUint16Slot(3, u16, 0)
+def AddU16(builder, u16):
+ return TypeAliasesAddU16(builder, u16)
def TypeAliasesAddI32(builder, i32): builder.PrependInt32Slot(4, i32, 0)
+def AddI32(builder, i32):
+ return TypeAliasesAddI32(builder, i32)
def TypeAliasesAddU32(builder, u32): builder.PrependUint32Slot(5, u32, 0)
+def AddU32(builder, u32):
+ return TypeAliasesAddU32(builder, u32)
def TypeAliasesAddI64(builder, i64): builder.PrependInt64Slot(6, i64, 0)
+def AddI64(builder, i64):
+ return TypeAliasesAddI64(builder, i64)
def TypeAliasesAddU64(builder, u64): builder.PrependUint64Slot(7, u64, 0)
+def AddU64(builder, u64):
+ return TypeAliasesAddU64(builder, u64)
def TypeAliasesAddF32(builder, f32): builder.PrependFloat32Slot(8, f32, 0.0)
+def AddF32(builder, f32):
+ return TypeAliasesAddF32(builder, f32)
def TypeAliasesAddF64(builder, f64): builder.PrependFloat64Slot(9, f64, 0.0)
+def AddF64(builder, f64):
+ return TypeAliasesAddF64(builder, f64)
def TypeAliasesAddV8(builder, v8): builder.PrependUOffsetTRelativeSlot(10, flatbuffers.number_types.UOffsetTFlags.py_type(v8), 0)
+def AddV8(builder, v8):
+ return TypeAliasesAddV8(builder, v8)
def TypeAliasesStartV8Vector(builder, numElems): return builder.StartVector(1, numElems, 1)
+def StartV8Vector(builder, numElems):
+ return TypeAliasesStartV8Vector(builder, numElems)
def TypeAliasesAddVf64(builder, vf64): builder.PrependUOffsetTRelativeSlot(11, flatbuffers.number_types.UOffsetTFlags.py_type(vf64), 0)
+def AddVf64(builder, vf64):
+ return TypeAliasesAddVf64(builder, vf64)
def TypeAliasesStartVf64Vector(builder, numElems): return builder.StartVector(8, numElems, 8)
+def StartVf64Vector(builder, numElems):
+ return TypeAliasesStartVf64Vector(builder, numElems)
def TypeAliasesEnd(builder): return builder.EndObject()
-
+def End(builder):
+ return TypeAliasesEnd(builder)
try:
from typing import List
except:
@@ -237,7 +272,7 @@
TypeAliasesStartV8Vector(builder, len(self.v8))
for i in reversed(range(len(self.v8))):
builder.PrependByte(self.v8[i])
- v8 = builder.EndVector(len(self.v8))
+ v8 = builder.EndVector()
if self.vf64 is not None:
if np is not None and type(self.vf64) is np.ndarray:
vf64 = builder.CreateNumpyVector(self.vf64)
@@ -245,7 +280,7 @@
TypeAliasesStartVf64Vector(builder, len(self.vf64))
for i in reversed(range(len(self.vf64))):
builder.PrependFloat64(self.vf64[i])
- vf64 = builder.EndVector(len(self.vf64))
+ vf64 = builder.EndVector()
TypeAliasesStart(builder)
TypeAliasesAddI8(builder, self.i8)
TypeAliasesAddU8(builder, self.u8)
diff --git a/tests/MyGame/Example/TypeAliasesT.java b/tests/MyGame/Example/TypeAliasesT.java
new file mode 100644
index 0000000..3b07956
--- /dev/null
+++ b/tests/MyGame/Example/TypeAliasesT.java
@@ -0,0 +1,88 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+package MyGame.Example;
+
+import java.nio.*;
+import java.lang.*;
+import java.util.*;
+import com.google.flatbuffers.*;
+
+public class TypeAliasesT {
+ private byte i8;
+ private int u8;
+ private short i16;
+ private int u16;
+ private int i32;
+ private long u32;
+ private long i64;
+ private long u64;
+ private float f32;
+ private double f64;
+ private byte[] v8;
+ private double[] vf64;
+
+ public byte getI8() { return i8; }
+
+ public void setI8(byte i8) { this.i8 = i8; }
+
+ public int getU8() { return u8; }
+
+ public void setU8(int u8) { this.u8 = u8; }
+
+ public short getI16() { return i16; }
+
+ public void setI16(short i16) { this.i16 = i16; }
+
+ public int getU16() { return u16; }
+
+ public void setU16(int u16) { this.u16 = u16; }
+
+ public int getI32() { return i32; }
+
+ public void setI32(int i32) { this.i32 = i32; }
+
+ public long getU32() { return u32; }
+
+ public void setU32(long u32) { this.u32 = u32; }
+
+ public long getI64() { return i64; }
+
+ public void setI64(long i64) { this.i64 = i64; }
+
+ public long getU64() { return u64; }
+
+ public void setU64(long u64) { this.u64 = u64; }
+
+ public float getF32() { return f32; }
+
+ public void setF32(float f32) { this.f32 = f32; }
+
+ public double getF64() { return f64; }
+
+ public void setF64(double f64) { this.f64 = f64; }
+
+ public byte[] getV8() { return v8; }
+
+ public void setV8(byte[] v8) { this.v8 = v8; }
+
+ public double[] getVf64() { return vf64; }
+
+ public void setVf64(double[] vf64) { this.vf64 = vf64; }
+
+
+ public TypeAliasesT() {
+ this.i8 = 0;
+ this.u8 = 0;
+ this.i16 = 0;
+ this.u16 = 0;
+ this.i32 = 0;
+ this.u32 = 0L;
+ this.i64 = 0L;
+ this.u64 = 0L;
+ this.f32 = 0.0f;
+ this.f64 = 0.0;
+ this.v8 = null;
+ this.vf64 = null;
+ }
+}
+
diff --git a/tests/MyGame/Example/Vec3.cs b/tests/MyGame/Example/Vec3.cs
index 54fc8f9..31c9f7e 100644
--- a/tests/MyGame/Example/Vec3.cs
+++ b/tests/MyGame/Example/Vec3.cs
@@ -71,7 +71,7 @@
_test3_a,
_test3_b);
}
-};
+}
public class Vec3T
{
diff --git a/tests/MyGame/Example/Vec3.java b/tests/MyGame/Example/Vec3.java
index 89d38a1..62ef331 100644
--- a/tests/MyGame/Example/Vec3.java
+++ b/tests/MyGame/Example/Vec3.java
@@ -21,7 +21,7 @@
public double test1() { return bb.getDouble(bb_pos + 16); }
public void mutateTest1(double test1) { bb.putDouble(bb_pos + 16, test1); }
public int test2() { return bb.get(bb_pos + 24) & 0xFF; }
- public void mutateTest2(int test2) { bb.put(bb_pos + 24, (byte)test2); }
+ public void mutateTest2(int test2) { bb.put(bb_pos + 24, (byte) test2); }
public MyGame.Example.Test test3() { return test3(new MyGame.Example.Test()); }
public MyGame.Example.Test test3(MyGame.Example.Test obj) { return obj.__assign(bb_pos + 26, bb); }
@@ -33,7 +33,7 @@
builder.putByte(test3_b);
builder.putShort(test3_a);
builder.pad(1);
- builder.putByte((byte)test2);
+ builder.putByte((byte) test2);
builder.putDouble(test1);
builder.pad(4);
builder.putFloat(z);
@@ -48,5 +48,37 @@
public Vec3 get(int j) { return get(new Vec3(), j); }
public Vec3 get(Vec3 obj, int j) { return obj.__assign(__element(j), bb); }
}
+ public Vec3T unpack() {
+ Vec3T _o = new Vec3T();
+ unpackTo(_o);
+ return _o;
+ }
+ public void unpackTo(Vec3T _o) {
+ float _oX = x();
+ _o.setX(_oX);
+ float _oY = y();
+ _o.setY(_oY);
+ float _oZ = z();
+ _o.setZ(_oZ);
+ double _oTest1 = test1();
+ _o.setTest1(_oTest1);
+ int _oTest2 = test2();
+ _o.setTest2(_oTest2);
+ test3().unpackTo(_o.getTest3());
+ }
+ public static int pack(FlatBufferBuilder builder, Vec3T _o) {
+ if (_o == null) return 0;
+ short _test3_a = _o.getTest3().getA();
+ byte _test3_b = _o.getTest3().getB();
+ return createVec3(
+ builder,
+ _o.getX(),
+ _o.getY(),
+ _o.getZ(),
+ _o.getTest1(),
+ _o.getTest2(),
+ _test3_a,
+ _test3_b);
+ }
}
diff --git a/tests/MyGame/Example/Vec3.kt b/tests/MyGame/Example/Vec3.kt
index 90f1b4a..445601c 100644
--- a/tests/MyGame/Example/Vec3.kt
+++ b/tests/MyGame/Example/Vec3.kt
@@ -7,7 +7,6 @@
import com.google.flatbuffers.*
@Suppress("unused")
-@ExperimentalUnsignedTypes
class Vec3 : Struct() {
fun __init(_i: Int, _bb: ByteBuffer) {
diff --git a/tests/MyGame/Example/Vec3.lua b/tests/MyGame/Example/Vec3.lua
index 24d4cc1..ef51051 100644
--- a/tests/MyGame/Example/Vec3.lua
+++ b/tests/MyGame/Example/Vec3.lua
@@ -1,54 +1,70 @@
--- automatically generated by the FlatBuffers compiler, do not modify
+--[[ MyGame.Example.Vec3
--- namespace: Example
+ Automatically generated by the FlatBuffers compiler, do not modify.
+ Or modify. I'm a message, not a cop.
+
+ flatc version: 2.0.6
+
+ Declared by : //monster_test.fbs
+ Rooting type : MyGame.Example.Monster (//monster_test.fbs)
+
+--]]
local flatbuffers = require('flatbuffers')
-local Vec3 = {} -- the module
-local Vec3_mt = {} -- the class metatable
+local Vec3 = {}
+local mt = {}
function Vec3.New()
- local o = {}
- setmetatable(o, {__index = Vec3_mt})
- return o
-end
-function Vec3_mt:Init(buf, pos)
- self.view = flatbuffers.view.New(buf, pos)
-end
-function Vec3_mt:X()
- return self.view:Get(flatbuffers.N.Float32, self.view.pos + 0)
-end
-function Vec3_mt:Y()
- return self.view:Get(flatbuffers.N.Float32, self.view.pos + 4)
-end
-function Vec3_mt:Z()
- return self.view:Get(flatbuffers.N.Float32, self.view.pos + 8)
-end
-function Vec3_mt:Test1()
- return self.view:Get(flatbuffers.N.Float64, self.view.pos + 16)
-end
-function Vec3_mt:Test2()
- return self.view:Get(flatbuffers.N.Uint8, self.view.pos + 24)
-end
-function Vec3_mt:Test3(obj)
- obj:Init(self.view.bytes, self.view.pos + 26)
- return obj
-end
-function Vec3.CreateVec3(builder, x, y, z, test1, test2, test3_a, test3_b)
- builder:Prep(8, 32)
- builder:Pad(2)
- builder:Prep(2, 4)
- builder:Pad(1)
- builder:PrependInt8(test3_b)
- builder:PrependInt16(test3_a)
- builder:Pad(1)
- builder:PrependUint8(test2)
- builder:PrependFloat64(test1)
- builder:Pad(4)
- builder:PrependFloat32(z)
- builder:PrependFloat32(y)
- builder:PrependFloat32(x)
- return builder:Offset()
+ local o = {}
+ setmetatable(o, {__index = mt})
+ return o
end
-return Vec3 -- return the module
\ No newline at end of file
+function mt:Init(buf, pos)
+ self.view = flatbuffers.view.New(buf, pos)
+end
+
+function mt:X()
+ return self.view:Get(flatbuffers.N.Float32, self.view.pos + 0)
+end
+
+function mt:Y()
+ return self.view:Get(flatbuffers.N.Float32, self.view.pos + 4)
+end
+
+function mt:Z()
+ return self.view:Get(flatbuffers.N.Float32, self.view.pos + 8)
+end
+
+function mt:Test1()
+ return self.view:Get(flatbuffers.N.Float64, self.view.pos + 16)
+end
+
+function mt:Test2()
+ return self.view:Get(flatbuffers.N.Uint8, self.view.pos + 24)
+end
+
+function mt:Test3(obj)
+ obj:Init(self.view.bytes, self.view.pos + 26)
+ return obj
+end
+
+function Vec3.CreateVec3(builder, x, y, z, test1, test2, test3_a, test3_b)
+ builder:Prep(8, 32)
+ builder:Pad(2)
+ builder:Prep(2, 4)
+ builder:Pad(1)
+ builder:PrependInt8(test3_b)
+ builder:PrependInt16(test3_a)
+ builder:Pad(1)
+ builder:PrependUint8(test2)
+ builder:PrependFloat64(test1)
+ builder:Pad(4)
+ builder:PrependFloat32(z)
+ builder:PrependFloat32(y)
+ builder:PrependFloat32(x)
+ return builder:Offset()
+end
+
+return Vec3
\ No newline at end of file
diff --git a/tests/MyGame/Example/Vec3T.java b/tests/MyGame/Example/Vec3T.java
new file mode 100644
index 0000000..8728e3a
--- /dev/null
+++ b/tests/MyGame/Example/Vec3T.java
@@ -0,0 +1,52 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+package MyGame.Example;
+
+import java.nio.*;
+import java.lang.*;
+import java.util.*;
+import com.google.flatbuffers.*;
+
+public class Vec3T {
+ private float x;
+ private float y;
+ private float z;
+ private double test1;
+ private int test2;
+ private MyGame.Example.TestT test3;
+
+ public float getX() { return x; }
+
+ public void setX(float x) { this.x = x; }
+
+ public float getY() { return y; }
+
+ public void setY(float y) { this.y = y; }
+
+ public float getZ() { return z; }
+
+ public void setZ(float z) { this.z = z; }
+
+ public double getTest1() { return test1; }
+
+ public void setTest1(double test1) { this.test1 = test1; }
+
+ public int getTest2() { return test2; }
+
+ public void setTest2(int test2) { this.test2 = test2; }
+
+ public MyGame.Example.TestT getTest3() { return test3; }
+
+ public void setTest3(MyGame.Example.TestT test3) { this.test3 = test3; }
+
+
+ public Vec3T() {
+ this.x = 0.0f;
+ this.y = 0.0f;
+ this.z = 0.0f;
+ this.test1 = 0.0;
+ this.test2 = 0;
+ this.test3 = new MyGame.Example.TestT();
+ }
+}
+
diff --git a/tests/MyGame/Example2/Monster.cs b/tests/MyGame/Example2/Monster.cs
index 3291ee8..3232bd6 100644
--- a/tests/MyGame/Example2/Monster.cs
+++ b/tests/MyGame/Example2/Monster.cs
@@ -13,7 +13,7 @@
{
private Table __p;
public ByteBuffer ByteBuffer { get { return __p.bb; } }
- public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_1_12_0(); }
+ public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_2_0_0(); }
public static Monster GetRootAsMonster(ByteBuffer _bb) { return GetRootAsMonster(_bb, new Monster()); }
public static Monster GetRootAsMonster(ByteBuffer _bb, Monster obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); }
public void __init(int _i, ByteBuffer _bb) { __p = new Table(_i, _bb); }
@@ -37,7 +37,7 @@
StartMonster(builder);
return EndMonster(builder);
}
-};
+}
public class MonsterT
{
diff --git a/tests/MyGame/Example2/Monster.java b/tests/MyGame/Example2/Monster.java
index 950c427..6323def 100644
--- a/tests/MyGame/Example2/Monster.java
+++ b/tests/MyGame/Example2/Monster.java
@@ -9,7 +9,7 @@
@SuppressWarnings("unused")
public final class Monster extends Table {
- public static void ValidateVersion() { Constants.FLATBUFFERS_1_12_0(); }
+ public static void ValidateVersion() { Constants.FLATBUFFERS_2_0_0(); }
public static Monster getRootAsMonster(ByteBuffer _bb) { return getRootAsMonster(_bb, new Monster()); }
public static Monster getRootAsMonster(ByteBuffer _bb, Monster obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); }
@@ -28,5 +28,17 @@
public Monster get(int j) { return get(new Monster(), j); }
public Monster get(Monster obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); }
}
+ public MonsterT unpack() {
+ MonsterT _o = new MonsterT();
+ unpackTo(_o);
+ return _o;
+ }
+ public void unpackTo(MonsterT _o) {
+ }
+ public static int pack(FlatBufferBuilder builder, MonsterT _o) {
+ if (_o == null) return 0;
+ startMonster(builder);
+ return endMonster(builder);
+ }
}
diff --git a/tests/MyGame/Example2/Monster.kt b/tests/MyGame/Example2/Monster.kt
index f1df2e0..88b9d05 100644
--- a/tests/MyGame/Example2/Monster.kt
+++ b/tests/MyGame/Example2/Monster.kt
@@ -7,7 +7,6 @@
import com.google.flatbuffers.*
@Suppress("unused")
-@ExperimentalUnsignedTypes
class Monster : Table() {
fun __init(_i: Int, _bb: ByteBuffer) {
@@ -18,7 +17,7 @@
return this
}
companion object {
- fun validateVersion() = Constants.FLATBUFFERS_1_12_0()
+ fun validateVersion() = Constants.FLATBUFFERS_2_0_0()
fun getRootAsMonster(_bb: ByteBuffer): Monster = getRootAsMonster(_bb, Monster())
fun getRootAsMonster(_bb: ByteBuffer, obj: Monster): Monster {
_bb.order(ByteOrder.LITTLE_ENDIAN)
diff --git a/tests/MyGame/Example2/Monster.lua b/tests/MyGame/Example2/Monster.lua
index 347b5db..9c33904 100644
--- a/tests/MyGame/Example2/Monster.lua
+++ b/tests/MyGame/Example2/Monster.lua
@@ -1,27 +1,36 @@
--- automatically generated by the FlatBuffers compiler, do not modify
+--[[ MyGame.Example2.Monster
--- namespace: Example2
+ Automatically generated by the FlatBuffers compiler, do not modify.
+ Or modify. I'm a message, not a cop.
+
+ flatc version: 2.0.6
+
+ Declared by : //monster_test.fbs
+ Rooting type : MyGame.Example.Monster (//monster_test.fbs)
+
+--]]
local flatbuffers = require('flatbuffers')
-local Monster = {} -- the module
-local Monster_mt = {} -- the class metatable
+local Monster = {}
+local mt = {}
function Monster.New()
- local o = {}
- setmetatable(o, {__index = Monster_mt})
- return o
+ local o = {}
+ setmetatable(o, {__index = mt})
+ return o
end
-function Monster.GetRootAsMonster(buf, offset)
- local n = flatbuffers.N.UOffsetT:Unpack(buf, offset)
- local o = Monster.New()
- o:Init(buf, n + offset)
- return o
-end
-function Monster_mt:Init(buf, pos)
- self.view = flatbuffers.view.New(buf, pos)
-end
-function Monster.Start(builder) builder:StartObject(0) end
-function Monster.End(builder) return builder:EndObject() end
-return Monster -- return the module
\ No newline at end of file
+function mt:Init(buf, pos)
+ self.view = flatbuffers.view.New(buf, pos)
+end
+
+function Monster.Start(builder)
+ builder:StartObject(0)
+end
+
+function Monster.End(builder)
+ return builder:EndObject()
+end
+
+return Monster
\ No newline at end of file
diff --git a/tests/MyGame/Example2/Monster.py b/tests/MyGame/Example2/Monster.py
index 538b035..893ea9b 100644
--- a/tests/MyGame/Example2/Monster.py
+++ b/tests/MyGame/Example2/Monster.py
@@ -10,13 +10,17 @@
__slots__ = ['_tab']
@classmethod
- def GetRootAsMonster(cls, buf, offset):
+ def GetRootAs(cls, buf, offset=0):
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
x = Monster()
x.Init(buf, n + offset)
return x
@classmethod
+ def GetRootAsMonster(cls, buf, offset=0):
+ """This method is deprecated. Please switch to GetRootAs."""
+ return cls.GetRootAs(buf, offset)
+ @classmethod
def MonsterBufferHasIdentifier(cls, buf, offset, size_prefixed=False):
return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4D\x4F\x4E\x53", size_prefixed=size_prefixed)
@@ -25,8 +29,11 @@
self._tab = flatbuffers.table.Table(buf, pos)
def MonsterStart(builder): builder.StartObject(0)
+def Start(builder):
+ return MonsterStart(builder)
def MonsterEnd(builder): return builder.EndObject()
-
+def End(builder):
+ return MonsterEnd(builder)
class MonsterT(object):
diff --git a/tests/MyGame/Example2/MonsterT.java b/tests/MyGame/Example2/MonsterT.java
new file mode 100644
index 0000000..2939f9b
--- /dev/null
+++ b/tests/MyGame/Example2/MonsterT.java
@@ -0,0 +1,16 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+package MyGame.Example2;
+
+import java.nio.*;
+import java.lang.*;
+import java.util.*;
+import com.google.flatbuffers.*;
+
+public class MonsterT {
+
+
+ public MonsterT() {
+ }
+}
+
diff --git a/tests/MyGame/InParentNamespace.cs b/tests/MyGame/InParentNamespace.cs
index efefa34..b266aae 100644
--- a/tests/MyGame/InParentNamespace.cs
+++ b/tests/MyGame/InParentNamespace.cs
@@ -13,7 +13,7 @@
{
private Table __p;
public ByteBuffer ByteBuffer { get { return __p.bb; } }
- public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_1_12_0(); }
+ public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_2_0_0(); }
public static InParentNamespace GetRootAsInParentNamespace(ByteBuffer _bb) { return GetRootAsInParentNamespace(_bb, new InParentNamespace()); }
public static InParentNamespace GetRootAsInParentNamespace(ByteBuffer _bb, InParentNamespace obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); }
public void __init(int _i, ByteBuffer _bb) { __p = new Table(_i, _bb); }
@@ -37,7 +37,7 @@
StartInParentNamespace(builder);
return EndInParentNamespace(builder);
}
-};
+}
public class InParentNamespaceT
{
diff --git a/tests/MyGame/InParentNamespace.java b/tests/MyGame/InParentNamespace.java
index 20a1ea8..a3e6819 100644
--- a/tests/MyGame/InParentNamespace.java
+++ b/tests/MyGame/InParentNamespace.java
@@ -9,7 +9,7 @@
@SuppressWarnings("unused")
public final class InParentNamespace extends Table {
- public static void ValidateVersion() { Constants.FLATBUFFERS_1_12_0(); }
+ public static void ValidateVersion() { Constants.FLATBUFFERS_2_0_0(); }
public static InParentNamespace getRootAsInParentNamespace(ByteBuffer _bb) { return getRootAsInParentNamespace(_bb, new InParentNamespace()); }
public static InParentNamespace getRootAsInParentNamespace(ByteBuffer _bb, InParentNamespace obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); }
@@ -28,5 +28,17 @@
public InParentNamespace get(int j) { return get(new InParentNamespace(), j); }
public InParentNamespace get(InParentNamespace obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); }
}
+ public InParentNamespaceT unpack() {
+ InParentNamespaceT _o = new InParentNamespaceT();
+ unpackTo(_o);
+ return _o;
+ }
+ public void unpackTo(InParentNamespaceT _o) {
+ }
+ public static int pack(FlatBufferBuilder builder, InParentNamespaceT _o) {
+ if (_o == null) return 0;
+ startInParentNamespace(builder);
+ return endInParentNamespace(builder);
+ }
}
diff --git a/tests/MyGame/InParentNamespace.kt b/tests/MyGame/InParentNamespace.kt
index 02f078e..beb414a 100644
--- a/tests/MyGame/InParentNamespace.kt
+++ b/tests/MyGame/InParentNamespace.kt
@@ -7,7 +7,6 @@
import com.google.flatbuffers.*
@Suppress("unused")
-@ExperimentalUnsignedTypes
class InParentNamespace : Table() {
fun __init(_i: Int, _bb: ByteBuffer) {
@@ -18,7 +17,7 @@
return this
}
companion object {
- fun validateVersion() = Constants.FLATBUFFERS_1_12_0()
+ fun validateVersion() = Constants.FLATBUFFERS_2_0_0()
fun getRootAsInParentNamespace(_bb: ByteBuffer): InParentNamespace = getRootAsInParentNamespace(_bb, InParentNamespace())
fun getRootAsInParentNamespace(_bb: ByteBuffer, obj: InParentNamespace): InParentNamespace {
_bb.order(ByteOrder.LITTLE_ENDIAN)
diff --git a/tests/MyGame/InParentNamespace.lua b/tests/MyGame/InParentNamespace.lua
index b3fa0c8..8112c25 100644
--- a/tests/MyGame/InParentNamespace.lua
+++ b/tests/MyGame/InParentNamespace.lua
@@ -1,27 +1,36 @@
--- automatically generated by the FlatBuffers compiler, do not modify
+--[[ MyGame.InParentNamespace
--- namespace: MyGame
+ Automatically generated by the FlatBuffers compiler, do not modify.
+ Or modify. I'm a message, not a cop.
+
+ flatc version: 2.0.6
+
+ Declared by : //monster_test.fbs
+ Rooting type : MyGame.Example.Monster (//monster_test.fbs)
+
+--]]
local flatbuffers = require('flatbuffers')
-local InParentNamespace = {} -- the module
-local InParentNamespace_mt = {} -- the class metatable
+local InParentNamespace = {}
+local mt = {}
function InParentNamespace.New()
- local o = {}
- setmetatable(o, {__index = InParentNamespace_mt})
- return o
+ local o = {}
+ setmetatable(o, {__index = mt})
+ return o
end
-function InParentNamespace.GetRootAsInParentNamespace(buf, offset)
- local n = flatbuffers.N.UOffsetT:Unpack(buf, offset)
- local o = InParentNamespace.New()
- o:Init(buf, n + offset)
- return o
-end
-function InParentNamespace_mt:Init(buf, pos)
- self.view = flatbuffers.view.New(buf, pos)
-end
-function InParentNamespace.Start(builder) builder:StartObject(0) end
-function InParentNamespace.End(builder) return builder:EndObject() end
-return InParentNamespace -- return the module
\ No newline at end of file
+function mt:Init(buf, pos)
+ self.view = flatbuffers.view.New(buf, pos)
+end
+
+function InParentNamespace.Start(builder)
+ builder:StartObject(0)
+end
+
+function InParentNamespace.End(builder)
+ return builder:EndObject()
+end
+
+return InParentNamespace
\ No newline at end of file
diff --git a/tests/MyGame/InParentNamespace.py b/tests/MyGame/InParentNamespace.py
index e78ea6a..197072b 100644
--- a/tests/MyGame/InParentNamespace.py
+++ b/tests/MyGame/InParentNamespace.py
@@ -10,13 +10,17 @@
__slots__ = ['_tab']
@classmethod
- def GetRootAsInParentNamespace(cls, buf, offset):
+ def GetRootAs(cls, buf, offset=0):
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
x = InParentNamespace()
x.Init(buf, n + offset)
return x
@classmethod
+ def GetRootAsInParentNamespace(cls, buf, offset=0):
+ """This method is deprecated. Please switch to GetRootAs."""
+ return cls.GetRootAs(buf, offset)
+ @classmethod
def InParentNamespaceBufferHasIdentifier(cls, buf, offset, size_prefixed=False):
return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4D\x4F\x4E\x53", size_prefixed=size_prefixed)
@@ -25,8 +29,11 @@
self._tab = flatbuffers.table.Table(buf, pos)
def InParentNamespaceStart(builder): builder.StartObject(0)
+def Start(builder):
+ return InParentNamespaceStart(builder)
def InParentNamespaceEnd(builder): return builder.EndObject()
-
+def End(builder):
+ return InParentNamespaceEnd(builder)
class InParentNamespaceT(object):
diff --git a/tests/MyGame/InParentNamespaceT.java b/tests/MyGame/InParentNamespaceT.java
new file mode 100644
index 0000000..36d4485
--- /dev/null
+++ b/tests/MyGame/InParentNamespaceT.java
@@ -0,0 +1,16 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+package MyGame;
+
+import java.nio.*;
+import java.lang.*;
+import java.util.*;
+import com.google.flatbuffers.*;
+
+public class InParentNamespaceT {
+
+
+ public InParentNamespaceT() {
+ }
+}
+
diff --git a/tests/MyGame/MonsterExtra.cs b/tests/MyGame/MonsterExtra.cs
index d74ae8b..6af9932 100644
--- a/tests/MyGame/MonsterExtra.cs
+++ b/tests/MyGame/MonsterExtra.cs
@@ -13,7 +13,7 @@
{
private Table __p;
public ByteBuffer ByteBuffer { get { return __p.bb; } }
- public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_1_12_0(); }
+ public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_2_0_0(); }
public static MonsterExtra GetRootAsMonsterExtra(ByteBuffer _bb) { return GetRootAsMonsterExtra(_bb, new MonsterExtra()); }
public static MonsterExtra GetRootAsMonsterExtra(ByteBuffer _bb, MonsterExtra obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); }
public static bool MonsterExtraBufferHasIdentifier(ByteBuffer _bb) { return Table.__has_identifier(_bb, "MONE"); }
@@ -147,7 +147,7 @@
_dvec,
_fvec);
}
-};
+}
public class MonsterExtraT
{
diff --git a/tests/MyGame/MonsterExtra.java b/tests/MyGame/MonsterExtra.java
index 8a5fe75..a2c342d 100644
--- a/tests/MyGame/MonsterExtra.java
+++ b/tests/MyGame/MonsterExtra.java
@@ -9,7 +9,7 @@
@SuppressWarnings("unused")
public final class MonsterExtra extends Table {
- public static void ValidateVersion() { Constants.FLATBUFFERS_1_12_0(); }
+ public static void ValidateVersion() { Constants.FLATBUFFERS_2_0_0(); }
public static MonsterExtra getRootAsMonsterExtra(ByteBuffer _bb) { return getRootAsMonsterExtra(_bb, new MonsterExtra()); }
public static MonsterExtra getRootAsMonsterExtra(ByteBuffer _bb, MonsterExtra obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
public static boolean MonsterExtraBufferHasIdentifier(ByteBuffer _bb) { return __has_identifier(_bb, "MONE"); }
@@ -100,5 +100,57 @@
public MonsterExtra get(int j) { return get(new MonsterExtra(), j); }
public MonsterExtra get(MonsterExtra obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); }
}
+ public MonsterExtraT unpack() {
+ MonsterExtraT _o = new MonsterExtraT();
+ unpackTo(_o);
+ return _o;
+ }
+ public void unpackTo(MonsterExtraT _o) {
+ double _oD0 = d0();
+ _o.setD0(_oD0);
+ double _oD1 = d1();
+ _o.setD1(_oD1);
+ double _oD2 = d2();
+ _o.setD2(_oD2);
+ double _oD3 = d3();
+ _o.setD3(_oD3);
+ float _oF0 = f0();
+ _o.setF0(_oF0);
+ float _oF1 = f1();
+ _o.setF1(_oF1);
+ float _oF2 = f2();
+ _o.setF2(_oF2);
+ float _oF3 = f3();
+ _o.setF3(_oF3);
+ double[] _oDvec = new double[dvecLength()];
+ for (int _j = 0; _j < dvecLength(); ++_j) {_oDvec[_j] = dvec(_j);}
+ _o.setDvec(_oDvec);
+ float[] _oFvec = new float[fvecLength()];
+ for (int _j = 0; _j < fvecLength(); ++_j) {_oFvec[_j] = fvec(_j);}
+ _o.setFvec(_oFvec);
+ }
+ public static int pack(FlatBufferBuilder builder, MonsterExtraT _o) {
+ if (_o == null) return 0;
+ int _dvec = 0;
+ if (_o.getDvec() != null) {
+ _dvec = createDvecVector(builder, _o.getDvec());
+ }
+ int _fvec = 0;
+ if (_o.getFvec() != null) {
+ _fvec = createFvecVector(builder, _o.getFvec());
+ }
+ return createMonsterExtra(
+ builder,
+ _o.getD0(),
+ _o.getD1(),
+ _o.getD2(),
+ _o.getD3(),
+ _o.getF0(),
+ _o.getF1(),
+ _o.getF2(),
+ _o.getF3(),
+ _dvec,
+ _fvec);
+ }
}
diff --git a/tests/MyGame/MonsterExtra.kt b/tests/MyGame/MonsterExtra.kt
index e025c2f..f222647 100644
--- a/tests/MyGame/MonsterExtra.kt
+++ b/tests/MyGame/MonsterExtra.kt
@@ -7,7 +7,6 @@
import com.google.flatbuffers.*
@Suppress("unused")
-@ExperimentalUnsignedTypes
class MonsterExtra : Table() {
fun __init(_i: Int, _bb: ByteBuffer) {
@@ -176,7 +175,7 @@
}
}
companion object {
- fun validateVersion() = Constants.FLATBUFFERS_1_12_0()
+ fun validateVersion() = Constants.FLATBUFFERS_2_0_0()
fun getRootAsMonsterExtra(_bb: ByteBuffer): MonsterExtra = getRootAsMonsterExtra(_bb, MonsterExtra())
fun getRootAsMonsterExtra(_bb: ByteBuffer, obj: MonsterExtra): MonsterExtra {
_bb.order(ByteOrder.LITTLE_ENDIAN)
diff --git a/tests/MyGame/MonsterExtra.py b/tests/MyGame/MonsterExtra.py
index eafea7c..f7288b6 100644
--- a/tests/MyGame/MonsterExtra.py
+++ b/tests/MyGame/MonsterExtra.py
@@ -10,13 +10,17 @@
__slots__ = ['_tab']
@classmethod
- def GetRootAsMonsterExtra(cls, buf, offset):
+ def GetRootAs(cls, buf, offset=0):
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
x = MonsterExtra()
x.Init(buf, n + offset)
return x
@classmethod
+ def GetRootAsMonsterExtra(cls, buf, offset=0):
+ """This method is deprecated. Please switch to GetRootAs."""
+ return cls.GetRootAs(buf, offset)
+ @classmethod
def MonsterExtraBufferHasIdentifier(cls, buf, offset, size_prefixed=False):
return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4D\x4F\x4E\x45", size_prefixed=size_prefixed)
@@ -135,20 +139,47 @@
return o == 0
def MonsterExtraStart(builder): builder.StartObject(11)
+def Start(builder):
+ return MonsterExtraStart(builder)
def MonsterExtraAddD0(builder, d0): builder.PrependFloat64Slot(0, d0, float('nan'))
+def AddD0(builder, d0):
+ return MonsterExtraAddD0(builder, d0)
def MonsterExtraAddD1(builder, d1): builder.PrependFloat64Slot(1, d1, float('nan'))
+def AddD1(builder, d1):
+ return MonsterExtraAddD1(builder, d1)
def MonsterExtraAddD2(builder, d2): builder.PrependFloat64Slot(2, d2, float('inf'))
+def AddD2(builder, d2):
+ return MonsterExtraAddD2(builder, d2)
def MonsterExtraAddD3(builder, d3): builder.PrependFloat64Slot(3, d3, float('-inf'))
+def AddD3(builder, d3):
+ return MonsterExtraAddD3(builder, d3)
def MonsterExtraAddF0(builder, f0): builder.PrependFloat32Slot(4, f0, float('nan'))
+def AddF0(builder, f0):
+ return MonsterExtraAddF0(builder, f0)
def MonsterExtraAddF1(builder, f1): builder.PrependFloat32Slot(5, f1, float('nan'))
+def AddF1(builder, f1):
+ return MonsterExtraAddF1(builder, f1)
def MonsterExtraAddF2(builder, f2): builder.PrependFloat32Slot(6, f2, float('inf'))
+def AddF2(builder, f2):
+ return MonsterExtraAddF2(builder, f2)
def MonsterExtraAddF3(builder, f3): builder.PrependFloat32Slot(7, f3, float('-inf'))
+def AddF3(builder, f3):
+ return MonsterExtraAddF3(builder, f3)
def MonsterExtraAddDvec(builder, dvec): builder.PrependUOffsetTRelativeSlot(8, flatbuffers.number_types.UOffsetTFlags.py_type(dvec), 0)
+def AddDvec(builder, dvec):
+ return MonsterExtraAddDvec(builder, dvec)
def MonsterExtraStartDvecVector(builder, numElems): return builder.StartVector(8, numElems, 8)
+def StartDvecVector(builder, numElems):
+ return MonsterExtraStartDvecVector(builder, numElems)
def MonsterExtraAddFvec(builder, fvec): builder.PrependUOffsetTRelativeSlot(9, flatbuffers.number_types.UOffsetTFlags.py_type(fvec), 0)
+def AddFvec(builder, fvec):
+ return MonsterExtraAddFvec(builder, fvec)
def MonsterExtraStartFvecVector(builder, numElems): return builder.StartVector(4, numElems, 4)
+def StartFvecVector(builder, numElems):
+ return MonsterExtraStartFvecVector(builder, numElems)
def MonsterExtraEnd(builder): return builder.EndObject()
-
+def End(builder):
+ return MonsterExtraEnd(builder)
try:
from typing import List
except:
@@ -217,7 +248,7 @@
MonsterExtraStartDvecVector(builder, len(self.dvec))
for i in reversed(range(len(self.dvec))):
builder.PrependFloat64(self.dvec[i])
- dvec = builder.EndVector(len(self.dvec))
+ dvec = builder.EndVector()
if self.fvec is not None:
if np is not None and type(self.fvec) is np.ndarray:
fvec = builder.CreateNumpyVector(self.fvec)
@@ -225,7 +256,7 @@
MonsterExtraStartFvecVector(builder, len(self.fvec))
for i in reversed(range(len(self.fvec))):
builder.PrependFloat32(self.fvec[i])
- fvec = builder.EndVector(len(self.fvec))
+ fvec = builder.EndVector()
MonsterExtraStart(builder)
MonsterExtraAddD0(builder, self.d0)
MonsterExtraAddD1(builder, self.d1)
diff --git a/tests/MyGame/MonsterExtraT.java b/tests/MyGame/MonsterExtraT.java
new file mode 100644
index 0000000..4ec1932
--- /dev/null
+++ b/tests/MyGame/MonsterExtraT.java
@@ -0,0 +1,84 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+package MyGame;
+
+import java.nio.*;
+import java.lang.*;
+import java.util.*;
+import com.google.flatbuffers.*;
+
+public class MonsterExtraT {
+ private double d0;
+ private double d1;
+ private double d2;
+ private double d3;
+ private float f0;
+ private float f1;
+ private float f2;
+ private float f3;
+ private double[] dvec;
+ private float[] fvec;
+
+ public double getD0() { return d0; }
+
+ public void setD0(double d0) { this.d0 = d0; }
+
+ public double getD1() { return d1; }
+
+ public void setD1(double d1) { this.d1 = d1; }
+
+ public double getD2() { return d2; }
+
+ public void setD2(double d2) { this.d2 = d2; }
+
+ public double getD3() { return d3; }
+
+ public void setD3(double d3) { this.d3 = d3; }
+
+ public float getF0() { return f0; }
+
+ public void setF0(float f0) { this.f0 = f0; }
+
+ public float getF1() { return f1; }
+
+ public void setF1(float f1) { this.f1 = f1; }
+
+ public float getF2() { return f2; }
+
+ public void setF2(float f2) { this.f2 = f2; }
+
+ public float getF3() { return f3; }
+
+ public void setF3(float f3) { this.f3 = f3; }
+
+ public double[] getDvec() { return dvec; }
+
+ public void setDvec(double[] dvec) { this.dvec = dvec; }
+
+ public float[] getFvec() { return fvec; }
+
+ public void setFvec(float[] fvec) { this.fvec = fvec; }
+
+
+ public MonsterExtraT() {
+ this.d0 = Double.NaN;
+ this.d1 = Double.NaN;
+ this.d2 = Double.POSITIVE_INFINITY;
+ this.d3 = Double.NEGATIVE_INFINITY;
+ this.f0 = Float.NaN;
+ this.f1 = Float.NaN;
+ this.f2 = Float.POSITIVE_INFINITY;
+ this.f3 = Float.NEGATIVE_INFINITY;
+ this.dvec = null;
+ this.fvec = null;
+ }
+ public static MonsterExtraT deserializeFromBinary(byte[] fbBuffer) {
+ return MonsterExtra.getRootAsMonsterExtra(ByteBuffer.wrap(fbBuffer)).unpack();
+ }
+ public byte[] serializeToBinary() {
+ FlatBufferBuilder fbb = new FlatBufferBuilder();
+ MonsterExtra.finishMonsterExtraBuffer(fbb, MonsterExtra.pack(fbb, this));
+ return fbb.sizedByteArray();
+ }
+}
+
diff --git a/tests/MyGame/OtherNameSpace/FromInclude.lua b/tests/MyGame/OtherNameSpace/FromInclude.lua
new file mode 100644
index 0000000..2c2bf0a
--- /dev/null
+++ b/tests/MyGame/OtherNameSpace/FromInclude.lua
@@ -0,0 +1,17 @@
+--[[ MyGame.OtherNameSpace.FromInclude
+
+ Automatically generated by the FlatBuffers compiler, do not modify.
+ Or modify. I'm a message, not a cop.
+
+ flatc version: 2.0.6
+
+ Declared by : //include_test/sub/include_test2.fbs
+ Rooting type : MyGame.Example.Monster (//monster_test.fbs)
+
+--]]
+
+local FromInclude = {
+ IncludeVal = 0,
+}
+
+return FromInclude
\ No newline at end of file
diff --git a/tests/MyGame/OtherNameSpace/TableB.lua b/tests/MyGame/OtherNameSpace/TableB.lua
new file mode 100644
index 0000000..bfa8b03
--- /dev/null
+++ b/tests/MyGame/OtherNameSpace/TableB.lua
@@ -0,0 +1,51 @@
+--[[ MyGame.OtherNameSpace.TableB
+
+ Automatically generated by the FlatBuffers compiler, do not modify.
+ Or modify. I'm a message, not a cop.
+
+ flatc version: 2.0.6
+
+ Declared by : //include_test/sub/include_test2.fbs
+ Rooting type : MyGame.Example.Monster (//monster_test.fbs)
+
+--]]
+
+local __TableA = require('TableA')
+local flatbuffers = require('flatbuffers')
+
+local TableB = {}
+local mt = {}
+
+function TableB.New()
+ local o = {}
+ setmetatable(o, {__index = mt})
+ return o
+end
+
+function mt:Init(buf, pos)
+ self.view = flatbuffers.view.New(buf, pos)
+end
+
+function mt:A()
+ local o = self.view:Offset(4)
+ if o ~= 0 then
+ local x = self.view:Indirect(self.view.pos + o)
+ local obj = __TableA.New()
+ obj:Init(self.view.bytes, x)
+ return obj
+ end
+end
+
+function TableB.Start(builder)
+ builder:StartObject(1)
+end
+
+function TableB.AddA(builder, a)
+ builder:PrependStructSlot(0, a, 0)
+end
+
+function TableB.End(builder)
+ return builder:EndObject()
+end
+
+return TableB
\ No newline at end of file
diff --git a/tests/MyGame/OtherNameSpace/TableBT.java b/tests/MyGame/OtherNameSpace/TableBT.java
new file mode 100644
index 0000000..d38d9ce
--- /dev/null
+++ b/tests/MyGame/OtherNameSpace/TableBT.java
@@ -0,0 +1,22 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+package MyGame.OtherNameSpace;
+
+import java.nio.*;
+import java.lang.*;
+import java.util.*;
+import com.google.flatbuffers.*;
+
+public class TableBT {
+ private TableAT a;
+
+ public TableAT getA() { return a; }
+
+ public void setA(TableAT a) { this.a = a; }
+
+
+ public TableBT() {
+ this.a = null;
+ }
+}
+
diff --git a/tests/MyGame/OtherNameSpace/Unused.lua b/tests/MyGame/OtherNameSpace/Unused.lua
new file mode 100644
index 0000000..2769625
--- /dev/null
+++ b/tests/MyGame/OtherNameSpace/Unused.lua
@@ -0,0 +1,38 @@
+--[[ MyGame.OtherNameSpace.Unused
+
+ Automatically generated by the FlatBuffers compiler, do not modify.
+ Or modify. I'm a message, not a cop.
+
+ flatc version: 2.0.6
+
+ Declared by : //include_test/sub/include_test2.fbs
+ Rooting type : MyGame.Example.Monster (//monster_test.fbs)
+
+--]]
+
+local flatbuffers = require('flatbuffers')
+
+local Unused = {}
+local mt = {}
+
+function Unused.New()
+ local o = {}
+ setmetatable(o, {__index = mt})
+ return o
+end
+
+function mt:Init(buf, pos)
+ self.view = flatbuffers.view.New(buf, pos)
+end
+
+function mt:A()
+ return self.view:Get(flatbuffers.N.Int32, self.view.pos + 0)
+end
+
+function Unused.CreateUnused(builder, a)
+ builder:Prep(4, 4)
+ builder:PrependInt32(a)
+ return builder:Offset()
+end
+
+return Unused
\ No newline at end of file
diff --git a/tests/MyGame/OtherNameSpace/UnusedT.java b/tests/MyGame/OtherNameSpace/UnusedT.java
new file mode 100644
index 0000000..b525a1c
--- /dev/null
+++ b/tests/MyGame/OtherNameSpace/UnusedT.java
@@ -0,0 +1,22 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+package MyGame.OtherNameSpace;
+
+import java.nio.*;
+import java.lang.*;
+import java.util.*;
+import com.google.flatbuffers.*;
+
+public class UnusedT {
+ private int a;
+
+ public int getA() { return a; }
+
+ public void setA(int a) { this.a = a; }
+
+
+ public UnusedT() {
+ this.a = 0;
+ }
+}
+
diff --git a/tests/PythonTest.sh b/tests/PythonTest.sh
index ebe49bf..00772ea 100755
--- a/tests/PythonTest.sh
+++ b/tests/PythonTest.sh
@@ -21,6 +21,8 @@
# Emit Python code for the example schema in the test dir:
${test_dir}/../flatc -p -o ${gen_code_path} -I include_test monster_test.fbs --gen-object-api
+${test_dir}/../flatc -p -o ${gen_code_path} -I include_test monster_test.fbs --gen-object-api --gen-onefile
+${test_dir}/../flatc -p -o ${gen_code_path} -I include_test monster_extra.fbs --gen-object-api
# Syntax: run_tests <interpreter> <benchmark vtable dedupes>
# <benchmark read count> <benchmark build count>
@@ -34,7 +36,7 @@
JYTHONPATH=${runtime_library_dir}:${gen_code_path} \
COMPARE_GENERATED_TO_GO=0 \
COMPARE_GENERATED_TO_JAVA=0 \
- $1 py_test.py $2 $3 $4
+ $1 py_test.py $2 $3 $4 $5
if [ $1 = python3 ]; then
PYTHONDONTWRITEBYTECODE=1 \
PYTHONPATH=${runtime_library_dir}:${gen_code_path} \
@@ -46,10 +48,12 @@
}
# Run test suite with these interpreters. The arguments are benchmark counts.
-run_tests python2.6 100 100 100
-run_tests python2.7 100 100 100
-run_tests python3 100 100 100
-run_tests pypy 100 100 100
+run_tests python2.6 100 100 100 false
+run_tests python2.7 100 100 100 false
+run_tests python2.7 100 100 100 true
+run_tests python3 100 100 100 false
+run_tests python3 100 100 100 true
+run_tests pypy 100 100 100 false
# NOTE: We'd like to support python2.5 in the future.
diff --git a/tests/RustTest.bat b/tests/RustTest.bat
index 1473ffb..e897534 100644
--- a/tests/RustTest.bat
+++ b/tests/RustTest.bat
@@ -15,8 +15,6 @@
rem Compile then run the Rust test.
-rem TODO(rw): how do we make this script abort the calling script in appveyor?
-
cd rust_usage_test
cargo test -- --quiet || exit /b 1
cargo run --bin=flatbuffers_alloc_check || exit /b 1
diff --git a/tests/RustTest.sh b/tests/RustTest.sh
index 7a7606b..c0e1f9e 100755
--- a/tests/RustTest.sh
+++ b/tests/RustTest.sh
@@ -21,32 +21,53 @@
export CARGO_TARGET_MIPS_UNKNOWN_LINUX_GNU_RUNNER="qemu-mips -L /usr/mips-linux-gnu"
fi
-cd ./rust_usage_test
+
+function check_test_result() {
+ if [[ $? == 0 ]]; then
+ echo OK: $1 passed.
+ else
+ echo KO: $1 failed.
+ exit 1
+ fi
+}
+
+cd ./rust_serialize_test
+cargo run $TARGET_FLAG -- --quiet
+check_test_result "Rust serde tests"
+
+cd ../rust_usage_test
cargo test $TARGET_FLAG -- --quiet
-TEST_RESULT=$?
-if [[ $TEST_RESULT == 0 ]]; then
- echo "OK: Rust tests passed."
-else
- echo "KO: Rust tests failed."
- exit 1
-fi
+check_test_result "Rust tests"
+
+cargo test $TARGET_FLAG --no-default-features --features no_std -- --quiet
+check_test_result "Rust tests (no_std)"
cargo run $TARGET_FLAG --bin=flatbuffers_alloc_check
-TEST_RESULT=$?
-if [[ $TEST_RESULT == 0 ]]; then
- echo "OK: Rust heap alloc test passed."
-else
- echo "KO: Rust heap alloc test failed."
- exit 1
-fi
+check_test_result "Rust flatbuffers heap alloc test"
cargo run $TARGET_FLAG --bin=flexbuffers_alloc_check
-TEST_RESULT=$?
-if [[ $TEST_RESULT == 0 ]]; then
- echo "OK: Rust heap alloc test passed."
-else
- echo "KO: Rust heap alloc test failed."
- exit 1
-fi
+check_test_result "Rust flexbuffers heap alloc test"
+
+# TODO(caspern): Fix this.
+# Temporarily disabled due to error in upstream configuration
+# https://github.com/google/flatbuffers/issues/6491
+#
+# rustup component add clippy
+# cargo clippy $TARGET_FLAG
+# check_test_result "No Cargo clippy lints test"
cargo bench $TARGET_FLAG
+
+# This test is dependent on flatc.
+if [[ -f ../../flatc ]]; then
+ cd outdir
+ cargo test
+ check_test_result "Rust generated file in \$OUT_DIR"
+ cd ..
+fi
+
+# RUST_NIGHTLY environment variable set in dockerfile.
+if [[ $RUST_NIGHTLY == 1 ]]; then
+ rustup +nightly component add miri
+ MIRIFLAGS="-Zmiri-disable-isolation" cargo +nightly miri test
+fi
diff --git a/tests/TableA.lua b/tests/TableA.lua
new file mode 100644
index 0000000..90b9c95
--- /dev/null
+++ b/tests/TableA.lua
@@ -0,0 +1,51 @@
+--[[ TableA
+
+ Automatically generated by the FlatBuffers compiler, do not modify.
+ Or modify. I'm a message, not a cop.
+
+ flatc version: 2.0.6
+
+ Declared by : //include_test/include_test1.fbs
+ Rooting type : MyGame.Example.Monster (//monster_test.fbs)
+
+--]]
+
+local __MyGame_OtherNameSpace_TableB = require('MyGame.OtherNameSpace.TableB')
+local flatbuffers = require('flatbuffers')
+
+local TableA = {}
+local mt = {}
+
+function TableA.New()
+ local o = {}
+ setmetatable(o, {__index = mt})
+ return o
+end
+
+function mt:Init(buf, pos)
+ self.view = flatbuffers.view.New(buf, pos)
+end
+
+function mt:B()
+ local o = self.view:Offset(4)
+ if o ~= 0 then
+ local x = self.view:Indirect(self.view.pos + o)
+ local obj = __MyGame_OtherNameSpace_TableB.New()
+ obj:Init(self.view.bytes, x)
+ return obj
+ end
+end
+
+function TableA.Start(builder)
+ builder:StartObject(1)
+end
+
+function TableA.AddB(builder, b)
+ builder:PrependStructSlot(0, b, 0)
+end
+
+function TableA.End(builder)
+ return builder:EndObject()
+end
+
+return TableA
\ No newline at end of file
diff --git a/tests/TableAT.java b/tests/TableAT.java
new file mode 100644
index 0000000..a81b39b
--- /dev/null
+++ b/tests/TableAT.java
@@ -0,0 +1,20 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+import java.nio.*;
+import java.lang.*;
+import java.util.*;
+import com.google.flatbuffers.*;
+
+public class TableAT {
+ private MyGame.OtherNameSpace.TableBT b;
+
+ public MyGame.OtherNameSpace.TableBT getB() { return b; }
+
+ public void setB(MyGame.OtherNameSpace.TableBT b) { this.b = b; }
+
+
+ public TableAT() {
+ this.b = null;
+ }
+}
+
diff --git a/tests/TestAll.sh b/tests/TestAll.sh
index e20431c3..06548a2 100755
--- a/tests/TestAll.sh
+++ b/tests/TestAll.sh
@@ -14,12 +14,6 @@
sh PythonTest.sh
-echo "************************ JavaScript:"
-
-sh JavaScriptTest.sh
-# FIXME does not exist:
-# sh JavaScriptUnionVectorTest.sh
-
echo "************************ TypeScript:"
sh TypeScriptTest.sh
diff --git a/tests/TypeScriptTest.bat b/tests/TypeScriptTest.bat
new file mode 100755
index 0000000..daa5451
--- /dev/null
+++ b/tests/TypeScriptTest.bat
@@ -0,0 +1,9 @@
+npm install
+../flatc.exe --ts --gen-name-strings --gen-mutable --gen-object-api -I include_test monster_test.fbs
+../flatc.exe --gen-object-api -b -I include_test monster_test.fbs unicode_test.json
+../flatc.exe --ts --gen-name-strings --gen-mutable --gen-object-api -o union_vector union_vector/union_vector.fbs
+../flatc.exe --ts --gen-name-strings optional_scalars.fbs
+tsc
+node -r esm JavaScriptTest
+node -r esm JavaScriptUnionVectorTest
+node -r esm JavaScriptFlexBuffersTest
diff --git a/tests/TypeScriptTest.sh b/tests/TypeScriptTest.sh
index f114354..fd7b82d 100755
--- a/tests/TypeScriptTest.sh
+++ b/tests/TypeScriptTest.sh
@@ -14,22 +14,21 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-pushd "$(dirname $0)" >/dev/null
+set -e
-npm install @types/flatbuffers
-npm run pretest
+# clean node_modules to make sure we depend on latest local flatbuffers at ../
+rm -rf node_modules
+npm install
-export FB_TS_TEST="TRUE"
-
-../flatc --ts --no-fb-import --gen-name-strings --gen-mutable --gen-object-api -o ts -I include_test monster_test.fbs
-../flatc --gen-object-api -b -I include_test monster_test.fbs unicode_test.json
-tsc --strict --noUnusedParameters --noUnusedLocals --noImplicitReturns --strictNullChecks ts/monster_test_generated.ts
-node JavaScriptTest ./ts/monster_test_generated
-
-../flatc --ts --gen-name-strings --no-fb-import --gen-object-api -o ts union_vector/union_vector.fbs
-tsc --strict --noUnusedParameters --noUnusedLocals --noImplicitReturns --strictNullChecks ts/union_vector_generated.ts
-node JavaScriptUnionVectorTest ./ts/union_vector_generated
-
-unset FB_TS_TEST
-
-npm uninstall @types/flatbuffers
+if [ -x ../flatc ]; then
+ ../flatc --ts --gen-name-strings --gen-mutable --gen-object-api -I include_test monster_test.fbs
+ ../flatc --gen-object-api -b -I include_test monster_test.fbs unicode_test.json
+ ../flatc --ts --gen-name-strings --gen-mutable --gen-object-api -o union_vector union_vector/union_vector.fbs
+ ../flatc --ts --gen-name-strings optional_scalars.fbs
+ ../flatc --ts --gen-name-strings --gen-object-api --gen-mutable -I ../ ./typescript_keywords.fbs test_dir/typescript_include.fbs test_dir/typescript_transitive_include.fbs ../reflection/reflection.fbs
+ ../flatc --ts --gen-name-strings --gen-object-api --gen-mutable --ts-flat-files -I ../ ./typescript_keywords.fbs test_dir/typescript_include.fbs test_dir/typescript_transitive_include.fbs ../reflection/reflection.fbs
+fi
+tsc
+node -r esm JavaScriptTest
+node -r esm JavaScriptUnionVectorTest
+node -r esm JavaScriptFlexBuffersTest
diff --git a/tests/arrays_test.bfbs b/tests/arrays_test.bfbs
index fe24507..39acd0c 100644
--- a/tests/arrays_test.bfbs
+++ b/tests/arrays_test.bfbs
Binary files differ
diff --git a/tests/arrays_test.schema.json b/tests/arrays_test.schema.json
index ed33fba..c33dc6c 100644
--- a/tests/arrays_test.schema.json
+++ b/tests/arrays_test.schema.json
@@ -41,7 +41,7 @@
"maxItems": 15
},
"c" : {
- "type" : "integer", "minimum" : -128, "maximum" : 127"
+ "type" : "integer", "minimum" : -128, "maximum" : 127
},
"d" : {
"type" : "array", "items" : {"$ref" : "#/definitions/MyGame_Example_NestedStruct"},
diff --git a/tests/arrays_test/mod.rs b/tests/arrays_test/mod.rs
new file mode 100644
index 0000000..83782dc
--- /dev/null
+++ b/tests/arrays_test/mod.rs
@@ -0,0 +1,15 @@
+// Automatically generated by the Flatbuffers compiler. Do not modify.
+pub mod my_game {
+ use super::*;
+ pub mod example {
+ use super::*;
+ mod test_enum_generated;
+ pub use self::test_enum_generated::*;
+ mod nested_struct_generated;
+ pub use self::nested_struct_generated::*;
+ mod array_struct_generated;
+ pub use self::array_struct_generated::*;
+ mod array_table_generated;
+ pub use self::array_table_generated::*;
+ } // example
+} // my_game
diff --git a/tests/arrays_test/my_game/example/array_struct_generated.rs b/tests/arrays_test/my_game/example/array_struct_generated.rs
new file mode 100644
index 0000000..dea3655
--- /dev/null
+++ b/tests/arrays_test/my_game/example/array_struct_generated.rs
@@ -0,0 +1,233 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+// struct ArrayStruct, aligned to 8
+#[repr(transparent)]
+#[derive(Clone, Copy, PartialEq)]
+pub struct ArrayStruct(pub [u8; 160]);
+impl Default for ArrayStruct {
+ fn default() -> Self {
+ Self([0; 160])
+ }
+}
+impl std::fmt::Debug for ArrayStruct {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ f.debug_struct("ArrayStruct")
+ .field("a", &self.a())
+ .field("b", &self.b())
+ .field("c", &self.c())
+ .field("d", &self.d())
+ .field("e", &self.e())
+ .field("f", &self.f())
+ .finish()
+ }
+}
+
+impl flatbuffers::SimpleToVerifyInSlice for ArrayStruct {}
+impl flatbuffers::SafeSliceAccess for ArrayStruct {}
+impl<'a> flatbuffers::Follow<'a> for ArrayStruct {
+ type Inner = &'a ArrayStruct;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ <&'a ArrayStruct>::follow(buf, loc)
+ }
+}
+impl<'a> flatbuffers::Follow<'a> for &'a ArrayStruct {
+ type Inner = &'a ArrayStruct;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ flatbuffers::follow_cast_ref::<ArrayStruct>(buf, loc)
+ }
+}
+impl<'b> flatbuffers::Push for ArrayStruct {
+ type Output = ArrayStruct;
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ let src = unsafe {
+ ::std::slice::from_raw_parts(self as *const ArrayStruct as *const u8, Self::size())
+ };
+ dst.copy_from_slice(src);
+ }
+}
+impl<'b> flatbuffers::Push for &'b ArrayStruct {
+ type Output = ArrayStruct;
+
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ let src = unsafe {
+ ::std::slice::from_raw_parts(*self as *const ArrayStruct as *const u8, Self::size())
+ };
+ dst.copy_from_slice(src);
+ }
+}
+
+impl<'a> flatbuffers::Verifiable for ArrayStruct {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ v.in_buffer::<Self>(pos)
+ }
+}
+
+impl<'a> ArrayStruct {
+ #[allow(clippy::too_many_arguments)]
+ pub fn new(
+ a: f32,
+ b: &[i32; 15],
+ c: i8,
+ d: &[NestedStruct; 2],
+ e: i32,
+ f: &[i64; 2],
+ ) -> Self {
+ let mut s = Self([0; 160]);
+ s.set_a(a);
+ s.set_b(b);
+ s.set_c(c);
+ s.set_d(d);
+ s.set_e(e);
+ s.set_f(f);
+ s
+ }
+
+ pub const fn get_fully_qualified_name() -> &'static str {
+ "MyGame.Example.ArrayStruct"
+ }
+
+ pub fn a(&self) -> f32 {
+ let mut mem = core::mem::MaybeUninit::<f32>::uninit();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ self.0[0..].as_ptr(),
+ mem.as_mut_ptr() as *mut u8,
+ core::mem::size_of::<f32>(),
+ );
+ mem.assume_init()
+ }.from_little_endian()
+ }
+
+ pub fn set_a(&mut self, x: f32) {
+ let x_le = x.to_little_endian();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ &x_le as *const f32 as *const u8,
+ self.0[0..].as_mut_ptr(),
+ core::mem::size_of::<f32>(),
+ );
+ }
+ }
+
+ pub fn b(&'a self) -> flatbuffers::Array<'a, i32, 15> {
+ flatbuffers::Array::follow(&self.0, 4)
+ }
+
+ pub fn set_b(&mut self, items: &[i32; 15]) {
+ flatbuffers::emplace_scalar_array(&mut self.0, 4, items);
+ }
+
+ pub fn c(&self) -> i8 {
+ let mut mem = core::mem::MaybeUninit::<i8>::uninit();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ self.0[64..].as_ptr(),
+ mem.as_mut_ptr() as *mut u8,
+ core::mem::size_of::<i8>(),
+ );
+ mem.assume_init()
+ }.from_little_endian()
+ }
+
+ pub fn set_c(&mut self, x: i8) {
+ let x_le = x.to_little_endian();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ &x_le as *const i8 as *const u8,
+ self.0[64..].as_mut_ptr(),
+ core::mem::size_of::<i8>(),
+ );
+ }
+ }
+
+ pub fn d(&'a self) -> flatbuffers::Array<'a, NestedStruct, 2> {
+ flatbuffers::Array::follow(&self.0, 72)
+ }
+
+ pub fn set_d(&mut self, x: &[NestedStruct; 2]) {
+ unsafe {
+ std::ptr::copy(
+ x.as_ptr() as *const u8,
+ self.0.as_mut_ptr().add(72),
+ 64,
+ );
+ }
+ }
+
+ pub fn e(&self) -> i32 {
+ let mut mem = core::mem::MaybeUninit::<i32>::uninit();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ self.0[136..].as_ptr(),
+ mem.as_mut_ptr() as *mut u8,
+ core::mem::size_of::<i32>(),
+ );
+ mem.assume_init()
+ }.from_little_endian()
+ }
+
+ pub fn set_e(&mut self, x: i32) {
+ let x_le = x.to_little_endian();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ &x_le as *const i32 as *const u8,
+ self.0[136..].as_mut_ptr(),
+ core::mem::size_of::<i32>(),
+ );
+ }
+ }
+
+ pub fn f(&'a self) -> flatbuffers::Array<'a, i64, 2> {
+ flatbuffers::Array::follow(&self.0, 144)
+ }
+
+ pub fn set_f(&mut self, items: &[i64; 2]) {
+ flatbuffers::emplace_scalar_array(&mut self.0, 144, items);
+ }
+
+ pub fn unpack(&self) -> ArrayStructT {
+ ArrayStructT {
+ a: self.a(),
+ b: self.b().into(),
+ c: self.c(),
+ d: { let d = self.d(); flatbuffers::array_init(|i| d.get(i).unpack()) },
+ e: self.e(),
+ f: self.f().into(),
+ }
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Default)]
+pub struct ArrayStructT {
+ pub a: f32,
+ pub b: [i32; 15],
+ pub c: i8,
+ pub d: [NestedStructT; 2],
+ pub e: i32,
+ pub f: [i64; 2],
+}
+impl ArrayStructT {
+ pub fn pack(&self) -> ArrayStruct {
+ ArrayStruct::new(
+ self.a,
+ &self.b,
+ self.c,
+ &flatbuffers::array_init(|i| self.d[i].pack()),
+ self.e,
+ &self.f,
+ )
+ }
+}
+
diff --git a/tests/arrays_test/my_game/example/array_table_generated.rs b/tests/arrays_test/my_game/example/array_table_generated.rs
new file mode 100644
index 0000000..f46ac74
--- /dev/null
+++ b/tests/arrays_test/my_game/example/array_table_generated.rs
@@ -0,0 +1,233 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+pub enum ArrayTableOffset {}
+#[derive(Copy, Clone, PartialEq)]
+
+pub struct ArrayTable<'a> {
+ pub _tab: flatbuffers::Table<'a>,
+}
+
+impl<'a> flatbuffers::Follow<'a> for ArrayTable<'a> {
+ type Inner = ArrayTable<'a>;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ Self { _tab: flatbuffers::Table { buf, loc } }
+ }
+}
+
+impl<'a> ArrayTable<'a> {
+ pub const VT_A: flatbuffers::VOffsetT = 4;
+
+ pub const fn get_fully_qualified_name() -> &'static str {
+ "MyGame.Example.ArrayTable"
+ }
+
+ #[inline]
+ pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
+ ArrayTable { _tab: table }
+ }
+ #[allow(unused_mut)]
+ pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
+ _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
+ args: &'args ArrayTableArgs<'args>
+ ) -> flatbuffers::WIPOffset<ArrayTable<'bldr>> {
+ let mut builder = ArrayTableBuilder::new(_fbb);
+ if let Some(x) = args.a { builder.add_a(x); }
+ builder.finish()
+ }
+
+ pub fn unpack(&self) -> ArrayTableT {
+ let a = self.a().map(|x| {
+ x.unpack()
+ });
+ ArrayTableT {
+ a,
+ }
+ }
+
+ #[inline]
+ pub fn a(&self) -> Option<&'a ArrayStruct> {
+ self._tab.get::<ArrayStruct>(ArrayTable::VT_A, None)
+ }
+}
+
+impl flatbuffers::Verifiable for ArrayTable<'_> {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ v.visit_table(pos)?
+ .visit_field::<ArrayStruct>("a", Self::VT_A, false)?
+ .finish();
+ Ok(())
+ }
+}
+pub struct ArrayTableArgs<'a> {
+ pub a: Option<&'a ArrayStruct>,
+}
+impl<'a> Default for ArrayTableArgs<'a> {
+ #[inline]
+ fn default() -> Self {
+ ArrayTableArgs {
+ a: None,
+ }
+ }
+}
+
+pub struct ArrayTableBuilder<'a: 'b, 'b> {
+ fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
+ start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
+}
+impl<'a: 'b, 'b> ArrayTableBuilder<'a, 'b> {
+ #[inline]
+ pub fn add_a(&mut self, a: &ArrayStruct) {
+ self.fbb_.push_slot_always::<&ArrayStruct>(ArrayTable::VT_A, a);
+ }
+ #[inline]
+ pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> ArrayTableBuilder<'a, 'b> {
+ let start = _fbb.start_table();
+ ArrayTableBuilder {
+ fbb_: _fbb,
+ start_: start,
+ }
+ }
+ #[inline]
+ pub fn finish(self) -> flatbuffers::WIPOffset<ArrayTable<'a>> {
+ let o = self.fbb_.end_table(self.start_);
+ flatbuffers::WIPOffset::new(o.value())
+ }
+}
+
+impl std::fmt::Debug for ArrayTable<'_> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let mut ds = f.debug_struct("ArrayTable");
+ ds.field("a", &self.a());
+ ds.finish()
+ }
+}
+#[non_exhaustive]
+#[derive(Debug, Clone, PartialEq)]
+pub struct ArrayTableT {
+ pub a: Option<ArrayStructT>,
+}
+impl Default for ArrayTableT {
+ fn default() -> Self {
+ Self {
+ a: None,
+ }
+ }
+}
+impl ArrayTableT {
+ pub fn pack<'b>(
+ &self,
+ _fbb: &mut flatbuffers::FlatBufferBuilder<'b>
+ ) -> flatbuffers::WIPOffset<ArrayTable<'b>> {
+ let a_tmp = self.a.as_ref().map(|x| x.pack());
+ let a = a_tmp.as_ref();
+ ArrayTable::create(_fbb, &ArrayTableArgs{
+ a,
+ })
+ }
+}
+#[inline]
+#[deprecated(since="2.0.0", note="Deprecated in favor of `root_as...` methods.")]
+pub fn get_root_as_array_table<'a>(buf: &'a [u8]) -> ArrayTable<'a> {
+ unsafe { flatbuffers::root_unchecked::<ArrayTable<'a>>(buf) }
+}
+
+#[inline]
+#[deprecated(since="2.0.0", note="Deprecated in favor of `root_as...` methods.")]
+pub fn get_size_prefixed_root_as_array_table<'a>(buf: &'a [u8]) -> ArrayTable<'a> {
+ unsafe { flatbuffers::size_prefixed_root_unchecked::<ArrayTable<'a>>(buf) }
+}
+
+#[inline]
+/// Verifies that a buffer of bytes contains a `ArrayTable`
+/// and returns it.
+/// Note that verification is still experimental and may not
+/// catch every error, or be maximally performant. For the
+/// previous, unchecked, behavior use
+/// `root_as_array_table_unchecked`.
+pub fn root_as_array_table(buf: &[u8]) -> Result<ArrayTable, flatbuffers::InvalidFlatbuffer> {
+ flatbuffers::root::<ArrayTable>(buf)
+}
+#[inline]
+/// Verifies that a buffer of bytes contains a size prefixed
+/// `ArrayTable` and returns it.
+/// Note that verification is still experimental and may not
+/// catch every error, or be maximally performant. For the
+/// previous, unchecked, behavior use
+/// `size_prefixed_root_as_array_table_unchecked`.
+pub fn size_prefixed_root_as_array_table(buf: &[u8]) -> Result<ArrayTable, flatbuffers::InvalidFlatbuffer> {
+ flatbuffers::size_prefixed_root::<ArrayTable>(buf)
+}
+#[inline]
+/// Verifies, with the given options, that a buffer of bytes
+/// contains a `ArrayTable` and returns it.
+/// Note that verification is still experimental and may not
+/// catch every error, or be maximally performant. For the
+/// previous, unchecked, behavior use
+/// `root_as_array_table_unchecked`.
+pub fn root_as_array_table_with_opts<'b, 'o>(
+ opts: &'o flatbuffers::VerifierOptions,
+ buf: &'b [u8],
+) -> Result<ArrayTable<'b>, flatbuffers::InvalidFlatbuffer> {
+ flatbuffers::root_with_opts::<ArrayTable<'b>>(opts, buf)
+}
+#[inline]
+/// Verifies, with the given verifier options, that a buffer of
+/// bytes contains a size prefixed `ArrayTable` and returns
+/// it. Note that verification is still experimental and may not
+/// catch every error, or be maximally performant. For the
+/// previous, unchecked, behavior use
+/// `root_as_array_table_unchecked`.
+pub fn size_prefixed_root_as_array_table_with_opts<'b, 'o>(
+ opts: &'o flatbuffers::VerifierOptions,
+ buf: &'b [u8],
+) -> Result<ArrayTable<'b>, flatbuffers::InvalidFlatbuffer> {
+ flatbuffers::size_prefixed_root_with_opts::<ArrayTable<'b>>(opts, buf)
+}
+#[inline]
+/// Assumes, without verification, that a buffer of bytes contains a ArrayTable and returns it.
+/// # Safety
+/// Callers must trust the given bytes do indeed contain a valid `ArrayTable`.
+pub unsafe fn root_as_array_table_unchecked(buf: &[u8]) -> ArrayTable {
+ flatbuffers::root_unchecked::<ArrayTable>(buf)
+}
+#[inline]
+/// Assumes, without verification, that a buffer of bytes contains a size prefixed ArrayTable and returns it.
+/// # Safety
+/// Callers must trust the given bytes do indeed contain a valid size prefixed `ArrayTable`.
+pub unsafe fn size_prefixed_root_as_array_table_unchecked(buf: &[u8]) -> ArrayTable {
+ flatbuffers::size_prefixed_root_unchecked::<ArrayTable>(buf)
+}
+pub const ARRAY_TABLE_IDENTIFIER: &str = "ARRT";
+
+#[inline]
+pub fn array_table_buffer_has_identifier(buf: &[u8]) -> bool {
+ flatbuffers::buffer_has_identifier(buf, ARRAY_TABLE_IDENTIFIER, false)
+}
+
+#[inline]
+pub fn array_table_size_prefixed_buffer_has_identifier(buf: &[u8]) -> bool {
+ flatbuffers::buffer_has_identifier(buf, ARRAY_TABLE_IDENTIFIER, true)
+}
+
+pub const ARRAY_TABLE_EXTENSION: &str = "mon";
+
+#[inline]
+pub fn finish_array_table_buffer<'a, 'b>(
+ fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,
+ root: flatbuffers::WIPOffset<ArrayTable<'a>>) {
+ fbb.finish(root, Some(ARRAY_TABLE_IDENTIFIER));
+}
+
+#[inline]
+pub fn finish_size_prefixed_array_table_buffer<'a, 'b>(fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>, root: flatbuffers::WIPOffset<ArrayTable<'a>>) {
+ fbb.finish_size_prefixed(root, Some(ARRAY_TABLE_IDENTIFIER));
+}
diff --git a/tests/arrays_test/my_game/example/nested_struct_generated.rs b/tests/arrays_test/my_game/example/nested_struct_generated.rs
new file mode 100644
index 0000000..48a6b91
--- /dev/null
+++ b/tests/arrays_test/my_game/example/nested_struct_generated.rs
@@ -0,0 +1,175 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+// struct NestedStruct, aligned to 8
+#[repr(transparent)]
+#[derive(Clone, Copy, PartialEq)]
+pub struct NestedStruct(pub [u8; 32]);
+impl Default for NestedStruct {
+ fn default() -> Self {
+ Self([0; 32])
+ }
+}
+impl std::fmt::Debug for NestedStruct {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ f.debug_struct("NestedStruct")
+ .field("a", &self.a())
+ .field("b", &self.b())
+ .field("c", &self.c())
+ .field("d", &self.d())
+ .finish()
+ }
+}
+
+impl flatbuffers::SimpleToVerifyInSlice for NestedStruct {}
+impl flatbuffers::SafeSliceAccess for NestedStruct {}
+impl<'a> flatbuffers::Follow<'a> for NestedStruct {
+ type Inner = &'a NestedStruct;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ <&'a NestedStruct>::follow(buf, loc)
+ }
+}
+impl<'a> flatbuffers::Follow<'a> for &'a NestedStruct {
+ type Inner = &'a NestedStruct;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ flatbuffers::follow_cast_ref::<NestedStruct>(buf, loc)
+ }
+}
+impl<'b> flatbuffers::Push for NestedStruct {
+ type Output = NestedStruct;
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ let src = unsafe {
+ ::std::slice::from_raw_parts(self as *const NestedStruct as *const u8, Self::size())
+ };
+ dst.copy_from_slice(src);
+ }
+}
+impl<'b> flatbuffers::Push for &'b NestedStruct {
+ type Output = NestedStruct;
+
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ let src = unsafe {
+ ::std::slice::from_raw_parts(*self as *const NestedStruct as *const u8, Self::size())
+ };
+ dst.copy_from_slice(src);
+ }
+}
+
+impl<'a> flatbuffers::Verifiable for NestedStruct {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ v.in_buffer::<Self>(pos)
+ }
+}
+
+impl<'a> NestedStruct {
+ #[allow(clippy::too_many_arguments)]
+ pub fn new(
+ a: &[i32; 2],
+ b: TestEnum,
+ c: &[TestEnum; 2],
+ d: &[i64; 2],
+ ) -> Self {
+ let mut s = Self([0; 32]);
+ s.set_a(a);
+ s.set_b(b);
+ s.set_c(c);
+ s.set_d(d);
+ s
+ }
+
+ pub const fn get_fully_qualified_name() -> &'static str {
+ "MyGame.Example.NestedStruct"
+ }
+
+ pub fn a(&'a self) -> flatbuffers::Array<'a, i32, 2> {
+ flatbuffers::Array::follow(&self.0, 0)
+ }
+
+ pub fn set_a(&mut self, items: &[i32; 2]) {
+ flatbuffers::emplace_scalar_array(&mut self.0, 0, items);
+ }
+
+ pub fn b(&self) -> TestEnum {
+ let mut mem = core::mem::MaybeUninit::<TestEnum>::uninit();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ self.0[8..].as_ptr(),
+ mem.as_mut_ptr() as *mut u8,
+ core::mem::size_of::<TestEnum>(),
+ );
+ mem.assume_init()
+ }.from_little_endian()
+ }
+
+ pub fn set_b(&mut self, x: TestEnum) {
+ let x_le = x.to_little_endian();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ &x_le as *const TestEnum as *const u8,
+ self.0[8..].as_mut_ptr(),
+ core::mem::size_of::<TestEnum>(),
+ );
+ }
+ }
+
+ pub fn c(&'a self) -> flatbuffers::Array<'a, TestEnum, 2> {
+ flatbuffers::Array::follow(&self.0, 9)
+ }
+
+ pub fn set_c(&mut self, x: &[TestEnum; 2]) {
+ unsafe {
+ std::ptr::copy(
+ x.as_ptr() as *const u8,
+ self.0.as_mut_ptr().add(9),
+ 2,
+ );
+ }
+ }
+
+ pub fn d(&'a self) -> flatbuffers::Array<'a, i64, 2> {
+ flatbuffers::Array::follow(&self.0, 16)
+ }
+
+ pub fn set_d(&mut self, items: &[i64; 2]) {
+ flatbuffers::emplace_scalar_array(&mut self.0, 16, items);
+ }
+
+ pub fn unpack(&self) -> NestedStructT {
+ NestedStructT {
+ a: self.a().into(),
+ b: self.b(),
+ c: self.c().into(),
+ d: self.d().into(),
+ }
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Default)]
+pub struct NestedStructT {
+ pub a: [i32; 2],
+ pub b: TestEnum,
+ pub c: [TestEnum; 2],
+ pub d: [i64; 2],
+}
+impl NestedStructT {
+ pub fn pack(&self) -> NestedStruct {
+ NestedStruct::new(
+ &self.a,
+ self.b,
+ &self.c,
+ &self.d,
+ )
+ }
+}
+
diff --git a/tests/arrays_test/my_game/example/test_enum_generated.rs b/tests/arrays_test/my_game/example/test_enum_generated.rs
new file mode 100644
index 0000000..6dcc1cb
--- /dev/null
+++ b/tests/arrays_test/my_game/example/test_enum_generated.rs
@@ -0,0 +1,97 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+pub const ENUM_MIN_TEST_ENUM: i8 = 0;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+pub const ENUM_MAX_TEST_ENUM: i8 = 2;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+#[allow(non_camel_case_types)]
+pub const ENUM_VALUES_TEST_ENUM: [TestEnum; 3] = [
+ TestEnum::A,
+ TestEnum::B,
+ TestEnum::C,
+];
+
+#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
+#[repr(transparent)]
+pub struct TestEnum(pub i8);
+#[allow(non_upper_case_globals)]
+impl TestEnum {
+ pub const A: Self = Self(0);
+ pub const B: Self = Self(1);
+ pub const C: Self = Self(2);
+
+ pub const ENUM_MIN: i8 = 0;
+ pub const ENUM_MAX: i8 = 2;
+ pub const ENUM_VALUES: &'static [Self] = &[
+ Self::A,
+ Self::B,
+ Self::C,
+ ];
+ /// Returns the variant's name or "" if unknown.
+ pub fn variant_name(self) -> Option<&'static str> {
+ match self {
+ Self::A => Some("A"),
+ Self::B => Some("B"),
+ Self::C => Some("C"),
+ _ => None,
+ }
+ }
+}
+impl std::fmt::Debug for TestEnum {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ if let Some(name) = self.variant_name() {
+ f.write_str(name)
+ } else {
+ f.write_fmt(format_args!("<UNKNOWN {:?}>", self.0))
+ }
+ }
+}
+impl<'a> flatbuffers::Follow<'a> for TestEnum {
+ type Inner = Self;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ let b = unsafe {
+ flatbuffers::read_scalar_at::<i8>(buf, loc)
+ };
+ Self(b)
+ }
+}
+
+impl flatbuffers::Push for TestEnum {
+ type Output = TestEnum;
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ unsafe { flatbuffers::emplace_scalar::<i8>(dst, self.0); }
+ }
+}
+
+impl flatbuffers::EndianScalar for TestEnum {
+ #[inline]
+ fn to_little_endian(self) -> Self {
+ let b = i8::to_le(self.0);
+ Self(b)
+ }
+ #[inline]
+ #[allow(clippy::wrong_self_convention)]
+ fn from_little_endian(self) -> Self {
+ let b = i8::from_le(self.0);
+ Self(b)
+ }
+}
+
+impl<'a> flatbuffers::Verifiable for TestEnum {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ i8::run_verifier(v, pos)
+ }
+}
+
+impl flatbuffers::SimpleToVerifyInSlice for TestEnum {}
diff --git a/tests/arrays_test_generated.h b/tests/arrays_test_generated.h
index 2f47a9c..1300b92 100644
--- a/tests/arrays_test_generated.h
+++ b/tests/arrays_test_generated.h
@@ -264,21 +264,13 @@
struct ArrayTableT : public flatbuffers::NativeTable {
typedef ArrayTable TableType;
- flatbuffers::unique_ptr<MyGame::Example::ArrayStruct> a;
- ArrayTableT() {
- }
+ flatbuffers::unique_ptr<MyGame::Example::ArrayStruct> a{};
+ ArrayTableT() = default;
+ ArrayTableT(const ArrayTableT &o);
+ ArrayTableT(ArrayTableT&&) FLATBUFFERS_NOEXCEPT = default;
+ ArrayTableT &operator=(ArrayTableT o) FLATBUFFERS_NOEXCEPT;
};
-inline bool operator==(const ArrayTableT &lhs, const ArrayTableT &rhs) {
- return
- (lhs.a == rhs.a);
-}
-
-inline bool operator!=(const ArrayTableT &lhs, const ArrayTableT &rhs) {
- return !(lhs == rhs);
-}
-
-
struct ArrayTable FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
typedef ArrayTableT NativeTableType;
typedef ArrayTableBuilder Builder;
@@ -296,7 +288,7 @@
}
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
- VerifyField<MyGame::Example::ArrayStruct>(verifier, VT_A) &&
+ VerifyField<MyGame::Example::ArrayStruct>(verifier, VT_A, 8) &&
verifier.EndTable();
}
ArrayTableT *UnPack(const flatbuffers::resolver_function_t *_resolver = nullptr) const;
@@ -324,7 +316,7 @@
inline flatbuffers::Offset<ArrayTable> CreateArrayTable(
flatbuffers::FlatBufferBuilder &_fbb,
- const MyGame::Example::ArrayStruct *a = 0) {
+ const MyGame::Example::ArrayStruct *a = nullptr) {
ArrayTableBuilder builder_(_fbb);
builder_.add_a(a);
return builder_.Finish();
@@ -332,8 +324,28 @@
flatbuffers::Offset<ArrayTable> CreateArrayTable(flatbuffers::FlatBufferBuilder &_fbb, const ArrayTableT *_o, const flatbuffers::rehasher_function_t *_rehasher = nullptr);
+
+inline bool operator==(const ArrayTableT &lhs, const ArrayTableT &rhs) {
+ return
+ ((lhs.a == rhs.a) || (lhs.a && rhs.a && *lhs.a == *rhs.a));
+}
+
+inline bool operator!=(const ArrayTableT &lhs, const ArrayTableT &rhs) {
+ return !(lhs == rhs);
+}
+
+
+inline ArrayTableT::ArrayTableT(const ArrayTableT &o)
+ : a((o.a) ? new MyGame::Example::ArrayStruct(*o.a) : nullptr) {
+}
+
+inline ArrayTableT &ArrayTableT::operator=(ArrayTableT o) FLATBUFFERS_NOEXCEPT {
+ std::swap(a, o.a);
+ return *this;
+}
+
inline ArrayTableT *ArrayTable::UnPack(const flatbuffers::resolver_function_t *_resolver) const {
- flatbuffers::unique_ptr<MyGame::Example::ArrayTableT> _o = flatbuffers::unique_ptr<MyGame::Example::ArrayTableT>(new ArrayTableT());
+ auto _o = std::unique_ptr<ArrayTableT>(new ArrayTableT());
UnPackTo(_o.get(), _resolver);
return _o.release();
}
@@ -458,6 +470,10 @@
return flatbuffers::GetMutableRoot<ArrayTable>(buf);
}
+inline MyGame::Example::ArrayTable *GetMutableSizePrefixedArrayTable(void *buf) {
+ return flatbuffers::GetMutableSizePrefixedRoot<MyGame::Example::ArrayTable>(buf);
+}
+
inline const char *ArrayTableIdentifier() {
return "ARRT";
}
@@ -467,6 +483,11 @@
buf, ArrayTableIdentifier());
}
+inline bool SizePrefixedArrayTableBufferHasIdentifier(const void *buf) {
+ return flatbuffers::BufferHasIdentifier(
+ buf, ArrayTableIdentifier(), true);
+}
+
inline bool VerifyArrayTableBuffer(
flatbuffers::Verifier &verifier) {
return verifier.VerifyBuffer<MyGame::Example::ArrayTable>(ArrayTableIdentifier());
diff --git a/tests/cpp17/generated_cpp17/monster_test_generated.h b/tests/cpp17/generated_cpp17/monster_test_generated.h
index 77bc011..442ba50 100644
--- a/tests/cpp17/generated_cpp17/monster_test_generated.h
+++ b/tests/cpp17/generated_cpp17/monster_test_generated.h
@@ -33,6 +33,8 @@
struct Ability;
+struct StructOfStructs;
+
struct Stat;
struct StatBuilder;
struct StatT;
@@ -69,6 +71,8 @@
inline const flatbuffers::TypeTable *AbilityTypeTable();
+inline const flatbuffers::TypeTable *StructOfStructsTypeTable();
+
inline const flatbuffers::TypeTable *StatTypeTable();
inline const flatbuffers::TypeTable *ReferrableTypeTable();
@@ -156,6 +160,33 @@
return EnumNamesRace()[index];
}
+enum class LongEnum : uint64_t {
+ LongOne = 2ULL,
+ LongTwo = 4ULL,
+ LongBig = 1099511627776ULL,
+ NONE = 0,
+ ANY = 1099511627782ULL
+};
+FLATBUFFERS_DEFINE_BITMASK_OPERATORS(LongEnum, uint64_t)
+
+inline const LongEnum (&EnumValuesLongEnum())[3] {
+ static const LongEnum values[] = {
+ LongEnum::LongOne,
+ LongEnum::LongTwo,
+ LongEnum::LongBig
+ };
+ return values;
+}
+
+inline const char *EnumNameLongEnum(LongEnum e) {
+ switch (e) {
+ case LongEnum::LongOne: return "LongOne";
+ case LongEnum::LongTwo: return "LongTwo";
+ case LongEnum::LongBig: return "LongBig";
+ default: return "";
+ }
+}
+
enum class Any : uint8_t {
NONE = 0,
Monster = 1,
@@ -208,6 +239,22 @@
static const Any enum_value = Any::MyGame_Example2_Monster;
};
+template<typename T> struct AnyUnionTraits {
+ static const Any enum_value = Any::NONE;
+};
+
+template<> struct AnyUnionTraits<MyGame::Example::MonsterT> {
+ static const Any enum_value = Any::Monster;
+};
+
+template<> struct AnyUnionTraits<MyGame::Example::TestSimpleTableWithEnumT> {
+ static const Any enum_value = Any::TestSimpleTableWithEnum;
+};
+
+template<> struct AnyUnionTraits<MyGame::Example2::MonsterT> {
+ static const Any enum_value = Any::MyGame_Example2_Monster;
+};
+
struct AnyUnion {
Any type;
void *value;
@@ -225,17 +272,15 @@
void Reset();
-#ifndef FLATBUFFERS_CPP98_STL
template <typename T>
void Set(T&& val) {
- using RT = typename std::remove_reference<T>::type;
+ typedef typename std::remove_reference<T>::type RT;
Reset();
- type = AnyTraits<typename RT::TableType>::enum_value;
+ type = AnyUnionTraits<RT>::enum_value;
if (type != Any::NONE) {
value = new RT(std::forward<T>(val));
}
}
-#endif // FLATBUFFERS_CPP98_STL
static void *UnPack(const void *obj, Any type, const flatbuffers::resolver_function_t *resolver);
flatbuffers::Offset<void> Pack(flatbuffers::FlatBufferBuilder &_fbb, const flatbuffers::rehasher_function_t *_rehasher = nullptr) const;
@@ -267,7 +312,7 @@
};
bool VerifyAny(flatbuffers::Verifier &verifier, const void *obj, Any type);
-bool VerifyAnyVector(flatbuffers::Verifier &verifier, const flatbuffers::Vector<flatbuffers::Offset<void>> *values, const flatbuffers::Vector<uint8_t> *types);
+bool VerifyAnyVector(flatbuffers::Verifier &verifier, const flatbuffers::Vector<flatbuffers::Offset<void>> *values, const flatbuffers::Vector<Any> *types);
enum class AnyUniqueAliases : uint8_t {
NONE = 0,
@@ -321,6 +366,22 @@
static const AnyUniqueAliases enum_value = AnyUniqueAliases::M2;
};
+template<typename T> struct AnyUniqueAliasesUnionTraits {
+ static const AnyUniqueAliases enum_value = AnyUniqueAliases::NONE;
+};
+
+template<> struct AnyUniqueAliasesUnionTraits<MyGame::Example::MonsterT> {
+ static const AnyUniqueAliases enum_value = AnyUniqueAliases::M;
+};
+
+template<> struct AnyUniqueAliasesUnionTraits<MyGame::Example::TestSimpleTableWithEnumT> {
+ static const AnyUniqueAliases enum_value = AnyUniqueAliases::TS;
+};
+
+template<> struct AnyUniqueAliasesUnionTraits<MyGame::Example2::MonsterT> {
+ static const AnyUniqueAliases enum_value = AnyUniqueAliases::M2;
+};
+
struct AnyUniqueAliasesUnion {
AnyUniqueAliases type;
void *value;
@@ -338,17 +399,15 @@
void Reset();
-#ifndef FLATBUFFERS_CPP98_STL
template <typename T>
void Set(T&& val) {
- using RT = typename std::remove_reference<T>::type;
+ typedef typename std::remove_reference<T>::type RT;
Reset();
- type = AnyUniqueAliasesTraits<typename RT::TableType>::enum_value;
+ type = AnyUniqueAliasesUnionTraits<RT>::enum_value;
if (type != AnyUniqueAliases::NONE) {
value = new RT(std::forward<T>(val));
}
}
-#endif // FLATBUFFERS_CPP98_STL
static void *UnPack(const void *obj, AnyUniqueAliases type, const flatbuffers::resolver_function_t *resolver);
flatbuffers::Offset<void> Pack(flatbuffers::FlatBufferBuilder &_fbb, const flatbuffers::rehasher_function_t *_rehasher = nullptr) const;
@@ -380,7 +439,7 @@
};
bool VerifyAnyUniqueAliases(flatbuffers::Verifier &verifier, const void *obj, AnyUniqueAliases type);
-bool VerifyAnyUniqueAliasesVector(flatbuffers::Verifier &verifier, const flatbuffers::Vector<flatbuffers::Offset<void>> *values, const flatbuffers::Vector<uint8_t> *types);
+bool VerifyAnyUniqueAliasesVector(flatbuffers::Verifier &verifier, const flatbuffers::Vector<flatbuffers::Offset<void>> *values, const flatbuffers::Vector<AnyUniqueAliases> *types);
enum class AnyAmbiguousAliases : uint8_t {
NONE = 0,
@@ -465,7 +524,7 @@
};
bool VerifyAnyAmbiguousAliases(flatbuffers::Verifier &verifier, const void *obj, AnyAmbiguousAliases type);
-bool VerifyAnyAmbiguousAliasesVector(flatbuffers::Verifier &verifier, const flatbuffers::Vector<flatbuffers::Offset<void>> *values, const flatbuffers::Vector<uint8_t> *types);
+bool VerifyAnyAmbiguousAliasesVector(flatbuffers::Verifier &verifier, const flatbuffers::Vector<flatbuffers::Offset<void>> *values, const flatbuffers::Vector<AnyAmbiguousAliases> *types);
FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(2) Test FLATBUFFERS_FINAL_CLASS {
private:
@@ -474,6 +533,7 @@
int8_t padding0__;
public:
+ struct Traits;
static const flatbuffers::TypeTable *MiniReflectTypeTable() {
return TestTypeTable();
}
@@ -501,9 +561,28 @@
void mutate_b(int8_t _b) {
flatbuffers::WriteScalar(&b_, _b);
}
+ template<size_t Index>
+ auto get_field() const {
+ if constexpr (Index == 0) return a();
+ else if constexpr (Index == 1) return b();
+ else static_assert(Index != Index, "Invalid Field Index");
+ }
};
FLATBUFFERS_STRUCT_END(Test, 4);
+struct Test::Traits {
+ using type = Test;
+ static constexpr auto name = "Test";
+ static constexpr auto fully_qualified_name = "MyGame.Example.Test";
+ static constexpr size_t fields_number = 2;
+ static constexpr std::array<const char *, fields_number> field_names = {
+ "a",
+ "b"
+ };
+ template<size_t Index>
+ using FieldType = decltype(std::declval<type>().get_field<Index>());
+};
+
FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(8) Vec3 FLATBUFFERS_FINAL_CLASS {
private:
float x_;
@@ -517,6 +596,7 @@
int16_t padding2__;
public:
+ struct Traits;
static const flatbuffers::TypeTable *MiniReflectTypeTable() {
return Vec3TypeTable();
}
@@ -584,15 +664,43 @@
MyGame::Example::Test &mutable_test3() {
return test3_;
}
+ template<size_t Index>
+ auto get_field() const {
+ if constexpr (Index == 0) return x();
+ else if constexpr (Index == 1) return y();
+ else if constexpr (Index == 2) return z();
+ else if constexpr (Index == 3) return test1();
+ else if constexpr (Index == 4) return test2();
+ else if constexpr (Index == 5) return test3();
+ else static_assert(Index != Index, "Invalid Field Index");
+ }
};
FLATBUFFERS_STRUCT_END(Vec3, 32);
+struct Vec3::Traits {
+ using type = Vec3;
+ static constexpr auto name = "Vec3";
+ static constexpr auto fully_qualified_name = "MyGame.Example.Vec3";
+ static constexpr size_t fields_number = 6;
+ static constexpr std::array<const char *, fields_number> field_names = {
+ "x",
+ "y",
+ "z",
+ "test1",
+ "test2",
+ "test3"
+ };
+ template<size_t Index>
+ using FieldType = decltype(std::declval<type>().get_field<Index>());
+};
+
FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) Ability FLATBUFFERS_FINAL_CLASS {
private:
uint32_t id_;
uint32_t distance_;
public:
+ struct Traits;
static const flatbuffers::TypeTable *MiniReflectTypeTable() {
return AbilityTypeTable();
}
@@ -613,8 +721,8 @@
bool KeyCompareLessThan(const Ability *o) const {
return id() < o->id();
}
- int KeyCompareWithValue(uint32_t val) const {
- return static_cast<int>(id() > val) - static_cast<int>(id() < val);
+ int KeyCompareWithValue(uint32_t _id) const {
+ return static_cast<int>(id() > _id) - static_cast<int>(id() < _id);
}
uint32_t distance() const {
return flatbuffers::EndianScalar(distance_);
@@ -622,9 +730,91 @@
void mutate_distance(uint32_t _distance) {
flatbuffers::WriteScalar(&distance_, _distance);
}
+ template<size_t Index>
+ auto get_field() const {
+ if constexpr (Index == 0) return id();
+ else if constexpr (Index == 1) return distance();
+ else static_assert(Index != Index, "Invalid Field Index");
+ }
};
FLATBUFFERS_STRUCT_END(Ability, 8);
+struct Ability::Traits {
+ using type = Ability;
+ static constexpr auto name = "Ability";
+ static constexpr auto fully_qualified_name = "MyGame.Example.Ability";
+ static constexpr size_t fields_number = 2;
+ static constexpr std::array<const char *, fields_number> field_names = {
+ "id",
+ "distance"
+ };
+ template<size_t Index>
+ using FieldType = decltype(std::declval<type>().get_field<Index>());
+};
+
+FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) StructOfStructs FLATBUFFERS_FINAL_CLASS {
+ private:
+ MyGame::Example::Ability a_;
+ MyGame::Example::Test b_;
+ MyGame::Example::Ability c_;
+
+ public:
+ struct Traits;
+ static const flatbuffers::TypeTable *MiniReflectTypeTable() {
+ return StructOfStructsTypeTable();
+ }
+ StructOfStructs()
+ : a_(),
+ b_(),
+ c_() {
+ }
+ StructOfStructs(const MyGame::Example::Ability &_a, const MyGame::Example::Test &_b, const MyGame::Example::Ability &_c)
+ : a_(_a),
+ b_(_b),
+ c_(_c) {
+ }
+ const MyGame::Example::Ability &a() const {
+ return a_;
+ }
+ MyGame::Example::Ability &mutable_a() {
+ return a_;
+ }
+ const MyGame::Example::Test &b() const {
+ return b_;
+ }
+ MyGame::Example::Test &mutable_b() {
+ return b_;
+ }
+ const MyGame::Example::Ability &c() const {
+ return c_;
+ }
+ MyGame::Example::Ability &mutable_c() {
+ return c_;
+ }
+ template<size_t Index>
+ auto get_field() const {
+ if constexpr (Index == 0) return a();
+ else if constexpr (Index == 1) return b();
+ else if constexpr (Index == 2) return c();
+ else static_assert(Index != Index, "Invalid Field Index");
+ }
+};
+FLATBUFFERS_STRUCT_END(StructOfStructs, 20);
+
+struct StructOfStructs::Traits {
+ using type = StructOfStructs;
+ static constexpr auto name = "StructOfStructs";
+ static constexpr auto fully_qualified_name = "MyGame.Example.StructOfStructs";
+ static constexpr size_t fields_number = 3;
+ static constexpr std::array<const char *, fields_number> field_names = {
+ "a",
+ "b",
+ "c"
+ };
+ template<size_t Index>
+ using FieldType = decltype(std::declval<type>().get_field<Index>());
+};
+
} // namespace Example
struct InParentNamespaceT : public flatbuffers::NativeTable {
@@ -671,6 +861,10 @@
struct InParentNamespace::Traits {
using type = InParentNamespace;
static auto constexpr Create = CreateInParentNamespace;
+ static constexpr auto name = "InParentNamespace";
+ static constexpr auto fully_qualified_name = "MyGame.InParentNamespace";
+ static constexpr size_t fields_number = 0;
+ static constexpr std::array<const char *, fields_number> field_names = {};
};
flatbuffers::Offset<InParentNamespace> CreateInParentNamespace(flatbuffers::FlatBufferBuilder &_fbb, const InParentNamespaceT *_o, const flatbuffers::rehasher_function_t *_rehasher = nullptr);
@@ -721,6 +915,10 @@
struct Monster::Traits {
using type = Monster;
static auto constexpr Create = CreateMonster;
+ static constexpr auto name = "Monster";
+ static constexpr auto fully_qualified_name = "MyGame.Example2.Monster";
+ static constexpr size_t fields_number = 0;
+ static constexpr std::array<const char *, fields_number> field_names = {};
};
flatbuffers::Offset<Monster> CreateMonster(flatbuffers::FlatBufferBuilder &_fbb, const MonsterT *_o, const flatbuffers::rehasher_function_t *_rehasher = nullptr);
@@ -747,12 +945,17 @@
MyGame::Example::Color color() const {
return static_cast<MyGame::Example::Color>(GetField<uint8_t>(VT_COLOR, 2));
}
- bool mutate_color(MyGame::Example::Color _color) {
+ bool mutate_color(MyGame::Example::Color _color = static_cast<MyGame::Example::Color>(2)) {
return SetField<uint8_t>(VT_COLOR, static_cast<uint8_t>(_color), 2);
}
+ template<size_t Index>
+ auto get_field() const {
+ if constexpr (Index == 0) return color();
+ else static_assert(Index != Index, "Invalid Field Index");
+ }
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
- VerifyField<uint8_t>(verifier, VT_COLOR) &&
+ VerifyField<uint8_t>(verifier, VT_COLOR, 1) &&
verifier.EndTable();
}
TestSimpleTableWithEnumT *UnPack(const flatbuffers::resolver_function_t *_resolver = nullptr) const;
@@ -789,6 +992,14 @@
struct TestSimpleTableWithEnum::Traits {
using type = TestSimpleTableWithEnum;
static auto constexpr Create = CreateTestSimpleTableWithEnum;
+ static constexpr auto name = "TestSimpleTableWithEnum";
+ static constexpr auto fully_qualified_name = "MyGame.Example.TestSimpleTableWithEnum";
+ static constexpr size_t fields_number = 1;
+ static constexpr std::array<const char *, fields_number> field_names = {
+ "color"
+ };
+ template<size_t Index>
+ using FieldType = decltype(std::declval<type>().get_field<Index>());
};
flatbuffers::Offset<TestSimpleTableWithEnum> CreateTestSimpleTableWithEnum(flatbuffers::FlatBufferBuilder &_fbb, const TestSimpleTableWithEnumT *_o, const flatbuffers::rehasher_function_t *_rehasher = nullptr);
@@ -821,21 +1032,34 @@
int64_t val() const {
return GetField<int64_t>(VT_VAL, 0);
}
- bool mutate_val(int64_t _val) {
+ bool mutate_val(int64_t _val = 0) {
return SetField<int64_t>(VT_VAL, _val, 0);
}
uint16_t count() const {
return GetField<uint16_t>(VT_COUNT, 0);
}
- bool mutate_count(uint16_t _count) {
+ bool mutate_count(uint16_t _count = 0) {
return SetField<uint16_t>(VT_COUNT, _count, 0);
}
+ bool KeyCompareLessThan(const Stat *o) const {
+ return count() < o->count();
+ }
+ int KeyCompareWithValue(uint16_t _count) const {
+ return static_cast<int>(count() > _count) - static_cast<int>(count() < _count);
+ }
+ template<size_t Index>
+ auto get_field() const {
+ if constexpr (Index == 0) return id();
+ else if constexpr (Index == 1) return val();
+ else if constexpr (Index == 2) return count();
+ else static_assert(Index != Index, "Invalid Field Index");
+ }
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
VerifyOffset(verifier, VT_ID) &&
verifier.VerifyString(id()) &&
- VerifyField<int64_t>(verifier, VT_VAL) &&
- VerifyField<uint16_t>(verifier, VT_COUNT) &&
+ VerifyField<int64_t>(verifier, VT_VAL, 8) &&
+ VerifyField<uint16_t>(verifier, VT_COUNT, 2) &&
verifier.EndTable();
}
StatT *UnPack(const flatbuffers::resolver_function_t *_resolver = nullptr) const;
@@ -882,6 +1106,16 @@
struct Stat::Traits {
using type = Stat;
static auto constexpr Create = CreateStat;
+ static constexpr auto name = "Stat";
+ static constexpr auto fully_qualified_name = "MyGame.Example.Stat";
+ static constexpr size_t fields_number = 3;
+ static constexpr std::array<const char *, fields_number> field_names = {
+ "id",
+ "val",
+ "count"
+ };
+ template<size_t Index>
+ using FieldType = decltype(std::declval<type>().get_field<Index>());
};
inline flatbuffers::Offset<Stat> CreateStatDirect(
@@ -917,18 +1151,23 @@
uint64_t id() const {
return GetField<uint64_t>(VT_ID, 0);
}
- bool mutate_id(uint64_t _id) {
+ bool mutate_id(uint64_t _id = 0) {
return SetField<uint64_t>(VT_ID, _id, 0);
}
bool KeyCompareLessThan(const Referrable *o) const {
return id() < o->id();
}
- int KeyCompareWithValue(uint64_t val) const {
- return static_cast<int>(id() > val) - static_cast<int>(id() < val);
+ int KeyCompareWithValue(uint64_t _id) const {
+ return static_cast<int>(id() > _id) - static_cast<int>(id() < _id);
+ }
+ template<size_t Index>
+ auto get_field() const {
+ if constexpr (Index == 0) return id();
+ else static_assert(Index != Index, "Invalid Field Index");
}
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
- VerifyField<uint64_t>(verifier, VT_ID) &&
+ VerifyField<uint64_t>(verifier, VT_ID, 8) &&
verifier.EndTable();
}
ReferrableT *UnPack(const flatbuffers::resolver_function_t *_resolver = nullptr) const;
@@ -965,6 +1204,14 @@
struct Referrable::Traits {
using type = Referrable;
static auto constexpr Create = CreateReferrable;
+ static constexpr auto name = "Referrable";
+ static constexpr auto fully_qualified_name = "MyGame.Example.Referrable";
+ static constexpr size_t fields_number = 1;
+ static constexpr std::array<const char *, fields_number> field_names = {
+ "id"
+ };
+ template<size_t Index>
+ using FieldType = decltype(std::declval<type>().get_field<Index>());
};
flatbuffers::Offset<Referrable> CreateReferrable(flatbuffers::FlatBufferBuilder &_fbb, const ReferrableT *_o, const flatbuffers::rehasher_function_t *_rehasher = nullptr);
@@ -1017,6 +1264,14 @@
std::vector<MyGame::Example::Color> vector_of_enums{};
MyGame::Example::Race signed_enum = MyGame::Example::Race::None;
std::vector<uint8_t> testrequirednestedflatbuffer{};
+ std::vector<std::unique_ptr<MyGame::Example::StatT>> scalar_key_sorted_tables{};
+ MyGame::Example::Test native_inline{};
+ MyGame::Example::LongEnum long_enum_non_enum_default = static_cast<MyGame::Example::LongEnum>(0);
+ MyGame::Example::LongEnum long_enum_normal_default = MyGame::Example::LongEnum::LongOne;
+ MonsterT() = default;
+ MonsterT(const MonsterT &o);
+ MonsterT(MonsterT&&) FLATBUFFERS_NOEXCEPT = default;
+ MonsterT &operator=(MonsterT o) FLATBUFFERS_NOEXCEPT;
};
/// an example documentation comment: "monster object"
@@ -1076,7 +1331,11 @@
VT_ANY_AMBIGUOUS = 96,
VT_VECTOR_OF_ENUMS = 98,
VT_SIGNED_ENUM = 100,
- VT_TESTREQUIREDNESTEDFLATBUFFER = 102
+ VT_TESTREQUIREDNESTEDFLATBUFFER = 102,
+ VT_SCALAR_KEY_SORTED_TABLES = 104,
+ VT_NATIVE_INLINE = 106,
+ VT_LONG_ENUM_NON_ENUM_DEFAULT = 108,
+ VT_LONG_ENUM_NORMAL_DEFAULT = 110
};
const MyGame::Example::Vec3 *pos() const {
return GetStruct<const MyGame::Example::Vec3 *>(VT_POS);
@@ -1087,13 +1346,13 @@
int16_t mana() const {
return GetField<int16_t>(VT_MANA, 150);
}
- bool mutate_mana(int16_t _mana) {
+ bool mutate_mana(int16_t _mana = 150) {
return SetField<int16_t>(VT_MANA, _mana, 150);
}
int16_t hp() const {
return GetField<int16_t>(VT_HP, 100);
}
- bool mutate_hp(int16_t _hp) {
+ bool mutate_hp(int16_t _hp = 100) {
return SetField<int16_t>(VT_HP, _hp, 100);
}
const flatbuffers::String *name() const {
@@ -1105,8 +1364,8 @@
bool KeyCompareLessThan(const Monster *o) const {
return *name() < *o->name();
}
- int KeyCompareWithValue(const char *val) const {
- return strcmp(name()->c_str(), val);
+ int KeyCompareWithValue(const char *_name) const {
+ return strcmp(name()->c_str(), _name);
}
const flatbuffers::Vector<uint8_t> *inventory() const {
return GetPointer<const flatbuffers::Vector<uint8_t> *>(VT_INVENTORY);
@@ -1117,7 +1376,7 @@
MyGame::Example::Color color() const {
return static_cast<MyGame::Example::Color>(GetField<uint8_t>(VT_COLOR, 8));
}
- bool mutate_color(MyGame::Example::Color _color) {
+ bool mutate_color(MyGame::Example::Color _color = static_cast<MyGame::Example::Color>(8)) {
return SetField<uint8_t>(VT_COLOR, static_cast<uint8_t>(_color), 8);
}
MyGame::Example::Any test_type() const {
@@ -1183,55 +1442,55 @@
bool testbool() const {
return GetField<uint8_t>(VT_TESTBOOL, 0) != 0;
}
- bool mutate_testbool(bool _testbool) {
+ bool mutate_testbool(bool _testbool = 0) {
return SetField<uint8_t>(VT_TESTBOOL, static_cast<uint8_t>(_testbool), 0);
}
int32_t testhashs32_fnv1() const {
return GetField<int32_t>(VT_TESTHASHS32_FNV1, 0);
}
- bool mutate_testhashs32_fnv1(int32_t _testhashs32_fnv1) {
+ bool mutate_testhashs32_fnv1(int32_t _testhashs32_fnv1 = 0) {
return SetField<int32_t>(VT_TESTHASHS32_FNV1, _testhashs32_fnv1, 0);
}
uint32_t testhashu32_fnv1() const {
return GetField<uint32_t>(VT_TESTHASHU32_FNV1, 0);
}
- bool mutate_testhashu32_fnv1(uint32_t _testhashu32_fnv1) {
+ bool mutate_testhashu32_fnv1(uint32_t _testhashu32_fnv1 = 0) {
return SetField<uint32_t>(VT_TESTHASHU32_FNV1, _testhashu32_fnv1, 0);
}
int64_t testhashs64_fnv1() const {
return GetField<int64_t>(VT_TESTHASHS64_FNV1, 0);
}
- bool mutate_testhashs64_fnv1(int64_t _testhashs64_fnv1) {
+ bool mutate_testhashs64_fnv1(int64_t _testhashs64_fnv1 = 0) {
return SetField<int64_t>(VT_TESTHASHS64_FNV1, _testhashs64_fnv1, 0);
}
uint64_t testhashu64_fnv1() const {
return GetField<uint64_t>(VT_TESTHASHU64_FNV1, 0);
}
- bool mutate_testhashu64_fnv1(uint64_t _testhashu64_fnv1) {
+ bool mutate_testhashu64_fnv1(uint64_t _testhashu64_fnv1 = 0) {
return SetField<uint64_t>(VT_TESTHASHU64_FNV1, _testhashu64_fnv1, 0);
}
int32_t testhashs32_fnv1a() const {
return GetField<int32_t>(VT_TESTHASHS32_FNV1A, 0);
}
- bool mutate_testhashs32_fnv1a(int32_t _testhashs32_fnv1a) {
+ bool mutate_testhashs32_fnv1a(int32_t _testhashs32_fnv1a = 0) {
return SetField<int32_t>(VT_TESTHASHS32_FNV1A, _testhashs32_fnv1a, 0);
}
uint32_t testhashu32_fnv1a() const {
return GetField<uint32_t>(VT_TESTHASHU32_FNV1A, 0);
}
- bool mutate_testhashu32_fnv1a(uint32_t _testhashu32_fnv1a) {
+ bool mutate_testhashu32_fnv1a(uint32_t _testhashu32_fnv1a = 0) {
return SetField<uint32_t>(VT_TESTHASHU32_FNV1A, _testhashu32_fnv1a, 0);
}
int64_t testhashs64_fnv1a() const {
return GetField<int64_t>(VT_TESTHASHS64_FNV1A, 0);
}
- bool mutate_testhashs64_fnv1a(int64_t _testhashs64_fnv1a) {
+ bool mutate_testhashs64_fnv1a(int64_t _testhashs64_fnv1a = 0) {
return SetField<int64_t>(VT_TESTHASHS64_FNV1A, _testhashs64_fnv1a, 0);
}
uint64_t testhashu64_fnv1a() const {
return GetField<uint64_t>(VT_TESTHASHU64_FNV1A, 0);
}
- bool mutate_testhashu64_fnv1a(uint64_t _testhashu64_fnv1a) {
+ bool mutate_testhashu64_fnv1a(uint64_t _testhashu64_fnv1a = 0) {
return SetField<uint64_t>(VT_TESTHASHU64_FNV1A, _testhashu64_fnv1a, 0);
}
const flatbuffers::Vector<uint8_t> *testarrayofbools() const {
@@ -1243,19 +1502,19 @@
float testf() const {
return GetField<float>(VT_TESTF, 3.14159f);
}
- bool mutate_testf(float _testf) {
+ bool mutate_testf(float _testf = 3.14159f) {
return SetField<float>(VT_TESTF, _testf, 3.14159f);
}
float testf2() const {
return GetField<float>(VT_TESTF2, 3.0f);
}
- bool mutate_testf2(float _testf2) {
+ bool mutate_testf2(float _testf2 = 3.0f) {
return SetField<float>(VT_TESTF2, _testf2, 3.0f);
}
float testf3() const {
return GetField<float>(VT_TESTF3, 0.0f);
}
- bool mutate_testf3(float _testf3) {
+ bool mutate_testf3(float _testf3 = 0.0f) {
return SetField<float>(VT_TESTF3, _testf3, 0.0f);
}
const flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>> *testarrayofstring2() const {
@@ -1312,7 +1571,7 @@
uint64_t single_weak_reference() const {
return GetField<uint64_t>(VT_SINGLE_WEAK_REFERENCE, 0);
}
- bool mutate_single_weak_reference(uint64_t _single_weak_reference) {
+ bool mutate_single_weak_reference(uint64_t _single_weak_reference = 0) {
return SetField<uint64_t>(VT_SINGLE_WEAK_REFERENCE, _single_weak_reference, 0);
}
const flatbuffers::Vector<uint64_t> *vector_of_weak_references() const {
@@ -1330,7 +1589,7 @@
uint64_t co_owning_reference() const {
return GetField<uint64_t>(VT_CO_OWNING_REFERENCE, 0);
}
- bool mutate_co_owning_reference(uint64_t _co_owning_reference) {
+ bool mutate_co_owning_reference(uint64_t _co_owning_reference = 0) {
return SetField<uint64_t>(VT_CO_OWNING_REFERENCE, _co_owning_reference, 0);
}
const flatbuffers::Vector<uint64_t> *vector_of_co_owning_references() const {
@@ -1342,7 +1601,7 @@
uint64_t non_owning_reference() const {
return GetField<uint64_t>(VT_NON_OWNING_REFERENCE, 0);
}
- bool mutate_non_owning_reference(uint64_t _non_owning_reference) {
+ bool mutate_non_owning_reference(uint64_t _non_owning_reference = 0) {
return SetField<uint64_t>(VT_NON_OWNING_REFERENCE, _non_owning_reference, 0);
}
const flatbuffers::Vector<uint64_t> *vector_of_non_owning_references() const {
@@ -1397,7 +1656,7 @@
MyGame::Example::Race signed_enum() const {
return static_cast<MyGame::Example::Race>(GetField<int8_t>(VT_SIGNED_ENUM, -1));
}
- bool mutate_signed_enum(MyGame::Example::Race _signed_enum) {
+ bool mutate_signed_enum(MyGame::Example::Race _signed_enum = static_cast<MyGame::Example::Race>(-1)) {
return SetField<int8_t>(VT_SIGNED_ENUM, static_cast<int8_t>(_signed_enum), -1);
}
const flatbuffers::Vector<uint8_t> *testrequirednestedflatbuffer() const {
@@ -1409,17 +1668,98 @@
const MyGame::Example::Monster *testrequirednestedflatbuffer_nested_root() const {
return flatbuffers::GetRoot<MyGame::Example::Monster>(testrequirednestedflatbuffer()->Data());
}
+ const flatbuffers::Vector<flatbuffers::Offset<MyGame::Example::Stat>> *scalar_key_sorted_tables() const {
+ return GetPointer<const flatbuffers::Vector<flatbuffers::Offset<MyGame::Example::Stat>> *>(VT_SCALAR_KEY_SORTED_TABLES);
+ }
+ flatbuffers::Vector<flatbuffers::Offset<MyGame::Example::Stat>> *mutable_scalar_key_sorted_tables() {
+ return GetPointer<flatbuffers::Vector<flatbuffers::Offset<MyGame::Example::Stat>> *>(VT_SCALAR_KEY_SORTED_TABLES);
+ }
+ const MyGame::Example::Test *native_inline() const {
+ return GetStruct<const MyGame::Example::Test *>(VT_NATIVE_INLINE);
+ }
+ MyGame::Example::Test *mutable_native_inline() {
+ return GetStruct<MyGame::Example::Test *>(VT_NATIVE_INLINE);
+ }
+ MyGame::Example::LongEnum long_enum_non_enum_default() const {
+ return static_cast<MyGame::Example::LongEnum>(GetField<uint64_t>(VT_LONG_ENUM_NON_ENUM_DEFAULT, 0));
+ }
+ bool mutate_long_enum_non_enum_default(MyGame::Example::LongEnum _long_enum_non_enum_default = static_cast<MyGame::Example::LongEnum>(0)) {
+ return SetField<uint64_t>(VT_LONG_ENUM_NON_ENUM_DEFAULT, static_cast<uint64_t>(_long_enum_non_enum_default), 0);
+ }
+ MyGame::Example::LongEnum long_enum_normal_default() const {
+ return static_cast<MyGame::Example::LongEnum>(GetField<uint64_t>(VT_LONG_ENUM_NORMAL_DEFAULT, 2ULL));
+ }
+ bool mutate_long_enum_normal_default(MyGame::Example::LongEnum _long_enum_normal_default = static_cast<MyGame::Example::LongEnum>(2ULL)) {
+ return SetField<uint64_t>(VT_LONG_ENUM_NORMAL_DEFAULT, static_cast<uint64_t>(_long_enum_normal_default), 2ULL);
+ }
+ template<size_t Index>
+ auto get_field() const {
+ if constexpr (Index == 0) return pos();
+ else if constexpr (Index == 1) return mana();
+ else if constexpr (Index == 2) return hp();
+ else if constexpr (Index == 3) return name();
+ else if constexpr (Index == 4) return inventory();
+ else if constexpr (Index == 5) return color();
+ else if constexpr (Index == 6) return test_type();
+ else if constexpr (Index == 7) return test();
+ else if constexpr (Index == 8) return test4();
+ else if constexpr (Index == 9) return testarrayofstring();
+ else if constexpr (Index == 10) return testarrayoftables();
+ else if constexpr (Index == 11) return enemy();
+ else if constexpr (Index == 12) return testnestedflatbuffer();
+ else if constexpr (Index == 13) return testempty();
+ else if constexpr (Index == 14) return testbool();
+ else if constexpr (Index == 15) return testhashs32_fnv1();
+ else if constexpr (Index == 16) return testhashu32_fnv1();
+ else if constexpr (Index == 17) return testhashs64_fnv1();
+ else if constexpr (Index == 18) return testhashu64_fnv1();
+ else if constexpr (Index == 19) return testhashs32_fnv1a();
+ else if constexpr (Index == 20) return testhashu32_fnv1a();
+ else if constexpr (Index == 21) return testhashs64_fnv1a();
+ else if constexpr (Index == 22) return testhashu64_fnv1a();
+ else if constexpr (Index == 23) return testarrayofbools();
+ else if constexpr (Index == 24) return testf();
+ else if constexpr (Index == 25) return testf2();
+ else if constexpr (Index == 26) return testf3();
+ else if constexpr (Index == 27) return testarrayofstring2();
+ else if constexpr (Index == 28) return testarrayofsortedstruct();
+ else if constexpr (Index == 29) return flex();
+ else if constexpr (Index == 30) return test5();
+ else if constexpr (Index == 31) return vector_of_longs();
+ else if constexpr (Index == 32) return vector_of_doubles();
+ else if constexpr (Index == 33) return parent_namespace_test();
+ else if constexpr (Index == 34) return vector_of_referrables();
+ else if constexpr (Index == 35) return single_weak_reference();
+ else if constexpr (Index == 36) return vector_of_weak_references();
+ else if constexpr (Index == 37) return vector_of_strong_referrables();
+ else if constexpr (Index == 38) return co_owning_reference();
+ else if constexpr (Index == 39) return vector_of_co_owning_references();
+ else if constexpr (Index == 40) return non_owning_reference();
+ else if constexpr (Index == 41) return vector_of_non_owning_references();
+ else if constexpr (Index == 42) return any_unique_type();
+ else if constexpr (Index == 43) return any_unique();
+ else if constexpr (Index == 44) return any_ambiguous_type();
+ else if constexpr (Index == 45) return any_ambiguous();
+ else if constexpr (Index == 46) return vector_of_enums();
+ else if constexpr (Index == 47) return signed_enum();
+ else if constexpr (Index == 48) return testrequirednestedflatbuffer();
+ else if constexpr (Index == 49) return scalar_key_sorted_tables();
+ else if constexpr (Index == 50) return native_inline();
+ else if constexpr (Index == 51) return long_enum_non_enum_default();
+ else if constexpr (Index == 52) return long_enum_normal_default();
+ else static_assert(Index != Index, "Invalid Field Index");
+ }
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
- VerifyField<MyGame::Example::Vec3>(verifier, VT_POS) &&
- VerifyField<int16_t>(verifier, VT_MANA) &&
- VerifyField<int16_t>(verifier, VT_HP) &&
+ VerifyField<MyGame::Example::Vec3>(verifier, VT_POS, 8) &&
+ VerifyField<int16_t>(verifier, VT_MANA, 2) &&
+ VerifyField<int16_t>(verifier, VT_HP, 2) &&
VerifyOffsetRequired(verifier, VT_NAME) &&
verifier.VerifyString(name()) &&
VerifyOffset(verifier, VT_INVENTORY) &&
verifier.VerifyVector(inventory()) &&
- VerifyField<uint8_t>(verifier, VT_COLOR) &&
- VerifyField<uint8_t>(verifier, VT_TEST_TYPE) &&
+ VerifyField<uint8_t>(verifier, VT_COLOR, 1) &&
+ VerifyField<uint8_t>(verifier, VT_TEST_TYPE, 1) &&
VerifyOffset(verifier, VT_TEST) &&
VerifyAny(verifier, test(), test_type()) &&
VerifyOffset(verifier, VT_TEST4) &&
@@ -1434,22 +1774,23 @@
verifier.VerifyTable(enemy()) &&
VerifyOffset(verifier, VT_TESTNESTEDFLATBUFFER) &&
verifier.VerifyVector(testnestedflatbuffer()) &&
+ verifier.VerifyNestedFlatBuffer<MyGame::Example::Monster>(testnestedflatbuffer(), nullptr) &&
VerifyOffset(verifier, VT_TESTEMPTY) &&
verifier.VerifyTable(testempty()) &&
- VerifyField<uint8_t>(verifier, VT_TESTBOOL) &&
- VerifyField<int32_t>(verifier, VT_TESTHASHS32_FNV1) &&
- VerifyField<uint32_t>(verifier, VT_TESTHASHU32_FNV1) &&
- VerifyField<int64_t>(verifier, VT_TESTHASHS64_FNV1) &&
- VerifyField<uint64_t>(verifier, VT_TESTHASHU64_FNV1) &&
- VerifyField<int32_t>(verifier, VT_TESTHASHS32_FNV1A) &&
- VerifyField<uint32_t>(verifier, VT_TESTHASHU32_FNV1A) &&
- VerifyField<int64_t>(verifier, VT_TESTHASHS64_FNV1A) &&
- VerifyField<uint64_t>(verifier, VT_TESTHASHU64_FNV1A) &&
+ VerifyField<uint8_t>(verifier, VT_TESTBOOL, 1) &&
+ VerifyField<int32_t>(verifier, VT_TESTHASHS32_FNV1, 4) &&
+ VerifyField<uint32_t>(verifier, VT_TESTHASHU32_FNV1, 4) &&
+ VerifyField<int64_t>(verifier, VT_TESTHASHS64_FNV1, 8) &&
+ VerifyField<uint64_t>(verifier, VT_TESTHASHU64_FNV1, 8) &&
+ VerifyField<int32_t>(verifier, VT_TESTHASHS32_FNV1A, 4) &&
+ VerifyField<uint32_t>(verifier, VT_TESTHASHU32_FNV1A, 4) &&
+ VerifyField<int64_t>(verifier, VT_TESTHASHS64_FNV1A, 8) &&
+ VerifyField<uint64_t>(verifier, VT_TESTHASHU64_FNV1A, 8) &&
VerifyOffset(verifier, VT_TESTARRAYOFBOOLS) &&
verifier.VerifyVector(testarrayofbools()) &&
- VerifyField<float>(verifier, VT_TESTF) &&
- VerifyField<float>(verifier, VT_TESTF2) &&
- VerifyField<float>(verifier, VT_TESTF3) &&
+ VerifyField<float>(verifier, VT_TESTF, 4) &&
+ VerifyField<float>(verifier, VT_TESTF2, 4) &&
+ VerifyField<float>(verifier, VT_TESTF3, 4) &&
VerifyOffset(verifier, VT_TESTARRAYOFSTRING2) &&
verifier.VerifyVector(testarrayofstring2()) &&
verifier.VerifyVectorOfStrings(testarrayofstring2()) &&
@@ -1457,6 +1798,7 @@
verifier.VerifyVector(testarrayofsortedstruct()) &&
VerifyOffset(verifier, VT_FLEX) &&
verifier.VerifyVector(flex()) &&
+ flexbuffers::VerifyNestedFlexBuffer(flex(), verifier) &&
VerifyOffset(verifier, VT_TEST5) &&
verifier.VerifyVector(test5()) &&
VerifyOffset(verifier, VT_VECTOR_OF_LONGS) &&
@@ -1468,29 +1810,36 @@
VerifyOffset(verifier, VT_VECTOR_OF_REFERRABLES) &&
verifier.VerifyVector(vector_of_referrables()) &&
verifier.VerifyVectorOfTables(vector_of_referrables()) &&
- VerifyField<uint64_t>(verifier, VT_SINGLE_WEAK_REFERENCE) &&
+ VerifyField<uint64_t>(verifier, VT_SINGLE_WEAK_REFERENCE, 8) &&
VerifyOffset(verifier, VT_VECTOR_OF_WEAK_REFERENCES) &&
verifier.VerifyVector(vector_of_weak_references()) &&
VerifyOffset(verifier, VT_VECTOR_OF_STRONG_REFERRABLES) &&
verifier.VerifyVector(vector_of_strong_referrables()) &&
verifier.VerifyVectorOfTables(vector_of_strong_referrables()) &&
- VerifyField<uint64_t>(verifier, VT_CO_OWNING_REFERENCE) &&
+ VerifyField<uint64_t>(verifier, VT_CO_OWNING_REFERENCE, 8) &&
VerifyOffset(verifier, VT_VECTOR_OF_CO_OWNING_REFERENCES) &&
verifier.VerifyVector(vector_of_co_owning_references()) &&
- VerifyField<uint64_t>(verifier, VT_NON_OWNING_REFERENCE) &&
+ VerifyField<uint64_t>(verifier, VT_NON_OWNING_REFERENCE, 8) &&
VerifyOffset(verifier, VT_VECTOR_OF_NON_OWNING_REFERENCES) &&
verifier.VerifyVector(vector_of_non_owning_references()) &&
- VerifyField<uint8_t>(verifier, VT_ANY_UNIQUE_TYPE) &&
+ VerifyField<uint8_t>(verifier, VT_ANY_UNIQUE_TYPE, 1) &&
VerifyOffset(verifier, VT_ANY_UNIQUE) &&
VerifyAnyUniqueAliases(verifier, any_unique(), any_unique_type()) &&
- VerifyField<uint8_t>(verifier, VT_ANY_AMBIGUOUS_TYPE) &&
+ VerifyField<uint8_t>(verifier, VT_ANY_AMBIGUOUS_TYPE, 1) &&
VerifyOffset(verifier, VT_ANY_AMBIGUOUS) &&
VerifyAnyAmbiguousAliases(verifier, any_ambiguous(), any_ambiguous_type()) &&
VerifyOffset(verifier, VT_VECTOR_OF_ENUMS) &&
verifier.VerifyVector(vector_of_enums()) &&
- VerifyField<int8_t>(verifier, VT_SIGNED_ENUM) &&
+ VerifyField<int8_t>(verifier, VT_SIGNED_ENUM, 1) &&
VerifyOffset(verifier, VT_TESTREQUIREDNESTEDFLATBUFFER) &&
verifier.VerifyVector(testrequirednestedflatbuffer()) &&
+ verifier.VerifyNestedFlatBuffer<MyGame::Example::Monster>(testrequirednestedflatbuffer(), nullptr) &&
+ VerifyOffset(verifier, VT_SCALAR_KEY_SORTED_TABLES) &&
+ verifier.VerifyVector(scalar_key_sorted_tables()) &&
+ verifier.VerifyVectorOfTables(scalar_key_sorted_tables()) &&
+ VerifyField<MyGame::Example::Test>(verifier, VT_NATIVE_INLINE, 2) &&
+ VerifyField<uint64_t>(verifier, VT_LONG_ENUM_NON_ENUM_DEFAULT, 8) &&
+ VerifyField<uint64_t>(verifier, VT_LONG_ENUM_NORMAL_DEFAULT, 8) &&
verifier.EndTable();
}
MonsterT *UnPack(const flatbuffers::resolver_function_t *_resolver = nullptr) const;
@@ -1673,6 +2022,18 @@
void add_testrequirednestedflatbuffer(flatbuffers::Offset<flatbuffers::Vector<uint8_t>> testrequirednestedflatbuffer) {
fbb_.AddOffset(Monster::VT_TESTREQUIREDNESTEDFLATBUFFER, testrequirednestedflatbuffer);
}
+ void add_scalar_key_sorted_tables(flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<MyGame::Example::Stat>>> scalar_key_sorted_tables) {
+ fbb_.AddOffset(Monster::VT_SCALAR_KEY_SORTED_TABLES, scalar_key_sorted_tables);
+ }
+ void add_native_inline(const MyGame::Example::Test *native_inline) {
+ fbb_.AddStruct(Monster::VT_NATIVE_INLINE, native_inline);
+ }
+ void add_long_enum_non_enum_default(MyGame::Example::LongEnum long_enum_non_enum_default) {
+ fbb_.AddElement<uint64_t>(Monster::VT_LONG_ENUM_NON_ENUM_DEFAULT, static_cast<uint64_t>(long_enum_non_enum_default), 0);
+ }
+ void add_long_enum_normal_default(MyGame::Example::LongEnum long_enum_normal_default) {
+ fbb_.AddElement<uint64_t>(Monster::VT_LONG_ENUM_NORMAL_DEFAULT, static_cast<uint64_t>(long_enum_normal_default), 2ULL);
+ }
explicit MonsterBuilder(flatbuffers::FlatBufferBuilder &_fbb)
: fbb_(_fbb) {
start_ = fbb_.StartTable();
@@ -1687,7 +2048,7 @@
inline flatbuffers::Offset<Monster> CreateMonster(
flatbuffers::FlatBufferBuilder &_fbb,
- const MyGame::Example::Vec3 *pos = 0,
+ const MyGame::Example::Vec3 *pos = nullptr,
int16_t mana = 150,
int16_t hp = 100,
flatbuffers::Offset<flatbuffers::String> name = 0,
@@ -1735,8 +2096,14 @@
flatbuffers::Offset<void> any_ambiguous = 0,
flatbuffers::Offset<flatbuffers::Vector<MyGame::Example::Color>> vector_of_enums = 0,
MyGame::Example::Race signed_enum = MyGame::Example::Race::None,
- flatbuffers::Offset<flatbuffers::Vector<uint8_t>> testrequirednestedflatbuffer = 0) {
+ flatbuffers::Offset<flatbuffers::Vector<uint8_t>> testrequirednestedflatbuffer = 0,
+ flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<MyGame::Example::Stat>>> scalar_key_sorted_tables = 0,
+ const MyGame::Example::Test *native_inline = nullptr,
+ MyGame::Example::LongEnum long_enum_non_enum_default = static_cast<MyGame::Example::LongEnum>(0),
+ MyGame::Example::LongEnum long_enum_normal_default = MyGame::Example::LongEnum::LongOne) {
MonsterBuilder builder_(_fbb);
+ builder_.add_long_enum_normal_default(long_enum_normal_default);
+ builder_.add_long_enum_non_enum_default(long_enum_non_enum_default);
builder_.add_non_owning_reference(non_owning_reference);
builder_.add_co_owning_reference(co_owning_reference);
builder_.add_single_weak_reference(single_weak_reference);
@@ -1744,6 +2111,8 @@
builder_.add_testhashs64_fnv1a(testhashs64_fnv1a);
builder_.add_testhashu64_fnv1(testhashu64_fnv1);
builder_.add_testhashs64_fnv1(testhashs64_fnv1);
+ builder_.add_native_inline(native_inline);
+ builder_.add_scalar_key_sorted_tables(scalar_key_sorted_tables);
builder_.add_testrequirednestedflatbuffer(testrequirednestedflatbuffer);
builder_.add_vector_of_enums(vector_of_enums);
builder_.add_any_ambiguous(any_ambiguous);
@@ -1792,11 +2161,71 @@
struct Monster::Traits {
using type = Monster;
static auto constexpr Create = CreateMonster;
+ static constexpr auto name = "Monster";
+ static constexpr auto fully_qualified_name = "MyGame.Example.Monster";
+ static constexpr size_t fields_number = 53;
+ static constexpr std::array<const char *, fields_number> field_names = {
+ "pos",
+ "mana",
+ "hp",
+ "name",
+ "inventory",
+ "color",
+ "test_type",
+ "test",
+ "test4",
+ "testarrayofstring",
+ "testarrayoftables",
+ "enemy",
+ "testnestedflatbuffer",
+ "testempty",
+ "testbool",
+ "testhashs32_fnv1",
+ "testhashu32_fnv1",
+ "testhashs64_fnv1",
+ "testhashu64_fnv1",
+ "testhashs32_fnv1a",
+ "testhashu32_fnv1a",
+ "testhashs64_fnv1a",
+ "testhashu64_fnv1a",
+ "testarrayofbools",
+ "testf",
+ "testf2",
+ "testf3",
+ "testarrayofstring2",
+ "testarrayofsortedstruct",
+ "flex",
+ "test5",
+ "vector_of_longs",
+ "vector_of_doubles",
+ "parent_namespace_test",
+ "vector_of_referrables",
+ "single_weak_reference",
+ "vector_of_weak_references",
+ "vector_of_strong_referrables",
+ "co_owning_reference",
+ "vector_of_co_owning_references",
+ "non_owning_reference",
+ "vector_of_non_owning_references",
+ "any_unique_type",
+ "any_unique",
+ "any_ambiguous_type",
+ "any_ambiguous",
+ "vector_of_enums",
+ "signed_enum",
+ "testrequirednestedflatbuffer",
+ "scalar_key_sorted_tables",
+ "native_inline",
+ "long_enum_non_enum_default",
+ "long_enum_normal_default"
+ };
+ template<size_t Index>
+ using FieldType = decltype(std::declval<type>().get_field<Index>());
};
inline flatbuffers::Offset<Monster> CreateMonsterDirect(
flatbuffers::FlatBufferBuilder &_fbb,
- const MyGame::Example::Vec3 *pos = 0,
+ const MyGame::Example::Vec3 *pos = nullptr,
int16_t mana = 150,
int16_t hp = 100,
const char *name = nullptr,
@@ -1844,7 +2273,11 @@
flatbuffers::Offset<void> any_ambiguous = 0,
const std::vector<MyGame::Example::Color> *vector_of_enums = nullptr,
MyGame::Example::Race signed_enum = MyGame::Example::Race::None,
- const std::vector<uint8_t> *testrequirednestedflatbuffer = nullptr) {
+ const std::vector<uint8_t> *testrequirednestedflatbuffer = nullptr,
+ std::vector<flatbuffers::Offset<MyGame::Example::Stat>> *scalar_key_sorted_tables = nullptr,
+ const MyGame::Example::Test *native_inline = nullptr,
+ MyGame::Example::LongEnum long_enum_non_enum_default = static_cast<MyGame::Example::LongEnum>(0),
+ MyGame::Example::LongEnum long_enum_normal_default = MyGame::Example::LongEnum::LongOne) {
auto name__ = name ? _fbb.CreateString(name) : 0;
auto inventory__ = inventory ? _fbb.CreateVector<uint8_t>(*inventory) : 0;
auto test4__ = test4 ? _fbb.CreateVectorOfStructs<MyGame::Example::Test>(*test4) : 0;
@@ -1865,6 +2298,7 @@
auto vector_of_non_owning_references__ = vector_of_non_owning_references ? _fbb.CreateVector<uint64_t>(*vector_of_non_owning_references) : 0;
auto vector_of_enums__ = vector_of_enums ? _fbb.CreateVector<MyGame::Example::Color>(*vector_of_enums) : 0;
auto testrequirednestedflatbuffer__ = testrequirednestedflatbuffer ? _fbb.CreateVector<uint8_t>(*testrequirednestedflatbuffer) : 0;
+ auto scalar_key_sorted_tables__ = scalar_key_sorted_tables ? _fbb.CreateVectorOfSortedTables<MyGame::Example::Stat>(scalar_key_sorted_tables) : 0;
return MyGame::Example::CreateMonster(
_fbb,
pos,
@@ -1915,7 +2349,11 @@
any_ambiguous,
vector_of_enums__,
signed_enum,
- testrequirednestedflatbuffer__);
+ testrequirednestedflatbuffer__,
+ scalar_key_sorted_tables__,
+ native_inline,
+ long_enum_non_enum_default,
+ long_enum_normal_default);
}
flatbuffers::Offset<Monster> CreateMonster(flatbuffers::FlatBufferBuilder &_fbb, const MonsterT *_o, const flatbuffers::rehasher_function_t *_rehasher = nullptr);
@@ -1960,61 +2398,61 @@
int8_t i8() const {
return GetField<int8_t>(VT_I8, 0);
}
- bool mutate_i8(int8_t _i8) {
+ bool mutate_i8(int8_t _i8 = 0) {
return SetField<int8_t>(VT_I8, _i8, 0);
}
uint8_t u8() const {
return GetField<uint8_t>(VT_U8, 0);
}
- bool mutate_u8(uint8_t _u8) {
+ bool mutate_u8(uint8_t _u8 = 0) {
return SetField<uint8_t>(VT_U8, _u8, 0);
}
int16_t i16() const {
return GetField<int16_t>(VT_I16, 0);
}
- bool mutate_i16(int16_t _i16) {
+ bool mutate_i16(int16_t _i16 = 0) {
return SetField<int16_t>(VT_I16, _i16, 0);
}
uint16_t u16() const {
return GetField<uint16_t>(VT_U16, 0);
}
- bool mutate_u16(uint16_t _u16) {
+ bool mutate_u16(uint16_t _u16 = 0) {
return SetField<uint16_t>(VT_U16, _u16, 0);
}
int32_t i32() const {
return GetField<int32_t>(VT_I32, 0);
}
- bool mutate_i32(int32_t _i32) {
+ bool mutate_i32(int32_t _i32 = 0) {
return SetField<int32_t>(VT_I32, _i32, 0);
}
uint32_t u32() const {
return GetField<uint32_t>(VT_U32, 0);
}
- bool mutate_u32(uint32_t _u32) {
+ bool mutate_u32(uint32_t _u32 = 0) {
return SetField<uint32_t>(VT_U32, _u32, 0);
}
int64_t i64() const {
return GetField<int64_t>(VT_I64, 0);
}
- bool mutate_i64(int64_t _i64) {
+ bool mutate_i64(int64_t _i64 = 0) {
return SetField<int64_t>(VT_I64, _i64, 0);
}
uint64_t u64() const {
return GetField<uint64_t>(VT_U64, 0);
}
- bool mutate_u64(uint64_t _u64) {
+ bool mutate_u64(uint64_t _u64 = 0) {
return SetField<uint64_t>(VT_U64, _u64, 0);
}
float f32() const {
return GetField<float>(VT_F32, 0.0f);
}
- bool mutate_f32(float _f32) {
+ bool mutate_f32(float _f32 = 0.0f) {
return SetField<float>(VT_F32, _f32, 0.0f);
}
double f64() const {
return GetField<double>(VT_F64, 0.0);
}
- bool mutate_f64(double _f64) {
+ bool mutate_f64(double _f64 = 0.0) {
return SetField<double>(VT_F64, _f64, 0.0);
}
const flatbuffers::Vector<int8_t> *v8() const {
@@ -2029,18 +2467,34 @@
flatbuffers::Vector<double> *mutable_vf64() {
return GetPointer<flatbuffers::Vector<double> *>(VT_VF64);
}
+ template<size_t Index>
+ auto get_field() const {
+ if constexpr (Index == 0) return i8();
+ else if constexpr (Index == 1) return u8();
+ else if constexpr (Index == 2) return i16();
+ else if constexpr (Index == 3) return u16();
+ else if constexpr (Index == 4) return i32();
+ else if constexpr (Index == 5) return u32();
+ else if constexpr (Index == 6) return i64();
+ else if constexpr (Index == 7) return u64();
+ else if constexpr (Index == 8) return f32();
+ else if constexpr (Index == 9) return f64();
+ else if constexpr (Index == 10) return v8();
+ else if constexpr (Index == 11) return vf64();
+ else static_assert(Index != Index, "Invalid Field Index");
+ }
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
- VerifyField<int8_t>(verifier, VT_I8) &&
- VerifyField<uint8_t>(verifier, VT_U8) &&
- VerifyField<int16_t>(verifier, VT_I16) &&
- VerifyField<uint16_t>(verifier, VT_U16) &&
- VerifyField<int32_t>(verifier, VT_I32) &&
- VerifyField<uint32_t>(verifier, VT_U32) &&
- VerifyField<int64_t>(verifier, VT_I64) &&
- VerifyField<uint64_t>(verifier, VT_U64) &&
- VerifyField<float>(verifier, VT_F32) &&
- VerifyField<double>(verifier, VT_F64) &&
+ VerifyField<int8_t>(verifier, VT_I8, 1) &&
+ VerifyField<uint8_t>(verifier, VT_U8, 1) &&
+ VerifyField<int16_t>(verifier, VT_I16, 2) &&
+ VerifyField<uint16_t>(verifier, VT_U16, 2) &&
+ VerifyField<int32_t>(verifier, VT_I32, 4) &&
+ VerifyField<uint32_t>(verifier, VT_U32, 4) &&
+ VerifyField<int64_t>(verifier, VT_I64, 8) &&
+ VerifyField<uint64_t>(verifier, VT_U64, 8) &&
+ VerifyField<float>(verifier, VT_F32, 4) &&
+ VerifyField<double>(verifier, VT_F64, 8) &&
VerifyOffset(verifier, VT_V8) &&
verifier.VerifyVector(v8()) &&
VerifyOffset(verifier, VT_VF64) &&
@@ -2136,6 +2590,25 @@
struct TypeAliases::Traits {
using type = TypeAliases;
static auto constexpr Create = CreateTypeAliases;
+ static constexpr auto name = "TypeAliases";
+ static constexpr auto fully_qualified_name = "MyGame.Example.TypeAliases";
+ static constexpr size_t fields_number = 12;
+ static constexpr std::array<const char *, fields_number> field_names = {
+ "i8",
+ "u8",
+ "i16",
+ "u16",
+ "i32",
+ "u32",
+ "i64",
+ "u64",
+ "f32",
+ "f64",
+ "v8",
+ "vf64"
+ };
+ template<size_t Index>
+ using FieldType = decltype(std::declval<type>().get_field<Index>());
};
inline flatbuffers::Offset<TypeAliases> CreateTypeAliasesDirect(
@@ -2310,6 +2783,118 @@
_id);
}
+inline MonsterT::MonsterT(const MonsterT &o)
+ : pos((o.pos) ? new MyGame::Example::Vec3(*o.pos) : nullptr),
+ mana(o.mana),
+ hp(o.hp),
+ name(o.name),
+ inventory(o.inventory),
+ color(o.color),
+ test(o.test),
+ test4(o.test4),
+ testarrayofstring(o.testarrayofstring),
+ enemy((o.enemy) ? new MyGame::Example::MonsterT(*o.enemy) : nullptr),
+ testnestedflatbuffer(o.testnestedflatbuffer),
+ testempty((o.testempty) ? new MyGame::Example::StatT(*o.testempty) : nullptr),
+ testbool(o.testbool),
+ testhashs32_fnv1(o.testhashs32_fnv1),
+ testhashu32_fnv1(o.testhashu32_fnv1),
+ testhashs64_fnv1(o.testhashs64_fnv1),
+ testhashu64_fnv1(o.testhashu64_fnv1),
+ testhashs32_fnv1a(o.testhashs32_fnv1a),
+ testhashu32_fnv1a(o.testhashu32_fnv1a),
+ testhashs64_fnv1a(o.testhashs64_fnv1a),
+ testhashu64_fnv1a(o.testhashu64_fnv1a),
+ testarrayofbools(o.testarrayofbools),
+ testf(o.testf),
+ testf2(o.testf2),
+ testf3(o.testf3),
+ testarrayofstring2(o.testarrayofstring2),
+ testarrayofsortedstruct(o.testarrayofsortedstruct),
+ flex(o.flex),
+ test5(o.test5),
+ vector_of_longs(o.vector_of_longs),
+ vector_of_doubles(o.vector_of_doubles),
+ parent_namespace_test((o.parent_namespace_test) ? new MyGame::InParentNamespaceT(*o.parent_namespace_test) : nullptr),
+ single_weak_reference(o.single_weak_reference),
+ vector_of_weak_references(o.vector_of_weak_references),
+ co_owning_reference(o.co_owning_reference),
+ non_owning_reference(o.non_owning_reference),
+ vector_of_non_owning_references(o.vector_of_non_owning_references),
+ any_unique(o.any_unique),
+ any_ambiguous(o.any_ambiguous),
+ vector_of_enums(o.vector_of_enums),
+ signed_enum(o.signed_enum),
+ testrequirednestedflatbuffer(o.testrequirednestedflatbuffer),
+ native_inline(o.native_inline),
+ long_enum_non_enum_default(o.long_enum_non_enum_default),
+ long_enum_normal_default(o.long_enum_normal_default) {
+ testarrayoftables.reserve(o.testarrayoftables.size());
+ for (const auto &testarrayoftables_ : o.testarrayoftables) { testarrayoftables.emplace_back((testarrayoftables_) ? new MyGame::Example::MonsterT(*testarrayoftables_) : nullptr); }
+ vector_of_referrables.reserve(o.vector_of_referrables.size());
+ for (const auto &vector_of_referrables_ : o.vector_of_referrables) { vector_of_referrables.emplace_back((vector_of_referrables_) ? new MyGame::Example::ReferrableT(*vector_of_referrables_) : nullptr); }
+ vector_of_strong_referrables.reserve(o.vector_of_strong_referrables.size());
+ for (const auto &vector_of_strong_referrables_ : o.vector_of_strong_referrables) { vector_of_strong_referrables.emplace_back((vector_of_strong_referrables_) ? new MyGame::Example::ReferrableT(*vector_of_strong_referrables_) : nullptr); }
+ vector_of_co_owning_references.reserve(o.vector_of_co_owning_references.size());
+ for (const auto &vector_of_co_owning_references_ : o.vector_of_co_owning_references) { vector_of_co_owning_references.emplace_back((vector_of_co_owning_references_) ? new ReferrableT(*vector_of_co_owning_references_) : nullptr); }
+ scalar_key_sorted_tables.reserve(o.scalar_key_sorted_tables.size());
+ for (const auto &scalar_key_sorted_tables_ : o.scalar_key_sorted_tables) { scalar_key_sorted_tables.emplace_back((scalar_key_sorted_tables_) ? new MyGame::Example::StatT(*scalar_key_sorted_tables_) : nullptr); }
+}
+
+inline MonsterT &MonsterT::operator=(MonsterT o) FLATBUFFERS_NOEXCEPT {
+ std::swap(pos, o.pos);
+ std::swap(mana, o.mana);
+ std::swap(hp, o.hp);
+ std::swap(name, o.name);
+ std::swap(inventory, o.inventory);
+ std::swap(color, o.color);
+ std::swap(test, o.test);
+ std::swap(test4, o.test4);
+ std::swap(testarrayofstring, o.testarrayofstring);
+ std::swap(testarrayoftables, o.testarrayoftables);
+ std::swap(enemy, o.enemy);
+ std::swap(testnestedflatbuffer, o.testnestedflatbuffer);
+ std::swap(testempty, o.testempty);
+ std::swap(testbool, o.testbool);
+ std::swap(testhashs32_fnv1, o.testhashs32_fnv1);
+ std::swap(testhashu32_fnv1, o.testhashu32_fnv1);
+ std::swap(testhashs64_fnv1, o.testhashs64_fnv1);
+ std::swap(testhashu64_fnv1, o.testhashu64_fnv1);
+ std::swap(testhashs32_fnv1a, o.testhashs32_fnv1a);
+ std::swap(testhashu32_fnv1a, o.testhashu32_fnv1a);
+ std::swap(testhashs64_fnv1a, o.testhashs64_fnv1a);
+ std::swap(testhashu64_fnv1a, o.testhashu64_fnv1a);
+ std::swap(testarrayofbools, o.testarrayofbools);
+ std::swap(testf, o.testf);
+ std::swap(testf2, o.testf2);
+ std::swap(testf3, o.testf3);
+ std::swap(testarrayofstring2, o.testarrayofstring2);
+ std::swap(testarrayofsortedstruct, o.testarrayofsortedstruct);
+ std::swap(flex, o.flex);
+ std::swap(test5, o.test5);
+ std::swap(vector_of_longs, o.vector_of_longs);
+ std::swap(vector_of_doubles, o.vector_of_doubles);
+ std::swap(parent_namespace_test, o.parent_namespace_test);
+ std::swap(vector_of_referrables, o.vector_of_referrables);
+ std::swap(single_weak_reference, o.single_weak_reference);
+ std::swap(vector_of_weak_references, o.vector_of_weak_references);
+ std::swap(vector_of_strong_referrables, o.vector_of_strong_referrables);
+ std::swap(co_owning_reference, o.co_owning_reference);
+ std::swap(vector_of_co_owning_references, o.vector_of_co_owning_references);
+ std::swap(non_owning_reference, o.non_owning_reference);
+ std::swap(vector_of_non_owning_references, o.vector_of_non_owning_references);
+ std::swap(any_unique, o.any_unique);
+ std::swap(any_ambiguous, o.any_ambiguous);
+ std::swap(vector_of_enums, o.vector_of_enums);
+ std::swap(signed_enum, o.signed_enum);
+ std::swap(testrequirednestedflatbuffer, o.testrequirednestedflatbuffer);
+ std::swap(scalar_key_sorted_tables, o.scalar_key_sorted_tables);
+ std::swap(native_inline, o.native_inline);
+ std::swap(long_enum_non_enum_default, o.long_enum_non_enum_default);
+ std::swap(long_enum_normal_default, o.long_enum_normal_default);
+ return *this;
+}
+
inline MonsterT *Monster::UnPack(const flatbuffers::resolver_function_t *_resolver) const {
auto _o = std::make_unique<MonsterT>();
UnPackTo(_o.get(), _resolver);
@@ -2329,10 +2914,10 @@
{ auto _e = test(); if (_e) _o->test.value = MyGame::Example::AnyUnion::UnPack(_e, test_type(), _resolver); }
{ auto _e = test4(); if (_e) { _o->test4.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->test4[_i] = *_e->Get(_i); } } }
{ auto _e = testarrayofstring(); if (_e) { _o->testarrayofstring.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->testarrayofstring[_i] = _e->Get(_i)->str(); } } }
- { auto _e = testarrayoftables(); if (_e) { _o->testarrayoftables.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->testarrayoftables[_i] = std::unique_ptr<MyGame::Example::MonsterT>(_e->Get(_i)->UnPack(_resolver)); } } }
- { auto _e = enemy(); if (_e) _o->enemy = std::unique_ptr<MyGame::Example::MonsterT>(_e->UnPack(_resolver)); }
+ { auto _e = testarrayoftables(); if (_e) { _o->testarrayoftables.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { if(_o->testarrayoftables[_i]) { _e->Get(_i)->UnPackTo(_o->testarrayoftables[_i].get(), _resolver); } else { _o->testarrayoftables[_i] = std::unique_ptr<MyGame::Example::MonsterT>(_e->Get(_i)->UnPack(_resolver)); }; } } }
+ { auto _e = enemy(); if (_e) { if(_o->enemy) { _e->UnPackTo(_o->enemy.get(), _resolver); } else { _o->enemy = std::unique_ptr<MyGame::Example::MonsterT>(_e->UnPack(_resolver)); } } }
{ auto _e = testnestedflatbuffer(); if (_e) { _o->testnestedflatbuffer.resize(_e->size()); std::copy(_e->begin(), _e->end(), _o->testnestedflatbuffer.begin()); } }
- { auto _e = testempty(); if (_e) _o->testempty = std::unique_ptr<MyGame::Example::StatT>(_e->UnPack(_resolver)); }
+ { auto _e = testempty(); if (_e) { if(_o->testempty) { _e->UnPackTo(_o->testempty.get(), _resolver); } else { _o->testempty = std::unique_ptr<MyGame::Example::StatT>(_e->UnPack(_resolver)); } } }
{ auto _e = testbool(); _o->testbool = _e; }
{ auto _e = testhashs32_fnv1(); _o->testhashs32_fnv1 = _e; }
{ auto _e = testhashu32_fnv1(); _o->testhashu32_fnv1 = _e; }
@@ -2353,13 +2938,13 @@
{ auto _e = test5(); if (_e) { _o->test5.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->test5[_i] = *_e->Get(_i); } } }
{ auto _e = vector_of_longs(); if (_e) { _o->vector_of_longs.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->vector_of_longs[_i] = _e->Get(_i); } } }
{ auto _e = vector_of_doubles(); if (_e) { _o->vector_of_doubles.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->vector_of_doubles[_i] = _e->Get(_i); } } }
- { auto _e = parent_namespace_test(); if (_e) _o->parent_namespace_test = std::unique_ptr<MyGame::InParentNamespaceT>(_e->UnPack(_resolver)); }
- { auto _e = vector_of_referrables(); if (_e) { _o->vector_of_referrables.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->vector_of_referrables[_i] = std::unique_ptr<MyGame::Example::ReferrableT>(_e->Get(_i)->UnPack(_resolver)); } } }
+ { auto _e = parent_namespace_test(); if (_e) { if(_o->parent_namespace_test) { _e->UnPackTo(_o->parent_namespace_test.get(), _resolver); } else { _o->parent_namespace_test = std::unique_ptr<MyGame::InParentNamespaceT>(_e->UnPack(_resolver)); } } }
+ { auto _e = vector_of_referrables(); if (_e) { _o->vector_of_referrables.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { if(_o->vector_of_referrables[_i]) { _e->Get(_i)->UnPackTo(_o->vector_of_referrables[_i].get(), _resolver); } else { _o->vector_of_referrables[_i] = std::unique_ptr<MyGame::Example::ReferrableT>(_e->Get(_i)->UnPack(_resolver)); }; } } }
{ auto _e = single_weak_reference(); //scalar resolver, naked
if (_resolver) (*_resolver)(reinterpret_cast<void **>(&_o->single_weak_reference), static_cast<flatbuffers::hash_value_t>(_e)); else _o->single_weak_reference = nullptr; }
{ auto _e = vector_of_weak_references(); if (_e) { _o->vector_of_weak_references.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { //vector resolver, naked
if (_resolver) (*_resolver)(reinterpret_cast<void **>(&_o->vector_of_weak_references[_i]), static_cast<flatbuffers::hash_value_t>(_e->Get(_i))); else _o->vector_of_weak_references[_i] = nullptr; } } }
- { auto _e = vector_of_strong_referrables(); if (_e) { _o->vector_of_strong_referrables.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->vector_of_strong_referrables[_i] = std::unique_ptr<MyGame::Example::ReferrableT>(_e->Get(_i)->UnPack(_resolver)); } } }
+ { auto _e = vector_of_strong_referrables(); if (_e) { _o->vector_of_strong_referrables.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { if(_o->vector_of_strong_referrables[_i]) { _e->Get(_i)->UnPackTo(_o->vector_of_strong_referrables[_i].get(), _resolver); } else { _o->vector_of_strong_referrables[_i] = std::unique_ptr<MyGame::Example::ReferrableT>(_e->Get(_i)->UnPack(_resolver)); }; } } }
{ auto _e = co_owning_reference(); //scalar resolver, naked
if (_resolver) (*_resolver)(reinterpret_cast<void **>(&_o->co_owning_reference), static_cast<flatbuffers::hash_value_t>(_e)); else _o->co_owning_reference = nullptr; }
{ auto _e = vector_of_co_owning_references(); if (_e) { _o->vector_of_co_owning_references.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { //vector resolver, default_ptr_type
@@ -2375,6 +2960,10 @@
{ auto _e = vector_of_enums(); if (_e) { _o->vector_of_enums.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->vector_of_enums[_i] = static_cast<MyGame::Example::Color>(_e->Get(_i)); } } }
{ auto _e = signed_enum(); _o->signed_enum = _e; }
{ auto _e = testrequirednestedflatbuffer(); if (_e) { _o->testrequirednestedflatbuffer.resize(_e->size()); std::copy(_e->begin(), _e->end(), _o->testrequirednestedflatbuffer.begin()); } }
+ { auto _e = scalar_key_sorted_tables(); if (_e) { _o->scalar_key_sorted_tables.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { if(_o->scalar_key_sorted_tables[_i]) { _e->Get(_i)->UnPackTo(_o->scalar_key_sorted_tables[_i].get(), _resolver); } else { _o->scalar_key_sorted_tables[_i] = std::unique_ptr<MyGame::Example::StatT>(_e->Get(_i)->UnPack(_resolver)); }; } } }
+ { auto _e = native_inline(); if (_e) _o->native_inline = *_e; }
+ { auto _e = long_enum_non_enum_default(); _o->long_enum_non_enum_default = _e; }
+ { auto _e = long_enum_normal_default(); _o->long_enum_normal_default = _e; }
}
inline flatbuffers::Offset<Monster> Monster::Pack(flatbuffers::FlatBufferBuilder &_fbb, const MonsterT* _o, const flatbuffers::rehasher_function_t *_rehasher) {
@@ -2434,6 +3023,10 @@
auto _vector_of_enums = _o->vector_of_enums.size() ? _fbb.CreateVector(_o->vector_of_enums) : 0;
auto _signed_enum = _o->signed_enum;
auto _testrequirednestedflatbuffer = _o->testrequirednestedflatbuffer.size() ? _fbb.CreateVector(_o->testrequirednestedflatbuffer) : 0;
+ auto _scalar_key_sorted_tables = _o->scalar_key_sorted_tables.size() ? _fbb.CreateVector<flatbuffers::Offset<MyGame::Example::Stat>> (_o->scalar_key_sorted_tables.size(), [](size_t i, _VectorArgs *__va) { return CreateStat(*__va->__fbb, __va->__o->scalar_key_sorted_tables[i].get(), __va->__rehasher); }, &_va ) : 0;
+ auto _native_inline = &_o->native_inline;
+ auto _long_enum_non_enum_default = _o->long_enum_non_enum_default;
+ auto _long_enum_normal_default = _o->long_enum_normal_default;
return MyGame::Example::CreateMonster(
_fbb,
_pos,
@@ -2484,7 +3077,11 @@
_any_ambiguous,
_vector_of_enums,
_signed_enum,
- _testrequirednestedflatbuffer);
+ _testrequirednestedflatbuffer,
+ _scalar_key_sorted_tables,
+ _native_inline,
+ _long_enum_non_enum_default,
+ _long_enum_normal_default);
}
inline TypeAliasesT *TypeAliases::UnPack(const flatbuffers::resolver_function_t *_resolver) const {
@@ -2567,7 +3164,7 @@
}
}
-inline bool VerifyAnyVector(flatbuffers::Verifier &verifier, const flatbuffers::Vector<flatbuffers::Offset<void>> *values, const flatbuffers::Vector<uint8_t> *types) {
+inline bool VerifyAnyVector(flatbuffers::Verifier &verifier, const flatbuffers::Vector<flatbuffers::Offset<void>> *values, const flatbuffers::Vector<Any> *types) {
if (!values || !types) return !values && !types;
if (values->size() != types->size()) return false;
for (flatbuffers::uoffset_t i = 0; i < values->size(); ++i) {
@@ -2580,6 +3177,7 @@
}
inline void *AnyUnion::UnPack(const void *obj, Any type, const flatbuffers::resolver_function_t *resolver) {
+ (void)resolver;
switch (type) {
case Any::Monster: {
auto ptr = reinterpret_cast<const MyGame::Example::Monster *>(obj);
@@ -2598,6 +3196,7 @@
}
inline flatbuffers::Offset<void> AnyUnion::Pack(flatbuffers::FlatBufferBuilder &_fbb, const flatbuffers::rehasher_function_t *_rehasher) const {
+ (void)_rehasher;
switch (type) {
case Any::Monster: {
auto ptr = reinterpret_cast<const MyGame::Example::MonsterT *>(value);
@@ -2618,7 +3217,7 @@
inline AnyUnion::AnyUnion(const AnyUnion &u) : type(u.type), value(nullptr) {
switch (type) {
case Any::Monster: {
- FLATBUFFERS_ASSERT(false); // MyGame::Example::MonsterT not copyable.
+ value = new MyGame::Example::MonsterT(*reinterpret_cast<MyGame::Example::MonsterT *>(u.value));
break;
}
case Any::TestSimpleTableWithEnum: {
@@ -2678,7 +3277,7 @@
}
}
-inline bool VerifyAnyUniqueAliasesVector(flatbuffers::Verifier &verifier, const flatbuffers::Vector<flatbuffers::Offset<void>> *values, const flatbuffers::Vector<uint8_t> *types) {
+inline bool VerifyAnyUniqueAliasesVector(flatbuffers::Verifier &verifier, const flatbuffers::Vector<flatbuffers::Offset<void>> *values, const flatbuffers::Vector<AnyUniqueAliases> *types) {
if (!values || !types) return !values && !types;
if (values->size() != types->size()) return false;
for (flatbuffers::uoffset_t i = 0; i < values->size(); ++i) {
@@ -2691,6 +3290,7 @@
}
inline void *AnyUniqueAliasesUnion::UnPack(const void *obj, AnyUniqueAliases type, const flatbuffers::resolver_function_t *resolver) {
+ (void)resolver;
switch (type) {
case AnyUniqueAliases::M: {
auto ptr = reinterpret_cast<const MyGame::Example::Monster *>(obj);
@@ -2709,6 +3309,7 @@
}
inline flatbuffers::Offset<void> AnyUniqueAliasesUnion::Pack(flatbuffers::FlatBufferBuilder &_fbb, const flatbuffers::rehasher_function_t *_rehasher) const {
+ (void)_rehasher;
switch (type) {
case AnyUniqueAliases::M: {
auto ptr = reinterpret_cast<const MyGame::Example::MonsterT *>(value);
@@ -2729,7 +3330,7 @@
inline AnyUniqueAliasesUnion::AnyUniqueAliasesUnion(const AnyUniqueAliasesUnion &u) : type(u.type), value(nullptr) {
switch (type) {
case AnyUniqueAliases::M: {
- FLATBUFFERS_ASSERT(false); // MyGame::Example::MonsterT not copyable.
+ value = new MyGame::Example::MonsterT(*reinterpret_cast<MyGame::Example::MonsterT *>(u.value));
break;
}
case AnyUniqueAliases::TS: {
@@ -2789,7 +3390,7 @@
}
}
-inline bool VerifyAnyAmbiguousAliasesVector(flatbuffers::Verifier &verifier, const flatbuffers::Vector<flatbuffers::Offset<void>> *values, const flatbuffers::Vector<uint8_t> *types) {
+inline bool VerifyAnyAmbiguousAliasesVector(flatbuffers::Verifier &verifier, const flatbuffers::Vector<flatbuffers::Offset<void>> *values, const flatbuffers::Vector<AnyAmbiguousAliases> *types) {
if (!values || !types) return !values && !types;
if (values->size() != types->size()) return false;
for (flatbuffers::uoffset_t i = 0; i < values->size(); ++i) {
@@ -2802,6 +3403,7 @@
}
inline void *AnyAmbiguousAliasesUnion::UnPack(const void *obj, AnyAmbiguousAliases type, const flatbuffers::resolver_function_t *resolver) {
+ (void)resolver;
switch (type) {
case AnyAmbiguousAliases::M1: {
auto ptr = reinterpret_cast<const MyGame::Example::Monster *>(obj);
@@ -2820,6 +3422,7 @@
}
inline flatbuffers::Offset<void> AnyAmbiguousAliasesUnion::Pack(flatbuffers::FlatBufferBuilder &_fbb, const flatbuffers::rehasher_function_t *_rehasher) const {
+ (void)_rehasher;
switch (type) {
case AnyAmbiguousAliases::M1: {
auto ptr = reinterpret_cast<const MyGame::Example::MonsterT *>(value);
@@ -2840,15 +3443,15 @@
inline AnyAmbiguousAliasesUnion::AnyAmbiguousAliasesUnion(const AnyAmbiguousAliasesUnion &u) : type(u.type), value(nullptr) {
switch (type) {
case AnyAmbiguousAliases::M1: {
- FLATBUFFERS_ASSERT(false); // MyGame::Example::MonsterT not copyable.
+ value = new MyGame::Example::MonsterT(*reinterpret_cast<MyGame::Example::MonsterT *>(u.value));
break;
}
case AnyAmbiguousAliases::M2: {
- FLATBUFFERS_ASSERT(false); // MyGame::Example::MonsterT not copyable.
+ value = new MyGame::Example::MonsterT(*reinterpret_cast<MyGame::Example::MonsterT *>(u.value));
break;
}
case AnyAmbiguousAliases::M3: {
- FLATBUFFERS_ASSERT(false); // MyGame::Example::MonsterT not copyable.
+ value = new MyGame::Example::MonsterT(*reinterpret_cast<MyGame::Example::MonsterT *>(u.value));
break;
}
default:
@@ -2923,6 +3526,27 @@
return &tt;
}
+inline const flatbuffers::TypeTable *LongEnumTypeTable() {
+ static const flatbuffers::TypeCode type_codes[] = {
+ { flatbuffers::ET_ULONG, 0, 0 },
+ { flatbuffers::ET_ULONG, 0, 0 },
+ { flatbuffers::ET_ULONG, 0, 0 }
+ };
+ static const flatbuffers::TypeFunction type_refs[] = {
+ MyGame::Example::LongEnumTypeTable
+ };
+ static const int64_t values[] = { 2ULL, 4ULL, 1099511627776ULL };
+ static const char * const names[] = {
+ "LongOne",
+ "LongTwo",
+ "LongBig"
+ };
+ static const flatbuffers::TypeTable tt = {
+ flatbuffers::ST_ENUM, 3, type_codes, type_refs, nullptr, values, names
+ };
+ return &tt;
+}
+
inline const flatbuffers::TypeTable *AnyTypeTable() {
static const flatbuffers::TypeCode type_codes[] = {
{ flatbuffers::ET_SEQUENCE, 0, -1 },
@@ -3091,6 +3715,28 @@
return &tt;
}
+inline const flatbuffers::TypeTable *StructOfStructsTypeTable() {
+ static const flatbuffers::TypeCode type_codes[] = {
+ { flatbuffers::ET_SEQUENCE, 0, 0 },
+ { flatbuffers::ET_SEQUENCE, 0, 1 },
+ { flatbuffers::ET_SEQUENCE, 0, 0 }
+ };
+ static const flatbuffers::TypeFunction type_refs[] = {
+ MyGame::Example::AbilityTypeTable,
+ MyGame::Example::TestTypeTable
+ };
+ static const int64_t values[] = { 0, 8, 12, 20 };
+ static const char * const names[] = {
+ "a",
+ "b",
+ "c"
+ };
+ static const flatbuffers::TypeTable tt = {
+ flatbuffers::ST_STRUCT, 3, type_codes, type_refs, nullptr, values, names
+ };
+ return &tt;
+}
+
inline const flatbuffers::TypeTable *StatTypeTable() {
static const flatbuffers::TypeCode type_codes[] = {
{ flatbuffers::ET_STRING, 0, -1 },
@@ -3172,7 +3818,11 @@
{ flatbuffers::ET_SEQUENCE, 0, 10 },
{ flatbuffers::ET_UCHAR, 1, 1 },
{ flatbuffers::ET_CHAR, 0, 11 },
- { flatbuffers::ET_UCHAR, 1, -1 }
+ { flatbuffers::ET_UCHAR, 1, -1 },
+ { flatbuffers::ET_SEQUENCE, 1, 5 },
+ { flatbuffers::ET_SEQUENCE, 0, 3 },
+ { flatbuffers::ET_ULONG, 0, 12 },
+ { flatbuffers::ET_ULONG, 0, 12 }
};
static const flatbuffers::TypeFunction type_refs[] = {
MyGame::Example::Vec3TypeTable,
@@ -3186,7 +3836,8 @@
MyGame::Example::ReferrableTypeTable,
MyGame::Example::AnyUniqueAliasesTypeTable,
MyGame::Example::AnyAmbiguousAliasesTypeTable,
- MyGame::Example::RaceTypeTable
+ MyGame::Example::RaceTypeTable,
+ MyGame::Example::LongEnumTypeTable
};
static const char * const names[] = {
"pos",
@@ -3238,10 +3889,14 @@
"any_ambiguous",
"vector_of_enums",
"signed_enum",
- "testrequirednestedflatbuffer"
+ "testrequirednestedflatbuffer",
+ "scalar_key_sorted_tables",
+ "native_inline",
+ "long_enum_non_enum_default",
+ "long_enum_normal_default"
};
static const flatbuffers::TypeTable tt = {
- flatbuffers::ST_TABLE, 50, type_codes, type_refs, nullptr, nullptr, names
+ flatbuffers::ST_TABLE, 54, type_codes, type_refs, nullptr, nullptr, names
};
return &tt;
}
@@ -3293,6 +3948,10 @@
return flatbuffers::GetMutableRoot<Monster>(buf);
}
+inline MyGame::Example::Monster *GetMutableSizePrefixedMonster(void *buf) {
+ return flatbuffers::GetMutableSizePrefixedRoot<MyGame::Example::Monster>(buf);
+}
+
inline const char *MonsterIdentifier() {
return "MONS";
}
@@ -3302,6 +3961,11 @@
buf, MonsterIdentifier());
}
+inline bool SizePrefixedMonsterBufferHasIdentifier(const void *buf) {
+ return flatbuffers::BufferHasIdentifier(
+ buf, MonsterIdentifier(), true);
+}
+
inline bool VerifyMonsterBuffer(
flatbuffers::Verifier &verifier) {
return verifier.VerifyBuffer<MyGame::Example::Monster>(MonsterIdentifier());
diff --git a/tests/cpp17/generated_cpp17/optional_scalars_generated.h b/tests/cpp17/generated_cpp17/optional_scalars_generated.h
index 7581e38..24b5ccd 100644
--- a/tests/cpp17/generated_cpp17/optional_scalars_generated.h
+++ b/tests/cpp17/generated_cpp17/optional_scalars_generated.h
@@ -135,7 +135,7 @@
int8_t just_i8() const {
return GetField<int8_t>(VT_JUST_I8, 0);
}
- bool mutate_just_i8(int8_t _just_i8) {
+ bool mutate_just_i8(int8_t _just_i8 = 0) {
return SetField<int8_t>(VT_JUST_I8, _just_i8, 0);
}
flatbuffers::Optional<int8_t> maybe_i8() const {
@@ -147,13 +147,13 @@
int8_t default_i8() const {
return GetField<int8_t>(VT_DEFAULT_I8, 42);
}
- bool mutate_default_i8(int8_t _default_i8) {
+ bool mutate_default_i8(int8_t _default_i8 = 42) {
return SetField<int8_t>(VT_DEFAULT_I8, _default_i8, 42);
}
uint8_t just_u8() const {
return GetField<uint8_t>(VT_JUST_U8, 0);
}
- bool mutate_just_u8(uint8_t _just_u8) {
+ bool mutate_just_u8(uint8_t _just_u8 = 0) {
return SetField<uint8_t>(VT_JUST_U8, _just_u8, 0);
}
flatbuffers::Optional<uint8_t> maybe_u8() const {
@@ -165,13 +165,13 @@
uint8_t default_u8() const {
return GetField<uint8_t>(VT_DEFAULT_U8, 42);
}
- bool mutate_default_u8(uint8_t _default_u8) {
+ bool mutate_default_u8(uint8_t _default_u8 = 42) {
return SetField<uint8_t>(VT_DEFAULT_U8, _default_u8, 42);
}
int16_t just_i16() const {
return GetField<int16_t>(VT_JUST_I16, 0);
}
- bool mutate_just_i16(int16_t _just_i16) {
+ bool mutate_just_i16(int16_t _just_i16 = 0) {
return SetField<int16_t>(VT_JUST_I16, _just_i16, 0);
}
flatbuffers::Optional<int16_t> maybe_i16() const {
@@ -183,13 +183,13 @@
int16_t default_i16() const {
return GetField<int16_t>(VT_DEFAULT_I16, 42);
}
- bool mutate_default_i16(int16_t _default_i16) {
+ bool mutate_default_i16(int16_t _default_i16 = 42) {
return SetField<int16_t>(VT_DEFAULT_I16, _default_i16, 42);
}
uint16_t just_u16() const {
return GetField<uint16_t>(VT_JUST_U16, 0);
}
- bool mutate_just_u16(uint16_t _just_u16) {
+ bool mutate_just_u16(uint16_t _just_u16 = 0) {
return SetField<uint16_t>(VT_JUST_U16, _just_u16, 0);
}
flatbuffers::Optional<uint16_t> maybe_u16() const {
@@ -201,13 +201,13 @@
uint16_t default_u16() const {
return GetField<uint16_t>(VT_DEFAULT_U16, 42);
}
- bool mutate_default_u16(uint16_t _default_u16) {
+ bool mutate_default_u16(uint16_t _default_u16 = 42) {
return SetField<uint16_t>(VT_DEFAULT_U16, _default_u16, 42);
}
int32_t just_i32() const {
return GetField<int32_t>(VT_JUST_I32, 0);
}
- bool mutate_just_i32(int32_t _just_i32) {
+ bool mutate_just_i32(int32_t _just_i32 = 0) {
return SetField<int32_t>(VT_JUST_I32, _just_i32, 0);
}
flatbuffers::Optional<int32_t> maybe_i32() const {
@@ -219,13 +219,13 @@
int32_t default_i32() const {
return GetField<int32_t>(VT_DEFAULT_I32, 42);
}
- bool mutate_default_i32(int32_t _default_i32) {
+ bool mutate_default_i32(int32_t _default_i32 = 42) {
return SetField<int32_t>(VT_DEFAULT_I32, _default_i32, 42);
}
uint32_t just_u32() const {
return GetField<uint32_t>(VT_JUST_U32, 0);
}
- bool mutate_just_u32(uint32_t _just_u32) {
+ bool mutate_just_u32(uint32_t _just_u32 = 0) {
return SetField<uint32_t>(VT_JUST_U32, _just_u32, 0);
}
flatbuffers::Optional<uint32_t> maybe_u32() const {
@@ -237,13 +237,13 @@
uint32_t default_u32() const {
return GetField<uint32_t>(VT_DEFAULT_U32, 42);
}
- bool mutate_default_u32(uint32_t _default_u32) {
+ bool mutate_default_u32(uint32_t _default_u32 = 42) {
return SetField<uint32_t>(VT_DEFAULT_U32, _default_u32, 42);
}
int64_t just_i64() const {
return GetField<int64_t>(VT_JUST_I64, 0);
}
- bool mutate_just_i64(int64_t _just_i64) {
+ bool mutate_just_i64(int64_t _just_i64 = 0) {
return SetField<int64_t>(VT_JUST_I64, _just_i64, 0);
}
flatbuffers::Optional<int64_t> maybe_i64() const {
@@ -255,13 +255,13 @@
int64_t default_i64() const {
return GetField<int64_t>(VT_DEFAULT_I64, 42LL);
}
- bool mutate_default_i64(int64_t _default_i64) {
+ bool mutate_default_i64(int64_t _default_i64 = 42LL) {
return SetField<int64_t>(VT_DEFAULT_I64, _default_i64, 42LL);
}
uint64_t just_u64() const {
return GetField<uint64_t>(VT_JUST_U64, 0);
}
- bool mutate_just_u64(uint64_t _just_u64) {
+ bool mutate_just_u64(uint64_t _just_u64 = 0) {
return SetField<uint64_t>(VT_JUST_U64, _just_u64, 0);
}
flatbuffers::Optional<uint64_t> maybe_u64() const {
@@ -273,13 +273,13 @@
uint64_t default_u64() const {
return GetField<uint64_t>(VT_DEFAULT_U64, 42ULL);
}
- bool mutate_default_u64(uint64_t _default_u64) {
+ bool mutate_default_u64(uint64_t _default_u64 = 42ULL) {
return SetField<uint64_t>(VT_DEFAULT_U64, _default_u64, 42ULL);
}
float just_f32() const {
return GetField<float>(VT_JUST_F32, 0.0f);
}
- bool mutate_just_f32(float _just_f32) {
+ bool mutate_just_f32(float _just_f32 = 0.0f) {
return SetField<float>(VT_JUST_F32, _just_f32, 0.0f);
}
flatbuffers::Optional<float> maybe_f32() const {
@@ -291,13 +291,13 @@
float default_f32() const {
return GetField<float>(VT_DEFAULT_F32, 42.0f);
}
- bool mutate_default_f32(float _default_f32) {
+ bool mutate_default_f32(float _default_f32 = 42.0f) {
return SetField<float>(VT_DEFAULT_F32, _default_f32, 42.0f);
}
double just_f64() const {
return GetField<double>(VT_JUST_F64, 0.0);
}
- bool mutate_just_f64(double _just_f64) {
+ bool mutate_just_f64(double _just_f64 = 0.0) {
return SetField<double>(VT_JUST_F64, _just_f64, 0.0);
}
flatbuffers::Optional<double> maybe_f64() const {
@@ -309,13 +309,13 @@
double default_f64() const {
return GetField<double>(VT_DEFAULT_F64, 42.0);
}
- bool mutate_default_f64(double _default_f64) {
+ bool mutate_default_f64(double _default_f64 = 42.0) {
return SetField<double>(VT_DEFAULT_F64, _default_f64, 42.0);
}
bool just_bool() const {
return GetField<uint8_t>(VT_JUST_BOOL, 0) != 0;
}
- bool mutate_just_bool(bool _just_bool) {
+ bool mutate_just_bool(bool _just_bool = 0) {
return SetField<uint8_t>(VT_JUST_BOOL, static_cast<uint8_t>(_just_bool), 0);
}
flatbuffers::Optional<bool> maybe_bool() const {
@@ -327,13 +327,13 @@
bool default_bool() const {
return GetField<uint8_t>(VT_DEFAULT_BOOL, 1) != 0;
}
- bool mutate_default_bool(bool _default_bool) {
+ bool mutate_default_bool(bool _default_bool = 1) {
return SetField<uint8_t>(VT_DEFAULT_BOOL, static_cast<uint8_t>(_default_bool), 1);
}
optional_scalars::OptionalByte just_enum() const {
return static_cast<optional_scalars::OptionalByte>(GetField<int8_t>(VT_JUST_ENUM, 0));
}
- bool mutate_just_enum(optional_scalars::OptionalByte _just_enum) {
+ bool mutate_just_enum(optional_scalars::OptionalByte _just_enum = static_cast<optional_scalars::OptionalByte>(0)) {
return SetField<int8_t>(VT_JUST_ENUM, static_cast<int8_t>(_just_enum), 0);
}
flatbuffers::Optional<optional_scalars::OptionalByte> maybe_enum() const {
@@ -345,47 +345,87 @@
optional_scalars::OptionalByte default_enum() const {
return static_cast<optional_scalars::OptionalByte>(GetField<int8_t>(VT_DEFAULT_ENUM, 1));
}
- bool mutate_default_enum(optional_scalars::OptionalByte _default_enum) {
+ bool mutate_default_enum(optional_scalars::OptionalByte _default_enum = static_cast<optional_scalars::OptionalByte>(1)) {
return SetField<int8_t>(VT_DEFAULT_ENUM, static_cast<int8_t>(_default_enum), 1);
}
+ template<size_t Index>
+ auto get_field() const {
+ if constexpr (Index == 0) return just_i8();
+ else if constexpr (Index == 1) return maybe_i8();
+ else if constexpr (Index == 2) return default_i8();
+ else if constexpr (Index == 3) return just_u8();
+ else if constexpr (Index == 4) return maybe_u8();
+ else if constexpr (Index == 5) return default_u8();
+ else if constexpr (Index == 6) return just_i16();
+ else if constexpr (Index == 7) return maybe_i16();
+ else if constexpr (Index == 8) return default_i16();
+ else if constexpr (Index == 9) return just_u16();
+ else if constexpr (Index == 10) return maybe_u16();
+ else if constexpr (Index == 11) return default_u16();
+ else if constexpr (Index == 12) return just_i32();
+ else if constexpr (Index == 13) return maybe_i32();
+ else if constexpr (Index == 14) return default_i32();
+ else if constexpr (Index == 15) return just_u32();
+ else if constexpr (Index == 16) return maybe_u32();
+ else if constexpr (Index == 17) return default_u32();
+ else if constexpr (Index == 18) return just_i64();
+ else if constexpr (Index == 19) return maybe_i64();
+ else if constexpr (Index == 20) return default_i64();
+ else if constexpr (Index == 21) return just_u64();
+ else if constexpr (Index == 22) return maybe_u64();
+ else if constexpr (Index == 23) return default_u64();
+ else if constexpr (Index == 24) return just_f32();
+ else if constexpr (Index == 25) return maybe_f32();
+ else if constexpr (Index == 26) return default_f32();
+ else if constexpr (Index == 27) return just_f64();
+ else if constexpr (Index == 28) return maybe_f64();
+ else if constexpr (Index == 29) return default_f64();
+ else if constexpr (Index == 30) return just_bool();
+ else if constexpr (Index == 31) return maybe_bool();
+ else if constexpr (Index == 32) return default_bool();
+ else if constexpr (Index == 33) return just_enum();
+ else if constexpr (Index == 34) return maybe_enum();
+ else if constexpr (Index == 35) return default_enum();
+ else static_assert(Index != Index, "Invalid Field Index");
+ }
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
- VerifyField<int8_t>(verifier, VT_JUST_I8) &&
- VerifyField<int8_t>(verifier, VT_MAYBE_I8) &&
- VerifyField<int8_t>(verifier, VT_DEFAULT_I8) &&
- VerifyField<uint8_t>(verifier, VT_JUST_U8) &&
- VerifyField<uint8_t>(verifier, VT_MAYBE_U8) &&
- VerifyField<uint8_t>(verifier, VT_DEFAULT_U8) &&
- VerifyField<int16_t>(verifier, VT_JUST_I16) &&
- VerifyField<int16_t>(verifier, VT_MAYBE_I16) &&
- VerifyField<int16_t>(verifier, VT_DEFAULT_I16) &&
- VerifyField<uint16_t>(verifier, VT_JUST_U16) &&
- VerifyField<uint16_t>(verifier, VT_MAYBE_U16) &&
- VerifyField<uint16_t>(verifier, VT_DEFAULT_U16) &&
- VerifyField<int32_t>(verifier, VT_JUST_I32) &&
- VerifyField<int32_t>(verifier, VT_MAYBE_I32) &&
- VerifyField<int32_t>(verifier, VT_DEFAULT_I32) &&
- VerifyField<uint32_t>(verifier, VT_JUST_U32) &&
- VerifyField<uint32_t>(verifier, VT_MAYBE_U32) &&
- VerifyField<uint32_t>(verifier, VT_DEFAULT_U32) &&
- VerifyField<int64_t>(verifier, VT_JUST_I64) &&
- VerifyField<int64_t>(verifier, VT_MAYBE_I64) &&
- VerifyField<int64_t>(verifier, VT_DEFAULT_I64) &&
- VerifyField<uint64_t>(verifier, VT_JUST_U64) &&
- VerifyField<uint64_t>(verifier, VT_MAYBE_U64) &&
- VerifyField<uint64_t>(verifier, VT_DEFAULT_U64) &&
- VerifyField<float>(verifier, VT_JUST_F32) &&
- VerifyField<float>(verifier, VT_MAYBE_F32) &&
- VerifyField<float>(verifier, VT_DEFAULT_F32) &&
- VerifyField<double>(verifier, VT_JUST_F64) &&
- VerifyField<double>(verifier, VT_MAYBE_F64) &&
- VerifyField<double>(verifier, VT_DEFAULT_F64) &&
- VerifyField<uint8_t>(verifier, VT_JUST_BOOL) &&
- VerifyField<uint8_t>(verifier, VT_MAYBE_BOOL) &&
- VerifyField<uint8_t>(verifier, VT_DEFAULT_BOOL) &&
- VerifyField<int8_t>(verifier, VT_JUST_ENUM) &&
- VerifyField<int8_t>(verifier, VT_MAYBE_ENUM) &&
- VerifyField<int8_t>(verifier, VT_DEFAULT_ENUM) &&
+ VerifyField<int8_t>(verifier, VT_JUST_I8, 1) &&
+ VerifyField<int8_t>(verifier, VT_MAYBE_I8, 1) &&
+ VerifyField<int8_t>(verifier, VT_DEFAULT_I8, 1) &&
+ VerifyField<uint8_t>(verifier, VT_JUST_U8, 1) &&
+ VerifyField<uint8_t>(verifier, VT_MAYBE_U8, 1) &&
+ VerifyField<uint8_t>(verifier, VT_DEFAULT_U8, 1) &&
+ VerifyField<int16_t>(verifier, VT_JUST_I16, 2) &&
+ VerifyField<int16_t>(verifier, VT_MAYBE_I16, 2) &&
+ VerifyField<int16_t>(verifier, VT_DEFAULT_I16, 2) &&
+ VerifyField<uint16_t>(verifier, VT_JUST_U16, 2) &&
+ VerifyField<uint16_t>(verifier, VT_MAYBE_U16, 2) &&
+ VerifyField<uint16_t>(verifier, VT_DEFAULT_U16, 2) &&
+ VerifyField<int32_t>(verifier, VT_JUST_I32, 4) &&
+ VerifyField<int32_t>(verifier, VT_MAYBE_I32, 4) &&
+ VerifyField<int32_t>(verifier, VT_DEFAULT_I32, 4) &&
+ VerifyField<uint32_t>(verifier, VT_JUST_U32, 4) &&
+ VerifyField<uint32_t>(verifier, VT_MAYBE_U32, 4) &&
+ VerifyField<uint32_t>(verifier, VT_DEFAULT_U32, 4) &&
+ VerifyField<int64_t>(verifier, VT_JUST_I64, 8) &&
+ VerifyField<int64_t>(verifier, VT_MAYBE_I64, 8) &&
+ VerifyField<int64_t>(verifier, VT_DEFAULT_I64, 8) &&
+ VerifyField<uint64_t>(verifier, VT_JUST_U64, 8) &&
+ VerifyField<uint64_t>(verifier, VT_MAYBE_U64, 8) &&
+ VerifyField<uint64_t>(verifier, VT_DEFAULT_U64, 8) &&
+ VerifyField<float>(verifier, VT_JUST_F32, 4) &&
+ VerifyField<float>(verifier, VT_MAYBE_F32, 4) &&
+ VerifyField<float>(verifier, VT_DEFAULT_F32, 4) &&
+ VerifyField<double>(verifier, VT_JUST_F64, 8) &&
+ VerifyField<double>(verifier, VT_MAYBE_F64, 8) &&
+ VerifyField<double>(verifier, VT_DEFAULT_F64, 8) &&
+ VerifyField<uint8_t>(verifier, VT_JUST_BOOL, 1) &&
+ VerifyField<uint8_t>(verifier, VT_MAYBE_BOOL, 1) &&
+ VerifyField<uint8_t>(verifier, VT_DEFAULT_BOOL, 1) &&
+ VerifyField<int8_t>(verifier, VT_JUST_ENUM, 1) &&
+ VerifyField<int8_t>(verifier, VT_MAYBE_ENUM, 1) &&
+ VerifyField<int8_t>(verifier, VT_DEFAULT_ENUM, 1) &&
verifier.EndTable();
}
ScalarStuffT *UnPack(const flatbuffers::resolver_function_t *_resolver = nullptr) const;
@@ -597,6 +637,49 @@
struct ScalarStuff::Traits {
using type = ScalarStuff;
static auto constexpr Create = CreateScalarStuff;
+ static constexpr auto name = "ScalarStuff";
+ static constexpr auto fully_qualified_name = "optional_scalars.ScalarStuff";
+ static constexpr size_t fields_number = 36;
+ static constexpr std::array<const char *, fields_number> field_names = {
+ "just_i8",
+ "maybe_i8",
+ "default_i8",
+ "just_u8",
+ "maybe_u8",
+ "default_u8",
+ "just_i16",
+ "maybe_i16",
+ "default_i16",
+ "just_u16",
+ "maybe_u16",
+ "default_u16",
+ "just_i32",
+ "maybe_i32",
+ "default_i32",
+ "just_u32",
+ "maybe_u32",
+ "default_u32",
+ "just_i64",
+ "maybe_i64",
+ "default_i64",
+ "just_u64",
+ "maybe_u64",
+ "default_u64",
+ "just_f32",
+ "maybe_f32",
+ "default_f32",
+ "just_f64",
+ "maybe_f64",
+ "default_f64",
+ "just_bool",
+ "maybe_bool",
+ "default_bool",
+ "just_enum",
+ "maybe_enum",
+ "default_enum"
+ };
+ template<size_t Index>
+ using FieldType = decltype(std::declval<type>().get_field<Index>());
};
flatbuffers::Offset<ScalarStuff> CreateScalarStuff(flatbuffers::FlatBufferBuilder &_fbb, const ScalarStuffT *_o, const flatbuffers::rehasher_function_t *_rehasher = nullptr);
@@ -850,6 +933,10 @@
return flatbuffers::GetMutableRoot<ScalarStuff>(buf);
}
+inline optional_scalars::ScalarStuff *GetMutableSizePrefixedScalarStuff(void *buf) {
+ return flatbuffers::GetMutableSizePrefixedRoot<optional_scalars::ScalarStuff>(buf);
+}
+
inline const char *ScalarStuffIdentifier() {
return "NULL";
}
@@ -859,6 +946,11 @@
buf, ScalarStuffIdentifier());
}
+inline bool SizePrefixedScalarStuffBufferHasIdentifier(const void *buf) {
+ return flatbuffers::BufferHasIdentifier(
+ buf, ScalarStuffIdentifier(), true);
+}
+
inline bool VerifyScalarStuffBuffer(
flatbuffers::Verifier &verifier) {
return verifier.VerifyBuffer<optional_scalars::ScalarStuff>(ScalarStuffIdentifier());
diff --git a/tests/cpp17/generated_cpp17/union_vector_generated.h b/tests/cpp17/generated_cpp17/union_vector_generated.h
new file mode 100644
index 0000000..aa0daf8
--- /dev/null
+++ b/tests/cpp17/generated_cpp17/union_vector_generated.h
@@ -0,0 +1,1256 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+
+#ifndef FLATBUFFERS_GENERATED_UNIONVECTOR_H_
+#define FLATBUFFERS_GENERATED_UNIONVECTOR_H_
+
+#include "flatbuffers/flatbuffers.h"
+
+struct Attacker;
+struct AttackerBuilder;
+struct AttackerT;
+
+struct Rapunzel;
+
+struct BookReader;
+
+struct FallingTub;
+
+struct HandFan;
+struct HandFanBuilder;
+struct HandFanT;
+
+struct Movie;
+struct MovieBuilder;
+struct MovieT;
+
+inline const flatbuffers::TypeTable *AttackerTypeTable();
+
+inline const flatbuffers::TypeTable *RapunzelTypeTable();
+
+inline const flatbuffers::TypeTable *BookReaderTypeTable();
+
+inline const flatbuffers::TypeTable *FallingTubTypeTable();
+
+inline const flatbuffers::TypeTable *HandFanTypeTable();
+
+inline const flatbuffers::TypeTable *MovieTypeTable();
+
+enum class Character : uint8_t {
+ NONE = 0,
+ MuLan = 1,
+ Rapunzel = 2,
+ Belle = 3,
+ BookFan = 4,
+ Other = 5,
+ Unused = 6,
+ MIN = NONE,
+ MAX = Unused
+};
+
+inline const Character (&EnumValuesCharacter())[7] {
+ static const Character values[] = {
+ Character::NONE,
+ Character::MuLan,
+ Character::Rapunzel,
+ Character::Belle,
+ Character::BookFan,
+ Character::Other,
+ Character::Unused
+ };
+ return values;
+}
+
+inline const char * const *EnumNamesCharacter() {
+ static const char * const names[8] = {
+ "NONE",
+ "MuLan",
+ "Rapunzel",
+ "Belle",
+ "BookFan",
+ "Other",
+ "Unused",
+ nullptr
+ };
+ return names;
+}
+
+inline const char *EnumNameCharacter(Character e) {
+ if (flatbuffers::IsOutRange(e, Character::NONE, Character::Unused)) return "";
+ const size_t index = static_cast<size_t>(e);
+ return EnumNamesCharacter()[index];
+}
+
+struct CharacterUnion {
+ Character type;
+ void *value;
+
+ CharacterUnion() : type(Character::NONE), value(nullptr) {}
+ CharacterUnion(CharacterUnion&& u) FLATBUFFERS_NOEXCEPT :
+ type(Character::NONE), value(nullptr)
+ { std::swap(type, u.type); std::swap(value, u.value); }
+ CharacterUnion(const CharacterUnion &);
+ CharacterUnion &operator=(const CharacterUnion &u)
+ { CharacterUnion t(u); std::swap(type, t.type); std::swap(value, t.value); return *this; }
+ CharacterUnion &operator=(CharacterUnion &&u) FLATBUFFERS_NOEXCEPT
+ { std::swap(type, u.type); std::swap(value, u.value); return *this; }
+ ~CharacterUnion() { Reset(); }
+
+ void Reset();
+
+ static void *UnPack(const void *obj, Character type, const flatbuffers::resolver_function_t *resolver);
+ flatbuffers::Offset<void> Pack(flatbuffers::FlatBufferBuilder &_fbb, const flatbuffers::rehasher_function_t *_rehasher = nullptr) const;
+
+ AttackerT *AsMuLan() {
+ return type == Character::MuLan ?
+ reinterpret_cast<AttackerT *>(value) : nullptr;
+ }
+ const AttackerT *AsMuLan() const {
+ return type == Character::MuLan ?
+ reinterpret_cast<const AttackerT *>(value) : nullptr;
+ }
+ Rapunzel *AsRapunzel() {
+ return type == Character::Rapunzel ?
+ reinterpret_cast<Rapunzel *>(value) : nullptr;
+ }
+ const Rapunzel *AsRapunzel() const {
+ return type == Character::Rapunzel ?
+ reinterpret_cast<const Rapunzel *>(value) : nullptr;
+ }
+ BookReader *AsBelle() {
+ return type == Character::Belle ?
+ reinterpret_cast<BookReader *>(value) : nullptr;
+ }
+ const BookReader *AsBelle() const {
+ return type == Character::Belle ?
+ reinterpret_cast<const BookReader *>(value) : nullptr;
+ }
+ BookReader *AsBookFan() {
+ return type == Character::BookFan ?
+ reinterpret_cast<BookReader *>(value) : nullptr;
+ }
+ const BookReader *AsBookFan() const {
+ return type == Character::BookFan ?
+ reinterpret_cast<const BookReader *>(value) : nullptr;
+ }
+ std::string *AsOther() {
+ return type == Character::Other ?
+ reinterpret_cast<std::string *>(value) : nullptr;
+ }
+ const std::string *AsOther() const {
+ return type == Character::Other ?
+ reinterpret_cast<const std::string *>(value) : nullptr;
+ }
+ std::string *AsUnused() {
+ return type == Character::Unused ?
+ reinterpret_cast<std::string *>(value) : nullptr;
+ }
+ const std::string *AsUnused() const {
+ return type == Character::Unused ?
+ reinterpret_cast<const std::string *>(value) : nullptr;
+ }
+};
+
+bool VerifyCharacter(flatbuffers::Verifier &verifier, const void *obj, Character type);
+bool VerifyCharacterVector(flatbuffers::Verifier &verifier, const flatbuffers::Vector<flatbuffers::Offset<void>> *values, const flatbuffers::Vector<Character> *types);
+
+enum class Gadget : uint8_t {
+ NONE = 0,
+ FallingTub = 1,
+ HandFan = 2,
+ MIN = NONE,
+ MAX = HandFan
+};
+
+inline const Gadget (&EnumValuesGadget())[3] {
+ static const Gadget values[] = {
+ Gadget::NONE,
+ Gadget::FallingTub,
+ Gadget::HandFan
+ };
+ return values;
+}
+
+inline const char * const *EnumNamesGadget() {
+ static const char * const names[4] = {
+ "NONE",
+ "FallingTub",
+ "HandFan",
+ nullptr
+ };
+ return names;
+}
+
+inline const char *EnumNameGadget(Gadget e) {
+ if (flatbuffers::IsOutRange(e, Gadget::NONE, Gadget::HandFan)) return "";
+ const size_t index = static_cast<size_t>(e);
+ return EnumNamesGadget()[index];
+}
+
+template<typename T> struct GadgetTraits {
+ static const Gadget enum_value = Gadget::NONE;
+};
+
+template<> struct GadgetTraits<FallingTub> {
+ static const Gadget enum_value = Gadget::FallingTub;
+};
+
+template<> struct GadgetTraits<HandFan> {
+ static const Gadget enum_value = Gadget::HandFan;
+};
+
+template<typename T> struct GadgetUnionTraits {
+ static const Gadget enum_value = Gadget::NONE;
+};
+
+template<> struct GadgetUnionTraits<FallingTub> {
+ static const Gadget enum_value = Gadget::FallingTub;
+};
+
+template<> struct GadgetUnionTraits<HandFanT> {
+ static const Gadget enum_value = Gadget::HandFan;
+};
+
+struct GadgetUnion {
+ Gadget type;
+ void *value;
+
+ GadgetUnion() : type(Gadget::NONE), value(nullptr) {}
+ GadgetUnion(GadgetUnion&& u) FLATBUFFERS_NOEXCEPT :
+ type(Gadget::NONE), value(nullptr)
+ { std::swap(type, u.type); std::swap(value, u.value); }
+ GadgetUnion(const GadgetUnion &);
+ GadgetUnion &operator=(const GadgetUnion &u)
+ { GadgetUnion t(u); std::swap(type, t.type); std::swap(value, t.value); return *this; }
+ GadgetUnion &operator=(GadgetUnion &&u) FLATBUFFERS_NOEXCEPT
+ { std::swap(type, u.type); std::swap(value, u.value); return *this; }
+ ~GadgetUnion() { Reset(); }
+
+ void Reset();
+
+ template <typename T>
+ void Set(T&& val) {
+ typedef typename std::remove_reference<T>::type RT;
+ Reset();
+ type = GadgetUnionTraits<RT>::enum_value;
+ if (type != Gadget::NONE) {
+ value = new RT(std::forward<T>(val));
+ }
+ }
+
+ static void *UnPack(const void *obj, Gadget type, const flatbuffers::resolver_function_t *resolver);
+ flatbuffers::Offset<void> Pack(flatbuffers::FlatBufferBuilder &_fbb, const flatbuffers::rehasher_function_t *_rehasher = nullptr) const;
+
+ FallingTub *AsFallingTub() {
+ return type == Gadget::FallingTub ?
+ reinterpret_cast<FallingTub *>(value) : nullptr;
+ }
+ const FallingTub *AsFallingTub() const {
+ return type == Gadget::FallingTub ?
+ reinterpret_cast<const FallingTub *>(value) : nullptr;
+ }
+ HandFanT *AsHandFan() {
+ return type == Gadget::HandFan ?
+ reinterpret_cast<HandFanT *>(value) : nullptr;
+ }
+ const HandFanT *AsHandFan() const {
+ return type == Gadget::HandFan ?
+ reinterpret_cast<const HandFanT *>(value) : nullptr;
+ }
+};
+
+bool VerifyGadget(flatbuffers::Verifier &verifier, const void *obj, Gadget type);
+bool VerifyGadgetVector(flatbuffers::Verifier &verifier, const flatbuffers::Vector<flatbuffers::Offset<void>> *values, const flatbuffers::Vector<Gadget> *types);
+
+FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) Rapunzel FLATBUFFERS_FINAL_CLASS {
+ private:
+ int32_t hair_length_;
+
+ public:
+ struct Traits;
+ static const flatbuffers::TypeTable *MiniReflectTypeTable() {
+ return RapunzelTypeTable();
+ }
+ Rapunzel()
+ : hair_length_(0) {
+ }
+ Rapunzel(int32_t _hair_length)
+ : hair_length_(flatbuffers::EndianScalar(_hair_length)) {
+ }
+ int32_t hair_length() const {
+ return flatbuffers::EndianScalar(hair_length_);
+ }
+ void mutate_hair_length(int32_t _hair_length) {
+ flatbuffers::WriteScalar(&hair_length_, _hair_length);
+ }
+ template<size_t Index>
+ auto get_field() const {
+ if constexpr (Index == 0) return hair_length();
+ else static_assert(Index != Index, "Invalid Field Index");
+ }
+};
+FLATBUFFERS_STRUCT_END(Rapunzel, 4);
+
+struct Rapunzel::Traits {
+ using type = Rapunzel;
+ static constexpr auto name = "Rapunzel";
+ static constexpr auto fully_qualified_name = "Rapunzel";
+ static constexpr size_t fields_number = 1;
+ static constexpr std::array<const char *, fields_number> field_names = {
+ "hair_length"
+ };
+ template<size_t Index>
+ using FieldType = decltype(std::declval<type>().get_field<Index>());
+};
+
+FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) BookReader FLATBUFFERS_FINAL_CLASS {
+ private:
+ int32_t books_read_;
+
+ public:
+ struct Traits;
+ static const flatbuffers::TypeTable *MiniReflectTypeTable() {
+ return BookReaderTypeTable();
+ }
+ BookReader()
+ : books_read_(0) {
+ }
+ BookReader(int32_t _books_read)
+ : books_read_(flatbuffers::EndianScalar(_books_read)) {
+ }
+ int32_t books_read() const {
+ return flatbuffers::EndianScalar(books_read_);
+ }
+ void mutate_books_read(int32_t _books_read) {
+ flatbuffers::WriteScalar(&books_read_, _books_read);
+ }
+ template<size_t Index>
+ auto get_field() const {
+ if constexpr (Index == 0) return books_read();
+ else static_assert(Index != Index, "Invalid Field Index");
+ }
+};
+FLATBUFFERS_STRUCT_END(BookReader, 4);
+
+struct BookReader::Traits {
+ using type = BookReader;
+ static constexpr auto name = "BookReader";
+ static constexpr auto fully_qualified_name = "BookReader";
+ static constexpr size_t fields_number = 1;
+ static constexpr std::array<const char *, fields_number> field_names = {
+ "books_read"
+ };
+ template<size_t Index>
+ using FieldType = decltype(std::declval<type>().get_field<Index>());
+};
+
+FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) FallingTub FLATBUFFERS_FINAL_CLASS {
+ private:
+ int32_t weight_;
+
+ public:
+ struct Traits;
+ static const flatbuffers::TypeTable *MiniReflectTypeTable() {
+ return FallingTubTypeTable();
+ }
+ FallingTub()
+ : weight_(0) {
+ }
+ FallingTub(int32_t _weight)
+ : weight_(flatbuffers::EndianScalar(_weight)) {
+ }
+ int32_t weight() const {
+ return flatbuffers::EndianScalar(weight_);
+ }
+ void mutate_weight(int32_t _weight) {
+ flatbuffers::WriteScalar(&weight_, _weight);
+ }
+ template<size_t Index>
+ auto get_field() const {
+ if constexpr (Index == 0) return weight();
+ else static_assert(Index != Index, "Invalid Field Index");
+ }
+};
+FLATBUFFERS_STRUCT_END(FallingTub, 4);
+
+struct FallingTub::Traits {
+ using type = FallingTub;
+ static constexpr auto name = "FallingTub";
+ static constexpr auto fully_qualified_name = "FallingTub";
+ static constexpr size_t fields_number = 1;
+ static constexpr std::array<const char *, fields_number> field_names = {
+ "weight"
+ };
+ template<size_t Index>
+ using FieldType = decltype(std::declval<type>().get_field<Index>());
+};
+
+struct AttackerT : public flatbuffers::NativeTable {
+ typedef Attacker TableType;
+ int32_t sword_attack_damage = 0;
+};
+
+struct Attacker FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
+ typedef AttackerT NativeTableType;
+ typedef AttackerBuilder Builder;
+ struct Traits;
+ static const flatbuffers::TypeTable *MiniReflectTypeTable() {
+ return AttackerTypeTable();
+ }
+ enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE {
+ VT_SWORD_ATTACK_DAMAGE = 4
+ };
+ int32_t sword_attack_damage() const {
+ return GetField<int32_t>(VT_SWORD_ATTACK_DAMAGE, 0);
+ }
+ bool mutate_sword_attack_damage(int32_t _sword_attack_damage = 0) {
+ return SetField<int32_t>(VT_SWORD_ATTACK_DAMAGE, _sword_attack_damage, 0);
+ }
+ template<size_t Index>
+ auto get_field() const {
+ if constexpr (Index == 0) return sword_attack_damage();
+ else static_assert(Index != Index, "Invalid Field Index");
+ }
+ bool Verify(flatbuffers::Verifier &verifier) const {
+ return VerifyTableStart(verifier) &&
+ VerifyField<int32_t>(verifier, VT_SWORD_ATTACK_DAMAGE, 4) &&
+ verifier.EndTable();
+ }
+ AttackerT *UnPack(const flatbuffers::resolver_function_t *_resolver = nullptr) const;
+ void UnPackTo(AttackerT *_o, const flatbuffers::resolver_function_t *_resolver = nullptr) const;
+ static flatbuffers::Offset<Attacker> Pack(flatbuffers::FlatBufferBuilder &_fbb, const AttackerT* _o, const flatbuffers::rehasher_function_t *_rehasher = nullptr);
+};
+
+struct AttackerBuilder {
+ typedef Attacker Table;
+ flatbuffers::FlatBufferBuilder &fbb_;
+ flatbuffers::uoffset_t start_;
+ void add_sword_attack_damage(int32_t sword_attack_damage) {
+ fbb_.AddElement<int32_t>(Attacker::VT_SWORD_ATTACK_DAMAGE, sword_attack_damage, 0);
+ }
+ explicit AttackerBuilder(flatbuffers::FlatBufferBuilder &_fbb)
+ : fbb_(_fbb) {
+ start_ = fbb_.StartTable();
+ }
+ flatbuffers::Offset<Attacker> Finish() {
+ const auto end = fbb_.EndTable(start_);
+ auto o = flatbuffers::Offset<Attacker>(end);
+ return o;
+ }
+};
+
+inline flatbuffers::Offset<Attacker> CreateAttacker(
+ flatbuffers::FlatBufferBuilder &_fbb,
+ int32_t sword_attack_damage = 0) {
+ AttackerBuilder builder_(_fbb);
+ builder_.add_sword_attack_damage(sword_attack_damage);
+ return builder_.Finish();
+}
+
+struct Attacker::Traits {
+ using type = Attacker;
+ static auto constexpr Create = CreateAttacker;
+ static constexpr auto name = "Attacker";
+ static constexpr auto fully_qualified_name = "Attacker";
+ static constexpr size_t fields_number = 1;
+ static constexpr std::array<const char *, fields_number> field_names = {
+ "sword_attack_damage"
+ };
+ template<size_t Index>
+ using FieldType = decltype(std::declval<type>().get_field<Index>());
+};
+
+flatbuffers::Offset<Attacker> CreateAttacker(flatbuffers::FlatBufferBuilder &_fbb, const AttackerT *_o, const flatbuffers::rehasher_function_t *_rehasher = nullptr);
+
+struct HandFanT : public flatbuffers::NativeTable {
+ typedef HandFan TableType;
+ int32_t length = 0;
+};
+
+struct HandFan FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
+ typedef HandFanT NativeTableType;
+ typedef HandFanBuilder Builder;
+ struct Traits;
+ static const flatbuffers::TypeTable *MiniReflectTypeTable() {
+ return HandFanTypeTable();
+ }
+ enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE {
+ VT_LENGTH = 4
+ };
+ int32_t length() const {
+ return GetField<int32_t>(VT_LENGTH, 0);
+ }
+ bool mutate_length(int32_t _length = 0) {
+ return SetField<int32_t>(VT_LENGTH, _length, 0);
+ }
+ template<size_t Index>
+ auto get_field() const {
+ if constexpr (Index == 0) return length();
+ else static_assert(Index != Index, "Invalid Field Index");
+ }
+ bool Verify(flatbuffers::Verifier &verifier) const {
+ return VerifyTableStart(verifier) &&
+ VerifyField<int32_t>(verifier, VT_LENGTH, 4) &&
+ verifier.EndTable();
+ }
+ HandFanT *UnPack(const flatbuffers::resolver_function_t *_resolver = nullptr) const;
+ void UnPackTo(HandFanT *_o, const flatbuffers::resolver_function_t *_resolver = nullptr) const;
+ static flatbuffers::Offset<HandFan> Pack(flatbuffers::FlatBufferBuilder &_fbb, const HandFanT* _o, const flatbuffers::rehasher_function_t *_rehasher = nullptr);
+};
+
+struct HandFanBuilder {
+ typedef HandFan Table;
+ flatbuffers::FlatBufferBuilder &fbb_;
+ flatbuffers::uoffset_t start_;
+ void add_length(int32_t length) {
+ fbb_.AddElement<int32_t>(HandFan::VT_LENGTH, length, 0);
+ }
+ explicit HandFanBuilder(flatbuffers::FlatBufferBuilder &_fbb)
+ : fbb_(_fbb) {
+ start_ = fbb_.StartTable();
+ }
+ flatbuffers::Offset<HandFan> Finish() {
+ const auto end = fbb_.EndTable(start_);
+ auto o = flatbuffers::Offset<HandFan>(end);
+ return o;
+ }
+};
+
+inline flatbuffers::Offset<HandFan> CreateHandFan(
+ flatbuffers::FlatBufferBuilder &_fbb,
+ int32_t length = 0) {
+ HandFanBuilder builder_(_fbb);
+ builder_.add_length(length);
+ return builder_.Finish();
+}
+
+struct HandFan::Traits {
+ using type = HandFan;
+ static auto constexpr Create = CreateHandFan;
+ static constexpr auto name = "HandFan";
+ static constexpr auto fully_qualified_name = "HandFan";
+ static constexpr size_t fields_number = 1;
+ static constexpr std::array<const char *, fields_number> field_names = {
+ "length"
+ };
+ template<size_t Index>
+ using FieldType = decltype(std::declval<type>().get_field<Index>());
+};
+
+flatbuffers::Offset<HandFan> CreateHandFan(flatbuffers::FlatBufferBuilder &_fbb, const HandFanT *_o, const flatbuffers::rehasher_function_t *_rehasher = nullptr);
+
+struct MovieT : public flatbuffers::NativeTable {
+ typedef Movie TableType;
+ CharacterUnion main_character{};
+ std::vector<CharacterUnion> characters{};
+};
+
+struct Movie FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
+ typedef MovieT NativeTableType;
+ typedef MovieBuilder Builder;
+ struct Traits;
+ static const flatbuffers::TypeTable *MiniReflectTypeTable() {
+ return MovieTypeTable();
+ }
+ enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE {
+ VT_MAIN_CHARACTER_TYPE = 4,
+ VT_MAIN_CHARACTER = 6,
+ VT_CHARACTERS_TYPE = 8,
+ VT_CHARACTERS = 10
+ };
+ Character main_character_type() const {
+ return static_cast<Character>(GetField<uint8_t>(VT_MAIN_CHARACTER_TYPE, 0));
+ }
+ const void *main_character() const {
+ return GetPointer<const void *>(VT_MAIN_CHARACTER);
+ }
+ const Attacker *main_character_as_MuLan() const {
+ return main_character_type() == Character::MuLan ? static_cast<const Attacker *>(main_character()) : nullptr;
+ }
+ const Rapunzel *main_character_as_Rapunzel() const {
+ return main_character_type() == Character::Rapunzel ? static_cast<const Rapunzel *>(main_character()) : nullptr;
+ }
+ const BookReader *main_character_as_Belle() const {
+ return main_character_type() == Character::Belle ? static_cast<const BookReader *>(main_character()) : nullptr;
+ }
+ const BookReader *main_character_as_BookFan() const {
+ return main_character_type() == Character::BookFan ? static_cast<const BookReader *>(main_character()) : nullptr;
+ }
+ const flatbuffers::String *main_character_as_Other() const {
+ return main_character_type() == Character::Other ? static_cast<const flatbuffers::String *>(main_character()) : nullptr;
+ }
+ const flatbuffers::String *main_character_as_Unused() const {
+ return main_character_type() == Character::Unused ? static_cast<const flatbuffers::String *>(main_character()) : nullptr;
+ }
+ void *mutable_main_character() {
+ return GetPointer<void *>(VT_MAIN_CHARACTER);
+ }
+ const flatbuffers::Vector<Character> *characters_type() const {
+ return GetPointer<const flatbuffers::Vector<Character> *>(VT_CHARACTERS_TYPE);
+ }
+ flatbuffers::Vector<Character> *mutable_characters_type() {
+ return GetPointer<flatbuffers::Vector<Character> *>(VT_CHARACTERS_TYPE);
+ }
+ const flatbuffers::Vector<flatbuffers::Offset<void>> *characters() const {
+ return GetPointer<const flatbuffers::Vector<flatbuffers::Offset<void>> *>(VT_CHARACTERS);
+ }
+ flatbuffers::Vector<flatbuffers::Offset<void>> *mutable_characters() {
+ return GetPointer<flatbuffers::Vector<flatbuffers::Offset<void>> *>(VT_CHARACTERS);
+ }
+ template<size_t Index>
+ auto get_field() const {
+ if constexpr (Index == 0) return main_character_type();
+ else if constexpr (Index == 1) return main_character();
+ else if constexpr (Index == 2) return characters_type();
+ else if constexpr (Index == 3) return characters();
+ else static_assert(Index != Index, "Invalid Field Index");
+ }
+ bool Verify(flatbuffers::Verifier &verifier) const {
+ return VerifyTableStart(verifier) &&
+ VerifyField<uint8_t>(verifier, VT_MAIN_CHARACTER_TYPE, 1) &&
+ VerifyOffset(verifier, VT_MAIN_CHARACTER) &&
+ VerifyCharacter(verifier, main_character(), main_character_type()) &&
+ VerifyOffset(verifier, VT_CHARACTERS_TYPE) &&
+ verifier.VerifyVector(characters_type()) &&
+ VerifyOffset(verifier, VT_CHARACTERS) &&
+ verifier.VerifyVector(characters()) &&
+ VerifyCharacterVector(verifier, characters(), characters_type()) &&
+ verifier.EndTable();
+ }
+ MovieT *UnPack(const flatbuffers::resolver_function_t *_resolver = nullptr) const;
+ void UnPackTo(MovieT *_o, const flatbuffers::resolver_function_t *_resolver = nullptr) const;
+ static flatbuffers::Offset<Movie> Pack(flatbuffers::FlatBufferBuilder &_fbb, const MovieT* _o, const flatbuffers::rehasher_function_t *_rehasher = nullptr);
+};
+
+struct MovieBuilder {
+ typedef Movie Table;
+ flatbuffers::FlatBufferBuilder &fbb_;
+ flatbuffers::uoffset_t start_;
+ void add_main_character_type(Character main_character_type) {
+ fbb_.AddElement<uint8_t>(Movie::VT_MAIN_CHARACTER_TYPE, static_cast<uint8_t>(main_character_type), 0);
+ }
+ void add_main_character(flatbuffers::Offset<void> main_character) {
+ fbb_.AddOffset(Movie::VT_MAIN_CHARACTER, main_character);
+ }
+ void add_characters_type(flatbuffers::Offset<flatbuffers::Vector<Character>> characters_type) {
+ fbb_.AddOffset(Movie::VT_CHARACTERS_TYPE, characters_type);
+ }
+ void add_characters(flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<void>>> characters) {
+ fbb_.AddOffset(Movie::VT_CHARACTERS, characters);
+ }
+ explicit MovieBuilder(flatbuffers::FlatBufferBuilder &_fbb)
+ : fbb_(_fbb) {
+ start_ = fbb_.StartTable();
+ }
+ flatbuffers::Offset<Movie> Finish() {
+ const auto end = fbb_.EndTable(start_);
+ auto o = flatbuffers::Offset<Movie>(end);
+ return o;
+ }
+};
+
+inline flatbuffers::Offset<Movie> CreateMovie(
+ flatbuffers::FlatBufferBuilder &_fbb,
+ Character main_character_type = Character::NONE,
+ flatbuffers::Offset<void> main_character = 0,
+ flatbuffers::Offset<flatbuffers::Vector<Character>> characters_type = 0,
+ flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<void>>> characters = 0) {
+ MovieBuilder builder_(_fbb);
+ builder_.add_characters(characters);
+ builder_.add_characters_type(characters_type);
+ builder_.add_main_character(main_character);
+ builder_.add_main_character_type(main_character_type);
+ return builder_.Finish();
+}
+
+struct Movie::Traits {
+ using type = Movie;
+ static auto constexpr Create = CreateMovie;
+ static constexpr auto name = "Movie";
+ static constexpr auto fully_qualified_name = "Movie";
+ static constexpr size_t fields_number = 4;
+ static constexpr std::array<const char *, fields_number> field_names = {
+ "main_character_type",
+ "main_character",
+ "characters_type",
+ "characters"
+ };
+ template<size_t Index>
+ using FieldType = decltype(std::declval<type>().get_field<Index>());
+};
+
+inline flatbuffers::Offset<Movie> CreateMovieDirect(
+ flatbuffers::FlatBufferBuilder &_fbb,
+ Character main_character_type = Character::NONE,
+ flatbuffers::Offset<void> main_character = 0,
+ const std::vector<Character> *characters_type = nullptr,
+ const std::vector<flatbuffers::Offset<void>> *characters = nullptr) {
+ auto characters_type__ = characters_type ? _fbb.CreateVector<Character>(*characters_type) : 0;
+ auto characters__ = characters ? _fbb.CreateVector<flatbuffers::Offset<void>>(*characters) : 0;
+ return CreateMovie(
+ _fbb,
+ main_character_type,
+ main_character,
+ characters_type__,
+ characters__);
+}
+
+flatbuffers::Offset<Movie> CreateMovie(flatbuffers::FlatBufferBuilder &_fbb, const MovieT *_o, const flatbuffers::rehasher_function_t *_rehasher = nullptr);
+
+inline AttackerT *Attacker::UnPack(const flatbuffers::resolver_function_t *_resolver) const {
+ auto _o = std::make_unique<AttackerT>();
+ UnPackTo(_o.get(), _resolver);
+ return _o.release();
+}
+
+inline void Attacker::UnPackTo(AttackerT *_o, const flatbuffers::resolver_function_t *_resolver) const {
+ (void)_o;
+ (void)_resolver;
+ { auto _e = sword_attack_damage(); _o->sword_attack_damage = _e; }
+}
+
+inline flatbuffers::Offset<Attacker> Attacker::Pack(flatbuffers::FlatBufferBuilder &_fbb, const AttackerT* _o, const flatbuffers::rehasher_function_t *_rehasher) {
+ return CreateAttacker(_fbb, _o, _rehasher);
+}
+
+inline flatbuffers::Offset<Attacker> CreateAttacker(flatbuffers::FlatBufferBuilder &_fbb, const AttackerT *_o, const flatbuffers::rehasher_function_t *_rehasher) {
+ (void)_rehasher;
+ (void)_o;
+ struct _VectorArgs { flatbuffers::FlatBufferBuilder *__fbb; const AttackerT* __o; const flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va;
+ auto _sword_attack_damage = _o->sword_attack_damage;
+ return CreateAttacker(
+ _fbb,
+ _sword_attack_damage);
+}
+
+inline HandFanT *HandFan::UnPack(const flatbuffers::resolver_function_t *_resolver) const {
+ auto _o = std::make_unique<HandFanT>();
+ UnPackTo(_o.get(), _resolver);
+ return _o.release();
+}
+
+inline void HandFan::UnPackTo(HandFanT *_o, const flatbuffers::resolver_function_t *_resolver) const {
+ (void)_o;
+ (void)_resolver;
+ { auto _e = length(); _o->length = _e; }
+}
+
+inline flatbuffers::Offset<HandFan> HandFan::Pack(flatbuffers::FlatBufferBuilder &_fbb, const HandFanT* _o, const flatbuffers::rehasher_function_t *_rehasher) {
+ return CreateHandFan(_fbb, _o, _rehasher);
+}
+
+inline flatbuffers::Offset<HandFan> CreateHandFan(flatbuffers::FlatBufferBuilder &_fbb, const HandFanT *_o, const flatbuffers::rehasher_function_t *_rehasher) {
+ (void)_rehasher;
+ (void)_o;
+ struct _VectorArgs { flatbuffers::FlatBufferBuilder *__fbb; const HandFanT* __o; const flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va;
+ auto _length = _o->length;
+ return CreateHandFan(
+ _fbb,
+ _length);
+}
+
+inline MovieT *Movie::UnPack(const flatbuffers::resolver_function_t *_resolver) const {
+ auto _o = std::make_unique<MovieT>();
+ UnPackTo(_o.get(), _resolver);
+ return _o.release();
+}
+
+inline void Movie::UnPackTo(MovieT *_o, const flatbuffers::resolver_function_t *_resolver) const {
+ (void)_o;
+ (void)_resolver;
+ { auto _e = main_character_type(); _o->main_character.type = _e; }
+ { auto _e = main_character(); if (_e) _o->main_character.value = CharacterUnion::UnPack(_e, main_character_type(), _resolver); }
+ { auto _e = characters_type(); if (_e) { _o->characters.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->characters[_i].type = static_cast<Character>(_e->Get(_i)); } } }
+ { auto _e = characters(); if (_e) { _o->characters.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->characters[_i].value = CharacterUnion::UnPack(_e->Get(_i), characters_type()->GetEnum<Character>(_i), _resolver); } } }
+}
+
+inline flatbuffers::Offset<Movie> Movie::Pack(flatbuffers::FlatBufferBuilder &_fbb, const MovieT* _o, const flatbuffers::rehasher_function_t *_rehasher) {
+ return CreateMovie(_fbb, _o, _rehasher);
+}
+
+inline flatbuffers::Offset<Movie> CreateMovie(flatbuffers::FlatBufferBuilder &_fbb, const MovieT *_o, const flatbuffers::rehasher_function_t *_rehasher) {
+ (void)_rehasher;
+ (void)_o;
+ struct _VectorArgs { flatbuffers::FlatBufferBuilder *__fbb; const MovieT* __o; const flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va;
+ auto _main_character_type = _o->main_character.type;
+ auto _main_character = _o->main_character.Pack(_fbb);
+ auto _characters_type = _o->characters.size() ? _fbb.CreateVector<Character>(_o->characters.size(), [](size_t i, _VectorArgs *__va) { return __va->__o->characters[i].type; }, &_va) : 0;
+ auto _characters = _o->characters.size() ? _fbb.CreateVector<flatbuffers::Offset<void>>(_o->characters.size(), [](size_t i, _VectorArgs *__va) { return __va->__o->characters[i].Pack(*__va->__fbb, __va->__rehasher); }, &_va) : 0;
+ return CreateMovie(
+ _fbb,
+ _main_character_type,
+ _main_character,
+ _characters_type,
+ _characters);
+}
+
+inline bool VerifyCharacter(flatbuffers::Verifier &verifier, const void *obj, Character type) {
+ switch (type) {
+ case Character::NONE: {
+ return true;
+ }
+ case Character::MuLan: {
+ auto ptr = reinterpret_cast<const Attacker *>(obj);
+ return verifier.VerifyTable(ptr);
+ }
+ case Character::Rapunzel: {
+ return verifier.VerifyField<Rapunzel>(static_cast<const uint8_t *>(obj), 0, 4);
+ }
+ case Character::Belle: {
+ return verifier.VerifyField<BookReader>(static_cast<const uint8_t *>(obj), 0, 4);
+ }
+ case Character::BookFan: {
+ return verifier.VerifyField<BookReader>(static_cast<const uint8_t *>(obj), 0, 4);
+ }
+ case Character::Other: {
+ auto ptr = reinterpret_cast<const flatbuffers::String *>(obj);
+ return verifier.VerifyString(ptr);
+ }
+ case Character::Unused: {
+ auto ptr = reinterpret_cast<const flatbuffers::String *>(obj);
+ return verifier.VerifyString(ptr);
+ }
+ default: return true;
+ }
+}
+
+inline bool VerifyCharacterVector(flatbuffers::Verifier &verifier, const flatbuffers::Vector<flatbuffers::Offset<void>> *values, const flatbuffers::Vector<Character> *types) {
+ if (!values || !types) return !values && !types;
+ if (values->size() != types->size()) return false;
+ for (flatbuffers::uoffset_t i = 0; i < values->size(); ++i) {
+ if (!VerifyCharacter(
+ verifier, values->Get(i), types->GetEnum<Character>(i))) {
+ return false;
+ }
+ }
+ return true;
+}
+
+inline void *CharacterUnion::UnPack(const void *obj, Character type, const flatbuffers::resolver_function_t *resolver) {
+ (void)resolver;
+ switch (type) {
+ case Character::MuLan: {
+ auto ptr = reinterpret_cast<const Attacker *>(obj);
+ return ptr->UnPack(resolver);
+ }
+ case Character::Rapunzel: {
+ auto ptr = reinterpret_cast<const Rapunzel *>(obj);
+ return new Rapunzel(*ptr);
+ }
+ case Character::Belle: {
+ auto ptr = reinterpret_cast<const BookReader *>(obj);
+ return new BookReader(*ptr);
+ }
+ case Character::BookFan: {
+ auto ptr = reinterpret_cast<const BookReader *>(obj);
+ return new BookReader(*ptr);
+ }
+ case Character::Other: {
+ auto ptr = reinterpret_cast<const flatbuffers::String *>(obj);
+ return new std::string(ptr->c_str(), ptr->size());
+ }
+ case Character::Unused: {
+ auto ptr = reinterpret_cast<const flatbuffers::String *>(obj);
+ return new std::string(ptr->c_str(), ptr->size());
+ }
+ default: return nullptr;
+ }
+}
+
+inline flatbuffers::Offset<void> CharacterUnion::Pack(flatbuffers::FlatBufferBuilder &_fbb, const flatbuffers::rehasher_function_t *_rehasher) const {
+ (void)_rehasher;
+ switch (type) {
+ case Character::MuLan: {
+ auto ptr = reinterpret_cast<const AttackerT *>(value);
+ return CreateAttacker(_fbb, ptr, _rehasher).Union();
+ }
+ case Character::Rapunzel: {
+ auto ptr = reinterpret_cast<const Rapunzel *>(value);
+ return _fbb.CreateStruct(*ptr).Union();
+ }
+ case Character::Belle: {
+ auto ptr = reinterpret_cast<const BookReader *>(value);
+ return _fbb.CreateStruct(*ptr).Union();
+ }
+ case Character::BookFan: {
+ auto ptr = reinterpret_cast<const BookReader *>(value);
+ return _fbb.CreateStruct(*ptr).Union();
+ }
+ case Character::Other: {
+ auto ptr = reinterpret_cast<const std::string *>(value);
+ return _fbb.CreateString(*ptr).Union();
+ }
+ case Character::Unused: {
+ auto ptr = reinterpret_cast<const std::string *>(value);
+ return _fbb.CreateString(*ptr).Union();
+ }
+ default: return 0;
+ }
+}
+
+inline CharacterUnion::CharacterUnion(const CharacterUnion &u) : type(u.type), value(nullptr) {
+ switch (type) {
+ case Character::MuLan: {
+ value = new AttackerT(*reinterpret_cast<AttackerT *>(u.value));
+ break;
+ }
+ case Character::Rapunzel: {
+ value = new Rapunzel(*reinterpret_cast<Rapunzel *>(u.value));
+ break;
+ }
+ case Character::Belle: {
+ value = new BookReader(*reinterpret_cast<BookReader *>(u.value));
+ break;
+ }
+ case Character::BookFan: {
+ value = new BookReader(*reinterpret_cast<BookReader *>(u.value));
+ break;
+ }
+ case Character::Other: {
+ value = new std::string(*reinterpret_cast<std::string *>(u.value));
+ break;
+ }
+ case Character::Unused: {
+ value = new std::string(*reinterpret_cast<std::string *>(u.value));
+ break;
+ }
+ default:
+ break;
+ }
+}
+
+inline void CharacterUnion::Reset() {
+ switch (type) {
+ case Character::MuLan: {
+ auto ptr = reinterpret_cast<AttackerT *>(value);
+ delete ptr;
+ break;
+ }
+ case Character::Rapunzel: {
+ auto ptr = reinterpret_cast<Rapunzel *>(value);
+ delete ptr;
+ break;
+ }
+ case Character::Belle: {
+ auto ptr = reinterpret_cast<BookReader *>(value);
+ delete ptr;
+ break;
+ }
+ case Character::BookFan: {
+ auto ptr = reinterpret_cast<BookReader *>(value);
+ delete ptr;
+ break;
+ }
+ case Character::Other: {
+ auto ptr = reinterpret_cast<std::string *>(value);
+ delete ptr;
+ break;
+ }
+ case Character::Unused: {
+ auto ptr = reinterpret_cast<std::string *>(value);
+ delete ptr;
+ break;
+ }
+ default: break;
+ }
+ value = nullptr;
+ type = Character::NONE;
+}
+
+inline bool VerifyGadget(flatbuffers::Verifier &verifier, const void *obj, Gadget type) {
+ switch (type) {
+ case Gadget::NONE: {
+ return true;
+ }
+ case Gadget::FallingTub: {
+ return verifier.VerifyField<FallingTub>(static_cast<const uint8_t *>(obj), 0, 4);
+ }
+ case Gadget::HandFan: {
+ auto ptr = reinterpret_cast<const HandFan *>(obj);
+ return verifier.VerifyTable(ptr);
+ }
+ default: return true;
+ }
+}
+
+inline bool VerifyGadgetVector(flatbuffers::Verifier &verifier, const flatbuffers::Vector<flatbuffers::Offset<void>> *values, const flatbuffers::Vector<Gadget> *types) {
+ if (!values || !types) return !values && !types;
+ if (values->size() != types->size()) return false;
+ for (flatbuffers::uoffset_t i = 0; i < values->size(); ++i) {
+ if (!VerifyGadget(
+ verifier, values->Get(i), types->GetEnum<Gadget>(i))) {
+ return false;
+ }
+ }
+ return true;
+}
+
+inline void *GadgetUnion::UnPack(const void *obj, Gadget type, const flatbuffers::resolver_function_t *resolver) {
+ (void)resolver;
+ switch (type) {
+ case Gadget::FallingTub: {
+ auto ptr = reinterpret_cast<const FallingTub *>(obj);
+ return new FallingTub(*ptr);
+ }
+ case Gadget::HandFan: {
+ auto ptr = reinterpret_cast<const HandFan *>(obj);
+ return ptr->UnPack(resolver);
+ }
+ default: return nullptr;
+ }
+}
+
+inline flatbuffers::Offset<void> GadgetUnion::Pack(flatbuffers::FlatBufferBuilder &_fbb, const flatbuffers::rehasher_function_t *_rehasher) const {
+ (void)_rehasher;
+ switch (type) {
+ case Gadget::FallingTub: {
+ auto ptr = reinterpret_cast<const FallingTub *>(value);
+ return _fbb.CreateStruct(*ptr).Union();
+ }
+ case Gadget::HandFan: {
+ auto ptr = reinterpret_cast<const HandFanT *>(value);
+ return CreateHandFan(_fbb, ptr, _rehasher).Union();
+ }
+ default: return 0;
+ }
+}
+
+inline GadgetUnion::GadgetUnion(const GadgetUnion &u) : type(u.type), value(nullptr) {
+ switch (type) {
+ case Gadget::FallingTub: {
+ value = new FallingTub(*reinterpret_cast<FallingTub *>(u.value));
+ break;
+ }
+ case Gadget::HandFan: {
+ value = new HandFanT(*reinterpret_cast<HandFanT *>(u.value));
+ break;
+ }
+ default:
+ break;
+ }
+}
+
+inline void GadgetUnion::Reset() {
+ switch (type) {
+ case Gadget::FallingTub: {
+ auto ptr = reinterpret_cast<FallingTub *>(value);
+ delete ptr;
+ break;
+ }
+ case Gadget::HandFan: {
+ auto ptr = reinterpret_cast<HandFanT *>(value);
+ delete ptr;
+ break;
+ }
+ default: break;
+ }
+ value = nullptr;
+ type = Gadget::NONE;
+}
+
+inline const flatbuffers::TypeTable *CharacterTypeTable() {
+ static const flatbuffers::TypeCode type_codes[] = {
+ { flatbuffers::ET_SEQUENCE, 0, -1 },
+ { flatbuffers::ET_SEQUENCE, 0, 0 },
+ { flatbuffers::ET_SEQUENCE, 0, 1 },
+ { flatbuffers::ET_SEQUENCE, 0, 2 },
+ { flatbuffers::ET_SEQUENCE, 0, 2 },
+ { flatbuffers::ET_STRING, 0, -1 },
+ { flatbuffers::ET_STRING, 0, -1 }
+ };
+ static const flatbuffers::TypeFunction type_refs[] = {
+ AttackerTypeTable,
+ RapunzelTypeTable,
+ BookReaderTypeTable
+ };
+ static const char * const names[] = {
+ "NONE",
+ "MuLan",
+ "Rapunzel",
+ "Belle",
+ "BookFan",
+ "Other",
+ "Unused"
+ };
+ static const flatbuffers::TypeTable tt = {
+ flatbuffers::ST_UNION, 7, type_codes, type_refs, nullptr, nullptr, names
+ };
+ return &tt;
+}
+
+inline const flatbuffers::TypeTable *GadgetTypeTable() {
+ static const flatbuffers::TypeCode type_codes[] = {
+ { flatbuffers::ET_SEQUENCE, 0, -1 },
+ { flatbuffers::ET_SEQUENCE, 0, 0 },
+ { flatbuffers::ET_SEQUENCE, 0, 1 }
+ };
+ static const flatbuffers::TypeFunction type_refs[] = {
+ FallingTubTypeTable,
+ HandFanTypeTable
+ };
+ static const char * const names[] = {
+ "NONE",
+ "FallingTub",
+ "HandFan"
+ };
+ static const flatbuffers::TypeTable tt = {
+ flatbuffers::ST_UNION, 3, type_codes, type_refs, nullptr, nullptr, names
+ };
+ return &tt;
+}
+
+inline const flatbuffers::TypeTable *AttackerTypeTable() {
+ static const flatbuffers::TypeCode type_codes[] = {
+ { flatbuffers::ET_INT, 0, -1 }
+ };
+ static const char * const names[] = {
+ "sword_attack_damage"
+ };
+ static const flatbuffers::TypeTable tt = {
+ flatbuffers::ST_TABLE, 1, type_codes, nullptr, nullptr, nullptr, names
+ };
+ return &tt;
+}
+
+inline const flatbuffers::TypeTable *RapunzelTypeTable() {
+ static const flatbuffers::TypeCode type_codes[] = {
+ { flatbuffers::ET_INT, 0, -1 }
+ };
+ static const int64_t values[] = { 0, 4 };
+ static const char * const names[] = {
+ "hair_length"
+ };
+ static const flatbuffers::TypeTable tt = {
+ flatbuffers::ST_STRUCT, 1, type_codes, nullptr, nullptr, values, names
+ };
+ return &tt;
+}
+
+inline const flatbuffers::TypeTable *BookReaderTypeTable() {
+ static const flatbuffers::TypeCode type_codes[] = {
+ { flatbuffers::ET_INT, 0, -1 }
+ };
+ static const int64_t values[] = { 0, 4 };
+ static const char * const names[] = {
+ "books_read"
+ };
+ static const flatbuffers::TypeTable tt = {
+ flatbuffers::ST_STRUCT, 1, type_codes, nullptr, nullptr, values, names
+ };
+ return &tt;
+}
+
+inline const flatbuffers::TypeTable *FallingTubTypeTable() {
+ static const flatbuffers::TypeCode type_codes[] = {
+ { flatbuffers::ET_INT, 0, -1 }
+ };
+ static const int64_t values[] = { 0, 4 };
+ static const char * const names[] = {
+ "weight"
+ };
+ static const flatbuffers::TypeTable tt = {
+ flatbuffers::ST_STRUCT, 1, type_codes, nullptr, nullptr, values, names
+ };
+ return &tt;
+}
+
+inline const flatbuffers::TypeTable *HandFanTypeTable() {
+ static const flatbuffers::TypeCode type_codes[] = {
+ { flatbuffers::ET_INT, 0, -1 }
+ };
+ static const char * const names[] = {
+ "length"
+ };
+ static const flatbuffers::TypeTable tt = {
+ flatbuffers::ST_TABLE, 1, type_codes, nullptr, nullptr, nullptr, names
+ };
+ return &tt;
+}
+
+inline const flatbuffers::TypeTable *MovieTypeTable() {
+ static const flatbuffers::TypeCode type_codes[] = {
+ { flatbuffers::ET_UTYPE, 0, 0 },
+ { flatbuffers::ET_SEQUENCE, 0, 0 },
+ { flatbuffers::ET_UTYPE, 1, 0 },
+ { flatbuffers::ET_SEQUENCE, 1, 0 }
+ };
+ static const flatbuffers::TypeFunction type_refs[] = {
+ CharacterTypeTable
+ };
+ static const char * const names[] = {
+ "main_character_type",
+ "main_character",
+ "characters_type",
+ "characters"
+ };
+ static const flatbuffers::TypeTable tt = {
+ flatbuffers::ST_TABLE, 4, type_codes, type_refs, nullptr, nullptr, names
+ };
+ return &tt;
+}
+
+inline const Movie *GetMovie(const void *buf) {
+ return flatbuffers::GetRoot<Movie>(buf);
+}
+
+inline const Movie *GetSizePrefixedMovie(const void *buf) {
+ return flatbuffers::GetSizePrefixedRoot<Movie>(buf);
+}
+
+inline Movie *GetMutableMovie(void *buf) {
+ return flatbuffers::GetMutableRoot<Movie>(buf);
+}
+
+inline Movie *GetMutableSizePrefixedMovie(void *buf) {
+ return flatbuffers::GetMutableSizePrefixedRoot<Movie>(buf);
+}
+
+inline const char *MovieIdentifier() {
+ return "MOVI";
+}
+
+inline bool MovieBufferHasIdentifier(const void *buf) {
+ return flatbuffers::BufferHasIdentifier(
+ buf, MovieIdentifier());
+}
+
+inline bool SizePrefixedMovieBufferHasIdentifier(const void *buf) {
+ return flatbuffers::BufferHasIdentifier(
+ buf, MovieIdentifier(), true);
+}
+
+inline bool VerifyMovieBuffer(
+ flatbuffers::Verifier &verifier) {
+ return verifier.VerifyBuffer<Movie>(MovieIdentifier());
+}
+
+inline bool VerifySizePrefixedMovieBuffer(
+ flatbuffers::Verifier &verifier) {
+ return verifier.VerifySizePrefixedBuffer<Movie>(MovieIdentifier());
+}
+
+inline void FinishMovieBuffer(
+ flatbuffers::FlatBufferBuilder &fbb,
+ flatbuffers::Offset<Movie> root) {
+ fbb.Finish(root, MovieIdentifier());
+}
+
+inline void FinishSizePrefixedMovieBuffer(
+ flatbuffers::FlatBufferBuilder &fbb,
+ flatbuffers::Offset<Movie> root) {
+ fbb.FinishSizePrefixed(root, MovieIdentifier());
+}
+
+inline std::unique_ptr<MovieT> UnPackMovie(
+ const void *buf,
+ const flatbuffers::resolver_function_t *res = nullptr) {
+ return std::unique_ptr<MovieT>(GetMovie(buf)->UnPack(res));
+}
+
+inline std::unique_ptr<MovieT> UnPackSizePrefixedMovie(
+ const void *buf,
+ const flatbuffers::resolver_function_t *res = nullptr) {
+ return std::unique_ptr<MovieT>(GetSizePrefixedMovie(buf)->UnPack(res));
+}
+
+#endif // FLATBUFFERS_GENERATED_UNIONVECTOR_H_
diff --git a/tests/cpp17/stringify_util.h b/tests/cpp17/stringify_util.h
new file mode 100644
index 0000000..e2e7e22
--- /dev/null
+++ b/tests/cpp17/stringify_util.h
@@ -0,0 +1,189 @@
+/*
+ * Copyright 2020 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.
+ */
+
+// This contains some utilities/examples for how to leverage the static reflec-
+// tion features of tables and structs in the C++17 code generation to recur-
+// sively produce a string representation of any Flatbuffer table or struct use
+// compile-time iteration over the fields. Note that this code is completely
+// generic in that it makes no reference to any particular Flatbuffer type.
+
+#include <optional>
+#include <string>
+#include <type_traits>
+#include <utility>
+#include <vector>
+
+#include "flatbuffers/flatbuffers.h"
+#include "flatbuffers/util.h"
+
+namespace cpp17 {
+
+// User calls this; need to forward declare it since it is called recursively.
+template<typename T>
+std::optional<std::string> StringifyFlatbufferValue(
+ T &&val, const std::string &indent = "");
+
+namespace detail {
+
+/*******************************************************************************
+** Metaprogramming helpers for detecting Flatbuffers Tables, Structs, & Vectors.
+*******************************************************************************/
+template<typename FBS, typename = void>
+struct is_flatbuffers_table_or_struct : std::false_type {};
+
+// We know it's a table or struct when it has a Traits subclass.
+template<typename FBS>
+struct is_flatbuffers_table_or_struct<FBS, std::void_t<typename FBS::Traits>>
+ : std::true_type {};
+
+template<typename FBS>
+inline constexpr bool is_flatbuffers_table_or_struct_v =
+ is_flatbuffers_table_or_struct<FBS>::value;
+
+template<typename T> struct is_flatbuffers_vector : std::false_type {};
+
+template<typename T>
+struct is_flatbuffers_vector<flatbuffers::Vector<T>> : std::true_type {};
+
+template<typename T>
+inline constexpr bool is_flatbuffers_vector_v = is_flatbuffers_vector<T>::value;
+
+/*******************************************************************************
+** Compile-time Iteration & Recursive Stringification over Flatbuffers types.
+*******************************************************************************/
+template<size_t Index, typename FBS>
+std::string AddStringifiedField(const FBS &fbs, const std::string &indent) {
+ auto value_string =
+ StringifyFlatbufferValue(fbs.template get_field<Index>(), indent);
+ if (!value_string) { return ""; }
+ return indent + FBS::Traits::field_names[Index] + " = " + *value_string +
+ "\n";
+}
+
+template<typename FBS, size_t... Indexes>
+std::string StringifyTableOrStructImpl(const FBS &fbs,
+ const std::string &indent,
+ std::index_sequence<Indexes...>) {
+ // This line is where the compile-time iteration happens!
+ return (AddStringifiedField<Indexes>(fbs, indent) + ...);
+}
+
+template<typename FBS>
+std::string StringifyTableOrStruct(const FBS &fbs, const std::string &indent) {
+ (void)fbs;
+ (void)indent;
+ static constexpr size_t field_count = FBS::Traits::fields_number;
+ std::string out;
+ if constexpr (field_count > 0) {
+ out = std::string(FBS::Traits::fully_qualified_name) + "{\n" +
+ StringifyTableOrStructImpl(fbs, indent + " ",
+ std::make_index_sequence<field_count>{}) +
+ indent + '}';
+ }
+ return out;
+}
+
+template<typename T>
+std::string StringifyVector(const flatbuffers::Vector<T> &vec,
+ const std::string &indent) {
+ const auto prologue = indent + std::string(" ");
+ const auto epilogue = std::string(",\n");
+ std::string text;
+ text += "[\n";
+ for (auto it = vec.cbegin(), end = vec.cend(); it != end; ++it) {
+ text += prologue;
+ text += StringifyFlatbufferValue(*it).value_or("(field absent)");
+ text += epilogue;
+ }
+ if (vec.cbegin() != vec.cend()) {
+ text.resize(text.size() - epilogue.size());
+ }
+ text += '\n' + indent + ']';
+ return text;
+}
+
+template<typename T> std::string StringifyArithmeticType(T val) {
+ return flatbuffers::NumToString(val);
+}
+
+} // namespace detail
+
+/*******************************************************************************
+** Take any flatbuffer type (table, struct, Vector, int...) and stringify it.
+*******************************************************************************/
+template<typename T>
+std::optional<std::string> StringifyFlatbufferValue(T &&val,
+ const std::string &indent) {
+ (void)indent;
+ constexpr bool is_pointer = std::is_pointer_v<std::remove_reference_t<T>>;
+ if constexpr (is_pointer) {
+ if (val == nullptr) return std::nullopt; // Field is absent.
+ }
+ using decayed =
+ std::decay_t<std::remove_pointer_t<std::remove_reference_t<T>>>;
+
+ // Is it a Flatbuffers Table or Struct?
+ if constexpr (detail::is_flatbuffers_table_or_struct_v<decayed>) {
+ // We have a nested table or struct; use recursion!
+ if constexpr (is_pointer)
+ return detail::StringifyTableOrStruct(*val, indent);
+ else
+ return detail::StringifyTableOrStruct(val, indent);
+ }
+
+ // Is it an 8-bit number? If so, print it like an int (not char).
+ else if constexpr (std::is_same_v<decayed, int8_t> ||
+ std::is_same_v<decayed, uint8_t>) {
+ return detail::StringifyArithmeticType(static_cast<int>(val));
+ }
+
+ // Is it an enum? If so, print it like an int, since Flatbuffers doesn't yet
+ // have type-based reflection for enums, so we can't print the enum's name :(
+ else if constexpr (std::is_enum_v<decayed>) {
+ return StringifyFlatbufferValue(
+ static_cast<std::underlying_type_t<decayed>>(val), indent);
+ }
+
+ // Is it an int, double, float, uint32_t, etc.?
+ else if constexpr (std::is_arithmetic_v<decayed>) {
+ return detail::StringifyArithmeticType(val);
+ }
+
+ // Is it a Flatbuffers string?
+ else if constexpr (std::is_same_v<decayed, flatbuffers::String>) {
+ return '"' + val->str() + '"';
+ }
+
+ // Is it a Flatbuffers Vector?
+ else if constexpr (detail::is_flatbuffers_vector_v<decayed>) {
+ return detail::StringifyVector(*val, indent);
+ }
+
+ // Is it a void pointer?
+ else if constexpr (std::is_same_v<decayed, void>) {
+ // Can't format it.
+ return std::nullopt;
+ }
+
+ else {
+ // Not sure how to format this type, whatever it is.
+ static_assert(sizeof(T) != sizeof(T),
+ "Do not know how to format this type T (the compiler error "
+ "should tell you nearby what T is).");
+ }
+}
+
+} // namespace cpp17
diff --git a/tests/cpp17/test_cpp17.cpp b/tests/cpp17/test_cpp17.cpp
index 9b47c10..a17205a 100644
--- a/tests/cpp17/test_cpp17.cpp
+++ b/tests/cpp17/test_cpp17.cpp
@@ -15,7 +15,7 @@
*/
// This is a sandbox for modeling C++17 code generator.
-// C++17 code generator: "flatc --cpp_std c++17".
+// C++17 code generator: "flatc --cpp-std c++17".
// Warning:
// This is an experimental feature and could change at any time.
@@ -25,12 +25,14 @@
#include "flatbuffers/minireflect.h"
#include "flatbuffers/registry.h"
#include "flatbuffers/util.h"
+#include "stringify_util.h"
#include "test_assert.h"
// Embed generated code into an isolated namespace.
namespace cpp17 {
#include "generated_cpp17/monster_test_generated.h"
#include "generated_cpp17/optional_scalars_generated.h"
+#include "generated_cpp17/union_vector_generated.h"
} // namespace cpp17
namespace cpp11 {
@@ -38,6 +40,144 @@
#include "../optional_scalars_generated.h"
} // namespace cpp11
+using ::cpp17::MyGame::Example::Monster;
+using ::cpp17::MyGame::Example::Vec3;
+
+/*******************************************************************************
+** Build some FB objects.
+*******************************************************************************/
+const Monster *BuildMonster(flatbuffers::FlatBufferBuilder &fbb) {
+ using ::cpp17::MyGame::Example::Color;
+ using ::cpp17::MyGame::Example::MonsterBuilder;
+ using ::cpp17::MyGame::Example::Test;
+ auto name = fbb.CreateString("my_monster");
+ auto inventory = fbb.CreateVector(std::vector<uint8_t>{ 4, 5, 6, 7 });
+ MonsterBuilder builder(fbb);
+ auto vec3 = Vec3{ /*x=*/1.1f,
+ /*y=*/2.2f,
+ /*z=*/3.3f,
+ /*test1=*/6.6,
+ /*test2=*/Color::Green,
+ /*test3=*/
+ Test(
+ /*a=*/11,
+ /*b=*/90) };
+ builder.add_pos(&vec3);
+ builder.add_name(name);
+ builder.add_mana(1);
+ builder.add_hp(2);
+ builder.add_testbool(true);
+ builder.add_testhashs32_fnv1(4);
+ builder.add_testhashu32_fnv1(5);
+ builder.add_testhashs64_fnv1(6);
+ builder.add_testhashu64_fnv1(7);
+ builder.add_testhashs32_fnv1a(8);
+ builder.add_testhashu32_fnv1a(9);
+ builder.add_testhashs64_fnv1a(10);
+ builder.add_testhashu64_fnv1a(11);
+ builder.add_testf(12.1f);
+ builder.add_testf2(13.1f);
+ builder.add_testf3(14.1f);
+ builder.add_single_weak_reference(15);
+ builder.add_co_owning_reference(16);
+ builder.add_non_owning_reference(17);
+ builder.add_inventory(inventory);
+ fbb.Finish(builder.Finish());
+ const Monster *monster =
+ flatbuffers::GetRoot<Monster>(fbb.GetBufferPointer());
+ return monster;
+}
+
+/*******************************************************************************
+** Test Case: Static Field Reflection Traits for Table & Structs.
+*******************************************************************************/
+// This test tests & demonstrates the power of the static reflection. Using it,
+// we can given any Flatbuffer type to a generic function and it will be able to
+// produce is full recursive string representation of it.
+//
+// This test covers all types: primitive types, structs, tables, Vectors, etc.
+//
+void StringifyAnyFlatbuffersTypeTest() {
+ flatbuffers::FlatBufferBuilder fbb;
+ // We are using a Monster here, but we could have used any type, because the
+ // code that follows is totally generic!
+ const auto *monster = BuildMonster(fbb);
+
+ std::string expected = R"(MyGame.Example.Monster{
+ pos = MyGame.Example.Vec3{
+ x = 1.1
+ y = 2.2
+ z = 3.3
+ test1 = 6.6
+ test2 = 2
+ test3 = MyGame.Example.Test{
+ a = 11
+ b = 90
+ }
+ }
+ mana = 1
+ hp = 2
+ name = "my_monster"
+ inventory = [
+ 4,
+ 5,
+ 6,
+ 7
+ ]
+ color = 8
+ test_type = 0
+ testbool = 1
+ testhashs32_fnv1 = 4
+ testhashu32_fnv1 = 5
+ testhashs64_fnv1 = 6
+ testhashu64_fnv1 = 7
+ testhashs32_fnv1a = 8
+ testhashu32_fnv1a = 9
+ testhashs64_fnv1a = 10
+ testhashu64_fnv1a = 11
+ testf = 12.1
+ testf2 = 13.1
+ testf3 = 14.1
+ single_weak_reference = 15
+ co_owning_reference = 16
+ non_owning_reference = 17
+ any_unique_type = 0
+ any_ambiguous_type = 0
+ signed_enum = -1
+ })";
+
+ // Call a generic function that has no specific knowledge of the flatbuffer we
+ // are passing in; it should use only static reflection to produce a string
+ // representations of the field names and values recursively. We give it an
+ // initial indentation so that the result can be compared with our raw string
+ // above, which we wanted to indent so that it will look nicer in this code.
+ //
+ // A note about JSON: as can be seen from the string above, this produces a
+ // JSON-like notation, but we are not using any of Flatbuffers' JSON infra to
+ // produce this! It is produced entirely using compile-time reflection, and
+ // thus does not require any runtime access to the *.fbs definition files!
+ std::optional<std::string> result =
+ cpp17::StringifyFlatbufferValue(*monster, /*indent=*/" ");
+
+ TEST_ASSERT(result.has_value());
+ TEST_EQ_STR(expected.c_str(), result->c_str());
+}
+
+/*******************************************************************************
+** Test Traits::FieldType
+*******************************************************************************/
+using pos_type = Monster::Traits::FieldType<0>;
+static_assert(std::is_same_v<pos_type, const Vec3*>);
+
+using mana_type = Monster::Traits::FieldType<1>;
+static_assert(std::is_same_v<mana_type, int16_t>);
+
+using name_type = Monster::Traits::FieldType<3>;
+static_assert(std::is_same_v<name_type, const flatbuffers::String*>);
+
+/*******************************************************************************
+** Generic Create Function Test.
+*******************************************************************************/
void CreateTableByTypeTest() {
flatbuffers::FlatBufferBuilder builder;
@@ -62,7 +202,8 @@
}
void OptionalScalarsTest() {
- static_assert(std::is_same<flatbuffers::Optional<float>, std::optional<float>>::value);
+ static_assert(
+ std::is_same<flatbuffers::Optional<float>, std::optional<float>>::value);
static_assert(std::is_same<flatbuffers::nullopt_t, std::nullopt_t>::value);
// test C++ nullable
@@ -105,6 +246,7 @@
int FlatBufferCpp17Tests() {
CreateTableByTypeTest();
OptionalScalarsTest();
+ StringifyAnyFlatbuffersTypeTest();
return 0;
}
diff --git a/tests/docker/build_flatc.run.sh b/tests/docker/build_flatc.run.sh
index c8885b1..c00adf6 100755
--- a/tests/docker/build_flatc.run.sh
+++ b/tests/docker/build_flatc.run.sh
@@ -10,6 +10,6 @@
-DFLATBUFFERS_BUILD_TESTS=0 -DFLATBUFFERS_INSTALL=0
cmake --build . --target flatc --clean-first -- -j$JOBS
-echo "Check generated code"
-.travis/check-generate-code.sh
+echo "Checking generated code"
+scripts/check_generate_code.py
echo "Done"
diff --git a/tests/docker/cpp_test.run.sh b/tests/docker/cpp_test.run.sh
index fa3b0fb..370662a 100755
--- a/tests/docker/cpp_test.run.sh
+++ b/tests/docker/cpp_test.run.sh
@@ -14,7 +14,7 @@
cmake --build . --target all --clean-first -- -j$JOBS
ctest --extra-verbose --output-on-failure -j$JOBS
-echo "Check generated code"
-.travis/check-generate-code.sh
+echo "Checking generated code"
+scripts/check_generate_code.py
echo "C++ tests done"
diff --git a/tests/docker/languages/Dockerfile.testing.node.10_13_0 b/tests/docker/languages/Dockerfile.testing.node.10_13_0
deleted file mode 100644
index 8e48c23..0000000
--- a/tests/docker/languages/Dockerfile.testing.node.10_13_0
+++ /dev/null
@@ -1,10 +0,0 @@
-FROM node:10.13.0-stretch as base
-WORKDIR /code
-ADD . .
-RUN cp flatc_debian_stretch flatc
-WORKDIR /code/tests
-RUN node --version
-RUN ../flatc -b -I include_test monster_test.fbs unicode_test.json
-RUN npm install
-RUN npm run pretest
-RUN node JavaScriptTest ./monster_test_generated
diff --git a/tests/docker/languages/Dockerfile.testing.node.11_2_0 b/tests/docker/languages/Dockerfile.testing.node.11_2_0
deleted file mode 100644
index 090bb45..0000000
--- a/tests/docker/languages/Dockerfile.testing.node.11_2_0
+++ /dev/null
@@ -1,10 +0,0 @@
-FROM node:11.2.0-stretch as base
-WORKDIR /code
-ADD . .
-RUN cp flatc_debian_stretch flatc
-WORKDIR /code/tests
-RUN node --version
-RUN ../flatc -b -I include_test monster_test.fbs unicode_test.json
-RUN npm install
-RUN npm run pretest
-RUN node JavaScriptTest ./monster_test_generated
diff --git a/tests/docker/languages/Dockerfile.testing.node.12_20_1 b/tests/docker/languages/Dockerfile.testing.node.12_20_1
new file mode 100644
index 0000000..013661f
--- /dev/null
+++ b/tests/docker/languages/Dockerfile.testing.node.12_20_1
@@ -0,0 +1,6 @@
+FROM node:12.20.1-stretch as base
+WORKDIR /code
+ADD . .
+RUN cp flatc_debian_stretch flatc
+RUN npm install
+RUN npm test
diff --git a/tests/docker/languages/Dockerfile.testing.node.14_15_4 b/tests/docker/languages/Dockerfile.testing.node.14_15_4
new file mode 100644
index 0000000..fb546bc
--- /dev/null
+++ b/tests/docker/languages/Dockerfile.testing.node.14_15_4
@@ -0,0 +1,6 @@
+FROM node:14.15.4-stretch as base
+WORKDIR /code
+ADD . .
+RUN cp flatc_debian_stretch flatc
+RUN npm install
+RUN npm test
diff --git a/tests/docker/languages/Dockerfile.testing.rust.1_40_0 b/tests/docker/languages/Dockerfile.testing.rust.1_40_0
deleted file mode 100644
index 849ad76..0000000
--- a/tests/docker/languages/Dockerfile.testing.rust.1_40_0
+++ /dev/null
@@ -1,7 +0,0 @@
-FROM rust:1.40.0-slim-stretch as base
-WORKDIR /code
-ADD . .
-RUN cp flatc_debian_stretch flatc
-WORKDIR /code/tests
-RUN rustc --version
-RUN ./RustTest.sh
diff --git a/tests/docker/languages/Dockerfile.testing.rust.1_51_0 b/tests/docker/languages/Dockerfile.testing.rust.1_51_0
new file mode 100644
index 0000000..38c1d26
--- /dev/null
+++ b/tests/docker/languages/Dockerfile.testing.rust.1_51_0
@@ -0,0 +1,7 @@
+FROM rust:1.51.0-slim as base
+WORKDIR /code
+ADD . .
+RUN cp flatc_debian_stretch flatc
+WORKDIR /code/tests
+RUN rustc --version
+RUN ./RustTest.sh
diff --git a/tests/docker/languages/Dockerfile.testing.rust.big_endian.1_40_0 b/tests/docker/languages/Dockerfile.testing.rust.big_endian.1_40_0
deleted file mode 100644
index 3abf8df..0000000
--- a/tests/docker/languages/Dockerfile.testing.rust.big_endian.1_40_0
+++ /dev/null
@@ -1,15 +0,0 @@
-FROM rust:1.40.0-slim-stretch as base
-RUN apt -qq update -y && apt -qq install -y \
- gcc-mips-linux-gnu \
- libexpat1 \
- libmagic1 \
- libmpdec2 \
- libreadline7 \
- qemu-user
-RUN rustup target add mips-unknown-linux-gnu
-WORKDIR /code
-ADD . .
-RUN cp flatc_debian_stretch flatc
-WORKDIR /code/tests
-RUN rustc --version
-RUN ./RustTest.sh mips-unknown-linux-gnu
diff --git a/tests/docker/languages/Dockerfile.testing.rust.big_endian.1_51_0 b/tests/docker/languages/Dockerfile.testing.rust.big_endian.1_51_0
new file mode 100644
index 0000000..aa35ed7
--- /dev/null
+++ b/tests/docker/languages/Dockerfile.testing.rust.big_endian.1_51_0
@@ -0,0 +1,15 @@
+FROM rust:1.51.0-slim as base
+RUN apt -qq update -y && apt -qq install -y \
+ gcc-mips-linux-gnu \
+ libexpat1 \
+ libmagic1 \
+ libmpdec2 \
+ libreadline7 \
+ qemu-user
+RUN rustup target add mips-unknown-linux-gnu
+WORKDIR /code
+ADD . .
+RUN cp flatc_debian_stretch flatc
+WORKDIR /code/tests
+RUN rustc --version
+RUN ./RustTest.sh mips-unknown-linux-gnu
diff --git a/tests/docker/languages/Dockerfile.testing.rust.nightly b/tests/docker/languages/Dockerfile.testing.rust.nightly
new file mode 100644
index 0000000..5194d6d
--- /dev/null
+++ b/tests/docker/languages/Dockerfile.testing.rust.nightly
@@ -0,0 +1,8 @@
+FROM rustlang/rust:nightly-stretch-slim as base
+WORKDIR /code
+ADD . .
+RUN cp flatc_debian_stretch flatc
+WORKDIR /code/tests
+RUN rustc --version
+RUN export RUST_NIGHTLY=1
+RUN ./RustTest.sh
diff --git a/tests/evolution_test/evolution_v1_generated.h b/tests/evolution_test/evolution_v1_generated.h
index a9c2b7f..d5ddf8f 100644
--- a/tests/evolution_test/evolution_v1_generated.h
+++ b/tests/evolution_test/evolution_v1_generated.h
@@ -96,7 +96,7 @@
};
bool VerifyUnion(flatbuffers::Verifier &verifier, const void *obj, Union type);
-bool VerifyUnionVector(flatbuffers::Verifier &verifier, const flatbuffers::Vector<flatbuffers::Offset<void>> *values, const flatbuffers::Vector<uint8_t> *types);
+bool VerifyUnionVector(flatbuffers::Verifier &verifier, const flatbuffers::Vector<flatbuffers::Offset<void>> *values, const flatbuffers::Vector<Union> *types);
FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(8) Struct FLATBUFFERS_FINAL_CLASS {
private:
@@ -151,8 +151,8 @@
}
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
- VerifyField<float>(verifier, VT_A) &&
- VerifyField<int32_t>(verifier, VT_B) &&
+ VerifyField<float>(verifier, VT_A, 4) &&
+ VerifyField<int32_t>(verifier, VT_B, 4) &&
verifier.EndTable();
}
};
@@ -198,7 +198,7 @@
}
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
- VerifyField<int32_t>(verifier, VT_A) &&
+ VerifyField<int32_t>(verifier, VT_A, 4) &&
verifier.EndTable();
}
};
@@ -297,22 +297,22 @@
}
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
- VerifyField<int32_t>(verifier, VT_A) &&
- VerifyField<uint8_t>(verifier, VT_B) &&
- VerifyField<uint8_t>(verifier, VT_C_TYPE) &&
+ VerifyField<int32_t>(verifier, VT_A, 4) &&
+ VerifyField<uint8_t>(verifier, VT_B, 1) &&
+ VerifyField<uint8_t>(verifier, VT_C_TYPE, 1) &&
VerifyOffset(verifier, VT_C) &&
VerifyUnion(verifier, c(), c_type()) &&
- VerifyField<int8_t>(verifier, VT_D) &&
+ VerifyField<int8_t>(verifier, VT_D, 1) &&
VerifyOffset(verifier, VT_E) &&
verifier.VerifyTable(e()) &&
- VerifyField<Evolution::V1::Struct>(verifier, VT_F) &&
+ VerifyField<Evolution::V1::Struct>(verifier, VT_F, 8) &&
VerifyOffset(verifier, VT_G) &&
verifier.VerifyVector(g()) &&
VerifyOffset(verifier, VT_H) &&
verifier.VerifyVector(h()) &&
verifier.VerifyVectorOfTables(h()) &&
- VerifyField<int32_t>(verifier, VT_I) &&
- VerifyField<uint8_t>(verifier, VT_J_TYPE) &&
+ VerifyField<int32_t>(verifier, VT_I, 4) &&
+ VerifyField<uint8_t>(verifier, VT_J_TYPE, 1) &&
VerifyOffset(verifier, VT_J) &&
VerifyUnion(verifier, j(), j_type()) &&
verifier.EndTable();
@@ -394,7 +394,7 @@
flatbuffers::Offset<void> c = 0,
Evolution::V1::Enum d = Evolution::V1::Enum::King,
flatbuffers::Offset<Evolution::V1::TableA> e = 0,
- const Evolution::V1::Struct *f = 0,
+ const Evolution::V1::Struct *f = nullptr,
flatbuffers::Offset<flatbuffers::Vector<int32_t>> g = 0,
flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Evolution::V1::TableB>>> h = 0,
int32_t i = 1234,
@@ -424,7 +424,7 @@
flatbuffers::Offset<void> c = 0,
Evolution::V1::Enum d = Evolution::V1::Enum::King,
flatbuffers::Offset<Evolution::V1::TableA> e = 0,
- const Evolution::V1::Struct *f = 0,
+ const Evolution::V1::Struct *f = nullptr,
const std::vector<int32_t> *g = nullptr,
const std::vector<flatbuffers::Offset<Evolution::V1::TableB>> *h = nullptr,
int32_t i = 1234,
@@ -465,7 +465,7 @@
}
}
-inline bool VerifyUnionVector(flatbuffers::Verifier &verifier, const flatbuffers::Vector<flatbuffers::Offset<void>> *values, const flatbuffers::Vector<uint8_t> *types) {
+inline bool VerifyUnionVector(flatbuffers::Verifier &verifier, const flatbuffers::Vector<flatbuffers::Offset<void>> *values, const flatbuffers::Vector<Union> *types) {
if (!values || !types) return !values && !types;
if (values->size() != types->size()) return false;
for (flatbuffers::uoffset_t i = 0; i < values->size(); ++i) {
diff --git a/tests/evolution_test/evolution_v2_generated.h b/tests/evolution_test/evolution_v2_generated.h
index 303d94d..2a0efcb 100644
--- a/tests/evolution_test/evolution_v2_generated.h
+++ b/tests/evolution_test/evolution_v2_generated.h
@@ -112,7 +112,7 @@
};
bool VerifyUnion(flatbuffers::Verifier &verifier, const void *obj, Union type);
-bool VerifyUnionVector(flatbuffers::Verifier &verifier, const flatbuffers::Vector<flatbuffers::Offset<void>> *values, const flatbuffers::Vector<uint8_t> *types);
+bool VerifyUnionVector(flatbuffers::Verifier &verifier, const flatbuffers::Vector<flatbuffers::Offset<void>> *values, const flatbuffers::Vector<Union> *types);
FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(8) Struct FLATBUFFERS_FINAL_CLASS {
private:
@@ -171,8 +171,8 @@
}
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
- VerifyField<float>(verifier, VT_A) &&
- VerifyField<int32_t>(verifier, VT_B) &&
+ VerifyField<float>(verifier, VT_A, 4) &&
+ VerifyField<int32_t>(verifier, VT_B, 4) &&
VerifyOffset(verifier, VT_C) &&
verifier.VerifyString(c()) &&
verifier.EndTable();
@@ -238,7 +238,7 @@
}
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
- VerifyField<int32_t>(verifier, VT_A) &&
+ VerifyField<int32_t>(verifier, VT_A, 4) &&
verifier.EndTable();
}
};
@@ -283,7 +283,7 @@
}
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
- VerifyField<double>(verifier, VT_A) &&
+ VerifyField<double>(verifier, VT_A, 8) &&
VerifyOffset(verifier, VT_B) &&
verifier.VerifyString(b()) &&
verifier.EndTable();
@@ -392,23 +392,23 @@
}
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
- VerifyField<uint8_t>(verifier, VT_B) &&
- VerifyField<uint8_t>(verifier, VT_C_TYPE) &&
+ VerifyField<uint8_t>(verifier, VT_B, 1) &&
+ VerifyField<uint8_t>(verifier, VT_C_TYPE, 1) &&
VerifyOffset(verifier, VT_C) &&
VerifyUnion(verifier, c(), c_type()) &&
- VerifyField<int8_t>(verifier, VT_D) &&
+ VerifyField<int8_t>(verifier, VT_D, 1) &&
VerifyOffset(verifier, VT_E) &&
verifier.VerifyTable(e()) &&
- VerifyField<Evolution::V2::Struct>(verifier, VT_FF) &&
+ VerifyField<Evolution::V2::Struct>(verifier, VT_FF, 8) &&
VerifyOffset(verifier, VT_G) &&
verifier.VerifyVector(g()) &&
VerifyOffset(verifier, VT_H) &&
verifier.VerifyVector(h()) &&
verifier.VerifyVectorOfTables(h()) &&
- VerifyField<uint32_t>(verifier, VT_I) &&
+ VerifyField<uint32_t>(verifier, VT_I, 4) &&
VerifyOffset(verifier, VT_K) &&
verifier.VerifyTable(k()) &&
- VerifyField<uint8_t>(verifier, VT_L) &&
+ VerifyField<uint8_t>(verifier, VT_L, 1) &&
verifier.EndTable();
}
};
@@ -480,7 +480,7 @@
flatbuffers::Offset<void> c = 0,
Evolution::V2::Enum d = Evolution::V2::Enum::King,
flatbuffers::Offset<Evolution::V2::TableA> e = 0,
- const Evolution::V2::Struct *ff = 0,
+ const Evolution::V2::Struct *ff = nullptr,
flatbuffers::Offset<flatbuffers::Vector<int32_t>> g = 0,
flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Evolution::V2::TableB>>> h = 0,
uint32_t i = 1234,
@@ -508,7 +508,7 @@
flatbuffers::Offset<void> c = 0,
Evolution::V2::Enum d = Evolution::V2::Enum::King,
flatbuffers::Offset<Evolution::V2::TableA> e = 0,
- const Evolution::V2::Struct *ff = 0,
+ const Evolution::V2::Struct *ff = nullptr,
const std::vector<int32_t> *g = nullptr,
const std::vector<flatbuffers::Offset<Evolution::V2::TableB>> *h = nullptr,
uint32_t i = 1234,
@@ -552,7 +552,7 @@
}
}
-inline bool VerifyUnionVector(flatbuffers::Verifier &verifier, const flatbuffers::Vector<flatbuffers::Offset<void>> *values, const flatbuffers::Vector<uint8_t> *types) {
+inline bool VerifyUnionVector(flatbuffers::Verifier &verifier, const flatbuffers::Vector<flatbuffers::Offset<void>> *values, const flatbuffers::Vector<Union> *types) {
if (!values || !types) return !values && !types;
if (values->size() != types->size()) return false;
for (flatbuffers::uoffset_t i = 0; i < values->size(); ++i) {
diff --git a/tests/fuzzer/CMakeLists.txt b/tests/fuzzer/CMakeLists.txt
index 5deba0f..9cc5a5f 100644
--- a/tests/fuzzer/CMakeLists.txt
+++ b/tests/fuzzer/CMakeLists.txt
@@ -10,7 +10,7 @@
if(NOT DEFINED FLATBUFFERS_MAX_PARSING_DEPTH)
# Force checking of RecursionError in the test
- set(FLATBUFFERS_MAX_PARSING_DEPTH 8)
+ set(FLATBUFFERS_MAX_PARSING_DEPTH 24)
endif()
message(STATUS "FLATBUFFERS_MAX_PARSING_DEPTH: ${FLATBUFFERS_MAX_PARSING_DEPTH}")
@@ -53,7 +53,7 @@
fuzzer_config
INTERFACE
$<$<NOT:$<BOOL:${OSS_FUZZ}>>:
- -fsanitize-coverage=edge,trace-cmp
+ -fsanitize-coverage=trace-cmp
>
$<$<BOOL:${USE_ASAN}>:
-fsanitize=fuzzer,undefined,address
@@ -85,17 +85,30 @@
set(FLATBUFFERS_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../")
set(FlatBuffers_Library_SRCS
+ ${FLATBUFFERS_DIR}/include/flatbuffers/allocator.h
+ ${FLATBUFFERS_DIR}/include/flatbuffers/array.h
${FLATBUFFERS_DIR}/include/flatbuffers/base.h
+ ${FLATBUFFERS_DIR}/include/flatbuffers/buffer.h
+ ${FLATBUFFERS_DIR}/include/flatbuffers/buffer_ref.h
+ ${FLATBUFFERS_DIR}/include/flatbuffers/default_allocator.h
+ ${FLATBUFFERS_DIR}/include/flatbuffers/detached_buffer.h
+ ${FLATBUFFERS_DIR}/include/flatbuffers/flatbuffer_builder.h
${FLATBUFFERS_DIR}/include/flatbuffers/flatbuffers.h
+ ${FLATBUFFERS_DIR}/include/flatbuffers/flexbuffers.h
${FLATBUFFERS_DIR}/include/flatbuffers/hash.h
${FLATBUFFERS_DIR}/include/flatbuffers/idl.h
- ${FLATBUFFERS_DIR}/include/flatbuffers/util.h
+ ${FLATBUFFERS_DIR}/include/flatbuffers/minireflect.h
${FLATBUFFERS_DIR}/include/flatbuffers/reflection.h
${FLATBUFFERS_DIR}/include/flatbuffers/reflection_generated.h
- ${FLATBUFFERS_DIR}/include/flatbuffers/stl_emulation.h
- ${FLATBUFFERS_DIR}/include/flatbuffers/flexbuffers.h
${FLATBUFFERS_DIR}/include/flatbuffers/registry.h
- ${FLATBUFFERS_DIR}/include/flatbuffers/minireflect.h
+ ${FLATBUFFERS_DIR}/include/flatbuffers/stl_emulation.h
+ ${FLATBUFFERS_DIR}/include/flatbuffers/string.h
+ ${FLATBUFFERS_DIR}/include/flatbuffers/struct.h
+ ${FLATBUFFERS_DIR}/include/flatbuffers/table.h
+ ${FLATBUFFERS_DIR}/include/flatbuffers/util.h
+ ${FLATBUFFERS_DIR}/include/flatbuffers/vector.h
+ ${FLATBUFFERS_DIR}/include/flatbuffers/vector_downward.h
+ ${FLATBUFFERS_DIR}/include/flatbuffers/verifier.h
${FLATBUFFERS_DIR}/src/idl_parser.cpp
${FLATBUFFERS_DIR}/src/idl_gen_text.cpp
${FLATBUFFERS_DIR}/src/reflection.cpp
@@ -133,12 +146,38 @@
add_executable(verifier_fuzzer flatbuffers_verifier_fuzzer.cc)
target_link_libraries(verifier_fuzzer PRIVATE flatbuffers_fuzzed)
+add_executable(flexverifier_fuzzer flexbuffers_verifier_fuzzer.cc)
+target_link_libraries(flexverifier_fuzzer PRIVATE flatbuffers_fuzzed)
+
add_executable(monster_fuzzer flatbuffers_monster_fuzzer.cc)
target_link_libraries(monster_fuzzer PRIVATE flatbuffers_fuzzed)
+add_custom_command(
+ TARGET monster_fuzzer PRE_BUILD
+ COMMAND ${CMAKE_COMMAND} -E copy
+ ${CMAKE_SOURCE_DIR}/../monster_test.bfbs
+ ${CMAKE_CURRENT_BINARY_DIR}/monster_test.bfbs)
+
# Build debugger for weird cases found with fuzzer.
if(BUILD_DEBUGGER)
add_library(flatbuffers_nonfuzz STATIC ${FlatBuffers_Library_SRCS})
+ target_compile_options(
+ flatbuffers_nonfuzz
+ PUBLIC
+ $<$<BOOL:${USE_ASAN}>:
+ -fsanitize=undefined,address
+ >
+ -fno-limit-debug-info
+ )
+
+ target_link_libraries(
+ flatbuffers_nonfuzz
+ PUBLIC
+ $<$<BOOL:${USE_ASAN}>:
+ -fsanitize=undefined,address
+ >
+ )
+
target_compile_definitions(
flatbuffers_nonfuzz
PUBLIC
@@ -147,6 +186,21 @@
PRIVATE
FLATBUFFERS_MAX_PARSING_DEPTH=${FLATBUFFERS_MAX_PARSING_DEPTH}
)
- add_executable(scalar_debug flatbuffers_scalar_fuzzer.cc scalar_debug.cpp)
+ add_executable(scalar_debug
+ flatbuffers_scalar_fuzzer.cc
+ scalar_debug.cpp
+ )
target_link_libraries(scalar_debug PRIVATE flatbuffers_nonfuzz)
+
+ add_executable(monster_debug
+ flatbuffers_monster_fuzzer.cc
+ monster_debug.cpp
+ )
+ target_link_libraries(monster_debug PRIVATE flatbuffers_nonfuzz)
+ add_custom_command(
+ TARGET monster_debug PRE_BUILD
+ COMMAND ${CMAKE_COMMAND} -E copy
+ ${CMAKE_SOURCE_DIR}/../monster_test.bfbs
+ ${CMAKE_CURRENT_BINARY_DIR}/monster_test.bfbs)
+
endif(BUILD_DEBUGGER)
diff --git a/tests/fuzzer/flatbuffers_monster_fuzzer.cc b/tests/fuzzer/flatbuffers_monster_fuzzer.cc
index 9464607..8981c2f 100644
--- a/tests/fuzzer/flatbuffers_monster_fuzzer.cc
+++ b/tests/fuzzer/flatbuffers_monster_fuzzer.cc
@@ -18,78 +18,90 @@
#include <stdint.h>
#include <clocale>
+#include <filesystem>
#include <string>
#include "cpp17/generated_cpp17/monster_test_generated.h"
#include "flatbuffers/idl.h"
#include "test_init.h"
+namespace fs = std::filesystem;
+
+// Utility for test run.
+OneTimeTestInit OneTimeTestInit::one_time_init_;
+// The current executable path (see LLVMFuzzerInitialize).
+static fs::path exe_path_;
+
namespace {
-constexpr bool use_binary_schema = true;
-// should point to flatbuffers/tests/
-constexpr const char *test_data_path = "../../";
-constexpr const char *schema_file_name = "monster_test";
+
+static constexpr size_t kMinInputLength = 1;
+static constexpr size_t kMaxInputLength = 16384;
static constexpr uint8_t flags_strict_json = 0x80;
static constexpr uint8_t flags_skip_unexpected_fields_in_json = 0x40;
static constexpr uint8_t flags_allow_non_utf8 = 0x20;
-flatbuffers::Parser make_parser(const flatbuffers::IDLOptions opts) {
- // once loaded from disk
- static const std::string schemafile = [&]() {
- std::string schemafile;
- TEST_EQ(
- flatbuffers::LoadFile((std::string(test_data_path) + schema_file_name +
- (use_binary_schema ? ".bfbs" : ".fbs"))
- .c_str(),
- use_binary_schema, &schemafile),
- true);
+bool TestFileExists(fs::path file_path) {
+ if (file_path.has_filename() && fs::exists(file_path)) return true;
- if (use_binary_schema) {
- flatbuffers::Verifier verifier(
- reinterpret_cast<const uint8_t *>(schemafile.c_str()),
- schemafile.size());
- TEST_EQ(reflection::VerifySchemaBuffer(verifier), true);
- }
- return schemafile;
- }();
-
- // parse schema first, so we can use it to parse the data after
- flatbuffers::Parser parser;
- if (use_binary_schema) {
- TEST_EQ(parser.Deserialize(
- reinterpret_cast<const uint8_t *>(schemafile.c_str()),
- schemafile.size()),
- true);
- } else {
- auto include_test_path =
- flatbuffers::ConCatPathFileName(test_data_path, "include_test");
- const char *include_directories[] = { test_data_path,
- include_test_path.c_str(), nullptr };
- TEST_EQ(parser.Parse(schemafile.c_str(), include_directories), true);
+ TEST_OUTPUT_LINE("@DEBUG: file '%s' not found", file_path.string().c_str());
+ for (const auto &entry : fs::directory_iterator(file_path.parent_path())) {
+ TEST_OUTPUT_LINE("@DEBUG: parent path entry: '%s'", entry.path().string().c_str());
}
- // (re)define parser options
- parser.opts = opts;
- return parser;
+ return false;
+}
+
+std::string LoadBinarySchema(const char *file_name) {
+ const auto file_path = exe_path_.parent_path() / file_name;
+ TEST_EQ(true, TestFileExists(file_path));
+ std::string schemafile;
+ TEST_EQ(true, flatbuffers::LoadFile(file_path.string().c_str(), true, &schemafile));
+
+ flatbuffers::Verifier verifier(
+ reinterpret_cast<const uint8_t *>(schemafile.c_str()), schemafile.size());
+ TEST_EQ(true, reflection::VerifySchemaBuffer(verifier));
+ return schemafile;
}
std::string do_test(const flatbuffers::IDLOptions &opts,
- const std::string input_json) {
- auto parser = make_parser(opts);
+ const std::string input_json, const bool check_parser) {
+ // once loaded from disk
+ static const std::string schemafile = LoadBinarySchema("monster_test.bfbs");
+ // parse schema first, so we can use it to parse the data after
+ flatbuffers::Parser parser;
+ TEST_EQ(true, parser.Deserialize(
+ reinterpret_cast<const uint8_t *>(schemafile.c_str()),
+ schemafile.size()));
+ // (re)define parser options
+ parser.opts = opts;
+
std::string jsongen;
if (parser.ParseJson(input_json.c_str())) {
flatbuffers::Verifier verifier(parser.builder_.GetBufferPointer(),
parser.builder_.GetSize());
- TEST_EQ(MyGame::Example::VerifyMonsterBuffer(verifier), true);
+ TEST_EQ(true, MyGame::Example::VerifyMonsterBuffer(verifier));
TEST_ASSERT(
GenerateText(parser, parser.builder_.GetBufferPointer(), &jsongen));
+ } else if (check_parser) {
+ TEST_OUTPUT_LINE("parser failed with JSON:\n%s", input_json.c_str());
+ TEST_EQ_STR("", parser.error_.c_str());
+ TEST_ASSERT(false);
}
return jsongen;
};
} // namespace
-// Utility for test run.
-OneTimeTestInit OneTimeTestInit::one_time_init_;
+// https://google.github.io/oss-fuzz/further-reading/fuzzer-environment/
+// Current working directory
+// You should not make any assumptions about the current working directory of
+// your fuzz target. If you need to load data files, please use argv[0] to get
+// the directory where your fuzz target executable is located.
+// You must not modify argv[0].
+extern "C" int LLVMFuzzerInitialize(int *argc, char ***argv) {
+ (void)argc;
+ exe_path_ = (*argv)[0];
+ return 0;
+}
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
// Reserve one byte for Parser flags and one byte for repetition counter.
@@ -101,7 +113,8 @@
const std::string original(reinterpret_cast<const char *>(data), size);
auto input = std::string(original.c_str()); // until '\0'
- if (input.empty()) return 0;
+ if (input.size() < kMinInputLength || input.size() > kMaxInputLength)
+ return 0;
flatbuffers::IDLOptions opts;
opts.strict_json = (flags & flags_strict_json);
@@ -109,9 +122,9 @@
(flags & flags_skip_unexpected_fields_in_json);
opts.allow_non_utf8 = (flags & flags_allow_non_utf8);
- const std::string jsongen_1 = do_test(opts, input);
+ const std::string jsongen_1 = do_test(opts, input, false);
if (!jsongen_1.empty()) {
- const std::string jsongen_2 = do_test(opts, jsongen_1);
+ const std::string jsongen_2 = do_test(opts, jsongen_1, true);
TEST_EQ(jsongen_1, jsongen_2);
}
return 0;
diff --git a/tests/fuzzer/flatbuffers_parser_fuzzer.cc b/tests/fuzzer/flatbuffers_parser_fuzzer.cc
index a7483a5..0b74f2c 100644
--- a/tests/fuzzer/flatbuffers_parser_fuzzer.cc
+++ b/tests/fuzzer/flatbuffers_parser_fuzzer.cc
@@ -9,6 +9,9 @@
#include "flatbuffers/idl.h"
#include "test_init.h"
+static constexpr size_t kMinInputLength = 1;
+static constexpr size_t kMaxInputLength = 16384;
+
static constexpr uint8_t flags_strict_json = 0x80;
static constexpr uint8_t flags_skip_unexpected_fields_in_json = 0x40;
static constexpr uint8_t flags_allow_non_utf8 = 0x20;
@@ -20,15 +23,14 @@
// Reserve one byte for Parser flags and one byte for repetition counter.
if (size < 3) return 0;
const uint8_t flags = data[0];
- // normalize to ascii alphabet
- const int extra_rep_number =
- std::max(5, (data[1] < '0' ? (data[1] - '0') : 0));
+ (void)data[1]; // reserved
data += 2;
size -= 2; // bypass
const std::string original(reinterpret_cast<const char *>(data), size);
auto input = std::string(original.c_str()); // until '\0'
- if (input.empty()) return 0;
+ if (input.size() < kMinInputLength || input.size() > kMaxInputLength)
+ return 0;
flatbuffers::IDLOptions opts;
opts.strict_json = (flags & flags_strict_json);
@@ -41,23 +43,13 @@
// Guarantee 0-termination in the input.
auto parse_input = input.c_str();
- // The fuzzer can adjust the number repetition if a side-effects have found.
- // Each test should pass at least two times to ensure that the parser doesn't
- // have any hidden-states or locale-depended effects.
- for (auto cnt = 0; cnt < (extra_rep_number + 2); cnt++) {
- // Each even run (0,2,4..) will test locale independed code.
- auto use_locale = !!OneTimeTestInit::test_locale() && (0 == (cnt % 2));
- // Set new locale.
- if (use_locale) {
- FLATBUFFERS_ASSERT(setlocale(LC_ALL, OneTimeTestInit::test_locale()));
- }
-
- // Check Parser.
- parser.Parse(parse_input);
-
- // Restore locale.
- if (use_locale) { FLATBUFFERS_ASSERT(setlocale(LC_ALL, "C")); }
- }
-
+ // Check Parser.
+ parser.Parse(parse_input);
+ // TODO:
+ // Need to add additional checks for inputs passed Parse(parse_input) successfully:
+ // 1. Serialization to bfbs.
+ // 2. Generation of a default object.
+ // 3. Verification of the object using reflection.
+ // 3. Printing to json.
return 0;
}
diff --git a/tests/fuzzer/flatbuffers_scalar_fuzzer.cc b/tests/fuzzer/flatbuffers_scalar_fuzzer.cc
index 3c711fc..faa069e 100644
--- a/tests/fuzzer/flatbuffers_scalar_fuzzer.cc
+++ b/tests/fuzzer/flatbuffers_scalar_fuzzer.cc
@@ -27,6 +27,9 @@
#include "flatbuffers/idl.h"
#include "test_init.h"
+static constexpr size_t kMinInputLength = 1;
+static constexpr size_t kMaxInputLength = 3000;
+
static constexpr uint8_t flags_scalar_type = 0x0F; // type of scalar value
static constexpr uint8_t flags_quotes_kind = 0x10; // quote " or '
// reserved for future: json {named} or [unnamed]
@@ -234,14 +237,15 @@
const uint8_t flags = data[0];
// normalize to ascii alphabet
const int extra_rep_number =
- std::max(5, (data[1] < '0' ? (data[1] - '0') : 0));
+ std::max(5, (data[1] > '0' ? (data[1] - '0') : 0));
data += 2;
size -= 2; // bypass
// Guarantee 0-termination.
const std::string original(reinterpret_cast<const char *>(data), size);
auto input = std::string(original.c_str()); // until '\0'
- if (input.empty()) return 0;
+ if (input.size() < kMinInputLength || input.size() > kMaxInputLength)
+ return 0;
// Break comments in json to avoid complexity with regex matcher.
// The string " 12345 /* text */" will be accepted if insert it to string
@@ -288,7 +292,7 @@
}
// Parse original input as-is.
- auto orig_scalar = "{ \"Y\" : " + input + " }";
+ auto orig_scalar = "{\"Y\" : " + input + "}";
std::string orig_back;
auto orig_done = Parse(parser, orig_scalar, &orig_back);
@@ -326,7 +330,7 @@
// Test quoted version of the string
if (!qouted_input.empty()) {
- auto fix_scalar = "{ \"Y\" : " + qouted_input + " }";
+ auto fix_scalar = "{\"Y\" : " + qouted_input + "}";
std::string fix_back;
auto fix_done = Parse(parser, fix_scalar, &fix_back);
diff --git a/tests/fuzzer/flexbuffers_verifier_fuzzer.cc b/tests/fuzzer/flexbuffers_verifier_fuzzer.cc
new file mode 100644
index 0000000..ad374b3
--- /dev/null
+++ b/tests/fuzzer/flexbuffers_verifier_fuzzer.cc
@@ -0,0 +1,19 @@
+// Copyright 2015 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+#include <stddef.h>
+#include <stdint.h>
+#include <string>
+
+#include "flatbuffers/flexbuffers.h"
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
+ std::vector<uint8_t> reuse_tracker;
+ // Check both with and without reuse tracker paths.
+ flexbuffers::VerifyBuffer(data, size, &reuse_tracker);
+ // FIXME: we can't really verify this path, because the fuzzer will
+ // construct buffers that time out.
+ // Add a simple #define to bound the number of steps just for the fuzzer?
+ //flexbuffers::VerifyBuffer(data, size, nullptr);
+ return 0;
+}
diff --git a/tests/fuzzer/fuzzer_assert.h b/tests/fuzzer/fuzzer_assert.h
index afdcf78..41a4164 100644
--- a/tests/fuzzer/fuzzer_assert.h
+++ b/tests/fuzzer/fuzzer_assert.h
@@ -1,9 +1,14 @@
#ifndef FUZZER_ASSERT_IMPL_H_
#define FUZZER_ASSERT_IMPL_H_
+#if defined(_MSC_VER)
+extern "C" void __debugbreak();
+#define __builtin_trap __debugbreak
+#else // Clang
+extern "C" void __builtin_trap(void);
+#endif
+
// Declare Debug/Release independed assert macro.
#define fuzzer_assert_impl(x) (!!(x) ? static_cast<void>(0) : __builtin_trap())
-extern "C" void __builtin_trap(void);
-
#endif // !FUZZER_ASSERT_IMPL_H_
diff --git a/tests/fuzzer/monster_debug.cpp b/tests/fuzzer/monster_debug.cpp
new file mode 100644
index 0000000..c7a02e1
--- /dev/null
+++ b/tests/fuzzer/monster_debug.cpp
@@ -0,0 +1,30 @@
+#include <iostream>
+#include <assert.h>
+
+#include "flatbuffers/util.h"
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size);
+
+int main(int argc, char *argv[]) {
+ if (argc < 2) {
+ std::cerr << "Usage: monster_debug <path to fuzzer crash file>\n";
+ return 0;
+ }
+ std::string crash_file_name(argv[1]);
+ std::string crash_file_data;
+ auto done =
+ flatbuffers::LoadFile(crash_file_name.c_str(), true, &crash_file_data);
+ if (!done) {
+ std::cerr << "Can not load file: '" << crash_file_name << "'";
+ return -1;
+ }
+ if (crash_file_data.size() < 3) {
+ std::cerr << "Invalid file data: '" << crash_file_data << "'";
+ return -2;
+ }
+ auto rc = LLVMFuzzerTestOneInput(
+ reinterpret_cast<const uint8_t *>(crash_file_data.data()),
+ crash_file_data.size());
+ std::cout << "LLVMFuzzerTestOneInput finished with code " << rc << "\n\n";
+ return rc;
+}
diff --git a/tests/fuzzer/monster_json.dict b/tests/fuzzer/monster_fuzzer.dict
similarity index 100%
rename from tests/fuzzer/monster_json.dict
rename to tests/fuzzer/monster_fuzzer.dict
diff --git a/tests/fuzzer/parser_fbs.dict b/tests/fuzzer/parser_fuzzer.dict
similarity index 100%
rename from tests/fuzzer/parser_fbs.dict
rename to tests/fuzzer/parser_fuzzer.dict
diff --git a/tests/fuzzer/readme.md b/tests/fuzzer/readme.md
index b2c7db4..1d0b392 100644
--- a/tests/fuzzer/readme.md
+++ b/tests/fuzzer/readme.md
@@ -10,10 +10,17 @@
To build and run these tests LLVM compiler (with clang frontend) and CMake should be installed before.
-The fuzzer section include three tests:
+The fuzzer section include four tests:
- `verifier_fuzzer` checks stability of deserialization engine for `Monster` schema;
- `parser_fuzzer` checks stability of schema and json parser under various inputs;
- `scalar_parser` focused on validation of the parser while parse numeric scalars in schema and/or json files;
+- `flexverifier_fuzzer` checks stability of deserialization engine for FlexBuffers only;
+
+## Build
+```sh
+cd tests/fuzzer
+CC=clang CXX=clang++ cmake . -DCMAKE_BUILD_TYPE=Debug -DUSE_ASAN=ON
+```
## Run tests with a specific locale
The grammar of the Flatbuffers library is based on printable-ASCII characters.
diff --git a/tests/fuzzer/scalar_debug.cpp b/tests/fuzzer/scalar_debug.cpp
index 9ce9e5e..d0c9b40 100644
--- a/tests/fuzzer/scalar_debug.cpp
+++ b/tests/fuzzer/scalar_debug.cpp
@@ -23,6 +23,6 @@
auto rc = LLVMFuzzerTestOneInput(
reinterpret_cast<const uint8_t *>(crash_file_data.data()),
crash_file_data.size());
- std::cout << "LLVMFuzzerTestOneInput finished with code " << rc;
+ std::cout << "LLVMFuzzerTestOneInput finished with code " << rc << "\n\n";
return rc;
}
diff --git a/tests/fuzzer/scalar_fuzzer.dict b/tests/fuzzer/scalar_fuzzer.dict
new file mode 100644
index 0000000..3b2fbc8
--- /dev/null
+++ b/tests/fuzzer/scalar_fuzzer.dict
@@ -0,0 +1,37 @@
+"-"
+"+"
+"."
+"e"
+"e+"
+"e-"
+"E"
+"E+"
+"E-"
+"0x"
+"-0x"
+"p"
+"0"
+"1"
+"2"
+"3"
+"4"
+"5"
+"6"
+"7"
+"8"
+"9"
+"a"
+"b"
+"c"
+"d"
+"e"
+"f"
+"nan"
+"-nan"
+"+nan"
+"inf"
+"+inf"
+"-inf"
+"infinity"
+"+infinity"
+"-infinity"
diff --git a/tests/fuzzer/scalar_json.dict b/tests/fuzzer/scalar_json.dict
deleted file mode 100644
index 60689dd..0000000
--- a/tests/fuzzer/scalar_json.dict
+++ /dev/null
@@ -1,23 +0,0 @@
-"-"
-"+"
-"."
-"e"
-"e+"
-"e-"
-"E"
-"E+"
-"E-"
-"0x"
-"-0x"
-"p"
-"a"
-"b"
-"c"
-"d"
-"e"
-"f"
-"nan"
-"inf"
-"-inf"
-"infinity"
-"-infinity"
diff --git a/tests/generate_code.bat b/tests/generate_code.bat
deleted file mode 100644
index 1fc96a2..0000000
--- a/tests/generate_code.bat
+++ /dev/null
@@ -1,95 +0,0 @@
-:: Copyright 2015 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.
-
-@SETLOCAL
-
-set buildtype=Release
-if "%1"=="-b" set buildtype=%2
-
-set commandline=%*
-
-
-if NOT "%commandline%"=="%commandline:--cpp-std c++0x=%" (
- set TEST_CPP_FLAGS=--cpp-std c++0x
-) else (
- @rem --cpp-std is defined by flatc default settings.
- set TEST_CPP_FLAGS=
-)
-
-set TEST_CPP_FLAGS=--gen-compare --cpp-ptr-type flatbuffers::unique_ptr %TEST_CPP_FLAGS%
-set TEST_CS_FLAGS=--cs-gen-json-serializer
-set TEST_JS_TS_FLAGS=--gen-name-strings
-set TEST_RUST_FLAGS=--gen-name-strings
-set TEST_BASE_FLAGS=--reflect-names --gen-mutable --gen-object-api
-set TEST_NOINCL_FLAGS=%TEST_BASE_FLAGS% --no-includes --no-fb-import
-
-..\%buildtype%\flatc.exe --binary --cpp --java --kotlin --csharp --dart --go --lobster --lua --js --ts --php --grpc ^
-%TEST_NOINCL_FLAGS% %TEST_CPP_FLAGS% %TEST_CS_FLAGS% -I include_test monster_test.fbs monsterdata_test.json || goto FAIL
-..\%buildtype%\flatc.exe --rust %TEST_NOINCL_FLAGS% %TEST_RUST_FLAGS% -I include_test monster_test.fbs monsterdata_test.json || goto FAIL
-
-..\%buildtype%\flatc.exe --python %TEST_BASE_FLAGS% --no-fb-import -I include_test monster_test.fbs monsterdata_test.json || goto FAIL
-
-..\%buildtype%\flatc.exe --binary --cpp --java --csharp --dart --go --lobster --lua --js --ts --php --python --rust ^
-%TEST_NOINCL_FLAGS% %TEST_CPP_FLAGS% %TEST_CS_FLAGS% %TEST_JS_TS_FLAGS% -o namespace_test namespace_test/namespace_test1.fbs namespace_test/namespace_test2.fbs || goto FAIL
-
-..\%buildtype%\flatc.exe --cpp --java --csharp --js --ts --php %TEST_BASE_FLAGS% %TEST_CPP_FLAGS% %TEST_CS_FLAGS% %TEST_JS_TS_FLAGS% -o union_vector ./union_vector/union_vector.fbs || goto FAIL
-..\%buildtype%\flatc.exe --rust -I include_test -o include_test include_test/include_test1.fbs || goto FAIL
-..\%buildtype%\flatc.exe --rust -I include_test -o include_test/sub include_test/sub/include_test2.fbs || goto FAIL
-..\%buildtype%\flatc.exe -b --schema --bfbs-comments --bfbs-builtins -I include_test monster_test.fbs || goto FAIL
-..\%buildtype%\flatc.exe --cpp --bfbs-comments --bfbs-builtins --bfbs-gen-embed %TEST_NOINCL_FLAGS% %TEST_CPP_FLAGS% -I include_test monster_test.fbs || goto FAIL
-..\%buildtype%\flatc.exe -b --schema --bfbs-comments --bfbs-builtins -I include_test arrays_test.fbs || goto FAIL
-..\%buildtype%\flatc.exe --jsonschema --schema -I include_test monster_test.fbs || goto FAIL
-..\%buildtype%\flatc.exe --cpp --java --csharp --jsonschema %TEST_NOINCL_FLAGS% %TEST_CPP_FLAGS% %TEST_CS_FLAGS% --scoped-enums arrays_test.fbs || goto FAIL
-..\%buildtype%\flatc.exe --python %TEST_BASE_FLAGS% arrays_test.fbs || goto FAIL
-..\%buildtype%\flatc.exe --cpp %TEST_BASE_FLAGS% --cpp-ptr-type flatbuffers::unique_ptr native_type_test.fbs || goto FAIL
-
-@rem Generate the optional scalar code for tests.
-..\%buildtype%\flatc.exe --csharp --java --kotlin --rust --lobster --ts --js optional_scalars.fbs || goto FAIL
-..\%buildtype%\flatc.exe %TEST_NOINCL_FLAGS% %TEST_CPP_FLAGS% --cpp optional_scalars.fbs || goto FAIL
-
-@rem Generate the schema evolution tests
-..\%buildtype%\flatc.exe --cpp --scoped-enums %TEST_CPP_FLAGS% -o evolution_test ./evolution_test/evolution_v1.fbs ./evolution_test/evolution_v2.fbs || goto FAIL
-
-if NOT "%MONSTER_EXTRA%"=="skip" (
- @echo Generate MosterExtra
- ..\%buildtype%\flatc.exe --cpp --java --csharp %TEST_NOINCL_FLAGS% %TEST_CPP_FLAGS% %TEST_CS_FLAGS% monster_extra.fbs monsterdata_extra.json || goto FAIL
- ..\%buildtype%\flatc.exe --python %TEST_BASE_FLAGS% monster_extra.fbs monsterdata_extra.json || goto FAIL
-) else (
- @echo monster_extra.fbs skipped (the strtod function from MSVC2013 or older doesn't support NaN/Inf arguments)
-)
-
-set TEST_CPP17_FLAGS=--cpp --cpp-std c++17 -o ./cpp17/generated_cpp17 %TEST_NOINCL_FLAGS%
-if NOT "%MONSTER_EXTRA%"=="skip" (
- @rem Flag c++17 requires Clang6, GCC7, MSVC2017 (_MSC_VER >= 1914) or higher.
- ..\%buildtype%\flatc.exe %TEST_CPP17_FLAGS% -I include_test monster_test.fbs || goto FAIL
- ..\%buildtype%\flatc.exe %TEST_CPP17_FLAGS% optional_scalars.fbs || goto FAIL
- @rem..\%buildtype%\flatc.exe %TEST_CPP17_FLAGS% arrays_test.fbs || goto FAIL
- @rem..\%buildtype%\flatc.exe %TEST_CPP17_FLAGS% native_type_test.fbs || goto FAIL
- @rem..\%buildtype%\flatc.exe %TEST_CPP17_FLAGS% monster_extra.fbs || goto FAIL
- @rem..\%buildtype%\flatc.exe %TEST_CPP17_FLAGS% ./union_vector/union_vector.fbs || goto FAIL
-)
-
-cd ../samples
-..\%buildtype%\flatc.exe --cpp --lobster %TEST_BASE_FLAGS% %TEST_CPP_FLAGS% monster.fbs || goto FAIL
-..\%buildtype%\flatc.exe -b --schema --bfbs-comments --bfbs-builtins monster.fbs || goto FAIL
-cd ../reflection
-call generate_code.bat %1 %2 || goto FAIL
-
-set EXITCODE=0
-goto SUCCESS
-:FAIL
-set EXITCODE=1
-:SUCCESS
-cd ../tests
-EXIT /B %EXITCODE%
diff --git a/tests/generate_code.sh b/tests/generate_code.sh
deleted file mode 100755
index 89d9429..0000000
--- a/tests/generate_code.sh
+++ /dev/null
@@ -1,94 +0,0 @@
-#!/bin/bash
-#
-# Copyright 2015 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.
-set -e
-
-commandline="'$*'"
-
-if [[ $commandline == *"--cpp-std c++0x"* ]]; then
- TEST_CPP_FLAGS="--cpp-std c++0x"
-else
- # --cpp-std is defined by flatc default settings.
- TEST_CPP_FLAGS=
-fi
-
-TEST_CPP_FLAGS="--gen-compare --cpp-ptr-type flatbuffers::unique_ptr $TEST_CPP_FLAGS"
-TEST_CS_FLAGS="--cs-gen-json-serializer"
-TEST_JS_TS_FLAGS="--gen-name-strings"
-TEST_BASE_FLAGS="--reflect-names --gen-mutable --gen-object-api"
-TEST_RUST_FLAGS="$TEST_BASE_FLAGS --gen-name-strings"
-TEST_NOINCL_FLAGS="$TEST_BASE_FLAGS --no-includes --no-fb-import"
-
-../flatc --binary --cpp --java --kotlin --csharp --dart --go --lobster --lua --js --ts --php --grpc \
-$TEST_NOINCL_FLAGS $TEST_CPP_FLAGS $TEST_CS_FLAGS -I include_test monster_test.fbs monsterdata_test.json
-../flatc --rust $TEST_RUST_FLAGS -I include_test monster_test.fbs monsterdata_test.json
-
-../flatc --python $TEST_BASE_FLAGS -I include_test monster_test.fbs monsterdata_test.json
-
-../flatc --cpp --java --kotlin --csharp --dart --go --binary --lobster --lua --js --ts --php --python --rust \
-$TEST_NOINCL_FLAGS $TEST_CPP_FLAGS $TEST_CS_FLAGS $TEST_JS_TS_FLAGS -o namespace_test namespace_test/namespace_test1.fbs namespace_test/namespace_test2.fbs
-
-../flatc --cpp --java --kotlin --csharp --js --ts --php $TEST_BASE_FLAGS $TEST_CPP_FLAGS $TEST_CS_FLAGS $TEST_JS_TS_FLAGS -o union_vector ./union_vector/union_vector.fbs
-../flatc --rust -I include_test -o include_test include_test/include_test1.fbs
-../flatc --rust -I include_test -o include_test/sub include_test/sub/include_test2.fbs
-../flatc -b --schema --bfbs-comments --bfbs-builtins -I include_test monster_test.fbs
-../flatc --cpp --bfbs-comments --bfbs-builtins --bfbs-gen-embed $TEST_NOINCL_FLAGS $TEST_CPP_FLAGS -I include_test monster_test.fbs
-../flatc -b --schema --bfbs-comments --bfbs-builtins -I include_test arrays_test.fbs
-../flatc --jsonschema --schema -I include_test monster_test.fbs
-../flatc --cpp --java --kotlin --csharp --python $TEST_NOINCL_FLAGS $TEST_CPP_FLAGS $TEST_CS_FLAGS monster_extra.fbs monsterdata_extra.json
-../flatc --cpp --java --csharp --jsonschema $TEST_NOINCL_FLAGS $TEST_CPP_FLAGS $TEST_CS_FLAGS --scoped-enums arrays_test.fbs
-../flatc --python $TEST_BASE_FLAGS arrays_test.fbs
-../flatc --dart monster_extra.fbs
-
-# Generate optional scalar code for tests.
-../flatc --csharp --java --kotlin --rust --lobster --ts --js optional_scalars.fbs
-../flatc $TEST_NOINCL_FLAGS $TEST_CPP_FLAGS --cpp optional_scalars.fbs
-
-# Generate the schema evolution tests
-../flatc --cpp --scoped-enums $TEST_CPP_FLAGS -o evolution_test ./evolution_test/evolution_v*.fbs
-
-working_dir=`pwd`
-cd FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests
-$working_dir/../flatc --swift --grpc $TEST_NOINCL_FLAGS $TEST_CPP_FLAGS $TEST_CS_FLAGS -I ../../../include_test ../../../monster_test.fbs
-$working_dir/../flatc --swift $TEST_BASE_FLAGS $TEST_CPP_FLAGS $TEST_CS_FLAGS ../../../union_vector/union_vector.fbs
-$working_dir/../flatc --swift ../../../optional_scalars.fbs
-cd $working_dir
-
-cd FlatBuffers.GRPC.Swift/Sources/Model
-$working_dir/../flatc --swift --grpc greeter.fbs
-cd $working_dir
-
-# Tests if the --filename-suffix and --filename-ext works and produces the same
-# outputs.
-../flatc --cpp --filename-suffix _suffix --filename-ext hpp $TEST_NOINCL_FLAGS $TEST_CPP_FLAGS -I include_test monster_test.fbs
-if [ -f "monster_test_suffix.hpp" ]; then
- if ! cmp -s "monster_test_suffix.hpp" "monster_test_generated.h"; then
- echo "[Error] Filename suffix option did not produce identical results"
- fi
- rm "monster_test_suffix.hpp"
-else
- echo "[Error] Filename suffix option did not produce a file"
-fi
-
-# Flag c++17 requires Clang6, GCC7, MSVC2017 (_MSC_VER >= 1914) or higher.
-TEST_CPP17_FLAGS="--cpp --cpp-std c++17 -o ./cpp17/generated_cpp17 $TEST_NOINCL_FLAGS"
-../flatc $TEST_CPP17_FLAGS -I include_test monster_test.fbs
-../flatc $TEST_CPP17_FLAGS optional_scalars.fbs
-
-cd ../samples
-../flatc --cpp --rust --lobster $TEST_BASE_FLAGS $TEST_CPP_FLAGS monster.fbs
-../flatc -b --schema --bfbs-comments --bfbs-builtins monster.fbs
-cd ../reflection
-./generate_code.sh --cpp-std c++0x
diff --git a/tests/go_test.go b/tests/go_test.go
index 9e64cca..11b3f0a 100644
--- a/tests/go_test.go
+++ b/tests/go_test.go
@@ -17,8 +17,9 @@
package main
import (
- mygame "MyGame" // refers to generated code
- example "MyGame/Example" // refers to generated code
+ mygame "MyGame" // refers to generated code
+ example "MyGame/Example" // refers to generated code
+ optional_scalars "optional_scalars" // refers to generated code
"bytes"
"flag"
@@ -50,12 +51,6 @@
flag.IntVar(&fuzzFields, "fuzz_fields", 4, "fields per fuzzer object")
flag.IntVar(&fuzzObjects, "fuzz_objects", 10000,
"number of fuzzer objects (higher is slower and more thorough")
- flag.Parse()
-
- if cppData == "" {
- fmt.Fprintf(os.Stderr, "cpp_data argument is required\n")
- os.Exit(1)
- }
}
// Store specific byte patterns in these variables for the fuzzer. These
@@ -65,6 +60,15 @@
overflowingInt64Val = flatbuffers.GetInt64([]byte{0x84, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44})
)
+func TestMain(m *testing.M) {
+ flag.Parse()
+ if cppData == "" {
+ fmt.Fprintf(os.Stderr, "cpp_data argument is required\n")
+ os.Exit(1)
+ }
+ os.Exit(m.Run())
+}
+
// TestAll runs all checks, failing if any errors occur.
func TestAll(t *testing.T) {
// Verify that the Go FlatBuffers runtime library generates the
@@ -130,6 +134,9 @@
// Check size-prefixed flatbuffers
CheckSizePrefixedBuffer(t.Fatalf)
+ // Check that optional scalars work
+ CheckOptionalScalars(t.Fatalf)
+
// If the filename of the FlatBuffers file generated by the Java test
// is given, check that Go code can read it, and that Go code
// generates an identical buffer when used to create the example data:
@@ -1858,6 +1865,296 @@
}
}
+// CheckOptionalScalars verifies against the ScalarStuff schema.
+func CheckOptionalScalars(fail func(string, ...interface{})) {
+ type testCase struct {
+ what string
+ result, expect interface{}
+ }
+
+ makeDefaultTestCases := func(s *optional_scalars.ScalarStuff) []testCase {
+ return []testCase{
+ {"justI8", s.JustI8(), int8(0)},
+ {"maybeI8", s.MaybeI8(), (*int8)(nil)},
+ {"defaultI8", s.DefaultI8(), int8(42)},
+ {"justU8", s.JustU8(), byte(0)},
+ {"maybeU8", s.MaybeU8(), (*byte)(nil)},
+ {"defaultU8", s.DefaultU8(), byte(42)},
+ {"justI16", s.JustI16(), int16(0)},
+ {"maybeI16", s.MaybeI16(), (*int16)(nil)},
+ {"defaultI16", s.DefaultI16(), int16(42)},
+ {"justU16", s.JustU16(), uint16(0)},
+ {"maybeU16", s.MaybeU16(), (*uint16)(nil)},
+ {"defaultU16", s.DefaultU16(), uint16(42)},
+ {"justI32", s.JustI32(), int32(0)},
+ {"maybeI32", s.MaybeI32(), (*int32)(nil)},
+ {"defaultI32", s.DefaultI32(), int32(42)},
+ {"justU32", s.JustU32(), uint32(0)},
+ {"maybeU32", s.MaybeU32(), (*uint32)(nil)},
+ {"defaultU32", s.DefaultU32(), uint32(42)},
+ {"justI64", s.JustI64(), int64(0)},
+ {"maybeI64", s.MaybeI64(), (*int64)(nil)},
+ {"defaultI64", s.DefaultI64(), int64(42)},
+ {"justU64", s.JustU64(), uint64(0)},
+ {"maybeU64", s.MaybeU64(), (*uint64)(nil)},
+ {"defaultU64", s.DefaultU64(), uint64(42)},
+ {"justF32", s.JustF32(), float32(0)},
+ {"maybeF32", s.MaybeF32(), (*float32)(nil)},
+ {"defaultF32", s.DefaultF32(), float32(42)},
+ {"justF64", s.JustF64(), float64(0)},
+ {"maybeF64", s.MaybeF64(), (*float64)(nil)},
+ {"defaultF64", s.DefaultF64(), float64(42)},
+ {"justBool", s.JustBool(), false},
+ {"maybeBool", s.MaybeBool(), (*bool)(nil)},
+ {"defaultBool", s.DefaultBool(), true},
+ {"justEnum", s.JustEnum(), optional_scalars.OptionalByte(0)},
+ {"maybeEnum", s.MaybeEnum(), (*optional_scalars.OptionalByte)(nil)},
+ {"defaultEnum", s.DefaultEnum(), optional_scalars.OptionalByteOne},
+ }
+ }
+
+ makeAssignedTestCases := func(s *optional_scalars.ScalarStuff) []testCase {
+ return []testCase{
+ {"justI8", s.JustI8(), int8(5)},
+ {"maybeI8", s.MaybeI8(), int8(5)},
+ {"defaultI8", s.DefaultI8(), int8(5)},
+ {"justU8", s.JustU8(), byte(6)},
+ {"maybeU8", s.MaybeU8(), byte(6)},
+ {"defaultU8", s.DefaultU8(), byte(6)},
+ {"justI16", s.JustI16(), int16(7)},
+ {"maybeI16", s.MaybeI16(), int16(7)},
+ {"defaultI16", s.DefaultI16(), int16(7)},
+ {"justU16", s.JustU16(), uint16(8)},
+ {"maybeU16", s.MaybeU16(), uint16(8)},
+ {"defaultU16", s.DefaultU16(), uint16(8)},
+ {"justI32", s.JustI32(), int32(9)},
+ {"maybeI32", s.MaybeI32(), int32(9)},
+ {"defaultI32", s.DefaultI32(), int32(9)},
+ {"justU32", s.JustU32(), uint32(10)},
+ {"maybeU32", s.MaybeU32(), uint32(10)},
+ {"defaultU32", s.DefaultU32(), uint32(10)},
+ {"justI64", s.JustI64(), int64(11)},
+ {"maybeI64", s.MaybeI64(), int64(11)},
+ {"defaultI64", s.DefaultI64(), int64(11)},
+ {"justU64", s.JustU64(), uint64(12)},
+ {"maybeU64", s.MaybeU64(), uint64(12)},
+ {"defaultU64", s.DefaultU64(), uint64(12)},
+ {"justF32", s.JustF32(), float32(13)},
+ {"maybeF32", s.MaybeF32(), float32(13)},
+ {"defaultF32", s.DefaultF32(), float32(13)},
+ {"justF64", s.JustF64(), float64(14)},
+ {"maybeF64", s.MaybeF64(), float64(14)},
+ {"defaultF64", s.DefaultF64(), float64(14)},
+ {"justBool", s.JustBool(), true},
+ {"maybeBool", s.MaybeBool(), true},
+ {"defaultBool", s.DefaultBool(), false},
+ {"justEnum", s.JustEnum(), optional_scalars.OptionalByteTwo},
+ {"maybeEnum", s.MaybeEnum(), optional_scalars.OptionalByteTwo},
+ {"defaultEnum", s.DefaultEnum(), optional_scalars.OptionalByteTwo},
+ }
+ }
+
+ resolvePointer := func(v interface{}) interface{} {
+ switch v := v.(type) {
+ case *int8:
+ return *v
+ case *byte:
+ return *v
+ case *int16:
+ return *v
+ case *uint16:
+ return *v
+ case *int32:
+ return *v
+ case *uint32:
+ return *v
+ case *int64:
+ return *v
+ case *uint64:
+ return *v
+ case *float32:
+ return *v
+ case *float64:
+ return *v
+ case *bool:
+ return *v
+ case *optional_scalars.OptionalByte:
+ return *v
+ default:
+ return v
+ }
+ }
+
+ buildAssignedTable := func(b *flatbuffers.Builder) *optional_scalars.ScalarStuff {
+ optional_scalars.ScalarStuffStart(b)
+ optional_scalars.ScalarStuffAddJustI8(b, int8(5))
+ optional_scalars.ScalarStuffAddMaybeI8(b, int8(5))
+ optional_scalars.ScalarStuffAddDefaultI8(b, int8(5))
+ optional_scalars.ScalarStuffAddJustU8(b, byte(6))
+ optional_scalars.ScalarStuffAddMaybeU8(b, byte(6))
+ optional_scalars.ScalarStuffAddDefaultU8(b, byte(6))
+ optional_scalars.ScalarStuffAddJustI16(b, int16(7))
+ optional_scalars.ScalarStuffAddMaybeI16(b, int16(7))
+ optional_scalars.ScalarStuffAddDefaultI16(b, int16(7))
+ optional_scalars.ScalarStuffAddJustU16(b, uint16(8))
+ optional_scalars.ScalarStuffAddMaybeU16(b, uint16(8))
+ optional_scalars.ScalarStuffAddDefaultU16(b, uint16(8))
+ optional_scalars.ScalarStuffAddJustI32(b, int32(9))
+ optional_scalars.ScalarStuffAddMaybeI32(b, int32(9))
+ optional_scalars.ScalarStuffAddDefaultI32(b, int32(9))
+ optional_scalars.ScalarStuffAddJustU32(b, uint32(10))
+ optional_scalars.ScalarStuffAddMaybeU32(b, uint32(10))
+ optional_scalars.ScalarStuffAddDefaultU32(b, uint32(10))
+ optional_scalars.ScalarStuffAddJustI64(b, int64(11))
+ optional_scalars.ScalarStuffAddMaybeI64(b, int64(11))
+ optional_scalars.ScalarStuffAddDefaultI64(b, int64(11))
+ optional_scalars.ScalarStuffAddJustU64(b, uint64(12))
+ optional_scalars.ScalarStuffAddMaybeU64(b, uint64(12))
+ optional_scalars.ScalarStuffAddDefaultU64(b, uint64(12))
+ optional_scalars.ScalarStuffAddJustF32(b, float32(13))
+ optional_scalars.ScalarStuffAddMaybeF32(b, float32(13))
+ optional_scalars.ScalarStuffAddDefaultF32(b, float32(13))
+ optional_scalars.ScalarStuffAddJustF64(b, float64(14))
+ optional_scalars.ScalarStuffAddMaybeF64(b, float64(14))
+ optional_scalars.ScalarStuffAddDefaultF64(b, float64(14))
+ optional_scalars.ScalarStuffAddJustBool(b, true)
+ optional_scalars.ScalarStuffAddMaybeBool(b, true)
+ optional_scalars.ScalarStuffAddDefaultBool(b, false)
+ optional_scalars.ScalarStuffAddJustEnum(b, optional_scalars.OptionalByteTwo)
+ optional_scalars.ScalarStuffAddMaybeEnum(b, optional_scalars.OptionalByteTwo)
+ optional_scalars.ScalarStuffAddDefaultEnum(b, optional_scalars.OptionalByteTwo)
+ b.Finish(optional_scalars.ScalarStuffEnd(b))
+ return optional_scalars.GetRootAsScalarStuff(b.FinishedBytes(), 0)
+ }
+
+ // test default values
+
+ fbb := flatbuffers.NewBuilder(1)
+ optional_scalars.ScalarStuffStart(fbb)
+ fbb.Finish(optional_scalars.ScalarStuffEnd(fbb))
+ ss := optional_scalars.GetRootAsScalarStuff(fbb.FinishedBytes(), 0)
+ for _, tc := range makeDefaultTestCases(ss) {
+ if tc.result != tc.expect {
+ fail(FailString("Default ScalarStuff: "+tc.what, tc.expect, tc.result))
+ }
+ }
+
+ // test assigned values
+ fbb.Reset()
+ ss = buildAssignedTable(fbb)
+ for _, tc := range makeAssignedTestCases(ss) {
+ if resolvePointer(tc.result) != tc.expect {
+ fail(FailString("Assigned ScalarStuff: "+tc.what, tc.expect, tc.result))
+ }
+ }
+
+ // test native object pack
+ fbb.Reset()
+ i8 := int8(5)
+ u8 := byte(6)
+ i16 := int16(7)
+ u16 := uint16(8)
+ i32 := int32(9)
+ u32 := uint32(10)
+ i64 := int64(11)
+ u64 := uint64(12)
+ f32 := float32(13)
+ f64 := float64(14)
+ b := true
+ enum := optional_scalars.OptionalByteTwo
+ obj := optional_scalars.ScalarStuffT{
+ JustI8: 5,
+ MaybeI8: &i8,
+ DefaultI8: 5,
+ JustU8: 6,
+ MaybeU8: &u8,
+ DefaultU8: 6,
+ JustI16: 7,
+ MaybeI16: &i16,
+ DefaultI16: 7,
+ JustU16: 8,
+ MaybeU16: &u16,
+ DefaultU16: 8,
+ JustI32: 9,
+ MaybeI32: &i32,
+ DefaultI32: 9,
+ JustU32: 10,
+ MaybeU32: &u32,
+ DefaultU32: 10,
+ JustI64: 11,
+ MaybeI64: &i64,
+ DefaultI64: 11,
+ JustU64: 12,
+ MaybeU64: &u64,
+ DefaultU64: 12,
+ JustF32: 13,
+ MaybeF32: &f32,
+ DefaultF32: 13,
+ JustF64: 14,
+ MaybeF64: &f64,
+ DefaultF64: 14,
+ JustBool: true,
+ MaybeBool: &b,
+ DefaultBool: false,
+ JustEnum: optional_scalars.OptionalByteTwo,
+ MaybeEnum: &enum,
+ DefaultEnum: optional_scalars.OptionalByteTwo,
+ }
+ fbb.Finish(obj.Pack(fbb))
+ ss = optional_scalars.GetRootAsScalarStuff(fbb.FinishedBytes(), 0)
+ for _, tc := range makeAssignedTestCases(ss) {
+ if resolvePointer(tc.result) != tc.expect {
+ fail(FailString("Native Object ScalarStuff: "+tc.what, tc.expect, tc.result))
+ }
+ }
+
+ // test native object unpack
+ fbb.Reset()
+ ss = buildAssignedTable(fbb)
+ ss.UnPackTo(&obj)
+ expectEq := func(what string, a, b interface{}) {
+ if resolvePointer(a) != b {
+ fail(FailString("Native Object Unpack ScalarStuff: "+what, b, a))
+ }
+ }
+ expectEq("justI8", obj.JustI8, int8(5))
+ expectEq("maybeI8", obj.MaybeI8, int8(5))
+ expectEq("defaultI8", obj.DefaultI8, int8(5))
+ expectEq("justU8", obj.JustU8, byte(6))
+ expectEq("maybeU8", obj.MaybeU8, byte(6))
+ expectEq("defaultU8", obj.DefaultU8, byte(6))
+ expectEq("justI16", obj.JustI16, int16(7))
+ expectEq("maybeI16", obj.MaybeI16, int16(7))
+ expectEq("defaultI16", obj.DefaultI16, int16(7))
+ expectEq("justU16", obj.JustU16, uint16(8))
+ expectEq("maybeU16", obj.MaybeU16, uint16(8))
+ expectEq("defaultU16", obj.DefaultU16, uint16(8))
+ expectEq("justI32", obj.JustI32, int32(9))
+ expectEq("maybeI32", obj.MaybeI32, int32(9))
+ expectEq("defaultI32", obj.DefaultI32, int32(9))
+ expectEq("justU32", obj.JustU32, uint32(10))
+ expectEq("maybeU32", obj.MaybeU32, uint32(10))
+ expectEq("defaultU32", obj.DefaultU32, uint32(10))
+ expectEq("justI64", obj.JustI64, int64(11))
+ expectEq("maybeI64", obj.MaybeI64, int64(11))
+ expectEq("defaultI64", obj.DefaultI64, int64(11))
+ expectEq("justU64", obj.JustU64, uint64(12))
+ expectEq("maybeU64", obj.MaybeU64, uint64(12))
+ expectEq("defaultU64", obj.DefaultU64, uint64(12))
+ expectEq("justF32", obj.JustF32, float32(13))
+ expectEq("maybeF32", obj.MaybeF32, float32(13))
+ expectEq("defaultF32", obj.DefaultF32, float32(13))
+ expectEq("justF64", obj.JustF64, float64(14))
+ expectEq("maybeF64", obj.MaybeF64, float64(14))
+ expectEq("defaultF64", obj.DefaultF64, float64(14))
+ expectEq("justBool", obj.JustBool, true)
+ expectEq("maybeBool", obj.MaybeBool, true)
+ expectEq("defaultBool", obj.DefaultBool, false)
+ expectEq("justEnum", obj.JustEnum, optional_scalars.OptionalByteTwo)
+ expectEq("maybeEnum", obj.MaybeEnum, optional_scalars.OptionalByteTwo)
+ expectEq("defaultEnum", obj.DefaultEnum, optional_scalars.OptionalByteTwo)
+}
+
// BenchmarkVtableDeduplication measures the speed of vtable deduplication
// by creating prePop vtables, then populating b.N objects with a
// different single vtable.
diff --git a/tests/include_build_test.cc b/tests/include_build_test.cc
new file mode 100644
index 0000000..a5282cc
--- /dev/null
+++ b/tests/include_build_test.cc
@@ -0,0 +1 @@
+#include "tests/includer_test_generated.h"
diff --git a/tests/include_test/include_test1_generated.rs b/tests/include_test/include_test1_generated.rs
deleted file mode 100644
index 3c7b9bd..0000000
--- a/tests/include_test/include_test1_generated.rs
+++ /dev/null
@@ -1,93 +0,0 @@
-// automatically generated by the FlatBuffers compiler, do not modify
-
-
-#![allow(unused_imports, dead_code)]
-
-use crate::include_test2_generated::*;
-use std::mem;
-use std::cmp::Ordering;
-
-extern crate flatbuffers;
-use self::flatbuffers::EndianScalar;
-
-pub enum TableAOffset {}
-#[derive(Copy, Clone, PartialEq)]
-
-pub struct TableA<'a> {
- pub _tab: flatbuffers::Table<'a>,
-}
-
-impl<'a> flatbuffers::Follow<'a> for TableA<'a> {
- type Inner = TableA<'a>;
- #[inline]
- fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
- Self { _tab: flatbuffers::Table { buf, loc } }
- }
-}
-
-impl<'a> TableA<'a> {
- #[inline]
- pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
- TableA {
- _tab: table,
- }
- }
- #[allow(unused_mut)]
- pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
- _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
- args: &'args TableAArgs<'args>) -> flatbuffers::WIPOffset<TableA<'bldr>> {
- let mut builder = TableABuilder::new(_fbb);
- if let Some(x) = args.b { builder.add_b(x); }
- builder.finish()
- }
-
- pub const VT_B: flatbuffers::VOffsetT = 4;
-
- #[inline]
- pub fn b(&self) -> Option<my_game::other_name_space::TableB<'a>> {
- self._tab.get::<flatbuffers::ForwardsUOffset<my_game::other_name_space::TableB<'a>>>(TableA::VT_B, None)
- }
-}
-
-pub struct TableAArgs<'a> {
- pub b: Option<flatbuffers::WIPOffset<my_game::other_name_space::TableB<'a>>>,
-}
-impl<'a> Default for TableAArgs<'a> {
- #[inline]
- fn default() -> Self {
- TableAArgs {
- b: None,
- }
- }
-}
-pub struct TableABuilder<'a: 'b, 'b> {
- fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
- start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
-}
-impl<'a: 'b, 'b> TableABuilder<'a, 'b> {
- #[inline]
- pub fn add_b(&mut self, b: flatbuffers::WIPOffset<my_game::other_name_space::TableB<'b >>) {
- self.fbb_.push_slot_always::<flatbuffers::WIPOffset<my_game::other_name_space::TableB>>(TableA::VT_B, b);
- }
- #[inline]
- pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> TableABuilder<'a, 'b> {
- let start = _fbb.start_table();
- TableABuilder {
- fbb_: _fbb,
- start_: start,
- }
- }
- #[inline]
- pub fn finish(self) -> flatbuffers::WIPOffset<TableA<'a>> {
- let o = self.fbb_.end_table(self.start_);
- flatbuffers::WIPOffset::new(o.value())
- }
-}
-
-impl std::fmt::Debug for TableA<'_> {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- let mut ds = f.debug_struct("TableA");
- ds.field("b", &self.b());
- ds.finish()
- }
-}
diff --git a/tests/include_test/sub/include_test2_generated.rs b/tests/include_test/sub/include_test2_generated.rs
deleted file mode 100644
index 892c652..0000000
--- a/tests/include_test/sub/include_test2_generated.rs
+++ /dev/null
@@ -1,245 +0,0 @@
-// automatically generated by the FlatBuffers compiler, do not modify
-
-
-#![allow(unused_imports, dead_code)]
-
-use crate::include_test1_generated::*;
-use std::mem;
-use std::cmp::Ordering;
-
-extern crate flatbuffers;
-use self::flatbuffers::EndianScalar;
-
-#[allow(unused_imports, dead_code)]
-pub mod my_game {
-
- use crate::include_test1_generated::*;
- use std::mem;
- use std::cmp::Ordering;
-
- extern crate flatbuffers;
- use self::flatbuffers::EndianScalar;
-#[allow(unused_imports, dead_code)]
-pub mod other_name_space {
-
- use crate::include_test1_generated::*;
- use std::mem;
- use std::cmp::Ordering;
-
- extern crate flatbuffers;
- use self::flatbuffers::EndianScalar;
-
-#[deprecated(since = "1.13", note = "Use associated constants instead. This will no longer be generated in 2021.")]
-pub const ENUM_MIN_FROM_INCLUDE: i64 = 0;
-#[deprecated(since = "1.13", note = "Use associated constants instead. This will no longer be generated in 2021.")]
-pub const ENUM_MAX_FROM_INCLUDE: i64 = 0;
-#[deprecated(since = "1.13", note = "Use associated constants instead. This will no longer be generated in 2021.")]
-#[allow(non_camel_case_types)]
-pub const ENUM_VALUES_FROM_INCLUDE: [FromInclude; 1] = [
- FromInclude::IncludeVal,
-];
-
-#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
-#[repr(transparent)]
-pub struct FromInclude(pub i64);
-#[allow(non_upper_case_globals)]
-impl FromInclude {
- pub const IncludeVal: Self = Self(0);
-
- pub const ENUM_MIN: i64 = 0;
- pub const ENUM_MAX: i64 = 0;
- pub const ENUM_VALUES: &'static [Self] = &[
- Self::IncludeVal,
- ];
- /// Returns the variant's name or "" if unknown.
- pub fn variant_name(self) -> Option<&'static str> {
- match self {
- Self::IncludeVal => Some("IncludeVal"),
- _ => None,
- }
- }
-}
-impl std::fmt::Debug for FromInclude {
- fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
- if let Some(name) = self.variant_name() {
- f.write_str(name)
- } else {
- f.write_fmt(format_args!("<UNKNOWN {:?}>", self.0))
- }
- }
-}
-impl<'a> flatbuffers::Follow<'a> for FromInclude {
- type Inner = Self;
- #[inline]
- fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
- Self(flatbuffers::read_scalar_at::<i64>(buf, loc))
- }
-}
-
-impl flatbuffers::Push for FromInclude {
- type Output = FromInclude;
- #[inline]
- fn push(&self, dst: &mut [u8], _rest: &[u8]) {
- flatbuffers::emplace_scalar::<i64>(dst, self.0);
- }
-}
-
-impl flatbuffers::EndianScalar for FromInclude {
- #[inline]
- fn to_little_endian(self) -> Self {
- Self(i64::to_le(self.0))
- }
- #[inline]
- fn from_little_endian(self) -> Self {
- Self(i64::from_le(self.0))
- }
-}
-
-// struct Unused, aligned to 4
-#[repr(C, align(4))]
-#[derive(Clone, Copy, PartialEq)]
-pub struct Unused {
- a_: i32,
-} // pub struct Unused
-impl std::fmt::Debug for Unused {
- fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
- f.debug_struct("Unused")
- .field("a", &self.a())
- .finish()
- }
-}
-
-impl flatbuffers::SafeSliceAccess for Unused {}
-impl<'a> flatbuffers::Follow<'a> for Unused {
- type Inner = &'a Unused;
- #[inline]
- fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
- <&'a Unused>::follow(buf, loc)
- }
-}
-impl<'a> flatbuffers::Follow<'a> for &'a Unused {
- type Inner = &'a Unused;
- #[inline]
- fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
- flatbuffers::follow_cast_ref::<Unused>(buf, loc)
- }
-}
-impl<'b> flatbuffers::Push for Unused {
- type Output = Unused;
- #[inline]
- fn push(&self, dst: &mut [u8], _rest: &[u8]) {
- let src = unsafe {
- ::std::slice::from_raw_parts(self as *const Unused as *const u8, Self::size())
- };
- dst.copy_from_slice(src);
- }
-}
-impl<'b> flatbuffers::Push for &'b Unused {
- type Output = Unused;
-
- #[inline]
- fn push(&self, dst: &mut [u8], _rest: &[u8]) {
- let src = unsafe {
- ::std::slice::from_raw_parts(*self as *const Unused as *const u8, Self::size())
- };
- dst.copy_from_slice(src);
- }
-}
-
-
-impl Unused {
- pub fn new(_a: i32) -> Self {
- Unused {
- a_: _a.to_little_endian(),
-
- }
- }
- pub fn a(&self) -> i32 {
- self.a_.from_little_endian()
- }
-}
-
-pub enum TableBOffset {}
-#[derive(Copy, Clone, PartialEq)]
-
-pub struct TableB<'a> {
- pub _tab: flatbuffers::Table<'a>,
-}
-
-impl<'a> flatbuffers::Follow<'a> for TableB<'a> {
- type Inner = TableB<'a>;
- #[inline]
- fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
- Self { _tab: flatbuffers::Table { buf, loc } }
- }
-}
-
-impl<'a> TableB<'a> {
- #[inline]
- pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
- TableB {
- _tab: table,
- }
- }
- #[allow(unused_mut)]
- pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
- _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
- args: &'args TableBArgs<'args>) -> flatbuffers::WIPOffset<TableB<'bldr>> {
- let mut builder = TableBBuilder::new(_fbb);
- if let Some(x) = args.a { builder.add_a(x); }
- builder.finish()
- }
-
- pub const VT_A: flatbuffers::VOffsetT = 4;
-
- #[inline]
- pub fn a(&self) -> Option<super::super::TableA<'a>> {
- self._tab.get::<flatbuffers::ForwardsUOffset<super::super::TableA<'a>>>(TableB::VT_A, None)
- }
-}
-
-pub struct TableBArgs<'a> {
- pub a: Option<flatbuffers::WIPOffset<super::super::TableA<'a>>>,
-}
-impl<'a> Default for TableBArgs<'a> {
- #[inline]
- fn default() -> Self {
- TableBArgs {
- a: None,
- }
- }
-}
-pub struct TableBBuilder<'a: 'b, 'b> {
- fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
- start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
-}
-impl<'a: 'b, 'b> TableBBuilder<'a, 'b> {
- #[inline]
- pub fn add_a(&mut self, a: flatbuffers::WIPOffset<super::super::TableA<'b >>) {
- self.fbb_.push_slot_always::<flatbuffers::WIPOffset<super::super::TableA>>(TableB::VT_A, a);
- }
- #[inline]
- pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> TableBBuilder<'a, 'b> {
- let start = _fbb.start_table();
- TableBBuilder {
- fbb_: _fbb,
- start_: start,
- }
- }
- #[inline]
- pub fn finish(self) -> flatbuffers::WIPOffset<TableB<'a>> {
- let o = self.fbb_.end_table(self.start_);
- flatbuffers::WIPOffset::new(o.value())
- }
-}
-
-impl std::fmt::Debug for TableB<'_> {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- let mut ds = f.debug_struct("TableB");
- ds.field("a", &self.a());
- ds.finish()
- }
-}
-} // pub mod OtherNameSpace
-} // pub mod MyGame
-
diff --git a/tests/include_test1/mod.rs b/tests/include_test1/mod.rs
new file mode 100644
index 0000000..3a6afa9
--- /dev/null
+++ b/tests/include_test1/mod.rs
@@ -0,0 +1,15 @@
+// Automatically generated by the Flatbuffers compiler. Do not modify.
+pub mod my_game {
+ use super::*;
+ pub mod other_name_space {
+ use super::*;
+ mod from_include_generated;
+ pub use self::from_include_generated::*;
+ mod unused_generated;
+ pub use self::unused_generated::*;
+ mod table_b_generated;
+ pub use self::table_b_generated::*;
+ } // other_name_space
+} // my_game
+mod table_a_generated;
+pub use self::table_a_generated::*;
diff --git a/tests/include_test1/my_game/other_name_space/from_include_generated.rs b/tests/include_test1/my_game/other_name_space/from_include_generated.rs
new file mode 100644
index 0000000..048bafd
--- /dev/null
+++ b/tests/include_test1/my_game/other_name_space/from_include_generated.rs
@@ -0,0 +1,89 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+pub const ENUM_MIN_FROM_INCLUDE: i64 = 0;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+pub const ENUM_MAX_FROM_INCLUDE: i64 = 0;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+#[allow(non_camel_case_types)]
+pub const ENUM_VALUES_FROM_INCLUDE: [FromInclude; 1] = [
+ FromInclude::IncludeVal,
+];
+
+#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
+#[repr(transparent)]
+pub struct FromInclude(pub i64);
+#[allow(non_upper_case_globals)]
+impl FromInclude {
+ pub const IncludeVal: Self = Self(0);
+
+ pub const ENUM_MIN: i64 = 0;
+ pub const ENUM_MAX: i64 = 0;
+ pub const ENUM_VALUES: &'static [Self] = &[
+ Self::IncludeVal,
+ ];
+ /// Returns the variant's name or "" if unknown.
+ pub fn variant_name(self) -> Option<&'static str> {
+ match self {
+ Self::IncludeVal => Some("IncludeVal"),
+ _ => None,
+ }
+ }
+}
+impl std::fmt::Debug for FromInclude {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ if let Some(name) = self.variant_name() {
+ f.write_str(name)
+ } else {
+ f.write_fmt(format_args!("<UNKNOWN {:?}>", self.0))
+ }
+ }
+}
+impl<'a> flatbuffers::Follow<'a> for FromInclude {
+ type Inner = Self;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ let b = unsafe {
+ flatbuffers::read_scalar_at::<i64>(buf, loc)
+ };
+ Self(b)
+ }
+}
+
+impl flatbuffers::Push for FromInclude {
+ type Output = FromInclude;
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ unsafe { flatbuffers::emplace_scalar::<i64>(dst, self.0); }
+ }
+}
+
+impl flatbuffers::EndianScalar for FromInclude {
+ #[inline]
+ fn to_little_endian(self) -> Self {
+ let b = i64::to_le(self.0);
+ Self(b)
+ }
+ #[inline]
+ #[allow(clippy::wrong_self_convention)]
+ fn from_little_endian(self) -> Self {
+ let b = i64::from_le(self.0);
+ Self(b)
+ }
+}
+
+impl<'a> flatbuffers::Verifiable for FromInclude {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ i64::run_verifier(v, pos)
+ }
+}
+
+impl flatbuffers::SimpleToVerifyInSlice for FromInclude {}
diff --git a/tests/include_test1/my_game/other_name_space/table_b_generated.rs b/tests/include_test1/my_game/other_name_space/table_b_generated.rs
new file mode 100644
index 0000000..46a99cb
--- /dev/null
+++ b/tests/include_test1/my_game/other_name_space/table_b_generated.rs
@@ -0,0 +1,137 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+pub enum TableBOffset {}
+#[derive(Copy, Clone, PartialEq)]
+
+pub struct TableB<'a> {
+ pub _tab: flatbuffers::Table<'a>,
+}
+
+impl<'a> flatbuffers::Follow<'a> for TableB<'a> {
+ type Inner = TableB<'a>;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ Self { _tab: flatbuffers::Table { buf, loc } }
+ }
+}
+
+impl<'a> TableB<'a> {
+ pub const VT_A: flatbuffers::VOffsetT = 4;
+
+ pub const fn get_fully_qualified_name() -> &'static str {
+ "MyGame.OtherNameSpace.TableB"
+ }
+
+ #[inline]
+ pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
+ TableB { _tab: table }
+ }
+ #[allow(unused_mut)]
+ pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
+ _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
+ args: &'args TableBArgs<'args>
+ ) -> flatbuffers::WIPOffset<TableB<'bldr>> {
+ let mut builder = TableBBuilder::new(_fbb);
+ if let Some(x) = args.a { builder.add_a(x); }
+ builder.finish()
+ }
+
+ pub fn unpack(&self) -> TableBT {
+ let a = self.a().map(|x| {
+ Box::new(x.unpack())
+ });
+ TableBT {
+ a,
+ }
+ }
+
+ #[inline]
+ pub fn a(&self) -> Option<super::super::TableA<'a>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<super::super::TableA>>(TableB::VT_A, None)
+ }
+}
+
+impl flatbuffers::Verifiable for TableB<'_> {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ v.visit_table(pos)?
+ .visit_field::<flatbuffers::ForwardsUOffset<super::super::TableA>>("a", Self::VT_A, false)?
+ .finish();
+ Ok(())
+ }
+}
+pub struct TableBArgs<'a> {
+ pub a: Option<flatbuffers::WIPOffset<super::super::TableA<'a>>>,
+}
+impl<'a> Default for TableBArgs<'a> {
+ #[inline]
+ fn default() -> Self {
+ TableBArgs {
+ a: None,
+ }
+ }
+}
+
+pub struct TableBBuilder<'a: 'b, 'b> {
+ fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
+ start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
+}
+impl<'a: 'b, 'b> TableBBuilder<'a, 'b> {
+ #[inline]
+ pub fn add_a(&mut self, a: flatbuffers::WIPOffset<super::super::TableA<'b >>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<super::super::TableA>>(TableB::VT_A, a);
+ }
+ #[inline]
+ pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> TableBBuilder<'a, 'b> {
+ let start = _fbb.start_table();
+ TableBBuilder {
+ fbb_: _fbb,
+ start_: start,
+ }
+ }
+ #[inline]
+ pub fn finish(self) -> flatbuffers::WIPOffset<TableB<'a>> {
+ let o = self.fbb_.end_table(self.start_);
+ flatbuffers::WIPOffset::new(o.value())
+ }
+}
+
+impl std::fmt::Debug for TableB<'_> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let mut ds = f.debug_struct("TableB");
+ ds.field("a", &self.a());
+ ds.finish()
+ }
+}
+#[non_exhaustive]
+#[derive(Debug, Clone, PartialEq)]
+pub struct TableBT {
+ pub a: Option<Box<super::super::TableAT>>,
+}
+impl Default for TableBT {
+ fn default() -> Self {
+ Self {
+ a: None,
+ }
+ }
+}
+impl TableBT {
+ pub fn pack<'b>(
+ &self,
+ _fbb: &mut flatbuffers::FlatBufferBuilder<'b>
+ ) -> flatbuffers::WIPOffset<TableB<'b>> {
+ let a = self.a.as_ref().map(|x|{
+ x.pack(_fbb)
+ });
+ TableB::create(_fbb, &TableBArgs{
+ a,
+ })
+ }
+}
diff --git a/tests/include_test1/my_game/other_name_space/unused_generated.rs b/tests/include_test1/my_game/other_name_space/unused_generated.rs
new file mode 100644
index 0000000..1dc5913
--- /dev/null
+++ b/tests/include_test1/my_game/other_name_space/unused_generated.rs
@@ -0,0 +1,127 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+// struct Unused, aligned to 4
+#[repr(transparent)]
+#[derive(Clone, Copy, PartialEq)]
+pub struct Unused(pub [u8; 4]);
+impl Default for Unused {
+ fn default() -> Self {
+ Self([0; 4])
+ }
+}
+impl std::fmt::Debug for Unused {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ f.debug_struct("Unused")
+ .field("a", &self.a())
+ .finish()
+ }
+}
+
+impl flatbuffers::SimpleToVerifyInSlice for Unused {}
+impl flatbuffers::SafeSliceAccess for Unused {}
+impl<'a> flatbuffers::Follow<'a> for Unused {
+ type Inner = &'a Unused;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ <&'a Unused>::follow(buf, loc)
+ }
+}
+impl<'a> flatbuffers::Follow<'a> for &'a Unused {
+ type Inner = &'a Unused;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ flatbuffers::follow_cast_ref::<Unused>(buf, loc)
+ }
+}
+impl<'b> flatbuffers::Push for Unused {
+ type Output = Unused;
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ let src = unsafe {
+ ::std::slice::from_raw_parts(self as *const Unused as *const u8, Self::size())
+ };
+ dst.copy_from_slice(src);
+ }
+}
+impl<'b> flatbuffers::Push for &'b Unused {
+ type Output = Unused;
+
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ let src = unsafe {
+ ::std::slice::from_raw_parts(*self as *const Unused as *const u8, Self::size())
+ };
+ dst.copy_from_slice(src);
+ }
+}
+
+impl<'a> flatbuffers::Verifiable for Unused {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ v.in_buffer::<Self>(pos)
+ }
+}
+
+impl<'a> Unused {
+ #[allow(clippy::too_many_arguments)]
+ pub fn new(
+ a: i32,
+ ) -> Self {
+ let mut s = Self([0; 4]);
+ s.set_a(a);
+ s
+ }
+
+ pub const fn get_fully_qualified_name() -> &'static str {
+ "MyGame.OtherNameSpace.Unused"
+ }
+
+ pub fn a(&self) -> i32 {
+ let mut mem = core::mem::MaybeUninit::<i32>::uninit();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ self.0[0..].as_ptr(),
+ mem.as_mut_ptr() as *mut u8,
+ core::mem::size_of::<i32>(),
+ );
+ mem.assume_init()
+ }.from_little_endian()
+ }
+
+ pub fn set_a(&mut self, x: i32) {
+ let x_le = x.to_little_endian();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ &x_le as *const i32 as *const u8,
+ self.0[0..].as_mut_ptr(),
+ core::mem::size_of::<i32>(),
+ );
+ }
+ }
+
+ pub fn unpack(&self) -> UnusedT {
+ UnusedT {
+ a: self.a(),
+ }
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Default)]
+pub struct UnusedT {
+ pub a: i32,
+}
+impl UnusedT {
+ pub fn pack(&self) -> Unused {
+ Unused::new(
+ self.a,
+ )
+ }
+}
+
diff --git a/tests/include_test1/table_a_generated.rs b/tests/include_test1/table_a_generated.rs
new file mode 100644
index 0000000..9188b29
--- /dev/null
+++ b/tests/include_test1/table_a_generated.rs
@@ -0,0 +1,137 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+pub enum TableAOffset {}
+#[derive(Copy, Clone, PartialEq)]
+
+pub struct TableA<'a> {
+ pub _tab: flatbuffers::Table<'a>,
+}
+
+impl<'a> flatbuffers::Follow<'a> for TableA<'a> {
+ type Inner = TableA<'a>;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ Self { _tab: flatbuffers::Table { buf, loc } }
+ }
+}
+
+impl<'a> TableA<'a> {
+ pub const VT_B: flatbuffers::VOffsetT = 4;
+
+ pub const fn get_fully_qualified_name() -> &'static str {
+ "TableA"
+ }
+
+ #[inline]
+ pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
+ TableA { _tab: table }
+ }
+ #[allow(unused_mut)]
+ pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
+ _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
+ args: &'args TableAArgs<'args>
+ ) -> flatbuffers::WIPOffset<TableA<'bldr>> {
+ let mut builder = TableABuilder::new(_fbb);
+ if let Some(x) = args.b { builder.add_b(x); }
+ builder.finish()
+ }
+
+ pub fn unpack(&self) -> TableAT {
+ let b = self.b().map(|x| {
+ Box::new(x.unpack())
+ });
+ TableAT {
+ b,
+ }
+ }
+
+ #[inline]
+ pub fn b(&self) -> Option<my_game::other_name_space::TableB<'a>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<my_game::other_name_space::TableB>>(TableA::VT_B, None)
+ }
+}
+
+impl flatbuffers::Verifiable for TableA<'_> {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ v.visit_table(pos)?
+ .visit_field::<flatbuffers::ForwardsUOffset<my_game::other_name_space::TableB>>("b", Self::VT_B, false)?
+ .finish();
+ Ok(())
+ }
+}
+pub struct TableAArgs<'a> {
+ pub b: Option<flatbuffers::WIPOffset<my_game::other_name_space::TableB<'a>>>,
+}
+impl<'a> Default for TableAArgs<'a> {
+ #[inline]
+ fn default() -> Self {
+ TableAArgs {
+ b: None,
+ }
+ }
+}
+
+pub struct TableABuilder<'a: 'b, 'b> {
+ fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
+ start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
+}
+impl<'a: 'b, 'b> TableABuilder<'a, 'b> {
+ #[inline]
+ pub fn add_b(&mut self, b: flatbuffers::WIPOffset<my_game::other_name_space::TableB<'b >>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<my_game::other_name_space::TableB>>(TableA::VT_B, b);
+ }
+ #[inline]
+ pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> TableABuilder<'a, 'b> {
+ let start = _fbb.start_table();
+ TableABuilder {
+ fbb_: _fbb,
+ start_: start,
+ }
+ }
+ #[inline]
+ pub fn finish(self) -> flatbuffers::WIPOffset<TableA<'a>> {
+ let o = self.fbb_.end_table(self.start_);
+ flatbuffers::WIPOffset::new(o.value())
+ }
+}
+
+impl std::fmt::Debug for TableA<'_> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let mut ds = f.debug_struct("TableA");
+ ds.field("b", &self.b());
+ ds.finish()
+ }
+}
+#[non_exhaustive]
+#[derive(Debug, Clone, PartialEq)]
+pub struct TableAT {
+ pub b: Option<Box<my_game::other_name_space::TableBT>>,
+}
+impl Default for TableAT {
+ fn default() -> Self {
+ Self {
+ b: None,
+ }
+ }
+}
+impl TableAT {
+ pub fn pack<'b>(
+ &self,
+ _fbb: &mut flatbuffers::FlatBufferBuilder<'b>
+ ) -> flatbuffers::WIPOffset<TableA<'b>> {
+ let b = self.b.as_ref().map(|x|{
+ x.pack(_fbb)
+ });
+ TableA::create(_fbb, &TableAArgs{
+ b,
+ })
+ }
+}
diff --git a/tests/include_test2/mod.rs b/tests/include_test2/mod.rs
new file mode 100644
index 0000000..3a6afa9
--- /dev/null
+++ b/tests/include_test2/mod.rs
@@ -0,0 +1,15 @@
+// Automatically generated by the Flatbuffers compiler. Do not modify.
+pub mod my_game {
+ use super::*;
+ pub mod other_name_space {
+ use super::*;
+ mod from_include_generated;
+ pub use self::from_include_generated::*;
+ mod unused_generated;
+ pub use self::unused_generated::*;
+ mod table_b_generated;
+ pub use self::table_b_generated::*;
+ } // other_name_space
+} // my_game
+mod table_a_generated;
+pub use self::table_a_generated::*;
diff --git a/tests/include_test2/my_game/other_name_space/from_include_generated.rs b/tests/include_test2/my_game/other_name_space/from_include_generated.rs
new file mode 100644
index 0000000..048bafd
--- /dev/null
+++ b/tests/include_test2/my_game/other_name_space/from_include_generated.rs
@@ -0,0 +1,89 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+pub const ENUM_MIN_FROM_INCLUDE: i64 = 0;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+pub const ENUM_MAX_FROM_INCLUDE: i64 = 0;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+#[allow(non_camel_case_types)]
+pub const ENUM_VALUES_FROM_INCLUDE: [FromInclude; 1] = [
+ FromInclude::IncludeVal,
+];
+
+#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
+#[repr(transparent)]
+pub struct FromInclude(pub i64);
+#[allow(non_upper_case_globals)]
+impl FromInclude {
+ pub const IncludeVal: Self = Self(0);
+
+ pub const ENUM_MIN: i64 = 0;
+ pub const ENUM_MAX: i64 = 0;
+ pub const ENUM_VALUES: &'static [Self] = &[
+ Self::IncludeVal,
+ ];
+ /// Returns the variant's name or "" if unknown.
+ pub fn variant_name(self) -> Option<&'static str> {
+ match self {
+ Self::IncludeVal => Some("IncludeVal"),
+ _ => None,
+ }
+ }
+}
+impl std::fmt::Debug for FromInclude {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ if let Some(name) = self.variant_name() {
+ f.write_str(name)
+ } else {
+ f.write_fmt(format_args!("<UNKNOWN {:?}>", self.0))
+ }
+ }
+}
+impl<'a> flatbuffers::Follow<'a> for FromInclude {
+ type Inner = Self;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ let b = unsafe {
+ flatbuffers::read_scalar_at::<i64>(buf, loc)
+ };
+ Self(b)
+ }
+}
+
+impl flatbuffers::Push for FromInclude {
+ type Output = FromInclude;
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ unsafe { flatbuffers::emplace_scalar::<i64>(dst, self.0); }
+ }
+}
+
+impl flatbuffers::EndianScalar for FromInclude {
+ #[inline]
+ fn to_little_endian(self) -> Self {
+ let b = i64::to_le(self.0);
+ Self(b)
+ }
+ #[inline]
+ #[allow(clippy::wrong_self_convention)]
+ fn from_little_endian(self) -> Self {
+ let b = i64::from_le(self.0);
+ Self(b)
+ }
+}
+
+impl<'a> flatbuffers::Verifiable for FromInclude {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ i64::run_verifier(v, pos)
+ }
+}
+
+impl flatbuffers::SimpleToVerifyInSlice for FromInclude {}
diff --git a/tests/include_test2/my_game/other_name_space/table_b_generated.rs b/tests/include_test2/my_game/other_name_space/table_b_generated.rs
new file mode 100644
index 0000000..46a99cb
--- /dev/null
+++ b/tests/include_test2/my_game/other_name_space/table_b_generated.rs
@@ -0,0 +1,137 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+pub enum TableBOffset {}
+#[derive(Copy, Clone, PartialEq)]
+
+pub struct TableB<'a> {
+ pub _tab: flatbuffers::Table<'a>,
+}
+
+impl<'a> flatbuffers::Follow<'a> for TableB<'a> {
+ type Inner = TableB<'a>;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ Self { _tab: flatbuffers::Table { buf, loc } }
+ }
+}
+
+impl<'a> TableB<'a> {
+ pub const VT_A: flatbuffers::VOffsetT = 4;
+
+ pub const fn get_fully_qualified_name() -> &'static str {
+ "MyGame.OtherNameSpace.TableB"
+ }
+
+ #[inline]
+ pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
+ TableB { _tab: table }
+ }
+ #[allow(unused_mut)]
+ pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
+ _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
+ args: &'args TableBArgs<'args>
+ ) -> flatbuffers::WIPOffset<TableB<'bldr>> {
+ let mut builder = TableBBuilder::new(_fbb);
+ if let Some(x) = args.a { builder.add_a(x); }
+ builder.finish()
+ }
+
+ pub fn unpack(&self) -> TableBT {
+ let a = self.a().map(|x| {
+ Box::new(x.unpack())
+ });
+ TableBT {
+ a,
+ }
+ }
+
+ #[inline]
+ pub fn a(&self) -> Option<super::super::TableA<'a>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<super::super::TableA>>(TableB::VT_A, None)
+ }
+}
+
+impl flatbuffers::Verifiable for TableB<'_> {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ v.visit_table(pos)?
+ .visit_field::<flatbuffers::ForwardsUOffset<super::super::TableA>>("a", Self::VT_A, false)?
+ .finish();
+ Ok(())
+ }
+}
+pub struct TableBArgs<'a> {
+ pub a: Option<flatbuffers::WIPOffset<super::super::TableA<'a>>>,
+}
+impl<'a> Default for TableBArgs<'a> {
+ #[inline]
+ fn default() -> Self {
+ TableBArgs {
+ a: None,
+ }
+ }
+}
+
+pub struct TableBBuilder<'a: 'b, 'b> {
+ fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
+ start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
+}
+impl<'a: 'b, 'b> TableBBuilder<'a, 'b> {
+ #[inline]
+ pub fn add_a(&mut self, a: flatbuffers::WIPOffset<super::super::TableA<'b >>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<super::super::TableA>>(TableB::VT_A, a);
+ }
+ #[inline]
+ pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> TableBBuilder<'a, 'b> {
+ let start = _fbb.start_table();
+ TableBBuilder {
+ fbb_: _fbb,
+ start_: start,
+ }
+ }
+ #[inline]
+ pub fn finish(self) -> flatbuffers::WIPOffset<TableB<'a>> {
+ let o = self.fbb_.end_table(self.start_);
+ flatbuffers::WIPOffset::new(o.value())
+ }
+}
+
+impl std::fmt::Debug for TableB<'_> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let mut ds = f.debug_struct("TableB");
+ ds.field("a", &self.a());
+ ds.finish()
+ }
+}
+#[non_exhaustive]
+#[derive(Debug, Clone, PartialEq)]
+pub struct TableBT {
+ pub a: Option<Box<super::super::TableAT>>,
+}
+impl Default for TableBT {
+ fn default() -> Self {
+ Self {
+ a: None,
+ }
+ }
+}
+impl TableBT {
+ pub fn pack<'b>(
+ &self,
+ _fbb: &mut flatbuffers::FlatBufferBuilder<'b>
+ ) -> flatbuffers::WIPOffset<TableB<'b>> {
+ let a = self.a.as_ref().map(|x|{
+ x.pack(_fbb)
+ });
+ TableB::create(_fbb, &TableBArgs{
+ a,
+ })
+ }
+}
diff --git a/tests/include_test2/my_game/other_name_space/unused_generated.rs b/tests/include_test2/my_game/other_name_space/unused_generated.rs
new file mode 100644
index 0000000..1dc5913
--- /dev/null
+++ b/tests/include_test2/my_game/other_name_space/unused_generated.rs
@@ -0,0 +1,127 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+// struct Unused, aligned to 4
+#[repr(transparent)]
+#[derive(Clone, Copy, PartialEq)]
+pub struct Unused(pub [u8; 4]);
+impl Default for Unused {
+ fn default() -> Self {
+ Self([0; 4])
+ }
+}
+impl std::fmt::Debug for Unused {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ f.debug_struct("Unused")
+ .field("a", &self.a())
+ .finish()
+ }
+}
+
+impl flatbuffers::SimpleToVerifyInSlice for Unused {}
+impl flatbuffers::SafeSliceAccess for Unused {}
+impl<'a> flatbuffers::Follow<'a> for Unused {
+ type Inner = &'a Unused;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ <&'a Unused>::follow(buf, loc)
+ }
+}
+impl<'a> flatbuffers::Follow<'a> for &'a Unused {
+ type Inner = &'a Unused;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ flatbuffers::follow_cast_ref::<Unused>(buf, loc)
+ }
+}
+impl<'b> flatbuffers::Push for Unused {
+ type Output = Unused;
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ let src = unsafe {
+ ::std::slice::from_raw_parts(self as *const Unused as *const u8, Self::size())
+ };
+ dst.copy_from_slice(src);
+ }
+}
+impl<'b> flatbuffers::Push for &'b Unused {
+ type Output = Unused;
+
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ let src = unsafe {
+ ::std::slice::from_raw_parts(*self as *const Unused as *const u8, Self::size())
+ };
+ dst.copy_from_slice(src);
+ }
+}
+
+impl<'a> flatbuffers::Verifiable for Unused {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ v.in_buffer::<Self>(pos)
+ }
+}
+
+impl<'a> Unused {
+ #[allow(clippy::too_many_arguments)]
+ pub fn new(
+ a: i32,
+ ) -> Self {
+ let mut s = Self([0; 4]);
+ s.set_a(a);
+ s
+ }
+
+ pub const fn get_fully_qualified_name() -> &'static str {
+ "MyGame.OtherNameSpace.Unused"
+ }
+
+ pub fn a(&self) -> i32 {
+ let mut mem = core::mem::MaybeUninit::<i32>::uninit();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ self.0[0..].as_ptr(),
+ mem.as_mut_ptr() as *mut u8,
+ core::mem::size_of::<i32>(),
+ );
+ mem.assume_init()
+ }.from_little_endian()
+ }
+
+ pub fn set_a(&mut self, x: i32) {
+ let x_le = x.to_little_endian();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ &x_le as *const i32 as *const u8,
+ self.0[0..].as_mut_ptr(),
+ core::mem::size_of::<i32>(),
+ );
+ }
+ }
+
+ pub fn unpack(&self) -> UnusedT {
+ UnusedT {
+ a: self.a(),
+ }
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Default)]
+pub struct UnusedT {
+ pub a: i32,
+}
+impl UnusedT {
+ pub fn pack(&self) -> Unused {
+ Unused::new(
+ self.a,
+ )
+ }
+}
+
diff --git a/tests/include_test2/table_a_generated.rs b/tests/include_test2/table_a_generated.rs
new file mode 100644
index 0000000..9188b29
--- /dev/null
+++ b/tests/include_test2/table_a_generated.rs
@@ -0,0 +1,137 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+pub enum TableAOffset {}
+#[derive(Copy, Clone, PartialEq)]
+
+pub struct TableA<'a> {
+ pub _tab: flatbuffers::Table<'a>,
+}
+
+impl<'a> flatbuffers::Follow<'a> for TableA<'a> {
+ type Inner = TableA<'a>;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ Self { _tab: flatbuffers::Table { buf, loc } }
+ }
+}
+
+impl<'a> TableA<'a> {
+ pub const VT_B: flatbuffers::VOffsetT = 4;
+
+ pub const fn get_fully_qualified_name() -> &'static str {
+ "TableA"
+ }
+
+ #[inline]
+ pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
+ TableA { _tab: table }
+ }
+ #[allow(unused_mut)]
+ pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
+ _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
+ args: &'args TableAArgs<'args>
+ ) -> flatbuffers::WIPOffset<TableA<'bldr>> {
+ let mut builder = TableABuilder::new(_fbb);
+ if let Some(x) = args.b { builder.add_b(x); }
+ builder.finish()
+ }
+
+ pub fn unpack(&self) -> TableAT {
+ let b = self.b().map(|x| {
+ Box::new(x.unpack())
+ });
+ TableAT {
+ b,
+ }
+ }
+
+ #[inline]
+ pub fn b(&self) -> Option<my_game::other_name_space::TableB<'a>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<my_game::other_name_space::TableB>>(TableA::VT_B, None)
+ }
+}
+
+impl flatbuffers::Verifiable for TableA<'_> {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ v.visit_table(pos)?
+ .visit_field::<flatbuffers::ForwardsUOffset<my_game::other_name_space::TableB>>("b", Self::VT_B, false)?
+ .finish();
+ Ok(())
+ }
+}
+pub struct TableAArgs<'a> {
+ pub b: Option<flatbuffers::WIPOffset<my_game::other_name_space::TableB<'a>>>,
+}
+impl<'a> Default for TableAArgs<'a> {
+ #[inline]
+ fn default() -> Self {
+ TableAArgs {
+ b: None,
+ }
+ }
+}
+
+pub struct TableABuilder<'a: 'b, 'b> {
+ fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
+ start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
+}
+impl<'a: 'b, 'b> TableABuilder<'a, 'b> {
+ #[inline]
+ pub fn add_b(&mut self, b: flatbuffers::WIPOffset<my_game::other_name_space::TableB<'b >>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<my_game::other_name_space::TableB>>(TableA::VT_B, b);
+ }
+ #[inline]
+ pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> TableABuilder<'a, 'b> {
+ let start = _fbb.start_table();
+ TableABuilder {
+ fbb_: _fbb,
+ start_: start,
+ }
+ }
+ #[inline]
+ pub fn finish(self) -> flatbuffers::WIPOffset<TableA<'a>> {
+ let o = self.fbb_.end_table(self.start_);
+ flatbuffers::WIPOffset::new(o.value())
+ }
+}
+
+impl std::fmt::Debug for TableA<'_> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let mut ds = f.debug_struct("TableA");
+ ds.field("b", &self.b());
+ ds.finish()
+ }
+}
+#[non_exhaustive]
+#[derive(Debug, Clone, PartialEq)]
+pub struct TableAT {
+ pub b: Option<Box<my_game::other_name_space::TableBT>>,
+}
+impl Default for TableAT {
+ fn default() -> Self {
+ Self {
+ b: None,
+ }
+ }
+}
+impl TableAT {
+ pub fn pack<'b>(
+ &self,
+ _fbb: &mut flatbuffers::FlatBufferBuilder<'b>
+ ) -> flatbuffers::WIPOffset<TableA<'b>> {
+ let b = self.b.as_ref().map(|x|{
+ x.pack(_fbb)
+ });
+ TableA::create(_fbb, &TableAArgs{
+ b,
+ })
+ }
+}
diff --git a/tests/included_test.fbs b/tests/included_test.fbs
new file mode 100644
index 0000000..59c4a85
--- /dev/null
+++ b/tests/included_test.fbs
@@ -0,0 +1,3 @@
+table Wrapped {
+ a:double;
+}
diff --git a/tests/includer_test.fbs b/tests/includer_test.fbs
new file mode 100644
index 0000000..890fa70
--- /dev/null
+++ b/tests/includer_test.fbs
@@ -0,0 +1,5 @@
+include "tests/included_test.fbs";
+
+table Wrapper {
+ a:Wrapped;
+}
diff --git a/tests/keyword_test.fbs b/tests/keyword_test.fbs
new file mode 100644
index 0000000..4ca761b
--- /dev/null
+++ b/tests/keyword_test.fbs
@@ -0,0 +1,16 @@
+namespace KeywordTest;
+
+enum ABC: int { void, where, stackalloc }
+
+enum public: int { }
+
+table KeywordsInTable {
+ is: ABC = void;
+ private: public;
+ type: int;
+}
+
+union KeywordsInUnion {
+ static: KeywordsInTable,
+ internal: KeywordsInTable,
+}
diff --git a/tests/keyword_test/keyword_test/abc_generated.rs b/tests/keyword_test/keyword_test/abc_generated.rs
new file mode 100644
index 0000000..99b43e4
--- /dev/null
+++ b/tests/keyword_test/keyword_test/abc_generated.rs
@@ -0,0 +1,97 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+pub const ENUM_MIN_ABC: i32 = 0;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+pub const ENUM_MAX_ABC: i32 = 2;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+#[allow(non_camel_case_types)]
+pub const ENUM_VALUES_ABC: [ABC; 3] = [
+ ABC::void,
+ ABC::where_,
+ ABC::stackalloc,
+];
+
+#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
+#[repr(transparent)]
+pub struct ABC(pub i32);
+#[allow(non_upper_case_globals)]
+impl ABC {
+ pub const void: Self = Self(0);
+ pub const where_: Self = Self(1);
+ pub const stackalloc: Self = Self(2);
+
+ pub const ENUM_MIN: i32 = 0;
+ pub const ENUM_MAX: i32 = 2;
+ pub const ENUM_VALUES: &'static [Self] = &[
+ Self::void,
+ Self::where_,
+ Self::stackalloc,
+ ];
+ /// Returns the variant's name or "" if unknown.
+ pub fn variant_name(self) -> Option<&'static str> {
+ match self {
+ Self::void => Some("void"),
+ Self::where_ => Some("where_"),
+ Self::stackalloc => Some("stackalloc"),
+ _ => None,
+ }
+ }
+}
+impl std::fmt::Debug for ABC {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ if let Some(name) = self.variant_name() {
+ f.write_str(name)
+ } else {
+ f.write_fmt(format_args!("<UNKNOWN {:?}>", self.0))
+ }
+ }
+}
+impl<'a> flatbuffers::Follow<'a> for ABC {
+ type Inner = Self;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ let b = unsafe {
+ flatbuffers::read_scalar_at::<i32>(buf, loc)
+ };
+ Self(b)
+ }
+}
+
+impl flatbuffers::Push for ABC {
+ type Output = ABC;
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ unsafe { flatbuffers::emplace_scalar::<i32>(dst, self.0); }
+ }
+}
+
+impl flatbuffers::EndianScalar for ABC {
+ #[inline]
+ fn to_little_endian(self) -> Self {
+ let b = i32::to_le(self.0);
+ Self(b)
+ }
+ #[inline]
+ #[allow(clippy::wrong_self_convention)]
+ fn from_little_endian(self) -> Self {
+ let b = i32::from_le(self.0);
+ Self(b)
+ }
+}
+
+impl<'a> flatbuffers::Verifiable for ABC {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ i32::run_verifier(v, pos)
+ }
+}
+
+impl flatbuffers::SimpleToVerifyInSlice for ABC {}
diff --git a/tests/keyword_test/keyword_test/keywords_in_table_generated.rs b/tests/keyword_test/keyword_test/keywords_in_table_generated.rs
new file mode 100644
index 0000000..6a16f05
--- /dev/null
+++ b/tests/keyword_test/keyword_test/keywords_in_table_generated.rs
@@ -0,0 +1,173 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+pub enum KeywordsInTableOffset {}
+#[derive(Copy, Clone, PartialEq)]
+
+pub struct KeywordsInTable<'a> {
+ pub _tab: flatbuffers::Table<'a>,
+}
+
+impl<'a> flatbuffers::Follow<'a> for KeywordsInTable<'a> {
+ type Inner = KeywordsInTable<'a>;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ Self { _tab: flatbuffers::Table { buf, loc } }
+ }
+}
+
+impl<'a> KeywordsInTable<'a> {
+ pub const VT_IS: flatbuffers::VOffsetT = 4;
+ pub const VT_PRIVATE: flatbuffers::VOffsetT = 6;
+ pub const VT_TYPE_: flatbuffers::VOffsetT = 8;
+
+ pub const fn get_fully_qualified_name() -> &'static str {
+ "KeywordTest.KeywordsInTable"
+ }
+
+ #[inline]
+ pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
+ KeywordsInTable { _tab: table }
+ }
+ #[allow(unused_mut)]
+ pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
+ _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
+ args: &'args KeywordsInTableArgs
+ ) -> flatbuffers::WIPOffset<KeywordsInTable<'bldr>> {
+ let mut builder = KeywordsInTableBuilder::new(_fbb);
+ builder.add_type_(args.type_);
+ builder.add_private(args.private);
+ builder.add_is(args.is);
+ builder.finish()
+ }
+
+ pub fn unpack(&self) -> KeywordsInTableT {
+ let is = self.is();
+ let private = self.private();
+ let type_ = self.type_();
+ KeywordsInTableT {
+ is,
+ private,
+ type_,
+ }
+ }
+
+ #[inline]
+ pub fn is(&self) -> ABC {
+ self._tab.get::<ABC>(KeywordsInTable::VT_IS, Some(ABC::void)).unwrap()
+ }
+ #[inline]
+ pub fn private(&self) -> public {
+ self._tab.get::<public>(KeywordsInTable::VT_PRIVATE, Some(public::NONE)).unwrap()
+ }
+ #[inline]
+ pub fn type_(&self) -> i32 {
+ self._tab.get::<i32>(KeywordsInTable::VT_TYPE_, Some(0)).unwrap()
+ }
+}
+
+impl flatbuffers::Verifiable for KeywordsInTable<'_> {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ v.visit_table(pos)?
+ .visit_field::<ABC>("is", Self::VT_IS, false)?
+ .visit_field::<public>("private", Self::VT_PRIVATE, false)?
+ .visit_field::<i32>("type_", Self::VT_TYPE_, false)?
+ .finish();
+ Ok(())
+ }
+}
+pub struct KeywordsInTableArgs {
+ pub is: ABC,
+ pub private: public,
+ pub type_: i32,
+}
+impl<'a> Default for KeywordsInTableArgs {
+ #[inline]
+ fn default() -> Self {
+ KeywordsInTableArgs {
+ is: ABC::void,
+ private: public::NONE,
+ type_: 0,
+ }
+ }
+}
+
+pub struct KeywordsInTableBuilder<'a: 'b, 'b> {
+ fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
+ start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
+}
+impl<'a: 'b, 'b> KeywordsInTableBuilder<'a, 'b> {
+ #[inline]
+ pub fn add_is(&mut self, is: ABC) {
+ self.fbb_.push_slot::<ABC>(KeywordsInTable::VT_IS, is, ABC::void);
+ }
+ #[inline]
+ pub fn add_private(&mut self, private: public) {
+ self.fbb_.push_slot::<public>(KeywordsInTable::VT_PRIVATE, private, public::NONE);
+ }
+ #[inline]
+ pub fn add_type_(&mut self, type_: i32) {
+ self.fbb_.push_slot::<i32>(KeywordsInTable::VT_TYPE_, type_, 0);
+ }
+ #[inline]
+ pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> KeywordsInTableBuilder<'a, 'b> {
+ let start = _fbb.start_table();
+ KeywordsInTableBuilder {
+ fbb_: _fbb,
+ start_: start,
+ }
+ }
+ #[inline]
+ pub fn finish(self) -> flatbuffers::WIPOffset<KeywordsInTable<'a>> {
+ let o = self.fbb_.end_table(self.start_);
+ flatbuffers::WIPOffset::new(o.value())
+ }
+}
+
+impl std::fmt::Debug for KeywordsInTable<'_> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let mut ds = f.debug_struct("KeywordsInTable");
+ ds.field("is", &self.is());
+ ds.field("private", &self.private());
+ ds.field("type_", &self.type_());
+ ds.finish()
+ }
+}
+#[non_exhaustive]
+#[derive(Debug, Clone, PartialEq)]
+pub struct KeywordsInTableT {
+ pub is: ABC,
+ pub private: public,
+ pub type_: i32,
+}
+impl Default for KeywordsInTableT {
+ fn default() -> Self {
+ Self {
+ is: ABC::void,
+ private: public::NONE,
+ type_: 0,
+ }
+ }
+}
+impl KeywordsInTableT {
+ pub fn pack<'b>(
+ &self,
+ _fbb: &mut flatbuffers::FlatBufferBuilder<'b>
+ ) -> flatbuffers::WIPOffset<KeywordsInTable<'b>> {
+ let is = self.is;
+ let private = self.private;
+ let type_ = self.type_;
+ KeywordsInTable::create(_fbb, &KeywordsInTableArgs{
+ is,
+ private,
+ type_,
+ })
+ }
+}
diff --git a/tests/keyword_test/keyword_test/keywords_in_union_generated.rs b/tests/keyword_test/keyword_test/keywords_in_union_generated.rs
new file mode 100644
index 0000000..cf03797
--- /dev/null
+++ b/tests/keyword_test/keyword_test/keywords_in_union_generated.rs
@@ -0,0 +1,170 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+pub const ENUM_MIN_KEYWORDS_IN_UNION: u8 = 0;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+pub const ENUM_MAX_KEYWORDS_IN_UNION: u8 = 2;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+#[allow(non_camel_case_types)]
+pub const ENUM_VALUES_KEYWORDS_IN_UNION: [KeywordsInUnion; 3] = [
+ KeywordsInUnion::NONE,
+ KeywordsInUnion::static_,
+ KeywordsInUnion::internal,
+];
+
+#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
+#[repr(transparent)]
+pub struct KeywordsInUnion(pub u8);
+#[allow(non_upper_case_globals)]
+impl KeywordsInUnion {
+ pub const NONE: Self = Self(0);
+ pub const static_: Self = Self(1);
+ pub const internal: Self = Self(2);
+
+ pub const ENUM_MIN: u8 = 0;
+ pub const ENUM_MAX: u8 = 2;
+ pub const ENUM_VALUES: &'static [Self] = &[
+ Self::NONE,
+ Self::static_,
+ Self::internal,
+ ];
+ /// Returns the variant's name or "" if unknown.
+ pub fn variant_name(self) -> Option<&'static str> {
+ match self {
+ Self::NONE => Some("NONE"),
+ Self::static_ => Some("static_"),
+ Self::internal => Some("internal"),
+ _ => None,
+ }
+ }
+}
+impl std::fmt::Debug for KeywordsInUnion {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ if let Some(name) = self.variant_name() {
+ f.write_str(name)
+ } else {
+ f.write_fmt(format_args!("<UNKNOWN {:?}>", self.0))
+ }
+ }
+}
+impl<'a> flatbuffers::Follow<'a> for KeywordsInUnion {
+ type Inner = Self;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ let b = unsafe {
+ flatbuffers::read_scalar_at::<u8>(buf, loc)
+ };
+ Self(b)
+ }
+}
+
+impl flatbuffers::Push for KeywordsInUnion {
+ type Output = KeywordsInUnion;
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ unsafe { flatbuffers::emplace_scalar::<u8>(dst, self.0); }
+ }
+}
+
+impl flatbuffers::EndianScalar for KeywordsInUnion {
+ #[inline]
+ fn to_little_endian(self) -> Self {
+ let b = u8::to_le(self.0);
+ Self(b)
+ }
+ #[inline]
+ #[allow(clippy::wrong_self_convention)]
+ fn from_little_endian(self) -> Self {
+ let b = u8::from_le(self.0);
+ Self(b)
+ }
+}
+
+impl<'a> flatbuffers::Verifiable for KeywordsInUnion {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ u8::run_verifier(v, pos)
+ }
+}
+
+impl flatbuffers::SimpleToVerifyInSlice for KeywordsInUnion {}
+pub struct KeywordsInUnionUnionTableOffset {}
+
+#[allow(clippy::upper_case_acronyms)]
+#[non_exhaustive]
+#[derive(Debug, Clone, PartialEq)]
+pub enum KeywordsInUnionT {
+ NONE,
+ Static_(Box<KeywordsInTableT>),
+ Internal(Box<KeywordsInTableT>),
+}
+impl Default for KeywordsInUnionT {
+ fn default() -> Self {
+ Self::NONE
+ }
+}
+impl KeywordsInUnionT {
+ pub fn keywords_in_union_type(&self) -> KeywordsInUnion {
+ match self {
+ Self::NONE => KeywordsInUnion::NONE,
+ Self::Static_(_) => KeywordsInUnion::static_,
+ Self::Internal(_) => KeywordsInUnion::internal,
+ }
+ }
+ pub fn pack(&self, fbb: &mut flatbuffers::FlatBufferBuilder) -> Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>> {
+ match self {
+ Self::NONE => None,
+ Self::Static_(v) => Some(v.pack(fbb).as_union_value()),
+ Self::Internal(v) => Some(v.pack(fbb).as_union_value()),
+ }
+ }
+ /// If the union variant matches, return the owned KeywordsInTableT, setting the union to NONE.
+ pub fn take_static_(&mut self) -> Option<Box<KeywordsInTableT>> {
+ if let Self::Static_(_) = self {
+ let v = std::mem::replace(self, Self::NONE);
+ if let Self::Static_(w) = v {
+ Some(w)
+ } else {
+ unreachable!()
+ }
+ } else {
+ None
+ }
+ }
+ /// If the union variant matches, return a reference to the KeywordsInTableT.
+ pub fn as_static_(&self) -> Option<&KeywordsInTableT> {
+ if let Self::Static_(v) = self { Some(v.as_ref()) } else { None }
+ }
+ /// If the union variant matches, return a mutable reference to the KeywordsInTableT.
+ pub fn as_static__mut(&mut self) -> Option<&mut KeywordsInTableT> {
+ if let Self::Static_(v) = self { Some(v.as_mut()) } else { None }
+ }
+ /// If the union variant matches, return the owned KeywordsInTableT, setting the union to NONE.
+ pub fn take_internal(&mut self) -> Option<Box<KeywordsInTableT>> {
+ if let Self::Internal(_) = self {
+ let v = std::mem::replace(self, Self::NONE);
+ if let Self::Internal(w) = v {
+ Some(w)
+ } else {
+ unreachable!()
+ }
+ } else {
+ None
+ }
+ }
+ /// If the union variant matches, return a reference to the KeywordsInTableT.
+ pub fn as_internal(&self) -> Option<&KeywordsInTableT> {
+ if let Self::Internal(v) = self { Some(v.as_ref()) } else { None }
+ }
+ /// If the union variant matches, return a mutable reference to the KeywordsInTableT.
+ pub fn as_internal_mut(&mut self) -> Option<&mut KeywordsInTableT> {
+ if let Self::Internal(v) = self { Some(v.as_mut()) } else { None }
+ }
+}
diff --git a/tests/keyword_test/keyword_test/public_generated.rs b/tests/keyword_test/keyword_test/public_generated.rs
new file mode 100644
index 0000000..2de4c0b
--- /dev/null
+++ b/tests/keyword_test/keyword_test/public_generated.rs
@@ -0,0 +1,89 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+pub const ENUM_MIN_PUBLIC: i32 = 0;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+pub const ENUM_MAX_PUBLIC: i32 = 0;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+#[allow(non_camel_case_types)]
+pub const ENUM_VALUES_PUBLIC: [public; 1] = [
+ public::NONE,
+];
+
+#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
+#[repr(transparent)]
+pub struct public(pub i32);
+#[allow(non_upper_case_globals)]
+impl public {
+ pub const NONE: Self = Self(0);
+
+ pub const ENUM_MIN: i32 = 0;
+ pub const ENUM_MAX: i32 = 0;
+ pub const ENUM_VALUES: &'static [Self] = &[
+ Self::NONE,
+ ];
+ /// Returns the variant's name or "" if unknown.
+ pub fn variant_name(self) -> Option<&'static str> {
+ match self {
+ Self::NONE => Some("NONE"),
+ _ => None,
+ }
+ }
+}
+impl std::fmt::Debug for public {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ if let Some(name) = self.variant_name() {
+ f.write_str(name)
+ } else {
+ f.write_fmt(format_args!("<UNKNOWN {:?}>", self.0))
+ }
+ }
+}
+impl<'a> flatbuffers::Follow<'a> for public {
+ type Inner = Self;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ let b = unsafe {
+ flatbuffers::read_scalar_at::<i32>(buf, loc)
+ };
+ Self(b)
+ }
+}
+
+impl flatbuffers::Push for public {
+ type Output = public;
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ unsafe { flatbuffers::emplace_scalar::<i32>(dst, self.0); }
+ }
+}
+
+impl flatbuffers::EndianScalar for public {
+ #[inline]
+ fn to_little_endian(self) -> Self {
+ let b = i32::to_le(self.0);
+ Self(b)
+ }
+ #[inline]
+ #[allow(clippy::wrong_self_convention)]
+ fn from_little_endian(self) -> Self {
+ let b = i32::from_le(self.0);
+ Self(b)
+ }
+}
+
+impl<'a> flatbuffers::Verifiable for public {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ i32::run_verifier(v, pos)
+ }
+}
+
+impl flatbuffers::SimpleToVerifyInSlice for public {}
diff --git a/tests/keyword_test/mod.rs b/tests/keyword_test/mod.rs
new file mode 100644
index 0000000..94ce650
--- /dev/null
+++ b/tests/keyword_test/mod.rs
@@ -0,0 +1,12 @@
+// Automatically generated by the Flatbuffers compiler. Do not modify.
+pub mod keyword_test {
+ use super::*;
+ mod abc_generated;
+ pub use self::abc_generated::*;
+ mod public_generated;
+ pub use self::public_generated::*;
+ mod keywords_in_union_generated;
+ pub use self::keywords_in_union_generated::*;
+ mod keywords_in_table_generated;
+ pub use self::keywords_in_table_generated::*;
+} // keyword_test
diff --git a/tests/lobstertest.lobster b/tests/lobstertest.lobster
index a0f81ce..454c2b8 100644
--- a/tests/lobstertest.lobster
+++ b/tests/lobstertest.lobster
@@ -17,7 +17,9 @@
import optional_scalars_generated
def check_read_buffer(buf):
- // CheckReadBuffer checks that the given buffer is evaluated correctly as the example Monster.
+ // Check that the given buffer is evaluated correctly as the example Monster.
+ assert flatbuffers_has_identifier(buf, "MONS")
+
let monster = MyGame_Example_GetRootAsMonster(buf)
assert monster.hp == 80
@@ -105,7 +107,7 @@
.add_vector_of_doubles(vector_of_doubles)
.end()
- b.Finish(mon)
+ b.Finish(mon, "MONS")
return b.SizedCopy()
@@ -126,8 +128,10 @@
ss.add_just_enum(optional_scalars_OptionalByte_Two)
ss.add_maybe_enum(optional_scalars_OptionalByte_Two)
ss.add_default_enum(optional_scalars_OptionalByte_Two)
- b.Finish(ss.end())
- return optional_scalars_GetRootAsScalarStuff(b.SizedCopy())
+ b.Finish(ss.end(), "NULL")
+ let buf = b.SizedCopy()
+ assert flatbuffers_has_identifier(buf, "NULL")
+ return optional_scalars_GetRootAsScalarStuff(buf)
var root = build(true)
diff --git a/tests/luatest.lua b/tests/luatest.lua
index e60f837..1a70f5f 100644
--- a/tests/luatest.lua
+++ b/tests/luatest.lua
@@ -1,4 +1,16 @@
package.path = string.format("../lua/?.lua;./?.lua;%s",package.path)
+local compat = require("flatbuffers.compat")
+
+local performBenchmarkTests = false
+
+if #arg > 1 then
+ print("usage: lua luatests [benchmark]");
+ return
+elseif #arg > 0 then
+ if(arg[1] == "benchmark") then
+ performBenchmarkTests = true
+ end
+end
local function checkReadBuffer(buf, offset, sizePrefix)
offset = offset or 0
@@ -9,7 +21,7 @@
if sizePrefix then
local size = flatbuffers.N.Int32:Unpack(buf, offset)
- assert(size == #buf - offset - 4)
+ assert(size == buf.size - offset - 4)
offset = offset + flatbuffers.N.Int32.bytewidth
end
@@ -17,6 +29,7 @@
assert(mon:Hp() == 80, "Monster Hp is not 80")
assert(mon:Mana() == 150, "Monster Mana is not 150")
assert(mon:Name() == "MyMonster", "Monster Name is not MyMonster")
+ assert(mon:Testbool() == true)
local vec = assert(mon:Pos(), "Monster Position is nil")
assert(vec:X() == 1.0)
@@ -209,6 +222,18 @@
checkReadBuffer(wireData)
end
+local function testCreateEmptyString()
+ local b = flatbuffers.Builder(0)
+ local str = b:CreateString("")
+ monster.Start(b)
+ monster.AddName(b, str)
+ b:Finish(monster.End(b))
+ local s = b:Output()
+ local data = flatbuffers.binaryArray.New(s)
+ local mon = monster.GetRootAsMonster(data, 0)
+ assert(mon:Name() == "")
+end
+
local function benchmarkMakeMonster(count, reuseBuilder)
local fbb = reuseBuilder and flatbuffers.Builder(0)
local length = #(generateMonster(false, fbb))
@@ -247,7 +272,51 @@
print(string.format('traversed %d %d-byte flatbuffers in %.2fsec: %.2f/msec, %.2fMB/sec',
count, #buf, dur, rate, dataRate))
end
+
+local function getRootAs_canAcceptString()
+ local f = assert(io.open('monsterdata_test.mon', 'rb'))
+ local wireData = f:read("*a")
+ f:close()
+ assert(type(wireData) == "string", "Data is not a string");
+ local mon = monster.GetRootAsMonster(wireData, 0)
+ assert(mon:Hp() == 80, "Monster Hp is not 80")
+end
+local function testAccessByteVectorAsString()
+ local f = assert(io.open('monsterdata_test.mon', 'rb'))
+ local wireData = f:read("*a")
+ f:close()
+ local mon = monster.GetRootAsMonster(wireData, 0)
+ -- the data of byte array Inventory is [0, 1, 2, 3, 4]
+ local s = mon:InventoryAsString(1, 3)
+ assert(#s == 3)
+ for i = 1, #s do
+ assert(string.byte(s, i) == i - 1)
+ end
+
+ local s = mon:InventoryAsString(2, 5)
+ assert(#s == 4)
+ for i = 1, #s do
+ assert(string.byte(s, i) == i)
+ end
+
+ local s = mon:InventoryAsString(5, 5)
+ assert(#s == 1)
+ assert(string.byte(s, 1) == 4)
+
+ local s = mon:InventoryAsString(2)
+ assert(#s == 4)
+ for i = 1, #s do
+ assert(string.byte(s, i) == i)
+ end
+
+ local s = mon:InventoryAsString()
+ assert(#s == 5)
+ for i = 1, #s do
+ assert(string.byte(s, i) == i - 1)
+ end
+end
+
local tests =
{
{
@@ -264,6 +333,22 @@
d = "Tests Canonical flatbuffer file included in repo"
},
{
+ f = testCreateEmptyString,
+ d = "Avoid infinite loop when creating empty string"
+ },
+ {
+ f = getRootAs_canAcceptString,
+ d = "Tests that GetRootAs<type>() generated methods accept strings"
+ },
+ {
+ f = testAccessByteVectorAsString,
+ d = "Access byte vector as string"
+ },
+}
+
+local benchmarks =
+{
+ {
f = benchmarkMakeMonster,
d = "Benchmark making monsters",
args = {
@@ -301,6 +386,12 @@
return s:sub(1,-2)
end
+ if performBenchmarkTests then
+ for _,benchmark in ipairs(benchmarks) do
+ table.insert(tests, benchmark)
+ end
+ end
+
local testsPassed, testsFailed = 0,0
for _,test in ipairs(tests) do
local allargs = test.args or {{}}
@@ -334,4 +425,4 @@
print("Unable to run tests due to test framework error: ",err)
end
-os.exit(result or -1)
+os.exit(result and 0 or -1)
diff --git a/tests/monster_extra_generated.h b/tests/monster_extra_generated.h
index 5c4d8de..b27e092 100644
--- a/tests/monster_extra_generated.h
+++ b/tests/monster_extra_generated.h
@@ -19,47 +19,18 @@
struct MonsterExtraT : public flatbuffers::NativeTable {
typedef MonsterExtra TableType;
- double d0;
- double d1;
- double d2;
- double d3;
- float f0;
- float f1;
- float f2;
- float f3;
- std::vector<double> dvec;
- std::vector<float> fvec;
- MonsterExtraT()
- : d0(std::numeric_limits<double>::quiet_NaN()),
- d1(std::numeric_limits<double>::quiet_NaN()),
- d2(std::numeric_limits<double>::infinity()),
- d3(-std::numeric_limits<double>::infinity()),
- f0(std::numeric_limits<float>::quiet_NaN()),
- f1(std::numeric_limits<float>::quiet_NaN()),
- f2(std::numeric_limits<float>::infinity()),
- f3(-std::numeric_limits<float>::infinity()) {
- }
+ double d0 = std::numeric_limits<double>::quiet_NaN();
+ double d1 = std::numeric_limits<double>::quiet_NaN();
+ double d2 = std::numeric_limits<double>::infinity();
+ double d3 = -std::numeric_limits<double>::infinity();
+ float f0 = std::numeric_limits<float>::quiet_NaN();
+ float f1 = std::numeric_limits<float>::quiet_NaN();
+ float f2 = std::numeric_limits<float>::infinity();
+ float f3 = -std::numeric_limits<float>::infinity();
+ std::vector<double> dvec{};
+ std::vector<float> fvec{};
};
-inline bool operator==(const MonsterExtraT &lhs, const MonsterExtraT &rhs) {
- return
- (lhs.d0 == rhs.d0) &&
- (lhs.d1 == rhs.d1) &&
- (lhs.d2 == rhs.d2) &&
- (lhs.d3 == rhs.d3) &&
- (lhs.f0 == rhs.f0) &&
- (lhs.f1 == rhs.f1) &&
- (lhs.f2 == rhs.f2) &&
- (lhs.f3 == rhs.f3) &&
- (lhs.dvec == rhs.dvec) &&
- (lhs.fvec == rhs.fvec);
-}
-
-inline bool operator!=(const MonsterExtraT &lhs, const MonsterExtraT &rhs) {
- return !(lhs == rhs);
-}
-
-
struct MonsterExtra FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
typedef MonsterExtraT NativeTableType;
typedef MonsterExtraBuilder Builder;
@@ -81,49 +52,49 @@
double d0() const {
return GetField<double>(VT_D0, std::numeric_limits<double>::quiet_NaN());
}
- bool mutate_d0(double _d0) {
+ bool mutate_d0(double _d0 = std::numeric_limits<double>::quiet_NaN()) {
return SetField<double>(VT_D0, _d0, std::numeric_limits<double>::quiet_NaN());
}
double d1() const {
return GetField<double>(VT_D1, std::numeric_limits<double>::quiet_NaN());
}
- bool mutate_d1(double _d1) {
+ bool mutate_d1(double _d1 = std::numeric_limits<double>::quiet_NaN()) {
return SetField<double>(VT_D1, _d1, std::numeric_limits<double>::quiet_NaN());
}
double d2() const {
return GetField<double>(VT_D2, std::numeric_limits<double>::infinity());
}
- bool mutate_d2(double _d2) {
+ bool mutate_d2(double _d2 = std::numeric_limits<double>::infinity()) {
return SetField<double>(VT_D2, _d2, std::numeric_limits<double>::infinity());
}
double d3() const {
return GetField<double>(VT_D3, -std::numeric_limits<double>::infinity());
}
- bool mutate_d3(double _d3) {
+ bool mutate_d3(double _d3 = -std::numeric_limits<double>::infinity()) {
return SetField<double>(VT_D3, _d3, -std::numeric_limits<double>::infinity());
}
float f0() const {
return GetField<float>(VT_F0, std::numeric_limits<float>::quiet_NaN());
}
- bool mutate_f0(float _f0) {
+ bool mutate_f0(float _f0 = std::numeric_limits<float>::quiet_NaN()) {
return SetField<float>(VT_F0, _f0, std::numeric_limits<float>::quiet_NaN());
}
float f1() const {
return GetField<float>(VT_F1, std::numeric_limits<float>::quiet_NaN());
}
- bool mutate_f1(float _f1) {
+ bool mutate_f1(float _f1 = std::numeric_limits<float>::quiet_NaN()) {
return SetField<float>(VT_F1, _f1, std::numeric_limits<float>::quiet_NaN());
}
float f2() const {
return GetField<float>(VT_F2, std::numeric_limits<float>::infinity());
}
- bool mutate_f2(float _f2) {
+ bool mutate_f2(float _f2 = std::numeric_limits<float>::infinity()) {
return SetField<float>(VT_F2, _f2, std::numeric_limits<float>::infinity());
}
float f3() const {
return GetField<float>(VT_F3, -std::numeric_limits<float>::infinity());
}
- bool mutate_f3(float _f3) {
+ bool mutate_f3(float _f3 = -std::numeric_limits<float>::infinity()) {
return SetField<float>(VT_F3, _f3, -std::numeric_limits<float>::infinity());
}
const flatbuffers::Vector<double> *dvec() const {
@@ -140,14 +111,14 @@
}
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
- VerifyField<double>(verifier, VT_D0) &&
- VerifyField<double>(verifier, VT_D1) &&
- VerifyField<double>(verifier, VT_D2) &&
- VerifyField<double>(verifier, VT_D3) &&
- VerifyField<float>(verifier, VT_F0) &&
- VerifyField<float>(verifier, VT_F1) &&
- VerifyField<float>(verifier, VT_F2) &&
- VerifyField<float>(verifier, VT_F3) &&
+ VerifyField<double>(verifier, VT_D0, 8) &&
+ VerifyField<double>(verifier, VT_D1, 8) &&
+ VerifyField<double>(verifier, VT_D2, 8) &&
+ VerifyField<double>(verifier, VT_D3, 8) &&
+ VerifyField<float>(verifier, VT_F0, 4) &&
+ VerifyField<float>(verifier, VT_F1, 4) &&
+ VerifyField<float>(verifier, VT_F2, 4) &&
+ VerifyField<float>(verifier, VT_F3, 4) &&
VerifyOffset(verifier, VT_DVEC) &&
verifier.VerifyVector(dvec()) &&
VerifyOffset(verifier, VT_FVEC) &&
@@ -260,8 +231,28 @@
flatbuffers::Offset<MonsterExtra> CreateMonsterExtra(flatbuffers::FlatBufferBuilder &_fbb, const MonsterExtraT *_o, const flatbuffers::rehasher_function_t *_rehasher = nullptr);
+
+inline bool operator==(const MonsterExtraT &lhs, const MonsterExtraT &rhs) {
+ return
+ (lhs.d0 == rhs.d0) &&
+ (lhs.d1 == rhs.d1) &&
+ (lhs.d2 == rhs.d2) &&
+ (lhs.d3 == rhs.d3) &&
+ (lhs.f0 == rhs.f0) &&
+ (lhs.f1 == rhs.f1) &&
+ (lhs.f2 == rhs.f2) &&
+ (lhs.f3 == rhs.f3) &&
+ (lhs.dvec == rhs.dvec) &&
+ (lhs.fvec == rhs.fvec);
+}
+
+inline bool operator!=(const MonsterExtraT &lhs, const MonsterExtraT &rhs) {
+ return !(lhs == rhs);
+}
+
+
inline MonsterExtraT *MonsterExtra::UnPack(const flatbuffers::resolver_function_t *_resolver) const {
- flatbuffers::unique_ptr<MyGame::MonsterExtraT> _o = flatbuffers::unique_ptr<MyGame::MonsterExtraT>(new MonsterExtraT());
+ auto _o = std::unique_ptr<MonsterExtraT>(new MonsterExtraT());
UnPackTo(_o.get(), _resolver);
return _o.release();
}
@@ -358,6 +349,10 @@
return flatbuffers::GetMutableRoot<MonsterExtra>(buf);
}
+inline MyGame::MonsterExtra *GetMutableSizePrefixedMonsterExtra(void *buf) {
+ return flatbuffers::GetMutableSizePrefixedRoot<MyGame::MonsterExtra>(buf);
+}
+
inline const char *MonsterExtraIdentifier() {
return "MONE";
}
@@ -367,6 +362,11 @@
buf, MonsterExtraIdentifier());
}
+inline bool SizePrefixedMonsterExtraBufferHasIdentifier(const void *buf) {
+ return flatbuffers::BufferHasIdentifier(
+ buf, MonsterExtraIdentifier(), true);
+}
+
inline bool VerifyMonsterExtraBuffer(
flatbuffers::Verifier &verifier) {
return verifier.VerifyBuffer<MyGame::MonsterExtra>(MonsterExtraIdentifier());
diff --git a/tests/monster_extra_my_game_generated.dart b/tests/monster_extra_my_game_generated.dart
index 676641d..238ab8f 100644
--- a/tests/monster_extra_my_game_generated.dart
+++ b/tests/monster_extra_my_game_generated.dart
@@ -1,5 +1,5 @@
// automatically generated by the FlatBuffers compiler, do not modify
-// ignore_for_file: unused_import, unused_field, unused_local_variable
+// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable
library my_game;
@@ -10,11 +10,11 @@
class MonsterExtra {
MonsterExtra._(this._bc, this._bcOffset);
factory MonsterExtra(List<int> bytes) {
- fb.BufferContext rootRef = new fb.BufferContext.fromBytes(bytes);
+ final rootRef = fb.BufferContext.fromBytes(bytes);
return reader.read(rootRef, 0);
}
- static const fb.Reader<MonsterExtra> reader = const _MonsterExtraReader();
+ static const fb.Reader<MonsterExtra> reader = _MonsterExtraReader();
final fb.BufferContext _bc;
final int _bcOffset;
@@ -27,13 +27,80 @@
double get f1 => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 14, double.nan);
double get f2 => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 16, double.infinity);
double get f3 => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 18, double.negativeInfinity);
- List<double> get dvec => const fb.ListReader<double>(const fb.Float64Reader()).vTableGet(_bc, _bcOffset, 20, null);
- List<double> get fvec => const fb.ListReader<double>(const fb.Float32Reader()).vTableGet(_bc, _bcOffset, 22, null);
+ List<double>? get dvec => const fb.ListReader<double>(fb.Float64Reader()).vTableGetNullable(_bc, _bcOffset, 20);
+ List<double>? get fvec => const fb.ListReader<double>(fb.Float32Reader()).vTableGetNullable(_bc, _bcOffset, 22);
@override
String toString() {
return 'MonsterExtra{d0: $d0, d1: $d1, d2: $d2, d3: $d3, f0: $f0, f1: $f1, f2: $f2, f3: $f3, dvec: $dvec, fvec: $fvec}';
}
+
+ MonsterExtraT unpack() => MonsterExtraT(
+ d0: d0,
+ d1: d1,
+ d2: d2,
+ d3: d3,
+ f0: f0,
+ f1: f1,
+ f2: f2,
+ f3: f3,
+ dvec: const fb.ListReader<double>(fb.Float64Reader(), lazy: false).vTableGetNullable(_bc, _bcOffset, 20),
+ fvec: const fb.ListReader<double>(fb.Float32Reader(), lazy: false).vTableGetNullable(_bc, _bcOffset, 22));
+
+ static int pack(fb.Builder fbBuilder, MonsterExtraT? object) {
+ if (object == null) return 0;
+ return object.pack(fbBuilder);
+ }
+}
+
+class MonsterExtraT implements fb.Packable {
+ double d0;
+ double d1;
+ double d2;
+ double d3;
+ double f0;
+ double f1;
+ double f2;
+ double f3;
+ List<double>? dvec;
+ List<double>? fvec;
+
+ MonsterExtraT({
+ this.d0 = double.nan,
+ this.d1 = double.nan,
+ this.d2 = double.infinity,
+ this.d3 = double.negativeInfinity,
+ this.f0 = double.nan,
+ this.f1 = double.nan,
+ this.f2 = double.infinity,
+ this.f3 = double.negativeInfinity,
+ this.dvec,
+ this.fvec});
+
+ @override
+ int pack(fb.Builder fbBuilder) {
+ final int? dvecOffset = dvec == null ? null
+ : fbBuilder.writeListFloat64(dvec!);
+ final int? fvecOffset = fvec == null ? null
+ : fbBuilder.writeListFloat32(fvec!);
+ fbBuilder.startTable(11);
+ fbBuilder.addFloat64(0, d0);
+ fbBuilder.addFloat64(1, d1);
+ fbBuilder.addFloat64(2, d2);
+ fbBuilder.addFloat64(3, d3);
+ fbBuilder.addFloat32(4, f0);
+ fbBuilder.addFloat32(5, f1);
+ fbBuilder.addFloat32(6, f2);
+ fbBuilder.addFloat32(7, f3);
+ fbBuilder.addOffset(8, dvecOffset);
+ fbBuilder.addOffset(9, fvecOffset);
+ return fbBuilder.endTable();
+ }
+
+ @override
+ String toString() {
+ return 'MonsterExtraT{d0: $d0, d1: $d1, d2: $d2, d3: $d3, f0: $f0, f1: $f1, f2: $f2, f3: $f3, dvec: $dvec, fvec: $fvec}';
+ }
}
class _MonsterExtraReader extends fb.TableReader<MonsterExtra> {
@@ -41,57 +108,55 @@
@override
MonsterExtra createObject(fb.BufferContext bc, int offset) =>
- new MonsterExtra._(bc, offset);
+ MonsterExtra._(bc, offset);
}
class MonsterExtraBuilder {
- MonsterExtraBuilder(this.fbBuilder) {
- assert(fbBuilder != null);
- }
+ MonsterExtraBuilder(this.fbBuilder);
final fb.Builder fbBuilder;
void begin() {
- fbBuilder.startTable();
+ fbBuilder.startTable(11);
}
- int addD0(double d0) {
+ int addD0(double? d0) {
fbBuilder.addFloat64(0, d0);
return fbBuilder.offset;
}
- int addD1(double d1) {
+ int addD1(double? d1) {
fbBuilder.addFloat64(1, d1);
return fbBuilder.offset;
}
- int addD2(double d2) {
+ int addD2(double? d2) {
fbBuilder.addFloat64(2, d2);
return fbBuilder.offset;
}
- int addD3(double d3) {
+ int addD3(double? d3) {
fbBuilder.addFloat64(3, d3);
return fbBuilder.offset;
}
- int addF0(double f0) {
+ int addF0(double? f0) {
fbBuilder.addFloat32(4, f0);
return fbBuilder.offset;
}
- int addF1(double f1) {
+ int addF1(double? f1) {
fbBuilder.addFloat32(5, f1);
return fbBuilder.offset;
}
- int addF2(double f2) {
+ int addF2(double? f2) {
fbBuilder.addFloat32(6, f2);
return fbBuilder.offset;
}
- int addF3(double f3) {
+ int addF3(double? f3) {
fbBuilder.addFloat32(7, f3);
return fbBuilder.offset;
}
- int addDvecOffset(int offset) {
+ int addDvecOffset(int? offset) {
fbBuilder.addOffset(8, offset);
return fbBuilder.offset;
}
- int addFvecOffset(int offset) {
+ int addFvecOffset(int? offset) {
fbBuilder.addOffset(9, offset);
return fbBuilder.offset;
}
@@ -102,28 +167,28 @@
}
class MonsterExtraObjectBuilder extends fb.ObjectBuilder {
- final double _d0;
- final double _d1;
- final double _d2;
- final double _d3;
- final double _f0;
- final double _f1;
- final double _f2;
- final double _f3;
- final List<double> _dvec;
- final List<double> _fvec;
+ final double? _d0;
+ final double? _d1;
+ final double? _d2;
+ final double? _d3;
+ final double? _f0;
+ final double? _f1;
+ final double? _f2;
+ final double? _f3;
+ final List<double>? _dvec;
+ final List<double>? _fvec;
MonsterExtraObjectBuilder({
- double d0,
- double d1,
- double d2,
- double d3,
- double f0,
- double f1,
- double f2,
- double f3,
- List<double> dvec,
- List<double> fvec,
+ double? d0,
+ double? d1,
+ double? d2,
+ double? d3,
+ double? f0,
+ double? f1,
+ double? f2,
+ double? f3,
+ List<double>? dvec,
+ List<double>? fvec,
})
: _d0 = d0,
_d1 = d1,
@@ -138,17 +203,12 @@
/// Finish building, and store into the [fbBuilder].
@override
- int finish(
- fb.Builder fbBuilder) {
- assert(fbBuilder != null);
- final int dvecOffset = _dvec?.isNotEmpty == true
- ? fbBuilder.writeListFloat64(_dvec)
- : null;
- final int fvecOffset = _fvec?.isNotEmpty == true
- ? fbBuilder.writeListFloat32(_fvec)
- : null;
-
- fbBuilder.startTable();
+ int finish(fb.Builder fbBuilder) {
+ final int? dvecOffset = _dvec == null ? null
+ : fbBuilder.writeListFloat64(_dvec!);
+ final int? fvecOffset = _fvec == null ? null
+ : fbBuilder.writeListFloat32(_fvec!);
+ fbBuilder.startTable(11);
fbBuilder.addFloat64(0, _d0);
fbBuilder.addFloat64(1, _d1);
fbBuilder.addFloat64(2, _d2);
@@ -157,20 +217,16 @@
fbBuilder.addFloat32(5, _f1);
fbBuilder.addFloat32(6, _f2);
fbBuilder.addFloat32(7, _f3);
- if (dvecOffset != null) {
- fbBuilder.addOffset(8, dvecOffset);
- }
- if (fvecOffset != null) {
- fbBuilder.addOffset(9, fvecOffset);
- }
+ fbBuilder.addOffset(8, dvecOffset);
+ fbBuilder.addOffset(9, fvecOffset);
return fbBuilder.endTable();
}
/// Convenience method to serialize to byte list.
@override
- Uint8List toBytes([String fileIdentifier]) {
- fb.Builder fbBuilder = new fb.Builder();
- int offset = finish(fbBuilder);
- return fbBuilder.finish(offset, fileIdentifier);
+ Uint8List toBytes([String? fileIdentifier]) {
+ final fbBuilder = fb.Builder(deduplicateTables: false);
+ fbBuilder.finish(finish(fbBuilder), fileIdentifier);
+ return fbBuilder.buffer;
}
}
diff --git a/tests/monster_test.bfbs b/tests/monster_test.bfbs
index dc672d8..0eb130a 100644
--- a/tests/monster_test.bfbs
+++ b/tests/monster_test.bfbs
Binary files differ
diff --git a/tests/monster_test.fbs b/tests/monster_test.fbs
index dde5137..b28ddc8 100644
--- a/tests/monster_test.fbs
+++ b/tests/monster_test.fbs
@@ -31,6 +31,14 @@
Elf,
}
+enum LongEnum:ulong (bit_flags) {
+ LongOne = 1,
+ LongTwo = 2,
+ // Because this is a bitflag, 40 will be out of range of a 32-bit integer,
+ // allowing us to exercise any logic special to big numbers.
+ LongBig = 40,
+}
+
union Any { Monster, TestSimpleTableWithEnum, MyGame.Example2.Monster }
union AnyUniqueAliases { M: Monster, TS: TestSimpleTableWithEnum, M2: MyGame.Example2.Monster }
@@ -56,10 +64,16 @@
distance:uint;
}
+struct StructOfStructs {
+ a: Ability;
+ b: Test;
+ c: Ability;
+}
+
table Stat {
id:string;
val:long;
- count:ushort;
+ count:ushort (key);
}
table Referrable {
@@ -71,7 +85,7 @@
pos:Vec3 (id: 0);
hp:short = 100 (id: 2);
mana:short = 150 (id: 1);
- name:string (id: 3, required, key);
+ name:string (id: 3, key);
color:Color = Blue (id: 6);
inventory:[ubyte] (id: 5);
friendly:bool = false (deprecated, priority: 1, id: 4);
@@ -117,6 +131,12 @@
vector_of_enums:[Color] (id:47);
signed_enum:Race = None (id:48);
testrequirednestedflatbuffer:[ubyte] (id:49, nested_flatbuffer: "Monster");
+ scalar_key_sorted_tables:[Stat] (id: 50);
+ native_inline:Test (id: 51, native_inline);
+ // The default value of this enum will be a numeric zero, which isn't a valid
+ // enum value.
+ long_enum_non_enum_default:LongEnum (id: 52);
+ long_enum_normal_default:LongEnum = LongOne (id: 53);
}
table TypeAliases {
diff --git a/tests/monster_test.grpc.fb.cc b/tests/monster_test.grpc.fb.cc
index f83e604..f3ac136 100644
--- a/tests/monster_test.grpc.fb.cc
+++ b/tests/monster_test.grpc.fb.cc
@@ -5,14 +5,14 @@
#include "monster_test_generated.h"
#include "monster_test.grpc.fb.h"
-#include <grpc++/impl/codegen/async_stream.h>
-#include <grpc++/impl/codegen/async_unary_call.h>
-#include <grpc++/impl/codegen/channel_interface.h>
-#include <grpc++/impl/codegen/client_unary_call.h>
-#include <grpc++/impl/codegen/method_handler_impl.h>
-#include <grpc++/impl/codegen/rpc_service_method.h>
-#include <grpc++/impl/codegen/service_type.h>
-#include <grpc++/impl/codegen/sync_stream.h>
+#include <grpcpp/impl/codegen/async_stream.h>
+#include <grpcpp/impl/codegen/async_unary_call.h>
+#include <grpcpp/impl/codegen/channel_interface.h>
+#include <grpcpp/impl/codegen/client_unary_call.h>
+#include <grpcpp/impl/codegen/method_handler.h>
+#include <grpcpp/impl/codegen/rpc_service_method.h>
+#include <grpcpp/impl/codegen/service_type.h>
+#include <grpcpp/impl/codegen/sync_stream.h>
namespace MyGame {
namespace Example {
@@ -23,7 +23,7 @@
"/MyGame.Example.MonsterStorage/GetMinMaxHitPoints",
};
-std::unique_ptr< MonsterStorage::Stub> MonsterStorage::NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel, const ::grpc::StubOptions& options) {
+std::unique_ptr< MonsterStorage::Stub> MonsterStorage::NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel, const ::grpc::StubOptions& /*options*/) {
std::unique_ptr< MonsterStorage::Stub> stub(new MonsterStorage::Stub(channel));
return stub;
}
@@ -109,30 +109,19 @@
MonsterStorage::Service::~Service() {
}
-::grpc::Status MonsterStorage::Service::Store(::grpc::ServerContext* context, const flatbuffers::grpc::Message<Monster>* request, flatbuffers::grpc::Message<Stat>* response) {
- (void) context;
- (void) request;
- (void) response;
+::grpc::Status MonsterStorage::Service::Store(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message<Monster>* /*request*/, flatbuffers::grpc::Message<Stat>* /*response*/) {
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
-::grpc::Status MonsterStorage::Service::Retrieve(::grpc::ServerContext* context, const flatbuffers::grpc::Message<Stat>* request, ::grpc::ServerWriter< flatbuffers::grpc::Message<Monster>>* writer) {
- (void) context;
- (void) request;
- (void) writer;
+::grpc::Status MonsterStorage::Service::Retrieve(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message<Stat>* /*request*/, ::grpc::ServerWriter< flatbuffers::grpc::Message<Monster>>* /*writer*/) {
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
-::grpc::Status MonsterStorage::Service::GetMaxHitPoint(::grpc::ServerContext* context, ::grpc::ServerReader< flatbuffers::grpc::Message<Monster>>* reader, flatbuffers::grpc::Message<Stat>* response) {
- (void) context;
- (void) reader;
- (void) response;
+::grpc::Status MonsterStorage::Service::GetMaxHitPoint(::grpc::ServerContext* /*context*/, ::grpc::ServerReader< flatbuffers::grpc::Message<Monster>>* /*reader*/, flatbuffers::grpc::Message<Stat>* /*response*/) {
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
-::grpc::Status MonsterStorage::Service::GetMinMaxHitPoints(::grpc::ServerContext* context, ::grpc::ServerReaderWriter< flatbuffers::grpc::Message<Stat>, flatbuffers::grpc::Message<Monster>>* stream) {
- (void) context;
- (void) stream;
+::grpc::Status MonsterStorage::Service::GetMinMaxHitPoints(::grpc::ServerContext* /*context*/, ::grpc::ServerReaderWriter< flatbuffers::grpc::Message<Stat>, flatbuffers::grpc::Message<Monster>>* /*stream*/) {
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
diff --git a/tests/monster_test.grpc.fb.h b/tests/monster_test.grpc.fb.h
index 72402ec..4d726e1 100644
--- a/tests/monster_test.grpc.fb.h
+++ b/tests/monster_test.grpc.fb.h
@@ -7,15 +7,15 @@
#include "monster_test_generated.h"
#include "flatbuffers/grpc.h"
-#include <grpc++/impl/codegen/async_stream.h>
-#include <grpc++/impl/codegen/async_unary_call.h>
-#include <grpc++/impl/codegen/method_handler_impl.h>
-#include <grpc++/impl/codegen/proto_utils.h>
-#include <grpc++/impl/codegen/rpc_method.h>
-#include <grpc++/impl/codegen/service_type.h>
-#include <grpc++/impl/codegen/status.h>
-#include <grpc++/impl/codegen/stub_options.h>
-#include <grpc++/impl/codegen/sync_stream.h>
+#include <grpcpp/impl/codegen/async_stream.h>
+#include <grpcpp/impl/codegen/async_unary_call.h>
+#include <grpcpp/impl/codegen/method_handler.h>
+#include <grpcpp/impl/codegen/proto_utils.h>
+#include <grpcpp/impl/codegen/rpc_method.h>
+#include <grpcpp/impl/codegen/service_type.h>
+#include <grpcpp/impl/codegen/status.h>
+#include <grpcpp/impl/codegen/stub_options.h>
+#include <grpcpp/impl/codegen/sync_stream.h>
namespace grpc {
class CompletionQueue;
@@ -152,7 +152,7 @@
template <class BaseClass>
class WithAsyncMethod_Store : public BaseClass {
private:
- void BaseClassMustBeDerivedFromService(const Service *service) {}
+ void BaseClassMustBeDerivedFromService(const Service */*service*/) {}
public:
WithAsyncMethod_Store() {
::grpc::Service::MarkMethodAsync(0);
@@ -161,7 +161,7 @@
BaseClassMustBeDerivedFromService(this);
}
// disable synchronous version of this method
- ::grpc::Status Store(::grpc::ServerContext* context, const flatbuffers::grpc::Message<Monster>* request, flatbuffers::grpc::Message<Stat>* response) final override {
+ ::grpc::Status Store(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message<Monster>* /*request*/, flatbuffers::grpc::Message<Stat>* /*response*/) final override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
@@ -172,7 +172,7 @@
template <class BaseClass>
class WithAsyncMethod_Retrieve : public BaseClass {
private:
- void BaseClassMustBeDerivedFromService(const Service *service) {}
+ void BaseClassMustBeDerivedFromService(const Service */*service*/) {}
public:
WithAsyncMethod_Retrieve() {
::grpc::Service::MarkMethodAsync(1);
@@ -181,7 +181,7 @@
BaseClassMustBeDerivedFromService(this);
}
// disable synchronous version of this method
- ::grpc::Status Retrieve(::grpc::ServerContext* context, const flatbuffers::grpc::Message<Stat>* request, ::grpc::ServerWriter< flatbuffers::grpc::Message<Monster>>* writer) final override {
+ ::grpc::Status Retrieve(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message<Stat>* /*request*/, ::grpc::ServerWriter< flatbuffers::grpc::Message<Monster>>* /*writer*/) final override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
@@ -192,7 +192,7 @@
template <class BaseClass>
class WithAsyncMethod_GetMaxHitPoint : public BaseClass {
private:
- void BaseClassMustBeDerivedFromService(const Service *service) {}
+ void BaseClassMustBeDerivedFromService(const Service */*service*/) {}
public:
WithAsyncMethod_GetMaxHitPoint() {
::grpc::Service::MarkMethodAsync(2);
@@ -201,7 +201,7 @@
BaseClassMustBeDerivedFromService(this);
}
// disable synchronous version of this method
- ::grpc::Status GetMaxHitPoint(::grpc::ServerContext* context, ::grpc::ServerReader< flatbuffers::grpc::Message<Monster>>* reader, flatbuffers::grpc::Message<Stat>* response) final override {
+ ::grpc::Status GetMaxHitPoint(::grpc::ServerContext* /*context*/, ::grpc::ServerReader< flatbuffers::grpc::Message<Monster>>* /*reader*/, flatbuffers::grpc::Message<Stat>* response) final override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
@@ -212,7 +212,7 @@
template <class BaseClass>
class WithAsyncMethod_GetMinMaxHitPoints : public BaseClass {
private:
- void BaseClassMustBeDerivedFromService(const Service *service) {}
+ void BaseClassMustBeDerivedFromService(const Service */*service*/) {}
public:
WithAsyncMethod_GetMinMaxHitPoints() {
::grpc::Service::MarkMethodAsync(3);
@@ -221,7 +221,7 @@
BaseClassMustBeDerivedFromService(this);
}
// disable synchronous version of this method
- ::grpc::Status GetMinMaxHitPoints(::grpc::ServerContext* context, ::grpc::ServerReaderWriter< flatbuffers::grpc::Message<Stat>, flatbuffers::grpc::Message<Monster>>* stream) final override {
+ ::grpc::Status GetMinMaxHitPoints(::grpc::ServerContext* /*context*/, ::grpc::ServerReaderWriter< flatbuffers::grpc::Message<Stat>, flatbuffers::grpc::Message<Monster>>* /*stream*/) final override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
@@ -233,7 +233,7 @@
template <class BaseClass>
class WithGenericMethod_Store : public BaseClass {
private:
- void BaseClassMustBeDerivedFromService(const Service *service) {}
+ void BaseClassMustBeDerivedFromService(const Service */*service*/) {}
public:
WithGenericMethod_Store() {
::grpc::Service::MarkMethodGeneric(0);
@@ -242,7 +242,7 @@
BaseClassMustBeDerivedFromService(this);
}
// disable synchronous version of this method
- ::grpc::Status Store(::grpc::ServerContext* context, const flatbuffers::grpc::Message<Monster>* request, flatbuffers::grpc::Message<Stat>* response) final override {
+ ::grpc::Status Store(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message<Monster>* /*request*/, flatbuffers::grpc::Message<Stat>* /*response*/) final override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
@@ -250,7 +250,7 @@
template <class BaseClass>
class WithGenericMethod_Retrieve : public BaseClass {
private:
- void BaseClassMustBeDerivedFromService(const Service *service) {}
+ void BaseClassMustBeDerivedFromService(const Service */*service*/) {}
public:
WithGenericMethod_Retrieve() {
::grpc::Service::MarkMethodGeneric(1);
@@ -259,7 +259,7 @@
BaseClassMustBeDerivedFromService(this);
}
// disable synchronous version of this method
- ::grpc::Status Retrieve(::grpc::ServerContext* context, const flatbuffers::grpc::Message<Stat>* request, ::grpc::ServerWriter< flatbuffers::grpc::Message<Monster>>* writer) final override {
+ ::grpc::Status Retrieve(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message<Stat>* /*request*/, ::grpc::ServerWriter< flatbuffers::grpc::Message<Monster>>* /*writer*/) final override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
@@ -267,7 +267,7 @@
template <class BaseClass>
class WithGenericMethod_GetMaxHitPoint : public BaseClass {
private:
- void BaseClassMustBeDerivedFromService(const Service *service) {}
+ void BaseClassMustBeDerivedFromService(const Service */*service*/) {}
public:
WithGenericMethod_GetMaxHitPoint() {
::grpc::Service::MarkMethodGeneric(2);
@@ -276,7 +276,7 @@
BaseClassMustBeDerivedFromService(this);
}
// disable synchronous version of this method
- ::grpc::Status GetMaxHitPoint(::grpc::ServerContext* context, ::grpc::ServerReader< flatbuffers::grpc::Message<Monster>>* reader, flatbuffers::grpc::Message<Stat>* response) final override {
+ ::grpc::Status GetMaxHitPoint(::grpc::ServerContext* /*context*/, ::grpc::ServerReader< flatbuffers::grpc::Message<Monster>>* /*reader*/, flatbuffers::grpc::Message<Stat>* /*response*/) final override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
@@ -284,7 +284,7 @@
template <class BaseClass>
class WithGenericMethod_GetMinMaxHitPoints : public BaseClass {
private:
- void BaseClassMustBeDerivedFromService(const Service *service) {}
+ void BaseClassMustBeDerivedFromService(const Service */*service*/) {}
public:
WithGenericMethod_GetMinMaxHitPoints() {
::grpc::Service::MarkMethodGeneric(3);
@@ -293,7 +293,7 @@
BaseClassMustBeDerivedFromService(this);
}
// disable synchronous version of this method
- ::grpc::Status GetMinMaxHitPoints(::grpc::ServerContext* context, ::grpc::ServerReaderWriter< flatbuffers::grpc::Message<Stat>, flatbuffers::grpc::Message<Monster>>* stream) final override {
+ ::grpc::Status GetMinMaxHitPoints(::grpc::ServerContext* /*context*/, ::grpc::ServerReaderWriter< flatbuffers::grpc::Message<Stat>, flatbuffers::grpc::Message<Monster>>* /*stream*/) final override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
@@ -301,7 +301,7 @@
template <class BaseClass>
class WithStreamedUnaryMethod_Store : public BaseClass {
private:
- void BaseClassMustBeDerivedFromService(const Service *service) {}
+ void BaseClassMustBeDerivedFromService(const Service */*service*/) {}
public:
WithStreamedUnaryMethod_Store() {
::grpc::Service::MarkMethodStreamed(0,
@@ -311,7 +311,7 @@
BaseClassMustBeDerivedFromService(this);
}
// disable regular version of this method
- ::grpc::Status Store(::grpc::ServerContext* context, const flatbuffers::grpc::Message<Monster>* request, flatbuffers::grpc::Message<Stat>* response) final override {
+ ::grpc::Status Store(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message<Monster>* /*request*/, flatbuffers::grpc::Message<Stat>* /*response*/) final override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
@@ -322,7 +322,7 @@
template <class BaseClass>
class WithSplitStreamingMethod_Retrieve : public BaseClass {
private:
- void BaseClassMustBeDerivedFromService(const Service *service) {}
+ void BaseClassMustBeDerivedFromService(const Service */*service*/) { }
public:
WithSplitStreamingMethod_Retrieve() {
::grpc::Service::MarkMethodStreamed(1,
@@ -332,7 +332,7 @@
BaseClassMustBeDerivedFromService(this);
}
// disable regular version of this method
- ::grpc::Status Retrieve(::grpc::ServerContext* context, const flatbuffers::grpc::Message<Stat>* request, ::grpc::ServerWriter< flatbuffers::grpc::Message<Monster>>* writer) final override {
+ ::grpc::Status Retrieve(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message<Stat>* /*request*/, ::grpc::ServerWriter< flatbuffers::grpc::Message<Monster>>* /*writer*/) final override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
diff --git a/tests/monster_test.js b/tests/monster_test.js
new file mode 100644
index 0000000..b4e13d1
--- /dev/null
+++ b/tests/monster_test.js
@@ -0,0 +1,16 @@
+export { Monster as MyGameExample2Monster, MonsterT as MyGameExample2MonsterT } from './my-game/example2/monster';
+export { Ability, AbilityT } from './my-game/example/ability';
+export { Any, unionToAny, unionListToAny } from './my-game/example/any';
+export { AnyAmbiguousAliases, unionToAnyAmbiguousAliases, unionListToAnyAmbiguousAliases } from './my-game/example/any-ambiguous-aliases';
+export { AnyUniqueAliases, unionToAnyUniqueAliases, unionListToAnyUniqueAliases } from './my-game/example/any-unique-aliases';
+export { Color } from './my-game/example/color';
+export { Monster, MonsterT } from './my-game/example/monster';
+export { Race } from './my-game/example/race';
+export { Referrable, ReferrableT } from './my-game/example/referrable';
+export { Stat, StatT } from './my-game/example/stat';
+export { StructOfStructs, StructOfStructsT } from './my-game/example/struct-of-structs';
+export { Test, TestT } from './my-game/example/test';
+export { TestSimpleTableWithEnum, TestSimpleTableWithEnumT } from './my-game/example/test-simple-table-with-enum';
+export { TypeAliases, TypeAliasesT } from './my-game/example/type-aliases';
+export { Vec3, Vec3T } from './my-game/example/vec3';
+export { InParentNamespace, InParentNamespaceT } from './my-game/in-parent-namespace';
diff --git a/tests/monster_test.schema.json b/tests/monster_test.schema.json
index 3fe7a5f..7517269 100644
--- a/tests/monster_test.schema.json
+++ b/tests/monster_test.schema.json
@@ -13,6 +13,10 @@
"type" : "string",
"enum": ["None", "Human", "Dwarf", "Elf"]
},
+ "MyGame_Example_LongEnum" : {
+ "type" : "string",
+ "enum": ["LongOne", "LongTwo", "LongBig"]
+ },
"MyGame_Example_Any" : {
"type" : "string",
"enum": ["NONE", "Monster", "TestSimpleTableWithEnum", "MyGame_Example2_Monster"]
@@ -71,7 +75,7 @@
"type" : "integer", "minimum" : -32768, "maximum" : 32767
},
"b" : {
- "type" : "integer", "minimum" : -128, "maximum" : 127"
+ "type" : "integer", "minimum" : -128, "maximum" : 127
}
},
"additionalProperties" : false
@@ -121,6 +125,21 @@
},
"additionalProperties" : false
},
+ "MyGame_Example_StructOfStructs" : {
+ "type" : "object",
+ "properties" : {
+ "a" : {
+ "$ref" : "#/definitions/MyGame_Example_Ability"
+ },
+ "b" : {
+ "$ref" : "#/definitions/MyGame_Example_Test"
+ },
+ "c" : {
+ "$ref" : "#/definitions/MyGame_Example_Ability"
+ }
+ },
+ "additionalProperties" : false
+ },
"MyGame_Example_Stat" : {
"type" : "object",
"properties" : {
@@ -147,7 +166,7 @@
},
"MyGame_Example_Monster" : {
"type" : "object",
- "description" : " an example documentation comment: \"monster object\"",
+ "description" : "an example documentation comment: \"monster object\"",
"properties" : {
"pos" : {
"$ref" : "#/definitions/MyGame_Example_Vec3"
@@ -163,10 +182,10 @@
},
"friendly" : {
"type" : "boolean",
- "deprecated" : true,
+ "deprecated" : true
},
"inventory" : {
- "type" : "array", "items" : {"type" : "integer", "minimum" : 0, "maximum" :255"}
+ "type" : "array", "items" : {"type" : "integer", "minimum" : 0, "maximum" :255}
},
"color" : {
"$ref" : "#/definitions/MyGame_Example_Color"
@@ -184,13 +203,14 @@
"type" : "array", "items" : {"type" : "string"}
},
"testarrayoftables" : {
- "type" : "array", "items" : {"$ref" : "#/definitions/MyGame_Example_Monster"}
+ "type" : "array", "items" : {"$ref" : "#/definitions/MyGame_Example_Monster"},
+ "description" : "an example documentation comment: this will end up in the generated code\nmultiline too"
},
"enemy" : {
"$ref" : "#/definitions/MyGame_Example_Monster"
},
"testnestedflatbuffer" : {
- "type" : "array", "items" : {"type" : "integer", "minimum" : 0, "maximum" :255"}
+ "type" : "array", "items" : {"type" : "integer", "minimum" : 0, "maximum" :255}
},
"testempty" : {
"$ref" : "#/definitions/MyGame_Example_Stat"
@@ -241,7 +261,7 @@
"type" : "array", "items" : {"$ref" : "#/definitions/MyGame_Example_Ability"}
},
"flex" : {
- "type" : "array", "items" : {"type" : "integer", "minimum" : 0, "maximum" :255"}
+ "type" : "array", "items" : {"type" : "integer", "minimum" : 0, "maximum" :255}
},
"test5" : {
"type" : "array", "items" : {"$ref" : "#/definitions/MyGame_Example_Test"}
@@ -298,7 +318,19 @@
"$ref" : "#/definitions/MyGame_Example_Race"
},
"testrequirednestedflatbuffer" : {
- "type" : "array", "items" : {"type" : "integer", "minimum" : 0, "maximum" :255"}
+ "type" : "array", "items" : {"type" : "integer", "minimum" : 0, "maximum" :255}
+ },
+ "scalar_key_sorted_tables" : {
+ "type" : "array", "items" : {"$ref" : "#/definitions/MyGame_Example_Stat"}
+ },
+ "native_inline" : {
+ "$ref" : "#/definitions/MyGame_Example_Test"
+ },
+ "long_enum_non_enum_default" : {
+ "$ref" : "#/definitions/MyGame_Example_LongEnum"
+ },
+ "long_enum_normal_default" : {
+ "$ref" : "#/definitions/MyGame_Example_LongEnum"
}
},
"required" : ["name"],
@@ -308,10 +340,10 @@
"type" : "object",
"properties" : {
"i8" : {
- "type" : "integer", "minimum" : -128, "maximum" : 127"
+ "type" : "integer", "minimum" : -128, "maximum" : 127
},
"u8" : {
- "type" : "integer", "minimum" : 0, "maximum" :255"
+ "type" : "integer", "minimum" : 0, "maximum" :255
},
"i16" : {
"type" : "integer", "minimum" : -32768, "maximum" : 32767
@@ -338,7 +370,7 @@
"type" : "number"
},
"v8" : {
- "type" : "array", "items" : {"type" : "integer", "minimum" : -128, "maximum" : 127"}
+ "type" : "array", "items" : {"type" : "integer", "minimum" : -128, "maximum" : 127}
},
"vf64" : {
"type" : "array", "items" : {"type" : "number"}
diff --git a/tests/monster_test.ts b/tests/monster_test.ts
new file mode 100644
index 0000000..b4e13d1
--- /dev/null
+++ b/tests/monster_test.ts
@@ -0,0 +1,16 @@
+export { Monster as MyGameExample2Monster, MonsterT as MyGameExample2MonsterT } from './my-game/example2/monster';
+export { Ability, AbilityT } from './my-game/example/ability';
+export { Any, unionToAny, unionListToAny } from './my-game/example/any';
+export { AnyAmbiguousAliases, unionToAnyAmbiguousAliases, unionListToAnyAmbiguousAliases } from './my-game/example/any-ambiguous-aliases';
+export { AnyUniqueAliases, unionToAnyUniqueAliases, unionListToAnyUniqueAliases } from './my-game/example/any-unique-aliases';
+export { Color } from './my-game/example/color';
+export { Monster, MonsterT } from './my-game/example/monster';
+export { Race } from './my-game/example/race';
+export { Referrable, ReferrableT } from './my-game/example/referrable';
+export { Stat, StatT } from './my-game/example/stat';
+export { StructOfStructs, StructOfStructsT } from './my-game/example/struct-of-structs';
+export { Test, TestT } from './my-game/example/test';
+export { TestSimpleTableWithEnum, TestSimpleTableWithEnumT } from './my-game/example/test-simple-table-with-enum';
+export { TypeAliases, TypeAliasesT } from './my-game/example/type-aliases';
+export { Vec3, Vec3T } from './my-game/example/vec3';
+export { InParentNamespace, InParentNamespaceT } from './my-game/in-parent-namespace';
diff --git a/tests/monster_test/mod.rs b/tests/monster_test/mod.rs
new file mode 100644
index 0000000..fdbc26b
--- /dev/null
+++ b/tests/monster_test/mod.rs
@@ -0,0 +1,55 @@
+// Automatically generated by the Flatbuffers compiler. Do not modify.
+pub mod my_game {
+ use super::*;
+ pub mod example {
+ use super::*;
+ mod color_generated;
+ pub use self::color_generated::*;
+ mod race_generated;
+ pub use self::race_generated::*;
+ mod long_enum_generated;
+ pub use self::long_enum_generated::*;
+ mod any_generated;
+ pub use self::any_generated::*;
+ mod any_unique_aliases_generated;
+ pub use self::any_unique_aliases_generated::*;
+ mod any_ambiguous_aliases_generated;
+ pub use self::any_ambiguous_aliases_generated::*;
+ mod test_generated;
+ pub use self::test_generated::*;
+ mod test_simple_table_with_enum_generated;
+ pub use self::test_simple_table_with_enum_generated::*;
+ mod vec_3_generated;
+ pub use self::vec_3_generated::*;
+ mod ability_generated;
+ pub use self::ability_generated::*;
+ mod struct_of_structs_generated;
+ pub use self::struct_of_structs_generated::*;
+ mod stat_generated;
+ pub use self::stat_generated::*;
+ mod referrable_generated;
+ pub use self::referrable_generated::*;
+ mod monster_generated;
+ pub use self::monster_generated::*;
+ mod type_aliases_generated;
+ pub use self::type_aliases_generated::*;
+ } // example
+ pub mod example_2 {
+ use super::*;
+ mod monster_generated;
+ pub use self::monster_generated::*;
+ } // example_2
+ pub mod other_name_space {
+ use super::*;
+ mod from_include_generated;
+ pub use self::from_include_generated::*;
+ mod unused_generated;
+ pub use self::unused_generated::*;
+ mod table_b_generated;
+ pub use self::table_b_generated::*;
+ } // other_name_space
+ mod in_parent_namespace_generated;
+ pub use self::in_parent_namespace_generated::*;
+} // my_game
+mod table_a_generated;
+pub use self::table_a_generated::*;
diff --git a/tests/monster_test/my_game/example/ability_generated.rs b/tests/monster_test/my_game/example/ability_generated.rs
new file mode 100644
index 0000000..5746e8e
--- /dev/null
+++ b/tests/monster_test/my_game/example/ability_generated.rs
@@ -0,0 +1,166 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+// struct Ability, aligned to 4
+#[repr(transparent)]
+#[derive(Clone, Copy, PartialEq)]
+pub struct Ability(pub [u8; 8]);
+impl Default for Ability {
+ fn default() -> Self {
+ Self([0; 8])
+ }
+}
+impl std::fmt::Debug for Ability {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ f.debug_struct("Ability")
+ .field("id", &self.id())
+ .field("distance", &self.distance())
+ .finish()
+ }
+}
+
+impl flatbuffers::SimpleToVerifyInSlice for Ability {}
+impl flatbuffers::SafeSliceAccess for Ability {}
+impl<'a> flatbuffers::Follow<'a> for Ability {
+ type Inner = &'a Ability;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ <&'a Ability>::follow(buf, loc)
+ }
+}
+impl<'a> flatbuffers::Follow<'a> for &'a Ability {
+ type Inner = &'a Ability;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ flatbuffers::follow_cast_ref::<Ability>(buf, loc)
+ }
+}
+impl<'b> flatbuffers::Push for Ability {
+ type Output = Ability;
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ let src = unsafe {
+ ::std::slice::from_raw_parts(self as *const Ability as *const u8, Self::size())
+ };
+ dst.copy_from_slice(src);
+ }
+}
+impl<'b> flatbuffers::Push for &'b Ability {
+ type Output = Ability;
+
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ let src = unsafe {
+ ::std::slice::from_raw_parts(*self as *const Ability as *const u8, Self::size())
+ };
+ dst.copy_from_slice(src);
+ }
+}
+
+impl<'a> flatbuffers::Verifiable for Ability {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ v.in_buffer::<Self>(pos)
+ }
+}
+
+impl<'a> Ability {
+ #[allow(clippy::too_many_arguments)]
+ pub fn new(
+ id: u32,
+ distance: u32,
+ ) -> Self {
+ let mut s = Self([0; 8]);
+ s.set_id(id);
+ s.set_distance(distance);
+ s
+ }
+
+ pub const fn get_fully_qualified_name() -> &'static str {
+ "MyGame.Example.Ability"
+ }
+
+ pub fn id(&self) -> u32 {
+ let mut mem = core::mem::MaybeUninit::<u32>::uninit();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ self.0[0..].as_ptr(),
+ mem.as_mut_ptr() as *mut u8,
+ core::mem::size_of::<u32>(),
+ );
+ mem.assume_init()
+ }.from_little_endian()
+ }
+
+ pub fn set_id(&mut self, x: u32) {
+ let x_le = x.to_little_endian();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ &x_le as *const u32 as *const u8,
+ self.0[0..].as_mut_ptr(),
+ core::mem::size_of::<u32>(),
+ );
+ }
+ }
+
+ #[inline]
+ pub fn key_compare_less_than(&self, o: &Ability) -> bool {
+ self.id() < o.id()
+ }
+
+ #[inline]
+ pub fn key_compare_with_value(&self, val: u32) -> ::std::cmp::Ordering {
+ let key = self.id();
+ key.cmp(&val)
+ }
+ pub fn distance(&self) -> u32 {
+ let mut mem = core::mem::MaybeUninit::<u32>::uninit();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ self.0[4..].as_ptr(),
+ mem.as_mut_ptr() as *mut u8,
+ core::mem::size_of::<u32>(),
+ );
+ mem.assume_init()
+ }.from_little_endian()
+ }
+
+ pub fn set_distance(&mut self, x: u32) {
+ let x_le = x.to_little_endian();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ &x_le as *const u32 as *const u8,
+ self.0[4..].as_mut_ptr(),
+ core::mem::size_of::<u32>(),
+ );
+ }
+ }
+
+ pub fn unpack(&self) -> AbilityT {
+ AbilityT {
+ id: self.id(),
+ distance: self.distance(),
+ }
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Default)]
+pub struct AbilityT {
+ pub id: u32,
+ pub distance: u32,
+}
+impl AbilityT {
+ pub fn pack(&self) -> Ability {
+ Ability::new(
+ self.id,
+ self.distance,
+ )
+ }
+}
+
diff --git a/tests/monster_test/my_game/example/any_ambiguous_aliases_generated.rs b/tests/monster_test/my_game/example/any_ambiguous_aliases_generated.rs
new file mode 100644
index 0000000..321007a
--- /dev/null
+++ b/tests/monster_test/my_game/example/any_ambiguous_aliases_generated.rs
@@ -0,0 +1,198 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+pub const ENUM_MIN_ANY_AMBIGUOUS_ALIASES: u8 = 0;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+pub const ENUM_MAX_ANY_AMBIGUOUS_ALIASES: u8 = 3;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+#[allow(non_camel_case_types)]
+pub const ENUM_VALUES_ANY_AMBIGUOUS_ALIASES: [AnyAmbiguousAliases; 4] = [
+ AnyAmbiguousAliases::NONE,
+ AnyAmbiguousAliases::M1,
+ AnyAmbiguousAliases::M2,
+ AnyAmbiguousAliases::M3,
+];
+
+#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
+#[repr(transparent)]
+pub struct AnyAmbiguousAliases(pub u8);
+#[allow(non_upper_case_globals)]
+impl AnyAmbiguousAliases {
+ pub const NONE: Self = Self(0);
+ pub const M1: Self = Self(1);
+ pub const M2: Self = Self(2);
+ pub const M3: Self = Self(3);
+
+ pub const ENUM_MIN: u8 = 0;
+ pub const ENUM_MAX: u8 = 3;
+ pub const ENUM_VALUES: &'static [Self] = &[
+ Self::NONE,
+ Self::M1,
+ Self::M2,
+ Self::M3,
+ ];
+ /// Returns the variant's name or "" if unknown.
+ pub fn variant_name(self) -> Option<&'static str> {
+ match self {
+ Self::NONE => Some("NONE"),
+ Self::M1 => Some("M1"),
+ Self::M2 => Some("M2"),
+ Self::M3 => Some("M3"),
+ _ => None,
+ }
+ }
+}
+impl std::fmt::Debug for AnyAmbiguousAliases {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ if let Some(name) = self.variant_name() {
+ f.write_str(name)
+ } else {
+ f.write_fmt(format_args!("<UNKNOWN {:?}>", self.0))
+ }
+ }
+}
+impl<'a> flatbuffers::Follow<'a> for AnyAmbiguousAliases {
+ type Inner = Self;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ let b = unsafe {
+ flatbuffers::read_scalar_at::<u8>(buf, loc)
+ };
+ Self(b)
+ }
+}
+
+impl flatbuffers::Push for AnyAmbiguousAliases {
+ type Output = AnyAmbiguousAliases;
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ unsafe { flatbuffers::emplace_scalar::<u8>(dst, self.0); }
+ }
+}
+
+impl flatbuffers::EndianScalar for AnyAmbiguousAliases {
+ #[inline]
+ fn to_little_endian(self) -> Self {
+ let b = u8::to_le(self.0);
+ Self(b)
+ }
+ #[inline]
+ #[allow(clippy::wrong_self_convention)]
+ fn from_little_endian(self) -> Self {
+ let b = u8::from_le(self.0);
+ Self(b)
+ }
+}
+
+impl<'a> flatbuffers::Verifiable for AnyAmbiguousAliases {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ u8::run_verifier(v, pos)
+ }
+}
+
+impl flatbuffers::SimpleToVerifyInSlice for AnyAmbiguousAliases {}
+pub struct AnyAmbiguousAliasesUnionTableOffset {}
+
+#[allow(clippy::upper_case_acronyms)]
+#[non_exhaustive]
+#[derive(Debug, Clone, PartialEq)]
+pub enum AnyAmbiguousAliasesT {
+ NONE,
+ M1(Box<MonsterT>),
+ M2(Box<MonsterT>),
+ M3(Box<MonsterT>),
+}
+impl Default for AnyAmbiguousAliasesT {
+ fn default() -> Self {
+ Self::NONE
+ }
+}
+impl AnyAmbiguousAliasesT {
+ pub fn any_ambiguous_aliases_type(&self) -> AnyAmbiguousAliases {
+ match self {
+ Self::NONE => AnyAmbiguousAliases::NONE,
+ Self::M1(_) => AnyAmbiguousAliases::M1,
+ Self::M2(_) => AnyAmbiguousAliases::M2,
+ Self::M3(_) => AnyAmbiguousAliases::M3,
+ }
+ }
+ pub fn pack(&self, fbb: &mut flatbuffers::FlatBufferBuilder) -> Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>> {
+ match self {
+ Self::NONE => None,
+ Self::M1(v) => Some(v.pack(fbb).as_union_value()),
+ Self::M2(v) => Some(v.pack(fbb).as_union_value()),
+ Self::M3(v) => Some(v.pack(fbb).as_union_value()),
+ }
+ }
+ /// If the union variant matches, return the owned MonsterT, setting the union to NONE.
+ pub fn take_m1(&mut self) -> Option<Box<MonsterT>> {
+ if let Self::M1(_) = self {
+ let v = std::mem::replace(self, Self::NONE);
+ if let Self::M1(w) = v {
+ Some(w)
+ } else {
+ unreachable!()
+ }
+ } else {
+ None
+ }
+ }
+ /// If the union variant matches, return a reference to the MonsterT.
+ pub fn as_m1(&self) -> Option<&MonsterT> {
+ if let Self::M1(v) = self { Some(v.as_ref()) } else { None }
+ }
+ /// If the union variant matches, return a mutable reference to the MonsterT.
+ pub fn as_m1_mut(&mut self) -> Option<&mut MonsterT> {
+ if let Self::M1(v) = self { Some(v.as_mut()) } else { None }
+ }
+ /// If the union variant matches, return the owned MonsterT, setting the union to NONE.
+ pub fn take_m2(&mut self) -> Option<Box<MonsterT>> {
+ if let Self::M2(_) = self {
+ let v = std::mem::replace(self, Self::NONE);
+ if let Self::M2(w) = v {
+ Some(w)
+ } else {
+ unreachable!()
+ }
+ } else {
+ None
+ }
+ }
+ /// If the union variant matches, return a reference to the MonsterT.
+ pub fn as_m2(&self) -> Option<&MonsterT> {
+ if let Self::M2(v) = self { Some(v.as_ref()) } else { None }
+ }
+ /// If the union variant matches, return a mutable reference to the MonsterT.
+ pub fn as_m2_mut(&mut self) -> Option<&mut MonsterT> {
+ if let Self::M2(v) = self { Some(v.as_mut()) } else { None }
+ }
+ /// If the union variant matches, return the owned MonsterT, setting the union to NONE.
+ pub fn take_m3(&mut self) -> Option<Box<MonsterT>> {
+ if let Self::M3(_) = self {
+ let v = std::mem::replace(self, Self::NONE);
+ if let Self::M3(w) = v {
+ Some(w)
+ } else {
+ unreachable!()
+ }
+ } else {
+ None
+ }
+ }
+ /// If the union variant matches, return a reference to the MonsterT.
+ pub fn as_m3(&self) -> Option<&MonsterT> {
+ if let Self::M3(v) = self { Some(v.as_ref()) } else { None }
+ }
+ /// If the union variant matches, return a mutable reference to the MonsterT.
+ pub fn as_m3_mut(&mut self) -> Option<&mut MonsterT> {
+ if let Self::M3(v) = self { Some(v.as_mut()) } else { None }
+ }
+}
diff --git a/tests/monster_test/my_game/example/any_generated.rs b/tests/monster_test/my_game/example/any_generated.rs
new file mode 100644
index 0000000..6f7f6fd
--- /dev/null
+++ b/tests/monster_test/my_game/example/any_generated.rs
@@ -0,0 +1,198 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+pub const ENUM_MIN_ANY: u8 = 0;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+pub const ENUM_MAX_ANY: u8 = 3;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+#[allow(non_camel_case_types)]
+pub const ENUM_VALUES_ANY: [Any; 4] = [
+ Any::NONE,
+ Any::Monster,
+ Any::TestSimpleTableWithEnum,
+ Any::MyGame_Example2_Monster,
+];
+
+#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
+#[repr(transparent)]
+pub struct Any(pub u8);
+#[allow(non_upper_case_globals)]
+impl Any {
+ pub const NONE: Self = Self(0);
+ pub const Monster: Self = Self(1);
+ pub const TestSimpleTableWithEnum: Self = Self(2);
+ pub const MyGame_Example2_Monster: Self = Self(3);
+
+ pub const ENUM_MIN: u8 = 0;
+ pub const ENUM_MAX: u8 = 3;
+ pub const ENUM_VALUES: &'static [Self] = &[
+ Self::NONE,
+ Self::Monster,
+ Self::TestSimpleTableWithEnum,
+ Self::MyGame_Example2_Monster,
+ ];
+ /// Returns the variant's name or "" if unknown.
+ pub fn variant_name(self) -> Option<&'static str> {
+ match self {
+ Self::NONE => Some("NONE"),
+ Self::Monster => Some("Monster"),
+ Self::TestSimpleTableWithEnum => Some("TestSimpleTableWithEnum"),
+ Self::MyGame_Example2_Monster => Some("MyGame_Example2_Monster"),
+ _ => None,
+ }
+ }
+}
+impl std::fmt::Debug for Any {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ if let Some(name) = self.variant_name() {
+ f.write_str(name)
+ } else {
+ f.write_fmt(format_args!("<UNKNOWN {:?}>", self.0))
+ }
+ }
+}
+impl<'a> flatbuffers::Follow<'a> for Any {
+ type Inner = Self;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ let b = unsafe {
+ flatbuffers::read_scalar_at::<u8>(buf, loc)
+ };
+ Self(b)
+ }
+}
+
+impl flatbuffers::Push for Any {
+ type Output = Any;
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ unsafe { flatbuffers::emplace_scalar::<u8>(dst, self.0); }
+ }
+}
+
+impl flatbuffers::EndianScalar for Any {
+ #[inline]
+ fn to_little_endian(self) -> Self {
+ let b = u8::to_le(self.0);
+ Self(b)
+ }
+ #[inline]
+ #[allow(clippy::wrong_self_convention)]
+ fn from_little_endian(self) -> Self {
+ let b = u8::from_le(self.0);
+ Self(b)
+ }
+}
+
+impl<'a> flatbuffers::Verifiable for Any {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ u8::run_verifier(v, pos)
+ }
+}
+
+impl flatbuffers::SimpleToVerifyInSlice for Any {}
+pub struct AnyUnionTableOffset {}
+
+#[allow(clippy::upper_case_acronyms)]
+#[non_exhaustive]
+#[derive(Debug, Clone, PartialEq)]
+pub enum AnyT {
+ NONE,
+ Monster(Box<MonsterT>),
+ TestSimpleTableWithEnum(Box<TestSimpleTableWithEnumT>),
+ MyGameExample2Monster(Box<super::example_2::MonsterT>),
+}
+impl Default for AnyT {
+ fn default() -> Self {
+ Self::NONE
+ }
+}
+impl AnyT {
+ pub fn any_type(&self) -> Any {
+ match self {
+ Self::NONE => Any::NONE,
+ Self::Monster(_) => Any::Monster,
+ Self::TestSimpleTableWithEnum(_) => Any::TestSimpleTableWithEnum,
+ Self::MyGameExample2Monster(_) => Any::MyGame_Example2_Monster,
+ }
+ }
+ pub fn pack(&self, fbb: &mut flatbuffers::FlatBufferBuilder) -> Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>> {
+ match self {
+ Self::NONE => None,
+ Self::Monster(v) => Some(v.pack(fbb).as_union_value()),
+ Self::TestSimpleTableWithEnum(v) => Some(v.pack(fbb).as_union_value()),
+ Self::MyGameExample2Monster(v) => Some(v.pack(fbb).as_union_value()),
+ }
+ }
+ /// If the union variant matches, return the owned MonsterT, setting the union to NONE.
+ pub fn take_monster(&mut self) -> Option<Box<MonsterT>> {
+ if let Self::Monster(_) = self {
+ let v = std::mem::replace(self, Self::NONE);
+ if let Self::Monster(w) = v {
+ Some(w)
+ } else {
+ unreachable!()
+ }
+ } else {
+ None
+ }
+ }
+ /// If the union variant matches, return a reference to the MonsterT.
+ pub fn as_monster(&self) -> Option<&MonsterT> {
+ if let Self::Monster(v) = self { Some(v.as_ref()) } else { None }
+ }
+ /// If the union variant matches, return a mutable reference to the MonsterT.
+ pub fn as_monster_mut(&mut self) -> Option<&mut MonsterT> {
+ if let Self::Monster(v) = self { Some(v.as_mut()) } else { None }
+ }
+ /// If the union variant matches, return the owned TestSimpleTableWithEnumT, setting the union to NONE.
+ pub fn take_test_simple_table_with_enum(&mut self) -> Option<Box<TestSimpleTableWithEnumT>> {
+ if let Self::TestSimpleTableWithEnum(_) = self {
+ let v = std::mem::replace(self, Self::NONE);
+ if let Self::TestSimpleTableWithEnum(w) = v {
+ Some(w)
+ } else {
+ unreachable!()
+ }
+ } else {
+ None
+ }
+ }
+ /// If the union variant matches, return a reference to the TestSimpleTableWithEnumT.
+ pub fn as_test_simple_table_with_enum(&self) -> Option<&TestSimpleTableWithEnumT> {
+ if let Self::TestSimpleTableWithEnum(v) = self { Some(v.as_ref()) } else { None }
+ }
+ /// If the union variant matches, return a mutable reference to the TestSimpleTableWithEnumT.
+ pub fn as_test_simple_table_with_enum_mut(&mut self) -> Option<&mut TestSimpleTableWithEnumT> {
+ if let Self::TestSimpleTableWithEnum(v) = self { Some(v.as_mut()) } else { None }
+ }
+ /// If the union variant matches, return the owned super::example_2::MonsterT, setting the union to NONE.
+ pub fn take_my_game_example_2_monster(&mut self) -> Option<Box<super::example_2::MonsterT>> {
+ if let Self::MyGameExample2Monster(_) = self {
+ let v = std::mem::replace(self, Self::NONE);
+ if let Self::MyGameExample2Monster(w) = v {
+ Some(w)
+ } else {
+ unreachable!()
+ }
+ } else {
+ None
+ }
+ }
+ /// If the union variant matches, return a reference to the super::example_2::MonsterT.
+ pub fn as_my_game_example_2_monster(&self) -> Option<&super::example_2::MonsterT> {
+ if let Self::MyGameExample2Monster(v) = self { Some(v.as_ref()) } else { None }
+ }
+ /// If the union variant matches, return a mutable reference to the super::example_2::MonsterT.
+ pub fn as_my_game_example_2_monster_mut(&mut self) -> Option<&mut super::example_2::MonsterT> {
+ if let Self::MyGameExample2Monster(v) = self { Some(v.as_mut()) } else { None }
+ }
+}
diff --git a/tests/monster_test/my_game/example/any_unique_aliases_generated.rs b/tests/monster_test/my_game/example/any_unique_aliases_generated.rs
new file mode 100644
index 0000000..1749d5d
--- /dev/null
+++ b/tests/monster_test/my_game/example/any_unique_aliases_generated.rs
@@ -0,0 +1,198 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+pub const ENUM_MIN_ANY_UNIQUE_ALIASES: u8 = 0;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+pub const ENUM_MAX_ANY_UNIQUE_ALIASES: u8 = 3;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+#[allow(non_camel_case_types)]
+pub const ENUM_VALUES_ANY_UNIQUE_ALIASES: [AnyUniqueAliases; 4] = [
+ AnyUniqueAliases::NONE,
+ AnyUniqueAliases::M,
+ AnyUniqueAliases::TS,
+ AnyUniqueAliases::M2,
+];
+
+#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
+#[repr(transparent)]
+pub struct AnyUniqueAliases(pub u8);
+#[allow(non_upper_case_globals)]
+impl AnyUniqueAliases {
+ pub const NONE: Self = Self(0);
+ pub const M: Self = Self(1);
+ pub const TS: Self = Self(2);
+ pub const M2: Self = Self(3);
+
+ pub const ENUM_MIN: u8 = 0;
+ pub const ENUM_MAX: u8 = 3;
+ pub const ENUM_VALUES: &'static [Self] = &[
+ Self::NONE,
+ Self::M,
+ Self::TS,
+ Self::M2,
+ ];
+ /// Returns the variant's name or "" if unknown.
+ pub fn variant_name(self) -> Option<&'static str> {
+ match self {
+ Self::NONE => Some("NONE"),
+ Self::M => Some("M"),
+ Self::TS => Some("TS"),
+ Self::M2 => Some("M2"),
+ _ => None,
+ }
+ }
+}
+impl std::fmt::Debug for AnyUniqueAliases {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ if let Some(name) = self.variant_name() {
+ f.write_str(name)
+ } else {
+ f.write_fmt(format_args!("<UNKNOWN {:?}>", self.0))
+ }
+ }
+}
+impl<'a> flatbuffers::Follow<'a> for AnyUniqueAliases {
+ type Inner = Self;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ let b = unsafe {
+ flatbuffers::read_scalar_at::<u8>(buf, loc)
+ };
+ Self(b)
+ }
+}
+
+impl flatbuffers::Push for AnyUniqueAliases {
+ type Output = AnyUniqueAliases;
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ unsafe { flatbuffers::emplace_scalar::<u8>(dst, self.0); }
+ }
+}
+
+impl flatbuffers::EndianScalar for AnyUniqueAliases {
+ #[inline]
+ fn to_little_endian(self) -> Self {
+ let b = u8::to_le(self.0);
+ Self(b)
+ }
+ #[inline]
+ #[allow(clippy::wrong_self_convention)]
+ fn from_little_endian(self) -> Self {
+ let b = u8::from_le(self.0);
+ Self(b)
+ }
+}
+
+impl<'a> flatbuffers::Verifiable for AnyUniqueAliases {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ u8::run_verifier(v, pos)
+ }
+}
+
+impl flatbuffers::SimpleToVerifyInSlice for AnyUniqueAliases {}
+pub struct AnyUniqueAliasesUnionTableOffset {}
+
+#[allow(clippy::upper_case_acronyms)]
+#[non_exhaustive]
+#[derive(Debug, Clone, PartialEq)]
+pub enum AnyUniqueAliasesT {
+ NONE,
+ M(Box<MonsterT>),
+ TS(Box<TestSimpleTableWithEnumT>),
+ M2(Box<super::example_2::MonsterT>),
+}
+impl Default for AnyUniqueAliasesT {
+ fn default() -> Self {
+ Self::NONE
+ }
+}
+impl AnyUniqueAliasesT {
+ pub fn any_unique_aliases_type(&self) -> AnyUniqueAliases {
+ match self {
+ Self::NONE => AnyUniqueAliases::NONE,
+ Self::M(_) => AnyUniqueAliases::M,
+ Self::TS(_) => AnyUniqueAliases::TS,
+ Self::M2(_) => AnyUniqueAliases::M2,
+ }
+ }
+ pub fn pack(&self, fbb: &mut flatbuffers::FlatBufferBuilder) -> Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>> {
+ match self {
+ Self::NONE => None,
+ Self::M(v) => Some(v.pack(fbb).as_union_value()),
+ Self::TS(v) => Some(v.pack(fbb).as_union_value()),
+ Self::M2(v) => Some(v.pack(fbb).as_union_value()),
+ }
+ }
+ /// If the union variant matches, return the owned MonsterT, setting the union to NONE.
+ pub fn take_m(&mut self) -> Option<Box<MonsterT>> {
+ if let Self::M(_) = self {
+ let v = std::mem::replace(self, Self::NONE);
+ if let Self::M(w) = v {
+ Some(w)
+ } else {
+ unreachable!()
+ }
+ } else {
+ None
+ }
+ }
+ /// If the union variant matches, return a reference to the MonsterT.
+ pub fn as_m(&self) -> Option<&MonsterT> {
+ if let Self::M(v) = self { Some(v.as_ref()) } else { None }
+ }
+ /// If the union variant matches, return a mutable reference to the MonsterT.
+ pub fn as_m_mut(&mut self) -> Option<&mut MonsterT> {
+ if let Self::M(v) = self { Some(v.as_mut()) } else { None }
+ }
+ /// If the union variant matches, return the owned TestSimpleTableWithEnumT, setting the union to NONE.
+ pub fn take_ts(&mut self) -> Option<Box<TestSimpleTableWithEnumT>> {
+ if let Self::TS(_) = self {
+ let v = std::mem::replace(self, Self::NONE);
+ if let Self::TS(w) = v {
+ Some(w)
+ } else {
+ unreachable!()
+ }
+ } else {
+ None
+ }
+ }
+ /// If the union variant matches, return a reference to the TestSimpleTableWithEnumT.
+ pub fn as_ts(&self) -> Option<&TestSimpleTableWithEnumT> {
+ if let Self::TS(v) = self { Some(v.as_ref()) } else { None }
+ }
+ /// If the union variant matches, return a mutable reference to the TestSimpleTableWithEnumT.
+ pub fn as_ts_mut(&mut self) -> Option<&mut TestSimpleTableWithEnumT> {
+ if let Self::TS(v) = self { Some(v.as_mut()) } else { None }
+ }
+ /// If the union variant matches, return the owned super::example_2::MonsterT, setting the union to NONE.
+ pub fn take_m2(&mut self) -> Option<Box<super::example_2::MonsterT>> {
+ if let Self::M2(_) = self {
+ let v = std::mem::replace(self, Self::NONE);
+ if let Self::M2(w) = v {
+ Some(w)
+ } else {
+ unreachable!()
+ }
+ } else {
+ None
+ }
+ }
+ /// If the union variant matches, return a reference to the super::example_2::MonsterT.
+ pub fn as_m2(&self) -> Option<&super::example_2::MonsterT> {
+ if let Self::M2(v) = self { Some(v.as_ref()) } else { None }
+ }
+ /// If the union variant matches, return a mutable reference to the super::example_2::MonsterT.
+ pub fn as_m2_mut(&mut self) -> Option<&mut super::example_2::MonsterT> {
+ if let Self::M2(v) = self { Some(v.as_mut()) } else { None }
+ }
+}
diff --git a/tests/monster_test/my_game/example/color_generated.rs b/tests/monster_test/my_game/example/color_generated.rs
new file mode 100644
index 0000000..4a3282b
--- /dev/null
+++ b/tests/monster_test/my_game/example/color_generated.rs
@@ -0,0 +1,67 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+#[allow(non_upper_case_globals)]
+mod bitflags_color {
+ flatbuffers::bitflags::bitflags! {
+ /// Composite components of Monster color.
+ #[derive(Default)]
+ pub struct Color: u8 {
+ const Red = 1;
+ /// \brief color Green
+ /// Green is bit_flag with value (1u << 1)
+ const Green = 2;
+ /// \brief color Blue (1u << 3)
+ const Blue = 8;
+ }
+ }
+}
+pub use self::bitflags_color::Color;
+
+impl<'a> flatbuffers::Follow<'a> for Color {
+ type Inner = Self;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ let b = unsafe {
+ flatbuffers::read_scalar_at::<u8>(buf, loc)
+ };
+ unsafe { Self::from_bits_unchecked(b) }
+ }
+}
+
+impl flatbuffers::Push for Color {
+ type Output = Color;
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ unsafe { flatbuffers::emplace_scalar::<u8>(dst, self.bits()); }
+ }
+}
+
+impl flatbuffers::EndianScalar for Color {
+ #[inline]
+ fn to_little_endian(self) -> Self {
+ let b = u8::to_le(self.bits());
+ unsafe { Self::from_bits_unchecked(b) }
+ }
+ #[inline]
+ #[allow(clippy::wrong_self_convention)]
+ fn from_little_endian(self) -> Self {
+ let b = u8::from_le(self.bits());
+ unsafe { Self::from_bits_unchecked(b) }
+ }
+}
+
+impl<'a> flatbuffers::Verifiable for Color {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ u8::run_verifier(v, pos)
+ }
+}
+
+impl flatbuffers::SimpleToVerifyInSlice for Color {}
diff --git a/tests/monster_test/my_game/example/long_enum_generated.rs b/tests/monster_test/my_game/example/long_enum_generated.rs
new file mode 100644
index 0000000..b22f826
--- /dev/null
+++ b/tests/monster_test/my_game/example/long_enum_generated.rs
@@ -0,0 +1,63 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+#[allow(non_upper_case_globals)]
+mod bitflags_long_enum {
+ flatbuffers::bitflags::bitflags! {
+ #[derive(Default)]
+ pub struct LongEnum: u64 {
+ const LongOne = 2;
+ const LongTwo = 4;
+ const LongBig = 1099511627776;
+ }
+ }
+}
+pub use self::bitflags_long_enum::LongEnum;
+
+impl<'a> flatbuffers::Follow<'a> for LongEnum {
+ type Inner = Self;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ let b = unsafe {
+ flatbuffers::read_scalar_at::<u64>(buf, loc)
+ };
+ unsafe { Self::from_bits_unchecked(b) }
+ }
+}
+
+impl flatbuffers::Push for LongEnum {
+ type Output = LongEnum;
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ unsafe { flatbuffers::emplace_scalar::<u64>(dst, self.bits()); }
+ }
+}
+
+impl flatbuffers::EndianScalar for LongEnum {
+ #[inline]
+ fn to_little_endian(self) -> Self {
+ let b = u64::to_le(self.bits());
+ unsafe { Self::from_bits_unchecked(b) }
+ }
+ #[inline]
+ #[allow(clippy::wrong_self_convention)]
+ fn from_little_endian(self) -> Self {
+ let b = u64::from_le(self.bits());
+ unsafe { Self::from_bits_unchecked(b) }
+ }
+}
+
+impl<'a> flatbuffers::Verifiable for LongEnum {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ u64::run_verifier(v, pos)
+ }
+}
+
+impl flatbuffers::SimpleToVerifyInSlice for LongEnum {}
diff --git a/tests/monster_test/my_game/example/monster_generated.rs b/tests/monster_test/my_game/example/monster_generated.rs
new file mode 100644
index 0000000..58e7628
--- /dev/null
+++ b/tests/monster_test/my_game/example/monster_generated.rs
@@ -0,0 +1,1628 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+pub enum MonsterOffset {}
+#[derive(Copy, Clone, PartialEq)]
+
+/// an example documentation comment: "monster object"
+pub struct Monster<'a> {
+ pub _tab: flatbuffers::Table<'a>,
+}
+
+impl<'a> flatbuffers::Follow<'a> for Monster<'a> {
+ type Inner = Monster<'a>;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ Self { _tab: flatbuffers::Table { buf, loc } }
+ }
+}
+
+impl<'a> Monster<'a> {
+ pub const VT_POS: flatbuffers::VOffsetT = 4;
+ pub const VT_MANA: flatbuffers::VOffsetT = 6;
+ pub const VT_HP: flatbuffers::VOffsetT = 8;
+ pub const VT_NAME: flatbuffers::VOffsetT = 10;
+ pub const VT_INVENTORY: flatbuffers::VOffsetT = 14;
+ pub const VT_COLOR: flatbuffers::VOffsetT = 16;
+ pub const VT_TEST_TYPE: flatbuffers::VOffsetT = 18;
+ pub const VT_TEST: flatbuffers::VOffsetT = 20;
+ pub const VT_TEST4: flatbuffers::VOffsetT = 22;
+ pub const VT_TESTARRAYOFSTRING: flatbuffers::VOffsetT = 24;
+ pub const VT_TESTARRAYOFTABLES: flatbuffers::VOffsetT = 26;
+ pub const VT_ENEMY: flatbuffers::VOffsetT = 28;
+ pub const VT_TESTNESTEDFLATBUFFER: flatbuffers::VOffsetT = 30;
+ pub const VT_TESTEMPTY: flatbuffers::VOffsetT = 32;
+ pub const VT_TESTBOOL: flatbuffers::VOffsetT = 34;
+ pub const VT_TESTHASHS32_FNV1: flatbuffers::VOffsetT = 36;
+ pub const VT_TESTHASHU32_FNV1: flatbuffers::VOffsetT = 38;
+ pub const VT_TESTHASHS64_FNV1: flatbuffers::VOffsetT = 40;
+ pub const VT_TESTHASHU64_FNV1: flatbuffers::VOffsetT = 42;
+ pub const VT_TESTHASHS32_FNV1A: flatbuffers::VOffsetT = 44;
+ pub const VT_TESTHASHU32_FNV1A: flatbuffers::VOffsetT = 46;
+ pub const VT_TESTHASHS64_FNV1A: flatbuffers::VOffsetT = 48;
+ pub const VT_TESTHASHU64_FNV1A: flatbuffers::VOffsetT = 50;
+ pub const VT_TESTARRAYOFBOOLS: flatbuffers::VOffsetT = 52;
+ pub const VT_TESTF: flatbuffers::VOffsetT = 54;
+ pub const VT_TESTF2: flatbuffers::VOffsetT = 56;
+ pub const VT_TESTF3: flatbuffers::VOffsetT = 58;
+ pub const VT_TESTARRAYOFSTRING2: flatbuffers::VOffsetT = 60;
+ pub const VT_TESTARRAYOFSORTEDSTRUCT: flatbuffers::VOffsetT = 62;
+ pub const VT_FLEX: flatbuffers::VOffsetT = 64;
+ pub const VT_TEST5: flatbuffers::VOffsetT = 66;
+ pub const VT_VECTOR_OF_LONGS: flatbuffers::VOffsetT = 68;
+ pub const VT_VECTOR_OF_DOUBLES: flatbuffers::VOffsetT = 70;
+ pub const VT_PARENT_NAMESPACE_TEST: flatbuffers::VOffsetT = 72;
+ pub const VT_VECTOR_OF_REFERRABLES: flatbuffers::VOffsetT = 74;
+ pub const VT_SINGLE_WEAK_REFERENCE: flatbuffers::VOffsetT = 76;
+ pub const VT_VECTOR_OF_WEAK_REFERENCES: flatbuffers::VOffsetT = 78;
+ pub const VT_VECTOR_OF_STRONG_REFERRABLES: flatbuffers::VOffsetT = 80;
+ pub const VT_CO_OWNING_REFERENCE: flatbuffers::VOffsetT = 82;
+ pub const VT_VECTOR_OF_CO_OWNING_REFERENCES: flatbuffers::VOffsetT = 84;
+ pub const VT_NON_OWNING_REFERENCE: flatbuffers::VOffsetT = 86;
+ pub const VT_VECTOR_OF_NON_OWNING_REFERENCES: flatbuffers::VOffsetT = 88;
+ pub const VT_ANY_UNIQUE_TYPE: flatbuffers::VOffsetT = 90;
+ pub const VT_ANY_UNIQUE: flatbuffers::VOffsetT = 92;
+ pub const VT_ANY_AMBIGUOUS_TYPE: flatbuffers::VOffsetT = 94;
+ pub const VT_ANY_AMBIGUOUS: flatbuffers::VOffsetT = 96;
+ pub const VT_VECTOR_OF_ENUMS: flatbuffers::VOffsetT = 98;
+ pub const VT_SIGNED_ENUM: flatbuffers::VOffsetT = 100;
+ pub const VT_TESTREQUIREDNESTEDFLATBUFFER: flatbuffers::VOffsetT = 102;
+ pub const VT_SCALAR_KEY_SORTED_TABLES: flatbuffers::VOffsetT = 104;
+ pub const VT_NATIVE_INLINE: flatbuffers::VOffsetT = 106;
+ pub const VT_LONG_ENUM_NON_ENUM_DEFAULT: flatbuffers::VOffsetT = 108;
+ pub const VT_LONG_ENUM_NORMAL_DEFAULT: flatbuffers::VOffsetT = 110;
+
+ pub const fn get_fully_qualified_name() -> &'static str {
+ "MyGame.Example.Monster"
+ }
+
+ #[inline]
+ pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
+ Monster { _tab: table }
+ }
+ #[allow(unused_mut)]
+ pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
+ _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
+ args: &'args MonsterArgs<'args>
+ ) -> flatbuffers::WIPOffset<Monster<'bldr>> {
+ let mut builder = MonsterBuilder::new(_fbb);
+ builder.add_long_enum_normal_default(args.long_enum_normal_default);
+ builder.add_long_enum_non_enum_default(args.long_enum_non_enum_default);
+ builder.add_non_owning_reference(args.non_owning_reference);
+ builder.add_co_owning_reference(args.co_owning_reference);
+ builder.add_single_weak_reference(args.single_weak_reference);
+ builder.add_testhashu64_fnv1a(args.testhashu64_fnv1a);
+ builder.add_testhashs64_fnv1a(args.testhashs64_fnv1a);
+ builder.add_testhashu64_fnv1(args.testhashu64_fnv1);
+ builder.add_testhashs64_fnv1(args.testhashs64_fnv1);
+ if let Some(x) = args.native_inline { builder.add_native_inline(x); }
+ if let Some(x) = args.scalar_key_sorted_tables { builder.add_scalar_key_sorted_tables(x); }
+ if let Some(x) = args.testrequirednestedflatbuffer { builder.add_testrequirednestedflatbuffer(x); }
+ if let Some(x) = args.vector_of_enums { builder.add_vector_of_enums(x); }
+ if let Some(x) = args.any_ambiguous { builder.add_any_ambiguous(x); }
+ if let Some(x) = args.any_unique { builder.add_any_unique(x); }
+ if let Some(x) = args.vector_of_non_owning_references { builder.add_vector_of_non_owning_references(x); }
+ if let Some(x) = args.vector_of_co_owning_references { builder.add_vector_of_co_owning_references(x); }
+ if let Some(x) = args.vector_of_strong_referrables { builder.add_vector_of_strong_referrables(x); }
+ if let Some(x) = args.vector_of_weak_references { builder.add_vector_of_weak_references(x); }
+ if let Some(x) = args.vector_of_referrables { builder.add_vector_of_referrables(x); }
+ if let Some(x) = args.parent_namespace_test { builder.add_parent_namespace_test(x); }
+ if let Some(x) = args.vector_of_doubles { builder.add_vector_of_doubles(x); }
+ if let Some(x) = args.vector_of_longs { builder.add_vector_of_longs(x); }
+ if let Some(x) = args.test5 { builder.add_test5(x); }
+ if let Some(x) = args.flex { builder.add_flex(x); }
+ if let Some(x) = args.testarrayofsortedstruct { builder.add_testarrayofsortedstruct(x); }
+ if let Some(x) = args.testarrayofstring2 { builder.add_testarrayofstring2(x); }
+ builder.add_testf3(args.testf3);
+ builder.add_testf2(args.testf2);
+ builder.add_testf(args.testf);
+ if let Some(x) = args.testarrayofbools { builder.add_testarrayofbools(x); }
+ builder.add_testhashu32_fnv1a(args.testhashu32_fnv1a);
+ builder.add_testhashs32_fnv1a(args.testhashs32_fnv1a);
+ builder.add_testhashu32_fnv1(args.testhashu32_fnv1);
+ builder.add_testhashs32_fnv1(args.testhashs32_fnv1);
+ if let Some(x) = args.testempty { builder.add_testempty(x); }
+ if let Some(x) = args.testnestedflatbuffer { builder.add_testnestedflatbuffer(x); }
+ if let Some(x) = args.enemy { builder.add_enemy(x); }
+ if let Some(x) = args.testarrayoftables { builder.add_testarrayoftables(x); }
+ if let Some(x) = args.testarrayofstring { builder.add_testarrayofstring(x); }
+ if let Some(x) = args.test4 { builder.add_test4(x); }
+ if let Some(x) = args.test { builder.add_test(x); }
+ if let Some(x) = args.inventory { builder.add_inventory(x); }
+ if let Some(x) = args.name { builder.add_name(x); }
+ if let Some(x) = args.pos { builder.add_pos(x); }
+ builder.add_hp(args.hp);
+ builder.add_mana(args.mana);
+ builder.add_signed_enum(args.signed_enum);
+ builder.add_any_ambiguous_type(args.any_ambiguous_type);
+ builder.add_any_unique_type(args.any_unique_type);
+ builder.add_testbool(args.testbool);
+ builder.add_test_type(args.test_type);
+ builder.add_color(args.color);
+ builder.finish()
+ }
+
+ pub fn unpack(&self) -> MonsterT {
+ let pos = self.pos().map(|x| {
+ x.unpack()
+ });
+ let mana = self.mana();
+ let hp = self.hp();
+ let name = {
+ let x = self.name();
+ x.to_string()
+ };
+ let inventory = self.inventory().map(|x| {
+ x.to_vec()
+ });
+ let color = self.color();
+ let test = match self.test_type() {
+ Any::NONE => AnyT::NONE,
+ Any::Monster => AnyT::Monster(Box::new(
+ self.test_as_monster()
+ .expect("Invalid union table, expected `Any::Monster`.")
+ .unpack()
+ )),
+ Any::TestSimpleTableWithEnum => AnyT::TestSimpleTableWithEnum(Box::new(
+ self.test_as_test_simple_table_with_enum()
+ .expect("Invalid union table, expected `Any::TestSimpleTableWithEnum`.")
+ .unpack()
+ )),
+ Any::MyGame_Example2_Monster => AnyT::MyGameExample2Monster(Box::new(
+ self.test_as_my_game_example_2_monster()
+ .expect("Invalid union table, expected `Any::MyGame_Example2_Monster`.")
+ .unpack()
+ )),
+ _ => AnyT::NONE,
+ };
+ let test4 = self.test4().map(|x| {
+ x.iter().map(|t| t.unpack()).collect()
+ });
+ let testarrayofstring = self.testarrayofstring().map(|x| {
+ x.iter().map(|s| s.to_string()).collect()
+ });
+ let testarrayoftables = self.testarrayoftables().map(|x| {
+ x.iter().map(|t| t.unpack()).collect()
+ });
+ let enemy = self.enemy().map(|x| {
+ Box::new(x.unpack())
+ });
+ let testnestedflatbuffer = self.testnestedflatbuffer().map(|x| {
+ x.to_vec()
+ });
+ let testempty = self.testempty().map(|x| {
+ Box::new(x.unpack())
+ });
+ let testbool = self.testbool();
+ let testhashs32_fnv1 = self.testhashs32_fnv1();
+ let testhashu32_fnv1 = self.testhashu32_fnv1();
+ let testhashs64_fnv1 = self.testhashs64_fnv1();
+ let testhashu64_fnv1 = self.testhashu64_fnv1();
+ let testhashs32_fnv1a = self.testhashs32_fnv1a();
+ let testhashu32_fnv1a = self.testhashu32_fnv1a();
+ let testhashs64_fnv1a = self.testhashs64_fnv1a();
+ let testhashu64_fnv1a = self.testhashu64_fnv1a();
+ let testarrayofbools = self.testarrayofbools().map(|x| {
+ x.to_vec()
+ });
+ let testf = self.testf();
+ let testf2 = self.testf2();
+ let testf3 = self.testf3();
+ let testarrayofstring2 = self.testarrayofstring2().map(|x| {
+ x.iter().map(|s| s.to_string()).collect()
+ });
+ let testarrayofsortedstruct = self.testarrayofsortedstruct().map(|x| {
+ x.iter().map(|t| t.unpack()).collect()
+ });
+ let flex = self.flex().map(|x| {
+ x.to_vec()
+ });
+ let test5 = self.test5().map(|x| {
+ x.iter().map(|t| t.unpack()).collect()
+ });
+ let vector_of_longs = self.vector_of_longs().map(|x| {
+ x.into_iter().collect()
+ });
+ let vector_of_doubles = self.vector_of_doubles().map(|x| {
+ x.into_iter().collect()
+ });
+ let parent_namespace_test = self.parent_namespace_test().map(|x| {
+ Box::new(x.unpack())
+ });
+ let vector_of_referrables = self.vector_of_referrables().map(|x| {
+ x.iter().map(|t| t.unpack()).collect()
+ });
+ let single_weak_reference = self.single_weak_reference();
+ let vector_of_weak_references = self.vector_of_weak_references().map(|x| {
+ x.into_iter().collect()
+ });
+ let vector_of_strong_referrables = self.vector_of_strong_referrables().map(|x| {
+ x.iter().map(|t| t.unpack()).collect()
+ });
+ let co_owning_reference = self.co_owning_reference();
+ let vector_of_co_owning_references = self.vector_of_co_owning_references().map(|x| {
+ x.into_iter().collect()
+ });
+ let non_owning_reference = self.non_owning_reference();
+ let vector_of_non_owning_references = self.vector_of_non_owning_references().map(|x| {
+ x.into_iter().collect()
+ });
+ let any_unique = match self.any_unique_type() {
+ AnyUniqueAliases::NONE => AnyUniqueAliasesT::NONE,
+ AnyUniqueAliases::M => AnyUniqueAliasesT::M(Box::new(
+ self.any_unique_as_m()
+ .expect("Invalid union table, expected `AnyUniqueAliases::M`.")
+ .unpack()
+ )),
+ AnyUniqueAliases::TS => AnyUniqueAliasesT::TS(Box::new(
+ self.any_unique_as_ts()
+ .expect("Invalid union table, expected `AnyUniqueAliases::TS`.")
+ .unpack()
+ )),
+ AnyUniqueAliases::M2 => AnyUniqueAliasesT::M2(Box::new(
+ self.any_unique_as_m2()
+ .expect("Invalid union table, expected `AnyUniqueAliases::M2`.")
+ .unpack()
+ )),
+ _ => AnyUniqueAliasesT::NONE,
+ };
+ let any_ambiguous = match self.any_ambiguous_type() {
+ AnyAmbiguousAliases::NONE => AnyAmbiguousAliasesT::NONE,
+ AnyAmbiguousAliases::M1 => AnyAmbiguousAliasesT::M1(Box::new(
+ self.any_ambiguous_as_m1()
+ .expect("Invalid union table, expected `AnyAmbiguousAliases::M1`.")
+ .unpack()
+ )),
+ AnyAmbiguousAliases::M2 => AnyAmbiguousAliasesT::M2(Box::new(
+ self.any_ambiguous_as_m2()
+ .expect("Invalid union table, expected `AnyAmbiguousAliases::M2`.")
+ .unpack()
+ )),
+ AnyAmbiguousAliases::M3 => AnyAmbiguousAliasesT::M3(Box::new(
+ self.any_ambiguous_as_m3()
+ .expect("Invalid union table, expected `AnyAmbiguousAliases::M3`.")
+ .unpack()
+ )),
+ _ => AnyAmbiguousAliasesT::NONE,
+ };
+ let vector_of_enums = self.vector_of_enums().map(|x| {
+ x.into_iter().collect()
+ });
+ let signed_enum = self.signed_enum();
+ let testrequirednestedflatbuffer = self.testrequirednestedflatbuffer().map(|x| {
+ x.to_vec()
+ });
+ let scalar_key_sorted_tables = self.scalar_key_sorted_tables().map(|x| {
+ x.iter().map(|t| t.unpack()).collect()
+ });
+ let native_inline = self.native_inline().map(|x| {
+ x.unpack()
+ });
+ let long_enum_non_enum_default = self.long_enum_non_enum_default();
+ let long_enum_normal_default = self.long_enum_normal_default();
+ MonsterT {
+ pos,
+ mana,
+ hp,
+ name,
+ inventory,
+ color,
+ test,
+ test4,
+ testarrayofstring,
+ testarrayoftables,
+ enemy,
+ testnestedflatbuffer,
+ testempty,
+ testbool,
+ testhashs32_fnv1,
+ testhashu32_fnv1,
+ testhashs64_fnv1,
+ testhashu64_fnv1,
+ testhashs32_fnv1a,
+ testhashu32_fnv1a,
+ testhashs64_fnv1a,
+ testhashu64_fnv1a,
+ testarrayofbools,
+ testf,
+ testf2,
+ testf3,
+ testarrayofstring2,
+ testarrayofsortedstruct,
+ flex,
+ test5,
+ vector_of_longs,
+ vector_of_doubles,
+ parent_namespace_test,
+ vector_of_referrables,
+ single_weak_reference,
+ vector_of_weak_references,
+ vector_of_strong_referrables,
+ co_owning_reference,
+ vector_of_co_owning_references,
+ non_owning_reference,
+ vector_of_non_owning_references,
+ any_unique,
+ any_ambiguous,
+ vector_of_enums,
+ signed_enum,
+ testrequirednestedflatbuffer,
+ scalar_key_sorted_tables,
+ native_inline,
+ long_enum_non_enum_default,
+ long_enum_normal_default,
+ }
+ }
+
+ #[inline]
+ pub fn pos(&self) -> Option<&'a Vec3> {
+ self._tab.get::<Vec3>(Monster::VT_POS, None)
+ }
+ #[inline]
+ pub fn mana(&self) -> i16 {
+ self._tab.get::<i16>(Monster::VT_MANA, Some(150)).unwrap()
+ }
+ #[inline]
+ pub fn hp(&self) -> i16 {
+ self._tab.get::<i16>(Monster::VT_HP, Some(100)).unwrap()
+ }
+ #[inline]
+ pub fn name(&self) -> &'a str {
+ self._tab.get::<flatbuffers::ForwardsUOffset<&str>>(Monster::VT_NAME, None).unwrap()
+ }
+ #[inline]
+ pub fn key_compare_less_than(&self, o: &Monster) -> bool {
+ self.name() < o.name()
+ }
+
+ #[inline]
+ pub fn key_compare_with_value(&self, val: & str) -> ::std::cmp::Ordering {
+ let key = self.name();
+ key.cmp(val)
+ }
+ #[inline]
+ pub fn inventory(&self) -> Option<&'a [u8]> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, u8>>>(Monster::VT_INVENTORY, None).map(|v| v.safe_slice())
+ }
+ #[inline]
+ pub fn color(&self) -> Color {
+ self._tab.get::<Color>(Monster::VT_COLOR, Some(Color::Blue)).unwrap()
+ }
+ #[inline]
+ pub fn test_type(&self) -> Any {
+ self._tab.get::<Any>(Monster::VT_TEST_TYPE, Some(Any::NONE)).unwrap()
+ }
+ #[inline]
+ pub fn test(&self) -> Option<flatbuffers::Table<'a>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Table<'a>>>(Monster::VT_TEST, None)
+ }
+ #[inline]
+ pub fn test4(&self) -> Option<&'a [Test]> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, Test>>>(Monster::VT_TEST4, None).map(|v| v.safe_slice())
+ }
+ #[inline]
+ pub fn testarrayofstring(&self) -> Option<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<&'a str>>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<&'a str>>>>(Monster::VT_TESTARRAYOFSTRING, None)
+ }
+ /// an example documentation comment: this will end up in the generated code
+ /// multiline too
+ #[inline]
+ pub fn testarrayoftables(&self) -> Option<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Monster<'a>>>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Monster>>>>(Monster::VT_TESTARRAYOFTABLES, None)
+ }
+ #[inline]
+ pub fn enemy(&self) -> Option<Monster<'a>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<Monster>>(Monster::VT_ENEMY, None)
+ }
+ #[inline]
+ pub fn testnestedflatbuffer(&self) -> Option<&'a [u8]> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, u8>>>(Monster::VT_TESTNESTEDFLATBUFFER, None).map(|v| v.safe_slice())
+ }
+ pub fn testnestedflatbuffer_nested_flatbuffer(&'a self) -> Option<Monster<'a>> {
+ self.testnestedflatbuffer().map(|data| {
+ use flatbuffers::Follow;
+ <flatbuffers::ForwardsUOffset<Monster<'a>>>::follow(data, 0)
+ })
+ }
+ #[inline]
+ pub fn testempty(&self) -> Option<Stat<'a>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<Stat>>(Monster::VT_TESTEMPTY, None)
+ }
+ #[inline]
+ pub fn testbool(&self) -> bool {
+ self._tab.get::<bool>(Monster::VT_TESTBOOL, Some(false)).unwrap()
+ }
+ #[inline]
+ pub fn testhashs32_fnv1(&self) -> i32 {
+ self._tab.get::<i32>(Monster::VT_TESTHASHS32_FNV1, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn testhashu32_fnv1(&self) -> u32 {
+ self._tab.get::<u32>(Monster::VT_TESTHASHU32_FNV1, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn testhashs64_fnv1(&self) -> i64 {
+ self._tab.get::<i64>(Monster::VT_TESTHASHS64_FNV1, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn testhashu64_fnv1(&self) -> u64 {
+ self._tab.get::<u64>(Monster::VT_TESTHASHU64_FNV1, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn testhashs32_fnv1a(&self) -> i32 {
+ self._tab.get::<i32>(Monster::VT_TESTHASHS32_FNV1A, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn testhashu32_fnv1a(&self) -> u32 {
+ self._tab.get::<u32>(Monster::VT_TESTHASHU32_FNV1A, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn testhashs64_fnv1a(&self) -> i64 {
+ self._tab.get::<i64>(Monster::VT_TESTHASHS64_FNV1A, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn testhashu64_fnv1a(&self) -> u64 {
+ self._tab.get::<u64>(Monster::VT_TESTHASHU64_FNV1A, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn testarrayofbools(&self) -> Option<&'a [bool]> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, bool>>>(Monster::VT_TESTARRAYOFBOOLS, None).map(|v| v.safe_slice())
+ }
+ #[inline]
+ pub fn testf(&self) -> f32 {
+ self._tab.get::<f32>(Monster::VT_TESTF, Some(3.14159)).unwrap()
+ }
+ #[inline]
+ pub fn testf2(&self) -> f32 {
+ self._tab.get::<f32>(Monster::VT_TESTF2, Some(3.0)).unwrap()
+ }
+ #[inline]
+ pub fn testf3(&self) -> f32 {
+ self._tab.get::<f32>(Monster::VT_TESTF3, Some(0.0)).unwrap()
+ }
+ #[inline]
+ pub fn testarrayofstring2(&self) -> Option<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<&'a str>>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<&'a str>>>>(Monster::VT_TESTARRAYOFSTRING2, None)
+ }
+ #[inline]
+ pub fn testarrayofsortedstruct(&self) -> Option<&'a [Ability]> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, Ability>>>(Monster::VT_TESTARRAYOFSORTEDSTRUCT, None).map(|v| v.safe_slice())
+ }
+ #[inline]
+ pub fn flex(&self) -> Option<&'a [u8]> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, u8>>>(Monster::VT_FLEX, None).map(|v| v.safe_slice())
+ }
+ #[inline]
+ pub fn test5(&self) -> Option<&'a [Test]> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, Test>>>(Monster::VT_TEST5, None).map(|v| v.safe_slice())
+ }
+ #[inline]
+ pub fn vector_of_longs(&self) -> Option<flatbuffers::Vector<'a, i64>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, i64>>>(Monster::VT_VECTOR_OF_LONGS, None)
+ }
+ #[inline]
+ pub fn vector_of_doubles(&self) -> Option<flatbuffers::Vector<'a, f64>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, f64>>>(Monster::VT_VECTOR_OF_DOUBLES, None)
+ }
+ #[inline]
+ pub fn parent_namespace_test(&self) -> Option<super::InParentNamespace<'a>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<super::InParentNamespace>>(Monster::VT_PARENT_NAMESPACE_TEST, None)
+ }
+ #[inline]
+ pub fn vector_of_referrables(&self) -> Option<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Referrable<'a>>>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Referrable>>>>(Monster::VT_VECTOR_OF_REFERRABLES, None)
+ }
+ #[inline]
+ pub fn single_weak_reference(&self) -> u64 {
+ self._tab.get::<u64>(Monster::VT_SINGLE_WEAK_REFERENCE, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn vector_of_weak_references(&self) -> Option<flatbuffers::Vector<'a, u64>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, u64>>>(Monster::VT_VECTOR_OF_WEAK_REFERENCES, None)
+ }
+ #[inline]
+ pub fn vector_of_strong_referrables(&self) -> Option<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Referrable<'a>>>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Referrable>>>>(Monster::VT_VECTOR_OF_STRONG_REFERRABLES, None)
+ }
+ #[inline]
+ pub fn co_owning_reference(&self) -> u64 {
+ self._tab.get::<u64>(Monster::VT_CO_OWNING_REFERENCE, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn vector_of_co_owning_references(&self) -> Option<flatbuffers::Vector<'a, u64>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, u64>>>(Monster::VT_VECTOR_OF_CO_OWNING_REFERENCES, None)
+ }
+ #[inline]
+ pub fn non_owning_reference(&self) -> u64 {
+ self._tab.get::<u64>(Monster::VT_NON_OWNING_REFERENCE, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn vector_of_non_owning_references(&self) -> Option<flatbuffers::Vector<'a, u64>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, u64>>>(Monster::VT_VECTOR_OF_NON_OWNING_REFERENCES, None)
+ }
+ #[inline]
+ pub fn any_unique_type(&self) -> AnyUniqueAliases {
+ self._tab.get::<AnyUniqueAliases>(Monster::VT_ANY_UNIQUE_TYPE, Some(AnyUniqueAliases::NONE)).unwrap()
+ }
+ #[inline]
+ pub fn any_unique(&self) -> Option<flatbuffers::Table<'a>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Table<'a>>>(Monster::VT_ANY_UNIQUE, None)
+ }
+ #[inline]
+ pub fn any_ambiguous_type(&self) -> AnyAmbiguousAliases {
+ self._tab.get::<AnyAmbiguousAliases>(Monster::VT_ANY_AMBIGUOUS_TYPE, Some(AnyAmbiguousAliases::NONE)).unwrap()
+ }
+ #[inline]
+ pub fn any_ambiguous(&self) -> Option<flatbuffers::Table<'a>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Table<'a>>>(Monster::VT_ANY_AMBIGUOUS, None)
+ }
+ #[inline]
+ pub fn vector_of_enums(&self) -> Option<flatbuffers::Vector<'a, Color>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, Color>>>(Monster::VT_VECTOR_OF_ENUMS, None)
+ }
+ #[inline]
+ pub fn signed_enum(&self) -> Race {
+ self._tab.get::<Race>(Monster::VT_SIGNED_ENUM, Some(Race::None)).unwrap()
+ }
+ #[inline]
+ pub fn testrequirednestedflatbuffer(&self) -> Option<&'a [u8]> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, u8>>>(Monster::VT_TESTREQUIREDNESTEDFLATBUFFER, None).map(|v| v.safe_slice())
+ }
+ pub fn testrequirednestedflatbuffer_nested_flatbuffer(&'a self) -> Option<Monster<'a>> {
+ self.testrequirednestedflatbuffer().map(|data| {
+ use flatbuffers::Follow;
+ <flatbuffers::ForwardsUOffset<Monster<'a>>>::follow(data, 0)
+ })
+ }
+ #[inline]
+ pub fn scalar_key_sorted_tables(&self) -> Option<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Stat<'a>>>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Stat>>>>(Monster::VT_SCALAR_KEY_SORTED_TABLES, None)
+ }
+ #[inline]
+ pub fn native_inline(&self) -> Option<&'a Test> {
+ self._tab.get::<Test>(Monster::VT_NATIVE_INLINE, None)
+ }
+ #[inline]
+ pub fn long_enum_non_enum_default(&self) -> LongEnum {
+ self._tab.get::<LongEnum>(Monster::VT_LONG_ENUM_NON_ENUM_DEFAULT, Some(Default::default())).unwrap()
+ }
+ #[inline]
+ pub fn long_enum_normal_default(&self) -> LongEnum {
+ self._tab.get::<LongEnum>(Monster::VT_LONG_ENUM_NORMAL_DEFAULT, Some(LongEnum::LongOne)).unwrap()
+ }
+ #[inline]
+ #[allow(non_snake_case)]
+ pub fn test_as_monster(&self) -> Option<Monster<'a>> {
+ if self.test_type() == Any::Monster {
+ self.test().map(Monster::init_from_table)
+ } else {
+ None
+ }
+ }
+
+ #[inline]
+ #[allow(non_snake_case)]
+ pub fn test_as_test_simple_table_with_enum(&self) -> Option<TestSimpleTableWithEnum<'a>> {
+ if self.test_type() == Any::TestSimpleTableWithEnum {
+ self.test().map(TestSimpleTableWithEnum::init_from_table)
+ } else {
+ None
+ }
+ }
+
+ #[inline]
+ #[allow(non_snake_case)]
+ pub fn test_as_my_game_example_2_monster(&self) -> Option<super::example_2::Monster<'a>> {
+ if self.test_type() == Any::MyGame_Example2_Monster {
+ self.test().map(super::example_2::Monster::init_from_table)
+ } else {
+ None
+ }
+ }
+
+ #[inline]
+ #[allow(non_snake_case)]
+ pub fn any_unique_as_m(&self) -> Option<Monster<'a>> {
+ if self.any_unique_type() == AnyUniqueAliases::M {
+ self.any_unique().map(Monster::init_from_table)
+ } else {
+ None
+ }
+ }
+
+ #[inline]
+ #[allow(non_snake_case)]
+ pub fn any_unique_as_ts(&self) -> Option<TestSimpleTableWithEnum<'a>> {
+ if self.any_unique_type() == AnyUniqueAliases::TS {
+ self.any_unique().map(TestSimpleTableWithEnum::init_from_table)
+ } else {
+ None
+ }
+ }
+
+ #[inline]
+ #[allow(non_snake_case)]
+ pub fn any_unique_as_m2(&self) -> Option<super::example_2::Monster<'a>> {
+ if self.any_unique_type() == AnyUniqueAliases::M2 {
+ self.any_unique().map(super::example_2::Monster::init_from_table)
+ } else {
+ None
+ }
+ }
+
+ #[inline]
+ #[allow(non_snake_case)]
+ pub fn any_ambiguous_as_m1(&self) -> Option<Monster<'a>> {
+ if self.any_ambiguous_type() == AnyAmbiguousAliases::M1 {
+ self.any_ambiguous().map(Monster::init_from_table)
+ } else {
+ None
+ }
+ }
+
+ #[inline]
+ #[allow(non_snake_case)]
+ pub fn any_ambiguous_as_m2(&self) -> Option<Monster<'a>> {
+ if self.any_ambiguous_type() == AnyAmbiguousAliases::M2 {
+ self.any_ambiguous().map(Monster::init_from_table)
+ } else {
+ None
+ }
+ }
+
+ #[inline]
+ #[allow(non_snake_case)]
+ pub fn any_ambiguous_as_m3(&self) -> Option<Monster<'a>> {
+ if self.any_ambiguous_type() == AnyAmbiguousAliases::M3 {
+ self.any_ambiguous().map(Monster::init_from_table)
+ } else {
+ None
+ }
+ }
+
+}
+
+impl flatbuffers::Verifiable for Monster<'_> {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ v.visit_table(pos)?
+ .visit_field::<Vec3>("pos", Self::VT_POS, false)?
+ .visit_field::<i16>("mana", Self::VT_MANA, false)?
+ .visit_field::<i16>("hp", Self::VT_HP, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<&str>>("name", Self::VT_NAME, true)?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, u8>>>("inventory", Self::VT_INVENTORY, false)?
+ .visit_field::<Color>("color", Self::VT_COLOR, false)?
+ .visit_union::<Any, _>("test_type", Self::VT_TEST_TYPE, "test", Self::VT_TEST, false, |key, v, pos| {
+ match key {
+ Any::Monster => v.verify_union_variant::<flatbuffers::ForwardsUOffset<Monster>>("Any::Monster", pos),
+ Any::TestSimpleTableWithEnum => v.verify_union_variant::<flatbuffers::ForwardsUOffset<TestSimpleTableWithEnum>>("Any::TestSimpleTableWithEnum", pos),
+ Any::MyGame_Example2_Monster => v.verify_union_variant::<flatbuffers::ForwardsUOffset<super::example_2::Monster>>("Any::MyGame_Example2_Monster", pos),
+ _ => Ok(()),
+ }
+ })?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, Test>>>("test4", Self::VT_TEST4, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, flatbuffers::ForwardsUOffset<&'_ str>>>>("testarrayofstring", Self::VT_TESTARRAYOFSTRING, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, flatbuffers::ForwardsUOffset<Monster>>>>("testarrayoftables", Self::VT_TESTARRAYOFTABLES, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<Monster>>("enemy", Self::VT_ENEMY, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, u8>>>("testnestedflatbuffer", Self::VT_TESTNESTEDFLATBUFFER, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<Stat>>("testempty", Self::VT_TESTEMPTY, false)?
+ .visit_field::<bool>("testbool", Self::VT_TESTBOOL, false)?
+ .visit_field::<i32>("testhashs32_fnv1", Self::VT_TESTHASHS32_FNV1, false)?
+ .visit_field::<u32>("testhashu32_fnv1", Self::VT_TESTHASHU32_FNV1, false)?
+ .visit_field::<i64>("testhashs64_fnv1", Self::VT_TESTHASHS64_FNV1, false)?
+ .visit_field::<u64>("testhashu64_fnv1", Self::VT_TESTHASHU64_FNV1, false)?
+ .visit_field::<i32>("testhashs32_fnv1a", Self::VT_TESTHASHS32_FNV1A, false)?
+ .visit_field::<u32>("testhashu32_fnv1a", Self::VT_TESTHASHU32_FNV1A, false)?
+ .visit_field::<i64>("testhashs64_fnv1a", Self::VT_TESTHASHS64_FNV1A, false)?
+ .visit_field::<u64>("testhashu64_fnv1a", Self::VT_TESTHASHU64_FNV1A, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, bool>>>("testarrayofbools", Self::VT_TESTARRAYOFBOOLS, false)?
+ .visit_field::<f32>("testf", Self::VT_TESTF, false)?
+ .visit_field::<f32>("testf2", Self::VT_TESTF2, false)?
+ .visit_field::<f32>("testf3", Self::VT_TESTF3, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, flatbuffers::ForwardsUOffset<&'_ str>>>>("testarrayofstring2", Self::VT_TESTARRAYOFSTRING2, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, Ability>>>("testarrayofsortedstruct", Self::VT_TESTARRAYOFSORTEDSTRUCT, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, u8>>>("flex", Self::VT_FLEX, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, Test>>>("test5", Self::VT_TEST5, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, i64>>>("vector_of_longs", Self::VT_VECTOR_OF_LONGS, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, f64>>>("vector_of_doubles", Self::VT_VECTOR_OF_DOUBLES, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<super::InParentNamespace>>("parent_namespace_test", Self::VT_PARENT_NAMESPACE_TEST, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, flatbuffers::ForwardsUOffset<Referrable>>>>("vector_of_referrables", Self::VT_VECTOR_OF_REFERRABLES, false)?
+ .visit_field::<u64>("single_weak_reference", Self::VT_SINGLE_WEAK_REFERENCE, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, u64>>>("vector_of_weak_references", Self::VT_VECTOR_OF_WEAK_REFERENCES, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, flatbuffers::ForwardsUOffset<Referrable>>>>("vector_of_strong_referrables", Self::VT_VECTOR_OF_STRONG_REFERRABLES, false)?
+ .visit_field::<u64>("co_owning_reference", Self::VT_CO_OWNING_REFERENCE, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, u64>>>("vector_of_co_owning_references", Self::VT_VECTOR_OF_CO_OWNING_REFERENCES, false)?
+ .visit_field::<u64>("non_owning_reference", Self::VT_NON_OWNING_REFERENCE, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, u64>>>("vector_of_non_owning_references", Self::VT_VECTOR_OF_NON_OWNING_REFERENCES, false)?
+ .visit_union::<AnyUniqueAliases, _>("any_unique_type", Self::VT_ANY_UNIQUE_TYPE, "any_unique", Self::VT_ANY_UNIQUE, false, |key, v, pos| {
+ match key {
+ AnyUniqueAliases::M => v.verify_union_variant::<flatbuffers::ForwardsUOffset<Monster>>("AnyUniqueAliases::M", pos),
+ AnyUniqueAliases::TS => v.verify_union_variant::<flatbuffers::ForwardsUOffset<TestSimpleTableWithEnum>>("AnyUniqueAliases::TS", pos),
+ AnyUniqueAliases::M2 => v.verify_union_variant::<flatbuffers::ForwardsUOffset<super::example_2::Monster>>("AnyUniqueAliases::M2", pos),
+ _ => Ok(()),
+ }
+ })?
+ .visit_union::<AnyAmbiguousAliases, _>("any_ambiguous_type", Self::VT_ANY_AMBIGUOUS_TYPE, "any_ambiguous", Self::VT_ANY_AMBIGUOUS, false, |key, v, pos| {
+ match key {
+ AnyAmbiguousAliases::M1 => v.verify_union_variant::<flatbuffers::ForwardsUOffset<Monster>>("AnyAmbiguousAliases::M1", pos),
+ AnyAmbiguousAliases::M2 => v.verify_union_variant::<flatbuffers::ForwardsUOffset<Monster>>("AnyAmbiguousAliases::M2", pos),
+ AnyAmbiguousAliases::M3 => v.verify_union_variant::<flatbuffers::ForwardsUOffset<Monster>>("AnyAmbiguousAliases::M3", pos),
+ _ => Ok(()),
+ }
+ })?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, Color>>>("vector_of_enums", Self::VT_VECTOR_OF_ENUMS, false)?
+ .visit_field::<Race>("signed_enum", Self::VT_SIGNED_ENUM, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, u8>>>("testrequirednestedflatbuffer", Self::VT_TESTREQUIREDNESTEDFLATBUFFER, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, flatbuffers::ForwardsUOffset<Stat>>>>("scalar_key_sorted_tables", Self::VT_SCALAR_KEY_SORTED_TABLES, false)?
+ .visit_field::<Test>("native_inline", Self::VT_NATIVE_INLINE, false)?
+ .visit_field::<LongEnum>("long_enum_non_enum_default", Self::VT_LONG_ENUM_NON_ENUM_DEFAULT, false)?
+ .visit_field::<LongEnum>("long_enum_normal_default", Self::VT_LONG_ENUM_NORMAL_DEFAULT, false)?
+ .finish();
+ Ok(())
+ }
+}
+pub struct MonsterArgs<'a> {
+ pub pos: Option<&'a Vec3>,
+ pub mana: i16,
+ pub hp: i16,
+ pub name: Option<flatbuffers::WIPOffset<&'a str>>,
+ pub inventory: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, u8>>>,
+ pub color: Color,
+ pub test_type: Any,
+ pub test: Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>,
+ pub test4: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, Test>>>,
+ pub testarrayofstring: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<&'a str>>>>,
+ pub testarrayoftables: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Monster<'a>>>>>,
+ pub enemy: Option<flatbuffers::WIPOffset<Monster<'a>>>,
+ pub testnestedflatbuffer: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, u8>>>,
+ pub testempty: Option<flatbuffers::WIPOffset<Stat<'a>>>,
+ pub testbool: bool,
+ pub testhashs32_fnv1: i32,
+ pub testhashu32_fnv1: u32,
+ pub testhashs64_fnv1: i64,
+ pub testhashu64_fnv1: u64,
+ pub testhashs32_fnv1a: i32,
+ pub testhashu32_fnv1a: u32,
+ pub testhashs64_fnv1a: i64,
+ pub testhashu64_fnv1a: u64,
+ pub testarrayofbools: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, bool>>>,
+ pub testf: f32,
+ pub testf2: f32,
+ pub testf3: f32,
+ pub testarrayofstring2: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<&'a str>>>>,
+ pub testarrayofsortedstruct: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, Ability>>>,
+ pub flex: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, u8>>>,
+ pub test5: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, Test>>>,
+ pub vector_of_longs: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, i64>>>,
+ pub vector_of_doubles: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, f64>>>,
+ pub parent_namespace_test: Option<flatbuffers::WIPOffset<super::InParentNamespace<'a>>>,
+ pub vector_of_referrables: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Referrable<'a>>>>>,
+ pub single_weak_reference: u64,
+ pub vector_of_weak_references: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, u64>>>,
+ pub vector_of_strong_referrables: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Referrable<'a>>>>>,
+ pub co_owning_reference: u64,
+ pub vector_of_co_owning_references: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, u64>>>,
+ pub non_owning_reference: u64,
+ pub vector_of_non_owning_references: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, u64>>>,
+ pub any_unique_type: AnyUniqueAliases,
+ pub any_unique: Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>,
+ pub any_ambiguous_type: AnyAmbiguousAliases,
+ pub any_ambiguous: Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>,
+ pub vector_of_enums: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, Color>>>,
+ pub signed_enum: Race,
+ pub testrequirednestedflatbuffer: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, u8>>>,
+ pub scalar_key_sorted_tables: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Stat<'a>>>>>,
+ pub native_inline: Option<&'a Test>,
+ pub long_enum_non_enum_default: LongEnum,
+ pub long_enum_normal_default: LongEnum,
+}
+impl<'a> Default for MonsterArgs<'a> {
+ #[inline]
+ fn default() -> Self {
+ MonsterArgs {
+ pos: None,
+ mana: 150,
+ hp: 100,
+ name: None, // required field
+ inventory: None,
+ color: Color::Blue,
+ test_type: Any::NONE,
+ test: None,
+ test4: None,
+ testarrayofstring: None,
+ testarrayoftables: None,
+ enemy: None,
+ testnestedflatbuffer: None,
+ testempty: None,
+ testbool: false,
+ testhashs32_fnv1: 0,
+ testhashu32_fnv1: 0,
+ testhashs64_fnv1: 0,
+ testhashu64_fnv1: 0,
+ testhashs32_fnv1a: 0,
+ testhashu32_fnv1a: 0,
+ testhashs64_fnv1a: 0,
+ testhashu64_fnv1a: 0,
+ testarrayofbools: None,
+ testf: 3.14159,
+ testf2: 3.0,
+ testf3: 0.0,
+ testarrayofstring2: None,
+ testarrayofsortedstruct: None,
+ flex: None,
+ test5: None,
+ vector_of_longs: None,
+ vector_of_doubles: None,
+ parent_namespace_test: None,
+ vector_of_referrables: None,
+ single_weak_reference: 0,
+ vector_of_weak_references: None,
+ vector_of_strong_referrables: None,
+ co_owning_reference: 0,
+ vector_of_co_owning_references: None,
+ non_owning_reference: 0,
+ vector_of_non_owning_references: None,
+ any_unique_type: AnyUniqueAliases::NONE,
+ any_unique: None,
+ any_ambiguous_type: AnyAmbiguousAliases::NONE,
+ any_ambiguous: None,
+ vector_of_enums: None,
+ signed_enum: Race::None,
+ testrequirednestedflatbuffer: None,
+ scalar_key_sorted_tables: None,
+ native_inline: None,
+ long_enum_non_enum_default: Default::default(),
+ long_enum_normal_default: LongEnum::LongOne,
+ }
+ }
+}
+
+pub struct MonsterBuilder<'a: 'b, 'b> {
+ fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
+ start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
+}
+impl<'a: 'b, 'b> MonsterBuilder<'a, 'b> {
+ #[inline]
+ pub fn add_pos(&mut self, pos: &Vec3) {
+ self.fbb_.push_slot_always::<&Vec3>(Monster::VT_POS, pos);
+ }
+ #[inline]
+ pub fn add_mana(&mut self, mana: i16) {
+ self.fbb_.push_slot::<i16>(Monster::VT_MANA, mana, 150);
+ }
+ #[inline]
+ pub fn add_hp(&mut self, hp: i16) {
+ self.fbb_.push_slot::<i16>(Monster::VT_HP, hp, 100);
+ }
+ #[inline]
+ pub fn add_name(&mut self, name: flatbuffers::WIPOffset<&'b str>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_NAME, name);
+ }
+ #[inline]
+ pub fn add_inventory(&mut self, inventory: flatbuffers::WIPOffset<flatbuffers::Vector<'b , u8>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_INVENTORY, inventory);
+ }
+ #[inline]
+ pub fn add_color(&mut self, color: Color) {
+ self.fbb_.push_slot::<Color>(Monster::VT_COLOR, color, Color::Blue);
+ }
+ #[inline]
+ pub fn add_test_type(&mut self, test_type: Any) {
+ self.fbb_.push_slot::<Any>(Monster::VT_TEST_TYPE, test_type, Any::NONE);
+ }
+ #[inline]
+ pub fn add_test(&mut self, test: flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_TEST, test);
+ }
+ #[inline]
+ pub fn add_test4(&mut self, test4: flatbuffers::WIPOffset<flatbuffers::Vector<'b , Test>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_TEST4, test4);
+ }
+ #[inline]
+ pub fn add_testarrayofstring(&mut self, testarrayofstring: flatbuffers::WIPOffset<flatbuffers::Vector<'b , flatbuffers::ForwardsUOffset<&'b str>>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_TESTARRAYOFSTRING, testarrayofstring);
+ }
+ #[inline]
+ pub fn add_testarrayoftables(&mut self, testarrayoftables: flatbuffers::WIPOffset<flatbuffers::Vector<'b , flatbuffers::ForwardsUOffset<Monster<'b >>>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_TESTARRAYOFTABLES, testarrayoftables);
+ }
+ #[inline]
+ pub fn add_enemy(&mut self, enemy: flatbuffers::WIPOffset<Monster<'b >>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<Monster>>(Monster::VT_ENEMY, enemy);
+ }
+ #[inline]
+ pub fn add_testnestedflatbuffer(&mut self, testnestedflatbuffer: flatbuffers::WIPOffset<flatbuffers::Vector<'b , u8>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_TESTNESTEDFLATBUFFER, testnestedflatbuffer);
+ }
+ #[inline]
+ pub fn add_testempty(&mut self, testempty: flatbuffers::WIPOffset<Stat<'b >>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<Stat>>(Monster::VT_TESTEMPTY, testempty);
+ }
+ #[inline]
+ pub fn add_testbool(&mut self, testbool: bool) {
+ self.fbb_.push_slot::<bool>(Monster::VT_TESTBOOL, testbool, false);
+ }
+ #[inline]
+ pub fn add_testhashs32_fnv1(&mut self, testhashs32_fnv1: i32) {
+ self.fbb_.push_slot::<i32>(Monster::VT_TESTHASHS32_FNV1, testhashs32_fnv1, 0);
+ }
+ #[inline]
+ pub fn add_testhashu32_fnv1(&mut self, testhashu32_fnv1: u32) {
+ self.fbb_.push_slot::<u32>(Monster::VT_TESTHASHU32_FNV1, testhashu32_fnv1, 0);
+ }
+ #[inline]
+ pub fn add_testhashs64_fnv1(&mut self, testhashs64_fnv1: i64) {
+ self.fbb_.push_slot::<i64>(Monster::VT_TESTHASHS64_FNV1, testhashs64_fnv1, 0);
+ }
+ #[inline]
+ pub fn add_testhashu64_fnv1(&mut self, testhashu64_fnv1: u64) {
+ self.fbb_.push_slot::<u64>(Monster::VT_TESTHASHU64_FNV1, testhashu64_fnv1, 0);
+ }
+ #[inline]
+ pub fn add_testhashs32_fnv1a(&mut self, testhashs32_fnv1a: i32) {
+ self.fbb_.push_slot::<i32>(Monster::VT_TESTHASHS32_FNV1A, testhashs32_fnv1a, 0);
+ }
+ #[inline]
+ pub fn add_testhashu32_fnv1a(&mut self, testhashu32_fnv1a: u32) {
+ self.fbb_.push_slot::<u32>(Monster::VT_TESTHASHU32_FNV1A, testhashu32_fnv1a, 0);
+ }
+ #[inline]
+ pub fn add_testhashs64_fnv1a(&mut self, testhashs64_fnv1a: i64) {
+ self.fbb_.push_slot::<i64>(Monster::VT_TESTHASHS64_FNV1A, testhashs64_fnv1a, 0);
+ }
+ #[inline]
+ pub fn add_testhashu64_fnv1a(&mut self, testhashu64_fnv1a: u64) {
+ self.fbb_.push_slot::<u64>(Monster::VT_TESTHASHU64_FNV1A, testhashu64_fnv1a, 0);
+ }
+ #[inline]
+ pub fn add_testarrayofbools(&mut self, testarrayofbools: flatbuffers::WIPOffset<flatbuffers::Vector<'b , bool>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_TESTARRAYOFBOOLS, testarrayofbools);
+ }
+ #[inline]
+ pub fn add_testf(&mut self, testf: f32) {
+ self.fbb_.push_slot::<f32>(Monster::VT_TESTF, testf, 3.14159);
+ }
+ #[inline]
+ pub fn add_testf2(&mut self, testf2: f32) {
+ self.fbb_.push_slot::<f32>(Monster::VT_TESTF2, testf2, 3.0);
+ }
+ #[inline]
+ pub fn add_testf3(&mut self, testf3: f32) {
+ self.fbb_.push_slot::<f32>(Monster::VT_TESTF3, testf3, 0.0);
+ }
+ #[inline]
+ pub fn add_testarrayofstring2(&mut self, testarrayofstring2: flatbuffers::WIPOffset<flatbuffers::Vector<'b , flatbuffers::ForwardsUOffset<&'b str>>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_TESTARRAYOFSTRING2, testarrayofstring2);
+ }
+ #[inline]
+ pub fn add_testarrayofsortedstruct(&mut self, testarrayofsortedstruct: flatbuffers::WIPOffset<flatbuffers::Vector<'b , Ability>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_TESTARRAYOFSORTEDSTRUCT, testarrayofsortedstruct);
+ }
+ #[inline]
+ pub fn add_flex(&mut self, flex: flatbuffers::WIPOffset<flatbuffers::Vector<'b , u8>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_FLEX, flex);
+ }
+ #[inline]
+ pub fn add_test5(&mut self, test5: flatbuffers::WIPOffset<flatbuffers::Vector<'b , Test>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_TEST5, test5);
+ }
+ #[inline]
+ pub fn add_vector_of_longs(&mut self, vector_of_longs: flatbuffers::WIPOffset<flatbuffers::Vector<'b , i64>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_LONGS, vector_of_longs);
+ }
+ #[inline]
+ pub fn add_vector_of_doubles(&mut self, vector_of_doubles: flatbuffers::WIPOffset<flatbuffers::Vector<'b , f64>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_DOUBLES, vector_of_doubles);
+ }
+ #[inline]
+ pub fn add_parent_namespace_test(&mut self, parent_namespace_test: flatbuffers::WIPOffset<super::InParentNamespace<'b >>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<super::InParentNamespace>>(Monster::VT_PARENT_NAMESPACE_TEST, parent_namespace_test);
+ }
+ #[inline]
+ pub fn add_vector_of_referrables(&mut self, vector_of_referrables: flatbuffers::WIPOffset<flatbuffers::Vector<'b , flatbuffers::ForwardsUOffset<Referrable<'b >>>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_REFERRABLES, vector_of_referrables);
+ }
+ #[inline]
+ pub fn add_single_weak_reference(&mut self, single_weak_reference: u64) {
+ self.fbb_.push_slot::<u64>(Monster::VT_SINGLE_WEAK_REFERENCE, single_weak_reference, 0);
+ }
+ #[inline]
+ pub fn add_vector_of_weak_references(&mut self, vector_of_weak_references: flatbuffers::WIPOffset<flatbuffers::Vector<'b , u64>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_WEAK_REFERENCES, vector_of_weak_references);
+ }
+ #[inline]
+ pub fn add_vector_of_strong_referrables(&mut self, vector_of_strong_referrables: flatbuffers::WIPOffset<flatbuffers::Vector<'b , flatbuffers::ForwardsUOffset<Referrable<'b >>>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_STRONG_REFERRABLES, vector_of_strong_referrables);
+ }
+ #[inline]
+ pub fn add_co_owning_reference(&mut self, co_owning_reference: u64) {
+ self.fbb_.push_slot::<u64>(Monster::VT_CO_OWNING_REFERENCE, co_owning_reference, 0);
+ }
+ #[inline]
+ pub fn add_vector_of_co_owning_references(&mut self, vector_of_co_owning_references: flatbuffers::WIPOffset<flatbuffers::Vector<'b , u64>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_CO_OWNING_REFERENCES, vector_of_co_owning_references);
+ }
+ #[inline]
+ pub fn add_non_owning_reference(&mut self, non_owning_reference: u64) {
+ self.fbb_.push_slot::<u64>(Monster::VT_NON_OWNING_REFERENCE, non_owning_reference, 0);
+ }
+ #[inline]
+ pub fn add_vector_of_non_owning_references(&mut self, vector_of_non_owning_references: flatbuffers::WIPOffset<flatbuffers::Vector<'b , u64>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_NON_OWNING_REFERENCES, vector_of_non_owning_references);
+ }
+ #[inline]
+ pub fn add_any_unique_type(&mut self, any_unique_type: AnyUniqueAliases) {
+ self.fbb_.push_slot::<AnyUniqueAliases>(Monster::VT_ANY_UNIQUE_TYPE, any_unique_type, AnyUniqueAliases::NONE);
+ }
+ #[inline]
+ pub fn add_any_unique(&mut self, any_unique: flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_ANY_UNIQUE, any_unique);
+ }
+ #[inline]
+ pub fn add_any_ambiguous_type(&mut self, any_ambiguous_type: AnyAmbiguousAliases) {
+ self.fbb_.push_slot::<AnyAmbiguousAliases>(Monster::VT_ANY_AMBIGUOUS_TYPE, any_ambiguous_type, AnyAmbiguousAliases::NONE);
+ }
+ #[inline]
+ pub fn add_any_ambiguous(&mut self, any_ambiguous: flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_ANY_AMBIGUOUS, any_ambiguous);
+ }
+ #[inline]
+ pub fn add_vector_of_enums(&mut self, vector_of_enums: flatbuffers::WIPOffset<flatbuffers::Vector<'b , Color>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_ENUMS, vector_of_enums);
+ }
+ #[inline]
+ pub fn add_signed_enum(&mut self, signed_enum: Race) {
+ self.fbb_.push_slot::<Race>(Monster::VT_SIGNED_ENUM, signed_enum, Race::None);
+ }
+ #[inline]
+ pub fn add_testrequirednestedflatbuffer(&mut self, testrequirednestedflatbuffer: flatbuffers::WIPOffset<flatbuffers::Vector<'b , u8>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_TESTREQUIREDNESTEDFLATBUFFER, testrequirednestedflatbuffer);
+ }
+ #[inline]
+ pub fn add_scalar_key_sorted_tables(&mut self, scalar_key_sorted_tables: flatbuffers::WIPOffset<flatbuffers::Vector<'b , flatbuffers::ForwardsUOffset<Stat<'b >>>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_SCALAR_KEY_SORTED_TABLES, scalar_key_sorted_tables);
+ }
+ #[inline]
+ pub fn add_native_inline(&mut self, native_inline: &Test) {
+ self.fbb_.push_slot_always::<&Test>(Monster::VT_NATIVE_INLINE, native_inline);
+ }
+ #[inline]
+ pub fn add_long_enum_non_enum_default(&mut self, long_enum_non_enum_default: LongEnum) {
+ self.fbb_.push_slot::<LongEnum>(Monster::VT_LONG_ENUM_NON_ENUM_DEFAULT, long_enum_non_enum_default, Default::default());
+ }
+ #[inline]
+ pub fn add_long_enum_normal_default(&mut self, long_enum_normal_default: LongEnum) {
+ self.fbb_.push_slot::<LongEnum>(Monster::VT_LONG_ENUM_NORMAL_DEFAULT, long_enum_normal_default, LongEnum::LongOne);
+ }
+ #[inline]
+ pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> MonsterBuilder<'a, 'b> {
+ let start = _fbb.start_table();
+ MonsterBuilder {
+ fbb_: _fbb,
+ start_: start,
+ }
+ }
+ #[inline]
+ pub fn finish(self) -> flatbuffers::WIPOffset<Monster<'a>> {
+ let o = self.fbb_.end_table(self.start_);
+ self.fbb_.required(o, Monster::VT_NAME,"name");
+ flatbuffers::WIPOffset::new(o.value())
+ }
+}
+
+impl std::fmt::Debug for Monster<'_> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let mut ds = f.debug_struct("Monster");
+ ds.field("pos", &self.pos());
+ ds.field("mana", &self.mana());
+ ds.field("hp", &self.hp());
+ ds.field("name", &self.name());
+ ds.field("inventory", &self.inventory());
+ ds.field("color", &self.color());
+ ds.field("test_type", &self.test_type());
+ match self.test_type() {
+ Any::Monster => {
+ if let Some(x) = self.test_as_monster() {
+ ds.field("test", &x)
+ } else {
+ ds.field("test", &"InvalidFlatbuffer: Union discriminant does not match value.")
+ }
+ },
+ Any::TestSimpleTableWithEnum => {
+ if let Some(x) = self.test_as_test_simple_table_with_enum() {
+ ds.field("test", &x)
+ } else {
+ ds.field("test", &"InvalidFlatbuffer: Union discriminant does not match value.")
+ }
+ },
+ Any::MyGame_Example2_Monster => {
+ if let Some(x) = self.test_as_my_game_example_2_monster() {
+ ds.field("test", &x)
+ } else {
+ ds.field("test", &"InvalidFlatbuffer: Union discriminant does not match value.")
+ }
+ },
+ _ => {
+ let x: Option<()> = None;
+ ds.field("test", &x)
+ },
+ };
+ ds.field("test4", &self.test4());
+ ds.field("testarrayofstring", &self.testarrayofstring());
+ ds.field("testarrayoftables", &self.testarrayoftables());
+ ds.field("enemy", &self.enemy());
+ ds.field("testnestedflatbuffer", &self.testnestedflatbuffer());
+ ds.field("testempty", &self.testempty());
+ ds.field("testbool", &self.testbool());
+ ds.field("testhashs32_fnv1", &self.testhashs32_fnv1());
+ ds.field("testhashu32_fnv1", &self.testhashu32_fnv1());
+ ds.field("testhashs64_fnv1", &self.testhashs64_fnv1());
+ ds.field("testhashu64_fnv1", &self.testhashu64_fnv1());
+ ds.field("testhashs32_fnv1a", &self.testhashs32_fnv1a());
+ ds.field("testhashu32_fnv1a", &self.testhashu32_fnv1a());
+ ds.field("testhashs64_fnv1a", &self.testhashs64_fnv1a());
+ ds.field("testhashu64_fnv1a", &self.testhashu64_fnv1a());
+ ds.field("testarrayofbools", &self.testarrayofbools());
+ ds.field("testf", &self.testf());
+ ds.field("testf2", &self.testf2());
+ ds.field("testf3", &self.testf3());
+ ds.field("testarrayofstring2", &self.testarrayofstring2());
+ ds.field("testarrayofsortedstruct", &self.testarrayofsortedstruct());
+ ds.field("flex", &self.flex());
+ ds.field("test5", &self.test5());
+ ds.field("vector_of_longs", &self.vector_of_longs());
+ ds.field("vector_of_doubles", &self.vector_of_doubles());
+ ds.field("parent_namespace_test", &self.parent_namespace_test());
+ ds.field("vector_of_referrables", &self.vector_of_referrables());
+ ds.field("single_weak_reference", &self.single_weak_reference());
+ ds.field("vector_of_weak_references", &self.vector_of_weak_references());
+ ds.field("vector_of_strong_referrables", &self.vector_of_strong_referrables());
+ ds.field("co_owning_reference", &self.co_owning_reference());
+ ds.field("vector_of_co_owning_references", &self.vector_of_co_owning_references());
+ ds.field("non_owning_reference", &self.non_owning_reference());
+ ds.field("vector_of_non_owning_references", &self.vector_of_non_owning_references());
+ ds.field("any_unique_type", &self.any_unique_type());
+ match self.any_unique_type() {
+ AnyUniqueAliases::M => {
+ if let Some(x) = self.any_unique_as_m() {
+ ds.field("any_unique", &x)
+ } else {
+ ds.field("any_unique", &"InvalidFlatbuffer: Union discriminant does not match value.")
+ }
+ },
+ AnyUniqueAliases::TS => {
+ if let Some(x) = self.any_unique_as_ts() {
+ ds.field("any_unique", &x)
+ } else {
+ ds.field("any_unique", &"InvalidFlatbuffer: Union discriminant does not match value.")
+ }
+ },
+ AnyUniqueAliases::M2 => {
+ if let Some(x) = self.any_unique_as_m2() {
+ ds.field("any_unique", &x)
+ } else {
+ ds.field("any_unique", &"InvalidFlatbuffer: Union discriminant does not match value.")
+ }
+ },
+ _ => {
+ let x: Option<()> = None;
+ ds.field("any_unique", &x)
+ },
+ };
+ ds.field("any_ambiguous_type", &self.any_ambiguous_type());
+ match self.any_ambiguous_type() {
+ AnyAmbiguousAliases::M1 => {
+ if let Some(x) = self.any_ambiguous_as_m1() {
+ ds.field("any_ambiguous", &x)
+ } else {
+ ds.field("any_ambiguous", &"InvalidFlatbuffer: Union discriminant does not match value.")
+ }
+ },
+ AnyAmbiguousAliases::M2 => {
+ if let Some(x) = self.any_ambiguous_as_m2() {
+ ds.field("any_ambiguous", &x)
+ } else {
+ ds.field("any_ambiguous", &"InvalidFlatbuffer: Union discriminant does not match value.")
+ }
+ },
+ AnyAmbiguousAliases::M3 => {
+ if let Some(x) = self.any_ambiguous_as_m3() {
+ ds.field("any_ambiguous", &x)
+ } else {
+ ds.field("any_ambiguous", &"InvalidFlatbuffer: Union discriminant does not match value.")
+ }
+ },
+ _ => {
+ let x: Option<()> = None;
+ ds.field("any_ambiguous", &x)
+ },
+ };
+ ds.field("vector_of_enums", &self.vector_of_enums());
+ ds.field("signed_enum", &self.signed_enum());
+ ds.field("testrequirednestedflatbuffer", &self.testrequirednestedflatbuffer());
+ ds.field("scalar_key_sorted_tables", &self.scalar_key_sorted_tables());
+ ds.field("native_inline", &self.native_inline());
+ ds.field("long_enum_non_enum_default", &self.long_enum_non_enum_default());
+ ds.field("long_enum_normal_default", &self.long_enum_normal_default());
+ ds.finish()
+ }
+}
+#[non_exhaustive]
+#[derive(Debug, Clone, PartialEq)]
+pub struct MonsterT {
+ pub pos: Option<Vec3T>,
+ pub mana: i16,
+ pub hp: i16,
+ pub name: String,
+ pub inventory: Option<Vec<u8>>,
+ pub color: Color,
+ pub test: AnyT,
+ pub test4: Option<Vec<TestT>>,
+ pub testarrayofstring: Option<Vec<String>>,
+ pub testarrayoftables: Option<Vec<MonsterT>>,
+ pub enemy: Option<Box<MonsterT>>,
+ pub testnestedflatbuffer: Option<Vec<u8>>,
+ pub testempty: Option<Box<StatT>>,
+ pub testbool: bool,
+ pub testhashs32_fnv1: i32,
+ pub testhashu32_fnv1: u32,
+ pub testhashs64_fnv1: i64,
+ pub testhashu64_fnv1: u64,
+ pub testhashs32_fnv1a: i32,
+ pub testhashu32_fnv1a: u32,
+ pub testhashs64_fnv1a: i64,
+ pub testhashu64_fnv1a: u64,
+ pub testarrayofbools: Option<Vec<bool>>,
+ pub testf: f32,
+ pub testf2: f32,
+ pub testf3: f32,
+ pub testarrayofstring2: Option<Vec<String>>,
+ pub testarrayofsortedstruct: Option<Vec<AbilityT>>,
+ pub flex: Option<Vec<u8>>,
+ pub test5: Option<Vec<TestT>>,
+ pub vector_of_longs: Option<Vec<i64>>,
+ pub vector_of_doubles: Option<Vec<f64>>,
+ pub parent_namespace_test: Option<Box<super::InParentNamespaceT>>,
+ pub vector_of_referrables: Option<Vec<ReferrableT>>,
+ pub single_weak_reference: u64,
+ pub vector_of_weak_references: Option<Vec<u64>>,
+ pub vector_of_strong_referrables: Option<Vec<ReferrableT>>,
+ pub co_owning_reference: u64,
+ pub vector_of_co_owning_references: Option<Vec<u64>>,
+ pub non_owning_reference: u64,
+ pub vector_of_non_owning_references: Option<Vec<u64>>,
+ pub any_unique: AnyUniqueAliasesT,
+ pub any_ambiguous: AnyAmbiguousAliasesT,
+ pub vector_of_enums: Option<Vec<Color>>,
+ pub signed_enum: Race,
+ pub testrequirednestedflatbuffer: Option<Vec<u8>>,
+ pub scalar_key_sorted_tables: Option<Vec<StatT>>,
+ pub native_inline: Option<TestT>,
+ pub long_enum_non_enum_default: LongEnum,
+ pub long_enum_normal_default: LongEnum,
+}
+impl Default for MonsterT {
+ fn default() -> Self {
+ Self {
+ pos: None,
+ mana: 150,
+ hp: 100,
+ name: "".to_string(),
+ inventory: None,
+ color: Color::Blue,
+ test: AnyT::NONE,
+ test4: None,
+ testarrayofstring: None,
+ testarrayoftables: None,
+ enemy: None,
+ testnestedflatbuffer: None,
+ testempty: None,
+ testbool: false,
+ testhashs32_fnv1: 0,
+ testhashu32_fnv1: 0,
+ testhashs64_fnv1: 0,
+ testhashu64_fnv1: 0,
+ testhashs32_fnv1a: 0,
+ testhashu32_fnv1a: 0,
+ testhashs64_fnv1a: 0,
+ testhashu64_fnv1a: 0,
+ testarrayofbools: None,
+ testf: 3.14159,
+ testf2: 3.0,
+ testf3: 0.0,
+ testarrayofstring2: None,
+ testarrayofsortedstruct: None,
+ flex: None,
+ test5: None,
+ vector_of_longs: None,
+ vector_of_doubles: None,
+ parent_namespace_test: None,
+ vector_of_referrables: None,
+ single_weak_reference: 0,
+ vector_of_weak_references: None,
+ vector_of_strong_referrables: None,
+ co_owning_reference: 0,
+ vector_of_co_owning_references: None,
+ non_owning_reference: 0,
+ vector_of_non_owning_references: None,
+ any_unique: AnyUniqueAliasesT::NONE,
+ any_ambiguous: AnyAmbiguousAliasesT::NONE,
+ vector_of_enums: None,
+ signed_enum: Race::None,
+ testrequirednestedflatbuffer: None,
+ scalar_key_sorted_tables: None,
+ native_inline: None,
+ long_enum_non_enum_default: Default::default(),
+ long_enum_normal_default: LongEnum::LongOne,
+ }
+ }
+}
+impl MonsterT {
+ pub fn pack<'b>(
+ &self,
+ _fbb: &mut flatbuffers::FlatBufferBuilder<'b>
+ ) -> flatbuffers::WIPOffset<Monster<'b>> {
+ let pos_tmp = self.pos.as_ref().map(|x| x.pack());
+ let pos = pos_tmp.as_ref();
+ let mana = self.mana;
+ let hp = self.hp;
+ let name = Some({
+ let x = &self.name;
+ _fbb.create_string(x)
+ });
+ let inventory = self.inventory.as_ref().map(|x|{
+ _fbb.create_vector(x)
+ });
+ let color = self.color;
+ let test_type = self.test.any_type();
+ let test = self.test.pack(_fbb);
+ let test4 = self.test4.as_ref().map(|x|{
+ let w: Vec<_> = x.iter().map(|t| t.pack()).collect();_fbb.create_vector(&w)
+ });
+ let testarrayofstring = self.testarrayofstring.as_ref().map(|x|{
+ let w: Vec<_> = x.iter().map(|s| s.as_ref()).collect();_fbb.create_vector_of_strings(&w)
+ });
+ let testarrayoftables = self.testarrayoftables.as_ref().map(|x|{
+ let w: Vec<_> = x.iter().map(|t| t.pack(_fbb)).collect();_fbb.create_vector(&w)
+ });
+ let enemy = self.enemy.as_ref().map(|x|{
+ x.pack(_fbb)
+ });
+ let testnestedflatbuffer = self.testnestedflatbuffer.as_ref().map(|x|{
+ _fbb.create_vector(x)
+ });
+ let testempty = self.testempty.as_ref().map(|x|{
+ x.pack(_fbb)
+ });
+ let testbool = self.testbool;
+ let testhashs32_fnv1 = self.testhashs32_fnv1;
+ let testhashu32_fnv1 = self.testhashu32_fnv1;
+ let testhashs64_fnv1 = self.testhashs64_fnv1;
+ let testhashu64_fnv1 = self.testhashu64_fnv1;
+ let testhashs32_fnv1a = self.testhashs32_fnv1a;
+ let testhashu32_fnv1a = self.testhashu32_fnv1a;
+ let testhashs64_fnv1a = self.testhashs64_fnv1a;
+ let testhashu64_fnv1a = self.testhashu64_fnv1a;
+ let testarrayofbools = self.testarrayofbools.as_ref().map(|x|{
+ _fbb.create_vector(x)
+ });
+ let testf = self.testf;
+ let testf2 = self.testf2;
+ let testf3 = self.testf3;
+ let testarrayofstring2 = self.testarrayofstring2.as_ref().map(|x|{
+ let w: Vec<_> = x.iter().map(|s| s.as_ref()).collect();_fbb.create_vector_of_strings(&w)
+ });
+ let testarrayofsortedstruct = self.testarrayofsortedstruct.as_ref().map(|x|{
+ let w: Vec<_> = x.iter().map(|t| t.pack()).collect();_fbb.create_vector(&w)
+ });
+ let flex = self.flex.as_ref().map(|x|{
+ _fbb.create_vector(x)
+ });
+ let test5 = self.test5.as_ref().map(|x|{
+ let w: Vec<_> = x.iter().map(|t| t.pack()).collect();_fbb.create_vector(&w)
+ });
+ let vector_of_longs = self.vector_of_longs.as_ref().map(|x|{
+ _fbb.create_vector(x)
+ });
+ let vector_of_doubles = self.vector_of_doubles.as_ref().map(|x|{
+ _fbb.create_vector(x)
+ });
+ let parent_namespace_test = self.parent_namespace_test.as_ref().map(|x|{
+ x.pack(_fbb)
+ });
+ let vector_of_referrables = self.vector_of_referrables.as_ref().map(|x|{
+ let w: Vec<_> = x.iter().map(|t| t.pack(_fbb)).collect();_fbb.create_vector(&w)
+ });
+ let single_weak_reference = self.single_weak_reference;
+ let vector_of_weak_references = self.vector_of_weak_references.as_ref().map(|x|{
+ _fbb.create_vector(x)
+ });
+ let vector_of_strong_referrables = self.vector_of_strong_referrables.as_ref().map(|x|{
+ let w: Vec<_> = x.iter().map(|t| t.pack(_fbb)).collect();_fbb.create_vector(&w)
+ });
+ let co_owning_reference = self.co_owning_reference;
+ let vector_of_co_owning_references = self.vector_of_co_owning_references.as_ref().map(|x|{
+ _fbb.create_vector(x)
+ });
+ let non_owning_reference = self.non_owning_reference;
+ let vector_of_non_owning_references = self.vector_of_non_owning_references.as_ref().map(|x|{
+ _fbb.create_vector(x)
+ });
+ let any_unique_type = self.any_unique.any_unique_aliases_type();
+ let any_unique = self.any_unique.pack(_fbb);
+ let any_ambiguous_type = self.any_ambiguous.any_ambiguous_aliases_type();
+ let any_ambiguous = self.any_ambiguous.pack(_fbb);
+ let vector_of_enums = self.vector_of_enums.as_ref().map(|x|{
+ _fbb.create_vector(x)
+ });
+ let signed_enum = self.signed_enum;
+ let testrequirednestedflatbuffer = self.testrequirednestedflatbuffer.as_ref().map(|x|{
+ _fbb.create_vector(x)
+ });
+ let scalar_key_sorted_tables = self.scalar_key_sorted_tables.as_ref().map(|x|{
+ let w: Vec<_> = x.iter().map(|t| t.pack(_fbb)).collect();_fbb.create_vector(&w)
+ });
+ let native_inline_tmp = self.native_inline.as_ref().map(|x| x.pack());
+ let native_inline = native_inline_tmp.as_ref();
+ let long_enum_non_enum_default = self.long_enum_non_enum_default;
+ let long_enum_normal_default = self.long_enum_normal_default;
+ Monster::create(_fbb, &MonsterArgs{
+ pos,
+ mana,
+ hp,
+ name,
+ inventory,
+ color,
+ test_type,
+ test,
+ test4,
+ testarrayofstring,
+ testarrayoftables,
+ enemy,
+ testnestedflatbuffer,
+ testempty,
+ testbool,
+ testhashs32_fnv1,
+ testhashu32_fnv1,
+ testhashs64_fnv1,
+ testhashu64_fnv1,
+ testhashs32_fnv1a,
+ testhashu32_fnv1a,
+ testhashs64_fnv1a,
+ testhashu64_fnv1a,
+ testarrayofbools,
+ testf,
+ testf2,
+ testf3,
+ testarrayofstring2,
+ testarrayofsortedstruct,
+ flex,
+ test5,
+ vector_of_longs,
+ vector_of_doubles,
+ parent_namespace_test,
+ vector_of_referrables,
+ single_weak_reference,
+ vector_of_weak_references,
+ vector_of_strong_referrables,
+ co_owning_reference,
+ vector_of_co_owning_references,
+ non_owning_reference,
+ vector_of_non_owning_references,
+ any_unique_type,
+ any_unique,
+ any_ambiguous_type,
+ any_ambiguous,
+ vector_of_enums,
+ signed_enum,
+ testrequirednestedflatbuffer,
+ scalar_key_sorted_tables,
+ native_inline,
+ long_enum_non_enum_default,
+ long_enum_normal_default,
+ })
+ }
+}
+#[inline]
+#[deprecated(since="2.0.0", note="Deprecated in favor of `root_as...` methods.")]
+pub fn get_root_as_monster<'a>(buf: &'a [u8]) -> Monster<'a> {
+ unsafe { flatbuffers::root_unchecked::<Monster<'a>>(buf) }
+}
+
+#[inline]
+#[deprecated(since="2.0.0", note="Deprecated in favor of `root_as...` methods.")]
+pub fn get_size_prefixed_root_as_monster<'a>(buf: &'a [u8]) -> Monster<'a> {
+ unsafe { flatbuffers::size_prefixed_root_unchecked::<Monster<'a>>(buf) }
+}
+
+#[inline]
+/// Verifies that a buffer of bytes contains a `Monster`
+/// and returns it.
+/// Note that verification is still experimental and may not
+/// catch every error, or be maximally performant. For the
+/// previous, unchecked, behavior use
+/// `root_as_monster_unchecked`.
+pub fn root_as_monster(buf: &[u8]) -> Result<Monster, flatbuffers::InvalidFlatbuffer> {
+ flatbuffers::root::<Monster>(buf)
+}
+#[inline]
+/// Verifies that a buffer of bytes contains a size prefixed
+/// `Monster` and returns it.
+/// Note that verification is still experimental and may not
+/// catch every error, or be maximally performant. For the
+/// previous, unchecked, behavior use
+/// `size_prefixed_root_as_monster_unchecked`.
+pub fn size_prefixed_root_as_monster(buf: &[u8]) -> Result<Monster, flatbuffers::InvalidFlatbuffer> {
+ flatbuffers::size_prefixed_root::<Monster>(buf)
+}
+#[inline]
+/// Verifies, with the given options, that a buffer of bytes
+/// contains a `Monster` and returns it.
+/// Note that verification is still experimental and may not
+/// catch every error, or be maximally performant. For the
+/// previous, unchecked, behavior use
+/// `root_as_monster_unchecked`.
+pub fn root_as_monster_with_opts<'b, 'o>(
+ opts: &'o flatbuffers::VerifierOptions,
+ buf: &'b [u8],
+) -> Result<Monster<'b>, flatbuffers::InvalidFlatbuffer> {
+ flatbuffers::root_with_opts::<Monster<'b>>(opts, buf)
+}
+#[inline]
+/// Verifies, with the given verifier options, that a buffer of
+/// bytes contains a size prefixed `Monster` and returns
+/// it. Note that verification is still experimental and may not
+/// catch every error, or be maximally performant. For the
+/// previous, unchecked, behavior use
+/// `root_as_monster_unchecked`.
+pub fn size_prefixed_root_as_monster_with_opts<'b, 'o>(
+ opts: &'o flatbuffers::VerifierOptions,
+ buf: &'b [u8],
+) -> Result<Monster<'b>, flatbuffers::InvalidFlatbuffer> {
+ flatbuffers::size_prefixed_root_with_opts::<Monster<'b>>(opts, buf)
+}
+#[inline]
+/// Assumes, without verification, that a buffer of bytes contains a Monster and returns it.
+/// # Safety
+/// Callers must trust the given bytes do indeed contain a valid `Monster`.
+pub unsafe fn root_as_monster_unchecked(buf: &[u8]) -> Monster {
+ flatbuffers::root_unchecked::<Monster>(buf)
+}
+#[inline]
+/// Assumes, without verification, that a buffer of bytes contains a size prefixed Monster and returns it.
+/// # Safety
+/// Callers must trust the given bytes do indeed contain a valid size prefixed `Monster`.
+pub unsafe fn size_prefixed_root_as_monster_unchecked(buf: &[u8]) -> Monster {
+ flatbuffers::size_prefixed_root_unchecked::<Monster>(buf)
+}
+pub const MONSTER_IDENTIFIER: &str = "MONS";
+
+#[inline]
+pub fn monster_buffer_has_identifier(buf: &[u8]) -> bool {
+ flatbuffers::buffer_has_identifier(buf, MONSTER_IDENTIFIER, false)
+}
+
+#[inline]
+pub fn monster_size_prefixed_buffer_has_identifier(buf: &[u8]) -> bool {
+ flatbuffers::buffer_has_identifier(buf, MONSTER_IDENTIFIER, true)
+}
+
+pub const MONSTER_EXTENSION: &str = "mon";
+
+#[inline]
+pub fn finish_monster_buffer<'a, 'b>(
+ fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,
+ root: flatbuffers::WIPOffset<Monster<'a>>) {
+ fbb.finish(root, Some(MONSTER_IDENTIFIER));
+}
+
+#[inline]
+pub fn finish_size_prefixed_monster_buffer<'a, 'b>(fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>, root: flatbuffers::WIPOffset<Monster<'a>>) {
+ fbb.finish_size_prefixed(root, Some(MONSTER_IDENTIFIER));
+}
diff --git a/tests/monster_test/my_game/example/race_generated.rs b/tests/monster_test/my_game/example/race_generated.rs
new file mode 100644
index 0000000..ab012f9
--- /dev/null
+++ b/tests/monster_test/my_game/example/race_generated.rs
@@ -0,0 +1,101 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+pub const ENUM_MIN_RACE: i8 = -1;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+pub const ENUM_MAX_RACE: i8 = 2;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+#[allow(non_camel_case_types)]
+pub const ENUM_VALUES_RACE: [Race; 4] = [
+ Race::None,
+ Race::Human,
+ Race::Dwarf,
+ Race::Elf,
+];
+
+#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
+#[repr(transparent)]
+pub struct Race(pub i8);
+#[allow(non_upper_case_globals)]
+impl Race {
+ pub const None: Self = Self(-1);
+ pub const Human: Self = Self(0);
+ pub const Dwarf: Self = Self(1);
+ pub const Elf: Self = Self(2);
+
+ pub const ENUM_MIN: i8 = -1;
+ pub const ENUM_MAX: i8 = 2;
+ pub const ENUM_VALUES: &'static [Self] = &[
+ Self::None,
+ Self::Human,
+ Self::Dwarf,
+ Self::Elf,
+ ];
+ /// Returns the variant's name or "" if unknown.
+ pub fn variant_name(self) -> Option<&'static str> {
+ match self {
+ Self::None => Some("None"),
+ Self::Human => Some("Human"),
+ Self::Dwarf => Some("Dwarf"),
+ Self::Elf => Some("Elf"),
+ _ => None,
+ }
+ }
+}
+impl std::fmt::Debug for Race {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ if let Some(name) = self.variant_name() {
+ f.write_str(name)
+ } else {
+ f.write_fmt(format_args!("<UNKNOWN {:?}>", self.0))
+ }
+ }
+}
+impl<'a> flatbuffers::Follow<'a> for Race {
+ type Inner = Self;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ let b = unsafe {
+ flatbuffers::read_scalar_at::<i8>(buf, loc)
+ };
+ Self(b)
+ }
+}
+
+impl flatbuffers::Push for Race {
+ type Output = Race;
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ unsafe { flatbuffers::emplace_scalar::<i8>(dst, self.0); }
+ }
+}
+
+impl flatbuffers::EndianScalar for Race {
+ #[inline]
+ fn to_little_endian(self) -> Self {
+ let b = i8::to_le(self.0);
+ Self(b)
+ }
+ #[inline]
+ #[allow(clippy::wrong_self_convention)]
+ fn from_little_endian(self) -> Self {
+ let b = i8::from_le(self.0);
+ Self(b)
+ }
+}
+
+impl<'a> flatbuffers::Verifiable for Race {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ i8::run_verifier(v, pos)
+ }
+}
+
+impl flatbuffers::SimpleToVerifyInSlice for Race {}
diff --git a/tests/monster_test/my_game/example/referrable_generated.rs b/tests/monster_test/my_game/example/referrable_generated.rs
new file mode 100644
index 0000000..877e3b8
--- /dev/null
+++ b/tests/monster_test/my_game/example/referrable_generated.rs
@@ -0,0 +1,143 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+pub enum ReferrableOffset {}
+#[derive(Copy, Clone, PartialEq)]
+
+pub struct Referrable<'a> {
+ pub _tab: flatbuffers::Table<'a>,
+}
+
+impl<'a> flatbuffers::Follow<'a> for Referrable<'a> {
+ type Inner = Referrable<'a>;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ Self { _tab: flatbuffers::Table { buf, loc } }
+ }
+}
+
+impl<'a> Referrable<'a> {
+ pub const VT_ID: flatbuffers::VOffsetT = 4;
+
+ pub const fn get_fully_qualified_name() -> &'static str {
+ "MyGame.Example.Referrable"
+ }
+
+ #[inline]
+ pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
+ Referrable { _tab: table }
+ }
+ #[allow(unused_mut)]
+ pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
+ _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
+ args: &'args ReferrableArgs
+ ) -> flatbuffers::WIPOffset<Referrable<'bldr>> {
+ let mut builder = ReferrableBuilder::new(_fbb);
+ builder.add_id(args.id);
+ builder.finish()
+ }
+
+ pub fn unpack(&self) -> ReferrableT {
+ let id = self.id();
+ ReferrableT {
+ id,
+ }
+ }
+
+ #[inline]
+ pub fn id(&self) -> u64 {
+ self._tab.get::<u64>(Referrable::VT_ID, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn key_compare_less_than(&self, o: &Referrable) -> bool {
+ self.id() < o.id()
+ }
+
+ #[inline]
+ pub fn key_compare_with_value(&self, val: u64) -> ::std::cmp::Ordering {
+ let key = self.id();
+ key.cmp(&val)
+ }
+}
+
+impl flatbuffers::Verifiable for Referrable<'_> {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ v.visit_table(pos)?
+ .visit_field::<u64>("id", Self::VT_ID, false)?
+ .finish();
+ Ok(())
+ }
+}
+pub struct ReferrableArgs {
+ pub id: u64,
+}
+impl<'a> Default for ReferrableArgs {
+ #[inline]
+ fn default() -> Self {
+ ReferrableArgs {
+ id: 0,
+ }
+ }
+}
+
+pub struct ReferrableBuilder<'a: 'b, 'b> {
+ fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
+ start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
+}
+impl<'a: 'b, 'b> ReferrableBuilder<'a, 'b> {
+ #[inline]
+ pub fn add_id(&mut self, id: u64) {
+ self.fbb_.push_slot::<u64>(Referrable::VT_ID, id, 0);
+ }
+ #[inline]
+ pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> ReferrableBuilder<'a, 'b> {
+ let start = _fbb.start_table();
+ ReferrableBuilder {
+ fbb_: _fbb,
+ start_: start,
+ }
+ }
+ #[inline]
+ pub fn finish(self) -> flatbuffers::WIPOffset<Referrable<'a>> {
+ let o = self.fbb_.end_table(self.start_);
+ flatbuffers::WIPOffset::new(o.value())
+ }
+}
+
+impl std::fmt::Debug for Referrable<'_> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let mut ds = f.debug_struct("Referrable");
+ ds.field("id", &self.id());
+ ds.finish()
+ }
+}
+#[non_exhaustive]
+#[derive(Debug, Clone, PartialEq)]
+pub struct ReferrableT {
+ pub id: u64,
+}
+impl Default for ReferrableT {
+ fn default() -> Self {
+ Self {
+ id: 0,
+ }
+ }
+}
+impl ReferrableT {
+ pub fn pack<'b>(
+ &self,
+ _fbb: &mut flatbuffers::FlatBufferBuilder<'b>
+ ) -> flatbuffers::WIPOffset<Referrable<'b>> {
+ let id = self.id;
+ Referrable::create(_fbb, &ReferrableArgs{
+ id,
+ })
+ }
+}
diff --git a/tests/monster_test/my_game/example/stat_generated.rs b/tests/monster_test/my_game/example/stat_generated.rs
new file mode 100644
index 0000000..d6e5fad
--- /dev/null
+++ b/tests/monster_test/my_game/example/stat_generated.rs
@@ -0,0 +1,187 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+pub enum StatOffset {}
+#[derive(Copy, Clone, PartialEq)]
+
+pub struct Stat<'a> {
+ pub _tab: flatbuffers::Table<'a>,
+}
+
+impl<'a> flatbuffers::Follow<'a> for Stat<'a> {
+ type Inner = Stat<'a>;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ Self { _tab: flatbuffers::Table { buf, loc } }
+ }
+}
+
+impl<'a> Stat<'a> {
+ pub const VT_ID: flatbuffers::VOffsetT = 4;
+ pub const VT_VAL: flatbuffers::VOffsetT = 6;
+ pub const VT_COUNT: flatbuffers::VOffsetT = 8;
+
+ pub const fn get_fully_qualified_name() -> &'static str {
+ "MyGame.Example.Stat"
+ }
+
+ #[inline]
+ pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
+ Stat { _tab: table }
+ }
+ #[allow(unused_mut)]
+ pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
+ _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
+ args: &'args StatArgs<'args>
+ ) -> flatbuffers::WIPOffset<Stat<'bldr>> {
+ let mut builder = StatBuilder::new(_fbb);
+ builder.add_val(args.val);
+ if let Some(x) = args.id { builder.add_id(x); }
+ builder.add_count(args.count);
+ builder.finish()
+ }
+
+ pub fn unpack(&self) -> StatT {
+ let id = self.id().map(|x| {
+ x.to_string()
+ });
+ let val = self.val();
+ let count = self.count();
+ StatT {
+ id,
+ val,
+ count,
+ }
+ }
+
+ #[inline]
+ pub fn id(&self) -> Option<&'a str> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<&str>>(Stat::VT_ID, None)
+ }
+ #[inline]
+ pub fn val(&self) -> i64 {
+ self._tab.get::<i64>(Stat::VT_VAL, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn count(&self) -> u16 {
+ self._tab.get::<u16>(Stat::VT_COUNT, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn key_compare_less_than(&self, o: &Stat) -> bool {
+ self.count() < o.count()
+ }
+
+ #[inline]
+ pub fn key_compare_with_value(&self, val: u16) -> ::std::cmp::Ordering {
+ let key = self.count();
+ key.cmp(&val)
+ }
+}
+
+impl flatbuffers::Verifiable for Stat<'_> {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ v.visit_table(pos)?
+ .visit_field::<flatbuffers::ForwardsUOffset<&str>>("id", Self::VT_ID, false)?
+ .visit_field::<i64>("val", Self::VT_VAL, false)?
+ .visit_field::<u16>("count", Self::VT_COUNT, false)?
+ .finish();
+ Ok(())
+ }
+}
+pub struct StatArgs<'a> {
+ pub id: Option<flatbuffers::WIPOffset<&'a str>>,
+ pub val: i64,
+ pub count: u16,
+}
+impl<'a> Default for StatArgs<'a> {
+ #[inline]
+ fn default() -> Self {
+ StatArgs {
+ id: None,
+ val: 0,
+ count: 0,
+ }
+ }
+}
+
+pub struct StatBuilder<'a: 'b, 'b> {
+ fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
+ start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
+}
+impl<'a: 'b, 'b> StatBuilder<'a, 'b> {
+ #[inline]
+ pub fn add_id(&mut self, id: flatbuffers::WIPOffset<&'b str>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Stat::VT_ID, id);
+ }
+ #[inline]
+ pub fn add_val(&mut self, val: i64) {
+ self.fbb_.push_slot::<i64>(Stat::VT_VAL, val, 0);
+ }
+ #[inline]
+ pub fn add_count(&mut self, count: u16) {
+ self.fbb_.push_slot::<u16>(Stat::VT_COUNT, count, 0);
+ }
+ #[inline]
+ pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> StatBuilder<'a, 'b> {
+ let start = _fbb.start_table();
+ StatBuilder {
+ fbb_: _fbb,
+ start_: start,
+ }
+ }
+ #[inline]
+ pub fn finish(self) -> flatbuffers::WIPOffset<Stat<'a>> {
+ let o = self.fbb_.end_table(self.start_);
+ flatbuffers::WIPOffset::new(o.value())
+ }
+}
+
+impl std::fmt::Debug for Stat<'_> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let mut ds = f.debug_struct("Stat");
+ ds.field("id", &self.id());
+ ds.field("val", &self.val());
+ ds.field("count", &self.count());
+ ds.finish()
+ }
+}
+#[non_exhaustive]
+#[derive(Debug, Clone, PartialEq)]
+pub struct StatT {
+ pub id: Option<String>,
+ pub val: i64,
+ pub count: u16,
+}
+impl Default for StatT {
+ fn default() -> Self {
+ Self {
+ id: None,
+ val: 0,
+ count: 0,
+ }
+ }
+}
+impl StatT {
+ pub fn pack<'b>(
+ &self,
+ _fbb: &mut flatbuffers::FlatBufferBuilder<'b>
+ ) -> flatbuffers::WIPOffset<Stat<'b>> {
+ let id = self.id.as_ref().map(|x|{
+ _fbb.create_string(x)
+ });
+ let val = self.val;
+ let count = self.count;
+ Stat::create(_fbb, &StatArgs{
+ id,
+ val,
+ count,
+ })
+ }
+}
diff --git a/tests/monster_test/my_game/example/struct_of_structs_generated.rs b/tests/monster_test/my_game/example/struct_of_structs_generated.rs
new file mode 100644
index 0000000..9994f7e
--- /dev/null
+++ b/tests/monster_test/my_game/example/struct_of_structs_generated.rs
@@ -0,0 +1,143 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+// struct StructOfStructs, aligned to 4
+#[repr(transparent)]
+#[derive(Clone, Copy, PartialEq)]
+pub struct StructOfStructs(pub [u8; 20]);
+impl Default for StructOfStructs {
+ fn default() -> Self {
+ Self([0; 20])
+ }
+}
+impl std::fmt::Debug for StructOfStructs {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ f.debug_struct("StructOfStructs")
+ .field("a", &self.a())
+ .field("b", &self.b())
+ .field("c", &self.c())
+ .finish()
+ }
+}
+
+impl flatbuffers::SimpleToVerifyInSlice for StructOfStructs {}
+impl flatbuffers::SafeSliceAccess for StructOfStructs {}
+impl<'a> flatbuffers::Follow<'a> for StructOfStructs {
+ type Inner = &'a StructOfStructs;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ <&'a StructOfStructs>::follow(buf, loc)
+ }
+}
+impl<'a> flatbuffers::Follow<'a> for &'a StructOfStructs {
+ type Inner = &'a StructOfStructs;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ flatbuffers::follow_cast_ref::<StructOfStructs>(buf, loc)
+ }
+}
+impl<'b> flatbuffers::Push for StructOfStructs {
+ type Output = StructOfStructs;
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ let src = unsafe {
+ ::std::slice::from_raw_parts(self as *const StructOfStructs as *const u8, Self::size())
+ };
+ dst.copy_from_slice(src);
+ }
+}
+impl<'b> flatbuffers::Push for &'b StructOfStructs {
+ type Output = StructOfStructs;
+
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ let src = unsafe {
+ ::std::slice::from_raw_parts(*self as *const StructOfStructs as *const u8, Self::size())
+ };
+ dst.copy_from_slice(src);
+ }
+}
+
+impl<'a> flatbuffers::Verifiable for StructOfStructs {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ v.in_buffer::<Self>(pos)
+ }
+}
+
+impl<'a> StructOfStructs {
+ #[allow(clippy::too_many_arguments)]
+ pub fn new(
+ a: &Ability,
+ b: &Test,
+ c: &Ability,
+ ) -> Self {
+ let mut s = Self([0; 20]);
+ s.set_a(a);
+ s.set_b(b);
+ s.set_c(c);
+ s
+ }
+
+ pub const fn get_fully_qualified_name() -> &'static str {
+ "MyGame.Example.StructOfStructs"
+ }
+
+ pub fn a(&self) -> &Ability {
+ unsafe { &*(self.0[0..].as_ptr() as *const Ability) }
+ }
+
+ #[allow(clippy::identity_op)]
+ pub fn set_a(&mut self, x: &Ability) {
+ self.0[0..0 + 8].copy_from_slice(&x.0)
+ }
+
+ pub fn b(&self) -> &Test {
+ unsafe { &*(self.0[8..].as_ptr() as *const Test) }
+ }
+
+ #[allow(clippy::identity_op)]
+ pub fn set_b(&mut self, x: &Test) {
+ self.0[8..8 + 4].copy_from_slice(&x.0)
+ }
+
+ pub fn c(&self) -> &Ability {
+ unsafe { &*(self.0[12..].as_ptr() as *const Ability) }
+ }
+
+ #[allow(clippy::identity_op)]
+ pub fn set_c(&mut self, x: &Ability) {
+ self.0[12..12 + 8].copy_from_slice(&x.0)
+ }
+
+ pub fn unpack(&self) -> StructOfStructsT {
+ StructOfStructsT {
+ a: self.a().unpack(),
+ b: self.b().unpack(),
+ c: self.c().unpack(),
+ }
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Default)]
+pub struct StructOfStructsT {
+ pub a: AbilityT,
+ pub b: TestT,
+ pub c: AbilityT,
+}
+impl StructOfStructsT {
+ pub fn pack(&self) -> StructOfStructs {
+ StructOfStructs::new(
+ &self.a.pack(),
+ &self.b.pack(),
+ &self.c.pack(),
+ )
+ }
+}
+
diff --git a/tests/monster_test/my_game/example/test_generated.rs b/tests/monster_test/my_game/example/test_generated.rs
new file mode 100644
index 0000000..187b7cd
--- /dev/null
+++ b/tests/monster_test/my_game/example/test_generated.rs
@@ -0,0 +1,156 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+// struct Test, aligned to 2
+#[repr(transparent)]
+#[derive(Clone, Copy, PartialEq)]
+pub struct Test(pub [u8; 4]);
+impl Default for Test {
+ fn default() -> Self {
+ Self([0; 4])
+ }
+}
+impl std::fmt::Debug for Test {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ f.debug_struct("Test")
+ .field("a", &self.a())
+ .field("b", &self.b())
+ .finish()
+ }
+}
+
+impl flatbuffers::SimpleToVerifyInSlice for Test {}
+impl flatbuffers::SafeSliceAccess for Test {}
+impl<'a> flatbuffers::Follow<'a> for Test {
+ type Inner = &'a Test;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ <&'a Test>::follow(buf, loc)
+ }
+}
+impl<'a> flatbuffers::Follow<'a> for &'a Test {
+ type Inner = &'a Test;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ flatbuffers::follow_cast_ref::<Test>(buf, loc)
+ }
+}
+impl<'b> flatbuffers::Push for Test {
+ type Output = Test;
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ let src = unsafe {
+ ::std::slice::from_raw_parts(self as *const Test as *const u8, Self::size())
+ };
+ dst.copy_from_slice(src);
+ }
+}
+impl<'b> flatbuffers::Push for &'b Test {
+ type Output = Test;
+
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ let src = unsafe {
+ ::std::slice::from_raw_parts(*self as *const Test as *const u8, Self::size())
+ };
+ dst.copy_from_slice(src);
+ }
+}
+
+impl<'a> flatbuffers::Verifiable for Test {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ v.in_buffer::<Self>(pos)
+ }
+}
+
+impl<'a> Test {
+ #[allow(clippy::too_many_arguments)]
+ pub fn new(
+ a: i16,
+ b: i8,
+ ) -> Self {
+ let mut s = Self([0; 4]);
+ s.set_a(a);
+ s.set_b(b);
+ s
+ }
+
+ pub const fn get_fully_qualified_name() -> &'static str {
+ "MyGame.Example.Test"
+ }
+
+ pub fn a(&self) -> i16 {
+ let mut mem = core::mem::MaybeUninit::<i16>::uninit();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ self.0[0..].as_ptr(),
+ mem.as_mut_ptr() as *mut u8,
+ core::mem::size_of::<i16>(),
+ );
+ mem.assume_init()
+ }.from_little_endian()
+ }
+
+ pub fn set_a(&mut self, x: i16) {
+ let x_le = x.to_little_endian();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ &x_le as *const i16 as *const u8,
+ self.0[0..].as_mut_ptr(),
+ core::mem::size_of::<i16>(),
+ );
+ }
+ }
+
+ pub fn b(&self) -> i8 {
+ let mut mem = core::mem::MaybeUninit::<i8>::uninit();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ self.0[2..].as_ptr(),
+ mem.as_mut_ptr() as *mut u8,
+ core::mem::size_of::<i8>(),
+ );
+ mem.assume_init()
+ }.from_little_endian()
+ }
+
+ pub fn set_b(&mut self, x: i8) {
+ let x_le = x.to_little_endian();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ &x_le as *const i8 as *const u8,
+ self.0[2..].as_mut_ptr(),
+ core::mem::size_of::<i8>(),
+ );
+ }
+ }
+
+ pub fn unpack(&self) -> TestT {
+ TestT {
+ a: self.a(),
+ b: self.b(),
+ }
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Default)]
+pub struct TestT {
+ pub a: i16,
+ pub b: i8,
+}
+impl TestT {
+ pub fn pack(&self) -> Test {
+ Test::new(
+ self.a,
+ self.b,
+ )
+ }
+}
+
diff --git a/tests/monster_test/my_game/example/test_simple_table_with_enum_generated.rs b/tests/monster_test/my_game/example/test_simple_table_with_enum_generated.rs
new file mode 100644
index 0000000..6ebe31f
--- /dev/null
+++ b/tests/monster_test/my_game/example/test_simple_table_with_enum_generated.rs
@@ -0,0 +1,133 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+pub enum TestSimpleTableWithEnumOffset {}
+#[derive(Copy, Clone, PartialEq)]
+
+pub struct TestSimpleTableWithEnum<'a> {
+ pub _tab: flatbuffers::Table<'a>,
+}
+
+impl<'a> flatbuffers::Follow<'a> for TestSimpleTableWithEnum<'a> {
+ type Inner = TestSimpleTableWithEnum<'a>;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ Self { _tab: flatbuffers::Table { buf, loc } }
+ }
+}
+
+impl<'a> TestSimpleTableWithEnum<'a> {
+ pub const VT_COLOR: flatbuffers::VOffsetT = 4;
+
+ pub const fn get_fully_qualified_name() -> &'static str {
+ "MyGame.Example.TestSimpleTableWithEnum"
+ }
+
+ #[inline]
+ pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
+ TestSimpleTableWithEnum { _tab: table }
+ }
+ #[allow(unused_mut)]
+ pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
+ _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
+ args: &'args TestSimpleTableWithEnumArgs
+ ) -> flatbuffers::WIPOffset<TestSimpleTableWithEnum<'bldr>> {
+ let mut builder = TestSimpleTableWithEnumBuilder::new(_fbb);
+ builder.add_color(args.color);
+ builder.finish()
+ }
+
+ pub fn unpack(&self) -> TestSimpleTableWithEnumT {
+ let color = self.color();
+ TestSimpleTableWithEnumT {
+ color,
+ }
+ }
+
+ #[inline]
+ pub fn color(&self) -> Color {
+ self._tab.get::<Color>(TestSimpleTableWithEnum::VT_COLOR, Some(Color::Green)).unwrap()
+ }
+}
+
+impl flatbuffers::Verifiable for TestSimpleTableWithEnum<'_> {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ v.visit_table(pos)?
+ .visit_field::<Color>("color", Self::VT_COLOR, false)?
+ .finish();
+ Ok(())
+ }
+}
+pub struct TestSimpleTableWithEnumArgs {
+ pub color: Color,
+}
+impl<'a> Default for TestSimpleTableWithEnumArgs {
+ #[inline]
+ fn default() -> Self {
+ TestSimpleTableWithEnumArgs {
+ color: Color::Green,
+ }
+ }
+}
+
+pub struct TestSimpleTableWithEnumBuilder<'a: 'b, 'b> {
+ fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
+ start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
+}
+impl<'a: 'b, 'b> TestSimpleTableWithEnumBuilder<'a, 'b> {
+ #[inline]
+ pub fn add_color(&mut self, color: Color) {
+ self.fbb_.push_slot::<Color>(TestSimpleTableWithEnum::VT_COLOR, color, Color::Green);
+ }
+ #[inline]
+ pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> TestSimpleTableWithEnumBuilder<'a, 'b> {
+ let start = _fbb.start_table();
+ TestSimpleTableWithEnumBuilder {
+ fbb_: _fbb,
+ start_: start,
+ }
+ }
+ #[inline]
+ pub fn finish(self) -> flatbuffers::WIPOffset<TestSimpleTableWithEnum<'a>> {
+ let o = self.fbb_.end_table(self.start_);
+ flatbuffers::WIPOffset::new(o.value())
+ }
+}
+
+impl std::fmt::Debug for TestSimpleTableWithEnum<'_> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let mut ds = f.debug_struct("TestSimpleTableWithEnum");
+ ds.field("color", &self.color());
+ ds.finish()
+ }
+}
+#[non_exhaustive]
+#[derive(Debug, Clone, PartialEq)]
+pub struct TestSimpleTableWithEnumT {
+ pub color: Color,
+}
+impl Default for TestSimpleTableWithEnumT {
+ fn default() -> Self {
+ Self {
+ color: Color::Green,
+ }
+ }
+}
+impl TestSimpleTableWithEnumT {
+ pub fn pack<'b>(
+ &self,
+ _fbb: &mut flatbuffers::FlatBufferBuilder<'b>
+ ) -> flatbuffers::WIPOffset<TestSimpleTableWithEnum<'b>> {
+ let color = self.color;
+ TestSimpleTableWithEnum::create(_fbb, &TestSimpleTableWithEnumArgs{
+ color,
+ })
+ }
+}
diff --git a/tests/monster_test/my_game/example/type_aliases_generated.rs b/tests/monster_test/my_game/example/type_aliases_generated.rs
new file mode 100644
index 0000000..5b3ede5
--- /dev/null
+++ b/tests/monster_test/my_game/example/type_aliases_generated.rs
@@ -0,0 +1,361 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+pub enum TypeAliasesOffset {}
+#[derive(Copy, Clone, PartialEq)]
+
+pub struct TypeAliases<'a> {
+ pub _tab: flatbuffers::Table<'a>,
+}
+
+impl<'a> flatbuffers::Follow<'a> for TypeAliases<'a> {
+ type Inner = TypeAliases<'a>;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ Self { _tab: flatbuffers::Table { buf, loc } }
+ }
+}
+
+impl<'a> TypeAliases<'a> {
+ pub const VT_I8_: flatbuffers::VOffsetT = 4;
+ pub const VT_U8_: flatbuffers::VOffsetT = 6;
+ pub const VT_I16_: flatbuffers::VOffsetT = 8;
+ pub const VT_U16_: flatbuffers::VOffsetT = 10;
+ pub const VT_I32_: flatbuffers::VOffsetT = 12;
+ pub const VT_U32_: flatbuffers::VOffsetT = 14;
+ pub const VT_I64_: flatbuffers::VOffsetT = 16;
+ pub const VT_U64_: flatbuffers::VOffsetT = 18;
+ pub const VT_F32_: flatbuffers::VOffsetT = 20;
+ pub const VT_F64_: flatbuffers::VOffsetT = 22;
+ pub const VT_V8: flatbuffers::VOffsetT = 24;
+ pub const VT_VF64: flatbuffers::VOffsetT = 26;
+
+ pub const fn get_fully_qualified_name() -> &'static str {
+ "MyGame.Example.TypeAliases"
+ }
+
+ #[inline]
+ pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
+ TypeAliases { _tab: table }
+ }
+ #[allow(unused_mut)]
+ pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
+ _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
+ args: &'args TypeAliasesArgs<'args>
+ ) -> flatbuffers::WIPOffset<TypeAliases<'bldr>> {
+ let mut builder = TypeAliasesBuilder::new(_fbb);
+ builder.add_f64_(args.f64_);
+ builder.add_u64_(args.u64_);
+ builder.add_i64_(args.i64_);
+ if let Some(x) = args.vf64 { builder.add_vf64(x); }
+ if let Some(x) = args.v8 { builder.add_v8(x); }
+ builder.add_f32_(args.f32_);
+ builder.add_u32_(args.u32_);
+ builder.add_i32_(args.i32_);
+ builder.add_u16_(args.u16_);
+ builder.add_i16_(args.i16_);
+ builder.add_u8_(args.u8_);
+ builder.add_i8_(args.i8_);
+ builder.finish()
+ }
+
+ pub fn unpack(&self) -> TypeAliasesT {
+ let i8_ = self.i8_();
+ let u8_ = self.u8_();
+ let i16_ = self.i16_();
+ let u16_ = self.u16_();
+ let i32_ = self.i32_();
+ let u32_ = self.u32_();
+ let i64_ = self.i64_();
+ let u64_ = self.u64_();
+ let f32_ = self.f32_();
+ let f64_ = self.f64_();
+ let v8 = self.v8().map(|x| {
+ x.to_vec()
+ });
+ let vf64 = self.vf64().map(|x| {
+ x.into_iter().collect()
+ });
+ TypeAliasesT {
+ i8_,
+ u8_,
+ i16_,
+ u16_,
+ i32_,
+ u32_,
+ i64_,
+ u64_,
+ f32_,
+ f64_,
+ v8,
+ vf64,
+ }
+ }
+
+ #[inline]
+ pub fn i8_(&self) -> i8 {
+ self._tab.get::<i8>(TypeAliases::VT_I8_, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn u8_(&self) -> u8 {
+ self._tab.get::<u8>(TypeAliases::VT_U8_, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn i16_(&self) -> i16 {
+ self._tab.get::<i16>(TypeAliases::VT_I16_, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn u16_(&self) -> u16 {
+ self._tab.get::<u16>(TypeAliases::VT_U16_, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn i32_(&self) -> i32 {
+ self._tab.get::<i32>(TypeAliases::VT_I32_, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn u32_(&self) -> u32 {
+ self._tab.get::<u32>(TypeAliases::VT_U32_, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn i64_(&self) -> i64 {
+ self._tab.get::<i64>(TypeAliases::VT_I64_, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn u64_(&self) -> u64 {
+ self._tab.get::<u64>(TypeAliases::VT_U64_, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn f32_(&self) -> f32 {
+ self._tab.get::<f32>(TypeAliases::VT_F32_, Some(0.0)).unwrap()
+ }
+ #[inline]
+ pub fn f64_(&self) -> f64 {
+ self._tab.get::<f64>(TypeAliases::VT_F64_, Some(0.0)).unwrap()
+ }
+ #[inline]
+ pub fn v8(&self) -> Option<&'a [i8]> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, i8>>>(TypeAliases::VT_V8, None).map(|v| v.safe_slice())
+ }
+ #[inline]
+ pub fn vf64(&self) -> Option<flatbuffers::Vector<'a, f64>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, f64>>>(TypeAliases::VT_VF64, None)
+ }
+}
+
+impl flatbuffers::Verifiable for TypeAliases<'_> {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ v.visit_table(pos)?
+ .visit_field::<i8>("i8_", Self::VT_I8_, false)?
+ .visit_field::<u8>("u8_", Self::VT_U8_, false)?
+ .visit_field::<i16>("i16_", Self::VT_I16_, false)?
+ .visit_field::<u16>("u16_", Self::VT_U16_, false)?
+ .visit_field::<i32>("i32_", Self::VT_I32_, false)?
+ .visit_field::<u32>("u32_", Self::VT_U32_, false)?
+ .visit_field::<i64>("i64_", Self::VT_I64_, false)?
+ .visit_field::<u64>("u64_", Self::VT_U64_, false)?
+ .visit_field::<f32>("f32_", Self::VT_F32_, false)?
+ .visit_field::<f64>("f64_", Self::VT_F64_, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, i8>>>("v8", Self::VT_V8, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, f64>>>("vf64", Self::VT_VF64, false)?
+ .finish();
+ Ok(())
+ }
+}
+pub struct TypeAliasesArgs<'a> {
+ pub i8_: i8,
+ pub u8_: u8,
+ pub i16_: i16,
+ pub u16_: u16,
+ pub i32_: i32,
+ pub u32_: u32,
+ pub i64_: i64,
+ pub u64_: u64,
+ pub f32_: f32,
+ pub f64_: f64,
+ pub v8: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, i8>>>,
+ pub vf64: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, f64>>>,
+}
+impl<'a> Default for TypeAliasesArgs<'a> {
+ #[inline]
+ fn default() -> Self {
+ TypeAliasesArgs {
+ i8_: 0,
+ u8_: 0,
+ i16_: 0,
+ u16_: 0,
+ i32_: 0,
+ u32_: 0,
+ i64_: 0,
+ u64_: 0,
+ f32_: 0.0,
+ f64_: 0.0,
+ v8: None,
+ vf64: None,
+ }
+ }
+}
+
+pub struct TypeAliasesBuilder<'a: 'b, 'b> {
+ fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
+ start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
+}
+impl<'a: 'b, 'b> TypeAliasesBuilder<'a, 'b> {
+ #[inline]
+ pub fn add_i8_(&mut self, i8_: i8) {
+ self.fbb_.push_slot::<i8>(TypeAliases::VT_I8_, i8_, 0);
+ }
+ #[inline]
+ pub fn add_u8_(&mut self, u8_: u8) {
+ self.fbb_.push_slot::<u8>(TypeAliases::VT_U8_, u8_, 0);
+ }
+ #[inline]
+ pub fn add_i16_(&mut self, i16_: i16) {
+ self.fbb_.push_slot::<i16>(TypeAliases::VT_I16_, i16_, 0);
+ }
+ #[inline]
+ pub fn add_u16_(&mut self, u16_: u16) {
+ self.fbb_.push_slot::<u16>(TypeAliases::VT_U16_, u16_, 0);
+ }
+ #[inline]
+ pub fn add_i32_(&mut self, i32_: i32) {
+ self.fbb_.push_slot::<i32>(TypeAliases::VT_I32_, i32_, 0);
+ }
+ #[inline]
+ pub fn add_u32_(&mut self, u32_: u32) {
+ self.fbb_.push_slot::<u32>(TypeAliases::VT_U32_, u32_, 0);
+ }
+ #[inline]
+ pub fn add_i64_(&mut self, i64_: i64) {
+ self.fbb_.push_slot::<i64>(TypeAliases::VT_I64_, i64_, 0);
+ }
+ #[inline]
+ pub fn add_u64_(&mut self, u64_: u64) {
+ self.fbb_.push_slot::<u64>(TypeAliases::VT_U64_, u64_, 0);
+ }
+ #[inline]
+ pub fn add_f32_(&mut self, f32_: f32) {
+ self.fbb_.push_slot::<f32>(TypeAliases::VT_F32_, f32_, 0.0);
+ }
+ #[inline]
+ pub fn add_f64_(&mut self, f64_: f64) {
+ self.fbb_.push_slot::<f64>(TypeAliases::VT_F64_, f64_, 0.0);
+ }
+ #[inline]
+ pub fn add_v8(&mut self, v8: flatbuffers::WIPOffset<flatbuffers::Vector<'b , i8>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(TypeAliases::VT_V8, v8);
+ }
+ #[inline]
+ pub fn add_vf64(&mut self, vf64: flatbuffers::WIPOffset<flatbuffers::Vector<'b , f64>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(TypeAliases::VT_VF64, vf64);
+ }
+ #[inline]
+ pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> TypeAliasesBuilder<'a, 'b> {
+ let start = _fbb.start_table();
+ TypeAliasesBuilder {
+ fbb_: _fbb,
+ start_: start,
+ }
+ }
+ #[inline]
+ pub fn finish(self) -> flatbuffers::WIPOffset<TypeAliases<'a>> {
+ let o = self.fbb_.end_table(self.start_);
+ flatbuffers::WIPOffset::new(o.value())
+ }
+}
+
+impl std::fmt::Debug for TypeAliases<'_> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let mut ds = f.debug_struct("TypeAliases");
+ ds.field("i8_", &self.i8_());
+ ds.field("u8_", &self.u8_());
+ ds.field("i16_", &self.i16_());
+ ds.field("u16_", &self.u16_());
+ ds.field("i32_", &self.i32_());
+ ds.field("u32_", &self.u32_());
+ ds.field("i64_", &self.i64_());
+ ds.field("u64_", &self.u64_());
+ ds.field("f32_", &self.f32_());
+ ds.field("f64_", &self.f64_());
+ ds.field("v8", &self.v8());
+ ds.field("vf64", &self.vf64());
+ ds.finish()
+ }
+}
+#[non_exhaustive]
+#[derive(Debug, Clone, PartialEq)]
+pub struct TypeAliasesT {
+ pub i8_: i8,
+ pub u8_: u8,
+ pub i16_: i16,
+ pub u16_: u16,
+ pub i32_: i32,
+ pub u32_: u32,
+ pub i64_: i64,
+ pub u64_: u64,
+ pub f32_: f32,
+ pub f64_: f64,
+ pub v8: Option<Vec<i8>>,
+ pub vf64: Option<Vec<f64>>,
+}
+impl Default for TypeAliasesT {
+ fn default() -> Self {
+ Self {
+ i8_: 0,
+ u8_: 0,
+ i16_: 0,
+ u16_: 0,
+ i32_: 0,
+ u32_: 0,
+ i64_: 0,
+ u64_: 0,
+ f32_: 0.0,
+ f64_: 0.0,
+ v8: None,
+ vf64: None,
+ }
+ }
+}
+impl TypeAliasesT {
+ pub fn pack<'b>(
+ &self,
+ _fbb: &mut flatbuffers::FlatBufferBuilder<'b>
+ ) -> flatbuffers::WIPOffset<TypeAliases<'b>> {
+ let i8_ = self.i8_;
+ let u8_ = self.u8_;
+ let i16_ = self.i16_;
+ let u16_ = self.u16_;
+ let i32_ = self.i32_;
+ let u32_ = self.u32_;
+ let i64_ = self.i64_;
+ let u64_ = self.u64_;
+ let f32_ = self.f32_;
+ let f64_ = self.f64_;
+ let v8 = self.v8.as_ref().map(|x|{
+ _fbb.create_vector(x)
+ });
+ let vf64 = self.vf64.as_ref().map(|x|{
+ _fbb.create_vector(x)
+ });
+ TypeAliases::create(_fbb, &TypeAliasesArgs{
+ i8_,
+ u8_,
+ i16_,
+ u16_,
+ i32_,
+ u32_,
+ i64_,
+ u64_,
+ f32_,
+ f64_,
+ v8,
+ vf64,
+ })
+ }
+}
diff --git a/tests/monster_test/my_game/example/vec_3_generated.rs b/tests/monster_test/my_game/example/vec_3_generated.rs
new file mode 100644
index 0000000..e5a25bb
--- /dev/null
+++ b/tests/monster_test/my_game/example/vec_3_generated.rs
@@ -0,0 +1,258 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+// struct Vec3, aligned to 8
+#[repr(transparent)]
+#[derive(Clone, Copy, PartialEq)]
+pub struct Vec3(pub [u8; 32]);
+impl Default for Vec3 {
+ fn default() -> Self {
+ Self([0; 32])
+ }
+}
+impl std::fmt::Debug for Vec3 {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ f.debug_struct("Vec3")
+ .field("x", &self.x())
+ .field("y", &self.y())
+ .field("z", &self.z())
+ .field("test1", &self.test1())
+ .field("test2", &self.test2())
+ .field("test3", &self.test3())
+ .finish()
+ }
+}
+
+impl flatbuffers::SimpleToVerifyInSlice for Vec3 {}
+impl flatbuffers::SafeSliceAccess for Vec3 {}
+impl<'a> flatbuffers::Follow<'a> for Vec3 {
+ type Inner = &'a Vec3;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ <&'a Vec3>::follow(buf, loc)
+ }
+}
+impl<'a> flatbuffers::Follow<'a> for &'a Vec3 {
+ type Inner = &'a Vec3;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ flatbuffers::follow_cast_ref::<Vec3>(buf, loc)
+ }
+}
+impl<'b> flatbuffers::Push for Vec3 {
+ type Output = Vec3;
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ let src = unsafe {
+ ::std::slice::from_raw_parts(self as *const Vec3 as *const u8, Self::size())
+ };
+ dst.copy_from_slice(src);
+ }
+}
+impl<'b> flatbuffers::Push for &'b Vec3 {
+ type Output = Vec3;
+
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ let src = unsafe {
+ ::std::slice::from_raw_parts(*self as *const Vec3 as *const u8, Self::size())
+ };
+ dst.copy_from_slice(src);
+ }
+}
+
+impl<'a> flatbuffers::Verifiable for Vec3 {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ v.in_buffer::<Self>(pos)
+ }
+}
+
+impl<'a> Vec3 {
+ #[allow(clippy::too_many_arguments)]
+ pub fn new(
+ x: f32,
+ y: f32,
+ z: f32,
+ test1: f64,
+ test2: Color,
+ test3: &Test,
+ ) -> Self {
+ let mut s = Self([0; 32]);
+ s.set_x(x);
+ s.set_y(y);
+ s.set_z(z);
+ s.set_test1(test1);
+ s.set_test2(test2);
+ s.set_test3(test3);
+ s
+ }
+
+ pub const fn get_fully_qualified_name() -> &'static str {
+ "MyGame.Example.Vec3"
+ }
+
+ pub fn x(&self) -> f32 {
+ let mut mem = core::mem::MaybeUninit::<f32>::uninit();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ self.0[0..].as_ptr(),
+ mem.as_mut_ptr() as *mut u8,
+ core::mem::size_of::<f32>(),
+ );
+ mem.assume_init()
+ }.from_little_endian()
+ }
+
+ pub fn set_x(&mut self, x: f32) {
+ let x_le = x.to_little_endian();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ &x_le as *const f32 as *const u8,
+ self.0[0..].as_mut_ptr(),
+ core::mem::size_of::<f32>(),
+ );
+ }
+ }
+
+ pub fn y(&self) -> f32 {
+ let mut mem = core::mem::MaybeUninit::<f32>::uninit();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ self.0[4..].as_ptr(),
+ mem.as_mut_ptr() as *mut u8,
+ core::mem::size_of::<f32>(),
+ );
+ mem.assume_init()
+ }.from_little_endian()
+ }
+
+ pub fn set_y(&mut self, x: f32) {
+ let x_le = x.to_little_endian();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ &x_le as *const f32 as *const u8,
+ self.0[4..].as_mut_ptr(),
+ core::mem::size_of::<f32>(),
+ );
+ }
+ }
+
+ pub fn z(&self) -> f32 {
+ let mut mem = core::mem::MaybeUninit::<f32>::uninit();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ self.0[8..].as_ptr(),
+ mem.as_mut_ptr() as *mut u8,
+ core::mem::size_of::<f32>(),
+ );
+ mem.assume_init()
+ }.from_little_endian()
+ }
+
+ pub fn set_z(&mut self, x: f32) {
+ let x_le = x.to_little_endian();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ &x_le as *const f32 as *const u8,
+ self.0[8..].as_mut_ptr(),
+ core::mem::size_of::<f32>(),
+ );
+ }
+ }
+
+ pub fn test1(&self) -> f64 {
+ let mut mem = core::mem::MaybeUninit::<f64>::uninit();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ self.0[16..].as_ptr(),
+ mem.as_mut_ptr() as *mut u8,
+ core::mem::size_of::<f64>(),
+ );
+ mem.assume_init()
+ }.from_little_endian()
+ }
+
+ pub fn set_test1(&mut self, x: f64) {
+ let x_le = x.to_little_endian();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ &x_le as *const f64 as *const u8,
+ self.0[16..].as_mut_ptr(),
+ core::mem::size_of::<f64>(),
+ );
+ }
+ }
+
+ pub fn test2(&self) -> Color {
+ let mut mem = core::mem::MaybeUninit::<Color>::uninit();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ self.0[24..].as_ptr(),
+ mem.as_mut_ptr() as *mut u8,
+ core::mem::size_of::<Color>(),
+ );
+ mem.assume_init()
+ }.from_little_endian()
+ }
+
+ pub fn set_test2(&mut self, x: Color) {
+ let x_le = x.to_little_endian();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ &x_le as *const Color as *const u8,
+ self.0[24..].as_mut_ptr(),
+ core::mem::size_of::<Color>(),
+ );
+ }
+ }
+
+ pub fn test3(&self) -> &Test {
+ unsafe { &*(self.0[26..].as_ptr() as *const Test) }
+ }
+
+ #[allow(clippy::identity_op)]
+ pub fn set_test3(&mut self, x: &Test) {
+ self.0[26..26 + 4].copy_from_slice(&x.0)
+ }
+
+ pub fn unpack(&self) -> Vec3T {
+ Vec3T {
+ x: self.x(),
+ y: self.y(),
+ z: self.z(),
+ test1: self.test1(),
+ test2: self.test2(),
+ test3: self.test3().unpack(),
+ }
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Default)]
+pub struct Vec3T {
+ pub x: f32,
+ pub y: f32,
+ pub z: f32,
+ pub test1: f64,
+ pub test2: Color,
+ pub test3: TestT,
+}
+impl Vec3T {
+ pub fn pack(&self) -> Vec3 {
+ Vec3::new(
+ self.x,
+ self.y,
+ self.z,
+ self.test1,
+ self.test2,
+ &self.test3.pack(),
+ )
+ }
+}
+
diff --git a/tests/monster_test/my_game/example_2/monster_generated.rs b/tests/monster_test/my_game/example_2/monster_generated.rs
new file mode 100644
index 0000000..54384b5
--- /dev/null
+++ b/tests/monster_test/my_game/example_2/monster_generated.rs
@@ -0,0 +1,112 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+pub enum MonsterOffset {}
+#[derive(Copy, Clone, PartialEq)]
+
+pub struct Monster<'a> {
+ pub _tab: flatbuffers::Table<'a>,
+}
+
+impl<'a> flatbuffers::Follow<'a> for Monster<'a> {
+ type Inner = Monster<'a>;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ Self { _tab: flatbuffers::Table { buf, loc } }
+ }
+}
+
+impl<'a> Monster<'a> {
+
+ pub const fn get_fully_qualified_name() -> &'static str {
+ "MyGame.Example2.Monster"
+ }
+
+ #[inline]
+ pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
+ Monster { _tab: table }
+ }
+ #[allow(unused_mut)]
+ pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
+ _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
+ _args: &'args MonsterArgs
+ ) -> flatbuffers::WIPOffset<Monster<'bldr>> {
+ let mut builder = MonsterBuilder::new(_fbb);
+ builder.finish()
+ }
+
+ pub fn unpack(&self) -> MonsterT {
+ MonsterT {
+ }
+ }
+}
+
+impl flatbuffers::Verifiable for Monster<'_> {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ v.visit_table(pos)?
+ .finish();
+ Ok(())
+ }
+}
+pub struct MonsterArgs {
+}
+impl<'a> Default for MonsterArgs {
+ #[inline]
+ fn default() -> Self {
+ MonsterArgs {
+ }
+ }
+}
+
+pub struct MonsterBuilder<'a: 'b, 'b> {
+ fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
+ start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
+}
+impl<'a: 'b, 'b> MonsterBuilder<'a, 'b> {
+ #[inline]
+ pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> MonsterBuilder<'a, 'b> {
+ let start = _fbb.start_table();
+ MonsterBuilder {
+ fbb_: _fbb,
+ start_: start,
+ }
+ }
+ #[inline]
+ pub fn finish(self) -> flatbuffers::WIPOffset<Monster<'a>> {
+ let o = self.fbb_.end_table(self.start_);
+ flatbuffers::WIPOffset::new(o.value())
+ }
+}
+
+impl std::fmt::Debug for Monster<'_> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let mut ds = f.debug_struct("Monster");
+ ds.finish()
+ }
+}
+#[non_exhaustive]
+#[derive(Debug, Clone, PartialEq)]
+pub struct MonsterT {
+}
+impl Default for MonsterT {
+ fn default() -> Self {
+ Self {
+ }
+ }
+}
+impl MonsterT {
+ pub fn pack<'b>(
+ &self,
+ _fbb: &mut flatbuffers::FlatBufferBuilder<'b>
+ ) -> flatbuffers::WIPOffset<Monster<'b>> {
+ Monster::create(_fbb, &MonsterArgs{
+ })
+ }
+}
diff --git a/tests/monster_test/my_game/in_parent_namespace_generated.rs b/tests/monster_test/my_game/in_parent_namespace_generated.rs
new file mode 100644
index 0000000..aabd4b8
--- /dev/null
+++ b/tests/monster_test/my_game/in_parent_namespace_generated.rs
@@ -0,0 +1,112 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+pub enum InParentNamespaceOffset {}
+#[derive(Copy, Clone, PartialEq)]
+
+pub struct InParentNamespace<'a> {
+ pub _tab: flatbuffers::Table<'a>,
+}
+
+impl<'a> flatbuffers::Follow<'a> for InParentNamespace<'a> {
+ type Inner = InParentNamespace<'a>;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ Self { _tab: flatbuffers::Table { buf, loc } }
+ }
+}
+
+impl<'a> InParentNamespace<'a> {
+
+ pub const fn get_fully_qualified_name() -> &'static str {
+ "MyGame.InParentNamespace"
+ }
+
+ #[inline]
+ pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
+ InParentNamespace { _tab: table }
+ }
+ #[allow(unused_mut)]
+ pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
+ _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
+ _args: &'args InParentNamespaceArgs
+ ) -> flatbuffers::WIPOffset<InParentNamespace<'bldr>> {
+ let mut builder = InParentNamespaceBuilder::new(_fbb);
+ builder.finish()
+ }
+
+ pub fn unpack(&self) -> InParentNamespaceT {
+ InParentNamespaceT {
+ }
+ }
+}
+
+impl flatbuffers::Verifiable for InParentNamespace<'_> {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ v.visit_table(pos)?
+ .finish();
+ Ok(())
+ }
+}
+pub struct InParentNamespaceArgs {
+}
+impl<'a> Default for InParentNamespaceArgs {
+ #[inline]
+ fn default() -> Self {
+ InParentNamespaceArgs {
+ }
+ }
+}
+
+pub struct InParentNamespaceBuilder<'a: 'b, 'b> {
+ fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
+ start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
+}
+impl<'a: 'b, 'b> InParentNamespaceBuilder<'a, 'b> {
+ #[inline]
+ pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> InParentNamespaceBuilder<'a, 'b> {
+ let start = _fbb.start_table();
+ InParentNamespaceBuilder {
+ fbb_: _fbb,
+ start_: start,
+ }
+ }
+ #[inline]
+ pub fn finish(self) -> flatbuffers::WIPOffset<InParentNamespace<'a>> {
+ let o = self.fbb_.end_table(self.start_);
+ flatbuffers::WIPOffset::new(o.value())
+ }
+}
+
+impl std::fmt::Debug for InParentNamespace<'_> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let mut ds = f.debug_struct("InParentNamespace");
+ ds.finish()
+ }
+}
+#[non_exhaustive]
+#[derive(Debug, Clone, PartialEq)]
+pub struct InParentNamespaceT {
+}
+impl Default for InParentNamespaceT {
+ fn default() -> Self {
+ Self {
+ }
+ }
+}
+impl InParentNamespaceT {
+ pub fn pack<'b>(
+ &self,
+ _fbb: &mut flatbuffers::FlatBufferBuilder<'b>
+ ) -> flatbuffers::WIPOffset<InParentNamespace<'b>> {
+ InParentNamespace::create(_fbb, &InParentNamespaceArgs{
+ })
+ }
+}
diff --git a/tests/monster_test/my_game/other_name_space/from_include_generated.rs b/tests/monster_test/my_game/other_name_space/from_include_generated.rs
new file mode 100644
index 0000000..048bafd
--- /dev/null
+++ b/tests/monster_test/my_game/other_name_space/from_include_generated.rs
@@ -0,0 +1,89 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+pub const ENUM_MIN_FROM_INCLUDE: i64 = 0;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+pub const ENUM_MAX_FROM_INCLUDE: i64 = 0;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+#[allow(non_camel_case_types)]
+pub const ENUM_VALUES_FROM_INCLUDE: [FromInclude; 1] = [
+ FromInclude::IncludeVal,
+];
+
+#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
+#[repr(transparent)]
+pub struct FromInclude(pub i64);
+#[allow(non_upper_case_globals)]
+impl FromInclude {
+ pub const IncludeVal: Self = Self(0);
+
+ pub const ENUM_MIN: i64 = 0;
+ pub const ENUM_MAX: i64 = 0;
+ pub const ENUM_VALUES: &'static [Self] = &[
+ Self::IncludeVal,
+ ];
+ /// Returns the variant's name or "" if unknown.
+ pub fn variant_name(self) -> Option<&'static str> {
+ match self {
+ Self::IncludeVal => Some("IncludeVal"),
+ _ => None,
+ }
+ }
+}
+impl std::fmt::Debug for FromInclude {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ if let Some(name) = self.variant_name() {
+ f.write_str(name)
+ } else {
+ f.write_fmt(format_args!("<UNKNOWN {:?}>", self.0))
+ }
+ }
+}
+impl<'a> flatbuffers::Follow<'a> for FromInclude {
+ type Inner = Self;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ let b = unsafe {
+ flatbuffers::read_scalar_at::<i64>(buf, loc)
+ };
+ Self(b)
+ }
+}
+
+impl flatbuffers::Push for FromInclude {
+ type Output = FromInclude;
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ unsafe { flatbuffers::emplace_scalar::<i64>(dst, self.0); }
+ }
+}
+
+impl flatbuffers::EndianScalar for FromInclude {
+ #[inline]
+ fn to_little_endian(self) -> Self {
+ let b = i64::to_le(self.0);
+ Self(b)
+ }
+ #[inline]
+ #[allow(clippy::wrong_self_convention)]
+ fn from_little_endian(self) -> Self {
+ let b = i64::from_le(self.0);
+ Self(b)
+ }
+}
+
+impl<'a> flatbuffers::Verifiable for FromInclude {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ i64::run_verifier(v, pos)
+ }
+}
+
+impl flatbuffers::SimpleToVerifyInSlice for FromInclude {}
diff --git a/tests/monster_test/my_game/other_name_space/table_b_generated.rs b/tests/monster_test/my_game/other_name_space/table_b_generated.rs
new file mode 100644
index 0000000..46a99cb
--- /dev/null
+++ b/tests/monster_test/my_game/other_name_space/table_b_generated.rs
@@ -0,0 +1,137 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+pub enum TableBOffset {}
+#[derive(Copy, Clone, PartialEq)]
+
+pub struct TableB<'a> {
+ pub _tab: flatbuffers::Table<'a>,
+}
+
+impl<'a> flatbuffers::Follow<'a> for TableB<'a> {
+ type Inner = TableB<'a>;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ Self { _tab: flatbuffers::Table { buf, loc } }
+ }
+}
+
+impl<'a> TableB<'a> {
+ pub const VT_A: flatbuffers::VOffsetT = 4;
+
+ pub const fn get_fully_qualified_name() -> &'static str {
+ "MyGame.OtherNameSpace.TableB"
+ }
+
+ #[inline]
+ pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
+ TableB { _tab: table }
+ }
+ #[allow(unused_mut)]
+ pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
+ _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
+ args: &'args TableBArgs<'args>
+ ) -> flatbuffers::WIPOffset<TableB<'bldr>> {
+ let mut builder = TableBBuilder::new(_fbb);
+ if let Some(x) = args.a { builder.add_a(x); }
+ builder.finish()
+ }
+
+ pub fn unpack(&self) -> TableBT {
+ let a = self.a().map(|x| {
+ Box::new(x.unpack())
+ });
+ TableBT {
+ a,
+ }
+ }
+
+ #[inline]
+ pub fn a(&self) -> Option<super::super::TableA<'a>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<super::super::TableA>>(TableB::VT_A, None)
+ }
+}
+
+impl flatbuffers::Verifiable for TableB<'_> {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ v.visit_table(pos)?
+ .visit_field::<flatbuffers::ForwardsUOffset<super::super::TableA>>("a", Self::VT_A, false)?
+ .finish();
+ Ok(())
+ }
+}
+pub struct TableBArgs<'a> {
+ pub a: Option<flatbuffers::WIPOffset<super::super::TableA<'a>>>,
+}
+impl<'a> Default for TableBArgs<'a> {
+ #[inline]
+ fn default() -> Self {
+ TableBArgs {
+ a: None,
+ }
+ }
+}
+
+pub struct TableBBuilder<'a: 'b, 'b> {
+ fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
+ start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
+}
+impl<'a: 'b, 'b> TableBBuilder<'a, 'b> {
+ #[inline]
+ pub fn add_a(&mut self, a: flatbuffers::WIPOffset<super::super::TableA<'b >>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<super::super::TableA>>(TableB::VT_A, a);
+ }
+ #[inline]
+ pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> TableBBuilder<'a, 'b> {
+ let start = _fbb.start_table();
+ TableBBuilder {
+ fbb_: _fbb,
+ start_: start,
+ }
+ }
+ #[inline]
+ pub fn finish(self) -> flatbuffers::WIPOffset<TableB<'a>> {
+ let o = self.fbb_.end_table(self.start_);
+ flatbuffers::WIPOffset::new(o.value())
+ }
+}
+
+impl std::fmt::Debug for TableB<'_> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let mut ds = f.debug_struct("TableB");
+ ds.field("a", &self.a());
+ ds.finish()
+ }
+}
+#[non_exhaustive]
+#[derive(Debug, Clone, PartialEq)]
+pub struct TableBT {
+ pub a: Option<Box<super::super::TableAT>>,
+}
+impl Default for TableBT {
+ fn default() -> Self {
+ Self {
+ a: None,
+ }
+ }
+}
+impl TableBT {
+ pub fn pack<'b>(
+ &self,
+ _fbb: &mut flatbuffers::FlatBufferBuilder<'b>
+ ) -> flatbuffers::WIPOffset<TableB<'b>> {
+ let a = self.a.as_ref().map(|x|{
+ x.pack(_fbb)
+ });
+ TableB::create(_fbb, &TableBArgs{
+ a,
+ })
+ }
+}
diff --git a/tests/monster_test/my_game/other_name_space/unused_generated.rs b/tests/monster_test/my_game/other_name_space/unused_generated.rs
new file mode 100644
index 0000000..1dc5913
--- /dev/null
+++ b/tests/monster_test/my_game/other_name_space/unused_generated.rs
@@ -0,0 +1,127 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+// struct Unused, aligned to 4
+#[repr(transparent)]
+#[derive(Clone, Copy, PartialEq)]
+pub struct Unused(pub [u8; 4]);
+impl Default for Unused {
+ fn default() -> Self {
+ Self([0; 4])
+ }
+}
+impl std::fmt::Debug for Unused {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ f.debug_struct("Unused")
+ .field("a", &self.a())
+ .finish()
+ }
+}
+
+impl flatbuffers::SimpleToVerifyInSlice for Unused {}
+impl flatbuffers::SafeSliceAccess for Unused {}
+impl<'a> flatbuffers::Follow<'a> for Unused {
+ type Inner = &'a Unused;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ <&'a Unused>::follow(buf, loc)
+ }
+}
+impl<'a> flatbuffers::Follow<'a> for &'a Unused {
+ type Inner = &'a Unused;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ flatbuffers::follow_cast_ref::<Unused>(buf, loc)
+ }
+}
+impl<'b> flatbuffers::Push for Unused {
+ type Output = Unused;
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ let src = unsafe {
+ ::std::slice::from_raw_parts(self as *const Unused as *const u8, Self::size())
+ };
+ dst.copy_from_slice(src);
+ }
+}
+impl<'b> flatbuffers::Push for &'b Unused {
+ type Output = Unused;
+
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ let src = unsafe {
+ ::std::slice::from_raw_parts(*self as *const Unused as *const u8, Self::size())
+ };
+ dst.copy_from_slice(src);
+ }
+}
+
+impl<'a> flatbuffers::Verifiable for Unused {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ v.in_buffer::<Self>(pos)
+ }
+}
+
+impl<'a> Unused {
+ #[allow(clippy::too_many_arguments)]
+ pub fn new(
+ a: i32,
+ ) -> Self {
+ let mut s = Self([0; 4]);
+ s.set_a(a);
+ s
+ }
+
+ pub const fn get_fully_qualified_name() -> &'static str {
+ "MyGame.OtherNameSpace.Unused"
+ }
+
+ pub fn a(&self) -> i32 {
+ let mut mem = core::mem::MaybeUninit::<i32>::uninit();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ self.0[0..].as_ptr(),
+ mem.as_mut_ptr() as *mut u8,
+ core::mem::size_of::<i32>(),
+ );
+ mem.assume_init()
+ }.from_little_endian()
+ }
+
+ pub fn set_a(&mut self, x: i32) {
+ let x_le = x.to_little_endian();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ &x_le as *const i32 as *const u8,
+ self.0[0..].as_mut_ptr(),
+ core::mem::size_of::<i32>(),
+ );
+ }
+ }
+
+ pub fn unpack(&self) -> UnusedT {
+ UnusedT {
+ a: self.a(),
+ }
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Default)]
+pub struct UnusedT {
+ pub a: i32,
+}
+impl UnusedT {
+ pub fn pack(&self) -> Unused {
+ Unused::new(
+ self.a,
+ )
+ }
+}
+
diff --git a/tests/monster_test/table_a_generated.rs b/tests/monster_test/table_a_generated.rs
new file mode 100644
index 0000000..9188b29
--- /dev/null
+++ b/tests/monster_test/table_a_generated.rs
@@ -0,0 +1,137 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+pub enum TableAOffset {}
+#[derive(Copy, Clone, PartialEq)]
+
+pub struct TableA<'a> {
+ pub _tab: flatbuffers::Table<'a>,
+}
+
+impl<'a> flatbuffers::Follow<'a> for TableA<'a> {
+ type Inner = TableA<'a>;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ Self { _tab: flatbuffers::Table { buf, loc } }
+ }
+}
+
+impl<'a> TableA<'a> {
+ pub const VT_B: flatbuffers::VOffsetT = 4;
+
+ pub const fn get_fully_qualified_name() -> &'static str {
+ "TableA"
+ }
+
+ #[inline]
+ pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
+ TableA { _tab: table }
+ }
+ #[allow(unused_mut)]
+ pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
+ _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
+ args: &'args TableAArgs<'args>
+ ) -> flatbuffers::WIPOffset<TableA<'bldr>> {
+ let mut builder = TableABuilder::new(_fbb);
+ if let Some(x) = args.b { builder.add_b(x); }
+ builder.finish()
+ }
+
+ pub fn unpack(&self) -> TableAT {
+ let b = self.b().map(|x| {
+ Box::new(x.unpack())
+ });
+ TableAT {
+ b,
+ }
+ }
+
+ #[inline]
+ pub fn b(&self) -> Option<my_game::other_name_space::TableB<'a>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<my_game::other_name_space::TableB>>(TableA::VT_B, None)
+ }
+}
+
+impl flatbuffers::Verifiable for TableA<'_> {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ v.visit_table(pos)?
+ .visit_field::<flatbuffers::ForwardsUOffset<my_game::other_name_space::TableB>>("b", Self::VT_B, false)?
+ .finish();
+ Ok(())
+ }
+}
+pub struct TableAArgs<'a> {
+ pub b: Option<flatbuffers::WIPOffset<my_game::other_name_space::TableB<'a>>>,
+}
+impl<'a> Default for TableAArgs<'a> {
+ #[inline]
+ fn default() -> Self {
+ TableAArgs {
+ b: None,
+ }
+ }
+}
+
+pub struct TableABuilder<'a: 'b, 'b> {
+ fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
+ start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
+}
+impl<'a: 'b, 'b> TableABuilder<'a, 'b> {
+ #[inline]
+ pub fn add_b(&mut self, b: flatbuffers::WIPOffset<my_game::other_name_space::TableB<'b >>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<my_game::other_name_space::TableB>>(TableA::VT_B, b);
+ }
+ #[inline]
+ pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> TableABuilder<'a, 'b> {
+ let start = _fbb.start_table();
+ TableABuilder {
+ fbb_: _fbb,
+ start_: start,
+ }
+ }
+ #[inline]
+ pub fn finish(self) -> flatbuffers::WIPOffset<TableA<'a>> {
+ let o = self.fbb_.end_table(self.start_);
+ flatbuffers::WIPOffset::new(o.value())
+ }
+}
+
+impl std::fmt::Debug for TableA<'_> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let mut ds = f.debug_struct("TableA");
+ ds.field("b", &self.b());
+ ds.finish()
+ }
+}
+#[non_exhaustive]
+#[derive(Debug, Clone, PartialEq)]
+pub struct TableAT {
+ pub b: Option<Box<my_game::other_name_space::TableBT>>,
+}
+impl Default for TableAT {
+ fn default() -> Self {
+ Self {
+ b: None,
+ }
+ }
+}
+impl TableAT {
+ pub fn pack<'b>(
+ &self,
+ _fbb: &mut flatbuffers::FlatBufferBuilder<'b>
+ ) -> flatbuffers::WIPOffset<TableA<'b>> {
+ let b = self.b.as_ref().map(|x|{
+ x.pack(_fbb)
+ });
+ TableA::create(_fbb, &TableAArgs{
+ b,
+ })
+ }
+}
diff --git a/tests/monster_test_bfbs_generated.h b/tests/monster_test_bfbs_generated.h
index b034fff..fc611db 100644
--- a/tests/monster_test_bfbs_generated.h
+++ b/tests/monster_test_bfbs_generated.h
@@ -4,646 +4,753 @@
#ifndef FLATBUFFERS_GENERATED_MONSTERTEST_MYGAME_EXAMPLE_BFBS_H_
#define FLATBUFFERS_GENERATED_MONSTERTEST_MYGAME_EXAMPLE_BFBS_H_
+#include "flatbuffers/flatbuffers.h"
+
namespace MyGame {
namespace Example {
struct MonsterBinarySchema {
static const uint8_t *data() {
// Buffer containing the binary schema.
- static const uint8_t bfbsData[12544] = {
- 0x18,0x00,0x00,0x00,0x42,0x46,0x42,0x53,0x10,0x00,0x1C,0x00,0x04,0x00,0x08,0x00,0x0C,0x00,0x10,0x00,
- 0x14,0x00,0x18,0x00,0x10,0x00,0x00,0x00,0x50,0x00,0x00,0x00,0x30,0x00,0x00,0x00,0x20,0x00,0x00,0x00,
- 0x14,0x00,0x00,0x00,0x1C,0x0C,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x78,0x00,0x00,0x00,
- 0x03,0x00,0x00,0x00,0x6D,0x6F,0x6E,0x00,0x04,0x00,0x00,0x00,0x4D,0x4F,0x4E,0x53,0x00,0x00,0x00,0x00,
- 0x06,0x00,0x00,0x00,0xCC,0x04,0x00,0x00,0x50,0x02,0x00,0x00,0x78,0x03,0x00,0x00,0x18,0x07,0x00,0x00,
- 0x0C,0x06,0x00,0x00,0xE0,0x08,0x00,0x00,0x0D,0x00,0x00,0x00,0x24,0x2A,0x00,0x00,0xD4,0x0B,0x00,0x00,
- 0x8C,0x28,0x00,0x00,0x5C,0x29,0x00,0x00,0xC0,0x2D,0x00,0x00,0xB8,0x2C,0x00,0x00,0x4C,0x09,0x00,0x00,
- 0xFC,0x2A,0x00,0x00,0x5C,0x2E,0x00,0x00,0x90,0x2E,0x00,0x00,0x30,0x2F,0x00,0x00,0xD4,0x2F,0x00,0x00,
- 0xC0,0x2E,0x00,0x00,0x0C,0x00,0x10,0x00,0x04,0x00,0x08,0x00,0x00,0x00,0x0C,0x00,0x0C,0x00,0x00,0x00,
- 0x24,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
- 0x88,0x01,0x00,0x00,0xF4,0x00,0x00,0x00,0x90,0x00,0x00,0x00,0x28,0x00,0x00,0x00,0x1D,0x00,0x00,0x00,
- 0x4D,0x79,0x47,0x61,0x6D,0x65,0x2E,0x45,0x78,0x61,0x6D,0x70,0x6C,0x65,0x2E,0x4D,0x6F,0x6E,0x73,0x74,
- 0x65,0x72,0x53,0x74,0x6F,0x72,0x61,0x67,0x65,0x00,0x00,0x00,0xBA,0xFE,0xFF,0xFF,0x48,0x00,0x00,0x00,
- 0x44,0x0B,0x00,0x00,0xD0,0x28,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
- 0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x9C,0xD3,0xFF,0xFF,0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x62,0x69,0x64,0x69,0x00,0x00,0x00,0x00,0x09,0x00,0x00,0x00,0x73,0x74,0x72,0x65,
- 0x61,0x6D,0x69,0x6E,0x67,0x00,0x00,0x00,0x12,0x00,0x00,0x00,0x47,0x65,0x74,0x4D,0x69,0x6E,0x4D,0x61,
- 0x78,0x48,0x69,0x74,0x50,0x6F,0x69,0x6E,0x74,0x73,0x00,0x00,0x1E,0xFF,0xFF,0xFF,0x48,0x00,0x00,0x00,
- 0xE0,0x0A,0x00,0x00,0x6C,0x28,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
- 0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0xD4,0xFF,0xFF,0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
- 0x06,0x00,0x00,0x00,0x63,0x6C,0x69,0x65,0x6E,0x74,0x00,0x00,0x09,0x00,0x00,0x00,0x73,0x74,0x72,0x65,
- 0x61,0x6D,0x69,0x6E,0x67,0x00,0x00,0x00,0x0E,0x00,0x00,0x00,0x47,0x65,0x74,0x4D,0x61,0x78,0x48,0x69,
- 0x74,0x50,0x6F,0x69,0x6E,0x74,0x00,0x00,0x7E,0xFF,0xFF,0xFF,0x70,0x00,0x00,0x00,0x10,0x28,0x00,0x00,
- 0x7C,0x0A,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x00,0x00,0x00,
- 0x30,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x64,0xD4,0xFF,0xFF,0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
- 0x06,0x00,0x00,0x00,0x73,0x65,0x72,0x76,0x65,0x72,0x00,0x00,0x09,0x00,0x00,0x00,0x73,0x74,0x72,0x65,
- 0x61,0x6D,0x69,0x6E,0x67,0x00,0x00,0x00,0x8C,0xD4,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
- 0x01,0x00,0x00,0x00,0x30,0x00,0x00,0x00,0x0A,0x00,0x00,0x00,0x69,0x64,0x65,0x6D,0x70,0x6F,0x74,0x65,
- 0x6E,0x74,0x00,0x00,0x08,0x00,0x00,0x00,0x52,0x65,0x74,0x72,0x69,0x65,0x76,0x65,0x00,0x00,0x0E,0x00,
- 0x18,0x00,0x04,0x00,0x08,0x00,0x0C,0x00,0x10,0x00,0x14,0x00,0x0E,0x00,0x00,0x00,0x48,0x00,0x00,0x00,
- 0xF0,0x09,0x00,0x00,0x7C,0x27,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
- 0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xF0,0xD4,0xFF,0xFF,0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x6E,0x6F,0x6E,0x65,0x00,0x00,0x00,0x00,0x09,0x00,0x00,0x00,0x73,0x74,0x72,0x65,
- 0x61,0x6D,0x69,0x6E,0x67,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0x53,0x74,0x6F,0x72,0x65,0x00,0x00,0x00,
- 0x98,0xFD,0xFF,0xFF,0x00,0x00,0x00,0x01,0x34,0x00,0x00,0x00,0x1C,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x82,0xD2,0xFF,0xFF,0x00,0x00,0x00,0x01,0x01,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0xDC,0x00,0x00,0x00,0xA4,0x00,0x00,0x00,0x68,0x00,0x00,0x00,0x2C,0x00,0x00,0x00,
- 0x22,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,0x6D,0x65,0x2E,0x45,0x78,0x61,0x6D,0x70,0x6C,0x65,0x2E,0x41,
- 0x6E,0x79,0x41,0x6D,0x62,0x69,0x67,0x75,0x6F,0x75,0x73,0x41,0x6C,0x69,0x61,0x73,0x65,0x73,0x00,0x00,
- 0x66,0xFE,0xFF,0xFF,0x2C,0x00,0x00,0x00,0x34,0x09,0x00,0x00,0x18,0x00,0x00,0x00,0x10,0x00,0x00,0x00,
- 0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xEE,0xD2,0xFF,0xFF,
- 0x00,0x00,0x00,0x0F,0x01,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x4D,0x33,0x00,0x00,0x9E,0xFE,0xFF,0xFF,
- 0x2C,0x00,0x00,0x00,0xFC,0x08,0x00,0x00,0x18,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x02,0x00,0x00,0x00,
- 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x26,0xD3,0xFF,0xFF,0x00,0x00,0x00,0x0F,
- 0x01,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x4D,0x32,0x00,0x00,0x76,0xFD,0xFF,0xFF,0x28,0x00,0x00,0x00,
- 0xC4,0x08,0x00,0x00,0x14,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
- 0x00,0x00,0x00,0x00,0x5A,0xD3,0xFF,0xFF,0x00,0x00,0x00,0x0F,0x01,0x00,0x00,0x00,0x02,0x00,0x00,0x00,
- 0x4D,0x31,0x00,0x00,0x16,0xFA,0xFF,0xFF,0x14,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
- 0x00,0x00,0x00,0x00,0x08,0xFA,0xFF,0xFF,0x04,0x00,0x00,0x00,0x4E,0x4F,0x4E,0x45,0x00,0x00,0x00,0x00,
- 0xC4,0xFE,0xFF,0xFF,0x00,0x00,0x00,0x01,0x34,0x00,0x00,0x00,0x1C,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xAE,0xD3,0xFF,0xFF,0x00,0x00,0x00,0x01,0x02,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0xEC,0x00,0x00,0x00,0xB0,0x00,0x00,0x00,0x64,0x00,0x00,0x00,0x28,0x00,0x00,0x00,
- 0x1F,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,0x6D,0x65,0x2E,0x45,0x78,0x61,0x6D,0x70,0x6C,0x65,0x2E,0x41,
- 0x6E,0x79,0x55,0x6E,0x69,0x71,0x75,0x65,0x41,0x6C,0x69,0x61,0x73,0x65,0x73,0x00,0x8E,0xFF,0xFF,0xFF,
- 0x2C,0x00,0x00,0x00,0xB0,0x2A,0x00,0x00,0x18,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x03,0x00,0x00,0x00,
- 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x16,0xD4,0xFF,0xFF,0x00,0x00,0x00,0x0F,
- 0x08,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x4D,0x32,0x00,0x00,0xC6,0xFF,0xFF,0xFF,0x2C,0x00,0x00,0x00,
- 0xC8,0x28,0x00,0x00,0x18,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
- 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x4E,0xD4,0xFF,0xFF,0x00,0x00,0x00,0x0F,0x05,0x00,0x00,0x00,
- 0x02,0x00,0x00,0x00,0x54,0x53,0x00,0x00,0x00,0x00,0x0E,0x00,0x20,0x00,0x04,0x00,0x14,0x00,0x08,0x00,
- 0x0C,0x00,0x10,0x00,0x0E,0x00,0x00,0x00,0x2C,0x00,0x00,0x00,0x8C,0x07,0x00,0x00,0x18,0x00,0x00,0x00,
- 0x10,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
- 0x96,0xD4,0xFF,0xFF,0x00,0x00,0x00,0x0F,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x4D,0x00,0x00,0x00,
- 0x52,0xFB,0xFF,0xFF,0x14,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
- 0x44,0xFB,0xFF,0xFF,0x04,0x00,0x00,0x00,0x4E,0x4F,0x4E,0x45,0x00,0x00,0x00,0x00,0x10,0x00,0x18,0x00,
- 0x08,0x00,0x0C,0x00,0x07,0x00,0x10,0x00,0x00,0x00,0x14,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x01,
- 0x34,0x00,0x00,0x00,0x1C,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
- 0xFA,0xD4,0xFF,0xFF,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x01,0x00,0x00,
- 0xC4,0x00,0x00,0x00,0x68,0x00,0x00,0x00,0x1C,0x00,0x00,0x00,0x12,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,
- 0x6D,0x65,0x2E,0x45,0x78,0x61,0x6D,0x70,0x6C,0x65,0x2E,0x41,0x6E,0x79,0x00,0x00,0x6E,0xFF,0xFF,0xFF,
- 0x28,0x00,0x00,0x00,0x70,0x29,0x00,0x00,0x14,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x03,0x00,0x00,0x00,
- 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x52,0xD5,0xFF,0xFF,0x00,0x00,0x00,0x0F,0x08,0x00,0x00,0x00,
- 0x17,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,0x6D,0x65,0x5F,0x45,0x78,0x61,0x6D,0x70,0x6C,0x65,0x32,0x5F,
- 0x4D,0x6F,0x6E,0x73,0x74,0x65,0x72,0x00,0xB6,0xFF,0xFF,0xFF,0x28,0x00,0x00,0x00,0x78,0x27,0x00,0x00,
- 0x14,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
- 0x9A,0xD5,0xFF,0xFF,0x00,0x00,0x00,0x0F,0x05,0x00,0x00,0x00,0x17,0x00,0x00,0x00,0x54,0x65,0x73,0x74,
- 0x53,0x69,0x6D,0x70,0x6C,0x65,0x54,0x61,0x62,0x6C,0x65,0x57,0x69,0x74,0x68,0x45,0x6E,0x75,0x6D,0x00,
- 0x00,0x00,0x0E,0x00,0x1C,0x00,0x04,0x00,0x14,0x00,0x08,0x00,0x0C,0x00,0x10,0x00,0x0E,0x00,0x00,0x00,
- 0x28,0x00,0x00,0x00,0x2C,0x06,0x00,0x00,0x14,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
- 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xF2,0xD5,0xFF,0xFF,0x00,0x00,0x00,0x0F,0x01,0x00,0x00,0x00,
- 0x07,0x00,0x00,0x00,0x4D,0x6F,0x6E,0x73,0x74,0x65,0x72,0x00,0xB2,0xFC,0xFF,0xFF,0x14,0x00,0x00,0x00,
- 0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xA4,0xFC,0xFF,0xFF,0x04,0x00,0x00,0x00,
- 0x4E,0x4F,0x4E,0x45,0x00,0x00,0x00,0x00,0x38,0xFD,0xFF,0xFF,0x34,0x00,0x00,0x00,0x1C,0x00,0x00,0x00,
- 0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x46,0xD6,0xFF,0xFF,0x00,0x00,0x00,0x03,
- 0x04,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xA0,0x00,0x00,0x00,0x78,0x00,0x00,0x00,0x48,0x00,0x00,0x00,
- 0x1C,0x00,0x00,0x00,0x13,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,0x6D,0x65,0x2E,0x45,0x78,0x61,0x6D,0x70,
- 0x6C,0x65,0x2E,0x52,0x61,0x63,0x65,0x00,0xBE,0xFD,0xFF,0xFF,0x1C,0x00,0x00,0x00,0x14,0x00,0x00,0x00,
- 0x0C,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x20,0xFD,0xFF,0xFF,
- 0x03,0x00,0x00,0x00,0x45,0x6C,0x66,0x00,0xE6,0xFD,0xFF,0xFF,0x1C,0x00,0x00,0x00,0x14,0x00,0x00,0x00,
- 0x0C,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x48,0xFD,0xFF,0xFF,
- 0x05,0x00,0x00,0x00,0x44,0x77,0x61,0x72,0x66,0x00,0x00,0x00,0x7A,0xFD,0xFF,0xFF,0x14,0x00,0x00,0x00,
- 0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x6C,0xFD,0xFF,0xFF,0x05,0x00,0x00,0x00,
- 0x48,0x75,0x6D,0x61,0x6E,0x00,0x00,0x00,0xBE,0xFE,0xFF,0xFF,0x20,0x00,0x00,0x00,0x18,0x00,0x00,0x00,
- 0x10,0x00,0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
- 0x9C,0xFD,0xFF,0xFF,0x04,0x00,0x00,0x00,0x4E,0x6F,0x6E,0x65,0x00,0x00,0x00,0x00,0x10,0x00,0x18,0x00,
- 0x04,0x00,0x08,0x00,0x00,0x00,0x0C,0x00,0x10,0x00,0x14,0x00,0x10,0x00,0x00,0x00,0x90,0x00,0x00,0x00,
- 0x7C,0x00,0x00,0x00,0x6C,0x00,0x00,0x00,0x3C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x27,0x00,0x00,0x00,0x20,0x43,0x6F,0x6D,0x70,0x6F,0x73,0x69,0x74,0x65,0x20,0x63,
- 0x6F,0x6D,0x70,0x6F,0x6E,0x65,0x6E,0x74,0x73,0x20,0x6F,0x66,0x20,0x4D,0x6F,0x6E,0x73,0x74,0x65,0x72,
- 0x20,0x63,0x6F,0x6C,0x6F,0x72,0x2E,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x48,0xDA,0xFF,0xFF,
- 0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x30,0x00,0x00,0x00,0x09,0x00,0x00,0x00,
- 0x62,0x69,0x74,0x5F,0x66,0x6C,0x61,0x67,0x73,0x00,0x00,0x00,0xAE,0xD7,0xFF,0xFF,0x00,0x00,0x00,0x04,
- 0x03,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x10,0x01,0x00,0x00,0x84,0x00,0x00,0x00,0x20,0x00,0x00,0x00,
- 0x14,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,0x6D,0x65,0x2E,0x45,0x78,0x61,0x6D,0x70,0x6C,0x65,0x2E,0x43,
- 0x6F,0x6C,0x6F,0x72,0x00,0x00,0x00,0x00,0x26,0xFF,0xFF,0xFF,0x44,0x00,0x00,0x00,0x3C,0x00,0x00,0x00,
- 0x0C,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
- 0x1C,0x00,0x00,0x00,0x20,0x5C,0x62,0x72,0x69,0x65,0x66,0x20,0x63,0x6F,0x6C,0x6F,0x72,0x20,0x42,0x6C,
- 0x75,0x65,0x20,0x28,0x31,0x75,0x20,0x3C,0x3C,0x20,0x33,0x29,0x00,0x00,0x00,0x00,0xB0,0xFE,0xFF,0xFF,
- 0x04,0x00,0x00,0x00,0x42,0x6C,0x75,0x65,0x00,0x00,0x0E,0x00,0x1C,0x00,0x04,0x00,0x10,0x00,0x00,0x00,
- 0x08,0x00,0x0C,0x00,0x0E,0x00,0x00,0x00,0x6C,0x00,0x00,0x00,0x64,0x00,0x00,0x00,0x10,0x00,0x00,0x00,
- 0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x34,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x27,0x00,0x00,0x00,0x20,0x47,0x72,0x65,0x65,0x6E,0x20,0x69,0x73,0x20,0x62,0x69,
- 0x74,0x5F,0x66,0x6C,0x61,0x67,0x20,0x77,0x69,0x74,0x68,0x20,0x76,0x61,0x6C,0x75,0x65,0x20,0x28,0x31,
- 0x75,0x20,0x3C,0x3C,0x20,0x31,0x29,0x00,0x13,0x00,0x00,0x00,0x20,0x5C,0x62,0x72,0x69,0x65,0x66,0x20,
- 0x63,0x6F,0x6C,0x6F,0x72,0x20,0x47,0x72,0x65,0x65,0x6E,0x00,0x38,0xFF,0xFF,0xFF,0x05,0x00,0x00,0x00,
- 0x47,0x72,0x65,0x65,0x6E,0x00,0x0E,0x00,0x18,0x00,0x04,0x00,0x10,0x00,0x00,0x00,0x08,0x00,0x0C,0x00,
- 0x0E,0x00,0x00,0x00,0x1C,0x00,0x00,0x00,0x14,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
- 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0xFF,0xFF,0xFF,0x03,0x00,0x00,0x00,0x52,0x65,0x64,0x00,
- 0x10,0x00,0x14,0x00,0x04,0x00,0x08,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x10,0x00,0x10,0x00,0x00,0x00,
- 0x28,0x00,0x00,0x00,0x1C,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
- 0x1E,0xD9,0xFF,0xFF,0x00,0x00,0x00,0x09,0x05,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x38,0x00,0x00,0x00,
- 0x21,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,0x6D,0x65,0x2E,0x4F,0x74,0x68,0x65,0x72,0x4E,0x61,0x6D,0x65,
- 0x53,0x70,0x61,0x63,0x65,0x2E,0x46,0x72,0x6F,0x6D,0x49,0x6E,0x63,0x6C,0x75,0x64,0x65,0x00,0x0E,0x00,
- 0x10,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x08,0x00,0x0C,0x00,0x0E,0x00,0x00,0x00,0x18,0x00,0x00,0x00,
- 0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x04,0x00,0x04,0x00,0x04,0x00,0x00,0x00,
- 0x0A,0x00,0x00,0x00,0x49,0x6E,0x63,0x6C,0x75,0x64,0x65,0x56,0x61,0x6C,0x00,0x00,0x1E,0xDA,0xFF,0xFF,
- 0x48,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
- 0x0C,0x00,0x00,0x00,0xD4,0x00,0x00,0x00,0xA8,0x00,0x00,0x00,0xBC,0x01,0x00,0x00,0x68,0x01,0x00,0x00,
- 0x14,0x01,0x00,0x00,0x1C,0x02,0x00,0x00,0x84,0x01,0x00,0x00,0x30,0x01,0x00,0x00,0xDC,0x00,0x00,0x00,
- 0xC8,0x01,0x00,0x00,0x58,0x00,0x00,0x00,0x24,0x00,0x00,0x00,0x1A,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,
- 0x6D,0x65,0x2E,0x45,0x78,0x61,0x6D,0x70,0x6C,0x65,0x2E,0x54,0x79,0x70,0x65,0x41,0x6C,0x69,0x61,0x73,
- 0x65,0x73,0x00,0x00,0x34,0xDE,0xFF,0xFF,0x00,0x00,0x00,0x01,0x0B,0x00,0x1A,0x00,0x18,0x00,0x00,0x00,
- 0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x50,0xE4,0xFF,0xFF,0x00,0x00,0x0E,0x0C,
- 0x04,0x00,0x00,0x00,0x76,0x66,0x36,0x34,0x00,0x00,0x00,0x00,0x64,0xDE,0xFF,0xFF,0x00,0x00,0x00,0x01,
- 0x0A,0x00,0x18,0x00,0x18,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
- 0x80,0xE4,0xFF,0xFF,0x00,0x00,0x0E,0x03,0x02,0x00,0x00,0x00,0x76,0x38,0x00,0x00,0x16,0xDC,0xFF,0xFF,
- 0x09,0x00,0x16,0x00,0x18,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
- 0xCA,0xD9,0xFF,0xFF,0x00,0x00,0x00,0x0C,0x03,0x00,0x00,0x00,0x66,0x36,0x34,0x00,0x3E,0xDC,0xFF,0xFF,
- 0x08,0x00,0x14,0x00,0x18,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
- 0xF2,0xD9,0xFF,0xFF,0x00,0x00,0x00,0x0B,0x03,0x00,0x00,0x00,0x66,0x33,0x32,0x00,0x66,0xDC,0xFF,0xFF,
- 0x07,0x00,0x12,0x00,0x18,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
- 0x1A,0xDA,0xFF,0xFF,0x00,0x00,0x00,0x0A,0x03,0x00,0x00,0x00,0x75,0x36,0x34,0x00,0x8E,0xDC,0xFF,0xFF,
- 0x06,0x00,0x10,0x00,0x18,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
- 0x42,0xDA,0xFF,0xFF,0x00,0x00,0x00,0x09,0x03,0x00,0x00,0x00,0x69,0x36,0x34,0x00,0xB6,0xDC,0xFF,0xFF,
- 0x05,0x00,0x0E,0x00,0x18,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
- 0x6A,0xDA,0xFF,0xFF,0x00,0x00,0x00,0x08,0x03,0x00,0x00,0x00,0x75,0x33,0x32,0x00,0xDE,0xDC,0xFF,0xFF,
- 0x04,0x00,0x0C,0x00,0x18,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
- 0x92,0xDA,0xFF,0xFF,0x00,0x00,0x00,0x07,0x03,0x00,0x00,0x00,0x69,0x33,0x32,0x00,0x06,0xDD,0xFF,0xFF,
- 0x03,0x00,0x0A,0x00,0x18,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
- 0xBA,0xDA,0xFF,0xFF,0x00,0x00,0x00,0x06,0x03,0x00,0x00,0x00,0x75,0x31,0x36,0x00,0x2E,0xDD,0xFF,0xFF,
- 0x02,0x00,0x08,0x00,0x18,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
- 0xE2,0xDA,0xFF,0xFF,0x00,0x00,0x00,0x05,0x03,0x00,0x00,0x00,0x69,0x31,0x36,0x00,0x56,0xDD,0xFF,0xFF,
- 0x01,0x00,0x06,0x00,0x18,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
- 0x0A,0xDB,0xFF,0xFF,0x00,0x00,0x00,0x04,0x02,0x00,0x00,0x00,0x75,0x38,0x00,0x00,0x00,0x00,0x1A,0x00,
+ static const uint8_t bfbsData[14648] = {
+ 0x20,0x00,0x00,0x00,0x42,0x46,0x42,0x53,0x00,0x00,0x00,0x00,0x14,0x00,0x20,0x00,0x04,0x00,0x08,0x00,
+ 0x0C,0x00,0x10,0x00,0x14,0x00,0x18,0x00,0x00,0x00,0x1C,0x00,0x14,0x00,0x00,0x00,0x58,0x00,0x00,0x00,
+ 0x34,0x00,0x00,0x00,0x24,0x00,0x00,0x00,0x18,0x00,0x00,0x00,0x9C,0x0E,0x00,0x00,0x08,0x00,0x00,0x00,
+ 0x7C,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0xD8,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x6D,0x6F,0x6E,0x00,
+ 0x04,0x00,0x00,0x00,0x4D,0x4F,0x4E,0x53,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x48,0x05,0x00,0x00,
+ 0xB4,0x02,0x00,0x00,0xF4,0x03,0x00,0x00,0x00,0x09,0x00,0x00,0x8C,0x06,0x00,0x00,0xB8,0x07,0x00,0x00,
+ 0xE8,0x0A,0x00,0x00,0x0E,0x00,0x00,0x00,0x10,0x31,0x00,0x00,0x4C,0x0E,0x00,0x00,0xE4,0x2D,0x00,0x00,
+ 0xC0,0x2E,0x00,0x00,0xD8,0x2F,0x00,0x00,0x18,0x35,0x00,0x00,0xF8,0x33,0x00,0x00,0x70,0x0B,0x00,0x00,
+ 0xF0,0x31,0x00,0x00,0xE0,0x35,0x00,0x00,0x18,0x36,0x00,0x00,0x08,0x37,0x00,0x00,0xBC,0x37,0x00,0x00,
+ 0x64,0x36,0x00,0x00,0x03,0x00,0x00,0x00,0x38,0x00,0x00,0x00,0x1C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0xEC,0xCB,0xFF,0xFF,0x0C,0x36,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x58,0x36,0x00,0x00,
+ 0x00,0xCC,0xFF,0xFF,0xAC,0x37,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x44,0x36,0x00,0x00,
+ 0x9C,0x37,0x00,0x00,0x18,0xCC,0xFF,0xFF,0x38,0x36,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,
+ 0x2C,0x36,0x00,0x00,0x84,0x37,0x00,0x00,0x00,0x00,0x0E,0x00,0x14,0x00,0x04,0x00,0x08,0x00,0x00,0x00,
+ 0x0C,0x00,0x10,0x00,0x0E,0x00,0x00,0x00,0x28,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x08,0x00,0x00,0x00,
+ 0xAC,0x35,0x00,0x00,0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x88,0x01,0x00,0x00,0xF4,0x00,0x00,0x00,
+ 0x90,0x00,0x00,0x00,0x28,0x00,0x00,0x00,0x1D,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,0x6D,0x65,0x2E,0x45,
+ 0x78,0x61,0x6D,0x70,0x6C,0x65,0x2E,0x4D,0x6F,0x6E,0x73,0x74,0x65,0x72,0x53,0x74,0x6F,0x72,0x61,0x67,
+ 0x65,0x00,0x00,0x00,0xBA,0xFE,0xFF,0xFF,0x48,0x00,0x00,0x00,0x5C,0x0D,0x00,0x00,0xD4,0x2D,0x00,0x00,
+ 0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0xB4,0xCC,0xFF,0xFF,0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x62,0x69,0x64,0x69,
+ 0x00,0x00,0x00,0x00,0x09,0x00,0x00,0x00,0x73,0x74,0x72,0x65,0x61,0x6D,0x69,0x6E,0x67,0x00,0x00,0x00,
+ 0x12,0x00,0x00,0x00,0x47,0x65,0x74,0x4D,0x69,0x6E,0x4D,0x61,0x78,0x48,0x69,0x74,0x50,0x6F,0x69,0x6E,
+ 0x74,0x73,0x00,0x00,0x1E,0xFF,0xFF,0xFF,0x48,0x00,0x00,0x00,0xF8,0x0C,0x00,0x00,0x70,0x2D,0x00,0x00,
+ 0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x18,0xCD,0xFF,0xFF,0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x06,0x00,0x00,0x00,0x63,0x6C,0x69,0x65,
+ 0x6E,0x74,0x00,0x00,0x09,0x00,0x00,0x00,0x73,0x74,0x72,0x65,0x61,0x6D,0x69,0x6E,0x67,0x00,0x00,0x00,
+ 0x0E,0x00,0x00,0x00,0x47,0x65,0x74,0x4D,0x61,0x78,0x48,0x69,0x74,0x50,0x6F,0x69,0x6E,0x74,0x00,0x00,
+ 0x7E,0xFF,0xFF,0xFF,0x70,0x00,0x00,0x00,0x14,0x2D,0x00,0x00,0x94,0x0C,0x00,0x00,0x0C,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x30,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x7C,0xCD,0xFF,0xFF,0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x06,0x00,0x00,0x00,0x73,0x65,0x72,0x76,
+ 0x65,0x72,0x00,0x00,0x09,0x00,0x00,0x00,0x73,0x74,0x72,0x65,0x61,0x6D,0x69,0x6E,0x67,0x00,0x00,0x00,
+ 0xA4,0xCD,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x30,0x00,0x00,0x00,
+ 0x0A,0x00,0x00,0x00,0x69,0x64,0x65,0x6D,0x70,0x6F,0x74,0x65,0x6E,0x74,0x00,0x00,0x08,0x00,0x00,0x00,
+ 0x52,0x65,0x74,0x72,0x69,0x65,0x76,0x65,0x00,0x00,0x0E,0x00,0x18,0x00,0x04,0x00,0x08,0x00,0x0C,0x00,
+ 0x10,0x00,0x14,0x00,0x0E,0x00,0x00,0x00,0x48,0x00,0x00,0x00,0x08,0x0C,0x00,0x00,0x80,0x2C,0x00,0x00,
+ 0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x08,0xCE,0xFF,0xFF,0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x6E,0x6F,0x6E,0x65,
+ 0x00,0x00,0x00,0x00,0x09,0x00,0x00,0x00,0x73,0x74,0x72,0x65,0x61,0x6D,0x69,0x6E,0x67,0x00,0x00,0x00,
+ 0x05,0x00,0x00,0x00,0x53,0x74,0x6F,0x72,0x65,0x00,0x00,0x00,0x82,0xFD,0xFF,0xFF,0x00,0x00,0x00,0x01,
+ 0x40,0x00,0x00,0x00,0x28,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0xA8,0x33,0x00,0x00,
+ 0x00,0x00,0x00,0x00,0xBC,0xCD,0xFF,0xFF,0x00,0x00,0x00,0x01,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
+ 0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xE0,0x00,0x00,0x00,0xA4,0x00,0x00,0x00,0x68,0x00,0x00,0x00,
+ 0x2C,0x00,0x00,0x00,0x22,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,0x6D,0x65,0x2E,0x45,0x78,0x61,0x6D,0x70,
+ 0x6C,0x65,0x2E,0x41,0x6E,0x79,0x41,0x6D,0x62,0x69,0x67,0x75,0x6F,0x75,0x73,0x41,0x6C,0x69,0x61,0x73,
+ 0x65,0x73,0x00,0x00,0x7E,0xF8,0xFF,0xFF,0x2C,0x00,0x00,0x00,0x18,0x00,0x00,0x00,0x10,0x00,0x00,0x00,
+ 0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x78,0xCB,0xFF,0xFF,
+ 0x00,0x00,0x00,0x0F,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x4D,0x33,0x00,0x00,
+ 0xB6,0xF8,0xFF,0xFF,0x2C,0x00,0x00,0x00,0x18,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x02,0x00,0x00,0x00,
+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xB0,0xCB,0xFF,0xFF,0x00,0x00,0x00,0x0F,
+ 0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x4D,0x32,0x00,0x00,0xEE,0xF8,0xFF,0xFF,
+ 0x2C,0x00,0x00,0x00,0x18,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xE8,0xCB,0xFF,0xFF,0x00,0x00,0x00,0x0F,0x01,0x00,0x00,0x00,
+ 0x01,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x4D,0x31,0x00,0x00,0x72,0xF8,0xFF,0xFF,0x1C,0x00,0x00,0x00,
+ 0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x64,0xF8,0xFF,0xFF,0x01,0x00,0x00,0x00,
+ 0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x4E,0x4F,0x4E,0x45,0x00,0x00,0x00,0x00,0xC6,0xFE,0xFF,0xFF,
+ 0x00,0x00,0x00,0x01,0x40,0x00,0x00,0x00,0x28,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x08,0x00,0x00,0x00,
+ 0x64,0x32,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xCF,0xFF,0xFF,0x00,0x00,0x00,0x01,0x02,0x00,0x00,0x00,
+ 0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xD8,0x00,0x00,0x00,0xA0,0x00,0x00,0x00,
+ 0x64,0x00,0x00,0x00,0x28,0x00,0x00,0x00,0x1F,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,0x6D,0x65,0x2E,0x45,
+ 0x78,0x61,0x6D,0x70,0x6C,0x65,0x2E,0x41,0x6E,0x79,0x55,0x6E,0x69,0x71,0x75,0x65,0x41,0x6C,0x69,0x61,
+ 0x73,0x65,0x73,0x00,0xBE,0xF9,0xFF,0xFF,0x2C,0x00,0x00,0x00,0x18,0x00,0x00,0x00,0x10,0x00,0x00,0x00,
+ 0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xB8,0xCC,0xFF,0xFF,
+ 0x00,0x00,0x00,0x0F,0x09,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x4D,0x32,0x00,0x00,
+ 0xF6,0xF9,0xFF,0xFF,0x2C,0x00,0x00,0x00,0x18,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x02,0x00,0x00,0x00,
+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xF0,0xCC,0xFF,0xFF,0x00,0x00,0x00,0x0F,
+ 0x06,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x54,0x53,0x00,0x00,0x1E,0xFC,0xFF,0xFF,
+ 0x28,0x00,0x00,0x00,0x14,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+ 0x00,0x00,0x00,0x00,0x24,0xCD,0xFF,0xFF,0x00,0x00,0x00,0x0F,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
+ 0x01,0x00,0x00,0x00,0x4D,0x00,0x00,0x00,0xAE,0xF9,0xFF,0xFF,0x1C,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xA0,0xF9,0xFF,0xFF,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x4E,0x4F,0x4E,0x45,0x00,0x00,0x12,0x00,0x1C,0x00,0x08,0x00,0x0C,0x00,0x07,0x00,
+ 0x10,0x00,0x00,0x00,0x14,0x00,0x18,0x00,0x12,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x40,0x00,0x00,0x00,
+ 0x28,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x18,0x31,0x00,0x00,0x00,0x00,0x00,0x00,
+ 0x4C,0xD0,0xFF,0xFF,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0xF0,0x00,0x00,0x00,0xB4,0x00,0x00,0x00,0x68,0x00,0x00,0x00,0x1C,0x00,0x00,0x00,
+ 0x12,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,0x6D,0x65,0x2E,0x45,0x78,0x61,0x6D,0x70,0x6C,0x65,0x2E,0x41,
+ 0x6E,0x79,0x00,0x00,0xEE,0xFC,0xFF,0xFF,0x28,0x00,0x00,0x00,0x14,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,
+ 0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xF4,0xCD,0xFF,0xFF,0x00,0x00,0x00,0x0F,
+ 0x09,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x17,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,0x6D,0x65,0x5F,0x45,
+ 0x78,0x61,0x6D,0x70,0x6C,0x65,0x32,0x5F,0x4D,0x6F,0x6E,0x73,0x74,0x65,0x72,0x00,0x36,0xFD,0xFF,0xFF,
+ 0x28,0x00,0x00,0x00,0x14,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+ 0x00,0x00,0x00,0x00,0x3C,0xCE,0xFF,0xFF,0x00,0x00,0x00,0x0F,0x06,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
+ 0x17,0x00,0x00,0x00,0x54,0x65,0x73,0x74,0x53,0x69,0x6D,0x70,0x6C,0x65,0x54,0x61,0x62,0x6C,0x65,0x57,
+ 0x69,0x74,0x68,0x45,0x6E,0x75,0x6D,0x00,0x7E,0xFD,0xFF,0xFF,0x28,0x00,0x00,0x00,0x14,0x00,0x00,0x00,
+ 0x0C,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x84,0xCE,0xFF,0xFF,
+ 0x00,0x00,0x00,0x0F,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x4D,0x6F,0x6E,0x73,
+ 0x74,0x65,0x72,0x00,0x12,0xFB,0xFF,0xFF,0x1C,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x00,0x00,0x00,0x00,0x04,0xFB,0xFF,0xFF,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x4E,0x4F,0x4E,0x45,0x00,0x00,0x00,0x00,0xA2,0xFD,0xFF,0xFF,0x6C,0x00,0x00,0x00,0x58,0x00,0x00,0x00,
+ 0x40,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0xC4,0x2F,0x00,0x00,0x00,0x00,0x00,0x00,
+ 0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x48,0xD2,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x01,0x00,0x00,0x00,0x30,0x00,0x00,0x00,0x09,0x00,0x00,0x00,0x62,0x69,0x74,0x5F,0x66,0x6C,0x61,0x67,
+ 0x73,0x00,0x00,0x00,0xCC,0xD1,0xFF,0xFF,0x00,0x00,0x00,0x0A,0x04,0x00,0x00,0x00,0x08,0x00,0x00,0x00,
+ 0x01,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x98,0x00,0x00,0x00,0x5C,0x00,0x00,0x00,0x20,0x00,0x00,0x00,
+ 0x17,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,0x6D,0x65,0x2E,0x45,0x78,0x61,0x6D,0x70,0x6C,0x65,0x2E,0x4C,
+ 0x6F,0x6E,0x67,0x45,0x6E,0x75,0x6D,0x00,0x7E,0xFC,0xFF,0xFF,0x28,0x00,0x00,0x00,0x18,0x00,0x00,0x00,
+ 0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+ 0xC8,0xFB,0xFF,0xFF,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x4C,0x6F,0x6E,0x67,
+ 0x42,0x69,0x67,0x00,0xB6,0xFC,0xFF,0xFF,0x28,0x00,0x00,0x00,0x18,0x00,0x00,0x00,0x10,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xFC,0xFF,0xFF,
+ 0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x4C,0x6F,0x6E,0x67,0x54,0x77,0x6F,0x00,
+ 0xDE,0xFE,0xFF,0xFF,0x24,0x00,0x00,0x00,0x14,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x02,0x00,0x00,0x00,
+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x34,0xFC,0xFF,0xFF,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
+ 0x07,0x00,0x00,0x00,0x4C,0x6F,0x6E,0x67,0x4F,0x6E,0x65,0x00,0xDE,0xFC,0xFF,0xFF,0x40,0x00,0x00,0x00,
+ 0x28,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x98,0x2E,0x00,0x00,0x00,0x00,0x00,0x00,
+ 0xCC,0xD2,0xFF,0xFF,0x00,0x00,0x00,0x03,0x05,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0xC8,0x00,0x00,0x00,0x8C,0x00,0x00,0x00,0x50,0x00,0x00,0x00,0x1C,0x00,0x00,0x00,
+ 0x13,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,0x6D,0x65,0x2E,0x45,0x78,0x61,0x6D,0x70,0x6C,0x65,0x2E,0x52,
+ 0x61,0x63,0x65,0x00,0x6E,0xFF,0xFF,0xFF,0x24,0x00,0x00,0x00,0x14,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,
+ 0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xC4,0xFC,0xFF,0xFF,0x01,0x00,0x00,0x00,
+ 0x01,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x45,0x6C,0x66,0x00,0xAE,0xFD,0xFF,0xFF,0x28,0x00,0x00,0x00,
+ 0x18,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+ 0x00,0x00,0x00,0x00,0xF8,0xFC,0xFF,0xFF,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x05,0x00,0x00,0x00,
+ 0x44,0x77,0x61,0x72,0x66,0x00,0x00,0x00,0x32,0xFD,0xFF,0xFF,0x1C,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x24,0xFD,0xFF,0xFF,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
+ 0x05,0x00,0x00,0x00,0x48,0x75,0x6D,0x61,0x6E,0x00,0x0E,0x00,0x18,0x00,0x04,0x00,0x10,0x00,0x00,0x00,
+ 0x08,0x00,0x0C,0x00,0x0E,0x00,0x00,0x00,0x24,0x00,0x00,0x00,0x14,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,
+ 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x00,0x00,0x00,0x00,0x64,0xFD,0xFF,0xFF,0x01,0x00,0x00,0x00,
+ 0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x4E,0x6F,0x6E,0x65,0x00,0x00,0x12,0x00,0x1C,0x00,0x04,0x00,
+ 0x08,0x00,0x00,0x00,0x0C,0x00,0x10,0x00,0x14,0x00,0x18,0x00,0x12,0x00,0x00,0x00,0x9C,0x00,0x00,0x00,
+ 0x88,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x40,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x54,0x2D,0x00,0x00,
+ 0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x27,0x00,0x00,0x00,0x20,0x43,0x6F,0x6D,0x70,0x6F,0x73,0x69,
+ 0x74,0x65,0x20,0x63,0x6F,0x6D,0x70,0x6F,0x6E,0x65,0x6E,0x74,0x73,0x20,0x6F,0x66,0x20,0x4D,0x6F,0x6E,
+ 0x73,0x74,0x65,0x72,0x20,0x63,0x6F,0x6C,0x6F,0x72,0x2E,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0xE8,0xD4,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x30,0x00,0x00,0x00,
+ 0x09,0x00,0x00,0x00,0x62,0x69,0x74,0x5F,0x66,0x6C,0x61,0x67,0x73,0x00,0x00,0x00,0x6C,0xD4,0xFF,0xFF,
+ 0x00,0x00,0x00,0x04,0x03,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x03,0x00,0x00,0x00,
+ 0x18,0x01,0x00,0x00,0x84,0x00,0x00,0x00,0x20,0x00,0x00,0x00,0x14,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,
+ 0x6D,0x65,0x2E,0x45,0x78,0x61,0x6D,0x70,0x6C,0x65,0x2E,0x43,0x6F,0x6C,0x6F,0x72,0x00,0x00,0x00,0x00,
+ 0x1E,0xFF,0xFF,0xFF,0x50,0x00,0x00,0x00,0x40,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x08,0x00,0x00,0x00,
+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x1C,0x00,0x00,0x00,
+ 0x20,0x5C,0x62,0x72,0x69,0x65,0x66,0x20,0x63,0x6F,0x6C,0x6F,0x72,0x20,0x42,0x6C,0x75,0x65,0x20,0x28,
+ 0x31,0x75,0x20,0x3C,0x3C,0x20,0x33,0x29,0x00,0x00,0x00,0x00,0x90,0xFE,0xFF,0xFF,0x01,0x00,0x00,0x00,
+ 0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x42,0x6C,0x75,0x65,0x00,0x00,0x00,0x00,0x7E,0xFF,0xFF,0xFF,
+ 0x74,0x00,0x00,0x00,0x64,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+ 0x00,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x34,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x27,0x00,0x00,0x00,
+ 0x20,0x47,0x72,0x65,0x65,0x6E,0x20,0x69,0x73,0x20,0x62,0x69,0x74,0x5F,0x66,0x6C,0x61,0x67,0x20,0x77,
+ 0x69,0x74,0x68,0x20,0x76,0x61,0x6C,0x75,0x65,0x20,0x28,0x31,0x75,0x20,0x3C,0x3C,0x20,0x31,0x29,0x00,
+ 0x13,0x00,0x00,0x00,0x20,0x5C,0x62,0x72,0x69,0x65,0x66,0x20,0x63,0x6F,0x6C,0x6F,0x72,0x20,0x47,0x72,
+ 0x65,0x65,0x6E,0x00,0x14,0xFF,0xFF,0xFF,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x05,0x00,0x00,0x00,
+ 0x47,0x72,0x65,0x65,0x6E,0x00,0x0E,0x00,0x1C,0x00,0x04,0x00,0x10,0x00,0x00,0x00,0x08,0x00,0x0C,0x00,
+ 0x0E,0x00,0x00,0x00,0x28,0x00,0x00,0x00,0x18,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x58,0xFF,0xFF,0xFF,0x01,0x00,0x00,0x00,
+ 0x01,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x52,0x65,0x64,0x00,0x00,0x00,0x12,0x00,0x18,0x00,0x04,0x00,
+ 0x08,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x10,0x00,0x14,0x00,0x12,0x00,0x00,0x00,0x34,0x00,0x00,0x00,
+ 0x28,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x18,0x2D,0x00,0x00,0x00,0x00,0x00,0x00,
+ 0x00,0xD6,0xFF,0xFF,0x00,0x00,0x00,0x09,0x06,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
+ 0x01,0x00,0x00,0x00,0x38,0x00,0x00,0x00,0x21,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,0x6D,0x65,0x2E,0x4F,
+ 0x74,0x68,0x65,0x72,0x4E,0x61,0x6D,0x65,0x53,0x70,0x61,0x63,0x65,0x2E,0x46,0x72,0x6F,0x6D,0x49,0x6E,
+ 0x63,0x6C,0x75,0x64,0x65,0x00,0x0E,0x00,0x10,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x08,0x00,0x0C,0x00,
+ 0x0E,0x00,0x00,0x00,0x2C,0x00,0x00,0x00,0x1C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+ 0x10,0x00,0x0C,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x04,0x00,0x08,0x00,0x10,0x00,0x00,0x00,
+ 0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x0A,0x00,0x00,0x00,0x49,0x6E,0x63,0x6C,0x75,0x64,0x65,0x56,
+ 0x61,0x6C,0x00,0x00,0x6C,0xD4,0xFF,0xFF,0x4C,0x00,0x00,0x00,0x14,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
+ 0x08,0x00,0x00,0x00,0xB8,0x2A,0x00,0x00,0x00,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0xE4,0x00,0x00,0x00,
+ 0xB0,0x00,0x00,0x00,0xF0,0x01,0x00,0x00,0x90,0x01,0x00,0x00,0x30,0x01,0x00,0x00,0x60,0x02,0x00,0x00,
+ 0xB0,0x01,0x00,0x00,0x54,0x01,0x00,0x00,0xF0,0x00,0x00,0x00,0x04,0x02,0x00,0x00,0x5C,0x00,0x00,0x00,
+ 0x24,0x00,0x00,0x00,0x1A,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,0x6D,0x65,0x2E,0x45,0x78,0x61,0x6D,0x70,
+ 0x6C,0x65,0x2E,0x54,0x79,0x70,0x65,0x41,0x6C,0x69,0x61,0x73,0x65,0x73,0x00,0x00,0x88,0xDB,0xFF,0xFF,
+ 0x00,0x00,0x00,0x01,0x0B,0x00,0x1A,0x00,0x1C,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x00,0x00,0x00,0x00,0x14,0xE1,0xFF,0xFF,0x00,0x00,0x0E,0x0C,0x08,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x76,0x66,0x36,0x34,0x00,0x00,0x00,0x00,0xBC,0xDB,0xFF,0xFF,0x00,0x00,0x00,0x01,0x0A,0x00,0x18,0x00,
+ 0x1C,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x48,0xE1,0xFF,0xFF,
+ 0x00,0x00,0x0E,0x03,0x01,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x76,0x38,0x00,0x00,0xD2,0xD8,0xFF,0xFF,
+ 0x09,0x00,0x16,0x00,0x20,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+ 0x9C,0xD6,0xFF,0xFF,0x00,0x00,0x00,0x0C,0x08,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x03,0x00,0x00,0x00,
+ 0x66,0x36,0x34,0x00,0x02,0xD9,0xFF,0xFF,0x08,0x00,0x14,0x00,0x1C,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x14,0xD4,0xFF,0xFF,0x00,0x00,0x00,0x0B,0x01,0x00,0x00,0x00,
+ 0x03,0x00,0x00,0x00,0x66,0x33,0x32,0x00,0x2E,0xD9,0xFF,0xFF,0x07,0x00,0x12,0x00,0x20,0x00,0x00,0x00,
+ 0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xF8,0xD6,0xFF,0xFF,0x00,0x00,0x00,0x0A,
+ 0x08,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x75,0x36,0x34,0x00,0x5E,0xD9,0xFF,0xFF,
+ 0x06,0x00,0x10,0x00,0x20,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+ 0x28,0xD7,0xFF,0xFF,0x00,0x00,0x00,0x09,0x08,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x03,0x00,0x00,0x00,
+ 0x69,0x36,0x34,0x00,0x8E,0xD9,0xFF,0xFF,0x05,0x00,0x0E,0x00,0x1C,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xA0,0xD4,0xFF,0xFF,0x00,0x00,0x00,0x08,0x01,0x00,0x00,0x00,
+ 0x03,0x00,0x00,0x00,0x75,0x33,0x32,0x00,0xBA,0xD9,0xFF,0xFF,0x04,0x00,0x0C,0x00,0x1C,0x00,0x00,0x00,
+ 0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xCC,0xD4,0xFF,0xFF,0x00,0x00,0x00,0x07,
+ 0x01,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x69,0x33,0x32,0x00,0xE6,0xD9,0xFF,0xFF,0x03,0x00,0x0A,0x00,
+ 0x20,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xB0,0xD7,0xFF,0xFF,
+ 0x00,0x00,0x00,0x06,0x02,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x75,0x31,0x36,0x00,
+ 0x16,0xDA,0xFF,0xFF,0x02,0x00,0x08,0x00,0x20,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x00,0x00,0x00,0x00,0xE0,0xD7,0xFF,0xFF,0x00,0x00,0x00,0x05,0x02,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
+ 0x03,0x00,0x00,0x00,0x69,0x31,0x36,0x00,0x46,0xDA,0xFF,0xFF,0x01,0x00,0x06,0x00,0x20,0x00,0x00,0x00,
+ 0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0xD8,0xFF,0xFF,0x00,0x00,0x00,0x04,
+ 0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x75,0x38,0x00,0x00,0x00,0x00,0x1A,0x00,
0x14,0x00,0x08,0x00,0x0C,0x00,0x00,0x00,0x06,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
- 0x00,0x00,0x10,0x00,0x1A,0x00,0x00,0x00,0x00,0x00,0x04,0x00,0x18,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x4E,0xDB,0xFF,0xFF,0x00,0x00,0x00,0x03,0x02,0x00,0x00,0x00,
- 0x69,0x38,0x00,0x00,0x92,0xDC,0xFF,0xFF,0x1C,0x01,0x00,0x00,0x4C,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x33,0x00,0x00,0x00,0x20,0x61,0x6E,0x20,
- 0x65,0x78,0x61,0x6D,0x70,0x6C,0x65,0x20,0x64,0x6F,0x63,0x75,0x6D,0x65,0x6E,0x74,0x61,0x74,0x69,0x6F,
- 0x6E,0x20,0x63,0x6F,0x6D,0x6D,0x65,0x6E,0x74,0x3A,0x20,0x22,0x6D,0x6F,0x6E,0x73,0x74,0x65,0x72,0x20,
- 0x6F,0x62,0x6A,0x65,0x63,0x74,0x22,0x00,0x32,0x00,0x00,0x00,0x54,0x02,0x00,0x00,0xB4,0x02,0x00,0x00,
- 0x14,0x03,0x00,0x00,0x70,0x03,0x00,0x00,0x54,0x07,0x00,0x00,0x94,0x18,0x00,0x00,0xC4,0x15,0x00,0x00,
- 0xC4,0x0C,0x00,0x00,0x84,0x19,0x00,0x00,0xFC,0x1A,0x00,0x00,0x00,0x19,0x00,0x00,0x6C,0x1B,0x00,0x00,
- 0x38,0x1A,0x00,0x00,0xD4,0x04,0x00,0x00,0x1C,0x0B,0x00,0x00,0xD4,0x1B,0x00,0x00,0x48,0x01,0x00,0x00,
- 0xB4,0x09,0x00,0x00,0x90,0x17,0x00,0x00,0x24,0x17,0x00,0x00,0x34,0x0C,0x00,0x00,0xF8,0x17,0x00,0x00,
- 0x20,0x0F,0x00,0x00,0x04,0x0D,0x00,0x00,0xAC,0x16,0x00,0x00,0x68,0x0D,0x00,0x00,0xD0,0x15,0x00,0x00,
- 0x1C,0x14,0x00,0x00,0x70,0x14,0x00,0x00,0xA4,0x0E,0x00,0x00,0x28,0x0E,0x00,0x00,0xB4,0x0D,0x00,0x00,
- 0x80,0x13,0x00,0x00,0x58,0x11,0x00,0x00,0x68,0x12,0x00,0x00,0xDC,0x0F,0x00,0x00,0xE8,0x12,0x00,0x00,
- 0x60,0x10,0x00,0x00,0xD0,0x11,0x00,0x00,0x40,0x0F,0x00,0x00,0xA0,0x14,0x00,0x00,0x40,0x00,0x00,0x00,
- 0x80,0x05,0x00,0x00,0x14,0x0B,0x00,0x00,0x40,0x01,0x00,0x00,0x70,0x0B,0x00,0x00,0x24,0x03,0x00,0x00,
- 0x2C,0x0A,0x00,0x00,0x90,0x07,0x00,0x00,0x3C,0x08,0x00,0x00,0x16,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,
- 0x6D,0x65,0x2E,0x45,0x78,0x61,0x6D,0x70,0x6C,0x65,0x2E,0x4D,0x6F,0x6E,0x73,0x74,0x65,0x72,0x00,0x00,
- 0xD8,0xE7,0xFF,0xFF,0x00,0x00,0x00,0x01,0x31,0x00,0x66,0x00,0x74,0x00,0x00,0x00,0x68,0x00,0x00,0x00,
- 0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x38,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x2C,0xE0,0xFF,0xFF,0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x07,0x00,0x00,0x00,
- 0x4D,0x6F,0x6E,0x73,0x74,0x65,0x72,0x00,0x11,0x00,0x00,0x00,0x6E,0x65,0x73,0x74,0x65,0x64,0x5F,0x66,
- 0x6C,0x61,0x74,0x62,0x75,0x66,0x66,0x65,0x72,0x00,0x00,0x00,0x5C,0xE0,0xFF,0xFF,0x10,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x34,0x39,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,
- 0xF0,0xE7,0xFF,0xFF,0x00,0x00,0x0E,0x04,0x1C,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x72,0x65,0x71,0x75,
- 0x69,0x72,0x65,0x64,0x6E,0x65,0x73,0x74,0x65,0x64,0x66,0x6C,0x61,0x74,0x62,0x75,0x66,0x66,0x65,0x72,
- 0x00,0x00,0x00,0x00,0x82,0xE6,0xFF,0xFF,0x30,0x00,0x64,0x00,0x50,0x00,0x00,0x00,0x40,0x00,0x00,0x00,
- 0x18,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x00,0x00,0x00,0x00,
- 0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xD4,0xE0,0xFF,0xFF,0x10,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x34,0x38,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,
- 0x32,0xDE,0xFF,0xFF,0x00,0x00,0x00,0x03,0x04,0x00,0x00,0x00,0x0B,0x00,0x00,0x00,0x73,0x69,0x67,0x6E,
- 0x65,0x64,0x5F,0x65,0x6E,0x75,0x6D,0x00,0xE4,0xE8,0xFF,0xFF,0x00,0x00,0x00,0x01,0x2F,0x00,0x62,0x00,
- 0x44,0x00,0x00,0x00,0x34,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
- 0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x34,0xE1,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
- 0x02,0x00,0x00,0x00,0x34,0x37,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x7E,0xEA,0xFF,0xFF,
- 0x00,0x00,0x0E,0x04,0x03,0x00,0x00,0x00,0x0F,0x00,0x00,0x00,0x76,0x65,0x63,0x74,0x6F,0x72,0x5F,0x6F,
- 0x66,0x5F,0x65,0x6E,0x75,0x6D,0x73,0x00,0x48,0xE9,0xFF,0xFF,0x00,0x00,0x00,0x01,0x2E,0x00,0x60,0x00,
- 0x44,0x00,0x00,0x00,0x34,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
- 0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x98,0xE1,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
- 0x02,0x00,0x00,0x00,0x34,0x36,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0xF6,0xDE,0xFF,0xFF,
- 0x00,0x00,0x00,0x10,0x01,0x00,0x00,0x00,0x0D,0x00,0x00,0x00,0x61,0x6E,0x79,0x5F,0x61,0x6D,0x62,0x69,
- 0x67,0x75,0x6F,0x75,0x73,0x00,0x00,0x00,0x86,0xEA,0xFF,0xFF,0x2D,0x00,0x5E,0x00,0x44,0x00,0x00,0x00,
- 0x34,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0xF8,0xE1,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,
- 0x34,0x35,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x56,0xDF,0xFF,0xFF,0x00,0x00,0x00,0x01,
- 0x01,0x00,0x00,0x00,0x12,0x00,0x00,0x00,0x61,0x6E,0x79,0x5F,0x61,0x6D,0x62,0x69,0x67,0x75,0x6F,0x75,
- 0x73,0x5F,0x74,0x79,0x70,0x65,0x00,0x00,0x10,0xEA,0xFF,0xFF,0x00,0x00,0x00,0x01,0x2C,0x00,0x5C,0x00,
- 0x44,0x00,0x00,0x00,0x34,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
- 0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x60,0xE2,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
- 0x02,0x00,0x00,0x00,0x34,0x34,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0xBE,0xDF,0xFF,0xFF,
- 0x00,0x00,0x00,0x10,0x02,0x00,0x00,0x00,0x0A,0x00,0x00,0x00,0x61,0x6E,0x79,0x5F,0x75,0x6E,0x69,0x71,
- 0x75,0x65,0x00,0x00,0x4A,0xEB,0xFF,0xFF,0x2B,0x00,0x5A,0x00,0x44,0x00,0x00,0x00,0x34,0x00,0x00,0x00,
- 0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
- 0xBC,0xE2,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x34,0x33,0x00,0x00,
- 0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x1A,0xE0,0xFF,0xFF,0x00,0x00,0x00,0x01,0x02,0x00,0x00,0x00,
- 0x0F,0x00,0x00,0x00,0x61,0x6E,0x79,0x5F,0x75,0x6E,0x69,0x71,0x75,0x65,0x5F,0x74,0x79,0x70,0x65,0x00,
- 0xD0,0xEA,0xFF,0xFF,0x00,0x00,0x00,0x01,0x2A,0x00,0x58,0x00,0xFC,0x00,0x00,0x00,0xF0,0x00,0x00,0x00,
- 0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0xB0,0x00,0x00,0x00,
- 0x80,0x00,0x00,0x00,0x50,0x00,0x00,0x00,0x24,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x30,0xE3,0xFF,0xFF,
- 0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x34,0x32,0x00,0x00,0x02,0x00,0x00,0x00,
- 0x69,0x64,0x00,0x00,0x4C,0xE3,0xFF,0xFF,0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x08,0x00,0x00,0x00,
- 0x66,0x6E,0x76,0x31,0x61,0x5F,0x36,0x34,0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x68,0x61,0x73,0x68,
- 0x00,0x00,0x00,0x00,0x74,0xE3,0xFF,0xFF,0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x0B,0x00,0x00,0x00,
- 0x52,0x65,0x66,0x65,0x72,0x72,0x61,0x62,0x6C,0x65,0x54,0x00,0x08,0x00,0x00,0x00,0x63,0x70,0x70,0x5F,
- 0x74,0x79,0x70,0x65,0x00,0x00,0x00,0x00,0xA0,0xE3,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
- 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x63,0x70,0x70,0x5F,0x70,0x74,0x72,0x5F,
- 0x74,0x79,0x70,0x65,0x5F,0x67,0x65,0x74,0x00,0x00,0x00,0x00,0xCC,0xE3,0xFF,0xFF,0x14,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0x6E,0x61,0x6B,0x65,0x64,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,
- 0x63,0x70,0x70,0x5F,0x70,0x74,0x72,0x5F,0x74,0x79,0x70,0x65,0x00,0x00,0x00,0x00,0x70,0xEB,0xFF,0xFF,
- 0x00,0x00,0x0E,0x0A,0x1F,0x00,0x00,0x00,0x76,0x65,0x63,0x74,0x6F,0x72,0x5F,0x6F,0x66,0x5F,0x6E,0x6F,
- 0x6E,0x5F,0x6F,0x77,0x6E,0x69,0x6E,0x67,0x5F,0x72,0x65,0x66,0x65,0x72,0x65,0x6E,0x63,0x65,0x73,0x00,
- 0xD6,0xEC,0xFF,0xFF,0x29,0x00,0x56,0x00,0xFC,0x00,0x00,0x00,0xF0,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0xB0,0x00,0x00,0x00,0x80,0x00,0x00,0x00,
- 0x50,0x00,0x00,0x00,0x24,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x58,0xE4,0xFF,0xFF,0x10,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x34,0x31,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,
- 0x74,0xE4,0xFF,0xFF,0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x66,0x6E,0x76,0x31,
- 0x61,0x5F,0x36,0x34,0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x68,0x61,0x73,0x68,0x00,0x00,0x00,0x00,
- 0x9C,0xE4,0xFF,0xFF,0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x0B,0x00,0x00,0x00,0x52,0x65,0x66,0x65,
- 0x72,0x72,0x61,0x62,0x6C,0x65,0x54,0x00,0x08,0x00,0x00,0x00,0x63,0x70,0x70,0x5F,0x74,0x79,0x70,0x65,
- 0x00,0x00,0x00,0x00,0xC8,0xE4,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
- 0x00,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x63,0x70,0x70,0x5F,0x70,0x74,0x72,0x5F,0x74,0x79,0x70,0x65,
- 0x5F,0x67,0x65,0x74,0x00,0x00,0x00,0x00,0xF4,0xE4,0xFF,0xFF,0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
- 0x05,0x00,0x00,0x00,0x6E,0x61,0x6B,0x65,0x64,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x63,0x70,0x70,0x5F,
- 0x70,0x74,0x72,0x5F,0x74,0x79,0x70,0x65,0x00,0x00,0x00,0x00,0xBA,0xE1,0xFF,0xFF,0x00,0x00,0x00,0x0A,
- 0x14,0x00,0x00,0x00,0x6E,0x6F,0x6E,0x5F,0x6F,0x77,0x6E,0x69,0x6E,0x67,0x5F,0x72,0x65,0x66,0x65,0x72,
- 0x65,0x6E,0x63,0x65,0x00,0x00,0x00,0x00,0x1C,0xED,0xFF,0xFF,0x00,0x00,0x00,0x01,0x28,0x00,0x54,0x00,
- 0x0C,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
- 0x05,0x00,0x00,0x00,0xB4,0x00,0x00,0x00,0x80,0x00,0x00,0x00,0x50,0x00,0x00,0x00,0x24,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x7C,0xE5,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,
- 0x34,0x30,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x98,0xE5,0xFF,0xFF,0x18,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x66,0x6E,0x76,0x31,0x61,0x5F,0x36,0x34,0x00,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x68,0x61,0x73,0x68,0x00,0x00,0x00,0x00,0xC0,0xE5,0xFF,0xFF,0x18,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x0B,0x00,0x00,0x00,0x52,0x65,0x66,0x65,0x72,0x72,0x61,0x62,0x6C,0x65,0x54,0x00,
- 0x08,0x00,0x00,0x00,0x63,0x70,0x70,0x5F,0x74,0x79,0x70,0x65,0x00,0x00,0x00,0x00,0xEC,0xE5,0xFF,0xFF,
- 0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x06,0x00,0x00,0x00,0x2E,0x67,0x65,0x74,0x28,0x29,0x00,0x00,
- 0x10,0x00,0x00,0x00,0x63,0x70,0x70,0x5F,0x70,0x74,0x72,0x5F,0x74,0x79,0x70,0x65,0x5F,0x67,0x65,0x74,
- 0x00,0x00,0x00,0x00,0x1C,0xE6,0xFF,0xFF,0x20,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x10,0x00,0x00,0x00,
- 0x64,0x65,0x66,0x61,0x75,0x6C,0x74,0x5F,0x70,0x74,0x72,0x5F,0x74,0x79,0x70,0x65,0x00,0x00,0x00,0x00,
- 0x0C,0x00,0x00,0x00,0x63,0x70,0x70,0x5F,0x70,0x74,0x72,0x5F,0x74,0x79,0x70,0x65,0x00,0x00,0x00,0x00,
- 0xCC,0xED,0xFF,0xFF,0x00,0x00,0x0E,0x0A,0x1E,0x00,0x00,0x00,0x76,0x65,0x63,0x74,0x6F,0x72,0x5F,0x6F,
- 0x66,0x5F,0x63,0x6F,0x5F,0x6F,0x77,0x6E,0x69,0x6E,0x67,0x5F,0x72,0x65,0x66,0x65,0x72,0x65,0x6E,0x63,
- 0x65,0x73,0x00,0x00,0x32,0xEF,0xFF,0xFF,0x27,0x00,0x52,0x00,0xCC,0x00,0x00,0x00,0xC0,0x00,0x00,0x00,
- 0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x80,0x00,0x00,0x00,
- 0x50,0x00,0x00,0x00,0x24,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xB0,0xE6,0xFF,0xFF,0x10,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x33,0x39,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,
- 0xCC,0xE6,0xFF,0xFF,0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x66,0x6E,0x76,0x31,
- 0x61,0x5F,0x36,0x34,0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x68,0x61,0x73,0x68,0x00,0x00,0x00,0x00,
- 0xF4,0xE6,0xFF,0xFF,0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x0B,0x00,0x00,0x00,0x52,0x65,0x66,0x65,
- 0x72,0x72,0x61,0x62,0x6C,0x65,0x54,0x00,0x08,0x00,0x00,0x00,0x63,0x70,0x70,0x5F,0x74,0x79,0x70,0x65,
- 0x00,0x00,0x00,0x00,0x20,0xE7,0xFF,0xFF,0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x05,0x00,0x00,0x00,
- 0x6E,0x61,0x6B,0x65,0x64,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x63,0x70,0x70,0x5F,0x70,0x74,0x72,0x5F,
- 0x74,0x79,0x70,0x65,0x00,0x00,0x00,0x00,0xE6,0xE3,0xFF,0xFF,0x00,0x00,0x00,0x0A,0x13,0x00,0x00,0x00,
- 0x63,0x6F,0x5F,0x6F,0x77,0x6E,0x69,0x6E,0x67,0x5F,0x72,0x65,0x66,0x65,0x72,0x65,0x6E,0x63,0x65,0x00,
- 0x44,0xEF,0xFF,0xFF,0x00,0x00,0x00,0x01,0x26,0x00,0x50,0x00,0x80,0x00,0x00,0x00,0x70,0x00,0x00,0x00,
- 0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x24,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x98,0xE7,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,
- 0x33,0x38,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0xB4,0xE7,0xFF,0xFF,0x20,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x64,0x65,0x66,0x61,0x75,0x6C,0x74,0x5F,0x70,0x74,0x72,0x5F,
- 0x74,0x79,0x70,0x65,0x00,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x63,0x70,0x70,0x5F,0x70,0x74,0x72,0x5F,
- 0x74,0x79,0x70,0x65,0x00,0x00,0x00,0x00,0x1A,0xF1,0xFF,0xFF,0x00,0x00,0x0E,0x0F,0x02,0x00,0x00,0x00,
- 0x1C,0x00,0x00,0x00,0x76,0x65,0x63,0x74,0x6F,0x72,0x5F,0x6F,0x66,0x5F,0x73,0x74,0x72,0x6F,0x6E,0x67,
- 0x5F,0x72,0x65,0x66,0x65,0x72,0x72,0x61,0x62,0x6C,0x65,0x73,0x00,0x00,0x00,0x00,0xF4,0xEF,0xFF,0xFF,
- 0x00,0x00,0x00,0x01,0x25,0x00,0x4E,0x00,0xCC,0x00,0x00,0x00,0xC0,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x80,0x00,0x00,0x00,0x50,0x00,0x00,0x00,
- 0x24,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x50,0xE8,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
- 0x02,0x00,0x00,0x00,0x33,0x37,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x6C,0xE8,0xFF,0xFF,
- 0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x66,0x6E,0x76,0x31,0x61,0x5F,0x36,0x34,
- 0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x68,0x61,0x73,0x68,0x00,0x00,0x00,0x00,0x94,0xE8,0xFF,0xFF,
- 0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x0B,0x00,0x00,0x00,0x52,0x65,0x66,0x65,0x72,0x72,0x61,0x62,
- 0x6C,0x65,0x54,0x00,0x08,0x00,0x00,0x00,0x63,0x70,0x70,0x5F,0x74,0x79,0x70,0x65,0x00,0x00,0x00,0x00,
- 0xC0,0xE8,0xFF,0xFF,0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0x6E,0x61,0x6B,0x65,
- 0x64,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x63,0x70,0x70,0x5F,0x70,0x74,0x72,0x5F,0x74,0x79,0x70,0x65,
- 0x00,0x00,0x00,0x00,0x64,0xF0,0xFF,0xFF,0x00,0x00,0x0E,0x0A,0x19,0x00,0x00,0x00,0x76,0x65,0x63,0x74,
- 0x6F,0x72,0x5F,0x6F,0x66,0x5F,0x77,0x65,0x61,0x6B,0x5F,0x72,0x65,0x66,0x65,0x72,0x65,0x6E,0x63,0x65,
- 0x73,0x00,0x00,0x00,0xC6,0xF1,0xFF,0xFF,0x24,0x00,0x4C,0x00,0xCC,0x00,0x00,0x00,0xC0,0x00,0x00,0x00,
- 0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x80,0x00,0x00,0x00,
- 0x50,0x00,0x00,0x00,0x24,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x44,0xE9,0xFF,0xFF,0x10,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x33,0x36,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,
- 0x60,0xE9,0xFF,0xFF,0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x66,0x6E,0x76,0x31,
- 0x61,0x5F,0x36,0x34,0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x68,0x61,0x73,0x68,0x00,0x00,0x00,0x00,
- 0x88,0xE9,0xFF,0xFF,0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x0B,0x00,0x00,0x00,0x52,0x65,0x66,0x65,
- 0x72,0x72,0x61,0x62,0x6C,0x65,0x54,0x00,0x08,0x00,0x00,0x00,0x63,0x70,0x70,0x5F,0x74,0x79,0x70,0x65,
- 0x00,0x00,0x00,0x00,0xB4,0xE9,0xFF,0xFF,0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x05,0x00,0x00,0x00,
- 0x6E,0x61,0x6B,0x65,0x64,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x63,0x70,0x70,0x5F,0x70,0x74,0x72,0x5F,
- 0x74,0x79,0x70,0x65,0x00,0x00,0x00,0x00,0x7A,0xE6,0xFF,0xFF,0x00,0x00,0x00,0x0A,0x15,0x00,0x00,0x00,
- 0x73,0x69,0x6E,0x67,0x6C,0x65,0x5F,0x77,0x65,0x61,0x6B,0x5F,0x72,0x65,0x66,0x65,0x72,0x65,0x6E,0x63,
- 0x65,0x00,0x00,0x00,0xDC,0xF1,0xFF,0xFF,0x00,0x00,0x00,0x01,0x23,0x00,0x4A,0x00,0x44,0x00,0x00,0x00,
- 0x34,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x2C,0xEA,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,
- 0x33,0x35,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x76,0xF3,0xFF,0xFF,0x00,0x00,0x0E,0x0F,
- 0x02,0x00,0x00,0x00,0x15,0x00,0x00,0x00,0x76,0x65,0x63,0x74,0x6F,0x72,0x5F,0x6F,0x66,0x5F,0x72,0x65,
- 0x66,0x65,0x72,0x72,0x61,0x62,0x6C,0x65,0x73,0x00,0x00,0x00,0x48,0xF2,0xFF,0xFF,0x00,0x00,0x00,0x01,
- 0x22,0x00,0x48,0x00,0x44,0x00,0x00,0x00,0x34,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
- 0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x98,0xEA,0xFF,0xFF,0x10,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x33,0x34,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,
- 0xF6,0xE7,0xFF,0xFF,0x00,0x00,0x00,0x0F,0x09,0x00,0x00,0x00,0x15,0x00,0x00,0x00,0x70,0x61,0x72,0x65,
- 0x6E,0x74,0x5F,0x6E,0x61,0x6D,0x65,0x73,0x70,0x61,0x63,0x65,0x5F,0x74,0x65,0x73,0x74,0x00,0x00,0x00,
- 0xB4,0xF2,0xFF,0xFF,0x00,0x00,0x00,0x01,0x21,0x00,0x46,0x00,0x40,0x00,0x00,0x00,0x34,0x00,0x00,0x00,
- 0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
- 0x04,0xEB,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x33,0x33,0x00,0x00,
- 0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x98,0xF2,0xFF,0xFF,0x00,0x00,0x0E,0x0C,0x11,0x00,0x00,0x00,
- 0x76,0x65,0x63,0x74,0x6F,0x72,0x5F,0x6F,0x66,0x5F,0x64,0x6F,0x75,0x62,0x6C,0x65,0x73,0x00,0x00,0x00,
- 0x18,0xF3,0xFF,0xFF,0x00,0x00,0x00,0x01,0x20,0x00,0x44,0x00,0x40,0x00,0x00,0x00,0x34,0x00,0x00,0x00,
- 0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
- 0x68,0xEB,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x33,0x32,0x00,0x00,
- 0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0xFC,0xF2,0xFF,0xFF,0x00,0x00,0x0E,0x09,0x0F,0x00,0x00,0x00,
- 0x76,0x65,0x63,0x74,0x6F,0x72,0x5F,0x6F,0x66,0x5F,0x6C,0x6F,0x6E,0x67,0x73,0x00,0x78,0xF3,0xFF,0xFF,
- 0x00,0x00,0x00,0x01,0x1F,0x00,0x42,0x00,0x44,0x00,0x00,0x00,0x34,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xC8,0xEB,0xFF,0xFF,
- 0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x33,0x31,0x00,0x00,0x02,0x00,0x00,0x00,
- 0x69,0x64,0x00,0x00,0x12,0xF5,0xFF,0xFF,0x00,0x00,0x0E,0x0F,0x04,0x00,0x00,0x00,0x05,0x00,0x00,0x00,
- 0x74,0x65,0x73,0x74,0x35,0x00,0x00,0x00,0xD4,0xF3,0xFF,0xFF,0x00,0x00,0x00,0x01,0x1E,0x00,0x40,0x00,
- 0x68,0x00,0x00,0x00,0x5C,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
- 0x02,0x00,0x00,0x00,0x24,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x28,0xEC,0xFF,0xFF,0x10,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x33,0x30,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,
- 0x44,0xEC,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x30,0x00,0x00,0x00,
- 0x0A,0x00,0x00,0x00,0x66,0x6C,0x65,0x78,0x62,0x75,0x66,0x66,0x65,0x72,0x00,0x00,0xE0,0xF3,0xFF,0xFF,
- 0x00,0x00,0x0E,0x04,0x04,0x00,0x00,0x00,0x66,0x6C,0x65,0x78,0x00,0x00,0x00,0x00,0x54,0xF4,0xFF,0xFF,
- 0x00,0x00,0x00,0x01,0x1D,0x00,0x3E,0x00,0x44,0x00,0x00,0x00,0x34,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xA4,0xEC,0xFF,0xFF,
- 0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x32,0x39,0x00,0x00,0x02,0x00,0x00,0x00,
- 0x69,0x64,0x00,0x00,0xEE,0xF5,0xFF,0xFF,0x00,0x00,0x0E,0x0F,0x00,0x00,0x00,0x00,0x17,0x00,0x00,0x00,
- 0x74,0x65,0x73,0x74,0x61,0x72,0x72,0x61,0x79,0x6F,0x66,0x73,0x6F,0x72,0x74,0x65,0x64,0x73,0x74,0x72,
- 0x75,0x63,0x74,0x00,0xC0,0xF4,0xFF,0xFF,0x00,0x00,0x00,0x01,0x1C,0x00,0x3C,0x00,0x40,0x00,0x00,0x00,
- 0x34,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x10,0xED,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,
- 0x32,0x38,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0xA4,0xF4,0xFF,0xFF,0x00,0x00,0x0E,0x0D,
- 0x12,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x61,0x72,0x72,0x61,0x79,0x6F,0x66,0x73,0x74,0x72,0x69,0x6E,
- 0x67,0x32,0x00,0x00,0xFE,0xF5,0xFF,0xFF,0x1B,0x00,0x3A,0x00,0x40,0x00,0x00,0x00,0x34,0x00,0x00,0x00,
- 0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
- 0x70,0xED,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x32,0x37,0x00,0x00,
- 0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x26,0xEA,0xFF,0xFF,0x00,0x00,0x00,0x0B,0x06,0x00,0x00,0x00,
- 0x74,0x65,0x73,0x74,0x66,0x33,0x00,0x00,0x00,0x00,0x1A,0x00,0x20,0x00,0x08,0x00,0x0C,0x00,0x04,0x00,
- 0x06,0x00,0x00,0x00,0x18,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x14,0x00,0x1A,0x00,0x00,0x00,
- 0x1A,0x00,0x38,0x00,0x48,0x00,0x00,0x00,0x3C,0x00,0x00,0x00,0x14,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,
- 0x00,0x00,0x00,0x00,0x00,0x00,0x08,0x40,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
- 0xE8,0xED,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x32,0x36,0x00,0x00,
- 0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x9E,0xEA,0xFF,0xFF,0x00,0x00,0x00,0x0B,0x06,0x00,0x00,0x00,
- 0x74,0x65,0x73,0x74,0x66,0x32,0x00,0x00,0x00,0x00,0x1A,0x00,0x24,0x00,0x08,0x00,0x0C,0x00,0x04,0x00,
- 0x06,0x00,0x00,0x00,0x18,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x14,0x00,0x1A,0x00,0x00,0x00,
- 0x19,0x00,0x36,0x00,0x4C,0x00,0x00,0x00,0x40,0x00,0x00,0x00,0x18,0x00,0x00,0x00,0x10,0x00,0x00,0x00,
- 0x6E,0x86,0x1B,0xF0,0xF9,0x21,0x09,0x40,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x64,0xEE,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,
- 0x32,0x35,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x1A,0xEB,0xFF,0xFF,0x00,0x00,0x00,0x0B,
- 0x05,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x66,0x00,0x00,0x00,0x6C,0xF6,0xFF,0xFF,0x00,0x00,0x00,0x01,
- 0x18,0x00,0x34,0x00,0x40,0x00,0x00,0x00,0x34,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
- 0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xBC,0xEE,0xFF,0xFF,0x10,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x32,0x34,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,
- 0x50,0xF6,0xFF,0xFF,0x00,0x00,0x0E,0x02,0x10,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x61,0x72,0x72,0x61,
- 0x79,0x6F,0x66,0x62,0x6F,0x6F,0x6C,0x73,0x00,0x00,0x00,0x00,0xAA,0xF7,0xFF,0xFF,0x17,0x00,0x32,0x00,
- 0x6C,0x00,0x00,0x00,0x60,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
- 0x02,0x00,0x00,0x00,0x24,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x20,0xEF,0xFF,0xFF,0x10,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x32,0x33,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,
- 0x3C,0xEF,0xFF,0xFF,0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x66,0x6E,0x76,0x31,
- 0x61,0x5F,0x36,0x34,0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x68,0x61,0x73,0x68,0x00,0x00,0x00,0x00,
- 0xFE,0xEB,0xFF,0xFF,0x00,0x00,0x00,0x0A,0x11,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x68,0x61,0x73,0x68,
- 0x75,0x36,0x34,0x5F,0x66,0x6E,0x76,0x31,0x61,0x00,0x00,0x00,0x36,0xF8,0xFF,0xFF,0x16,0x00,0x30,0x00,
- 0x6C,0x00,0x00,0x00,0x60,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
- 0x02,0x00,0x00,0x00,0x24,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xAC,0xEF,0xFF,0xFF,0x10,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x32,0x32,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,
- 0xC8,0xEF,0xFF,0xFF,0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x66,0x6E,0x76,0x31,
- 0x61,0x5F,0x36,0x34,0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x68,0x61,0x73,0x68,0x00,0x00,0x00,0x00,
- 0x8A,0xEC,0xFF,0xFF,0x00,0x00,0x00,0x09,0x11,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x68,0x61,0x73,0x68,
- 0x73,0x36,0x34,0x5F,0x66,0x6E,0x76,0x31,0x61,0x00,0x00,0x00,0xC2,0xF8,0xFF,0xFF,0x15,0x00,0x2E,0x00,
- 0xC8,0x00,0x00,0x00,0xBC,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x7C,0x00,0x00,0x00,0x50,0x00,0x00,0x00,0x24,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
- 0x40,0xF0,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x32,0x31,0x00,0x00,
- 0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x5C,0xF0,0xFF,0xFF,0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
- 0x08,0x00,0x00,0x00,0x66,0x6E,0x76,0x31,0x61,0x5F,0x33,0x32,0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
- 0x68,0x61,0x73,0x68,0x00,0x00,0x00,0x00,0x84,0xF0,0xFF,0xFF,0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x53,0x74,0x61,0x74,0x00,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x63,0x70,0x70,0x5F,
- 0x74,0x79,0x70,0x65,0x00,0x00,0x00,0x00,0xAC,0xF0,0xFF,0xFF,0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
- 0x05,0x00,0x00,0x00,0x6E,0x61,0x6B,0x65,0x64,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x63,0x70,0x70,0x5F,
- 0x70,0x74,0x72,0x5F,0x74,0x79,0x70,0x65,0x00,0x00,0x00,0x00,0x72,0xED,0xFF,0xFF,0x00,0x00,0x00,0x08,
- 0x11,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x68,0x61,0x73,0x68,0x75,0x33,0x32,0x5F,0x66,0x6E,0x76,0x31,
- 0x61,0x00,0x00,0x00,0xAA,0xF9,0xFF,0xFF,0x14,0x00,0x2C,0x00,0x6C,0x00,0x00,0x00,0x60,0x00,0x00,0x00,
- 0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x24,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x20,0xF1,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,
- 0x32,0x30,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x3C,0xF1,0xFF,0xFF,0x18,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x66,0x6E,0x76,0x31,0x61,0x5F,0x33,0x32,0x00,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x68,0x61,0x73,0x68,0x00,0x00,0x00,0x00,0xFE,0xED,0xFF,0xFF,0x00,0x00,0x00,0x07,
- 0x11,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x68,0x61,0x73,0x68,0x73,0x33,0x32,0x5F,0x66,0x6E,0x76,0x31,
- 0x61,0x00,0x00,0x00,0x36,0xFA,0xFF,0xFF,0x13,0x00,0x2A,0x00,0x68,0x00,0x00,0x00,0x5C,0x00,0x00,0x00,
- 0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x24,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0xAC,0xF1,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,
- 0x31,0x39,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0xC8,0xF1,0xFF,0xFF,0x14,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x66,0x6E,0x76,0x31,0x5F,0x36,0x34,0x00,0x04,0x00,0x00,0x00,
- 0x68,0x61,0x73,0x68,0x00,0x00,0x00,0x00,0x86,0xEE,0xFF,0xFF,0x00,0x00,0x00,0x0A,0x10,0x00,0x00,0x00,
- 0x74,0x65,0x73,0x74,0x68,0x61,0x73,0x68,0x75,0x36,0x34,0x5F,0x66,0x6E,0x76,0x31,0x00,0x00,0x00,0x00,
- 0xBE,0xFA,0xFF,0xFF,0x12,0x00,0x28,0x00,0x68,0x00,0x00,0x00,0x5C,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x24,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
- 0x34,0xF2,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x31,0x38,0x00,0x00,
- 0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x50,0xF2,0xFF,0xFF,0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
- 0x07,0x00,0x00,0x00,0x66,0x6E,0x76,0x31,0x5F,0x36,0x34,0x00,0x04,0x00,0x00,0x00,0x68,0x61,0x73,0x68,
- 0x00,0x00,0x00,0x00,0x0E,0xEF,0xFF,0xFF,0x00,0x00,0x00,0x09,0x10,0x00,0x00,0x00,0x74,0x65,0x73,0x74,
- 0x68,0x61,0x73,0x68,0x73,0x36,0x34,0x5F,0x66,0x6E,0x76,0x31,0x00,0x00,0x00,0x00,0x46,0xFB,0xFF,0xFF,
- 0x11,0x00,0x26,0x00,0x68,0x00,0x00,0x00,0x5C,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
- 0x00,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x24,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xBC,0xF2,0xFF,0xFF,
- 0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x31,0x37,0x00,0x00,0x02,0x00,0x00,0x00,
- 0x69,0x64,0x00,0x00,0xD8,0xF2,0xFF,0xFF,0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x07,0x00,0x00,0x00,
- 0x66,0x6E,0x76,0x31,0x5F,0x33,0x32,0x00,0x04,0x00,0x00,0x00,0x68,0x61,0x73,0x68,0x00,0x00,0x00,0x00,
- 0x96,0xEF,0xFF,0xFF,0x00,0x00,0x00,0x08,0x10,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x68,0x61,0x73,0x68,
- 0x75,0x33,0x32,0x5F,0x66,0x6E,0x76,0x31,0x00,0x00,0x00,0x00,0xCE,0xFB,0xFF,0xFF,0x10,0x00,0x24,0x00,
- 0x68,0x00,0x00,0x00,0x5C,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
- 0x02,0x00,0x00,0x00,0x24,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x44,0xF3,0xFF,0xFF,0x10,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x31,0x36,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,
- 0x60,0xF3,0xFF,0xFF,0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x66,0x6E,0x76,0x31,
- 0x5F,0x33,0x32,0x00,0x04,0x00,0x00,0x00,0x68,0x61,0x73,0x68,0x00,0x00,0x00,0x00,0x1E,0xF0,0xFF,0xFF,
- 0x00,0x00,0x00,0x07,0x10,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x68,0x61,0x73,0x68,0x73,0x33,0x32,0x5F,
- 0x66,0x6E,0x76,0x31,0x00,0x00,0x00,0x00,0x56,0xFC,0xFF,0xFF,0x0F,0x00,0x22,0x00,0x40,0x00,0x00,0x00,
- 0x34,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0xC8,0xF3,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,
- 0x31,0x35,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x7E,0xF0,0xFF,0xFF,0x00,0x00,0x00,0x02,
- 0x08,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x62,0x6F,0x6F,0x6C,0x00,0x00,0x00,0x00,0xD4,0xFB,0xFF,0xFF,
- 0x00,0x00,0x00,0x01,0x0E,0x00,0x20,0x00,0x44,0x00,0x00,0x00,0x34,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x24,0xF4,0xFF,0xFF,
- 0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x31,0x34,0x00,0x00,0x02,0x00,0x00,0x00,
- 0x69,0x64,0x00,0x00,0x82,0xF1,0xFF,0xFF,0x00,0x00,0x00,0x0F,0x03,0x00,0x00,0x00,0x09,0x00,0x00,0x00,
- 0x74,0x65,0x73,0x74,0x65,0x6D,0x70,0x74,0x79,0x00,0x00,0x00,0x34,0xFC,0xFF,0xFF,0x00,0x00,0x00,0x01,
- 0x0D,0x00,0x1E,0x00,0x74,0x00,0x00,0x00,0x68,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
- 0x00,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x38,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x88,0xF4,0xFF,0xFF,
+ 0x00,0x00,0x10,0x00,0x1A,0x00,0x00,0x00,0x00,0x00,0x04,0x00,0x20,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x5C,0xD8,0xFF,0xFF,0x00,0x00,0x00,0x03,0x01,0x00,0x00,0x00,
+ 0x01,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x38,0x00,0x00,0x30,0xD7,0xFF,0xFF,0x30,0x01,0x00,0x00,
+ 0x50,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0xF4,0x27,0x00,0x00,0x01,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x33,0x00,0x00,0x00,0x20,0x61,0x6E,0x20,0x65,0x78,0x61,0x6D,0x70,0x6C,0x65,0x20,
+ 0x64,0x6F,0x63,0x75,0x6D,0x65,0x6E,0x74,0x61,0x74,0x69,0x6F,0x6E,0x20,0x63,0x6F,0x6D,0x6D,0x65,0x6E,
+ 0x74,0x3A,0x20,0x22,0x6D,0x6F,0x6E,0x73,0x74,0x65,0x72,0x20,0x6F,0x62,0x6A,0x65,0x63,0x74,0x22,0x00,
+ 0x36,0x00,0x00,0x00,0x80,0x04,0x00,0x00,0xE4,0x04,0x00,0x00,0x4C,0x05,0x00,0x00,0xAC,0x05,0x00,0x00,
+ 0xA8,0x09,0x00,0x00,0x78,0x1B,0x00,0x00,0x88,0x18,0x00,0x00,0x44,0x0F,0x00,0x00,0x7C,0x1C,0x00,0x00,
+ 0xC0,0x1D,0x00,0x00,0xEC,0x1B,0x00,0x00,0x44,0x01,0x00,0x00,0xC4,0x00,0x00,0x00,0x30,0x1E,0x00,0x00,
+ 0x30,0x1D,0x00,0x00,0xA8,0x01,0x00,0x00,0x10,0x07,0x00,0x00,0x80,0x0D,0x00,0x00,0xA0,0x1E,0x00,0x00,
+ 0x2C,0x02,0x00,0x00,0x5C,0x03,0x00,0x00,0x08,0x0C,0x00,0x00,0x58,0x1A,0x00,0x00,0xE4,0x19,0x00,0x00,
+ 0xA0,0x0E,0x00,0x00,0xC4,0x1A,0x00,0x00,0x90,0x11,0x00,0x00,0x78,0x0F,0x00,0x00,0x68,0x19,0x00,0x00,
+ 0xE0,0x0F,0x00,0x00,0x88,0x18,0x00,0x00,0xC0,0x16,0x00,0x00,0x1C,0x17,0x00,0x00,0x10,0x11,0x00,0x00,
+ 0x8C,0x10,0x00,0x00,0x30,0x10,0x00,0x00,0x20,0x16,0x00,0x00,0xE0,0x13,0x00,0x00,0xFC,0x14,0x00,0x00,
+ 0x58,0x12,0x00,0x00,0x84,0x15,0x00,0x00,0xE4,0x12,0x00,0x00,0x5C,0x14,0x00,0x00,0xB4,0x11,0x00,0x00,
+ 0x50,0x17,0x00,0x00,0x38,0x02,0x00,0x00,0xC0,0x07,0x00,0x00,0x78,0x0D,0x00,0x00,0x58,0x03,0x00,0x00,
+ 0xD8,0x0D,0x00,0x00,0x58,0x05,0x00,0x00,0x88,0x0C,0x00,0x00,0xDC,0x09,0x00,0x00,0x8C,0x0A,0x00,0x00,
+ 0x16,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,0x6D,0x65,0x2E,0x45,0x78,0x61,0x6D,0x70,0x6C,0x65,0x2E,0x4D,
+ 0x6F,0x6E,0x73,0x74,0x65,0x72,0x00,0x00,0x62,0xFD,0xFF,0xFF,0x35,0x00,0x6E,0x00,0x54,0x00,0x00,0x00,
+ 0x3C,0x00,0x00,0x00,0x14,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+ 0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x70,0xDB,0xFF,0xFF,0x10,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x35,0x33,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,
+ 0xEC,0xDA,0xFF,0xFF,0x00,0x00,0x00,0x0A,0x04,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
+ 0x18,0x00,0x00,0x00,0x6C,0x6F,0x6E,0x67,0x5F,0x65,0x6E,0x75,0x6D,0x5F,0x6E,0x6F,0x72,0x6D,0x61,0x6C,
+ 0x5F,0x64,0x65,0x66,0x61,0x75,0x6C,0x74,0x00,0x00,0x00,0x00,0x62,0xE6,0xFF,0xFF,0x34,0x00,0x6C,0x00,
+ 0x4C,0x00,0x00,0x00,0x34,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+ 0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xE4,0xDB,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x02,0x00,0x00,0x00,0x35,0x32,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x60,0xDB,0xFF,0xFF,
+ 0x00,0x00,0x00,0x0A,0x04,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x1A,0x00,0x00,0x00,
+ 0x6C,0x6F,0x6E,0x67,0x5F,0x65,0x6E,0x75,0x6D,0x5F,0x6E,0x6F,0x6E,0x5F,0x65,0x6E,0x75,0x6D,0x5F,0x64,
+ 0x65,0x66,0x61,0x75,0x6C,0x74,0x00,0x00,0xEC,0xE5,0xFF,0xFF,0x00,0x00,0x00,0x01,0x33,0x00,0x6A,0x00,
+ 0x74,0x00,0x00,0x00,0x60,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+ 0x02,0x00,0x00,0x00,0x30,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x60,0xDC,0xFF,0xFF,0x10,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x30,0x00,0x00,0x00,0x0D,0x00,0x00,0x00,0x6E,0x61,0x74,0x69,
+ 0x76,0x65,0x5F,0x69,0x6E,0x6C,0x69,0x6E,0x65,0x00,0x00,0x00,0x88,0xDC,0xFF,0xFF,0x10,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x35,0x31,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,
+ 0x50,0xD9,0xFF,0xFF,0x00,0x00,0x00,0x0F,0x05,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x0D,0x00,0x00,0x00,
+ 0x6E,0x61,0x74,0x69,0x76,0x65,0x5F,0x69,0x6E,0x6C,0x69,0x6E,0x65,0x00,0x00,0x00,0x80,0xE6,0xFF,0xFF,
+ 0x00,0x00,0x00,0x01,0x32,0x00,0x68,0x00,0x48,0x00,0x00,0x00,0x34,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xF0,0xDC,0xFF,0xFF,
+ 0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x35,0x30,0x00,0x00,0x02,0x00,0x00,0x00,
+ 0x69,0x64,0x00,0x00,0x38,0xE8,0xFF,0xFF,0x00,0x00,0x0E,0x0F,0x03,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x18,0x00,0x00,0x00,0x73,0x63,0x61,0x6C,0x61,0x72,0x5F,0x6B,0x65,0x79,0x5F,0x73,0x6F,0x72,0x74,0x65,
+ 0x64,0x5F,0x74,0x61,0x62,0x6C,0x65,0x73,0x00,0x00,0x00,0x00,0xF4,0xE6,0xFF,0xFF,0x00,0x00,0x00,0x01,
+ 0x31,0x00,0x66,0x00,0x78,0x00,0x00,0x00,0x68,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x00,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x38,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x68,0xDD,0xFF,0xFF,
0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x4D,0x6F,0x6E,0x73,0x74,0x65,0x72,0x00,
0x11,0x00,0x00,0x00,0x6E,0x65,0x73,0x74,0x65,0x64,0x5F,0x66,0x6C,0x61,0x74,0x62,0x75,0x66,0x66,0x65,
- 0x72,0x00,0x00,0x00,0xB8,0xF4,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,
- 0x31,0x33,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x4C,0xFC,0xFF,0xFF,0x00,0x00,0x0E,0x04,
+ 0x72,0x00,0x00,0x00,0x98,0xDD,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,
+ 0x34,0x39,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x0C,0xE7,0xFF,0xFF,0x00,0x00,0x0E,0x04,
+ 0x01,0x00,0x00,0x00,0x1C,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x72,0x65,0x71,0x75,0x69,0x72,0x65,0x64,
+ 0x6E,0x65,0x73,0x74,0x65,0x64,0x66,0x6C,0x61,0x74,0x62,0x75,0x66,0x66,0x65,0x72,0x00,0x00,0x1A,0x00,
+ 0x20,0x00,0x08,0x00,0x0C,0x00,0x04,0x00,0x06,0x00,0x18,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+ 0x10,0x00,0x14,0x00,0x1A,0x00,0x00,0x00,0x30,0x00,0x64,0x00,0x54,0x00,0x00,0x00,0x3C,0x00,0x00,0x00,
+ 0x14,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x00,0x00,0x00,0x00,
+ 0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x28,0xDE,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x02,0x00,0x00,0x00,0x34,0x38,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0xA4,0xDD,0xFF,0xFF,
+ 0x00,0x00,0x00,0x03,0x05,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x0B,0x00,0x00,0x00,
+ 0x73,0x69,0x67,0x6E,0x65,0x64,0x5F,0x65,0x6E,0x75,0x6D,0x00,0x20,0xE8,0xFF,0xFF,0x00,0x00,0x00,0x01,
+ 0x2F,0x00,0x62,0x00,0x48,0x00,0x00,0x00,0x34,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x90,0xDE,0xFF,0xFF,0x10,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x34,0x37,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,
+ 0xD8,0xE9,0xFF,0xFF,0x00,0x00,0x0E,0x04,0x03,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x0F,0x00,0x00,0x00,
+ 0x76,0x65,0x63,0x74,0x6F,0x72,0x5F,0x6F,0x66,0x5F,0x65,0x6E,0x75,0x6D,0x73,0x00,0x88,0xE8,0xFF,0xFF,
+ 0x00,0x00,0x00,0x01,0x2E,0x00,0x60,0x00,0x48,0x00,0x00,0x00,0x34,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xF8,0xDE,0xFF,0xFF,
+ 0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x34,0x36,0x00,0x00,0x02,0x00,0x00,0x00,
+ 0x69,0x64,0x00,0x00,0xC0,0xDB,0xFF,0xFF,0x00,0x00,0x00,0x10,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
+ 0x0D,0x00,0x00,0x00,0x61,0x6E,0x79,0x5F,0x61,0x6D,0x62,0x69,0x67,0x75,0x6F,0x75,0x73,0x00,0x00,0x00,
+ 0xDA,0xE9,0xFF,0xFF,0x2D,0x00,0x5E,0x00,0x4C,0x00,0x00,0x00,0x34,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x5C,0xDF,0xFF,0xFF,
+ 0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x34,0x35,0x00,0x00,0x02,0x00,0x00,0x00,
+ 0x69,0x64,0x00,0x00,0xD8,0xDE,0xFF,0xFF,0x00,0x00,0x00,0x01,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
+ 0x01,0x00,0x00,0x00,0x12,0x00,0x00,0x00,0x61,0x6E,0x79,0x5F,0x61,0x6D,0x62,0x69,0x67,0x75,0x6F,0x75,
+ 0x73,0x5F,0x74,0x79,0x70,0x65,0x00,0x00,0x5C,0xE9,0xFF,0xFF,0x00,0x00,0x00,0x01,0x2C,0x00,0x5C,0x00,
+ 0x48,0x00,0x00,0x00,0x34,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+ 0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xCC,0xDF,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x02,0x00,0x00,0x00,0x34,0x34,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x94,0xDC,0xFF,0xFF,
+ 0x00,0x00,0x00,0x10,0x02,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x0A,0x00,0x00,0x00,0x61,0x6E,0x79,0x5F,
+ 0x75,0x6E,0x69,0x71,0x75,0x65,0x00,0x00,0xAA,0xEA,0xFF,0xFF,0x2B,0x00,0x5A,0x00,0x4C,0x00,0x00,0x00,
+ 0x34,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x2C,0xE0,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,
+ 0x34,0x33,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0xA8,0xDF,0xFF,0xFF,0x00,0x00,0x00,0x01,
+ 0x02,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x0F,0x00,0x00,0x00,0x61,0x6E,0x79,0x5F,
+ 0x75,0x6E,0x69,0x71,0x75,0x65,0x5F,0x74,0x79,0x70,0x65,0x00,0x28,0xEA,0xFF,0xFF,0x00,0x00,0x00,0x01,
+ 0x2A,0x00,0x58,0x00,0x00,0x01,0x00,0x00,0xF0,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x00,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0xB0,0x00,0x00,0x00,0x80,0x00,0x00,0x00,0x50,0x00,0x00,0x00,
+ 0x24,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xA8,0xE0,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x02,0x00,0x00,0x00,0x34,0x32,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0xC4,0xE0,0xFF,0xFF,
+ 0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x66,0x6E,0x76,0x31,0x61,0x5F,0x36,0x34,
+ 0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x68,0x61,0x73,0x68,0x00,0x00,0x00,0x00,0xEC,0xE0,0xFF,0xFF,
+ 0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x0B,0x00,0x00,0x00,0x52,0x65,0x66,0x65,0x72,0x72,0x61,0x62,
+ 0x6C,0x65,0x54,0x00,0x08,0x00,0x00,0x00,0x63,0x70,0x70,0x5F,0x74,0x79,0x70,0x65,0x00,0x00,0x00,0x00,
+ 0x18,0xE1,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+ 0x10,0x00,0x00,0x00,0x63,0x70,0x70,0x5F,0x70,0x74,0x72,0x5F,0x74,0x79,0x70,0x65,0x5F,0x67,0x65,0x74,
+ 0x00,0x00,0x00,0x00,0x44,0xE1,0xFF,0xFF,0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x05,0x00,0x00,0x00,
+ 0x6E,0x61,0x6B,0x65,0x64,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x63,0x70,0x70,0x5F,0x70,0x74,0x72,0x5F,
+ 0x74,0x79,0x70,0x65,0x00,0x00,0x00,0x00,0xC8,0xEA,0xFF,0xFF,0x00,0x00,0x0E,0x0A,0x08,0x00,0x00,0x00,
+ 0x1F,0x00,0x00,0x00,0x76,0x65,0x63,0x74,0x6F,0x72,0x5F,0x6F,0x66,0x5F,0x6E,0x6F,0x6E,0x5F,0x6F,0x77,
+ 0x6E,0x69,0x6E,0x67,0x5F,0x72,0x65,0x66,0x65,0x72,0x65,0x6E,0x63,0x65,0x73,0x00,0x42,0xEC,0xFF,0xFF,
+ 0x29,0x00,0x56,0x00,0x04,0x01,0x00,0x00,0xF0,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x00,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0xB0,0x00,0x00,0x00,0x80,0x00,0x00,0x00,0x50,0x00,0x00,0x00,
+ 0x24,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xD4,0xE1,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x02,0x00,0x00,0x00,0x34,0x31,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0xF0,0xE1,0xFF,0xFF,
+ 0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x66,0x6E,0x76,0x31,0x61,0x5F,0x36,0x34,
+ 0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x68,0x61,0x73,0x68,0x00,0x00,0x00,0x00,0x18,0xE2,0xFF,0xFF,
+ 0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x0B,0x00,0x00,0x00,0x52,0x65,0x66,0x65,0x72,0x72,0x61,0x62,
+ 0x6C,0x65,0x54,0x00,0x08,0x00,0x00,0x00,0x63,0x70,0x70,0x5F,0x74,0x79,0x70,0x65,0x00,0x00,0x00,0x00,
+ 0x44,0xE2,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+ 0x10,0x00,0x00,0x00,0x63,0x70,0x70,0x5F,0x70,0x74,0x72,0x5F,0x74,0x79,0x70,0x65,0x5F,0x67,0x65,0x74,
+ 0x00,0x00,0x00,0x00,0x70,0xE2,0xFF,0xFF,0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x05,0x00,0x00,0x00,
+ 0x6E,0x61,0x6B,0x65,0x64,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x63,0x70,0x70,0x5F,0x70,0x74,0x72,0x5F,
+ 0x74,0x79,0x70,0x65,0x00,0x00,0x00,0x00,0x1C,0xE1,0xFF,0xFF,0x00,0x00,0x00,0x0A,0x08,0x00,0x00,0x00,
+ 0x01,0x00,0x00,0x00,0x14,0x00,0x00,0x00,0x6E,0x6F,0x6E,0x5F,0x6F,0x77,0x6E,0x69,0x6E,0x67,0x5F,0x72,
+ 0x65,0x66,0x65,0x72,0x65,0x6E,0x63,0x65,0x00,0x00,0x00,0x00,0x80,0xEC,0xFF,0xFF,0x00,0x00,0x00,0x01,
+ 0x28,0x00,0x54,0x00,0x10,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x00,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0xB4,0x00,0x00,0x00,0x80,0x00,0x00,0x00,0x50,0x00,0x00,0x00,
+ 0x24,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0xE3,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x02,0x00,0x00,0x00,0x34,0x30,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x1C,0xE3,0xFF,0xFF,
+ 0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x66,0x6E,0x76,0x31,0x61,0x5F,0x36,0x34,
+ 0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x68,0x61,0x73,0x68,0x00,0x00,0x00,0x00,0x44,0xE3,0xFF,0xFF,
+ 0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x0B,0x00,0x00,0x00,0x52,0x65,0x66,0x65,0x72,0x72,0x61,0x62,
+ 0x6C,0x65,0x54,0x00,0x08,0x00,0x00,0x00,0x63,0x70,0x70,0x5F,0x74,0x79,0x70,0x65,0x00,0x00,0x00,0x00,
+ 0x70,0xE3,0xFF,0xFF,0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x06,0x00,0x00,0x00,0x2E,0x67,0x65,0x74,
+ 0x28,0x29,0x00,0x00,0x10,0x00,0x00,0x00,0x63,0x70,0x70,0x5F,0x70,0x74,0x72,0x5F,0x74,0x79,0x70,0x65,
+ 0x5F,0x67,0x65,0x74,0x00,0x00,0x00,0x00,0xA0,0xE3,0xFF,0xFF,0x20,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x10,0x00,0x00,0x00,0x64,0x65,0x66,0x61,0x75,0x6C,0x74,0x5F,0x70,0x74,0x72,0x5F,0x74,0x79,0x70,0x65,
+ 0x00,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x63,0x70,0x70,0x5F,0x70,0x74,0x72,0x5F,0x74,0x79,0x70,0x65,
+ 0x00,0x00,0x00,0x00,0x30,0xED,0xFF,0xFF,0x00,0x00,0x0E,0x0A,0x08,0x00,0x00,0x00,0x1E,0x00,0x00,0x00,
+ 0x76,0x65,0x63,0x74,0x6F,0x72,0x5F,0x6F,0x66,0x5F,0x63,0x6F,0x5F,0x6F,0x77,0x6E,0x69,0x6E,0x67,0x5F,
+ 0x72,0x65,0x66,0x65,0x72,0x65,0x6E,0x63,0x65,0x73,0x00,0x00,0xAA,0xEE,0xFF,0xFF,0x27,0x00,0x52,0x00,
+ 0xD4,0x00,0x00,0x00,0xC0,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x80,0x00,0x00,0x00,0x50,0x00,0x00,0x00,0x24,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x38,0xE4,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x33,0x39,0x00,0x00,
+ 0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x54,0xE4,0xFF,0xFF,0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x08,0x00,0x00,0x00,0x66,0x6E,0x76,0x31,0x61,0x5F,0x36,0x34,0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x68,0x61,0x73,0x68,0x00,0x00,0x00,0x00,0x7C,0xE4,0xFF,0xFF,0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x0B,0x00,0x00,0x00,0x52,0x65,0x66,0x65,0x72,0x72,0x61,0x62,0x6C,0x65,0x54,0x00,0x08,0x00,0x00,0x00,
+ 0x63,0x70,0x70,0x5F,0x74,0x79,0x70,0x65,0x00,0x00,0x00,0x00,0xA8,0xE4,0xFF,0xFF,0x14,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0x6E,0x61,0x6B,0x65,0x64,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,
+ 0x63,0x70,0x70,0x5F,0x70,0x74,0x72,0x5F,0x74,0x79,0x70,0x65,0x00,0x00,0x00,0x00,0x54,0xE3,0xFF,0xFF,
+ 0x00,0x00,0x00,0x0A,0x08,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x13,0x00,0x00,0x00,0x63,0x6F,0x5F,0x6F,
+ 0x77,0x6E,0x69,0x6E,0x67,0x5F,0x72,0x65,0x66,0x65,0x72,0x65,0x6E,0x63,0x65,0x00,0xB4,0xEE,0xFF,0xFF,
+ 0x00,0x00,0x00,0x01,0x26,0x00,0x50,0x00,0x84,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x24,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x28,0xE5,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x33,0x38,0x00,0x00,
+ 0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x44,0xE5,0xFF,0xFF,0x20,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x10,0x00,0x00,0x00,0x64,0x65,0x66,0x61,0x75,0x6C,0x74,0x5F,0x70,0x74,0x72,0x5F,0x74,0x79,0x70,0x65,
+ 0x00,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x63,0x70,0x70,0x5F,0x70,0x74,0x72,0x5F,0x74,0x79,0x70,0x65,
+ 0x00,0x00,0x00,0x00,0xA8,0xF0,0xFF,0xFF,0x00,0x00,0x0E,0x0F,0x02,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x1C,0x00,0x00,0x00,0x76,0x65,0x63,0x74,0x6F,0x72,0x5F,0x6F,0x66,0x5F,0x73,0x74,0x72,0x6F,0x6E,0x67,
+ 0x5F,0x72,0x65,0x66,0x65,0x72,0x72,0x61,0x62,0x6C,0x65,0x73,0x00,0x00,0x00,0x00,0x68,0xEF,0xFF,0xFF,
+ 0x00,0x00,0x00,0x01,0x25,0x00,0x4E,0x00,0xD0,0x00,0x00,0x00,0xC0,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x80,0x00,0x00,0x00,0x50,0x00,0x00,0x00,
+ 0x24,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xE4,0xE5,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x02,0x00,0x00,0x00,0x33,0x37,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x00,0xE6,0xFF,0xFF,
+ 0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x66,0x6E,0x76,0x31,0x61,0x5F,0x36,0x34,
+ 0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x68,0x61,0x73,0x68,0x00,0x00,0x00,0x00,0x28,0xE6,0xFF,0xFF,
+ 0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x0B,0x00,0x00,0x00,0x52,0x65,0x66,0x65,0x72,0x72,0x61,0x62,
+ 0x6C,0x65,0x54,0x00,0x08,0x00,0x00,0x00,0x63,0x70,0x70,0x5F,0x74,0x79,0x70,0x65,0x00,0x00,0x00,0x00,
+ 0x54,0xE6,0xFF,0xFF,0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0x6E,0x61,0x6B,0x65,
+ 0x64,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x63,0x70,0x70,0x5F,0x70,0x74,0x72,0x5F,0x74,0x79,0x70,0x65,
+ 0x00,0x00,0x00,0x00,0xD8,0xEF,0xFF,0xFF,0x00,0x00,0x0E,0x0A,0x08,0x00,0x00,0x00,0x19,0x00,0x00,0x00,
+ 0x76,0x65,0x63,0x74,0x6F,0x72,0x5F,0x6F,0x66,0x5F,0x77,0x65,0x61,0x6B,0x5F,0x72,0x65,0x66,0x65,0x72,
+ 0x65,0x6E,0x63,0x65,0x73,0x00,0x00,0x00,0x4E,0xF1,0xFF,0xFF,0x24,0x00,0x4C,0x00,0xD4,0x00,0x00,0x00,
+ 0xC0,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x80,0x00,0x00,0x00,0x50,0x00,0x00,0x00,0x24,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xDC,0xE6,0xFF,0xFF,
+ 0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x33,0x36,0x00,0x00,0x02,0x00,0x00,0x00,
+ 0x69,0x64,0x00,0x00,0xF8,0xE6,0xFF,0xFF,0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x08,0x00,0x00,0x00,
+ 0x66,0x6E,0x76,0x31,0x61,0x5F,0x36,0x34,0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x68,0x61,0x73,0x68,
+ 0x00,0x00,0x00,0x00,0x20,0xE7,0xFF,0xFF,0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x0B,0x00,0x00,0x00,
+ 0x52,0x65,0x66,0x65,0x72,0x72,0x61,0x62,0x6C,0x65,0x54,0x00,0x08,0x00,0x00,0x00,0x63,0x70,0x70,0x5F,
+ 0x74,0x79,0x70,0x65,0x00,0x00,0x00,0x00,0x4C,0xE7,0xFF,0xFF,0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x05,0x00,0x00,0x00,0x6E,0x61,0x6B,0x65,0x64,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x63,0x70,0x70,0x5F,
+ 0x70,0x74,0x72,0x5F,0x74,0x79,0x70,0x65,0x00,0x00,0x00,0x00,0xF8,0xE5,0xFF,0xFF,0x00,0x00,0x00,0x0A,
+ 0x08,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x15,0x00,0x00,0x00,0x73,0x69,0x6E,0x67,0x6C,0x65,0x5F,0x77,
+ 0x65,0x61,0x6B,0x5F,0x72,0x65,0x66,0x65,0x72,0x65,0x6E,0x63,0x65,0x00,0x00,0x00,0x5C,0xF1,0xFF,0xFF,
+ 0x00,0x00,0x00,0x01,0x23,0x00,0x4A,0x00,0x48,0x00,0x00,0x00,0x34,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xCC,0xE7,0xFF,0xFF,
+ 0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x33,0x35,0x00,0x00,0x02,0x00,0x00,0x00,
+ 0x69,0x64,0x00,0x00,0x14,0xF3,0xFF,0xFF,0x00,0x00,0x0E,0x0F,0x02,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x15,0x00,0x00,0x00,0x76,0x65,0x63,0x74,0x6F,0x72,0x5F,0x6F,0x66,0x5F,0x72,0x65,0x66,0x65,0x72,0x72,
+ 0x61,0x62,0x6C,0x65,0x73,0x00,0x00,0x00,0xCC,0xF1,0xFF,0xFF,0x00,0x00,0x00,0x01,0x22,0x00,0x48,0x00,
+ 0x48,0x00,0x00,0x00,0x34,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+ 0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x3C,0xE8,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x02,0x00,0x00,0x00,0x33,0x34,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x04,0xE5,0xFF,0xFF,
+ 0x00,0x00,0x00,0x0F,0x0A,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x15,0x00,0x00,0x00,0x70,0x61,0x72,0x65,
+ 0x6E,0x74,0x5F,0x6E,0x61,0x6D,0x65,0x73,0x70,0x61,0x63,0x65,0x5F,0x74,0x65,0x73,0x74,0x00,0x00,0x00,
+ 0x3C,0xF2,0xFF,0xFF,0x00,0x00,0x00,0x01,0x21,0x00,0x46,0x00,0x44,0x00,0x00,0x00,0x34,0x00,0x00,0x00,
+ 0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0xAC,0xE8,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x33,0x33,0x00,0x00,
+ 0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x20,0xF2,0xFF,0xFF,0x00,0x00,0x0E,0x0C,0x08,0x00,0x00,0x00,
+ 0x11,0x00,0x00,0x00,0x76,0x65,0x63,0x74,0x6F,0x72,0x5F,0x6F,0x66,0x5F,0x64,0x6F,0x75,0x62,0x6C,0x65,
+ 0x73,0x00,0x00,0x00,0xA4,0xF2,0xFF,0xFF,0x00,0x00,0x00,0x01,0x20,0x00,0x44,0x00,0x44,0x00,0x00,0x00,
+ 0x34,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x14,0xE9,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,
+ 0x33,0x32,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x88,0xF2,0xFF,0xFF,0x00,0x00,0x0E,0x09,
+ 0x08,0x00,0x00,0x00,0x0F,0x00,0x00,0x00,0x76,0x65,0x63,0x74,0x6F,0x72,0x5F,0x6F,0x66,0x5F,0x6C,0x6F,
+ 0x6E,0x67,0x73,0x00,0x08,0xF3,0xFF,0xFF,0x00,0x00,0x00,0x01,0x1F,0x00,0x42,0x00,0x48,0x00,0x00,0x00,
+ 0x34,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x78,0xE9,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,
+ 0x33,0x31,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0xC0,0xF4,0xFF,0xFF,0x00,0x00,0x0E,0x0F,
+ 0x05,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x35,0x00,0x00,0x00,
+ 0x68,0xF3,0xFF,0xFF,0x00,0x00,0x00,0x01,0x1E,0x00,0x40,0x00,0x6C,0x00,0x00,0x00,0x5C,0x00,0x00,0x00,
+ 0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x24,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0xDC,0xE9,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,
+ 0x33,0x30,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0xF8,0xE9,0xFF,0xFF,0x10,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x30,0x00,0x00,0x00,0x0A,0x00,0x00,0x00,0x66,0x6C,0x65,0x78,
+ 0x62,0x75,0x66,0x66,0x65,0x72,0x00,0x00,0x74,0xF3,0xFF,0xFF,0x00,0x00,0x0E,0x04,0x01,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x66,0x6C,0x65,0x78,0x00,0x00,0x00,0x00,0xEC,0xF3,0xFF,0xFF,0x00,0x00,0x00,0x01,
+ 0x1D,0x00,0x3E,0x00,0x48,0x00,0x00,0x00,0x34,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x5C,0xEA,0xFF,0xFF,0x10,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x32,0x39,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,
+ 0xA4,0xF5,0xFF,0xFF,0x00,0x00,0x0E,0x0F,0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x17,0x00,0x00,0x00,
+ 0x74,0x65,0x73,0x74,0x61,0x72,0x72,0x61,0x79,0x6F,0x66,0x73,0x6F,0x72,0x74,0x65,0x64,0x73,0x74,0x72,
+ 0x75,0x63,0x74,0x00,0x5C,0xF4,0xFF,0xFF,0x00,0x00,0x00,0x01,0x1C,0x00,0x3C,0x00,0x44,0x00,0x00,0x00,
+ 0x34,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0xCC,0xEA,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,
+ 0x32,0x38,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x40,0xF4,0xFF,0xFF,0x00,0x00,0x0E,0x0D,
+ 0x04,0x00,0x00,0x00,0x12,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x61,0x72,0x72,0x61,0x79,0x6F,0x66,0x73,
+ 0x74,0x72,0x69,0x6E,0x67,0x32,0x00,0x00,0xAE,0xF5,0xFF,0xFF,0x1B,0x00,0x3A,0x00,0x44,0x00,0x00,0x00,
+ 0x34,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x30,0xEB,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,
+ 0x32,0x37,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x14,0xE7,0xFF,0xFF,0x00,0x00,0x00,0x0B,
+ 0x01,0x00,0x00,0x00,0x06,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x66,0x33,0x00,0x00,0x9A,0xFF,0xFF,0xFF,
+ 0x1A,0x00,0x38,0x00,0x50,0x00,0x00,0x00,0x40,0x00,0x00,0x00,0x18,0x00,0x00,0x00,0x10,0x00,0x00,0x00,
+ 0x00,0x00,0x00,0x00,0x00,0x00,0x08,0x40,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x94,0xEB,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,
+ 0x32,0x36,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x78,0xE7,0xFF,0xFF,0x00,0x00,0x00,0x0B,
+ 0x01,0x00,0x00,0x00,0x06,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x66,0x32,0x00,0x00,0x00,0x00,0x1A,0x00,
+ 0x24,0x00,0x08,0x00,0x0C,0x00,0x04,0x00,0x06,0x00,0x00,0x00,0x18,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+ 0x10,0x00,0x14,0x00,0x1A,0x00,0x00,0x00,0x19,0x00,0x36,0x00,0x50,0x00,0x00,0x00,0x40,0x00,0x00,0x00,
+ 0x18,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x6E,0x86,0x1B,0xF0,0xF9,0x21,0x09,0x40,0x00,0x00,0x00,0x00,
+ 0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x14,0xEC,0xFF,0xFF,0x10,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x32,0x35,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,
+ 0xF8,0xE7,0xFF,0xFF,0x00,0x00,0x00,0x0B,0x01,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0x74,0x65,0x73,0x74,
+ 0x66,0x00,0x00,0x00,0x00,0xF6,0xFF,0xFF,0x00,0x00,0x00,0x01,0x18,0x00,0x34,0x00,0x44,0x00,0x00,0x00,
+ 0x34,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x70,0xEC,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,
+ 0x32,0x34,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0xE4,0xF5,0xFF,0xFF,0x00,0x00,0x0E,0x02,
+ 0x01,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x61,0x72,0x72,0x61,0x79,0x6F,0x66,0x62,
+ 0x6F,0x6F,0x6C,0x73,0x00,0x00,0x00,0x00,0x52,0xF7,0xFF,0xFF,0x17,0x00,0x32,0x00,0x74,0x00,0x00,0x00,
+ 0x60,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x00,0x00,0x00,
+ 0x24,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xD8,0xEC,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x02,0x00,0x00,0x00,0x32,0x33,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0xF4,0xEC,0xFF,0xFF,
+ 0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x66,0x6E,0x76,0x31,0x61,0x5F,0x36,0x34,
+ 0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x68,0x61,0x73,0x68,0x00,0x00,0x00,0x00,0x9C,0xEB,0xFF,0xFF,
+ 0x00,0x00,0x00,0x0A,0x08,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x11,0x00,0x00,0x00,0x74,0x65,0x73,0x74,
+ 0x68,0x61,0x73,0x68,0x75,0x36,0x34,0x5F,0x66,0x6E,0x76,0x31,0x61,0x00,0x00,0x00,0xE6,0xF7,0xFF,0xFF,
+ 0x16,0x00,0x30,0x00,0x74,0x00,0x00,0x00,0x60,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x00,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x24,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x6C,0xED,0xFF,0xFF,
+ 0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x32,0x32,0x00,0x00,0x02,0x00,0x00,0x00,
+ 0x69,0x64,0x00,0x00,0x88,0xED,0xFF,0xFF,0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x08,0x00,0x00,0x00,
+ 0x66,0x6E,0x76,0x31,0x61,0x5F,0x36,0x34,0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x68,0x61,0x73,0x68,
+ 0x00,0x00,0x00,0x00,0x30,0xEC,0xFF,0xFF,0x00,0x00,0x00,0x09,0x08,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
+ 0x11,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x68,0x61,0x73,0x68,0x73,0x36,0x34,0x5F,0x66,0x6E,0x76,0x31,
+ 0x61,0x00,0x00,0x00,0x7A,0xF8,0xFF,0xFF,0x15,0x00,0x2E,0x00,0xCC,0x00,0x00,0x00,0xBC,0x00,0x00,0x00,
+ 0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x7C,0x00,0x00,0x00,
+ 0x50,0x00,0x00,0x00,0x24,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x08,0xEE,0xFF,0xFF,0x10,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x32,0x31,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,
+ 0x24,0xEE,0xFF,0xFF,0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x66,0x6E,0x76,0x31,
+ 0x61,0x5F,0x33,0x32,0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x68,0x61,0x73,0x68,0x00,0x00,0x00,0x00,
+ 0x4C,0xEE,0xFF,0xFF,0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x53,0x74,0x61,0x74,
+ 0x00,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x63,0x70,0x70,0x5F,0x74,0x79,0x70,0x65,0x00,0x00,0x00,0x00,
+ 0x74,0xEE,0xFF,0xFF,0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0x6E,0x61,0x6B,0x65,
+ 0x64,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x63,0x70,0x70,0x5F,0x70,0x74,0x72,0x5F,0x74,0x79,0x70,0x65,
+ 0x00,0x00,0x00,0x00,0x68,0xEA,0xFF,0xFF,0x00,0x00,0x00,0x08,0x01,0x00,0x00,0x00,0x11,0x00,0x00,0x00,
+ 0x74,0x65,0x73,0x74,0x68,0x61,0x73,0x68,0x75,0x33,0x32,0x5F,0x66,0x6E,0x76,0x31,0x61,0x00,0x00,0x00,
+ 0x66,0xF9,0xFF,0xFF,0x14,0x00,0x2C,0x00,0x70,0x00,0x00,0x00,0x60,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x24,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0xEC,0xEE,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x32,0x30,0x00,0x00,
+ 0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x08,0xEF,0xFF,0xFF,0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x08,0x00,0x00,0x00,0x66,0x6E,0x76,0x31,0x61,0x5F,0x33,0x32,0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x68,0x61,0x73,0x68,0x00,0x00,0x00,0x00,0xF8,0xEA,0xFF,0xFF,0x00,0x00,0x00,0x07,0x01,0x00,0x00,0x00,
+ 0x11,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x68,0x61,0x73,0x68,0x73,0x33,0x32,0x5F,0x66,0x6E,0x76,0x31,
+ 0x61,0x00,0x00,0x00,0xF6,0xF9,0xFF,0xFF,0x13,0x00,0x2A,0x00,0x70,0x00,0x00,0x00,0x5C,0x00,0x00,0x00,
+ 0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x24,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x7C,0xEF,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,
+ 0x31,0x39,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x98,0xEF,0xFF,0xFF,0x14,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x66,0x6E,0x76,0x31,0x5F,0x36,0x34,0x00,0x04,0x00,0x00,0x00,
+ 0x68,0x61,0x73,0x68,0x00,0x00,0x00,0x00,0x3C,0xEE,0xFF,0xFF,0x00,0x00,0x00,0x0A,0x08,0x00,0x00,0x00,
+ 0x01,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x68,0x61,0x73,0x68,0x75,0x36,0x34,0x5F,
+ 0x66,0x6E,0x76,0x31,0x00,0x00,0x00,0x00,0x86,0xFA,0xFF,0xFF,0x12,0x00,0x28,0x00,0x70,0x00,0x00,0x00,
+ 0x5C,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x00,0x00,0x00,
+ 0x24,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x0C,0xF0,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x02,0x00,0x00,0x00,0x31,0x38,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x28,0xF0,0xFF,0xFF,
+ 0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x66,0x6E,0x76,0x31,0x5F,0x36,0x34,0x00,
+ 0x04,0x00,0x00,0x00,0x68,0x61,0x73,0x68,0x00,0x00,0x00,0x00,0xCC,0xEE,0xFF,0xFF,0x00,0x00,0x00,0x09,
+ 0x08,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x68,0x61,0x73,0x68,
+ 0x73,0x36,0x34,0x5F,0x66,0x6E,0x76,0x31,0x00,0x00,0x00,0x00,0x16,0xFB,0xFF,0xFF,0x11,0x00,0x26,0x00,
+ 0x6C,0x00,0x00,0x00,0x5C,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+ 0x02,0x00,0x00,0x00,0x24,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x9C,0xF0,0xFF,0xFF,0x10,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x31,0x37,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,
+ 0xB8,0xF0,0xFF,0xFF,0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x66,0x6E,0x76,0x31,
+ 0x5F,0x33,0x32,0x00,0x04,0x00,0x00,0x00,0x68,0x61,0x73,0x68,0x00,0x00,0x00,0x00,0xA4,0xEC,0xFF,0xFF,
+ 0x00,0x00,0x00,0x08,0x01,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x68,0x61,0x73,0x68,
+ 0x75,0x33,0x32,0x5F,0x66,0x6E,0x76,0x31,0x00,0x00,0x00,0x00,0xA2,0xFB,0xFF,0xFF,0x10,0x00,0x24,0x00,
+ 0x6C,0x00,0x00,0x00,0x5C,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+ 0x02,0x00,0x00,0x00,0x24,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x28,0xF1,0xFF,0xFF,0x10,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x31,0x36,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,
+ 0x44,0xF1,0xFF,0xFF,0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x66,0x6E,0x76,0x31,
+ 0x5F,0x33,0x32,0x00,0x04,0x00,0x00,0x00,0x68,0x61,0x73,0x68,0x00,0x00,0x00,0x00,0x30,0xED,0xFF,0xFF,
+ 0x00,0x00,0x00,0x07,0x01,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x68,0x61,0x73,0x68,
+ 0x73,0x33,0x32,0x5F,0x66,0x6E,0x76,0x31,0x00,0x00,0x00,0x00,0x2E,0xFC,0xFF,0xFF,0x0F,0x00,0x22,0x00,
+ 0x48,0x00,0x00,0x00,0x34,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+ 0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xB0,0xF1,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x02,0x00,0x00,0x00,0x31,0x35,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x4C,0xF0,0xFF,0xFF,
+ 0x00,0x00,0x00,0x02,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x74,0x65,0x73,0x74,
+ 0x62,0x6F,0x6F,0x6C,0x00,0x00,0x00,0x00,0xA4,0xFB,0xFF,0xFF,0x00,0x00,0x00,0x01,0x0E,0x00,0x20,0x00,
+ 0x48,0x00,0x00,0x00,0x34,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+ 0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x14,0xF2,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x02,0x00,0x00,0x00,0x31,0x34,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0xDC,0xEE,0xFF,0xFF,
+ 0x00,0x00,0x00,0x0F,0x03,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x09,0x00,0x00,0x00,0x74,0x65,0x73,0x74,
+ 0x65,0x6D,0x70,0x74,0x79,0x00,0x00,0x00,0x08,0xFC,0xFF,0xFF,0x00,0x00,0x00,0x01,0x0D,0x00,0x1E,0x00,
+ 0x78,0x00,0x00,0x00,0x68,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+ 0x02,0x00,0x00,0x00,0x38,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x7C,0xF2,0xFF,0xFF,0x14,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x4D,0x6F,0x6E,0x73,0x74,0x65,0x72,0x00,0x11,0x00,0x00,0x00,
+ 0x6E,0x65,0x73,0x74,0x65,0x64,0x5F,0x66,0x6C,0x61,0x74,0x62,0x75,0x66,0x66,0x65,0x72,0x00,0x00,0x00,
+ 0xAC,0xF2,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x31,0x33,0x00,0x00,
+ 0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x20,0xFC,0xFF,0xFF,0x00,0x00,0x0E,0x04,0x01,0x00,0x00,0x00,
0x14,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x6E,0x65,0x73,0x74,0x65,0x64,0x66,0x6C,0x61,0x74,0x62,0x75,
- 0x66,0x66,0x65,0x72,0x00,0x00,0x00,0x00,0xD0,0xFC,0xFF,0xFF,0x00,0x00,0x00,0x01,0x0C,0x00,0x1C,0x00,
- 0x44,0x00,0x00,0x00,0x34,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
- 0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x20,0xF5,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
- 0x02,0x00,0x00,0x00,0x31,0x32,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x7E,0xF2,0xFF,0xFF,
- 0x00,0x00,0x00,0x0F,0x01,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0x65,0x6E,0x65,0x6D,0x79,0x00,0x00,0x00,
- 0x2C,0xFD,0xFF,0xFF,0x00,0x00,0x00,0x01,0x0B,0x00,0x1A,0x00,0xB0,0x00,0x00,0x00,0xA0,0x00,0x00,0x00,
- 0x78,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x1C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
- 0x0E,0x00,0x00,0x00,0x20,0x6D,0x75,0x6C,0x74,0x69,0x6C,0x69,0x6E,0x65,0x20,0x74,0x6F,0x6F,0x00,0x00,
- 0x49,0x00,0x00,0x00,0x20,0x61,0x6E,0x20,0x65,0x78,0x61,0x6D,0x70,0x6C,0x65,0x20,0x64,0x6F,0x63,0x75,
- 0x6D,0x65,0x6E,0x74,0x61,0x74,0x69,0x6F,0x6E,0x20,0x63,0x6F,0x6D,0x6D,0x65,0x6E,0x74,0x3A,0x20,0x74,
- 0x68,0x69,0x73,0x20,0x77,0x69,0x6C,0x6C,0x20,0x65,0x6E,0x64,0x20,0x75,0x70,0x20,0x69,0x6E,0x20,0x74,
- 0x68,0x65,0x20,0x67,0x65,0x6E,0x65,0x72,0x61,0x74,0x65,0x64,0x20,0x63,0x6F,0x64,0x65,0x00,0x00,0x00,
- 0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xE8,0xF5,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
- 0x02,0x00,0x00,0x00,0x31,0x31,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x32,0xFF,0xFF,0xFF,
- 0x00,0x00,0x0E,0x0F,0x01,0x00,0x00,0x00,0x11,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x61,0x72,0x72,0x61,
- 0x79,0x6F,0x66,0x74,0x61,0x62,0x6C,0x65,0x73,0x00,0x00,0x00,0x00,0xFE,0xFF,0xFF,0x00,0x00,0x00,0x01,
- 0x0A,0x00,0x18,0x00,0x40,0x00,0x00,0x00,0x34,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
- 0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x50,0xF6,0xFF,0xFF,0x10,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x31,0x30,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,
- 0xE4,0xFD,0xFF,0xFF,0x00,0x00,0x0E,0x0D,0x11,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x61,0x72,0x72,0x61,
- 0x79,0x6F,0x66,0x73,0x74,0x72,0x69,0x6E,0x67,0x00,0x00,0x00,0x64,0xFE,0xFF,0xFF,0x00,0x00,0x00,0x01,
- 0x09,0x00,0x16,0x00,0x50,0x00,0x00,0x00,0x40,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
- 0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xB4,0xF6,0xFF,0xFF,0x10,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x39,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,
- 0x00,0x00,0x0A,0x00,0x0C,0x00,0x06,0x00,0x07,0x00,0x08,0x00,0x0A,0x00,0x00,0x00,0x00,0x00,0x0E,0x0F,
- 0x04,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x34,0x00,0x00,0x00,0xCC,0xFE,0xFF,0xFF,
- 0x00,0x00,0x00,0x01,0x08,0x00,0x14,0x00,0x44,0x00,0x00,0x00,0x34,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x1C,0xF7,0xFF,0xFF,
+ 0x66,0x66,0x65,0x72,0x00,0x00,0x00,0x00,0xA8,0xFC,0xFF,0xFF,0x00,0x00,0x00,0x01,0x0C,0x00,0x1C,0x00,
+ 0x48,0x00,0x00,0x00,0x34,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+ 0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x18,0xF3,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x02,0x00,0x00,0x00,0x31,0x32,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0xE0,0xEF,0xFF,0xFF,
+ 0x00,0x00,0x00,0x0F,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0x65,0x6E,0x65,0x6D,
+ 0x79,0x00,0x00,0x00,0x08,0xFD,0xFF,0xFF,0x00,0x00,0x00,0x01,0x0B,0x00,0x1A,0x00,0xB4,0x00,0x00,0x00,
+ 0xA0,0x00,0x00,0x00,0x78,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x1C,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x0E,0x00,0x00,0x00,0x20,0x6D,0x75,0x6C,0x74,0x69,0x6C,0x69,0x6E,0x65,0x20,0x74,
+ 0x6F,0x6F,0x00,0x00,0x49,0x00,0x00,0x00,0x20,0x61,0x6E,0x20,0x65,0x78,0x61,0x6D,0x70,0x6C,0x65,0x20,
+ 0x64,0x6F,0x63,0x75,0x6D,0x65,0x6E,0x74,0x61,0x74,0x69,0x6F,0x6E,0x20,0x63,0x6F,0x6D,0x6D,0x65,0x6E,
+ 0x74,0x3A,0x20,0x74,0x68,0x69,0x73,0x20,0x77,0x69,0x6C,0x6C,0x20,0x65,0x6E,0x64,0x20,0x75,0x70,0x20,
+ 0x69,0x6E,0x20,0x74,0x68,0x65,0x20,0x67,0x65,0x6E,0x65,0x72,0x61,0x74,0x65,0x64,0x20,0x63,0x6F,0x64,
+ 0x65,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xE4,0xF3,0xFF,0xFF,0x10,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x31,0x31,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,
+ 0x2C,0xFF,0xFF,0xFF,0x00,0x00,0x0E,0x0F,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x11,0x00,0x00,0x00,
+ 0x74,0x65,0x73,0x74,0x61,0x72,0x72,0x61,0x79,0x6F,0x66,0x74,0x61,0x62,0x6C,0x65,0x73,0x00,0x00,0x00,
+ 0xE0,0xFD,0xFF,0xFF,0x00,0x00,0x00,0x01,0x0A,0x00,0x18,0x00,0x44,0x00,0x00,0x00,0x34,0x00,0x00,0x00,
+ 0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x50,0xF4,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x31,0x30,0x00,0x00,
+ 0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0xC4,0xFD,0xFF,0xFF,0x00,0x00,0x0E,0x0D,0x04,0x00,0x00,0x00,
+ 0x11,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x61,0x72,0x72,0x61,0x79,0x6F,0x66,0x73,0x74,0x72,0x69,0x6E,
+ 0x67,0x00,0x00,0x00,0x48,0xFE,0xFF,0xFF,0x00,0x00,0x00,0x01,0x09,0x00,0x16,0x00,0x58,0x00,0x00,0x00,
+ 0x44,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0xB8,0xF4,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
+ 0x39,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x10,0x00,0x10,0x00,0x06,0x00,0x07,0x00,
+ 0x08,0x00,0x00,0x00,0x00,0x00,0x0C,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x0E,0x0F,0x05,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x34,0x00,0x00,0x00,0xB8,0xFE,0xFF,0xFF,
+ 0x00,0x00,0x00,0x01,0x08,0x00,0x14,0x00,0x48,0x00,0x00,0x00,0x34,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x28,0xF5,0xFF,0xFF,
0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x38,0x00,0x00,0x00,0x02,0x00,0x00,0x00,
- 0x69,0x64,0x00,0x00,0x7A,0xF4,0xFF,0xFF,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
- 0x74,0x65,0x73,0x74,0x00,0x00,0x1A,0x00,0x18,0x00,0x08,0x00,0x0C,0x00,0x04,0x00,0x06,0x00,0x00,0x00,
- 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x14,0x00,0x1A,0x00,0x00,0x00,0x07,0x00,0x12,0x00,
- 0x44,0x00,0x00,0x00,0x34,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
- 0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x8C,0xF7,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
- 0x01,0x00,0x00,0x00,0x37,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0xEA,0xF4,0xFF,0xFF,
- 0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x09,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x5F,0x74,0x79,0x70,
- 0x65,0x00,0x00,0x00,0xA2,0xFD,0xFF,0xFF,0x06,0x00,0x10,0x00,0x50,0x00,0x00,0x00,0x40,0x00,0x00,0x00,
- 0x18,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
- 0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xF4,0xF7,0xFF,0xFF,0x10,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x36,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,
- 0x52,0xF5,0xFF,0xFF,0x00,0x00,0x00,0x04,0x03,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0x63,0x6F,0x6C,0x6F,
+ 0x69,0x64,0x00,0x00,0xF0,0xF1,0xFF,0xFF,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x00,0x00,0x1A,0x00,0x18,0x00,0x08,0x00,0x0C,0x00,0x04,0x00,
+ 0x06,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x14,0x00,0x1A,0x00,0x00,0x00,
+ 0x07,0x00,0x12,0x00,0x4C,0x00,0x00,0x00,0x34,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x9C,0xF5,0xFF,0xFF,0x10,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x37,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,
+ 0x18,0xF5,0xFF,0xFF,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
+ 0x09,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x5F,0x74,0x79,0x70,0x65,0x00,0x00,0x00,0x42,0xFD,0xFF,0xFF,
+ 0x06,0x00,0x10,0x00,0x58,0x00,0x00,0x00,0x40,0x00,0x00,0x00,0x18,0x00,0x00,0x00,0x10,0x00,0x00,0x00,
+ 0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x0C,0xF6,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
+ 0x36,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x88,0xF5,0xFF,0xFF,0x00,0x00,0x00,0x04,
+ 0x03,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0x63,0x6F,0x6C,0x6F,
0x72,0x00,0x00,0x00,0x1C,0x00,0x1C,0x00,0x0C,0x00,0x10,0x00,0x08,0x00,0x0A,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x14,0x00,0x18,0x00,0x07,0x00,0x1C,0x00,0x00,0x00,0x00,0x00,0x00,0x01,
- 0x05,0x00,0x0E,0x00,0x48,0x00,0x00,0x00,0x3C,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
- 0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x6C,0xF8,0xFF,0xFF,0x10,0x00,0x00,0x00,
+ 0x05,0x00,0x0E,0x00,0x54,0x00,0x00,0x00,0x44,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x8C,0xF6,0xFF,0xFF,0x10,0x00,0x00,0x00,
0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x35,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,
- 0x08,0x00,0x08,0x00,0x06,0x00,0x07,0x00,0x08,0x00,0x00,0x00,0x00,0x00,0x0E,0x04,0x09,0x00,0x00,0x00,
- 0x69,0x6E,0x76,0x65,0x6E,0x74,0x6F,0x72,0x79,0x00,0x1A,0x00,0x1C,0x00,0x0C,0x00,0x10,0x00,0x08,0x00,
- 0x0A,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x00,0x14,0x00,0x18,0x00,0x1A,0x00,0x00,0x00,
- 0x00,0x00,0x00,0x01,0x04,0x00,0x0C,0x00,0x90,0x00,0x00,0x00,0x84,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x4C,0x00,0x00,0x00,0x2C,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0xF0,0xF8,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
- 0x31,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x70,0x72,0x69,0x6F,0x72,0x69,0x74,0x79,0x00,0x00,0x00,0x00,
- 0x14,0xF9,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x34,0x00,0x00,0x00,
- 0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x30,0xF9,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
- 0x01,0x00,0x00,0x00,0x30,0x00,0x00,0x00,0x0A,0x00,0x00,0x00,0x64,0x65,0x70,0x72,0x65,0x63,0x61,0x74,
- 0x65,0x64,0x00,0x00,0xEE,0xF5,0xFF,0xFF,0x00,0x00,0x00,0x02,0x08,0x00,0x00,0x00,0x66,0x72,0x69,0x65,
+ 0x10,0x00,0x0C,0x00,0x06,0x00,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x08,0x00,0x10,0x00,0x00,0x00,
+ 0x00,0x00,0x0E,0x04,0x01,0x00,0x00,0x00,0x09,0x00,0x00,0x00,0x69,0x6E,0x76,0x65,0x6E,0x74,0x6F,0x72,
+ 0x79,0x00,0x1A,0x00,0x1C,0x00,0x0C,0x00,0x10,0x00,0x08,0x00,0x0A,0x00,0x00,0x00,0x00,0x00,0x07,0x00,
+ 0x00,0x00,0x00,0x00,0x14,0x00,0x18,0x00,0x1A,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x04,0x00,0x0C,0x00,
+ 0x98,0x00,0x00,0x00,0x84,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+ 0x03,0x00,0x00,0x00,0x4C,0x00,0x00,0x00,0x2C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x1C,0xF7,0xFF,0xFF,
+ 0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x31,0x00,0x00,0x00,0x08,0x00,0x00,0x00,
+ 0x70,0x72,0x69,0x6F,0x72,0x69,0x74,0x79,0x00,0x00,0x00,0x00,0x40,0xF7,0xFF,0xFF,0x10,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x34,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,
+ 0x5C,0xF7,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x30,0x00,0x00,0x00,
+ 0x0A,0x00,0x00,0x00,0x64,0x65,0x70,0x72,0x65,0x63,0x61,0x74,0x65,0x64,0x00,0x00,0x00,0xF6,0xFF,0xFF,
+ 0x00,0x00,0x00,0x02,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x66,0x72,0x69,0x65,
0x6E,0x64,0x6C,0x79,0x00,0x00,0x1A,0x00,0x1C,0x00,0x0C,0x00,0x10,0x00,0x08,0x00,0x0A,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x06,0x00,0x07,0x00,0x14,0x00,0x18,0x00,0x1A,0x00,0x00,0x00,0x00,0x00,0x01,0x01,
- 0x03,0x00,0x0A,0x00,0x88,0x00,0x00,0x00,0x7C,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
- 0x00,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x4C,0x00,0x00,0x00,0x2C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
- 0xB4,0xF9,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x30,0x00,0x00,0x00,
- 0x08,0x00,0x00,0x00,0x72,0x65,0x71,0x75,0x69,0x72,0x65,0x64,0x00,0x00,0x00,0x00,0xD8,0xF9,0xFF,0xFF,
+ 0x03,0x00,0x0A,0x00,0x64,0x00,0x00,0x00,0x54,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x00,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x24,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xE4,0xF7,0xFF,0xFF,
0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x30,0x00,0x00,0x00,0x03,0x00,0x00,0x00,
- 0x6B,0x65,0x79,0x00,0xF4,0xF9,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
- 0x33,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0xAA,0xF6,0xFF,0xFF,0x00,0x00,0x00,0x0D,
- 0x04,0x00,0x00,0x00,0x6E,0x61,0x6D,0x65,0x00,0x00,0x1A,0x00,0x24,0x00,0x08,0x00,0x0C,0x00,0x04,0x00,
- 0x06,0x00,0x18,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x14,0x00,0x1A,0x00,0x00,0x00,
- 0x02,0x00,0x08,0x00,0x4C,0x00,0x00,0x00,0x40,0x00,0x00,0x00,0x18,0x00,0x00,0x00,0x10,0x00,0x00,0x00,
+ 0x6B,0x65,0x79,0x00,0x00,0xF8,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
+ 0x33,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0xE4,0xF3,0xFF,0xFF,0x00,0x00,0x00,0x0D,
+ 0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x6E,0x61,0x6D,0x65,0x00,0x00,0x00,0x00,0x9A,0xFF,0xFF,0xFF,
+ 0x02,0x00,0x08,0x00,0x54,0x00,0x00,0x00,0x40,0x00,0x00,0x00,0x18,0x00,0x00,0x00,0x10,0x00,0x00,0x00,
0x64,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x6C,0xFA,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
- 0x32,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x22,0xF7,0xFF,0xFF,0x00,0x00,0x00,0x05,
- 0x02,0x00,0x00,0x00,0x68,0x70,0x00,0x00,0x00,0x00,0x1A,0x00,0x20,0x00,0x08,0x00,0x0C,0x00,0x04,0x00,
- 0x06,0x00,0x18,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x14,0x00,0x1A,0x00,0x00,0x00,
- 0x01,0x00,0x06,0x00,0x48,0x00,0x00,0x00,0x3C,0x00,0x00,0x00,0x14,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,
- 0x96,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
- 0xE0,0xFA,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x31,0x00,0x00,0x00,
- 0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x96,0xF7,0xFF,0xFF,0x00,0x00,0x00,0x05,0x04,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x64,0xF8,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
+ 0x32,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x00,0xF7,0xFF,0xFF,0x00,0x00,0x00,0x05,
+ 0x02,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x68,0x70,0x00,0x00,0x00,0x00,0x1A,0x00,
+ 0x24,0x00,0x08,0x00,0x0C,0x00,0x04,0x00,0x06,0x00,0x18,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+ 0x10,0x00,0x14,0x00,0x1A,0x00,0x00,0x00,0x01,0x00,0x06,0x00,0x54,0x00,0x00,0x00,0x40,0x00,0x00,0x00,
+ 0x18,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x96,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+ 0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xE4,0xF8,0xFF,0xFF,0x10,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x31,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,
+ 0x80,0xF7,0xFF,0xFF,0x00,0x00,0x00,0x05,0x02,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
0x6D,0x61,0x6E,0x61,0x00,0x00,0x00,0x00,0x1C,0x00,0x18,0x00,0x08,0x00,0x0C,0x00,0x00,0x00,0x06,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x14,0x00,0x05,0x00,0x1C,0x00,0x00,0x00,
- 0x00,0x01,0x04,0x00,0x44,0x00,0x00,0x00,0x34,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
- 0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x50,0xFB,0xFF,0xFF,0x10,0x00,0x00,0x00,
+ 0x00,0x01,0x04,0x00,0x48,0x00,0x00,0x00,0x34,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x5C,0xF9,0xFF,0xFF,0x10,0x00,0x00,0x00,
0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x30,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,
- 0xAE,0xF8,0xFF,0xFF,0x00,0x00,0x00,0x0F,0x07,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x70,0x6F,0x73,0x00,
- 0x4E,0xF9,0xFF,0xFF,0x1C,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
- 0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x3C,0x00,0x00,0x00,0x19,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,
- 0x6D,0x65,0x2E,0x45,0x78,0x61,0x6D,0x70,0x6C,0x65,0x2E,0x52,0x65,0x66,0x65,0x72,0x72,0x61,0x62,0x6C,
- 0x65,0x00,0x1A,0x00,0x18,0x00,0x08,0x00,0x0C,0x00,0x00,0x00,0x06,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
- 0x00,0x00,0x05,0x00,0x10,0x00,0x14,0x00,0x1A,0x00,0x00,0x00,0x00,0x01,0x04,0x00,0x6C,0x00,0x00,0x00,
- 0x60,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x00,0x00,0x00,
- 0x24,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0xFC,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
- 0x01,0x00,0x00,0x00,0x30,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x6B,0x65,0x79,0x00,0x1C,0xFC,0xFF,0xFF,
- 0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x66,0x6E,0x76,0x31,0x61,0x5F,0x36,0x34,
- 0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x68,0x61,0x73,0x68,0x00,0x00,0x00,0x00,0xDE,0xF8,0xFF,0xFF,
- 0x00,0x00,0x00,0x0A,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x22,0xFA,0xFF,0xFF,0x24,0x00,0x00,0x00,
- 0x10,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x03,0x00,0x00,0x00,
- 0x24,0x00,0x00,0x00,0x74,0x00,0x00,0x00,0x48,0x00,0x00,0x00,0x13,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,
- 0x6D,0x65,0x2E,0x45,0x78,0x61,0x6D,0x70,0x6C,0x65,0x2E,0x53,0x74,0x61,0x74,0x00,0x92,0xFB,0xFF,0xFF,
- 0x02,0x00,0x08,0x00,0x18,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
- 0x46,0xF9,0xFF,0xFF,0x00,0x00,0x00,0x06,0x05,0x00,0x00,0x00,0x63,0x6F,0x75,0x6E,0x74,0x00,0x00,0x00,
- 0xBE,0xFB,0xFF,0xFF,0x01,0x00,0x06,0x00,0x18,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
- 0x00,0x00,0x00,0x00,0x72,0xF9,0xFF,0xFF,0x00,0x00,0x00,0x09,0x03,0x00,0x00,0x00,0x76,0x61,0x6C,0x00,
- 0x60,0xFA,0xFF,0xFF,0x00,0x01,0x04,0x00,0x18,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
- 0x00,0x00,0x00,0x00,0x9A,0xF9,0xFF,0xFF,0x00,0x00,0x00,0x0D,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,
- 0x36,0xFA,0xFF,0xFF,0x00,0x00,0x00,0x01,0x24,0x00,0x00,0x00,0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
- 0x08,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x24,0x00,0x00,0x00,
- 0x68,0x00,0x00,0x00,0x16,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,0x6D,0x65,0x2E,0x45,0x78,0x61,0x6D,0x70,
- 0x6C,0x65,0x2E,0x41,0x62,0x69,0x6C,0x69,0x74,0x79,0x00,0x00,0x56,0xFC,0xFF,0xFF,0x01,0x00,0x04,0x00,
- 0x18,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x0A,0xFA,0xFF,0xFF,
- 0x00,0x00,0x00,0x08,0x08,0x00,0x00,0x00,0x64,0x69,0x73,0x74,0x61,0x6E,0x63,0x65,0x00,0x00,0x1A,0x00,
- 0x18,0x00,0x08,0x00,0x0C,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x00,
- 0x10,0x00,0x14,0x00,0x1A,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x40,0x00,0x00,0x00,0x34,0x00,0x00,0x00,
- 0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
- 0xC4,0xFD,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x30,0x00,0x00,0x00,
- 0x03,0x00,0x00,0x00,0x6B,0x65,0x79,0x00,0x7A,0xFA,0xFF,0xFF,0x00,0x00,0x00,0x08,0x02,0x00,0x00,0x00,
- 0x69,0x64,0x00,0x00,0x00,0x00,0x12,0x00,0x20,0x00,0x08,0x00,0x0C,0x00,0x07,0x00,0x10,0x00,0x14,0x00,
- 0x18,0x00,0x1C,0x00,0x12,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x64,0x00,0x00,0x00,0x44,0x00,0x00,0x00,
- 0x08,0x00,0x00,0x00,0x20,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
- 0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x30,0xFE,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
- 0x01,0x00,0x00,0x00,0x38,0x00,0x00,0x00,0x0B,0x00,0x00,0x00,0x66,0x6F,0x72,0x63,0x65,0x5F,0x61,0x6C,
- 0x69,0x67,0x6E,0x00,0x06,0x00,0x00,0x00,0xB0,0x00,0x00,0x00,0x7C,0x00,0x00,0x00,0x44,0x00,0x00,0x00,
- 0x20,0x01,0x00,0x00,0xF4,0x00,0x00,0x00,0xC8,0x00,0x00,0x00,0x13,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,
- 0x6D,0x65,0x2E,0x45,0x78,0x61,0x6D,0x70,0x6C,0x65,0x2E,0x56,0x65,0x63,0x33,0x00,0x1C,0x00,0x18,0x00,
- 0x0C,0x00,0x10,0x00,0x08,0x00,0x0A,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
- 0x14,0x00,0x07,0x00,0x1C,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x05,0x00,0x1A,0x00,0x1C,0x00,0x00,0x00,
- 0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0xFC,0xFF,0xFF,0x00,0x00,0x00,0x0F,
- 0x04,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x33,0x00,0x00,0x00,0xD6,0xFD,0xFF,0xFF,
- 0x04,0x00,0x18,0x00,0x1C,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
- 0x32,0xFC,0xFF,0xFF,0x00,0x00,0x00,0x04,0x03,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0x74,0x65,0x73,0x74,
- 0x32,0x00,0x00,0x00,0x06,0xFE,0xFF,0xFF,0x03,0x00,0x10,0x00,0x18,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xBA,0xFB,0xFF,0xFF,0x00,0x00,0x00,0x0C,0x05,0x00,0x00,0x00,
- 0x74,0x65,0x73,0x74,0x31,0x00,0x00,0x00,0x32,0xFE,0xFF,0xFF,0x02,0x00,0x08,0x00,0x18,0x00,0x00,0x00,
- 0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xE6,0xFB,0xFF,0xFF,0x00,0x00,0x00,0x0B,
- 0x01,0x00,0x00,0x00,0x7A,0x00,0x00,0x00,0x5A,0xFE,0xFF,0xFF,0x01,0x00,0x04,0x00,0x18,0x00,0x00,0x00,
- 0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x0E,0xFC,0xFF,0xFF,0x00,0x00,0x00,0x0B,
- 0x01,0x00,0x00,0x00,0x79,0x00,0x00,0x00,0x4E,0xFC,0xFF,0xFF,0x18,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x32,0xFC,0xFF,0xFF,0x00,0x00,0x00,0x0B,0x01,0x00,0x00,0x00,
- 0x78,0x00,0x12,0x00,0x18,0x00,0x04,0x00,0x08,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x10,0x00,0x14,0x00,
- 0x12,0x00,0x00,0x00,0x7C,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x30,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x24,0xF6,0xFF,0xFF,0x00,0x00,0x00,0x0F,0x08,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x03,0x00,0x00,0x00,
+ 0x70,0x6F,0x73,0x00,0xCC,0xF6,0xFF,0xFF,0x20,0x00,0x00,0x00,0x14,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
+ 0x08,0x00,0x00,0x00,0x58,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x3C,0x00,0x00,0x00,
+ 0x19,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,0x6D,0x65,0x2E,0x45,0x78,0x61,0x6D,0x70,0x6C,0x65,0x2E,0x52,
+ 0x65,0x66,0x65,0x72,0x72,0x61,0x62,0x6C,0x65,0x00,0x1A,0x00,0x18,0x00,0x08,0x00,0x0C,0x00,0x00,0x00,
+ 0x06,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x05,0x00,0x10,0x00,0x14,0x00,0x1A,0x00,0x00,0x00,
+ 0x00,0x01,0x04,0x00,0x74,0x00,0x00,0x00,0x60,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x00,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x24,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x14,0xFA,0xFF,0xFF,
+ 0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x30,0x00,0x00,0x00,0x03,0x00,0x00,0x00,
+ 0x6B,0x65,0x79,0x00,0x30,0xFA,0xFF,0xFF,0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x08,0x00,0x00,0x00,
+ 0x66,0x6E,0x76,0x31,0x61,0x5F,0x36,0x34,0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x68,0x61,0x73,0x68,
+ 0x00,0x00,0x00,0x00,0xD8,0xF8,0xFF,0xFF,0x00,0x00,0x00,0x0A,0x08,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
+ 0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0xAC,0xF7,0xFF,0xFF,0x28,0x00,0x00,0x00,0x14,0x00,0x00,0x00,
+ 0x01,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x78,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x03,0x00,0x00,0x00,
+ 0x40,0x00,0x00,0x00,0xCC,0x00,0x00,0x00,0x98,0x00,0x00,0x00,0x13,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,
+ 0x6D,0x65,0x2E,0x45,0x78,0x61,0x6D,0x70,0x6C,0x65,0x2E,0x53,0x74,0x61,0x74,0x00,0x00,0x00,0x1A,0x00,
+ 0x1C,0x00,0x0C,0x00,0x10,0x00,0x08,0x00,0x0A,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x00,
+ 0x14,0x00,0x18,0x00,0x1A,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x02,0x00,0x08,0x00,0x48,0x00,0x00,0x00,
+ 0x34,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0xF8,0xFA,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
+ 0x30,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x6B,0x65,0x79,0x00,0x94,0xF9,0xFF,0xFF,0x00,0x00,0x00,0x06,
+ 0x02,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0x63,0x6F,0x75,0x6E,0x74,0x00,0x00,0x00,
+ 0xFE,0xFB,0xFF,0xFF,0x01,0x00,0x06,0x00,0x20,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x00,0x00,0x00,0x00,0xC8,0xF9,0xFF,0xFF,0x00,0x00,0x00,0x09,0x08,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
+ 0x03,0x00,0x00,0x00,0x76,0x61,0x6C,0x00,0x40,0xF8,0xFF,0xFF,0x00,0x01,0x04,0x00,0x1C,0x00,0x00,0x00,
+ 0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0xF7,0xFF,0xFF,0x00,0x00,0x00,0x0D,
+ 0x01,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x10,0xF8,0xFF,0xFF,0x00,0x00,0x00,0x01,
+ 0x2C,0x00,0x00,0x00,0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x14,0x00,0x00,0x00,0x08,0x00,0x00,0x00,
+ 0x54,0x06,0x00,0x00,0x00,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0xD0,0x00,0x00,0x00,0x7C,0x00,0x00,0x00,
+ 0x28,0x00,0x00,0x00,0x1E,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,0x6D,0x65,0x2E,0x45,0x78,0x61,0x6D,0x70,
+ 0x6C,0x65,0x2E,0x53,0x74,0x72,0x75,0x63,0x74,0x4F,0x66,0x53,0x74,0x72,0x75,0x63,0x74,0x73,0x00,0x00,
+ 0xCC,0xFF,0xFF,0xFF,0x00,0x00,0x00,0x01,0x02,0x00,0x0C,0x00,0x20,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xAC,0xF8,0xFF,0xFF,0x00,0x00,0x00,0x0F,0x00,0x00,0x00,0x00,
+ 0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x63,0x00,0x00,0x00,0x1C,0x00,0x18,0x00,0x0C,0x00,0x10,0x00,
+ 0x08,0x00,0x0A,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x14,0x00,0x07,0x00,
+ 0x1C,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x01,0x00,0x08,0x00,0x20,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xFC,0xF8,0xFF,0xFF,0x00,0x00,0x00,0x0F,0x05,0x00,0x00,0x00,
+ 0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x62,0x00,0x00,0x00,0x1C,0x00,0x14,0x00,0x08,0x00,0x0C,0x00,
+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x07,0x00,
+ 0x1C,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x20,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x00,0x00,0x00,0x00,0x48,0xF9,0xFF,0xFF,0x00,0x00,0x00,0x0F,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
+ 0x01,0x00,0x00,0x00,0x61,0x00,0x00,0x00,0x38,0xF9,0xFF,0xFF,0x00,0x00,0x00,0x01,0x28,0x00,0x00,0x00,
+ 0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x2C,0x05,0x00,0x00,
+ 0x00,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x24,0x00,0x00,0x00,0x6C,0x00,0x00,0x00,0x16,0x00,0x00,0x00,
+ 0x4D,0x79,0x47,0x61,0x6D,0x65,0x2E,0x45,0x78,0x61,0x6D,0x70,0x6C,0x65,0x2E,0x41,0x62,0x69,0x6C,0x69,
+ 0x74,0x79,0x00,0x00,0xCE,0xFD,0xFF,0xFF,0x01,0x00,0x04,0x00,0x1C,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xE0,0xF8,0xFF,0xFF,0x00,0x00,0x00,0x08,0x01,0x00,0x00,0x00,
+ 0x08,0x00,0x00,0x00,0x64,0x69,0x73,0x74,0x61,0x6E,0x63,0x65,0x00,0x00,0x1A,0x00,0x18,0x00,0x08,0x00,
+ 0x0C,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x10,0x00,0x14,0x00,
+ 0x1A,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x44,0x00,0x00,0x00,0x34,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x70,0xFD,0xFF,0xFF,
+ 0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x30,0x00,0x00,0x00,0x03,0x00,0x00,0x00,
+ 0x6B,0x65,0x79,0x00,0x54,0xF9,0xFF,0xFF,0x00,0x00,0x00,0x08,0x01,0x00,0x00,0x00,0x02,0x00,0x00,0x00,
+ 0x69,0x64,0x00,0x00,0x14,0x00,0x24,0x00,0x08,0x00,0x0C,0x00,0x07,0x00,0x10,0x00,0x14,0x00,0x18,0x00,
+ 0x1C,0x00,0x20,0x00,0x14,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x68,0x00,0x00,0x00,0x48,0x00,0x00,0x00,
+ 0x08,0x00,0x00,0x00,0x20,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x28,0x04,0x00,0x00,
+ 0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xE4,0xFD,0xFF,0xFF,0x10,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x38,0x00,0x00,0x00,0x0B,0x00,0x00,0x00,0x66,0x6F,0x72,0x63,
+ 0x65,0x5F,0x61,0x6C,0x69,0x67,0x6E,0x00,0x06,0x00,0x00,0x00,0xC4,0x00,0x00,0x00,0x84,0x00,0x00,0x00,
+ 0x48,0x00,0x00,0x00,0x60,0x01,0x00,0x00,0x30,0x01,0x00,0x00,0xE4,0x00,0x00,0x00,0x13,0x00,0x00,0x00,
+ 0x4D,0x79,0x47,0x61,0x6D,0x65,0x2E,0x45,0x78,0x61,0x6D,0x70,0x6C,0x65,0x2E,0x56,0x65,0x63,0x33,0x00,
+ 0x00,0x00,0x1E,0x00,0x18,0x00,0x0C,0x00,0x10,0x00,0x06,0x00,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+ 0x00,0x00,0x00,0x00,0x00,0x00,0x14,0x00,0x05,0x00,0x0A,0x00,0x1E,0x00,0x00,0x00,0x00,0x01,0x05,0x00,
+ 0x1A,0x00,0x02,0x00,0x20,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+ 0x24,0xFB,0xFF,0xFF,0x00,0x00,0x00,0x0F,0x05,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x05,0x00,0x00,0x00,
+ 0x74,0x65,0x73,0x74,0x33,0x00,0x00,0x00,0x7A,0xFD,0xFF,0xFF,0x00,0x00,0x04,0x00,0x18,0x00,0x01,0x00,
+ 0x24,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0xFE,0xFF,0xFF,
+ 0x00,0x00,0x00,0x04,0x03,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x05,0x00,0x00,0x00,
+ 0x74,0x65,0x73,0x74,0x32,0x00,0x00,0x00,0x9E,0xFF,0xFF,0xFF,0x03,0x00,0x10,0x00,0x20,0x00,0x00,0x00,
+ 0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x68,0xFD,0xFF,0xFF,0x00,0x00,0x00,0x0C,
+ 0x08,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x31,0x00,0x00,0x00,
+ 0xEA,0xFD,0xFF,0xFF,0x00,0x00,0x02,0x00,0x08,0x00,0x04,0x00,0x1C,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xE8,0xFA,0xFF,0xFF,0x00,0x00,0x00,0x0B,0x01,0x00,0x00,0x00,
+ 0x01,0x00,0x00,0x00,0x7A,0x00,0x1A,0x00,0x14,0x00,0x08,0x00,0x0C,0x00,0x04,0x00,0x06,0x00,0x00,0x00,
+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x1A,0x00,0x00,0x00,0x01,0x00,0x04,0x00,
+ 0x1C,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x2C,0xFB,0xFF,0xFF,
+ 0x00,0x00,0x00,0x0B,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x79,0x00,0x00,0x00,0x6E,0xFB,0xFF,0xFF,
+ 0x1C,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x54,0xFB,0xFF,0xFF,
+ 0x00,0x00,0x00,0x0B,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x78,0x00,0x00,0x00,0x14,0x00,0x1C,0x00,
+ 0x04,0x00,0x08,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x10,0x00,0x14,0x00,0x18,0x00,0x14,0x00,0x00,0x00,
+ 0x80,0x00,0x00,0x00,0x74,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x08,0x00,0x00,0x00,
+ 0x30,0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x30,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
0xE0,0xFF,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x30,0x00,0x00,0x00,
0x07,0x00,0x00,0x00,0x70,0x72,0x69,0x76,0x61,0x74,0x65,0x00,0x08,0x00,0x0C,0x00,0x04,0x00,0x08,0x00,
0x08,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x30,0x00,0x00,0x00,
0x0E,0x00,0x00,0x00,0x63,0x73,0x68,0x61,0x72,0x70,0x5F,0x70,0x61,0x72,0x74,0x69,0x61,0x6C,0x00,0x00,
0x01,0x00,0x00,0x00,0x4C,0x00,0x00,0x00,0x26,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,0x6D,0x65,0x2E,0x45,
0x78,0x61,0x6D,0x70,0x6C,0x65,0x2E,0x54,0x65,0x73,0x74,0x53,0x69,0x6D,0x70,0x6C,0x65,0x54,0x61,0x62,
- 0x6C,0x65,0x57,0x69,0x74,0x68,0x45,0x6E,0x75,0x6D,0x00,0x00,0x00,0x00,0x1A,0x00,0x20,0x00,0x08,0x00,
+ 0x6C,0x65,0x57,0x69,0x74,0x68,0x45,0x6E,0x75,0x6D,0x00,0x00,0x00,0x00,0x1A,0x00,0x1C,0x00,0x08,0x00,
0x0C,0x00,0x00,0x00,0x06,0x00,0x14,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x00,
- 0x1A,0x00,0x00,0x00,0x00,0x00,0x04,0x00,0x28,0x00,0x00,0x00,0x18,0x00,0x00,0x00,0x10,0x00,0x00,0x00,
- 0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xE6,0xFD,0xFF,0xFF,
- 0x00,0x00,0x00,0x04,0x03,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0x63,0x6F,0x6C,0x6F,0x72,0x00,0x00,0x00,
- 0xE2,0xFD,0xFF,0xFF,0x00,0x00,0x00,0x01,0x24,0x00,0x00,0x00,0x14,0x00,0x00,0x00,0x02,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x64,0x00,0x00,0x00,
- 0x38,0x00,0x00,0x00,0x13,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,0x6D,0x65,0x2E,0x45,0x78,0x61,0x6D,0x70,
- 0x6C,0x65,0x2E,0x54,0x65,0x73,0x74,0x00,0x00,0x00,0x1A,0x00,0x14,0x00,0x08,0x00,0x0C,0x00,0x04,0x00,
- 0x06,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x1A,0x00,0x00,0x00,
- 0x01,0x00,0x02,0x00,0x18,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
- 0xCE,0xFD,0xFF,0xFF,0x00,0x00,0x00,0x03,0x01,0x00,0x00,0x00,0x62,0x00,0x00,0x00,0x0E,0xFE,0xFF,0xFF,
- 0x18,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xF2,0xFD,0xFF,0xFF,
- 0x00,0x00,0x00,0x05,0x01,0x00,0x00,0x00,0x61,0x00,0x00,0x00,0x36,0xFF,0xFF,0xFF,0x18,0x00,0x00,0x00,
- 0x10,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
- 0x17,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,0x6D,0x65,0x2E,0x45,0x78,0x61,0x6D,0x70,0x6C,0x65,0x32,0x2E,
- 0x4D,0x6F,0x6E,0x73,0x74,0x65,0x72,0x00,0x6E,0xFF,0xFF,0xFF,0x18,0x00,0x00,0x00,0x10,0x00,0x00,0x00,
- 0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x18,0x00,0x00,0x00,
- 0x4D,0x79,0x47,0x61,0x6D,0x65,0x2E,0x49,0x6E,0x50,0x61,0x72,0x65,0x6E,0x74,0x4E,0x61,0x6D,0x65,0x73,
- 0x70,0x61,0x63,0x65,0x00,0x00,0x00,0x00,0xAA,0xFF,0xFF,0xFF,0x1C,0x00,0x00,0x00,0x10,0x00,0x00,0x00,
- 0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x10,0x00,0x00,0x00,
- 0x06,0x00,0x00,0x00,0x54,0x61,0x62,0x6C,0x65,0x41,0x00,0x00,0x80,0xFF,0xFF,0xFF,0x00,0x01,0x04,0x00,
- 0x1C,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x62,0xFF,0xFF,0xFF,
- 0x00,0x00,0x00,0x0F,0x0A,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x62,0x00,0x12,0x00,0x14,0x00,0x04,0x00,
- 0x08,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x12,0x00,0x00,0x00,0x1C,0x00,0x00,0x00,
- 0x10,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
- 0x44,0x00,0x00,0x00,0x1C,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,0x6D,0x65,0x2E,0x4F,0x74,0x68,0x65,0x72,
- 0x4E,0x61,0x6D,0x65,0x53,0x70,0x61,0x63,0x65,0x2E,0x54,0x61,0x62,0x6C,0x65,0x42,0x00,0x00,0x00,0x00,
- 0x1C,0x00,0x14,0x00,0x08,0x00,0x0C,0x00,0x00,0x00,0x06,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
- 0x00,0x00,0x00,0x00,0x10,0x00,0x05,0x00,0x1C,0x00,0x00,0x00,0x00,0x01,0x04,0x00,0x28,0x00,0x00,0x00,
- 0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x0A,0x00,0x0C,0x00,0x07,0x00,
- 0x00,0x00,0x08,0x00,0x0A,0x00,0x00,0x00,0x00,0x00,0x00,0x0F,0x0C,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
- 0x61,0x00,0x12,0x00,0x1C,0x00,0x08,0x00,0x0C,0x00,0x07,0x00,0x10,0x00,0x14,0x00,0x00,0x00,0x18,0x00,
- 0x12,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x20,0x00,0x00,0x00,0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
- 0x04,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x40,0x00,0x00,0x00,
- 0x1C,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,0x6D,0x65,0x2E,0x4F,0x74,0x68,0x65,0x72,0x4E,0x61,0x6D,0x65,
- 0x53,0x70,0x61,0x63,0x65,0x2E,0x55,0x6E,0x75,0x73,0x65,0x64,0x00,0x00,0x1A,0x00,0x10,0x00,0x04,0x00,
- 0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x0C,0x00,
- 0x1A,0x00,0x00,0x00,0x20,0x00,0x00,0x00,0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
- 0x00,0x00,0x06,0x00,0x08,0x00,0x07,0x00,0x06,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x01,0x00,0x00,0x00,
- 0x61,0x00,0x00,0x00
+ 0x1A,0x00,0x00,0x00,0x00,0x00,0x04,0x00,0x3C,0x00,0x00,0x00,0x24,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,
+ 0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x14,0x00,0x07,0x00,0x00,0x00,
+ 0x08,0x00,0x00,0x00,0x0C,0x00,0x10,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x04,0x03,0x00,0x00,0x00,
+ 0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0x63,0x6F,0x6C,0x6F,0x72,0x00,0x00,0x00,
+ 0x54,0xFD,0xFF,0xFF,0x00,0x00,0x00,0x01,0x28,0x00,0x00,0x00,0x18,0x00,0x00,0x00,0x02,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x10,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x00,0x00,0x00,
+ 0x74,0x00,0x00,0x00,0x3C,0x00,0x00,0x00,0x13,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,0x6D,0x65,0x2E,0x45,
+ 0x78,0x61,0x6D,0x70,0x6C,0x65,0x2E,0x54,0x65,0x73,0x74,0x00,0x00,0x00,0x1E,0x00,0x18,0x00,0x0C,0x00,
+ 0x10,0x00,0x06,0x00,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x14,0x00,
+ 0x00,0x00,0x0A,0x00,0x1E,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x02,0x00,0x01,0x00,0x20,0x00,0x00,0x00,
+ 0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xD4,0xFF,0xFF,0xFF,0x00,0x00,0x00,0x03,
+ 0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x62,0x00,0x00,0x00,0x62,0xFD,0xFF,0xFF,
+ 0x30,0x00,0x00,0x00,0x1C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x10,0x00,
+ 0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x08,0x00,0x0C,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x05,
+ 0x02,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x61,0x00,0x00,0x00,0xE4,0xFE,0xFF,0xFF,
+ 0x1C,0x00,0x00,0x00,0x14,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x40,0x00,0x00,0x00,
+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x17,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,0x6D,0x65,0x2E,0x45,
+ 0x78,0x61,0x6D,0x70,0x6C,0x65,0x32,0x2E,0x4D,0x6F,0x6E,0x73,0x74,0x65,0x72,0x00,0x20,0xFF,0xFF,0xFF,
+ 0x34,0x00,0x00,0x00,0x2C,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x20,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x12,0x00,0x00,0x00,0x2F,0x2F,0x6D,0x6F,0x6E,0x73,0x74,0x65,0x72,0x5F,0x74,0x65,0x73,0x74,0x2E,0x66,
+ 0x62,0x73,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x18,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,
+ 0x6D,0x65,0x2E,0x49,0x6E,0x50,0x61,0x72,0x65,0x6E,0x74,0x4E,0x61,0x6D,0x65,0x73,0x70,0x61,0x63,0x65,
+ 0x00,0x00,0x00,0x00,0x78,0xFF,0xFF,0xFF,0x48,0x00,0x00,0x00,0x3C,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
+ 0x30,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x20,0x00,0x00,0x00,0x2F,0x2F,0x69,0x6E,0x63,0x6C,0x75,0x64,
+ 0x65,0x5F,0x74,0x65,0x73,0x74,0x2F,0x69,0x6E,0x63,0x6C,0x75,0x64,0x65,0x5F,0x74,0x65,0x73,0x74,0x31,
+ 0x2E,0x66,0x62,0x73,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x10,0x00,0x00,0x00,
+ 0x06,0x00,0x00,0x00,0x54,0x61,0x62,0x6C,0x65,0x41,0x00,0x00,0x74,0xFF,0xFF,0xFF,0x00,0x01,0x04,0x00,
+ 0x20,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x58,0xFF,0xFF,0xFF,
+ 0x00,0x00,0x00,0x0F,0x0B,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x62,0x00,0x00,0x00,
+ 0x14,0x00,0x18,0x00,0x04,0x00,0x08,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x14,0x00,
+ 0x14,0x00,0x00,0x00,0x20,0x00,0x00,0x00,0x14,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x08,0x00,0x00,0x00,
+ 0xC4,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x44,0x00,0x00,0x00,0x1C,0x00,0x00,0x00,
+ 0x4D,0x79,0x47,0x61,0x6D,0x65,0x2E,0x4F,0x74,0x68,0x65,0x72,0x4E,0x61,0x6D,0x65,0x53,0x70,0x61,0x63,
+ 0x65,0x2E,0x54,0x61,0x62,0x6C,0x65,0x42,0x00,0x00,0x00,0x00,0x1C,0x00,0x14,0x00,0x08,0x00,0x0C,0x00,
+ 0x00,0x00,0x06,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x05,0x00,
+ 0x1C,0x00,0x00,0x00,0x00,0x01,0x04,0x00,0x30,0x00,0x00,0x00,0x1C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+ 0x00,0x00,0x00,0x00,0x10,0x00,0x10,0x00,0x07,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x00,0x00,0x0C,0x00,
+ 0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x0F,0x0D,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
+ 0x61,0x00,0x00,0x00,0x14,0x00,0x20,0x00,0x08,0x00,0x0C,0x00,0x07,0x00,0x10,0x00,0x14,0x00,0x00,0x00,
+ 0x18,0x00,0x1C,0x00,0x14,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x50,0x00,0x00,0x00,0x44,0x00,0x00,0x00,
+ 0x04,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x34,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x24,0x00,0x00,0x00,
+ 0x2F,0x2F,0x69,0x6E,0x63,0x6C,0x75,0x64,0x65,0x5F,0x74,0x65,0x73,0x74,0x2F,0x73,0x75,0x62,0x2F,0x69,
+ 0x6E,0x63,0x6C,0x75,0x64,0x65,0x5F,0x74,0x65,0x73,0x74,0x32,0x2E,0x66,0x62,0x73,0x00,0x00,0x00,0x00,
+ 0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x40,0x00,0x00,0x00,0x1C,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,
+ 0x6D,0x65,0x2E,0x4F,0x74,0x68,0x65,0x72,0x4E,0x61,0x6D,0x65,0x53,0x70,0x61,0x63,0x65,0x2E,0x55,0x6E,
+ 0x75,0x73,0x65,0x64,0x00,0x00,0x1A,0x00,0x10,0x00,0x04,0x00,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x0C,0x00,0x1A,0x00,0x00,0x00,0x2C,0x00,0x00,0x00,
+ 0x1C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x0C,0x00,0x07,0x00,0x00,0x00,
+ 0x00,0x00,0x00,0x00,0x00,0x00,0x08,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x01,0x00,0x00,0x00,
+ 0x01,0x00,0x00,0x00,0x61,0x00,0x00,0x00
};
return bfbsData;
}
static size_t size() {
- return 12544;
+ return 14648;
}
const uint8_t *begin() {
return data();
diff --git a/tests/monster_test_generated.grpc.fb.cc b/tests/monster_test_generated.grpc.fb.cc
new file mode 100644
index 0000000..9a56eb8
--- /dev/null
+++ b/tests/monster_test_generated.grpc.fb.cc
@@ -0,0 +1,130 @@
+// Generated by the gRPC C++ plugin.
+// If you make any local change, they will be lost.
+// source: monster_test
+
+#include "monster_test_generated.grpc.fb.h"
+
+#include <grpcpp/impl/codegen/async_stream.h>
+#include <grpcpp/impl/codegen/async_unary_call.h>
+#include <grpcpp/impl/codegen/channel_interface.h>
+#include <grpcpp/impl/codegen/client_unary_call.h>
+#include <grpcpp/impl/codegen/method_handler.h>
+#include <grpcpp/impl/codegen/rpc_service_method.h>
+#include <grpcpp/impl/codegen/service_type.h>
+#include <grpcpp/impl/codegen/sync_stream.h>
+namespace MyGame {
+namespace Example {
+
+static const char* MonsterStorage_method_names[] = {
+ "/MyGame.Example.MonsterStorage/Store",
+ "/MyGame.Example.MonsterStorage/Retrieve",
+ "/MyGame.Example.MonsterStorage/GetMaxHitPoint",
+ "/MyGame.Example.MonsterStorage/GetMinMaxHitPoints",
+};
+
+std::unique_ptr< MonsterStorage::Stub> MonsterStorage::NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel, const ::grpc::StubOptions& /*options*/) {
+ std::unique_ptr< MonsterStorage::Stub> stub(new MonsterStorage::Stub(channel));
+ return stub;
+}
+
+MonsterStorage::Stub::Stub(const std::shared_ptr< ::grpc::ChannelInterface>& channel)
+ : channel_(channel) , rpcmethod_Store_(MonsterStorage_method_names[0], ::grpc::internal::RpcMethod::NORMAL_RPC, channel)
+ , rpcmethod_Retrieve_(MonsterStorage_method_names[1], ::grpc::internal::RpcMethod::SERVER_STREAMING, channel)
+ , rpcmethod_GetMaxHitPoint_(MonsterStorage_method_names[2], ::grpc::internal::RpcMethod::CLIENT_STREAMING, channel)
+ , rpcmethod_GetMinMaxHitPoints_(MonsterStorage_method_names[3], ::grpc::internal::RpcMethod::BIDI_STREAMING, channel)
+ {}
+
+::grpc::Status MonsterStorage::Stub::Store(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Monster>& request, flatbuffers::grpc::Message<Stat>* response) {
+ return ::grpc::internal::BlockingUnaryCall(channel_.get(), rpcmethod_Store_, context, request, response);
+}
+
+::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message<Stat>>* MonsterStorage::Stub::AsyncStoreRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Monster>& request, ::grpc::CompletionQueue* cq) {
+ return ::grpc::internal::ClientAsyncResponseReaderFactory< flatbuffers::grpc::Message<Stat>>::Create(channel_.get(), cq, rpcmethod_Store_, context, request, true);
+}
+
+::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message<Stat>>* MonsterStorage::Stub::PrepareAsyncStoreRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Monster>& request, ::grpc::CompletionQueue* cq) {
+ return ::grpc::internal::ClientAsyncResponseReaderFactory< flatbuffers::grpc::Message<Stat>>::Create(channel_.get(), cq, rpcmethod_Store_, context, request, false);
+}
+
+::grpc::ClientReader< flatbuffers::grpc::Message<Monster>>* MonsterStorage::Stub::RetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Stat>& request) {
+ return ::grpc::internal::ClientReaderFactory< flatbuffers::grpc::Message<Monster>>::Create(channel_.get(), rpcmethod_Retrieve_, context, request);
+}
+
+::grpc::ClientAsyncReader< flatbuffers::grpc::Message<Monster>>* MonsterStorage::Stub::AsyncRetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Stat>& request, ::grpc::CompletionQueue* cq, void* tag) {
+ return ::grpc::internal::ClientAsyncReaderFactory< flatbuffers::grpc::Message<Monster>>::Create(channel_.get(), cq, rpcmethod_Retrieve_, context, request, true, tag);
+}
+
+::grpc::ClientAsyncReader< flatbuffers::grpc::Message<Monster>>* MonsterStorage::Stub::PrepareAsyncRetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Stat>& request, ::grpc::CompletionQueue* cq) {
+ return ::grpc::internal::ClientAsyncReaderFactory< flatbuffers::grpc::Message<Monster>>::Create(channel_.get(), cq, rpcmethod_Retrieve_, context, request, false, nullptr);
+}
+
+::grpc::ClientWriter< flatbuffers::grpc::Message<Monster>>* MonsterStorage::Stub::GetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message<Stat>* response) {
+ return ::grpc::internal::ClientWriterFactory< flatbuffers::grpc::Message<Monster>>::Create(channel_.get(), rpcmethod_GetMaxHitPoint_, context, response);
+}
+
+::grpc::ClientAsyncWriter< flatbuffers::grpc::Message<Monster>>* MonsterStorage::Stub::AsyncGetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message<Stat>* response, ::grpc::CompletionQueue* cq, void* tag) {
+ return ::grpc::internal::ClientAsyncWriterFactory< flatbuffers::grpc::Message<Monster>>::Create(channel_.get(), cq, rpcmethod_GetMaxHitPoint_, context, response, true, tag);
+}
+
+::grpc::ClientAsyncWriter< flatbuffers::grpc::Message<Monster>>* MonsterStorage::Stub::PrepareAsyncGetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message<Stat>* response, ::grpc::CompletionQueue* cq) {
+ return ::grpc::internal::ClientAsyncWriterFactory< flatbuffers::grpc::Message<Monster>>::Create(channel_.get(), cq, rpcmethod_GetMaxHitPoint_, context, response, false, nullptr);
+}
+
+::grpc::ClientReaderWriter< flatbuffers::grpc::Message<Monster>, flatbuffers::grpc::Message<Stat>>* MonsterStorage::Stub::GetMinMaxHitPointsRaw(::grpc::ClientContext* context) {
+ return ::grpc::internal::ClientReaderWriterFactory< flatbuffers::grpc::Message<Monster>, flatbuffers::grpc::Message<Stat>>::Create(channel_.get(), rpcmethod_GetMinMaxHitPoints_, context);
+}
+
+::grpc::ClientAsyncReaderWriter< flatbuffers::grpc::Message<Monster>, flatbuffers::grpc::Message<Stat>>* MonsterStorage::Stub::AsyncGetMinMaxHitPointsRaw(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, void* tag) {
+ return ::grpc::internal::ClientAsyncReaderWriterFactory< flatbuffers::grpc::Message<Monster>, flatbuffers::grpc::Message<Stat>>::Create(channel_.get(), cq, rpcmethod_GetMinMaxHitPoints_, context, true, tag);
+}
+
+::grpc::ClientAsyncReaderWriter< flatbuffers::grpc::Message<Monster>, flatbuffers::grpc::Message<Stat>>* MonsterStorage::Stub::PrepareAsyncGetMinMaxHitPointsRaw(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq) {
+ return ::grpc::internal::ClientAsyncReaderWriterFactory< flatbuffers::grpc::Message<Monster>, flatbuffers::grpc::Message<Stat>>::Create(channel_.get(), cq, rpcmethod_GetMinMaxHitPoints_, context, false, nullptr);
+}
+
+MonsterStorage::Service::Service() {
+ AddMethod(new ::grpc::internal::RpcServiceMethod(
+ MonsterStorage_method_names[0],
+ ::grpc::internal::RpcMethod::NORMAL_RPC,
+ new ::grpc::internal::RpcMethodHandler< MonsterStorage::Service, flatbuffers::grpc::Message<Monster>, flatbuffers::grpc::Message<Stat>>(
+ std::mem_fn(&MonsterStorage::Service::Store), this)));
+ AddMethod(new ::grpc::internal::RpcServiceMethod(
+ MonsterStorage_method_names[1],
+ ::grpc::internal::RpcMethod::SERVER_STREAMING,
+ new ::grpc::internal::ServerStreamingHandler< MonsterStorage::Service, flatbuffers::grpc::Message<Stat>, flatbuffers::grpc::Message<Monster>>(
+ std::mem_fn(&MonsterStorage::Service::Retrieve), this)));
+ AddMethod(new ::grpc::internal::RpcServiceMethod(
+ MonsterStorage_method_names[2],
+ ::grpc::internal::RpcMethod::CLIENT_STREAMING,
+ new ::grpc::internal::ClientStreamingHandler< MonsterStorage::Service, flatbuffers::grpc::Message<Monster>, flatbuffers::grpc::Message<Stat>>(
+ std::mem_fn(&MonsterStorage::Service::GetMaxHitPoint), this)));
+ AddMethod(new ::grpc::internal::RpcServiceMethod(
+ MonsterStorage_method_names[3],
+ ::grpc::internal::RpcMethod::BIDI_STREAMING,
+ new ::grpc::internal::BidiStreamingHandler< MonsterStorage::Service, flatbuffers::grpc::Message<Monster>, flatbuffers::grpc::Message<Stat>>(
+ std::mem_fn(&MonsterStorage::Service::GetMinMaxHitPoints), this)));
+}
+
+MonsterStorage::Service::~Service() {
+}
+
+::grpc::Status MonsterStorage::Service::Store(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message<Monster>* /*request*/, flatbuffers::grpc::Message<Stat>* /*response*/) {
+ return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
+}
+
+::grpc::Status MonsterStorage::Service::Retrieve(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message<Stat>* /*request*/, ::grpc::ServerWriter< flatbuffers::grpc::Message<Monster>>* /*writer*/) {
+ return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
+}
+
+::grpc::Status MonsterStorage::Service::GetMaxHitPoint(::grpc::ServerContext* /*context*/, ::grpc::ServerReader< flatbuffers::grpc::Message<Monster>>* /*reader*/, flatbuffers::grpc::Message<Stat>* /*response*/) {
+ return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
+}
+
+::grpc::Status MonsterStorage::Service::GetMinMaxHitPoints(::grpc::ServerContext* /*context*/, ::grpc::ServerReaderWriter< flatbuffers::grpc::Message<Stat>, flatbuffers::grpc::Message<Monster>>* /*stream*/) {
+ return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
+}
+
+
+} // namespace MyGame
+} // namespace Example
+
diff --git a/tests/monster_test_generated.grpc.fb.h b/tests/monster_test_generated.grpc.fb.h
new file mode 100644
index 0000000..4d726e1
--- /dev/null
+++ b/tests/monster_test_generated.grpc.fb.h
@@ -0,0 +1,350 @@
+// Generated by the gRPC C++ plugin.
+// If you make any local change, they will be lost.
+// source: monster_test
+#ifndef GRPC_monster_5ftest__INCLUDED
+#define GRPC_monster_5ftest__INCLUDED
+
+#include "monster_test_generated.h"
+#include "flatbuffers/grpc.h"
+
+#include <grpcpp/impl/codegen/async_stream.h>
+#include <grpcpp/impl/codegen/async_unary_call.h>
+#include <grpcpp/impl/codegen/method_handler.h>
+#include <grpcpp/impl/codegen/proto_utils.h>
+#include <grpcpp/impl/codegen/rpc_method.h>
+#include <grpcpp/impl/codegen/service_type.h>
+#include <grpcpp/impl/codegen/status.h>
+#include <grpcpp/impl/codegen/stub_options.h>
+#include <grpcpp/impl/codegen/sync_stream.h>
+
+namespace grpc {
+class CompletionQueue;
+class Channel;
+class ServerCompletionQueue;
+class ServerContext;
+} // namespace grpc
+
+namespace MyGame {
+namespace Example {
+
+class MonsterStorage final {
+ public:
+ static constexpr char const* service_full_name() {
+ return "MyGame.Example.MonsterStorage";
+ }
+ class StubInterface {
+ public:
+ virtual ~StubInterface() {}
+ virtual ::grpc::Status Store(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Monster>& request, flatbuffers::grpc::Message<Stat>* response) = 0;
+ std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< flatbuffers::grpc::Message<Stat>>> AsyncStore(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Monster>& request, ::grpc::CompletionQueue* cq) {
+ return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< flatbuffers::grpc::Message<Stat>>>(AsyncStoreRaw(context, request, cq));
+ }
+ std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< flatbuffers::grpc::Message<Stat>>> PrepareAsyncStore(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Monster>& request, ::grpc::CompletionQueue* cq) {
+ return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< flatbuffers::grpc::Message<Stat>>>(PrepareAsyncStoreRaw(context, request, cq));
+ }
+ std::unique_ptr< ::grpc::ClientReaderInterface< flatbuffers::grpc::Message<Monster>>> Retrieve(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Stat>& request) {
+ return std::unique_ptr< ::grpc::ClientReaderInterface< flatbuffers::grpc::Message<Monster>>>(RetrieveRaw(context, request));
+ }
+ std::unique_ptr< ::grpc::ClientAsyncReaderInterface< flatbuffers::grpc::Message<Monster>>> AsyncRetrieve(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Stat>& request, ::grpc::CompletionQueue* cq, void* tag) {
+ return std::unique_ptr< ::grpc::ClientAsyncReaderInterface< flatbuffers::grpc::Message<Monster>>>(AsyncRetrieveRaw(context, request, cq, tag));
+ }
+ std::unique_ptr< ::grpc::ClientAsyncReaderInterface< flatbuffers::grpc::Message<Monster>>> PrepareAsyncRetrieve(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Stat>& request, ::grpc::CompletionQueue* cq) {
+ return std::unique_ptr< ::grpc::ClientAsyncReaderInterface< flatbuffers::grpc::Message<Monster>>>(PrepareAsyncRetrieveRaw(context, request, cq));
+ }
+ std::unique_ptr< ::grpc::ClientWriterInterface< flatbuffers::grpc::Message<Monster>>> GetMaxHitPoint(::grpc::ClientContext* context, flatbuffers::grpc::Message<Stat>* response) {
+ return std::unique_ptr< ::grpc::ClientWriterInterface< flatbuffers::grpc::Message<Monster>>>(GetMaxHitPointRaw(context, response));
+ }
+ std::unique_ptr< ::grpc::ClientAsyncWriterInterface< flatbuffers::grpc::Message<Monster>>> AsyncGetMaxHitPoint(::grpc::ClientContext* context, flatbuffers::grpc::Message<Stat>* response, ::grpc::CompletionQueue* cq, void* tag) {
+ return std::unique_ptr< ::grpc::ClientAsyncWriterInterface< flatbuffers::grpc::Message<Monster>>>(AsyncGetMaxHitPointRaw(context, response, cq, tag));
+ }
+ std::unique_ptr< ::grpc::ClientAsyncWriterInterface< flatbuffers::grpc::Message<Monster>>> PrepareAsyncGetMaxHitPoint(::grpc::ClientContext* context, flatbuffers::grpc::Message<Stat>* response, ::grpc::CompletionQueue* cq) {
+ return std::unique_ptr< ::grpc::ClientAsyncWriterInterface< flatbuffers::grpc::Message<Monster>>>(PrepareAsyncGetMaxHitPointRaw(context, response, cq));
+ }
+ std::unique_ptr< ::grpc::ClientReaderWriterInterface< flatbuffers::grpc::Message<Monster>, flatbuffers::grpc::Message<Stat>>> GetMinMaxHitPoints(::grpc::ClientContext* context) {
+ return std::unique_ptr< ::grpc::ClientReaderWriterInterface< flatbuffers::grpc::Message<Monster>, flatbuffers::grpc::Message<Stat>>>(GetMinMaxHitPointsRaw(context));
+ }
+ std::unique_ptr< ::grpc::ClientAsyncReaderWriterInterface< flatbuffers::grpc::Message<Monster>, flatbuffers::grpc::Message<Stat>>> AsyncGetMinMaxHitPoints(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, void* tag) {
+ return std::unique_ptr< ::grpc::ClientAsyncReaderWriterInterface< flatbuffers::grpc::Message<Monster>, flatbuffers::grpc::Message<Stat>>>(AsyncGetMinMaxHitPointsRaw(context, cq, tag));
+ }
+ std::unique_ptr< ::grpc::ClientAsyncReaderWriterInterface< flatbuffers::grpc::Message<Monster>, flatbuffers::grpc::Message<Stat>>> PrepareAsyncGetMinMaxHitPoints(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq) {
+ return std::unique_ptr< ::grpc::ClientAsyncReaderWriterInterface< flatbuffers::grpc::Message<Monster>, flatbuffers::grpc::Message<Stat>>>(PrepareAsyncGetMinMaxHitPointsRaw(context, cq));
+ }
+ private:
+ virtual ::grpc::ClientAsyncResponseReaderInterface< flatbuffers::grpc::Message<Stat>>* AsyncStoreRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Monster>& request, ::grpc::CompletionQueue* cq) = 0;
+ virtual ::grpc::ClientAsyncResponseReaderInterface< flatbuffers::grpc::Message<Stat>>* PrepareAsyncStoreRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Monster>& request, ::grpc::CompletionQueue* cq) = 0;
+ virtual ::grpc::ClientReaderInterface< flatbuffers::grpc::Message<Monster>>* RetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Stat>& request) = 0;
+ virtual ::grpc::ClientAsyncReaderInterface< flatbuffers::grpc::Message<Monster>>* AsyncRetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Stat>& request, ::grpc::CompletionQueue* cq, void* tag) = 0;
+ virtual ::grpc::ClientAsyncReaderInterface< flatbuffers::grpc::Message<Monster>>* PrepareAsyncRetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Stat>& request, ::grpc::CompletionQueue* cq) = 0;
+ virtual ::grpc::ClientWriterInterface< flatbuffers::grpc::Message<Monster>>* GetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message<Stat>* response) = 0;
+ virtual ::grpc::ClientAsyncWriterInterface< flatbuffers::grpc::Message<Monster>>* AsyncGetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message<Stat>* response, ::grpc::CompletionQueue* cq, void* tag) = 0;
+ virtual ::grpc::ClientAsyncWriterInterface< flatbuffers::grpc::Message<Monster>>* PrepareAsyncGetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message<Stat>* response, ::grpc::CompletionQueue* cq) = 0;
+ virtual ::grpc::ClientReaderWriterInterface< flatbuffers::grpc::Message<Monster>, flatbuffers::grpc::Message<Stat>>* GetMinMaxHitPointsRaw(::grpc::ClientContext* context) = 0;
+ virtual ::grpc::ClientAsyncReaderWriterInterface< flatbuffers::grpc::Message<Monster>, flatbuffers::grpc::Message<Stat>>* AsyncGetMinMaxHitPointsRaw(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, void* tag) = 0;
+ virtual ::grpc::ClientAsyncReaderWriterInterface< flatbuffers::grpc::Message<Monster>, flatbuffers::grpc::Message<Stat>>* PrepareAsyncGetMinMaxHitPointsRaw(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq) = 0;
+ };
+ class Stub final : public StubInterface {
+ public:
+ Stub(const std::shared_ptr< ::grpc::ChannelInterface>& channel);
+ ::grpc::Status Store(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Monster>& request, flatbuffers::grpc::Message<Stat>* response) override;
+ std::unique_ptr< ::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message<Stat>>> AsyncStore(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Monster>& request, ::grpc::CompletionQueue* cq) {
+ return std::unique_ptr< ::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message<Stat>>>(AsyncStoreRaw(context, request, cq));
+ }
+ std::unique_ptr< ::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message<Stat>>> PrepareAsyncStore(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Monster>& request, ::grpc::CompletionQueue* cq) {
+ return std::unique_ptr< ::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message<Stat>>>(PrepareAsyncStoreRaw(context, request, cq));
+ }
+ std::unique_ptr< ::grpc::ClientReader< flatbuffers::grpc::Message<Monster>>> Retrieve(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Stat>& request) {
+ return std::unique_ptr< ::grpc::ClientReader< flatbuffers::grpc::Message<Monster>>>(RetrieveRaw(context, request));
+ }
+ std::unique_ptr< ::grpc::ClientAsyncReader< flatbuffers::grpc::Message<Monster>>> AsyncRetrieve(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Stat>& request, ::grpc::CompletionQueue* cq, void* tag) {
+ return std::unique_ptr< ::grpc::ClientAsyncReader< flatbuffers::grpc::Message<Monster>>>(AsyncRetrieveRaw(context, request, cq, tag));
+ }
+ std::unique_ptr< ::grpc::ClientAsyncReader< flatbuffers::grpc::Message<Monster>>> PrepareAsyncRetrieve(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Stat>& request, ::grpc::CompletionQueue* cq) {
+ return std::unique_ptr< ::grpc::ClientAsyncReader< flatbuffers::grpc::Message<Monster>>>(PrepareAsyncRetrieveRaw(context, request, cq));
+ }
+ std::unique_ptr< ::grpc::ClientWriter< flatbuffers::grpc::Message<Monster>>> GetMaxHitPoint(::grpc::ClientContext* context, flatbuffers::grpc::Message<Stat>* response) {
+ return std::unique_ptr< ::grpc::ClientWriter< flatbuffers::grpc::Message<Monster>>>(GetMaxHitPointRaw(context, response));
+ }
+ std::unique_ptr< ::grpc::ClientAsyncWriter< flatbuffers::grpc::Message<Monster>>> AsyncGetMaxHitPoint(::grpc::ClientContext* context, flatbuffers::grpc::Message<Stat>* response, ::grpc::CompletionQueue* cq, void* tag) {
+ return std::unique_ptr< ::grpc::ClientAsyncWriter< flatbuffers::grpc::Message<Monster>>>(AsyncGetMaxHitPointRaw(context, response, cq, tag));
+ }
+ std::unique_ptr< ::grpc::ClientAsyncWriter< flatbuffers::grpc::Message<Monster>>> PrepareAsyncGetMaxHitPoint(::grpc::ClientContext* context, flatbuffers::grpc::Message<Stat>* response, ::grpc::CompletionQueue* cq) {
+ return std::unique_ptr< ::grpc::ClientAsyncWriter< flatbuffers::grpc::Message<Monster>>>(PrepareAsyncGetMaxHitPointRaw(context, response, cq));
+ }
+ std::unique_ptr< ::grpc::ClientReaderWriter< flatbuffers::grpc::Message<Monster>, flatbuffers::grpc::Message<Stat>>> GetMinMaxHitPoints(::grpc::ClientContext* context) {
+ return std::unique_ptr< ::grpc::ClientReaderWriter< flatbuffers::grpc::Message<Monster>, flatbuffers::grpc::Message<Stat>>>(GetMinMaxHitPointsRaw(context));
+ }
+ std::unique_ptr< ::grpc::ClientAsyncReaderWriter< flatbuffers::grpc::Message<Monster>, flatbuffers::grpc::Message<Stat>>> AsyncGetMinMaxHitPoints(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, void* tag) {
+ return std::unique_ptr< ::grpc::ClientAsyncReaderWriter< flatbuffers::grpc::Message<Monster>, flatbuffers::grpc::Message<Stat>>>(AsyncGetMinMaxHitPointsRaw(context, cq, tag));
+ }
+ std::unique_ptr< ::grpc::ClientAsyncReaderWriter< flatbuffers::grpc::Message<Monster>, flatbuffers::grpc::Message<Stat>>> PrepareAsyncGetMinMaxHitPoints(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq) {
+ return std::unique_ptr< ::grpc::ClientAsyncReaderWriter< flatbuffers::grpc::Message<Monster>, flatbuffers::grpc::Message<Stat>>>(PrepareAsyncGetMinMaxHitPointsRaw(context, cq));
+ }
+
+ private:
+ std::shared_ptr< ::grpc::ChannelInterface> channel_;
+ ::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message<Stat>>* AsyncStoreRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Monster>& request, ::grpc::CompletionQueue* cq) override;
+ ::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message<Stat>>* PrepareAsyncStoreRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Monster>& request, ::grpc::CompletionQueue* cq) override;
+ ::grpc::ClientReader< flatbuffers::grpc::Message<Monster>>* RetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Stat>& request) override;
+ ::grpc::ClientAsyncReader< flatbuffers::grpc::Message<Monster>>* AsyncRetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Stat>& request, ::grpc::CompletionQueue* cq, void* tag) override;
+ ::grpc::ClientAsyncReader< flatbuffers::grpc::Message<Monster>>* PrepareAsyncRetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message<Stat>& request, ::grpc::CompletionQueue* cq) override;
+ ::grpc::ClientWriter< flatbuffers::grpc::Message<Monster>>* GetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message<Stat>* response) override;
+ ::grpc::ClientAsyncWriter< flatbuffers::grpc::Message<Monster>>* AsyncGetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message<Stat>* response, ::grpc::CompletionQueue* cq, void* tag) override;
+ ::grpc::ClientAsyncWriter< flatbuffers::grpc::Message<Monster>>* PrepareAsyncGetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message<Stat>* response, ::grpc::CompletionQueue* cq) override;
+ ::grpc::ClientReaderWriter< flatbuffers::grpc::Message<Monster>, flatbuffers::grpc::Message<Stat>>* GetMinMaxHitPointsRaw(::grpc::ClientContext* context) override;
+ ::grpc::ClientAsyncReaderWriter< flatbuffers::grpc::Message<Monster>, flatbuffers::grpc::Message<Stat>>* AsyncGetMinMaxHitPointsRaw(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, void* tag) override;
+ ::grpc::ClientAsyncReaderWriter< flatbuffers::grpc::Message<Monster>, flatbuffers::grpc::Message<Stat>>* PrepareAsyncGetMinMaxHitPointsRaw(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq) override;
+ const ::grpc::internal::RpcMethod rpcmethod_Store_;
+ const ::grpc::internal::RpcMethod rpcmethod_Retrieve_;
+ const ::grpc::internal::RpcMethod rpcmethod_GetMaxHitPoint_;
+ const ::grpc::internal::RpcMethod rpcmethod_GetMinMaxHitPoints_;
+ };
+ static std::unique_ptr<Stub> NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel, const ::grpc::StubOptions& options = ::grpc::StubOptions());
+
+ class Service : public ::grpc::Service {
+ public:
+ Service();
+ virtual ~Service();
+ virtual ::grpc::Status Store(::grpc::ServerContext* context, const flatbuffers::grpc::Message<Monster>* request, flatbuffers::grpc::Message<Stat>* response);
+ virtual ::grpc::Status Retrieve(::grpc::ServerContext* context, const flatbuffers::grpc::Message<Stat>* request, ::grpc::ServerWriter< flatbuffers::grpc::Message<Monster>>* writer);
+ virtual ::grpc::Status GetMaxHitPoint(::grpc::ServerContext* context, ::grpc::ServerReader< flatbuffers::grpc::Message<Monster>>* reader, flatbuffers::grpc::Message<Stat>* response);
+ virtual ::grpc::Status GetMinMaxHitPoints(::grpc::ServerContext* context, ::grpc::ServerReaderWriter< flatbuffers::grpc::Message<Stat>, flatbuffers::grpc::Message<Monster>>* stream);
+ };
+ template <class BaseClass>
+ class WithAsyncMethod_Store : public BaseClass {
+ private:
+ void BaseClassMustBeDerivedFromService(const Service */*service*/) {}
+ public:
+ WithAsyncMethod_Store() {
+ ::grpc::Service::MarkMethodAsync(0);
+ }
+ ~WithAsyncMethod_Store() override {
+ BaseClassMustBeDerivedFromService(this);
+ }
+ // disable synchronous version of this method
+ ::grpc::Status Store(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message<Monster>* /*request*/, flatbuffers::grpc::Message<Stat>* /*response*/) final override {
+ abort();
+ return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
+ }
+ void RequestStore(::grpc::ServerContext* context, flatbuffers::grpc::Message<Monster>* request, ::grpc::ServerAsyncResponseWriter< flatbuffers::grpc::Message<Stat>>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) {
+ ::grpc::Service::RequestAsyncUnary(0, context, request, response, new_call_cq, notification_cq, tag);
+ }
+ };
+ template <class BaseClass>
+ class WithAsyncMethod_Retrieve : public BaseClass {
+ private:
+ void BaseClassMustBeDerivedFromService(const Service */*service*/) {}
+ public:
+ WithAsyncMethod_Retrieve() {
+ ::grpc::Service::MarkMethodAsync(1);
+ }
+ ~WithAsyncMethod_Retrieve() override {
+ BaseClassMustBeDerivedFromService(this);
+ }
+ // disable synchronous version of this method
+ ::grpc::Status Retrieve(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message<Stat>* /*request*/, ::grpc::ServerWriter< flatbuffers::grpc::Message<Monster>>* /*writer*/) final override {
+ abort();
+ return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
+ }
+ void RequestRetrieve(::grpc::ServerContext* context, flatbuffers::grpc::Message<Stat>* request, ::grpc::ServerAsyncWriter< flatbuffers::grpc::Message<Monster>>* writer, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) {
+ ::grpc::Service::RequestAsyncServerStreaming(1, context, request, writer, new_call_cq, notification_cq, tag);
+ }
+ };
+ template <class BaseClass>
+ class WithAsyncMethod_GetMaxHitPoint : public BaseClass {
+ private:
+ void BaseClassMustBeDerivedFromService(const Service */*service*/) {}
+ public:
+ WithAsyncMethod_GetMaxHitPoint() {
+ ::grpc::Service::MarkMethodAsync(2);
+ }
+ ~WithAsyncMethod_GetMaxHitPoint() override {
+ BaseClassMustBeDerivedFromService(this);
+ }
+ // disable synchronous version of this method
+ ::grpc::Status GetMaxHitPoint(::grpc::ServerContext* /*context*/, ::grpc::ServerReader< flatbuffers::grpc::Message<Monster>>* /*reader*/, flatbuffers::grpc::Message<Stat>* response) final override {
+ abort();
+ return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
+ }
+ void RequestGetMaxHitPoint(::grpc::ServerContext* context, ::grpc::ServerAsyncReader< flatbuffers::grpc::Message<Stat>, flatbuffers::grpc::Message<Monster>>* reader, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) {
+ ::grpc::Service::RequestAsyncClientStreaming(2, context, reader, new_call_cq, notification_cq, tag);
+ }
+ };
+ template <class BaseClass>
+ class WithAsyncMethod_GetMinMaxHitPoints : public BaseClass {
+ private:
+ void BaseClassMustBeDerivedFromService(const Service */*service*/) {}
+ public:
+ WithAsyncMethod_GetMinMaxHitPoints() {
+ ::grpc::Service::MarkMethodAsync(3);
+ }
+ ~WithAsyncMethod_GetMinMaxHitPoints() override {
+ BaseClassMustBeDerivedFromService(this);
+ }
+ // disable synchronous version of this method
+ ::grpc::Status GetMinMaxHitPoints(::grpc::ServerContext* /*context*/, ::grpc::ServerReaderWriter< flatbuffers::grpc::Message<Stat>, flatbuffers::grpc::Message<Monster>>* /*stream*/) final override {
+ abort();
+ return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
+ }
+ void RequestGetMinMaxHitPoints(::grpc::ServerContext* context, ::grpc::ServerAsyncReaderWriter< flatbuffers::grpc::Message<Stat>, flatbuffers::grpc::Message<Monster>>* stream, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) {
+ ::grpc::Service::RequestAsyncBidiStreaming(3, context, stream, new_call_cq, notification_cq, tag);
+ }
+ };
+ typedef WithAsyncMethod_Store< WithAsyncMethod_Retrieve< WithAsyncMethod_GetMaxHitPoint< WithAsyncMethod_GetMinMaxHitPoints< Service > > > > AsyncService;
+ template <class BaseClass>
+ class WithGenericMethod_Store : public BaseClass {
+ private:
+ void BaseClassMustBeDerivedFromService(const Service */*service*/) {}
+ public:
+ WithGenericMethod_Store() {
+ ::grpc::Service::MarkMethodGeneric(0);
+ }
+ ~WithGenericMethod_Store() override {
+ BaseClassMustBeDerivedFromService(this);
+ }
+ // disable synchronous version of this method
+ ::grpc::Status Store(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message<Monster>* /*request*/, flatbuffers::grpc::Message<Stat>* /*response*/) final override {
+ abort();
+ return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
+ }
+ };
+ template <class BaseClass>
+ class WithGenericMethod_Retrieve : public BaseClass {
+ private:
+ void BaseClassMustBeDerivedFromService(const Service */*service*/) {}
+ public:
+ WithGenericMethod_Retrieve() {
+ ::grpc::Service::MarkMethodGeneric(1);
+ }
+ ~WithGenericMethod_Retrieve() override {
+ BaseClassMustBeDerivedFromService(this);
+ }
+ // disable synchronous version of this method
+ ::grpc::Status Retrieve(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message<Stat>* /*request*/, ::grpc::ServerWriter< flatbuffers::grpc::Message<Monster>>* /*writer*/) final override {
+ abort();
+ return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
+ }
+ };
+ template <class BaseClass>
+ class WithGenericMethod_GetMaxHitPoint : public BaseClass {
+ private:
+ void BaseClassMustBeDerivedFromService(const Service */*service*/) {}
+ public:
+ WithGenericMethod_GetMaxHitPoint() {
+ ::grpc::Service::MarkMethodGeneric(2);
+ }
+ ~WithGenericMethod_GetMaxHitPoint() override {
+ BaseClassMustBeDerivedFromService(this);
+ }
+ // disable synchronous version of this method
+ ::grpc::Status GetMaxHitPoint(::grpc::ServerContext* /*context*/, ::grpc::ServerReader< flatbuffers::grpc::Message<Monster>>* /*reader*/, flatbuffers::grpc::Message<Stat>* /*response*/) final override {
+ abort();
+ return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
+ }
+ };
+ template <class BaseClass>
+ class WithGenericMethod_GetMinMaxHitPoints : public BaseClass {
+ private:
+ void BaseClassMustBeDerivedFromService(const Service */*service*/) {}
+ public:
+ WithGenericMethod_GetMinMaxHitPoints() {
+ ::grpc::Service::MarkMethodGeneric(3);
+ }
+ ~WithGenericMethod_GetMinMaxHitPoints() override {
+ BaseClassMustBeDerivedFromService(this);
+ }
+ // disable synchronous version of this method
+ ::grpc::Status GetMinMaxHitPoints(::grpc::ServerContext* /*context*/, ::grpc::ServerReaderWriter< flatbuffers::grpc::Message<Stat>, flatbuffers::grpc::Message<Monster>>* /*stream*/) final override {
+ abort();
+ return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
+ }
+ };
+ template <class BaseClass>
+ class WithStreamedUnaryMethod_Store : public BaseClass {
+ private:
+ void BaseClassMustBeDerivedFromService(const Service */*service*/) {}
+ public:
+ WithStreamedUnaryMethod_Store() {
+ ::grpc::Service::MarkMethodStreamed(0,
+ new ::grpc::internal::StreamedUnaryHandler< flatbuffers::grpc::Message<Monster>, flatbuffers::grpc::Message<Stat>>(std::bind(&WithStreamedUnaryMethod_Store<BaseClass>::StreamedStore, this, std::placeholders::_1, std::placeholders::_2)));
+ }
+ ~WithStreamedUnaryMethod_Store() override {
+ BaseClassMustBeDerivedFromService(this);
+ }
+ // disable regular version of this method
+ ::grpc::Status Store(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message<Monster>* /*request*/, flatbuffers::grpc::Message<Stat>* /*response*/) final override {
+ abort();
+ return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
+ }
+ // replace default version of method with streamed unary
+ virtual ::grpc::Status StreamedStore(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< flatbuffers::grpc::Message<Monster>,flatbuffers::grpc::Message<Stat>>* server_unary_streamer) = 0;
+ };
+ typedef WithStreamedUnaryMethod_Store< Service > StreamedUnaryService;
+ template <class BaseClass>
+ class WithSplitStreamingMethod_Retrieve : public BaseClass {
+ private:
+ void BaseClassMustBeDerivedFromService(const Service */*service*/) { }
+ public:
+ WithSplitStreamingMethod_Retrieve() {
+ ::grpc::Service::MarkMethodStreamed(1,
+ new ::grpc::internal::SplitServerStreamingHandler< flatbuffers::grpc::Message<Stat>, flatbuffers::grpc::Message<Monster>>(std::bind(&WithSplitStreamingMethod_Retrieve<BaseClass>::StreamedRetrieve, this, std::placeholders::_1, std::placeholders::_2)));
+ }
+ ~WithSplitStreamingMethod_Retrieve() override {
+ BaseClassMustBeDerivedFromService(this);
+ }
+ // disable regular version of this method
+ ::grpc::Status Retrieve(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message<Stat>* /*request*/, ::grpc::ServerWriter< flatbuffers::grpc::Message<Monster>>* /*writer*/) final override {
+ abort();
+ return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
+ }
+ // replace default version of method with split streamed
+ virtual ::grpc::Status StreamedRetrieve(::grpc::ServerContext* context, ::grpc::ServerSplitStreamer< flatbuffers::grpc::Message<Stat>,flatbuffers::grpc::Message<Monster>>* server_split_streamer) = 0;
+ };
+ typedef WithSplitStreamingMethod_Retrieve< Service > SplitStreamedService;
+ typedef WithStreamedUnaryMethod_Store< WithSplitStreamingMethod_Retrieve< Service > > StreamedService;
+};
+
+} // namespace Example
+} // namespace MyGame
+
+
+#endif // GRPC_monster_5ftest__INCLUDED
diff --git a/tests/monster_test_generated.h b/tests/monster_test_generated.h
index 8f55b1d..eeaa341 100644
--- a/tests/monster_test_generated.h
+++ b/tests/monster_test_generated.h
@@ -33,6 +33,8 @@
struct Ability;
+struct StructOfStructs;
+
struct Stat;
struct StatBuilder;
struct StatT;
@@ -69,6 +71,8 @@
bool operator!=(const Vec3 &lhs, const Vec3 &rhs);
bool operator==(const Ability &lhs, const Ability &rhs);
bool operator!=(const Ability &lhs, const Ability &rhs);
+bool operator==(const StructOfStructs &lhs, const StructOfStructs &rhs);
+bool operator!=(const StructOfStructs &lhs, const StructOfStructs &rhs);
bool operator==(const StatT &lhs, const StatT &rhs);
bool operator!=(const StatT &lhs, const StatT &rhs);
bool operator==(const ReferrableT &lhs, const ReferrableT &rhs);
@@ -98,6 +102,8 @@
inline const flatbuffers::TypeTable *AbilityTypeTable();
+inline const flatbuffers::TypeTable *StructOfStructsTypeTable();
+
inline const flatbuffers::TypeTable *StatTypeTable();
inline const flatbuffers::TypeTable *ReferrableTypeTable();
@@ -107,7 +113,7 @@
inline const flatbuffers::TypeTable *TypeAliasesTypeTable();
/// Composite components of Monster color.
-enum Color {
+enum Color : uint8_t {
Color_Red = 1,
/// \brief color Green
/// Green is bit_flag with value (1u << 1)
@@ -148,7 +154,7 @@
return EnumNamesColor()[index];
}
-enum Race {
+enum Race : int8_t {
Race_None = -1,
Race_Human = 0,
Race_Dwarf = 1,
@@ -184,7 +190,33 @@
return EnumNamesRace()[index];
}
-enum Any {
+enum LongEnum : uint64_t {
+ LongEnum_LongOne = 2ULL,
+ LongEnum_LongTwo = 4ULL,
+ LongEnum_LongBig = 1099511627776ULL,
+ LongEnum_NONE = 0,
+ LongEnum_ANY = 1099511627782ULL
+};
+
+inline const LongEnum (&EnumValuesLongEnum())[3] {
+ static const LongEnum values[] = {
+ LongEnum_LongOne,
+ LongEnum_LongTwo,
+ LongEnum_LongBig
+ };
+ return values;
+}
+
+inline const char *EnumNameLongEnum(LongEnum e) {
+ switch (e) {
+ case LongEnum_LongOne: return "LongOne";
+ case LongEnum_LongTwo: return "LongTwo";
+ case LongEnum_LongBig: return "LongBig";
+ default: return "";
+ }
+}
+
+enum Any : uint8_t {
Any_NONE = 0,
Any_Monster = 1,
Any_TestSimpleTableWithEnum = 2,
@@ -236,6 +268,22 @@
static const Any enum_value = Any_MyGame_Example2_Monster;
};
+template<typename T> struct AnyUnionTraits {
+ static const Any enum_value = Any_NONE;
+};
+
+template<> struct AnyUnionTraits<MyGame::Example::MonsterT> {
+ static const Any enum_value = Any_Monster;
+};
+
+template<> struct AnyUnionTraits<MyGame::Example::TestSimpleTableWithEnumT> {
+ static const Any enum_value = Any_TestSimpleTableWithEnum;
+};
+
+template<> struct AnyUnionTraits<MyGame::Example2::MonsterT> {
+ static const Any enum_value = Any_MyGame_Example2_Monster;
+};
+
struct AnyUnion {
Any type;
void *value;
@@ -253,17 +301,15 @@
void Reset();
-#ifndef FLATBUFFERS_CPP98_STL
template <typename T>
void Set(T&& val) {
- using RT = typename std::remove_reference<T>::type;
+ typedef typename std::remove_reference<T>::type RT;
Reset();
- type = AnyTraits<typename RT::TableType>::enum_value;
+ type = AnyUnionTraits<RT>::enum_value;
if (type != Any_NONE) {
value = new RT(std::forward<T>(val));
}
}
-#endif // FLATBUFFERS_CPP98_STL
static void *UnPack(const void *obj, Any type, const flatbuffers::resolver_function_t *resolver);
flatbuffers::Offset<void> Pack(flatbuffers::FlatBufferBuilder &_fbb, const flatbuffers::rehasher_function_t *_rehasher = nullptr) const;
@@ -326,7 +372,7 @@
bool VerifyAny(flatbuffers::Verifier &verifier, const void *obj, Any type);
bool VerifyAnyVector(flatbuffers::Verifier &verifier, const flatbuffers::Vector<flatbuffers::Offset<void>> *values, const flatbuffers::Vector<uint8_t> *types);
-enum AnyUniqueAliases {
+enum AnyUniqueAliases : uint8_t {
AnyUniqueAliases_NONE = 0,
AnyUniqueAliases_M = 1,
AnyUniqueAliases_TS = 2,
@@ -378,6 +424,22 @@
static const AnyUniqueAliases enum_value = AnyUniqueAliases_M2;
};
+template<typename T> struct AnyUniqueAliasesUnionTraits {
+ static const AnyUniqueAliases enum_value = AnyUniqueAliases_NONE;
+};
+
+template<> struct AnyUniqueAliasesUnionTraits<MyGame::Example::MonsterT> {
+ static const AnyUniqueAliases enum_value = AnyUniqueAliases_M;
+};
+
+template<> struct AnyUniqueAliasesUnionTraits<MyGame::Example::TestSimpleTableWithEnumT> {
+ static const AnyUniqueAliases enum_value = AnyUniqueAliases_TS;
+};
+
+template<> struct AnyUniqueAliasesUnionTraits<MyGame::Example2::MonsterT> {
+ static const AnyUniqueAliases enum_value = AnyUniqueAliases_M2;
+};
+
struct AnyUniqueAliasesUnion {
AnyUniqueAliases type;
void *value;
@@ -395,17 +457,15 @@
void Reset();
-#ifndef FLATBUFFERS_CPP98_STL
template <typename T>
void Set(T&& val) {
- using RT = typename std::remove_reference<T>::type;
+ typedef typename std::remove_reference<T>::type RT;
Reset();
- type = AnyUniqueAliasesTraits<typename RT::TableType>::enum_value;
+ type = AnyUniqueAliasesUnionTraits<RT>::enum_value;
if (type != AnyUniqueAliases_NONE) {
value = new RT(std::forward<T>(val));
}
}
-#endif // FLATBUFFERS_CPP98_STL
static void *UnPack(const void *obj, AnyUniqueAliases type, const flatbuffers::resolver_function_t *resolver);
flatbuffers::Offset<void> Pack(flatbuffers::FlatBufferBuilder &_fbb, const flatbuffers::rehasher_function_t *_rehasher = nullptr) const;
@@ -468,7 +528,7 @@
bool VerifyAnyUniqueAliases(flatbuffers::Verifier &verifier, const void *obj, AnyUniqueAliases type);
bool VerifyAnyUniqueAliasesVector(flatbuffers::Verifier &verifier, const flatbuffers::Vector<flatbuffers::Offset<void>> *values, const flatbuffers::Vector<uint8_t> *types);
-enum AnyAmbiguousAliases {
+enum AnyAmbiguousAliases : uint8_t {
AnyAmbiguousAliases_NONE = 0,
AnyAmbiguousAliases_M1 = 1,
AnyAmbiguousAliases_M2 = 2,
@@ -754,8 +814,8 @@
bool KeyCompareLessThan(const Ability *o) const {
return id() < o->id();
}
- int KeyCompareWithValue(uint32_t val) const {
- return static_cast<int>(id() > val) - static_cast<int>(id() < val);
+ int KeyCompareWithValue(uint32_t _id) const {
+ return static_cast<int>(id() > _id) - static_cast<int>(id() < _id);
}
uint32_t distance() const {
return flatbuffers::EndianScalar(distance_);
@@ -777,23 +837,65 @@
}
+FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) StructOfStructs FLATBUFFERS_FINAL_CLASS {
+ private:
+ MyGame::Example::Ability a_;
+ MyGame::Example::Test b_;
+ MyGame::Example::Ability c_;
+
+ public:
+ static const flatbuffers::TypeTable *MiniReflectTypeTable() {
+ return StructOfStructsTypeTable();
+ }
+ StructOfStructs()
+ : a_(),
+ b_(),
+ c_() {
+ }
+ StructOfStructs(const MyGame::Example::Ability &_a, const MyGame::Example::Test &_b, const MyGame::Example::Ability &_c)
+ : a_(_a),
+ b_(_b),
+ c_(_c) {
+ }
+ const MyGame::Example::Ability &a() const {
+ return a_;
+ }
+ MyGame::Example::Ability &mutable_a() {
+ return a_;
+ }
+ const MyGame::Example::Test &b() const {
+ return b_;
+ }
+ MyGame::Example::Test &mutable_b() {
+ return b_;
+ }
+ const MyGame::Example::Ability &c() const {
+ return c_;
+ }
+ MyGame::Example::Ability &mutable_c() {
+ return c_;
+ }
+};
+FLATBUFFERS_STRUCT_END(StructOfStructs, 20);
+
+inline bool operator==(const StructOfStructs &lhs, const StructOfStructs &rhs) {
+ return
+ (lhs.a() == rhs.a()) &&
+ (lhs.b() == rhs.b()) &&
+ (lhs.c() == rhs.c());
+}
+
+inline bool operator!=(const StructOfStructs &lhs, const StructOfStructs &rhs) {
+ return !(lhs == rhs);
+}
+
+
} // namespace Example
struct InParentNamespaceT : public flatbuffers::NativeTable {
typedef InParentNamespace TableType;
- InParentNamespaceT() {
- }
};
-inline bool operator==(const InParentNamespaceT &, const InParentNamespaceT &) {
- return true;
-}
-
-inline bool operator!=(const InParentNamespaceT &lhs, const InParentNamespaceT &rhs) {
- return !(lhs == rhs);
-}
-
-
struct InParentNamespace FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
typedef InParentNamespaceT NativeTableType;
typedef InParentNamespaceBuilder Builder;
@@ -836,19 +938,8 @@
struct MonsterT : public flatbuffers::NativeTable {
typedef Monster TableType;
- MonsterT() {
- }
};
-inline bool operator==(const MonsterT &, const MonsterT &) {
- return true;
-}
-
-inline bool operator!=(const MonsterT &lhs, const MonsterT &rhs) {
- return !(lhs == rhs);
-}
-
-
struct Monster FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
typedef MonsterT NativeTableType;
typedef MonsterBuilder Builder;
@@ -893,22 +984,9 @@
struct TestSimpleTableWithEnumT : public flatbuffers::NativeTable {
typedef TestSimpleTableWithEnum TableType;
- MyGame::Example::Color color;
- TestSimpleTableWithEnumT()
- : color(MyGame::Example::Color_Green) {
- }
+ MyGame::Example::Color color = MyGame::Example::Color_Green;
};
-inline bool operator==(const TestSimpleTableWithEnumT &lhs, const TestSimpleTableWithEnumT &rhs) {
- return
- (lhs.color == rhs.color);
-}
-
-inline bool operator!=(const TestSimpleTableWithEnumT &lhs, const TestSimpleTableWithEnumT &rhs) {
- return !(lhs == rhs);
-}
-
-
struct TestSimpleTableWithEnum FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
typedef TestSimpleTableWithEnumT NativeTableType;
typedef TestSimpleTableWithEnumBuilder Builder;
@@ -921,12 +999,12 @@
MyGame::Example::Color color() const {
return static_cast<MyGame::Example::Color>(GetField<uint8_t>(VT_COLOR, 2));
}
- bool mutate_color(MyGame::Example::Color _color) {
+ bool mutate_color(MyGame::Example::Color _color = static_cast<MyGame::Example::Color>(2)) {
return SetField<uint8_t>(VT_COLOR, static_cast<uint8_t>(_color), 2);
}
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
- VerifyField<uint8_t>(verifier, VT_COLOR) &&
+ VerifyField<uint8_t>(verifier, VT_COLOR, 1) &&
verifier.EndTable();
}
TestSimpleTableWithEnumT *UnPack(const flatbuffers::resolver_function_t *_resolver = nullptr) const;
@@ -964,27 +1042,11 @@
struct StatT : public flatbuffers::NativeTable {
typedef Stat TableType;
- std::string id;
- int64_t val;
- uint16_t count;
- StatT()
- : val(0),
- count(0) {
- }
+ std::string id{};
+ int64_t val = 0;
+ uint16_t count = 0;
};
-inline bool operator==(const StatT &lhs, const StatT &rhs) {
- return
- (lhs.id == rhs.id) &&
- (lhs.val == rhs.val) &&
- (lhs.count == rhs.count);
-}
-
-inline bool operator!=(const StatT &lhs, const StatT &rhs) {
- return !(lhs == rhs);
-}
-
-
struct Stat FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
typedef StatT NativeTableType;
typedef StatBuilder Builder;
@@ -1005,21 +1067,27 @@
int64_t val() const {
return GetField<int64_t>(VT_VAL, 0);
}
- bool mutate_val(int64_t _val) {
+ bool mutate_val(int64_t _val = 0) {
return SetField<int64_t>(VT_VAL, _val, 0);
}
uint16_t count() const {
return GetField<uint16_t>(VT_COUNT, 0);
}
- bool mutate_count(uint16_t _count) {
+ bool mutate_count(uint16_t _count = 0) {
return SetField<uint16_t>(VT_COUNT, _count, 0);
}
+ bool KeyCompareLessThan(const Stat *o) const {
+ return count() < o->count();
+ }
+ int KeyCompareWithValue(uint16_t _count) const {
+ return static_cast<int>(count() > _count) - static_cast<int>(count() < _count);
+ }
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
VerifyOffset(verifier, VT_ID) &&
verifier.VerifyString(id()) &&
- VerifyField<int64_t>(verifier, VT_VAL) &&
- VerifyField<uint16_t>(verifier, VT_COUNT) &&
+ VerifyField<int64_t>(verifier, VT_VAL, 8) &&
+ VerifyField<uint16_t>(verifier, VT_COUNT, 2) &&
verifier.EndTable();
}
StatT *UnPack(const flatbuffers::resolver_function_t *_resolver = nullptr) const;
@@ -1080,22 +1148,9 @@
struct ReferrableT : public flatbuffers::NativeTable {
typedef Referrable TableType;
- uint64_t id;
- ReferrableT()
- : id(0) {
- }
+ uint64_t id = 0;
};
-inline bool operator==(const ReferrableT &lhs, const ReferrableT &rhs) {
- return
- (lhs.id == rhs.id);
-}
-
-inline bool operator!=(const ReferrableT &lhs, const ReferrableT &rhs) {
- return !(lhs == rhs);
-}
-
-
struct Referrable FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
typedef ReferrableT NativeTableType;
typedef ReferrableBuilder Builder;
@@ -1108,18 +1163,18 @@
uint64_t id() const {
return GetField<uint64_t>(VT_ID, 0);
}
- bool mutate_id(uint64_t _id) {
+ bool mutate_id(uint64_t _id = 0) {
return SetField<uint64_t>(VT_ID, _id, 0);
}
bool KeyCompareLessThan(const Referrable *o) const {
return id() < o->id();
}
- int KeyCompareWithValue(uint64_t val) const {
- return static_cast<int>(id() > val) - static_cast<int>(id() < val);
+ int KeyCompareWithValue(uint64_t _id) const {
+ return static_cast<int>(id() > _id) - static_cast<int>(id() < _id);
}
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
- VerifyField<uint64_t>(verifier, VT_ID) &&
+ VerifyField<uint64_t>(verifier, VT_ID, 8) &&
verifier.EndTable();
}
ReferrableT *UnPack(const flatbuffers::resolver_function_t *_resolver = nullptr) const;
@@ -1157,130 +1212,62 @@
struct MonsterT : public flatbuffers::NativeTable {
typedef Monster TableType;
- flatbuffers::unique_ptr<MyGame::Example::Vec3> pos;
- int16_t mana;
- int16_t hp;
- std::string name;
- std::vector<uint8_t> inventory;
- MyGame::Example::Color color;
- MyGame::Example::AnyUnion test;
- std::vector<MyGame::Example::Test> test4;
- std::vector<std::string> testarrayofstring;
- std::vector<flatbuffers::unique_ptr<MyGame::Example::MonsterT>> testarrayoftables;
- flatbuffers::unique_ptr<MyGame::Example::MonsterT> enemy;
- std::vector<uint8_t> testnestedflatbuffer;
- flatbuffers::unique_ptr<MyGame::Example::StatT> testempty;
- bool testbool;
- int32_t testhashs32_fnv1;
- uint32_t testhashu32_fnv1;
- int64_t testhashs64_fnv1;
- uint64_t testhashu64_fnv1;
- int32_t testhashs32_fnv1a;
- Stat *testhashu32_fnv1a;
- int64_t testhashs64_fnv1a;
- uint64_t testhashu64_fnv1a;
- std::vector<bool> testarrayofbools;
- float testf;
- float testf2;
- float testf3;
- std::vector<std::string> testarrayofstring2;
- std::vector<MyGame::Example::Ability> testarrayofsortedstruct;
- std::vector<uint8_t> flex;
- std::vector<MyGame::Example::Test> test5;
- std::vector<int64_t> vector_of_longs;
- std::vector<double> vector_of_doubles;
- flatbuffers::unique_ptr<MyGame::InParentNamespaceT> parent_namespace_test;
- std::vector<flatbuffers::unique_ptr<MyGame::Example::ReferrableT>> vector_of_referrables;
- ReferrableT *single_weak_reference;
- std::vector<ReferrableT *> vector_of_weak_references;
- std::vector<flatbuffers::unique_ptr<MyGame::Example::ReferrableT>> vector_of_strong_referrables;
- ReferrableT *co_owning_reference;
- std::vector<flatbuffers::unique_ptr<ReferrableT>> vector_of_co_owning_references;
- ReferrableT *non_owning_reference;
- std::vector<ReferrableT *> vector_of_non_owning_references;
- MyGame::Example::AnyUniqueAliasesUnion any_unique;
- MyGame::Example::AnyAmbiguousAliasesUnion any_ambiguous;
- std::vector<MyGame::Example::Color> vector_of_enums;
- MyGame::Example::Race signed_enum;
- std::vector<uint8_t> testrequirednestedflatbuffer;
- MonsterT()
- : mana(150),
- hp(100),
- color(MyGame::Example::Color_Blue),
- testbool(false),
- testhashs32_fnv1(0),
- testhashu32_fnv1(0),
- testhashs64_fnv1(0),
- testhashu64_fnv1(0),
- testhashs32_fnv1a(0),
- testhashu32_fnv1a(nullptr),
- testhashs64_fnv1a(0),
- testhashu64_fnv1a(0),
- testf(3.14159f),
- testf2(3.0f),
- testf3(0.0f),
- single_weak_reference(nullptr),
- co_owning_reference(nullptr),
- non_owning_reference(nullptr),
- signed_enum(MyGame::Example::Race_None) {
- }
+ flatbuffers::unique_ptr<MyGame::Example::Vec3> pos{};
+ int16_t mana = 150;
+ int16_t hp = 100;
+ std::string name{};
+ std::vector<uint8_t> inventory{};
+ MyGame::Example::Color color = MyGame::Example::Color_Blue;
+ MyGame::Example::AnyUnion test{};
+ std::vector<MyGame::Example::Test> test4{};
+ std::vector<std::string> testarrayofstring{};
+ std::vector<flatbuffers::unique_ptr<MyGame::Example::MonsterT>> testarrayoftables{};
+ flatbuffers::unique_ptr<MyGame::Example::MonsterT> enemy{};
+ std::vector<uint8_t> testnestedflatbuffer{};
+ flatbuffers::unique_ptr<MyGame::Example::StatT> testempty{};
+ bool testbool = false;
+ int32_t testhashs32_fnv1 = 0;
+ uint32_t testhashu32_fnv1 = 0;
+ int64_t testhashs64_fnv1 = 0;
+ uint64_t testhashu64_fnv1 = 0;
+ int32_t testhashs32_fnv1a = 0;
+ Stat *testhashu32_fnv1a = nullptr;
+ int64_t testhashs64_fnv1a = 0;
+ uint64_t testhashu64_fnv1a = 0;
+ std::vector<bool> testarrayofbools{};
+ float testf = 3.14159f;
+ float testf2 = 3.0f;
+ float testf3 = 0.0f;
+ std::vector<std::string> testarrayofstring2{};
+ std::vector<MyGame::Example::Ability> testarrayofsortedstruct{};
+ std::vector<uint8_t> flex{};
+ std::vector<MyGame::Example::Test> test5{};
+ std::vector<int64_t> vector_of_longs{};
+ std::vector<double> vector_of_doubles{};
+ flatbuffers::unique_ptr<MyGame::InParentNamespaceT> parent_namespace_test{};
+ std::vector<flatbuffers::unique_ptr<MyGame::Example::ReferrableT>> vector_of_referrables{};
+ ReferrableT *single_weak_reference = nullptr;
+ std::vector<ReferrableT *> vector_of_weak_references{};
+ std::vector<flatbuffers::unique_ptr<MyGame::Example::ReferrableT>> vector_of_strong_referrables{};
+ ReferrableT *co_owning_reference = nullptr;
+ std::vector<flatbuffers::unique_ptr<ReferrableT>> vector_of_co_owning_references{};
+ ReferrableT *non_owning_reference = nullptr;
+ std::vector<ReferrableT *> vector_of_non_owning_references{};
+ MyGame::Example::AnyUniqueAliasesUnion any_unique{};
+ MyGame::Example::AnyAmbiguousAliasesUnion any_ambiguous{};
+ std::vector<MyGame::Example::Color> vector_of_enums{};
+ MyGame::Example::Race signed_enum = MyGame::Example::Race_None;
+ std::vector<uint8_t> testrequirednestedflatbuffer{};
+ std::vector<flatbuffers::unique_ptr<MyGame::Example::StatT>> scalar_key_sorted_tables{};
+ MyGame::Example::Test native_inline{};
+ MyGame::Example::LongEnum long_enum_non_enum_default = static_cast<MyGame::Example::LongEnum>(0);
+ MyGame::Example::LongEnum long_enum_normal_default = MyGame::Example::LongEnum_LongOne;
+ MonsterT() = default;
+ MonsterT(const MonsterT &o);
+ MonsterT(MonsterT&&) FLATBUFFERS_NOEXCEPT = default;
+ MonsterT &operator=(MonsterT o) FLATBUFFERS_NOEXCEPT;
};
-inline bool operator==(const MonsterT &lhs, const MonsterT &rhs) {
- return
- (lhs.pos == rhs.pos) &&
- (lhs.mana == rhs.mana) &&
- (lhs.hp == rhs.hp) &&
- (lhs.name == rhs.name) &&
- (lhs.inventory == rhs.inventory) &&
- (lhs.color == rhs.color) &&
- (lhs.test == rhs.test) &&
- (lhs.test4 == rhs.test4) &&
- (lhs.testarrayofstring == rhs.testarrayofstring) &&
- (lhs.testarrayoftables == rhs.testarrayoftables) &&
- (lhs.enemy == rhs.enemy) &&
- (lhs.testnestedflatbuffer == rhs.testnestedflatbuffer) &&
- (lhs.testempty == rhs.testempty) &&
- (lhs.testbool == rhs.testbool) &&
- (lhs.testhashs32_fnv1 == rhs.testhashs32_fnv1) &&
- (lhs.testhashu32_fnv1 == rhs.testhashu32_fnv1) &&
- (lhs.testhashs64_fnv1 == rhs.testhashs64_fnv1) &&
- (lhs.testhashu64_fnv1 == rhs.testhashu64_fnv1) &&
- (lhs.testhashs32_fnv1a == rhs.testhashs32_fnv1a) &&
- (lhs.testhashu32_fnv1a == rhs.testhashu32_fnv1a) &&
- (lhs.testhashs64_fnv1a == rhs.testhashs64_fnv1a) &&
- (lhs.testhashu64_fnv1a == rhs.testhashu64_fnv1a) &&
- (lhs.testarrayofbools == rhs.testarrayofbools) &&
- (lhs.testf == rhs.testf) &&
- (lhs.testf2 == rhs.testf2) &&
- (lhs.testf3 == rhs.testf3) &&
- (lhs.testarrayofstring2 == rhs.testarrayofstring2) &&
- (lhs.testarrayofsortedstruct == rhs.testarrayofsortedstruct) &&
- (lhs.flex == rhs.flex) &&
- (lhs.test5 == rhs.test5) &&
- (lhs.vector_of_longs == rhs.vector_of_longs) &&
- (lhs.vector_of_doubles == rhs.vector_of_doubles) &&
- (lhs.parent_namespace_test == rhs.parent_namespace_test) &&
- (lhs.vector_of_referrables == rhs.vector_of_referrables) &&
- (lhs.single_weak_reference == rhs.single_weak_reference) &&
- (lhs.vector_of_weak_references == rhs.vector_of_weak_references) &&
- (lhs.vector_of_strong_referrables == rhs.vector_of_strong_referrables) &&
- (lhs.co_owning_reference == rhs.co_owning_reference) &&
- (lhs.vector_of_co_owning_references == rhs.vector_of_co_owning_references) &&
- (lhs.non_owning_reference == rhs.non_owning_reference) &&
- (lhs.vector_of_non_owning_references == rhs.vector_of_non_owning_references) &&
- (lhs.any_unique == rhs.any_unique) &&
- (lhs.any_ambiguous == rhs.any_ambiguous) &&
- (lhs.vector_of_enums == rhs.vector_of_enums) &&
- (lhs.signed_enum == rhs.signed_enum) &&
- (lhs.testrequirednestedflatbuffer == rhs.testrequirednestedflatbuffer);
-}
-
-inline bool operator!=(const MonsterT &lhs, const MonsterT &rhs) {
- return !(lhs == rhs);
-}
-
-
/// an example documentation comment: "monster object"
struct Monster FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
typedef MonsterT NativeTableType;
@@ -1337,7 +1324,11 @@
VT_ANY_AMBIGUOUS = 96,
VT_VECTOR_OF_ENUMS = 98,
VT_SIGNED_ENUM = 100,
- VT_TESTREQUIREDNESTEDFLATBUFFER = 102
+ VT_TESTREQUIREDNESTEDFLATBUFFER = 102,
+ VT_SCALAR_KEY_SORTED_TABLES = 104,
+ VT_NATIVE_INLINE = 106,
+ VT_LONG_ENUM_NON_ENUM_DEFAULT = 108,
+ VT_LONG_ENUM_NORMAL_DEFAULT = 110
};
const MyGame::Example::Vec3 *pos() const {
return GetStruct<const MyGame::Example::Vec3 *>(VT_POS);
@@ -1348,13 +1339,13 @@
int16_t mana() const {
return GetField<int16_t>(VT_MANA, 150);
}
- bool mutate_mana(int16_t _mana) {
+ bool mutate_mana(int16_t _mana = 150) {
return SetField<int16_t>(VT_MANA, _mana, 150);
}
int16_t hp() const {
return GetField<int16_t>(VT_HP, 100);
}
- bool mutate_hp(int16_t _hp) {
+ bool mutate_hp(int16_t _hp = 100) {
return SetField<int16_t>(VT_HP, _hp, 100);
}
const flatbuffers::String *name() const {
@@ -1366,8 +1357,8 @@
bool KeyCompareLessThan(const Monster *o) const {
return *name() < *o->name();
}
- int KeyCompareWithValue(const char *val) const {
- return strcmp(name()->c_str(), val);
+ int KeyCompareWithValue(const char *_name) const {
+ return strcmp(name()->c_str(), _name);
}
const flatbuffers::Vector<uint8_t> *inventory() const {
return GetPointer<const flatbuffers::Vector<uint8_t> *>(VT_INVENTORY);
@@ -1378,7 +1369,7 @@
MyGame::Example::Color color() const {
return static_cast<MyGame::Example::Color>(GetField<uint8_t>(VT_COLOR, 8));
}
- bool mutate_color(MyGame::Example::Color _color) {
+ bool mutate_color(MyGame::Example::Color _color = static_cast<MyGame::Example::Color>(8)) {
return SetField<uint8_t>(VT_COLOR, static_cast<uint8_t>(_color), 8);
}
MyGame::Example::Any test_type() const {
@@ -1444,55 +1435,55 @@
bool testbool() const {
return GetField<uint8_t>(VT_TESTBOOL, 0) != 0;
}
- bool mutate_testbool(bool _testbool) {
+ bool mutate_testbool(bool _testbool = 0) {
return SetField<uint8_t>(VT_TESTBOOL, static_cast<uint8_t>(_testbool), 0);
}
int32_t testhashs32_fnv1() const {
return GetField<int32_t>(VT_TESTHASHS32_FNV1, 0);
}
- bool mutate_testhashs32_fnv1(int32_t _testhashs32_fnv1) {
+ bool mutate_testhashs32_fnv1(int32_t _testhashs32_fnv1 = 0) {
return SetField<int32_t>(VT_TESTHASHS32_FNV1, _testhashs32_fnv1, 0);
}
uint32_t testhashu32_fnv1() const {
return GetField<uint32_t>(VT_TESTHASHU32_FNV1, 0);
}
- bool mutate_testhashu32_fnv1(uint32_t _testhashu32_fnv1) {
+ bool mutate_testhashu32_fnv1(uint32_t _testhashu32_fnv1 = 0) {
return SetField<uint32_t>(VT_TESTHASHU32_FNV1, _testhashu32_fnv1, 0);
}
int64_t testhashs64_fnv1() const {
return GetField<int64_t>(VT_TESTHASHS64_FNV1, 0);
}
- bool mutate_testhashs64_fnv1(int64_t _testhashs64_fnv1) {
+ bool mutate_testhashs64_fnv1(int64_t _testhashs64_fnv1 = 0) {
return SetField<int64_t>(VT_TESTHASHS64_FNV1, _testhashs64_fnv1, 0);
}
uint64_t testhashu64_fnv1() const {
return GetField<uint64_t>(VT_TESTHASHU64_FNV1, 0);
}
- bool mutate_testhashu64_fnv1(uint64_t _testhashu64_fnv1) {
+ bool mutate_testhashu64_fnv1(uint64_t _testhashu64_fnv1 = 0) {
return SetField<uint64_t>(VT_TESTHASHU64_FNV1, _testhashu64_fnv1, 0);
}
int32_t testhashs32_fnv1a() const {
return GetField<int32_t>(VT_TESTHASHS32_FNV1A, 0);
}
- bool mutate_testhashs32_fnv1a(int32_t _testhashs32_fnv1a) {
+ bool mutate_testhashs32_fnv1a(int32_t _testhashs32_fnv1a = 0) {
return SetField<int32_t>(VT_TESTHASHS32_FNV1A, _testhashs32_fnv1a, 0);
}
uint32_t testhashu32_fnv1a() const {
return GetField<uint32_t>(VT_TESTHASHU32_FNV1A, 0);
}
- bool mutate_testhashu32_fnv1a(uint32_t _testhashu32_fnv1a) {
+ bool mutate_testhashu32_fnv1a(uint32_t _testhashu32_fnv1a = 0) {
return SetField<uint32_t>(VT_TESTHASHU32_FNV1A, _testhashu32_fnv1a, 0);
}
int64_t testhashs64_fnv1a() const {
return GetField<int64_t>(VT_TESTHASHS64_FNV1A, 0);
}
- bool mutate_testhashs64_fnv1a(int64_t _testhashs64_fnv1a) {
+ bool mutate_testhashs64_fnv1a(int64_t _testhashs64_fnv1a = 0) {
return SetField<int64_t>(VT_TESTHASHS64_FNV1A, _testhashs64_fnv1a, 0);
}
uint64_t testhashu64_fnv1a() const {
return GetField<uint64_t>(VT_TESTHASHU64_FNV1A, 0);
}
- bool mutate_testhashu64_fnv1a(uint64_t _testhashu64_fnv1a) {
+ bool mutate_testhashu64_fnv1a(uint64_t _testhashu64_fnv1a = 0) {
return SetField<uint64_t>(VT_TESTHASHU64_FNV1A, _testhashu64_fnv1a, 0);
}
const flatbuffers::Vector<uint8_t> *testarrayofbools() const {
@@ -1504,19 +1495,19 @@
float testf() const {
return GetField<float>(VT_TESTF, 3.14159f);
}
- bool mutate_testf(float _testf) {
+ bool mutate_testf(float _testf = 3.14159f) {
return SetField<float>(VT_TESTF, _testf, 3.14159f);
}
float testf2() const {
return GetField<float>(VT_TESTF2, 3.0f);
}
- bool mutate_testf2(float _testf2) {
+ bool mutate_testf2(float _testf2 = 3.0f) {
return SetField<float>(VT_TESTF2, _testf2, 3.0f);
}
float testf3() const {
return GetField<float>(VT_TESTF3, 0.0f);
}
- bool mutate_testf3(float _testf3) {
+ bool mutate_testf3(float _testf3 = 0.0f) {
return SetField<float>(VT_TESTF3, _testf3, 0.0f);
}
const flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>> *testarrayofstring2() const {
@@ -1573,7 +1564,7 @@
uint64_t single_weak_reference() const {
return GetField<uint64_t>(VT_SINGLE_WEAK_REFERENCE, 0);
}
- bool mutate_single_weak_reference(uint64_t _single_weak_reference) {
+ bool mutate_single_weak_reference(uint64_t _single_weak_reference = 0) {
return SetField<uint64_t>(VT_SINGLE_WEAK_REFERENCE, _single_weak_reference, 0);
}
const flatbuffers::Vector<uint64_t> *vector_of_weak_references() const {
@@ -1591,7 +1582,7 @@
uint64_t co_owning_reference() const {
return GetField<uint64_t>(VT_CO_OWNING_REFERENCE, 0);
}
- bool mutate_co_owning_reference(uint64_t _co_owning_reference) {
+ bool mutate_co_owning_reference(uint64_t _co_owning_reference = 0) {
return SetField<uint64_t>(VT_CO_OWNING_REFERENCE, _co_owning_reference, 0);
}
const flatbuffers::Vector<uint64_t> *vector_of_co_owning_references() const {
@@ -1603,7 +1594,7 @@
uint64_t non_owning_reference() const {
return GetField<uint64_t>(VT_NON_OWNING_REFERENCE, 0);
}
- bool mutate_non_owning_reference(uint64_t _non_owning_reference) {
+ bool mutate_non_owning_reference(uint64_t _non_owning_reference = 0) {
return SetField<uint64_t>(VT_NON_OWNING_REFERENCE, _non_owning_reference, 0);
}
const flatbuffers::Vector<uint64_t> *vector_of_non_owning_references() const {
@@ -1658,7 +1649,7 @@
MyGame::Example::Race signed_enum() const {
return static_cast<MyGame::Example::Race>(GetField<int8_t>(VT_SIGNED_ENUM, -1));
}
- bool mutate_signed_enum(MyGame::Example::Race _signed_enum) {
+ bool mutate_signed_enum(MyGame::Example::Race _signed_enum = static_cast<MyGame::Example::Race>(-1)) {
return SetField<int8_t>(VT_SIGNED_ENUM, static_cast<int8_t>(_signed_enum), -1);
}
const flatbuffers::Vector<uint8_t> *testrequirednestedflatbuffer() const {
@@ -1670,17 +1661,41 @@
const MyGame::Example::Monster *testrequirednestedflatbuffer_nested_root() const {
return flatbuffers::GetRoot<MyGame::Example::Monster>(testrequirednestedflatbuffer()->Data());
}
+ const flatbuffers::Vector<flatbuffers::Offset<MyGame::Example::Stat>> *scalar_key_sorted_tables() const {
+ return GetPointer<const flatbuffers::Vector<flatbuffers::Offset<MyGame::Example::Stat>> *>(VT_SCALAR_KEY_SORTED_TABLES);
+ }
+ flatbuffers::Vector<flatbuffers::Offset<MyGame::Example::Stat>> *mutable_scalar_key_sorted_tables() {
+ return GetPointer<flatbuffers::Vector<flatbuffers::Offset<MyGame::Example::Stat>> *>(VT_SCALAR_KEY_SORTED_TABLES);
+ }
+ const MyGame::Example::Test *native_inline() const {
+ return GetStruct<const MyGame::Example::Test *>(VT_NATIVE_INLINE);
+ }
+ MyGame::Example::Test *mutable_native_inline() {
+ return GetStruct<MyGame::Example::Test *>(VT_NATIVE_INLINE);
+ }
+ MyGame::Example::LongEnum long_enum_non_enum_default() const {
+ return static_cast<MyGame::Example::LongEnum>(GetField<uint64_t>(VT_LONG_ENUM_NON_ENUM_DEFAULT, 0));
+ }
+ bool mutate_long_enum_non_enum_default(MyGame::Example::LongEnum _long_enum_non_enum_default = static_cast<MyGame::Example::LongEnum>(0)) {
+ return SetField<uint64_t>(VT_LONG_ENUM_NON_ENUM_DEFAULT, static_cast<uint64_t>(_long_enum_non_enum_default), 0);
+ }
+ MyGame::Example::LongEnum long_enum_normal_default() const {
+ return static_cast<MyGame::Example::LongEnum>(GetField<uint64_t>(VT_LONG_ENUM_NORMAL_DEFAULT, 2ULL));
+ }
+ bool mutate_long_enum_normal_default(MyGame::Example::LongEnum _long_enum_normal_default = static_cast<MyGame::Example::LongEnum>(2ULL)) {
+ return SetField<uint64_t>(VT_LONG_ENUM_NORMAL_DEFAULT, static_cast<uint64_t>(_long_enum_normal_default), 2ULL);
+ }
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
- VerifyField<MyGame::Example::Vec3>(verifier, VT_POS) &&
- VerifyField<int16_t>(verifier, VT_MANA) &&
- VerifyField<int16_t>(verifier, VT_HP) &&
+ VerifyField<MyGame::Example::Vec3>(verifier, VT_POS, 8) &&
+ VerifyField<int16_t>(verifier, VT_MANA, 2) &&
+ VerifyField<int16_t>(verifier, VT_HP, 2) &&
VerifyOffsetRequired(verifier, VT_NAME) &&
verifier.VerifyString(name()) &&
VerifyOffset(verifier, VT_INVENTORY) &&
verifier.VerifyVector(inventory()) &&
- VerifyField<uint8_t>(verifier, VT_COLOR) &&
- VerifyField<uint8_t>(verifier, VT_TEST_TYPE) &&
+ VerifyField<uint8_t>(verifier, VT_COLOR, 1) &&
+ VerifyField<uint8_t>(verifier, VT_TEST_TYPE, 1) &&
VerifyOffset(verifier, VT_TEST) &&
VerifyAny(verifier, test(), test_type()) &&
VerifyOffset(verifier, VT_TEST4) &&
@@ -1695,22 +1710,23 @@
verifier.VerifyTable(enemy()) &&
VerifyOffset(verifier, VT_TESTNESTEDFLATBUFFER) &&
verifier.VerifyVector(testnestedflatbuffer()) &&
+ verifier.VerifyNestedFlatBuffer<MyGame::Example::Monster>(testnestedflatbuffer(), nullptr) &&
VerifyOffset(verifier, VT_TESTEMPTY) &&
verifier.VerifyTable(testempty()) &&
- VerifyField<uint8_t>(verifier, VT_TESTBOOL) &&
- VerifyField<int32_t>(verifier, VT_TESTHASHS32_FNV1) &&
- VerifyField<uint32_t>(verifier, VT_TESTHASHU32_FNV1) &&
- VerifyField<int64_t>(verifier, VT_TESTHASHS64_FNV1) &&
- VerifyField<uint64_t>(verifier, VT_TESTHASHU64_FNV1) &&
- VerifyField<int32_t>(verifier, VT_TESTHASHS32_FNV1A) &&
- VerifyField<uint32_t>(verifier, VT_TESTHASHU32_FNV1A) &&
- VerifyField<int64_t>(verifier, VT_TESTHASHS64_FNV1A) &&
- VerifyField<uint64_t>(verifier, VT_TESTHASHU64_FNV1A) &&
+ VerifyField<uint8_t>(verifier, VT_TESTBOOL, 1) &&
+ VerifyField<int32_t>(verifier, VT_TESTHASHS32_FNV1, 4) &&
+ VerifyField<uint32_t>(verifier, VT_TESTHASHU32_FNV1, 4) &&
+ VerifyField<int64_t>(verifier, VT_TESTHASHS64_FNV1, 8) &&
+ VerifyField<uint64_t>(verifier, VT_TESTHASHU64_FNV1, 8) &&
+ VerifyField<int32_t>(verifier, VT_TESTHASHS32_FNV1A, 4) &&
+ VerifyField<uint32_t>(verifier, VT_TESTHASHU32_FNV1A, 4) &&
+ VerifyField<int64_t>(verifier, VT_TESTHASHS64_FNV1A, 8) &&
+ VerifyField<uint64_t>(verifier, VT_TESTHASHU64_FNV1A, 8) &&
VerifyOffset(verifier, VT_TESTARRAYOFBOOLS) &&
verifier.VerifyVector(testarrayofbools()) &&
- VerifyField<float>(verifier, VT_TESTF) &&
- VerifyField<float>(verifier, VT_TESTF2) &&
- VerifyField<float>(verifier, VT_TESTF3) &&
+ VerifyField<float>(verifier, VT_TESTF, 4) &&
+ VerifyField<float>(verifier, VT_TESTF2, 4) &&
+ VerifyField<float>(verifier, VT_TESTF3, 4) &&
VerifyOffset(verifier, VT_TESTARRAYOFSTRING2) &&
verifier.VerifyVector(testarrayofstring2()) &&
verifier.VerifyVectorOfStrings(testarrayofstring2()) &&
@@ -1718,6 +1734,7 @@
verifier.VerifyVector(testarrayofsortedstruct()) &&
VerifyOffset(verifier, VT_FLEX) &&
verifier.VerifyVector(flex()) &&
+ flexbuffers::VerifyNestedFlexBuffer(flex(), verifier) &&
VerifyOffset(verifier, VT_TEST5) &&
verifier.VerifyVector(test5()) &&
VerifyOffset(verifier, VT_VECTOR_OF_LONGS) &&
@@ -1729,29 +1746,36 @@
VerifyOffset(verifier, VT_VECTOR_OF_REFERRABLES) &&
verifier.VerifyVector(vector_of_referrables()) &&
verifier.VerifyVectorOfTables(vector_of_referrables()) &&
- VerifyField<uint64_t>(verifier, VT_SINGLE_WEAK_REFERENCE) &&
+ VerifyField<uint64_t>(verifier, VT_SINGLE_WEAK_REFERENCE, 8) &&
VerifyOffset(verifier, VT_VECTOR_OF_WEAK_REFERENCES) &&
verifier.VerifyVector(vector_of_weak_references()) &&
VerifyOffset(verifier, VT_VECTOR_OF_STRONG_REFERRABLES) &&
verifier.VerifyVector(vector_of_strong_referrables()) &&
verifier.VerifyVectorOfTables(vector_of_strong_referrables()) &&
- VerifyField<uint64_t>(verifier, VT_CO_OWNING_REFERENCE) &&
+ VerifyField<uint64_t>(verifier, VT_CO_OWNING_REFERENCE, 8) &&
VerifyOffset(verifier, VT_VECTOR_OF_CO_OWNING_REFERENCES) &&
verifier.VerifyVector(vector_of_co_owning_references()) &&
- VerifyField<uint64_t>(verifier, VT_NON_OWNING_REFERENCE) &&
+ VerifyField<uint64_t>(verifier, VT_NON_OWNING_REFERENCE, 8) &&
VerifyOffset(verifier, VT_VECTOR_OF_NON_OWNING_REFERENCES) &&
verifier.VerifyVector(vector_of_non_owning_references()) &&
- VerifyField<uint8_t>(verifier, VT_ANY_UNIQUE_TYPE) &&
+ VerifyField<uint8_t>(verifier, VT_ANY_UNIQUE_TYPE, 1) &&
VerifyOffset(verifier, VT_ANY_UNIQUE) &&
VerifyAnyUniqueAliases(verifier, any_unique(), any_unique_type()) &&
- VerifyField<uint8_t>(verifier, VT_ANY_AMBIGUOUS_TYPE) &&
+ VerifyField<uint8_t>(verifier, VT_ANY_AMBIGUOUS_TYPE, 1) &&
VerifyOffset(verifier, VT_ANY_AMBIGUOUS) &&
VerifyAnyAmbiguousAliases(verifier, any_ambiguous(), any_ambiguous_type()) &&
VerifyOffset(verifier, VT_VECTOR_OF_ENUMS) &&
verifier.VerifyVector(vector_of_enums()) &&
- VerifyField<int8_t>(verifier, VT_SIGNED_ENUM) &&
+ VerifyField<int8_t>(verifier, VT_SIGNED_ENUM, 1) &&
VerifyOffset(verifier, VT_TESTREQUIREDNESTEDFLATBUFFER) &&
verifier.VerifyVector(testrequirednestedflatbuffer()) &&
+ verifier.VerifyNestedFlatBuffer<MyGame::Example::Monster>(testrequirednestedflatbuffer(), nullptr) &&
+ VerifyOffset(verifier, VT_SCALAR_KEY_SORTED_TABLES) &&
+ verifier.VerifyVector(scalar_key_sorted_tables()) &&
+ verifier.VerifyVectorOfTables(scalar_key_sorted_tables()) &&
+ VerifyField<MyGame::Example::Test>(verifier, VT_NATIVE_INLINE, 2) &&
+ VerifyField<uint64_t>(verifier, VT_LONG_ENUM_NON_ENUM_DEFAULT, 8) &&
+ VerifyField<uint64_t>(verifier, VT_LONG_ENUM_NORMAL_DEFAULT, 8) &&
verifier.EndTable();
}
MonsterT *UnPack(const flatbuffers::resolver_function_t *_resolver = nullptr) const;
@@ -1934,6 +1958,18 @@
void add_testrequirednestedflatbuffer(flatbuffers::Offset<flatbuffers::Vector<uint8_t>> testrequirednestedflatbuffer) {
fbb_.AddOffset(Monster::VT_TESTREQUIREDNESTEDFLATBUFFER, testrequirednestedflatbuffer);
}
+ void add_scalar_key_sorted_tables(flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<MyGame::Example::Stat>>> scalar_key_sorted_tables) {
+ fbb_.AddOffset(Monster::VT_SCALAR_KEY_SORTED_TABLES, scalar_key_sorted_tables);
+ }
+ void add_native_inline(const MyGame::Example::Test *native_inline) {
+ fbb_.AddStruct(Monster::VT_NATIVE_INLINE, native_inline);
+ }
+ void add_long_enum_non_enum_default(MyGame::Example::LongEnum long_enum_non_enum_default) {
+ fbb_.AddElement<uint64_t>(Monster::VT_LONG_ENUM_NON_ENUM_DEFAULT, static_cast<uint64_t>(long_enum_non_enum_default), 0);
+ }
+ void add_long_enum_normal_default(MyGame::Example::LongEnum long_enum_normal_default) {
+ fbb_.AddElement<uint64_t>(Monster::VT_LONG_ENUM_NORMAL_DEFAULT, static_cast<uint64_t>(long_enum_normal_default), 2ULL);
+ }
explicit MonsterBuilder(flatbuffers::FlatBufferBuilder &_fbb)
: fbb_(_fbb) {
start_ = fbb_.StartTable();
@@ -1948,7 +1984,7 @@
inline flatbuffers::Offset<Monster> CreateMonster(
flatbuffers::FlatBufferBuilder &_fbb,
- const MyGame::Example::Vec3 *pos = 0,
+ const MyGame::Example::Vec3 *pos = nullptr,
int16_t mana = 150,
int16_t hp = 100,
flatbuffers::Offset<flatbuffers::String> name = 0,
@@ -1996,8 +2032,14 @@
flatbuffers::Offset<void> any_ambiguous = 0,
flatbuffers::Offset<flatbuffers::Vector<uint8_t>> vector_of_enums = 0,
MyGame::Example::Race signed_enum = MyGame::Example::Race_None,
- flatbuffers::Offset<flatbuffers::Vector<uint8_t>> testrequirednestedflatbuffer = 0) {
+ flatbuffers::Offset<flatbuffers::Vector<uint8_t>> testrequirednestedflatbuffer = 0,
+ flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<MyGame::Example::Stat>>> scalar_key_sorted_tables = 0,
+ const MyGame::Example::Test *native_inline = nullptr,
+ MyGame::Example::LongEnum long_enum_non_enum_default = static_cast<MyGame::Example::LongEnum>(0),
+ MyGame::Example::LongEnum long_enum_normal_default = MyGame::Example::LongEnum_LongOne) {
MonsterBuilder builder_(_fbb);
+ builder_.add_long_enum_normal_default(long_enum_normal_default);
+ builder_.add_long_enum_non_enum_default(long_enum_non_enum_default);
builder_.add_non_owning_reference(non_owning_reference);
builder_.add_co_owning_reference(co_owning_reference);
builder_.add_single_weak_reference(single_weak_reference);
@@ -2005,6 +2047,8 @@
builder_.add_testhashs64_fnv1a(testhashs64_fnv1a);
builder_.add_testhashu64_fnv1(testhashu64_fnv1);
builder_.add_testhashs64_fnv1(testhashs64_fnv1);
+ builder_.add_native_inline(native_inline);
+ builder_.add_scalar_key_sorted_tables(scalar_key_sorted_tables);
builder_.add_testrequirednestedflatbuffer(testrequirednestedflatbuffer);
builder_.add_vector_of_enums(vector_of_enums);
builder_.add_any_ambiguous(any_ambiguous);
@@ -2052,7 +2096,7 @@
inline flatbuffers::Offset<Monster> CreateMonsterDirect(
flatbuffers::FlatBufferBuilder &_fbb,
- const MyGame::Example::Vec3 *pos = 0,
+ const MyGame::Example::Vec3 *pos = nullptr,
int16_t mana = 150,
int16_t hp = 100,
const char *name = nullptr,
@@ -2100,7 +2144,11 @@
flatbuffers::Offset<void> any_ambiguous = 0,
const std::vector<uint8_t> *vector_of_enums = nullptr,
MyGame::Example::Race signed_enum = MyGame::Example::Race_None,
- const std::vector<uint8_t> *testrequirednestedflatbuffer = nullptr) {
+ const std::vector<uint8_t> *testrequirednestedflatbuffer = nullptr,
+ std::vector<flatbuffers::Offset<MyGame::Example::Stat>> *scalar_key_sorted_tables = nullptr,
+ const MyGame::Example::Test *native_inline = nullptr,
+ MyGame::Example::LongEnum long_enum_non_enum_default = static_cast<MyGame::Example::LongEnum>(0),
+ MyGame::Example::LongEnum long_enum_normal_default = MyGame::Example::LongEnum_LongOne) {
auto name__ = name ? _fbb.CreateString(name) : 0;
auto inventory__ = inventory ? _fbb.CreateVector<uint8_t>(*inventory) : 0;
auto test4__ = test4 ? _fbb.CreateVectorOfStructs<MyGame::Example::Test>(*test4) : 0;
@@ -2121,6 +2169,7 @@
auto vector_of_non_owning_references__ = vector_of_non_owning_references ? _fbb.CreateVector<uint64_t>(*vector_of_non_owning_references) : 0;
auto vector_of_enums__ = vector_of_enums ? _fbb.CreateVector<uint8_t>(*vector_of_enums) : 0;
auto testrequirednestedflatbuffer__ = testrequirednestedflatbuffer ? _fbb.CreateVector<uint8_t>(*testrequirednestedflatbuffer) : 0;
+ auto scalar_key_sorted_tables__ = scalar_key_sorted_tables ? _fbb.CreateVectorOfSortedTables<MyGame::Example::Stat>(scalar_key_sorted_tables) : 0;
return MyGame::Example::CreateMonster(
_fbb,
pos,
@@ -2171,60 +2220,31 @@
any_ambiguous,
vector_of_enums__,
signed_enum,
- testrequirednestedflatbuffer__);
+ testrequirednestedflatbuffer__,
+ scalar_key_sorted_tables__,
+ native_inline,
+ long_enum_non_enum_default,
+ long_enum_normal_default);
}
flatbuffers::Offset<Monster> CreateMonster(flatbuffers::FlatBufferBuilder &_fbb, const MonsterT *_o, const flatbuffers::rehasher_function_t *_rehasher = nullptr);
struct TypeAliasesT : public flatbuffers::NativeTable {
typedef TypeAliases TableType;
- int8_t i8;
- uint8_t u8;
- int16_t i16;
- uint16_t u16;
- int32_t i32;
- uint32_t u32;
- int64_t i64;
- uint64_t u64;
- float f32;
- double f64;
- std::vector<int8_t> v8;
- std::vector<double> vf64;
- TypeAliasesT()
- : i8(0),
- u8(0),
- i16(0),
- u16(0),
- i32(0),
- u32(0),
- i64(0),
- u64(0),
- f32(0.0f),
- f64(0.0) {
- }
+ int8_t i8 = 0;
+ uint8_t u8 = 0;
+ int16_t i16 = 0;
+ uint16_t u16 = 0;
+ int32_t i32 = 0;
+ uint32_t u32 = 0;
+ int64_t i64 = 0;
+ uint64_t u64 = 0;
+ float f32 = 0.0f;
+ double f64 = 0.0;
+ std::vector<int8_t> v8{};
+ std::vector<double> vf64{};
};
-inline bool operator==(const TypeAliasesT &lhs, const TypeAliasesT &rhs) {
- return
- (lhs.i8 == rhs.i8) &&
- (lhs.u8 == rhs.u8) &&
- (lhs.i16 == rhs.i16) &&
- (lhs.u16 == rhs.u16) &&
- (lhs.i32 == rhs.i32) &&
- (lhs.u32 == rhs.u32) &&
- (lhs.i64 == rhs.i64) &&
- (lhs.u64 == rhs.u64) &&
- (lhs.f32 == rhs.f32) &&
- (lhs.f64 == rhs.f64) &&
- (lhs.v8 == rhs.v8) &&
- (lhs.vf64 == rhs.vf64);
-}
-
-inline bool operator!=(const TypeAliasesT &lhs, const TypeAliasesT &rhs) {
- return !(lhs == rhs);
-}
-
-
struct TypeAliases FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
typedef TypeAliasesT NativeTableType;
typedef TypeAliasesBuilder Builder;
@@ -2248,61 +2268,61 @@
int8_t i8() const {
return GetField<int8_t>(VT_I8, 0);
}
- bool mutate_i8(int8_t _i8) {
+ bool mutate_i8(int8_t _i8 = 0) {
return SetField<int8_t>(VT_I8, _i8, 0);
}
uint8_t u8() const {
return GetField<uint8_t>(VT_U8, 0);
}
- bool mutate_u8(uint8_t _u8) {
+ bool mutate_u8(uint8_t _u8 = 0) {
return SetField<uint8_t>(VT_U8, _u8, 0);
}
int16_t i16() const {
return GetField<int16_t>(VT_I16, 0);
}
- bool mutate_i16(int16_t _i16) {
+ bool mutate_i16(int16_t _i16 = 0) {
return SetField<int16_t>(VT_I16, _i16, 0);
}
uint16_t u16() const {
return GetField<uint16_t>(VT_U16, 0);
}
- bool mutate_u16(uint16_t _u16) {
+ bool mutate_u16(uint16_t _u16 = 0) {
return SetField<uint16_t>(VT_U16, _u16, 0);
}
int32_t i32() const {
return GetField<int32_t>(VT_I32, 0);
}
- bool mutate_i32(int32_t _i32) {
+ bool mutate_i32(int32_t _i32 = 0) {
return SetField<int32_t>(VT_I32, _i32, 0);
}
uint32_t u32() const {
return GetField<uint32_t>(VT_U32, 0);
}
- bool mutate_u32(uint32_t _u32) {
+ bool mutate_u32(uint32_t _u32 = 0) {
return SetField<uint32_t>(VT_U32, _u32, 0);
}
int64_t i64() const {
return GetField<int64_t>(VT_I64, 0);
}
- bool mutate_i64(int64_t _i64) {
+ bool mutate_i64(int64_t _i64 = 0) {
return SetField<int64_t>(VT_I64, _i64, 0);
}
uint64_t u64() const {
return GetField<uint64_t>(VT_U64, 0);
}
- bool mutate_u64(uint64_t _u64) {
+ bool mutate_u64(uint64_t _u64 = 0) {
return SetField<uint64_t>(VT_U64, _u64, 0);
}
float f32() const {
return GetField<float>(VT_F32, 0.0f);
}
- bool mutate_f32(float _f32) {
+ bool mutate_f32(float _f32 = 0.0f) {
return SetField<float>(VT_F32, _f32, 0.0f);
}
double f64() const {
return GetField<double>(VT_F64, 0.0);
}
- bool mutate_f64(double _f64) {
+ bool mutate_f64(double _f64 = 0.0) {
return SetField<double>(VT_F64, _f64, 0.0);
}
const flatbuffers::Vector<int8_t> *v8() const {
@@ -2319,16 +2339,16 @@
}
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
- VerifyField<int8_t>(verifier, VT_I8) &&
- VerifyField<uint8_t>(verifier, VT_U8) &&
- VerifyField<int16_t>(verifier, VT_I16) &&
- VerifyField<uint16_t>(verifier, VT_U16) &&
- VerifyField<int32_t>(verifier, VT_I32) &&
- VerifyField<uint32_t>(verifier, VT_U32) &&
- VerifyField<int64_t>(verifier, VT_I64) &&
- VerifyField<uint64_t>(verifier, VT_U64) &&
- VerifyField<float>(verifier, VT_F32) &&
- VerifyField<double>(verifier, VT_F64) &&
+ VerifyField<int8_t>(verifier, VT_I8, 1) &&
+ VerifyField<uint8_t>(verifier, VT_U8, 1) &&
+ VerifyField<int16_t>(verifier, VT_I16, 2) &&
+ VerifyField<uint16_t>(verifier, VT_U16, 2) &&
+ VerifyField<int32_t>(verifier, VT_I32, 4) &&
+ VerifyField<uint32_t>(verifier, VT_U32, 4) &&
+ VerifyField<int64_t>(verifier, VT_I64, 8) &&
+ VerifyField<uint64_t>(verifier, VT_U64, 8) &&
+ VerifyField<float>(verifier, VT_F32, 4) &&
+ VerifyField<double>(verifier, VT_F64, 8) &&
VerifyOffset(verifier, VT_V8) &&
verifier.VerifyVector(v8()) &&
VerifyOffset(verifier, VT_VF64) &&
@@ -2457,8 +2477,18 @@
} // namespace Example
+
+inline bool operator==(const InParentNamespaceT &, const InParentNamespaceT &) {
+ return true;
+}
+
+inline bool operator!=(const InParentNamespaceT &lhs, const InParentNamespaceT &rhs) {
+ return !(lhs == rhs);
+}
+
+
inline InParentNamespaceT *InParentNamespace::UnPack(const flatbuffers::resolver_function_t *_resolver) const {
- flatbuffers::unique_ptr<MyGame::InParentNamespaceT> _o = flatbuffers::unique_ptr<MyGame::InParentNamespaceT>(new InParentNamespaceT());
+ auto _o = std::unique_ptr<InParentNamespaceT>(new InParentNamespaceT());
UnPackTo(_o.get(), _resolver);
return _o.release();
}
@@ -2482,8 +2512,18 @@
namespace Example2 {
+
+inline bool operator==(const MonsterT &, const MonsterT &) {
+ return true;
+}
+
+inline bool operator!=(const MonsterT &lhs, const MonsterT &rhs) {
+ return !(lhs == rhs);
+}
+
+
inline MonsterT *Monster::UnPack(const flatbuffers::resolver_function_t *_resolver) const {
- flatbuffers::unique_ptr<MyGame::Example2::MonsterT> _o = flatbuffers::unique_ptr<MyGame::Example2::MonsterT>(new MonsterT());
+ auto _o = std::unique_ptr<MonsterT>(new MonsterT());
UnPackTo(_o.get(), _resolver);
return _o.release();
}
@@ -2509,8 +2549,19 @@
namespace Example {
+
+inline bool operator==(const TestSimpleTableWithEnumT &lhs, const TestSimpleTableWithEnumT &rhs) {
+ return
+ (lhs.color == rhs.color);
+}
+
+inline bool operator!=(const TestSimpleTableWithEnumT &lhs, const TestSimpleTableWithEnumT &rhs) {
+ return !(lhs == rhs);
+}
+
+
inline TestSimpleTableWithEnumT *TestSimpleTableWithEnum::UnPack(const flatbuffers::resolver_function_t *_resolver) const {
- flatbuffers::unique_ptr<MyGame::Example::TestSimpleTableWithEnumT> _o = flatbuffers::unique_ptr<MyGame::Example::TestSimpleTableWithEnumT>(new TestSimpleTableWithEnumT());
+ auto _o = std::unique_ptr<TestSimpleTableWithEnumT>(new TestSimpleTableWithEnumT());
UnPackTo(_o.get(), _resolver);
return _o.release();
}
@@ -2535,8 +2586,21 @@
_color);
}
+
+inline bool operator==(const StatT &lhs, const StatT &rhs) {
+ return
+ (lhs.id == rhs.id) &&
+ (lhs.val == rhs.val) &&
+ (lhs.count == rhs.count);
+}
+
+inline bool operator!=(const StatT &lhs, const StatT &rhs) {
+ return !(lhs == rhs);
+}
+
+
inline StatT *Stat::UnPack(const flatbuffers::resolver_function_t *_resolver) const {
- flatbuffers::unique_ptr<MyGame::Example::StatT> _o = flatbuffers::unique_ptr<MyGame::Example::StatT>(new StatT());
+ auto _o = std::unique_ptr<StatT>(new StatT());
UnPackTo(_o.get(), _resolver);
return _o.release();
}
@@ -2567,8 +2631,19 @@
_count);
}
+
+inline bool operator==(const ReferrableT &lhs, const ReferrableT &rhs) {
+ return
+ (lhs.id == rhs.id);
+}
+
+inline bool operator!=(const ReferrableT &lhs, const ReferrableT &rhs) {
+ return !(lhs == rhs);
+}
+
+
inline ReferrableT *Referrable::UnPack(const flatbuffers::resolver_function_t *_resolver) const {
- flatbuffers::unique_ptr<MyGame::Example::ReferrableT> _o = flatbuffers::unique_ptr<MyGame::Example::ReferrableT>(new ReferrableT());
+ auto _o = std::unique_ptr<ReferrableT>(new ReferrableT());
UnPackTo(_o.get(), _resolver);
return _o.release();
}
@@ -2593,8 +2668,180 @@
_id);
}
+
+inline bool operator==(const MonsterT &lhs, const MonsterT &rhs) {
+ return
+ ((lhs.pos == rhs.pos) || (lhs.pos && rhs.pos && *lhs.pos == *rhs.pos)) &&
+ (lhs.mana == rhs.mana) &&
+ (lhs.hp == rhs.hp) &&
+ (lhs.name == rhs.name) &&
+ (lhs.inventory == rhs.inventory) &&
+ (lhs.color == rhs.color) &&
+ (lhs.test == rhs.test) &&
+ (lhs.test4 == rhs.test4) &&
+ (lhs.testarrayofstring == rhs.testarrayofstring) &&
+ (lhs.testarrayoftables == rhs.testarrayoftables) &&
+ ((lhs.enemy == rhs.enemy) || (lhs.enemy && rhs.enemy && *lhs.enemy == *rhs.enemy)) &&
+ (lhs.testnestedflatbuffer == rhs.testnestedflatbuffer) &&
+ ((lhs.testempty == rhs.testempty) || (lhs.testempty && rhs.testempty && *lhs.testempty == *rhs.testempty)) &&
+ (lhs.testbool == rhs.testbool) &&
+ (lhs.testhashs32_fnv1 == rhs.testhashs32_fnv1) &&
+ (lhs.testhashu32_fnv1 == rhs.testhashu32_fnv1) &&
+ (lhs.testhashs64_fnv1 == rhs.testhashs64_fnv1) &&
+ (lhs.testhashu64_fnv1 == rhs.testhashu64_fnv1) &&
+ (lhs.testhashs32_fnv1a == rhs.testhashs32_fnv1a) &&
+ (lhs.testhashu32_fnv1a == rhs.testhashu32_fnv1a) &&
+ (lhs.testhashs64_fnv1a == rhs.testhashs64_fnv1a) &&
+ (lhs.testhashu64_fnv1a == rhs.testhashu64_fnv1a) &&
+ (lhs.testarrayofbools == rhs.testarrayofbools) &&
+ (lhs.testf == rhs.testf) &&
+ (lhs.testf2 == rhs.testf2) &&
+ (lhs.testf3 == rhs.testf3) &&
+ (lhs.testarrayofstring2 == rhs.testarrayofstring2) &&
+ (lhs.testarrayofsortedstruct == rhs.testarrayofsortedstruct) &&
+ (lhs.flex == rhs.flex) &&
+ (lhs.test5 == rhs.test5) &&
+ (lhs.vector_of_longs == rhs.vector_of_longs) &&
+ (lhs.vector_of_doubles == rhs.vector_of_doubles) &&
+ ((lhs.parent_namespace_test == rhs.parent_namespace_test) || (lhs.parent_namespace_test && rhs.parent_namespace_test && *lhs.parent_namespace_test == *rhs.parent_namespace_test)) &&
+ (lhs.vector_of_referrables == rhs.vector_of_referrables) &&
+ (lhs.single_weak_reference == rhs.single_weak_reference) &&
+ (lhs.vector_of_weak_references == rhs.vector_of_weak_references) &&
+ (lhs.vector_of_strong_referrables == rhs.vector_of_strong_referrables) &&
+ (lhs.co_owning_reference == rhs.co_owning_reference) &&
+ (lhs.vector_of_co_owning_references == rhs.vector_of_co_owning_references) &&
+ (lhs.non_owning_reference == rhs.non_owning_reference) &&
+ (lhs.vector_of_non_owning_references == rhs.vector_of_non_owning_references) &&
+ (lhs.any_unique == rhs.any_unique) &&
+ (lhs.any_ambiguous == rhs.any_ambiguous) &&
+ (lhs.vector_of_enums == rhs.vector_of_enums) &&
+ (lhs.signed_enum == rhs.signed_enum) &&
+ (lhs.testrequirednestedflatbuffer == rhs.testrequirednestedflatbuffer) &&
+ (lhs.scalar_key_sorted_tables == rhs.scalar_key_sorted_tables) &&
+ (lhs.native_inline == rhs.native_inline) &&
+ (lhs.long_enum_non_enum_default == rhs.long_enum_non_enum_default) &&
+ (lhs.long_enum_normal_default == rhs.long_enum_normal_default);
+}
+
+inline bool operator!=(const MonsterT &lhs, const MonsterT &rhs) {
+ return !(lhs == rhs);
+}
+
+
+inline MonsterT::MonsterT(const MonsterT &o)
+ : pos((o.pos) ? new MyGame::Example::Vec3(*o.pos) : nullptr),
+ mana(o.mana),
+ hp(o.hp),
+ name(o.name),
+ inventory(o.inventory),
+ color(o.color),
+ test(o.test),
+ test4(o.test4),
+ testarrayofstring(o.testarrayofstring),
+ enemy((o.enemy) ? new MyGame::Example::MonsterT(*o.enemy) : nullptr),
+ testnestedflatbuffer(o.testnestedflatbuffer),
+ testempty((o.testempty) ? new MyGame::Example::StatT(*o.testempty) : nullptr),
+ testbool(o.testbool),
+ testhashs32_fnv1(o.testhashs32_fnv1),
+ testhashu32_fnv1(o.testhashu32_fnv1),
+ testhashs64_fnv1(o.testhashs64_fnv1),
+ testhashu64_fnv1(o.testhashu64_fnv1),
+ testhashs32_fnv1a(o.testhashs32_fnv1a),
+ testhashu32_fnv1a(o.testhashu32_fnv1a),
+ testhashs64_fnv1a(o.testhashs64_fnv1a),
+ testhashu64_fnv1a(o.testhashu64_fnv1a),
+ testarrayofbools(o.testarrayofbools),
+ testf(o.testf),
+ testf2(o.testf2),
+ testf3(o.testf3),
+ testarrayofstring2(o.testarrayofstring2),
+ testarrayofsortedstruct(o.testarrayofsortedstruct),
+ flex(o.flex),
+ test5(o.test5),
+ vector_of_longs(o.vector_of_longs),
+ vector_of_doubles(o.vector_of_doubles),
+ parent_namespace_test((o.parent_namespace_test) ? new MyGame::InParentNamespaceT(*o.parent_namespace_test) : nullptr),
+ single_weak_reference(o.single_weak_reference),
+ vector_of_weak_references(o.vector_of_weak_references),
+ co_owning_reference(o.co_owning_reference),
+ non_owning_reference(o.non_owning_reference),
+ vector_of_non_owning_references(o.vector_of_non_owning_references),
+ any_unique(o.any_unique),
+ any_ambiguous(o.any_ambiguous),
+ vector_of_enums(o.vector_of_enums),
+ signed_enum(o.signed_enum),
+ testrequirednestedflatbuffer(o.testrequirednestedflatbuffer),
+ native_inline(o.native_inline),
+ long_enum_non_enum_default(o.long_enum_non_enum_default),
+ long_enum_normal_default(o.long_enum_normal_default) {
+ testarrayoftables.reserve(o.testarrayoftables.size());
+ for (const auto &testarrayoftables_ : o.testarrayoftables) { testarrayoftables.emplace_back((testarrayoftables_) ? new MyGame::Example::MonsterT(*testarrayoftables_) : nullptr); }
+ vector_of_referrables.reserve(o.vector_of_referrables.size());
+ for (const auto &vector_of_referrables_ : o.vector_of_referrables) { vector_of_referrables.emplace_back((vector_of_referrables_) ? new MyGame::Example::ReferrableT(*vector_of_referrables_) : nullptr); }
+ vector_of_strong_referrables.reserve(o.vector_of_strong_referrables.size());
+ for (const auto &vector_of_strong_referrables_ : o.vector_of_strong_referrables) { vector_of_strong_referrables.emplace_back((vector_of_strong_referrables_) ? new MyGame::Example::ReferrableT(*vector_of_strong_referrables_) : nullptr); }
+ vector_of_co_owning_references.reserve(o.vector_of_co_owning_references.size());
+ for (const auto &vector_of_co_owning_references_ : o.vector_of_co_owning_references) { vector_of_co_owning_references.emplace_back((vector_of_co_owning_references_) ? new ReferrableT(*vector_of_co_owning_references_) : nullptr); }
+ scalar_key_sorted_tables.reserve(o.scalar_key_sorted_tables.size());
+ for (const auto &scalar_key_sorted_tables_ : o.scalar_key_sorted_tables) { scalar_key_sorted_tables.emplace_back((scalar_key_sorted_tables_) ? new MyGame::Example::StatT(*scalar_key_sorted_tables_) : nullptr); }
+}
+
+inline MonsterT &MonsterT::operator=(MonsterT o) FLATBUFFERS_NOEXCEPT {
+ std::swap(pos, o.pos);
+ std::swap(mana, o.mana);
+ std::swap(hp, o.hp);
+ std::swap(name, o.name);
+ std::swap(inventory, o.inventory);
+ std::swap(color, o.color);
+ std::swap(test, o.test);
+ std::swap(test4, o.test4);
+ std::swap(testarrayofstring, o.testarrayofstring);
+ std::swap(testarrayoftables, o.testarrayoftables);
+ std::swap(enemy, o.enemy);
+ std::swap(testnestedflatbuffer, o.testnestedflatbuffer);
+ std::swap(testempty, o.testempty);
+ std::swap(testbool, o.testbool);
+ std::swap(testhashs32_fnv1, o.testhashs32_fnv1);
+ std::swap(testhashu32_fnv1, o.testhashu32_fnv1);
+ std::swap(testhashs64_fnv1, o.testhashs64_fnv1);
+ std::swap(testhashu64_fnv1, o.testhashu64_fnv1);
+ std::swap(testhashs32_fnv1a, o.testhashs32_fnv1a);
+ std::swap(testhashu32_fnv1a, o.testhashu32_fnv1a);
+ std::swap(testhashs64_fnv1a, o.testhashs64_fnv1a);
+ std::swap(testhashu64_fnv1a, o.testhashu64_fnv1a);
+ std::swap(testarrayofbools, o.testarrayofbools);
+ std::swap(testf, o.testf);
+ std::swap(testf2, o.testf2);
+ std::swap(testf3, o.testf3);
+ std::swap(testarrayofstring2, o.testarrayofstring2);
+ std::swap(testarrayofsortedstruct, o.testarrayofsortedstruct);
+ std::swap(flex, o.flex);
+ std::swap(test5, o.test5);
+ std::swap(vector_of_longs, o.vector_of_longs);
+ std::swap(vector_of_doubles, o.vector_of_doubles);
+ std::swap(parent_namespace_test, o.parent_namespace_test);
+ std::swap(vector_of_referrables, o.vector_of_referrables);
+ std::swap(single_weak_reference, o.single_weak_reference);
+ std::swap(vector_of_weak_references, o.vector_of_weak_references);
+ std::swap(vector_of_strong_referrables, o.vector_of_strong_referrables);
+ std::swap(co_owning_reference, o.co_owning_reference);
+ std::swap(vector_of_co_owning_references, o.vector_of_co_owning_references);
+ std::swap(non_owning_reference, o.non_owning_reference);
+ std::swap(vector_of_non_owning_references, o.vector_of_non_owning_references);
+ std::swap(any_unique, o.any_unique);
+ std::swap(any_ambiguous, o.any_ambiguous);
+ std::swap(vector_of_enums, o.vector_of_enums);
+ std::swap(signed_enum, o.signed_enum);
+ std::swap(testrequirednestedflatbuffer, o.testrequirednestedflatbuffer);
+ std::swap(scalar_key_sorted_tables, o.scalar_key_sorted_tables);
+ std::swap(native_inline, o.native_inline);
+ std::swap(long_enum_non_enum_default, o.long_enum_non_enum_default);
+ std::swap(long_enum_normal_default, o.long_enum_normal_default);
+ return *this;
+}
+
inline MonsterT *Monster::UnPack(const flatbuffers::resolver_function_t *_resolver) const {
- flatbuffers::unique_ptr<MyGame::Example::MonsterT> _o = flatbuffers::unique_ptr<MyGame::Example::MonsterT>(new MonsterT());
+ auto _o = std::unique_ptr<MonsterT>(new MonsterT());
UnPackTo(_o.get(), _resolver);
return _o.release();
}
@@ -2612,10 +2859,10 @@
{ auto _e = test(); if (_e) _o->test.value = MyGame::Example::AnyUnion::UnPack(_e, test_type(), _resolver); }
{ auto _e = test4(); if (_e) { _o->test4.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->test4[_i] = *_e->Get(_i); } } }
{ auto _e = testarrayofstring(); if (_e) { _o->testarrayofstring.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->testarrayofstring[_i] = _e->Get(_i)->str(); } } }
- { auto _e = testarrayoftables(); if (_e) { _o->testarrayoftables.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->testarrayoftables[_i] = flatbuffers::unique_ptr<MyGame::Example::MonsterT>(_e->Get(_i)->UnPack(_resolver)); } } }
- { auto _e = enemy(); if (_e) _o->enemy = flatbuffers::unique_ptr<MyGame::Example::MonsterT>(_e->UnPack(_resolver)); }
+ { auto _e = testarrayoftables(); if (_e) { _o->testarrayoftables.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { if(_o->testarrayoftables[_i]) { _e->Get(_i)->UnPackTo(_o->testarrayoftables[_i].get(), _resolver); } else { _o->testarrayoftables[_i] = flatbuffers::unique_ptr<MyGame::Example::MonsterT>(_e->Get(_i)->UnPack(_resolver)); }; } } }
+ { auto _e = enemy(); if (_e) { if(_o->enemy) { _e->UnPackTo(_o->enemy.get(), _resolver); } else { _o->enemy = flatbuffers::unique_ptr<MyGame::Example::MonsterT>(_e->UnPack(_resolver)); } } }
{ auto _e = testnestedflatbuffer(); if (_e) { _o->testnestedflatbuffer.resize(_e->size()); std::copy(_e->begin(), _e->end(), _o->testnestedflatbuffer.begin()); } }
- { auto _e = testempty(); if (_e) _o->testempty = flatbuffers::unique_ptr<MyGame::Example::StatT>(_e->UnPack(_resolver)); }
+ { auto _e = testempty(); if (_e) { if(_o->testempty) { _e->UnPackTo(_o->testempty.get(), _resolver); } else { _o->testempty = flatbuffers::unique_ptr<MyGame::Example::StatT>(_e->UnPack(_resolver)); } } }
{ auto _e = testbool(); _o->testbool = _e; }
{ auto _e = testhashs32_fnv1(); _o->testhashs32_fnv1 = _e; }
{ auto _e = testhashu32_fnv1(); _o->testhashu32_fnv1 = _e; }
@@ -2636,13 +2883,13 @@
{ auto _e = test5(); if (_e) { _o->test5.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->test5[_i] = *_e->Get(_i); } } }
{ auto _e = vector_of_longs(); if (_e) { _o->vector_of_longs.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->vector_of_longs[_i] = _e->Get(_i); } } }
{ auto _e = vector_of_doubles(); if (_e) { _o->vector_of_doubles.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->vector_of_doubles[_i] = _e->Get(_i); } } }
- { auto _e = parent_namespace_test(); if (_e) _o->parent_namespace_test = flatbuffers::unique_ptr<MyGame::InParentNamespaceT>(_e->UnPack(_resolver)); }
- { auto _e = vector_of_referrables(); if (_e) { _o->vector_of_referrables.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->vector_of_referrables[_i] = flatbuffers::unique_ptr<MyGame::Example::ReferrableT>(_e->Get(_i)->UnPack(_resolver)); } } }
+ { auto _e = parent_namespace_test(); if (_e) { if(_o->parent_namespace_test) { _e->UnPackTo(_o->parent_namespace_test.get(), _resolver); } else { _o->parent_namespace_test = flatbuffers::unique_ptr<MyGame::InParentNamespaceT>(_e->UnPack(_resolver)); } } }
+ { auto _e = vector_of_referrables(); if (_e) { _o->vector_of_referrables.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { if(_o->vector_of_referrables[_i]) { _e->Get(_i)->UnPackTo(_o->vector_of_referrables[_i].get(), _resolver); } else { _o->vector_of_referrables[_i] = flatbuffers::unique_ptr<MyGame::Example::ReferrableT>(_e->Get(_i)->UnPack(_resolver)); }; } } }
{ auto _e = single_weak_reference(); //scalar resolver, naked
if (_resolver) (*_resolver)(reinterpret_cast<void **>(&_o->single_weak_reference), static_cast<flatbuffers::hash_value_t>(_e)); else _o->single_weak_reference = nullptr; }
{ auto _e = vector_of_weak_references(); if (_e) { _o->vector_of_weak_references.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { //vector resolver, naked
if (_resolver) (*_resolver)(reinterpret_cast<void **>(&_o->vector_of_weak_references[_i]), static_cast<flatbuffers::hash_value_t>(_e->Get(_i))); else _o->vector_of_weak_references[_i] = nullptr; } } }
- { auto _e = vector_of_strong_referrables(); if (_e) { _o->vector_of_strong_referrables.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->vector_of_strong_referrables[_i] = flatbuffers::unique_ptr<MyGame::Example::ReferrableT>(_e->Get(_i)->UnPack(_resolver)); } } }
+ { auto _e = vector_of_strong_referrables(); if (_e) { _o->vector_of_strong_referrables.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { if(_o->vector_of_strong_referrables[_i]) { _e->Get(_i)->UnPackTo(_o->vector_of_strong_referrables[_i].get(), _resolver); } else { _o->vector_of_strong_referrables[_i] = flatbuffers::unique_ptr<MyGame::Example::ReferrableT>(_e->Get(_i)->UnPack(_resolver)); }; } } }
{ auto _e = co_owning_reference(); //scalar resolver, naked
if (_resolver) (*_resolver)(reinterpret_cast<void **>(&_o->co_owning_reference), static_cast<flatbuffers::hash_value_t>(_e)); else _o->co_owning_reference = nullptr; }
{ auto _e = vector_of_co_owning_references(); if (_e) { _o->vector_of_co_owning_references.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { //vector resolver, default_ptr_type
@@ -2658,6 +2905,10 @@
{ auto _e = vector_of_enums(); if (_e) { _o->vector_of_enums.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->vector_of_enums[_i] = static_cast<MyGame::Example::Color>(_e->Get(_i)); } } }
{ auto _e = signed_enum(); _o->signed_enum = _e; }
{ auto _e = testrequirednestedflatbuffer(); if (_e) { _o->testrequirednestedflatbuffer.resize(_e->size()); std::copy(_e->begin(), _e->end(), _o->testrequirednestedflatbuffer.begin()); } }
+ { auto _e = scalar_key_sorted_tables(); if (_e) { _o->scalar_key_sorted_tables.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { if(_o->scalar_key_sorted_tables[_i]) { _e->Get(_i)->UnPackTo(_o->scalar_key_sorted_tables[_i].get(), _resolver); } else { _o->scalar_key_sorted_tables[_i] = flatbuffers::unique_ptr<MyGame::Example::StatT>(_e->Get(_i)->UnPack(_resolver)); }; } } }
+ { auto _e = native_inline(); if (_e) _o->native_inline = *_e; }
+ { auto _e = long_enum_non_enum_default(); _o->long_enum_non_enum_default = _e; }
+ { auto _e = long_enum_normal_default(); _o->long_enum_normal_default = _e; }
}
inline flatbuffers::Offset<Monster> Monster::Pack(flatbuffers::FlatBufferBuilder &_fbb, const MonsterT* _o, const flatbuffers::rehasher_function_t *_rehasher) {
@@ -2717,6 +2968,10 @@
auto _vector_of_enums = _o->vector_of_enums.size() ? _fbb.CreateVectorScalarCast<uint8_t>(flatbuffers::data(_o->vector_of_enums), _o->vector_of_enums.size()) : 0;
auto _signed_enum = _o->signed_enum;
auto _testrequirednestedflatbuffer = _o->testrequirednestedflatbuffer.size() ? _fbb.CreateVector(_o->testrequirednestedflatbuffer) : 0;
+ auto _scalar_key_sorted_tables = _o->scalar_key_sorted_tables.size() ? _fbb.CreateVector<flatbuffers::Offset<MyGame::Example::Stat>> (_o->scalar_key_sorted_tables.size(), [](size_t i, _VectorArgs *__va) { return CreateStat(*__va->__fbb, __va->__o->scalar_key_sorted_tables[i].get(), __va->__rehasher); }, &_va ) : 0;
+ auto _native_inline = &_o->native_inline;
+ auto _long_enum_non_enum_default = _o->long_enum_non_enum_default;
+ auto _long_enum_normal_default = _o->long_enum_normal_default;
return MyGame::Example::CreateMonster(
_fbb,
_pos,
@@ -2767,11 +3022,37 @@
_any_ambiguous,
_vector_of_enums,
_signed_enum,
- _testrequirednestedflatbuffer);
+ _testrequirednestedflatbuffer,
+ _scalar_key_sorted_tables,
+ _native_inline,
+ _long_enum_non_enum_default,
+ _long_enum_normal_default);
}
+
+inline bool operator==(const TypeAliasesT &lhs, const TypeAliasesT &rhs) {
+ return
+ (lhs.i8 == rhs.i8) &&
+ (lhs.u8 == rhs.u8) &&
+ (lhs.i16 == rhs.i16) &&
+ (lhs.u16 == rhs.u16) &&
+ (lhs.i32 == rhs.i32) &&
+ (lhs.u32 == rhs.u32) &&
+ (lhs.i64 == rhs.i64) &&
+ (lhs.u64 == rhs.u64) &&
+ (lhs.f32 == rhs.f32) &&
+ (lhs.f64 == rhs.f64) &&
+ (lhs.v8 == rhs.v8) &&
+ (lhs.vf64 == rhs.vf64);
+}
+
+inline bool operator!=(const TypeAliasesT &lhs, const TypeAliasesT &rhs) {
+ return !(lhs == rhs);
+}
+
+
inline TypeAliasesT *TypeAliases::UnPack(const flatbuffers::resolver_function_t *_resolver) const {
- flatbuffers::unique_ptr<MyGame::Example::TypeAliasesT> _o = flatbuffers::unique_ptr<MyGame::Example::TypeAliasesT>(new TypeAliasesT());
+ auto _o = std::unique_ptr<TypeAliasesT>(new TypeAliasesT());
UnPackTo(_o.get(), _resolver);
return _o.release();
}
@@ -2863,6 +3144,7 @@
}
inline void *AnyUnion::UnPack(const void *obj, Any type, const flatbuffers::resolver_function_t *resolver) {
+ (void)resolver;
switch (type) {
case Any_Monster: {
auto ptr = reinterpret_cast<const MyGame::Example::Monster *>(obj);
@@ -2881,6 +3163,7 @@
}
inline flatbuffers::Offset<void> AnyUnion::Pack(flatbuffers::FlatBufferBuilder &_fbb, const flatbuffers::rehasher_function_t *_rehasher) const {
+ (void)_rehasher;
switch (type) {
case Any_Monster: {
auto ptr = reinterpret_cast<const MyGame::Example::MonsterT *>(value);
@@ -2901,7 +3184,7 @@
inline AnyUnion::AnyUnion(const AnyUnion &u) : type(u.type), value(nullptr) {
switch (type) {
case Any_Monster: {
- FLATBUFFERS_ASSERT(false); // MyGame::Example::MonsterT not copyable.
+ value = new MyGame::Example::MonsterT(*reinterpret_cast<MyGame::Example::MonsterT *>(u.value));
break;
}
case Any_TestSimpleTableWithEnum: {
@@ -2974,6 +3257,7 @@
}
inline void *AnyUniqueAliasesUnion::UnPack(const void *obj, AnyUniqueAliases type, const flatbuffers::resolver_function_t *resolver) {
+ (void)resolver;
switch (type) {
case AnyUniqueAliases_M: {
auto ptr = reinterpret_cast<const MyGame::Example::Monster *>(obj);
@@ -2992,6 +3276,7 @@
}
inline flatbuffers::Offset<void> AnyUniqueAliasesUnion::Pack(flatbuffers::FlatBufferBuilder &_fbb, const flatbuffers::rehasher_function_t *_rehasher) const {
+ (void)_rehasher;
switch (type) {
case AnyUniqueAliases_M: {
auto ptr = reinterpret_cast<const MyGame::Example::MonsterT *>(value);
@@ -3012,7 +3297,7 @@
inline AnyUniqueAliasesUnion::AnyUniqueAliasesUnion(const AnyUniqueAliasesUnion &u) : type(u.type), value(nullptr) {
switch (type) {
case AnyUniqueAliases_M: {
- FLATBUFFERS_ASSERT(false); // MyGame::Example::MonsterT not copyable.
+ value = new MyGame::Example::MonsterT(*reinterpret_cast<MyGame::Example::MonsterT *>(u.value));
break;
}
case AnyUniqueAliases_TS: {
@@ -3085,6 +3370,7 @@
}
inline void *AnyAmbiguousAliasesUnion::UnPack(const void *obj, AnyAmbiguousAliases type, const flatbuffers::resolver_function_t *resolver) {
+ (void)resolver;
switch (type) {
case AnyAmbiguousAliases_M1: {
auto ptr = reinterpret_cast<const MyGame::Example::Monster *>(obj);
@@ -3103,6 +3389,7 @@
}
inline flatbuffers::Offset<void> AnyAmbiguousAliasesUnion::Pack(flatbuffers::FlatBufferBuilder &_fbb, const flatbuffers::rehasher_function_t *_rehasher) const {
+ (void)_rehasher;
switch (type) {
case AnyAmbiguousAliases_M1: {
auto ptr = reinterpret_cast<const MyGame::Example::MonsterT *>(value);
@@ -3123,15 +3410,15 @@
inline AnyAmbiguousAliasesUnion::AnyAmbiguousAliasesUnion(const AnyAmbiguousAliasesUnion &u) : type(u.type), value(nullptr) {
switch (type) {
case AnyAmbiguousAliases_M1: {
- FLATBUFFERS_ASSERT(false); // MyGame::Example::MonsterT not copyable.
+ value = new MyGame::Example::MonsterT(*reinterpret_cast<MyGame::Example::MonsterT *>(u.value));
break;
}
case AnyAmbiguousAliases_M2: {
- FLATBUFFERS_ASSERT(false); // MyGame::Example::MonsterT not copyable.
+ value = new MyGame::Example::MonsterT(*reinterpret_cast<MyGame::Example::MonsterT *>(u.value));
break;
}
case AnyAmbiguousAliases_M3: {
- FLATBUFFERS_ASSERT(false); // MyGame::Example::MonsterT not copyable.
+ value = new MyGame::Example::MonsterT(*reinterpret_cast<MyGame::Example::MonsterT *>(u.value));
break;
}
default:
@@ -3206,6 +3493,27 @@
return &tt;
}
+inline const flatbuffers::TypeTable *LongEnumTypeTable() {
+ static const flatbuffers::TypeCode type_codes[] = {
+ { flatbuffers::ET_ULONG, 0, 0 },
+ { flatbuffers::ET_ULONG, 0, 0 },
+ { flatbuffers::ET_ULONG, 0, 0 }
+ };
+ static const flatbuffers::TypeFunction type_refs[] = {
+ MyGame::Example::LongEnumTypeTable
+ };
+ static const int64_t values[] = { 2ULL, 4ULL, 1099511627776ULL };
+ static const char * const names[] = {
+ "LongOne",
+ "LongTwo",
+ "LongBig"
+ };
+ static const flatbuffers::TypeTable tt = {
+ flatbuffers::ST_ENUM, 3, type_codes, type_refs, nullptr, values, names
+ };
+ return &tt;
+}
+
inline const flatbuffers::TypeTable *AnyTypeTable() {
static const flatbuffers::TypeCode type_codes[] = {
{ flatbuffers::ET_SEQUENCE, 0, -1 },
@@ -3374,6 +3682,28 @@
return &tt;
}
+inline const flatbuffers::TypeTable *StructOfStructsTypeTable() {
+ static const flatbuffers::TypeCode type_codes[] = {
+ { flatbuffers::ET_SEQUENCE, 0, 0 },
+ { flatbuffers::ET_SEQUENCE, 0, 1 },
+ { flatbuffers::ET_SEQUENCE, 0, 0 }
+ };
+ static const flatbuffers::TypeFunction type_refs[] = {
+ MyGame::Example::AbilityTypeTable,
+ MyGame::Example::TestTypeTable
+ };
+ static const int64_t values[] = { 0, 8, 12, 20 };
+ static const char * const names[] = {
+ "a",
+ "b",
+ "c"
+ };
+ static const flatbuffers::TypeTable tt = {
+ flatbuffers::ST_STRUCT, 3, type_codes, type_refs, nullptr, values, names
+ };
+ return &tt;
+}
+
inline const flatbuffers::TypeTable *StatTypeTable() {
static const flatbuffers::TypeCode type_codes[] = {
{ flatbuffers::ET_STRING, 0, -1 },
@@ -3455,7 +3785,11 @@
{ flatbuffers::ET_SEQUENCE, 0, 10 },
{ flatbuffers::ET_UCHAR, 1, 1 },
{ flatbuffers::ET_CHAR, 0, 11 },
- { flatbuffers::ET_UCHAR, 1, -1 }
+ { flatbuffers::ET_UCHAR, 1, -1 },
+ { flatbuffers::ET_SEQUENCE, 1, 5 },
+ { flatbuffers::ET_SEQUENCE, 0, 3 },
+ { flatbuffers::ET_ULONG, 0, 12 },
+ { flatbuffers::ET_ULONG, 0, 12 }
};
static const flatbuffers::TypeFunction type_refs[] = {
MyGame::Example::Vec3TypeTable,
@@ -3469,7 +3803,8 @@
MyGame::Example::ReferrableTypeTable,
MyGame::Example::AnyUniqueAliasesTypeTable,
MyGame::Example::AnyAmbiguousAliasesTypeTable,
- MyGame::Example::RaceTypeTable
+ MyGame::Example::RaceTypeTable,
+ MyGame::Example::LongEnumTypeTable
};
static const char * const names[] = {
"pos",
@@ -3521,10 +3856,14 @@
"any_ambiguous",
"vector_of_enums",
"signed_enum",
- "testrequirednestedflatbuffer"
+ "testrequirednestedflatbuffer",
+ "scalar_key_sorted_tables",
+ "native_inline",
+ "long_enum_non_enum_default",
+ "long_enum_normal_default"
};
static const flatbuffers::TypeTable tt = {
- flatbuffers::ST_TABLE, 50, type_codes, type_refs, nullptr, nullptr, names
+ flatbuffers::ST_TABLE, 54, type_codes, type_refs, nullptr, nullptr, names
};
return &tt;
}
@@ -3576,6 +3915,10 @@
return flatbuffers::GetMutableRoot<Monster>(buf);
}
+inline MyGame::Example::Monster *GetMutableSizePrefixedMonster(void *buf) {
+ return flatbuffers::GetMutableSizePrefixedRoot<MyGame::Example::Monster>(buf);
+}
+
inline const char *MonsterIdentifier() {
return "MONS";
}
@@ -3585,6 +3928,11 @@
buf, MonsterIdentifier());
}
+inline bool SizePrefixedMonsterBufferHasIdentifier(const void *buf) {
+ return flatbuffers::BufferHasIdentifier(
+ buf, MonsterIdentifier(), true);
+}
+
inline bool VerifyMonsterBuffer(
flatbuffers::Verifier &verifier) {
return verifier.VerifyBuffer<MyGame::Example::Monster>(MonsterIdentifier());
diff --git a/tests/monster_test_generated.js b/tests/monster_test_generated.js
deleted file mode 100644
index a2abec7..0000000
--- a/tests/monster_test_generated.js
+++ /dev/null
@@ -1,3230 +0,0 @@
-// automatically generated by the FlatBuffers compiler, do not modify
-
-/**
- * @const
- * @namespace
- */
-var MyGame = MyGame || {};
-
-/**
- * @const
- * @namespace
- */
-MyGame.Example = MyGame.Example || {};
-
-/**
- * @const
- * @namespace
- */
-MyGame.Example2 = MyGame.Example2 || {};
-
-/**
- * @const
- * @namespace
- */
-MyGame.OtherNameSpace = MyGame.OtherNameSpace || {};
-
-/**
- * Composite components of Monster color.
- *
- * @enum {number}
- */
-MyGame.Example.Color = {
- Red: 1,
-
- /**
- * \brief color Green
- * Green is bit_flag with value (1u << 1)
- */
- Green: 2,
-
- /**
- * \brief color Blue (1u << 3)
- */
- Blue: 8
-};
-
-/**
- * Composite components of Monster color.
- *
- * @enum {string}
- */
-MyGame.Example.ColorName = {
- '1': 'Red',
-
- /**
- * \brief color Green
- * Green is bit_flag with value (1u << 1)
- */
- '2': 'Green',
-
- /**
- * \brief color Blue (1u << 3)
- */
- '8': 'Blue'
-};
-
-/**
- * @enum {number}
- */
-MyGame.Example.Race = {
- None: -1,
- Human: 0,
- Dwarf: 1,
- Elf: 2
-};
-
-/**
- * @enum {string}
- */
-MyGame.Example.RaceName = {
- '-1': 'None',
- '0': 'Human',
- '1': 'Dwarf',
- '2': 'Elf'
-};
-
-/**
- * @enum {number}
- */
-MyGame.Example.Any = {
- NONE: 0,
- Monster: 1,
- TestSimpleTableWithEnum: 2,
- MyGame_Example2_Monster: 3
-};
-
-/**
- * @enum {string}
- */
-MyGame.Example.AnyName = {
- '0': 'NONE',
- '1': 'Monster',
- '2': 'TestSimpleTableWithEnum',
- '3': 'MyGame_Example2_Monster'
-};
-
-/**
- * @enum {number}
- */
-MyGame.Example.AnyUniqueAliases = {
- NONE: 0,
- M: 1,
- TS: 2,
- M2: 3
-};
-
-/**
- * @enum {string}
- */
-MyGame.Example.AnyUniqueAliasesName = {
- '0': 'NONE',
- '1': 'M',
- '2': 'TS',
- '3': 'M2'
-};
-
-/**
- * @enum {number}
- */
-MyGame.Example.AnyAmbiguousAliases = {
- NONE: 0,
- M1: 1,
- M2: 2,
- M3: 3
-};
-
-/**
- * @enum {string}
- */
-MyGame.Example.AnyAmbiguousAliasesName = {
- '0': 'NONE',
- '1': 'M1',
- '2': 'M2',
- '3': 'M3'
-};
-
-/**
- * @constructor
- */
-MyGame.InParentNamespace = function() {
- /**
- * @type {flatbuffers.ByteBuffer}
- */
- this.bb = null;
-
- /**
- * @type {number}
- */
- this.bb_pos = 0;
-};
-
-/**
- * @param {number} i
- * @param {flatbuffers.ByteBuffer} bb
- * @returns {MyGame.InParentNamespace}
- */
-MyGame.InParentNamespace.prototype.__init = function(i, bb) {
- this.bb_pos = i;
- this.bb = bb;
- return this;
-};
-
-/**
- * @param {flatbuffers.ByteBuffer} bb
- * @param {MyGame.InParentNamespace=} obj
- * @returns {MyGame.InParentNamespace}
- */
-MyGame.InParentNamespace.getRootAsInParentNamespace = function(bb, obj) {
- return (obj || new MyGame.InParentNamespace).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param {flatbuffers.ByteBuffer} bb
- * @param {MyGame.InParentNamespace=} obj
- * @returns {MyGame.InParentNamespace}
- */
-MyGame.InParentNamespace.getSizePrefixedRootAsInParentNamespace = function(bb, obj) {
- bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
- return (obj || new MyGame.InParentNamespace).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- */
-MyGame.InParentNamespace.startInParentNamespace = function(builder) {
- builder.startObject(0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @returns {flatbuffers.Offset}
- */
-MyGame.InParentNamespace.endInParentNamespace = function(builder) {
- var offset = builder.endObject();
- return offset;
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @returns {flatbuffers.Offset}
- */
-MyGame.InParentNamespace.createInParentNamespace = function(builder) {
- MyGame.InParentNamespace.startInParentNamespace(builder);
- return MyGame.InParentNamespace.endInParentNamespace(builder);
-}
-
-/**
- * @constructor
- */
-MyGame.Example2.Monster = function() {
- /**
- * @type {flatbuffers.ByteBuffer}
- */
- this.bb = null;
-
- /**
- * @type {number}
- */
- this.bb_pos = 0;
-};
-
-/**
- * @param {number} i
- * @param {flatbuffers.ByteBuffer} bb
- * @returns {MyGame.Example2.Monster}
- */
-MyGame.Example2.Monster.prototype.__init = function(i, bb) {
- this.bb_pos = i;
- this.bb = bb;
- return this;
-};
-
-/**
- * @param {flatbuffers.ByteBuffer} bb
- * @param {MyGame.Example2.Monster=} obj
- * @returns {MyGame.Example2.Monster}
- */
-MyGame.Example2.Monster.getRootAsMonster = function(bb, obj) {
- return (obj || new MyGame.Example2.Monster).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param {flatbuffers.ByteBuffer} bb
- * @param {MyGame.Example2.Monster=} obj
- * @returns {MyGame.Example2.Monster}
- */
-MyGame.Example2.Monster.getSizePrefixedRootAsMonster = function(bb, obj) {
- bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
- return (obj || new MyGame.Example2.Monster).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- */
-MyGame.Example2.Monster.startMonster = function(builder) {
- builder.startObject(0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @returns {flatbuffers.Offset}
- */
-MyGame.Example2.Monster.endMonster = function(builder) {
- var offset = builder.endObject();
- return offset;
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @returns {flatbuffers.Offset}
- */
-MyGame.Example2.Monster.createMonster = function(builder) {
- MyGame.Example2.Monster.startMonster(builder);
- return MyGame.Example2.Monster.endMonster(builder);
-}
-
-/**
- * @constructor
- */
-MyGame.Example.Test = function() {
- /**
- * @type {flatbuffers.ByteBuffer}
- */
- this.bb = null;
-
- /**
- * @type {number}
- */
- this.bb_pos = 0;
-};
-
-/**
- * @param {number} i
- * @param {flatbuffers.ByteBuffer} bb
- * @returns {MyGame.Example.Test}
- */
-MyGame.Example.Test.prototype.__init = function(i, bb) {
- this.bb_pos = i;
- this.bb = bb;
- return this;
-};
-
-/**
- * @returns {number}
- */
-MyGame.Example.Test.prototype.a = function() {
- return this.bb.readInt16(this.bb_pos);
-};
-
-/**
- * @param {number} value
- * @returns {boolean}
- */
-MyGame.Example.Test.prototype.mutate_a = function(value) {
- this.bb.writeInt16(this.bb_pos + 0, value);
- return true;
-};
-
-/**
- * @returns {number}
- */
-MyGame.Example.Test.prototype.b = function() {
- return this.bb.readInt8(this.bb_pos + 2);
-};
-
-/**
- * @param {number} value
- * @returns {boolean}
- */
-MyGame.Example.Test.prototype.mutate_b = function(value) {
- this.bb.writeInt8(this.bb_pos + 2, value);
- return true;
-};
-
-/**
- * @returns {number}
- */
-MyGame.Example.Test.sizeOf = function() {
- return 4;
-}
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} a
- * @param {number} b
- * @returns {flatbuffers.Offset}
- */
-MyGame.Example.Test.createTest = function(builder, a, b) {
- builder.prep(2, 4);
- builder.pad(1);
- builder.writeInt8(b);
- builder.writeInt16(a);
- return builder.offset();
-};
-
-/**
- * @constructor
- */
-MyGame.Example.TestSimpleTableWithEnum = function() {
- /**
- * @type {flatbuffers.ByteBuffer}
- */
- this.bb = null;
-
- /**
- * @type {number}
- */
- this.bb_pos = 0;
-};
-
-/**
- * @param {number} i
- * @param {flatbuffers.ByteBuffer} bb
- * @returns {MyGame.Example.TestSimpleTableWithEnum}
- */
-MyGame.Example.TestSimpleTableWithEnum.prototype.__init = function(i, bb) {
- this.bb_pos = i;
- this.bb = bb;
- return this;
-};
-
-/**
- * @param {flatbuffers.ByteBuffer} bb
- * @param {MyGame.Example.TestSimpleTableWithEnum=} obj
- * @returns {MyGame.Example.TestSimpleTableWithEnum}
- */
-MyGame.Example.TestSimpleTableWithEnum.getRootAsTestSimpleTableWithEnum = function(bb, obj) {
- return (obj || new MyGame.Example.TestSimpleTableWithEnum).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param {flatbuffers.ByteBuffer} bb
- * @param {MyGame.Example.TestSimpleTableWithEnum=} obj
- * @returns {MyGame.Example.TestSimpleTableWithEnum}
- */
-MyGame.Example.TestSimpleTableWithEnum.getSizePrefixedRootAsTestSimpleTableWithEnum = function(bb, obj) {
- bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
- return (obj || new MyGame.Example.TestSimpleTableWithEnum).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @returns {MyGame.Example.Color}
- */
-MyGame.Example.TestSimpleTableWithEnum.prototype.color = function() {
- var offset = this.bb.__offset(this.bb_pos, 4);
- return offset ? /** @type {MyGame.Example.Color} */ (this.bb.readUint8(this.bb_pos + offset)) : MyGame.Example.Color.Green;
-};
-
-/**
- * @param {MyGame.Example.Color} value
- * @returns {boolean}
- */
-MyGame.Example.TestSimpleTableWithEnum.prototype.mutate_color = function(value) {
- var offset = this.bb.__offset(this.bb_pos, 4);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb.writeUint8(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- */
-MyGame.Example.TestSimpleTableWithEnum.startTestSimpleTableWithEnum = function(builder) {
- builder.startObject(1);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {MyGame.Example.Color} color
- */
-MyGame.Example.TestSimpleTableWithEnum.addColor = function(builder, color) {
- builder.addFieldInt8(0, color, MyGame.Example.Color.Green);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @returns {flatbuffers.Offset}
- */
-MyGame.Example.TestSimpleTableWithEnum.endTestSimpleTableWithEnum = function(builder) {
- var offset = builder.endObject();
- return offset;
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {MyGame.Example.Color} color
- * @returns {flatbuffers.Offset}
- */
-MyGame.Example.TestSimpleTableWithEnum.createTestSimpleTableWithEnum = function(builder, color) {
- MyGame.Example.TestSimpleTableWithEnum.startTestSimpleTableWithEnum(builder);
- MyGame.Example.TestSimpleTableWithEnum.addColor(builder, color);
- return MyGame.Example.TestSimpleTableWithEnum.endTestSimpleTableWithEnum(builder);
-}
-
-/**
- * @constructor
- */
-MyGame.Example.Vec3 = function() {
- /**
- * @type {flatbuffers.ByteBuffer}
- */
- this.bb = null;
-
- /**
- * @type {number}
- */
- this.bb_pos = 0;
-};
-
-/**
- * @param {number} i
- * @param {flatbuffers.ByteBuffer} bb
- * @returns {MyGame.Example.Vec3}
- */
-MyGame.Example.Vec3.prototype.__init = function(i, bb) {
- this.bb_pos = i;
- this.bb = bb;
- return this;
-};
-
-/**
- * @returns {number}
- */
-MyGame.Example.Vec3.prototype.x = function() {
- return this.bb.readFloat32(this.bb_pos);
-};
-
-/**
- * @param {number} value
- * @returns {boolean}
- */
-MyGame.Example.Vec3.prototype.mutate_x = function(value) {
- this.bb.writeFloat32(this.bb_pos + 0, value);
- return true;
-};
-
-/**
- * @returns {number}
- */
-MyGame.Example.Vec3.prototype.y = function() {
- return this.bb.readFloat32(this.bb_pos + 4);
-};
-
-/**
- * @param {number} value
- * @returns {boolean}
- */
-MyGame.Example.Vec3.prototype.mutate_y = function(value) {
- this.bb.writeFloat32(this.bb_pos + 4, value);
- return true;
-};
-
-/**
- * @returns {number}
- */
-MyGame.Example.Vec3.prototype.z = function() {
- return this.bb.readFloat32(this.bb_pos + 8);
-};
-
-/**
- * @param {number} value
- * @returns {boolean}
- */
-MyGame.Example.Vec3.prototype.mutate_z = function(value) {
- this.bb.writeFloat32(this.bb_pos + 8, value);
- return true;
-};
-
-/**
- * @returns {number}
- */
-MyGame.Example.Vec3.prototype.test1 = function() {
- return this.bb.readFloat64(this.bb_pos + 16);
-};
-
-/**
- * @param {number} value
- * @returns {boolean}
- */
-MyGame.Example.Vec3.prototype.mutate_test1 = function(value) {
- this.bb.writeFloat64(this.bb_pos + 16, value);
- return true;
-};
-
-/**
- * @returns {MyGame.Example.Color}
- */
-MyGame.Example.Vec3.prototype.test2 = function() {
- return /** @type {MyGame.Example.Color} */ (this.bb.readUint8(this.bb_pos + 24));
-};
-
-/**
- * @param {MyGame.Example.Color} value
- * @returns {boolean}
- */
-MyGame.Example.Vec3.prototype.mutate_test2 = function(value) {
- this.bb.writeUint8(this.bb_pos + 24, value);
- return true;
-};
-
-/**
- * @param {MyGame.Example.Test=} obj
- * @returns {MyGame.Example.Test|null}
- */
-MyGame.Example.Vec3.prototype.test3 = function(obj) {
- return (obj || new MyGame.Example.Test).__init(this.bb_pos + 26, this.bb);
-};
-
-/**
- * @returns {number}
- */
-MyGame.Example.Vec3.sizeOf = function() {
- return 32;
-}
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} x
- * @param {number} y
- * @param {number} z
- * @param {number} test1
- * @param {MyGame.Example.Color} test2
- * @param {number} test3_a
- * @param {number} test3_b
- * @returns {flatbuffers.Offset}
- */
-MyGame.Example.Vec3.createVec3 = function(builder, x, y, z, test1, test2, test3_a, test3_b) {
- builder.prep(8, 32);
- builder.pad(2);
- builder.prep(2, 4);
- builder.pad(1);
- builder.writeInt8(test3_b);
- builder.writeInt16(test3_a);
- builder.pad(1);
- builder.writeInt8(test2);
- builder.writeFloat64(test1);
- builder.pad(4);
- builder.writeFloat32(z);
- builder.writeFloat32(y);
- builder.writeFloat32(x);
- return builder.offset();
-};
-
-/**
- * @constructor
- */
-MyGame.Example.Ability = function() {
- /**
- * @type {flatbuffers.ByteBuffer}
- */
- this.bb = null;
-
- /**
- * @type {number}
- */
- this.bb_pos = 0;
-};
-
-/**
- * @param {number} i
- * @param {flatbuffers.ByteBuffer} bb
- * @returns {MyGame.Example.Ability}
- */
-MyGame.Example.Ability.prototype.__init = function(i, bb) {
- this.bb_pos = i;
- this.bb = bb;
- return this;
-};
-
-/**
- * @returns {number}
- */
-MyGame.Example.Ability.prototype.id = function() {
- return this.bb.readUint32(this.bb_pos);
-};
-
-/**
- * @param {number} value
- * @returns {boolean}
- */
-MyGame.Example.Ability.prototype.mutate_id = function(value) {
- this.bb.writeUint32(this.bb_pos + 0, value);
- return true;
-};
-
-/**
- * @returns {number}
- */
-MyGame.Example.Ability.prototype.distance = function() {
- return this.bb.readUint32(this.bb_pos + 4);
-};
-
-/**
- * @param {number} value
- * @returns {boolean}
- */
-MyGame.Example.Ability.prototype.mutate_distance = function(value) {
- this.bb.writeUint32(this.bb_pos + 4, value);
- return true;
-};
-
-/**
- * @returns {number}
- */
-MyGame.Example.Ability.sizeOf = function() {
- return 8;
-}
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} id
- * @param {number} distance
- * @returns {flatbuffers.Offset}
- */
-MyGame.Example.Ability.createAbility = function(builder, id, distance) {
- builder.prep(4, 8);
- builder.writeInt32(distance);
- builder.writeInt32(id);
- return builder.offset();
-};
-
-/**
- * @constructor
- */
-MyGame.Example.Stat = function() {
- /**
- * @type {flatbuffers.ByteBuffer}
- */
- this.bb = null;
-
- /**
- * @type {number}
- */
- this.bb_pos = 0;
-};
-
-/**
- * @param {number} i
- * @param {flatbuffers.ByteBuffer} bb
- * @returns {MyGame.Example.Stat}
- */
-MyGame.Example.Stat.prototype.__init = function(i, bb) {
- this.bb_pos = i;
- this.bb = bb;
- return this;
-};
-
-/**
- * @param {flatbuffers.ByteBuffer} bb
- * @param {MyGame.Example.Stat=} obj
- * @returns {MyGame.Example.Stat}
- */
-MyGame.Example.Stat.getRootAsStat = function(bb, obj) {
- return (obj || new MyGame.Example.Stat).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param {flatbuffers.ByteBuffer} bb
- * @param {MyGame.Example.Stat=} obj
- * @returns {MyGame.Example.Stat}
- */
-MyGame.Example.Stat.getSizePrefixedRootAsStat = function(bb, obj) {
- bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
- return (obj || new MyGame.Example.Stat).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param {flatbuffers.Encoding=} optionalEncoding
- * @returns {string|Uint8Array|null}
- */
-MyGame.Example.Stat.prototype.id = function(optionalEncoding) {
- var offset = this.bb.__offset(this.bb_pos, 4);
- return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
-};
-
-/**
- * @returns {flatbuffers.Long}
- */
-MyGame.Example.Stat.prototype.val = function() {
- var offset = this.bb.__offset(this.bb_pos, 6);
- return offset ? this.bb.readInt64(this.bb_pos + offset) : this.bb.createLong(0, 0);
-};
-
-/**
- * @param {flatbuffers.Long} value
- * @returns {boolean}
- */
-MyGame.Example.Stat.prototype.mutate_val = function(value) {
- var offset = this.bb.__offset(this.bb_pos, 6);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb.writeInt64(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @returns {number}
- */
-MyGame.Example.Stat.prototype.count = function() {
- var offset = this.bb.__offset(this.bb_pos, 8);
- return offset ? this.bb.readUint16(this.bb_pos + offset) : 0;
-};
-
-/**
- * @param {number} value
- * @returns {boolean}
- */
-MyGame.Example.Stat.prototype.mutate_count = function(value) {
- var offset = this.bb.__offset(this.bb_pos, 8);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb.writeUint16(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- */
-MyGame.Example.Stat.startStat = function(builder) {
- builder.startObject(3);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Offset} idOffset
- */
-MyGame.Example.Stat.addId = function(builder, idOffset) {
- builder.addFieldOffset(0, idOffset, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Long} val
- */
-MyGame.Example.Stat.addVal = function(builder, val) {
- builder.addFieldInt64(1, val, builder.createLong(0, 0));
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} count
- */
-MyGame.Example.Stat.addCount = function(builder, count) {
- builder.addFieldInt16(2, count, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @returns {flatbuffers.Offset}
- */
-MyGame.Example.Stat.endStat = function(builder) {
- var offset = builder.endObject();
- return offset;
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Offset} idOffset
- * @param {flatbuffers.Long} val
- * @param {number} count
- * @returns {flatbuffers.Offset}
- */
-MyGame.Example.Stat.createStat = function(builder, idOffset, val, count) {
- MyGame.Example.Stat.startStat(builder);
- MyGame.Example.Stat.addId(builder, idOffset);
- MyGame.Example.Stat.addVal(builder, val);
- MyGame.Example.Stat.addCount(builder, count);
- return MyGame.Example.Stat.endStat(builder);
-}
-
-/**
- * @constructor
- */
-MyGame.Example.Referrable = function() {
- /**
- * @type {flatbuffers.ByteBuffer}
- */
- this.bb = null;
-
- /**
- * @type {number}
- */
- this.bb_pos = 0;
-};
-
-/**
- * @param {number} i
- * @param {flatbuffers.ByteBuffer} bb
- * @returns {MyGame.Example.Referrable}
- */
-MyGame.Example.Referrable.prototype.__init = function(i, bb) {
- this.bb_pos = i;
- this.bb = bb;
- return this;
-};
-
-/**
- * @param {flatbuffers.ByteBuffer} bb
- * @param {MyGame.Example.Referrable=} obj
- * @returns {MyGame.Example.Referrable}
- */
-MyGame.Example.Referrable.getRootAsReferrable = function(bb, obj) {
- return (obj || new MyGame.Example.Referrable).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param {flatbuffers.ByteBuffer} bb
- * @param {MyGame.Example.Referrable=} obj
- * @returns {MyGame.Example.Referrable}
- */
-MyGame.Example.Referrable.getSizePrefixedRootAsReferrable = function(bb, obj) {
- bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
- return (obj || new MyGame.Example.Referrable).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @returns {flatbuffers.Long}
- */
-MyGame.Example.Referrable.prototype.id = function() {
- var offset = this.bb.__offset(this.bb_pos, 4);
- return offset ? this.bb.readUint64(this.bb_pos + offset) : this.bb.createLong(0, 0);
-};
-
-/**
- * @param {flatbuffers.Long} value
- * @returns {boolean}
- */
-MyGame.Example.Referrable.prototype.mutate_id = function(value) {
- var offset = this.bb.__offset(this.bb_pos, 4);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb.writeUint64(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- */
-MyGame.Example.Referrable.startReferrable = function(builder) {
- builder.startObject(1);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Long} id
- */
-MyGame.Example.Referrable.addId = function(builder, id) {
- builder.addFieldInt64(0, id, builder.createLong(0, 0));
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @returns {flatbuffers.Offset}
- */
-MyGame.Example.Referrable.endReferrable = function(builder) {
- var offset = builder.endObject();
- return offset;
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Long} id
- * @returns {flatbuffers.Offset}
- */
-MyGame.Example.Referrable.createReferrable = function(builder, id) {
- MyGame.Example.Referrable.startReferrable(builder);
- MyGame.Example.Referrable.addId(builder, id);
- return MyGame.Example.Referrable.endReferrable(builder);
-}
-
-/**
- * an example documentation comment: "monster object"
- *
- * @constructor
- */
-MyGame.Example.Monster = function() {
- /**
- * @type {flatbuffers.ByteBuffer}
- */
- this.bb = null;
-
- /**
- * @type {number}
- */
- this.bb_pos = 0;
-};
-
-/**
- * @param {number} i
- * @param {flatbuffers.ByteBuffer} bb
- * @returns {MyGame.Example.Monster}
- */
-MyGame.Example.Monster.prototype.__init = function(i, bb) {
- this.bb_pos = i;
- this.bb = bb;
- return this;
-};
-
-/**
- * @param {flatbuffers.ByteBuffer} bb
- * @param {MyGame.Example.Monster=} obj
- * @returns {MyGame.Example.Monster}
- */
-MyGame.Example.Monster.getRootAsMonster = function(bb, obj) {
- return (obj || new MyGame.Example.Monster).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param {flatbuffers.ByteBuffer} bb
- * @param {MyGame.Example.Monster=} obj
- * @returns {MyGame.Example.Monster}
- */
-MyGame.Example.Monster.getSizePrefixedRootAsMonster = function(bb, obj) {
- bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
- return (obj || new MyGame.Example.Monster).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param {flatbuffers.ByteBuffer} bb
- * @returns {boolean}
- */
-MyGame.Example.Monster.bufferHasIdentifier = function(bb) {
- return bb.__has_identifier('MONS');
-};
-
-/**
- * @param {MyGame.Example.Vec3=} obj
- * @returns {MyGame.Example.Vec3|null}
- */
-MyGame.Example.Monster.prototype.pos = function(obj) {
- var offset = this.bb.__offset(this.bb_pos, 4);
- return offset ? (obj || new MyGame.Example.Vec3).__init(this.bb_pos + offset, this.bb) : null;
-};
-
-/**
- * @returns {number}
- */
-MyGame.Example.Monster.prototype.mana = function() {
- var offset = this.bb.__offset(this.bb_pos, 6);
- return offset ? this.bb.readInt16(this.bb_pos + offset) : 150;
-};
-
-/**
- * @param {number} value
- * @returns {boolean}
- */
-MyGame.Example.Monster.prototype.mutate_mana = function(value) {
- var offset = this.bb.__offset(this.bb_pos, 6);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb.writeInt16(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @returns {number}
- */
-MyGame.Example.Monster.prototype.hp = function() {
- var offset = this.bb.__offset(this.bb_pos, 8);
- return offset ? this.bb.readInt16(this.bb_pos + offset) : 100;
-};
-
-/**
- * @param {number} value
- * @returns {boolean}
- */
-MyGame.Example.Monster.prototype.mutate_hp = function(value) {
- var offset = this.bb.__offset(this.bb_pos, 8);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb.writeInt16(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @param {flatbuffers.Encoding=} optionalEncoding
- * @returns {string|Uint8Array|null}
- */
-MyGame.Example.Monster.prototype.name = function(optionalEncoding) {
- var offset = this.bb.__offset(this.bb_pos, 10);
- return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
-};
-
-/**
- * @param {number} index
- * @returns {number}
- */
-MyGame.Example.Monster.prototype.inventory = function(index) {
- var offset = this.bb.__offset(this.bb_pos, 14);
- return offset ? this.bb.readUint8(this.bb.__vector(this.bb_pos + offset) + index) : 0;
-};
-
-/**
- * @returns {number}
- */
-MyGame.Example.Monster.prototype.inventoryLength = function() {
- var offset = this.bb.__offset(this.bb_pos, 14);
- return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
-};
-
-/**
- * @returns {Uint8Array}
- */
-MyGame.Example.Monster.prototype.inventoryArray = function() {
- var offset = this.bb.__offset(this.bb_pos, 14);
- return offset ? new Uint8Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null;
-};
-
-/**
- * @returns {MyGame.Example.Color}
- */
-MyGame.Example.Monster.prototype.color = function() {
- var offset = this.bb.__offset(this.bb_pos, 16);
- return offset ? /** @type {MyGame.Example.Color} */ (this.bb.readUint8(this.bb_pos + offset)) : MyGame.Example.Color.Blue;
-};
-
-/**
- * @param {MyGame.Example.Color} value
- * @returns {boolean}
- */
-MyGame.Example.Monster.prototype.mutate_color = function(value) {
- var offset = this.bb.__offset(this.bb_pos, 16);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb.writeUint8(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @returns {MyGame.Example.Any}
- */
-MyGame.Example.Monster.prototype.testType = function() {
- var offset = this.bb.__offset(this.bb_pos, 18);
- return offset ? /** @type {MyGame.Example.Any} */ (this.bb.readUint8(this.bb_pos + offset)) : MyGame.Example.Any.NONE;
-};
-
-/**
- * @param {flatbuffers.Table} obj
- * @returns {?flatbuffers.Table}
- */
-MyGame.Example.Monster.prototype.test = function(obj) {
- var offset = this.bb.__offset(this.bb_pos, 20);
- return offset ? this.bb.__union(obj, this.bb_pos + offset) : null;
-};
-
-/**
- * @param {number} index
- * @param {MyGame.Example.Test=} obj
- * @returns {MyGame.Example.Test}
- */
-MyGame.Example.Monster.prototype.test4 = function(index, obj) {
- var offset = this.bb.__offset(this.bb_pos, 22);
- return offset ? (obj || new MyGame.Example.Test).__init(this.bb.__vector(this.bb_pos + offset) + index * 4, this.bb) : null;
-};
-
-/**
- * @returns {number}
- */
-MyGame.Example.Monster.prototype.test4Length = function() {
- var offset = this.bb.__offset(this.bb_pos, 22);
- return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
-};
-
-/**
- * @param {number} index
- * @param {flatbuffers.Encoding=} optionalEncoding
- * @returns {string|Uint8Array}
- */
-MyGame.Example.Monster.prototype.testarrayofstring = function(index, optionalEncoding) {
- var offset = this.bb.__offset(this.bb_pos, 24);
- return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null;
-};
-
-/**
- * @returns {number}
- */
-MyGame.Example.Monster.prototype.testarrayofstringLength = function() {
- var offset = this.bb.__offset(this.bb_pos, 24);
- return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
-};
-
-/**
- * an example documentation comment: this will end up in the generated code
- * multiline too
- *
- * @param {number} index
- * @param {MyGame.Example.Monster=} obj
- * @returns {MyGame.Example.Monster}
- */
-MyGame.Example.Monster.prototype.testarrayoftables = function(index, obj) {
- var offset = this.bb.__offset(this.bb_pos, 26);
- return offset ? (obj || new MyGame.Example.Monster).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null;
-};
-
-/**
- * @returns {number}
- */
-MyGame.Example.Monster.prototype.testarrayoftablesLength = function() {
- var offset = this.bb.__offset(this.bb_pos, 26);
- return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
-};
-
-/**
- * @param {MyGame.Example.Monster=} obj
- * @returns {MyGame.Example.Monster|null}
- */
-MyGame.Example.Monster.prototype.enemy = function(obj) {
- var offset = this.bb.__offset(this.bb_pos, 28);
- return offset ? (obj || new MyGame.Example.Monster).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null;
-};
-
-/**
- * @param {number} index
- * @returns {number}
- */
-MyGame.Example.Monster.prototype.testnestedflatbuffer = function(index) {
- var offset = this.bb.__offset(this.bb_pos, 30);
- return offset ? this.bb.readUint8(this.bb.__vector(this.bb_pos + offset) + index) : 0;
-};
-
-/**
- * @returns {number}
- */
-MyGame.Example.Monster.prototype.testnestedflatbufferLength = function() {
- var offset = this.bb.__offset(this.bb_pos, 30);
- return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
-};
-
-/**
- * @returns {Uint8Array}
- */
-MyGame.Example.Monster.prototype.testnestedflatbufferArray = function() {
- var offset = this.bb.__offset(this.bb_pos, 30);
- return offset ? new Uint8Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null;
-};
-
-/**
- * @param {MyGame.Example.Stat=} obj
- * @returns {MyGame.Example.Stat|null}
- */
-MyGame.Example.Monster.prototype.testempty = function(obj) {
- var offset = this.bb.__offset(this.bb_pos, 32);
- return offset ? (obj || new MyGame.Example.Stat).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null;
-};
-
-/**
- * @returns {boolean}
- */
-MyGame.Example.Monster.prototype.testbool = function() {
- var offset = this.bb.__offset(this.bb_pos, 34);
- return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false;
-};
-
-/**
- * @param {boolean} value
- * @returns {boolean}
- */
-MyGame.Example.Monster.prototype.mutate_testbool = function(value) {
- var offset = this.bb.__offset(this.bb_pos, 34);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb.writeInt8(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @returns {number}
- */
-MyGame.Example.Monster.prototype.testhashs32Fnv1 = function() {
- var offset = this.bb.__offset(this.bb_pos, 36);
- return offset ? this.bb.readInt32(this.bb_pos + offset) : 0;
-};
-
-/**
- * @param {number} value
- * @returns {boolean}
- */
-MyGame.Example.Monster.prototype.mutate_testhashs32_fnv1 = function(value) {
- var offset = this.bb.__offset(this.bb_pos, 36);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb.writeInt32(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @returns {number}
- */
-MyGame.Example.Monster.prototype.testhashu32Fnv1 = function() {
- var offset = this.bb.__offset(this.bb_pos, 38);
- return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
-};
-
-/**
- * @param {number} value
- * @returns {boolean}
- */
-MyGame.Example.Monster.prototype.mutate_testhashu32_fnv1 = function(value) {
- var offset = this.bb.__offset(this.bb_pos, 38);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb.writeUint32(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @returns {flatbuffers.Long}
- */
-MyGame.Example.Monster.prototype.testhashs64Fnv1 = function() {
- var offset = this.bb.__offset(this.bb_pos, 40);
- return offset ? this.bb.readInt64(this.bb_pos + offset) : this.bb.createLong(0, 0);
-};
-
-/**
- * @param {flatbuffers.Long} value
- * @returns {boolean}
- */
-MyGame.Example.Monster.prototype.mutate_testhashs64_fnv1 = function(value) {
- var offset = this.bb.__offset(this.bb_pos, 40);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb.writeInt64(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @returns {flatbuffers.Long}
- */
-MyGame.Example.Monster.prototype.testhashu64Fnv1 = function() {
- var offset = this.bb.__offset(this.bb_pos, 42);
- return offset ? this.bb.readUint64(this.bb_pos + offset) : this.bb.createLong(0, 0);
-};
-
-/**
- * @param {flatbuffers.Long} value
- * @returns {boolean}
- */
-MyGame.Example.Monster.prototype.mutate_testhashu64_fnv1 = function(value) {
- var offset = this.bb.__offset(this.bb_pos, 42);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb.writeUint64(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @returns {number}
- */
-MyGame.Example.Monster.prototype.testhashs32Fnv1a = function() {
- var offset = this.bb.__offset(this.bb_pos, 44);
- return offset ? this.bb.readInt32(this.bb_pos + offset) : 0;
-};
-
-/**
- * @param {number} value
- * @returns {boolean}
- */
-MyGame.Example.Monster.prototype.mutate_testhashs32_fnv1a = function(value) {
- var offset = this.bb.__offset(this.bb_pos, 44);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb.writeInt32(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @returns {number}
- */
-MyGame.Example.Monster.prototype.testhashu32Fnv1a = function() {
- var offset = this.bb.__offset(this.bb_pos, 46);
- return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
-};
-
-/**
- * @param {number} value
- * @returns {boolean}
- */
-MyGame.Example.Monster.prototype.mutate_testhashu32_fnv1a = function(value) {
- var offset = this.bb.__offset(this.bb_pos, 46);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb.writeUint32(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @returns {flatbuffers.Long}
- */
-MyGame.Example.Monster.prototype.testhashs64Fnv1a = function() {
- var offset = this.bb.__offset(this.bb_pos, 48);
- return offset ? this.bb.readInt64(this.bb_pos + offset) : this.bb.createLong(0, 0);
-};
-
-/**
- * @param {flatbuffers.Long} value
- * @returns {boolean}
- */
-MyGame.Example.Monster.prototype.mutate_testhashs64_fnv1a = function(value) {
- var offset = this.bb.__offset(this.bb_pos, 48);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb.writeInt64(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @returns {flatbuffers.Long}
- */
-MyGame.Example.Monster.prototype.testhashu64Fnv1a = function() {
- var offset = this.bb.__offset(this.bb_pos, 50);
- return offset ? this.bb.readUint64(this.bb_pos + offset) : this.bb.createLong(0, 0);
-};
-
-/**
- * @param {flatbuffers.Long} value
- * @returns {boolean}
- */
-MyGame.Example.Monster.prototype.mutate_testhashu64_fnv1a = function(value) {
- var offset = this.bb.__offset(this.bb_pos, 50);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb.writeUint64(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @param {number} index
- * @returns {boolean}
- */
-MyGame.Example.Monster.prototype.testarrayofbools = function(index) {
- var offset = this.bb.__offset(this.bb_pos, 52);
- return offset ? !!this.bb.readInt8(this.bb.__vector(this.bb_pos + offset) + index) : false;
-};
-
-/**
- * @returns {number}
- */
-MyGame.Example.Monster.prototype.testarrayofboolsLength = function() {
- var offset = this.bb.__offset(this.bb_pos, 52);
- return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
-};
-
-/**
- * @returns {Int8Array}
- */
-MyGame.Example.Monster.prototype.testarrayofboolsArray = function() {
- var offset = this.bb.__offset(this.bb_pos, 52);
- return offset ? new Int8Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null;
-};
-
-/**
- * @returns {number}
- */
-MyGame.Example.Monster.prototype.testf = function() {
- var offset = this.bb.__offset(this.bb_pos, 54);
- return offset ? this.bb.readFloat32(this.bb_pos + offset) : 3.14159;
-};
-
-/**
- * @param {number} value
- * @returns {boolean}
- */
-MyGame.Example.Monster.prototype.mutate_testf = function(value) {
- var offset = this.bb.__offset(this.bb_pos, 54);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb.writeFloat32(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @returns {number}
- */
-MyGame.Example.Monster.prototype.testf2 = function() {
- var offset = this.bb.__offset(this.bb_pos, 56);
- return offset ? this.bb.readFloat32(this.bb_pos + offset) : 3.0;
-};
-
-/**
- * @param {number} value
- * @returns {boolean}
- */
-MyGame.Example.Monster.prototype.mutate_testf2 = function(value) {
- var offset = this.bb.__offset(this.bb_pos, 56);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb.writeFloat32(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @returns {number}
- */
-MyGame.Example.Monster.prototype.testf3 = function() {
- var offset = this.bb.__offset(this.bb_pos, 58);
- return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0.0;
-};
-
-/**
- * @param {number} value
- * @returns {boolean}
- */
-MyGame.Example.Monster.prototype.mutate_testf3 = function(value) {
- var offset = this.bb.__offset(this.bb_pos, 58);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb.writeFloat32(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @param {number} index
- * @param {flatbuffers.Encoding=} optionalEncoding
- * @returns {string|Uint8Array}
- */
-MyGame.Example.Monster.prototype.testarrayofstring2 = function(index, optionalEncoding) {
- var offset = this.bb.__offset(this.bb_pos, 60);
- return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null;
-};
-
-/**
- * @returns {number}
- */
-MyGame.Example.Monster.prototype.testarrayofstring2Length = function() {
- var offset = this.bb.__offset(this.bb_pos, 60);
- return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
-};
-
-/**
- * @param {number} index
- * @param {MyGame.Example.Ability=} obj
- * @returns {MyGame.Example.Ability}
- */
-MyGame.Example.Monster.prototype.testarrayofsortedstruct = function(index, obj) {
- var offset = this.bb.__offset(this.bb_pos, 62);
- return offset ? (obj || new MyGame.Example.Ability).__init(this.bb.__vector(this.bb_pos + offset) + index * 8, this.bb) : null;
-};
-
-/**
- * @returns {number}
- */
-MyGame.Example.Monster.prototype.testarrayofsortedstructLength = function() {
- var offset = this.bb.__offset(this.bb_pos, 62);
- return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
-};
-
-/**
- * @param {number} index
- * @returns {number}
- */
-MyGame.Example.Monster.prototype.flex = function(index) {
- var offset = this.bb.__offset(this.bb_pos, 64);
- return offset ? this.bb.readUint8(this.bb.__vector(this.bb_pos + offset) + index) : 0;
-};
-
-/**
- * @returns {number}
- */
-MyGame.Example.Monster.prototype.flexLength = function() {
- var offset = this.bb.__offset(this.bb_pos, 64);
- return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
-};
-
-/**
- * @returns {Uint8Array}
- */
-MyGame.Example.Monster.prototype.flexArray = function() {
- var offset = this.bb.__offset(this.bb_pos, 64);
- return offset ? new Uint8Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null;
-};
-
-/**
- * @param {number} index
- * @param {MyGame.Example.Test=} obj
- * @returns {MyGame.Example.Test}
- */
-MyGame.Example.Monster.prototype.test5 = function(index, obj) {
- var offset = this.bb.__offset(this.bb_pos, 66);
- return offset ? (obj || new MyGame.Example.Test).__init(this.bb.__vector(this.bb_pos + offset) + index * 4, this.bb) : null;
-};
-
-/**
- * @returns {number}
- */
-MyGame.Example.Monster.prototype.test5Length = function() {
- var offset = this.bb.__offset(this.bb_pos, 66);
- return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
-};
-
-/**
- * @param {number} index
- * @returns {flatbuffers.Long}
- */
-MyGame.Example.Monster.prototype.vectorOfLongs = function(index) {
- var offset = this.bb.__offset(this.bb_pos, 68);
- return offset ? this.bb.readInt64(this.bb.__vector(this.bb_pos + offset) + index * 8) : this.bb.createLong(0, 0);
-};
-
-/**
- * @returns {number}
- */
-MyGame.Example.Monster.prototype.vectorOfLongsLength = function() {
- var offset = this.bb.__offset(this.bb_pos, 68);
- return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
-};
-
-/**
- * @param {number} index
- * @returns {number}
- */
-MyGame.Example.Monster.prototype.vectorOfDoubles = function(index) {
- var offset = this.bb.__offset(this.bb_pos, 70);
- return offset ? this.bb.readFloat64(this.bb.__vector(this.bb_pos + offset) + index * 8) : 0;
-};
-
-/**
- * @returns {number}
- */
-MyGame.Example.Monster.prototype.vectorOfDoublesLength = function() {
- var offset = this.bb.__offset(this.bb_pos, 70);
- return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
-};
-
-/**
- * @returns {Float64Array}
- */
-MyGame.Example.Monster.prototype.vectorOfDoublesArray = function() {
- var offset = this.bb.__offset(this.bb_pos, 70);
- return offset ? new Float64Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null;
-};
-
-/**
- * @param {MyGame.InParentNamespace=} obj
- * @returns {MyGame.InParentNamespace|null}
- */
-MyGame.Example.Monster.prototype.parentNamespaceTest = function(obj) {
- var offset = this.bb.__offset(this.bb_pos, 72);
- return offset ? (obj || new MyGame.InParentNamespace).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null;
-};
-
-/**
- * @param {number} index
- * @param {MyGame.Example.Referrable=} obj
- * @returns {MyGame.Example.Referrable}
- */
-MyGame.Example.Monster.prototype.vectorOfReferrables = function(index, obj) {
- var offset = this.bb.__offset(this.bb_pos, 74);
- return offset ? (obj || new MyGame.Example.Referrable).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null;
-};
-
-/**
- * @returns {number}
- */
-MyGame.Example.Monster.prototype.vectorOfReferrablesLength = function() {
- var offset = this.bb.__offset(this.bb_pos, 74);
- return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
-};
-
-/**
- * @returns {flatbuffers.Long}
- */
-MyGame.Example.Monster.prototype.singleWeakReference = function() {
- var offset = this.bb.__offset(this.bb_pos, 76);
- return offset ? this.bb.readUint64(this.bb_pos + offset) : this.bb.createLong(0, 0);
-};
-
-/**
- * @param {flatbuffers.Long} value
- * @returns {boolean}
- */
-MyGame.Example.Monster.prototype.mutate_single_weak_reference = function(value) {
- var offset = this.bb.__offset(this.bb_pos, 76);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb.writeUint64(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @param {number} index
- * @returns {flatbuffers.Long}
- */
-MyGame.Example.Monster.prototype.vectorOfWeakReferences = function(index) {
- var offset = this.bb.__offset(this.bb_pos, 78);
- return offset ? this.bb.readUint64(this.bb.__vector(this.bb_pos + offset) + index * 8) : this.bb.createLong(0, 0);
-};
-
-/**
- * @returns {number}
- */
-MyGame.Example.Monster.prototype.vectorOfWeakReferencesLength = function() {
- var offset = this.bb.__offset(this.bb_pos, 78);
- return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
-};
-
-/**
- * @param {number} index
- * @param {MyGame.Example.Referrable=} obj
- * @returns {MyGame.Example.Referrable}
- */
-MyGame.Example.Monster.prototype.vectorOfStrongReferrables = function(index, obj) {
- var offset = this.bb.__offset(this.bb_pos, 80);
- return offset ? (obj || new MyGame.Example.Referrable).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null;
-};
-
-/**
- * @returns {number}
- */
-MyGame.Example.Monster.prototype.vectorOfStrongReferrablesLength = function() {
- var offset = this.bb.__offset(this.bb_pos, 80);
- return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
-};
-
-/**
- * @returns {flatbuffers.Long}
- */
-MyGame.Example.Monster.prototype.coOwningReference = function() {
- var offset = this.bb.__offset(this.bb_pos, 82);
- return offset ? this.bb.readUint64(this.bb_pos + offset) : this.bb.createLong(0, 0);
-};
-
-/**
- * @param {flatbuffers.Long} value
- * @returns {boolean}
- */
-MyGame.Example.Monster.prototype.mutate_co_owning_reference = function(value) {
- var offset = this.bb.__offset(this.bb_pos, 82);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb.writeUint64(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @param {number} index
- * @returns {flatbuffers.Long}
- */
-MyGame.Example.Monster.prototype.vectorOfCoOwningReferences = function(index) {
- var offset = this.bb.__offset(this.bb_pos, 84);
- return offset ? this.bb.readUint64(this.bb.__vector(this.bb_pos + offset) + index * 8) : this.bb.createLong(0, 0);
-};
-
-/**
- * @returns {number}
- */
-MyGame.Example.Monster.prototype.vectorOfCoOwningReferencesLength = function() {
- var offset = this.bb.__offset(this.bb_pos, 84);
- return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
-};
-
-/**
- * @returns {flatbuffers.Long}
- */
-MyGame.Example.Monster.prototype.nonOwningReference = function() {
- var offset = this.bb.__offset(this.bb_pos, 86);
- return offset ? this.bb.readUint64(this.bb_pos + offset) : this.bb.createLong(0, 0);
-};
-
-/**
- * @param {flatbuffers.Long} value
- * @returns {boolean}
- */
-MyGame.Example.Monster.prototype.mutate_non_owning_reference = function(value) {
- var offset = this.bb.__offset(this.bb_pos, 86);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb.writeUint64(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @param {number} index
- * @returns {flatbuffers.Long}
- */
-MyGame.Example.Monster.prototype.vectorOfNonOwningReferences = function(index) {
- var offset = this.bb.__offset(this.bb_pos, 88);
- return offset ? this.bb.readUint64(this.bb.__vector(this.bb_pos + offset) + index * 8) : this.bb.createLong(0, 0);
-};
-
-/**
- * @returns {number}
- */
-MyGame.Example.Monster.prototype.vectorOfNonOwningReferencesLength = function() {
- var offset = this.bb.__offset(this.bb_pos, 88);
- return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
-};
-
-/**
- * @returns {MyGame.Example.AnyUniqueAliases}
- */
-MyGame.Example.Monster.prototype.anyUniqueType = function() {
- var offset = this.bb.__offset(this.bb_pos, 90);
- return offset ? /** @type {MyGame.Example.AnyUniqueAliases} */ (this.bb.readUint8(this.bb_pos + offset)) : MyGame.Example.AnyUniqueAliases.NONE;
-};
-
-/**
- * @param {flatbuffers.Table} obj
- * @returns {?flatbuffers.Table}
- */
-MyGame.Example.Monster.prototype.anyUnique = function(obj) {
- var offset = this.bb.__offset(this.bb_pos, 92);
- return offset ? this.bb.__union(obj, this.bb_pos + offset) : null;
-};
-
-/**
- * @returns {MyGame.Example.AnyAmbiguousAliases}
- */
-MyGame.Example.Monster.prototype.anyAmbiguousType = function() {
- var offset = this.bb.__offset(this.bb_pos, 94);
- return offset ? /** @type {MyGame.Example.AnyAmbiguousAliases} */ (this.bb.readUint8(this.bb_pos + offset)) : MyGame.Example.AnyAmbiguousAliases.NONE;
-};
-
-/**
- * @param {flatbuffers.Table} obj
- * @returns {?flatbuffers.Table}
- */
-MyGame.Example.Monster.prototype.anyAmbiguous = function(obj) {
- var offset = this.bb.__offset(this.bb_pos, 96);
- return offset ? this.bb.__union(obj, this.bb_pos + offset) : null;
-};
-
-/**
- * @param {number} index
- * @returns {MyGame.Example.Color}
- */
-MyGame.Example.Monster.prototype.vectorOfEnums = function(index) {
- var offset = this.bb.__offset(this.bb_pos, 98);
- return offset ? /** @type {MyGame.Example.Color} */ (this.bb.readUint8(this.bb.__vector(this.bb_pos + offset) + index)) : /** @type {MyGame.Example.Color} */ (0);
-};
-
-/**
- * @returns {number}
- */
-MyGame.Example.Monster.prototype.vectorOfEnumsLength = function() {
- var offset = this.bb.__offset(this.bb_pos, 98);
- return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
-};
-
-/**
- * @returns {Uint8Array}
- */
-MyGame.Example.Monster.prototype.vectorOfEnumsArray = function() {
- var offset = this.bb.__offset(this.bb_pos, 98);
- return offset ? new Uint8Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null;
-};
-
-/**
- * @returns {MyGame.Example.Race}
- */
-MyGame.Example.Monster.prototype.signedEnum = function() {
- var offset = this.bb.__offset(this.bb_pos, 100);
- return offset ? /** @type {MyGame.Example.Race} */ (this.bb.readInt8(this.bb_pos + offset)) : MyGame.Example.Race.None;
-};
-
-/**
- * @param {MyGame.Example.Race} value
- * @returns {boolean}
- */
-MyGame.Example.Monster.prototype.mutate_signed_enum = function(value) {
- var offset = this.bb.__offset(this.bb_pos, 100);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb.writeInt8(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @param {number} index
- * @returns {number}
- */
-MyGame.Example.Monster.prototype.testrequirednestedflatbuffer = function(index) {
- var offset = this.bb.__offset(this.bb_pos, 102);
- return offset ? this.bb.readUint8(this.bb.__vector(this.bb_pos + offset) + index) : 0;
-};
-
-/**
- * @returns {number}
- */
-MyGame.Example.Monster.prototype.testrequirednestedflatbufferLength = function() {
- var offset = this.bb.__offset(this.bb_pos, 102);
- return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
-};
-
-/**
- * @returns {Uint8Array}
- */
-MyGame.Example.Monster.prototype.testrequirednestedflatbufferArray = function() {
- var offset = this.bb.__offset(this.bb_pos, 102);
- return offset ? new Uint8Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null;
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- */
-MyGame.Example.Monster.startMonster = function(builder) {
- builder.startObject(50);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Offset} posOffset
- */
-MyGame.Example.Monster.addPos = function(builder, posOffset) {
- builder.addFieldStruct(0, posOffset, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} mana
- */
-MyGame.Example.Monster.addMana = function(builder, mana) {
- builder.addFieldInt16(1, mana, 150);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} hp
- */
-MyGame.Example.Monster.addHp = function(builder, hp) {
- builder.addFieldInt16(2, hp, 100);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Offset} nameOffset
- */
-MyGame.Example.Monster.addName = function(builder, nameOffset) {
- builder.addFieldOffset(3, nameOffset, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Offset} inventoryOffset
- */
-MyGame.Example.Monster.addInventory = function(builder, inventoryOffset) {
- builder.addFieldOffset(5, inventoryOffset, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {Array.<number>} data
- * @returns {flatbuffers.Offset}
- */
-MyGame.Example.Monster.createInventoryVector = function(builder, data) {
- builder.startVector(1, data.length, 1);
- for (var i = data.length - 1; i >= 0; i--) {
- builder.addInt8(data[i]);
- }
- return builder.endVector();
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} numElems
- */
-MyGame.Example.Monster.startInventoryVector = function(builder, numElems) {
- builder.startVector(1, numElems, 1);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {MyGame.Example.Color} color
- */
-MyGame.Example.Monster.addColor = function(builder, color) {
- builder.addFieldInt8(6, color, MyGame.Example.Color.Blue);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {MyGame.Example.Any} testType
- */
-MyGame.Example.Monster.addTestType = function(builder, testType) {
- builder.addFieldInt8(7, testType, MyGame.Example.Any.NONE);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Offset} testOffset
- */
-MyGame.Example.Monster.addTest = function(builder, testOffset) {
- builder.addFieldOffset(8, testOffset, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Offset} test4Offset
- */
-MyGame.Example.Monster.addTest4 = function(builder, test4Offset) {
- builder.addFieldOffset(9, test4Offset, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} numElems
- */
-MyGame.Example.Monster.startTest4Vector = function(builder, numElems) {
- builder.startVector(4, numElems, 2);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Offset} testarrayofstringOffset
- */
-MyGame.Example.Monster.addTestarrayofstring = function(builder, testarrayofstringOffset) {
- builder.addFieldOffset(10, testarrayofstringOffset, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {Array.<flatbuffers.Offset>} data
- * @returns {flatbuffers.Offset}
- */
-MyGame.Example.Monster.createTestarrayofstringVector = function(builder, data) {
- builder.startVector(4, data.length, 4);
- for (var i = data.length - 1; i >= 0; i--) {
- builder.addOffset(data[i]);
- }
- return builder.endVector();
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} numElems
- */
-MyGame.Example.Monster.startTestarrayofstringVector = function(builder, numElems) {
- builder.startVector(4, numElems, 4);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Offset} testarrayoftablesOffset
- */
-MyGame.Example.Monster.addTestarrayoftables = function(builder, testarrayoftablesOffset) {
- builder.addFieldOffset(11, testarrayoftablesOffset, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {Array.<flatbuffers.Offset>} data
- * @returns {flatbuffers.Offset}
- */
-MyGame.Example.Monster.createTestarrayoftablesVector = function(builder, data) {
- builder.startVector(4, data.length, 4);
- for (var i = data.length - 1; i >= 0; i--) {
- builder.addOffset(data[i]);
- }
- return builder.endVector();
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} numElems
- */
-MyGame.Example.Monster.startTestarrayoftablesVector = function(builder, numElems) {
- builder.startVector(4, numElems, 4);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Offset} enemyOffset
- */
-MyGame.Example.Monster.addEnemy = function(builder, enemyOffset) {
- builder.addFieldOffset(12, enemyOffset, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Offset} testnestedflatbufferOffset
- */
-MyGame.Example.Monster.addTestnestedflatbuffer = function(builder, testnestedflatbufferOffset) {
- builder.addFieldOffset(13, testnestedflatbufferOffset, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {Array.<number>} data
- * @returns {flatbuffers.Offset}
- */
-MyGame.Example.Monster.createTestnestedflatbufferVector = function(builder, data) {
- builder.startVector(1, data.length, 1);
- for (var i = data.length - 1; i >= 0; i--) {
- builder.addInt8(data[i]);
- }
- return builder.endVector();
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} numElems
- */
-MyGame.Example.Monster.startTestnestedflatbufferVector = function(builder, numElems) {
- builder.startVector(1, numElems, 1);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Offset} testemptyOffset
- */
-MyGame.Example.Monster.addTestempty = function(builder, testemptyOffset) {
- builder.addFieldOffset(14, testemptyOffset, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {boolean} testbool
- */
-MyGame.Example.Monster.addTestbool = function(builder, testbool) {
- builder.addFieldInt8(15, +testbool, +false);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} testhashs32Fnv1
- */
-MyGame.Example.Monster.addTesthashs32Fnv1 = function(builder, testhashs32Fnv1) {
- builder.addFieldInt32(16, testhashs32Fnv1, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} testhashu32Fnv1
- */
-MyGame.Example.Monster.addTesthashu32Fnv1 = function(builder, testhashu32Fnv1) {
- builder.addFieldInt32(17, testhashu32Fnv1, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Long} testhashs64Fnv1
- */
-MyGame.Example.Monster.addTesthashs64Fnv1 = function(builder, testhashs64Fnv1) {
- builder.addFieldInt64(18, testhashs64Fnv1, builder.createLong(0, 0));
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Long} testhashu64Fnv1
- */
-MyGame.Example.Monster.addTesthashu64Fnv1 = function(builder, testhashu64Fnv1) {
- builder.addFieldInt64(19, testhashu64Fnv1, builder.createLong(0, 0));
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} testhashs32Fnv1a
- */
-MyGame.Example.Monster.addTesthashs32Fnv1a = function(builder, testhashs32Fnv1a) {
- builder.addFieldInt32(20, testhashs32Fnv1a, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} testhashu32Fnv1a
- */
-MyGame.Example.Monster.addTesthashu32Fnv1a = function(builder, testhashu32Fnv1a) {
- builder.addFieldInt32(21, testhashu32Fnv1a, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Long} testhashs64Fnv1a
- */
-MyGame.Example.Monster.addTesthashs64Fnv1a = function(builder, testhashs64Fnv1a) {
- builder.addFieldInt64(22, testhashs64Fnv1a, builder.createLong(0, 0));
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Long} testhashu64Fnv1a
- */
-MyGame.Example.Monster.addTesthashu64Fnv1a = function(builder, testhashu64Fnv1a) {
- builder.addFieldInt64(23, testhashu64Fnv1a, builder.createLong(0, 0));
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Offset} testarrayofboolsOffset
- */
-MyGame.Example.Monster.addTestarrayofbools = function(builder, testarrayofboolsOffset) {
- builder.addFieldOffset(24, testarrayofboolsOffset, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {Array.<boolean>} data
- * @returns {flatbuffers.Offset}
- */
-MyGame.Example.Monster.createTestarrayofboolsVector = function(builder, data) {
- builder.startVector(1, data.length, 1);
- for (var i = data.length - 1; i >= 0; i--) {
- builder.addInt8(+data[i]);
- }
- return builder.endVector();
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} numElems
- */
-MyGame.Example.Monster.startTestarrayofboolsVector = function(builder, numElems) {
- builder.startVector(1, numElems, 1);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} testf
- */
-MyGame.Example.Monster.addTestf = function(builder, testf) {
- builder.addFieldFloat32(25, testf, 3.14159);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} testf2
- */
-MyGame.Example.Monster.addTestf2 = function(builder, testf2) {
- builder.addFieldFloat32(26, testf2, 3.0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} testf3
- */
-MyGame.Example.Monster.addTestf3 = function(builder, testf3) {
- builder.addFieldFloat32(27, testf3, 0.0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Offset} testarrayofstring2Offset
- */
-MyGame.Example.Monster.addTestarrayofstring2 = function(builder, testarrayofstring2Offset) {
- builder.addFieldOffset(28, testarrayofstring2Offset, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {Array.<flatbuffers.Offset>} data
- * @returns {flatbuffers.Offset}
- */
-MyGame.Example.Monster.createTestarrayofstring2Vector = function(builder, data) {
- builder.startVector(4, data.length, 4);
- for (var i = data.length - 1; i >= 0; i--) {
- builder.addOffset(data[i]);
- }
- return builder.endVector();
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} numElems
- */
-MyGame.Example.Monster.startTestarrayofstring2Vector = function(builder, numElems) {
- builder.startVector(4, numElems, 4);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Offset} testarrayofsortedstructOffset
- */
-MyGame.Example.Monster.addTestarrayofsortedstruct = function(builder, testarrayofsortedstructOffset) {
- builder.addFieldOffset(29, testarrayofsortedstructOffset, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} numElems
- */
-MyGame.Example.Monster.startTestarrayofsortedstructVector = function(builder, numElems) {
- builder.startVector(8, numElems, 4);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Offset} flexOffset
- */
-MyGame.Example.Monster.addFlex = function(builder, flexOffset) {
- builder.addFieldOffset(30, flexOffset, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {Array.<number>} data
- * @returns {flatbuffers.Offset}
- */
-MyGame.Example.Monster.createFlexVector = function(builder, data) {
- builder.startVector(1, data.length, 1);
- for (var i = data.length - 1; i >= 0; i--) {
- builder.addInt8(data[i]);
- }
- return builder.endVector();
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} numElems
- */
-MyGame.Example.Monster.startFlexVector = function(builder, numElems) {
- builder.startVector(1, numElems, 1);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Offset} test5Offset
- */
-MyGame.Example.Monster.addTest5 = function(builder, test5Offset) {
- builder.addFieldOffset(31, test5Offset, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} numElems
- */
-MyGame.Example.Monster.startTest5Vector = function(builder, numElems) {
- builder.startVector(4, numElems, 2);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Offset} vectorOfLongsOffset
- */
-MyGame.Example.Monster.addVectorOfLongs = function(builder, vectorOfLongsOffset) {
- builder.addFieldOffset(32, vectorOfLongsOffset, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {Array.<flatbuffers.Long>} data
- * @returns {flatbuffers.Offset}
- */
-MyGame.Example.Monster.createVectorOfLongsVector = function(builder, data) {
- builder.startVector(8, data.length, 8);
- for (var i = data.length - 1; i >= 0; i--) {
- builder.addInt64(data[i]);
- }
- return builder.endVector();
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} numElems
- */
-MyGame.Example.Monster.startVectorOfLongsVector = function(builder, numElems) {
- builder.startVector(8, numElems, 8);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Offset} vectorOfDoublesOffset
- */
-MyGame.Example.Monster.addVectorOfDoubles = function(builder, vectorOfDoublesOffset) {
- builder.addFieldOffset(33, vectorOfDoublesOffset, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {Array.<number>} data
- * @returns {flatbuffers.Offset}
- */
-MyGame.Example.Monster.createVectorOfDoublesVector = function(builder, data) {
- builder.startVector(8, data.length, 8);
- for (var i = data.length - 1; i >= 0; i--) {
- builder.addFloat64(data[i]);
- }
- return builder.endVector();
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} numElems
- */
-MyGame.Example.Monster.startVectorOfDoublesVector = function(builder, numElems) {
- builder.startVector(8, numElems, 8);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Offset} parentNamespaceTestOffset
- */
-MyGame.Example.Monster.addParentNamespaceTest = function(builder, parentNamespaceTestOffset) {
- builder.addFieldOffset(34, parentNamespaceTestOffset, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Offset} vectorOfReferrablesOffset
- */
-MyGame.Example.Monster.addVectorOfReferrables = function(builder, vectorOfReferrablesOffset) {
- builder.addFieldOffset(35, vectorOfReferrablesOffset, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {Array.<flatbuffers.Offset>} data
- * @returns {flatbuffers.Offset}
- */
-MyGame.Example.Monster.createVectorOfReferrablesVector = function(builder, data) {
- builder.startVector(4, data.length, 4);
- for (var i = data.length - 1; i >= 0; i--) {
- builder.addOffset(data[i]);
- }
- return builder.endVector();
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} numElems
- */
-MyGame.Example.Monster.startVectorOfReferrablesVector = function(builder, numElems) {
- builder.startVector(4, numElems, 4);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Long} singleWeakReference
- */
-MyGame.Example.Monster.addSingleWeakReference = function(builder, singleWeakReference) {
- builder.addFieldInt64(36, singleWeakReference, builder.createLong(0, 0));
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Offset} vectorOfWeakReferencesOffset
- */
-MyGame.Example.Monster.addVectorOfWeakReferences = function(builder, vectorOfWeakReferencesOffset) {
- builder.addFieldOffset(37, vectorOfWeakReferencesOffset, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {Array.<flatbuffers.Long>} data
- * @returns {flatbuffers.Offset}
- */
-MyGame.Example.Monster.createVectorOfWeakReferencesVector = function(builder, data) {
- builder.startVector(8, data.length, 8);
- for (var i = data.length - 1; i >= 0; i--) {
- builder.addInt64(data[i]);
- }
- return builder.endVector();
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} numElems
- */
-MyGame.Example.Monster.startVectorOfWeakReferencesVector = function(builder, numElems) {
- builder.startVector(8, numElems, 8);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Offset} vectorOfStrongReferrablesOffset
- */
-MyGame.Example.Monster.addVectorOfStrongReferrables = function(builder, vectorOfStrongReferrablesOffset) {
- builder.addFieldOffset(38, vectorOfStrongReferrablesOffset, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {Array.<flatbuffers.Offset>} data
- * @returns {flatbuffers.Offset}
- */
-MyGame.Example.Monster.createVectorOfStrongReferrablesVector = function(builder, data) {
- builder.startVector(4, data.length, 4);
- for (var i = data.length - 1; i >= 0; i--) {
- builder.addOffset(data[i]);
- }
- return builder.endVector();
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} numElems
- */
-MyGame.Example.Monster.startVectorOfStrongReferrablesVector = function(builder, numElems) {
- builder.startVector(4, numElems, 4);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Long} coOwningReference
- */
-MyGame.Example.Monster.addCoOwningReference = function(builder, coOwningReference) {
- builder.addFieldInt64(39, coOwningReference, builder.createLong(0, 0));
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Offset} vectorOfCoOwningReferencesOffset
- */
-MyGame.Example.Monster.addVectorOfCoOwningReferences = function(builder, vectorOfCoOwningReferencesOffset) {
- builder.addFieldOffset(40, vectorOfCoOwningReferencesOffset, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {Array.<flatbuffers.Long>} data
- * @returns {flatbuffers.Offset}
- */
-MyGame.Example.Monster.createVectorOfCoOwningReferencesVector = function(builder, data) {
- builder.startVector(8, data.length, 8);
- for (var i = data.length - 1; i >= 0; i--) {
- builder.addInt64(data[i]);
- }
- return builder.endVector();
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} numElems
- */
-MyGame.Example.Monster.startVectorOfCoOwningReferencesVector = function(builder, numElems) {
- builder.startVector(8, numElems, 8);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Long} nonOwningReference
- */
-MyGame.Example.Monster.addNonOwningReference = function(builder, nonOwningReference) {
- builder.addFieldInt64(41, nonOwningReference, builder.createLong(0, 0));
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Offset} vectorOfNonOwningReferencesOffset
- */
-MyGame.Example.Monster.addVectorOfNonOwningReferences = function(builder, vectorOfNonOwningReferencesOffset) {
- builder.addFieldOffset(42, vectorOfNonOwningReferencesOffset, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {Array.<flatbuffers.Long>} data
- * @returns {flatbuffers.Offset}
- */
-MyGame.Example.Monster.createVectorOfNonOwningReferencesVector = function(builder, data) {
- builder.startVector(8, data.length, 8);
- for (var i = data.length - 1; i >= 0; i--) {
- builder.addInt64(data[i]);
- }
- return builder.endVector();
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} numElems
- */
-MyGame.Example.Monster.startVectorOfNonOwningReferencesVector = function(builder, numElems) {
- builder.startVector(8, numElems, 8);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {MyGame.Example.AnyUniqueAliases} anyUniqueType
- */
-MyGame.Example.Monster.addAnyUniqueType = function(builder, anyUniqueType) {
- builder.addFieldInt8(43, anyUniqueType, MyGame.Example.AnyUniqueAliases.NONE);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Offset} anyUniqueOffset
- */
-MyGame.Example.Monster.addAnyUnique = function(builder, anyUniqueOffset) {
- builder.addFieldOffset(44, anyUniqueOffset, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {MyGame.Example.AnyAmbiguousAliases} anyAmbiguousType
- */
-MyGame.Example.Monster.addAnyAmbiguousType = function(builder, anyAmbiguousType) {
- builder.addFieldInt8(45, anyAmbiguousType, MyGame.Example.AnyAmbiguousAliases.NONE);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Offset} anyAmbiguousOffset
- */
-MyGame.Example.Monster.addAnyAmbiguous = function(builder, anyAmbiguousOffset) {
- builder.addFieldOffset(46, anyAmbiguousOffset, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Offset} vectorOfEnumsOffset
- */
-MyGame.Example.Monster.addVectorOfEnums = function(builder, vectorOfEnumsOffset) {
- builder.addFieldOffset(47, vectorOfEnumsOffset, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {Array.<MyGame.Example.Color>} data
- * @returns {flatbuffers.Offset}
- */
-MyGame.Example.Monster.createVectorOfEnumsVector = function(builder, data) {
- builder.startVector(1, data.length, 1);
- for (var i = data.length - 1; i >= 0; i--) {
- builder.addInt8(data[i]);
- }
- return builder.endVector();
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} numElems
- */
-MyGame.Example.Monster.startVectorOfEnumsVector = function(builder, numElems) {
- builder.startVector(1, numElems, 1);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {MyGame.Example.Race} signedEnum
- */
-MyGame.Example.Monster.addSignedEnum = function(builder, signedEnum) {
- builder.addFieldInt8(48, signedEnum, MyGame.Example.Race.None);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Offset} testrequirednestedflatbufferOffset
- */
-MyGame.Example.Monster.addTestrequirednestedflatbuffer = function(builder, testrequirednestedflatbufferOffset) {
- builder.addFieldOffset(49, testrequirednestedflatbufferOffset, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {Array.<number>} data
- * @returns {flatbuffers.Offset}
- */
-MyGame.Example.Monster.createTestrequirednestedflatbufferVector = function(builder, data) {
- builder.startVector(1, data.length, 1);
- for (var i = data.length - 1; i >= 0; i--) {
- builder.addInt8(data[i]);
- }
- return builder.endVector();
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} numElems
- */
-MyGame.Example.Monster.startTestrequirednestedflatbufferVector = function(builder, numElems) {
- builder.startVector(1, numElems, 1);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @returns {flatbuffers.Offset}
- */
-MyGame.Example.Monster.endMonster = function(builder) {
- var offset = builder.endObject();
- builder.requiredField(offset, 10); // name
- return offset;
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Offset} offset
- */
-MyGame.Example.Monster.finishMonsterBuffer = function(builder, offset) {
- builder.finish(offset, 'MONS');
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Offset} offset
- */
-MyGame.Example.Monster.finishSizePrefixedMonsterBuffer = function(builder, offset) {
- builder.finish(offset, 'MONS', true);
-};
-
-/**
- * @constructor
- */
-MyGame.Example.TypeAliases = function() {
- /**
- * @type {flatbuffers.ByteBuffer}
- */
- this.bb = null;
-
- /**
- * @type {number}
- */
- this.bb_pos = 0;
-};
-
-/**
- * @param {number} i
- * @param {flatbuffers.ByteBuffer} bb
- * @returns {MyGame.Example.TypeAliases}
- */
-MyGame.Example.TypeAliases.prototype.__init = function(i, bb) {
- this.bb_pos = i;
- this.bb = bb;
- return this;
-};
-
-/**
- * @param {flatbuffers.ByteBuffer} bb
- * @param {MyGame.Example.TypeAliases=} obj
- * @returns {MyGame.Example.TypeAliases}
- */
-MyGame.Example.TypeAliases.getRootAsTypeAliases = function(bb, obj) {
- return (obj || new MyGame.Example.TypeAliases).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param {flatbuffers.ByteBuffer} bb
- * @param {MyGame.Example.TypeAliases=} obj
- * @returns {MyGame.Example.TypeAliases}
- */
-MyGame.Example.TypeAliases.getSizePrefixedRootAsTypeAliases = function(bb, obj) {
- bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
- return (obj || new MyGame.Example.TypeAliases).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @returns {number}
- */
-MyGame.Example.TypeAliases.prototype.i8 = function() {
- var offset = this.bb.__offset(this.bb_pos, 4);
- return offset ? this.bb.readInt8(this.bb_pos + offset) : 0;
-};
-
-/**
- * @param {number} value
- * @returns {boolean}
- */
-MyGame.Example.TypeAliases.prototype.mutate_i8 = function(value) {
- var offset = this.bb.__offset(this.bb_pos, 4);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb.writeInt8(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @returns {number}
- */
-MyGame.Example.TypeAliases.prototype.u8 = function() {
- var offset = this.bb.__offset(this.bb_pos, 6);
- return offset ? this.bb.readUint8(this.bb_pos + offset) : 0;
-};
-
-/**
- * @param {number} value
- * @returns {boolean}
- */
-MyGame.Example.TypeAliases.prototype.mutate_u8 = function(value) {
- var offset = this.bb.__offset(this.bb_pos, 6);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb.writeUint8(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @returns {number}
- */
-MyGame.Example.TypeAliases.prototype.i16 = function() {
- var offset = this.bb.__offset(this.bb_pos, 8);
- return offset ? this.bb.readInt16(this.bb_pos + offset) : 0;
-};
-
-/**
- * @param {number} value
- * @returns {boolean}
- */
-MyGame.Example.TypeAliases.prototype.mutate_i16 = function(value) {
- var offset = this.bb.__offset(this.bb_pos, 8);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb.writeInt16(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @returns {number}
- */
-MyGame.Example.TypeAliases.prototype.u16 = function() {
- var offset = this.bb.__offset(this.bb_pos, 10);
- return offset ? this.bb.readUint16(this.bb_pos + offset) : 0;
-};
-
-/**
- * @param {number} value
- * @returns {boolean}
- */
-MyGame.Example.TypeAliases.prototype.mutate_u16 = function(value) {
- var offset = this.bb.__offset(this.bb_pos, 10);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb.writeUint16(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @returns {number}
- */
-MyGame.Example.TypeAliases.prototype.i32 = function() {
- var offset = this.bb.__offset(this.bb_pos, 12);
- return offset ? this.bb.readInt32(this.bb_pos + offset) : 0;
-};
-
-/**
- * @param {number} value
- * @returns {boolean}
- */
-MyGame.Example.TypeAliases.prototype.mutate_i32 = function(value) {
- var offset = this.bb.__offset(this.bb_pos, 12);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb.writeInt32(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @returns {number}
- */
-MyGame.Example.TypeAliases.prototype.u32 = function() {
- var offset = this.bb.__offset(this.bb_pos, 14);
- return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
-};
-
-/**
- * @param {number} value
- * @returns {boolean}
- */
-MyGame.Example.TypeAliases.prototype.mutate_u32 = function(value) {
- var offset = this.bb.__offset(this.bb_pos, 14);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb.writeUint32(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @returns {flatbuffers.Long}
- */
-MyGame.Example.TypeAliases.prototype.i64 = function() {
- var offset = this.bb.__offset(this.bb_pos, 16);
- return offset ? this.bb.readInt64(this.bb_pos + offset) : this.bb.createLong(0, 0);
-};
-
-/**
- * @param {flatbuffers.Long} value
- * @returns {boolean}
- */
-MyGame.Example.TypeAliases.prototype.mutate_i64 = function(value) {
- var offset = this.bb.__offset(this.bb_pos, 16);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb.writeInt64(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @returns {flatbuffers.Long}
- */
-MyGame.Example.TypeAliases.prototype.u64 = function() {
- var offset = this.bb.__offset(this.bb_pos, 18);
- return offset ? this.bb.readUint64(this.bb_pos + offset) : this.bb.createLong(0, 0);
-};
-
-/**
- * @param {flatbuffers.Long} value
- * @returns {boolean}
- */
-MyGame.Example.TypeAliases.prototype.mutate_u64 = function(value) {
- var offset = this.bb.__offset(this.bb_pos, 18);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb.writeUint64(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @returns {number}
- */
-MyGame.Example.TypeAliases.prototype.f32 = function() {
- var offset = this.bb.__offset(this.bb_pos, 20);
- return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0.0;
-};
-
-/**
- * @param {number} value
- * @returns {boolean}
- */
-MyGame.Example.TypeAliases.prototype.mutate_f32 = function(value) {
- var offset = this.bb.__offset(this.bb_pos, 20);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb.writeFloat32(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @returns {number}
- */
-MyGame.Example.TypeAliases.prototype.f64 = function() {
- var offset = this.bb.__offset(this.bb_pos, 22);
- return offset ? this.bb.readFloat64(this.bb_pos + offset) : 0.0;
-};
-
-/**
- * @param {number} value
- * @returns {boolean}
- */
-MyGame.Example.TypeAliases.prototype.mutate_f64 = function(value) {
- var offset = this.bb.__offset(this.bb_pos, 22);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb.writeFloat64(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @param {number} index
- * @returns {number}
- */
-MyGame.Example.TypeAliases.prototype.v8 = function(index) {
- var offset = this.bb.__offset(this.bb_pos, 24);
- return offset ? this.bb.readInt8(this.bb.__vector(this.bb_pos + offset) + index) : 0;
-};
-
-/**
- * @returns {number}
- */
-MyGame.Example.TypeAliases.prototype.v8Length = function() {
- var offset = this.bb.__offset(this.bb_pos, 24);
- return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
-};
-
-/**
- * @returns {Int8Array}
- */
-MyGame.Example.TypeAliases.prototype.v8Array = function() {
- var offset = this.bb.__offset(this.bb_pos, 24);
- return offset ? new Int8Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null;
-};
-
-/**
- * @param {number} index
- * @returns {number}
- */
-MyGame.Example.TypeAliases.prototype.vf64 = function(index) {
- var offset = this.bb.__offset(this.bb_pos, 26);
- return offset ? this.bb.readFloat64(this.bb.__vector(this.bb_pos + offset) + index * 8) : 0;
-};
-
-/**
- * @returns {number}
- */
-MyGame.Example.TypeAliases.prototype.vf64Length = function() {
- var offset = this.bb.__offset(this.bb_pos, 26);
- return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
-};
-
-/**
- * @returns {Float64Array}
- */
-MyGame.Example.TypeAliases.prototype.vf64Array = function() {
- var offset = this.bb.__offset(this.bb_pos, 26);
- return offset ? new Float64Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null;
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- */
-MyGame.Example.TypeAliases.startTypeAliases = function(builder) {
- builder.startObject(12);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} i8
- */
-MyGame.Example.TypeAliases.addI8 = function(builder, i8) {
- builder.addFieldInt8(0, i8, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} u8
- */
-MyGame.Example.TypeAliases.addU8 = function(builder, u8) {
- builder.addFieldInt8(1, u8, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} i16
- */
-MyGame.Example.TypeAliases.addI16 = function(builder, i16) {
- builder.addFieldInt16(2, i16, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} u16
- */
-MyGame.Example.TypeAliases.addU16 = function(builder, u16) {
- builder.addFieldInt16(3, u16, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} i32
- */
-MyGame.Example.TypeAliases.addI32 = function(builder, i32) {
- builder.addFieldInt32(4, i32, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} u32
- */
-MyGame.Example.TypeAliases.addU32 = function(builder, u32) {
- builder.addFieldInt32(5, u32, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Long} i64
- */
-MyGame.Example.TypeAliases.addI64 = function(builder, i64) {
- builder.addFieldInt64(6, i64, builder.createLong(0, 0));
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Long} u64
- */
-MyGame.Example.TypeAliases.addU64 = function(builder, u64) {
- builder.addFieldInt64(7, u64, builder.createLong(0, 0));
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} f32
- */
-MyGame.Example.TypeAliases.addF32 = function(builder, f32) {
- builder.addFieldFloat32(8, f32, 0.0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} f64
- */
-MyGame.Example.TypeAliases.addF64 = function(builder, f64) {
- builder.addFieldFloat64(9, f64, 0.0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Offset} v8Offset
- */
-MyGame.Example.TypeAliases.addV8 = function(builder, v8Offset) {
- builder.addFieldOffset(10, v8Offset, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {Array.<number>} data
- * @returns {flatbuffers.Offset}
- */
-MyGame.Example.TypeAliases.createV8Vector = function(builder, data) {
- builder.startVector(1, data.length, 1);
- for (var i = data.length - 1; i >= 0; i--) {
- builder.addInt8(data[i]);
- }
- return builder.endVector();
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} numElems
- */
-MyGame.Example.TypeAliases.startV8Vector = function(builder, numElems) {
- builder.startVector(1, numElems, 1);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Offset} vf64Offset
- */
-MyGame.Example.TypeAliases.addVf64 = function(builder, vf64Offset) {
- builder.addFieldOffset(11, vf64Offset, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {Array.<number>} data
- * @returns {flatbuffers.Offset}
- */
-MyGame.Example.TypeAliases.createVf64Vector = function(builder, data) {
- builder.startVector(8, data.length, 8);
- for (var i = data.length - 1; i >= 0; i--) {
- builder.addFloat64(data[i]);
- }
- return builder.endVector();
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} numElems
- */
-MyGame.Example.TypeAliases.startVf64Vector = function(builder, numElems) {
- builder.startVector(8, numElems, 8);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @returns {flatbuffers.Offset}
- */
-MyGame.Example.TypeAliases.endTypeAliases = function(builder) {
- var offset = builder.endObject();
- return offset;
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} i8
- * @param {number} u8
- * @param {number} i16
- * @param {number} u16
- * @param {number} i32
- * @param {number} u32
- * @param {flatbuffers.Long} i64
- * @param {flatbuffers.Long} u64
- * @param {number} f32
- * @param {number} f64
- * @param {flatbuffers.Offset} v8Offset
- * @param {flatbuffers.Offset} vf64Offset
- * @returns {flatbuffers.Offset}
- */
-MyGame.Example.TypeAliases.createTypeAliases = function(builder, i8, u8, i16, u16, i32, u32, i64, u64, f32, f64, v8Offset, vf64Offset) {
- MyGame.Example.TypeAliases.startTypeAliases(builder);
- MyGame.Example.TypeAliases.addI8(builder, i8);
- MyGame.Example.TypeAliases.addU8(builder, u8);
- MyGame.Example.TypeAliases.addI16(builder, i16);
- MyGame.Example.TypeAliases.addU16(builder, u16);
- MyGame.Example.TypeAliases.addI32(builder, i32);
- MyGame.Example.TypeAliases.addU32(builder, u32);
- MyGame.Example.TypeAliases.addI64(builder, i64);
- MyGame.Example.TypeAliases.addU64(builder, u64);
- MyGame.Example.TypeAliases.addF32(builder, f32);
- MyGame.Example.TypeAliases.addF64(builder, f64);
- MyGame.Example.TypeAliases.addV8(builder, v8Offset);
- MyGame.Example.TypeAliases.addVf64(builder, vf64Offset);
- return MyGame.Example.TypeAliases.endTypeAliases(builder);
-}
-
-// Exports for Node.js and RequireJS
-this.MyGame = MyGame;
diff --git a/tests/monster_test_generated.lobster b/tests/monster_test_generated.lobster
index 3a0d371..238206f 100644
--- a/tests/monster_test_generated.lobster
+++ b/tests/monster_test_generated.lobster
@@ -18,6 +18,11 @@
Race_Dwarf = 1
Race_Elf = 2
+enum LongEnum:
+ LongEnum_LongOne = 2
+ LongEnum_LongTwo = 4
+ LongEnum_LongBig = 1099511627776
+
enum Any:
Any_NONE = 0
Any_Monster = 1
@@ -54,6 +59,8 @@
class Ability
+class StructOfStructs
+
class Stat
class Referrable
@@ -107,7 +114,7 @@
class TestSimpleTableWithEnum : flatbuffers_handle
def color():
- return Color(buf_.flatbuffers_field_int8(pos_, 4, 2))
+ return Color(buf_.flatbuffers_field_uint8(pos_, 4, 2))
def GetRootAsTestSimpleTableWithEnum(buf:string): return TestSimpleTableWithEnum { buf, buf.flatbuffers_indirect(0) }
@@ -132,7 +139,7 @@
def test1():
return buf_.read_float64_le(pos_ + 16)
def test2():
- return Color(buf_.read_int8_le(pos_ + 24))
+ return Color(buf_.read_uint8_le(pos_ + 24))
def test3():
return MyGame_Example_Test{ buf_, pos_ + 26 }
@@ -154,9 +161,9 @@
class Ability : flatbuffers_handle
def id():
- return buf_.read_int32_le(pos_ + 0)
+ return buf_.read_uint32_le(pos_ + 0)
def distance():
- return buf_.read_int32_le(pos_ + 4)
+ return buf_.read_uint32_le(pos_ + 4)
def CreateAbility(b_:flatbuffers_builder, id:int, distance:int):
b_.Prep(4, 8)
@@ -164,13 +171,35 @@
b_.PrependUint32(id)
return b_.Offset()
+class StructOfStructs : flatbuffers_handle
+ def a():
+ return MyGame_Example_Ability{ buf_, pos_ + 0 }
+ def b():
+ return MyGame_Example_Test{ buf_, pos_ + 8 }
+ def c():
+ return MyGame_Example_Ability{ buf_, pos_ + 12 }
+
+def CreateStructOfStructs(b_:flatbuffers_builder, a_id:int, a_distance:int, b_a:int, b_b:int, c_id:int, c_distance:int):
+ b_.Prep(4, 20)
+ b_.Prep(4, 8)
+ b_.PrependUint32(c_distance)
+ b_.PrependUint32(c_id)
+ b_.Prep(2, 4)
+ b_.Pad(1)
+ b_.PrependInt8(b_b)
+ b_.PrependInt16(b_a)
+ b_.Prep(4, 8)
+ b_.PrependUint32(a_distance)
+ b_.PrependUint32(a_id)
+ return b_.Offset()
+
class Stat : flatbuffers_handle
def id():
return buf_.flatbuffers_field_string(pos_, 4)
def val():
return buf_.flatbuffers_field_int64(pos_, 6, 0)
def count():
- return buf_.flatbuffers_field_int16(pos_, 8, 0)
+ return buf_.flatbuffers_field_uint16(pos_, 8, 0)
def GetRootAsStat(buf:string): return Stat { buf, buf.flatbuffers_indirect(0) }
@@ -193,7 +222,7 @@
class Referrable : flatbuffers_handle
def id():
- return buf_.flatbuffers_field_int64(pos_, 4, 0)
+ return buf_.flatbuffers_field_uint64(pos_, 4, 0)
def GetRootAsReferrable(buf:string): return Referrable { buf, buf.flatbuffers_indirect(0) }
@@ -220,13 +249,13 @@
def name():
return buf_.flatbuffers_field_string(pos_, 10)
def inventory(i:int):
- return buf_.read_int8_le(buf_.flatbuffers_field_vector(pos_, 14) + i * 1)
+ return buf_.read_uint8_le(buf_.flatbuffers_field_vector(pos_, 14) + i * 1)
def inventory_length():
return buf_.flatbuffers_field_vector_len(pos_, 14)
def color():
- return Color(buf_.flatbuffers_field_int8(pos_, 16, 8))
+ return Color(buf_.flatbuffers_field_uint8(pos_, 16, 8))
def test_type():
- return Any(buf_.flatbuffers_field_int8(pos_, 18, 0))
+ return Any(buf_.flatbuffers_field_uint8(pos_, 18, 0))
def test_as_Monster():
return MyGame_Example_Monster { buf_, buf_.flatbuffers_field_table(pos_, 20) }
def test_as_TestSimpleTableWithEnum():
@@ -251,7 +280,7 @@
let o = buf_.flatbuffers_field_table(pos_, 28)
return if o: MyGame_Example_Monster { buf_, o } else: nil
def testnestedflatbuffer(i:int):
- return buf_.read_int8_le(buf_.flatbuffers_field_vector(pos_, 30) + i * 1)
+ return buf_.read_uint8_le(buf_.flatbuffers_field_vector(pos_, 30) + i * 1)
def testnestedflatbuffer_length():
return buf_.flatbuffers_field_vector_len(pos_, 30)
def testempty():
@@ -262,19 +291,19 @@
def testhashs32_fnv1():
return buf_.flatbuffers_field_int32(pos_, 36, 0)
def testhashu32_fnv1():
- return buf_.flatbuffers_field_int32(pos_, 38, 0)
+ return buf_.flatbuffers_field_uint32(pos_, 38, 0)
def testhashs64_fnv1():
return buf_.flatbuffers_field_int64(pos_, 40, 0)
def testhashu64_fnv1():
- return buf_.flatbuffers_field_int64(pos_, 42, 0)
+ return buf_.flatbuffers_field_uint64(pos_, 42, 0)
def testhashs32_fnv1a():
return buf_.flatbuffers_field_int32(pos_, 44, 0)
def testhashu32_fnv1a():
- return buf_.flatbuffers_field_int32(pos_, 46, 0)
+ return buf_.flatbuffers_field_uint32(pos_, 46, 0)
def testhashs64_fnv1a():
return buf_.flatbuffers_field_int64(pos_, 48, 0)
def testhashu64_fnv1a():
- return buf_.flatbuffers_field_int64(pos_, 50, 0)
+ return buf_.flatbuffers_field_uint64(pos_, 50, 0)
def testarrayofbools(i:int):
return buf_.read_int8_le(buf_.flatbuffers_field_vector(pos_, 52) + i * 1)
def testarrayofbools_length():
@@ -294,7 +323,7 @@
def testarrayofsortedstruct_length():
return buf_.flatbuffers_field_vector_len(pos_, 62)
def flex(i:int):
- return buf_.read_int8_le(buf_.flatbuffers_field_vector(pos_, 64) + i * 1)
+ return buf_.read_uint8_le(buf_.flatbuffers_field_vector(pos_, 64) + i * 1)
def flex_length():
return buf_.flatbuffers_field_vector_len(pos_, 64)
def test5(i:int):
@@ -317,9 +346,9 @@
def vector_of_referrables_length():
return buf_.flatbuffers_field_vector_len(pos_, 74)
def single_weak_reference():
- return buf_.flatbuffers_field_int64(pos_, 76, 0)
+ return buf_.flatbuffers_field_uint64(pos_, 76, 0)
def vector_of_weak_references(i:int):
- return buf_.read_int64_le(buf_.flatbuffers_field_vector(pos_, 78) + i * 8)
+ return buf_.read_uint64_le(buf_.flatbuffers_field_vector(pos_, 78) + i * 8)
def vector_of_weak_references_length():
return buf_.flatbuffers_field_vector_len(pos_, 78)
def vector_of_strong_referrables(i:int):
@@ -327,19 +356,19 @@
def vector_of_strong_referrables_length():
return buf_.flatbuffers_field_vector_len(pos_, 80)
def co_owning_reference():
- return buf_.flatbuffers_field_int64(pos_, 82, 0)
+ return buf_.flatbuffers_field_uint64(pos_, 82, 0)
def vector_of_co_owning_references(i:int):
- return buf_.read_int64_le(buf_.flatbuffers_field_vector(pos_, 84) + i * 8)
+ return buf_.read_uint64_le(buf_.flatbuffers_field_vector(pos_, 84) + i * 8)
def vector_of_co_owning_references_length():
return buf_.flatbuffers_field_vector_len(pos_, 84)
def non_owning_reference():
- return buf_.flatbuffers_field_int64(pos_, 86, 0)
+ return buf_.flatbuffers_field_uint64(pos_, 86, 0)
def vector_of_non_owning_references(i:int):
- return buf_.read_int64_le(buf_.flatbuffers_field_vector(pos_, 88) + i * 8)
+ return buf_.read_uint64_le(buf_.flatbuffers_field_vector(pos_, 88) + i * 8)
def vector_of_non_owning_references_length():
return buf_.flatbuffers_field_vector_len(pos_, 88)
def any_unique_type():
- return AnyUniqueAliases(buf_.flatbuffers_field_int8(pos_, 90, 0))
+ return AnyUniqueAliases(buf_.flatbuffers_field_uint8(pos_, 90, 0))
def any_unique_as_M():
return MyGame_Example_Monster { buf_, buf_.flatbuffers_field_table(pos_, 92) }
def any_unique_as_TS():
@@ -347,7 +376,7 @@
def any_unique_as_M2():
return MyGame_Example2_Monster { buf_, buf_.flatbuffers_field_table(pos_, 92) }
def any_ambiguous_type():
- return AnyAmbiguousAliases(buf_.flatbuffers_field_int8(pos_, 94, 0))
+ return AnyAmbiguousAliases(buf_.flatbuffers_field_uint8(pos_, 94, 0))
def any_ambiguous_as_M1():
return MyGame_Example_Monster { buf_, buf_.flatbuffers_field_table(pos_, 96) }
def any_ambiguous_as_M2():
@@ -355,22 +384,33 @@
def any_ambiguous_as_M3():
return MyGame_Example_Monster { buf_, buf_.flatbuffers_field_table(pos_, 96) }
def vector_of_enums(i:int):
- return buf_.read_int8_le(buf_.flatbuffers_field_vector(pos_, 98) + i * 1)
+ return buf_.read_uint8_le(buf_.flatbuffers_field_vector(pos_, 98) + i * 1)
def vector_of_enums_length():
return buf_.flatbuffers_field_vector_len(pos_, 98)
def signed_enum():
return Race(buf_.flatbuffers_field_int8(pos_, 100, -1))
def testrequirednestedflatbuffer(i:int):
- return buf_.read_int8_le(buf_.flatbuffers_field_vector(pos_, 102) + i * 1)
+ return buf_.read_uint8_le(buf_.flatbuffers_field_vector(pos_, 102) + i * 1)
def testrequirednestedflatbuffer_length():
return buf_.flatbuffers_field_vector_len(pos_, 102)
+ def scalar_key_sorted_tables(i:int):
+ return MyGame_Example_Stat { buf_, buf_.flatbuffers_indirect(buf_.flatbuffers_field_vector(pos_, 104) + i * 4) }
+ def scalar_key_sorted_tables_length():
+ return buf_.flatbuffers_field_vector_len(pos_, 104)
+ def native_inline():
+ let o = buf_.flatbuffers_field_struct(pos_, 106)
+ return if o: MyGame_Example_Test { buf_, o } else: nil
+ def long_enum_non_enum_default():
+ return LongEnum(buf_.flatbuffers_field_uint64(pos_, 108, 0))
+ def long_enum_normal_default():
+ return LongEnum(buf_.flatbuffers_field_uint64(pos_, 110, 2))
def GetRootAsMonster(buf:string): return Monster { buf, buf.flatbuffers_indirect(0) }
struct MonsterBuilder:
b_:flatbuffers_builder
def start():
- b_.StartObject(50)
+ b_.StartObject(54)
return this
def add_pos(pos:flatbuffers_offset):
b_.PrependStructSlot(0, pos)
@@ -519,6 +559,18 @@
def add_testrequirednestedflatbuffer(testrequirednestedflatbuffer:flatbuffers_offset):
b_.PrependUOffsetTRelativeSlot(49, testrequirednestedflatbuffer)
return this
+ def add_scalar_key_sorted_tables(scalar_key_sorted_tables:flatbuffers_offset):
+ b_.PrependUOffsetTRelativeSlot(50, scalar_key_sorted_tables)
+ return this
+ def add_native_inline(native_inline:flatbuffers_offset):
+ b_.PrependStructSlot(51, native_inline)
+ return this
+ def add_long_enum_non_enum_default(long_enum_non_enum_default:LongEnum):
+ b_.PrependUint64Slot(52, long_enum_non_enum_default, 0)
+ return this
+ def add_long_enum_normal_default(long_enum_normal_default:LongEnum):
+ b_.PrependUint64Slot(53, long_enum_normal_default, 2)
+ return this
def end():
return b_.EndObject()
@@ -643,23 +695,30 @@
reverse(v_) e_: b_.PrependUint8(e_)
return b_.EndVector(v_.length)
+def MonsterStartScalarKeySortedTablesVector(b_:flatbuffers_builder, n_:int):
+ b_.StartVector(4, n_, 4)
+def MonsterCreateScalarKeySortedTablesVector(b_:flatbuffers_builder, v_:[flatbuffers_offset]):
+ b_.StartVector(4, v_.length, 4)
+ reverse(v_) e_: b_.PrependUOffsetTRelative(e_)
+ return b_.EndVector(v_.length)
+
class TypeAliases : flatbuffers_handle
def i8():
return buf_.flatbuffers_field_int8(pos_, 4, 0)
def u8():
- return buf_.flatbuffers_field_int8(pos_, 6, 0)
+ return buf_.flatbuffers_field_uint8(pos_, 6, 0)
def i16():
return buf_.flatbuffers_field_int16(pos_, 8, 0)
def u16():
- return buf_.flatbuffers_field_int16(pos_, 10, 0)
+ return buf_.flatbuffers_field_uint16(pos_, 10, 0)
def i32():
return buf_.flatbuffers_field_int32(pos_, 12, 0)
def u32():
- return buf_.flatbuffers_field_int32(pos_, 14, 0)
+ return buf_.flatbuffers_field_uint32(pos_, 14, 0)
def i64():
return buf_.flatbuffers_field_int64(pos_, 16, 0)
def u64():
- return buf_.flatbuffers_field_int64(pos_, 18, 0)
+ return buf_.flatbuffers_field_uint64(pos_, 18, 0)
def f32():
return buf_.flatbuffers_field_float32(pos_, 20, 0.0)
def f64():
diff --git a/tests/monster_test_generated.py b/tests/monster_test_generated.py
new file mode 100644
index 0000000..71e266d
--- /dev/null
+++ b/tests/monster_test_generated.py
@@ -0,0 +1,2364 @@
+# automatically generated by the FlatBuffers compiler, do not modify
+
+# namespace: Example
+
+import flatbuffers
+from flatbuffers.compat import import_numpy
+np = import_numpy()
+
+# Composite components of Monster color.
+class Color(object):
+ Red = 1
+ # \brief color Green
+ # Green is bit_flag with value (1u << 1)
+ Green = 2
+ # \brief color Blue (1u << 3)
+ Blue = 8
+
+
+class Race(object):
+ None_ = -1
+ Human = 0
+ Dwarf = 1
+ Elf = 2
+
+
+class LongEnum(object):
+ LongOne = 2
+ LongTwo = 4
+ LongBig = 1099511627776
+
+
+class Any(object):
+ NONE = 0
+ Monster = 1
+ TestSimpleTableWithEnum = 2
+ MyGame_Example2_Monster = 3
+
+def AnyCreator(unionType, table):
+ from flatbuffers.table import Table
+ if not isinstance(table, Table):
+ return None
+ if unionType == Any().Monster:
+ return MonsterT.InitFromBuf(table.Bytes, table.Pos)
+ if unionType == Any().TestSimpleTableWithEnum:
+ return TestSimpleTableWithEnumT.InitFromBuf(table.Bytes, table.Pos)
+ if unionType == Any().MyGame_Example2_Monster:
+ return MonsterT.InitFromBuf(table.Bytes, table.Pos)
+ return None
+
+
+class AnyUniqueAliases(object):
+ NONE = 0
+ M = 1
+ TS = 2
+ M2 = 3
+
+def AnyUniqueAliasesCreator(unionType, table):
+ from flatbuffers.table import Table
+ if not isinstance(table, Table):
+ return None
+ if unionType == AnyUniqueAliases().M:
+ return MonsterT.InitFromBuf(table.Bytes, table.Pos)
+ if unionType == AnyUniqueAliases().TS:
+ return TestSimpleTableWithEnumT.InitFromBuf(table.Bytes, table.Pos)
+ if unionType == AnyUniqueAliases().M2:
+ return MonsterT.InitFromBuf(table.Bytes, table.Pos)
+ return None
+
+
+class AnyAmbiguousAliases(object):
+ NONE = 0
+ M1 = 1
+ M2 = 2
+ M3 = 3
+
+def AnyAmbiguousAliasesCreator(unionType, table):
+ from flatbuffers.table import Table
+ if not isinstance(table, Table):
+ return None
+ if unionType == AnyAmbiguousAliases().M1:
+ return MonsterT.InitFromBuf(table.Bytes, table.Pos)
+ if unionType == AnyAmbiguousAliases().M2:
+ return MonsterT.InitFromBuf(table.Bytes, table.Pos)
+ if unionType == AnyAmbiguousAliases().M3:
+ return MonsterT.InitFromBuf(table.Bytes, table.Pos)
+ return None
+
+
+class InParentNamespace(object):
+ __slots__ = ['_tab']
+
+ @classmethod
+ def GetRootAs(cls, buf, offset=0):
+ n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
+ x = InParentNamespace()
+ x.Init(buf, n + offset)
+ return x
+
+ @classmethod
+ def GetRootAsInParentNamespace(cls, buf, offset=0):
+ """This method is deprecated. Please switch to GetRootAs."""
+ return cls.GetRootAs(buf, offset)
+ @classmethod
+ def InParentNamespaceBufferHasIdentifier(cls, buf, offset, size_prefixed=False):
+ return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4D\x4F\x4E\x53", size_prefixed=size_prefixed)
+
+ # InParentNamespace
+ def Init(self, buf, pos):
+ self._tab = flatbuffers.table.Table(buf, pos)
+
+def InParentNamespaceStart(builder): builder.StartObject(0)
+def InParentNamespaceEnd(builder): return builder.EndObject()
+
+
+class InParentNamespaceT(object):
+
+ # InParentNamespaceT
+ def __init__(self):
+ pass
+
+ @classmethod
+ def InitFromBuf(cls, buf, pos):
+ inParentNamespace = InParentNamespace()
+ inParentNamespace.Init(buf, pos)
+ return cls.InitFromObj(inParentNamespace)
+
+ @classmethod
+ def InitFromObj(cls, inParentNamespace):
+ x = InParentNamespaceT()
+ x._UnPack(inParentNamespace)
+ return x
+
+ # InParentNamespaceT
+ def _UnPack(self, inParentNamespace):
+ if inParentNamespace is None:
+ return
+
+ # InParentNamespaceT
+ def Pack(self, builder):
+ InParentNamespaceStart(builder)
+ inParentNamespace = InParentNamespaceEnd(builder)
+ return inParentNamespace
+
+
+class Monster(object):
+ __slots__ = ['_tab']
+
+ @classmethod
+ def GetRootAs(cls, buf, offset=0):
+ n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
+ x = Monster()
+ x.Init(buf, n + offset)
+ return x
+
+ @classmethod
+ def GetRootAsMonster(cls, buf, offset=0):
+ """This method is deprecated. Please switch to GetRootAs."""
+ return cls.GetRootAs(buf, offset)
+ @classmethod
+ def MonsterBufferHasIdentifier(cls, buf, offset, size_prefixed=False):
+ return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4D\x4F\x4E\x53", size_prefixed=size_prefixed)
+
+ # Monster
+ def Init(self, buf, pos):
+ self._tab = flatbuffers.table.Table(buf, pos)
+
+def MonsterStart(builder): builder.StartObject(0)
+def MonsterEnd(builder): return builder.EndObject()
+
+
+class MonsterT(object):
+
+ # MonsterT
+ def __init__(self):
+ pass
+
+ @classmethod
+ def InitFromBuf(cls, buf, pos):
+ monster = Monster()
+ monster.Init(buf, pos)
+ return cls.InitFromObj(monster)
+
+ @classmethod
+ def InitFromObj(cls, monster):
+ x = MonsterT()
+ x._UnPack(monster)
+ return x
+
+ # MonsterT
+ def _UnPack(self, monster):
+ if monster is None:
+ return
+
+ # MonsterT
+ def Pack(self, builder):
+ MonsterStart(builder)
+ monster = MonsterEnd(builder)
+ return monster
+
+
+class Test(object):
+ __slots__ = ['_tab']
+
+ @classmethod
+ def SizeOf(cls):
+ return 4
+
+ # Test
+ def Init(self, buf, pos):
+ self._tab = flatbuffers.table.Table(buf, pos)
+
+ # Test
+ def A(self): return self._tab.Get(flatbuffers.number_types.Int16Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(0))
+ # Test
+ def B(self): return self._tab.Get(flatbuffers.number_types.Int8Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(2))
+
+def CreateTest(builder, a, b):
+ builder.Prep(2, 4)
+ builder.Pad(1)
+ builder.PrependInt8(b)
+ builder.PrependInt16(a)
+ return builder.Offset()
+
+
+class TestT(object):
+
+ # TestT
+ def __init__(self):
+ self.a = 0 # type: int
+ self.b = 0 # type: int
+
+ @classmethod
+ def InitFromBuf(cls, buf, pos):
+ test = Test()
+ test.Init(buf, pos)
+ return cls.InitFromObj(test)
+
+ @classmethod
+ def InitFromObj(cls, test):
+ x = TestT()
+ x._UnPack(test)
+ return x
+
+ # TestT
+ def _UnPack(self, test):
+ if test is None:
+ return
+ self.a = test.A()
+ self.b = test.B()
+
+ # TestT
+ def Pack(self, builder):
+ return CreateTest(builder, self.a, self.b)
+
+
+class TestSimpleTableWithEnum(object):
+ __slots__ = ['_tab']
+
+ @classmethod
+ def GetRootAs(cls, buf, offset=0):
+ n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
+ x = TestSimpleTableWithEnum()
+ x.Init(buf, n + offset)
+ return x
+
+ @classmethod
+ def GetRootAsTestSimpleTableWithEnum(cls, buf, offset=0):
+ """This method is deprecated. Please switch to GetRootAs."""
+ return cls.GetRootAs(buf, offset)
+ @classmethod
+ def TestSimpleTableWithEnumBufferHasIdentifier(cls, buf, offset, size_prefixed=False):
+ return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4D\x4F\x4E\x53", size_prefixed=size_prefixed)
+
+ # TestSimpleTableWithEnum
+ def Init(self, buf, pos):
+ self._tab = flatbuffers.table.Table(buf, pos)
+
+ # TestSimpleTableWithEnum
+ def Color(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Uint8Flags, o + self._tab.Pos)
+ return 2
+
+def TestSimpleTableWithEnumStart(builder): builder.StartObject(1)
+def TestSimpleTableWithEnumAddColor(builder, color): builder.PrependUint8Slot(0, color, 2)
+def TestSimpleTableWithEnumEnd(builder): return builder.EndObject()
+
+
+class TestSimpleTableWithEnumT(object):
+
+ # TestSimpleTableWithEnumT
+ def __init__(self):
+ self.color = 2 # type: int
+
+ @classmethod
+ def InitFromBuf(cls, buf, pos):
+ testSimpleTableWithEnum = TestSimpleTableWithEnum()
+ testSimpleTableWithEnum.Init(buf, pos)
+ return cls.InitFromObj(testSimpleTableWithEnum)
+
+ @classmethod
+ def InitFromObj(cls, testSimpleTableWithEnum):
+ x = TestSimpleTableWithEnumT()
+ x._UnPack(testSimpleTableWithEnum)
+ return x
+
+ # TestSimpleTableWithEnumT
+ def _UnPack(self, testSimpleTableWithEnum):
+ if testSimpleTableWithEnum is None:
+ return
+ self.color = testSimpleTableWithEnum.Color()
+
+ # TestSimpleTableWithEnumT
+ def Pack(self, builder):
+ TestSimpleTableWithEnumStart(builder)
+ TestSimpleTableWithEnumAddColor(builder, self.color)
+ testSimpleTableWithEnum = TestSimpleTableWithEnumEnd(builder)
+ return testSimpleTableWithEnum
+
+
+class Vec3(object):
+ __slots__ = ['_tab']
+
+ @classmethod
+ def SizeOf(cls):
+ return 32
+
+ # Vec3
+ def Init(self, buf, pos):
+ self._tab = flatbuffers.table.Table(buf, pos)
+
+ # Vec3
+ def X(self): return self._tab.Get(flatbuffers.number_types.Float32Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(0))
+ # Vec3
+ def Y(self): return self._tab.Get(flatbuffers.number_types.Float32Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(4))
+ # Vec3
+ def Z(self): return self._tab.Get(flatbuffers.number_types.Float32Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(8))
+ # Vec3
+ def Test1(self): return self._tab.Get(flatbuffers.number_types.Float64Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(16))
+ # Vec3
+ def Test2(self): return self._tab.Get(flatbuffers.number_types.Uint8Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(24))
+ # Vec3
+ def Test3(self, obj):
+ obj.Init(self._tab.Bytes, self._tab.Pos + 26)
+ return obj
+
+
+def CreateVec3(builder, x, y, z, test1, test2, test3_a, test3_b):
+ builder.Prep(8, 32)
+ builder.Pad(2)
+ builder.Prep(2, 4)
+ builder.Pad(1)
+ builder.PrependInt8(test3_b)
+ builder.PrependInt16(test3_a)
+ builder.Pad(1)
+ builder.PrependUint8(test2)
+ builder.PrependFloat64(test1)
+ builder.Pad(4)
+ builder.PrependFloat32(z)
+ builder.PrependFloat32(y)
+ builder.PrependFloat32(x)
+ return builder.Offset()
+
+try:
+ from typing import Optional
+except:
+ pass
+
+class Vec3T(object):
+
+ # Vec3T
+ def __init__(self):
+ self.x = 0.0 # type: float
+ self.y = 0.0 # type: float
+ self.z = 0.0 # type: float
+ self.test1 = 0.0 # type: float
+ self.test2 = 0 # type: int
+ self.test3 = None # type: Optional[TestT]
+
+ @classmethod
+ def InitFromBuf(cls, buf, pos):
+ vec3 = Vec3()
+ vec3.Init(buf, pos)
+ return cls.InitFromObj(vec3)
+
+ @classmethod
+ def InitFromObj(cls, vec3):
+ x = Vec3T()
+ x._UnPack(vec3)
+ return x
+
+ # Vec3T
+ def _UnPack(self, vec3):
+ if vec3 is None:
+ return
+ self.x = vec3.X()
+ self.y = vec3.Y()
+ self.z = vec3.Z()
+ self.test1 = vec3.Test1()
+ self.test2 = vec3.Test2()
+ if vec3.Test3(Test()) is not None:
+ self.test3 = TestT.InitFromObj(vec3.Test3(Test()))
+
+ # Vec3T
+ def Pack(self, builder):
+ return CreateVec3(builder, self.x, self.y, self.z, self.test1, self.test2, self.test3.a, self.test3.b)
+
+
+class Ability(object):
+ __slots__ = ['_tab']
+
+ @classmethod
+ def SizeOf(cls):
+ return 8
+
+ # Ability
+ def Init(self, buf, pos):
+ self._tab = flatbuffers.table.Table(buf, pos)
+
+ # Ability
+ def Id(self): return self._tab.Get(flatbuffers.number_types.Uint32Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(0))
+ # Ability
+ def Distance(self): return self._tab.Get(flatbuffers.number_types.Uint32Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(4))
+
+def CreateAbility(builder, id, distance):
+ builder.Prep(4, 8)
+ builder.PrependUint32(distance)
+ builder.PrependUint32(id)
+ return builder.Offset()
+
+
+class AbilityT(object):
+
+ # AbilityT
+ def __init__(self):
+ self.id = 0 # type: int
+ self.distance = 0 # type: int
+
+ @classmethod
+ def InitFromBuf(cls, buf, pos):
+ ability = Ability()
+ ability.Init(buf, pos)
+ return cls.InitFromObj(ability)
+
+ @classmethod
+ def InitFromObj(cls, ability):
+ x = AbilityT()
+ x._UnPack(ability)
+ return x
+
+ # AbilityT
+ def _UnPack(self, ability):
+ if ability is None:
+ return
+ self.id = ability.Id()
+ self.distance = ability.Distance()
+
+ # AbilityT
+ def Pack(self, builder):
+ return CreateAbility(builder, self.id, self.distance)
+
+
+class StructOfStructs(object):
+ __slots__ = ['_tab']
+
+ @classmethod
+ def SizeOf(cls):
+ return 20
+
+ # StructOfStructs
+ def Init(self, buf, pos):
+ self._tab = flatbuffers.table.Table(buf, pos)
+
+ # StructOfStructs
+ def A(self, obj):
+ obj.Init(self._tab.Bytes, self._tab.Pos + 0)
+ return obj
+
+ # StructOfStructs
+ def B(self, obj):
+ obj.Init(self._tab.Bytes, self._tab.Pos + 8)
+ return obj
+
+ # StructOfStructs
+ def C(self, obj):
+ obj.Init(self._tab.Bytes, self._tab.Pos + 12)
+ return obj
+
+
+def CreateStructOfStructs(builder, a_id, a_distance, b_a, b_b, c_id, c_distance):
+ builder.Prep(4, 20)
+ builder.Prep(4, 8)
+ builder.PrependUint32(c_distance)
+ builder.PrependUint32(c_id)
+ builder.Prep(2, 4)
+ builder.Pad(1)
+ builder.PrependInt8(b_b)
+ builder.PrependInt16(b_a)
+ builder.Prep(4, 8)
+ builder.PrependUint32(a_distance)
+ builder.PrependUint32(a_id)
+ return builder.Offset()
+
+try:
+ from typing import Optional
+except:
+ pass
+
+class StructOfStructsT(object):
+
+ # StructOfStructsT
+ def __init__(self):
+ self.a = None # type: Optional[AbilityT]
+ self.b = None # type: Optional[TestT]
+ self.c = None # type: Optional[AbilityT]
+
+ @classmethod
+ def InitFromBuf(cls, buf, pos):
+ structOfStructs = StructOfStructs()
+ structOfStructs.Init(buf, pos)
+ return cls.InitFromObj(structOfStructs)
+
+ @classmethod
+ def InitFromObj(cls, structOfStructs):
+ x = StructOfStructsT()
+ x._UnPack(structOfStructs)
+ return x
+
+ # StructOfStructsT
+ def _UnPack(self, structOfStructs):
+ if structOfStructs is None:
+ return
+ if structOfStructs.A(Ability()) is not None:
+ self.a = AbilityT.InitFromObj(structOfStructs.A(Ability()))
+ if structOfStructs.B(Test()) is not None:
+ self.b = TestT.InitFromObj(structOfStructs.B(Test()))
+ if structOfStructs.C(Ability()) is not None:
+ self.c = AbilityT.InitFromObj(structOfStructs.C(Ability()))
+
+ # StructOfStructsT
+ def Pack(self, builder):
+ return CreateStructOfStructs(builder, self.a.id, self.a.distance, self.b.a, self.b.b, self.c.id, self.c.distance)
+
+
+class Stat(object):
+ __slots__ = ['_tab']
+
+ @classmethod
+ def GetRootAs(cls, buf, offset=0):
+ n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
+ x = Stat()
+ x.Init(buf, n + offset)
+ return x
+
+ @classmethod
+ def GetRootAsStat(cls, buf, offset=0):
+ """This method is deprecated. Please switch to GetRootAs."""
+ return cls.GetRootAs(buf, offset)
+ @classmethod
+ def StatBufferHasIdentifier(cls, buf, offset, size_prefixed=False):
+ return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4D\x4F\x4E\x53", size_prefixed=size_prefixed)
+
+ # Stat
+ def Init(self, buf, pos):
+ self._tab = flatbuffers.table.Table(buf, pos)
+
+ # Stat
+ def Id(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
+ if o != 0:
+ return self._tab.String(o + self._tab.Pos)
+ return None
+
+ # Stat
+ def Val(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Int64Flags, o + self._tab.Pos)
+ return 0
+
+ # Stat
+ def Count(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Uint16Flags, o + self._tab.Pos)
+ return 0
+
+def StatStart(builder): builder.StartObject(3)
+def StatAddId(builder, id): builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(id), 0)
+def StatAddVal(builder, val): builder.PrependInt64Slot(1, val, 0)
+def StatAddCount(builder, count): builder.PrependUint16Slot(2, count, 0)
+def StatEnd(builder): return builder.EndObject()
+
+
+class StatT(object):
+
+ # StatT
+ def __init__(self):
+ self.id = None # type: str
+ self.val = 0 # type: int
+ self.count = 0 # type: int
+
+ @classmethod
+ def InitFromBuf(cls, buf, pos):
+ stat = Stat()
+ stat.Init(buf, pos)
+ return cls.InitFromObj(stat)
+
+ @classmethod
+ def InitFromObj(cls, stat):
+ x = StatT()
+ x._UnPack(stat)
+ return x
+
+ # StatT
+ def _UnPack(self, stat):
+ if stat is None:
+ return
+ self.id = stat.Id()
+ self.val = stat.Val()
+ self.count = stat.Count()
+
+ # StatT
+ def Pack(self, builder):
+ if self.id is not None:
+ id = builder.CreateString(self.id)
+ StatStart(builder)
+ if self.id is not None:
+ StatAddId(builder, id)
+ StatAddVal(builder, self.val)
+ StatAddCount(builder, self.count)
+ stat = StatEnd(builder)
+ return stat
+
+
+class Referrable(object):
+ __slots__ = ['_tab']
+
+ @classmethod
+ def GetRootAs(cls, buf, offset=0):
+ n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
+ x = Referrable()
+ x.Init(buf, n + offset)
+ return x
+
+ @classmethod
+ def GetRootAsReferrable(cls, buf, offset=0):
+ """This method is deprecated. Please switch to GetRootAs."""
+ return cls.GetRootAs(buf, offset)
+ @classmethod
+ def ReferrableBufferHasIdentifier(cls, buf, offset, size_prefixed=False):
+ return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4D\x4F\x4E\x53", size_prefixed=size_prefixed)
+
+ # Referrable
+ def Init(self, buf, pos):
+ self._tab = flatbuffers.table.Table(buf, pos)
+
+ # Referrable
+ def Id(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Uint64Flags, o + self._tab.Pos)
+ return 0
+
+def ReferrableStart(builder): builder.StartObject(1)
+def ReferrableAddId(builder, id): builder.PrependUint64Slot(0, id, 0)
+def ReferrableEnd(builder): return builder.EndObject()
+
+
+class ReferrableT(object):
+
+ # ReferrableT
+ def __init__(self):
+ self.id = 0 # type: int
+
+ @classmethod
+ def InitFromBuf(cls, buf, pos):
+ referrable = Referrable()
+ referrable.Init(buf, pos)
+ return cls.InitFromObj(referrable)
+
+ @classmethod
+ def InitFromObj(cls, referrable):
+ x = ReferrableT()
+ x._UnPack(referrable)
+ return x
+
+ # ReferrableT
+ def _UnPack(self, referrable):
+ if referrable is None:
+ return
+ self.id = referrable.Id()
+
+ # ReferrableT
+ def Pack(self, builder):
+ ReferrableStart(builder)
+ ReferrableAddId(builder, self.id)
+ referrable = ReferrableEnd(builder)
+ return referrable
+
+
+# an example documentation comment: "monster object"
+class Monster(object):
+ __slots__ = ['_tab']
+
+ @classmethod
+ def GetRootAs(cls, buf, offset=0):
+ n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
+ x = Monster()
+ x.Init(buf, n + offset)
+ return x
+
+ @classmethod
+ def GetRootAsMonster(cls, buf, offset=0):
+ """This method is deprecated. Please switch to GetRootAs."""
+ return cls.GetRootAs(buf, offset)
+ @classmethod
+ def MonsterBufferHasIdentifier(cls, buf, offset, size_prefixed=False):
+ return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4D\x4F\x4E\x53", size_prefixed=size_prefixed)
+
+ # Monster
+ def Init(self, buf, pos):
+ self._tab = flatbuffers.table.Table(buf, pos)
+
+ # Monster
+ def Pos(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
+ if o != 0:
+ x = o + self._tab.Pos
+ obj = Vec3()
+ obj.Init(self._tab.Bytes, x)
+ return obj
+ return None
+
+ # Monster
+ def Mana(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Int16Flags, o + self._tab.Pos)
+ return 150
+
+ # Monster
+ def Hp(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Int16Flags, o + self._tab.Pos)
+ return 100
+
+ # Monster
+ def Name(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10))
+ if o != 0:
+ return self._tab.String(o + self._tab.Pos)
+ return None
+
+ # Monster
+ def Inventory(self, j):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14))
+ if o != 0:
+ a = self._tab.Vector(o)
+ return self._tab.Get(flatbuffers.number_types.Uint8Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 1))
+ return 0
+
+ # Monster
+ def InventoryAsNumpy(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14))
+ if o != 0:
+ return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Uint8Flags, o)
+ return 0
+
+ # Monster
+ def InventoryLength(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14))
+ if o != 0:
+ return self._tab.VectorLen(o)
+ return 0
+
+ # Monster
+ def InventoryIsNone(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14))
+ return o == 0
+
+ # Monster
+ def Color(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(16))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Uint8Flags, o + self._tab.Pos)
+ return 8
+
+ # Monster
+ def TestType(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(18))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Uint8Flags, o + self._tab.Pos)
+ return 0
+
+ # Monster
+ def Test(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(20))
+ if o != 0:
+ from flatbuffers.table import Table
+ obj = Table(bytearray(), 0)
+ self._tab.Union(obj, o)
+ return obj
+ return None
+
+ # Monster
+ def Test4(self, j):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(22))
+ if o != 0:
+ x = self._tab.Vector(o)
+ x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4
+ obj = Test()
+ obj.Init(self._tab.Bytes, x)
+ return obj
+ return None
+
+ # Monster
+ def Test4Length(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(22))
+ if o != 0:
+ return self._tab.VectorLen(o)
+ return 0
+
+ # Monster
+ def Test4IsNone(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(22))
+ return o == 0
+
+ # Monster
+ def Testarrayofstring(self, j):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(24))
+ if o != 0:
+ a = self._tab.Vector(o)
+ return self._tab.String(a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4))
+ return ""
+
+ # Monster
+ def TestarrayofstringLength(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(24))
+ if o != 0:
+ return self._tab.VectorLen(o)
+ return 0
+
+ # Monster
+ def TestarrayofstringIsNone(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(24))
+ return o == 0
+
+ # an example documentation comment: this will end up in the generated code
+ # multiline too
+ # Monster
+ def Testarrayoftables(self, j):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(26))
+ if o != 0:
+ x = self._tab.Vector(o)
+ x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4
+ x = self._tab.Indirect(x)
+ obj = Monster()
+ obj.Init(self._tab.Bytes, x)
+ return obj
+ return None
+
+ # Monster
+ def TestarrayoftablesLength(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(26))
+ if o != 0:
+ return self._tab.VectorLen(o)
+ return 0
+
+ # Monster
+ def TestarrayoftablesIsNone(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(26))
+ return o == 0
+
+ # Monster
+ def Enemy(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(28))
+ if o != 0:
+ x = self._tab.Indirect(o + self._tab.Pos)
+ obj = Monster()
+ obj.Init(self._tab.Bytes, x)
+ return obj
+ return None
+
+ # Monster
+ def Testnestedflatbuffer(self, j):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(30))
+ if o != 0:
+ a = self._tab.Vector(o)
+ return self._tab.Get(flatbuffers.number_types.Uint8Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 1))
+ return 0
+
+ # Monster
+ def TestnestedflatbufferAsNumpy(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(30))
+ if o != 0:
+ return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Uint8Flags, o)
+ return 0
+
+ # Monster
+ def TestnestedflatbufferNestedRoot(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(30))
+ if o != 0:
+ from MyGame.Example.Monster import Monster
+ return Monster.GetRootAsMonster(self._tab.Bytes, self._tab.Vector(o))
+ return 0
+
+ # Monster
+ def TestnestedflatbufferLength(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(30))
+ if o != 0:
+ return self._tab.VectorLen(o)
+ return 0
+
+ # Monster
+ def TestnestedflatbufferIsNone(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(30))
+ return o == 0
+
+ # Monster
+ def Testempty(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(32))
+ if o != 0:
+ x = self._tab.Indirect(o + self._tab.Pos)
+ obj = Stat()
+ obj.Init(self._tab.Bytes, x)
+ return obj
+ return None
+
+ # Monster
+ def Testbool(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(34))
+ if o != 0:
+ return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos))
+ return False
+
+ # Monster
+ def Testhashs32Fnv1(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(36))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos)
+ return 0
+
+ # Monster
+ def Testhashu32Fnv1(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(38))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Uint32Flags, o + self._tab.Pos)
+ return 0
+
+ # Monster
+ def Testhashs64Fnv1(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(40))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Int64Flags, o + self._tab.Pos)
+ return 0
+
+ # Monster
+ def Testhashu64Fnv1(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(42))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Uint64Flags, o + self._tab.Pos)
+ return 0
+
+ # Monster
+ def Testhashs32Fnv1a(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(44))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos)
+ return 0
+
+ # Monster
+ def Testhashu32Fnv1a(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(46))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Uint32Flags, o + self._tab.Pos)
+ return 0
+
+ # Monster
+ def Testhashs64Fnv1a(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(48))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Int64Flags, o + self._tab.Pos)
+ return 0
+
+ # Monster
+ def Testhashu64Fnv1a(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(50))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Uint64Flags, o + self._tab.Pos)
+ return 0
+
+ # Monster
+ def Testarrayofbools(self, j):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(52))
+ if o != 0:
+ a = self._tab.Vector(o)
+ return self._tab.Get(flatbuffers.number_types.BoolFlags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 1))
+ return 0
+
+ # Monster
+ def TestarrayofboolsAsNumpy(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(52))
+ if o != 0:
+ return self._tab.GetVectorAsNumpy(flatbuffers.number_types.BoolFlags, o)
+ return 0
+
+ # Monster
+ def TestarrayofboolsLength(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(52))
+ if o != 0:
+ return self._tab.VectorLen(o)
+ return 0
+
+ # Monster
+ def TestarrayofboolsIsNone(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(52))
+ return o == 0
+
+ # Monster
+ def Testf(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(54))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Float32Flags, o + self._tab.Pos)
+ return 3.14159
+
+ # Monster
+ def Testf2(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(56))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Float32Flags, o + self._tab.Pos)
+ return 3.0
+
+ # Monster
+ def Testf3(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(58))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Float32Flags, o + self._tab.Pos)
+ return 0.0
+
+ # Monster
+ def Testarrayofstring2(self, j):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(60))
+ if o != 0:
+ a = self._tab.Vector(o)
+ return self._tab.String(a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4))
+ return ""
+
+ # Monster
+ def Testarrayofstring2Length(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(60))
+ if o != 0:
+ return self._tab.VectorLen(o)
+ return 0
+
+ # Monster
+ def Testarrayofstring2IsNone(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(60))
+ return o == 0
+
+ # Monster
+ def Testarrayofsortedstruct(self, j):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(62))
+ if o != 0:
+ x = self._tab.Vector(o)
+ x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 8
+ obj = Ability()
+ obj.Init(self._tab.Bytes, x)
+ return obj
+ return None
+
+ # Monster
+ def TestarrayofsortedstructLength(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(62))
+ if o != 0:
+ return self._tab.VectorLen(o)
+ return 0
+
+ # Monster
+ def TestarrayofsortedstructIsNone(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(62))
+ return o == 0
+
+ # Monster
+ def Flex(self, j):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(64))
+ if o != 0:
+ a = self._tab.Vector(o)
+ return self._tab.Get(flatbuffers.number_types.Uint8Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 1))
+ return 0
+
+ # Monster
+ def FlexAsNumpy(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(64))
+ if o != 0:
+ return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Uint8Flags, o)
+ return 0
+
+ # Monster
+ def FlexLength(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(64))
+ if o != 0:
+ return self._tab.VectorLen(o)
+ return 0
+
+ # Monster
+ def FlexIsNone(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(64))
+ return o == 0
+
+ # Monster
+ def Test5(self, j):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(66))
+ if o != 0:
+ x = self._tab.Vector(o)
+ x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4
+ obj = Test()
+ obj.Init(self._tab.Bytes, x)
+ return obj
+ return None
+
+ # Monster
+ def Test5Length(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(66))
+ if o != 0:
+ return self._tab.VectorLen(o)
+ return 0
+
+ # Monster
+ def Test5IsNone(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(66))
+ return o == 0
+
+ # Monster
+ def VectorOfLongs(self, j):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(68))
+ if o != 0:
+ a = self._tab.Vector(o)
+ return self._tab.Get(flatbuffers.number_types.Int64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8))
+ return 0
+
+ # Monster
+ def VectorOfLongsAsNumpy(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(68))
+ if o != 0:
+ return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int64Flags, o)
+ return 0
+
+ # Monster
+ def VectorOfLongsLength(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(68))
+ if o != 0:
+ return self._tab.VectorLen(o)
+ return 0
+
+ # Monster
+ def VectorOfLongsIsNone(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(68))
+ return o == 0
+
+ # Monster
+ def VectorOfDoubles(self, j):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(70))
+ if o != 0:
+ a = self._tab.Vector(o)
+ return self._tab.Get(flatbuffers.number_types.Float64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8))
+ return 0
+
+ # Monster
+ def VectorOfDoublesAsNumpy(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(70))
+ if o != 0:
+ return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Float64Flags, o)
+ return 0
+
+ # Monster
+ def VectorOfDoublesLength(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(70))
+ if o != 0:
+ return self._tab.VectorLen(o)
+ return 0
+
+ # Monster
+ def VectorOfDoublesIsNone(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(70))
+ return o == 0
+
+ # Monster
+ def ParentNamespaceTest(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(72))
+ if o != 0:
+ x = self._tab.Indirect(o + self._tab.Pos)
+ obj = InParentNamespace()
+ obj.Init(self._tab.Bytes, x)
+ return obj
+ return None
+
+ # Monster
+ def VectorOfReferrables(self, j):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(74))
+ if o != 0:
+ x = self._tab.Vector(o)
+ x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4
+ x = self._tab.Indirect(x)
+ obj = Referrable()
+ obj.Init(self._tab.Bytes, x)
+ return obj
+ return None
+
+ # Monster
+ def VectorOfReferrablesLength(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(74))
+ if o != 0:
+ return self._tab.VectorLen(o)
+ return 0
+
+ # Monster
+ def VectorOfReferrablesIsNone(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(74))
+ return o == 0
+
+ # Monster
+ def SingleWeakReference(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(76))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Uint64Flags, o + self._tab.Pos)
+ return 0
+
+ # Monster
+ def VectorOfWeakReferences(self, j):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(78))
+ if o != 0:
+ a = self._tab.Vector(o)
+ return self._tab.Get(flatbuffers.number_types.Uint64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8))
+ return 0
+
+ # Monster
+ def VectorOfWeakReferencesAsNumpy(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(78))
+ if o != 0:
+ return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Uint64Flags, o)
+ return 0
+
+ # Monster
+ def VectorOfWeakReferencesLength(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(78))
+ if o != 0:
+ return self._tab.VectorLen(o)
+ return 0
+
+ # Monster
+ def VectorOfWeakReferencesIsNone(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(78))
+ return o == 0
+
+ # Monster
+ def VectorOfStrongReferrables(self, j):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(80))
+ if o != 0:
+ x = self._tab.Vector(o)
+ x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4
+ x = self._tab.Indirect(x)
+ obj = Referrable()
+ obj.Init(self._tab.Bytes, x)
+ return obj
+ return None
+
+ # Monster
+ def VectorOfStrongReferrablesLength(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(80))
+ if o != 0:
+ return self._tab.VectorLen(o)
+ return 0
+
+ # Monster
+ def VectorOfStrongReferrablesIsNone(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(80))
+ return o == 0
+
+ # Monster
+ def CoOwningReference(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(82))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Uint64Flags, o + self._tab.Pos)
+ return 0
+
+ # Monster
+ def VectorOfCoOwningReferences(self, j):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(84))
+ if o != 0:
+ a = self._tab.Vector(o)
+ return self._tab.Get(flatbuffers.number_types.Uint64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8))
+ return 0
+
+ # Monster
+ def VectorOfCoOwningReferencesAsNumpy(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(84))
+ if o != 0:
+ return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Uint64Flags, o)
+ return 0
+
+ # Monster
+ def VectorOfCoOwningReferencesLength(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(84))
+ if o != 0:
+ return self._tab.VectorLen(o)
+ return 0
+
+ # Monster
+ def VectorOfCoOwningReferencesIsNone(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(84))
+ return o == 0
+
+ # Monster
+ def NonOwningReference(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(86))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Uint64Flags, o + self._tab.Pos)
+ return 0
+
+ # Monster
+ def VectorOfNonOwningReferences(self, j):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(88))
+ if o != 0:
+ a = self._tab.Vector(o)
+ return self._tab.Get(flatbuffers.number_types.Uint64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8))
+ return 0
+
+ # Monster
+ def VectorOfNonOwningReferencesAsNumpy(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(88))
+ if o != 0:
+ return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Uint64Flags, o)
+ return 0
+
+ # Monster
+ def VectorOfNonOwningReferencesLength(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(88))
+ if o != 0:
+ return self._tab.VectorLen(o)
+ return 0
+
+ # Monster
+ def VectorOfNonOwningReferencesIsNone(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(88))
+ return o == 0
+
+ # Monster
+ def AnyUniqueType(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(90))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Uint8Flags, o + self._tab.Pos)
+ return 0
+
+ # Monster
+ def AnyUnique(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(92))
+ if o != 0:
+ from flatbuffers.table import Table
+ obj = Table(bytearray(), 0)
+ self._tab.Union(obj, o)
+ return obj
+ return None
+
+ # Monster
+ def AnyAmbiguousType(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(94))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Uint8Flags, o + self._tab.Pos)
+ return 0
+
+ # Monster
+ def AnyAmbiguous(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(96))
+ if o != 0:
+ from flatbuffers.table import Table
+ obj = Table(bytearray(), 0)
+ self._tab.Union(obj, o)
+ return obj
+ return None
+
+ # Monster
+ def VectorOfEnums(self, j):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(98))
+ if o != 0:
+ a = self._tab.Vector(o)
+ return self._tab.Get(flatbuffers.number_types.Uint8Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 1))
+ return 0
+
+ # Monster
+ def VectorOfEnumsAsNumpy(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(98))
+ if o != 0:
+ return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Uint8Flags, o)
+ return 0
+
+ # Monster
+ def VectorOfEnumsLength(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(98))
+ if o != 0:
+ return self._tab.VectorLen(o)
+ return 0
+
+ # Monster
+ def VectorOfEnumsIsNone(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(98))
+ return o == 0
+
+ # Monster
+ def SignedEnum(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(100))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos)
+ return -1
+
+ # Monster
+ def Testrequirednestedflatbuffer(self, j):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(102))
+ if o != 0:
+ a = self._tab.Vector(o)
+ return self._tab.Get(flatbuffers.number_types.Uint8Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 1))
+ return 0
+
+ # Monster
+ def TestrequirednestedflatbufferAsNumpy(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(102))
+ if o != 0:
+ return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Uint8Flags, o)
+ return 0
+
+ # Monster
+ def TestrequirednestedflatbufferNestedRoot(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(102))
+ if o != 0:
+ from MyGame.Example.Monster import Monster
+ return Monster.GetRootAsMonster(self._tab.Bytes, self._tab.Vector(o))
+ return 0
+
+ # Monster
+ def TestrequirednestedflatbufferLength(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(102))
+ if o != 0:
+ return self._tab.VectorLen(o)
+ return 0
+
+ # Monster
+ def TestrequirednestedflatbufferIsNone(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(102))
+ return o == 0
+
+ # Monster
+ def ScalarKeySortedTables(self, j):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(104))
+ if o != 0:
+ x = self._tab.Vector(o)
+ x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4
+ x = self._tab.Indirect(x)
+ obj = Stat()
+ obj.Init(self._tab.Bytes, x)
+ return obj
+ return None
+
+ # Monster
+ def ScalarKeySortedTablesLength(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(104))
+ if o != 0:
+ return self._tab.VectorLen(o)
+ return 0
+
+ # Monster
+ def ScalarKeySortedTablesIsNone(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(104))
+ return o == 0
+
+ # Monster
+ def NativeInline(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(106))
+ if o != 0:
+ x = o + self._tab.Pos
+ obj = Test()
+ obj.Init(self._tab.Bytes, x)
+ return obj
+ return None
+
+ # Monster
+ def LongEnumNonEnumDefault(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(108))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Uint64Flags, o + self._tab.Pos)
+ return 0
+
+ # Monster
+ def LongEnumNormalDefault(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(110))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Uint64Flags, o + self._tab.Pos)
+ return 2
+
+def MonsterStart(builder): builder.StartObject(54)
+def MonsterAddPos(builder, pos): builder.PrependStructSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(pos), 0)
+def MonsterAddMana(builder, mana): builder.PrependInt16Slot(1, mana, 150)
+def MonsterAddHp(builder, hp): builder.PrependInt16Slot(2, hp, 100)
+def MonsterAddName(builder, name): builder.PrependUOffsetTRelativeSlot(3, flatbuffers.number_types.UOffsetTFlags.py_type(name), 0)
+def MonsterAddInventory(builder, inventory): builder.PrependUOffsetTRelativeSlot(5, flatbuffers.number_types.UOffsetTFlags.py_type(inventory), 0)
+def MonsterStartInventoryVector(builder, numElems): return builder.StartVector(1, numElems, 1)
+def MonsterAddColor(builder, color): builder.PrependUint8Slot(6, color, 8)
+def MonsterAddTestType(builder, testType): builder.PrependUint8Slot(7, testType, 0)
+def MonsterAddTest(builder, test): builder.PrependUOffsetTRelativeSlot(8, flatbuffers.number_types.UOffsetTFlags.py_type(test), 0)
+def MonsterAddTest4(builder, test4): builder.PrependUOffsetTRelativeSlot(9, flatbuffers.number_types.UOffsetTFlags.py_type(test4), 0)
+def MonsterStartTest4Vector(builder, numElems): return builder.StartVector(4, numElems, 2)
+def MonsterAddTestarrayofstring(builder, testarrayofstring): builder.PrependUOffsetTRelativeSlot(10, flatbuffers.number_types.UOffsetTFlags.py_type(testarrayofstring), 0)
+def MonsterStartTestarrayofstringVector(builder, numElems): return builder.StartVector(4, numElems, 4)
+def MonsterAddTestarrayoftables(builder, testarrayoftables): builder.PrependUOffsetTRelativeSlot(11, flatbuffers.number_types.UOffsetTFlags.py_type(testarrayoftables), 0)
+def MonsterStartTestarrayoftablesVector(builder, numElems): return builder.StartVector(4, numElems, 4)
+def MonsterAddEnemy(builder, enemy): builder.PrependUOffsetTRelativeSlot(12, flatbuffers.number_types.UOffsetTFlags.py_type(enemy), 0)
+def MonsterAddTestnestedflatbuffer(builder, testnestedflatbuffer): builder.PrependUOffsetTRelativeSlot(13, flatbuffers.number_types.UOffsetTFlags.py_type(testnestedflatbuffer), 0)
+def MonsterStartTestnestedflatbufferVector(builder, numElems): return builder.StartVector(1, numElems, 1)
+def MonsterMakeTestnestedflatbufferVectorFromBytes(builder, bytes):
+ builder.StartVector(1, len(bytes), 1)
+ builder.head = builder.head - len(bytes)
+ builder.Bytes[builder.head : builder.head + len(bytes)] = bytes
+ return builder.EndVector()
+def MonsterAddTestempty(builder, testempty): builder.PrependUOffsetTRelativeSlot(14, flatbuffers.number_types.UOffsetTFlags.py_type(testempty), 0)
+def MonsterAddTestbool(builder, testbool): builder.PrependBoolSlot(15, testbool, 0)
+def MonsterAddTesthashs32Fnv1(builder, testhashs32Fnv1): builder.PrependInt32Slot(16, testhashs32Fnv1, 0)
+def MonsterAddTesthashu32Fnv1(builder, testhashu32Fnv1): builder.PrependUint32Slot(17, testhashu32Fnv1, 0)
+def MonsterAddTesthashs64Fnv1(builder, testhashs64Fnv1): builder.PrependInt64Slot(18, testhashs64Fnv1, 0)
+def MonsterAddTesthashu64Fnv1(builder, testhashu64Fnv1): builder.PrependUint64Slot(19, testhashu64Fnv1, 0)
+def MonsterAddTesthashs32Fnv1a(builder, testhashs32Fnv1a): builder.PrependInt32Slot(20, testhashs32Fnv1a, 0)
+def MonsterAddTesthashu32Fnv1a(builder, testhashu32Fnv1a): builder.PrependUint32Slot(21, testhashu32Fnv1a, 0)
+def MonsterAddTesthashs64Fnv1a(builder, testhashs64Fnv1a): builder.PrependInt64Slot(22, testhashs64Fnv1a, 0)
+def MonsterAddTesthashu64Fnv1a(builder, testhashu64Fnv1a): builder.PrependUint64Slot(23, testhashu64Fnv1a, 0)
+def MonsterAddTestarrayofbools(builder, testarrayofbools): builder.PrependUOffsetTRelativeSlot(24, flatbuffers.number_types.UOffsetTFlags.py_type(testarrayofbools), 0)
+def MonsterStartTestarrayofboolsVector(builder, numElems): return builder.StartVector(1, numElems, 1)
+def MonsterAddTestf(builder, testf): builder.PrependFloat32Slot(25, testf, 3.14159)
+def MonsterAddTestf2(builder, testf2): builder.PrependFloat32Slot(26, testf2, 3.0)
+def MonsterAddTestf3(builder, testf3): builder.PrependFloat32Slot(27, testf3, 0.0)
+def MonsterAddTestarrayofstring2(builder, testarrayofstring2): builder.PrependUOffsetTRelativeSlot(28, flatbuffers.number_types.UOffsetTFlags.py_type(testarrayofstring2), 0)
+def MonsterStartTestarrayofstring2Vector(builder, numElems): return builder.StartVector(4, numElems, 4)
+def MonsterAddTestarrayofsortedstruct(builder, testarrayofsortedstruct): builder.PrependUOffsetTRelativeSlot(29, flatbuffers.number_types.UOffsetTFlags.py_type(testarrayofsortedstruct), 0)
+def MonsterStartTestarrayofsortedstructVector(builder, numElems): return builder.StartVector(8, numElems, 4)
+def MonsterAddFlex(builder, flex): builder.PrependUOffsetTRelativeSlot(30, flatbuffers.number_types.UOffsetTFlags.py_type(flex), 0)
+def MonsterStartFlexVector(builder, numElems): return builder.StartVector(1, numElems, 1)
+def MonsterAddTest5(builder, test5): builder.PrependUOffsetTRelativeSlot(31, flatbuffers.number_types.UOffsetTFlags.py_type(test5), 0)
+def MonsterStartTest5Vector(builder, numElems): return builder.StartVector(4, numElems, 2)
+def MonsterAddVectorOfLongs(builder, vectorOfLongs): builder.PrependUOffsetTRelativeSlot(32, flatbuffers.number_types.UOffsetTFlags.py_type(vectorOfLongs), 0)
+def MonsterStartVectorOfLongsVector(builder, numElems): return builder.StartVector(8, numElems, 8)
+def MonsterAddVectorOfDoubles(builder, vectorOfDoubles): builder.PrependUOffsetTRelativeSlot(33, flatbuffers.number_types.UOffsetTFlags.py_type(vectorOfDoubles), 0)
+def MonsterStartVectorOfDoublesVector(builder, numElems): return builder.StartVector(8, numElems, 8)
+def MonsterAddParentNamespaceTest(builder, parentNamespaceTest): builder.PrependUOffsetTRelativeSlot(34, flatbuffers.number_types.UOffsetTFlags.py_type(parentNamespaceTest), 0)
+def MonsterAddVectorOfReferrables(builder, vectorOfReferrables): builder.PrependUOffsetTRelativeSlot(35, flatbuffers.number_types.UOffsetTFlags.py_type(vectorOfReferrables), 0)
+def MonsterStartVectorOfReferrablesVector(builder, numElems): return builder.StartVector(4, numElems, 4)
+def MonsterAddSingleWeakReference(builder, singleWeakReference): builder.PrependUint64Slot(36, singleWeakReference, 0)
+def MonsterAddVectorOfWeakReferences(builder, vectorOfWeakReferences): builder.PrependUOffsetTRelativeSlot(37, flatbuffers.number_types.UOffsetTFlags.py_type(vectorOfWeakReferences), 0)
+def MonsterStartVectorOfWeakReferencesVector(builder, numElems): return builder.StartVector(8, numElems, 8)
+def MonsterAddVectorOfStrongReferrables(builder, vectorOfStrongReferrables): builder.PrependUOffsetTRelativeSlot(38, flatbuffers.number_types.UOffsetTFlags.py_type(vectorOfStrongReferrables), 0)
+def MonsterStartVectorOfStrongReferrablesVector(builder, numElems): return builder.StartVector(4, numElems, 4)
+def MonsterAddCoOwningReference(builder, coOwningReference): builder.PrependUint64Slot(39, coOwningReference, 0)
+def MonsterAddVectorOfCoOwningReferences(builder, vectorOfCoOwningReferences): builder.PrependUOffsetTRelativeSlot(40, flatbuffers.number_types.UOffsetTFlags.py_type(vectorOfCoOwningReferences), 0)
+def MonsterStartVectorOfCoOwningReferencesVector(builder, numElems): return builder.StartVector(8, numElems, 8)
+def MonsterAddNonOwningReference(builder, nonOwningReference): builder.PrependUint64Slot(41, nonOwningReference, 0)
+def MonsterAddVectorOfNonOwningReferences(builder, vectorOfNonOwningReferences): builder.PrependUOffsetTRelativeSlot(42, flatbuffers.number_types.UOffsetTFlags.py_type(vectorOfNonOwningReferences), 0)
+def MonsterStartVectorOfNonOwningReferencesVector(builder, numElems): return builder.StartVector(8, numElems, 8)
+def MonsterAddAnyUniqueType(builder, anyUniqueType): builder.PrependUint8Slot(43, anyUniqueType, 0)
+def MonsterAddAnyUnique(builder, anyUnique): builder.PrependUOffsetTRelativeSlot(44, flatbuffers.number_types.UOffsetTFlags.py_type(anyUnique), 0)
+def MonsterAddAnyAmbiguousType(builder, anyAmbiguousType): builder.PrependUint8Slot(45, anyAmbiguousType, 0)
+def MonsterAddAnyAmbiguous(builder, anyAmbiguous): builder.PrependUOffsetTRelativeSlot(46, flatbuffers.number_types.UOffsetTFlags.py_type(anyAmbiguous), 0)
+def MonsterAddVectorOfEnums(builder, vectorOfEnums): builder.PrependUOffsetTRelativeSlot(47, flatbuffers.number_types.UOffsetTFlags.py_type(vectorOfEnums), 0)
+def MonsterStartVectorOfEnumsVector(builder, numElems): return builder.StartVector(1, numElems, 1)
+def MonsterAddSignedEnum(builder, signedEnum): builder.PrependInt8Slot(48, signedEnum, -1)
+def MonsterAddTestrequirednestedflatbuffer(builder, testrequirednestedflatbuffer): builder.PrependUOffsetTRelativeSlot(49, flatbuffers.number_types.UOffsetTFlags.py_type(testrequirednestedflatbuffer), 0)
+def MonsterStartTestrequirednestedflatbufferVector(builder, numElems): return builder.StartVector(1, numElems, 1)
+def MonsterMakeTestrequirednestedflatbufferVectorFromBytes(builder, bytes):
+ builder.StartVector(1, len(bytes), 1)
+ builder.head = builder.head - len(bytes)
+ builder.Bytes[builder.head : builder.head + len(bytes)] = bytes
+ return builder.EndVector()
+def MonsterAddScalarKeySortedTables(builder, scalarKeySortedTables): builder.PrependUOffsetTRelativeSlot(50, flatbuffers.number_types.UOffsetTFlags.py_type(scalarKeySortedTables), 0)
+def MonsterStartScalarKeySortedTablesVector(builder, numElems): return builder.StartVector(4, numElems, 4)
+def MonsterAddNativeInline(builder, nativeInline): builder.PrependStructSlot(51, flatbuffers.number_types.UOffsetTFlags.py_type(nativeInline), 0)
+def MonsterAddLongEnumNonEnumDefault(builder, longEnumNonEnumDefault): builder.PrependUint64Slot(52, longEnumNonEnumDefault, 0)
+def MonsterAddLongEnumNormalDefault(builder, longEnumNormalDefault): builder.PrependUint64Slot(53, longEnumNormalDefault, 2)
+def MonsterEnd(builder): return builder.EndObject()
+
+try:
+ from typing import List, Optional, Union
+except:
+ pass
+
+class MonsterT(object):
+
+ # MonsterT
+ def __init__(self):
+ self.pos = None # type: Optional[Vec3T]
+ self.mana = 150 # type: int
+ self.hp = 100 # type: int
+ self.name = None # type: str
+ self.inventory = None # type: List[int]
+ self.color = 8 # type: int
+ self.testType = 0 # type: int
+ self.test = None # type: Union[None, MonsterT, TestSimpleTableWithEnumT, MonsterT]
+ self.test4 = None # type: List[TestT]
+ self.testarrayofstring = None # type: List[str]
+ self.testarrayoftables = None # type: List[MonsterT]
+ self.enemy = None # type: Optional[MonsterT]
+ self.testnestedflatbuffer = None # type: List[int]
+ self.testempty = None # type: Optional[StatT]
+ self.testbool = False # type: bool
+ self.testhashs32Fnv1 = 0 # type: int
+ self.testhashu32Fnv1 = 0 # type: int
+ self.testhashs64Fnv1 = 0 # type: int
+ self.testhashu64Fnv1 = 0 # type: int
+ self.testhashs32Fnv1a = 0 # type: int
+ self.testhashu32Fnv1a = 0 # type: int
+ self.testhashs64Fnv1a = 0 # type: int
+ self.testhashu64Fnv1a = 0 # type: int
+ self.testarrayofbools = None # type: List[bool]
+ self.testf = 3.14159 # type: float
+ self.testf2 = 3.0 # type: float
+ self.testf3 = 0.0 # type: float
+ self.testarrayofstring2 = None # type: List[str]
+ self.testarrayofsortedstruct = None # type: List[AbilityT]
+ self.flex = None # type: List[int]
+ self.test5 = None # type: List[TestT]
+ self.vectorOfLongs = None # type: List[int]
+ self.vectorOfDoubles = None # type: List[float]
+ self.parentNamespaceTest = None # type: Optional[InParentNamespaceT]
+ self.vectorOfReferrables = None # type: List[ReferrableT]
+ self.singleWeakReference = 0 # type: int
+ self.vectorOfWeakReferences = None # type: List[int]
+ self.vectorOfStrongReferrables = None # type: List[ReferrableT]
+ self.coOwningReference = 0 # type: int
+ self.vectorOfCoOwningReferences = None # type: List[int]
+ self.nonOwningReference = 0 # type: int
+ self.vectorOfNonOwningReferences = None # type: List[int]
+ self.anyUniqueType = 0 # type: int
+ self.anyUnique = None # type: Union[None, MonsterT, TestSimpleTableWithEnumT, MonsterT]
+ self.anyAmbiguousType = 0 # type: int
+ self.anyAmbiguous = None # type: Union[None, MonsterT, MonsterT, MonsterT]
+ self.vectorOfEnums = None # type: List[int]
+ self.signedEnum = -1 # type: int
+ self.testrequirednestedflatbuffer = None # type: List[int]
+ self.scalarKeySortedTables = None # type: List[StatT]
+ self.nativeInline = None # type: Optional[TestT]
+ self.longEnumNonEnumDefault = 0 # type: int
+ self.longEnumNormalDefault = 2 # type: int
+
+ @classmethod
+ def InitFromBuf(cls, buf, pos):
+ monster = Monster()
+ monster.Init(buf, pos)
+ return cls.InitFromObj(monster)
+
+ @classmethod
+ def InitFromObj(cls, monster):
+ x = MonsterT()
+ x._UnPack(monster)
+ return x
+
+ # MonsterT
+ def _UnPack(self, monster):
+ if monster is None:
+ return
+ if monster.Pos() is not None:
+ self.pos = Vec3T.InitFromObj(monster.Pos())
+ self.mana = monster.Mana()
+ self.hp = monster.Hp()
+ self.name = monster.Name()
+ if not monster.InventoryIsNone():
+ if np is None:
+ self.inventory = []
+ for i in range(monster.InventoryLength()):
+ self.inventory.append(monster.Inventory(i))
+ else:
+ self.inventory = monster.InventoryAsNumpy()
+ self.color = monster.Color()
+ self.testType = monster.TestType()
+ self.test = AnyCreator(self.testType, monster.Test())
+ if not monster.Test4IsNone():
+ self.test4 = []
+ for i in range(monster.Test4Length()):
+ if monster.Test4(i) is None:
+ self.test4.append(None)
+ else:
+ test_ = TestT.InitFromObj(monster.Test4(i))
+ self.test4.append(test_)
+ if not monster.TestarrayofstringIsNone():
+ self.testarrayofstring = []
+ for i in range(monster.TestarrayofstringLength()):
+ self.testarrayofstring.append(monster.Testarrayofstring(i))
+ if not monster.TestarrayoftablesIsNone():
+ self.testarrayoftables = []
+ for i in range(monster.TestarrayoftablesLength()):
+ if monster.Testarrayoftables(i) is None:
+ self.testarrayoftables.append(None)
+ else:
+ monster_ = MonsterT.InitFromObj(monster.Testarrayoftables(i))
+ self.testarrayoftables.append(monster_)
+ if monster.Enemy() is not None:
+ self.enemy = MonsterT.InitFromObj(monster.Enemy())
+ if not monster.TestnestedflatbufferIsNone():
+ if np is None:
+ self.testnestedflatbuffer = []
+ for i in range(monster.TestnestedflatbufferLength()):
+ self.testnestedflatbuffer.append(monster.Testnestedflatbuffer(i))
+ else:
+ self.testnestedflatbuffer = monster.TestnestedflatbufferAsNumpy()
+ if monster.Testempty() is not None:
+ self.testempty = StatT.InitFromObj(monster.Testempty())
+ self.testbool = monster.Testbool()
+ self.testhashs32Fnv1 = monster.Testhashs32Fnv1()
+ self.testhashu32Fnv1 = monster.Testhashu32Fnv1()
+ self.testhashs64Fnv1 = monster.Testhashs64Fnv1()
+ self.testhashu64Fnv1 = monster.Testhashu64Fnv1()
+ self.testhashs32Fnv1a = monster.Testhashs32Fnv1a()
+ self.testhashu32Fnv1a = monster.Testhashu32Fnv1a()
+ self.testhashs64Fnv1a = monster.Testhashs64Fnv1a()
+ self.testhashu64Fnv1a = monster.Testhashu64Fnv1a()
+ if not monster.TestarrayofboolsIsNone():
+ if np is None:
+ self.testarrayofbools = []
+ for i in range(monster.TestarrayofboolsLength()):
+ self.testarrayofbools.append(monster.Testarrayofbools(i))
+ else:
+ self.testarrayofbools = monster.TestarrayofboolsAsNumpy()
+ self.testf = monster.Testf()
+ self.testf2 = monster.Testf2()
+ self.testf3 = monster.Testf3()
+ if not monster.Testarrayofstring2IsNone():
+ self.testarrayofstring2 = []
+ for i in range(monster.Testarrayofstring2Length()):
+ self.testarrayofstring2.append(monster.Testarrayofstring2(i))
+ if not monster.TestarrayofsortedstructIsNone():
+ self.testarrayofsortedstruct = []
+ for i in range(monster.TestarrayofsortedstructLength()):
+ if monster.Testarrayofsortedstruct(i) is None:
+ self.testarrayofsortedstruct.append(None)
+ else:
+ ability_ = AbilityT.InitFromObj(monster.Testarrayofsortedstruct(i))
+ self.testarrayofsortedstruct.append(ability_)
+ if not monster.FlexIsNone():
+ if np is None:
+ self.flex = []
+ for i in range(monster.FlexLength()):
+ self.flex.append(monster.Flex(i))
+ else:
+ self.flex = monster.FlexAsNumpy()
+ if not monster.Test5IsNone():
+ self.test5 = []
+ for i in range(monster.Test5Length()):
+ if monster.Test5(i) is None:
+ self.test5.append(None)
+ else:
+ test_ = TestT.InitFromObj(monster.Test5(i))
+ self.test5.append(test_)
+ if not monster.VectorOfLongsIsNone():
+ if np is None:
+ self.vectorOfLongs = []
+ for i in range(monster.VectorOfLongsLength()):
+ self.vectorOfLongs.append(monster.VectorOfLongs(i))
+ else:
+ self.vectorOfLongs = monster.VectorOfLongsAsNumpy()
+ if not monster.VectorOfDoublesIsNone():
+ if np is None:
+ self.vectorOfDoubles = []
+ for i in range(monster.VectorOfDoublesLength()):
+ self.vectorOfDoubles.append(monster.VectorOfDoubles(i))
+ else:
+ self.vectorOfDoubles = monster.VectorOfDoublesAsNumpy()
+ if monster.ParentNamespaceTest() is not None:
+ self.parentNamespaceTest = InParentNamespaceT.InitFromObj(monster.ParentNamespaceTest())
+ if not monster.VectorOfReferrablesIsNone():
+ self.vectorOfReferrables = []
+ for i in range(monster.VectorOfReferrablesLength()):
+ if monster.VectorOfReferrables(i) is None:
+ self.vectorOfReferrables.append(None)
+ else:
+ referrable_ = ReferrableT.InitFromObj(monster.VectorOfReferrables(i))
+ self.vectorOfReferrables.append(referrable_)
+ self.singleWeakReference = monster.SingleWeakReference()
+ if not monster.VectorOfWeakReferencesIsNone():
+ if np is None:
+ self.vectorOfWeakReferences = []
+ for i in range(monster.VectorOfWeakReferencesLength()):
+ self.vectorOfWeakReferences.append(monster.VectorOfWeakReferences(i))
+ else:
+ self.vectorOfWeakReferences = monster.VectorOfWeakReferencesAsNumpy()
+ if not monster.VectorOfStrongReferrablesIsNone():
+ self.vectorOfStrongReferrables = []
+ for i in range(monster.VectorOfStrongReferrablesLength()):
+ if monster.VectorOfStrongReferrables(i) is None:
+ self.vectorOfStrongReferrables.append(None)
+ else:
+ referrable_ = ReferrableT.InitFromObj(monster.VectorOfStrongReferrables(i))
+ self.vectorOfStrongReferrables.append(referrable_)
+ self.coOwningReference = monster.CoOwningReference()
+ if not monster.VectorOfCoOwningReferencesIsNone():
+ if np is None:
+ self.vectorOfCoOwningReferences = []
+ for i in range(monster.VectorOfCoOwningReferencesLength()):
+ self.vectorOfCoOwningReferences.append(monster.VectorOfCoOwningReferences(i))
+ else:
+ self.vectorOfCoOwningReferences = monster.VectorOfCoOwningReferencesAsNumpy()
+ self.nonOwningReference = monster.NonOwningReference()
+ if not monster.VectorOfNonOwningReferencesIsNone():
+ if np is None:
+ self.vectorOfNonOwningReferences = []
+ for i in range(monster.VectorOfNonOwningReferencesLength()):
+ self.vectorOfNonOwningReferences.append(monster.VectorOfNonOwningReferences(i))
+ else:
+ self.vectorOfNonOwningReferences = monster.VectorOfNonOwningReferencesAsNumpy()
+ self.anyUniqueType = monster.AnyUniqueType()
+ self.anyUnique = AnyUniqueAliasesCreator(self.anyUniqueType, monster.AnyUnique())
+ self.anyAmbiguousType = monster.AnyAmbiguousType()
+ self.anyAmbiguous = AnyAmbiguousAliasesCreator(self.anyAmbiguousType, monster.AnyAmbiguous())
+ if not monster.VectorOfEnumsIsNone():
+ if np is None:
+ self.vectorOfEnums = []
+ for i in range(monster.VectorOfEnumsLength()):
+ self.vectorOfEnums.append(monster.VectorOfEnums(i))
+ else:
+ self.vectorOfEnums = monster.VectorOfEnumsAsNumpy()
+ self.signedEnum = monster.SignedEnum()
+ if not monster.TestrequirednestedflatbufferIsNone():
+ if np is None:
+ self.testrequirednestedflatbuffer = []
+ for i in range(monster.TestrequirednestedflatbufferLength()):
+ self.testrequirednestedflatbuffer.append(monster.Testrequirednestedflatbuffer(i))
+ else:
+ self.testrequirednestedflatbuffer = monster.TestrequirednestedflatbufferAsNumpy()
+ if not monster.ScalarKeySortedTablesIsNone():
+ self.scalarKeySortedTables = []
+ for i in range(monster.ScalarKeySortedTablesLength()):
+ if monster.ScalarKeySortedTables(i) is None:
+ self.scalarKeySortedTables.append(None)
+ else:
+ stat_ = StatT.InitFromObj(monster.ScalarKeySortedTables(i))
+ self.scalarKeySortedTables.append(stat_)
+ if monster.NativeInline() is not None:
+ self.nativeInline = TestT.InitFromObj(monster.NativeInline())
+ self.longEnumNonEnumDefault = monster.LongEnumNonEnumDefault()
+ self.longEnumNormalDefault = monster.LongEnumNormalDefault()
+
+ # MonsterT
+ def Pack(self, builder):
+ if self.name is not None:
+ name = builder.CreateString(self.name)
+ if self.inventory is not None:
+ if np is not None and type(self.inventory) is np.ndarray:
+ inventory = builder.CreateNumpyVector(self.inventory)
+ else:
+ MonsterStartInventoryVector(builder, len(self.inventory))
+ for i in reversed(range(len(self.inventory))):
+ builder.PrependUint8(self.inventory[i])
+ inventory = builder.EndVector()
+ if self.test is not None:
+ test = self.test.Pack(builder)
+ if self.test4 is not None:
+ MonsterStartTest4Vector(builder, len(self.test4))
+ for i in reversed(range(len(self.test4))):
+ self.test4[i].Pack(builder)
+ test4 = builder.EndVector()
+ if self.testarrayofstring is not None:
+ testarrayofstringlist = []
+ for i in range(len(self.testarrayofstring)):
+ testarrayofstringlist.append(builder.CreateString(self.testarrayofstring[i]))
+ MonsterStartTestarrayofstringVector(builder, len(self.testarrayofstring))
+ for i in reversed(range(len(self.testarrayofstring))):
+ builder.PrependUOffsetTRelative(testarrayofstringlist[i])
+ testarrayofstring = builder.EndVector()
+ if self.testarrayoftables is not None:
+ testarrayoftableslist = []
+ for i in range(len(self.testarrayoftables)):
+ testarrayoftableslist.append(self.testarrayoftables[i].Pack(builder))
+ MonsterStartTestarrayoftablesVector(builder, len(self.testarrayoftables))
+ for i in reversed(range(len(self.testarrayoftables))):
+ builder.PrependUOffsetTRelative(testarrayoftableslist[i])
+ testarrayoftables = builder.EndVector()
+ if self.enemy is not None:
+ enemy = self.enemy.Pack(builder)
+ if self.testnestedflatbuffer is not None:
+ if np is not None and type(self.testnestedflatbuffer) is np.ndarray:
+ testnestedflatbuffer = builder.CreateNumpyVector(self.testnestedflatbuffer)
+ else:
+ MonsterStartTestnestedflatbufferVector(builder, len(self.testnestedflatbuffer))
+ for i in reversed(range(len(self.testnestedflatbuffer))):
+ builder.PrependUint8(self.testnestedflatbuffer[i])
+ testnestedflatbuffer = builder.EndVector()
+ if self.testempty is not None:
+ testempty = self.testempty.Pack(builder)
+ if self.testarrayofbools is not None:
+ if np is not None and type(self.testarrayofbools) is np.ndarray:
+ testarrayofbools = builder.CreateNumpyVector(self.testarrayofbools)
+ else:
+ MonsterStartTestarrayofboolsVector(builder, len(self.testarrayofbools))
+ for i in reversed(range(len(self.testarrayofbools))):
+ builder.PrependBool(self.testarrayofbools[i])
+ testarrayofbools = builder.EndVector()
+ if self.testarrayofstring2 is not None:
+ testarrayofstring2list = []
+ for i in range(len(self.testarrayofstring2)):
+ testarrayofstring2list.append(builder.CreateString(self.testarrayofstring2[i]))
+ MonsterStartTestarrayofstring2Vector(builder, len(self.testarrayofstring2))
+ for i in reversed(range(len(self.testarrayofstring2))):
+ builder.PrependUOffsetTRelative(testarrayofstring2list[i])
+ testarrayofstring2 = builder.EndVector()
+ if self.testarrayofsortedstruct is not None:
+ MonsterStartTestarrayofsortedstructVector(builder, len(self.testarrayofsortedstruct))
+ for i in reversed(range(len(self.testarrayofsortedstruct))):
+ self.testarrayofsortedstruct[i].Pack(builder)
+ testarrayofsortedstruct = builder.EndVector()
+ if self.flex is not None:
+ if np is not None and type(self.flex) is np.ndarray:
+ flex = builder.CreateNumpyVector(self.flex)
+ else:
+ MonsterStartFlexVector(builder, len(self.flex))
+ for i in reversed(range(len(self.flex))):
+ builder.PrependUint8(self.flex[i])
+ flex = builder.EndVector()
+ if self.test5 is not None:
+ MonsterStartTest5Vector(builder, len(self.test5))
+ for i in reversed(range(len(self.test5))):
+ self.test5[i].Pack(builder)
+ test5 = builder.EndVector()
+ if self.vectorOfLongs is not None:
+ if np is not None and type(self.vectorOfLongs) is np.ndarray:
+ vectorOfLongs = builder.CreateNumpyVector(self.vectorOfLongs)
+ else:
+ MonsterStartVectorOfLongsVector(builder, len(self.vectorOfLongs))
+ for i in reversed(range(len(self.vectorOfLongs))):
+ builder.PrependInt64(self.vectorOfLongs[i])
+ vectorOfLongs = builder.EndVector()
+ if self.vectorOfDoubles is not None:
+ if np is not None and type(self.vectorOfDoubles) is np.ndarray:
+ vectorOfDoubles = builder.CreateNumpyVector(self.vectorOfDoubles)
+ else:
+ MonsterStartVectorOfDoublesVector(builder, len(self.vectorOfDoubles))
+ for i in reversed(range(len(self.vectorOfDoubles))):
+ builder.PrependFloat64(self.vectorOfDoubles[i])
+ vectorOfDoubles = builder.EndVector()
+ if self.parentNamespaceTest is not None:
+ parentNamespaceTest = self.parentNamespaceTest.Pack(builder)
+ if self.vectorOfReferrables is not None:
+ vectorOfReferrableslist = []
+ for i in range(len(self.vectorOfReferrables)):
+ vectorOfReferrableslist.append(self.vectorOfReferrables[i].Pack(builder))
+ MonsterStartVectorOfReferrablesVector(builder, len(self.vectorOfReferrables))
+ for i in reversed(range(len(self.vectorOfReferrables))):
+ builder.PrependUOffsetTRelative(vectorOfReferrableslist[i])
+ vectorOfReferrables = builder.EndVector()
+ if self.vectorOfWeakReferences is not None:
+ if np is not None and type(self.vectorOfWeakReferences) is np.ndarray:
+ vectorOfWeakReferences = builder.CreateNumpyVector(self.vectorOfWeakReferences)
+ else:
+ MonsterStartVectorOfWeakReferencesVector(builder, len(self.vectorOfWeakReferences))
+ for i in reversed(range(len(self.vectorOfWeakReferences))):
+ builder.PrependUint64(self.vectorOfWeakReferences[i])
+ vectorOfWeakReferences = builder.EndVector()
+ if self.vectorOfStrongReferrables is not None:
+ vectorOfStrongReferrableslist = []
+ for i in range(len(self.vectorOfStrongReferrables)):
+ vectorOfStrongReferrableslist.append(self.vectorOfStrongReferrables[i].Pack(builder))
+ MonsterStartVectorOfStrongReferrablesVector(builder, len(self.vectorOfStrongReferrables))
+ for i in reversed(range(len(self.vectorOfStrongReferrables))):
+ builder.PrependUOffsetTRelative(vectorOfStrongReferrableslist[i])
+ vectorOfStrongReferrables = builder.EndVector()
+ if self.vectorOfCoOwningReferences is not None:
+ if np is not None and type(self.vectorOfCoOwningReferences) is np.ndarray:
+ vectorOfCoOwningReferences = builder.CreateNumpyVector(self.vectorOfCoOwningReferences)
+ else:
+ MonsterStartVectorOfCoOwningReferencesVector(builder, len(self.vectorOfCoOwningReferences))
+ for i in reversed(range(len(self.vectorOfCoOwningReferences))):
+ builder.PrependUint64(self.vectorOfCoOwningReferences[i])
+ vectorOfCoOwningReferences = builder.EndVector()
+ if self.vectorOfNonOwningReferences is not None:
+ if np is not None and type(self.vectorOfNonOwningReferences) is np.ndarray:
+ vectorOfNonOwningReferences = builder.CreateNumpyVector(self.vectorOfNonOwningReferences)
+ else:
+ MonsterStartVectorOfNonOwningReferencesVector(builder, len(self.vectorOfNonOwningReferences))
+ for i in reversed(range(len(self.vectorOfNonOwningReferences))):
+ builder.PrependUint64(self.vectorOfNonOwningReferences[i])
+ vectorOfNonOwningReferences = builder.EndVector()
+ if self.anyUnique is not None:
+ anyUnique = self.anyUnique.Pack(builder)
+ if self.anyAmbiguous is not None:
+ anyAmbiguous = self.anyAmbiguous.Pack(builder)
+ if self.vectorOfEnums is not None:
+ if np is not None and type(self.vectorOfEnums) is np.ndarray:
+ vectorOfEnums = builder.CreateNumpyVector(self.vectorOfEnums)
+ else:
+ MonsterStartVectorOfEnumsVector(builder, len(self.vectorOfEnums))
+ for i in reversed(range(len(self.vectorOfEnums))):
+ builder.PrependUint8(self.vectorOfEnums[i])
+ vectorOfEnums = builder.EndVector()
+ if self.testrequirednestedflatbuffer is not None:
+ if np is not None and type(self.testrequirednestedflatbuffer) is np.ndarray:
+ testrequirednestedflatbuffer = builder.CreateNumpyVector(self.testrequirednestedflatbuffer)
+ else:
+ MonsterStartTestrequirednestedflatbufferVector(builder, len(self.testrequirednestedflatbuffer))
+ for i in reversed(range(len(self.testrequirednestedflatbuffer))):
+ builder.PrependUint8(self.testrequirednestedflatbuffer[i])
+ testrequirednestedflatbuffer = builder.EndVector()
+ if self.scalarKeySortedTables is not None:
+ scalarKeySortedTableslist = []
+ for i in range(len(self.scalarKeySortedTables)):
+ scalarKeySortedTableslist.append(self.scalarKeySortedTables[i].Pack(builder))
+ MonsterStartScalarKeySortedTablesVector(builder, len(self.scalarKeySortedTables))
+ for i in reversed(range(len(self.scalarKeySortedTables))):
+ builder.PrependUOffsetTRelative(scalarKeySortedTableslist[i])
+ scalarKeySortedTables = builder.EndVector()
+ MonsterStart(builder)
+ if self.pos is not None:
+ pos = self.pos.Pack(builder)
+ MonsterAddPos(builder, pos)
+ MonsterAddMana(builder, self.mana)
+ MonsterAddHp(builder, self.hp)
+ if self.name is not None:
+ MonsterAddName(builder, name)
+ if self.inventory is not None:
+ MonsterAddInventory(builder, inventory)
+ MonsterAddColor(builder, self.color)
+ MonsterAddTestType(builder, self.testType)
+ if self.test is not None:
+ MonsterAddTest(builder, test)
+ if self.test4 is not None:
+ MonsterAddTest4(builder, test4)
+ if self.testarrayofstring is not None:
+ MonsterAddTestarrayofstring(builder, testarrayofstring)
+ if self.testarrayoftables is not None:
+ MonsterAddTestarrayoftables(builder, testarrayoftables)
+ if self.enemy is not None:
+ MonsterAddEnemy(builder, enemy)
+ if self.testnestedflatbuffer is not None:
+ MonsterAddTestnestedflatbuffer(builder, testnestedflatbuffer)
+ if self.testempty is not None:
+ MonsterAddTestempty(builder, testempty)
+ MonsterAddTestbool(builder, self.testbool)
+ MonsterAddTesthashs32Fnv1(builder, self.testhashs32Fnv1)
+ MonsterAddTesthashu32Fnv1(builder, self.testhashu32Fnv1)
+ MonsterAddTesthashs64Fnv1(builder, self.testhashs64Fnv1)
+ MonsterAddTesthashu64Fnv1(builder, self.testhashu64Fnv1)
+ MonsterAddTesthashs32Fnv1a(builder, self.testhashs32Fnv1a)
+ MonsterAddTesthashu32Fnv1a(builder, self.testhashu32Fnv1a)
+ MonsterAddTesthashs64Fnv1a(builder, self.testhashs64Fnv1a)
+ MonsterAddTesthashu64Fnv1a(builder, self.testhashu64Fnv1a)
+ if self.testarrayofbools is not None:
+ MonsterAddTestarrayofbools(builder, testarrayofbools)
+ MonsterAddTestf(builder, self.testf)
+ MonsterAddTestf2(builder, self.testf2)
+ MonsterAddTestf3(builder, self.testf3)
+ if self.testarrayofstring2 is not None:
+ MonsterAddTestarrayofstring2(builder, testarrayofstring2)
+ if self.testarrayofsortedstruct is not None:
+ MonsterAddTestarrayofsortedstruct(builder, testarrayofsortedstruct)
+ if self.flex is not None:
+ MonsterAddFlex(builder, flex)
+ if self.test5 is not None:
+ MonsterAddTest5(builder, test5)
+ if self.vectorOfLongs is not None:
+ MonsterAddVectorOfLongs(builder, vectorOfLongs)
+ if self.vectorOfDoubles is not None:
+ MonsterAddVectorOfDoubles(builder, vectorOfDoubles)
+ if self.parentNamespaceTest is not None:
+ MonsterAddParentNamespaceTest(builder, parentNamespaceTest)
+ if self.vectorOfReferrables is not None:
+ MonsterAddVectorOfReferrables(builder, vectorOfReferrables)
+ MonsterAddSingleWeakReference(builder, self.singleWeakReference)
+ if self.vectorOfWeakReferences is not None:
+ MonsterAddVectorOfWeakReferences(builder, vectorOfWeakReferences)
+ if self.vectorOfStrongReferrables is not None:
+ MonsterAddVectorOfStrongReferrables(builder, vectorOfStrongReferrables)
+ MonsterAddCoOwningReference(builder, self.coOwningReference)
+ if self.vectorOfCoOwningReferences is not None:
+ MonsterAddVectorOfCoOwningReferences(builder, vectorOfCoOwningReferences)
+ MonsterAddNonOwningReference(builder, self.nonOwningReference)
+ if self.vectorOfNonOwningReferences is not None:
+ MonsterAddVectorOfNonOwningReferences(builder, vectorOfNonOwningReferences)
+ MonsterAddAnyUniqueType(builder, self.anyUniqueType)
+ if self.anyUnique is not None:
+ MonsterAddAnyUnique(builder, anyUnique)
+ MonsterAddAnyAmbiguousType(builder, self.anyAmbiguousType)
+ if self.anyAmbiguous is not None:
+ MonsterAddAnyAmbiguous(builder, anyAmbiguous)
+ if self.vectorOfEnums is not None:
+ MonsterAddVectorOfEnums(builder, vectorOfEnums)
+ MonsterAddSignedEnum(builder, self.signedEnum)
+ if self.testrequirednestedflatbuffer is not None:
+ MonsterAddTestrequirednestedflatbuffer(builder, testrequirednestedflatbuffer)
+ if self.scalarKeySortedTables is not None:
+ MonsterAddScalarKeySortedTables(builder, scalarKeySortedTables)
+ if self.nativeInline is not None:
+ nativeInline = self.nativeInline.Pack(builder)
+ MonsterAddNativeInline(builder, nativeInline)
+ MonsterAddLongEnumNonEnumDefault(builder, self.longEnumNonEnumDefault)
+ MonsterAddLongEnumNormalDefault(builder, self.longEnumNormalDefault)
+ monster = MonsterEnd(builder)
+ return monster
+
+
+class TypeAliases(object):
+ __slots__ = ['_tab']
+
+ @classmethod
+ def GetRootAs(cls, buf, offset=0):
+ n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
+ x = TypeAliases()
+ x.Init(buf, n + offset)
+ return x
+
+ @classmethod
+ def GetRootAsTypeAliases(cls, buf, offset=0):
+ """This method is deprecated. Please switch to GetRootAs."""
+ return cls.GetRootAs(buf, offset)
+ @classmethod
+ def TypeAliasesBufferHasIdentifier(cls, buf, offset, size_prefixed=False):
+ return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4D\x4F\x4E\x53", size_prefixed=size_prefixed)
+
+ # TypeAliases
+ def Init(self, buf, pos):
+ self._tab = flatbuffers.table.Table(buf, pos)
+
+ # TypeAliases
+ def I8(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos)
+ return 0
+
+ # TypeAliases
+ def U8(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Uint8Flags, o + self._tab.Pos)
+ return 0
+
+ # TypeAliases
+ def I16(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Int16Flags, o + self._tab.Pos)
+ return 0
+
+ # TypeAliases
+ def U16(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Uint16Flags, o + self._tab.Pos)
+ return 0
+
+ # TypeAliases
+ def I32(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos)
+ return 0
+
+ # TypeAliases
+ def U32(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Uint32Flags, o + self._tab.Pos)
+ return 0
+
+ # TypeAliases
+ def I64(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(16))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Int64Flags, o + self._tab.Pos)
+ return 0
+
+ # TypeAliases
+ def U64(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(18))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Uint64Flags, o + self._tab.Pos)
+ return 0
+
+ # TypeAliases
+ def F32(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(20))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Float32Flags, o + self._tab.Pos)
+ return 0.0
+
+ # TypeAliases
+ def F64(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(22))
+ if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Float64Flags, o + self._tab.Pos)
+ return 0.0
+
+ # TypeAliases
+ def V8(self, j):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(24))
+ if o != 0:
+ a = self._tab.Vector(o)
+ return self._tab.Get(flatbuffers.number_types.Int8Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 1))
+ return 0
+
+ # TypeAliases
+ def V8AsNumpy(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(24))
+ if o != 0:
+ return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int8Flags, o)
+ return 0
+
+ # TypeAliases
+ def V8Length(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(24))
+ if o != 0:
+ return self._tab.VectorLen(o)
+ return 0
+
+ # TypeAliases
+ def V8IsNone(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(24))
+ return o == 0
+
+ # TypeAliases
+ def Vf64(self, j):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(26))
+ if o != 0:
+ a = self._tab.Vector(o)
+ return self._tab.Get(flatbuffers.number_types.Float64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8))
+ return 0
+
+ # TypeAliases
+ def Vf64AsNumpy(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(26))
+ if o != 0:
+ return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Float64Flags, o)
+ return 0
+
+ # TypeAliases
+ def Vf64Length(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(26))
+ if o != 0:
+ return self._tab.VectorLen(o)
+ return 0
+
+ # TypeAliases
+ def Vf64IsNone(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(26))
+ return o == 0
+
+def TypeAliasesStart(builder): builder.StartObject(12)
+def TypeAliasesAddI8(builder, i8): builder.PrependInt8Slot(0, i8, 0)
+def TypeAliasesAddU8(builder, u8): builder.PrependUint8Slot(1, u8, 0)
+def TypeAliasesAddI16(builder, i16): builder.PrependInt16Slot(2, i16, 0)
+def TypeAliasesAddU16(builder, u16): builder.PrependUint16Slot(3, u16, 0)
+def TypeAliasesAddI32(builder, i32): builder.PrependInt32Slot(4, i32, 0)
+def TypeAliasesAddU32(builder, u32): builder.PrependUint32Slot(5, u32, 0)
+def TypeAliasesAddI64(builder, i64): builder.PrependInt64Slot(6, i64, 0)
+def TypeAliasesAddU64(builder, u64): builder.PrependUint64Slot(7, u64, 0)
+def TypeAliasesAddF32(builder, f32): builder.PrependFloat32Slot(8, f32, 0.0)
+def TypeAliasesAddF64(builder, f64): builder.PrependFloat64Slot(9, f64, 0.0)
+def TypeAliasesAddV8(builder, v8): builder.PrependUOffsetTRelativeSlot(10, flatbuffers.number_types.UOffsetTFlags.py_type(v8), 0)
+def TypeAliasesStartV8Vector(builder, numElems): return builder.StartVector(1, numElems, 1)
+def TypeAliasesAddVf64(builder, vf64): builder.PrependUOffsetTRelativeSlot(11, flatbuffers.number_types.UOffsetTFlags.py_type(vf64), 0)
+def TypeAliasesStartVf64Vector(builder, numElems): return builder.StartVector(8, numElems, 8)
+def TypeAliasesEnd(builder): return builder.EndObject()
+
+try:
+ from typing import List
+except:
+ pass
+
+class TypeAliasesT(object):
+
+ # TypeAliasesT
+ def __init__(self):
+ self.i8 = 0 # type: int
+ self.u8 = 0 # type: int
+ self.i16 = 0 # type: int
+ self.u16 = 0 # type: int
+ self.i32 = 0 # type: int
+ self.u32 = 0 # type: int
+ self.i64 = 0 # type: int
+ self.u64 = 0 # type: int
+ self.f32 = 0.0 # type: float
+ self.f64 = 0.0 # type: float
+ self.v8 = None # type: List[int]
+ self.vf64 = None # type: List[float]
+
+ @classmethod
+ def InitFromBuf(cls, buf, pos):
+ typeAliases = TypeAliases()
+ typeAliases.Init(buf, pos)
+ return cls.InitFromObj(typeAliases)
+
+ @classmethod
+ def InitFromObj(cls, typeAliases):
+ x = TypeAliasesT()
+ x._UnPack(typeAliases)
+ return x
+
+ # TypeAliasesT
+ def _UnPack(self, typeAliases):
+ if typeAliases is None:
+ return
+ self.i8 = typeAliases.I8()
+ self.u8 = typeAliases.U8()
+ self.i16 = typeAliases.I16()
+ self.u16 = typeAliases.U16()
+ self.i32 = typeAliases.I32()
+ self.u32 = typeAliases.U32()
+ self.i64 = typeAliases.I64()
+ self.u64 = typeAliases.U64()
+ self.f32 = typeAliases.F32()
+ self.f64 = typeAliases.F64()
+ if not typeAliases.V8IsNone():
+ if np is None:
+ self.v8 = []
+ for i in range(typeAliases.V8Length()):
+ self.v8.append(typeAliases.V8(i))
+ else:
+ self.v8 = typeAliases.V8AsNumpy()
+ if not typeAliases.Vf64IsNone():
+ if np is None:
+ self.vf64 = []
+ for i in range(typeAliases.Vf64Length()):
+ self.vf64.append(typeAliases.Vf64(i))
+ else:
+ self.vf64 = typeAliases.Vf64AsNumpy()
+
+ # TypeAliasesT
+ def Pack(self, builder):
+ if self.v8 is not None:
+ if np is not None and type(self.v8) is np.ndarray:
+ v8 = builder.CreateNumpyVector(self.v8)
+ else:
+ TypeAliasesStartV8Vector(builder, len(self.v8))
+ for i in reversed(range(len(self.v8))):
+ builder.PrependByte(self.v8[i])
+ v8 = builder.EndVector()
+ if self.vf64 is not None:
+ if np is not None and type(self.vf64) is np.ndarray:
+ vf64 = builder.CreateNumpyVector(self.vf64)
+ else:
+ TypeAliasesStartVf64Vector(builder, len(self.vf64))
+ for i in reversed(range(len(self.vf64))):
+ builder.PrependFloat64(self.vf64[i])
+ vf64 = builder.EndVector()
+ TypeAliasesStart(builder)
+ TypeAliasesAddI8(builder, self.i8)
+ TypeAliasesAddU8(builder, self.u8)
+ TypeAliasesAddI16(builder, self.i16)
+ TypeAliasesAddU16(builder, self.u16)
+ TypeAliasesAddI32(builder, self.i32)
+ TypeAliasesAddU32(builder, self.u32)
+ TypeAliasesAddI64(builder, self.i64)
+ TypeAliasesAddU64(builder, self.u64)
+ TypeAliasesAddF32(builder, self.f32)
+ TypeAliasesAddF64(builder, self.f64)
+ if self.v8 is not None:
+ TypeAliasesAddV8(builder, v8)
+ if self.vf64 is not None:
+ TypeAliasesAddVf64(builder, vf64)
+ typeAliases = TypeAliasesEnd(builder)
+ return typeAliases
+
+
diff --git a/tests/monster_test_generated.rs b/tests/monster_test_generated.rs
deleted file mode 100644
index e653933..0000000
--- a/tests/monster_test_generated.rs
+++ /dev/null
@@ -1,2275 +0,0 @@
-// automatically generated by the FlatBuffers compiler, do not modify
-
-
-#![allow(unused_imports, dead_code)]
-
-use crate::include_test1_generated::*;
-use crate::include_test2_generated::*;
-use std::mem;
-use std::cmp::Ordering;
-
-extern crate flatbuffers;
-use self::flatbuffers::EndianScalar;
-
-#[allow(unused_imports, dead_code)]
-pub mod my_game {
-
- use crate::include_test1_generated::*;
- use crate::include_test2_generated::*;
- use std::mem;
- use std::cmp::Ordering;
-
- extern crate flatbuffers;
- use self::flatbuffers::EndianScalar;
-
-pub enum InParentNamespaceOffset {}
-#[derive(Copy, Clone, PartialEq)]
-
-pub struct InParentNamespace<'a> {
- pub _tab: flatbuffers::Table<'a>,
-}
-
-impl<'a> flatbuffers::Follow<'a> for InParentNamespace<'a> {
- type Inner = InParentNamespace<'a>;
- #[inline]
- fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
- Self { _tab: flatbuffers::Table { buf, loc } }
- }
-}
-
-impl<'a> InParentNamespace<'a> {
- pub const fn get_fully_qualified_name() -> &'static str {
- "MyGame.InParentNamespace"
- }
-
- #[inline]
- pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
- InParentNamespace {
- _tab: table,
- }
- }
- #[allow(unused_mut)]
- pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
- _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
- _args: &'args InParentNamespaceArgs) -> flatbuffers::WIPOffset<InParentNamespace<'bldr>> {
- let mut builder = InParentNamespaceBuilder::new(_fbb);
- builder.finish()
- }
-
-}
-
-pub struct InParentNamespaceArgs {
-}
-impl<'a> Default for InParentNamespaceArgs {
- #[inline]
- fn default() -> Self {
- InParentNamespaceArgs {
- }
- }
-}
-pub struct InParentNamespaceBuilder<'a: 'b, 'b> {
- fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
- start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
-}
-impl<'a: 'b, 'b> InParentNamespaceBuilder<'a, 'b> {
- #[inline]
- pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> InParentNamespaceBuilder<'a, 'b> {
- let start = _fbb.start_table();
- InParentNamespaceBuilder {
- fbb_: _fbb,
- start_: start,
- }
- }
- #[inline]
- pub fn finish(self) -> flatbuffers::WIPOffset<InParentNamespace<'a>> {
- let o = self.fbb_.end_table(self.start_);
- flatbuffers::WIPOffset::new(o.value())
- }
-}
-
-impl std::fmt::Debug for InParentNamespace<'_> {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- let mut ds = f.debug_struct("InParentNamespace");
- ds.finish()
- }
-}
-#[allow(unused_imports, dead_code)]
-pub mod example_2 {
-
- use crate::include_test1_generated::*;
- use crate::include_test2_generated::*;
- use std::mem;
- use std::cmp::Ordering;
-
- extern crate flatbuffers;
- use self::flatbuffers::EndianScalar;
-
-pub enum MonsterOffset {}
-#[derive(Copy, Clone, PartialEq)]
-
-pub struct Monster<'a> {
- pub _tab: flatbuffers::Table<'a>,
-}
-
-impl<'a> flatbuffers::Follow<'a> for Monster<'a> {
- type Inner = Monster<'a>;
- #[inline]
- fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
- Self { _tab: flatbuffers::Table { buf, loc } }
- }
-}
-
-impl<'a> Monster<'a> {
- pub const fn get_fully_qualified_name() -> &'static str {
- "MyGame.Example2.Monster"
- }
-
- #[inline]
- pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
- Monster {
- _tab: table,
- }
- }
- #[allow(unused_mut)]
- pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
- _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
- _args: &'args MonsterArgs) -> flatbuffers::WIPOffset<Monster<'bldr>> {
- let mut builder = MonsterBuilder::new(_fbb);
- builder.finish()
- }
-
-}
-
-pub struct MonsterArgs {
-}
-impl<'a> Default for MonsterArgs {
- #[inline]
- fn default() -> Self {
- MonsterArgs {
- }
- }
-}
-pub struct MonsterBuilder<'a: 'b, 'b> {
- fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
- start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
-}
-impl<'a: 'b, 'b> MonsterBuilder<'a, 'b> {
- #[inline]
- pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> MonsterBuilder<'a, 'b> {
- let start = _fbb.start_table();
- MonsterBuilder {
- fbb_: _fbb,
- start_: start,
- }
- }
- #[inline]
- pub fn finish(self) -> flatbuffers::WIPOffset<Monster<'a>> {
- let o = self.fbb_.end_table(self.start_);
- flatbuffers::WIPOffset::new(o.value())
- }
-}
-
-impl std::fmt::Debug for Monster<'_> {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- let mut ds = f.debug_struct("Monster");
- ds.finish()
- }
-}
-} // pub mod Example2
-
-#[allow(unused_imports, dead_code)]
-pub mod example {
-
- use crate::include_test1_generated::*;
- use crate::include_test2_generated::*;
- use std::mem;
- use std::cmp::Ordering;
-
- extern crate flatbuffers;
- use self::flatbuffers::EndianScalar;
-
-#[allow(non_upper_case_globals)]
-mod bitflags_color {
- flatbuffers::bitflags::bitflags! {
- /// Composite components of Monster color.
- pub struct Color: u8 {
- const Red = 1;
- /// \brief color Green
- /// Green is bit_flag with value (1u << 1)
- const Green = 2;
- /// \brief color Blue (1u << 3)
- const Blue = 8;
- }
- }
-}
-pub use self::bitflags_color::Color;
-
-impl<'a> flatbuffers::Follow<'a> for Color {
- type Inner = Self;
- #[inline]
- fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
- let bits = flatbuffers::read_scalar_at::<u8>(buf, loc);
- unsafe { Self::from_bits_unchecked(bits) }
- }
-}
-
-impl flatbuffers::Push for Color {
- type Output = Color;
- #[inline]
- fn push(&self, dst: &mut [u8], _rest: &[u8]) {
- flatbuffers::emplace_scalar::<u8>(dst, self.bits());
- }
-}
-
-impl flatbuffers::EndianScalar for Color {
- #[inline]
- fn to_little_endian(self) -> Self {
- let bits = u8::to_le(self.bits());
- unsafe { Self::from_bits_unchecked(bits) }
- }
- #[inline]
- fn from_little_endian(self) -> Self {
- let bits = u8::from_le(self.bits());
- unsafe { Self::from_bits_unchecked(bits) }
- }
-}
-
-#[deprecated(since = "1.13", note = "Use associated constants instead. This will no longer be generated in 2021.")]
-pub const ENUM_MIN_RACE: i8 = -1;
-#[deprecated(since = "1.13", note = "Use associated constants instead. This will no longer be generated in 2021.")]
-pub const ENUM_MAX_RACE: i8 = 2;
-#[deprecated(since = "1.13", note = "Use associated constants instead. This will no longer be generated in 2021.")]
-#[allow(non_camel_case_types)]
-pub const ENUM_VALUES_RACE: [Race; 4] = [
- Race::None,
- Race::Human,
- Race::Dwarf,
- Race::Elf,
-];
-
-#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
-#[repr(transparent)]
-pub struct Race(pub i8);
-#[allow(non_upper_case_globals)]
-impl Race {
- pub const None: Self = Self(-1);
- pub const Human: Self = Self(0);
- pub const Dwarf: Self = Self(1);
- pub const Elf: Self = Self(2);
-
- pub const ENUM_MIN: i8 = -1;
- pub const ENUM_MAX: i8 = 2;
- pub const ENUM_VALUES: &'static [Self] = &[
- Self::None,
- Self::Human,
- Self::Dwarf,
- Self::Elf,
- ];
- /// Returns the variant's name or "" if unknown.
- pub fn variant_name(self) -> Option<&'static str> {
- match self {
- Self::None => Some("None"),
- Self::Human => Some("Human"),
- Self::Dwarf => Some("Dwarf"),
- Self::Elf => Some("Elf"),
- _ => None,
- }
- }
-}
-impl std::fmt::Debug for Race {
- fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
- if let Some(name) = self.variant_name() {
- f.write_str(name)
- } else {
- f.write_fmt(format_args!("<UNKNOWN {:?}>", self.0))
- }
- }
-}
-impl<'a> flatbuffers::Follow<'a> for Race {
- type Inner = Self;
- #[inline]
- fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
- Self(flatbuffers::read_scalar_at::<i8>(buf, loc))
- }
-}
-
-impl flatbuffers::Push for Race {
- type Output = Race;
- #[inline]
- fn push(&self, dst: &mut [u8], _rest: &[u8]) {
- flatbuffers::emplace_scalar::<i8>(dst, self.0);
- }
-}
-
-impl flatbuffers::EndianScalar for Race {
- #[inline]
- fn to_little_endian(self) -> Self {
- Self(i8::to_le(self.0))
- }
- #[inline]
- fn from_little_endian(self) -> Self {
- Self(i8::from_le(self.0))
- }
-}
-
-#[deprecated(since = "1.13", note = "Use associated constants instead. This will no longer be generated in 2021.")]
-pub const ENUM_MIN_ANY: u8 = 0;
-#[deprecated(since = "1.13", note = "Use associated constants instead. This will no longer be generated in 2021.")]
-pub const ENUM_MAX_ANY: u8 = 3;
-#[deprecated(since = "1.13", note = "Use associated constants instead. This will no longer be generated in 2021.")]
-#[allow(non_camel_case_types)]
-pub const ENUM_VALUES_ANY: [Any; 4] = [
- Any::NONE,
- Any::Monster,
- Any::TestSimpleTableWithEnum,
- Any::MyGame_Example2_Monster,
-];
-
-#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
-#[repr(transparent)]
-pub struct Any(pub u8);
-#[allow(non_upper_case_globals)]
-impl Any {
- pub const NONE: Self = Self(0);
- pub const Monster: Self = Self(1);
- pub const TestSimpleTableWithEnum: Self = Self(2);
- pub const MyGame_Example2_Monster: Self = Self(3);
-
- pub const ENUM_MIN: u8 = 0;
- pub const ENUM_MAX: u8 = 3;
- pub const ENUM_VALUES: &'static [Self] = &[
- Self::NONE,
- Self::Monster,
- Self::TestSimpleTableWithEnum,
- Self::MyGame_Example2_Monster,
- ];
- /// Returns the variant's name or "" if unknown.
- pub fn variant_name(self) -> Option<&'static str> {
- match self {
- Self::NONE => Some("NONE"),
- Self::Monster => Some("Monster"),
- Self::TestSimpleTableWithEnum => Some("TestSimpleTableWithEnum"),
- Self::MyGame_Example2_Monster => Some("MyGame_Example2_Monster"),
- _ => None,
- }
- }
-}
-impl std::fmt::Debug for Any {
- fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
- if let Some(name) = self.variant_name() {
- f.write_str(name)
- } else {
- f.write_fmt(format_args!("<UNKNOWN {:?}>", self.0))
- }
- }
-}
-impl<'a> flatbuffers::Follow<'a> for Any {
- type Inner = Self;
- #[inline]
- fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
- Self(flatbuffers::read_scalar_at::<u8>(buf, loc))
- }
-}
-
-impl flatbuffers::Push for Any {
- type Output = Any;
- #[inline]
- fn push(&self, dst: &mut [u8], _rest: &[u8]) {
- flatbuffers::emplace_scalar::<u8>(dst, self.0);
- }
-}
-
-impl flatbuffers::EndianScalar for Any {
- #[inline]
- fn to_little_endian(self) -> Self {
- Self(u8::to_le(self.0))
- }
- #[inline]
- fn from_little_endian(self) -> Self {
- Self(u8::from_le(self.0))
- }
-}
-
-pub struct AnyUnionTableOffset {}
-#[deprecated(since = "1.13", note = "Use associated constants instead. This will no longer be generated in 2021.")]
-pub const ENUM_MIN_ANY_UNIQUE_ALIASES: u8 = 0;
-#[deprecated(since = "1.13", note = "Use associated constants instead. This will no longer be generated in 2021.")]
-pub const ENUM_MAX_ANY_UNIQUE_ALIASES: u8 = 3;
-#[deprecated(since = "1.13", note = "Use associated constants instead. This will no longer be generated in 2021.")]
-#[allow(non_camel_case_types)]
-pub const ENUM_VALUES_ANY_UNIQUE_ALIASES: [AnyUniqueAliases; 4] = [
- AnyUniqueAliases::NONE,
- AnyUniqueAliases::M,
- AnyUniqueAliases::TS,
- AnyUniqueAliases::M2,
-];
-
-#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
-#[repr(transparent)]
-pub struct AnyUniqueAliases(pub u8);
-#[allow(non_upper_case_globals)]
-impl AnyUniqueAliases {
- pub const NONE: Self = Self(0);
- pub const M: Self = Self(1);
- pub const TS: Self = Self(2);
- pub const M2: Self = Self(3);
-
- pub const ENUM_MIN: u8 = 0;
- pub const ENUM_MAX: u8 = 3;
- pub const ENUM_VALUES: &'static [Self] = &[
- Self::NONE,
- Self::M,
- Self::TS,
- Self::M2,
- ];
- /// Returns the variant's name or "" if unknown.
- pub fn variant_name(self) -> Option<&'static str> {
- match self {
- Self::NONE => Some("NONE"),
- Self::M => Some("M"),
- Self::TS => Some("TS"),
- Self::M2 => Some("M2"),
- _ => None,
- }
- }
-}
-impl std::fmt::Debug for AnyUniqueAliases {
- fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
- if let Some(name) = self.variant_name() {
- f.write_str(name)
- } else {
- f.write_fmt(format_args!("<UNKNOWN {:?}>", self.0))
- }
- }
-}
-impl<'a> flatbuffers::Follow<'a> for AnyUniqueAliases {
- type Inner = Self;
- #[inline]
- fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
- Self(flatbuffers::read_scalar_at::<u8>(buf, loc))
- }
-}
-
-impl flatbuffers::Push for AnyUniqueAliases {
- type Output = AnyUniqueAliases;
- #[inline]
- fn push(&self, dst: &mut [u8], _rest: &[u8]) {
- flatbuffers::emplace_scalar::<u8>(dst, self.0);
- }
-}
-
-impl flatbuffers::EndianScalar for AnyUniqueAliases {
- #[inline]
- fn to_little_endian(self) -> Self {
- Self(u8::to_le(self.0))
- }
- #[inline]
- fn from_little_endian(self) -> Self {
- Self(u8::from_le(self.0))
- }
-}
-
-pub struct AnyUniqueAliasesUnionTableOffset {}
-#[deprecated(since = "1.13", note = "Use associated constants instead. This will no longer be generated in 2021.")]
-pub const ENUM_MIN_ANY_AMBIGUOUS_ALIASES: u8 = 0;
-#[deprecated(since = "1.13", note = "Use associated constants instead. This will no longer be generated in 2021.")]
-pub const ENUM_MAX_ANY_AMBIGUOUS_ALIASES: u8 = 3;
-#[deprecated(since = "1.13", note = "Use associated constants instead. This will no longer be generated in 2021.")]
-#[allow(non_camel_case_types)]
-pub const ENUM_VALUES_ANY_AMBIGUOUS_ALIASES: [AnyAmbiguousAliases; 4] = [
- AnyAmbiguousAliases::NONE,
- AnyAmbiguousAliases::M1,
- AnyAmbiguousAliases::M2,
- AnyAmbiguousAliases::M3,
-];
-
-#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
-#[repr(transparent)]
-pub struct AnyAmbiguousAliases(pub u8);
-#[allow(non_upper_case_globals)]
-impl AnyAmbiguousAliases {
- pub const NONE: Self = Self(0);
- pub const M1: Self = Self(1);
- pub const M2: Self = Self(2);
- pub const M3: Self = Self(3);
-
- pub const ENUM_MIN: u8 = 0;
- pub const ENUM_MAX: u8 = 3;
- pub const ENUM_VALUES: &'static [Self] = &[
- Self::NONE,
- Self::M1,
- Self::M2,
- Self::M3,
- ];
- /// Returns the variant's name or "" if unknown.
- pub fn variant_name(self) -> Option<&'static str> {
- match self {
- Self::NONE => Some("NONE"),
- Self::M1 => Some("M1"),
- Self::M2 => Some("M2"),
- Self::M3 => Some("M3"),
- _ => None,
- }
- }
-}
-impl std::fmt::Debug for AnyAmbiguousAliases {
- fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
- if let Some(name) = self.variant_name() {
- f.write_str(name)
- } else {
- f.write_fmt(format_args!("<UNKNOWN {:?}>", self.0))
- }
- }
-}
-impl<'a> flatbuffers::Follow<'a> for AnyAmbiguousAliases {
- type Inner = Self;
- #[inline]
- fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
- Self(flatbuffers::read_scalar_at::<u8>(buf, loc))
- }
-}
-
-impl flatbuffers::Push for AnyAmbiguousAliases {
- type Output = AnyAmbiguousAliases;
- #[inline]
- fn push(&self, dst: &mut [u8], _rest: &[u8]) {
- flatbuffers::emplace_scalar::<u8>(dst, self.0);
- }
-}
-
-impl flatbuffers::EndianScalar for AnyAmbiguousAliases {
- #[inline]
- fn to_little_endian(self) -> Self {
- Self(u8::to_le(self.0))
- }
- #[inline]
- fn from_little_endian(self) -> Self {
- Self(u8::from_le(self.0))
- }
-}
-
-pub struct AnyAmbiguousAliasesUnionTableOffset {}
-// struct Test, aligned to 2
-#[repr(C, align(2))]
-#[derive(Clone, Copy, PartialEq)]
-pub struct Test {
- a_: i16,
- b_: i8,
- padding0__: u8,
-} // pub struct Test
-impl std::fmt::Debug for Test {
- fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
- f.debug_struct("Test")
- .field("a", &self.a())
- .field("b", &self.b())
- .finish()
- }
-}
-
-impl flatbuffers::SafeSliceAccess for Test {}
-impl<'a> flatbuffers::Follow<'a> for Test {
- type Inner = &'a Test;
- #[inline]
- fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
- <&'a Test>::follow(buf, loc)
- }
-}
-impl<'a> flatbuffers::Follow<'a> for &'a Test {
- type Inner = &'a Test;
- #[inline]
- fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
- flatbuffers::follow_cast_ref::<Test>(buf, loc)
- }
-}
-impl<'b> flatbuffers::Push for Test {
- type Output = Test;
- #[inline]
- fn push(&self, dst: &mut [u8], _rest: &[u8]) {
- let src = unsafe {
- ::std::slice::from_raw_parts(self as *const Test as *const u8, Self::size())
- };
- dst.copy_from_slice(src);
- }
-}
-impl<'b> flatbuffers::Push for &'b Test {
- type Output = Test;
-
- #[inline]
- fn push(&self, dst: &mut [u8], _rest: &[u8]) {
- let src = unsafe {
- ::std::slice::from_raw_parts(*self as *const Test as *const u8, Self::size())
- };
- dst.copy_from_slice(src);
- }
-}
-
-
-impl Test {
- pub fn new(_a: i16, _b: i8) -> Self {
- Test {
- a_: _a.to_little_endian(),
- b_: _b.to_little_endian(),
-
- padding0__: 0,
- }
- }
- pub const fn get_fully_qualified_name() -> &'static str {
- "MyGame.Example.Test"
- }
-
- pub fn a(&self) -> i16 {
- self.a_.from_little_endian()
- }
- pub fn b(&self) -> i8 {
- self.b_.from_little_endian()
- }
-}
-
-// struct Vec3, aligned to 8
-#[repr(C, align(8))]
-#[derive(Clone, Copy, PartialEq)]
-pub struct Vec3 {
- x_: f32,
- y_: f32,
- z_: f32,
- padding0__: u32,
- test1_: f64,
- test2_: Color,
- padding1__: u8,
- test3_: Test,
- padding2__: u16,
-} // pub struct Vec3
-impl std::fmt::Debug for Vec3 {
- fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
- f.debug_struct("Vec3")
- .field("x", &self.x())
- .field("y", &self.y())
- .field("z", &self.z())
- .field("test1", &self.test1())
- .field("test2", &self.test2())
- .field("test3", &self.test3())
- .finish()
- }
-}
-
-impl flatbuffers::SafeSliceAccess for Vec3 {}
-impl<'a> flatbuffers::Follow<'a> for Vec3 {
- type Inner = &'a Vec3;
- #[inline]
- fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
- <&'a Vec3>::follow(buf, loc)
- }
-}
-impl<'a> flatbuffers::Follow<'a> for &'a Vec3 {
- type Inner = &'a Vec3;
- #[inline]
- fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
- flatbuffers::follow_cast_ref::<Vec3>(buf, loc)
- }
-}
-impl<'b> flatbuffers::Push for Vec3 {
- type Output = Vec3;
- #[inline]
- fn push(&self, dst: &mut [u8], _rest: &[u8]) {
- let src = unsafe {
- ::std::slice::from_raw_parts(self as *const Vec3 as *const u8, Self::size())
- };
- dst.copy_from_slice(src);
- }
-}
-impl<'b> flatbuffers::Push for &'b Vec3 {
- type Output = Vec3;
-
- #[inline]
- fn push(&self, dst: &mut [u8], _rest: &[u8]) {
- let src = unsafe {
- ::std::slice::from_raw_parts(*self as *const Vec3 as *const u8, Self::size())
- };
- dst.copy_from_slice(src);
- }
-}
-
-
-impl Vec3 {
- pub fn new(_x: f32, _y: f32, _z: f32, _test1: f64, _test2: Color, _test3: &Test) -> Self {
- Vec3 {
- x_: _x.to_little_endian(),
- y_: _y.to_little_endian(),
- z_: _z.to_little_endian(),
- test1_: _test1.to_little_endian(),
- test2_: _test2.to_little_endian(),
- test3_: *_test3,
-
- padding0__: 0,
- padding1__: 0,
- padding2__: 0,
- }
- }
- pub const fn get_fully_qualified_name() -> &'static str {
- "MyGame.Example.Vec3"
- }
-
- pub fn x(&self) -> f32 {
- self.x_.from_little_endian()
- }
- pub fn y(&self) -> f32 {
- self.y_.from_little_endian()
- }
- pub fn z(&self) -> f32 {
- self.z_.from_little_endian()
- }
- pub fn test1(&self) -> f64 {
- self.test1_.from_little_endian()
- }
- pub fn test2(&self) -> Color {
- self.test2_.from_little_endian()
- }
- pub fn test3(&self) -> &Test {
- &self.test3_
- }
-}
-
-// struct Ability, aligned to 4
-#[repr(C, align(4))]
-#[derive(Clone, Copy, PartialEq)]
-pub struct Ability {
- id_: u32,
- distance_: u32,
-} // pub struct Ability
-impl std::fmt::Debug for Ability {
- fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
- f.debug_struct("Ability")
- .field("id", &self.id())
- .field("distance", &self.distance())
- .finish()
- }
-}
-
-impl flatbuffers::SafeSliceAccess for Ability {}
-impl<'a> flatbuffers::Follow<'a> for Ability {
- type Inner = &'a Ability;
- #[inline]
- fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
- <&'a Ability>::follow(buf, loc)
- }
-}
-impl<'a> flatbuffers::Follow<'a> for &'a Ability {
- type Inner = &'a Ability;
- #[inline]
- fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
- flatbuffers::follow_cast_ref::<Ability>(buf, loc)
- }
-}
-impl<'b> flatbuffers::Push for Ability {
- type Output = Ability;
- #[inline]
- fn push(&self, dst: &mut [u8], _rest: &[u8]) {
- let src = unsafe {
- ::std::slice::from_raw_parts(self as *const Ability as *const u8, Self::size())
- };
- dst.copy_from_slice(src);
- }
-}
-impl<'b> flatbuffers::Push for &'b Ability {
- type Output = Ability;
-
- #[inline]
- fn push(&self, dst: &mut [u8], _rest: &[u8]) {
- let src = unsafe {
- ::std::slice::from_raw_parts(*self as *const Ability as *const u8, Self::size())
- };
- dst.copy_from_slice(src);
- }
-}
-
-
-impl Ability {
- pub fn new(_id: u32, _distance: u32) -> Self {
- Ability {
- id_: _id.to_little_endian(),
- distance_: _distance.to_little_endian(),
-
- }
- }
- pub const fn get_fully_qualified_name() -> &'static str {
- "MyGame.Example.Ability"
- }
-
- pub fn id(&self) -> u32 {
- self.id_.from_little_endian()
- }
- #[inline]
- pub fn key_compare_less_than(&self, o: &Ability) -> bool {
- self.id() < o.id()
- }
-
- #[inline]
- pub fn key_compare_with_value(&self, val: u32) -> ::std::cmp::Ordering {
- let key = self.id();
- key.cmp(&val)
- }
- pub fn distance(&self) -> u32 {
- self.distance_.from_little_endian()
- }
-}
-
-pub enum TestSimpleTableWithEnumOffset {}
-#[derive(Copy, Clone, PartialEq)]
-
-pub struct TestSimpleTableWithEnum<'a> {
- pub _tab: flatbuffers::Table<'a>,
-}
-
-impl<'a> flatbuffers::Follow<'a> for TestSimpleTableWithEnum<'a> {
- type Inner = TestSimpleTableWithEnum<'a>;
- #[inline]
- fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
- Self { _tab: flatbuffers::Table { buf, loc } }
- }
-}
-
-impl<'a> TestSimpleTableWithEnum<'a> {
- pub const fn get_fully_qualified_name() -> &'static str {
- "MyGame.Example.TestSimpleTableWithEnum"
- }
-
- #[inline]
- pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
- TestSimpleTableWithEnum {
- _tab: table,
- }
- }
- #[allow(unused_mut)]
- pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
- _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
- args: &'args TestSimpleTableWithEnumArgs) -> flatbuffers::WIPOffset<TestSimpleTableWithEnum<'bldr>> {
- let mut builder = TestSimpleTableWithEnumBuilder::new(_fbb);
- builder.add_color(args.color);
- builder.finish()
- }
-
- pub const VT_COLOR: flatbuffers::VOffsetT = 4;
-
- #[inline]
- pub fn color(&self) -> Color {
- self._tab.get::<Color>(TestSimpleTableWithEnum::VT_COLOR, Some(Color::Green)).unwrap()
- }
-}
-
-pub struct TestSimpleTableWithEnumArgs {
- pub color: Color,
-}
-impl<'a> Default for TestSimpleTableWithEnumArgs {
- #[inline]
- fn default() -> Self {
- TestSimpleTableWithEnumArgs {
- color: Color::Green,
- }
- }
-}
-pub struct TestSimpleTableWithEnumBuilder<'a: 'b, 'b> {
- fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
- start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
-}
-impl<'a: 'b, 'b> TestSimpleTableWithEnumBuilder<'a, 'b> {
- #[inline]
- pub fn add_color(&mut self, color: Color) {
- self.fbb_.push_slot::<Color>(TestSimpleTableWithEnum::VT_COLOR, color, Color::Green);
- }
- #[inline]
- pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> TestSimpleTableWithEnumBuilder<'a, 'b> {
- let start = _fbb.start_table();
- TestSimpleTableWithEnumBuilder {
- fbb_: _fbb,
- start_: start,
- }
- }
- #[inline]
- pub fn finish(self) -> flatbuffers::WIPOffset<TestSimpleTableWithEnum<'a>> {
- let o = self.fbb_.end_table(self.start_);
- flatbuffers::WIPOffset::new(o.value())
- }
-}
-
-impl std::fmt::Debug for TestSimpleTableWithEnum<'_> {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- let mut ds = f.debug_struct("TestSimpleTableWithEnum");
- ds.field("color", &self.color());
- ds.finish()
- }
-}
-pub enum StatOffset {}
-#[derive(Copy, Clone, PartialEq)]
-
-pub struct Stat<'a> {
- pub _tab: flatbuffers::Table<'a>,
-}
-
-impl<'a> flatbuffers::Follow<'a> for Stat<'a> {
- type Inner = Stat<'a>;
- #[inline]
- fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
- Self { _tab: flatbuffers::Table { buf, loc } }
- }
-}
-
-impl<'a> Stat<'a> {
- pub const fn get_fully_qualified_name() -> &'static str {
- "MyGame.Example.Stat"
- }
-
- #[inline]
- pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
- Stat {
- _tab: table,
- }
- }
- #[allow(unused_mut)]
- pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
- _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
- args: &'args StatArgs<'args>) -> flatbuffers::WIPOffset<Stat<'bldr>> {
- let mut builder = StatBuilder::new(_fbb);
- builder.add_val(args.val);
- if let Some(x) = args.id { builder.add_id(x); }
- builder.add_count(args.count);
- builder.finish()
- }
-
- pub const VT_ID: flatbuffers::VOffsetT = 4;
- pub const VT_VAL: flatbuffers::VOffsetT = 6;
- pub const VT_COUNT: flatbuffers::VOffsetT = 8;
-
- #[inline]
- pub fn id(&self) -> Option<&'a str> {
- self._tab.get::<flatbuffers::ForwardsUOffset<&str>>(Stat::VT_ID, None)
- }
- #[inline]
- pub fn val(&self) -> i64 {
- self._tab.get::<i64>(Stat::VT_VAL, Some(0)).unwrap()
- }
- #[inline]
- pub fn count(&self) -> u16 {
- self._tab.get::<u16>(Stat::VT_COUNT, Some(0)).unwrap()
- }
-}
-
-pub struct StatArgs<'a> {
- pub id: Option<flatbuffers::WIPOffset<&'a str>>,
- pub val: i64,
- pub count: u16,
-}
-impl<'a> Default for StatArgs<'a> {
- #[inline]
- fn default() -> Self {
- StatArgs {
- id: None,
- val: 0,
- count: 0,
- }
- }
-}
-pub struct StatBuilder<'a: 'b, 'b> {
- fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
- start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
-}
-impl<'a: 'b, 'b> StatBuilder<'a, 'b> {
- #[inline]
- pub fn add_id(&mut self, id: flatbuffers::WIPOffset<&'b str>) {
- self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Stat::VT_ID, id);
- }
- #[inline]
- pub fn add_val(&mut self, val: i64) {
- self.fbb_.push_slot::<i64>(Stat::VT_VAL, val, 0);
- }
- #[inline]
- pub fn add_count(&mut self, count: u16) {
- self.fbb_.push_slot::<u16>(Stat::VT_COUNT, count, 0);
- }
- #[inline]
- pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> StatBuilder<'a, 'b> {
- let start = _fbb.start_table();
- StatBuilder {
- fbb_: _fbb,
- start_: start,
- }
- }
- #[inline]
- pub fn finish(self) -> flatbuffers::WIPOffset<Stat<'a>> {
- let o = self.fbb_.end_table(self.start_);
- flatbuffers::WIPOffset::new(o.value())
- }
-}
-
-impl std::fmt::Debug for Stat<'_> {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- let mut ds = f.debug_struct("Stat");
- ds.field("id", &self.id());
- ds.field("val", &self.val());
- ds.field("count", &self.count());
- ds.finish()
- }
-}
-pub enum ReferrableOffset {}
-#[derive(Copy, Clone, PartialEq)]
-
-pub struct Referrable<'a> {
- pub _tab: flatbuffers::Table<'a>,
-}
-
-impl<'a> flatbuffers::Follow<'a> for Referrable<'a> {
- type Inner = Referrable<'a>;
- #[inline]
- fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
- Self { _tab: flatbuffers::Table { buf, loc } }
- }
-}
-
-impl<'a> Referrable<'a> {
- pub const fn get_fully_qualified_name() -> &'static str {
- "MyGame.Example.Referrable"
- }
-
- #[inline]
- pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
- Referrable {
- _tab: table,
- }
- }
- #[allow(unused_mut)]
- pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
- _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
- args: &'args ReferrableArgs) -> flatbuffers::WIPOffset<Referrable<'bldr>> {
- let mut builder = ReferrableBuilder::new(_fbb);
- builder.add_id(args.id);
- builder.finish()
- }
-
- pub const VT_ID: flatbuffers::VOffsetT = 4;
-
- #[inline]
- pub fn id(&self) -> u64 {
- self._tab.get::<u64>(Referrable::VT_ID, Some(0)).unwrap()
- }
- #[inline]
- pub fn key_compare_less_than(&self, o: &Referrable) -> bool {
- self.id() < o.id()
- }
-
- #[inline]
- pub fn key_compare_with_value(&self, val: u64) -> ::std::cmp::Ordering {
- let key = self.id();
- key.cmp(&val)
- }
-}
-
-pub struct ReferrableArgs {
- pub id: u64,
-}
-impl<'a> Default for ReferrableArgs {
- #[inline]
- fn default() -> Self {
- ReferrableArgs {
- id: 0,
- }
- }
-}
-pub struct ReferrableBuilder<'a: 'b, 'b> {
- fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
- start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
-}
-impl<'a: 'b, 'b> ReferrableBuilder<'a, 'b> {
- #[inline]
- pub fn add_id(&mut self, id: u64) {
- self.fbb_.push_slot::<u64>(Referrable::VT_ID, id, 0);
- }
- #[inline]
- pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> ReferrableBuilder<'a, 'b> {
- let start = _fbb.start_table();
- ReferrableBuilder {
- fbb_: _fbb,
- start_: start,
- }
- }
- #[inline]
- pub fn finish(self) -> flatbuffers::WIPOffset<Referrable<'a>> {
- let o = self.fbb_.end_table(self.start_);
- flatbuffers::WIPOffset::new(o.value())
- }
-}
-
-impl std::fmt::Debug for Referrable<'_> {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- let mut ds = f.debug_struct("Referrable");
- ds.field("id", &self.id());
- ds.finish()
- }
-}
-pub enum MonsterOffset {}
-#[derive(Copy, Clone, PartialEq)]
-
-/// an example documentation comment: "monster object"
-pub struct Monster<'a> {
- pub _tab: flatbuffers::Table<'a>,
-}
-
-impl<'a> flatbuffers::Follow<'a> for Monster<'a> {
- type Inner = Monster<'a>;
- #[inline]
- fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
- Self { _tab: flatbuffers::Table { buf, loc } }
- }
-}
-
-impl<'a> Monster<'a> {
- pub const fn get_fully_qualified_name() -> &'static str {
- "MyGame.Example.Monster"
- }
-
- #[inline]
- pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
- Monster {
- _tab: table,
- }
- }
- #[allow(unused_mut)]
- pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
- _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
- args: &'args MonsterArgs<'args>) -> flatbuffers::WIPOffset<Monster<'bldr>> {
- let mut builder = MonsterBuilder::new(_fbb);
- builder.add_non_owning_reference(args.non_owning_reference);
- builder.add_co_owning_reference(args.co_owning_reference);
- builder.add_single_weak_reference(args.single_weak_reference);
- builder.add_testhashu64_fnv1a(args.testhashu64_fnv1a);
- builder.add_testhashs64_fnv1a(args.testhashs64_fnv1a);
- builder.add_testhashu64_fnv1(args.testhashu64_fnv1);
- builder.add_testhashs64_fnv1(args.testhashs64_fnv1);
- if let Some(x) = args.testrequirednestedflatbuffer { builder.add_testrequirednestedflatbuffer(x); }
- if let Some(x) = args.vector_of_enums { builder.add_vector_of_enums(x); }
- if let Some(x) = args.any_ambiguous { builder.add_any_ambiguous(x); }
- if let Some(x) = args.any_unique { builder.add_any_unique(x); }
- if let Some(x) = args.vector_of_non_owning_references { builder.add_vector_of_non_owning_references(x); }
- if let Some(x) = args.vector_of_co_owning_references { builder.add_vector_of_co_owning_references(x); }
- if let Some(x) = args.vector_of_strong_referrables { builder.add_vector_of_strong_referrables(x); }
- if let Some(x) = args.vector_of_weak_references { builder.add_vector_of_weak_references(x); }
- if let Some(x) = args.vector_of_referrables { builder.add_vector_of_referrables(x); }
- if let Some(x) = args.parent_namespace_test { builder.add_parent_namespace_test(x); }
- if let Some(x) = args.vector_of_doubles { builder.add_vector_of_doubles(x); }
- if let Some(x) = args.vector_of_longs { builder.add_vector_of_longs(x); }
- if let Some(x) = args.test5 { builder.add_test5(x); }
- if let Some(x) = args.flex { builder.add_flex(x); }
- if let Some(x) = args.testarrayofsortedstruct { builder.add_testarrayofsortedstruct(x); }
- if let Some(x) = args.testarrayofstring2 { builder.add_testarrayofstring2(x); }
- builder.add_testf3(args.testf3);
- builder.add_testf2(args.testf2);
- builder.add_testf(args.testf);
- if let Some(x) = args.testarrayofbools { builder.add_testarrayofbools(x); }
- builder.add_testhashu32_fnv1a(args.testhashu32_fnv1a);
- builder.add_testhashs32_fnv1a(args.testhashs32_fnv1a);
- builder.add_testhashu32_fnv1(args.testhashu32_fnv1);
- builder.add_testhashs32_fnv1(args.testhashs32_fnv1);
- if let Some(x) = args.testempty { builder.add_testempty(x); }
- if let Some(x) = args.testnestedflatbuffer { builder.add_testnestedflatbuffer(x); }
- if let Some(x) = args.enemy { builder.add_enemy(x); }
- if let Some(x) = args.testarrayoftables { builder.add_testarrayoftables(x); }
- if let Some(x) = args.testarrayofstring { builder.add_testarrayofstring(x); }
- if let Some(x) = args.test4 { builder.add_test4(x); }
- if let Some(x) = args.test { builder.add_test(x); }
- if let Some(x) = args.inventory { builder.add_inventory(x); }
- if let Some(x) = args.name { builder.add_name(x); }
- if let Some(x) = args.pos { builder.add_pos(x); }
- builder.add_hp(args.hp);
- builder.add_mana(args.mana);
- builder.add_signed_enum(args.signed_enum);
- builder.add_any_ambiguous_type(args.any_ambiguous_type);
- builder.add_any_unique_type(args.any_unique_type);
- builder.add_testbool(args.testbool);
- builder.add_test_type(args.test_type);
- builder.add_color(args.color);
- builder.finish()
- }
-
- pub const VT_POS: flatbuffers::VOffsetT = 4;
- pub const VT_MANA: flatbuffers::VOffsetT = 6;
- pub const VT_HP: flatbuffers::VOffsetT = 8;
- pub const VT_NAME: flatbuffers::VOffsetT = 10;
- pub const VT_INVENTORY: flatbuffers::VOffsetT = 14;
- pub const VT_COLOR: flatbuffers::VOffsetT = 16;
- pub const VT_TEST_TYPE: flatbuffers::VOffsetT = 18;
- pub const VT_TEST: flatbuffers::VOffsetT = 20;
- pub const VT_TEST4: flatbuffers::VOffsetT = 22;
- pub const VT_TESTARRAYOFSTRING: flatbuffers::VOffsetT = 24;
- pub const VT_TESTARRAYOFTABLES: flatbuffers::VOffsetT = 26;
- pub const VT_ENEMY: flatbuffers::VOffsetT = 28;
- pub const VT_TESTNESTEDFLATBUFFER: flatbuffers::VOffsetT = 30;
- pub const VT_TESTEMPTY: flatbuffers::VOffsetT = 32;
- pub const VT_TESTBOOL: flatbuffers::VOffsetT = 34;
- pub const VT_TESTHASHS32_FNV1: flatbuffers::VOffsetT = 36;
- pub const VT_TESTHASHU32_FNV1: flatbuffers::VOffsetT = 38;
- pub const VT_TESTHASHS64_FNV1: flatbuffers::VOffsetT = 40;
- pub const VT_TESTHASHU64_FNV1: flatbuffers::VOffsetT = 42;
- pub const VT_TESTHASHS32_FNV1A: flatbuffers::VOffsetT = 44;
- pub const VT_TESTHASHU32_FNV1A: flatbuffers::VOffsetT = 46;
- pub const VT_TESTHASHS64_FNV1A: flatbuffers::VOffsetT = 48;
- pub const VT_TESTHASHU64_FNV1A: flatbuffers::VOffsetT = 50;
- pub const VT_TESTARRAYOFBOOLS: flatbuffers::VOffsetT = 52;
- pub const VT_TESTF: flatbuffers::VOffsetT = 54;
- pub const VT_TESTF2: flatbuffers::VOffsetT = 56;
- pub const VT_TESTF3: flatbuffers::VOffsetT = 58;
- pub const VT_TESTARRAYOFSTRING2: flatbuffers::VOffsetT = 60;
- pub const VT_TESTARRAYOFSORTEDSTRUCT: flatbuffers::VOffsetT = 62;
- pub const VT_FLEX: flatbuffers::VOffsetT = 64;
- pub const VT_TEST5: flatbuffers::VOffsetT = 66;
- pub const VT_VECTOR_OF_LONGS: flatbuffers::VOffsetT = 68;
- pub const VT_VECTOR_OF_DOUBLES: flatbuffers::VOffsetT = 70;
- pub const VT_PARENT_NAMESPACE_TEST: flatbuffers::VOffsetT = 72;
- pub const VT_VECTOR_OF_REFERRABLES: flatbuffers::VOffsetT = 74;
- pub const VT_SINGLE_WEAK_REFERENCE: flatbuffers::VOffsetT = 76;
- pub const VT_VECTOR_OF_WEAK_REFERENCES: flatbuffers::VOffsetT = 78;
- pub const VT_VECTOR_OF_STRONG_REFERRABLES: flatbuffers::VOffsetT = 80;
- pub const VT_CO_OWNING_REFERENCE: flatbuffers::VOffsetT = 82;
- pub const VT_VECTOR_OF_CO_OWNING_REFERENCES: flatbuffers::VOffsetT = 84;
- pub const VT_NON_OWNING_REFERENCE: flatbuffers::VOffsetT = 86;
- pub const VT_VECTOR_OF_NON_OWNING_REFERENCES: flatbuffers::VOffsetT = 88;
- pub const VT_ANY_UNIQUE_TYPE: flatbuffers::VOffsetT = 90;
- pub const VT_ANY_UNIQUE: flatbuffers::VOffsetT = 92;
- pub const VT_ANY_AMBIGUOUS_TYPE: flatbuffers::VOffsetT = 94;
- pub const VT_ANY_AMBIGUOUS: flatbuffers::VOffsetT = 96;
- pub const VT_VECTOR_OF_ENUMS: flatbuffers::VOffsetT = 98;
- pub const VT_SIGNED_ENUM: flatbuffers::VOffsetT = 100;
- pub const VT_TESTREQUIREDNESTEDFLATBUFFER: flatbuffers::VOffsetT = 102;
-
- #[inline]
- pub fn pos(&self) -> Option<&'a Vec3> {
- self._tab.get::<Vec3>(Monster::VT_POS, None)
- }
- #[inline]
- pub fn mana(&self) -> i16 {
- self._tab.get::<i16>(Monster::VT_MANA, Some(150)).unwrap()
- }
- #[inline]
- pub fn hp(&self) -> i16 {
- self._tab.get::<i16>(Monster::VT_HP, Some(100)).unwrap()
- }
- #[inline]
- pub fn name(&self) -> &'a str {
- self._tab.get::<flatbuffers::ForwardsUOffset<&str>>(Monster::VT_NAME, None).unwrap()
- }
- #[inline]
- pub fn key_compare_less_than(&self, o: &Monster) -> bool {
- self.name() < o.name()
- }
-
- #[inline]
- pub fn key_compare_with_value(&self, val: & str) -> ::std::cmp::Ordering {
- let key = self.name();
- key.cmp(&val)
- }
- #[inline]
- pub fn inventory(&self) -> Option<&'a [u8]> {
- self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, u8>>>(Monster::VT_INVENTORY, None).map(|v| v.safe_slice())
- }
- #[inline]
- pub fn color(&self) -> Color {
- self._tab.get::<Color>(Monster::VT_COLOR, Some(Color::Blue)).unwrap()
- }
- #[inline]
- pub fn test_type(&self) -> Any {
- self._tab.get::<Any>(Monster::VT_TEST_TYPE, Some(Any::NONE)).unwrap()
- }
- #[inline]
- pub fn test(&self) -> Option<flatbuffers::Table<'a>> {
- self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Table<'a>>>(Monster::VT_TEST, None)
- }
- #[inline]
- pub fn test4(&self) -> Option<&'a [Test]> {
- self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<Test>>>(Monster::VT_TEST4, None).map(|v| v.safe_slice() )
- }
- #[inline]
- pub fn testarrayofstring(&self) -> Option<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<&'a str>>> {
- self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<flatbuffers::ForwardsUOffset<&'a str>>>>(Monster::VT_TESTARRAYOFSTRING, None)
- }
- /// an example documentation comment: this will end up in the generated code
- /// multiline too
- #[inline]
- pub fn testarrayoftables(&self) -> Option<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Monster<'a>>>> {
- self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<flatbuffers::ForwardsUOffset<Monster<'a>>>>>(Monster::VT_TESTARRAYOFTABLES, None)
- }
- #[inline]
- pub fn enemy(&self) -> Option<Monster<'a>> {
- self._tab.get::<flatbuffers::ForwardsUOffset<Monster<'a>>>(Monster::VT_ENEMY, None)
- }
- #[inline]
- pub fn testnestedflatbuffer(&self) -> Option<&'a [u8]> {
- self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, u8>>>(Monster::VT_TESTNESTEDFLATBUFFER, None).map(|v| v.safe_slice())
- }
- pub fn testnestedflatbuffer_nested_flatbuffer(&'a self) -> Option<Monster<'a>> {
- self.testnestedflatbuffer().map(|data| {
- use flatbuffers::Follow;
- <flatbuffers::ForwardsUOffset<Monster<'a>>>::follow(data, 0)
- })
- }
- #[inline]
- pub fn testempty(&self) -> Option<Stat<'a>> {
- self._tab.get::<flatbuffers::ForwardsUOffset<Stat<'a>>>(Monster::VT_TESTEMPTY, None)
- }
- #[inline]
- pub fn testbool(&self) -> bool {
- self._tab.get::<bool>(Monster::VT_TESTBOOL, Some(false)).unwrap()
- }
- #[inline]
- pub fn testhashs32_fnv1(&self) -> i32 {
- self._tab.get::<i32>(Monster::VT_TESTHASHS32_FNV1, Some(0)).unwrap()
- }
- #[inline]
- pub fn testhashu32_fnv1(&self) -> u32 {
- self._tab.get::<u32>(Monster::VT_TESTHASHU32_FNV1, Some(0)).unwrap()
- }
- #[inline]
- pub fn testhashs64_fnv1(&self) -> i64 {
- self._tab.get::<i64>(Monster::VT_TESTHASHS64_FNV1, Some(0)).unwrap()
- }
- #[inline]
- pub fn testhashu64_fnv1(&self) -> u64 {
- self._tab.get::<u64>(Monster::VT_TESTHASHU64_FNV1, Some(0)).unwrap()
- }
- #[inline]
- pub fn testhashs32_fnv1a(&self) -> i32 {
- self._tab.get::<i32>(Monster::VT_TESTHASHS32_FNV1A, Some(0)).unwrap()
- }
- #[inline]
- pub fn testhashu32_fnv1a(&self) -> u32 {
- self._tab.get::<u32>(Monster::VT_TESTHASHU32_FNV1A, Some(0)).unwrap()
- }
- #[inline]
- pub fn testhashs64_fnv1a(&self) -> i64 {
- self._tab.get::<i64>(Monster::VT_TESTHASHS64_FNV1A, Some(0)).unwrap()
- }
- #[inline]
- pub fn testhashu64_fnv1a(&self) -> u64 {
- self._tab.get::<u64>(Monster::VT_TESTHASHU64_FNV1A, Some(0)).unwrap()
- }
- #[inline]
- pub fn testarrayofbools(&self) -> Option<&'a [bool]> {
- self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, bool>>>(Monster::VT_TESTARRAYOFBOOLS, None).map(|v| v.safe_slice())
- }
- #[inline]
- pub fn testf(&self) -> f32 {
- self._tab.get::<f32>(Monster::VT_TESTF, Some(3.14159)).unwrap()
- }
- #[inline]
- pub fn testf2(&self) -> f32 {
- self._tab.get::<f32>(Monster::VT_TESTF2, Some(3.0)).unwrap()
- }
- #[inline]
- pub fn testf3(&self) -> f32 {
- self._tab.get::<f32>(Monster::VT_TESTF3, Some(0.0)).unwrap()
- }
- #[inline]
- pub fn testarrayofstring2(&self) -> Option<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<&'a str>>> {
- self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<flatbuffers::ForwardsUOffset<&'a str>>>>(Monster::VT_TESTARRAYOFSTRING2, None)
- }
- #[inline]
- pub fn testarrayofsortedstruct(&self) -> Option<&'a [Ability]> {
- self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<Ability>>>(Monster::VT_TESTARRAYOFSORTEDSTRUCT, None).map(|v| v.safe_slice() )
- }
- #[inline]
- pub fn flex(&self) -> Option<&'a [u8]> {
- self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, u8>>>(Monster::VT_FLEX, None).map(|v| v.safe_slice())
- }
- #[inline]
- pub fn test5(&self) -> Option<&'a [Test]> {
- self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<Test>>>(Monster::VT_TEST5, None).map(|v| v.safe_slice() )
- }
- #[inline]
- pub fn vector_of_longs(&self) -> Option<flatbuffers::Vector<'a, i64>> {
- self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, i64>>>(Monster::VT_VECTOR_OF_LONGS, None)
- }
- #[inline]
- pub fn vector_of_doubles(&self) -> Option<flatbuffers::Vector<'a, f64>> {
- self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, f64>>>(Monster::VT_VECTOR_OF_DOUBLES, None)
- }
- #[inline]
- pub fn parent_namespace_test(&self) -> Option<super::InParentNamespace<'a>> {
- self._tab.get::<flatbuffers::ForwardsUOffset<super::InParentNamespace<'a>>>(Monster::VT_PARENT_NAMESPACE_TEST, None)
- }
- #[inline]
- pub fn vector_of_referrables(&self) -> Option<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Referrable<'a>>>> {
- self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<flatbuffers::ForwardsUOffset<Referrable<'a>>>>>(Monster::VT_VECTOR_OF_REFERRABLES, None)
- }
- #[inline]
- pub fn single_weak_reference(&self) -> u64 {
- self._tab.get::<u64>(Monster::VT_SINGLE_WEAK_REFERENCE, Some(0)).unwrap()
- }
- #[inline]
- pub fn vector_of_weak_references(&self) -> Option<flatbuffers::Vector<'a, u64>> {
- self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, u64>>>(Monster::VT_VECTOR_OF_WEAK_REFERENCES, None)
- }
- #[inline]
- pub fn vector_of_strong_referrables(&self) -> Option<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Referrable<'a>>>> {
- self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<flatbuffers::ForwardsUOffset<Referrable<'a>>>>>(Monster::VT_VECTOR_OF_STRONG_REFERRABLES, None)
- }
- #[inline]
- pub fn co_owning_reference(&self) -> u64 {
- self._tab.get::<u64>(Monster::VT_CO_OWNING_REFERENCE, Some(0)).unwrap()
- }
- #[inline]
- pub fn vector_of_co_owning_references(&self) -> Option<flatbuffers::Vector<'a, u64>> {
- self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, u64>>>(Monster::VT_VECTOR_OF_CO_OWNING_REFERENCES, None)
- }
- #[inline]
- pub fn non_owning_reference(&self) -> u64 {
- self._tab.get::<u64>(Monster::VT_NON_OWNING_REFERENCE, Some(0)).unwrap()
- }
- #[inline]
- pub fn vector_of_non_owning_references(&self) -> Option<flatbuffers::Vector<'a, u64>> {
- self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, u64>>>(Monster::VT_VECTOR_OF_NON_OWNING_REFERENCES, None)
- }
- #[inline]
- pub fn any_unique_type(&self) -> AnyUniqueAliases {
- self._tab.get::<AnyUniqueAliases>(Monster::VT_ANY_UNIQUE_TYPE, Some(AnyUniqueAliases::NONE)).unwrap()
- }
- #[inline]
- pub fn any_unique(&self) -> Option<flatbuffers::Table<'a>> {
- self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Table<'a>>>(Monster::VT_ANY_UNIQUE, None)
- }
- #[inline]
- pub fn any_ambiguous_type(&self) -> AnyAmbiguousAliases {
- self._tab.get::<AnyAmbiguousAliases>(Monster::VT_ANY_AMBIGUOUS_TYPE, Some(AnyAmbiguousAliases::NONE)).unwrap()
- }
- #[inline]
- pub fn any_ambiguous(&self) -> Option<flatbuffers::Table<'a>> {
- self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Table<'a>>>(Monster::VT_ANY_AMBIGUOUS, None)
- }
- #[inline]
- pub fn vector_of_enums(&self) -> Option<flatbuffers::Vector<'a, Color>> {
- self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, Color>>>(Monster::VT_VECTOR_OF_ENUMS, None)
- }
- #[inline]
- pub fn signed_enum(&self) -> Race {
- self._tab.get::<Race>(Monster::VT_SIGNED_ENUM, Some(Race::None)).unwrap()
- }
- #[inline]
- pub fn testrequirednestedflatbuffer(&self) -> Option<&'a [u8]> {
- self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, u8>>>(Monster::VT_TESTREQUIREDNESTEDFLATBUFFER, None).map(|v| v.safe_slice())
- }
- pub fn testrequirednestedflatbuffer_nested_flatbuffer(&'a self) -> Option<Monster<'a>> {
- self.testrequirednestedflatbuffer().map(|data| {
- use flatbuffers::Follow;
- <flatbuffers::ForwardsUOffset<Monster<'a>>>::follow(data, 0)
- })
- }
- #[inline]
- #[allow(non_snake_case)]
- pub fn test_as_monster(&self) -> Option<Monster<'a>> {
- if self.test_type() == Any::Monster {
- self.test().map(Monster::init_from_table)
- } else {
- None
- }
- }
-
- #[inline]
- #[allow(non_snake_case)]
- pub fn test_as_test_simple_table_with_enum(&self) -> Option<TestSimpleTableWithEnum<'a>> {
- if self.test_type() == Any::TestSimpleTableWithEnum {
- self.test().map(TestSimpleTableWithEnum::init_from_table)
- } else {
- None
- }
- }
-
- #[inline]
- #[allow(non_snake_case)]
- pub fn test_as_my_game_example_2_monster(&self) -> Option<super::example_2::Monster<'a>> {
- if self.test_type() == Any::MyGame_Example2_Monster {
- self.test().map(super::example_2::Monster::init_from_table)
- } else {
- None
- }
- }
-
- #[inline]
- #[allow(non_snake_case)]
- pub fn any_unique_as_m(&self) -> Option<Monster<'a>> {
- if self.any_unique_type() == AnyUniqueAliases::M {
- self.any_unique().map(Monster::init_from_table)
- } else {
- None
- }
- }
-
- #[inline]
- #[allow(non_snake_case)]
- pub fn any_unique_as_ts(&self) -> Option<TestSimpleTableWithEnum<'a>> {
- if self.any_unique_type() == AnyUniqueAliases::TS {
- self.any_unique().map(TestSimpleTableWithEnum::init_from_table)
- } else {
- None
- }
- }
-
- #[inline]
- #[allow(non_snake_case)]
- pub fn any_unique_as_m2(&self) -> Option<super::example_2::Monster<'a>> {
- if self.any_unique_type() == AnyUniqueAliases::M2 {
- self.any_unique().map(super::example_2::Monster::init_from_table)
- } else {
- None
- }
- }
-
- #[inline]
- #[allow(non_snake_case)]
- pub fn any_ambiguous_as_m1(&self) -> Option<Monster<'a>> {
- if self.any_ambiguous_type() == AnyAmbiguousAliases::M1 {
- self.any_ambiguous().map(Monster::init_from_table)
- } else {
- None
- }
- }
-
- #[inline]
- #[allow(non_snake_case)]
- pub fn any_ambiguous_as_m2(&self) -> Option<Monster<'a>> {
- if self.any_ambiguous_type() == AnyAmbiguousAliases::M2 {
- self.any_ambiguous().map(Monster::init_from_table)
- } else {
- None
- }
- }
-
- #[inline]
- #[allow(non_snake_case)]
- pub fn any_ambiguous_as_m3(&self) -> Option<Monster<'a>> {
- if self.any_ambiguous_type() == AnyAmbiguousAliases::M3 {
- self.any_ambiguous().map(Monster::init_from_table)
- } else {
- None
- }
- }
-
-}
-
-pub struct MonsterArgs<'a> {
- pub pos: Option<&'a Vec3>,
- pub mana: i16,
- pub hp: i16,
- pub name: Option<flatbuffers::WIPOffset<&'a str>>,
- pub inventory: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, u8>>>,
- pub color: Color,
- pub test_type: Any,
- pub test: Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>,
- pub test4: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, Test>>>,
- pub testarrayofstring: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<&'a str>>>>,
- pub testarrayoftables: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Monster<'a>>>>>,
- pub enemy: Option<flatbuffers::WIPOffset<Monster<'a>>>,
- pub testnestedflatbuffer: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, u8>>>,
- pub testempty: Option<flatbuffers::WIPOffset<Stat<'a>>>,
- pub testbool: bool,
- pub testhashs32_fnv1: i32,
- pub testhashu32_fnv1: u32,
- pub testhashs64_fnv1: i64,
- pub testhashu64_fnv1: u64,
- pub testhashs32_fnv1a: i32,
- pub testhashu32_fnv1a: u32,
- pub testhashs64_fnv1a: i64,
- pub testhashu64_fnv1a: u64,
- pub testarrayofbools: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, bool>>>,
- pub testf: f32,
- pub testf2: f32,
- pub testf3: f32,
- pub testarrayofstring2: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<&'a str>>>>,
- pub testarrayofsortedstruct: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, Ability>>>,
- pub flex: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, u8>>>,
- pub test5: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, Test>>>,
- pub vector_of_longs: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, i64>>>,
- pub vector_of_doubles: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, f64>>>,
- pub parent_namespace_test: Option<flatbuffers::WIPOffset<super::InParentNamespace<'a>>>,
- pub vector_of_referrables: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Referrable<'a>>>>>,
- pub single_weak_reference: u64,
- pub vector_of_weak_references: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, u64>>>,
- pub vector_of_strong_referrables: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Referrable<'a>>>>>,
- pub co_owning_reference: u64,
- pub vector_of_co_owning_references: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, u64>>>,
- pub non_owning_reference: u64,
- pub vector_of_non_owning_references: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, u64>>>,
- pub any_unique_type: AnyUniqueAliases,
- pub any_unique: Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>,
- pub any_ambiguous_type: AnyAmbiguousAliases,
- pub any_ambiguous: Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>,
- pub vector_of_enums: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, Color>>>,
- pub signed_enum: Race,
- pub testrequirednestedflatbuffer: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, u8>>>,
-}
-impl<'a> Default for MonsterArgs<'a> {
- #[inline]
- fn default() -> Self {
- MonsterArgs {
- pos: None,
- mana: 150,
- hp: 100,
- name: None, // required field
- inventory: None,
- color: Color::Blue,
- test_type: Any::NONE,
- test: None,
- test4: None,
- testarrayofstring: None,
- testarrayoftables: None,
- enemy: None,
- testnestedflatbuffer: None,
- testempty: None,
- testbool: false,
- testhashs32_fnv1: 0,
- testhashu32_fnv1: 0,
- testhashs64_fnv1: 0,
- testhashu64_fnv1: 0,
- testhashs32_fnv1a: 0,
- testhashu32_fnv1a: 0,
- testhashs64_fnv1a: 0,
- testhashu64_fnv1a: 0,
- testarrayofbools: None,
- testf: 3.14159,
- testf2: 3.0,
- testf3: 0.0,
- testarrayofstring2: None,
- testarrayofsortedstruct: None,
- flex: None,
- test5: None,
- vector_of_longs: None,
- vector_of_doubles: None,
- parent_namespace_test: None,
- vector_of_referrables: None,
- single_weak_reference: 0,
- vector_of_weak_references: None,
- vector_of_strong_referrables: None,
- co_owning_reference: 0,
- vector_of_co_owning_references: None,
- non_owning_reference: 0,
- vector_of_non_owning_references: None,
- any_unique_type: AnyUniqueAliases::NONE,
- any_unique: None,
- any_ambiguous_type: AnyAmbiguousAliases::NONE,
- any_ambiguous: None,
- vector_of_enums: None,
- signed_enum: Race::None,
- testrequirednestedflatbuffer: None,
- }
- }
-}
-pub struct MonsterBuilder<'a: 'b, 'b> {
- fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
- start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
-}
-impl<'a: 'b, 'b> MonsterBuilder<'a, 'b> {
- #[inline]
- pub fn add_pos(&mut self, pos: &Vec3) {
- self.fbb_.push_slot_always::<&Vec3>(Monster::VT_POS, pos);
- }
- #[inline]
- pub fn add_mana(&mut self, mana: i16) {
- self.fbb_.push_slot::<i16>(Monster::VT_MANA, mana, 150);
- }
- #[inline]
- pub fn add_hp(&mut self, hp: i16) {
- self.fbb_.push_slot::<i16>(Monster::VT_HP, hp, 100);
- }
- #[inline]
- pub fn add_name(&mut self, name: flatbuffers::WIPOffset<&'b str>) {
- self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_NAME, name);
- }
- #[inline]
- pub fn add_inventory(&mut self, inventory: flatbuffers::WIPOffset<flatbuffers::Vector<'b , u8>>) {
- self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_INVENTORY, inventory);
- }
- #[inline]
- pub fn add_color(&mut self, color: Color) {
- self.fbb_.push_slot::<Color>(Monster::VT_COLOR, color, Color::Blue);
- }
- #[inline]
- pub fn add_test_type(&mut self, test_type: Any) {
- self.fbb_.push_slot::<Any>(Monster::VT_TEST_TYPE, test_type, Any::NONE);
- }
- #[inline]
- pub fn add_test(&mut self, test: flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>) {
- self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_TEST, test);
- }
- #[inline]
- pub fn add_test4(&mut self, test4: flatbuffers::WIPOffset<flatbuffers::Vector<'b , Test>>) {
- self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_TEST4, test4);
- }
- #[inline]
- pub fn add_testarrayofstring(&mut self, testarrayofstring: flatbuffers::WIPOffset<flatbuffers::Vector<'b , flatbuffers::ForwardsUOffset<&'b str>>>) {
- self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_TESTARRAYOFSTRING, testarrayofstring);
- }
- #[inline]
- pub fn add_testarrayoftables(&mut self, testarrayoftables: flatbuffers::WIPOffset<flatbuffers::Vector<'b , flatbuffers::ForwardsUOffset<Monster<'b >>>>) {
- self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_TESTARRAYOFTABLES, testarrayoftables);
- }
- #[inline]
- pub fn add_enemy(&mut self, enemy: flatbuffers::WIPOffset<Monster<'b >>) {
- self.fbb_.push_slot_always::<flatbuffers::WIPOffset<Monster>>(Monster::VT_ENEMY, enemy);
- }
- #[inline]
- pub fn add_testnestedflatbuffer(&mut self, testnestedflatbuffer: flatbuffers::WIPOffset<flatbuffers::Vector<'b , u8>>) {
- self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_TESTNESTEDFLATBUFFER, testnestedflatbuffer);
- }
- #[inline]
- pub fn add_testempty(&mut self, testempty: flatbuffers::WIPOffset<Stat<'b >>) {
- self.fbb_.push_slot_always::<flatbuffers::WIPOffset<Stat>>(Monster::VT_TESTEMPTY, testempty);
- }
- #[inline]
- pub fn add_testbool(&mut self, testbool: bool) {
- self.fbb_.push_slot::<bool>(Monster::VT_TESTBOOL, testbool, false);
- }
- #[inline]
- pub fn add_testhashs32_fnv1(&mut self, testhashs32_fnv1: i32) {
- self.fbb_.push_slot::<i32>(Monster::VT_TESTHASHS32_FNV1, testhashs32_fnv1, 0);
- }
- #[inline]
- pub fn add_testhashu32_fnv1(&mut self, testhashu32_fnv1: u32) {
- self.fbb_.push_slot::<u32>(Monster::VT_TESTHASHU32_FNV1, testhashu32_fnv1, 0);
- }
- #[inline]
- pub fn add_testhashs64_fnv1(&mut self, testhashs64_fnv1: i64) {
- self.fbb_.push_slot::<i64>(Monster::VT_TESTHASHS64_FNV1, testhashs64_fnv1, 0);
- }
- #[inline]
- pub fn add_testhashu64_fnv1(&mut self, testhashu64_fnv1: u64) {
- self.fbb_.push_slot::<u64>(Monster::VT_TESTHASHU64_FNV1, testhashu64_fnv1, 0);
- }
- #[inline]
- pub fn add_testhashs32_fnv1a(&mut self, testhashs32_fnv1a: i32) {
- self.fbb_.push_slot::<i32>(Monster::VT_TESTHASHS32_FNV1A, testhashs32_fnv1a, 0);
- }
- #[inline]
- pub fn add_testhashu32_fnv1a(&mut self, testhashu32_fnv1a: u32) {
- self.fbb_.push_slot::<u32>(Monster::VT_TESTHASHU32_FNV1A, testhashu32_fnv1a, 0);
- }
- #[inline]
- pub fn add_testhashs64_fnv1a(&mut self, testhashs64_fnv1a: i64) {
- self.fbb_.push_slot::<i64>(Monster::VT_TESTHASHS64_FNV1A, testhashs64_fnv1a, 0);
- }
- #[inline]
- pub fn add_testhashu64_fnv1a(&mut self, testhashu64_fnv1a: u64) {
- self.fbb_.push_slot::<u64>(Monster::VT_TESTHASHU64_FNV1A, testhashu64_fnv1a, 0);
- }
- #[inline]
- pub fn add_testarrayofbools(&mut self, testarrayofbools: flatbuffers::WIPOffset<flatbuffers::Vector<'b , bool>>) {
- self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_TESTARRAYOFBOOLS, testarrayofbools);
- }
- #[inline]
- pub fn add_testf(&mut self, testf: f32) {
- self.fbb_.push_slot::<f32>(Monster::VT_TESTF, testf, 3.14159);
- }
- #[inline]
- pub fn add_testf2(&mut self, testf2: f32) {
- self.fbb_.push_slot::<f32>(Monster::VT_TESTF2, testf2, 3.0);
- }
- #[inline]
- pub fn add_testf3(&mut self, testf3: f32) {
- self.fbb_.push_slot::<f32>(Monster::VT_TESTF3, testf3, 0.0);
- }
- #[inline]
- pub fn add_testarrayofstring2(&mut self, testarrayofstring2: flatbuffers::WIPOffset<flatbuffers::Vector<'b , flatbuffers::ForwardsUOffset<&'b str>>>) {
- self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_TESTARRAYOFSTRING2, testarrayofstring2);
- }
- #[inline]
- pub fn add_testarrayofsortedstruct(&mut self, testarrayofsortedstruct: flatbuffers::WIPOffset<flatbuffers::Vector<'b , Ability>>) {
- self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_TESTARRAYOFSORTEDSTRUCT, testarrayofsortedstruct);
- }
- #[inline]
- pub fn add_flex(&mut self, flex: flatbuffers::WIPOffset<flatbuffers::Vector<'b , u8>>) {
- self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_FLEX, flex);
- }
- #[inline]
- pub fn add_test5(&mut self, test5: flatbuffers::WIPOffset<flatbuffers::Vector<'b , Test>>) {
- self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_TEST5, test5);
- }
- #[inline]
- pub fn add_vector_of_longs(&mut self, vector_of_longs: flatbuffers::WIPOffset<flatbuffers::Vector<'b , i64>>) {
- self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_LONGS, vector_of_longs);
- }
- #[inline]
- pub fn add_vector_of_doubles(&mut self, vector_of_doubles: flatbuffers::WIPOffset<flatbuffers::Vector<'b , f64>>) {
- self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_DOUBLES, vector_of_doubles);
- }
- #[inline]
- pub fn add_parent_namespace_test(&mut self, parent_namespace_test: flatbuffers::WIPOffset<super::InParentNamespace<'b >>) {
- self.fbb_.push_slot_always::<flatbuffers::WIPOffset<super::InParentNamespace>>(Monster::VT_PARENT_NAMESPACE_TEST, parent_namespace_test);
- }
- #[inline]
- pub fn add_vector_of_referrables(&mut self, vector_of_referrables: flatbuffers::WIPOffset<flatbuffers::Vector<'b , flatbuffers::ForwardsUOffset<Referrable<'b >>>>) {
- self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_REFERRABLES, vector_of_referrables);
- }
- #[inline]
- pub fn add_single_weak_reference(&mut self, single_weak_reference: u64) {
- self.fbb_.push_slot::<u64>(Monster::VT_SINGLE_WEAK_REFERENCE, single_weak_reference, 0);
- }
- #[inline]
- pub fn add_vector_of_weak_references(&mut self, vector_of_weak_references: flatbuffers::WIPOffset<flatbuffers::Vector<'b , u64>>) {
- self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_WEAK_REFERENCES, vector_of_weak_references);
- }
- #[inline]
- pub fn add_vector_of_strong_referrables(&mut self, vector_of_strong_referrables: flatbuffers::WIPOffset<flatbuffers::Vector<'b , flatbuffers::ForwardsUOffset<Referrable<'b >>>>) {
- self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_STRONG_REFERRABLES, vector_of_strong_referrables);
- }
- #[inline]
- pub fn add_co_owning_reference(&mut self, co_owning_reference: u64) {
- self.fbb_.push_slot::<u64>(Monster::VT_CO_OWNING_REFERENCE, co_owning_reference, 0);
- }
- #[inline]
- pub fn add_vector_of_co_owning_references(&mut self, vector_of_co_owning_references: flatbuffers::WIPOffset<flatbuffers::Vector<'b , u64>>) {
- self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_CO_OWNING_REFERENCES, vector_of_co_owning_references);
- }
- #[inline]
- pub fn add_non_owning_reference(&mut self, non_owning_reference: u64) {
- self.fbb_.push_slot::<u64>(Monster::VT_NON_OWNING_REFERENCE, non_owning_reference, 0);
- }
- #[inline]
- pub fn add_vector_of_non_owning_references(&mut self, vector_of_non_owning_references: flatbuffers::WIPOffset<flatbuffers::Vector<'b , u64>>) {
- self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_NON_OWNING_REFERENCES, vector_of_non_owning_references);
- }
- #[inline]
- pub fn add_any_unique_type(&mut self, any_unique_type: AnyUniqueAliases) {
- self.fbb_.push_slot::<AnyUniqueAliases>(Monster::VT_ANY_UNIQUE_TYPE, any_unique_type, AnyUniqueAliases::NONE);
- }
- #[inline]
- pub fn add_any_unique(&mut self, any_unique: flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>) {
- self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_ANY_UNIQUE, any_unique);
- }
- #[inline]
- pub fn add_any_ambiguous_type(&mut self, any_ambiguous_type: AnyAmbiguousAliases) {
- self.fbb_.push_slot::<AnyAmbiguousAliases>(Monster::VT_ANY_AMBIGUOUS_TYPE, any_ambiguous_type, AnyAmbiguousAliases::NONE);
- }
- #[inline]
- pub fn add_any_ambiguous(&mut self, any_ambiguous: flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>) {
- self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_ANY_AMBIGUOUS, any_ambiguous);
- }
- #[inline]
- pub fn add_vector_of_enums(&mut self, vector_of_enums: flatbuffers::WIPOffset<flatbuffers::Vector<'b , Color>>) {
- self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_ENUMS, vector_of_enums);
- }
- #[inline]
- pub fn add_signed_enum(&mut self, signed_enum: Race) {
- self.fbb_.push_slot::<Race>(Monster::VT_SIGNED_ENUM, signed_enum, Race::None);
- }
- #[inline]
- pub fn add_testrequirednestedflatbuffer(&mut self, testrequirednestedflatbuffer: flatbuffers::WIPOffset<flatbuffers::Vector<'b , u8>>) {
- self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_TESTREQUIREDNESTEDFLATBUFFER, testrequirednestedflatbuffer);
- }
- #[inline]
- pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> MonsterBuilder<'a, 'b> {
- let start = _fbb.start_table();
- MonsterBuilder {
- fbb_: _fbb,
- start_: start,
- }
- }
- #[inline]
- pub fn finish(self) -> flatbuffers::WIPOffset<Monster<'a>> {
- let o = self.fbb_.end_table(self.start_);
- self.fbb_.required(o, Monster::VT_NAME,"name");
- flatbuffers::WIPOffset::new(o.value())
- }
-}
-
-impl std::fmt::Debug for Monster<'_> {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- let mut ds = f.debug_struct("Monster");
- ds.field("pos", &self.pos());
- ds.field("mana", &self.mana());
- ds.field("hp", &self.hp());
- ds.field("name", &self.name());
- ds.field("inventory", &self.inventory());
- ds.field("color", &self.color());
- ds.field("test_type", &self.test_type());
- match self.test_type() {
- Any::Monster => {
- if let Some(x) = self.test_as_monster() {
- ds.field("test", &x)
- } else {
- ds.field("test", &"InvalidFlatbuffer: Union discriminant does not match value.")
- }
- },
- Any::TestSimpleTableWithEnum => {
- if let Some(x) = self.test_as_test_simple_table_with_enum() {
- ds.field("test", &x)
- } else {
- ds.field("test", &"InvalidFlatbuffer: Union discriminant does not match value.")
- }
- },
- Any::MyGame_Example2_Monster => {
- if let Some(x) = self.test_as_my_game_example_2_monster() {
- ds.field("test", &x)
- } else {
- ds.field("test", &"InvalidFlatbuffer: Union discriminant does not match value.")
- }
- },
- _ => {
- let x: Option<()> = None;
- ds.field("test", &x)
- },
- };
- ds.field("test4", &self.test4());
- ds.field("testarrayofstring", &self.testarrayofstring());
- ds.field("testarrayoftables", &self.testarrayoftables());
- ds.field("enemy", &self.enemy());
- ds.field("testnestedflatbuffer", &self.testnestedflatbuffer());
- ds.field("testempty", &self.testempty());
- ds.field("testbool", &self.testbool());
- ds.field("testhashs32_fnv1", &self.testhashs32_fnv1());
- ds.field("testhashu32_fnv1", &self.testhashu32_fnv1());
- ds.field("testhashs64_fnv1", &self.testhashs64_fnv1());
- ds.field("testhashu64_fnv1", &self.testhashu64_fnv1());
- ds.field("testhashs32_fnv1a", &self.testhashs32_fnv1a());
- ds.field("testhashu32_fnv1a", &self.testhashu32_fnv1a());
- ds.field("testhashs64_fnv1a", &self.testhashs64_fnv1a());
- ds.field("testhashu64_fnv1a", &self.testhashu64_fnv1a());
- ds.field("testarrayofbools", &self.testarrayofbools());
- ds.field("testf", &self.testf());
- ds.field("testf2", &self.testf2());
- ds.field("testf3", &self.testf3());
- ds.field("testarrayofstring2", &self.testarrayofstring2());
- ds.field("testarrayofsortedstruct", &self.testarrayofsortedstruct());
- ds.field("flex", &self.flex());
- ds.field("test5", &self.test5());
- ds.field("vector_of_longs", &self.vector_of_longs());
- ds.field("vector_of_doubles", &self.vector_of_doubles());
- ds.field("parent_namespace_test", &self.parent_namespace_test());
- ds.field("vector_of_referrables", &self.vector_of_referrables());
- ds.field("single_weak_reference", &self.single_weak_reference());
- ds.field("vector_of_weak_references", &self.vector_of_weak_references());
- ds.field("vector_of_strong_referrables", &self.vector_of_strong_referrables());
- ds.field("co_owning_reference", &self.co_owning_reference());
- ds.field("vector_of_co_owning_references", &self.vector_of_co_owning_references());
- ds.field("non_owning_reference", &self.non_owning_reference());
- ds.field("vector_of_non_owning_references", &self.vector_of_non_owning_references());
- ds.field("any_unique_type", &self.any_unique_type());
- match self.any_unique_type() {
- AnyUniqueAliases::M => {
- if let Some(x) = self.any_unique_as_m() {
- ds.field("any_unique", &x)
- } else {
- ds.field("any_unique", &"InvalidFlatbuffer: Union discriminant does not match value.")
- }
- },
- AnyUniqueAliases::TS => {
- if let Some(x) = self.any_unique_as_ts() {
- ds.field("any_unique", &x)
- } else {
- ds.field("any_unique", &"InvalidFlatbuffer: Union discriminant does not match value.")
- }
- },
- AnyUniqueAliases::M2 => {
- if let Some(x) = self.any_unique_as_m2() {
- ds.field("any_unique", &x)
- } else {
- ds.field("any_unique", &"InvalidFlatbuffer: Union discriminant does not match value.")
- }
- },
- _ => {
- let x: Option<()> = None;
- ds.field("any_unique", &x)
- },
- };
- ds.field("any_ambiguous_type", &self.any_ambiguous_type());
- match self.any_ambiguous_type() {
- AnyAmbiguousAliases::M1 => {
- if let Some(x) = self.any_ambiguous_as_m1() {
- ds.field("any_ambiguous", &x)
- } else {
- ds.field("any_ambiguous", &"InvalidFlatbuffer: Union discriminant does not match value.")
- }
- },
- AnyAmbiguousAliases::M2 => {
- if let Some(x) = self.any_ambiguous_as_m2() {
- ds.field("any_ambiguous", &x)
- } else {
- ds.field("any_ambiguous", &"InvalidFlatbuffer: Union discriminant does not match value.")
- }
- },
- AnyAmbiguousAliases::M3 => {
- if let Some(x) = self.any_ambiguous_as_m3() {
- ds.field("any_ambiguous", &x)
- } else {
- ds.field("any_ambiguous", &"InvalidFlatbuffer: Union discriminant does not match value.")
- }
- },
- _ => {
- let x: Option<()> = None;
- ds.field("any_ambiguous", &x)
- },
- };
- ds.field("vector_of_enums", &self.vector_of_enums());
- ds.field("signed_enum", &self.signed_enum());
- ds.field("testrequirednestedflatbuffer", &self.testrequirednestedflatbuffer());
- ds.finish()
- }
-}
-pub enum TypeAliasesOffset {}
-#[derive(Copy, Clone, PartialEq)]
-
-pub struct TypeAliases<'a> {
- pub _tab: flatbuffers::Table<'a>,
-}
-
-impl<'a> flatbuffers::Follow<'a> for TypeAliases<'a> {
- type Inner = TypeAliases<'a>;
- #[inline]
- fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
- Self { _tab: flatbuffers::Table { buf, loc } }
- }
-}
-
-impl<'a> TypeAliases<'a> {
- pub const fn get_fully_qualified_name() -> &'static str {
- "MyGame.Example.TypeAliases"
- }
-
- #[inline]
- pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
- TypeAliases {
- _tab: table,
- }
- }
- #[allow(unused_mut)]
- pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
- _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
- args: &'args TypeAliasesArgs<'args>) -> flatbuffers::WIPOffset<TypeAliases<'bldr>> {
- let mut builder = TypeAliasesBuilder::new(_fbb);
- builder.add_f64_(args.f64_);
- builder.add_u64_(args.u64_);
- builder.add_i64_(args.i64_);
- if let Some(x) = args.vf64 { builder.add_vf64(x); }
- if let Some(x) = args.v8 { builder.add_v8(x); }
- builder.add_f32_(args.f32_);
- builder.add_u32_(args.u32_);
- builder.add_i32_(args.i32_);
- builder.add_u16_(args.u16_);
- builder.add_i16_(args.i16_);
- builder.add_u8_(args.u8_);
- builder.add_i8_(args.i8_);
- builder.finish()
- }
-
- pub const VT_I8_: flatbuffers::VOffsetT = 4;
- pub const VT_U8_: flatbuffers::VOffsetT = 6;
- pub const VT_I16_: flatbuffers::VOffsetT = 8;
- pub const VT_U16_: flatbuffers::VOffsetT = 10;
- pub const VT_I32_: flatbuffers::VOffsetT = 12;
- pub const VT_U32_: flatbuffers::VOffsetT = 14;
- pub const VT_I64_: flatbuffers::VOffsetT = 16;
- pub const VT_U64_: flatbuffers::VOffsetT = 18;
- pub const VT_F32_: flatbuffers::VOffsetT = 20;
- pub const VT_F64_: flatbuffers::VOffsetT = 22;
- pub const VT_V8: flatbuffers::VOffsetT = 24;
- pub const VT_VF64: flatbuffers::VOffsetT = 26;
-
- #[inline]
- pub fn i8_(&self) -> i8 {
- self._tab.get::<i8>(TypeAliases::VT_I8_, Some(0)).unwrap()
- }
- #[inline]
- pub fn u8_(&self) -> u8 {
- self._tab.get::<u8>(TypeAliases::VT_U8_, Some(0)).unwrap()
- }
- #[inline]
- pub fn i16_(&self) -> i16 {
- self._tab.get::<i16>(TypeAliases::VT_I16_, Some(0)).unwrap()
- }
- #[inline]
- pub fn u16_(&self) -> u16 {
- self._tab.get::<u16>(TypeAliases::VT_U16_, Some(0)).unwrap()
- }
- #[inline]
- pub fn i32_(&self) -> i32 {
- self._tab.get::<i32>(TypeAliases::VT_I32_, Some(0)).unwrap()
- }
- #[inline]
- pub fn u32_(&self) -> u32 {
- self._tab.get::<u32>(TypeAliases::VT_U32_, Some(0)).unwrap()
- }
- #[inline]
- pub fn i64_(&self) -> i64 {
- self._tab.get::<i64>(TypeAliases::VT_I64_, Some(0)).unwrap()
- }
- #[inline]
- pub fn u64_(&self) -> u64 {
- self._tab.get::<u64>(TypeAliases::VT_U64_, Some(0)).unwrap()
- }
- #[inline]
- pub fn f32_(&self) -> f32 {
- self._tab.get::<f32>(TypeAliases::VT_F32_, Some(0.0)).unwrap()
- }
- #[inline]
- pub fn f64_(&self) -> f64 {
- self._tab.get::<f64>(TypeAliases::VT_F64_, Some(0.0)).unwrap()
- }
- #[inline]
- pub fn v8(&self) -> Option<&'a [i8]> {
- self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, i8>>>(TypeAliases::VT_V8, None).map(|v| v.safe_slice())
- }
- #[inline]
- pub fn vf64(&self) -> Option<flatbuffers::Vector<'a, f64>> {
- self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, f64>>>(TypeAliases::VT_VF64, None)
- }
-}
-
-pub struct TypeAliasesArgs<'a> {
- pub i8_: i8,
- pub u8_: u8,
- pub i16_: i16,
- pub u16_: u16,
- pub i32_: i32,
- pub u32_: u32,
- pub i64_: i64,
- pub u64_: u64,
- pub f32_: f32,
- pub f64_: f64,
- pub v8: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, i8>>>,
- pub vf64: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, f64>>>,
-}
-impl<'a> Default for TypeAliasesArgs<'a> {
- #[inline]
- fn default() -> Self {
- TypeAliasesArgs {
- i8_: 0,
- u8_: 0,
- i16_: 0,
- u16_: 0,
- i32_: 0,
- u32_: 0,
- i64_: 0,
- u64_: 0,
- f32_: 0.0,
- f64_: 0.0,
- v8: None,
- vf64: None,
- }
- }
-}
-pub struct TypeAliasesBuilder<'a: 'b, 'b> {
- fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
- start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
-}
-impl<'a: 'b, 'b> TypeAliasesBuilder<'a, 'b> {
- #[inline]
- pub fn add_i8_(&mut self, i8_: i8) {
- self.fbb_.push_slot::<i8>(TypeAliases::VT_I8_, i8_, 0);
- }
- #[inline]
- pub fn add_u8_(&mut self, u8_: u8) {
- self.fbb_.push_slot::<u8>(TypeAliases::VT_U8_, u8_, 0);
- }
- #[inline]
- pub fn add_i16_(&mut self, i16_: i16) {
- self.fbb_.push_slot::<i16>(TypeAliases::VT_I16_, i16_, 0);
- }
- #[inline]
- pub fn add_u16_(&mut self, u16_: u16) {
- self.fbb_.push_slot::<u16>(TypeAliases::VT_U16_, u16_, 0);
- }
- #[inline]
- pub fn add_i32_(&mut self, i32_: i32) {
- self.fbb_.push_slot::<i32>(TypeAliases::VT_I32_, i32_, 0);
- }
- #[inline]
- pub fn add_u32_(&mut self, u32_: u32) {
- self.fbb_.push_slot::<u32>(TypeAliases::VT_U32_, u32_, 0);
- }
- #[inline]
- pub fn add_i64_(&mut self, i64_: i64) {
- self.fbb_.push_slot::<i64>(TypeAliases::VT_I64_, i64_, 0);
- }
- #[inline]
- pub fn add_u64_(&mut self, u64_: u64) {
- self.fbb_.push_slot::<u64>(TypeAliases::VT_U64_, u64_, 0);
- }
- #[inline]
- pub fn add_f32_(&mut self, f32_: f32) {
- self.fbb_.push_slot::<f32>(TypeAliases::VT_F32_, f32_, 0.0);
- }
- #[inline]
- pub fn add_f64_(&mut self, f64_: f64) {
- self.fbb_.push_slot::<f64>(TypeAliases::VT_F64_, f64_, 0.0);
- }
- #[inline]
- pub fn add_v8(&mut self, v8: flatbuffers::WIPOffset<flatbuffers::Vector<'b , i8>>) {
- self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(TypeAliases::VT_V8, v8);
- }
- #[inline]
- pub fn add_vf64(&mut self, vf64: flatbuffers::WIPOffset<flatbuffers::Vector<'b , f64>>) {
- self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(TypeAliases::VT_VF64, vf64);
- }
- #[inline]
- pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> TypeAliasesBuilder<'a, 'b> {
- let start = _fbb.start_table();
- TypeAliasesBuilder {
- fbb_: _fbb,
- start_: start,
- }
- }
- #[inline]
- pub fn finish(self) -> flatbuffers::WIPOffset<TypeAliases<'a>> {
- let o = self.fbb_.end_table(self.start_);
- flatbuffers::WIPOffset::new(o.value())
- }
-}
-
-impl std::fmt::Debug for TypeAliases<'_> {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- let mut ds = f.debug_struct("TypeAliases");
- ds.field("i8_", &self.i8_());
- ds.field("u8_", &self.u8_());
- ds.field("i16_", &self.i16_());
- ds.field("u16_", &self.u16_());
- ds.field("i32_", &self.i32_());
- ds.field("u32_", &self.u32_());
- ds.field("i64_", &self.i64_());
- ds.field("u64_", &self.u64_());
- ds.field("f32_", &self.f32_());
- ds.field("f64_", &self.f64_());
- ds.field("v8", &self.v8());
- ds.field("vf64", &self.vf64());
- ds.finish()
- }
-}
-#[inline]
-pub fn get_root_as_monster<'a>(buf: &'a [u8]) -> Monster<'a> {
- flatbuffers::get_root::<Monster<'a>>(buf)
-}
-
-#[inline]
-pub fn get_size_prefixed_root_as_monster<'a>(buf: &'a [u8]) -> Monster<'a> {
- flatbuffers::get_size_prefixed_root::<Monster<'a>>(buf)
-}
-
-pub const MONSTER_IDENTIFIER: &str = "MONS";
-
-#[inline]
-pub fn monster_buffer_has_identifier(buf: &[u8]) -> bool {
- flatbuffers::buffer_has_identifier(buf, MONSTER_IDENTIFIER, false)
-}
-
-#[inline]
-pub fn monster_size_prefixed_buffer_has_identifier(buf: &[u8]) -> bool {
- flatbuffers::buffer_has_identifier(buf, MONSTER_IDENTIFIER, true)
-}
-
-pub const MONSTER_EXTENSION: &str = "mon";
-
-#[inline]
-pub fn finish_monster_buffer<'a, 'b>(
- fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,
- root: flatbuffers::WIPOffset<Monster<'a>>) {
- fbb.finish(root, Some(MONSTER_IDENTIFIER));
-}
-
-#[inline]
-pub fn finish_size_prefixed_monster_buffer<'a, 'b>(fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>, root: flatbuffers::WIPOffset<Monster<'a>>) {
- fbb.finish_size_prefixed(root, Some(MONSTER_IDENTIFIER));
-}
-} // pub mod Example
-} // pub mod MyGame
-
diff --git a/tests/monster_test_generated.ts b/tests/monster_test_generated.ts
deleted file mode 100644
index d210917..0000000
--- a/tests/monster_test_generated.ts
+++ /dev/null
@@ -1,3954 +0,0 @@
-// automatically generated by the FlatBuffers compiler, do not modify
-
-/**
- * Composite components of Monster color.
- *
- * @enum {number}
- */
-export namespace MyGame.Example{
-export enum Color{
- Red= 1,
-
- /**
- * \brief color Green
- * Green is bit_flag with value (1u << 1)
- */
- Green= 2,
-
- /**
- * \brief color Blue (1u << 3)
- */
- Blue= 8
-};
-}
-
-/**
- * @enum {number}
- */
-export namespace MyGame.Example{
-export enum Race{
- None= -1,
- Human= 0,
- Dwarf= 1,
- Elf= 2
-};
-}
-
-/**
- * @enum {number}
- */
-export namespace MyGame.Example{
-export enum Any{
- NONE= 0,
- Monster= 1,
- TestSimpleTableWithEnum= 2,
- MyGame_Example2_Monster= 3
-};
-
-export function unionToAny(
- type: Any,
- accessor: (obj:MyGame.Example.Monster|MyGame.Example.TestSimpleTableWithEnum|MyGame.Example2.Monster) => MyGame.Example.Monster|MyGame.Example.TestSimpleTableWithEnum|MyGame.Example2.Monster|null
-): MyGame.Example.Monster|MyGame.Example.TestSimpleTableWithEnum|MyGame.Example2.Monster|null {
- switch(MyGame.Example.Any[type]) {
- case 'NONE': return null;
- case 'Monster': return accessor(new MyGame.Example.Monster())! as MyGame.Example.Monster;
- case 'TestSimpleTableWithEnum': return accessor(new MyGame.Example.TestSimpleTableWithEnum())! as MyGame.Example.TestSimpleTableWithEnum;
- case 'MyGame_Example2_Monster': return accessor(new MyGame.Example2.Monster())! as MyGame.Example2.Monster;
- default: return null;
- }
-}
-
-export function unionListToAny(
- type: Any,
- accessor: (index: number, obj:MyGame.Example.Monster|MyGame.Example.TestSimpleTableWithEnum|MyGame.Example2.Monster) => MyGame.Example.Monster|MyGame.Example.TestSimpleTableWithEnum|MyGame.Example2.Monster|null,
- index: number
-): MyGame.Example.Monster|MyGame.Example.TestSimpleTableWithEnum|MyGame.Example2.Monster|null {
- switch(MyGame.Example.Any[type]) {
- case 'NONE': return null;
- case 'Monster': return accessor(index, new MyGame.Example.Monster())! as MyGame.Example.Monster;
- case 'TestSimpleTableWithEnum': return accessor(index, new MyGame.Example.TestSimpleTableWithEnum())! as MyGame.Example.TestSimpleTableWithEnum;
- case 'MyGame_Example2_Monster': return accessor(index, new MyGame.Example2.Monster())! as MyGame.Example2.Monster;
- default: return null;
- }
-}
-}
-
-/**
- * @enum {number}
- */
-export namespace MyGame.Example{
-export enum AnyUniqueAliases{
- NONE= 0,
- M= 1,
- TS= 2,
- M2= 3
-};
-
-export function unionToAnyUniqueAliases(
- type: AnyUniqueAliases,
- accessor: (obj:MyGame.Example.Monster|MyGame.Example.TestSimpleTableWithEnum|MyGame.Example2.Monster) => MyGame.Example.Monster|MyGame.Example.TestSimpleTableWithEnum|MyGame.Example2.Monster|null
-): MyGame.Example.Monster|MyGame.Example.TestSimpleTableWithEnum|MyGame.Example2.Monster|null {
- switch(MyGame.Example.AnyUniqueAliases[type]) {
- case 'NONE': return null;
- case 'M': return accessor(new MyGame.Example.Monster())! as MyGame.Example.Monster;
- case 'TS': return accessor(new MyGame.Example.TestSimpleTableWithEnum())! as MyGame.Example.TestSimpleTableWithEnum;
- case 'M2': return accessor(new MyGame.Example2.Monster())! as MyGame.Example2.Monster;
- default: return null;
- }
-}
-
-export function unionListToAnyUniqueAliases(
- type: AnyUniqueAliases,
- accessor: (index: number, obj:MyGame.Example.Monster|MyGame.Example.TestSimpleTableWithEnum|MyGame.Example2.Monster) => MyGame.Example.Monster|MyGame.Example.TestSimpleTableWithEnum|MyGame.Example2.Monster|null,
- index: number
-): MyGame.Example.Monster|MyGame.Example.TestSimpleTableWithEnum|MyGame.Example2.Monster|null {
- switch(MyGame.Example.AnyUniqueAliases[type]) {
- case 'NONE': return null;
- case 'M': return accessor(index, new MyGame.Example.Monster())! as MyGame.Example.Monster;
- case 'TS': return accessor(index, new MyGame.Example.TestSimpleTableWithEnum())! as MyGame.Example.TestSimpleTableWithEnum;
- case 'M2': return accessor(index, new MyGame.Example2.Monster())! as MyGame.Example2.Monster;
- default: return null;
- }
-}
-}
-
-/**
- * @enum {number}
- */
-export namespace MyGame.Example{
-export enum AnyAmbiguousAliases{
- NONE= 0,
- M1= 1,
- M2= 2,
- M3= 3
-};
-
-export function unionToAnyAmbiguousAliases(
- type: AnyAmbiguousAliases,
- accessor: (obj:MyGame.Example.Monster) => MyGame.Example.Monster|null
-): MyGame.Example.Monster|null {
- switch(MyGame.Example.AnyAmbiguousAliases[type]) {
- case 'NONE': return null;
- case 'M1': return accessor(new MyGame.Example.Monster())! as MyGame.Example.Monster;
- case 'M2': return accessor(new MyGame.Example.Monster())! as MyGame.Example.Monster;
- case 'M3': return accessor(new MyGame.Example.Monster())! as MyGame.Example.Monster;
- default: return null;
- }
-}
-
-export function unionListToAnyAmbiguousAliases(
- type: AnyAmbiguousAliases,
- accessor: (index: number, obj:MyGame.Example.Monster) => MyGame.Example.Monster|null,
- index: number
-): MyGame.Example.Monster|null {
- switch(MyGame.Example.AnyAmbiguousAliases[type]) {
- case 'NONE': return null;
- case 'M1': return accessor(index, new MyGame.Example.Monster())! as MyGame.Example.Monster;
- case 'M2': return accessor(index, new MyGame.Example.Monster())! as MyGame.Example.Monster;
- case 'M3': return accessor(index, new MyGame.Example.Monster())! as MyGame.Example.Monster;
- default: return null;
- }
-}
-}
-
-/**
- * @constructor
- */
-export namespace MyGame{
-export class InParentNamespace {
- bb: flatbuffers.ByteBuffer|null = null;
-
- bb_pos:number = 0;
-/**
- * @param number i
- * @param flatbuffers.ByteBuffer bb
- * @returns InParentNamespace
- */
-__init(i:number, bb:flatbuffers.ByteBuffer):InParentNamespace {
- this.bb_pos = i;
- this.bb = bb;
- return this;
-};
-
-/**
- * @param flatbuffers.ByteBuffer bb
- * @param InParentNamespace= obj
- * @returns InParentNamespace
- */
-static getRootAsInParentNamespace(bb:flatbuffers.ByteBuffer, obj?:InParentNamespace):InParentNamespace {
- return (obj || new InParentNamespace()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param flatbuffers.ByteBuffer bb
- * @param InParentNamespace= obj
- * @returns InParentNamespace
- */
-static getSizePrefixedRootAsInParentNamespace(bb:flatbuffers.ByteBuffer, obj?:InParentNamespace):InParentNamespace {
- bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
- return (obj || new InParentNamespace()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param flatbuffers.Builder builder
- */
-static startInParentNamespace(builder:flatbuffers.Builder) {
- builder.startObject(0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @returns flatbuffers.Offset
- */
-static endInParentNamespace(builder:flatbuffers.Builder):flatbuffers.Offset {
- var offset = builder.endObject();
- return offset;
-};
-
-static createInParentNamespace(builder:flatbuffers.Builder):flatbuffers.Offset {
- InParentNamespace.startInParentNamespace(builder);
- return InParentNamespace.endInParentNamespace(builder);
-}
-
-serialize():Uint8Array {
- return this.bb!.bytes();
-}
-
-static deserialize(buffer: Uint8Array):InParentNamespace {
- return InParentNamespace.getRootAsInParentNamespace(new flatbuffers.ByteBuffer(buffer))
-}
-
-/**
- * @returns InParentNamespaceT
- */
-unpack(): InParentNamespaceT {
- return new InParentNamespaceT();
-};
-
-/**
- * @param InParentNamespaceT _o
- */
-unpackTo(_o: InParentNamespaceT): void {};
-}
-
-export class InParentNamespaceT {
-/**
- * @constructor
- */
-constructor(){};
-
-/**
- * @param flatbuffers.Builder builder
- * @returns flatbuffers.Offset
- */
-pack(builder:flatbuffers.Builder): flatbuffers.Offset {
- return MyGame.InParentNamespace.createInParentNamespace(builder);
-};
-}
-}
-/**
- * @constructor
- */
-export namespace MyGame.Example2{
-export class Monster {
- bb: flatbuffers.ByteBuffer|null = null;
-
- bb_pos:number = 0;
-/**
- * @param number i
- * @param flatbuffers.ByteBuffer bb
- * @returns Monster
- */
-__init(i:number, bb:flatbuffers.ByteBuffer):Monster {
- this.bb_pos = i;
- this.bb = bb;
- return this;
-};
-
-/**
- * @param flatbuffers.ByteBuffer bb
- * @param Monster= obj
- * @returns Monster
- */
-static getRootAsMonster(bb:flatbuffers.ByteBuffer, obj?:Monster):Monster {
- return (obj || new Monster()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param flatbuffers.ByteBuffer bb
- * @param Monster= obj
- * @returns Monster
- */
-static getSizePrefixedRootAsMonster(bb:flatbuffers.ByteBuffer, obj?:Monster):Monster {
- bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
- return (obj || new Monster()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param flatbuffers.Builder builder
- */
-static startMonster(builder:flatbuffers.Builder) {
- builder.startObject(0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @returns flatbuffers.Offset
- */
-static endMonster(builder:flatbuffers.Builder):flatbuffers.Offset {
- var offset = builder.endObject();
- return offset;
-};
-
-static createMonster(builder:flatbuffers.Builder):flatbuffers.Offset {
- Monster.startMonster(builder);
- return Monster.endMonster(builder);
-}
-
-serialize():Uint8Array {
- return this.bb!.bytes();
-}
-
-static deserialize(buffer: Uint8Array):Monster {
- return Monster.getRootAsMonster(new flatbuffers.ByteBuffer(buffer))
-}
-
-/**
- * @returns MonsterT
- */
-unpack(): MonsterT {
- return new MonsterT();
-};
-
-/**
- * @param MonsterT _o
- */
-unpackTo(_o: MonsterT): void {};
-}
-
-export class MonsterT {
-/**
- * @constructor
- */
-constructor(){};
-
-/**
- * @param flatbuffers.Builder builder
- * @returns flatbuffers.Offset
- */
-pack(builder:flatbuffers.Builder): flatbuffers.Offset {
- return MyGame.Example2.Monster.createMonster(builder);
-};
-}
-}
-/**
- * @constructor
- */
-export namespace MyGame.Example{
-export class Test {
- bb: flatbuffers.ByteBuffer|null = null;
-
- bb_pos:number = 0;
-/**
- * @param number i
- * @param flatbuffers.ByteBuffer bb
- * @returns Test
- */
-__init(i:number, bb:flatbuffers.ByteBuffer):Test {
- this.bb_pos = i;
- this.bb = bb;
- return this;
-};
-
-/**
- * @returns number
- */
-a():number {
- return this.bb!.readInt16(this.bb_pos);
-};
-
-/**
- * @param number value
- * @returns boolean
- */
-mutate_a(value:number):boolean {
- this.bb!.writeInt16(this.bb_pos + 0, value);
- return true;
-};
-
-/**
- * @returns number
- */
-b():number {
- return this.bb!.readInt8(this.bb_pos + 2);
-};
-
-/**
- * @param number value
- * @returns boolean
- */
-mutate_b(value:number):boolean {
- this.bb!.writeInt8(this.bb_pos + 2, value);
- return true;
-};
-
-/**
- * @returns number
- */
-static sizeOf():number {
- return 4;
-}
-
-/**
- * @param flatbuffers.Builder builder
- * @param number a
- * @param number b
- * @returns flatbuffers.Offset
- */
-static createTest(builder:flatbuffers.Builder, a: number, b: number):flatbuffers.Offset {
- builder.prep(2, 4);
- builder.pad(1);
- builder.writeInt8(b);
- builder.writeInt16(a);
- return builder.offset();
-};
-
-
-/**
- * @returns TestT
- */
-unpack(): TestT {
- return new TestT(
- this.a(),
- this.b()
- );
-};
-
-/**
- * @param TestT _o
- */
-unpackTo(_o: TestT): void {
- _o.a = this.a();
- _o.b = this.b();
-};
-}
-
-export class TestT {
-/**
- * @constructor
- * @param number a
- * @param number b
- */
-constructor(
- public a: number = 0,
- public b: number = 0
-){};
-
-/**
- * @param flatbuffers.Builder builder
- * @returns flatbuffers.Offset
- */
-pack(builder:flatbuffers.Builder): flatbuffers.Offset {
- return MyGame.Example.Test.createTest(builder,
- this.a,
- this.b
- );
-};
-}
-}
-/**
- * @constructor
- */
-export namespace MyGame.Example{
-export class TestSimpleTableWithEnum {
- bb: flatbuffers.ByteBuffer|null = null;
-
- bb_pos:number = 0;
-/**
- * @param number i
- * @param flatbuffers.ByteBuffer bb
- * @returns TestSimpleTableWithEnum
- */
-__init(i:number, bb:flatbuffers.ByteBuffer):TestSimpleTableWithEnum {
- this.bb_pos = i;
- this.bb = bb;
- return this;
-};
-
-/**
- * @param flatbuffers.ByteBuffer bb
- * @param TestSimpleTableWithEnum= obj
- * @returns TestSimpleTableWithEnum
- */
-static getRootAsTestSimpleTableWithEnum(bb:flatbuffers.ByteBuffer, obj?:TestSimpleTableWithEnum):TestSimpleTableWithEnum {
- return (obj || new TestSimpleTableWithEnum()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param flatbuffers.ByteBuffer bb
- * @param TestSimpleTableWithEnum= obj
- * @returns TestSimpleTableWithEnum
- */
-static getSizePrefixedRootAsTestSimpleTableWithEnum(bb:flatbuffers.ByteBuffer, obj?:TestSimpleTableWithEnum):TestSimpleTableWithEnum {
- bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
- return (obj || new TestSimpleTableWithEnum()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @returns MyGame.Example.Color
- */
-color():MyGame.Example.Color {
- var offset = this.bb!.__offset(this.bb_pos, 4);
- return offset ? /** */ (this.bb!.readUint8(this.bb_pos + offset)) : MyGame.Example.Color.Green;
-};
-
-/**
- * @param MyGame.Example.Color value
- * @returns boolean
- */
-mutate_color(value:MyGame.Example.Color):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 4);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb!.writeUint8(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @param flatbuffers.Builder builder
- */
-static startTestSimpleTableWithEnum(builder:flatbuffers.Builder) {
- builder.startObject(1);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param MyGame.Example.Color color
- */
-static addColor(builder:flatbuffers.Builder, color:MyGame.Example.Color) {
- builder.addFieldInt8(0, color, MyGame.Example.Color.Green);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @returns flatbuffers.Offset
- */
-static endTestSimpleTableWithEnum(builder:flatbuffers.Builder):flatbuffers.Offset {
- var offset = builder.endObject();
- return offset;
-};
-
-static createTestSimpleTableWithEnum(builder:flatbuffers.Builder, color:MyGame.Example.Color):flatbuffers.Offset {
- TestSimpleTableWithEnum.startTestSimpleTableWithEnum(builder);
- TestSimpleTableWithEnum.addColor(builder, color);
- return TestSimpleTableWithEnum.endTestSimpleTableWithEnum(builder);
-}
-
-serialize():Uint8Array {
- return this.bb!.bytes();
-}
-
-static deserialize(buffer: Uint8Array):TestSimpleTableWithEnum {
- return TestSimpleTableWithEnum.getRootAsTestSimpleTableWithEnum(new flatbuffers.ByteBuffer(buffer))
-}
-
-/**
- * @returns TestSimpleTableWithEnumT
- */
-unpack(): TestSimpleTableWithEnumT {
- return new TestSimpleTableWithEnumT(
- this.color()
- );
-};
-
-/**
- * @param TestSimpleTableWithEnumT _o
- */
-unpackTo(_o: TestSimpleTableWithEnumT): void {
- _o.color = this.color();
-};
-}
-
-export class TestSimpleTableWithEnumT {
-/**
- * @constructor
- * @param MyGame.Example.Color color
- */
-constructor(
- public color: MyGame.Example.Color = MyGame.Example.Color.Green
-){};
-
-/**
- * @param flatbuffers.Builder builder
- * @returns flatbuffers.Offset
- */
-pack(builder:flatbuffers.Builder): flatbuffers.Offset {
- return MyGame.Example.TestSimpleTableWithEnum.createTestSimpleTableWithEnum(builder,
- this.color
- );
-};
-}
-}
-/**
- * @constructor
- */
-export namespace MyGame.Example{
-export class Vec3 {
- bb: flatbuffers.ByteBuffer|null = null;
-
- bb_pos:number = 0;
-/**
- * @param number i
- * @param flatbuffers.ByteBuffer bb
- * @returns Vec3
- */
-__init(i:number, bb:flatbuffers.ByteBuffer):Vec3 {
- this.bb_pos = i;
- this.bb = bb;
- return this;
-};
-
-/**
- * @returns number
- */
-x():number {
- return this.bb!.readFloat32(this.bb_pos);
-};
-
-/**
- * @param number value
- * @returns boolean
- */
-mutate_x(value:number):boolean {
- this.bb!.writeFloat32(this.bb_pos + 0, value);
- return true;
-};
-
-/**
- * @returns number
- */
-y():number {
- return this.bb!.readFloat32(this.bb_pos + 4);
-};
-
-/**
- * @param number value
- * @returns boolean
- */
-mutate_y(value:number):boolean {
- this.bb!.writeFloat32(this.bb_pos + 4, value);
- return true;
-};
-
-/**
- * @returns number
- */
-z():number {
- return this.bb!.readFloat32(this.bb_pos + 8);
-};
-
-/**
- * @param number value
- * @returns boolean
- */
-mutate_z(value:number):boolean {
- this.bb!.writeFloat32(this.bb_pos + 8, value);
- return true;
-};
-
-/**
- * @returns number
- */
-test1():number {
- return this.bb!.readFloat64(this.bb_pos + 16);
-};
-
-/**
- * @param number value
- * @returns boolean
- */
-mutate_test1(value:number):boolean {
- this.bb!.writeFloat64(this.bb_pos + 16, value);
- return true;
-};
-
-/**
- * @returns MyGame.Example.Color
- */
-test2():MyGame.Example.Color {
- return /** */ (this.bb!.readUint8(this.bb_pos + 24));
-};
-
-/**
- * @param MyGame.Example.Color value
- * @returns boolean
- */
-mutate_test2(value:MyGame.Example.Color):boolean {
- this.bb!.writeUint8(this.bb_pos + 24, value);
- return true;
-};
-
-/**
- * @param MyGame.Example.Test= obj
- * @returns MyGame.Example.Test|null
- */
-test3(obj?:MyGame.Example.Test):MyGame.Example.Test|null {
- return (obj || new MyGame.Example.Test()).__init(this.bb_pos + 26, this.bb!);
-};
-
-/**
- * @returns number
- */
-static sizeOf():number {
- return 32;
-}
-
-/**
- * @param flatbuffers.Builder builder
- * @param number x
- * @param number y
- * @param number z
- * @param number test1
- * @param MyGame.Example.Color test2
- * @param number test3_a
- * @param number test3_b
- * @returns flatbuffers.Offset
- */
-static createVec3(builder:flatbuffers.Builder, x: number, y: number, z: number, test1: number, test2: MyGame.Example.Color, test3_a: number, test3_b: number):flatbuffers.Offset {
- builder.prep(8, 32);
- builder.pad(2);
- builder.prep(2, 4);
- builder.pad(1);
- builder.writeInt8(test3_b);
- builder.writeInt16(test3_a);
- builder.pad(1);
- builder.writeInt8(test2);
- builder.writeFloat64(test1);
- builder.pad(4);
- builder.writeFloat32(z);
- builder.writeFloat32(y);
- builder.writeFloat32(x);
- return builder.offset();
-};
-
-
-/**
- * @returns Vec3T
- */
-unpack(): Vec3T {
- return new Vec3T(
- this.x(),
- this.y(),
- this.z(),
- this.test1(),
- this.test2(),
- (this.test3() !== null ? this.test3()!.unpack() : null)
- );
-};
-
-/**
- * @param Vec3T _o
- */
-unpackTo(_o: Vec3T): void {
- _o.x = this.x();
- _o.y = this.y();
- _o.z = this.z();
- _o.test1 = this.test1();
- _o.test2 = this.test2();
- _o.test3 = (this.test3() !== null ? this.test3()!.unpack() : null);
-};
-}
-
-export class Vec3T {
-/**
- * @constructor
- * @param number x
- * @param number y
- * @param number z
- * @param number test1
- * @param MyGame.Example.Color test2
- * @param MyGame.Example.TestT|null test3
- */
-constructor(
- public x: number = 0.0,
- public y: number = 0.0,
- public z: number = 0.0,
- public test1: number = 0.0,
- public test2: MyGame.Example.Color = /** } */ (0),
- public test3: MyGame.Example.TestT|null = null
-){};
-
-/**
- * @param flatbuffers.Builder builder
- * @returns flatbuffers.Offset
- */
-pack(builder:flatbuffers.Builder): flatbuffers.Offset {
- return MyGame.Example.Vec3.createVec3(builder,
- this.x,
- this.y,
- this.z,
- this.test1,
- this.test2,
- (this.test3 === null ? 0 : this.test3.a!),
- (this.test3 === null ? 0 : this.test3.b!)
- );
-};
-}
-}
-/**
- * @constructor
- */
-export namespace MyGame.Example{
-export class Ability {
- bb: flatbuffers.ByteBuffer|null = null;
-
- bb_pos:number = 0;
-/**
- * @param number i
- * @param flatbuffers.ByteBuffer bb
- * @returns Ability
- */
-__init(i:number, bb:flatbuffers.ByteBuffer):Ability {
- this.bb_pos = i;
- this.bb = bb;
- return this;
-};
-
-/**
- * @returns number
- */
-id():number {
- return this.bb!.readUint32(this.bb_pos);
-};
-
-/**
- * @param number value
- * @returns boolean
- */
-mutate_id(value:number):boolean {
- this.bb!.writeUint32(this.bb_pos + 0, value);
- return true;
-};
-
-/**
- * @returns number
- */
-distance():number {
- return this.bb!.readUint32(this.bb_pos + 4);
-};
-
-/**
- * @param number value
- * @returns boolean
- */
-mutate_distance(value:number):boolean {
- this.bb!.writeUint32(this.bb_pos + 4, value);
- return true;
-};
-
-/**
- * @returns number
- */
-static sizeOf():number {
- return 8;
-}
-
-/**
- * @param flatbuffers.Builder builder
- * @param number id
- * @param number distance
- * @returns flatbuffers.Offset
- */
-static createAbility(builder:flatbuffers.Builder, id: number, distance: number):flatbuffers.Offset {
- builder.prep(4, 8);
- builder.writeInt32(distance);
- builder.writeInt32(id);
- return builder.offset();
-};
-
-
-/**
- * @returns AbilityT
- */
-unpack(): AbilityT {
- return new AbilityT(
- this.id(),
- this.distance()
- );
-};
-
-/**
- * @param AbilityT _o
- */
-unpackTo(_o: AbilityT): void {
- _o.id = this.id();
- _o.distance = this.distance();
-};
-}
-
-export class AbilityT {
-/**
- * @constructor
- * @param number id
- * @param number distance
- */
-constructor(
- public id: number = 0,
- public distance: number = 0
-){};
-
-/**
- * @param flatbuffers.Builder builder
- * @returns flatbuffers.Offset
- */
-pack(builder:flatbuffers.Builder): flatbuffers.Offset {
- return MyGame.Example.Ability.createAbility(builder,
- this.id,
- this.distance
- );
-};
-}
-}
-/**
- * @constructor
- */
-export namespace MyGame.Example{
-export class Stat {
- bb: flatbuffers.ByteBuffer|null = null;
-
- bb_pos:number = 0;
-/**
- * @param number i
- * @param flatbuffers.ByteBuffer bb
- * @returns Stat
- */
-__init(i:number, bb:flatbuffers.ByteBuffer):Stat {
- this.bb_pos = i;
- this.bb = bb;
- return this;
-};
-
-/**
- * @param flatbuffers.ByteBuffer bb
- * @param Stat= obj
- * @returns Stat
- */
-static getRootAsStat(bb:flatbuffers.ByteBuffer, obj?:Stat):Stat {
- return (obj || new Stat()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param flatbuffers.ByteBuffer bb
- * @param Stat= obj
- * @returns Stat
- */
-static getSizePrefixedRootAsStat(bb:flatbuffers.ByteBuffer, obj?:Stat):Stat {
- bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
- return (obj || new Stat()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param flatbuffers.Encoding= optionalEncoding
- * @returns string|Uint8Array|null
- */
-id():string|null
-id(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null
-id(optionalEncoding?:any):string|Uint8Array|null {
- var offset = this.bb!.__offset(this.bb_pos, 4);
- return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
-};
-
-/**
- * @returns flatbuffers.Long
- */
-val():flatbuffers.Long {
- var offset = this.bb!.__offset(this.bb_pos, 6);
- return offset ? this.bb!.readInt64(this.bb_pos + offset) : this.bb!.createLong(0, 0);
-};
-
-/**
- * @param flatbuffers.Long value
- * @returns boolean
- */
-mutate_val(value:flatbuffers.Long):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 6);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb!.writeInt64(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @returns number
- */
-count():number {
- var offset = this.bb!.__offset(this.bb_pos, 8);
- return offset ? this.bb!.readUint16(this.bb_pos + offset) : 0;
-};
-
-/**
- * @param number value
- * @returns boolean
- */
-mutate_count(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 8);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb!.writeUint16(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @param flatbuffers.Builder builder
- */
-static startStat(builder:flatbuffers.Builder) {
- builder.startObject(3);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Offset idOffset
- */
-static addId(builder:flatbuffers.Builder, idOffset:flatbuffers.Offset) {
- builder.addFieldOffset(0, idOffset, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Long val
- */
-static addVal(builder:flatbuffers.Builder, val:flatbuffers.Long) {
- builder.addFieldInt64(1, val, builder.createLong(0, 0));
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number count
- */
-static addCount(builder:flatbuffers.Builder, count:number) {
- builder.addFieldInt16(2, count, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @returns flatbuffers.Offset
- */
-static endStat(builder:flatbuffers.Builder):flatbuffers.Offset {
- var offset = builder.endObject();
- return offset;
-};
-
-static createStat(builder:flatbuffers.Builder, idOffset:flatbuffers.Offset, val:flatbuffers.Long, count:number):flatbuffers.Offset {
- Stat.startStat(builder);
- Stat.addId(builder, idOffset);
- Stat.addVal(builder, val);
- Stat.addCount(builder, count);
- return Stat.endStat(builder);
-}
-
-serialize():Uint8Array {
- return this.bb!.bytes();
-}
-
-static deserialize(buffer: Uint8Array):Stat {
- return Stat.getRootAsStat(new flatbuffers.ByteBuffer(buffer))
-}
-
-/**
- * @returns StatT
- */
-unpack(): StatT {
- return new StatT(
- this.id(),
- this.val(),
- this.count()
- );
-};
-
-/**
- * @param StatT _o
- */
-unpackTo(_o: StatT): void {
- _o.id = this.id();
- _o.val = this.val();
- _o.count = this.count();
-};
-}
-
-export class StatT {
-/**
- * @constructor
- * @param string|Uint8Array|null id
- * @param flatbuffers.Long val
- * @param number count
- */
-constructor(
- public id: string|Uint8Array|null = null,
- public val: flatbuffers.Long = flatbuffers.createLong(0, 0),
- public count: number = 0
-){};
-
-/**
- * @param flatbuffers.Builder builder
- * @returns flatbuffers.Offset
- */
-pack(builder:flatbuffers.Builder): flatbuffers.Offset {
- const id = (this.id !== null ? builder.createString(this.id!) : 0);
-
- return MyGame.Example.Stat.createStat(builder,
- id,
- this.val,
- this.count
- );
-};
-}
-}
-/**
- * @constructor
- */
-export namespace MyGame.Example{
-export class Referrable {
- bb: flatbuffers.ByteBuffer|null = null;
-
- bb_pos:number = 0;
-/**
- * @param number i
- * @param flatbuffers.ByteBuffer bb
- * @returns Referrable
- */
-__init(i:number, bb:flatbuffers.ByteBuffer):Referrable {
- this.bb_pos = i;
- this.bb = bb;
- return this;
-};
-
-/**
- * @param flatbuffers.ByteBuffer bb
- * @param Referrable= obj
- * @returns Referrable
- */
-static getRootAsReferrable(bb:flatbuffers.ByteBuffer, obj?:Referrable):Referrable {
- return (obj || new Referrable()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param flatbuffers.ByteBuffer bb
- * @param Referrable= obj
- * @returns Referrable
- */
-static getSizePrefixedRootAsReferrable(bb:flatbuffers.ByteBuffer, obj?:Referrable):Referrable {
- bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
- return (obj || new Referrable()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @returns flatbuffers.Long
- */
-id():flatbuffers.Long {
- var offset = this.bb!.__offset(this.bb_pos, 4);
- return offset ? this.bb!.readUint64(this.bb_pos + offset) : this.bb!.createLong(0, 0);
-};
-
-/**
- * @param flatbuffers.Long value
- * @returns boolean
- */
-mutate_id(value:flatbuffers.Long):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 4);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb!.writeUint64(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @param flatbuffers.Builder builder
- */
-static startReferrable(builder:flatbuffers.Builder) {
- builder.startObject(1);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Long id
- */
-static addId(builder:flatbuffers.Builder, id:flatbuffers.Long) {
- builder.addFieldInt64(0, id, builder.createLong(0, 0));
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @returns flatbuffers.Offset
- */
-static endReferrable(builder:flatbuffers.Builder):flatbuffers.Offset {
- var offset = builder.endObject();
- return offset;
-};
-
-static createReferrable(builder:flatbuffers.Builder, id:flatbuffers.Long):flatbuffers.Offset {
- Referrable.startReferrable(builder);
- Referrable.addId(builder, id);
- return Referrable.endReferrable(builder);
-}
-
-serialize():Uint8Array {
- return this.bb!.bytes();
-}
-
-static deserialize(buffer: Uint8Array):Referrable {
- return Referrable.getRootAsReferrable(new flatbuffers.ByteBuffer(buffer))
-}
-
-/**
- * @returns ReferrableT
- */
-unpack(): ReferrableT {
- return new ReferrableT(
- this.id()
- );
-};
-
-/**
- * @param ReferrableT _o
- */
-unpackTo(_o: ReferrableT): void {
- _o.id = this.id();
-};
-}
-
-export class ReferrableT {
-/**
- * @constructor
- * @param flatbuffers.Long id
- */
-constructor(
- public id: flatbuffers.Long = flatbuffers.createLong(0, 0)
-){};
-
-/**
- * @param flatbuffers.Builder builder
- * @returns flatbuffers.Offset
- */
-pack(builder:flatbuffers.Builder): flatbuffers.Offset {
- return MyGame.Example.Referrable.createReferrable(builder,
- this.id
- );
-};
-}
-}
-/**
- * an example documentation comment: "monster object"
- *
- * @constructor
- */
-export namespace MyGame.Example{
-export class Monster {
- bb: flatbuffers.ByteBuffer|null = null;
-
- bb_pos:number = 0;
-/**
- * @param number i
- * @param flatbuffers.ByteBuffer bb
- * @returns Monster
- */
-__init(i:number, bb:flatbuffers.ByteBuffer):Monster {
- this.bb_pos = i;
- this.bb = bb;
- return this;
-};
-
-/**
- * @param flatbuffers.ByteBuffer bb
- * @param Monster= obj
- * @returns Monster
- */
-static getRootAsMonster(bb:flatbuffers.ByteBuffer, obj?:Monster):Monster {
- return (obj || new Monster()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param flatbuffers.ByteBuffer bb
- * @param Monster= obj
- * @returns Monster
- */
-static getSizePrefixedRootAsMonster(bb:flatbuffers.ByteBuffer, obj?:Monster):Monster {
- bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
- return (obj || new Monster()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param flatbuffers.ByteBuffer bb
- * @returns boolean
- */
-static bufferHasIdentifier(bb:flatbuffers.ByteBuffer):boolean {
- return bb.__has_identifier('MONS');
-};
-
-/**
- * @param MyGame.Example.Vec3= obj
- * @returns MyGame.Example.Vec3|null
- */
-pos(obj?:MyGame.Example.Vec3):MyGame.Example.Vec3|null {
- var offset = this.bb!.__offset(this.bb_pos, 4);
- return offset ? (obj || new MyGame.Example.Vec3()).__init(this.bb_pos + offset, this.bb!) : null;
-};
-
-/**
- * @returns number
- */
-mana():number {
- var offset = this.bb!.__offset(this.bb_pos, 6);
- return offset ? this.bb!.readInt16(this.bb_pos + offset) : 150;
-};
-
-/**
- * @param number value
- * @returns boolean
- */
-mutate_mana(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 6);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb!.writeInt16(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @returns number
- */
-hp():number {
- var offset = this.bb!.__offset(this.bb_pos, 8);
- return offset ? this.bb!.readInt16(this.bb_pos + offset) : 100;
-};
-
-/**
- * @param number value
- * @returns boolean
- */
-mutate_hp(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 8);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb!.writeInt16(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @param flatbuffers.Encoding= optionalEncoding
- * @returns string|Uint8Array|null
- */
-name():string|null
-name(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null
-name(optionalEncoding?:any):string|Uint8Array|null {
- var offset = this.bb!.__offset(this.bb_pos, 10);
- return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
-};
-
-/**
- * @param number index
- * @returns number
- */
-inventory(index: number):number|null {
- var offset = this.bb!.__offset(this.bb_pos, 14);
- return offset ? this.bb!.readUint8(this.bb!.__vector(this.bb_pos + offset) + index) : 0;
-};
-
-/**
- * @returns number
- */
-inventoryLength():number {
- var offset = this.bb!.__offset(this.bb_pos, 14);
- return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
-};
-
-/**
- * @returns Uint8Array
- */
-inventoryArray():Uint8Array|null {
- var offset = this.bb!.__offset(this.bb_pos, 14);
- return offset ? new Uint8Array(this.bb!.bytes().buffer, this.bb!.bytes().byteOffset + this.bb!.__vector(this.bb_pos + offset), this.bb!.__vector_len(this.bb_pos + offset)) : null;
-};
-
-/**
- * @returns MyGame.Example.Color
- */
-color():MyGame.Example.Color {
- var offset = this.bb!.__offset(this.bb_pos, 16);
- return offset ? /** */ (this.bb!.readUint8(this.bb_pos + offset)) : MyGame.Example.Color.Blue;
-};
-
-/**
- * @param MyGame.Example.Color value
- * @returns boolean
- */
-mutate_color(value:MyGame.Example.Color):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 16);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb!.writeUint8(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @returns MyGame.Example.Any
- */
-testType():MyGame.Example.Any {
- var offset = this.bb!.__offset(this.bb_pos, 18);
- return offset ? /** */ (this.bb!.readUint8(this.bb_pos + offset)) : MyGame.Example.Any.NONE;
-};
-
-/**
- * @param flatbuffers.Table obj
- * @returns ?flatbuffers.Table
- */
-test<T extends flatbuffers.Table>(obj:T):T|null {
- var offset = this.bb!.__offset(this.bb_pos, 20);
- return offset ? this.bb!.__union(obj, this.bb_pos + offset) : null;
-};
-
-/**
- * @param number index
- * @param MyGame.Example.Test= obj
- * @returns MyGame.Example.Test
- */
-test4(index: number, obj?:MyGame.Example.Test):MyGame.Example.Test|null {
- var offset = this.bb!.__offset(this.bb_pos, 22);
- return offset ? (obj || new MyGame.Example.Test()).__init(this.bb!.__vector(this.bb_pos + offset) + index * 4, this.bb!) : null;
-};
-
-/**
- * @returns number
- */
-test4Length():number {
- var offset = this.bb!.__offset(this.bb_pos, 22);
- return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
-};
-
-/**
- * @param number index
- * @param flatbuffers.Encoding= optionalEncoding
- * @returns string|Uint8Array
- */
-testarrayofstring(index: number):string
-testarrayofstring(index: number,optionalEncoding:flatbuffers.Encoding):string|Uint8Array
-testarrayofstring(index: number,optionalEncoding?:any):string|Uint8Array|null {
- var offset = this.bb!.__offset(this.bb_pos, 24);
- return offset ? this.bb!.__string(this.bb!.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null;
-};
-
-/**
- * @returns number
- */
-testarrayofstringLength():number {
- var offset = this.bb!.__offset(this.bb_pos, 24);
- return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
-};
-
-/**
- * an example documentation comment: this will end up in the generated code
- * multiline too
- *
- * @param number index
- * @param MyGame.Example.Monster= obj
- * @returns MyGame.Example.Monster
- */
-testarrayoftables(index: number, obj?:MyGame.Example.Monster):MyGame.Example.Monster|null {
- var offset = this.bb!.__offset(this.bb_pos, 26);
- return offset ? (obj || new MyGame.Example.Monster()).__init(this.bb!.__indirect(this.bb!.__vector(this.bb_pos + offset) + index * 4), this.bb!) : null;
-};
-
-/**
- * @returns number
- */
-testarrayoftablesLength():number {
- var offset = this.bb!.__offset(this.bb_pos, 26);
- return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
-};
-
-/**
- * @param MyGame.Example.Monster= obj
- * @returns MyGame.Example.Monster|null
- */
-enemy(obj?:MyGame.Example.Monster):MyGame.Example.Monster|null {
- var offset = this.bb!.__offset(this.bb_pos, 28);
- return offset ? (obj || new MyGame.Example.Monster()).__init(this.bb!.__indirect(this.bb_pos + offset), this.bb!) : null;
-};
-
-/**
- * @param number index
- * @returns number
- */
-testnestedflatbuffer(index: number):number|null {
- var offset = this.bb!.__offset(this.bb_pos, 30);
- return offset ? this.bb!.readUint8(this.bb!.__vector(this.bb_pos + offset) + index) : 0;
-};
-
-/**
- * @returns number
- */
-testnestedflatbufferLength():number {
- var offset = this.bb!.__offset(this.bb_pos, 30);
- return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
-};
-
-/**
- * @returns Uint8Array
- */
-testnestedflatbufferArray():Uint8Array|null {
- var offset = this.bb!.__offset(this.bb_pos, 30);
- return offset ? new Uint8Array(this.bb!.bytes().buffer, this.bb!.bytes().byteOffset + this.bb!.__vector(this.bb_pos + offset), this.bb!.__vector_len(this.bb_pos + offset)) : null;
-};
-
-/**
- * @param MyGame.Example.Stat= obj
- * @returns MyGame.Example.Stat|null
- */
-testempty(obj?:MyGame.Example.Stat):MyGame.Example.Stat|null {
- var offset = this.bb!.__offset(this.bb_pos, 32);
- return offset ? (obj || new MyGame.Example.Stat()).__init(this.bb!.__indirect(this.bb_pos + offset), this.bb!) : null;
-};
-
-/**
- * @returns boolean
- */
-testbool():boolean {
- var offset = this.bb!.__offset(this.bb_pos, 34);
- return offset ? !!this.bb!.readInt8(this.bb_pos + offset) : false;
-};
-
-/**
- * @param boolean value
- * @returns boolean
- */
-mutate_testbool(value:boolean):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 34);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb!.writeInt8(this.bb_pos + offset, +value);
- return true;
-};
-
-/**
- * @returns number
- */
-testhashs32Fnv1():number {
- var offset = this.bb!.__offset(this.bb_pos, 36);
- return offset ? this.bb!.readInt32(this.bb_pos + offset) : 0;
-};
-
-/**
- * @param number value
- * @returns boolean
- */
-mutate_testhashs32_fnv1(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 36);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb!.writeInt32(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @returns number
- */
-testhashu32Fnv1():number {
- var offset = this.bb!.__offset(this.bb_pos, 38);
- return offset ? this.bb!.readUint32(this.bb_pos + offset) : 0;
-};
-
-/**
- * @param number value
- * @returns boolean
- */
-mutate_testhashu32_fnv1(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 38);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb!.writeUint32(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @returns flatbuffers.Long
- */
-testhashs64Fnv1():flatbuffers.Long {
- var offset = this.bb!.__offset(this.bb_pos, 40);
- return offset ? this.bb!.readInt64(this.bb_pos + offset) : this.bb!.createLong(0, 0);
-};
-
-/**
- * @param flatbuffers.Long value
- * @returns boolean
- */
-mutate_testhashs64_fnv1(value:flatbuffers.Long):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 40);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb!.writeInt64(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @returns flatbuffers.Long
- */
-testhashu64Fnv1():flatbuffers.Long {
- var offset = this.bb!.__offset(this.bb_pos, 42);
- return offset ? this.bb!.readUint64(this.bb_pos + offset) : this.bb!.createLong(0, 0);
-};
-
-/**
- * @param flatbuffers.Long value
- * @returns boolean
- */
-mutate_testhashu64_fnv1(value:flatbuffers.Long):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 42);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb!.writeUint64(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @returns number
- */
-testhashs32Fnv1a():number {
- var offset = this.bb!.__offset(this.bb_pos, 44);
- return offset ? this.bb!.readInt32(this.bb_pos + offset) : 0;
-};
-
-/**
- * @param number value
- * @returns boolean
- */
-mutate_testhashs32_fnv1a(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 44);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb!.writeInt32(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @returns number
- */
-testhashu32Fnv1a():number {
- var offset = this.bb!.__offset(this.bb_pos, 46);
- return offset ? this.bb!.readUint32(this.bb_pos + offset) : 0;
-};
-
-/**
- * @param number value
- * @returns boolean
- */
-mutate_testhashu32_fnv1a(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 46);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb!.writeUint32(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @returns flatbuffers.Long
- */
-testhashs64Fnv1a():flatbuffers.Long {
- var offset = this.bb!.__offset(this.bb_pos, 48);
- return offset ? this.bb!.readInt64(this.bb_pos + offset) : this.bb!.createLong(0, 0);
-};
-
-/**
- * @param flatbuffers.Long value
- * @returns boolean
- */
-mutate_testhashs64_fnv1a(value:flatbuffers.Long):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 48);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb!.writeInt64(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @returns flatbuffers.Long
- */
-testhashu64Fnv1a():flatbuffers.Long {
- var offset = this.bb!.__offset(this.bb_pos, 50);
- return offset ? this.bb!.readUint64(this.bb_pos + offset) : this.bb!.createLong(0, 0);
-};
-
-/**
- * @param flatbuffers.Long value
- * @returns boolean
- */
-mutate_testhashu64_fnv1a(value:flatbuffers.Long):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 50);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb!.writeUint64(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @param number index
- * @returns boolean
- */
-testarrayofbools(index: number):boolean|null {
- var offset = this.bb!.__offset(this.bb_pos, 52);
- return offset ? !!this.bb!.readInt8(this.bb!.__vector(this.bb_pos + offset) + index) : false;
-};
-
-/**
- * @returns number
- */
-testarrayofboolsLength():number {
- var offset = this.bb!.__offset(this.bb_pos, 52);
- return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
-};
-
-/**
- * @returns Int8Array
- */
-testarrayofboolsArray():Int8Array|null {
- var offset = this.bb!.__offset(this.bb_pos, 52);
- return offset ? new Int8Array(this.bb!.bytes().buffer, this.bb!.bytes().byteOffset + this.bb!.__vector(this.bb_pos + offset), this.bb!.__vector_len(this.bb_pos + offset)) : null;
-};
-
-/**
- * @returns number
- */
-testf():number {
- var offset = this.bb!.__offset(this.bb_pos, 54);
- return offset ? this.bb!.readFloat32(this.bb_pos + offset) : 3.14159;
-};
-
-/**
- * @param number value
- * @returns boolean
- */
-mutate_testf(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 54);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb!.writeFloat32(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @returns number
- */
-testf2():number {
- var offset = this.bb!.__offset(this.bb_pos, 56);
- return offset ? this.bb!.readFloat32(this.bb_pos + offset) : 3.0;
-};
-
-/**
- * @param number value
- * @returns boolean
- */
-mutate_testf2(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 56);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb!.writeFloat32(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @returns number
- */
-testf3():number {
- var offset = this.bb!.__offset(this.bb_pos, 58);
- return offset ? this.bb!.readFloat32(this.bb_pos + offset) : 0.0;
-};
-
-/**
- * @param number value
- * @returns boolean
- */
-mutate_testf3(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 58);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb!.writeFloat32(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @param number index
- * @param flatbuffers.Encoding= optionalEncoding
- * @returns string|Uint8Array
- */
-testarrayofstring2(index: number):string
-testarrayofstring2(index: number,optionalEncoding:flatbuffers.Encoding):string|Uint8Array
-testarrayofstring2(index: number,optionalEncoding?:any):string|Uint8Array|null {
- var offset = this.bb!.__offset(this.bb_pos, 60);
- return offset ? this.bb!.__string(this.bb!.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null;
-};
-
-/**
- * @returns number
- */
-testarrayofstring2Length():number {
- var offset = this.bb!.__offset(this.bb_pos, 60);
- return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
-};
-
-/**
- * @param number index
- * @param MyGame.Example.Ability= obj
- * @returns MyGame.Example.Ability
- */
-testarrayofsortedstruct(index: number, obj?:MyGame.Example.Ability):MyGame.Example.Ability|null {
- var offset = this.bb!.__offset(this.bb_pos, 62);
- return offset ? (obj || new MyGame.Example.Ability()).__init(this.bb!.__vector(this.bb_pos + offset) + index * 8, this.bb!) : null;
-};
-
-/**
- * @returns number
- */
-testarrayofsortedstructLength():number {
- var offset = this.bb!.__offset(this.bb_pos, 62);
- return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
-};
-
-/**
- * @param number index
- * @returns number
- */
-flex(index: number):number|null {
- var offset = this.bb!.__offset(this.bb_pos, 64);
- return offset ? this.bb!.readUint8(this.bb!.__vector(this.bb_pos + offset) + index) : 0;
-};
-
-/**
- * @returns number
- */
-flexLength():number {
- var offset = this.bb!.__offset(this.bb_pos, 64);
- return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
-};
-
-/**
- * @returns Uint8Array
- */
-flexArray():Uint8Array|null {
- var offset = this.bb!.__offset(this.bb_pos, 64);
- return offset ? new Uint8Array(this.bb!.bytes().buffer, this.bb!.bytes().byteOffset + this.bb!.__vector(this.bb_pos + offset), this.bb!.__vector_len(this.bb_pos + offset)) : null;
-};
-
-/**
- * @param number index
- * @param MyGame.Example.Test= obj
- * @returns MyGame.Example.Test
- */
-test5(index: number, obj?:MyGame.Example.Test):MyGame.Example.Test|null {
- var offset = this.bb!.__offset(this.bb_pos, 66);
- return offset ? (obj || new MyGame.Example.Test()).__init(this.bb!.__vector(this.bb_pos + offset) + index * 4, this.bb!) : null;
-};
-
-/**
- * @returns number
- */
-test5Length():number {
- var offset = this.bb!.__offset(this.bb_pos, 66);
- return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
-};
-
-/**
- * @param number index
- * @returns flatbuffers.Long
- */
-vectorOfLongs(index: number):flatbuffers.Long|null {
- var offset = this.bb!.__offset(this.bb_pos, 68);
- return offset ? this.bb!.readInt64(this.bb!.__vector(this.bb_pos + offset) + index * 8) : this.bb!.createLong(0, 0);
-};
-
-/**
- * @returns number
- */
-vectorOfLongsLength():number {
- var offset = this.bb!.__offset(this.bb_pos, 68);
- return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
-};
-
-/**
- * @param number index
- * @returns number
- */
-vectorOfDoubles(index: number):number|null {
- var offset = this.bb!.__offset(this.bb_pos, 70);
- return offset ? this.bb!.readFloat64(this.bb!.__vector(this.bb_pos + offset) + index * 8) : 0;
-};
-
-/**
- * @returns number
- */
-vectorOfDoublesLength():number {
- var offset = this.bb!.__offset(this.bb_pos, 70);
- return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
-};
-
-/**
- * @returns Float64Array
- */
-vectorOfDoublesArray():Float64Array|null {
- var offset = this.bb!.__offset(this.bb_pos, 70);
- return offset ? new Float64Array(this.bb!.bytes().buffer, this.bb!.bytes().byteOffset + this.bb!.__vector(this.bb_pos + offset), this.bb!.__vector_len(this.bb_pos + offset)) : null;
-};
-
-/**
- * @param MyGame.InParentNamespace= obj
- * @returns MyGame.InParentNamespace|null
- */
-parentNamespaceTest(obj?:MyGame.InParentNamespace):MyGame.InParentNamespace|null {
- var offset = this.bb!.__offset(this.bb_pos, 72);
- return offset ? (obj || new MyGame.InParentNamespace()).__init(this.bb!.__indirect(this.bb_pos + offset), this.bb!) : null;
-};
-
-/**
- * @param number index
- * @param MyGame.Example.Referrable= obj
- * @returns MyGame.Example.Referrable
- */
-vectorOfReferrables(index: number, obj?:MyGame.Example.Referrable):MyGame.Example.Referrable|null {
- var offset = this.bb!.__offset(this.bb_pos, 74);
- return offset ? (obj || new MyGame.Example.Referrable()).__init(this.bb!.__indirect(this.bb!.__vector(this.bb_pos + offset) + index * 4), this.bb!) : null;
-};
-
-/**
- * @returns number
- */
-vectorOfReferrablesLength():number {
- var offset = this.bb!.__offset(this.bb_pos, 74);
- return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
-};
-
-/**
- * @returns flatbuffers.Long
- */
-singleWeakReference():flatbuffers.Long {
- var offset = this.bb!.__offset(this.bb_pos, 76);
- return offset ? this.bb!.readUint64(this.bb_pos + offset) : this.bb!.createLong(0, 0);
-};
-
-/**
- * @param flatbuffers.Long value
- * @returns boolean
- */
-mutate_single_weak_reference(value:flatbuffers.Long):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 76);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb!.writeUint64(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @param number index
- * @returns flatbuffers.Long
- */
-vectorOfWeakReferences(index: number):flatbuffers.Long|null {
- var offset = this.bb!.__offset(this.bb_pos, 78);
- return offset ? this.bb!.readUint64(this.bb!.__vector(this.bb_pos + offset) + index * 8) : this.bb!.createLong(0, 0);
-};
-
-/**
- * @returns number
- */
-vectorOfWeakReferencesLength():number {
- var offset = this.bb!.__offset(this.bb_pos, 78);
- return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
-};
-
-/**
- * @param number index
- * @param MyGame.Example.Referrable= obj
- * @returns MyGame.Example.Referrable
- */
-vectorOfStrongReferrables(index: number, obj?:MyGame.Example.Referrable):MyGame.Example.Referrable|null {
- var offset = this.bb!.__offset(this.bb_pos, 80);
- return offset ? (obj || new MyGame.Example.Referrable()).__init(this.bb!.__indirect(this.bb!.__vector(this.bb_pos + offset) + index * 4), this.bb!) : null;
-};
-
-/**
- * @returns number
- */
-vectorOfStrongReferrablesLength():number {
- var offset = this.bb!.__offset(this.bb_pos, 80);
- return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
-};
-
-/**
- * @returns flatbuffers.Long
- */
-coOwningReference():flatbuffers.Long {
- var offset = this.bb!.__offset(this.bb_pos, 82);
- return offset ? this.bb!.readUint64(this.bb_pos + offset) : this.bb!.createLong(0, 0);
-};
-
-/**
- * @param flatbuffers.Long value
- * @returns boolean
- */
-mutate_co_owning_reference(value:flatbuffers.Long):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 82);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb!.writeUint64(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @param number index
- * @returns flatbuffers.Long
- */
-vectorOfCoOwningReferences(index: number):flatbuffers.Long|null {
- var offset = this.bb!.__offset(this.bb_pos, 84);
- return offset ? this.bb!.readUint64(this.bb!.__vector(this.bb_pos + offset) + index * 8) : this.bb!.createLong(0, 0);
-};
-
-/**
- * @returns number
- */
-vectorOfCoOwningReferencesLength():number {
- var offset = this.bb!.__offset(this.bb_pos, 84);
- return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
-};
-
-/**
- * @returns flatbuffers.Long
- */
-nonOwningReference():flatbuffers.Long {
- var offset = this.bb!.__offset(this.bb_pos, 86);
- return offset ? this.bb!.readUint64(this.bb_pos + offset) : this.bb!.createLong(0, 0);
-};
-
-/**
- * @param flatbuffers.Long value
- * @returns boolean
- */
-mutate_non_owning_reference(value:flatbuffers.Long):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 86);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb!.writeUint64(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @param number index
- * @returns flatbuffers.Long
- */
-vectorOfNonOwningReferences(index: number):flatbuffers.Long|null {
- var offset = this.bb!.__offset(this.bb_pos, 88);
- return offset ? this.bb!.readUint64(this.bb!.__vector(this.bb_pos + offset) + index * 8) : this.bb!.createLong(0, 0);
-};
-
-/**
- * @returns number
- */
-vectorOfNonOwningReferencesLength():number {
- var offset = this.bb!.__offset(this.bb_pos, 88);
- return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
-};
-
-/**
- * @returns MyGame.Example.AnyUniqueAliases
- */
-anyUniqueType():MyGame.Example.AnyUniqueAliases {
- var offset = this.bb!.__offset(this.bb_pos, 90);
- return offset ? /** */ (this.bb!.readUint8(this.bb_pos + offset)) : MyGame.Example.AnyUniqueAliases.NONE;
-};
-
-/**
- * @param flatbuffers.Table obj
- * @returns ?flatbuffers.Table
- */
-anyUnique<T extends flatbuffers.Table>(obj:T):T|null {
- var offset = this.bb!.__offset(this.bb_pos, 92);
- return offset ? this.bb!.__union(obj, this.bb_pos + offset) : null;
-};
-
-/**
- * @returns MyGame.Example.AnyAmbiguousAliases
- */
-anyAmbiguousType():MyGame.Example.AnyAmbiguousAliases {
- var offset = this.bb!.__offset(this.bb_pos, 94);
- return offset ? /** */ (this.bb!.readUint8(this.bb_pos + offset)) : MyGame.Example.AnyAmbiguousAliases.NONE;
-};
-
-/**
- * @param flatbuffers.Table obj
- * @returns ?flatbuffers.Table
- */
-anyAmbiguous<T extends flatbuffers.Table>(obj:T):T|null {
- var offset = this.bb!.__offset(this.bb_pos, 96);
- return offset ? this.bb!.__union(obj, this.bb_pos + offset) : null;
-};
-
-/**
- * @param number index
- * @returns MyGame.Example.Color
- */
-vectorOfEnums(index: number):MyGame.Example.Color|null {
- var offset = this.bb!.__offset(this.bb_pos, 98);
- return offset ? /** */ (this.bb!.readUint8(this.bb!.__vector(this.bb_pos + offset) + index)) : /** */ (0);
-};
-
-/**
- * @returns number
- */
-vectorOfEnumsLength():number {
- var offset = this.bb!.__offset(this.bb_pos, 98);
- return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
-};
-
-/**
- * @returns Uint8Array
- */
-vectorOfEnumsArray():Uint8Array|null {
- var offset = this.bb!.__offset(this.bb_pos, 98);
- return offset ? new Uint8Array(this.bb!.bytes().buffer, this.bb!.bytes().byteOffset + this.bb!.__vector(this.bb_pos + offset), this.bb!.__vector_len(this.bb_pos + offset)) : null;
-};
-
-/**
- * @returns MyGame.Example.Race
- */
-signedEnum():MyGame.Example.Race {
- var offset = this.bb!.__offset(this.bb_pos, 100);
- return offset ? /** */ (this.bb!.readInt8(this.bb_pos + offset)) : MyGame.Example.Race.None;
-};
-
-/**
- * @param MyGame.Example.Race value
- * @returns boolean
- */
-mutate_signed_enum(value:MyGame.Example.Race):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 100);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb!.writeInt8(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @param number index
- * @returns number
- */
-testrequirednestedflatbuffer(index: number):number|null {
- var offset = this.bb!.__offset(this.bb_pos, 102);
- return offset ? this.bb!.readUint8(this.bb!.__vector(this.bb_pos + offset) + index) : 0;
-};
-
-/**
- * @returns number
- */
-testrequirednestedflatbufferLength():number {
- var offset = this.bb!.__offset(this.bb_pos, 102);
- return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
-};
-
-/**
- * @returns Uint8Array
- */
-testrequirednestedflatbufferArray():Uint8Array|null {
- var offset = this.bb!.__offset(this.bb_pos, 102);
- return offset ? new Uint8Array(this.bb!.bytes().buffer, this.bb!.bytes().byteOffset + this.bb!.__vector(this.bb_pos + offset), this.bb!.__vector_len(this.bb_pos + offset)) : null;
-};
-
-/**
- * @param flatbuffers.Builder builder
- */
-static startMonster(builder:flatbuffers.Builder) {
- builder.startObject(50);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Offset posOffset
- */
-static addPos(builder:flatbuffers.Builder, posOffset:flatbuffers.Offset) {
- builder.addFieldStruct(0, posOffset, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number mana
- */
-static addMana(builder:flatbuffers.Builder, mana:number) {
- builder.addFieldInt16(1, mana, 150);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number hp
- */
-static addHp(builder:flatbuffers.Builder, hp:number) {
- builder.addFieldInt16(2, hp, 100);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Offset nameOffset
- */
-static addName(builder:flatbuffers.Builder, nameOffset:flatbuffers.Offset) {
- builder.addFieldOffset(3, nameOffset, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Offset inventoryOffset
- */
-static addInventory(builder:flatbuffers.Builder, inventoryOffset:flatbuffers.Offset) {
- builder.addFieldOffset(5, inventoryOffset, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param Array.<number> data
- * @returns flatbuffers.Offset
- */
-static createInventoryVector(builder:flatbuffers.Builder, data:number[]|Uint8Array):flatbuffers.Offset {
- builder.startVector(1, data.length, 1);
- for (var i = data.length - 1; i >= 0; i--) {
- builder.addInt8(data[i]);
- }
- return builder.endVector();
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number numElems
- */
-static startInventoryVector(builder:flatbuffers.Builder, numElems:number) {
- builder.startVector(1, numElems, 1);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param MyGame.Example.Color color
- */
-static addColor(builder:flatbuffers.Builder, color:MyGame.Example.Color) {
- builder.addFieldInt8(6, color, MyGame.Example.Color.Blue);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param MyGame.Example.Any testType
- */
-static addTestType(builder:flatbuffers.Builder, testType:MyGame.Example.Any) {
- builder.addFieldInt8(7, testType, MyGame.Example.Any.NONE);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Offset testOffset
- */
-static addTest(builder:flatbuffers.Builder, testOffset:flatbuffers.Offset) {
- builder.addFieldOffset(8, testOffset, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Offset test4Offset
- */
-static addTest4(builder:flatbuffers.Builder, test4Offset:flatbuffers.Offset) {
- builder.addFieldOffset(9, test4Offset, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number numElems
- */
-static startTest4Vector(builder:flatbuffers.Builder, numElems:number) {
- builder.startVector(4, numElems, 2);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Offset testarrayofstringOffset
- */
-static addTestarrayofstring(builder:flatbuffers.Builder, testarrayofstringOffset:flatbuffers.Offset) {
- builder.addFieldOffset(10, testarrayofstringOffset, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param Array.<flatbuffers.Offset> data
- * @returns flatbuffers.Offset
- */
-static createTestarrayofstringVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset {
- builder.startVector(4, data.length, 4);
- for (var i = data.length - 1; i >= 0; i--) {
- builder.addOffset(data[i]);
- }
- return builder.endVector();
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number numElems
- */
-static startTestarrayofstringVector(builder:flatbuffers.Builder, numElems:number) {
- builder.startVector(4, numElems, 4);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Offset testarrayoftablesOffset
- */
-static addTestarrayoftables(builder:flatbuffers.Builder, testarrayoftablesOffset:flatbuffers.Offset) {
- builder.addFieldOffset(11, testarrayoftablesOffset, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param Array.<flatbuffers.Offset> data
- * @returns flatbuffers.Offset
- */
-static createTestarrayoftablesVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset {
- builder.startVector(4, data.length, 4);
- for (var i = data.length - 1; i >= 0; i--) {
- builder.addOffset(data[i]);
- }
- return builder.endVector();
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number numElems
- */
-static startTestarrayoftablesVector(builder:flatbuffers.Builder, numElems:number) {
- builder.startVector(4, numElems, 4);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Offset enemyOffset
- */
-static addEnemy(builder:flatbuffers.Builder, enemyOffset:flatbuffers.Offset) {
- builder.addFieldOffset(12, enemyOffset, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Offset testnestedflatbufferOffset
- */
-static addTestnestedflatbuffer(builder:flatbuffers.Builder, testnestedflatbufferOffset:flatbuffers.Offset) {
- builder.addFieldOffset(13, testnestedflatbufferOffset, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param Array.<number> data
- * @returns flatbuffers.Offset
- */
-static createTestnestedflatbufferVector(builder:flatbuffers.Builder, data:number[]|Uint8Array):flatbuffers.Offset {
- builder.startVector(1, data.length, 1);
- for (var i = data.length - 1; i >= 0; i--) {
- builder.addInt8(data[i]);
- }
- return builder.endVector();
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number numElems
- */
-static startTestnestedflatbufferVector(builder:flatbuffers.Builder, numElems:number) {
- builder.startVector(1, numElems, 1);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Offset testemptyOffset
- */
-static addTestempty(builder:flatbuffers.Builder, testemptyOffset:flatbuffers.Offset) {
- builder.addFieldOffset(14, testemptyOffset, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param boolean testbool
- */
-static addTestbool(builder:flatbuffers.Builder, testbool:boolean) {
- builder.addFieldInt8(15, +testbool, +false);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number testhashs32Fnv1
- */
-static addTesthashs32Fnv1(builder:flatbuffers.Builder, testhashs32Fnv1:number) {
- builder.addFieldInt32(16, testhashs32Fnv1, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number testhashu32Fnv1
- */
-static addTesthashu32Fnv1(builder:flatbuffers.Builder, testhashu32Fnv1:number) {
- builder.addFieldInt32(17, testhashu32Fnv1, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Long testhashs64Fnv1
- */
-static addTesthashs64Fnv1(builder:flatbuffers.Builder, testhashs64Fnv1:flatbuffers.Long) {
- builder.addFieldInt64(18, testhashs64Fnv1, builder.createLong(0, 0));
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Long testhashu64Fnv1
- */
-static addTesthashu64Fnv1(builder:flatbuffers.Builder, testhashu64Fnv1:flatbuffers.Long) {
- builder.addFieldInt64(19, testhashu64Fnv1, builder.createLong(0, 0));
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number testhashs32Fnv1a
- */
-static addTesthashs32Fnv1a(builder:flatbuffers.Builder, testhashs32Fnv1a:number) {
- builder.addFieldInt32(20, testhashs32Fnv1a, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number testhashu32Fnv1a
- */
-static addTesthashu32Fnv1a(builder:flatbuffers.Builder, testhashu32Fnv1a:number) {
- builder.addFieldInt32(21, testhashu32Fnv1a, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Long testhashs64Fnv1a
- */
-static addTesthashs64Fnv1a(builder:flatbuffers.Builder, testhashs64Fnv1a:flatbuffers.Long) {
- builder.addFieldInt64(22, testhashs64Fnv1a, builder.createLong(0, 0));
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Long testhashu64Fnv1a
- */
-static addTesthashu64Fnv1a(builder:flatbuffers.Builder, testhashu64Fnv1a:flatbuffers.Long) {
- builder.addFieldInt64(23, testhashu64Fnv1a, builder.createLong(0, 0));
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Offset testarrayofboolsOffset
- */
-static addTestarrayofbools(builder:flatbuffers.Builder, testarrayofboolsOffset:flatbuffers.Offset) {
- builder.addFieldOffset(24, testarrayofboolsOffset, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param Array.<boolean> data
- * @returns flatbuffers.Offset
- */
-static createTestarrayofboolsVector(builder:flatbuffers.Builder, data:boolean[]):flatbuffers.Offset {
- builder.startVector(1, data.length, 1);
- for (var i = data.length - 1; i >= 0; i--) {
- builder.addInt8(+data[i]);
- }
- return builder.endVector();
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number numElems
- */
-static startTestarrayofboolsVector(builder:flatbuffers.Builder, numElems:number) {
- builder.startVector(1, numElems, 1);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number testf
- */
-static addTestf(builder:flatbuffers.Builder, testf:number) {
- builder.addFieldFloat32(25, testf, 3.14159);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number testf2
- */
-static addTestf2(builder:flatbuffers.Builder, testf2:number) {
- builder.addFieldFloat32(26, testf2, 3.0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number testf3
- */
-static addTestf3(builder:flatbuffers.Builder, testf3:number) {
- builder.addFieldFloat32(27, testf3, 0.0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Offset testarrayofstring2Offset
- */
-static addTestarrayofstring2(builder:flatbuffers.Builder, testarrayofstring2Offset:flatbuffers.Offset) {
- builder.addFieldOffset(28, testarrayofstring2Offset, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param Array.<flatbuffers.Offset> data
- * @returns flatbuffers.Offset
- */
-static createTestarrayofstring2Vector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset {
- builder.startVector(4, data.length, 4);
- for (var i = data.length - 1; i >= 0; i--) {
- builder.addOffset(data[i]);
- }
- return builder.endVector();
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number numElems
- */
-static startTestarrayofstring2Vector(builder:flatbuffers.Builder, numElems:number) {
- builder.startVector(4, numElems, 4);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Offset testarrayofsortedstructOffset
- */
-static addTestarrayofsortedstruct(builder:flatbuffers.Builder, testarrayofsortedstructOffset:flatbuffers.Offset) {
- builder.addFieldOffset(29, testarrayofsortedstructOffset, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number numElems
- */
-static startTestarrayofsortedstructVector(builder:flatbuffers.Builder, numElems:number) {
- builder.startVector(8, numElems, 4);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Offset flexOffset
- */
-static addFlex(builder:flatbuffers.Builder, flexOffset:flatbuffers.Offset) {
- builder.addFieldOffset(30, flexOffset, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param Array.<number> data
- * @returns flatbuffers.Offset
- */
-static createFlexVector(builder:flatbuffers.Builder, data:number[]|Uint8Array):flatbuffers.Offset {
- builder.startVector(1, data.length, 1);
- for (var i = data.length - 1; i >= 0; i--) {
- builder.addInt8(data[i]);
- }
- return builder.endVector();
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number numElems
- */
-static startFlexVector(builder:flatbuffers.Builder, numElems:number) {
- builder.startVector(1, numElems, 1);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Offset test5Offset
- */
-static addTest5(builder:flatbuffers.Builder, test5Offset:flatbuffers.Offset) {
- builder.addFieldOffset(31, test5Offset, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number numElems
- */
-static startTest5Vector(builder:flatbuffers.Builder, numElems:number) {
- builder.startVector(4, numElems, 2);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Offset vectorOfLongsOffset
- */
-static addVectorOfLongs(builder:flatbuffers.Builder, vectorOfLongsOffset:flatbuffers.Offset) {
- builder.addFieldOffset(32, vectorOfLongsOffset, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param Array.<flatbuffers.Long> data
- * @returns flatbuffers.Offset
- */
-static createVectorOfLongsVector(builder:flatbuffers.Builder, data:flatbuffers.Long[]):flatbuffers.Offset {
- builder.startVector(8, data.length, 8);
- for (var i = data.length - 1; i >= 0; i--) {
- builder.addInt64(data[i]);
- }
- return builder.endVector();
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number numElems
- */
-static startVectorOfLongsVector(builder:flatbuffers.Builder, numElems:number) {
- builder.startVector(8, numElems, 8);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Offset vectorOfDoublesOffset
- */
-static addVectorOfDoubles(builder:flatbuffers.Builder, vectorOfDoublesOffset:flatbuffers.Offset) {
- builder.addFieldOffset(33, vectorOfDoublesOffset, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param Array.<number> data
- * @returns flatbuffers.Offset
- */
-static createVectorOfDoublesVector(builder:flatbuffers.Builder, data:number[]|Float64Array):flatbuffers.Offset;
-/**
- * @deprecated This Uint8Array overload will be removed in the future.
- */
-static createVectorOfDoublesVector(builder:flatbuffers.Builder, data:number[]|Uint8Array):flatbuffers.Offset;
-static createVectorOfDoublesVector(builder:flatbuffers.Builder, data:number[]|Float64Array|Uint8Array):flatbuffers.Offset {
- builder.startVector(8, data.length, 8);
- for (var i = data.length - 1; i >= 0; i--) {
- builder.addFloat64(data[i]);
- }
- return builder.endVector();
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number numElems
- */
-static startVectorOfDoublesVector(builder:flatbuffers.Builder, numElems:number) {
- builder.startVector(8, numElems, 8);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Offset parentNamespaceTestOffset
- */
-static addParentNamespaceTest(builder:flatbuffers.Builder, parentNamespaceTestOffset:flatbuffers.Offset) {
- builder.addFieldOffset(34, parentNamespaceTestOffset, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Offset vectorOfReferrablesOffset
- */
-static addVectorOfReferrables(builder:flatbuffers.Builder, vectorOfReferrablesOffset:flatbuffers.Offset) {
- builder.addFieldOffset(35, vectorOfReferrablesOffset, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param Array.<flatbuffers.Offset> data
- * @returns flatbuffers.Offset
- */
-static createVectorOfReferrablesVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset {
- builder.startVector(4, data.length, 4);
- for (var i = data.length - 1; i >= 0; i--) {
- builder.addOffset(data[i]);
- }
- return builder.endVector();
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number numElems
- */
-static startVectorOfReferrablesVector(builder:flatbuffers.Builder, numElems:number) {
- builder.startVector(4, numElems, 4);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Long singleWeakReference
- */
-static addSingleWeakReference(builder:flatbuffers.Builder, singleWeakReference:flatbuffers.Long) {
- builder.addFieldInt64(36, singleWeakReference, builder.createLong(0, 0));
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Offset vectorOfWeakReferencesOffset
- */
-static addVectorOfWeakReferences(builder:flatbuffers.Builder, vectorOfWeakReferencesOffset:flatbuffers.Offset) {
- builder.addFieldOffset(37, vectorOfWeakReferencesOffset, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param Array.<flatbuffers.Long> data
- * @returns flatbuffers.Offset
- */
-static createVectorOfWeakReferencesVector(builder:flatbuffers.Builder, data:flatbuffers.Long[]):flatbuffers.Offset {
- builder.startVector(8, data.length, 8);
- for (var i = data.length - 1; i >= 0; i--) {
- builder.addInt64(data[i]);
- }
- return builder.endVector();
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number numElems
- */
-static startVectorOfWeakReferencesVector(builder:flatbuffers.Builder, numElems:number) {
- builder.startVector(8, numElems, 8);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Offset vectorOfStrongReferrablesOffset
- */
-static addVectorOfStrongReferrables(builder:flatbuffers.Builder, vectorOfStrongReferrablesOffset:flatbuffers.Offset) {
- builder.addFieldOffset(38, vectorOfStrongReferrablesOffset, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param Array.<flatbuffers.Offset> data
- * @returns flatbuffers.Offset
- */
-static createVectorOfStrongReferrablesVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset {
- builder.startVector(4, data.length, 4);
- for (var i = data.length - 1; i >= 0; i--) {
- builder.addOffset(data[i]);
- }
- return builder.endVector();
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number numElems
- */
-static startVectorOfStrongReferrablesVector(builder:flatbuffers.Builder, numElems:number) {
- builder.startVector(4, numElems, 4);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Long coOwningReference
- */
-static addCoOwningReference(builder:flatbuffers.Builder, coOwningReference:flatbuffers.Long) {
- builder.addFieldInt64(39, coOwningReference, builder.createLong(0, 0));
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Offset vectorOfCoOwningReferencesOffset
- */
-static addVectorOfCoOwningReferences(builder:flatbuffers.Builder, vectorOfCoOwningReferencesOffset:flatbuffers.Offset) {
- builder.addFieldOffset(40, vectorOfCoOwningReferencesOffset, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param Array.<flatbuffers.Long> data
- * @returns flatbuffers.Offset
- */
-static createVectorOfCoOwningReferencesVector(builder:flatbuffers.Builder, data:flatbuffers.Long[]):flatbuffers.Offset {
- builder.startVector(8, data.length, 8);
- for (var i = data.length - 1; i >= 0; i--) {
- builder.addInt64(data[i]);
- }
- return builder.endVector();
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number numElems
- */
-static startVectorOfCoOwningReferencesVector(builder:flatbuffers.Builder, numElems:number) {
- builder.startVector(8, numElems, 8);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Long nonOwningReference
- */
-static addNonOwningReference(builder:flatbuffers.Builder, nonOwningReference:flatbuffers.Long) {
- builder.addFieldInt64(41, nonOwningReference, builder.createLong(0, 0));
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Offset vectorOfNonOwningReferencesOffset
- */
-static addVectorOfNonOwningReferences(builder:flatbuffers.Builder, vectorOfNonOwningReferencesOffset:flatbuffers.Offset) {
- builder.addFieldOffset(42, vectorOfNonOwningReferencesOffset, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param Array.<flatbuffers.Long> data
- * @returns flatbuffers.Offset
- */
-static createVectorOfNonOwningReferencesVector(builder:flatbuffers.Builder, data:flatbuffers.Long[]):flatbuffers.Offset {
- builder.startVector(8, data.length, 8);
- for (var i = data.length - 1; i >= 0; i--) {
- builder.addInt64(data[i]);
- }
- return builder.endVector();
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number numElems
- */
-static startVectorOfNonOwningReferencesVector(builder:flatbuffers.Builder, numElems:number) {
- builder.startVector(8, numElems, 8);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param MyGame.Example.AnyUniqueAliases anyUniqueType
- */
-static addAnyUniqueType(builder:flatbuffers.Builder, anyUniqueType:MyGame.Example.AnyUniqueAliases) {
- builder.addFieldInt8(43, anyUniqueType, MyGame.Example.AnyUniqueAliases.NONE);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Offset anyUniqueOffset
- */
-static addAnyUnique(builder:flatbuffers.Builder, anyUniqueOffset:flatbuffers.Offset) {
- builder.addFieldOffset(44, anyUniqueOffset, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param MyGame.Example.AnyAmbiguousAliases anyAmbiguousType
- */
-static addAnyAmbiguousType(builder:flatbuffers.Builder, anyAmbiguousType:MyGame.Example.AnyAmbiguousAliases) {
- builder.addFieldInt8(45, anyAmbiguousType, MyGame.Example.AnyAmbiguousAliases.NONE);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Offset anyAmbiguousOffset
- */
-static addAnyAmbiguous(builder:flatbuffers.Builder, anyAmbiguousOffset:flatbuffers.Offset) {
- builder.addFieldOffset(46, anyAmbiguousOffset, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Offset vectorOfEnumsOffset
- */
-static addVectorOfEnums(builder:flatbuffers.Builder, vectorOfEnumsOffset:flatbuffers.Offset) {
- builder.addFieldOffset(47, vectorOfEnumsOffset, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param Array.<MyGame.Example.Color> data
- * @returns flatbuffers.Offset
- */
-static createVectorOfEnumsVector(builder:flatbuffers.Builder, data:MyGame.Example.Color[]):flatbuffers.Offset {
- builder.startVector(1, data.length, 1);
- for (var i = data.length - 1; i >= 0; i--) {
- builder.addInt8(data[i]);
- }
- return builder.endVector();
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number numElems
- */
-static startVectorOfEnumsVector(builder:flatbuffers.Builder, numElems:number) {
- builder.startVector(1, numElems, 1);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param MyGame.Example.Race signedEnum
- */
-static addSignedEnum(builder:flatbuffers.Builder, signedEnum:MyGame.Example.Race) {
- builder.addFieldInt8(48, signedEnum, MyGame.Example.Race.None);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Offset testrequirednestedflatbufferOffset
- */
-static addTestrequirednestedflatbuffer(builder:flatbuffers.Builder, testrequirednestedflatbufferOffset:flatbuffers.Offset) {
- builder.addFieldOffset(49, testrequirednestedflatbufferOffset, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param Array.<number> data
- * @returns flatbuffers.Offset
- */
-static createTestrequirednestedflatbufferVector(builder:flatbuffers.Builder, data:number[]|Uint8Array):flatbuffers.Offset {
- builder.startVector(1, data.length, 1);
- for (var i = data.length - 1; i >= 0; i--) {
- builder.addInt8(data[i]);
- }
- return builder.endVector();
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number numElems
- */
-static startTestrequirednestedflatbufferVector(builder:flatbuffers.Builder, numElems:number) {
- builder.startVector(1, numElems, 1);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @returns flatbuffers.Offset
- */
-static endMonster(builder:flatbuffers.Builder):flatbuffers.Offset {
- var offset = builder.endObject();
- builder.requiredField(offset, 10); // name
- return offset;
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Offset offset
- */
-static finishMonsterBuffer(builder:flatbuffers.Builder, offset:flatbuffers.Offset) {
- builder.finish(offset, 'MONS');
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Offset offset
- */
-static finishSizePrefixedMonsterBuffer(builder:flatbuffers.Builder, offset:flatbuffers.Offset) {
- builder.finish(offset, 'MONS', true);
-};
-
-
-serialize():Uint8Array {
- return this.bb!.bytes();
-}
-
-static deserialize(buffer: Uint8Array):Monster {
- return Monster.getRootAsMonster(new flatbuffers.ByteBuffer(buffer))
-}
-
-/**
- * @returns MonsterT
- */
-unpack(): MonsterT {
- return new MonsterT(
- (this.pos() !== null ? this.pos()!.unpack() : null),
- this.mana(),
- this.hp(),
- this.name(),
- this.bb!.createScalarList(this.inventory.bind(this), this.inventoryLength()),
- this.color(),
- this.testType(),
- (() => {
- let temp = MyGame.Example.unionToAny(this.testType(), this.test.bind(this));
- if(temp === null) { return null; }
- return temp.unpack()
- })(),
- this.bb!.createObjList(this.test4.bind(this), this.test4Length()),
- this.bb!.createStringList(this.testarrayofstring.bind(this), this.testarrayofstringLength()),
- this.bb!.createObjList(this.testarrayoftables.bind(this), this.testarrayoftablesLength()),
- (this.enemy() !== null ? this.enemy()!.unpack() : null),
- this.bb!.createScalarList(this.testnestedflatbuffer.bind(this), this.testnestedflatbufferLength()),
- (this.testempty() !== null ? this.testempty()!.unpack() : null),
- this.testbool(),
- this.testhashs32Fnv1(),
- this.testhashu32Fnv1(),
- this.testhashs64Fnv1(),
- this.testhashu64Fnv1(),
- this.testhashs32Fnv1a(),
- this.testhashu32Fnv1a(),
- this.testhashs64Fnv1a(),
- this.testhashu64Fnv1a(),
- this.bb!.createScalarList(this.testarrayofbools.bind(this), this.testarrayofboolsLength()),
- this.testf(),
- this.testf2(),
- this.testf3(),
- this.bb!.createStringList(this.testarrayofstring2.bind(this), this.testarrayofstring2Length()),
- this.bb!.createObjList(this.testarrayofsortedstruct.bind(this), this.testarrayofsortedstructLength()),
- this.bb!.createScalarList(this.flex.bind(this), this.flexLength()),
- this.bb!.createObjList(this.test5.bind(this), this.test5Length()),
- this.bb!.createScalarList(this.vectorOfLongs.bind(this), this.vectorOfLongsLength()),
- this.bb!.createScalarList(this.vectorOfDoubles.bind(this), this.vectorOfDoublesLength()),
- (this.parentNamespaceTest() !== null ? this.parentNamespaceTest()!.unpack() : null),
- this.bb!.createObjList(this.vectorOfReferrables.bind(this), this.vectorOfReferrablesLength()),
- this.singleWeakReference(),
- this.bb!.createScalarList(this.vectorOfWeakReferences.bind(this), this.vectorOfWeakReferencesLength()),
- this.bb!.createObjList(this.vectorOfStrongReferrables.bind(this), this.vectorOfStrongReferrablesLength()),
- this.coOwningReference(),
- this.bb!.createScalarList(this.vectorOfCoOwningReferences.bind(this), this.vectorOfCoOwningReferencesLength()),
- this.nonOwningReference(),
- this.bb!.createScalarList(this.vectorOfNonOwningReferences.bind(this), this.vectorOfNonOwningReferencesLength()),
- this.anyUniqueType(),
- (() => {
- let temp = MyGame.Example.unionToAnyUniqueAliases(this.anyUniqueType(), this.anyUnique.bind(this));
- if(temp === null) { return null; }
- return temp.unpack()
- })(),
- this.anyAmbiguousType(),
- (() => {
- let temp = MyGame.Example.unionToAnyAmbiguousAliases(this.anyAmbiguousType(), this.anyAmbiguous.bind(this));
- if(temp === null) { return null; }
- return temp.unpack()
- })(),
- this.bb!.createScalarList(this.vectorOfEnums.bind(this), this.vectorOfEnumsLength()),
- this.signedEnum(),
- this.bb!.createScalarList(this.testrequirednestedflatbuffer.bind(this), this.testrequirednestedflatbufferLength())
- );
-};
-
-/**
- * @param MonsterT _o
- */
-unpackTo(_o: MonsterT): void {
- _o.pos = (this.pos() !== null ? this.pos()!.unpack() : null);
- _o.mana = this.mana();
- _o.hp = this.hp();
- _o.name = this.name();
- _o.inventory = this.bb!.createScalarList(this.inventory.bind(this), this.inventoryLength());
- _o.color = this.color();
- _o.testType = this.testType();
- _o.test = (() => {
- let temp = MyGame.Example.unionToAny(this.testType(), this.test.bind(this));
- if(temp === null) { return null; }
- return temp.unpack()
- })();
- _o.test4 = this.bb!.createObjList(this.test4.bind(this), this.test4Length());
- _o.testarrayofstring = this.bb!.createStringList(this.testarrayofstring.bind(this), this.testarrayofstringLength());
- _o.testarrayoftables = this.bb!.createObjList(this.testarrayoftables.bind(this), this.testarrayoftablesLength());
- _o.enemy = (this.enemy() !== null ? this.enemy()!.unpack() : null);
- _o.testnestedflatbuffer = this.bb!.createScalarList(this.testnestedflatbuffer.bind(this), this.testnestedflatbufferLength());
- _o.testempty = (this.testempty() !== null ? this.testempty()!.unpack() : null);
- _o.testbool = this.testbool();
- _o.testhashs32Fnv1 = this.testhashs32Fnv1();
- _o.testhashu32Fnv1 = this.testhashu32Fnv1();
- _o.testhashs64Fnv1 = this.testhashs64Fnv1();
- _o.testhashu64Fnv1 = this.testhashu64Fnv1();
- _o.testhashs32Fnv1a = this.testhashs32Fnv1a();
- _o.testhashu32Fnv1a = this.testhashu32Fnv1a();
- _o.testhashs64Fnv1a = this.testhashs64Fnv1a();
- _o.testhashu64Fnv1a = this.testhashu64Fnv1a();
- _o.testarrayofbools = this.bb!.createScalarList(this.testarrayofbools.bind(this), this.testarrayofboolsLength());
- _o.testf = this.testf();
- _o.testf2 = this.testf2();
- _o.testf3 = this.testf3();
- _o.testarrayofstring2 = this.bb!.createStringList(this.testarrayofstring2.bind(this), this.testarrayofstring2Length());
- _o.testarrayofsortedstruct = this.bb!.createObjList(this.testarrayofsortedstruct.bind(this), this.testarrayofsortedstructLength());
- _o.flex = this.bb!.createScalarList(this.flex.bind(this), this.flexLength());
- _o.test5 = this.bb!.createObjList(this.test5.bind(this), this.test5Length());
- _o.vectorOfLongs = this.bb!.createScalarList(this.vectorOfLongs.bind(this), this.vectorOfLongsLength());
- _o.vectorOfDoubles = this.bb!.createScalarList(this.vectorOfDoubles.bind(this), this.vectorOfDoublesLength());
- _o.parentNamespaceTest = (this.parentNamespaceTest() !== null ? this.parentNamespaceTest()!.unpack() : null);
- _o.vectorOfReferrables = this.bb!.createObjList(this.vectorOfReferrables.bind(this), this.vectorOfReferrablesLength());
- _o.singleWeakReference = this.singleWeakReference();
- _o.vectorOfWeakReferences = this.bb!.createScalarList(this.vectorOfWeakReferences.bind(this), this.vectorOfWeakReferencesLength());
- _o.vectorOfStrongReferrables = this.bb!.createObjList(this.vectorOfStrongReferrables.bind(this), this.vectorOfStrongReferrablesLength());
- _o.coOwningReference = this.coOwningReference();
- _o.vectorOfCoOwningReferences = this.bb!.createScalarList(this.vectorOfCoOwningReferences.bind(this), this.vectorOfCoOwningReferencesLength());
- _o.nonOwningReference = this.nonOwningReference();
- _o.vectorOfNonOwningReferences = this.bb!.createScalarList(this.vectorOfNonOwningReferences.bind(this), this.vectorOfNonOwningReferencesLength());
- _o.anyUniqueType = this.anyUniqueType();
- _o.anyUnique = (() => {
- let temp = MyGame.Example.unionToAnyUniqueAliases(this.anyUniqueType(), this.anyUnique.bind(this));
- if(temp === null) { return null; }
- return temp.unpack()
- })();
- _o.anyAmbiguousType = this.anyAmbiguousType();
- _o.anyAmbiguous = (() => {
- let temp = MyGame.Example.unionToAnyAmbiguousAliases(this.anyAmbiguousType(), this.anyAmbiguous.bind(this));
- if(temp === null) { return null; }
- return temp.unpack()
- })();
- _o.vectorOfEnums = this.bb!.createScalarList(this.vectorOfEnums.bind(this), this.vectorOfEnumsLength());
- _o.signedEnum = this.signedEnum();
- _o.testrequirednestedflatbuffer = this.bb!.createScalarList(this.testrequirednestedflatbuffer.bind(this), this.testrequirednestedflatbufferLength());
-};
-}
-
-export class MonsterT {
-/**
- * @constructor
- * @param MyGame.Example.Vec3T|null pos
- * @param number mana
- * @param number hp
- * @param string|Uint8Array|null name
- * @param (number)[] inventory
- * @param MyGame.Example.Color color
- * @param MyGame.Example.Any testType
- * @param MyGame.Example.MonsterT|MyGame.Example.TestSimpleTableWithEnumT|MyGame.Example2.MonsterT|null test
- * @param (MyGame.Example.TestT)[] test4
- * @param (string)[] testarrayofstring
- * @param (MyGame.Example.MonsterT)[] testarrayoftables
- * @param MyGame.Example.MonsterT|null enemy
- * @param (number)[] testnestedflatbuffer
- * @param MyGame.Example.StatT|null testempty
- * @param boolean testbool
- * @param number testhashs32Fnv1
- * @param number testhashu32Fnv1
- * @param flatbuffers.Long testhashs64Fnv1
- * @param flatbuffers.Long testhashu64Fnv1
- * @param number testhashs32Fnv1a
- * @param number testhashu32Fnv1a
- * @param flatbuffers.Long testhashs64Fnv1a
- * @param flatbuffers.Long testhashu64Fnv1a
- * @param (boolean)[] testarrayofbools
- * @param number testf
- * @param number testf2
- * @param number testf3
- * @param (string)[] testarrayofstring2
- * @param (MyGame.Example.AbilityT)[] testarrayofsortedstruct
- * @param (number)[] flex
- * @param (MyGame.Example.TestT)[] test5
- * @param (flatbuffers.Long)[] vectorOfLongs
- * @param (number)[] vectorOfDoubles
- * @param MyGame.InParentNamespaceT|null parentNamespaceTest
- * @param (MyGame.Example.ReferrableT)[] vectorOfReferrables
- * @param flatbuffers.Long singleWeakReference
- * @param (flatbuffers.Long)[] vectorOfWeakReferences
- * @param (MyGame.Example.ReferrableT)[] vectorOfStrongReferrables
- * @param flatbuffers.Long coOwningReference
- * @param (flatbuffers.Long)[] vectorOfCoOwningReferences
- * @param flatbuffers.Long nonOwningReference
- * @param (flatbuffers.Long)[] vectorOfNonOwningReferences
- * @param MyGame.Example.AnyUniqueAliases anyUniqueType
- * @param MyGame.Example.MonsterT|MyGame.Example.TestSimpleTableWithEnumT|MyGame.Example2.MonsterT|null anyUnique
- * @param MyGame.Example.AnyAmbiguousAliases anyAmbiguousType
- * @param MyGame.Example.MonsterT|null anyAmbiguous
- * @param (MyGame.Example.Color)[] vectorOfEnums
- * @param MyGame.Example.Race signedEnum
- * @param (number)[] testrequirednestedflatbuffer
- */
-constructor(
- public pos: MyGame.Example.Vec3T|null = null,
- public mana: number = 150,
- public hp: number = 100,
- public name: string|Uint8Array|null = null,
- public inventory: (number)[] = [],
- public color: MyGame.Example.Color = MyGame.Example.Color.Blue,
- public testType: MyGame.Example.Any = MyGame.Example.Any.NONE,
- public test: MyGame.Example.MonsterT|MyGame.Example.TestSimpleTableWithEnumT|MyGame.Example2.MonsterT|null = null,
- public test4: (MyGame.Example.TestT)[] = [],
- public testarrayofstring: (string)[] = [],
- public testarrayoftables: (MyGame.Example.MonsterT)[] = [],
- public enemy: MyGame.Example.MonsterT|null = null,
- public testnestedflatbuffer: (number)[] = [],
- public testempty: MyGame.Example.StatT|null = null,
- public testbool: boolean = false,
- public testhashs32Fnv1: number = 0,
- public testhashu32Fnv1: number = 0,
- public testhashs64Fnv1: flatbuffers.Long = flatbuffers.createLong(0, 0),
- public testhashu64Fnv1: flatbuffers.Long = flatbuffers.createLong(0, 0),
- public testhashs32Fnv1a: number = 0,
- public testhashu32Fnv1a: number = 0,
- public testhashs64Fnv1a: flatbuffers.Long = flatbuffers.createLong(0, 0),
- public testhashu64Fnv1a: flatbuffers.Long = flatbuffers.createLong(0, 0),
- public testarrayofbools: (boolean)[] = [],
- public testf: number = 3.14159,
- public testf2: number = 3.0,
- public testf3: number = 0.0,
- public testarrayofstring2: (string)[] = [],
- public testarrayofsortedstruct: (MyGame.Example.AbilityT)[] = [],
- public flex: (number)[] = [],
- public test5: (MyGame.Example.TestT)[] = [],
- public vectorOfLongs: (flatbuffers.Long)[] = [],
- public vectorOfDoubles: (number)[] = [],
- public parentNamespaceTest: MyGame.InParentNamespaceT|null = null,
- public vectorOfReferrables: (MyGame.Example.ReferrableT)[] = [],
- public singleWeakReference: flatbuffers.Long = flatbuffers.createLong(0, 0),
- public vectorOfWeakReferences: (flatbuffers.Long)[] = [],
- public vectorOfStrongReferrables: (MyGame.Example.ReferrableT)[] = [],
- public coOwningReference: flatbuffers.Long = flatbuffers.createLong(0, 0),
- public vectorOfCoOwningReferences: (flatbuffers.Long)[] = [],
- public nonOwningReference: flatbuffers.Long = flatbuffers.createLong(0, 0),
- public vectorOfNonOwningReferences: (flatbuffers.Long)[] = [],
- public anyUniqueType: MyGame.Example.AnyUniqueAliases = MyGame.Example.AnyUniqueAliases.NONE,
- public anyUnique: MyGame.Example.MonsterT|MyGame.Example.TestSimpleTableWithEnumT|MyGame.Example2.MonsterT|null = null,
- public anyAmbiguousType: MyGame.Example.AnyAmbiguousAliases = MyGame.Example.AnyAmbiguousAliases.NONE,
- public anyAmbiguous: MyGame.Example.MonsterT|null = null,
- public vectorOfEnums: (MyGame.Example.Color)[] = [],
- public signedEnum: MyGame.Example.Race = MyGame.Example.Race.None,
- public testrequirednestedflatbuffer: (number)[] = []
-){};
-
-/**
- * @param flatbuffers.Builder builder
- * @returns flatbuffers.Offset
- */
-pack(builder:flatbuffers.Builder): flatbuffers.Offset {
- const name = (this.name !== null ? builder.createString(this.name!) : 0);
- const inventory = MyGame.Example.Monster.createInventoryVector(builder, this.inventory);
- const test = builder.createObjectOffset(this.test);
- const test4 = builder.createStructOffsetList(this.test4, MyGame.Example.Monster.startTest4Vector);
- const testarrayofstring = MyGame.Example.Monster.createTestarrayofstringVector(builder, builder.createObjectOffsetList(this.testarrayofstring));
- const testarrayoftables = MyGame.Example.Monster.createTestarrayoftablesVector(builder, builder.createObjectOffsetList(this.testarrayoftables));
- const testnestedflatbuffer = MyGame.Example.Monster.createTestnestedflatbufferVector(builder, this.testnestedflatbuffer);
- const testarrayofbools = MyGame.Example.Monster.createTestarrayofboolsVector(builder, this.testarrayofbools);
- const testarrayofstring2 = MyGame.Example.Monster.createTestarrayofstring2Vector(builder, builder.createObjectOffsetList(this.testarrayofstring2));
- const testarrayofsortedstruct = builder.createStructOffsetList(this.testarrayofsortedstruct, MyGame.Example.Monster.startTestarrayofsortedstructVector);
- const flex = MyGame.Example.Monster.createFlexVector(builder, this.flex);
- const test5 = builder.createStructOffsetList(this.test5, MyGame.Example.Monster.startTest5Vector);
- const vectorOfLongs = MyGame.Example.Monster.createVectorOfLongsVector(builder, this.vectorOfLongs);
- const vectorOfDoubles = MyGame.Example.Monster.createVectorOfDoublesVector(builder, this.vectorOfDoubles);
- const vectorOfReferrables = MyGame.Example.Monster.createVectorOfReferrablesVector(builder, builder.createObjectOffsetList(this.vectorOfReferrables));
- const vectorOfWeakReferences = MyGame.Example.Monster.createVectorOfWeakReferencesVector(builder, this.vectorOfWeakReferences);
- const vectorOfStrongReferrables = MyGame.Example.Monster.createVectorOfStrongReferrablesVector(builder, builder.createObjectOffsetList(this.vectorOfStrongReferrables));
- const vectorOfCoOwningReferences = MyGame.Example.Monster.createVectorOfCoOwningReferencesVector(builder, this.vectorOfCoOwningReferences);
- const vectorOfNonOwningReferences = MyGame.Example.Monster.createVectorOfNonOwningReferencesVector(builder, this.vectorOfNonOwningReferences);
- const anyUnique = builder.createObjectOffset(this.anyUnique);
- const anyAmbiguous = builder.createObjectOffset(this.anyAmbiguous);
- const vectorOfEnums = MyGame.Example.Monster.createVectorOfEnumsVector(builder, this.vectorOfEnums);
- const testrequirednestedflatbuffer = MyGame.Example.Monster.createTestrequirednestedflatbufferVector(builder, this.testrequirednestedflatbuffer);
-
- MyGame.Example.Monster.start(builder);
- MyGame.Example.Monster.addPos(builder, (this.pos !== null ? this.pos!.pack(builder) : 0));
- MyGame.Example.Monster.addMana(builder, this.mana);
- MyGame.Example.Monster.addHp(builder, this.hp);
- MyGame.Example.Monster.addName(builder, name);
- MyGame.Example.Monster.addInventory(builder, inventory);
- MyGame.Example.Monster.addColor(builder, this.color);
- MyGame.Example.Monster.addTestType(builder, this.testType);
- MyGame.Example.Monster.addTest(builder, test);
- MyGame.Example.Monster.addTest4(builder, test4);
- MyGame.Example.Monster.addTestarrayofstring(builder, testarrayofstring);
- MyGame.Example.Monster.addTestarrayoftables(builder, testarrayoftables);
- MyGame.Example.Monster.addEnemy(builder, (this.enemy !== null ? this.enemy!.pack(builder) : 0));
- MyGame.Example.Monster.addTestnestedflatbuffer(builder, testnestedflatbuffer);
- MyGame.Example.Monster.addTestempty(builder, (this.testempty !== null ? this.testempty!.pack(builder) : 0));
- MyGame.Example.Monster.addTestbool(builder, this.testbool);
- MyGame.Example.Monster.addTesthashs32Fnv1(builder, this.testhashs32Fnv1);
- MyGame.Example.Monster.addTesthashu32Fnv1(builder, this.testhashu32Fnv1);
- MyGame.Example.Monster.addTesthashs64Fnv1(builder, this.testhashs64Fnv1);
- MyGame.Example.Monster.addTesthashu64Fnv1(builder, this.testhashu64Fnv1);
- MyGame.Example.Monster.addTesthashs32Fnv1a(builder, this.testhashs32Fnv1a);
- MyGame.Example.Monster.addTesthashu32Fnv1a(builder, this.testhashu32Fnv1a);
- MyGame.Example.Monster.addTesthashs64Fnv1a(builder, this.testhashs64Fnv1a);
- MyGame.Example.Monster.addTesthashu64Fnv1a(builder, this.testhashu64Fnv1a);
- MyGame.Example.Monster.addTestarrayofbools(builder, testarrayofbools);
- MyGame.Example.Monster.addTestf(builder, this.testf);
- MyGame.Example.Monster.addTestf2(builder, this.testf2);
- MyGame.Example.Monster.addTestf3(builder, this.testf3);
- MyGame.Example.Monster.addTestarrayofstring2(builder, testarrayofstring2);
- MyGame.Example.Monster.addTestarrayofsortedstruct(builder, testarrayofsortedstruct);
- MyGame.Example.Monster.addFlex(builder, flex);
- MyGame.Example.Monster.addTest5(builder, test5);
- MyGame.Example.Monster.addVectorOfLongs(builder, vectorOfLongs);
- MyGame.Example.Monster.addVectorOfDoubles(builder, vectorOfDoubles);
- MyGame.Example.Monster.addParentNamespaceTest(builder, (this.parentNamespaceTest !== null ? this.parentNamespaceTest!.pack(builder) : 0));
- MyGame.Example.Monster.addVectorOfReferrables(builder, vectorOfReferrables);
- MyGame.Example.Monster.addSingleWeakReference(builder, this.singleWeakReference);
- MyGame.Example.Monster.addVectorOfWeakReferences(builder, vectorOfWeakReferences);
- MyGame.Example.Monster.addVectorOfStrongReferrables(builder, vectorOfStrongReferrables);
- MyGame.Example.Monster.addCoOwningReference(builder, this.coOwningReference);
- MyGame.Example.Monster.addVectorOfCoOwningReferences(builder, vectorOfCoOwningReferences);
- MyGame.Example.Monster.addNonOwningReference(builder, this.nonOwningReference);
- MyGame.Example.Monster.addVectorOfNonOwningReferences(builder, vectorOfNonOwningReferences);
- MyGame.Example.Monster.addAnyUniqueType(builder, this.anyUniqueType);
- MyGame.Example.Monster.addAnyUnique(builder, anyUnique);
- MyGame.Example.Monster.addAnyAmbiguousType(builder, this.anyAmbiguousType);
- MyGame.Example.Monster.addAnyAmbiguous(builder, anyAmbiguous);
- MyGame.Example.Monster.addVectorOfEnums(builder, vectorOfEnums);
- MyGame.Example.Monster.addSignedEnum(builder, this.signedEnum);
- MyGame.Example.Monster.addTestrequirednestedflatbuffer(builder, testrequirednestedflatbuffer);
-
- return MyGame.Example.Monster.end(builder);
-};
-}
-}
-/**
- * @constructor
- */
-export namespace MyGame.Example{
-export class TypeAliases {
- bb: flatbuffers.ByteBuffer|null = null;
-
- bb_pos:number = 0;
-/**
- * @param number i
- * @param flatbuffers.ByteBuffer bb
- * @returns TypeAliases
- */
-__init(i:number, bb:flatbuffers.ByteBuffer):TypeAliases {
- this.bb_pos = i;
- this.bb = bb;
- return this;
-};
-
-/**
- * @param flatbuffers.ByteBuffer bb
- * @param TypeAliases= obj
- * @returns TypeAliases
- */
-static getRootAsTypeAliases(bb:flatbuffers.ByteBuffer, obj?:TypeAliases):TypeAliases {
- return (obj || new TypeAliases()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param flatbuffers.ByteBuffer bb
- * @param TypeAliases= obj
- * @returns TypeAliases
- */
-static getSizePrefixedRootAsTypeAliases(bb:flatbuffers.ByteBuffer, obj?:TypeAliases):TypeAliases {
- bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
- return (obj || new TypeAliases()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @returns number
- */
-i8():number {
- var offset = this.bb!.__offset(this.bb_pos, 4);
- return offset ? this.bb!.readInt8(this.bb_pos + offset) : 0;
-};
-
-/**
- * @param number value
- * @returns boolean
- */
-mutate_i8(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 4);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb!.writeInt8(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @returns number
- */
-u8():number {
- var offset = this.bb!.__offset(this.bb_pos, 6);
- return offset ? this.bb!.readUint8(this.bb_pos + offset) : 0;
-};
-
-/**
- * @param number value
- * @returns boolean
- */
-mutate_u8(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 6);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb!.writeUint8(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @returns number
- */
-i16():number {
- var offset = this.bb!.__offset(this.bb_pos, 8);
- return offset ? this.bb!.readInt16(this.bb_pos + offset) : 0;
-};
-
-/**
- * @param number value
- * @returns boolean
- */
-mutate_i16(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 8);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb!.writeInt16(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @returns number
- */
-u16():number {
- var offset = this.bb!.__offset(this.bb_pos, 10);
- return offset ? this.bb!.readUint16(this.bb_pos + offset) : 0;
-};
-
-/**
- * @param number value
- * @returns boolean
- */
-mutate_u16(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 10);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb!.writeUint16(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @returns number
- */
-i32():number {
- var offset = this.bb!.__offset(this.bb_pos, 12);
- return offset ? this.bb!.readInt32(this.bb_pos + offset) : 0;
-};
-
-/**
- * @param number value
- * @returns boolean
- */
-mutate_i32(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 12);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb!.writeInt32(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @returns number
- */
-u32():number {
- var offset = this.bb!.__offset(this.bb_pos, 14);
- return offset ? this.bb!.readUint32(this.bb_pos + offset) : 0;
-};
-
-/**
- * @param number value
- * @returns boolean
- */
-mutate_u32(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 14);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb!.writeUint32(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @returns flatbuffers.Long
- */
-i64():flatbuffers.Long {
- var offset = this.bb!.__offset(this.bb_pos, 16);
- return offset ? this.bb!.readInt64(this.bb_pos + offset) : this.bb!.createLong(0, 0);
-};
-
-/**
- * @param flatbuffers.Long value
- * @returns boolean
- */
-mutate_i64(value:flatbuffers.Long):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 16);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb!.writeInt64(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @returns flatbuffers.Long
- */
-u64():flatbuffers.Long {
- var offset = this.bb!.__offset(this.bb_pos, 18);
- return offset ? this.bb!.readUint64(this.bb_pos + offset) : this.bb!.createLong(0, 0);
-};
-
-/**
- * @param flatbuffers.Long value
- * @returns boolean
- */
-mutate_u64(value:flatbuffers.Long):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 18);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb!.writeUint64(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @returns number
- */
-f32():number {
- var offset = this.bb!.__offset(this.bb_pos, 20);
- return offset ? this.bb!.readFloat32(this.bb_pos + offset) : 0.0;
-};
-
-/**
- * @param number value
- * @returns boolean
- */
-mutate_f32(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 20);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb!.writeFloat32(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @returns number
- */
-f64():number {
- var offset = this.bb!.__offset(this.bb_pos, 22);
- return offset ? this.bb!.readFloat64(this.bb_pos + offset) : 0.0;
-};
-
-/**
- * @param number value
- * @returns boolean
- */
-mutate_f64(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 22);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb!.writeFloat64(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @param number index
- * @returns number
- */
-v8(index: number):number|null {
- var offset = this.bb!.__offset(this.bb_pos, 24);
- return offset ? this.bb!.readInt8(this.bb!.__vector(this.bb_pos + offset) + index) : 0;
-};
-
-/**
- * @returns number
- */
-v8Length():number {
- var offset = this.bb!.__offset(this.bb_pos, 24);
- return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
-};
-
-/**
- * @returns Int8Array
- */
-v8Array():Int8Array|null {
- var offset = this.bb!.__offset(this.bb_pos, 24);
- return offset ? new Int8Array(this.bb!.bytes().buffer, this.bb!.bytes().byteOffset + this.bb!.__vector(this.bb_pos + offset), this.bb!.__vector_len(this.bb_pos + offset)) : null;
-};
-
-/**
- * @param number index
- * @returns number
- */
-vf64(index: number):number|null {
- var offset = this.bb!.__offset(this.bb_pos, 26);
- return offset ? this.bb!.readFloat64(this.bb!.__vector(this.bb_pos + offset) + index * 8) : 0;
-};
-
-/**
- * @returns number
- */
-vf64Length():number {
- var offset = this.bb!.__offset(this.bb_pos, 26);
- return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
-};
-
-/**
- * @returns Float64Array
- */
-vf64Array():Float64Array|null {
- var offset = this.bb!.__offset(this.bb_pos, 26);
- return offset ? new Float64Array(this.bb!.bytes().buffer, this.bb!.bytes().byteOffset + this.bb!.__vector(this.bb_pos + offset), this.bb!.__vector_len(this.bb_pos + offset)) : null;
-};
-
-/**
- * @param flatbuffers.Builder builder
- */
-static startTypeAliases(builder:flatbuffers.Builder) {
- builder.startObject(12);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number i8
- */
-static addI8(builder:flatbuffers.Builder, i8:number) {
- builder.addFieldInt8(0, i8, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number u8
- */
-static addU8(builder:flatbuffers.Builder, u8:number) {
- builder.addFieldInt8(1, u8, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number i16
- */
-static addI16(builder:flatbuffers.Builder, i16:number) {
- builder.addFieldInt16(2, i16, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number u16
- */
-static addU16(builder:flatbuffers.Builder, u16:number) {
- builder.addFieldInt16(3, u16, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number i32
- */
-static addI32(builder:flatbuffers.Builder, i32:number) {
- builder.addFieldInt32(4, i32, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number u32
- */
-static addU32(builder:flatbuffers.Builder, u32:number) {
- builder.addFieldInt32(5, u32, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Long i64
- */
-static addI64(builder:flatbuffers.Builder, i64:flatbuffers.Long) {
- builder.addFieldInt64(6, i64, builder.createLong(0, 0));
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Long u64
- */
-static addU64(builder:flatbuffers.Builder, u64:flatbuffers.Long) {
- builder.addFieldInt64(7, u64, builder.createLong(0, 0));
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number f32
- */
-static addF32(builder:flatbuffers.Builder, f32:number) {
- builder.addFieldFloat32(8, f32, 0.0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number f64
- */
-static addF64(builder:flatbuffers.Builder, f64:number) {
- builder.addFieldFloat64(9, f64, 0.0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Offset v8Offset
- */
-static addV8(builder:flatbuffers.Builder, v8Offset:flatbuffers.Offset) {
- builder.addFieldOffset(10, v8Offset, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param Array.<number> data
- * @returns flatbuffers.Offset
- */
-static createV8Vector(builder:flatbuffers.Builder, data:number[]|Int8Array):flatbuffers.Offset;
-/**
- * @deprecated This Uint8Array overload will be removed in the future.
- */
-static createV8Vector(builder:flatbuffers.Builder, data:number[]|Uint8Array):flatbuffers.Offset;
-static createV8Vector(builder:flatbuffers.Builder, data:number[]|Int8Array|Uint8Array):flatbuffers.Offset {
- builder.startVector(1, data.length, 1);
- for (var i = data.length - 1; i >= 0; i--) {
- builder.addInt8(data[i]);
- }
- return builder.endVector();
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number numElems
- */
-static startV8Vector(builder:flatbuffers.Builder, numElems:number) {
- builder.startVector(1, numElems, 1);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Offset vf64Offset
- */
-static addVf64(builder:flatbuffers.Builder, vf64Offset:flatbuffers.Offset) {
- builder.addFieldOffset(11, vf64Offset, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param Array.<number> data
- * @returns flatbuffers.Offset
- */
-static createVf64Vector(builder:flatbuffers.Builder, data:number[]|Float64Array):flatbuffers.Offset;
-/**
- * @deprecated This Uint8Array overload will be removed in the future.
- */
-static createVf64Vector(builder:flatbuffers.Builder, data:number[]|Uint8Array):flatbuffers.Offset;
-static createVf64Vector(builder:flatbuffers.Builder, data:number[]|Float64Array|Uint8Array):flatbuffers.Offset {
- builder.startVector(8, data.length, 8);
- for (var i = data.length - 1; i >= 0; i--) {
- builder.addFloat64(data[i]);
- }
- return builder.endVector();
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number numElems
- */
-static startVf64Vector(builder:flatbuffers.Builder, numElems:number) {
- builder.startVector(8, numElems, 8);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @returns flatbuffers.Offset
- */
-static endTypeAliases(builder:flatbuffers.Builder):flatbuffers.Offset {
- var offset = builder.endObject();
- return offset;
-};
-
-static createTypeAliases(builder:flatbuffers.Builder, i8:number, u8:number, i16:number, u16:number, i32:number, u32:number, i64:flatbuffers.Long, u64:flatbuffers.Long, f32:number, f64:number, v8Offset:flatbuffers.Offset, vf64Offset:flatbuffers.Offset):flatbuffers.Offset {
- TypeAliases.startTypeAliases(builder);
- TypeAliases.addI8(builder, i8);
- TypeAliases.addU8(builder, u8);
- TypeAliases.addI16(builder, i16);
- TypeAliases.addU16(builder, u16);
- TypeAliases.addI32(builder, i32);
- TypeAliases.addU32(builder, u32);
- TypeAliases.addI64(builder, i64);
- TypeAliases.addU64(builder, u64);
- TypeAliases.addF32(builder, f32);
- TypeAliases.addF64(builder, f64);
- TypeAliases.addV8(builder, v8Offset);
- TypeAliases.addVf64(builder, vf64Offset);
- return TypeAliases.endTypeAliases(builder);
-}
-
-serialize():Uint8Array {
- return this.bb!.bytes();
-}
-
-static deserialize(buffer: Uint8Array):TypeAliases {
- return TypeAliases.getRootAsTypeAliases(new flatbuffers.ByteBuffer(buffer))
-}
-
-/**
- * @returns TypeAliasesT
- */
-unpack(): TypeAliasesT {
- return new TypeAliasesT(
- this.i8(),
- this.u8(),
- this.i16(),
- this.u16(),
- this.i32(),
- this.u32(),
- this.i64(),
- this.u64(),
- this.f32(),
- this.f64(),
- this.bb!.createScalarList(this.v8.bind(this), this.v8Length()),
- this.bb!.createScalarList(this.vf64.bind(this), this.vf64Length())
- );
-};
-
-/**
- * @param TypeAliasesT _o
- */
-unpackTo(_o: TypeAliasesT): void {
- _o.i8 = this.i8();
- _o.u8 = this.u8();
- _o.i16 = this.i16();
- _o.u16 = this.u16();
- _o.i32 = this.i32();
- _o.u32 = this.u32();
- _o.i64 = this.i64();
- _o.u64 = this.u64();
- _o.f32 = this.f32();
- _o.f64 = this.f64();
- _o.v8 = this.bb!.createScalarList(this.v8.bind(this), this.v8Length());
- _o.vf64 = this.bb!.createScalarList(this.vf64.bind(this), this.vf64Length());
-};
-}
-
-export class TypeAliasesT {
-/**
- * @constructor
- * @param number i8
- * @param number u8
- * @param number i16
- * @param number u16
- * @param number i32
- * @param number u32
- * @param flatbuffers.Long i64
- * @param flatbuffers.Long u64
- * @param number f32
- * @param number f64
- * @param (number)[] v8
- * @param (number)[] vf64
- */
-constructor(
- public i8: number = 0,
- public u8: number = 0,
- public i16: number = 0,
- public u16: number = 0,
- public i32: number = 0,
- public u32: number = 0,
- public i64: flatbuffers.Long = flatbuffers.createLong(0, 0),
- public u64: flatbuffers.Long = flatbuffers.createLong(0, 0),
- public f32: number = 0.0,
- public f64: number = 0.0,
- public v8: (number)[] = [],
- public vf64: (number)[] = []
-){};
-
-/**
- * @param flatbuffers.Builder builder
- * @returns flatbuffers.Offset
- */
-pack(builder:flatbuffers.Builder): flatbuffers.Offset {
- const v8 = MyGame.Example.TypeAliases.createV8Vector(builder, this.v8);
- const vf64 = MyGame.Example.TypeAliases.createVf64Vector(builder, this.vf64);
-
- return MyGame.Example.TypeAliases.createTypeAliases(builder,
- this.i8,
- this.u8,
- this.i16,
- this.u16,
- this.i32,
- this.u32,
- this.i64,
- this.u64,
- this.f32,
- this.f64,
- v8,
- vf64
- );
-};
-}
-}
diff --git a/tests/monster_test_grpc.d.ts b/tests/monster_test_grpc.d.ts
index 128c602..e7a71d1 100644
--- a/tests/monster_test_grpc.d.ts
+++ b/tests/monster_test_grpc.d.ts
@@ -1,8 +1,9 @@
// Generated GRPC code for FlatBuffers TS *** DO NOT EDIT ***
-import { flatbuffers } from 'flatbuffers';
-import * as MonsterStorage_fbs from './monster_test_generated';
+import * as flatbuffers from 'flatbuffers';
+import { Stat as MyGame_Example_Stat } from './my-game/example/stat';
+import { Monster as MyGame_Example_Monster } from './my-game/example/monster';
-import * as grpc from 'grpc';
+import * as grpc from '@grpc/grpc-js';
interface IMonsterStorageService extends grpc.ServiceDefinition<grpc.UntypedServiceImplementation> {
Store: IMonsterStorageService_IStore;
@@ -10,83 +11,84 @@
GetMaxHitPoint: IMonsterStorageService_IGetMaxHitPoint;
GetMinMaxHitPoints: IMonsterStorageService_IGetMinMaxHitPoints;
}
-interface IMonsterStorageService_IStore extends grpc.MethodDefinition<MonsterStorage_fbs.Monster, MonsterStorage_fbs.Stat> {
+interface IMonsterStorageService_IStore extends grpc.MethodDefinition<MyGame_Example_Monster, MyGame_Example_Stat> {
path: string; // /MyGame.Example.MonsterStorage/Store
requestStream: boolean; // false
responseStream: boolean; // false
- requestSerialize: grpc.serialize<MonsterStorage_fbs.Monster>;
- requestDeserialize: grpc.deserialize<MonsterStorage_fbs.Monster>;
- responseSerialize: grpc.serialize<MonsterStorage_fbs.Stat>;
- responseDeserialize: grpc.deserialize<MonsterStorage_fbs.Stat>;
+ requestSerialize: grpc.serialize<MyGame_Example_Monster>;
+ requestDeserialize: grpc.deserialize<MyGame_Example_Monster>;
+ responseSerialize: grpc.serialize<MyGame_Example_Stat>;
+ responseDeserialize: grpc.deserialize<MyGame_Example_Stat>;
}
-interface IMonsterStorageService_IRetrieve extends grpc.MethodDefinition<MonsterStorage_fbs.Stat, MonsterStorage_fbs.Monster> {
+interface IMonsterStorageService_IRetrieve extends grpc.MethodDefinition<MyGame_Example_Stat, MyGame_Example_Monster> {
path: string; // /MyGame.Example.MonsterStorage/Retrieve
requestStream: boolean; // false
responseStream: boolean; // true
- requestSerialize: grpc.serialize<MonsterStorage_fbs.Stat>;
- requestDeserialize: grpc.deserialize<MonsterStorage_fbs.Stat>;
- responseSerialize: grpc.serialize<MonsterStorage_fbs.Monster>;
- responseDeserialize: grpc.deserialize<MonsterStorage_fbs.Monster>;
+ requestSerialize: grpc.serialize<MyGame_Example_Stat>;
+ requestDeserialize: grpc.deserialize<MyGame_Example_Stat>;
+ responseSerialize: grpc.serialize<MyGame_Example_Monster>;
+ responseDeserialize: grpc.deserialize<MyGame_Example_Monster>;
}
-interface IMonsterStorageService_IGetMaxHitPoint extends grpc.MethodDefinition<MonsterStorage_fbs.Monster, MonsterStorage_fbs.Stat> {
+interface IMonsterStorageService_IGetMaxHitPoint extends grpc.MethodDefinition<MyGame_Example_Monster, MyGame_Example_Stat> {
path: string; // /MyGame.Example.MonsterStorage/GetMaxHitPoint
requestStream: boolean; // true
responseStream: boolean; // false
- requestSerialize: grpc.serialize<MonsterStorage_fbs.Monster>;
- requestDeserialize: grpc.deserialize<MonsterStorage_fbs.Monster>;
- responseSerialize: grpc.serialize<MonsterStorage_fbs.Stat>;
- responseDeserialize: grpc.deserialize<MonsterStorage_fbs.Stat>;
+ requestSerialize: grpc.serialize<MyGame_Example_Monster>;
+ requestDeserialize: grpc.deserialize<MyGame_Example_Monster>;
+ responseSerialize: grpc.serialize<MyGame_Example_Stat>;
+ responseDeserialize: grpc.deserialize<MyGame_Example_Stat>;
}
-interface IMonsterStorageService_IGetMinMaxHitPoints extends grpc.MethodDefinition<MonsterStorage_fbs.Monster, MonsterStorage_fbs.Stat> {
+interface IMonsterStorageService_IGetMinMaxHitPoints extends grpc.MethodDefinition<MyGame_Example_Monster, MyGame_Example_Stat> {
path: string; // /MyGame.Example.MonsterStorage/GetMinMaxHitPoints
requestStream: boolean; // true
responseStream: boolean; // true
- requestSerialize: grpc.serialize<MonsterStorage_fbs.Monster>;
- requestDeserialize: grpc.deserialize<MonsterStorage_fbs.Monster>;
- responseSerialize: grpc.serialize<MonsterStorage_fbs.Stat>;
- responseDeserialize: grpc.deserialize<MonsterStorage_fbs.Stat>;
+ requestSerialize: grpc.serialize<MyGame_Example_Monster>;
+ requestDeserialize: grpc.deserialize<MyGame_Example_Monster>;
+ responseSerialize: grpc.serialize<MyGame_Example_Stat>;
+ responseDeserialize: grpc.deserialize<MyGame_Example_Stat>;
}
export const MonsterStorageService: IMonsterStorageService;
-export interface IMonsterStorageServer {
- Store: grpc.handleUnaryCall<MonsterStorage_fbs.Monster, MonsterStorage_fbs.Stat>;
- Retrieve: grpc.handleServerStreamingCall<MonsterStorage_fbs.Stat, MonsterStorage_fbs.Monster>;
- GetMaxHitPoint: grpc.handleClientStreamingCall<MonsterStorage_fbs.Monster, MonsterStorage_fbs.Stat>;
- GetMinMaxHitPoints: grpc.handleBidiStreamingCall<MonsterStorage_fbs.Monster, MonsterStorage_fbs.Stat>;
+export interface IMonsterStorageServer extends grpc.UntypedServiceImplementation {
+ Store: grpc.handleUnaryCall<MyGame_Example_Monster, MyGame_Example_Stat>;
+ Retrieve: grpc.handleServerStreamingCall<MyGame_Example_Stat, MyGame_Example_Monster>;
+ GetMaxHitPoint: grpc.handleClientStreamingCall<MyGame_Example_Monster, MyGame_Example_Stat>;
+ GetMinMaxHitPoints: grpc.handleBidiStreamingCall<MyGame_Example_Monster, MyGame_Example_Stat>;
}
export interface IMonsterStorageClient {
- Store(request: MonsterStorage_fbs.Monster, callback: (error: grpc.ServiceError | null, response: MonsterStorage_fbs.Stat) => void): grpc.ClientUnaryCall;
- Store(request: MonsterStorage_fbs.Monster, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: MonsterStorage_fbs.Stat) => void): grpc.ClientUnaryCall;
- Store(request: MonsterStorage_fbs.Monster, metadata: grpc.Metadata, options: Partial<grpc.CallOptions>, callback: (error: grpc.ServiceError | null, response: MonsterStorage_fbs.Stat) => void): grpc.ClientUnaryCall;
- Retrieve(request: MonsterStorage_fbs.Stat, metadata: grpc.Metadata): grpc.ClientReadableStream<MonsterStorage_fbs.Monster>;
- Retrieve(request: MonsterStorage_fbs.Stat, options: Partial<grpc.CallOptions>): grpc.ClientReadableStream<MonsterStorage_fbs.Monster>;
- GetMaxHitPoint(callback: (error: grpc.ServiceError | null, response: MonsterStorage_fbs.Monster) => void): grpc.ClientWritableStream<MonsterStorage_fbs.Stat>;
- GetMaxHitPoint(metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: MonsterStorage_fbs.Monster) => void): grpc.ClientWritableStream<MonsterStorage_fbs.Stat>;
- GetMaxHitPoint(options: Partial<grpc.CallOptions>, callback: (error: grpc.ServiceError | null, response: MonsterStorage_fbs.Monster) => void): grpc.ClientWritableStream<MonsterStorage_fbs.Stat>;
- GetMaxHitPoint(metadata: grpc.Metadata, options: Partial<grpc.CallOptions>, callback: (error: grpc.ServiceError | null, response: MonsterStorage_fbs.Monster) => void): grpc.ClientWritableStream<MonsterStorage_fbs.Stat>;
- GetMinMaxHitPoints(): grpc.ClientDuplexStream<MonsterStorage_fbs.Monster, MonsterStorage_fbs.Stat>;
- GetMinMaxHitPoints(options: Partial<grpc.CallOptions>): grpc.ClientDuplexStream<MonsterStorage_fbs.Monster, MonsterStorage_fbs.Stat>;
- GetMinMaxHitPoints(metadata: grpc.Metadata, options?: Partial<grpc.CallOptions>): grpc.ClientDuplexStream<MonsterStorage_fbs.Monster, MonsterStorage_fbs.Stat>;
+ Store(request: MyGame_Example_Monster, callback: (error: grpc.ServiceError | null, response: MyGame_Example_Stat) => void): grpc.ClientUnaryCall;
+ Store(request: MyGame_Example_Monster, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: MyGame_Example_Stat) => void): grpc.ClientUnaryCall;
+ Store(request: MyGame_Example_Monster, metadata: grpc.Metadata, options: Partial<grpc.CallOptions>, callback: (error: grpc.ServiceError | null, response: MyGame_Example_Stat) => void): grpc.ClientUnaryCall;
+ Retrieve(request: MyGame_Example_Stat, metadata: grpc.Metadata): grpc.ClientReadableStream<MyGame_Example_Monster>;
+ Retrieve(request: MyGame_Example_Stat, options: Partial<grpc.CallOptions>): grpc.ClientReadableStream<MyGame_Example_Monster>;
+ GetMaxHitPoint(callback: (error: grpc.ServiceError | null, response: MyGame_Example_Monster) => void): grpc.ClientWritableStream<MyGame_Example_Stat>;
+ GetMaxHitPoint(metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: MyGame_Example_Monster) => void): grpc.ClientWritableStream<MyGame_Example_Stat>;
+ GetMaxHitPoint(options: Partial<grpc.CallOptions>, callback: (error: grpc.ServiceError | null, response: MyGame_Example_Monster) => void): grpc.ClientWritableStream<MyGame_Example_Stat>;
+ GetMaxHitPoint(metadata: grpc.Metadata, options: Partial<grpc.CallOptions>, callback: (error: grpc.ServiceError | null, response: MyGame_Example_Monster) => void): grpc.ClientWritableStream<MyGame_Example_Stat>;
+ GetMinMaxHitPoints(): grpc.ClientDuplexStream<MyGame_Example_Monster, MyGame_Example_Stat>;
+ GetMinMaxHitPoints(options: Partial<grpc.CallOptions>): grpc.ClientDuplexStream<MyGame_Example_Monster, MyGame_Example_Stat>;
+ GetMinMaxHitPoints(metadata: grpc.Metadata, options?: Partial<grpc.CallOptions>): grpc.ClientDuplexStream<MyGame_Example_Monster, MyGame_Example_Stat>;
}
export class MonsterStorageClient extends grpc.Client implements IMonsterStorageClient {
- constructor(address: string, credentials: grpc.ChannelCredentials, options?: object); public Store(request: MonsterStorage_fbs.Monster, callback: (error: grpc.ServiceError | null, response: MonsterStorage_fbs.Stat) => void): grpc.ClientUnaryCall;
- public Store(request: MonsterStorage_fbs.Monster, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: MonsterStorage_fbs.Stat) => void): grpc.ClientUnaryCall;
- public Store(request: MonsterStorage_fbs.Monster, metadata: grpc.Metadata, options: Partial<grpc.CallOptions>, callback: (error: grpc.ServiceError | null, response: MonsterStorage_fbs.Stat) => void): grpc.ClientUnaryCall;
- public Retrieve(request: MonsterStorage_fbs.Stat, metadata: grpc.Metadata): grpc.ClientReadableStream<MonsterStorage_fbs.Monster>;
- public Retrieve(request: MonsterStorage_fbs.Stat, options: Partial<grpc.CallOptions>): grpc.ClientReadableStream<MonsterStorage_fbs.Monster>;
- public GetMaxHitPoint(callback: (error: grpc.ServiceError | null, response: MonsterStorage_fbs.Monster) => void): grpc.ClientWritableStream<MonsterStorage_fbs.Stat>;
- public GetMaxHitPoint(metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: MonsterStorage_fbs.Monster) => void): grpc.ClientWritableStream<MonsterStorage_fbs.Stat>;
- public GetMaxHitPoint(options: Partial<grpc.CallOptions>, callback: (error: grpc.ServiceError | null, response: MonsterStorage_fbs.Monster) => void): grpc.ClientWritableStream<MonsterStorage_fbs.Stat>;
- public GetMaxHitPoint(metadata: grpc.Metadata, options: Partial<grpc.CallOptions>, callback: (error: grpc.ServiceError | null, response: MonsterStorage_fbs.Monster) => void): grpc.ClientWritableStream<MonsterStorage_fbs.Stat>;
- public GetMinMaxHitPoints(): grpc.ClientDuplexStream<MonsterStorage_fbs.Monster, MonsterStorage_fbs.Stat>;
- public GetMinMaxHitPoints(options: Partial<grpc.CallOptions>): grpc.ClientDuplexStream<MonsterStorage_fbs.Monster, MonsterStorage_fbs.Stat>;
- public GetMinMaxHitPoints(metadata: grpc.Metadata, options?: Partial<grpc.CallOptions>): grpc.ClientDuplexStream<MonsterStorage_fbs.Monster, MonsterStorage_fbs.Stat>;
+ constructor(address: string, credentials: grpc.ChannelCredentials, options?: object);
+ public Store(request: MyGame_Example_Monster, callback: (error: grpc.ServiceError | null, response: MyGame_Example_Stat) => void): grpc.ClientUnaryCall;
+ public Store(request: MyGame_Example_Monster, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: MyGame_Example_Stat) => void): grpc.ClientUnaryCall;
+ public Store(request: MyGame_Example_Monster, metadata: grpc.Metadata, options: Partial<grpc.CallOptions>, callback: (error: grpc.ServiceError | null, response: MyGame_Example_Stat) => void): grpc.ClientUnaryCall;
+ public Retrieve(request: MyGame_Example_Stat, metadata: grpc.Metadata): grpc.ClientReadableStream<MyGame_Example_Monster>;
+ public Retrieve(request: MyGame_Example_Stat, options: Partial<grpc.CallOptions>): grpc.ClientReadableStream<MyGame_Example_Monster>;
+ public GetMaxHitPoint(callback: (error: grpc.ServiceError | null, response: MyGame_Example_Monster) => void): grpc.ClientWritableStream<MyGame_Example_Stat>;
+ public GetMaxHitPoint(metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: MyGame_Example_Monster) => void): grpc.ClientWritableStream<MyGame_Example_Stat>;
+ public GetMaxHitPoint(options: Partial<grpc.CallOptions>, callback: (error: grpc.ServiceError | null, response: MyGame_Example_Monster) => void): grpc.ClientWritableStream<MyGame_Example_Stat>;
+ public GetMaxHitPoint(metadata: grpc.Metadata, options: Partial<grpc.CallOptions>, callback: (error: grpc.ServiceError | null, response: MyGame_Example_Monster) => void): grpc.ClientWritableStream<MyGame_Example_Stat>;
+ public GetMinMaxHitPoints(): grpc.ClientDuplexStream<MyGame_Example_Monster, MyGame_Example_Stat>;
+ public GetMinMaxHitPoints(options: Partial<grpc.CallOptions>): grpc.ClientDuplexStream<MyGame_Example_Monster, MyGame_Example_Stat>;
+ public GetMinMaxHitPoints(metadata: grpc.Metadata, options?: Partial<grpc.CallOptions>): grpc.ClientDuplexStream<MyGame_Example_Monster, MyGame_Example_Stat>;
}
diff --git a/tests/monster_test_grpc.js b/tests/monster_test_grpc.js
index c12d789..34f8cb2 100644
--- a/tests/monster_test_grpc.js
+++ b/tests/monster_test_grpc.js
@@ -1,30 +1,31 @@
// Generated GRPC code for FlatBuffers TS *** DO NOT EDIT ***
-import { flatbuffers } from 'flatbuffers';
-import * as MonsterStorage_fbs from './monster_test_generated';
+import * as flatbuffers from 'flatbuffers';
+import { Stat as MyGame_Example_Stat } from './my-game/example/stat';
+import { Monster as MyGame_Example_Monster } from './my-game/example/monster';
-var grpc = require('grpc');
+var grpc = require('@grpc/grpc-js');
-function serialize_Stat(buffer_args) {
- if (!(buffer_args instanceof MonsterStorage_fbs.Stat)) {
- throw new Error('Expected argument of type MonsterStorage_fbs.Stat');
+function serialize_MyGame_Example_Stat(buffer_args) {
+ if (!(buffer_args instanceof MyGame_Example_Stat)) {
+ throw new Error('Expected argument of type Stat');
}
- return buffer_args.serialize();
+ return Buffer.from(buffer_args.serialize());
}
-function deserialize_Stat(buffer) {
- return MonsterStorage_fbs.Stat.getRootAsStat(new flatbuffers.ByteBuffer(buffer))
+function deserialize_MyGame_Example_Stat(buffer) {
+ return MyGame_Example_Stat.getRootAsStat(new flatbuffers.ByteBuffer(buffer))
}
-function serialize_Monster(buffer_args) {
- if (!(buffer_args instanceof MonsterStorage_fbs.Monster)) {
- throw new Error('Expected argument of type MonsterStorage_fbs.Monster');
+function serialize_MyGame_Example_Monster(buffer_args) {
+ if (!(buffer_args instanceof MyGame_Example_Monster)) {
+ throw new Error('Expected argument of type Monster');
}
- return buffer_args.serialize();
+ return Buffer.from(buffer_args.serialize());
}
-function deserialize_Monster(buffer) {
- return MonsterStorage_fbs.Monster.getRootAsMonster(new flatbuffers.ByteBuffer(buffer))
+function deserialize_MyGame_Example_Monster(buffer) {
+ return MyGame_Example_Monster.getRootAsMonster(new flatbuffers.ByteBuffer(buffer))
}
@@ -36,44 +37,44 @@
requestStream: false,
responseStream: false,
requestType: flatbuffers.ByteBuffer,
- responseType: MonsterStorage_fbs.Stat,
- requestSerialize: serialize_Monster,
- requestDeserialize: deserialize_Monster,
- responseSerialize: serialize_Stat,
- responseDeserialize: deserialize_Stat,
+ responseType: MyGame_Example_Stat,
+ requestSerialize: serialize_MyGame_Example_Monster,
+ requestDeserialize: deserialize_MyGame_Example_Monster,
+ responseSerialize: serialize_MyGame_Example_Stat,
+ responseDeserialize: deserialize_MyGame_Example_Stat,
},
Retrieve: {
path: '/MyGame.Example.MonsterStorage/Retrieve',
requestStream: false,
responseStream: true,
requestType: flatbuffers.ByteBuffer,
- responseType: MonsterStorage_fbs.Monster,
- requestSerialize: serialize_Stat,
- requestDeserialize: deserialize_Stat,
- responseSerialize: serialize_Monster,
- responseDeserialize: deserialize_Monster,
+ responseType: MyGame_Example_Monster,
+ requestSerialize: serialize_MyGame_Example_Stat,
+ requestDeserialize: deserialize_MyGame_Example_Stat,
+ responseSerialize: serialize_MyGame_Example_Monster,
+ responseDeserialize: deserialize_MyGame_Example_Monster,
},
GetMaxHitPoint: {
path: '/MyGame.Example.MonsterStorage/GetMaxHitPoint',
requestStream: true,
responseStream: false,
requestType: flatbuffers.ByteBuffer,
- responseType: MonsterStorage_fbs.Stat,
- requestSerialize: serialize_Monster,
- requestDeserialize: deserialize_Monster,
- responseSerialize: serialize_Stat,
- responseDeserialize: deserialize_Stat,
+ responseType: MyGame_Example_Stat,
+ requestSerialize: serialize_MyGame_Example_Monster,
+ requestDeserialize: deserialize_MyGame_Example_Monster,
+ responseSerialize: serialize_MyGame_Example_Stat,
+ responseDeserialize: deserialize_MyGame_Example_Stat,
},
GetMinMaxHitPoints: {
path: '/MyGame.Example.MonsterStorage/GetMinMaxHitPoints',
requestStream: true,
responseStream: true,
requestType: flatbuffers.ByteBuffer,
- responseType: MonsterStorage_fbs.Stat,
- requestSerialize: serialize_Monster,
- requestDeserialize: deserialize_Monster,
- responseSerialize: serialize_Stat,
- responseDeserialize: deserialize_Stat,
+ responseType: MyGame_Example_Stat,
+ requestSerialize: serialize_MyGame_Example_Monster,
+ requestDeserialize: deserialize_MyGame_Example_Monster,
+ responseSerialize: serialize_MyGame_Example_Stat,
+ responseDeserialize: deserialize_MyGame_Example_Stat,
},
};
exports.MonsterStorageClient = grpc.makeGenericClientConstructor(MonsterStorageService);
diff --git a/tests/monster_test_my_game.example2_generated.dart b/tests/monster_test_my_game.example2_generated.dart
index eed14bc..24ccf72 100644
--- a/tests/monster_test_my_game.example2_generated.dart
+++ b/tests/monster_test_my_game.example2_generated.dart
@@ -1,5 +1,5 @@
// automatically generated by the FlatBuffers compiler, do not modify
-// ignore_for_file: unused_import, unused_field, unused_local_variable
+// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable
library my_game.example2;
@@ -12,11 +12,11 @@
class Monster {
Monster._(this._bc, this._bcOffset);
factory Monster(List<int> bytes) {
- fb.BufferContext rootRef = new fb.BufferContext.fromBytes(bytes);
+ final rootRef = fb.BufferContext.fromBytes(bytes);
return reader.read(rootRef, 0);
}
- static const fb.Reader<Monster> reader = const _MonsterReader();
+ static const fb.Reader<Monster> reader = _MonsterReader();
final fb.BufferContext _bc;
final int _bcOffset;
@@ -26,6 +26,26 @@
String toString() {
return 'Monster{}';
}
+
+ MonsterT unpack() => MonsterT();
+
+ static int pack(fb.Builder fbBuilder, MonsterT? object) {
+ if (object == null) return 0;
+ return object.pack(fbBuilder);
+ }
+}
+
+class MonsterT implements fb.Packable {
+ @override
+ int pack(fb.Builder fbBuilder) {
+ fbBuilder.startTable(0);
+ return fbBuilder.endTable();
+ }
+
+ @override
+ String toString() {
+ return 'MonsterT{}';
+ }
}
class _MonsterReader extends fb.TableReader<Monster> {
@@ -33,7 +53,7 @@
@override
Monster createObject(fb.BufferContext bc, int offset) =>
- new Monster._(bc, offset);
+ Monster._(bc, offset);
}
class MonsterObjectBuilder extends fb.ObjectBuilder {
@@ -42,19 +62,16 @@
/// Finish building, and store into the [fbBuilder].
@override
- int finish(
- fb.Builder fbBuilder) {
- assert(fbBuilder != null);
-
- fbBuilder.startTable();
+ int finish(fb.Builder fbBuilder) {
+ fbBuilder.startTable(0);
return fbBuilder.endTable();
}
/// Convenience method to serialize to byte list.
@override
- Uint8List toBytes([String fileIdentifier]) {
- fb.Builder fbBuilder = new fb.Builder();
- int offset = finish(fbBuilder);
- return fbBuilder.finish(offset, fileIdentifier);
+ Uint8List toBytes([String? fileIdentifier]) {
+ final fbBuilder = fb.Builder(deduplicateTables: false);
+ fbBuilder.finish(finish(fbBuilder), fileIdentifier);
+ return fbBuilder.buffer;
}
}
diff --git a/tests/monster_test_my_game.example_generated.dart b/tests/monster_test_my_game.example_generated.dart
index fa8f1ca..dd816d9 100644
--- a/tests/monster_test_my_game.example_generated.dart
+++ b/tests/monster_test_my_game.example_generated.dart
@@ -1,5 +1,5 @@
// automatically generated by the FlatBuffers compiler, do not modify
-// ignore_for_file: unused_import, unused_field, unused_local_variable
+// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable
library my_game.example;
@@ -15,26 +15,36 @@
const Color._(this.value);
factory Color.fromValue(int value) {
- if (value == null) value = 0;
- if (!values.containsKey(value)) {
- throw new StateError('Invalid value $value for bit flag enum Color');
+ final result = values[value];
+ if (result == null) {
+ if (value == 0) {
+ return Color._(0);
+ } else {
+ throw StateError('Invalid value $value for bit flag enum Color');
+ }
}
- return values[value];
+ return result;
}
+ static Color? _createOrNull(int? value) =>
+ value == null ? null : Color.fromValue(value);
+
static bool containsValue(int value) => values.containsKey(value);
- static const Color Red = const Color._(1);
+ static const Color Red = Color._(1);
/// \brief color Green
/// Green is bit_flag with value (1u << 1)
- static const Color Green = const Color._(2);
+ static const Color Green = Color._(2);
/// \brief color Blue (1u << 3)
- static const Color Blue = const Color._(8);
- static const values = {1: Red,2: Green,8: Blue,};
+ static const Color Blue = Color._(8);
+ static const Map<int, Color> values = {
+ 1: Red,
+ 2: Green,
+ 8: Blue};
- static const fb.Reader<Color> reader = const _ColorReader();
+ static const fb.Reader<Color> reader = _ColorReader();
@override
String toString() {
@@ -50,7 +60,7 @@
@override
Color read(fb.BufferContext bc, int offset) =>
- new Color.fromValue(const fb.Uint8Reader().read(bc, offset));
+ Color.fromValue(const fb.Uint8Reader().read(bc, offset));
}
class Race {
@@ -58,24 +68,31 @@
const Race._(this.value);
factory Race.fromValue(int value) {
- if (value == null) value = 0;
- if (!values.containsKey(value)) {
- throw new StateError('Invalid value $value for bit flag enum Race');
+ final result = values[value];
+ if (result == null) {
+ throw StateError('Invalid value $value for bit flag enum Race');
}
- return values[value];
+ return result;
}
+ static Race? _createOrNull(int? value) =>
+ value == null ? null : Race.fromValue(value);
+
static const int minValue = -1;
static const int maxValue = 2;
static bool containsValue(int value) => values.containsKey(value);
- static const Race None = const Race._(-1);
- static const Race Human = const Race._(0);
- static const Race Dwarf = const Race._(1);
- static const Race Elf = const Race._(2);
- static const values = {-1: None,0: Human,1: Dwarf,2: Elf,};
+ static const Race None = Race._(-1);
+ static const Race Human = Race._(0);
+ static const Race Dwarf = Race._(1);
+ static const Race Elf = Race._(2);
+ static const Map<int, Race> values = {
+ -1: None,
+ 0: Human,
+ 1: Dwarf,
+ 2: Elf};
- static const fb.Reader<Race> reader = const _RaceReader();
+ static const fb.Reader<Race> reader = _RaceReader();
@override
String toString() {
@@ -91,7 +108,55 @@
@override
Race read(fb.BufferContext bc, int offset) =>
- new Race.fromValue(const fb.Int8Reader().read(bc, offset));
+ Race.fromValue(const fb.Int8Reader().read(bc, offset));
+}
+
+class LongEnum {
+ final int value;
+ const LongEnum._(this.value);
+
+ factory LongEnum.fromValue(int value) {
+ final result = values[value];
+ if (result == null) {
+ if (value == 0) {
+ return LongEnum._(0);
+ } else {
+ throw StateError('Invalid value $value for bit flag enum LongEnum');
+ }
+ }
+ return result;
+ }
+
+ static LongEnum? _createOrNull(int? value) =>
+ value == null ? null : LongEnum.fromValue(value);
+
+ static bool containsValue(int value) => values.containsKey(value);
+
+ static const LongEnum LongOne = LongEnum._(2);
+ static const LongEnum LongTwo = LongEnum._(4);
+ static const LongEnum LongBig = LongEnum._(1099511627776);
+ static const Map<int, LongEnum> values = {
+ 2: LongOne,
+ 4: LongTwo,
+ 1099511627776: LongBig};
+
+ static const fb.Reader<LongEnum> reader = _LongEnumReader();
+
+ @override
+ String toString() {
+ return 'LongEnum{value: $value}';
+ }
+}
+
+class _LongEnumReader extends fb.Reader<LongEnum> {
+ const _LongEnumReader();
+
+ @override
+ int get size => 1;
+
+ @override
+ LongEnum read(fb.BufferContext bc, int offset) =>
+ LongEnum.fromValue(const fb.Uint64Reader().read(bc, offset));
}
class AnyTypeId {
@@ -99,24 +164,31 @@
const AnyTypeId._(this.value);
factory AnyTypeId.fromValue(int value) {
- if (value == null) value = 0;
- if (!values.containsKey(value)) {
- throw new StateError('Invalid value $value for bit flag enum AnyTypeId');
+ final result = values[value];
+ if (result == null) {
+ throw StateError('Invalid value $value for bit flag enum AnyTypeId');
}
- return values[value];
+ return result;
}
+ static AnyTypeId? _createOrNull(int? value) =>
+ value == null ? null : AnyTypeId.fromValue(value);
+
static const int minValue = 0;
static const int maxValue = 3;
static bool containsValue(int value) => values.containsKey(value);
- static const AnyTypeId NONE = const AnyTypeId._(0);
- static const AnyTypeId Monster = const AnyTypeId._(1);
- static const AnyTypeId TestSimpleTableWithEnum = const AnyTypeId._(2);
- static const AnyTypeId MyGame_Example2_Monster = const AnyTypeId._(3);
- static const values = {0: NONE,1: Monster,2: TestSimpleTableWithEnum,3: MyGame_Example2_Monster,};
+ static const AnyTypeId NONE = AnyTypeId._(0);
+ static const AnyTypeId Monster = AnyTypeId._(1);
+ static const AnyTypeId TestSimpleTableWithEnum = AnyTypeId._(2);
+ static const AnyTypeId MyGame_Example2_Monster = AnyTypeId._(3);
+ static const Map<int, AnyTypeId> values = {
+ 0: NONE,
+ 1: Monster,
+ 2: TestSimpleTableWithEnum,
+ 3: MyGame_Example2_Monster};
- static const fb.Reader<AnyTypeId> reader = const _AnyTypeIdReader();
+ static const fb.Reader<AnyTypeId> reader = _AnyTypeIdReader();
@override
String toString() {
@@ -132,7 +204,7 @@
@override
AnyTypeId read(fb.BufferContext bc, int offset) =>
- new AnyTypeId.fromValue(const fb.Uint8Reader().read(bc, offset));
+ AnyTypeId.fromValue(const fb.Uint8Reader().read(bc, offset));
}
class AnyUniqueAliasesTypeId {
@@ -140,24 +212,31 @@
const AnyUniqueAliasesTypeId._(this.value);
factory AnyUniqueAliasesTypeId.fromValue(int value) {
- if (value == null) value = 0;
- if (!values.containsKey(value)) {
- throw new StateError('Invalid value $value for bit flag enum AnyUniqueAliasesTypeId');
+ final result = values[value];
+ if (result == null) {
+ throw StateError('Invalid value $value for bit flag enum AnyUniqueAliasesTypeId');
}
- return values[value];
+ return result;
}
+ static AnyUniqueAliasesTypeId? _createOrNull(int? value) =>
+ value == null ? null : AnyUniqueAliasesTypeId.fromValue(value);
+
static const int minValue = 0;
static const int maxValue = 3;
static bool containsValue(int value) => values.containsKey(value);
- static const AnyUniqueAliasesTypeId NONE = const AnyUniqueAliasesTypeId._(0);
- static const AnyUniqueAliasesTypeId M = const AnyUniqueAliasesTypeId._(1);
- static const AnyUniqueAliasesTypeId TS = const AnyUniqueAliasesTypeId._(2);
- static const AnyUniqueAliasesTypeId M2 = const AnyUniqueAliasesTypeId._(3);
- static const values = {0: NONE,1: M,2: TS,3: M2,};
+ static const AnyUniqueAliasesTypeId NONE = AnyUniqueAliasesTypeId._(0);
+ static const AnyUniqueAliasesTypeId M = AnyUniqueAliasesTypeId._(1);
+ static const AnyUniqueAliasesTypeId TS = AnyUniqueAliasesTypeId._(2);
+ static const AnyUniqueAliasesTypeId M2 = AnyUniqueAliasesTypeId._(3);
+ static const Map<int, AnyUniqueAliasesTypeId> values = {
+ 0: NONE,
+ 1: M,
+ 2: TS,
+ 3: M2};
- static const fb.Reader<AnyUniqueAliasesTypeId> reader = const _AnyUniqueAliasesTypeIdReader();
+ static const fb.Reader<AnyUniqueAliasesTypeId> reader = _AnyUniqueAliasesTypeIdReader();
@override
String toString() {
@@ -173,7 +252,7 @@
@override
AnyUniqueAliasesTypeId read(fb.BufferContext bc, int offset) =>
- new AnyUniqueAliasesTypeId.fromValue(const fb.Uint8Reader().read(bc, offset));
+ AnyUniqueAliasesTypeId.fromValue(const fb.Uint8Reader().read(bc, offset));
}
class AnyAmbiguousAliasesTypeId {
@@ -181,24 +260,31 @@
const AnyAmbiguousAliasesTypeId._(this.value);
factory AnyAmbiguousAliasesTypeId.fromValue(int value) {
- if (value == null) value = 0;
- if (!values.containsKey(value)) {
- throw new StateError('Invalid value $value for bit flag enum AnyAmbiguousAliasesTypeId');
+ final result = values[value];
+ if (result == null) {
+ throw StateError('Invalid value $value for bit flag enum AnyAmbiguousAliasesTypeId');
}
- return values[value];
+ return result;
}
+ static AnyAmbiguousAliasesTypeId? _createOrNull(int? value) =>
+ value == null ? null : AnyAmbiguousAliasesTypeId.fromValue(value);
+
static const int minValue = 0;
static const int maxValue = 3;
static bool containsValue(int value) => values.containsKey(value);
- static const AnyAmbiguousAliasesTypeId NONE = const AnyAmbiguousAliasesTypeId._(0);
- static const AnyAmbiguousAliasesTypeId M1 = const AnyAmbiguousAliasesTypeId._(1);
- static const AnyAmbiguousAliasesTypeId M2 = const AnyAmbiguousAliasesTypeId._(2);
- static const AnyAmbiguousAliasesTypeId M3 = const AnyAmbiguousAliasesTypeId._(3);
- static const values = {0: NONE,1: M1,2: M2,3: M3,};
+ static const AnyAmbiguousAliasesTypeId NONE = AnyAmbiguousAliasesTypeId._(0);
+ static const AnyAmbiguousAliasesTypeId M1 = AnyAmbiguousAliasesTypeId._(1);
+ static const AnyAmbiguousAliasesTypeId M2 = AnyAmbiguousAliasesTypeId._(2);
+ static const AnyAmbiguousAliasesTypeId M3 = AnyAmbiguousAliasesTypeId._(3);
+ static const Map<int, AnyAmbiguousAliasesTypeId> values = {
+ 0: NONE,
+ 1: M1,
+ 2: M2,
+ 3: M3};
- static const fb.Reader<AnyAmbiguousAliasesTypeId> reader = const _AnyAmbiguousAliasesTypeIdReader();
+ static const fb.Reader<AnyAmbiguousAliasesTypeId> reader = _AnyAmbiguousAliasesTypeIdReader();
@override
String toString() {
@@ -214,13 +300,13 @@
@override
AnyAmbiguousAliasesTypeId read(fb.BufferContext bc, int offset) =>
- new AnyAmbiguousAliasesTypeId.fromValue(const fb.Uint8Reader().read(bc, offset));
+ AnyAmbiguousAliasesTypeId.fromValue(const fb.Uint8Reader().read(bc, offset));
}
class Test {
Test._(this._bc, this._bcOffset);
- static const fb.Reader<Test> reader = const _TestReader();
+ static const fb.Reader<Test> reader = _TestReader();
final fb.BufferContext _bc;
final int _bcOffset;
@@ -232,6 +318,37 @@
String toString() {
return 'Test{a: $a, b: $b}';
}
+
+ TestT unpack() => TestT(
+ a: a,
+ b: b);
+
+ static int pack(fb.Builder fbBuilder, TestT? object) {
+ if (object == null) return 0;
+ return object.pack(fbBuilder);
+ }
+}
+
+class TestT implements fb.Packable {
+ int a;
+ int b;
+
+ TestT({
+ required this.a,
+ required this.b});
+
+ @override
+ int pack(fb.Builder fbBuilder) {
+ fbBuilder.pad(1);
+ fbBuilder.putInt8(b);
+ fbBuilder.putInt16(a);
+ return fbBuilder.offset;
+ }
+
+ @override
+ String toString() {
+ return 'TestT{a: $a, b: $b}';
+ }
}
class _TestReader extends fb.StructReader<Test> {
@@ -242,13 +359,11 @@
@override
Test createObject(fb.BufferContext bc, int offset) =>
- new Test._(bc, offset);
+ Test._(bc, offset);
}
class TestBuilder {
- TestBuilder(this.fbBuilder) {
- assert(fbBuilder != null);
- }
+ TestBuilder(this.fbBuilder);
final fb.Builder fbBuilder;
@@ -266,18 +381,15 @@
final int _b;
TestObjectBuilder({
- int a,
- int b,
+ required int a,
+ required int b,
})
: _a = a,
_b = b;
/// Finish building, and store into the [fbBuilder].
@override
- int finish(
- fb.Builder fbBuilder) {
- assert(fbBuilder != null);
-
+ int finish(fb.Builder fbBuilder) {
fbBuilder.pad(1);
fbBuilder.putInt8(_b);
fbBuilder.putInt16(_a);
@@ -286,30 +398,57 @@
/// Convenience method to serialize to byte list.
@override
- Uint8List toBytes([String fileIdentifier]) {
- fb.Builder fbBuilder = new fb.Builder();
- int offset = finish(fbBuilder);
- return fbBuilder.finish(offset, fileIdentifier);
+ Uint8List toBytes([String? fileIdentifier]) {
+ final fbBuilder = fb.Builder(deduplicateTables: false);
+ fbBuilder.finish(finish(fbBuilder), fileIdentifier);
+ return fbBuilder.buffer;
}
}
class TestSimpleTableWithEnum {
TestSimpleTableWithEnum._(this._bc, this._bcOffset);
factory TestSimpleTableWithEnum(List<int> bytes) {
- fb.BufferContext rootRef = new fb.BufferContext.fromBytes(bytes);
+ final rootRef = fb.BufferContext.fromBytes(bytes);
return reader.read(rootRef, 0);
}
- static const fb.Reader<TestSimpleTableWithEnum> reader = const _TestSimpleTableWithEnumReader();
+ static const fb.Reader<TestSimpleTableWithEnum> reader = _TestSimpleTableWithEnumReader();
final fb.BufferContext _bc;
final int _bcOffset;
- Color get color => new Color.fromValue(const fb.Uint8Reader().vTableGet(_bc, _bcOffset, 4, 2));
+ Color get color => Color.fromValue(const fb.Uint8Reader().vTableGet(_bc, _bcOffset, 4, 2));
@override
String toString() {
return 'TestSimpleTableWithEnum{color: $color}';
}
+
+ TestSimpleTableWithEnumT unpack() => TestSimpleTableWithEnumT(
+ color: color);
+
+ static int pack(fb.Builder fbBuilder, TestSimpleTableWithEnumT? object) {
+ if (object == null) return 0;
+ return object.pack(fbBuilder);
+ }
+}
+
+class TestSimpleTableWithEnumT implements fb.Packable {
+ Color color;
+
+ TestSimpleTableWithEnumT({
+ this.color = Color.Green});
+
+ @override
+ int pack(fb.Builder fbBuilder) {
+ fbBuilder.startTable(1);
+ fbBuilder.addUint8(0, color.value);
+ return fbBuilder.endTable();
+ }
+
+ @override
+ String toString() {
+ return 'TestSimpleTableWithEnumT{color: $color}';
+ }
}
class _TestSimpleTableWithEnumReader extends fb.TableReader<TestSimpleTableWithEnum> {
@@ -317,21 +456,19 @@
@override
TestSimpleTableWithEnum createObject(fb.BufferContext bc, int offset) =>
- new TestSimpleTableWithEnum._(bc, offset);
+ TestSimpleTableWithEnum._(bc, offset);
}
class TestSimpleTableWithEnumBuilder {
- TestSimpleTableWithEnumBuilder(this.fbBuilder) {
- assert(fbBuilder != null);
- }
+ TestSimpleTableWithEnumBuilder(this.fbBuilder);
final fb.Builder fbBuilder;
void begin() {
- fbBuilder.startTable();
+ fbBuilder.startTable(1);
}
- int addColor(Color color) {
+ int addColor(Color? color) {
fbBuilder.addUint8(0, color?.value);
return fbBuilder.offset;
}
@@ -342,36 +479,33 @@
}
class TestSimpleTableWithEnumObjectBuilder extends fb.ObjectBuilder {
- final Color _color;
+ final Color? _color;
TestSimpleTableWithEnumObjectBuilder({
- Color color,
+ Color? color,
})
: _color = color;
/// Finish building, and store into the [fbBuilder].
@override
- int finish(
- fb.Builder fbBuilder) {
- assert(fbBuilder != null);
-
- fbBuilder.startTable();
+ int finish(fb.Builder fbBuilder) {
+ fbBuilder.startTable(1);
fbBuilder.addUint8(0, _color?.value);
return fbBuilder.endTable();
}
/// Convenience method to serialize to byte list.
@override
- Uint8List toBytes([String fileIdentifier]) {
- fb.Builder fbBuilder = new fb.Builder();
- int offset = finish(fbBuilder);
- return fbBuilder.finish(offset, fileIdentifier);
+ Uint8List toBytes([String? fileIdentifier]) {
+ final fbBuilder = fb.Builder(deduplicateTables: false);
+ fbBuilder.finish(finish(fbBuilder), fileIdentifier);
+ return fbBuilder.buffer;
}
}
class Vec3 {
Vec3._(this._bc, this._bcOffset);
- static const fb.Reader<Vec3> reader = const _Vec3Reader();
+ static const fb.Reader<Vec3> reader = _Vec3Reader();
final fb.BufferContext _bc;
final int _bcOffset;
@@ -380,13 +514,62 @@
double get y => const fb.Float32Reader().read(_bc, _bcOffset + 4);
double get z => const fb.Float32Reader().read(_bc, _bcOffset + 8);
double get test1 => const fb.Float64Reader().read(_bc, _bcOffset + 16);
- Color get test2 => new Color.fromValue(const fb.Uint8Reader().read(_bc, _bcOffset + 24));
+ Color get test2 => Color.fromValue(const fb.Uint8Reader().read(_bc, _bcOffset + 24));
Test get test3 => Test.reader.read(_bc, _bcOffset + 26);
@override
String toString() {
return 'Vec3{x: $x, y: $y, z: $z, test1: $test1, test2: $test2, test3: $test3}';
}
+
+ Vec3T unpack() => Vec3T(
+ x: x,
+ y: y,
+ z: z,
+ test1: test1,
+ test2: test2,
+ test3: test3.unpack());
+
+ static int pack(fb.Builder fbBuilder, Vec3T? object) {
+ if (object == null) return 0;
+ return object.pack(fbBuilder);
+ }
+}
+
+class Vec3T implements fb.Packable {
+ double x;
+ double y;
+ double z;
+ double test1;
+ Color test2;
+ TestT test3;
+
+ Vec3T({
+ required this.x,
+ required this.y,
+ required this.z,
+ required this.test1,
+ required this.test2,
+ required this.test3});
+
+ @override
+ int pack(fb.Builder fbBuilder) {
+ fbBuilder.pad(2);
+ test3.pack(fbBuilder);
+ fbBuilder.pad(1);
+ fbBuilder.putUint8(test2.value);
+ fbBuilder.putFloat64(test1);
+ fbBuilder.pad(4);
+ fbBuilder.putFloat32(z);
+ fbBuilder.putFloat32(y);
+ fbBuilder.putFloat32(x);
+ return fbBuilder.offset;
+ }
+
+ @override
+ String toString() {
+ return 'Vec3T{x: $x, y: $y, z: $z, test1: $test1, test2: $test2, test3: $test3}';
+ }
}
class _Vec3Reader extends fb.StructReader<Vec3> {
@@ -397,13 +580,11 @@
@override
Vec3 createObject(fb.BufferContext bc, int offset) =>
- new Vec3._(bc, offset);
+ Vec3._(bc, offset);
}
class Vec3Builder {
- Vec3Builder(this.fbBuilder) {
- assert(fbBuilder != null);
- }
+ Vec3Builder(this.fbBuilder);
final fb.Builder fbBuilder;
@@ -411,7 +592,7 @@
fbBuilder.pad(2);
test3();
fbBuilder.pad(1);
- fbBuilder.putUint8(test2?.value);
+ fbBuilder.putUint8(test2.value);
fbBuilder.putFloat64(test1);
fbBuilder.pad(4);
fbBuilder.putFloat32(z);
@@ -431,12 +612,12 @@
final TestObjectBuilder _test3;
Vec3ObjectBuilder({
- double x,
- double y,
- double z,
- double test1,
- Color test2,
- TestObjectBuilder test3,
+ required double x,
+ required double y,
+ required double z,
+ required double test1,
+ required Color test2,
+ required TestObjectBuilder test3,
})
: _x = x,
_y = y,
@@ -447,14 +628,11 @@
/// Finish building, and store into the [fbBuilder].
@override
- int finish(
- fb.Builder fbBuilder) {
- assert(fbBuilder != null);
-
+ int finish(fb.Builder fbBuilder) {
fbBuilder.pad(2);
_test3.finish(fbBuilder);
fbBuilder.pad(1);
- fbBuilder.putUint8(_test2?.value);
+ fbBuilder.putUint8(_test2.value);
fbBuilder.putFloat64(_test1);
fbBuilder.pad(4);
fbBuilder.putFloat32(_z);
@@ -465,16 +643,16 @@
/// Convenience method to serialize to byte list.
@override
- Uint8List toBytes([String fileIdentifier]) {
- fb.Builder fbBuilder = new fb.Builder();
- int offset = finish(fbBuilder);
- return fbBuilder.finish(offset, fileIdentifier);
+ Uint8List toBytes([String? fileIdentifier]) {
+ final fbBuilder = fb.Builder(deduplicateTables: false);
+ fbBuilder.finish(finish(fbBuilder), fileIdentifier);
+ return fbBuilder.buffer;
}
}
class Ability {
Ability._(this._bc, this._bcOffset);
- static const fb.Reader<Ability> reader = const _AbilityReader();
+ static const fb.Reader<Ability> reader = _AbilityReader();
final fb.BufferContext _bc;
final int _bcOffset;
@@ -486,6 +664,36 @@
String toString() {
return 'Ability{id: $id, distance: $distance}';
}
+
+ AbilityT unpack() => AbilityT(
+ id: id,
+ distance: distance);
+
+ static int pack(fb.Builder fbBuilder, AbilityT? object) {
+ if (object == null) return 0;
+ return object.pack(fbBuilder);
+ }
+}
+
+class AbilityT implements fb.Packable {
+ int id;
+ int distance;
+
+ AbilityT({
+ required this.id,
+ required this.distance});
+
+ @override
+ int pack(fb.Builder fbBuilder) {
+ fbBuilder.putUint32(distance);
+ fbBuilder.putUint32(id);
+ return fbBuilder.offset;
+ }
+
+ @override
+ String toString() {
+ return 'AbilityT{id: $id, distance: $distance}';
+ }
}
class _AbilityReader extends fb.StructReader<Ability> {
@@ -496,13 +704,11 @@
@override
Ability createObject(fb.BufferContext bc, int offset) =>
- new Ability._(bc, offset);
+ Ability._(bc, offset);
}
class AbilityBuilder {
- AbilityBuilder(this.fbBuilder) {
- assert(fbBuilder != null);
- }
+ AbilityBuilder(this.fbBuilder);
final fb.Builder fbBuilder;
@@ -519,18 +725,15 @@
final int _distance;
AbilityObjectBuilder({
- int id,
- int distance,
+ required int id,
+ required int distance,
})
: _id = id,
_distance = distance;
/// Finish building, and store into the [fbBuilder].
@override
- int finish(
- fb.Builder fbBuilder) {
- assert(fbBuilder != null);
-
+ int finish(fb.Builder fbBuilder) {
fbBuilder.putUint32(_distance);
fbBuilder.putUint32(_id);
return fbBuilder.offset;
@@ -538,25 +741,133 @@
/// Convenience method to serialize to byte list.
@override
- Uint8List toBytes([String fileIdentifier]) {
- fb.Builder fbBuilder = new fb.Builder();
- int offset = finish(fbBuilder);
- return fbBuilder.finish(offset, fileIdentifier);
+ Uint8List toBytes([String? fileIdentifier]) {
+ final fbBuilder = fb.Builder(deduplicateTables: false);
+ fbBuilder.finish(finish(fbBuilder), fileIdentifier);
+ return fbBuilder.buffer;
+ }
+}
+class StructOfStructs {
+ StructOfStructs._(this._bc, this._bcOffset);
+
+ static const fb.Reader<StructOfStructs> reader = _StructOfStructsReader();
+
+ final fb.BufferContext _bc;
+ final int _bcOffset;
+
+ Ability get a => Ability.reader.read(_bc, _bcOffset + 0);
+ Test get b => Test.reader.read(_bc, _bcOffset + 8);
+ Ability get c => Ability.reader.read(_bc, _bcOffset + 12);
+
+ @override
+ String toString() {
+ return 'StructOfStructs{a: $a, b: $b, c: $c}';
+ }
+
+ StructOfStructsT unpack() => StructOfStructsT(
+ a: a.unpack(),
+ b: b.unpack(),
+ c: c.unpack());
+
+ static int pack(fb.Builder fbBuilder, StructOfStructsT? object) {
+ if (object == null) return 0;
+ return object.pack(fbBuilder);
+ }
+}
+
+class StructOfStructsT implements fb.Packable {
+ AbilityT a;
+ TestT b;
+ AbilityT c;
+
+ StructOfStructsT({
+ required this.a,
+ required this.b,
+ required this.c});
+
+ @override
+ int pack(fb.Builder fbBuilder) {
+ c.pack(fbBuilder);
+ b.pack(fbBuilder);
+ a.pack(fbBuilder);
+ return fbBuilder.offset;
+ }
+
+ @override
+ String toString() {
+ return 'StructOfStructsT{a: $a, b: $b, c: $c}';
+ }
+}
+
+class _StructOfStructsReader extends fb.StructReader<StructOfStructs> {
+ const _StructOfStructsReader();
+
+ @override
+ int get size => 20;
+
+ @override
+ StructOfStructs createObject(fb.BufferContext bc, int offset) =>
+ StructOfStructs._(bc, offset);
+}
+
+class StructOfStructsBuilder {
+ StructOfStructsBuilder(this.fbBuilder);
+
+ final fb.Builder fbBuilder;
+
+ int finish(fb.StructBuilder a, fb.StructBuilder b, fb.StructBuilder c) {
+ c();
+ b();
+ a();
+ return fbBuilder.offset;
+ }
+
+}
+
+class StructOfStructsObjectBuilder extends fb.ObjectBuilder {
+ final AbilityObjectBuilder _a;
+ final TestObjectBuilder _b;
+ final AbilityObjectBuilder _c;
+
+ StructOfStructsObjectBuilder({
+ required AbilityObjectBuilder a,
+ required TestObjectBuilder b,
+ required AbilityObjectBuilder c,
+ })
+ : _a = a,
+ _b = b,
+ _c = c;
+
+ /// Finish building, and store into the [fbBuilder].
+ @override
+ int finish(fb.Builder fbBuilder) {
+ _c.finish(fbBuilder);
+ _b.finish(fbBuilder);
+ _a.finish(fbBuilder);
+ return fbBuilder.offset;
+ }
+
+ /// Convenience method to serialize to byte list.
+ @override
+ Uint8List toBytes([String? fileIdentifier]) {
+ final fbBuilder = fb.Builder(deduplicateTables: false);
+ fbBuilder.finish(finish(fbBuilder), fileIdentifier);
+ return fbBuilder.buffer;
}
}
class Stat {
Stat._(this._bc, this._bcOffset);
factory Stat(List<int> bytes) {
- fb.BufferContext rootRef = new fb.BufferContext.fromBytes(bytes);
+ final rootRef = fb.BufferContext.fromBytes(bytes);
return reader.read(rootRef, 0);
}
- static const fb.Reader<Stat> reader = const _StatReader();
+ static const fb.Reader<Stat> reader = _StatReader();
final fb.BufferContext _bc;
final int _bcOffset;
- String get id => const fb.StringReader().vTableGet(_bc, _bcOffset, 4, null);
+ String? get id => const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 4);
int get val => const fb.Int64Reader().vTableGet(_bc, _bcOffset, 6, 0);
int get count => const fb.Uint16Reader().vTableGet(_bc, _bcOffset, 8, 0);
@@ -564,6 +875,43 @@
String toString() {
return 'Stat{id: $id, val: $val, count: $count}';
}
+
+ StatT unpack() => StatT(
+ id: id,
+ val: val,
+ count: count);
+
+ static int pack(fb.Builder fbBuilder, StatT? object) {
+ if (object == null) return 0;
+ return object.pack(fbBuilder);
+ }
+}
+
+class StatT implements fb.Packable {
+ String? id;
+ int val;
+ int count;
+
+ StatT({
+ this.id,
+ this.val = 0,
+ this.count = 0});
+
+ @override
+ int pack(fb.Builder fbBuilder) {
+ final int? idOffset = id == null ? null
+ : fbBuilder.writeString(id!);
+ fbBuilder.startTable(3);
+ fbBuilder.addOffset(0, idOffset);
+ fbBuilder.addInt64(1, val);
+ fbBuilder.addUint16(2, count);
+ return fbBuilder.endTable();
+ }
+
+ @override
+ String toString() {
+ return 'StatT{id: $id, val: $val, count: $count}';
+ }
}
class _StatReader extends fb.TableReader<Stat> {
@@ -571,29 +919,27 @@
@override
Stat createObject(fb.BufferContext bc, int offset) =>
- new Stat._(bc, offset);
+ Stat._(bc, offset);
}
class StatBuilder {
- StatBuilder(this.fbBuilder) {
- assert(fbBuilder != null);
- }
+ StatBuilder(this.fbBuilder);
final fb.Builder fbBuilder;
void begin() {
- fbBuilder.startTable();
+ fbBuilder.startTable(3);
}
- int addIdOffset(int offset) {
+ int addIdOffset(int? offset) {
fbBuilder.addOffset(0, offset);
return fbBuilder.offset;
}
- int addVal(int val) {
+ int addVal(int? val) {
fbBuilder.addInt64(1, val);
return fbBuilder.offset;
}
- int addCount(int count) {
+ int addCount(int? count) {
fbBuilder.addUint16(2, count);
return fbBuilder.offset;
}
@@ -604,14 +950,14 @@
}
class StatObjectBuilder extends fb.ObjectBuilder {
- final String _id;
- final int _val;
- final int _count;
+ final String? _id;
+ final int? _val;
+ final int? _count;
StatObjectBuilder({
- String id,
- int val,
- int count,
+ String? id,
+ int? val,
+ int? count,
})
: _id = id,
_val = val,
@@ -619,15 +965,11 @@
/// Finish building, and store into the [fbBuilder].
@override
- int finish(
- fb.Builder fbBuilder) {
- assert(fbBuilder != null);
- final int idOffset = fbBuilder.writeString(_id);
-
- fbBuilder.startTable();
- if (idOffset != null) {
- fbBuilder.addOffset(0, idOffset);
- }
+ int finish(fb.Builder fbBuilder) {
+ final int? idOffset = _id == null ? null
+ : fbBuilder.writeString(_id!);
+ fbBuilder.startTable(3);
+ fbBuilder.addOffset(0, idOffset);
fbBuilder.addInt64(1, _val);
fbBuilder.addUint16(2, _count);
return fbBuilder.endTable();
@@ -635,20 +977,20 @@
/// Convenience method to serialize to byte list.
@override
- Uint8List toBytes([String fileIdentifier]) {
- fb.Builder fbBuilder = new fb.Builder();
- int offset = finish(fbBuilder);
- return fbBuilder.finish(offset, fileIdentifier);
+ Uint8List toBytes([String? fileIdentifier]) {
+ final fbBuilder = fb.Builder(deduplicateTables: false);
+ fbBuilder.finish(finish(fbBuilder), fileIdentifier);
+ return fbBuilder.buffer;
}
}
class Referrable {
Referrable._(this._bc, this._bcOffset);
factory Referrable(List<int> bytes) {
- fb.BufferContext rootRef = new fb.BufferContext.fromBytes(bytes);
+ final rootRef = fb.BufferContext.fromBytes(bytes);
return reader.read(rootRef, 0);
}
- static const fb.Reader<Referrable> reader = const _ReferrableReader();
+ static const fb.Reader<Referrable> reader = _ReferrableReader();
final fb.BufferContext _bc;
final int _bcOffset;
@@ -659,6 +1001,33 @@
String toString() {
return 'Referrable{id: $id}';
}
+
+ ReferrableT unpack() => ReferrableT(
+ id: id);
+
+ static int pack(fb.Builder fbBuilder, ReferrableT? object) {
+ if (object == null) return 0;
+ return object.pack(fbBuilder);
+ }
+}
+
+class ReferrableT implements fb.Packable {
+ int id;
+
+ ReferrableT({
+ this.id = 0});
+
+ @override
+ int pack(fb.Builder fbBuilder) {
+ fbBuilder.startTable(1);
+ fbBuilder.addUint64(0, id);
+ return fbBuilder.endTable();
+ }
+
+ @override
+ String toString() {
+ return 'ReferrableT{id: $id}';
+ }
}
class _ReferrableReader extends fb.TableReader<Referrable> {
@@ -666,21 +1035,19 @@
@override
Referrable createObject(fb.BufferContext bc, int offset) =>
- new Referrable._(bc, offset);
+ Referrable._(bc, offset);
}
class ReferrableBuilder {
- ReferrableBuilder(this.fbBuilder) {
- assert(fbBuilder != null);
- }
+ ReferrableBuilder(this.fbBuilder);
final fb.Builder fbBuilder;
void begin() {
- fbBuilder.startTable();
+ fbBuilder.startTable(1);
}
- int addId(int id) {
+ int addId(int? id) {
fbBuilder.addUint64(0, id);
return fbBuilder.offset;
}
@@ -691,68 +1058,65 @@
}
class ReferrableObjectBuilder extends fb.ObjectBuilder {
- final int _id;
+ final int? _id;
ReferrableObjectBuilder({
- int id,
+ int? id,
})
: _id = id;
/// Finish building, and store into the [fbBuilder].
@override
- int finish(
- fb.Builder fbBuilder) {
- assert(fbBuilder != null);
-
- fbBuilder.startTable();
+ int finish(fb.Builder fbBuilder) {
+ fbBuilder.startTable(1);
fbBuilder.addUint64(0, _id);
return fbBuilder.endTable();
}
/// Convenience method to serialize to byte list.
@override
- Uint8List toBytes([String fileIdentifier]) {
- fb.Builder fbBuilder = new fb.Builder();
- int offset = finish(fbBuilder);
- return fbBuilder.finish(offset, fileIdentifier);
+ Uint8List toBytes([String? fileIdentifier]) {
+ final fbBuilder = fb.Builder(deduplicateTables: false);
+ fbBuilder.finish(finish(fbBuilder), fileIdentifier);
+ return fbBuilder.buffer;
}
}
/// an example documentation comment: "monster object"
class Monster {
Monster._(this._bc, this._bcOffset);
factory Monster(List<int> bytes) {
- fb.BufferContext rootRef = new fb.BufferContext.fromBytes(bytes);
+ final rootRef = fb.BufferContext.fromBytes(bytes);
return reader.read(rootRef, 0);
}
- static const fb.Reader<Monster> reader = const _MonsterReader();
+ static const fb.Reader<Monster> reader = _MonsterReader();
final fb.BufferContext _bc;
final int _bcOffset;
- Vec3 get pos => Vec3.reader.vTableGet(_bc, _bcOffset, 4, null);
+ Vec3? get pos => Vec3.reader.vTableGetNullable(_bc, _bcOffset, 4);
int get mana => const fb.Int16Reader().vTableGet(_bc, _bcOffset, 6, 150);
int get hp => const fb.Int16Reader().vTableGet(_bc, _bcOffset, 8, 100);
- String get name => const fb.StringReader().vTableGet(_bc, _bcOffset, 10, null);
- List<int> get inventory => const fb.ListReader<int>(const fb.Uint8Reader()).vTableGet(_bc, _bcOffset, 14, null);
- Color get color => new Color.fromValue(const fb.Uint8Reader().vTableGet(_bc, _bcOffset, 16, 8));
- AnyTypeId get testType => new AnyTypeId.fromValue(const fb.Uint8Reader().vTableGet(_bc, _bcOffset, 18, 0));
+ String? get name => const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 10);
+ List<int>? get inventory => const fb.Uint8ListReader().vTableGetNullable(_bc, _bcOffset, 14);
+ Color get color => Color.fromValue(const fb.Uint8Reader().vTableGet(_bc, _bcOffset, 16, 8));
+ AnyTypeId? get testType => AnyTypeId._createOrNull(const fb.Uint8Reader().vTableGetNullable(_bc, _bcOffset, 18));
dynamic get test {
switch (testType?.value) {
- case 1: return Monster.reader.vTableGet(_bc, _bcOffset, 20, null);
- case 2: return TestSimpleTableWithEnum.reader.vTableGet(_bc, _bcOffset, 20, null);
- case 3: return my_game_example2.Monster.reader.vTableGet(_bc, _bcOffset, 20, null);
+ case 1: return Monster.reader.vTableGetNullable(_bc, _bcOffset, 20);
+ case 2: return TestSimpleTableWithEnum.reader.vTableGetNullable(_bc, _bcOffset, 20);
+ case 3: return my_game_example2.Monster.reader.vTableGetNullable(_bc, _bcOffset, 20);
default: return null;
}
}
- List<Test> get test4 => const fb.ListReader<Test>(Test.reader).vTableGet(_bc, _bcOffset, 22, null);
- List<String> get testarrayofstring => const fb.ListReader<String>(const fb.StringReader()).vTableGet(_bc, _bcOffset, 24, null);
+ List<Test>? get test4 => const fb.ListReader<Test>(Test.reader).vTableGetNullable(_bc, _bcOffset, 22);
+ List<String>? get testarrayofstring => const fb.ListReader<String>(fb.StringReader()).vTableGetNullable(_bc, _bcOffset, 24);
/// an example documentation comment: this will end up in the generated code
/// multiline too
- List<Monster> get testarrayoftables => const fb.ListReader<Monster>(Monster.reader).vTableGet(_bc, _bcOffset, 26, null);
- Monster get enemy => Monster.reader.vTableGet(_bc, _bcOffset, 28, null);
- List<int> get testnestedflatbuffer => const fb.ListReader<int>(const fb.Uint8Reader()).vTableGet(_bc, _bcOffset, 30, null);
- Stat get testempty => Stat.reader.vTableGet(_bc, _bcOffset, 32, null);
+ List<Monster>? get testarrayoftables => const fb.ListReader<Monster>(Monster.reader).vTableGetNullable(_bc, _bcOffset, 26);
+ Monster? get enemy => Monster.reader.vTableGetNullable(_bc, _bcOffset, 28);
+ List<int>? get testnestedflatbuffer => const fb.Uint8ListReader().vTableGetNullable(_bc, _bcOffset, 30);
+ Stat? get testempty => Stat.reader.vTableGetNullable(_bc, _bcOffset, 32);
bool get testbool => const fb.BoolReader().vTableGet(_bc, _bcOffset, 34, false);
int get testhashs32Fnv1 => const fb.Int32Reader().vTableGet(_bc, _bcOffset, 36, 0);
int get testhashu32Fnv1 => const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 38, 0);
@@ -762,50 +1126,353 @@
int get testhashu32Fnv1a => const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 46, 0);
int get testhashs64Fnv1a => const fb.Int64Reader().vTableGet(_bc, _bcOffset, 48, 0);
int get testhashu64Fnv1a => const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 50, 0);
- List<bool> get testarrayofbools => const fb.ListReader<bool>(const fb.BoolReader()).vTableGet(_bc, _bcOffset, 52, null);
+ List<bool>? get testarrayofbools => const fb.ListReader<bool>(fb.BoolReader()).vTableGetNullable(_bc, _bcOffset, 52);
double get testf => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 54, 3.14159);
double get testf2 => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 56, 3.0);
double get testf3 => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 58, 0.0);
- List<String> get testarrayofstring2 => const fb.ListReader<String>(const fb.StringReader()).vTableGet(_bc, _bcOffset, 60, null);
- List<Ability> get testarrayofsortedstruct => const fb.ListReader<Ability>(Ability.reader).vTableGet(_bc, _bcOffset, 62, null);
- List<int> get flex => const fb.ListReader<int>(const fb.Uint8Reader()).vTableGet(_bc, _bcOffset, 64, null);
- List<Test> get test5 => const fb.ListReader<Test>(Test.reader).vTableGet(_bc, _bcOffset, 66, null);
- List<int> get vectorOfLongs => const fb.ListReader<int>(const fb.Int64Reader()).vTableGet(_bc, _bcOffset, 68, null);
- List<double> get vectorOfDoubles => const fb.ListReader<double>(const fb.Float64Reader()).vTableGet(_bc, _bcOffset, 70, null);
- my_game.InParentNamespace get parentNamespaceTest => my_game.InParentNamespace.reader.vTableGet(_bc, _bcOffset, 72, null);
- List<Referrable> get vectorOfReferrables => const fb.ListReader<Referrable>(Referrable.reader).vTableGet(_bc, _bcOffset, 74, null);
+ List<String>? get testarrayofstring2 => const fb.ListReader<String>(fb.StringReader()).vTableGetNullable(_bc, _bcOffset, 60);
+ List<Ability>? get testarrayofsortedstruct => const fb.ListReader<Ability>(Ability.reader).vTableGetNullable(_bc, _bcOffset, 62);
+ List<int>? get flex => const fb.Uint8ListReader().vTableGetNullable(_bc, _bcOffset, 64);
+ List<Test>? get test5 => const fb.ListReader<Test>(Test.reader).vTableGetNullable(_bc, _bcOffset, 66);
+ List<int>? get vectorOfLongs => const fb.ListReader<int>(fb.Int64Reader()).vTableGetNullable(_bc, _bcOffset, 68);
+ List<double>? get vectorOfDoubles => const fb.ListReader<double>(fb.Float64Reader()).vTableGetNullable(_bc, _bcOffset, 70);
+ my_game.InParentNamespace? get parentNamespaceTest => my_game.InParentNamespace.reader.vTableGetNullable(_bc, _bcOffset, 72);
+ List<Referrable>? get vectorOfReferrables => const fb.ListReader<Referrable>(Referrable.reader).vTableGetNullable(_bc, _bcOffset, 74);
int get singleWeakReference => const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 76, 0);
- List<int> get vectorOfWeakReferences => const fb.ListReader<int>(const fb.Uint64Reader()).vTableGet(_bc, _bcOffset, 78, null);
- List<Referrable> get vectorOfStrongReferrables => const fb.ListReader<Referrable>(Referrable.reader).vTableGet(_bc, _bcOffset, 80, null);
+ List<int>? get vectorOfWeakReferences => const fb.ListReader<int>(fb.Uint64Reader()).vTableGetNullable(_bc, _bcOffset, 78);
+ List<Referrable>? get vectorOfStrongReferrables => const fb.ListReader<Referrable>(Referrable.reader).vTableGetNullable(_bc, _bcOffset, 80);
int get coOwningReference => const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 82, 0);
- List<int> get vectorOfCoOwningReferences => const fb.ListReader<int>(const fb.Uint64Reader()).vTableGet(_bc, _bcOffset, 84, null);
+ List<int>? get vectorOfCoOwningReferences => const fb.ListReader<int>(fb.Uint64Reader()).vTableGetNullable(_bc, _bcOffset, 84);
int get nonOwningReference => const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 86, 0);
- List<int> get vectorOfNonOwningReferences => const fb.ListReader<int>(const fb.Uint64Reader()).vTableGet(_bc, _bcOffset, 88, null);
- AnyUniqueAliasesTypeId get anyUniqueType => new AnyUniqueAliasesTypeId.fromValue(const fb.Uint8Reader().vTableGet(_bc, _bcOffset, 90, 0));
+ List<int>? get vectorOfNonOwningReferences => const fb.ListReader<int>(fb.Uint64Reader()).vTableGetNullable(_bc, _bcOffset, 88);
+ AnyUniqueAliasesTypeId? get anyUniqueType => AnyUniqueAliasesTypeId._createOrNull(const fb.Uint8Reader().vTableGetNullable(_bc, _bcOffset, 90));
dynamic get anyUnique {
switch (anyUniqueType?.value) {
- case 1: return Monster.reader.vTableGet(_bc, _bcOffset, 92, null);
- case 2: return TestSimpleTableWithEnum.reader.vTableGet(_bc, _bcOffset, 92, null);
- case 3: return my_game_example2.Monster.reader.vTableGet(_bc, _bcOffset, 92, null);
+ case 1: return Monster.reader.vTableGetNullable(_bc, _bcOffset, 92);
+ case 2: return TestSimpleTableWithEnum.reader.vTableGetNullable(_bc, _bcOffset, 92);
+ case 3: return my_game_example2.Monster.reader.vTableGetNullable(_bc, _bcOffset, 92);
default: return null;
}
}
- AnyAmbiguousAliasesTypeId get anyAmbiguousType => new AnyAmbiguousAliasesTypeId.fromValue(const fb.Uint8Reader().vTableGet(_bc, _bcOffset, 94, 0));
+ AnyAmbiguousAliasesTypeId? get anyAmbiguousType => AnyAmbiguousAliasesTypeId._createOrNull(const fb.Uint8Reader().vTableGetNullable(_bc, _bcOffset, 94));
dynamic get anyAmbiguous {
switch (anyAmbiguousType?.value) {
- case 1: return Monster.reader.vTableGet(_bc, _bcOffset, 96, null);
- case 2: return Monster.reader.vTableGet(_bc, _bcOffset, 96, null);
- case 3: return Monster.reader.vTableGet(_bc, _bcOffset, 96, null);
+ case 1: return Monster.reader.vTableGetNullable(_bc, _bcOffset, 96);
+ case 2: return Monster.reader.vTableGetNullable(_bc, _bcOffset, 96);
+ case 3: return Monster.reader.vTableGetNullable(_bc, _bcOffset, 96);
default: return null;
}
}
- List<Color> get vectorOfEnums => const fb.ListReader<Color>(Color.reader).vTableGet(_bc, _bcOffset, 98, null);
- Race get signedEnum => new Race.fromValue(const fb.Int8Reader().vTableGet(_bc, _bcOffset, 100, -1));
- List<int> get testrequirednestedflatbuffer => const fb.ListReader<int>(const fb.Uint8Reader()).vTableGet(_bc, _bcOffset, 102, null);
+ List<Color>? get vectorOfEnums => const fb.ListReader<Color>(Color.reader).vTableGetNullable(_bc, _bcOffset, 98);
+ Race get signedEnum => Race.fromValue(const fb.Int8Reader().vTableGet(_bc, _bcOffset, 100, -1));
+ List<int>? get testrequirednestedflatbuffer => const fb.Uint8ListReader().vTableGetNullable(_bc, _bcOffset, 102);
+ List<Stat>? get scalarKeySortedTables => const fb.ListReader<Stat>(Stat.reader).vTableGetNullable(_bc, _bcOffset, 104);
+ Test? get nativeInline => Test.reader.vTableGetNullable(_bc, _bcOffset, 106);
+ LongEnum get longEnumNonEnumDefault => LongEnum.fromValue(const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 108, 0));
+ LongEnum get longEnumNormalDefault => LongEnum.fromValue(const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 110, 2));
@override
String toString() {
- return 'Monster{pos: $pos, mana: $mana, hp: $hp, name: $name, inventory: $inventory, color: $color, testType: $testType, test: $test, test4: $test4, testarrayofstring: $testarrayofstring, testarrayoftables: $testarrayoftables, enemy: $enemy, testnestedflatbuffer: $testnestedflatbuffer, testempty: $testempty, testbool: $testbool, testhashs32Fnv1: $testhashs32Fnv1, testhashu32Fnv1: $testhashu32Fnv1, testhashs64Fnv1: $testhashs64Fnv1, testhashu64Fnv1: $testhashu64Fnv1, testhashs32Fnv1a: $testhashs32Fnv1a, testhashu32Fnv1a: $testhashu32Fnv1a, testhashs64Fnv1a: $testhashs64Fnv1a, testhashu64Fnv1a: $testhashu64Fnv1a, testarrayofbools: $testarrayofbools, testf: $testf, testf2: $testf2, testf3: $testf3, testarrayofstring2: $testarrayofstring2, testarrayofsortedstruct: $testarrayofsortedstruct, flex: $flex, test5: $test5, vectorOfLongs: $vectorOfLongs, vectorOfDoubles: $vectorOfDoubles, parentNamespaceTest: $parentNamespaceTest, vectorOfReferrables: $vectorOfReferrables, singleWeakReference: $singleWeakReference, vectorOfWeakReferences: $vectorOfWeakReferences, vectorOfStrongReferrables: $vectorOfStrongReferrables, coOwningReference: $coOwningReference, vectorOfCoOwningReferences: $vectorOfCoOwningReferences, nonOwningReference: $nonOwningReference, vectorOfNonOwningReferences: $vectorOfNonOwningReferences, anyUniqueType: $anyUniqueType, anyUnique: $anyUnique, anyAmbiguousType: $anyAmbiguousType, anyAmbiguous: $anyAmbiguous, vectorOfEnums: $vectorOfEnums, signedEnum: $signedEnum, testrequirednestedflatbuffer: $testrequirednestedflatbuffer}';
+ return 'Monster{pos: $pos, mana: $mana, hp: $hp, name: $name, inventory: $inventory, color: $color, testType: $testType, test: $test, test4: $test4, testarrayofstring: $testarrayofstring, testarrayoftables: $testarrayoftables, enemy: $enemy, testnestedflatbuffer: $testnestedflatbuffer, testempty: $testempty, testbool: $testbool, testhashs32Fnv1: $testhashs32Fnv1, testhashu32Fnv1: $testhashu32Fnv1, testhashs64Fnv1: $testhashs64Fnv1, testhashu64Fnv1: $testhashu64Fnv1, testhashs32Fnv1a: $testhashs32Fnv1a, testhashu32Fnv1a: $testhashu32Fnv1a, testhashs64Fnv1a: $testhashs64Fnv1a, testhashu64Fnv1a: $testhashu64Fnv1a, testarrayofbools: $testarrayofbools, testf: $testf, testf2: $testf2, testf3: $testf3, testarrayofstring2: $testarrayofstring2, testarrayofsortedstruct: $testarrayofsortedstruct, flex: $flex, test5: $test5, vectorOfLongs: $vectorOfLongs, vectorOfDoubles: $vectorOfDoubles, parentNamespaceTest: $parentNamespaceTest, vectorOfReferrables: $vectorOfReferrables, singleWeakReference: $singleWeakReference, vectorOfWeakReferences: $vectorOfWeakReferences, vectorOfStrongReferrables: $vectorOfStrongReferrables, coOwningReference: $coOwningReference, vectorOfCoOwningReferences: $vectorOfCoOwningReferences, nonOwningReference: $nonOwningReference, vectorOfNonOwningReferences: $vectorOfNonOwningReferences, anyUniqueType: $anyUniqueType, anyUnique: $anyUnique, anyAmbiguousType: $anyAmbiguousType, anyAmbiguous: $anyAmbiguous, vectorOfEnums: $vectorOfEnums, signedEnum: $signedEnum, testrequirednestedflatbuffer: $testrequirednestedflatbuffer, scalarKeySortedTables: $scalarKeySortedTables, nativeInline: $nativeInline, longEnumNonEnumDefault: $longEnumNonEnumDefault, longEnumNormalDefault: $longEnumNormalDefault}';
+ }
+
+ MonsterT unpack() => MonsterT(
+ pos: pos?.unpack(),
+ mana: mana,
+ hp: hp,
+ name: name,
+ inventory: const fb.Uint8ListReader(lazy: false).vTableGetNullable(_bc, _bcOffset, 14),
+ color: color,
+ testType: testType,
+ test: test,
+ test4: test4?.map((e) => e.unpack()).toList(),
+ testarrayofstring: const fb.ListReader<String>(fb.StringReader(), lazy: false).vTableGetNullable(_bc, _bcOffset, 24),
+ testarrayoftables: testarrayoftables?.map((e) => e.unpack()).toList(),
+ enemy: enemy?.unpack(),
+ testnestedflatbuffer: const fb.Uint8ListReader(lazy: false).vTableGetNullable(_bc, _bcOffset, 30),
+ testempty: testempty?.unpack(),
+ testbool: testbool,
+ testhashs32Fnv1: testhashs32Fnv1,
+ testhashu32Fnv1: testhashu32Fnv1,
+ testhashs64Fnv1: testhashs64Fnv1,
+ testhashu64Fnv1: testhashu64Fnv1,
+ testhashs32Fnv1a: testhashs32Fnv1a,
+ testhashu32Fnv1a: testhashu32Fnv1a,
+ testhashs64Fnv1a: testhashs64Fnv1a,
+ testhashu64Fnv1a: testhashu64Fnv1a,
+ testarrayofbools: const fb.ListReader<bool>(fb.BoolReader(), lazy: false).vTableGetNullable(_bc, _bcOffset, 52),
+ testf: testf,
+ testf2: testf2,
+ testf3: testf3,
+ testarrayofstring2: const fb.ListReader<String>(fb.StringReader(), lazy: false).vTableGetNullable(_bc, _bcOffset, 60),
+ testarrayofsortedstruct: testarrayofsortedstruct?.map((e) => e.unpack()).toList(),
+ flex: const fb.Uint8ListReader(lazy: false).vTableGetNullable(_bc, _bcOffset, 64),
+ test5: test5?.map((e) => e.unpack()).toList(),
+ vectorOfLongs: const fb.ListReader<int>(fb.Int64Reader(), lazy: false).vTableGetNullable(_bc, _bcOffset, 68),
+ vectorOfDoubles: const fb.ListReader<double>(fb.Float64Reader(), lazy: false).vTableGetNullable(_bc, _bcOffset, 70),
+ parentNamespaceTest: parentNamespaceTest?.unpack(),
+ vectorOfReferrables: vectorOfReferrables?.map((e) => e.unpack()).toList(),
+ singleWeakReference: singleWeakReference,
+ vectorOfWeakReferences: const fb.ListReader<int>(fb.Uint64Reader(), lazy: false).vTableGetNullable(_bc, _bcOffset, 78),
+ vectorOfStrongReferrables: vectorOfStrongReferrables?.map((e) => e.unpack()).toList(),
+ coOwningReference: coOwningReference,
+ vectorOfCoOwningReferences: const fb.ListReader<int>(fb.Uint64Reader(), lazy: false).vTableGetNullable(_bc, _bcOffset, 84),
+ nonOwningReference: nonOwningReference,
+ vectorOfNonOwningReferences: const fb.ListReader<int>(fb.Uint64Reader(), lazy: false).vTableGetNullable(_bc, _bcOffset, 88),
+ anyUniqueType: anyUniqueType,
+ anyUnique: anyUnique,
+ anyAmbiguousType: anyAmbiguousType,
+ anyAmbiguous: anyAmbiguous,
+ vectorOfEnums: const fb.ListReader<Color>(Color.reader, lazy: false).vTableGetNullable(_bc, _bcOffset, 98),
+ signedEnum: signedEnum,
+ testrequirednestedflatbuffer: const fb.Uint8ListReader(lazy: false).vTableGetNullable(_bc, _bcOffset, 102),
+ scalarKeySortedTables: scalarKeySortedTables?.map((e) => e.unpack()).toList(),
+ nativeInline: nativeInline?.unpack(),
+ longEnumNonEnumDefault: longEnumNonEnumDefault,
+ longEnumNormalDefault: longEnumNormalDefault);
+
+ static int pack(fb.Builder fbBuilder, MonsterT? object) {
+ if (object == null) return 0;
+ return object.pack(fbBuilder);
+ }
+}
+
+/// an example documentation comment: "monster object"
+class MonsterT implements fb.Packable {
+ Vec3T? pos;
+ int mana;
+ int hp;
+ String? name;
+ List<int>? inventory;
+ Color color;
+ AnyTypeId? testType;
+ dynamic test;
+ List<TestT>? test4;
+ List<String>? testarrayofstring;
+ /// an example documentation comment: this will end up in the generated code
+ /// multiline too
+ List<MonsterT>? testarrayoftables;
+ MonsterT? enemy;
+ List<int>? testnestedflatbuffer;
+ StatT? testempty;
+ bool testbool;
+ int testhashs32Fnv1;
+ int testhashu32Fnv1;
+ int testhashs64Fnv1;
+ int testhashu64Fnv1;
+ int testhashs32Fnv1a;
+ int testhashu32Fnv1a;
+ int testhashs64Fnv1a;
+ int testhashu64Fnv1a;
+ List<bool>? testarrayofbools;
+ double testf;
+ double testf2;
+ double testf3;
+ List<String>? testarrayofstring2;
+ List<AbilityT>? testarrayofsortedstruct;
+ List<int>? flex;
+ List<TestT>? test5;
+ List<int>? vectorOfLongs;
+ List<double>? vectorOfDoubles;
+ my_game.InParentNamespaceT? parentNamespaceTest;
+ List<ReferrableT>? vectorOfReferrables;
+ int singleWeakReference;
+ List<int>? vectorOfWeakReferences;
+ List<ReferrableT>? vectorOfStrongReferrables;
+ int coOwningReference;
+ List<int>? vectorOfCoOwningReferences;
+ int nonOwningReference;
+ List<int>? vectorOfNonOwningReferences;
+ AnyUniqueAliasesTypeId? anyUniqueType;
+ dynamic anyUnique;
+ AnyAmbiguousAliasesTypeId? anyAmbiguousType;
+ dynamic anyAmbiguous;
+ List<Color>? vectorOfEnums;
+ Race signedEnum;
+ List<int>? testrequirednestedflatbuffer;
+ List<StatT>? scalarKeySortedTables;
+ TestT? nativeInline;
+ LongEnum longEnumNonEnumDefault;
+ LongEnum longEnumNormalDefault;
+
+ MonsterT({
+ this.pos,
+ this.mana = 150,
+ this.hp = 100,
+ this.name,
+ this.inventory,
+ this.color = Color.Blue,
+ this.testType,
+ this.test,
+ this.test4,
+ this.testarrayofstring,
+ this.testarrayoftables,
+ this.enemy,
+ this.testnestedflatbuffer,
+ this.testempty,
+ this.testbool = false,
+ this.testhashs32Fnv1 = 0,
+ this.testhashu32Fnv1 = 0,
+ this.testhashs64Fnv1 = 0,
+ this.testhashu64Fnv1 = 0,
+ this.testhashs32Fnv1a = 0,
+ this.testhashu32Fnv1a = 0,
+ this.testhashs64Fnv1a = 0,
+ this.testhashu64Fnv1a = 0,
+ this.testarrayofbools,
+ this.testf = 3.14159,
+ this.testf2 = 3.0,
+ this.testf3 = 0.0,
+ this.testarrayofstring2,
+ this.testarrayofsortedstruct,
+ this.flex,
+ this.test5,
+ this.vectorOfLongs,
+ this.vectorOfDoubles,
+ this.parentNamespaceTest,
+ this.vectorOfReferrables,
+ this.singleWeakReference = 0,
+ this.vectorOfWeakReferences,
+ this.vectorOfStrongReferrables,
+ this.coOwningReference = 0,
+ this.vectorOfCoOwningReferences,
+ this.nonOwningReference = 0,
+ this.vectorOfNonOwningReferences,
+ this.anyUniqueType,
+ this.anyUnique,
+ this.anyAmbiguousType,
+ this.anyAmbiguous,
+ this.vectorOfEnums,
+ this.signedEnum = Race.None,
+ this.testrequirednestedflatbuffer,
+ this.scalarKeySortedTables,
+ this.nativeInline,
+ this.longEnumNonEnumDefault = const LongEnum._(0),
+ this.longEnumNormalDefault = LongEnum.LongOne});
+
+ @override
+ int pack(fb.Builder fbBuilder) {
+ final int? nameOffset = name == null ? null
+ : fbBuilder.writeString(name!);
+ final int? inventoryOffset = inventory == null ? null
+ : fbBuilder.writeListUint8(inventory!);
+ final int? testOffset = test?.pack(fbBuilder);
+ int? test4Offset;
+ if (test4 != null) {
+ for (var e in test4!) { e.pack(fbBuilder); }
+ test4Offset = fbBuilder.endStructVector(test4!.length);
+ }
+ final int? testarrayofstringOffset = testarrayofstring == null ? null
+ : fbBuilder.writeList(testarrayofstring!.map(fbBuilder.writeString).toList());
+ final int? testarrayoftablesOffset = testarrayoftables == null ? null
+ : fbBuilder.writeList(testarrayoftables!.map((b) => b.pack(fbBuilder)).toList());
+ final int? enemyOffset = enemy?.pack(fbBuilder);
+ final int? testnestedflatbufferOffset = testnestedflatbuffer == null ? null
+ : fbBuilder.writeListUint8(testnestedflatbuffer!);
+ final int? testemptyOffset = testempty?.pack(fbBuilder);
+ final int? testarrayofboolsOffset = testarrayofbools == null ? null
+ : fbBuilder.writeListBool(testarrayofbools!);
+ final int? testarrayofstring2Offset = testarrayofstring2 == null ? null
+ : fbBuilder.writeList(testarrayofstring2!.map(fbBuilder.writeString).toList());
+ int? testarrayofsortedstructOffset;
+ if (testarrayofsortedstruct != null) {
+ for (var e in testarrayofsortedstruct!) { e.pack(fbBuilder); }
+ testarrayofsortedstructOffset = fbBuilder.endStructVector(testarrayofsortedstruct!.length);
+ }
+ final int? flexOffset = flex == null ? null
+ : fbBuilder.writeListUint8(flex!);
+ int? test5Offset;
+ if (test5 != null) {
+ for (var e in test5!) { e.pack(fbBuilder); }
+ test5Offset = fbBuilder.endStructVector(test5!.length);
+ }
+ final int? vectorOfLongsOffset = vectorOfLongs == null ? null
+ : fbBuilder.writeListInt64(vectorOfLongs!);
+ final int? vectorOfDoublesOffset = vectorOfDoubles == null ? null
+ : fbBuilder.writeListFloat64(vectorOfDoubles!);
+ final int? parentNamespaceTestOffset = parentNamespaceTest?.pack(fbBuilder);
+ final int? vectorOfReferrablesOffset = vectorOfReferrables == null ? null
+ : fbBuilder.writeList(vectorOfReferrables!.map((b) => b.pack(fbBuilder)).toList());
+ final int? vectorOfWeakReferencesOffset = vectorOfWeakReferences == null ? null
+ : fbBuilder.writeListUint64(vectorOfWeakReferences!);
+ final int? vectorOfStrongReferrablesOffset = vectorOfStrongReferrables == null ? null
+ : fbBuilder.writeList(vectorOfStrongReferrables!.map((b) => b.pack(fbBuilder)).toList());
+ final int? vectorOfCoOwningReferencesOffset = vectorOfCoOwningReferences == null ? null
+ : fbBuilder.writeListUint64(vectorOfCoOwningReferences!);
+ final int? vectorOfNonOwningReferencesOffset = vectorOfNonOwningReferences == null ? null
+ : fbBuilder.writeListUint64(vectorOfNonOwningReferences!);
+ final int? anyUniqueOffset = anyUnique?.pack(fbBuilder);
+ final int? anyAmbiguousOffset = anyAmbiguous?.pack(fbBuilder);
+ final int? vectorOfEnumsOffset = vectorOfEnums == null ? null
+ : fbBuilder.writeListUint8(vectorOfEnums!.map((f) => f.value).toList());
+ final int? testrequirednestedflatbufferOffset = testrequirednestedflatbuffer == null ? null
+ : fbBuilder.writeListUint8(testrequirednestedflatbuffer!);
+ final int? scalarKeySortedTablesOffset = scalarKeySortedTables == null ? null
+ : fbBuilder.writeList(scalarKeySortedTables!.map((b) => b.pack(fbBuilder)).toList());
+ fbBuilder.startTable(54);
+ if (pos != null) {
+ fbBuilder.addStruct(0, pos!.pack(fbBuilder));
+ }
+ fbBuilder.addInt16(1, mana);
+ fbBuilder.addInt16(2, hp);
+ fbBuilder.addOffset(3, nameOffset);
+ fbBuilder.addOffset(5, inventoryOffset);
+ fbBuilder.addUint8(6, color.value);
+ fbBuilder.addUint8(7, testType?.value);
+ fbBuilder.addOffset(8, testOffset);
+ fbBuilder.addOffset(9, test4Offset);
+ fbBuilder.addOffset(10, testarrayofstringOffset);
+ fbBuilder.addOffset(11, testarrayoftablesOffset);
+ fbBuilder.addOffset(12, enemyOffset);
+ fbBuilder.addOffset(13, testnestedflatbufferOffset);
+ fbBuilder.addOffset(14, testemptyOffset);
+ fbBuilder.addBool(15, testbool);
+ fbBuilder.addInt32(16, testhashs32Fnv1);
+ fbBuilder.addUint32(17, testhashu32Fnv1);
+ fbBuilder.addInt64(18, testhashs64Fnv1);
+ fbBuilder.addUint64(19, testhashu64Fnv1);
+ fbBuilder.addInt32(20, testhashs32Fnv1a);
+ fbBuilder.addUint32(21, testhashu32Fnv1a);
+ fbBuilder.addInt64(22, testhashs64Fnv1a);
+ fbBuilder.addUint64(23, testhashu64Fnv1a);
+ fbBuilder.addOffset(24, testarrayofboolsOffset);
+ fbBuilder.addFloat32(25, testf);
+ fbBuilder.addFloat32(26, testf2);
+ fbBuilder.addFloat32(27, testf3);
+ fbBuilder.addOffset(28, testarrayofstring2Offset);
+ fbBuilder.addOffset(29, testarrayofsortedstructOffset);
+ fbBuilder.addOffset(30, flexOffset);
+ fbBuilder.addOffset(31, test5Offset);
+ fbBuilder.addOffset(32, vectorOfLongsOffset);
+ fbBuilder.addOffset(33, vectorOfDoublesOffset);
+ fbBuilder.addOffset(34, parentNamespaceTestOffset);
+ fbBuilder.addOffset(35, vectorOfReferrablesOffset);
+ fbBuilder.addUint64(36, singleWeakReference);
+ fbBuilder.addOffset(37, vectorOfWeakReferencesOffset);
+ fbBuilder.addOffset(38, vectorOfStrongReferrablesOffset);
+ fbBuilder.addUint64(39, coOwningReference);
+ fbBuilder.addOffset(40, vectorOfCoOwningReferencesOffset);
+ fbBuilder.addUint64(41, nonOwningReference);
+ fbBuilder.addOffset(42, vectorOfNonOwningReferencesOffset);
+ fbBuilder.addUint8(43, anyUniqueType?.value);
+ fbBuilder.addOffset(44, anyUniqueOffset);
+ fbBuilder.addUint8(45, anyAmbiguousType?.value);
+ fbBuilder.addOffset(46, anyAmbiguousOffset);
+ fbBuilder.addOffset(47, vectorOfEnumsOffset);
+ fbBuilder.addInt8(48, signedEnum.value);
+ fbBuilder.addOffset(49, testrequirednestedflatbufferOffset);
+ fbBuilder.addOffset(50, scalarKeySortedTablesOffset);
+ if (nativeInline != null) {
+ fbBuilder.addStruct(51, nativeInline!.pack(fbBuilder));
+ }
+ fbBuilder.addUint64(52, longEnumNonEnumDefault.value);
+ fbBuilder.addUint64(53, longEnumNormalDefault.value);
+ return fbBuilder.endTable();
+ }
+
+ @override
+ String toString() {
+ return 'MonsterT{pos: $pos, mana: $mana, hp: $hp, name: $name, inventory: $inventory, color: $color, testType: $testType, test: $test, test4: $test4, testarrayofstring: $testarrayofstring, testarrayoftables: $testarrayoftables, enemy: $enemy, testnestedflatbuffer: $testnestedflatbuffer, testempty: $testempty, testbool: $testbool, testhashs32Fnv1: $testhashs32Fnv1, testhashu32Fnv1: $testhashu32Fnv1, testhashs64Fnv1: $testhashs64Fnv1, testhashu64Fnv1: $testhashu64Fnv1, testhashs32Fnv1a: $testhashs32Fnv1a, testhashu32Fnv1a: $testhashu32Fnv1a, testhashs64Fnv1a: $testhashs64Fnv1a, testhashu64Fnv1a: $testhashu64Fnv1a, testarrayofbools: $testarrayofbools, testf: $testf, testf2: $testf2, testf3: $testf3, testarrayofstring2: $testarrayofstring2, testarrayofsortedstruct: $testarrayofsortedstruct, flex: $flex, test5: $test5, vectorOfLongs: $vectorOfLongs, vectorOfDoubles: $vectorOfDoubles, parentNamespaceTest: $parentNamespaceTest, vectorOfReferrables: $vectorOfReferrables, singleWeakReference: $singleWeakReference, vectorOfWeakReferences: $vectorOfWeakReferences, vectorOfStrongReferrables: $vectorOfStrongReferrables, coOwningReference: $coOwningReference, vectorOfCoOwningReferences: $vectorOfCoOwningReferences, nonOwningReference: $nonOwningReference, vectorOfNonOwningReferences: $vectorOfNonOwningReferences, anyUniqueType: $anyUniqueType, anyUnique: $anyUnique, anyAmbiguousType: $anyAmbiguousType, anyAmbiguous: $anyAmbiguous, vectorOfEnums: $vectorOfEnums, signedEnum: $signedEnum, testrequirednestedflatbuffer: $testrequirednestedflatbuffer, scalarKeySortedTables: $scalarKeySortedTables, nativeInline: $nativeInline, longEnumNonEnumDefault: $longEnumNonEnumDefault, longEnumNormalDefault: $longEnumNormalDefault}';
}
}
@@ -814,216 +1481,230 @@
@override
Monster createObject(fb.BufferContext bc, int offset) =>
- new Monster._(bc, offset);
+ Monster._(bc, offset);
}
class MonsterBuilder {
- MonsterBuilder(this.fbBuilder) {
- assert(fbBuilder != null);
- }
+ MonsterBuilder(this.fbBuilder);
final fb.Builder fbBuilder;
void begin() {
- fbBuilder.startTable();
+ fbBuilder.startTable(54);
}
int addPos(int offset) {
fbBuilder.addStruct(0, offset);
return fbBuilder.offset;
}
- int addMana(int mana) {
+ int addMana(int? mana) {
fbBuilder.addInt16(1, mana);
return fbBuilder.offset;
}
- int addHp(int hp) {
+ int addHp(int? hp) {
fbBuilder.addInt16(2, hp);
return fbBuilder.offset;
}
- int addNameOffset(int offset) {
+ int addNameOffset(int? offset) {
fbBuilder.addOffset(3, offset);
return fbBuilder.offset;
}
- int addInventoryOffset(int offset) {
+ int addInventoryOffset(int? offset) {
fbBuilder.addOffset(5, offset);
return fbBuilder.offset;
}
- int addColor(Color color) {
+ int addColor(Color? color) {
fbBuilder.addUint8(6, color?.value);
return fbBuilder.offset;
}
- int addTestType(AnyTypeId testType) {
+ int addTestType(AnyTypeId? testType) {
fbBuilder.addUint8(7, testType?.value);
return fbBuilder.offset;
}
- int addTestOffset(int offset) {
+ int addTestOffset(int? offset) {
fbBuilder.addOffset(8, offset);
return fbBuilder.offset;
}
- int addTest4Offset(int offset) {
+ int addTest4Offset(int? offset) {
fbBuilder.addOffset(9, offset);
return fbBuilder.offset;
}
- int addTestarrayofstringOffset(int offset) {
+ int addTestarrayofstringOffset(int? offset) {
fbBuilder.addOffset(10, offset);
return fbBuilder.offset;
}
- int addTestarrayoftablesOffset(int offset) {
+ int addTestarrayoftablesOffset(int? offset) {
fbBuilder.addOffset(11, offset);
return fbBuilder.offset;
}
- int addEnemyOffset(int offset) {
+ int addEnemyOffset(int? offset) {
fbBuilder.addOffset(12, offset);
return fbBuilder.offset;
}
- int addTestnestedflatbufferOffset(int offset) {
+ int addTestnestedflatbufferOffset(int? offset) {
fbBuilder.addOffset(13, offset);
return fbBuilder.offset;
}
- int addTestemptyOffset(int offset) {
+ int addTestemptyOffset(int? offset) {
fbBuilder.addOffset(14, offset);
return fbBuilder.offset;
}
- int addTestbool(bool testbool) {
+ int addTestbool(bool? testbool) {
fbBuilder.addBool(15, testbool);
return fbBuilder.offset;
}
- int addTesthashs32Fnv1(int testhashs32Fnv1) {
+ int addTesthashs32Fnv1(int? testhashs32Fnv1) {
fbBuilder.addInt32(16, testhashs32Fnv1);
return fbBuilder.offset;
}
- int addTesthashu32Fnv1(int testhashu32Fnv1) {
+ int addTesthashu32Fnv1(int? testhashu32Fnv1) {
fbBuilder.addUint32(17, testhashu32Fnv1);
return fbBuilder.offset;
}
- int addTesthashs64Fnv1(int testhashs64Fnv1) {
+ int addTesthashs64Fnv1(int? testhashs64Fnv1) {
fbBuilder.addInt64(18, testhashs64Fnv1);
return fbBuilder.offset;
}
- int addTesthashu64Fnv1(int testhashu64Fnv1) {
+ int addTesthashu64Fnv1(int? testhashu64Fnv1) {
fbBuilder.addUint64(19, testhashu64Fnv1);
return fbBuilder.offset;
}
- int addTesthashs32Fnv1a(int testhashs32Fnv1a) {
+ int addTesthashs32Fnv1a(int? testhashs32Fnv1a) {
fbBuilder.addInt32(20, testhashs32Fnv1a);
return fbBuilder.offset;
}
- int addTesthashu32Fnv1a(int testhashu32Fnv1a) {
+ int addTesthashu32Fnv1a(int? testhashu32Fnv1a) {
fbBuilder.addUint32(21, testhashu32Fnv1a);
return fbBuilder.offset;
}
- int addTesthashs64Fnv1a(int testhashs64Fnv1a) {
+ int addTesthashs64Fnv1a(int? testhashs64Fnv1a) {
fbBuilder.addInt64(22, testhashs64Fnv1a);
return fbBuilder.offset;
}
- int addTesthashu64Fnv1a(int testhashu64Fnv1a) {
+ int addTesthashu64Fnv1a(int? testhashu64Fnv1a) {
fbBuilder.addUint64(23, testhashu64Fnv1a);
return fbBuilder.offset;
}
- int addTestarrayofboolsOffset(int offset) {
+ int addTestarrayofboolsOffset(int? offset) {
fbBuilder.addOffset(24, offset);
return fbBuilder.offset;
}
- int addTestf(double testf) {
+ int addTestf(double? testf) {
fbBuilder.addFloat32(25, testf);
return fbBuilder.offset;
}
- int addTestf2(double testf2) {
+ int addTestf2(double? testf2) {
fbBuilder.addFloat32(26, testf2);
return fbBuilder.offset;
}
- int addTestf3(double testf3) {
+ int addTestf3(double? testf3) {
fbBuilder.addFloat32(27, testf3);
return fbBuilder.offset;
}
- int addTestarrayofstring2Offset(int offset) {
+ int addTestarrayofstring2Offset(int? offset) {
fbBuilder.addOffset(28, offset);
return fbBuilder.offset;
}
- int addTestarrayofsortedstructOffset(int offset) {
+ int addTestarrayofsortedstructOffset(int? offset) {
fbBuilder.addOffset(29, offset);
return fbBuilder.offset;
}
- int addFlexOffset(int offset) {
+ int addFlexOffset(int? offset) {
fbBuilder.addOffset(30, offset);
return fbBuilder.offset;
}
- int addTest5Offset(int offset) {
+ int addTest5Offset(int? offset) {
fbBuilder.addOffset(31, offset);
return fbBuilder.offset;
}
- int addVectorOfLongsOffset(int offset) {
+ int addVectorOfLongsOffset(int? offset) {
fbBuilder.addOffset(32, offset);
return fbBuilder.offset;
}
- int addVectorOfDoublesOffset(int offset) {
+ int addVectorOfDoublesOffset(int? offset) {
fbBuilder.addOffset(33, offset);
return fbBuilder.offset;
}
- int addParentNamespaceTestOffset(int offset) {
+ int addParentNamespaceTestOffset(int? offset) {
fbBuilder.addOffset(34, offset);
return fbBuilder.offset;
}
- int addVectorOfReferrablesOffset(int offset) {
+ int addVectorOfReferrablesOffset(int? offset) {
fbBuilder.addOffset(35, offset);
return fbBuilder.offset;
}
- int addSingleWeakReference(int singleWeakReference) {
+ int addSingleWeakReference(int? singleWeakReference) {
fbBuilder.addUint64(36, singleWeakReference);
return fbBuilder.offset;
}
- int addVectorOfWeakReferencesOffset(int offset) {
+ int addVectorOfWeakReferencesOffset(int? offset) {
fbBuilder.addOffset(37, offset);
return fbBuilder.offset;
}
- int addVectorOfStrongReferrablesOffset(int offset) {
+ int addVectorOfStrongReferrablesOffset(int? offset) {
fbBuilder.addOffset(38, offset);
return fbBuilder.offset;
}
- int addCoOwningReference(int coOwningReference) {
+ int addCoOwningReference(int? coOwningReference) {
fbBuilder.addUint64(39, coOwningReference);
return fbBuilder.offset;
}
- int addVectorOfCoOwningReferencesOffset(int offset) {
+ int addVectorOfCoOwningReferencesOffset(int? offset) {
fbBuilder.addOffset(40, offset);
return fbBuilder.offset;
}
- int addNonOwningReference(int nonOwningReference) {
+ int addNonOwningReference(int? nonOwningReference) {
fbBuilder.addUint64(41, nonOwningReference);
return fbBuilder.offset;
}
- int addVectorOfNonOwningReferencesOffset(int offset) {
+ int addVectorOfNonOwningReferencesOffset(int? offset) {
fbBuilder.addOffset(42, offset);
return fbBuilder.offset;
}
- int addAnyUniqueType(AnyUniqueAliasesTypeId anyUniqueType) {
+ int addAnyUniqueType(AnyUniqueAliasesTypeId? anyUniqueType) {
fbBuilder.addUint8(43, anyUniqueType?.value);
return fbBuilder.offset;
}
- int addAnyUniqueOffset(int offset) {
+ int addAnyUniqueOffset(int? offset) {
fbBuilder.addOffset(44, offset);
return fbBuilder.offset;
}
- int addAnyAmbiguousType(AnyAmbiguousAliasesTypeId anyAmbiguousType) {
+ int addAnyAmbiguousType(AnyAmbiguousAliasesTypeId? anyAmbiguousType) {
fbBuilder.addUint8(45, anyAmbiguousType?.value);
return fbBuilder.offset;
}
- int addAnyAmbiguousOffset(int offset) {
+ int addAnyAmbiguousOffset(int? offset) {
fbBuilder.addOffset(46, offset);
return fbBuilder.offset;
}
- int addVectorOfEnumsOffset(int offset) {
+ int addVectorOfEnumsOffset(int? offset) {
fbBuilder.addOffset(47, offset);
return fbBuilder.offset;
}
- int addSignedEnum(Race signedEnum) {
+ int addSignedEnum(Race? signedEnum) {
fbBuilder.addInt8(48, signedEnum?.value);
return fbBuilder.offset;
}
- int addTestrequirednestedflatbufferOffset(int offset) {
+ int addTestrequirednestedflatbufferOffset(int? offset) {
fbBuilder.addOffset(49, offset);
return fbBuilder.offset;
}
+ int addScalarKeySortedTablesOffset(int? offset) {
+ fbBuilder.addOffset(50, offset);
+ return fbBuilder.offset;
+ }
+ int addNativeInline(int offset) {
+ fbBuilder.addStruct(51, offset);
+ return fbBuilder.offset;
+ }
+ int addLongEnumNonEnumDefault(LongEnum? longEnumNonEnumDefault) {
+ fbBuilder.addUint64(52, longEnumNonEnumDefault?.value);
+ return fbBuilder.offset;
+ }
+ int addLongEnumNormalDefault(LongEnum? longEnumNormalDefault) {
+ fbBuilder.addUint64(53, longEnumNormalDefault?.value);
+ return fbBuilder.offset;
+ }
int finish() {
return fbBuilder.endTable();
@@ -1031,106 +1712,114 @@
}
class MonsterObjectBuilder extends fb.ObjectBuilder {
- final Vec3ObjectBuilder _pos;
- final int _mana;
- final int _hp;
- final String _name;
- final List<int> _inventory;
- final Color _color;
- final AnyTypeId _testType;
+ final Vec3ObjectBuilder? _pos;
+ final int? _mana;
+ final int? _hp;
+ final String? _name;
+ final List<int>? _inventory;
+ final Color? _color;
+ final AnyTypeId? _testType;
final dynamic _test;
- final List<TestObjectBuilder> _test4;
- final List<String> _testarrayofstring;
- final List<MonsterObjectBuilder> _testarrayoftables;
- final MonsterObjectBuilder _enemy;
- final List<int> _testnestedflatbuffer;
- final StatObjectBuilder _testempty;
- final bool _testbool;
- final int _testhashs32Fnv1;
- final int _testhashu32Fnv1;
- final int _testhashs64Fnv1;
- final int _testhashu64Fnv1;
- final int _testhashs32Fnv1a;
- final int _testhashu32Fnv1a;
- final int _testhashs64Fnv1a;
- final int _testhashu64Fnv1a;
- final List<bool> _testarrayofbools;
- final double _testf;
- final double _testf2;
- final double _testf3;
- final List<String> _testarrayofstring2;
- final List<AbilityObjectBuilder> _testarrayofsortedstruct;
- final List<int> _flex;
- final List<TestObjectBuilder> _test5;
- final List<int> _vectorOfLongs;
- final List<double> _vectorOfDoubles;
- final my_game.InParentNamespaceObjectBuilder _parentNamespaceTest;
- final List<ReferrableObjectBuilder> _vectorOfReferrables;
- final int _singleWeakReference;
- final List<int> _vectorOfWeakReferences;
- final List<ReferrableObjectBuilder> _vectorOfStrongReferrables;
- final int _coOwningReference;
- final List<int> _vectorOfCoOwningReferences;
- final int _nonOwningReference;
- final List<int> _vectorOfNonOwningReferences;
- final AnyUniqueAliasesTypeId _anyUniqueType;
+ final List<TestObjectBuilder>? _test4;
+ final List<String>? _testarrayofstring;
+ final List<MonsterObjectBuilder>? _testarrayoftables;
+ final MonsterObjectBuilder? _enemy;
+ final List<int>? _testnestedflatbuffer;
+ final StatObjectBuilder? _testempty;
+ final bool? _testbool;
+ final int? _testhashs32Fnv1;
+ final int? _testhashu32Fnv1;
+ final int? _testhashs64Fnv1;
+ final int? _testhashu64Fnv1;
+ final int? _testhashs32Fnv1a;
+ final int? _testhashu32Fnv1a;
+ final int? _testhashs64Fnv1a;
+ final int? _testhashu64Fnv1a;
+ final List<bool>? _testarrayofbools;
+ final double? _testf;
+ final double? _testf2;
+ final double? _testf3;
+ final List<String>? _testarrayofstring2;
+ final List<AbilityObjectBuilder>? _testarrayofsortedstruct;
+ final List<int>? _flex;
+ final List<TestObjectBuilder>? _test5;
+ final List<int>? _vectorOfLongs;
+ final List<double>? _vectorOfDoubles;
+ final my_game.InParentNamespaceObjectBuilder? _parentNamespaceTest;
+ final List<ReferrableObjectBuilder>? _vectorOfReferrables;
+ final int? _singleWeakReference;
+ final List<int>? _vectorOfWeakReferences;
+ final List<ReferrableObjectBuilder>? _vectorOfStrongReferrables;
+ final int? _coOwningReference;
+ final List<int>? _vectorOfCoOwningReferences;
+ final int? _nonOwningReference;
+ final List<int>? _vectorOfNonOwningReferences;
+ final AnyUniqueAliasesTypeId? _anyUniqueType;
final dynamic _anyUnique;
- final AnyAmbiguousAliasesTypeId _anyAmbiguousType;
+ final AnyAmbiguousAliasesTypeId? _anyAmbiguousType;
final dynamic _anyAmbiguous;
- final List<Color> _vectorOfEnums;
- final Race _signedEnum;
- final List<int> _testrequirednestedflatbuffer;
+ final List<Color>? _vectorOfEnums;
+ final Race? _signedEnum;
+ final List<int>? _testrequirednestedflatbuffer;
+ final List<StatObjectBuilder>? _scalarKeySortedTables;
+ final TestObjectBuilder? _nativeInline;
+ final LongEnum? _longEnumNonEnumDefault;
+ final LongEnum? _longEnumNormalDefault;
MonsterObjectBuilder({
- Vec3ObjectBuilder pos,
- int mana,
- int hp,
- String name,
- List<int> inventory,
- Color color,
- AnyTypeId testType,
+ Vec3ObjectBuilder? pos,
+ int? mana,
+ int? hp,
+ String? name,
+ List<int>? inventory,
+ Color? color,
+ AnyTypeId? testType,
dynamic test,
- List<TestObjectBuilder> test4,
- List<String> testarrayofstring,
- List<MonsterObjectBuilder> testarrayoftables,
- MonsterObjectBuilder enemy,
- List<int> testnestedflatbuffer,
- StatObjectBuilder testempty,
- bool testbool,
- int testhashs32Fnv1,
- int testhashu32Fnv1,
- int testhashs64Fnv1,
- int testhashu64Fnv1,
- int testhashs32Fnv1a,
- int testhashu32Fnv1a,
- int testhashs64Fnv1a,
- int testhashu64Fnv1a,
- List<bool> testarrayofbools,
- double testf,
- double testf2,
- double testf3,
- List<String> testarrayofstring2,
- List<AbilityObjectBuilder> testarrayofsortedstruct,
- List<int> flex,
- List<TestObjectBuilder> test5,
- List<int> vectorOfLongs,
- List<double> vectorOfDoubles,
- my_game.InParentNamespaceObjectBuilder parentNamespaceTest,
- List<ReferrableObjectBuilder> vectorOfReferrables,
- int singleWeakReference,
- List<int> vectorOfWeakReferences,
- List<ReferrableObjectBuilder> vectorOfStrongReferrables,
- int coOwningReference,
- List<int> vectorOfCoOwningReferences,
- int nonOwningReference,
- List<int> vectorOfNonOwningReferences,
- AnyUniqueAliasesTypeId anyUniqueType,
+ List<TestObjectBuilder>? test4,
+ List<String>? testarrayofstring,
+ List<MonsterObjectBuilder>? testarrayoftables,
+ MonsterObjectBuilder? enemy,
+ List<int>? testnestedflatbuffer,
+ StatObjectBuilder? testempty,
+ bool? testbool,
+ int? testhashs32Fnv1,
+ int? testhashu32Fnv1,
+ int? testhashs64Fnv1,
+ int? testhashu64Fnv1,
+ int? testhashs32Fnv1a,
+ int? testhashu32Fnv1a,
+ int? testhashs64Fnv1a,
+ int? testhashu64Fnv1a,
+ List<bool>? testarrayofbools,
+ double? testf,
+ double? testf2,
+ double? testf3,
+ List<String>? testarrayofstring2,
+ List<AbilityObjectBuilder>? testarrayofsortedstruct,
+ List<int>? flex,
+ List<TestObjectBuilder>? test5,
+ List<int>? vectorOfLongs,
+ List<double>? vectorOfDoubles,
+ my_game.InParentNamespaceObjectBuilder? parentNamespaceTest,
+ List<ReferrableObjectBuilder>? vectorOfReferrables,
+ int? singleWeakReference,
+ List<int>? vectorOfWeakReferences,
+ List<ReferrableObjectBuilder>? vectorOfStrongReferrables,
+ int? coOwningReference,
+ List<int>? vectorOfCoOwningReferences,
+ int? nonOwningReference,
+ List<int>? vectorOfNonOwningReferences,
+ AnyUniqueAliasesTypeId? anyUniqueType,
dynamic anyUnique,
- AnyAmbiguousAliasesTypeId anyAmbiguousType,
+ AnyAmbiguousAliasesTypeId? anyAmbiguousType,
dynamic anyAmbiguous,
- List<Color> vectorOfEnums,
- Race signedEnum,
- List<int> testrequirednestedflatbuffer,
+ List<Color>? vectorOfEnums,
+ Race? signedEnum,
+ List<int>? testrequirednestedflatbuffer,
+ List<StatObjectBuilder>? scalarKeySortedTables,
+ TestObjectBuilder? nativeInline,
+ LongEnum? longEnumNonEnumDefault,
+ LongEnum? longEnumNormalDefault,
})
: _pos = pos,
_mana = mana,
@@ -1180,113 +1869,80 @@
_anyAmbiguous = anyAmbiguous,
_vectorOfEnums = vectorOfEnums,
_signedEnum = signedEnum,
- _testrequirednestedflatbuffer = testrequirednestedflatbuffer;
+ _testrequirednestedflatbuffer = testrequirednestedflatbuffer,
+ _scalarKeySortedTables = scalarKeySortedTables,
+ _nativeInline = nativeInline,
+ _longEnumNonEnumDefault = longEnumNonEnumDefault,
+ _longEnumNormalDefault = longEnumNormalDefault;
/// Finish building, and store into the [fbBuilder].
@override
- int finish(
- fb.Builder fbBuilder) {
- assert(fbBuilder != null);
- final int nameOffset = fbBuilder.writeString(_name);
- final int inventoryOffset = _inventory?.isNotEmpty == true
- ? fbBuilder.writeListUint8(_inventory)
- : null;
- final int testOffset = _test?.getOrCreateOffset(fbBuilder);
- final int test4Offset = _test4?.isNotEmpty == true
- ? fbBuilder.writeListOfStructs(_test4)
- : null;
- final int testarrayofstringOffset = _testarrayofstring?.isNotEmpty == true
- ? fbBuilder.writeList(_testarrayofstring.map((b) => fbBuilder.writeString(b)).toList())
- : null;
- final int testarrayoftablesOffset = _testarrayoftables?.isNotEmpty == true
- ? fbBuilder.writeList(_testarrayoftables.map((b) => b.getOrCreateOffset(fbBuilder)).toList())
- : null;
- final int enemyOffset = _enemy?.getOrCreateOffset(fbBuilder);
- final int testnestedflatbufferOffset = _testnestedflatbuffer?.isNotEmpty == true
- ? fbBuilder.writeListUint8(_testnestedflatbuffer)
- : null;
- final int testemptyOffset = _testempty?.getOrCreateOffset(fbBuilder);
- final int testarrayofboolsOffset = _testarrayofbools?.isNotEmpty == true
- ? fbBuilder.writeListBool(_testarrayofbools)
- : null;
- final int testarrayofstring2Offset = _testarrayofstring2?.isNotEmpty == true
- ? fbBuilder.writeList(_testarrayofstring2.map((b) => fbBuilder.writeString(b)).toList())
- : null;
- final int testarrayofsortedstructOffset = _testarrayofsortedstruct?.isNotEmpty == true
- ? fbBuilder.writeListOfStructs(_testarrayofsortedstruct)
- : null;
- final int flexOffset = _flex?.isNotEmpty == true
- ? fbBuilder.writeListUint8(_flex)
- : null;
- final int test5Offset = _test5?.isNotEmpty == true
- ? fbBuilder.writeListOfStructs(_test5)
- : null;
- final int vectorOfLongsOffset = _vectorOfLongs?.isNotEmpty == true
- ? fbBuilder.writeListInt64(_vectorOfLongs)
- : null;
- final int vectorOfDoublesOffset = _vectorOfDoubles?.isNotEmpty == true
- ? fbBuilder.writeListFloat64(_vectorOfDoubles)
- : null;
- final int parentNamespaceTestOffset = _parentNamespaceTest?.getOrCreateOffset(fbBuilder);
- final int vectorOfReferrablesOffset = _vectorOfReferrables?.isNotEmpty == true
- ? fbBuilder.writeList(_vectorOfReferrables.map((b) => b.getOrCreateOffset(fbBuilder)).toList())
- : null;
- final int vectorOfWeakReferencesOffset = _vectorOfWeakReferences?.isNotEmpty == true
- ? fbBuilder.writeListUint64(_vectorOfWeakReferences)
- : null;
- final int vectorOfStrongReferrablesOffset = _vectorOfStrongReferrables?.isNotEmpty == true
- ? fbBuilder.writeList(_vectorOfStrongReferrables.map((b) => b.getOrCreateOffset(fbBuilder)).toList())
- : null;
- final int vectorOfCoOwningReferencesOffset = _vectorOfCoOwningReferences?.isNotEmpty == true
- ? fbBuilder.writeListUint64(_vectorOfCoOwningReferences)
- : null;
- final int vectorOfNonOwningReferencesOffset = _vectorOfNonOwningReferences?.isNotEmpty == true
- ? fbBuilder.writeListUint64(_vectorOfNonOwningReferences)
- : null;
- final int anyUniqueOffset = _anyUnique?.getOrCreateOffset(fbBuilder);
- final int anyAmbiguousOffset = _anyAmbiguous?.getOrCreateOffset(fbBuilder);
- final int vectorOfEnumsOffset = _vectorOfEnums?.isNotEmpty == true
- ? fbBuilder.writeListUint8(_vectorOfEnums.map((f) => f.value))
- : null;
- final int testrequirednestedflatbufferOffset = _testrequirednestedflatbuffer?.isNotEmpty == true
- ? fbBuilder.writeListUint8(_testrequirednestedflatbuffer)
- : null;
-
- fbBuilder.startTable();
+ int finish(fb.Builder fbBuilder) {
+ final int? nameOffset = _name == null ? null
+ : fbBuilder.writeString(_name!);
+ final int? inventoryOffset = _inventory == null ? null
+ : fbBuilder.writeListUint8(_inventory!);
+ final int? testOffset = _test?.getOrCreateOffset(fbBuilder);
+ final int? test4Offset = _test4 == null ? null
+ : fbBuilder.writeListOfStructs(_test4!);
+ final int? testarrayofstringOffset = _testarrayofstring == null ? null
+ : fbBuilder.writeList(_testarrayofstring!.map(fbBuilder.writeString).toList());
+ final int? testarrayoftablesOffset = _testarrayoftables == null ? null
+ : fbBuilder.writeList(_testarrayoftables!.map((b) => b.getOrCreateOffset(fbBuilder)).toList());
+ final int? enemyOffset = _enemy?.getOrCreateOffset(fbBuilder);
+ final int? testnestedflatbufferOffset = _testnestedflatbuffer == null ? null
+ : fbBuilder.writeListUint8(_testnestedflatbuffer!);
+ final int? testemptyOffset = _testempty?.getOrCreateOffset(fbBuilder);
+ final int? testarrayofboolsOffset = _testarrayofbools == null ? null
+ : fbBuilder.writeListBool(_testarrayofbools!);
+ final int? testarrayofstring2Offset = _testarrayofstring2 == null ? null
+ : fbBuilder.writeList(_testarrayofstring2!.map(fbBuilder.writeString).toList());
+ final int? testarrayofsortedstructOffset = _testarrayofsortedstruct == null ? null
+ : fbBuilder.writeListOfStructs(_testarrayofsortedstruct!);
+ final int? flexOffset = _flex == null ? null
+ : fbBuilder.writeListUint8(_flex!);
+ final int? test5Offset = _test5 == null ? null
+ : fbBuilder.writeListOfStructs(_test5!);
+ final int? vectorOfLongsOffset = _vectorOfLongs == null ? null
+ : fbBuilder.writeListInt64(_vectorOfLongs!);
+ final int? vectorOfDoublesOffset = _vectorOfDoubles == null ? null
+ : fbBuilder.writeListFloat64(_vectorOfDoubles!);
+ final int? parentNamespaceTestOffset = _parentNamespaceTest?.getOrCreateOffset(fbBuilder);
+ final int? vectorOfReferrablesOffset = _vectorOfReferrables == null ? null
+ : fbBuilder.writeList(_vectorOfReferrables!.map((b) => b.getOrCreateOffset(fbBuilder)).toList());
+ final int? vectorOfWeakReferencesOffset = _vectorOfWeakReferences == null ? null
+ : fbBuilder.writeListUint64(_vectorOfWeakReferences!);
+ final int? vectorOfStrongReferrablesOffset = _vectorOfStrongReferrables == null ? null
+ : fbBuilder.writeList(_vectorOfStrongReferrables!.map((b) => b.getOrCreateOffset(fbBuilder)).toList());
+ final int? vectorOfCoOwningReferencesOffset = _vectorOfCoOwningReferences == null ? null
+ : fbBuilder.writeListUint64(_vectorOfCoOwningReferences!);
+ final int? vectorOfNonOwningReferencesOffset = _vectorOfNonOwningReferences == null ? null
+ : fbBuilder.writeListUint64(_vectorOfNonOwningReferences!);
+ final int? anyUniqueOffset = _anyUnique?.getOrCreateOffset(fbBuilder);
+ final int? anyAmbiguousOffset = _anyAmbiguous?.getOrCreateOffset(fbBuilder);
+ final int? vectorOfEnumsOffset = _vectorOfEnums == null ? null
+ : fbBuilder.writeListUint8(_vectorOfEnums!.map((f) => f.value).toList());
+ final int? testrequirednestedflatbufferOffset = _testrequirednestedflatbuffer == null ? null
+ : fbBuilder.writeListUint8(_testrequirednestedflatbuffer!);
+ final int? scalarKeySortedTablesOffset = _scalarKeySortedTables == null ? null
+ : fbBuilder.writeList(_scalarKeySortedTables!.map((b) => b.getOrCreateOffset(fbBuilder)).toList());
+ fbBuilder.startTable(54);
if (_pos != null) {
- fbBuilder.addStruct(0, _pos.finish(fbBuilder));
+ fbBuilder.addStruct(0, _pos!.finish(fbBuilder));
}
fbBuilder.addInt16(1, _mana);
fbBuilder.addInt16(2, _hp);
- if (nameOffset != null) {
- fbBuilder.addOffset(3, nameOffset);
- }
- if (inventoryOffset != null) {
- fbBuilder.addOffset(5, inventoryOffset);
- }
+ fbBuilder.addOffset(3, nameOffset);
+ fbBuilder.addOffset(5, inventoryOffset);
fbBuilder.addUint8(6, _color?.value);
fbBuilder.addUint8(7, _testType?.value);
- if (testOffset != null) {
- fbBuilder.addOffset(8, testOffset);
- }
- if (test4Offset != null) {
- fbBuilder.addOffset(9, test4Offset);
- }
- if (testarrayofstringOffset != null) {
- fbBuilder.addOffset(10, testarrayofstringOffset);
- }
- if (testarrayoftablesOffset != null) {
- fbBuilder.addOffset(11, testarrayoftablesOffset);
- }
- if (enemyOffset != null) {
- fbBuilder.addOffset(12, enemyOffset);
- }
- if (testnestedflatbufferOffset != null) {
- fbBuilder.addOffset(13, testnestedflatbufferOffset);
- }
- if (testemptyOffset != null) {
- fbBuilder.addOffset(14, testemptyOffset);
- }
+ fbBuilder.addOffset(8, testOffset);
+ fbBuilder.addOffset(9, test4Offset);
+ fbBuilder.addOffset(10, testarrayofstringOffset);
+ fbBuilder.addOffset(11, testarrayoftablesOffset);
+ fbBuilder.addOffset(12, enemyOffset);
+ fbBuilder.addOffset(13, testnestedflatbufferOffset);
+ fbBuilder.addOffset(14, testemptyOffset);
fbBuilder.addBool(15, _testbool);
fbBuilder.addInt32(16, _testhashs32Fnv1);
fbBuilder.addUint32(17, _testhashu32Fnv1);
@@ -1296,85 +1952,57 @@
fbBuilder.addUint32(21, _testhashu32Fnv1a);
fbBuilder.addInt64(22, _testhashs64Fnv1a);
fbBuilder.addUint64(23, _testhashu64Fnv1a);
- if (testarrayofboolsOffset != null) {
- fbBuilder.addOffset(24, testarrayofboolsOffset);
- }
+ fbBuilder.addOffset(24, testarrayofboolsOffset);
fbBuilder.addFloat32(25, _testf);
fbBuilder.addFloat32(26, _testf2);
fbBuilder.addFloat32(27, _testf3);
- if (testarrayofstring2Offset != null) {
- fbBuilder.addOffset(28, testarrayofstring2Offset);
- }
- if (testarrayofsortedstructOffset != null) {
- fbBuilder.addOffset(29, testarrayofsortedstructOffset);
- }
- if (flexOffset != null) {
- fbBuilder.addOffset(30, flexOffset);
- }
- if (test5Offset != null) {
- fbBuilder.addOffset(31, test5Offset);
- }
- if (vectorOfLongsOffset != null) {
- fbBuilder.addOffset(32, vectorOfLongsOffset);
- }
- if (vectorOfDoublesOffset != null) {
- fbBuilder.addOffset(33, vectorOfDoublesOffset);
- }
- if (parentNamespaceTestOffset != null) {
- fbBuilder.addOffset(34, parentNamespaceTestOffset);
- }
- if (vectorOfReferrablesOffset != null) {
- fbBuilder.addOffset(35, vectorOfReferrablesOffset);
- }
+ fbBuilder.addOffset(28, testarrayofstring2Offset);
+ fbBuilder.addOffset(29, testarrayofsortedstructOffset);
+ fbBuilder.addOffset(30, flexOffset);
+ fbBuilder.addOffset(31, test5Offset);
+ fbBuilder.addOffset(32, vectorOfLongsOffset);
+ fbBuilder.addOffset(33, vectorOfDoublesOffset);
+ fbBuilder.addOffset(34, parentNamespaceTestOffset);
+ fbBuilder.addOffset(35, vectorOfReferrablesOffset);
fbBuilder.addUint64(36, _singleWeakReference);
- if (vectorOfWeakReferencesOffset != null) {
- fbBuilder.addOffset(37, vectorOfWeakReferencesOffset);
- }
- if (vectorOfStrongReferrablesOffset != null) {
- fbBuilder.addOffset(38, vectorOfStrongReferrablesOffset);
- }
+ fbBuilder.addOffset(37, vectorOfWeakReferencesOffset);
+ fbBuilder.addOffset(38, vectorOfStrongReferrablesOffset);
fbBuilder.addUint64(39, _coOwningReference);
- if (vectorOfCoOwningReferencesOffset != null) {
- fbBuilder.addOffset(40, vectorOfCoOwningReferencesOffset);
- }
+ fbBuilder.addOffset(40, vectorOfCoOwningReferencesOffset);
fbBuilder.addUint64(41, _nonOwningReference);
- if (vectorOfNonOwningReferencesOffset != null) {
- fbBuilder.addOffset(42, vectorOfNonOwningReferencesOffset);
- }
+ fbBuilder.addOffset(42, vectorOfNonOwningReferencesOffset);
fbBuilder.addUint8(43, _anyUniqueType?.value);
- if (anyUniqueOffset != null) {
- fbBuilder.addOffset(44, anyUniqueOffset);
- }
+ fbBuilder.addOffset(44, anyUniqueOffset);
fbBuilder.addUint8(45, _anyAmbiguousType?.value);
- if (anyAmbiguousOffset != null) {
- fbBuilder.addOffset(46, anyAmbiguousOffset);
- }
- if (vectorOfEnumsOffset != null) {
- fbBuilder.addOffset(47, vectorOfEnumsOffset);
- }
+ fbBuilder.addOffset(46, anyAmbiguousOffset);
+ fbBuilder.addOffset(47, vectorOfEnumsOffset);
fbBuilder.addInt8(48, _signedEnum?.value);
- if (testrequirednestedflatbufferOffset != null) {
- fbBuilder.addOffset(49, testrequirednestedflatbufferOffset);
+ fbBuilder.addOffset(49, testrequirednestedflatbufferOffset);
+ fbBuilder.addOffset(50, scalarKeySortedTablesOffset);
+ if (_nativeInline != null) {
+ fbBuilder.addStruct(51, _nativeInline!.finish(fbBuilder));
}
+ fbBuilder.addUint64(52, _longEnumNonEnumDefault?.value);
+ fbBuilder.addUint64(53, _longEnumNormalDefault?.value);
return fbBuilder.endTable();
}
/// Convenience method to serialize to byte list.
@override
- Uint8List toBytes([String fileIdentifier]) {
- fb.Builder fbBuilder = new fb.Builder();
- int offset = finish(fbBuilder);
- return fbBuilder.finish(offset, fileIdentifier);
+ Uint8List toBytes([String? fileIdentifier]) {
+ final fbBuilder = fb.Builder(deduplicateTables: false);
+ fbBuilder.finish(finish(fbBuilder), fileIdentifier);
+ return fbBuilder.buffer;
}
}
class TypeAliases {
TypeAliases._(this._bc, this._bcOffset);
factory TypeAliases(List<int> bytes) {
- fb.BufferContext rootRef = new fb.BufferContext.fromBytes(bytes);
+ final rootRef = fb.BufferContext.fromBytes(bytes);
return reader.read(rootRef, 0);
}
- static const fb.Reader<TypeAliases> reader = const _TypeAliasesReader();
+ static const fb.Reader<TypeAliases> reader = _TypeAliasesReader();
final fb.BufferContext _bc;
final int _bcOffset;
@@ -1389,13 +2017,88 @@
int get u64 => const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 18, 0);
double get f32 => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 20, 0.0);
double get f64 => const fb.Float64Reader().vTableGet(_bc, _bcOffset, 22, 0.0);
- List<int> get v8 => const fb.ListReader<int>(const fb.Int8Reader()).vTableGet(_bc, _bcOffset, 24, null);
- List<double> get vf64 => const fb.ListReader<double>(const fb.Float64Reader()).vTableGet(_bc, _bcOffset, 26, null);
+ List<int>? get v8 => const fb.Int8ListReader().vTableGetNullable(_bc, _bcOffset, 24);
+ List<double>? get vf64 => const fb.ListReader<double>(fb.Float64Reader()).vTableGetNullable(_bc, _bcOffset, 26);
@override
String toString() {
return 'TypeAliases{i8: $i8, u8: $u8, i16: $i16, u16: $u16, i32: $i32, u32: $u32, i64: $i64, u64: $u64, f32: $f32, f64: $f64, v8: $v8, vf64: $vf64}';
}
+
+ TypeAliasesT unpack() => TypeAliasesT(
+ i8: i8,
+ u8: u8,
+ i16: i16,
+ u16: u16,
+ i32: i32,
+ u32: u32,
+ i64: i64,
+ u64: u64,
+ f32: f32,
+ f64: f64,
+ v8: const fb.Int8ListReader(lazy: false).vTableGetNullable(_bc, _bcOffset, 24),
+ vf64: const fb.ListReader<double>(fb.Float64Reader(), lazy: false).vTableGetNullable(_bc, _bcOffset, 26));
+
+ static int pack(fb.Builder fbBuilder, TypeAliasesT? object) {
+ if (object == null) return 0;
+ return object.pack(fbBuilder);
+ }
+}
+
+class TypeAliasesT implements fb.Packable {
+ int i8;
+ int u8;
+ int i16;
+ int u16;
+ int i32;
+ int u32;
+ int i64;
+ int u64;
+ double f32;
+ double f64;
+ List<int>? v8;
+ List<double>? vf64;
+
+ TypeAliasesT({
+ this.i8 = 0,
+ this.u8 = 0,
+ this.i16 = 0,
+ this.u16 = 0,
+ this.i32 = 0,
+ this.u32 = 0,
+ this.i64 = 0,
+ this.u64 = 0,
+ this.f32 = 0.0,
+ this.f64 = 0.0,
+ this.v8,
+ this.vf64});
+
+ @override
+ int pack(fb.Builder fbBuilder) {
+ final int? v8Offset = v8 == null ? null
+ : fbBuilder.writeListInt8(v8!);
+ final int? vf64Offset = vf64 == null ? null
+ : fbBuilder.writeListFloat64(vf64!);
+ fbBuilder.startTable(12);
+ fbBuilder.addInt8(0, i8);
+ fbBuilder.addUint8(1, u8);
+ fbBuilder.addInt16(2, i16);
+ fbBuilder.addUint16(3, u16);
+ fbBuilder.addInt32(4, i32);
+ fbBuilder.addUint32(5, u32);
+ fbBuilder.addInt64(6, i64);
+ fbBuilder.addUint64(7, u64);
+ fbBuilder.addFloat32(8, f32);
+ fbBuilder.addFloat64(9, f64);
+ fbBuilder.addOffset(10, v8Offset);
+ fbBuilder.addOffset(11, vf64Offset);
+ return fbBuilder.endTable();
+ }
+
+ @override
+ String toString() {
+ return 'TypeAliasesT{i8: $i8, u8: $u8, i16: $i16, u16: $u16, i32: $i32, u32: $u32, i64: $i64, u64: $u64, f32: $f32, f64: $f64, v8: $v8, vf64: $vf64}';
+ }
}
class _TypeAliasesReader extends fb.TableReader<TypeAliases> {
@@ -1403,65 +2106,63 @@
@override
TypeAliases createObject(fb.BufferContext bc, int offset) =>
- new TypeAliases._(bc, offset);
+ TypeAliases._(bc, offset);
}
class TypeAliasesBuilder {
- TypeAliasesBuilder(this.fbBuilder) {
- assert(fbBuilder != null);
- }
+ TypeAliasesBuilder(this.fbBuilder);
final fb.Builder fbBuilder;
void begin() {
- fbBuilder.startTable();
+ fbBuilder.startTable(12);
}
- int addI8(int i8) {
+ int addI8(int? i8) {
fbBuilder.addInt8(0, i8);
return fbBuilder.offset;
}
- int addU8(int u8) {
+ int addU8(int? u8) {
fbBuilder.addUint8(1, u8);
return fbBuilder.offset;
}
- int addI16(int i16) {
+ int addI16(int? i16) {
fbBuilder.addInt16(2, i16);
return fbBuilder.offset;
}
- int addU16(int u16) {
+ int addU16(int? u16) {
fbBuilder.addUint16(3, u16);
return fbBuilder.offset;
}
- int addI32(int i32) {
+ int addI32(int? i32) {
fbBuilder.addInt32(4, i32);
return fbBuilder.offset;
}
- int addU32(int u32) {
+ int addU32(int? u32) {
fbBuilder.addUint32(5, u32);
return fbBuilder.offset;
}
- int addI64(int i64) {
+ int addI64(int? i64) {
fbBuilder.addInt64(6, i64);
return fbBuilder.offset;
}
- int addU64(int u64) {
+ int addU64(int? u64) {
fbBuilder.addUint64(7, u64);
return fbBuilder.offset;
}
- int addF32(double f32) {
+ int addF32(double? f32) {
fbBuilder.addFloat32(8, f32);
return fbBuilder.offset;
}
- int addF64(double f64) {
+ int addF64(double? f64) {
fbBuilder.addFloat64(9, f64);
return fbBuilder.offset;
}
- int addV8Offset(int offset) {
+ int addV8Offset(int? offset) {
fbBuilder.addOffset(10, offset);
return fbBuilder.offset;
}
- int addVf64Offset(int offset) {
+ int addVf64Offset(int? offset) {
fbBuilder.addOffset(11, offset);
return fbBuilder.offset;
}
@@ -1472,32 +2173,32 @@
}
class TypeAliasesObjectBuilder extends fb.ObjectBuilder {
- final int _i8;
- final int _u8;
- final int _i16;
- final int _u16;
- final int _i32;
- final int _u32;
- final int _i64;
- final int _u64;
- final double _f32;
- final double _f64;
- final List<int> _v8;
- final List<double> _vf64;
+ final int? _i8;
+ final int? _u8;
+ final int? _i16;
+ final int? _u16;
+ final int? _i32;
+ final int? _u32;
+ final int? _i64;
+ final int? _u64;
+ final double? _f32;
+ final double? _f64;
+ final List<int>? _v8;
+ final List<double>? _vf64;
TypeAliasesObjectBuilder({
- int i8,
- int u8,
- int i16,
- int u16,
- int i32,
- int u32,
- int i64,
- int u64,
- double f32,
- double f64,
- List<int> v8,
- List<double> vf64,
+ int? i8,
+ int? u8,
+ int? i16,
+ int? u16,
+ int? i32,
+ int? u32,
+ int? i64,
+ int? u64,
+ double? f32,
+ double? f64,
+ List<int>? v8,
+ List<double>? vf64,
})
: _i8 = i8,
_u8 = u8,
@@ -1514,17 +2215,12 @@
/// Finish building, and store into the [fbBuilder].
@override
- int finish(
- fb.Builder fbBuilder) {
- assert(fbBuilder != null);
- final int v8Offset = _v8?.isNotEmpty == true
- ? fbBuilder.writeListInt8(_v8)
- : null;
- final int vf64Offset = _vf64?.isNotEmpty == true
- ? fbBuilder.writeListFloat64(_vf64)
- : null;
-
- fbBuilder.startTable();
+ int finish(fb.Builder fbBuilder) {
+ final int? v8Offset = _v8 == null ? null
+ : fbBuilder.writeListInt8(_v8!);
+ final int? vf64Offset = _vf64 == null ? null
+ : fbBuilder.writeListFloat64(_vf64!);
+ fbBuilder.startTable(12);
fbBuilder.addInt8(0, _i8);
fbBuilder.addUint8(1, _u8);
fbBuilder.addInt16(2, _i16);
@@ -1535,20 +2231,16 @@
fbBuilder.addUint64(7, _u64);
fbBuilder.addFloat32(8, _f32);
fbBuilder.addFloat64(9, _f64);
- if (v8Offset != null) {
- fbBuilder.addOffset(10, v8Offset);
- }
- if (vf64Offset != null) {
- fbBuilder.addOffset(11, vf64Offset);
- }
+ fbBuilder.addOffset(10, v8Offset);
+ fbBuilder.addOffset(11, vf64Offset);
return fbBuilder.endTable();
}
/// Convenience method to serialize to byte list.
@override
- Uint8List toBytes([String fileIdentifier]) {
- fb.Builder fbBuilder = new fb.Builder();
- int offset = finish(fbBuilder);
- return fbBuilder.finish(offset, fileIdentifier);
+ Uint8List toBytes([String? fileIdentifier]) {
+ final fbBuilder = fb.Builder(deduplicateTables: false);
+ fbBuilder.finish(finish(fbBuilder), fileIdentifier);
+ return fbBuilder.buffer;
}
}
diff --git a/tests/monster_test_my_game_generated.dart b/tests/monster_test_my_game_generated.dart
index abd538c..70e256c 100644
--- a/tests/monster_test_my_game_generated.dart
+++ b/tests/monster_test_my_game_generated.dart
@@ -1,5 +1,5 @@
// automatically generated by the FlatBuffers compiler, do not modify
-// ignore_for_file: unused_import, unused_field, unused_local_variable
+// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable
library my_game;
@@ -12,11 +12,11 @@
class InParentNamespace {
InParentNamespace._(this._bc, this._bcOffset);
factory InParentNamespace(List<int> bytes) {
- fb.BufferContext rootRef = new fb.BufferContext.fromBytes(bytes);
+ final rootRef = fb.BufferContext.fromBytes(bytes);
return reader.read(rootRef, 0);
}
- static const fb.Reader<InParentNamespace> reader = const _InParentNamespaceReader();
+ static const fb.Reader<InParentNamespace> reader = _InParentNamespaceReader();
final fb.BufferContext _bc;
final int _bcOffset;
@@ -26,6 +26,26 @@
String toString() {
return 'InParentNamespace{}';
}
+
+ InParentNamespaceT unpack() => InParentNamespaceT();
+
+ static int pack(fb.Builder fbBuilder, InParentNamespaceT? object) {
+ if (object == null) return 0;
+ return object.pack(fbBuilder);
+ }
+}
+
+class InParentNamespaceT implements fb.Packable {
+ @override
+ int pack(fb.Builder fbBuilder) {
+ fbBuilder.startTable(0);
+ return fbBuilder.endTable();
+ }
+
+ @override
+ String toString() {
+ return 'InParentNamespaceT{}';
+ }
}
class _InParentNamespaceReader extends fb.TableReader<InParentNamespace> {
@@ -33,7 +53,7 @@
@override
InParentNamespace createObject(fb.BufferContext bc, int offset) =>
- new InParentNamespace._(bc, offset);
+ InParentNamespace._(bc, offset);
}
class InParentNamespaceObjectBuilder extends fb.ObjectBuilder {
@@ -42,19 +62,16 @@
/// Finish building, and store into the [fbBuilder].
@override
- int finish(
- fb.Builder fbBuilder) {
- assert(fbBuilder != null);
-
- fbBuilder.startTable();
+ int finish(fb.Builder fbBuilder) {
+ fbBuilder.startTable(0);
return fbBuilder.endTable();
}
/// Convenience method to serialize to byte list.
@override
- Uint8List toBytes([String fileIdentifier]) {
- fb.Builder fbBuilder = new fb.Builder();
- int offset = finish(fbBuilder);
- return fbBuilder.finish(offset, fileIdentifier);
+ Uint8List toBytes([String? fileIdentifier]) {
+ final fbBuilder = fb.Builder(deduplicateTables: false);
+ fbBuilder.finish(finish(fbBuilder), fileIdentifier);
+ return fbBuilder.buffer;
}
}
diff --git a/tests/monster_test_serialize/mod.rs b/tests/monster_test_serialize/mod.rs
new file mode 100644
index 0000000..fdbc26b
--- /dev/null
+++ b/tests/monster_test_serialize/mod.rs
@@ -0,0 +1,55 @@
+// Automatically generated by the Flatbuffers compiler. Do not modify.
+pub mod my_game {
+ use super::*;
+ pub mod example {
+ use super::*;
+ mod color_generated;
+ pub use self::color_generated::*;
+ mod race_generated;
+ pub use self::race_generated::*;
+ mod long_enum_generated;
+ pub use self::long_enum_generated::*;
+ mod any_generated;
+ pub use self::any_generated::*;
+ mod any_unique_aliases_generated;
+ pub use self::any_unique_aliases_generated::*;
+ mod any_ambiguous_aliases_generated;
+ pub use self::any_ambiguous_aliases_generated::*;
+ mod test_generated;
+ pub use self::test_generated::*;
+ mod test_simple_table_with_enum_generated;
+ pub use self::test_simple_table_with_enum_generated::*;
+ mod vec_3_generated;
+ pub use self::vec_3_generated::*;
+ mod ability_generated;
+ pub use self::ability_generated::*;
+ mod struct_of_structs_generated;
+ pub use self::struct_of_structs_generated::*;
+ mod stat_generated;
+ pub use self::stat_generated::*;
+ mod referrable_generated;
+ pub use self::referrable_generated::*;
+ mod monster_generated;
+ pub use self::monster_generated::*;
+ mod type_aliases_generated;
+ pub use self::type_aliases_generated::*;
+ } // example
+ pub mod example_2 {
+ use super::*;
+ mod monster_generated;
+ pub use self::monster_generated::*;
+ } // example_2
+ pub mod other_name_space {
+ use super::*;
+ mod from_include_generated;
+ pub use self::from_include_generated::*;
+ mod unused_generated;
+ pub use self::unused_generated::*;
+ mod table_b_generated;
+ pub use self::table_b_generated::*;
+ } // other_name_space
+ mod in_parent_namespace_generated;
+ pub use self::in_parent_namespace_generated::*;
+} // my_game
+mod table_a_generated;
+pub use self::table_a_generated::*;
diff --git a/tests/monster_test_serialize/my_game/example/ability_generated.rs b/tests/monster_test_serialize/my_game/example/ability_generated.rs
new file mode 100644
index 0000000..cdc7882
--- /dev/null
+++ b/tests/monster_test_serialize/my_game/example/ability_generated.rs
@@ -0,0 +1,180 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+extern crate serde;
+use self::serde::ser::{Serialize, Serializer, SerializeStruct};
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+// struct Ability, aligned to 4
+#[repr(transparent)]
+#[derive(Clone, Copy, PartialEq)]
+pub struct Ability(pub [u8; 8]);
+impl Default for Ability {
+ fn default() -> Self {
+ Self([0; 8])
+ }
+}
+impl std::fmt::Debug for Ability {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ f.debug_struct("Ability")
+ .field("id", &self.id())
+ .field("distance", &self.distance())
+ .finish()
+ }
+}
+
+impl flatbuffers::SimpleToVerifyInSlice for Ability {}
+impl flatbuffers::SafeSliceAccess for Ability {}
+impl<'a> flatbuffers::Follow<'a> for Ability {
+ type Inner = &'a Ability;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ <&'a Ability>::follow(buf, loc)
+ }
+}
+impl<'a> flatbuffers::Follow<'a> for &'a Ability {
+ type Inner = &'a Ability;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ flatbuffers::follow_cast_ref::<Ability>(buf, loc)
+ }
+}
+impl<'b> flatbuffers::Push for Ability {
+ type Output = Ability;
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ let src = unsafe {
+ ::std::slice::from_raw_parts(self as *const Ability as *const u8, Self::size())
+ };
+ dst.copy_from_slice(src);
+ }
+}
+impl<'b> flatbuffers::Push for &'b Ability {
+ type Output = Ability;
+
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ let src = unsafe {
+ ::std::slice::from_raw_parts(*self as *const Ability as *const u8, Self::size())
+ };
+ dst.copy_from_slice(src);
+ }
+}
+
+impl<'a> flatbuffers::Verifiable for Ability {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ v.in_buffer::<Self>(pos)
+ }
+}
+
+impl Serialize for Ability {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: Serializer,
+ {
+ let mut s = serializer.serialize_struct("Ability", 2)?;
+ s.serialize_field("id", &self.id())?;
+ s.serialize_field("distance", &self.distance())?;
+ s.end()
+ }
+}
+
+impl<'a> Ability {
+ #[allow(clippy::too_many_arguments)]
+ pub fn new(
+ id: u32,
+ distance: u32,
+ ) -> Self {
+ let mut s = Self([0; 8]);
+ s.set_id(id);
+ s.set_distance(distance);
+ s
+ }
+
+ pub const fn get_fully_qualified_name() -> &'static str {
+ "MyGame.Example.Ability"
+ }
+
+ pub fn id(&self) -> u32 {
+ let mut mem = core::mem::MaybeUninit::<u32>::uninit();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ self.0[0..].as_ptr(),
+ mem.as_mut_ptr() as *mut u8,
+ core::mem::size_of::<u32>(),
+ );
+ mem.assume_init()
+ }.from_little_endian()
+ }
+
+ pub fn set_id(&mut self, x: u32) {
+ let x_le = x.to_little_endian();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ &x_le as *const u32 as *const u8,
+ self.0[0..].as_mut_ptr(),
+ core::mem::size_of::<u32>(),
+ );
+ }
+ }
+
+ #[inline]
+ pub fn key_compare_less_than(&self, o: &Ability) -> bool {
+ self.id() < o.id()
+ }
+
+ #[inline]
+ pub fn key_compare_with_value(&self, val: u32) -> ::std::cmp::Ordering {
+ let key = self.id();
+ key.cmp(&val)
+ }
+ pub fn distance(&self) -> u32 {
+ let mut mem = core::mem::MaybeUninit::<u32>::uninit();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ self.0[4..].as_ptr(),
+ mem.as_mut_ptr() as *mut u8,
+ core::mem::size_of::<u32>(),
+ );
+ mem.assume_init()
+ }.from_little_endian()
+ }
+
+ pub fn set_distance(&mut self, x: u32) {
+ let x_le = x.to_little_endian();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ &x_le as *const u32 as *const u8,
+ self.0[4..].as_mut_ptr(),
+ core::mem::size_of::<u32>(),
+ );
+ }
+ }
+
+ pub fn unpack(&self) -> AbilityT {
+ AbilityT {
+ id: self.id(),
+ distance: self.distance(),
+ }
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Default)]
+pub struct AbilityT {
+ pub id: u32,
+ pub distance: u32,
+}
+impl AbilityT {
+ pub fn pack(&self) -> Ability {
+ Ability::new(
+ self.id,
+ self.distance,
+ )
+ }
+}
+
diff --git a/tests/monster_test_serialize/my_game/example/any_ambiguous_aliases_generated.rs b/tests/monster_test_serialize/my_game/example/any_ambiguous_aliases_generated.rs
new file mode 100644
index 0000000..2e757a8
--- /dev/null
+++ b/tests/monster_test_serialize/my_game/example/any_ambiguous_aliases_generated.rs
@@ -0,0 +1,209 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+extern crate serde;
+use self::serde::ser::{Serialize, Serializer, SerializeStruct};
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+pub const ENUM_MIN_ANY_AMBIGUOUS_ALIASES: u8 = 0;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+pub const ENUM_MAX_ANY_AMBIGUOUS_ALIASES: u8 = 3;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+#[allow(non_camel_case_types)]
+pub const ENUM_VALUES_ANY_AMBIGUOUS_ALIASES: [AnyAmbiguousAliases; 4] = [
+ AnyAmbiguousAliases::NONE,
+ AnyAmbiguousAliases::M1,
+ AnyAmbiguousAliases::M2,
+ AnyAmbiguousAliases::M3,
+];
+
+#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
+#[repr(transparent)]
+pub struct AnyAmbiguousAliases(pub u8);
+#[allow(non_upper_case_globals)]
+impl AnyAmbiguousAliases {
+ pub const NONE: Self = Self(0);
+ pub const M1: Self = Self(1);
+ pub const M2: Self = Self(2);
+ pub const M3: Self = Self(3);
+
+ pub const ENUM_MIN: u8 = 0;
+ pub const ENUM_MAX: u8 = 3;
+ pub const ENUM_VALUES: &'static [Self] = &[
+ Self::NONE,
+ Self::M1,
+ Self::M2,
+ Self::M3,
+ ];
+ /// Returns the variant's name or "" if unknown.
+ pub fn variant_name(self) -> Option<&'static str> {
+ match self {
+ Self::NONE => Some("NONE"),
+ Self::M1 => Some("M1"),
+ Self::M2 => Some("M2"),
+ Self::M3 => Some("M3"),
+ _ => None,
+ }
+ }
+}
+impl std::fmt::Debug for AnyAmbiguousAliases {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ if let Some(name) = self.variant_name() {
+ f.write_str(name)
+ } else {
+ f.write_fmt(format_args!("<UNKNOWN {:?}>", self.0))
+ }
+ }
+}
+impl Serialize for AnyAmbiguousAliases {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: Serializer,
+ {
+ serializer.serialize_unit_variant("AnyAmbiguousAliases", self.0 as u32, self.variant_name().unwrap())
+ }
+}
+
+impl<'a> flatbuffers::Follow<'a> for AnyAmbiguousAliases {
+ type Inner = Self;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ let b = unsafe {
+ flatbuffers::read_scalar_at::<u8>(buf, loc)
+ };
+ Self(b)
+ }
+}
+
+impl flatbuffers::Push for AnyAmbiguousAliases {
+ type Output = AnyAmbiguousAliases;
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ unsafe { flatbuffers::emplace_scalar::<u8>(dst, self.0); }
+ }
+}
+
+impl flatbuffers::EndianScalar for AnyAmbiguousAliases {
+ #[inline]
+ fn to_little_endian(self) -> Self {
+ let b = u8::to_le(self.0);
+ Self(b)
+ }
+ #[inline]
+ #[allow(clippy::wrong_self_convention)]
+ fn from_little_endian(self) -> Self {
+ let b = u8::from_le(self.0);
+ Self(b)
+ }
+}
+
+impl<'a> flatbuffers::Verifiable for AnyAmbiguousAliases {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ u8::run_verifier(v, pos)
+ }
+}
+
+impl flatbuffers::SimpleToVerifyInSlice for AnyAmbiguousAliases {}
+pub struct AnyAmbiguousAliasesUnionTableOffset {}
+
+#[allow(clippy::upper_case_acronyms)]
+#[non_exhaustive]
+#[derive(Debug, Clone, PartialEq)]
+pub enum AnyAmbiguousAliasesT {
+ NONE,
+ M1(Box<MonsterT>),
+ M2(Box<MonsterT>),
+ M3(Box<MonsterT>),
+}
+impl Default for AnyAmbiguousAliasesT {
+ fn default() -> Self {
+ Self::NONE
+ }
+}
+impl AnyAmbiguousAliasesT {
+ pub fn any_ambiguous_aliases_type(&self) -> AnyAmbiguousAliases {
+ match self {
+ Self::NONE => AnyAmbiguousAliases::NONE,
+ Self::M1(_) => AnyAmbiguousAliases::M1,
+ Self::M2(_) => AnyAmbiguousAliases::M2,
+ Self::M3(_) => AnyAmbiguousAliases::M3,
+ }
+ }
+ pub fn pack(&self, fbb: &mut flatbuffers::FlatBufferBuilder) -> Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>> {
+ match self {
+ Self::NONE => None,
+ Self::M1(v) => Some(v.pack(fbb).as_union_value()),
+ Self::M2(v) => Some(v.pack(fbb).as_union_value()),
+ Self::M3(v) => Some(v.pack(fbb).as_union_value()),
+ }
+ }
+ /// If the union variant matches, return the owned MonsterT, setting the union to NONE.
+ pub fn take_m1(&mut self) -> Option<Box<MonsterT>> {
+ if let Self::M1(_) = self {
+ let v = std::mem::replace(self, Self::NONE);
+ if let Self::M1(w) = v {
+ Some(w)
+ } else {
+ unreachable!()
+ }
+ } else {
+ None
+ }
+ }
+ /// If the union variant matches, return a reference to the MonsterT.
+ pub fn as_m1(&self) -> Option<&MonsterT> {
+ if let Self::M1(v) = self { Some(v.as_ref()) } else { None }
+ }
+ /// If the union variant matches, return a mutable reference to the MonsterT.
+ pub fn as_m1_mut(&mut self) -> Option<&mut MonsterT> {
+ if let Self::M1(v) = self { Some(v.as_mut()) } else { None }
+ }
+ /// If the union variant matches, return the owned MonsterT, setting the union to NONE.
+ pub fn take_m2(&mut self) -> Option<Box<MonsterT>> {
+ if let Self::M2(_) = self {
+ let v = std::mem::replace(self, Self::NONE);
+ if let Self::M2(w) = v {
+ Some(w)
+ } else {
+ unreachable!()
+ }
+ } else {
+ None
+ }
+ }
+ /// If the union variant matches, return a reference to the MonsterT.
+ pub fn as_m2(&self) -> Option<&MonsterT> {
+ if let Self::M2(v) = self { Some(v.as_ref()) } else { None }
+ }
+ /// If the union variant matches, return a mutable reference to the MonsterT.
+ pub fn as_m2_mut(&mut self) -> Option<&mut MonsterT> {
+ if let Self::M2(v) = self { Some(v.as_mut()) } else { None }
+ }
+ /// If the union variant matches, return the owned MonsterT, setting the union to NONE.
+ pub fn take_m3(&mut self) -> Option<Box<MonsterT>> {
+ if let Self::M3(_) = self {
+ let v = std::mem::replace(self, Self::NONE);
+ if let Self::M3(w) = v {
+ Some(w)
+ } else {
+ unreachable!()
+ }
+ } else {
+ None
+ }
+ }
+ /// If the union variant matches, return a reference to the MonsterT.
+ pub fn as_m3(&self) -> Option<&MonsterT> {
+ if let Self::M3(v) = self { Some(v.as_ref()) } else { None }
+ }
+ /// If the union variant matches, return a mutable reference to the MonsterT.
+ pub fn as_m3_mut(&mut self) -> Option<&mut MonsterT> {
+ if let Self::M3(v) = self { Some(v.as_mut()) } else { None }
+ }
+}
diff --git a/tests/monster_test_serialize/my_game/example/any_generated.rs b/tests/monster_test_serialize/my_game/example/any_generated.rs
new file mode 100644
index 0000000..d572642
--- /dev/null
+++ b/tests/monster_test_serialize/my_game/example/any_generated.rs
@@ -0,0 +1,209 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+extern crate serde;
+use self::serde::ser::{Serialize, Serializer, SerializeStruct};
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+pub const ENUM_MIN_ANY: u8 = 0;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+pub const ENUM_MAX_ANY: u8 = 3;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+#[allow(non_camel_case_types)]
+pub const ENUM_VALUES_ANY: [Any; 4] = [
+ Any::NONE,
+ Any::Monster,
+ Any::TestSimpleTableWithEnum,
+ Any::MyGame_Example2_Monster,
+];
+
+#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
+#[repr(transparent)]
+pub struct Any(pub u8);
+#[allow(non_upper_case_globals)]
+impl Any {
+ pub const NONE: Self = Self(0);
+ pub const Monster: Self = Self(1);
+ pub const TestSimpleTableWithEnum: Self = Self(2);
+ pub const MyGame_Example2_Monster: Self = Self(3);
+
+ pub const ENUM_MIN: u8 = 0;
+ pub const ENUM_MAX: u8 = 3;
+ pub const ENUM_VALUES: &'static [Self] = &[
+ Self::NONE,
+ Self::Monster,
+ Self::TestSimpleTableWithEnum,
+ Self::MyGame_Example2_Monster,
+ ];
+ /// Returns the variant's name or "" if unknown.
+ pub fn variant_name(self) -> Option<&'static str> {
+ match self {
+ Self::NONE => Some("NONE"),
+ Self::Monster => Some("Monster"),
+ Self::TestSimpleTableWithEnum => Some("TestSimpleTableWithEnum"),
+ Self::MyGame_Example2_Monster => Some("MyGame_Example2_Monster"),
+ _ => None,
+ }
+ }
+}
+impl std::fmt::Debug for Any {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ if let Some(name) = self.variant_name() {
+ f.write_str(name)
+ } else {
+ f.write_fmt(format_args!("<UNKNOWN {:?}>", self.0))
+ }
+ }
+}
+impl Serialize for Any {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: Serializer,
+ {
+ serializer.serialize_unit_variant("Any", self.0 as u32, self.variant_name().unwrap())
+ }
+}
+
+impl<'a> flatbuffers::Follow<'a> for Any {
+ type Inner = Self;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ let b = unsafe {
+ flatbuffers::read_scalar_at::<u8>(buf, loc)
+ };
+ Self(b)
+ }
+}
+
+impl flatbuffers::Push for Any {
+ type Output = Any;
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ unsafe { flatbuffers::emplace_scalar::<u8>(dst, self.0); }
+ }
+}
+
+impl flatbuffers::EndianScalar for Any {
+ #[inline]
+ fn to_little_endian(self) -> Self {
+ let b = u8::to_le(self.0);
+ Self(b)
+ }
+ #[inline]
+ #[allow(clippy::wrong_self_convention)]
+ fn from_little_endian(self) -> Self {
+ let b = u8::from_le(self.0);
+ Self(b)
+ }
+}
+
+impl<'a> flatbuffers::Verifiable for Any {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ u8::run_verifier(v, pos)
+ }
+}
+
+impl flatbuffers::SimpleToVerifyInSlice for Any {}
+pub struct AnyUnionTableOffset {}
+
+#[allow(clippy::upper_case_acronyms)]
+#[non_exhaustive]
+#[derive(Debug, Clone, PartialEq)]
+pub enum AnyT {
+ NONE,
+ Monster(Box<MonsterT>),
+ TestSimpleTableWithEnum(Box<TestSimpleTableWithEnumT>),
+ MyGameExample2Monster(Box<super::example_2::MonsterT>),
+}
+impl Default for AnyT {
+ fn default() -> Self {
+ Self::NONE
+ }
+}
+impl AnyT {
+ pub fn any_type(&self) -> Any {
+ match self {
+ Self::NONE => Any::NONE,
+ Self::Monster(_) => Any::Monster,
+ Self::TestSimpleTableWithEnum(_) => Any::TestSimpleTableWithEnum,
+ Self::MyGameExample2Monster(_) => Any::MyGame_Example2_Monster,
+ }
+ }
+ pub fn pack(&self, fbb: &mut flatbuffers::FlatBufferBuilder) -> Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>> {
+ match self {
+ Self::NONE => None,
+ Self::Monster(v) => Some(v.pack(fbb).as_union_value()),
+ Self::TestSimpleTableWithEnum(v) => Some(v.pack(fbb).as_union_value()),
+ Self::MyGameExample2Monster(v) => Some(v.pack(fbb).as_union_value()),
+ }
+ }
+ /// If the union variant matches, return the owned MonsterT, setting the union to NONE.
+ pub fn take_monster(&mut self) -> Option<Box<MonsterT>> {
+ if let Self::Monster(_) = self {
+ let v = std::mem::replace(self, Self::NONE);
+ if let Self::Monster(w) = v {
+ Some(w)
+ } else {
+ unreachable!()
+ }
+ } else {
+ None
+ }
+ }
+ /// If the union variant matches, return a reference to the MonsterT.
+ pub fn as_monster(&self) -> Option<&MonsterT> {
+ if let Self::Monster(v) = self { Some(v.as_ref()) } else { None }
+ }
+ /// If the union variant matches, return a mutable reference to the MonsterT.
+ pub fn as_monster_mut(&mut self) -> Option<&mut MonsterT> {
+ if let Self::Monster(v) = self { Some(v.as_mut()) } else { None }
+ }
+ /// If the union variant matches, return the owned TestSimpleTableWithEnumT, setting the union to NONE.
+ pub fn take_test_simple_table_with_enum(&mut self) -> Option<Box<TestSimpleTableWithEnumT>> {
+ if let Self::TestSimpleTableWithEnum(_) = self {
+ let v = std::mem::replace(self, Self::NONE);
+ if let Self::TestSimpleTableWithEnum(w) = v {
+ Some(w)
+ } else {
+ unreachable!()
+ }
+ } else {
+ None
+ }
+ }
+ /// If the union variant matches, return a reference to the TestSimpleTableWithEnumT.
+ pub fn as_test_simple_table_with_enum(&self) -> Option<&TestSimpleTableWithEnumT> {
+ if let Self::TestSimpleTableWithEnum(v) = self { Some(v.as_ref()) } else { None }
+ }
+ /// If the union variant matches, return a mutable reference to the TestSimpleTableWithEnumT.
+ pub fn as_test_simple_table_with_enum_mut(&mut self) -> Option<&mut TestSimpleTableWithEnumT> {
+ if let Self::TestSimpleTableWithEnum(v) = self { Some(v.as_mut()) } else { None }
+ }
+ /// If the union variant matches, return the owned super::example_2::MonsterT, setting the union to NONE.
+ pub fn take_my_game_example_2_monster(&mut self) -> Option<Box<super::example_2::MonsterT>> {
+ if let Self::MyGameExample2Monster(_) = self {
+ let v = std::mem::replace(self, Self::NONE);
+ if let Self::MyGameExample2Monster(w) = v {
+ Some(w)
+ } else {
+ unreachable!()
+ }
+ } else {
+ None
+ }
+ }
+ /// If the union variant matches, return a reference to the super::example_2::MonsterT.
+ pub fn as_my_game_example_2_monster(&self) -> Option<&super::example_2::MonsterT> {
+ if let Self::MyGameExample2Monster(v) = self { Some(v.as_ref()) } else { None }
+ }
+ /// If the union variant matches, return a mutable reference to the super::example_2::MonsterT.
+ pub fn as_my_game_example_2_monster_mut(&mut self) -> Option<&mut super::example_2::MonsterT> {
+ if let Self::MyGameExample2Monster(v) = self { Some(v.as_mut()) } else { None }
+ }
+}
diff --git a/tests/monster_test_serialize/my_game/example/any_unique_aliases_generated.rs b/tests/monster_test_serialize/my_game/example/any_unique_aliases_generated.rs
new file mode 100644
index 0000000..8a3fa66
--- /dev/null
+++ b/tests/monster_test_serialize/my_game/example/any_unique_aliases_generated.rs
@@ -0,0 +1,209 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+extern crate serde;
+use self::serde::ser::{Serialize, Serializer, SerializeStruct};
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+pub const ENUM_MIN_ANY_UNIQUE_ALIASES: u8 = 0;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+pub const ENUM_MAX_ANY_UNIQUE_ALIASES: u8 = 3;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+#[allow(non_camel_case_types)]
+pub const ENUM_VALUES_ANY_UNIQUE_ALIASES: [AnyUniqueAliases; 4] = [
+ AnyUniqueAliases::NONE,
+ AnyUniqueAliases::M,
+ AnyUniqueAliases::TS,
+ AnyUniqueAliases::M2,
+];
+
+#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
+#[repr(transparent)]
+pub struct AnyUniqueAliases(pub u8);
+#[allow(non_upper_case_globals)]
+impl AnyUniqueAliases {
+ pub const NONE: Self = Self(0);
+ pub const M: Self = Self(1);
+ pub const TS: Self = Self(2);
+ pub const M2: Self = Self(3);
+
+ pub const ENUM_MIN: u8 = 0;
+ pub const ENUM_MAX: u8 = 3;
+ pub const ENUM_VALUES: &'static [Self] = &[
+ Self::NONE,
+ Self::M,
+ Self::TS,
+ Self::M2,
+ ];
+ /// Returns the variant's name or "" if unknown.
+ pub fn variant_name(self) -> Option<&'static str> {
+ match self {
+ Self::NONE => Some("NONE"),
+ Self::M => Some("M"),
+ Self::TS => Some("TS"),
+ Self::M2 => Some("M2"),
+ _ => None,
+ }
+ }
+}
+impl std::fmt::Debug for AnyUniqueAliases {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ if let Some(name) = self.variant_name() {
+ f.write_str(name)
+ } else {
+ f.write_fmt(format_args!("<UNKNOWN {:?}>", self.0))
+ }
+ }
+}
+impl Serialize for AnyUniqueAliases {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: Serializer,
+ {
+ serializer.serialize_unit_variant("AnyUniqueAliases", self.0 as u32, self.variant_name().unwrap())
+ }
+}
+
+impl<'a> flatbuffers::Follow<'a> for AnyUniqueAliases {
+ type Inner = Self;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ let b = unsafe {
+ flatbuffers::read_scalar_at::<u8>(buf, loc)
+ };
+ Self(b)
+ }
+}
+
+impl flatbuffers::Push for AnyUniqueAliases {
+ type Output = AnyUniqueAliases;
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ unsafe { flatbuffers::emplace_scalar::<u8>(dst, self.0); }
+ }
+}
+
+impl flatbuffers::EndianScalar for AnyUniqueAliases {
+ #[inline]
+ fn to_little_endian(self) -> Self {
+ let b = u8::to_le(self.0);
+ Self(b)
+ }
+ #[inline]
+ #[allow(clippy::wrong_self_convention)]
+ fn from_little_endian(self) -> Self {
+ let b = u8::from_le(self.0);
+ Self(b)
+ }
+}
+
+impl<'a> flatbuffers::Verifiable for AnyUniqueAliases {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ u8::run_verifier(v, pos)
+ }
+}
+
+impl flatbuffers::SimpleToVerifyInSlice for AnyUniqueAliases {}
+pub struct AnyUniqueAliasesUnionTableOffset {}
+
+#[allow(clippy::upper_case_acronyms)]
+#[non_exhaustive]
+#[derive(Debug, Clone, PartialEq)]
+pub enum AnyUniqueAliasesT {
+ NONE,
+ M(Box<MonsterT>),
+ TS(Box<TestSimpleTableWithEnumT>),
+ M2(Box<super::example_2::MonsterT>),
+}
+impl Default for AnyUniqueAliasesT {
+ fn default() -> Self {
+ Self::NONE
+ }
+}
+impl AnyUniqueAliasesT {
+ pub fn any_unique_aliases_type(&self) -> AnyUniqueAliases {
+ match self {
+ Self::NONE => AnyUniqueAliases::NONE,
+ Self::M(_) => AnyUniqueAliases::M,
+ Self::TS(_) => AnyUniqueAliases::TS,
+ Self::M2(_) => AnyUniqueAliases::M2,
+ }
+ }
+ pub fn pack(&self, fbb: &mut flatbuffers::FlatBufferBuilder) -> Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>> {
+ match self {
+ Self::NONE => None,
+ Self::M(v) => Some(v.pack(fbb).as_union_value()),
+ Self::TS(v) => Some(v.pack(fbb).as_union_value()),
+ Self::M2(v) => Some(v.pack(fbb).as_union_value()),
+ }
+ }
+ /// If the union variant matches, return the owned MonsterT, setting the union to NONE.
+ pub fn take_m(&mut self) -> Option<Box<MonsterT>> {
+ if let Self::M(_) = self {
+ let v = std::mem::replace(self, Self::NONE);
+ if let Self::M(w) = v {
+ Some(w)
+ } else {
+ unreachable!()
+ }
+ } else {
+ None
+ }
+ }
+ /// If the union variant matches, return a reference to the MonsterT.
+ pub fn as_m(&self) -> Option<&MonsterT> {
+ if let Self::M(v) = self { Some(v.as_ref()) } else { None }
+ }
+ /// If the union variant matches, return a mutable reference to the MonsterT.
+ pub fn as_m_mut(&mut self) -> Option<&mut MonsterT> {
+ if let Self::M(v) = self { Some(v.as_mut()) } else { None }
+ }
+ /// If the union variant matches, return the owned TestSimpleTableWithEnumT, setting the union to NONE.
+ pub fn take_ts(&mut self) -> Option<Box<TestSimpleTableWithEnumT>> {
+ if let Self::TS(_) = self {
+ let v = std::mem::replace(self, Self::NONE);
+ if let Self::TS(w) = v {
+ Some(w)
+ } else {
+ unreachable!()
+ }
+ } else {
+ None
+ }
+ }
+ /// If the union variant matches, return a reference to the TestSimpleTableWithEnumT.
+ pub fn as_ts(&self) -> Option<&TestSimpleTableWithEnumT> {
+ if let Self::TS(v) = self { Some(v.as_ref()) } else { None }
+ }
+ /// If the union variant matches, return a mutable reference to the TestSimpleTableWithEnumT.
+ pub fn as_ts_mut(&mut self) -> Option<&mut TestSimpleTableWithEnumT> {
+ if let Self::TS(v) = self { Some(v.as_mut()) } else { None }
+ }
+ /// If the union variant matches, return the owned super::example_2::MonsterT, setting the union to NONE.
+ pub fn take_m2(&mut self) -> Option<Box<super::example_2::MonsterT>> {
+ if let Self::M2(_) = self {
+ let v = std::mem::replace(self, Self::NONE);
+ if let Self::M2(w) = v {
+ Some(w)
+ } else {
+ unreachable!()
+ }
+ } else {
+ None
+ }
+ }
+ /// If the union variant matches, return a reference to the super::example_2::MonsterT.
+ pub fn as_m2(&self) -> Option<&super::example_2::MonsterT> {
+ if let Self::M2(v) = self { Some(v.as_ref()) } else { None }
+ }
+ /// If the union variant matches, return a mutable reference to the super::example_2::MonsterT.
+ pub fn as_m2_mut(&mut self) -> Option<&mut super::example_2::MonsterT> {
+ if let Self::M2(v) = self { Some(v.as_mut()) } else { None }
+ }
+}
diff --git a/tests/monster_test_serialize/my_game/example/color_generated.rs b/tests/monster_test_serialize/my_game/example/color_generated.rs
new file mode 100644
index 0000000..e27f79c
--- /dev/null
+++ b/tests/monster_test_serialize/my_game/example/color_generated.rs
@@ -0,0 +1,78 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+extern crate serde;
+use self::serde::ser::{Serialize, Serializer, SerializeStruct};
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+#[allow(non_upper_case_globals)]
+mod bitflags_color {
+ flatbuffers::bitflags::bitflags! {
+ /// Composite components of Monster color.
+ #[derive(Default)]
+ pub struct Color: u8 {
+ const Red = 1;
+ /// \brief color Green
+ /// Green is bit_flag with value (1u << 1)
+ const Green = 2;
+ /// \brief color Blue (1u << 3)
+ const Blue = 8;
+ }
+ }
+}
+pub use self::bitflags_color::Color;
+
+impl Serialize for Color {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: Serializer,
+ {
+ serializer.serialize_u32(self.bits() as u32)
+ }
+}
+
+impl<'a> flatbuffers::Follow<'a> for Color {
+ type Inner = Self;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ let b = unsafe {
+ flatbuffers::read_scalar_at::<u8>(buf, loc)
+ };
+ unsafe { Self::from_bits_unchecked(b) }
+ }
+}
+
+impl flatbuffers::Push for Color {
+ type Output = Color;
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ unsafe { flatbuffers::emplace_scalar::<u8>(dst, self.bits()); }
+ }
+}
+
+impl flatbuffers::EndianScalar for Color {
+ #[inline]
+ fn to_little_endian(self) -> Self {
+ let b = u8::to_le(self.bits());
+ unsafe { Self::from_bits_unchecked(b) }
+ }
+ #[inline]
+ #[allow(clippy::wrong_self_convention)]
+ fn from_little_endian(self) -> Self {
+ let b = u8::from_le(self.bits());
+ unsafe { Self::from_bits_unchecked(b) }
+ }
+}
+
+impl<'a> flatbuffers::Verifiable for Color {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ u8::run_verifier(v, pos)
+ }
+}
+
+impl flatbuffers::SimpleToVerifyInSlice for Color {}
diff --git a/tests/monster_test_serialize/my_game/example/long_enum_generated.rs b/tests/monster_test_serialize/my_game/example/long_enum_generated.rs
new file mode 100644
index 0000000..f513d29
--- /dev/null
+++ b/tests/monster_test_serialize/my_game/example/long_enum_generated.rs
@@ -0,0 +1,74 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+extern crate serde;
+use self::serde::ser::{Serialize, Serializer, SerializeStruct};
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+#[allow(non_upper_case_globals)]
+mod bitflags_long_enum {
+ flatbuffers::bitflags::bitflags! {
+ #[derive(Default)]
+ pub struct LongEnum: u64 {
+ const LongOne = 2;
+ const LongTwo = 4;
+ const LongBig = 1099511627776;
+ }
+ }
+}
+pub use self::bitflags_long_enum::LongEnum;
+
+impl Serialize for LongEnum {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: Serializer,
+ {
+ serializer.serialize_u32(self.bits() as u32)
+ }
+}
+
+impl<'a> flatbuffers::Follow<'a> for LongEnum {
+ type Inner = Self;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ let b = unsafe {
+ flatbuffers::read_scalar_at::<u64>(buf, loc)
+ };
+ unsafe { Self::from_bits_unchecked(b) }
+ }
+}
+
+impl flatbuffers::Push for LongEnum {
+ type Output = LongEnum;
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ unsafe { flatbuffers::emplace_scalar::<u64>(dst, self.bits()); }
+ }
+}
+
+impl flatbuffers::EndianScalar for LongEnum {
+ #[inline]
+ fn to_little_endian(self) -> Self {
+ let b = u64::to_le(self.bits());
+ unsafe { Self::from_bits_unchecked(b) }
+ }
+ #[inline]
+ #[allow(clippy::wrong_self_convention)]
+ fn from_little_endian(self) -> Self {
+ let b = u64::from_le(self.bits());
+ unsafe { Self::from_bits_unchecked(b) }
+ }
+}
+
+impl<'a> flatbuffers::Verifiable for LongEnum {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ u64::run_verifier(v, pos)
+ }
+}
+
+impl flatbuffers::SimpleToVerifyInSlice for LongEnum {}
diff --git a/tests/monster_test_serialize/my_game/example/monster_generated.rs b/tests/monster_test_serialize/my_game/example/monster_generated.rs
new file mode 100644
index 0000000..cd5730f
--- /dev/null
+++ b/tests/monster_test_serialize/my_game/example/monster_generated.rs
@@ -0,0 +1,1847 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+extern crate serde;
+use self::serde::ser::{Serialize, Serializer, SerializeStruct};
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+pub enum MonsterOffset {}
+#[derive(Copy, Clone, PartialEq)]
+
+/// an example documentation comment: "monster object"
+pub struct Monster<'a> {
+ pub _tab: flatbuffers::Table<'a>,
+}
+
+impl<'a> flatbuffers::Follow<'a> for Monster<'a> {
+ type Inner = Monster<'a>;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ Self { _tab: flatbuffers::Table { buf, loc } }
+ }
+}
+
+impl<'a> Monster<'a> {
+ pub const VT_POS: flatbuffers::VOffsetT = 4;
+ pub const VT_MANA: flatbuffers::VOffsetT = 6;
+ pub const VT_HP: flatbuffers::VOffsetT = 8;
+ pub const VT_NAME: flatbuffers::VOffsetT = 10;
+ pub const VT_INVENTORY: flatbuffers::VOffsetT = 14;
+ pub const VT_COLOR: flatbuffers::VOffsetT = 16;
+ pub const VT_TEST_TYPE: flatbuffers::VOffsetT = 18;
+ pub const VT_TEST: flatbuffers::VOffsetT = 20;
+ pub const VT_TEST4: flatbuffers::VOffsetT = 22;
+ pub const VT_TESTARRAYOFSTRING: flatbuffers::VOffsetT = 24;
+ pub const VT_TESTARRAYOFTABLES: flatbuffers::VOffsetT = 26;
+ pub const VT_ENEMY: flatbuffers::VOffsetT = 28;
+ pub const VT_TESTNESTEDFLATBUFFER: flatbuffers::VOffsetT = 30;
+ pub const VT_TESTEMPTY: flatbuffers::VOffsetT = 32;
+ pub const VT_TESTBOOL: flatbuffers::VOffsetT = 34;
+ pub const VT_TESTHASHS32_FNV1: flatbuffers::VOffsetT = 36;
+ pub const VT_TESTHASHU32_FNV1: flatbuffers::VOffsetT = 38;
+ pub const VT_TESTHASHS64_FNV1: flatbuffers::VOffsetT = 40;
+ pub const VT_TESTHASHU64_FNV1: flatbuffers::VOffsetT = 42;
+ pub const VT_TESTHASHS32_FNV1A: flatbuffers::VOffsetT = 44;
+ pub const VT_TESTHASHU32_FNV1A: flatbuffers::VOffsetT = 46;
+ pub const VT_TESTHASHS64_FNV1A: flatbuffers::VOffsetT = 48;
+ pub const VT_TESTHASHU64_FNV1A: flatbuffers::VOffsetT = 50;
+ pub const VT_TESTARRAYOFBOOLS: flatbuffers::VOffsetT = 52;
+ pub const VT_TESTF: flatbuffers::VOffsetT = 54;
+ pub const VT_TESTF2: flatbuffers::VOffsetT = 56;
+ pub const VT_TESTF3: flatbuffers::VOffsetT = 58;
+ pub const VT_TESTARRAYOFSTRING2: flatbuffers::VOffsetT = 60;
+ pub const VT_TESTARRAYOFSORTEDSTRUCT: flatbuffers::VOffsetT = 62;
+ pub const VT_FLEX: flatbuffers::VOffsetT = 64;
+ pub const VT_TEST5: flatbuffers::VOffsetT = 66;
+ pub const VT_VECTOR_OF_LONGS: flatbuffers::VOffsetT = 68;
+ pub const VT_VECTOR_OF_DOUBLES: flatbuffers::VOffsetT = 70;
+ pub const VT_PARENT_NAMESPACE_TEST: flatbuffers::VOffsetT = 72;
+ pub const VT_VECTOR_OF_REFERRABLES: flatbuffers::VOffsetT = 74;
+ pub const VT_SINGLE_WEAK_REFERENCE: flatbuffers::VOffsetT = 76;
+ pub const VT_VECTOR_OF_WEAK_REFERENCES: flatbuffers::VOffsetT = 78;
+ pub const VT_VECTOR_OF_STRONG_REFERRABLES: flatbuffers::VOffsetT = 80;
+ pub const VT_CO_OWNING_REFERENCE: flatbuffers::VOffsetT = 82;
+ pub const VT_VECTOR_OF_CO_OWNING_REFERENCES: flatbuffers::VOffsetT = 84;
+ pub const VT_NON_OWNING_REFERENCE: flatbuffers::VOffsetT = 86;
+ pub const VT_VECTOR_OF_NON_OWNING_REFERENCES: flatbuffers::VOffsetT = 88;
+ pub const VT_ANY_UNIQUE_TYPE: flatbuffers::VOffsetT = 90;
+ pub const VT_ANY_UNIQUE: flatbuffers::VOffsetT = 92;
+ pub const VT_ANY_AMBIGUOUS_TYPE: flatbuffers::VOffsetT = 94;
+ pub const VT_ANY_AMBIGUOUS: flatbuffers::VOffsetT = 96;
+ pub const VT_VECTOR_OF_ENUMS: flatbuffers::VOffsetT = 98;
+ pub const VT_SIGNED_ENUM: flatbuffers::VOffsetT = 100;
+ pub const VT_TESTREQUIREDNESTEDFLATBUFFER: flatbuffers::VOffsetT = 102;
+ pub const VT_SCALAR_KEY_SORTED_TABLES: flatbuffers::VOffsetT = 104;
+ pub const VT_NATIVE_INLINE: flatbuffers::VOffsetT = 106;
+ pub const VT_LONG_ENUM_NON_ENUM_DEFAULT: flatbuffers::VOffsetT = 108;
+ pub const VT_LONG_ENUM_NORMAL_DEFAULT: flatbuffers::VOffsetT = 110;
+
+ pub const fn get_fully_qualified_name() -> &'static str {
+ "MyGame.Example.Monster"
+ }
+
+ #[inline]
+ pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
+ Monster { _tab: table }
+ }
+ #[allow(unused_mut)]
+ pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
+ _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
+ args: &'args MonsterArgs<'args>
+ ) -> flatbuffers::WIPOffset<Monster<'bldr>> {
+ let mut builder = MonsterBuilder::new(_fbb);
+ builder.add_long_enum_normal_default(args.long_enum_normal_default);
+ builder.add_long_enum_non_enum_default(args.long_enum_non_enum_default);
+ builder.add_non_owning_reference(args.non_owning_reference);
+ builder.add_co_owning_reference(args.co_owning_reference);
+ builder.add_single_weak_reference(args.single_weak_reference);
+ builder.add_testhashu64_fnv1a(args.testhashu64_fnv1a);
+ builder.add_testhashs64_fnv1a(args.testhashs64_fnv1a);
+ builder.add_testhashu64_fnv1(args.testhashu64_fnv1);
+ builder.add_testhashs64_fnv1(args.testhashs64_fnv1);
+ if let Some(x) = args.native_inline { builder.add_native_inline(x); }
+ if let Some(x) = args.scalar_key_sorted_tables { builder.add_scalar_key_sorted_tables(x); }
+ if let Some(x) = args.testrequirednestedflatbuffer { builder.add_testrequirednestedflatbuffer(x); }
+ if let Some(x) = args.vector_of_enums { builder.add_vector_of_enums(x); }
+ if let Some(x) = args.any_ambiguous { builder.add_any_ambiguous(x); }
+ if let Some(x) = args.any_unique { builder.add_any_unique(x); }
+ if let Some(x) = args.vector_of_non_owning_references { builder.add_vector_of_non_owning_references(x); }
+ if let Some(x) = args.vector_of_co_owning_references { builder.add_vector_of_co_owning_references(x); }
+ if let Some(x) = args.vector_of_strong_referrables { builder.add_vector_of_strong_referrables(x); }
+ if let Some(x) = args.vector_of_weak_references { builder.add_vector_of_weak_references(x); }
+ if let Some(x) = args.vector_of_referrables { builder.add_vector_of_referrables(x); }
+ if let Some(x) = args.parent_namespace_test { builder.add_parent_namespace_test(x); }
+ if let Some(x) = args.vector_of_doubles { builder.add_vector_of_doubles(x); }
+ if let Some(x) = args.vector_of_longs { builder.add_vector_of_longs(x); }
+ if let Some(x) = args.test5 { builder.add_test5(x); }
+ if let Some(x) = args.flex { builder.add_flex(x); }
+ if let Some(x) = args.testarrayofsortedstruct { builder.add_testarrayofsortedstruct(x); }
+ if let Some(x) = args.testarrayofstring2 { builder.add_testarrayofstring2(x); }
+ builder.add_testf3(args.testf3);
+ builder.add_testf2(args.testf2);
+ builder.add_testf(args.testf);
+ if let Some(x) = args.testarrayofbools { builder.add_testarrayofbools(x); }
+ builder.add_testhashu32_fnv1a(args.testhashu32_fnv1a);
+ builder.add_testhashs32_fnv1a(args.testhashs32_fnv1a);
+ builder.add_testhashu32_fnv1(args.testhashu32_fnv1);
+ builder.add_testhashs32_fnv1(args.testhashs32_fnv1);
+ if let Some(x) = args.testempty { builder.add_testempty(x); }
+ if let Some(x) = args.testnestedflatbuffer { builder.add_testnestedflatbuffer(x); }
+ if let Some(x) = args.enemy { builder.add_enemy(x); }
+ if let Some(x) = args.testarrayoftables { builder.add_testarrayoftables(x); }
+ if let Some(x) = args.testarrayofstring { builder.add_testarrayofstring(x); }
+ if let Some(x) = args.test4 { builder.add_test4(x); }
+ if let Some(x) = args.test { builder.add_test(x); }
+ if let Some(x) = args.inventory { builder.add_inventory(x); }
+ if let Some(x) = args.name { builder.add_name(x); }
+ if let Some(x) = args.pos { builder.add_pos(x); }
+ builder.add_hp(args.hp);
+ builder.add_mana(args.mana);
+ builder.add_signed_enum(args.signed_enum);
+ builder.add_any_ambiguous_type(args.any_ambiguous_type);
+ builder.add_any_unique_type(args.any_unique_type);
+ builder.add_testbool(args.testbool);
+ builder.add_test_type(args.test_type);
+ builder.add_color(args.color);
+ builder.finish()
+ }
+
+ pub fn unpack(&self) -> MonsterT {
+ let pos = self.pos().map(|x| {
+ x.unpack()
+ });
+ let mana = self.mana();
+ let hp = self.hp();
+ let name = {
+ let x = self.name();
+ x.to_string()
+ };
+ let inventory = self.inventory().map(|x| {
+ x.to_vec()
+ });
+ let color = self.color();
+ let test = match self.test_type() {
+ Any::NONE => AnyT::NONE,
+ Any::Monster => AnyT::Monster(Box::new(
+ self.test_as_monster()
+ .expect("Invalid union table, expected `Any::Monster`.")
+ .unpack()
+ )),
+ Any::TestSimpleTableWithEnum => AnyT::TestSimpleTableWithEnum(Box::new(
+ self.test_as_test_simple_table_with_enum()
+ .expect("Invalid union table, expected `Any::TestSimpleTableWithEnum`.")
+ .unpack()
+ )),
+ Any::MyGame_Example2_Monster => AnyT::MyGameExample2Monster(Box::new(
+ self.test_as_my_game_example_2_monster()
+ .expect("Invalid union table, expected `Any::MyGame_Example2_Monster`.")
+ .unpack()
+ )),
+ _ => AnyT::NONE,
+ };
+ let test4 = self.test4().map(|x| {
+ x.iter().map(|t| t.unpack()).collect()
+ });
+ let testarrayofstring = self.testarrayofstring().map(|x| {
+ x.iter().map(|s| s.to_string()).collect()
+ });
+ let testarrayoftables = self.testarrayoftables().map(|x| {
+ x.iter().map(|t| t.unpack()).collect()
+ });
+ let enemy = self.enemy().map(|x| {
+ Box::new(x.unpack())
+ });
+ let testnestedflatbuffer = self.testnestedflatbuffer().map(|x| {
+ x.to_vec()
+ });
+ let testempty = self.testempty().map(|x| {
+ Box::new(x.unpack())
+ });
+ let testbool = self.testbool();
+ let testhashs32_fnv1 = self.testhashs32_fnv1();
+ let testhashu32_fnv1 = self.testhashu32_fnv1();
+ let testhashs64_fnv1 = self.testhashs64_fnv1();
+ let testhashu64_fnv1 = self.testhashu64_fnv1();
+ let testhashs32_fnv1a = self.testhashs32_fnv1a();
+ let testhashu32_fnv1a = self.testhashu32_fnv1a();
+ let testhashs64_fnv1a = self.testhashs64_fnv1a();
+ let testhashu64_fnv1a = self.testhashu64_fnv1a();
+ let testarrayofbools = self.testarrayofbools().map(|x| {
+ x.to_vec()
+ });
+ let testf = self.testf();
+ let testf2 = self.testf2();
+ let testf3 = self.testf3();
+ let testarrayofstring2 = self.testarrayofstring2().map(|x| {
+ x.iter().map(|s| s.to_string()).collect()
+ });
+ let testarrayofsortedstruct = self.testarrayofsortedstruct().map(|x| {
+ x.iter().map(|t| t.unpack()).collect()
+ });
+ let flex = self.flex().map(|x| {
+ x.to_vec()
+ });
+ let test5 = self.test5().map(|x| {
+ x.iter().map(|t| t.unpack()).collect()
+ });
+ let vector_of_longs = self.vector_of_longs().map(|x| {
+ x.into_iter().collect()
+ });
+ let vector_of_doubles = self.vector_of_doubles().map(|x| {
+ x.into_iter().collect()
+ });
+ let parent_namespace_test = self.parent_namespace_test().map(|x| {
+ Box::new(x.unpack())
+ });
+ let vector_of_referrables = self.vector_of_referrables().map(|x| {
+ x.iter().map(|t| t.unpack()).collect()
+ });
+ let single_weak_reference = self.single_weak_reference();
+ let vector_of_weak_references = self.vector_of_weak_references().map(|x| {
+ x.into_iter().collect()
+ });
+ let vector_of_strong_referrables = self.vector_of_strong_referrables().map(|x| {
+ x.iter().map(|t| t.unpack()).collect()
+ });
+ let co_owning_reference = self.co_owning_reference();
+ let vector_of_co_owning_references = self.vector_of_co_owning_references().map(|x| {
+ x.into_iter().collect()
+ });
+ let non_owning_reference = self.non_owning_reference();
+ let vector_of_non_owning_references = self.vector_of_non_owning_references().map(|x| {
+ x.into_iter().collect()
+ });
+ let any_unique = match self.any_unique_type() {
+ AnyUniqueAliases::NONE => AnyUniqueAliasesT::NONE,
+ AnyUniqueAliases::M => AnyUniqueAliasesT::M(Box::new(
+ self.any_unique_as_m()
+ .expect("Invalid union table, expected `AnyUniqueAliases::M`.")
+ .unpack()
+ )),
+ AnyUniqueAliases::TS => AnyUniqueAliasesT::TS(Box::new(
+ self.any_unique_as_ts()
+ .expect("Invalid union table, expected `AnyUniqueAliases::TS`.")
+ .unpack()
+ )),
+ AnyUniqueAliases::M2 => AnyUniqueAliasesT::M2(Box::new(
+ self.any_unique_as_m2()
+ .expect("Invalid union table, expected `AnyUniqueAliases::M2`.")
+ .unpack()
+ )),
+ _ => AnyUniqueAliasesT::NONE,
+ };
+ let any_ambiguous = match self.any_ambiguous_type() {
+ AnyAmbiguousAliases::NONE => AnyAmbiguousAliasesT::NONE,
+ AnyAmbiguousAliases::M1 => AnyAmbiguousAliasesT::M1(Box::new(
+ self.any_ambiguous_as_m1()
+ .expect("Invalid union table, expected `AnyAmbiguousAliases::M1`.")
+ .unpack()
+ )),
+ AnyAmbiguousAliases::M2 => AnyAmbiguousAliasesT::M2(Box::new(
+ self.any_ambiguous_as_m2()
+ .expect("Invalid union table, expected `AnyAmbiguousAliases::M2`.")
+ .unpack()
+ )),
+ AnyAmbiguousAliases::M3 => AnyAmbiguousAliasesT::M3(Box::new(
+ self.any_ambiguous_as_m3()
+ .expect("Invalid union table, expected `AnyAmbiguousAliases::M3`.")
+ .unpack()
+ )),
+ _ => AnyAmbiguousAliasesT::NONE,
+ };
+ let vector_of_enums = self.vector_of_enums().map(|x| {
+ x.into_iter().collect()
+ });
+ let signed_enum = self.signed_enum();
+ let testrequirednestedflatbuffer = self.testrequirednestedflatbuffer().map(|x| {
+ x.to_vec()
+ });
+ let scalar_key_sorted_tables = self.scalar_key_sorted_tables().map(|x| {
+ x.iter().map(|t| t.unpack()).collect()
+ });
+ let native_inline = self.native_inline().map(|x| {
+ x.unpack()
+ });
+ let long_enum_non_enum_default = self.long_enum_non_enum_default();
+ let long_enum_normal_default = self.long_enum_normal_default();
+ MonsterT {
+ pos,
+ mana,
+ hp,
+ name,
+ inventory,
+ color,
+ test,
+ test4,
+ testarrayofstring,
+ testarrayoftables,
+ enemy,
+ testnestedflatbuffer,
+ testempty,
+ testbool,
+ testhashs32_fnv1,
+ testhashu32_fnv1,
+ testhashs64_fnv1,
+ testhashu64_fnv1,
+ testhashs32_fnv1a,
+ testhashu32_fnv1a,
+ testhashs64_fnv1a,
+ testhashu64_fnv1a,
+ testarrayofbools,
+ testf,
+ testf2,
+ testf3,
+ testarrayofstring2,
+ testarrayofsortedstruct,
+ flex,
+ test5,
+ vector_of_longs,
+ vector_of_doubles,
+ parent_namespace_test,
+ vector_of_referrables,
+ single_weak_reference,
+ vector_of_weak_references,
+ vector_of_strong_referrables,
+ co_owning_reference,
+ vector_of_co_owning_references,
+ non_owning_reference,
+ vector_of_non_owning_references,
+ any_unique,
+ any_ambiguous,
+ vector_of_enums,
+ signed_enum,
+ testrequirednestedflatbuffer,
+ scalar_key_sorted_tables,
+ native_inline,
+ long_enum_non_enum_default,
+ long_enum_normal_default,
+ }
+ }
+
+ #[inline]
+ pub fn pos(&self) -> Option<&'a Vec3> {
+ self._tab.get::<Vec3>(Monster::VT_POS, None)
+ }
+ #[inline]
+ pub fn mana(&self) -> i16 {
+ self._tab.get::<i16>(Monster::VT_MANA, Some(150)).unwrap()
+ }
+ #[inline]
+ pub fn hp(&self) -> i16 {
+ self._tab.get::<i16>(Monster::VT_HP, Some(100)).unwrap()
+ }
+ #[inline]
+ pub fn name(&self) -> &'a str {
+ self._tab.get::<flatbuffers::ForwardsUOffset<&str>>(Monster::VT_NAME, None).unwrap()
+ }
+ #[inline]
+ pub fn key_compare_less_than(&self, o: &Monster) -> bool {
+ self.name() < o.name()
+ }
+
+ #[inline]
+ pub fn key_compare_with_value(&self, val: & str) -> ::std::cmp::Ordering {
+ let key = self.name();
+ key.cmp(val)
+ }
+ #[inline]
+ pub fn inventory(&self) -> Option<&'a [u8]> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, u8>>>(Monster::VT_INVENTORY, None).map(|v| v.safe_slice())
+ }
+ #[inline]
+ pub fn color(&self) -> Color {
+ self._tab.get::<Color>(Monster::VT_COLOR, Some(Color::Blue)).unwrap()
+ }
+ #[inline]
+ pub fn test_type(&self) -> Any {
+ self._tab.get::<Any>(Monster::VT_TEST_TYPE, Some(Any::NONE)).unwrap()
+ }
+ #[inline]
+ pub fn test(&self) -> Option<flatbuffers::Table<'a>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Table<'a>>>(Monster::VT_TEST, None)
+ }
+ #[inline]
+ pub fn test4(&self) -> Option<&'a [Test]> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, Test>>>(Monster::VT_TEST4, None).map(|v| v.safe_slice())
+ }
+ #[inline]
+ pub fn testarrayofstring(&self) -> Option<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<&'a str>>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<&'a str>>>>(Monster::VT_TESTARRAYOFSTRING, None)
+ }
+ /// an example documentation comment: this will end up in the generated code
+ /// multiline too
+ #[inline]
+ pub fn testarrayoftables(&self) -> Option<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Monster<'a>>>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Monster>>>>(Monster::VT_TESTARRAYOFTABLES, None)
+ }
+ #[inline]
+ pub fn enemy(&self) -> Option<Monster<'a>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<Monster>>(Monster::VT_ENEMY, None)
+ }
+ #[inline]
+ pub fn testnestedflatbuffer(&self) -> Option<&'a [u8]> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, u8>>>(Monster::VT_TESTNESTEDFLATBUFFER, None).map(|v| v.safe_slice())
+ }
+ pub fn testnestedflatbuffer_nested_flatbuffer(&'a self) -> Option<Monster<'a>> {
+ self.testnestedflatbuffer().map(|data| {
+ use flatbuffers::Follow;
+ <flatbuffers::ForwardsUOffset<Monster<'a>>>::follow(data, 0)
+ })
+ }
+ #[inline]
+ pub fn testempty(&self) -> Option<Stat<'a>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<Stat>>(Monster::VT_TESTEMPTY, None)
+ }
+ #[inline]
+ pub fn testbool(&self) -> bool {
+ self._tab.get::<bool>(Monster::VT_TESTBOOL, Some(false)).unwrap()
+ }
+ #[inline]
+ pub fn testhashs32_fnv1(&self) -> i32 {
+ self._tab.get::<i32>(Monster::VT_TESTHASHS32_FNV1, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn testhashu32_fnv1(&self) -> u32 {
+ self._tab.get::<u32>(Monster::VT_TESTHASHU32_FNV1, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn testhashs64_fnv1(&self) -> i64 {
+ self._tab.get::<i64>(Monster::VT_TESTHASHS64_FNV1, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn testhashu64_fnv1(&self) -> u64 {
+ self._tab.get::<u64>(Monster::VT_TESTHASHU64_FNV1, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn testhashs32_fnv1a(&self) -> i32 {
+ self._tab.get::<i32>(Monster::VT_TESTHASHS32_FNV1A, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn testhashu32_fnv1a(&self) -> u32 {
+ self._tab.get::<u32>(Monster::VT_TESTHASHU32_FNV1A, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn testhashs64_fnv1a(&self) -> i64 {
+ self._tab.get::<i64>(Monster::VT_TESTHASHS64_FNV1A, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn testhashu64_fnv1a(&self) -> u64 {
+ self._tab.get::<u64>(Monster::VT_TESTHASHU64_FNV1A, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn testarrayofbools(&self) -> Option<&'a [bool]> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, bool>>>(Monster::VT_TESTARRAYOFBOOLS, None).map(|v| v.safe_slice())
+ }
+ #[inline]
+ pub fn testf(&self) -> f32 {
+ self._tab.get::<f32>(Monster::VT_TESTF, Some(3.14159)).unwrap()
+ }
+ #[inline]
+ pub fn testf2(&self) -> f32 {
+ self._tab.get::<f32>(Monster::VT_TESTF2, Some(3.0)).unwrap()
+ }
+ #[inline]
+ pub fn testf3(&self) -> f32 {
+ self._tab.get::<f32>(Monster::VT_TESTF3, Some(0.0)).unwrap()
+ }
+ #[inline]
+ pub fn testarrayofstring2(&self) -> Option<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<&'a str>>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<&'a str>>>>(Monster::VT_TESTARRAYOFSTRING2, None)
+ }
+ #[inline]
+ pub fn testarrayofsortedstruct(&self) -> Option<&'a [Ability]> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, Ability>>>(Monster::VT_TESTARRAYOFSORTEDSTRUCT, None).map(|v| v.safe_slice())
+ }
+ #[inline]
+ pub fn flex(&self) -> Option<&'a [u8]> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, u8>>>(Monster::VT_FLEX, None).map(|v| v.safe_slice())
+ }
+ #[inline]
+ pub fn test5(&self) -> Option<&'a [Test]> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, Test>>>(Monster::VT_TEST5, None).map(|v| v.safe_slice())
+ }
+ #[inline]
+ pub fn vector_of_longs(&self) -> Option<flatbuffers::Vector<'a, i64>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, i64>>>(Monster::VT_VECTOR_OF_LONGS, None)
+ }
+ #[inline]
+ pub fn vector_of_doubles(&self) -> Option<flatbuffers::Vector<'a, f64>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, f64>>>(Monster::VT_VECTOR_OF_DOUBLES, None)
+ }
+ #[inline]
+ pub fn parent_namespace_test(&self) -> Option<super::InParentNamespace<'a>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<super::InParentNamespace>>(Monster::VT_PARENT_NAMESPACE_TEST, None)
+ }
+ #[inline]
+ pub fn vector_of_referrables(&self) -> Option<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Referrable<'a>>>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Referrable>>>>(Monster::VT_VECTOR_OF_REFERRABLES, None)
+ }
+ #[inline]
+ pub fn single_weak_reference(&self) -> u64 {
+ self._tab.get::<u64>(Monster::VT_SINGLE_WEAK_REFERENCE, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn vector_of_weak_references(&self) -> Option<flatbuffers::Vector<'a, u64>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, u64>>>(Monster::VT_VECTOR_OF_WEAK_REFERENCES, None)
+ }
+ #[inline]
+ pub fn vector_of_strong_referrables(&self) -> Option<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Referrable<'a>>>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Referrable>>>>(Monster::VT_VECTOR_OF_STRONG_REFERRABLES, None)
+ }
+ #[inline]
+ pub fn co_owning_reference(&self) -> u64 {
+ self._tab.get::<u64>(Monster::VT_CO_OWNING_REFERENCE, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn vector_of_co_owning_references(&self) -> Option<flatbuffers::Vector<'a, u64>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, u64>>>(Monster::VT_VECTOR_OF_CO_OWNING_REFERENCES, None)
+ }
+ #[inline]
+ pub fn non_owning_reference(&self) -> u64 {
+ self._tab.get::<u64>(Monster::VT_NON_OWNING_REFERENCE, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn vector_of_non_owning_references(&self) -> Option<flatbuffers::Vector<'a, u64>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, u64>>>(Monster::VT_VECTOR_OF_NON_OWNING_REFERENCES, None)
+ }
+ #[inline]
+ pub fn any_unique_type(&self) -> AnyUniqueAliases {
+ self._tab.get::<AnyUniqueAliases>(Monster::VT_ANY_UNIQUE_TYPE, Some(AnyUniqueAliases::NONE)).unwrap()
+ }
+ #[inline]
+ pub fn any_unique(&self) -> Option<flatbuffers::Table<'a>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Table<'a>>>(Monster::VT_ANY_UNIQUE, None)
+ }
+ #[inline]
+ pub fn any_ambiguous_type(&self) -> AnyAmbiguousAliases {
+ self._tab.get::<AnyAmbiguousAliases>(Monster::VT_ANY_AMBIGUOUS_TYPE, Some(AnyAmbiguousAliases::NONE)).unwrap()
+ }
+ #[inline]
+ pub fn any_ambiguous(&self) -> Option<flatbuffers::Table<'a>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Table<'a>>>(Monster::VT_ANY_AMBIGUOUS, None)
+ }
+ #[inline]
+ pub fn vector_of_enums(&self) -> Option<flatbuffers::Vector<'a, Color>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, Color>>>(Monster::VT_VECTOR_OF_ENUMS, None)
+ }
+ #[inline]
+ pub fn signed_enum(&self) -> Race {
+ self._tab.get::<Race>(Monster::VT_SIGNED_ENUM, Some(Race::None)).unwrap()
+ }
+ #[inline]
+ pub fn testrequirednestedflatbuffer(&self) -> Option<&'a [u8]> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, u8>>>(Monster::VT_TESTREQUIREDNESTEDFLATBUFFER, None).map(|v| v.safe_slice())
+ }
+ pub fn testrequirednestedflatbuffer_nested_flatbuffer(&'a self) -> Option<Monster<'a>> {
+ self.testrequirednestedflatbuffer().map(|data| {
+ use flatbuffers::Follow;
+ <flatbuffers::ForwardsUOffset<Monster<'a>>>::follow(data, 0)
+ })
+ }
+ #[inline]
+ pub fn scalar_key_sorted_tables(&self) -> Option<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Stat<'a>>>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Stat>>>>(Monster::VT_SCALAR_KEY_SORTED_TABLES, None)
+ }
+ #[inline]
+ pub fn native_inline(&self) -> Option<&'a Test> {
+ self._tab.get::<Test>(Monster::VT_NATIVE_INLINE, None)
+ }
+ #[inline]
+ pub fn long_enum_non_enum_default(&self) -> LongEnum {
+ self._tab.get::<LongEnum>(Monster::VT_LONG_ENUM_NON_ENUM_DEFAULT, Some(Default::default())).unwrap()
+ }
+ #[inline]
+ pub fn long_enum_normal_default(&self) -> LongEnum {
+ self._tab.get::<LongEnum>(Monster::VT_LONG_ENUM_NORMAL_DEFAULT, Some(LongEnum::LongOne)).unwrap()
+ }
+ #[inline]
+ #[allow(non_snake_case)]
+ pub fn test_as_monster(&self) -> Option<Monster<'a>> {
+ if self.test_type() == Any::Monster {
+ self.test().map(Monster::init_from_table)
+ } else {
+ None
+ }
+ }
+
+ #[inline]
+ #[allow(non_snake_case)]
+ pub fn test_as_test_simple_table_with_enum(&self) -> Option<TestSimpleTableWithEnum<'a>> {
+ if self.test_type() == Any::TestSimpleTableWithEnum {
+ self.test().map(TestSimpleTableWithEnum::init_from_table)
+ } else {
+ None
+ }
+ }
+
+ #[inline]
+ #[allow(non_snake_case)]
+ pub fn test_as_my_game_example_2_monster(&self) -> Option<super::example_2::Monster<'a>> {
+ if self.test_type() == Any::MyGame_Example2_Monster {
+ self.test().map(super::example_2::Monster::init_from_table)
+ } else {
+ None
+ }
+ }
+
+ #[inline]
+ #[allow(non_snake_case)]
+ pub fn any_unique_as_m(&self) -> Option<Monster<'a>> {
+ if self.any_unique_type() == AnyUniqueAliases::M {
+ self.any_unique().map(Monster::init_from_table)
+ } else {
+ None
+ }
+ }
+
+ #[inline]
+ #[allow(non_snake_case)]
+ pub fn any_unique_as_ts(&self) -> Option<TestSimpleTableWithEnum<'a>> {
+ if self.any_unique_type() == AnyUniqueAliases::TS {
+ self.any_unique().map(TestSimpleTableWithEnum::init_from_table)
+ } else {
+ None
+ }
+ }
+
+ #[inline]
+ #[allow(non_snake_case)]
+ pub fn any_unique_as_m2(&self) -> Option<super::example_2::Monster<'a>> {
+ if self.any_unique_type() == AnyUniqueAliases::M2 {
+ self.any_unique().map(super::example_2::Monster::init_from_table)
+ } else {
+ None
+ }
+ }
+
+ #[inline]
+ #[allow(non_snake_case)]
+ pub fn any_ambiguous_as_m1(&self) -> Option<Monster<'a>> {
+ if self.any_ambiguous_type() == AnyAmbiguousAliases::M1 {
+ self.any_ambiguous().map(Monster::init_from_table)
+ } else {
+ None
+ }
+ }
+
+ #[inline]
+ #[allow(non_snake_case)]
+ pub fn any_ambiguous_as_m2(&self) -> Option<Monster<'a>> {
+ if self.any_ambiguous_type() == AnyAmbiguousAliases::M2 {
+ self.any_ambiguous().map(Monster::init_from_table)
+ } else {
+ None
+ }
+ }
+
+ #[inline]
+ #[allow(non_snake_case)]
+ pub fn any_ambiguous_as_m3(&self) -> Option<Monster<'a>> {
+ if self.any_ambiguous_type() == AnyAmbiguousAliases::M3 {
+ self.any_ambiguous().map(Monster::init_from_table)
+ } else {
+ None
+ }
+ }
+
+}
+
+impl flatbuffers::Verifiable for Monster<'_> {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ v.visit_table(pos)?
+ .visit_field::<Vec3>("pos", Self::VT_POS, false)?
+ .visit_field::<i16>("mana", Self::VT_MANA, false)?
+ .visit_field::<i16>("hp", Self::VT_HP, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<&str>>("name", Self::VT_NAME, true)?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, u8>>>("inventory", Self::VT_INVENTORY, false)?
+ .visit_field::<Color>("color", Self::VT_COLOR, false)?
+ .visit_union::<Any, _>("test_type", Self::VT_TEST_TYPE, "test", Self::VT_TEST, false, |key, v, pos| {
+ match key {
+ Any::Monster => v.verify_union_variant::<flatbuffers::ForwardsUOffset<Monster>>("Any::Monster", pos),
+ Any::TestSimpleTableWithEnum => v.verify_union_variant::<flatbuffers::ForwardsUOffset<TestSimpleTableWithEnum>>("Any::TestSimpleTableWithEnum", pos),
+ Any::MyGame_Example2_Monster => v.verify_union_variant::<flatbuffers::ForwardsUOffset<super::example_2::Monster>>("Any::MyGame_Example2_Monster", pos),
+ _ => Ok(()),
+ }
+ })?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, Test>>>("test4", Self::VT_TEST4, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, flatbuffers::ForwardsUOffset<&'_ str>>>>("testarrayofstring", Self::VT_TESTARRAYOFSTRING, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, flatbuffers::ForwardsUOffset<Monster>>>>("testarrayoftables", Self::VT_TESTARRAYOFTABLES, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<Monster>>("enemy", Self::VT_ENEMY, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, u8>>>("testnestedflatbuffer", Self::VT_TESTNESTEDFLATBUFFER, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<Stat>>("testempty", Self::VT_TESTEMPTY, false)?
+ .visit_field::<bool>("testbool", Self::VT_TESTBOOL, false)?
+ .visit_field::<i32>("testhashs32_fnv1", Self::VT_TESTHASHS32_FNV1, false)?
+ .visit_field::<u32>("testhashu32_fnv1", Self::VT_TESTHASHU32_FNV1, false)?
+ .visit_field::<i64>("testhashs64_fnv1", Self::VT_TESTHASHS64_FNV1, false)?
+ .visit_field::<u64>("testhashu64_fnv1", Self::VT_TESTHASHU64_FNV1, false)?
+ .visit_field::<i32>("testhashs32_fnv1a", Self::VT_TESTHASHS32_FNV1A, false)?
+ .visit_field::<u32>("testhashu32_fnv1a", Self::VT_TESTHASHU32_FNV1A, false)?
+ .visit_field::<i64>("testhashs64_fnv1a", Self::VT_TESTHASHS64_FNV1A, false)?
+ .visit_field::<u64>("testhashu64_fnv1a", Self::VT_TESTHASHU64_FNV1A, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, bool>>>("testarrayofbools", Self::VT_TESTARRAYOFBOOLS, false)?
+ .visit_field::<f32>("testf", Self::VT_TESTF, false)?
+ .visit_field::<f32>("testf2", Self::VT_TESTF2, false)?
+ .visit_field::<f32>("testf3", Self::VT_TESTF3, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, flatbuffers::ForwardsUOffset<&'_ str>>>>("testarrayofstring2", Self::VT_TESTARRAYOFSTRING2, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, Ability>>>("testarrayofsortedstruct", Self::VT_TESTARRAYOFSORTEDSTRUCT, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, u8>>>("flex", Self::VT_FLEX, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, Test>>>("test5", Self::VT_TEST5, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, i64>>>("vector_of_longs", Self::VT_VECTOR_OF_LONGS, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, f64>>>("vector_of_doubles", Self::VT_VECTOR_OF_DOUBLES, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<super::InParentNamespace>>("parent_namespace_test", Self::VT_PARENT_NAMESPACE_TEST, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, flatbuffers::ForwardsUOffset<Referrable>>>>("vector_of_referrables", Self::VT_VECTOR_OF_REFERRABLES, false)?
+ .visit_field::<u64>("single_weak_reference", Self::VT_SINGLE_WEAK_REFERENCE, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, u64>>>("vector_of_weak_references", Self::VT_VECTOR_OF_WEAK_REFERENCES, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, flatbuffers::ForwardsUOffset<Referrable>>>>("vector_of_strong_referrables", Self::VT_VECTOR_OF_STRONG_REFERRABLES, false)?
+ .visit_field::<u64>("co_owning_reference", Self::VT_CO_OWNING_REFERENCE, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, u64>>>("vector_of_co_owning_references", Self::VT_VECTOR_OF_CO_OWNING_REFERENCES, false)?
+ .visit_field::<u64>("non_owning_reference", Self::VT_NON_OWNING_REFERENCE, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, u64>>>("vector_of_non_owning_references", Self::VT_VECTOR_OF_NON_OWNING_REFERENCES, false)?
+ .visit_union::<AnyUniqueAliases, _>("any_unique_type", Self::VT_ANY_UNIQUE_TYPE, "any_unique", Self::VT_ANY_UNIQUE, false, |key, v, pos| {
+ match key {
+ AnyUniqueAliases::M => v.verify_union_variant::<flatbuffers::ForwardsUOffset<Monster>>("AnyUniqueAliases::M", pos),
+ AnyUniqueAliases::TS => v.verify_union_variant::<flatbuffers::ForwardsUOffset<TestSimpleTableWithEnum>>("AnyUniqueAliases::TS", pos),
+ AnyUniqueAliases::M2 => v.verify_union_variant::<flatbuffers::ForwardsUOffset<super::example_2::Monster>>("AnyUniqueAliases::M2", pos),
+ _ => Ok(()),
+ }
+ })?
+ .visit_union::<AnyAmbiguousAliases, _>("any_ambiguous_type", Self::VT_ANY_AMBIGUOUS_TYPE, "any_ambiguous", Self::VT_ANY_AMBIGUOUS, false, |key, v, pos| {
+ match key {
+ AnyAmbiguousAliases::M1 => v.verify_union_variant::<flatbuffers::ForwardsUOffset<Monster>>("AnyAmbiguousAliases::M1", pos),
+ AnyAmbiguousAliases::M2 => v.verify_union_variant::<flatbuffers::ForwardsUOffset<Monster>>("AnyAmbiguousAliases::M2", pos),
+ AnyAmbiguousAliases::M3 => v.verify_union_variant::<flatbuffers::ForwardsUOffset<Monster>>("AnyAmbiguousAliases::M3", pos),
+ _ => Ok(()),
+ }
+ })?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, Color>>>("vector_of_enums", Self::VT_VECTOR_OF_ENUMS, false)?
+ .visit_field::<Race>("signed_enum", Self::VT_SIGNED_ENUM, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, u8>>>("testrequirednestedflatbuffer", Self::VT_TESTREQUIREDNESTEDFLATBUFFER, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, flatbuffers::ForwardsUOffset<Stat>>>>("scalar_key_sorted_tables", Self::VT_SCALAR_KEY_SORTED_TABLES, false)?
+ .visit_field::<Test>("native_inline", Self::VT_NATIVE_INLINE, false)?
+ .visit_field::<LongEnum>("long_enum_non_enum_default", Self::VT_LONG_ENUM_NON_ENUM_DEFAULT, false)?
+ .visit_field::<LongEnum>("long_enum_normal_default", Self::VT_LONG_ENUM_NORMAL_DEFAULT, false)?
+ .finish();
+ Ok(())
+ }
+}
+pub struct MonsterArgs<'a> {
+ pub pos: Option<&'a Vec3>,
+ pub mana: i16,
+ pub hp: i16,
+ pub name: Option<flatbuffers::WIPOffset<&'a str>>,
+ pub inventory: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, u8>>>,
+ pub color: Color,
+ pub test_type: Any,
+ pub test: Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>,
+ pub test4: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, Test>>>,
+ pub testarrayofstring: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<&'a str>>>>,
+ pub testarrayoftables: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Monster<'a>>>>>,
+ pub enemy: Option<flatbuffers::WIPOffset<Monster<'a>>>,
+ pub testnestedflatbuffer: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, u8>>>,
+ pub testempty: Option<flatbuffers::WIPOffset<Stat<'a>>>,
+ pub testbool: bool,
+ pub testhashs32_fnv1: i32,
+ pub testhashu32_fnv1: u32,
+ pub testhashs64_fnv1: i64,
+ pub testhashu64_fnv1: u64,
+ pub testhashs32_fnv1a: i32,
+ pub testhashu32_fnv1a: u32,
+ pub testhashs64_fnv1a: i64,
+ pub testhashu64_fnv1a: u64,
+ pub testarrayofbools: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, bool>>>,
+ pub testf: f32,
+ pub testf2: f32,
+ pub testf3: f32,
+ pub testarrayofstring2: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<&'a str>>>>,
+ pub testarrayofsortedstruct: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, Ability>>>,
+ pub flex: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, u8>>>,
+ pub test5: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, Test>>>,
+ pub vector_of_longs: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, i64>>>,
+ pub vector_of_doubles: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, f64>>>,
+ pub parent_namespace_test: Option<flatbuffers::WIPOffset<super::InParentNamespace<'a>>>,
+ pub vector_of_referrables: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Referrable<'a>>>>>,
+ pub single_weak_reference: u64,
+ pub vector_of_weak_references: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, u64>>>,
+ pub vector_of_strong_referrables: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Referrable<'a>>>>>,
+ pub co_owning_reference: u64,
+ pub vector_of_co_owning_references: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, u64>>>,
+ pub non_owning_reference: u64,
+ pub vector_of_non_owning_references: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, u64>>>,
+ pub any_unique_type: AnyUniqueAliases,
+ pub any_unique: Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>,
+ pub any_ambiguous_type: AnyAmbiguousAliases,
+ pub any_ambiguous: Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>,
+ pub vector_of_enums: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, Color>>>,
+ pub signed_enum: Race,
+ pub testrequirednestedflatbuffer: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, u8>>>,
+ pub scalar_key_sorted_tables: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Stat<'a>>>>>,
+ pub native_inline: Option<&'a Test>,
+ pub long_enum_non_enum_default: LongEnum,
+ pub long_enum_normal_default: LongEnum,
+}
+impl<'a> Default for MonsterArgs<'a> {
+ #[inline]
+ fn default() -> Self {
+ MonsterArgs {
+ pos: None,
+ mana: 150,
+ hp: 100,
+ name: None, // required field
+ inventory: None,
+ color: Color::Blue,
+ test_type: Any::NONE,
+ test: None,
+ test4: None,
+ testarrayofstring: None,
+ testarrayoftables: None,
+ enemy: None,
+ testnestedflatbuffer: None,
+ testempty: None,
+ testbool: false,
+ testhashs32_fnv1: 0,
+ testhashu32_fnv1: 0,
+ testhashs64_fnv1: 0,
+ testhashu64_fnv1: 0,
+ testhashs32_fnv1a: 0,
+ testhashu32_fnv1a: 0,
+ testhashs64_fnv1a: 0,
+ testhashu64_fnv1a: 0,
+ testarrayofbools: None,
+ testf: 3.14159,
+ testf2: 3.0,
+ testf3: 0.0,
+ testarrayofstring2: None,
+ testarrayofsortedstruct: None,
+ flex: None,
+ test5: None,
+ vector_of_longs: None,
+ vector_of_doubles: None,
+ parent_namespace_test: None,
+ vector_of_referrables: None,
+ single_weak_reference: 0,
+ vector_of_weak_references: None,
+ vector_of_strong_referrables: None,
+ co_owning_reference: 0,
+ vector_of_co_owning_references: None,
+ non_owning_reference: 0,
+ vector_of_non_owning_references: None,
+ any_unique_type: AnyUniqueAliases::NONE,
+ any_unique: None,
+ any_ambiguous_type: AnyAmbiguousAliases::NONE,
+ any_ambiguous: None,
+ vector_of_enums: None,
+ signed_enum: Race::None,
+ testrequirednestedflatbuffer: None,
+ scalar_key_sorted_tables: None,
+ native_inline: None,
+ long_enum_non_enum_default: Default::default(),
+ long_enum_normal_default: LongEnum::LongOne,
+ }
+ }
+}
+
+impl Serialize for Monster<'_> {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: Serializer,
+ {
+ let mut s = serializer.serialize_struct("Monster", 54)?;
+ if let Some(f) = self.pos() {
+ s.serialize_field("pos", &f)?;
+ } else {
+ s.skip_field("pos")?;
+ }
+ s.serialize_field("mana", &self.mana())?;
+ s.serialize_field("hp", &self.hp())?;
+ s.serialize_field("name", &self.name())?;
+ if let Some(f) = self.inventory() {
+ s.serialize_field("inventory", &f)?;
+ } else {
+ s.skip_field("inventory")?;
+ }
+ s.serialize_field("color", &self.color())?;
+ s.serialize_field("test_type", &self.test_type())?;
+ match self.test_type() {
+ Any::NONE => (),
+ Any::Monster => {
+ let f = self.test_as_monster()
+ .expect("Invalid union table, expected `Any::Monster`.");
+ s.serialize_field("test", &f)?;
+ }
+ Any::TestSimpleTableWithEnum => {
+ let f = self.test_as_test_simple_table_with_enum()
+ .expect("Invalid union table, expected `Any::TestSimpleTableWithEnum`.");
+ s.serialize_field("test", &f)?;
+ }
+ Any::MyGame_Example2_Monster => {
+ let f = self.test_as_my_game_example_2_monster()
+ .expect("Invalid union table, expected `Any::MyGame_Example2_Monster`.");
+ s.serialize_field("test", &f)?;
+ }
+ _ => unimplemented!(),
+ }
+ if let Some(f) = self.test4() {
+ s.serialize_field("test4", &f)?;
+ } else {
+ s.skip_field("test4")?;
+ }
+ if let Some(f) = self.testarrayofstring() {
+ s.serialize_field("testarrayofstring", &f)?;
+ } else {
+ s.skip_field("testarrayofstring")?;
+ }
+ if let Some(f) = self.testarrayoftables() {
+ s.serialize_field("testarrayoftables", &f)?;
+ } else {
+ s.skip_field("testarrayoftables")?;
+ }
+ if let Some(f) = self.enemy() {
+ s.serialize_field("enemy", &f)?;
+ } else {
+ s.skip_field("enemy")?;
+ }
+ if let Some(f) = self.testnestedflatbuffer() {
+ s.serialize_field("testnestedflatbuffer", &f)?;
+ } else {
+ s.skip_field("testnestedflatbuffer")?;
+ }
+ if let Some(f) = self.testempty() {
+ s.serialize_field("testempty", &f)?;
+ } else {
+ s.skip_field("testempty")?;
+ }
+ s.serialize_field("testbool", &self.testbool())?;
+ s.serialize_field("testhashs32_fnv1", &self.testhashs32_fnv1())?;
+ s.serialize_field("testhashu32_fnv1", &self.testhashu32_fnv1())?;
+ s.serialize_field("testhashs64_fnv1", &self.testhashs64_fnv1())?;
+ s.serialize_field("testhashu64_fnv1", &self.testhashu64_fnv1())?;
+ s.serialize_field("testhashs32_fnv1a", &self.testhashs32_fnv1a())?;
+ s.serialize_field("testhashu32_fnv1a", &self.testhashu32_fnv1a())?;
+ s.serialize_field("testhashs64_fnv1a", &self.testhashs64_fnv1a())?;
+ s.serialize_field("testhashu64_fnv1a", &self.testhashu64_fnv1a())?;
+ if let Some(f) = self.testarrayofbools() {
+ s.serialize_field("testarrayofbools", &f)?;
+ } else {
+ s.skip_field("testarrayofbools")?;
+ }
+ s.serialize_field("testf", &self.testf())?;
+ s.serialize_field("testf2", &self.testf2())?;
+ s.serialize_field("testf3", &self.testf3())?;
+ if let Some(f) = self.testarrayofstring2() {
+ s.serialize_field("testarrayofstring2", &f)?;
+ } else {
+ s.skip_field("testarrayofstring2")?;
+ }
+ if let Some(f) = self.testarrayofsortedstruct() {
+ s.serialize_field("testarrayofsortedstruct", &f)?;
+ } else {
+ s.skip_field("testarrayofsortedstruct")?;
+ }
+ if let Some(f) = self.flex() {
+ s.serialize_field("flex", &f)?;
+ } else {
+ s.skip_field("flex")?;
+ }
+ if let Some(f) = self.test5() {
+ s.serialize_field("test5", &f)?;
+ } else {
+ s.skip_field("test5")?;
+ }
+ if let Some(f) = self.vector_of_longs() {
+ s.serialize_field("vector_of_longs", &f)?;
+ } else {
+ s.skip_field("vector_of_longs")?;
+ }
+ if let Some(f) = self.vector_of_doubles() {
+ s.serialize_field("vector_of_doubles", &f)?;
+ } else {
+ s.skip_field("vector_of_doubles")?;
+ }
+ if let Some(f) = self.parent_namespace_test() {
+ s.serialize_field("parent_namespace_test", &f)?;
+ } else {
+ s.skip_field("parent_namespace_test")?;
+ }
+ if let Some(f) = self.vector_of_referrables() {
+ s.serialize_field("vector_of_referrables", &f)?;
+ } else {
+ s.skip_field("vector_of_referrables")?;
+ }
+ s.serialize_field("single_weak_reference", &self.single_weak_reference())?;
+ if let Some(f) = self.vector_of_weak_references() {
+ s.serialize_field("vector_of_weak_references", &f)?;
+ } else {
+ s.skip_field("vector_of_weak_references")?;
+ }
+ if let Some(f) = self.vector_of_strong_referrables() {
+ s.serialize_field("vector_of_strong_referrables", &f)?;
+ } else {
+ s.skip_field("vector_of_strong_referrables")?;
+ }
+ s.serialize_field("co_owning_reference", &self.co_owning_reference())?;
+ if let Some(f) = self.vector_of_co_owning_references() {
+ s.serialize_field("vector_of_co_owning_references", &f)?;
+ } else {
+ s.skip_field("vector_of_co_owning_references")?;
+ }
+ s.serialize_field("non_owning_reference", &self.non_owning_reference())?;
+ if let Some(f) = self.vector_of_non_owning_references() {
+ s.serialize_field("vector_of_non_owning_references", &f)?;
+ } else {
+ s.skip_field("vector_of_non_owning_references")?;
+ }
+ s.serialize_field("any_unique_type", &self.any_unique_type())?;
+ match self.any_unique_type() {
+ AnyUniqueAliases::NONE => (),
+ AnyUniqueAliases::M => {
+ let f = self.any_unique_as_m()
+ .expect("Invalid union table, expected `AnyUniqueAliases::M`.");
+ s.serialize_field("any_unique", &f)?;
+ }
+ AnyUniqueAliases::TS => {
+ let f = self.any_unique_as_ts()
+ .expect("Invalid union table, expected `AnyUniqueAliases::TS`.");
+ s.serialize_field("any_unique", &f)?;
+ }
+ AnyUniqueAliases::M2 => {
+ let f = self.any_unique_as_m2()
+ .expect("Invalid union table, expected `AnyUniqueAliases::M2`.");
+ s.serialize_field("any_unique", &f)?;
+ }
+ _ => unimplemented!(),
+ }
+ s.serialize_field("any_ambiguous_type", &self.any_ambiguous_type())?;
+ match self.any_ambiguous_type() {
+ AnyAmbiguousAliases::NONE => (),
+ AnyAmbiguousAliases::M1 => {
+ let f = self.any_ambiguous_as_m1()
+ .expect("Invalid union table, expected `AnyAmbiguousAliases::M1`.");
+ s.serialize_field("any_ambiguous", &f)?;
+ }
+ AnyAmbiguousAliases::M2 => {
+ let f = self.any_ambiguous_as_m2()
+ .expect("Invalid union table, expected `AnyAmbiguousAliases::M2`.");
+ s.serialize_field("any_ambiguous", &f)?;
+ }
+ AnyAmbiguousAliases::M3 => {
+ let f = self.any_ambiguous_as_m3()
+ .expect("Invalid union table, expected `AnyAmbiguousAliases::M3`.");
+ s.serialize_field("any_ambiguous", &f)?;
+ }
+ _ => unimplemented!(),
+ }
+ if let Some(f) = self.vector_of_enums() {
+ s.serialize_field("vector_of_enums", &f)?;
+ } else {
+ s.skip_field("vector_of_enums")?;
+ }
+ s.serialize_field("signed_enum", &self.signed_enum())?;
+ if let Some(f) = self.testrequirednestedflatbuffer() {
+ s.serialize_field("testrequirednestedflatbuffer", &f)?;
+ } else {
+ s.skip_field("testrequirednestedflatbuffer")?;
+ }
+ if let Some(f) = self.scalar_key_sorted_tables() {
+ s.serialize_field("scalar_key_sorted_tables", &f)?;
+ } else {
+ s.skip_field("scalar_key_sorted_tables")?;
+ }
+ if let Some(f) = self.native_inline() {
+ s.serialize_field("native_inline", &f)?;
+ } else {
+ s.skip_field("native_inline")?;
+ }
+ s.serialize_field("long_enum_non_enum_default", &self.long_enum_non_enum_default())?;
+ s.serialize_field("long_enum_normal_default", &self.long_enum_normal_default())?;
+ s.end()
+ }
+}
+
+pub struct MonsterBuilder<'a: 'b, 'b> {
+ fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
+ start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
+}
+impl<'a: 'b, 'b> MonsterBuilder<'a, 'b> {
+ #[inline]
+ pub fn add_pos(&mut self, pos: &Vec3) {
+ self.fbb_.push_slot_always::<&Vec3>(Monster::VT_POS, pos);
+ }
+ #[inline]
+ pub fn add_mana(&mut self, mana: i16) {
+ self.fbb_.push_slot::<i16>(Monster::VT_MANA, mana, 150);
+ }
+ #[inline]
+ pub fn add_hp(&mut self, hp: i16) {
+ self.fbb_.push_slot::<i16>(Monster::VT_HP, hp, 100);
+ }
+ #[inline]
+ pub fn add_name(&mut self, name: flatbuffers::WIPOffset<&'b str>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_NAME, name);
+ }
+ #[inline]
+ pub fn add_inventory(&mut self, inventory: flatbuffers::WIPOffset<flatbuffers::Vector<'b , u8>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_INVENTORY, inventory);
+ }
+ #[inline]
+ pub fn add_color(&mut self, color: Color) {
+ self.fbb_.push_slot::<Color>(Monster::VT_COLOR, color, Color::Blue);
+ }
+ #[inline]
+ pub fn add_test_type(&mut self, test_type: Any) {
+ self.fbb_.push_slot::<Any>(Monster::VT_TEST_TYPE, test_type, Any::NONE);
+ }
+ #[inline]
+ pub fn add_test(&mut self, test: flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_TEST, test);
+ }
+ #[inline]
+ pub fn add_test4(&mut self, test4: flatbuffers::WIPOffset<flatbuffers::Vector<'b , Test>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_TEST4, test4);
+ }
+ #[inline]
+ pub fn add_testarrayofstring(&mut self, testarrayofstring: flatbuffers::WIPOffset<flatbuffers::Vector<'b , flatbuffers::ForwardsUOffset<&'b str>>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_TESTARRAYOFSTRING, testarrayofstring);
+ }
+ #[inline]
+ pub fn add_testarrayoftables(&mut self, testarrayoftables: flatbuffers::WIPOffset<flatbuffers::Vector<'b , flatbuffers::ForwardsUOffset<Monster<'b >>>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_TESTARRAYOFTABLES, testarrayoftables);
+ }
+ #[inline]
+ pub fn add_enemy(&mut self, enemy: flatbuffers::WIPOffset<Monster<'b >>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<Monster>>(Monster::VT_ENEMY, enemy);
+ }
+ #[inline]
+ pub fn add_testnestedflatbuffer(&mut self, testnestedflatbuffer: flatbuffers::WIPOffset<flatbuffers::Vector<'b , u8>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_TESTNESTEDFLATBUFFER, testnestedflatbuffer);
+ }
+ #[inline]
+ pub fn add_testempty(&mut self, testempty: flatbuffers::WIPOffset<Stat<'b >>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<Stat>>(Monster::VT_TESTEMPTY, testempty);
+ }
+ #[inline]
+ pub fn add_testbool(&mut self, testbool: bool) {
+ self.fbb_.push_slot::<bool>(Monster::VT_TESTBOOL, testbool, false);
+ }
+ #[inline]
+ pub fn add_testhashs32_fnv1(&mut self, testhashs32_fnv1: i32) {
+ self.fbb_.push_slot::<i32>(Monster::VT_TESTHASHS32_FNV1, testhashs32_fnv1, 0);
+ }
+ #[inline]
+ pub fn add_testhashu32_fnv1(&mut self, testhashu32_fnv1: u32) {
+ self.fbb_.push_slot::<u32>(Monster::VT_TESTHASHU32_FNV1, testhashu32_fnv1, 0);
+ }
+ #[inline]
+ pub fn add_testhashs64_fnv1(&mut self, testhashs64_fnv1: i64) {
+ self.fbb_.push_slot::<i64>(Monster::VT_TESTHASHS64_FNV1, testhashs64_fnv1, 0);
+ }
+ #[inline]
+ pub fn add_testhashu64_fnv1(&mut self, testhashu64_fnv1: u64) {
+ self.fbb_.push_slot::<u64>(Monster::VT_TESTHASHU64_FNV1, testhashu64_fnv1, 0);
+ }
+ #[inline]
+ pub fn add_testhashs32_fnv1a(&mut self, testhashs32_fnv1a: i32) {
+ self.fbb_.push_slot::<i32>(Monster::VT_TESTHASHS32_FNV1A, testhashs32_fnv1a, 0);
+ }
+ #[inline]
+ pub fn add_testhashu32_fnv1a(&mut self, testhashu32_fnv1a: u32) {
+ self.fbb_.push_slot::<u32>(Monster::VT_TESTHASHU32_FNV1A, testhashu32_fnv1a, 0);
+ }
+ #[inline]
+ pub fn add_testhashs64_fnv1a(&mut self, testhashs64_fnv1a: i64) {
+ self.fbb_.push_slot::<i64>(Monster::VT_TESTHASHS64_FNV1A, testhashs64_fnv1a, 0);
+ }
+ #[inline]
+ pub fn add_testhashu64_fnv1a(&mut self, testhashu64_fnv1a: u64) {
+ self.fbb_.push_slot::<u64>(Monster::VT_TESTHASHU64_FNV1A, testhashu64_fnv1a, 0);
+ }
+ #[inline]
+ pub fn add_testarrayofbools(&mut self, testarrayofbools: flatbuffers::WIPOffset<flatbuffers::Vector<'b , bool>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_TESTARRAYOFBOOLS, testarrayofbools);
+ }
+ #[inline]
+ pub fn add_testf(&mut self, testf: f32) {
+ self.fbb_.push_slot::<f32>(Monster::VT_TESTF, testf, 3.14159);
+ }
+ #[inline]
+ pub fn add_testf2(&mut self, testf2: f32) {
+ self.fbb_.push_slot::<f32>(Monster::VT_TESTF2, testf2, 3.0);
+ }
+ #[inline]
+ pub fn add_testf3(&mut self, testf3: f32) {
+ self.fbb_.push_slot::<f32>(Monster::VT_TESTF3, testf3, 0.0);
+ }
+ #[inline]
+ pub fn add_testarrayofstring2(&mut self, testarrayofstring2: flatbuffers::WIPOffset<flatbuffers::Vector<'b , flatbuffers::ForwardsUOffset<&'b str>>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_TESTARRAYOFSTRING2, testarrayofstring2);
+ }
+ #[inline]
+ pub fn add_testarrayofsortedstruct(&mut self, testarrayofsortedstruct: flatbuffers::WIPOffset<flatbuffers::Vector<'b , Ability>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_TESTARRAYOFSORTEDSTRUCT, testarrayofsortedstruct);
+ }
+ #[inline]
+ pub fn add_flex(&mut self, flex: flatbuffers::WIPOffset<flatbuffers::Vector<'b , u8>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_FLEX, flex);
+ }
+ #[inline]
+ pub fn add_test5(&mut self, test5: flatbuffers::WIPOffset<flatbuffers::Vector<'b , Test>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_TEST5, test5);
+ }
+ #[inline]
+ pub fn add_vector_of_longs(&mut self, vector_of_longs: flatbuffers::WIPOffset<flatbuffers::Vector<'b , i64>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_LONGS, vector_of_longs);
+ }
+ #[inline]
+ pub fn add_vector_of_doubles(&mut self, vector_of_doubles: flatbuffers::WIPOffset<flatbuffers::Vector<'b , f64>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_DOUBLES, vector_of_doubles);
+ }
+ #[inline]
+ pub fn add_parent_namespace_test(&mut self, parent_namespace_test: flatbuffers::WIPOffset<super::InParentNamespace<'b >>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<super::InParentNamespace>>(Monster::VT_PARENT_NAMESPACE_TEST, parent_namespace_test);
+ }
+ #[inline]
+ pub fn add_vector_of_referrables(&mut self, vector_of_referrables: flatbuffers::WIPOffset<flatbuffers::Vector<'b , flatbuffers::ForwardsUOffset<Referrable<'b >>>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_REFERRABLES, vector_of_referrables);
+ }
+ #[inline]
+ pub fn add_single_weak_reference(&mut self, single_weak_reference: u64) {
+ self.fbb_.push_slot::<u64>(Monster::VT_SINGLE_WEAK_REFERENCE, single_weak_reference, 0);
+ }
+ #[inline]
+ pub fn add_vector_of_weak_references(&mut self, vector_of_weak_references: flatbuffers::WIPOffset<flatbuffers::Vector<'b , u64>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_WEAK_REFERENCES, vector_of_weak_references);
+ }
+ #[inline]
+ pub fn add_vector_of_strong_referrables(&mut self, vector_of_strong_referrables: flatbuffers::WIPOffset<flatbuffers::Vector<'b , flatbuffers::ForwardsUOffset<Referrable<'b >>>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_STRONG_REFERRABLES, vector_of_strong_referrables);
+ }
+ #[inline]
+ pub fn add_co_owning_reference(&mut self, co_owning_reference: u64) {
+ self.fbb_.push_slot::<u64>(Monster::VT_CO_OWNING_REFERENCE, co_owning_reference, 0);
+ }
+ #[inline]
+ pub fn add_vector_of_co_owning_references(&mut self, vector_of_co_owning_references: flatbuffers::WIPOffset<flatbuffers::Vector<'b , u64>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_CO_OWNING_REFERENCES, vector_of_co_owning_references);
+ }
+ #[inline]
+ pub fn add_non_owning_reference(&mut self, non_owning_reference: u64) {
+ self.fbb_.push_slot::<u64>(Monster::VT_NON_OWNING_REFERENCE, non_owning_reference, 0);
+ }
+ #[inline]
+ pub fn add_vector_of_non_owning_references(&mut self, vector_of_non_owning_references: flatbuffers::WIPOffset<flatbuffers::Vector<'b , u64>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_NON_OWNING_REFERENCES, vector_of_non_owning_references);
+ }
+ #[inline]
+ pub fn add_any_unique_type(&mut self, any_unique_type: AnyUniqueAliases) {
+ self.fbb_.push_slot::<AnyUniqueAliases>(Monster::VT_ANY_UNIQUE_TYPE, any_unique_type, AnyUniqueAliases::NONE);
+ }
+ #[inline]
+ pub fn add_any_unique(&mut self, any_unique: flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_ANY_UNIQUE, any_unique);
+ }
+ #[inline]
+ pub fn add_any_ambiguous_type(&mut self, any_ambiguous_type: AnyAmbiguousAliases) {
+ self.fbb_.push_slot::<AnyAmbiguousAliases>(Monster::VT_ANY_AMBIGUOUS_TYPE, any_ambiguous_type, AnyAmbiguousAliases::NONE);
+ }
+ #[inline]
+ pub fn add_any_ambiguous(&mut self, any_ambiguous: flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_ANY_AMBIGUOUS, any_ambiguous);
+ }
+ #[inline]
+ pub fn add_vector_of_enums(&mut self, vector_of_enums: flatbuffers::WIPOffset<flatbuffers::Vector<'b , Color>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_ENUMS, vector_of_enums);
+ }
+ #[inline]
+ pub fn add_signed_enum(&mut self, signed_enum: Race) {
+ self.fbb_.push_slot::<Race>(Monster::VT_SIGNED_ENUM, signed_enum, Race::None);
+ }
+ #[inline]
+ pub fn add_testrequirednestedflatbuffer(&mut self, testrequirednestedflatbuffer: flatbuffers::WIPOffset<flatbuffers::Vector<'b , u8>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_TESTREQUIREDNESTEDFLATBUFFER, testrequirednestedflatbuffer);
+ }
+ #[inline]
+ pub fn add_scalar_key_sorted_tables(&mut self, scalar_key_sorted_tables: flatbuffers::WIPOffset<flatbuffers::Vector<'b , flatbuffers::ForwardsUOffset<Stat<'b >>>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_SCALAR_KEY_SORTED_TABLES, scalar_key_sorted_tables);
+ }
+ #[inline]
+ pub fn add_native_inline(&mut self, native_inline: &Test) {
+ self.fbb_.push_slot_always::<&Test>(Monster::VT_NATIVE_INLINE, native_inline);
+ }
+ #[inline]
+ pub fn add_long_enum_non_enum_default(&mut self, long_enum_non_enum_default: LongEnum) {
+ self.fbb_.push_slot::<LongEnum>(Monster::VT_LONG_ENUM_NON_ENUM_DEFAULT, long_enum_non_enum_default, Default::default());
+ }
+ #[inline]
+ pub fn add_long_enum_normal_default(&mut self, long_enum_normal_default: LongEnum) {
+ self.fbb_.push_slot::<LongEnum>(Monster::VT_LONG_ENUM_NORMAL_DEFAULT, long_enum_normal_default, LongEnum::LongOne);
+ }
+ #[inline]
+ pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> MonsterBuilder<'a, 'b> {
+ let start = _fbb.start_table();
+ MonsterBuilder {
+ fbb_: _fbb,
+ start_: start,
+ }
+ }
+ #[inline]
+ pub fn finish(self) -> flatbuffers::WIPOffset<Monster<'a>> {
+ let o = self.fbb_.end_table(self.start_);
+ self.fbb_.required(o, Monster::VT_NAME,"name");
+ flatbuffers::WIPOffset::new(o.value())
+ }
+}
+
+impl std::fmt::Debug for Monster<'_> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let mut ds = f.debug_struct("Monster");
+ ds.field("pos", &self.pos());
+ ds.field("mana", &self.mana());
+ ds.field("hp", &self.hp());
+ ds.field("name", &self.name());
+ ds.field("inventory", &self.inventory());
+ ds.field("color", &self.color());
+ ds.field("test_type", &self.test_type());
+ match self.test_type() {
+ Any::Monster => {
+ if let Some(x) = self.test_as_monster() {
+ ds.field("test", &x)
+ } else {
+ ds.field("test", &"InvalidFlatbuffer: Union discriminant does not match value.")
+ }
+ },
+ Any::TestSimpleTableWithEnum => {
+ if let Some(x) = self.test_as_test_simple_table_with_enum() {
+ ds.field("test", &x)
+ } else {
+ ds.field("test", &"InvalidFlatbuffer: Union discriminant does not match value.")
+ }
+ },
+ Any::MyGame_Example2_Monster => {
+ if let Some(x) = self.test_as_my_game_example_2_monster() {
+ ds.field("test", &x)
+ } else {
+ ds.field("test", &"InvalidFlatbuffer: Union discriminant does not match value.")
+ }
+ },
+ _ => {
+ let x: Option<()> = None;
+ ds.field("test", &x)
+ },
+ };
+ ds.field("test4", &self.test4());
+ ds.field("testarrayofstring", &self.testarrayofstring());
+ ds.field("testarrayoftables", &self.testarrayoftables());
+ ds.field("enemy", &self.enemy());
+ ds.field("testnestedflatbuffer", &self.testnestedflatbuffer());
+ ds.field("testempty", &self.testempty());
+ ds.field("testbool", &self.testbool());
+ ds.field("testhashs32_fnv1", &self.testhashs32_fnv1());
+ ds.field("testhashu32_fnv1", &self.testhashu32_fnv1());
+ ds.field("testhashs64_fnv1", &self.testhashs64_fnv1());
+ ds.field("testhashu64_fnv1", &self.testhashu64_fnv1());
+ ds.field("testhashs32_fnv1a", &self.testhashs32_fnv1a());
+ ds.field("testhashu32_fnv1a", &self.testhashu32_fnv1a());
+ ds.field("testhashs64_fnv1a", &self.testhashs64_fnv1a());
+ ds.field("testhashu64_fnv1a", &self.testhashu64_fnv1a());
+ ds.field("testarrayofbools", &self.testarrayofbools());
+ ds.field("testf", &self.testf());
+ ds.field("testf2", &self.testf2());
+ ds.field("testf3", &self.testf3());
+ ds.field("testarrayofstring2", &self.testarrayofstring2());
+ ds.field("testarrayofsortedstruct", &self.testarrayofsortedstruct());
+ ds.field("flex", &self.flex());
+ ds.field("test5", &self.test5());
+ ds.field("vector_of_longs", &self.vector_of_longs());
+ ds.field("vector_of_doubles", &self.vector_of_doubles());
+ ds.field("parent_namespace_test", &self.parent_namespace_test());
+ ds.field("vector_of_referrables", &self.vector_of_referrables());
+ ds.field("single_weak_reference", &self.single_weak_reference());
+ ds.field("vector_of_weak_references", &self.vector_of_weak_references());
+ ds.field("vector_of_strong_referrables", &self.vector_of_strong_referrables());
+ ds.field("co_owning_reference", &self.co_owning_reference());
+ ds.field("vector_of_co_owning_references", &self.vector_of_co_owning_references());
+ ds.field("non_owning_reference", &self.non_owning_reference());
+ ds.field("vector_of_non_owning_references", &self.vector_of_non_owning_references());
+ ds.field("any_unique_type", &self.any_unique_type());
+ match self.any_unique_type() {
+ AnyUniqueAliases::M => {
+ if let Some(x) = self.any_unique_as_m() {
+ ds.field("any_unique", &x)
+ } else {
+ ds.field("any_unique", &"InvalidFlatbuffer: Union discriminant does not match value.")
+ }
+ },
+ AnyUniqueAliases::TS => {
+ if let Some(x) = self.any_unique_as_ts() {
+ ds.field("any_unique", &x)
+ } else {
+ ds.field("any_unique", &"InvalidFlatbuffer: Union discriminant does not match value.")
+ }
+ },
+ AnyUniqueAliases::M2 => {
+ if let Some(x) = self.any_unique_as_m2() {
+ ds.field("any_unique", &x)
+ } else {
+ ds.field("any_unique", &"InvalidFlatbuffer: Union discriminant does not match value.")
+ }
+ },
+ _ => {
+ let x: Option<()> = None;
+ ds.field("any_unique", &x)
+ },
+ };
+ ds.field("any_ambiguous_type", &self.any_ambiguous_type());
+ match self.any_ambiguous_type() {
+ AnyAmbiguousAliases::M1 => {
+ if let Some(x) = self.any_ambiguous_as_m1() {
+ ds.field("any_ambiguous", &x)
+ } else {
+ ds.field("any_ambiguous", &"InvalidFlatbuffer: Union discriminant does not match value.")
+ }
+ },
+ AnyAmbiguousAliases::M2 => {
+ if let Some(x) = self.any_ambiguous_as_m2() {
+ ds.field("any_ambiguous", &x)
+ } else {
+ ds.field("any_ambiguous", &"InvalidFlatbuffer: Union discriminant does not match value.")
+ }
+ },
+ AnyAmbiguousAliases::M3 => {
+ if let Some(x) = self.any_ambiguous_as_m3() {
+ ds.field("any_ambiguous", &x)
+ } else {
+ ds.field("any_ambiguous", &"InvalidFlatbuffer: Union discriminant does not match value.")
+ }
+ },
+ _ => {
+ let x: Option<()> = None;
+ ds.field("any_ambiguous", &x)
+ },
+ };
+ ds.field("vector_of_enums", &self.vector_of_enums());
+ ds.field("signed_enum", &self.signed_enum());
+ ds.field("testrequirednestedflatbuffer", &self.testrequirednestedflatbuffer());
+ ds.field("scalar_key_sorted_tables", &self.scalar_key_sorted_tables());
+ ds.field("native_inline", &self.native_inline());
+ ds.field("long_enum_non_enum_default", &self.long_enum_non_enum_default());
+ ds.field("long_enum_normal_default", &self.long_enum_normal_default());
+ ds.finish()
+ }
+}
+#[non_exhaustive]
+#[derive(Debug, Clone, PartialEq)]
+pub struct MonsterT {
+ pub pos: Option<Vec3T>,
+ pub mana: i16,
+ pub hp: i16,
+ pub name: String,
+ pub inventory: Option<Vec<u8>>,
+ pub color: Color,
+ pub test: AnyT,
+ pub test4: Option<Vec<TestT>>,
+ pub testarrayofstring: Option<Vec<String>>,
+ pub testarrayoftables: Option<Vec<MonsterT>>,
+ pub enemy: Option<Box<MonsterT>>,
+ pub testnestedflatbuffer: Option<Vec<u8>>,
+ pub testempty: Option<Box<StatT>>,
+ pub testbool: bool,
+ pub testhashs32_fnv1: i32,
+ pub testhashu32_fnv1: u32,
+ pub testhashs64_fnv1: i64,
+ pub testhashu64_fnv1: u64,
+ pub testhashs32_fnv1a: i32,
+ pub testhashu32_fnv1a: u32,
+ pub testhashs64_fnv1a: i64,
+ pub testhashu64_fnv1a: u64,
+ pub testarrayofbools: Option<Vec<bool>>,
+ pub testf: f32,
+ pub testf2: f32,
+ pub testf3: f32,
+ pub testarrayofstring2: Option<Vec<String>>,
+ pub testarrayofsortedstruct: Option<Vec<AbilityT>>,
+ pub flex: Option<Vec<u8>>,
+ pub test5: Option<Vec<TestT>>,
+ pub vector_of_longs: Option<Vec<i64>>,
+ pub vector_of_doubles: Option<Vec<f64>>,
+ pub parent_namespace_test: Option<Box<super::InParentNamespaceT>>,
+ pub vector_of_referrables: Option<Vec<ReferrableT>>,
+ pub single_weak_reference: u64,
+ pub vector_of_weak_references: Option<Vec<u64>>,
+ pub vector_of_strong_referrables: Option<Vec<ReferrableT>>,
+ pub co_owning_reference: u64,
+ pub vector_of_co_owning_references: Option<Vec<u64>>,
+ pub non_owning_reference: u64,
+ pub vector_of_non_owning_references: Option<Vec<u64>>,
+ pub any_unique: AnyUniqueAliasesT,
+ pub any_ambiguous: AnyAmbiguousAliasesT,
+ pub vector_of_enums: Option<Vec<Color>>,
+ pub signed_enum: Race,
+ pub testrequirednestedflatbuffer: Option<Vec<u8>>,
+ pub scalar_key_sorted_tables: Option<Vec<StatT>>,
+ pub native_inline: Option<TestT>,
+ pub long_enum_non_enum_default: LongEnum,
+ pub long_enum_normal_default: LongEnum,
+}
+impl Default for MonsterT {
+ fn default() -> Self {
+ Self {
+ pos: None,
+ mana: 150,
+ hp: 100,
+ name: "".to_string(),
+ inventory: None,
+ color: Color::Blue,
+ test: AnyT::NONE,
+ test4: None,
+ testarrayofstring: None,
+ testarrayoftables: None,
+ enemy: None,
+ testnestedflatbuffer: None,
+ testempty: None,
+ testbool: false,
+ testhashs32_fnv1: 0,
+ testhashu32_fnv1: 0,
+ testhashs64_fnv1: 0,
+ testhashu64_fnv1: 0,
+ testhashs32_fnv1a: 0,
+ testhashu32_fnv1a: 0,
+ testhashs64_fnv1a: 0,
+ testhashu64_fnv1a: 0,
+ testarrayofbools: None,
+ testf: 3.14159,
+ testf2: 3.0,
+ testf3: 0.0,
+ testarrayofstring2: None,
+ testarrayofsortedstruct: None,
+ flex: None,
+ test5: None,
+ vector_of_longs: None,
+ vector_of_doubles: None,
+ parent_namespace_test: None,
+ vector_of_referrables: None,
+ single_weak_reference: 0,
+ vector_of_weak_references: None,
+ vector_of_strong_referrables: None,
+ co_owning_reference: 0,
+ vector_of_co_owning_references: None,
+ non_owning_reference: 0,
+ vector_of_non_owning_references: None,
+ any_unique: AnyUniqueAliasesT::NONE,
+ any_ambiguous: AnyAmbiguousAliasesT::NONE,
+ vector_of_enums: None,
+ signed_enum: Race::None,
+ testrequirednestedflatbuffer: None,
+ scalar_key_sorted_tables: None,
+ native_inline: None,
+ long_enum_non_enum_default: Default::default(),
+ long_enum_normal_default: LongEnum::LongOne,
+ }
+ }
+}
+impl MonsterT {
+ pub fn pack<'b>(
+ &self,
+ _fbb: &mut flatbuffers::FlatBufferBuilder<'b>
+ ) -> flatbuffers::WIPOffset<Monster<'b>> {
+ let pos_tmp = self.pos.as_ref().map(|x| x.pack());
+ let pos = pos_tmp.as_ref();
+ let mana = self.mana;
+ let hp = self.hp;
+ let name = Some({
+ let x = &self.name;
+ _fbb.create_string(x)
+ });
+ let inventory = self.inventory.as_ref().map(|x|{
+ _fbb.create_vector(x)
+ });
+ let color = self.color;
+ let test_type = self.test.any_type();
+ let test = self.test.pack(_fbb);
+ let test4 = self.test4.as_ref().map(|x|{
+ let w: Vec<_> = x.iter().map(|t| t.pack()).collect();_fbb.create_vector(&w)
+ });
+ let testarrayofstring = self.testarrayofstring.as_ref().map(|x|{
+ let w: Vec<_> = x.iter().map(|s| s.as_ref()).collect();_fbb.create_vector_of_strings(&w)
+ });
+ let testarrayoftables = self.testarrayoftables.as_ref().map(|x|{
+ let w: Vec<_> = x.iter().map(|t| t.pack(_fbb)).collect();_fbb.create_vector(&w)
+ });
+ let enemy = self.enemy.as_ref().map(|x|{
+ x.pack(_fbb)
+ });
+ let testnestedflatbuffer = self.testnestedflatbuffer.as_ref().map(|x|{
+ _fbb.create_vector(x)
+ });
+ let testempty = self.testempty.as_ref().map(|x|{
+ x.pack(_fbb)
+ });
+ let testbool = self.testbool;
+ let testhashs32_fnv1 = self.testhashs32_fnv1;
+ let testhashu32_fnv1 = self.testhashu32_fnv1;
+ let testhashs64_fnv1 = self.testhashs64_fnv1;
+ let testhashu64_fnv1 = self.testhashu64_fnv1;
+ let testhashs32_fnv1a = self.testhashs32_fnv1a;
+ let testhashu32_fnv1a = self.testhashu32_fnv1a;
+ let testhashs64_fnv1a = self.testhashs64_fnv1a;
+ let testhashu64_fnv1a = self.testhashu64_fnv1a;
+ let testarrayofbools = self.testarrayofbools.as_ref().map(|x|{
+ _fbb.create_vector(x)
+ });
+ let testf = self.testf;
+ let testf2 = self.testf2;
+ let testf3 = self.testf3;
+ let testarrayofstring2 = self.testarrayofstring2.as_ref().map(|x|{
+ let w: Vec<_> = x.iter().map(|s| s.as_ref()).collect();_fbb.create_vector_of_strings(&w)
+ });
+ let testarrayofsortedstruct = self.testarrayofsortedstruct.as_ref().map(|x|{
+ let w: Vec<_> = x.iter().map(|t| t.pack()).collect();_fbb.create_vector(&w)
+ });
+ let flex = self.flex.as_ref().map(|x|{
+ _fbb.create_vector(x)
+ });
+ let test5 = self.test5.as_ref().map(|x|{
+ let w: Vec<_> = x.iter().map(|t| t.pack()).collect();_fbb.create_vector(&w)
+ });
+ let vector_of_longs = self.vector_of_longs.as_ref().map(|x|{
+ _fbb.create_vector(x)
+ });
+ let vector_of_doubles = self.vector_of_doubles.as_ref().map(|x|{
+ _fbb.create_vector(x)
+ });
+ let parent_namespace_test = self.parent_namespace_test.as_ref().map(|x|{
+ x.pack(_fbb)
+ });
+ let vector_of_referrables = self.vector_of_referrables.as_ref().map(|x|{
+ let w: Vec<_> = x.iter().map(|t| t.pack(_fbb)).collect();_fbb.create_vector(&w)
+ });
+ let single_weak_reference = self.single_weak_reference;
+ let vector_of_weak_references = self.vector_of_weak_references.as_ref().map(|x|{
+ _fbb.create_vector(x)
+ });
+ let vector_of_strong_referrables = self.vector_of_strong_referrables.as_ref().map(|x|{
+ let w: Vec<_> = x.iter().map(|t| t.pack(_fbb)).collect();_fbb.create_vector(&w)
+ });
+ let co_owning_reference = self.co_owning_reference;
+ let vector_of_co_owning_references = self.vector_of_co_owning_references.as_ref().map(|x|{
+ _fbb.create_vector(x)
+ });
+ let non_owning_reference = self.non_owning_reference;
+ let vector_of_non_owning_references = self.vector_of_non_owning_references.as_ref().map(|x|{
+ _fbb.create_vector(x)
+ });
+ let any_unique_type = self.any_unique.any_unique_aliases_type();
+ let any_unique = self.any_unique.pack(_fbb);
+ let any_ambiguous_type = self.any_ambiguous.any_ambiguous_aliases_type();
+ let any_ambiguous = self.any_ambiguous.pack(_fbb);
+ let vector_of_enums = self.vector_of_enums.as_ref().map(|x|{
+ _fbb.create_vector(x)
+ });
+ let signed_enum = self.signed_enum;
+ let testrequirednestedflatbuffer = self.testrequirednestedflatbuffer.as_ref().map(|x|{
+ _fbb.create_vector(x)
+ });
+ let scalar_key_sorted_tables = self.scalar_key_sorted_tables.as_ref().map(|x|{
+ let w: Vec<_> = x.iter().map(|t| t.pack(_fbb)).collect();_fbb.create_vector(&w)
+ });
+ let native_inline_tmp = self.native_inline.as_ref().map(|x| x.pack());
+ let native_inline = native_inline_tmp.as_ref();
+ let long_enum_non_enum_default = self.long_enum_non_enum_default;
+ let long_enum_normal_default = self.long_enum_normal_default;
+ Monster::create(_fbb, &MonsterArgs{
+ pos,
+ mana,
+ hp,
+ name,
+ inventory,
+ color,
+ test_type,
+ test,
+ test4,
+ testarrayofstring,
+ testarrayoftables,
+ enemy,
+ testnestedflatbuffer,
+ testempty,
+ testbool,
+ testhashs32_fnv1,
+ testhashu32_fnv1,
+ testhashs64_fnv1,
+ testhashu64_fnv1,
+ testhashs32_fnv1a,
+ testhashu32_fnv1a,
+ testhashs64_fnv1a,
+ testhashu64_fnv1a,
+ testarrayofbools,
+ testf,
+ testf2,
+ testf3,
+ testarrayofstring2,
+ testarrayofsortedstruct,
+ flex,
+ test5,
+ vector_of_longs,
+ vector_of_doubles,
+ parent_namespace_test,
+ vector_of_referrables,
+ single_weak_reference,
+ vector_of_weak_references,
+ vector_of_strong_referrables,
+ co_owning_reference,
+ vector_of_co_owning_references,
+ non_owning_reference,
+ vector_of_non_owning_references,
+ any_unique_type,
+ any_unique,
+ any_ambiguous_type,
+ any_ambiguous,
+ vector_of_enums,
+ signed_enum,
+ testrequirednestedflatbuffer,
+ scalar_key_sorted_tables,
+ native_inline,
+ long_enum_non_enum_default,
+ long_enum_normal_default,
+ })
+ }
+}
+#[inline]
+#[deprecated(since="2.0.0", note="Deprecated in favor of `root_as...` methods.")]
+pub fn get_root_as_monster<'a>(buf: &'a [u8]) -> Monster<'a> {
+ unsafe { flatbuffers::root_unchecked::<Monster<'a>>(buf) }
+}
+
+#[inline]
+#[deprecated(since="2.0.0", note="Deprecated in favor of `root_as...` methods.")]
+pub fn get_size_prefixed_root_as_monster<'a>(buf: &'a [u8]) -> Monster<'a> {
+ unsafe { flatbuffers::size_prefixed_root_unchecked::<Monster<'a>>(buf) }
+}
+
+#[inline]
+/// Verifies that a buffer of bytes contains a `Monster`
+/// and returns it.
+/// Note that verification is still experimental and may not
+/// catch every error, or be maximally performant. For the
+/// previous, unchecked, behavior use
+/// `root_as_monster_unchecked`.
+pub fn root_as_monster(buf: &[u8]) -> Result<Monster, flatbuffers::InvalidFlatbuffer> {
+ flatbuffers::root::<Monster>(buf)
+}
+#[inline]
+/// Verifies that a buffer of bytes contains a size prefixed
+/// `Monster` and returns it.
+/// Note that verification is still experimental and may not
+/// catch every error, or be maximally performant. For the
+/// previous, unchecked, behavior use
+/// `size_prefixed_root_as_monster_unchecked`.
+pub fn size_prefixed_root_as_monster(buf: &[u8]) -> Result<Monster, flatbuffers::InvalidFlatbuffer> {
+ flatbuffers::size_prefixed_root::<Monster>(buf)
+}
+#[inline]
+/// Verifies, with the given options, that a buffer of bytes
+/// contains a `Monster` and returns it.
+/// Note that verification is still experimental and may not
+/// catch every error, or be maximally performant. For the
+/// previous, unchecked, behavior use
+/// `root_as_monster_unchecked`.
+pub fn root_as_monster_with_opts<'b, 'o>(
+ opts: &'o flatbuffers::VerifierOptions,
+ buf: &'b [u8],
+) -> Result<Monster<'b>, flatbuffers::InvalidFlatbuffer> {
+ flatbuffers::root_with_opts::<Monster<'b>>(opts, buf)
+}
+#[inline]
+/// Verifies, with the given verifier options, that a buffer of
+/// bytes contains a size prefixed `Monster` and returns
+/// it. Note that verification is still experimental and may not
+/// catch every error, or be maximally performant. For the
+/// previous, unchecked, behavior use
+/// `root_as_monster_unchecked`.
+pub fn size_prefixed_root_as_monster_with_opts<'b, 'o>(
+ opts: &'o flatbuffers::VerifierOptions,
+ buf: &'b [u8],
+) -> Result<Monster<'b>, flatbuffers::InvalidFlatbuffer> {
+ flatbuffers::size_prefixed_root_with_opts::<Monster<'b>>(opts, buf)
+}
+#[inline]
+/// Assumes, without verification, that a buffer of bytes contains a Monster and returns it.
+/// # Safety
+/// Callers must trust the given bytes do indeed contain a valid `Monster`.
+pub unsafe fn root_as_monster_unchecked(buf: &[u8]) -> Monster {
+ flatbuffers::root_unchecked::<Monster>(buf)
+}
+#[inline]
+/// Assumes, without verification, that a buffer of bytes contains a size prefixed Monster and returns it.
+/// # Safety
+/// Callers must trust the given bytes do indeed contain a valid size prefixed `Monster`.
+pub unsafe fn size_prefixed_root_as_monster_unchecked(buf: &[u8]) -> Monster {
+ flatbuffers::size_prefixed_root_unchecked::<Monster>(buf)
+}
+pub const MONSTER_IDENTIFIER: &str = "MONS";
+
+#[inline]
+pub fn monster_buffer_has_identifier(buf: &[u8]) -> bool {
+ flatbuffers::buffer_has_identifier(buf, MONSTER_IDENTIFIER, false)
+}
+
+#[inline]
+pub fn monster_size_prefixed_buffer_has_identifier(buf: &[u8]) -> bool {
+ flatbuffers::buffer_has_identifier(buf, MONSTER_IDENTIFIER, true)
+}
+
+pub const MONSTER_EXTENSION: &str = "mon";
+
+#[inline]
+pub fn finish_monster_buffer<'a, 'b>(
+ fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,
+ root: flatbuffers::WIPOffset<Monster<'a>>) {
+ fbb.finish(root, Some(MONSTER_IDENTIFIER));
+}
+
+#[inline]
+pub fn finish_size_prefixed_monster_buffer<'a, 'b>(fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>, root: flatbuffers::WIPOffset<Monster<'a>>) {
+ fbb.finish_size_prefixed(root, Some(MONSTER_IDENTIFIER));
+}
diff --git a/tests/monster_test_serialize/my_game/example/race_generated.rs b/tests/monster_test_serialize/my_game/example/race_generated.rs
new file mode 100644
index 0000000..63754ff
--- /dev/null
+++ b/tests/monster_test_serialize/my_game/example/race_generated.rs
@@ -0,0 +1,112 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+extern crate serde;
+use self::serde::ser::{Serialize, Serializer, SerializeStruct};
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+pub const ENUM_MIN_RACE: i8 = -1;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+pub const ENUM_MAX_RACE: i8 = 2;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+#[allow(non_camel_case_types)]
+pub const ENUM_VALUES_RACE: [Race; 4] = [
+ Race::None,
+ Race::Human,
+ Race::Dwarf,
+ Race::Elf,
+];
+
+#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
+#[repr(transparent)]
+pub struct Race(pub i8);
+#[allow(non_upper_case_globals)]
+impl Race {
+ pub const None: Self = Self(-1);
+ pub const Human: Self = Self(0);
+ pub const Dwarf: Self = Self(1);
+ pub const Elf: Self = Self(2);
+
+ pub const ENUM_MIN: i8 = -1;
+ pub const ENUM_MAX: i8 = 2;
+ pub const ENUM_VALUES: &'static [Self] = &[
+ Self::None,
+ Self::Human,
+ Self::Dwarf,
+ Self::Elf,
+ ];
+ /// Returns the variant's name or "" if unknown.
+ pub fn variant_name(self) -> Option<&'static str> {
+ match self {
+ Self::None => Some("None"),
+ Self::Human => Some("Human"),
+ Self::Dwarf => Some("Dwarf"),
+ Self::Elf => Some("Elf"),
+ _ => None,
+ }
+ }
+}
+impl std::fmt::Debug for Race {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ if let Some(name) = self.variant_name() {
+ f.write_str(name)
+ } else {
+ f.write_fmt(format_args!("<UNKNOWN {:?}>", self.0))
+ }
+ }
+}
+impl Serialize for Race {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: Serializer,
+ {
+ serializer.serialize_unit_variant("Race", self.0 as u32, self.variant_name().unwrap())
+ }
+}
+
+impl<'a> flatbuffers::Follow<'a> for Race {
+ type Inner = Self;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ let b = unsafe {
+ flatbuffers::read_scalar_at::<i8>(buf, loc)
+ };
+ Self(b)
+ }
+}
+
+impl flatbuffers::Push for Race {
+ type Output = Race;
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ unsafe { flatbuffers::emplace_scalar::<i8>(dst, self.0); }
+ }
+}
+
+impl flatbuffers::EndianScalar for Race {
+ #[inline]
+ fn to_little_endian(self) -> Self {
+ let b = i8::to_le(self.0);
+ Self(b)
+ }
+ #[inline]
+ #[allow(clippy::wrong_self_convention)]
+ fn from_little_endian(self) -> Self {
+ let b = i8::from_le(self.0);
+ Self(b)
+ }
+}
+
+impl<'a> flatbuffers::Verifiable for Race {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ i8::run_verifier(v, pos)
+ }
+}
+
+impl flatbuffers::SimpleToVerifyInSlice for Race {}
diff --git a/tests/monster_test_serialize/my_game/example/referrable_generated.rs b/tests/monster_test_serialize/my_game/example/referrable_generated.rs
new file mode 100644
index 0000000..490980d
--- /dev/null
+++ b/tests/monster_test_serialize/my_game/example/referrable_generated.rs
@@ -0,0 +1,156 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+extern crate serde;
+use self::serde::ser::{Serialize, Serializer, SerializeStruct};
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+pub enum ReferrableOffset {}
+#[derive(Copy, Clone, PartialEq)]
+
+pub struct Referrable<'a> {
+ pub _tab: flatbuffers::Table<'a>,
+}
+
+impl<'a> flatbuffers::Follow<'a> for Referrable<'a> {
+ type Inner = Referrable<'a>;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ Self { _tab: flatbuffers::Table { buf, loc } }
+ }
+}
+
+impl<'a> Referrable<'a> {
+ pub const VT_ID: flatbuffers::VOffsetT = 4;
+
+ pub const fn get_fully_qualified_name() -> &'static str {
+ "MyGame.Example.Referrable"
+ }
+
+ #[inline]
+ pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
+ Referrable { _tab: table }
+ }
+ #[allow(unused_mut)]
+ pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
+ _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
+ args: &'args ReferrableArgs
+ ) -> flatbuffers::WIPOffset<Referrable<'bldr>> {
+ let mut builder = ReferrableBuilder::new(_fbb);
+ builder.add_id(args.id);
+ builder.finish()
+ }
+
+ pub fn unpack(&self) -> ReferrableT {
+ let id = self.id();
+ ReferrableT {
+ id,
+ }
+ }
+
+ #[inline]
+ pub fn id(&self) -> u64 {
+ self._tab.get::<u64>(Referrable::VT_ID, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn key_compare_less_than(&self, o: &Referrable) -> bool {
+ self.id() < o.id()
+ }
+
+ #[inline]
+ pub fn key_compare_with_value(&self, val: u64) -> ::std::cmp::Ordering {
+ let key = self.id();
+ key.cmp(&val)
+ }
+}
+
+impl flatbuffers::Verifiable for Referrable<'_> {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ v.visit_table(pos)?
+ .visit_field::<u64>("id", Self::VT_ID, false)?
+ .finish();
+ Ok(())
+ }
+}
+pub struct ReferrableArgs {
+ pub id: u64,
+}
+impl<'a> Default for ReferrableArgs {
+ #[inline]
+ fn default() -> Self {
+ ReferrableArgs {
+ id: 0,
+ }
+ }
+}
+
+impl Serialize for Referrable<'_> {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: Serializer,
+ {
+ let mut s = serializer.serialize_struct("Referrable", 1)?;
+ s.serialize_field("id", &self.id())?;
+ s.end()
+ }
+}
+
+pub struct ReferrableBuilder<'a: 'b, 'b> {
+ fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
+ start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
+}
+impl<'a: 'b, 'b> ReferrableBuilder<'a, 'b> {
+ #[inline]
+ pub fn add_id(&mut self, id: u64) {
+ self.fbb_.push_slot::<u64>(Referrable::VT_ID, id, 0);
+ }
+ #[inline]
+ pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> ReferrableBuilder<'a, 'b> {
+ let start = _fbb.start_table();
+ ReferrableBuilder {
+ fbb_: _fbb,
+ start_: start,
+ }
+ }
+ #[inline]
+ pub fn finish(self) -> flatbuffers::WIPOffset<Referrable<'a>> {
+ let o = self.fbb_.end_table(self.start_);
+ flatbuffers::WIPOffset::new(o.value())
+ }
+}
+
+impl std::fmt::Debug for Referrable<'_> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let mut ds = f.debug_struct("Referrable");
+ ds.field("id", &self.id());
+ ds.finish()
+ }
+}
+#[non_exhaustive]
+#[derive(Debug, Clone, PartialEq)]
+pub struct ReferrableT {
+ pub id: u64,
+}
+impl Default for ReferrableT {
+ fn default() -> Self {
+ Self {
+ id: 0,
+ }
+ }
+}
+impl ReferrableT {
+ pub fn pack<'b>(
+ &self,
+ _fbb: &mut flatbuffers::FlatBufferBuilder<'b>
+ ) -> flatbuffers::WIPOffset<Referrable<'b>> {
+ let id = self.id;
+ Referrable::create(_fbb, &ReferrableArgs{
+ id,
+ })
+ }
+}
diff --git a/tests/monster_test_serialize/my_game/example/stat_generated.rs b/tests/monster_test_serialize/my_game/example/stat_generated.rs
new file mode 100644
index 0000000..abfa05d
--- /dev/null
+++ b/tests/monster_test_serialize/my_game/example/stat_generated.rs
@@ -0,0 +1,206 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+extern crate serde;
+use self::serde::ser::{Serialize, Serializer, SerializeStruct};
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+pub enum StatOffset {}
+#[derive(Copy, Clone, PartialEq)]
+
+pub struct Stat<'a> {
+ pub _tab: flatbuffers::Table<'a>,
+}
+
+impl<'a> flatbuffers::Follow<'a> for Stat<'a> {
+ type Inner = Stat<'a>;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ Self { _tab: flatbuffers::Table { buf, loc } }
+ }
+}
+
+impl<'a> Stat<'a> {
+ pub const VT_ID: flatbuffers::VOffsetT = 4;
+ pub const VT_VAL: flatbuffers::VOffsetT = 6;
+ pub const VT_COUNT: flatbuffers::VOffsetT = 8;
+
+ pub const fn get_fully_qualified_name() -> &'static str {
+ "MyGame.Example.Stat"
+ }
+
+ #[inline]
+ pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
+ Stat { _tab: table }
+ }
+ #[allow(unused_mut)]
+ pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
+ _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
+ args: &'args StatArgs<'args>
+ ) -> flatbuffers::WIPOffset<Stat<'bldr>> {
+ let mut builder = StatBuilder::new(_fbb);
+ builder.add_val(args.val);
+ if let Some(x) = args.id { builder.add_id(x); }
+ builder.add_count(args.count);
+ builder.finish()
+ }
+
+ pub fn unpack(&self) -> StatT {
+ let id = self.id().map(|x| {
+ x.to_string()
+ });
+ let val = self.val();
+ let count = self.count();
+ StatT {
+ id,
+ val,
+ count,
+ }
+ }
+
+ #[inline]
+ pub fn id(&self) -> Option<&'a str> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<&str>>(Stat::VT_ID, None)
+ }
+ #[inline]
+ pub fn val(&self) -> i64 {
+ self._tab.get::<i64>(Stat::VT_VAL, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn count(&self) -> u16 {
+ self._tab.get::<u16>(Stat::VT_COUNT, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn key_compare_less_than(&self, o: &Stat) -> bool {
+ self.count() < o.count()
+ }
+
+ #[inline]
+ pub fn key_compare_with_value(&self, val: u16) -> ::std::cmp::Ordering {
+ let key = self.count();
+ key.cmp(&val)
+ }
+}
+
+impl flatbuffers::Verifiable for Stat<'_> {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ v.visit_table(pos)?
+ .visit_field::<flatbuffers::ForwardsUOffset<&str>>("id", Self::VT_ID, false)?
+ .visit_field::<i64>("val", Self::VT_VAL, false)?
+ .visit_field::<u16>("count", Self::VT_COUNT, false)?
+ .finish();
+ Ok(())
+ }
+}
+pub struct StatArgs<'a> {
+ pub id: Option<flatbuffers::WIPOffset<&'a str>>,
+ pub val: i64,
+ pub count: u16,
+}
+impl<'a> Default for StatArgs<'a> {
+ #[inline]
+ fn default() -> Self {
+ StatArgs {
+ id: None,
+ val: 0,
+ count: 0,
+ }
+ }
+}
+
+impl Serialize for Stat<'_> {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: Serializer,
+ {
+ let mut s = serializer.serialize_struct("Stat", 3)?;
+ if let Some(f) = self.id() {
+ s.serialize_field("id", &f)?;
+ } else {
+ s.skip_field("id")?;
+ }
+ s.serialize_field("val", &self.val())?;
+ s.serialize_field("count", &self.count())?;
+ s.end()
+ }
+}
+
+pub struct StatBuilder<'a: 'b, 'b> {
+ fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
+ start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
+}
+impl<'a: 'b, 'b> StatBuilder<'a, 'b> {
+ #[inline]
+ pub fn add_id(&mut self, id: flatbuffers::WIPOffset<&'b str>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Stat::VT_ID, id);
+ }
+ #[inline]
+ pub fn add_val(&mut self, val: i64) {
+ self.fbb_.push_slot::<i64>(Stat::VT_VAL, val, 0);
+ }
+ #[inline]
+ pub fn add_count(&mut self, count: u16) {
+ self.fbb_.push_slot::<u16>(Stat::VT_COUNT, count, 0);
+ }
+ #[inline]
+ pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> StatBuilder<'a, 'b> {
+ let start = _fbb.start_table();
+ StatBuilder {
+ fbb_: _fbb,
+ start_: start,
+ }
+ }
+ #[inline]
+ pub fn finish(self) -> flatbuffers::WIPOffset<Stat<'a>> {
+ let o = self.fbb_.end_table(self.start_);
+ flatbuffers::WIPOffset::new(o.value())
+ }
+}
+
+impl std::fmt::Debug for Stat<'_> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let mut ds = f.debug_struct("Stat");
+ ds.field("id", &self.id());
+ ds.field("val", &self.val());
+ ds.field("count", &self.count());
+ ds.finish()
+ }
+}
+#[non_exhaustive]
+#[derive(Debug, Clone, PartialEq)]
+pub struct StatT {
+ pub id: Option<String>,
+ pub val: i64,
+ pub count: u16,
+}
+impl Default for StatT {
+ fn default() -> Self {
+ Self {
+ id: None,
+ val: 0,
+ count: 0,
+ }
+ }
+}
+impl StatT {
+ pub fn pack<'b>(
+ &self,
+ _fbb: &mut flatbuffers::FlatBufferBuilder<'b>
+ ) -> flatbuffers::WIPOffset<Stat<'b>> {
+ let id = self.id.as_ref().map(|x|{
+ _fbb.create_string(x)
+ });
+ let val = self.val;
+ let count = self.count;
+ Stat::create(_fbb, &StatArgs{
+ id,
+ val,
+ count,
+ })
+ }
+}
diff --git a/tests/monster_test_serialize/my_game/example/struct_of_structs_generated.rs b/tests/monster_test_serialize/my_game/example/struct_of_structs_generated.rs
new file mode 100644
index 0000000..75b8865
--- /dev/null
+++ b/tests/monster_test_serialize/my_game/example/struct_of_structs_generated.rs
@@ -0,0 +1,158 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+extern crate serde;
+use self::serde::ser::{Serialize, Serializer, SerializeStruct};
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+// struct StructOfStructs, aligned to 4
+#[repr(transparent)]
+#[derive(Clone, Copy, PartialEq)]
+pub struct StructOfStructs(pub [u8; 20]);
+impl Default for StructOfStructs {
+ fn default() -> Self {
+ Self([0; 20])
+ }
+}
+impl std::fmt::Debug for StructOfStructs {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ f.debug_struct("StructOfStructs")
+ .field("a", &self.a())
+ .field("b", &self.b())
+ .field("c", &self.c())
+ .finish()
+ }
+}
+
+impl flatbuffers::SimpleToVerifyInSlice for StructOfStructs {}
+impl flatbuffers::SafeSliceAccess for StructOfStructs {}
+impl<'a> flatbuffers::Follow<'a> for StructOfStructs {
+ type Inner = &'a StructOfStructs;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ <&'a StructOfStructs>::follow(buf, loc)
+ }
+}
+impl<'a> flatbuffers::Follow<'a> for &'a StructOfStructs {
+ type Inner = &'a StructOfStructs;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ flatbuffers::follow_cast_ref::<StructOfStructs>(buf, loc)
+ }
+}
+impl<'b> flatbuffers::Push for StructOfStructs {
+ type Output = StructOfStructs;
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ let src = unsafe {
+ ::std::slice::from_raw_parts(self as *const StructOfStructs as *const u8, Self::size())
+ };
+ dst.copy_from_slice(src);
+ }
+}
+impl<'b> flatbuffers::Push for &'b StructOfStructs {
+ type Output = StructOfStructs;
+
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ let src = unsafe {
+ ::std::slice::from_raw_parts(*self as *const StructOfStructs as *const u8, Self::size())
+ };
+ dst.copy_from_slice(src);
+ }
+}
+
+impl<'a> flatbuffers::Verifiable for StructOfStructs {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ v.in_buffer::<Self>(pos)
+ }
+}
+
+impl Serialize for StructOfStructs {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: Serializer,
+ {
+ let mut s = serializer.serialize_struct("StructOfStructs", 3)?;
+ s.serialize_field("a", &self.a())?;
+ s.serialize_field("b", &self.b())?;
+ s.serialize_field("c", &self.c())?;
+ s.end()
+ }
+}
+
+impl<'a> StructOfStructs {
+ #[allow(clippy::too_many_arguments)]
+ pub fn new(
+ a: &Ability,
+ b: &Test,
+ c: &Ability,
+ ) -> Self {
+ let mut s = Self([0; 20]);
+ s.set_a(a);
+ s.set_b(b);
+ s.set_c(c);
+ s
+ }
+
+ pub const fn get_fully_qualified_name() -> &'static str {
+ "MyGame.Example.StructOfStructs"
+ }
+
+ pub fn a(&self) -> &Ability {
+ unsafe { &*(self.0[0..].as_ptr() as *const Ability) }
+ }
+
+ #[allow(clippy::identity_op)]
+ pub fn set_a(&mut self, x: &Ability) {
+ self.0[0..0 + 8].copy_from_slice(&x.0)
+ }
+
+ pub fn b(&self) -> &Test {
+ unsafe { &*(self.0[8..].as_ptr() as *const Test) }
+ }
+
+ #[allow(clippy::identity_op)]
+ pub fn set_b(&mut self, x: &Test) {
+ self.0[8..8 + 4].copy_from_slice(&x.0)
+ }
+
+ pub fn c(&self) -> &Ability {
+ unsafe { &*(self.0[12..].as_ptr() as *const Ability) }
+ }
+
+ #[allow(clippy::identity_op)]
+ pub fn set_c(&mut self, x: &Ability) {
+ self.0[12..12 + 8].copy_from_slice(&x.0)
+ }
+
+ pub fn unpack(&self) -> StructOfStructsT {
+ StructOfStructsT {
+ a: self.a().unpack(),
+ b: self.b().unpack(),
+ c: self.c().unpack(),
+ }
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Default)]
+pub struct StructOfStructsT {
+ pub a: AbilityT,
+ pub b: TestT,
+ pub c: AbilityT,
+}
+impl StructOfStructsT {
+ pub fn pack(&self) -> StructOfStructs {
+ StructOfStructs::new(
+ &self.a.pack(),
+ &self.b.pack(),
+ &self.c.pack(),
+ )
+ }
+}
+
diff --git a/tests/monster_test_serialize/my_game/example/test_generated.rs b/tests/monster_test_serialize/my_game/example/test_generated.rs
new file mode 100644
index 0000000..56493ba
--- /dev/null
+++ b/tests/monster_test_serialize/my_game/example/test_generated.rs
@@ -0,0 +1,170 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+extern crate serde;
+use self::serde::ser::{Serialize, Serializer, SerializeStruct};
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+// struct Test, aligned to 2
+#[repr(transparent)]
+#[derive(Clone, Copy, PartialEq)]
+pub struct Test(pub [u8; 4]);
+impl Default for Test {
+ fn default() -> Self {
+ Self([0; 4])
+ }
+}
+impl std::fmt::Debug for Test {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ f.debug_struct("Test")
+ .field("a", &self.a())
+ .field("b", &self.b())
+ .finish()
+ }
+}
+
+impl flatbuffers::SimpleToVerifyInSlice for Test {}
+impl flatbuffers::SafeSliceAccess for Test {}
+impl<'a> flatbuffers::Follow<'a> for Test {
+ type Inner = &'a Test;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ <&'a Test>::follow(buf, loc)
+ }
+}
+impl<'a> flatbuffers::Follow<'a> for &'a Test {
+ type Inner = &'a Test;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ flatbuffers::follow_cast_ref::<Test>(buf, loc)
+ }
+}
+impl<'b> flatbuffers::Push for Test {
+ type Output = Test;
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ let src = unsafe {
+ ::std::slice::from_raw_parts(self as *const Test as *const u8, Self::size())
+ };
+ dst.copy_from_slice(src);
+ }
+}
+impl<'b> flatbuffers::Push for &'b Test {
+ type Output = Test;
+
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ let src = unsafe {
+ ::std::slice::from_raw_parts(*self as *const Test as *const u8, Self::size())
+ };
+ dst.copy_from_slice(src);
+ }
+}
+
+impl<'a> flatbuffers::Verifiable for Test {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ v.in_buffer::<Self>(pos)
+ }
+}
+
+impl Serialize for Test {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: Serializer,
+ {
+ let mut s = serializer.serialize_struct("Test", 2)?;
+ s.serialize_field("a", &self.a())?;
+ s.serialize_field("b", &self.b())?;
+ s.end()
+ }
+}
+
+impl<'a> Test {
+ #[allow(clippy::too_many_arguments)]
+ pub fn new(
+ a: i16,
+ b: i8,
+ ) -> Self {
+ let mut s = Self([0; 4]);
+ s.set_a(a);
+ s.set_b(b);
+ s
+ }
+
+ pub const fn get_fully_qualified_name() -> &'static str {
+ "MyGame.Example.Test"
+ }
+
+ pub fn a(&self) -> i16 {
+ let mut mem = core::mem::MaybeUninit::<i16>::uninit();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ self.0[0..].as_ptr(),
+ mem.as_mut_ptr() as *mut u8,
+ core::mem::size_of::<i16>(),
+ );
+ mem.assume_init()
+ }.from_little_endian()
+ }
+
+ pub fn set_a(&mut self, x: i16) {
+ let x_le = x.to_little_endian();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ &x_le as *const i16 as *const u8,
+ self.0[0..].as_mut_ptr(),
+ core::mem::size_of::<i16>(),
+ );
+ }
+ }
+
+ pub fn b(&self) -> i8 {
+ let mut mem = core::mem::MaybeUninit::<i8>::uninit();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ self.0[2..].as_ptr(),
+ mem.as_mut_ptr() as *mut u8,
+ core::mem::size_of::<i8>(),
+ );
+ mem.assume_init()
+ }.from_little_endian()
+ }
+
+ pub fn set_b(&mut self, x: i8) {
+ let x_le = x.to_little_endian();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ &x_le as *const i8 as *const u8,
+ self.0[2..].as_mut_ptr(),
+ core::mem::size_of::<i8>(),
+ );
+ }
+ }
+
+ pub fn unpack(&self) -> TestT {
+ TestT {
+ a: self.a(),
+ b: self.b(),
+ }
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Default)]
+pub struct TestT {
+ pub a: i16,
+ pub b: i8,
+}
+impl TestT {
+ pub fn pack(&self) -> Test {
+ Test::new(
+ self.a,
+ self.b,
+ )
+ }
+}
+
diff --git a/tests/monster_test_serialize/my_game/example/test_simple_table_with_enum_generated.rs b/tests/monster_test_serialize/my_game/example/test_simple_table_with_enum_generated.rs
new file mode 100644
index 0000000..cd64311
--- /dev/null
+++ b/tests/monster_test_serialize/my_game/example/test_simple_table_with_enum_generated.rs
@@ -0,0 +1,146 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+extern crate serde;
+use self::serde::ser::{Serialize, Serializer, SerializeStruct};
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+pub enum TestSimpleTableWithEnumOffset {}
+#[derive(Copy, Clone, PartialEq)]
+
+pub struct TestSimpleTableWithEnum<'a> {
+ pub _tab: flatbuffers::Table<'a>,
+}
+
+impl<'a> flatbuffers::Follow<'a> for TestSimpleTableWithEnum<'a> {
+ type Inner = TestSimpleTableWithEnum<'a>;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ Self { _tab: flatbuffers::Table { buf, loc } }
+ }
+}
+
+impl<'a> TestSimpleTableWithEnum<'a> {
+ pub const VT_COLOR: flatbuffers::VOffsetT = 4;
+
+ pub const fn get_fully_qualified_name() -> &'static str {
+ "MyGame.Example.TestSimpleTableWithEnum"
+ }
+
+ #[inline]
+ pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
+ TestSimpleTableWithEnum { _tab: table }
+ }
+ #[allow(unused_mut)]
+ pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
+ _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
+ args: &'args TestSimpleTableWithEnumArgs
+ ) -> flatbuffers::WIPOffset<TestSimpleTableWithEnum<'bldr>> {
+ let mut builder = TestSimpleTableWithEnumBuilder::new(_fbb);
+ builder.add_color(args.color);
+ builder.finish()
+ }
+
+ pub fn unpack(&self) -> TestSimpleTableWithEnumT {
+ let color = self.color();
+ TestSimpleTableWithEnumT {
+ color,
+ }
+ }
+
+ #[inline]
+ pub fn color(&self) -> Color {
+ self._tab.get::<Color>(TestSimpleTableWithEnum::VT_COLOR, Some(Color::Green)).unwrap()
+ }
+}
+
+impl flatbuffers::Verifiable for TestSimpleTableWithEnum<'_> {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ v.visit_table(pos)?
+ .visit_field::<Color>("color", Self::VT_COLOR, false)?
+ .finish();
+ Ok(())
+ }
+}
+pub struct TestSimpleTableWithEnumArgs {
+ pub color: Color,
+}
+impl<'a> Default for TestSimpleTableWithEnumArgs {
+ #[inline]
+ fn default() -> Self {
+ TestSimpleTableWithEnumArgs {
+ color: Color::Green,
+ }
+ }
+}
+
+impl Serialize for TestSimpleTableWithEnum<'_> {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: Serializer,
+ {
+ let mut s = serializer.serialize_struct("TestSimpleTableWithEnum", 1)?;
+ s.serialize_field("color", &self.color())?;
+ s.end()
+ }
+}
+
+pub struct TestSimpleTableWithEnumBuilder<'a: 'b, 'b> {
+ fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
+ start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
+}
+impl<'a: 'b, 'b> TestSimpleTableWithEnumBuilder<'a, 'b> {
+ #[inline]
+ pub fn add_color(&mut self, color: Color) {
+ self.fbb_.push_slot::<Color>(TestSimpleTableWithEnum::VT_COLOR, color, Color::Green);
+ }
+ #[inline]
+ pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> TestSimpleTableWithEnumBuilder<'a, 'b> {
+ let start = _fbb.start_table();
+ TestSimpleTableWithEnumBuilder {
+ fbb_: _fbb,
+ start_: start,
+ }
+ }
+ #[inline]
+ pub fn finish(self) -> flatbuffers::WIPOffset<TestSimpleTableWithEnum<'a>> {
+ let o = self.fbb_.end_table(self.start_);
+ flatbuffers::WIPOffset::new(o.value())
+ }
+}
+
+impl std::fmt::Debug for TestSimpleTableWithEnum<'_> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let mut ds = f.debug_struct("TestSimpleTableWithEnum");
+ ds.field("color", &self.color());
+ ds.finish()
+ }
+}
+#[non_exhaustive]
+#[derive(Debug, Clone, PartialEq)]
+pub struct TestSimpleTableWithEnumT {
+ pub color: Color,
+}
+impl Default for TestSimpleTableWithEnumT {
+ fn default() -> Self {
+ Self {
+ color: Color::Green,
+ }
+ }
+}
+impl TestSimpleTableWithEnumT {
+ pub fn pack<'b>(
+ &self,
+ _fbb: &mut flatbuffers::FlatBufferBuilder<'b>
+ ) -> flatbuffers::WIPOffset<TestSimpleTableWithEnum<'b>> {
+ let color = self.color;
+ TestSimpleTableWithEnum::create(_fbb, &TestSimpleTableWithEnumArgs{
+ color,
+ })
+ }
+}
diff --git a/tests/monster_test_serialize/my_game/example/type_aliases_generated.rs b/tests/monster_test_serialize/my_game/example/type_aliases_generated.rs
new file mode 100644
index 0000000..44d1198
--- /dev/null
+++ b/tests/monster_test_serialize/my_game/example/type_aliases_generated.rs
@@ -0,0 +1,393 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+extern crate serde;
+use self::serde::ser::{Serialize, Serializer, SerializeStruct};
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+pub enum TypeAliasesOffset {}
+#[derive(Copy, Clone, PartialEq)]
+
+pub struct TypeAliases<'a> {
+ pub _tab: flatbuffers::Table<'a>,
+}
+
+impl<'a> flatbuffers::Follow<'a> for TypeAliases<'a> {
+ type Inner = TypeAliases<'a>;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ Self { _tab: flatbuffers::Table { buf, loc } }
+ }
+}
+
+impl<'a> TypeAliases<'a> {
+ pub const VT_I8_: flatbuffers::VOffsetT = 4;
+ pub const VT_U8_: flatbuffers::VOffsetT = 6;
+ pub const VT_I16_: flatbuffers::VOffsetT = 8;
+ pub const VT_U16_: flatbuffers::VOffsetT = 10;
+ pub const VT_I32_: flatbuffers::VOffsetT = 12;
+ pub const VT_U32_: flatbuffers::VOffsetT = 14;
+ pub const VT_I64_: flatbuffers::VOffsetT = 16;
+ pub const VT_U64_: flatbuffers::VOffsetT = 18;
+ pub const VT_F32_: flatbuffers::VOffsetT = 20;
+ pub const VT_F64_: flatbuffers::VOffsetT = 22;
+ pub const VT_V8: flatbuffers::VOffsetT = 24;
+ pub const VT_VF64: flatbuffers::VOffsetT = 26;
+
+ pub const fn get_fully_qualified_name() -> &'static str {
+ "MyGame.Example.TypeAliases"
+ }
+
+ #[inline]
+ pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
+ TypeAliases { _tab: table }
+ }
+ #[allow(unused_mut)]
+ pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
+ _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
+ args: &'args TypeAliasesArgs<'args>
+ ) -> flatbuffers::WIPOffset<TypeAliases<'bldr>> {
+ let mut builder = TypeAliasesBuilder::new(_fbb);
+ builder.add_f64_(args.f64_);
+ builder.add_u64_(args.u64_);
+ builder.add_i64_(args.i64_);
+ if let Some(x) = args.vf64 { builder.add_vf64(x); }
+ if let Some(x) = args.v8 { builder.add_v8(x); }
+ builder.add_f32_(args.f32_);
+ builder.add_u32_(args.u32_);
+ builder.add_i32_(args.i32_);
+ builder.add_u16_(args.u16_);
+ builder.add_i16_(args.i16_);
+ builder.add_u8_(args.u8_);
+ builder.add_i8_(args.i8_);
+ builder.finish()
+ }
+
+ pub fn unpack(&self) -> TypeAliasesT {
+ let i8_ = self.i8_();
+ let u8_ = self.u8_();
+ let i16_ = self.i16_();
+ let u16_ = self.u16_();
+ let i32_ = self.i32_();
+ let u32_ = self.u32_();
+ let i64_ = self.i64_();
+ let u64_ = self.u64_();
+ let f32_ = self.f32_();
+ let f64_ = self.f64_();
+ let v8 = self.v8().map(|x| {
+ x.to_vec()
+ });
+ let vf64 = self.vf64().map(|x| {
+ x.into_iter().collect()
+ });
+ TypeAliasesT {
+ i8_,
+ u8_,
+ i16_,
+ u16_,
+ i32_,
+ u32_,
+ i64_,
+ u64_,
+ f32_,
+ f64_,
+ v8,
+ vf64,
+ }
+ }
+
+ #[inline]
+ pub fn i8_(&self) -> i8 {
+ self._tab.get::<i8>(TypeAliases::VT_I8_, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn u8_(&self) -> u8 {
+ self._tab.get::<u8>(TypeAliases::VT_U8_, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn i16_(&self) -> i16 {
+ self._tab.get::<i16>(TypeAliases::VT_I16_, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn u16_(&self) -> u16 {
+ self._tab.get::<u16>(TypeAliases::VT_U16_, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn i32_(&self) -> i32 {
+ self._tab.get::<i32>(TypeAliases::VT_I32_, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn u32_(&self) -> u32 {
+ self._tab.get::<u32>(TypeAliases::VT_U32_, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn i64_(&self) -> i64 {
+ self._tab.get::<i64>(TypeAliases::VT_I64_, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn u64_(&self) -> u64 {
+ self._tab.get::<u64>(TypeAliases::VT_U64_, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn f32_(&self) -> f32 {
+ self._tab.get::<f32>(TypeAliases::VT_F32_, Some(0.0)).unwrap()
+ }
+ #[inline]
+ pub fn f64_(&self) -> f64 {
+ self._tab.get::<f64>(TypeAliases::VT_F64_, Some(0.0)).unwrap()
+ }
+ #[inline]
+ pub fn v8(&self) -> Option<&'a [i8]> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, i8>>>(TypeAliases::VT_V8, None).map(|v| v.safe_slice())
+ }
+ #[inline]
+ pub fn vf64(&self) -> Option<flatbuffers::Vector<'a, f64>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, f64>>>(TypeAliases::VT_VF64, None)
+ }
+}
+
+impl flatbuffers::Verifiable for TypeAliases<'_> {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ v.visit_table(pos)?
+ .visit_field::<i8>("i8_", Self::VT_I8_, false)?
+ .visit_field::<u8>("u8_", Self::VT_U8_, false)?
+ .visit_field::<i16>("i16_", Self::VT_I16_, false)?
+ .visit_field::<u16>("u16_", Self::VT_U16_, false)?
+ .visit_field::<i32>("i32_", Self::VT_I32_, false)?
+ .visit_field::<u32>("u32_", Self::VT_U32_, false)?
+ .visit_field::<i64>("i64_", Self::VT_I64_, false)?
+ .visit_field::<u64>("u64_", Self::VT_U64_, false)?
+ .visit_field::<f32>("f32_", Self::VT_F32_, false)?
+ .visit_field::<f64>("f64_", Self::VT_F64_, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, i8>>>("v8", Self::VT_V8, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, f64>>>("vf64", Self::VT_VF64, false)?
+ .finish();
+ Ok(())
+ }
+}
+pub struct TypeAliasesArgs<'a> {
+ pub i8_: i8,
+ pub u8_: u8,
+ pub i16_: i16,
+ pub u16_: u16,
+ pub i32_: i32,
+ pub u32_: u32,
+ pub i64_: i64,
+ pub u64_: u64,
+ pub f32_: f32,
+ pub f64_: f64,
+ pub v8: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, i8>>>,
+ pub vf64: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, f64>>>,
+}
+impl<'a> Default for TypeAliasesArgs<'a> {
+ #[inline]
+ fn default() -> Self {
+ TypeAliasesArgs {
+ i8_: 0,
+ u8_: 0,
+ i16_: 0,
+ u16_: 0,
+ i32_: 0,
+ u32_: 0,
+ i64_: 0,
+ u64_: 0,
+ f32_: 0.0,
+ f64_: 0.0,
+ v8: None,
+ vf64: None,
+ }
+ }
+}
+
+impl Serialize for TypeAliases<'_> {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: Serializer,
+ {
+ let mut s = serializer.serialize_struct("TypeAliases", 12)?;
+ s.serialize_field("i8_", &self.i8_())?;
+ s.serialize_field("u8_", &self.u8_())?;
+ s.serialize_field("i16_", &self.i16_())?;
+ s.serialize_field("u16_", &self.u16_())?;
+ s.serialize_field("i32_", &self.i32_())?;
+ s.serialize_field("u32_", &self.u32_())?;
+ s.serialize_field("i64_", &self.i64_())?;
+ s.serialize_field("u64_", &self.u64_())?;
+ s.serialize_field("f32_", &self.f32_())?;
+ s.serialize_field("f64_", &self.f64_())?;
+ if let Some(f) = self.v8() {
+ s.serialize_field("v8", &f)?;
+ } else {
+ s.skip_field("v8")?;
+ }
+ if let Some(f) = self.vf64() {
+ s.serialize_field("vf64", &f)?;
+ } else {
+ s.skip_field("vf64")?;
+ }
+ s.end()
+ }
+}
+
+pub struct TypeAliasesBuilder<'a: 'b, 'b> {
+ fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
+ start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
+}
+impl<'a: 'b, 'b> TypeAliasesBuilder<'a, 'b> {
+ #[inline]
+ pub fn add_i8_(&mut self, i8_: i8) {
+ self.fbb_.push_slot::<i8>(TypeAliases::VT_I8_, i8_, 0);
+ }
+ #[inline]
+ pub fn add_u8_(&mut self, u8_: u8) {
+ self.fbb_.push_slot::<u8>(TypeAliases::VT_U8_, u8_, 0);
+ }
+ #[inline]
+ pub fn add_i16_(&mut self, i16_: i16) {
+ self.fbb_.push_slot::<i16>(TypeAliases::VT_I16_, i16_, 0);
+ }
+ #[inline]
+ pub fn add_u16_(&mut self, u16_: u16) {
+ self.fbb_.push_slot::<u16>(TypeAliases::VT_U16_, u16_, 0);
+ }
+ #[inline]
+ pub fn add_i32_(&mut self, i32_: i32) {
+ self.fbb_.push_slot::<i32>(TypeAliases::VT_I32_, i32_, 0);
+ }
+ #[inline]
+ pub fn add_u32_(&mut self, u32_: u32) {
+ self.fbb_.push_slot::<u32>(TypeAliases::VT_U32_, u32_, 0);
+ }
+ #[inline]
+ pub fn add_i64_(&mut self, i64_: i64) {
+ self.fbb_.push_slot::<i64>(TypeAliases::VT_I64_, i64_, 0);
+ }
+ #[inline]
+ pub fn add_u64_(&mut self, u64_: u64) {
+ self.fbb_.push_slot::<u64>(TypeAliases::VT_U64_, u64_, 0);
+ }
+ #[inline]
+ pub fn add_f32_(&mut self, f32_: f32) {
+ self.fbb_.push_slot::<f32>(TypeAliases::VT_F32_, f32_, 0.0);
+ }
+ #[inline]
+ pub fn add_f64_(&mut self, f64_: f64) {
+ self.fbb_.push_slot::<f64>(TypeAliases::VT_F64_, f64_, 0.0);
+ }
+ #[inline]
+ pub fn add_v8(&mut self, v8: flatbuffers::WIPOffset<flatbuffers::Vector<'b , i8>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(TypeAliases::VT_V8, v8);
+ }
+ #[inline]
+ pub fn add_vf64(&mut self, vf64: flatbuffers::WIPOffset<flatbuffers::Vector<'b , f64>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(TypeAliases::VT_VF64, vf64);
+ }
+ #[inline]
+ pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> TypeAliasesBuilder<'a, 'b> {
+ let start = _fbb.start_table();
+ TypeAliasesBuilder {
+ fbb_: _fbb,
+ start_: start,
+ }
+ }
+ #[inline]
+ pub fn finish(self) -> flatbuffers::WIPOffset<TypeAliases<'a>> {
+ let o = self.fbb_.end_table(self.start_);
+ flatbuffers::WIPOffset::new(o.value())
+ }
+}
+
+impl std::fmt::Debug for TypeAliases<'_> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let mut ds = f.debug_struct("TypeAliases");
+ ds.field("i8_", &self.i8_());
+ ds.field("u8_", &self.u8_());
+ ds.field("i16_", &self.i16_());
+ ds.field("u16_", &self.u16_());
+ ds.field("i32_", &self.i32_());
+ ds.field("u32_", &self.u32_());
+ ds.field("i64_", &self.i64_());
+ ds.field("u64_", &self.u64_());
+ ds.field("f32_", &self.f32_());
+ ds.field("f64_", &self.f64_());
+ ds.field("v8", &self.v8());
+ ds.field("vf64", &self.vf64());
+ ds.finish()
+ }
+}
+#[non_exhaustive]
+#[derive(Debug, Clone, PartialEq)]
+pub struct TypeAliasesT {
+ pub i8_: i8,
+ pub u8_: u8,
+ pub i16_: i16,
+ pub u16_: u16,
+ pub i32_: i32,
+ pub u32_: u32,
+ pub i64_: i64,
+ pub u64_: u64,
+ pub f32_: f32,
+ pub f64_: f64,
+ pub v8: Option<Vec<i8>>,
+ pub vf64: Option<Vec<f64>>,
+}
+impl Default for TypeAliasesT {
+ fn default() -> Self {
+ Self {
+ i8_: 0,
+ u8_: 0,
+ i16_: 0,
+ u16_: 0,
+ i32_: 0,
+ u32_: 0,
+ i64_: 0,
+ u64_: 0,
+ f32_: 0.0,
+ f64_: 0.0,
+ v8: None,
+ vf64: None,
+ }
+ }
+}
+impl TypeAliasesT {
+ pub fn pack<'b>(
+ &self,
+ _fbb: &mut flatbuffers::FlatBufferBuilder<'b>
+ ) -> flatbuffers::WIPOffset<TypeAliases<'b>> {
+ let i8_ = self.i8_;
+ let u8_ = self.u8_;
+ let i16_ = self.i16_;
+ let u16_ = self.u16_;
+ let i32_ = self.i32_;
+ let u32_ = self.u32_;
+ let i64_ = self.i64_;
+ let u64_ = self.u64_;
+ let f32_ = self.f32_;
+ let f64_ = self.f64_;
+ let v8 = self.v8.as_ref().map(|x|{
+ _fbb.create_vector(x)
+ });
+ let vf64 = self.vf64.as_ref().map(|x|{
+ _fbb.create_vector(x)
+ });
+ TypeAliases::create(_fbb, &TypeAliasesArgs{
+ i8_,
+ u8_,
+ i16_,
+ u16_,
+ i32_,
+ u32_,
+ i64_,
+ u64_,
+ f32_,
+ f64_,
+ v8,
+ vf64,
+ })
+ }
+}
diff --git a/tests/monster_test_serialize/my_game/example/vec_3_generated.rs b/tests/monster_test_serialize/my_game/example/vec_3_generated.rs
new file mode 100644
index 0000000..f04d0e8
--- /dev/null
+++ b/tests/monster_test_serialize/my_game/example/vec_3_generated.rs
@@ -0,0 +1,276 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+extern crate serde;
+use self::serde::ser::{Serialize, Serializer, SerializeStruct};
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+// struct Vec3, aligned to 8
+#[repr(transparent)]
+#[derive(Clone, Copy, PartialEq)]
+pub struct Vec3(pub [u8; 32]);
+impl Default for Vec3 {
+ fn default() -> Self {
+ Self([0; 32])
+ }
+}
+impl std::fmt::Debug for Vec3 {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ f.debug_struct("Vec3")
+ .field("x", &self.x())
+ .field("y", &self.y())
+ .field("z", &self.z())
+ .field("test1", &self.test1())
+ .field("test2", &self.test2())
+ .field("test3", &self.test3())
+ .finish()
+ }
+}
+
+impl flatbuffers::SimpleToVerifyInSlice for Vec3 {}
+impl flatbuffers::SafeSliceAccess for Vec3 {}
+impl<'a> flatbuffers::Follow<'a> for Vec3 {
+ type Inner = &'a Vec3;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ <&'a Vec3>::follow(buf, loc)
+ }
+}
+impl<'a> flatbuffers::Follow<'a> for &'a Vec3 {
+ type Inner = &'a Vec3;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ flatbuffers::follow_cast_ref::<Vec3>(buf, loc)
+ }
+}
+impl<'b> flatbuffers::Push for Vec3 {
+ type Output = Vec3;
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ let src = unsafe {
+ ::std::slice::from_raw_parts(self as *const Vec3 as *const u8, Self::size())
+ };
+ dst.copy_from_slice(src);
+ }
+}
+impl<'b> flatbuffers::Push for &'b Vec3 {
+ type Output = Vec3;
+
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ let src = unsafe {
+ ::std::slice::from_raw_parts(*self as *const Vec3 as *const u8, Self::size())
+ };
+ dst.copy_from_slice(src);
+ }
+}
+
+impl<'a> flatbuffers::Verifiable for Vec3 {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ v.in_buffer::<Self>(pos)
+ }
+}
+
+impl Serialize for Vec3 {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: Serializer,
+ {
+ let mut s = serializer.serialize_struct("Vec3", 6)?;
+ s.serialize_field("x", &self.x())?;
+ s.serialize_field("y", &self.y())?;
+ s.serialize_field("z", &self.z())?;
+ s.serialize_field("test1", &self.test1())?;
+ s.serialize_field("test2", &self.test2())?;
+ s.serialize_field("test3", &self.test3())?;
+ s.end()
+ }
+}
+
+impl<'a> Vec3 {
+ #[allow(clippy::too_many_arguments)]
+ pub fn new(
+ x: f32,
+ y: f32,
+ z: f32,
+ test1: f64,
+ test2: Color,
+ test3: &Test,
+ ) -> Self {
+ let mut s = Self([0; 32]);
+ s.set_x(x);
+ s.set_y(y);
+ s.set_z(z);
+ s.set_test1(test1);
+ s.set_test2(test2);
+ s.set_test3(test3);
+ s
+ }
+
+ pub const fn get_fully_qualified_name() -> &'static str {
+ "MyGame.Example.Vec3"
+ }
+
+ pub fn x(&self) -> f32 {
+ let mut mem = core::mem::MaybeUninit::<f32>::uninit();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ self.0[0..].as_ptr(),
+ mem.as_mut_ptr() as *mut u8,
+ core::mem::size_of::<f32>(),
+ );
+ mem.assume_init()
+ }.from_little_endian()
+ }
+
+ pub fn set_x(&mut self, x: f32) {
+ let x_le = x.to_little_endian();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ &x_le as *const f32 as *const u8,
+ self.0[0..].as_mut_ptr(),
+ core::mem::size_of::<f32>(),
+ );
+ }
+ }
+
+ pub fn y(&self) -> f32 {
+ let mut mem = core::mem::MaybeUninit::<f32>::uninit();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ self.0[4..].as_ptr(),
+ mem.as_mut_ptr() as *mut u8,
+ core::mem::size_of::<f32>(),
+ );
+ mem.assume_init()
+ }.from_little_endian()
+ }
+
+ pub fn set_y(&mut self, x: f32) {
+ let x_le = x.to_little_endian();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ &x_le as *const f32 as *const u8,
+ self.0[4..].as_mut_ptr(),
+ core::mem::size_of::<f32>(),
+ );
+ }
+ }
+
+ pub fn z(&self) -> f32 {
+ let mut mem = core::mem::MaybeUninit::<f32>::uninit();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ self.0[8..].as_ptr(),
+ mem.as_mut_ptr() as *mut u8,
+ core::mem::size_of::<f32>(),
+ );
+ mem.assume_init()
+ }.from_little_endian()
+ }
+
+ pub fn set_z(&mut self, x: f32) {
+ let x_le = x.to_little_endian();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ &x_le as *const f32 as *const u8,
+ self.0[8..].as_mut_ptr(),
+ core::mem::size_of::<f32>(),
+ );
+ }
+ }
+
+ pub fn test1(&self) -> f64 {
+ let mut mem = core::mem::MaybeUninit::<f64>::uninit();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ self.0[16..].as_ptr(),
+ mem.as_mut_ptr() as *mut u8,
+ core::mem::size_of::<f64>(),
+ );
+ mem.assume_init()
+ }.from_little_endian()
+ }
+
+ pub fn set_test1(&mut self, x: f64) {
+ let x_le = x.to_little_endian();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ &x_le as *const f64 as *const u8,
+ self.0[16..].as_mut_ptr(),
+ core::mem::size_of::<f64>(),
+ );
+ }
+ }
+
+ pub fn test2(&self) -> Color {
+ let mut mem = core::mem::MaybeUninit::<Color>::uninit();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ self.0[24..].as_ptr(),
+ mem.as_mut_ptr() as *mut u8,
+ core::mem::size_of::<Color>(),
+ );
+ mem.assume_init()
+ }.from_little_endian()
+ }
+
+ pub fn set_test2(&mut self, x: Color) {
+ let x_le = x.to_little_endian();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ &x_le as *const Color as *const u8,
+ self.0[24..].as_mut_ptr(),
+ core::mem::size_of::<Color>(),
+ );
+ }
+ }
+
+ pub fn test3(&self) -> &Test {
+ unsafe { &*(self.0[26..].as_ptr() as *const Test) }
+ }
+
+ #[allow(clippy::identity_op)]
+ pub fn set_test3(&mut self, x: &Test) {
+ self.0[26..26 + 4].copy_from_slice(&x.0)
+ }
+
+ pub fn unpack(&self) -> Vec3T {
+ Vec3T {
+ x: self.x(),
+ y: self.y(),
+ z: self.z(),
+ test1: self.test1(),
+ test2: self.test2(),
+ test3: self.test3().unpack(),
+ }
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Default)]
+pub struct Vec3T {
+ pub x: f32,
+ pub y: f32,
+ pub z: f32,
+ pub test1: f64,
+ pub test2: Color,
+ pub test3: TestT,
+}
+impl Vec3T {
+ pub fn pack(&self) -> Vec3 {
+ Vec3::new(
+ self.x,
+ self.y,
+ self.z,
+ self.test1,
+ self.test2,
+ &self.test3.pack(),
+ )
+ }
+}
+
diff --git a/tests/monster_test_serialize/my_game/example_2/monster_generated.rs b/tests/monster_test_serialize/my_game/example_2/monster_generated.rs
new file mode 100644
index 0000000..7687c5e
--- /dev/null
+++ b/tests/monster_test_serialize/my_game/example_2/monster_generated.rs
@@ -0,0 +1,124 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+extern crate serde;
+use self::serde::ser::{Serialize, Serializer, SerializeStruct};
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+pub enum MonsterOffset {}
+#[derive(Copy, Clone, PartialEq)]
+
+pub struct Monster<'a> {
+ pub _tab: flatbuffers::Table<'a>,
+}
+
+impl<'a> flatbuffers::Follow<'a> for Monster<'a> {
+ type Inner = Monster<'a>;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ Self { _tab: flatbuffers::Table { buf, loc } }
+ }
+}
+
+impl<'a> Monster<'a> {
+
+ pub const fn get_fully_qualified_name() -> &'static str {
+ "MyGame.Example2.Monster"
+ }
+
+ #[inline]
+ pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
+ Monster { _tab: table }
+ }
+ #[allow(unused_mut)]
+ pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
+ _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
+ _args: &'args MonsterArgs
+ ) -> flatbuffers::WIPOffset<Monster<'bldr>> {
+ let mut builder = MonsterBuilder::new(_fbb);
+ builder.finish()
+ }
+
+ pub fn unpack(&self) -> MonsterT {
+ MonsterT {
+ }
+ }
+}
+
+impl flatbuffers::Verifiable for Monster<'_> {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ v.visit_table(pos)?
+ .finish();
+ Ok(())
+ }
+}
+pub struct MonsterArgs {
+}
+impl<'a> Default for MonsterArgs {
+ #[inline]
+ fn default() -> Self {
+ MonsterArgs {
+ }
+ }
+}
+
+impl Serialize for Monster<'_> {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: Serializer,
+ {
+ let s = serializer.serialize_struct("Monster", 0)?;
+ s.end()
+ }
+}
+
+pub struct MonsterBuilder<'a: 'b, 'b> {
+ fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
+ start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
+}
+impl<'a: 'b, 'b> MonsterBuilder<'a, 'b> {
+ #[inline]
+ pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> MonsterBuilder<'a, 'b> {
+ let start = _fbb.start_table();
+ MonsterBuilder {
+ fbb_: _fbb,
+ start_: start,
+ }
+ }
+ #[inline]
+ pub fn finish(self) -> flatbuffers::WIPOffset<Monster<'a>> {
+ let o = self.fbb_.end_table(self.start_);
+ flatbuffers::WIPOffset::new(o.value())
+ }
+}
+
+impl std::fmt::Debug for Monster<'_> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let mut ds = f.debug_struct("Monster");
+ ds.finish()
+ }
+}
+#[non_exhaustive]
+#[derive(Debug, Clone, PartialEq)]
+pub struct MonsterT {
+}
+impl Default for MonsterT {
+ fn default() -> Self {
+ Self {
+ }
+ }
+}
+impl MonsterT {
+ pub fn pack<'b>(
+ &self,
+ _fbb: &mut flatbuffers::FlatBufferBuilder<'b>
+ ) -> flatbuffers::WIPOffset<Monster<'b>> {
+ Monster::create(_fbb, &MonsterArgs{
+ })
+ }
+}
diff --git a/tests/monster_test_serialize/my_game/in_parent_namespace_generated.rs b/tests/monster_test_serialize/my_game/in_parent_namespace_generated.rs
new file mode 100644
index 0000000..b2b0a09
--- /dev/null
+++ b/tests/monster_test_serialize/my_game/in_parent_namespace_generated.rs
@@ -0,0 +1,124 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+extern crate serde;
+use self::serde::ser::{Serialize, Serializer, SerializeStruct};
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+pub enum InParentNamespaceOffset {}
+#[derive(Copy, Clone, PartialEq)]
+
+pub struct InParentNamespace<'a> {
+ pub _tab: flatbuffers::Table<'a>,
+}
+
+impl<'a> flatbuffers::Follow<'a> for InParentNamespace<'a> {
+ type Inner = InParentNamespace<'a>;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ Self { _tab: flatbuffers::Table { buf, loc } }
+ }
+}
+
+impl<'a> InParentNamespace<'a> {
+
+ pub const fn get_fully_qualified_name() -> &'static str {
+ "MyGame.InParentNamespace"
+ }
+
+ #[inline]
+ pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
+ InParentNamespace { _tab: table }
+ }
+ #[allow(unused_mut)]
+ pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
+ _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
+ _args: &'args InParentNamespaceArgs
+ ) -> flatbuffers::WIPOffset<InParentNamespace<'bldr>> {
+ let mut builder = InParentNamespaceBuilder::new(_fbb);
+ builder.finish()
+ }
+
+ pub fn unpack(&self) -> InParentNamespaceT {
+ InParentNamespaceT {
+ }
+ }
+}
+
+impl flatbuffers::Verifiable for InParentNamespace<'_> {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ v.visit_table(pos)?
+ .finish();
+ Ok(())
+ }
+}
+pub struct InParentNamespaceArgs {
+}
+impl<'a> Default for InParentNamespaceArgs {
+ #[inline]
+ fn default() -> Self {
+ InParentNamespaceArgs {
+ }
+ }
+}
+
+impl Serialize for InParentNamespace<'_> {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: Serializer,
+ {
+ let s = serializer.serialize_struct("InParentNamespace", 0)?;
+ s.end()
+ }
+}
+
+pub struct InParentNamespaceBuilder<'a: 'b, 'b> {
+ fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
+ start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
+}
+impl<'a: 'b, 'b> InParentNamespaceBuilder<'a, 'b> {
+ #[inline]
+ pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> InParentNamespaceBuilder<'a, 'b> {
+ let start = _fbb.start_table();
+ InParentNamespaceBuilder {
+ fbb_: _fbb,
+ start_: start,
+ }
+ }
+ #[inline]
+ pub fn finish(self) -> flatbuffers::WIPOffset<InParentNamespace<'a>> {
+ let o = self.fbb_.end_table(self.start_);
+ flatbuffers::WIPOffset::new(o.value())
+ }
+}
+
+impl std::fmt::Debug for InParentNamespace<'_> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let mut ds = f.debug_struct("InParentNamespace");
+ ds.finish()
+ }
+}
+#[non_exhaustive]
+#[derive(Debug, Clone, PartialEq)]
+pub struct InParentNamespaceT {
+}
+impl Default for InParentNamespaceT {
+ fn default() -> Self {
+ Self {
+ }
+ }
+}
+impl InParentNamespaceT {
+ pub fn pack<'b>(
+ &self,
+ _fbb: &mut flatbuffers::FlatBufferBuilder<'b>
+ ) -> flatbuffers::WIPOffset<InParentNamespace<'b>> {
+ InParentNamespace::create(_fbb, &InParentNamespaceArgs{
+ })
+ }
+}
diff --git a/tests/monster_test_serialize/my_game/other_name_space/from_include_generated.rs b/tests/monster_test_serialize/my_game/other_name_space/from_include_generated.rs
new file mode 100644
index 0000000..06a0fa8
--- /dev/null
+++ b/tests/monster_test_serialize/my_game/other_name_space/from_include_generated.rs
@@ -0,0 +1,100 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+extern crate serde;
+use self::serde::ser::{Serialize, Serializer, SerializeStruct};
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+pub const ENUM_MIN_FROM_INCLUDE: i64 = 0;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+pub const ENUM_MAX_FROM_INCLUDE: i64 = 0;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+#[allow(non_camel_case_types)]
+pub const ENUM_VALUES_FROM_INCLUDE: [FromInclude; 1] = [
+ FromInclude::IncludeVal,
+];
+
+#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
+#[repr(transparent)]
+pub struct FromInclude(pub i64);
+#[allow(non_upper_case_globals)]
+impl FromInclude {
+ pub const IncludeVal: Self = Self(0);
+
+ pub const ENUM_MIN: i64 = 0;
+ pub const ENUM_MAX: i64 = 0;
+ pub const ENUM_VALUES: &'static [Self] = &[
+ Self::IncludeVal,
+ ];
+ /// Returns the variant's name or "" if unknown.
+ pub fn variant_name(self) -> Option<&'static str> {
+ match self {
+ Self::IncludeVal => Some("IncludeVal"),
+ _ => None,
+ }
+ }
+}
+impl std::fmt::Debug for FromInclude {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ if let Some(name) = self.variant_name() {
+ f.write_str(name)
+ } else {
+ f.write_fmt(format_args!("<UNKNOWN {:?}>", self.0))
+ }
+ }
+}
+impl Serialize for FromInclude {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: Serializer,
+ {
+ serializer.serialize_unit_variant("FromInclude", self.0 as u32, self.variant_name().unwrap())
+ }
+}
+
+impl<'a> flatbuffers::Follow<'a> for FromInclude {
+ type Inner = Self;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ let b = unsafe {
+ flatbuffers::read_scalar_at::<i64>(buf, loc)
+ };
+ Self(b)
+ }
+}
+
+impl flatbuffers::Push for FromInclude {
+ type Output = FromInclude;
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ unsafe { flatbuffers::emplace_scalar::<i64>(dst, self.0); }
+ }
+}
+
+impl flatbuffers::EndianScalar for FromInclude {
+ #[inline]
+ fn to_little_endian(self) -> Self {
+ let b = i64::to_le(self.0);
+ Self(b)
+ }
+ #[inline]
+ #[allow(clippy::wrong_self_convention)]
+ fn from_little_endian(self) -> Self {
+ let b = i64::from_le(self.0);
+ Self(b)
+ }
+}
+
+impl<'a> flatbuffers::Verifiable for FromInclude {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ i64::run_verifier(v, pos)
+ }
+}
+
+impl flatbuffers::SimpleToVerifyInSlice for FromInclude {}
diff --git a/tests/monster_test_serialize/my_game/other_name_space/table_b_generated.rs b/tests/monster_test_serialize/my_game/other_name_space/table_b_generated.rs
new file mode 100644
index 0000000..f09e175
--- /dev/null
+++ b/tests/monster_test_serialize/my_game/other_name_space/table_b_generated.rs
@@ -0,0 +1,154 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+extern crate serde;
+use self::serde::ser::{Serialize, Serializer, SerializeStruct};
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+pub enum TableBOffset {}
+#[derive(Copy, Clone, PartialEq)]
+
+pub struct TableB<'a> {
+ pub _tab: flatbuffers::Table<'a>,
+}
+
+impl<'a> flatbuffers::Follow<'a> for TableB<'a> {
+ type Inner = TableB<'a>;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ Self { _tab: flatbuffers::Table { buf, loc } }
+ }
+}
+
+impl<'a> TableB<'a> {
+ pub const VT_A: flatbuffers::VOffsetT = 4;
+
+ pub const fn get_fully_qualified_name() -> &'static str {
+ "MyGame.OtherNameSpace.TableB"
+ }
+
+ #[inline]
+ pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
+ TableB { _tab: table }
+ }
+ #[allow(unused_mut)]
+ pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
+ _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
+ args: &'args TableBArgs<'args>
+ ) -> flatbuffers::WIPOffset<TableB<'bldr>> {
+ let mut builder = TableBBuilder::new(_fbb);
+ if let Some(x) = args.a { builder.add_a(x); }
+ builder.finish()
+ }
+
+ pub fn unpack(&self) -> TableBT {
+ let a = self.a().map(|x| {
+ Box::new(x.unpack())
+ });
+ TableBT {
+ a,
+ }
+ }
+
+ #[inline]
+ pub fn a(&self) -> Option<super::super::TableA<'a>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<super::super::TableA>>(TableB::VT_A, None)
+ }
+}
+
+impl flatbuffers::Verifiable for TableB<'_> {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ v.visit_table(pos)?
+ .visit_field::<flatbuffers::ForwardsUOffset<super::super::TableA>>("a", Self::VT_A, false)?
+ .finish();
+ Ok(())
+ }
+}
+pub struct TableBArgs<'a> {
+ pub a: Option<flatbuffers::WIPOffset<super::super::TableA<'a>>>,
+}
+impl<'a> Default for TableBArgs<'a> {
+ #[inline]
+ fn default() -> Self {
+ TableBArgs {
+ a: None,
+ }
+ }
+}
+
+impl Serialize for TableB<'_> {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: Serializer,
+ {
+ let mut s = serializer.serialize_struct("TableB", 1)?;
+ if let Some(f) = self.a() {
+ s.serialize_field("a", &f)?;
+ } else {
+ s.skip_field("a")?;
+ }
+ s.end()
+ }
+}
+
+pub struct TableBBuilder<'a: 'b, 'b> {
+ fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
+ start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
+}
+impl<'a: 'b, 'b> TableBBuilder<'a, 'b> {
+ #[inline]
+ pub fn add_a(&mut self, a: flatbuffers::WIPOffset<super::super::TableA<'b >>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<super::super::TableA>>(TableB::VT_A, a);
+ }
+ #[inline]
+ pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> TableBBuilder<'a, 'b> {
+ let start = _fbb.start_table();
+ TableBBuilder {
+ fbb_: _fbb,
+ start_: start,
+ }
+ }
+ #[inline]
+ pub fn finish(self) -> flatbuffers::WIPOffset<TableB<'a>> {
+ let o = self.fbb_.end_table(self.start_);
+ flatbuffers::WIPOffset::new(o.value())
+ }
+}
+
+impl std::fmt::Debug for TableB<'_> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let mut ds = f.debug_struct("TableB");
+ ds.field("a", &self.a());
+ ds.finish()
+ }
+}
+#[non_exhaustive]
+#[derive(Debug, Clone, PartialEq)]
+pub struct TableBT {
+ pub a: Option<Box<super::super::TableAT>>,
+}
+impl Default for TableBT {
+ fn default() -> Self {
+ Self {
+ a: None,
+ }
+ }
+}
+impl TableBT {
+ pub fn pack<'b>(
+ &self,
+ _fbb: &mut flatbuffers::FlatBufferBuilder<'b>
+ ) -> flatbuffers::WIPOffset<TableB<'b>> {
+ let a = self.a.as_ref().map(|x|{
+ x.pack(_fbb)
+ });
+ TableB::create(_fbb, &TableBArgs{
+ a,
+ })
+ }
+}
diff --git a/tests/monster_test_serialize/my_game/other_name_space/unused_generated.rs b/tests/monster_test_serialize/my_game/other_name_space/unused_generated.rs
new file mode 100644
index 0000000..7b91447
--- /dev/null
+++ b/tests/monster_test_serialize/my_game/other_name_space/unused_generated.rs
@@ -0,0 +1,140 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+extern crate serde;
+use self::serde::ser::{Serialize, Serializer, SerializeStruct};
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+// struct Unused, aligned to 4
+#[repr(transparent)]
+#[derive(Clone, Copy, PartialEq)]
+pub struct Unused(pub [u8; 4]);
+impl Default for Unused {
+ fn default() -> Self {
+ Self([0; 4])
+ }
+}
+impl std::fmt::Debug for Unused {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ f.debug_struct("Unused")
+ .field("a", &self.a())
+ .finish()
+ }
+}
+
+impl flatbuffers::SimpleToVerifyInSlice for Unused {}
+impl flatbuffers::SafeSliceAccess for Unused {}
+impl<'a> flatbuffers::Follow<'a> for Unused {
+ type Inner = &'a Unused;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ <&'a Unused>::follow(buf, loc)
+ }
+}
+impl<'a> flatbuffers::Follow<'a> for &'a Unused {
+ type Inner = &'a Unused;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ flatbuffers::follow_cast_ref::<Unused>(buf, loc)
+ }
+}
+impl<'b> flatbuffers::Push for Unused {
+ type Output = Unused;
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ let src = unsafe {
+ ::std::slice::from_raw_parts(self as *const Unused as *const u8, Self::size())
+ };
+ dst.copy_from_slice(src);
+ }
+}
+impl<'b> flatbuffers::Push for &'b Unused {
+ type Output = Unused;
+
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ let src = unsafe {
+ ::std::slice::from_raw_parts(*self as *const Unused as *const u8, Self::size())
+ };
+ dst.copy_from_slice(src);
+ }
+}
+
+impl<'a> flatbuffers::Verifiable for Unused {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ v.in_buffer::<Self>(pos)
+ }
+}
+
+impl Serialize for Unused {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: Serializer,
+ {
+ let mut s = serializer.serialize_struct("Unused", 1)?;
+ s.serialize_field("a", &self.a())?;
+ s.end()
+ }
+}
+
+impl<'a> Unused {
+ #[allow(clippy::too_many_arguments)]
+ pub fn new(
+ a: i32,
+ ) -> Self {
+ let mut s = Self([0; 4]);
+ s.set_a(a);
+ s
+ }
+
+ pub const fn get_fully_qualified_name() -> &'static str {
+ "MyGame.OtherNameSpace.Unused"
+ }
+
+ pub fn a(&self) -> i32 {
+ let mut mem = core::mem::MaybeUninit::<i32>::uninit();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ self.0[0..].as_ptr(),
+ mem.as_mut_ptr() as *mut u8,
+ core::mem::size_of::<i32>(),
+ );
+ mem.assume_init()
+ }.from_little_endian()
+ }
+
+ pub fn set_a(&mut self, x: i32) {
+ let x_le = x.to_little_endian();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ &x_le as *const i32 as *const u8,
+ self.0[0..].as_mut_ptr(),
+ core::mem::size_of::<i32>(),
+ );
+ }
+ }
+
+ pub fn unpack(&self) -> UnusedT {
+ UnusedT {
+ a: self.a(),
+ }
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Default)]
+pub struct UnusedT {
+ pub a: i32,
+}
+impl UnusedT {
+ pub fn pack(&self) -> Unused {
+ Unused::new(
+ self.a,
+ )
+ }
+}
+
diff --git a/tests/monster_test_serialize/table_a_generated.rs b/tests/monster_test_serialize/table_a_generated.rs
new file mode 100644
index 0000000..eb03f49
--- /dev/null
+++ b/tests/monster_test_serialize/table_a_generated.rs
@@ -0,0 +1,154 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+extern crate serde;
+use self::serde::ser::{Serialize, Serializer, SerializeStruct};
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+pub enum TableAOffset {}
+#[derive(Copy, Clone, PartialEq)]
+
+pub struct TableA<'a> {
+ pub _tab: flatbuffers::Table<'a>,
+}
+
+impl<'a> flatbuffers::Follow<'a> for TableA<'a> {
+ type Inner = TableA<'a>;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ Self { _tab: flatbuffers::Table { buf, loc } }
+ }
+}
+
+impl<'a> TableA<'a> {
+ pub const VT_B: flatbuffers::VOffsetT = 4;
+
+ pub const fn get_fully_qualified_name() -> &'static str {
+ "TableA"
+ }
+
+ #[inline]
+ pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
+ TableA { _tab: table }
+ }
+ #[allow(unused_mut)]
+ pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
+ _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
+ args: &'args TableAArgs<'args>
+ ) -> flatbuffers::WIPOffset<TableA<'bldr>> {
+ let mut builder = TableABuilder::new(_fbb);
+ if let Some(x) = args.b { builder.add_b(x); }
+ builder.finish()
+ }
+
+ pub fn unpack(&self) -> TableAT {
+ let b = self.b().map(|x| {
+ Box::new(x.unpack())
+ });
+ TableAT {
+ b,
+ }
+ }
+
+ #[inline]
+ pub fn b(&self) -> Option<my_game::other_name_space::TableB<'a>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<my_game::other_name_space::TableB>>(TableA::VT_B, None)
+ }
+}
+
+impl flatbuffers::Verifiable for TableA<'_> {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ v.visit_table(pos)?
+ .visit_field::<flatbuffers::ForwardsUOffset<my_game::other_name_space::TableB>>("b", Self::VT_B, false)?
+ .finish();
+ Ok(())
+ }
+}
+pub struct TableAArgs<'a> {
+ pub b: Option<flatbuffers::WIPOffset<my_game::other_name_space::TableB<'a>>>,
+}
+impl<'a> Default for TableAArgs<'a> {
+ #[inline]
+ fn default() -> Self {
+ TableAArgs {
+ b: None,
+ }
+ }
+}
+
+impl Serialize for TableA<'_> {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: Serializer,
+ {
+ let mut s = serializer.serialize_struct("TableA", 1)?;
+ if let Some(f) = self.b() {
+ s.serialize_field("b", &f)?;
+ } else {
+ s.skip_field("b")?;
+ }
+ s.end()
+ }
+}
+
+pub struct TableABuilder<'a: 'b, 'b> {
+ fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
+ start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
+}
+impl<'a: 'b, 'b> TableABuilder<'a, 'b> {
+ #[inline]
+ pub fn add_b(&mut self, b: flatbuffers::WIPOffset<my_game::other_name_space::TableB<'b >>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<my_game::other_name_space::TableB>>(TableA::VT_B, b);
+ }
+ #[inline]
+ pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> TableABuilder<'a, 'b> {
+ let start = _fbb.start_table();
+ TableABuilder {
+ fbb_: _fbb,
+ start_: start,
+ }
+ }
+ #[inline]
+ pub fn finish(self) -> flatbuffers::WIPOffset<TableA<'a>> {
+ let o = self.fbb_.end_table(self.start_);
+ flatbuffers::WIPOffset::new(o.value())
+ }
+}
+
+impl std::fmt::Debug for TableA<'_> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let mut ds = f.debug_struct("TableA");
+ ds.field("b", &self.b());
+ ds.finish()
+ }
+}
+#[non_exhaustive]
+#[derive(Debug, Clone, PartialEq)]
+pub struct TableAT {
+ pub b: Option<Box<my_game::other_name_space::TableBT>>,
+}
+impl Default for TableAT {
+ fn default() -> Self {
+ Self {
+ b: None,
+ }
+ }
+}
+impl TableAT {
+ pub fn pack<'b>(
+ &self,
+ _fbb: &mut flatbuffers::FlatBufferBuilder<'b>
+ ) -> flatbuffers::WIPOffset<TableA<'b>> {
+ let b = self.b.as_ref().map(|x|{
+ x.pack(_fbb)
+ });
+ TableA::create(_fbb, &TableAArgs{
+ b,
+ })
+ }
+}
diff --git a/tests/monsterdata_go_wire.mon.sp b/tests/monsterdata_go_wire.mon.sp
new file mode 100644
index 0000000..cf3019c
--- /dev/null
+++ b/tests/monsterdata_go_wire.mon.sp
Binary files differ
diff --git a/tests/monsterdata_test.json b/tests/monsterdata_test.json
index eb40080..411c055 100644
--- a/tests/monsterdata_test.json
+++ b/tests/monsterdata_test.json
@@ -20,16 +20,16 @@
4
],
vector_of_longs: [
- 1,
- 100,
- 10000,
- 1000000,
- 100000000
+ 1,
+ 100,
+ 10000,
+ 1000000,
+ 100000000
],
vector_of_doubles: [
- -1.7976931348623157e+308,
- 0,
- 1.7976931348623157e+308
+ -1.7976931348623157e+308,
+ 0,
+ 1.7976931348623157e+308
],
test_type: "Monster",
test: {
@@ -63,8 +63,10 @@
enemy: {
name: "Fred"
},
- testarrayofbools:[
- true, false, true
+ testarrayofbools: [
+ true,
+ false,
+ true
],
testbool: true,
testhashs32_fnv1: "This string is being hashed!",
@@ -75,4 +77,22 @@
testhashu32_fnv1a: "This string is being hashed!",
testhashs64_fnv1a: "This string is being hashed!",
testhashu64_fnv1a: "This string is being hashed!",
-}
+ testarrayofsortedstruct: [
+ {id: 5,distance: 12
+ },
+ {id: 1,distance: 21
+ },
+ {id: 0,distance: 45
+ }
+ ],
+ scalar_key_sorted_tables: [
+ {id: "hit",val: 10,count: 1
+ },
+ {id: "miss",val: 0,count: 0
+ }
+ ],
+ native_inline: {
+ a: 1,
+ b: 2
+ }
+}
\ No newline at end of file
diff --git a/tests/monsterdata_test.mon b/tests/monsterdata_test.mon
index ba6cf27..da0ed86 100644
--- a/tests/monsterdata_test.mon
+++ b/tests/monsterdata_test.mon
Binary files differ
diff --git a/tests/more_defaults.fbs b/tests/more_defaults.fbs
new file mode 100644
index 0000000..da4976a
--- /dev/null
+++ b/tests/more_defaults.fbs
@@ -0,0 +1,12 @@
+
+enum ABC: int { A, B, C }
+
+
+table MoreDefaults {
+ ints: [int] = [];
+ floats: [float] = [ ];
+ empty_string: string = "";
+ some_string: string = "some";
+ abcs: [ABC] = [];
+ bools: [bool] = [];
+}
diff --git a/tests/more_defaults/abc_generated.rs b/tests/more_defaults/abc_generated.rs
new file mode 100644
index 0000000..8622d9b
--- /dev/null
+++ b/tests/more_defaults/abc_generated.rs
@@ -0,0 +1,97 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+pub const ENUM_MIN_ABC: i32 = 0;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+pub const ENUM_MAX_ABC: i32 = 2;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+#[allow(non_camel_case_types)]
+pub const ENUM_VALUES_ABC: [ABC; 3] = [
+ ABC::A,
+ ABC::B,
+ ABC::C,
+];
+
+#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
+#[repr(transparent)]
+pub struct ABC(pub i32);
+#[allow(non_upper_case_globals)]
+impl ABC {
+ pub const A: Self = Self(0);
+ pub const B: Self = Self(1);
+ pub const C: Self = Self(2);
+
+ pub const ENUM_MIN: i32 = 0;
+ pub const ENUM_MAX: i32 = 2;
+ pub const ENUM_VALUES: &'static [Self] = &[
+ Self::A,
+ Self::B,
+ Self::C,
+ ];
+ /// Returns the variant's name or "" if unknown.
+ pub fn variant_name(self) -> Option<&'static str> {
+ match self {
+ Self::A => Some("A"),
+ Self::B => Some("B"),
+ Self::C => Some("C"),
+ _ => None,
+ }
+ }
+}
+impl std::fmt::Debug for ABC {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ if let Some(name) = self.variant_name() {
+ f.write_str(name)
+ } else {
+ f.write_fmt(format_args!("<UNKNOWN {:?}>", self.0))
+ }
+ }
+}
+impl<'a> flatbuffers::Follow<'a> for ABC {
+ type Inner = Self;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ let b = unsafe {
+ flatbuffers::read_scalar_at::<i32>(buf, loc)
+ };
+ Self(b)
+ }
+}
+
+impl flatbuffers::Push for ABC {
+ type Output = ABC;
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ unsafe { flatbuffers::emplace_scalar::<i32>(dst, self.0); }
+ }
+}
+
+impl flatbuffers::EndianScalar for ABC {
+ #[inline]
+ fn to_little_endian(self) -> Self {
+ let b = i32::to_le(self.0);
+ Self(b)
+ }
+ #[inline]
+ #[allow(clippy::wrong_self_convention)]
+ fn from_little_endian(self) -> Self {
+ let b = i32::from_le(self.0);
+ Self(b)
+ }
+}
+
+impl<'a> flatbuffers::Verifiable for ABC {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ i32::run_verifier(v, pos)
+ }
+}
+
+impl flatbuffers::SimpleToVerifyInSlice for ABC {}
diff --git a/tests/more_defaults/mod.rs b/tests/more_defaults/mod.rs
new file mode 100644
index 0000000..639f8ac
--- /dev/null
+++ b/tests/more_defaults/mod.rs
@@ -0,0 +1,5 @@
+// Automatically generated by the Flatbuffers compiler. Do not modify.
+mod abc_generated;
+pub use self::abc_generated::*;
+mod more_defaults_generated;
+pub use self::more_defaults_generated::*;
diff --git a/tests/more_defaults/more_defaults_generated.rs b/tests/more_defaults/more_defaults_generated.rs
new file mode 100644
index 0000000..0a88105
--- /dev/null
+++ b/tests/more_defaults/more_defaults_generated.rs
@@ -0,0 +1,269 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+pub enum MoreDefaultsOffset {}
+#[derive(Copy, Clone, PartialEq)]
+
+pub struct MoreDefaults<'a> {
+ pub _tab: flatbuffers::Table<'a>,
+}
+
+impl<'a> flatbuffers::Follow<'a> for MoreDefaults<'a> {
+ type Inner = MoreDefaults<'a>;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ Self { _tab: flatbuffers::Table { buf, loc } }
+ }
+}
+
+impl<'a> MoreDefaults<'a> {
+ pub const VT_INTS: flatbuffers::VOffsetT = 4;
+ pub const VT_FLOATS: flatbuffers::VOffsetT = 6;
+ pub const VT_EMPTY_STRING: flatbuffers::VOffsetT = 8;
+ pub const VT_SOME_STRING: flatbuffers::VOffsetT = 10;
+ pub const VT_ABCS: flatbuffers::VOffsetT = 12;
+ pub const VT_BOOLS: flatbuffers::VOffsetT = 14;
+
+ pub const fn get_fully_qualified_name() -> &'static str {
+ "MoreDefaults"
+ }
+
+ #[inline]
+ pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
+ MoreDefaults { _tab: table }
+ }
+ #[allow(unused_mut)]
+ pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
+ _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
+ args: &'args MoreDefaultsArgs<'args>
+ ) -> flatbuffers::WIPOffset<MoreDefaults<'bldr>> {
+ let mut builder = MoreDefaultsBuilder::new(_fbb);
+ if let Some(x) = args.bools { builder.add_bools(x); }
+ if let Some(x) = args.abcs { builder.add_abcs(x); }
+ if let Some(x) = args.some_string { builder.add_some_string(x); }
+ if let Some(x) = args.empty_string { builder.add_empty_string(x); }
+ if let Some(x) = args.floats { builder.add_floats(x); }
+ if let Some(x) = args.ints { builder.add_ints(x); }
+ builder.finish()
+ }
+
+ pub fn unpack(&self) -> MoreDefaultsT {
+ let ints = {
+ let x = self.ints();
+ x.into_iter().collect()
+ };
+ let floats = {
+ let x = self.floats();
+ x.into_iter().collect()
+ };
+ let empty_string = {
+ let x = self.empty_string();
+ x.to_string()
+ };
+ let some_string = {
+ let x = self.some_string();
+ x.to_string()
+ };
+ let abcs = {
+ let x = self.abcs();
+ x.into_iter().collect()
+ };
+ let bools = {
+ let x = self.bools();
+ x.to_vec()
+ };
+ MoreDefaultsT {
+ ints,
+ floats,
+ empty_string,
+ some_string,
+ abcs,
+ bools,
+ }
+ }
+
+ #[inline]
+ pub fn ints(&self) -> flatbuffers::Vector<'a, i32> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, i32>>>(MoreDefaults::VT_INTS, Some(Default::default())).unwrap()
+ }
+ #[inline]
+ pub fn floats(&self) -> flatbuffers::Vector<'a, f32> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, f32>>>(MoreDefaults::VT_FLOATS, Some(Default::default())).unwrap()
+ }
+ #[inline]
+ pub fn empty_string(&self) -> &'a str {
+ self._tab.get::<flatbuffers::ForwardsUOffset<&str>>(MoreDefaults::VT_EMPTY_STRING, Some(&"")).unwrap()
+ }
+ #[inline]
+ pub fn some_string(&self) -> &'a str {
+ self._tab.get::<flatbuffers::ForwardsUOffset<&str>>(MoreDefaults::VT_SOME_STRING, Some(&"some")).unwrap()
+ }
+ #[inline]
+ pub fn abcs(&self) -> flatbuffers::Vector<'a, ABC> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, ABC>>>(MoreDefaults::VT_ABCS, Some(Default::default())).unwrap()
+ }
+ #[inline]
+ pub fn bools(&self) -> &'a [bool] {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, bool>>>(MoreDefaults::VT_BOOLS, Some(Default::default())).map(|v| v.safe_slice()).unwrap()
+ }
+}
+
+impl flatbuffers::Verifiable for MoreDefaults<'_> {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ v.visit_table(pos)?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, i32>>>("ints", Self::VT_INTS, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, f32>>>("floats", Self::VT_FLOATS, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<&str>>("empty_string", Self::VT_EMPTY_STRING, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<&str>>("some_string", Self::VT_SOME_STRING, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, ABC>>>("abcs", Self::VT_ABCS, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, bool>>>("bools", Self::VT_BOOLS, false)?
+ .finish();
+ Ok(())
+ }
+}
+pub struct MoreDefaultsArgs<'a> {
+ pub ints: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, i32>>>,
+ pub floats: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, f32>>>,
+ pub empty_string: Option<flatbuffers::WIPOffset<&'a str>>,
+ pub some_string: Option<flatbuffers::WIPOffset<&'a str>>,
+ pub abcs: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, ABC>>>,
+ pub bools: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, bool>>>,
+}
+impl<'a> Default for MoreDefaultsArgs<'a> {
+ #[inline]
+ fn default() -> Self {
+ MoreDefaultsArgs {
+ ints: None,
+ floats: None,
+ empty_string: None,
+ some_string: None,
+ abcs: None,
+ bools: None,
+ }
+ }
+}
+
+pub struct MoreDefaultsBuilder<'a: 'b, 'b> {
+ fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
+ start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
+}
+impl<'a: 'b, 'b> MoreDefaultsBuilder<'a, 'b> {
+ #[inline]
+ pub fn add_ints(&mut self, ints: flatbuffers::WIPOffset<flatbuffers::Vector<'b , i32>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(MoreDefaults::VT_INTS, ints);
+ }
+ #[inline]
+ pub fn add_floats(&mut self, floats: flatbuffers::WIPOffset<flatbuffers::Vector<'b , f32>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(MoreDefaults::VT_FLOATS, floats);
+ }
+ #[inline]
+ pub fn add_empty_string(&mut self, empty_string: flatbuffers::WIPOffset<&'b str>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(MoreDefaults::VT_EMPTY_STRING, empty_string);
+ }
+ #[inline]
+ pub fn add_some_string(&mut self, some_string: flatbuffers::WIPOffset<&'b str>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(MoreDefaults::VT_SOME_STRING, some_string);
+ }
+ #[inline]
+ pub fn add_abcs(&mut self, abcs: flatbuffers::WIPOffset<flatbuffers::Vector<'b , ABC>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(MoreDefaults::VT_ABCS, abcs);
+ }
+ #[inline]
+ pub fn add_bools(&mut self, bools: flatbuffers::WIPOffset<flatbuffers::Vector<'b , bool>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(MoreDefaults::VT_BOOLS, bools);
+ }
+ #[inline]
+ pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> MoreDefaultsBuilder<'a, 'b> {
+ let start = _fbb.start_table();
+ MoreDefaultsBuilder {
+ fbb_: _fbb,
+ start_: start,
+ }
+ }
+ #[inline]
+ pub fn finish(self) -> flatbuffers::WIPOffset<MoreDefaults<'a>> {
+ let o = self.fbb_.end_table(self.start_);
+ flatbuffers::WIPOffset::new(o.value())
+ }
+}
+
+impl std::fmt::Debug for MoreDefaults<'_> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let mut ds = f.debug_struct("MoreDefaults");
+ ds.field("ints", &self.ints());
+ ds.field("floats", &self.floats());
+ ds.field("empty_string", &self.empty_string());
+ ds.field("some_string", &self.some_string());
+ ds.field("abcs", &self.abcs());
+ ds.field("bools", &self.bools());
+ ds.finish()
+ }
+}
+#[non_exhaustive]
+#[derive(Debug, Clone, PartialEq)]
+pub struct MoreDefaultsT {
+ pub ints: Vec<i32>,
+ pub floats: Vec<f32>,
+ pub empty_string: String,
+ pub some_string: String,
+ pub abcs: Vec<ABC>,
+ pub bools: Vec<bool>,
+}
+impl Default for MoreDefaultsT {
+ fn default() -> Self {
+ Self {
+ ints: Default::default(),
+ floats: Default::default(),
+ empty_string: "".to_string(),
+ some_string: "some".to_string(),
+ abcs: Default::default(),
+ bools: Default::default(),
+ }
+ }
+}
+impl MoreDefaultsT {
+ pub fn pack<'b>(
+ &self,
+ _fbb: &mut flatbuffers::FlatBufferBuilder<'b>
+ ) -> flatbuffers::WIPOffset<MoreDefaults<'b>> {
+ let ints = Some({
+ let x = &self.ints;
+ _fbb.create_vector(x)
+ });
+ let floats = Some({
+ let x = &self.floats;
+ _fbb.create_vector(x)
+ });
+ let empty_string = Some({
+ let x = &self.empty_string;
+ _fbb.create_string(x)
+ });
+ let some_string = Some({
+ let x = &self.some_string;
+ _fbb.create_string(x)
+ });
+ let abcs = Some({
+ let x = &self.abcs;
+ _fbb.create_vector(x)
+ });
+ let bools = Some({
+ let x = &self.bools;
+ _fbb.create_vector(x)
+ });
+ MoreDefaults::create(_fbb, &MoreDefaultsArgs{
+ ints,
+ floats,
+ empty_string,
+ some_string,
+ abcs,
+ bools,
+ })
+ }
+}
diff --git a/tests/my-game/example/ability.js b/tests/my-game/example/ability.js
new file mode 100644
index 0000000..9fea3d6
--- /dev/null
+++ b/tests/my-game/example/ability.js
@@ -0,0 +1,54 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+export class Ability {
+ constructor() {
+ this.bb = null;
+ this.bb_pos = 0;
+ }
+ __init(i, bb) {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+ }
+ id() {
+ return this.bb.readUint32(this.bb_pos);
+ }
+ mutate_id(value) {
+ this.bb.writeUint32(this.bb_pos + 0, value);
+ return true;
+ }
+ distance() {
+ return this.bb.readUint32(this.bb_pos + 4);
+ }
+ mutate_distance(value) {
+ this.bb.writeUint32(this.bb_pos + 4, value);
+ return true;
+ }
+ static getFullyQualifiedName() {
+ return 'MyGame.Example.Ability';
+ }
+ static sizeOf() {
+ return 8;
+ }
+ static createAbility(builder, id, distance) {
+ builder.prep(4, 8);
+ builder.writeInt32(distance);
+ builder.writeInt32(id);
+ return builder.offset();
+ }
+ unpack() {
+ return new AbilityT(this.id(), this.distance());
+ }
+ unpackTo(_o) {
+ _o.id = this.id();
+ _o.distance = this.distance();
+ }
+}
+export class AbilityT {
+ constructor(id = 0, distance = 0) {
+ this.id = id;
+ this.distance = distance;
+ }
+ pack(builder) {
+ return Ability.createAbility(builder, this.id, this.distance);
+ }
+}
diff --git a/tests/my-game/example/ability.ts b/tests/my-game/example/ability.ts
new file mode 100644
index 0000000..26395fb
--- /dev/null
+++ b/tests/my-game/example/ability.ts
@@ -0,0 +1,77 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+import * as flatbuffers from 'flatbuffers';
+
+
+
+export class Ability {
+ bb: flatbuffers.ByteBuffer|null = null;
+ bb_pos = 0;
+__init(i:number, bb:flatbuffers.ByteBuffer):Ability {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+}
+
+id():number {
+ return this.bb!.readUint32(this.bb_pos);
+}
+
+mutate_id(value:number):boolean {
+ this.bb!.writeUint32(this.bb_pos + 0, value);
+ return true;
+}
+
+distance():number {
+ return this.bb!.readUint32(this.bb_pos + 4);
+}
+
+mutate_distance(value:number):boolean {
+ this.bb!.writeUint32(this.bb_pos + 4, value);
+ return true;
+}
+
+static getFullyQualifiedName():string {
+ return 'MyGame.Example.Ability';
+}
+
+static sizeOf():number {
+ return 8;
+}
+
+static createAbility(builder:flatbuffers.Builder, id: number, distance: number):flatbuffers.Offset {
+ builder.prep(4, 8);
+ builder.writeInt32(distance);
+ builder.writeInt32(id);
+ return builder.offset();
+}
+
+
+unpack(): AbilityT {
+ return new AbilityT(
+ this.id(),
+ this.distance()
+ );
+}
+
+
+unpackTo(_o: AbilityT): void {
+ _o.id = this.id();
+ _o.distance = this.distance();
+}
+}
+
+export class AbilityT {
+constructor(
+ public id: number = 0,
+ public distance: number = 0
+){}
+
+
+pack(builder:flatbuffers.Builder): flatbuffers.Offset {
+ return Ability.createAbility(builder,
+ this.id,
+ this.distance
+ );
+}
+}
diff --git a/tests/my-game/example/any-ambiguous-aliases.js b/tests/my-game/example/any-ambiguous-aliases.js
new file mode 100644
index 0000000..7cd2a85
--- /dev/null
+++ b/tests/my-game/example/any-ambiguous-aliases.js
@@ -0,0 +1,27 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+import { Monster } from '../../my-game/example/monster';
+export var AnyAmbiguousAliases;
+(function (AnyAmbiguousAliases) {
+ AnyAmbiguousAliases[AnyAmbiguousAliases["NONE"] = 0] = "NONE";
+ AnyAmbiguousAliases[AnyAmbiguousAliases["M1"] = 1] = "M1";
+ AnyAmbiguousAliases[AnyAmbiguousAliases["M2"] = 2] = "M2";
+ AnyAmbiguousAliases[AnyAmbiguousAliases["M3"] = 3] = "M3";
+})(AnyAmbiguousAliases || (AnyAmbiguousAliases = {}));
+export function unionToAnyAmbiguousAliases(type, accessor) {
+ switch (AnyAmbiguousAliases[type]) {
+ case 'NONE': return null;
+ case 'M1': return accessor(new Monster());
+ case 'M2': return accessor(new Monster());
+ case 'M3': return accessor(new Monster());
+ default: return null;
+ }
+}
+export function unionListToAnyAmbiguousAliases(type, accessor, index) {
+ switch (AnyAmbiguousAliases[type]) {
+ case 'NONE': return null;
+ case 'M1': return accessor(index, new Monster());
+ case 'M2': return accessor(index, new Monster());
+ case 'M3': return accessor(index, new Monster());
+ default: return null;
+ }
+}
diff --git a/tests/my-game/example/any-ambiguous-aliases.ts b/tests/my-game/example/any-ambiguous-aliases.ts
new file mode 100644
index 0000000..6687a41
--- /dev/null
+++ b/tests/my-game/example/any-ambiguous-aliases.ts
@@ -0,0 +1,39 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+import { Monster, MonsterT } from '../../my-game/example/monster';
+
+
+export enum AnyAmbiguousAliases{
+ NONE = 0,
+ M1 = 1,
+ M2 = 2,
+ M3 = 3
+}
+
+export function unionToAnyAmbiguousAliases(
+ type: AnyAmbiguousAliases,
+ accessor: (obj:Monster) => Monster|null
+): Monster|null {
+ switch(AnyAmbiguousAliases[type]) {
+ case 'NONE': return null;
+ case 'M1': return accessor(new Monster())! as Monster;
+ case 'M2': return accessor(new Monster())! as Monster;
+ case 'M3': return accessor(new Monster())! as Monster;
+ default: return null;
+ }
+}
+
+export function unionListToAnyAmbiguousAliases(
+ type: AnyAmbiguousAliases,
+ accessor: (index: number, obj:Monster) => Monster|null,
+ index: number
+): Monster|null {
+ switch(AnyAmbiguousAliases[type]) {
+ case 'NONE': return null;
+ case 'M1': return accessor(index, new Monster())! as Monster;
+ case 'M2': return accessor(index, new Monster())! as Monster;
+ case 'M3': return accessor(index, new Monster())! as Monster;
+ default: return null;
+ }
+}
+
diff --git a/tests/my-game/example/any-unique-aliases.js b/tests/my-game/example/any-unique-aliases.js
new file mode 100644
index 0000000..b5cc882
--- /dev/null
+++ b/tests/my-game/example/any-unique-aliases.js
@@ -0,0 +1,29 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+import { Monster as MyGameExample2Monster } from '../../my-game/example2/monster';
+import { Monster } from '../../my-game/example/monster';
+import { TestSimpleTableWithEnum } from '../../my-game/example/test-simple-table-with-enum';
+export var AnyUniqueAliases;
+(function (AnyUniqueAliases) {
+ AnyUniqueAliases[AnyUniqueAliases["NONE"] = 0] = "NONE";
+ AnyUniqueAliases[AnyUniqueAliases["M"] = 1] = "M";
+ AnyUniqueAliases[AnyUniqueAliases["TS"] = 2] = "TS";
+ AnyUniqueAliases[AnyUniqueAliases["M2"] = 3] = "M2";
+})(AnyUniqueAliases || (AnyUniqueAliases = {}));
+export function unionToAnyUniqueAliases(type, accessor) {
+ switch (AnyUniqueAliases[type]) {
+ case 'NONE': return null;
+ case 'M': return accessor(new Monster());
+ case 'TS': return accessor(new TestSimpleTableWithEnum());
+ case 'M2': return accessor(new MyGameExample2Monster());
+ default: return null;
+ }
+}
+export function unionListToAnyUniqueAliases(type, accessor, index) {
+ switch (AnyUniqueAliases[type]) {
+ case 'NONE': return null;
+ case 'M': return accessor(index, new Monster());
+ case 'TS': return accessor(index, new TestSimpleTableWithEnum());
+ case 'M2': return accessor(index, new MyGameExample2Monster());
+ default: return null;
+ }
+}
diff --git a/tests/my-game/example/any-unique-aliases.ts b/tests/my-game/example/any-unique-aliases.ts
new file mode 100644
index 0000000..5106148
--- /dev/null
+++ b/tests/my-game/example/any-unique-aliases.ts
@@ -0,0 +1,41 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+import { Monster as MyGameExample2Monster, MonsterT as MyGameExample2MonsterT } from '../../my-game/example2/monster';
+import { Monster, MonsterT } from '../../my-game/example/monster';
+import { TestSimpleTableWithEnum, TestSimpleTableWithEnumT } from '../../my-game/example/test-simple-table-with-enum';
+
+
+export enum AnyUniqueAliases{
+ NONE = 0,
+ M = 1,
+ TS = 2,
+ M2 = 3
+}
+
+export function unionToAnyUniqueAliases(
+ type: AnyUniqueAliases,
+ accessor: (obj:Monster|MyGameExample2Monster|TestSimpleTableWithEnum) => Monster|MyGameExample2Monster|TestSimpleTableWithEnum|null
+): Monster|MyGameExample2Monster|TestSimpleTableWithEnum|null {
+ switch(AnyUniqueAliases[type]) {
+ case 'NONE': return null;
+ case 'M': return accessor(new Monster())! as Monster;
+ case 'TS': return accessor(new TestSimpleTableWithEnum())! as TestSimpleTableWithEnum;
+ case 'M2': return accessor(new MyGameExample2Monster())! as MyGameExample2Monster;
+ default: return null;
+ }
+}
+
+export function unionListToAnyUniqueAliases(
+ type: AnyUniqueAliases,
+ accessor: (index: number, obj:Monster|MyGameExample2Monster|TestSimpleTableWithEnum) => Monster|MyGameExample2Monster|TestSimpleTableWithEnum|null,
+ index: number
+): Monster|MyGameExample2Monster|TestSimpleTableWithEnum|null {
+ switch(AnyUniqueAliases[type]) {
+ case 'NONE': return null;
+ case 'M': return accessor(index, new Monster())! as Monster;
+ case 'TS': return accessor(index, new TestSimpleTableWithEnum())! as TestSimpleTableWithEnum;
+ case 'M2': return accessor(index, new MyGameExample2Monster())! as MyGameExample2Monster;
+ default: return null;
+ }
+}
+
diff --git a/tests/my-game/example/any.js b/tests/my-game/example/any.js
new file mode 100644
index 0000000..7349c07
--- /dev/null
+++ b/tests/my-game/example/any.js
@@ -0,0 +1,29 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+import { Monster as MyGameExample2Monster } from '../../my-game/example2/monster';
+import { Monster } from '../../my-game/example/monster';
+import { TestSimpleTableWithEnum } from '../../my-game/example/test-simple-table-with-enum';
+export var Any;
+(function (Any) {
+ Any[Any["NONE"] = 0] = "NONE";
+ Any[Any["Monster"] = 1] = "Monster";
+ Any[Any["TestSimpleTableWithEnum"] = 2] = "TestSimpleTableWithEnum";
+ Any[Any["MyGame_Example2_Monster"] = 3] = "MyGame_Example2_Monster";
+})(Any || (Any = {}));
+export function unionToAny(type, accessor) {
+ switch (Any[type]) {
+ case 'NONE': return null;
+ case 'Monster': return accessor(new Monster());
+ case 'TestSimpleTableWithEnum': return accessor(new TestSimpleTableWithEnum());
+ case 'MyGame_Example2_Monster': return accessor(new MyGameExample2Monster());
+ default: return null;
+ }
+}
+export function unionListToAny(type, accessor, index) {
+ switch (Any[type]) {
+ case 'NONE': return null;
+ case 'Monster': return accessor(index, new Monster());
+ case 'TestSimpleTableWithEnum': return accessor(index, new TestSimpleTableWithEnum());
+ case 'MyGame_Example2_Monster': return accessor(index, new MyGameExample2Monster());
+ default: return null;
+ }
+}
diff --git a/tests/my-game/example/any.ts b/tests/my-game/example/any.ts
new file mode 100644
index 0000000..9d8b2a6
--- /dev/null
+++ b/tests/my-game/example/any.ts
@@ -0,0 +1,41 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+import { Monster as MyGameExample2Monster, MonsterT as MyGameExample2MonsterT } from '../../my-game/example2/monster';
+import { Monster, MonsterT } from '../../my-game/example/monster';
+import { TestSimpleTableWithEnum, TestSimpleTableWithEnumT } from '../../my-game/example/test-simple-table-with-enum';
+
+
+export enum Any{
+ NONE = 0,
+ Monster = 1,
+ TestSimpleTableWithEnum = 2,
+ MyGame_Example2_Monster = 3
+}
+
+export function unionToAny(
+ type: Any,
+ accessor: (obj:Monster|MyGameExample2Monster|TestSimpleTableWithEnum) => Monster|MyGameExample2Monster|TestSimpleTableWithEnum|null
+): Monster|MyGameExample2Monster|TestSimpleTableWithEnum|null {
+ switch(Any[type]) {
+ case 'NONE': return null;
+ case 'Monster': return accessor(new Monster())! as Monster;
+ case 'TestSimpleTableWithEnum': return accessor(new TestSimpleTableWithEnum())! as TestSimpleTableWithEnum;
+ case 'MyGame_Example2_Monster': return accessor(new MyGameExample2Monster())! as MyGameExample2Monster;
+ default: return null;
+ }
+}
+
+export function unionListToAny(
+ type: Any,
+ accessor: (index: number, obj:Monster|MyGameExample2Monster|TestSimpleTableWithEnum) => Monster|MyGameExample2Monster|TestSimpleTableWithEnum|null,
+ index: number
+): Monster|MyGameExample2Monster|TestSimpleTableWithEnum|null {
+ switch(Any[type]) {
+ case 'NONE': return null;
+ case 'Monster': return accessor(index, new Monster())! as Monster;
+ case 'TestSimpleTableWithEnum': return accessor(index, new TestSimpleTableWithEnum())! as TestSimpleTableWithEnum;
+ case 'MyGame_Example2_Monster': return accessor(index, new MyGameExample2Monster())! as MyGameExample2Monster;
+ default: return null;
+ }
+}
+
diff --git a/tests/my-game/example/color.js b/tests/my-game/example/color.js
new file mode 100644
index 0000000..f95f75e
--- /dev/null
+++ b/tests/my-game/example/color.js
@@ -0,0 +1,17 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+/**
+ * Composite components of Monster color.
+ */
+export var Color;
+(function (Color) {
+ Color[Color["Red"] = 1] = "Red";
+ /**
+ * \brief color Green
+ * Green is bit_flag with value (1u << 1)
+ */
+ Color[Color["Green"] = 2] = "Green";
+ /**
+ * \brief color Blue (1u << 3)
+ */
+ Color[Color["Blue"] = 8] = "Blue";
+})(Color || (Color = {}));
diff --git a/tests/my-game/example/color.ts b/tests/my-game/example/color.ts
new file mode 100644
index 0000000..ceb31f8
--- /dev/null
+++ b/tests/my-game/example/color.ts
@@ -0,0 +1,20 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+/**
+ * Composite components of Monster color.
+ */
+export enum Color{
+ Red = 1,
+
+ /**
+ * \brief color Green
+ * Green is bit_flag with value (1u << 1)
+ */
+ Green = 2,
+
+ /**
+ * \brief color Blue (1u << 3)
+ */
+ Blue = 8
+}
+
diff --git a/tests/my-game/example/long-enum.ts b/tests/my-game/example/long-enum.ts
new file mode 100644
index 0000000..be41819
--- /dev/null
+++ b/tests/my-game/example/long-enum.ts
@@ -0,0 +1,8 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+export enum LongEnum{
+ LongOne = '2',
+ LongTwo = '4',
+ LongBig = '1099511627776'
+}
+
diff --git a/tests/my-game/example/monster.js b/tests/my-game/example/monster.js
new file mode 100644
index 0000000..3c3c23b
--- /dev/null
+++ b/tests/my-game/example/monster.js
@@ -0,0 +1,1125 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+import * as flatbuffers from 'flatbuffers';
+import { Ability } from '../../my-game/example/ability';
+import { Any, unionToAny } from '../../my-game/example/any';
+import { AnyAmbiguousAliases, unionToAnyAmbiguousAliases } from '../../my-game/example/any-ambiguous-aliases';
+import { AnyUniqueAliases, unionToAnyUniqueAliases } from '../../my-game/example/any-unique-aliases';
+import { Color } from '../../my-game/example/color';
+import { Race } from '../../my-game/example/race';
+import { Referrable } from '../../my-game/example/referrable';
+import { Stat } from '../../my-game/example/stat';
+import { Test } from '../../my-game/example/test';
+import { Vec3 } from '../../my-game/example/vec3';
+import { InParentNamespace } from '../../my-game/in-parent-namespace';
+/**
+ * an example documentation comment: "monster object"
+ */
+export class Monster {
+ constructor() {
+ this.bb = null;
+ this.bb_pos = 0;
+ }
+ __init(i, bb) {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+ }
+ static getRootAsMonster(bb, obj) {
+ return (obj || new Monster()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ static getSizePrefixedRootAsMonster(bb, obj) {
+ bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new Monster()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ static bufferHasIdentifier(bb) {
+ return bb.__has_identifier('MONS');
+ }
+ pos(obj) {
+ const offset = this.bb.__offset(this.bb_pos, 4);
+ return offset ? (obj || new Vec3()).__init(this.bb_pos + offset, this.bb) : null;
+ }
+ mana() {
+ const offset = this.bb.__offset(this.bb_pos, 6);
+ return offset ? this.bb.readInt16(this.bb_pos + offset) : 150;
+ }
+ mutate_mana(value) {
+ const offset = this.bb.__offset(this.bb_pos, 6);
+ if (offset === 0) {
+ return false;
+ }
+ this.bb.writeInt16(this.bb_pos + offset, value);
+ return true;
+ }
+ hp() {
+ const offset = this.bb.__offset(this.bb_pos, 8);
+ return offset ? this.bb.readInt16(this.bb_pos + offset) : 100;
+ }
+ mutate_hp(value) {
+ const offset = this.bb.__offset(this.bb_pos, 8);
+ if (offset === 0) {
+ return false;
+ }
+ this.bb.writeInt16(this.bb_pos + offset, value);
+ return true;
+ }
+ name(optionalEncoding) {
+ const offset = this.bb.__offset(this.bb_pos, 10);
+ return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
+ }
+ inventory(index) {
+ const offset = this.bb.__offset(this.bb_pos, 14);
+ return offset ? this.bb.readUint8(this.bb.__vector(this.bb_pos + offset) + index) : 0;
+ }
+ inventoryLength() {
+ const offset = this.bb.__offset(this.bb_pos, 14);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ inventoryArray() {
+ const offset = this.bb.__offset(this.bb_pos, 14);
+ return offset ? new Uint8Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null;
+ }
+ color() {
+ const offset = this.bb.__offset(this.bb_pos, 16);
+ return offset ? this.bb.readUint8(this.bb_pos + offset) : Color.Blue;
+ }
+ mutate_color(value) {
+ const offset = this.bb.__offset(this.bb_pos, 16);
+ if (offset === 0) {
+ return false;
+ }
+ this.bb.writeUint8(this.bb_pos + offset, value);
+ return true;
+ }
+ testType() {
+ const offset = this.bb.__offset(this.bb_pos, 18);
+ return offset ? this.bb.readUint8(this.bb_pos + offset) : Any.NONE;
+ }
+ test(obj) {
+ const offset = this.bb.__offset(this.bb_pos, 20);
+ return offset ? this.bb.__union(obj, this.bb_pos + offset) : null;
+ }
+ test4(index, obj) {
+ const offset = this.bb.__offset(this.bb_pos, 22);
+ return offset ? (obj || new Test()).__init(this.bb.__vector(this.bb_pos + offset) + index * 4, this.bb) : null;
+ }
+ test4Length() {
+ const offset = this.bb.__offset(this.bb_pos, 22);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ testarrayofstring(index, optionalEncoding) {
+ const offset = this.bb.__offset(this.bb_pos, 24);
+ return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null;
+ }
+ testarrayofstringLength() {
+ const offset = this.bb.__offset(this.bb_pos, 24);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ /**
+ * an example documentation comment: this will end up in the generated code
+ * multiline too
+ */
+ testarrayoftables(index, obj) {
+ const offset = this.bb.__offset(this.bb_pos, 26);
+ return offset ? (obj || new Monster()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null;
+ }
+ testarrayoftablesLength() {
+ const offset = this.bb.__offset(this.bb_pos, 26);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ enemy(obj) {
+ const offset = this.bb.__offset(this.bb_pos, 28);
+ return offset ? (obj || new Monster()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null;
+ }
+ testnestedflatbuffer(index) {
+ const offset = this.bb.__offset(this.bb_pos, 30);
+ return offset ? this.bb.readUint8(this.bb.__vector(this.bb_pos + offset) + index) : 0;
+ }
+ testnestedflatbufferLength() {
+ const offset = this.bb.__offset(this.bb_pos, 30);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ testnestedflatbufferArray() {
+ const offset = this.bb.__offset(this.bb_pos, 30);
+ return offset ? new Uint8Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null;
+ }
+ testempty(obj) {
+ const offset = this.bb.__offset(this.bb_pos, 32);
+ return offset ? (obj || new Stat()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null;
+ }
+ testbool() {
+ const offset = this.bb.__offset(this.bb_pos, 34);
+ return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false;
+ }
+ mutate_testbool(value) {
+ const offset = this.bb.__offset(this.bb_pos, 34);
+ if (offset === 0) {
+ return false;
+ }
+ this.bb.writeInt8(this.bb_pos + offset, +value);
+ return true;
+ }
+ testhashs32Fnv1() {
+ const offset = this.bb.__offset(this.bb_pos, 36);
+ return offset ? this.bb.readInt32(this.bb_pos + offset) : 0;
+ }
+ mutate_testhashs32_fnv1(value) {
+ const offset = this.bb.__offset(this.bb_pos, 36);
+ if (offset === 0) {
+ return false;
+ }
+ this.bb.writeInt32(this.bb_pos + offset, value);
+ return true;
+ }
+ testhashu32Fnv1() {
+ const offset = this.bb.__offset(this.bb_pos, 38);
+ return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
+ }
+ mutate_testhashu32_fnv1(value) {
+ const offset = this.bb.__offset(this.bb_pos, 38);
+ if (offset === 0) {
+ return false;
+ }
+ this.bb.writeUint32(this.bb_pos + offset, value);
+ return true;
+ }
+ testhashs64Fnv1() {
+ const offset = this.bb.__offset(this.bb_pos, 40);
+ return offset ? this.bb.readInt64(this.bb_pos + offset) : BigInt('0');
+ }
+ mutate_testhashs64_fnv1(value) {
+ const offset = this.bb.__offset(this.bb_pos, 40);
+ if (offset === 0) {
+ return false;
+ }
+ this.bb.writeInt64(this.bb_pos + offset, value);
+ return true;
+ }
+ testhashu64Fnv1() {
+ const offset = this.bb.__offset(this.bb_pos, 42);
+ return offset ? this.bb.readUint64(this.bb_pos + offset) : BigInt('0');
+ }
+ mutate_testhashu64_fnv1(value) {
+ const offset = this.bb.__offset(this.bb_pos, 42);
+ if (offset === 0) {
+ return false;
+ }
+ this.bb.writeUint64(this.bb_pos + offset, value);
+ return true;
+ }
+ testhashs32Fnv1a() {
+ const offset = this.bb.__offset(this.bb_pos, 44);
+ return offset ? this.bb.readInt32(this.bb_pos + offset) : 0;
+ }
+ mutate_testhashs32_fnv1a(value) {
+ const offset = this.bb.__offset(this.bb_pos, 44);
+ if (offset === 0) {
+ return false;
+ }
+ this.bb.writeInt32(this.bb_pos + offset, value);
+ return true;
+ }
+ testhashu32Fnv1a() {
+ const offset = this.bb.__offset(this.bb_pos, 46);
+ return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
+ }
+ mutate_testhashu32_fnv1a(value) {
+ const offset = this.bb.__offset(this.bb_pos, 46);
+ if (offset === 0) {
+ return false;
+ }
+ this.bb.writeUint32(this.bb_pos + offset, value);
+ return true;
+ }
+ testhashs64Fnv1a() {
+ const offset = this.bb.__offset(this.bb_pos, 48);
+ return offset ? this.bb.readInt64(this.bb_pos + offset) : BigInt('0');
+ }
+ mutate_testhashs64_fnv1a(value) {
+ const offset = this.bb.__offset(this.bb_pos, 48);
+ if (offset === 0) {
+ return false;
+ }
+ this.bb.writeInt64(this.bb_pos + offset, value);
+ return true;
+ }
+ testhashu64Fnv1a() {
+ const offset = this.bb.__offset(this.bb_pos, 50);
+ return offset ? this.bb.readUint64(this.bb_pos + offset) : BigInt('0');
+ }
+ mutate_testhashu64_fnv1a(value) {
+ const offset = this.bb.__offset(this.bb_pos, 50);
+ if (offset === 0) {
+ return false;
+ }
+ this.bb.writeUint64(this.bb_pos + offset, value);
+ return true;
+ }
+ testarrayofbools(index) {
+ const offset = this.bb.__offset(this.bb_pos, 52);
+ return offset ? !!this.bb.readInt8(this.bb.__vector(this.bb_pos + offset) + index) : false;
+ }
+ testarrayofboolsLength() {
+ const offset = this.bb.__offset(this.bb_pos, 52);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ testarrayofboolsArray() {
+ const offset = this.bb.__offset(this.bb_pos, 52);
+ return offset ? new Int8Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null;
+ }
+ testf() {
+ const offset = this.bb.__offset(this.bb_pos, 54);
+ return offset ? this.bb.readFloat32(this.bb_pos + offset) : 3.14159;
+ }
+ mutate_testf(value) {
+ const offset = this.bb.__offset(this.bb_pos, 54);
+ if (offset === 0) {
+ return false;
+ }
+ this.bb.writeFloat32(this.bb_pos + offset, value);
+ return true;
+ }
+ testf2() {
+ const offset = this.bb.__offset(this.bb_pos, 56);
+ return offset ? this.bb.readFloat32(this.bb_pos + offset) : 3.0;
+ }
+ mutate_testf2(value) {
+ const offset = this.bb.__offset(this.bb_pos, 56);
+ if (offset === 0) {
+ return false;
+ }
+ this.bb.writeFloat32(this.bb_pos + offset, value);
+ return true;
+ }
+ testf3() {
+ const offset = this.bb.__offset(this.bb_pos, 58);
+ return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0.0;
+ }
+ mutate_testf3(value) {
+ const offset = this.bb.__offset(this.bb_pos, 58);
+ if (offset === 0) {
+ return false;
+ }
+ this.bb.writeFloat32(this.bb_pos + offset, value);
+ return true;
+ }
+ testarrayofstring2(index, optionalEncoding) {
+ const offset = this.bb.__offset(this.bb_pos, 60);
+ return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null;
+ }
+ testarrayofstring2Length() {
+ const offset = this.bb.__offset(this.bb_pos, 60);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ testarrayofsortedstruct(index, obj) {
+ const offset = this.bb.__offset(this.bb_pos, 62);
+ return offset ? (obj || new Ability()).__init(this.bb.__vector(this.bb_pos + offset) + index * 8, this.bb) : null;
+ }
+ testarrayofsortedstructLength() {
+ const offset = this.bb.__offset(this.bb_pos, 62);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ flex(index) {
+ const offset = this.bb.__offset(this.bb_pos, 64);
+ return offset ? this.bb.readUint8(this.bb.__vector(this.bb_pos + offset) + index) : 0;
+ }
+ flexLength() {
+ const offset = this.bb.__offset(this.bb_pos, 64);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ flexArray() {
+ const offset = this.bb.__offset(this.bb_pos, 64);
+ return offset ? new Uint8Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null;
+ }
+ test5(index, obj) {
+ const offset = this.bb.__offset(this.bb_pos, 66);
+ return offset ? (obj || new Test()).__init(this.bb.__vector(this.bb_pos + offset) + index * 4, this.bb) : null;
+ }
+ test5Length() {
+ const offset = this.bb.__offset(this.bb_pos, 66);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ vectorOfLongs(index) {
+ const offset = this.bb.__offset(this.bb_pos, 68);
+ return offset ? this.bb.readInt64(this.bb.__vector(this.bb_pos + offset) + index * 8) : BigInt(0);
+ }
+ vectorOfLongsLength() {
+ const offset = this.bb.__offset(this.bb_pos, 68);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ vectorOfDoubles(index) {
+ const offset = this.bb.__offset(this.bb_pos, 70);
+ return offset ? this.bb.readFloat64(this.bb.__vector(this.bb_pos + offset) + index * 8) : 0;
+ }
+ vectorOfDoublesLength() {
+ const offset = this.bb.__offset(this.bb_pos, 70);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ vectorOfDoublesArray() {
+ const offset = this.bb.__offset(this.bb_pos, 70);
+ return offset ? new Float64Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null;
+ }
+ parentNamespaceTest(obj) {
+ const offset = this.bb.__offset(this.bb_pos, 72);
+ return offset ? (obj || new InParentNamespace()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null;
+ }
+ vectorOfReferrables(index, obj) {
+ const offset = this.bb.__offset(this.bb_pos, 74);
+ return offset ? (obj || new Referrable()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null;
+ }
+ vectorOfReferrablesLength() {
+ const offset = this.bb.__offset(this.bb_pos, 74);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ singleWeakReference() {
+ const offset = this.bb.__offset(this.bb_pos, 76);
+ return offset ? this.bb.readUint64(this.bb_pos + offset) : BigInt('0');
+ }
+ mutate_single_weak_reference(value) {
+ const offset = this.bb.__offset(this.bb_pos, 76);
+ if (offset === 0) {
+ return false;
+ }
+ this.bb.writeUint64(this.bb_pos + offset, value);
+ return true;
+ }
+ vectorOfWeakReferences(index) {
+ const offset = this.bb.__offset(this.bb_pos, 78);
+ return offset ? this.bb.readUint64(this.bb.__vector(this.bb_pos + offset) + index * 8) : BigInt(0);
+ }
+ vectorOfWeakReferencesLength() {
+ const offset = this.bb.__offset(this.bb_pos, 78);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ vectorOfStrongReferrables(index, obj) {
+ const offset = this.bb.__offset(this.bb_pos, 80);
+ return offset ? (obj || new Referrable()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null;
+ }
+ vectorOfStrongReferrablesLength() {
+ const offset = this.bb.__offset(this.bb_pos, 80);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ coOwningReference() {
+ const offset = this.bb.__offset(this.bb_pos, 82);
+ return offset ? this.bb.readUint64(this.bb_pos + offset) : BigInt('0');
+ }
+ mutate_co_owning_reference(value) {
+ const offset = this.bb.__offset(this.bb_pos, 82);
+ if (offset === 0) {
+ return false;
+ }
+ this.bb.writeUint64(this.bb_pos + offset, value);
+ return true;
+ }
+ vectorOfCoOwningReferences(index) {
+ const offset = this.bb.__offset(this.bb_pos, 84);
+ return offset ? this.bb.readUint64(this.bb.__vector(this.bb_pos + offset) + index * 8) : BigInt(0);
+ }
+ vectorOfCoOwningReferencesLength() {
+ const offset = this.bb.__offset(this.bb_pos, 84);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ nonOwningReference() {
+ const offset = this.bb.__offset(this.bb_pos, 86);
+ return offset ? this.bb.readUint64(this.bb_pos + offset) : BigInt('0');
+ }
+ mutate_non_owning_reference(value) {
+ const offset = this.bb.__offset(this.bb_pos, 86);
+ if (offset === 0) {
+ return false;
+ }
+ this.bb.writeUint64(this.bb_pos + offset, value);
+ return true;
+ }
+ vectorOfNonOwningReferences(index) {
+ const offset = this.bb.__offset(this.bb_pos, 88);
+ return offset ? this.bb.readUint64(this.bb.__vector(this.bb_pos + offset) + index * 8) : BigInt(0);
+ }
+ vectorOfNonOwningReferencesLength() {
+ const offset = this.bb.__offset(this.bb_pos, 88);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ anyUniqueType() {
+ const offset = this.bb.__offset(this.bb_pos, 90);
+ return offset ? this.bb.readUint8(this.bb_pos + offset) : AnyUniqueAliases.NONE;
+ }
+ anyUnique(obj) {
+ const offset = this.bb.__offset(this.bb_pos, 92);
+ return offset ? this.bb.__union(obj, this.bb_pos + offset) : null;
+ }
+ anyAmbiguousType() {
+ const offset = this.bb.__offset(this.bb_pos, 94);
+ return offset ? this.bb.readUint8(this.bb_pos + offset) : AnyAmbiguousAliases.NONE;
+ }
+ anyAmbiguous(obj) {
+ const offset = this.bb.__offset(this.bb_pos, 96);
+ return offset ? this.bb.__union(obj, this.bb_pos + offset) : null;
+ }
+ vectorOfEnums(index) {
+ const offset = this.bb.__offset(this.bb_pos, 98);
+ return offset ? this.bb.readUint8(this.bb.__vector(this.bb_pos + offset) + index) : 0;
+ }
+ vectorOfEnumsLength() {
+ const offset = this.bb.__offset(this.bb_pos, 98);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ vectorOfEnumsArray() {
+ const offset = this.bb.__offset(this.bb_pos, 98);
+ return offset ? new Uint8Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null;
+ }
+ signedEnum() {
+ const offset = this.bb.__offset(this.bb_pos, 100);
+ return offset ? this.bb.readInt8(this.bb_pos + offset) : Race.None;
+ }
+ mutate_signed_enum(value) {
+ const offset = this.bb.__offset(this.bb_pos, 100);
+ if (offset === 0) {
+ return false;
+ }
+ this.bb.writeInt8(this.bb_pos + offset, value);
+ return true;
+ }
+ testrequirednestedflatbuffer(index) {
+ const offset = this.bb.__offset(this.bb_pos, 102);
+ return offset ? this.bb.readUint8(this.bb.__vector(this.bb_pos + offset) + index) : 0;
+ }
+ testrequirednestedflatbufferLength() {
+ const offset = this.bb.__offset(this.bb_pos, 102);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ testrequirednestedflatbufferArray() {
+ const offset = this.bb.__offset(this.bb_pos, 102);
+ return offset ? new Uint8Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null;
+ }
+ scalarKeySortedTables(index, obj) {
+ const offset = this.bb.__offset(this.bb_pos, 104);
+ return offset ? (obj || new Stat()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null;
+ }
+ scalarKeySortedTablesLength() {
+ const offset = this.bb.__offset(this.bb_pos, 104);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ nativeInline(obj) {
+ const offset = this.bb.__offset(this.bb_pos, 106);
+ return offset ? (obj || new Test()).__init(this.bb_pos + offset, this.bb) : null;
+ }
+ longEnumNonEnumDefault() {
+ const offset = this.bb.__offset(this.bb_pos, 108);
+ return offset ? this.bb.readUint64(this.bb_pos + offset) : BigInt('0');
+ }
+ mutate_long_enum_non_enum_default(value) {
+ const offset = this.bb.__offset(this.bb_pos, 108);
+ if (offset === 0) {
+ return false;
+ }
+ this.bb.writeUint64(this.bb_pos + offset, value);
+ return true;
+ }
+ longEnumNormalDefault() {
+ const offset = this.bb.__offset(this.bb_pos, 110);
+ return offset ? this.bb.readUint64(this.bb_pos + offset) : BigInt('2');
+ }
+ mutate_long_enum_normal_default(value) {
+ const offset = this.bb.__offset(this.bb_pos, 110);
+ if (offset === 0) {
+ return false;
+ }
+ this.bb.writeUint64(this.bb_pos + offset, value);
+ return true;
+ }
+ static getFullyQualifiedName() {
+ return 'MyGame.Example.Monster';
+ }
+ static startMonster(builder) {
+ builder.startObject(54);
+ }
+ static addPos(builder, posOffset) {
+ builder.addFieldStruct(0, posOffset, 0);
+ }
+ static addMana(builder, mana) {
+ builder.addFieldInt16(1, mana, 150);
+ }
+ static addHp(builder, hp) {
+ builder.addFieldInt16(2, hp, 100);
+ }
+ static addName(builder, nameOffset) {
+ builder.addFieldOffset(3, nameOffset, 0);
+ }
+ static addInventory(builder, inventoryOffset) {
+ builder.addFieldOffset(5, inventoryOffset, 0);
+ }
+ static createInventoryVector(builder, data) {
+ builder.startVector(1, data.length, 1);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addInt8(data[i]);
+ }
+ return builder.endVector();
+ }
+ static startInventoryVector(builder, numElems) {
+ builder.startVector(1, numElems, 1);
+ }
+ static addColor(builder, color) {
+ builder.addFieldInt8(6, color, Color.Blue);
+ }
+ static addTestType(builder, testType) {
+ builder.addFieldInt8(7, testType, Any.NONE);
+ }
+ static addTest(builder, testOffset) {
+ builder.addFieldOffset(8, testOffset, 0);
+ }
+ static addTest4(builder, test4Offset) {
+ builder.addFieldOffset(9, test4Offset, 0);
+ }
+ static startTest4Vector(builder, numElems) {
+ builder.startVector(4, numElems, 2);
+ }
+ static addTestarrayofstring(builder, testarrayofstringOffset) {
+ builder.addFieldOffset(10, testarrayofstringOffset, 0);
+ }
+ static createTestarrayofstringVector(builder, data) {
+ builder.startVector(4, data.length, 4);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addOffset(data[i]);
+ }
+ return builder.endVector();
+ }
+ static startTestarrayofstringVector(builder, numElems) {
+ builder.startVector(4, numElems, 4);
+ }
+ static addTestarrayoftables(builder, testarrayoftablesOffset) {
+ builder.addFieldOffset(11, testarrayoftablesOffset, 0);
+ }
+ static createTestarrayoftablesVector(builder, data) {
+ builder.startVector(4, data.length, 4);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addOffset(data[i]);
+ }
+ return builder.endVector();
+ }
+ static startTestarrayoftablesVector(builder, numElems) {
+ builder.startVector(4, numElems, 4);
+ }
+ static addEnemy(builder, enemyOffset) {
+ builder.addFieldOffset(12, enemyOffset, 0);
+ }
+ static addTestnestedflatbuffer(builder, testnestedflatbufferOffset) {
+ builder.addFieldOffset(13, testnestedflatbufferOffset, 0);
+ }
+ static createTestnestedflatbufferVector(builder, data) {
+ builder.startVector(1, data.length, 1);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addInt8(data[i]);
+ }
+ return builder.endVector();
+ }
+ static startTestnestedflatbufferVector(builder, numElems) {
+ builder.startVector(1, numElems, 1);
+ }
+ static addTestempty(builder, testemptyOffset) {
+ builder.addFieldOffset(14, testemptyOffset, 0);
+ }
+ static addTestbool(builder, testbool) {
+ builder.addFieldInt8(15, +testbool, +false);
+ }
+ static addTesthashs32Fnv1(builder, testhashs32Fnv1) {
+ builder.addFieldInt32(16, testhashs32Fnv1, 0);
+ }
+ static addTesthashu32Fnv1(builder, testhashu32Fnv1) {
+ builder.addFieldInt32(17, testhashu32Fnv1, 0);
+ }
+ static addTesthashs64Fnv1(builder, testhashs64Fnv1) {
+ builder.addFieldInt64(18, testhashs64Fnv1, BigInt('0'));
+ }
+ static addTesthashu64Fnv1(builder, testhashu64Fnv1) {
+ builder.addFieldInt64(19, testhashu64Fnv1, BigInt('0'));
+ }
+ static addTesthashs32Fnv1a(builder, testhashs32Fnv1a) {
+ builder.addFieldInt32(20, testhashs32Fnv1a, 0);
+ }
+ static addTesthashu32Fnv1a(builder, testhashu32Fnv1a) {
+ builder.addFieldInt32(21, testhashu32Fnv1a, 0);
+ }
+ static addTesthashs64Fnv1a(builder, testhashs64Fnv1a) {
+ builder.addFieldInt64(22, testhashs64Fnv1a, BigInt('0'));
+ }
+ static addTesthashu64Fnv1a(builder, testhashu64Fnv1a) {
+ builder.addFieldInt64(23, testhashu64Fnv1a, BigInt('0'));
+ }
+ static addTestarrayofbools(builder, testarrayofboolsOffset) {
+ builder.addFieldOffset(24, testarrayofboolsOffset, 0);
+ }
+ static createTestarrayofboolsVector(builder, data) {
+ builder.startVector(1, data.length, 1);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addInt8(+data[i]);
+ }
+ return builder.endVector();
+ }
+ static startTestarrayofboolsVector(builder, numElems) {
+ builder.startVector(1, numElems, 1);
+ }
+ static addTestf(builder, testf) {
+ builder.addFieldFloat32(25, testf, 3.14159);
+ }
+ static addTestf2(builder, testf2) {
+ builder.addFieldFloat32(26, testf2, 3.0);
+ }
+ static addTestf3(builder, testf3) {
+ builder.addFieldFloat32(27, testf3, 0.0);
+ }
+ static addTestarrayofstring2(builder, testarrayofstring2Offset) {
+ builder.addFieldOffset(28, testarrayofstring2Offset, 0);
+ }
+ static createTestarrayofstring2Vector(builder, data) {
+ builder.startVector(4, data.length, 4);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addOffset(data[i]);
+ }
+ return builder.endVector();
+ }
+ static startTestarrayofstring2Vector(builder, numElems) {
+ builder.startVector(4, numElems, 4);
+ }
+ static addTestarrayofsortedstruct(builder, testarrayofsortedstructOffset) {
+ builder.addFieldOffset(29, testarrayofsortedstructOffset, 0);
+ }
+ static startTestarrayofsortedstructVector(builder, numElems) {
+ builder.startVector(8, numElems, 4);
+ }
+ static addFlex(builder, flexOffset) {
+ builder.addFieldOffset(30, flexOffset, 0);
+ }
+ static createFlexVector(builder, data) {
+ builder.startVector(1, data.length, 1);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addInt8(data[i]);
+ }
+ return builder.endVector();
+ }
+ static startFlexVector(builder, numElems) {
+ builder.startVector(1, numElems, 1);
+ }
+ static addTest5(builder, test5Offset) {
+ builder.addFieldOffset(31, test5Offset, 0);
+ }
+ static startTest5Vector(builder, numElems) {
+ builder.startVector(4, numElems, 2);
+ }
+ static addVectorOfLongs(builder, vectorOfLongsOffset) {
+ builder.addFieldOffset(32, vectorOfLongsOffset, 0);
+ }
+ static createVectorOfLongsVector(builder, data) {
+ builder.startVector(8, data.length, 8);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addInt64(data[i]);
+ }
+ return builder.endVector();
+ }
+ static startVectorOfLongsVector(builder, numElems) {
+ builder.startVector(8, numElems, 8);
+ }
+ static addVectorOfDoubles(builder, vectorOfDoublesOffset) {
+ builder.addFieldOffset(33, vectorOfDoublesOffset, 0);
+ }
+ static createVectorOfDoublesVector(builder, data) {
+ builder.startVector(8, data.length, 8);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addFloat64(data[i]);
+ }
+ return builder.endVector();
+ }
+ static startVectorOfDoublesVector(builder, numElems) {
+ builder.startVector(8, numElems, 8);
+ }
+ static addParentNamespaceTest(builder, parentNamespaceTestOffset) {
+ builder.addFieldOffset(34, parentNamespaceTestOffset, 0);
+ }
+ static addVectorOfReferrables(builder, vectorOfReferrablesOffset) {
+ builder.addFieldOffset(35, vectorOfReferrablesOffset, 0);
+ }
+ static createVectorOfReferrablesVector(builder, data) {
+ builder.startVector(4, data.length, 4);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addOffset(data[i]);
+ }
+ return builder.endVector();
+ }
+ static startVectorOfReferrablesVector(builder, numElems) {
+ builder.startVector(4, numElems, 4);
+ }
+ static addSingleWeakReference(builder, singleWeakReference) {
+ builder.addFieldInt64(36, singleWeakReference, BigInt('0'));
+ }
+ static addVectorOfWeakReferences(builder, vectorOfWeakReferencesOffset) {
+ builder.addFieldOffset(37, vectorOfWeakReferencesOffset, 0);
+ }
+ static createVectorOfWeakReferencesVector(builder, data) {
+ builder.startVector(8, data.length, 8);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addInt64(data[i]);
+ }
+ return builder.endVector();
+ }
+ static startVectorOfWeakReferencesVector(builder, numElems) {
+ builder.startVector(8, numElems, 8);
+ }
+ static addVectorOfStrongReferrables(builder, vectorOfStrongReferrablesOffset) {
+ builder.addFieldOffset(38, vectorOfStrongReferrablesOffset, 0);
+ }
+ static createVectorOfStrongReferrablesVector(builder, data) {
+ builder.startVector(4, data.length, 4);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addOffset(data[i]);
+ }
+ return builder.endVector();
+ }
+ static startVectorOfStrongReferrablesVector(builder, numElems) {
+ builder.startVector(4, numElems, 4);
+ }
+ static addCoOwningReference(builder, coOwningReference) {
+ builder.addFieldInt64(39, coOwningReference, BigInt('0'));
+ }
+ static addVectorOfCoOwningReferences(builder, vectorOfCoOwningReferencesOffset) {
+ builder.addFieldOffset(40, vectorOfCoOwningReferencesOffset, 0);
+ }
+ static createVectorOfCoOwningReferencesVector(builder, data) {
+ builder.startVector(8, data.length, 8);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addInt64(data[i]);
+ }
+ return builder.endVector();
+ }
+ static startVectorOfCoOwningReferencesVector(builder, numElems) {
+ builder.startVector(8, numElems, 8);
+ }
+ static addNonOwningReference(builder, nonOwningReference) {
+ builder.addFieldInt64(41, nonOwningReference, BigInt('0'));
+ }
+ static addVectorOfNonOwningReferences(builder, vectorOfNonOwningReferencesOffset) {
+ builder.addFieldOffset(42, vectorOfNonOwningReferencesOffset, 0);
+ }
+ static createVectorOfNonOwningReferencesVector(builder, data) {
+ builder.startVector(8, data.length, 8);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addInt64(data[i]);
+ }
+ return builder.endVector();
+ }
+ static startVectorOfNonOwningReferencesVector(builder, numElems) {
+ builder.startVector(8, numElems, 8);
+ }
+ static addAnyUniqueType(builder, anyUniqueType) {
+ builder.addFieldInt8(43, anyUniqueType, AnyUniqueAliases.NONE);
+ }
+ static addAnyUnique(builder, anyUniqueOffset) {
+ builder.addFieldOffset(44, anyUniqueOffset, 0);
+ }
+ static addAnyAmbiguousType(builder, anyAmbiguousType) {
+ builder.addFieldInt8(45, anyAmbiguousType, AnyAmbiguousAliases.NONE);
+ }
+ static addAnyAmbiguous(builder, anyAmbiguousOffset) {
+ builder.addFieldOffset(46, anyAmbiguousOffset, 0);
+ }
+ static addVectorOfEnums(builder, vectorOfEnumsOffset) {
+ builder.addFieldOffset(47, vectorOfEnumsOffset, 0);
+ }
+ static createVectorOfEnumsVector(builder, data) {
+ builder.startVector(1, data.length, 1);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addInt8(data[i]);
+ }
+ return builder.endVector();
+ }
+ static startVectorOfEnumsVector(builder, numElems) {
+ builder.startVector(1, numElems, 1);
+ }
+ static addSignedEnum(builder, signedEnum) {
+ builder.addFieldInt8(48, signedEnum, Race.None);
+ }
+ static addTestrequirednestedflatbuffer(builder, testrequirednestedflatbufferOffset) {
+ builder.addFieldOffset(49, testrequirednestedflatbufferOffset, 0);
+ }
+ static createTestrequirednestedflatbufferVector(builder, data) {
+ builder.startVector(1, data.length, 1);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addInt8(data[i]);
+ }
+ return builder.endVector();
+ }
+ static startTestrequirednestedflatbufferVector(builder, numElems) {
+ builder.startVector(1, numElems, 1);
+ }
+ static addScalarKeySortedTables(builder, scalarKeySortedTablesOffset) {
+ builder.addFieldOffset(50, scalarKeySortedTablesOffset, 0);
+ }
+ static createScalarKeySortedTablesVector(builder, data) {
+ builder.startVector(4, data.length, 4);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addOffset(data[i]);
+ }
+ return builder.endVector();
+ }
+ static startScalarKeySortedTablesVector(builder, numElems) {
+ builder.startVector(4, numElems, 4);
+ }
+ static addNativeInline(builder, nativeInlineOffset) {
+ builder.addFieldStruct(51, nativeInlineOffset, 0);
+ }
+ static addLongEnumNonEnumDefault(builder, longEnumNonEnumDefault) {
+ builder.addFieldInt64(52, longEnumNonEnumDefault, BigInt('0'));
+ }
+ static addLongEnumNormalDefault(builder, longEnumNormalDefault) {
+ builder.addFieldInt64(53, longEnumNormalDefault, BigInt('2'));
+ }
+ static endMonster(builder) {
+ const offset = builder.endObject();
+ builder.requiredField(offset, 10); // name
+ return offset;
+ }
+ static finishMonsterBuffer(builder, offset) {
+ builder.finish(offset, 'MONS');
+ }
+ static finishSizePrefixedMonsterBuffer(builder, offset) {
+ builder.finish(offset, 'MONS', true);
+ }
+ serialize() {
+ return this.bb.bytes();
+ }
+ static deserialize(buffer) {
+ return Monster.getRootAsMonster(new flatbuffers.ByteBuffer(buffer));
+ }
+ unpack() {
+ return new MonsterT((this.pos() !== null ? this.pos().unpack() : null), this.mana(), this.hp(), this.name(), this.bb.createScalarList(this.inventory.bind(this), this.inventoryLength()), this.color(), this.testType(), (() => {
+ let temp = unionToAny(this.testType(), this.test.bind(this));
+ if (temp === null) {
+ return null;
+ }
+ return temp.unpack();
+ })(), this.bb.createObjList(this.test4.bind(this), this.test4Length()), this.bb.createScalarList(this.testarrayofstring.bind(this), this.testarrayofstringLength()), this.bb.createObjList(this.testarrayoftables.bind(this), this.testarrayoftablesLength()), (this.enemy() !== null ? this.enemy().unpack() : null), this.bb.createScalarList(this.testnestedflatbuffer.bind(this), this.testnestedflatbufferLength()), (this.testempty() !== null ? this.testempty().unpack() : null), this.testbool(), this.testhashs32Fnv1(), this.testhashu32Fnv1(), this.testhashs64Fnv1(), this.testhashu64Fnv1(), this.testhashs32Fnv1a(), this.testhashu32Fnv1a(), this.testhashs64Fnv1a(), this.testhashu64Fnv1a(), this.bb.createScalarList(this.testarrayofbools.bind(this), this.testarrayofboolsLength()), this.testf(), this.testf2(), this.testf3(), this.bb.createScalarList(this.testarrayofstring2.bind(this), this.testarrayofstring2Length()), this.bb.createObjList(this.testarrayofsortedstruct.bind(this), this.testarrayofsortedstructLength()), this.bb.createScalarList(this.flex.bind(this), this.flexLength()), this.bb.createObjList(this.test5.bind(this), this.test5Length()), this.bb.createScalarList(this.vectorOfLongs.bind(this), this.vectorOfLongsLength()), this.bb.createScalarList(this.vectorOfDoubles.bind(this), this.vectorOfDoublesLength()), (this.parentNamespaceTest() !== null ? this.parentNamespaceTest().unpack() : null), this.bb.createObjList(this.vectorOfReferrables.bind(this), this.vectorOfReferrablesLength()), this.singleWeakReference(), this.bb.createScalarList(this.vectorOfWeakReferences.bind(this), this.vectorOfWeakReferencesLength()), this.bb.createObjList(this.vectorOfStrongReferrables.bind(this), this.vectorOfStrongReferrablesLength()), this.coOwningReference(), this.bb.createScalarList(this.vectorOfCoOwningReferences.bind(this), this.vectorOfCoOwningReferencesLength()), this.nonOwningReference(), this.bb.createScalarList(this.vectorOfNonOwningReferences.bind(this), this.vectorOfNonOwningReferencesLength()), this.anyUniqueType(), (() => {
+ let temp = unionToAnyUniqueAliases(this.anyUniqueType(), this.anyUnique.bind(this));
+ if (temp === null) {
+ return null;
+ }
+ return temp.unpack();
+ })(), this.anyAmbiguousType(), (() => {
+ let temp = unionToAnyAmbiguousAliases(this.anyAmbiguousType(), this.anyAmbiguous.bind(this));
+ if (temp === null) {
+ return null;
+ }
+ return temp.unpack();
+ })(), this.bb.createScalarList(this.vectorOfEnums.bind(this), this.vectorOfEnumsLength()), this.signedEnum(), this.bb.createScalarList(this.testrequirednestedflatbuffer.bind(this), this.testrequirednestedflatbufferLength()), this.bb.createObjList(this.scalarKeySortedTables.bind(this), this.scalarKeySortedTablesLength()), (this.nativeInline() !== null ? this.nativeInline().unpack() : null), this.longEnumNonEnumDefault(), this.longEnumNormalDefault());
+ }
+ unpackTo(_o) {
+ _o.pos = (this.pos() !== null ? this.pos().unpack() : null);
+ _o.mana = this.mana();
+ _o.hp = this.hp();
+ _o.name = this.name();
+ _o.inventory = this.bb.createScalarList(this.inventory.bind(this), this.inventoryLength());
+ _o.color = this.color();
+ _o.testType = this.testType();
+ _o.test = (() => {
+ let temp = unionToAny(this.testType(), this.test.bind(this));
+ if (temp === null) {
+ return null;
+ }
+ return temp.unpack();
+ })();
+ _o.test4 = this.bb.createObjList(this.test4.bind(this), this.test4Length());
+ _o.testarrayofstring = this.bb.createScalarList(this.testarrayofstring.bind(this), this.testarrayofstringLength());
+ _o.testarrayoftables = this.bb.createObjList(this.testarrayoftables.bind(this), this.testarrayoftablesLength());
+ _o.enemy = (this.enemy() !== null ? this.enemy().unpack() : null);
+ _o.testnestedflatbuffer = this.bb.createScalarList(this.testnestedflatbuffer.bind(this), this.testnestedflatbufferLength());
+ _o.testempty = (this.testempty() !== null ? this.testempty().unpack() : null);
+ _o.testbool = this.testbool();
+ _o.testhashs32Fnv1 = this.testhashs32Fnv1();
+ _o.testhashu32Fnv1 = this.testhashu32Fnv1();
+ _o.testhashs64Fnv1 = this.testhashs64Fnv1();
+ _o.testhashu64Fnv1 = this.testhashu64Fnv1();
+ _o.testhashs32Fnv1a = this.testhashs32Fnv1a();
+ _o.testhashu32Fnv1a = this.testhashu32Fnv1a();
+ _o.testhashs64Fnv1a = this.testhashs64Fnv1a();
+ _o.testhashu64Fnv1a = this.testhashu64Fnv1a();
+ _o.testarrayofbools = this.bb.createScalarList(this.testarrayofbools.bind(this), this.testarrayofboolsLength());
+ _o.testf = this.testf();
+ _o.testf2 = this.testf2();
+ _o.testf3 = this.testf3();
+ _o.testarrayofstring2 = this.bb.createScalarList(this.testarrayofstring2.bind(this), this.testarrayofstring2Length());
+ _o.testarrayofsortedstruct = this.bb.createObjList(this.testarrayofsortedstruct.bind(this), this.testarrayofsortedstructLength());
+ _o.flex = this.bb.createScalarList(this.flex.bind(this), this.flexLength());
+ _o.test5 = this.bb.createObjList(this.test5.bind(this), this.test5Length());
+ _o.vectorOfLongs = this.bb.createScalarList(this.vectorOfLongs.bind(this), this.vectorOfLongsLength());
+ _o.vectorOfDoubles = this.bb.createScalarList(this.vectorOfDoubles.bind(this), this.vectorOfDoublesLength());
+ _o.parentNamespaceTest = (this.parentNamespaceTest() !== null ? this.parentNamespaceTest().unpack() : null);
+ _o.vectorOfReferrables = this.bb.createObjList(this.vectorOfReferrables.bind(this), this.vectorOfReferrablesLength());
+ _o.singleWeakReference = this.singleWeakReference();
+ _o.vectorOfWeakReferences = this.bb.createScalarList(this.vectorOfWeakReferences.bind(this), this.vectorOfWeakReferencesLength());
+ _o.vectorOfStrongReferrables = this.bb.createObjList(this.vectorOfStrongReferrables.bind(this), this.vectorOfStrongReferrablesLength());
+ _o.coOwningReference = this.coOwningReference();
+ _o.vectorOfCoOwningReferences = this.bb.createScalarList(this.vectorOfCoOwningReferences.bind(this), this.vectorOfCoOwningReferencesLength());
+ _o.nonOwningReference = this.nonOwningReference();
+ _o.vectorOfNonOwningReferences = this.bb.createScalarList(this.vectorOfNonOwningReferences.bind(this), this.vectorOfNonOwningReferencesLength());
+ _o.anyUniqueType = this.anyUniqueType();
+ _o.anyUnique = (() => {
+ let temp = unionToAnyUniqueAliases(this.anyUniqueType(), this.anyUnique.bind(this));
+ if (temp === null) {
+ return null;
+ }
+ return temp.unpack();
+ })();
+ _o.anyAmbiguousType = this.anyAmbiguousType();
+ _o.anyAmbiguous = (() => {
+ let temp = unionToAnyAmbiguousAliases(this.anyAmbiguousType(), this.anyAmbiguous.bind(this));
+ if (temp === null) {
+ return null;
+ }
+ return temp.unpack();
+ })();
+ _o.vectorOfEnums = this.bb.createScalarList(this.vectorOfEnums.bind(this), this.vectorOfEnumsLength());
+ _o.signedEnum = this.signedEnum();
+ _o.testrequirednestedflatbuffer = this.bb.createScalarList(this.testrequirednestedflatbuffer.bind(this), this.testrequirednestedflatbufferLength());
+ _o.scalarKeySortedTables = this.bb.createObjList(this.scalarKeySortedTables.bind(this), this.scalarKeySortedTablesLength());
+ _o.nativeInline = (this.nativeInline() !== null ? this.nativeInline().unpack() : null);
+ _o.longEnumNonEnumDefault = this.longEnumNonEnumDefault();
+ _o.longEnumNormalDefault = this.longEnumNormalDefault();
+ }
+}
+export class MonsterT {
+ constructor(pos = null, mana = 150, hp = 100, name = null, inventory = [], color = Color.Blue, testType = Any.NONE, test = null, test4 = [], testarrayofstring = [], testarrayoftables = [], enemy = null, testnestedflatbuffer = [], testempty = null, testbool = false, testhashs32Fnv1 = 0, testhashu32Fnv1 = 0, testhashs64Fnv1 = BigInt('0'), testhashu64Fnv1 = BigInt('0'), testhashs32Fnv1a = 0, testhashu32Fnv1a = 0, testhashs64Fnv1a = BigInt('0'), testhashu64Fnv1a = BigInt('0'), testarrayofbools = [], testf = 3.14159, testf2 = 3.0, testf3 = 0.0, testarrayofstring2 = [], testarrayofsortedstruct = [], flex = [], test5 = [], vectorOfLongs = [], vectorOfDoubles = [], parentNamespaceTest = null, vectorOfReferrables = [], singleWeakReference = BigInt('0'), vectorOfWeakReferences = [], vectorOfStrongReferrables = [], coOwningReference = BigInt('0'), vectorOfCoOwningReferences = [], nonOwningReference = BigInt('0'), vectorOfNonOwningReferences = [], anyUniqueType = AnyUniqueAliases.NONE, anyUnique = null, anyAmbiguousType = AnyAmbiguousAliases.NONE, anyAmbiguous = null, vectorOfEnums = [], signedEnum = Race.None, testrequirednestedflatbuffer = [], scalarKeySortedTables = [], nativeInline = null, longEnumNonEnumDefault = BigInt('0'), longEnumNormalDefault = BigInt('2')) {
+ this.pos = pos;
+ this.mana = mana;
+ this.hp = hp;
+ this.name = name;
+ this.inventory = inventory;
+ this.color = color;
+ this.testType = testType;
+ this.test = test;
+ this.test4 = test4;
+ this.testarrayofstring = testarrayofstring;
+ this.testarrayoftables = testarrayoftables;
+ this.enemy = enemy;
+ this.testnestedflatbuffer = testnestedflatbuffer;
+ this.testempty = testempty;
+ this.testbool = testbool;
+ this.testhashs32Fnv1 = testhashs32Fnv1;
+ this.testhashu32Fnv1 = testhashu32Fnv1;
+ this.testhashs64Fnv1 = testhashs64Fnv1;
+ this.testhashu64Fnv1 = testhashu64Fnv1;
+ this.testhashs32Fnv1a = testhashs32Fnv1a;
+ this.testhashu32Fnv1a = testhashu32Fnv1a;
+ this.testhashs64Fnv1a = testhashs64Fnv1a;
+ this.testhashu64Fnv1a = testhashu64Fnv1a;
+ this.testarrayofbools = testarrayofbools;
+ this.testf = testf;
+ this.testf2 = testf2;
+ this.testf3 = testf3;
+ this.testarrayofstring2 = testarrayofstring2;
+ this.testarrayofsortedstruct = testarrayofsortedstruct;
+ this.flex = flex;
+ this.test5 = test5;
+ this.vectorOfLongs = vectorOfLongs;
+ this.vectorOfDoubles = vectorOfDoubles;
+ this.parentNamespaceTest = parentNamespaceTest;
+ this.vectorOfReferrables = vectorOfReferrables;
+ this.singleWeakReference = singleWeakReference;
+ this.vectorOfWeakReferences = vectorOfWeakReferences;
+ this.vectorOfStrongReferrables = vectorOfStrongReferrables;
+ this.coOwningReference = coOwningReference;
+ this.vectorOfCoOwningReferences = vectorOfCoOwningReferences;
+ this.nonOwningReference = nonOwningReference;
+ this.vectorOfNonOwningReferences = vectorOfNonOwningReferences;
+ this.anyUniqueType = anyUniqueType;
+ this.anyUnique = anyUnique;
+ this.anyAmbiguousType = anyAmbiguousType;
+ this.anyAmbiguous = anyAmbiguous;
+ this.vectorOfEnums = vectorOfEnums;
+ this.signedEnum = signedEnum;
+ this.testrequirednestedflatbuffer = testrequirednestedflatbuffer;
+ this.scalarKeySortedTables = scalarKeySortedTables;
+ this.nativeInline = nativeInline;
+ this.longEnumNonEnumDefault = longEnumNonEnumDefault;
+ this.longEnumNormalDefault = longEnumNormalDefault;
+ }
+ pack(builder) {
+ const name = (this.name !== null ? builder.createString(this.name) : 0);
+ const inventory = Monster.createInventoryVector(builder, this.inventory);
+ const test = builder.createObjectOffset(this.test);
+ const test4 = builder.createStructOffsetList(this.test4, Monster.startTest4Vector);
+ const testarrayofstring = Monster.createTestarrayofstringVector(builder, builder.createObjectOffsetList(this.testarrayofstring));
+ const testarrayoftables = Monster.createTestarrayoftablesVector(builder, builder.createObjectOffsetList(this.testarrayoftables));
+ const enemy = (this.enemy !== null ? this.enemy.pack(builder) : 0);
+ const testnestedflatbuffer = Monster.createTestnestedflatbufferVector(builder, this.testnestedflatbuffer);
+ const testempty = (this.testempty !== null ? this.testempty.pack(builder) : 0);
+ const testarrayofbools = Monster.createTestarrayofboolsVector(builder, this.testarrayofbools);
+ const testarrayofstring2 = Monster.createTestarrayofstring2Vector(builder, builder.createObjectOffsetList(this.testarrayofstring2));
+ const testarrayofsortedstruct = builder.createStructOffsetList(this.testarrayofsortedstruct, Monster.startTestarrayofsortedstructVector);
+ const flex = Monster.createFlexVector(builder, this.flex);
+ const test5 = builder.createStructOffsetList(this.test5, Monster.startTest5Vector);
+ const vectorOfLongs = Monster.createVectorOfLongsVector(builder, this.vectorOfLongs);
+ const vectorOfDoubles = Monster.createVectorOfDoublesVector(builder, this.vectorOfDoubles);
+ const parentNamespaceTest = (this.parentNamespaceTest !== null ? this.parentNamespaceTest.pack(builder) : 0);
+ const vectorOfReferrables = Monster.createVectorOfReferrablesVector(builder, builder.createObjectOffsetList(this.vectorOfReferrables));
+ const vectorOfWeakReferences = Monster.createVectorOfWeakReferencesVector(builder, this.vectorOfWeakReferences);
+ const vectorOfStrongReferrables = Monster.createVectorOfStrongReferrablesVector(builder, builder.createObjectOffsetList(this.vectorOfStrongReferrables));
+ const vectorOfCoOwningReferences = Monster.createVectorOfCoOwningReferencesVector(builder, this.vectorOfCoOwningReferences);
+ const vectorOfNonOwningReferences = Monster.createVectorOfNonOwningReferencesVector(builder, this.vectorOfNonOwningReferences);
+ const anyUnique = builder.createObjectOffset(this.anyUnique);
+ const anyAmbiguous = builder.createObjectOffset(this.anyAmbiguous);
+ const vectorOfEnums = Monster.createVectorOfEnumsVector(builder, this.vectorOfEnums);
+ const testrequirednestedflatbuffer = Monster.createTestrequirednestedflatbufferVector(builder, this.testrequirednestedflatbuffer);
+ const scalarKeySortedTables = Monster.createScalarKeySortedTablesVector(builder, builder.createObjectOffsetList(this.scalarKeySortedTables));
+ Monster.startMonster(builder);
+ Monster.addPos(builder, (this.pos !== null ? this.pos.pack(builder) : 0));
+ Monster.addMana(builder, this.mana);
+ Monster.addHp(builder, this.hp);
+ Monster.addName(builder, name);
+ Monster.addInventory(builder, inventory);
+ Monster.addColor(builder, this.color);
+ Monster.addTestType(builder, this.testType);
+ Monster.addTest(builder, test);
+ Monster.addTest4(builder, test4);
+ Monster.addTestarrayofstring(builder, testarrayofstring);
+ Monster.addTestarrayoftables(builder, testarrayoftables);
+ Monster.addEnemy(builder, enemy);
+ Monster.addTestnestedflatbuffer(builder, testnestedflatbuffer);
+ Monster.addTestempty(builder, testempty);
+ Monster.addTestbool(builder, this.testbool);
+ Monster.addTesthashs32Fnv1(builder, this.testhashs32Fnv1);
+ Monster.addTesthashu32Fnv1(builder, this.testhashu32Fnv1);
+ Monster.addTesthashs64Fnv1(builder, this.testhashs64Fnv1);
+ Monster.addTesthashu64Fnv1(builder, this.testhashu64Fnv1);
+ Monster.addTesthashs32Fnv1a(builder, this.testhashs32Fnv1a);
+ Monster.addTesthashu32Fnv1a(builder, this.testhashu32Fnv1a);
+ Monster.addTesthashs64Fnv1a(builder, this.testhashs64Fnv1a);
+ Monster.addTesthashu64Fnv1a(builder, this.testhashu64Fnv1a);
+ Monster.addTestarrayofbools(builder, testarrayofbools);
+ Monster.addTestf(builder, this.testf);
+ Monster.addTestf2(builder, this.testf2);
+ Monster.addTestf3(builder, this.testf3);
+ Monster.addTestarrayofstring2(builder, testarrayofstring2);
+ Monster.addTestarrayofsortedstruct(builder, testarrayofsortedstruct);
+ Monster.addFlex(builder, flex);
+ Monster.addTest5(builder, test5);
+ Monster.addVectorOfLongs(builder, vectorOfLongs);
+ Monster.addVectorOfDoubles(builder, vectorOfDoubles);
+ Monster.addParentNamespaceTest(builder, parentNamespaceTest);
+ Monster.addVectorOfReferrables(builder, vectorOfReferrables);
+ Monster.addSingleWeakReference(builder, this.singleWeakReference);
+ Monster.addVectorOfWeakReferences(builder, vectorOfWeakReferences);
+ Monster.addVectorOfStrongReferrables(builder, vectorOfStrongReferrables);
+ Monster.addCoOwningReference(builder, this.coOwningReference);
+ Monster.addVectorOfCoOwningReferences(builder, vectorOfCoOwningReferences);
+ Monster.addNonOwningReference(builder, this.nonOwningReference);
+ Monster.addVectorOfNonOwningReferences(builder, vectorOfNonOwningReferences);
+ Monster.addAnyUniqueType(builder, this.anyUniqueType);
+ Monster.addAnyUnique(builder, anyUnique);
+ Monster.addAnyAmbiguousType(builder, this.anyAmbiguousType);
+ Monster.addAnyAmbiguous(builder, anyAmbiguous);
+ Monster.addVectorOfEnums(builder, vectorOfEnums);
+ Monster.addSignedEnum(builder, this.signedEnum);
+ Monster.addTestrequirednestedflatbuffer(builder, testrequirednestedflatbuffer);
+ Monster.addScalarKeySortedTables(builder, scalarKeySortedTables);
+ Monster.addNativeInline(builder, (this.nativeInline !== null ? this.nativeInline.pack(builder) : 0));
+ Monster.addLongEnumNonEnumDefault(builder, this.longEnumNonEnumDefault);
+ Monster.addLongEnumNormalDefault(builder, this.longEnumNormalDefault);
+ return Monster.endMonster(builder);
+ }
+}
diff --git a/tests/my-game/example/monster.ts b/tests/my-game/example/monster.ts
new file mode 100644
index 0000000..c6cb33e
--- /dev/null
+++ b/tests/my-game/example/monster.ts
@@ -0,0 +1,1434 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+import * as flatbuffers from 'flatbuffers';
+
+import { Monster as MyGameExample2Monster, MonsterT as MyGameExample2MonsterT } from '../../my-game/example2/monster';
+import { Ability, AbilityT } from '../../my-game/example/ability';
+import { Any, unionToAny, unionListToAny } from '../../my-game/example/any';
+import { AnyAmbiguousAliases, unionToAnyAmbiguousAliases, unionListToAnyAmbiguousAliases } from '../../my-game/example/any-ambiguous-aliases';
+import { AnyUniqueAliases, unionToAnyUniqueAliases, unionListToAnyUniqueAliases } from '../../my-game/example/any-unique-aliases';
+import { Color } from '../../my-game/example/color';
+import { Race } from '../../my-game/example/race';
+import { Referrable, ReferrableT } from '../../my-game/example/referrable';
+import { Stat, StatT } from '../../my-game/example/stat';
+import { Test, TestT } from '../../my-game/example/test';
+import { TestSimpleTableWithEnum, TestSimpleTableWithEnumT } from '../../my-game/example/test-simple-table-with-enum';
+import { Vec3, Vec3T } from '../../my-game/example/vec3';
+import { InParentNamespace, InParentNamespaceT } from '../../my-game/in-parent-namespace';
+
+
+/**
+ * an example documentation comment: "monster object"
+ */
+export class Monster {
+ bb: flatbuffers.ByteBuffer|null = null;
+ bb_pos = 0;
+__init(i:number, bb:flatbuffers.ByteBuffer):Monster {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+}
+
+static getRootAsMonster(bb:flatbuffers.ByteBuffer, obj?:Monster):Monster {
+ return (obj || new Monster()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+}
+
+static getSizePrefixedRootAsMonster(bb:flatbuffers.ByteBuffer, obj?:Monster):Monster {
+ bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new Monster()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+}
+
+static bufferHasIdentifier(bb:flatbuffers.ByteBuffer):boolean {
+ return bb.__has_identifier('MONS');
+}
+
+pos(obj?:Vec3):Vec3|null {
+ const offset = this.bb!.__offset(this.bb_pos, 4);
+ return offset ? (obj || new Vec3()).__init(this.bb_pos + offset, this.bb!) : null;
+}
+
+mana():number {
+ const offset = this.bb!.__offset(this.bb_pos, 6);
+ return offset ? this.bb!.readInt16(this.bb_pos + offset) : 150;
+}
+
+mutate_mana(value:number):boolean {
+ const offset = this.bb!.__offset(this.bb_pos, 6);
+
+ if (offset === 0) {
+ return false;
+ }
+
+ this.bb!.writeInt16(this.bb_pos + offset, value);
+ return true;
+}
+
+hp():number {
+ const offset = this.bb!.__offset(this.bb_pos, 8);
+ return offset ? this.bb!.readInt16(this.bb_pos + offset) : 100;
+}
+
+mutate_hp(value:number):boolean {
+ const offset = this.bb!.__offset(this.bb_pos, 8);
+
+ if (offset === 0) {
+ return false;
+ }
+
+ this.bb!.writeInt16(this.bb_pos + offset, value);
+ return true;
+}
+
+name():string|null
+name(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null
+name(optionalEncoding?:any):string|Uint8Array|null {
+ const offset = this.bb!.__offset(this.bb_pos, 10);
+ return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
+}
+
+inventory(index: number):number|null {
+ const offset = this.bb!.__offset(this.bb_pos, 14);
+ return offset ? this.bb!.readUint8(this.bb!.__vector(this.bb_pos + offset) + index) : 0;
+}
+
+inventoryLength():number {
+ const offset = this.bb!.__offset(this.bb_pos, 14);
+ return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
+}
+
+inventoryArray():Uint8Array|null {
+ const offset = this.bb!.__offset(this.bb_pos, 14);
+ return offset ? new Uint8Array(this.bb!.bytes().buffer, this.bb!.bytes().byteOffset + this.bb!.__vector(this.bb_pos + offset), this.bb!.__vector_len(this.bb_pos + offset)) : null;
+}
+
+color():Color {
+ const offset = this.bb!.__offset(this.bb_pos, 16);
+ return offset ? this.bb!.readUint8(this.bb_pos + offset) : Color.Blue;
+}
+
+mutate_color(value:Color):boolean {
+ const offset = this.bb!.__offset(this.bb_pos, 16);
+
+ if (offset === 0) {
+ return false;
+ }
+
+ this.bb!.writeUint8(this.bb_pos + offset, value);
+ return true;
+}
+
+testType():Any {
+ const offset = this.bb!.__offset(this.bb_pos, 18);
+ return offset ? this.bb!.readUint8(this.bb_pos + offset) : Any.NONE;
+}
+
+test<T extends flatbuffers.Table>(obj:any):any|null {
+ const offset = this.bb!.__offset(this.bb_pos, 20);
+ return offset ? this.bb!.__union(obj, this.bb_pos + offset) : null;
+}
+
+test4(index: number, obj?:Test):Test|null {
+ const offset = this.bb!.__offset(this.bb_pos, 22);
+ return offset ? (obj || new Test()).__init(this.bb!.__vector(this.bb_pos + offset) + index * 4, this.bb!) : null;
+}
+
+test4Length():number {
+ const offset = this.bb!.__offset(this.bb_pos, 22);
+ return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
+}
+
+testarrayofstring(index: number):string
+testarrayofstring(index: number,optionalEncoding:flatbuffers.Encoding):string|Uint8Array
+testarrayofstring(index: number,optionalEncoding?:any):string|Uint8Array|null {
+ const offset = this.bb!.__offset(this.bb_pos, 24);
+ return offset ? this.bb!.__string(this.bb!.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null;
+}
+
+testarrayofstringLength():number {
+ const offset = this.bb!.__offset(this.bb_pos, 24);
+ return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
+}
+
+/**
+ * an example documentation comment: this will end up in the generated code
+ * multiline too
+ */
+testarrayoftables(index: number, obj?:Monster):Monster|null {
+ const offset = this.bb!.__offset(this.bb_pos, 26);
+ return offset ? (obj || new Monster()).__init(this.bb!.__indirect(this.bb!.__vector(this.bb_pos + offset) + index * 4), this.bb!) : null;
+}
+
+testarrayoftablesLength():number {
+ const offset = this.bb!.__offset(this.bb_pos, 26);
+ return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
+}
+
+enemy(obj?:Monster):Monster|null {
+ const offset = this.bb!.__offset(this.bb_pos, 28);
+ return offset ? (obj || new Monster()).__init(this.bb!.__indirect(this.bb_pos + offset), this.bb!) : null;
+}
+
+testnestedflatbuffer(index: number):number|null {
+ const offset = this.bb!.__offset(this.bb_pos, 30);
+ return offset ? this.bb!.readUint8(this.bb!.__vector(this.bb_pos + offset) + index) : 0;
+}
+
+testnestedflatbufferLength():number {
+ const offset = this.bb!.__offset(this.bb_pos, 30);
+ return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
+}
+
+testnestedflatbufferArray():Uint8Array|null {
+ const offset = this.bb!.__offset(this.bb_pos, 30);
+ return offset ? new Uint8Array(this.bb!.bytes().buffer, this.bb!.bytes().byteOffset + this.bb!.__vector(this.bb_pos + offset), this.bb!.__vector_len(this.bb_pos + offset)) : null;
+}
+
+testempty(obj?:Stat):Stat|null {
+ const offset = this.bb!.__offset(this.bb_pos, 32);
+ return offset ? (obj || new Stat()).__init(this.bb!.__indirect(this.bb_pos + offset), this.bb!) : null;
+}
+
+testbool():boolean {
+ const offset = this.bb!.__offset(this.bb_pos, 34);
+ return offset ? !!this.bb!.readInt8(this.bb_pos + offset) : false;
+}
+
+mutate_testbool(value:boolean):boolean {
+ const offset = this.bb!.__offset(this.bb_pos, 34);
+
+ if (offset === 0) {
+ return false;
+ }
+
+ this.bb!.writeInt8(this.bb_pos + offset, +value);
+ return true;
+}
+
+testhashs32Fnv1():number {
+ const offset = this.bb!.__offset(this.bb_pos, 36);
+ return offset ? this.bb!.readInt32(this.bb_pos + offset) : 0;
+}
+
+mutate_testhashs32_fnv1(value:number):boolean {
+ const offset = this.bb!.__offset(this.bb_pos, 36);
+
+ if (offset === 0) {
+ return false;
+ }
+
+ this.bb!.writeInt32(this.bb_pos + offset, value);
+ return true;
+}
+
+testhashu32Fnv1():number {
+ const offset = this.bb!.__offset(this.bb_pos, 38);
+ return offset ? this.bb!.readUint32(this.bb_pos + offset) : 0;
+}
+
+mutate_testhashu32_fnv1(value:number):boolean {
+ const offset = this.bb!.__offset(this.bb_pos, 38);
+
+ if (offset === 0) {
+ return false;
+ }
+
+ this.bb!.writeUint32(this.bb_pos + offset, value);
+ return true;
+}
+
+testhashs64Fnv1():bigint {
+ const offset = this.bb!.__offset(this.bb_pos, 40);
+ return offset ? this.bb!.readInt64(this.bb_pos + offset) : BigInt('0');
+}
+
+mutate_testhashs64_fnv1(value:bigint):boolean {
+ const offset = this.bb!.__offset(this.bb_pos, 40);
+
+ if (offset === 0) {
+ return false;
+ }
+
+ this.bb!.writeInt64(this.bb_pos + offset, value);
+ return true;
+}
+
+testhashu64Fnv1():bigint {
+ const offset = this.bb!.__offset(this.bb_pos, 42);
+ return offset ? this.bb!.readUint64(this.bb_pos + offset) : BigInt('0');
+}
+
+mutate_testhashu64_fnv1(value:bigint):boolean {
+ const offset = this.bb!.__offset(this.bb_pos, 42);
+
+ if (offset === 0) {
+ return false;
+ }
+
+ this.bb!.writeUint64(this.bb_pos + offset, value);
+ return true;
+}
+
+testhashs32Fnv1a():number {
+ const offset = this.bb!.__offset(this.bb_pos, 44);
+ return offset ? this.bb!.readInt32(this.bb_pos + offset) : 0;
+}
+
+mutate_testhashs32_fnv1a(value:number):boolean {
+ const offset = this.bb!.__offset(this.bb_pos, 44);
+
+ if (offset === 0) {
+ return false;
+ }
+
+ this.bb!.writeInt32(this.bb_pos + offset, value);
+ return true;
+}
+
+testhashu32Fnv1a():number {
+ const offset = this.bb!.__offset(this.bb_pos, 46);
+ return offset ? this.bb!.readUint32(this.bb_pos + offset) : 0;
+}
+
+mutate_testhashu32_fnv1a(value:number):boolean {
+ const offset = this.bb!.__offset(this.bb_pos, 46);
+
+ if (offset === 0) {
+ return false;
+ }
+
+ this.bb!.writeUint32(this.bb_pos + offset, value);
+ return true;
+}
+
+testhashs64Fnv1a():bigint {
+ const offset = this.bb!.__offset(this.bb_pos, 48);
+ return offset ? this.bb!.readInt64(this.bb_pos + offset) : BigInt('0');
+}
+
+mutate_testhashs64_fnv1a(value:bigint):boolean {
+ const offset = this.bb!.__offset(this.bb_pos, 48);
+
+ if (offset === 0) {
+ return false;
+ }
+
+ this.bb!.writeInt64(this.bb_pos + offset, value);
+ return true;
+}
+
+testhashu64Fnv1a():bigint {
+ const offset = this.bb!.__offset(this.bb_pos, 50);
+ return offset ? this.bb!.readUint64(this.bb_pos + offset) : BigInt('0');
+}
+
+mutate_testhashu64_fnv1a(value:bigint):boolean {
+ const offset = this.bb!.__offset(this.bb_pos, 50);
+
+ if (offset === 0) {
+ return false;
+ }
+
+ this.bb!.writeUint64(this.bb_pos + offset, value);
+ return true;
+}
+
+testarrayofbools(index: number):boolean|null {
+ const offset = this.bb!.__offset(this.bb_pos, 52);
+ return offset ? !!this.bb!.readInt8(this.bb!.__vector(this.bb_pos + offset) + index) : false;
+}
+
+testarrayofboolsLength():number {
+ const offset = this.bb!.__offset(this.bb_pos, 52);
+ return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
+}
+
+testarrayofboolsArray():Int8Array|null {
+ const offset = this.bb!.__offset(this.bb_pos, 52);
+ return offset ? new Int8Array(this.bb!.bytes().buffer, this.bb!.bytes().byteOffset + this.bb!.__vector(this.bb_pos + offset), this.bb!.__vector_len(this.bb_pos + offset)) : null;
+}
+
+testf():number {
+ const offset = this.bb!.__offset(this.bb_pos, 54);
+ return offset ? this.bb!.readFloat32(this.bb_pos + offset) : 3.14159;
+}
+
+mutate_testf(value:number):boolean {
+ const offset = this.bb!.__offset(this.bb_pos, 54);
+
+ if (offset === 0) {
+ return false;
+ }
+
+ this.bb!.writeFloat32(this.bb_pos + offset, value);
+ return true;
+}
+
+testf2():number {
+ const offset = this.bb!.__offset(this.bb_pos, 56);
+ return offset ? this.bb!.readFloat32(this.bb_pos + offset) : 3.0;
+}
+
+mutate_testf2(value:number):boolean {
+ const offset = this.bb!.__offset(this.bb_pos, 56);
+
+ if (offset === 0) {
+ return false;
+ }
+
+ this.bb!.writeFloat32(this.bb_pos + offset, value);
+ return true;
+}
+
+testf3():number {
+ const offset = this.bb!.__offset(this.bb_pos, 58);
+ return offset ? this.bb!.readFloat32(this.bb_pos + offset) : 0.0;
+}
+
+mutate_testf3(value:number):boolean {
+ const offset = this.bb!.__offset(this.bb_pos, 58);
+
+ if (offset === 0) {
+ return false;
+ }
+
+ this.bb!.writeFloat32(this.bb_pos + offset, value);
+ return true;
+}
+
+testarrayofstring2(index: number):string
+testarrayofstring2(index: number,optionalEncoding:flatbuffers.Encoding):string|Uint8Array
+testarrayofstring2(index: number,optionalEncoding?:any):string|Uint8Array|null {
+ const offset = this.bb!.__offset(this.bb_pos, 60);
+ return offset ? this.bb!.__string(this.bb!.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null;
+}
+
+testarrayofstring2Length():number {
+ const offset = this.bb!.__offset(this.bb_pos, 60);
+ return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
+}
+
+testarrayofsortedstruct(index: number, obj?:Ability):Ability|null {
+ const offset = this.bb!.__offset(this.bb_pos, 62);
+ return offset ? (obj || new Ability()).__init(this.bb!.__vector(this.bb_pos + offset) + index * 8, this.bb!) : null;
+}
+
+testarrayofsortedstructLength():number {
+ const offset = this.bb!.__offset(this.bb_pos, 62);
+ return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
+}
+
+flex(index: number):number|null {
+ const offset = this.bb!.__offset(this.bb_pos, 64);
+ return offset ? this.bb!.readUint8(this.bb!.__vector(this.bb_pos + offset) + index) : 0;
+}
+
+flexLength():number {
+ const offset = this.bb!.__offset(this.bb_pos, 64);
+ return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
+}
+
+flexArray():Uint8Array|null {
+ const offset = this.bb!.__offset(this.bb_pos, 64);
+ return offset ? new Uint8Array(this.bb!.bytes().buffer, this.bb!.bytes().byteOffset + this.bb!.__vector(this.bb_pos + offset), this.bb!.__vector_len(this.bb_pos + offset)) : null;
+}
+
+test5(index: number, obj?:Test):Test|null {
+ const offset = this.bb!.__offset(this.bb_pos, 66);
+ return offset ? (obj || new Test()).__init(this.bb!.__vector(this.bb_pos + offset) + index * 4, this.bb!) : null;
+}
+
+test5Length():number {
+ const offset = this.bb!.__offset(this.bb_pos, 66);
+ return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
+}
+
+vectorOfLongs(index: number):bigint|null {
+ const offset = this.bb!.__offset(this.bb_pos, 68);
+ return offset ? this.bb!.readInt64(this.bb!.__vector(this.bb_pos + offset) + index * 8) : BigInt(0);
+}
+
+vectorOfLongsLength():number {
+ const offset = this.bb!.__offset(this.bb_pos, 68);
+ return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
+}
+
+vectorOfDoubles(index: number):number|null {
+ const offset = this.bb!.__offset(this.bb_pos, 70);
+ return offset ? this.bb!.readFloat64(this.bb!.__vector(this.bb_pos + offset) + index * 8) : 0;
+}
+
+vectorOfDoublesLength():number {
+ const offset = this.bb!.__offset(this.bb_pos, 70);
+ return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
+}
+
+vectorOfDoublesArray():Float64Array|null {
+ const offset = this.bb!.__offset(this.bb_pos, 70);
+ return offset ? new Float64Array(this.bb!.bytes().buffer, this.bb!.bytes().byteOffset + this.bb!.__vector(this.bb_pos + offset), this.bb!.__vector_len(this.bb_pos + offset)) : null;
+}
+
+parentNamespaceTest(obj?:InParentNamespace):InParentNamespace|null {
+ const offset = this.bb!.__offset(this.bb_pos, 72);
+ return offset ? (obj || new InParentNamespace()).__init(this.bb!.__indirect(this.bb_pos + offset), this.bb!) : null;
+}
+
+vectorOfReferrables(index: number, obj?:Referrable):Referrable|null {
+ const offset = this.bb!.__offset(this.bb_pos, 74);
+ return offset ? (obj || new Referrable()).__init(this.bb!.__indirect(this.bb!.__vector(this.bb_pos + offset) + index * 4), this.bb!) : null;
+}
+
+vectorOfReferrablesLength():number {
+ const offset = this.bb!.__offset(this.bb_pos, 74);
+ return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
+}
+
+singleWeakReference():bigint {
+ const offset = this.bb!.__offset(this.bb_pos, 76);
+ return offset ? this.bb!.readUint64(this.bb_pos + offset) : BigInt('0');
+}
+
+mutate_single_weak_reference(value:bigint):boolean {
+ const offset = this.bb!.__offset(this.bb_pos, 76);
+
+ if (offset === 0) {
+ return false;
+ }
+
+ this.bb!.writeUint64(this.bb_pos + offset, value);
+ return true;
+}
+
+vectorOfWeakReferences(index: number):bigint|null {
+ const offset = this.bb!.__offset(this.bb_pos, 78);
+ return offset ? this.bb!.readUint64(this.bb!.__vector(this.bb_pos + offset) + index * 8) : BigInt(0);
+}
+
+vectorOfWeakReferencesLength():number {
+ const offset = this.bb!.__offset(this.bb_pos, 78);
+ return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
+}
+
+vectorOfStrongReferrables(index: number, obj?:Referrable):Referrable|null {
+ const offset = this.bb!.__offset(this.bb_pos, 80);
+ return offset ? (obj || new Referrable()).__init(this.bb!.__indirect(this.bb!.__vector(this.bb_pos + offset) + index * 4), this.bb!) : null;
+}
+
+vectorOfStrongReferrablesLength():number {
+ const offset = this.bb!.__offset(this.bb_pos, 80);
+ return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
+}
+
+coOwningReference():bigint {
+ const offset = this.bb!.__offset(this.bb_pos, 82);
+ return offset ? this.bb!.readUint64(this.bb_pos + offset) : BigInt('0');
+}
+
+mutate_co_owning_reference(value:bigint):boolean {
+ const offset = this.bb!.__offset(this.bb_pos, 82);
+
+ if (offset === 0) {
+ return false;
+ }
+
+ this.bb!.writeUint64(this.bb_pos + offset, value);
+ return true;
+}
+
+vectorOfCoOwningReferences(index: number):bigint|null {
+ const offset = this.bb!.__offset(this.bb_pos, 84);
+ return offset ? this.bb!.readUint64(this.bb!.__vector(this.bb_pos + offset) + index * 8) : BigInt(0);
+}
+
+vectorOfCoOwningReferencesLength():number {
+ const offset = this.bb!.__offset(this.bb_pos, 84);
+ return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
+}
+
+nonOwningReference():bigint {
+ const offset = this.bb!.__offset(this.bb_pos, 86);
+ return offset ? this.bb!.readUint64(this.bb_pos + offset) : BigInt('0');
+}
+
+mutate_non_owning_reference(value:bigint):boolean {
+ const offset = this.bb!.__offset(this.bb_pos, 86);
+
+ if (offset === 0) {
+ return false;
+ }
+
+ this.bb!.writeUint64(this.bb_pos + offset, value);
+ return true;
+}
+
+vectorOfNonOwningReferences(index: number):bigint|null {
+ const offset = this.bb!.__offset(this.bb_pos, 88);
+ return offset ? this.bb!.readUint64(this.bb!.__vector(this.bb_pos + offset) + index * 8) : BigInt(0);
+}
+
+vectorOfNonOwningReferencesLength():number {
+ const offset = this.bb!.__offset(this.bb_pos, 88);
+ return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
+}
+
+anyUniqueType():AnyUniqueAliases {
+ const offset = this.bb!.__offset(this.bb_pos, 90);
+ return offset ? this.bb!.readUint8(this.bb_pos + offset) : AnyUniqueAliases.NONE;
+}
+
+anyUnique<T extends flatbuffers.Table>(obj:any):any|null {
+ const offset = this.bb!.__offset(this.bb_pos, 92);
+ return offset ? this.bb!.__union(obj, this.bb_pos + offset) : null;
+}
+
+anyAmbiguousType():AnyAmbiguousAliases {
+ const offset = this.bb!.__offset(this.bb_pos, 94);
+ return offset ? this.bb!.readUint8(this.bb_pos + offset) : AnyAmbiguousAliases.NONE;
+}
+
+anyAmbiguous<T extends flatbuffers.Table>(obj:any):any|null {
+ const offset = this.bb!.__offset(this.bb_pos, 96);
+ return offset ? this.bb!.__union(obj, this.bb_pos + offset) : null;
+}
+
+vectorOfEnums(index: number):Color|null {
+ const offset = this.bb!.__offset(this.bb_pos, 98);
+ return offset ? this.bb!.readUint8(this.bb!.__vector(this.bb_pos + offset) + index) : 0;
+}
+
+vectorOfEnumsLength():number {
+ const offset = this.bb!.__offset(this.bb_pos, 98);
+ return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
+}
+
+vectorOfEnumsArray():Uint8Array|null {
+ const offset = this.bb!.__offset(this.bb_pos, 98);
+ return offset ? new Uint8Array(this.bb!.bytes().buffer, this.bb!.bytes().byteOffset + this.bb!.__vector(this.bb_pos + offset), this.bb!.__vector_len(this.bb_pos + offset)) : null;
+}
+
+signedEnum():Race {
+ const offset = this.bb!.__offset(this.bb_pos, 100);
+ return offset ? this.bb!.readInt8(this.bb_pos + offset) : Race.None;
+}
+
+mutate_signed_enum(value:Race):boolean {
+ const offset = this.bb!.__offset(this.bb_pos, 100);
+
+ if (offset === 0) {
+ return false;
+ }
+
+ this.bb!.writeInt8(this.bb_pos + offset, value);
+ return true;
+}
+
+testrequirednestedflatbuffer(index: number):number|null {
+ const offset = this.bb!.__offset(this.bb_pos, 102);
+ return offset ? this.bb!.readUint8(this.bb!.__vector(this.bb_pos + offset) + index) : 0;
+}
+
+testrequirednestedflatbufferLength():number {
+ const offset = this.bb!.__offset(this.bb_pos, 102);
+ return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
+}
+
+testrequirednestedflatbufferArray():Uint8Array|null {
+ const offset = this.bb!.__offset(this.bb_pos, 102);
+ return offset ? new Uint8Array(this.bb!.bytes().buffer, this.bb!.bytes().byteOffset + this.bb!.__vector(this.bb_pos + offset), this.bb!.__vector_len(this.bb_pos + offset)) : null;
+}
+
+scalarKeySortedTables(index: number, obj?:Stat):Stat|null {
+ const offset = this.bb!.__offset(this.bb_pos, 104);
+ return offset ? (obj || new Stat()).__init(this.bb!.__indirect(this.bb!.__vector(this.bb_pos + offset) + index * 4), this.bb!) : null;
+}
+
+scalarKeySortedTablesLength():number {
+ const offset = this.bb!.__offset(this.bb_pos, 104);
+ return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
+}
+
+nativeInline(obj?:Test):Test|null {
+ const offset = this.bb!.__offset(this.bb_pos, 106);
+ return offset ? (obj || new Test()).__init(this.bb_pos + offset, this.bb!) : null;
+}
+
+longEnumNonEnumDefault():bigint {
+ const offset = this.bb!.__offset(this.bb_pos, 108);
+ return offset ? this.bb!.readUint64(this.bb_pos + offset) : BigInt('0');
+}
+
+mutate_long_enum_non_enum_default(value:bigint):boolean {
+ const offset = this.bb!.__offset(this.bb_pos, 108);
+
+ if (offset === 0) {
+ return false;
+ }
+
+ this.bb!.writeUint64(this.bb_pos + offset, value);
+ return true;
+}
+
+longEnumNormalDefault():bigint {
+ const offset = this.bb!.__offset(this.bb_pos, 110);
+ return offset ? this.bb!.readUint64(this.bb_pos + offset) : BigInt('2');
+}
+
+mutate_long_enum_normal_default(value:bigint):boolean {
+ const offset = this.bb!.__offset(this.bb_pos, 110);
+
+ if (offset === 0) {
+ return false;
+ }
+
+ this.bb!.writeUint64(this.bb_pos + offset, value);
+ return true;
+}
+
+static getFullyQualifiedName():string {
+ return 'MyGame.Example.Monster';
+}
+
+static startMonster(builder:flatbuffers.Builder) {
+ builder.startObject(54);
+}
+
+static addPos(builder:flatbuffers.Builder, posOffset:flatbuffers.Offset) {
+ builder.addFieldStruct(0, posOffset, 0);
+}
+
+static addMana(builder:flatbuffers.Builder, mana:number) {
+ builder.addFieldInt16(1, mana, 150);
+}
+
+static addHp(builder:flatbuffers.Builder, hp:number) {
+ builder.addFieldInt16(2, hp, 100);
+}
+
+static addName(builder:flatbuffers.Builder, nameOffset:flatbuffers.Offset) {
+ builder.addFieldOffset(3, nameOffset, 0);
+}
+
+static addInventory(builder:flatbuffers.Builder, inventoryOffset:flatbuffers.Offset) {
+ builder.addFieldOffset(5, inventoryOffset, 0);
+}
+
+static createInventoryVector(builder:flatbuffers.Builder, data:number[]|Uint8Array):flatbuffers.Offset {
+ builder.startVector(1, data.length, 1);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addInt8(data[i]!);
+ }
+ return builder.endVector();
+}
+
+static startInventoryVector(builder:flatbuffers.Builder, numElems:number) {
+ builder.startVector(1, numElems, 1);
+}
+
+static addColor(builder:flatbuffers.Builder, color:Color) {
+ builder.addFieldInt8(6, color, Color.Blue);
+}
+
+static addTestType(builder:flatbuffers.Builder, testType:Any) {
+ builder.addFieldInt8(7, testType, Any.NONE);
+}
+
+static addTest(builder:flatbuffers.Builder, testOffset:flatbuffers.Offset) {
+ builder.addFieldOffset(8, testOffset, 0);
+}
+
+static addTest4(builder:flatbuffers.Builder, test4Offset:flatbuffers.Offset) {
+ builder.addFieldOffset(9, test4Offset, 0);
+}
+
+static startTest4Vector(builder:flatbuffers.Builder, numElems:number) {
+ builder.startVector(4, numElems, 2);
+}
+
+static addTestarrayofstring(builder:flatbuffers.Builder, testarrayofstringOffset:flatbuffers.Offset) {
+ builder.addFieldOffset(10, testarrayofstringOffset, 0);
+}
+
+static createTestarrayofstringVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset {
+ builder.startVector(4, data.length, 4);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addOffset(data[i]!);
+ }
+ return builder.endVector();
+}
+
+static startTestarrayofstringVector(builder:flatbuffers.Builder, numElems:number) {
+ builder.startVector(4, numElems, 4);
+}
+
+static addTestarrayoftables(builder:flatbuffers.Builder, testarrayoftablesOffset:flatbuffers.Offset) {
+ builder.addFieldOffset(11, testarrayoftablesOffset, 0);
+}
+
+static createTestarrayoftablesVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset {
+ builder.startVector(4, data.length, 4);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addOffset(data[i]!);
+ }
+ return builder.endVector();
+}
+
+static startTestarrayoftablesVector(builder:flatbuffers.Builder, numElems:number) {
+ builder.startVector(4, numElems, 4);
+}
+
+static addEnemy(builder:flatbuffers.Builder, enemyOffset:flatbuffers.Offset) {
+ builder.addFieldOffset(12, enemyOffset, 0);
+}
+
+static addTestnestedflatbuffer(builder:flatbuffers.Builder, testnestedflatbufferOffset:flatbuffers.Offset) {
+ builder.addFieldOffset(13, testnestedflatbufferOffset, 0);
+}
+
+static createTestnestedflatbufferVector(builder:flatbuffers.Builder, data:number[]|Uint8Array):flatbuffers.Offset {
+ builder.startVector(1, data.length, 1);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addInt8(data[i]!);
+ }
+ return builder.endVector();
+}
+
+static startTestnestedflatbufferVector(builder:flatbuffers.Builder, numElems:number) {
+ builder.startVector(1, numElems, 1);
+}
+
+static addTestempty(builder:flatbuffers.Builder, testemptyOffset:flatbuffers.Offset) {
+ builder.addFieldOffset(14, testemptyOffset, 0);
+}
+
+static addTestbool(builder:flatbuffers.Builder, testbool:boolean) {
+ builder.addFieldInt8(15, +testbool, +false);
+}
+
+static addTesthashs32Fnv1(builder:flatbuffers.Builder, testhashs32Fnv1:number) {
+ builder.addFieldInt32(16, testhashs32Fnv1, 0);
+}
+
+static addTesthashu32Fnv1(builder:flatbuffers.Builder, testhashu32Fnv1:number) {
+ builder.addFieldInt32(17, testhashu32Fnv1, 0);
+}
+
+static addTesthashs64Fnv1(builder:flatbuffers.Builder, testhashs64Fnv1:bigint) {
+ builder.addFieldInt64(18, testhashs64Fnv1, BigInt('0'));
+}
+
+static addTesthashu64Fnv1(builder:flatbuffers.Builder, testhashu64Fnv1:bigint) {
+ builder.addFieldInt64(19, testhashu64Fnv1, BigInt('0'));
+}
+
+static addTesthashs32Fnv1a(builder:flatbuffers.Builder, testhashs32Fnv1a:number) {
+ builder.addFieldInt32(20, testhashs32Fnv1a, 0);
+}
+
+static addTesthashu32Fnv1a(builder:flatbuffers.Builder, testhashu32Fnv1a:number) {
+ builder.addFieldInt32(21, testhashu32Fnv1a, 0);
+}
+
+static addTesthashs64Fnv1a(builder:flatbuffers.Builder, testhashs64Fnv1a:bigint) {
+ builder.addFieldInt64(22, testhashs64Fnv1a, BigInt('0'));
+}
+
+static addTesthashu64Fnv1a(builder:flatbuffers.Builder, testhashu64Fnv1a:bigint) {
+ builder.addFieldInt64(23, testhashu64Fnv1a, BigInt('0'));
+}
+
+static addTestarrayofbools(builder:flatbuffers.Builder, testarrayofboolsOffset:flatbuffers.Offset) {
+ builder.addFieldOffset(24, testarrayofboolsOffset, 0);
+}
+
+static createTestarrayofboolsVector(builder:flatbuffers.Builder, data:boolean[]):flatbuffers.Offset {
+ builder.startVector(1, data.length, 1);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addInt8(+data[i]!);
+ }
+ return builder.endVector();
+}
+
+static startTestarrayofboolsVector(builder:flatbuffers.Builder, numElems:number) {
+ builder.startVector(1, numElems, 1);
+}
+
+static addTestf(builder:flatbuffers.Builder, testf:number) {
+ builder.addFieldFloat32(25, testf, 3.14159);
+}
+
+static addTestf2(builder:flatbuffers.Builder, testf2:number) {
+ builder.addFieldFloat32(26, testf2, 3.0);
+}
+
+static addTestf3(builder:flatbuffers.Builder, testf3:number) {
+ builder.addFieldFloat32(27, testf3, 0.0);
+}
+
+static addTestarrayofstring2(builder:flatbuffers.Builder, testarrayofstring2Offset:flatbuffers.Offset) {
+ builder.addFieldOffset(28, testarrayofstring2Offset, 0);
+}
+
+static createTestarrayofstring2Vector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset {
+ builder.startVector(4, data.length, 4);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addOffset(data[i]!);
+ }
+ return builder.endVector();
+}
+
+static startTestarrayofstring2Vector(builder:flatbuffers.Builder, numElems:number) {
+ builder.startVector(4, numElems, 4);
+}
+
+static addTestarrayofsortedstruct(builder:flatbuffers.Builder, testarrayofsortedstructOffset:flatbuffers.Offset) {
+ builder.addFieldOffset(29, testarrayofsortedstructOffset, 0);
+}
+
+static startTestarrayofsortedstructVector(builder:flatbuffers.Builder, numElems:number) {
+ builder.startVector(8, numElems, 4);
+}
+
+static addFlex(builder:flatbuffers.Builder, flexOffset:flatbuffers.Offset) {
+ builder.addFieldOffset(30, flexOffset, 0);
+}
+
+static createFlexVector(builder:flatbuffers.Builder, data:number[]|Uint8Array):flatbuffers.Offset {
+ builder.startVector(1, data.length, 1);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addInt8(data[i]!);
+ }
+ return builder.endVector();
+}
+
+static startFlexVector(builder:flatbuffers.Builder, numElems:number) {
+ builder.startVector(1, numElems, 1);
+}
+
+static addTest5(builder:flatbuffers.Builder, test5Offset:flatbuffers.Offset) {
+ builder.addFieldOffset(31, test5Offset, 0);
+}
+
+static startTest5Vector(builder:flatbuffers.Builder, numElems:number) {
+ builder.startVector(4, numElems, 2);
+}
+
+static addVectorOfLongs(builder:flatbuffers.Builder, vectorOfLongsOffset:flatbuffers.Offset) {
+ builder.addFieldOffset(32, vectorOfLongsOffset, 0);
+}
+
+static createVectorOfLongsVector(builder:flatbuffers.Builder, data:bigint[]):flatbuffers.Offset {
+ builder.startVector(8, data.length, 8);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addInt64(data[i]!);
+ }
+ return builder.endVector();
+}
+
+static startVectorOfLongsVector(builder:flatbuffers.Builder, numElems:number) {
+ builder.startVector(8, numElems, 8);
+}
+
+static addVectorOfDoubles(builder:flatbuffers.Builder, vectorOfDoublesOffset:flatbuffers.Offset) {
+ builder.addFieldOffset(33, vectorOfDoublesOffset, 0);
+}
+
+static createVectorOfDoublesVector(builder:flatbuffers.Builder, data:number[]|Float64Array):flatbuffers.Offset;
+/**
+ * @deprecated This Uint8Array overload will be removed in the future.
+ */
+static createVectorOfDoublesVector(builder:flatbuffers.Builder, data:number[]|Uint8Array):flatbuffers.Offset;
+static createVectorOfDoublesVector(builder:flatbuffers.Builder, data:number[]|Float64Array|Uint8Array):flatbuffers.Offset {
+ builder.startVector(8, data.length, 8);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addFloat64(data[i]!);
+ }
+ return builder.endVector();
+}
+
+static startVectorOfDoublesVector(builder:flatbuffers.Builder, numElems:number) {
+ builder.startVector(8, numElems, 8);
+}
+
+static addParentNamespaceTest(builder:flatbuffers.Builder, parentNamespaceTestOffset:flatbuffers.Offset) {
+ builder.addFieldOffset(34, parentNamespaceTestOffset, 0);
+}
+
+static addVectorOfReferrables(builder:flatbuffers.Builder, vectorOfReferrablesOffset:flatbuffers.Offset) {
+ builder.addFieldOffset(35, vectorOfReferrablesOffset, 0);
+}
+
+static createVectorOfReferrablesVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset {
+ builder.startVector(4, data.length, 4);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addOffset(data[i]!);
+ }
+ return builder.endVector();
+}
+
+static startVectorOfReferrablesVector(builder:flatbuffers.Builder, numElems:number) {
+ builder.startVector(4, numElems, 4);
+}
+
+static addSingleWeakReference(builder:flatbuffers.Builder, singleWeakReference:bigint) {
+ builder.addFieldInt64(36, singleWeakReference, BigInt('0'));
+}
+
+static addVectorOfWeakReferences(builder:flatbuffers.Builder, vectorOfWeakReferencesOffset:flatbuffers.Offset) {
+ builder.addFieldOffset(37, vectorOfWeakReferencesOffset, 0);
+}
+
+static createVectorOfWeakReferencesVector(builder:flatbuffers.Builder, data:bigint[]):flatbuffers.Offset {
+ builder.startVector(8, data.length, 8);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addInt64(data[i]!);
+ }
+ return builder.endVector();
+}
+
+static startVectorOfWeakReferencesVector(builder:flatbuffers.Builder, numElems:number) {
+ builder.startVector(8, numElems, 8);
+}
+
+static addVectorOfStrongReferrables(builder:flatbuffers.Builder, vectorOfStrongReferrablesOffset:flatbuffers.Offset) {
+ builder.addFieldOffset(38, vectorOfStrongReferrablesOffset, 0);
+}
+
+static createVectorOfStrongReferrablesVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset {
+ builder.startVector(4, data.length, 4);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addOffset(data[i]!);
+ }
+ return builder.endVector();
+}
+
+static startVectorOfStrongReferrablesVector(builder:flatbuffers.Builder, numElems:number) {
+ builder.startVector(4, numElems, 4);
+}
+
+static addCoOwningReference(builder:flatbuffers.Builder, coOwningReference:bigint) {
+ builder.addFieldInt64(39, coOwningReference, BigInt('0'));
+}
+
+static addVectorOfCoOwningReferences(builder:flatbuffers.Builder, vectorOfCoOwningReferencesOffset:flatbuffers.Offset) {
+ builder.addFieldOffset(40, vectorOfCoOwningReferencesOffset, 0);
+}
+
+static createVectorOfCoOwningReferencesVector(builder:flatbuffers.Builder, data:bigint[]):flatbuffers.Offset {
+ builder.startVector(8, data.length, 8);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addInt64(data[i]!);
+ }
+ return builder.endVector();
+}
+
+static startVectorOfCoOwningReferencesVector(builder:flatbuffers.Builder, numElems:number) {
+ builder.startVector(8, numElems, 8);
+}
+
+static addNonOwningReference(builder:flatbuffers.Builder, nonOwningReference:bigint) {
+ builder.addFieldInt64(41, nonOwningReference, BigInt('0'));
+}
+
+static addVectorOfNonOwningReferences(builder:flatbuffers.Builder, vectorOfNonOwningReferencesOffset:flatbuffers.Offset) {
+ builder.addFieldOffset(42, vectorOfNonOwningReferencesOffset, 0);
+}
+
+static createVectorOfNonOwningReferencesVector(builder:flatbuffers.Builder, data:bigint[]):flatbuffers.Offset {
+ builder.startVector(8, data.length, 8);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addInt64(data[i]!);
+ }
+ return builder.endVector();
+}
+
+static startVectorOfNonOwningReferencesVector(builder:flatbuffers.Builder, numElems:number) {
+ builder.startVector(8, numElems, 8);
+}
+
+static addAnyUniqueType(builder:flatbuffers.Builder, anyUniqueType:AnyUniqueAliases) {
+ builder.addFieldInt8(43, anyUniqueType, AnyUniqueAliases.NONE);
+}
+
+static addAnyUnique(builder:flatbuffers.Builder, anyUniqueOffset:flatbuffers.Offset) {
+ builder.addFieldOffset(44, anyUniqueOffset, 0);
+}
+
+static addAnyAmbiguousType(builder:flatbuffers.Builder, anyAmbiguousType:AnyAmbiguousAliases) {
+ builder.addFieldInt8(45, anyAmbiguousType, AnyAmbiguousAliases.NONE);
+}
+
+static addAnyAmbiguous(builder:flatbuffers.Builder, anyAmbiguousOffset:flatbuffers.Offset) {
+ builder.addFieldOffset(46, anyAmbiguousOffset, 0);
+}
+
+static addVectorOfEnums(builder:flatbuffers.Builder, vectorOfEnumsOffset:flatbuffers.Offset) {
+ builder.addFieldOffset(47, vectorOfEnumsOffset, 0);
+}
+
+static createVectorOfEnumsVector(builder:flatbuffers.Builder, data:Color[]):flatbuffers.Offset {
+ builder.startVector(1, data.length, 1);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addInt8(data[i]!);
+ }
+ return builder.endVector();
+}
+
+static startVectorOfEnumsVector(builder:flatbuffers.Builder, numElems:number) {
+ builder.startVector(1, numElems, 1);
+}
+
+static addSignedEnum(builder:flatbuffers.Builder, signedEnum:Race) {
+ builder.addFieldInt8(48, signedEnum, Race.None);
+}
+
+static addTestrequirednestedflatbuffer(builder:flatbuffers.Builder, testrequirednestedflatbufferOffset:flatbuffers.Offset) {
+ builder.addFieldOffset(49, testrequirednestedflatbufferOffset, 0);
+}
+
+static createTestrequirednestedflatbufferVector(builder:flatbuffers.Builder, data:number[]|Uint8Array):flatbuffers.Offset {
+ builder.startVector(1, data.length, 1);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addInt8(data[i]!);
+ }
+ return builder.endVector();
+}
+
+static startTestrequirednestedflatbufferVector(builder:flatbuffers.Builder, numElems:number) {
+ builder.startVector(1, numElems, 1);
+}
+
+static addScalarKeySortedTables(builder:flatbuffers.Builder, scalarKeySortedTablesOffset:flatbuffers.Offset) {
+ builder.addFieldOffset(50, scalarKeySortedTablesOffset, 0);
+}
+
+static createScalarKeySortedTablesVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset {
+ builder.startVector(4, data.length, 4);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addOffset(data[i]!);
+ }
+ return builder.endVector();
+}
+
+static startScalarKeySortedTablesVector(builder:flatbuffers.Builder, numElems:number) {
+ builder.startVector(4, numElems, 4);
+}
+
+static addNativeInline(builder:flatbuffers.Builder, nativeInlineOffset:flatbuffers.Offset) {
+ builder.addFieldStruct(51, nativeInlineOffset, 0);
+}
+
+static addLongEnumNonEnumDefault(builder:flatbuffers.Builder, longEnumNonEnumDefault:bigint) {
+ builder.addFieldInt64(52, longEnumNonEnumDefault, BigInt('0'));
+}
+
+static addLongEnumNormalDefault(builder:flatbuffers.Builder, longEnumNormalDefault:bigint) {
+ builder.addFieldInt64(53, longEnumNormalDefault, BigInt('2'));
+}
+
+static endMonster(builder:flatbuffers.Builder):flatbuffers.Offset {
+ const offset = builder.endObject();
+ builder.requiredField(offset, 10) // name
+ return offset;
+}
+
+static finishMonsterBuffer(builder:flatbuffers.Builder, offset:flatbuffers.Offset) {
+ builder.finish(offset, 'MONS');
+}
+
+static finishSizePrefixedMonsterBuffer(builder:flatbuffers.Builder, offset:flatbuffers.Offset) {
+ builder.finish(offset, 'MONS', true);
+}
+
+
+serialize():Uint8Array {
+ return this.bb!.bytes();
+}
+
+static deserialize(buffer: Uint8Array):Monster {
+ return Monster.getRootAsMonster(new flatbuffers.ByteBuffer(buffer))
+}
+
+unpack(): MonsterT {
+ return new MonsterT(
+ (this.pos() !== null ? this.pos()!.unpack() : null),
+ this.mana(),
+ this.hp(),
+ this.name(),
+ this.bb!.createScalarList(this.inventory.bind(this), this.inventoryLength()),
+ this.color(),
+ this.testType(),
+ (() => {
+ let temp = unionToAny(this.testType(), this.test.bind(this));
+ if(temp === null) { return null; }
+ return temp.unpack()
+ })(),
+ this.bb!.createObjList(this.test4.bind(this), this.test4Length()),
+ this.bb!.createScalarList(this.testarrayofstring.bind(this), this.testarrayofstringLength()),
+ this.bb!.createObjList(this.testarrayoftables.bind(this), this.testarrayoftablesLength()),
+ (this.enemy() !== null ? this.enemy()!.unpack() : null),
+ this.bb!.createScalarList(this.testnestedflatbuffer.bind(this), this.testnestedflatbufferLength()),
+ (this.testempty() !== null ? this.testempty()!.unpack() : null),
+ this.testbool(),
+ this.testhashs32Fnv1(),
+ this.testhashu32Fnv1(),
+ this.testhashs64Fnv1(),
+ this.testhashu64Fnv1(),
+ this.testhashs32Fnv1a(),
+ this.testhashu32Fnv1a(),
+ this.testhashs64Fnv1a(),
+ this.testhashu64Fnv1a(),
+ this.bb!.createScalarList(this.testarrayofbools.bind(this), this.testarrayofboolsLength()),
+ this.testf(),
+ this.testf2(),
+ this.testf3(),
+ this.bb!.createScalarList(this.testarrayofstring2.bind(this), this.testarrayofstring2Length()),
+ this.bb!.createObjList(this.testarrayofsortedstruct.bind(this), this.testarrayofsortedstructLength()),
+ this.bb!.createScalarList(this.flex.bind(this), this.flexLength()),
+ this.bb!.createObjList(this.test5.bind(this), this.test5Length()),
+ this.bb!.createScalarList(this.vectorOfLongs.bind(this), this.vectorOfLongsLength()),
+ this.bb!.createScalarList(this.vectorOfDoubles.bind(this), this.vectorOfDoublesLength()),
+ (this.parentNamespaceTest() !== null ? this.parentNamespaceTest()!.unpack() : null),
+ this.bb!.createObjList(this.vectorOfReferrables.bind(this), this.vectorOfReferrablesLength()),
+ this.singleWeakReference(),
+ this.bb!.createScalarList(this.vectorOfWeakReferences.bind(this), this.vectorOfWeakReferencesLength()),
+ this.bb!.createObjList(this.vectorOfStrongReferrables.bind(this), this.vectorOfStrongReferrablesLength()),
+ this.coOwningReference(),
+ this.bb!.createScalarList(this.vectorOfCoOwningReferences.bind(this), this.vectorOfCoOwningReferencesLength()),
+ this.nonOwningReference(),
+ this.bb!.createScalarList(this.vectorOfNonOwningReferences.bind(this), this.vectorOfNonOwningReferencesLength()),
+ this.anyUniqueType(),
+ (() => {
+ let temp = unionToAnyUniqueAliases(this.anyUniqueType(), this.anyUnique.bind(this));
+ if(temp === null) { return null; }
+ return temp.unpack()
+ })(),
+ this.anyAmbiguousType(),
+ (() => {
+ let temp = unionToAnyAmbiguousAliases(this.anyAmbiguousType(), this.anyAmbiguous.bind(this));
+ if(temp === null) { return null; }
+ return temp.unpack()
+ })(),
+ this.bb!.createScalarList(this.vectorOfEnums.bind(this), this.vectorOfEnumsLength()),
+ this.signedEnum(),
+ this.bb!.createScalarList(this.testrequirednestedflatbuffer.bind(this), this.testrequirednestedflatbufferLength()),
+ this.bb!.createObjList(this.scalarKeySortedTables.bind(this), this.scalarKeySortedTablesLength()),
+ (this.nativeInline() !== null ? this.nativeInline()!.unpack() : null),
+ this.longEnumNonEnumDefault(),
+ this.longEnumNormalDefault()
+ );
+}
+
+
+unpackTo(_o: MonsterT): void {
+ _o.pos = (this.pos() !== null ? this.pos()!.unpack() : null);
+ _o.mana = this.mana();
+ _o.hp = this.hp();
+ _o.name = this.name();
+ _o.inventory = this.bb!.createScalarList(this.inventory.bind(this), this.inventoryLength());
+ _o.color = this.color();
+ _o.testType = this.testType();
+ _o.test = (() => {
+ let temp = unionToAny(this.testType(), this.test.bind(this));
+ if(temp === null) { return null; }
+ return temp.unpack()
+ })();
+ _o.test4 = this.bb!.createObjList(this.test4.bind(this), this.test4Length());
+ _o.testarrayofstring = this.bb!.createScalarList(this.testarrayofstring.bind(this), this.testarrayofstringLength());
+ _o.testarrayoftables = this.bb!.createObjList(this.testarrayoftables.bind(this), this.testarrayoftablesLength());
+ _o.enemy = (this.enemy() !== null ? this.enemy()!.unpack() : null);
+ _o.testnestedflatbuffer = this.bb!.createScalarList(this.testnestedflatbuffer.bind(this), this.testnestedflatbufferLength());
+ _o.testempty = (this.testempty() !== null ? this.testempty()!.unpack() : null);
+ _o.testbool = this.testbool();
+ _o.testhashs32Fnv1 = this.testhashs32Fnv1();
+ _o.testhashu32Fnv1 = this.testhashu32Fnv1();
+ _o.testhashs64Fnv1 = this.testhashs64Fnv1();
+ _o.testhashu64Fnv1 = this.testhashu64Fnv1();
+ _o.testhashs32Fnv1a = this.testhashs32Fnv1a();
+ _o.testhashu32Fnv1a = this.testhashu32Fnv1a();
+ _o.testhashs64Fnv1a = this.testhashs64Fnv1a();
+ _o.testhashu64Fnv1a = this.testhashu64Fnv1a();
+ _o.testarrayofbools = this.bb!.createScalarList(this.testarrayofbools.bind(this), this.testarrayofboolsLength());
+ _o.testf = this.testf();
+ _o.testf2 = this.testf2();
+ _o.testf3 = this.testf3();
+ _o.testarrayofstring2 = this.bb!.createScalarList(this.testarrayofstring2.bind(this), this.testarrayofstring2Length());
+ _o.testarrayofsortedstruct = this.bb!.createObjList(this.testarrayofsortedstruct.bind(this), this.testarrayofsortedstructLength());
+ _o.flex = this.bb!.createScalarList(this.flex.bind(this), this.flexLength());
+ _o.test5 = this.bb!.createObjList(this.test5.bind(this), this.test5Length());
+ _o.vectorOfLongs = this.bb!.createScalarList(this.vectorOfLongs.bind(this), this.vectorOfLongsLength());
+ _o.vectorOfDoubles = this.bb!.createScalarList(this.vectorOfDoubles.bind(this), this.vectorOfDoublesLength());
+ _o.parentNamespaceTest = (this.parentNamespaceTest() !== null ? this.parentNamespaceTest()!.unpack() : null);
+ _o.vectorOfReferrables = this.bb!.createObjList(this.vectorOfReferrables.bind(this), this.vectorOfReferrablesLength());
+ _o.singleWeakReference = this.singleWeakReference();
+ _o.vectorOfWeakReferences = this.bb!.createScalarList(this.vectorOfWeakReferences.bind(this), this.vectorOfWeakReferencesLength());
+ _o.vectorOfStrongReferrables = this.bb!.createObjList(this.vectorOfStrongReferrables.bind(this), this.vectorOfStrongReferrablesLength());
+ _o.coOwningReference = this.coOwningReference();
+ _o.vectorOfCoOwningReferences = this.bb!.createScalarList(this.vectorOfCoOwningReferences.bind(this), this.vectorOfCoOwningReferencesLength());
+ _o.nonOwningReference = this.nonOwningReference();
+ _o.vectorOfNonOwningReferences = this.bb!.createScalarList(this.vectorOfNonOwningReferences.bind(this), this.vectorOfNonOwningReferencesLength());
+ _o.anyUniqueType = this.anyUniqueType();
+ _o.anyUnique = (() => {
+ let temp = unionToAnyUniqueAliases(this.anyUniqueType(), this.anyUnique.bind(this));
+ if(temp === null) { return null; }
+ return temp.unpack()
+ })();
+ _o.anyAmbiguousType = this.anyAmbiguousType();
+ _o.anyAmbiguous = (() => {
+ let temp = unionToAnyAmbiguousAliases(this.anyAmbiguousType(), this.anyAmbiguous.bind(this));
+ if(temp === null) { return null; }
+ return temp.unpack()
+ })();
+ _o.vectorOfEnums = this.bb!.createScalarList(this.vectorOfEnums.bind(this), this.vectorOfEnumsLength());
+ _o.signedEnum = this.signedEnum();
+ _o.testrequirednestedflatbuffer = this.bb!.createScalarList(this.testrequirednestedflatbuffer.bind(this), this.testrequirednestedflatbufferLength());
+ _o.scalarKeySortedTables = this.bb!.createObjList(this.scalarKeySortedTables.bind(this), this.scalarKeySortedTablesLength());
+ _o.nativeInline = (this.nativeInline() !== null ? this.nativeInline()!.unpack() : null);
+ _o.longEnumNonEnumDefault = this.longEnumNonEnumDefault();
+ _o.longEnumNormalDefault = this.longEnumNormalDefault();
+}
+}
+
+export class MonsterT {
+constructor(
+ public pos: Vec3T|null = null,
+ public mana: number = 150,
+ public hp: number = 100,
+ public name: string|Uint8Array|null = null,
+ public inventory: (number)[] = [],
+ public color: Color = Color.Blue,
+ public testType: Any = Any.NONE,
+ public test: MonsterT|MyGameExample2MonsterT|TestSimpleTableWithEnumT|null = null,
+ public test4: (TestT)[] = [],
+ public testarrayofstring: (string)[] = [],
+ public testarrayoftables: (MonsterT)[] = [],
+ public enemy: MonsterT|null = null,
+ public testnestedflatbuffer: (number)[] = [],
+ public testempty: StatT|null = null,
+ public testbool: boolean = false,
+ public testhashs32Fnv1: number = 0,
+ public testhashu32Fnv1: number = 0,
+ public testhashs64Fnv1: bigint = BigInt('0'),
+ public testhashu64Fnv1: bigint = BigInt('0'),
+ public testhashs32Fnv1a: number = 0,
+ public testhashu32Fnv1a: number = 0,
+ public testhashs64Fnv1a: bigint = BigInt('0'),
+ public testhashu64Fnv1a: bigint = BigInt('0'),
+ public testarrayofbools: (boolean)[] = [],
+ public testf: number = 3.14159,
+ public testf2: number = 3.0,
+ public testf3: number = 0.0,
+ public testarrayofstring2: (string)[] = [],
+ public testarrayofsortedstruct: (AbilityT)[] = [],
+ public flex: (number)[] = [],
+ public test5: (TestT)[] = [],
+ public vectorOfLongs: (bigint)[] = [],
+ public vectorOfDoubles: (number)[] = [],
+ public parentNamespaceTest: InParentNamespaceT|null = null,
+ public vectorOfReferrables: (ReferrableT)[] = [],
+ public singleWeakReference: bigint = BigInt('0'),
+ public vectorOfWeakReferences: (bigint)[] = [],
+ public vectorOfStrongReferrables: (ReferrableT)[] = [],
+ public coOwningReference: bigint = BigInt('0'),
+ public vectorOfCoOwningReferences: (bigint)[] = [],
+ public nonOwningReference: bigint = BigInt('0'),
+ public vectorOfNonOwningReferences: (bigint)[] = [],
+ public anyUniqueType: AnyUniqueAliases = AnyUniqueAliases.NONE,
+ public anyUnique: MonsterT|MyGameExample2MonsterT|TestSimpleTableWithEnumT|null = null,
+ public anyAmbiguousType: AnyAmbiguousAliases = AnyAmbiguousAliases.NONE,
+ public anyAmbiguous: MonsterT|null = null,
+ public vectorOfEnums: (Color)[] = [],
+ public signedEnum: Race = Race.None,
+ public testrequirednestedflatbuffer: (number)[] = [],
+ public scalarKeySortedTables: (StatT)[] = [],
+ public nativeInline: TestT|null = null,
+ public longEnumNonEnumDefault: bigint = BigInt('0'),
+ public longEnumNormalDefault: bigint = BigInt('2')
+){}
+
+
+pack(builder:flatbuffers.Builder): flatbuffers.Offset {
+ const name = (this.name !== null ? builder.createString(this.name!) : 0);
+ const inventory = Monster.createInventoryVector(builder, this.inventory);
+ const test = builder.createObjectOffset(this.test);
+ const test4 = builder.createStructOffsetList(this.test4, Monster.startTest4Vector);
+ const testarrayofstring = Monster.createTestarrayofstringVector(builder, builder.createObjectOffsetList(this.testarrayofstring));
+ const testarrayoftables = Monster.createTestarrayoftablesVector(builder, builder.createObjectOffsetList(this.testarrayoftables));
+ const enemy = (this.enemy !== null ? this.enemy!.pack(builder) : 0);
+ const testnestedflatbuffer = Monster.createTestnestedflatbufferVector(builder, this.testnestedflatbuffer);
+ const testempty = (this.testempty !== null ? this.testempty!.pack(builder) : 0);
+ const testarrayofbools = Monster.createTestarrayofboolsVector(builder, this.testarrayofbools);
+ const testarrayofstring2 = Monster.createTestarrayofstring2Vector(builder, builder.createObjectOffsetList(this.testarrayofstring2));
+ const testarrayofsortedstruct = builder.createStructOffsetList(this.testarrayofsortedstruct, Monster.startTestarrayofsortedstructVector);
+ const flex = Monster.createFlexVector(builder, this.flex);
+ const test5 = builder.createStructOffsetList(this.test5, Monster.startTest5Vector);
+ const vectorOfLongs = Monster.createVectorOfLongsVector(builder, this.vectorOfLongs);
+ const vectorOfDoubles = Monster.createVectorOfDoublesVector(builder, this.vectorOfDoubles);
+ const parentNamespaceTest = (this.parentNamespaceTest !== null ? this.parentNamespaceTest!.pack(builder) : 0);
+ const vectorOfReferrables = Monster.createVectorOfReferrablesVector(builder, builder.createObjectOffsetList(this.vectorOfReferrables));
+ const vectorOfWeakReferences = Monster.createVectorOfWeakReferencesVector(builder, this.vectorOfWeakReferences);
+ const vectorOfStrongReferrables = Monster.createVectorOfStrongReferrablesVector(builder, builder.createObjectOffsetList(this.vectorOfStrongReferrables));
+ const vectorOfCoOwningReferences = Monster.createVectorOfCoOwningReferencesVector(builder, this.vectorOfCoOwningReferences);
+ const vectorOfNonOwningReferences = Monster.createVectorOfNonOwningReferencesVector(builder, this.vectorOfNonOwningReferences);
+ const anyUnique = builder.createObjectOffset(this.anyUnique);
+ const anyAmbiguous = builder.createObjectOffset(this.anyAmbiguous);
+ const vectorOfEnums = Monster.createVectorOfEnumsVector(builder, this.vectorOfEnums);
+ const testrequirednestedflatbuffer = Monster.createTestrequirednestedflatbufferVector(builder, this.testrequirednestedflatbuffer);
+ const scalarKeySortedTables = Monster.createScalarKeySortedTablesVector(builder, builder.createObjectOffsetList(this.scalarKeySortedTables));
+
+ Monster.startMonster(builder);
+ Monster.addPos(builder, (this.pos !== null ? this.pos!.pack(builder) : 0));
+ Monster.addMana(builder, this.mana);
+ Monster.addHp(builder, this.hp);
+ Monster.addName(builder, name);
+ Monster.addInventory(builder, inventory);
+ Monster.addColor(builder, this.color);
+ Monster.addTestType(builder, this.testType);
+ Monster.addTest(builder, test);
+ Monster.addTest4(builder, test4);
+ Monster.addTestarrayofstring(builder, testarrayofstring);
+ Monster.addTestarrayoftables(builder, testarrayoftables);
+ Monster.addEnemy(builder, enemy);
+ Monster.addTestnestedflatbuffer(builder, testnestedflatbuffer);
+ Monster.addTestempty(builder, testempty);
+ Monster.addTestbool(builder, this.testbool);
+ Monster.addTesthashs32Fnv1(builder, this.testhashs32Fnv1);
+ Monster.addTesthashu32Fnv1(builder, this.testhashu32Fnv1);
+ Monster.addTesthashs64Fnv1(builder, this.testhashs64Fnv1);
+ Monster.addTesthashu64Fnv1(builder, this.testhashu64Fnv1);
+ Monster.addTesthashs32Fnv1a(builder, this.testhashs32Fnv1a);
+ Monster.addTesthashu32Fnv1a(builder, this.testhashu32Fnv1a);
+ Monster.addTesthashs64Fnv1a(builder, this.testhashs64Fnv1a);
+ Monster.addTesthashu64Fnv1a(builder, this.testhashu64Fnv1a);
+ Monster.addTestarrayofbools(builder, testarrayofbools);
+ Monster.addTestf(builder, this.testf);
+ Monster.addTestf2(builder, this.testf2);
+ Monster.addTestf3(builder, this.testf3);
+ Monster.addTestarrayofstring2(builder, testarrayofstring2);
+ Monster.addTestarrayofsortedstruct(builder, testarrayofsortedstruct);
+ Monster.addFlex(builder, flex);
+ Monster.addTest5(builder, test5);
+ Monster.addVectorOfLongs(builder, vectorOfLongs);
+ Monster.addVectorOfDoubles(builder, vectorOfDoubles);
+ Monster.addParentNamespaceTest(builder, parentNamespaceTest);
+ Monster.addVectorOfReferrables(builder, vectorOfReferrables);
+ Monster.addSingleWeakReference(builder, this.singleWeakReference);
+ Monster.addVectorOfWeakReferences(builder, vectorOfWeakReferences);
+ Monster.addVectorOfStrongReferrables(builder, vectorOfStrongReferrables);
+ Monster.addCoOwningReference(builder, this.coOwningReference);
+ Monster.addVectorOfCoOwningReferences(builder, vectorOfCoOwningReferences);
+ Monster.addNonOwningReference(builder, this.nonOwningReference);
+ Monster.addVectorOfNonOwningReferences(builder, vectorOfNonOwningReferences);
+ Monster.addAnyUniqueType(builder, this.anyUniqueType);
+ Monster.addAnyUnique(builder, anyUnique);
+ Monster.addAnyAmbiguousType(builder, this.anyAmbiguousType);
+ Monster.addAnyAmbiguous(builder, anyAmbiguous);
+ Monster.addVectorOfEnums(builder, vectorOfEnums);
+ Monster.addSignedEnum(builder, this.signedEnum);
+ Monster.addTestrequirednestedflatbuffer(builder, testrequirednestedflatbuffer);
+ Monster.addScalarKeySortedTables(builder, scalarKeySortedTables);
+ Monster.addNativeInline(builder, (this.nativeInline !== null ? this.nativeInline!.pack(builder) : 0));
+ Monster.addLongEnumNonEnumDefault(builder, this.longEnumNonEnumDefault);
+ Monster.addLongEnumNormalDefault(builder, this.longEnumNormalDefault);
+
+ return Monster.endMonster(builder);
+}
+}
diff --git a/tests/my-game/example/race.js b/tests/my-game/example/race.js
new file mode 100644
index 0000000..74f5105
--- /dev/null
+++ b/tests/my-game/example/race.js
@@ -0,0 +1,8 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+export var Race;
+(function (Race) {
+ Race[Race["None"] = -1] = "None";
+ Race[Race["Human"] = 0] = "Human";
+ Race[Race["Dwarf"] = 1] = "Dwarf";
+ Race[Race["Elf"] = 2] = "Elf";
+})(Race || (Race = {}));
diff --git a/tests/my-game/example/race.ts b/tests/my-game/example/race.ts
new file mode 100644
index 0000000..06ca128
--- /dev/null
+++ b/tests/my-game/example/race.ts
@@ -0,0 +1,9 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+export enum Race{
+ None = -1,
+ Human = 0,
+ Dwarf = 1,
+ Elf = 2
+}
+
diff --git a/tests/my-game/example/referrable.js b/tests/my-game/example/referrable.js
new file mode 100644
index 0000000..0370768
--- /dev/null
+++ b/tests/my-game/example/referrable.js
@@ -0,0 +1,70 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+import * as flatbuffers from 'flatbuffers';
+export class Referrable {
+ constructor() {
+ this.bb = null;
+ this.bb_pos = 0;
+ }
+ __init(i, bb) {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+ }
+ static getRootAsReferrable(bb, obj) {
+ return (obj || new Referrable()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ static getSizePrefixedRootAsReferrable(bb, obj) {
+ bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new Referrable()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ id() {
+ const offset = this.bb.__offset(this.bb_pos, 4);
+ return offset ? this.bb.readUint64(this.bb_pos + offset) : BigInt('0');
+ }
+ mutate_id(value) {
+ const offset = this.bb.__offset(this.bb_pos, 4);
+ if (offset === 0) {
+ return false;
+ }
+ this.bb.writeUint64(this.bb_pos + offset, value);
+ return true;
+ }
+ static getFullyQualifiedName() {
+ return 'MyGame.Example.Referrable';
+ }
+ static startReferrable(builder) {
+ builder.startObject(1);
+ }
+ static addId(builder, id) {
+ builder.addFieldInt64(0, id, BigInt('0'));
+ }
+ static endReferrable(builder) {
+ const offset = builder.endObject();
+ return offset;
+ }
+ static createReferrable(builder, id) {
+ Referrable.startReferrable(builder);
+ Referrable.addId(builder, id);
+ return Referrable.endReferrable(builder);
+ }
+ serialize() {
+ return this.bb.bytes();
+ }
+ static deserialize(buffer) {
+ return Referrable.getRootAsReferrable(new flatbuffers.ByteBuffer(buffer));
+ }
+ unpack() {
+ return new ReferrableT(this.id());
+ }
+ unpackTo(_o) {
+ _o.id = this.id();
+ }
+}
+export class ReferrableT {
+ constructor(id = BigInt('0')) {
+ this.id = id;
+ }
+ pack(builder) {
+ return Referrable.createReferrable(builder, this.id);
+ }
+}
diff --git a/tests/my-game/example/referrable.ts b/tests/my-game/example/referrable.ts
new file mode 100644
index 0000000..fdac6c3
--- /dev/null
+++ b/tests/my-game/example/referrable.ts
@@ -0,0 +1,95 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+import * as flatbuffers from 'flatbuffers';
+
+
+
+export class Referrable {
+ bb: flatbuffers.ByteBuffer|null = null;
+ bb_pos = 0;
+__init(i:number, bb:flatbuffers.ByteBuffer):Referrable {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+}
+
+static getRootAsReferrable(bb:flatbuffers.ByteBuffer, obj?:Referrable):Referrable {
+ return (obj || new Referrable()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+}
+
+static getSizePrefixedRootAsReferrable(bb:flatbuffers.ByteBuffer, obj?:Referrable):Referrable {
+ bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new Referrable()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+}
+
+id():bigint {
+ const offset = this.bb!.__offset(this.bb_pos, 4);
+ return offset ? this.bb!.readUint64(this.bb_pos + offset) : BigInt('0');
+}
+
+mutate_id(value:bigint):boolean {
+ const offset = this.bb!.__offset(this.bb_pos, 4);
+
+ if (offset === 0) {
+ return false;
+ }
+
+ this.bb!.writeUint64(this.bb_pos + offset, value);
+ return true;
+}
+
+static getFullyQualifiedName():string {
+ return 'MyGame.Example.Referrable';
+}
+
+static startReferrable(builder:flatbuffers.Builder) {
+ builder.startObject(1);
+}
+
+static addId(builder:flatbuffers.Builder, id:bigint) {
+ builder.addFieldInt64(0, id, BigInt('0'));
+}
+
+static endReferrable(builder:flatbuffers.Builder):flatbuffers.Offset {
+ const offset = builder.endObject();
+ return offset;
+}
+
+static createReferrable(builder:flatbuffers.Builder, id:bigint):flatbuffers.Offset {
+ Referrable.startReferrable(builder);
+ Referrable.addId(builder, id);
+ return Referrable.endReferrable(builder);
+}
+
+serialize():Uint8Array {
+ return this.bb!.bytes();
+}
+
+static deserialize(buffer: Uint8Array):Referrable {
+ return Referrable.getRootAsReferrable(new flatbuffers.ByteBuffer(buffer))
+}
+
+unpack(): ReferrableT {
+ return new ReferrableT(
+ this.id()
+ );
+}
+
+
+unpackTo(_o: ReferrableT): void {
+ _o.id = this.id();
+}
+}
+
+export class ReferrableT {
+constructor(
+ public id: bigint = BigInt('0')
+){}
+
+
+pack(builder:flatbuffers.Builder): flatbuffers.Offset {
+ return Referrable.createReferrable(builder,
+ this.id
+ );
+}
+}
diff --git a/tests/my-game/example/stat.js b/tests/my-game/example/stat.js
new file mode 100644
index 0000000..46eec43
--- /dev/null
+++ b/tests/my-game/example/stat.js
@@ -0,0 +1,99 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+import * as flatbuffers from 'flatbuffers';
+export class Stat {
+ constructor() {
+ this.bb = null;
+ this.bb_pos = 0;
+ }
+ __init(i, bb) {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+ }
+ static getRootAsStat(bb, obj) {
+ return (obj || new Stat()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ static getSizePrefixedRootAsStat(bb, obj) {
+ bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new Stat()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ id(optionalEncoding) {
+ const offset = this.bb.__offset(this.bb_pos, 4);
+ return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
+ }
+ val() {
+ const offset = this.bb.__offset(this.bb_pos, 6);
+ return offset ? this.bb.readInt64(this.bb_pos + offset) : BigInt('0');
+ }
+ mutate_val(value) {
+ const offset = this.bb.__offset(this.bb_pos, 6);
+ if (offset === 0) {
+ return false;
+ }
+ this.bb.writeInt64(this.bb_pos + offset, value);
+ return true;
+ }
+ count() {
+ const offset = this.bb.__offset(this.bb_pos, 8);
+ return offset ? this.bb.readUint16(this.bb_pos + offset) : 0;
+ }
+ mutate_count(value) {
+ const offset = this.bb.__offset(this.bb_pos, 8);
+ if (offset === 0) {
+ return false;
+ }
+ this.bb.writeUint16(this.bb_pos + offset, value);
+ return true;
+ }
+ static getFullyQualifiedName() {
+ return 'MyGame.Example.Stat';
+ }
+ static startStat(builder) {
+ builder.startObject(3);
+ }
+ static addId(builder, idOffset) {
+ builder.addFieldOffset(0, idOffset, 0);
+ }
+ static addVal(builder, val) {
+ builder.addFieldInt64(1, val, BigInt('0'));
+ }
+ static addCount(builder, count) {
+ builder.addFieldInt16(2, count, 0);
+ }
+ static endStat(builder) {
+ const offset = builder.endObject();
+ return offset;
+ }
+ static createStat(builder, idOffset, val, count) {
+ Stat.startStat(builder);
+ Stat.addId(builder, idOffset);
+ Stat.addVal(builder, val);
+ Stat.addCount(builder, count);
+ return Stat.endStat(builder);
+ }
+ serialize() {
+ return this.bb.bytes();
+ }
+ static deserialize(buffer) {
+ return Stat.getRootAsStat(new flatbuffers.ByteBuffer(buffer));
+ }
+ unpack() {
+ return new StatT(this.id(), this.val(), this.count());
+ }
+ unpackTo(_o) {
+ _o.id = this.id();
+ _o.val = this.val();
+ _o.count = this.count();
+ }
+}
+export class StatT {
+ constructor(id = null, val = BigInt('0'), count = 0) {
+ this.id = id;
+ this.val = val;
+ this.count = count;
+ }
+ pack(builder) {
+ const id = (this.id !== null ? builder.createString(this.id) : 0);
+ return Stat.createStat(builder, id, this.val, this.count);
+ }
+}
diff --git a/tests/my-game/example/stat.ts b/tests/my-game/example/stat.ts
new file mode 100644
index 0000000..0082ef8
--- /dev/null
+++ b/tests/my-game/example/stat.ts
@@ -0,0 +1,138 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+import * as flatbuffers from 'flatbuffers';
+
+
+
+export class Stat {
+ bb: flatbuffers.ByteBuffer|null = null;
+ bb_pos = 0;
+__init(i:number, bb:flatbuffers.ByteBuffer):Stat {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+}
+
+static getRootAsStat(bb:flatbuffers.ByteBuffer, obj?:Stat):Stat {
+ return (obj || new Stat()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+}
+
+static getSizePrefixedRootAsStat(bb:flatbuffers.ByteBuffer, obj?:Stat):Stat {
+ bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new Stat()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+}
+
+id():string|null
+id(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null
+id(optionalEncoding?:any):string|Uint8Array|null {
+ const offset = this.bb!.__offset(this.bb_pos, 4);
+ return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
+}
+
+val():bigint {
+ const offset = this.bb!.__offset(this.bb_pos, 6);
+ return offset ? this.bb!.readInt64(this.bb_pos + offset) : BigInt('0');
+}
+
+mutate_val(value:bigint):boolean {
+ const offset = this.bb!.__offset(this.bb_pos, 6);
+
+ if (offset === 0) {
+ return false;
+ }
+
+ this.bb!.writeInt64(this.bb_pos + offset, value);
+ return true;
+}
+
+count():number {
+ const offset = this.bb!.__offset(this.bb_pos, 8);
+ return offset ? this.bb!.readUint16(this.bb_pos + offset) : 0;
+}
+
+mutate_count(value:number):boolean {
+ const offset = this.bb!.__offset(this.bb_pos, 8);
+
+ if (offset === 0) {
+ return false;
+ }
+
+ this.bb!.writeUint16(this.bb_pos + offset, value);
+ return true;
+}
+
+static getFullyQualifiedName():string {
+ return 'MyGame.Example.Stat';
+}
+
+static startStat(builder:flatbuffers.Builder) {
+ builder.startObject(3);
+}
+
+static addId(builder:flatbuffers.Builder, idOffset:flatbuffers.Offset) {
+ builder.addFieldOffset(0, idOffset, 0);
+}
+
+static addVal(builder:flatbuffers.Builder, val:bigint) {
+ builder.addFieldInt64(1, val, BigInt('0'));
+}
+
+static addCount(builder:flatbuffers.Builder, count:number) {
+ builder.addFieldInt16(2, count, 0);
+}
+
+static endStat(builder:flatbuffers.Builder):flatbuffers.Offset {
+ const offset = builder.endObject();
+ return offset;
+}
+
+static createStat(builder:flatbuffers.Builder, idOffset:flatbuffers.Offset, val:bigint, count:number):flatbuffers.Offset {
+ Stat.startStat(builder);
+ Stat.addId(builder, idOffset);
+ Stat.addVal(builder, val);
+ Stat.addCount(builder, count);
+ return Stat.endStat(builder);
+}
+
+serialize():Uint8Array {
+ return this.bb!.bytes();
+}
+
+static deserialize(buffer: Uint8Array):Stat {
+ return Stat.getRootAsStat(new flatbuffers.ByteBuffer(buffer))
+}
+
+unpack(): StatT {
+ return new StatT(
+ this.id(),
+ this.val(),
+ this.count()
+ );
+}
+
+
+unpackTo(_o: StatT): void {
+ _o.id = this.id();
+ _o.val = this.val();
+ _o.count = this.count();
+}
+}
+
+export class StatT {
+constructor(
+ public id: string|Uint8Array|null = null,
+ public val: bigint = BigInt('0'),
+ public count: number = 0
+){}
+
+
+pack(builder:flatbuffers.Builder): flatbuffers.Offset {
+ const id = (this.id !== null ? builder.createString(this.id!) : 0);
+
+ return Stat.createStat(builder,
+ id,
+ this.val,
+ this.count
+ );
+}
+}
diff --git a/tests/my-game/example/struct-of-structs.js b/tests/my-game/example/struct-of-structs.js
new file mode 100644
index 0000000..2debc29
--- /dev/null
+++ b/tests/my-game/example/struct-of-structs.js
@@ -0,0 +1,61 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+import { Ability } from '../../my-game/example/ability';
+import { Test } from '../../my-game/example/test';
+export class StructOfStructs {
+ constructor() {
+ this.bb = null;
+ this.bb_pos = 0;
+ }
+ __init(i, bb) {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+ }
+ a(obj) {
+ return (obj || new Ability()).__init(this.bb_pos, this.bb);
+ }
+ b(obj) {
+ return (obj || new Test()).__init(this.bb_pos + 8, this.bb);
+ }
+ c(obj) {
+ return (obj || new Ability()).__init(this.bb_pos + 12, this.bb);
+ }
+ static getFullyQualifiedName() {
+ return 'MyGame.Example.StructOfStructs';
+ }
+ static sizeOf() {
+ return 20;
+ }
+ static createStructOfStructs(builder, a_id, a_distance, b_a, b_b, c_id, c_distance) {
+ builder.prep(4, 20);
+ builder.prep(4, 8);
+ builder.writeInt32(c_distance);
+ builder.writeInt32(c_id);
+ builder.prep(2, 4);
+ builder.pad(1);
+ builder.writeInt8(b_b);
+ builder.writeInt16(b_a);
+ builder.prep(4, 8);
+ builder.writeInt32(a_distance);
+ builder.writeInt32(a_id);
+ return builder.offset();
+ }
+ unpack() {
+ return new StructOfStructsT((this.a() !== null ? this.a().unpack() : null), (this.b() !== null ? this.b().unpack() : null), (this.c() !== null ? this.c().unpack() : null));
+ }
+ unpackTo(_o) {
+ _o.a = (this.a() !== null ? this.a().unpack() : null);
+ _o.b = (this.b() !== null ? this.b().unpack() : null);
+ _o.c = (this.c() !== null ? this.c().unpack() : null);
+ }
+}
+export class StructOfStructsT {
+ constructor(a = null, b = null, c = null) {
+ this.a = a;
+ this.b = b;
+ this.c = c;
+ }
+ pack(builder) {
+ return StructOfStructs.createStructOfStructs(builder, (this.a === null ? 0 : this.a.id), (this.a === null ? 0 : this.a.distance), (this.b === null ? 0 : this.b.a), (this.b === null ? 0 : this.b.b), (this.c === null ? 0 : this.c.id), (this.c === null ? 0 : this.c.distance));
+ }
+}
diff --git a/tests/my-game/example/struct-of-structs.ts b/tests/my-game/example/struct-of-structs.ts
new file mode 100644
index 0000000..11eca7e
--- /dev/null
+++ b/tests/my-game/example/struct-of-structs.ts
@@ -0,0 +1,88 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+import * as flatbuffers from 'flatbuffers';
+
+import { Ability, AbilityT } from '../../my-game/example/ability';
+import { Test, TestT } from '../../my-game/example/test';
+
+
+export class StructOfStructs {
+ bb: flatbuffers.ByteBuffer|null = null;
+ bb_pos = 0;
+__init(i:number, bb:flatbuffers.ByteBuffer):StructOfStructs {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+}
+
+a(obj?:Ability):Ability|null {
+ return (obj || new Ability()).__init(this.bb_pos, this.bb!);
+}
+
+b(obj?:Test):Test|null {
+ return (obj || new Test()).__init(this.bb_pos + 8, this.bb!);
+}
+
+c(obj?:Ability):Ability|null {
+ return (obj || new Ability()).__init(this.bb_pos + 12, this.bb!);
+}
+
+static getFullyQualifiedName():string {
+ return 'MyGame.Example.StructOfStructs';
+}
+
+static sizeOf():number {
+ return 20;
+}
+
+static createStructOfStructs(builder:flatbuffers.Builder, a_id: number, a_distance: number, b_a: number, b_b: number, c_id: number, c_distance: number):flatbuffers.Offset {
+ builder.prep(4, 20);
+ builder.prep(4, 8);
+ builder.writeInt32(c_distance);
+ builder.writeInt32(c_id);
+ builder.prep(2, 4);
+ builder.pad(1);
+ builder.writeInt8(b_b);
+ builder.writeInt16(b_a);
+ builder.prep(4, 8);
+ builder.writeInt32(a_distance);
+ builder.writeInt32(a_id);
+ return builder.offset();
+}
+
+
+unpack(): StructOfStructsT {
+ return new StructOfStructsT(
+ (this.a() !== null ? this.a()!.unpack() : null),
+ (this.b() !== null ? this.b()!.unpack() : null),
+ (this.c() !== null ? this.c()!.unpack() : null)
+ );
+}
+
+
+unpackTo(_o: StructOfStructsT): void {
+ _o.a = (this.a() !== null ? this.a()!.unpack() : null);
+ _o.b = (this.b() !== null ? this.b()!.unpack() : null);
+ _o.c = (this.c() !== null ? this.c()!.unpack() : null);
+}
+}
+
+export class StructOfStructsT {
+constructor(
+ public a: AbilityT|null = null,
+ public b: TestT|null = null,
+ public c: AbilityT|null = null
+){}
+
+
+pack(builder:flatbuffers.Builder): flatbuffers.Offset {
+ return StructOfStructs.createStructOfStructs(builder,
+ (this.a === null ? 0 : this.a.id!),
+ (this.a === null ? 0 : this.a.distance!),
+ (this.b === null ? 0 : this.b.a!),
+ (this.b === null ? 0 : this.b.b!),
+ (this.c === null ? 0 : this.c.id!),
+ (this.c === null ? 0 : this.c.distance!)
+ );
+}
+}
diff --git a/tests/my-game/example/test-simple-table-with-enum.js b/tests/my-game/example/test-simple-table-with-enum.js
new file mode 100644
index 0000000..b56bda4
--- /dev/null
+++ b/tests/my-game/example/test-simple-table-with-enum.js
@@ -0,0 +1,71 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+import * as flatbuffers from 'flatbuffers';
+import { Color } from '../../my-game/example/color';
+export class TestSimpleTableWithEnum {
+ constructor() {
+ this.bb = null;
+ this.bb_pos = 0;
+ }
+ __init(i, bb) {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+ }
+ static getRootAsTestSimpleTableWithEnum(bb, obj) {
+ return (obj || new TestSimpleTableWithEnum()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ static getSizePrefixedRootAsTestSimpleTableWithEnum(bb, obj) {
+ bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new TestSimpleTableWithEnum()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ color() {
+ const offset = this.bb.__offset(this.bb_pos, 4);
+ return offset ? this.bb.readUint8(this.bb_pos + offset) : Color.Green;
+ }
+ mutate_color(value) {
+ const offset = this.bb.__offset(this.bb_pos, 4);
+ if (offset === 0) {
+ return false;
+ }
+ this.bb.writeUint8(this.bb_pos + offset, value);
+ return true;
+ }
+ static getFullyQualifiedName() {
+ return 'MyGame.Example.TestSimpleTableWithEnum';
+ }
+ static startTestSimpleTableWithEnum(builder) {
+ builder.startObject(1);
+ }
+ static addColor(builder, color) {
+ builder.addFieldInt8(0, color, Color.Green);
+ }
+ static endTestSimpleTableWithEnum(builder) {
+ const offset = builder.endObject();
+ return offset;
+ }
+ static createTestSimpleTableWithEnum(builder, color) {
+ TestSimpleTableWithEnum.startTestSimpleTableWithEnum(builder);
+ TestSimpleTableWithEnum.addColor(builder, color);
+ return TestSimpleTableWithEnum.endTestSimpleTableWithEnum(builder);
+ }
+ serialize() {
+ return this.bb.bytes();
+ }
+ static deserialize(buffer) {
+ return TestSimpleTableWithEnum.getRootAsTestSimpleTableWithEnum(new flatbuffers.ByteBuffer(buffer));
+ }
+ unpack() {
+ return new TestSimpleTableWithEnumT(this.color());
+ }
+ unpackTo(_o) {
+ _o.color = this.color();
+ }
+}
+export class TestSimpleTableWithEnumT {
+ constructor(color = Color.Green) {
+ this.color = color;
+ }
+ pack(builder) {
+ return TestSimpleTableWithEnum.createTestSimpleTableWithEnum(builder, this.color);
+ }
+}
diff --git a/tests/my-game/example/test-simple-table-with-enum.ts b/tests/my-game/example/test-simple-table-with-enum.ts
new file mode 100644
index 0000000..99a541f
--- /dev/null
+++ b/tests/my-game/example/test-simple-table-with-enum.ts
@@ -0,0 +1,96 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+import * as flatbuffers from 'flatbuffers';
+
+import { Color } from '../../my-game/example/color';
+
+
+export class TestSimpleTableWithEnum {
+ bb: flatbuffers.ByteBuffer|null = null;
+ bb_pos = 0;
+__init(i:number, bb:flatbuffers.ByteBuffer):TestSimpleTableWithEnum {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+}
+
+static getRootAsTestSimpleTableWithEnum(bb:flatbuffers.ByteBuffer, obj?:TestSimpleTableWithEnum):TestSimpleTableWithEnum {
+ return (obj || new TestSimpleTableWithEnum()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+}
+
+static getSizePrefixedRootAsTestSimpleTableWithEnum(bb:flatbuffers.ByteBuffer, obj?:TestSimpleTableWithEnum):TestSimpleTableWithEnum {
+ bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new TestSimpleTableWithEnum()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+}
+
+color():Color {
+ const offset = this.bb!.__offset(this.bb_pos, 4);
+ return offset ? this.bb!.readUint8(this.bb_pos + offset) : Color.Green;
+}
+
+mutate_color(value:Color):boolean {
+ const offset = this.bb!.__offset(this.bb_pos, 4);
+
+ if (offset === 0) {
+ return false;
+ }
+
+ this.bb!.writeUint8(this.bb_pos + offset, value);
+ return true;
+}
+
+static getFullyQualifiedName():string {
+ return 'MyGame.Example.TestSimpleTableWithEnum';
+}
+
+static startTestSimpleTableWithEnum(builder:flatbuffers.Builder) {
+ builder.startObject(1);
+}
+
+static addColor(builder:flatbuffers.Builder, color:Color) {
+ builder.addFieldInt8(0, color, Color.Green);
+}
+
+static endTestSimpleTableWithEnum(builder:flatbuffers.Builder):flatbuffers.Offset {
+ const offset = builder.endObject();
+ return offset;
+}
+
+static createTestSimpleTableWithEnum(builder:flatbuffers.Builder, color:Color):flatbuffers.Offset {
+ TestSimpleTableWithEnum.startTestSimpleTableWithEnum(builder);
+ TestSimpleTableWithEnum.addColor(builder, color);
+ return TestSimpleTableWithEnum.endTestSimpleTableWithEnum(builder);
+}
+
+serialize():Uint8Array {
+ return this.bb!.bytes();
+}
+
+static deserialize(buffer: Uint8Array):TestSimpleTableWithEnum {
+ return TestSimpleTableWithEnum.getRootAsTestSimpleTableWithEnum(new flatbuffers.ByteBuffer(buffer))
+}
+
+unpack(): TestSimpleTableWithEnumT {
+ return new TestSimpleTableWithEnumT(
+ this.color()
+ );
+}
+
+
+unpackTo(_o: TestSimpleTableWithEnumT): void {
+ _o.color = this.color();
+}
+}
+
+export class TestSimpleTableWithEnumT {
+constructor(
+ public color: Color = Color.Green
+){}
+
+
+pack(builder:flatbuffers.Builder): flatbuffers.Offset {
+ return TestSimpleTableWithEnum.createTestSimpleTableWithEnum(builder,
+ this.color
+ );
+}
+}
diff --git a/tests/my-game/example/test.js b/tests/my-game/example/test.js
new file mode 100644
index 0000000..ba6ebfb
--- /dev/null
+++ b/tests/my-game/example/test.js
@@ -0,0 +1,55 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+export class Test {
+ constructor() {
+ this.bb = null;
+ this.bb_pos = 0;
+ }
+ __init(i, bb) {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+ }
+ a() {
+ return this.bb.readInt16(this.bb_pos);
+ }
+ mutate_a(value) {
+ this.bb.writeInt16(this.bb_pos + 0, value);
+ return true;
+ }
+ b() {
+ return this.bb.readInt8(this.bb_pos + 2);
+ }
+ mutate_b(value) {
+ this.bb.writeInt8(this.bb_pos + 2, value);
+ return true;
+ }
+ static getFullyQualifiedName() {
+ return 'MyGame.Example.Test';
+ }
+ static sizeOf() {
+ return 4;
+ }
+ static createTest(builder, a, b) {
+ builder.prep(2, 4);
+ builder.pad(1);
+ builder.writeInt8(b);
+ builder.writeInt16(a);
+ return builder.offset();
+ }
+ unpack() {
+ return new TestT(this.a(), this.b());
+ }
+ unpackTo(_o) {
+ _o.a = this.a();
+ _o.b = this.b();
+ }
+}
+export class TestT {
+ constructor(a = 0, b = 0) {
+ this.a = a;
+ this.b = b;
+ }
+ pack(builder) {
+ return Test.createTest(builder, this.a, this.b);
+ }
+}
diff --git a/tests/my-game/example/test.ts b/tests/my-game/example/test.ts
new file mode 100644
index 0000000..afed125
--- /dev/null
+++ b/tests/my-game/example/test.ts
@@ -0,0 +1,78 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+import * as flatbuffers from 'flatbuffers';
+
+
+
+export class Test {
+ bb: flatbuffers.ByteBuffer|null = null;
+ bb_pos = 0;
+__init(i:number, bb:flatbuffers.ByteBuffer):Test {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+}
+
+a():number {
+ return this.bb!.readInt16(this.bb_pos);
+}
+
+mutate_a(value:number):boolean {
+ this.bb!.writeInt16(this.bb_pos + 0, value);
+ return true;
+}
+
+b():number {
+ return this.bb!.readInt8(this.bb_pos + 2);
+}
+
+mutate_b(value:number):boolean {
+ this.bb!.writeInt8(this.bb_pos + 2, value);
+ return true;
+}
+
+static getFullyQualifiedName():string {
+ return 'MyGame.Example.Test';
+}
+
+static sizeOf():number {
+ return 4;
+}
+
+static createTest(builder:flatbuffers.Builder, a: number, b: number):flatbuffers.Offset {
+ builder.prep(2, 4);
+ builder.pad(1);
+ builder.writeInt8(b);
+ builder.writeInt16(a);
+ return builder.offset();
+}
+
+
+unpack(): TestT {
+ return new TestT(
+ this.a(),
+ this.b()
+ );
+}
+
+
+unpackTo(_o: TestT): void {
+ _o.a = this.a();
+ _o.b = this.b();
+}
+}
+
+export class TestT {
+constructor(
+ public a: number = 0,
+ public b: number = 0
+){}
+
+
+pack(builder:flatbuffers.Builder): flatbuffers.Offset {
+ return Test.createTest(builder,
+ this.a,
+ this.b
+ );
+}
+}
diff --git a/tests/my-game/example/type-aliases.js b/tests/my-game/example/type-aliases.js
new file mode 100644
index 0000000..f26f226
--- /dev/null
+++ b/tests/my-game/example/type-aliases.js
@@ -0,0 +1,290 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+import * as flatbuffers from 'flatbuffers';
+export class TypeAliases {
+ constructor() {
+ this.bb = null;
+ this.bb_pos = 0;
+ }
+ __init(i, bb) {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+ }
+ static getRootAsTypeAliases(bb, obj) {
+ return (obj || new TypeAliases()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ static getSizePrefixedRootAsTypeAliases(bb, obj) {
+ bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new TypeAliases()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ i8() {
+ const offset = this.bb.__offset(this.bb_pos, 4);
+ return offset ? this.bb.readInt8(this.bb_pos + offset) : 0;
+ }
+ mutate_i8(value) {
+ const offset = this.bb.__offset(this.bb_pos, 4);
+ if (offset === 0) {
+ return false;
+ }
+ this.bb.writeInt8(this.bb_pos + offset, value);
+ return true;
+ }
+ u8() {
+ const offset = this.bb.__offset(this.bb_pos, 6);
+ return offset ? this.bb.readUint8(this.bb_pos + offset) : 0;
+ }
+ mutate_u8(value) {
+ const offset = this.bb.__offset(this.bb_pos, 6);
+ if (offset === 0) {
+ return false;
+ }
+ this.bb.writeUint8(this.bb_pos + offset, value);
+ return true;
+ }
+ i16() {
+ const offset = this.bb.__offset(this.bb_pos, 8);
+ return offset ? this.bb.readInt16(this.bb_pos + offset) : 0;
+ }
+ mutate_i16(value) {
+ const offset = this.bb.__offset(this.bb_pos, 8);
+ if (offset === 0) {
+ return false;
+ }
+ this.bb.writeInt16(this.bb_pos + offset, value);
+ return true;
+ }
+ u16() {
+ const offset = this.bb.__offset(this.bb_pos, 10);
+ return offset ? this.bb.readUint16(this.bb_pos + offset) : 0;
+ }
+ mutate_u16(value) {
+ const offset = this.bb.__offset(this.bb_pos, 10);
+ if (offset === 0) {
+ return false;
+ }
+ this.bb.writeUint16(this.bb_pos + offset, value);
+ return true;
+ }
+ i32() {
+ const offset = this.bb.__offset(this.bb_pos, 12);
+ return offset ? this.bb.readInt32(this.bb_pos + offset) : 0;
+ }
+ mutate_i32(value) {
+ const offset = this.bb.__offset(this.bb_pos, 12);
+ if (offset === 0) {
+ return false;
+ }
+ this.bb.writeInt32(this.bb_pos + offset, value);
+ return true;
+ }
+ u32() {
+ const offset = this.bb.__offset(this.bb_pos, 14);
+ return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
+ }
+ mutate_u32(value) {
+ const offset = this.bb.__offset(this.bb_pos, 14);
+ if (offset === 0) {
+ return false;
+ }
+ this.bb.writeUint32(this.bb_pos + offset, value);
+ return true;
+ }
+ i64() {
+ const offset = this.bb.__offset(this.bb_pos, 16);
+ return offset ? this.bb.readInt64(this.bb_pos + offset) : BigInt('0');
+ }
+ mutate_i64(value) {
+ const offset = this.bb.__offset(this.bb_pos, 16);
+ if (offset === 0) {
+ return false;
+ }
+ this.bb.writeInt64(this.bb_pos + offset, value);
+ return true;
+ }
+ u64() {
+ const offset = this.bb.__offset(this.bb_pos, 18);
+ return offset ? this.bb.readUint64(this.bb_pos + offset) : BigInt('0');
+ }
+ mutate_u64(value) {
+ const offset = this.bb.__offset(this.bb_pos, 18);
+ if (offset === 0) {
+ return false;
+ }
+ this.bb.writeUint64(this.bb_pos + offset, value);
+ return true;
+ }
+ f32() {
+ const offset = this.bb.__offset(this.bb_pos, 20);
+ return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0.0;
+ }
+ mutate_f32(value) {
+ const offset = this.bb.__offset(this.bb_pos, 20);
+ if (offset === 0) {
+ return false;
+ }
+ this.bb.writeFloat32(this.bb_pos + offset, value);
+ return true;
+ }
+ f64() {
+ const offset = this.bb.__offset(this.bb_pos, 22);
+ return offset ? this.bb.readFloat64(this.bb_pos + offset) : 0.0;
+ }
+ mutate_f64(value) {
+ const offset = this.bb.__offset(this.bb_pos, 22);
+ if (offset === 0) {
+ return false;
+ }
+ this.bb.writeFloat64(this.bb_pos + offset, value);
+ return true;
+ }
+ v8(index) {
+ const offset = this.bb.__offset(this.bb_pos, 24);
+ return offset ? this.bb.readInt8(this.bb.__vector(this.bb_pos + offset) + index) : 0;
+ }
+ v8Length() {
+ const offset = this.bb.__offset(this.bb_pos, 24);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ v8Array() {
+ const offset = this.bb.__offset(this.bb_pos, 24);
+ return offset ? new Int8Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null;
+ }
+ vf64(index) {
+ const offset = this.bb.__offset(this.bb_pos, 26);
+ return offset ? this.bb.readFloat64(this.bb.__vector(this.bb_pos + offset) + index * 8) : 0;
+ }
+ vf64Length() {
+ const offset = this.bb.__offset(this.bb_pos, 26);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ vf64Array() {
+ const offset = this.bb.__offset(this.bb_pos, 26);
+ return offset ? new Float64Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null;
+ }
+ static getFullyQualifiedName() {
+ return 'MyGame.Example.TypeAliases';
+ }
+ static startTypeAliases(builder) {
+ builder.startObject(12);
+ }
+ static addI8(builder, i8) {
+ builder.addFieldInt8(0, i8, 0);
+ }
+ static addU8(builder, u8) {
+ builder.addFieldInt8(1, u8, 0);
+ }
+ static addI16(builder, i16) {
+ builder.addFieldInt16(2, i16, 0);
+ }
+ static addU16(builder, u16) {
+ builder.addFieldInt16(3, u16, 0);
+ }
+ static addI32(builder, i32) {
+ builder.addFieldInt32(4, i32, 0);
+ }
+ static addU32(builder, u32) {
+ builder.addFieldInt32(5, u32, 0);
+ }
+ static addI64(builder, i64) {
+ builder.addFieldInt64(6, i64, BigInt('0'));
+ }
+ static addU64(builder, u64) {
+ builder.addFieldInt64(7, u64, BigInt('0'));
+ }
+ static addF32(builder, f32) {
+ builder.addFieldFloat32(8, f32, 0.0);
+ }
+ static addF64(builder, f64) {
+ builder.addFieldFloat64(9, f64, 0.0);
+ }
+ static addV8(builder, v8Offset) {
+ builder.addFieldOffset(10, v8Offset, 0);
+ }
+ static createV8Vector(builder, data) {
+ builder.startVector(1, data.length, 1);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addInt8(data[i]);
+ }
+ return builder.endVector();
+ }
+ static startV8Vector(builder, numElems) {
+ builder.startVector(1, numElems, 1);
+ }
+ static addVf64(builder, vf64Offset) {
+ builder.addFieldOffset(11, vf64Offset, 0);
+ }
+ static createVf64Vector(builder, data) {
+ builder.startVector(8, data.length, 8);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addFloat64(data[i]);
+ }
+ return builder.endVector();
+ }
+ static startVf64Vector(builder, numElems) {
+ builder.startVector(8, numElems, 8);
+ }
+ static endTypeAliases(builder) {
+ const offset = builder.endObject();
+ return offset;
+ }
+ static createTypeAliases(builder, i8, u8, i16, u16, i32, u32, i64, u64, f32, f64, v8Offset, vf64Offset) {
+ TypeAliases.startTypeAliases(builder);
+ TypeAliases.addI8(builder, i8);
+ TypeAliases.addU8(builder, u8);
+ TypeAliases.addI16(builder, i16);
+ TypeAliases.addU16(builder, u16);
+ TypeAliases.addI32(builder, i32);
+ TypeAliases.addU32(builder, u32);
+ TypeAliases.addI64(builder, i64);
+ TypeAliases.addU64(builder, u64);
+ TypeAliases.addF32(builder, f32);
+ TypeAliases.addF64(builder, f64);
+ TypeAliases.addV8(builder, v8Offset);
+ TypeAliases.addVf64(builder, vf64Offset);
+ return TypeAliases.endTypeAliases(builder);
+ }
+ serialize() {
+ return this.bb.bytes();
+ }
+ static deserialize(buffer) {
+ return TypeAliases.getRootAsTypeAliases(new flatbuffers.ByteBuffer(buffer));
+ }
+ unpack() {
+ return new TypeAliasesT(this.i8(), this.u8(), this.i16(), this.u16(), this.i32(), this.u32(), this.i64(), this.u64(), this.f32(), this.f64(), this.bb.createScalarList(this.v8.bind(this), this.v8Length()), this.bb.createScalarList(this.vf64.bind(this), this.vf64Length()));
+ }
+ unpackTo(_o) {
+ _o.i8 = this.i8();
+ _o.u8 = this.u8();
+ _o.i16 = this.i16();
+ _o.u16 = this.u16();
+ _o.i32 = this.i32();
+ _o.u32 = this.u32();
+ _o.i64 = this.i64();
+ _o.u64 = this.u64();
+ _o.f32 = this.f32();
+ _o.f64 = this.f64();
+ _o.v8 = this.bb.createScalarList(this.v8.bind(this), this.v8Length());
+ _o.vf64 = this.bb.createScalarList(this.vf64.bind(this), this.vf64Length());
+ }
+}
+export class TypeAliasesT {
+ constructor(i8 = 0, u8 = 0, i16 = 0, u16 = 0, i32 = 0, u32 = 0, i64 = BigInt('0'), u64 = BigInt('0'), f32 = 0.0, f64 = 0.0, v8 = [], vf64 = []) {
+ this.i8 = i8;
+ this.u8 = u8;
+ this.i16 = i16;
+ this.u16 = u16;
+ this.i32 = i32;
+ this.u32 = u32;
+ this.i64 = i64;
+ this.u64 = u64;
+ this.f32 = f32;
+ this.f64 = f64;
+ this.v8 = v8;
+ this.vf64 = vf64;
+ }
+ pack(builder) {
+ const v8 = TypeAliases.createV8Vector(builder, this.v8);
+ const vf64 = TypeAliases.createVf64Vector(builder, this.vf64);
+ return TypeAliases.createTypeAliases(builder, this.i8, this.u8, this.i16, this.u16, this.i32, this.u32, this.i64, this.u64, this.f32, this.f64, v8, vf64);
+ }
+}
diff --git a/tests/my-game/example/type-aliases.ts b/tests/my-game/example/type-aliases.ts
new file mode 100644
index 0000000..edb4567
--- /dev/null
+++ b/tests/my-game/example/type-aliases.ts
@@ -0,0 +1,405 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+import * as flatbuffers from 'flatbuffers';
+
+
+
+export class TypeAliases {
+ bb: flatbuffers.ByteBuffer|null = null;
+ bb_pos = 0;
+__init(i:number, bb:flatbuffers.ByteBuffer):TypeAliases {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+}
+
+static getRootAsTypeAliases(bb:flatbuffers.ByteBuffer, obj?:TypeAliases):TypeAliases {
+ return (obj || new TypeAliases()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+}
+
+static getSizePrefixedRootAsTypeAliases(bb:flatbuffers.ByteBuffer, obj?:TypeAliases):TypeAliases {
+ bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new TypeAliases()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+}
+
+i8():number {
+ const offset = this.bb!.__offset(this.bb_pos, 4);
+ return offset ? this.bb!.readInt8(this.bb_pos + offset) : 0;
+}
+
+mutate_i8(value:number):boolean {
+ const offset = this.bb!.__offset(this.bb_pos, 4);
+
+ if (offset === 0) {
+ return false;
+ }
+
+ this.bb!.writeInt8(this.bb_pos + offset, value);
+ return true;
+}
+
+u8():number {
+ const offset = this.bb!.__offset(this.bb_pos, 6);
+ return offset ? this.bb!.readUint8(this.bb_pos + offset) : 0;
+}
+
+mutate_u8(value:number):boolean {
+ const offset = this.bb!.__offset(this.bb_pos, 6);
+
+ if (offset === 0) {
+ return false;
+ }
+
+ this.bb!.writeUint8(this.bb_pos + offset, value);
+ return true;
+}
+
+i16():number {
+ const offset = this.bb!.__offset(this.bb_pos, 8);
+ return offset ? this.bb!.readInt16(this.bb_pos + offset) : 0;
+}
+
+mutate_i16(value:number):boolean {
+ const offset = this.bb!.__offset(this.bb_pos, 8);
+
+ if (offset === 0) {
+ return false;
+ }
+
+ this.bb!.writeInt16(this.bb_pos + offset, value);
+ return true;
+}
+
+u16():number {
+ const offset = this.bb!.__offset(this.bb_pos, 10);
+ return offset ? this.bb!.readUint16(this.bb_pos + offset) : 0;
+}
+
+mutate_u16(value:number):boolean {
+ const offset = this.bb!.__offset(this.bb_pos, 10);
+
+ if (offset === 0) {
+ return false;
+ }
+
+ this.bb!.writeUint16(this.bb_pos + offset, value);
+ return true;
+}
+
+i32():number {
+ const offset = this.bb!.__offset(this.bb_pos, 12);
+ return offset ? this.bb!.readInt32(this.bb_pos + offset) : 0;
+}
+
+mutate_i32(value:number):boolean {
+ const offset = this.bb!.__offset(this.bb_pos, 12);
+
+ if (offset === 0) {
+ return false;
+ }
+
+ this.bb!.writeInt32(this.bb_pos + offset, value);
+ return true;
+}
+
+u32():number {
+ const offset = this.bb!.__offset(this.bb_pos, 14);
+ return offset ? this.bb!.readUint32(this.bb_pos + offset) : 0;
+}
+
+mutate_u32(value:number):boolean {
+ const offset = this.bb!.__offset(this.bb_pos, 14);
+
+ if (offset === 0) {
+ return false;
+ }
+
+ this.bb!.writeUint32(this.bb_pos + offset, value);
+ return true;
+}
+
+i64():bigint {
+ const offset = this.bb!.__offset(this.bb_pos, 16);
+ return offset ? this.bb!.readInt64(this.bb_pos + offset) : BigInt('0');
+}
+
+mutate_i64(value:bigint):boolean {
+ const offset = this.bb!.__offset(this.bb_pos, 16);
+
+ if (offset === 0) {
+ return false;
+ }
+
+ this.bb!.writeInt64(this.bb_pos + offset, value);
+ return true;
+}
+
+u64():bigint {
+ const offset = this.bb!.__offset(this.bb_pos, 18);
+ return offset ? this.bb!.readUint64(this.bb_pos + offset) : BigInt('0');
+}
+
+mutate_u64(value:bigint):boolean {
+ const offset = this.bb!.__offset(this.bb_pos, 18);
+
+ if (offset === 0) {
+ return false;
+ }
+
+ this.bb!.writeUint64(this.bb_pos + offset, value);
+ return true;
+}
+
+f32():number {
+ const offset = this.bb!.__offset(this.bb_pos, 20);
+ return offset ? this.bb!.readFloat32(this.bb_pos + offset) : 0.0;
+}
+
+mutate_f32(value:number):boolean {
+ const offset = this.bb!.__offset(this.bb_pos, 20);
+
+ if (offset === 0) {
+ return false;
+ }
+
+ this.bb!.writeFloat32(this.bb_pos + offset, value);
+ return true;
+}
+
+f64():number {
+ const offset = this.bb!.__offset(this.bb_pos, 22);
+ return offset ? this.bb!.readFloat64(this.bb_pos + offset) : 0.0;
+}
+
+mutate_f64(value:number):boolean {
+ const offset = this.bb!.__offset(this.bb_pos, 22);
+
+ if (offset === 0) {
+ return false;
+ }
+
+ this.bb!.writeFloat64(this.bb_pos + offset, value);
+ return true;
+}
+
+v8(index: number):number|null {
+ const offset = this.bb!.__offset(this.bb_pos, 24);
+ return offset ? this.bb!.readInt8(this.bb!.__vector(this.bb_pos + offset) + index) : 0;
+}
+
+v8Length():number {
+ const offset = this.bb!.__offset(this.bb_pos, 24);
+ return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
+}
+
+v8Array():Int8Array|null {
+ const offset = this.bb!.__offset(this.bb_pos, 24);
+ return offset ? new Int8Array(this.bb!.bytes().buffer, this.bb!.bytes().byteOffset + this.bb!.__vector(this.bb_pos + offset), this.bb!.__vector_len(this.bb_pos + offset)) : null;
+}
+
+vf64(index: number):number|null {
+ const offset = this.bb!.__offset(this.bb_pos, 26);
+ return offset ? this.bb!.readFloat64(this.bb!.__vector(this.bb_pos + offset) + index * 8) : 0;
+}
+
+vf64Length():number {
+ const offset = this.bb!.__offset(this.bb_pos, 26);
+ return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
+}
+
+vf64Array():Float64Array|null {
+ const offset = this.bb!.__offset(this.bb_pos, 26);
+ return offset ? new Float64Array(this.bb!.bytes().buffer, this.bb!.bytes().byteOffset + this.bb!.__vector(this.bb_pos + offset), this.bb!.__vector_len(this.bb_pos + offset)) : null;
+}
+
+static getFullyQualifiedName():string {
+ return 'MyGame.Example.TypeAliases';
+}
+
+static startTypeAliases(builder:flatbuffers.Builder) {
+ builder.startObject(12);
+}
+
+static addI8(builder:flatbuffers.Builder, i8:number) {
+ builder.addFieldInt8(0, i8, 0);
+}
+
+static addU8(builder:flatbuffers.Builder, u8:number) {
+ builder.addFieldInt8(1, u8, 0);
+}
+
+static addI16(builder:flatbuffers.Builder, i16:number) {
+ builder.addFieldInt16(2, i16, 0);
+}
+
+static addU16(builder:flatbuffers.Builder, u16:number) {
+ builder.addFieldInt16(3, u16, 0);
+}
+
+static addI32(builder:flatbuffers.Builder, i32:number) {
+ builder.addFieldInt32(4, i32, 0);
+}
+
+static addU32(builder:flatbuffers.Builder, u32:number) {
+ builder.addFieldInt32(5, u32, 0);
+}
+
+static addI64(builder:flatbuffers.Builder, i64:bigint) {
+ builder.addFieldInt64(6, i64, BigInt('0'));
+}
+
+static addU64(builder:flatbuffers.Builder, u64:bigint) {
+ builder.addFieldInt64(7, u64, BigInt('0'));
+}
+
+static addF32(builder:flatbuffers.Builder, f32:number) {
+ builder.addFieldFloat32(8, f32, 0.0);
+}
+
+static addF64(builder:flatbuffers.Builder, f64:number) {
+ builder.addFieldFloat64(9, f64, 0.0);
+}
+
+static addV8(builder:flatbuffers.Builder, v8Offset:flatbuffers.Offset) {
+ builder.addFieldOffset(10, v8Offset, 0);
+}
+
+static createV8Vector(builder:flatbuffers.Builder, data:number[]|Int8Array):flatbuffers.Offset;
+/**
+ * @deprecated This Uint8Array overload will be removed in the future.
+ */
+static createV8Vector(builder:flatbuffers.Builder, data:number[]|Uint8Array):flatbuffers.Offset;
+static createV8Vector(builder:flatbuffers.Builder, data:number[]|Int8Array|Uint8Array):flatbuffers.Offset {
+ builder.startVector(1, data.length, 1);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addInt8(data[i]!);
+ }
+ return builder.endVector();
+}
+
+static startV8Vector(builder:flatbuffers.Builder, numElems:number) {
+ builder.startVector(1, numElems, 1);
+}
+
+static addVf64(builder:flatbuffers.Builder, vf64Offset:flatbuffers.Offset) {
+ builder.addFieldOffset(11, vf64Offset, 0);
+}
+
+static createVf64Vector(builder:flatbuffers.Builder, data:number[]|Float64Array):flatbuffers.Offset;
+/**
+ * @deprecated This Uint8Array overload will be removed in the future.
+ */
+static createVf64Vector(builder:flatbuffers.Builder, data:number[]|Uint8Array):flatbuffers.Offset;
+static createVf64Vector(builder:flatbuffers.Builder, data:number[]|Float64Array|Uint8Array):flatbuffers.Offset {
+ builder.startVector(8, data.length, 8);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addFloat64(data[i]!);
+ }
+ return builder.endVector();
+}
+
+static startVf64Vector(builder:flatbuffers.Builder, numElems:number) {
+ builder.startVector(8, numElems, 8);
+}
+
+static endTypeAliases(builder:flatbuffers.Builder):flatbuffers.Offset {
+ const offset = builder.endObject();
+ return offset;
+}
+
+static createTypeAliases(builder:flatbuffers.Builder, i8:number, u8:number, i16:number, u16:number, i32:number, u32:number, i64:bigint, u64:bigint, f32:number, f64:number, v8Offset:flatbuffers.Offset, vf64Offset:flatbuffers.Offset):flatbuffers.Offset {
+ TypeAliases.startTypeAliases(builder);
+ TypeAliases.addI8(builder, i8);
+ TypeAliases.addU8(builder, u8);
+ TypeAliases.addI16(builder, i16);
+ TypeAliases.addU16(builder, u16);
+ TypeAliases.addI32(builder, i32);
+ TypeAliases.addU32(builder, u32);
+ TypeAliases.addI64(builder, i64);
+ TypeAliases.addU64(builder, u64);
+ TypeAliases.addF32(builder, f32);
+ TypeAliases.addF64(builder, f64);
+ TypeAliases.addV8(builder, v8Offset);
+ TypeAliases.addVf64(builder, vf64Offset);
+ return TypeAliases.endTypeAliases(builder);
+}
+
+serialize():Uint8Array {
+ return this.bb!.bytes();
+}
+
+static deserialize(buffer: Uint8Array):TypeAliases {
+ return TypeAliases.getRootAsTypeAliases(new flatbuffers.ByteBuffer(buffer))
+}
+
+unpack(): TypeAliasesT {
+ return new TypeAliasesT(
+ this.i8(),
+ this.u8(),
+ this.i16(),
+ this.u16(),
+ this.i32(),
+ this.u32(),
+ this.i64(),
+ this.u64(),
+ this.f32(),
+ this.f64(),
+ this.bb!.createScalarList(this.v8.bind(this), this.v8Length()),
+ this.bb!.createScalarList(this.vf64.bind(this), this.vf64Length())
+ );
+}
+
+
+unpackTo(_o: TypeAliasesT): void {
+ _o.i8 = this.i8();
+ _o.u8 = this.u8();
+ _o.i16 = this.i16();
+ _o.u16 = this.u16();
+ _o.i32 = this.i32();
+ _o.u32 = this.u32();
+ _o.i64 = this.i64();
+ _o.u64 = this.u64();
+ _o.f32 = this.f32();
+ _o.f64 = this.f64();
+ _o.v8 = this.bb!.createScalarList(this.v8.bind(this), this.v8Length());
+ _o.vf64 = this.bb!.createScalarList(this.vf64.bind(this), this.vf64Length());
+}
+}
+
+export class TypeAliasesT {
+constructor(
+ public i8: number = 0,
+ public u8: number = 0,
+ public i16: number = 0,
+ public u16: number = 0,
+ public i32: number = 0,
+ public u32: number = 0,
+ public i64: bigint = BigInt('0'),
+ public u64: bigint = BigInt('0'),
+ public f32: number = 0.0,
+ public f64: number = 0.0,
+ public v8: (number)[] = [],
+ public vf64: (number)[] = []
+){}
+
+
+pack(builder:flatbuffers.Builder): flatbuffers.Offset {
+ const v8 = TypeAliases.createV8Vector(builder, this.v8);
+ const vf64 = TypeAliases.createVf64Vector(builder, this.vf64);
+
+ return TypeAliases.createTypeAliases(builder,
+ this.i8,
+ this.u8,
+ this.i16,
+ this.u16,
+ this.i32,
+ this.u32,
+ this.i64,
+ this.u64,
+ this.f32,
+ this.f64,
+ v8,
+ vf64
+ );
+}
+}
diff --git a/tests/my-game/example/vec3.js b/tests/my-game/example/vec3.js
new file mode 100644
index 0000000..5fd2447
--- /dev/null
+++ b/tests/my-game/example/vec3.js
@@ -0,0 +1,97 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+import { Test } from '../../my-game/example/test';
+export class Vec3 {
+ constructor() {
+ this.bb = null;
+ this.bb_pos = 0;
+ }
+ __init(i, bb) {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+ }
+ x() {
+ return this.bb.readFloat32(this.bb_pos);
+ }
+ mutate_x(value) {
+ this.bb.writeFloat32(this.bb_pos + 0, value);
+ return true;
+ }
+ y() {
+ return this.bb.readFloat32(this.bb_pos + 4);
+ }
+ mutate_y(value) {
+ this.bb.writeFloat32(this.bb_pos + 4, value);
+ return true;
+ }
+ z() {
+ return this.bb.readFloat32(this.bb_pos + 8);
+ }
+ mutate_z(value) {
+ this.bb.writeFloat32(this.bb_pos + 8, value);
+ return true;
+ }
+ test1() {
+ return this.bb.readFloat64(this.bb_pos + 16);
+ }
+ mutate_test1(value) {
+ this.bb.writeFloat64(this.bb_pos + 16, value);
+ return true;
+ }
+ test2() {
+ return this.bb.readUint8(this.bb_pos + 24);
+ }
+ mutate_test2(value) {
+ this.bb.writeUint8(this.bb_pos + 24, value);
+ return true;
+ }
+ test3(obj) {
+ return (obj || new Test()).__init(this.bb_pos + 26, this.bb);
+ }
+ static getFullyQualifiedName() {
+ return 'MyGame.Example.Vec3';
+ }
+ static sizeOf() {
+ return 32;
+ }
+ static createVec3(builder, x, y, z, test1, test2, test3_a, test3_b) {
+ builder.prep(8, 32);
+ builder.pad(2);
+ builder.prep(2, 4);
+ builder.pad(1);
+ builder.writeInt8(test3_b);
+ builder.writeInt16(test3_a);
+ builder.pad(1);
+ builder.writeInt8(test2);
+ builder.writeFloat64(test1);
+ builder.pad(4);
+ builder.writeFloat32(z);
+ builder.writeFloat32(y);
+ builder.writeFloat32(x);
+ return builder.offset();
+ }
+ unpack() {
+ return new Vec3T(this.x(), this.y(), this.z(), this.test1(), this.test2(), (this.test3() !== null ? this.test3().unpack() : null));
+ }
+ unpackTo(_o) {
+ _o.x = this.x();
+ _o.y = this.y();
+ _o.z = this.z();
+ _o.test1 = this.test1();
+ _o.test2 = this.test2();
+ _o.test3 = (this.test3() !== null ? this.test3().unpack() : null);
+ }
+}
+export class Vec3T {
+ constructor(x = 0.0, y = 0.0, z = 0.0, test1 = 0.0, test2 = 0, test3 = null) {
+ this.x = x;
+ this.y = y;
+ this.z = z;
+ this.test1 = test1;
+ this.test2 = test2;
+ this.test3 = test3;
+ }
+ pack(builder) {
+ return Vec3.createVec3(builder, this.x, this.y, this.z, this.test1, this.test2, (this.test3 === null ? 0 : this.test3.a), (this.test3 === null ? 0 : this.test3.b));
+ }
+}
diff --git a/tests/my-game/example/vec3.ts b/tests/my-game/example/vec3.ts
new file mode 100644
index 0000000..9756977
--- /dev/null
+++ b/tests/my-game/example/vec3.ts
@@ -0,0 +1,137 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+import * as flatbuffers from 'flatbuffers';
+
+import { Color } from '../../my-game/example/color';
+import { Test, TestT } from '../../my-game/example/test';
+
+
+export class Vec3 {
+ bb: flatbuffers.ByteBuffer|null = null;
+ bb_pos = 0;
+__init(i:number, bb:flatbuffers.ByteBuffer):Vec3 {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+}
+
+x():number {
+ return this.bb!.readFloat32(this.bb_pos);
+}
+
+mutate_x(value:number):boolean {
+ this.bb!.writeFloat32(this.bb_pos + 0, value);
+ return true;
+}
+
+y():number {
+ return this.bb!.readFloat32(this.bb_pos + 4);
+}
+
+mutate_y(value:number):boolean {
+ this.bb!.writeFloat32(this.bb_pos + 4, value);
+ return true;
+}
+
+z():number {
+ return this.bb!.readFloat32(this.bb_pos + 8);
+}
+
+mutate_z(value:number):boolean {
+ this.bb!.writeFloat32(this.bb_pos + 8, value);
+ return true;
+}
+
+test1():number {
+ return this.bb!.readFloat64(this.bb_pos + 16);
+}
+
+mutate_test1(value:number):boolean {
+ this.bb!.writeFloat64(this.bb_pos + 16, value);
+ return true;
+}
+
+test2():Color {
+ return this.bb!.readUint8(this.bb_pos + 24);
+}
+
+mutate_test2(value:Color):boolean {
+ this.bb!.writeUint8(this.bb_pos + 24, value);
+ return true;
+}
+
+test3(obj?:Test):Test|null {
+ return (obj || new Test()).__init(this.bb_pos + 26, this.bb!);
+}
+
+static getFullyQualifiedName():string {
+ return 'MyGame.Example.Vec3';
+}
+
+static sizeOf():number {
+ return 32;
+}
+
+static createVec3(builder:flatbuffers.Builder, x: number, y: number, z: number, test1: number, test2: Color, test3_a: number, test3_b: number):flatbuffers.Offset {
+ builder.prep(8, 32);
+ builder.pad(2);
+ builder.prep(2, 4);
+ builder.pad(1);
+ builder.writeInt8(test3_b);
+ builder.writeInt16(test3_a);
+ builder.pad(1);
+ builder.writeInt8(test2);
+ builder.writeFloat64(test1);
+ builder.pad(4);
+ builder.writeFloat32(z);
+ builder.writeFloat32(y);
+ builder.writeFloat32(x);
+ return builder.offset();
+}
+
+
+unpack(): Vec3T {
+ return new Vec3T(
+ this.x(),
+ this.y(),
+ this.z(),
+ this.test1(),
+ this.test2(),
+ (this.test3() !== null ? this.test3()!.unpack() : null)
+ );
+}
+
+
+unpackTo(_o: Vec3T): void {
+ _o.x = this.x();
+ _o.y = this.y();
+ _o.z = this.z();
+ _o.test1 = this.test1();
+ _o.test2 = this.test2();
+ _o.test3 = (this.test3() !== null ? this.test3()!.unpack() : null);
+}
+}
+
+export class Vec3T {
+constructor(
+ public x: number = 0.0,
+ public y: number = 0.0,
+ public z: number = 0.0,
+ public test1: number = 0.0,
+ public test2: Color = 0,
+ public test3: TestT|null = null
+){}
+
+
+pack(builder:flatbuffers.Builder): flatbuffers.Offset {
+ return Vec3.createVec3(builder,
+ this.x,
+ this.y,
+ this.z,
+ this.test1,
+ this.test2,
+ (this.test3 === null ? 0 : this.test3.a!),
+ (this.test3 === null ? 0 : this.test3.b!)
+ );
+}
+}
diff --git a/tests/my-game/example2/monster.js b/tests/my-game/example2/monster.js
new file mode 100644
index 0000000..17f02b1
--- /dev/null
+++ b/tests/my-game/example2/monster.js
@@ -0,0 +1,50 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+import * as flatbuffers from 'flatbuffers';
+export class Monster {
+ constructor() {
+ this.bb = null;
+ this.bb_pos = 0;
+ }
+ __init(i, bb) {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+ }
+ static getRootAsMonster(bb, obj) {
+ return (obj || new Monster()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ static getSizePrefixedRootAsMonster(bb, obj) {
+ bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new Monster()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ static getFullyQualifiedName() {
+ return 'MyGame.Example2.Monster';
+ }
+ static startMonster(builder) {
+ builder.startObject(0);
+ }
+ static endMonster(builder) {
+ const offset = builder.endObject();
+ return offset;
+ }
+ static createMonster(builder) {
+ Monster.startMonster(builder);
+ return Monster.endMonster(builder);
+ }
+ serialize() {
+ return this.bb.bytes();
+ }
+ static deserialize(buffer) {
+ return Monster.getRootAsMonster(new flatbuffers.ByteBuffer(buffer));
+ }
+ unpack() {
+ return new MonsterT();
+ }
+ unpackTo(_o) { }
+}
+export class MonsterT {
+ constructor() { }
+ pack(builder) {
+ return Monster.createMonster(builder);
+ }
+}
diff --git a/tests/my-game/example2/monster.ts b/tests/my-game/example2/monster.ts
new file mode 100644
index 0000000..14d7685
--- /dev/null
+++ b/tests/my-game/example2/monster.ts
@@ -0,0 +1,66 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+import * as flatbuffers from 'flatbuffers';
+
+
+
+export class Monster {
+ bb: flatbuffers.ByteBuffer|null = null;
+ bb_pos = 0;
+__init(i:number, bb:flatbuffers.ByteBuffer):Monster {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+}
+
+static getRootAsMonster(bb:flatbuffers.ByteBuffer, obj?:Monster):Monster {
+ return (obj || new Monster()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+}
+
+static getSizePrefixedRootAsMonster(bb:flatbuffers.ByteBuffer, obj?:Monster):Monster {
+ bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new Monster()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+}
+
+static getFullyQualifiedName():string {
+ return 'MyGame.Example2.Monster';
+}
+
+static startMonster(builder:flatbuffers.Builder) {
+ builder.startObject(0);
+}
+
+static endMonster(builder:flatbuffers.Builder):flatbuffers.Offset {
+ const offset = builder.endObject();
+ return offset;
+}
+
+static createMonster(builder:flatbuffers.Builder):flatbuffers.Offset {
+ Monster.startMonster(builder);
+ return Monster.endMonster(builder);
+}
+
+serialize():Uint8Array {
+ return this.bb!.bytes();
+}
+
+static deserialize(buffer: Uint8Array):Monster {
+ return Monster.getRootAsMonster(new flatbuffers.ByteBuffer(buffer))
+}
+
+unpack(): MonsterT {
+ return new MonsterT();
+}
+
+
+unpackTo(_o: MonsterT): void {}
+}
+
+export class MonsterT {
+constructor(){}
+
+
+pack(builder:flatbuffers.Builder): flatbuffers.Offset {
+ return Monster.createMonster(builder);
+}
+}
diff --git a/tests/my-game/in-parent-namespace.js b/tests/my-game/in-parent-namespace.js
new file mode 100644
index 0000000..4881741
--- /dev/null
+++ b/tests/my-game/in-parent-namespace.js
@@ -0,0 +1,50 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+import * as flatbuffers from 'flatbuffers';
+export class InParentNamespace {
+ constructor() {
+ this.bb = null;
+ this.bb_pos = 0;
+ }
+ __init(i, bb) {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+ }
+ static getRootAsInParentNamespace(bb, obj) {
+ return (obj || new InParentNamespace()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ static getSizePrefixedRootAsInParentNamespace(bb, obj) {
+ bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new InParentNamespace()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ static getFullyQualifiedName() {
+ return 'MyGame.InParentNamespace';
+ }
+ static startInParentNamespace(builder) {
+ builder.startObject(0);
+ }
+ static endInParentNamespace(builder) {
+ const offset = builder.endObject();
+ return offset;
+ }
+ static createInParentNamespace(builder) {
+ InParentNamespace.startInParentNamespace(builder);
+ return InParentNamespace.endInParentNamespace(builder);
+ }
+ serialize() {
+ return this.bb.bytes();
+ }
+ static deserialize(buffer) {
+ return InParentNamespace.getRootAsInParentNamespace(new flatbuffers.ByteBuffer(buffer));
+ }
+ unpack() {
+ return new InParentNamespaceT();
+ }
+ unpackTo(_o) { }
+}
+export class InParentNamespaceT {
+ constructor() { }
+ pack(builder) {
+ return InParentNamespace.createInParentNamespace(builder);
+ }
+}
diff --git a/tests/my-game/in-parent-namespace.ts b/tests/my-game/in-parent-namespace.ts
new file mode 100644
index 0000000..8cfe9b6
--- /dev/null
+++ b/tests/my-game/in-parent-namespace.ts
@@ -0,0 +1,66 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+import * as flatbuffers from 'flatbuffers';
+
+
+
+export class InParentNamespace {
+ bb: flatbuffers.ByteBuffer|null = null;
+ bb_pos = 0;
+__init(i:number, bb:flatbuffers.ByteBuffer):InParentNamespace {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+}
+
+static getRootAsInParentNamespace(bb:flatbuffers.ByteBuffer, obj?:InParentNamespace):InParentNamespace {
+ return (obj || new InParentNamespace()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+}
+
+static getSizePrefixedRootAsInParentNamespace(bb:flatbuffers.ByteBuffer, obj?:InParentNamespace):InParentNamespace {
+ bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new InParentNamespace()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+}
+
+static getFullyQualifiedName():string {
+ return 'MyGame.InParentNamespace';
+}
+
+static startInParentNamespace(builder:flatbuffers.Builder) {
+ builder.startObject(0);
+}
+
+static endInParentNamespace(builder:flatbuffers.Builder):flatbuffers.Offset {
+ const offset = builder.endObject();
+ return offset;
+}
+
+static createInParentNamespace(builder:flatbuffers.Builder):flatbuffers.Offset {
+ InParentNamespace.startInParentNamespace(builder);
+ return InParentNamespace.endInParentNamespace(builder);
+}
+
+serialize():Uint8Array {
+ return this.bb!.bytes();
+}
+
+static deserialize(buffer: Uint8Array):InParentNamespace {
+ return InParentNamespace.getRootAsInParentNamespace(new flatbuffers.ByteBuffer(buffer))
+}
+
+unpack(): InParentNamespaceT {
+ return new InParentNamespaceT();
+}
+
+
+unpackTo(_o: InParentNamespaceT): void {}
+}
+
+export class InParentNamespaceT {
+constructor(){}
+
+
+pack(builder:flatbuffers.Builder): flatbuffers.Offset {
+ return InParentNamespace.createInParentNamespace(builder);
+}
+}
diff --git a/tests/name_clash_test/invalid_test1.fbs b/tests/name_clash_test/invalid_test1.fbs
new file mode 100644
index 0000000..aa7213f
--- /dev/null
+++ b/tests/name_clash_test/invalid_test1.fbs
@@ -0,0 +1,5 @@
+include "invalid_test2.fbs";
+
+namespace A;
+
+table X {}
diff --git a/tests/name_clash_test/invalid_test2.fbs b/tests/name_clash_test/invalid_test2.fbs
new file mode 100644
index 0000000..6d70e9c
--- /dev/null
+++ b/tests/name_clash_test/invalid_test2.fbs
@@ -0,0 +1,3 @@
+namespace A;
+
+union X {}
diff --git a/tests/name_clash_test/valid_test1.fbs b/tests/name_clash_test/valid_test1.fbs
new file mode 100644
index 0000000..d61dea6
--- /dev/null
+++ b/tests/name_clash_test/valid_test1.fbs
@@ -0,0 +1,5 @@
+include "valid_test2.fbs";
+
+namespace A;
+
+table X {}
diff --git a/tests/name_clash_test/valid_test2.fbs b/tests/name_clash_test/valid_test2.fbs
new file mode 100644
index 0000000..78edad6
--- /dev/null
+++ b/tests/name_clash_test/valid_test2.fbs
@@ -0,0 +1,3 @@
+namespace B;
+
+union X {}
diff --git a/tests/namespace_test/NamespaceA/NamespaceB/EnumInNestedNS.java b/tests/namespace_test/NamespaceA/NamespaceB/EnumInNestedNS.java
index e23cecc..949c204 100644
--- a/tests/namespace_test/NamespaceA/NamespaceB/EnumInNestedNS.java
+++ b/tests/namespace_test/NamespaceA/NamespaceB/EnumInNestedNS.java
@@ -2,6 +2,7 @@
package NamespaceA.NamespaceB;
+@SuppressWarnings("unused")
public final class EnumInNestedNS {
private EnumInNestedNS() { }
public static final byte A = 0;
diff --git a/tests/namespace_test/NamespaceA/NamespaceB/EnumInNestedNS.py b/tests/namespace_test/NamespaceA/NamespaceB/EnumInNestedNS.py
index cb8218f..ae74c54 100644
--- a/tests/namespace_test/NamespaceA/NamespaceB/EnumInNestedNS.py
+++ b/tests/namespace_test/NamespaceA/NamespaceB/EnumInNestedNS.py
@@ -6,4 +6,3 @@
A = 0
B = 1
C = 2
-
diff --git a/tests/namespace_test/NamespaceA/NamespaceB/StructInNestedNS.cs b/tests/namespace_test/NamespaceA/NamespaceB/StructInNestedNS.cs
index 6fa9dd3..0ed6a63 100644
--- a/tests/namespace_test/NamespaceA/NamespaceB/StructInNestedNS.cs
+++ b/tests/namespace_test/NamespaceA/NamespaceB/StructInNestedNS.cs
@@ -43,7 +43,7 @@
_o.A,
_o.B);
}
-};
+}
public class StructInNestedNST
{
diff --git a/tests/namespace_test/NamespaceA/NamespaceB/StructInNestedNS.java b/tests/namespace_test/NamespaceA/NamespaceB/StructInNestedNS.java
index 6505561..7184f03 100644
--- a/tests/namespace_test/NamespaceA/NamespaceB/StructInNestedNS.java
+++ b/tests/namespace_test/NamespaceA/NamespaceB/StructInNestedNS.java
@@ -30,5 +30,23 @@
public StructInNestedNS get(int j) { return get(new StructInNestedNS(), j); }
public StructInNestedNS get(StructInNestedNS obj, int j) { return obj.__assign(__element(j), bb); }
}
+ public StructInNestedNST unpack() {
+ StructInNestedNST _o = new StructInNestedNST();
+ unpackTo(_o);
+ return _o;
+ }
+ public void unpackTo(StructInNestedNST _o) {
+ int _oA = a();
+ _o.setA(_oA);
+ int _oB = b();
+ _o.setB(_oB);
+ }
+ public static int pack(FlatBufferBuilder builder, StructInNestedNST _o) {
+ if (_o == null) return 0;
+ return createStructInNestedNS(
+ builder,
+ _o.getA(),
+ _o.getB());
+ }
}
diff --git a/tests/namespace_test/NamespaceA/NamespaceB/StructInNestedNST.java b/tests/namespace_test/NamespaceA/NamespaceB/StructInNestedNST.java
new file mode 100644
index 0000000..0e6963c
--- /dev/null
+++ b/tests/namespace_test/NamespaceA/NamespaceB/StructInNestedNST.java
@@ -0,0 +1,28 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+package NamespaceA.NamespaceB;
+
+import java.nio.*;
+import java.lang.*;
+import java.util.*;
+import com.google.flatbuffers.*;
+
+public class StructInNestedNST {
+ private int a;
+ private int b;
+
+ public int getA() { return a; }
+
+ public void setA(int a) { this.a = a; }
+
+ public int getB() { return b; }
+
+ public void setB(int b) { this.b = b; }
+
+
+ public StructInNestedNST() {
+ this.a = 0;
+ this.b = 0;
+ }
+}
+
diff --git a/tests/namespace_test/NamespaceA/NamespaceB/TableInNestedNS.cs b/tests/namespace_test/NamespaceA/NamespaceB/TableInNestedNS.cs
index cdbf6f8..9e67112 100644
--- a/tests/namespace_test/NamespaceA/NamespaceB/TableInNestedNS.cs
+++ b/tests/namespace_test/NamespaceA/NamespaceB/TableInNestedNS.cs
@@ -13,7 +13,7 @@
{
private Table __p;
public ByteBuffer ByteBuffer { get { return __p.bb; } }
- public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_1_12_0(); }
+ public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_2_0_0(); }
public static TableInNestedNS GetRootAsTableInNestedNS(ByteBuffer _bb) { return GetRootAsTableInNestedNS(_bb, new TableInNestedNS()); }
public static TableInNestedNS GetRootAsTableInNestedNS(ByteBuffer _bb, TableInNestedNS obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); }
public void __init(int _i, ByteBuffer _bb) { __p = new Table(_i, _bb); }
@@ -49,7 +49,7 @@
builder,
_o.Foo);
}
-};
+}
public class TableInNestedNST
{
diff --git a/tests/namespace_test/NamespaceA/NamespaceB/TableInNestedNS.java b/tests/namespace_test/NamespaceA/NamespaceB/TableInNestedNS.java
index b0931b1..45e4974 100644
--- a/tests/namespace_test/NamespaceA/NamespaceB/TableInNestedNS.java
+++ b/tests/namespace_test/NamespaceA/NamespaceB/TableInNestedNS.java
@@ -9,7 +9,7 @@
@SuppressWarnings("unused")
public final class TableInNestedNS extends Table {
- public static void ValidateVersion() { Constants.FLATBUFFERS_1_12_0(); }
+ public static void ValidateVersion() { Constants.FLATBUFFERS_2_0_0(); }
public static TableInNestedNS getRootAsTableInNestedNS(ByteBuffer _bb) { return getRootAsTableInNestedNS(_bb, new TableInNestedNS()); }
public static TableInNestedNS getRootAsTableInNestedNS(ByteBuffer _bb, TableInNestedNS obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); }
@@ -38,5 +38,20 @@
public TableInNestedNS get(int j) { return get(new TableInNestedNS(), j); }
public TableInNestedNS get(TableInNestedNS obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); }
}
+ public TableInNestedNST unpack() {
+ TableInNestedNST _o = new TableInNestedNST();
+ unpackTo(_o);
+ return _o;
+ }
+ public void unpackTo(TableInNestedNST _o) {
+ int _oFoo = foo();
+ _o.setFoo(_oFoo);
+ }
+ public static int pack(FlatBufferBuilder builder, TableInNestedNST _o) {
+ if (_o == null) return 0;
+ return createTableInNestedNS(
+ builder,
+ _o.getFoo());
+ }
}
diff --git a/tests/namespace_test/NamespaceA/NamespaceB/TableInNestedNS.kt b/tests/namespace_test/NamespaceA/NamespaceB/TableInNestedNS.kt
index 0fb2e3c..cb4cc10 100644
--- a/tests/namespace_test/NamespaceA/NamespaceB/TableInNestedNS.kt
+++ b/tests/namespace_test/NamespaceA/NamespaceB/TableInNestedNS.kt
@@ -32,7 +32,7 @@
}
}
companion object {
- fun validateVersion() = Constants.FLATBUFFERS_1_12_0()
+ fun validateVersion() = Constants.FLATBUFFERS_2_0_0()
fun getRootAsTableInNestedNS(_bb: ByteBuffer): TableInNestedNS = getRootAsTableInNestedNS(_bb, TableInNestedNS())
fun getRootAsTableInNestedNS(_bb: ByteBuffer, obj: TableInNestedNS): TableInNestedNS {
_bb.order(ByteOrder.LITTLE_ENDIAN)
diff --git a/tests/namespace_test/NamespaceA/NamespaceB/TableInNestedNS.lua b/tests/namespace_test/NamespaceA/NamespaceB/TableInNestedNS.lua
index dd45e58..af86203 100644
--- a/tests/namespace_test/NamespaceA/NamespaceB/TableInNestedNS.lua
+++ b/tests/namespace_test/NamespaceA/NamespaceB/TableInNestedNS.lua
@@ -13,6 +13,9 @@
return o
end
function TableInNestedNS.GetRootAsTableInNestedNS(buf, offset)
+ if type(buf) == "string" then
+ buf = flatbuffers.binaryArray.New(buf)
+ end
local n = flatbuffers.N.UOffsetT:Unpack(buf, offset)
local o = TableInNestedNS.New()
o:Init(buf, n + offset)
diff --git a/tests/namespace_test/NamespaceA/NamespaceB/TableInNestedNS.py b/tests/namespace_test/NamespaceA/NamespaceB/TableInNestedNS.py
index e86ba63..a9848d8 100644
--- a/tests/namespace_test/NamespaceA/NamespaceB/TableInNestedNS.py
+++ b/tests/namespace_test/NamespaceA/NamespaceB/TableInNestedNS.py
@@ -10,12 +10,16 @@
__slots__ = ['_tab']
@classmethod
- def GetRootAsTableInNestedNS(cls, buf, offset):
+ def GetRootAs(cls, buf, offset=0):
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
x = TableInNestedNS()
x.Init(buf, n + offset)
return x
+ @classmethod
+ def GetRootAsTableInNestedNS(cls, buf, offset=0):
+ """This method is deprecated. Please switch to GetRootAs."""
+ return cls.GetRootAs(buf, offset)
# TableInNestedNS
def Init(self, buf, pos):
self._tab = flatbuffers.table.Table(buf, pos)
@@ -28,9 +32,14 @@
return 0
def TableInNestedNSStart(builder): builder.StartObject(1)
+def Start(builder):
+ return TableInNestedNSStart(builder)
def TableInNestedNSAddFoo(builder, foo): builder.PrependInt32Slot(0, foo, 0)
+def AddFoo(builder, foo):
+ return TableInNestedNSAddFoo(builder, foo)
def TableInNestedNSEnd(builder): return builder.EndObject()
-
+def End(builder):
+ return TableInNestedNSEnd(builder)
class TableInNestedNST(object):
diff --git a/tests/namespace_test/NamespaceA/NamespaceB/TableInNestedNST.java b/tests/namespace_test/NamespaceA/NamespaceB/TableInNestedNST.java
new file mode 100644
index 0000000..1968a96
--- /dev/null
+++ b/tests/namespace_test/NamespaceA/NamespaceB/TableInNestedNST.java
@@ -0,0 +1,22 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+package NamespaceA.NamespaceB;
+
+import java.nio.*;
+import java.lang.*;
+import java.util.*;
+import com.google.flatbuffers.*;
+
+public class TableInNestedNST {
+ private int foo;
+
+ public int getFoo() { return foo; }
+
+ public void setFoo(int foo) { this.foo = foo; }
+
+
+ public TableInNestedNST() {
+ this.foo = 0;
+ }
+}
+
diff --git a/tests/namespace_test/NamespaceA/NamespaceB/UnionInNestedNS.cs b/tests/namespace_test/NamespaceA/NamespaceB/UnionInNestedNS.cs
new file mode 100644
index 0000000..7d1234f
--- /dev/null
+++ b/tests/namespace_test/NamespaceA/NamespaceB/UnionInNestedNS.cs
@@ -0,0 +1,78 @@
+// <auto-generated>
+// automatically generated by the FlatBuffers compiler, do not modify
+// </auto-generated>
+
+namespace NamespaceA.NamespaceB
+{
+
+[Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))]
+public enum UnionInNestedNS : byte
+{
+ NONE = 0,
+ TableInNestedNS = 1,
+};
+
+public class UnionInNestedNSUnion {
+ public UnionInNestedNS Type { get; set; }
+ public object Value { get; set; }
+
+ public UnionInNestedNSUnion() {
+ this.Type = UnionInNestedNS.NONE;
+ this.Value = null;
+ }
+
+ public T As<T>() where T : class { return this.Value as T; }
+ public NamespaceA.NamespaceB.TableInNestedNST AsTableInNestedNS() { return this.As<NamespaceA.NamespaceB.TableInNestedNST>(); }
+ public static UnionInNestedNSUnion FromTableInNestedNS(NamespaceA.NamespaceB.TableInNestedNST _tableinnestedns) { return new UnionInNestedNSUnion{ Type = UnionInNestedNS.TableInNestedNS, Value = _tableinnestedns }; }
+
+ public static int Pack(FlatBuffers.FlatBufferBuilder builder, UnionInNestedNSUnion _o) {
+ switch (_o.Type) {
+ default: return 0;
+ case UnionInNestedNS.TableInNestedNS: return NamespaceA.NamespaceB.TableInNestedNS.Pack(builder, _o.AsTableInNestedNS()).Value;
+ }
+ }
+}
+
+public class UnionInNestedNSUnion_JsonConverter : Newtonsoft.Json.JsonConverter {
+ public override bool CanConvert(System.Type objectType) {
+ return objectType == typeof(UnionInNestedNSUnion) || objectType == typeof(System.Collections.Generic.List<UnionInNestedNSUnion>);
+ }
+ public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer) {
+ var _olist = value as System.Collections.Generic.List<UnionInNestedNSUnion>;
+ if (_olist != null) {
+ writer.WriteStartArray();
+ foreach (var _o in _olist) { this.WriteJson(writer, _o, serializer); }
+ writer.WriteEndArray();
+ } else {
+ this.WriteJson(writer, value as UnionInNestedNSUnion, serializer);
+ }
+ }
+ public void WriteJson(Newtonsoft.Json.JsonWriter writer, UnionInNestedNSUnion _o, Newtonsoft.Json.JsonSerializer serializer) {
+ if (_o == null) return;
+ serializer.Serialize(writer, _o.Value);
+ }
+ public override object ReadJson(Newtonsoft.Json.JsonReader reader, System.Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer) {
+ var _olist = existingValue as System.Collections.Generic.List<UnionInNestedNSUnion>;
+ if (_olist != null) {
+ for (var _j = 0; _j < _olist.Count; ++_j) {
+ reader.Read();
+ _olist[_j] = this.ReadJson(reader, _olist[_j], serializer);
+ }
+ reader.Read();
+ return _olist;
+ } else {
+ return this.ReadJson(reader, existingValue as UnionInNestedNSUnion, serializer);
+ }
+ }
+ public UnionInNestedNSUnion ReadJson(Newtonsoft.Json.JsonReader reader, UnionInNestedNSUnion _o, Newtonsoft.Json.JsonSerializer serializer) {
+ if (_o == null) return null;
+ switch (_o.Type) {
+ default: break;
+ case UnionInNestedNS.TableInNestedNS: _o.Value = serializer.Deserialize<NamespaceA.NamespaceB.TableInNestedNST>(reader); break;
+ }
+ return _o;
+ }
+}
+
+
+}
diff --git a/tests/namespace_test/NamespaceA/NamespaceB/UnionInNestedNS.go b/tests/namespace_test/NamespaceA/NamespaceB/UnionInNestedNS.go
new file mode 100644
index 0000000..f7b1d1c
--- /dev/null
+++ b/tests/namespace_test/NamespaceA/NamespaceB/UnionInNestedNS.go
@@ -0,0 +1,36 @@
+// Code generated by the FlatBuffers compiler. DO NOT EDIT.
+
+package NamespaceB
+
+import (
+ "strconv"
+
+ flatbuffers "github.com/google/flatbuffers/go"
+
+ NamespaceA__NamespaceB "NamespaceA/NamespaceB"
+)
+
+type UnionInNestedNST struct {
+ Type UnionInNestedNS
+ Value interface{}
+}
+
+func (t *UnionInNestedNST) Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT {
+ if t == nil {
+ return 0
+ }
+ switch t.Type {
+ case UnionInNestedNSTableInNestedNS:
+ return t.Value.(*NamespaceA__NamespaceB.TableInNestedNST).Pack(builder)
+ }
+ return 0
+}
+
+func (rcv UnionInNestedNS) UnPack(table flatbuffers.Table) *UnionInNestedNST {
+ switch rcv {
+ case UnionInNestedNSTableInNestedNS:
+ x := TableInNestedNS{_tab: table}
+ return &NamespaceA__NamespaceB.UnionInNestedNST{ Type: UnionInNestedNSTableInNestedNS, Value: x.UnPack() }
+ }
+ return nil
+}
diff --git a/tests/namespace_test/NamespaceA/NamespaceB/UnionInNestedNS.java b/tests/namespace_test/NamespaceA/NamespaceB/UnionInNestedNS.java
new file mode 100644
index 0000000..27f24e3
--- /dev/null
+++ b/tests/namespace_test/NamespaceA/NamespaceB/UnionInNestedNS.java
@@ -0,0 +1,15 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+package NamespaceA.NamespaceB;
+
+@SuppressWarnings("unused")
+public final class UnionInNestedNS {
+ private UnionInNestedNS() { }
+ public static final byte NONE = 0;
+ public static final byte TableInNestedNS = 1;
+
+ public static final String[] names = { "NONE", "TableInNestedNS", };
+
+ public static String name(int e) { return names[e]; }
+}
+
diff --git a/tests/namespace_test/NamespaceA/NamespaceB/UnionInNestedNS.kt b/tests/namespace_test/NamespaceA/NamespaceB/UnionInNestedNS.kt
new file mode 100644
index 0000000..1c52f95
--- /dev/null
+++ b/tests/namespace_test/NamespaceA/NamespaceB/UnionInNestedNS.kt
@@ -0,0 +1,14 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+package NamespaceA.NamespaceB
+
+@Suppress("unused")
+@ExperimentalUnsignedTypes
+class UnionInNestedNS private constructor() {
+ companion object {
+ const val NONE: UByte = 0u
+ const val TableInNestedNS: UByte = 1u
+ val names : Array<String> = arrayOf("NONE", "TableInNestedNS")
+ fun name(e: Int) : String = names[e]
+ }
+}
diff --git a/tests/namespace_test/NamespaceA/NamespaceB/UnionInNestedNS.lua b/tests/namespace_test/NamespaceA/NamespaceB/UnionInNestedNS.lua
new file mode 100644
index 0000000..30bc93e
--- /dev/null
+++ b/tests/namespace_test/NamespaceA/NamespaceB/UnionInNestedNS.lua
@@ -0,0 +1,10 @@
+-- automatically generated by the FlatBuffers compiler, do not modify
+
+-- namespace: NamespaceB
+
+local UnionInNestedNS = {
+ NONE = 0,
+ TableInNestedNS = 1,
+}
+
+return UnionInNestedNS -- return the module
\ No newline at end of file
diff --git a/tests/namespace_test/NamespaceA/NamespaceB/UnionInNestedNS.php b/tests/namespace_test/NamespaceA/NamespaceB/UnionInNestedNS.php
new file mode 100644
index 0000000..ff948d7
--- /dev/null
+++ b/tests/namespace_test/NamespaceA/NamespaceB/UnionInNestedNS.php
@@ -0,0 +1,23 @@
+<?php
+// automatically generated by the FlatBuffers compiler, do not modify
+
+namespace NamespaceA\NamespaceB;
+
+class UnionInNestedNS
+{
+ const NONE = 0;
+ const TableInNestedNS = 1;
+
+ private static $names = array(
+ UnionInNestedNS::NONE=>"NONE",
+ UnionInNestedNS::TableInNestedNS=>"TableInNestedNS",
+ );
+
+ public static function Name($e)
+ {
+ if (!isset(self::$names[$e])) {
+ throw new \Exception();
+ }
+ return self::$names[$e];
+ }
+}
diff --git a/tests/namespace_test/NamespaceA/NamespaceB/UnionInNestedNS.py b/tests/namespace_test/NamespaceA/NamespaceB/UnionInNestedNS.py
new file mode 100644
index 0000000..af601c7
--- /dev/null
+++ b/tests/namespace_test/NamespaceA/NamespaceB/UnionInNestedNS.py
@@ -0,0 +1,15 @@
+# automatically generated by the FlatBuffers compiler, do not modify
+
+# namespace: NamespaceB
+
+class UnionInNestedNS(object):
+ NONE = 0
+ TableInNestedNS = 1
+
+def UnionInNestedNSCreator(unionType, table):
+ from flatbuffers.table import Table
+ if not isinstance(table, Table):
+ return None
+ if unionType == UnionInNestedNS().TableInNestedNS:
+ return TableInNestedNST.InitFromBuf(table.Bytes, table.Pos)
+ return None
diff --git a/tests/namespace_test/NamespaceA/NamespaceB/UnionInNestedNSUnion.java b/tests/namespace_test/NamespaceA/NamespaceB/UnionInNestedNSUnion.java
new file mode 100644
index 0000000..5b89938
--- /dev/null
+++ b/tests/namespace_test/NamespaceA/NamespaceB/UnionInNestedNSUnion.java
@@ -0,0 +1,33 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+package NamespaceA.NamespaceB;
+
+import com.google.flatbuffers.FlatBufferBuilder;
+
+public class UnionInNestedNSUnion {
+ private byte type;
+ private Object value;
+
+ public byte getType() { return type; }
+
+ public void setType(byte type) { this.type = type; }
+
+ public Object getValue() { return value; }
+
+ public void setValue(Object value) { this.value = value; }
+
+ public UnionInNestedNSUnion() {
+ this.type = UnionInNestedNS.NONE;
+ this.value = null;
+ }
+
+ public NamespaceA.NamespaceB.TableInNestedNST asTableInNestedNS() { return (NamespaceA.NamespaceB.TableInNestedNST) value; }
+
+ public static int pack(FlatBufferBuilder builder, UnionInNestedNSUnion _o) {
+ switch (_o.type) {
+ case UnionInNestedNS.TableInNestedNS: return NamespaceA.NamespaceB.TableInNestedNS.pack(builder, _o.asTableInNestedNS());
+ default: return 0;
+ }
+ }
+}
+
diff --git a/tests/namespace_test/NamespaceA/SecondTableInA.cs b/tests/namespace_test/NamespaceA/SecondTableInA.cs
index a949c61..6e7ef88 100644
--- a/tests/namespace_test/NamespaceA/SecondTableInA.cs
+++ b/tests/namespace_test/NamespaceA/SecondTableInA.cs
@@ -13,7 +13,7 @@
{
private Table __p;
public ByteBuffer ByteBuffer { get { return __p.bb; } }
- public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_1_12_0(); }
+ public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_2_0_0(); }
public static SecondTableInA GetRootAsSecondTableInA(ByteBuffer _bb) { return GetRootAsSecondTableInA(_bb, new SecondTableInA()); }
public static SecondTableInA GetRootAsSecondTableInA(ByteBuffer _bb, SecondTableInA obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); }
public void __init(int _i, ByteBuffer _bb) { __p = new Table(_i, _bb); }
@@ -49,7 +49,7 @@
builder,
_refer_to_c);
}
-};
+}
public class SecondTableInAT
{
diff --git a/tests/namespace_test/NamespaceA/SecondTableInA.java b/tests/namespace_test/NamespaceA/SecondTableInA.java
index ec6e561..ff539ab 100644
--- a/tests/namespace_test/NamespaceA/SecondTableInA.java
+++ b/tests/namespace_test/NamespaceA/SecondTableInA.java
@@ -9,7 +9,7 @@
@SuppressWarnings("unused")
public final class SecondTableInA extends Table {
- public static void ValidateVersion() { Constants.FLATBUFFERS_1_12_0(); }
+ public static void ValidateVersion() { Constants.FLATBUFFERS_2_0_0(); }
public static SecondTableInA getRootAsSecondTableInA(ByteBuffer _bb) { return getRootAsSecondTableInA(_bb, new SecondTableInA()); }
public static SecondTableInA getRootAsSecondTableInA(ByteBuffer _bb, SecondTableInA obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); }
@@ -19,9 +19,9 @@
public NamespaceC.TableInC referToC(NamespaceC.TableInC obj) { int o = __offset(4); return o != 0 ? obj.__assign(__indirect(o + bb_pos), bb) : null; }
public static int createSecondTableInA(FlatBufferBuilder builder,
- int refer_to_cOffset) {
+ int referToCOffset) {
builder.startTable(1);
- SecondTableInA.addReferToC(builder, refer_to_cOffset);
+ SecondTableInA.addReferToC(builder, referToCOffset);
return SecondTableInA.endSecondTableInA(builder);
}
@@ -38,5 +38,21 @@
public SecondTableInA get(int j) { return get(new SecondTableInA(), j); }
public SecondTableInA get(SecondTableInA obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); }
}
+ public SecondTableInAT unpack() {
+ SecondTableInAT _o = new SecondTableInAT();
+ unpackTo(_o);
+ return _o;
+ }
+ public void unpackTo(SecondTableInAT _o) {
+ if (referToC() != null) _o.setReferToC(referToC().unpack());
+ else _o.setReferToC(null);
+ }
+ public static int pack(FlatBufferBuilder builder, SecondTableInAT _o) {
+ if (_o == null) return 0;
+ int _refer_to_c = _o.getReferToC() == null ? 0 : NamespaceC.TableInC.pack(builder, _o.getReferToC());
+ return createSecondTableInA(
+ builder,
+ _refer_to_c);
+ }
}
diff --git a/tests/namespace_test/NamespaceA/SecondTableInA.kt b/tests/namespace_test/NamespaceA/SecondTableInA.kt
index 5b41f73..a516070 100644
--- a/tests/namespace_test/NamespaceA/SecondTableInA.kt
+++ b/tests/namespace_test/NamespaceA/SecondTableInA.kt
@@ -27,7 +27,7 @@
}
}
companion object {
- fun validateVersion() = Constants.FLATBUFFERS_1_12_0()
+ fun validateVersion() = Constants.FLATBUFFERS_2_0_0()
fun getRootAsSecondTableInA(_bb: ByteBuffer): SecondTableInA = getRootAsSecondTableInA(_bb, SecondTableInA())
fun getRootAsSecondTableInA(_bb: ByteBuffer, obj: SecondTableInA): SecondTableInA {
_bb.order(ByteOrder.LITTLE_ENDIAN)
diff --git a/tests/namespace_test/NamespaceA/SecondTableInA.lua b/tests/namespace_test/NamespaceA/SecondTableInA.lua
index 9a60e4b..b953c12 100644
--- a/tests/namespace_test/NamespaceA/SecondTableInA.lua
+++ b/tests/namespace_test/NamespaceA/SecondTableInA.lua
@@ -13,6 +13,9 @@
return o
end
function SecondTableInA.GetRootAsSecondTableInA(buf, offset)
+ if type(buf) == "string" then
+ buf = flatbuffers.binaryArray.New(buf)
+ end
local n = flatbuffers.N.UOffsetT:Unpack(buf, offset)
local o = SecondTableInA.New()
o:Init(buf, n + offset)
diff --git a/tests/namespace_test/NamespaceA/SecondTableInA.py b/tests/namespace_test/NamespaceA/SecondTableInA.py
index 5aaa8ed..474f44d 100644
--- a/tests/namespace_test/NamespaceA/SecondTableInA.py
+++ b/tests/namespace_test/NamespaceA/SecondTableInA.py
@@ -10,12 +10,16 @@
__slots__ = ['_tab']
@classmethod
- def GetRootAsSecondTableInA(cls, buf, offset):
+ def GetRootAs(cls, buf, offset=0):
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
x = SecondTableInA()
x.Init(buf, n + offset)
return x
+ @classmethod
+ def GetRootAsSecondTableInA(cls, buf, offset=0):
+ """This method is deprecated. Please switch to GetRootAs."""
+ return cls.GetRootAs(buf, offset)
# SecondTableInA
def Init(self, buf, pos):
self._tab = flatbuffers.table.Table(buf, pos)
@@ -31,9 +35,14 @@
return None
def SecondTableInAStart(builder): builder.StartObject(1)
+def Start(builder):
+ return SecondTableInAStart(builder)
def SecondTableInAAddReferToC(builder, referToC): builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(referToC), 0)
+def AddReferToC(builder, referToC):
+ return SecondTableInAAddReferToC(builder, referToC)
def SecondTableInAEnd(builder): return builder.EndObject()
-
+def End(builder):
+ return SecondTableInAEnd(builder)
try:
from typing import Optional
except:
diff --git a/tests/namespace_test/NamespaceA/SecondTableInAT.java b/tests/namespace_test/NamespaceA/SecondTableInAT.java
new file mode 100644
index 0000000..98fe21c
--- /dev/null
+++ b/tests/namespace_test/NamespaceA/SecondTableInAT.java
@@ -0,0 +1,22 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+package NamespaceA;
+
+import java.nio.*;
+import java.lang.*;
+import java.util.*;
+import com.google.flatbuffers.*;
+
+public class SecondTableInAT {
+ private NamespaceC.TableInCT referToC;
+
+ public NamespaceC.TableInCT getReferToC() { return referToC; }
+
+ public void setReferToC(NamespaceC.TableInCT referToC) { this.referToC = referToC; }
+
+
+ public SecondTableInAT() {
+ this.referToC = null;
+ }
+}
+
diff --git a/tests/namespace_test/NamespaceA/TableInFirstNS.cs b/tests/namespace_test/NamespaceA/TableInFirstNS.cs
index 3d597d7..6522f49 100644
--- a/tests/namespace_test/NamespaceA/TableInFirstNS.cs
+++ b/tests/namespace_test/NamespaceA/TableInFirstNS.cs
@@ -13,7 +13,7 @@
{
private Table __p;
public ByteBuffer ByteBuffer { get { return __p.bb; } }
- public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_1_12_0(); }
+ public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_2_0_0(); }
public static TableInFirstNS GetRootAsTableInFirstNS(ByteBuffer _bb) { return GetRootAsTableInFirstNS(_bb, new TableInFirstNS()); }
public static TableInFirstNS GetRootAsTableInFirstNS(ByteBuffer _bb, TableInFirstNS obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); }
public void __init(int _i, ByteBuffer _bb) { __p = new Table(_i, _bb); }
@@ -22,23 +22,32 @@
public NamespaceA.NamespaceB.TableInNestedNS? FooTable { get { int o = __p.__offset(4); return o != 0 ? (NamespaceA.NamespaceB.TableInNestedNS?)(new NamespaceA.NamespaceB.TableInNestedNS()).__assign(__p.__indirect(o + __p.bb_pos), __p.bb) : null; } }
public NamespaceA.NamespaceB.EnumInNestedNS FooEnum { get { int o = __p.__offset(6); return o != 0 ? (NamespaceA.NamespaceB.EnumInNestedNS)__p.bb.GetSbyte(o + __p.bb_pos) : NamespaceA.NamespaceB.EnumInNestedNS.A; } }
public bool MutateFooEnum(NamespaceA.NamespaceB.EnumInNestedNS foo_enum) { int o = __p.__offset(6); if (o != 0) { __p.bb.PutSbyte(o + __p.bb_pos, (sbyte)foo_enum); return true; } else { return false; } }
- public NamespaceA.NamespaceB.StructInNestedNS? FooStruct { get { int o = __p.__offset(8); return o != 0 ? (NamespaceA.NamespaceB.StructInNestedNS?)(new NamespaceA.NamespaceB.StructInNestedNS()).__assign(o + __p.bb_pos, __p.bb) : null; } }
+ public NamespaceA.NamespaceB.UnionInNestedNS FooUnionType { get { int o = __p.__offset(8); return o != 0 ? (NamespaceA.NamespaceB.UnionInNestedNS)__p.bb.Get(o + __p.bb_pos) : NamespaceA.NamespaceB.UnionInNestedNS.NONE; } }
+ public TTable? FooUnion<TTable>() where TTable : struct, IFlatbufferObject { int o = __p.__offset(10); return o != 0 ? (TTable?)__p.__union<TTable>(o + __p.bb_pos) : null; }
+ public NamespaceA.NamespaceB.TableInNestedNS FooUnionAsTableInNestedNS() { return FooUnion<NamespaceA.NamespaceB.TableInNestedNS>().Value; }
+ public NamespaceA.NamespaceB.StructInNestedNS? FooStruct { get { int o = __p.__offset(12); return o != 0 ? (NamespaceA.NamespaceB.StructInNestedNS?)(new NamespaceA.NamespaceB.StructInNestedNS()).__assign(o + __p.bb_pos, __p.bb) : null; } }
public static Offset<NamespaceA.TableInFirstNS> CreateTableInFirstNS(FlatBufferBuilder builder,
Offset<NamespaceA.NamespaceB.TableInNestedNS> foo_tableOffset = default(Offset<NamespaceA.NamespaceB.TableInNestedNS>),
NamespaceA.NamespaceB.EnumInNestedNS foo_enum = NamespaceA.NamespaceB.EnumInNestedNS.A,
+ NamespaceA.NamespaceB.UnionInNestedNS foo_union_type = NamespaceA.NamespaceB.UnionInNestedNS.NONE,
+ int foo_unionOffset = 0,
NamespaceA.NamespaceB.StructInNestedNST foo_struct = null) {
- builder.StartTable(3);
+ builder.StartTable(5);
TableInFirstNS.AddFooStruct(builder, NamespaceA.NamespaceB.StructInNestedNS.Pack(builder, foo_struct));
+ TableInFirstNS.AddFooUnion(builder, foo_unionOffset);
TableInFirstNS.AddFooTable(builder, foo_tableOffset);
+ TableInFirstNS.AddFooUnionType(builder, foo_union_type);
TableInFirstNS.AddFooEnum(builder, foo_enum);
return TableInFirstNS.EndTableInFirstNS(builder);
}
- public static void StartTableInFirstNS(FlatBufferBuilder builder) { builder.StartTable(3); }
+ public static void StartTableInFirstNS(FlatBufferBuilder builder) { builder.StartTable(5); }
public static void AddFooTable(FlatBufferBuilder builder, Offset<NamespaceA.NamespaceB.TableInNestedNS> fooTableOffset) { builder.AddOffset(0, fooTableOffset.Value, 0); }
public static void AddFooEnum(FlatBufferBuilder builder, NamespaceA.NamespaceB.EnumInNestedNS fooEnum) { builder.AddSbyte(1, (sbyte)fooEnum, 0); }
- public static void AddFooStruct(FlatBufferBuilder builder, Offset<NamespaceA.NamespaceB.StructInNestedNS> fooStructOffset) { builder.AddStruct(2, fooStructOffset.Value, 0); }
+ public static void AddFooUnionType(FlatBufferBuilder builder, NamespaceA.NamespaceB.UnionInNestedNS fooUnionType) { builder.AddByte(2, (byte)fooUnionType, 0); }
+ public static void AddFooUnion(FlatBufferBuilder builder, int fooUnionOffset) { builder.AddOffset(3, fooUnionOffset, 0); }
+ public static void AddFooStruct(FlatBufferBuilder builder, Offset<NamespaceA.NamespaceB.StructInNestedNS> fooStructOffset) { builder.AddStruct(4, fooStructOffset.Value, 0); }
public static Offset<NamespaceA.TableInFirstNS> EndTableInFirstNS(FlatBufferBuilder builder) {
int o = builder.EndTable();
return new Offset<NamespaceA.TableInFirstNS>(o);
@@ -51,18 +60,30 @@
public void UnPackTo(TableInFirstNST _o) {
_o.FooTable = this.FooTable.HasValue ? this.FooTable.Value.UnPack() : null;
_o.FooEnum = this.FooEnum;
+ _o.FooUnion = new NamespaceA.NamespaceB.UnionInNestedNSUnion();
+ _o.FooUnion.Type = this.FooUnionType;
+ switch (this.FooUnionType) {
+ default: break;
+ case NamespaceA.NamespaceB.UnionInNestedNS.TableInNestedNS:
+ _o.FooUnion.Value = this.FooUnion<NamespaceA.NamespaceB.TableInNestedNS>().HasValue ? this.FooUnion<NamespaceA.NamespaceB.TableInNestedNS>().Value.UnPack() : null;
+ break;
+ }
_o.FooStruct = this.FooStruct.HasValue ? this.FooStruct.Value.UnPack() : null;
}
public static Offset<NamespaceA.TableInFirstNS> Pack(FlatBufferBuilder builder, TableInFirstNST _o) {
if (_o == null) return default(Offset<NamespaceA.TableInFirstNS>);
var _foo_table = _o.FooTable == null ? default(Offset<NamespaceA.NamespaceB.TableInNestedNS>) : NamespaceA.NamespaceB.TableInNestedNS.Pack(builder, _o.FooTable);
+ var _foo_union_type = _o.FooUnion == null ? NamespaceA.NamespaceB.UnionInNestedNS.NONE : _o.FooUnion.Type;
+ var _foo_union = _o.FooUnion == null ? 0 : NamespaceA.NamespaceB.UnionInNestedNSUnion.Pack(builder, _o.FooUnion);
return CreateTableInFirstNS(
builder,
_foo_table,
_o.FooEnum,
+ _foo_union_type,
+ _foo_union,
_o.FooStruct);
}
-};
+}
public class TableInFirstNST
{
@@ -70,12 +91,26 @@
public NamespaceA.NamespaceB.TableInNestedNST FooTable { get; set; }
[Newtonsoft.Json.JsonProperty("foo_enum")]
public NamespaceA.NamespaceB.EnumInNestedNS FooEnum { get; set; }
+ [Newtonsoft.Json.JsonProperty("foo_union_type")]
+ private NamespaceA.NamespaceB.UnionInNestedNS FooUnionType {
+ get {
+ return this.FooUnion != null ? this.FooUnion.Type : NamespaceA.NamespaceB.UnionInNestedNS.NONE;
+ }
+ set {
+ this.FooUnion = new NamespaceA.NamespaceB.UnionInNestedNSUnion();
+ this.FooUnion.Type = value;
+ }
+ }
+ [Newtonsoft.Json.JsonProperty("foo_union")]
+ [Newtonsoft.Json.JsonConverter(typeof(NamespaceA.NamespaceB.UnionInNestedNSUnion_JsonConverter))]
+ public NamespaceA.NamespaceB.UnionInNestedNSUnion FooUnion { get; set; }
[Newtonsoft.Json.JsonProperty("foo_struct")]
public NamespaceA.NamespaceB.StructInNestedNST FooStruct { get; set; }
public TableInFirstNST() {
this.FooTable = null;
this.FooEnum = NamespaceA.NamespaceB.EnumInNestedNS.A;
+ this.FooUnion = null;
this.FooStruct = new NamespaceA.NamespaceB.StructInNestedNST();
}
}
diff --git a/tests/namespace_test/NamespaceA/TableInFirstNS.go b/tests/namespace_test/NamespaceA/TableInFirstNS.go
index 7f419b8..3feaaaa 100644
--- a/tests/namespace_test/NamespaceA/TableInFirstNS.go
+++ b/tests/namespace_test/NamespaceA/TableInFirstNS.go
@@ -11,15 +11,22 @@
type TableInFirstNST struct {
FooTable *NamespaceA__NamespaceB.TableInNestedNST
FooEnum NamespaceA__NamespaceB.EnumInNestedNS
+ FooUnion *NamespaceA__NamespaceB.UnionInNestedNST
FooStruct *NamespaceA__NamespaceB.StructInNestedNST
}
func (t *TableInFirstNST) Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT {
if t == nil { return 0 }
fooTableOffset := t.FooTable.Pack(builder)
+ fooUnionOffset := t.FooUnion.Pack(builder)
+
TableInFirstNSStart(builder)
TableInFirstNSAddFooTable(builder, fooTableOffset)
TableInFirstNSAddFooEnum(builder, t.FooEnum)
+ if t.FooUnion != nil {
+ TableInFirstNSAddFooUnionType(builder, t.FooUnion.Type)
+ }
+ TableInFirstNSAddFooUnion(builder, fooUnionOffset)
fooStructOffset := t.FooStruct.Pack(builder)
TableInFirstNSAddFooStruct(builder, fooStructOffset)
return TableInFirstNSEnd(builder)
@@ -28,6 +35,10 @@
func (rcv *TableInFirstNS) UnPackTo(t *TableInFirstNST) {
t.FooTable = rcv.FooTable(nil).UnPack()
t.FooEnum = rcv.FooEnum()
+ fooUnionTable := flatbuffers.Table{}
+ if rcv.FooUnion(&fooUnionTable) {
+ t.FooUnion = rcv.FooUnionType().UnPack(fooUnionTable)
+ }
t.FooStruct = rcv.FooStruct(nil).UnPack()
}
@@ -90,9 +101,30 @@
return rcv._tab.MutateInt8Slot(6, int8(n))
}
-func (rcv *TableInFirstNS) FooStruct(obj *NamespaceA__NamespaceB.StructInNestedNS) *NamespaceA__NamespaceB.StructInNestedNS {
+func (rcv *TableInFirstNS) FooUnionType() NamespaceA__NamespaceB.UnionInNestedNS {
o := flatbuffers.UOffsetT(rcv._tab.Offset(8))
if o != 0 {
+ return NamespaceA__NamespaceB.UnionInNestedNS(rcv._tab.GetByte(o + rcv._tab.Pos))
+ }
+ return 0
+}
+
+func (rcv *TableInFirstNS) MutateFooUnionType(n NamespaceA__NamespaceB.UnionInNestedNS) bool {
+ return rcv._tab.MutateByteSlot(8, byte(n))
+}
+
+func (rcv *TableInFirstNS) FooUnion(obj *flatbuffers.Table) bool {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(10))
+ if o != 0 {
+ rcv._tab.Union(obj, o)
+ return true
+ }
+ return false
+}
+
+func (rcv *TableInFirstNS) FooStruct(obj *NamespaceA__NamespaceB.StructInNestedNS) *NamespaceA__NamespaceB.StructInNestedNS {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(12))
+ if o != 0 {
x := o + rcv._tab.Pos
if obj == nil {
obj = new(NamespaceA__NamespaceB.StructInNestedNS)
@@ -104,7 +136,7 @@
}
func TableInFirstNSStart(builder *flatbuffers.Builder) {
- builder.StartObject(3)
+ builder.StartObject(5)
}
func TableInFirstNSAddFooTable(builder *flatbuffers.Builder, fooTable flatbuffers.UOffsetT) {
builder.PrependUOffsetTSlot(0, flatbuffers.UOffsetT(fooTable), 0)
@@ -112,8 +144,14 @@
func TableInFirstNSAddFooEnum(builder *flatbuffers.Builder, fooEnum NamespaceA__NamespaceB.EnumInNestedNS) {
builder.PrependInt8Slot(1, int8(fooEnum), 0)
}
+func TableInFirstNSAddFooUnionType(builder *flatbuffers.Builder, fooUnionType NamespaceA__NamespaceB.UnionInNestedNS) {
+ builder.PrependByteSlot(2, byte(fooUnionType), 0)
+}
+func TableInFirstNSAddFooUnion(builder *flatbuffers.Builder, fooUnion flatbuffers.UOffsetT) {
+ builder.PrependUOffsetTSlot(3, flatbuffers.UOffsetT(fooUnion), 0)
+}
func TableInFirstNSAddFooStruct(builder *flatbuffers.Builder, fooStruct flatbuffers.UOffsetT) {
- builder.PrependStructSlot(2, flatbuffers.UOffsetT(fooStruct), 0)
+ builder.PrependStructSlot(4, flatbuffers.UOffsetT(fooStruct), 0)
}
func TableInFirstNSEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT {
return builder.EndObject()
diff --git a/tests/namespace_test/NamespaceA/TableInFirstNS.java b/tests/namespace_test/NamespaceA/TableInFirstNS.java
index f04d9e9..2fdfec8 100644
--- a/tests/namespace_test/NamespaceA/TableInFirstNS.java
+++ b/tests/namespace_test/NamespaceA/TableInFirstNS.java
@@ -9,7 +9,7 @@
@SuppressWarnings("unused")
public final class TableInFirstNS extends Table {
- public static void ValidateVersion() { Constants.FLATBUFFERS_1_12_0(); }
+ public static void ValidateVersion() { Constants.FLATBUFFERS_2_0_0(); }
public static TableInFirstNS getRootAsTableInFirstNS(ByteBuffer _bb) { return getRootAsTableInFirstNS(_bb, new TableInFirstNS()); }
public static TableInFirstNS getRootAsTableInFirstNS(ByteBuffer _bb, TableInFirstNS obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); }
@@ -19,13 +19,17 @@
public NamespaceA.NamespaceB.TableInNestedNS fooTable(NamespaceA.NamespaceB.TableInNestedNS obj) { int o = __offset(4); return o != 0 ? obj.__assign(__indirect(o + bb_pos), bb) : null; }
public byte fooEnum() { int o = __offset(6); return o != 0 ? bb.get(o + bb_pos) : 0; }
public boolean mutateFooEnum(byte foo_enum) { int o = __offset(6); if (o != 0) { bb.put(o + bb_pos, foo_enum); return true; } else { return false; } }
+ public byte fooUnionType() { int o = __offset(8); return o != 0 ? bb.get(o + bb_pos) : 0; }
+ public Table fooUnion(Table obj) { int o = __offset(10); return o != 0 ? __union(obj, o + bb_pos) : null; }
public NamespaceA.NamespaceB.StructInNestedNS fooStruct() { return fooStruct(new NamespaceA.NamespaceB.StructInNestedNS()); }
- public NamespaceA.NamespaceB.StructInNestedNS fooStruct(NamespaceA.NamespaceB.StructInNestedNS obj) { int o = __offset(8); return o != 0 ? obj.__assign(o + bb_pos, bb) : null; }
+ public NamespaceA.NamespaceB.StructInNestedNS fooStruct(NamespaceA.NamespaceB.StructInNestedNS obj) { int o = __offset(12); return o != 0 ? obj.__assign(o + bb_pos, bb) : null; }
- public static void startTableInFirstNS(FlatBufferBuilder builder) { builder.startTable(3); }
+ public static void startTableInFirstNS(FlatBufferBuilder builder) { builder.startTable(5); }
public static void addFooTable(FlatBufferBuilder builder, int fooTableOffset) { builder.addOffset(0, fooTableOffset, 0); }
public static void addFooEnum(FlatBufferBuilder builder, byte fooEnum) { builder.addByte(1, fooEnum, 0); }
- public static void addFooStruct(FlatBufferBuilder builder, int fooStructOffset) { builder.addStruct(2, fooStructOffset, 0); }
+ public static void addFooUnionType(FlatBufferBuilder builder, byte fooUnionType) { builder.addByte(2, fooUnionType, 0); }
+ public static void addFooUnion(FlatBufferBuilder builder, int fooUnionOffset) { builder.addOffset(3, fooUnionOffset, 0); }
+ public static void addFooStruct(FlatBufferBuilder builder, int fooStructOffset) { builder.addStruct(4, fooStructOffset, 0); }
public static int endTableInFirstNS(FlatBufferBuilder builder) {
int o = builder.endTable();
return o;
@@ -37,5 +41,43 @@
public TableInFirstNS get(int j) { return get(new TableInFirstNS(), j); }
public TableInFirstNS get(TableInFirstNS obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); }
}
+ public TableInFirstNST unpack() {
+ TableInFirstNST _o = new TableInFirstNST();
+ unpackTo(_o);
+ return _o;
+ }
+ public void unpackTo(TableInFirstNST _o) {
+ if (fooTable() != null) _o.setFooTable(fooTable().unpack());
+ else _o.setFooTable(null);
+ byte _oFooEnum = fooEnum();
+ _o.setFooEnum(_oFooEnum);
+ NamespaceA.NamespaceB.UnionInNestedNSUnion _oFooUnion = new NamespaceA.NamespaceB.UnionInNestedNSUnion();
+ byte _oFooUnionType = fooUnionType();
+ _oFooUnion.setType(_oFooUnionType);
+ Table _oFooUnionValue;
+ switch (_oFooUnionType) {
+ case NamespaceA.NamespaceB.UnionInNestedNS.TableInNestedNS:
+ _oFooUnionValue = fooUnion(new NamespaceA.NamespaceB.TableInNestedNS());
+ _oFooUnion.setValue(_oFooUnionValue != null ? ((NamespaceA.NamespaceB.TableInNestedNS) _oFooUnionValue).unpack() : null);
+ break;
+ default: break;
+ }
+ _o.setFooUnion(_oFooUnion);
+ if (fooStruct() != null) fooStruct().unpackTo(_o.getFooStruct());
+ else _o.setFooStruct(null);
+ }
+ public static int pack(FlatBufferBuilder builder, TableInFirstNST _o) {
+ if (_o == null) return 0;
+ int _foo_table = _o.getFooTable() == null ? 0 : NamespaceA.NamespaceB.TableInNestedNS.pack(builder, _o.getFooTable());
+ byte _fooUnionType = _o.getFooUnion() == null ? NamespaceA.NamespaceB.UnionInNestedNS.NONE : _o.getFooUnion().getType();
+ int _fooUnion = _o.getFooUnion() == null ? 0 : NamespaceA.NamespaceB.UnionInNestedNSUnion.pack(builder, _o.getFooUnion());
+ startTableInFirstNS(builder);
+ addFooTable(builder, _foo_table);
+ addFooEnum(builder, _o.getFooEnum());
+ addFooUnionType(builder, _fooUnionType);
+ addFooUnion(builder, _fooUnion);
+ addFooStruct(builder, NamespaceA.NamespaceB.StructInNestedNS.pack(builder, _o.getFooStruct()));
+ return endTableInFirstNS(builder);
+ }
}
diff --git a/tests/namespace_test/NamespaceA/TableInFirstNS.kt b/tests/namespace_test/NamespaceA/TableInFirstNS.kt
index febe050..bec3319 100644
--- a/tests/namespace_test/NamespaceA/TableInFirstNS.kt
+++ b/tests/namespace_test/NamespaceA/TableInFirstNS.kt
@@ -40,9 +40,26 @@
false
}
}
+ val fooUnionType : UByte
+ get() {
+ val o = __offset(8)
+ return if(o != 0) bb.get(o + bb_pos).toUByte() else 0u
+ }
+ fun mutateFooUnionType(fooUnionType: UByte) : Boolean {
+ val o = __offset(8)
+ return if (o != 0) {
+ bb.put(o + bb_pos, fooUnionType.toByte())
+ true
+ } else {
+ false
+ }
+ }
+ fun fooUnion(obj: Table) : Table? {
+ val o = __offset(10); return if (o != 0) __union(obj, o + bb_pos) else null
+ }
val fooStruct : NamespaceA.NamespaceB.StructInNestedNS? get() = fooStruct(NamespaceA.NamespaceB.StructInNestedNS())
fun fooStruct(obj: NamespaceA.NamespaceB.StructInNestedNS) : NamespaceA.NamespaceB.StructInNestedNS? {
- val o = __offset(8)
+ val o = __offset(12)
return if (o != 0) {
obj.__assign(o + bb_pos, bb)
} else {
@@ -50,16 +67,18 @@
}
}
companion object {
- fun validateVersion() = Constants.FLATBUFFERS_1_12_0()
+ fun validateVersion() = Constants.FLATBUFFERS_2_0_0()
fun getRootAsTableInFirstNS(_bb: ByteBuffer): TableInFirstNS = getRootAsTableInFirstNS(_bb, TableInFirstNS())
fun getRootAsTableInFirstNS(_bb: ByteBuffer, obj: TableInFirstNS): TableInFirstNS {
_bb.order(ByteOrder.LITTLE_ENDIAN)
return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb))
}
- fun startTableInFirstNS(builder: FlatBufferBuilder) = builder.startTable(3)
+ fun startTableInFirstNS(builder: FlatBufferBuilder) = builder.startTable(5)
fun addFooTable(builder: FlatBufferBuilder, fooTable: Int) = builder.addOffset(0, fooTable, 0)
fun addFooEnum(builder: FlatBufferBuilder, fooEnum: Byte) = builder.addByte(1, fooEnum, 0)
- fun addFooStruct(builder: FlatBufferBuilder, fooStruct: Int) = builder.addStruct(2, fooStruct, 0)
+ fun addFooUnionType(builder: FlatBufferBuilder, fooUnionType: UByte) = builder.addByte(2, fooUnionType.toByte(), 0)
+ fun addFooUnion(builder: FlatBufferBuilder, fooUnion: Int) = builder.addOffset(3, fooUnion, 0)
+ fun addFooStruct(builder: FlatBufferBuilder, fooStruct: Int) = builder.addStruct(4, fooStruct, 0)
fun endTableInFirstNS(builder: FlatBufferBuilder) : Int {
val o = builder.endTable()
return o
diff --git a/tests/namespace_test/NamespaceA/TableInFirstNS.lua b/tests/namespace_test/NamespaceA/TableInFirstNS.lua
index f70f2c7..1b62cc5 100644
--- a/tests/namespace_test/NamespaceA/TableInFirstNS.lua
+++ b/tests/namespace_test/NamespaceA/TableInFirstNS.lua
@@ -13,6 +13,9 @@
return o
end
function TableInFirstNS.GetRootAsTableInFirstNS(buf, offset)
+ if type(buf) == "string" then
+ buf = flatbuffers.binaryArray.New(buf)
+ end
local n = flatbuffers.N.UOffsetT:Unpack(buf, offset)
local o = TableInFirstNS.New()
o:Init(buf, n + offset)
@@ -37,19 +40,36 @@
end
return 0
end
-function TableInFirstNS_mt:FooStruct()
+function TableInFirstNS_mt:FooUnionType()
local o = self.view:Offset(8)
if o ~= 0 then
+ return self.view:Get(flatbuffers.N.Uint8, o + self.view.pos)
+ end
+ return 0
+end
+function TableInFirstNS_mt:FooUnion()
+ local o = self.view:Offset(10)
+ if o ~= 0 then
+ local obj = flatbuffers.view.New(require('flatbuffers.binaryarray').New(0), 0)
+ self.view:Union(obj, o)
+ return obj
+ end
+end
+function TableInFirstNS_mt:FooStruct()
+ local o = self.view:Offset(12)
+ if o ~= 0 then
local x = o + self.view.pos
local obj = require('NamespaceA.NamespaceB.StructInNestedNS').New()
obj:Init(self.view.bytes, x)
return obj
end
end
-function TableInFirstNS.Start(builder) builder:StartObject(3) end
+function TableInFirstNS.Start(builder) builder:StartObject(5) end
function TableInFirstNS.AddFooTable(builder, fooTable) builder:PrependUOffsetTRelativeSlot(0, fooTable, 0) end
function TableInFirstNS.AddFooEnum(builder, fooEnum) builder:PrependInt8Slot(1, fooEnum, 0) end
-function TableInFirstNS.AddFooStruct(builder, fooStruct) builder:PrependStructSlot(2, fooStruct, 0) end
+function TableInFirstNS.AddFooUnionType(builder, fooUnionType) builder:PrependUint8Slot(2, fooUnionType, 0) end
+function TableInFirstNS.AddFooUnion(builder, fooUnion) builder:PrependUOffsetTRelativeSlot(3, fooUnion, 0) end
+function TableInFirstNS.AddFooStruct(builder, fooStruct) builder:PrependStructSlot(4, fooStruct, 0) end
function TableInFirstNS.End(builder) return builder:EndObject() end
return TableInFirstNS -- return the module
\ No newline at end of file
diff --git a/tests/namespace_test/NamespaceA/TableInFirstNS.php b/tests/namespace_test/NamespaceA/TableInFirstNS.php
index 9fb29c3..637ead5 100644
--- a/tests/namespace_test/NamespaceA/TableInFirstNS.php
+++ b/tests/namespace_test/NamespaceA/TableInFirstNS.php
@@ -48,10 +48,28 @@
return $o != 0 ? $this->bb->getSbyte($o + $this->bb_pos) : \NamespaceA\NamespaceB\EnumInNestedNS::A;
}
+ /**
+ * @return byte
+ */
+ public function getFooUnionType()
+ {
+ $o = $this->__offset(8);
+ return $o != 0 ? $this->bb->getByte($o + $this->bb_pos) : \NamespaceA\NamespaceB\UnionInNestedNS::NONE;
+ }
+
+ /**
+ * @returnint
+ */
+ public function getFooUnion($obj)
+ {
+ $o = $this->__offset(10);
+ return $o != 0 ? $this->__union($obj, $o) : null;
+ }
+
public function getFooStruct()
{
$obj = new StructInNestedNS();
- $o = $this->__offset(8);
+ $o = $this->__offset(12);
return $o != 0 ? $obj->init($o + $this->bb_pos, $this->bb) : 0;
}
@@ -61,18 +79,20 @@
*/
public static function startTableInFirstNS(FlatBufferBuilder $builder)
{
- $builder->StartObject(3);
+ $builder->StartObject(5);
}
/**
* @param FlatBufferBuilder $builder
* @return TableInFirstNS
*/
- public static function createTableInFirstNS(FlatBufferBuilder $builder, $foo_table, $foo_enum, $foo_struct)
+ public static function createTableInFirstNS(FlatBufferBuilder $builder, $foo_table, $foo_enum, $foo_union_type, $foo_union, $foo_struct)
{
- $builder->startObject(3);
+ $builder->startObject(5);
self::addFooTable($builder, $foo_table);
self::addFooEnum($builder, $foo_enum);
+ self::addFooUnionType($builder, $foo_union_type);
+ self::addFooUnion($builder, $foo_union);
self::addFooStruct($builder, $foo_struct);
$o = $builder->endObject();
return $o;
@@ -100,12 +120,27 @@
/**
* @param FlatBufferBuilder $builder
+ * @param byte
+ * @return void
+ */
+ public static function addFooUnionType(FlatBufferBuilder $builder, $fooUnionType)
+ {
+ $builder->addByteX(2, $fooUnionType, 0);
+ }
+
+ public static function addFooUnion(FlatBufferBuilder $builder, $offset)
+ {
+ $builder->addOffsetX(3, $offset, 0);
+ }
+
+ /**
+ * @param FlatBufferBuilder $builder
* @param int
* @return void
*/
public static function addFooStruct(FlatBufferBuilder $builder, $fooStruct)
{
- $builder->addStructX(2, $fooStruct, 0);
+ $builder->addStructX(4, $fooStruct, 0);
}
/**
diff --git a/tests/namespace_test/NamespaceA/TableInFirstNS.py b/tests/namespace_test/NamespaceA/TableInFirstNS.py
index 39598f5..8f191f8 100644
--- a/tests/namespace_test/NamespaceA/TableInFirstNS.py
+++ b/tests/namespace_test/NamespaceA/TableInFirstNS.py
@@ -10,12 +10,16 @@
__slots__ = ['_tab']
@classmethod
- def GetRootAsTableInFirstNS(cls, buf, offset):
+ def GetRootAs(cls, buf, offset=0):
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
x = TableInFirstNS()
x.Init(buf, n + offset)
return x
+ @classmethod
+ def GetRootAsTableInFirstNS(cls, buf, offset=0):
+ """This method is deprecated. Please switch to GetRootAs."""
+ return cls.GetRootAs(buf, offset)
# TableInFirstNS
def Init(self, buf, pos):
self._tab = flatbuffers.table.Table(buf, pos)
@@ -38,23 +42,55 @@
return 0
# TableInFirstNS
- def FooStruct(self):
+ def FooUnionType(self):
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8))
if o != 0:
+ return self._tab.Get(flatbuffers.number_types.Uint8Flags, o + self._tab.Pos)
+ return 0
+
+ # TableInFirstNS
+ def FooUnion(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10))
+ if o != 0:
+ from flatbuffers.table import Table
+ obj = Table(bytearray(), 0)
+ self._tab.Union(obj, o)
+ return obj
+ return None
+
+ # TableInFirstNS
+ def FooStruct(self):
+ o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12))
+ if o != 0:
x = o + self._tab.Pos
obj = StructInNestedNS()
obj.Init(self._tab.Bytes, x)
return obj
return None
-def TableInFirstNSStart(builder): builder.StartObject(3)
+def TableInFirstNSStart(builder): builder.StartObject(5)
+def Start(builder):
+ return TableInFirstNSStart(builder)
def TableInFirstNSAddFooTable(builder, fooTable): builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(fooTable), 0)
+def AddFooTable(builder, fooTable):
+ return TableInFirstNSAddFooTable(builder, fooTable)
def TableInFirstNSAddFooEnum(builder, fooEnum): builder.PrependInt8Slot(1, fooEnum, 0)
-def TableInFirstNSAddFooStruct(builder, fooStruct): builder.PrependStructSlot(2, flatbuffers.number_types.UOffsetTFlags.py_type(fooStruct), 0)
+def AddFooEnum(builder, fooEnum):
+ return TableInFirstNSAddFooEnum(builder, fooEnum)
+def TableInFirstNSAddFooUnionType(builder, fooUnionType): builder.PrependUint8Slot(2, fooUnionType, 0)
+def AddFooUnionType(builder, fooUnionType):
+ return TableInFirstNSAddFooUnionType(builder, fooUnionType)
+def TableInFirstNSAddFooUnion(builder, fooUnion): builder.PrependUOffsetTRelativeSlot(3, flatbuffers.number_types.UOffsetTFlags.py_type(fooUnion), 0)
+def AddFooUnion(builder, fooUnion):
+ return TableInFirstNSAddFooUnion(builder, fooUnion)
+def TableInFirstNSAddFooStruct(builder, fooStruct): builder.PrependStructSlot(4, flatbuffers.number_types.UOffsetTFlags.py_type(fooStruct), 0)
+def AddFooStruct(builder, fooStruct):
+ return TableInFirstNSAddFooStruct(builder, fooStruct)
def TableInFirstNSEnd(builder): return builder.EndObject()
-
+def End(builder):
+ return TableInFirstNSEnd(builder)
try:
- from typing import Optional
+ from typing import Optional, Union
except:
pass
@@ -64,6 +100,8 @@
def __init__(self):
self.fooTable = None # type: Optional[TableInNestedNST]
self.fooEnum = 0 # type: int
+ self.fooUnionType = 0 # type: int
+ self.fooUnion = None # type: Union[None, TableInNestedNST]
self.fooStruct = None # type: Optional[StructInNestedNST]
@classmethod
@@ -85,6 +123,8 @@
if tableInFirstNS.FooTable() is not None:
self.fooTable = TableInNestedNST.InitFromObj(tableInFirstNS.FooTable())
self.fooEnum = tableInFirstNS.FooEnum()
+ self.fooUnionType = tableInFirstNS.FooUnionType()
+ self.fooUnion = UnionInNestedNSCreator(self.fooUnionType, tableInFirstNS.FooUnion())
if tableInFirstNS.FooStruct() is not None:
self.fooStruct = StructInNestedNST.InitFromObj(tableInFirstNS.FooStruct())
@@ -92,10 +132,15 @@
def Pack(self, builder):
if self.fooTable is not None:
fooTable = self.fooTable.Pack(builder)
+ if self.fooUnion is not None:
+ fooUnion = self.fooUnion.Pack(builder)
TableInFirstNSStart(builder)
if self.fooTable is not None:
TableInFirstNSAddFooTable(builder, fooTable)
TableInFirstNSAddFooEnum(builder, self.fooEnum)
+ TableInFirstNSAddFooUnionType(builder, self.fooUnionType)
+ if self.fooUnion is not None:
+ TableInFirstNSAddFooUnion(builder, fooUnion)
if self.fooStruct is not None:
fooStruct = self.fooStruct.Pack(builder)
TableInFirstNSAddFooStruct(builder, fooStruct)
diff --git a/tests/namespace_test/NamespaceA/TableInFirstNST.java b/tests/namespace_test/NamespaceA/TableInFirstNST.java
new file mode 100644
index 0000000..ee439d4
--- /dev/null
+++ b/tests/namespace_test/NamespaceA/TableInFirstNST.java
@@ -0,0 +1,40 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+package NamespaceA;
+
+import java.nio.*;
+import java.lang.*;
+import java.util.*;
+import com.google.flatbuffers.*;
+
+public class TableInFirstNST {
+ private NamespaceA.NamespaceB.TableInNestedNST fooTable;
+ private byte fooEnum;
+ private NamespaceA.NamespaceB.UnionInNestedNSUnion fooUnion;
+ private NamespaceA.NamespaceB.StructInNestedNST fooStruct;
+
+ public NamespaceA.NamespaceB.TableInNestedNST getFooTable() { return fooTable; }
+
+ public void setFooTable(NamespaceA.NamespaceB.TableInNestedNST fooTable) { this.fooTable = fooTable; }
+
+ public byte getFooEnum() { return fooEnum; }
+
+ public void setFooEnum(byte fooEnum) { this.fooEnum = fooEnum; }
+
+ public NamespaceA.NamespaceB.UnionInNestedNSUnion getFooUnion() { return fooUnion; }
+
+ public void setFooUnion(NamespaceA.NamespaceB.UnionInNestedNSUnion fooUnion) { this.fooUnion = fooUnion; }
+
+ public NamespaceA.NamespaceB.StructInNestedNST getFooStruct() { return fooStruct; }
+
+ public void setFooStruct(NamespaceA.NamespaceB.StructInNestedNST fooStruct) { this.fooStruct = fooStruct; }
+
+
+ public TableInFirstNST() {
+ this.fooTable = null;
+ this.fooEnum = 0;
+ this.fooUnion = null;
+ this.fooStruct = new NamespaceA.NamespaceB.StructInNestedNST();
+ }
+}
+
diff --git a/tests/namespace_test/NamespaceC/TableInC.cs b/tests/namespace_test/NamespaceC/TableInC.cs
index bfb9b76..2077e32 100644
--- a/tests/namespace_test/NamespaceC/TableInC.cs
+++ b/tests/namespace_test/NamespaceC/TableInC.cs
@@ -13,7 +13,7 @@
{
private Table __p;
public ByteBuffer ByteBuffer { get { return __p.bb; } }
- public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_1_12_0(); }
+ public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_2_0_0(); }
public static TableInC GetRootAsTableInC(ByteBuffer _bb) { return GetRootAsTableInC(_bb, new TableInC()); }
public static TableInC GetRootAsTableInC(ByteBuffer _bb, TableInC obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); }
public void __init(int _i, ByteBuffer _bb) { __p = new Table(_i, _bb); }
@@ -56,7 +56,7 @@
_refer_to_a1,
_refer_to_a2);
}
-};
+}
public class TableInCT
{
diff --git a/tests/namespace_test/NamespaceC/TableInC.java b/tests/namespace_test/NamespaceC/TableInC.java
index 503f237..04ceac7 100644
--- a/tests/namespace_test/NamespaceC/TableInC.java
+++ b/tests/namespace_test/NamespaceC/TableInC.java
@@ -9,7 +9,7 @@
@SuppressWarnings("unused")
public final class TableInC extends Table {
- public static void ValidateVersion() { Constants.FLATBUFFERS_1_12_0(); }
+ public static void ValidateVersion() { Constants.FLATBUFFERS_2_0_0(); }
public static TableInC getRootAsTableInC(ByteBuffer _bb) { return getRootAsTableInC(_bb, new TableInC()); }
public static TableInC getRootAsTableInC(ByteBuffer _bb, TableInC obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); }
@@ -21,11 +21,11 @@
public NamespaceA.SecondTableInA referToA2(NamespaceA.SecondTableInA obj) { int o = __offset(6); return o != 0 ? obj.__assign(__indirect(o + bb_pos), bb) : null; }
public static int createTableInC(FlatBufferBuilder builder,
- int refer_to_a1Offset,
- int refer_to_a2Offset) {
+ int referToA1Offset,
+ int referToA2Offset) {
builder.startTable(2);
- TableInC.addReferToA2(builder, refer_to_a2Offset);
- TableInC.addReferToA1(builder, refer_to_a1Offset);
+ TableInC.addReferToA2(builder, referToA2Offset);
+ TableInC.addReferToA1(builder, referToA1Offset);
return TableInC.endTableInC(builder);
}
@@ -43,5 +43,25 @@
public TableInC get(int j) { return get(new TableInC(), j); }
public TableInC get(TableInC obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); }
}
+ public TableInCT unpack() {
+ TableInCT _o = new TableInCT();
+ unpackTo(_o);
+ return _o;
+ }
+ public void unpackTo(TableInCT _o) {
+ if (referToA1() != null) _o.setReferToA1(referToA1().unpack());
+ else _o.setReferToA1(null);
+ if (referToA2() != null) _o.setReferToA2(referToA2().unpack());
+ else _o.setReferToA2(null);
+ }
+ public static int pack(FlatBufferBuilder builder, TableInCT _o) {
+ if (_o == null) return 0;
+ int _refer_to_a1 = _o.getReferToA1() == null ? 0 : NamespaceA.TableInFirstNS.pack(builder, _o.getReferToA1());
+ int _refer_to_a2 = _o.getReferToA2() == null ? 0 : NamespaceA.SecondTableInA.pack(builder, _o.getReferToA2());
+ return createTableInC(
+ builder,
+ _refer_to_a1,
+ _refer_to_a2);
+ }
}
diff --git a/tests/namespace_test/NamespaceC/TableInC.kt b/tests/namespace_test/NamespaceC/TableInC.kt
index a5222f1..7586e25 100644
--- a/tests/namespace_test/NamespaceC/TableInC.kt
+++ b/tests/namespace_test/NamespaceC/TableInC.kt
@@ -36,7 +36,7 @@
}
}
companion object {
- fun validateVersion() = Constants.FLATBUFFERS_1_12_0()
+ fun validateVersion() = Constants.FLATBUFFERS_2_0_0()
fun getRootAsTableInC(_bb: ByteBuffer): TableInC = getRootAsTableInC(_bb, TableInC())
fun getRootAsTableInC(_bb: ByteBuffer, obj: TableInC): TableInC {
_bb.order(ByteOrder.LITTLE_ENDIAN)
diff --git a/tests/namespace_test/NamespaceC/TableInC.lua b/tests/namespace_test/NamespaceC/TableInC.lua
index bb4fef0..71e4842 100644
--- a/tests/namespace_test/NamespaceC/TableInC.lua
+++ b/tests/namespace_test/NamespaceC/TableInC.lua
@@ -13,6 +13,9 @@
return o
end
function TableInC.GetRootAsTableInC(buf, offset)
+ if type(buf) == "string" then
+ buf = flatbuffers.binaryArray.New(buf)
+ end
local n = flatbuffers.N.UOffsetT:Unpack(buf, offset)
local o = TableInC.New()
o:Init(buf, n + offset)
diff --git a/tests/namespace_test/NamespaceC/TableInC.py b/tests/namespace_test/NamespaceC/TableInC.py
index 8f04b52..762e1a1 100644
--- a/tests/namespace_test/NamespaceC/TableInC.py
+++ b/tests/namespace_test/NamespaceC/TableInC.py
@@ -10,12 +10,16 @@
__slots__ = ['_tab']
@classmethod
- def GetRootAsTableInC(cls, buf, offset):
+ def GetRootAs(cls, buf, offset=0):
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
x = TableInC()
x.Init(buf, n + offset)
return x
+ @classmethod
+ def GetRootAsTableInC(cls, buf, offset=0):
+ """This method is deprecated. Please switch to GetRootAs."""
+ return cls.GetRootAs(buf, offset)
# TableInC
def Init(self, buf, pos):
self._tab = flatbuffers.table.Table(buf, pos)
@@ -41,10 +45,17 @@
return None
def TableInCStart(builder): builder.StartObject(2)
+def Start(builder):
+ return TableInCStart(builder)
def TableInCAddReferToA1(builder, referToA1): builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(referToA1), 0)
+def AddReferToA1(builder, referToA1):
+ return TableInCAddReferToA1(builder, referToA1)
def TableInCAddReferToA2(builder, referToA2): builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(referToA2), 0)
+def AddReferToA2(builder, referToA2):
+ return TableInCAddReferToA2(builder, referToA2)
def TableInCEnd(builder): return builder.EndObject()
-
+def End(builder):
+ return TableInCEnd(builder)
try:
from typing import Optional
except:
diff --git a/tests/namespace_test/NamespaceC/TableInCT.java b/tests/namespace_test/NamespaceC/TableInCT.java
new file mode 100644
index 0000000..d265091
--- /dev/null
+++ b/tests/namespace_test/NamespaceC/TableInCT.java
@@ -0,0 +1,28 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+package NamespaceC;
+
+import java.nio.*;
+import java.lang.*;
+import java.util.*;
+import com.google.flatbuffers.*;
+
+public class TableInCT {
+ private NamespaceA.TableInFirstNST referToA1;
+ private NamespaceA.SecondTableInAT referToA2;
+
+ public NamespaceA.TableInFirstNST getReferToA1() { return referToA1; }
+
+ public void setReferToA1(NamespaceA.TableInFirstNST referToA1) { this.referToA1 = referToA1; }
+
+ public NamespaceA.SecondTableInAT getReferToA2() { return referToA2; }
+
+ public void setReferToA2(NamespaceA.SecondTableInAT referToA2) { this.referToA2 = referToA2; }
+
+
+ public TableInCT() {
+ this.referToA1 = null;
+ this.referToA2 = null;
+ }
+}
+
diff --git a/tests/namespace_test/mod.rs b/tests/namespace_test/mod.rs
new file mode 100644
index 0000000..8572c8d
--- /dev/null
+++ b/tests/namespace_test/mod.rs
@@ -0,0 +1,24 @@
+// Automatically generated by the Flatbuffers compiler. Do not modify.
+pub mod namespace_a {
+ use super::*;
+ pub mod namespace_b {
+ use super::*;
+ mod union_in_nested_ns_generated;
+ pub use self::union_in_nested_ns_generated::*;
+ mod enum_in_nested_ns_generated;
+ pub use self::enum_in_nested_ns_generated::*;
+ mod table_in_nested_ns_generated;
+ pub use self::table_in_nested_ns_generated::*;
+ mod struct_in_nested_ns_generated;
+ pub use self::struct_in_nested_ns_generated::*;
+ } // namespace_b
+ mod table_in_first_ns_generated;
+ pub use self::table_in_first_ns_generated::*;
+ mod second_table_in_a_generated;
+ pub use self::second_table_in_a_generated::*;
+} // namespace_a
+pub mod namespace_c {
+ use super::*;
+ mod table_in_c_generated;
+ pub use self::table_in_c_generated::*;
+} // namespace_c
diff --git a/tests/namespace_test/namespace-a/namespace-b/enum-in-nested-n-s.js b/tests/namespace_test/namespace-a/namespace-b/enum-in-nested-n-s.js
new file mode 100644
index 0000000..9105ed4
--- /dev/null
+++ b/tests/namespace_test/namespace-a/namespace-b/enum-in-nested-n-s.js
@@ -0,0 +1,7 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+export var EnumInNestedNS;
+(function (EnumInNestedNS) {
+ EnumInNestedNS[EnumInNestedNS["A"] = 0] = "A";
+ EnumInNestedNS[EnumInNestedNS["B"] = 1] = "B";
+ EnumInNestedNS[EnumInNestedNS["C"] = 2] = "C";
+})(EnumInNestedNS || (EnumInNestedNS = {}));
diff --git a/tests/namespace_test/namespace-a/namespace-b/enum-in-nested-n-s.ts b/tests/namespace_test/namespace-a/namespace-b/enum-in-nested-n-s.ts
new file mode 100644
index 0000000..676b7e4
--- /dev/null
+++ b/tests/namespace_test/namespace-a/namespace-b/enum-in-nested-n-s.ts
@@ -0,0 +1,8 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+export enum EnumInNestedNS{
+ A = 0,
+ B = 1,
+ C = 2
+}
+
diff --git a/tests/namespace_test/namespace-a/namespace-b/struct-in-nested-n-s.js b/tests/namespace_test/namespace-a/namespace-b/struct-in-nested-n-s.js
new file mode 100644
index 0000000..918e238
--- /dev/null
+++ b/tests/namespace_test/namespace-a/namespace-b/struct-in-nested-n-s.js
@@ -0,0 +1,54 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+export class StructInNestedNS {
+ constructor() {
+ this.bb = null;
+ this.bb_pos = 0;
+ }
+ __init(i, bb) {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+ }
+ a() {
+ return this.bb.readInt32(this.bb_pos);
+ }
+ mutate_a(value) {
+ this.bb.writeInt32(this.bb_pos + 0, value);
+ return true;
+ }
+ b() {
+ return this.bb.readInt32(this.bb_pos + 4);
+ }
+ mutate_b(value) {
+ this.bb.writeInt32(this.bb_pos + 4, value);
+ return true;
+ }
+ static getFullyQualifiedName() {
+ return 'NamespaceA.NamespaceB.StructInNestedNS';
+ }
+ static sizeOf() {
+ return 8;
+ }
+ static createStructInNestedNS(builder, a, b) {
+ builder.prep(4, 8);
+ builder.writeInt32(b);
+ builder.writeInt32(a);
+ return builder.offset();
+ }
+ unpack() {
+ return new StructInNestedNST(this.a(), this.b());
+ }
+ unpackTo(_o) {
+ _o.a = this.a();
+ _o.b = this.b();
+ }
+}
+export class StructInNestedNST {
+ constructor(a = 0, b = 0) {
+ this.a = a;
+ this.b = b;
+ }
+ pack(builder) {
+ return StructInNestedNS.createStructInNestedNS(builder, this.a, this.b);
+ }
+}
diff --git a/tests/namespace_test/namespace-a/namespace-b/struct-in-nested-n-s.ts b/tests/namespace_test/namespace-a/namespace-b/struct-in-nested-n-s.ts
new file mode 100644
index 0000000..4b10118
--- /dev/null
+++ b/tests/namespace_test/namespace-a/namespace-b/struct-in-nested-n-s.ts
@@ -0,0 +1,77 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+import * as flatbuffers from 'flatbuffers';
+
+
+
+export class StructInNestedNS {
+ bb: flatbuffers.ByteBuffer|null = null;
+ bb_pos = 0;
+__init(i:number, bb:flatbuffers.ByteBuffer):StructInNestedNS {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+}
+
+a():number {
+ return this.bb!.readInt32(this.bb_pos);
+}
+
+mutate_a(value:number):boolean {
+ this.bb!.writeInt32(this.bb_pos + 0, value);
+ return true;
+}
+
+b():number {
+ return this.bb!.readInt32(this.bb_pos + 4);
+}
+
+mutate_b(value:number):boolean {
+ this.bb!.writeInt32(this.bb_pos + 4, value);
+ return true;
+}
+
+static getFullyQualifiedName():string {
+ return 'NamespaceA.NamespaceB.StructInNestedNS';
+}
+
+static sizeOf():number {
+ return 8;
+}
+
+static createStructInNestedNS(builder:flatbuffers.Builder, a: number, b: number):flatbuffers.Offset {
+ builder.prep(4, 8);
+ builder.writeInt32(b);
+ builder.writeInt32(a);
+ return builder.offset();
+}
+
+
+unpack(): StructInNestedNST {
+ return new StructInNestedNST(
+ this.a(),
+ this.b()
+ );
+}
+
+
+unpackTo(_o: StructInNestedNST): void {
+ _o.a = this.a();
+ _o.b = this.b();
+}
+}
+
+export class StructInNestedNST {
+constructor(
+ public a: number = 0,
+ public b: number = 0
+){}
+
+
+pack(builder:flatbuffers.Builder): flatbuffers.Offset {
+ return StructInNestedNS.createStructInNestedNS(builder,
+ this.a,
+ this.b
+ );
+}
+}
diff --git a/tests/namespace_test/namespace-a/namespace-b/table-in-nested-n-s.js b/tests/namespace_test/namespace-a/namespace-b/table-in-nested-n-s.js
new file mode 100644
index 0000000..fca1668
--- /dev/null
+++ b/tests/namespace_test/namespace-a/namespace-b/table-in-nested-n-s.js
@@ -0,0 +1,64 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+import * as flatbuffers from 'flatbuffers';
+export class TableInNestedNS {
+ constructor() {
+ this.bb = null;
+ this.bb_pos = 0;
+ }
+ __init(i, bb) {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+ }
+ static getRootAsTableInNestedNS(bb, obj) {
+ return (obj || new TableInNestedNS()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ static getSizePrefixedRootAsTableInNestedNS(bb, obj) {
+ bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new TableInNestedNS()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ foo() {
+ const offset = this.bb.__offset(this.bb_pos, 4);
+ return offset ? this.bb.readInt32(this.bb_pos + offset) : 0;
+ }
+ mutate_foo(value) {
+ const offset = this.bb.__offset(this.bb_pos, 4);
+ if (offset === 0) {
+ return false;
+ }
+ this.bb.writeInt32(this.bb_pos + offset, value);
+ return true;
+ }
+ static getFullyQualifiedName() {
+ return 'NamespaceA.NamespaceB.TableInNestedNS';
+ }
+ static startTableInNestedNS(builder) {
+ builder.startObject(1);
+ }
+ static addFoo(builder, foo) {
+ builder.addFieldInt32(0, foo, 0);
+ }
+ static endTableInNestedNS(builder) {
+ const offset = builder.endObject();
+ return offset;
+ }
+ static createTableInNestedNS(builder, foo) {
+ TableInNestedNS.startTableInNestedNS(builder);
+ TableInNestedNS.addFoo(builder, foo);
+ return TableInNestedNS.endTableInNestedNS(builder);
+ }
+ unpack() {
+ return new TableInNestedNST(this.foo());
+ }
+ unpackTo(_o) {
+ _o.foo = this.foo();
+ }
+}
+export class TableInNestedNST {
+ constructor(foo = 0) {
+ this.foo = foo;
+ }
+ pack(builder) {
+ return TableInNestedNS.createTableInNestedNS(builder, this.foo);
+ }
+}
diff --git a/tests/namespace_test/namespace-a/namespace-b/table-in-nested-n-s.ts b/tests/namespace_test/namespace-a/namespace-b/table-in-nested-n-s.ts
new file mode 100644
index 0000000..5279fdb
--- /dev/null
+++ b/tests/namespace_test/namespace-a/namespace-b/table-in-nested-n-s.ts
@@ -0,0 +1,87 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+import * as flatbuffers from 'flatbuffers';
+
+
+
+export class TableInNestedNS {
+ bb: flatbuffers.ByteBuffer|null = null;
+ bb_pos = 0;
+__init(i:number, bb:flatbuffers.ByteBuffer):TableInNestedNS {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+}
+
+static getRootAsTableInNestedNS(bb:flatbuffers.ByteBuffer, obj?:TableInNestedNS):TableInNestedNS {
+ return (obj || new TableInNestedNS()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+}
+
+static getSizePrefixedRootAsTableInNestedNS(bb:flatbuffers.ByteBuffer, obj?:TableInNestedNS):TableInNestedNS {
+ bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new TableInNestedNS()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+}
+
+foo():number {
+ const offset = this.bb!.__offset(this.bb_pos, 4);
+ return offset ? this.bb!.readInt32(this.bb_pos + offset) : 0;
+}
+
+mutate_foo(value:number):boolean {
+ const offset = this.bb!.__offset(this.bb_pos, 4);
+
+ if (offset === 0) {
+ return false;
+ }
+
+ this.bb!.writeInt32(this.bb_pos + offset, value);
+ return true;
+}
+
+static getFullyQualifiedName():string {
+ return 'NamespaceA.NamespaceB.TableInNestedNS';
+}
+
+static startTableInNestedNS(builder:flatbuffers.Builder) {
+ builder.startObject(1);
+}
+
+static addFoo(builder:flatbuffers.Builder, foo:number) {
+ builder.addFieldInt32(0, foo, 0);
+}
+
+static endTableInNestedNS(builder:flatbuffers.Builder):flatbuffers.Offset {
+ const offset = builder.endObject();
+ return offset;
+}
+
+static createTableInNestedNS(builder:flatbuffers.Builder, foo:number):flatbuffers.Offset {
+ TableInNestedNS.startTableInNestedNS(builder);
+ TableInNestedNS.addFoo(builder, foo);
+ return TableInNestedNS.endTableInNestedNS(builder);
+}
+
+unpack(): TableInNestedNST {
+ return new TableInNestedNST(
+ this.foo()
+ );
+}
+
+
+unpackTo(_o: TableInNestedNST): void {
+ _o.foo = this.foo();
+}
+}
+
+export class TableInNestedNST {
+constructor(
+ public foo: number = 0
+){}
+
+
+pack(builder:flatbuffers.Builder): flatbuffers.Offset {
+ return TableInNestedNS.createTableInNestedNS(builder,
+ this.foo
+ );
+}
+}
diff --git a/tests/namespace_test/namespace-a/namespace-b/union-in-nested-n-s.js b/tests/namespace_test/namespace-a/namespace-b/union-in-nested-n-s.js
new file mode 100644
index 0000000..b820bce
--- /dev/null
+++ b/tests/namespace_test/namespace-a/namespace-b/union-in-nested-n-s.js
@@ -0,0 +1,21 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+import { TableInNestedNS } from '../../namespace-a/namespace-b/table-in-nested-n-s';
+export var UnionInNestedNS;
+(function (UnionInNestedNS) {
+ UnionInNestedNS[UnionInNestedNS["NONE"] = 0] = "NONE";
+ UnionInNestedNS[UnionInNestedNS["TableInNestedNS"] = 1] = "TableInNestedNS";
+})(UnionInNestedNS || (UnionInNestedNS = {}));
+export function unionToUnionInNestedNS(type, accessor) {
+ switch (UnionInNestedNS[type]) {
+ case 'NONE': return null;
+ case 'TableInNestedNS': return accessor(new TableInNestedNS());
+ default: return null;
+ }
+}
+export function unionListToUnionInNestedNS(type, accessor, index) {
+ switch (UnionInNestedNS[type]) {
+ case 'NONE': return null;
+ case 'TableInNestedNS': return accessor(index, new TableInNestedNS());
+ default: return null;
+ }
+}
diff --git a/tests/namespace_test/namespace-a/namespace-b/union-in-nested-n-s.ts b/tests/namespace_test/namespace-a/namespace-b/union-in-nested-n-s.ts
new file mode 100644
index 0000000..441ebf7
--- /dev/null
+++ b/tests/namespace_test/namespace-a/namespace-b/union-in-nested-n-s.ts
@@ -0,0 +1,33 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+import { TableInNestedNS, TableInNestedNST } from '../../namespace-a/namespace-b/table-in-nested-n-s';
+
+
+export enum UnionInNestedNS{
+ NONE = 0,
+ TableInNestedNS = 1
+}
+
+export function unionToUnionInNestedNS(
+ type: UnionInNestedNS,
+ accessor: (obj:TableInNestedNS) => TableInNestedNS|null
+): TableInNestedNS|null {
+ switch(UnionInNestedNS[type]) {
+ case 'NONE': return null;
+ case 'TableInNestedNS': return accessor(new TableInNestedNS())! as TableInNestedNS;
+ default: return null;
+ }
+}
+
+export function unionListToUnionInNestedNS(
+ type: UnionInNestedNS,
+ accessor: (index: number, obj:TableInNestedNS) => TableInNestedNS|null,
+ index: number
+): TableInNestedNS|null {
+ switch(UnionInNestedNS[type]) {
+ case 'NONE': return null;
+ case 'TableInNestedNS': return accessor(index, new TableInNestedNS())! as TableInNestedNS;
+ default: return null;
+ }
+}
+
diff --git a/tests/namespace_test/namespace-a/second-table-in-a.js b/tests/namespace_test/namespace-a/second-table-in-a.js
new file mode 100644
index 0000000..fe848e0
--- /dev/null
+++ b/tests/namespace_test/namespace-a/second-table-in-a.js
@@ -0,0 +1,58 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+import * as flatbuffers from 'flatbuffers';
+import { TableInC } from '../namespace-c/table-in-c';
+export class SecondTableInA {
+ constructor() {
+ this.bb = null;
+ this.bb_pos = 0;
+ }
+ __init(i, bb) {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+ }
+ static getRootAsSecondTableInA(bb, obj) {
+ return (obj || new SecondTableInA()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ static getSizePrefixedRootAsSecondTableInA(bb, obj) {
+ bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new SecondTableInA()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ referToC(obj) {
+ const offset = this.bb.__offset(this.bb_pos, 4);
+ return offset ? (obj || new TableInC()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null;
+ }
+ static getFullyQualifiedName() {
+ return 'NamespaceA.SecondTableInA';
+ }
+ static startSecondTableInA(builder) {
+ builder.startObject(1);
+ }
+ static addReferToC(builder, referToCOffset) {
+ builder.addFieldOffset(0, referToCOffset, 0);
+ }
+ static endSecondTableInA(builder) {
+ const offset = builder.endObject();
+ return offset;
+ }
+ static createSecondTableInA(builder, referToCOffset) {
+ SecondTableInA.startSecondTableInA(builder);
+ SecondTableInA.addReferToC(builder, referToCOffset);
+ return SecondTableInA.endSecondTableInA(builder);
+ }
+ unpack() {
+ return new SecondTableInAT((this.referToC() !== null ? this.referToC().unpack() : null));
+ }
+ unpackTo(_o) {
+ _o.referToC = (this.referToC() !== null ? this.referToC().unpack() : null);
+ }
+}
+export class SecondTableInAT {
+ constructor(referToC = null) {
+ this.referToC = referToC;
+ }
+ pack(builder) {
+ const referToC = (this.referToC !== null ? this.referToC.pack(builder) : 0);
+ return SecondTableInA.createSecondTableInA(builder, referToC);
+ }
+}
diff --git a/tests/namespace_test/namespace-a/second-table-in-a.ts b/tests/namespace_test/namespace-a/second-table-in-a.ts
new file mode 100644
index 0000000..9be3402
--- /dev/null
+++ b/tests/namespace_test/namespace-a/second-table-in-a.ts
@@ -0,0 +1,79 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+import * as flatbuffers from 'flatbuffers';
+
+import { TableInC, TableInCT } from '../namespace-c/table-in-c';
+
+
+export class SecondTableInA {
+ bb: flatbuffers.ByteBuffer|null = null;
+ bb_pos = 0;
+__init(i:number, bb:flatbuffers.ByteBuffer):SecondTableInA {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+}
+
+static getRootAsSecondTableInA(bb:flatbuffers.ByteBuffer, obj?:SecondTableInA):SecondTableInA {
+ return (obj || new SecondTableInA()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+}
+
+static getSizePrefixedRootAsSecondTableInA(bb:flatbuffers.ByteBuffer, obj?:SecondTableInA):SecondTableInA {
+ bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new SecondTableInA()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+}
+
+referToC(obj?:TableInC):TableInC|null {
+ const offset = this.bb!.__offset(this.bb_pos, 4);
+ return offset ? (obj || new TableInC()).__init(this.bb!.__indirect(this.bb_pos + offset), this.bb!) : null;
+}
+
+static getFullyQualifiedName():string {
+ return 'NamespaceA.SecondTableInA';
+}
+
+static startSecondTableInA(builder:flatbuffers.Builder) {
+ builder.startObject(1);
+}
+
+static addReferToC(builder:flatbuffers.Builder, referToCOffset:flatbuffers.Offset) {
+ builder.addFieldOffset(0, referToCOffset, 0);
+}
+
+static endSecondTableInA(builder:flatbuffers.Builder):flatbuffers.Offset {
+ const offset = builder.endObject();
+ return offset;
+}
+
+static createSecondTableInA(builder:flatbuffers.Builder, referToCOffset:flatbuffers.Offset):flatbuffers.Offset {
+ SecondTableInA.startSecondTableInA(builder);
+ SecondTableInA.addReferToC(builder, referToCOffset);
+ return SecondTableInA.endSecondTableInA(builder);
+}
+
+unpack(): SecondTableInAT {
+ return new SecondTableInAT(
+ (this.referToC() !== null ? this.referToC()!.unpack() : null)
+ );
+}
+
+
+unpackTo(_o: SecondTableInAT): void {
+ _o.referToC = (this.referToC() !== null ? this.referToC()!.unpack() : null);
+}
+}
+
+export class SecondTableInAT {
+constructor(
+ public referToC: TableInCT|null = null
+){}
+
+
+pack(builder:flatbuffers.Builder): flatbuffers.Offset {
+ const referToC = (this.referToC !== null ? this.referToC!.pack(builder) : 0);
+
+ return SecondTableInA.createSecondTableInA(builder,
+ referToC
+ );
+}
+}
diff --git a/tests/namespace_test/namespace-a/table-in-first-n-s.js b/tests/namespace_test/namespace-a/table-in-first-n-s.js
new file mode 100644
index 0000000..91bcc85
--- /dev/null
+++ b/tests/namespace_test/namespace-a/table-in-first-n-s.js
@@ -0,0 +1,119 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+import * as flatbuffers from 'flatbuffers';
+import { EnumInNestedNS } from '../namespace-a/namespace-b/enum-in-nested-n-s';
+import { StructInNestedNS } from '../namespace-a/namespace-b/struct-in-nested-n-s';
+import { TableInNestedNS } from '../namespace-a/namespace-b/table-in-nested-n-s';
+import { UnionInNestedNS, unionToUnionInNestedNS } from '../namespace-a/namespace-b/union-in-nested-n-s';
+export class TableInFirstNS {
+ constructor() {
+ this.bb = null;
+ this.bb_pos = 0;
+ }
+ __init(i, bb) {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+ }
+ static getRootAsTableInFirstNS(bb, obj) {
+ return (obj || new TableInFirstNS()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ static getSizePrefixedRootAsTableInFirstNS(bb, obj) {
+ bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new TableInFirstNS()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ fooTable(obj) {
+ const offset = this.bb.__offset(this.bb_pos, 4);
+ return offset ? (obj || new TableInNestedNS()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null;
+ }
+ fooEnum() {
+ const offset = this.bb.__offset(this.bb_pos, 6);
+ return offset ? this.bb.readInt8(this.bb_pos + offset) : EnumInNestedNS.A;
+ }
+ mutate_foo_enum(value) {
+ const offset = this.bb.__offset(this.bb_pos, 6);
+ if (offset === 0) {
+ return false;
+ }
+ this.bb.writeInt8(this.bb_pos + offset, value);
+ return true;
+ }
+ fooUnionType() {
+ const offset = this.bb.__offset(this.bb_pos, 8);
+ return offset ? this.bb.readUint8(this.bb_pos + offset) : UnionInNestedNS.NONE;
+ }
+ fooUnion(obj) {
+ const offset = this.bb.__offset(this.bb_pos, 10);
+ return offset ? this.bb.__union(obj, this.bb_pos + offset) : null;
+ }
+ fooStruct(obj) {
+ const offset = this.bb.__offset(this.bb_pos, 12);
+ return offset ? (obj || new StructInNestedNS()).__init(this.bb_pos + offset, this.bb) : null;
+ }
+ static getFullyQualifiedName() {
+ return 'NamespaceA.TableInFirstNS';
+ }
+ static startTableInFirstNS(builder) {
+ builder.startObject(5);
+ }
+ static addFooTable(builder, fooTableOffset) {
+ builder.addFieldOffset(0, fooTableOffset, 0);
+ }
+ static addFooEnum(builder, fooEnum) {
+ builder.addFieldInt8(1, fooEnum, EnumInNestedNS.A);
+ }
+ static addFooUnionType(builder, fooUnionType) {
+ builder.addFieldInt8(2, fooUnionType, UnionInNestedNS.NONE);
+ }
+ static addFooUnion(builder, fooUnionOffset) {
+ builder.addFieldOffset(3, fooUnionOffset, 0);
+ }
+ static addFooStruct(builder, fooStructOffset) {
+ builder.addFieldStruct(4, fooStructOffset, 0);
+ }
+ static endTableInFirstNS(builder) {
+ const offset = builder.endObject();
+ return offset;
+ }
+ unpack() {
+ return new TableInFirstNST((this.fooTable() !== null ? this.fooTable().unpack() : null), this.fooEnum(), this.fooUnionType(), (() => {
+ let temp = unionToUnionInNestedNS(this.fooUnionType(), this.fooUnion.bind(this));
+ if (temp === null) {
+ return null;
+ }
+ return temp.unpack();
+ })(), (this.fooStruct() !== null ? this.fooStruct().unpack() : null));
+ }
+ unpackTo(_o) {
+ _o.fooTable = (this.fooTable() !== null ? this.fooTable().unpack() : null);
+ _o.fooEnum = this.fooEnum();
+ _o.fooUnionType = this.fooUnionType();
+ _o.fooUnion = (() => {
+ let temp = unionToUnionInNestedNS(this.fooUnionType(), this.fooUnion.bind(this));
+ if (temp === null) {
+ return null;
+ }
+ return temp.unpack();
+ })();
+ _o.fooStruct = (this.fooStruct() !== null ? this.fooStruct().unpack() : null);
+ }
+}
+export class TableInFirstNST {
+ constructor(fooTable = null, fooEnum = EnumInNestedNS.A, fooUnionType = UnionInNestedNS.NONE, fooUnion = null, fooStruct = null) {
+ this.fooTable = fooTable;
+ this.fooEnum = fooEnum;
+ this.fooUnionType = fooUnionType;
+ this.fooUnion = fooUnion;
+ this.fooStruct = fooStruct;
+ }
+ pack(builder) {
+ const fooTable = (this.fooTable !== null ? this.fooTable.pack(builder) : 0);
+ const fooUnion = builder.createObjectOffset(this.fooUnion);
+ TableInFirstNS.startTableInFirstNS(builder);
+ TableInFirstNS.addFooTable(builder, fooTable);
+ TableInFirstNS.addFooEnum(builder, this.fooEnum);
+ TableInFirstNS.addFooUnionType(builder, this.fooUnionType);
+ TableInFirstNS.addFooUnion(builder, fooUnion);
+ TableInFirstNS.addFooStruct(builder, (this.fooStruct !== null ? this.fooStruct.pack(builder) : 0));
+ return TableInFirstNS.endTableInFirstNS(builder);
+ }
+}
diff --git a/tests/namespace_test/namespace-a/table-in-first-n-s.ts b/tests/namespace_test/namespace-a/table-in-first-n-s.ts
new file mode 100644
index 0000000..8e4d706
--- /dev/null
+++ b/tests/namespace_test/namespace-a/table-in-first-n-s.ts
@@ -0,0 +1,150 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+import * as flatbuffers from 'flatbuffers';
+
+import { EnumInNestedNS } from '../namespace-a/namespace-b/enum-in-nested-n-s';
+import { StructInNestedNS, StructInNestedNST } from '../namespace-a/namespace-b/struct-in-nested-n-s';
+import { TableInNestedNS, TableInNestedNST } from '../namespace-a/namespace-b/table-in-nested-n-s';
+import { UnionInNestedNS, unionToUnionInNestedNS, unionListToUnionInNestedNS } from '../namespace-a/namespace-b/union-in-nested-n-s';
+
+
+export class TableInFirstNS {
+ bb: flatbuffers.ByteBuffer|null = null;
+ bb_pos = 0;
+__init(i:number, bb:flatbuffers.ByteBuffer):TableInFirstNS {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+}
+
+static getRootAsTableInFirstNS(bb:flatbuffers.ByteBuffer, obj?:TableInFirstNS):TableInFirstNS {
+ return (obj || new TableInFirstNS()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+}
+
+static getSizePrefixedRootAsTableInFirstNS(bb:flatbuffers.ByteBuffer, obj?:TableInFirstNS):TableInFirstNS {
+ bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new TableInFirstNS()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+}
+
+fooTable(obj?:TableInNestedNS):TableInNestedNS|null {
+ const offset = this.bb!.__offset(this.bb_pos, 4);
+ return offset ? (obj || new TableInNestedNS()).__init(this.bb!.__indirect(this.bb_pos + offset), this.bb!) : null;
+}
+
+fooEnum():EnumInNestedNS {
+ const offset = this.bb!.__offset(this.bb_pos, 6);
+ return offset ? this.bb!.readInt8(this.bb_pos + offset) : EnumInNestedNS.A;
+}
+
+mutate_foo_enum(value:EnumInNestedNS):boolean {
+ const offset = this.bb!.__offset(this.bb_pos, 6);
+
+ if (offset === 0) {
+ return false;
+ }
+
+ this.bb!.writeInt8(this.bb_pos + offset, value);
+ return true;
+}
+
+fooUnionType():UnionInNestedNS {
+ const offset = this.bb!.__offset(this.bb_pos, 8);
+ return offset ? this.bb!.readUint8(this.bb_pos + offset) : UnionInNestedNS.NONE;
+}
+
+fooUnion<T extends flatbuffers.Table>(obj:any):any|null {
+ const offset = this.bb!.__offset(this.bb_pos, 10);
+ return offset ? this.bb!.__union(obj, this.bb_pos + offset) : null;
+}
+
+fooStruct(obj?:StructInNestedNS):StructInNestedNS|null {
+ const offset = this.bb!.__offset(this.bb_pos, 12);
+ return offset ? (obj || new StructInNestedNS()).__init(this.bb_pos + offset, this.bb!) : null;
+}
+
+static getFullyQualifiedName():string {
+ return 'NamespaceA.TableInFirstNS';
+}
+
+static startTableInFirstNS(builder:flatbuffers.Builder) {
+ builder.startObject(5);
+}
+
+static addFooTable(builder:flatbuffers.Builder, fooTableOffset:flatbuffers.Offset) {
+ builder.addFieldOffset(0, fooTableOffset, 0);
+}
+
+static addFooEnum(builder:flatbuffers.Builder, fooEnum:EnumInNestedNS) {
+ builder.addFieldInt8(1, fooEnum, EnumInNestedNS.A);
+}
+
+static addFooUnionType(builder:flatbuffers.Builder, fooUnionType:UnionInNestedNS) {
+ builder.addFieldInt8(2, fooUnionType, UnionInNestedNS.NONE);
+}
+
+static addFooUnion(builder:flatbuffers.Builder, fooUnionOffset:flatbuffers.Offset) {
+ builder.addFieldOffset(3, fooUnionOffset, 0);
+}
+
+static addFooStruct(builder:flatbuffers.Builder, fooStructOffset:flatbuffers.Offset) {
+ builder.addFieldStruct(4, fooStructOffset, 0);
+}
+
+static endTableInFirstNS(builder:flatbuffers.Builder):flatbuffers.Offset {
+ const offset = builder.endObject();
+ return offset;
+}
+
+
+unpack(): TableInFirstNST {
+ return new TableInFirstNST(
+ (this.fooTable() !== null ? this.fooTable()!.unpack() : null),
+ this.fooEnum(),
+ this.fooUnionType(),
+ (() => {
+ let temp = unionToUnionInNestedNS(this.fooUnionType(), this.fooUnion.bind(this));
+ if(temp === null) { return null; }
+ return temp.unpack()
+ })(),
+ (this.fooStruct() !== null ? this.fooStruct()!.unpack() : null)
+ );
+}
+
+
+unpackTo(_o: TableInFirstNST): void {
+ _o.fooTable = (this.fooTable() !== null ? this.fooTable()!.unpack() : null);
+ _o.fooEnum = this.fooEnum();
+ _o.fooUnionType = this.fooUnionType();
+ _o.fooUnion = (() => {
+ let temp = unionToUnionInNestedNS(this.fooUnionType(), this.fooUnion.bind(this));
+ if(temp === null) { return null; }
+ return temp.unpack()
+ })();
+ _o.fooStruct = (this.fooStruct() !== null ? this.fooStruct()!.unpack() : null);
+}
+}
+
+export class TableInFirstNST {
+constructor(
+ public fooTable: TableInNestedNST|null = null,
+ public fooEnum: EnumInNestedNS = EnumInNestedNS.A,
+ public fooUnionType: UnionInNestedNS = UnionInNestedNS.NONE,
+ public fooUnion: TableInNestedNST|null = null,
+ public fooStruct: StructInNestedNST|null = null
+){}
+
+
+pack(builder:flatbuffers.Builder): flatbuffers.Offset {
+ const fooTable = (this.fooTable !== null ? this.fooTable!.pack(builder) : 0);
+ const fooUnion = builder.createObjectOffset(this.fooUnion);
+
+ TableInFirstNS.startTableInFirstNS(builder);
+ TableInFirstNS.addFooTable(builder, fooTable);
+ TableInFirstNS.addFooEnum(builder, this.fooEnum);
+ TableInFirstNS.addFooUnionType(builder, this.fooUnionType);
+ TableInFirstNS.addFooUnion(builder, fooUnion);
+ TableInFirstNS.addFooStruct(builder, (this.fooStruct !== null ? this.fooStruct!.pack(builder) : 0));
+
+ return TableInFirstNS.endTableInFirstNS(builder);
+}
+}
diff --git a/tests/namespace_test/namespace-c/table-in-c.js b/tests/namespace_test/namespace-c/table-in-c.js
new file mode 100644
index 0000000..d097a3c
--- /dev/null
+++ b/tests/namespace_test/namespace-c/table-in-c.js
@@ -0,0 +1,67 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+import * as flatbuffers from 'flatbuffers';
+import { SecondTableInA } from '../namespace-a/second-table-in-a';
+import { TableInFirstNS } from '../namespace-a/table-in-first-n-s';
+export class TableInC {
+ constructor() {
+ this.bb = null;
+ this.bb_pos = 0;
+ }
+ __init(i, bb) {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+ }
+ static getRootAsTableInC(bb, obj) {
+ return (obj || new TableInC()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ static getSizePrefixedRootAsTableInC(bb, obj) {
+ bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new TableInC()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ referToA1(obj) {
+ const offset = this.bb.__offset(this.bb_pos, 4);
+ return offset ? (obj || new TableInFirstNS()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null;
+ }
+ referToA2(obj) {
+ const offset = this.bb.__offset(this.bb_pos, 6);
+ return offset ? (obj || new SecondTableInA()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null;
+ }
+ static getFullyQualifiedName() {
+ return 'NamespaceC.TableInC';
+ }
+ static startTableInC(builder) {
+ builder.startObject(2);
+ }
+ static addReferToA1(builder, referToA1Offset) {
+ builder.addFieldOffset(0, referToA1Offset, 0);
+ }
+ static addReferToA2(builder, referToA2Offset) {
+ builder.addFieldOffset(1, referToA2Offset, 0);
+ }
+ static endTableInC(builder) {
+ const offset = builder.endObject();
+ return offset;
+ }
+ unpack() {
+ return new TableInCT((this.referToA1() !== null ? this.referToA1().unpack() : null), (this.referToA2() !== null ? this.referToA2().unpack() : null));
+ }
+ unpackTo(_o) {
+ _o.referToA1 = (this.referToA1() !== null ? this.referToA1().unpack() : null);
+ _o.referToA2 = (this.referToA2() !== null ? this.referToA2().unpack() : null);
+ }
+}
+export class TableInCT {
+ constructor(referToA1 = null, referToA2 = null) {
+ this.referToA1 = referToA1;
+ this.referToA2 = referToA2;
+ }
+ pack(builder) {
+ const referToA1 = (this.referToA1 !== null ? this.referToA1.pack(builder) : 0);
+ const referToA2 = (this.referToA2 !== null ? this.referToA2.pack(builder) : 0);
+ TableInC.startTableInC(builder);
+ TableInC.addReferToA1(builder, referToA1);
+ TableInC.addReferToA2(builder, referToA2);
+ return TableInC.endTableInC(builder);
+ }
+}
diff --git a/tests/namespace_test/namespace-c/table-in-c.ts b/tests/namespace_test/namespace-c/table-in-c.ts
new file mode 100644
index 0000000..7b924b8
--- /dev/null
+++ b/tests/namespace_test/namespace-c/table-in-c.ts
@@ -0,0 +1,90 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+import * as flatbuffers from 'flatbuffers';
+
+import { SecondTableInA, SecondTableInAT } from '../namespace-a/second-table-in-a';
+import { TableInFirstNS, TableInFirstNST } from '../namespace-a/table-in-first-n-s';
+
+
+export class TableInC {
+ bb: flatbuffers.ByteBuffer|null = null;
+ bb_pos = 0;
+__init(i:number, bb:flatbuffers.ByteBuffer):TableInC {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+}
+
+static getRootAsTableInC(bb:flatbuffers.ByteBuffer, obj?:TableInC):TableInC {
+ return (obj || new TableInC()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+}
+
+static getSizePrefixedRootAsTableInC(bb:flatbuffers.ByteBuffer, obj?:TableInC):TableInC {
+ bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new TableInC()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+}
+
+referToA1(obj?:TableInFirstNS):TableInFirstNS|null {
+ const offset = this.bb!.__offset(this.bb_pos, 4);
+ return offset ? (obj || new TableInFirstNS()).__init(this.bb!.__indirect(this.bb_pos + offset), this.bb!) : null;
+}
+
+referToA2(obj?:SecondTableInA):SecondTableInA|null {
+ const offset = this.bb!.__offset(this.bb_pos, 6);
+ return offset ? (obj || new SecondTableInA()).__init(this.bb!.__indirect(this.bb_pos + offset), this.bb!) : null;
+}
+
+static getFullyQualifiedName():string {
+ return 'NamespaceC.TableInC';
+}
+
+static startTableInC(builder:flatbuffers.Builder) {
+ builder.startObject(2);
+}
+
+static addReferToA1(builder:flatbuffers.Builder, referToA1Offset:flatbuffers.Offset) {
+ builder.addFieldOffset(0, referToA1Offset, 0);
+}
+
+static addReferToA2(builder:flatbuffers.Builder, referToA2Offset:flatbuffers.Offset) {
+ builder.addFieldOffset(1, referToA2Offset, 0);
+}
+
+static endTableInC(builder:flatbuffers.Builder):flatbuffers.Offset {
+ const offset = builder.endObject();
+ return offset;
+}
+
+
+unpack(): TableInCT {
+ return new TableInCT(
+ (this.referToA1() !== null ? this.referToA1()!.unpack() : null),
+ (this.referToA2() !== null ? this.referToA2()!.unpack() : null)
+ );
+}
+
+
+unpackTo(_o: TableInCT): void {
+ _o.referToA1 = (this.referToA1() !== null ? this.referToA1()!.unpack() : null);
+ _o.referToA2 = (this.referToA2() !== null ? this.referToA2()!.unpack() : null);
+}
+}
+
+export class TableInCT {
+constructor(
+ public referToA1: TableInFirstNST|null = null,
+ public referToA2: SecondTableInAT|null = null
+){}
+
+
+pack(builder:flatbuffers.Builder): flatbuffers.Offset {
+ const referToA1 = (this.referToA1 !== null ? this.referToA1!.pack(builder) : 0);
+ const referToA2 = (this.referToA2 !== null ? this.referToA2!.pack(builder) : 0);
+
+ TableInC.startTableInC(builder);
+ TableInC.addReferToA1(builder, referToA1);
+ TableInC.addReferToA2(builder, referToA2);
+
+ return TableInC.endTableInC(builder);
+}
+}
diff --git a/tests/namespace_test/namespace_a/namespace_b/enum_in_nested_ns_generated.rs b/tests/namespace_test/namespace_a/namespace_b/enum_in_nested_ns_generated.rs
new file mode 100644
index 0000000..b636638
--- /dev/null
+++ b/tests/namespace_test/namespace_a/namespace_b/enum_in_nested_ns_generated.rs
@@ -0,0 +1,97 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+pub const ENUM_MIN_ENUM_IN_NESTED_NS: i8 = 0;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+pub const ENUM_MAX_ENUM_IN_NESTED_NS: i8 = 2;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+#[allow(non_camel_case_types)]
+pub const ENUM_VALUES_ENUM_IN_NESTED_NS: [EnumInNestedNS; 3] = [
+ EnumInNestedNS::A,
+ EnumInNestedNS::B,
+ EnumInNestedNS::C,
+];
+
+#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
+#[repr(transparent)]
+pub struct EnumInNestedNS(pub i8);
+#[allow(non_upper_case_globals)]
+impl EnumInNestedNS {
+ pub const A: Self = Self(0);
+ pub const B: Self = Self(1);
+ pub const C: Self = Self(2);
+
+ pub const ENUM_MIN: i8 = 0;
+ pub const ENUM_MAX: i8 = 2;
+ pub const ENUM_VALUES: &'static [Self] = &[
+ Self::A,
+ Self::B,
+ Self::C,
+ ];
+ /// Returns the variant's name or "" if unknown.
+ pub fn variant_name(self) -> Option<&'static str> {
+ match self {
+ Self::A => Some("A"),
+ Self::B => Some("B"),
+ Self::C => Some("C"),
+ _ => None,
+ }
+ }
+}
+impl std::fmt::Debug for EnumInNestedNS {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ if let Some(name) = self.variant_name() {
+ f.write_str(name)
+ } else {
+ f.write_fmt(format_args!("<UNKNOWN {:?}>", self.0))
+ }
+ }
+}
+impl<'a> flatbuffers::Follow<'a> for EnumInNestedNS {
+ type Inner = Self;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ let b = unsafe {
+ flatbuffers::read_scalar_at::<i8>(buf, loc)
+ };
+ Self(b)
+ }
+}
+
+impl flatbuffers::Push for EnumInNestedNS {
+ type Output = EnumInNestedNS;
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ unsafe { flatbuffers::emplace_scalar::<i8>(dst, self.0); }
+ }
+}
+
+impl flatbuffers::EndianScalar for EnumInNestedNS {
+ #[inline]
+ fn to_little_endian(self) -> Self {
+ let b = i8::to_le(self.0);
+ Self(b)
+ }
+ #[inline]
+ #[allow(clippy::wrong_self_convention)]
+ fn from_little_endian(self) -> Self {
+ let b = i8::from_le(self.0);
+ Self(b)
+ }
+}
+
+impl<'a> flatbuffers::Verifiable for EnumInNestedNS {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ i8::run_verifier(v, pos)
+ }
+}
+
+impl flatbuffers::SimpleToVerifyInSlice for EnumInNestedNS {}
diff --git a/tests/namespace_test/namespace_a/namespace_b/struct_in_nested_ns_generated.rs b/tests/namespace_test/namespace_a/namespace_b/struct_in_nested_ns_generated.rs
new file mode 100644
index 0000000..55fff40
--- /dev/null
+++ b/tests/namespace_test/namespace_a/namespace_b/struct_in_nested_ns_generated.rs
@@ -0,0 +1,156 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+// struct StructInNestedNS, aligned to 4
+#[repr(transparent)]
+#[derive(Clone, Copy, PartialEq)]
+pub struct StructInNestedNS(pub [u8; 8]);
+impl Default for StructInNestedNS {
+ fn default() -> Self {
+ Self([0; 8])
+ }
+}
+impl std::fmt::Debug for StructInNestedNS {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ f.debug_struct("StructInNestedNS")
+ .field("a", &self.a())
+ .field("b", &self.b())
+ .finish()
+ }
+}
+
+impl flatbuffers::SimpleToVerifyInSlice for StructInNestedNS {}
+impl flatbuffers::SafeSliceAccess for StructInNestedNS {}
+impl<'a> flatbuffers::Follow<'a> for StructInNestedNS {
+ type Inner = &'a StructInNestedNS;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ <&'a StructInNestedNS>::follow(buf, loc)
+ }
+}
+impl<'a> flatbuffers::Follow<'a> for &'a StructInNestedNS {
+ type Inner = &'a StructInNestedNS;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ flatbuffers::follow_cast_ref::<StructInNestedNS>(buf, loc)
+ }
+}
+impl<'b> flatbuffers::Push for StructInNestedNS {
+ type Output = StructInNestedNS;
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ let src = unsafe {
+ ::std::slice::from_raw_parts(self as *const StructInNestedNS as *const u8, Self::size())
+ };
+ dst.copy_from_slice(src);
+ }
+}
+impl<'b> flatbuffers::Push for &'b StructInNestedNS {
+ type Output = StructInNestedNS;
+
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ let src = unsafe {
+ ::std::slice::from_raw_parts(*self as *const StructInNestedNS as *const u8, Self::size())
+ };
+ dst.copy_from_slice(src);
+ }
+}
+
+impl<'a> flatbuffers::Verifiable for StructInNestedNS {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ v.in_buffer::<Self>(pos)
+ }
+}
+
+impl<'a> StructInNestedNS {
+ #[allow(clippy::too_many_arguments)]
+ pub fn new(
+ a: i32,
+ b: i32,
+ ) -> Self {
+ let mut s = Self([0; 8]);
+ s.set_a(a);
+ s.set_b(b);
+ s
+ }
+
+ pub const fn get_fully_qualified_name() -> &'static str {
+ "NamespaceA.NamespaceB.StructInNestedNS"
+ }
+
+ pub fn a(&self) -> i32 {
+ let mut mem = core::mem::MaybeUninit::<i32>::uninit();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ self.0[0..].as_ptr(),
+ mem.as_mut_ptr() as *mut u8,
+ core::mem::size_of::<i32>(),
+ );
+ mem.assume_init()
+ }.from_little_endian()
+ }
+
+ pub fn set_a(&mut self, x: i32) {
+ let x_le = x.to_little_endian();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ &x_le as *const i32 as *const u8,
+ self.0[0..].as_mut_ptr(),
+ core::mem::size_of::<i32>(),
+ );
+ }
+ }
+
+ pub fn b(&self) -> i32 {
+ let mut mem = core::mem::MaybeUninit::<i32>::uninit();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ self.0[4..].as_ptr(),
+ mem.as_mut_ptr() as *mut u8,
+ core::mem::size_of::<i32>(),
+ );
+ mem.assume_init()
+ }.from_little_endian()
+ }
+
+ pub fn set_b(&mut self, x: i32) {
+ let x_le = x.to_little_endian();
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ &x_le as *const i32 as *const u8,
+ self.0[4..].as_mut_ptr(),
+ core::mem::size_of::<i32>(),
+ );
+ }
+ }
+
+ pub fn unpack(&self) -> StructInNestedNST {
+ StructInNestedNST {
+ a: self.a(),
+ b: self.b(),
+ }
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Default)]
+pub struct StructInNestedNST {
+ pub a: i32,
+ pub b: i32,
+}
+impl StructInNestedNST {
+ pub fn pack(&self) -> StructInNestedNS {
+ StructInNestedNS::new(
+ self.a,
+ self.b,
+ )
+ }
+}
+
diff --git a/tests/namespace_test/namespace_a/namespace_b/table_in_nested_ns_generated.rs b/tests/namespace_test/namespace_a/namespace_b/table_in_nested_ns_generated.rs
new file mode 100644
index 0000000..10d5b7c
--- /dev/null
+++ b/tests/namespace_test/namespace_a/namespace_b/table_in_nested_ns_generated.rs
@@ -0,0 +1,133 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+pub enum TableInNestedNSOffset {}
+#[derive(Copy, Clone, PartialEq)]
+
+pub struct TableInNestedNS<'a> {
+ pub _tab: flatbuffers::Table<'a>,
+}
+
+impl<'a> flatbuffers::Follow<'a> for TableInNestedNS<'a> {
+ type Inner = TableInNestedNS<'a>;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ Self { _tab: flatbuffers::Table { buf, loc } }
+ }
+}
+
+impl<'a> TableInNestedNS<'a> {
+ pub const VT_FOO: flatbuffers::VOffsetT = 4;
+
+ pub const fn get_fully_qualified_name() -> &'static str {
+ "NamespaceA.NamespaceB.TableInNestedNS"
+ }
+
+ #[inline]
+ pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
+ TableInNestedNS { _tab: table }
+ }
+ #[allow(unused_mut)]
+ pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
+ _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
+ args: &'args TableInNestedNSArgs
+ ) -> flatbuffers::WIPOffset<TableInNestedNS<'bldr>> {
+ let mut builder = TableInNestedNSBuilder::new(_fbb);
+ builder.add_foo(args.foo);
+ builder.finish()
+ }
+
+ pub fn unpack(&self) -> TableInNestedNST {
+ let foo = self.foo();
+ TableInNestedNST {
+ foo,
+ }
+ }
+
+ #[inline]
+ pub fn foo(&self) -> i32 {
+ self._tab.get::<i32>(TableInNestedNS::VT_FOO, Some(0)).unwrap()
+ }
+}
+
+impl flatbuffers::Verifiable for TableInNestedNS<'_> {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ v.visit_table(pos)?
+ .visit_field::<i32>("foo", Self::VT_FOO, false)?
+ .finish();
+ Ok(())
+ }
+}
+pub struct TableInNestedNSArgs {
+ pub foo: i32,
+}
+impl<'a> Default for TableInNestedNSArgs {
+ #[inline]
+ fn default() -> Self {
+ TableInNestedNSArgs {
+ foo: 0,
+ }
+ }
+}
+
+pub struct TableInNestedNSBuilder<'a: 'b, 'b> {
+ fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
+ start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
+}
+impl<'a: 'b, 'b> TableInNestedNSBuilder<'a, 'b> {
+ #[inline]
+ pub fn add_foo(&mut self, foo: i32) {
+ self.fbb_.push_slot::<i32>(TableInNestedNS::VT_FOO, foo, 0);
+ }
+ #[inline]
+ pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> TableInNestedNSBuilder<'a, 'b> {
+ let start = _fbb.start_table();
+ TableInNestedNSBuilder {
+ fbb_: _fbb,
+ start_: start,
+ }
+ }
+ #[inline]
+ pub fn finish(self) -> flatbuffers::WIPOffset<TableInNestedNS<'a>> {
+ let o = self.fbb_.end_table(self.start_);
+ flatbuffers::WIPOffset::new(o.value())
+ }
+}
+
+impl std::fmt::Debug for TableInNestedNS<'_> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let mut ds = f.debug_struct("TableInNestedNS");
+ ds.field("foo", &self.foo());
+ ds.finish()
+ }
+}
+#[non_exhaustive]
+#[derive(Debug, Clone, PartialEq)]
+pub struct TableInNestedNST {
+ pub foo: i32,
+}
+impl Default for TableInNestedNST {
+ fn default() -> Self {
+ Self {
+ foo: 0,
+ }
+ }
+}
+impl TableInNestedNST {
+ pub fn pack<'b>(
+ &self,
+ _fbb: &mut flatbuffers::FlatBufferBuilder<'b>
+ ) -> flatbuffers::WIPOffset<TableInNestedNS<'b>> {
+ let foo = self.foo;
+ TableInNestedNS::create(_fbb, &TableInNestedNSArgs{
+ foo,
+ })
+ }
+}
diff --git a/tests/namespace_test/namespace_a/namespace_b/union_in_nested_ns_generated.rs b/tests/namespace_test/namespace_a/namespace_b/union_in_nested_ns_generated.rs
new file mode 100644
index 0000000..8d650a5
--- /dev/null
+++ b/tests/namespace_test/namespace_a/namespace_b/union_in_nested_ns_generated.rs
@@ -0,0 +1,142 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+pub const ENUM_MIN_UNION_IN_NESTED_NS: u8 = 0;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+pub const ENUM_MAX_UNION_IN_NESTED_NS: u8 = 1;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+#[allow(non_camel_case_types)]
+pub const ENUM_VALUES_UNION_IN_NESTED_NS: [UnionInNestedNS; 2] = [
+ UnionInNestedNS::NONE,
+ UnionInNestedNS::TableInNestedNS,
+];
+
+#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
+#[repr(transparent)]
+pub struct UnionInNestedNS(pub u8);
+#[allow(non_upper_case_globals)]
+impl UnionInNestedNS {
+ pub const NONE: Self = Self(0);
+ pub const TableInNestedNS: Self = Self(1);
+
+ pub const ENUM_MIN: u8 = 0;
+ pub const ENUM_MAX: u8 = 1;
+ pub const ENUM_VALUES: &'static [Self] = &[
+ Self::NONE,
+ Self::TableInNestedNS,
+ ];
+ /// Returns the variant's name or "" if unknown.
+ pub fn variant_name(self) -> Option<&'static str> {
+ match self {
+ Self::NONE => Some("NONE"),
+ Self::TableInNestedNS => Some("TableInNestedNS"),
+ _ => None,
+ }
+ }
+}
+impl std::fmt::Debug for UnionInNestedNS {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ if let Some(name) = self.variant_name() {
+ f.write_str(name)
+ } else {
+ f.write_fmt(format_args!("<UNKNOWN {:?}>", self.0))
+ }
+ }
+}
+impl<'a> flatbuffers::Follow<'a> for UnionInNestedNS {
+ type Inner = Self;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ let b = unsafe {
+ flatbuffers::read_scalar_at::<u8>(buf, loc)
+ };
+ Self(b)
+ }
+}
+
+impl flatbuffers::Push for UnionInNestedNS {
+ type Output = UnionInNestedNS;
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ unsafe { flatbuffers::emplace_scalar::<u8>(dst, self.0); }
+ }
+}
+
+impl flatbuffers::EndianScalar for UnionInNestedNS {
+ #[inline]
+ fn to_little_endian(self) -> Self {
+ let b = u8::to_le(self.0);
+ Self(b)
+ }
+ #[inline]
+ #[allow(clippy::wrong_self_convention)]
+ fn from_little_endian(self) -> Self {
+ let b = u8::from_le(self.0);
+ Self(b)
+ }
+}
+
+impl<'a> flatbuffers::Verifiable for UnionInNestedNS {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ u8::run_verifier(v, pos)
+ }
+}
+
+impl flatbuffers::SimpleToVerifyInSlice for UnionInNestedNS {}
+pub struct UnionInNestedNSUnionTableOffset {}
+
+#[allow(clippy::upper_case_acronyms)]
+#[non_exhaustive]
+#[derive(Debug, Clone, PartialEq)]
+pub enum UnionInNestedNST {
+ NONE,
+ TableInNestedNS(Box<TableInNestedNST>),
+}
+impl Default for UnionInNestedNST {
+ fn default() -> Self {
+ Self::NONE
+ }
+}
+impl UnionInNestedNST {
+ pub fn union_in_nested_ns_type(&self) -> UnionInNestedNS {
+ match self {
+ Self::NONE => UnionInNestedNS::NONE,
+ Self::TableInNestedNS(_) => UnionInNestedNS::TableInNestedNS,
+ }
+ }
+ pub fn pack(&self, fbb: &mut flatbuffers::FlatBufferBuilder) -> Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>> {
+ match self {
+ Self::NONE => None,
+ Self::TableInNestedNS(v) => Some(v.pack(fbb).as_union_value()),
+ }
+ }
+ /// If the union variant matches, return the owned TableInNestedNST, setting the union to NONE.
+ pub fn take_table_in_nested_ns(&mut self) -> Option<Box<TableInNestedNST>> {
+ if let Self::TableInNestedNS(_) = self {
+ let v = std::mem::replace(self, Self::NONE);
+ if let Self::TableInNestedNS(w) = v {
+ Some(w)
+ } else {
+ unreachable!()
+ }
+ } else {
+ None
+ }
+ }
+ /// If the union variant matches, return a reference to the TableInNestedNST.
+ pub fn as_table_in_nested_ns(&self) -> Option<&TableInNestedNST> {
+ if let Self::TableInNestedNS(v) = self { Some(v.as_ref()) } else { None }
+ }
+ /// If the union variant matches, return a mutable reference to the TableInNestedNST.
+ pub fn as_table_in_nested_ns_mut(&mut self) -> Option<&mut TableInNestedNST> {
+ if let Self::TableInNestedNS(v) = self { Some(v.as_mut()) } else { None }
+ }
+}
diff --git a/tests/namespace_test/namespace_a/second_table_in_a_generated.rs b/tests/namespace_test/namespace_a/second_table_in_a_generated.rs
new file mode 100644
index 0000000..d63438b
--- /dev/null
+++ b/tests/namespace_test/namespace_a/second_table_in_a_generated.rs
@@ -0,0 +1,137 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+pub enum SecondTableInAOffset {}
+#[derive(Copy, Clone, PartialEq)]
+
+pub struct SecondTableInA<'a> {
+ pub _tab: flatbuffers::Table<'a>,
+}
+
+impl<'a> flatbuffers::Follow<'a> for SecondTableInA<'a> {
+ type Inner = SecondTableInA<'a>;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ Self { _tab: flatbuffers::Table { buf, loc } }
+ }
+}
+
+impl<'a> SecondTableInA<'a> {
+ pub const VT_REFER_TO_C: flatbuffers::VOffsetT = 4;
+
+ pub const fn get_fully_qualified_name() -> &'static str {
+ "NamespaceA.SecondTableInA"
+ }
+
+ #[inline]
+ pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
+ SecondTableInA { _tab: table }
+ }
+ #[allow(unused_mut)]
+ pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
+ _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
+ args: &'args SecondTableInAArgs<'args>
+ ) -> flatbuffers::WIPOffset<SecondTableInA<'bldr>> {
+ let mut builder = SecondTableInABuilder::new(_fbb);
+ if let Some(x) = args.refer_to_c { builder.add_refer_to_c(x); }
+ builder.finish()
+ }
+
+ pub fn unpack(&self) -> SecondTableInAT {
+ let refer_to_c = self.refer_to_c().map(|x| {
+ Box::new(x.unpack())
+ });
+ SecondTableInAT {
+ refer_to_c,
+ }
+ }
+
+ #[inline]
+ pub fn refer_to_c(&self) -> Option<super::namespace_c::TableInC<'a>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<super::namespace_c::TableInC>>(SecondTableInA::VT_REFER_TO_C, None)
+ }
+}
+
+impl flatbuffers::Verifiable for SecondTableInA<'_> {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ v.visit_table(pos)?
+ .visit_field::<flatbuffers::ForwardsUOffset<super::namespace_c::TableInC>>("refer_to_c", Self::VT_REFER_TO_C, false)?
+ .finish();
+ Ok(())
+ }
+}
+pub struct SecondTableInAArgs<'a> {
+ pub refer_to_c: Option<flatbuffers::WIPOffset<super::namespace_c::TableInC<'a>>>,
+}
+impl<'a> Default for SecondTableInAArgs<'a> {
+ #[inline]
+ fn default() -> Self {
+ SecondTableInAArgs {
+ refer_to_c: None,
+ }
+ }
+}
+
+pub struct SecondTableInABuilder<'a: 'b, 'b> {
+ fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
+ start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
+}
+impl<'a: 'b, 'b> SecondTableInABuilder<'a, 'b> {
+ #[inline]
+ pub fn add_refer_to_c(&mut self, refer_to_c: flatbuffers::WIPOffset<super::namespace_c::TableInC<'b >>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<super::namespace_c::TableInC>>(SecondTableInA::VT_REFER_TO_C, refer_to_c);
+ }
+ #[inline]
+ pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> SecondTableInABuilder<'a, 'b> {
+ let start = _fbb.start_table();
+ SecondTableInABuilder {
+ fbb_: _fbb,
+ start_: start,
+ }
+ }
+ #[inline]
+ pub fn finish(self) -> flatbuffers::WIPOffset<SecondTableInA<'a>> {
+ let o = self.fbb_.end_table(self.start_);
+ flatbuffers::WIPOffset::new(o.value())
+ }
+}
+
+impl std::fmt::Debug for SecondTableInA<'_> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let mut ds = f.debug_struct("SecondTableInA");
+ ds.field("refer_to_c", &self.refer_to_c());
+ ds.finish()
+ }
+}
+#[non_exhaustive]
+#[derive(Debug, Clone, PartialEq)]
+pub struct SecondTableInAT {
+ pub refer_to_c: Option<Box<super::namespace_c::TableInCT>>,
+}
+impl Default for SecondTableInAT {
+ fn default() -> Self {
+ Self {
+ refer_to_c: None,
+ }
+ }
+}
+impl SecondTableInAT {
+ pub fn pack<'b>(
+ &self,
+ _fbb: &mut flatbuffers::FlatBufferBuilder<'b>
+ ) -> flatbuffers::WIPOffset<SecondTableInA<'b>> {
+ let refer_to_c = self.refer_to_c.as_ref().map(|x|{
+ x.pack(_fbb)
+ });
+ SecondTableInA::create(_fbb, &SecondTableInAArgs{
+ refer_to_c,
+ })
+ }
+}
diff --git a/tests/namespace_test/namespace_a/table_in_first_ns_generated.rs b/tests/namespace_test/namespace_a/table_in_first_ns_generated.rs
new file mode 100644
index 0000000..0a16074
--- /dev/null
+++ b/tests/namespace_test/namespace_a/table_in_first_ns_generated.rs
@@ -0,0 +1,250 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+pub enum TableInFirstNSOffset {}
+#[derive(Copy, Clone, PartialEq)]
+
+pub struct TableInFirstNS<'a> {
+ pub _tab: flatbuffers::Table<'a>,
+}
+
+impl<'a> flatbuffers::Follow<'a> for TableInFirstNS<'a> {
+ type Inner = TableInFirstNS<'a>;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ Self { _tab: flatbuffers::Table { buf, loc } }
+ }
+}
+
+impl<'a> TableInFirstNS<'a> {
+ pub const VT_FOO_TABLE: flatbuffers::VOffsetT = 4;
+ pub const VT_FOO_ENUM: flatbuffers::VOffsetT = 6;
+ pub const VT_FOO_UNION_TYPE: flatbuffers::VOffsetT = 8;
+ pub const VT_FOO_UNION: flatbuffers::VOffsetT = 10;
+ pub const VT_FOO_STRUCT: flatbuffers::VOffsetT = 12;
+
+ pub const fn get_fully_qualified_name() -> &'static str {
+ "NamespaceA.TableInFirstNS"
+ }
+
+ #[inline]
+ pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
+ TableInFirstNS { _tab: table }
+ }
+ #[allow(unused_mut)]
+ pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
+ _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
+ args: &'args TableInFirstNSArgs<'args>
+ ) -> flatbuffers::WIPOffset<TableInFirstNS<'bldr>> {
+ let mut builder = TableInFirstNSBuilder::new(_fbb);
+ if let Some(x) = args.foo_struct { builder.add_foo_struct(x); }
+ if let Some(x) = args.foo_union { builder.add_foo_union(x); }
+ if let Some(x) = args.foo_table { builder.add_foo_table(x); }
+ builder.add_foo_union_type(args.foo_union_type);
+ builder.add_foo_enum(args.foo_enum);
+ builder.finish()
+ }
+
+ pub fn unpack(&self) -> TableInFirstNST {
+ let foo_table = self.foo_table().map(|x| {
+ Box::new(x.unpack())
+ });
+ let foo_enum = self.foo_enum();
+ let foo_union = match self.foo_union_type() {
+ namespace_b::UnionInNestedNS::NONE => namespace_b::UnionInNestedNST::NONE,
+ namespace_b::UnionInNestedNS::TableInNestedNS => namespace_b::UnionInNestedNST::TableInNestedNS(Box::new(
+ self.foo_union_as_table_in_nested_ns()
+ .expect("Invalid union table, expected `namespace_b::UnionInNestedNS::TableInNestedNS`.")
+ .unpack()
+ )),
+ _ => namespace_b::UnionInNestedNST::NONE,
+ };
+ let foo_struct = self.foo_struct().map(|x| {
+ x.unpack()
+ });
+ TableInFirstNST {
+ foo_table,
+ foo_enum,
+ foo_union,
+ foo_struct,
+ }
+ }
+
+ #[inline]
+ pub fn foo_table(&self) -> Option<namespace_b::TableInNestedNS<'a>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<namespace_b::TableInNestedNS>>(TableInFirstNS::VT_FOO_TABLE, None)
+ }
+ #[inline]
+ pub fn foo_enum(&self) -> namespace_b::EnumInNestedNS {
+ self._tab.get::<namespace_b::EnumInNestedNS>(TableInFirstNS::VT_FOO_ENUM, Some(namespace_b::EnumInNestedNS::A)).unwrap()
+ }
+ #[inline]
+ pub fn foo_union_type(&self) -> namespace_b::UnionInNestedNS {
+ self._tab.get::<namespace_b::UnionInNestedNS>(TableInFirstNS::VT_FOO_UNION_TYPE, Some(namespace_b::UnionInNestedNS::NONE)).unwrap()
+ }
+ #[inline]
+ pub fn foo_union(&self) -> Option<flatbuffers::Table<'a>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Table<'a>>>(TableInFirstNS::VT_FOO_UNION, None)
+ }
+ #[inline]
+ pub fn foo_struct(&self) -> Option<&'a namespace_b::StructInNestedNS> {
+ self._tab.get::<namespace_b::StructInNestedNS>(TableInFirstNS::VT_FOO_STRUCT, None)
+ }
+ #[inline]
+ #[allow(non_snake_case)]
+ pub fn foo_union_as_table_in_nested_ns(&self) -> Option<namespace_b::TableInNestedNS<'a>> {
+ if self.foo_union_type() == namespace_b::UnionInNestedNS::TableInNestedNS {
+ self.foo_union().map(namespace_b::TableInNestedNS::init_from_table)
+ } else {
+ None
+ }
+ }
+
+}
+
+impl flatbuffers::Verifiable for TableInFirstNS<'_> {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ v.visit_table(pos)?
+ .visit_field::<flatbuffers::ForwardsUOffset<namespace_b::TableInNestedNS>>("foo_table", Self::VT_FOO_TABLE, false)?
+ .visit_field::<namespace_b::EnumInNestedNS>("foo_enum", Self::VT_FOO_ENUM, false)?
+ .visit_union::<namespace_b::UnionInNestedNS, _>("foo_union_type", Self::VT_FOO_UNION_TYPE, "foo_union", Self::VT_FOO_UNION, false, |key, v, pos| {
+ match key {
+ namespace_b::UnionInNestedNS::TableInNestedNS => v.verify_union_variant::<flatbuffers::ForwardsUOffset<namespace_b::TableInNestedNS>>("namespace_b::UnionInNestedNS::TableInNestedNS", pos),
+ _ => Ok(()),
+ }
+ })?
+ .visit_field::<namespace_b::StructInNestedNS>("foo_struct", Self::VT_FOO_STRUCT, false)?
+ .finish();
+ Ok(())
+ }
+}
+pub struct TableInFirstNSArgs<'a> {
+ pub foo_table: Option<flatbuffers::WIPOffset<namespace_b::TableInNestedNS<'a>>>,
+ pub foo_enum: namespace_b::EnumInNestedNS,
+ pub foo_union_type: namespace_b::UnionInNestedNS,
+ pub foo_union: Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>,
+ pub foo_struct: Option<&'a namespace_b::StructInNestedNS>,
+}
+impl<'a> Default for TableInFirstNSArgs<'a> {
+ #[inline]
+ fn default() -> Self {
+ TableInFirstNSArgs {
+ foo_table: None,
+ foo_enum: namespace_b::EnumInNestedNS::A,
+ foo_union_type: namespace_b::UnionInNestedNS::NONE,
+ foo_union: None,
+ foo_struct: None,
+ }
+ }
+}
+
+pub struct TableInFirstNSBuilder<'a: 'b, 'b> {
+ fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
+ start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
+}
+impl<'a: 'b, 'b> TableInFirstNSBuilder<'a, 'b> {
+ #[inline]
+ pub fn add_foo_table(&mut self, foo_table: flatbuffers::WIPOffset<namespace_b::TableInNestedNS<'b >>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<namespace_b::TableInNestedNS>>(TableInFirstNS::VT_FOO_TABLE, foo_table);
+ }
+ #[inline]
+ pub fn add_foo_enum(&mut self, foo_enum: namespace_b::EnumInNestedNS) {
+ self.fbb_.push_slot::<namespace_b::EnumInNestedNS>(TableInFirstNS::VT_FOO_ENUM, foo_enum, namespace_b::EnumInNestedNS::A);
+ }
+ #[inline]
+ pub fn add_foo_union_type(&mut self, foo_union_type: namespace_b::UnionInNestedNS) {
+ self.fbb_.push_slot::<namespace_b::UnionInNestedNS>(TableInFirstNS::VT_FOO_UNION_TYPE, foo_union_type, namespace_b::UnionInNestedNS::NONE);
+ }
+ #[inline]
+ pub fn add_foo_union(&mut self, foo_union: flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(TableInFirstNS::VT_FOO_UNION, foo_union);
+ }
+ #[inline]
+ pub fn add_foo_struct(&mut self, foo_struct: &namespace_b::StructInNestedNS) {
+ self.fbb_.push_slot_always::<&namespace_b::StructInNestedNS>(TableInFirstNS::VT_FOO_STRUCT, foo_struct);
+ }
+ #[inline]
+ pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> TableInFirstNSBuilder<'a, 'b> {
+ let start = _fbb.start_table();
+ TableInFirstNSBuilder {
+ fbb_: _fbb,
+ start_: start,
+ }
+ }
+ #[inline]
+ pub fn finish(self) -> flatbuffers::WIPOffset<TableInFirstNS<'a>> {
+ let o = self.fbb_.end_table(self.start_);
+ flatbuffers::WIPOffset::new(o.value())
+ }
+}
+
+impl std::fmt::Debug for TableInFirstNS<'_> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let mut ds = f.debug_struct("TableInFirstNS");
+ ds.field("foo_table", &self.foo_table());
+ ds.field("foo_enum", &self.foo_enum());
+ ds.field("foo_union_type", &self.foo_union_type());
+ match self.foo_union_type() {
+ namespace_b::UnionInNestedNS::TableInNestedNS => {
+ if let Some(x) = self.foo_union_as_table_in_nested_ns() {
+ ds.field("foo_union", &x)
+ } else {
+ ds.field("foo_union", &"InvalidFlatbuffer: Union discriminant does not match value.")
+ }
+ },
+ _ => {
+ let x: Option<()> = None;
+ ds.field("foo_union", &x)
+ },
+ };
+ ds.field("foo_struct", &self.foo_struct());
+ ds.finish()
+ }
+}
+#[non_exhaustive]
+#[derive(Debug, Clone, PartialEq)]
+pub struct TableInFirstNST {
+ pub foo_table: Option<Box<namespace_b::TableInNestedNST>>,
+ pub foo_enum: namespace_b::EnumInNestedNS,
+ pub foo_union: namespace_b::UnionInNestedNST,
+ pub foo_struct: Option<namespace_b::StructInNestedNST>,
+}
+impl Default for TableInFirstNST {
+ fn default() -> Self {
+ Self {
+ foo_table: None,
+ foo_enum: namespace_b::EnumInNestedNS::A,
+ foo_union: namespace_b::UnionInNestedNST::NONE,
+ foo_struct: None,
+ }
+ }
+}
+impl TableInFirstNST {
+ pub fn pack<'b>(
+ &self,
+ _fbb: &mut flatbuffers::FlatBufferBuilder<'b>
+ ) -> flatbuffers::WIPOffset<TableInFirstNS<'b>> {
+ let foo_table = self.foo_table.as_ref().map(|x|{
+ x.pack(_fbb)
+ });
+ let foo_enum = self.foo_enum;
+ let foo_union_type = self.foo_union.union_in_nested_ns_type();
+ let foo_union = self.foo_union.pack(_fbb);
+ let foo_struct_tmp = self.foo_struct.as_ref().map(|x| x.pack());
+ let foo_struct = foo_struct_tmp.as_ref();
+ TableInFirstNS::create(_fbb, &TableInFirstNSArgs{
+ foo_table,
+ foo_enum,
+ foo_union_type,
+ foo_union,
+ foo_struct,
+ })
+ }
+}
diff --git a/tests/namespace_test/namespace_c/table_in_c_generated.rs b/tests/namespace_test/namespace_c/table_in_c_generated.rs
new file mode 100644
index 0000000..d4ac783
--- /dev/null
+++ b/tests/namespace_test/namespace_c/table_in_c_generated.rs
@@ -0,0 +1,161 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+pub enum TableInCOffset {}
+#[derive(Copy, Clone, PartialEq)]
+
+pub struct TableInC<'a> {
+ pub _tab: flatbuffers::Table<'a>,
+}
+
+impl<'a> flatbuffers::Follow<'a> for TableInC<'a> {
+ type Inner = TableInC<'a>;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ Self { _tab: flatbuffers::Table { buf, loc } }
+ }
+}
+
+impl<'a> TableInC<'a> {
+ pub const VT_REFER_TO_A1: flatbuffers::VOffsetT = 4;
+ pub const VT_REFER_TO_A2: flatbuffers::VOffsetT = 6;
+
+ pub const fn get_fully_qualified_name() -> &'static str {
+ "NamespaceC.TableInC"
+ }
+
+ #[inline]
+ pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
+ TableInC { _tab: table }
+ }
+ #[allow(unused_mut)]
+ pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
+ _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
+ args: &'args TableInCArgs<'args>
+ ) -> flatbuffers::WIPOffset<TableInC<'bldr>> {
+ let mut builder = TableInCBuilder::new(_fbb);
+ if let Some(x) = args.refer_to_a2 { builder.add_refer_to_a2(x); }
+ if let Some(x) = args.refer_to_a1 { builder.add_refer_to_a1(x); }
+ builder.finish()
+ }
+
+ pub fn unpack(&self) -> TableInCT {
+ let refer_to_a1 = self.refer_to_a1().map(|x| {
+ Box::new(x.unpack())
+ });
+ let refer_to_a2 = self.refer_to_a2().map(|x| {
+ Box::new(x.unpack())
+ });
+ TableInCT {
+ refer_to_a1,
+ refer_to_a2,
+ }
+ }
+
+ #[inline]
+ pub fn refer_to_a1(&self) -> Option<super::namespace_a::TableInFirstNS<'a>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<super::namespace_a::TableInFirstNS>>(TableInC::VT_REFER_TO_A1, None)
+ }
+ #[inline]
+ pub fn refer_to_a2(&self) -> Option<super::namespace_a::SecondTableInA<'a>> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<super::namespace_a::SecondTableInA>>(TableInC::VT_REFER_TO_A2, None)
+ }
+}
+
+impl flatbuffers::Verifiable for TableInC<'_> {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ v.visit_table(pos)?
+ .visit_field::<flatbuffers::ForwardsUOffset<super::namespace_a::TableInFirstNS>>("refer_to_a1", Self::VT_REFER_TO_A1, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<super::namespace_a::SecondTableInA>>("refer_to_a2", Self::VT_REFER_TO_A2, false)?
+ .finish();
+ Ok(())
+ }
+}
+pub struct TableInCArgs<'a> {
+ pub refer_to_a1: Option<flatbuffers::WIPOffset<super::namespace_a::TableInFirstNS<'a>>>,
+ pub refer_to_a2: Option<flatbuffers::WIPOffset<super::namespace_a::SecondTableInA<'a>>>,
+}
+impl<'a> Default for TableInCArgs<'a> {
+ #[inline]
+ fn default() -> Self {
+ TableInCArgs {
+ refer_to_a1: None,
+ refer_to_a2: None,
+ }
+ }
+}
+
+pub struct TableInCBuilder<'a: 'b, 'b> {
+ fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
+ start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
+}
+impl<'a: 'b, 'b> TableInCBuilder<'a, 'b> {
+ #[inline]
+ pub fn add_refer_to_a1(&mut self, refer_to_a1: flatbuffers::WIPOffset<super::namespace_a::TableInFirstNS<'b >>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<super::namespace_a::TableInFirstNS>>(TableInC::VT_REFER_TO_A1, refer_to_a1);
+ }
+ #[inline]
+ pub fn add_refer_to_a2(&mut self, refer_to_a2: flatbuffers::WIPOffset<super::namespace_a::SecondTableInA<'b >>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<super::namespace_a::SecondTableInA>>(TableInC::VT_REFER_TO_A2, refer_to_a2);
+ }
+ #[inline]
+ pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> TableInCBuilder<'a, 'b> {
+ let start = _fbb.start_table();
+ TableInCBuilder {
+ fbb_: _fbb,
+ start_: start,
+ }
+ }
+ #[inline]
+ pub fn finish(self) -> flatbuffers::WIPOffset<TableInC<'a>> {
+ let o = self.fbb_.end_table(self.start_);
+ flatbuffers::WIPOffset::new(o.value())
+ }
+}
+
+impl std::fmt::Debug for TableInC<'_> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let mut ds = f.debug_struct("TableInC");
+ ds.field("refer_to_a1", &self.refer_to_a1());
+ ds.field("refer_to_a2", &self.refer_to_a2());
+ ds.finish()
+ }
+}
+#[non_exhaustive]
+#[derive(Debug, Clone, PartialEq)]
+pub struct TableInCT {
+ pub refer_to_a1: Option<Box<super::namespace_a::TableInFirstNST>>,
+ pub refer_to_a2: Option<Box<super::namespace_a::SecondTableInAT>>,
+}
+impl Default for TableInCT {
+ fn default() -> Self {
+ Self {
+ refer_to_a1: None,
+ refer_to_a2: None,
+ }
+ }
+}
+impl TableInCT {
+ pub fn pack<'b>(
+ &self,
+ _fbb: &mut flatbuffers::FlatBufferBuilder<'b>
+ ) -> flatbuffers::WIPOffset<TableInC<'b>> {
+ let refer_to_a1 = self.refer_to_a1.as_ref().map(|x|{
+ x.pack(_fbb)
+ });
+ let refer_to_a2 = self.refer_to_a2.as_ref().map(|x|{
+ x.pack(_fbb)
+ });
+ TableInC::create(_fbb, &TableInCArgs{
+ refer_to_a1,
+ refer_to_a2,
+ })
+ }
+}
diff --git a/tests/namespace_test/namespace_test1.fbs b/tests/namespace_test/namespace_test1.fbs
index 49449bf..f0b9c16 100644
--- a/tests/namespace_test/namespace_test1.fbs
+++ b/tests/namespace_test/namespace_test1.fbs
@@ -5,6 +5,10 @@
foo:int;
}
+union UnionInNestedNS {
+ TableInNestedNS,
+}
+
enum EnumInNestedNS:byte
{
A, B, C
diff --git a/tests/namespace_test/namespace_test1.ts b/tests/namespace_test/namespace_test1.ts
new file mode 100644
index 0000000..9d8cf33
--- /dev/null
+++ b/tests/namespace_test/namespace_test1.ts
@@ -0,0 +1,3 @@
+export { StructInNestedNS, StructInNestedNST } from './namespace-a/namespace-b/struct-in-nested-n-s';
+export { TableInNestedNS, TableInNestedNST } from './namespace-a/namespace-b/table-in-nested-n-s';
+export { UnionInNestedNS, unionToUnionInNestedNS, unionListToUnionInNestedNS } from './namespace-a/namespace-b/union-in-nested-n-s';
diff --git a/tests/namespace_test/namespace_test1_generated.h b/tests/namespace_test/namespace_test1_generated.h
index 5ec21f8..bb82236 100644
--- a/tests/namespace_test/namespace_test1_generated.h
+++ b/tests/namespace_test/namespace_test1_generated.h
@@ -24,7 +24,117 @@
inline const flatbuffers::TypeTable *StructInNestedNSTypeTable();
-enum EnumInNestedNS {
+enum UnionInNestedNS : uint8_t {
+ UnionInNestedNS_NONE = 0,
+ UnionInNestedNS_TableInNestedNS = 1,
+ UnionInNestedNS_MIN = UnionInNestedNS_NONE,
+ UnionInNestedNS_MAX = UnionInNestedNS_TableInNestedNS
+};
+
+inline const UnionInNestedNS (&EnumValuesUnionInNestedNS())[2] {
+ static const UnionInNestedNS values[] = {
+ UnionInNestedNS_NONE,
+ UnionInNestedNS_TableInNestedNS
+ };
+ return values;
+}
+
+inline const char * const *EnumNamesUnionInNestedNS() {
+ static const char * const names[3] = {
+ "NONE",
+ "TableInNestedNS",
+ nullptr
+ };
+ return names;
+}
+
+inline const char *EnumNameUnionInNestedNS(UnionInNestedNS e) {
+ if (flatbuffers::IsOutRange(e, UnionInNestedNS_NONE, UnionInNestedNS_TableInNestedNS)) return "";
+ const size_t index = static_cast<size_t>(e);
+ return EnumNamesUnionInNestedNS()[index];
+}
+
+template<typename T> struct UnionInNestedNSTraits {
+ static const UnionInNestedNS enum_value = UnionInNestedNS_NONE;
+};
+
+template<> struct UnionInNestedNSTraits<NamespaceA::NamespaceB::TableInNestedNS> {
+ static const UnionInNestedNS enum_value = UnionInNestedNS_TableInNestedNS;
+};
+
+template<typename T> struct UnionInNestedNSUnionTraits {
+ static const UnionInNestedNS enum_value = UnionInNestedNS_NONE;
+};
+
+template<> struct UnionInNestedNSUnionTraits<NamespaceA::NamespaceB::TableInNestedNST> {
+ static const UnionInNestedNS enum_value = UnionInNestedNS_TableInNestedNS;
+};
+
+struct UnionInNestedNSUnion {
+ UnionInNestedNS type;
+ void *value;
+
+ UnionInNestedNSUnion() : type(UnionInNestedNS_NONE), value(nullptr) {}
+ UnionInNestedNSUnion(UnionInNestedNSUnion&& u) FLATBUFFERS_NOEXCEPT :
+ type(UnionInNestedNS_NONE), value(nullptr)
+ { std::swap(type, u.type); std::swap(value, u.value); }
+ UnionInNestedNSUnion(const UnionInNestedNSUnion &);
+ UnionInNestedNSUnion &operator=(const UnionInNestedNSUnion &u)
+ { UnionInNestedNSUnion t(u); std::swap(type, t.type); std::swap(value, t.value); return *this; }
+ UnionInNestedNSUnion &operator=(UnionInNestedNSUnion &&u) FLATBUFFERS_NOEXCEPT
+ { std::swap(type, u.type); std::swap(value, u.value); return *this; }
+ ~UnionInNestedNSUnion() { Reset(); }
+
+ void Reset();
+
+ template <typename T>
+ void Set(T&& val) {
+ typedef typename std::remove_reference<T>::type RT;
+ Reset();
+ type = UnionInNestedNSUnionTraits<RT>::enum_value;
+ if (type != UnionInNestedNS_NONE) {
+ value = new RT(std::forward<T>(val));
+ }
+ }
+
+ static void *UnPack(const void *obj, UnionInNestedNS type, const flatbuffers::resolver_function_t *resolver);
+ flatbuffers::Offset<void> Pack(flatbuffers::FlatBufferBuilder &_fbb, const flatbuffers::rehasher_function_t *_rehasher = nullptr) const;
+
+ NamespaceA::NamespaceB::TableInNestedNST *AsTableInNestedNS() {
+ return type == UnionInNestedNS_TableInNestedNS ?
+ reinterpret_cast<NamespaceA::NamespaceB::TableInNestedNST *>(value) : nullptr;
+ }
+ const NamespaceA::NamespaceB::TableInNestedNST *AsTableInNestedNS() const {
+ return type == UnionInNestedNS_TableInNestedNS ?
+ reinterpret_cast<const NamespaceA::NamespaceB::TableInNestedNST *>(value) : nullptr;
+ }
+};
+
+
+inline bool operator==(const UnionInNestedNSUnion &lhs, const UnionInNestedNSUnion &rhs) {
+ if (lhs.type != rhs.type) return false;
+ switch (lhs.type) {
+ case UnionInNestedNS_NONE: {
+ return true;
+ }
+ case UnionInNestedNS_TableInNestedNS: {
+ return *(reinterpret_cast<const NamespaceA::NamespaceB::TableInNestedNST *>(lhs.value)) ==
+ *(reinterpret_cast<const NamespaceA::NamespaceB::TableInNestedNST *>(rhs.value));
+ }
+ default: {
+ return false;
+ }
+ }
+}
+
+inline bool operator!=(const UnionInNestedNSUnion &lhs, const UnionInNestedNSUnion &rhs) {
+ return !(lhs == rhs);
+}
+
+bool VerifyUnionInNestedNS(flatbuffers::Verifier &verifier, const void *obj, UnionInNestedNS type);
+bool VerifyUnionInNestedNSVector(flatbuffers::Verifier &verifier, const flatbuffers::Vector<flatbuffers::Offset<void>> *values, const flatbuffers::Vector<uint8_t> *types);
+
+enum EnumInNestedNS : int8_t {
EnumInNestedNS_A = 0,
EnumInNestedNS_B = 1,
EnumInNestedNS_C = 2,
@@ -66,7 +176,7 @@
static const flatbuffers::TypeTable *MiniReflectTypeTable() {
return StructInNestedNSTypeTable();
}
- static FLATBUFFERS_CONSTEXPR const char *GetFullyQualifiedName() {
+ static FLATBUFFERS_CONSTEXPR_CPP11 const char *GetFullyQualifiedName() {
return "NamespaceA.NamespaceB.StructInNestedNS";
}
StructInNestedNS()
@@ -105,32 +215,19 @@
struct TableInNestedNST : public flatbuffers::NativeTable {
typedef TableInNestedNS TableType;
- static FLATBUFFERS_CONSTEXPR const char *GetFullyQualifiedName() {
+ static FLATBUFFERS_CONSTEXPR_CPP11 const char *GetFullyQualifiedName() {
return "NamespaceA.NamespaceB.TableInNestedNST";
}
- int32_t foo;
- TableInNestedNST()
- : foo(0) {
- }
+ int32_t foo = 0;
};
-inline bool operator==(const TableInNestedNST &lhs, const TableInNestedNST &rhs) {
- return
- (lhs.foo == rhs.foo);
-}
-
-inline bool operator!=(const TableInNestedNST &lhs, const TableInNestedNST &rhs) {
- return !(lhs == rhs);
-}
-
-
struct TableInNestedNS FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
typedef TableInNestedNST NativeTableType;
typedef TableInNestedNSBuilder Builder;
static const flatbuffers::TypeTable *MiniReflectTypeTable() {
return TableInNestedNSTypeTable();
}
- static FLATBUFFERS_CONSTEXPR const char *GetFullyQualifiedName() {
+ static FLATBUFFERS_CONSTEXPR_CPP11 const char *GetFullyQualifiedName() {
return "NamespaceA.NamespaceB.TableInNestedNS";
}
enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE {
@@ -139,12 +236,12 @@
int32_t foo() const {
return GetField<int32_t>(VT_FOO, 0);
}
- bool mutate_foo(int32_t _foo) {
+ bool mutate_foo(int32_t _foo = 0) {
return SetField<int32_t>(VT_FOO, _foo, 0);
}
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
- VerifyField<int32_t>(verifier, VT_FOO) &&
+ VerifyField<int32_t>(verifier, VT_FOO, 4) &&
verifier.EndTable();
}
TableInNestedNST *UnPack(const flatbuffers::resolver_function_t *_resolver = nullptr) const;
@@ -180,8 +277,19 @@
flatbuffers::Offset<TableInNestedNS> CreateTableInNestedNS(flatbuffers::FlatBufferBuilder &_fbb, const TableInNestedNST *_o, const flatbuffers::rehasher_function_t *_rehasher = nullptr);
+
+inline bool operator==(const TableInNestedNST &lhs, const TableInNestedNST &rhs) {
+ return
+ (lhs.foo == rhs.foo);
+}
+
+inline bool operator!=(const TableInNestedNST &lhs, const TableInNestedNST &rhs) {
+ return !(lhs == rhs);
+}
+
+
inline TableInNestedNST *TableInNestedNS::UnPack(const flatbuffers::resolver_function_t *_resolver) const {
- flatbuffers::unique_ptr<NamespaceA::NamespaceB::TableInNestedNST> _o = flatbuffers::unique_ptr<NamespaceA::NamespaceB::TableInNestedNST>(new TableInNestedNST());
+ auto _o = std::unique_ptr<TableInNestedNST>(new TableInNestedNST());
UnPackTo(_o.get(), _resolver);
return _o.release();
}
@@ -206,6 +314,95 @@
_foo);
}
+inline bool VerifyUnionInNestedNS(flatbuffers::Verifier &verifier, const void *obj, UnionInNestedNS type) {
+ switch (type) {
+ case UnionInNestedNS_NONE: {
+ return true;
+ }
+ case UnionInNestedNS_TableInNestedNS: {
+ auto ptr = reinterpret_cast<const NamespaceA::NamespaceB::TableInNestedNS *>(obj);
+ return verifier.VerifyTable(ptr);
+ }
+ default: return true;
+ }
+}
+
+inline bool VerifyUnionInNestedNSVector(flatbuffers::Verifier &verifier, const flatbuffers::Vector<flatbuffers::Offset<void>> *values, const flatbuffers::Vector<uint8_t> *types) {
+ if (!values || !types) return !values && !types;
+ if (values->size() != types->size()) return false;
+ for (flatbuffers::uoffset_t i = 0; i < values->size(); ++i) {
+ if (!VerifyUnionInNestedNS(
+ verifier, values->Get(i), types->GetEnum<UnionInNestedNS>(i))) {
+ return false;
+ }
+ }
+ return true;
+}
+
+inline void *UnionInNestedNSUnion::UnPack(const void *obj, UnionInNestedNS type, const flatbuffers::resolver_function_t *resolver) {
+ (void)resolver;
+ switch (type) {
+ case UnionInNestedNS_TableInNestedNS: {
+ auto ptr = reinterpret_cast<const NamespaceA::NamespaceB::TableInNestedNS *>(obj);
+ return ptr->UnPack(resolver);
+ }
+ default: return nullptr;
+ }
+}
+
+inline flatbuffers::Offset<void> UnionInNestedNSUnion::Pack(flatbuffers::FlatBufferBuilder &_fbb, const flatbuffers::rehasher_function_t *_rehasher) const {
+ (void)_rehasher;
+ switch (type) {
+ case UnionInNestedNS_TableInNestedNS: {
+ auto ptr = reinterpret_cast<const NamespaceA::NamespaceB::TableInNestedNST *>(value);
+ return CreateTableInNestedNS(_fbb, ptr, _rehasher).Union();
+ }
+ default: return 0;
+ }
+}
+
+inline UnionInNestedNSUnion::UnionInNestedNSUnion(const UnionInNestedNSUnion &u) : type(u.type), value(nullptr) {
+ switch (type) {
+ case UnionInNestedNS_TableInNestedNS: {
+ value = new NamespaceA::NamespaceB::TableInNestedNST(*reinterpret_cast<NamespaceA::NamespaceB::TableInNestedNST *>(u.value));
+ break;
+ }
+ default:
+ break;
+ }
+}
+
+inline void UnionInNestedNSUnion::Reset() {
+ switch (type) {
+ case UnionInNestedNS_TableInNestedNS: {
+ auto ptr = reinterpret_cast<NamespaceA::NamespaceB::TableInNestedNST *>(value);
+ delete ptr;
+ break;
+ }
+ default: break;
+ }
+ value = nullptr;
+ type = UnionInNestedNS_NONE;
+}
+
+inline const flatbuffers::TypeTable *UnionInNestedNSTypeTable() {
+ static const flatbuffers::TypeCode type_codes[] = {
+ { flatbuffers::ET_SEQUENCE, 0, -1 },
+ { flatbuffers::ET_SEQUENCE, 0, 0 }
+ };
+ static const flatbuffers::TypeFunction type_refs[] = {
+ NamespaceA::NamespaceB::TableInNestedNSTypeTable
+ };
+ static const char * const names[] = {
+ "NONE",
+ "TableInNestedNS"
+ };
+ static const flatbuffers::TypeTable tt = {
+ flatbuffers::ST_UNION, 2, type_codes, type_refs, nullptr, nullptr, names
+ };
+ return &tt;
+}
+
inline const flatbuffers::TypeTable *EnumInNestedNSTypeTable() {
static const flatbuffers::TypeCode type_codes[] = {
{ flatbuffers::ET_CHAR, 0, 0 },
diff --git a/tests/namespace_test/namespace_test1_generated.js b/tests/namespace_test/namespace_test1_generated.js
deleted file mode 100644
index 7331f64..0000000
--- a/tests/namespace_test/namespace_test1_generated.js
+++ /dev/null
@@ -1,229 +0,0 @@
-// automatically generated by the FlatBuffers compiler, do not modify
-
-/**
- * @const
- * @namespace
- */
-var NamespaceA = NamespaceA || {};
-
-/**
- * @const
- * @namespace
- */
-NamespaceA.NamespaceB = NamespaceA.NamespaceB || {};
-
-/**
- * @enum {number}
- */
-NamespaceA.NamespaceB.EnumInNestedNS = {
- A: 0,
- B: 1,
- C: 2
-};
-
-/**
- * @enum {string}
- */
-NamespaceA.NamespaceB.EnumInNestedNSName = {
- '0': 'A',
- '1': 'B',
- '2': 'C'
-};
-
-/**
- * @constructor
- */
-NamespaceA.NamespaceB.TableInNestedNS = function() {
- /**
- * @type {flatbuffers.ByteBuffer}
- */
- this.bb = null;
-
- /**
- * @type {number}
- */
- this.bb_pos = 0;
-};
-
-/**
- * @param {number} i
- * @param {flatbuffers.ByteBuffer} bb
- * @returns {NamespaceA.NamespaceB.TableInNestedNS}
- */
-NamespaceA.NamespaceB.TableInNestedNS.prototype.__init = function(i, bb) {
- this.bb_pos = i;
- this.bb = bb;
- return this;
-};
-
-/**
- * @param {flatbuffers.ByteBuffer} bb
- * @param {NamespaceA.NamespaceB.TableInNestedNS=} obj
- * @returns {NamespaceA.NamespaceB.TableInNestedNS}
- */
-NamespaceA.NamespaceB.TableInNestedNS.getRootAsTableInNestedNS = function(bb, obj) {
- return (obj || new NamespaceA.NamespaceB.TableInNestedNS).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param {flatbuffers.ByteBuffer} bb
- * @param {NamespaceA.NamespaceB.TableInNestedNS=} obj
- * @returns {NamespaceA.NamespaceB.TableInNestedNS}
- */
-NamespaceA.NamespaceB.TableInNestedNS.getSizePrefixedRootAsTableInNestedNS = function(bb, obj) {
- bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
- return (obj || new NamespaceA.NamespaceB.TableInNestedNS).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @returns {number}
- */
-NamespaceA.NamespaceB.TableInNestedNS.prototype.foo = function() {
- var offset = this.bb.__offset(this.bb_pos, 4);
- return offset ? this.bb.readInt32(this.bb_pos + offset) : 0;
-};
-
-/**
- * @param {number} value
- * @returns {boolean}
- */
-NamespaceA.NamespaceB.TableInNestedNS.prototype.mutate_foo = function(value) {
- var offset = this.bb.__offset(this.bb_pos, 4);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb.writeInt32(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @returns {string}
- */
-NamespaceA.NamespaceB.TableInNestedNS.getFullyQualifiedName = function() {
- return 'NamespaceA.NamespaceB.TableInNestedNS';
-}
-
-/**
- * @param {flatbuffers.Builder} builder
- */
-NamespaceA.NamespaceB.TableInNestedNS.startTableInNestedNS = function(builder) {
- builder.startObject(1);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} foo
- */
-NamespaceA.NamespaceB.TableInNestedNS.addFoo = function(builder, foo) {
- builder.addFieldInt32(0, foo, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @returns {flatbuffers.Offset}
- */
-NamespaceA.NamespaceB.TableInNestedNS.endTableInNestedNS = function(builder) {
- var offset = builder.endObject();
- return offset;
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} foo
- * @returns {flatbuffers.Offset}
- */
-NamespaceA.NamespaceB.TableInNestedNS.createTableInNestedNS = function(builder, foo) {
- NamespaceA.NamespaceB.TableInNestedNS.startTableInNestedNS(builder);
- NamespaceA.NamespaceB.TableInNestedNS.addFoo(builder, foo);
- return NamespaceA.NamespaceB.TableInNestedNS.endTableInNestedNS(builder);
-}
-
-/**
- * @constructor
- */
-NamespaceA.NamespaceB.StructInNestedNS = function() {
- /**
- * @type {flatbuffers.ByteBuffer}
- */
- this.bb = null;
-
- /**
- * @type {number}
- */
- this.bb_pos = 0;
-};
-
-/**
- * @param {number} i
- * @param {flatbuffers.ByteBuffer} bb
- * @returns {NamespaceA.NamespaceB.StructInNestedNS}
- */
-NamespaceA.NamespaceB.StructInNestedNS.prototype.__init = function(i, bb) {
- this.bb_pos = i;
- this.bb = bb;
- return this;
-};
-
-/**
- * @returns {number}
- */
-NamespaceA.NamespaceB.StructInNestedNS.prototype.a = function() {
- return this.bb.readInt32(this.bb_pos);
-};
-
-/**
- * @param {number} value
- * @returns {boolean}
- */
-NamespaceA.NamespaceB.StructInNestedNS.prototype.mutate_a = function(value) {
- this.bb.writeInt32(this.bb_pos + 0, value);
- return true;
-};
-
-/**
- * @returns {number}
- */
-NamespaceA.NamespaceB.StructInNestedNS.prototype.b = function() {
- return this.bb.readInt32(this.bb_pos + 4);
-};
-
-/**
- * @param {number} value
- * @returns {boolean}
- */
-NamespaceA.NamespaceB.StructInNestedNS.prototype.mutate_b = function(value) {
- this.bb.writeInt32(this.bb_pos + 4, value);
- return true;
-};
-
-/**
- * @returns {string}
- */
-NamespaceA.NamespaceB.StructInNestedNS.getFullyQualifiedName = function() {
- return 'NamespaceA.NamespaceB.StructInNestedNS';
-}
-
-/**
- * @returns {number}
- */
-NamespaceA.NamespaceB.StructInNestedNS.sizeOf = function() {
- return 8;
-}
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} a
- * @param {number} b
- * @returns {flatbuffers.Offset}
- */
-NamespaceA.NamespaceB.StructInNestedNS.createStructInNestedNS = function(builder, a, b) {
- builder.prep(4, 8);
- builder.writeInt32(b);
- builder.writeInt32(a);
- return builder.offset();
-};
-
-// Exports for Node.js and RequireJS
-this.NamespaceA = NamespaceA;
diff --git a/tests/namespace_test/namespace_test1_generated.lobster b/tests/namespace_test/namespace_test1_generated.lobster
index 6503005..5721b8f 100644
--- a/tests/namespace_test/namespace_test1_generated.lobster
+++ b/tests/namespace_test/namespace_test1_generated.lobster
@@ -3,6 +3,10 @@
namespace NamespaceA_NamespaceB
+enum UnionInNestedNS:
+ UnionInNestedNS_NONE = 0
+ UnionInNestedNS_TableInNestedNS = 1
+
enum EnumInNestedNS:
EnumInNestedNS_A = 0
EnumInNestedNS_B = 1
diff --git a/tests/namespace_test/namespace_test1_generated.rs b/tests/namespace_test/namespace_test1_generated.rs
deleted file mode 100644
index dd735a6..0000000
--- a/tests/namespace_test/namespace_test1_generated.rs
+++ /dev/null
@@ -1,264 +0,0 @@
-// automatically generated by the FlatBuffers compiler, do not modify
-
-
-#![allow(unused_imports, dead_code)]
-
-use std::mem;
-use std::cmp::Ordering;
-
-extern crate flatbuffers;
-use self::flatbuffers::EndianScalar;
-
-#[allow(unused_imports, dead_code)]
-pub mod namespace_a {
-
- use std::mem;
- use std::cmp::Ordering;
-
- extern crate flatbuffers;
- use self::flatbuffers::EndianScalar;
-#[allow(unused_imports, dead_code)]
-pub mod namespace_b {
-
- use std::mem;
- use std::cmp::Ordering;
-
- extern crate flatbuffers;
- use self::flatbuffers::EndianScalar;
-
-#[deprecated(since = "1.13", note = "Use associated constants instead. This will no longer be generated in 2021.")]
-pub const ENUM_MIN_ENUM_IN_NESTED_NS: i8 = 0;
-#[deprecated(since = "1.13", note = "Use associated constants instead. This will no longer be generated in 2021.")]
-pub const ENUM_MAX_ENUM_IN_NESTED_NS: i8 = 2;
-#[deprecated(since = "1.13", note = "Use associated constants instead. This will no longer be generated in 2021.")]
-#[allow(non_camel_case_types)]
-pub const ENUM_VALUES_ENUM_IN_NESTED_NS: [EnumInNestedNS; 3] = [
- EnumInNestedNS::A,
- EnumInNestedNS::B,
- EnumInNestedNS::C,
-];
-
-#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
-#[repr(transparent)]
-pub struct EnumInNestedNS(pub i8);
-#[allow(non_upper_case_globals)]
-impl EnumInNestedNS {
- pub const A: Self = Self(0);
- pub const B: Self = Self(1);
- pub const C: Self = Self(2);
-
- pub const ENUM_MIN: i8 = 0;
- pub const ENUM_MAX: i8 = 2;
- pub const ENUM_VALUES: &'static [Self] = &[
- Self::A,
- Self::B,
- Self::C,
- ];
- /// Returns the variant's name or "" if unknown.
- pub fn variant_name(self) -> Option<&'static str> {
- match self {
- Self::A => Some("A"),
- Self::B => Some("B"),
- Self::C => Some("C"),
- _ => None,
- }
- }
-}
-impl std::fmt::Debug for EnumInNestedNS {
- fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
- if let Some(name) = self.variant_name() {
- f.write_str(name)
- } else {
- f.write_fmt(format_args!("<UNKNOWN {:?}>", self.0))
- }
- }
-}
-impl<'a> flatbuffers::Follow<'a> for EnumInNestedNS {
- type Inner = Self;
- #[inline]
- fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
- Self(flatbuffers::read_scalar_at::<i8>(buf, loc))
- }
-}
-
-impl flatbuffers::Push for EnumInNestedNS {
- type Output = EnumInNestedNS;
- #[inline]
- fn push(&self, dst: &mut [u8], _rest: &[u8]) {
- flatbuffers::emplace_scalar::<i8>(dst, self.0);
- }
-}
-
-impl flatbuffers::EndianScalar for EnumInNestedNS {
- #[inline]
- fn to_little_endian(self) -> Self {
- Self(i8::to_le(self.0))
- }
- #[inline]
- fn from_little_endian(self) -> Self {
- Self(i8::from_le(self.0))
- }
-}
-
-// struct StructInNestedNS, aligned to 4
-#[repr(C, align(4))]
-#[derive(Clone, Copy, PartialEq)]
-pub struct StructInNestedNS {
- a_: i32,
- b_: i32,
-} // pub struct StructInNestedNS
-impl std::fmt::Debug for StructInNestedNS {
- fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
- f.debug_struct("StructInNestedNS")
- .field("a", &self.a())
- .field("b", &self.b())
- .finish()
- }
-}
-
-impl flatbuffers::SafeSliceAccess for StructInNestedNS {}
-impl<'a> flatbuffers::Follow<'a> for StructInNestedNS {
- type Inner = &'a StructInNestedNS;
- #[inline]
- fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
- <&'a StructInNestedNS>::follow(buf, loc)
- }
-}
-impl<'a> flatbuffers::Follow<'a> for &'a StructInNestedNS {
- type Inner = &'a StructInNestedNS;
- #[inline]
- fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
- flatbuffers::follow_cast_ref::<StructInNestedNS>(buf, loc)
- }
-}
-impl<'b> flatbuffers::Push for StructInNestedNS {
- type Output = StructInNestedNS;
- #[inline]
- fn push(&self, dst: &mut [u8], _rest: &[u8]) {
- let src = unsafe {
- ::std::slice::from_raw_parts(self as *const StructInNestedNS as *const u8, Self::size())
- };
- dst.copy_from_slice(src);
- }
-}
-impl<'b> flatbuffers::Push for &'b StructInNestedNS {
- type Output = StructInNestedNS;
-
- #[inline]
- fn push(&self, dst: &mut [u8], _rest: &[u8]) {
- let src = unsafe {
- ::std::slice::from_raw_parts(*self as *const StructInNestedNS as *const u8, Self::size())
- };
- dst.copy_from_slice(src);
- }
-}
-
-
-impl StructInNestedNS {
- pub fn new(_a: i32, _b: i32) -> Self {
- StructInNestedNS {
- a_: _a.to_little_endian(),
- b_: _b.to_little_endian(),
-
- }
- }
- pub const fn get_fully_qualified_name() -> &'static str {
- "NamespaceA.NamespaceB.StructInNestedNS"
- }
-
- pub fn a(&self) -> i32 {
- self.a_.from_little_endian()
- }
- pub fn b(&self) -> i32 {
- self.b_.from_little_endian()
- }
-}
-
-pub enum TableInNestedNSOffset {}
-#[derive(Copy, Clone, PartialEq)]
-
-pub struct TableInNestedNS<'a> {
- pub _tab: flatbuffers::Table<'a>,
-}
-
-impl<'a> flatbuffers::Follow<'a> for TableInNestedNS<'a> {
- type Inner = TableInNestedNS<'a>;
- #[inline]
- fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
- Self { _tab: flatbuffers::Table { buf, loc } }
- }
-}
-
-impl<'a> TableInNestedNS<'a> {
- pub const fn get_fully_qualified_name() -> &'static str {
- "NamespaceA.NamespaceB.TableInNestedNS"
- }
-
- #[inline]
- pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
- TableInNestedNS {
- _tab: table,
- }
- }
- #[allow(unused_mut)]
- pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
- _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
- args: &'args TableInNestedNSArgs) -> flatbuffers::WIPOffset<TableInNestedNS<'bldr>> {
- let mut builder = TableInNestedNSBuilder::new(_fbb);
- builder.add_foo(args.foo);
- builder.finish()
- }
-
- pub const VT_FOO: flatbuffers::VOffsetT = 4;
-
- #[inline]
- pub fn foo(&self) -> i32 {
- self._tab.get::<i32>(TableInNestedNS::VT_FOO, Some(0)).unwrap()
- }
-}
-
-pub struct TableInNestedNSArgs {
- pub foo: i32,
-}
-impl<'a> Default for TableInNestedNSArgs {
- #[inline]
- fn default() -> Self {
- TableInNestedNSArgs {
- foo: 0,
- }
- }
-}
-pub struct TableInNestedNSBuilder<'a: 'b, 'b> {
- fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
- start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
-}
-impl<'a: 'b, 'b> TableInNestedNSBuilder<'a, 'b> {
- #[inline]
- pub fn add_foo(&mut self, foo: i32) {
- self.fbb_.push_slot::<i32>(TableInNestedNS::VT_FOO, foo, 0);
- }
- #[inline]
- pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> TableInNestedNSBuilder<'a, 'b> {
- let start = _fbb.start_table();
- TableInNestedNSBuilder {
- fbb_: _fbb,
- start_: start,
- }
- }
- #[inline]
- pub fn finish(self) -> flatbuffers::WIPOffset<TableInNestedNS<'a>> {
- let o = self.fbb_.end_table(self.start_);
- flatbuffers::WIPOffset::new(o.value())
- }
-}
-
-impl std::fmt::Debug for TableInNestedNS<'_> {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- let mut ds = f.debug_struct("TableInNestedNS");
- ds.field("foo", &self.foo());
- ds.finish()
- }
-}
-} // pub mod NamespaceB
-} // pub mod NamespaceA
-
diff --git a/tests/namespace_test/namespace_test1_generated.ts b/tests/namespace_test/namespace_test1_generated.ts
deleted file mode 100644
index 933a43d..0000000
--- a/tests/namespace_test/namespace_test1_generated.ts
+++ /dev/null
@@ -1,269 +0,0 @@
-// automatically generated by the FlatBuffers compiler, do not modify
-
-/**
- * @enum {number}
- */
-export namespace NamespaceA.NamespaceB{
-export enum EnumInNestedNS{
- A= 0,
- B= 1,
- C= 2
-};
-}
-
-/**
- * @constructor
- */
-export namespace NamespaceA.NamespaceB{
-export class TableInNestedNS {
- bb: flatbuffers.ByteBuffer|null = null;
-
- bb_pos:number = 0;
-/**
- * @param number i
- * @param flatbuffers.ByteBuffer bb
- * @returns TableInNestedNS
- */
-__init(i:number, bb:flatbuffers.ByteBuffer):TableInNestedNS {
- this.bb_pos = i;
- this.bb = bb;
- return this;
-};
-
-/**
- * @param flatbuffers.ByteBuffer bb
- * @param TableInNestedNS= obj
- * @returns TableInNestedNS
- */
-static getRootAsTableInNestedNS(bb:flatbuffers.ByteBuffer, obj?:TableInNestedNS):TableInNestedNS {
- return (obj || new TableInNestedNS()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param flatbuffers.ByteBuffer bb
- * @param TableInNestedNS= obj
- * @returns TableInNestedNS
- */
-static getSizePrefixedRootAsTableInNestedNS(bb:flatbuffers.ByteBuffer, obj?:TableInNestedNS):TableInNestedNS {
- bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
- return (obj || new TableInNestedNS()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @returns number
- */
-foo():number {
- var offset = this.bb!.__offset(this.bb_pos, 4);
- return offset ? this.bb!.readInt32(this.bb_pos + offset) : 0;
-};
-
-/**
- * @param number value
- * @returns boolean
- */
-mutate_foo(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 4);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb!.writeInt32(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @returns string
- */
-static getFullyQualifiedName():string {
- return 'NamespaceA.NamespaceB.TableInNestedNS';
-}
-
-/**
- * @param flatbuffers.Builder builder
- */
-static startTableInNestedNS(builder:flatbuffers.Builder) {
- builder.startObject(1);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number foo
- */
-static addFoo(builder:flatbuffers.Builder, foo:number) {
- builder.addFieldInt32(0, foo, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @returns flatbuffers.Offset
- */
-static endTableInNestedNS(builder:flatbuffers.Builder):flatbuffers.Offset {
- var offset = builder.endObject();
- return offset;
-};
-
-static createTableInNestedNS(builder:flatbuffers.Builder, foo:number):flatbuffers.Offset {
- TableInNestedNS.startTableInNestedNS(builder);
- TableInNestedNS.addFoo(builder, foo);
- return TableInNestedNS.endTableInNestedNS(builder);
-}
-
-/**
- * @returns TableInNestedNST
- */
-unpack(): TableInNestedNST {
- return new TableInNestedNST(
- this.foo()
- );
-};
-
-/**
- * @param TableInNestedNST _o
- */
-unpackTo(_o: TableInNestedNST): void {
- _o.foo = this.foo();
-};
-}
-
-export class TableInNestedNST {
-/**
- * @constructor
- * @param number foo
- */
-constructor(
- public foo: number = 0
-){};
-
-/**
- * @param flatbuffers.Builder builder
- * @returns flatbuffers.Offset
- */
-pack(builder:flatbuffers.Builder): flatbuffers.Offset {
- return NamespaceA.NamespaceB.TableInNestedNS.createTableInNestedNS(builder,
- this.foo
- );
-};
-}
-}
-/**
- * @constructor
- */
-export namespace NamespaceA.NamespaceB{
-export class StructInNestedNS {
- bb: flatbuffers.ByteBuffer|null = null;
-
- bb_pos:number = 0;
-/**
- * @param number i
- * @param flatbuffers.ByteBuffer bb
- * @returns StructInNestedNS
- */
-__init(i:number, bb:flatbuffers.ByteBuffer):StructInNestedNS {
- this.bb_pos = i;
- this.bb = bb;
- return this;
-};
-
-/**
- * @returns number
- */
-a():number {
- return this.bb!.readInt32(this.bb_pos);
-};
-
-/**
- * @param number value
- * @returns boolean
- */
-mutate_a(value:number):boolean {
- this.bb!.writeInt32(this.bb_pos + 0, value);
- return true;
-};
-
-/**
- * @returns number
- */
-b():number {
- return this.bb!.readInt32(this.bb_pos + 4);
-};
-
-/**
- * @param number value
- * @returns boolean
- */
-mutate_b(value:number):boolean {
- this.bb!.writeInt32(this.bb_pos + 4, value);
- return true;
-};
-
-/**
- * @returns string
- */
-static getFullyQualifiedName():string {
- return 'NamespaceA.NamespaceB.StructInNestedNS';
-}
-
-/**
- * @returns number
- */
-static sizeOf():number {
- return 8;
-}
-
-/**
- * @param flatbuffers.Builder builder
- * @param number a
- * @param number b
- * @returns flatbuffers.Offset
- */
-static createStructInNestedNS(builder:flatbuffers.Builder, a: number, b: number):flatbuffers.Offset {
- builder.prep(4, 8);
- builder.writeInt32(b);
- builder.writeInt32(a);
- return builder.offset();
-};
-
-
-/**
- * @returns StructInNestedNST
- */
-unpack(): StructInNestedNST {
- return new StructInNestedNST(
- this.a(),
- this.b()
- );
-};
-
-/**
- * @param StructInNestedNST _o
- */
-unpackTo(_o: StructInNestedNST): void {
- _o.a = this.a();
- _o.b = this.b();
-};
-}
-
-export class StructInNestedNST {
-/**
- * @constructor
- * @param number a
- * @param number b
- */
-constructor(
- public a: number = 0,
- public b: number = 0
-){};
-
-/**
- * @param flatbuffers.Builder builder
- * @returns flatbuffers.Offset
- */
-pack(builder:flatbuffers.Builder): flatbuffers.Offset {
- return NamespaceA.NamespaceB.StructInNestedNS.createStructInNestedNS(builder,
- this.a,
- this.b
- );
-};
-}
-}
diff --git a/tests/namespace_test/namespace_test1_namespace_a.namespace_b_generated.dart b/tests/namespace_test/namespace_test1_namespace_a.namespace_b_generated.dart
index cc936c3..5e0fb1d 100644
--- a/tests/namespace_test/namespace_test1_namespace_a.namespace_b_generated.dart
+++ b/tests/namespace_test/namespace_test1_namespace_a.namespace_b_generated.dart
@@ -1,5 +1,5 @@
// automatically generated by the FlatBuffers compiler, do not modify
-// ignore_for_file: unused_import, unused_field, unused_local_variable
+// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable
library namespace_a.namespace_b;
@@ -7,28 +7,78 @@
import 'package:flat_buffers/flat_buffers.dart' as fb;
+class UnionInNestedNSTypeId {
+ final int value;
+ const UnionInNestedNSTypeId._(this.value);
+
+ factory UnionInNestedNSTypeId.fromValue(int value) {
+ final result = values[value];
+ if (result == null) {
+ throw StateError('Invalid value $value for bit flag enum UnionInNestedNSTypeId');
+ }
+ return result;
+ }
+
+ static UnionInNestedNSTypeId? _createOrNull(int? value) =>
+ value == null ? null : UnionInNestedNSTypeId.fromValue(value);
+
+ static const int minValue = 0;
+ static const int maxValue = 1;
+ static bool containsValue(int value) => values.containsKey(value);
+
+ static const UnionInNestedNSTypeId NONE = UnionInNestedNSTypeId._(0);
+ static const UnionInNestedNSTypeId TableInNestedNS = UnionInNestedNSTypeId._(1);
+ static const Map<int, UnionInNestedNSTypeId> values = {
+ 0: NONE,
+ 1: TableInNestedNS};
+
+ static const fb.Reader<UnionInNestedNSTypeId> reader = _UnionInNestedNSTypeIdReader();
+
+ @override
+ String toString() {
+ return 'UnionInNestedNSTypeId{value: $value}';
+ }
+}
+
+class _UnionInNestedNSTypeIdReader extends fb.Reader<UnionInNestedNSTypeId> {
+ const _UnionInNestedNSTypeIdReader();
+
+ @override
+ int get size => 1;
+
+ @override
+ UnionInNestedNSTypeId read(fb.BufferContext bc, int offset) =>
+ UnionInNestedNSTypeId.fromValue(const fb.Uint8Reader().read(bc, offset));
+}
+
class EnumInNestedNS {
final int value;
const EnumInNestedNS._(this.value);
factory EnumInNestedNS.fromValue(int value) {
- if (value == null) value = 0;
- if (!values.containsKey(value)) {
- throw new StateError('Invalid value $value for bit flag enum EnumInNestedNS');
+ final result = values[value];
+ if (result == null) {
+ throw StateError('Invalid value $value for bit flag enum EnumInNestedNS');
}
- return values[value];
+ return result;
}
+ static EnumInNestedNS? _createOrNull(int? value) =>
+ value == null ? null : EnumInNestedNS.fromValue(value);
+
static const int minValue = 0;
static const int maxValue = 2;
static bool containsValue(int value) => values.containsKey(value);
- static const EnumInNestedNS A = const EnumInNestedNS._(0);
- static const EnumInNestedNS B = const EnumInNestedNS._(1);
- static const EnumInNestedNS C = const EnumInNestedNS._(2);
- static const values = {0: A,1: B,2: C,};
+ static const EnumInNestedNS A = EnumInNestedNS._(0);
+ static const EnumInNestedNS B = EnumInNestedNS._(1);
+ static const EnumInNestedNS C = EnumInNestedNS._(2);
+ static const Map<int, EnumInNestedNS> values = {
+ 0: A,
+ 1: B,
+ 2: C};
- static const fb.Reader<EnumInNestedNS> reader = const _EnumInNestedNSReader();
+ static const fb.Reader<EnumInNestedNS> reader = _EnumInNestedNSReader();
@override
String toString() {
@@ -44,17 +94,17 @@
@override
EnumInNestedNS read(fb.BufferContext bc, int offset) =>
- new EnumInNestedNS.fromValue(const fb.Int8Reader().read(bc, offset));
+ EnumInNestedNS.fromValue(const fb.Int8Reader().read(bc, offset));
}
class TableInNestedNS {
TableInNestedNS._(this._bc, this._bcOffset);
factory TableInNestedNS(List<int> bytes) {
- fb.BufferContext rootRef = new fb.BufferContext.fromBytes(bytes);
+ final rootRef = fb.BufferContext.fromBytes(bytes);
return reader.read(rootRef, 0);
}
- static const fb.Reader<TableInNestedNS> reader = const _TableInNestedNSReader();
+ static const fb.Reader<TableInNestedNS> reader = _TableInNestedNSReader();
final fb.BufferContext _bc;
final int _bcOffset;
@@ -65,6 +115,33 @@
String toString() {
return 'TableInNestedNS{foo: $foo}';
}
+
+ TableInNestedNST unpack() => TableInNestedNST(
+ foo: foo);
+
+ static int pack(fb.Builder fbBuilder, TableInNestedNST? object) {
+ if (object == null) return 0;
+ return object.pack(fbBuilder);
+ }
+}
+
+class TableInNestedNST implements fb.Packable {
+ int foo;
+
+ TableInNestedNST({
+ this.foo = 0});
+
+ @override
+ int pack(fb.Builder fbBuilder) {
+ fbBuilder.startTable(1);
+ fbBuilder.addInt32(0, foo);
+ return fbBuilder.endTable();
+ }
+
+ @override
+ String toString() {
+ return 'TableInNestedNST{foo: $foo}';
+ }
}
class _TableInNestedNSReader extends fb.TableReader<TableInNestedNS> {
@@ -72,21 +149,19 @@
@override
TableInNestedNS createObject(fb.BufferContext bc, int offset) =>
- new TableInNestedNS._(bc, offset);
+ TableInNestedNS._(bc, offset);
}
class TableInNestedNSBuilder {
- TableInNestedNSBuilder(this.fbBuilder) {
- assert(fbBuilder != null);
- }
+ TableInNestedNSBuilder(this.fbBuilder);
final fb.Builder fbBuilder;
void begin() {
- fbBuilder.startTable();
+ fbBuilder.startTable(1);
}
- int addFoo(int foo) {
+ int addFoo(int? foo) {
fbBuilder.addInt32(0, foo);
return fbBuilder.offset;
}
@@ -97,36 +172,33 @@
}
class TableInNestedNSObjectBuilder extends fb.ObjectBuilder {
- final int _foo;
+ final int? _foo;
TableInNestedNSObjectBuilder({
- int foo,
+ int? foo,
})
: _foo = foo;
/// Finish building, and store into the [fbBuilder].
@override
- int finish(
- fb.Builder fbBuilder) {
- assert(fbBuilder != null);
-
- fbBuilder.startTable();
+ int finish(fb.Builder fbBuilder) {
+ fbBuilder.startTable(1);
fbBuilder.addInt32(0, _foo);
return fbBuilder.endTable();
}
/// Convenience method to serialize to byte list.
@override
- Uint8List toBytes([String fileIdentifier]) {
- fb.Builder fbBuilder = new fb.Builder();
- int offset = finish(fbBuilder);
- return fbBuilder.finish(offset, fileIdentifier);
+ Uint8List toBytes([String? fileIdentifier]) {
+ final fbBuilder = fb.Builder(deduplicateTables: false);
+ fbBuilder.finish(finish(fbBuilder), fileIdentifier);
+ return fbBuilder.buffer;
}
}
class StructInNestedNS {
StructInNestedNS._(this._bc, this._bcOffset);
- static const fb.Reader<StructInNestedNS> reader = const _StructInNestedNSReader();
+ static const fb.Reader<StructInNestedNS> reader = _StructInNestedNSReader();
final fb.BufferContext _bc;
final int _bcOffset;
@@ -138,6 +210,36 @@
String toString() {
return 'StructInNestedNS{a: $a, b: $b}';
}
+
+ StructInNestedNST unpack() => StructInNestedNST(
+ a: a,
+ b: b);
+
+ static int pack(fb.Builder fbBuilder, StructInNestedNST? object) {
+ if (object == null) return 0;
+ return object.pack(fbBuilder);
+ }
+}
+
+class StructInNestedNST implements fb.Packable {
+ int a;
+ int b;
+
+ StructInNestedNST({
+ required this.a,
+ required this.b});
+
+ @override
+ int pack(fb.Builder fbBuilder) {
+ fbBuilder.putInt32(b);
+ fbBuilder.putInt32(a);
+ return fbBuilder.offset;
+ }
+
+ @override
+ String toString() {
+ return 'StructInNestedNST{a: $a, b: $b}';
+ }
}
class _StructInNestedNSReader extends fb.StructReader<StructInNestedNS> {
@@ -148,13 +250,11 @@
@override
StructInNestedNS createObject(fb.BufferContext bc, int offset) =>
- new StructInNestedNS._(bc, offset);
+ StructInNestedNS._(bc, offset);
}
class StructInNestedNSBuilder {
- StructInNestedNSBuilder(this.fbBuilder) {
- assert(fbBuilder != null);
- }
+ StructInNestedNSBuilder(this.fbBuilder);
final fb.Builder fbBuilder;
@@ -171,18 +271,15 @@
final int _b;
StructInNestedNSObjectBuilder({
- int a,
- int b,
+ required int a,
+ required int b,
})
: _a = a,
_b = b;
/// Finish building, and store into the [fbBuilder].
@override
- int finish(
- fb.Builder fbBuilder) {
- assert(fbBuilder != null);
-
+ int finish(fb.Builder fbBuilder) {
fbBuilder.putInt32(_b);
fbBuilder.putInt32(_a);
return fbBuilder.offset;
@@ -190,9 +287,9 @@
/// Convenience method to serialize to byte list.
@override
- Uint8List toBytes([String fileIdentifier]) {
- fb.Builder fbBuilder = new fb.Builder();
- int offset = finish(fbBuilder);
- return fbBuilder.finish(offset, fileIdentifier);
+ Uint8List toBytes([String? fileIdentifier]) {
+ final fbBuilder = fb.Builder(deduplicateTables: false);
+ fbBuilder.finish(finish(fbBuilder), fileIdentifier);
+ return fbBuilder.buffer;
}
}
diff --git a/tests/namespace_test/namespace_test2.fbs b/tests/namespace_test/namespace_test2.fbs
index 11d7dea..e1440e7 100644
--- a/tests/namespace_test/namespace_test2.fbs
+++ b/tests/namespace_test/namespace_test2.fbs
@@ -6,6 +6,7 @@
{
foo_table:NamespaceB.TableInNestedNS;
foo_enum:NamespaceB.EnumInNestedNS;
+ foo_union:NamespaceB.UnionInNestedNS;
foo_struct:NamespaceB.StructInNestedNS;
}
diff --git a/tests/namespace_test/namespace_test2.ts b/tests/namespace_test/namespace_test2.ts
new file mode 100644
index 0000000..01f1bd4
--- /dev/null
+++ b/tests/namespace_test/namespace_test2.ts
@@ -0,0 +1,7 @@
+export { EnumInNestedNS } from './namespace-a/namespace-b/enum-in-nested-n-s';
+export { StructInNestedNS, StructInNestedNST } from './namespace-a/namespace-b/struct-in-nested-n-s';
+export { TableInNestedNS, TableInNestedNST } from './namespace-a/namespace-b/table-in-nested-n-s';
+export { UnionInNestedNS, unionToUnionInNestedNS, unionListToUnionInNestedNS } from './namespace-a/namespace-b/union-in-nested-n-s';
+export { SecondTableInA, SecondTableInAT } from './namespace-a/second-table-in-a';
+export { TableInFirstNS, TableInFirstNST } from './namespace-a/table-in-first-n-s';
+export { TableInC, TableInCT } from './namespace-c/table-in-c';
diff --git a/tests/namespace_test/namespace_test2_generated.h b/tests/namespace_test/namespace_test2_generated.h
index 9c0a1b6..ff164cc 100644
--- a/tests/namespace_test/namespace_test2_generated.h
+++ b/tests/namespace_test/namespace_test2_generated.h
@@ -59,42 +59,34 @@
struct TableInFirstNST : public flatbuffers::NativeTable {
typedef TableInFirstNS TableType;
- static FLATBUFFERS_CONSTEXPR const char *GetFullyQualifiedName() {
+ static FLATBUFFERS_CONSTEXPR_CPP11 const char *GetFullyQualifiedName() {
return "NamespaceA.TableInFirstNST";
}
- flatbuffers::unique_ptr<NamespaceA::NamespaceB::TableInNestedNST> foo_table;
- NamespaceA::NamespaceB::EnumInNestedNS foo_enum;
- flatbuffers::unique_ptr<NamespaceA::NamespaceB::StructInNestedNS> foo_struct;
- TableInFirstNST()
- : foo_enum(NamespaceA::NamespaceB::EnumInNestedNS_A) {
- }
+ flatbuffers::unique_ptr<NamespaceA::NamespaceB::TableInNestedNST> foo_table{};
+ NamespaceA::NamespaceB::EnumInNestedNS foo_enum = NamespaceA::NamespaceB::EnumInNestedNS_A;
+ NamespaceA::NamespaceB::UnionInNestedNSUnion foo_union{};
+ flatbuffers::unique_ptr<NamespaceA::NamespaceB::StructInNestedNS> foo_struct{};
+ TableInFirstNST() = default;
+ TableInFirstNST(const TableInFirstNST &o);
+ TableInFirstNST(TableInFirstNST&&) FLATBUFFERS_NOEXCEPT = default;
+ TableInFirstNST &operator=(TableInFirstNST o) FLATBUFFERS_NOEXCEPT;
};
-inline bool operator==(const TableInFirstNST &lhs, const TableInFirstNST &rhs) {
- return
- (lhs.foo_table == rhs.foo_table) &&
- (lhs.foo_enum == rhs.foo_enum) &&
- (lhs.foo_struct == rhs.foo_struct);
-}
-
-inline bool operator!=(const TableInFirstNST &lhs, const TableInFirstNST &rhs) {
- return !(lhs == rhs);
-}
-
-
struct TableInFirstNS FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
typedef TableInFirstNST NativeTableType;
typedef TableInFirstNSBuilder Builder;
static const flatbuffers::TypeTable *MiniReflectTypeTable() {
return TableInFirstNSTypeTable();
}
- static FLATBUFFERS_CONSTEXPR const char *GetFullyQualifiedName() {
+ static FLATBUFFERS_CONSTEXPR_CPP11 const char *GetFullyQualifiedName() {
return "NamespaceA.TableInFirstNS";
}
enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE {
VT_FOO_TABLE = 4,
VT_FOO_ENUM = 6,
- VT_FOO_STRUCT = 8
+ VT_FOO_UNION_TYPE = 8,
+ VT_FOO_UNION = 10,
+ VT_FOO_STRUCT = 12
};
const NamespaceA::NamespaceB::TableInNestedNS *foo_table() const {
return GetPointer<const NamespaceA::NamespaceB::TableInNestedNS *>(VT_FOO_TABLE);
@@ -105,9 +97,22 @@
NamespaceA::NamespaceB::EnumInNestedNS foo_enum() const {
return static_cast<NamespaceA::NamespaceB::EnumInNestedNS>(GetField<int8_t>(VT_FOO_ENUM, 0));
}
- bool mutate_foo_enum(NamespaceA::NamespaceB::EnumInNestedNS _foo_enum) {
+ bool mutate_foo_enum(NamespaceA::NamespaceB::EnumInNestedNS _foo_enum = static_cast<NamespaceA::NamespaceB::EnumInNestedNS>(0)) {
return SetField<int8_t>(VT_FOO_ENUM, static_cast<int8_t>(_foo_enum), 0);
}
+ NamespaceA::NamespaceB::UnionInNestedNS foo_union_type() const {
+ return static_cast<NamespaceA::NamespaceB::UnionInNestedNS>(GetField<uint8_t>(VT_FOO_UNION_TYPE, 0));
+ }
+ const void *foo_union() const {
+ return GetPointer<const void *>(VT_FOO_UNION);
+ }
+ template<typename T> const T *foo_union_as() const;
+ const NamespaceA::NamespaceB::TableInNestedNS *foo_union_as_TableInNestedNS() const {
+ return foo_union_type() == NamespaceA::NamespaceB::UnionInNestedNS_TableInNestedNS ? static_cast<const NamespaceA::NamespaceB::TableInNestedNS *>(foo_union()) : nullptr;
+ }
+ void *mutable_foo_union() {
+ return GetPointer<void *>(VT_FOO_UNION);
+ }
const NamespaceA::NamespaceB::StructInNestedNS *foo_struct() const {
return GetStruct<const NamespaceA::NamespaceB::StructInNestedNS *>(VT_FOO_STRUCT);
}
@@ -118,8 +123,11 @@
return VerifyTableStart(verifier) &&
VerifyOffset(verifier, VT_FOO_TABLE) &&
verifier.VerifyTable(foo_table()) &&
- VerifyField<int8_t>(verifier, VT_FOO_ENUM) &&
- VerifyField<NamespaceA::NamespaceB::StructInNestedNS>(verifier, VT_FOO_STRUCT) &&
+ VerifyField<int8_t>(verifier, VT_FOO_ENUM, 1) &&
+ VerifyField<uint8_t>(verifier, VT_FOO_UNION_TYPE, 1) &&
+ VerifyOffset(verifier, VT_FOO_UNION) &&
+ VerifyUnionInNestedNS(verifier, foo_union(), foo_union_type()) &&
+ VerifyField<NamespaceA::NamespaceB::StructInNestedNS>(verifier, VT_FOO_STRUCT, 4) &&
verifier.EndTable();
}
TableInFirstNST *UnPack(const flatbuffers::resolver_function_t *_resolver = nullptr) const;
@@ -127,6 +135,10 @@
static flatbuffers::Offset<TableInFirstNS> Pack(flatbuffers::FlatBufferBuilder &_fbb, const TableInFirstNST* _o, const flatbuffers::rehasher_function_t *_rehasher = nullptr);
};
+template<> inline const NamespaceA::NamespaceB::TableInNestedNS *TableInFirstNS::foo_union_as<NamespaceA::NamespaceB::TableInNestedNS>() const {
+ return foo_union_as_TableInNestedNS();
+}
+
struct TableInFirstNSBuilder {
typedef TableInFirstNS Table;
flatbuffers::FlatBufferBuilder &fbb_;
@@ -137,6 +149,12 @@
void add_foo_enum(NamespaceA::NamespaceB::EnumInNestedNS foo_enum) {
fbb_.AddElement<int8_t>(TableInFirstNS::VT_FOO_ENUM, static_cast<int8_t>(foo_enum), 0);
}
+ void add_foo_union_type(NamespaceA::NamespaceB::UnionInNestedNS foo_union_type) {
+ fbb_.AddElement<uint8_t>(TableInFirstNS::VT_FOO_UNION_TYPE, static_cast<uint8_t>(foo_union_type), 0);
+ }
+ void add_foo_union(flatbuffers::Offset<void> foo_union) {
+ fbb_.AddOffset(TableInFirstNS::VT_FOO_UNION, foo_union);
+ }
void add_foo_struct(const NamespaceA::NamespaceB::StructInNestedNS *foo_struct) {
fbb_.AddStruct(TableInFirstNS::VT_FOO_STRUCT, foo_struct);
}
@@ -155,10 +173,14 @@
flatbuffers::FlatBufferBuilder &_fbb,
flatbuffers::Offset<NamespaceA::NamespaceB::TableInNestedNS> foo_table = 0,
NamespaceA::NamespaceB::EnumInNestedNS foo_enum = NamespaceA::NamespaceB::EnumInNestedNS_A,
- const NamespaceA::NamespaceB::StructInNestedNS *foo_struct = 0) {
+ NamespaceA::NamespaceB::UnionInNestedNS foo_union_type = NamespaceA::NamespaceB::UnionInNestedNS_NONE,
+ flatbuffers::Offset<void> foo_union = 0,
+ const NamespaceA::NamespaceB::StructInNestedNS *foo_struct = nullptr) {
TableInFirstNSBuilder builder_(_fbb);
builder_.add_foo_struct(foo_struct);
+ builder_.add_foo_union(foo_union);
builder_.add_foo_table(foo_table);
+ builder_.add_foo_union_type(foo_union_type);
builder_.add_foo_enum(foo_enum);
return builder_.Finish();
}
@@ -171,33 +193,24 @@
struct TableInCT : public flatbuffers::NativeTable {
typedef TableInC TableType;
- static FLATBUFFERS_CONSTEXPR const char *GetFullyQualifiedName() {
+ static FLATBUFFERS_CONSTEXPR_CPP11 const char *GetFullyQualifiedName() {
return "NamespaceC.TableInCT";
}
- flatbuffers::unique_ptr<NamespaceA::TableInFirstNST> refer_to_a1;
- flatbuffers::unique_ptr<NamespaceA::SecondTableInAT> refer_to_a2;
- TableInCT() {
- }
+ flatbuffers::unique_ptr<NamespaceA::TableInFirstNST> refer_to_a1{};
+ flatbuffers::unique_ptr<NamespaceA::SecondTableInAT> refer_to_a2{};
+ TableInCT() = default;
+ TableInCT(const TableInCT &o);
+ TableInCT(TableInCT&&) FLATBUFFERS_NOEXCEPT = default;
+ TableInCT &operator=(TableInCT o) FLATBUFFERS_NOEXCEPT;
};
-inline bool operator==(const TableInCT &lhs, const TableInCT &rhs) {
- return
- (lhs.refer_to_a1 == rhs.refer_to_a1) &&
- (lhs.refer_to_a2 == rhs.refer_to_a2);
-}
-
-inline bool operator!=(const TableInCT &lhs, const TableInCT &rhs) {
- return !(lhs == rhs);
-}
-
-
struct TableInC FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
typedef TableInCT NativeTableType;
typedef TableInCBuilder Builder;
static const flatbuffers::TypeTable *MiniReflectTypeTable() {
return TableInCTypeTable();
}
- static FLATBUFFERS_CONSTEXPR const char *GetFullyQualifiedName() {
+ static FLATBUFFERS_CONSTEXPR_CPP11 const char *GetFullyQualifiedName() {
return "NamespaceC.TableInC";
}
enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE {
@@ -268,31 +281,23 @@
struct SecondTableInAT : public flatbuffers::NativeTable {
typedef SecondTableInA TableType;
- static FLATBUFFERS_CONSTEXPR const char *GetFullyQualifiedName() {
+ static FLATBUFFERS_CONSTEXPR_CPP11 const char *GetFullyQualifiedName() {
return "NamespaceA.SecondTableInAT";
}
- flatbuffers::unique_ptr<NamespaceC::TableInCT> refer_to_c;
- SecondTableInAT() {
- }
+ flatbuffers::unique_ptr<NamespaceC::TableInCT> refer_to_c{};
+ SecondTableInAT() = default;
+ SecondTableInAT(const SecondTableInAT &o);
+ SecondTableInAT(SecondTableInAT&&) FLATBUFFERS_NOEXCEPT = default;
+ SecondTableInAT &operator=(SecondTableInAT o) FLATBUFFERS_NOEXCEPT;
};
-inline bool operator==(const SecondTableInAT &lhs, const SecondTableInAT &rhs) {
- return
- (lhs.refer_to_c == rhs.refer_to_c);
-}
-
-inline bool operator!=(const SecondTableInAT &lhs, const SecondTableInAT &rhs) {
- return !(lhs == rhs);
-}
-
-
struct SecondTableInA FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
typedef SecondTableInAT NativeTableType;
typedef SecondTableInABuilder Builder;
static const flatbuffers::TypeTable *MiniReflectTypeTable() {
return SecondTableInATypeTable();
}
- static FLATBUFFERS_CONSTEXPR const char *GetFullyQualifiedName() {
+ static FLATBUFFERS_CONSTEXPR_CPP11 const char *GetFullyQualifiedName() {
return "NamespaceA.SecondTableInA";
}
enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE {
@@ -343,8 +348,37 @@
flatbuffers::Offset<SecondTableInA> CreateSecondTableInA(flatbuffers::FlatBufferBuilder &_fbb, const SecondTableInAT *_o, const flatbuffers::rehasher_function_t *_rehasher = nullptr);
+
+inline bool operator==(const TableInFirstNST &lhs, const TableInFirstNST &rhs) {
+ return
+ ((lhs.foo_table == rhs.foo_table) || (lhs.foo_table && rhs.foo_table && *lhs.foo_table == *rhs.foo_table)) &&
+ (lhs.foo_enum == rhs.foo_enum) &&
+ (lhs.foo_union == rhs.foo_union) &&
+ ((lhs.foo_struct == rhs.foo_struct) || (lhs.foo_struct && rhs.foo_struct && *lhs.foo_struct == *rhs.foo_struct));
+}
+
+inline bool operator!=(const TableInFirstNST &lhs, const TableInFirstNST &rhs) {
+ return !(lhs == rhs);
+}
+
+
+inline TableInFirstNST::TableInFirstNST(const TableInFirstNST &o)
+ : foo_table((o.foo_table) ? new NamespaceA::NamespaceB::TableInNestedNST(*o.foo_table) : nullptr),
+ foo_enum(o.foo_enum),
+ foo_union(o.foo_union),
+ foo_struct((o.foo_struct) ? new NamespaceA::NamespaceB::StructInNestedNS(*o.foo_struct) : nullptr) {
+}
+
+inline TableInFirstNST &TableInFirstNST::operator=(TableInFirstNST o) FLATBUFFERS_NOEXCEPT {
+ std::swap(foo_table, o.foo_table);
+ std::swap(foo_enum, o.foo_enum);
+ std::swap(foo_union, o.foo_union);
+ std::swap(foo_struct, o.foo_struct);
+ return *this;
+}
+
inline TableInFirstNST *TableInFirstNS::UnPack(const flatbuffers::resolver_function_t *_resolver) const {
- flatbuffers::unique_ptr<NamespaceA::TableInFirstNST> _o = flatbuffers::unique_ptr<NamespaceA::TableInFirstNST>(new TableInFirstNST());
+ auto _o = std::unique_ptr<TableInFirstNST>(new TableInFirstNST());
UnPackTo(_o.get(), _resolver);
return _o.release();
}
@@ -352,8 +386,10 @@
inline void TableInFirstNS::UnPackTo(TableInFirstNST *_o, const flatbuffers::resolver_function_t *_resolver) const {
(void)_o;
(void)_resolver;
- { auto _e = foo_table(); if (_e) _o->foo_table = flatbuffers::unique_ptr<NamespaceA::NamespaceB::TableInNestedNST>(_e->UnPack(_resolver)); }
+ { auto _e = foo_table(); if (_e) { if(_o->foo_table) { _e->UnPackTo(_o->foo_table.get(), _resolver); } else { _o->foo_table = flatbuffers::unique_ptr<NamespaceA::NamespaceB::TableInNestedNST>(_e->UnPack(_resolver)); } } }
{ auto _e = foo_enum(); _o->foo_enum = _e; }
+ { auto _e = foo_union_type(); _o->foo_union.type = _e; }
+ { auto _e = foo_union(); if (_e) _o->foo_union.value = NamespaceA::NamespaceB::UnionInNestedNSUnion::UnPack(_e, foo_union_type(), _resolver); }
{ auto _e = foo_struct(); if (_e) _o->foo_struct = flatbuffers::unique_ptr<NamespaceA::NamespaceB::StructInNestedNS>(new NamespaceA::NamespaceB::StructInNestedNS(*_e)); }
}
@@ -367,11 +403,15 @@
struct _VectorArgs { flatbuffers::FlatBufferBuilder *__fbb; const TableInFirstNST* __o; const flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va;
auto _foo_table = _o->foo_table ? CreateTableInNestedNS(_fbb, _o->foo_table.get(), _rehasher) : 0;
auto _foo_enum = _o->foo_enum;
+ auto _foo_union_type = _o->foo_union.type;
+ auto _foo_union = _o->foo_union.Pack(_fbb);
auto _foo_struct = _o->foo_struct ? _o->foo_struct.get() : 0;
return NamespaceA::CreateTableInFirstNS(
_fbb,
_foo_table,
_foo_enum,
+ _foo_union_type,
+ _foo_union,
_foo_struct);
}
@@ -379,8 +419,31 @@
namespace NamespaceC {
+
+inline bool operator==(const TableInCT &lhs, const TableInCT &rhs) {
+ return
+ ((lhs.refer_to_a1 == rhs.refer_to_a1) || (lhs.refer_to_a1 && rhs.refer_to_a1 && *lhs.refer_to_a1 == *rhs.refer_to_a1)) &&
+ ((lhs.refer_to_a2 == rhs.refer_to_a2) || (lhs.refer_to_a2 && rhs.refer_to_a2 && *lhs.refer_to_a2 == *rhs.refer_to_a2));
+}
+
+inline bool operator!=(const TableInCT &lhs, const TableInCT &rhs) {
+ return !(lhs == rhs);
+}
+
+
+inline TableInCT::TableInCT(const TableInCT &o)
+ : refer_to_a1((o.refer_to_a1) ? new NamespaceA::TableInFirstNST(*o.refer_to_a1) : nullptr),
+ refer_to_a2((o.refer_to_a2) ? new NamespaceA::SecondTableInAT(*o.refer_to_a2) : nullptr) {
+}
+
+inline TableInCT &TableInCT::operator=(TableInCT o) FLATBUFFERS_NOEXCEPT {
+ std::swap(refer_to_a1, o.refer_to_a1);
+ std::swap(refer_to_a2, o.refer_to_a2);
+ return *this;
+}
+
inline TableInCT *TableInC::UnPack(const flatbuffers::resolver_function_t *_resolver) const {
- flatbuffers::unique_ptr<NamespaceC::TableInCT> _o = flatbuffers::unique_ptr<NamespaceC::TableInCT>(new TableInCT());
+ auto _o = std::unique_ptr<TableInCT>(new TableInCT());
UnPackTo(_o.get(), _resolver);
return _o.release();
}
@@ -388,8 +451,8 @@
inline void TableInC::UnPackTo(TableInCT *_o, const flatbuffers::resolver_function_t *_resolver) const {
(void)_o;
(void)_resolver;
- { auto _e = refer_to_a1(); if (_e) _o->refer_to_a1 = flatbuffers::unique_ptr<NamespaceA::TableInFirstNST>(_e->UnPack(_resolver)); }
- { auto _e = refer_to_a2(); if (_e) _o->refer_to_a2 = flatbuffers::unique_ptr<NamespaceA::SecondTableInAT>(_e->UnPack(_resolver)); }
+ { auto _e = refer_to_a1(); if (_e) { if(_o->refer_to_a1) { _e->UnPackTo(_o->refer_to_a1.get(), _resolver); } else { _o->refer_to_a1 = flatbuffers::unique_ptr<NamespaceA::TableInFirstNST>(_e->UnPack(_resolver)); } } }
+ { auto _e = refer_to_a2(); if (_e) { if(_o->refer_to_a2) { _e->UnPackTo(_o->refer_to_a2.get(), _resolver); } else { _o->refer_to_a2 = flatbuffers::unique_ptr<NamespaceA::SecondTableInAT>(_e->UnPack(_resolver)); } } }
}
inline flatbuffers::Offset<TableInC> TableInC::Pack(flatbuffers::FlatBufferBuilder &_fbb, const TableInCT* _o, const flatbuffers::rehasher_function_t *_rehasher) {
@@ -412,8 +475,28 @@
namespace NamespaceA {
+
+inline bool operator==(const SecondTableInAT &lhs, const SecondTableInAT &rhs) {
+ return
+ ((lhs.refer_to_c == rhs.refer_to_c) || (lhs.refer_to_c && rhs.refer_to_c && *lhs.refer_to_c == *rhs.refer_to_c));
+}
+
+inline bool operator!=(const SecondTableInAT &lhs, const SecondTableInAT &rhs) {
+ return !(lhs == rhs);
+}
+
+
+inline SecondTableInAT::SecondTableInAT(const SecondTableInAT &o)
+ : refer_to_c((o.refer_to_c) ? new NamespaceC::TableInCT(*o.refer_to_c) : nullptr) {
+}
+
+inline SecondTableInAT &SecondTableInAT::operator=(SecondTableInAT o) FLATBUFFERS_NOEXCEPT {
+ std::swap(refer_to_c, o.refer_to_c);
+ return *this;
+}
+
inline SecondTableInAT *SecondTableInA::UnPack(const flatbuffers::resolver_function_t *_resolver) const {
- flatbuffers::unique_ptr<NamespaceA::SecondTableInAT> _o = flatbuffers::unique_ptr<NamespaceA::SecondTableInAT>(new SecondTableInAT());
+ auto _o = std::unique_ptr<SecondTableInAT>(new SecondTableInAT());
UnPackTo(_o.get(), _resolver);
return _o.release();
}
@@ -421,7 +504,7 @@
inline void SecondTableInA::UnPackTo(SecondTableInAT *_o, const flatbuffers::resolver_function_t *_resolver) const {
(void)_o;
(void)_resolver;
- { auto _e = refer_to_c(); if (_e) _o->refer_to_c = flatbuffers::unique_ptr<NamespaceC::TableInCT>(_e->UnPack(_resolver)); }
+ { auto _e = refer_to_c(); if (_e) { if(_o->refer_to_c) { _e->UnPackTo(_o->refer_to_c.get(), _resolver); } else { _o->refer_to_c = flatbuffers::unique_ptr<NamespaceC::TableInCT>(_e->UnPack(_resolver)); } } }
}
inline flatbuffers::Offset<SecondTableInA> SecondTableInA::Pack(flatbuffers::FlatBufferBuilder &_fbb, const SecondTableInAT* _o, const flatbuffers::rehasher_function_t *_rehasher) {
@@ -442,20 +525,25 @@
static const flatbuffers::TypeCode type_codes[] = {
{ flatbuffers::ET_SEQUENCE, 0, 0 },
{ flatbuffers::ET_CHAR, 0, 1 },
- { flatbuffers::ET_SEQUENCE, 0, 2 }
+ { flatbuffers::ET_UTYPE, 0, 2 },
+ { flatbuffers::ET_SEQUENCE, 0, 2 },
+ { flatbuffers::ET_SEQUENCE, 0, 3 }
};
static const flatbuffers::TypeFunction type_refs[] = {
NamespaceA::NamespaceB::TableInNestedNSTypeTable,
NamespaceA::NamespaceB::EnumInNestedNSTypeTable,
+ NamespaceA::NamespaceB::UnionInNestedNSTypeTable,
NamespaceA::NamespaceB::StructInNestedNSTypeTable
};
static const char * const names[] = {
"foo_table",
"foo_enum",
+ "foo_union_type",
+ "foo_union",
"foo_struct"
};
static const flatbuffers::TypeTable tt = {
- flatbuffers::ST_TABLE, 3, type_codes, type_refs, nullptr, nullptr, names
+ flatbuffers::ST_TABLE, 5, type_codes, type_refs, nullptr, nullptr, names
};
return &tt;
}
diff --git a/tests/namespace_test/namespace_test2_generated.js b/tests/namespace_test/namespace_test2_generated.js
deleted file mode 100644
index 9b2668c..0000000
--- a/tests/namespace_test/namespace_test2_generated.js
+++ /dev/null
@@ -1,354 +0,0 @@
-// automatically generated by the FlatBuffers compiler, do not modify
-
-/**
- * @const
- * @namespace
- */
-var NamespaceA = NamespaceA || {};
-
-/**
- * @const
- * @namespace
- */
-NamespaceA.NamespaceB = NamespaceA.NamespaceB || {};
-
-/**
- * @const
- * @namespace
- */
-var NamespaceC = NamespaceC || {};
-
-/**
- * @constructor
- */
-NamespaceA.TableInFirstNS = function() {
- /**
- * @type {flatbuffers.ByteBuffer}
- */
- this.bb = null;
-
- /**
- * @type {number}
- */
- this.bb_pos = 0;
-};
-
-/**
- * @param {number} i
- * @param {flatbuffers.ByteBuffer} bb
- * @returns {NamespaceA.TableInFirstNS}
- */
-NamespaceA.TableInFirstNS.prototype.__init = function(i, bb) {
- this.bb_pos = i;
- this.bb = bb;
- return this;
-};
-
-/**
- * @param {flatbuffers.ByteBuffer} bb
- * @param {NamespaceA.TableInFirstNS=} obj
- * @returns {NamespaceA.TableInFirstNS}
- */
-NamespaceA.TableInFirstNS.getRootAsTableInFirstNS = function(bb, obj) {
- return (obj || new NamespaceA.TableInFirstNS).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param {flatbuffers.ByteBuffer} bb
- * @param {NamespaceA.TableInFirstNS=} obj
- * @returns {NamespaceA.TableInFirstNS}
- */
-NamespaceA.TableInFirstNS.getSizePrefixedRootAsTableInFirstNS = function(bb, obj) {
- bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
- return (obj || new NamespaceA.TableInFirstNS).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param {NamespaceA.NamespaceB.TableInNestedNS=} obj
- * @returns {NamespaceA.NamespaceB.TableInNestedNS|null}
- */
-NamespaceA.TableInFirstNS.prototype.fooTable = function(obj) {
- var offset = this.bb.__offset(this.bb_pos, 4);
- return offset ? (obj || new NamespaceA.NamespaceB.TableInNestedNS).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null;
-};
-
-/**
- * @returns {NamespaceA.NamespaceB.EnumInNestedNS}
- */
-NamespaceA.TableInFirstNS.prototype.fooEnum = function() {
- var offset = this.bb.__offset(this.bb_pos, 6);
- return offset ? /** @type {NamespaceA.NamespaceB.EnumInNestedNS} */ (this.bb.readInt8(this.bb_pos + offset)) : NamespaceA.NamespaceB.EnumInNestedNS.A;
-};
-
-/**
- * @param {NamespaceA.NamespaceB.EnumInNestedNS} value
- * @returns {boolean}
- */
-NamespaceA.TableInFirstNS.prototype.mutate_foo_enum = function(value) {
- var offset = this.bb.__offset(this.bb_pos, 6);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb.writeInt8(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @param {NamespaceA.NamespaceB.StructInNestedNS=} obj
- * @returns {NamespaceA.NamespaceB.StructInNestedNS|null}
- */
-NamespaceA.TableInFirstNS.prototype.fooStruct = function(obj) {
- var offset = this.bb.__offset(this.bb_pos, 8);
- return offset ? (obj || new NamespaceA.NamespaceB.StructInNestedNS).__init(this.bb_pos + offset, this.bb) : null;
-};
-
-/**
- * @returns {string}
- */
-NamespaceA.TableInFirstNS.getFullyQualifiedName = function() {
- return 'NamespaceA.TableInFirstNS';
-}
-
-/**
- * @param {flatbuffers.Builder} builder
- */
-NamespaceA.TableInFirstNS.startTableInFirstNS = function(builder) {
- builder.startObject(3);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Offset} fooTableOffset
- */
-NamespaceA.TableInFirstNS.addFooTable = function(builder, fooTableOffset) {
- builder.addFieldOffset(0, fooTableOffset, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {NamespaceA.NamespaceB.EnumInNestedNS} fooEnum
- */
-NamespaceA.TableInFirstNS.addFooEnum = function(builder, fooEnum) {
- builder.addFieldInt8(1, fooEnum, NamespaceA.NamespaceB.EnumInNestedNS.A);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Offset} fooStructOffset
- */
-NamespaceA.TableInFirstNS.addFooStruct = function(builder, fooStructOffset) {
- builder.addFieldStruct(2, fooStructOffset, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @returns {flatbuffers.Offset}
- */
-NamespaceA.TableInFirstNS.endTableInFirstNS = function(builder) {
- var offset = builder.endObject();
- return offset;
-};
-
-/**
- * @constructor
- */
-NamespaceC.TableInC = function() {
- /**
- * @type {flatbuffers.ByteBuffer}
- */
- this.bb = null;
-
- /**
- * @type {number}
- */
- this.bb_pos = 0;
-};
-
-/**
- * @param {number} i
- * @param {flatbuffers.ByteBuffer} bb
- * @returns {NamespaceC.TableInC}
- */
-NamespaceC.TableInC.prototype.__init = function(i, bb) {
- this.bb_pos = i;
- this.bb = bb;
- return this;
-};
-
-/**
- * @param {flatbuffers.ByteBuffer} bb
- * @param {NamespaceC.TableInC=} obj
- * @returns {NamespaceC.TableInC}
- */
-NamespaceC.TableInC.getRootAsTableInC = function(bb, obj) {
- return (obj || new NamespaceC.TableInC).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param {flatbuffers.ByteBuffer} bb
- * @param {NamespaceC.TableInC=} obj
- * @returns {NamespaceC.TableInC}
- */
-NamespaceC.TableInC.getSizePrefixedRootAsTableInC = function(bb, obj) {
- bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
- return (obj || new NamespaceC.TableInC).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param {NamespaceA.TableInFirstNS=} obj
- * @returns {NamespaceA.TableInFirstNS|null}
- */
-NamespaceC.TableInC.prototype.referToA1 = function(obj) {
- var offset = this.bb.__offset(this.bb_pos, 4);
- return offset ? (obj || new NamespaceA.TableInFirstNS).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null;
-};
-
-/**
- * @param {NamespaceA.SecondTableInA=} obj
- * @returns {NamespaceA.SecondTableInA|null}
- */
-NamespaceC.TableInC.prototype.referToA2 = function(obj) {
- var offset = this.bb.__offset(this.bb_pos, 6);
- return offset ? (obj || new NamespaceA.SecondTableInA).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null;
-};
-
-/**
- * @returns {string}
- */
-NamespaceC.TableInC.getFullyQualifiedName = function() {
- return 'NamespaceC.TableInC';
-}
-
-/**
- * @param {flatbuffers.Builder} builder
- */
-NamespaceC.TableInC.startTableInC = function(builder) {
- builder.startObject(2);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Offset} referToA1Offset
- */
-NamespaceC.TableInC.addReferToA1 = function(builder, referToA1Offset) {
- builder.addFieldOffset(0, referToA1Offset, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Offset} referToA2Offset
- */
-NamespaceC.TableInC.addReferToA2 = function(builder, referToA2Offset) {
- builder.addFieldOffset(1, referToA2Offset, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @returns {flatbuffers.Offset}
- */
-NamespaceC.TableInC.endTableInC = function(builder) {
- var offset = builder.endObject();
- return offset;
-};
-
-/**
- * @constructor
- */
-NamespaceA.SecondTableInA = function() {
- /**
- * @type {flatbuffers.ByteBuffer}
- */
- this.bb = null;
-
- /**
- * @type {number}
- */
- this.bb_pos = 0;
-};
-
-/**
- * @param {number} i
- * @param {flatbuffers.ByteBuffer} bb
- * @returns {NamespaceA.SecondTableInA}
- */
-NamespaceA.SecondTableInA.prototype.__init = function(i, bb) {
- this.bb_pos = i;
- this.bb = bb;
- return this;
-};
-
-/**
- * @param {flatbuffers.ByteBuffer} bb
- * @param {NamespaceA.SecondTableInA=} obj
- * @returns {NamespaceA.SecondTableInA}
- */
-NamespaceA.SecondTableInA.getRootAsSecondTableInA = function(bb, obj) {
- return (obj || new NamespaceA.SecondTableInA).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param {flatbuffers.ByteBuffer} bb
- * @param {NamespaceA.SecondTableInA=} obj
- * @returns {NamespaceA.SecondTableInA}
- */
-NamespaceA.SecondTableInA.getSizePrefixedRootAsSecondTableInA = function(bb, obj) {
- bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
- return (obj || new NamespaceA.SecondTableInA).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param {NamespaceC.TableInC=} obj
- * @returns {NamespaceC.TableInC|null}
- */
-NamespaceA.SecondTableInA.prototype.referToC = function(obj) {
- var offset = this.bb.__offset(this.bb_pos, 4);
- return offset ? (obj || new NamespaceC.TableInC).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null;
-};
-
-/**
- * @returns {string}
- */
-NamespaceA.SecondTableInA.getFullyQualifiedName = function() {
- return 'NamespaceA.SecondTableInA';
-}
-
-/**
- * @param {flatbuffers.Builder} builder
- */
-NamespaceA.SecondTableInA.startSecondTableInA = function(builder) {
- builder.startObject(1);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Offset} referToCOffset
- */
-NamespaceA.SecondTableInA.addReferToC = function(builder, referToCOffset) {
- builder.addFieldOffset(0, referToCOffset, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @returns {flatbuffers.Offset}
- */
-NamespaceA.SecondTableInA.endSecondTableInA = function(builder) {
- var offset = builder.endObject();
- return offset;
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Offset} referToCOffset
- * @returns {flatbuffers.Offset}
- */
-NamespaceA.SecondTableInA.createSecondTableInA = function(builder, referToCOffset) {
- NamespaceA.SecondTableInA.startSecondTableInA(builder);
- NamespaceA.SecondTableInA.addReferToC(builder, referToCOffset);
- return NamespaceA.SecondTableInA.endSecondTableInA(builder);
-}
-
-// Exports for Node.js and RequireJS
-this.NamespaceA = NamespaceA;
-this.NamespaceC = NamespaceC;
diff --git a/tests/namespace_test/namespace_test2_generated.lobster b/tests/namespace_test/namespace_test2_generated.lobster
index 4383e68..3820928 100644
--- a/tests/namespace_test/namespace_test2_generated.lobster
+++ b/tests/namespace_test/namespace_test2_generated.lobster
@@ -19,8 +19,12 @@
return if o: NamespaceA_NamespaceB_TableInNestedNS { buf_, o } else: nil
def foo_enum():
return EnumInNestedNS(buf_.flatbuffers_field_int8(pos_, 6, 0))
+ def foo_union_type():
+ return UnionInNestedNS(buf_.flatbuffers_field_int8(pos_, 8, 0))
+ def foo_union_as_TableInNestedNS():
+ return NamespaceA_NamespaceB_TableInNestedNS { buf_, buf_.flatbuffers_field_table(pos_, 10) }
def foo_struct():
- let o = buf_.flatbuffers_field_struct(pos_, 8)
+ let o = buf_.flatbuffers_field_struct(pos_, 12)
return if o: NamespaceA_NamespaceB_StructInNestedNS { buf_, o } else: nil
def GetRootAsTableInFirstNS(buf:string): return TableInFirstNS { buf, buf.flatbuffers_indirect(0) }
@@ -28,7 +32,7 @@
struct TableInFirstNSBuilder:
b_:flatbuffers_builder
def start():
- b_.StartObject(3)
+ b_.StartObject(5)
return this
def add_foo_table(foo_table:flatbuffers_offset):
b_.PrependUOffsetTRelativeSlot(0, foo_table)
@@ -36,8 +40,14 @@
def add_foo_enum(foo_enum:EnumInNestedNS):
b_.PrependInt8Slot(1, foo_enum, 0)
return this
+ def add_foo_union_type(foo_union_type:UnionInNestedNS):
+ b_.PrependUint8Slot(2, foo_union_type, 0)
+ return this
+ def add_foo_union(foo_union:flatbuffers_offset):
+ b_.PrependUOffsetTRelativeSlot(3, foo_union)
+ return this
def add_foo_struct(foo_struct:flatbuffers_offset):
- b_.PrependStructSlot(2, foo_struct)
+ b_.PrependStructSlot(4, foo_struct)
return this
def end():
return b_.EndObject()
diff --git a/tests/namespace_test/namespace_test2_generated.rs b/tests/namespace_test/namespace_test2_generated.rs
deleted file mode 100644
index b1d84cf..0000000
--- a/tests/namespace_test/namespace_test2_generated.rs
+++ /dev/null
@@ -1,330 +0,0 @@
-// automatically generated by the FlatBuffers compiler, do not modify
-
-
-#![allow(unused_imports, dead_code)]
-
-use crate::namespace_test1_generated::*;
-use std::mem;
-use std::cmp::Ordering;
-
-extern crate flatbuffers;
-use self::flatbuffers::EndianScalar;
-
-#[allow(unused_imports, dead_code)]
-pub mod namespace_a {
-
- use crate::namespace_test1_generated::*;
- use std::mem;
- use std::cmp::Ordering;
-
- extern crate flatbuffers;
- use self::flatbuffers::EndianScalar;
-
-pub enum TableInFirstNSOffset {}
-#[derive(Copy, Clone, PartialEq)]
-
-pub struct TableInFirstNS<'a> {
- pub _tab: flatbuffers::Table<'a>,
-}
-
-impl<'a> flatbuffers::Follow<'a> for TableInFirstNS<'a> {
- type Inner = TableInFirstNS<'a>;
- #[inline]
- fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
- Self { _tab: flatbuffers::Table { buf, loc } }
- }
-}
-
-impl<'a> TableInFirstNS<'a> {
- pub const fn get_fully_qualified_name() -> &'static str {
- "NamespaceA.TableInFirstNS"
- }
-
- #[inline]
- pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
- TableInFirstNS {
- _tab: table,
- }
- }
- #[allow(unused_mut)]
- pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
- _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
- args: &'args TableInFirstNSArgs<'args>) -> flatbuffers::WIPOffset<TableInFirstNS<'bldr>> {
- let mut builder = TableInFirstNSBuilder::new(_fbb);
- if let Some(x) = args.foo_struct { builder.add_foo_struct(x); }
- if let Some(x) = args.foo_table { builder.add_foo_table(x); }
- builder.add_foo_enum(args.foo_enum);
- builder.finish()
- }
-
- pub const VT_FOO_TABLE: flatbuffers::VOffsetT = 4;
- pub const VT_FOO_ENUM: flatbuffers::VOffsetT = 6;
- pub const VT_FOO_STRUCT: flatbuffers::VOffsetT = 8;
-
- #[inline]
- pub fn foo_table(&self) -> Option<namespace_b::TableInNestedNS<'a>> {
- self._tab.get::<flatbuffers::ForwardsUOffset<namespace_b::TableInNestedNS<'a>>>(TableInFirstNS::VT_FOO_TABLE, None)
- }
- #[inline]
- pub fn foo_enum(&self) -> namespace_b::EnumInNestedNS {
- self._tab.get::<namespace_b::EnumInNestedNS>(TableInFirstNS::VT_FOO_ENUM, Some(namespace_b::EnumInNestedNS::A)).unwrap()
- }
- #[inline]
- pub fn foo_struct(&self) -> Option<&'a namespace_b::StructInNestedNS> {
- self._tab.get::<namespace_b::StructInNestedNS>(TableInFirstNS::VT_FOO_STRUCT, None)
- }
-}
-
-pub struct TableInFirstNSArgs<'a> {
- pub foo_table: Option<flatbuffers::WIPOffset<namespace_b::TableInNestedNS<'a>>>,
- pub foo_enum: namespace_b::EnumInNestedNS,
- pub foo_struct: Option<&'a namespace_b::StructInNestedNS>,
-}
-impl<'a> Default for TableInFirstNSArgs<'a> {
- #[inline]
- fn default() -> Self {
- TableInFirstNSArgs {
- foo_table: None,
- foo_enum: namespace_b::EnumInNestedNS::A,
- foo_struct: None,
- }
- }
-}
-pub struct TableInFirstNSBuilder<'a: 'b, 'b> {
- fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
- start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
-}
-impl<'a: 'b, 'b> TableInFirstNSBuilder<'a, 'b> {
- #[inline]
- pub fn add_foo_table(&mut self, foo_table: flatbuffers::WIPOffset<namespace_b::TableInNestedNS<'b >>) {
- self.fbb_.push_slot_always::<flatbuffers::WIPOffset<namespace_b::TableInNestedNS>>(TableInFirstNS::VT_FOO_TABLE, foo_table);
- }
- #[inline]
- pub fn add_foo_enum(&mut self, foo_enum: namespace_b::EnumInNestedNS) {
- self.fbb_.push_slot::<namespace_b::EnumInNestedNS>(TableInFirstNS::VT_FOO_ENUM, foo_enum, namespace_b::EnumInNestedNS::A);
- }
- #[inline]
- pub fn add_foo_struct(&mut self, foo_struct: &namespace_b::StructInNestedNS) {
- self.fbb_.push_slot_always::<&namespace_b::StructInNestedNS>(TableInFirstNS::VT_FOO_STRUCT, foo_struct);
- }
- #[inline]
- pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> TableInFirstNSBuilder<'a, 'b> {
- let start = _fbb.start_table();
- TableInFirstNSBuilder {
- fbb_: _fbb,
- start_: start,
- }
- }
- #[inline]
- pub fn finish(self) -> flatbuffers::WIPOffset<TableInFirstNS<'a>> {
- let o = self.fbb_.end_table(self.start_);
- flatbuffers::WIPOffset::new(o.value())
- }
-}
-
-impl std::fmt::Debug for TableInFirstNS<'_> {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- let mut ds = f.debug_struct("TableInFirstNS");
- ds.field("foo_table", &self.foo_table());
- ds.field("foo_enum", &self.foo_enum());
- ds.field("foo_struct", &self.foo_struct());
- ds.finish()
- }
-}
-pub enum SecondTableInAOffset {}
-#[derive(Copy, Clone, PartialEq)]
-
-pub struct SecondTableInA<'a> {
- pub _tab: flatbuffers::Table<'a>,
-}
-
-impl<'a> flatbuffers::Follow<'a> for SecondTableInA<'a> {
- type Inner = SecondTableInA<'a>;
- #[inline]
- fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
- Self { _tab: flatbuffers::Table { buf, loc } }
- }
-}
-
-impl<'a> SecondTableInA<'a> {
- pub const fn get_fully_qualified_name() -> &'static str {
- "NamespaceA.SecondTableInA"
- }
-
- #[inline]
- pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
- SecondTableInA {
- _tab: table,
- }
- }
- #[allow(unused_mut)]
- pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
- _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
- args: &'args SecondTableInAArgs<'args>) -> flatbuffers::WIPOffset<SecondTableInA<'bldr>> {
- let mut builder = SecondTableInABuilder::new(_fbb);
- if let Some(x) = args.refer_to_c { builder.add_refer_to_c(x); }
- builder.finish()
- }
-
- pub const VT_REFER_TO_C: flatbuffers::VOffsetT = 4;
-
- #[inline]
- pub fn refer_to_c(&self) -> Option<super::namespace_c::TableInC<'a>> {
- self._tab.get::<flatbuffers::ForwardsUOffset<super::namespace_c::TableInC<'a>>>(SecondTableInA::VT_REFER_TO_C, None)
- }
-}
-
-pub struct SecondTableInAArgs<'a> {
- pub refer_to_c: Option<flatbuffers::WIPOffset<super::namespace_c::TableInC<'a>>>,
-}
-impl<'a> Default for SecondTableInAArgs<'a> {
- #[inline]
- fn default() -> Self {
- SecondTableInAArgs {
- refer_to_c: None,
- }
- }
-}
-pub struct SecondTableInABuilder<'a: 'b, 'b> {
- fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
- start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
-}
-impl<'a: 'b, 'b> SecondTableInABuilder<'a, 'b> {
- #[inline]
- pub fn add_refer_to_c(&mut self, refer_to_c: flatbuffers::WIPOffset<super::namespace_c::TableInC<'b >>) {
- self.fbb_.push_slot_always::<flatbuffers::WIPOffset<super::namespace_c::TableInC>>(SecondTableInA::VT_REFER_TO_C, refer_to_c);
- }
- #[inline]
- pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> SecondTableInABuilder<'a, 'b> {
- let start = _fbb.start_table();
- SecondTableInABuilder {
- fbb_: _fbb,
- start_: start,
- }
- }
- #[inline]
- pub fn finish(self) -> flatbuffers::WIPOffset<SecondTableInA<'a>> {
- let o = self.fbb_.end_table(self.start_);
- flatbuffers::WIPOffset::new(o.value())
- }
-}
-
-impl std::fmt::Debug for SecondTableInA<'_> {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- let mut ds = f.debug_struct("SecondTableInA");
- ds.field("refer_to_c", &self.refer_to_c());
- ds.finish()
- }
-}
-} // pub mod NamespaceA
-
-#[allow(unused_imports, dead_code)]
-pub mod namespace_c {
-
- use crate::namespace_test1_generated::*;
- use std::mem;
- use std::cmp::Ordering;
-
- extern crate flatbuffers;
- use self::flatbuffers::EndianScalar;
-
-pub enum TableInCOffset {}
-#[derive(Copy, Clone, PartialEq)]
-
-pub struct TableInC<'a> {
- pub _tab: flatbuffers::Table<'a>,
-}
-
-impl<'a> flatbuffers::Follow<'a> for TableInC<'a> {
- type Inner = TableInC<'a>;
- #[inline]
- fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
- Self { _tab: flatbuffers::Table { buf, loc } }
- }
-}
-
-impl<'a> TableInC<'a> {
- pub const fn get_fully_qualified_name() -> &'static str {
- "NamespaceC.TableInC"
- }
-
- #[inline]
- pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
- TableInC {
- _tab: table,
- }
- }
- #[allow(unused_mut)]
- pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
- _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
- args: &'args TableInCArgs<'args>) -> flatbuffers::WIPOffset<TableInC<'bldr>> {
- let mut builder = TableInCBuilder::new(_fbb);
- if let Some(x) = args.refer_to_a2 { builder.add_refer_to_a2(x); }
- if let Some(x) = args.refer_to_a1 { builder.add_refer_to_a1(x); }
- builder.finish()
- }
-
- pub const VT_REFER_TO_A1: flatbuffers::VOffsetT = 4;
- pub const VT_REFER_TO_A2: flatbuffers::VOffsetT = 6;
-
- #[inline]
- pub fn refer_to_a1(&self) -> Option<super::namespace_a::TableInFirstNS<'a>> {
- self._tab.get::<flatbuffers::ForwardsUOffset<super::namespace_a::TableInFirstNS<'a>>>(TableInC::VT_REFER_TO_A1, None)
- }
- #[inline]
- pub fn refer_to_a2(&self) -> Option<super::namespace_a::SecondTableInA<'a>> {
- self._tab.get::<flatbuffers::ForwardsUOffset<super::namespace_a::SecondTableInA<'a>>>(TableInC::VT_REFER_TO_A2, None)
- }
-}
-
-pub struct TableInCArgs<'a> {
- pub refer_to_a1: Option<flatbuffers::WIPOffset<super::namespace_a::TableInFirstNS<'a>>>,
- pub refer_to_a2: Option<flatbuffers::WIPOffset<super::namespace_a::SecondTableInA<'a>>>,
-}
-impl<'a> Default for TableInCArgs<'a> {
- #[inline]
- fn default() -> Self {
- TableInCArgs {
- refer_to_a1: None,
- refer_to_a2: None,
- }
- }
-}
-pub struct TableInCBuilder<'a: 'b, 'b> {
- fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
- start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
-}
-impl<'a: 'b, 'b> TableInCBuilder<'a, 'b> {
- #[inline]
- pub fn add_refer_to_a1(&mut self, refer_to_a1: flatbuffers::WIPOffset<super::namespace_a::TableInFirstNS<'b >>) {
- self.fbb_.push_slot_always::<flatbuffers::WIPOffset<super::namespace_a::TableInFirstNS>>(TableInC::VT_REFER_TO_A1, refer_to_a1);
- }
- #[inline]
- pub fn add_refer_to_a2(&mut self, refer_to_a2: flatbuffers::WIPOffset<super::namespace_a::SecondTableInA<'b >>) {
- self.fbb_.push_slot_always::<flatbuffers::WIPOffset<super::namespace_a::SecondTableInA>>(TableInC::VT_REFER_TO_A2, refer_to_a2);
- }
- #[inline]
- pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> TableInCBuilder<'a, 'b> {
- let start = _fbb.start_table();
- TableInCBuilder {
- fbb_: _fbb,
- start_: start,
- }
- }
- #[inline]
- pub fn finish(self) -> flatbuffers::WIPOffset<TableInC<'a>> {
- let o = self.fbb_.end_table(self.start_);
- flatbuffers::WIPOffset::new(o.value())
- }
-}
-
-impl std::fmt::Debug for TableInC<'_> {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- let mut ds = f.debug_struct("TableInC");
- ds.field("refer_to_a1", &self.refer_to_a1());
- ds.field("refer_to_a2", &self.refer_to_a2());
- ds.finish()
- }
-}
-} // pub mod NamespaceC
-
diff --git a/tests/namespace_test/namespace_test2_generated.ts b/tests/namespace_test/namespace_test2_generated.ts
deleted file mode 100644
index bd3c903..0000000
--- a/tests/namespace_test/namespace_test2_generated.ts
+++ /dev/null
@@ -1,438 +0,0 @@
-// automatically generated by the FlatBuffers compiler, do not modify
-
-import * as NS8755221360535654258 from "./namespace_test1_generated";
-/**
- * @constructor
- */
-export namespace NamespaceA{
-export class TableInFirstNS {
- bb: flatbuffers.ByteBuffer|null = null;
-
- bb_pos:number = 0;
-/**
- * @param number i
- * @param flatbuffers.ByteBuffer bb
- * @returns TableInFirstNS
- */
-__init(i:number, bb:flatbuffers.ByteBuffer):TableInFirstNS {
- this.bb_pos = i;
- this.bb = bb;
- return this;
-};
-
-/**
- * @param flatbuffers.ByteBuffer bb
- * @param TableInFirstNS= obj
- * @returns TableInFirstNS
- */
-static getRootAsTableInFirstNS(bb:flatbuffers.ByteBuffer, obj?:TableInFirstNS):TableInFirstNS {
- return (obj || new TableInFirstNS()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param flatbuffers.ByteBuffer bb
- * @param TableInFirstNS= obj
- * @returns TableInFirstNS
- */
-static getSizePrefixedRootAsTableInFirstNS(bb:flatbuffers.ByteBuffer, obj?:TableInFirstNS):TableInFirstNS {
- bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
- return (obj || new TableInFirstNS()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param NamespaceA.NamespaceB.TableInNestedNS= obj
- * @returns NamespaceA.NamespaceB.TableInNestedNS|null
- */
-fooTable(obj?:NS8755221360535654258.NamespaceA.NamespaceB.TableInNestedNS):NS8755221360535654258.NamespaceA.NamespaceB.TableInNestedNS|null {
- var offset = this.bb!.__offset(this.bb_pos, 4);
- return offset ? (obj || new NS8755221360535654258.NamespaceA.NamespaceB.TableInNestedNS()).__init(this.bb!.__indirect(this.bb_pos + offset), this.bb!) : null;
-};
-
-/**
- * @returns NamespaceA.NamespaceB.EnumInNestedNS
- */
-fooEnum():NS8755221360535654258.NamespaceA.NamespaceB.EnumInNestedNS {
- var offset = this.bb!.__offset(this.bb_pos, 6);
- return offset ? /** */ (this.bb!.readInt8(this.bb_pos + offset)) : NS8755221360535654258.NamespaceA.NamespaceB.EnumInNestedNS.A;
-};
-
-/**
- * @param NamespaceA.NamespaceB.EnumInNestedNS value
- * @returns boolean
- */
-mutate_foo_enum(value:NS8755221360535654258.NamespaceA.NamespaceB.EnumInNestedNS):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 6);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb!.writeInt8(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @param NamespaceA.NamespaceB.StructInNestedNS= obj
- * @returns NamespaceA.NamespaceB.StructInNestedNS|null
- */
-fooStruct(obj?:NS8755221360535654258.NamespaceA.NamespaceB.StructInNestedNS):NS8755221360535654258.NamespaceA.NamespaceB.StructInNestedNS|null {
- var offset = this.bb!.__offset(this.bb_pos, 8);
- return offset ? (obj || new NS8755221360535654258.NamespaceA.NamespaceB.StructInNestedNS()).__init(this.bb_pos + offset, this.bb!) : null;
-};
-
-/**
- * @returns string
- */
-static getFullyQualifiedName():string {
- return 'NamespaceA.TableInFirstNS';
-}
-
-/**
- * @param flatbuffers.Builder builder
- */
-static startTableInFirstNS(builder:flatbuffers.Builder) {
- builder.startObject(3);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Offset fooTableOffset
- */
-static addFooTable(builder:flatbuffers.Builder, fooTableOffset:flatbuffers.Offset) {
- builder.addFieldOffset(0, fooTableOffset, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param NamespaceA.NamespaceB.EnumInNestedNS fooEnum
- */
-static addFooEnum(builder:flatbuffers.Builder, fooEnum:NS8755221360535654258.NamespaceA.NamespaceB.EnumInNestedNS) {
- builder.addFieldInt8(1, fooEnum, NS8755221360535654258.NamespaceA.NamespaceB.EnumInNestedNS.A);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Offset fooStructOffset
- */
-static addFooStruct(builder:flatbuffers.Builder, fooStructOffset:flatbuffers.Offset) {
- builder.addFieldStruct(2, fooStructOffset, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @returns flatbuffers.Offset
- */
-static endTableInFirstNS(builder:flatbuffers.Builder):flatbuffers.Offset {
- var offset = builder.endObject();
- return offset;
-};
-
-
-/**
- * @returns TableInFirstNST
- */
-unpack(): TableInFirstNST {
- return new TableInFirstNST(
- (this.fooTable() !== null ? this.fooTable()!.unpack() : null),
- this.fooEnum(),
- (this.fooStruct() !== null ? this.fooStruct()!.unpack() : null)
- );
-};
-
-/**
- * @param TableInFirstNST _o
- */
-unpackTo(_o: TableInFirstNST): void {
- _o.fooTable = (this.fooTable() !== null ? this.fooTable()!.unpack() : null);
- _o.fooEnum = this.fooEnum();
- _o.fooStruct = (this.fooStruct() !== null ? this.fooStruct()!.unpack() : null);
-};
-}
-
-export class TableInFirstNST {
-/**
- * @constructor
- * @param NS8755221360535654258.NamespaceA.NamespaceB.TableInNestedNST|null fooTable
- * @param NS8755221360535654258.NamespaceA.NamespaceB.EnumInNestedNS fooEnum
- * @param NS8755221360535654258.NamespaceA.NamespaceB.StructInNestedNST|null fooStruct
- */
-constructor(
- public fooTable: NS8755221360535654258.NamespaceA.NamespaceB.TableInNestedNST|null = null,
- public fooEnum: NS8755221360535654258.NamespaceA.NamespaceB.EnumInNestedNS = NS8755221360535654258.NamespaceA.NamespaceB.EnumInNestedNS.A,
- public fooStruct: NS8755221360535654258.NamespaceA.NamespaceB.StructInNestedNST|null = null
-){};
-
-/**
- * @param flatbuffers.Builder builder
- * @returns flatbuffers.Offset
- */
-pack(builder:flatbuffers.Builder): flatbuffers.Offset {
- NamespaceA.TableInFirstNS.start(builder);
- NamespaceA.TableInFirstNS.addFooTable(builder, (this.fooTable !== null ? this.fooTable!.pack(builder) : 0));
- NamespaceA.TableInFirstNS.addFooEnum(builder, this.fooEnum);
- NamespaceA.TableInFirstNS.addFooStruct(builder, (this.fooStruct !== null ? this.fooStruct!.pack(builder) : 0));
-
- return NamespaceA.TableInFirstNS.end(builder);
-};
-}
-}
-/**
- * @constructor
- */
-export namespace NamespaceC{
-export class TableInC {
- bb: flatbuffers.ByteBuffer|null = null;
-
- bb_pos:number = 0;
-/**
- * @param number i
- * @param flatbuffers.ByteBuffer bb
- * @returns TableInC
- */
-__init(i:number, bb:flatbuffers.ByteBuffer):TableInC {
- this.bb_pos = i;
- this.bb = bb;
- return this;
-};
-
-/**
- * @param flatbuffers.ByteBuffer bb
- * @param TableInC= obj
- * @returns TableInC
- */
-static getRootAsTableInC(bb:flatbuffers.ByteBuffer, obj?:TableInC):TableInC {
- return (obj || new TableInC()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param flatbuffers.ByteBuffer bb
- * @param TableInC= obj
- * @returns TableInC
- */
-static getSizePrefixedRootAsTableInC(bb:flatbuffers.ByteBuffer, obj?:TableInC):TableInC {
- bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
- return (obj || new TableInC()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param NamespaceA.TableInFirstNS= obj
- * @returns NamespaceA.TableInFirstNS|null
- */
-referToA1(obj?:NamespaceA.TableInFirstNS):NamespaceA.TableInFirstNS|null {
- var offset = this.bb!.__offset(this.bb_pos, 4);
- return offset ? (obj || new NamespaceA.TableInFirstNS()).__init(this.bb!.__indirect(this.bb_pos + offset), this.bb!) : null;
-};
-
-/**
- * @param NamespaceA.SecondTableInA= obj
- * @returns NamespaceA.SecondTableInA|null
- */
-referToA2(obj?:NamespaceA.SecondTableInA):NamespaceA.SecondTableInA|null {
- var offset = this.bb!.__offset(this.bb_pos, 6);
- return offset ? (obj || new NamespaceA.SecondTableInA()).__init(this.bb!.__indirect(this.bb_pos + offset), this.bb!) : null;
-};
-
-/**
- * @returns string
- */
-static getFullyQualifiedName():string {
- return 'NamespaceC.TableInC';
-}
-
-/**
- * @param flatbuffers.Builder builder
- */
-static startTableInC(builder:flatbuffers.Builder) {
- builder.startObject(2);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Offset referToA1Offset
- */
-static addReferToA1(builder:flatbuffers.Builder, referToA1Offset:flatbuffers.Offset) {
- builder.addFieldOffset(0, referToA1Offset, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Offset referToA2Offset
- */
-static addReferToA2(builder:flatbuffers.Builder, referToA2Offset:flatbuffers.Offset) {
- builder.addFieldOffset(1, referToA2Offset, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @returns flatbuffers.Offset
- */
-static endTableInC(builder:flatbuffers.Builder):flatbuffers.Offset {
- var offset = builder.endObject();
- return offset;
-};
-
-
-/**
- * @returns TableInCT
- */
-unpack(): TableInCT {
- return new TableInCT(
- (this.referToA1() !== null ? this.referToA1()!.unpack() : null),
- (this.referToA2() !== null ? this.referToA2()!.unpack() : null)
- );
-};
-
-/**
- * @param TableInCT _o
- */
-unpackTo(_o: TableInCT): void {
- _o.referToA1 = (this.referToA1() !== null ? this.referToA1()!.unpack() : null);
- _o.referToA2 = (this.referToA2() !== null ? this.referToA2()!.unpack() : null);
-};
-}
-
-export class TableInCT {
-/**
- * @constructor
- * @param NamespaceA.TableInFirstNST|null referToA1
- * @param NamespaceA.SecondTableInAT|null referToA2
- */
-constructor(
- public referToA1: NamespaceA.TableInFirstNST|null = null,
- public referToA2: NamespaceA.SecondTableInAT|null = null
-){};
-
-/**
- * @param flatbuffers.Builder builder
- * @returns flatbuffers.Offset
- */
-pack(builder:flatbuffers.Builder): flatbuffers.Offset {
- NamespaceC.TableInC.start(builder);
- NamespaceC.TableInC.addReferToA1(builder, (this.referToA1 !== null ? this.referToA1!.pack(builder) : 0));
- NamespaceC.TableInC.addReferToA2(builder, (this.referToA2 !== null ? this.referToA2!.pack(builder) : 0));
-
- return NamespaceC.TableInC.end(builder);
-};
-}
-}
-/**
- * @constructor
- */
-export namespace NamespaceA{
-export class SecondTableInA {
- bb: flatbuffers.ByteBuffer|null = null;
-
- bb_pos:number = 0;
-/**
- * @param number i
- * @param flatbuffers.ByteBuffer bb
- * @returns SecondTableInA
- */
-__init(i:number, bb:flatbuffers.ByteBuffer):SecondTableInA {
- this.bb_pos = i;
- this.bb = bb;
- return this;
-};
-
-/**
- * @param flatbuffers.ByteBuffer bb
- * @param SecondTableInA= obj
- * @returns SecondTableInA
- */
-static getRootAsSecondTableInA(bb:flatbuffers.ByteBuffer, obj?:SecondTableInA):SecondTableInA {
- return (obj || new SecondTableInA()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param flatbuffers.ByteBuffer bb
- * @param SecondTableInA= obj
- * @returns SecondTableInA
- */
-static getSizePrefixedRootAsSecondTableInA(bb:flatbuffers.ByteBuffer, obj?:SecondTableInA):SecondTableInA {
- bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
- return (obj || new SecondTableInA()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param NamespaceC.TableInC= obj
- * @returns NamespaceC.TableInC|null
- */
-referToC(obj?:NamespaceC.TableInC):NamespaceC.TableInC|null {
- var offset = this.bb!.__offset(this.bb_pos, 4);
- return offset ? (obj || new NamespaceC.TableInC()).__init(this.bb!.__indirect(this.bb_pos + offset), this.bb!) : null;
-};
-
-/**
- * @returns string
- */
-static getFullyQualifiedName():string {
- return 'NamespaceA.SecondTableInA';
-}
-
-/**
- * @param flatbuffers.Builder builder
- */
-static startSecondTableInA(builder:flatbuffers.Builder) {
- builder.startObject(1);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Offset referToCOffset
- */
-static addReferToC(builder:flatbuffers.Builder, referToCOffset:flatbuffers.Offset) {
- builder.addFieldOffset(0, referToCOffset, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @returns flatbuffers.Offset
- */
-static endSecondTableInA(builder:flatbuffers.Builder):flatbuffers.Offset {
- var offset = builder.endObject();
- return offset;
-};
-
-static createSecondTableInA(builder:flatbuffers.Builder, referToCOffset:flatbuffers.Offset):flatbuffers.Offset {
- SecondTableInA.startSecondTableInA(builder);
- SecondTableInA.addReferToC(builder, referToCOffset);
- return SecondTableInA.endSecondTableInA(builder);
-}
-
-/**
- * @returns SecondTableInAT
- */
-unpack(): SecondTableInAT {
- return new SecondTableInAT(
- (this.referToC() !== null ? this.referToC()!.unpack() : null)
- );
-};
-
-/**
- * @param SecondTableInAT _o
- */
-unpackTo(_o: SecondTableInAT): void {
- _o.referToC = (this.referToC() !== null ? this.referToC()!.unpack() : null);
-};
-}
-
-export class SecondTableInAT {
-/**
- * @constructor
- * @param NamespaceC.TableInCT|null referToC
- */
-constructor(
- public referToC: NamespaceC.TableInCT|null = null
-){};
-
-/**
- * @param flatbuffers.Builder builder
- * @returns flatbuffers.Offset
- */
-pack(builder:flatbuffers.Builder): flatbuffers.Offset {
- return NamespaceA.SecondTableInA.createSecondTableInA(builder,
- (this.referToC !== null ? this.referToC!.pack(builder) : 0)
- );
-};
-}
-}
diff --git a/tests/namespace_test/namespace_test2_namespace_a_generated.dart b/tests/namespace_test/namespace_test2_namespace_a_generated.dart
index e10ad4b..070cb5f 100644
--- a/tests/namespace_test/namespace_test2_namespace_a_generated.dart
+++ b/tests/namespace_test/namespace_test2_namespace_a_generated.dart
@@ -1,5 +1,5 @@
// automatically generated by the FlatBuffers compiler, do not modify
-// ignore_for_file: unused_import, unused_field, unused_local_variable
+// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable
library namespace_a;
@@ -11,22 +11,76 @@
class TableInFirstNS {
TableInFirstNS._(this._bc, this._bcOffset);
factory TableInFirstNS(List<int> bytes) {
- fb.BufferContext rootRef = new fb.BufferContext.fromBytes(bytes);
+ final rootRef = fb.BufferContext.fromBytes(bytes);
return reader.read(rootRef, 0);
}
- static const fb.Reader<TableInFirstNS> reader = const _TableInFirstNSReader();
+ static const fb.Reader<TableInFirstNS> reader = _TableInFirstNSReader();
final fb.BufferContext _bc;
final int _bcOffset;
- namespace_a_namespace_b.TableInNestedNS get fooTable => namespace_a_namespace_b.TableInNestedNS.reader.vTableGet(_bc, _bcOffset, 4, null);
- EnumInNestedNS get fooEnum => new EnumInNestedNS.fromValue(const fb.Int8Reader().vTableGet(_bc, _bcOffset, 6, 0));
- namespace_a_namespace_b.StructInNestedNS get fooStruct => namespace_a_namespace_b.StructInNestedNS.reader.vTableGet(_bc, _bcOffset, 8, null);
+ namespace_a_namespace_b.TableInNestedNS? get fooTable => namespace_a_namespace_b.TableInNestedNS.reader.vTableGetNullable(_bc, _bcOffset, 4);
+ EnumInNestedNS get fooEnum => EnumInNestedNS.fromValue(const fb.Int8Reader().vTableGet(_bc, _bcOffset, 6, 0));
+ UnionInNestedNSTypeId? get fooUnionType => UnionInNestedNSTypeId._createOrNull(const fb.Uint8Reader().vTableGetNullable(_bc, _bcOffset, 8));
+ dynamic get fooUnion {
+ switch (fooUnionType?.value) {
+ case 1: return TableInNestedNS.reader.vTableGetNullable(_bc, _bcOffset, 10);
+ default: return null;
+ }
+ }
+ namespace_a_namespace_b.StructInNestedNS? get fooStruct => namespace_a_namespace_b.StructInNestedNS.reader.vTableGetNullable(_bc, _bcOffset, 12);
@override
String toString() {
- return 'TableInFirstNS{fooTable: $fooTable, fooEnum: $fooEnum, fooStruct: $fooStruct}';
+ return 'TableInFirstNS{fooTable: $fooTable, fooEnum: $fooEnum, fooUnionType: $fooUnionType, fooUnion: $fooUnion, fooStruct: $fooStruct}';
+ }
+
+ TableInFirstNST unpack() => TableInFirstNST(
+ fooTable: fooTable?.unpack(),
+ fooEnum: fooEnum,
+ fooUnionType: fooUnionType,
+ fooUnion: fooUnion,
+ fooStruct: fooStruct?.unpack());
+
+ static int pack(fb.Builder fbBuilder, TableInFirstNST? object) {
+ if (object == null) return 0;
+ return object.pack(fbBuilder);
+ }
+}
+
+class TableInFirstNST implements fb.Packable {
+ namespace_a_namespace_b.TableInNestedNST? fooTable;
+ EnumInNestedNS fooEnum;
+ UnionInNestedNSTypeId? fooUnionType;
+ dynamic fooUnion;
+ namespace_a_namespace_b.StructInNestedNST? fooStruct;
+
+ TableInFirstNST({
+ this.fooTable,
+ this.fooEnum = EnumInNestedNS.A,
+ this.fooUnionType,
+ this.fooUnion,
+ this.fooStruct});
+
+ @override
+ int pack(fb.Builder fbBuilder) {
+ final int? fooTableOffset = fooTable?.pack(fbBuilder);
+ final int? fooUnionOffset = fooUnion?.pack(fbBuilder);
+ fbBuilder.startTable(5);
+ fbBuilder.addOffset(0, fooTableOffset);
+ fbBuilder.addInt8(1, fooEnum.value);
+ fbBuilder.addUint8(2, fooUnionType?.value);
+ fbBuilder.addOffset(3, fooUnionOffset);
+ if (fooStruct != null) {
+ fbBuilder.addStruct(4, fooStruct!.pack(fbBuilder));
+ }
+ return fbBuilder.endTable();
+ }
+
+ @override
+ String toString() {
+ return 'TableInFirstNST{fooTable: $fooTable, fooEnum: $fooEnum, fooUnionType: $fooUnionType, fooUnion: $fooUnion, fooStruct: $fooStruct}';
}
}
@@ -35,30 +89,36 @@
@override
TableInFirstNS createObject(fb.BufferContext bc, int offset) =>
- new TableInFirstNS._(bc, offset);
+ TableInFirstNS._(bc, offset);
}
class TableInFirstNSBuilder {
- TableInFirstNSBuilder(this.fbBuilder) {
- assert(fbBuilder != null);
- }
+ TableInFirstNSBuilder(this.fbBuilder);
final fb.Builder fbBuilder;
void begin() {
- fbBuilder.startTable();
+ fbBuilder.startTable(5);
}
- int addFooTableOffset(int offset) {
+ int addFooTableOffset(int? offset) {
fbBuilder.addOffset(0, offset);
return fbBuilder.offset;
}
- int addFooEnum(EnumInNestedNS fooEnum) {
+ int addFooEnum(EnumInNestedNS? fooEnum) {
fbBuilder.addInt8(1, fooEnum?.value);
return fbBuilder.offset;
}
+ int addFooUnionType(UnionInNestedNSTypeId? fooUnionType) {
+ fbBuilder.addUint8(2, fooUnionType?.value);
+ return fbBuilder.offset;
+ }
+ int addFooUnionOffset(int? offset) {
+ fbBuilder.addOffset(3, offset);
+ return fbBuilder.offset;
+ }
int addFooStruct(int offset) {
- fbBuilder.addStruct(2, offset);
+ fbBuilder.addStruct(4, offset);
return fbBuilder.offset;
}
@@ -68,63 +128,95 @@
}
class TableInFirstNSObjectBuilder extends fb.ObjectBuilder {
- final namespace_a_namespace_b.TableInNestedNSObjectBuilder _fooTable;
- final EnumInNestedNS _fooEnum;
- final namespace_a_namespace_b.StructInNestedNSObjectBuilder _fooStruct;
+ final namespace_a_namespace_b.TableInNestedNSObjectBuilder? _fooTable;
+ final EnumInNestedNS? _fooEnum;
+ final UnionInNestedNSTypeId? _fooUnionType;
+ final dynamic _fooUnion;
+ final namespace_a_namespace_b.StructInNestedNSObjectBuilder? _fooStruct;
TableInFirstNSObjectBuilder({
- namespace_a_namespace_b.TableInNestedNSObjectBuilder fooTable,
- EnumInNestedNS fooEnum,
- namespace_a_namespace_b.StructInNestedNSObjectBuilder fooStruct,
+ namespace_a_namespace_b.TableInNestedNSObjectBuilder? fooTable,
+ EnumInNestedNS? fooEnum,
+ UnionInNestedNSTypeId? fooUnionType,
+ dynamic fooUnion,
+ namespace_a_namespace_b.StructInNestedNSObjectBuilder? fooStruct,
})
: _fooTable = fooTable,
_fooEnum = fooEnum,
+ _fooUnionType = fooUnionType,
+ _fooUnion = fooUnion,
_fooStruct = fooStruct;
/// Finish building, and store into the [fbBuilder].
@override
- int finish(
- fb.Builder fbBuilder) {
- assert(fbBuilder != null);
- final int fooTableOffset = _fooTable?.getOrCreateOffset(fbBuilder);
-
- fbBuilder.startTable();
- if (fooTableOffset != null) {
- fbBuilder.addOffset(0, fooTableOffset);
- }
+ int finish(fb.Builder fbBuilder) {
+ final int? fooTableOffset = _fooTable?.getOrCreateOffset(fbBuilder);
+ final int? fooUnionOffset = _fooUnion?.getOrCreateOffset(fbBuilder);
+ fbBuilder.startTable(5);
+ fbBuilder.addOffset(0, fooTableOffset);
fbBuilder.addInt8(1, _fooEnum?.value);
+ fbBuilder.addUint8(2, _fooUnionType?.value);
+ fbBuilder.addOffset(3, fooUnionOffset);
if (_fooStruct != null) {
- fbBuilder.addStruct(2, _fooStruct.finish(fbBuilder));
+ fbBuilder.addStruct(4, _fooStruct!.finish(fbBuilder));
}
return fbBuilder.endTable();
}
/// Convenience method to serialize to byte list.
@override
- Uint8List toBytes([String fileIdentifier]) {
- fb.Builder fbBuilder = new fb.Builder();
- int offset = finish(fbBuilder);
- return fbBuilder.finish(offset, fileIdentifier);
+ Uint8List toBytes([String? fileIdentifier]) {
+ final fbBuilder = fb.Builder(deduplicateTables: false);
+ fbBuilder.finish(finish(fbBuilder), fileIdentifier);
+ return fbBuilder.buffer;
}
}
class SecondTableInA {
SecondTableInA._(this._bc, this._bcOffset);
factory SecondTableInA(List<int> bytes) {
- fb.BufferContext rootRef = new fb.BufferContext.fromBytes(bytes);
+ final rootRef = fb.BufferContext.fromBytes(bytes);
return reader.read(rootRef, 0);
}
- static const fb.Reader<SecondTableInA> reader = const _SecondTableInAReader();
+ static const fb.Reader<SecondTableInA> reader = _SecondTableInAReader();
final fb.BufferContext _bc;
final int _bcOffset;
- namespace_c.TableInC get referToC => namespace_c.TableInC.reader.vTableGet(_bc, _bcOffset, 4, null);
+ namespace_c.TableInC? get referToC => namespace_c.TableInC.reader.vTableGetNullable(_bc, _bcOffset, 4);
@override
String toString() {
return 'SecondTableInA{referToC: $referToC}';
}
+
+ SecondTableInAT unpack() => SecondTableInAT(
+ referToC: referToC?.unpack());
+
+ static int pack(fb.Builder fbBuilder, SecondTableInAT? object) {
+ if (object == null) return 0;
+ return object.pack(fbBuilder);
+ }
+}
+
+class SecondTableInAT implements fb.Packable {
+ namespace_c.TableInCT? referToC;
+
+ SecondTableInAT({
+ this.referToC});
+
+ @override
+ int pack(fb.Builder fbBuilder) {
+ final int? referToCOffset = referToC?.pack(fbBuilder);
+ fbBuilder.startTable(1);
+ fbBuilder.addOffset(0, referToCOffset);
+ return fbBuilder.endTable();
+ }
+
+ @override
+ String toString() {
+ return 'SecondTableInAT{referToC: $referToC}';
+ }
}
class _SecondTableInAReader extends fb.TableReader<SecondTableInA> {
@@ -132,21 +224,19 @@
@override
SecondTableInA createObject(fb.BufferContext bc, int offset) =>
- new SecondTableInA._(bc, offset);
+ SecondTableInA._(bc, offset);
}
class SecondTableInABuilder {
- SecondTableInABuilder(this.fbBuilder) {
- assert(fbBuilder != null);
- }
+ SecondTableInABuilder(this.fbBuilder);
final fb.Builder fbBuilder;
void begin() {
- fbBuilder.startTable();
+ fbBuilder.startTable(1);
}
- int addReferToCOffset(int offset) {
+ int addReferToCOffset(int? offset) {
fbBuilder.addOffset(0, offset);
return fbBuilder.offset;
}
@@ -157,32 +247,27 @@
}
class SecondTableInAObjectBuilder extends fb.ObjectBuilder {
- final namespace_c.TableInCObjectBuilder _referToC;
+ final namespace_c.TableInCObjectBuilder? _referToC;
SecondTableInAObjectBuilder({
- namespace_c.TableInCObjectBuilder referToC,
+ namespace_c.TableInCObjectBuilder? referToC,
})
: _referToC = referToC;
/// Finish building, and store into the [fbBuilder].
@override
- int finish(
- fb.Builder fbBuilder) {
- assert(fbBuilder != null);
- final int referToCOffset = _referToC?.getOrCreateOffset(fbBuilder);
-
- fbBuilder.startTable();
- if (referToCOffset != null) {
- fbBuilder.addOffset(0, referToCOffset);
- }
+ int finish(fb.Builder fbBuilder) {
+ final int? referToCOffset = _referToC?.getOrCreateOffset(fbBuilder);
+ fbBuilder.startTable(1);
+ fbBuilder.addOffset(0, referToCOffset);
return fbBuilder.endTable();
}
/// Convenience method to serialize to byte list.
@override
- Uint8List toBytes([String fileIdentifier]) {
- fb.Builder fbBuilder = new fb.Builder();
- int offset = finish(fbBuilder);
- return fbBuilder.finish(offset, fileIdentifier);
+ Uint8List toBytes([String? fileIdentifier]) {
+ final fbBuilder = fb.Builder(deduplicateTables: false);
+ fbBuilder.finish(finish(fbBuilder), fileIdentifier);
+ return fbBuilder.buffer;
}
}
diff --git a/tests/namespace_test/namespace_test2_namespace_c_generated.dart b/tests/namespace_test/namespace_test2_namespace_c_generated.dart
index edb6ffc..1c30bb4 100644
--- a/tests/namespace_test/namespace_test2_namespace_c_generated.dart
+++ b/tests/namespace_test/namespace_test2_namespace_c_generated.dart
@@ -1,5 +1,5 @@
// automatically generated by the FlatBuffers compiler, do not modify
-// ignore_for_file: unused_import, unused_field, unused_local_variable
+// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable
library namespace_c;
@@ -11,22 +11,55 @@
class TableInC {
TableInC._(this._bc, this._bcOffset);
factory TableInC(List<int> bytes) {
- fb.BufferContext rootRef = new fb.BufferContext.fromBytes(bytes);
+ final rootRef = fb.BufferContext.fromBytes(bytes);
return reader.read(rootRef, 0);
}
- static const fb.Reader<TableInC> reader = const _TableInCReader();
+ static const fb.Reader<TableInC> reader = _TableInCReader();
final fb.BufferContext _bc;
final int _bcOffset;
- namespace_a.TableInFirstNS get referToA1 => namespace_a.TableInFirstNS.reader.vTableGet(_bc, _bcOffset, 4, null);
- namespace_a.SecondTableInA get referToA2 => namespace_a.SecondTableInA.reader.vTableGet(_bc, _bcOffset, 6, null);
+ namespace_a.TableInFirstNS? get referToA1 => namespace_a.TableInFirstNS.reader.vTableGetNullable(_bc, _bcOffset, 4);
+ namespace_a.SecondTableInA? get referToA2 => namespace_a.SecondTableInA.reader.vTableGetNullable(_bc, _bcOffset, 6);
@override
String toString() {
return 'TableInC{referToA1: $referToA1, referToA2: $referToA2}';
}
+
+ TableInCT unpack() => TableInCT(
+ referToA1: referToA1?.unpack(),
+ referToA2: referToA2?.unpack());
+
+ static int pack(fb.Builder fbBuilder, TableInCT? object) {
+ if (object == null) return 0;
+ return object.pack(fbBuilder);
+ }
+}
+
+class TableInCT implements fb.Packable {
+ namespace_a.TableInFirstNST? referToA1;
+ namespace_a.SecondTableInAT? referToA2;
+
+ TableInCT({
+ this.referToA1,
+ this.referToA2});
+
+ @override
+ int pack(fb.Builder fbBuilder) {
+ final int? referToA1Offset = referToA1?.pack(fbBuilder);
+ final int? referToA2Offset = referToA2?.pack(fbBuilder);
+ fbBuilder.startTable(2);
+ fbBuilder.addOffset(0, referToA1Offset);
+ fbBuilder.addOffset(1, referToA2Offset);
+ return fbBuilder.endTable();
+ }
+
+ @override
+ String toString() {
+ return 'TableInCT{referToA1: $referToA1, referToA2: $referToA2}';
+ }
}
class _TableInCReader extends fb.TableReader<TableInC> {
@@ -34,25 +67,23 @@
@override
TableInC createObject(fb.BufferContext bc, int offset) =>
- new TableInC._(bc, offset);
+ TableInC._(bc, offset);
}
class TableInCBuilder {
- TableInCBuilder(this.fbBuilder) {
- assert(fbBuilder != null);
- }
+ TableInCBuilder(this.fbBuilder);
final fb.Builder fbBuilder;
void begin() {
- fbBuilder.startTable();
+ fbBuilder.startTable(2);
}
- int addReferToA1Offset(int offset) {
+ int addReferToA1Offset(int? offset) {
fbBuilder.addOffset(0, offset);
return fbBuilder.offset;
}
- int addReferToA2Offset(int offset) {
+ int addReferToA2Offset(int? offset) {
fbBuilder.addOffset(1, offset);
return fbBuilder.offset;
}
@@ -63,39 +94,32 @@
}
class TableInCObjectBuilder extends fb.ObjectBuilder {
- final namespace_a.TableInFirstNSObjectBuilder _referToA1;
- final namespace_a.SecondTableInAObjectBuilder _referToA2;
+ final namespace_a.TableInFirstNSObjectBuilder? _referToA1;
+ final namespace_a.SecondTableInAObjectBuilder? _referToA2;
TableInCObjectBuilder({
- namespace_a.TableInFirstNSObjectBuilder referToA1,
- namespace_a.SecondTableInAObjectBuilder referToA2,
+ namespace_a.TableInFirstNSObjectBuilder? referToA1,
+ namespace_a.SecondTableInAObjectBuilder? referToA2,
})
: _referToA1 = referToA1,
_referToA2 = referToA2;
/// Finish building, and store into the [fbBuilder].
@override
- int finish(
- fb.Builder fbBuilder) {
- assert(fbBuilder != null);
- final int referToA1Offset = _referToA1?.getOrCreateOffset(fbBuilder);
- final int referToA2Offset = _referToA2?.getOrCreateOffset(fbBuilder);
-
- fbBuilder.startTable();
- if (referToA1Offset != null) {
- fbBuilder.addOffset(0, referToA1Offset);
- }
- if (referToA2Offset != null) {
- fbBuilder.addOffset(1, referToA2Offset);
- }
+ int finish(fb.Builder fbBuilder) {
+ final int? referToA1Offset = _referToA1?.getOrCreateOffset(fbBuilder);
+ final int? referToA2Offset = _referToA2?.getOrCreateOffset(fbBuilder);
+ fbBuilder.startTable(2);
+ fbBuilder.addOffset(0, referToA1Offset);
+ fbBuilder.addOffset(1, referToA2Offset);
return fbBuilder.endTable();
}
/// Convenience method to serialize to byte list.
@override
- Uint8List toBytes([String fileIdentifier]) {
- fb.Builder fbBuilder = new fb.Builder();
- int offset = finish(fbBuilder);
- return fbBuilder.finish(offset, fileIdentifier);
+ Uint8List toBytes([String? fileIdentifier]) {
+ final fbBuilder = fb.Builder(deduplicateTables: false);
+ fbBuilder.finish(finish(fbBuilder), fileIdentifier);
+ return fbBuilder.buffer;
}
}
diff --git a/tests/native_type_test.fbs b/tests/native_type_test.fbs
index de80bdf..e22150f 100644
--- a/tests/native_type_test.fbs
+++ b/tests/native_type_test.fbs
@@ -8,8 +8,15 @@
z:float;
}
+struct Vector3DAlt (native_type:"Native::Vector3D", native_type_pack_name:"Vector3DAlt") {
+ a:float;
+ b:float;
+ c:float;
+}
+
table ApplicationData {
vectors:[Vector3D];
+ vectors_alt:[Vector3DAlt];
}
root_type ApplicationData;
diff --git a/tests/native_type_test_generated.h b/tests/native_type_test_generated.h
index e504c92..8678718 100644
--- a/tests/native_type_test_generated.h
+++ b/tests/native_type_test_generated.h
@@ -12,12 +12,16 @@
struct Vector3D;
+struct Vector3DAlt;
+
struct ApplicationData;
struct ApplicationDataBuilder;
struct ApplicationDataT;
inline const flatbuffers::TypeTable *Vector3DTypeTable();
+inline const flatbuffers::TypeTable *Vector3DAltTypeTable();
+
inline const flatbuffers::TypeTable *ApplicationDataTypeTable();
FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) Vector3D FLATBUFFERS_FINAL_CLASS {
@@ -61,11 +65,51 @@
};
FLATBUFFERS_STRUCT_END(Vector3D, 12);
+FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) Vector3DAlt FLATBUFFERS_FINAL_CLASS {
+ private:
+ float a_;
+ float b_;
+ float c_;
+
+ public:
+ static const flatbuffers::TypeTable *MiniReflectTypeTable() {
+ return Vector3DAltTypeTable();
+ }
+ Vector3DAlt()
+ : a_(0),
+ b_(0),
+ c_(0) {
+ }
+ Vector3DAlt(float _a, float _b, float _c)
+ : a_(flatbuffers::EndianScalar(_a)),
+ b_(flatbuffers::EndianScalar(_b)),
+ c_(flatbuffers::EndianScalar(_c)) {
+ }
+ float a() const {
+ return flatbuffers::EndianScalar(a_);
+ }
+ void mutate_a(float _a) {
+ flatbuffers::WriteScalar(&a_, _a);
+ }
+ float b() const {
+ return flatbuffers::EndianScalar(b_);
+ }
+ void mutate_b(float _b) {
+ flatbuffers::WriteScalar(&b_, _b);
+ }
+ float c() const {
+ return flatbuffers::EndianScalar(c_);
+ }
+ void mutate_c(float _c) {
+ flatbuffers::WriteScalar(&c_, _c);
+ }
+};
+FLATBUFFERS_STRUCT_END(Vector3DAlt, 12);
+
struct ApplicationDataT : public flatbuffers::NativeTable {
typedef ApplicationData TableType;
- std::vector<Native::Vector3D> vectors;
- ApplicationDataT() {
- }
+ std::vector<Native::Vector3D> vectors{};
+ std::vector<Native::Vector3D> vectors_alt{};
};
struct ApplicationData FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
@@ -75,7 +119,8 @@
return ApplicationDataTypeTable();
}
enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE {
- VT_VECTORS = 4
+ VT_VECTORS = 4,
+ VT_VECTORS_ALT = 6
};
const flatbuffers::Vector<const Geometry::Vector3D *> *vectors() const {
return GetPointer<const flatbuffers::Vector<const Geometry::Vector3D *> *>(VT_VECTORS);
@@ -83,10 +128,18 @@
flatbuffers::Vector<const Geometry::Vector3D *> *mutable_vectors() {
return GetPointer<flatbuffers::Vector<const Geometry::Vector3D *> *>(VT_VECTORS);
}
+ const flatbuffers::Vector<const Geometry::Vector3DAlt *> *vectors_alt() const {
+ return GetPointer<const flatbuffers::Vector<const Geometry::Vector3DAlt *> *>(VT_VECTORS_ALT);
+ }
+ flatbuffers::Vector<const Geometry::Vector3DAlt *> *mutable_vectors_alt() {
+ return GetPointer<flatbuffers::Vector<const Geometry::Vector3DAlt *> *>(VT_VECTORS_ALT);
+ }
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
VerifyOffset(verifier, VT_VECTORS) &&
verifier.VerifyVector(vectors()) &&
+ VerifyOffset(verifier, VT_VECTORS_ALT) &&
+ verifier.VerifyVector(vectors_alt()) &&
verifier.EndTable();
}
ApplicationDataT *UnPack(const flatbuffers::resolver_function_t *_resolver = nullptr) const;
@@ -101,6 +154,9 @@
void add_vectors(flatbuffers::Offset<flatbuffers::Vector<const Geometry::Vector3D *>> vectors) {
fbb_.AddOffset(ApplicationData::VT_VECTORS, vectors);
}
+ void add_vectors_alt(flatbuffers::Offset<flatbuffers::Vector<const Geometry::Vector3DAlt *>> vectors_alt) {
+ fbb_.AddOffset(ApplicationData::VT_VECTORS_ALT, vectors_alt);
+ }
explicit ApplicationDataBuilder(flatbuffers::FlatBufferBuilder &_fbb)
: fbb_(_fbb) {
start_ = fbb_.StartTable();
@@ -114,25 +170,30 @@
inline flatbuffers::Offset<ApplicationData> CreateApplicationData(
flatbuffers::FlatBufferBuilder &_fbb,
- flatbuffers::Offset<flatbuffers::Vector<const Geometry::Vector3D *>> vectors = 0) {
+ flatbuffers::Offset<flatbuffers::Vector<const Geometry::Vector3D *>> vectors = 0,
+ flatbuffers::Offset<flatbuffers::Vector<const Geometry::Vector3DAlt *>> vectors_alt = 0) {
ApplicationDataBuilder builder_(_fbb);
+ builder_.add_vectors_alt(vectors_alt);
builder_.add_vectors(vectors);
return builder_.Finish();
}
inline flatbuffers::Offset<ApplicationData> CreateApplicationDataDirect(
flatbuffers::FlatBufferBuilder &_fbb,
- const std::vector<Geometry::Vector3D> *vectors = nullptr) {
+ const std::vector<Geometry::Vector3D> *vectors = nullptr,
+ const std::vector<Geometry::Vector3DAlt> *vectors_alt = nullptr) {
auto vectors__ = vectors ? _fbb.CreateVectorOfStructs<Geometry::Vector3D>(*vectors) : 0;
+ auto vectors_alt__ = vectors_alt ? _fbb.CreateVectorOfStructs<Geometry::Vector3DAlt>(*vectors_alt) : 0;
return Geometry::CreateApplicationData(
_fbb,
- vectors__);
+ vectors__,
+ vectors_alt__);
}
flatbuffers::Offset<ApplicationData> CreateApplicationData(flatbuffers::FlatBufferBuilder &_fbb, const ApplicationDataT *_o, const flatbuffers::rehasher_function_t *_rehasher = nullptr);
inline ApplicationDataT *ApplicationData::UnPack(const flatbuffers::resolver_function_t *_resolver) const {
- flatbuffers::unique_ptr<Geometry::ApplicationDataT> _o = flatbuffers::unique_ptr<Geometry::ApplicationDataT>(new ApplicationDataT());
+ auto _o = std::unique_ptr<ApplicationDataT>(new ApplicationDataT());
UnPackTo(_o.get(), _resolver);
return _o.release();
}
@@ -141,6 +202,7 @@
(void)_o;
(void)_resolver;
{ auto _e = vectors(); if (_e) { _o->vectors.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->vectors[_i] = flatbuffers::UnPack(*_e->Get(_i)); } } }
+ { auto _e = vectors_alt(); if (_e) { _o->vectors_alt.resize(_e->size()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->vectors_alt[_i] = flatbuffers::UnPackVector3DAlt(*_e->Get(_i)); } } }
}
inline flatbuffers::Offset<ApplicationData> ApplicationData::Pack(flatbuffers::FlatBufferBuilder &_fbb, const ApplicationDataT* _o, const flatbuffers::rehasher_function_t *_rehasher) {
@@ -151,10 +213,12 @@
(void)_rehasher;
(void)_o;
struct _VectorArgs { flatbuffers::FlatBufferBuilder *__fbb; const ApplicationDataT* __o; const flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va;
- auto _vectors = _o->vectors.size() ? _fbb.CreateVectorOfNativeStructs<Geometry::Vector3D>(_o->vectors) : 0;
+ auto _vectors = _o->vectors.size() ? _fbb.CreateVectorOfNativeStructs<Geometry::Vector3D, Native::Vector3D>(_o->vectors) : 0;
+ auto _vectors_alt = _o->vectors_alt.size() ? _fbb.CreateVectorOfNativeStructs<Geometry::Vector3DAlt, Native::Vector3D>(_o->vectors_alt, flatbuffers::PackVector3DAlt) : 0;
return Geometry::CreateApplicationData(
_fbb,
- _vectors);
+ _vectors,
+ _vectors_alt);
}
inline const flatbuffers::TypeTable *Vector3DTypeTable() {
@@ -175,18 +239,39 @@
return &tt;
}
-inline const flatbuffers::TypeTable *ApplicationDataTypeTable() {
+inline const flatbuffers::TypeTable *Vector3DAltTypeTable() {
static const flatbuffers::TypeCode type_codes[] = {
- { flatbuffers::ET_SEQUENCE, 1, 0 }
+ { flatbuffers::ET_FLOAT, 0, -1 },
+ { flatbuffers::ET_FLOAT, 0, -1 },
+ { flatbuffers::ET_FLOAT, 0, -1 }
};
- static const flatbuffers::TypeFunction type_refs[] = {
- Geometry::Vector3DTypeTable
- };
+ static const int64_t values[] = { 0, 4, 8, 12 };
static const char * const names[] = {
- "vectors"
+ "a",
+ "b",
+ "c"
};
static const flatbuffers::TypeTable tt = {
- flatbuffers::ST_TABLE, 1, type_codes, type_refs, nullptr, nullptr, names
+ flatbuffers::ST_STRUCT, 3, type_codes, nullptr, nullptr, values, names
+ };
+ return &tt;
+}
+
+inline const flatbuffers::TypeTable *ApplicationDataTypeTable() {
+ static const flatbuffers::TypeCode type_codes[] = {
+ { flatbuffers::ET_SEQUENCE, 1, 0 },
+ { flatbuffers::ET_SEQUENCE, 1, 1 }
+ };
+ static const flatbuffers::TypeFunction type_refs[] = {
+ Geometry::Vector3DTypeTable,
+ Geometry::Vector3DAltTypeTable
+ };
+ static const char * const names[] = {
+ "vectors",
+ "vectors_alt"
+ };
+ static const flatbuffers::TypeTable tt = {
+ flatbuffers::ST_TABLE, 2, type_codes, type_refs, nullptr, nullptr, names
};
return &tt;
}
@@ -203,6 +288,10 @@
return flatbuffers::GetMutableRoot<ApplicationData>(buf);
}
+inline Geometry::ApplicationData *GetMutableSizePrefixedApplicationData(void *buf) {
+ return flatbuffers::GetMutableSizePrefixedRoot<Geometry::ApplicationData>(buf);
+}
+
inline bool VerifyApplicationDataBuffer(
flatbuffers::Verifier &verifier) {
return verifier.VerifyBuffer<Geometry::ApplicationData>(nullptr);
diff --git a/tests/native_type_test_impl.cpp b/tests/native_type_test_impl.cpp
index edf23eb..b5b595b 100644
--- a/tests/native_type_test_impl.cpp
+++ b/tests/native_type_test_impl.cpp
@@ -10,4 +10,12 @@
const Native::Vector3D UnPack(const Geometry::Vector3D &obj) {
return Native::Vector3D(obj.x(), obj.y(), obj.z());
}
+
+Geometry::Vector3DAlt PackVector3DAlt(const Native::Vector3D &obj) {
+ return Geometry::Vector3DAlt(obj.x, obj.y, obj.z);
+}
+
+const Native::Vector3D UnPackVector3DAlt(const Geometry::Vector3DAlt &obj) {
+ return Native::Vector3D(obj.a(), obj.b(), obj.c());
+}
} // namespace flatbuffers
diff --git a/tests/native_type_test_impl.h b/tests/native_type_test_impl.h
index fb35e0f..bc8f385 100644
--- a/tests/native_type_test_impl.h
+++ b/tests/native_type_test_impl.h
@@ -11,7 +11,7 @@
x = 0;
y = 0;
z = 0;
- };
+ }
Vector3D(float _x, float _y, float _z) {
this->x = _x;
this->y = _y;
@@ -22,11 +22,14 @@
namespace Geometry {
struct Vector3D;
-}
+struct Vector3DAlt;
+} // namespace Geometry
namespace flatbuffers {
Geometry::Vector3D Pack(const Native::Vector3D &obj);
const Native::Vector3D UnPack(const Geometry::Vector3D &obj);
+Geometry::Vector3DAlt PackVector3DAlt(const Native::Vector3D &obj);
+const Native::Vector3D UnPackVector3DAlt(const Geometry::Vector3DAlt &obj);
} // namespace flatbuffers
#endif // VECTOR3D_PACK_H
diff --git a/tests/nested_namespace_test/nested_namespace_test1.fbs b/tests/nested_namespace_test/nested_namespace_test1.fbs
new file mode 100644
index 0000000..1b43847
--- /dev/null
+++ b/tests/nested_namespace_test/nested_namespace_test1.fbs
@@ -0,0 +1,3 @@
+namespace NamespaceB;
+
+enum Color:byte { Red, Green, Blue }
diff --git a/tests/nested_namespace_test/nested_namespace_test1_generated.cs b/tests/nested_namespace_test/nested_namespace_test1_generated.cs
new file mode 100644
index 0000000..e42e96a
--- /dev/null
+++ b/tests/nested_namespace_test/nested_namespace_test1_generated.cs
@@ -0,0 +1,21 @@
+// <auto-generated>
+// automatically generated by the FlatBuffers compiler, do not modify
+// </auto-generated>
+
+namespace NamespaceB
+{
+
+using global::System;
+using global::System.Collections.Generic;
+using global::FlatBuffers;
+
+[Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))]
+public enum Color : sbyte
+{
+ Red = 0,
+ Green = 1,
+ Blue = 2,
+};
+
+
+}
diff --git a/tests/nested_namespace_test/nested_namespace_test2.fbs b/tests/nested_namespace_test/nested_namespace_test2.fbs
new file mode 100644
index 0000000..f2e04c3
--- /dev/null
+++ b/tests/nested_namespace_test/nested_namespace_test2.fbs
@@ -0,0 +1,3 @@
+namespace NamespaceA.NamespaceB;
+
+enum Color:byte { Purple }
diff --git a/tests/nested_namespace_test/nested_namespace_test2_generated.cs b/tests/nested_namespace_test/nested_namespace_test2_generated.cs
new file mode 100644
index 0000000..cdc1b09
--- /dev/null
+++ b/tests/nested_namespace_test/nested_namespace_test2_generated.cs
@@ -0,0 +1,19 @@
+// <auto-generated>
+// automatically generated by the FlatBuffers compiler, do not modify
+// </auto-generated>
+
+namespace NamespaceA.NamespaceB
+{
+
+using global::System;
+using global::System.Collections.Generic;
+using global::FlatBuffers;
+
+[Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))]
+public enum Color : sbyte
+{
+ Purple = 0,
+};
+
+
+}
diff --git a/tests/nested_namespace_test/nested_namespace_test3.fbs b/tests/nested_namespace_test/nested_namespace_test3.fbs
new file mode 100644
index 0000000..2672ace
--- /dev/null
+++ b/tests/nested_namespace_test/nested_namespace_test3.fbs
@@ -0,0 +1,7 @@
+include "nested_namespace_test1.fbs";
+
+namespace NamespaceA.NamespaceB;
+
+table ColorTestTable {
+ color:NamespaceB.Color = Blue;
+}
diff --git a/tests/nested_namespace_test/nested_namespace_test3_generated.cs b/tests/nested_namespace_test/nested_namespace_test3_generated.cs
new file mode 100644
index 0000000..f2f3778
--- /dev/null
+++ b/tests/nested_namespace_test/nested_namespace_test3_generated.cs
@@ -0,0 +1,65 @@
+// <auto-generated>
+// automatically generated by the FlatBuffers compiler, do not modify
+// </auto-generated>
+
+namespace NamespaceA.NamespaceB
+{
+
+using global::System;
+using global::System.Collections.Generic;
+using global::FlatBuffers;
+
+public struct ColorTestTable : IFlatbufferObject
+{
+ private Table __p;
+ public ByteBuffer ByteBuffer { get { return __p.bb; } }
+ public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_2_0_0(); }
+ public static ColorTestTable GetRootAsColorTestTable(ByteBuffer _bb) { return GetRootAsColorTestTable(_bb, new ColorTestTable()); }
+ public static ColorTestTable GetRootAsColorTestTable(ByteBuffer _bb, ColorTestTable obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); }
+ public void __init(int _i, ByteBuffer _bb) { __p = new Table(_i, _bb); }
+ public ColorTestTable __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; }
+
+ public global::NamespaceB.Color Color { get { int o = __p.__offset(4); return o != 0 ? (global::NamespaceB.Color)__p.bb.GetSbyte(o + __p.bb_pos) : global::NamespaceB.Color.Blue; } }
+ public bool MutateColor(global::NamespaceB.Color color) { int o = __p.__offset(4); if (o != 0) { __p.bb.PutSbyte(o + __p.bb_pos, (sbyte)color); return true; } else { return false; } }
+
+ public static Offset<global::NamespaceA.NamespaceB.ColorTestTable> CreateColorTestTable(FlatBufferBuilder builder,
+ global::NamespaceB.Color color = global::NamespaceB.Color.Blue) {
+ builder.StartTable(1);
+ ColorTestTable.AddColor(builder, color);
+ return ColorTestTable.EndColorTestTable(builder);
+ }
+
+ public static void StartColorTestTable(FlatBufferBuilder builder) { builder.StartTable(1); }
+ public static void AddColor(FlatBufferBuilder builder, global::NamespaceB.Color color) { builder.AddSbyte(0, (sbyte)color, 2); }
+ public static Offset<global::NamespaceA.NamespaceB.ColorTestTable> EndColorTestTable(FlatBufferBuilder builder) {
+ int o = builder.EndTable();
+ return new Offset<global::NamespaceA.NamespaceB.ColorTestTable>(o);
+ }
+ public ColorTestTableT UnPack() {
+ var _o = new ColorTestTableT();
+ this.UnPackTo(_o);
+ return _o;
+ }
+ public void UnPackTo(ColorTestTableT _o) {
+ _o.Color = this.Color;
+ }
+ public static Offset<global::NamespaceA.NamespaceB.ColorTestTable> Pack(FlatBufferBuilder builder, ColorTestTableT _o) {
+ if (_o == null) return default(Offset<global::NamespaceA.NamespaceB.ColorTestTable>);
+ return CreateColorTestTable(
+ builder,
+ _o.Color);
+ }
+}
+
+public class ColorTestTableT
+{
+ [Newtonsoft.Json.JsonProperty("color")]
+ public global::NamespaceB.Color Color { get; set; }
+
+ public ColorTestTableT() {
+ this.Color = global::NamespaceB.Color.Blue;
+ }
+}
+
+
+}
diff --git a/tests/optional-scalars/optional-byte.ts b/tests/optional-scalars/optional-byte.ts
new file mode 100644
index 0000000..1db479f
--- /dev/null
+++ b/tests/optional-scalars/optional-byte.ts
@@ -0,0 +1,8 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+export enum OptionalByte{
+ None = 0,
+ One = 1,
+ Two = 2
+}
+
diff --git a/tests/optional-scalars/scalar-stuff.ts b/tests/optional-scalars/scalar-stuff.ts
new file mode 100644
index 0000000..a748c22
--- /dev/null
+++ b/tests/optional-scalars/scalar-stuff.ts
@@ -0,0 +1,423 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+import * as flatbuffers from 'flatbuffers';
+
+import { OptionalByte } from '../optional-scalars/optional-byte';
+
+
+export class ScalarStuff {
+ bb: flatbuffers.ByteBuffer|null = null;
+ bb_pos = 0;
+__init(i:number, bb:flatbuffers.ByteBuffer):ScalarStuff {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+}
+
+static getRootAsScalarStuff(bb:flatbuffers.ByteBuffer, obj?:ScalarStuff):ScalarStuff {
+ return (obj || new ScalarStuff()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+}
+
+static getSizePrefixedRootAsScalarStuff(bb:flatbuffers.ByteBuffer, obj?:ScalarStuff):ScalarStuff {
+ bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new ScalarStuff()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+}
+
+static bufferHasIdentifier(bb:flatbuffers.ByteBuffer):boolean {
+ return bb.__has_identifier('NULL');
+}
+
+justI8():number {
+ const offset = this.bb!.__offset(this.bb_pos, 4);
+ return offset ? this.bb!.readInt8(this.bb_pos + offset) : 0;
+}
+
+maybeI8():number|null {
+ const offset = this.bb!.__offset(this.bb_pos, 6);
+ return offset ? this.bb!.readInt8(this.bb_pos + offset) : null;
+}
+
+defaultI8():number {
+ const offset = this.bb!.__offset(this.bb_pos, 8);
+ return offset ? this.bb!.readInt8(this.bb_pos + offset) : 42;
+}
+
+justU8():number {
+ const offset = this.bb!.__offset(this.bb_pos, 10);
+ return offset ? this.bb!.readUint8(this.bb_pos + offset) : 0;
+}
+
+maybeU8():number|null {
+ const offset = this.bb!.__offset(this.bb_pos, 12);
+ return offset ? this.bb!.readUint8(this.bb_pos + offset) : null;
+}
+
+defaultU8():number {
+ const offset = this.bb!.__offset(this.bb_pos, 14);
+ return offset ? this.bb!.readUint8(this.bb_pos + offset) : 42;
+}
+
+justI16():number {
+ const offset = this.bb!.__offset(this.bb_pos, 16);
+ return offset ? this.bb!.readInt16(this.bb_pos + offset) : 0;
+}
+
+maybeI16():number|null {
+ const offset = this.bb!.__offset(this.bb_pos, 18);
+ return offset ? this.bb!.readInt16(this.bb_pos + offset) : null;
+}
+
+defaultI16():number {
+ const offset = this.bb!.__offset(this.bb_pos, 20);
+ return offset ? this.bb!.readInt16(this.bb_pos + offset) : 42;
+}
+
+justU16():number {
+ const offset = this.bb!.__offset(this.bb_pos, 22);
+ return offset ? this.bb!.readUint16(this.bb_pos + offset) : 0;
+}
+
+maybeU16():number|null {
+ const offset = this.bb!.__offset(this.bb_pos, 24);
+ return offset ? this.bb!.readUint16(this.bb_pos + offset) : null;
+}
+
+defaultU16():number {
+ const offset = this.bb!.__offset(this.bb_pos, 26);
+ return offset ? this.bb!.readUint16(this.bb_pos + offset) : 42;
+}
+
+justI32():number {
+ const offset = this.bb!.__offset(this.bb_pos, 28);
+ return offset ? this.bb!.readInt32(this.bb_pos + offset) : 0;
+}
+
+maybeI32():number|null {
+ const offset = this.bb!.__offset(this.bb_pos, 30);
+ return offset ? this.bb!.readInt32(this.bb_pos + offset) : null;
+}
+
+defaultI32():number {
+ const offset = this.bb!.__offset(this.bb_pos, 32);
+ return offset ? this.bb!.readInt32(this.bb_pos + offset) : 42;
+}
+
+justU32():number {
+ const offset = this.bb!.__offset(this.bb_pos, 34);
+ return offset ? this.bb!.readUint32(this.bb_pos + offset) : 0;
+}
+
+maybeU32():number|null {
+ const offset = this.bb!.__offset(this.bb_pos, 36);
+ return offset ? this.bb!.readUint32(this.bb_pos + offset) : null;
+}
+
+defaultU32():number {
+ const offset = this.bb!.__offset(this.bb_pos, 38);
+ return offset ? this.bb!.readUint32(this.bb_pos + offset) : 42;
+}
+
+justI64():bigint {
+ const offset = this.bb!.__offset(this.bb_pos, 40);
+ return offset ? this.bb!.readInt64(this.bb_pos + offset) : BigInt('0');
+}
+
+maybeI64():bigint|null {
+ const offset = this.bb!.__offset(this.bb_pos, 42);
+ return offset ? this.bb!.readInt64(this.bb_pos + offset) : null;
+}
+
+defaultI64():bigint {
+ const offset = this.bb!.__offset(this.bb_pos, 44);
+ return offset ? this.bb!.readInt64(this.bb_pos + offset) : BigInt('42');
+}
+
+justU64():bigint {
+ const offset = this.bb!.__offset(this.bb_pos, 46);
+ return offset ? this.bb!.readUint64(this.bb_pos + offset) : BigInt('0');
+}
+
+maybeU64():bigint|null {
+ const offset = this.bb!.__offset(this.bb_pos, 48);
+ return offset ? this.bb!.readUint64(this.bb_pos + offset) : null;
+}
+
+defaultU64():bigint {
+ const offset = this.bb!.__offset(this.bb_pos, 50);
+ return offset ? this.bb!.readUint64(this.bb_pos + offset) : BigInt('42');
+}
+
+justF32():number {
+ const offset = this.bb!.__offset(this.bb_pos, 52);
+ return offset ? this.bb!.readFloat32(this.bb_pos + offset) : 0.0;
+}
+
+maybeF32():number|null {
+ const offset = this.bb!.__offset(this.bb_pos, 54);
+ return offset ? this.bb!.readFloat32(this.bb_pos + offset) : null;
+}
+
+defaultF32():number {
+ const offset = this.bb!.__offset(this.bb_pos, 56);
+ return offset ? this.bb!.readFloat32(this.bb_pos + offset) : 42.0;
+}
+
+justF64():number {
+ const offset = this.bb!.__offset(this.bb_pos, 58);
+ return offset ? this.bb!.readFloat64(this.bb_pos + offset) : 0.0;
+}
+
+maybeF64():number|null {
+ const offset = this.bb!.__offset(this.bb_pos, 60);
+ return offset ? this.bb!.readFloat64(this.bb_pos + offset) : null;
+}
+
+defaultF64():number {
+ const offset = this.bb!.__offset(this.bb_pos, 62);
+ return offset ? this.bb!.readFloat64(this.bb_pos + offset) : 42.0;
+}
+
+justBool():boolean {
+ const offset = this.bb!.__offset(this.bb_pos, 64);
+ return offset ? !!this.bb!.readInt8(this.bb_pos + offset) : false;
+}
+
+maybeBool():boolean|null {
+ const offset = this.bb!.__offset(this.bb_pos, 66);
+ return offset ? !!this.bb!.readInt8(this.bb_pos + offset) : null;
+}
+
+defaultBool():boolean {
+ const offset = this.bb!.__offset(this.bb_pos, 68);
+ return offset ? !!this.bb!.readInt8(this.bb_pos + offset) : true;
+}
+
+justEnum():OptionalByte {
+ const offset = this.bb!.__offset(this.bb_pos, 70);
+ return offset ? this.bb!.readInt8(this.bb_pos + offset) : OptionalByte.None;
+}
+
+maybeEnum():OptionalByte|null {
+ const offset = this.bb!.__offset(this.bb_pos, 72);
+ return offset ? this.bb!.readInt8(this.bb_pos + offset) : null;
+}
+
+defaultEnum():OptionalByte {
+ const offset = this.bb!.__offset(this.bb_pos, 74);
+ return offset ? this.bb!.readInt8(this.bb_pos + offset) : OptionalByte.One;
+}
+
+static startScalarStuff(builder:flatbuffers.Builder) {
+ builder.startObject(36);
+}
+
+static addJustI8(builder:flatbuffers.Builder, justI8:number) {
+ builder.addFieldInt8(0, justI8, 0);
+}
+
+static addMaybeI8(builder:flatbuffers.Builder, maybeI8:number) {
+ builder.addFieldInt8(1, maybeI8, 0);
+}
+
+static addDefaultI8(builder:flatbuffers.Builder, defaultI8:number) {
+ builder.addFieldInt8(2, defaultI8, 42);
+}
+
+static addJustU8(builder:flatbuffers.Builder, justU8:number) {
+ builder.addFieldInt8(3, justU8, 0);
+}
+
+static addMaybeU8(builder:flatbuffers.Builder, maybeU8:number) {
+ builder.addFieldInt8(4, maybeU8, 0);
+}
+
+static addDefaultU8(builder:flatbuffers.Builder, defaultU8:number) {
+ builder.addFieldInt8(5, defaultU8, 42);
+}
+
+static addJustI16(builder:flatbuffers.Builder, justI16:number) {
+ builder.addFieldInt16(6, justI16, 0);
+}
+
+static addMaybeI16(builder:flatbuffers.Builder, maybeI16:number) {
+ builder.addFieldInt16(7, maybeI16, 0);
+}
+
+static addDefaultI16(builder:flatbuffers.Builder, defaultI16:number) {
+ builder.addFieldInt16(8, defaultI16, 42);
+}
+
+static addJustU16(builder:flatbuffers.Builder, justU16:number) {
+ builder.addFieldInt16(9, justU16, 0);
+}
+
+static addMaybeU16(builder:flatbuffers.Builder, maybeU16:number) {
+ builder.addFieldInt16(10, maybeU16, 0);
+}
+
+static addDefaultU16(builder:flatbuffers.Builder, defaultU16:number) {
+ builder.addFieldInt16(11, defaultU16, 42);
+}
+
+static addJustI32(builder:flatbuffers.Builder, justI32:number) {
+ builder.addFieldInt32(12, justI32, 0);
+}
+
+static addMaybeI32(builder:flatbuffers.Builder, maybeI32:number) {
+ builder.addFieldInt32(13, maybeI32, 0);
+}
+
+static addDefaultI32(builder:flatbuffers.Builder, defaultI32:number) {
+ builder.addFieldInt32(14, defaultI32, 42);
+}
+
+static addJustU32(builder:flatbuffers.Builder, justU32:number) {
+ builder.addFieldInt32(15, justU32, 0);
+}
+
+static addMaybeU32(builder:flatbuffers.Builder, maybeU32:number) {
+ builder.addFieldInt32(16, maybeU32, 0);
+}
+
+static addDefaultU32(builder:flatbuffers.Builder, defaultU32:number) {
+ builder.addFieldInt32(17, defaultU32, 42);
+}
+
+static addJustI64(builder:flatbuffers.Builder, justI64:bigint) {
+ builder.addFieldInt64(18, justI64, BigInt('0'));
+}
+
+static addMaybeI64(builder:flatbuffers.Builder, maybeI64:bigint) {
+ builder.addFieldInt64(19, maybeI64, BigInt(0));
+}
+
+static addDefaultI64(builder:flatbuffers.Builder, defaultI64:bigint) {
+ builder.addFieldInt64(20, defaultI64, BigInt('42'));
+}
+
+static addJustU64(builder:flatbuffers.Builder, justU64:bigint) {
+ builder.addFieldInt64(21, justU64, BigInt('0'));
+}
+
+static addMaybeU64(builder:flatbuffers.Builder, maybeU64:bigint) {
+ builder.addFieldInt64(22, maybeU64, BigInt(0));
+}
+
+static addDefaultU64(builder:flatbuffers.Builder, defaultU64:bigint) {
+ builder.addFieldInt64(23, defaultU64, BigInt('42'));
+}
+
+static addJustF32(builder:flatbuffers.Builder, justF32:number) {
+ builder.addFieldFloat32(24, justF32, 0.0);
+}
+
+static addMaybeF32(builder:flatbuffers.Builder, maybeF32:number) {
+ builder.addFieldFloat32(25, maybeF32, 0);
+}
+
+static addDefaultF32(builder:flatbuffers.Builder, defaultF32:number) {
+ builder.addFieldFloat32(26, defaultF32, 42.0);
+}
+
+static addJustF64(builder:flatbuffers.Builder, justF64:number) {
+ builder.addFieldFloat64(27, justF64, 0.0);
+}
+
+static addMaybeF64(builder:flatbuffers.Builder, maybeF64:number) {
+ builder.addFieldFloat64(28, maybeF64, 0);
+}
+
+static addDefaultF64(builder:flatbuffers.Builder, defaultF64:number) {
+ builder.addFieldFloat64(29, defaultF64, 42.0);
+}
+
+static addJustBool(builder:flatbuffers.Builder, justBool:boolean) {
+ builder.addFieldInt8(30, +justBool, +false);
+}
+
+static addMaybeBool(builder:flatbuffers.Builder, maybeBool:boolean) {
+ builder.addFieldInt8(31, +maybeBool, 0);
+}
+
+static addDefaultBool(builder:flatbuffers.Builder, defaultBool:boolean) {
+ builder.addFieldInt8(32, +defaultBool, +true);
+}
+
+static addJustEnum(builder:flatbuffers.Builder, justEnum:OptionalByte) {
+ builder.addFieldInt8(33, justEnum, OptionalByte.None);
+}
+
+static addMaybeEnum(builder:flatbuffers.Builder, maybeEnum:OptionalByte) {
+ builder.addFieldInt8(34, maybeEnum, 0);
+}
+
+static addDefaultEnum(builder:flatbuffers.Builder, defaultEnum:OptionalByte) {
+ builder.addFieldInt8(35, defaultEnum, OptionalByte.One);
+}
+
+static endScalarStuff(builder:flatbuffers.Builder):flatbuffers.Offset {
+ const offset = builder.endObject();
+ return offset;
+}
+
+static finishScalarStuffBuffer(builder:flatbuffers.Builder, offset:flatbuffers.Offset) {
+ builder.finish(offset, 'NULL');
+}
+
+static finishSizePrefixedScalarStuffBuffer(builder:flatbuffers.Builder, offset:flatbuffers.Offset) {
+ builder.finish(offset, 'NULL', true);
+}
+
+static createScalarStuff(builder:flatbuffers.Builder, justI8:number, maybeI8:number|null, defaultI8:number, justU8:number, maybeU8:number|null, defaultU8:number, justI16:number, maybeI16:number|null, defaultI16:number, justU16:number, maybeU16:number|null, defaultU16:number, justI32:number, maybeI32:number|null, defaultI32:number, justU32:number, maybeU32:number|null, defaultU32:number, justI64:bigint, maybeI64:bigint|null, defaultI64:bigint, justU64:bigint, maybeU64:bigint|null, defaultU64:bigint, justF32:number, maybeF32:number|null, defaultF32:number, justF64:number, maybeF64:number|null, defaultF64:number, justBool:boolean, maybeBool:boolean|null, defaultBool:boolean, justEnum:OptionalByte, maybeEnum:OptionalByte|null, defaultEnum:OptionalByte):flatbuffers.Offset {
+ ScalarStuff.startScalarStuff(builder);
+ ScalarStuff.addJustI8(builder, justI8);
+ if (maybeI8 !== null)
+ ScalarStuff.addMaybeI8(builder, maybeI8);
+ ScalarStuff.addDefaultI8(builder, defaultI8);
+ ScalarStuff.addJustU8(builder, justU8);
+ if (maybeU8 !== null)
+ ScalarStuff.addMaybeU8(builder, maybeU8);
+ ScalarStuff.addDefaultU8(builder, defaultU8);
+ ScalarStuff.addJustI16(builder, justI16);
+ if (maybeI16 !== null)
+ ScalarStuff.addMaybeI16(builder, maybeI16);
+ ScalarStuff.addDefaultI16(builder, defaultI16);
+ ScalarStuff.addJustU16(builder, justU16);
+ if (maybeU16 !== null)
+ ScalarStuff.addMaybeU16(builder, maybeU16);
+ ScalarStuff.addDefaultU16(builder, defaultU16);
+ ScalarStuff.addJustI32(builder, justI32);
+ if (maybeI32 !== null)
+ ScalarStuff.addMaybeI32(builder, maybeI32);
+ ScalarStuff.addDefaultI32(builder, defaultI32);
+ ScalarStuff.addJustU32(builder, justU32);
+ if (maybeU32 !== null)
+ ScalarStuff.addMaybeU32(builder, maybeU32);
+ ScalarStuff.addDefaultU32(builder, defaultU32);
+ ScalarStuff.addJustI64(builder, justI64);
+ if (maybeI64 !== null)
+ ScalarStuff.addMaybeI64(builder, maybeI64);
+ ScalarStuff.addDefaultI64(builder, defaultI64);
+ ScalarStuff.addJustU64(builder, justU64);
+ if (maybeU64 !== null)
+ ScalarStuff.addMaybeU64(builder, maybeU64);
+ ScalarStuff.addDefaultU64(builder, defaultU64);
+ ScalarStuff.addJustF32(builder, justF32);
+ if (maybeF32 !== null)
+ ScalarStuff.addMaybeF32(builder, maybeF32);
+ ScalarStuff.addDefaultF32(builder, defaultF32);
+ ScalarStuff.addJustF64(builder, justF64);
+ if (maybeF64 !== null)
+ ScalarStuff.addMaybeF64(builder, maybeF64);
+ ScalarStuff.addDefaultF64(builder, defaultF64);
+ ScalarStuff.addJustBool(builder, justBool);
+ if (maybeBool !== null)
+ ScalarStuff.addMaybeBool(builder, maybeBool);
+ ScalarStuff.addDefaultBool(builder, defaultBool);
+ ScalarStuff.addJustEnum(builder, justEnum);
+ if (maybeEnum !== null)
+ ScalarStuff.addMaybeEnum(builder, maybeEnum);
+ ScalarStuff.addDefaultEnum(builder, defaultEnum);
+ return ScalarStuff.endScalarStuff(builder);
+}
+}
diff --git a/tests/optional_scalars.ts b/tests/optional_scalars.ts
new file mode 100644
index 0000000..6d9830c
--- /dev/null
+++ b/tests/optional_scalars.ts
@@ -0,0 +1 @@
+export { OptionalByte } from './optional-scalars/optional-byte';
diff --git a/tests/optional_scalars/OptionalByte.go b/tests/optional_scalars/OptionalByte.go
new file mode 100644
index 0000000..e1f5ac0
--- /dev/null
+++ b/tests/optional_scalars/OptionalByte.go
@@ -0,0 +1,32 @@
+// Code generated by the FlatBuffers compiler. DO NOT EDIT.
+
+package optional_scalars
+
+import "strconv"
+
+type OptionalByte int8
+
+const (
+ OptionalByteNone OptionalByte = 0
+ OptionalByteOne OptionalByte = 1
+ OptionalByteTwo OptionalByte = 2
+)
+
+var EnumNamesOptionalByte = map[OptionalByte]string{
+ OptionalByteNone: "None",
+ OptionalByteOne: "One",
+ OptionalByteTwo: "Two",
+}
+
+var EnumValuesOptionalByte = map[string]OptionalByte{
+ "None": OptionalByteNone,
+ "One": OptionalByteOne,
+ "Two": OptionalByteTwo,
+}
+
+func (v OptionalByte) String() string {
+ if s, ok := EnumNamesOptionalByte[v]; ok {
+ return s
+ }
+ return "OptionalByte(" + strconv.FormatInt(int64(v), 10) + ")"
+}
diff --git a/tests/optional_scalars/OptionalByte.java b/tests/optional_scalars/OptionalByte.java
index 2ca8475..90a37fd 100644
--- a/tests/optional_scalars/OptionalByte.java
+++ b/tests/optional_scalars/OptionalByte.java
@@ -2,6 +2,7 @@
package optional_scalars;
+@SuppressWarnings("unused")
public final class OptionalByte {
private OptionalByte() { }
public static final byte None = 0;
diff --git a/tests/optional_scalars/OptionalByte.kt b/tests/optional_scalars/OptionalByte.kt
index 41fe6cd..afb3690 100644
--- a/tests/optional_scalars/OptionalByte.kt
+++ b/tests/optional_scalars/OptionalByte.kt
@@ -3,7 +3,6 @@
package optional_scalars
@Suppress("unused")
-@ExperimentalUnsignedTypes
class OptionalByte private constructor() {
companion object {
const val None: Byte = 0
diff --git a/tests/optional_scalars/ScalarStuff.cs b/tests/optional_scalars/ScalarStuff.cs
index a5c9ffb..e549838 100644
--- a/tests/optional_scalars/ScalarStuff.cs
+++ b/tests/optional_scalars/ScalarStuff.cs
@@ -13,7 +13,7 @@
{
private Table __p;
public ByteBuffer ByteBuffer { get { return __p.bb; } }
- public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_1_12_0(); }
+ public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_2_0_0(); }
public static ScalarStuff GetRootAsScalarStuff(ByteBuffer _bb) { return GetRootAsScalarStuff(_bb, new ScalarStuff()); }
public static ScalarStuff GetRootAsScalarStuff(ByteBuffer _bb, ScalarStuff obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); }
public static bool ScalarStuffBufferHasIdentifier(ByteBuffer _bb) { return Table.__has_identifier(_bb, "NULL"); }
@@ -169,7 +169,7 @@
public static void AddMaybeBool(FlatBufferBuilder builder, bool? maybeBool) { builder.AddBool(31, maybeBool); }
public static void AddDefaultBool(FlatBufferBuilder builder, bool defaultBool) { builder.AddBool(32, defaultBool, true); }
public static void AddJustEnum(FlatBufferBuilder builder, optional_scalars.OptionalByte justEnum) { builder.AddSbyte(33, (sbyte)justEnum, 0); }
- public static void AddMaybeEnum(FlatBufferBuilder builder, optional_scalars.OptionalByte? maybeEnum) { builder.AddSbyte(34, (sbyte)maybeEnum); }
+ public static void AddMaybeEnum(FlatBufferBuilder builder, optional_scalars.OptionalByte? maybeEnum) { builder.AddSbyte(34, (sbyte?)maybeEnum); }
public static void AddDefaultEnum(FlatBufferBuilder builder, optional_scalars.OptionalByte defaultEnum) { builder.AddSbyte(35, (sbyte)defaultEnum, 1); }
public static Offset<optional_scalars.ScalarStuff> EndScalarStuff(FlatBufferBuilder builder) {
int o = builder.EndTable();
@@ -177,7 +177,178 @@
}
public static void FinishScalarStuffBuffer(FlatBufferBuilder builder, Offset<optional_scalars.ScalarStuff> offset) { builder.Finish(offset.Value, "NULL"); }
public static void FinishSizePrefixedScalarStuffBuffer(FlatBufferBuilder builder, Offset<optional_scalars.ScalarStuff> offset) { builder.FinishSizePrefixed(offset.Value, "NULL"); }
-};
+ public ScalarStuffT UnPack() {
+ var _o = new ScalarStuffT();
+ this.UnPackTo(_o);
+ return _o;
+ }
+ public void UnPackTo(ScalarStuffT _o) {
+ _o.JustI8 = this.JustI8;
+ _o.MaybeI8 = this.MaybeI8;
+ _o.DefaultI8 = this.DefaultI8;
+ _o.JustU8 = this.JustU8;
+ _o.MaybeU8 = this.MaybeU8;
+ _o.DefaultU8 = this.DefaultU8;
+ _o.JustI16 = this.JustI16;
+ _o.MaybeI16 = this.MaybeI16;
+ _o.DefaultI16 = this.DefaultI16;
+ _o.JustU16 = this.JustU16;
+ _o.MaybeU16 = this.MaybeU16;
+ _o.DefaultU16 = this.DefaultU16;
+ _o.JustI32 = this.JustI32;
+ _o.MaybeI32 = this.MaybeI32;
+ _o.DefaultI32 = this.DefaultI32;
+ _o.JustU32 = this.JustU32;
+ _o.MaybeU32 = this.MaybeU32;
+ _o.DefaultU32 = this.DefaultU32;
+ _o.JustI64 = this.JustI64;
+ _o.MaybeI64 = this.MaybeI64;
+ _o.DefaultI64 = this.DefaultI64;
+ _o.JustU64 = this.JustU64;
+ _o.MaybeU64 = this.MaybeU64;
+ _o.DefaultU64 = this.DefaultU64;
+ _o.JustF32 = this.JustF32;
+ _o.MaybeF32 = this.MaybeF32;
+ _o.DefaultF32 = this.DefaultF32;
+ _o.JustF64 = this.JustF64;
+ _o.MaybeF64 = this.MaybeF64;
+ _o.DefaultF64 = this.DefaultF64;
+ _o.JustBool = this.JustBool;
+ _o.MaybeBool = this.MaybeBool;
+ _o.DefaultBool = this.DefaultBool;
+ _o.JustEnum = this.JustEnum;
+ _o.MaybeEnum = this.MaybeEnum;
+ _o.DefaultEnum = this.DefaultEnum;
+ }
+ public static Offset<optional_scalars.ScalarStuff> Pack(FlatBufferBuilder builder, ScalarStuffT _o) {
+ if (_o == null) return default(Offset<optional_scalars.ScalarStuff>);
+ return CreateScalarStuff(
+ builder,
+ _o.JustI8,
+ _o.MaybeI8,
+ _o.DefaultI8,
+ _o.JustU8,
+ _o.MaybeU8,
+ _o.DefaultU8,
+ _o.JustI16,
+ _o.MaybeI16,
+ _o.DefaultI16,
+ _o.JustU16,
+ _o.MaybeU16,
+ _o.DefaultU16,
+ _o.JustI32,
+ _o.MaybeI32,
+ _o.DefaultI32,
+ _o.JustU32,
+ _o.MaybeU32,
+ _o.DefaultU32,
+ _o.JustI64,
+ _o.MaybeI64,
+ _o.DefaultI64,
+ _o.JustU64,
+ _o.MaybeU64,
+ _o.DefaultU64,
+ _o.JustF32,
+ _o.MaybeF32,
+ _o.DefaultF32,
+ _o.JustF64,
+ _o.MaybeF64,
+ _o.DefaultF64,
+ _o.JustBool,
+ _o.MaybeBool,
+ _o.DefaultBool,
+ _o.JustEnum,
+ _o.MaybeEnum,
+ _o.DefaultEnum);
+ }
+}
+
+public class ScalarStuffT
+{
+ public sbyte JustI8 { get; set; }
+ public sbyte? MaybeI8 { get; set; }
+ public sbyte DefaultI8 { get; set; }
+ public byte JustU8 { get; set; }
+ public byte? MaybeU8 { get; set; }
+ public byte DefaultU8 { get; set; }
+ public short JustI16 { get; set; }
+ public short? MaybeI16 { get; set; }
+ public short DefaultI16 { get; set; }
+ public ushort JustU16 { get; set; }
+ public ushort? MaybeU16 { get; set; }
+ public ushort DefaultU16 { get; set; }
+ public int JustI32 { get; set; }
+ public int? MaybeI32 { get; set; }
+ public int DefaultI32 { get; set; }
+ public uint JustU32 { get; set; }
+ public uint? MaybeU32 { get; set; }
+ public uint DefaultU32 { get; set; }
+ public long JustI64 { get; set; }
+ public long? MaybeI64 { get; set; }
+ public long DefaultI64 { get; set; }
+ public ulong JustU64 { get; set; }
+ public ulong? MaybeU64 { get; set; }
+ public ulong DefaultU64 { get; set; }
+ public float JustF32 { get; set; }
+ public float? MaybeF32 { get; set; }
+ public float DefaultF32 { get; set; }
+ public double JustF64 { get; set; }
+ public double? MaybeF64 { get; set; }
+ public double DefaultF64 { get; set; }
+ public bool JustBool { get; set; }
+ public bool? MaybeBool { get; set; }
+ public bool DefaultBool { get; set; }
+ public optional_scalars.OptionalByte JustEnum { get; set; }
+ public optional_scalars.OptionalByte? MaybeEnum { get; set; }
+ public optional_scalars.OptionalByte DefaultEnum { get; set; }
+
+ public ScalarStuffT() {
+ this.JustI8 = 0;
+ this.MaybeI8 = null;
+ this.DefaultI8 = 42;
+ this.JustU8 = 0;
+ this.MaybeU8 = null;
+ this.DefaultU8 = 42;
+ this.JustI16 = 0;
+ this.MaybeI16 = null;
+ this.DefaultI16 = 42;
+ this.JustU16 = 0;
+ this.MaybeU16 = null;
+ this.DefaultU16 = 42;
+ this.JustI32 = 0;
+ this.MaybeI32 = null;
+ this.DefaultI32 = 42;
+ this.JustU32 = 0;
+ this.MaybeU32 = null;
+ this.DefaultU32 = 42;
+ this.JustI64 = 0;
+ this.MaybeI64 = null;
+ this.DefaultI64 = 42;
+ this.JustU64 = 0;
+ this.MaybeU64 = null;
+ this.DefaultU64 = 42;
+ this.JustF32 = 0.0f;
+ this.MaybeF32 = null;
+ this.DefaultF32 = 42.0f;
+ this.JustF64 = 0.0;
+ this.MaybeF64 = null;
+ this.DefaultF64 = 42.0;
+ this.JustBool = false;
+ this.MaybeBool = null;
+ this.DefaultBool = true;
+ this.JustEnum = optional_scalars.OptionalByte.None;
+ this.MaybeEnum = null;
+ this.DefaultEnum = optional_scalars.OptionalByte.One;
+ }
+ public static ScalarStuffT DeserializeFromBinary(byte[] fbBuffer) {
+ return ScalarStuff.GetRootAsScalarStuff(new ByteBuffer(fbBuffer)).UnPack();
+ }
+ public byte[] SerializeToBinary() {
+ var fbb = new FlatBufferBuilder(0x10000);
+ ScalarStuff.FinishScalarStuffBuffer(fbb, ScalarStuff.Pack(fbb, this));
+ return fbb.DataBuffer.ToSizedArray();
+ }
+}
}
diff --git a/tests/optional_scalars/ScalarStuff.go b/tests/optional_scalars/ScalarStuff.go
new file mode 100644
index 0000000..2992f30
--- /dev/null
+++ b/tests/optional_scalars/ScalarStuff.go
@@ -0,0 +1,756 @@
+// Code generated by the FlatBuffers compiler. DO NOT EDIT.
+
+package optional_scalars
+
+import (
+ flatbuffers "github.com/google/flatbuffers/go"
+)
+
+type ScalarStuffT struct {
+ JustI8 int8
+ MaybeI8 *int8
+ DefaultI8 int8
+ JustU8 byte
+ MaybeU8 *byte
+ DefaultU8 byte
+ JustI16 int16
+ MaybeI16 *int16
+ DefaultI16 int16
+ JustU16 uint16
+ MaybeU16 *uint16
+ DefaultU16 uint16
+ JustI32 int32
+ MaybeI32 *int32
+ DefaultI32 int32
+ JustU32 uint32
+ MaybeU32 *uint32
+ DefaultU32 uint32
+ JustI64 int64
+ MaybeI64 *int64
+ DefaultI64 int64
+ JustU64 uint64
+ MaybeU64 *uint64
+ DefaultU64 uint64
+ JustF32 float32
+ MaybeF32 *float32
+ DefaultF32 float32
+ JustF64 float64
+ MaybeF64 *float64
+ DefaultF64 float64
+ JustBool bool
+ MaybeBool *bool
+ DefaultBool bool
+ JustEnum OptionalByte
+ MaybeEnum *OptionalByte
+ DefaultEnum OptionalByte
+}
+
+func (t *ScalarStuffT) Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT {
+ if t == nil { return 0 }
+ ScalarStuffStart(builder)
+ ScalarStuffAddJustI8(builder, t.JustI8)
+ if t.MaybeI8 != nil {
+ ScalarStuffAddMaybeI8(builder, *t.MaybeI8)
+ }
+ ScalarStuffAddDefaultI8(builder, t.DefaultI8)
+ ScalarStuffAddJustU8(builder, t.JustU8)
+ if t.MaybeU8 != nil {
+ ScalarStuffAddMaybeU8(builder, *t.MaybeU8)
+ }
+ ScalarStuffAddDefaultU8(builder, t.DefaultU8)
+ ScalarStuffAddJustI16(builder, t.JustI16)
+ if t.MaybeI16 != nil {
+ ScalarStuffAddMaybeI16(builder, *t.MaybeI16)
+ }
+ ScalarStuffAddDefaultI16(builder, t.DefaultI16)
+ ScalarStuffAddJustU16(builder, t.JustU16)
+ if t.MaybeU16 != nil {
+ ScalarStuffAddMaybeU16(builder, *t.MaybeU16)
+ }
+ ScalarStuffAddDefaultU16(builder, t.DefaultU16)
+ ScalarStuffAddJustI32(builder, t.JustI32)
+ if t.MaybeI32 != nil {
+ ScalarStuffAddMaybeI32(builder, *t.MaybeI32)
+ }
+ ScalarStuffAddDefaultI32(builder, t.DefaultI32)
+ ScalarStuffAddJustU32(builder, t.JustU32)
+ if t.MaybeU32 != nil {
+ ScalarStuffAddMaybeU32(builder, *t.MaybeU32)
+ }
+ ScalarStuffAddDefaultU32(builder, t.DefaultU32)
+ ScalarStuffAddJustI64(builder, t.JustI64)
+ if t.MaybeI64 != nil {
+ ScalarStuffAddMaybeI64(builder, *t.MaybeI64)
+ }
+ ScalarStuffAddDefaultI64(builder, t.DefaultI64)
+ ScalarStuffAddJustU64(builder, t.JustU64)
+ if t.MaybeU64 != nil {
+ ScalarStuffAddMaybeU64(builder, *t.MaybeU64)
+ }
+ ScalarStuffAddDefaultU64(builder, t.DefaultU64)
+ ScalarStuffAddJustF32(builder, t.JustF32)
+ if t.MaybeF32 != nil {
+ ScalarStuffAddMaybeF32(builder, *t.MaybeF32)
+ }
+ ScalarStuffAddDefaultF32(builder, t.DefaultF32)
+ ScalarStuffAddJustF64(builder, t.JustF64)
+ if t.MaybeF64 != nil {
+ ScalarStuffAddMaybeF64(builder, *t.MaybeF64)
+ }
+ ScalarStuffAddDefaultF64(builder, t.DefaultF64)
+ ScalarStuffAddJustBool(builder, t.JustBool)
+ if t.MaybeBool != nil {
+ ScalarStuffAddMaybeBool(builder, *t.MaybeBool)
+ }
+ ScalarStuffAddDefaultBool(builder, t.DefaultBool)
+ ScalarStuffAddJustEnum(builder, t.JustEnum)
+ if t.MaybeEnum != nil {
+ ScalarStuffAddMaybeEnum(builder, *t.MaybeEnum)
+ }
+ ScalarStuffAddDefaultEnum(builder, t.DefaultEnum)
+ return ScalarStuffEnd(builder)
+}
+
+func (rcv *ScalarStuff) UnPackTo(t *ScalarStuffT) {
+ t.JustI8 = rcv.JustI8()
+ t.MaybeI8 = rcv.MaybeI8()
+ t.DefaultI8 = rcv.DefaultI8()
+ t.JustU8 = rcv.JustU8()
+ t.MaybeU8 = rcv.MaybeU8()
+ t.DefaultU8 = rcv.DefaultU8()
+ t.JustI16 = rcv.JustI16()
+ t.MaybeI16 = rcv.MaybeI16()
+ t.DefaultI16 = rcv.DefaultI16()
+ t.JustU16 = rcv.JustU16()
+ t.MaybeU16 = rcv.MaybeU16()
+ t.DefaultU16 = rcv.DefaultU16()
+ t.JustI32 = rcv.JustI32()
+ t.MaybeI32 = rcv.MaybeI32()
+ t.DefaultI32 = rcv.DefaultI32()
+ t.JustU32 = rcv.JustU32()
+ t.MaybeU32 = rcv.MaybeU32()
+ t.DefaultU32 = rcv.DefaultU32()
+ t.JustI64 = rcv.JustI64()
+ t.MaybeI64 = rcv.MaybeI64()
+ t.DefaultI64 = rcv.DefaultI64()
+ t.JustU64 = rcv.JustU64()
+ t.MaybeU64 = rcv.MaybeU64()
+ t.DefaultU64 = rcv.DefaultU64()
+ t.JustF32 = rcv.JustF32()
+ t.MaybeF32 = rcv.MaybeF32()
+ t.DefaultF32 = rcv.DefaultF32()
+ t.JustF64 = rcv.JustF64()
+ t.MaybeF64 = rcv.MaybeF64()
+ t.DefaultF64 = rcv.DefaultF64()
+ t.JustBool = rcv.JustBool()
+ t.MaybeBool = rcv.MaybeBool()
+ t.DefaultBool = rcv.DefaultBool()
+ t.JustEnum = rcv.JustEnum()
+ t.MaybeEnum = rcv.MaybeEnum()
+ t.DefaultEnum = rcv.DefaultEnum()
+}
+
+func (rcv *ScalarStuff) UnPack() *ScalarStuffT {
+ if rcv == nil { return nil }
+ t := &ScalarStuffT{}
+ rcv.UnPackTo(t)
+ return t
+}
+
+type ScalarStuff struct {
+ _tab flatbuffers.Table
+}
+
+func GetRootAsScalarStuff(buf []byte, offset flatbuffers.UOffsetT) *ScalarStuff {
+ n := flatbuffers.GetUOffsetT(buf[offset:])
+ x := &ScalarStuff{}
+ x.Init(buf, n+offset)
+ return x
+}
+
+func GetSizePrefixedRootAsScalarStuff(buf []byte, offset flatbuffers.UOffsetT) *ScalarStuff {
+ n := flatbuffers.GetUOffsetT(buf[offset+flatbuffers.SizeUint32:])
+ x := &ScalarStuff{}
+ x.Init(buf, n+offset+flatbuffers.SizeUint32)
+ return x
+}
+
+func (rcv *ScalarStuff) Init(buf []byte, i flatbuffers.UOffsetT) {
+ rcv._tab.Bytes = buf
+ rcv._tab.Pos = i
+}
+
+func (rcv *ScalarStuff) Table() flatbuffers.Table {
+ return rcv._tab
+}
+
+func (rcv *ScalarStuff) JustI8() int8 {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(4))
+ if o != 0 {
+ return rcv._tab.GetInt8(o + rcv._tab.Pos)
+ }
+ return 0
+}
+
+func (rcv *ScalarStuff) MutateJustI8(n int8) bool {
+ return rcv._tab.MutateInt8Slot(4, n)
+}
+
+func (rcv *ScalarStuff) MaybeI8() *int8 {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(6))
+ if o != 0 {
+ v := rcv._tab.GetInt8(o + rcv._tab.Pos)
+ return &v
+ }
+ return nil
+}
+
+func (rcv *ScalarStuff) MutateMaybeI8(n int8) bool {
+ return rcv._tab.MutateInt8Slot(6, n)
+}
+
+func (rcv *ScalarStuff) DefaultI8() int8 {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(8))
+ if o != 0 {
+ return rcv._tab.GetInt8(o + rcv._tab.Pos)
+ }
+ return 42
+}
+
+func (rcv *ScalarStuff) MutateDefaultI8(n int8) bool {
+ return rcv._tab.MutateInt8Slot(8, n)
+}
+
+func (rcv *ScalarStuff) JustU8() byte {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(10))
+ if o != 0 {
+ return rcv._tab.GetByte(o + rcv._tab.Pos)
+ }
+ return 0
+}
+
+func (rcv *ScalarStuff) MutateJustU8(n byte) bool {
+ return rcv._tab.MutateByteSlot(10, n)
+}
+
+func (rcv *ScalarStuff) MaybeU8() *byte {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(12))
+ if o != 0 {
+ v := rcv._tab.GetByte(o + rcv._tab.Pos)
+ return &v
+ }
+ return nil
+}
+
+func (rcv *ScalarStuff) MutateMaybeU8(n byte) bool {
+ return rcv._tab.MutateByteSlot(12, n)
+}
+
+func (rcv *ScalarStuff) DefaultU8() byte {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(14))
+ if o != 0 {
+ return rcv._tab.GetByte(o + rcv._tab.Pos)
+ }
+ return 42
+}
+
+func (rcv *ScalarStuff) MutateDefaultU8(n byte) bool {
+ return rcv._tab.MutateByteSlot(14, n)
+}
+
+func (rcv *ScalarStuff) JustI16() int16 {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(16))
+ if o != 0 {
+ return rcv._tab.GetInt16(o + rcv._tab.Pos)
+ }
+ return 0
+}
+
+func (rcv *ScalarStuff) MutateJustI16(n int16) bool {
+ return rcv._tab.MutateInt16Slot(16, n)
+}
+
+func (rcv *ScalarStuff) MaybeI16() *int16 {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(18))
+ if o != 0 {
+ v := rcv._tab.GetInt16(o + rcv._tab.Pos)
+ return &v
+ }
+ return nil
+}
+
+func (rcv *ScalarStuff) MutateMaybeI16(n int16) bool {
+ return rcv._tab.MutateInt16Slot(18, n)
+}
+
+func (rcv *ScalarStuff) DefaultI16() int16 {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(20))
+ if o != 0 {
+ return rcv._tab.GetInt16(o + rcv._tab.Pos)
+ }
+ return 42
+}
+
+func (rcv *ScalarStuff) MutateDefaultI16(n int16) bool {
+ return rcv._tab.MutateInt16Slot(20, n)
+}
+
+func (rcv *ScalarStuff) JustU16() uint16 {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(22))
+ if o != 0 {
+ return rcv._tab.GetUint16(o + rcv._tab.Pos)
+ }
+ return 0
+}
+
+func (rcv *ScalarStuff) MutateJustU16(n uint16) bool {
+ return rcv._tab.MutateUint16Slot(22, n)
+}
+
+func (rcv *ScalarStuff) MaybeU16() *uint16 {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(24))
+ if o != 0 {
+ v := rcv._tab.GetUint16(o + rcv._tab.Pos)
+ return &v
+ }
+ return nil
+}
+
+func (rcv *ScalarStuff) MutateMaybeU16(n uint16) bool {
+ return rcv._tab.MutateUint16Slot(24, n)
+}
+
+func (rcv *ScalarStuff) DefaultU16() uint16 {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(26))
+ if o != 0 {
+ return rcv._tab.GetUint16(o + rcv._tab.Pos)
+ }
+ return 42
+}
+
+func (rcv *ScalarStuff) MutateDefaultU16(n uint16) bool {
+ return rcv._tab.MutateUint16Slot(26, n)
+}
+
+func (rcv *ScalarStuff) JustI32() int32 {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(28))
+ if o != 0 {
+ return rcv._tab.GetInt32(o + rcv._tab.Pos)
+ }
+ return 0
+}
+
+func (rcv *ScalarStuff) MutateJustI32(n int32) bool {
+ return rcv._tab.MutateInt32Slot(28, n)
+}
+
+func (rcv *ScalarStuff) MaybeI32() *int32 {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(30))
+ if o != 0 {
+ v := rcv._tab.GetInt32(o + rcv._tab.Pos)
+ return &v
+ }
+ return nil
+}
+
+func (rcv *ScalarStuff) MutateMaybeI32(n int32) bool {
+ return rcv._tab.MutateInt32Slot(30, n)
+}
+
+func (rcv *ScalarStuff) DefaultI32() int32 {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(32))
+ if o != 0 {
+ return rcv._tab.GetInt32(o + rcv._tab.Pos)
+ }
+ return 42
+}
+
+func (rcv *ScalarStuff) MutateDefaultI32(n int32) bool {
+ return rcv._tab.MutateInt32Slot(32, n)
+}
+
+func (rcv *ScalarStuff) JustU32() uint32 {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(34))
+ if o != 0 {
+ return rcv._tab.GetUint32(o + rcv._tab.Pos)
+ }
+ return 0
+}
+
+func (rcv *ScalarStuff) MutateJustU32(n uint32) bool {
+ return rcv._tab.MutateUint32Slot(34, n)
+}
+
+func (rcv *ScalarStuff) MaybeU32() *uint32 {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(36))
+ if o != 0 {
+ v := rcv._tab.GetUint32(o + rcv._tab.Pos)
+ return &v
+ }
+ return nil
+}
+
+func (rcv *ScalarStuff) MutateMaybeU32(n uint32) bool {
+ return rcv._tab.MutateUint32Slot(36, n)
+}
+
+func (rcv *ScalarStuff) DefaultU32() uint32 {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(38))
+ if o != 0 {
+ return rcv._tab.GetUint32(o + rcv._tab.Pos)
+ }
+ return 42
+}
+
+func (rcv *ScalarStuff) MutateDefaultU32(n uint32) bool {
+ return rcv._tab.MutateUint32Slot(38, n)
+}
+
+func (rcv *ScalarStuff) JustI64() int64 {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(40))
+ if o != 0 {
+ return rcv._tab.GetInt64(o + rcv._tab.Pos)
+ }
+ return 0
+}
+
+func (rcv *ScalarStuff) MutateJustI64(n int64) bool {
+ return rcv._tab.MutateInt64Slot(40, n)
+}
+
+func (rcv *ScalarStuff) MaybeI64() *int64 {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(42))
+ if o != 0 {
+ v := rcv._tab.GetInt64(o + rcv._tab.Pos)
+ return &v
+ }
+ return nil
+}
+
+func (rcv *ScalarStuff) MutateMaybeI64(n int64) bool {
+ return rcv._tab.MutateInt64Slot(42, n)
+}
+
+func (rcv *ScalarStuff) DefaultI64() int64 {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(44))
+ if o != 0 {
+ return rcv._tab.GetInt64(o + rcv._tab.Pos)
+ }
+ return 42
+}
+
+func (rcv *ScalarStuff) MutateDefaultI64(n int64) bool {
+ return rcv._tab.MutateInt64Slot(44, n)
+}
+
+func (rcv *ScalarStuff) JustU64() uint64 {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(46))
+ if o != 0 {
+ return rcv._tab.GetUint64(o + rcv._tab.Pos)
+ }
+ return 0
+}
+
+func (rcv *ScalarStuff) MutateJustU64(n uint64) bool {
+ return rcv._tab.MutateUint64Slot(46, n)
+}
+
+func (rcv *ScalarStuff) MaybeU64() *uint64 {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(48))
+ if o != 0 {
+ v := rcv._tab.GetUint64(o + rcv._tab.Pos)
+ return &v
+ }
+ return nil
+}
+
+func (rcv *ScalarStuff) MutateMaybeU64(n uint64) bool {
+ return rcv._tab.MutateUint64Slot(48, n)
+}
+
+func (rcv *ScalarStuff) DefaultU64() uint64 {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(50))
+ if o != 0 {
+ return rcv._tab.GetUint64(o + rcv._tab.Pos)
+ }
+ return 42
+}
+
+func (rcv *ScalarStuff) MutateDefaultU64(n uint64) bool {
+ return rcv._tab.MutateUint64Slot(50, n)
+}
+
+func (rcv *ScalarStuff) JustF32() float32 {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(52))
+ if o != 0 {
+ return rcv._tab.GetFloat32(o + rcv._tab.Pos)
+ }
+ return 0.0
+}
+
+func (rcv *ScalarStuff) MutateJustF32(n float32) bool {
+ return rcv._tab.MutateFloat32Slot(52, n)
+}
+
+func (rcv *ScalarStuff) MaybeF32() *float32 {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(54))
+ if o != 0 {
+ v := rcv._tab.GetFloat32(o + rcv._tab.Pos)
+ return &v
+ }
+ return nil
+}
+
+func (rcv *ScalarStuff) MutateMaybeF32(n float32) bool {
+ return rcv._tab.MutateFloat32Slot(54, n)
+}
+
+func (rcv *ScalarStuff) DefaultF32() float32 {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(56))
+ if o != 0 {
+ return rcv._tab.GetFloat32(o + rcv._tab.Pos)
+ }
+ return 42.0
+}
+
+func (rcv *ScalarStuff) MutateDefaultF32(n float32) bool {
+ return rcv._tab.MutateFloat32Slot(56, n)
+}
+
+func (rcv *ScalarStuff) JustF64() float64 {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(58))
+ if o != 0 {
+ return rcv._tab.GetFloat64(o + rcv._tab.Pos)
+ }
+ return 0.0
+}
+
+func (rcv *ScalarStuff) MutateJustF64(n float64) bool {
+ return rcv._tab.MutateFloat64Slot(58, n)
+}
+
+func (rcv *ScalarStuff) MaybeF64() *float64 {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(60))
+ if o != 0 {
+ v := rcv._tab.GetFloat64(o + rcv._tab.Pos)
+ return &v
+ }
+ return nil
+}
+
+func (rcv *ScalarStuff) MutateMaybeF64(n float64) bool {
+ return rcv._tab.MutateFloat64Slot(60, n)
+}
+
+func (rcv *ScalarStuff) DefaultF64() float64 {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(62))
+ if o != 0 {
+ return rcv._tab.GetFloat64(o + rcv._tab.Pos)
+ }
+ return 42.0
+}
+
+func (rcv *ScalarStuff) MutateDefaultF64(n float64) bool {
+ return rcv._tab.MutateFloat64Slot(62, n)
+}
+
+func (rcv *ScalarStuff) JustBool() bool {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(64))
+ if o != 0 {
+ return rcv._tab.GetBool(o + rcv._tab.Pos)
+ }
+ return false
+}
+
+func (rcv *ScalarStuff) MutateJustBool(n bool) bool {
+ return rcv._tab.MutateBoolSlot(64, n)
+}
+
+func (rcv *ScalarStuff) MaybeBool() *bool {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(66))
+ if o != 0 {
+ v := rcv._tab.GetBool(o + rcv._tab.Pos)
+ return &v
+ }
+ return nil
+}
+
+func (rcv *ScalarStuff) MutateMaybeBool(n bool) bool {
+ return rcv._tab.MutateBoolSlot(66, n)
+}
+
+func (rcv *ScalarStuff) DefaultBool() bool {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(68))
+ if o != 0 {
+ return rcv._tab.GetBool(o + rcv._tab.Pos)
+ }
+ return true
+}
+
+func (rcv *ScalarStuff) MutateDefaultBool(n bool) bool {
+ return rcv._tab.MutateBoolSlot(68, n)
+}
+
+func (rcv *ScalarStuff) JustEnum() OptionalByte {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(70))
+ if o != 0 {
+ return OptionalByte(rcv._tab.GetInt8(o + rcv._tab.Pos))
+ }
+ return 0
+}
+
+func (rcv *ScalarStuff) MutateJustEnum(n OptionalByte) bool {
+ return rcv._tab.MutateInt8Slot(70, int8(n))
+}
+
+func (rcv *ScalarStuff) MaybeEnum() *OptionalByte {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(72))
+ if o != 0 {
+ v := OptionalByte(rcv._tab.GetInt8(o + rcv._tab.Pos))
+ return &v
+ }
+ return nil
+}
+
+func (rcv *ScalarStuff) MutateMaybeEnum(n OptionalByte) bool {
+ return rcv._tab.MutateInt8Slot(72, int8(n))
+}
+
+func (rcv *ScalarStuff) DefaultEnum() OptionalByte {
+ o := flatbuffers.UOffsetT(rcv._tab.Offset(74))
+ if o != 0 {
+ return OptionalByte(rcv._tab.GetInt8(o + rcv._tab.Pos))
+ }
+ return 1
+}
+
+func (rcv *ScalarStuff) MutateDefaultEnum(n OptionalByte) bool {
+ return rcv._tab.MutateInt8Slot(74, int8(n))
+}
+
+func ScalarStuffStart(builder *flatbuffers.Builder) {
+ builder.StartObject(36)
+}
+func ScalarStuffAddJustI8(builder *flatbuffers.Builder, justI8 int8) {
+ builder.PrependInt8Slot(0, justI8, 0)
+}
+func ScalarStuffAddMaybeI8(builder *flatbuffers.Builder, maybeI8 int8) {
+ builder.PrependInt8(maybeI8)
+ builder.Slot(1)
+}
+func ScalarStuffAddDefaultI8(builder *flatbuffers.Builder, defaultI8 int8) {
+ builder.PrependInt8Slot(2, defaultI8, 42)
+}
+func ScalarStuffAddJustU8(builder *flatbuffers.Builder, justU8 byte) {
+ builder.PrependByteSlot(3, justU8, 0)
+}
+func ScalarStuffAddMaybeU8(builder *flatbuffers.Builder, maybeU8 byte) {
+ builder.PrependByte(maybeU8)
+ builder.Slot(4)
+}
+func ScalarStuffAddDefaultU8(builder *flatbuffers.Builder, defaultU8 byte) {
+ builder.PrependByteSlot(5, defaultU8, 42)
+}
+func ScalarStuffAddJustI16(builder *flatbuffers.Builder, justI16 int16) {
+ builder.PrependInt16Slot(6, justI16, 0)
+}
+func ScalarStuffAddMaybeI16(builder *flatbuffers.Builder, maybeI16 int16) {
+ builder.PrependInt16(maybeI16)
+ builder.Slot(7)
+}
+func ScalarStuffAddDefaultI16(builder *flatbuffers.Builder, defaultI16 int16) {
+ builder.PrependInt16Slot(8, defaultI16, 42)
+}
+func ScalarStuffAddJustU16(builder *flatbuffers.Builder, justU16 uint16) {
+ builder.PrependUint16Slot(9, justU16, 0)
+}
+func ScalarStuffAddMaybeU16(builder *flatbuffers.Builder, maybeU16 uint16) {
+ builder.PrependUint16(maybeU16)
+ builder.Slot(10)
+}
+func ScalarStuffAddDefaultU16(builder *flatbuffers.Builder, defaultU16 uint16) {
+ builder.PrependUint16Slot(11, defaultU16, 42)
+}
+func ScalarStuffAddJustI32(builder *flatbuffers.Builder, justI32 int32) {
+ builder.PrependInt32Slot(12, justI32, 0)
+}
+func ScalarStuffAddMaybeI32(builder *flatbuffers.Builder, maybeI32 int32) {
+ builder.PrependInt32(maybeI32)
+ builder.Slot(13)
+}
+func ScalarStuffAddDefaultI32(builder *flatbuffers.Builder, defaultI32 int32) {
+ builder.PrependInt32Slot(14, defaultI32, 42)
+}
+func ScalarStuffAddJustU32(builder *flatbuffers.Builder, justU32 uint32) {
+ builder.PrependUint32Slot(15, justU32, 0)
+}
+func ScalarStuffAddMaybeU32(builder *flatbuffers.Builder, maybeU32 uint32) {
+ builder.PrependUint32(maybeU32)
+ builder.Slot(16)
+}
+func ScalarStuffAddDefaultU32(builder *flatbuffers.Builder, defaultU32 uint32) {
+ builder.PrependUint32Slot(17, defaultU32, 42)
+}
+func ScalarStuffAddJustI64(builder *flatbuffers.Builder, justI64 int64) {
+ builder.PrependInt64Slot(18, justI64, 0)
+}
+func ScalarStuffAddMaybeI64(builder *flatbuffers.Builder, maybeI64 int64) {
+ builder.PrependInt64(maybeI64)
+ builder.Slot(19)
+}
+func ScalarStuffAddDefaultI64(builder *flatbuffers.Builder, defaultI64 int64) {
+ builder.PrependInt64Slot(20, defaultI64, 42)
+}
+func ScalarStuffAddJustU64(builder *flatbuffers.Builder, justU64 uint64) {
+ builder.PrependUint64Slot(21, justU64, 0)
+}
+func ScalarStuffAddMaybeU64(builder *flatbuffers.Builder, maybeU64 uint64) {
+ builder.PrependUint64(maybeU64)
+ builder.Slot(22)
+}
+func ScalarStuffAddDefaultU64(builder *flatbuffers.Builder, defaultU64 uint64) {
+ builder.PrependUint64Slot(23, defaultU64, 42)
+}
+func ScalarStuffAddJustF32(builder *flatbuffers.Builder, justF32 float32) {
+ builder.PrependFloat32Slot(24, justF32, 0.0)
+}
+func ScalarStuffAddMaybeF32(builder *flatbuffers.Builder, maybeF32 float32) {
+ builder.PrependFloat32(maybeF32)
+ builder.Slot(25)
+}
+func ScalarStuffAddDefaultF32(builder *flatbuffers.Builder, defaultF32 float32) {
+ builder.PrependFloat32Slot(26, defaultF32, 42.0)
+}
+func ScalarStuffAddJustF64(builder *flatbuffers.Builder, justF64 float64) {
+ builder.PrependFloat64Slot(27, justF64, 0.0)
+}
+func ScalarStuffAddMaybeF64(builder *flatbuffers.Builder, maybeF64 float64) {
+ builder.PrependFloat64(maybeF64)
+ builder.Slot(28)
+}
+func ScalarStuffAddDefaultF64(builder *flatbuffers.Builder, defaultF64 float64) {
+ builder.PrependFloat64Slot(29, defaultF64, 42.0)
+}
+func ScalarStuffAddJustBool(builder *flatbuffers.Builder, justBool bool) {
+ builder.PrependBoolSlot(30, justBool, false)
+}
+func ScalarStuffAddMaybeBool(builder *flatbuffers.Builder, maybeBool bool) {
+ builder.PrependBool(maybeBool)
+ builder.Slot(31)
+}
+func ScalarStuffAddDefaultBool(builder *flatbuffers.Builder, defaultBool bool) {
+ builder.PrependBoolSlot(32, defaultBool, true)
+}
+func ScalarStuffAddJustEnum(builder *flatbuffers.Builder, justEnum OptionalByte) {
+ builder.PrependInt8Slot(33, int8(justEnum), 0)
+}
+func ScalarStuffAddMaybeEnum(builder *flatbuffers.Builder, maybeEnum OptionalByte) {
+ builder.PrependInt8(int8(maybeEnum))
+ builder.Slot(34)
+}
+func ScalarStuffAddDefaultEnum(builder *flatbuffers.Builder, defaultEnum OptionalByte) {
+ builder.PrependInt8Slot(35, int8(defaultEnum), 1)
+}
+func ScalarStuffEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT {
+ return builder.EndObject()
+}
diff --git a/tests/optional_scalars/ScalarStuff.java b/tests/optional_scalars/ScalarStuff.java
index 3689292..e415210 100644
--- a/tests/optional_scalars/ScalarStuff.java
+++ b/tests/optional_scalars/ScalarStuff.java
@@ -9,7 +9,7 @@
@SuppressWarnings("unused")
public final class ScalarStuff extends Table {
- public static void ValidateVersion() { Constants.FLATBUFFERS_1_12_0(); }
+ public static void ValidateVersion() { Constants.FLATBUFFERS_2_0_0(); }
public static ScalarStuff getRootAsScalarStuff(ByteBuffer _bb) { return getRootAsScalarStuff(_bb, new ScalarStuff()); }
public static ScalarStuff getRootAsScalarStuff(ByteBuffer _bb, ScalarStuff obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
public static boolean ScalarStuffBufferHasIdentifier(ByteBuffer _bb) { return __has_identifier(_bb, "NULL"); }
@@ -66,79 +66,79 @@
public byte defaultEnum() { int o = __offset(74); return o != 0 ? bb.get(o + bb_pos) : 1; }
public static int createScalarStuff(FlatBufferBuilder builder,
- byte just_i8,
- byte maybe_i8,
- byte default_i8,
- int just_u8,
- int maybe_u8,
- int default_u8,
- short just_i16,
- short maybe_i16,
- short default_i16,
- int just_u16,
- int maybe_u16,
- int default_u16,
- int just_i32,
- int maybe_i32,
- int default_i32,
- long just_u32,
- long maybe_u32,
- long default_u32,
- long just_i64,
- long maybe_i64,
- long default_i64,
- long just_u64,
- long maybe_u64,
- long default_u64,
- float just_f32,
- float maybe_f32,
- float default_f32,
- double just_f64,
- double maybe_f64,
- double default_f64,
- boolean just_bool,
- boolean maybe_bool,
- boolean default_bool,
- byte just_enum,
- byte maybe_enum,
- byte default_enum) {
+ byte justI8,
+ byte maybeI8,
+ byte defaultI8,
+ int justU8,
+ int maybeU8,
+ int defaultU8,
+ short justI16,
+ short maybeI16,
+ short defaultI16,
+ int justU16,
+ int maybeU16,
+ int defaultU16,
+ int justI32,
+ int maybeI32,
+ int defaultI32,
+ long justU32,
+ long maybeU32,
+ long defaultU32,
+ long justI64,
+ long maybeI64,
+ long defaultI64,
+ long justU64,
+ long maybeU64,
+ long defaultU64,
+ float justF32,
+ float maybeF32,
+ float defaultF32,
+ double justF64,
+ double maybeF64,
+ double defaultF64,
+ boolean justBool,
+ boolean maybeBool,
+ boolean defaultBool,
+ byte justEnum,
+ byte maybeEnum,
+ byte defaultEnum) {
builder.startTable(36);
- ScalarStuff.addDefaultF64(builder, default_f64);
- ScalarStuff.addMaybeF64(builder, maybe_f64);
- ScalarStuff.addJustF64(builder, just_f64);
- ScalarStuff.addDefaultU64(builder, default_u64);
- ScalarStuff.addMaybeU64(builder, maybe_u64);
- ScalarStuff.addJustU64(builder, just_u64);
- ScalarStuff.addDefaultI64(builder, default_i64);
- ScalarStuff.addMaybeI64(builder, maybe_i64);
- ScalarStuff.addJustI64(builder, just_i64);
- ScalarStuff.addDefaultF32(builder, default_f32);
- ScalarStuff.addMaybeF32(builder, maybe_f32);
- ScalarStuff.addJustF32(builder, just_f32);
- ScalarStuff.addDefaultU32(builder, default_u32);
- ScalarStuff.addMaybeU32(builder, maybe_u32);
- ScalarStuff.addJustU32(builder, just_u32);
- ScalarStuff.addDefaultI32(builder, default_i32);
- ScalarStuff.addMaybeI32(builder, maybe_i32);
- ScalarStuff.addJustI32(builder, just_i32);
- ScalarStuff.addDefaultU16(builder, default_u16);
- ScalarStuff.addMaybeU16(builder, maybe_u16);
- ScalarStuff.addJustU16(builder, just_u16);
- ScalarStuff.addDefaultI16(builder, default_i16);
- ScalarStuff.addMaybeI16(builder, maybe_i16);
- ScalarStuff.addJustI16(builder, just_i16);
- ScalarStuff.addDefaultEnum(builder, default_enum);
- ScalarStuff.addMaybeEnum(builder, maybe_enum);
- ScalarStuff.addJustEnum(builder, just_enum);
- ScalarStuff.addDefaultBool(builder, default_bool);
- ScalarStuff.addMaybeBool(builder, maybe_bool);
- ScalarStuff.addJustBool(builder, just_bool);
- ScalarStuff.addDefaultU8(builder, default_u8);
- ScalarStuff.addMaybeU8(builder, maybe_u8);
- ScalarStuff.addJustU8(builder, just_u8);
- ScalarStuff.addDefaultI8(builder, default_i8);
- ScalarStuff.addMaybeI8(builder, maybe_i8);
- ScalarStuff.addJustI8(builder, just_i8);
+ ScalarStuff.addDefaultF64(builder, defaultF64);
+ ScalarStuff.addMaybeF64(builder, maybeF64);
+ ScalarStuff.addJustF64(builder, justF64);
+ ScalarStuff.addDefaultU64(builder, defaultU64);
+ ScalarStuff.addMaybeU64(builder, maybeU64);
+ ScalarStuff.addJustU64(builder, justU64);
+ ScalarStuff.addDefaultI64(builder, defaultI64);
+ ScalarStuff.addMaybeI64(builder, maybeI64);
+ ScalarStuff.addJustI64(builder, justI64);
+ ScalarStuff.addDefaultF32(builder, defaultF32);
+ ScalarStuff.addMaybeF32(builder, maybeF32);
+ ScalarStuff.addJustF32(builder, justF32);
+ ScalarStuff.addDefaultU32(builder, defaultU32);
+ ScalarStuff.addMaybeU32(builder, maybeU32);
+ ScalarStuff.addJustU32(builder, justU32);
+ ScalarStuff.addDefaultI32(builder, defaultI32);
+ ScalarStuff.addMaybeI32(builder, maybeI32);
+ ScalarStuff.addJustI32(builder, justI32);
+ ScalarStuff.addDefaultU16(builder, defaultU16);
+ ScalarStuff.addMaybeU16(builder, maybeU16);
+ ScalarStuff.addJustU16(builder, justU16);
+ ScalarStuff.addDefaultI16(builder, defaultI16);
+ ScalarStuff.addMaybeI16(builder, maybeI16);
+ ScalarStuff.addJustI16(builder, justI16);
+ ScalarStuff.addDefaultEnum(builder, defaultEnum);
+ ScalarStuff.addMaybeEnum(builder, maybeEnum);
+ ScalarStuff.addJustEnum(builder, justEnum);
+ ScalarStuff.addDefaultBool(builder, defaultBool);
+ ScalarStuff.addMaybeBool(builder, maybeBool);
+ ScalarStuff.addJustBool(builder, justBool);
+ ScalarStuff.addDefaultU8(builder, defaultU8);
+ ScalarStuff.addMaybeU8(builder, maybeU8);
+ ScalarStuff.addJustU8(builder, justU8);
+ ScalarStuff.addDefaultI8(builder, defaultI8);
+ ScalarStuff.addMaybeI8(builder, maybeI8);
+ ScalarStuff.addJustI8(builder, justI8);
return ScalarStuff.endScalarStuff(builder);
}
@@ -146,21 +146,21 @@
public static void addJustI8(FlatBufferBuilder builder, byte justI8) { builder.addByte(0, justI8, 0); }
public static void addMaybeI8(FlatBufferBuilder builder, byte maybeI8) { builder.addByte(1, maybeI8, 0); }
public static void addDefaultI8(FlatBufferBuilder builder, byte defaultI8) { builder.addByte(2, defaultI8, 42); }
- public static void addJustU8(FlatBufferBuilder builder, int justU8) { builder.addByte(3, (byte)justU8, (byte)0); }
- public static void addMaybeU8(FlatBufferBuilder builder, int maybeU8) { builder.addByte(4, (byte)maybeU8, (byte)0); }
- public static void addDefaultU8(FlatBufferBuilder builder, int defaultU8) { builder.addByte(5, (byte)defaultU8, (byte)42); }
+ public static void addJustU8(FlatBufferBuilder builder, int justU8) { builder.addByte(3, (byte) justU8, (byte) 0); }
+ public static void addMaybeU8(FlatBufferBuilder builder, int maybeU8) { builder.addByte(4, (byte) maybeU8, (byte) 0); }
+ public static void addDefaultU8(FlatBufferBuilder builder, int defaultU8) { builder.addByte(5, (byte) defaultU8, (byte) 42); }
public static void addJustI16(FlatBufferBuilder builder, short justI16) { builder.addShort(6, justI16, 0); }
public static void addMaybeI16(FlatBufferBuilder builder, short maybeI16) { builder.addShort(7, maybeI16, 0); }
public static void addDefaultI16(FlatBufferBuilder builder, short defaultI16) { builder.addShort(8, defaultI16, 42); }
- public static void addJustU16(FlatBufferBuilder builder, int justU16) { builder.addShort(9, (short)justU16, (short)0); }
- public static void addMaybeU16(FlatBufferBuilder builder, int maybeU16) { builder.addShort(10, (short)maybeU16, (short)0); }
- public static void addDefaultU16(FlatBufferBuilder builder, int defaultU16) { builder.addShort(11, (short)defaultU16, (short)42); }
+ public static void addJustU16(FlatBufferBuilder builder, int justU16) { builder.addShort(9, (short) justU16, (short) 0); }
+ public static void addMaybeU16(FlatBufferBuilder builder, int maybeU16) { builder.addShort(10, (short) maybeU16, (short) 0); }
+ public static void addDefaultU16(FlatBufferBuilder builder, int defaultU16) { builder.addShort(11, (short) defaultU16, (short) 42); }
public static void addJustI32(FlatBufferBuilder builder, int justI32) { builder.addInt(12, justI32, 0); }
public static void addMaybeI32(FlatBufferBuilder builder, int maybeI32) { builder.addInt(13, maybeI32, 0); }
public static void addDefaultI32(FlatBufferBuilder builder, int defaultI32) { builder.addInt(14, defaultI32, 42); }
- public static void addJustU32(FlatBufferBuilder builder, long justU32) { builder.addInt(15, (int)justU32, (int)0L); }
- public static void addMaybeU32(FlatBufferBuilder builder, long maybeU32) { builder.addInt(16, (int)maybeU32, (int)0L); }
- public static void addDefaultU32(FlatBufferBuilder builder, long defaultU32) { builder.addInt(17, (int)defaultU32, (int)42L); }
+ public static void addJustU32(FlatBufferBuilder builder, long justU32) { builder.addInt(15, (int) justU32, (int) 0L); }
+ public static void addMaybeU32(FlatBufferBuilder builder, long maybeU32) { builder.addInt(16, (int) maybeU32, (int) 0L); }
+ public static void addDefaultU32(FlatBufferBuilder builder, long defaultU32) { builder.addInt(17, (int) defaultU32, (int) 42L); }
public static void addJustI64(FlatBufferBuilder builder, long justI64) { builder.addLong(18, justI64, 0L); }
public static void addMaybeI64(FlatBufferBuilder builder, long maybeI64) { builder.addLong(19, maybeI64, 0L); }
public static void addDefaultI64(FlatBufferBuilder builder, long defaultI64) { builder.addLong(20, defaultI64, 42L); }
diff --git a/tests/optional_scalars/ScalarStuff.kt b/tests/optional_scalars/ScalarStuff.kt
index 5728384..5ab8bf4 100644
--- a/tests/optional_scalars/ScalarStuff.kt
+++ b/tests/optional_scalars/ScalarStuff.kt
@@ -7,7 +7,6 @@
import com.google.flatbuffers.*
@Suppress("unused")
-@ExperimentalUnsignedTypes
class ScalarStuff : Table() {
fun __init(_i: Int, _bb: ByteBuffer) {
@@ -198,7 +197,7 @@
return if(o != 0) bb.get(o + bb_pos) else 1
}
companion object {
- fun validateVersion() = Constants.FLATBUFFERS_1_12_0()
+ fun validateVersion() = Constants.FLATBUFFERS_2_0_0()
fun getRootAsScalarStuff(_bb: ByteBuffer): ScalarStuff = getRootAsScalarStuff(_bb, ScalarStuff())
fun getRootAsScalarStuff(_bb: ByteBuffer, obj: ScalarStuff): ScalarStuff {
_bb.order(ByteOrder.LITTLE_ENDIAN)
diff --git a/tests/optional_scalars/mod.rs b/tests/optional_scalars/mod.rs
new file mode 100644
index 0000000..b7af3c5
--- /dev/null
+++ b/tests/optional_scalars/mod.rs
@@ -0,0 +1,8 @@
+// Automatically generated by the Flatbuffers compiler. Do not modify.
+pub mod optional_scalars {
+ use super::*;
+ mod optional_byte_generated;
+ pub use self::optional_byte_generated::*;
+ mod scalar_stuff_generated;
+ pub use self::scalar_stuff_generated::*;
+} // optional_scalars
diff --git a/tests/optional_scalars/optional-byte.js b/tests/optional_scalars/optional-byte.js
new file mode 100644
index 0000000..8257f93
--- /dev/null
+++ b/tests/optional_scalars/optional-byte.js
@@ -0,0 +1,7 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+export var OptionalByte;
+(function (OptionalByte) {
+ OptionalByte[OptionalByte["None"] = 0] = "None";
+ OptionalByte[OptionalByte["One"] = 1] = "One";
+ OptionalByte[OptionalByte["Two"] = 2] = "Two";
+})(OptionalByte || (OptionalByte = {}));
diff --git a/tests/optional_scalars/optional-byte.ts b/tests/optional_scalars/optional-byte.ts
new file mode 100644
index 0000000..1db479f
--- /dev/null
+++ b/tests/optional_scalars/optional-byte.ts
@@ -0,0 +1,8 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+export enum OptionalByte{
+ None = 0,
+ One = 1,
+ Two = 2
+}
+
diff --git a/tests/optional_scalars/optional_scalars/optional_byte_generated.rs b/tests/optional_scalars/optional_scalars/optional_byte_generated.rs
new file mode 100644
index 0000000..226e9ec
--- /dev/null
+++ b/tests/optional_scalars/optional_scalars/optional_byte_generated.rs
@@ -0,0 +1,97 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+pub const ENUM_MIN_OPTIONAL_BYTE: i8 = 0;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+pub const ENUM_MAX_OPTIONAL_BYTE: i8 = 2;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+#[allow(non_camel_case_types)]
+pub const ENUM_VALUES_OPTIONAL_BYTE: [OptionalByte; 3] = [
+ OptionalByte::None,
+ OptionalByte::One,
+ OptionalByte::Two,
+];
+
+#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
+#[repr(transparent)]
+pub struct OptionalByte(pub i8);
+#[allow(non_upper_case_globals)]
+impl OptionalByte {
+ pub const None: Self = Self(0);
+ pub const One: Self = Self(1);
+ pub const Two: Self = Self(2);
+
+ pub const ENUM_MIN: i8 = 0;
+ pub const ENUM_MAX: i8 = 2;
+ pub const ENUM_VALUES: &'static [Self] = &[
+ Self::None,
+ Self::One,
+ Self::Two,
+ ];
+ /// Returns the variant's name or "" if unknown.
+ pub fn variant_name(self) -> Option<&'static str> {
+ match self {
+ Self::None => Some("None"),
+ Self::One => Some("One"),
+ Self::Two => Some("Two"),
+ _ => None,
+ }
+ }
+}
+impl std::fmt::Debug for OptionalByte {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ if let Some(name) = self.variant_name() {
+ f.write_str(name)
+ } else {
+ f.write_fmt(format_args!("<UNKNOWN {:?}>", self.0))
+ }
+ }
+}
+impl<'a> flatbuffers::Follow<'a> for OptionalByte {
+ type Inner = Self;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ let b = unsafe {
+ flatbuffers::read_scalar_at::<i8>(buf, loc)
+ };
+ Self(b)
+ }
+}
+
+impl flatbuffers::Push for OptionalByte {
+ type Output = OptionalByte;
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ unsafe { flatbuffers::emplace_scalar::<i8>(dst, self.0); }
+ }
+}
+
+impl flatbuffers::EndianScalar for OptionalByte {
+ #[inline]
+ fn to_little_endian(self) -> Self {
+ let b = i8::to_le(self.0);
+ Self(b)
+ }
+ #[inline]
+ #[allow(clippy::wrong_self_convention)]
+ fn from_little_endian(self) -> Self {
+ let b = i8::from_le(self.0);
+ Self(b)
+ }
+}
+
+impl<'a> flatbuffers::Verifiable for OptionalByte {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ i8::run_verifier(v, pos)
+ }
+}
+
+impl flatbuffers::SimpleToVerifyInSlice for OptionalByte {}
diff --git a/tests/optional_scalars/optional_scalars/scalar_stuff_generated.rs b/tests/optional_scalars/optional_scalars/scalar_stuff_generated.rs
new file mode 100644
index 0000000..407e278
--- /dev/null
+++ b/tests/optional_scalars/optional_scalars/scalar_stuff_generated.rs
@@ -0,0 +1,930 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+extern crate flatbuffers;
+use std::mem;
+use std::cmp::Ordering;
+use self::flatbuffers::{EndianScalar, Follow};
+use super::*;
+pub enum ScalarStuffOffset {}
+#[derive(Copy, Clone, PartialEq)]
+
+pub struct ScalarStuff<'a> {
+ pub _tab: flatbuffers::Table<'a>,
+}
+
+impl<'a> flatbuffers::Follow<'a> for ScalarStuff<'a> {
+ type Inner = ScalarStuff<'a>;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ Self { _tab: flatbuffers::Table { buf, loc } }
+ }
+}
+
+impl<'a> ScalarStuff<'a> {
+ pub const VT_JUST_I8: flatbuffers::VOffsetT = 4;
+ pub const VT_MAYBE_I8: flatbuffers::VOffsetT = 6;
+ pub const VT_DEFAULT_I8: flatbuffers::VOffsetT = 8;
+ pub const VT_JUST_U8: flatbuffers::VOffsetT = 10;
+ pub const VT_MAYBE_U8: flatbuffers::VOffsetT = 12;
+ pub const VT_DEFAULT_U8: flatbuffers::VOffsetT = 14;
+ pub const VT_JUST_I16: flatbuffers::VOffsetT = 16;
+ pub const VT_MAYBE_I16: flatbuffers::VOffsetT = 18;
+ pub const VT_DEFAULT_I16: flatbuffers::VOffsetT = 20;
+ pub const VT_JUST_U16: flatbuffers::VOffsetT = 22;
+ pub const VT_MAYBE_U16: flatbuffers::VOffsetT = 24;
+ pub const VT_DEFAULT_U16: flatbuffers::VOffsetT = 26;
+ pub const VT_JUST_I32: flatbuffers::VOffsetT = 28;
+ pub const VT_MAYBE_I32: flatbuffers::VOffsetT = 30;
+ pub const VT_DEFAULT_I32: flatbuffers::VOffsetT = 32;
+ pub const VT_JUST_U32: flatbuffers::VOffsetT = 34;
+ pub const VT_MAYBE_U32: flatbuffers::VOffsetT = 36;
+ pub const VT_DEFAULT_U32: flatbuffers::VOffsetT = 38;
+ pub const VT_JUST_I64: flatbuffers::VOffsetT = 40;
+ pub const VT_MAYBE_I64: flatbuffers::VOffsetT = 42;
+ pub const VT_DEFAULT_I64: flatbuffers::VOffsetT = 44;
+ pub const VT_JUST_U64: flatbuffers::VOffsetT = 46;
+ pub const VT_MAYBE_U64: flatbuffers::VOffsetT = 48;
+ pub const VT_DEFAULT_U64: flatbuffers::VOffsetT = 50;
+ pub const VT_JUST_F32: flatbuffers::VOffsetT = 52;
+ pub const VT_MAYBE_F32: flatbuffers::VOffsetT = 54;
+ pub const VT_DEFAULT_F32: flatbuffers::VOffsetT = 56;
+ pub const VT_JUST_F64: flatbuffers::VOffsetT = 58;
+ pub const VT_MAYBE_F64: flatbuffers::VOffsetT = 60;
+ pub const VT_DEFAULT_F64: flatbuffers::VOffsetT = 62;
+ pub const VT_JUST_BOOL: flatbuffers::VOffsetT = 64;
+ pub const VT_MAYBE_BOOL: flatbuffers::VOffsetT = 66;
+ pub const VT_DEFAULT_BOOL: flatbuffers::VOffsetT = 68;
+ pub const VT_JUST_ENUM: flatbuffers::VOffsetT = 70;
+ pub const VT_MAYBE_ENUM: flatbuffers::VOffsetT = 72;
+ pub const VT_DEFAULT_ENUM: flatbuffers::VOffsetT = 74;
+
+ pub const fn get_fully_qualified_name() -> &'static str {
+ "optional_scalars.ScalarStuff"
+ }
+
+ #[inline]
+ pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
+ ScalarStuff { _tab: table }
+ }
+ #[allow(unused_mut)]
+ pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
+ _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
+ args: &'args ScalarStuffArgs
+ ) -> flatbuffers::WIPOffset<ScalarStuff<'bldr>> {
+ let mut builder = ScalarStuffBuilder::new(_fbb);
+ builder.add_default_f64(args.default_f64);
+ if let Some(x) = args.maybe_f64 { builder.add_maybe_f64(x); }
+ builder.add_just_f64(args.just_f64);
+ builder.add_default_u64(args.default_u64);
+ if let Some(x) = args.maybe_u64 { builder.add_maybe_u64(x); }
+ builder.add_just_u64(args.just_u64);
+ builder.add_default_i64(args.default_i64);
+ if let Some(x) = args.maybe_i64 { builder.add_maybe_i64(x); }
+ builder.add_just_i64(args.just_i64);
+ builder.add_default_f32(args.default_f32);
+ if let Some(x) = args.maybe_f32 { builder.add_maybe_f32(x); }
+ builder.add_just_f32(args.just_f32);
+ builder.add_default_u32(args.default_u32);
+ if let Some(x) = args.maybe_u32 { builder.add_maybe_u32(x); }
+ builder.add_just_u32(args.just_u32);
+ builder.add_default_i32(args.default_i32);
+ if let Some(x) = args.maybe_i32 { builder.add_maybe_i32(x); }
+ builder.add_just_i32(args.just_i32);
+ builder.add_default_u16(args.default_u16);
+ if let Some(x) = args.maybe_u16 { builder.add_maybe_u16(x); }
+ builder.add_just_u16(args.just_u16);
+ builder.add_default_i16(args.default_i16);
+ if let Some(x) = args.maybe_i16 { builder.add_maybe_i16(x); }
+ builder.add_just_i16(args.just_i16);
+ builder.add_default_enum(args.default_enum);
+ if let Some(x) = args.maybe_enum { builder.add_maybe_enum(x); }
+ builder.add_just_enum(args.just_enum);
+ builder.add_default_bool(args.default_bool);
+ if let Some(x) = args.maybe_bool { builder.add_maybe_bool(x); }
+ builder.add_just_bool(args.just_bool);
+ builder.add_default_u8(args.default_u8);
+ if let Some(x) = args.maybe_u8 { builder.add_maybe_u8(x); }
+ builder.add_just_u8(args.just_u8);
+ builder.add_default_i8(args.default_i8);
+ if let Some(x) = args.maybe_i8 { builder.add_maybe_i8(x); }
+ builder.add_just_i8(args.just_i8);
+ builder.finish()
+ }
+
+ pub fn unpack(&self) -> ScalarStuffT {
+ let just_i8 = self.just_i8();
+ let maybe_i8 = self.maybe_i8();
+ let default_i8 = self.default_i8();
+ let just_u8 = self.just_u8();
+ let maybe_u8 = self.maybe_u8();
+ let default_u8 = self.default_u8();
+ let just_i16 = self.just_i16();
+ let maybe_i16 = self.maybe_i16();
+ let default_i16 = self.default_i16();
+ let just_u16 = self.just_u16();
+ let maybe_u16 = self.maybe_u16();
+ let default_u16 = self.default_u16();
+ let just_i32 = self.just_i32();
+ let maybe_i32 = self.maybe_i32();
+ let default_i32 = self.default_i32();
+ let just_u32 = self.just_u32();
+ let maybe_u32 = self.maybe_u32();
+ let default_u32 = self.default_u32();
+ let just_i64 = self.just_i64();
+ let maybe_i64 = self.maybe_i64();
+ let default_i64 = self.default_i64();
+ let just_u64 = self.just_u64();
+ let maybe_u64 = self.maybe_u64();
+ let default_u64 = self.default_u64();
+ let just_f32 = self.just_f32();
+ let maybe_f32 = self.maybe_f32();
+ let default_f32 = self.default_f32();
+ let just_f64 = self.just_f64();
+ let maybe_f64 = self.maybe_f64();
+ let default_f64 = self.default_f64();
+ let just_bool = self.just_bool();
+ let maybe_bool = self.maybe_bool();
+ let default_bool = self.default_bool();
+ let just_enum = self.just_enum();
+ let maybe_enum = self.maybe_enum();
+ let default_enum = self.default_enum();
+ ScalarStuffT {
+ just_i8,
+ maybe_i8,
+ default_i8,
+ just_u8,
+ maybe_u8,
+ default_u8,
+ just_i16,
+ maybe_i16,
+ default_i16,
+ just_u16,
+ maybe_u16,
+ default_u16,
+ just_i32,
+ maybe_i32,
+ default_i32,
+ just_u32,
+ maybe_u32,
+ default_u32,
+ just_i64,
+ maybe_i64,
+ default_i64,
+ just_u64,
+ maybe_u64,
+ default_u64,
+ just_f32,
+ maybe_f32,
+ default_f32,
+ just_f64,
+ maybe_f64,
+ default_f64,
+ just_bool,
+ maybe_bool,
+ default_bool,
+ just_enum,
+ maybe_enum,
+ default_enum,
+ }
+ }
+
+ #[inline]
+ pub fn just_i8(&self) -> i8 {
+ self._tab.get::<i8>(ScalarStuff::VT_JUST_I8, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn maybe_i8(&self) -> Option<i8> {
+ self._tab.get::<i8>(ScalarStuff::VT_MAYBE_I8, None)
+ }
+ #[inline]
+ pub fn default_i8(&self) -> i8 {
+ self._tab.get::<i8>(ScalarStuff::VT_DEFAULT_I8, Some(42)).unwrap()
+ }
+ #[inline]
+ pub fn just_u8(&self) -> u8 {
+ self._tab.get::<u8>(ScalarStuff::VT_JUST_U8, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn maybe_u8(&self) -> Option<u8> {
+ self._tab.get::<u8>(ScalarStuff::VT_MAYBE_U8, None)
+ }
+ #[inline]
+ pub fn default_u8(&self) -> u8 {
+ self._tab.get::<u8>(ScalarStuff::VT_DEFAULT_U8, Some(42)).unwrap()
+ }
+ #[inline]
+ pub fn just_i16(&self) -> i16 {
+ self._tab.get::<i16>(ScalarStuff::VT_JUST_I16, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn maybe_i16(&self) -> Option<i16> {
+ self._tab.get::<i16>(ScalarStuff::VT_MAYBE_I16, None)
+ }
+ #[inline]
+ pub fn default_i16(&self) -> i16 {
+ self._tab.get::<i16>(ScalarStuff::VT_DEFAULT_I16, Some(42)).unwrap()
+ }
+ #[inline]
+ pub fn just_u16(&self) -> u16 {
+ self._tab.get::<u16>(ScalarStuff::VT_JUST_U16, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn maybe_u16(&self) -> Option<u16> {
+ self._tab.get::<u16>(ScalarStuff::VT_MAYBE_U16, None)
+ }
+ #[inline]
+ pub fn default_u16(&self) -> u16 {
+ self._tab.get::<u16>(ScalarStuff::VT_DEFAULT_U16, Some(42)).unwrap()
+ }
+ #[inline]
+ pub fn just_i32(&self) -> i32 {
+ self._tab.get::<i32>(ScalarStuff::VT_JUST_I32, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn maybe_i32(&self) -> Option<i32> {
+ self._tab.get::<i32>(ScalarStuff::VT_MAYBE_I32, None)
+ }
+ #[inline]
+ pub fn default_i32(&self) -> i32 {
+ self._tab.get::<i32>(ScalarStuff::VT_DEFAULT_I32, Some(42)).unwrap()
+ }
+ #[inline]
+ pub fn just_u32(&self) -> u32 {
+ self._tab.get::<u32>(ScalarStuff::VT_JUST_U32, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn maybe_u32(&self) -> Option<u32> {
+ self._tab.get::<u32>(ScalarStuff::VT_MAYBE_U32, None)
+ }
+ #[inline]
+ pub fn default_u32(&self) -> u32 {
+ self._tab.get::<u32>(ScalarStuff::VT_DEFAULT_U32, Some(42)).unwrap()
+ }
+ #[inline]
+ pub fn just_i64(&self) -> i64 {
+ self._tab.get::<i64>(ScalarStuff::VT_JUST_I64, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn maybe_i64(&self) -> Option<i64> {
+ self._tab.get::<i64>(ScalarStuff::VT_MAYBE_I64, None)
+ }
+ #[inline]
+ pub fn default_i64(&self) -> i64 {
+ self._tab.get::<i64>(ScalarStuff::VT_DEFAULT_I64, Some(42)).unwrap()
+ }
+ #[inline]
+ pub fn just_u64(&self) -> u64 {
+ self._tab.get::<u64>(ScalarStuff::VT_JUST_U64, Some(0)).unwrap()
+ }
+ #[inline]
+ pub fn maybe_u64(&self) -> Option<u64> {
+ self._tab.get::<u64>(ScalarStuff::VT_MAYBE_U64, None)
+ }
+ #[inline]
+ pub fn default_u64(&self) -> u64 {
+ self._tab.get::<u64>(ScalarStuff::VT_DEFAULT_U64, Some(42)).unwrap()
+ }
+ #[inline]
+ pub fn just_f32(&self) -> f32 {
+ self._tab.get::<f32>(ScalarStuff::VT_JUST_F32, Some(0.0)).unwrap()
+ }
+ #[inline]
+ pub fn maybe_f32(&self) -> Option<f32> {
+ self._tab.get::<f32>(ScalarStuff::VT_MAYBE_F32, None)
+ }
+ #[inline]
+ pub fn default_f32(&self) -> f32 {
+ self._tab.get::<f32>(ScalarStuff::VT_DEFAULT_F32, Some(42.0)).unwrap()
+ }
+ #[inline]
+ pub fn just_f64(&self) -> f64 {
+ self._tab.get::<f64>(ScalarStuff::VT_JUST_F64, Some(0.0)).unwrap()
+ }
+ #[inline]
+ pub fn maybe_f64(&self) -> Option<f64> {
+ self._tab.get::<f64>(ScalarStuff::VT_MAYBE_F64, None)
+ }
+ #[inline]
+ pub fn default_f64(&self) -> f64 {
+ self._tab.get::<f64>(ScalarStuff::VT_DEFAULT_F64, Some(42.0)).unwrap()
+ }
+ #[inline]
+ pub fn just_bool(&self) -> bool {
+ self._tab.get::<bool>(ScalarStuff::VT_JUST_BOOL, Some(false)).unwrap()
+ }
+ #[inline]
+ pub fn maybe_bool(&self) -> Option<bool> {
+ self._tab.get::<bool>(ScalarStuff::VT_MAYBE_BOOL, None)
+ }
+ #[inline]
+ pub fn default_bool(&self) -> bool {
+ self._tab.get::<bool>(ScalarStuff::VT_DEFAULT_BOOL, Some(true)).unwrap()
+ }
+ #[inline]
+ pub fn just_enum(&self) -> OptionalByte {
+ self._tab.get::<OptionalByte>(ScalarStuff::VT_JUST_ENUM, Some(OptionalByte::None)).unwrap()
+ }
+ #[inline]
+ pub fn maybe_enum(&self) -> Option<OptionalByte> {
+ self._tab.get::<OptionalByte>(ScalarStuff::VT_MAYBE_ENUM, None)
+ }
+ #[inline]
+ pub fn default_enum(&self) -> OptionalByte {
+ self._tab.get::<OptionalByte>(ScalarStuff::VT_DEFAULT_ENUM, Some(OptionalByte::One)).unwrap()
+ }
+}
+
+impl flatbuffers::Verifiable for ScalarStuff<'_> {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ v.visit_table(pos)?
+ .visit_field::<i8>("just_i8", Self::VT_JUST_I8, false)?
+ .visit_field::<i8>("maybe_i8", Self::VT_MAYBE_I8, false)?
+ .visit_field::<i8>("default_i8", Self::VT_DEFAULT_I8, false)?
+ .visit_field::<u8>("just_u8", Self::VT_JUST_U8, false)?
+ .visit_field::<u8>("maybe_u8", Self::VT_MAYBE_U8, false)?
+ .visit_field::<u8>("default_u8", Self::VT_DEFAULT_U8, false)?
+ .visit_field::<i16>("just_i16", Self::VT_JUST_I16, false)?
+ .visit_field::<i16>("maybe_i16", Self::VT_MAYBE_I16, false)?
+ .visit_field::<i16>("default_i16", Self::VT_DEFAULT_I16, false)?
+ .visit_field::<u16>("just_u16", Self::VT_JUST_U16, false)?
+ .visit_field::<u16>("maybe_u16", Self::VT_MAYBE_U16, false)?
+ .visit_field::<u16>("default_u16", Self::VT_DEFAULT_U16, false)?
+ .visit_field::<i32>("just_i32", Self::VT_JUST_I32, false)?
+ .visit_field::<i32>("maybe_i32", Self::VT_MAYBE_I32, false)?
+ .visit_field::<i32>("default_i32", Self::VT_DEFAULT_I32, false)?
+ .visit_field::<u32>("just_u32", Self::VT_JUST_U32, false)?
+ .visit_field::<u32>("maybe_u32", Self::VT_MAYBE_U32, false)?
+ .visit_field::<u32>("default_u32", Self::VT_DEFAULT_U32, false)?
+ .visit_field::<i64>("just_i64", Self::VT_JUST_I64, false)?
+ .visit_field::<i64>("maybe_i64", Self::VT_MAYBE_I64, false)?
+ .visit_field::<i64>("default_i64", Self::VT_DEFAULT_I64, false)?
+ .visit_field::<u64>("just_u64", Self::VT_JUST_U64, false)?
+ .visit_field::<u64>("maybe_u64", Self::VT_MAYBE_U64, false)?
+ .visit_field::<u64>("default_u64", Self::VT_DEFAULT_U64, false)?
+ .visit_field::<f32>("just_f32", Self::VT_JUST_F32, false)?
+ .visit_field::<f32>("maybe_f32", Self::VT_MAYBE_F32, false)?
+ .visit_field::<f32>("default_f32", Self::VT_DEFAULT_F32, false)?
+ .visit_field::<f64>("just_f64", Self::VT_JUST_F64, false)?
+ .visit_field::<f64>("maybe_f64", Self::VT_MAYBE_F64, false)?
+ .visit_field::<f64>("default_f64", Self::VT_DEFAULT_F64, false)?
+ .visit_field::<bool>("just_bool", Self::VT_JUST_BOOL, false)?
+ .visit_field::<bool>("maybe_bool", Self::VT_MAYBE_BOOL, false)?
+ .visit_field::<bool>("default_bool", Self::VT_DEFAULT_BOOL, false)?
+ .visit_field::<OptionalByte>("just_enum", Self::VT_JUST_ENUM, false)?
+ .visit_field::<OptionalByte>("maybe_enum", Self::VT_MAYBE_ENUM, false)?
+ .visit_field::<OptionalByte>("default_enum", Self::VT_DEFAULT_ENUM, false)?
+ .finish();
+ Ok(())
+ }
+}
+pub struct ScalarStuffArgs {
+ pub just_i8: i8,
+ pub maybe_i8: Option<i8>,
+ pub default_i8: i8,
+ pub just_u8: u8,
+ pub maybe_u8: Option<u8>,
+ pub default_u8: u8,
+ pub just_i16: i16,
+ pub maybe_i16: Option<i16>,
+ pub default_i16: i16,
+ pub just_u16: u16,
+ pub maybe_u16: Option<u16>,
+ pub default_u16: u16,
+ pub just_i32: i32,
+ pub maybe_i32: Option<i32>,
+ pub default_i32: i32,
+ pub just_u32: u32,
+ pub maybe_u32: Option<u32>,
+ pub default_u32: u32,
+ pub just_i64: i64,
+ pub maybe_i64: Option<i64>,
+ pub default_i64: i64,
+ pub just_u64: u64,
+ pub maybe_u64: Option<u64>,
+ pub default_u64: u64,
+ pub just_f32: f32,
+ pub maybe_f32: Option<f32>,
+ pub default_f32: f32,
+ pub just_f64: f64,
+ pub maybe_f64: Option<f64>,
+ pub default_f64: f64,
+ pub just_bool: bool,
+ pub maybe_bool: Option<bool>,
+ pub default_bool: bool,
+ pub just_enum: OptionalByte,
+ pub maybe_enum: Option<OptionalByte>,
+ pub default_enum: OptionalByte,
+}
+impl<'a> Default for ScalarStuffArgs {
+ #[inline]
+ fn default() -> Self {
+ ScalarStuffArgs {
+ just_i8: 0,
+ maybe_i8: None,
+ default_i8: 42,
+ just_u8: 0,
+ maybe_u8: None,
+ default_u8: 42,
+ just_i16: 0,
+ maybe_i16: None,
+ default_i16: 42,
+ just_u16: 0,
+ maybe_u16: None,
+ default_u16: 42,
+ just_i32: 0,
+ maybe_i32: None,
+ default_i32: 42,
+ just_u32: 0,
+ maybe_u32: None,
+ default_u32: 42,
+ just_i64: 0,
+ maybe_i64: None,
+ default_i64: 42,
+ just_u64: 0,
+ maybe_u64: None,
+ default_u64: 42,
+ just_f32: 0.0,
+ maybe_f32: None,
+ default_f32: 42.0,
+ just_f64: 0.0,
+ maybe_f64: None,
+ default_f64: 42.0,
+ just_bool: false,
+ maybe_bool: None,
+ default_bool: true,
+ just_enum: OptionalByte::None,
+ maybe_enum: None,
+ default_enum: OptionalByte::One,
+ }
+ }
+}
+
+pub struct ScalarStuffBuilder<'a: 'b, 'b> {
+ fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
+ start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
+}
+impl<'a: 'b, 'b> ScalarStuffBuilder<'a, 'b> {
+ #[inline]
+ pub fn add_just_i8(&mut self, just_i8: i8) {
+ self.fbb_.push_slot::<i8>(ScalarStuff::VT_JUST_I8, just_i8, 0);
+ }
+ #[inline]
+ pub fn add_maybe_i8(&mut self, maybe_i8: i8) {
+ self.fbb_.push_slot_always::<i8>(ScalarStuff::VT_MAYBE_I8, maybe_i8);
+ }
+ #[inline]
+ pub fn add_default_i8(&mut self, default_i8: i8) {
+ self.fbb_.push_slot::<i8>(ScalarStuff::VT_DEFAULT_I8, default_i8, 42);
+ }
+ #[inline]
+ pub fn add_just_u8(&mut self, just_u8: u8) {
+ self.fbb_.push_slot::<u8>(ScalarStuff::VT_JUST_U8, just_u8, 0);
+ }
+ #[inline]
+ pub fn add_maybe_u8(&mut self, maybe_u8: u8) {
+ self.fbb_.push_slot_always::<u8>(ScalarStuff::VT_MAYBE_U8, maybe_u8);
+ }
+ #[inline]
+ pub fn add_default_u8(&mut self, default_u8: u8) {
+ self.fbb_.push_slot::<u8>(ScalarStuff::VT_DEFAULT_U8, default_u8, 42);
+ }
+ #[inline]
+ pub fn add_just_i16(&mut self, just_i16: i16) {
+ self.fbb_.push_slot::<i16>(ScalarStuff::VT_JUST_I16, just_i16, 0);
+ }
+ #[inline]
+ pub fn add_maybe_i16(&mut self, maybe_i16: i16) {
+ self.fbb_.push_slot_always::<i16>(ScalarStuff::VT_MAYBE_I16, maybe_i16);
+ }
+ #[inline]
+ pub fn add_default_i16(&mut self, default_i16: i16) {
+ self.fbb_.push_slot::<i16>(ScalarStuff::VT_DEFAULT_I16, default_i16, 42);
+ }
+ #[inline]
+ pub fn add_just_u16(&mut self, just_u16: u16) {
+ self.fbb_.push_slot::<u16>(ScalarStuff::VT_JUST_U16, just_u16, 0);
+ }
+ #[inline]
+ pub fn add_maybe_u16(&mut self, maybe_u16: u16) {
+ self.fbb_.push_slot_always::<u16>(ScalarStuff::VT_MAYBE_U16, maybe_u16);
+ }
+ #[inline]
+ pub fn add_default_u16(&mut self, default_u16: u16) {
+ self.fbb_.push_slot::<u16>(ScalarStuff::VT_DEFAULT_U16, default_u16, 42);
+ }
+ #[inline]
+ pub fn add_just_i32(&mut self, just_i32: i32) {
+ self.fbb_.push_slot::<i32>(ScalarStuff::VT_JUST_I32, just_i32, 0);
+ }
+ #[inline]
+ pub fn add_maybe_i32(&mut self, maybe_i32: i32) {
+ self.fbb_.push_slot_always::<i32>(ScalarStuff::VT_MAYBE_I32, maybe_i32);
+ }
+ #[inline]
+ pub fn add_default_i32(&mut self, default_i32: i32) {
+ self.fbb_.push_slot::<i32>(ScalarStuff::VT_DEFAULT_I32, default_i32, 42);
+ }
+ #[inline]
+ pub fn add_just_u32(&mut self, just_u32: u32) {
+ self.fbb_.push_slot::<u32>(ScalarStuff::VT_JUST_U32, just_u32, 0);
+ }
+ #[inline]
+ pub fn add_maybe_u32(&mut self, maybe_u32: u32) {
+ self.fbb_.push_slot_always::<u32>(ScalarStuff::VT_MAYBE_U32, maybe_u32);
+ }
+ #[inline]
+ pub fn add_default_u32(&mut self, default_u32: u32) {
+ self.fbb_.push_slot::<u32>(ScalarStuff::VT_DEFAULT_U32, default_u32, 42);
+ }
+ #[inline]
+ pub fn add_just_i64(&mut self, just_i64: i64) {
+ self.fbb_.push_slot::<i64>(ScalarStuff::VT_JUST_I64, just_i64, 0);
+ }
+ #[inline]
+ pub fn add_maybe_i64(&mut self, maybe_i64: i64) {
+ self.fbb_.push_slot_always::<i64>(ScalarStuff::VT_MAYBE_I64, maybe_i64);
+ }
+ #[inline]
+ pub fn add_default_i64(&mut self, default_i64: i64) {
+ self.fbb_.push_slot::<i64>(ScalarStuff::VT_DEFAULT_I64, default_i64, 42);
+ }
+ #[inline]
+ pub fn add_just_u64(&mut self, just_u64: u64) {
+ self.fbb_.push_slot::<u64>(ScalarStuff::VT_JUST_U64, just_u64, 0);
+ }
+ #[inline]
+ pub fn add_maybe_u64(&mut self, maybe_u64: u64) {
+ self.fbb_.push_slot_always::<u64>(ScalarStuff::VT_MAYBE_U64, maybe_u64);
+ }
+ #[inline]
+ pub fn add_default_u64(&mut self, default_u64: u64) {
+ self.fbb_.push_slot::<u64>(ScalarStuff::VT_DEFAULT_U64, default_u64, 42);
+ }
+ #[inline]
+ pub fn add_just_f32(&mut self, just_f32: f32) {
+ self.fbb_.push_slot::<f32>(ScalarStuff::VT_JUST_F32, just_f32, 0.0);
+ }
+ #[inline]
+ pub fn add_maybe_f32(&mut self, maybe_f32: f32) {
+ self.fbb_.push_slot_always::<f32>(ScalarStuff::VT_MAYBE_F32, maybe_f32);
+ }
+ #[inline]
+ pub fn add_default_f32(&mut self, default_f32: f32) {
+ self.fbb_.push_slot::<f32>(ScalarStuff::VT_DEFAULT_F32, default_f32, 42.0);
+ }
+ #[inline]
+ pub fn add_just_f64(&mut self, just_f64: f64) {
+ self.fbb_.push_slot::<f64>(ScalarStuff::VT_JUST_F64, just_f64, 0.0);
+ }
+ #[inline]
+ pub fn add_maybe_f64(&mut self, maybe_f64: f64) {
+ self.fbb_.push_slot_always::<f64>(ScalarStuff::VT_MAYBE_F64, maybe_f64);
+ }
+ #[inline]
+ pub fn add_default_f64(&mut self, default_f64: f64) {
+ self.fbb_.push_slot::<f64>(ScalarStuff::VT_DEFAULT_F64, default_f64, 42.0);
+ }
+ #[inline]
+ pub fn add_just_bool(&mut self, just_bool: bool) {
+ self.fbb_.push_slot::<bool>(ScalarStuff::VT_JUST_BOOL, just_bool, false);
+ }
+ #[inline]
+ pub fn add_maybe_bool(&mut self, maybe_bool: bool) {
+ self.fbb_.push_slot_always::<bool>(ScalarStuff::VT_MAYBE_BOOL, maybe_bool);
+ }
+ #[inline]
+ pub fn add_default_bool(&mut self, default_bool: bool) {
+ self.fbb_.push_slot::<bool>(ScalarStuff::VT_DEFAULT_BOOL, default_bool, true);
+ }
+ #[inline]
+ pub fn add_just_enum(&mut self, just_enum: OptionalByte) {
+ self.fbb_.push_slot::<OptionalByte>(ScalarStuff::VT_JUST_ENUM, just_enum, OptionalByte::None);
+ }
+ #[inline]
+ pub fn add_maybe_enum(&mut self, maybe_enum: OptionalByte) {
+ self.fbb_.push_slot_always::<OptionalByte>(ScalarStuff::VT_MAYBE_ENUM, maybe_enum);
+ }
+ #[inline]
+ pub fn add_default_enum(&mut self, default_enum: OptionalByte) {
+ self.fbb_.push_slot::<OptionalByte>(ScalarStuff::VT_DEFAULT_ENUM, default_enum, OptionalByte::One);
+ }
+ #[inline]
+ pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> ScalarStuffBuilder<'a, 'b> {
+ let start = _fbb.start_table();
+ ScalarStuffBuilder {
+ fbb_: _fbb,
+ start_: start,
+ }
+ }
+ #[inline]
+ pub fn finish(self) -> flatbuffers::WIPOffset<ScalarStuff<'a>> {
+ let o = self.fbb_.end_table(self.start_);
+ flatbuffers::WIPOffset::new(o.value())
+ }
+}
+
+impl std::fmt::Debug for ScalarStuff<'_> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let mut ds = f.debug_struct("ScalarStuff");
+ ds.field("just_i8", &self.just_i8());
+ ds.field("maybe_i8", &self.maybe_i8());
+ ds.field("default_i8", &self.default_i8());
+ ds.field("just_u8", &self.just_u8());
+ ds.field("maybe_u8", &self.maybe_u8());
+ ds.field("default_u8", &self.default_u8());
+ ds.field("just_i16", &self.just_i16());
+ ds.field("maybe_i16", &self.maybe_i16());
+ ds.field("default_i16", &self.default_i16());
+ ds.field("just_u16", &self.just_u16());
+ ds.field("maybe_u16", &self.maybe_u16());
+ ds.field("default_u16", &self.default_u16());
+ ds.field("just_i32", &self.just_i32());
+ ds.field("maybe_i32", &self.maybe_i32());
+ ds.field("default_i32", &self.default_i32());
+ ds.field("just_u32", &self.just_u32());
+ ds.field("maybe_u32", &self.maybe_u32());
+ ds.field("default_u32", &self.default_u32());
+ ds.field("just_i64", &self.just_i64());
+ ds.field("maybe_i64", &self.maybe_i64());
+ ds.field("default_i64", &self.default_i64());
+ ds.field("just_u64", &self.just_u64());
+ ds.field("maybe_u64", &self.maybe_u64());
+ ds.field("default_u64", &self.default_u64());
+ ds.field("just_f32", &self.just_f32());
+ ds.field("maybe_f32", &self.maybe_f32());
+ ds.field("default_f32", &self.default_f32());
+ ds.field("just_f64", &self.just_f64());
+ ds.field("maybe_f64", &self.maybe_f64());
+ ds.field("default_f64", &self.default_f64());
+ ds.field("just_bool", &self.just_bool());
+ ds.field("maybe_bool", &self.maybe_bool());
+ ds.field("default_bool", &self.default_bool());
+ ds.field("just_enum", &self.just_enum());
+ ds.field("maybe_enum", &self.maybe_enum());
+ ds.field("default_enum", &self.default_enum());
+ ds.finish()
+ }
+}
+#[non_exhaustive]
+#[derive(Debug, Clone, PartialEq)]
+pub struct ScalarStuffT {
+ pub just_i8: i8,
+ pub maybe_i8: Option<i8>,
+ pub default_i8: i8,
+ pub just_u8: u8,
+ pub maybe_u8: Option<u8>,
+ pub default_u8: u8,
+ pub just_i16: i16,
+ pub maybe_i16: Option<i16>,
+ pub default_i16: i16,
+ pub just_u16: u16,
+ pub maybe_u16: Option<u16>,
+ pub default_u16: u16,
+ pub just_i32: i32,
+ pub maybe_i32: Option<i32>,
+ pub default_i32: i32,
+ pub just_u32: u32,
+ pub maybe_u32: Option<u32>,
+ pub default_u32: u32,
+ pub just_i64: i64,
+ pub maybe_i64: Option<i64>,
+ pub default_i64: i64,
+ pub just_u64: u64,
+ pub maybe_u64: Option<u64>,
+ pub default_u64: u64,
+ pub just_f32: f32,
+ pub maybe_f32: Option<f32>,
+ pub default_f32: f32,
+ pub just_f64: f64,
+ pub maybe_f64: Option<f64>,
+ pub default_f64: f64,
+ pub just_bool: bool,
+ pub maybe_bool: Option<bool>,
+ pub default_bool: bool,
+ pub just_enum: OptionalByte,
+ pub maybe_enum: Option<OptionalByte>,
+ pub default_enum: OptionalByte,
+}
+impl Default for ScalarStuffT {
+ fn default() -> Self {
+ Self {
+ just_i8: 0,
+ maybe_i8: None,
+ default_i8: 42,
+ just_u8: 0,
+ maybe_u8: None,
+ default_u8: 42,
+ just_i16: 0,
+ maybe_i16: None,
+ default_i16: 42,
+ just_u16: 0,
+ maybe_u16: None,
+ default_u16: 42,
+ just_i32: 0,
+ maybe_i32: None,
+ default_i32: 42,
+ just_u32: 0,
+ maybe_u32: None,
+ default_u32: 42,
+ just_i64: 0,
+ maybe_i64: None,
+ default_i64: 42,
+ just_u64: 0,
+ maybe_u64: None,
+ default_u64: 42,
+ just_f32: 0.0,
+ maybe_f32: None,
+ default_f32: 42.0,
+ just_f64: 0.0,
+ maybe_f64: None,
+ default_f64: 42.0,
+ just_bool: false,
+ maybe_bool: None,
+ default_bool: true,
+ just_enum: OptionalByte::None,
+ maybe_enum: None,
+ default_enum: OptionalByte::One,
+ }
+ }
+}
+impl ScalarStuffT {
+ pub fn pack<'b>(
+ &self,
+ _fbb: &mut flatbuffers::FlatBufferBuilder<'b>
+ ) -> flatbuffers::WIPOffset<ScalarStuff<'b>> {
+ let just_i8 = self.just_i8;
+ let maybe_i8 = self.maybe_i8;
+ let default_i8 = self.default_i8;
+ let just_u8 = self.just_u8;
+ let maybe_u8 = self.maybe_u8;
+ let default_u8 = self.default_u8;
+ let just_i16 = self.just_i16;
+ let maybe_i16 = self.maybe_i16;
+ let default_i16 = self.default_i16;
+ let just_u16 = self.just_u16;
+ let maybe_u16 = self.maybe_u16;
+ let default_u16 = self.default_u16;
+ let just_i32 = self.just_i32;
+ let maybe_i32 = self.maybe_i32;
+ let default_i32 = self.default_i32;
+ let just_u32 = self.just_u32;
+ let maybe_u32 = self.maybe_u32;
+ let default_u32 = self.default_u32;
+ let just_i64 = self.just_i64;
+ let maybe_i64 = self.maybe_i64;
+ let default_i64 = self.default_i64;
+ let just_u64 = self.just_u64;
+ let maybe_u64 = self.maybe_u64;
+ let default_u64 = self.default_u64;
+ let just_f32 = self.just_f32;
+ let maybe_f32 = self.maybe_f32;
+ let default_f32 = self.default_f32;
+ let just_f64 = self.just_f64;
+ let maybe_f64 = self.maybe_f64;
+ let default_f64 = self.default_f64;
+ let just_bool = self.just_bool;
+ let maybe_bool = self.maybe_bool;
+ let default_bool = self.default_bool;
+ let just_enum = self.just_enum;
+ let maybe_enum = self.maybe_enum;
+ let default_enum = self.default_enum;
+ ScalarStuff::create(_fbb, &ScalarStuffArgs{
+ just_i8,
+ maybe_i8,
+ default_i8,
+ just_u8,
+ maybe_u8,
+ default_u8,
+ just_i16,
+ maybe_i16,
+ default_i16,
+ just_u16,
+ maybe_u16,
+ default_u16,
+ just_i32,
+ maybe_i32,
+ default_i32,
+ just_u32,
+ maybe_u32,
+ default_u32,
+ just_i64,
+ maybe_i64,
+ default_i64,
+ just_u64,
+ maybe_u64,
+ default_u64,
+ just_f32,
+ maybe_f32,
+ default_f32,
+ just_f64,
+ maybe_f64,
+ default_f64,
+ just_bool,
+ maybe_bool,
+ default_bool,
+ just_enum,
+ maybe_enum,
+ default_enum,
+ })
+ }
+}
+#[inline]
+#[deprecated(since="2.0.0", note="Deprecated in favor of `root_as...` methods.")]
+pub fn get_root_as_scalar_stuff<'a>(buf: &'a [u8]) -> ScalarStuff<'a> {
+ unsafe { flatbuffers::root_unchecked::<ScalarStuff<'a>>(buf) }
+}
+
+#[inline]
+#[deprecated(since="2.0.0", note="Deprecated in favor of `root_as...` methods.")]
+pub fn get_size_prefixed_root_as_scalar_stuff<'a>(buf: &'a [u8]) -> ScalarStuff<'a> {
+ unsafe { flatbuffers::size_prefixed_root_unchecked::<ScalarStuff<'a>>(buf) }
+}
+
+#[inline]
+/// Verifies that a buffer of bytes contains a `ScalarStuff`
+/// and returns it.
+/// Note that verification is still experimental and may not
+/// catch every error, or be maximally performant. For the
+/// previous, unchecked, behavior use
+/// `root_as_scalar_stuff_unchecked`.
+pub fn root_as_scalar_stuff(buf: &[u8]) -> Result<ScalarStuff, flatbuffers::InvalidFlatbuffer> {
+ flatbuffers::root::<ScalarStuff>(buf)
+}
+#[inline]
+/// Verifies that a buffer of bytes contains a size prefixed
+/// `ScalarStuff` and returns it.
+/// Note that verification is still experimental and may not
+/// catch every error, or be maximally performant. For the
+/// previous, unchecked, behavior use
+/// `size_prefixed_root_as_scalar_stuff_unchecked`.
+pub fn size_prefixed_root_as_scalar_stuff(buf: &[u8]) -> Result<ScalarStuff, flatbuffers::InvalidFlatbuffer> {
+ flatbuffers::size_prefixed_root::<ScalarStuff>(buf)
+}
+#[inline]
+/// Verifies, with the given options, that a buffer of bytes
+/// contains a `ScalarStuff` and returns it.
+/// Note that verification is still experimental and may not
+/// catch every error, or be maximally performant. For the
+/// previous, unchecked, behavior use
+/// `root_as_scalar_stuff_unchecked`.
+pub fn root_as_scalar_stuff_with_opts<'b, 'o>(
+ opts: &'o flatbuffers::VerifierOptions,
+ buf: &'b [u8],
+) -> Result<ScalarStuff<'b>, flatbuffers::InvalidFlatbuffer> {
+ flatbuffers::root_with_opts::<ScalarStuff<'b>>(opts, buf)
+}
+#[inline]
+/// Verifies, with the given verifier options, that a buffer of
+/// bytes contains a size prefixed `ScalarStuff` and returns
+/// it. Note that verification is still experimental and may not
+/// catch every error, or be maximally performant. For the
+/// previous, unchecked, behavior use
+/// `root_as_scalar_stuff_unchecked`.
+pub fn size_prefixed_root_as_scalar_stuff_with_opts<'b, 'o>(
+ opts: &'o flatbuffers::VerifierOptions,
+ buf: &'b [u8],
+) -> Result<ScalarStuff<'b>, flatbuffers::InvalidFlatbuffer> {
+ flatbuffers::size_prefixed_root_with_opts::<ScalarStuff<'b>>(opts, buf)
+}
+#[inline]
+/// Assumes, without verification, that a buffer of bytes contains a ScalarStuff and returns it.
+/// # Safety
+/// Callers must trust the given bytes do indeed contain a valid `ScalarStuff`.
+pub unsafe fn root_as_scalar_stuff_unchecked(buf: &[u8]) -> ScalarStuff {
+ flatbuffers::root_unchecked::<ScalarStuff>(buf)
+}
+#[inline]
+/// Assumes, without verification, that a buffer of bytes contains a size prefixed ScalarStuff and returns it.
+/// # Safety
+/// Callers must trust the given bytes do indeed contain a valid size prefixed `ScalarStuff`.
+pub unsafe fn size_prefixed_root_as_scalar_stuff_unchecked(buf: &[u8]) -> ScalarStuff {
+ flatbuffers::size_prefixed_root_unchecked::<ScalarStuff>(buf)
+}
+pub const SCALAR_STUFF_IDENTIFIER: &str = "NULL";
+
+#[inline]
+pub fn scalar_stuff_buffer_has_identifier(buf: &[u8]) -> bool {
+ flatbuffers::buffer_has_identifier(buf, SCALAR_STUFF_IDENTIFIER, false)
+}
+
+#[inline]
+pub fn scalar_stuff_size_prefixed_buffer_has_identifier(buf: &[u8]) -> bool {
+ flatbuffers::buffer_has_identifier(buf, SCALAR_STUFF_IDENTIFIER, true)
+}
+
+pub const SCALAR_STUFF_EXTENSION: &str = "mon";
+
+#[inline]
+pub fn finish_scalar_stuff_buffer<'a, 'b>(
+ fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,
+ root: flatbuffers::WIPOffset<ScalarStuff<'a>>) {
+ fbb.finish(root, Some(SCALAR_STUFF_IDENTIFIER));
+}
+
+#[inline]
+pub fn finish_size_prefixed_scalar_stuff_buffer<'a, 'b>(fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>, root: flatbuffers::WIPOffset<ScalarStuff<'a>>) {
+ fbb.finish_size_prefixed(root, Some(SCALAR_STUFF_IDENTIFIER));
+}
diff --git a/tests/optional_scalars/scalar-stuff.js b/tests/optional_scalars/scalar-stuff.js
new file mode 100644
index 0000000..f02b885
--- /dev/null
+++ b/tests/optional_scalars/scalar-stuff.js
@@ -0,0 +1,341 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+import * as flatbuffers from 'flatbuffers';
+import { OptionalByte } from '../optional_scalars/optional-byte';
+export class ScalarStuff {
+ constructor() {
+ this.bb = null;
+ this.bb_pos = 0;
+ }
+ __init(i, bb) {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+ }
+ static getRootAsScalarStuff(bb, obj) {
+ return (obj || new ScalarStuff()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ static getSizePrefixedRootAsScalarStuff(bb, obj) {
+ bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new ScalarStuff()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ static bufferHasIdentifier(bb) {
+ return bb.__has_identifier('NULL');
+ }
+ justI8() {
+ const offset = this.bb.__offset(this.bb_pos, 4);
+ return offset ? this.bb.readInt8(this.bb_pos + offset) : 0;
+ }
+ maybeI8() {
+ const offset = this.bb.__offset(this.bb_pos, 6);
+ return offset ? this.bb.readInt8(this.bb_pos + offset) : null;
+ }
+ defaultI8() {
+ const offset = this.bb.__offset(this.bb_pos, 8);
+ return offset ? this.bb.readInt8(this.bb_pos + offset) : 42;
+ }
+ justU8() {
+ const offset = this.bb.__offset(this.bb_pos, 10);
+ return offset ? this.bb.readUint8(this.bb_pos + offset) : 0;
+ }
+ maybeU8() {
+ const offset = this.bb.__offset(this.bb_pos, 12);
+ return offset ? this.bb.readUint8(this.bb_pos + offset) : null;
+ }
+ defaultU8() {
+ const offset = this.bb.__offset(this.bb_pos, 14);
+ return offset ? this.bb.readUint8(this.bb_pos + offset) : 42;
+ }
+ justI16() {
+ const offset = this.bb.__offset(this.bb_pos, 16);
+ return offset ? this.bb.readInt16(this.bb_pos + offset) : 0;
+ }
+ maybeI16() {
+ const offset = this.bb.__offset(this.bb_pos, 18);
+ return offset ? this.bb.readInt16(this.bb_pos + offset) : null;
+ }
+ defaultI16() {
+ const offset = this.bb.__offset(this.bb_pos, 20);
+ return offset ? this.bb.readInt16(this.bb_pos + offset) : 42;
+ }
+ justU16() {
+ const offset = this.bb.__offset(this.bb_pos, 22);
+ return offset ? this.bb.readUint16(this.bb_pos + offset) : 0;
+ }
+ maybeU16() {
+ const offset = this.bb.__offset(this.bb_pos, 24);
+ return offset ? this.bb.readUint16(this.bb_pos + offset) : null;
+ }
+ defaultU16() {
+ const offset = this.bb.__offset(this.bb_pos, 26);
+ return offset ? this.bb.readUint16(this.bb_pos + offset) : 42;
+ }
+ justI32() {
+ const offset = this.bb.__offset(this.bb_pos, 28);
+ return offset ? this.bb.readInt32(this.bb_pos + offset) : 0;
+ }
+ maybeI32() {
+ const offset = this.bb.__offset(this.bb_pos, 30);
+ return offset ? this.bb.readInt32(this.bb_pos + offset) : null;
+ }
+ defaultI32() {
+ const offset = this.bb.__offset(this.bb_pos, 32);
+ return offset ? this.bb.readInt32(this.bb_pos + offset) : 42;
+ }
+ justU32() {
+ const offset = this.bb.__offset(this.bb_pos, 34);
+ return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
+ }
+ maybeU32() {
+ const offset = this.bb.__offset(this.bb_pos, 36);
+ return offset ? this.bb.readUint32(this.bb_pos + offset) : null;
+ }
+ defaultU32() {
+ const offset = this.bb.__offset(this.bb_pos, 38);
+ return offset ? this.bb.readUint32(this.bb_pos + offset) : 42;
+ }
+ justI64() {
+ const offset = this.bb.__offset(this.bb_pos, 40);
+ return offset ? this.bb.readInt64(this.bb_pos + offset) : BigInt('0');
+ }
+ maybeI64() {
+ const offset = this.bb.__offset(this.bb_pos, 42);
+ return offset ? this.bb.readInt64(this.bb_pos + offset) : null;
+ }
+ defaultI64() {
+ const offset = this.bb.__offset(this.bb_pos, 44);
+ return offset ? this.bb.readInt64(this.bb_pos + offset) : BigInt('42');
+ }
+ justU64() {
+ const offset = this.bb.__offset(this.bb_pos, 46);
+ return offset ? this.bb.readUint64(this.bb_pos + offset) : BigInt('0');
+ }
+ maybeU64() {
+ const offset = this.bb.__offset(this.bb_pos, 48);
+ return offset ? this.bb.readUint64(this.bb_pos + offset) : null;
+ }
+ defaultU64() {
+ const offset = this.bb.__offset(this.bb_pos, 50);
+ return offset ? this.bb.readUint64(this.bb_pos + offset) : BigInt('42');
+ }
+ justF32() {
+ const offset = this.bb.__offset(this.bb_pos, 52);
+ return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0.0;
+ }
+ maybeF32() {
+ const offset = this.bb.__offset(this.bb_pos, 54);
+ return offset ? this.bb.readFloat32(this.bb_pos + offset) : null;
+ }
+ defaultF32() {
+ const offset = this.bb.__offset(this.bb_pos, 56);
+ return offset ? this.bb.readFloat32(this.bb_pos + offset) : 42.0;
+ }
+ justF64() {
+ const offset = this.bb.__offset(this.bb_pos, 58);
+ return offset ? this.bb.readFloat64(this.bb_pos + offset) : 0.0;
+ }
+ maybeF64() {
+ const offset = this.bb.__offset(this.bb_pos, 60);
+ return offset ? this.bb.readFloat64(this.bb_pos + offset) : null;
+ }
+ defaultF64() {
+ const offset = this.bb.__offset(this.bb_pos, 62);
+ return offset ? this.bb.readFloat64(this.bb_pos + offset) : 42.0;
+ }
+ justBool() {
+ const offset = this.bb.__offset(this.bb_pos, 64);
+ return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false;
+ }
+ maybeBool() {
+ const offset = this.bb.__offset(this.bb_pos, 66);
+ return offset ? !!this.bb.readInt8(this.bb_pos + offset) : null;
+ }
+ defaultBool() {
+ const offset = this.bb.__offset(this.bb_pos, 68);
+ return offset ? !!this.bb.readInt8(this.bb_pos + offset) : true;
+ }
+ justEnum() {
+ const offset = this.bb.__offset(this.bb_pos, 70);
+ return offset ? this.bb.readInt8(this.bb_pos + offset) : OptionalByte.None;
+ }
+ maybeEnum() {
+ const offset = this.bb.__offset(this.bb_pos, 72);
+ return offset ? this.bb.readInt8(this.bb_pos + offset) : null;
+ }
+ defaultEnum() {
+ const offset = this.bb.__offset(this.bb_pos, 74);
+ return offset ? this.bb.readInt8(this.bb_pos + offset) : OptionalByte.One;
+ }
+ static startScalarStuff(builder) {
+ builder.startObject(36);
+ }
+ static addJustI8(builder, justI8) {
+ builder.addFieldInt8(0, justI8, 0);
+ }
+ static addMaybeI8(builder, maybeI8) {
+ builder.addFieldInt8(1, maybeI8, 0);
+ }
+ static addDefaultI8(builder, defaultI8) {
+ builder.addFieldInt8(2, defaultI8, 42);
+ }
+ static addJustU8(builder, justU8) {
+ builder.addFieldInt8(3, justU8, 0);
+ }
+ static addMaybeU8(builder, maybeU8) {
+ builder.addFieldInt8(4, maybeU8, 0);
+ }
+ static addDefaultU8(builder, defaultU8) {
+ builder.addFieldInt8(5, defaultU8, 42);
+ }
+ static addJustI16(builder, justI16) {
+ builder.addFieldInt16(6, justI16, 0);
+ }
+ static addMaybeI16(builder, maybeI16) {
+ builder.addFieldInt16(7, maybeI16, 0);
+ }
+ static addDefaultI16(builder, defaultI16) {
+ builder.addFieldInt16(8, defaultI16, 42);
+ }
+ static addJustU16(builder, justU16) {
+ builder.addFieldInt16(9, justU16, 0);
+ }
+ static addMaybeU16(builder, maybeU16) {
+ builder.addFieldInt16(10, maybeU16, 0);
+ }
+ static addDefaultU16(builder, defaultU16) {
+ builder.addFieldInt16(11, defaultU16, 42);
+ }
+ static addJustI32(builder, justI32) {
+ builder.addFieldInt32(12, justI32, 0);
+ }
+ static addMaybeI32(builder, maybeI32) {
+ builder.addFieldInt32(13, maybeI32, 0);
+ }
+ static addDefaultI32(builder, defaultI32) {
+ builder.addFieldInt32(14, defaultI32, 42);
+ }
+ static addJustU32(builder, justU32) {
+ builder.addFieldInt32(15, justU32, 0);
+ }
+ static addMaybeU32(builder, maybeU32) {
+ builder.addFieldInt32(16, maybeU32, 0);
+ }
+ static addDefaultU32(builder, defaultU32) {
+ builder.addFieldInt32(17, defaultU32, 42);
+ }
+ static addJustI64(builder, justI64) {
+ builder.addFieldInt64(18, justI64, BigInt('0'));
+ }
+ static addMaybeI64(builder, maybeI64) {
+ builder.addFieldInt64(19, maybeI64, BigInt(0));
+ }
+ static addDefaultI64(builder, defaultI64) {
+ builder.addFieldInt64(20, defaultI64, BigInt('42'));
+ }
+ static addJustU64(builder, justU64) {
+ builder.addFieldInt64(21, justU64, BigInt('0'));
+ }
+ static addMaybeU64(builder, maybeU64) {
+ builder.addFieldInt64(22, maybeU64, BigInt(0));
+ }
+ static addDefaultU64(builder, defaultU64) {
+ builder.addFieldInt64(23, defaultU64, BigInt('42'));
+ }
+ static addJustF32(builder, justF32) {
+ builder.addFieldFloat32(24, justF32, 0.0);
+ }
+ static addMaybeF32(builder, maybeF32) {
+ builder.addFieldFloat32(25, maybeF32, 0);
+ }
+ static addDefaultF32(builder, defaultF32) {
+ builder.addFieldFloat32(26, defaultF32, 42.0);
+ }
+ static addJustF64(builder, justF64) {
+ builder.addFieldFloat64(27, justF64, 0.0);
+ }
+ static addMaybeF64(builder, maybeF64) {
+ builder.addFieldFloat64(28, maybeF64, 0);
+ }
+ static addDefaultF64(builder, defaultF64) {
+ builder.addFieldFloat64(29, defaultF64, 42.0);
+ }
+ static addJustBool(builder, justBool) {
+ builder.addFieldInt8(30, +justBool, +false);
+ }
+ static addMaybeBool(builder, maybeBool) {
+ builder.addFieldInt8(31, +maybeBool, 0);
+ }
+ static addDefaultBool(builder, defaultBool) {
+ builder.addFieldInt8(32, +defaultBool, +true);
+ }
+ static addJustEnum(builder, justEnum) {
+ builder.addFieldInt8(33, justEnum, OptionalByte.None);
+ }
+ static addMaybeEnum(builder, maybeEnum) {
+ builder.addFieldInt8(34, maybeEnum, 0);
+ }
+ static addDefaultEnum(builder, defaultEnum) {
+ builder.addFieldInt8(35, defaultEnum, OptionalByte.One);
+ }
+ static endScalarStuff(builder) {
+ const offset = builder.endObject();
+ return offset;
+ }
+ static finishScalarStuffBuffer(builder, offset) {
+ builder.finish(offset, 'NULL');
+ }
+ static finishSizePrefixedScalarStuffBuffer(builder, offset) {
+ builder.finish(offset, 'NULL', true);
+ }
+ static createScalarStuff(builder, justI8, maybeI8, defaultI8, justU8, maybeU8, defaultU8, justI16, maybeI16, defaultI16, justU16, maybeU16, defaultU16, justI32, maybeI32, defaultI32, justU32, maybeU32, defaultU32, justI64, maybeI64, defaultI64, justU64, maybeU64, defaultU64, justF32, maybeF32, defaultF32, justF64, maybeF64, defaultF64, justBool, maybeBool, defaultBool, justEnum, maybeEnum, defaultEnum) {
+ ScalarStuff.startScalarStuff(builder);
+ ScalarStuff.addJustI8(builder, justI8);
+ if (maybeI8 !== null)
+ ScalarStuff.addMaybeI8(builder, maybeI8);
+ ScalarStuff.addDefaultI8(builder, defaultI8);
+ ScalarStuff.addJustU8(builder, justU8);
+ if (maybeU8 !== null)
+ ScalarStuff.addMaybeU8(builder, maybeU8);
+ ScalarStuff.addDefaultU8(builder, defaultU8);
+ ScalarStuff.addJustI16(builder, justI16);
+ if (maybeI16 !== null)
+ ScalarStuff.addMaybeI16(builder, maybeI16);
+ ScalarStuff.addDefaultI16(builder, defaultI16);
+ ScalarStuff.addJustU16(builder, justU16);
+ if (maybeU16 !== null)
+ ScalarStuff.addMaybeU16(builder, maybeU16);
+ ScalarStuff.addDefaultU16(builder, defaultU16);
+ ScalarStuff.addJustI32(builder, justI32);
+ if (maybeI32 !== null)
+ ScalarStuff.addMaybeI32(builder, maybeI32);
+ ScalarStuff.addDefaultI32(builder, defaultI32);
+ ScalarStuff.addJustU32(builder, justU32);
+ if (maybeU32 !== null)
+ ScalarStuff.addMaybeU32(builder, maybeU32);
+ ScalarStuff.addDefaultU32(builder, defaultU32);
+ ScalarStuff.addJustI64(builder, justI64);
+ if (maybeI64 !== null)
+ ScalarStuff.addMaybeI64(builder, maybeI64);
+ ScalarStuff.addDefaultI64(builder, defaultI64);
+ ScalarStuff.addJustU64(builder, justU64);
+ if (maybeU64 !== null)
+ ScalarStuff.addMaybeU64(builder, maybeU64);
+ ScalarStuff.addDefaultU64(builder, defaultU64);
+ ScalarStuff.addJustF32(builder, justF32);
+ if (maybeF32 !== null)
+ ScalarStuff.addMaybeF32(builder, maybeF32);
+ ScalarStuff.addDefaultF32(builder, defaultF32);
+ ScalarStuff.addJustF64(builder, justF64);
+ if (maybeF64 !== null)
+ ScalarStuff.addMaybeF64(builder, maybeF64);
+ ScalarStuff.addDefaultF64(builder, defaultF64);
+ ScalarStuff.addJustBool(builder, justBool);
+ if (maybeBool !== null)
+ ScalarStuff.addMaybeBool(builder, maybeBool);
+ ScalarStuff.addDefaultBool(builder, defaultBool);
+ ScalarStuff.addJustEnum(builder, justEnum);
+ if (maybeEnum !== null)
+ ScalarStuff.addMaybeEnum(builder, maybeEnum);
+ ScalarStuff.addDefaultEnum(builder, defaultEnum);
+ return ScalarStuff.endScalarStuff(builder);
+ }
+}
diff --git a/tests/optional_scalars/scalar-stuff.ts b/tests/optional_scalars/scalar-stuff.ts
new file mode 100644
index 0000000..38d7ccc
--- /dev/null
+++ b/tests/optional_scalars/scalar-stuff.ts
@@ -0,0 +1,423 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+import * as flatbuffers from 'flatbuffers';
+
+import { OptionalByte } from '../optional_scalars/optional-byte';
+
+
+export class ScalarStuff {
+ bb: flatbuffers.ByteBuffer|null = null;
+ bb_pos = 0;
+__init(i:number, bb:flatbuffers.ByteBuffer):ScalarStuff {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+}
+
+static getRootAsScalarStuff(bb:flatbuffers.ByteBuffer, obj?:ScalarStuff):ScalarStuff {
+ return (obj || new ScalarStuff()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+}
+
+static getSizePrefixedRootAsScalarStuff(bb:flatbuffers.ByteBuffer, obj?:ScalarStuff):ScalarStuff {
+ bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new ScalarStuff()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+}
+
+static bufferHasIdentifier(bb:flatbuffers.ByteBuffer):boolean {
+ return bb.__has_identifier('NULL');
+}
+
+justI8():number {
+ const offset = this.bb!.__offset(this.bb_pos, 4);
+ return offset ? this.bb!.readInt8(this.bb_pos + offset) : 0;
+}
+
+maybeI8():number|null {
+ const offset = this.bb!.__offset(this.bb_pos, 6);
+ return offset ? this.bb!.readInt8(this.bb_pos + offset) : null;
+}
+
+defaultI8():number {
+ const offset = this.bb!.__offset(this.bb_pos, 8);
+ return offset ? this.bb!.readInt8(this.bb_pos + offset) : 42;
+}
+
+justU8():number {
+ const offset = this.bb!.__offset(this.bb_pos, 10);
+ return offset ? this.bb!.readUint8(this.bb_pos + offset) : 0;
+}
+
+maybeU8():number|null {
+ const offset = this.bb!.__offset(this.bb_pos, 12);
+ return offset ? this.bb!.readUint8(this.bb_pos + offset) : null;
+}
+
+defaultU8():number {
+ const offset = this.bb!.__offset(this.bb_pos, 14);
+ return offset ? this.bb!.readUint8(this.bb_pos + offset) : 42;
+}
+
+justI16():number {
+ const offset = this.bb!.__offset(this.bb_pos, 16);
+ return offset ? this.bb!.readInt16(this.bb_pos + offset) : 0;
+}
+
+maybeI16():number|null {
+ const offset = this.bb!.__offset(this.bb_pos, 18);
+ return offset ? this.bb!.readInt16(this.bb_pos + offset) : null;
+}
+
+defaultI16():number {
+ const offset = this.bb!.__offset(this.bb_pos, 20);
+ return offset ? this.bb!.readInt16(this.bb_pos + offset) : 42;
+}
+
+justU16():number {
+ const offset = this.bb!.__offset(this.bb_pos, 22);
+ return offset ? this.bb!.readUint16(this.bb_pos + offset) : 0;
+}
+
+maybeU16():number|null {
+ const offset = this.bb!.__offset(this.bb_pos, 24);
+ return offset ? this.bb!.readUint16(this.bb_pos + offset) : null;
+}
+
+defaultU16():number {
+ const offset = this.bb!.__offset(this.bb_pos, 26);
+ return offset ? this.bb!.readUint16(this.bb_pos + offset) : 42;
+}
+
+justI32():number {
+ const offset = this.bb!.__offset(this.bb_pos, 28);
+ return offset ? this.bb!.readInt32(this.bb_pos + offset) : 0;
+}
+
+maybeI32():number|null {
+ const offset = this.bb!.__offset(this.bb_pos, 30);
+ return offset ? this.bb!.readInt32(this.bb_pos + offset) : null;
+}
+
+defaultI32():number {
+ const offset = this.bb!.__offset(this.bb_pos, 32);
+ return offset ? this.bb!.readInt32(this.bb_pos + offset) : 42;
+}
+
+justU32():number {
+ const offset = this.bb!.__offset(this.bb_pos, 34);
+ return offset ? this.bb!.readUint32(this.bb_pos + offset) : 0;
+}
+
+maybeU32():number|null {
+ const offset = this.bb!.__offset(this.bb_pos, 36);
+ return offset ? this.bb!.readUint32(this.bb_pos + offset) : null;
+}
+
+defaultU32():number {
+ const offset = this.bb!.__offset(this.bb_pos, 38);
+ return offset ? this.bb!.readUint32(this.bb_pos + offset) : 42;
+}
+
+justI64():bigint {
+ const offset = this.bb!.__offset(this.bb_pos, 40);
+ return offset ? this.bb!.readInt64(this.bb_pos + offset) : BigInt('0');
+}
+
+maybeI64():bigint|null {
+ const offset = this.bb!.__offset(this.bb_pos, 42);
+ return offset ? this.bb!.readInt64(this.bb_pos + offset) : null;
+}
+
+defaultI64():bigint {
+ const offset = this.bb!.__offset(this.bb_pos, 44);
+ return offset ? this.bb!.readInt64(this.bb_pos + offset) : BigInt('42');
+}
+
+justU64():bigint {
+ const offset = this.bb!.__offset(this.bb_pos, 46);
+ return offset ? this.bb!.readUint64(this.bb_pos + offset) : BigInt('0');
+}
+
+maybeU64():bigint|null {
+ const offset = this.bb!.__offset(this.bb_pos, 48);
+ return offset ? this.bb!.readUint64(this.bb_pos + offset) : null;
+}
+
+defaultU64():bigint {
+ const offset = this.bb!.__offset(this.bb_pos, 50);
+ return offset ? this.bb!.readUint64(this.bb_pos + offset) : BigInt('42');
+}
+
+justF32():number {
+ const offset = this.bb!.__offset(this.bb_pos, 52);
+ return offset ? this.bb!.readFloat32(this.bb_pos + offset) : 0.0;
+}
+
+maybeF32():number|null {
+ const offset = this.bb!.__offset(this.bb_pos, 54);
+ return offset ? this.bb!.readFloat32(this.bb_pos + offset) : null;
+}
+
+defaultF32():number {
+ const offset = this.bb!.__offset(this.bb_pos, 56);
+ return offset ? this.bb!.readFloat32(this.bb_pos + offset) : 42.0;
+}
+
+justF64():number {
+ const offset = this.bb!.__offset(this.bb_pos, 58);
+ return offset ? this.bb!.readFloat64(this.bb_pos + offset) : 0.0;
+}
+
+maybeF64():number|null {
+ const offset = this.bb!.__offset(this.bb_pos, 60);
+ return offset ? this.bb!.readFloat64(this.bb_pos + offset) : null;
+}
+
+defaultF64():number {
+ const offset = this.bb!.__offset(this.bb_pos, 62);
+ return offset ? this.bb!.readFloat64(this.bb_pos + offset) : 42.0;
+}
+
+justBool():boolean {
+ const offset = this.bb!.__offset(this.bb_pos, 64);
+ return offset ? !!this.bb!.readInt8(this.bb_pos + offset) : false;
+}
+
+maybeBool():boolean|null {
+ const offset = this.bb!.__offset(this.bb_pos, 66);
+ return offset ? !!this.bb!.readInt8(this.bb_pos + offset) : null;
+}
+
+defaultBool():boolean {
+ const offset = this.bb!.__offset(this.bb_pos, 68);
+ return offset ? !!this.bb!.readInt8(this.bb_pos + offset) : true;
+}
+
+justEnum():OptionalByte {
+ const offset = this.bb!.__offset(this.bb_pos, 70);
+ return offset ? this.bb!.readInt8(this.bb_pos + offset) : OptionalByte.None;
+}
+
+maybeEnum():OptionalByte|null {
+ const offset = this.bb!.__offset(this.bb_pos, 72);
+ return offset ? this.bb!.readInt8(this.bb_pos + offset) : null;
+}
+
+defaultEnum():OptionalByte {
+ const offset = this.bb!.__offset(this.bb_pos, 74);
+ return offset ? this.bb!.readInt8(this.bb_pos + offset) : OptionalByte.One;
+}
+
+static startScalarStuff(builder:flatbuffers.Builder) {
+ builder.startObject(36);
+}
+
+static addJustI8(builder:flatbuffers.Builder, justI8:number) {
+ builder.addFieldInt8(0, justI8, 0);
+}
+
+static addMaybeI8(builder:flatbuffers.Builder, maybeI8:number) {
+ builder.addFieldInt8(1, maybeI8, 0);
+}
+
+static addDefaultI8(builder:flatbuffers.Builder, defaultI8:number) {
+ builder.addFieldInt8(2, defaultI8, 42);
+}
+
+static addJustU8(builder:flatbuffers.Builder, justU8:number) {
+ builder.addFieldInt8(3, justU8, 0);
+}
+
+static addMaybeU8(builder:flatbuffers.Builder, maybeU8:number) {
+ builder.addFieldInt8(4, maybeU8, 0);
+}
+
+static addDefaultU8(builder:flatbuffers.Builder, defaultU8:number) {
+ builder.addFieldInt8(5, defaultU8, 42);
+}
+
+static addJustI16(builder:flatbuffers.Builder, justI16:number) {
+ builder.addFieldInt16(6, justI16, 0);
+}
+
+static addMaybeI16(builder:flatbuffers.Builder, maybeI16:number) {
+ builder.addFieldInt16(7, maybeI16, 0);
+}
+
+static addDefaultI16(builder:flatbuffers.Builder, defaultI16:number) {
+ builder.addFieldInt16(8, defaultI16, 42);
+}
+
+static addJustU16(builder:flatbuffers.Builder, justU16:number) {
+ builder.addFieldInt16(9, justU16, 0);
+}
+
+static addMaybeU16(builder:flatbuffers.Builder, maybeU16:number) {
+ builder.addFieldInt16(10, maybeU16, 0);
+}
+
+static addDefaultU16(builder:flatbuffers.Builder, defaultU16:number) {
+ builder.addFieldInt16(11, defaultU16, 42);
+}
+
+static addJustI32(builder:flatbuffers.Builder, justI32:number) {
+ builder.addFieldInt32(12, justI32, 0);
+}
+
+static addMaybeI32(builder:flatbuffers.Builder, maybeI32:number) {
+ builder.addFieldInt32(13, maybeI32, 0);
+}
+
+static addDefaultI32(builder:flatbuffers.Builder, defaultI32:number) {
+ builder.addFieldInt32(14, defaultI32, 42);
+}
+
+static addJustU32(builder:flatbuffers.Builder, justU32:number) {
+ builder.addFieldInt32(15, justU32, 0);
+}
+
+static addMaybeU32(builder:flatbuffers.Builder, maybeU32:number) {
+ builder.addFieldInt32(16, maybeU32, 0);
+}
+
+static addDefaultU32(builder:flatbuffers.Builder, defaultU32:number) {
+ builder.addFieldInt32(17, defaultU32, 42);
+}
+
+static addJustI64(builder:flatbuffers.Builder, justI64:bigint) {
+ builder.addFieldInt64(18, justI64, BigInt('0'));
+}
+
+static addMaybeI64(builder:flatbuffers.Builder, maybeI64:bigint) {
+ builder.addFieldInt64(19, maybeI64, BigInt(0));
+}
+
+static addDefaultI64(builder:flatbuffers.Builder, defaultI64:bigint) {
+ builder.addFieldInt64(20, defaultI64, BigInt('42'));
+}
+
+static addJustU64(builder:flatbuffers.Builder, justU64:bigint) {
+ builder.addFieldInt64(21, justU64, BigInt('0'));
+}
+
+static addMaybeU64(builder:flatbuffers.Builder, maybeU64:bigint) {
+ builder.addFieldInt64(22, maybeU64, BigInt(0));
+}
+
+static addDefaultU64(builder:flatbuffers.Builder, defaultU64:bigint) {
+ builder.addFieldInt64(23, defaultU64, BigInt('42'));
+}
+
+static addJustF32(builder:flatbuffers.Builder, justF32:number) {
+ builder.addFieldFloat32(24, justF32, 0.0);
+}
+
+static addMaybeF32(builder:flatbuffers.Builder, maybeF32:number) {
+ builder.addFieldFloat32(25, maybeF32, 0);
+}
+
+static addDefaultF32(builder:flatbuffers.Builder, defaultF32:number) {
+ builder.addFieldFloat32(26, defaultF32, 42.0);
+}
+
+static addJustF64(builder:flatbuffers.Builder, justF64:number) {
+ builder.addFieldFloat64(27, justF64, 0.0);
+}
+
+static addMaybeF64(builder:flatbuffers.Builder, maybeF64:number) {
+ builder.addFieldFloat64(28, maybeF64, 0);
+}
+
+static addDefaultF64(builder:flatbuffers.Builder, defaultF64:number) {
+ builder.addFieldFloat64(29, defaultF64, 42.0);
+}
+
+static addJustBool(builder:flatbuffers.Builder, justBool:boolean) {
+ builder.addFieldInt8(30, +justBool, +false);
+}
+
+static addMaybeBool(builder:flatbuffers.Builder, maybeBool:boolean) {
+ builder.addFieldInt8(31, +maybeBool, 0);
+}
+
+static addDefaultBool(builder:flatbuffers.Builder, defaultBool:boolean) {
+ builder.addFieldInt8(32, +defaultBool, +true);
+}
+
+static addJustEnum(builder:flatbuffers.Builder, justEnum:OptionalByte) {
+ builder.addFieldInt8(33, justEnum, OptionalByte.None);
+}
+
+static addMaybeEnum(builder:flatbuffers.Builder, maybeEnum:OptionalByte) {
+ builder.addFieldInt8(34, maybeEnum, 0);
+}
+
+static addDefaultEnum(builder:flatbuffers.Builder, defaultEnum:OptionalByte) {
+ builder.addFieldInt8(35, defaultEnum, OptionalByte.One);
+}
+
+static endScalarStuff(builder:flatbuffers.Builder):flatbuffers.Offset {
+ const offset = builder.endObject();
+ return offset;
+}
+
+static finishScalarStuffBuffer(builder:flatbuffers.Builder, offset:flatbuffers.Offset) {
+ builder.finish(offset, 'NULL');
+}
+
+static finishSizePrefixedScalarStuffBuffer(builder:flatbuffers.Builder, offset:flatbuffers.Offset) {
+ builder.finish(offset, 'NULL', true);
+}
+
+static createScalarStuff(builder:flatbuffers.Builder, justI8:number, maybeI8:number|null, defaultI8:number, justU8:number, maybeU8:number|null, defaultU8:number, justI16:number, maybeI16:number|null, defaultI16:number, justU16:number, maybeU16:number|null, defaultU16:number, justI32:number, maybeI32:number|null, defaultI32:number, justU32:number, maybeU32:number|null, defaultU32:number, justI64:bigint, maybeI64:bigint|null, defaultI64:bigint, justU64:bigint, maybeU64:bigint|null, defaultU64:bigint, justF32:number, maybeF32:number|null, defaultF32:number, justF64:number, maybeF64:number|null, defaultF64:number, justBool:boolean, maybeBool:boolean|null, defaultBool:boolean, justEnum:OptionalByte, maybeEnum:OptionalByte|null, defaultEnum:OptionalByte):flatbuffers.Offset {
+ ScalarStuff.startScalarStuff(builder);
+ ScalarStuff.addJustI8(builder, justI8);
+ if (maybeI8 !== null)
+ ScalarStuff.addMaybeI8(builder, maybeI8);
+ ScalarStuff.addDefaultI8(builder, defaultI8);
+ ScalarStuff.addJustU8(builder, justU8);
+ if (maybeU8 !== null)
+ ScalarStuff.addMaybeU8(builder, maybeU8);
+ ScalarStuff.addDefaultU8(builder, defaultU8);
+ ScalarStuff.addJustI16(builder, justI16);
+ if (maybeI16 !== null)
+ ScalarStuff.addMaybeI16(builder, maybeI16);
+ ScalarStuff.addDefaultI16(builder, defaultI16);
+ ScalarStuff.addJustU16(builder, justU16);
+ if (maybeU16 !== null)
+ ScalarStuff.addMaybeU16(builder, maybeU16);
+ ScalarStuff.addDefaultU16(builder, defaultU16);
+ ScalarStuff.addJustI32(builder, justI32);
+ if (maybeI32 !== null)
+ ScalarStuff.addMaybeI32(builder, maybeI32);
+ ScalarStuff.addDefaultI32(builder, defaultI32);
+ ScalarStuff.addJustU32(builder, justU32);
+ if (maybeU32 !== null)
+ ScalarStuff.addMaybeU32(builder, maybeU32);
+ ScalarStuff.addDefaultU32(builder, defaultU32);
+ ScalarStuff.addJustI64(builder, justI64);
+ if (maybeI64 !== null)
+ ScalarStuff.addMaybeI64(builder, maybeI64);
+ ScalarStuff.addDefaultI64(builder, defaultI64);
+ ScalarStuff.addJustU64(builder, justU64);
+ if (maybeU64 !== null)
+ ScalarStuff.addMaybeU64(builder, maybeU64);
+ ScalarStuff.addDefaultU64(builder, defaultU64);
+ ScalarStuff.addJustF32(builder, justF32);
+ if (maybeF32 !== null)
+ ScalarStuff.addMaybeF32(builder, maybeF32);
+ ScalarStuff.addDefaultF32(builder, defaultF32);
+ ScalarStuff.addJustF64(builder, justF64);
+ if (maybeF64 !== null)
+ ScalarStuff.addMaybeF64(builder, maybeF64);
+ ScalarStuff.addDefaultF64(builder, defaultF64);
+ ScalarStuff.addJustBool(builder, justBool);
+ if (maybeBool !== null)
+ ScalarStuff.addMaybeBool(builder, maybeBool);
+ ScalarStuff.addDefaultBool(builder, defaultBool);
+ ScalarStuff.addJustEnum(builder, justEnum);
+ if (maybeEnum !== null)
+ ScalarStuff.addMaybeEnum(builder, maybeEnum);
+ ScalarStuff.addDefaultEnum(builder, defaultEnum);
+ return ScalarStuff.endScalarStuff(builder);
+}
+}
diff --git a/tests/optional_scalars_generated.h b/tests/optional_scalars_generated.h
index e7c7fc1..c295eba 100644
--- a/tests/optional_scalars_generated.h
+++ b/tests/optional_scalars_generated.h
@@ -17,7 +17,7 @@
inline const flatbuffers::TypeTable *ScalarStuffTypeTable();
-enum OptionalByte {
+enum OptionalByte : int8_t {
OptionalByte_None = 0,
OptionalByte_One = 1,
OptionalByte_Two = 2,
@@ -52,127 +52,44 @@
struct ScalarStuffT : public flatbuffers::NativeTable {
typedef ScalarStuff TableType;
- int8_t just_i8;
- flatbuffers::Optional<int8_t> maybe_i8;
- int8_t default_i8;
- uint8_t just_u8;
- flatbuffers::Optional<uint8_t> maybe_u8;
- uint8_t default_u8;
- int16_t just_i16;
- flatbuffers::Optional<int16_t> maybe_i16;
- int16_t default_i16;
- uint16_t just_u16;
- flatbuffers::Optional<uint16_t> maybe_u16;
- uint16_t default_u16;
- int32_t just_i32;
- flatbuffers::Optional<int32_t> maybe_i32;
- int32_t default_i32;
- uint32_t just_u32;
- flatbuffers::Optional<uint32_t> maybe_u32;
- uint32_t default_u32;
- int64_t just_i64;
- flatbuffers::Optional<int64_t> maybe_i64;
- int64_t default_i64;
- uint64_t just_u64;
- flatbuffers::Optional<uint64_t> maybe_u64;
- uint64_t default_u64;
- float just_f32;
- flatbuffers::Optional<float> maybe_f32;
- float default_f32;
- double just_f64;
- flatbuffers::Optional<double> maybe_f64;
- double default_f64;
- bool just_bool;
- flatbuffers::Optional<bool> maybe_bool;
- bool default_bool;
- optional_scalars::OptionalByte just_enum;
- flatbuffers::Optional<optional_scalars::OptionalByte> maybe_enum;
- optional_scalars::OptionalByte default_enum;
- ScalarStuffT()
- : just_i8(0),
- maybe_i8(flatbuffers::nullopt),
- default_i8(42),
- just_u8(0),
- maybe_u8(flatbuffers::nullopt),
- default_u8(42),
- just_i16(0),
- maybe_i16(flatbuffers::nullopt),
- default_i16(42),
- just_u16(0),
- maybe_u16(flatbuffers::nullopt),
- default_u16(42),
- just_i32(0),
- maybe_i32(flatbuffers::nullopt),
- default_i32(42),
- just_u32(0),
- maybe_u32(flatbuffers::nullopt),
- default_u32(42),
- just_i64(0),
- maybe_i64(flatbuffers::nullopt),
- default_i64(42LL),
- just_u64(0),
- maybe_u64(flatbuffers::nullopt),
- default_u64(42ULL),
- just_f32(0.0f),
- maybe_f32(flatbuffers::nullopt),
- default_f32(42.0f),
- just_f64(0.0),
- maybe_f64(flatbuffers::nullopt),
- default_f64(42.0),
- just_bool(false),
- maybe_bool(flatbuffers::nullopt),
- default_bool(true),
- just_enum(optional_scalars::OptionalByte_None),
- maybe_enum(flatbuffers::nullopt),
- default_enum(optional_scalars::OptionalByte_One) {
- }
+ int8_t just_i8 = 0;
+ flatbuffers::Optional<int8_t> maybe_i8 = flatbuffers::nullopt;
+ int8_t default_i8 = 42;
+ uint8_t just_u8 = 0;
+ flatbuffers::Optional<uint8_t> maybe_u8 = flatbuffers::nullopt;
+ uint8_t default_u8 = 42;
+ int16_t just_i16 = 0;
+ flatbuffers::Optional<int16_t> maybe_i16 = flatbuffers::nullopt;
+ int16_t default_i16 = 42;
+ uint16_t just_u16 = 0;
+ flatbuffers::Optional<uint16_t> maybe_u16 = flatbuffers::nullopt;
+ uint16_t default_u16 = 42;
+ int32_t just_i32 = 0;
+ flatbuffers::Optional<int32_t> maybe_i32 = flatbuffers::nullopt;
+ int32_t default_i32 = 42;
+ uint32_t just_u32 = 0;
+ flatbuffers::Optional<uint32_t> maybe_u32 = flatbuffers::nullopt;
+ uint32_t default_u32 = 42;
+ int64_t just_i64 = 0;
+ flatbuffers::Optional<int64_t> maybe_i64 = flatbuffers::nullopt;
+ int64_t default_i64 = 42LL;
+ uint64_t just_u64 = 0;
+ flatbuffers::Optional<uint64_t> maybe_u64 = flatbuffers::nullopt;
+ uint64_t default_u64 = 42ULL;
+ float just_f32 = 0.0f;
+ flatbuffers::Optional<float> maybe_f32 = flatbuffers::nullopt;
+ float default_f32 = 42.0f;
+ double just_f64 = 0.0;
+ flatbuffers::Optional<double> maybe_f64 = flatbuffers::nullopt;
+ double default_f64 = 42.0;
+ bool just_bool = false;
+ flatbuffers::Optional<bool> maybe_bool = flatbuffers::nullopt;
+ bool default_bool = true;
+ optional_scalars::OptionalByte just_enum = optional_scalars::OptionalByte_None;
+ flatbuffers::Optional<optional_scalars::OptionalByte> maybe_enum = flatbuffers::nullopt;
+ optional_scalars::OptionalByte default_enum = optional_scalars::OptionalByte_One;
};
-inline bool operator==(const ScalarStuffT &lhs, const ScalarStuffT &rhs) {
- return
- (lhs.just_i8 == rhs.just_i8) &&
- (lhs.maybe_i8 == rhs.maybe_i8) &&
- (lhs.default_i8 == rhs.default_i8) &&
- (lhs.just_u8 == rhs.just_u8) &&
- (lhs.maybe_u8 == rhs.maybe_u8) &&
- (lhs.default_u8 == rhs.default_u8) &&
- (lhs.just_i16 == rhs.just_i16) &&
- (lhs.maybe_i16 == rhs.maybe_i16) &&
- (lhs.default_i16 == rhs.default_i16) &&
- (lhs.just_u16 == rhs.just_u16) &&
- (lhs.maybe_u16 == rhs.maybe_u16) &&
- (lhs.default_u16 == rhs.default_u16) &&
- (lhs.just_i32 == rhs.just_i32) &&
- (lhs.maybe_i32 == rhs.maybe_i32) &&
- (lhs.default_i32 == rhs.default_i32) &&
- (lhs.just_u32 == rhs.just_u32) &&
- (lhs.maybe_u32 == rhs.maybe_u32) &&
- (lhs.default_u32 == rhs.default_u32) &&
- (lhs.just_i64 == rhs.just_i64) &&
- (lhs.maybe_i64 == rhs.maybe_i64) &&
- (lhs.default_i64 == rhs.default_i64) &&
- (lhs.just_u64 == rhs.just_u64) &&
- (lhs.maybe_u64 == rhs.maybe_u64) &&
- (lhs.default_u64 == rhs.default_u64) &&
- (lhs.just_f32 == rhs.just_f32) &&
- (lhs.maybe_f32 == rhs.maybe_f32) &&
- (lhs.default_f32 == rhs.default_f32) &&
- (lhs.just_f64 == rhs.just_f64) &&
- (lhs.maybe_f64 == rhs.maybe_f64) &&
- (lhs.default_f64 == rhs.default_f64) &&
- (lhs.just_bool == rhs.just_bool) &&
- (lhs.maybe_bool == rhs.maybe_bool) &&
- (lhs.default_bool == rhs.default_bool) &&
- (lhs.just_enum == rhs.just_enum) &&
- (lhs.maybe_enum == rhs.maybe_enum) &&
- (lhs.default_enum == rhs.default_enum);
-}
-
-inline bool operator!=(const ScalarStuffT &lhs, const ScalarStuffT &rhs) {
- return !(lhs == rhs);
-}
-
-
struct ScalarStuff FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
typedef ScalarStuffT NativeTableType;
typedef ScalarStuffBuilder Builder;
@@ -220,7 +137,7 @@
int8_t just_i8() const {
return GetField<int8_t>(VT_JUST_I8, 0);
}
- bool mutate_just_i8(int8_t _just_i8) {
+ bool mutate_just_i8(int8_t _just_i8 = 0) {
return SetField<int8_t>(VT_JUST_I8, _just_i8, 0);
}
flatbuffers::Optional<int8_t> maybe_i8() const {
@@ -232,13 +149,13 @@
int8_t default_i8() const {
return GetField<int8_t>(VT_DEFAULT_I8, 42);
}
- bool mutate_default_i8(int8_t _default_i8) {
+ bool mutate_default_i8(int8_t _default_i8 = 42) {
return SetField<int8_t>(VT_DEFAULT_I8, _default_i8, 42);
}
uint8_t just_u8() const {
return GetField<uint8_t>(VT_JUST_U8, 0);
}
- bool mutate_just_u8(uint8_t _just_u8) {
+ bool mutate_just_u8(uint8_t _just_u8 = 0) {
return SetField<uint8_t>(VT_JUST_U8, _just_u8, 0);
}
flatbuffers::Optional<uint8_t> maybe_u8() const {
@@ -250,13 +167,13 @@
uint8_t default_u8() const {
return GetField<uint8_t>(VT_DEFAULT_U8, 42);
}
- bool mutate_default_u8(uint8_t _default_u8) {
+ bool mutate_default_u8(uint8_t _default_u8 = 42) {
return SetField<uint8_t>(VT_DEFAULT_U8, _default_u8, 42);
}
int16_t just_i16() const {
return GetField<int16_t>(VT_JUST_I16, 0);
}
- bool mutate_just_i16(int16_t _just_i16) {
+ bool mutate_just_i16(int16_t _just_i16 = 0) {
return SetField<int16_t>(VT_JUST_I16, _just_i16, 0);
}
flatbuffers::Optional<int16_t> maybe_i16() const {
@@ -268,13 +185,13 @@
int16_t default_i16() const {
return GetField<int16_t>(VT_DEFAULT_I16, 42);
}
- bool mutate_default_i16(int16_t _default_i16) {
+ bool mutate_default_i16(int16_t _default_i16 = 42) {
return SetField<int16_t>(VT_DEFAULT_I16, _default_i16, 42);
}
uint16_t just_u16() const {
return GetField<uint16_t>(VT_JUST_U16, 0);
}
- bool mutate_just_u16(uint16_t _just_u16) {
+ bool mutate_just_u16(uint16_t _just_u16 = 0) {
return SetField<uint16_t>(VT_JUST_U16, _just_u16, 0);
}
flatbuffers::Optional<uint16_t> maybe_u16() const {
@@ -286,13 +203,13 @@
uint16_t default_u16() const {
return GetField<uint16_t>(VT_DEFAULT_U16, 42);
}
- bool mutate_default_u16(uint16_t _default_u16) {
+ bool mutate_default_u16(uint16_t _default_u16 = 42) {
return SetField<uint16_t>(VT_DEFAULT_U16, _default_u16, 42);
}
int32_t just_i32() const {
return GetField<int32_t>(VT_JUST_I32, 0);
}
- bool mutate_just_i32(int32_t _just_i32) {
+ bool mutate_just_i32(int32_t _just_i32 = 0) {
return SetField<int32_t>(VT_JUST_I32, _just_i32, 0);
}
flatbuffers::Optional<int32_t> maybe_i32() const {
@@ -304,13 +221,13 @@
int32_t default_i32() const {
return GetField<int32_t>(VT_DEFAULT_I32, 42);
}
- bool mutate_default_i32(int32_t _default_i32) {
+ bool mutate_default_i32(int32_t _default_i32 = 42) {
return SetField<int32_t>(VT_DEFAULT_I32, _default_i32, 42);
}
uint32_t just_u32() const {
return GetField<uint32_t>(VT_JUST_U32, 0);
}
- bool mutate_just_u32(uint32_t _just_u32) {
+ bool mutate_just_u32(uint32_t _just_u32 = 0) {
return SetField<uint32_t>(VT_JUST_U32, _just_u32, 0);
}
flatbuffers::Optional<uint32_t> maybe_u32() const {
@@ -322,13 +239,13 @@
uint32_t default_u32() const {
return GetField<uint32_t>(VT_DEFAULT_U32, 42);
}
- bool mutate_default_u32(uint32_t _default_u32) {
+ bool mutate_default_u32(uint32_t _default_u32 = 42) {
return SetField<uint32_t>(VT_DEFAULT_U32, _default_u32, 42);
}
int64_t just_i64() const {
return GetField<int64_t>(VT_JUST_I64, 0);
}
- bool mutate_just_i64(int64_t _just_i64) {
+ bool mutate_just_i64(int64_t _just_i64 = 0) {
return SetField<int64_t>(VT_JUST_I64, _just_i64, 0);
}
flatbuffers::Optional<int64_t> maybe_i64() const {
@@ -340,13 +257,13 @@
int64_t default_i64() const {
return GetField<int64_t>(VT_DEFAULT_I64, 42LL);
}
- bool mutate_default_i64(int64_t _default_i64) {
+ bool mutate_default_i64(int64_t _default_i64 = 42LL) {
return SetField<int64_t>(VT_DEFAULT_I64, _default_i64, 42LL);
}
uint64_t just_u64() const {
return GetField<uint64_t>(VT_JUST_U64, 0);
}
- bool mutate_just_u64(uint64_t _just_u64) {
+ bool mutate_just_u64(uint64_t _just_u64 = 0) {
return SetField<uint64_t>(VT_JUST_U64, _just_u64, 0);
}
flatbuffers::Optional<uint64_t> maybe_u64() const {
@@ -358,13 +275,13 @@
uint64_t default_u64() const {
return GetField<uint64_t>(VT_DEFAULT_U64, 42ULL);
}
- bool mutate_default_u64(uint64_t _default_u64) {
+ bool mutate_default_u64(uint64_t _default_u64 = 42ULL) {
return SetField<uint64_t>(VT_DEFAULT_U64, _default_u64, 42ULL);
}
float just_f32() const {
return GetField<float>(VT_JUST_F32, 0.0f);
}
- bool mutate_just_f32(float _just_f32) {
+ bool mutate_just_f32(float _just_f32 = 0.0f) {
return SetField<float>(VT_JUST_F32, _just_f32, 0.0f);
}
flatbuffers::Optional<float> maybe_f32() const {
@@ -376,13 +293,13 @@
float default_f32() const {
return GetField<float>(VT_DEFAULT_F32, 42.0f);
}
- bool mutate_default_f32(float _default_f32) {
+ bool mutate_default_f32(float _default_f32 = 42.0f) {
return SetField<float>(VT_DEFAULT_F32, _default_f32, 42.0f);
}
double just_f64() const {
return GetField<double>(VT_JUST_F64, 0.0);
}
- bool mutate_just_f64(double _just_f64) {
+ bool mutate_just_f64(double _just_f64 = 0.0) {
return SetField<double>(VT_JUST_F64, _just_f64, 0.0);
}
flatbuffers::Optional<double> maybe_f64() const {
@@ -394,13 +311,13 @@
double default_f64() const {
return GetField<double>(VT_DEFAULT_F64, 42.0);
}
- bool mutate_default_f64(double _default_f64) {
+ bool mutate_default_f64(double _default_f64 = 42.0) {
return SetField<double>(VT_DEFAULT_F64, _default_f64, 42.0);
}
bool just_bool() const {
return GetField<uint8_t>(VT_JUST_BOOL, 0) != 0;
}
- bool mutate_just_bool(bool _just_bool) {
+ bool mutate_just_bool(bool _just_bool = 0) {
return SetField<uint8_t>(VT_JUST_BOOL, static_cast<uint8_t>(_just_bool), 0);
}
flatbuffers::Optional<bool> maybe_bool() const {
@@ -412,13 +329,13 @@
bool default_bool() const {
return GetField<uint8_t>(VT_DEFAULT_BOOL, 1) != 0;
}
- bool mutate_default_bool(bool _default_bool) {
+ bool mutate_default_bool(bool _default_bool = 1) {
return SetField<uint8_t>(VT_DEFAULT_BOOL, static_cast<uint8_t>(_default_bool), 1);
}
optional_scalars::OptionalByte just_enum() const {
return static_cast<optional_scalars::OptionalByte>(GetField<int8_t>(VT_JUST_ENUM, 0));
}
- bool mutate_just_enum(optional_scalars::OptionalByte _just_enum) {
+ bool mutate_just_enum(optional_scalars::OptionalByte _just_enum = static_cast<optional_scalars::OptionalByte>(0)) {
return SetField<int8_t>(VT_JUST_ENUM, static_cast<int8_t>(_just_enum), 0);
}
flatbuffers::Optional<optional_scalars::OptionalByte> maybe_enum() const {
@@ -430,47 +347,47 @@
optional_scalars::OptionalByte default_enum() const {
return static_cast<optional_scalars::OptionalByte>(GetField<int8_t>(VT_DEFAULT_ENUM, 1));
}
- bool mutate_default_enum(optional_scalars::OptionalByte _default_enum) {
+ bool mutate_default_enum(optional_scalars::OptionalByte _default_enum = static_cast<optional_scalars::OptionalByte>(1)) {
return SetField<int8_t>(VT_DEFAULT_ENUM, static_cast<int8_t>(_default_enum), 1);
}
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
- VerifyField<int8_t>(verifier, VT_JUST_I8) &&
- VerifyField<int8_t>(verifier, VT_MAYBE_I8) &&
- VerifyField<int8_t>(verifier, VT_DEFAULT_I8) &&
- VerifyField<uint8_t>(verifier, VT_JUST_U8) &&
- VerifyField<uint8_t>(verifier, VT_MAYBE_U8) &&
- VerifyField<uint8_t>(verifier, VT_DEFAULT_U8) &&
- VerifyField<int16_t>(verifier, VT_JUST_I16) &&
- VerifyField<int16_t>(verifier, VT_MAYBE_I16) &&
- VerifyField<int16_t>(verifier, VT_DEFAULT_I16) &&
- VerifyField<uint16_t>(verifier, VT_JUST_U16) &&
- VerifyField<uint16_t>(verifier, VT_MAYBE_U16) &&
- VerifyField<uint16_t>(verifier, VT_DEFAULT_U16) &&
- VerifyField<int32_t>(verifier, VT_JUST_I32) &&
- VerifyField<int32_t>(verifier, VT_MAYBE_I32) &&
- VerifyField<int32_t>(verifier, VT_DEFAULT_I32) &&
- VerifyField<uint32_t>(verifier, VT_JUST_U32) &&
- VerifyField<uint32_t>(verifier, VT_MAYBE_U32) &&
- VerifyField<uint32_t>(verifier, VT_DEFAULT_U32) &&
- VerifyField<int64_t>(verifier, VT_JUST_I64) &&
- VerifyField<int64_t>(verifier, VT_MAYBE_I64) &&
- VerifyField<int64_t>(verifier, VT_DEFAULT_I64) &&
- VerifyField<uint64_t>(verifier, VT_JUST_U64) &&
- VerifyField<uint64_t>(verifier, VT_MAYBE_U64) &&
- VerifyField<uint64_t>(verifier, VT_DEFAULT_U64) &&
- VerifyField<float>(verifier, VT_JUST_F32) &&
- VerifyField<float>(verifier, VT_MAYBE_F32) &&
- VerifyField<float>(verifier, VT_DEFAULT_F32) &&
- VerifyField<double>(verifier, VT_JUST_F64) &&
- VerifyField<double>(verifier, VT_MAYBE_F64) &&
- VerifyField<double>(verifier, VT_DEFAULT_F64) &&
- VerifyField<uint8_t>(verifier, VT_JUST_BOOL) &&
- VerifyField<uint8_t>(verifier, VT_MAYBE_BOOL) &&
- VerifyField<uint8_t>(verifier, VT_DEFAULT_BOOL) &&
- VerifyField<int8_t>(verifier, VT_JUST_ENUM) &&
- VerifyField<int8_t>(verifier, VT_MAYBE_ENUM) &&
- VerifyField<int8_t>(verifier, VT_DEFAULT_ENUM) &&
+ VerifyField<int8_t>(verifier, VT_JUST_I8, 1) &&
+ VerifyField<int8_t>(verifier, VT_MAYBE_I8, 1) &&
+ VerifyField<int8_t>(verifier, VT_DEFAULT_I8, 1) &&
+ VerifyField<uint8_t>(verifier, VT_JUST_U8, 1) &&
+ VerifyField<uint8_t>(verifier, VT_MAYBE_U8, 1) &&
+ VerifyField<uint8_t>(verifier, VT_DEFAULT_U8, 1) &&
+ VerifyField<int16_t>(verifier, VT_JUST_I16, 2) &&
+ VerifyField<int16_t>(verifier, VT_MAYBE_I16, 2) &&
+ VerifyField<int16_t>(verifier, VT_DEFAULT_I16, 2) &&
+ VerifyField<uint16_t>(verifier, VT_JUST_U16, 2) &&
+ VerifyField<uint16_t>(verifier, VT_MAYBE_U16, 2) &&
+ VerifyField<uint16_t>(verifier, VT_DEFAULT_U16, 2) &&
+ VerifyField<int32_t>(verifier, VT_JUST_I32, 4) &&
+ VerifyField<int32_t>(verifier, VT_MAYBE_I32, 4) &&
+ VerifyField<int32_t>(verifier, VT_DEFAULT_I32, 4) &&
+ VerifyField<uint32_t>(verifier, VT_JUST_U32, 4) &&
+ VerifyField<uint32_t>(verifier, VT_MAYBE_U32, 4) &&
+ VerifyField<uint32_t>(verifier, VT_DEFAULT_U32, 4) &&
+ VerifyField<int64_t>(verifier, VT_JUST_I64, 8) &&
+ VerifyField<int64_t>(verifier, VT_MAYBE_I64, 8) &&
+ VerifyField<int64_t>(verifier, VT_DEFAULT_I64, 8) &&
+ VerifyField<uint64_t>(verifier, VT_JUST_U64, 8) &&
+ VerifyField<uint64_t>(verifier, VT_MAYBE_U64, 8) &&
+ VerifyField<uint64_t>(verifier, VT_DEFAULT_U64, 8) &&
+ VerifyField<float>(verifier, VT_JUST_F32, 4) &&
+ VerifyField<float>(verifier, VT_MAYBE_F32, 4) &&
+ VerifyField<float>(verifier, VT_DEFAULT_F32, 4) &&
+ VerifyField<double>(verifier, VT_JUST_F64, 8) &&
+ VerifyField<double>(verifier, VT_MAYBE_F64, 8) &&
+ VerifyField<double>(verifier, VT_DEFAULT_F64, 8) &&
+ VerifyField<uint8_t>(verifier, VT_JUST_BOOL, 1) &&
+ VerifyField<uint8_t>(verifier, VT_MAYBE_BOOL, 1) &&
+ VerifyField<uint8_t>(verifier, VT_DEFAULT_BOOL, 1) &&
+ VerifyField<int8_t>(verifier, VT_JUST_ENUM, 1) &&
+ VerifyField<int8_t>(verifier, VT_MAYBE_ENUM, 1) &&
+ VerifyField<int8_t>(verifier, VT_DEFAULT_ENUM, 1) &&
verifier.EndTable();
}
ScalarStuffT *UnPack(const flatbuffers::resolver_function_t *_resolver = nullptr) const;
@@ -681,8 +598,54 @@
flatbuffers::Offset<ScalarStuff> CreateScalarStuff(flatbuffers::FlatBufferBuilder &_fbb, const ScalarStuffT *_o, const flatbuffers::rehasher_function_t *_rehasher = nullptr);
+
+inline bool operator==(const ScalarStuffT &lhs, const ScalarStuffT &rhs) {
+ return
+ (lhs.just_i8 == rhs.just_i8) &&
+ (lhs.maybe_i8 == rhs.maybe_i8) &&
+ (lhs.default_i8 == rhs.default_i8) &&
+ (lhs.just_u8 == rhs.just_u8) &&
+ (lhs.maybe_u8 == rhs.maybe_u8) &&
+ (lhs.default_u8 == rhs.default_u8) &&
+ (lhs.just_i16 == rhs.just_i16) &&
+ (lhs.maybe_i16 == rhs.maybe_i16) &&
+ (lhs.default_i16 == rhs.default_i16) &&
+ (lhs.just_u16 == rhs.just_u16) &&
+ (lhs.maybe_u16 == rhs.maybe_u16) &&
+ (lhs.default_u16 == rhs.default_u16) &&
+ (lhs.just_i32 == rhs.just_i32) &&
+ (lhs.maybe_i32 == rhs.maybe_i32) &&
+ (lhs.default_i32 == rhs.default_i32) &&
+ (lhs.just_u32 == rhs.just_u32) &&
+ (lhs.maybe_u32 == rhs.maybe_u32) &&
+ (lhs.default_u32 == rhs.default_u32) &&
+ (lhs.just_i64 == rhs.just_i64) &&
+ (lhs.maybe_i64 == rhs.maybe_i64) &&
+ (lhs.default_i64 == rhs.default_i64) &&
+ (lhs.just_u64 == rhs.just_u64) &&
+ (lhs.maybe_u64 == rhs.maybe_u64) &&
+ (lhs.default_u64 == rhs.default_u64) &&
+ (lhs.just_f32 == rhs.just_f32) &&
+ (lhs.maybe_f32 == rhs.maybe_f32) &&
+ (lhs.default_f32 == rhs.default_f32) &&
+ (lhs.just_f64 == rhs.just_f64) &&
+ (lhs.maybe_f64 == rhs.maybe_f64) &&
+ (lhs.default_f64 == rhs.default_f64) &&
+ (lhs.just_bool == rhs.just_bool) &&
+ (lhs.maybe_bool == rhs.maybe_bool) &&
+ (lhs.default_bool == rhs.default_bool) &&
+ (lhs.just_enum == rhs.just_enum) &&
+ (lhs.maybe_enum == rhs.maybe_enum) &&
+ (lhs.default_enum == rhs.default_enum);
+}
+
+inline bool operator!=(const ScalarStuffT &lhs, const ScalarStuffT &rhs) {
+ return !(lhs == rhs);
+}
+
+
inline ScalarStuffT *ScalarStuff::UnPack(const flatbuffers::resolver_function_t *_resolver) const {
- flatbuffers::unique_ptr<optional_scalars::ScalarStuffT> _o = flatbuffers::unique_ptr<optional_scalars::ScalarStuffT>(new ScalarStuffT());
+ auto _o = std::unique_ptr<ScalarStuffT>(new ScalarStuffT());
UnPackTo(_o.get(), _resolver);
return _o.release();
}
@@ -930,6 +893,10 @@
return flatbuffers::GetMutableRoot<ScalarStuff>(buf);
}
+inline optional_scalars::ScalarStuff *GetMutableSizePrefixedScalarStuff(void *buf) {
+ return flatbuffers::GetMutableSizePrefixedRoot<optional_scalars::ScalarStuff>(buf);
+}
+
inline const char *ScalarStuffIdentifier() {
return "NULL";
}
@@ -939,6 +906,11 @@
buf, ScalarStuffIdentifier());
}
+inline bool SizePrefixedScalarStuffBufferHasIdentifier(const void *buf) {
+ return flatbuffers::BufferHasIdentifier(
+ buf, ScalarStuffIdentifier(), true);
+}
+
inline bool VerifyScalarStuffBuffer(
flatbuffers::Verifier &verifier) {
return verifier.VerifyBuffer<optional_scalars::ScalarStuff>(ScalarStuffIdentifier());
diff --git a/tests/optional_scalars_generated.js b/tests/optional_scalars_generated.js
deleted file mode 100644
index 60a25a0..0000000
--- a/tests/optional_scalars_generated.js
+++ /dev/null
@@ -1,782 +0,0 @@
-// automatically generated by the FlatBuffers compiler, do not modify
-
-/**
- * @const
- * @namespace
- */
-var optional_scalars = optional_scalars || {};
-
-/**
- * @enum {number}
- */
-optional_scalars.OptionalByte = {
- None: 0,
- One: 1,
- Two: 2
-};
-
-/**
- * @enum {string}
- */
-optional_scalars.OptionalByteName = {
- '0': 'None',
- '1': 'One',
- '2': 'Two'
-};
-
-/**
- * @constructor
- */
-optional_scalars.ScalarStuff = function() {
- /**
- * @type {flatbuffers.ByteBuffer}
- */
- this.bb = null;
-
- /**
- * @type {number}
- */
- this.bb_pos = 0;
-};
-
-/**
- * @param {number} i
- * @param {flatbuffers.ByteBuffer} bb
- * @returns {optional_scalars.ScalarStuff}
- */
-optional_scalars.ScalarStuff.prototype.__init = function(i, bb) {
- this.bb_pos = i;
- this.bb = bb;
- return this;
-};
-
-/**
- * @param {flatbuffers.ByteBuffer} bb
- * @param {optional_scalars.ScalarStuff=} obj
- * @returns {optional_scalars.ScalarStuff}
- */
-optional_scalars.ScalarStuff.getRootAsScalarStuff = function(bb, obj) {
- return (obj || new optional_scalars.ScalarStuff).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param {flatbuffers.ByteBuffer} bb
- * @param {optional_scalars.ScalarStuff=} obj
- * @returns {optional_scalars.ScalarStuff}
- */
-optional_scalars.ScalarStuff.getSizePrefixedRootAsScalarStuff = function(bb, obj) {
- bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
- return (obj || new optional_scalars.ScalarStuff).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param {flatbuffers.ByteBuffer} bb
- * @returns {boolean}
- */
-optional_scalars.ScalarStuff.bufferHasIdentifier = function(bb) {
- return bb.__has_identifier('NULL');
-};
-
-/**
- * @returns {number}
- */
-optional_scalars.ScalarStuff.prototype.justI8 = function() {
- var offset = this.bb.__offset(this.bb_pos, 4);
- return offset ? this.bb.readInt8(this.bb_pos + offset) : 0;
-};
-
-/**
- * @returns {number|null}
- */
-optional_scalars.ScalarStuff.prototype.maybeI8 = function() {
- var offset = this.bb.__offset(this.bb_pos, 6);
- return offset ? this.bb.readInt8(this.bb_pos + offset) : null;
-};
-
-/**
- * @returns {number}
- */
-optional_scalars.ScalarStuff.prototype.defaultI8 = function() {
- var offset = this.bb.__offset(this.bb_pos, 8);
- return offset ? this.bb.readInt8(this.bb_pos + offset) : 42;
-};
-
-/**
- * @returns {number}
- */
-optional_scalars.ScalarStuff.prototype.justU8 = function() {
- var offset = this.bb.__offset(this.bb_pos, 10);
- return offset ? this.bb.readUint8(this.bb_pos + offset) : 0;
-};
-
-/**
- * @returns {number|null}
- */
-optional_scalars.ScalarStuff.prototype.maybeU8 = function() {
- var offset = this.bb.__offset(this.bb_pos, 12);
- return offset ? this.bb.readUint8(this.bb_pos + offset) : null;
-};
-
-/**
- * @returns {number}
- */
-optional_scalars.ScalarStuff.prototype.defaultU8 = function() {
- var offset = this.bb.__offset(this.bb_pos, 14);
- return offset ? this.bb.readUint8(this.bb_pos + offset) : 42;
-};
-
-/**
- * @returns {number}
- */
-optional_scalars.ScalarStuff.prototype.justI16 = function() {
- var offset = this.bb.__offset(this.bb_pos, 16);
- return offset ? this.bb.readInt16(this.bb_pos + offset) : 0;
-};
-
-/**
- * @returns {number|null}
- */
-optional_scalars.ScalarStuff.prototype.maybeI16 = function() {
- var offset = this.bb.__offset(this.bb_pos, 18);
- return offset ? this.bb.readInt16(this.bb_pos + offset) : null;
-};
-
-/**
- * @returns {number}
- */
-optional_scalars.ScalarStuff.prototype.defaultI16 = function() {
- var offset = this.bb.__offset(this.bb_pos, 20);
- return offset ? this.bb.readInt16(this.bb_pos + offset) : 42;
-};
-
-/**
- * @returns {number}
- */
-optional_scalars.ScalarStuff.prototype.justU16 = function() {
- var offset = this.bb.__offset(this.bb_pos, 22);
- return offset ? this.bb.readUint16(this.bb_pos + offset) : 0;
-};
-
-/**
- * @returns {number|null}
- */
-optional_scalars.ScalarStuff.prototype.maybeU16 = function() {
- var offset = this.bb.__offset(this.bb_pos, 24);
- return offset ? this.bb.readUint16(this.bb_pos + offset) : null;
-};
-
-/**
- * @returns {number}
- */
-optional_scalars.ScalarStuff.prototype.defaultU16 = function() {
- var offset = this.bb.__offset(this.bb_pos, 26);
- return offset ? this.bb.readUint16(this.bb_pos + offset) : 42;
-};
-
-/**
- * @returns {number}
- */
-optional_scalars.ScalarStuff.prototype.justI32 = function() {
- var offset = this.bb.__offset(this.bb_pos, 28);
- return offset ? this.bb.readInt32(this.bb_pos + offset) : 0;
-};
-
-/**
- * @returns {number|null}
- */
-optional_scalars.ScalarStuff.prototype.maybeI32 = function() {
- var offset = this.bb.__offset(this.bb_pos, 30);
- return offset ? this.bb.readInt32(this.bb_pos + offset) : null;
-};
-
-/**
- * @returns {number}
- */
-optional_scalars.ScalarStuff.prototype.defaultI32 = function() {
- var offset = this.bb.__offset(this.bb_pos, 32);
- return offset ? this.bb.readInt32(this.bb_pos + offset) : 42;
-};
-
-/**
- * @returns {number}
- */
-optional_scalars.ScalarStuff.prototype.justU32 = function() {
- var offset = this.bb.__offset(this.bb_pos, 34);
- return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
-};
-
-/**
- * @returns {number|null}
- */
-optional_scalars.ScalarStuff.prototype.maybeU32 = function() {
- var offset = this.bb.__offset(this.bb_pos, 36);
- return offset ? this.bb.readUint32(this.bb_pos + offset) : null;
-};
-
-/**
- * @returns {number}
- */
-optional_scalars.ScalarStuff.prototype.defaultU32 = function() {
- var offset = this.bb.__offset(this.bb_pos, 38);
- return offset ? this.bb.readUint32(this.bb_pos + offset) : 42;
-};
-
-/**
- * @returns {flatbuffers.Long}
- */
-optional_scalars.ScalarStuff.prototype.justI64 = function() {
- var offset = this.bb.__offset(this.bb_pos, 40);
- return offset ? this.bb.readInt64(this.bb_pos + offset) : this.bb.createLong(0, 0);
-};
-
-/**
- * @returns {flatbuffers.Long|null}
- */
-optional_scalars.ScalarStuff.prototype.maybeI64 = function() {
- var offset = this.bb.__offset(this.bb_pos, 42);
- return offset ? this.bb.readInt64(this.bb_pos + offset) : null;
-};
-
-/**
- * @returns {flatbuffers.Long}
- */
-optional_scalars.ScalarStuff.prototype.defaultI64 = function() {
- var offset = this.bb.__offset(this.bb_pos, 44);
- return offset ? this.bb.readInt64(this.bb_pos + offset) : this.bb.createLong(42, 0);
-};
-
-/**
- * @returns {flatbuffers.Long}
- */
-optional_scalars.ScalarStuff.prototype.justU64 = function() {
- var offset = this.bb.__offset(this.bb_pos, 46);
- return offset ? this.bb.readUint64(this.bb_pos + offset) : this.bb.createLong(0, 0);
-};
-
-/**
- * @returns {flatbuffers.Long|null}
- */
-optional_scalars.ScalarStuff.prototype.maybeU64 = function() {
- var offset = this.bb.__offset(this.bb_pos, 48);
- return offset ? this.bb.readUint64(this.bb_pos + offset) : null;
-};
-
-/**
- * @returns {flatbuffers.Long}
- */
-optional_scalars.ScalarStuff.prototype.defaultU64 = function() {
- var offset = this.bb.__offset(this.bb_pos, 50);
- return offset ? this.bb.readUint64(this.bb_pos + offset) : this.bb.createLong(42, 0);
-};
-
-/**
- * @returns {number}
- */
-optional_scalars.ScalarStuff.prototype.justF32 = function() {
- var offset = this.bb.__offset(this.bb_pos, 52);
- return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0.0;
-};
-
-/**
- * @returns {number|null}
- */
-optional_scalars.ScalarStuff.prototype.maybeF32 = function() {
- var offset = this.bb.__offset(this.bb_pos, 54);
- return offset ? this.bb.readFloat32(this.bb_pos + offset) : null;
-};
-
-/**
- * @returns {number}
- */
-optional_scalars.ScalarStuff.prototype.defaultF32 = function() {
- var offset = this.bb.__offset(this.bb_pos, 56);
- return offset ? this.bb.readFloat32(this.bb_pos + offset) : 42.0;
-};
-
-/**
- * @returns {number}
- */
-optional_scalars.ScalarStuff.prototype.justF64 = function() {
- var offset = this.bb.__offset(this.bb_pos, 58);
- return offset ? this.bb.readFloat64(this.bb_pos + offset) : 0.0;
-};
-
-/**
- * @returns {number|null}
- */
-optional_scalars.ScalarStuff.prototype.maybeF64 = function() {
- var offset = this.bb.__offset(this.bb_pos, 60);
- return offset ? this.bb.readFloat64(this.bb_pos + offset) : null;
-};
-
-/**
- * @returns {number}
- */
-optional_scalars.ScalarStuff.prototype.defaultF64 = function() {
- var offset = this.bb.__offset(this.bb_pos, 62);
- return offset ? this.bb.readFloat64(this.bb_pos + offset) : 42.0;
-};
-
-/**
- * @returns {boolean}
- */
-optional_scalars.ScalarStuff.prototype.justBool = function() {
- var offset = this.bb.__offset(this.bb_pos, 64);
- return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false;
-};
-
-/**
- * @returns {boolean|null}
- */
-optional_scalars.ScalarStuff.prototype.maybeBool = function() {
- var offset = this.bb.__offset(this.bb_pos, 66);
- return offset ? !!this.bb.readInt8(this.bb_pos + offset) : null;
-};
-
-/**
- * @returns {boolean}
- */
-optional_scalars.ScalarStuff.prototype.defaultBool = function() {
- var offset = this.bb.__offset(this.bb_pos, 68);
- return offset ? !!this.bb.readInt8(this.bb_pos + offset) : true;
-};
-
-/**
- * @returns {optional_scalars.OptionalByte}
- */
-optional_scalars.ScalarStuff.prototype.justEnum = function() {
- var offset = this.bb.__offset(this.bb_pos, 70);
- return offset ? /** @type {optional_scalars.OptionalByte} */ (this.bb.readInt8(this.bb_pos + offset)) : optional_scalars.OptionalByte.None;
-};
-
-/**
- * @returns {optional_scalars.OptionalByte|null}
- */
-optional_scalars.ScalarStuff.prototype.maybeEnum = function() {
- var offset = this.bb.__offset(this.bb_pos, 72);
- return offset ? /** @type {optional_scalars.OptionalByte} */ (this.bb.readInt8(this.bb_pos + offset)) : null;
-};
-
-/**
- * @returns {optional_scalars.OptionalByte}
- */
-optional_scalars.ScalarStuff.prototype.defaultEnum = function() {
- var offset = this.bb.__offset(this.bb_pos, 74);
- return offset ? /** @type {optional_scalars.OptionalByte} */ (this.bb.readInt8(this.bb_pos + offset)) : optional_scalars.OptionalByte.One;
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- */
-optional_scalars.ScalarStuff.startScalarStuff = function(builder) {
- builder.startObject(36);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} justI8
- */
-optional_scalars.ScalarStuff.addJustI8 = function(builder, justI8) {
- builder.addFieldInt8(0, justI8, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} maybeI8
- */
-optional_scalars.ScalarStuff.addMaybeI8 = function(builder, maybeI8) {
- builder.addFieldInt8(1, maybeI8, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} defaultI8
- */
-optional_scalars.ScalarStuff.addDefaultI8 = function(builder, defaultI8) {
- builder.addFieldInt8(2, defaultI8, 42);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} justU8
- */
-optional_scalars.ScalarStuff.addJustU8 = function(builder, justU8) {
- builder.addFieldInt8(3, justU8, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} maybeU8
- */
-optional_scalars.ScalarStuff.addMaybeU8 = function(builder, maybeU8) {
- builder.addFieldInt8(4, maybeU8, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} defaultU8
- */
-optional_scalars.ScalarStuff.addDefaultU8 = function(builder, defaultU8) {
- builder.addFieldInt8(5, defaultU8, 42);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} justI16
- */
-optional_scalars.ScalarStuff.addJustI16 = function(builder, justI16) {
- builder.addFieldInt16(6, justI16, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} maybeI16
- */
-optional_scalars.ScalarStuff.addMaybeI16 = function(builder, maybeI16) {
- builder.addFieldInt16(7, maybeI16, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} defaultI16
- */
-optional_scalars.ScalarStuff.addDefaultI16 = function(builder, defaultI16) {
- builder.addFieldInt16(8, defaultI16, 42);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} justU16
- */
-optional_scalars.ScalarStuff.addJustU16 = function(builder, justU16) {
- builder.addFieldInt16(9, justU16, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} maybeU16
- */
-optional_scalars.ScalarStuff.addMaybeU16 = function(builder, maybeU16) {
- builder.addFieldInt16(10, maybeU16, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} defaultU16
- */
-optional_scalars.ScalarStuff.addDefaultU16 = function(builder, defaultU16) {
- builder.addFieldInt16(11, defaultU16, 42);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} justI32
- */
-optional_scalars.ScalarStuff.addJustI32 = function(builder, justI32) {
- builder.addFieldInt32(12, justI32, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} maybeI32
- */
-optional_scalars.ScalarStuff.addMaybeI32 = function(builder, maybeI32) {
- builder.addFieldInt32(13, maybeI32, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} defaultI32
- */
-optional_scalars.ScalarStuff.addDefaultI32 = function(builder, defaultI32) {
- builder.addFieldInt32(14, defaultI32, 42);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} justU32
- */
-optional_scalars.ScalarStuff.addJustU32 = function(builder, justU32) {
- builder.addFieldInt32(15, justU32, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} maybeU32
- */
-optional_scalars.ScalarStuff.addMaybeU32 = function(builder, maybeU32) {
- builder.addFieldInt32(16, maybeU32, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} defaultU32
- */
-optional_scalars.ScalarStuff.addDefaultU32 = function(builder, defaultU32) {
- builder.addFieldInt32(17, defaultU32, 42);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Long} justI64
- */
-optional_scalars.ScalarStuff.addJustI64 = function(builder, justI64) {
- builder.addFieldInt64(18, justI64, builder.createLong(0, 0));
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Long} maybeI64
- */
-optional_scalars.ScalarStuff.addMaybeI64 = function(builder, maybeI64) {
- builder.addFieldInt64(19, maybeI64, builder.createLong(0, 0));
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Long} defaultI64
- */
-optional_scalars.ScalarStuff.addDefaultI64 = function(builder, defaultI64) {
- builder.addFieldInt64(20, defaultI64, builder.createLong(42, 0));
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Long} justU64
- */
-optional_scalars.ScalarStuff.addJustU64 = function(builder, justU64) {
- builder.addFieldInt64(21, justU64, builder.createLong(0, 0));
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Long} maybeU64
- */
-optional_scalars.ScalarStuff.addMaybeU64 = function(builder, maybeU64) {
- builder.addFieldInt64(22, maybeU64, builder.createLong(0, 0));
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Long} defaultU64
- */
-optional_scalars.ScalarStuff.addDefaultU64 = function(builder, defaultU64) {
- builder.addFieldInt64(23, defaultU64, builder.createLong(42, 0));
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} justF32
- */
-optional_scalars.ScalarStuff.addJustF32 = function(builder, justF32) {
- builder.addFieldFloat32(24, justF32, 0.0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} maybeF32
- */
-optional_scalars.ScalarStuff.addMaybeF32 = function(builder, maybeF32) {
- builder.addFieldFloat32(25, maybeF32, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} defaultF32
- */
-optional_scalars.ScalarStuff.addDefaultF32 = function(builder, defaultF32) {
- builder.addFieldFloat32(26, defaultF32, 42.0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} justF64
- */
-optional_scalars.ScalarStuff.addJustF64 = function(builder, justF64) {
- builder.addFieldFloat64(27, justF64, 0.0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} maybeF64
- */
-optional_scalars.ScalarStuff.addMaybeF64 = function(builder, maybeF64) {
- builder.addFieldFloat64(28, maybeF64, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} defaultF64
- */
-optional_scalars.ScalarStuff.addDefaultF64 = function(builder, defaultF64) {
- builder.addFieldFloat64(29, defaultF64, 42.0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {boolean} justBool
- */
-optional_scalars.ScalarStuff.addJustBool = function(builder, justBool) {
- builder.addFieldInt8(30, +justBool, +false);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {boolean} maybeBool
- */
-optional_scalars.ScalarStuff.addMaybeBool = function(builder, maybeBool) {
- builder.addFieldInt8(31, +maybeBool, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {boolean} defaultBool
- */
-optional_scalars.ScalarStuff.addDefaultBool = function(builder, defaultBool) {
- builder.addFieldInt8(32, +defaultBool, +true);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {optional_scalars.OptionalByte} justEnum
- */
-optional_scalars.ScalarStuff.addJustEnum = function(builder, justEnum) {
- builder.addFieldInt8(33, justEnum, optional_scalars.OptionalByte.None);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {optional_scalars.OptionalByte} maybeEnum
- */
-optional_scalars.ScalarStuff.addMaybeEnum = function(builder, maybeEnum) {
- builder.addFieldInt8(34, maybeEnum, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {optional_scalars.OptionalByte} defaultEnum
- */
-optional_scalars.ScalarStuff.addDefaultEnum = function(builder, defaultEnum) {
- builder.addFieldInt8(35, defaultEnum, optional_scalars.OptionalByte.One);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @returns {flatbuffers.Offset}
- */
-optional_scalars.ScalarStuff.endScalarStuff = function(builder) {
- var offset = builder.endObject();
- return offset;
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Offset} offset
- */
-optional_scalars.ScalarStuff.finishScalarStuffBuffer = function(builder, offset) {
- builder.finish(offset, 'NULL');
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Offset} offset
- */
-optional_scalars.ScalarStuff.finishSizePrefixedScalarStuffBuffer = function(builder, offset) {
- builder.finish(offset, 'NULL', true);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} justI8
- * @param {number|null} maybeI8
- * @param {number} defaultI8
- * @param {number} justU8
- * @param {number|null} maybeU8
- * @param {number} defaultU8
- * @param {number} justI16
- * @param {number|null} maybeI16
- * @param {number} defaultI16
- * @param {number} justU16
- * @param {number|null} maybeU16
- * @param {number} defaultU16
- * @param {number} justI32
- * @param {number|null} maybeI32
- * @param {number} defaultI32
- * @param {number} justU32
- * @param {number|null} maybeU32
- * @param {number} defaultU32
- * @param {flatbuffers.Long} justI64
- * @param {flatbuffers.Long|null} maybeI64
- * @param {flatbuffers.Long} defaultI64
- * @param {flatbuffers.Long} justU64
- * @param {flatbuffers.Long|null} maybeU64
- * @param {flatbuffers.Long} defaultU64
- * @param {number} justF32
- * @param {number|null} maybeF32
- * @param {number} defaultF32
- * @param {number} justF64
- * @param {number|null} maybeF64
- * @param {number} defaultF64
- * @param {boolean} justBool
- * @param {boolean|null} maybeBool
- * @param {boolean} defaultBool
- * @param {optional_scalars.OptionalByte} justEnum
- * @param {optional_scalars.OptionalByte|null} maybeEnum
- * @param {optional_scalars.OptionalByte} defaultEnum
- * @returns {flatbuffers.Offset}
- */
-optional_scalars.ScalarStuff.createScalarStuff = function(builder, justI8, maybeI8, defaultI8, justU8, maybeU8, defaultU8, justI16, maybeI16, defaultI16, justU16, maybeU16, defaultU16, justI32, maybeI32, defaultI32, justU32, maybeU32, defaultU32, justI64, maybeI64, defaultI64, justU64, maybeU64, defaultU64, justF32, maybeF32, defaultF32, justF64, maybeF64, defaultF64, justBool, maybeBool, defaultBool, justEnum, maybeEnum, defaultEnum) {
- optional_scalars.ScalarStuff.startScalarStuff(builder);
- optional_scalars.ScalarStuff.addJustI8(builder, justI8);
- if (maybeI8 !== null)
- optional_scalars.ScalarStuff.addMaybeI8(builder, maybeI8);
- optional_scalars.ScalarStuff.addDefaultI8(builder, defaultI8);
- optional_scalars.ScalarStuff.addJustU8(builder, justU8);
- if (maybeU8 !== null)
- optional_scalars.ScalarStuff.addMaybeU8(builder, maybeU8);
- optional_scalars.ScalarStuff.addDefaultU8(builder, defaultU8);
- optional_scalars.ScalarStuff.addJustI16(builder, justI16);
- if (maybeI16 !== null)
- optional_scalars.ScalarStuff.addMaybeI16(builder, maybeI16);
- optional_scalars.ScalarStuff.addDefaultI16(builder, defaultI16);
- optional_scalars.ScalarStuff.addJustU16(builder, justU16);
- if (maybeU16 !== null)
- optional_scalars.ScalarStuff.addMaybeU16(builder, maybeU16);
- optional_scalars.ScalarStuff.addDefaultU16(builder, defaultU16);
- optional_scalars.ScalarStuff.addJustI32(builder, justI32);
- if (maybeI32 !== null)
- optional_scalars.ScalarStuff.addMaybeI32(builder, maybeI32);
- optional_scalars.ScalarStuff.addDefaultI32(builder, defaultI32);
- optional_scalars.ScalarStuff.addJustU32(builder, justU32);
- if (maybeU32 !== null)
- optional_scalars.ScalarStuff.addMaybeU32(builder, maybeU32);
- optional_scalars.ScalarStuff.addDefaultU32(builder, defaultU32);
- optional_scalars.ScalarStuff.addJustI64(builder, justI64);
- if (maybeI64 !== null)
- optional_scalars.ScalarStuff.addMaybeI64(builder, maybeI64);
- optional_scalars.ScalarStuff.addDefaultI64(builder, defaultI64);
- optional_scalars.ScalarStuff.addJustU64(builder, justU64);
- if (maybeU64 !== null)
- optional_scalars.ScalarStuff.addMaybeU64(builder, maybeU64);
- optional_scalars.ScalarStuff.addDefaultU64(builder, defaultU64);
- optional_scalars.ScalarStuff.addJustF32(builder, justF32);
- if (maybeF32 !== null)
- optional_scalars.ScalarStuff.addMaybeF32(builder, maybeF32);
- optional_scalars.ScalarStuff.addDefaultF32(builder, defaultF32);
- optional_scalars.ScalarStuff.addJustF64(builder, justF64);
- if (maybeF64 !== null)
- optional_scalars.ScalarStuff.addMaybeF64(builder, maybeF64);
- optional_scalars.ScalarStuff.addDefaultF64(builder, defaultF64);
- optional_scalars.ScalarStuff.addJustBool(builder, justBool);
- if (maybeBool !== null)
- optional_scalars.ScalarStuff.addMaybeBool(builder, maybeBool);
- optional_scalars.ScalarStuff.addDefaultBool(builder, defaultBool);
- optional_scalars.ScalarStuff.addJustEnum(builder, justEnum);
- if (maybeEnum !== null)
- optional_scalars.ScalarStuff.addMaybeEnum(builder, maybeEnum);
- optional_scalars.ScalarStuff.addDefaultEnum(builder, defaultEnum);
- return optional_scalars.ScalarStuff.endScalarStuff(builder);
-}
-
-// Exports for Node.js and RequireJS
-this.optional_scalars = optional_scalars;
diff --git a/tests/optional_scalars_generated.lobster b/tests/optional_scalars_generated.lobster
index d0f7aef..95cba95 100644
--- a/tests/optional_scalars_generated.lobster
+++ b/tests/optional_scalars_generated.lobster
@@ -18,11 +18,11 @@
def default_i8():
return buf_.flatbuffers_field_int8(pos_, 8, 42)
def just_u8():
- return buf_.flatbuffers_field_int8(pos_, 10, 0)
+ return buf_.flatbuffers_field_uint8(pos_, 10, 0)
def maybe_u8():
- return buf_.flatbuffers_field_int8(pos_, 12, 0), buf_.flatbuffers_field_present(pos_, 12)
+ return buf_.flatbuffers_field_uint8(pos_, 12, 0), buf_.flatbuffers_field_present(pos_, 12)
def default_u8():
- return buf_.flatbuffers_field_int8(pos_, 14, 42)
+ return buf_.flatbuffers_field_uint8(pos_, 14, 42)
def just_i16():
return buf_.flatbuffers_field_int16(pos_, 16, 0)
def maybe_i16():
@@ -30,11 +30,11 @@
def default_i16():
return buf_.flatbuffers_field_int16(pos_, 20, 42)
def just_u16():
- return buf_.flatbuffers_field_int16(pos_, 22, 0)
+ return buf_.flatbuffers_field_uint16(pos_, 22, 0)
def maybe_u16():
- return buf_.flatbuffers_field_int16(pos_, 24, 0), buf_.flatbuffers_field_present(pos_, 24)
+ return buf_.flatbuffers_field_uint16(pos_, 24, 0), buf_.flatbuffers_field_present(pos_, 24)
def default_u16():
- return buf_.flatbuffers_field_int16(pos_, 26, 42)
+ return buf_.flatbuffers_field_uint16(pos_, 26, 42)
def just_i32():
return buf_.flatbuffers_field_int32(pos_, 28, 0)
def maybe_i32():
@@ -42,11 +42,11 @@
def default_i32():
return buf_.flatbuffers_field_int32(pos_, 32, 42)
def just_u32():
- return buf_.flatbuffers_field_int32(pos_, 34, 0)
+ return buf_.flatbuffers_field_uint32(pos_, 34, 0)
def maybe_u32():
- return buf_.flatbuffers_field_int32(pos_, 36, 0), buf_.flatbuffers_field_present(pos_, 36)
+ return buf_.flatbuffers_field_uint32(pos_, 36, 0), buf_.flatbuffers_field_present(pos_, 36)
def default_u32():
- return buf_.flatbuffers_field_int32(pos_, 38, 42)
+ return buf_.flatbuffers_field_uint32(pos_, 38, 42)
def just_i64():
return buf_.flatbuffers_field_int64(pos_, 40, 0)
def maybe_i64():
@@ -54,11 +54,11 @@
def default_i64():
return buf_.flatbuffers_field_int64(pos_, 44, 42)
def just_u64():
- return buf_.flatbuffers_field_int64(pos_, 46, 0)
+ return buf_.flatbuffers_field_uint64(pos_, 46, 0)
def maybe_u64():
- return buf_.flatbuffers_field_int64(pos_, 48, 0), buf_.flatbuffers_field_present(pos_, 48)
+ return buf_.flatbuffers_field_uint64(pos_, 48, 0), buf_.flatbuffers_field_present(pos_, 48)
def default_u64():
- return buf_.flatbuffers_field_int64(pos_, 50, 42)
+ return buf_.flatbuffers_field_uint64(pos_, 50, 42)
def just_f32():
return buf_.flatbuffers_field_float32(pos_, 52, 0.0)
def maybe_f32():
diff --git a/tests/optional_scalars_generated.rs b/tests/optional_scalars_generated.rs
deleted file mode 100644
index 793a8ac..0000000
--- a/tests/optional_scalars_generated.rs
+++ /dev/null
@@ -1,667 +0,0 @@
-// automatically generated by the FlatBuffers compiler, do not modify
-
-
-#![allow(unused_imports, dead_code)]
-
-use std::mem;
-use std::cmp::Ordering;
-
-extern crate flatbuffers;
-use self::flatbuffers::EndianScalar;
-
-#[allow(unused_imports, dead_code)]
-pub mod optional_scalars {
-
- use std::mem;
- use std::cmp::Ordering;
-
- extern crate flatbuffers;
- use self::flatbuffers::EndianScalar;
-
-#[deprecated(since = "1.13", note = "Use associated constants instead. This will no longer be generated in 2021.")]
-pub const ENUM_MIN_OPTIONAL_BYTE: i8 = 0;
-#[deprecated(since = "1.13", note = "Use associated constants instead. This will no longer be generated in 2021.")]
-pub const ENUM_MAX_OPTIONAL_BYTE: i8 = 2;
-#[deprecated(since = "1.13", note = "Use associated constants instead. This will no longer be generated in 2021.")]
-#[allow(non_camel_case_types)]
-pub const ENUM_VALUES_OPTIONAL_BYTE: [OptionalByte; 3] = [
- OptionalByte::None,
- OptionalByte::One,
- OptionalByte::Two,
-];
-
-#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
-#[repr(transparent)]
-pub struct OptionalByte(pub i8);
-#[allow(non_upper_case_globals)]
-impl OptionalByte {
- pub const None: Self = Self(0);
- pub const One: Self = Self(1);
- pub const Two: Self = Self(2);
-
- pub const ENUM_MIN: i8 = 0;
- pub const ENUM_MAX: i8 = 2;
- pub const ENUM_VALUES: &'static [Self] = &[
- Self::None,
- Self::One,
- Self::Two,
- ];
- /// Returns the variant's name or "" if unknown.
- pub fn variant_name(self) -> Option<&'static str> {
- match self {
- Self::None => Some("None"),
- Self::One => Some("One"),
- Self::Two => Some("Two"),
- _ => None,
- }
- }
-}
-impl std::fmt::Debug for OptionalByte {
- fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
- if let Some(name) = self.variant_name() {
- f.write_str(name)
- } else {
- f.write_fmt(format_args!("<UNKNOWN {:?}>", self.0))
- }
- }
-}
-impl<'a> flatbuffers::Follow<'a> for OptionalByte {
- type Inner = Self;
- #[inline]
- fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
- Self(flatbuffers::read_scalar_at::<i8>(buf, loc))
- }
-}
-
-impl flatbuffers::Push for OptionalByte {
- type Output = OptionalByte;
- #[inline]
- fn push(&self, dst: &mut [u8], _rest: &[u8]) {
- flatbuffers::emplace_scalar::<i8>(dst, self.0);
- }
-}
-
-impl flatbuffers::EndianScalar for OptionalByte {
- #[inline]
- fn to_little_endian(self) -> Self {
- Self(i8::to_le(self.0))
- }
- #[inline]
- fn from_little_endian(self) -> Self {
- Self(i8::from_le(self.0))
- }
-}
-
-pub enum ScalarStuffOffset {}
-#[derive(Copy, Clone, PartialEq)]
-
-pub struct ScalarStuff<'a> {
- pub _tab: flatbuffers::Table<'a>,
-}
-
-impl<'a> flatbuffers::Follow<'a> for ScalarStuff<'a> {
- type Inner = ScalarStuff<'a>;
- #[inline]
- fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
- Self { _tab: flatbuffers::Table { buf, loc } }
- }
-}
-
-impl<'a> ScalarStuff<'a> {
- #[inline]
- pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
- ScalarStuff {
- _tab: table,
- }
- }
- #[allow(unused_mut)]
- pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
- _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
- args: &'args ScalarStuffArgs) -> flatbuffers::WIPOffset<ScalarStuff<'bldr>> {
- let mut builder = ScalarStuffBuilder::new(_fbb);
- builder.add_default_f64(args.default_f64);
- if let Some(x) = args.maybe_f64 { builder.add_maybe_f64(x); }
- builder.add_just_f64(args.just_f64);
- builder.add_default_u64(args.default_u64);
- if let Some(x) = args.maybe_u64 { builder.add_maybe_u64(x); }
- builder.add_just_u64(args.just_u64);
- builder.add_default_i64(args.default_i64);
- if let Some(x) = args.maybe_i64 { builder.add_maybe_i64(x); }
- builder.add_just_i64(args.just_i64);
- builder.add_default_f32(args.default_f32);
- if let Some(x) = args.maybe_f32 { builder.add_maybe_f32(x); }
- builder.add_just_f32(args.just_f32);
- builder.add_default_u32(args.default_u32);
- if let Some(x) = args.maybe_u32 { builder.add_maybe_u32(x); }
- builder.add_just_u32(args.just_u32);
- builder.add_default_i32(args.default_i32);
- if let Some(x) = args.maybe_i32 { builder.add_maybe_i32(x); }
- builder.add_just_i32(args.just_i32);
- builder.add_default_u16(args.default_u16);
- if let Some(x) = args.maybe_u16 { builder.add_maybe_u16(x); }
- builder.add_just_u16(args.just_u16);
- builder.add_default_i16(args.default_i16);
- if let Some(x) = args.maybe_i16 { builder.add_maybe_i16(x); }
- builder.add_just_i16(args.just_i16);
- builder.add_default_enum(args.default_enum);
- if let Some(x) = args.maybe_enum { builder.add_maybe_enum(x); }
- builder.add_just_enum(args.just_enum);
- builder.add_default_bool(args.default_bool);
- if let Some(x) = args.maybe_bool { builder.add_maybe_bool(x); }
- builder.add_just_bool(args.just_bool);
- builder.add_default_u8(args.default_u8);
- if let Some(x) = args.maybe_u8 { builder.add_maybe_u8(x); }
- builder.add_just_u8(args.just_u8);
- builder.add_default_i8(args.default_i8);
- if let Some(x) = args.maybe_i8 { builder.add_maybe_i8(x); }
- builder.add_just_i8(args.just_i8);
- builder.finish()
- }
-
- pub const VT_JUST_I8: flatbuffers::VOffsetT = 4;
- pub const VT_MAYBE_I8: flatbuffers::VOffsetT = 6;
- pub const VT_DEFAULT_I8: flatbuffers::VOffsetT = 8;
- pub const VT_JUST_U8: flatbuffers::VOffsetT = 10;
- pub const VT_MAYBE_U8: flatbuffers::VOffsetT = 12;
- pub const VT_DEFAULT_U8: flatbuffers::VOffsetT = 14;
- pub const VT_JUST_I16: flatbuffers::VOffsetT = 16;
- pub const VT_MAYBE_I16: flatbuffers::VOffsetT = 18;
- pub const VT_DEFAULT_I16: flatbuffers::VOffsetT = 20;
- pub const VT_JUST_U16: flatbuffers::VOffsetT = 22;
- pub const VT_MAYBE_U16: flatbuffers::VOffsetT = 24;
- pub const VT_DEFAULT_U16: flatbuffers::VOffsetT = 26;
- pub const VT_JUST_I32: flatbuffers::VOffsetT = 28;
- pub const VT_MAYBE_I32: flatbuffers::VOffsetT = 30;
- pub const VT_DEFAULT_I32: flatbuffers::VOffsetT = 32;
- pub const VT_JUST_U32: flatbuffers::VOffsetT = 34;
- pub const VT_MAYBE_U32: flatbuffers::VOffsetT = 36;
- pub const VT_DEFAULT_U32: flatbuffers::VOffsetT = 38;
- pub const VT_JUST_I64: flatbuffers::VOffsetT = 40;
- pub const VT_MAYBE_I64: flatbuffers::VOffsetT = 42;
- pub const VT_DEFAULT_I64: flatbuffers::VOffsetT = 44;
- pub const VT_JUST_U64: flatbuffers::VOffsetT = 46;
- pub const VT_MAYBE_U64: flatbuffers::VOffsetT = 48;
- pub const VT_DEFAULT_U64: flatbuffers::VOffsetT = 50;
- pub const VT_JUST_F32: flatbuffers::VOffsetT = 52;
- pub const VT_MAYBE_F32: flatbuffers::VOffsetT = 54;
- pub const VT_DEFAULT_F32: flatbuffers::VOffsetT = 56;
- pub const VT_JUST_F64: flatbuffers::VOffsetT = 58;
- pub const VT_MAYBE_F64: flatbuffers::VOffsetT = 60;
- pub const VT_DEFAULT_F64: flatbuffers::VOffsetT = 62;
- pub const VT_JUST_BOOL: flatbuffers::VOffsetT = 64;
- pub const VT_MAYBE_BOOL: flatbuffers::VOffsetT = 66;
- pub const VT_DEFAULT_BOOL: flatbuffers::VOffsetT = 68;
- pub const VT_JUST_ENUM: flatbuffers::VOffsetT = 70;
- pub const VT_MAYBE_ENUM: flatbuffers::VOffsetT = 72;
- pub const VT_DEFAULT_ENUM: flatbuffers::VOffsetT = 74;
-
- #[inline]
- pub fn just_i8(&self) -> i8 {
- self._tab.get::<i8>(ScalarStuff::VT_JUST_I8, Some(0)).unwrap()
- }
- #[inline]
- pub fn maybe_i8(&self) -> Option<i8> {
- self._tab.get::<i8>(ScalarStuff::VT_MAYBE_I8, None)
- }
- #[inline]
- pub fn default_i8(&self) -> i8 {
- self._tab.get::<i8>(ScalarStuff::VT_DEFAULT_I8, Some(42)).unwrap()
- }
- #[inline]
- pub fn just_u8(&self) -> u8 {
- self._tab.get::<u8>(ScalarStuff::VT_JUST_U8, Some(0)).unwrap()
- }
- #[inline]
- pub fn maybe_u8(&self) -> Option<u8> {
- self._tab.get::<u8>(ScalarStuff::VT_MAYBE_U8, None)
- }
- #[inline]
- pub fn default_u8(&self) -> u8 {
- self._tab.get::<u8>(ScalarStuff::VT_DEFAULT_U8, Some(42)).unwrap()
- }
- #[inline]
- pub fn just_i16(&self) -> i16 {
- self._tab.get::<i16>(ScalarStuff::VT_JUST_I16, Some(0)).unwrap()
- }
- #[inline]
- pub fn maybe_i16(&self) -> Option<i16> {
- self._tab.get::<i16>(ScalarStuff::VT_MAYBE_I16, None)
- }
- #[inline]
- pub fn default_i16(&self) -> i16 {
- self._tab.get::<i16>(ScalarStuff::VT_DEFAULT_I16, Some(42)).unwrap()
- }
- #[inline]
- pub fn just_u16(&self) -> u16 {
- self._tab.get::<u16>(ScalarStuff::VT_JUST_U16, Some(0)).unwrap()
- }
- #[inline]
- pub fn maybe_u16(&self) -> Option<u16> {
- self._tab.get::<u16>(ScalarStuff::VT_MAYBE_U16, None)
- }
- #[inline]
- pub fn default_u16(&self) -> u16 {
- self._tab.get::<u16>(ScalarStuff::VT_DEFAULT_U16, Some(42)).unwrap()
- }
- #[inline]
- pub fn just_i32(&self) -> i32 {
- self._tab.get::<i32>(ScalarStuff::VT_JUST_I32, Some(0)).unwrap()
- }
- #[inline]
- pub fn maybe_i32(&self) -> Option<i32> {
- self._tab.get::<i32>(ScalarStuff::VT_MAYBE_I32, None)
- }
- #[inline]
- pub fn default_i32(&self) -> i32 {
- self._tab.get::<i32>(ScalarStuff::VT_DEFAULT_I32, Some(42)).unwrap()
- }
- #[inline]
- pub fn just_u32(&self) -> u32 {
- self._tab.get::<u32>(ScalarStuff::VT_JUST_U32, Some(0)).unwrap()
- }
- #[inline]
- pub fn maybe_u32(&self) -> Option<u32> {
- self._tab.get::<u32>(ScalarStuff::VT_MAYBE_U32, None)
- }
- #[inline]
- pub fn default_u32(&self) -> u32 {
- self._tab.get::<u32>(ScalarStuff::VT_DEFAULT_U32, Some(42)).unwrap()
- }
- #[inline]
- pub fn just_i64(&self) -> i64 {
- self._tab.get::<i64>(ScalarStuff::VT_JUST_I64, Some(0)).unwrap()
- }
- #[inline]
- pub fn maybe_i64(&self) -> Option<i64> {
- self._tab.get::<i64>(ScalarStuff::VT_MAYBE_I64, None)
- }
- #[inline]
- pub fn default_i64(&self) -> i64 {
- self._tab.get::<i64>(ScalarStuff::VT_DEFAULT_I64, Some(42)).unwrap()
- }
- #[inline]
- pub fn just_u64(&self) -> u64 {
- self._tab.get::<u64>(ScalarStuff::VT_JUST_U64, Some(0)).unwrap()
- }
- #[inline]
- pub fn maybe_u64(&self) -> Option<u64> {
- self._tab.get::<u64>(ScalarStuff::VT_MAYBE_U64, None)
- }
- #[inline]
- pub fn default_u64(&self) -> u64 {
- self._tab.get::<u64>(ScalarStuff::VT_DEFAULT_U64, Some(42)).unwrap()
- }
- #[inline]
- pub fn just_f32(&self) -> f32 {
- self._tab.get::<f32>(ScalarStuff::VT_JUST_F32, Some(0.0)).unwrap()
- }
- #[inline]
- pub fn maybe_f32(&self) -> Option<f32> {
- self._tab.get::<f32>(ScalarStuff::VT_MAYBE_F32, None)
- }
- #[inline]
- pub fn default_f32(&self) -> f32 {
- self._tab.get::<f32>(ScalarStuff::VT_DEFAULT_F32, Some(42.0)).unwrap()
- }
- #[inline]
- pub fn just_f64(&self) -> f64 {
- self._tab.get::<f64>(ScalarStuff::VT_JUST_F64, Some(0.0)).unwrap()
- }
- #[inline]
- pub fn maybe_f64(&self) -> Option<f64> {
- self._tab.get::<f64>(ScalarStuff::VT_MAYBE_F64, None)
- }
- #[inline]
- pub fn default_f64(&self) -> f64 {
- self._tab.get::<f64>(ScalarStuff::VT_DEFAULT_F64, Some(42.0)).unwrap()
- }
- #[inline]
- pub fn just_bool(&self) -> bool {
- self._tab.get::<bool>(ScalarStuff::VT_JUST_BOOL, Some(false)).unwrap()
- }
- #[inline]
- pub fn maybe_bool(&self) -> Option<bool> {
- self._tab.get::<bool>(ScalarStuff::VT_MAYBE_BOOL, None)
- }
- #[inline]
- pub fn default_bool(&self) -> bool {
- self._tab.get::<bool>(ScalarStuff::VT_DEFAULT_BOOL, Some(true)).unwrap()
- }
- #[inline]
- pub fn just_enum(&self) -> OptionalByte {
- self._tab.get::<OptionalByte>(ScalarStuff::VT_JUST_ENUM, Some(OptionalByte::None)).unwrap()
- }
- #[inline]
- pub fn maybe_enum(&self) -> Option<OptionalByte> {
- self._tab.get::<OptionalByte>(ScalarStuff::VT_MAYBE_ENUM, None)
- }
- #[inline]
- pub fn default_enum(&self) -> OptionalByte {
- self._tab.get::<OptionalByte>(ScalarStuff::VT_DEFAULT_ENUM, Some(OptionalByte::One)).unwrap()
- }
-}
-
-pub struct ScalarStuffArgs {
- pub just_i8: i8,
- pub maybe_i8: Option<i8>,
- pub default_i8: i8,
- pub just_u8: u8,
- pub maybe_u8: Option<u8>,
- pub default_u8: u8,
- pub just_i16: i16,
- pub maybe_i16: Option<i16>,
- pub default_i16: i16,
- pub just_u16: u16,
- pub maybe_u16: Option<u16>,
- pub default_u16: u16,
- pub just_i32: i32,
- pub maybe_i32: Option<i32>,
- pub default_i32: i32,
- pub just_u32: u32,
- pub maybe_u32: Option<u32>,
- pub default_u32: u32,
- pub just_i64: i64,
- pub maybe_i64: Option<i64>,
- pub default_i64: i64,
- pub just_u64: u64,
- pub maybe_u64: Option<u64>,
- pub default_u64: u64,
- pub just_f32: f32,
- pub maybe_f32: Option<f32>,
- pub default_f32: f32,
- pub just_f64: f64,
- pub maybe_f64: Option<f64>,
- pub default_f64: f64,
- pub just_bool: bool,
- pub maybe_bool: Option<bool>,
- pub default_bool: bool,
- pub just_enum: OptionalByte,
- pub maybe_enum: Option<OptionalByte>,
- pub default_enum: OptionalByte,
-}
-impl<'a> Default for ScalarStuffArgs {
- #[inline]
- fn default() -> Self {
- ScalarStuffArgs {
- just_i8: 0,
- maybe_i8: None,
- default_i8: 42,
- just_u8: 0,
- maybe_u8: None,
- default_u8: 42,
- just_i16: 0,
- maybe_i16: None,
- default_i16: 42,
- just_u16: 0,
- maybe_u16: None,
- default_u16: 42,
- just_i32: 0,
- maybe_i32: None,
- default_i32: 42,
- just_u32: 0,
- maybe_u32: None,
- default_u32: 42,
- just_i64: 0,
- maybe_i64: None,
- default_i64: 42,
- just_u64: 0,
- maybe_u64: None,
- default_u64: 42,
- just_f32: 0.0,
- maybe_f32: None,
- default_f32: 42.0,
- just_f64: 0.0,
- maybe_f64: None,
- default_f64: 42.0,
- just_bool: false,
- maybe_bool: None,
- default_bool: true,
- just_enum: OptionalByte::None,
- maybe_enum: None,
- default_enum: OptionalByte::One,
- }
- }
-}
-pub struct ScalarStuffBuilder<'a: 'b, 'b> {
- fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
- start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
-}
-impl<'a: 'b, 'b> ScalarStuffBuilder<'a, 'b> {
- #[inline]
- pub fn add_just_i8(&mut self, just_i8: i8) {
- self.fbb_.push_slot::<i8>(ScalarStuff::VT_JUST_I8, just_i8, 0);
- }
- #[inline]
- pub fn add_maybe_i8(&mut self, maybe_i8: i8) {
- self.fbb_.push_slot_always::<i8>(ScalarStuff::VT_MAYBE_I8, maybe_i8);
- }
- #[inline]
- pub fn add_default_i8(&mut self, default_i8: i8) {
- self.fbb_.push_slot::<i8>(ScalarStuff::VT_DEFAULT_I8, default_i8, 42);
- }
- #[inline]
- pub fn add_just_u8(&mut self, just_u8: u8) {
- self.fbb_.push_slot::<u8>(ScalarStuff::VT_JUST_U8, just_u8, 0);
- }
- #[inline]
- pub fn add_maybe_u8(&mut self, maybe_u8: u8) {
- self.fbb_.push_slot_always::<u8>(ScalarStuff::VT_MAYBE_U8, maybe_u8);
- }
- #[inline]
- pub fn add_default_u8(&mut self, default_u8: u8) {
- self.fbb_.push_slot::<u8>(ScalarStuff::VT_DEFAULT_U8, default_u8, 42);
- }
- #[inline]
- pub fn add_just_i16(&mut self, just_i16: i16) {
- self.fbb_.push_slot::<i16>(ScalarStuff::VT_JUST_I16, just_i16, 0);
- }
- #[inline]
- pub fn add_maybe_i16(&mut self, maybe_i16: i16) {
- self.fbb_.push_slot_always::<i16>(ScalarStuff::VT_MAYBE_I16, maybe_i16);
- }
- #[inline]
- pub fn add_default_i16(&mut self, default_i16: i16) {
- self.fbb_.push_slot::<i16>(ScalarStuff::VT_DEFAULT_I16, default_i16, 42);
- }
- #[inline]
- pub fn add_just_u16(&mut self, just_u16: u16) {
- self.fbb_.push_slot::<u16>(ScalarStuff::VT_JUST_U16, just_u16, 0);
- }
- #[inline]
- pub fn add_maybe_u16(&mut self, maybe_u16: u16) {
- self.fbb_.push_slot_always::<u16>(ScalarStuff::VT_MAYBE_U16, maybe_u16);
- }
- #[inline]
- pub fn add_default_u16(&mut self, default_u16: u16) {
- self.fbb_.push_slot::<u16>(ScalarStuff::VT_DEFAULT_U16, default_u16, 42);
- }
- #[inline]
- pub fn add_just_i32(&mut self, just_i32: i32) {
- self.fbb_.push_slot::<i32>(ScalarStuff::VT_JUST_I32, just_i32, 0);
- }
- #[inline]
- pub fn add_maybe_i32(&mut self, maybe_i32: i32) {
- self.fbb_.push_slot_always::<i32>(ScalarStuff::VT_MAYBE_I32, maybe_i32);
- }
- #[inline]
- pub fn add_default_i32(&mut self, default_i32: i32) {
- self.fbb_.push_slot::<i32>(ScalarStuff::VT_DEFAULT_I32, default_i32, 42);
- }
- #[inline]
- pub fn add_just_u32(&mut self, just_u32: u32) {
- self.fbb_.push_slot::<u32>(ScalarStuff::VT_JUST_U32, just_u32, 0);
- }
- #[inline]
- pub fn add_maybe_u32(&mut self, maybe_u32: u32) {
- self.fbb_.push_slot_always::<u32>(ScalarStuff::VT_MAYBE_U32, maybe_u32);
- }
- #[inline]
- pub fn add_default_u32(&mut self, default_u32: u32) {
- self.fbb_.push_slot::<u32>(ScalarStuff::VT_DEFAULT_U32, default_u32, 42);
- }
- #[inline]
- pub fn add_just_i64(&mut self, just_i64: i64) {
- self.fbb_.push_slot::<i64>(ScalarStuff::VT_JUST_I64, just_i64, 0);
- }
- #[inline]
- pub fn add_maybe_i64(&mut self, maybe_i64: i64) {
- self.fbb_.push_slot_always::<i64>(ScalarStuff::VT_MAYBE_I64, maybe_i64);
- }
- #[inline]
- pub fn add_default_i64(&mut self, default_i64: i64) {
- self.fbb_.push_slot::<i64>(ScalarStuff::VT_DEFAULT_I64, default_i64, 42);
- }
- #[inline]
- pub fn add_just_u64(&mut self, just_u64: u64) {
- self.fbb_.push_slot::<u64>(ScalarStuff::VT_JUST_U64, just_u64, 0);
- }
- #[inline]
- pub fn add_maybe_u64(&mut self, maybe_u64: u64) {
- self.fbb_.push_slot_always::<u64>(ScalarStuff::VT_MAYBE_U64, maybe_u64);
- }
- #[inline]
- pub fn add_default_u64(&mut self, default_u64: u64) {
- self.fbb_.push_slot::<u64>(ScalarStuff::VT_DEFAULT_U64, default_u64, 42);
- }
- #[inline]
- pub fn add_just_f32(&mut self, just_f32: f32) {
- self.fbb_.push_slot::<f32>(ScalarStuff::VT_JUST_F32, just_f32, 0.0);
- }
- #[inline]
- pub fn add_maybe_f32(&mut self, maybe_f32: f32) {
- self.fbb_.push_slot_always::<f32>(ScalarStuff::VT_MAYBE_F32, maybe_f32);
- }
- #[inline]
- pub fn add_default_f32(&mut self, default_f32: f32) {
- self.fbb_.push_slot::<f32>(ScalarStuff::VT_DEFAULT_F32, default_f32, 42.0);
- }
- #[inline]
- pub fn add_just_f64(&mut self, just_f64: f64) {
- self.fbb_.push_slot::<f64>(ScalarStuff::VT_JUST_F64, just_f64, 0.0);
- }
- #[inline]
- pub fn add_maybe_f64(&mut self, maybe_f64: f64) {
- self.fbb_.push_slot_always::<f64>(ScalarStuff::VT_MAYBE_F64, maybe_f64);
- }
- #[inline]
- pub fn add_default_f64(&mut self, default_f64: f64) {
- self.fbb_.push_slot::<f64>(ScalarStuff::VT_DEFAULT_F64, default_f64, 42.0);
- }
- #[inline]
- pub fn add_just_bool(&mut self, just_bool: bool) {
- self.fbb_.push_slot::<bool>(ScalarStuff::VT_JUST_BOOL, just_bool, false);
- }
- #[inline]
- pub fn add_maybe_bool(&mut self, maybe_bool: bool) {
- self.fbb_.push_slot_always::<bool>(ScalarStuff::VT_MAYBE_BOOL, maybe_bool);
- }
- #[inline]
- pub fn add_default_bool(&mut self, default_bool: bool) {
- self.fbb_.push_slot::<bool>(ScalarStuff::VT_DEFAULT_BOOL, default_bool, true);
- }
- #[inline]
- pub fn add_just_enum(&mut self, just_enum: OptionalByte) {
- self.fbb_.push_slot::<OptionalByte>(ScalarStuff::VT_JUST_ENUM, just_enum, OptionalByte::None);
- }
- #[inline]
- pub fn add_maybe_enum(&mut self, maybe_enum: OptionalByte) {
- self.fbb_.push_slot_always::<OptionalByte>(ScalarStuff::VT_MAYBE_ENUM, maybe_enum);
- }
- #[inline]
- pub fn add_default_enum(&mut self, default_enum: OptionalByte) {
- self.fbb_.push_slot::<OptionalByte>(ScalarStuff::VT_DEFAULT_ENUM, default_enum, OptionalByte::One);
- }
- #[inline]
- pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> ScalarStuffBuilder<'a, 'b> {
- let start = _fbb.start_table();
- ScalarStuffBuilder {
- fbb_: _fbb,
- start_: start,
- }
- }
- #[inline]
- pub fn finish(self) -> flatbuffers::WIPOffset<ScalarStuff<'a>> {
- let o = self.fbb_.end_table(self.start_);
- flatbuffers::WIPOffset::new(o.value())
- }
-}
-
-impl std::fmt::Debug for ScalarStuff<'_> {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- let mut ds = f.debug_struct("ScalarStuff");
- ds.field("just_i8", &self.just_i8());
- ds.field("maybe_i8", &self.maybe_i8());
- ds.field("default_i8", &self.default_i8());
- ds.field("just_u8", &self.just_u8());
- ds.field("maybe_u8", &self.maybe_u8());
- ds.field("default_u8", &self.default_u8());
- ds.field("just_i16", &self.just_i16());
- ds.field("maybe_i16", &self.maybe_i16());
- ds.field("default_i16", &self.default_i16());
- ds.field("just_u16", &self.just_u16());
- ds.field("maybe_u16", &self.maybe_u16());
- ds.field("default_u16", &self.default_u16());
- ds.field("just_i32", &self.just_i32());
- ds.field("maybe_i32", &self.maybe_i32());
- ds.field("default_i32", &self.default_i32());
- ds.field("just_u32", &self.just_u32());
- ds.field("maybe_u32", &self.maybe_u32());
- ds.field("default_u32", &self.default_u32());
- ds.field("just_i64", &self.just_i64());
- ds.field("maybe_i64", &self.maybe_i64());
- ds.field("default_i64", &self.default_i64());
- ds.field("just_u64", &self.just_u64());
- ds.field("maybe_u64", &self.maybe_u64());
- ds.field("default_u64", &self.default_u64());
- ds.field("just_f32", &self.just_f32());
- ds.field("maybe_f32", &self.maybe_f32());
- ds.field("default_f32", &self.default_f32());
- ds.field("just_f64", &self.just_f64());
- ds.field("maybe_f64", &self.maybe_f64());
- ds.field("default_f64", &self.default_f64());
- ds.field("just_bool", &self.just_bool());
- ds.field("maybe_bool", &self.maybe_bool());
- ds.field("default_bool", &self.default_bool());
- ds.field("just_enum", &self.just_enum());
- ds.field("maybe_enum", &self.maybe_enum());
- ds.field("default_enum", &self.default_enum());
- ds.finish()
- }
-}
-#[inline]
-pub fn get_root_as_scalar_stuff<'a>(buf: &'a [u8]) -> ScalarStuff<'a> {
- flatbuffers::get_root::<ScalarStuff<'a>>(buf)
-}
-
-#[inline]
-pub fn get_size_prefixed_root_as_scalar_stuff<'a>(buf: &'a [u8]) -> ScalarStuff<'a> {
- flatbuffers::get_size_prefixed_root::<ScalarStuff<'a>>(buf)
-}
-
-pub const SCALAR_STUFF_IDENTIFIER: &str = "NULL";
-
-#[inline]
-pub fn scalar_stuff_buffer_has_identifier(buf: &[u8]) -> bool {
- flatbuffers::buffer_has_identifier(buf, SCALAR_STUFF_IDENTIFIER, false)
-}
-
-#[inline]
-pub fn scalar_stuff_size_prefixed_buffer_has_identifier(buf: &[u8]) -> bool {
- flatbuffers::buffer_has_identifier(buf, SCALAR_STUFF_IDENTIFIER, true)
-}
-
-pub const SCALAR_STUFF_EXTENSION: &str = "mon";
-
-#[inline]
-pub fn finish_scalar_stuff_buffer<'a, 'b>(
- fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,
- root: flatbuffers::WIPOffset<ScalarStuff<'a>>) {
- fbb.finish(root, Some(SCALAR_STUFF_IDENTIFIER));
-}
-
-#[inline]
-pub fn finish_size_prefixed_scalar_stuff_buffer<'a, 'b>(fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>, root: flatbuffers::WIPOffset<ScalarStuff<'a>>) {
- fbb.finish_size_prefixed(root, Some(SCALAR_STUFF_IDENTIFIER));
-}
-} // pub mod optional_scalars
-
diff --git a/tests/optional_scalars_generated.ts b/tests/optional_scalars_generated.ts
deleted file mode 100644
index 668da8b..0000000
--- a/tests/optional_scalars_generated.ts
+++ /dev/null
@@ -1,722 +0,0 @@
-// automatically generated by the FlatBuffers compiler, do not modify
-
-import * as flatbuffers from 'flatbuffers';
-/**
- * @enum {number}
- */
-export namespace optional_scalars{
-export enum OptionalByte{
- None= 0,
- One= 1,
- Two= 2
-};
-}
-
-/**
- * @constructor
- */
-export namespace optional_scalars{
-export class ScalarStuff {
- bb: flatbuffers.ByteBuffer|null = null;
-
- bb_pos:number = 0;
-/**
- * @param number i
- * @param flatbuffers.ByteBuffer bb
- * @returns ScalarStuff
- */
-__init(i:number, bb:flatbuffers.ByteBuffer):ScalarStuff {
- this.bb_pos = i;
- this.bb = bb;
- return this;
-};
-
-/**
- * @param flatbuffers.ByteBuffer bb
- * @param ScalarStuff= obj
- * @returns ScalarStuff
- */
-static getRootAsScalarStuff(bb:flatbuffers.ByteBuffer, obj?:ScalarStuff):ScalarStuff {
- return (obj || new ScalarStuff()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param flatbuffers.ByteBuffer bb
- * @param ScalarStuff= obj
- * @returns ScalarStuff
- */
-static getSizePrefixedRootAsScalarStuff(bb:flatbuffers.ByteBuffer, obj?:ScalarStuff):ScalarStuff {
- bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
- return (obj || new ScalarStuff()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param flatbuffers.ByteBuffer bb
- * @returns boolean
- */
-static bufferHasIdentifier(bb:flatbuffers.ByteBuffer):boolean {
- return bb.__has_identifier('NULL');
-};
-
-/**
- * @returns number
- */
-justI8():number {
- var offset = this.bb!.__offset(this.bb_pos, 4);
- return offset ? this.bb!.readInt8(this.bb_pos + offset) : 0;
-};
-
-/**
- * @returns number|null
- */
-maybeI8():number|null {
- var offset = this.bb!.__offset(this.bb_pos, 6);
- return offset ? this.bb!.readInt8(this.bb_pos + offset) : null;
-};
-
-/**
- * @returns number
- */
-defaultI8():number {
- var offset = this.bb!.__offset(this.bb_pos, 8);
- return offset ? this.bb!.readInt8(this.bb_pos + offset) : 42;
-};
-
-/**
- * @returns number
- */
-justU8():number {
- var offset = this.bb!.__offset(this.bb_pos, 10);
- return offset ? this.bb!.readUint8(this.bb_pos + offset) : 0;
-};
-
-/**
- * @returns number|null
- */
-maybeU8():number|null {
- var offset = this.bb!.__offset(this.bb_pos, 12);
- return offset ? this.bb!.readUint8(this.bb_pos + offset) : null;
-};
-
-/**
- * @returns number
- */
-defaultU8():number {
- var offset = this.bb!.__offset(this.bb_pos, 14);
- return offset ? this.bb!.readUint8(this.bb_pos + offset) : 42;
-};
-
-/**
- * @returns number
- */
-justI16():number {
- var offset = this.bb!.__offset(this.bb_pos, 16);
- return offset ? this.bb!.readInt16(this.bb_pos + offset) : 0;
-};
-
-/**
- * @returns number|null
- */
-maybeI16():number|null {
- var offset = this.bb!.__offset(this.bb_pos, 18);
- return offset ? this.bb!.readInt16(this.bb_pos + offset) : null;
-};
-
-/**
- * @returns number
- */
-defaultI16():number {
- var offset = this.bb!.__offset(this.bb_pos, 20);
- return offset ? this.bb!.readInt16(this.bb_pos + offset) : 42;
-};
-
-/**
- * @returns number
- */
-justU16():number {
- var offset = this.bb!.__offset(this.bb_pos, 22);
- return offset ? this.bb!.readUint16(this.bb_pos + offset) : 0;
-};
-
-/**
- * @returns number|null
- */
-maybeU16():number|null {
- var offset = this.bb!.__offset(this.bb_pos, 24);
- return offset ? this.bb!.readUint16(this.bb_pos + offset) : null;
-};
-
-/**
- * @returns number
- */
-defaultU16():number {
- var offset = this.bb!.__offset(this.bb_pos, 26);
- return offset ? this.bb!.readUint16(this.bb_pos + offset) : 42;
-};
-
-/**
- * @returns number
- */
-justI32():number {
- var offset = this.bb!.__offset(this.bb_pos, 28);
- return offset ? this.bb!.readInt32(this.bb_pos + offset) : 0;
-};
-
-/**
- * @returns number|null
- */
-maybeI32():number|null {
- var offset = this.bb!.__offset(this.bb_pos, 30);
- return offset ? this.bb!.readInt32(this.bb_pos + offset) : null;
-};
-
-/**
- * @returns number
- */
-defaultI32():number {
- var offset = this.bb!.__offset(this.bb_pos, 32);
- return offset ? this.bb!.readInt32(this.bb_pos + offset) : 42;
-};
-
-/**
- * @returns number
- */
-justU32():number {
- var offset = this.bb!.__offset(this.bb_pos, 34);
- return offset ? this.bb!.readUint32(this.bb_pos + offset) : 0;
-};
-
-/**
- * @returns number|null
- */
-maybeU32():number|null {
- var offset = this.bb!.__offset(this.bb_pos, 36);
- return offset ? this.bb!.readUint32(this.bb_pos + offset) : null;
-};
-
-/**
- * @returns number
- */
-defaultU32():number {
- var offset = this.bb!.__offset(this.bb_pos, 38);
- return offset ? this.bb!.readUint32(this.bb_pos + offset) : 42;
-};
-
-/**
- * @returns flatbuffers.Long
- */
-justI64():flatbuffers.Long {
- var offset = this.bb!.__offset(this.bb_pos, 40);
- return offset ? this.bb!.readInt64(this.bb_pos + offset) : this.bb!.createLong(0, 0);
-};
-
-/**
- * @returns flatbuffers.Long|null
- */
-maybeI64():flatbuffers.Long|null {
- var offset = this.bb!.__offset(this.bb_pos, 42);
- return offset ? this.bb!.readInt64(this.bb_pos + offset) : null;
-};
-
-/**
- * @returns flatbuffers.Long
- */
-defaultI64():flatbuffers.Long {
- var offset = this.bb!.__offset(this.bb_pos, 44);
- return offset ? this.bb!.readInt64(this.bb_pos + offset) : this.bb!.createLong(42, 0);
-};
-
-/**
- * @returns flatbuffers.Long
- */
-justU64():flatbuffers.Long {
- var offset = this.bb!.__offset(this.bb_pos, 46);
- return offset ? this.bb!.readUint64(this.bb_pos + offset) : this.bb!.createLong(0, 0);
-};
-
-/**
- * @returns flatbuffers.Long|null
- */
-maybeU64():flatbuffers.Long|null {
- var offset = this.bb!.__offset(this.bb_pos, 48);
- return offset ? this.bb!.readUint64(this.bb_pos + offset) : null;
-};
-
-/**
- * @returns flatbuffers.Long
- */
-defaultU64():flatbuffers.Long {
- var offset = this.bb!.__offset(this.bb_pos, 50);
- return offset ? this.bb!.readUint64(this.bb_pos + offset) : this.bb!.createLong(42, 0);
-};
-
-/**
- * @returns number
- */
-justF32():number {
- var offset = this.bb!.__offset(this.bb_pos, 52);
- return offset ? this.bb!.readFloat32(this.bb_pos + offset) : 0.0;
-};
-
-/**
- * @returns number|null
- */
-maybeF32():number|null {
- var offset = this.bb!.__offset(this.bb_pos, 54);
- return offset ? this.bb!.readFloat32(this.bb_pos + offset) : null;
-};
-
-/**
- * @returns number
- */
-defaultF32():number {
- var offset = this.bb!.__offset(this.bb_pos, 56);
- return offset ? this.bb!.readFloat32(this.bb_pos + offset) : 42.0;
-};
-
-/**
- * @returns number
- */
-justF64():number {
- var offset = this.bb!.__offset(this.bb_pos, 58);
- return offset ? this.bb!.readFloat64(this.bb_pos + offset) : 0.0;
-};
-
-/**
- * @returns number|null
- */
-maybeF64():number|null {
- var offset = this.bb!.__offset(this.bb_pos, 60);
- return offset ? this.bb!.readFloat64(this.bb_pos + offset) : null;
-};
-
-/**
- * @returns number
- */
-defaultF64():number {
- var offset = this.bb!.__offset(this.bb_pos, 62);
- return offset ? this.bb!.readFloat64(this.bb_pos + offset) : 42.0;
-};
-
-/**
- * @returns boolean
- */
-justBool():boolean {
- var offset = this.bb!.__offset(this.bb_pos, 64);
- return offset ? !!this.bb!.readInt8(this.bb_pos + offset) : false;
-};
-
-/**
- * @returns boolean|null
- */
-maybeBool():boolean|null {
- var offset = this.bb!.__offset(this.bb_pos, 66);
- return offset ? !!this.bb!.readInt8(this.bb_pos + offset) : null;
-};
-
-/**
- * @returns boolean
- */
-defaultBool():boolean {
- var offset = this.bb!.__offset(this.bb_pos, 68);
- return offset ? !!this.bb!.readInt8(this.bb_pos + offset) : true;
-};
-
-/**
- * @returns optional_scalars.OptionalByte
- */
-justEnum():optional_scalars.OptionalByte {
- var offset = this.bb!.__offset(this.bb_pos, 70);
- return offset ? /** */ (this.bb!.readInt8(this.bb_pos + offset)) : optional_scalars.OptionalByte.None;
-};
-
-/**
- * @returns optional_scalars.OptionalByte|null
- */
-maybeEnum():optional_scalars.OptionalByte|null {
- var offset = this.bb!.__offset(this.bb_pos, 72);
- return offset ? /** */ (this.bb!.readInt8(this.bb_pos + offset)) : null;
-};
-
-/**
- * @returns optional_scalars.OptionalByte
- */
-defaultEnum():optional_scalars.OptionalByte {
- var offset = this.bb!.__offset(this.bb_pos, 74);
- return offset ? /** */ (this.bb!.readInt8(this.bb_pos + offset)) : optional_scalars.OptionalByte.One;
-};
-
-/**
- * @param flatbuffers.Builder builder
- */
-static startScalarStuff(builder:flatbuffers.Builder) {
- builder.startObject(36);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number justI8
- */
-static addJustI8(builder:flatbuffers.Builder, justI8:number) {
- builder.addFieldInt8(0, justI8, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number maybeI8
- */
-static addMaybeI8(builder:flatbuffers.Builder, maybeI8:number) {
- builder.addFieldInt8(1, maybeI8, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number defaultI8
- */
-static addDefaultI8(builder:flatbuffers.Builder, defaultI8:number) {
- builder.addFieldInt8(2, defaultI8, 42);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number justU8
- */
-static addJustU8(builder:flatbuffers.Builder, justU8:number) {
- builder.addFieldInt8(3, justU8, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number maybeU8
- */
-static addMaybeU8(builder:flatbuffers.Builder, maybeU8:number) {
- builder.addFieldInt8(4, maybeU8, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number defaultU8
- */
-static addDefaultU8(builder:flatbuffers.Builder, defaultU8:number) {
- builder.addFieldInt8(5, defaultU8, 42);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number justI16
- */
-static addJustI16(builder:flatbuffers.Builder, justI16:number) {
- builder.addFieldInt16(6, justI16, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number maybeI16
- */
-static addMaybeI16(builder:flatbuffers.Builder, maybeI16:number) {
- builder.addFieldInt16(7, maybeI16, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number defaultI16
- */
-static addDefaultI16(builder:flatbuffers.Builder, defaultI16:number) {
- builder.addFieldInt16(8, defaultI16, 42);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number justU16
- */
-static addJustU16(builder:flatbuffers.Builder, justU16:number) {
- builder.addFieldInt16(9, justU16, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number maybeU16
- */
-static addMaybeU16(builder:flatbuffers.Builder, maybeU16:number) {
- builder.addFieldInt16(10, maybeU16, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number defaultU16
- */
-static addDefaultU16(builder:flatbuffers.Builder, defaultU16:number) {
- builder.addFieldInt16(11, defaultU16, 42);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number justI32
- */
-static addJustI32(builder:flatbuffers.Builder, justI32:number) {
- builder.addFieldInt32(12, justI32, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number maybeI32
- */
-static addMaybeI32(builder:flatbuffers.Builder, maybeI32:number) {
- builder.addFieldInt32(13, maybeI32, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number defaultI32
- */
-static addDefaultI32(builder:flatbuffers.Builder, defaultI32:number) {
- builder.addFieldInt32(14, defaultI32, 42);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number justU32
- */
-static addJustU32(builder:flatbuffers.Builder, justU32:number) {
- builder.addFieldInt32(15, justU32, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number maybeU32
- */
-static addMaybeU32(builder:flatbuffers.Builder, maybeU32:number) {
- builder.addFieldInt32(16, maybeU32, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number defaultU32
- */
-static addDefaultU32(builder:flatbuffers.Builder, defaultU32:number) {
- builder.addFieldInt32(17, defaultU32, 42);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Long justI64
- */
-static addJustI64(builder:flatbuffers.Builder, justI64:flatbuffers.Long) {
- builder.addFieldInt64(18, justI64, builder.createLong(0, 0));
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Long maybeI64
- */
-static addMaybeI64(builder:flatbuffers.Builder, maybeI64:flatbuffers.Long) {
- builder.addFieldInt64(19, maybeI64, builder.createLong(0, 0));
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Long defaultI64
- */
-static addDefaultI64(builder:flatbuffers.Builder, defaultI64:flatbuffers.Long) {
- builder.addFieldInt64(20, defaultI64, builder.createLong(42, 0));
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Long justU64
- */
-static addJustU64(builder:flatbuffers.Builder, justU64:flatbuffers.Long) {
- builder.addFieldInt64(21, justU64, builder.createLong(0, 0));
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Long maybeU64
- */
-static addMaybeU64(builder:flatbuffers.Builder, maybeU64:flatbuffers.Long) {
- builder.addFieldInt64(22, maybeU64, builder.createLong(0, 0));
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Long defaultU64
- */
-static addDefaultU64(builder:flatbuffers.Builder, defaultU64:flatbuffers.Long) {
- builder.addFieldInt64(23, defaultU64, builder.createLong(42, 0));
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number justF32
- */
-static addJustF32(builder:flatbuffers.Builder, justF32:number) {
- builder.addFieldFloat32(24, justF32, 0.0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number maybeF32
- */
-static addMaybeF32(builder:flatbuffers.Builder, maybeF32:number) {
- builder.addFieldFloat32(25, maybeF32, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number defaultF32
- */
-static addDefaultF32(builder:flatbuffers.Builder, defaultF32:number) {
- builder.addFieldFloat32(26, defaultF32, 42.0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number justF64
- */
-static addJustF64(builder:flatbuffers.Builder, justF64:number) {
- builder.addFieldFloat64(27, justF64, 0.0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number maybeF64
- */
-static addMaybeF64(builder:flatbuffers.Builder, maybeF64:number) {
- builder.addFieldFloat64(28, maybeF64, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number defaultF64
- */
-static addDefaultF64(builder:flatbuffers.Builder, defaultF64:number) {
- builder.addFieldFloat64(29, defaultF64, 42.0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param boolean justBool
- */
-static addJustBool(builder:flatbuffers.Builder, justBool:boolean) {
- builder.addFieldInt8(30, +justBool, +false);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param boolean maybeBool
- */
-static addMaybeBool(builder:flatbuffers.Builder, maybeBool:boolean) {
- builder.addFieldInt8(31, +maybeBool, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param boolean defaultBool
- */
-static addDefaultBool(builder:flatbuffers.Builder, defaultBool:boolean) {
- builder.addFieldInt8(32, +defaultBool, +true);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param optional_scalars.OptionalByte justEnum
- */
-static addJustEnum(builder:flatbuffers.Builder, justEnum:optional_scalars.OptionalByte) {
- builder.addFieldInt8(33, justEnum, optional_scalars.OptionalByte.None);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param optional_scalars.OptionalByte maybeEnum
- */
-static addMaybeEnum(builder:flatbuffers.Builder, maybeEnum:optional_scalars.OptionalByte) {
- builder.addFieldInt8(34, maybeEnum, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param optional_scalars.OptionalByte defaultEnum
- */
-static addDefaultEnum(builder:flatbuffers.Builder, defaultEnum:optional_scalars.OptionalByte) {
- builder.addFieldInt8(35, defaultEnum, optional_scalars.OptionalByte.One);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @returns flatbuffers.Offset
- */
-static endScalarStuff(builder:flatbuffers.Builder):flatbuffers.Offset {
- var offset = builder.endObject();
- return offset;
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Offset offset
- */
-static finishScalarStuffBuffer(builder:flatbuffers.Builder, offset:flatbuffers.Offset) {
- builder.finish(offset, 'NULL');
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Offset offset
- */
-static finishSizePrefixedScalarStuffBuffer(builder:flatbuffers.Builder, offset:flatbuffers.Offset) {
- builder.finish(offset, 'NULL', true);
-};
-
-static createScalarStuff(builder:flatbuffers.Builder, justI8:number, maybeI8:number|null, defaultI8:number, justU8:number, maybeU8:number|null, defaultU8:number, justI16:number, maybeI16:number|null, defaultI16:number, justU16:number, maybeU16:number|null, defaultU16:number, justI32:number, maybeI32:number|null, defaultI32:number, justU32:number, maybeU32:number|null, defaultU32:number, justI64:flatbuffers.Long, maybeI64:flatbuffers.Long|null, defaultI64:flatbuffers.Long, justU64:flatbuffers.Long, maybeU64:flatbuffers.Long|null, defaultU64:flatbuffers.Long, justF32:number, maybeF32:number|null, defaultF32:number, justF64:number, maybeF64:number|null, defaultF64:number, justBool:boolean, maybeBool:boolean|null, defaultBool:boolean, justEnum:optional_scalars.OptionalByte, maybeEnum:optional_scalars.OptionalByte|null, defaultEnum:optional_scalars.OptionalByte):flatbuffers.Offset {
- ScalarStuff.startScalarStuff(builder);
- ScalarStuff.addJustI8(builder, justI8);
- if (maybeI8 !== null)
- ScalarStuff.addMaybeI8(builder, maybeI8);
- ScalarStuff.addDefaultI8(builder, defaultI8);
- ScalarStuff.addJustU8(builder, justU8);
- if (maybeU8 !== null)
- ScalarStuff.addMaybeU8(builder, maybeU8);
- ScalarStuff.addDefaultU8(builder, defaultU8);
- ScalarStuff.addJustI16(builder, justI16);
- if (maybeI16 !== null)
- ScalarStuff.addMaybeI16(builder, maybeI16);
- ScalarStuff.addDefaultI16(builder, defaultI16);
- ScalarStuff.addJustU16(builder, justU16);
- if (maybeU16 !== null)
- ScalarStuff.addMaybeU16(builder, maybeU16);
- ScalarStuff.addDefaultU16(builder, defaultU16);
- ScalarStuff.addJustI32(builder, justI32);
- if (maybeI32 !== null)
- ScalarStuff.addMaybeI32(builder, maybeI32);
- ScalarStuff.addDefaultI32(builder, defaultI32);
- ScalarStuff.addJustU32(builder, justU32);
- if (maybeU32 !== null)
- ScalarStuff.addMaybeU32(builder, maybeU32);
- ScalarStuff.addDefaultU32(builder, defaultU32);
- ScalarStuff.addJustI64(builder, justI64);
- if (maybeI64 !== null)
- ScalarStuff.addMaybeI64(builder, maybeI64);
- ScalarStuff.addDefaultI64(builder, defaultI64);
- ScalarStuff.addJustU64(builder, justU64);
- if (maybeU64 !== null)
- ScalarStuff.addMaybeU64(builder, maybeU64);
- ScalarStuff.addDefaultU64(builder, defaultU64);
- ScalarStuff.addJustF32(builder, justF32);
- if (maybeF32 !== null)
- ScalarStuff.addMaybeF32(builder, maybeF32);
- ScalarStuff.addDefaultF32(builder, defaultF32);
- ScalarStuff.addJustF64(builder, justF64);
- if (maybeF64 !== null)
- ScalarStuff.addMaybeF64(builder, maybeF64);
- ScalarStuff.addDefaultF64(builder, defaultF64);
- ScalarStuff.addJustBool(builder, justBool);
- if (maybeBool !== null)
- ScalarStuff.addMaybeBool(builder, maybeBool);
- ScalarStuff.addDefaultBool(builder, defaultBool);
- ScalarStuff.addJustEnum(builder, justEnum);
- if (maybeEnum !== null)
- ScalarStuff.addMaybeEnum(builder, maybeEnum);
- ScalarStuff.addDefaultEnum(builder, defaultEnum);
- return ScalarStuff.endScalarStuff(builder);
-}
-}
-}
diff --git a/tests/package.json b/tests/package.json
new file mode 100644
index 0000000..654e57f
--- /dev/null
+++ b/tests/package.json
@@ -0,0 +1,7 @@
+{
+ "dependencies": {
+ "esm": "^3.2.25",
+ "flatbuffers": "../",
+ "grpc": "^1.24.6"
+ }
+}
diff --git a/tests/prototest/test.golden b/tests/prototest/test.golden
index cf861b9..eb10671 100644
--- a/tests/prototest/test.golden
+++ b/tests/prototest/test.golden
@@ -10,6 +10,17 @@
BAR = 5,
}
+namespace proto.test.ProtoMessage_.OtherMessage_;
+
+enum ProtoEnum : int {
+ NUL = 0,
+ FOO = 1,
+ BAR = 2,
+ BAZ = 3,
+}
+
+namespace proto.test;
+
table ImportedMessage {
a:int;
}
@@ -39,6 +50,7 @@
z:proto.test.ImportedMessage;
/// doc comment for r.
r:proto.test.ProtoMessage_.Anonymous0;
+ outer_enum:proto.test.ProtoEnum;
}
namespace proto.test.ProtoMessage_;
@@ -47,6 +59,7 @@
a:double;
/// doc comment for b.
b:float = 3.14149;
+ foo_bar_baz:proto.test.ProtoMessage_.OtherMessage_.ProtoEnum;
}
table Anonymous0 {
diff --git a/tests/prototest/test.proto b/tests/prototest/test.proto
index 45ce6c0..10e45af 100644
--- a/tests/prototest/test.proto
+++ b/tests/prototest/test.proto
@@ -27,6 +27,16 @@
optional double a = 26;
/// doc comment for b.
optional float b = 32 [default = 3.14149];
+
+ // Nested enum that aliases the outer one.
+ enum ProtoEnum {
+ NUL = 0;
+ FOO = 1;
+ BAR = 2;
+ BAZ = 3;
+ }
+
+ optional ProtoEnum foo_bar_baz = 33;
}
optional int32 c = 12 [default = 16];
optional int64 d = 1 [default = 0];
@@ -56,4 +66,5 @@
/// lines.
OtherMessage t = 18;
}
+ optional ProtoEnum outer_enum = 33;
}
diff --git a/tests/prototest/test_include.golden b/tests/prototest/test_include.golden
index 16b92ed..358c3f6 100644
--- a/tests/prototest/test_include.golden
+++ b/tests/prototest/test_include.golden
@@ -12,6 +12,17 @@
BAR = 5,
}
+namespace proto.test.ProtoMessage_.OtherMessage_;
+
+enum ProtoEnum : int {
+ NUL = 0,
+ FOO = 1,
+ BAR = 2,
+ BAZ = 3,
+}
+
+namespace proto.test;
+
/// 2nd table doc comment with
/// many lines.
table ProtoMessage {
@@ -37,6 +48,7 @@
z:proto.test.ImportedMessage;
/// doc comment for r.
r:proto.test.ProtoMessage_.Anonymous0;
+ outer_enum:proto.test.ProtoEnum;
}
namespace proto.test.ProtoMessage_;
@@ -45,6 +57,7 @@
a:double;
/// doc comment for b.
b:float = 3.14149;
+ foo_bar_baz:proto.test.ProtoMessage_.OtherMessage_.ProtoEnum;
}
table Anonymous0 {
diff --git a/tests/prototest/test_suffix.golden b/tests/prototest/test_suffix.golden
index 94ffd26..a99f807 100644
--- a/tests/prototest/test_suffix.golden
+++ b/tests/prototest/test_suffix.golden
@@ -10,6 +10,17 @@
BAR = 5,
}
+namespace proto.test.test_namespace_suffix.ProtoMessage_.OtherMessage_;
+
+enum ProtoEnum : int {
+ NUL = 0,
+ FOO = 1,
+ BAR = 2,
+ BAZ = 3,
+}
+
+namespace proto.test.test_namespace_suffix;
+
table ImportedMessage {
a:int;
}
@@ -39,6 +50,7 @@
z:proto.test.test_namespace_suffix.ImportedMessage;
/// doc comment for r.
r:proto.test.test_namespace_suffix.ProtoMessage_.Anonymous0;
+ outer_enum:proto.test.test_namespace_suffix.ProtoEnum;
}
namespace proto.test.test_namespace_suffix.ProtoMessage_;
@@ -47,6 +59,7 @@
a:double;
/// doc comment for b.
b:float = 3.14149;
+ foo_bar_baz:proto.test.test_namespace_suffix.ProtoMessage_.OtherMessage_.ProtoEnum;
}
table Anonymous0 {
diff --git a/tests/prototest/test_union.golden b/tests/prototest/test_union.golden
index 18270eb..3e6becd 100644
--- a/tests/prototest/test_union.golden
+++ b/tests/prototest/test_union.golden
@@ -10,6 +10,15 @@
BAR = 5,
}
+namespace proto.test.ProtoMessage_.OtherMessage_;
+
+enum ProtoEnum : int {
+ NUL = 0,
+ FOO = 1,
+ BAR = 2,
+ BAZ = 3,
+}
+
namespace proto.test.ProtoMessage_;
union RUnion {
@@ -51,6 +60,7 @@
z:proto.test.ImportedMessage;
/// doc comment for r.
r:proto.test.ProtoMessage_.RUnion;
+ outer_enum:proto.test.ProtoEnum;
}
namespace proto.test.ProtoMessage_;
@@ -59,5 +69,6 @@
a:double;
/// doc comment for b.
b:float = 3.14149;
+ foo_bar_baz:proto.test.ProtoMessage_.OtherMessage_.ProtoEnum;
}
diff --git a/tests/prototest/test_union_include.golden b/tests/prototest/test_union_include.golden
index 1ce3ac3..abdb6e2 100644
--- a/tests/prototest/test_union_include.golden
+++ b/tests/prototest/test_union_include.golden
@@ -12,6 +12,15 @@
BAR = 5,
}
+namespace proto.test.ProtoMessage_.OtherMessage_;
+
+enum ProtoEnum : int {
+ NUL = 0,
+ FOO = 1,
+ BAR = 2,
+ BAZ = 3,
+}
+
namespace proto.test.ProtoMessage_;
union RUnion {
@@ -49,6 +58,7 @@
z:proto.test.ImportedMessage;
/// doc comment for r.
r:proto.test.ProtoMessage_.RUnion;
+ outer_enum:proto.test.ProtoEnum;
}
namespace proto.test.ProtoMessage_;
@@ -57,5 +67,6 @@
a:double;
/// doc comment for b.
b:float = 3.14149;
+ foo_bar_baz:proto.test.ProtoMessage_.OtherMessage_.ProtoEnum;
}
diff --git a/tests/prototest/test_union_suffix.golden b/tests/prototest/test_union_suffix.golden
index 0b0f920..6a240c0 100644
--- a/tests/prototest/test_union_suffix.golden
+++ b/tests/prototest/test_union_suffix.golden
@@ -10,6 +10,15 @@
BAR = 5,
}
+namespace proto.test.test_namespace_suffix.ProtoMessage_.OtherMessage_;
+
+enum ProtoEnum : int {
+ NUL = 0,
+ FOO = 1,
+ BAR = 2,
+ BAZ = 3,
+}
+
namespace proto.test.test_namespace_suffix.ProtoMessage_;
union RUnion {
@@ -51,6 +60,7 @@
z:proto.test.test_namespace_suffix.ImportedMessage;
/// doc comment for r.
r:proto.test.test_namespace_suffix.ProtoMessage_.RUnion;
+ outer_enum:proto.test.test_namespace_suffix.ProtoEnum;
}
namespace proto.test.test_namespace_suffix.ProtoMessage_;
@@ -59,5 +69,6 @@
a:double;
/// doc comment for b.
b:float = 3.14149;
+ foo_bar_baz:proto.test.test_namespace_suffix.ProtoMessage_.OtherMessage_.ProtoEnum;
}
diff --git a/tests/py_test.py b/tests/py_test.py
index 9b31f60..ed966d5 100644
--- a/tests/py_test.py
+++ b/tests/py_test.py
@@ -42,1452 +42,1839 @@
import MyGame.Example.Stat # refers to generated code
import MyGame.Example.Vec3 # refers to generated code
import MyGame.MonsterExtra # refers to generated code
-import MyGame.InParentNamespace # refers to generated code
+import MyGame.InParentNamespace # refers to generated code
import MyGame.Example.ArrayTable # refers to generated code
import MyGame.Example.ArrayStruct # refers to generated code
import MyGame.Example.NestedStruct # refers to generated code
import MyGame.Example.TestEnum # refers to generated code
+import monster_test_generated # the one-file version
+
+
+def create_namespace_shortcut(is_onefile):
+ # Create shortcut from either the one-file format or the multi-file format
+ global _ANY
+ global _COLOR
+ global _MONSTER
+ global _TEST
+ global _STAT
+ global _VEC3
+ global _IN_PARENT_NAMESPACE
+ if is_onefile:
+ print('Testing with the one-file generated code')
+ _ANY = monster_test_generated
+ _COLOR = monster_test_generated
+ _MONSTER = monster_test_generated
+ _TEST = monster_test_generated
+ _STAT = monster_test_generated
+ _VEC3 = monster_test_generated
+ _IN_PARENT_NAMESPACE = monster_test_generated
+ else:
+ print('Testing with multi-file generated code')
+ _ANY = MyGame.Example.Any
+ _COLOR = MyGame.Example.Color
+ _MONSTER = MyGame.Example.Monster
+ _TEST = MyGame.Example.Test
+ _STAT = MyGame.Example.Stat
+ _VEC3 = MyGame.Example.Vec3
+ _IN_PARENT_NAMESPACE = MyGame.InParentNamespace
+
def assertRaises(test_case, fn, exception_class):
- ''' Backwards-compatible assertion for exceptions raised. '''
+ """ Backwards-compatible assertion for exceptions raised. """
- exc = None
- try:
- fn()
- except Exception as e:
- exc = e
- test_case.assertTrue(exc is not None)
- test_case.assertTrue(isinstance(exc, exception_class))
+ exc = None
+ try:
+ fn()
+ except Exception as e:
+ exc = e
+ test_case.assertTrue(exc is not None)
+ test_case.assertTrue(isinstance(exc, exception_class))
class TestWireFormat(unittest.TestCase):
- def test_wire_format(self):
- # Verify that using the generated Python code builds a buffer without
- # returning errors, and is interpreted correctly, for size prefixed
- # representation and regular:
- for sizePrefix in [True, False]:
- for file_identifier in [None, b"MONS"]:
- gen_buf, gen_off = make_monster_from_generated_code(sizePrefix=sizePrefix, file_identifier=file_identifier)
- CheckReadBuffer(gen_buf, gen_off, sizePrefix=sizePrefix, file_identifier=file_identifier)
- # Verify that the canonical flatbuffer file is readable by the
- # generated Python code. Note that context managers are not part of
- # Python 2.5, so we use the simpler open/close methods here:
- f = open('monsterdata_test.mon', 'rb')
- canonicalWireData = f.read()
- f.close()
- CheckReadBuffer(bytearray(canonicalWireData), 0, file_identifier=b'MONS')
+ def test_wire_format(self):
+ # Verify that using the generated Python code builds a buffer without
+ # returning errors, and is interpreted correctly, for size prefixed
+ # representation and regular:
+ for sizePrefix in [True, False]:
+ for file_identifier in [None, b'MONS']:
+ gen_buf, gen_off = make_monster_from_generated_code(
+ sizePrefix=sizePrefix, file_identifier=file_identifier)
+ CheckReadBuffer(
+ gen_buf,
+ gen_off,
+ sizePrefix=sizePrefix,
+ file_identifier=file_identifier)
- # Write the generated buffer out to a file:
- f = open('monsterdata_python_wire.mon', 'wb')
- f.write(gen_buf[gen_off:])
- f.close()
+ # Verify that the canonical flatbuffer file is readable by the
+ # generated Python code. Note that context managers are not part of
+ # Python 2.5, so we use the simpler open/close methods here:
+ f = open('monsterdata_test.mon', 'rb')
+ canonicalWireData = f.read()
+ f.close()
+ CheckReadBuffer(bytearray(canonicalWireData), 0, file_identifier=b'MONS')
+
+ # Write the generated buffer out to a file:
+ f = open('monsterdata_python_wire.mon', 'wb')
+ f.write(gen_buf[gen_off:])
+ f.close()
class TestObjectBasedAPI(unittest.TestCase):
- ''' Tests the generated object based API.'''
+ """ Tests the generated object based API."""
- def test_consistenty_with_repeated_pack_and_unpack(self):
- ''' Checks the serialization and deserialization between a buffer and
+ def test_consistenty_with_repeated_pack_and_unpack(self):
+ """ Checks the serialization and deserialization between a buffer and
+
its python object. It tests in the same way as the C++ object API test,
- ObjectFlatBuffersTest in test.cpp. '''
+ ObjectFlatBuffersTest in test.cpp.
+ """
- buf, off = make_monster_from_generated_code()
+ buf, off = make_monster_from_generated_code()
- # Turns a buffer into Python object (T class).
- monster1 = MyGame.Example.Monster.Monster.GetRootAsMonster(buf, off)
- monsterT1 = MyGame.Example.Monster.MonsterT.InitFromObj(monster1)
+ # Turns a buffer into Python object (T class).
+ monster1 = _MONSTER.Monster.GetRootAs(buf, off)
+ monsterT1 = _MONSTER.MonsterT.InitFromObj(monster1)
- for sizePrefix in [True, False]:
- # Re-serialize the data into a buffer.
- b1 = flatbuffers.Builder(0)
- if sizePrefix:
- b1.FinishSizePrefixed(monsterT1.Pack(b1))
- else:
- b1.Finish(monsterT1.Pack(b1))
- CheckReadBuffer(b1.Bytes, b1.Head(), sizePrefix)
+ for sizePrefix in [True, False]:
+ # Re-serialize the data into a buffer.
+ b1 = flatbuffers.Builder(0)
+ if sizePrefix:
+ b1.FinishSizePrefixed(monsterT1.Pack(b1))
+ else:
+ b1.Finish(monsterT1.Pack(b1))
+ CheckReadBuffer(b1.Bytes, b1.Head(), sizePrefix)
- # Deserializes the buffer into Python object again.
- monster2 = MyGame.Example.Monster.Monster.GetRootAsMonster(b1.Bytes,
- b1.Head())
- # Re-serializes the data into a buffer for one more time.
- monsterT2 = MyGame.Example.Monster.MonsterT.InitFromObj(monster2)
- for sizePrefix in [True, False]:
- # Re-serializes the data into a buffer
- b2 = flatbuffers.Builder(0)
- if sizePrefix:
- b2.FinishSizePrefixed(monsterT2.Pack(b2))
- else:
- b2.Finish(monsterT2.Pack(b2))
- CheckReadBuffer(b2.Bytes, b2.Head(), sizePrefix)
+ # Deserializes the buffer into Python object again.
+ monster2 = _MONSTER.Monster.GetRootAs(b1.Bytes, b1.Head())
+ # Re-serializes the data into a buffer for one more time.
+ monsterT2 = _MONSTER.MonsterT.InitFromObj(monster2)
+ for sizePrefix in [True, False]:
+ # Re-serializes the data into a buffer
+ b2 = flatbuffers.Builder(0)
+ if sizePrefix:
+ b2.FinishSizePrefixed(monsterT2.Pack(b2))
+ else:
+ b2.Finish(monsterT2.Pack(b2))
+ CheckReadBuffer(b2.Bytes, b2.Head(), sizePrefix)
- def test_default_values_with_pack_and_unpack(self):
- ''' Serializes and deserializes between a buffer with default values (no
+ def test_default_values_with_pack_and_unpack(self):
+ """ Serializes and deserializes between a buffer with default values (no
+
specific values are filled when the buffer is created) and its python
- object. '''
- # Creates a flatbuffer with default values.
- b1 = flatbuffers.Builder(0)
- MyGame.Example.Monster.MonsterStart(b1)
- gen_mon = MyGame.Example.Monster.MonsterEnd(b1)
- b1.Finish(gen_mon)
+ object.
+ """
+ # Creates a flatbuffer with default values.
+ b1 = flatbuffers.Builder(0)
+ _MONSTER.MonsterStart(b1)
+ gen_mon = _MONSTER.MonsterEnd(b1)
+ b1.Finish(gen_mon)
- # Converts the flatbuffer into the object class.
- monster1 = MyGame.Example.Monster.Monster.GetRootAsMonster(b1.Bytes,
- b1.Head())
- monsterT1 = MyGame.Example.Monster.MonsterT.InitFromObj(monster1)
+ # Converts the flatbuffer into the object class.
+ monster1 = _MONSTER.Monster.GetRootAs(b1.Bytes, b1.Head())
+ monsterT1 = _MONSTER.MonsterT.InitFromObj(monster1)
- # Packs the object class into another flatbuffer.
- b2 = flatbuffers.Builder(0)
- b2.Finish(monsterT1.Pack(b2))
- monster2 = MyGame.Example.Monster.Monster.GetRootAsMonster(b2.Bytes,
- b2.Head())
- # Checks the default values.
- self.assertTrue(monster2.Pos() is None)
- self.assertEqual(monster2.Mana(),150)
- self.assertEqual(monster2.Hp(), 100)
- self.assertTrue(monster2.Name() is None)
- self.assertEqual(monster2.Inventory(0), 0)
- self.assertEqual(monster2.InventoryAsNumpy(), 0)
- self.assertEqual(monster2.InventoryLength(), 0)
- self.assertTrue(monster2.InventoryIsNone())
- self.assertTrue(monster2.Color() is 8)
- self.assertEqual(monster2.TestType(), 0)
- self.assertTrue(monster2.Test() is None)
- self.assertTrue(monster2.Test4(0) is None)
- self.assertEqual(monster2.Test4Length(), 0)
- self.assertTrue(monster2.Test4IsNone())
- self.assertTrue(monster2.Testarrayofstring(0) is "")
- self.assertEqual(monster2.TestarrayofstringLength(), 0)
- self.assertTrue(monster2.TestarrayofstringIsNone())
- self.assertTrue(monster2.Testarrayoftables(0) is None)
- self.assertEqual(monster2.TestarrayoftablesLength(), 0)
- self.assertTrue(monster2.TestarrayoftablesIsNone())
- self.assertTrue(monster2.Enemy() is None)
- self.assertEqual(monster2.Testnestedflatbuffer(0), 0)
- self.assertEqual(monster2.TestnestedflatbufferAsNumpy(), 0)
- self.assertEqual(monster2.TestnestedflatbufferLength(), 0)
- self.assertTrue(monster2.TestnestedflatbufferIsNone())
- self.assertTrue(monster2.Testempty() is None)
- self.assertTrue(monster2.Testbool() is False)
- self.assertEqual(monster2.Testhashs32Fnv1(), 0)
- self.assertEqual(monster2.Testhashu32Fnv1(), 0)
- self.assertEqual(monster2.Testhashs64Fnv1(), 0)
- self.assertEqual(monster2.Testhashu64Fnv1(), 0)
- self.assertEqual(monster2.Testhashs32Fnv1a(), 0)
- self.assertEqual(monster2.Testhashu32Fnv1a(), 0)
- self.assertEqual(monster2.Testhashs64Fnv1a(), 0)
- self.assertEqual(monster2.Testhashu64Fnv1a(), 0)
- self.assertEqual(monster2.Testarrayofbools(0), 0)
- self.assertEqual(monster2.TestarrayofboolsAsNumpy(), 0)
- self.assertEqual(monster2.TestarrayofboolsLength(), 0)
- self.assertTrue(monster2.TestarrayofboolsIsNone())
- self.assertEqual(monster2.Testf(), 3.14159)
- self.assertEqual(monster2.Testf2(), 3.0)
- self.assertEqual(monster2.Testf3(), 0.0)
- self.assertTrue(monster2.Testarrayofstring2(0) is "")
- self.assertEqual(monster2.Testarrayofstring2Length(), 0)
- self.assertTrue(monster2.Testarrayofstring2IsNone())
- self.assertTrue(monster2.Testarrayofsortedstruct(0) is None)
- self.assertEqual(monster2.TestarrayofsortedstructLength(), 0)
- self.assertTrue(monster2.TestarrayofsortedstructIsNone())
- self.assertEqual(monster2.Flex(0), 0)
- self.assertEqual(monster2.FlexAsNumpy(), 0)
- self.assertEqual(monster2.FlexLength(), 0)
- self.assertTrue(monster2.FlexIsNone())
- self.assertTrue(monster2.Test5(0) is None)
- self.assertEqual(monster2.Test5Length(), 0)
- self.assertTrue(monster2.Test5IsNone())
- self.assertEqual(monster2.VectorOfLongs(0), 0)
- self.assertEqual(monster2.VectorOfLongsAsNumpy(), 0)
- self.assertEqual(monster2.VectorOfLongsLength(), 0)
- self.assertTrue(monster2.VectorOfLongsIsNone())
- self.assertEqual(monster2.VectorOfDoubles(0), 0)
- self.assertEqual(monster2.VectorOfDoublesAsNumpy(), 0)
- self.assertEqual(monster2.VectorOfDoublesLength(), 0)
- self.assertTrue(monster2.VectorOfDoublesIsNone())
- self.assertTrue(monster2.ParentNamespaceTest() is None)
- self.assertTrue(monster2.VectorOfReferrables(0) is None)
- self.assertEqual(monster2.VectorOfReferrablesLength(), 0)
- self.assertTrue(monster2.VectorOfReferrablesIsNone())
- self.assertEqual(monster2.SingleWeakReference(), 0)
- self.assertEqual(monster2.VectorOfWeakReferences(0), 0)
- self.assertEqual(monster2.VectorOfWeakReferencesAsNumpy(), 0)
- self.assertEqual(monster2.VectorOfWeakReferencesLength(), 0)
- self.assertTrue(monster2.VectorOfWeakReferencesIsNone())
- self.assertTrue(monster2.VectorOfStrongReferrables(0) is None)
- self.assertEqual(monster2.VectorOfStrongReferrablesLength(), 0)
- self.assertTrue(monster2.VectorOfStrongReferrablesIsNone())
- self.assertEqual(monster2.CoOwningReference(), 0)
- self.assertEqual(monster2.VectorOfCoOwningReferences(0), 0)
- self.assertEqual(monster2.VectorOfCoOwningReferencesAsNumpy(), 0)
- self.assertEqual(monster2.VectorOfCoOwningReferencesLength(), 0)
- self.assertTrue(monster2.VectorOfCoOwningReferencesIsNone())
- self.assertEqual(monster2.NonOwningReference(), 0)
- self.assertEqual(monster2.VectorOfNonOwningReferences(0), 0)
- self.assertEqual(monster2.VectorOfNonOwningReferencesAsNumpy(), 0)
- self.assertEqual(monster2.VectorOfNonOwningReferencesLength(), 0)
- self.assertTrue(monster2.VectorOfNonOwningReferencesIsNone())
- self.assertEqual(monster2.AnyUniqueType(), 0)
- self.assertTrue(monster2.AnyUnique() is None)
- self.assertEqual(monster2.AnyAmbiguousType(), 0)
- self.assertTrue(monster2.AnyAmbiguous() is None)
- self.assertEqual(monster2.VectorOfEnums(0), 0)
- self.assertEqual(monster2.VectorOfEnumsAsNumpy(), 0)
- self.assertEqual(monster2.VectorOfEnumsLength(), 0)
- self.assertTrue(monster2.VectorOfEnumsIsNone())
+ # Packs the object class into another flatbuffer.
+ b2 = flatbuffers.Builder(0)
+ b2.Finish(monsterT1.Pack(b2))
+ monster2 = _MONSTER.Monster.GetRootAs(b2.Bytes, b2.Head())
+ # Checks the default values.
+ self.assertTrue(monster2.Pos() is None)
+ self.assertEqual(monster2.Mana(), 150)
+ self.assertEqual(monster2.Hp(), 100)
+ self.assertTrue(monster2.Name() is None)
+ self.assertEqual(monster2.Inventory(0), 0)
+ self.assertEqual(monster2.InventoryAsNumpy(), 0)
+ self.assertEqual(monster2.InventoryLength(), 0)
+ self.assertTrue(monster2.InventoryIsNone())
+ self.assertTrue(monster2.Color() is 8)
+ self.assertEqual(monster2.TestType(), 0)
+ self.assertTrue(monster2.Test() is None)
+ self.assertTrue(monster2.Test4(0) is None)
+ self.assertEqual(monster2.Test4Length(), 0)
+ self.assertTrue(monster2.Test4IsNone())
+ self.assertTrue(monster2.Testarrayofstring(0) is '')
+ self.assertEqual(monster2.TestarrayofstringLength(), 0)
+ self.assertTrue(monster2.TestarrayofstringIsNone())
+ self.assertTrue(monster2.Testarrayoftables(0) is None)
+ self.assertEqual(monster2.TestarrayoftablesLength(), 0)
+ self.assertTrue(monster2.TestarrayoftablesIsNone())
+ self.assertTrue(monster2.Enemy() is None)
+ self.assertEqual(monster2.Testnestedflatbuffer(0), 0)
+ self.assertEqual(monster2.TestnestedflatbufferAsNumpy(), 0)
+ self.assertEqual(monster2.TestnestedflatbufferLength(), 0)
+ self.assertTrue(monster2.TestnestedflatbufferIsNone())
+ self.assertTrue(monster2.Testempty() is None)
+ self.assertTrue(monster2.Testbool() is False)
+ self.assertEqual(monster2.Testhashs32Fnv1(), 0)
+ self.assertEqual(monster2.Testhashu32Fnv1(), 0)
+ self.assertEqual(monster2.Testhashs64Fnv1(), 0)
+ self.assertEqual(monster2.Testhashu64Fnv1(), 0)
+ self.assertEqual(monster2.Testhashs32Fnv1a(), 0)
+ self.assertEqual(monster2.Testhashu32Fnv1a(), 0)
+ self.assertEqual(monster2.Testhashs64Fnv1a(), 0)
+ self.assertEqual(monster2.Testhashu64Fnv1a(), 0)
+ self.assertEqual(monster2.Testarrayofbools(0), 0)
+ self.assertEqual(monster2.TestarrayofboolsAsNumpy(), 0)
+ self.assertEqual(monster2.TestarrayofboolsLength(), 0)
+ self.assertTrue(monster2.TestarrayofboolsIsNone())
+ self.assertEqual(monster2.Testf(), 3.14159)
+ self.assertEqual(monster2.Testf2(), 3.0)
+ self.assertEqual(monster2.Testf3(), 0.0)
+ self.assertTrue(monster2.Testarrayofstring2(0) is '')
+ self.assertEqual(monster2.Testarrayofstring2Length(), 0)
+ self.assertTrue(monster2.Testarrayofstring2IsNone())
+ self.assertTrue(monster2.Testarrayofsortedstruct(0) is None)
+ self.assertEqual(monster2.TestarrayofsortedstructLength(), 0)
+ self.assertTrue(monster2.TestarrayofsortedstructIsNone())
+ self.assertEqual(monster2.Flex(0), 0)
+ self.assertEqual(monster2.FlexAsNumpy(), 0)
+ self.assertEqual(monster2.FlexLength(), 0)
+ self.assertTrue(monster2.FlexIsNone())
+ self.assertTrue(monster2.Test5(0) is None)
+ self.assertEqual(monster2.Test5Length(), 0)
+ self.assertTrue(monster2.Test5IsNone())
+ self.assertEqual(monster2.VectorOfLongs(0), 0)
+ self.assertEqual(monster2.VectorOfLongsAsNumpy(), 0)
+ self.assertEqual(monster2.VectorOfLongsLength(), 0)
+ self.assertTrue(monster2.VectorOfLongsIsNone())
+ self.assertEqual(monster2.VectorOfDoubles(0), 0)
+ self.assertEqual(monster2.VectorOfDoublesAsNumpy(), 0)
+ self.assertEqual(monster2.VectorOfDoublesLength(), 0)
+ self.assertTrue(monster2.VectorOfDoublesIsNone())
+ self.assertTrue(monster2.ParentNamespaceTest() is None)
+ self.assertTrue(monster2.VectorOfReferrables(0) is None)
+ self.assertEqual(monster2.VectorOfReferrablesLength(), 0)
+ self.assertTrue(monster2.VectorOfReferrablesIsNone())
+ self.assertEqual(monster2.SingleWeakReference(), 0)
+ self.assertEqual(monster2.VectorOfWeakReferences(0), 0)
+ self.assertEqual(monster2.VectorOfWeakReferencesAsNumpy(), 0)
+ self.assertEqual(monster2.VectorOfWeakReferencesLength(), 0)
+ self.assertTrue(monster2.VectorOfWeakReferencesIsNone())
+ self.assertTrue(monster2.VectorOfStrongReferrables(0) is None)
+ self.assertEqual(monster2.VectorOfStrongReferrablesLength(), 0)
+ self.assertTrue(monster2.VectorOfStrongReferrablesIsNone())
+ self.assertEqual(monster2.CoOwningReference(), 0)
+ self.assertEqual(monster2.VectorOfCoOwningReferences(0), 0)
+ self.assertEqual(monster2.VectorOfCoOwningReferencesAsNumpy(), 0)
+ self.assertEqual(monster2.VectorOfCoOwningReferencesLength(), 0)
+ self.assertTrue(monster2.VectorOfCoOwningReferencesIsNone())
+ self.assertEqual(monster2.NonOwningReference(), 0)
+ self.assertEqual(monster2.VectorOfNonOwningReferences(0), 0)
+ self.assertEqual(monster2.VectorOfNonOwningReferencesAsNumpy(), 0)
+ self.assertEqual(monster2.VectorOfNonOwningReferencesLength(), 0)
+ self.assertTrue(monster2.VectorOfNonOwningReferencesIsNone())
+ self.assertEqual(monster2.AnyUniqueType(), 0)
+ self.assertTrue(monster2.AnyUnique() is None)
+ self.assertEqual(monster2.AnyAmbiguousType(), 0)
+ self.assertTrue(monster2.AnyAmbiguous() is None)
+ self.assertEqual(monster2.VectorOfEnums(0), 0)
+ self.assertEqual(monster2.VectorOfEnumsAsNumpy(), 0)
+ self.assertEqual(monster2.VectorOfEnumsLength(), 0)
+ self.assertTrue(monster2.VectorOfEnumsIsNone())
class TestAllMutableCodePathsOfExampleSchema(unittest.TestCase):
- ''' Tests the object API generated for monster_test.fbs for mutation
+ """ Tests the object API generated for monster_test.fbs for mutation
+
purposes. In each test, the default values will be changed through the
object API. We'll then pack the object class into the buf class and read
the updated values out from it to validate if the values are mutated as
- expected.'''
+ expected.
+ """
- def setUp(self, *args, **kwargs):
- super(TestAllMutableCodePathsOfExampleSchema, self).setUp(*args,
- **kwargs)
- # Creates an empty monster flatbuffer, and loads it into the object
- # class for future tests.
- b = flatbuffers.Builder(0)
- MyGame.Example.Monster.MonsterStart(b)
- self.monsterT = self._create_and_load_object_class(b)
+ def setUp(self, *args, **kwargs):
+ super(TestAllMutableCodePathsOfExampleSchema, self).setUp(*args, **kwargs)
+ # Creates an empty monster flatbuffer, and loads it into the object
+ # class for future tests.
+ b = flatbuffers.Builder(0)
+ _MONSTER.MonsterStart(b)
+ self.monsterT = self._create_and_load_object_class(b)
- def _pack_and_load_buf_class(self, monsterT):
- ''' Packs the object class into a flatbuffer and loads it into a buf
- class.'''
- b = flatbuffers.Builder(0)
- b.Finish(monsterT.Pack(b))
- monster = MyGame.Example.Monster.Monster.GetRootAsMonster(b.Bytes,
- b.Head())
- return monster
+ def _pack_and_load_buf_class(self, monsterT):
+ """ Packs the object class into a flatbuffer and loads it into a buf
- def _create_and_load_object_class(self, b):
- ''' Finishs the creation of a monster flatbuffer and loads it into an
- object class.'''
- gen_mon = MyGame.Example.Monster.MonsterEnd(b)
- b.Finish(gen_mon)
- monster = MyGame.Example.Monster.Monster.GetRootAsMonster(b.Bytes,
- b.Head())
- monsterT = MyGame.Example.Monster.MonsterT()
- monsterT.InitFromObj(monster)
- return monsterT
+ class.
+ """
+ b = flatbuffers.Builder(0)
+ b.Finish(monsterT.Pack(b))
+ monster = _MONSTER.Monster.GetRootAs(b.Bytes, b.Head())
+ return monster
- def test_mutate_pos(self):
- posT = MyGame.Example.Vec3.Vec3T()
- posT.x = 4.0
- posT.y = 5.0
- posT.z = 6.0
- posT.test1 = 6.0
- posT.test2 = 7
- test3T = MyGame.Example.Test.TestT()
- test3T.a = 8
- test3T.b = 9
- posT.test3 = test3T
- self.monsterT.pos = posT
+ def _create_and_load_object_class(self, b):
+ """ Finishs the creation of a monster flatbuffer and loads it into an
- # Packs the updated values.
- monster = self._pack_and_load_buf_class(self.monsterT)
+ object class.
+ """
+ gen_mon = _MONSTER.MonsterEnd(b)
+ b.Finish(gen_mon)
+ monster = _MONSTER.Monster.GetRootAs(b.Bytes, b.Head())
+ monsterT = _MONSTER.MonsterT()
+ monsterT.InitFromObj(monster)
+ return monsterT
- # Checks if values are loaded correctly into the object class.
- pos = monster.Pos()
+ def test_mutate_pos(self):
+ posT = _VEC3.Vec3T()
+ posT.x = 4.0
+ posT.y = 5.0
+ posT.z = 6.0
+ posT.test1 = 6.0
+ posT.test2 = 7
+ test3T = _TEST.TestT()
+ test3T.a = 8
+ test3T.b = 9
+ posT.test3 = test3T
+ self.monsterT.pos = posT
- # Verifies the properties of the Vec3.
- self.assertEqual(pos.X(), 4.0)
- self.assertEqual(pos.Y(), 5.0)
- self.assertEqual(pos.Z(), 6.0)
- self.assertEqual(pos.Test1(), 6.0)
- self.assertEqual(pos.Test2(), 7)
- t3 = MyGame.Example.Test.Test()
- t3 = pos.Test3(t3)
- self.assertEqual(t3.A(), 8)
- self.assertEqual(t3.B(), 9)
+ # Packs the updated values.
+ monster = self._pack_and_load_buf_class(self.monsterT)
- def test_mutate_mana(self):
- self.monsterT.mana = 200
- monster = self._pack_and_load_buf_class(self.monsterT)
- self.assertEqual(monster.Mana(), 200)
+ # Checks if values are loaded correctly into the object class.
+ pos = monster.Pos()
- def test_mutate_hp(self):
- self.monsterT.hp = 200
- monster = self._pack_and_load_buf_class(self.monsterT)
- self.assertEqual(monster.Hp(), 200)
+ # Verifies the properties of the Vec3.
+ self.assertEqual(pos.X(), 4.0)
+ self.assertEqual(pos.Y(), 5.0)
+ self.assertEqual(pos.Z(), 6.0)
+ self.assertEqual(pos.Test1(), 6.0)
+ self.assertEqual(pos.Test2(), 7)
+ t3 = _TEST.Test()
+ t3 = pos.Test3(t3)
+ self.assertEqual(t3.A(), 8)
+ self.assertEqual(t3.B(), 9)
- def test_mutate_name(self):
- self.monsterT.name = "MyMonster"
- monster = self._pack_and_load_buf_class(self.monsterT)
- self.assertEqual(monster.Name(), b"MyMonster")
+ def test_mutate_mana(self):
+ self.monsterT.mana = 200
+ monster = self._pack_and_load_buf_class(self.monsterT)
+ self.assertEqual(monster.Mana(), 200)
- def test_mutate_inventory(self):
- self.monsterT.inventory = [1, 7, 8]
- monster = self._pack_and_load_buf_class(self.monsterT)
- self.assertEqual(monster.Inventory(0), 1)
- self.assertEqual(monster.Inventory(1), 7)
- self.assertEqual(monster.Inventory(2), 8)
+ def test_mutate_hp(self):
+ self.monsterT.hp = 200
+ monster = self._pack_and_load_buf_class(self.monsterT)
+ self.assertEqual(monster.Hp(), 200)
- def test_empty_inventory(self):
- self.monsterT.inventory = []
- monster = self._pack_and_load_buf_class(self.monsterT)
- self.assertFalse(monster.InventoryIsNone())
+ def test_mutate_name(self):
+ self.monsterT.name = 'MyMonster'
+ monster = self._pack_and_load_buf_class(self.monsterT)
+ self.assertEqual(monster.Name(), b'MyMonster')
- def test_mutate_color(self):
- self.monsterT.color = MyGame.Example.Color.Color.Red
- monster = self._pack_and_load_buf_class(self.monsterT)
- self.assertEqual(monster.Color(), MyGame.Example.Color.Color.Red)
+ def test_mutate_inventory(self):
+ self.monsterT.inventory = [1, 7, 8]
+ monster = self._pack_and_load_buf_class(self.monsterT)
+ self.assertEqual(monster.Inventory(0), 1)
+ self.assertEqual(monster.Inventory(1), 7)
+ self.assertEqual(monster.Inventory(2), 8)
- def test_mutate_testtype(self):
- self.monsterT.testType = MyGame.Example.Any.Any.Monster
- monster = self._pack_and_load_buf_class(self.monsterT)
- self.assertEqual(monster.TestType(), MyGame.Example.Any.Any.Monster)
+ def test_empty_inventory(self):
+ self.monsterT.inventory = []
+ monster = self._pack_and_load_buf_class(self.monsterT)
+ self.assertFalse(monster.InventoryIsNone())
- def test_mutate_test(self):
- testT = MyGame.Example.Monster.MonsterT()
- testT.hp = 200
- self.monsterT.test = testT
- monster = self._pack_and_load_buf_class(self.monsterT)
- # Initializes a Table from a union field Test(...).
- table = monster.Test()
+ def test_mutate_color(self):
+ self.monsterT.color = _COLOR.Color.Red
+ monster = self._pack_and_load_buf_class(self.monsterT)
+ self.assertEqual(monster.Color(), _COLOR.Color.Red)
- # Initializes a Monster from the Table from the union.
- test_monster = MyGame.Example.Monster.Monster()
- test_monster.Init(table.Bytes, table.Pos)
- self.assertEqual(test_monster.Hp(), 200)
+ def test_mutate_testtype(self):
+ self.monsterT.testType = _ANY.Any.Monster
+ monster = self._pack_and_load_buf_class(self.monsterT)
+ self.assertEqual(monster.TestType(), _ANY.Any.Monster)
- def test_mutate_test4(self):
- test0T = MyGame.Example.Test.TestT()
- test0T.a = 10
- test0T.b = 20
- test1T = MyGame.Example.Test.TestT()
- test1T.a = 30
- test1T.b = 40
- self.monsterT.test4 = [test0T, test1T]
+ def test_mutate_test(self):
+ testT = _MONSTER.MonsterT()
+ testT.hp = 200
+ self.monsterT.test = testT
+ monster = self._pack_and_load_buf_class(self.monsterT)
+ # Initializes a Table from a union field Test(...).
+ table = monster.Test()
- monster = self._pack_and_load_buf_class(self.monsterT)
- test0 = monster.Test4(0)
- self.assertEqual(test0.A(), 10)
- self.assertEqual(test0.B(), 20)
- test1 = monster.Test4(1)
- self.assertEqual(test1.A(), 30)
- self.assertEqual(test1.B(), 40)
+ # Initializes a Monster from the Table from the union.
+ test_monster = _MONSTER.Monster()
+ test_monster.Init(table.Bytes, table.Pos)
+ self.assertEqual(test_monster.Hp(), 200)
- def test_empty_test4(self):
- self.monsterT.test4 = []
- monster = self._pack_and_load_buf_class(self.monsterT)
- self.assertFalse(monster.Test4IsNone())
+ def test_mutate_test4(self):
+ test0T = _TEST.TestT()
+ test0T.a = 10
+ test0T.b = 20
+ test1T = _TEST.TestT()
+ test1T.a = 30
+ test1T.b = 40
+ self.monsterT.test4 = [test0T, test1T]
- def test_mutate_testarrayofstring(self):
- self.monsterT.testarrayofstring = []
- self.monsterT.testarrayofstring.append("test1")
- self.monsterT.testarrayofstring.append("test2")
- monster = self._pack_and_load_buf_class(self.monsterT)
- self.assertEqual(monster.Testarrayofstring(0), b"test1")
- self.assertEqual(monster.Testarrayofstring(1), b"test2")
+ monster = self._pack_and_load_buf_class(self.monsterT)
+ test0 = monster.Test4(0)
+ self.assertEqual(test0.A(), 10)
+ self.assertEqual(test0.B(), 20)
+ test1 = monster.Test4(1)
+ self.assertEqual(test1.A(), 30)
+ self.assertEqual(test1.B(), 40)
- def test_empty_testarrayofstring(self):
- self.monsterT.testarrayofstring = []
- monster = self._pack_and_load_buf_class(self.monsterT)
- self.assertFalse(monster.TestarrayofstringIsNone())
+ def test_empty_test4(self):
+ self.monsterT.test4 = []
+ monster = self._pack_and_load_buf_class(self.monsterT)
+ self.assertFalse(monster.Test4IsNone())
- def test_mutate_testarrayoftables(self):
- monsterT0 = MyGame.Example.Monster.MonsterT()
- monsterT0.hp = 200
- monsterT1 = MyGame.Example.Monster.MonsterT()
- monsterT1.hp = 400
- self.monsterT.testarrayoftables = []
- self.monsterT.testarrayoftables.append(monsterT0)
- self.monsterT.testarrayoftables.append(monsterT1)
- monster = self._pack_and_load_buf_class(self.monsterT)
- self.assertEqual(monster.Testarrayoftables(0).Hp(), 200)
- self.assertEqual(monster.Testarrayoftables(1).Hp(), 400)
+ def test_mutate_testarrayofstring(self):
+ self.monsterT.testarrayofstring = []
+ self.monsterT.testarrayofstring.append('test1')
+ self.monsterT.testarrayofstring.append('test2')
+ monster = self._pack_and_load_buf_class(self.monsterT)
+ self.assertEqual(monster.Testarrayofstring(0), b'test1')
+ self.assertEqual(monster.Testarrayofstring(1), b'test2')
- def test_empty_testarrayoftables(self):
- self.monsterT.testarrayoftables = []
- monster = self._pack_and_load_buf_class(self.monsterT)
- self.assertFalse(monster.TestarrayoftablesIsNone())
+ def test_empty_testarrayofstring(self):
+ self.monsterT.testarrayofstring = []
+ monster = self._pack_and_load_buf_class(self.monsterT)
+ self.assertFalse(monster.TestarrayofstringIsNone())
- def test_mutate_enemy(self):
- monsterT = MyGame.Example.Monster.MonsterT()
- monsterT.hp = 200
- self.monsterT.enemy = monsterT
- monster = self._pack_and_load_buf_class(self.monsterT)
- self.assertEqual(monster.Enemy().Hp(), 200)
+ def test_mutate_testarrayoftables(self):
+ monsterT0 = _MONSTER.MonsterT()
+ monsterT0.hp = 200
+ monsterT1 = _MONSTER.MonsterT()
+ monsterT1.hp = 400
+ self.monsterT.testarrayoftables = []
+ self.monsterT.testarrayoftables.append(monsterT0)
+ self.monsterT.testarrayoftables.append(monsterT1)
+ monster = self._pack_and_load_buf_class(self.monsterT)
+ self.assertEqual(monster.Testarrayoftables(0).Hp(), 200)
+ self.assertEqual(monster.Testarrayoftables(1).Hp(), 400)
- def test_mutate_testnestedflatbuffer(self):
- self.monsterT.testnestedflatbuffer = [8, 2, 4]
- monster = self._pack_and_load_buf_class(self.monsterT)
- self.assertEqual(monster.Testnestedflatbuffer(0), 8)
- self.assertEqual(monster.Testnestedflatbuffer(1), 2)
- self.assertEqual(monster.Testnestedflatbuffer(2), 4)
+ def test_empty_testarrayoftables(self):
+ self.monsterT.testarrayoftables = []
+ monster = self._pack_and_load_buf_class(self.monsterT)
+ self.assertFalse(monster.TestarrayoftablesIsNone())
- def test_empty_testnestedflatbuffer(self):
- self.monsterT.testnestedflatbuffer = []
- monster = self._pack_and_load_buf_class(self.monsterT)
- self.assertFalse(monster.TestnestedflatbufferIsNone())
+ def test_mutate_enemy(self):
+ monsterT = _MONSTER.MonsterT()
+ monsterT.hp = 200
+ self.monsterT.enemy = monsterT
+ monster = self._pack_and_load_buf_class(self.monsterT)
+ self.assertEqual(monster.Enemy().Hp(), 200)
- def test_mutate_testbool(self):
- self.monsterT.testbool = True
- monster = self._pack_and_load_buf_class(self.monsterT)
- self.assertTrue(monster.Testbool())
+ def test_mutate_testnestedflatbuffer(self):
+ self.monsterT.testnestedflatbuffer = [8, 2, 4]
+ monster = self._pack_and_load_buf_class(self.monsterT)
+ self.assertEqual(monster.Testnestedflatbuffer(0), 8)
+ self.assertEqual(monster.Testnestedflatbuffer(1), 2)
+ self.assertEqual(monster.Testnestedflatbuffer(2), 4)
- def test_mutate_testhashes(self):
- self.monsterT.testhashs32Fnv1 = 1
- self.monsterT.testhashu32Fnv1 = 2
- self.monsterT.testhashs64Fnv1 = 3
- self.monsterT.testhashu64Fnv1 = 4
- self.monsterT.testhashs32Fnv1a = 5
- self.monsterT.testhashu32Fnv1a = 6
- self.monsterT.testhashs64Fnv1a = 7
- self.monsterT.testhashu64Fnv1a = 8
- monster = self._pack_and_load_buf_class(self.monsterT)
- self.assertEqual(monster.Testhashs32Fnv1(), 1)
- self.assertEqual(monster.Testhashu32Fnv1(), 2)
- self.assertEqual(monster.Testhashs64Fnv1(), 3)
- self.assertEqual(monster.Testhashu64Fnv1(), 4)
- self.assertEqual(monster.Testhashs32Fnv1a(), 5)
- self.assertEqual(monster.Testhashu32Fnv1a(), 6)
- self.assertEqual(monster.Testhashs64Fnv1a(), 7)
- self.assertEqual(monster.Testhashu64Fnv1a(), 8)
+ def test_empty_testnestedflatbuffer(self):
+ self.monsterT.testnestedflatbuffer = []
+ monster = self._pack_and_load_buf_class(self.monsterT)
+ self.assertFalse(monster.TestnestedflatbufferIsNone())
- def test_mutate_testarrayofbools(self):
- self.monsterT.testarrayofbools = []
- self.monsterT.testarrayofbools.append(True)
- self.monsterT.testarrayofbools.append(True)
- self.monsterT.testarrayofbools.append(False)
- monster = self._pack_and_load_buf_class(self.monsterT)
- self.assertEqual(monster.Testarrayofbools(0), True)
- self.assertEqual(monster.Testarrayofbools(1), True)
- self.assertEqual(monster.Testarrayofbools(2), False)
+ def test_mutate_testbool(self):
+ self.monsterT.testbool = True
+ monster = self._pack_and_load_buf_class(self.monsterT)
+ self.assertTrue(monster.Testbool())
- def test_empty_testarrayofbools(self):
- self.monsterT.testarrayofbools = []
- monster = self._pack_and_load_buf_class(self.monsterT)
- self.assertFalse(monster.TestarrayofboolsIsNone())
+ def test_mutate_testhashes(self):
+ self.monsterT.testhashs32Fnv1 = 1
+ self.monsterT.testhashu32Fnv1 = 2
+ self.monsterT.testhashs64Fnv1 = 3
+ self.monsterT.testhashu64Fnv1 = 4
+ self.monsterT.testhashs32Fnv1a = 5
+ self.monsterT.testhashu32Fnv1a = 6
+ self.monsterT.testhashs64Fnv1a = 7
+ self.monsterT.testhashu64Fnv1a = 8
+ monster = self._pack_and_load_buf_class(self.monsterT)
+ self.assertEqual(monster.Testhashs32Fnv1(), 1)
+ self.assertEqual(monster.Testhashu32Fnv1(), 2)
+ self.assertEqual(monster.Testhashs64Fnv1(), 3)
+ self.assertEqual(monster.Testhashu64Fnv1(), 4)
+ self.assertEqual(monster.Testhashs32Fnv1a(), 5)
+ self.assertEqual(monster.Testhashu32Fnv1a(), 6)
+ self.assertEqual(monster.Testhashs64Fnv1a(), 7)
+ self.assertEqual(monster.Testhashu64Fnv1a(), 8)
- def test_mutate_testf(self):
- self.monsterT.testf = 2.0
- monster = self._pack_and_load_buf_class(self.monsterT)
- self.assertEqual(monster.Testf(), 2.0)
+ def test_mutate_testarrayofbools(self):
+ self.monsterT.testarrayofbools = []
+ self.monsterT.testarrayofbools.append(True)
+ self.monsterT.testarrayofbools.append(True)
+ self.monsterT.testarrayofbools.append(False)
+ monster = self._pack_and_load_buf_class(self.monsterT)
+ self.assertEqual(monster.Testarrayofbools(0), True)
+ self.assertEqual(monster.Testarrayofbools(1), True)
+ self.assertEqual(monster.Testarrayofbools(2), False)
- def test_mutate_vectoroflongs(self):
- self.monsterT.vectorOfLongs = []
- self.monsterT.vectorOfLongs.append(1)
- self.monsterT.vectorOfLongs.append(100)
- self.monsterT.vectorOfLongs.append(10000)
- self.monsterT.vectorOfLongs.append(1000000)
- self.monsterT.vectorOfLongs.append(100000000)
- monster = self._pack_and_load_buf_class(self.monsterT)
- self.assertEqual(monster.VectorOfLongs(0), 1)
- self.assertEqual(monster.VectorOfLongs(1), 100)
- self.assertEqual(monster.VectorOfLongs(2), 10000)
- self.assertEqual(monster.VectorOfLongs(3), 1000000)
- self.assertEqual(monster.VectorOfLongs(4), 100000000)
+ def test_empty_testarrayofbools(self):
+ self.monsterT.testarrayofbools = []
+ monster = self._pack_and_load_buf_class(self.monsterT)
+ self.assertFalse(monster.TestarrayofboolsIsNone())
- def test_empty_vectoroflongs(self):
- self.monsterT.vectorOfLongs = []
- monster = self._pack_and_load_buf_class(self.monsterT)
- self.assertFalse(monster.VectorOfLongsIsNone())
+ def test_mutate_testf(self):
+ self.monsterT.testf = 2.0
+ monster = self._pack_and_load_buf_class(self.monsterT)
+ self.assertEqual(monster.Testf(), 2.0)
- def test_mutate_vectorofdoubles(self):
- self.monsterT.vectorOfDoubles = []
- self.monsterT.vectorOfDoubles.append(-1.7976931348623157e+308)
- self.monsterT.vectorOfDoubles.append(0)
- self.monsterT.vectorOfDoubles.append(1.7976931348623157e+308)
- monster = self._pack_and_load_buf_class(self.monsterT)
- self.assertEqual(monster.VectorOfDoubles(0), -1.7976931348623157e+308)
- self.assertEqual(monster.VectorOfDoubles(1), 0)
- self.assertEqual(monster.VectorOfDoubles(2), 1.7976931348623157e+308)
+ def test_mutate_vectoroflongs(self):
+ self.monsterT.vectorOfLongs = []
+ self.monsterT.vectorOfLongs.append(1)
+ self.monsterT.vectorOfLongs.append(100)
+ self.monsterT.vectorOfLongs.append(10000)
+ self.monsterT.vectorOfLongs.append(1000000)
+ self.monsterT.vectorOfLongs.append(100000000)
+ monster = self._pack_and_load_buf_class(self.monsterT)
+ self.assertEqual(monster.VectorOfLongs(0), 1)
+ self.assertEqual(monster.VectorOfLongs(1), 100)
+ self.assertEqual(monster.VectorOfLongs(2), 10000)
+ self.assertEqual(monster.VectorOfLongs(3), 1000000)
+ self.assertEqual(monster.VectorOfLongs(4), 100000000)
- def test_empty_vectorofdoubles(self):
- self.monsterT.vectorOfDoubles = []
- monster = self._pack_and_load_buf_class(self.monsterT)
- self.assertFalse(monster.VectorOfDoublesIsNone())
+ def test_empty_vectoroflongs(self):
+ self.monsterT.vectorOfLongs = []
+ monster = self._pack_and_load_buf_class(self.monsterT)
+ self.assertFalse(monster.VectorOfLongsIsNone())
- def test_mutate_parentnamespacetest(self):
- self.monsterT.parentNamespaceTest = MyGame.InParentNamespace.InParentNamespaceT()
- monster = self._pack_and_load_buf_class(self.monsterT)
- self.assertTrue(isinstance(monster.ParentNamespaceTest(),
- MyGame.InParentNamespace.InParentNamespace))
+ def test_mutate_vectorofdoubles(self):
+ self.monsterT.vectorOfDoubles = []
+ self.monsterT.vectorOfDoubles.append(-1.7976931348623157e+308)
+ self.monsterT.vectorOfDoubles.append(0)
+ self.monsterT.vectorOfDoubles.append(1.7976931348623157e+308)
+ monster = self._pack_and_load_buf_class(self.monsterT)
+ self.assertEqual(monster.VectorOfDoubles(0), -1.7976931348623157e+308)
+ self.assertEqual(monster.VectorOfDoubles(1), 0)
+ self.assertEqual(monster.VectorOfDoubles(2), 1.7976931348623157e+308)
- def test_mutate_vectorofEnums(self):
- self.monsterT.vectorOfEnums = []
- self.monsterT.vectorOfEnums.append(MyGame.Example.Color.Color.Red)
- self.monsterT.vectorOfEnums.append(MyGame.Example.Color.Color.Blue)
- self.monsterT.vectorOfEnums.append(MyGame.Example.Color.Color.Red)
- monster = self._pack_and_load_buf_class(self.monsterT)
- self.assertEqual(monster.VectorOfEnums(0),
- MyGame.Example.Color.Color.Red)
- self.assertEqual(monster.VectorOfEnums(1),
- MyGame.Example.Color.Color.Blue)
- self.assertEqual(monster.VectorOfEnums(2),
- MyGame.Example.Color.Color.Red)
+ def test_empty_vectorofdoubles(self):
+ self.monsterT.vectorOfDoubles = []
+ monster = self._pack_and_load_buf_class(self.monsterT)
+ self.assertFalse(monster.VectorOfDoublesIsNone())
- def test_empty_vectorofEnums(self):
- self.monsterT.vectorOfEnums = []
- monster = self._pack_and_load_buf_class(self.monsterT)
- self.assertFalse(monster.VectorOfEnumsIsNone())
+ def test_mutate_parentnamespacetest(self):
+ self.monsterT.parentNamespaceTest = _IN_PARENT_NAMESPACE.InParentNamespaceT(
+ )
+ monster = self._pack_and_load_buf_class(self.monsterT)
+ self.assertTrue(
+ isinstance(monster.ParentNamespaceTest(),
+ _IN_PARENT_NAMESPACE.InParentNamespace))
+
+ def test_mutate_vectorofEnums(self):
+ self.monsterT.vectorOfEnums = []
+ self.monsterT.vectorOfEnums.append(_COLOR.Color.Red)
+ self.monsterT.vectorOfEnums.append(_COLOR.Color.Blue)
+ self.monsterT.vectorOfEnums.append(_COLOR.Color.Red)
+ monster = self._pack_and_load_buf_class(self.monsterT)
+ self.assertEqual(monster.VectorOfEnums(0), _COLOR.Color.Red)
+ self.assertEqual(monster.VectorOfEnums(1), _COLOR.Color.Blue)
+ self.assertEqual(monster.VectorOfEnums(2), _COLOR.Color.Red)
+
+ def test_empty_vectorofEnums(self):
+ self.monsterT.vectorOfEnums = []
+ monster = self._pack_and_load_buf_class(self.monsterT)
+ self.assertFalse(monster.VectorOfEnumsIsNone())
def CheckReadBuffer(buf, offset, sizePrefix=False, file_identifier=None):
- ''' CheckReadBuffer checks that the given buffer is evaluated correctly
- as the example Monster. '''
+ """ CheckReadBuffer checks that the given buffer is evaluated correctly
- def asserter(stmt):
- ''' An assertion helper that is separated from TestCase classes. '''
- if not stmt:
- raise AssertionError('CheckReadBuffer case failed')
- if file_identifier:
- # test prior to removal of size_prefix
- asserter(util.GetBufferIdentifier(buf, offset, size_prefixed=sizePrefix) == file_identifier)
- asserter(util.BufferHasIdentifier(buf, offset, file_identifier=file_identifier, size_prefixed=sizePrefix))
- asserter(MyGame.Example.Monster.Monster.MonsterBufferHasIdentifier(buf, offset, size_prefixed=sizePrefix))
- if sizePrefix:
- size = util.GetSizePrefix(buf, offset)
- asserter(size == len(buf[offset:])-4)
- buf, offset = util.RemoveSizePrefix(buf, offset)
- if file_identifier:
- asserter(MyGame.Example.Monster.Monster.MonsterBufferHasIdentifier(buf, offset))
- else:
- asserter(not MyGame.Example.Monster.Monster.MonsterBufferHasIdentifier(buf, offset))
- monster = MyGame.Example.Monster.Monster.GetRootAsMonster(buf, offset)
+ as the example Monster.
+ """
- asserter(monster.Hp() == 80)
- asserter(monster.Mana() == 150)
- asserter(monster.Name() == b'MyMonster')
+ def asserter(stmt):
+ """ An assertion helper that is separated from TestCase classes. """
+ if not stmt:
+ raise AssertionError('CheckReadBuffer case failed')
- # initialize a Vec3 from Pos()
- vec = monster.Pos()
- asserter(vec is not None)
+ if file_identifier:
+ # test prior to removal of size_prefix
+ asserter(
+ util.GetBufferIdentifier(buf, offset, size_prefixed=sizePrefix) ==
+ file_identifier)
+ asserter(
+ util.BufferHasIdentifier(
+ buf,
+ offset,
+ file_identifier=file_identifier,
+ size_prefixed=sizePrefix))
+ asserter(
+ _MONSTER.Monster.MonsterBufferHasIdentifier(
+ buf, offset, size_prefixed=sizePrefix))
+ if sizePrefix:
+ size = util.GetSizePrefix(buf, offset)
+ asserter(size == len(buf[offset:]) - 4)
+ buf, offset = util.RemoveSizePrefix(buf, offset)
+ if file_identifier:
+ asserter(_MONSTER.Monster.MonsterBufferHasIdentifier(buf, offset))
+ else:
+ asserter(not _MONSTER.Monster.MonsterBufferHasIdentifier(buf, offset))
+ monster = _MONSTER.Monster.GetRootAs(buf, offset)
- # verify the properties of the Vec3
- asserter(vec.X() == 1.0)
- asserter(vec.Y() == 2.0)
- asserter(vec.Z() == 3.0)
- asserter(vec.Test1() == 3.0)
- asserter(vec.Test2() == 2)
+ asserter(monster.Hp() == 80)
+ asserter(monster.Mana() == 150)
+ asserter(monster.Name() == b'MyMonster')
- # initialize a Test from Test3(...)
- t = MyGame.Example.Test.Test()
- t = vec.Test3(t)
- asserter(t is not None)
+ # initialize a Vec3 from Pos()
+ vec = monster.Pos()
+ asserter(vec is not None)
- # verify the properties of the Test
- asserter(t.A() == 5)
- asserter(t.B() == 6)
+ # verify the properties of the Vec3
+ asserter(vec.X() == 1.0)
+ asserter(vec.Y() == 2.0)
+ asserter(vec.Z() == 3.0)
+ asserter(vec.Test1() == 3.0)
+ asserter(vec.Test2() == 2)
- # verify that the enum code matches the enum declaration:
- union_type = MyGame.Example.Any.Any
- asserter(monster.TestType() == union_type.Monster)
+ # initialize a Test from Test3(...)
+ t = _TEST.Test()
+ t = vec.Test3(t)
+ asserter(t is not None)
- # initialize a Table from a union field Test(...)
- table2 = monster.Test()
- asserter(type(table2) is flatbuffers.table.Table)
+ # verify the properties of the Test
+ asserter(t.A() == 5)
+ asserter(t.B() == 6)
- # initialize a Monster from the Table from the union
- monster2 = MyGame.Example.Monster.Monster()
- monster2.Init(table2.Bytes, table2.Pos)
+ # verify that the enum code matches the enum declaration:
+ union_type = _ANY.Any
+ asserter(monster.TestType() == union_type.Monster)
- asserter(monster2.Name() == b"Fred")
+ # initialize a Table from a union field Test(...)
+ table2 = monster.Test()
+ asserter(type(table2) is flatbuffers.table.Table)
- # iterate through the first monster's inventory:
- asserter(monster.InventoryLength() == 5)
- asserter(not monster.InventoryIsNone())
+ # initialize a Monster from the Table from the union
+ monster2 = _MONSTER.Monster()
+ monster2.Init(table2.Bytes, table2.Pos)
- invsum = 0
- for i in compat_range(monster.InventoryLength()):
- v = monster.Inventory(i)
- invsum += int(v)
- asserter(invsum == 10)
+ asserter(monster2.Name() == b'Fred')
+ # iterate through the first monster's inventory:
+ asserter(monster.InventoryLength() == 5)
+ asserter(not monster.InventoryIsNone())
+
+ invsum = 0
+ for i in compat_range(monster.InventoryLength()):
+ v = monster.Inventory(i)
+ invsum += int(v)
+ asserter(invsum == 10)
+
+ for i in range(5):
+ asserter(monster.VectorOfLongs(i) == 10**(i * 2))
+
+ asserter(not monster.VectorOfDoublesIsNone())
+ asserter(([-1.7976931348623157e+308, 0, 1.7976931348623157e+308] == [
+ monster.VectorOfDoubles(i) for i in range(monster.VectorOfDoublesLength())
+ ]))
+
+ try:
+ imp.find_module('numpy')
+ # if numpy exists, then we should be able to get the
+ # vector as a numpy array
+ import numpy as np
+
+ asserter(monster.InventoryAsNumpy().sum() == 10)
+ asserter(monster.InventoryAsNumpy().dtype == np.dtype('uint8'))
+
+ VectorOfLongs = monster.VectorOfLongsAsNumpy()
+ asserter(VectorOfLongs.dtype == np.dtype('int64'))
for i in range(5):
- asserter(monster.VectorOfLongs(i) == 10 ** (i * 2))
+ asserter(VectorOfLongs[i] == 10**(i * 2))
- asserter(not monster.VectorOfDoublesIsNone())
- asserter(([-1.7976931348623157e+308, 0, 1.7976931348623157e+308]
- == [monster.VectorOfDoubles(i)
- for i in range(monster.VectorOfDoublesLength())]))
+ VectorOfDoubles = monster.VectorOfDoublesAsNumpy()
+ asserter(VectorOfDoubles.dtype == np.dtype('float64'))
+ asserter(VectorOfDoubles[0] == np.finfo('float64').min)
+ asserter(VectorOfDoubles[1] == 0.0)
+ asserter(VectorOfDoubles[2] == np.finfo('float64').max)
- try:
- imp.find_module('numpy')
- # if numpy exists, then we should be able to get the
- # vector as a numpy array
- import numpy as np
+ except ImportError:
+ # If numpy does not exist, trying to get vector as numpy
+ # array should raise NumpyRequiredForThisFeature. The way
+ # assertRaises has been implemented prevents us from
+ # asserting this error is raised outside of a test case.
+ pass
- asserter(monster.InventoryAsNumpy().sum() == 10)
- asserter(monster.InventoryAsNumpy().dtype == np.dtype('uint8'))
+ asserter(monster.Test4Length() == 2)
+ asserter(not monster.Test4IsNone())
- VectorOfLongs = monster.VectorOfLongsAsNumpy()
- asserter(VectorOfLongs.dtype == np.dtype('int64'))
- for i in range(5):
- asserter(VectorOfLongs[i] == 10 ** (i * 2))
+ # create a 'Test' object and populate it:
+ test0 = monster.Test4(0)
+ asserter(type(test0) is _TEST.Test)
- VectorOfDoubles = monster.VectorOfDoublesAsNumpy()
- asserter(VectorOfDoubles.dtype == np.dtype('float64'))
- asserter(VectorOfDoubles[0] == np.finfo('float64').min)
- asserter(VectorOfDoubles[1] == 0.0)
- asserter(VectorOfDoubles[2] == np.finfo('float64').max)
+ test1 = monster.Test4(1)
+ asserter(type(test1) is _TEST.Test)
- except ImportError:
- # If numpy does not exist, trying to get vector as numpy
- # array should raise NumpyRequiredForThisFeature. The way
- # assertRaises has been implemented prevents us from
- # asserting this error is raised outside of a test case.
- pass
+ # the position of test0 and test1 are swapped in monsterdata_java_wire
+ # and monsterdata_test_wire, so ignore ordering
+ v0 = test0.A()
+ v1 = test0.B()
+ v2 = test1.A()
+ v3 = test1.B()
+ sumtest12 = int(v0) + int(v1) + int(v2) + int(v3)
- asserter(monster.Test4Length() == 2)
- asserter(not monster.Test4IsNone())
+ asserter(sumtest12 == 100)
- # create a 'Test' object and populate it:
- test0 = monster.Test4(0)
- asserter(type(test0) is MyGame.Example.Test.Test)
+ asserter(not monster.TestarrayofstringIsNone())
+ asserter(monster.TestarrayofstringLength() == 2)
+ asserter(monster.Testarrayofstring(0) == b'test1')
+ asserter(monster.Testarrayofstring(1) == b'test2')
- test1 = monster.Test4(1)
- asserter(type(test1) is MyGame.Example.Test.Test)
-
- # the position of test0 and test1 are swapped in monsterdata_java_wire
- # and monsterdata_test_wire, so ignore ordering
- v0 = test0.A()
- v1 = test0.B()
- v2 = test1.A()
- v3 = test1.B()
- sumtest12 = int(v0) + int(v1) + int(v2) + int(v3)
-
- asserter(sumtest12 == 100)
-
- asserter(not monster.TestarrayofstringIsNone())
- asserter(monster.TestarrayofstringLength() == 2)
- asserter(monster.Testarrayofstring(0) == b"test1")
- asserter(monster.Testarrayofstring(1) == b"test2")
-
- asserter(monster.TestarrayoftablesIsNone())
- asserter(monster.TestarrayoftablesLength() == 0)
- asserter(monster.TestnestedflatbufferIsNone())
- asserter(monster.TestnestedflatbufferLength() == 0)
- asserter(monster.Testempty() is None)
+ asserter(monster.TestarrayoftablesIsNone())
+ asserter(monster.TestarrayoftablesLength() == 0)
+ asserter(monster.TestnestedflatbufferIsNone())
+ asserter(monster.TestnestedflatbufferLength() == 0)
+ asserter(monster.Testempty() is None)
class TestFuzz(unittest.TestCase):
- ''' Low level stress/fuzz test: serialize/deserialize a variety of
- different kinds of data in different combinations '''
+ """ Low level stress/fuzz test: serialize/deserialize a variety of
- binary_type = compat.binary_types[0] # this will always exist
- ofInt32Bytes = binary_type([0x83, 0x33, 0x33, 0x33])
- ofInt64Bytes = binary_type([0x84, 0x44, 0x44, 0x44,
- 0x44, 0x44, 0x44, 0x44])
- overflowingInt32Val = flatbuffers.encode.Get(flatbuffers.packer.int32,
- ofInt32Bytes, 0)
- overflowingInt64Val = flatbuffers.encode.Get(flatbuffers.packer.int64,
- ofInt64Bytes, 0)
+ different kinds of data in different combinations
+ """
- # Values we're testing against: chosen to ensure no bits get chopped
- # off anywhere, and also be different from eachother.
- boolVal = True
- int8Val = N.Int8Flags.py_type(-127) # 0x81
- uint8Val = N.Uint8Flags.py_type(0xFF)
- int16Val = N.Int16Flags.py_type(-32222) # 0x8222
- uint16Val = N.Uint16Flags.py_type(0xFEEE)
- int32Val = N.Int32Flags.py_type(overflowingInt32Val)
- uint32Val = N.Uint32Flags.py_type(0xFDDDDDDD)
- int64Val = N.Int64Flags.py_type(overflowingInt64Val)
- uint64Val = N.Uint64Flags.py_type(0xFCCCCCCCCCCCCCCC)
- # Python uses doubles, so force it here
- float32Val = N.Float32Flags.py_type(ctypes.c_float(3.14159).value)
- float64Val = N.Float64Flags.py_type(3.14159265359)
+ binary_type = compat.binary_types[0] # this will always exist
+ ofInt32Bytes = binary_type([0x83, 0x33, 0x33, 0x33])
+ ofInt64Bytes = binary_type([0x84, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44])
+ overflowingInt32Val = flatbuffers.encode.Get(flatbuffers.packer.int32,
+ ofInt32Bytes, 0)
+ overflowingInt64Val = flatbuffers.encode.Get(flatbuffers.packer.int64,
+ ofInt64Bytes, 0)
- def test_fuzz(self):
- return self.check_once(11, 100)
+ # Values we're testing against: chosen to ensure no bits get chopped
+ # off anywhere, and also be different from eachother.
+ boolVal = True
+ int8Val = N.Int8Flags.py_type(-127) # 0x81
+ uint8Val = N.Uint8Flags.py_type(0xFF)
+ int16Val = N.Int16Flags.py_type(-32222) # 0x8222
+ uint16Val = N.Uint16Flags.py_type(0xFEEE)
+ int32Val = N.Int32Flags.py_type(overflowingInt32Val)
+ uint32Val = N.Uint32Flags.py_type(0xFDDDDDDD)
+ int64Val = N.Int64Flags.py_type(overflowingInt64Val)
+ uint64Val = N.Uint64Flags.py_type(0xFCCCCCCCCCCCCCCC)
+ # Python uses doubles, so force it here
+ float32Val = N.Float32Flags.py_type(ctypes.c_float(3.14159).value)
+ float64Val = N.Float64Flags.py_type(3.14159265359)
- def check_once(self, fuzzFields, fuzzObjects):
- testValuesMax = 11 # hardcoded to the number of scalar types
+ def test_fuzz(self):
+ return self.check_once(11, 100)
- builder = flatbuffers.Builder(0)
- l = LCG()
+ def check_once(self, fuzzFields, fuzzObjects):
+ testValuesMax = 11 # hardcoded to the number of scalar types
- objects = [0 for _ in compat_range(fuzzObjects)]
+ builder = flatbuffers.Builder(0)
+ l = LCG()
- # Generate fuzzObjects random objects each consisting of
- # fuzzFields fields, each of a random type.
- for i in compat_range(fuzzObjects):
- builder.StartObject(fuzzFields)
+ objects = [0 for _ in compat_range(fuzzObjects)]
- for j in compat_range(fuzzFields):
- choice = int(l.Next()) % testValuesMax
- if choice == 0:
- builder.PrependBoolSlot(int(j), self.boolVal, False)
- elif choice == 1:
- builder.PrependInt8Slot(int(j), self.int8Val, 0)
- elif choice == 2:
- builder.PrependUint8Slot(int(j), self.uint8Val, 0)
- elif choice == 3:
- builder.PrependInt16Slot(int(j), self.int16Val, 0)
- elif choice == 4:
- builder.PrependUint16Slot(int(j), self.uint16Val, 0)
- elif choice == 5:
- builder.PrependInt32Slot(int(j), self.int32Val, 0)
- elif choice == 6:
- builder.PrependUint32Slot(int(j), self.uint32Val, 0)
- elif choice == 7:
- builder.PrependInt64Slot(int(j), self.int64Val, 0)
- elif choice == 8:
- builder.PrependUint64Slot(int(j), self.uint64Val, 0)
- elif choice == 9:
- builder.PrependFloat32Slot(int(j), self.float32Val, 0)
- elif choice == 10:
- builder.PrependFloat64Slot(int(j), self.float64Val, 0)
- else:
- raise RuntimeError('unreachable')
+ # Generate fuzzObjects random objects each consisting of
+ # fuzzFields fields, each of a random type.
+ for i in compat_range(fuzzObjects):
+ builder.StartObject(fuzzFields)
- off = builder.EndObject()
+ for j in compat_range(fuzzFields):
+ choice = int(l.Next()) % testValuesMax
+ if choice == 0:
+ builder.PrependBoolSlot(int(j), self.boolVal, False)
+ elif choice == 1:
+ builder.PrependInt8Slot(int(j), self.int8Val, 0)
+ elif choice == 2:
+ builder.PrependUint8Slot(int(j), self.uint8Val, 0)
+ elif choice == 3:
+ builder.PrependInt16Slot(int(j), self.int16Val, 0)
+ elif choice == 4:
+ builder.PrependUint16Slot(int(j), self.uint16Val, 0)
+ elif choice == 5:
+ builder.PrependInt32Slot(int(j), self.int32Val, 0)
+ elif choice == 6:
+ builder.PrependUint32Slot(int(j), self.uint32Val, 0)
+ elif choice == 7:
+ builder.PrependInt64Slot(int(j), self.int64Val, 0)
+ elif choice == 8:
+ builder.PrependUint64Slot(int(j), self.uint64Val, 0)
+ elif choice == 9:
+ builder.PrependFloat32Slot(int(j), self.float32Val, 0)
+ elif choice == 10:
+ builder.PrependFloat64Slot(int(j), self.float64Val, 0)
+ else:
+ raise RuntimeError('unreachable')
- # store the offset from the end of the builder buffer,
- # since it will keep growing:
- objects[i] = off
+ off = builder.EndObject()
- # Do some bookkeeping to generate stats on fuzzes:
- stats = defaultdict(int)
- def check(table, desc, want, got):
- stats[desc] += 1
- self.assertEqual(want, got, "%s != %s, %s" % (want, got, desc))
+ # store the offset from the end of the builder buffer,
+ # since it will keep growing:
+ objects[i] = off
- l = LCG() # Reset.
+ # Do some bookkeeping to generate stats on fuzzes:
+ stats = defaultdict(int)
- # Test that all objects we generated are readable and return the
- # expected values. We generate random objects in the same order
- # so this is deterministic.
- for i in compat_range(fuzzObjects):
+ def check(table, desc, want, got):
+ stats[desc] += 1
+ self.assertEqual(want, got, '%s != %s, %s' % (want, got, desc))
- table = flatbuffers.table.Table(builder.Bytes,
- len(builder.Bytes) - objects[i])
+ l = LCG() # Reset.
- for j in compat_range(fuzzFields):
- field_count = flatbuffers.builder.VtableMetadataFields + j
- f = N.VOffsetTFlags.py_type(field_count *
- N.VOffsetTFlags.bytewidth)
- choice = int(l.Next()) % testValuesMax
+ # Test that all objects we generated are readable and return the
+ # expected values. We generate random objects in the same order
+ # so this is deterministic.
+ for i in compat_range(fuzzObjects):
- if choice == 0:
- check(table, "bool", self.boolVal,
- table.GetSlot(f, False, N.BoolFlags))
- elif choice == 1:
- check(table, "int8", self.int8Val,
- table.GetSlot(f, 0, N.Int8Flags))
- elif choice == 2:
- check(table, "uint8", self.uint8Val,
- table.GetSlot(f, 0, N.Uint8Flags))
- elif choice == 3:
- check(table, "int16", self.int16Val,
- table.GetSlot(f, 0, N.Int16Flags))
- elif choice == 4:
- check(table, "uint16", self.uint16Val,
- table.GetSlot(f, 0, N.Uint16Flags))
- elif choice == 5:
- check(table, "int32", self.int32Val,
- table.GetSlot(f, 0, N.Int32Flags))
- elif choice == 6:
- check(table, "uint32", self.uint32Val,
- table.GetSlot(f, 0, N.Uint32Flags))
- elif choice == 7:
- check(table, "int64", self.int64Val,
- table.GetSlot(f, 0, N.Int64Flags))
- elif choice == 8:
- check(table, "uint64", self.uint64Val,
- table.GetSlot(f, 0, N.Uint64Flags))
- elif choice == 9:
- check(table, "float32", self.float32Val,
- table.GetSlot(f, 0, N.Float32Flags))
- elif choice == 10:
- check(table, "float64", self.float64Val,
- table.GetSlot(f, 0, N.Float64Flags))
- else:
- raise RuntimeError('unreachable')
+ table = flatbuffers.table.Table(builder.Bytes,
+ len(builder.Bytes) - objects[i])
- # If enough checks were made, verify that all scalar types were used:
- self.assertEqual(testValuesMax, len(stats),
- "fuzzing failed to test all scalar types: %s" % stats)
+ for j in compat_range(fuzzFields):
+ field_count = flatbuffers.builder.VtableMetadataFields + j
+ f = N.VOffsetTFlags.py_type(field_count * N.VOffsetTFlags.bytewidth)
+ choice = int(l.Next()) % testValuesMax
+
+ if choice == 0:
+ check(table, 'bool', self.boolVal,
+ table.GetSlot(f, False, N.BoolFlags))
+ elif choice == 1:
+ check(table, 'int8', self.int8Val, table.GetSlot(f, 0, N.Int8Flags))
+ elif choice == 2:
+ check(table, 'uint8', self.uint8Val,
+ table.GetSlot(f, 0, N.Uint8Flags))
+ elif choice == 3:
+ check(table, 'int16', self.int16Val,
+ table.GetSlot(f, 0, N.Int16Flags))
+ elif choice == 4:
+ check(table, 'uint16', self.uint16Val,
+ table.GetSlot(f, 0, N.Uint16Flags))
+ elif choice == 5:
+ check(table, 'int32', self.int32Val,
+ table.GetSlot(f, 0, N.Int32Flags))
+ elif choice == 6:
+ check(table, 'uint32', self.uint32Val,
+ table.GetSlot(f, 0, N.Uint32Flags))
+ elif choice == 7:
+ check(table, 'int64', self.int64Val,
+ table.GetSlot(f, 0, N.Int64Flags))
+ elif choice == 8:
+ check(table, 'uint64', self.uint64Val,
+ table.GetSlot(f, 0, N.Uint64Flags))
+ elif choice == 9:
+ check(table, 'float32', self.float32Val,
+ table.GetSlot(f, 0, N.Float32Flags))
+ elif choice == 10:
+ check(table, 'float64', self.float64Val,
+ table.GetSlot(f, 0, N.Float64Flags))
+ else:
+ raise RuntimeError('unreachable')
+
+ # If enough checks were made, verify that all scalar types were used:
+ self.assertEqual(testValuesMax, len(stats),
+ 'fuzzing failed to test all scalar types: %s' % stats)
class TestByteLayout(unittest.TestCase):
- ''' TestByteLayout checks the bytes of a Builder in various scenarios. '''
+ """ TestByteLayout checks the bytes of a Builder in various scenarios. """
- def assertBuilderEquals(self, builder, want_chars_or_ints):
- def integerize(x):
- if isinstance(x, compat.string_types):
- return ord(x)
- return x
+ def assertBuilderEquals(self, builder, want_chars_or_ints):
- want_ints = list(map(integerize, want_chars_or_ints))
- want = bytearray(want_ints)
- got = builder.Bytes[builder.Head():] # use the buffer directly
- self.assertEqual(want, got)
+ def integerize(x):
+ if isinstance(x, compat.string_types):
+ return ord(x)
+ return x
- def test_numbers(self):
- b = flatbuffers.Builder(0)
- self.assertBuilderEquals(b, [])
- b.PrependBool(True)
- self.assertBuilderEquals(b, [1])
- b.PrependInt8(-127)
- self.assertBuilderEquals(b, [129, 1])
- b.PrependUint8(255)
- self.assertBuilderEquals(b, [255, 129, 1])
- b.PrependInt16(-32222)
- self.assertBuilderEquals(b, [0x22, 0x82, 0, 255, 129, 1]) # first pad
- b.PrependUint16(0xFEEE)
- # no pad this time:
- self.assertBuilderEquals(b, [0xEE, 0xFE, 0x22, 0x82, 0, 255, 129, 1])
- b.PrependInt32(-53687092)
- self.assertBuilderEquals(b, [204, 204, 204, 252, 0xEE, 0xFE,
- 0x22, 0x82, 0, 255, 129, 1])
- b.PrependUint32(0x98765432)
- self.assertBuilderEquals(b, [0x32, 0x54, 0x76, 0x98,
- 204, 204, 204, 252,
- 0xEE, 0xFE, 0x22, 0x82,
- 0, 255, 129, 1])
+ want_ints = list(map(integerize, want_chars_or_ints))
+ want = bytearray(want_ints)
+ got = builder.Bytes[builder.Head():] # use the buffer directly
+ self.assertEqual(want, got)
- def test_numbers64(self):
- b = flatbuffers.Builder(0)
- b.PrependUint64(0x1122334455667788)
- self.assertBuilderEquals(b, [0x88, 0x77, 0x66, 0x55,
- 0x44, 0x33, 0x22, 0x11])
+ def test_numbers(self):
+ b = flatbuffers.Builder(0)
+ self.assertBuilderEquals(b, [])
+ b.PrependBool(True)
+ self.assertBuilderEquals(b, [1])
+ b.PrependInt8(-127)
+ self.assertBuilderEquals(b, [129, 1])
+ b.PrependUint8(255)
+ self.assertBuilderEquals(b, [255, 129, 1])
+ b.PrependInt16(-32222)
+ self.assertBuilderEquals(b, [0x22, 0x82, 0, 255, 129, 1]) # first pad
+ b.PrependUint16(0xFEEE)
+ # no pad this time:
+ self.assertBuilderEquals(b, [0xEE, 0xFE, 0x22, 0x82, 0, 255, 129, 1])
+ b.PrependInt32(-53687092)
+ self.assertBuilderEquals(
+ b, [204, 204, 204, 252, 0xEE, 0xFE, 0x22, 0x82, 0, 255, 129, 1])
+ b.PrependUint32(0x98765432)
+ self.assertBuilderEquals(b, [
+ 0x32, 0x54, 0x76, 0x98, 204, 204, 204, 252, 0xEE, 0xFE, 0x22, 0x82, 0,
+ 255, 129, 1
+ ])
- b = flatbuffers.Builder(0)
- b.PrependInt64(0x1122334455667788)
- self.assertBuilderEquals(b, [0x88, 0x77, 0x66, 0x55,
- 0x44, 0x33, 0x22, 0x11])
+ def test_numbers64(self):
+ b = flatbuffers.Builder(0)
+ b.PrependUint64(0x1122334455667788)
+ self.assertBuilderEquals(b,
+ [0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11])
- def test_1xbyte_vector(self):
- b = flatbuffers.Builder(0)
- self.assertBuilderEquals(b, [])
- b.StartVector(flatbuffers.number_types.Uint8Flags.bytewidth, 1, 1)
- self.assertBuilderEquals(b, [0, 0, 0]) # align to 4bytes
- b.PrependByte(1)
- self.assertBuilderEquals(b, [1, 0, 0, 0])
- b.EndVector(1)
- self.assertBuilderEquals(b, [1, 0, 0, 0, 1, 0, 0, 0]) # padding
+ b = flatbuffers.Builder(0)
+ b.PrependInt64(0x1122334455667788)
+ self.assertBuilderEquals(b,
+ [0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11])
- def test_2xbyte_vector(self):
- b = flatbuffers.Builder(0)
- b.StartVector(flatbuffers.number_types.Uint8Flags.bytewidth, 2, 1)
- self.assertBuilderEquals(b, [0, 0]) # align to 4bytes
- b.PrependByte(1)
- self.assertBuilderEquals(b, [1, 0, 0])
- b.PrependByte(2)
- self.assertBuilderEquals(b, [2, 1, 0, 0])
- b.EndVector(2)
- self.assertBuilderEquals(b, [2, 0, 0, 0, 2, 1, 0, 0]) # padding
+ def test_1xbyte_vector(self):
+ b = flatbuffers.Builder(0)
+ self.assertBuilderEquals(b, [])
+ b.StartVector(flatbuffers.number_types.Uint8Flags.bytewidth, 1, 1)
+ self.assertBuilderEquals(b, [0, 0, 0]) # align to 4bytes
+ b.PrependByte(1)
+ self.assertBuilderEquals(b, [1, 0, 0, 0])
+ b.EndVector()
+ self.assertBuilderEquals(b, [1, 0, 0, 0, 1, 0, 0, 0]) # padding
- def test_1xuint16_vector(self):
- b = flatbuffers.Builder(0)
- b.StartVector(flatbuffers.number_types.Uint16Flags.bytewidth, 1, 1)
- self.assertBuilderEquals(b, [0, 0]) # align to 4bytes
- b.PrependUint16(1)
- self.assertBuilderEquals(b, [1, 0, 0, 0])
- b.EndVector(1)
- self.assertBuilderEquals(b, [1, 0, 0, 0, 1, 0, 0, 0]) # padding
+ def test_2xbyte_vector(self):
+ b = flatbuffers.Builder(0)
+ b.StartVector(flatbuffers.number_types.Uint8Flags.bytewidth, 2, 1)
+ self.assertBuilderEquals(b, [0, 0]) # align to 4bytes
+ b.PrependByte(1)
+ self.assertBuilderEquals(b, [1, 0, 0])
+ b.PrependByte(2)
+ self.assertBuilderEquals(b, [2, 1, 0, 0])
+ b.EndVector()
+ self.assertBuilderEquals(b, [2, 0, 0, 0, 2, 1, 0, 0]) # padding
- def test_2xuint16_vector(self):
- b = flatbuffers.Builder(0)
- b.StartVector(flatbuffers.number_types.Uint16Flags.bytewidth, 2, 1)
- self.assertBuilderEquals(b, []) # align to 4bytes
- b.PrependUint16(0xABCD)
- self.assertBuilderEquals(b, [0xCD, 0xAB])
- b.PrependUint16(0xDCBA)
- self.assertBuilderEquals(b, [0xBA, 0xDC, 0xCD, 0xAB])
- b.EndVector(2)
- self.assertBuilderEquals(b, [2, 0, 0, 0, 0xBA, 0xDC, 0xCD, 0xAB])
+ def test_1xuint16_vector(self):
+ b = flatbuffers.Builder(0)
+ b.StartVector(flatbuffers.number_types.Uint16Flags.bytewidth, 1, 1)
+ self.assertBuilderEquals(b, [0, 0]) # align to 4bytes
+ b.PrependUint16(1)
+ self.assertBuilderEquals(b, [1, 0, 0, 0])
+ b.EndVector()
+ self.assertBuilderEquals(b, [1, 0, 0, 0, 1, 0, 0, 0]) # padding
- def test_create_ascii_string(self):
- b = flatbuffers.Builder(0)
- b.CreateString(u"foo", encoding='ascii')
+ def test_2xuint16_vector(self):
+ b = flatbuffers.Builder(0)
+ b.StartVector(flatbuffers.number_types.Uint16Flags.bytewidth, 2, 1)
+ self.assertBuilderEquals(b, []) # align to 4bytes
+ b.PrependUint16(0xABCD)
+ self.assertBuilderEquals(b, [0xCD, 0xAB])
+ b.PrependUint16(0xDCBA)
+ self.assertBuilderEquals(b, [0xBA, 0xDC, 0xCD, 0xAB])
+ b.EndVector()
+ self.assertBuilderEquals(b, [2, 0, 0, 0, 0xBA, 0xDC, 0xCD, 0xAB])
- # 0-terminated, no pad:
- self.assertBuilderEquals(b, [3, 0, 0, 0, 'f', 'o', 'o', 0])
- b.CreateString(u"moop", encoding='ascii')
- # 0-terminated, 3-byte pad:
- self.assertBuilderEquals(b, [4, 0, 0, 0, 'm', 'o', 'o', 'p',
- 0, 0, 0, 0,
- 3, 0, 0, 0, 'f', 'o', 'o', 0])
+ def test_create_ascii_string(self):
+ b = flatbuffers.Builder(0)
+ b.CreateString(u'foo', encoding='ascii')
- def test_create_utf8_string(self):
- b = flatbuffers.Builder(0)
- b.CreateString(u"Цлїςσδε")
- self.assertBuilderEquals(b, "\x0e\x00\x00\x00\xd0\xa6\xd0\xbb\xd1\x97" \
- "\xcf\x82\xcf\x83\xce\xb4\xce\xb5\x00\x00")
+ # 0-terminated, no pad:
+ self.assertBuilderEquals(b, [3, 0, 0, 0, 'f', 'o', 'o', 0])
+ b.CreateString(u'moop', encoding='ascii')
+ # 0-terminated, 3-byte pad:
+ self.assertBuilderEquals(b, [
+ 4, 0, 0, 0, 'm', 'o', 'o', 'p', 0, 0, 0, 0, 3, 0, 0, 0, 'f', 'o', 'o', 0
+ ])
- b.CreateString(u"フムアムカモケモ")
- self.assertBuilderEquals(b, "\x18\x00\x00\x00\xef\xbe\x8c\xef\xbe\x91" \
- "\xef\xbd\xb1\xef\xbe\x91\xef\xbd\xb6\xef\xbe\x93\xef\xbd\xb9\xef" \
- "\xbe\x93\x00\x00\x00\x00\x0e\x00\x00\x00\xd0\xa6\xd0\xbb\xd1\x97" \
- "\xcf\x82\xcf\x83\xce\xb4\xce\xb5\x00\x00")
+ def test_create_utf8_string(self):
+ b = flatbuffers.Builder(0)
+ b.CreateString(u'Цлїςσδε')
+ self.assertBuilderEquals(b, '\x0e\x00\x00\x00\xd0\xa6\xd0\xbb\xd1\x97' \
+ '\xcf\x82\xcf\x83\xce\xb4\xce\xb5\x00\x00')
- def test_create_arbitrary_string(self):
- b = flatbuffers.Builder(0)
- s = "\x01\x02\x03"
- b.CreateString(s) # Default encoding is utf-8.
- # 0-terminated, no pad:
- self.assertBuilderEquals(b, [3, 0, 0, 0, 1, 2, 3, 0])
- s2 = "\x04\x05\x06\x07"
- b.CreateString(s2) # Default encoding is utf-8.
- # 0-terminated, 3-byte pad:
- self.assertBuilderEquals(b, [4, 0, 0, 0, 4, 5, 6, 7, 0, 0, 0, 0,
- 3, 0, 0, 0, 1, 2, 3, 0])
+ b.CreateString(u'フムアムカモケモ')
+ self.assertBuilderEquals(b, '\x18\x00\x00\x00\xef\xbe\x8c\xef\xbe\x91' \
+ '\xef\xbd\xb1\xef\xbe\x91\xef\xbd\xb6\xef\xbe\x93\xef\xbd\xb9\xef' \
+ '\xbe\x93\x00\x00\x00\x00\x0e\x00\x00\x00\xd0\xa6\xd0\xbb\xd1\x97' \
+ '\xcf\x82\xcf\x83\xce\xb4\xce\xb5\x00\x00')
- def test_create_byte_vector(self):
- b = flatbuffers.Builder(0)
- b.CreateByteVector(b"")
- # 0-byte pad:
- self.assertBuilderEquals(b, [0, 0, 0, 0])
+ def test_create_arbitrary_string(self):
+ b = flatbuffers.Builder(0)
+ s = '\x01\x02\x03'
+ b.CreateString(s) # Default encoding is utf-8.
+ # 0-terminated, no pad:
+ self.assertBuilderEquals(b, [3, 0, 0, 0, 1, 2, 3, 0])
+ s2 = '\x04\x05\x06\x07'
+ b.CreateString(s2) # Default encoding is utf-8.
+ # 0-terminated, 3-byte pad:
+ self.assertBuilderEquals(
+ b, [4, 0, 0, 0, 4, 5, 6, 7, 0, 0, 0, 0, 3, 0, 0, 0, 1, 2, 3, 0])
- b = flatbuffers.Builder(0)
- b.CreateByteVector(b"\x01\x02\x03")
- # 1-byte pad:
- self.assertBuilderEquals(b, [3, 0, 0, 0, 1, 2, 3, 0])
+ def test_create_byte_vector(self):
+ b = flatbuffers.Builder(0)
+ b.CreateByteVector(b'')
+ # 0-byte pad:
+ self.assertBuilderEquals(b, [0, 0, 0, 0])
- def test_create_numpy_vector_int8(self):
- try:
- imp.find_module('numpy')
- # if numpy exists, then we should be able to get the
- # vector as a numpy array
- import numpy as np
+ b = flatbuffers.Builder(0)
+ b.CreateByteVector(b'\x01\x02\x03')
+ # 1-byte pad:
+ self.assertBuilderEquals(b, [3, 0, 0, 0, 1, 2, 3, 0])
- # Systems endian:
- b = flatbuffers.Builder(0)
- x = np.array([1, 2, -3], dtype=np.int8)
- b.CreateNumpyVector(x)
- self.assertBuilderEquals(b, [
- 3, 0, 0, 0, # vector length
- 1, 2, 256 - 3, 0 # vector value + padding
- ])
+ def test_create_numpy_vector_int8(self):
+ try:
+ imp.find_module('numpy')
+ # if numpy exists, then we should be able to get the
+ # vector as a numpy array
+ import numpy as np
- # Reverse endian:
- b = flatbuffers.Builder(0)
- x_other_endian = x.byteswap().newbyteorder()
- b.CreateNumpyVector(x_other_endian)
- self.assertBuilderEquals(b, [
- 3, 0, 0, 0, # vector length
- 1, 2, 256 - 3, 0 # vector value + padding
- ])
- except ImportError:
- b = flatbuffers.Builder(0)
- x = 0
- assertRaises(
- self,
- lambda: b.CreateNumpyVector(x),
- NumpyRequiredForThisFeature)
+ # Systems endian:
+ b = flatbuffers.Builder(0)
+ x = np.array([1, 2, -3], dtype=np.int8)
+ b.CreateNumpyVector(x)
+ self.assertBuilderEquals(
+ b,
+ [
+ 3,
+ 0,
+ 0,
+ 0, # vector length
+ 1,
+ 2,
+ 256 - 3,
+ 0 # vector value + padding
+ ])
- def test_create_numpy_vector_uint16(self):
- try:
- imp.find_module('numpy')
- # if numpy exists, then we should be able to get the
- # vector as a numpy array
- import numpy as np
+ # Reverse endian:
+ b = flatbuffers.Builder(0)
+ x_other_endian = x.byteswap().newbyteorder()
+ b.CreateNumpyVector(x_other_endian)
+ self.assertBuilderEquals(
+ b,
+ [
+ 3,
+ 0,
+ 0,
+ 0, # vector length
+ 1,
+ 2,
+ 256 - 3,
+ 0 # vector value + padding
+ ])
+ except ImportError:
+ b = flatbuffers.Builder(0)
+ x = 0
+ assertRaises(self, lambda: b.CreateNumpyVector(x),
+ NumpyRequiredForThisFeature)
- # Systems endian:
- b = flatbuffers.Builder(0)
- x = np.array([1, 2, 312], dtype=np.uint16)
- b.CreateNumpyVector(x)
- self.assertBuilderEquals(b, [
- 3, 0, 0, 0, # vector length
- 1, 0, # 1
- 2, 0, # 2
- 312 - 256, 1, # 312
- 0, 0 # padding
- ])
+ def test_create_numpy_vector_uint16(self):
+ try:
+ imp.find_module('numpy')
+ # if numpy exists, then we should be able to get the
+ # vector as a numpy array
+ import numpy as np
- # Reverse endian:
- b = flatbuffers.Builder(0)
- x_other_endian = x.byteswap().newbyteorder()
- b.CreateNumpyVector(x_other_endian)
- self.assertBuilderEquals(b, [
- 3, 0, 0, 0, # vector length
- 1, 0, # 1
- 2, 0, # 2
- 312 - 256, 1, # 312
- 0, 0 # padding
- ])
- except ImportError:
- b = flatbuffers.Builder(0)
- x = 0
- assertRaises(
- self,
- lambda: b.CreateNumpyVector(x),
- NumpyRequiredForThisFeature)
+ # Systems endian:
+ b = flatbuffers.Builder(0)
+ x = np.array([1, 2, 312], dtype=np.uint16)
+ b.CreateNumpyVector(x)
+ self.assertBuilderEquals(
+ b,
+ [
+ 3,
+ 0,
+ 0,
+ 0, # vector length
+ 1,
+ 0, # 1
+ 2,
+ 0, # 2
+ 312 - 256,
+ 1, # 312
+ 0,
+ 0 # padding
+ ])
- def test_create_numpy_vector_int64(self):
- try:
- imp.find_module('numpy')
- # if numpy exists, then we should be able to get the
- # vector as a numpy array
- import numpy as np
+ # Reverse endian:
+ b = flatbuffers.Builder(0)
+ x_other_endian = x.byteswap().newbyteorder()
+ b.CreateNumpyVector(x_other_endian)
+ self.assertBuilderEquals(
+ b,
+ [
+ 3,
+ 0,
+ 0,
+ 0, # vector length
+ 1,
+ 0, # 1
+ 2,
+ 0, # 2
+ 312 - 256,
+ 1, # 312
+ 0,
+ 0 # padding
+ ])
+ except ImportError:
+ b = flatbuffers.Builder(0)
+ x = 0
+ assertRaises(self, lambda: b.CreateNumpyVector(x),
+ NumpyRequiredForThisFeature)
- # Systems endian:
- b = flatbuffers.Builder(0)
- x = np.array([1, 2, -12], dtype=np.int64)
- b.CreateNumpyVector(x)
- self.assertBuilderEquals(b, [
- 3, 0, 0, 0, # vector length
- 1, 0, 0, 0, 0, 0, 0, 0, # 1
- 2, 0, 0, 0, 0, 0, 0, 0, # 2
- 256 - 12, 255, 255, 255, 255, 255, 255, 255 # -12
- ])
+ def test_create_numpy_vector_int64(self):
+ try:
+ imp.find_module('numpy')
+ # if numpy exists, then we should be able to get the
+ # vector as a numpy array
+ import numpy as np
- # Reverse endian:
- b = flatbuffers.Builder(0)
- x_other_endian = x.byteswap().newbyteorder()
- b.CreateNumpyVector(x_other_endian)
- self.assertBuilderEquals(b, [
- 3, 0, 0, 0, # vector length
- 1, 0, 0, 0, 0, 0, 0, 0, # 1
- 2, 0, 0, 0, 0, 0, 0, 0, # 2
- 256 - 12, 255, 255, 255, 255, 255, 255, 255 # -12
- ])
+ # Systems endian:
+ b = flatbuffers.Builder(0)
+ x = np.array([1, 2, -12], dtype=np.int64)
+ b.CreateNumpyVector(x)
+ self.assertBuilderEquals(
+ b,
+ [
+ 3,
+ 0,
+ 0,
+ 0, # vector length
+ 1,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0, # 1
+ 2,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0, # 2
+ 256 - 12,
+ 255,
+ 255,
+ 255,
+ 255,
+ 255,
+ 255,
+ 255 # -12
+ ])
- except ImportError:
- b = flatbuffers.Builder(0)
- x = 0
- assertRaises(
- self,
- lambda: b.CreateNumpyVector(x),
- NumpyRequiredForThisFeature)
+ # Reverse endian:
+ b = flatbuffers.Builder(0)
+ x_other_endian = x.byteswap().newbyteorder()
+ b.CreateNumpyVector(x_other_endian)
+ self.assertBuilderEquals(
+ b,
+ [
+ 3,
+ 0,
+ 0,
+ 0, # vector length
+ 1,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0, # 1
+ 2,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0, # 2
+ 256 - 12,
+ 255,
+ 255,
+ 255,
+ 255,
+ 255,
+ 255,
+ 255 # -12
+ ])
- def test_create_numpy_vector_float32(self):
- try:
- imp.find_module('numpy')
- # if numpy exists, then we should be able to get the
- # vector as a numpy array
- import numpy as np
+ except ImportError:
+ b = flatbuffers.Builder(0)
+ x = 0
+ assertRaises(self, lambda: b.CreateNumpyVector(x),
+ NumpyRequiredForThisFeature)
- # Systems endian:
- b = flatbuffers.Builder(0)
- x = np.array([1, 2, -12], dtype=np.float32)
- b.CreateNumpyVector(x)
- self.assertBuilderEquals(b, [
- 3, 0, 0, 0, # vector length
- 0, 0, 128, 63, # 1
- 0, 0, 0, 64, # 2
- 0, 0, 64, 193 # -12
- ])
+ def test_create_numpy_vector_float32(self):
+ try:
+ imp.find_module('numpy')
+ # if numpy exists, then we should be able to get the
+ # vector as a numpy array
+ import numpy as np
- # Reverse endian:
- b = flatbuffers.Builder(0)
- x_other_endian = x.byteswap().newbyteorder()
- b.CreateNumpyVector(x_other_endian)
- self.assertBuilderEquals(b, [
- 3, 0, 0, 0, # vector length
- 0, 0, 128, 63, # 1
- 0, 0, 0, 64, # 2
- 0, 0, 64, 193 # -12
- ])
+ # Systems endian:
+ b = flatbuffers.Builder(0)
+ x = np.array([1, 2, -12], dtype=np.float32)
+ b.CreateNumpyVector(x)
+ self.assertBuilderEquals(
+ b,
+ [
+ 3,
+ 0,
+ 0,
+ 0, # vector length
+ 0,
+ 0,
+ 128,
+ 63, # 1
+ 0,
+ 0,
+ 0,
+ 64, # 2
+ 0,
+ 0,
+ 64,
+ 193 # -12
+ ])
- except ImportError:
- b = flatbuffers.Builder(0)
- x = 0
- assertRaises(
- self,
- lambda: b.CreateNumpyVector(x),
- NumpyRequiredForThisFeature)
+ # Reverse endian:
+ b = flatbuffers.Builder(0)
+ x_other_endian = x.byteswap().newbyteorder()
+ b.CreateNumpyVector(x_other_endian)
+ self.assertBuilderEquals(
+ b,
+ [
+ 3,
+ 0,
+ 0,
+ 0, # vector length
+ 0,
+ 0,
+ 128,
+ 63, # 1
+ 0,
+ 0,
+ 0,
+ 64, # 2
+ 0,
+ 0,
+ 64,
+ 193 # -12
+ ])
- def test_create_numpy_vector_float64(self):
- try:
- imp.find_module('numpy')
- # if numpy exists, then we should be able to get the
- # vector as a numpy array
- import numpy as np
+ except ImportError:
+ b = flatbuffers.Builder(0)
+ x = 0
+ assertRaises(self, lambda: b.CreateNumpyVector(x),
+ NumpyRequiredForThisFeature)
- # Systems endian:
- b = flatbuffers.Builder(0)
- x = np.array([1, 2, -12], dtype=np.float64)
- b.CreateNumpyVector(x)
- self.assertBuilderEquals(b, [
- 3, 0, 0, 0, # vector length
- 0, 0, 0, 0, 0, 0, 240, 63, # 1
- 0, 0, 0, 0, 0, 0, 0, 64, # 2
- 0, 0, 0, 0, 0, 0, 40, 192 # -12
- ])
+ def test_create_numpy_vector_float64(self):
+ try:
+ imp.find_module('numpy')
+ # if numpy exists, then we should be able to get the
+ # vector as a numpy array
+ import numpy as np
- # Reverse endian:
- b = flatbuffers.Builder(0)
- x_other_endian = x.byteswap().newbyteorder()
- b.CreateNumpyVector(x_other_endian)
- self.assertBuilderEquals(b, [
- 3, 0, 0, 0, # vector length
- 0, 0, 0, 0, 0, 0, 240, 63, # 1
- 0, 0, 0, 0, 0, 0, 0, 64, # 2
- 0, 0, 0, 0, 0, 0, 40, 192 # -12
- ])
+ # Systems endian:
+ b = flatbuffers.Builder(0)
+ x = np.array([1, 2, -12], dtype=np.float64)
+ b.CreateNumpyVector(x)
+ self.assertBuilderEquals(
+ b,
+ [
+ 3,
+ 0,
+ 0,
+ 0, # vector length
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 240,
+ 63, # 1
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 64, # 2
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 40,
+ 192 # -12
+ ])
- except ImportError:
- b = flatbuffers.Builder(0)
- x = 0
- assertRaises(
- self,
- lambda: b.CreateNumpyVector(x),
- NumpyRequiredForThisFeature)
+ # Reverse endian:
+ b = flatbuffers.Builder(0)
+ x_other_endian = x.byteswap().newbyteorder()
+ b.CreateNumpyVector(x_other_endian)
+ self.assertBuilderEquals(
+ b,
+ [
+ 3,
+ 0,
+ 0,
+ 0, # vector length
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 240,
+ 63, # 1
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 64, # 2
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 40,
+ 192 # -12
+ ])
- def test_create_numpy_vector_bool(self):
- try:
- imp.find_module('numpy')
- # if numpy exists, then we should be able to get the
- # vector as a numpy array
- import numpy as np
+ except ImportError:
+ b = flatbuffers.Builder(0)
+ x = 0
+ assertRaises(self, lambda: b.CreateNumpyVector(x),
+ NumpyRequiredForThisFeature)
- # Systems endian:
- b = flatbuffers.Builder(0)
- x = np.array([True, False, True], dtype=np.bool)
- b.CreateNumpyVector(x)
- self.assertBuilderEquals(b, [
- 3, 0, 0, 0, # vector length
- 1, 0, 1, 0 # vector values + padding
- ])
+ def test_create_numpy_vector_bool(self):
+ try:
+ imp.find_module('numpy')
+ # if numpy exists, then we should be able to get the
+ # vector as a numpy array
+ import numpy as np
- # Reverse endian:
- b = flatbuffers.Builder(0)
- x_other_endian = x.byteswap().newbyteorder()
- b.CreateNumpyVector(x_other_endian)
- self.assertBuilderEquals(b, [
- 3, 0, 0, 0, # vector length
- 1, 0, 1, 0 # vector values + padding
- ])
+ # Systems endian:
+ b = flatbuffers.Builder(0)
+ x = np.array([True, False, True], dtype=np.bool)
+ b.CreateNumpyVector(x)
+ self.assertBuilderEquals(
+ b,
+ [
+ 3,
+ 0,
+ 0,
+ 0, # vector length
+ 1,
+ 0,
+ 1,
+ 0 # vector values + padding
+ ])
- except ImportError:
- b = flatbuffers.Builder(0)
- x = 0
- assertRaises(
- self,
- lambda: b.CreateNumpyVector(x),
- NumpyRequiredForThisFeature)
+ # Reverse endian:
+ b = flatbuffers.Builder(0)
+ x_other_endian = x.byteswap().newbyteorder()
+ b.CreateNumpyVector(x_other_endian)
+ self.assertBuilderEquals(
+ b,
+ [
+ 3,
+ 0,
+ 0,
+ 0, # vector length
+ 1,
+ 0,
+ 1,
+ 0 # vector values + padding
+ ])
- def test_create_numpy_vector_reject_strings(self):
- try:
- imp.find_module('numpy')
- # if numpy exists, then we should be able to get the
- # vector as a numpy array
- import numpy as np
+ except ImportError:
+ b = flatbuffers.Builder(0)
+ x = 0
+ assertRaises(self, lambda: b.CreateNumpyVector(x),
+ NumpyRequiredForThisFeature)
- # Create String array
- b = flatbuffers.Builder(0)
- x = np.array(["hello", "fb", "testing"])
- assertRaises(
- self,
- lambda: b.CreateNumpyVector(x),
- TypeError)
+ def test_create_numpy_vector_reject_strings(self):
+ try:
+ imp.find_module('numpy')
+ # if numpy exists, then we should be able to get the
+ # vector as a numpy array
+ import numpy as np
- except ImportError:
- b = flatbuffers.Builder(0)
- x = 0
- assertRaises(
- self,
- lambda: b.CreateNumpyVector(x),
- NumpyRequiredForThisFeature)
+ # Create String array
+ b = flatbuffers.Builder(0)
+ x = np.array(['hello', 'fb', 'testing'])
+ assertRaises(self, lambda: b.CreateNumpyVector(x), TypeError)
- def test_create_numpy_vector_reject_object(self):
- try:
- imp.find_module('numpy')
- # if numpy exists, then we should be able to get the
- # vector as a numpy array
- import numpy as np
+ except ImportError:
+ b = flatbuffers.Builder(0)
+ x = 0
+ assertRaises(self, lambda: b.CreateNumpyVector(x),
+ NumpyRequiredForThisFeature)
- # Create String array
- b = flatbuffers.Builder(0)
- x = np.array([{"m": 0}, {"as": -2.1, 'c': 'c'}])
- assertRaises(
- self,
- lambda: b.CreateNumpyVector(x),
- TypeError)
+ def test_create_numpy_vector_reject_object(self):
+ try:
+ imp.find_module('numpy')
+ # if numpy exists, then we should be able to get the
+ # vector as a numpy array
+ import numpy as np
- except ImportError:
- b = flatbuffers.Builder(0)
- x = 0
- assertRaises(
- self,
- lambda: b.CreateNumpyVector(x),
- NumpyRequiredForThisFeature)
+ # Create String array
+ b = flatbuffers.Builder(0)
+ x = np.array([{'m': 0}, {'as': -2.1, 'c': 'c'}])
+ assertRaises(self, lambda: b.CreateNumpyVector(x), TypeError)
- def test_empty_vtable(self):
- b = flatbuffers.Builder(0)
- b.StartObject(0)
- self.assertBuilderEquals(b, [])
- b.EndObject()
- self.assertBuilderEquals(b, [4, 0, 4, 0, 4, 0, 0, 0])
+ except ImportError:
+ b = flatbuffers.Builder(0)
+ x = 0
+ assertRaises(self, lambda: b.CreateNumpyVector(x),
+ NumpyRequiredForThisFeature)
- def test_vtable_with_one_true_bool(self):
- b = flatbuffers.Builder(0)
- self.assertBuilderEquals(b, [])
- b.StartObject(1)
- self.assertBuilderEquals(b, [])
- b.PrependBoolSlot(0, True, False)
- b.EndObject()
- self.assertBuilderEquals(b, [
- 6, 0, # vtable bytes
- 8, 0, # length of object including vtable offset
- 7, 0, # start of bool value
- 6, 0, 0, 0, # offset for start of vtable (int32)
- 0, 0, 0, # padded to 4 bytes
+ def test_empty_vtable(self):
+ b = flatbuffers.Builder(0)
+ b.StartObject(0)
+ self.assertBuilderEquals(b, [])
+ b.EndObject()
+ self.assertBuilderEquals(b, [4, 0, 4, 0, 4, 0, 0, 0])
+
+ def test_vtable_with_one_true_bool(self):
+ b = flatbuffers.Builder(0)
+ self.assertBuilderEquals(b, [])
+ b.StartObject(1)
+ self.assertBuilderEquals(b, [])
+ b.PrependBoolSlot(0, True, False)
+ b.EndObject()
+ self.assertBuilderEquals(
+ b,
+ [
+ 6,
+ 0, # vtable bytes
+ 8,
+ 0, # length of object including vtable offset
+ 7,
+ 0, # start of bool value
+ 6,
+ 0,
+ 0,
+ 0, # offset for start of vtable (int32)
+ 0,
+ 0,
+ 0, # padded to 4 bytes
1, # bool value
])
- def test_vtable_with_one_default_bool(self):
- b = flatbuffers.Builder(0)
- self.assertBuilderEquals(b, [])
- b.StartObject(1)
- self.assertBuilderEquals(b, [])
- b.PrependBoolSlot(0, False, False)
- b.EndObject()
- self.assertBuilderEquals(b, [
- 4, 0, # vtable bytes
- 4, 0, # end of object from here
+ def test_vtable_with_one_default_bool(self):
+ b = flatbuffers.Builder(0)
+ self.assertBuilderEquals(b, [])
+ b.StartObject(1)
+ self.assertBuilderEquals(b, [])
+ b.PrependBoolSlot(0, False, False)
+ b.EndObject()
+ self.assertBuilderEquals(
+ b,
+ [
+ 4,
+ 0, # vtable bytes
+ 4,
+ 0, # end of object from here
# entry 1 is zero and not stored
- 4, 0, 0, 0, # offset for start of vtable (int32)
+ 4,
+ 0,
+ 0,
+ 0, # offset for start of vtable (int32)
])
- def test_vtable_with_one_int16(self):
- b = flatbuffers.Builder(0)
- b.StartObject(1)
- b.PrependInt16Slot(0, 0x789A, 0)
- b.EndObject()
- self.assertBuilderEquals(b, [
- 6, 0, # vtable bytes
- 8, 0, # end of object from here
- 6, 0, # offset to value
- 6, 0, 0, 0, # offset for start of vtable (int32)
- 0, 0, # padding to 4 bytes
- 0x9A, 0x78,
+ def test_vtable_with_one_int16(self):
+ b = flatbuffers.Builder(0)
+ b.StartObject(1)
+ b.PrependInt16Slot(0, 0x789A, 0)
+ b.EndObject()
+ self.assertBuilderEquals(
+ b,
+ [
+ 6,
+ 0, # vtable bytes
+ 8,
+ 0, # end of object from here
+ 6,
+ 0, # offset to value
+ 6,
+ 0,
+ 0,
+ 0, # offset for start of vtable (int32)
+ 0,
+ 0, # padding to 4 bytes
+ 0x9A,
+ 0x78,
])
- def test_vtable_with_two_int16(self):
- b = flatbuffers.Builder(0)
- b.StartObject(2)
- b.PrependInt16Slot(0, 0x3456, 0)
- b.PrependInt16Slot(1, 0x789A, 0)
- b.EndObject()
- self.assertBuilderEquals(b, [
- 8, 0, # vtable bytes
- 8, 0, # end of object from here
- 6, 0, # offset to value 0
- 4, 0, # offset to value 1
- 8, 0, 0, 0, # offset for start of vtable (int32)
- 0x9A, 0x78, # value 1
- 0x56, 0x34, # value 0
+ def test_vtable_with_two_int16(self):
+ b = flatbuffers.Builder(0)
+ b.StartObject(2)
+ b.PrependInt16Slot(0, 0x3456, 0)
+ b.PrependInt16Slot(1, 0x789A, 0)
+ b.EndObject()
+ self.assertBuilderEquals(
+ b,
+ [
+ 8,
+ 0, # vtable bytes
+ 8,
+ 0, # end of object from here
+ 6,
+ 0, # offset to value 0
+ 4,
+ 0, # offset to value 1
+ 8,
+ 0,
+ 0,
+ 0, # offset for start of vtable (int32)
+ 0x9A,
+ 0x78, # value 1
+ 0x56,
+ 0x34, # value 0
])
- def test_vtable_with_int16_and_bool(self):
- b = flatbuffers.Builder(0)
- b.StartObject(2)
- b.PrependInt16Slot(0, 0x3456, 0)
- b.PrependBoolSlot(1, True, False)
- b.EndObject()
- self.assertBuilderEquals(b, [
- 8, 0, # vtable bytes
- 8, 0, # end of object from here
- 6, 0, # offset to value 0
- 5, 0, # offset to value 1
- 8, 0, 0, 0, # offset for start of vtable (int32)
- 0, # padding
- 1, # value 1
- 0x56, 0x34, # value 0
+ def test_vtable_with_int16_and_bool(self):
+ b = flatbuffers.Builder(0)
+ b.StartObject(2)
+ b.PrependInt16Slot(0, 0x3456, 0)
+ b.PrependBoolSlot(1, True, False)
+ b.EndObject()
+ self.assertBuilderEquals(
+ b,
+ [
+ 8,
+ 0, # vtable bytes
+ 8,
+ 0, # end of object from here
+ 6,
+ 0, # offset to value 0
+ 5,
+ 0, # offset to value 1
+ 8,
+ 0,
+ 0,
+ 0, # offset for start of vtable (int32)
+ 0, # padding
+ 1, # value 1
+ 0x56,
+ 0x34, # value 0
])
- def test_vtable_with_empty_vector(self):
- b = flatbuffers.Builder(0)
- b.StartVector(flatbuffers.number_types.Uint8Flags.bytewidth, 0, 1)
- vecend = b.EndVector(0)
- b.StartObject(1)
- b.PrependUOffsetTRelativeSlot(0, vecend, 0)
- b.EndObject()
- self.assertBuilderEquals(b, [
- 6, 0, # vtable bytes
- 8, 0,
- 4, 0, # offset to vector offset
- 6, 0, 0, 0, # offset for start of vtable (int32)
- 4, 0, 0, 0,
- 0, 0, 0, 0, # length of vector (not in struct)
+ def test_vtable_with_empty_vector(self):
+ b = flatbuffers.Builder(0)
+ b.StartVector(flatbuffers.number_types.Uint8Flags.bytewidth, 0, 1)
+ vecend = b.EndVector()
+ b.StartObject(1)
+ b.PrependUOffsetTRelativeSlot(0, vecend, 0)
+ b.EndObject()
+ self.assertBuilderEquals(
+ b,
+ [
+ 6,
+ 0, # vtable bytes
+ 8,
+ 0,
+ 4,
+ 0, # offset to vector offset
+ 6,
+ 0,
+ 0,
+ 0, # offset for start of vtable (int32)
+ 4,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0, # length of vector (not in struct)
])
- def test_vtable_with_empty_vector_of_byte_and_some_scalars(self):
- b = flatbuffers.Builder(0)
- b.StartVector(flatbuffers.number_types.Uint8Flags.bytewidth, 0, 1)
- vecend = b.EndVector(0)
- b.StartObject(2)
- b.PrependInt16Slot(0, 55, 0)
- b.PrependUOffsetTRelativeSlot(1, vecend, 0)
- b.EndObject()
- self.assertBuilderEquals(b, [
- 8, 0, # vtable bytes
- 12, 0,
- 10, 0, # offset to value 0
- 4, 0, # offset to vector offset
- 8, 0, 0, 0, # vtable loc
- 8, 0, 0, 0, # value 1
- 0, 0, 55, 0, # value 0
-
- 0, 0, 0, 0, # length of vector (not in struct)
+ def test_vtable_with_empty_vector_of_byte_and_some_scalars(self):
+ b = flatbuffers.Builder(0)
+ b.StartVector(flatbuffers.number_types.Uint8Flags.bytewidth, 0, 1)
+ vecend = b.EndVector()
+ b.StartObject(2)
+ b.PrependInt16Slot(0, 55, 0)
+ b.PrependUOffsetTRelativeSlot(1, vecend, 0)
+ b.EndObject()
+ self.assertBuilderEquals(
+ b,
+ [
+ 8,
+ 0, # vtable bytes
+ 12,
+ 0,
+ 10,
+ 0, # offset to value 0
+ 4,
+ 0, # offset to vector offset
+ 8,
+ 0,
+ 0,
+ 0, # vtable loc
+ 8,
+ 0,
+ 0,
+ 0, # value 1
+ 0,
+ 0,
+ 55,
+ 0, # value 0
+ 0,
+ 0,
+ 0,
+ 0, # length of vector (not in struct)
])
- def test_vtable_with_1_int16_and_2vector_of_int16(self):
- b = flatbuffers.Builder(0)
- b.StartVector(flatbuffers.number_types.Int16Flags.bytewidth, 2, 1)
- b.PrependInt16(0x1234)
- b.PrependInt16(0x5678)
- vecend = b.EndVector(2)
- b.StartObject(2)
- b.PrependUOffsetTRelativeSlot(1, vecend, 0)
- b.PrependInt16Slot(0, 55, 0)
- b.EndObject()
- self.assertBuilderEquals(b, [
- 8, 0, # vtable bytes
- 12, 0, # length of object
- 6, 0, # start of value 0 from end of vtable
- 8, 0, # start of value 1 from end of buffer
- 8, 0, 0, 0, # offset for start of vtable (int32)
- 0, 0, # padding
- 55, 0, # value 0
- 4, 0, 0, 0, # vector position from here
- 2, 0, 0, 0, # length of vector (uint32)
- 0x78, 0x56, # vector value 1
- 0x34, 0x12, # vector value 0
+ def test_vtable_with_1_int16_and_2vector_of_int16(self):
+ b = flatbuffers.Builder(0)
+ b.StartVector(flatbuffers.number_types.Int16Flags.bytewidth, 2, 1)
+ b.PrependInt16(0x1234)
+ b.PrependInt16(0x5678)
+ vecend = b.EndVector()
+ b.StartObject(2)
+ b.PrependUOffsetTRelativeSlot(1, vecend, 0)
+ b.PrependInt16Slot(0, 55, 0)
+ b.EndObject()
+ self.assertBuilderEquals(
+ b,
+ [
+ 8,
+ 0, # vtable bytes
+ 12,
+ 0, # length of object
+ 6,
+ 0, # start of value 0 from end of vtable
+ 8,
+ 0, # start of value 1 from end of buffer
+ 8,
+ 0,
+ 0,
+ 0, # offset for start of vtable (int32)
+ 0,
+ 0, # padding
+ 55,
+ 0, # value 0
+ 4,
+ 0,
+ 0,
+ 0, # vector position from here
+ 2,
+ 0,
+ 0,
+ 0, # length of vector (uint32)
+ 0x78,
+ 0x56, # vector value 1
+ 0x34,
+ 0x12, # vector value 0
])
- def test_vtable_with_1_struct_of_1_int8__1_int16__1_int32(self):
- b = flatbuffers.Builder(0)
- b.StartObject(1)
- b.Prep(4+4+4, 0)
- b.PrependInt8(55)
- b.Pad(3)
- b.PrependInt16(0x1234)
- b.Pad(2)
- b.PrependInt32(0x12345678)
- structStart = b.Offset()
- b.PrependStructSlot(0, structStart, 0)
- b.EndObject()
- self.assertBuilderEquals(b, [
- 6, 0, # vtable bytes
- 16, 0, # end of object from here
- 4, 0, # start of struct from here
- 6, 0, 0, 0, # offset for start of vtable (int32)
- 0x78, 0x56, 0x34, 0x12, # value 2
- 0, 0, # padding
- 0x34, 0x12, # value 1
- 0, 0, 0, # padding
+ def test_vtable_with_1_struct_of_1_int8__1_int16__1_int32(self):
+ b = flatbuffers.Builder(0)
+ b.StartObject(1)
+ b.Prep(4 + 4 + 4, 0)
+ b.PrependInt8(55)
+ b.Pad(3)
+ b.PrependInt16(0x1234)
+ b.Pad(2)
+ b.PrependInt32(0x12345678)
+ structStart = b.Offset()
+ b.PrependStructSlot(0, structStart, 0)
+ b.EndObject()
+ self.assertBuilderEquals(
+ b,
+ [
+ 6,
+ 0, # vtable bytes
+ 16,
+ 0, # end of object from here
+ 4,
+ 0, # start of struct from here
+ 6,
+ 0,
+ 0,
+ 0, # offset for start of vtable (int32)
+ 0x78,
+ 0x56,
+ 0x34,
+ 0x12, # value 2
+ 0,
+ 0, # padding
+ 0x34,
+ 0x12, # value 1
+ 0,
+ 0,
+ 0, # padding
55, # value 0
])
- def test_vtable_with_1_vector_of_2_struct_of_2_int8(self):
- b = flatbuffers.Builder(0)
- b.StartVector(flatbuffers.number_types.Int8Flags.bytewidth*2, 2, 1)
- b.PrependInt8(33)
- b.PrependInt8(44)
- b.PrependInt8(55)
- b.PrependInt8(66)
- vecend = b.EndVector(2)
- b.StartObject(1)
- b.PrependUOffsetTRelativeSlot(0, vecend, 0)
- b.EndObject()
- self.assertBuilderEquals(b, [
- 6, 0, # vtable bytes
- 8, 0,
- 4, 0, # offset of vector offset
- 6, 0, 0, 0, # offset for start of vtable (int32)
- 4, 0, 0, 0, # vector start offset
-
- 2, 0, 0, 0, # vector length
+ def test_vtable_with_1_vector_of_2_struct_of_2_int8(self):
+ b = flatbuffers.Builder(0)
+ b.StartVector(flatbuffers.number_types.Int8Flags.bytewidth * 2, 2, 1)
+ b.PrependInt8(33)
+ b.PrependInt8(44)
+ b.PrependInt8(55)
+ b.PrependInt8(66)
+ vecend = b.EndVector()
+ b.StartObject(1)
+ b.PrependUOffsetTRelativeSlot(0, vecend, 0)
+ b.EndObject()
+ self.assertBuilderEquals(
+ b,
+ [
+ 6,
+ 0, # vtable bytes
+ 8,
+ 0,
+ 4,
+ 0, # offset of vector offset
+ 6,
+ 0,
+ 0,
+ 0, # offset for start of vtable (int32)
+ 4,
+ 0,
+ 0,
+ 0, # vector start offset
+ 2,
+ 0,
+ 0,
+ 0, # vector length
66, # vector value 1,1
55, # vector value 1,0
44, # vector value 0,1
33, # vector value 0,0
])
- def test_table_with_some_elements(self):
- b = flatbuffers.Builder(0)
- b.StartObject(2)
- b.PrependInt8Slot(0, 33, 0)
- b.PrependInt16Slot(1, 66, 0)
- off = b.EndObject()
- b.Finish(off)
+ def test_table_with_some_elements(self):
+ b = flatbuffers.Builder(0)
+ b.StartObject(2)
+ b.PrependInt8Slot(0, 33, 0)
+ b.PrependInt16Slot(1, 66, 0)
+ off = b.EndObject()
+ b.Finish(off)
- self.assertBuilderEquals(b, [
- 12, 0, 0, 0, # root of table: points to vtable offset
-
- 8, 0, # vtable bytes
- 8, 0, # end of object from here
- 7, 0, # start of value 0
- 4, 0, # start of value 1
-
- 8, 0, 0, 0, # offset for start of vtable (int32)
-
- 66, 0, # value 1
+ self.assertBuilderEquals(
+ b,
+ [
+ 12,
+ 0,
+ 0,
+ 0, # root of table: points to vtable offset
+ 8,
+ 0, # vtable bytes
+ 8,
+ 0, # end of object from here
+ 7,
+ 0, # start of value 0
+ 4,
+ 0, # start of value 1
+ 8,
+ 0,
+ 0,
+ 0, # offset for start of vtable (int32)
+ 66,
+ 0, # value 1
0, # padding
33, # value 0
])
- def test__one_unfinished_table_and_one_finished_table(self):
- b = flatbuffers.Builder(0)
- b.StartObject(2)
- b.PrependInt8Slot(0, 33, 0)
- b.PrependInt8Slot(1, 44, 0)
- off = b.EndObject()
- b.Finish(off)
+ def test__one_unfinished_table_and_one_finished_table(self):
+ b = flatbuffers.Builder(0)
+ b.StartObject(2)
+ b.PrependInt8Slot(0, 33, 0)
+ b.PrependInt8Slot(1, 44, 0)
+ off = b.EndObject()
+ b.Finish(off)
- b.StartObject(3)
- b.PrependInt8Slot(0, 55, 0)
- b.PrependInt8Slot(1, 66, 0)
- b.PrependInt8Slot(2, 77, 0)
- off = b.EndObject()
- b.Finish(off)
+ b.StartObject(3)
+ b.PrependInt8Slot(0, 55, 0)
+ b.PrependInt8Slot(1, 66, 0)
+ b.PrependInt8Slot(2, 77, 0)
+ off = b.EndObject()
+ b.Finish(off)
- self.assertBuilderEquals(b, [
- 16, 0, 0, 0, # root of table: points to object
- 0, 0, # padding
-
- 10, 0, # vtable bytes
- 8, 0, # size of object
- 7, 0, # start of value 0
- 6, 0, # start of value 1
- 5, 0, # start of value 2
- 10, 0, 0, 0, # offset for start of vtable (int32)
+ self.assertBuilderEquals(
+ b,
+ [
+ 16,
+ 0,
+ 0,
+ 0, # root of table: points to object
+ 0,
+ 0, # padding
+ 10,
+ 0, # vtable bytes
+ 8,
+ 0, # size of object
+ 7,
+ 0, # start of value 0
+ 6,
+ 0, # start of value 1
+ 5,
+ 0, # start of value 2
+ 10,
+ 0,
+ 0,
+ 0, # offset for start of vtable (int32)
0, # padding
77, # value 2
66, # value 1
55, # value 0
-
- 12, 0, 0, 0, # root of table: points to object
-
- 8, 0, # vtable bytes
- 8, 0, # size of object
- 7, 0, # start of value 0
- 6, 0, # start of value 1
- 8, 0, 0, 0, # offset for start of vtable (int32)
- 0, 0, # padding
+ 12,
+ 0,
+ 0,
+ 0, # root of table: points to object
+ 8,
+ 0, # vtable bytes
+ 8,
+ 0, # size of object
+ 7,
+ 0, # start of value 0
+ 6,
+ 0, # start of value 1
+ 8,
+ 0,
+ 0,
+ 0, # offset for start of vtable (int32)
+ 0,
+ 0, # padding
44, # value 1
33, # value 0
])
- def test_a_bunch_of_bools(self):
- b = flatbuffers.Builder(0)
- b.StartObject(8)
- b.PrependBoolSlot(0, True, False)
- b.PrependBoolSlot(1, True, False)
- b.PrependBoolSlot(2, True, False)
- b.PrependBoolSlot(3, True, False)
- b.PrependBoolSlot(4, True, False)
- b.PrependBoolSlot(5, True, False)
- b.PrependBoolSlot(6, True, False)
- b.PrependBoolSlot(7, True, False)
- off = b.EndObject()
- b.Finish(off)
+ def test_a_bunch_of_bools(self):
+ b = flatbuffers.Builder(0)
+ b.StartObject(8)
+ b.PrependBoolSlot(0, True, False)
+ b.PrependBoolSlot(1, True, False)
+ b.PrependBoolSlot(2, True, False)
+ b.PrependBoolSlot(3, True, False)
+ b.PrependBoolSlot(4, True, False)
+ b.PrependBoolSlot(5, True, False)
+ b.PrependBoolSlot(6, True, False)
+ b.PrependBoolSlot(7, True, False)
+ off = b.EndObject()
+ b.Finish(off)
- self.assertBuilderEquals(b, [
- 24, 0, 0, 0, # root of table: points to vtable offset
-
- 20, 0, # vtable bytes
- 12, 0, # size of object
- 11, 0, # start of value 0
- 10, 0, # start of value 1
- 9, 0, # start of value 2
- 8, 0, # start of value 3
- 7, 0, # start of value 4
- 6, 0, # start of value 5
- 5, 0, # start of value 6
- 4, 0, # start of value 7
- 20, 0, 0, 0, # vtable offset
-
+ self.assertBuilderEquals(
+ b,
+ [
+ 24,
+ 0,
+ 0,
+ 0, # root of table: points to vtable offset
+ 20,
+ 0, # vtable bytes
+ 12,
+ 0, # size of object
+ 11,
+ 0, # start of value 0
+ 10,
+ 0, # start of value 1
+ 9,
+ 0, # start of value 2
+ 8,
+ 0, # start of value 3
+ 7,
+ 0, # start of value 4
+ 6,
+ 0, # start of value 5
+ 5,
+ 0, # start of value 6
+ 4,
+ 0, # start of value 7
+ 20,
+ 0,
+ 0,
+ 0, # vtable offset
1, # value 7
1, # value 6
1, # value 5
@@ -1498,908 +1885,970 @@
1, # value 0
])
- def test_three_bools(self):
- b = flatbuffers.Builder(0)
- b.StartObject(3)
- b.PrependBoolSlot(0, True, False)
- b.PrependBoolSlot(1, True, False)
- b.PrependBoolSlot(2, True, False)
- off = b.EndObject()
- b.Finish(off)
+ def test_three_bools(self):
+ b = flatbuffers.Builder(0)
+ b.StartObject(3)
+ b.PrependBoolSlot(0, True, False)
+ b.PrependBoolSlot(1, True, False)
+ b.PrependBoolSlot(2, True, False)
+ off = b.EndObject()
+ b.Finish(off)
- self.assertBuilderEquals(b, [
- 16, 0, 0, 0, # root of table: points to vtable offset
-
- 0, 0, # padding
-
- 10, 0, # vtable bytes
- 8, 0, # size of object
- 7, 0, # start of value 0
- 6, 0, # start of value 1
- 5, 0, # start of value 2
- 10, 0, 0, 0, # vtable offset from here
-
+ self.assertBuilderEquals(
+ b,
+ [
+ 16,
+ 0,
+ 0,
+ 0, # root of table: points to vtable offset
+ 0,
+ 0, # padding
+ 10,
+ 0, # vtable bytes
+ 8,
+ 0, # size of object
+ 7,
+ 0, # start of value 0
+ 6,
+ 0, # start of value 1
+ 5,
+ 0, # start of value 2
+ 10,
+ 0,
+ 0,
+ 0, # vtable offset from here
0, # padding
1, # value 2
1, # value 1
1, # value 0
])
- def test_some_floats(self):
- b = flatbuffers.Builder(0)
- b.StartObject(1)
- b.PrependFloat32Slot(0, 1.0, 0.0)
- off = b.EndObject()
+ def test_some_floats(self):
+ b = flatbuffers.Builder(0)
+ b.StartObject(1)
+ b.PrependFloat32Slot(0, 1.0, 0.0)
+ off = b.EndObject()
- self.assertBuilderEquals(b, [
- 6, 0, # vtable bytes
- 8, 0, # size of object
- 4, 0, # start of value 0
- 6, 0, 0, 0, # vtable offset
-
- 0, 0, 128, 63, # value 0
+ self.assertBuilderEquals(
+ b,
+ [
+ 6,
+ 0, # vtable bytes
+ 8,
+ 0, # size of object
+ 4,
+ 0, # start of value 0
+ 6,
+ 0,
+ 0,
+ 0, # vtable offset
+ 0,
+ 0,
+ 128,
+ 63, # value 0
])
-def make_monster_from_generated_code(sizePrefix = False, file_identifier=None):
- ''' Use generated code to build the example Monster. '''
+def make_monster_from_generated_code(sizePrefix=False, file_identifier=None):
+ """ Use generated code to build the example Monster. """
- b = flatbuffers.Builder(0)
- string = b.CreateString("MyMonster")
- test1 = b.CreateString("test1")
- test2 = b.CreateString("test2")
- fred = b.CreateString("Fred")
+ b = flatbuffers.Builder(0)
+ string = b.CreateString('MyMonster')
+ test1 = b.CreateString('test1')
+ test2 = b.CreateString('test2')
+ fred = b.CreateString('Fred')
- MyGame.Example.Monster.MonsterStartInventoryVector(b, 5)
- b.PrependByte(4)
- b.PrependByte(3)
- b.PrependByte(2)
- b.PrependByte(1)
- b.PrependByte(0)
- inv = b.EndVector(5)
+ _MONSTER.MonsterStartInventoryVector(b, 5)
+ b.PrependByte(4)
+ b.PrependByte(3)
+ b.PrependByte(2)
+ b.PrependByte(1)
+ b.PrependByte(0)
+ inv = b.EndVector()
- MyGame.Example.Monster.MonsterStart(b)
- MyGame.Example.Monster.MonsterAddName(b, fred)
- mon2 = MyGame.Example.Monster.MonsterEnd(b)
+ _MONSTER.MonsterStart(b)
+ _MONSTER.MonsterAddName(b, fred)
+ mon2 = _MONSTER.MonsterEnd(b)
- MyGame.Example.Monster.MonsterStartTest4Vector(b, 2)
- MyGame.Example.Test.CreateTest(b, 10, 20)
- MyGame.Example.Test.CreateTest(b, 30, 40)
- test4 = b.EndVector(2)
+ _MONSTER.MonsterStartTest4Vector(b, 2)
+ _TEST.CreateTest(b, 10, 20)
+ _TEST.CreateTest(b, 30, 40)
+ test4 = b.EndVector()
- MyGame.Example.Monster.MonsterStartTestarrayofstringVector(b, 2)
- b.PrependUOffsetTRelative(test2)
- b.PrependUOffsetTRelative(test1)
- testArrayOfString = b.EndVector(2)
+ _MONSTER.MonsterStartTestarrayofstringVector(b, 2)
+ b.PrependUOffsetTRelative(test2)
+ b.PrependUOffsetTRelative(test1)
+ testArrayOfString = b.EndVector()
- MyGame.Example.Monster.MonsterStartVectorOfLongsVector(b, 5)
- b.PrependInt64(100000000)
- b.PrependInt64(1000000)
- b.PrependInt64(10000)
- b.PrependInt64(100)
- b.PrependInt64(1)
- VectorOfLongs = b.EndVector(5)
+ _MONSTER.MonsterStartVectorOfLongsVector(b, 5)
+ b.PrependInt64(100000000)
+ b.PrependInt64(1000000)
+ b.PrependInt64(10000)
+ b.PrependInt64(100)
+ b.PrependInt64(1)
+ VectorOfLongs = b.EndVector()
- MyGame.Example.Monster.MonsterStartVectorOfDoublesVector(b, 3)
- b.PrependFloat64(1.7976931348623157e+308)
- b.PrependFloat64(0)
- b.PrependFloat64(-1.7976931348623157e+308)
- VectorOfDoubles = b.EndVector(3)
+ _MONSTER.MonsterStartVectorOfDoublesVector(b, 3)
+ b.PrependFloat64(1.7976931348623157e+308)
+ b.PrependFloat64(0)
+ b.PrependFloat64(-1.7976931348623157e+308)
+ VectorOfDoubles = b.EndVector()
- MyGame.Example.Monster.MonsterStart(b)
+ _MONSTER.MonsterStart(b)
- pos = MyGame.Example.Vec3.CreateVec3(b, 1.0, 2.0, 3.0, 3.0, 2, 5, 6)
- MyGame.Example.Monster.MonsterAddPos(b, pos)
+ pos = _VEC3.CreateVec3(b, 1.0, 2.0, 3.0, 3.0, 2, 5, 6)
+ _MONSTER.MonsterAddPos(b, pos)
- MyGame.Example.Monster.MonsterAddHp(b, 80)
- MyGame.Example.Monster.MonsterAddName(b, string)
- MyGame.Example.Monster.MonsterAddInventory(b, inv)
- MyGame.Example.Monster.MonsterAddTestType(b, 1)
- MyGame.Example.Monster.MonsterAddTest(b, mon2)
- MyGame.Example.Monster.MonsterAddTest4(b, test4)
- MyGame.Example.Monster.MonsterAddTestarrayofstring(b, testArrayOfString)
- MyGame.Example.Monster.MonsterAddVectorOfLongs(b, VectorOfLongs)
- MyGame.Example.Monster.MonsterAddVectorOfDoubles(b, VectorOfDoubles)
- mon = MyGame.Example.Monster.MonsterEnd(b)
+ _MONSTER.MonsterAddHp(b, 80)
+ _MONSTER.MonsterAddName(b, string)
+ _MONSTER.MonsterAddInventory(b, inv)
+ _MONSTER.MonsterAddTestType(b, 1)
+ _MONSTER.MonsterAddTest(b, mon2)
+ _MONSTER.MonsterAddTest4(b, test4)
+ _MONSTER.MonsterAddTestarrayofstring(b, testArrayOfString)
+ _MONSTER.MonsterAddVectorOfLongs(b, VectorOfLongs)
+ _MONSTER.MonsterAddVectorOfDoubles(b, VectorOfDoubles)
+ mon = _MONSTER.MonsterEnd(b)
- if sizePrefix:
- b.FinishSizePrefixed(mon, file_identifier)
- else:
- b.Finish(mon, file_identifier)
+ if sizePrefix:
+ b.FinishSizePrefixed(mon, file_identifier)
+ else:
+ b.Finish(mon, file_identifier)
- return b.Bytes, b.Head()
+ return b.Bytes, b.Head()
class TestBuilderForceDefaults(unittest.TestCase):
- """Verify that the builder adds default values when forced."""
+ """Verify that the builder adds default values when forced."""
- test_flags = [N.BoolFlags(), N.Uint8Flags(), N.Uint16Flags(), \
- N.Uint32Flags(), N.Uint64Flags(), N.Int8Flags(), \
- N.Int16Flags(), N.Int32Flags(), N.Int64Flags(), \
- N.Float32Flags(), N.Float64Flags(), N.UOffsetTFlags()]
- def test_default_force_defaults(self):
- for flag in self.test_flags:
- b = flatbuffers.Builder(0)
- b.StartObject(1)
- stored_offset = b.Offset()
- if flag != N.UOffsetTFlags():
- b.PrependSlot(flag, 0, 0, 0)
- else:
- b.PrependUOffsetTRelativeSlot(0, 0, 0)
- end_offset = b.Offset()
- b.EndObject()
- self.assertEqual(0, end_offset - stored_offset)
+ test_flags = [N.BoolFlags(), N.Uint8Flags(), N.Uint16Flags(), \
+ N.Uint32Flags(), N.Uint64Flags(), N.Int8Flags(), \
+ N.Int16Flags(), N.Int32Flags(), N.Int64Flags(), \
+ N.Float32Flags(), N.Float64Flags(), N.UOffsetTFlags()]
- def test_force_defaults_true(self):
- for flag in self.test_flags:
- b = flatbuffers.Builder(0)
- b.ForceDefaults(True)
- b.StartObject(1)
- stored_offset = b.Offset()
- if flag != N.UOffsetTFlags():
- b.PrependSlot(flag, 0, 0, 0)
- else:
- b.PrependUOffsetTRelativeSlot(0, 0, 0)
- end_offset = b.Offset()
- b.EndObject()
- self.assertEqual(flag.bytewidth, end_offset - stored_offset)
+ def test_default_force_defaults(self):
+ for flag in self.test_flags:
+ b = flatbuffers.Builder(0)
+ b.StartObject(1)
+ stored_offset = b.Offset()
+ if flag != N.UOffsetTFlags():
+ b.PrependSlot(flag, 0, 0, 0)
+ else:
+ b.PrependUOffsetTRelativeSlot(0, 0, 0)
+ end_offset = b.Offset()
+ b.EndObject()
+ self.assertEqual(0, end_offset - stored_offset)
+
+ def test_force_defaults_true(self):
+ for flag in self.test_flags:
+ b = flatbuffers.Builder(0)
+ b.ForceDefaults(True)
+ b.StartObject(1)
+ stored_offset = b.Offset()
+ if flag != N.UOffsetTFlags():
+ b.PrependSlot(flag, 0, 0, 0)
+ else:
+ b.PrependUOffsetTRelativeSlot(0, 0, 0)
+ end_offset = b.Offset()
+ b.EndObject()
+ self.assertEqual(flag.bytewidth, end_offset - stored_offset)
class TestAllCodePathsOfExampleSchema(unittest.TestCase):
- def setUp(self, *args, **kwargs):
- super(TestAllCodePathsOfExampleSchema, self).setUp(*args, **kwargs)
- b = flatbuffers.Builder(0)
- MyGame.Example.Monster.MonsterStart(b)
- gen_mon = MyGame.Example.Monster.MonsterEnd(b)
- b.Finish(gen_mon)
+ def setUp(self, *args, **kwargs):
+ super(TestAllCodePathsOfExampleSchema, self).setUp(*args, **kwargs)
- self.mon = MyGame.Example.Monster.Monster.GetRootAsMonster(b.Bytes,
- b.Head())
+ b = flatbuffers.Builder(0)
+ _MONSTER.MonsterStart(b)
+ gen_mon = _MONSTER.MonsterEnd(b)
+ b.Finish(gen_mon)
- def test_default_monster_pos(self):
- self.assertTrue(self.mon.Pos() is None)
+ self.mon = _MONSTER.Monster.GetRootAs(b.Bytes, b.Head())
- def test_nondefault_monster_mana(self):
- b = flatbuffers.Builder(0)
- MyGame.Example.Monster.MonsterStart(b)
- MyGame.Example.Monster.MonsterAddMana(b, 50)
- mon = MyGame.Example.Monster.MonsterEnd(b)
- b.Finish(mon)
+ def test_default_monster_pos(self):
+ self.assertTrue(self.mon.Pos() is None)
- got_mon = MyGame.Example.Monster.Monster.GetRootAsMonster(b.Bytes,
- b.Head())
- self.assertEqual(50, got_mon.Mana())
+ def test_nondefault_monster_mana(self):
+ b = flatbuffers.Builder(0)
+ _MONSTER.MonsterStart(b)
+ _MONSTER.MonsterAddMana(b, 50)
+ mon = _MONSTER.MonsterEnd(b)
+ b.Finish(mon)
- def test_default_monster_hp(self):
- self.assertEqual(100, self.mon.Hp())
+ got_mon = _MONSTER.Monster.GetRootAs(b.Bytes, b.Head())
+ self.assertEqual(50, got_mon.Mana())
- def test_default_monster_name(self):
- self.assertEqual(None, self.mon.Name())
+ def test_default_monster_hp(self):
+ self.assertEqual(100, self.mon.Hp())
- def test_default_monster_inventory_item(self):
- self.assertEqual(0, self.mon.Inventory(0))
+ def test_default_monster_name(self):
+ self.assertEqual(None, self.mon.Name())
- def test_default_monster_inventory_length(self):
- self.assertEqual(0, self.mon.InventoryLength())
- self.assertTrue(self.mon.InventoryIsNone())
+ def test_default_monster_inventory_item(self):
+ self.assertEqual(0, self.mon.Inventory(0))
- def test_empty_monster_inventory_vector(self):
- b = flatbuffers.Builder(0)
- MyGame.Example.Monster.MonsterStartInventoryVector(b, 0)
- inv = b.EndVector(0)
- MyGame.Example.Monster.MonsterStart(b)
- MyGame.Example.Monster.MonsterAddInventory(b, inv)
- mon = MyGame.Example.Monster.MonsterEnd(b)
- b.Finish(mon)
- mon2 = MyGame.Example.Monster.Monster.GetRootAsMonster(b.Bytes,
- b.Head())
- self.assertFalse(mon2.InventoryIsNone())
+ def test_default_monster_inventory_length(self):
+ self.assertEqual(0, self.mon.InventoryLength())
+ self.assertTrue(self.mon.InventoryIsNone())
- def test_default_monster_color(self):
- self.assertEqual(MyGame.Example.Color.Color.Blue, self.mon.Color())
+ def test_empty_monster_inventory_vector(self):
+ b = flatbuffers.Builder(0)
+ _MONSTER.MonsterStartInventoryVector(b, 0)
+ inv = b.EndVector()
+ _MONSTER.MonsterStart(b)
+ _MONSTER.MonsterAddInventory(b, inv)
+ mon = _MONSTER.MonsterEnd(b)
+ b.Finish(mon)
+ mon2 = _MONSTER.Monster.GetRootAs(b.Bytes, b.Head())
+ self.assertFalse(mon2.InventoryIsNone())
- def test_nondefault_monster_color(self):
- b = flatbuffers.Builder(0)
- color = MyGame.Example.Color.Color.Red
- MyGame.Example.Monster.MonsterStart(b)
- MyGame.Example.Monster.MonsterAddColor(b, color)
- mon = MyGame.Example.Monster.MonsterEnd(b)
- b.Finish(mon)
+ def test_default_monster_color(self):
+ self.assertEqual(_COLOR.Color.Blue, self.mon.Color())
- mon2 = MyGame.Example.Monster.Monster.GetRootAsMonster(b.Bytes,
- b.Head())
- self.assertEqual(MyGame.Example.Color.Color.Red, mon2.Color())
+ def test_nondefault_monster_color(self):
+ b = flatbuffers.Builder(0)
+ color = _COLOR.Color.Red
+ _MONSTER.MonsterStart(b)
+ _MONSTER.MonsterAddColor(b, color)
+ mon = _MONSTER.MonsterEnd(b)
+ b.Finish(mon)
- def test_default_monster_testtype(self):
- self.assertEqual(0, self.mon.TestType())
+ mon2 = _MONSTER.Monster.GetRootAs(b.Bytes, b.Head())
+ self.assertEqual(_COLOR.Color.Red, mon2.Color())
- def test_default_monster_test_field(self):
- self.assertEqual(None, self.mon.Test())
+ def test_default_monster_testtype(self):
+ self.assertEqual(0, self.mon.TestType())
- def test_default_monster_test4_item(self):
- self.assertEqual(None, self.mon.Test4(0))
+ def test_default_monster_test_field(self):
+ self.assertEqual(None, self.mon.Test())
- def test_default_monster_test4_length(self):
- self.assertEqual(0, self.mon.Test4Length())
- self.assertTrue(self.mon.Test4IsNone())
+ def test_default_monster_test4_item(self):
+ self.assertEqual(None, self.mon.Test4(0))
- def test_empty_monster_test4_vector(self):
- b = flatbuffers.Builder(0)
- MyGame.Example.Monster.MonsterStartTest4Vector(b, 0)
- test4 = b.EndVector(0)
- MyGame.Example.Monster.MonsterStart(b)
- MyGame.Example.Monster.MonsterAddTest4(b, test4)
- mon = MyGame.Example.Monster.MonsterEnd(b)
- b.Finish(mon)
- mon2 = MyGame.Example.Monster.Monster.GetRootAsMonster(b.Bytes,
- b.Head())
- self.assertFalse(mon2.Test4IsNone())
+ def test_default_monster_test4_length(self):
+ self.assertEqual(0, self.mon.Test4Length())
+ self.assertTrue(self.mon.Test4IsNone())
- def test_default_monster_testarrayofstring(self):
- self.assertEqual("", self.mon.Testarrayofstring(0))
+ def test_empty_monster_test4_vector(self):
+ b = flatbuffers.Builder(0)
+ _MONSTER.MonsterStartTest4Vector(b, 0)
+ test4 = b.EndVector()
+ _MONSTER.MonsterStart(b)
+ _MONSTER.MonsterAddTest4(b, test4)
+ mon = _MONSTER.MonsterEnd(b)
+ b.Finish(mon)
+ mon2 = _MONSTER.Monster.GetRootAs(b.Bytes, b.Head())
+ self.assertFalse(mon2.Test4IsNone())
- def test_default_monster_testarrayofstring_length(self):
- self.assertEqual(0, self.mon.TestarrayofstringLength())
- self.assertTrue(self.mon.TestarrayofstringIsNone())
+ def test_default_monster_testarrayofstring(self):
+ self.assertEqual('', self.mon.Testarrayofstring(0))
- def test_empty_monster_testarrayofstring_vector(self):
- b = flatbuffers.Builder(0)
- MyGame.Example.Monster.MonsterStartTestarrayofstringVector(b, 0)
- testarrayofstring = b.EndVector(0)
- MyGame.Example.Monster.MonsterStart(b)
- MyGame.Example.Monster.MonsterAddTestarrayofstring(b, testarrayofstring)
- mon = MyGame.Example.Monster.MonsterEnd(b)
- b.Finish(mon)
- mon2 = MyGame.Example.Monster.Monster.GetRootAsMonster(b.Bytes,
- b.Head())
- self.assertFalse(mon2.TestarrayofstringIsNone())
+ def test_default_monster_testarrayofstring_length(self):
+ self.assertEqual(0, self.mon.TestarrayofstringLength())
+ self.assertTrue(self.mon.TestarrayofstringIsNone())
- def test_default_monster_testarrayoftables(self):
- self.assertEqual(None, self.mon.Testarrayoftables(0))
+ def test_empty_monster_testarrayofstring_vector(self):
+ b = flatbuffers.Builder(0)
+ _MONSTER.MonsterStartTestarrayofstringVector(b, 0)
+ testarrayofstring = b.EndVector()
+ _MONSTER.MonsterStart(b)
+ _MONSTER.MonsterAddTestarrayofstring(b, testarrayofstring)
+ mon = _MONSTER.MonsterEnd(b)
+ b.Finish(mon)
+ mon2 = _MONSTER.Monster.GetRootAs(b.Bytes, b.Head())
+ self.assertFalse(mon2.TestarrayofstringIsNone())
- def test_nondefault_monster_testarrayoftables(self):
- b = flatbuffers.Builder(0)
+ def test_default_monster_testarrayoftables(self):
+ self.assertEqual(None, self.mon.Testarrayoftables(0))
- # make a child Monster within a vector of Monsters:
- MyGame.Example.Monster.MonsterStart(b)
- MyGame.Example.Monster.MonsterAddHp(b, 99)
- sub_monster = MyGame.Example.Monster.MonsterEnd(b)
+ def test_nondefault_monster_testarrayoftables(self):
+ b = flatbuffers.Builder(0)
- # build the vector:
- MyGame.Example.Monster.MonsterStartTestarrayoftablesVector(b, 1)
- b.PrependUOffsetTRelative(sub_monster)
- vec = b.EndVector(1)
+ # make a child Monster within a vector of Monsters:
+ _MONSTER.MonsterStart(b)
+ _MONSTER.MonsterAddHp(b, 99)
+ sub_monster = _MONSTER.MonsterEnd(b)
- # make the parent monster and include the vector of Monster:
- MyGame.Example.Monster.MonsterStart(b)
- MyGame.Example.Monster.MonsterAddTestarrayoftables(b, vec)
- mon = MyGame.Example.Monster.MonsterEnd(b)
- b.Finish(mon)
+ # build the vector:
+ _MONSTER.MonsterStartTestarrayoftablesVector(b, 1)
+ b.PrependUOffsetTRelative(sub_monster)
+ vec = b.EndVector()
- # inspect the resulting data:
- mon2 = MyGame.Example.Monster.Monster.GetRootAsMonster(b.Output(), 0)
- self.assertEqual(99, mon2.Testarrayoftables(0).Hp())
- self.assertEqual(1, mon2.TestarrayoftablesLength())
- self.assertFalse(mon2.TestarrayoftablesIsNone())
+ # make the parent monster and include the vector of Monster:
+ _MONSTER.MonsterStart(b)
+ _MONSTER.MonsterAddTestarrayoftables(b, vec)
+ mon = _MONSTER.MonsterEnd(b)
+ b.Finish(mon)
- def test_default_monster_testarrayoftables_length(self):
- self.assertEqual(0, self.mon.TestarrayoftablesLength())
- self.assertTrue(self.mon.TestarrayoftablesIsNone())
+ # inspect the resulting data:
+ mon2 = _MONSTER.Monster.GetRootAs(b.Output(), 0)
+ self.assertEqual(99, mon2.Testarrayoftables(0).Hp())
+ self.assertEqual(1, mon2.TestarrayoftablesLength())
+ self.assertFalse(mon2.TestarrayoftablesIsNone())
- def test_empty_monster_testarrayoftables_vector(self):
- b = flatbuffers.Builder(0)
- MyGame.Example.Monster.MonsterStartTestarrayoftablesVector(b, 0)
- testarrayoftables = b.EndVector(0)
- MyGame.Example.Monster.MonsterStart(b)
- MyGame.Example.Monster.MonsterAddTestarrayoftables(b, testarrayoftables)
- mon = MyGame.Example.Monster.MonsterEnd(b)
- b.Finish(mon)
- mon2 = MyGame.Example.Monster.Monster.GetRootAsMonster(b.Bytes,
- b.Head())
- self.assertFalse(mon2.TestarrayoftablesIsNone())
+ def test_default_monster_testarrayoftables_length(self):
+ self.assertEqual(0, self.mon.TestarrayoftablesLength())
+ self.assertTrue(self.mon.TestarrayoftablesIsNone())
- def test_default_monster_testarrayoftables_length(self):
- self.assertEqual(0, self.mon.TestarrayoftablesLength())
+ def test_empty_monster_testarrayoftables_vector(self):
+ b = flatbuffers.Builder(0)
+ _MONSTER.MonsterStartTestarrayoftablesVector(b, 0)
+ testarrayoftables = b.EndVector()
+ _MONSTER.MonsterStart(b)
+ _MONSTER.MonsterAddTestarrayoftables(b, testarrayoftables)
+ mon = _MONSTER.MonsterEnd(b)
+ b.Finish(mon)
+ mon2 = _MONSTER.Monster.GetRootAs(b.Bytes, b.Head())
+ self.assertFalse(mon2.TestarrayoftablesIsNone())
- def test_nondefault_monster_enemy(self):
- b = flatbuffers.Builder(0)
+ def test_default_monster_testarrayoftables_length(self):
+ self.assertEqual(0, self.mon.TestarrayoftablesLength())
- # make an Enemy object:
- MyGame.Example.Monster.MonsterStart(b)
- MyGame.Example.Monster.MonsterAddHp(b, 88)
- enemy = MyGame.Example.Monster.MonsterEnd(b)
- b.Finish(enemy)
+ def test_nondefault_monster_enemy(self):
+ b = flatbuffers.Builder(0)
- # make the parent monster and include the vector of Monster:
- MyGame.Example.Monster.MonsterStart(b)
- MyGame.Example.Monster.MonsterAddEnemy(b, enemy)
- mon = MyGame.Example.Monster.MonsterEnd(b)
- b.Finish(mon)
+ # make an Enemy object:
+ _MONSTER.MonsterStart(b)
+ _MONSTER.MonsterAddHp(b, 88)
+ enemy = _MONSTER.MonsterEnd(b)
+ b.Finish(enemy)
- # inspect the resulting data:
- mon2 = MyGame.Example.Monster.Monster.GetRootAsMonster(b.Bytes,
- b.Head())
- self.assertEqual(88, mon2.Enemy().Hp())
+ # make the parent monster and include the vector of Monster:
+ _MONSTER.MonsterStart(b)
+ _MONSTER.MonsterAddEnemy(b, enemy)
+ mon = _MONSTER.MonsterEnd(b)
+ b.Finish(mon)
- def test_default_monster_testnestedflatbuffer(self):
- self.assertEqual(0, self.mon.Testnestedflatbuffer(0))
+ # inspect the resulting data:
+ mon2 = _MONSTER.Monster.GetRootAs(b.Bytes, b.Head())
+ self.assertEqual(88, mon2.Enemy().Hp())
- def test_default_monster_testnestedflatbuffer_length(self):
- self.assertEqual(0, self.mon.TestnestedflatbufferLength())
- self.assertTrue(self.mon.TestnestedflatbufferIsNone())
+ def test_default_monster_testnestedflatbuffer(self):
+ self.assertEqual(0, self.mon.Testnestedflatbuffer(0))
- def test_empty_monster_testnestedflatbuffer_vector(self):
- b = flatbuffers.Builder(0)
- MyGame.Example.Monster.MonsterStartTestnestedflatbufferVector(b, 0)
- testnestedflatbuffer = b.EndVector(0)
- MyGame.Example.Monster.MonsterStart(b)
- MyGame.Example.Monster.MonsterAddTestnestedflatbuffer(b, testnestedflatbuffer)
- mon = MyGame.Example.Monster.MonsterEnd(b)
- b.Finish(mon)
- mon2 = MyGame.Example.Monster.Monster.GetRootAsMonster(b.Bytes,
- b.Head())
- self.assertFalse(mon2.TestnestedflatbufferIsNone())
+ def test_default_monster_testnestedflatbuffer_length(self):
+ self.assertEqual(0, self.mon.TestnestedflatbufferLength())
+ self.assertTrue(self.mon.TestnestedflatbufferIsNone())
- def test_nondefault_monster_testnestedflatbuffer(self):
- b = flatbuffers.Builder(0)
+ def test_empty_monster_testnestedflatbuffer_vector(self):
+ b = flatbuffers.Builder(0)
+ _MONSTER.MonsterStartTestnestedflatbufferVector(b, 0)
+ testnestedflatbuffer = b.EndVector()
+ _MONSTER.MonsterStart(b)
+ _MONSTER.MonsterAddTestnestedflatbuffer(b, testnestedflatbuffer)
+ mon = _MONSTER.MonsterEnd(b)
+ b.Finish(mon)
+ mon2 = _MONSTER.Monster.GetRootAs(b.Bytes, b.Head())
+ self.assertFalse(mon2.TestnestedflatbufferIsNone())
- MyGame.Example.Monster.MonsterStartTestnestedflatbufferVector(b, 3)
- b.PrependByte(4)
- b.PrependByte(2)
- b.PrependByte(0)
- sub_buf = b.EndVector(3)
+ def test_nondefault_monster_testnestedflatbuffer(self):
+ b = flatbuffers.Builder(0)
- # make the parent monster and include the vector of Monster:
- MyGame.Example.Monster.MonsterStart(b)
- MyGame.Example.Monster.MonsterAddTestnestedflatbuffer(b, sub_buf)
- mon = MyGame.Example.Monster.MonsterEnd(b)
- b.Finish(mon)
+ _MONSTER.MonsterStartTestnestedflatbufferVector(b, 3)
+ b.PrependByte(4)
+ b.PrependByte(2)
+ b.PrependByte(0)
+ sub_buf = b.EndVector()
- # inspect the resulting data:
- mon2 = MyGame.Example.Monster.Monster.GetRootAsMonster(b.Bytes,
- b.Head())
- self.assertEqual(3, mon2.TestnestedflatbufferLength())
- self.assertFalse(mon2.TestnestedflatbufferIsNone())
- self.assertEqual(0, mon2.Testnestedflatbuffer(0))
- self.assertEqual(2, mon2.Testnestedflatbuffer(1))
- self.assertEqual(4, mon2.Testnestedflatbuffer(2))
- try:
- imp.find_module('numpy')
- # if numpy exists, then we should be able to get the
- # vector as a numpy array
- self.assertEqual([0, 2, 4], mon2.TestnestedflatbufferAsNumpy().tolist())
- except ImportError:
- assertRaises(self,
- lambda: mon2.TestnestedflatbufferAsNumpy(),
- NumpyRequiredForThisFeature)
+ # make the parent monster and include the vector of Monster:
+ _MONSTER.MonsterStart(b)
+ _MONSTER.MonsterAddTestnestedflatbuffer(b, sub_buf)
+ mon = _MONSTER.MonsterEnd(b)
+ b.Finish(mon)
- def test_nondefault_monster_testempty(self):
- b = flatbuffers.Builder(0)
+ # inspect the resulting data:
+ mon2 = _MONSTER.Monster.GetRootAs(b.Bytes, b.Head())
+ self.assertEqual(3, mon2.TestnestedflatbufferLength())
+ self.assertFalse(mon2.TestnestedflatbufferIsNone())
+ self.assertEqual(0, mon2.Testnestedflatbuffer(0))
+ self.assertEqual(2, mon2.Testnestedflatbuffer(1))
+ self.assertEqual(4, mon2.Testnestedflatbuffer(2))
+ try:
+ imp.find_module('numpy')
+ # if numpy exists, then we should be able to get the
+ # vector as a numpy array
+ self.assertEqual([0, 2, 4], mon2.TestnestedflatbufferAsNumpy().tolist())
+ except ImportError:
+ assertRaises(self, lambda: mon2.TestnestedflatbufferAsNumpy(),
+ NumpyRequiredForThisFeature)
- # make a Stat object:
- MyGame.Example.Stat.StatStart(b)
- MyGame.Example.Stat.StatAddVal(b, 123)
- my_stat = MyGame.Example.Stat.StatEnd(b)
- b.Finish(my_stat)
+ def test_nested_monster_testnestedflatbuffer(self):
+ b = flatbuffers.Builder(0)
- # include the stat object in a monster:
- MyGame.Example.Monster.MonsterStart(b)
- MyGame.Example.Monster.MonsterAddTestempty(b, my_stat)
- mon = MyGame.Example.Monster.MonsterEnd(b)
- b.Finish(mon)
+ # build another monster to nest inside testnestedflatbuffer
+ nestedB = flatbuffers.Builder(0)
+ nameStr = nestedB.CreateString('Nested Monster')
+ _MONSTER.MonsterStart(nestedB)
+ _MONSTER.MonsterAddHp(nestedB, 30)
+ _MONSTER.MonsterAddName(nestedB, nameStr)
+ nestedMon = _MONSTER.MonsterEnd(nestedB)
+ nestedB.Finish(nestedMon)
- # inspect the resulting data:
- mon2 = MyGame.Example.Monster.Monster.GetRootAsMonster(b.Bytes,
- b.Head())
- self.assertEqual(123, mon2.Testempty().Val())
+ # write the nested FB bytes
+ sub_buf = _MONSTER.MonsterMakeTestnestedflatbufferVectorFromBytes(
+ b, nestedB.Output())
- def test_default_monster_testbool(self):
- self.assertFalse(self.mon.Testbool())
+ # make the parent monster and include the bytes of the nested monster
+ _MONSTER.MonsterStart(b)
+ _MONSTER.MonsterAddTestnestedflatbuffer(b, sub_buf)
+ mon = _MONSTER.MonsterEnd(b)
+ b.Finish(mon)
- def test_nondefault_monster_testbool(self):
- b = flatbuffers.Builder(0)
- MyGame.Example.Monster.MonsterStart(b)
- MyGame.Example.Monster.MonsterAddTestbool(b, True)
- mon = MyGame.Example.Monster.MonsterEnd(b)
- b.Finish(mon)
+ # inspect the resulting data:
+ mon2 = _MONSTER.Monster.GetRootAs(b.Bytes, b.Head())
+ nestedMon2 = mon2.TestnestedflatbufferNestedRoot()
+ self.assertEqual(b'Nested Monster', nestedMon2.Name())
+ self.assertEqual(30, nestedMon2.Hp())
- # inspect the resulting data:
- mon2 = MyGame.Example.Monster.Monster.GetRootAsMonster(b.Bytes,
- b.Head())
- self.assertTrue(mon2.Testbool())
+ def test_nondefault_monster_testempty(self):
+ b = flatbuffers.Builder(0)
- def test_default_monster_testhashes(self):
- self.assertEqual(0, self.mon.Testhashs32Fnv1())
- self.assertEqual(0, self.mon.Testhashu32Fnv1())
- self.assertEqual(0, self.mon.Testhashs64Fnv1())
- self.assertEqual(0, self.mon.Testhashu64Fnv1())
- self.assertEqual(0, self.mon.Testhashs32Fnv1a())
- self.assertEqual(0, self.mon.Testhashu32Fnv1a())
- self.assertEqual(0, self.mon.Testhashs64Fnv1a())
- self.assertEqual(0, self.mon.Testhashu64Fnv1a())
+ # make a Stat object:
+ _STAT.StatStart(b)
+ _STAT.StatAddVal(b, 123)
+ my_stat = _STAT.StatEnd(b)
+ b.Finish(my_stat)
- def test_nondefault_monster_testhashes(self):
- b = flatbuffers.Builder(0)
- MyGame.Example.Monster.MonsterStart(b)
- MyGame.Example.Monster.MonsterAddTesthashs32Fnv1(b, 1)
- MyGame.Example.Monster.MonsterAddTesthashu32Fnv1(b, 2)
- MyGame.Example.Monster.MonsterAddTesthashs64Fnv1(b, 3)
- MyGame.Example.Monster.MonsterAddTesthashu64Fnv1(b, 4)
- MyGame.Example.Monster.MonsterAddTesthashs32Fnv1a(b, 5)
- MyGame.Example.Monster.MonsterAddTesthashu32Fnv1a(b, 6)
- MyGame.Example.Monster.MonsterAddTesthashs64Fnv1a(b, 7)
- MyGame.Example.Monster.MonsterAddTesthashu64Fnv1a(b, 8)
- mon = MyGame.Example.Monster.MonsterEnd(b)
- b.Finish(mon)
+ # include the stat object in a monster:
+ _MONSTER.MonsterStart(b)
+ _MONSTER.MonsterAddTestempty(b, my_stat)
+ mon = _MONSTER.MonsterEnd(b)
+ b.Finish(mon)
- # inspect the resulting data:
- mon2 = MyGame.Example.Monster.Monster.GetRootAsMonster(b.Bytes,
- b.Head())
- self.assertEqual(1, mon2.Testhashs32Fnv1())
- self.assertEqual(2, mon2.Testhashu32Fnv1())
- self.assertEqual(3, mon2.Testhashs64Fnv1())
- self.assertEqual(4, mon2.Testhashu64Fnv1())
- self.assertEqual(5, mon2.Testhashs32Fnv1a())
- self.assertEqual(6, mon2.Testhashu32Fnv1a())
- self.assertEqual(7, mon2.Testhashs64Fnv1a())
- self.assertEqual(8, mon2.Testhashu64Fnv1a())
+ # inspect the resulting data:
+ mon2 = _MONSTER.Monster.GetRootAs(b.Bytes, b.Head())
+ self.assertEqual(123, mon2.Testempty().Val())
- def test_default_monster_parent_namespace_test(self):
- self.assertEqual(None, self.mon.ParentNamespaceTest())
+ def test_default_monster_testbool(self):
+ self.assertFalse(self.mon.Testbool())
- def test_nondefault_monster_parent_namespace_test(self):
- b = flatbuffers.Builder(0)
- MyGame.InParentNamespace.InParentNamespaceStart(b)
- parent = MyGame.InParentNamespace.InParentNamespaceEnd(b)
- MyGame.Example.Monster.MonsterStart(b)
- MyGame.Example.Monster.MonsterAddParentNamespaceTest(b, parent)
- mon = MyGame.Example.Monster.MonsterEnd(b)
- b.Finish(mon)
+ def test_nondefault_monster_testbool(self):
+ b = flatbuffers.Builder(0)
+ _MONSTER.MonsterStart(b)
+ _MONSTER.MonsterAddTestbool(b, True)
+ mon = _MONSTER.MonsterEnd(b)
+ b.Finish(mon)
- # Inspect the resulting data.
- monster = MyGame.Example.Monster.Monster.GetRootAsMonster(b.Bytes,
- b.Head())
- self.assertTrue(isinstance(monster.ParentNamespaceTest(),
- MyGame.InParentNamespace.InParentNamespace))
+ # inspect the resulting data:
+ mon2 = _MONSTER.Monster.GetRootAs(b.Bytes, b.Head())
+ self.assertTrue(mon2.Testbool())
- def test_getrootas_for_nonroot_table(self):
- b = flatbuffers.Builder(0)
- string = b.CreateString("MyStat")
+ def test_default_monster_testhashes(self):
+ self.assertEqual(0, self.mon.Testhashs32Fnv1())
+ self.assertEqual(0, self.mon.Testhashu32Fnv1())
+ self.assertEqual(0, self.mon.Testhashs64Fnv1())
+ self.assertEqual(0, self.mon.Testhashu64Fnv1())
+ self.assertEqual(0, self.mon.Testhashs32Fnv1a())
+ self.assertEqual(0, self.mon.Testhashu32Fnv1a())
+ self.assertEqual(0, self.mon.Testhashs64Fnv1a())
+ self.assertEqual(0, self.mon.Testhashu64Fnv1a())
- MyGame.Example.Stat.StatStart(b)
- MyGame.Example.Stat.StatAddId(b, string)
- MyGame.Example.Stat.StatAddVal(b, 12345678)
- MyGame.Example.Stat.StatAddCount(b, 12345)
- stat = MyGame.Example.Stat.StatEnd(b)
- b.Finish(stat)
+ def test_nondefault_monster_testhashes(self):
+ b = flatbuffers.Builder(0)
+ _MONSTER.MonsterStart(b)
+ _MONSTER.MonsterAddTesthashs32Fnv1(b, 1)
+ _MONSTER.MonsterAddTesthashu32Fnv1(b, 2)
+ _MONSTER.MonsterAddTesthashs64Fnv1(b, 3)
+ _MONSTER.MonsterAddTesthashu64Fnv1(b, 4)
+ _MONSTER.MonsterAddTesthashs32Fnv1a(b, 5)
+ _MONSTER.MonsterAddTesthashu32Fnv1a(b, 6)
+ _MONSTER.MonsterAddTesthashs64Fnv1a(b, 7)
+ _MONSTER.MonsterAddTesthashu64Fnv1a(b, 8)
+ mon = _MONSTER.MonsterEnd(b)
+ b.Finish(mon)
- stat2 = MyGame.Example.Stat.Stat.GetRootAsStat(b.Bytes, b.Head())
+ # inspect the resulting data:
+ mon2 = _MONSTER.Monster.GetRootAs(b.Bytes, b.Head())
+ self.assertEqual(1, mon2.Testhashs32Fnv1())
+ self.assertEqual(2, mon2.Testhashu32Fnv1())
+ self.assertEqual(3, mon2.Testhashs64Fnv1())
+ self.assertEqual(4, mon2.Testhashu64Fnv1())
+ self.assertEqual(5, mon2.Testhashs32Fnv1a())
+ self.assertEqual(6, mon2.Testhashu32Fnv1a())
+ self.assertEqual(7, mon2.Testhashs64Fnv1a())
+ self.assertEqual(8, mon2.Testhashu64Fnv1a())
- self.assertEqual(b"MyStat", stat2.Id())
- self.assertEqual(12345678, stat2.Val())
- self.assertEqual(12345, stat2.Count())
+ def test_default_monster_parent_namespace_test(self):
+ self.assertEqual(None, self.mon.ParentNamespaceTest())
+
+ def test_nondefault_monster_parent_namespace_test(self):
+ b = flatbuffers.Builder(0)
+ _IN_PARENT_NAMESPACE.InParentNamespaceStart(b)
+ parent = _IN_PARENT_NAMESPACE.InParentNamespaceEnd(b)
+ _MONSTER.MonsterStart(b)
+ _MONSTER.MonsterAddParentNamespaceTest(b, parent)
+ mon = _MONSTER.MonsterEnd(b)
+ b.Finish(mon)
+
+ # Inspect the resulting data.
+ monster = _MONSTER.Monster.GetRootAs(b.Bytes, b.Head())
+ self.assertTrue(
+ isinstance(monster.ParentNamespaceTest(),
+ _IN_PARENT_NAMESPACE.InParentNamespace))
+
+ def test_getrootas_for_nonroot_table(self):
+ b = flatbuffers.Builder(0)
+ string = b.CreateString('MyStat')
+
+ _STAT.StatStart(b)
+ _STAT.StatAddId(b, string)
+ _STAT.StatAddVal(b, 12345678)
+ _STAT.StatAddCount(b, 12345)
+ stat = _STAT.StatEnd(b)
+ b.Finish(stat)
+
+ stat2 = _STAT.Stat.GetRootAs(b.Bytes, b.Head())
+
+ self.assertEqual(b'MyStat', stat2.Id())
+ self.assertEqual(12345678, stat2.Val())
+ self.assertEqual(12345, stat2.Count())
class TestAllCodePathsOfMonsterExtraSchema(unittest.TestCase):
- def setUp(self, *args, **kwargs):
- super(TestAllCodePathsOfMonsterExtraSchema, self).setUp(*args, **kwargs)
- b = flatbuffers.Builder(0)
- MyGame.MonsterExtra.MonsterExtraStart(b)
- gen_mon = MyGame.MonsterExtra.MonsterExtraEnd(b)
- b.Finish(gen_mon)
+ def setUp(self, *args, **kwargs):
+ super(TestAllCodePathsOfMonsterExtraSchema, self).setUp(*args, **kwargs)
- self.mon = MyGame.MonsterExtra.MonsterExtra.GetRootAsMonsterExtra(b.Bytes, b.Head())
+ b = flatbuffers.Builder(0)
+ MyGame.MonsterExtra.Start(b)
+ gen_mon = MyGame.MonsterExtra.End(b)
+ b.Finish(gen_mon)
- def test_default_nan_inf(self):
- self.assertTrue(math.isnan(self.mon.F1()))
- self.assertEqual(self.mon.F2(), float("inf"))
- self.assertEqual(self.mon.F3(), float("-inf"))
+ self.mon = MyGame.MonsterExtra.MonsterExtra.GetRootAs(b.Bytes, b.Head())
- self.assertTrue(math.isnan(self.mon.D1()))
- self.assertEqual(self.mon.D2(), float("inf"))
- self.assertEqual(self.mon.D3(), float("-inf"))
+ def test_default_nan_inf(self):
+ self.assertTrue(math.isnan(self.mon.F1()))
+ self.assertEqual(self.mon.F2(), float('inf'))
+ self.assertEqual(self.mon.F3(), float('-inf'))
+
+ self.assertTrue(math.isnan(self.mon.D1()))
+ self.assertEqual(self.mon.D2(), float('inf'))
+ self.assertEqual(self.mon.D3(), float('-inf'))
class TestVtableDeduplication(unittest.TestCase):
- ''' TestVtableDeduplication verifies that vtables are deduplicated. '''
+ """ TestVtableDeduplication verifies that vtables are deduplicated. """
- def test_vtable_deduplication(self):
- b = flatbuffers.Builder(0)
+ def test_vtable_deduplication(self):
+ b = flatbuffers.Builder(0)
- b.StartObject(4)
- b.PrependByteSlot(0, 0, 0)
- b.PrependByteSlot(1, 11, 0)
- b.PrependByteSlot(2, 22, 0)
- b.PrependInt16Slot(3, 33, 0)
- obj0 = b.EndObject()
+ b.StartObject(4)
+ b.PrependByteSlot(0, 0, 0)
+ b.PrependByteSlot(1, 11, 0)
+ b.PrependByteSlot(2, 22, 0)
+ b.PrependInt16Slot(3, 33, 0)
+ obj0 = b.EndObject()
- b.StartObject(4)
- b.PrependByteSlot(0, 0, 0)
- b.PrependByteSlot(1, 44, 0)
- b.PrependByteSlot(2, 55, 0)
- b.PrependInt16Slot(3, 66, 0)
- obj1 = b.EndObject()
+ b.StartObject(4)
+ b.PrependByteSlot(0, 0, 0)
+ b.PrependByteSlot(1, 44, 0)
+ b.PrependByteSlot(2, 55, 0)
+ b.PrependInt16Slot(3, 66, 0)
+ obj1 = b.EndObject()
- b.StartObject(4)
- b.PrependByteSlot(0, 0, 0)
- b.PrependByteSlot(1, 77, 0)
- b.PrependByteSlot(2, 88, 0)
- b.PrependInt16Slot(3, 99, 0)
- obj2 = b.EndObject()
+ b.StartObject(4)
+ b.PrependByteSlot(0, 0, 0)
+ b.PrependByteSlot(1, 77, 0)
+ b.PrependByteSlot(2, 88, 0)
+ b.PrependInt16Slot(3, 99, 0)
+ obj2 = b.EndObject()
- got = b.Bytes[b.Head():]
+ got = b.Bytes[b.Head():]
- want = bytearray([
- 240, 255, 255, 255, # == -12. offset to dedupped vtable.
- 99, 0,
- 88,
- 77,
- 248, 255, 255, 255, # == -8. offset to dedupped vtable.
- 66, 0,
- 55,
- 44,
- 12, 0,
- 8, 0,
- 0, 0,
- 7, 0,
- 6, 0,
- 4, 0,
- 12, 0, 0, 0,
- 33, 0,
- 22,
- 11,
- ])
+ want = bytearray([
+ 240,
+ 255,
+ 255,
+ 255, # == -12. offset to dedupped vtable.
+ 99,
+ 0,
+ 88,
+ 77,
+ 248,
+ 255,
+ 255,
+ 255, # == -8. offset to dedupped vtable.
+ 66,
+ 0,
+ 55,
+ 44,
+ 12,
+ 0,
+ 8,
+ 0,
+ 0,
+ 0,
+ 7,
+ 0,
+ 6,
+ 0,
+ 4,
+ 0,
+ 12,
+ 0,
+ 0,
+ 0,
+ 33,
+ 0,
+ 22,
+ 11,
+ ])
- self.assertEqual((len(want), want), (len(got), got))
+ self.assertEqual((len(want), want), (len(got), got))
- table0 = flatbuffers.table.Table(b.Bytes, len(b.Bytes) - obj0)
- table1 = flatbuffers.table.Table(b.Bytes, len(b.Bytes) - obj1)
- table2 = flatbuffers.table.Table(b.Bytes, len(b.Bytes) - obj2)
+ table0 = flatbuffers.table.Table(b.Bytes, len(b.Bytes) - obj0)
+ table1 = flatbuffers.table.Table(b.Bytes, len(b.Bytes) - obj1)
+ table2 = flatbuffers.table.Table(b.Bytes, len(b.Bytes) - obj2)
- def _checkTable(tab, voffsett_value, b, c, d):
- # vtable size
- got = tab.GetVOffsetTSlot(0, 0)
- self.assertEqual(12, got, 'case 0, 0')
+ def _checkTable(tab, voffsett_value, b, c, d):
+ # vtable size
+ got = tab.GetVOffsetTSlot(0, 0)
+ self.assertEqual(12, got, 'case 0, 0')
- # object size
- got = tab.GetVOffsetTSlot(2, 0)
- self.assertEqual(8, got, 'case 2, 0')
+ # object size
+ got = tab.GetVOffsetTSlot(2, 0)
+ self.assertEqual(8, got, 'case 2, 0')
- # default value
- got = tab.GetVOffsetTSlot(4, 0)
- self.assertEqual(voffsett_value, got, 'case 4, 0')
+ # default value
+ got = tab.GetVOffsetTSlot(4, 0)
+ self.assertEqual(voffsett_value, got, 'case 4, 0')
- got = tab.GetSlot(6, 0, N.Uint8Flags)
- self.assertEqual(b, got, 'case 6, 0')
+ got = tab.GetSlot(6, 0, N.Uint8Flags)
+ self.assertEqual(b, got, 'case 6, 0')
- val = tab.GetSlot(8, 0, N.Uint8Flags)
- self.assertEqual(c, val, 'failed 8, 0')
+ val = tab.GetSlot(8, 0, N.Uint8Flags)
+ self.assertEqual(c, val, 'failed 8, 0')
- got = tab.GetSlot(10, 0, N.Uint8Flags)
- self.assertEqual(d, got, 'failed 10, 0')
+ got = tab.GetSlot(10, 0, N.Uint8Flags)
+ self.assertEqual(d, got, 'failed 10, 0')
- _checkTable(table0, 0, 11, 22, 33)
- _checkTable(table1, 0, 44, 55, 66)
- _checkTable(table2, 0, 77, 88, 99)
+ _checkTable(table0, 0, 11, 22, 33)
+ _checkTable(table1, 0, 44, 55, 66)
+ _checkTable(table2, 0, 77, 88, 99)
class TestExceptions(unittest.TestCase):
- def test_object_is_nested_error(self):
- b = flatbuffers.Builder(0)
- b.StartObject(0)
- assertRaises(self, lambda: b.StartObject(0),
- flatbuffers.builder.IsNestedError)
- def test_object_is_not_nested_error(self):
- b = flatbuffers.Builder(0)
- assertRaises(self, lambda: b.EndObject(),
- flatbuffers.builder.IsNotNestedError)
+ def test_object_is_nested_error(self):
+ b = flatbuffers.Builder(0)
+ b.StartObject(0)
+ assertRaises(self, lambda: b.StartObject(0),
+ flatbuffers.builder.IsNestedError)
- def test_struct_is_not_inline_error(self):
- b = flatbuffers.Builder(0)
- b.StartObject(0)
- assertRaises(self, lambda: b.PrependStructSlot(0, 1, 0),
- flatbuffers.builder.StructIsNotInlineError)
+ def test_object_is_not_nested_error(self):
+ b = flatbuffers.Builder(0)
+ assertRaises(self, lambda: b.EndObject(),
+ flatbuffers.builder.IsNotNestedError)
- def test_unreachable_error(self):
- b = flatbuffers.Builder(0)
- assertRaises(self, lambda: b.PrependUOffsetTRelative(1),
- flatbuffers.builder.OffsetArithmeticError)
+ def test_struct_is_not_inline_error(self):
+ b = flatbuffers.Builder(0)
+ b.StartObject(0)
+ assertRaises(self, lambda: b.PrependStructSlot(0, 1, 0),
+ flatbuffers.builder.StructIsNotInlineError)
- def test_create_string_is_nested_error(self):
- b = flatbuffers.Builder(0)
- b.StartObject(0)
- s = 'test1'
- assertRaises(self, lambda: b.CreateString(s),
- flatbuffers.builder.IsNestedError)
+ def test_unreachable_error(self):
+ b = flatbuffers.Builder(0)
+ assertRaises(self, lambda: b.PrependUOffsetTRelative(1),
+ flatbuffers.builder.OffsetArithmeticError)
- def test_create_byte_vector_is_nested_error(self):
- b = flatbuffers.Builder(0)
- b.StartObject(0)
- s = b'test1'
- assertRaises(self, lambda: b.CreateByteVector(s),
- flatbuffers.builder.IsNestedError)
+ def test_create_string_is_nested_error(self):
+ b = flatbuffers.Builder(0)
+ b.StartObject(0)
+ s = 'test1'
+ assertRaises(self, lambda: b.CreateString(s),
+ flatbuffers.builder.IsNestedError)
- def test_finished_bytes_error(self):
- b = flatbuffers.Builder(0)
- assertRaises(self, lambda: b.Output(),
- flatbuffers.builder.BuilderNotFinishedError)
+ def test_create_byte_vector_is_nested_error(self):
+ b = flatbuffers.Builder(0)
+ b.StartObject(0)
+ s = b'test1'
+ assertRaises(self, lambda: b.CreateByteVector(s),
+ flatbuffers.builder.IsNestedError)
+
+ def test_finished_bytes_error(self):
+ b = flatbuffers.Builder(0)
+ assertRaises(self, lambda: b.Output(),
+ flatbuffers.builder.BuilderNotFinishedError)
class TestFixedLengthArrays(unittest.TestCase):
- def test_fixed_length_array(self):
- builder = flatbuffers.Builder(0)
- a = 0.5
- b = range(0, 15)
- c = 1
- d_a = [[1, 2], [3, 4]]
- d_b = [MyGame.Example.TestEnum.TestEnum.B, \
- MyGame.Example.TestEnum.TestEnum.C]
- d_c = [[MyGame.Example.TestEnum.TestEnum.A, \
- MyGame.Example.TestEnum.TestEnum.B], \
- [MyGame.Example.TestEnum.TestEnum.C, \
- MyGame.Example.TestEnum.TestEnum.B]]
- d_d = [[-1, 1], [-2, 2]]
- e = 2
- f = [-1, 1]
+ def test_fixed_length_array(self):
+ builder = flatbuffers.Builder(0)
- arrayOffset = MyGame.Example.ArrayStruct.CreateArrayStruct(builder, \
- a, b, c, d_a, d_b, d_c, d_d, e, f)
-
- # Create a table with the ArrayStruct.
- MyGame.Example.ArrayTable.ArrayTableStart(builder)
- MyGame.Example.ArrayTable.ArrayTableAddA(builder, arrayOffset)
- tableOffset = MyGame.Example.ArrayTable.ArrayTableEnd(builder)
-
- builder.Finish(tableOffset)
-
- buf = builder.Output()
-
- table = MyGame.Example.ArrayTable.ArrayTable.GetRootAsArrayTable(buf, 0)
-
- # Verify structure.
- nested = MyGame.Example.NestedStruct.NestedStruct()
- self.assertEqual(table.A().A(), 0.5)
- self.assertEqual(table.A().B(), \
- [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])
- self.assertEqual(table.A().C(), 1)
- self.assertEqual(table.A().D(nested, 0).A(), [1, 2])
- self.assertEqual(table.A().D(nested, 1).A(), [3, 4])
- self.assertEqual(table.A().D(nested, 0).B(), \
- MyGame.Example.TestEnum.TestEnum.B)
- self.assertEqual(table.A().D(nested, 1).B(), \
- MyGame.Example.TestEnum.TestEnum.C)
- self.assertEqual(table.A().D(nested, 0).C(), \
- [MyGame.Example.TestEnum.TestEnum.A, \
- MyGame.Example.TestEnum.TestEnum.B])
- self.assertEqual(table.A().D(nested, 1).C(), \
+ a = 0.5
+ b = range(0, 15)
+ c = 1
+ d_a = [[1, 2], [3, 4]]
+ d_b = [MyGame.Example.TestEnum.TestEnum.B, \
+ MyGame.Example.TestEnum.TestEnum.C]
+ d_c = [[MyGame.Example.TestEnum.TestEnum.A, \
+ MyGame.Example.TestEnum.TestEnum.B], \
[MyGame.Example.TestEnum.TestEnum.C, \
- MyGame.Example.TestEnum.TestEnum.B])
- self.assertEqual(table.A().D(nested, 0).D(), [-1, 1])
- self.assertEqual(table.A().D(nested, 1).D(), [-2, 2])
- self.assertEqual(table.A().E(), 2)
- self.assertEqual(table.A().F(), [-1, 1])
+ MyGame.Example.TestEnum.TestEnum.B]]
+ d_d = [[-1, 1], [-2, 2]]
+ e = 2
+ f = [-1, 1]
+
+ arrayOffset = MyGame.Example.ArrayStruct.CreateArrayStruct(builder, \
+ a, b, c, d_a, d_b, d_c, d_d, e, f)
+
+ # Create a table with the ArrayStruct.
+ MyGame.Example.ArrayTable.Start(builder)
+ MyGame.Example.ArrayTable.AddA(builder, arrayOffset)
+ tableOffset = MyGame.Example.ArrayTable.End(builder)
+
+ builder.Finish(tableOffset)
+
+ buf = builder.Output()
+
+ table = MyGame.Example.ArrayTable.ArrayTable.GetRootAs(buf)
+
+ # Verify structure.
+ nested = MyGame.Example.NestedStruct.NestedStruct()
+ self.assertEqual(table.A().A(), 0.5)
+ self.assertEqual(table.A().B(), \
+ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])
+ self.assertEqual(table.A().C(), 1)
+ self.assertEqual(table.A().D(nested, 0).A(), [1, 2])
+ self.assertEqual(table.A().D(nested, 1).A(), [3, 4])
+ self.assertEqual(table.A().D(nested, 0).B(), \
+ MyGame.Example.TestEnum.TestEnum.B)
+ self.assertEqual(table.A().D(nested, 1).B(), \
+ MyGame.Example.TestEnum.TestEnum.C)
+ self.assertEqual(table.A().D(nested, 0).C(), \
+ [MyGame.Example.TestEnum.TestEnum.A, \
+ MyGame.Example.TestEnum.TestEnum.B])
+ self.assertEqual(table.A().D(nested, 1).C(), \
+ [MyGame.Example.TestEnum.TestEnum.C, \
+ MyGame.Example.TestEnum.TestEnum.B])
+ self.assertEqual(table.A().D(nested, 0).D(), [-1, 1])
+ self.assertEqual(table.A().D(nested, 1).D(), [-2, 2])
+ self.assertEqual(table.A().E(), 2)
+ self.assertEqual(table.A().F(), [-1, 1])
def CheckAgainstGoldDataGo():
- try:
- gen_buf, gen_off = make_monster_from_generated_code()
- fn = 'monsterdata_go_wire.mon'
- if not os.path.exists(fn):
- print('Go-generated data does not exist, failed.')
- return False
+ try:
+ gen_buf, gen_off = make_monster_from_generated_code()
+ fn = 'monsterdata_go_wire.mon'
+ if not os.path.exists(fn):
+ print('Go-generated data does not exist, failed.')
+ return False
- # would like to use a context manager here, but it's less
- # backwards-compatible:
- f = open(fn, 'rb')
- go_wire_data = f.read()
- f.close()
+ # would like to use a context manager here, but it's less
+ # backwards-compatible:
+ f = open(fn, 'rb')
+ go_wire_data = f.read()
+ f.close()
- CheckReadBuffer(bytearray(go_wire_data), 0)
- if not bytearray(gen_buf[gen_off:]) == bytearray(go_wire_data):
- raise AssertionError('CheckAgainstGoldDataGo failed')
- except:
- print('Failed to test against Go-generated test data.')
- return False
+ CheckReadBuffer(bytearray(go_wire_data), 0)
+ if not bytearray(gen_buf[gen_off:]) == bytearray(go_wire_data):
+ raise AssertionError('CheckAgainstGoldDataGo failed')
+ except:
+ print('Failed to test against Go-generated test data.')
+ return False
- print('Can read Go-generated test data, and Python generates bytewise identical data.')
- return True
+ print(
+ 'Can read Go-generated test data, and Python generates bytewise identical data.'
+ )
+ return True
def CheckAgainstGoldDataJava():
- try:
- gen_buf, gen_off = make_monster_from_generated_code()
- fn = 'monsterdata_java_wire.mon'
- if not os.path.exists(fn):
- print('Java-generated data does not exist, failed.')
- return False
- f = open(fn, 'rb')
- java_wire_data = f.read()
- f.close()
+ try:
+ gen_buf, gen_off = make_monster_from_generated_code()
+ fn = 'monsterdata_java_wire.mon'
+ if not os.path.exists(fn):
+ print('Java-generated data does not exist, failed.')
+ return False
+ f = open(fn, 'rb')
+ java_wire_data = f.read()
+ f.close()
- CheckReadBuffer(bytearray(java_wire_data), 0)
- except:
- print('Failed to read Java-generated test data.')
- return False
+ CheckReadBuffer(bytearray(java_wire_data), 0)
+ except:
+ print('Failed to read Java-generated test data.')
+ return False
- print('Can read Java-generated test data.')
- return True
+ print('Can read Java-generated test data.')
+ return True
class LCG(object):
- ''' Include simple random number generator to ensure results will be the
+ """ Include simple random number generator to ensure results will be the
+
same cross platform.
- http://en.wikipedia.org/wiki/Park%E2%80%93Miller_random_number_generator '''
+ http://en.wikipedia.org/wiki/Park%E2%80%93Miller_random_number_generator
+ """
- __slots__ = ['n']
+ __slots__ = ['n']
- InitialLCGSeed = 48271
+ InitialLCGSeed = 48271
- def __init__(self):
- self.n = self.InitialLCGSeed
+ def __init__(self):
+ self.n = self.InitialLCGSeed
- def Reset(self):
- self.n = self.InitialLCGSeed
+ def Reset(self):
+ self.n = self.InitialLCGSeed
- def Next(self):
- self.n = ((self.n * 279470273) % 4294967291) & 0xFFFFFFFF
- return self.n
+ def Next(self):
+ self.n = ((self.n * 279470273) % 4294967291) & 0xFFFFFFFF
+ return self.n
def BenchmarkVtableDeduplication(count):
- '''
+ """
BenchmarkVtableDeduplication measures the speed of vtable deduplication
by creating `prePop` vtables, then populating `count` objects with a
different single vtable.
When count is large (as in long benchmarks), memory usage may be high.
- '''
+ """
- for prePop in (1, 10, 100, 1000):
- builder = flatbuffers.Builder(0)
- n = 1 + int(math.log(prePop, 1.5))
+ for prePop in (1, 10, 100, 1000):
+ builder = flatbuffers.Builder(0)
+ n = 1 + int(math.log(prePop, 1.5))
- # generate some layouts:
- layouts = set()
- r = list(compat_range(n))
- while len(layouts) < prePop:
- layouts.add(tuple(sorted(random.sample(r, int(max(1, n / 2))))))
+ # generate some layouts:
+ layouts = set()
+ r = list(compat_range(n))
+ while len(layouts) < prePop:
+ layouts.add(tuple(sorted(random.sample(r, int(max(1, n / 2))))))
- layouts = list(layouts)
+ layouts = list(layouts)
- # pre-populate vtables:
- for layout in layouts:
- builder.StartObject(n)
- for j in layout:
- builder.PrependInt16Slot(j, j, 0)
- builder.EndObject()
+ # pre-populate vtables:
+ for layout in layouts:
+ builder.StartObject(n)
+ for j in layout:
+ builder.PrependInt16Slot(j, j, 0)
+ builder.EndObject()
- # benchmark deduplication of a new vtable:
- def f():
- layout = random.choice(layouts)
- builder.StartObject(n)
- for j in layout:
- builder.PrependInt16Slot(j, j, 0)
- builder.EndObject()
-
- duration = timeit.timeit(stmt=f, number=count)
- rate = float(count) / duration
- print(('vtable deduplication rate (n=%d, vtables=%d): %.2f sec' % (
- prePop,
- len(builder.vtables),
- rate))
- )
-
-
-def BenchmarkCheckReadBuffer(count, buf, off):
- '''
- BenchmarkCheckReadBuffer measures the speed of flatbuffer reading
- by re-using the CheckReadBuffer function with the gold data.
- '''
-
+ # benchmark deduplication of a new vtable:
def f():
- CheckReadBuffer(buf, off)
+ layout = random.choice(layouts)
+ builder.StartObject(n)
+ for j in layout:
+ builder.PrependInt16Slot(j, j, 0)
+ builder.EndObject()
duration = timeit.timeit(stmt=f, number=count)
rate = float(count) / duration
- data = float(len(buf) * count) / float(1024 * 1024)
- data_rate = data / float(duration)
+ print(('vtable deduplication rate (n=%d, vtables=%d): %.2f sec' %
+ (prePop, len(builder.vtables), rate)))
- print(('traversed %d %d-byte flatbuffers in %.2fsec: %.2f/sec, %.2fMB/sec')
- % (count, len(buf), duration, rate, data_rate))
+
+def BenchmarkCheckReadBuffer(count, buf, off):
+ """
+ BenchmarkCheckReadBuffer measures the speed of flatbuffer reading
+ by re-using the CheckReadBuffer function with the gold data.
+ """
+
+ def f():
+ CheckReadBuffer(buf, off)
+
+ duration = timeit.timeit(stmt=f, number=count)
+ rate = float(count) / duration
+ data = float(len(buf) * count) / float(1024 * 1024)
+ data_rate = data / float(duration)
+
+ print(('traversed %d %d-byte flatbuffers in %.2fsec: %.2f/sec, %.2fMB/sec') %
+ (count, len(buf), duration, rate, data_rate))
def BenchmarkMakeMonsterFromGeneratedCode(count, length):
- '''
+ """
BenchmarkMakeMonsterFromGeneratedCode measures the speed of flatbuffer
creation by re-using the make_monster_from_generated_code function for
generating gold data examples.
- '''
+ """
- duration = timeit.timeit(stmt=make_monster_from_generated_code,
- number=count)
- rate = float(count) / duration
- data = float(length * count) / float(1024 * 1024)
- data_rate = data / float(duration)
+ duration = timeit.timeit(stmt=make_monster_from_generated_code, number=count)
+ rate = float(count) / duration
+ data = float(length * count) / float(1024 * 1024)
+ data_rate = data / float(duration)
- print(('built %d %d-byte flatbuffers in %.2fsec: %.2f/sec, %.2fMB/sec' % \
- (count, length, duration, rate, data_rate)))
+ print(('built %d %d-byte flatbuffers in %.2fsec: %.2f/sec, %.2fMB/sec' % \
+ (count, length, duration, rate, data_rate)))
def backward_compatible_run_tests(**kwargs):
- if PY_VERSION < (2, 6):
- sys.stderr.write("Python version less than 2.6 are not supported")
- sys.stderr.flush()
+ if PY_VERSION < (2, 6):
+ sys.stderr.write('Python version less than 2.6 are not supported')
+ sys.stderr.flush()
+ return False
+
+ # python2.6 has a reduced-functionality unittest.main function:
+ if PY_VERSION == (2, 6):
+ try:
+ unittest.main(**kwargs)
+ except SystemExit as e:
+ if not e.code == 0:
return False
-
- # python2.6 has a reduced-functionality unittest.main function:
- if PY_VERSION == (2, 6):
- try:
- unittest.main(**kwargs)
- except SystemExit as e:
- if not e.code == 0:
- return False
- return True
-
- # python2.7 and above let us not exit once unittest.main is run:
- kwargs['exit'] = False
- kwargs['verbosity'] = 0
- ret = unittest.main(**kwargs)
- if ret.result.errors or ret.result.failures:
- return False
-
return True
+ # python2.7 and above let us not exit once unittest.main is run:
+ kwargs['exit'] = False
+ kwargs['verbosity'] = 0
+ ret = unittest.main(**kwargs)
+ if ret.result.errors or ret.result.failures:
+ return False
+
+ return True
+
+
def main():
- import os
- import sys
- if not len(sys.argv) == 4:
- sys.stderr.write('Usage: %s <benchmark vtable count>'
- '<benchmark read count> <benchmark build count>\n'
- % sys.argv[0])
- sys.stderr.write(' Provide COMPARE_GENERATED_TO_GO=1 to check'
- 'for bytewise comparison to Go data.\n')
- sys.stderr.write(' Provide COMPARE_GENERATED_TO_JAVA=1 to check'
- 'for bytewise comparison to Java data.\n')
- sys.stderr.flush()
- sys.exit(1)
+ import os
+ import sys
+ if not len(sys.argv) == 5:
+ sys.stderr.write('Usage: %s <benchmark vtable count> '
+ '<benchmark read count> <benchmark build count> '
+ '<is_onefile>\n' % sys.argv[0])
+ sys.stderr.write(' Provide COMPARE_GENERATED_TO_GO=1 to check'
+ 'for bytewise comparison to Go data.\n')
+ sys.stderr.write(' Provide COMPARE_GENERATED_TO_JAVA=1 to check'
+ 'for bytewise comparison to Java data.\n')
+ sys.stderr.flush()
+ sys.exit(1)
- kwargs = dict(argv=sys.argv[:-3])
+ kwargs = dict(argv=sys.argv[:-4])
- # show whether numpy is present, as it changes the test logic:
- try:
- import numpy
- print('numpy available')
- except ImportError:
- print('numpy not available')
+ create_namespace_shortcut(sys.argv[4].lower() == 'true')
- # run tests, and run some language comparison checks if needed:
- success = backward_compatible_run_tests(**kwargs)
- if success and os.environ.get('COMPARE_GENERATED_TO_GO', 0) == "1":
- success = success and CheckAgainstGoldDataGo()
- if success and os.environ.get('COMPARE_GENERATED_TO_JAVA', 0) == "1":
- success = success and CheckAgainstGoldDataJava()
+ # show whether numpy is present, as it changes the test logic:
+ try:
+ import numpy
+ print('numpy available')
+ except ImportError:
+ print('numpy not available')
- if not success:
- sys.stderr.write('Tests failed, skipping benchmarks.\n')
- sys.stderr.flush()
- sys.exit(1)
+ # run tests, and run some language comparison checks if needed:
+ success = backward_compatible_run_tests(**kwargs)
+ if success and os.environ.get('COMPARE_GENERATED_TO_GO', 0) == '1':
+ success = success and CheckAgainstGoldDataGo()
+ if success and os.environ.get('COMPARE_GENERATED_TO_JAVA', 0) == '1':
+ success = success and CheckAgainstGoldDataJava()
- # run benchmarks (if 0, they will be a noop):
- bench_vtable = int(sys.argv[1])
- bench_traverse = int(sys.argv[2])
- bench_build = int(sys.argv[3])
- if bench_vtable:
- BenchmarkVtableDeduplication(bench_vtable)
- if bench_traverse:
- buf, off = make_monster_from_generated_code()
- BenchmarkCheckReadBuffer(bench_traverse, buf, off)
- if bench_build:
- buf, off = make_monster_from_generated_code()
- BenchmarkMakeMonsterFromGeneratedCode(bench_build, len(buf))
+ if not success:
+ sys.stderr.write('Tests failed, skipping benchmarks.\n')
+ sys.stderr.flush()
+ sys.exit(1)
+
+ # run benchmarks (if 0, they will be a noop):
+ bench_vtable = int(sys.argv[1])
+ bench_traverse = int(sys.argv[2])
+ bench_build = int(sys.argv[3])
+ if bench_vtable:
+ BenchmarkVtableDeduplication(bench_vtable)
+ if bench_traverse:
+ buf, off = make_monster_from_generated_code()
+ BenchmarkCheckReadBuffer(bench_traverse, buf, off)
+ if bench_build:
+ buf, off = make_monster_from_generated_code()
+ BenchmarkMakeMonsterFromGeneratedCode(bench_build, len(buf))
+
if __name__ == '__main__':
- main()
+ main()
diff --git a/tests/rust_serialize_test/Cargo.toml b/tests/rust_serialize_test/Cargo.toml
new file mode 100644
index 0000000..ff47c12
--- /dev/null
+++ b/tests/rust_serialize_test/Cargo.toml
@@ -0,0 +1,12 @@
+[package]
+name = "rust_serialize_test"
+version = "0.1.0"
+edition = "2021"
+
+# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+
+[dependencies]
+flatbuffers = { path = "../../rust/flatbuffers", features=["serialize"] }
+serde = "1.0"
+serde_json = "1.0"
+
diff --git a/tests/rust_serialize_test/src/main.rs b/tests/rust_serialize_test/src/main.rs
new file mode 100644
index 0000000..d67cc20
--- /dev/null
+++ b/tests/rust_serialize_test/src/main.rs
@@ -0,0 +1,89 @@
+#[allow(dead_code, unused_imports)]
+#[path = "../../monster_test_serialize/mod.rs"]
+mod monster_test_serialize_generated;
+pub use monster_test_serialize_generated::my_game;
+
+fn create_serialized_example_with_generated_code(builder: &mut flatbuffers::FlatBufferBuilder) {
+ let mon = {
+ let s0 = builder.create_string("test1");
+ let s1 = builder.create_string("test2");
+ let fred_name = builder.create_string("Fred");
+
+ // can't inline creation of this Vec3 because we refer to it by reference, so it must live
+ // long enough to be used by MonsterArgs.
+ let pos = my_game::example::Vec3::new(
+ 1.0,
+ 2.0,
+ 3.0,
+ 3.0,
+ my_game::example::Color::Green,
+ &my_game::example::Test::new(5i16, 6i8),
+ );
+
+ let args = my_game::example::MonsterArgs {
+ hp: 80,
+ mana: 150,
+ name: Some(builder.create_string("MyMonster")),
+ pos: Some(&pos),
+ test_type: my_game::example::Any::Monster,
+ test: Some(
+ my_game::example::Monster::create(
+ builder,
+ &my_game::example::MonsterArgs {
+ name: Some(fred_name),
+ ..Default::default()
+ },
+ )
+ .as_union_value(),
+ ),
+ inventory: Some(builder.create_vector_direct(&[0u8, 1, 2, 3, 4][..])),
+ test4: Some(builder.create_vector_direct(&[
+ my_game::example::Test::new(10, 20),
+ my_game::example::Test::new(30, 40),
+ ])),
+ testarrayofstring: Some(builder.create_vector(&[s0, s1])),
+ ..Default::default()
+ };
+ my_game::example::Monster::create(builder, &args)
+ };
+ my_game::example::finish_monster_buffer(builder, mon);
+}
+
+fn main() {
+ // This test is built into its own crate because it has a different set of
+ // dependencies as the normal Rust tests; it requires that the `flatbuffer`
+ // dependency have the "serialize" feature enabled. As this feature may
+ // cause extra code gen and dependencies for those who do not need it, it
+ // is disabled by default.
+ let mut builder = flatbuffers::FlatBufferBuilder::new();
+ create_serialized_example_with_generated_code(&mut builder);
+
+ let data = builder.finished_data();
+ let obj = my_game::example::root_as_monster(&data[..]).unwrap();
+ let value = serde_json::to_value(&obj).unwrap();
+ let o = value.as_object().unwrap();
+
+ let pos = o.get("pos").unwrap().as_object().unwrap();
+ assert_eq!(pos.get("x").unwrap().as_f64().unwrap(), 1.0);
+ assert_eq!(pos.get("y").unwrap().as_f64().unwrap(), 2.0);
+ assert_eq!(pos.get("z").unwrap().as_f64().unwrap(), 3.0);
+
+ let mana = o.get("mana").unwrap();
+ assert_eq!(mana.as_i64().unwrap(), 150);
+
+ let hp = o.get("hp").unwrap();
+ assert_eq!(hp.as_i64().unwrap(), 80);
+
+ let name = o.get("name").unwrap();
+ assert_eq!(name.as_str().unwrap(), "MyMonster");
+
+ let test_type = o.get("test_type").unwrap();
+ assert_eq!(test_type.as_str().unwrap(), "Monster");
+
+ let testarrayofstring = o.get("testarrayofstring").unwrap().as_array().unwrap();
+ let t0 = testarrayofstring[0].as_str().unwrap();
+ assert_eq!(t0, "test1");
+
+ let t1 = testarrayofstring[1].as_str().unwrap();
+ assert_eq!(t1, "test2");
+}
diff --git a/tests/rust_usage_test/Cargo.toml b/tests/rust_usage_test/Cargo.toml
index 664396d..e676970 100644
--- a/tests/rust_usage_test/Cargo.toml
+++ b/tests/rust_usage_test/Cargo.toml
@@ -6,11 +6,16 @@
"FlatBuffers Maintainers"]
[dependencies]
-flatbuffers = { path = "../../rust/flatbuffers" }
+flatbuffers = { path = "../../rust/flatbuffers", default-features = false }
flexbuffers = { path = "../../rust/flexbuffers" }
serde_derive = "1.0"
serde = "1.0"
serde_bytes = "0.11"
+libc_alloc = { version = "1.0.3", optional = true }
+
+[features]
+default = ["flatbuffers/default"]
+no_std = ["flatbuffers/no_std", "libc_alloc"]
[[bin]]
name = "monster_example"
@@ -36,14 +41,15 @@
name = "sample_flatbuffers"
path = "../../samples/sample_binary.rs"
-
[dev-dependencies]
quickcheck = "0.6"
# TODO(rw): look into moving to criterion.rs
+serde = "1.0"
bencher = "0.1.5"
static_assertions = "1.0.0"
rand = "*"
quickcheck_derive = "*"
+array-init = "2.0"
[[bench]]
# setup for bencher
diff --git a/tests/rust_usage_test/benches/benchmarks.rs b/tests/rust_usage_test/benches/benchmarks.rs
index bfe63b6..51fae75 100644
--- a/tests/rust_usage_test/benches/benchmarks.rs
+++ b/tests/rust_usage_test/benches/benchmarks.rs
@@ -23,15 +23,7 @@
mod flexbuffers_benchmarks;
#[allow(dead_code, unused_imports)]
-#[path = "../../include_test/include_test1_generated.rs"]
-pub mod include_test1_generated;
-
-#[allow(dead_code, unused_imports)]
-#[path = "../../include_test/sub/include_test2_generated.rs"]
-pub mod include_test2_generated;
-
-#[allow(dead_code, unused_imports)]
-#[path = "../../monster_test_generated.rs"]
+#[path = "../../monster_test/mod.rs"]
mod monster_test_generated;
pub use monster_test_generated::my_game;
diff --git a/tests/rust_usage_test/benches/flatbuffers_benchmarks.rs b/tests/rust_usage_test/benches/flatbuffers_benchmarks.rs
index ee6d81d..580d433 100644
--- a/tests/rust_usage_test/benches/flatbuffers_benchmarks.rs
+++ b/tests/rust_usage_test/benches/flatbuffers_benchmarks.rs
@@ -14,18 +14,12 @@
* limitations under the License.
*/
+use flatbuffers;
use bencher::Bencher;
-#[allow(dead_code, unused_imports)]
-#[path = "../../include_test/include_test1_generated.rs"]
-pub mod include_test1_generated;
#[allow(dead_code, unused_imports)]
-#[path = "../../include_test/sub/include_test2_generated.rs"]
-pub mod include_test2_generated;
-
-#[allow(dead_code, unused_imports)]
-#[path = "../../monster_test_generated.rs"]
+#[path = "../../monster_test/mod.rs"]
mod monster_test_generated;
pub use monster_test_generated::my_game;
@@ -148,7 +142,7 @@
#[inline(always)]
fn traverse_serialized_example_with_generated_code(bytes: &[u8]) {
- let m = my_game::example::get_root_as_monster(bytes);
+ let m = unsafe { my_game::example::root_as_monster_unchecked(bytes) };
blackbox(m.hp());
blackbox(m.mana());
blackbox(m.name());
@@ -178,7 +172,7 @@
}
fn create_string_10(bench: &mut Bencher) {
- let builder = &mut flatbuffers::FlatBufferBuilder::new_with_capacity(1 << 20);
+ let builder = &mut flatbuffers::FlatBufferBuilder::with_capacity(1 << 20);
let mut i = 0;
bench.iter(|| {
builder.create_string("foobarbaz"); // zero-terminated -> 10 bytes
@@ -193,7 +187,7 @@
}
fn create_string_100(bench: &mut Bencher) {
- let builder = &mut flatbuffers::FlatBufferBuilder::new_with_capacity(1 << 20);
+ let builder = &mut flatbuffers::FlatBufferBuilder::with_capacity(1 << 20);
let s_owned = (0..99).map(|_| "x").collect::<String>();
let s: &str = &s_owned;
@@ -211,7 +205,7 @@
}
fn create_byte_vector_100_naive(bench: &mut Bencher) {
- let builder = &mut flatbuffers::FlatBufferBuilder::new_with_capacity(1 << 20);
+ let builder = &mut flatbuffers::FlatBufferBuilder::with_capacity(1 << 20);
let v_owned = (0u8..100).map(|i| i).collect::<Vec<u8>>();
let v: &[u8] = &v_owned;
@@ -229,7 +223,7 @@
}
fn create_byte_vector_100_optimal(bench: &mut Bencher) {
- let builder = &mut flatbuffers::FlatBufferBuilder::new_with_capacity(1 << 20);
+ let builder = &mut flatbuffers::FlatBufferBuilder::with_capacity(1 << 20);
let v_owned = (0u8..100).map(|i| i).collect::<Vec<u8>>();
let v: &[u8] = &v_owned;
@@ -246,6 +240,24 @@
bench.bytes = v.len() as u64;
}
+fn create_many_tables(bench: &mut Bencher) {
+ let builder = &mut flatbuffers::FlatBufferBuilder::with_capacity(1 << 20);
+ // We test vtable overhead by making many unique tables of up to 16 fields of u8s.
+ bench.iter(|| {
+ for i in 0..(1u16 << 10) {
+ let t = builder.start_table();
+ for j in 0..15 {
+ if i & (1 << j) == 1 {
+ builder.push_slot_always(i * 2, 42u8);
+ }
+ }
+ builder.end_table(t);
+ }
+ builder.reset();
+ });
+ bench.bytes = 1 << 15;
+}
+
benchmark_group!(
benches,
create_byte_vector_100_naive,
@@ -253,5 +265,6 @@
traverse_canonical_buffer,
create_canonical_buffer_then_reset,
create_string_10,
- create_string_100
+ create_string_100,
+ create_many_tables,
);
diff --git a/tests/rust_usage_test/benches/flexbuffers_benchmarks.rs b/tests/rust_usage_test/benches/flexbuffers_benchmarks.rs
index 1e9c516..1b9a8fb 100644
--- a/tests/rust_usage_test/benches/flexbuffers_benchmarks.rs
+++ b/tests/rust_usage_test/benches/flexbuffers_benchmarks.rs
@@ -224,7 +224,7 @@
b.iter(go);
b.bytes = n as u64;
}
-fn validate_monster(r: MapReader) {
+fn validate_monster(r: MapReader<&[u8]>) {
assert_eq!(r.idx("type").as_str(), "great orc");
assert_eq!(r.idx("age").as_u8(), 100);
assert_eq!(r.idx("name").as_str(), "Mr. Orc");
diff --git a/tests/rust_usage_test/bin/flatbuffers_alloc_check.rs b/tests/rust_usage_test/bin/flatbuffers_alloc_check.rs
index c47e86e..418783c 100644
--- a/tests/rust_usage_test/bin/flatbuffers_alloc_check.rs
+++ b/tests/rust_usage_test/bin/flatbuffers_alloc_check.rs
@@ -29,15 +29,15 @@
// import the flatbuffers generated code:
extern crate flatbuffers;
#[allow(dead_code, unused_imports)]
-#[path = "../../include_test/include_test1_generated.rs"]
+#[path = "../../include_test1/mod.rs"]
pub mod include_test1_generated;
#[allow(dead_code, unused_imports)]
-#[path = "../../include_test/sub/include_test2_generated.rs"]
+#[path = "../../include_test2/mod.rs"]
pub mod include_test2_generated;
-#[allow(dead_code, unused_imports)]
-#[path = "../../monster_test_generated.rs"]
+#[allow(dead_code, unused_imports, clippy::approx_constant)]
+#[path = "../../monster_test/mod.rs"]
mod monster_test_generated;
pub use monster_test_generated::my_game;
@@ -98,6 +98,7 @@
my_game::example::finish_monster_buffer(builder, mon);
}
+#[cfg(not(miri))] // slow.
fn main() {
// test the allocation tracking:
{
@@ -131,7 +132,7 @@
// do many reads, forcing them to execute by using assert_eq:
{
- let m = my_game::example::get_root_as_monster(buf);
+ let m = unsafe { my_game::example::root_as_monster_unchecked(buf) };
assert_eq!(80, m.hp());
assert_eq!(150, m.mana());
assert_eq!("MyMonster", m.name());
diff --git a/tests/rust_usage_test/bin/flexbuffers_alloc_check.rs b/tests/rust_usage_test/bin/flexbuffers_alloc_check.rs
index 310d1a9..a921af7 100644
--- a/tests/rust_usage_test/bin/flexbuffers_alloc_check.rs
+++ b/tests/rust_usage_test/bin/flexbuffers_alloc_check.rs
@@ -70,6 +70,10 @@
fn validate_monster(flexbuffer: &[u8]) {
let r = Reader::get_root(flexbuffer).unwrap().as_map();
+ assert!(!r.is_empty());
+ assert!(r.index_key("not_a_field").is_none());
+
+ assert_eq!(r.len(), 7);
assert_eq!(r.idx("type").as_str(), "great orc");
assert_eq!(r.idx("age").as_u8(), 100);
assert_eq!(r.idx("name").as_str(), "Mr. Orc");
@@ -103,6 +107,7 @@
// This is in a separate binary than tests because taking over the global allocator is not
// hermetic and not thread safe.
+#[cfg(not(miri))] // slow.
fn main() {
let start_up = current_allocs();
@@ -133,6 +138,7 @@
}
#[test]
+#[cfg(not(miri))] // slow.
fn no_extra_allocations() {
main()
}
diff --git a/tests/rust_usage_test/bin/monster_example.rs b/tests/rust_usage_test/bin/monster_example.rs
index d0b75d7..17ce0e0 100644
--- a/tests/rust_usage_test/bin/monster_example.rs
+++ b/tests/rust_usage_test/bin/monster_example.rs
@@ -1,15 +1,15 @@
extern crate flatbuffers;
#[allow(dead_code, unused_imports)]
-#[path = "../../include_test/include_test1_generated.rs"]
+#[path = "../../include_test1/mod.rs"]
pub mod include_test1_generated;
#[allow(dead_code, unused_imports)]
-#[path = "../../include_test/sub/include_test2_generated.rs"]
+#[path = "../../include_test2/mod.rs"]
pub mod include_test2_generated;
-#[allow(dead_code, unused_imports)]
-#[path = "../../monster_test_generated.rs"]
+#[allow(dead_code, unused_imports, clippy::approx_constant)]
+#[path = "../../monster_test/mod.rs"]
mod monster_test_generated;
pub use monster_test_generated::my_game;
@@ -20,7 +20,7 @@
let mut buf = Vec::new();
f.read_to_end(&mut buf).expect("file reading failed");
- let monster = my_game::example::get_root_as_monster(&buf[..]);
+ let monster = my_game::example::root_as_monster(&buf[..]).unwrap();
println!("{}", monster.hp()); // `80`
println!("{}", monster.mana()); // default value of `150`
println!("{:?}", monster.name()); // Some("MyMonster")
diff --git a/tests/rust_usage_test/outdir/.gitignore b/tests/rust_usage_test/outdir/.gitignore
new file mode 100644
index 0000000..c83f90a
--- /dev/null
+++ b/tests/rust_usage_test/outdir/.gitignore
@@ -0,0 +1 @@
+src/generated
diff --git a/tests/rust_usage_test/outdir/Cargo.toml b/tests/rust_usage_test/outdir/Cargo.toml
new file mode 100644
index 0000000..659638f
--- /dev/null
+++ b/tests/rust_usage_test/outdir/Cargo.toml
@@ -0,0 +1,11 @@
+[package]
+name = "outdir"
+version = "0.1.0"
+authors = ["Casper Neo <cneo@google.com>"]
+edition = "2018"
+
+# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+
+[dependencies]
+flatbuffers = { path = "../../../rust/flatbuffers" }
+serde = "1.0"
diff --git a/tests/rust_usage_test/outdir/build.rs b/tests/rust_usage_test/outdir/build.rs
new file mode 100644
index 0000000..0462828
--- /dev/null
+++ b/tests/rust_usage_test/outdir/build.rs
@@ -0,0 +1,56 @@
+fn main() {
+ use std::process::Command;
+ let project_root = std::env::current_dir()
+ .unwrap()
+ .parent() // flatbuffers/tests/rust_usage test
+ .unwrap()
+ .parent() // flatbuffers/tests
+ .unwrap()
+ .parent() // flatbuffers/
+ .unwrap()
+ .to_path_buf();
+ let sample_schema = {
+ let mut s = project_root.to_path_buf();
+ s.push("samples");
+ s.push("monster.fbs");
+ s
+ };
+
+ let flatc = {
+ let mut f = project_root.to_path_buf();
+ f.push("flatc");
+ f
+ };
+
+ let out_dir = {
+ let mut d = std::path::Path::new(&std::env::var("OUT_DIR").unwrap()).to_path_buf();
+ d.push("flatbuffers");
+ d
+ };
+
+ Command::new(&flatc)
+ .arg("-o")
+ .arg(&out_dir)
+ .arg("--rust")
+ .arg(&sample_schema)
+ .output()
+ .expect("Failed to generate file");
+
+ assert!(out_dir.exists());
+
+ let generated = std::path::Path::new("src/generated");
+ #[cfg(target_os = "windows")]
+ {
+ if generated.exists() {
+ std::fs::remove_dir(generated).unwrap();
+ }
+ std::os::windows::fs::symlink_dir(out_dir, generated).unwrap();
+ }
+ #[cfg(not(target_os = "windows"))]
+ {
+ if generated.exists() {
+ std::fs::remove_file(generated).unwrap();
+ }
+ std::os::unix::fs::symlink(out_dir, generated).unwrap();
+ }
+}
diff --git a/tests/rust_usage_test/outdir/src/main.rs b/tests/rust_usage_test/outdir/src/main.rs
new file mode 100644
index 0000000..734e137
--- /dev/null
+++ b/tests/rust_usage_test/outdir/src/main.rs
@@ -0,0 +1,29 @@
+// In this example, a build.rs file generates the code and then copies it into generated/
+extern crate flatbuffers;
+#[allow(unused_imports, dead_code)]
+mod generated;
+use generated::my_game::sample::{Monster, MonsterArgs};
+
+fn main() {
+ let mut fbb = flatbuffers::FlatBufferBuilder::new();
+ let name = Some(fbb.create_string("bob"));
+ let m = Monster::create(
+ &mut fbb,
+ &MonsterArgs {
+ hp: 1,
+ mana: 2,
+ name,
+ ..Default::default()
+ },
+ );
+ fbb.finish(m, None);
+ let mon = flatbuffers::root::<Monster>(fbb.finished_data()).unwrap();
+ assert_eq!(mon.hp(), 1);
+ assert_eq!(mon.mana(), 2);
+ assert_eq!(mon.name().unwrap(), "bob");
+}
+
+#[test]
+fn test_main() {
+ main()
+}
diff --git a/tests/rust_usage_test/tests/arrays_test.rs b/tests/rust_usage_test/tests/arrays_test.rs
new file mode 100644
index 0000000..faa0ac8
--- /dev/null
+++ b/tests/rust_usage_test/tests/arrays_test.rs
@@ -0,0 +1,325 @@
+extern crate array_init;
+#[allow(dead_code, unused_imports)]
+#[path = "../../arrays_test/mod.rs"]
+mod arrays_test_generated;
+use std::fmt::Debug;
+
+use crate::arrays_test_generated::my_game::example::*;
+extern crate quickcheck;
+use array_init::array_init;
+use std::mem::size_of;
+use quickcheck::{Arbitrary, Gen};
+
+
+fn create_serialized_example_with_generated_code(builder: &mut flatbuffers::FlatBufferBuilder) {
+ let nested_struct1 = NestedStruct::new(
+ &[-1, 2],
+ TestEnum::A,
+ &[TestEnum::C, TestEnum::B],
+ &[0x1122334455667788, -0x1122334455667788],
+ );
+ let nested_struct2 = NestedStruct::new(
+ &[3, -4],
+ TestEnum::B,
+ &[TestEnum::B, TestEnum::A],
+ &[-0x1122334455667788, 0x1122334455667788],
+ );
+ let array_struct = ArrayStruct::new(
+ 12.34,
+ &[1, 2, 3, 4, 5, 6, 7, 8, 9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF],
+ -127,
+ &[nested_struct1, nested_struct2],
+ 1,
+ &[-0x8000000000000000, 0x7FFFFFFFFFFFFFFF],
+ );
+ // Test five makes sense when specified.
+ let ss = ArrayTable::create(
+ builder,
+ &ArrayTableArgs {
+ a: Some(&array_struct),
+ },
+ );
+ finish_array_table_buffer(builder, ss);
+}
+
+fn serialized_example_is_accessible_and_correct(
+ bytes: &[u8],
+ identifier_required: bool,
+ size_prefixed: bool,
+) {
+ if identifier_required {
+ let correct = if size_prefixed {
+ array_table_size_prefixed_buffer_has_identifier(bytes)
+ } else {
+ array_table_buffer_has_identifier(bytes)
+ };
+ assert_eq!(correct, true);
+ }
+
+ let array_table = if size_prefixed {
+ size_prefixed_root_as_array_table(bytes).unwrap()
+ } else {
+ root_as_array_table(bytes).unwrap()
+ };
+
+ let array_struct = array_table.a().unwrap();
+ assert_eq!(array_struct.a(), 12.34);
+ assert_eq!(array_struct.b().len(), 0xF);
+ assert_eq!(array_struct.b().iter().sum::<i32>(), 120);
+ assert_eq!(array_struct.c(), -127);
+
+ assert_eq!(array_struct.d().len(), 2);
+ let nested_struct1 = array_struct.d().get(0);
+ assert_eq!(nested_struct1.a().len(), 2);
+ assert_eq!(nested_struct1.a().iter().sum::<i32>(), 1);
+ assert_eq!(nested_struct1.b(), TestEnum::A);
+ assert_eq!(nested_struct1.c().len(), 2);
+ assert_eq!(nested_struct1.c().get(0), TestEnum::C);
+ assert_eq!(nested_struct1.c().get(1), TestEnum::B);
+ assert_eq!(nested_struct1.d().len(), 2);
+ assert_eq!(
+ [nested_struct1.d().get(0), nested_struct1.d().get(1)],
+ [0x1122334455667788, -0x1122334455667788]
+ );
+ let nested_struct2 = array_struct.d().get(1);
+ assert_eq!(nested_struct2.a().len(), 2);
+ assert_eq!(nested_struct2.a().iter().sum::<i32>(), -1);
+ assert_eq!(nested_struct2.b(), TestEnum::B);
+ assert_eq!(nested_struct2.c().len(), 2);
+ assert_eq!(nested_struct2.c().get(0), TestEnum::B);
+ assert_eq!(nested_struct2.c().get(1), TestEnum::A);
+ assert_eq!(nested_struct2.d().len(), 2);
+ let arr: [i64; 2] = nested_struct2.d().into();
+ assert_eq!(
+ arr,
+ [-0x1122334455667788, 0x1122334455667788]
+ );
+
+ assert_eq!(array_struct.e(), 1);
+ assert_eq!(array_struct.f().len(), 2);
+ assert_eq!(array_struct.f().get(0), -0x8000000000000000);
+ assert_eq!(array_struct.f().get(1), 0x7FFFFFFFFFFFFFFF);
+}
+
+#[test]
+fn generated_code_creates_correct_example() {
+ let mut b = flatbuffers::FlatBufferBuilder::new();
+ create_serialized_example_with_generated_code(&mut b);
+ let buf = b.finished_data();
+ serialized_example_is_accessible_and_correct(&buf[..], true, false);
+}
+
+#[test]
+fn struct_netsted_struct_is_32_bytes() {
+ assert_eq!(32, ::std::mem::size_of::<NestedStruct>());
+}
+
+#[test]
+fn struct_array_struct_is_160_bytes() {
+ assert_eq!(160, ::std::mem::size_of::<ArrayStruct>());
+}
+
+#[test]
+fn test_object_api_reads_correctly() {
+ let mut b = flatbuffers::FlatBufferBuilder::new();
+ create_serialized_example_with_generated_code(&mut b);
+
+ let array_table = root_as_array_table(b.finished_data()).unwrap().unpack();
+
+ let array_struct = array_table.a.unwrap();
+ assert_eq!(array_struct.a, 12.34);
+ assert_eq!(array_struct.b.len(), 0xF);
+ assert_eq!(array_struct.b.iter().sum::<i32>(), 120);
+ assert_eq!(array_struct.c, -127);
+
+ assert_eq!(array_struct.d.len(), 2);
+ let nested_struct1 = &array_struct.d[0];
+ assert_eq!(nested_struct1.a.len(), 2);
+ assert_eq!(nested_struct1.a.iter().sum::<i32>(), 1);
+ assert_eq!(nested_struct1.b, TestEnum::A);
+ assert_eq!(nested_struct1.c.len(), 2);
+ assert_eq!(nested_struct1.c[0], TestEnum::C);
+ assert_eq!(nested_struct1.c[1], TestEnum::B);
+ assert_eq!(nested_struct1.d.len(), 2);
+ assert_eq!(nested_struct1.d, [0x1122334455667788, -0x1122334455667788]);
+ let nested_struct2 = &array_struct.d[1];
+ assert_eq!(nested_struct2.a.len(), 2);
+ assert_eq!(nested_struct2.a.iter().sum::<i32>(), -1);
+ assert_eq!(nested_struct2.b, TestEnum::B);
+ assert_eq!(nested_struct2.c.len(), 2);
+ assert_eq!(nested_struct2.c[0], TestEnum::B);
+ assert_eq!(nested_struct2.c[1], TestEnum::A);
+ assert_eq!(nested_struct2.d.len(), 2);
+ assert_eq!(nested_struct2.d, [-0x1122334455667788, 0x1122334455667788]);
+
+ assert_eq!(array_struct.e, 1);
+ assert_eq!(array_struct.f.len(), 2);
+ assert_eq!(array_struct.f[0], -0x8000000000000000);
+ assert_eq!(array_struct.f[1], 0x7FFFFFFFFFFFFFFF);
+}
+
+#[test]
+fn object_api_defaults() {
+ use arrays_test_generated::my_game::example::*;
+
+ assert_eq!(
+ NestedStructT::default(),
+ NestedStructT {
+ a: [0, 0],
+ b: TestEnum::default(),
+ c: [TestEnum::default(), TestEnum::default()],
+ d: [0, 0]
+ }
+ );
+
+ assert_eq!(
+ ArrayStructT::default(),
+ ArrayStructT {
+ a: 0.0,
+ b: [0; 0xF],
+ c: 0,
+ d: [NestedStructT::default(), NestedStructT::default()],
+ e: 0,
+ f: [0, 0]
+ }
+ );
+}
+
+#[test]
+fn generated_code_debug_prints_correctly() {
+ let b = &mut flatbuffers::FlatBufferBuilder::new();
+ create_serialized_example_with_generated_code(b);
+ let buf = b.finished_data();
+ let array_table = root_as_array_table(buf).unwrap();
+ assert_eq!(
+ format!("{:.5?}", &array_table),
+ "ArrayTable { a: Some(ArrayStruct { a: 12.34000, \
+ b: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], \
+ c: -127, d: [NestedStruct { a: [-1, 2], b: A, c: [C, B], \
+ d: [1234605616436508552, -1234605616436508552] }, \
+ NestedStruct { a: [3, -4], b: B, c: [B, A], d: [-1234605616436508552, 1234605616436508552] }], \
+ e: 1, f: [-9223372036854775808, 9223372036854775807] }) }"
+ );
+}
+
+#[test]
+#[should_panic]
+fn assert_on_too_small_array_buf() {
+ let a = [0u8; 19];
+ flatbuffers::Array::<i32, 5>::new(&a);
+}
+
+#[test]
+#[should_panic]
+fn assert_on_too_big_array_buf() {
+ let a = [0u8; 21];
+ flatbuffers::Array::<i32, 5>::new(&a);
+}
+
+#[test]
+#[cfg(target_endian = "little")]
+fn verify_struct_array_alignment() {
+ let mut b = flatbuffers::FlatBufferBuilder::new();
+ create_serialized_example_with_generated_code(&mut b);
+ let buf = b.finished_data();
+ let array_table = root_as_array_table(buf).unwrap();
+ let array_struct = array_table.a().unwrap();
+ let struct_start_ptr = array_struct.0.as_ptr() as usize;
+ let b_start_ptr = array_struct.b().as_ptr() as usize;
+ let d_start_ptr = array_struct.d().as_ptr() as usize;
+ // The T type of b
+ let b_aln = ::std::mem::align_of::<i32>();
+ assert_eq!((b_start_ptr - struct_start_ptr) % b_aln, 0);
+ assert_eq!((d_start_ptr - b_start_ptr) % b_aln, 0);
+ assert_eq!((d_start_ptr - struct_start_ptr) % 8, 0);
+}
+
+#[derive(Clone, Debug)]
+struct FakeArray<T, const N: usize>([T; N]);
+
+impl<T: Arbitrary + Debug + PartialEq, const N: usize> Arbitrary for FakeArray<T, N> {
+ fn arbitrary<G: Gen>(g: &mut G) -> FakeArray<T, N> {
+ let x: [T; N] = array_init(|_| {
+ loop {
+ let generated_scalar = T::arbitrary(g);
+ // Verify that generated scalar is not Nan, which is not equals to itself,
+ // therefore we can't use it to validate input == output
+ if generated_scalar == generated_scalar { return generated_scalar }
+ }
+ });
+ FakeArray{0: x}
+ }
+}
+
+#[cfg(test)]
+mod array_fuzz {
+ #[cfg(not(miri))] // slow.
+ extern crate quickcheck;
+ extern crate flatbuffers;
+ use self::flatbuffers::{Follow, Push};
+ use super::*;
+
+ const MAX_TESTS: u64 = 20;
+ const ARRAY_SIZE: usize = 29;
+
+ // This uses a macro because lifetimes for the trait-bounded function get too
+ // complicated.
+ macro_rules! impl_prop {
+ ($test_name:ident, $fn_name:ident, $ty:ident) => (
+ fn $fn_name(xs: FakeArray<$ty, ARRAY_SIZE>) {
+ let mut test_buf = [0 as u8; 1024];
+ flatbuffers::emplace_scalar_array(&mut test_buf, 0, &xs.0);
+ let arr: flatbuffers::Array<$ty, ARRAY_SIZE> = flatbuffers::Array::follow(&test_buf, 0);
+ let got: [$ty; ARRAY_SIZE] = arr.into();
+ assert_eq!(got, xs.0);
+ }
+ #[test]
+ fn $test_name() {
+ quickcheck::QuickCheck::new().max_tests(MAX_TESTS).quickcheck($fn_name as fn(FakeArray<$ty, ARRAY_SIZE>));
+ }
+ )
+ }
+
+ impl_prop!(test_bool, prop_bool, bool);
+ impl_prop!(test_u8, prop_u8, u8);
+ impl_prop!(test_i8, prop_i8, i8);
+ impl_prop!(test_u16, prop_u16, u16);
+ impl_prop!(test_u32, prop_u32, u32);
+ impl_prop!(test_u64, prop_u64, u64);
+ impl_prop!(test_i16, prop_i16, i16);
+ impl_prop!(test_i32, prop_i32, i32);
+ impl_prop!(test_i64, prop_i64, i64);
+ impl_prop!(test_f32, prop_f32, f32);
+ impl_prop!(test_f64, prop_f64, f64);
+
+ const NESTED_STRUCT_SIZE: usize = size_of::<NestedStruct>();
+
+ #[derive(Clone, Debug, PartialEq)]
+ struct NestedStructWrapper(NestedStruct);
+
+ impl Arbitrary for NestedStructWrapper {
+ fn arbitrary<G: Gen>(g: &mut G) -> NestedStructWrapper {
+ let mut x = NestedStruct::default();
+ x.0 = FakeArray::<u8, NESTED_STRUCT_SIZE>::arbitrary(g).0;
+ NestedStructWrapper{0: x}
+ }
+ }
+
+ fn prop_struct(xs: FakeArray<NestedStructWrapper, ARRAY_SIZE>) {
+ let mut test_buf = [0 as u8; 1024];
+ let native_struct_array: [&NestedStruct; ARRAY_SIZE] = array_init::from_iter(xs.0.iter().map(|x| &x.0)).unwrap();
+ for i in 0..ARRAY_SIZE {
+ let offset = i * NESTED_STRUCT_SIZE;
+ native_struct_array[i].push(&mut test_buf[offset..offset + NESTED_STRUCT_SIZE], &[]);
+ }
+ let arr: flatbuffers::Array<NestedStruct, ARRAY_SIZE> = flatbuffers::Array::follow(&test_buf, 0);
+ let got: [&NestedStruct; ARRAY_SIZE] = arr.into();
+ assert_eq!(got, native_struct_array);
+ }
+
+ #[test]
+ #[cfg(not(miri))] // slow.
+ fn test_struct() {
+ quickcheck::QuickCheck::new().max_tests(MAX_TESTS).quickcheck(prop_struct as fn(FakeArray<NestedStructWrapper, ARRAY_SIZE>));
+ }
+}
diff --git a/tests/rust_usage_test/tests/flexbuffers_tests/binary_format.rs b/tests/rust_usage_test/tests/flexbuffers_tests/binary_format.rs
index ce69511..910fc78 100644
--- a/tests/rust_usage_test/tests/flexbuffers_tests/binary_format.rs
+++ b/tests/rust_usage_test/tests/flexbuffers_tests/binary_format.rs
@@ -108,6 +108,7 @@
);
}
+#[cfg(not(miri))] // slow.
quickcheck! {
fn qc_f32(x: f32) -> bool {
let fxb = singleton(x);
@@ -310,7 +311,7 @@
1, // Root bytes
]
);
- let r = Reader::get_root(&buf).unwrap();
+ let r = Reader::get_root(buf.as_ref()).unwrap();
assert_eq!(r.get_str(), Ok("snowman ☃︎"));
}
#[test]
diff --git a/tests/rust_usage_test/tests/flexbuffers_tests/interop.rs b/tests/rust_usage_test/tests/flexbuffers_tests/interop.rs
index 54ae1fd..705948f 100644
--- a/tests/rust_usage_test/tests/flexbuffers_tests/interop.rs
+++ b/tests/rust_usage_test/tests/flexbuffers_tests/interop.rs
@@ -18,14 +18,14 @@
fn read_golden_flexbuffer() {
let s =
std::fs::read("../gold_flexbuffer_example.bin").expect("Unable to read golden flexbuffer.");
- let r = Reader::get_root(&s).unwrap();
+ let r = Reader::get_root(s.as_ref()).unwrap();
let m = r.as_map();
let vec = m.idx("vec").as_vector();
assert_eq!(vec.idx(0).as_i8(), -100);
assert_eq!(vec.idx(1).as_str(), "Fred");
assert_eq!(vec.idx(2).as_f32(), 4.0);
- assert_eq!(vec.idx(3).as_blob(), Blob(&[77]));
+ assert_eq!(vec.idx(3).as_blob(), Blob([77].as_ref()));
assert_eq!(vec.idx(4).flexbuffer_type(), FlexBufferType::Bool);
assert_eq!(vec.idx(4).as_bool(), false);
assert_eq!(vec.idx(5).as_f64(), 4.0);
diff --git a/tests/rust_usage_test/tests/flexbuffers_tests/mod.rs b/tests/rust_usage_test/tests/flexbuffers_tests/mod.rs
index 2fccdb3..621f81b 100644
--- a/tests/rust_usage_test/tests/flexbuffers_tests/mod.rs
+++ b/tests/rust_usage_test/tests/flexbuffers_tests/mod.rs
@@ -15,5 +15,6 @@
mod binary_format;
mod interop;
mod other_api;
+#[cfg(not(miri))] // slow.
mod qc_serious;
mod rwyw;
diff --git a/tests/rust_usage_test/tests/flexbuffers_tests/other_api.rs b/tests/rust_usage_test/tests/flexbuffers_tests/other_api.rs
index 430cae5..d1c0873 100644
--- a/tests/rust_usage_test/tests/flexbuffers_tests/other_api.rs
+++ b/tests/rust_usage_test/tests/flexbuffers_tests/other_api.rs
@@ -13,12 +13,14 @@
// limitations under the License.
use flexbuffers::*;
+#[cfg(not(miri))] // slow.
use quickcheck::QuickCheck;
#[test]
+#[cfg(not(miri))] // slow.
fn qc_reader_no_crash() {
fn no_crash(xs: Vec<u8>) -> bool {
- let r = Reader::get_root(&xs);
+ let r = Reader::get_root(xs.as_ref());
r.is_err() || r.is_ok()
}
QuickCheck::new()
@@ -131,7 +133,7 @@
}
#[test]
fn null_reader() {
- let n = Reader::default();
+ let n = Reader::<&[u8]>::default();
assert_eq!(n.as_i8(), 0);
assert_eq!(n.as_i16(), 0);
assert_eq!(n.as_i32(), 0);
@@ -157,7 +159,7 @@
(FlexBufferType::Vector as u8) << 2 | BitWidth::W8 as u8,
1,
];
- assert!(Reader::get_root(s).is_err());
+ assert!(Reader::get_root(s.as_ref()).is_err());
}
#[test]
fn get_root_deref_u64() {
@@ -168,7 +170,24 @@
1,
];
// The risk of crashing is reading 8 bytes from index 0.
- assert_eq!(Reader::get_root(s).unwrap().as_u64(), 0);
+ assert_eq!(Reader::get_root(s.as_ref()).unwrap().as_u64(), 0);
+}
+
+/// Verifies that the clone operation is shallow / zero copy.
+#[test]
+fn clone_is_shallow() {
+ let mut fxb = Builder::default();
+ let mut m = fxb.start_map();
+ m.push("a", &[-1i8, -2, -3, -4]);
+ m.push("b", 250i64);
+ m.push("c", 5000u16);
+ m.end_map();
+
+ let r = Reader::get_root(fxb.view()).unwrap();
+
+ let r2 = r.clone();
+
+ assert_eq!(r.buffer().as_ptr(), r2.buffer().as_ptr());
}
#[test]
diff --git a/tests/rust_usage_test/tests/flexbuffers_tests/qc_serious.rs b/tests/rust_usage_test/tests/flexbuffers_tests/qc_serious.rs
index abd1ced..1bed3c2 100644
--- a/tests/rust_usage_test/tests/flexbuffers_tests/qc_serious.rs
+++ b/tests/rust_usage_test/tests/flexbuffers_tests/qc_serious.rs
@@ -1,7 +1,6 @@
use super::rwyw::NonNullString;
use flexbuffers::*;
use quickcheck::{Arbitrary, Gen};
-use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
@@ -134,12 +133,13 @@
}
quickcheck! {
- fn qc_serious(x: Struct) -> bool {
- let mut s = FlexbufferSerializer::new();
- x.serialize(&mut s).unwrap();
- let r = Reader::get_root(s.view()).unwrap();
- println!("{}", r);
- let x2 = Struct::deserialize(r).unwrap();
- x == x2
+ fn qc_serious(original: Struct) -> bool {
+ let struct_buf = flexbuffers::to_vec(&original).unwrap();
+ let root = Reader::get_root(&*struct_buf).unwrap();
+ let reader_buf = flexbuffers::to_vec(&root).unwrap();
+ let deserialized: Struct = flexbuffers::from_slice(&struct_buf).unwrap();
+ let reserialized: Struct = flexbuffers::from_slice(&reader_buf).unwrap();
+
+ original == deserialized && original == reserialized
}
}
diff --git a/tests/rust_usage_test/tests/flexbuffers_tests/rwyw.rs b/tests/rust_usage_test/tests/flexbuffers_tests/rwyw.rs
index 7ae7974..8c27e6b 100644
--- a/tests/rust_usage_test/tests/flexbuffers_tests/rwyw.rs
+++ b/tests/rust_usage_test/tests/flexbuffers_tests/rwyw.rs
@@ -14,6 +14,7 @@
// Read what you wrote.
use flexbuffers::*;
+#[cfg(not(miri))] // slow.
use quickcheck;
use serde::{Deserialize, Serialize};
@@ -33,6 +34,7 @@
}
}
+#[cfg(not(miri))] // slow.
quickcheck! {
fn qc_vec_bool(xs: Vec<bool>) -> bool {
let mut builder = Builder::default();
@@ -41,7 +43,7 @@
v.push(x);
}
v.end_vector();
- let r = Reader::get_root(&builder.view()).unwrap().as_vector();
+ let r = Reader::get_root(builder.view()).unwrap().as_vector();
xs.iter().enumerate().all(|(i, &x)| r.index(i).unwrap().get_bool().unwrap() == x)
}
fn qc_vec_uint(xs: Vec<u64>) -> bool {
@@ -51,7 +53,7 @@
v.push(x);
}
v.end_vector();
- let r = Reader::get_root(&builder.view()).unwrap().as_vector();
+ let r = Reader::get_root(builder.view()).unwrap().as_vector();
xs.iter().enumerate().all(|(i, &x)| r.idx(i).as_u64() == x)
}
fn qc_vec_int(xs: Vec<i64>) -> bool {
@@ -61,7 +63,7 @@
v.push(x);
}
v.end_vector();
- let r = Reader::get_root(&builder.view()).unwrap().as_vector();
+ let r = Reader::get_root(builder.view()).unwrap().as_vector();
xs.iter().enumerate().all(|(i, &x)| r.idx(i).as_i64() == x)
}
fn qc_vec_float(xs: Vec<f64>) -> bool {
@@ -71,7 +73,7 @@
v.push(x);
}
v.end_vector();
- let r = Reader::get_root(&builder.view()).unwrap().as_vector();
+ let r = Reader::get_root(builder.view()).unwrap().as_vector();
xs.iter().enumerate().all(|(i, &x)| (r.idx(i).as_f64() - x).abs() < std::f64::EPSILON)
}
fn qc_vec_string(xs: Vec<String>) -> bool {
@@ -81,7 +83,7 @@
v.push(x as &str);
}
v.end_vector();
- let r = Reader::get_root(&builder.view()).unwrap().as_vector();
+ let r = Reader::get_root(builder.view()).unwrap().as_vector();
xs.iter().enumerate().all(|(i, x)| (r.idx(i).as_str() == x))
}
fn qc_map_int(xs: std::collections::BTreeMap<NonNullString, i64>) -> bool {
@@ -91,7 +93,7 @@
m.push(&k.0, v);
}
m.end_map();
- let r = Reader::get_root(&builder.view()).unwrap().as_map();
+ let r = Reader::get_root(builder.view()).unwrap().as_map();
xs.iter().enumerate().all(|(i, (k, &v))| {
r.idx(i).as_i64() == v && r.idx(k.0.as_str()).as_i64() == v
})
@@ -103,7 +105,7 @@
m.push(&k.0, v as &str);
}
m.end_map();
- let r = Reader::get_root(&builder.view()).unwrap().as_map();
+ let r = Reader::get_root(builder.view()).unwrap().as_map();
xs.iter().enumerate().all(|(i, (k, v))| {
r.idx(i).as_str() == v && r.idx(k.0.as_str()).as_str() == v
})
@@ -112,10 +114,10 @@
let mut builder = Builder::default();
let mut v = builder.start_vector();
for x in &xs {
- v.push(Blob(&x));
+ v.push(Blob(x.as_ref()));
}
v.end_vector();
- let r = Reader::get_root(&builder.view()).unwrap().as_vector();
+ let r = Reader::get_root(builder.view()).unwrap().as_vector();
xs.iter().enumerate().all(
|(i, x)| r.idx(i).get_blob().unwrap().0.iter().eq(x.iter())
)
@@ -207,7 +209,7 @@
v.push("barrr");
v.push("bazzzzzz");
v.end_vector();
- let r = Reader::get_root(&builder.view()).unwrap().as_vector();
+ let r = Reader::get_root(builder.view()).unwrap().as_vector();
assert_eq!(r.idx(0).as_str(), "foo");
assert_eq!(r.idx(1).as_str(), "barrr");
assert_eq!(r.idx(2).as_str(), "bazzzzzz");
@@ -216,7 +218,7 @@
#[test]
fn store_13() {
let finished = singleton::<i32>(13);
- let r = Reader::get_root(&finished).unwrap();
+ let r = Reader::get_root(finished.as_ref()).unwrap();
assert_eq!(r.as_i32(), 13);
}
#[test]
@@ -231,7 +233,7 @@
let buf2 = singleton(&[2u8, 3, 5]);
assert_eq!(buf1, buf2.as_slice());
- let r = Reader::get_root(&buf1).unwrap().as_vector();
+ let r = Reader::get_root(buf1).unwrap().as_vector();
assert_eq!(r.idx(0).get_u64(), Ok(2));
assert_eq!(r.idx(1).get_u64(), Ok(3));
assert_eq!(r.idx(2).get_u64(), Ok(5));
@@ -246,13 +248,14 @@
v.push(5u8);
v.push(7u8);
v.end_vector();
- let r = Reader::get_root(&fxb.view()).unwrap();
+ let r = Reader::get_root(fxb.view()).unwrap();
let v = r.as_vector();
assert_eq!(v.idx(0).get_u64(), Ok(2));
assert_eq!(v.idx(1).get_u64(), Ok(3));
assert_eq!(v.idx(2).get_u64(), Ok(5));
assert_eq!(v.idx(3).get_u64(), Ok(7));
assert!(v.index(4).is_err());
+ #[allow(deprecated)]
#[cfg(target_endian = "little")]
{
assert_eq!(r.get_slice::<u8>().unwrap(), [2, 3, 5, 7]);
@@ -262,13 +265,13 @@
fn store_and_read_blob() {
let mut fxb = Builder::default();
let mut v = fxb.start_vector();
- v.push(Blob(&[1, 2, 3, 4]));
- v.push(Blob(&[5, 6, 7]));
+ v.push(Blob([1, 2, 3, 4].as_ref()));
+ v.push(Blob([5, 6, 7].as_ref()));
v.end_vector();
- let r = Reader::get_root(&fxb.view()).unwrap().as_vector();
- assert_eq!(r.idx(0).get_blob(), Ok(Blob(&[1, 2, 3, 4])));
- assert_eq!(r.idx(1).get_blob(), Ok(Blob(&[5, 6, 7])));
+ let r = Reader::get_root(fxb.view()).unwrap().as_vector();
+ assert_eq!(r.idx(0).get_blob(), Ok(Blob([1, 2, 3, 4].as_ref())));
+ assert_eq!(r.idx(1).get_blob(), Ok(Blob([5, 6, 7].as_ref())));
}
#[test]
fn map_64bit() {
@@ -278,7 +281,7 @@
m.push("b", u64::max_value() - 3);
m.end_map();
- let r = Reader::get_root(&fxb.view()).unwrap().as_map();
+ let r = Reader::get_root(fxb.view()).unwrap().as_map();
assert_eq!(r.idx("a").as_u16(), 257);
assert_eq!(r.idx("b").as_u64(), u64::max_value() - 3);
}
@@ -339,7 +342,7 @@
#[test]
fn store_u64() {
let finished = singleton(u64::max_value() - 10);
- let r = Reader::get_root(&finished).unwrap();
+ let r = Reader::get_root(finished.as_ref()).unwrap();
assert_eq!(r.get_u64(), Ok(u64::max_value() - 10));
}
#[test]
@@ -363,6 +366,8 @@
c: Vec<u32>,
d: String,
}
+
+#[cfg(not(miri))] // slow.
quickcheck! {
fn serde_foo(a: i8,
b: f64,
@@ -395,7 +400,7 @@
b: u16,
c: u32,
d: u64,
- };
+ }
#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct MyUnitStruct(Vec<String>);
@@ -440,7 +445,7 @@
Foo(vec![5, 6, 7, 8]).serialize(&mut s).unwrap();
let reader = Reader::get_root(s.view()).unwrap();
assert_eq!(reader.flexbuffer_type(), FlexBufferType::Blob);
- assert_eq!(reader.as_blob(), Blob(&[5, 6, 7, 8]));
+ assert_eq!(reader.as_blob(), Blob([5, 6, 7, 8].as_ref()));
}
#[test]
fn iter() {
@@ -462,7 +467,7 @@
#[derive(Deserialize)]
struct Foo(u8);
let data = [13, 4, 1];
- let r = Reader::get_root(&data).unwrap();
+ let r = Reader::get_root(data.as_ref()).unwrap();
let foo = Foo::deserialize(r).unwrap();
assert_eq!(foo.0, 13);
}
@@ -471,7 +476,7 @@
#[derive(Deserialize)]
struct Foo<'a>(&'a str);
let data = [5, b'h', b'e', b'l', b'l', b'o', b'\0', 6, 5 << 2, 1];
- let r = Reader::get_root(&data).unwrap();
+ let r = Reader::get_root(data.as_ref()).unwrap();
let foo = Foo::deserialize(r).unwrap();
assert_eq!(foo.0, "hello");
}
@@ -486,7 +491,7 @@
23 << 2 | 1, // (VectorUInt4, W16 - referring to data).
1, // Root width W8 - referring to vector.
];
- let r = Reader::get_root(&data).unwrap();
+ let r = Reader::get_root(data.as_ref()).unwrap();
let foo = Foo::deserialize(r).unwrap();
assert_eq!(foo.0, 4);
assert_eq!(foo.1, 16);
@@ -499,7 +504,7 @@
23 << 2, // Root type: VectorUInt4, W8.
1, // Root width: W8.
];
- let r = Reader::get_root(&data).unwrap();
+ let r = Reader::get_root(data.as_ref()).unwrap();
let foo = Foo::deserialize(r).unwrap();
assert_eq!(foo.0, 1);
assert_eq!(foo.1, 2);
diff --git a/tests/rust_usage_test/tests/integration_test.rs b/tests/rust_usage_test/tests/integration_test.rs
index 5957e2c..9a4c8b3 100644
--- a/tests/rust_usage_test/tests/integration_test.rs
+++ b/tests/rust_usage_test/tests/integration_test.rs
@@ -15,7 +15,12 @@
* limitations under the License.
*/
+#[cfg(feature = "no_std")]
+#[global_allocator]
+static ALLOCATOR: libc_alloc::LibcAlloc = libc_alloc::LibcAlloc;
+
#[macro_use]
+#[cfg(not(miri))] // slow.
extern crate quickcheck;
extern crate flatbuffers;
extern crate flexbuffers;
@@ -23,26 +28,44 @@
extern crate serde;
#[macro_use]
extern crate serde_derive;
+#[cfg(not(miri))] // slow.
#[macro_use]
extern crate quickcheck_derive;
mod flexbuffers_tests;
+mod more_defaults_test;
mod optional_scalars_test;
-#[path = "../../include_test/include_test1_generated.rs"]
+#[allow(dead_code, unused_imports)]
+#[path = "../../include_test1/mod.rs"]
pub mod include_test1_generated;
-#[path = "../../include_test/sub/include_test2_generated.rs"]
+#[allow(dead_code, unused_imports)]
+#[path = "../../include_test2/mod.rs"]
pub mod include_test2_generated;
-#[path = "../../monster_test_generated.rs"]
+#[allow(dead_code, unused_imports)]
+#[path = "../../namespace_test/mod.rs"]
+pub mod namespace_test_generated;
+
+#[allow(dead_code, unused_imports)]
+#[path = "../../monster_test/mod.rs"]
mod monster_test_generated;
pub use monster_test_generated::my_game;
#[allow(dead_code, unused_imports)]
-#[path = "../../optional_scalars_generated.rs"]
+#[path = "../../optional_scalars/mod.rs"]
mod optional_scalars_generated;
+#[allow(dead_code, unused_imports)]
+#[path = "../../arrays_test/mod.rs"]
+mod arrays_test_generated;
+
+// We use incorrect casing to test keywords.
+#[allow(dead_code, unused_imports, non_camel_case_types, non_snake_case)]
+#[path = "../../keyword_test/mod.rs"]
+mod keyword_test_generated;
+
#[rustfmt::skip] // TODO: Use standard rust formatting and remove dead code.
#[allow(dead_code)]
mod flatbuffers_tests {
@@ -102,6 +125,77 @@
assert!(check_is_some!(none).is_err());
}
+#[test]
+fn object_api_defaults() {
+ use my_game::example::*;
+ assert_eq!(
+ Vec3T::default(), Vec3T {
+ x: 0.0,
+ y: 0.0,
+ z: 0.0,
+ test1: 0.0,
+ test2: Color::empty(),
+ test3: TestT {
+ a: 0,
+ b: 0
+ }
+ });
+ assert_eq!(
+ MonsterT::default(),
+ MonsterT {
+ pos: None,
+ hp: 100,
+ mana: 150,
+ name: String::new(), // required string => default is empty string.
+ color: Color::Blue,
+ inventory: None,
+ testarrayoftables: None,
+ testarrayofstring: None,
+ testarrayofstring2: None,
+ testarrayofbools: None,
+ testarrayofsortedstruct: None,
+ enemy: None,
+ test: AnyT::NONE,
+ test4: None,
+ test5: None,
+ testnestedflatbuffer: None,
+ testempty: None,
+ testbool: false,
+ testhashs32_fnv1: 0,
+ testhashu32_fnv1: 0,
+ testhashs64_fnv1: 0,
+ testhashu64_fnv1: 0,
+ testhashs32_fnv1a: 0,
+ testhashu32_fnv1a: 0,
+ testhashs64_fnv1a: 0,
+ testhashu64_fnv1a: 0,
+ testf: 3.14159,
+ testf2: 3.0,
+ testf3: 0.0,
+ flex: None,
+ vector_of_longs: None,
+ vector_of_doubles: None,
+ parent_namespace_test: None,
+ vector_of_referrables: None,
+ single_weak_reference: 0,
+ vector_of_weak_references: None,
+ vector_of_strong_referrables: None,
+ co_owning_reference: 0,
+ vector_of_co_owning_references: None,
+ non_owning_reference: 0,
+ vector_of_non_owning_references: None,
+ any_unique: AnyUniqueAliasesT::NONE,
+ any_ambiguous: AnyAmbiguousAliasesT::NONE,
+ vector_of_enums: None,
+ signed_enum: Race::None,
+ testrequirednestedflatbuffer: None, // despite the name, it is not required.
+ scalar_key_sorted_tables: None,
+ native_inline: None,
+ long_enum_non_enum_default: Default::default(),
+ long_enum_normal_default: LongEnum::LongOne,
+ }
+ );
+}
fn create_serialized_example_with_generated_code(builder: &mut flatbuffers::FlatBufferBuilder) {
let mon = {
@@ -177,9 +271,9 @@
}
let m = if size_prefixed {
- my_game::example::get_size_prefixed_root_as_monster(bytes)
+ my_game::example::size_prefixed_root_as_monster(bytes).unwrap()
} else {
- my_game::example::get_root_as_monster(bytes)
+ my_game::example::root_as_monster(bytes).unwrap()
};
check_eq!(m.hp(), 80)?;
@@ -225,16 +319,60 @@
Ok(())
}
+#[test]
+fn test_object_api_reads_correctly() -> Result<(), &'static str>{
+ let mut fbb = flatbuffers::FlatBufferBuilder::new();
+ create_serialized_example_with_library_code(&mut fbb);
+
+ let m = my_game::example::root_as_monster(fbb.finished_data()).unwrap().unpack();
+
+ check_eq!(m.hp, 80)?;
+ check_eq!(m.mana, 150)?;
+ check_eq!(m.name, "MyMonster")?;
+
+ let pos = m.pos.as_ref().unwrap();
+ check_eq!(pos.x, 1.0f32)?;
+ check_eq!(pos.y, 2.0f32)?;
+ check_eq!(pos.z, 3.0f32)?;
+ check_eq!(pos.test1, 3.0f64)?;
+ check_eq!(pos.test2, my_game::example::Color::Green)?;
+
+ let pos_test3 = &pos.test3;
+ check_eq!(pos_test3.a, 5i16)?;
+ check_eq!(pos_test3.b, 6i8)?;
+
+ let monster2 = m.test.as_monster().unwrap();
+ check_eq!(monster2.name, "Fred")?;
+
+ let inv = m.inventory.as_ref().unwrap();
+ check_eq!(inv.len(), 5)?;
+ check_eq!(inv.iter().sum::<u8>(), 10u8)?;
+ check_eq!(inv.iter().rev().sum::<u8>(), 10u8)?;
+
+ let test4 = m.test4.as_ref().unwrap();
+ check_eq!(test4.len(), 2)?;
+ check_eq!(test4[0].a as i32 + test4[0].b as i32 +
+ test4[1].a as i32 + test4[1].b as i32, 100)?;
+
+ let testarrayofstring = m.testarrayofstring.as_ref().unwrap();
+ check_eq!(testarrayofstring.len(), 2)?;
+ check_eq!(testarrayofstring[0], "test1")?;
+ check_eq!(testarrayofstring[1], "test2")?;
+ Ok(())
+}
+
+
+
// Disabled due to Windows CI limitations.
// #[test]
// fn builder_initializes_with_maximum_buffer_size() {
-// flatbuffers::FlatBufferBuilder::new_with_capacity(flatbuffers::FLATBUFFERS_MAX_BUFFER_SIZE);
+// flatbuffers::FlatBufferBuilder::with_capacity(flatbuffers::FLATBUFFERS_MAX_BUFFER_SIZE);
// }
#[should_panic]
#[test]
fn builder_abort_with_greater_than_maximum_buffer_size() {
- flatbuffers::FlatBufferBuilder::new_with_capacity(flatbuffers::FLATBUFFERS_MAX_BUFFER_SIZE+1);
+ flatbuffers::FlatBufferBuilder::with_capacity(flatbuffers::FLATBUFFERS_MAX_BUFFER_SIZE+1);
}
#[test]
@@ -245,6 +383,109 @@
serialized_example_is_accessible_and_correct(&backing_buf[head..], true, false).unwrap();
}
+#[test]
+#[cfg(not(miri))] // slow.
+fn verifier_one_byte_errors_do_not_crash() {
+ let mut b = flatbuffers::FlatBufferBuilder::new();
+ create_serialized_example_with_library_code(&mut b);
+ let mut badbuf = b.finished_data().to_vec();
+ // If the verifier says a buffer is okay then using it won't cause a crash.
+ // We use write_fmt since Debug visits all the fields - but there's no need to store anything.
+ struct ForgetfulWriter;
+ use std::fmt::Write;
+ impl Write for ForgetfulWriter {
+ fn write_str(&mut self, _: &str) -> Result<(), std::fmt::Error> {
+ Ok(())
+ }
+ }
+ let mut w = ForgetfulWriter;
+ for d in 1..=255u8 {
+ for i in 0..badbuf.len() {
+ let orig = badbuf[i];
+ badbuf[i] = badbuf[i].wrapping_add(d);
+ if let Ok(m) = flatbuffers::root::<my_game::example::Monster>(&badbuf) {
+ w.write_fmt(format_args!("{:?}", m)).unwrap()
+ }
+ badbuf[i] = orig;
+ }
+ }
+}
+#[test]
+#[cfg(not(miri))] // slow.
+fn verifier_too_many_tables() {
+ use my_game::example::*;
+ let b = &mut flatbuffers::FlatBufferBuilder::new();
+ let r = Referrable::create(b, &ReferrableArgs { id: 42 });
+ let rs = b.create_vector(&vec![r; 500]);
+ let name = Some(b.create_string("foo"));
+ let m = Monster::create(b, &MonsterArgs {
+ vector_of_referrables: Some(rs),
+ name, // required field.
+ ..Default::default()
+ });
+ b.finish(m, None);
+
+ let data = b.finished_data();
+ let mut opts = flatbuffers::VerifierOptions::default();
+
+ opts.max_tables = 500;
+ let res = flatbuffers::root_with_opts::<Monster>(&opts, data);
+ assert_eq!(res.unwrap_err(), flatbuffers::InvalidFlatbuffer::TooManyTables);
+
+ opts.max_tables += 2;
+ assert!(flatbuffers::root_with_opts::<Monster>(&opts, data).is_ok());
+}
+#[test]
+#[cfg(not(miri))] // slow.
+fn verifier_apparent_size_too_large() {
+ use my_game::example::*;
+ let b = &mut flatbuffers::FlatBufferBuilder::new();
+ let name = Some(b.create_string("foo"));
+ // String amplification attack.
+ let s = b.create_string(&(std::iter::repeat("X").take(1000).collect::<String>()));
+ let testarrayofstring = Some(b.create_vector(&vec![s; 1000]));
+ let m = Monster::create(b, &MonsterArgs {
+ testarrayofstring,
+ name, // required field.
+ ..Default::default()
+ });
+ b.finish(m, None);
+ let data = b.finished_data();
+ assert!(data.len() < 5100); // est 4000 for the vector + 1000 for the string + 100 overhead.
+ let mut opts = flatbuffers::VerifierOptions::default();
+ opts.max_apparent_size = 1_000_000;
+
+ let res = flatbuffers::root_with_opts::<Monster>(&opts, data);
+ assert_eq!(res.unwrap_err(), flatbuffers::InvalidFlatbuffer::ApparentSizeTooLarge);
+
+ opts.max_apparent_size += 20_000;
+ assert!(flatbuffers::root_with_opts::<Monster>(&opts, data).is_ok());
+}
+#[test]
+fn verifier_in_too_deep() {
+ use my_game::example::*;
+ let b = &mut flatbuffers::FlatBufferBuilder::new();
+ let name = Some(b.create_string("foo"));
+ let mut prev_monster = None;
+ for _ in 0..11 {
+ prev_monster = Some(Monster::create(b, &MonsterArgs {
+ enemy: prev_monster,
+ name, // required field.
+ ..Default::default()
+ }));
+ };
+ b.finish(prev_monster.unwrap(), None);
+ let mut opts = flatbuffers::VerifierOptions::default();
+ opts.max_depth = 10;
+
+ let data = b.finished_data();
+ let res = flatbuffers::root_with_opts::<Monster>(&opts, data);
+ assert_eq!(res.unwrap_err(), flatbuffers::InvalidFlatbuffer::DepthLimitReached);
+
+ opts.max_depth += 1;
+ assert!(flatbuffers::root_with_opts::<Monster>(&opts, data).is_ok());
+}
+
#[cfg(test)]
mod generated_constants {
extern crate flatbuffers;
@@ -316,7 +557,7 @@
let slice: &[u8] = &buf;
let slice: &'static [u8] = unsafe { mem::transmute(slice) };
// make sure values retrieved from the 'static buffer are themselves 'static
- let monster: my_game::example::Monster<'static> = my_game::example::get_root_as_monster(slice);
+ let monster: my_game::example::Monster<'static> = my_game::example::root_as_monster(slice).unwrap();
// this line should compile:
let name: Option<&'static str> = monster._tab.get::<flatbuffers::ForwardsUOffset<&str>>(my_game::example::Monster::VT_NAME, None);
assert_eq!(name, Some("MyMonster"));
@@ -334,7 +575,7 @@
fn table_object_self_lifetime_in_closure() {
// This test is designed to ensure that lifetimes for temporary intermediate tables aren't inflated beyond where the need to be.
let buf = load_file("../monsterdata_test.mon").expect("missing monsterdata_test.mon");
- let monster = my_game::example::get_root_as_monster(&buf);
+ let monster = my_game::example::root_as_monster(&buf).unwrap();
let enemy: Option<my_game::example::Monster> = monster.enemy();
// This line won't compile if "self" is required to live for the lifetime of buf above as the borrow disappears at the end of the closure.
let enemy_of_my_enemy = enemy.map(|e| {
@@ -357,7 +598,7 @@
fn build_mon<'a, 'b>(builder: &'a mut flatbuffers::FlatBufferBuilder, args: &'b my_game::example::MonsterArgs) -> my_game::example::Monster<'a> {
let mon = my_game::example::Monster::create(builder, &args);
my_game::example::finish_monster_buffer(builder, mon);
- my_game::example::get_root_as_monster(builder.finished_data())
+ my_game::example::root_as_monster(builder.finished_data()).unwrap()
}
#[test]
@@ -437,7 +678,7 @@
my_game::example::finish_monster_buffer(b, outer);
}
- let mon = my_game::example::get_root_as_monster(b.finished_data());
+ let mon = my_game::example::root_as_monster(b.finished_data()).unwrap();
assert_eq!(mon.name(), "bar");
assert_eq!(mon.test_type(), my_game::example::Any::Monster);
assert_eq!(my_game::example::Monster::init_from_table(mon.test().unwrap()).name(),
@@ -473,7 +714,7 @@
my_game::example::finish_monster_buffer(b, outer);
}
- let mon = my_game::example::get_root_as_monster(b.finished_data());
+ let mon = my_game::example::root_as_monster(b.finished_data()).unwrap();
assert_eq!(mon.name(), "bar");
assert_eq!(mon.enemy().unwrap().name(), "foo");
}
@@ -503,7 +744,7 @@
my_game::example::finish_monster_buffer(b, outer);
}
- let mon = my_game::example::get_root_as_monster(b.finished_data());
+ let mon = my_game::example::root_as_monster(b.finished_data()).unwrap();
assert_eq!(mon.name(), "bar");
assert_eq!(mon.testempty().unwrap().id(), Some("foo"));
}
@@ -540,12 +781,12 @@
b1
};
- let m = my_game::example::get_root_as_monster(b1.finished_data());
+ let m = my_game::example::root_as_monster(b1.finished_data()).unwrap();
assert!(m.testnestedflatbuffer().is_some());
assert_eq!(m.testnestedflatbuffer().unwrap(), b0.finished_data());
- let m2_a = my_game::example::get_root_as_monster(m.testnestedflatbuffer().unwrap());
+ let m2_a = my_game::example::root_as_monster(m.testnestedflatbuffer().unwrap()).unwrap();
assert_eq!(m2_a.hp(), 123);
assert_eq!(m2_a.name(), "foobar");
@@ -751,11 +992,6 @@
}
#[test]
- fn enum_color_is_aligned_to_1() {
- assert_eq!(1, ::std::mem::align_of::<my_game::example::Color>());
- }
-
- #[test]
fn union_any_is_1_byte() {
assert_eq!(1, ::std::mem::size_of::<my_game::example::Any>());
}
@@ -764,28 +1000,16 @@
fn union_any_is_aligned_to_1() {
assert_eq!(1, ::std::mem::align_of::<my_game::example::Any>());
}
-
#[test]
fn struct_test_is_4_bytes() {
assert_eq!(4, ::std::mem::size_of::<my_game::example::Test>());
}
-
- #[test]
- fn struct_test_is_aligned_to_2() {
- assert_eq!(2, ::std::mem::align_of::<my_game::example::Test>());
- }
-
#[test]
fn struct_vec3_is_32_bytes() {
assert_eq!(32, ::std::mem::size_of::<my_game::example::Vec3>());
}
#[test]
- fn struct_vec3_is_aligned_to_8() {
- assert_eq!(8, ::std::mem::align_of::<my_game::example::Vec3>());
- }
-
- #[test]
fn struct_vec3_is_written_with_correct_alignment_in_table() {
let b = &mut flatbuffers::FlatBufferBuilder::new();
{
@@ -799,15 +1023,15 @@
my_game::example::finish_monster_buffer(b, mon);
}
let buf = b.finished_data();
- let mon = my_game::example::get_root_as_monster(buf);
+ let mon = my_game::example::root_as_monster(buf).unwrap();
let vec3 = mon.pos().unwrap();
let start_ptr = buf.as_ptr() as usize;
let vec3_ptr = vec3 as *const my_game::example::Vec3 as usize;
assert!(vec3_ptr > start_ptr);
- let aln = ::std::mem::align_of::<my_game::example::Vec3>();
- assert_eq!((vec3_ptr - start_ptr) % aln, 0);
+ // Vec3 is aligned to 8 wrt the flatbuffer.
+ assert_eq!((vec3_ptr - start_ptr) % 8, 0);
}
#[test]
@@ -816,11 +1040,6 @@
}
#[test]
- fn struct_ability_is_aligned_to_4() {
- assert_eq!(4, ::std::mem::align_of::<my_game::example::Ability>());
- }
-
- #[test]
fn struct_ability_is_written_with_correct_alignment_in_table_vector() {
let b = &mut flatbuffers::FlatBufferBuilder::new();
{
@@ -835,7 +1054,7 @@
my_game::example::finish_monster_buffer(b, mon);
}
let buf = b.finished_data();
- let mon = my_game::example::get_root_as_monster(buf);
+ let mon = my_game::example::root_as_monster(buf).unwrap();
let abilities = mon.testarrayofsortedstruct().unwrap();
let start_ptr = buf.as_ptr() as usize;
@@ -848,14 +1067,15 @@
for a in abilities.iter().rev() {
let a_ptr = a as *const my_game::example::Ability as usize;
assert!(a_ptr > start_ptr);
- let aln = ::std::mem::align_of::<my_game::example::Ability>();
- assert_eq!((a_ptr - start_ptr) % aln, 0);
+ // Vec3 is aligned to 8 wrt the flatbuffer.
+ assert_eq!((a_ptr - start_ptr) % 8, 0);
}
}
}
#[cfg(test)]
mod roundtrip_byteswap {
+ #[cfg(not(miri))] // slow.
extern crate quickcheck;
extern crate flatbuffers;
@@ -903,6 +1123,41 @@
// fn fuzz_f64() { quickcheck::QuickCheck::new().max_tests(N).quickcheck(prop_f64 as fn(f64)); }
}
+#[cfg(not(miri))]
+quickcheck! {
+ fn struct_of_structs(
+ a_id: u32,
+ a_distance: u32,
+ b_a: i16,
+ b_b: i8,
+ c_id: u32,
+ c_distance: u32
+ ) -> bool {
+ use my_game::example::*;
+ let mut sos = StructOfStructs::default();
+ let mut a = Ability::default();
+ a.set_id(a_id);
+ a.set_distance(a_distance);
+ let mut b = Test::default();
+ b.set_a(b_a);
+ b.set_b(b_b);
+ let mut c = Ability::default();
+ c.set_id(c_id);
+ c.set_distance(c_distance);
+ sos.set_a(&a);
+ sos.set_b(&b);
+ sos.set_c(&c);
+
+ sos.a().id() == a_id &&
+ sos.a().distance() == a_distance &&
+ sos.b().a() == b_a &&
+ sos.b().b() == b_b &&
+ sos.c().id() == c_id &&
+ sos.c().distance() == c_distance
+ }
+}
+
+#[cfg(not(miri))] // slow.
#[cfg(test)]
mod roundtrip_vectors {
@@ -982,6 +1237,7 @@
#[cfg(test)]
mod create_vector_direct {
+ #[cfg(not(miri))] // slow.
extern crate quickcheck;
extern crate flatbuffers;
@@ -1029,6 +1285,7 @@
#[cfg(test)]
mod string_manual_build {
+ #[cfg(not(miri))] // slow.
extern crate quickcheck;
extern crate flatbuffers;
@@ -1066,6 +1323,7 @@
#[cfg(test)]
mod string_helper_build {
+ #[cfg(not(miri))] // slow.
extern crate quickcheck;
extern crate flatbuffers;
@@ -1096,9 +1354,11 @@
#[cfg(test)]
mod ubyte {
+ #[cfg(not(miri))] // slow.
extern crate quickcheck;
extern crate flatbuffers;
+ #[cfg(not(miri))] // slow.
#[test]
fn fuzz_manual_build() {
fn prop(vec: Vec<u8>) {
@@ -1142,7 +1402,7 @@
// Access it.
let buf = b.finished_data();
- let m = flatbuffers::get_size_prefixed_root::<my_game::example::Monster>(buf);
+ let m = flatbuffers::size_prefixed_root::<my_game::example::Monster>(buf).unwrap();
assert_eq!(m.mana(), 200);
assert_eq!(m.hp(), 300);
assert_eq!(m.name(), "bob");
@@ -1154,11 +1414,13 @@
use std::collections::HashMap;
extern crate flatbuffers;
+ #[cfg(not(miri))] // slow.
extern crate quickcheck;
use super::LCG;
#[test]
+ #[cfg(not(miri))] // slow.
fn table_of_mixed_scalars_fuzz() {
// Values we're testing against: chosen to ensure no bits get chopped
// off anywhere, and also be different from eachother.
@@ -1260,12 +1522,12 @@
assert!(values_generated > 0);
assert!(min_tests_per_choice > 0);
for i in 0..test_value_types_max as u64 {
- assert!(stats[&i] >= min_tests_per_choice,
- format!("inadequately-tested fuzz case: {}", i));
+ assert!(stats[&i] >= min_tests_per_choice, "inadequately-tested fuzz case: {}", i);
}
}
#[test]
+ #[cfg(not(miri))] // slow.
fn table_of_byte_strings_fuzz() {
fn prop(vec: Vec<Vec<u8>>) {
use flatbuffers::field_index_to_field_offset as fi2fo;
@@ -1302,6 +1564,7 @@
}
#[test]
+ #[cfg(not(miri))] // slow.
fn fuzz_table_of_strings() {
fn prop(vec: Vec<String>) {
use flatbuffers::field_index_to_field_offset as fi2fo;
@@ -1333,8 +1596,10 @@
quickcheck::QuickCheck::new().max_tests(n).quickcheck(prop as fn(Vec<String>));
}
+ #[cfg(not(miri))] // slow.
mod table_of_vectors_of_scalars {
extern crate flatbuffers;
+ #[cfg(not(miri))] // slow.
extern crate quickcheck;
const N: u64 = 20;
@@ -1415,17 +1680,21 @@
}
}
+#[cfg(not(miri))] // slow.
#[cfg(test)]
mod roundtrip_scalars {
extern crate flatbuffers;
+ #[cfg(not(miri))] // slow.
extern crate quickcheck;
const N: u64 = 1000;
fn prop<T: PartialEq + ::std::fmt::Debug + Copy + flatbuffers::EndianScalar>(x: T) {
let mut buf = vec![0u8; ::std::mem::size_of::<T>()];
- flatbuffers::emplace_scalar(&mut buf[..], x);
- let y = flatbuffers::read_scalar(&buf[..]);
+ let y = unsafe {
+ flatbuffers::emplace_scalar(&mut buf[..], x);
+ flatbuffers::read_scalar(&buf[..])
+ };
assert_eq!(x, y);
}
@@ -1458,8 +1727,10 @@
}
#[cfg(test)]
+#[cfg(not(miri))] // slow.
mod roundtrip_push_follow_scalars {
extern crate flatbuffers;
+ #[cfg(not(miri))] // slow.
extern crate quickcheck;
use flatbuffers::Push;
@@ -1538,7 +1809,7 @@
create_serialized_example_with_generated_code(b);
let buf = b.finished_data();
serialized_example_is_accessible_and_correct(&buf, true, false).unwrap();
- let m = super::my_game::example::get_root_as_monster(buf);
+ let m = super::my_game::example::root_as_monster(buf).unwrap();
assert_eq!(
format!("{:.5?}", &m),
"Monster { pos: Some(Vec3 { x: 1.00000, y: 2.00000, z: 3.00000, \
@@ -1562,8 +1833,10 @@
vector_of_non_owning_references: None, any_unique_type: NONE, \
any_unique: None, any_ambiguous_type: NONE, any_ambiguous: None, \
vector_of_enums: None, signed_enum: None, \
- testrequirednestedflatbuffer: None }, test4: Some([Test { \
- a: 10, b: 20 }, Test { a: 30, b: 40 }]), \
+ testrequirednestedflatbuffer: None, scalar_key_sorted_tables: None, \
+ native_inline: None, long_enum_non_enum_default: (empty), \
+ long_enum_normal_default: LongOne }, \
+ test4: Some([Test { a: 10, b: 20 }, Test { a: 30, b: 40 }]), \
testarrayofstring: Some([\"test1\", \"test2\"]), \
testarrayoftables: None, enemy: None, testnestedflatbuffer: None, \
testempty: None, testbool: false, testhashs32_fnv1: 0, \
@@ -1580,11 +1853,14 @@
vector_of_non_owning_references: None, any_unique_type: NONE, \
any_unique: None, any_ambiguous_type: NONE, any_ambiguous: None, \
vector_of_enums: None, signed_enum: None, \
- testrequirednestedflatbuffer: None }"
+ testrequirednestedflatbuffer: None, scalar_key_sorted_tables: None, \
+ native_inline: None, long_enum_non_enum_default: (empty), \
+ long_enum_normal_default: LongOne }"
);
}
#[test]
+ #[cfg(not(miri))] // slow.
fn generated_code_creates_correct_example_repeatedly_with_reset() {
let b = &mut flatbuffers::FlatBufferBuilder::new();
for _ in 0..100 {
@@ -1606,6 +1882,7 @@
}
#[test]
+ #[cfg(not(miri))] // slow.
fn library_code_creates_correct_example_repeatedly_with_reset() {
let b = &mut flatbuffers::FlatBufferBuilder::new();
for _ in 0..100 {
@@ -1728,7 +2005,7 @@
let builder = &mut flatbuffers::FlatBufferBuilder::new();
super::create_serialized_example_with_library_code(builder);
let buf = builder.finished_data();
- let a = my_game::example::get_root_as_monster(buf);
+ let a = my_game::example::root_as_monster(buf).unwrap();
// preconditions
assert_eq!(a.name(), "MyMonster");
@@ -1744,7 +2021,7 @@
let builder = &mut flatbuffers::FlatBufferBuilder::new();
super::create_serialized_example_with_library_code(builder);
let buf = builder.finished_data();
- let a = my_game::example::get_root_as_monster(buf);
+ let a = my_game::example::root_as_monster(buf).unwrap();
let b = a.test_as_monster().unwrap();
// preconditions
@@ -1761,23 +2038,17 @@
#[cfg(test)]
mod included_schema_generated_code {
- extern crate flatbuffers;
- //extern crate rust_usage_test;
+ #[test]
+ #[allow(unused_imports)]
+ fn namespace_test_mod_is_importable() {
+ use super::namespace_test_generated::{
+ namespace_a,
+ namespace_a::namespace_b,
+ namespace_c,
+ };
- // TODO(rw): make generated sub-namespace files importable
- //#[test]
- //fn namespace_test_mod_is_importable() {
- // use rust_usage_test::namespace_test;
- //}
- //#[test]
- //fn namespace_test1_mod_is_importable() {
- // use rust_usage_test::namespace_test::namespace_test1_generated;
- //}
- //#[test]
- //fn namespace_test2_mod_is_importable() {
- // use rust_usage_test::namespace_test::namespace_test2_generated;
- //}
+ }
}
#[cfg(test)]
@@ -1848,7 +2119,7 @@
// Define a test struct to use in a few tests. This replicates the work that the code generator
// would normally do when defining a FlatBuffer struct. For reference, compare the following
// `FooStruct` code with the code generated for the `Vec3` struct in
- // `../../monster_test_generated.rs`.
+ // `../../monster_test/mod.rs`.
use flatbuffers::EndianScalar;
#[derive(Copy, Clone, Debug, PartialEq)]
#[repr(C, packed)]
@@ -1931,14 +2202,6 @@
assert_eq!(off.self_follow(&vec[..], 4).safe_slice(), &[1, 2, 3][..]);
}
- #[cfg(target_endian = "little")]
- #[test]
- fn to_slice_of_u16() {
- let vec: Vec<u8> = vec![255, 255, 255, 255, 2, 0, 0, 0, 1, 2, 3, 4];
- let off: flatbuffers::FollowStart<&[u16]> = flatbuffers::FollowStart::new();
- assert_eq!(off.self_follow(&vec[..], 4), &vec![513, 1027][..]);
- }
-
#[test]
fn to_vector_of_u16() {
let vec: Vec<u8> = vec![255, 255, 255, 255, 2, 0, 0, 0, 1, 2, 3, 4];
@@ -2271,6 +2534,7 @@
]);
}
+ #[cfg(not(miri))] // slow.
#[test]
fn many_identical_tables_use_few_vtables() {
let mut b = flatbuffers::FlatBufferBuilder::new();
@@ -2347,7 +2611,7 @@
#[test]
fn layout_03b_11xbyte_vector_matches_builder_size() {
- let mut b = flatbuffers::FlatBufferBuilder::new_with_capacity(12);
+ let mut b = flatbuffers::FlatBufferBuilder::with_capacity(12);
b.start_vector::<u8>(8);
let mut gold = vec![0u8; 0];
@@ -2951,4 +3215,51 @@
f.read_to_end(&mut buf)?;
Ok(buf)
}
+
+#[test]
+fn test_shared_strings() {
+ let mut builder = flatbuffers::FlatBufferBuilder::new();
+ let offset1 = builder.create_shared_string("welcome to flatbuffers!!");
+ let offset2 = builder.create_shared_string("welcome");
+ let offset3 = builder.create_shared_string("welcome to flatbuffers!!");
+ assert_ne!(offset2.value(), offset3.value());
+ assert_eq!(offset1.value(), offset3.value());
+ builder.reset();
+ let offset4 = builder.create_shared_string("welcome");
+ let offset5 = builder.create_shared_string("welcome to flatbuffers!!");
+ assert_ne!(offset2.value(), offset4.value());
+ assert_ne!(offset5.value(), offset1.value());
+ builder.reset();
+
+ // Checks if the shared string function would always work with
+ // an object in between the writes
+ let name = builder.create_shared_string("foo");
+ let enemy = my_game::example::Monster::create(&mut builder, &my_game::example::MonsterArgs {
+ name: Some(name),
+ ..Default::default()
+ });
+ let secondary_name = builder.create_shared_string("foo");
+ assert_eq!(name.value(), secondary_name.value());
+
+ // Builds a new monster object and embeds enemy into it so we can verify
+ // that shared strings are working.
+ let args = my_game::example::MonsterArgs {
+ name: Some(secondary_name),
+ enemy: Some(enemy),
+ testarrayofstring: Some(builder.create_vector(&[name, secondary_name])),
+ ..Default::default()
+ };
+ // Building secondary monster
+ let main_monster = my_game::example::Monster::create(&mut builder, &args);
+ builder.finish(main_monster, None);
+ let monster = my_game::example::root_as_monster(builder.finished_data()).unwrap();
+
+ // Checks if the embedded object (Enemy) name is foo
+ assert_eq!(monster.enemy().unwrap().name(), "foo");
+ let string_vector = monster.testarrayofstring().unwrap();
+ // Check if the vector will have the same string
+ assert_eq!(string_vector.get(0), "foo");
+ assert_eq!(string_vector.get(1), "foo");
+}
+
}
diff --git a/tests/rust_usage_test/tests/more_defaults_test.rs b/tests/rust_usage_test/tests/more_defaults_test.rs
new file mode 100644
index 0000000..af664f2
--- /dev/null
+++ b/tests/rust_usage_test/tests/more_defaults_test.rs
@@ -0,0 +1,30 @@
+#[allow(dead_code, unused_imports)]
+#[path = "../../more_defaults/mod.rs"]
+mod more_defaults_generated;
+use self::more_defaults_generated::*;
+
+#[test]
+fn object_defaults() {
+ assert_eq!(
+ MoreDefaultsT::default(),
+ MoreDefaultsT {
+ ints: Vec::new(),
+ floats: Vec::new(),
+ empty_string: "".to_string(),
+ some_string: "some".to_string(),
+ abcs: Vec::new(),
+ bools: Vec::new(),
+ },
+ )
+}
+
+#[test]
+fn nonpresent_values() {
+ let m = flatbuffers::root::<MoreDefaults>(&[0; 4]).unwrap();
+ assert_eq!(m.ints().len(), 0);
+ assert_eq!(m.floats().len(), 0);
+ assert_eq!(m.abcs().len(), 0);
+ assert_eq!(m.bools().len(), 0);
+ assert_eq!(m.empty_string(), "");
+ assert_eq!(m.some_string(), "some");
+}
diff --git a/tests/rust_usage_test/tests/optional_scalars_test.rs b/tests/rust_usage_test/tests/optional_scalars_test.rs
index f029d03..f8588c5 100644
--- a/tests/rust_usage_test/tests/optional_scalars_test.rs
+++ b/tests/rust_usage_test/tests/optional_scalars_test.rs
@@ -1,5 +1,5 @@
#[allow(dead_code, unused_imports)]
-#[path = "../../optional_scalars_generated.rs"]
+#[path = "../../optional_scalars/mod.rs"]
mod optional_scalars_generated;
use crate::optional_scalars_generated::optional_scalars::*;
@@ -27,16 +27,26 @@
);
builder.finish(ss, None);
- let s = flatbuffers::get_root::<ScalarStuff>(builder.finished_data());
+ let s = flatbuffers::root::<ScalarStuff>(builder.finished_data()).unwrap();
assert_eq!(s.$just(), $five);
assert_eq!(s.$default(), $five);
assert_eq!(s.$maybe(), Some($five));
// Test defaults are used when not specified.
- let s = flatbuffers::get_root::<ScalarStuff>(&[0; 8]);
+ let s = flatbuffers::root::<ScalarStuff>(&[0; 8]).unwrap();
assert_eq!(s.$just(), $zero);
assert_eq!(s.$default(), $fortytwo);
assert_eq!(s.$maybe(), None);
+
+ // Same for object API
+ let s = flatbuffers::root::<ScalarStuff>(builder.finished_data()).unwrap().unpack();
+ assert_eq!(s.$just, $five);
+ assert_eq!(s.$default, $five);
+ assert_eq!(s.$maybe, Some($five));
+ let s = flatbuffers::root::<ScalarStuff>(&[0; 8]).unwrap().unpack();
+ assert_eq!(s.$just, $zero);
+ assert_eq!(s.$default, $fortytwo);
+ assert_eq!(s.$maybe, None);
}
};
}
@@ -85,3 +95,55 @@
OptionalByte::None,
OptionalByte::One
);
+
+#[test]
+fn object_api_defaults() {
+ assert_eq!(
+ ScalarStuffT::default(),
+ ScalarStuffT {
+ just_i8: 0,
+ maybe_i8: None,
+ default_i8: 42,
+ just_u8: 0,
+ maybe_u8: None,
+ default_u8: 42,
+
+ just_i16: 0,
+ maybe_i16: None,
+ default_i16: 42,
+ just_u16: 0,
+ maybe_u16: None,
+ default_u16: 42,
+
+ just_i32: 0,
+ maybe_i32: None,
+ default_i32: 42,
+ just_u32: 0,
+ maybe_u32: None,
+ default_u32: 42,
+
+ just_i64: 0,
+ maybe_i64: None,
+ default_i64: 42,
+ just_u64: 0,
+ maybe_u64: None,
+ default_u64: 42,
+
+ just_f32: 0.0,
+ maybe_f32: None,
+ default_f32: 42.0,
+ just_f64: 0.0,
+ maybe_f64: None,
+ default_f64: 42.0,
+
+ just_bool: false,
+ maybe_bool: None,
+ default_bool: true,
+
+ just_enum: OptionalByte::None,
+ maybe_enum: None,
+ default_enum: OptionalByte::One,
+
+ }
+ );
+}
diff --git a/tests/test.cpp b/tests/test.cpp
index c11053c..756c0ea 100644
--- a/tests/test.cpp
+++ b/tests/test.cpp
@@ -14,38 +14,29 @@
* limitations under the License.
*/
#include <cmath>
+#include <string>
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
#include "flatbuffers/minireflect.h"
#include "flatbuffers/registry.h"
#include "flatbuffers/util.h"
-
-// clang-format off
-#ifdef FLATBUFFERS_CPP98_STL
- namespace std {
- using flatbuffers::unique_ptr;
- }
-#endif
-// clang-format on
-
#include "monster_test_generated.h"
#include "namespace_test/namespace_test1_generated.h"
#include "namespace_test/namespace_test2_generated.h"
-#include "union_vector/union_vector_generated.h"
-#include "monster_extra_generated.h"
#include "optional_scalars_generated.h"
+#include "union_vector/union_vector_generated.h"
#if !defined(_MSC_VER) || _MSC_VER >= 1700
# include "arrays_test_generated.h"
# include "evolution_test/evolution_v1_generated.h"
# include "evolution_test/evolution_v2_generated.h"
+# include "monster_extra_generated.h"
#endif
-#include "native_type_test_generated.h"
-#include "test_assert.h"
-
#include "flatbuffers/flexbuffers.h"
#include "monster_test_bfbs_generated.h" // Generated using --bfbs-comments --bfbs-builtins --cpp --bfbs-gen-embed
+#include "native_type_test_generated.h"
+#include "test_assert.h"
// clang-format off
// Check that char* and uint8_t* are interoperable types.
@@ -63,8 +54,8 @@
// clang-format on
// Shortcuts for the infinity.
-static const auto infinityf = std::numeric_limits<float>::infinity();
-static const auto infinityd = std::numeric_limits<double>::infinity();
+static const auto infinity_f = std::numeric_limits<float>::infinity();
+static const auto infinity_d = std::numeric_limits<double>::infinity();
using namespace MyGame::Example;
@@ -107,21 +98,9 @@
Test tests[] = { Test(10, 20), Test(30, 40) };
auto testv = builder.CreateVectorOfStructs(tests, 2);
- // clang-format off
- #ifndef FLATBUFFERS_CPP98_STL
- // Create a vector of structures from a lambda.
- auto testv2 = builder.CreateVectorOfStructs<Test>(
- 2, [&](size_t i, Test* s) -> void {
- *s = tests[i];
- });
- #else
- // Create a vector of structures using a plain old C++ function.
- auto testv2 = builder.CreateVectorOfStructs<Test>(
- 2, [](size_t i, Test* s, void *state) -> void {
- *s = (reinterpret_cast<Test*>(state))[i];
- }, tests);
- #endif // FLATBUFFERS_CPP98_STL
- // clang-format on
+ // Create a vector of structures from a lambda.
+ auto testv2 = builder.CreateVectorOfStructs<Test>(
+ 2, [&](size_t i, Test *s) -> void { *s = tests[i]; });
// create monster with very few fields set:
// (same functionality as CreateMonster below, but sets fields manually)
@@ -157,6 +136,15 @@
names2.push_back("mary");
auto vecofstrings2 = builder.CreateVectorOfStrings(names2);
+ // Create many vectors of strings
+ std::vector<std::string> manyNames;
+ for (auto i = 0; i < 100; i++) { manyNames.push_back("john_doe"); }
+ auto manyNamesVec = builder.CreateVectorOfStrings(manyNames);
+ TEST_EQ(false, manyNamesVec.IsNull());
+ auto manyNamesVec2 =
+ builder.CreateVectorOfStrings(manyNames.cbegin(), manyNames.cend());
+ TEST_EQ(false, manyNamesVec2.IsNull());
+
// Create an array of sorted tables, can be used with binary search when read:
auto vecoftables = builder.CreateVectorOfSortedTables(mlocs, 3);
@@ -166,9 +154,18 @@
abilities.push_back(Ability(4, 40));
abilities.push_back(Ability(3, 30));
abilities.push_back(Ability(2, 20));
- abilities.push_back(Ability(1, 10));
+ abilities.push_back(Ability(0, 0));
auto vecofstructs = builder.CreateVectorOfSortedStructs(&abilities);
+ flatbuffers::Offset<Stat> mlocs_stats[1];
+ auto miss = builder.CreateString("miss");
+ StatBuilder mb_miss(builder);
+ mb_miss.add_id(miss);
+ mb_miss.add_val(0);
+ mb_miss.add_count(0); // key
+ mlocs_stats[0] = mb_miss.Finish();
+ auto vec_of_stats = builder.CreateVectorOfSortedTables(mlocs_stats, 1);
+
// Create a nested FlatBuffer.
// Nested FlatBuffers are stored in a ubyte vector, which can be convenient
// since they can be memcpy'd around much easier than other FlatBuffer
@@ -195,7 +192,6 @@
flexbuild.Int(1234);
flexbuild.Finish();
auto flex = builder.CreateVector(flexbuild.GetBuffer());
-
// Test vector of enums.
Color colors[] = { Color_Blue, Color_Green };
// We use this special creation function because we have an array of
@@ -210,11 +206,12 @@
testv, vecofstrings, vecoftables, 0, nested_flatbuffer_vector, 0, false,
0, 0, 0, 0, 0, 0, 0, 0, 0, 3.14159f, 3.0f, 0.0f, vecofstrings2,
vecofstructs, flex, testv2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- AnyUniqueAliases_NONE, 0, AnyAmbiguousAliases_NONE, 0, vecofcolors);
+ AnyUniqueAliases_NONE, 0, AnyAmbiguousAliases_NONE, 0, vecofcolors,
+ MyGame::Example::Race_None, 0, vec_of_stats);
FinishMonsterBuffer(builder, mloc);
- // clang-format off
+// clang-format off
#ifdef FLATBUFFERS_TEST_VERBOSE
// print byte data for debugging:
auto p = builder.GetBufferPointer();
@@ -236,9 +233,11 @@
bool pooled = true) {
// First, verify the buffers integrity (optional)
flatbuffers::Verifier verifier(flatbuf, length);
+ std::vector<uint8_t> flex_reuse_tracker;
+ verifier.SetFlexReuseTracker(&flex_reuse_tracker);
TEST_EQ(VerifyMonsterBuffer(verifier), true);
- // clang-format off
+// clang-format off
#ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
std::vector<uint8_t> test_buff;
test_buff.resize(length * 2);
@@ -281,7 +280,7 @@
unsigned char inv_data[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
// Check compatibilty of iterators with STL.
std::vector<unsigned char> inv_vec(inventory->begin(), inventory->end());
- int n = 0;
+ size_t n = 0;
for (auto it = inventory->begin(); it != inventory->end(); ++it, ++n) {
auto indx = it - inventory->begin();
TEST_EQ(*it, inv_vec.at(indx)); // Use bounds-check.
@@ -361,11 +360,20 @@
auto right = vecofstructs->Get(i + 1);
TEST_EQ(true, (left->KeyCompareLessThan(right)));
}
+ TEST_NOTNULL(vecofstructs->LookupByKey(0)); // test default value
TEST_NOTNULL(vecofstructs->LookupByKey(3));
TEST_EQ(static_cast<const Ability *>(nullptr),
vecofstructs->LookupByKey(5));
}
+ if (auto vec_of_stat = monster->scalar_key_sorted_tables()) {
+ auto stat_0 = vec_of_stat->LookupByKey(static_cast<uint16_t>(0u));
+ TEST_NOTNULL(stat_0);
+ TEST_NOTNULL(stat_0->id());
+ TEST_EQ(0, stat_0->count());
+ TEST_EQ_STR("miss", stat_0->id()->c_str());
+ }
+
// Test nested FlatBuffers if available:
auto nested_buffer = monster->testnestedflatbuffer();
if (nested_buffer) {
@@ -473,52 +481,22 @@
TEST_EQ(first->hp(), 0);
first->mutate_hp(1000);
+ // Mutate via LookupByKey
+ TEST_NOTNULL(tables->MutableLookupByKey("Barney"));
+ TEST_EQ(static_cast<Monster *>(nullptr),
+ tables->MutableLookupByKey("DoesntExist"));
+ TEST_EQ(tables->MutableLookupByKey("Barney")->hp(), 1000);
+ TEST_EQ(tables->MutableLookupByKey("Barney")->mutate_hp(0), true);
+ TEST_EQ(tables->LookupByKey("Barney")->hp(), 0);
+ TEST_EQ(tables->MutableLookupByKey("Barney")->mutate_hp(1000), true);
+
// Run the verifier and the regular test to make sure we didn't trample on
// anything.
AccessFlatBufferTest(flatbuf, length);
}
-// Unpack a FlatBuffer into objects.
-void ObjectFlatBuffersTest(uint8_t *flatbuf) {
- // Optional: we can specify resolver and rehasher functions to turn hashed
- // strings into object pointers and back, to implement remote references
- // and such.
- auto resolver = flatbuffers::resolver_function_t(
- [](void **pointer_adr, flatbuffers::hash_value_t hash) {
- (void)pointer_adr;
- (void)hash;
- // Don't actually do anything, leave variable null.
- });
- auto rehasher = flatbuffers::rehasher_function_t(
- [](void *pointer) -> flatbuffers::hash_value_t {
- (void)pointer;
- return 0;
- });
-
- // Turn a buffer into C++ objects.
- auto monster1 = UnPackMonster(flatbuf, &resolver);
-
- // Re-serialize the data.
- flatbuffers::FlatBufferBuilder fbb1;
- fbb1.Finish(CreateMonster(fbb1, monster1.get(), &rehasher),
- MonsterIdentifier());
-
- // Unpack again, and re-serialize again.
- auto monster2 = UnPackMonster(fbb1.GetBufferPointer(), &resolver);
- flatbuffers::FlatBufferBuilder fbb2;
- fbb2.Finish(CreateMonster(fbb2, monster2.get(), &rehasher),
- MonsterIdentifier());
-
- // Now we've gone full round-trip, the two buffers should match.
- auto len1 = fbb1.GetSize();
- auto len2 = fbb2.GetSize();
- TEST_EQ(len1, len2);
- TEST_EQ(memcmp(fbb1.GetBufferPointer(), fbb2.GetBufferPointer(), len1), 0);
-
- // Test it with the original buffer test to make sure all data survived.
- AccessFlatBufferTest(fbb2.GetBufferPointer(), len2, false);
-
- // Test accessing fields, similar to AccessFlatBufferTest above.
+// Utility function to check a Monster object.
+void CheckMonsterObject(MonsterT *monster2) {
TEST_EQ(monster2->hp, 80);
TEST_EQ(monster2->mana, 150); // default
TEST_EQ_STR(monster2->name.c_str(), "MyMonster");
@@ -565,6 +543,62 @@
TEST_EQ(tests[1].b(), 40);
}
+// Unpack a FlatBuffer into objects.
+void ObjectFlatBuffersTest(uint8_t *flatbuf) {
+ // Optional: we can specify resolver and rehasher functions to turn hashed
+ // strings into object pointers and back, to implement remote references
+ // and such.
+ auto resolver = flatbuffers::resolver_function_t(
+ [](void **pointer_adr, flatbuffers::hash_value_t hash) {
+ (void)pointer_adr;
+ (void)hash;
+ // Don't actually do anything, leave variable null.
+ });
+ auto rehasher = flatbuffers::rehasher_function_t(
+ [](void *pointer) -> flatbuffers::hash_value_t {
+ (void)pointer;
+ return 0;
+ });
+
+ // Turn a buffer into C++ objects.
+ auto monster1 = UnPackMonster(flatbuf, &resolver);
+
+ // Re-serialize the data.
+ flatbuffers::FlatBufferBuilder fbb1;
+ fbb1.Finish(CreateMonster(fbb1, monster1.get(), &rehasher),
+ MonsterIdentifier());
+
+ // Unpack again, and re-serialize again.
+ auto monster2 = UnPackMonster(fbb1.GetBufferPointer(), &resolver);
+ flatbuffers::FlatBufferBuilder fbb2;
+ fbb2.Finish(CreateMonster(fbb2, monster2.get(), &rehasher),
+ MonsterIdentifier());
+
+ // Now we've gone full round-trip, the two buffers should match.
+ const auto len1 = fbb1.GetSize();
+ const auto len2 = fbb2.GetSize();
+ TEST_EQ(len1, len2);
+ TEST_EQ(memcmp(fbb1.GetBufferPointer(), fbb2.GetBufferPointer(), len1), 0);
+
+ // Test it with the original buffer test to make sure all data survived.
+ AccessFlatBufferTest(fbb2.GetBufferPointer(), len2, false);
+
+ // Test accessing fields, similar to AccessFlatBufferTest above.
+ CheckMonsterObject(monster2.get());
+
+ // Test object copy.
+ auto monster3 = *monster2;
+ flatbuffers::FlatBufferBuilder fbb3;
+ fbb3.Finish(CreateMonster(fbb3, &monster3, &rehasher), MonsterIdentifier());
+ const auto len3 = fbb3.GetSize();
+ TEST_EQ(len2, len3);
+ TEST_EQ(memcmp(fbb2.GetBufferPointer(), fbb3.GetBufferPointer(), len2), 0);
+ // Delete monster1 and monster2, then test accessing fields in monster3.
+ monster1.reset();
+ monster2.reset();
+ CheckMonsterObject(&monster3);
+}
+
// Prefix a FlatBuffer with a size field.
void SizePrefixedTest() {
// Create size prefixed buffer.
@@ -584,7 +618,7 @@
}
void TriviallyCopyableTest() {
- // clang-format off
+// clang-format off
#if __GNUG__ && __GNUC__ < 5
TEST_EQ(__has_trivial_copy(Vec3), true);
#else
@@ -678,7 +712,7 @@
std::memcpy(&b, &v, sizeof(T));
return ((b & qnan_base) == qnan_base);
}
-#if defined(__mips__) || defined(__hppa__)
+# if defined(__mips__) || defined(__hppa__)
static bool is_quiet_nan(float v) {
return is_quiet_nan_impl<float, uint32_t, 0x7FC00000u>(v) ||
is_quiet_nan_impl<float, uint32_t, 0x7FBFFFFFu>(v);
@@ -687,19 +721,19 @@
return is_quiet_nan_impl<double, uint64_t, 0x7FF8000000000000ul>(v) ||
is_quiet_nan_impl<double, uint64_t, 0x7FF7FFFFFFFFFFFFu>(v);
}
-#else
+# else
static bool is_quiet_nan(float v) {
return is_quiet_nan_impl<float, uint32_t, 0x7FC00000u>(v);
}
static bool is_quiet_nan(double v) {
return is_quiet_nan_impl<double, uint64_t, 0x7FF8000000000000ul>(v);
}
-#endif
+# endif
void TestMonsterExtraFloats() {
TEST_EQ(is_quiet_nan(1.0), false);
- TEST_EQ(is_quiet_nan(infinityd), false);
- TEST_EQ(is_quiet_nan(-infinityf), false);
+ TEST_EQ(is_quiet_nan(infinity_d), false);
+ TEST_EQ(is_quiet_nan(-infinity_f), false);
TEST_EQ(is_quiet_nan(std::numeric_limits<float>::quiet_NaN()), true);
TEST_EQ(is_quiet_nan(std::numeric_limits<double>::quiet_NaN()), true);
@@ -727,12 +761,12 @@
TEST_NOTNULL(def_extra);
TEST_EQ(is_quiet_nan(def_extra->f0()), true);
TEST_EQ(is_quiet_nan(def_extra->f1()), true);
- TEST_EQ(def_extra->f2(), +infinityf);
- TEST_EQ(def_extra->f3(), -infinityf);
+ TEST_EQ(def_extra->f2(), +infinity_f);
+ TEST_EQ(def_extra->f3(), -infinity_f);
TEST_EQ(is_quiet_nan(def_extra->d0()), true);
TEST_EQ(is_quiet_nan(def_extra->d1()), true);
- TEST_EQ(def_extra->d2(), +infinityd);
- TEST_EQ(def_extra->d3(), -infinityd);
+ TEST_EQ(def_extra->d2(), +infinity_d);
+ TEST_EQ(def_extra->d3(), -infinity_d);
std::string jsongen;
auto result = GenerateText(parser, def_obj, &jsongen);
TEST_EQ(result, true);
@@ -758,23 +792,23 @@
TEST_NOTNULL(extra);
TEST_EQ(is_quiet_nan(extra->f0()), true);
TEST_EQ(is_quiet_nan(extra->f1()), true);
- TEST_EQ(extra->f2(), +infinityf);
- TEST_EQ(extra->f3(), -infinityf);
+ TEST_EQ(extra->f2(), +infinity_f);
+ TEST_EQ(extra->f3(), -infinity_f);
TEST_EQ(is_quiet_nan(extra->d0()), true);
- TEST_EQ(extra->d1(), +infinityd);
- TEST_EQ(extra->d2(), -infinityd);
+ TEST_EQ(extra->d1(), +infinity_d);
+ TEST_EQ(extra->d2(), -infinity_d);
TEST_EQ(is_quiet_nan(extra->d3()), true);
TEST_NOTNULL(extra->fvec());
TEST_EQ(extra->fvec()->size(), 4);
TEST_EQ(extra->fvec()->Get(0), 1.0f);
- TEST_EQ(extra->fvec()->Get(1), -infinityf);
- TEST_EQ(extra->fvec()->Get(2), +infinityf);
+ TEST_EQ(extra->fvec()->Get(1), -infinity_f);
+ TEST_EQ(extra->fvec()->Get(2), +infinity_f);
TEST_EQ(is_quiet_nan(extra->fvec()->Get(3)), true);
TEST_NOTNULL(extra->dvec());
TEST_EQ(extra->dvec()->size(), 4);
TEST_EQ(extra->dvec()->Get(0), 2.0);
- TEST_EQ(extra->dvec()->Get(1), +infinityd);
- TEST_EQ(extra->dvec()->Get(2), -infinityd);
+ TEST_EQ(extra->dvec()->Get(1), +infinity_d);
+ TEST_EQ(extra->dvec()->Get(2), -infinity_d);
TEST_EQ(is_quiet_nan(extra->dvec()->Get(3)), true);
}
#else
@@ -892,7 +926,56 @@
// Make sure the schema is what we expect it to be.
auto &schema = *reflection::GetSchema(bfbsfile.c_str());
auto root_table = schema.root_table();
+
+ // Check the declaration files.
TEST_EQ_STR(root_table->name()->c_str(), "MyGame.Example.Monster");
+ TEST_EQ_STR(root_table->declaration_file()->c_str(), "//monster_test.fbs");
+ TEST_EQ_STR(
+ schema.objects()->LookupByKey("TableA")->declaration_file()->c_str(),
+ "//include_test/include_test1.fbs");
+ TEST_EQ_STR(schema.objects()
+ ->LookupByKey("MyGame.OtherNameSpace.Unused")
+ ->declaration_file()
+ ->c_str(),
+ "//include_test/sub/include_test2.fbs");
+ TEST_EQ_STR(schema.enums()
+ ->LookupByKey("MyGame.OtherNameSpace.FromInclude")
+ ->declaration_file()
+ ->c_str(),
+ "//include_test/sub/include_test2.fbs");
+
+ // Check scheam filenames and their includes.
+ TEST_EQ(schema.fbs_files()->size(), 3);
+
+ const auto fbs0 = schema.fbs_files()->Get(0);
+ TEST_EQ_STR(fbs0->filename()->c_str(), "//include_test/include_test1.fbs");
+ const auto fbs0_includes = fbs0->included_filenames();
+ TEST_EQ(fbs0_includes->size(), 2);
+
+ // TODO(caspern): Should we force or disallow inclusion of self?
+ TEST_EQ_STR(fbs0_includes->Get(0)->c_str(),
+ "//include_test/include_test1.fbs");
+ TEST_EQ_STR(fbs0_includes->Get(1)->c_str(),
+ "//include_test/sub/include_test2.fbs");
+
+ const auto fbs1 = schema.fbs_files()->Get(1);
+ TEST_EQ_STR(fbs1->filename()->c_str(),
+ "//include_test/sub/include_test2.fbs");
+ const auto fbs1_includes = fbs1->included_filenames();
+ TEST_EQ(fbs1_includes->size(), 2);
+ TEST_EQ_STR(fbs1_includes->Get(0)->c_str(),
+ "//include_test/include_test1.fbs");
+ TEST_EQ_STR(fbs1_includes->Get(1)->c_str(),
+ "//include_test/sub/include_test2.fbs");
+
+ const auto fbs2 = schema.fbs_files()->Get(2);
+ TEST_EQ_STR(fbs2->filename()->c_str(), "//monster_test.fbs");
+ const auto fbs2_includes = fbs2->included_filenames();
+ TEST_EQ(fbs2_includes->size(), 1);
+ TEST_EQ_STR(fbs2_includes->Get(0)->c_str(),
+ "//include_test/include_test1.fbs");
+
+ // Check Root table fields
auto fields = root_table->fields();
auto hp_field_ptr = fields->LookupByKey("hp");
TEST_NOTNULL(hp_field_ptr);
@@ -986,9 +1069,8 @@
// Get the root.
// This time we wrap the result from GetAnyRoot in a smartpointer that
// will keep rroot valid as resizingbuf resizes.
- auto rroot = flatbuffers::piv(
- flatbuffers::GetAnyRoot(flatbuffers::vector_data(resizingbuf)),
- resizingbuf);
+ auto rroot = flatbuffers::piv(flatbuffers::GetAnyRoot(resizingbuf.data()),
+ resizingbuf);
SetString(schema, "totally new string", GetFieldS(**rroot, name_field),
&resizingbuf);
// Here resizingbuf has changed, but rroot is still valid.
@@ -1032,13 +1114,12 @@
TEST_EQ_STR(rtestarrayofstring->Get(2)->c_str(), "hank");
// Test integrity of all resize operations above.
flatbuffers::Verifier resize_verifier(
- reinterpret_cast<const uint8_t *>(flatbuffers::vector_data(resizingbuf)),
+ reinterpret_cast<const uint8_t *>(resizingbuf.data()),
resizingbuf.size());
TEST_EQ(VerifyMonsterBuffer(resize_verifier), true);
// Test buffer is valid using reflection as well
- TEST_EQ(flatbuffers::Verify(schema, *schema.root_table(),
- flatbuffers::vector_data(resizingbuf),
+ TEST_EQ(flatbuffers::Verify(schema, *schema.root_table(), resizingbuf.data(),
resizingbuf.size()),
true);
@@ -1088,12 +1169,13 @@
"4, 0, 6, 0, 8, 0, 12, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 13, 0, 0, 0, 78, "
"101, 115, 116, 101, 100, 77, 111, 110, 115, 116, 101, 114, 0, 0, 0 ], "
"testarrayofstring2: [ \"jane\", \"mary\" ], "
- "testarrayofsortedstruct: [ { id: 1, distance: 10 }, "
+ "testarrayofsortedstruct: [ { id: 0, distance: 0 }, "
"{ id: 2, distance: 20 }, { id: 3, distance: 30 }, "
"{ id: 4, distance: 40 } ], "
"flex: [ 210, 4, 5, 2 ], "
"test5: [ { a: 10, b: 20 }, { a: 30, b: 40 } ], "
- "vector_of_enums: [ Blue, Green ] "
+ "vector_of_enums: [ Blue, Green ], "
+ "scalar_key_sorted_tables: [ { id: \"miss\" } ] "
"}");
Test test(16, 32);
@@ -1280,9 +1362,13 @@
// Ensure generated file is parsable.
flatbuffers::Parser parser2;
- TEST_EQ(
- parser2.Parse(import_fbs.c_str(), include_directories, "imported.fbs"),
- true);
+ // Since `imported.fbs` isn't in the filesystem AbsolutePath can't figure it
+ // out by itself. We manually construct it so Parser works.
+ std::string imported_fbs = flatbuffers::PosixPath(
+ flatbuffers::AbsolutePath(protopath) + "/imported.fbs");
+ TEST_EQ(parser2.Parse(import_fbs.c_str(), include_directories,
+ imported_fbs.c_str()),
+ true);
TEST_EQ(parser2.Parse(fbs.c_str(), nullptr), true);
TEST_EQ_STR(fbs.c_str(), goldenfile.c_str());
@@ -1296,7 +1382,8 @@
// Ensure generated file is parsable.
flatbuffers::Parser parser4;
- TEST_EQ(parser4.Parse(import_fbs.c_str(), nullptr, "imported.fbs"), true);
+ TEST_EQ(parser4.Parse(import_fbs.c_str(), nullptr, imported_fbs.c_str()),
+ true);
TEST_EQ(parser4.Parse(fbs_union.c_str(), nullptr), true);
TEST_EQ_STR(fbs_union.c_str(), goldenunionfile.c_str());
}
@@ -1308,6 +1395,90 @@
TEST_EQ(read, val);
}
+void UtilConvertCase() {
+ {
+ std::vector<std::tuple<std::string, flatbuffers::Case, std::string>>
+ cases = {
+ // Tests for the common cases
+ { "the_quick_brown_fox", flatbuffers::Case::kUpperCamel,
+ "TheQuickBrownFox" },
+ { "the_quick_brown_fox", flatbuffers::Case::kLowerCamel,
+ "theQuickBrownFox" },
+ { "the_quick_brown_fox", flatbuffers::Case::kSnake,
+ "the_quick_brown_fox" },
+ { "the_quick_brown_fox", flatbuffers::Case::kScreamingSnake,
+ "THE_QUICK_BROWN_FOX" },
+ { "the_quick_brown_fox", flatbuffers::Case::kAllLower,
+ "the_quick_brown_fox" },
+ { "the_quick_brown_fox", flatbuffers::Case::kAllUpper,
+ "THE_QUICK_BROWN_FOX" },
+ { "the_quick_brown_fox", flatbuffers::Case::kUnknown,
+ "the_quick_brown_fox" },
+ { "the_quick_brown_fox", flatbuffers::Case::kKeep,
+ "the_quick_brown_fox" },
+
+ // Tests for some snake_cases where the _ is oddly placed or missing.
+ { "single", flatbuffers::Case::kUpperCamel, "Single" },
+ { "Single", flatbuffers::Case::kUpperCamel, "Single" },
+ { "_leading", flatbuffers::Case::kUpperCamel, "_leading" },
+ { "trailing_", flatbuffers::Case::kUpperCamel, "Trailing_" },
+ { "double__underscore", flatbuffers::Case::kUpperCamel,
+ "Double_underscore" },
+ { "single", flatbuffers::Case::kLowerCamel, "single" },
+ { "Single", flatbuffers::Case::kLowerCamel, "Single" },
+ { "_leading", flatbuffers::Case::kLowerCamel, "Leading" },
+ { "trailing_", flatbuffers::Case::kLowerCamel, "trailing_" },
+ { "double__underscore", flatbuffers::Case::kLowerCamel,
+ "double_underscore" },
+
+ // Tests for some output snake_cases
+ { "single", flatbuffers::Case::kSnake, "single" },
+ { "single", flatbuffers::Case::kScreamingSnake, "SINGLE" },
+ { "_leading", flatbuffers::Case::kScreamingSnake, "_LEADING" },
+ { "trailing_", flatbuffers::Case::kScreamingSnake, "TRAILING_" },
+ { "double__underscore", flatbuffers::Case::kScreamingSnake,
+ "DOUBLE__UNDERSCORE" },
+ };
+
+ for (auto &test_case : cases) {
+ TEST_EQ(std::get<2>(test_case),
+ flatbuffers::ConvertCase(std::get<0>(test_case),
+ std::get<1>(test_case)));
+ }
+ }
+
+ // Tests for the non snake_case inputs.
+ {
+ std::vector<std::tuple<flatbuffers::Case, std::string, flatbuffers::Case,
+ std::string>>
+ cases = {
+ { flatbuffers::Case::kUpperCamel, "TheQuickBrownFox",
+ flatbuffers::Case::kSnake, "the_quick_brown_fox" },
+ { flatbuffers::Case::kLowerCamel, "theQuickBrownFox",
+ flatbuffers::Case::kSnake, "the_quick_brown_fox" },
+ { flatbuffers::Case::kSnake, "the_quick_brown_fox",
+ flatbuffers::Case::kSnake, "the_quick_brown_fox" },
+ { flatbuffers::Case::kScreamingSnake, "THE_QUICK_BROWN_FOX",
+ flatbuffers::Case::kSnake, "THE_QUICK_BROWN_FOX" },
+ { flatbuffers::Case::kAllUpper, "SINGLE", flatbuffers::Case::kSnake,
+ "SINGLE" },
+ { flatbuffers::Case::kAllLower, "single", flatbuffers::Case::kSnake,
+ "single" },
+ { flatbuffers::Case::kUpperCamel, "ABCtest",
+ flatbuffers::Case::kSnake, "abctest" },
+ { flatbuffers::Case::kUpperCamel, "tHe_qUiCk_BrOwN_fOx",
+ flatbuffers::Case::kKeep, "tHe_qUiCk_BrOwN_fOx" },
+ };
+
+ for (auto &test_case : cases) {
+ TEST_EQ(std::get<3>(test_case),
+ flatbuffers::ConvertCase(std::get<1>(test_case),
+ std::get<2>(test_case),
+ std::get<0>(test_case)));
+ }
+ }
+}
+
// Low level stress/fuzz test: serialize/deserialize a variety of
// different kinds of data in different combinations
void FuzzTest1() {
@@ -1419,7 +1590,7 @@
}
};
- // clang-format off
+// clang-format off
#define AddToSchemaAndInstances(schema_add, instance_add) \
RndDef::Add(definitions, schema, instances_per_definition, \
schema_add, instance_add, definition)
@@ -1526,7 +1697,9 @@
}
}
AddToSchemaAndInstances(deprecated ? "(deprecated);\n" : ";\n",
- deprecated ? "" : is_last_field ? "\n" : ",\n");
+ deprecated ? ""
+ : is_last_field ? "\n"
+ : ",\n");
}
AddToSchemaAndInstances("}\n\n", "}");
}
@@ -1571,7 +1744,7 @@
TEST_NOTNULL(nullptr); //-V501 (this comment supresses CWE-570 warning)
}
- // clang-format off
+// clang-format off
#ifdef FLATBUFFERS_TEST_VERBOSE
TEST_OUTPUT_LINE("%dk schema tested with %dk of json\n",
static_cast<int>(schema.length() / 1024),
@@ -1625,7 +1798,6 @@
TestError("table X { Y:int; Y:int; }", "field already");
TestError("table Y {} table X { Y:int; }", "same as table");
TestError("struct X { Y:string; }", "only scalar");
- TestError("table X { Y:string = \"\"; }", "default values");
TestError("struct X { a:uint = 42; }", "default values");
TestError("enum Y:byte { Z = 1 } table X { y:Y; }", "not part of enum");
TestError("struct X { Y:int (deprecated); }", "deprecate");
@@ -1649,6 +1821,12 @@
TestError("enum X:byte { Y, Y }", "value already");
TestError("enum X:byte { Y=2, Z=2 }", "unique");
TestError("table X { Y:int; } table X {", "datatype already");
+ TestError("table X { } union X { }", "datatype already");
+ TestError("union X { } table X { }", "datatype already");
+ TestError("namespace A; table X { } namespace A; union X { }",
+ "datatype already");
+ TestError("namespace A; union X { } namespace A; table X { }",
+ "datatype already");
TestError("struct X (force_align: 7) { Y:int; }", "force_align");
TestError("struct X {}", "size 0");
TestError("{}", "no root");
@@ -1670,6 +1848,15 @@
"may contain only scalar or struct fields");
// Non-snake case field names
TestError("table X { Y: int; } root_type Y: {Y:1.0}", "snake_case");
+ // Complex defaults
+ TestError("table X { y: string = 1; }", "expecting: string");
+ TestError("table X { y: string = []; }", " Cannot assign token");
+ TestError("table X { y: [int] = [1]; }", "Expected `]`");
+ TestError("table X { y: [int] = [; }", "Expected `]`");
+ TestError("table X { y: [int] = \"\"; }", "type mismatch");
+ // An identifier can't start from sign (+|-)
+ TestError("table X { -Y: int; } root_type Y: {Y:1.0}", "identifier");
+ TestError("table X { +Y: int; } root_type Y: {Y:1.0}", "identifier");
}
template<typename T>
@@ -1967,10 +2154,10 @@
void ValidFloatTest() {
// check rounding to infinity
- TEST_EQ(TestValue<float>("{ y:+3.4029e+38 }", "float"), +infinityf);
- TEST_EQ(TestValue<float>("{ y:-3.4029e+38 }", "float"), -infinityf);
- TEST_EQ(TestValue<double>("{ y:+1.7977e+308 }", "double"), +infinityd);
- TEST_EQ(TestValue<double>("{ y:-1.7977e+308 }", "double"), -infinityd);
+ TEST_EQ(TestValue<float>("{ y:+3.4029e+38 }", "float"), +infinity_f);
+ TEST_EQ(TestValue<float>("{ y:-3.4029e+38 }", "float"), -infinity_f);
+ TEST_EQ(TestValue<double>("{ y:+1.7977e+308 }", "double"), +infinity_d);
+ TEST_EQ(TestValue<double>("{ y:-1.7977e+308 }", "double"), -infinity_d);
TEST_EQ(
FloatCompare(TestValue<float>("{ y:0.0314159e+2 }", "float"), 3.14159f),
@@ -2004,17 +2191,21 @@
TEST_EQ(std::isnan(TestValue<double>("{ y:nan }", "double")), true);
TEST_EQ(std::isnan(TestValue<float>("{ y:nan }", "float")), true);
TEST_EQ(std::isnan(TestValue<float>("{ y:\"nan\" }", "float")), true);
+ TEST_EQ(std::isnan(TestValue<float>("{ y:\"+nan\" }", "float")), true);
+ TEST_EQ(std::isnan(TestValue<float>("{ y:\"-nan\" }", "float")), true);
TEST_EQ(std::isnan(TestValue<float>("{ y:+nan }", "float")), true);
TEST_EQ(std::isnan(TestValue<float>("{ y:-nan }", "float")), true);
TEST_EQ(std::isnan(TestValue<float>(nullptr, "float=nan")), true);
TEST_EQ(std::isnan(TestValue<float>(nullptr, "float=-nan")), true);
// check inf
- TEST_EQ(TestValue<float>("{ y:inf }", "float"), infinityf);
- TEST_EQ(TestValue<float>("{ y:\"inf\" }", "float"), infinityf);
- TEST_EQ(TestValue<float>("{ y:+inf }", "float"), infinityf);
- TEST_EQ(TestValue<float>("{ y:-inf }", "float"), -infinityf);
- TEST_EQ(TestValue<float>(nullptr, "float=inf"), infinityf);
- TEST_EQ(TestValue<float>(nullptr, "float=-inf"), -infinityf);
+ TEST_EQ(TestValue<float>("{ y:inf }", "float"), infinity_f);
+ TEST_EQ(TestValue<float>("{ y:\"inf\" }", "float"), infinity_f);
+ TEST_EQ(TestValue<float>("{ y:\"-inf\" }", "float"), -infinity_f);
+ TEST_EQ(TestValue<float>("{ y:\"+inf\" }", "float"), infinity_f);
+ TEST_EQ(TestValue<float>("{ y:+inf }", "float"), infinity_f);
+ TEST_EQ(TestValue<float>("{ y:-inf }", "float"), -infinity_f);
+ TEST_EQ(TestValue<float>(nullptr, "float=inf"), infinity_f);
+ TEST_EQ(TestValue<float>(nullptr, "float=-inf"), -infinity_f);
TestValue<double>(
"{ y: [0.2, .2, 1.0, -1.0, -2., 2., 1e0, -1e0, 1.0e0, -1.0e0, -3.e2, "
"3.0e2] }",
@@ -2134,6 +2325,15 @@
TEST_EQ(ok, true);
// Test root table
const Monster *monster = GetMonster(parser.builder_.GetBufferPointer());
+ const auto abilities = monster->testarrayofsortedstruct();
+ TEST_EQ(abilities->size(), 3);
+ TEST_EQ(abilities->Get(0)->id(), 0);
+ TEST_EQ(abilities->Get(0)->distance(), 45);
+ TEST_EQ(abilities->Get(1)->id(), 1);
+ TEST_EQ(abilities->Get(1)->distance(), 21);
+ TEST_EQ(abilities->Get(2)->id(), 5);
+ TEST_EQ(abilities->Get(2)->distance(), 12);
+
std::string jsongen;
auto result = GenerateTextFromTable(parser, monster, "MyGame.Example.Monster",
&jsongen);
@@ -2475,6 +2675,49 @@
true);
}
+void ValidSameNameDifferentNamespaceTest() {
+ // Duplicate table names in different namespaces must be parsable
+ TEST_ASSERT(flatbuffers::Parser().Parse(
+ "namespace A; table X {} namespace B; table X {}"));
+ // Duplicate union names in different namespaces must be parsable
+ TEST_ASSERT(flatbuffers::Parser().Parse(
+ "namespace A; union X {} namespace B; union X {}"));
+ // Clashing table and union names in different namespaces must be parsable
+ TEST_ASSERT(flatbuffers::Parser().Parse(
+ "namespace A; table X {} namespace B; union X {}"));
+ TEST_ASSERT(flatbuffers::Parser().Parse(
+ "namespace A; union X {} namespace B; table X {}"));
+}
+
+void MultiFileNameClashTest() {
+ const auto name_clash_path =
+ flatbuffers::ConCatPathFileName(test_data_path, "name_clash_test");
+ const char *include_directories[] = { name_clash_path.c_str() };
+
+ // Load valid 2 file Flatbuffer schema
+ const auto valid_path =
+ flatbuffers::ConCatPathFileName(name_clash_path, "valid_test1.fbs");
+ std::string valid_schema;
+ TEST_ASSERT(flatbuffers::LoadFile(valid_path.c_str(), false, &valid_schema));
+ // Clashing table and union names in different namespaces must be parsable
+ TEST_ASSERT(
+ flatbuffers::Parser().Parse(valid_schema.c_str(), include_directories));
+
+ flatbuffers::Parser p;
+ TEST_ASSERT(p.Parse(valid_schema.c_str(), include_directories));
+
+ // Load invalid 2 file Flatbuffer schema
+ const auto invalid_path =
+ flatbuffers::ConCatPathFileName(name_clash_path, "invalid_test1.fbs");
+ std::string invalid_schema;
+ TEST_ASSERT(
+ flatbuffers::LoadFile(invalid_path.c_str(), false, &invalid_schema));
+ // Clashing table and union names in same namespace must fail to parse
+ TEST_EQ(
+ flatbuffers::Parser().Parse(invalid_schema.c_str(), include_directories),
+ false);
+}
+
void InvalidNestedFlatbufferTest() {
// First, load and parse FlatBuffer schema (.fbs)
std::string schemafile;
@@ -2792,6 +3035,34 @@
TEST_EQ(parser2.Parse("{a_type:Bool,a:{b:true}}"), true);
}
+void StructUnionTest() {
+ GadgetUnion gadget;
+ gadget.Set(FallingTub(100));
+
+ HandFanT fan;
+ fan.length = 10;
+ gadget.Set(fan);
+}
+
+void WarningsAsErrorsTest() {
+ {
+ flatbuffers::IDLOptions opts;
+ // opts.warnings_as_errors should default to false
+ flatbuffers::Parser parser(opts);
+ TEST_EQ(parser.Parse("table T { THIS_NAME_CAUSES_A_WARNING:string;}\n"
+ "root_type T;"),
+ true);
+ }
+ {
+ flatbuffers::IDLOptions opts;
+ opts.warnings_as_errors = true;
+ flatbuffers::Parser parser(opts);
+ TEST_EQ(parser.Parse("table T { THIS_NAME_CAUSES_A_WARNING:string;}\n"
+ "root_type T;"),
+ false);
+ }
+}
+
void ConformTest() {
flatbuffers::Parser parser;
TEST_EQ(parser.Parse("table T { A:int; } enum E:byte { A }"), true);
@@ -2839,64 +3110,45 @@
// Write the equivalent of:
// { vec: [ -100, "Fred", 4.0, false ], bar: [ 1, 2, 3 ], bar3: [ 1, 2, 3 ],
// foo: 100, bool: true, mymap: { foo: "Fred" } }
- // clang-format off
- #ifndef FLATBUFFERS_CPP98_STL
- // It's possible to do this without std::function support as well.
- slb.Map([&]() {
- slb.Vector("vec", [&]() {
- slb += -100; // Equivalent to slb.Add(-100) or slb.Int(-100);
- slb += "Fred";
- slb.IndirectFloat(4.0f);
- auto i_f = slb.LastValue();
- uint8_t blob[] = { 77 };
- slb.Blob(blob, 1);
- slb += false;
- slb.ReuseValue(i_f);
- });
- int ints[] = { 1, 2, 3 };
- slb.Vector("bar", ints, 3);
- slb.FixedTypedVector("bar3", ints, 3);
- bool bools[] = {true, false, true, false};
- slb.Vector("bools", bools, 4);
- slb.Bool("bool", true);
- slb.Double("foo", 100);
- slb.Map("mymap", [&]() {
- slb.String("foo", "Fred"); // Testing key and string reuse.
- });
- });
- slb.Finish();
- #else
- // It's possible to do this without std::function support as well.
- slb.Map([](flexbuffers::Builder& slb2) {
- slb2.Vector("vec", [](flexbuffers::Builder& slb3) {
- slb3 += -100; // Equivalent to slb.Add(-100) or slb.Int(-100);
- slb3 += "Fred";
- slb3.IndirectFloat(4.0f);
- auto i_f = slb3.LastValue();
- uint8_t blob[] = { 77 };
- slb3.Blob(blob, 1);
- slb3 += false;
- slb3.ReuseValue(i_f);
- }, slb2);
- int ints[] = { 1, 2, 3 };
- slb2.Vector("bar", ints, 3);
- slb2.FixedTypedVector("bar3", ints, 3);
- slb2.Bool("bool", true);
- slb2.Double("foo", 100);
- slb2.Map("mymap", [](flexbuffers::Builder& slb3) {
- slb3.String("foo", "Fred"); // Testing key and string reuse.
- }, slb2);
- }, slb);
- slb.Finish();
- #endif // FLATBUFFERS_CPP98_STL
+ // It's possible to do this without std::function support as well.
+ slb.Map([&]() {
+ slb.Vector("vec", [&]() {
+ slb += -100; // Equivalent to slb.Add(-100) or slb.Int(-100);
+ slb += "Fred";
+ slb.IndirectFloat(4.0f);
+ auto i_f = slb.LastValue();
+ uint8_t blob[] = { 77 };
+ slb.Blob(blob, 1);
+ slb += false;
+ slb.ReuseValue(i_f);
+ });
+ int ints[] = { 1, 2, 3 };
+ slb.Vector("bar", ints, 3);
+ slb.FixedTypedVector("bar3", ints, 3);
+ bool bools[] = { true, false, true, false };
+ slb.Vector("bools", bools, 4);
+ slb.Bool("bool", true);
+ slb.Double("foo", 100);
+ slb.Map("mymap", [&]() {
+ slb.String("foo", "Fred"); // Testing key and string reuse.
+ });
+ });
+ slb.Finish();
+
+// clang-format off
#ifdef FLATBUFFERS_TEST_VERBOSE
for (size_t i = 0; i < slb.GetBuffer().size(); i++)
- printf("%d ", flatbuffers::vector_data(slb.GetBuffer())[i]);
+ printf("%d ", slb.GetBuffer().data()[i]);
printf("\n");
#endif
// clang-format on
+ std::vector<uint8_t> reuse_tracker;
+ TEST_EQ(flexbuffers::VerifyBuffer(slb.GetBuffer().data(),
+ slb.GetBuffer().size(), &reuse_tracker),
+ true);
+
auto map = flexbuffers::GetRoot(slb.GetBuffer()).AsMap();
TEST_EQ(map.size(), 7);
auto vec = map["vec"].AsVector();
@@ -2954,6 +3206,9 @@
slb.Clear();
auto jsontest = "{ a: [ 123, 456.0 ], b: \"hello\", c: true, d: false }";
TEST_EQ(parser.ParseFlexBuffer(jsontest, nullptr, &slb), true);
+ TEST_EQ(flexbuffers::VerifyBuffer(slb.GetBuffer().data(),
+ slb.GetBuffer().size(), &reuse_tracker),
+ true);
auto jroot = flexbuffers::GetRoot(slb.GetBuffer());
auto jmap = jroot.AsMap();
auto jvec = jmap["a"].AsVector();
@@ -2980,6 +3235,34 @@
TEST_EQ(slb.GetSize(), 664);
}
+void FlexBuffersFloatingPointTest() {
+#if defined(FLATBUFFERS_HAS_NEW_STRTOD) && (FLATBUFFERS_HAS_NEW_STRTOD > 0)
+ flexbuffers::Builder slb(512,
+ flexbuffers::BUILDER_FLAG_SHARE_KEYS_AND_STRINGS);
+ // Parse floating-point values from JSON:
+ flatbuffers::Parser parser;
+ slb.Clear();
+ auto jsontest =
+ "{ a: [1.0, nan, inf, infinity, -inf, +inf, -infinity, 8.0] }";
+ TEST_EQ(parser.ParseFlexBuffer(jsontest, nullptr, &slb), true);
+ auto jroot = flexbuffers::GetRoot(slb.GetBuffer());
+ TEST_EQ(flexbuffers::VerifyBuffer(slb.GetBuffer().data(),
+ slb.GetBuffer().size(), nullptr),
+ true);
+ auto jmap = jroot.AsMap();
+ auto jvec = jmap["a"].AsVector();
+ TEST_EQ(8, jvec.size());
+ TEST_EQ(1.0, jvec[0].AsDouble());
+ TEST_ASSERT(is_quiet_nan(jvec[1].AsDouble()));
+ TEST_EQ(infinity_d, jvec[2].AsDouble());
+ TEST_EQ(infinity_d, jvec[3].AsDouble());
+ TEST_EQ(-infinity_d, jvec[4].AsDouble());
+ TEST_EQ(+infinity_d, jvec[5].AsDouble());
+ TEST_EQ(-infinity_d, jvec[6].AsDouble());
+ TEST_EQ(8.0, jvec[7].AsDouble());
+#endif
+}
+
void FlexBuffersDeprecatedTest() {
// FlexBuffers as originally designed had a flaw involving the
// FBT_VECTOR_STRING datatype, and this test documents/tests the fix for it.
@@ -3009,6 +3292,10 @@
// same way, the fix lies on the reading side.
slb.EndVector(start, true, false);
slb.Finish();
+ // Verify because why not.
+ TEST_EQ(flexbuffers::VerifyBuffer(slb.GetBuffer().data(),
+ slb.GetBuffer().size(), nullptr),
+ true);
// So now lets read this data back.
// For existing data, since we have no way of knowing what the actual
// bit-width of the size field of the string is, we are going to ignore this
@@ -3140,6 +3427,31 @@
TEST_EQ(b == a, true);
TEST_EQ(b != a, false);
+ a.enemy.reset(new MonsterT());
+ TEST_EQ(b != a, true);
+ a.enemy->mana = 33;
+ TEST_EQ(b == a, false);
+ TEST_EQ(b != a, true);
+
+ b.enemy.reset(new MonsterT());
+ TEST_EQ(b == a, false);
+ TEST_EQ(b != a, true);
+ b.enemy->mana = 33;
+ TEST_EQ(b == a, true);
+ TEST_EQ(b != a, false);
+
+ a.enemy.reset(nullptr);
+ TEST_EQ(b == a, false);
+ TEST_EQ(b != a, true);
+ b.enemy->mana = 150;
+ TEST_EQ(b == a, false);
+ TEST_EQ(b != a, true);
+ a.enemy.reset(new MonsterT());
+ TEST_EQ(b == a, true);
+ TEST_EQ(b != a, false);
+
+ b.enemy.reset(nullptr);
+
b.test.type = Any_Monster;
TEST_EQ(b == a, false);
TEST_EQ(b != a, true);
@@ -3177,11 +3489,11 @@
TEST_EQ(null_b1.o, null_b2.o);
// Put the strings into an array for round trip verification.
- const flatbuffers::Offset<flatbuffers::String> array[7] = {
+ std::array<flatbuffers::Offset<flatbuffers::String>, 7> array = {
one1, two, one2, onetwo, null_b1, null_c, null_b2
};
const auto vector_offset =
- builder.CreateVector(array, flatbuffers::uoffset_t(7));
+ builder.CreateVector<flatbuffers::Offset<flatbuffers::String>>(array);
MonsterBuilder monster_builder(builder);
monster_builder.add_name(two);
monster_builder.add_testarrayofstring(vector_offset);
@@ -3297,9 +3609,9 @@
void FlatbuffersSpanTest() {}
#endif
-void FixedLengthArrayTest() {
- // VS10 does not support typed enums, exclude from tests
+// VS10 does not support typed enums, exclude from tests
#if !defined(_MSC_VER) || _MSC_VER >= 1700
+void FixedLengthArrayTest() {
// Generate an ArrayTable containing one ArrayStruct.
flatbuffers::FlatBufferBuilder fbb;
MyGame::Example::NestedStruct nStruct0(MyGame::Example::TestEnum::B);
@@ -3333,10 +3645,10 @@
aStruct.mutable_d()->Mutate(1, nStruct1);
auto aTable = MyGame::Example::CreateArrayTable(fbb, &aStruct);
MyGame::Example::FinishArrayTableBuffer(fbb, aTable);
-
// Verify correctness of the ArrayTable.
flatbuffers::Verifier verifier(fbb.GetBufferPointer(), fbb.GetSize());
- MyGame::Example::VerifyArrayTableBuffer(verifier);
+ TEST_ASSERT(MyGame::Example::VerifyArrayTableBuffer(verifier));
+ // Do test.
auto p = MyGame::Example::GetMutableArrayTable(fbb.GetBufferPointer());
auto mArStruct = p->mutable_a();
TEST_NOTNULL(mArStruct);
@@ -3346,10 +3658,10 @@
TEST_NOTNULL(mArStruct->mutable_b());
TEST_NOTNULL(mArStruct->mutable_d());
TEST_NOTNULL(mArStruct->mutable_f());
- mArStruct->mutable_b()->Mutate(14, -14);
TEST_EQ(mArStruct->a(), 2);
TEST_EQ(mArStruct->b()->size(), 15);
- TEST_EQ(mArStruct->b()->Get(aStruct.b()->size() - 1), -14);
+ mArStruct->mutable_b()->Mutate(14, -14);
+ TEST_EQ(mArStruct->b()->Get(14), -14);
TEST_EQ(mArStruct->c(), 12);
TEST_NOTNULL(mArStruct->d()->Get(0));
TEST_NOTNULL(mArStruct->d()->Get(0)->a());
@@ -3391,21 +3703,23 @@
// set memory chunk of size ArrayStruct to 1's
std::memset(static_cast<void *>(non_zero_memory), 1, arr_size);
// after placement-new it should be all 0's
-#if defined (_MSC_VER) && defined (_DEBUG)
- #undef new
-#endif
- MyGame::Example::ArrayStruct *ap = new (non_zero_memory) MyGame::Example::ArrayStruct;
-#if defined (_MSC_VER) && defined (_DEBUG)
- #define new DEBUG_NEW
-#endif
+# if defined(_MSC_VER) && defined(_DEBUG)
+# undef new
+# endif
+ MyGame::Example::ArrayStruct *ap =
+ new (non_zero_memory) MyGame::Example::ArrayStruct;
+# if defined(_MSC_VER) && defined(_DEBUG)
+# define new DEBUG_NEW
+# endif
(void)ap;
- for (size_t i = 0; i < arr_size; ++i) {
- TEST_EQ(non_zero_memory[i], 0);
- }
-#endif
+ for (size_t i = 0; i < arr_size; ++i) { TEST_EQ(non_zero_memory[i], 0); }
}
+#else
+void FixedLengthArrayTest() {}
+#endif // !defined(_MSC_VER) || _MSC_VER >= 1700
-#if !defined(FLATBUFFERS_SPAN_MINIMAL) && (!defined(_MSC_VER) || _MSC_VER >= 1700)
+#if !defined(FLATBUFFERS_SPAN_MINIMAL) && \
+ (!defined(_MSC_VER) || _MSC_VER >= 1700)
void FixedLengthArrayConstructorTest() {
const int32_t nested_a[2] = { 1, 2 };
MyGame::Example::TestEnum nested_c[2] = { MyGame::Example::TestEnum::A,
@@ -3452,8 +3766,7 @@
TEST_EQ(arr_struct.f()->Get(1), -1);
}
#else
-void FixedLengthArrayConstructorTest() {
-}
+void FixedLengthArrayConstructorTest() {}
#endif
void NativeTypeTest() {
@@ -3461,10 +3774,13 @@
Geometry::ApplicationDataT src_data;
src_data.vectors.reserve(N);
+ src_data.vectors_alt.reserve(N);
for (int i = 0; i < N; ++i) {
src_data.vectors.push_back(
Native::Vector3D(10 * i + 0.1f, 10 * i + 0.2f, 10 * i + 0.3f));
+ src_data.vectors_alt.push_back(
+ Native::Vector3D(20 * i + 0.1f, 20 * i + 0.2f, 20 * i + 0.3f));
}
flatbuffers::FlatBufferBuilder fbb;
@@ -3473,16 +3789,21 @@
auto dstDataT = Geometry::UnPackApplicationData(fbb.GetBufferPointer());
for (int i = 0; i < N; ++i) {
- Native::Vector3D &v = dstDataT->vectors[i];
+ const Native::Vector3D &v = dstDataT->vectors[i];
TEST_EQ(v.x, 10 * i + 0.1f);
TEST_EQ(v.y, 10 * i + 0.2f);
TEST_EQ(v.z, 10 * i + 0.3f);
+
+ const Native::Vector3D &v2 = dstDataT->vectors_alt[i];
+ TEST_EQ(v2.x, 20 * i + 0.1f);
+ TEST_EQ(v2.y, 20 * i + 0.2f);
+ TEST_EQ(v2.z, 20 * i + 0.3f);
}
}
-void FixedLengthArrayJsonTest(bool binary) {
- // VS10 does not support typed enums, exclude from tests
+// VS10 does not support typed enums, exclude from tests
#if !defined(_MSC_VER) || _MSC_VER >= 1700
+void FixedLengthArrayJsonTest(bool binary) {
// load FlatBuffer schema (.fbs) and JSON from disk
std::string schemafile;
std::string jsonfile;
@@ -3539,11 +3860,86 @@
parserGen.builder_.GetBufferPointer(),
parserOrg.builder_.GetSize()),
0);
-#else
- (void)binary;
-#endif
}
+void FixedLengthArraySpanTest() {
+ // load FlatBuffer schema (.fbs) and JSON from disk
+ std::string schemafile;
+ std::string jsonfile;
+ TEST_EQ(flatbuffers::LoadFile((test_data_path + "arrays_test.fbs").c_str(),
+ false, &schemafile),
+ true);
+ TEST_EQ(flatbuffers::LoadFile((test_data_path + "arrays_test.golden").c_str(),
+ false, &jsonfile),
+ true);
+
+ // parse schema first, so we can use it to parse the data after
+ flatbuffers::Parser parser;
+ TEST_EQ(parser.Parse(schemafile.c_str()), true);
+ TEST_EQ(parser.Parse(jsonfile.c_str()), true);
+ auto &fbb = parser.builder_;
+ auto verifier = flatbuffers::Verifier(fbb.GetBufferPointer(), fbb.GetSize());
+ TEST_EQ(true, VerifyArrayTableBuffer(verifier));
+
+ auto p = MyGame::Example::GetMutableArrayTable(fbb.GetBufferPointer());
+ TEST_NOTNULL(p);
+ auto table_struct = p->mutable_a();
+ TEST_NOTNULL(table_struct);
+ TEST_EQ(2, table_struct->d()->size());
+ TEST_NOTNULL(table_struct->d());
+ TEST_NOTNULL(table_struct->mutable_d());
+ // test array of structs
+ auto const_d = flatbuffers::make_span(*table_struct->d());
+ auto mutable_d = flatbuffers::make_span(*table_struct->mutable_d());
+ TEST_EQ(2, const_d.size());
+ TEST_EQ(2, mutable_d.size());
+ TEST_ASSERT(const_d[0] == mutable_d[0]);
+ TEST_ASSERT(const_d[1] == mutable_d[1]);
+ mutable_d[0] = const_d[0]; // mutate
+ // test scalars
+ auto &const_nested = const_d[0];
+ auto &mutable_nested = mutable_d[0];
+ static_assert(sizeof(MyGame::Example::TestEnum) == sizeof(uint8_t),
+ "TestEnum's underlaying type must by byte");
+ TEST_NOTNULL(const_nested.d());
+ TEST_NOTNULL(mutable_nested.d());
+ {
+ flatbuffers::span<const MyGame::Example::TestEnum, 2> const_d_c =
+ flatbuffers::make_span(*const_nested.c());
+ auto mutable_d_c = flatbuffers::make_span(*mutable_nested.mutable_c());
+ TEST_EQ(2, const_d_c.size());
+ TEST_EQ(2, mutable_d_c.size());
+ TEST_EQ(MyGame::Example::TestEnum::C, const_d_c[0]);
+ TEST_EQ(MyGame::Example::TestEnum::B, const_d_c[1]);
+ TEST_ASSERT(mutable_d_c.end() == std::copy(const_d_c.cbegin(),
+ const_d_c.cend(),
+ mutable_d_c.begin()));
+ TEST_ASSERT(
+ std::equal(const_d_c.cbegin(), const_d_c.cend(), mutable_d_c.cbegin()));
+ }
+ // test little endian array of int32
+# if FLATBUFFERS_LITTLEENDIAN
+ {
+ flatbuffers::span<const int32_t, 2> const_d_a =
+ flatbuffers::make_span(*const_nested.a());
+ auto mutable_d_a = flatbuffers::make_span(*mutable_nested.mutable_a());
+ TEST_EQ(2, const_d_a.size());
+ TEST_EQ(2, mutable_d_a.size());
+ TEST_EQ(-1, const_d_a[0]);
+ TEST_EQ(2, const_d_a[1]);
+ TEST_ASSERT(mutable_d_a.end() == std::copy(const_d_a.cbegin(),
+ const_d_a.cend(),
+ mutable_d_a.begin()));
+ TEST_ASSERT(
+ std::equal(const_d_a.cbegin(), const_d_a.cend(), mutable_d_a.cbegin()));
+ }
+# endif
+}
+#else
+void FixedLengthArrayJsonTest(bool /*binary*/) {}
+void FixedLengthArraySpanTest() {}
+#endif
+
void TestEmbeddedBinarySchema() {
// load JSON from disk
std::string jsonfile;
@@ -3592,6 +3988,24 @@
0);
}
+void StringVectorDefaultsTest() {
+ std::vector<std::string> schemas;
+ schemas.push_back("table Monster { mana: string = \"\"; }");
+ schemas.push_back("table Monster { mana: string = \"mystr\"; }");
+ schemas.push_back("table Monster { mana: string = \" \"; }");
+ schemas.push_back("table Monster { mana: string = \"null\"; }");
+ schemas.push_back("table Monster { mana: [int] = []; }");
+ schemas.push_back("table Monster { mana: [uint] = [ ]; }");
+ schemas.push_back("table Monster { mana: [byte] = [\t\t\n]; }");
+ schemas.push_back("enum E:int{}table Monster{mana:[E]=[];}");
+ for (auto s = schemas.begin(); s < schemas.end(); s++) {
+ flatbuffers::Parser parser;
+ TEST_ASSERT(parser.Parse(s->c_str()));
+ const auto *mana = parser.structs_.Lookup("Monster")->fields.Lookup("mana");
+ TEST_EQ(mana->IsDefault(), true);
+ }
+}
+
void OptionalScalarsTest() {
// Simple schemas and a "has optional scalar" sentinal.
std::vector<std::string> schemas;
@@ -3610,12 +4024,15 @@
schemas.push_back("table Monster { mana : bool; }");
schemas.push_back("table Monster { mana : bool = 42; }");
schemas.push_back("table Monster { mana : bool = null; }");
- schemas.push_back("enum Enum: int {A=0, B=1} "
- "table Monster { mana : Enum; }");
- schemas.push_back("enum Enum: int {A=0, B=1} "
- "table Monster { mana : Enum = B; }");
- schemas.push_back("enum Enum: int {A=0, B=1} "
- "table Monster { mana : Enum = null; }");
+ schemas.push_back(
+ "enum Enum: int {A=0, B=1} "
+ "table Monster { mana : Enum; }");
+ schemas.push_back(
+ "enum Enum: int {A=0, B=1} "
+ "table Monster { mana : Enum = B; }");
+ schemas.push_back(
+ "enum Enum: int {A=0, B=1} "
+ "table Monster { mana : Enum = null; }");
// Check the FieldDef is correctly set.
for (auto schema = schemas.begin(); schema < schemas.end(); schema++) {
@@ -3623,7 +4040,7 @@
flatbuffers::Parser parser;
TEST_ASSERT(parser.Parse(schema->c_str()));
const auto *mana = parser.structs_.Lookup("Monster")->fields.Lookup("mana");
- TEST_EQ(mana->optional, has_null);
+ TEST_EQ(mana->IsOptional(), has_null);
}
// Test if nullable scalars are allowed for each language.
@@ -3710,6 +4127,115 @@
}
}
+void FieldIdentifierTest() {
+ using flatbuffers::Parser;
+ TEST_EQ(true, Parser().Parse("table T{ f: int (id:0); }"));
+ // non-integer `id` should be rejected
+ TEST_EQ(false, Parser().Parse("table T{ f: int (id:text); }"));
+ TEST_EQ(false, Parser().Parse("table T{ f: int (id:\"text\"); }"));
+ TEST_EQ(false, Parser().Parse("table T{ f: int (id:0text); }"));
+ TEST_EQ(false, Parser().Parse("table T{ f: int (id:1.0); }"));
+ TEST_EQ(false, Parser().Parse("table T{ f: int (id:-1); g: int (id:0); }"));
+ TEST_EQ(false, Parser().Parse("table T{ f: int (id:129496726); }"));
+ // A unuion filed occupys two ids: enumerator + pointer (offset).
+ TEST_EQ(false,
+ Parser().Parse("union X{} table T{ u: X(id:0); table F{x:int;\n}"));
+ // Positive tests for unions
+ TEST_EQ(true, Parser().Parse("union X{} table T{ u: X (id:1); }"));
+ TEST_EQ(true, Parser().Parse("union X{} table T{ u: X; }"));
+ // Test using 'inf' and 'nan' words both as identifiers and as default values.
+ TEST_EQ(true, Parser().Parse("table T{ nan: string; }"));
+ TEST_EQ(true, Parser().Parse("table T{ inf: string; }"));
+#if defined(FLATBUFFERS_HAS_NEW_STRTOD) && (FLATBUFFERS_HAS_NEW_STRTOD > 0)
+ TEST_EQ(true, Parser().Parse("table T{ inf: float = inf; }"));
+ TEST_EQ(true, Parser().Parse("table T{ nan: float = inf; }"));
+#endif
+}
+
+void ParseIncorrectMonsterJsonTest() {
+ std::string schemafile;
+ TEST_EQ(flatbuffers::LoadFile((test_data_path + "monster_test.bfbs").c_str(),
+ true, &schemafile),
+ true);
+ flatbuffers::Parser parser;
+ flatbuffers::Verifier verifier(
+ reinterpret_cast<const uint8_t *>(schemafile.c_str()), schemafile.size());
+ TEST_EQ(reflection::VerifySchemaBuffer(verifier), true);
+ TEST_EQ(parser.Deserialize((const uint8_t *)schemafile.c_str(),
+ schemafile.size()),
+ true);
+ TEST_EQ(parser.ParseJson("{name:\"monster\"}"), true);
+ TEST_EQ(parser.ParseJson(""), false);
+ TEST_EQ(parser.ParseJson("{name: 1}"), false);
+ TEST_EQ(parser.ParseJson("{name:+1}"), false);
+ TEST_EQ(parser.ParseJson("{name:-1}"), false);
+ TEST_EQ(parser.ParseJson("{name:-f}"), false);
+ TEST_EQ(parser.ParseJson("{name:+f}"), false);
+}
+
+#if !defined(_MSC_VER) || _MSC_VER >= 1700
+template<class T, class Container>
+void TestIterators(const std::vector<T> &expected, const Container &tested) {
+ TEST_ASSERT(tested.rbegin().base() == tested.end());
+ TEST_ASSERT(tested.crbegin().base() == tested.cend());
+ TEST_ASSERT(tested.rend().base() == tested.begin());
+ TEST_ASSERT(tested.crend().base() == tested.cbegin());
+
+ size_t k = 0;
+ for (auto it = tested.begin(); it != tested.end(); ++it, ++k) {
+ const auto &e = expected.at(k);
+ TEST_EQ(*it, e);
+ }
+ TEST_EQ(k, expected.size());
+
+ k = expected.size();
+ for (auto it = tested.rbegin(); it != tested.rend(); ++it, --k) {
+ const auto &e = expected.at(k - 1);
+ TEST_EQ(*it, e);
+ }
+ TEST_EQ(k, 0);
+}
+
+void FlatbuffersIteratorsTest() {
+ {
+ flatbuffers::FlatBufferBuilder fbb;
+ const std::vector<unsigned char> inv_data = { 1, 2, 3 };
+ {
+ auto mon_name = fbb.CreateString("MyMonster"); // key, mandatory
+ auto inv_vec = fbb.CreateVector(inv_data);
+ auto empty_i64_vec =
+ fbb.CreateVector(static_cast<const int64_t *>(nullptr), 0);
+ MonsterBuilder mb(fbb);
+ mb.add_name(mon_name);
+ mb.add_inventory(inv_vec);
+ mb.add_vector_of_longs(empty_i64_vec);
+ FinishMonsterBuffer(fbb, mb.Finish());
+ }
+ const auto &mon = *flatbuffers::GetRoot<Monster>(fbb.GetBufferPointer());
+
+ TEST_EQ_STR("MyMonster", mon.name()->c_str());
+ TEST_ASSERT(mon.inventory());
+ TEST_ASSERT(mon.vector_of_longs());
+ TestIterators(inv_data, *mon.inventory());
+ TestIterators(std::vector<int64_t>(), *mon.vector_of_longs());
+ }
+
+ {
+ flatbuffers::FlatBufferBuilder fbb;
+ MyGame::Example::ArrayStruct aStruct;
+ MyGame::Example::FinishArrayTableBuffer(
+ fbb, MyGame::Example::CreateArrayTable(fbb, &aStruct));
+ const auto &array_table =
+ *flatbuffers::GetRoot<ArrayTable>(fbb.GetBufferPointer());
+ TEST_ASSERT(array_table.a());
+ auto &int_15 = *array_table.a()->b();
+ TestIterators(std::vector<int>(15, 0), int_15);
+ }
+}
+#else
+void FlatbuffersIteratorsTest() {}
+#endif
+
int FlatBufferTests() {
// clang-format off
@@ -3717,11 +4243,7 @@
std::string rawbuf;
auto flatbuf1 = CreateFlatBufferTest(rawbuf);
- #if !defined(FLATBUFFERS_CPP98_STL)
- auto flatbuf = std::move(flatbuf1); // Test move assignment.
- #else
- auto &flatbuf = flatbuf1;
- #endif // !defined(FLATBUFFERS_CPP98_STL)
+ auto flatbuf = std::move(flatbuf1); // Test move assignment.
TriviallyCopyableTest();
@@ -3760,6 +4282,8 @@
#endif
// clang-format on
+ UtilConvertCase();
+
FuzzTest1();
FuzzTest2();
@@ -3779,6 +4303,8 @@
InvalidUTF8Test();
UnknownFieldsTest();
ParseUnionTest();
+ ValidSameNameDifferentNamespaceTest();
+ MultiFileNameClashTest();
InvalidNestedFlatbufferTest();
ConformTest();
ParseProtoBufAsciiTest();
@@ -3802,10 +4328,32 @@
ParseFlexbuffersFromJsonWithNullTest();
FlatbuffersSpanTest();
FixedLengthArrayConstructorTest();
+ FieldIdentifierTest();
+ StringVectorDefaultsTest();
+ ParseIncorrectMonsterJsonTest();
+ FlexBuffersFloatingPointTest();
+ FlatbuffersIteratorsTest();
+ FixedLengthArraySpanTest();
+ StructUnionTest();
+ WarningsAsErrorsTest();
return 0;
}
-int main(int /*argc*/, const char * /*argv*/[]) {
+int main(int argc, const char *argv[]) {
+ for (int argi = 1; argi < argc; argi++) {
+ std::string arg = argv[argi];
+ if (arg == "--test_path") {
+ if (++argi >= argc) {
+ fprintf(stderr, "error: missing path following: %s\n", arg.c_str());
+ exit(1);
+ }
+ test_data_path = argv[argi];
+ } else {
+ fprintf(stderr, "error: Unknown argument: %s\n", arg.c_str());
+ exit(1);
+ }
+ }
+
InitTestEngine();
std::string req_locale;
diff --git a/tests/test_assert.h b/tests/test_assert.h
index 353e3ce..e6140cc 100644
--- a/tests/test_assert.h
+++ b/tests/test_assert.h
@@ -73,7 +73,7 @@
template<typename T> struct underlying_of_scalar<T, true> {
// clang-format off
// There are old compilers without full C++11 support (see stl_emulation.h).
- #if defined(FLATBUFFERS_TEMPLATES_ALIASES) && !defined(FLATBUFFERS_CPP98_STL)
+ #if defined(FLATBUFFERS_TEMPLATES_ALIASES)
using type = typename std::underlying_type<T>::type;
#else
typedef int64_t type;
diff --git a/tests/test_builder.cpp b/tests/test_builder.cpp
index 3a12d79..ae67076 100644
--- a/tests/test_builder.cpp
+++ b/tests/test_builder.cpp
@@ -9,20 +9,13 @@
class TestHeapBuilder : public flatbuffers::FlatBufferBuilder {
private:
- // clang-format off
- #if !defined(FLATBUFFERS_CPP98_STL)
TestHeapBuilder(const TestHeapBuilder &);
TestHeapBuilder &operator=(const TestHeapBuilder &);
- #endif // !defined(FLATBUFFERS_CPP98_STL)
- // clang-format on
public:
TestHeapBuilder()
: flatbuffers::FlatBufferBuilder(2048, new OwnedAllocator(), true) {}
- // clang-format off
- #if !defined(FLATBUFFERS_CPP98_STL)
- // clang-format on
TestHeapBuilder(TestHeapBuilder &&other)
: FlatBufferBuilder(std::move(other)) {}
@@ -30,9 +23,6 @@
FlatBufferBuilder::operator=(std::move(other));
return *this;
}
- // clang-format off
- #endif // !defined(FLATBUFFERS_CPP98_STL)
- // clang-format on
};
// This class simulates flatbuffers::grpc::detail::SliceAllocatorMember
@@ -56,18 +46,12 @@
Swap(other);
}
- // clang-format off
- #if !defined(FLATBUFFERS_CPP98_STL)
- // clang-format on
GrpcLikeMessageBuilder &operator=(GrpcLikeMessageBuilder &&other) {
// Construct temporary and swap idiom
GrpcLikeMessageBuilder temp(std::move(other));
Swap(temp);
return *this;
}
- // clang-format off
- #endif // !defined(FLATBUFFERS_CPP98_STL)
- // clang-format on
void Swap(GrpcLikeMessageBuilder &other) {
// No need to swap member_allocator_ because it's stateless.
@@ -155,4 +139,4 @@
}
// Link-time check using pointer type.
-void CheckTestGeneratedIsValid(const MyGame::Example::Color &) {}
\ No newline at end of file
+void CheckTestGeneratedIsValid(const MyGame::Example::Color &) {}
diff --git a/tests/test_builder.h b/tests/test_builder.h
index 5555e90..75338b0 100644
--- a/tests/test_builder.h
+++ b/tests/test_builder.h
@@ -54,9 +54,6 @@
bool release_n_verify(flatbuffers::grpc::MessageBuilder &mbb,
const std::string &expected_name, Color color);
-// clang-format off
-#if !defined(FLATBUFFERS_CPP98_STL)
-// clang-format on
// Invokes this function when testing the following Builder types
// FlatBufferBuilder, TestHeapBuilder, and GrpcLikeMessageBuilder
template<class Builder>
@@ -64,8 +61,10 @@
auto root_offset1 = populate1(b1);
b1.Finish(root_offset1);
size_t size, offset;
+
+ uint8_t *rr = b1.ReleaseRaw(size, offset);
std::shared_ptr<uint8_t> raw(
- b1.ReleaseRaw(size, offset), [size](uint8_t *ptr) {
+ rr, [size](uint8_t *ptr) {
flatbuffers::DefaultAllocator::dealloc(ptr, size);
});
Builder src;
@@ -78,18 +77,12 @@
TEST_ASSERT_FUNC(release_n_verify(b1, m2_name(), m2_color()));
TEST_EQ_FUNC(src.GetSize(), 0);
}
-// clang-format off
-#endif // !defined(FLATBUFFERS_CPP98_STL)
-// clang-format on
void builder_move_assign_after_releaseraw_test(
flatbuffers::grpc::MessageBuilder b1);
template<class DestBuilder, class SrcBuilder = DestBuilder>
struct BuilderTests {
- // clang-format off
- #if !defined(FLATBUFFERS_CPP98_STL)
- // clang-format on
static void empty_builder_movector_test() {
SrcBuilder src;
size_t src_size = src.GetSize();
@@ -171,9 +164,6 @@
TEST_ASSERT_FUNC(release_n_verify(dst, m2_name(), m2_color()));
TEST_EQ_FUNC(src.GetSize(), 0);
}
- // clang-format off
- #endif // !defined(FLATBUFFERS_CPP98_STL)
- // clang-format on
static void builder_swap_before_finish_test(
bool run = is_same<DestBuilder, SrcBuilder>::value) {
@@ -216,9 +206,6 @@
}
static void all_tests() {
- // clang-format off
- #if !defined(FLATBUFFERS_CPP98_STL)
- // clang-format on
empty_builder_movector_test();
nonempty_builder_movector_test();
builder_movector_before_finish_test();
@@ -227,9 +214,6 @@
builder_move_assign_after_finish_test();
builder_move_assign_after_release_test();
builder_move_assign_after_releaseraw_test(DestBuilder());
- // clang-format off
- #endif // !defined(FLATBUFFERS_CPP98_STL)
- // clang-format on
builder_swap_before_finish_test();
builder_swap_after_finish_test();
}
@@ -274,9 +258,6 @@
}
}
- // clang-format off
- #if !defined(FLATBUFFERS_CPP98_STL)
- // clang-format on
static void builder_reusable_after_release_and_move_assign_test(
TestSelector selector) {
if (!selector.count(REUSABLE_AFTER_RELEASE_AND_MOVE_ASSIGN)) { return; }
@@ -311,21 +292,12 @@
TEST_EQ_FUNC(src.GetSize(), 0);
}
}
- // clang-format off
- #endif // !defined(FLATBUFFERS_CPP98_STL)
- // clang-format on
static void run_tests(TestSelector selector) {
builder_reusable_after_release_test(selector);
builder_reusable_after_releaseraw_test(selector);
- // clang-format off
- #if !defined(FLATBUFFERS_CPP98_STL)
- // clang-format on
builder_reusable_after_release_and_move_assign_test(selector);
builder_reusable_after_releaseraw_and_move_assign_test(selector);
- // clang-format off
- #endif // !defined(FLATBUFFERS_CPP98_STL)
- // clang-format on
}
};
diff --git a/tests/test_dir/BUILD.bazel b/tests/test_dir/BUILD.bazel
new file mode 100644
index 0000000..6140d28
--- /dev/null
+++ b/tests/test_dir/BUILD.bazel
@@ -0,0 +1,14 @@
+load("//:build_defs.bzl", "flatbuffer_ts_library")
+
+flatbuffer_ts_library(
+ name = "typescript_transitive_ts_fbs",
+ srcs = ["typescript_transitive_include.fbs"],
+ visibility = ["//visibility:public"],
+)
+
+flatbuffer_ts_library(
+ name = "include_ts_fbs",
+ srcs = ["typescript_include.fbs"],
+ visibility = ["//visibility:public"],
+ deps = [":typescript_transitive_ts_fbs"],
+)
diff --git a/tests/test_dir/typescript_include.fbs b/tests/test_dir/typescript_include.fbs
new file mode 100644
index 0000000..c805693
--- /dev/null
+++ b/tests/test_dir/typescript_include.fbs
@@ -0,0 +1,6 @@
+include 'typescript_transitive_include.fbs';
+namespace foobar;
+
+enum class: int {
+ arguments,
+}
diff --git a/tests/test_dir/typescript_transitive_include.fbs b/tests/test_dir/typescript_transitive_include.fbs
new file mode 100644
index 0000000..80ccb07
--- /dev/null
+++ b/tests/test_dir/typescript_transitive_include.fbs
@@ -0,0 +1,5 @@
+namespace foobar;
+
+enum Abc: int {
+ a,
+}
diff --git a/tests/tsconfig.json b/tests/tsconfig.json
new file mode 100644
index 0000000..27196b3
--- /dev/null
+++ b/tests/tsconfig.json
@@ -0,0 +1,25 @@
+{
+ "compilerOptions": {
+ "target": "ES6",
+ "lib": ["ES2015", "ES2020.BigInt", "DOM"],
+ "moduleResolution": "Node",
+ "noImplicitAny": true,
+ "strict": true,
+ "noUnusedParameters": false,
+ "noUnusedLocals": false,
+ "noImplicitReturns": true,
+ "strictNullChecks": true,
+ "baseUrl": ".",
+ "noEmit": false
+ },
+ "include": [
+ "monster_test.ts",
+ "typescript_keywords.ts",
+ "typescript_keywords_generated.ts",
+ "my-game/**/*.ts",
+ "typescript/**/*.ts",
+ "optional_scalars/**/*.ts",
+ "namespace_test/**/*.ts",
+ "union_vector/**/*.ts"
+ ]
+}
diff --git a/tests/typescript_keywords.fbs b/tests/typescript_keywords.fbs
new file mode 100644
index 0000000..cdb9696
--- /dev/null
+++ b/tests/typescript_keywords.fbs
@@ -0,0 +1,21 @@
+include 'test_dir/typescript_include.fbs';
+include 'reflection/reflection.fbs';
+
+// This file includes a variety of keywords meant to deliberately interfere
+// with typescript keywords.
+namespace typescript;
+
+enum class: int {
+ new,
+ instanceof,
+}
+
+table Object {
+ return:int;
+ if:int;
+ switch:int;
+ enum:class;
+ enum2:foobar.class;
+ enum3:foobar.Abc;
+ reflect:reflection.Schema;
+}
diff --git a/tests/unicode_test.mon b/tests/unicode_test.mon
new file mode 100644
index 0000000..14f5fb4
--- /dev/null
+++ b/tests/unicode_test.mon
Binary files differ
diff --git a/tests/union_vector/Attacker.cs b/tests/union_vector/Attacker.cs
index 870643f..cf6d1a7 100644
--- a/tests/union_vector/Attacker.cs
+++ b/tests/union_vector/Attacker.cs
@@ -10,7 +10,7 @@
{
private Table __p;
public ByteBuffer ByteBuffer { get { return __p.bb; } }
- public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_1_12_0(); }
+ public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_2_0_0(); }
public static Attacker GetRootAsAttacker(ByteBuffer _bb) { return GetRootAsAttacker(_bb, new Attacker()); }
public static Attacker GetRootAsAttacker(ByteBuffer _bb, Attacker obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); }
public void __init(int _i, ByteBuffer _bb) { __p = new Table(_i, _bb); }
@@ -46,7 +46,7 @@
builder,
_o.SwordAttackDamage);
}
-};
+}
public class AttackerT
{
diff --git a/tests/union_vector/Attacker.java b/tests/union_vector/Attacker.java
index 2221944..482a3ae 100644
--- a/tests/union_vector/Attacker.java
+++ b/tests/union_vector/Attacker.java
@@ -7,7 +7,7 @@
@SuppressWarnings("unused")
public final class Attacker extends Table {
- public static void ValidateVersion() { Constants.FLATBUFFERS_1_12_0(); }
+ public static void ValidateVersion() { Constants.FLATBUFFERS_2_0_0(); }
public static Attacker getRootAsAttacker(ByteBuffer _bb) { return getRootAsAttacker(_bb, new Attacker()); }
public static Attacker getRootAsAttacker(ByteBuffer _bb, Attacker obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); }
@@ -17,9 +17,9 @@
public boolean mutateSwordAttackDamage(int sword_attack_damage) { int o = __offset(4); if (o != 0) { bb.putInt(o + bb_pos, sword_attack_damage); return true; } else { return false; } }
public static int createAttacker(FlatBufferBuilder builder,
- int sword_attack_damage) {
+ int swordAttackDamage) {
builder.startTable(1);
- Attacker.addSwordAttackDamage(builder, sword_attack_damage);
+ Attacker.addSwordAttackDamage(builder, swordAttackDamage);
return Attacker.endAttacker(builder);
}
@@ -36,5 +36,20 @@
public Attacker get(int j) { return get(new Attacker(), j); }
public Attacker get(Attacker obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); }
}
+ public AttackerT unpack() {
+ AttackerT _o = new AttackerT();
+ unpackTo(_o);
+ return _o;
+ }
+ public void unpackTo(AttackerT _o) {
+ int _oSwordAttackDamage = swordAttackDamage();
+ _o.setSwordAttackDamage(_oSwordAttackDamage);
+ }
+ public static int pack(FlatBufferBuilder builder, AttackerT _o) {
+ if (_o == null) return 0;
+ return createAttacker(
+ builder,
+ _o.getSwordAttackDamage());
+ }
}
diff --git a/tests/union_vector/Attacker.kt b/tests/union_vector/Attacker.kt
index d398227..9f22e98 100644
--- a/tests/union_vector/Attacker.kt
+++ b/tests/union_vector/Attacker.kt
@@ -5,7 +5,6 @@
import com.google.flatbuffers.*
@Suppress("unused")
-@ExperimentalUnsignedTypes
class Attacker : Table() {
fun __init(_i: Int, _bb: ByteBuffer) {
@@ -30,7 +29,7 @@
}
}
companion object {
- fun validateVersion() = Constants.FLATBUFFERS_1_12_0()
+ fun validateVersion() = Constants.FLATBUFFERS_2_0_0()
fun getRootAsAttacker(_bb: ByteBuffer): Attacker = getRootAsAttacker(_bb, Attacker())
fun getRootAsAttacker(_bb: ByteBuffer, obj: Attacker): Attacker {
_bb.order(ByteOrder.LITTLE_ENDIAN)
diff --git a/tests/union_vector/AttackerT.java b/tests/union_vector/AttackerT.java
new file mode 100644
index 0000000..c5ca2f1
--- /dev/null
+++ b/tests/union_vector/AttackerT.java
@@ -0,0 +1,20 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+import java.nio.*;
+import java.lang.*;
+import java.util.*;
+import com.google.flatbuffers.*;
+
+public class AttackerT {
+ private int swordAttackDamage;
+
+ public int getSwordAttackDamage() { return swordAttackDamage; }
+
+ public void setSwordAttackDamage(int swordAttackDamage) { this.swordAttackDamage = swordAttackDamage; }
+
+
+ public AttackerT() {
+ this.swordAttackDamage = 0;
+ }
+}
+
diff --git a/tests/union_vector/BookReader.cs b/tests/union_vector/BookReader.cs
index 3f80cdf..6cd88b3 100644
--- a/tests/union_vector/BookReader.cs
+++ b/tests/union_vector/BookReader.cs
@@ -35,7 +35,7 @@
builder,
_o.BooksRead);
}
-};
+}
public class BookReaderT
{
diff --git a/tests/union_vector/BookReader.java b/tests/union_vector/BookReader.java
index a6d1b43..e90fadd 100644
--- a/tests/union_vector/BookReader.java
+++ b/tests/union_vector/BookReader.java
@@ -25,5 +25,20 @@
public BookReader get(int j) { return get(new BookReader(), j); }
public BookReader get(BookReader obj, int j) { return obj.__assign(__element(j), bb); }
}
+ public BookReaderT unpack() {
+ BookReaderT _o = new BookReaderT();
+ unpackTo(_o);
+ return _o;
+ }
+ public void unpackTo(BookReaderT _o) {
+ int _oBooksRead = booksRead();
+ _o.setBooksRead(_oBooksRead);
+ }
+ public static int pack(FlatBufferBuilder builder, BookReaderT _o) {
+ if (_o == null) return 0;
+ return createBookReader(
+ builder,
+ _o.getBooksRead());
+ }
}
diff --git a/tests/union_vector/BookReader.kt b/tests/union_vector/BookReader.kt
index fc41473..558606e 100644
--- a/tests/union_vector/BookReader.kt
+++ b/tests/union_vector/BookReader.kt
@@ -5,7 +5,6 @@
import com.google.flatbuffers.*
@Suppress("unused")
-@ExperimentalUnsignedTypes
class BookReader : Struct() {
fun __init(_i: Int, _bb: ByteBuffer) {
diff --git a/tests/union_vector/BookReaderT.java b/tests/union_vector/BookReaderT.java
new file mode 100644
index 0000000..6a5d026
--- /dev/null
+++ b/tests/union_vector/BookReaderT.java
@@ -0,0 +1,20 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+import java.nio.*;
+import java.lang.*;
+import java.util.*;
+import com.google.flatbuffers.*;
+
+public class BookReaderT {
+ private int booksRead;
+
+ public int getBooksRead() { return booksRead; }
+
+ public void setBooksRead(int booksRead) { this.booksRead = booksRead; }
+
+
+ public BookReaderT() {
+ this.booksRead = 0;
+ }
+}
+
diff --git a/tests/union_vector/Character.cs b/tests/union_vector/Character.cs
index d067e22..4978bdc 100644
--- a/tests/union_vector/Character.cs
+++ b/tests/union_vector/Character.cs
@@ -25,11 +25,17 @@
public T As<T>() where T : class { return this.Value as T; }
public AttackerT AsMuLan() { return this.As<AttackerT>(); }
+ public static CharacterUnion FromMuLan(AttackerT _mulan) { return new CharacterUnion{ Type = Character.MuLan, Value = _mulan }; }
public RapunzelT AsRapunzel() { return this.As<RapunzelT>(); }
+ public static CharacterUnion FromRapunzel(RapunzelT _rapunzel) { return new CharacterUnion{ Type = Character.Rapunzel, Value = _rapunzel }; }
public BookReaderT AsBelle() { return this.As<BookReaderT>(); }
+ public static CharacterUnion FromBelle(BookReaderT _belle) { return new CharacterUnion{ Type = Character.Belle, Value = _belle }; }
public BookReaderT AsBookFan() { return this.As<BookReaderT>(); }
+ public static CharacterUnion FromBookFan(BookReaderT _bookfan) { return new CharacterUnion{ Type = Character.BookFan, Value = _bookfan }; }
public string AsOther() { return this.As<string>(); }
+ public static CharacterUnion FromOther(string _other) { return new CharacterUnion{ Type = Character.Other, Value = _other }; }
public string AsUnused() { return this.As<string>(); }
+ public static CharacterUnion FromUnused(string _unused) { return new CharacterUnion{ Type = Character.Unused, Value = _unused }; }
public static int Pack(FlatBuffers.FlatBufferBuilder builder, CharacterUnion _o) {
switch (_o.Type) {
diff --git a/tests/union_vector/Character.java b/tests/union_vector/Character.java
index 5d6c5b7..615958b 100644
--- a/tests/union_vector/Character.java
+++ b/tests/union_vector/Character.java
@@ -1,5 +1,6 @@
// automatically generated by the FlatBuffers compiler, do not modify
+@SuppressWarnings("unused")
public final class Character {
private Character() { }
public static final byte NONE = 0;
diff --git a/tests/union_vector/Character.kt b/tests/union_vector/Character.kt
index ff7dd5e..2e80a35 100644
--- a/tests/union_vector/Character.kt
+++ b/tests/union_vector/Character.kt
@@ -1,7 +1,6 @@
// automatically generated by the FlatBuffers compiler, do not modify
@Suppress("unused")
-@ExperimentalUnsignedTypes
class Character_ private constructor() {
companion object {
const val NONE: UByte = 0u
diff --git a/tests/union_vector/CharacterUnion.java b/tests/union_vector/CharacterUnion.java
new file mode 100644
index 0000000..424218b
--- /dev/null
+++ b/tests/union_vector/CharacterUnion.java
@@ -0,0 +1,41 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+import com.google.flatbuffers.FlatBufferBuilder;
+
+public class CharacterUnion {
+ private byte type;
+ private Object value;
+
+ public byte getType() { return type; }
+
+ public void setType(byte type) { this.type = type; }
+
+ public Object getValue() { return value; }
+
+ public void setValue(Object value) { this.value = value; }
+
+ public CharacterUnion() {
+ this.type = Character.NONE;
+ this.value = null;
+ }
+
+ public AttackerT asMuLan() { return (AttackerT) value; }
+ public RapunzelT asRapunzel() { return (RapunzelT) value; }
+ public BookReaderT asBelle() { return (BookReaderT) value; }
+ public BookReaderT asBookFan() { return (BookReaderT) value; }
+ public String asOther() { return (String) value; }
+ public String asUnused() { return (String) value; }
+
+ public static int pack(FlatBufferBuilder builder, CharacterUnion _o) {
+ switch (_o.type) {
+ case Character.MuLan: return Attacker.pack(builder, _o.asMuLan());
+ case Character.Rapunzel: return Rapunzel.pack(builder, _o.asRapunzel());
+ case Character.Belle: return BookReader.pack(builder, _o.asBelle());
+ case Character.BookFan: return BookReader.pack(builder, _o.asBookFan());
+ case Character.Other: return builder.createString(_o.asOther());
+ case Character.Unused: return builder.createString(_o.asUnused());
+ default: return 0;
+ }
+ }
+}
+
diff --git a/tests/union_vector/FallingTub.cs b/tests/union_vector/FallingTub.cs
new file mode 100644
index 0000000..36c574c
--- /dev/null
+++ b/tests/union_vector/FallingTub.cs
@@ -0,0 +1,49 @@
+// <auto-generated>
+// automatically generated by the FlatBuffers compiler, do not modify
+// </auto-generated>
+
+using global::System;
+using global::System.Collections.Generic;
+using global::FlatBuffers;
+
+public struct FallingTub : IFlatbufferObject
+{
+ private Struct __p;
+ public ByteBuffer ByteBuffer { get { return __p.bb; } }
+ public void __init(int _i, ByteBuffer _bb) { __p = new Struct(_i, _bb); }
+ public FallingTub __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; }
+
+ public int Weight { get { return __p.bb.GetInt(__p.bb_pos + 0); } }
+ public void MutateWeight(int weight) { __p.bb.PutInt(__p.bb_pos + 0, weight); }
+
+ public static Offset<FallingTub> CreateFallingTub(FlatBufferBuilder builder, int Weight) {
+ builder.Prep(4, 4);
+ builder.PutInt(Weight);
+ return new Offset<FallingTub>(builder.Offset);
+ }
+ public FallingTubT UnPack() {
+ var _o = new FallingTubT();
+ this.UnPackTo(_o);
+ return _o;
+ }
+ public void UnPackTo(FallingTubT _o) {
+ _o.Weight = this.Weight;
+ }
+ public static Offset<FallingTub> Pack(FlatBufferBuilder builder, FallingTubT _o) {
+ if (_o == null) return default(Offset<FallingTub>);
+ return CreateFallingTub(
+ builder,
+ _o.Weight);
+ }
+}
+
+public class FallingTubT
+{
+ [Newtonsoft.Json.JsonProperty("weight")]
+ public int Weight { get; set; }
+
+ public FallingTubT() {
+ this.Weight = 0;
+ }
+}
+
diff --git a/tests/union_vector/FallingTub.java b/tests/union_vector/FallingTub.java
new file mode 100644
index 0000000..5c2fae3
--- /dev/null
+++ b/tests/union_vector/FallingTub.java
@@ -0,0 +1,44 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+import java.nio.*;
+import java.lang.*;
+import java.util.*;
+import com.google.flatbuffers.*;
+
+@SuppressWarnings("unused")
+public final class FallingTub extends Struct {
+ public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); }
+ public FallingTub __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; }
+
+ public int weight() { return bb.getInt(bb_pos + 0); }
+ public void mutateWeight(int weight) { bb.putInt(bb_pos + 0, weight); }
+
+ public static int createFallingTub(FlatBufferBuilder builder, int weight) {
+ builder.prep(4, 4);
+ builder.putInt(weight);
+ return builder.offset();
+ }
+
+ public static final class Vector extends BaseVector {
+ public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; }
+
+ public FallingTub get(int j) { return get(new FallingTub(), j); }
+ public FallingTub get(FallingTub obj, int j) { return obj.__assign(__element(j), bb); }
+ }
+ public FallingTubT unpack() {
+ FallingTubT _o = new FallingTubT();
+ unpackTo(_o);
+ return _o;
+ }
+ public void unpackTo(FallingTubT _o) {
+ int _oWeight = weight();
+ _o.setWeight(_oWeight);
+ }
+ public static int pack(FlatBufferBuilder builder, FallingTubT _o) {
+ if (_o == null) return 0;
+ return createFallingTub(
+ builder,
+ _o.getWeight());
+ }
+}
+
diff --git a/tests/union_vector/FallingTub.kt b/tests/union_vector/FallingTub.kt
new file mode 100644
index 0000000..0a823e2
--- /dev/null
+++ b/tests/union_vector/FallingTub.kt
@@ -0,0 +1,26 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+import java.nio.*
+import kotlin.math.sign
+import com.google.flatbuffers.*
+
+@Suppress("unused")
+class FallingTub : Struct() {
+
+ fun __init(_i: Int, _bb: ByteBuffer) {
+ __reset(_i, _bb)
+ }
+ fun __assign(_i: Int, _bb: ByteBuffer) : FallingTub {
+ __init(_i, _bb)
+ return this
+ }
+ val weight : Int get() = bb.getInt(bb_pos + 0)
+ fun mutateWeight(weight: Int) : ByteBuffer = bb.putInt(bb_pos + 0, weight)
+ companion object {
+ fun createFallingTub(builder: FlatBufferBuilder, weight: Int) : Int {
+ builder.prep(4, 4)
+ builder.putInt(weight)
+ return builder.offset()
+ }
+ }
+}
diff --git a/tests/union_vector/FallingTub.php b/tests/union_vector/FallingTub.php
new file mode 100644
index 0000000..3a6800d
--- /dev/null
+++ b/tests/union_vector/FallingTub.php
@@ -0,0 +1,41 @@
+<?php
+// automatically generated by the FlatBuffers compiler, do not modify
+
+use \Google\FlatBuffers\Struct;
+use \Google\FlatBuffers\Table;
+use \Google\FlatBuffers\ByteBuffer;
+use \Google\FlatBuffers\FlatBufferBuilder;
+
+class FallingTub extends Struct
+{
+ /**
+ * @param int $_i offset
+ * @param ByteBuffer $_bb
+ * @return FallingTub
+ **/
+ public function init($_i, ByteBuffer $_bb)
+ {
+ $this->bb_pos = $_i;
+ $this->bb = $_bb;
+ return $this;
+ }
+
+ /**
+ * @return int
+ */
+ public function GetWeight()
+ {
+ return $this->bb->getInt($this->bb_pos + 0);
+ }
+
+
+ /**
+ * @return int offset
+ */
+ public static function createFallingTub(FlatBufferBuilder $builder, $weight)
+ {
+ $builder->prep(4, 4);
+ $builder->putInt($weight);
+ return $builder->offset();
+ }
+}
diff --git a/tests/union_vector/FallingTubT.java b/tests/union_vector/FallingTubT.java
new file mode 100644
index 0000000..0b98699
--- /dev/null
+++ b/tests/union_vector/FallingTubT.java
@@ -0,0 +1,20 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+import java.nio.*;
+import java.lang.*;
+import java.util.*;
+import com.google.flatbuffers.*;
+
+public class FallingTubT {
+ private int weight;
+
+ public int getWeight() { return weight; }
+
+ public void setWeight(int weight) { this.weight = weight; }
+
+
+ public FallingTubT() {
+ this.weight = 0;
+ }
+}
+
diff --git a/tests/union_vector/Gadget.cs b/tests/union_vector/Gadget.cs
new file mode 100644
index 0000000..e4770dd
--- /dev/null
+++ b/tests/union_vector/Gadget.cs
@@ -0,0 +1,78 @@
+// <auto-generated>
+// automatically generated by the FlatBuffers compiler, do not modify
+// </auto-generated>
+
+[Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))]
+public enum Gadget : byte
+{
+ NONE = 0,
+ FallingTub = 1,
+ HandFan = 2,
+};
+
+public class GadgetUnion {
+ public Gadget Type { get; set; }
+ public object Value { get; set; }
+
+ public GadgetUnion() {
+ this.Type = Gadget.NONE;
+ this.Value = null;
+ }
+
+ public T As<T>() where T : class { return this.Value as T; }
+ public FallingTubT AsFallingTub() { return this.As<FallingTubT>(); }
+ public static GadgetUnion FromFallingTub(FallingTubT _fallingtub) { return new GadgetUnion{ Type = Gadget.FallingTub, Value = _fallingtub }; }
+ public HandFanT AsHandFan() { return this.As<HandFanT>(); }
+ public static GadgetUnion FromHandFan(HandFanT _handfan) { return new GadgetUnion{ Type = Gadget.HandFan, Value = _handfan }; }
+
+ public static int Pack(FlatBuffers.FlatBufferBuilder builder, GadgetUnion _o) {
+ switch (_o.Type) {
+ default: return 0;
+ case Gadget.FallingTub: return FallingTub.Pack(builder, _o.AsFallingTub()).Value;
+ case Gadget.HandFan: return HandFan.Pack(builder, _o.AsHandFan()).Value;
+ }
+ }
+}
+
+public class GadgetUnion_JsonConverter : Newtonsoft.Json.JsonConverter {
+ public override bool CanConvert(System.Type objectType) {
+ return objectType == typeof(GadgetUnion) || objectType == typeof(System.Collections.Generic.List<GadgetUnion>);
+ }
+ public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer) {
+ var _olist = value as System.Collections.Generic.List<GadgetUnion>;
+ if (_olist != null) {
+ writer.WriteStartArray();
+ foreach (var _o in _olist) { this.WriteJson(writer, _o, serializer); }
+ writer.WriteEndArray();
+ } else {
+ this.WriteJson(writer, value as GadgetUnion, serializer);
+ }
+ }
+ public void WriteJson(Newtonsoft.Json.JsonWriter writer, GadgetUnion _o, Newtonsoft.Json.JsonSerializer serializer) {
+ if (_o == null) return;
+ serializer.Serialize(writer, _o.Value);
+ }
+ public override object ReadJson(Newtonsoft.Json.JsonReader reader, System.Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer) {
+ var _olist = existingValue as System.Collections.Generic.List<GadgetUnion>;
+ if (_olist != null) {
+ for (var _j = 0; _j < _olist.Count; ++_j) {
+ reader.Read();
+ _olist[_j] = this.ReadJson(reader, _olist[_j], serializer);
+ }
+ reader.Read();
+ return _olist;
+ } else {
+ return this.ReadJson(reader, existingValue as GadgetUnion, serializer);
+ }
+ }
+ public GadgetUnion ReadJson(Newtonsoft.Json.JsonReader reader, GadgetUnion _o, Newtonsoft.Json.JsonSerializer serializer) {
+ if (_o == null) return null;
+ switch (_o.Type) {
+ default: break;
+ case Gadget.FallingTub: _o.Value = serializer.Deserialize<FallingTubT>(reader); break;
+ case Gadget.HandFan: _o.Value = serializer.Deserialize<HandFanT>(reader); break;
+ }
+ return _o;
+ }
+}
+
diff --git a/tests/union_vector/Gadget.java b/tests/union_vector/Gadget.java
new file mode 100644
index 0000000..effc315
--- /dev/null
+++ b/tests/union_vector/Gadget.java
@@ -0,0 +1,14 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+@SuppressWarnings("unused")
+public final class Gadget {
+ private Gadget() { }
+ public static final byte NONE = 0;
+ public static final byte FallingTub = 1;
+ public static final byte HandFan = 2;
+
+ public static final String[] names = { "NONE", "FallingTub", "HandFan", };
+
+ public static String name(int e) { return names[e]; }
+}
+
diff --git a/tests/union_vector/Gadget.kt b/tests/union_vector/Gadget.kt
new file mode 100644
index 0000000..4fb3b10
--- /dev/null
+++ b/tests/union_vector/Gadget.kt
@@ -0,0 +1,12 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+@Suppress("unused")
+class Gadget private constructor() {
+ companion object {
+ const val NONE: UByte = 0u
+ const val FallingTub: UByte = 1u
+ const val HandFan: UByte = 2u
+ val names : Array<String> = arrayOf("NONE", "FallingTub", "HandFan")
+ fun name(e: Int) : String = names[e]
+ }
+}
diff --git a/tests/union_vector/Gadget.php b/tests/union_vector/Gadget.php
new file mode 100644
index 0000000..069f82d
--- /dev/null
+++ b/tests/union_vector/Gadget.php
@@ -0,0 +1,23 @@
+<?php
+// automatically generated by the FlatBuffers compiler, do not modify
+
+class Gadget
+{
+ const NONE = 0;
+ const FallingTub = 1;
+ const HandFan = 2;
+
+ private static $names = array(
+ Gadget::NONE=>"NONE",
+ Gadget::FallingTub=>"FallingTub",
+ Gadget::HandFan=>"HandFan",
+ );
+
+ public static function Name($e)
+ {
+ if (!isset(self::$names[$e])) {
+ throw new \Exception();
+ }
+ return self::$names[$e];
+ }
+}
diff --git a/tests/union_vector/GadgetUnion.java b/tests/union_vector/GadgetUnion.java
new file mode 100644
index 0000000..2ac2745
--- /dev/null
+++ b/tests/union_vector/GadgetUnion.java
@@ -0,0 +1,33 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+import com.google.flatbuffers.FlatBufferBuilder;
+
+public class GadgetUnion {
+ private byte type;
+ private Object value;
+
+ public byte getType() { return type; }
+
+ public void setType(byte type) { this.type = type; }
+
+ public Object getValue() { return value; }
+
+ public void setValue(Object value) { this.value = value; }
+
+ public GadgetUnion() {
+ this.type = Gadget.NONE;
+ this.value = null;
+ }
+
+ public FallingTubT asFallingTub() { return (FallingTubT) value; }
+ public HandFanT asHandFan() { return (HandFanT) value; }
+
+ public static int pack(FlatBufferBuilder builder, GadgetUnion _o) {
+ switch (_o.type) {
+ case Gadget.FallingTub: return FallingTub.pack(builder, _o.asFallingTub());
+ case Gadget.HandFan: return HandFan.pack(builder, _o.asHandFan());
+ default: return 0;
+ }
+ }
+}
+
diff --git a/tests/union_vector/HandFan.cs b/tests/union_vector/HandFan.cs
new file mode 100644
index 0000000..a888abf
--- /dev/null
+++ b/tests/union_vector/HandFan.cs
@@ -0,0 +1,60 @@
+// <auto-generated>
+// automatically generated by the FlatBuffers compiler, do not modify
+// </auto-generated>
+
+using global::System;
+using global::System.Collections.Generic;
+using global::FlatBuffers;
+
+public struct HandFan : IFlatbufferObject
+{
+ private Table __p;
+ public ByteBuffer ByteBuffer { get { return __p.bb; } }
+ public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_2_0_0(); }
+ public static HandFan GetRootAsHandFan(ByteBuffer _bb) { return GetRootAsHandFan(_bb, new HandFan()); }
+ public static HandFan GetRootAsHandFan(ByteBuffer _bb, HandFan obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); }
+ public void __init(int _i, ByteBuffer _bb) { __p = new Table(_i, _bb); }
+ public HandFan __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; }
+
+ public int Length { get { int o = __p.__offset(4); return o != 0 ? __p.bb.GetInt(o + __p.bb_pos) : (int)0; } }
+ public bool MutateLength(int length) { int o = __p.__offset(4); if (o != 0) { __p.bb.PutInt(o + __p.bb_pos, length); return true; } else { return false; } }
+
+ public static Offset<HandFan> CreateHandFan(FlatBufferBuilder builder,
+ int length = 0) {
+ builder.StartTable(1);
+ HandFan.AddLength(builder, length);
+ return HandFan.EndHandFan(builder);
+ }
+
+ public static void StartHandFan(FlatBufferBuilder builder) { builder.StartTable(1); }
+ public static void AddLength(FlatBufferBuilder builder, int length) { builder.AddInt(0, length, 0); }
+ public static Offset<HandFan> EndHandFan(FlatBufferBuilder builder) {
+ int o = builder.EndTable();
+ return new Offset<HandFan>(o);
+ }
+ public HandFanT UnPack() {
+ var _o = new HandFanT();
+ this.UnPackTo(_o);
+ return _o;
+ }
+ public void UnPackTo(HandFanT _o) {
+ _o.Length = this.Length;
+ }
+ public static Offset<HandFan> Pack(FlatBufferBuilder builder, HandFanT _o) {
+ if (_o == null) return default(Offset<HandFan>);
+ return CreateHandFan(
+ builder,
+ _o.Length);
+ }
+}
+
+public class HandFanT
+{
+ [Newtonsoft.Json.JsonProperty("length")]
+ public int Length { get; set; }
+
+ public HandFanT() {
+ this.Length = 0;
+ }
+}
+
diff --git a/tests/union_vector/HandFan.java b/tests/union_vector/HandFan.java
new file mode 100644
index 0000000..14b2520
--- /dev/null
+++ b/tests/union_vector/HandFan.java
@@ -0,0 +1,55 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+import java.nio.*;
+import java.lang.*;
+import java.util.*;
+import com.google.flatbuffers.*;
+
+@SuppressWarnings("unused")
+public final class HandFan extends Table {
+ public static void ValidateVersion() { Constants.FLATBUFFERS_2_0_0(); }
+ public static HandFan getRootAsHandFan(ByteBuffer _bb) { return getRootAsHandFan(_bb, new HandFan()); }
+ public static HandFan getRootAsHandFan(ByteBuffer _bb, HandFan obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
+ public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); }
+ public HandFan __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; }
+
+ public int length() { int o = __offset(4); return o != 0 ? bb.getInt(o + bb_pos) : 0; }
+ public boolean mutateLength(int length) { int o = __offset(4); if (o != 0) { bb.putInt(o + bb_pos, length); return true; } else { return false; } }
+
+ public static int createHandFan(FlatBufferBuilder builder,
+ int length) {
+ builder.startTable(1);
+ HandFan.addLength(builder, length);
+ return HandFan.endHandFan(builder);
+ }
+
+ public static void startHandFan(FlatBufferBuilder builder) { builder.startTable(1); }
+ public static void addLength(FlatBufferBuilder builder, int length) { builder.addInt(0, length, 0); }
+ public static int endHandFan(FlatBufferBuilder builder) {
+ int o = builder.endTable();
+ return o;
+ }
+
+ public static final class Vector extends BaseVector {
+ public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; }
+
+ public HandFan get(int j) { return get(new HandFan(), j); }
+ public HandFan get(HandFan obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); }
+ }
+ public HandFanT unpack() {
+ HandFanT _o = new HandFanT();
+ unpackTo(_o);
+ return _o;
+ }
+ public void unpackTo(HandFanT _o) {
+ int _oLength = length();
+ _o.setLength(_oLength);
+ }
+ public static int pack(FlatBufferBuilder builder, HandFanT _o) {
+ if (_o == null) return 0;
+ return createHandFan(
+ builder,
+ _o.getLength());
+ }
+}
+
diff --git a/tests/union_vector/HandFan.kt b/tests/union_vector/HandFan.kt
new file mode 100644
index 0000000..0a8a055
--- /dev/null
+++ b/tests/union_vector/HandFan.kt
@@ -0,0 +1,50 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+import java.nio.*
+import kotlin.math.sign
+import com.google.flatbuffers.*
+
+@Suppress("unused")
+class HandFan : Table() {
+
+ fun __init(_i: Int, _bb: ByteBuffer) {
+ __reset(_i, _bb)
+ }
+ fun __assign(_i: Int, _bb: ByteBuffer) : HandFan {
+ __init(_i, _bb)
+ return this
+ }
+ val length : Int
+ get() {
+ val o = __offset(4)
+ return if(o != 0) bb.getInt(o + bb_pos) else 0
+ }
+ fun mutateLength(length: Int) : Boolean {
+ val o = __offset(4)
+ return if (o != 0) {
+ bb.putInt(o + bb_pos, length)
+ true
+ } else {
+ false
+ }
+ }
+ companion object {
+ fun validateVersion() = Constants.FLATBUFFERS_2_0_0()
+ fun getRootAsHandFan(_bb: ByteBuffer): HandFan = getRootAsHandFan(_bb, HandFan())
+ fun getRootAsHandFan(_bb: ByteBuffer, obj: HandFan): HandFan {
+ _bb.order(ByteOrder.LITTLE_ENDIAN)
+ return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb))
+ }
+ fun createHandFan(builder: FlatBufferBuilder, length: Int) : Int {
+ builder.startTable(1)
+ addLength(builder, length)
+ return endHandFan(builder)
+ }
+ fun startHandFan(builder: FlatBufferBuilder) = builder.startTable(1)
+ fun addLength(builder: FlatBufferBuilder, length: Int) = builder.addInt(0, length, 0)
+ fun endHandFan(builder: FlatBufferBuilder) : Int {
+ val o = builder.endTable()
+ return o
+ }
+ }
+}
diff --git a/tests/union_vector/HandFan.php b/tests/union_vector/HandFan.php
new file mode 100644
index 0000000..673e336
--- /dev/null
+++ b/tests/union_vector/HandFan.php
@@ -0,0 +1,92 @@
+<?php
+// automatically generated by the FlatBuffers compiler, do not modify
+
+use \Google\FlatBuffers\Struct;
+use \Google\FlatBuffers\Table;
+use \Google\FlatBuffers\ByteBuffer;
+use \Google\FlatBuffers\FlatBufferBuilder;
+
+class HandFan extends Table
+{
+ /**
+ * @param ByteBuffer $bb
+ * @return HandFan
+ */
+ public static function getRootAsHandFan(ByteBuffer $bb)
+ {
+ $obj = new HandFan();
+ return ($obj->init($bb->getInt($bb->getPosition()) + $bb->getPosition(), $bb));
+ }
+
+ public static function HandFanIdentifier()
+ {
+ return "MOVI";
+ }
+
+ public static function HandFanBufferHasIdentifier(ByteBuffer $buf)
+ {
+ return self::__has_identifier($buf, self::HandFanIdentifier());
+ }
+
+ /**
+ * @param int $_i offset
+ * @param ByteBuffer $_bb
+ * @return HandFan
+ **/
+ public function init($_i, ByteBuffer $_bb)
+ {
+ $this->bb_pos = $_i;
+ $this->bb = $_bb;
+ return $this;
+ }
+
+ /**
+ * @return int
+ */
+ public function getLength()
+ {
+ $o = $this->__offset(4);
+ return $o != 0 ? $this->bb->getInt($o + $this->bb_pos) : 0;
+ }
+
+ /**
+ * @param FlatBufferBuilder $builder
+ * @return void
+ */
+ public static function startHandFan(FlatBufferBuilder $builder)
+ {
+ $builder->StartObject(1);
+ }
+
+ /**
+ * @param FlatBufferBuilder $builder
+ * @return HandFan
+ */
+ public static function createHandFan(FlatBufferBuilder $builder, $length)
+ {
+ $builder->startObject(1);
+ self::addLength($builder, $length);
+ $o = $builder->endObject();
+ return $o;
+ }
+
+ /**
+ * @param FlatBufferBuilder $builder
+ * @param int
+ * @return void
+ */
+ public static function addLength(FlatBufferBuilder $builder, $length)
+ {
+ $builder->addIntX(0, $length, 0);
+ }
+
+ /**
+ * @param FlatBufferBuilder $builder
+ * @return int table offset
+ */
+ public static function endHandFan(FlatBufferBuilder $builder)
+ {
+ $o = $builder->endObject();
+ return $o;
+ }
+}
diff --git a/tests/union_vector/HandFanT.java b/tests/union_vector/HandFanT.java
new file mode 100644
index 0000000..d3b202b
--- /dev/null
+++ b/tests/union_vector/HandFanT.java
@@ -0,0 +1,20 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+import java.nio.*;
+import java.lang.*;
+import java.util.*;
+import com.google.flatbuffers.*;
+
+public class HandFanT {
+ private int length;
+
+ public int getLength() { return length; }
+
+ public void setLength(int length) { this.length = length; }
+
+
+ public HandFanT() {
+ this.length = 0;
+ }
+}
+
diff --git a/tests/union_vector/Movie.cs b/tests/union_vector/Movie.cs
index dfbdd8d..f85daa6 100644
--- a/tests/union_vector/Movie.cs
+++ b/tests/union_vector/Movie.cs
@@ -10,7 +10,7 @@
{
private Table __p;
public ByteBuffer ByteBuffer { get { return __p.bb; } }
- public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_1_12_0(); }
+ public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_2_0_0(); }
public static Movie GetRootAsMovie(ByteBuffer _bb) { return GetRootAsMovie(_bb, new Movie()); }
public static Movie GetRootAsMovie(ByteBuffer _bb, Movie obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); }
public static bool MovieBufferHasIdentifier(ByteBuffer _bb) { return Table.__has_identifier(_bb, "MOVI"); }
@@ -148,7 +148,7 @@
_characters_type,
_characters);
}
-};
+}
public class MovieT
{
diff --git a/tests/union_vector/Movie.java b/tests/union_vector/Movie.java
index d8a97bf..dc40d80 100644
--- a/tests/union_vector/Movie.java
+++ b/tests/union_vector/Movie.java
@@ -7,7 +7,7 @@
@SuppressWarnings("unused")
public final class Movie extends Table {
- public static void ValidateVersion() { Constants.FLATBUFFERS_1_12_0(); }
+ public static void ValidateVersion() { Constants.FLATBUFFERS_2_0_0(); }
public static Movie getRootAsMovie(ByteBuffer _bb) { return getRootAsMovie(_bb, new Movie()); }
public static Movie getRootAsMovie(ByteBuffer _bb, Movie obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
public static boolean MovieBufferHasIdentifier(ByteBuffer _bb) { return __has_identifier(_bb, "MOVI"); }
@@ -28,15 +28,15 @@
public UnionVector charactersVector(UnionVector obj) { int o = __offset(10); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; }
public static int createMovie(FlatBufferBuilder builder,
- byte main_character_type,
- int main_characterOffset,
- int characters_typeOffset,
+ byte mainCharacterType,
+ int mainCharacterOffset,
+ int charactersTypeOffset,
int charactersOffset) {
builder.startTable(4);
Movie.addCharacters(builder, charactersOffset);
- Movie.addCharactersType(builder, characters_typeOffset);
- Movie.addMainCharacter(builder, main_characterOffset);
- Movie.addMainCharacterType(builder, main_character_type);
+ Movie.addCharactersType(builder, charactersTypeOffset);
+ Movie.addMainCharacter(builder, mainCharacterOffset);
+ Movie.addMainCharacterType(builder, mainCharacterType);
return Movie.endMovie(builder);
}
@@ -62,5 +62,65 @@
public Movie get(int j) { return get(new Movie(), j); }
public Movie get(Movie obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); }
}
+ public MovieT unpack() {
+ MovieT _o = new MovieT();
+ unpackTo(_o);
+ return _o;
+ }
+ public void unpackTo(MovieT _o) {
+ CharacterUnion _oMainCharacter = new CharacterUnion();
+ byte _oMainCharacterType = mainCharacterType();
+ _oMainCharacter.setType(_oMainCharacterType);
+ Table _oMainCharacterValue;
+ switch (_oMainCharacterType) {
+ case Character.MuLan:
+ _oMainCharacterValue = mainCharacter(new Attacker());
+ _oMainCharacter.setValue(_oMainCharacterValue != null ? ((Attacker) _oMainCharacterValue).unpack() : null);
+ break;
+ default: break;
+ }
+ _o.setMainCharacter(_oMainCharacter);
+ CharacterUnion[] _oCharacters = new CharacterUnion[charactersLength()];
+ for (int _j = 0; _j < charactersLength(); ++_j) {
+ CharacterUnion _oCharactersElement = new CharacterUnion();
+ byte _oCharactersElementType = charactersType(_j);
+ _oCharactersElement.setType(_oCharactersElementType);
+ Table _oCharactersElementValue;
+ switch (_oCharactersElementType) {
+ case Character.MuLan:
+ _oCharactersElementValue = characters(new Attacker(), _j);
+ _oCharactersElement.setValue(_oCharactersElementValue != null ? ((Attacker) _oCharactersElementValue).unpack() : null);
+ break;
+ default: break;
+ }
+ _oCharacters[_j] = _oCharactersElement;
+ }
+ _o.setCharacters(_oCharacters);
+ }
+ public static int pack(FlatBufferBuilder builder, MovieT _o) {
+ if (_o == null) return 0;
+ byte _mainCharacterType = _o.getMainCharacter() == null ? Character.NONE : _o.getMainCharacter().getType();
+ int _mainCharacter = _o.getMainCharacter() == null ? 0 : CharacterUnion.pack(builder, _o.getMainCharacter());
+ int _charactersType = 0;
+ if (_o.getCharacters() != null) {
+ byte[] __charactersType = new byte[_o.getCharacters().length];
+ int _j = 0;
+ for (CharacterUnion _e : _o.getCharacters()) { __charactersType[_j] = _o.getCharacters()[_j].getType(); _j++;}
+ _charactersType = createCharactersTypeVector(builder, __charactersType);
+ }
+ int _characters = 0;
+ if (_o.getCharacters() != null) {
+ int[] __characters = new int[_o.getCharacters().length];
+ int _j = 0;
+ for (CharacterUnion _e : _o.getCharacters()) { __characters[_j] = CharacterUnion.pack(builder, _o.getCharacters()[_j]); _j++;}
+ _characters = createCharactersVector(builder, __characters);
+ }
+ return createMovie(
+ builder,
+ _mainCharacterType,
+ _mainCharacter,
+ _charactersType,
+ _characters);
+ }
}
diff --git a/tests/union_vector/Movie.kt b/tests/union_vector/Movie.kt
index 714d46f..a9ad906 100644
--- a/tests/union_vector/Movie.kt
+++ b/tests/union_vector/Movie.kt
@@ -5,7 +5,6 @@
import com.google.flatbuffers.*
@Suppress("unused")
-@ExperimentalUnsignedTypes
class Movie : Table() {
fun __init(_i: Int, _bb: ByteBuffer) {
@@ -68,7 +67,7 @@
val o = __offset(10); return if (o != 0) __vector_len(o) else 0
}
companion object {
- fun validateVersion() = Constants.FLATBUFFERS_1_12_0()
+ fun validateVersion() = Constants.FLATBUFFERS_2_0_0()
fun getRootAsMovie(_bb: ByteBuffer): Movie = getRootAsMovie(_bb, Movie())
fun getRootAsMovie(_bb: ByteBuffer, obj: Movie): Movie {
_bb.order(ByteOrder.LITTLE_ENDIAN)
diff --git a/tests/union_vector/MovieT.java b/tests/union_vector/MovieT.java
new file mode 100644
index 0000000..122d4ea
--- /dev/null
+++ b/tests/union_vector/MovieT.java
@@ -0,0 +1,34 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+import java.nio.*;
+import java.lang.*;
+import java.util.*;
+import com.google.flatbuffers.*;
+
+public class MovieT {
+ private CharacterUnion mainCharacter;
+ private CharacterUnion[] characters;
+
+ public CharacterUnion getMainCharacter() { return mainCharacter; }
+
+ public void setMainCharacter(CharacterUnion mainCharacter) { this.mainCharacter = mainCharacter; }
+
+ public CharacterUnion[] getCharacters() { return characters; }
+
+ public void setCharacters(CharacterUnion[] characters) { this.characters = characters; }
+
+
+ public MovieT() {
+ this.mainCharacter = null;
+ this.characters = null;
+ }
+ public static MovieT deserializeFromBinary(byte[] fbBuffer) {
+ return Movie.getRootAsMovie(ByteBuffer.wrap(fbBuffer)).unpack();
+ }
+ public byte[] serializeToBinary() {
+ FlatBufferBuilder fbb = new FlatBufferBuilder();
+ Movie.finishMovieBuffer(fbb, Movie.pack(fbb, this));
+ return fbb.sizedByteArray();
+ }
+}
+
diff --git a/tests/union_vector/Rapunzel.cs b/tests/union_vector/Rapunzel.cs
index e5ffff8..31d2cdf 100644
--- a/tests/union_vector/Rapunzel.cs
+++ b/tests/union_vector/Rapunzel.cs
@@ -35,7 +35,7 @@
builder,
_o.HairLength);
}
-};
+}
public class RapunzelT
{
diff --git a/tests/union_vector/Rapunzel.java b/tests/union_vector/Rapunzel.java
index 96d3cfe..ad6d9c1 100644
--- a/tests/union_vector/Rapunzel.java
+++ b/tests/union_vector/Rapunzel.java
@@ -25,5 +25,20 @@
public Rapunzel get(int j) { return get(new Rapunzel(), j); }
public Rapunzel get(Rapunzel obj, int j) { return obj.__assign(__element(j), bb); }
}
+ public RapunzelT unpack() {
+ RapunzelT _o = new RapunzelT();
+ unpackTo(_o);
+ return _o;
+ }
+ public void unpackTo(RapunzelT _o) {
+ int _oHairLength = hairLength();
+ _o.setHairLength(_oHairLength);
+ }
+ public static int pack(FlatBufferBuilder builder, RapunzelT _o) {
+ if (_o == null) return 0;
+ return createRapunzel(
+ builder,
+ _o.getHairLength());
+ }
}
diff --git a/tests/union_vector/Rapunzel.kt b/tests/union_vector/Rapunzel.kt
index 080a7f7..72261d4 100644
--- a/tests/union_vector/Rapunzel.kt
+++ b/tests/union_vector/Rapunzel.kt
@@ -5,7 +5,6 @@
import com.google.flatbuffers.*
@Suppress("unused")
-@ExperimentalUnsignedTypes
class Rapunzel : Struct() {
fun __init(_i: Int, _bb: ByteBuffer) {
diff --git a/tests/union_vector/RapunzelT.java b/tests/union_vector/RapunzelT.java
new file mode 100644
index 0000000..b58732c
--- /dev/null
+++ b/tests/union_vector/RapunzelT.java
@@ -0,0 +1,20 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+import java.nio.*;
+import java.lang.*;
+import java.util.*;
+import com.google.flatbuffers.*;
+
+public class RapunzelT {
+ private int hairLength;
+
+ public int getHairLength() { return hairLength; }
+
+ public void setHairLength(int hairLength) { this.hairLength = hairLength; }
+
+
+ public RapunzelT() {
+ this.hairLength = 0;
+ }
+}
+
diff --git a/tests/union_vector/attacker.js b/tests/union_vector/attacker.js
new file mode 100644
index 0000000..32be94e
--- /dev/null
+++ b/tests/union_vector/attacker.js
@@ -0,0 +1,64 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+import * as flatbuffers from 'flatbuffers';
+export class Attacker {
+ constructor() {
+ this.bb = null;
+ this.bb_pos = 0;
+ }
+ __init(i, bb) {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+ }
+ static getRootAsAttacker(bb, obj) {
+ return (obj || new Attacker()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ static getSizePrefixedRootAsAttacker(bb, obj) {
+ bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new Attacker()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ swordAttackDamage() {
+ const offset = this.bb.__offset(this.bb_pos, 4);
+ return offset ? this.bb.readInt32(this.bb_pos + offset) : 0;
+ }
+ mutate_sword_attack_damage(value) {
+ const offset = this.bb.__offset(this.bb_pos, 4);
+ if (offset === 0) {
+ return false;
+ }
+ this.bb.writeInt32(this.bb_pos + offset, value);
+ return true;
+ }
+ static getFullyQualifiedName() {
+ return 'Attacker';
+ }
+ static startAttacker(builder) {
+ builder.startObject(1);
+ }
+ static addSwordAttackDamage(builder, swordAttackDamage) {
+ builder.addFieldInt32(0, swordAttackDamage, 0);
+ }
+ static endAttacker(builder) {
+ const offset = builder.endObject();
+ return offset;
+ }
+ static createAttacker(builder, swordAttackDamage) {
+ Attacker.startAttacker(builder);
+ Attacker.addSwordAttackDamage(builder, swordAttackDamage);
+ return Attacker.endAttacker(builder);
+ }
+ unpack() {
+ return new AttackerT(this.swordAttackDamage());
+ }
+ unpackTo(_o) {
+ _o.swordAttackDamage = this.swordAttackDamage();
+ }
+}
+export class AttackerT {
+ constructor(swordAttackDamage = 0) {
+ this.swordAttackDamage = swordAttackDamage;
+ }
+ pack(builder) {
+ return Attacker.createAttacker(builder, this.swordAttackDamage);
+ }
+}
diff --git a/tests/union_vector/attacker.ts b/tests/union_vector/attacker.ts
new file mode 100644
index 0000000..af37020
--- /dev/null
+++ b/tests/union_vector/attacker.ts
@@ -0,0 +1,87 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+import * as flatbuffers from 'flatbuffers';
+
+
+
+export class Attacker {
+ bb: flatbuffers.ByteBuffer|null = null;
+ bb_pos = 0;
+__init(i:number, bb:flatbuffers.ByteBuffer):Attacker {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+}
+
+static getRootAsAttacker(bb:flatbuffers.ByteBuffer, obj?:Attacker):Attacker {
+ return (obj || new Attacker()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+}
+
+static getSizePrefixedRootAsAttacker(bb:flatbuffers.ByteBuffer, obj?:Attacker):Attacker {
+ bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new Attacker()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+}
+
+swordAttackDamage():number {
+ const offset = this.bb!.__offset(this.bb_pos, 4);
+ return offset ? this.bb!.readInt32(this.bb_pos + offset) : 0;
+}
+
+mutate_sword_attack_damage(value:number):boolean {
+ const offset = this.bb!.__offset(this.bb_pos, 4);
+
+ if (offset === 0) {
+ return false;
+ }
+
+ this.bb!.writeInt32(this.bb_pos + offset, value);
+ return true;
+}
+
+static getFullyQualifiedName():string {
+ return 'Attacker';
+}
+
+static startAttacker(builder:flatbuffers.Builder) {
+ builder.startObject(1);
+}
+
+static addSwordAttackDamage(builder:flatbuffers.Builder, swordAttackDamage:number) {
+ builder.addFieldInt32(0, swordAttackDamage, 0);
+}
+
+static endAttacker(builder:flatbuffers.Builder):flatbuffers.Offset {
+ const offset = builder.endObject();
+ return offset;
+}
+
+static createAttacker(builder:flatbuffers.Builder, swordAttackDamage:number):flatbuffers.Offset {
+ Attacker.startAttacker(builder);
+ Attacker.addSwordAttackDamage(builder, swordAttackDamage);
+ return Attacker.endAttacker(builder);
+}
+
+unpack(): AttackerT {
+ return new AttackerT(
+ this.swordAttackDamage()
+ );
+}
+
+
+unpackTo(_o: AttackerT): void {
+ _o.swordAttackDamage = this.swordAttackDamage();
+}
+}
+
+export class AttackerT {
+constructor(
+ public swordAttackDamage: number = 0
+){}
+
+
+pack(builder:flatbuffers.Builder): flatbuffers.Offset {
+ return Attacker.createAttacker(builder,
+ this.swordAttackDamage
+ );
+}
+}
diff --git a/tests/union_vector/book-reader.js b/tests/union_vector/book-reader.js
new file mode 100644
index 0000000..0d9e1a5
--- /dev/null
+++ b/tests/union_vector/book-reader.js
@@ -0,0 +1,44 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+export class BookReader {
+ constructor() {
+ this.bb = null;
+ this.bb_pos = 0;
+ }
+ __init(i, bb) {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+ }
+ booksRead() {
+ return this.bb.readInt32(this.bb_pos);
+ }
+ mutate_books_read(value) {
+ this.bb.writeInt32(this.bb_pos + 0, value);
+ return true;
+ }
+ static getFullyQualifiedName() {
+ return 'BookReader';
+ }
+ static sizeOf() {
+ return 4;
+ }
+ static createBookReader(builder, books_read) {
+ builder.prep(4, 4);
+ builder.writeInt32(books_read);
+ return builder.offset();
+ }
+ unpack() {
+ return new BookReaderT(this.booksRead());
+ }
+ unpackTo(_o) {
+ _o.booksRead = this.booksRead();
+ }
+}
+export class BookReaderT {
+ constructor(booksRead = 0) {
+ this.booksRead = booksRead;
+ }
+ pack(builder) {
+ return BookReader.createBookReader(builder, this.booksRead);
+ }
+}
diff --git a/tests/union_vector/book-reader.ts b/tests/union_vector/book-reader.ts
new file mode 100644
index 0000000..2310600
--- /dev/null
+++ b/tests/union_vector/book-reader.ts
@@ -0,0 +1,63 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+import * as flatbuffers from 'flatbuffers';
+
+
+
+export class BookReader {
+ bb: flatbuffers.ByteBuffer|null = null;
+ bb_pos = 0;
+__init(i:number, bb:flatbuffers.ByteBuffer):BookReader {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+}
+
+booksRead():number {
+ return this.bb!.readInt32(this.bb_pos);
+}
+
+mutate_books_read(value:number):boolean {
+ this.bb!.writeInt32(this.bb_pos + 0, value);
+ return true;
+}
+
+static getFullyQualifiedName():string {
+ return 'BookReader';
+}
+
+static sizeOf():number {
+ return 4;
+}
+
+static createBookReader(builder:flatbuffers.Builder, books_read: number):flatbuffers.Offset {
+ builder.prep(4, 4);
+ builder.writeInt32(books_read);
+ return builder.offset();
+}
+
+
+unpack(): BookReaderT {
+ return new BookReaderT(
+ this.booksRead()
+ );
+}
+
+
+unpackTo(_o: BookReaderT): void {
+ _o.booksRead = this.booksRead();
+}
+}
+
+export class BookReaderT {
+constructor(
+ public booksRead: number = 0
+){}
+
+
+pack(builder:flatbuffers.Builder): flatbuffers.Offset {
+ return BookReader.createBookReader(builder,
+ this.booksRead
+ );
+}
+}
diff --git a/tests/union_vector/character.js b/tests/union_vector/character.js
new file mode 100644
index 0000000..c060298
--- /dev/null
+++ b/tests/union_vector/character.js
@@ -0,0 +1,38 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+import { Attacker } from './attacker';
+import { BookReader } from './book-reader';
+import { Rapunzel } from './rapunzel';
+export var Character;
+(function (Character) {
+ Character[Character["NONE"] = 0] = "NONE";
+ Character[Character["MuLan"] = 1] = "MuLan";
+ Character[Character["Rapunzel"] = 2] = "Rapunzel";
+ Character[Character["Belle"] = 3] = "Belle";
+ Character[Character["BookFan"] = 4] = "BookFan";
+ Character[Character["Other"] = 5] = "Other";
+ Character[Character["Unused"] = 6] = "Unused";
+})(Character || (Character = {}));
+export function unionToCharacter(type, accessor) {
+ switch (Character[type]) {
+ case 'NONE': return null;
+ case 'MuLan': return accessor(new Attacker());
+ case 'Rapunzel': return accessor(new Rapunzel());
+ case 'Belle': return accessor(new BookReader());
+ case 'BookFan': return accessor(new BookReader());
+ case 'Other': return accessor('');
+ case 'Unused': return accessor('');
+ default: return null;
+ }
+}
+export function unionListToCharacter(type, accessor, index) {
+ switch (Character[type]) {
+ case 'NONE': return null;
+ case 'MuLan': return accessor(index, new Attacker());
+ case 'Rapunzel': return accessor(index, new Rapunzel());
+ case 'Belle': return accessor(index, new BookReader());
+ case 'BookFan': return accessor(index, new BookReader());
+ case 'Other': return accessor(index, '');
+ case 'Unused': return accessor(index, '');
+ default: return null;
+ }
+}
diff --git a/tests/union_vector/character.ts b/tests/union_vector/character.ts
new file mode 100644
index 0000000..dbf8d51
--- /dev/null
+++ b/tests/union_vector/character.ts
@@ -0,0 +1,50 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+import { Attacker, AttackerT } from './attacker';
+import { BookReader, BookReaderT } from './book-reader';
+import { Rapunzel, RapunzelT } from './rapunzel';
+
+
+export enum Character{
+ NONE = 0,
+ MuLan = 1,
+ Rapunzel = 2,
+ Belle = 3,
+ BookFan = 4,
+ Other = 5,
+ Unused = 6
+}
+
+export function unionToCharacter(
+ type: Character,
+ accessor: (obj:Attacker|BookReader|Rapunzel|string) => Attacker|BookReader|Rapunzel|string|null
+): Attacker|BookReader|Rapunzel|string|null {
+ switch(Character[type]) {
+ case 'NONE': return null;
+ case 'MuLan': return accessor(new Attacker())! as Attacker;
+ case 'Rapunzel': return accessor(new Rapunzel())! as Rapunzel;
+ case 'Belle': return accessor(new BookReader())! as BookReader;
+ case 'BookFan': return accessor(new BookReader())! as BookReader;
+ case 'Other': return accessor('') as string;
+ case 'Unused': return accessor('') as string;
+ default: return null;
+ }
+}
+
+export function unionListToCharacter(
+ type: Character,
+ accessor: (index: number, obj:Attacker|BookReader|Rapunzel|string) => Attacker|BookReader|Rapunzel|string|null,
+ index: number
+): Attacker|BookReader|Rapunzel|string|null {
+ switch(Character[type]) {
+ case 'NONE': return null;
+ case 'MuLan': return accessor(index, new Attacker())! as Attacker;
+ case 'Rapunzel': return accessor(index, new Rapunzel())! as Rapunzel;
+ case 'Belle': return accessor(index, new BookReader())! as BookReader;
+ case 'BookFan': return accessor(index, new BookReader())! as BookReader;
+ case 'Other': return accessor(index, '') as string;
+ case 'Unused': return accessor(index, '') as string;
+ default: return null;
+ }
+}
+
diff --git a/tests/union_vector/falling-tub.ts b/tests/union_vector/falling-tub.ts
new file mode 100644
index 0000000..3a836b3
--- /dev/null
+++ b/tests/union_vector/falling-tub.ts
@@ -0,0 +1,63 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+import * as flatbuffers from 'flatbuffers';
+
+
+
+export class FallingTub {
+ bb: flatbuffers.ByteBuffer|null = null;
+ bb_pos = 0;
+__init(i:number, bb:flatbuffers.ByteBuffer):FallingTub {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+}
+
+weight():number {
+ return this.bb!.readInt32(this.bb_pos);
+}
+
+mutate_weight(value:number):boolean {
+ this.bb!.writeInt32(this.bb_pos + 0, value);
+ return true;
+}
+
+static getFullyQualifiedName():string {
+ return 'FallingTub';
+}
+
+static sizeOf():number {
+ return 4;
+}
+
+static createFallingTub(builder:flatbuffers.Builder, weight: number):flatbuffers.Offset {
+ builder.prep(4, 4);
+ builder.writeInt32(weight);
+ return builder.offset();
+}
+
+
+unpack(): FallingTubT {
+ return new FallingTubT(
+ this.weight()
+ );
+}
+
+
+unpackTo(_o: FallingTubT): void {
+ _o.weight = this.weight();
+}
+}
+
+export class FallingTubT {
+constructor(
+ public weight: number = 0
+){}
+
+
+pack(builder:flatbuffers.Builder): flatbuffers.Offset {
+ return FallingTub.createFallingTub(builder,
+ this.weight
+ );
+}
+}
diff --git a/tests/union_vector/gadget.ts b/tests/union_vector/gadget.ts
new file mode 100644
index 0000000..4d84b0a
--- /dev/null
+++ b/tests/union_vector/gadget.ts
@@ -0,0 +1,37 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+import { FallingTub, FallingTubT } from './falling-tub';
+import { HandFan, HandFanT } from './hand-fan';
+
+
+export enum Gadget{
+ NONE = 0,
+ FallingTub = 1,
+ HandFan = 2
+}
+
+export function unionToGadget(
+ type: Gadget,
+ accessor: (obj:FallingTub|HandFan) => FallingTub|HandFan|null
+): FallingTub|HandFan|null {
+ switch(Gadget[type]) {
+ case 'NONE': return null;
+ case 'FallingTub': return accessor(new FallingTub())! as FallingTub;
+ case 'HandFan': return accessor(new HandFan())! as HandFan;
+ default: return null;
+ }
+}
+
+export function unionListToGadget(
+ type: Gadget,
+ accessor: (index: number, obj:FallingTub|HandFan) => FallingTub|HandFan|null,
+ index: number
+): FallingTub|HandFan|null {
+ switch(Gadget[type]) {
+ case 'NONE': return null;
+ case 'FallingTub': return accessor(index, new FallingTub())! as FallingTub;
+ case 'HandFan': return accessor(index, new HandFan())! as HandFan;
+ default: return null;
+ }
+}
+
diff --git a/tests/union_vector/hand-fan.ts b/tests/union_vector/hand-fan.ts
new file mode 100644
index 0000000..4a770ba
--- /dev/null
+++ b/tests/union_vector/hand-fan.ts
@@ -0,0 +1,87 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+import * as flatbuffers from 'flatbuffers';
+
+
+
+export class HandFan {
+ bb: flatbuffers.ByteBuffer|null = null;
+ bb_pos = 0;
+__init(i:number, bb:flatbuffers.ByteBuffer):HandFan {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+}
+
+static getRootAsHandFan(bb:flatbuffers.ByteBuffer, obj?:HandFan):HandFan {
+ return (obj || new HandFan()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+}
+
+static getSizePrefixedRootAsHandFan(bb:flatbuffers.ByteBuffer, obj?:HandFan):HandFan {
+ bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new HandFan()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+}
+
+length():number {
+ const offset = this.bb!.__offset(this.bb_pos, 4);
+ return offset ? this.bb!.readInt32(this.bb_pos + offset) : 0;
+}
+
+mutate_length(value:number):boolean {
+ const offset = this.bb!.__offset(this.bb_pos, 4);
+
+ if (offset === 0) {
+ return false;
+ }
+
+ this.bb!.writeInt32(this.bb_pos + offset, value);
+ return true;
+}
+
+static getFullyQualifiedName():string {
+ return 'HandFan';
+}
+
+static startHandFan(builder:flatbuffers.Builder) {
+ builder.startObject(1);
+}
+
+static addLength(builder:flatbuffers.Builder, length:number) {
+ builder.addFieldInt32(0, length, 0);
+}
+
+static endHandFan(builder:flatbuffers.Builder):flatbuffers.Offset {
+ const offset = builder.endObject();
+ return offset;
+}
+
+static createHandFan(builder:flatbuffers.Builder, length:number):flatbuffers.Offset {
+ HandFan.startHandFan(builder);
+ HandFan.addLength(builder, length);
+ return HandFan.endHandFan(builder);
+}
+
+unpack(): HandFanT {
+ return new HandFanT(
+ this.length()
+ );
+}
+
+
+unpackTo(_o: HandFanT): void {
+ _o.length = this.length();
+}
+}
+
+export class HandFanT {
+constructor(
+ public length: number = 0
+){}
+
+
+pack(builder:flatbuffers.Builder): flatbuffers.Offset {
+ return HandFan.createHandFan(builder,
+ this.length
+ );
+}
+}
diff --git a/tests/union_vector/movie.js b/tests/union_vector/movie.js
new file mode 100644
index 0000000..b4d8099
--- /dev/null
+++ b/tests/union_vector/movie.js
@@ -0,0 +1,185 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+import * as flatbuffers from 'flatbuffers';
+import { Character, unionToCharacter, unionListToCharacter } from './character';
+export class Movie {
+ constructor() {
+ this.bb = null;
+ this.bb_pos = 0;
+ }
+ __init(i, bb) {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+ }
+ static getRootAsMovie(bb, obj) {
+ return (obj || new Movie()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ static getSizePrefixedRootAsMovie(bb, obj) {
+ bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new Movie()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+ }
+ static bufferHasIdentifier(bb) {
+ return bb.__has_identifier('MOVI');
+ }
+ mainCharacterType() {
+ const offset = this.bb.__offset(this.bb_pos, 4);
+ return offset ? this.bb.readUint8(this.bb_pos + offset) : Character.NONE;
+ }
+ mainCharacter(obj) {
+ const offset = this.bb.__offset(this.bb_pos, 6);
+ return offset ? this.bb.__union_with_string(obj, this.bb_pos + offset) : null;
+ }
+ charactersType(index) {
+ const offset = this.bb.__offset(this.bb_pos, 8);
+ return offset ? this.bb.readUint8(this.bb.__vector(this.bb_pos + offset) + index) : 0;
+ }
+ charactersTypeLength() {
+ const offset = this.bb.__offset(this.bb_pos, 8);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ charactersTypeArray() {
+ const offset = this.bb.__offset(this.bb_pos, 8);
+ return offset ? new Uint8Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null;
+ }
+ characters(index, obj) {
+ const offset = this.bb.__offset(this.bb_pos, 10);
+ return offset ? this.bb.__union_with_string(obj, this.bb.__vector(this.bb_pos + offset) + index * 4) : null;
+ }
+ charactersLength() {
+ const offset = this.bb.__offset(this.bb_pos, 10);
+ return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
+ }
+ static getFullyQualifiedName() {
+ return 'Movie';
+ }
+ static startMovie(builder) {
+ builder.startObject(4);
+ }
+ static addMainCharacterType(builder, mainCharacterType) {
+ builder.addFieldInt8(0, mainCharacterType, Character.NONE);
+ }
+ static addMainCharacter(builder, mainCharacterOffset) {
+ builder.addFieldOffset(1, mainCharacterOffset, 0);
+ }
+ static addCharactersType(builder, charactersTypeOffset) {
+ builder.addFieldOffset(2, charactersTypeOffset, 0);
+ }
+ static createCharactersTypeVector(builder, data) {
+ builder.startVector(1, data.length, 1);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addInt8(data[i]);
+ }
+ return builder.endVector();
+ }
+ static startCharactersTypeVector(builder, numElems) {
+ builder.startVector(1, numElems, 1);
+ }
+ static addCharacters(builder, charactersOffset) {
+ builder.addFieldOffset(3, charactersOffset, 0);
+ }
+ static createCharactersVector(builder, data) {
+ builder.startVector(4, data.length, 4);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addOffset(data[i]);
+ }
+ return builder.endVector();
+ }
+ static startCharactersVector(builder, numElems) {
+ builder.startVector(4, numElems, 4);
+ }
+ static endMovie(builder) {
+ const offset = builder.endObject();
+ return offset;
+ }
+ static finishMovieBuffer(builder, offset) {
+ builder.finish(offset, 'MOVI');
+ }
+ static finishSizePrefixedMovieBuffer(builder, offset) {
+ builder.finish(offset, 'MOVI', true);
+ }
+ static createMovie(builder, mainCharacterType, mainCharacterOffset, charactersTypeOffset, charactersOffset) {
+ Movie.startMovie(builder);
+ Movie.addMainCharacterType(builder, mainCharacterType);
+ Movie.addMainCharacter(builder, mainCharacterOffset);
+ Movie.addCharactersType(builder, charactersTypeOffset);
+ Movie.addCharacters(builder, charactersOffset);
+ return Movie.endMovie(builder);
+ }
+ unpack() {
+ return new MovieT(this.mainCharacterType(), (() => {
+ let temp = unionToCharacter(this.mainCharacterType(), this.mainCharacter.bind(this));
+ if (temp === null) {
+ return null;
+ }
+ if (typeof temp === 'string') {
+ return temp;
+ }
+ return temp.unpack();
+ })(), this.bb.createScalarList(this.charactersType.bind(this), this.charactersTypeLength()), (() => {
+ let ret = [];
+ for (let targetEnumIndex = 0; targetEnumIndex < this.charactersTypeLength(); ++targetEnumIndex) {
+ let targetEnum = this.charactersType(targetEnumIndex);
+ if (targetEnum === null || Character[targetEnum] === 'NONE') {
+ continue;
+ }
+ let temp = unionListToCharacter(targetEnum, this.characters.bind(this), targetEnumIndex);
+ if (temp === null) {
+ continue;
+ }
+ if (typeof temp === 'string') {
+ ret.push(temp);
+ continue;
+ }
+ ret.push(temp.unpack());
+ }
+ return ret;
+ })());
+ }
+ unpackTo(_o) {
+ _o.mainCharacterType = this.mainCharacterType();
+ _o.mainCharacter = (() => {
+ let temp = unionToCharacter(this.mainCharacterType(), this.mainCharacter.bind(this));
+ if (temp === null) {
+ return null;
+ }
+ if (typeof temp === 'string') {
+ return temp;
+ }
+ return temp.unpack();
+ })();
+ _o.charactersType = this.bb.createScalarList(this.charactersType.bind(this), this.charactersTypeLength());
+ _o.characters = (() => {
+ let ret = [];
+ for (let targetEnumIndex = 0; targetEnumIndex < this.charactersTypeLength(); ++targetEnumIndex) {
+ let targetEnum = this.charactersType(targetEnumIndex);
+ if (targetEnum === null || Character[targetEnum] === 'NONE') {
+ continue;
+ }
+ let temp = unionListToCharacter(targetEnum, this.characters.bind(this), targetEnumIndex);
+ if (temp === null) {
+ continue;
+ }
+ if (typeof temp === 'string') {
+ ret.push(temp);
+ continue;
+ }
+ ret.push(temp.unpack());
+ }
+ return ret;
+ })();
+ }
+}
+export class MovieT {
+ constructor(mainCharacterType = Character.NONE, mainCharacter = null, charactersType = [], characters = []) {
+ this.mainCharacterType = mainCharacterType;
+ this.mainCharacter = mainCharacter;
+ this.charactersType = charactersType;
+ this.characters = characters;
+ }
+ pack(builder) {
+ const mainCharacter = builder.createObjectOffset(this.mainCharacter);
+ const charactersType = Movie.createCharactersTypeVector(builder, this.charactersType);
+ const characters = Movie.createCharactersVector(builder, builder.createObjectOffsetList(this.characters));
+ return Movie.createMovie(builder, this.mainCharacterType, mainCharacter, charactersType, characters);
+ }
+}
diff --git a/tests/union_vector/movie.ts b/tests/union_vector/movie.ts
new file mode 100644
index 0000000..b3e8381
--- /dev/null
+++ b/tests/union_vector/movie.ts
@@ -0,0 +1,211 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+import * as flatbuffers from 'flatbuffers';
+
+import { Attacker, AttackerT } from './attacker';
+import { BookReader, BookReaderT } from './book-reader';
+import { Character, unionToCharacter, unionListToCharacter } from './character';
+import { Rapunzel, RapunzelT } from './rapunzel';
+
+
+export class Movie {
+ bb: flatbuffers.ByteBuffer|null = null;
+ bb_pos = 0;
+__init(i:number, bb:flatbuffers.ByteBuffer):Movie {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+}
+
+static getRootAsMovie(bb:flatbuffers.ByteBuffer, obj?:Movie):Movie {
+ return (obj || new Movie()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+}
+
+static getSizePrefixedRootAsMovie(bb:flatbuffers.ByteBuffer, obj?:Movie):Movie {
+ bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
+ return (obj || new Movie()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
+}
+
+static bufferHasIdentifier(bb:flatbuffers.ByteBuffer):boolean {
+ return bb.__has_identifier('MOVI');
+}
+
+mainCharacterType():Character {
+ const offset = this.bb!.__offset(this.bb_pos, 4);
+ return offset ? this.bb!.readUint8(this.bb_pos + offset) : Character.NONE;
+}
+
+mainCharacter<T extends flatbuffers.Table>(obj:any|string):any|string|null {
+ const offset = this.bb!.__offset(this.bb_pos, 6);
+ return offset ? this.bb!.__union_with_string(obj, this.bb_pos + offset) : null;
+}
+
+charactersType(index: number):Character|null {
+ const offset = this.bb!.__offset(this.bb_pos, 8);
+ return offset ? this.bb!.readUint8(this.bb!.__vector(this.bb_pos + offset) + index) : 0;
+}
+
+charactersTypeLength():number {
+ const offset = this.bb!.__offset(this.bb_pos, 8);
+ return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
+}
+
+charactersTypeArray():Uint8Array|null {
+ const offset = this.bb!.__offset(this.bb_pos, 8);
+ return offset ? new Uint8Array(this.bb!.bytes().buffer, this.bb!.bytes().byteOffset + this.bb!.__vector(this.bb_pos + offset), this.bb!.__vector_len(this.bb_pos + offset)) : null;
+}
+
+characters(index: number, obj:any|string):any|string|null {
+ const offset = this.bb!.__offset(this.bb_pos, 10);
+ return offset ? this.bb!.__union_with_string(obj, this.bb!.__vector(this.bb_pos + offset) + index * 4) : null;
+}
+
+charactersLength():number {
+ const offset = this.bb!.__offset(this.bb_pos, 10);
+ return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
+}
+
+static getFullyQualifiedName():string {
+ return 'Movie';
+}
+
+static startMovie(builder:flatbuffers.Builder) {
+ builder.startObject(4);
+}
+
+static addMainCharacterType(builder:flatbuffers.Builder, mainCharacterType:Character) {
+ builder.addFieldInt8(0, mainCharacterType, Character.NONE);
+}
+
+static addMainCharacter(builder:flatbuffers.Builder, mainCharacterOffset:flatbuffers.Offset) {
+ builder.addFieldOffset(1, mainCharacterOffset, 0);
+}
+
+static addCharactersType(builder:flatbuffers.Builder, charactersTypeOffset:flatbuffers.Offset) {
+ builder.addFieldOffset(2, charactersTypeOffset, 0);
+}
+
+static createCharactersTypeVector(builder:flatbuffers.Builder, data:Character[]):flatbuffers.Offset {
+ builder.startVector(1, data.length, 1);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addInt8(data[i]!);
+ }
+ return builder.endVector();
+}
+
+static startCharactersTypeVector(builder:flatbuffers.Builder, numElems:number) {
+ builder.startVector(1, numElems, 1);
+}
+
+static addCharacters(builder:flatbuffers.Builder, charactersOffset:flatbuffers.Offset) {
+ builder.addFieldOffset(3, charactersOffset, 0);
+}
+
+static createCharactersVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset {
+ builder.startVector(4, data.length, 4);
+ for (let i = data.length - 1; i >= 0; i--) {
+ builder.addOffset(data[i]!);
+ }
+ return builder.endVector();
+}
+
+static startCharactersVector(builder:flatbuffers.Builder, numElems:number) {
+ builder.startVector(4, numElems, 4);
+}
+
+static endMovie(builder:flatbuffers.Builder):flatbuffers.Offset {
+ const offset = builder.endObject();
+ return offset;
+}
+
+static finishMovieBuffer(builder:flatbuffers.Builder, offset:flatbuffers.Offset) {
+ builder.finish(offset, 'MOVI');
+}
+
+static finishSizePrefixedMovieBuffer(builder:flatbuffers.Builder, offset:flatbuffers.Offset) {
+ builder.finish(offset, 'MOVI', true);
+}
+
+static createMovie(builder:flatbuffers.Builder, mainCharacterType:Character, mainCharacterOffset:flatbuffers.Offset, charactersTypeOffset:flatbuffers.Offset, charactersOffset:flatbuffers.Offset):flatbuffers.Offset {
+ Movie.startMovie(builder);
+ Movie.addMainCharacterType(builder, mainCharacterType);
+ Movie.addMainCharacter(builder, mainCharacterOffset);
+ Movie.addCharactersType(builder, charactersTypeOffset);
+ Movie.addCharacters(builder, charactersOffset);
+ return Movie.endMovie(builder);
+}
+
+unpack(): MovieT {
+ return new MovieT(
+ this.mainCharacterType(),
+ (() => {
+ let temp = unionToCharacter(this.mainCharacterType(), this.mainCharacter.bind(this));
+ if(temp === null) { return null; }
+ if(typeof temp === 'string') { return temp; }
+ return temp.unpack()
+ })(),
+ this.bb!.createScalarList(this.charactersType.bind(this), this.charactersTypeLength()),
+ (() => {
+ let ret = [];
+ for(let targetEnumIndex = 0; targetEnumIndex < this.charactersTypeLength(); ++targetEnumIndex) {
+ let targetEnum = this.charactersType(targetEnumIndex);
+ if(targetEnum === null || Character[targetEnum!] === 'NONE') { continue; }
+
+ let temp = unionListToCharacter(targetEnum, this.characters.bind(this), targetEnumIndex);
+ if(temp === null) { continue; }
+ if(typeof temp === 'string') { ret.push(temp); continue; }
+ ret.push(temp.unpack());
+ }
+ return ret;
+ })()
+ );
+}
+
+
+unpackTo(_o: MovieT): void {
+ _o.mainCharacterType = this.mainCharacterType();
+ _o.mainCharacter = (() => {
+ let temp = unionToCharacter(this.mainCharacterType(), this.mainCharacter.bind(this));
+ if(temp === null) { return null; }
+ if(typeof temp === 'string') { return temp; }
+ return temp.unpack()
+ })();
+ _o.charactersType = this.bb!.createScalarList(this.charactersType.bind(this), this.charactersTypeLength());
+ _o.characters = (() => {
+ let ret = [];
+ for(let targetEnumIndex = 0; targetEnumIndex < this.charactersTypeLength(); ++targetEnumIndex) {
+ let targetEnum = this.charactersType(targetEnumIndex);
+ if(targetEnum === null || Character[targetEnum!] === 'NONE') { continue; }
+
+ let temp = unionListToCharacter(targetEnum, this.characters.bind(this), targetEnumIndex);
+ if(temp === null) { continue; }
+ if(typeof temp === 'string') { ret.push(temp); continue; }
+ ret.push(temp.unpack());
+ }
+ return ret;
+ })();
+}
+}
+
+export class MovieT {
+constructor(
+ public mainCharacterType: Character = Character.NONE,
+ public mainCharacter: AttackerT|BookReaderT|RapunzelT|string|null = null,
+ public charactersType: (Character)[] = [],
+ public characters: (AttackerT|BookReaderT|RapunzelT|string)[] = []
+){}
+
+
+pack(builder:flatbuffers.Builder): flatbuffers.Offset {
+ const mainCharacter = builder.createObjectOffset(this.mainCharacter);
+ const charactersType = Movie.createCharactersTypeVector(builder, this.charactersType);
+ const characters = Movie.createCharactersVector(builder, builder.createObjectOffsetList(this.characters));
+
+ return Movie.createMovie(builder,
+ this.mainCharacterType,
+ mainCharacter,
+ charactersType,
+ characters
+ );
+}
+}
diff --git a/tests/union_vector/rapunzel.js b/tests/union_vector/rapunzel.js
new file mode 100644
index 0000000..67a5e44
--- /dev/null
+++ b/tests/union_vector/rapunzel.js
@@ -0,0 +1,44 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+export class Rapunzel {
+ constructor() {
+ this.bb = null;
+ this.bb_pos = 0;
+ }
+ __init(i, bb) {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+ }
+ hairLength() {
+ return this.bb.readInt32(this.bb_pos);
+ }
+ mutate_hair_length(value) {
+ this.bb.writeInt32(this.bb_pos + 0, value);
+ return true;
+ }
+ static getFullyQualifiedName() {
+ return 'Rapunzel';
+ }
+ static sizeOf() {
+ return 4;
+ }
+ static createRapunzel(builder, hair_length) {
+ builder.prep(4, 4);
+ builder.writeInt32(hair_length);
+ return builder.offset();
+ }
+ unpack() {
+ return new RapunzelT(this.hairLength());
+ }
+ unpackTo(_o) {
+ _o.hairLength = this.hairLength();
+ }
+}
+export class RapunzelT {
+ constructor(hairLength = 0) {
+ this.hairLength = hairLength;
+ }
+ pack(builder) {
+ return Rapunzel.createRapunzel(builder, this.hairLength);
+ }
+}
diff --git a/tests/union_vector/rapunzel.ts b/tests/union_vector/rapunzel.ts
new file mode 100644
index 0000000..28f6e99
--- /dev/null
+++ b/tests/union_vector/rapunzel.ts
@@ -0,0 +1,63 @@
+// automatically generated by the FlatBuffers compiler, do not modify
+
+import * as flatbuffers from 'flatbuffers';
+
+
+
+export class Rapunzel {
+ bb: flatbuffers.ByteBuffer|null = null;
+ bb_pos = 0;
+__init(i:number, bb:flatbuffers.ByteBuffer):Rapunzel {
+ this.bb_pos = i;
+ this.bb = bb;
+ return this;
+}
+
+hairLength():number {
+ return this.bb!.readInt32(this.bb_pos);
+}
+
+mutate_hair_length(value:number):boolean {
+ this.bb!.writeInt32(this.bb_pos + 0, value);
+ return true;
+}
+
+static getFullyQualifiedName():string {
+ return 'Rapunzel';
+}
+
+static sizeOf():number {
+ return 4;
+}
+
+static createRapunzel(builder:flatbuffers.Builder, hair_length: number):flatbuffers.Offset {
+ builder.prep(4, 4);
+ builder.writeInt32(hair_length);
+ return builder.offset();
+}
+
+
+unpack(): RapunzelT {
+ return new RapunzelT(
+ this.hairLength()
+ );
+}
+
+
+unpackTo(_o: RapunzelT): void {
+ _o.hairLength = this.hairLength();
+}
+}
+
+export class RapunzelT {
+constructor(
+ public hairLength: number = 0
+){}
+
+
+pack(builder:flatbuffers.Builder): flatbuffers.Offset {
+ return Rapunzel.createRapunzel(builder,
+ this.hairLength
+ );
+}
+}
diff --git a/tests/union_vector/union_vector.fbs b/tests/union_vector/union_vector.fbs
index 495076f..3dd3848 100644
--- a/tests/union_vector/union_vector.fbs
+++ b/tests/union_vector/union_vector.fbs
@@ -22,6 +22,19 @@
Unused: string
}
+struct FallingTub {
+ weight: int;
+}
+
+table HandFan {
+ length: int;
+}
+
+union Gadget {
+ FallingTub,
+ HandFan,
+}
+
table Movie {
main_character: Character;
characters: [Character];
diff --git a/tests/union_vector/union_vector.js b/tests/union_vector/union_vector.js
new file mode 100644
index 0000000..f3a118b
--- /dev/null
+++ b/tests/union_vector/union_vector.js
@@ -0,0 +1,8 @@
+export { Attacker, AttackerT } from './attacker';
+export { BookReader, BookReaderT } from './book-reader';
+export { Character, unionToCharacter, unionListToCharacter } from './character';
+export { FallingTub, FallingTubT } from './falling-tub';
+export { Gadget, unionToGadget, unionListToGadget } from './gadget';
+export { HandFan, HandFanT } from './hand-fan';
+export { Movie, MovieT } from './movie';
+export { Rapunzel, RapunzelT } from './rapunzel';
diff --git a/tests/union_vector/union_vector.ts b/tests/union_vector/union_vector.ts
new file mode 100644
index 0000000..f3a118b
--- /dev/null
+++ b/tests/union_vector/union_vector.ts
@@ -0,0 +1,8 @@
+export { Attacker, AttackerT } from './attacker';
+export { BookReader, BookReaderT } from './book-reader';
+export { Character, unionToCharacter, unionListToCharacter } from './character';
+export { FallingTub, FallingTubT } from './falling-tub';
+export { Gadget, unionToGadget, unionListToGadget } from './gadget';
+export { HandFan, HandFanT } from './hand-fan';
+export { Movie, MovieT } from './movie';
+export { Rapunzel, RapunzelT } from './rapunzel';
diff --git a/tests/union_vector/union_vector_generated.h b/tests/union_vector/union_vector_generated.h
index e6c7971..e08df6a 100644
--- a/tests/union_vector/union_vector_generated.h
+++ b/tests/union_vector/union_vector_generated.h
@@ -14,6 +14,12 @@
struct BookReader;
+struct FallingTub;
+
+struct HandFan;
+struct HandFanBuilder;
+struct HandFanT;
+
struct Movie;
struct MovieBuilder;
struct MovieT;
@@ -24,6 +30,10 @@
bool operator!=(const Rapunzel &lhs, const Rapunzel &rhs);
bool operator==(const BookReader &lhs, const BookReader &rhs);
bool operator!=(const BookReader &lhs, const BookReader &rhs);
+bool operator==(const FallingTub &lhs, const FallingTub &rhs);
+bool operator!=(const FallingTub &lhs, const FallingTub &rhs);
+bool operator==(const HandFanT &lhs, const HandFanT &rhs);
+bool operator!=(const HandFanT &lhs, const HandFanT &rhs);
bool operator==(const MovieT &lhs, const MovieT &rhs);
bool operator!=(const MovieT &lhs, const MovieT &rhs);
@@ -33,9 +43,13 @@
inline const flatbuffers::TypeTable *BookReaderTypeTable();
+inline const flatbuffers::TypeTable *FallingTubTypeTable();
+
+inline const flatbuffers::TypeTable *HandFanTypeTable();
+
inline const flatbuffers::TypeTable *MovieTypeTable();
-enum Character {
+enum Character : uint8_t {
Character_NONE = 0,
Character_MuLan = 1,
Character_Rapunzel = 2,
@@ -194,6 +208,139 @@
bool VerifyCharacter(flatbuffers::Verifier &verifier, const void *obj, Character type);
bool VerifyCharacterVector(flatbuffers::Verifier &verifier, const flatbuffers::Vector<flatbuffers::Offset<void>> *values, const flatbuffers::Vector<uint8_t> *types);
+enum Gadget : uint8_t {
+ Gadget_NONE = 0,
+ Gadget_FallingTub = 1,
+ Gadget_HandFan = 2,
+ Gadget_MIN = Gadget_NONE,
+ Gadget_MAX = Gadget_HandFan
+};
+
+inline const Gadget (&EnumValuesGadget())[3] {
+ static const Gadget values[] = {
+ Gadget_NONE,
+ Gadget_FallingTub,
+ Gadget_HandFan
+ };
+ return values;
+}
+
+inline const char * const *EnumNamesGadget() {
+ static const char * const names[4] = {
+ "NONE",
+ "FallingTub",
+ "HandFan",
+ nullptr
+ };
+ return names;
+}
+
+inline const char *EnumNameGadget(Gadget e) {
+ if (flatbuffers::IsOutRange(e, Gadget_NONE, Gadget_HandFan)) return "";
+ const size_t index = static_cast<size_t>(e);
+ return EnumNamesGadget()[index];
+}
+
+template<typename T> struct GadgetTraits {
+ static const Gadget enum_value = Gadget_NONE;
+};
+
+template<> struct GadgetTraits<FallingTub> {
+ static const Gadget enum_value = Gadget_FallingTub;
+};
+
+template<> struct GadgetTraits<HandFan> {
+ static const Gadget enum_value = Gadget_HandFan;
+};
+
+template<typename T> struct GadgetUnionTraits {
+ static const Gadget enum_value = Gadget_NONE;
+};
+
+template<> struct GadgetUnionTraits<FallingTub> {
+ static const Gadget enum_value = Gadget_FallingTub;
+};
+
+template<> struct GadgetUnionTraits<HandFanT> {
+ static const Gadget enum_value = Gadget_HandFan;
+};
+
+struct GadgetUnion {
+ Gadget type;
+ void *value;
+
+ GadgetUnion() : type(Gadget_NONE), value(nullptr) {}
+ GadgetUnion(GadgetUnion&& u) FLATBUFFERS_NOEXCEPT :
+ type(Gadget_NONE), value(nullptr)
+ { std::swap(type, u.type); std::swap(value, u.value); }
+ GadgetUnion(const GadgetUnion &);
+ GadgetUnion &operator=(const GadgetUnion &u)
+ { GadgetUnion t(u); std::swap(type, t.type); std::swap(value, t.value); return *this; }
+ GadgetUnion &operator=(GadgetUnion &&u) FLATBUFFERS_NOEXCEPT
+ { std::swap(type, u.type); std::swap(value, u.value); return *this; }
+ ~GadgetUnion() { Reset(); }
+
+ void Reset();
+
+ template <typename T>
+ void Set(T&& val) {
+ typedef typename std::remove_reference<T>::type RT;
+ Reset();
+ type = GadgetUnionTraits<RT>::enum_value;
+ if (type != Gadget_NONE) {
+ value = new RT(std::forward<T>(val));
+ }
+ }
+
+ static void *UnPack(const void *obj, Gadget type, const flatbuffers::resolver_function_t *resolver);
+ flatbuffers::Offset<void> Pack(flatbuffers::FlatBufferBuilder &_fbb, const flatbuffers::rehasher_function_t *_rehasher = nullptr) const;
+
+ FallingTub *AsFallingTub() {
+ return type == Gadget_FallingTub ?
+ reinterpret_cast<FallingTub *>(value) : nullptr;
+ }
+ const FallingTub *AsFallingTub() const {
+ return type == Gadget_FallingTub ?
+ reinterpret_cast<const FallingTub *>(value) : nullptr;
+ }
+ HandFanT *AsHandFan() {
+ return type == Gadget_HandFan ?
+ reinterpret_cast<HandFanT *>(value) : nullptr;
+ }
+ const HandFanT *AsHandFan() const {
+ return type == Gadget_HandFan ?
+ reinterpret_cast<const HandFanT *>(value) : nullptr;
+ }
+};
+
+
+inline bool operator==(const GadgetUnion &lhs, const GadgetUnion &rhs) {
+ if (lhs.type != rhs.type) return false;
+ switch (lhs.type) {
+ case Gadget_NONE: {
+ return true;
+ }
+ case Gadget_FallingTub: {
+ return *(reinterpret_cast<const FallingTub *>(lhs.value)) ==
+ *(reinterpret_cast<const FallingTub *>(rhs.value));
+ }
+ case Gadget_HandFan: {
+ return *(reinterpret_cast<const HandFanT *>(lhs.value)) ==
+ *(reinterpret_cast<const HandFanT *>(rhs.value));
+ }
+ default: {
+ return false;
+ }
+ }
+}
+
+inline bool operator!=(const GadgetUnion &lhs, const GadgetUnion &rhs) {
+ return !(lhs == rhs);
+}
+
+bool VerifyGadget(flatbuffers::Verifier &verifier, const void *obj, Gadget type);
+bool VerifyGadgetVector(flatbuffers::Verifier &verifier, const flatbuffers::Vector<flatbuffers::Offset<void>> *values, const flatbuffers::Vector<uint8_t> *types);
+
FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) Rapunzel FLATBUFFERS_FINAL_CLASS {
private:
int32_t hair_length_;
@@ -202,7 +349,7 @@
static const flatbuffers::TypeTable *MiniReflectTypeTable() {
return RapunzelTypeTable();
}
- static FLATBUFFERS_CONSTEXPR const char *GetFullyQualifiedName() {
+ static FLATBUFFERS_CONSTEXPR_CPP11 const char *GetFullyQualifiedName() {
return "Rapunzel";
}
Rapunzel()
@@ -238,7 +385,7 @@
static const flatbuffers::TypeTable *MiniReflectTypeTable() {
return BookReaderTypeTable();
}
- static FLATBUFFERS_CONSTEXPR const char *GetFullyQualifiedName() {
+ static FLATBUFFERS_CONSTEXPR_CPP11 const char *GetFullyQualifiedName() {
return "BookReader";
}
BookReader()
@@ -266,34 +413,57 @@
}
-struct AttackerT : public flatbuffers::NativeTable {
- typedef Attacker TableType;
- static FLATBUFFERS_CONSTEXPR const char *GetFullyQualifiedName() {
- return "AttackerT";
+FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) FallingTub FLATBUFFERS_FINAL_CLASS {
+ private:
+ int32_t weight_;
+
+ public:
+ static const flatbuffers::TypeTable *MiniReflectTypeTable() {
+ return FallingTubTypeTable();
}
- int32_t sword_attack_damage;
- AttackerT()
- : sword_attack_damage(0) {
+ static FLATBUFFERS_CONSTEXPR_CPP11 const char *GetFullyQualifiedName() {
+ return "FallingTub";
+ }
+ FallingTub()
+ : weight_(0) {
+ }
+ FallingTub(int32_t _weight)
+ : weight_(flatbuffers::EndianScalar(_weight)) {
+ }
+ int32_t weight() const {
+ return flatbuffers::EndianScalar(weight_);
+ }
+ void mutate_weight(int32_t _weight) {
+ flatbuffers::WriteScalar(&weight_, _weight);
}
};
+FLATBUFFERS_STRUCT_END(FallingTub, 4);
-inline bool operator==(const AttackerT &lhs, const AttackerT &rhs) {
+inline bool operator==(const FallingTub &lhs, const FallingTub &rhs) {
return
- (lhs.sword_attack_damage == rhs.sword_attack_damage);
+ (lhs.weight() == rhs.weight());
}
-inline bool operator!=(const AttackerT &lhs, const AttackerT &rhs) {
+inline bool operator!=(const FallingTub &lhs, const FallingTub &rhs) {
return !(lhs == rhs);
}
+struct AttackerT : public flatbuffers::NativeTable {
+ typedef Attacker TableType;
+ static FLATBUFFERS_CONSTEXPR_CPP11 const char *GetFullyQualifiedName() {
+ return "AttackerT";
+ }
+ int32_t sword_attack_damage = 0;
+};
+
struct Attacker FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
typedef AttackerT NativeTableType;
typedef AttackerBuilder Builder;
static const flatbuffers::TypeTable *MiniReflectTypeTable() {
return AttackerTypeTable();
}
- static FLATBUFFERS_CONSTEXPR const char *GetFullyQualifiedName() {
+ static FLATBUFFERS_CONSTEXPR_CPP11 const char *GetFullyQualifiedName() {
return "Attacker";
}
enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE {
@@ -302,12 +472,12 @@
int32_t sword_attack_damage() const {
return GetField<int32_t>(VT_SWORD_ATTACK_DAMAGE, 0);
}
- bool mutate_sword_attack_damage(int32_t _sword_attack_damage) {
+ bool mutate_sword_attack_damage(int32_t _sword_attack_damage = 0) {
return SetField<int32_t>(VT_SWORD_ATTACK_DAMAGE, _sword_attack_damage, 0);
}
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
- VerifyField<int32_t>(verifier, VT_SWORD_ATTACK_DAMAGE) &&
+ VerifyField<int32_t>(verifier, VT_SWORD_ATTACK_DAMAGE, 4) &&
verifier.EndTable();
}
AttackerT *UnPack(const flatbuffers::resolver_function_t *_resolver = nullptr) const;
@@ -343,27 +513,78 @@
flatbuffers::Offset<Attacker> CreateAttacker(flatbuffers::FlatBufferBuilder &_fbb, const AttackerT *_o, const flatbuffers::rehasher_function_t *_rehasher = nullptr);
-struct MovieT : public flatbuffers::NativeTable {
- typedef Movie TableType;
- static FLATBUFFERS_CONSTEXPR const char *GetFullyQualifiedName() {
- return "MovieT";
+struct HandFanT : public flatbuffers::NativeTable {
+ typedef HandFan TableType;
+ static FLATBUFFERS_CONSTEXPR_CPP11 const char *GetFullyQualifiedName() {
+ return "HandFanT";
}
- CharacterUnion main_character;
- std::vector<CharacterUnion> characters;
- MovieT() {
+ int32_t length = 0;
+};
+
+struct HandFan FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
+ typedef HandFanT NativeTableType;
+ typedef HandFanBuilder Builder;
+ static const flatbuffers::TypeTable *MiniReflectTypeTable() {
+ return HandFanTypeTable();
+ }
+ static FLATBUFFERS_CONSTEXPR_CPP11 const char *GetFullyQualifiedName() {
+ return "HandFan";
+ }
+ enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE {
+ VT_LENGTH = 4
+ };
+ int32_t length() const {
+ return GetField<int32_t>(VT_LENGTH, 0);
+ }
+ bool mutate_length(int32_t _length = 0) {
+ return SetField<int32_t>(VT_LENGTH, _length, 0);
+ }
+ bool Verify(flatbuffers::Verifier &verifier) const {
+ return VerifyTableStart(verifier) &&
+ VerifyField<int32_t>(verifier, VT_LENGTH, 4) &&
+ verifier.EndTable();
+ }
+ HandFanT *UnPack(const flatbuffers::resolver_function_t *_resolver = nullptr) const;
+ void UnPackTo(HandFanT *_o, const flatbuffers::resolver_function_t *_resolver = nullptr) const;
+ static flatbuffers::Offset<HandFan> Pack(flatbuffers::FlatBufferBuilder &_fbb, const HandFanT* _o, const flatbuffers::rehasher_function_t *_rehasher = nullptr);
+};
+
+struct HandFanBuilder {
+ typedef HandFan Table;
+ flatbuffers::FlatBufferBuilder &fbb_;
+ flatbuffers::uoffset_t start_;
+ void add_length(int32_t length) {
+ fbb_.AddElement<int32_t>(HandFan::VT_LENGTH, length, 0);
+ }
+ explicit HandFanBuilder(flatbuffers::FlatBufferBuilder &_fbb)
+ : fbb_(_fbb) {
+ start_ = fbb_.StartTable();
+ }
+ flatbuffers::Offset<HandFan> Finish() {
+ const auto end = fbb_.EndTable(start_);
+ auto o = flatbuffers::Offset<HandFan>(end);
+ return o;
}
};
-inline bool operator==(const MovieT &lhs, const MovieT &rhs) {
- return
- (lhs.main_character == rhs.main_character) &&
- (lhs.characters == rhs.characters);
+inline flatbuffers::Offset<HandFan> CreateHandFan(
+ flatbuffers::FlatBufferBuilder &_fbb,
+ int32_t length = 0) {
+ HandFanBuilder builder_(_fbb);
+ builder_.add_length(length);
+ return builder_.Finish();
}
-inline bool operator!=(const MovieT &lhs, const MovieT &rhs) {
- return !(lhs == rhs);
-}
+flatbuffers::Offset<HandFan> CreateHandFan(flatbuffers::FlatBufferBuilder &_fbb, const HandFanT *_o, const flatbuffers::rehasher_function_t *_rehasher = nullptr);
+struct MovieT : public flatbuffers::NativeTable {
+ typedef Movie TableType;
+ static FLATBUFFERS_CONSTEXPR_CPP11 const char *GetFullyQualifiedName() {
+ return "MovieT";
+ }
+ CharacterUnion main_character{};
+ std::vector<CharacterUnion> characters{};
+};
struct Movie FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
typedef MovieT NativeTableType;
@@ -371,7 +592,7 @@
static const flatbuffers::TypeTable *MiniReflectTypeTable() {
return MovieTypeTable();
}
- static FLATBUFFERS_CONSTEXPR const char *GetFullyQualifiedName() {
+ static FLATBUFFERS_CONSTEXPR_CPP11 const char *GetFullyQualifiedName() {
return "Movie";
}
enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE {
@@ -421,7 +642,7 @@
}
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
- VerifyField<uint8_t>(verifier, VT_MAIN_CHARACTER_TYPE) &&
+ VerifyField<uint8_t>(verifier, VT_MAIN_CHARACTER_TYPE, 1) &&
VerifyOffset(verifier, VT_MAIN_CHARACTER) &&
VerifyCharacter(verifier, main_character(), main_character_type()) &&
VerifyOffset(verifier, VT_CHARACTERS_TYPE) &&
@@ -495,8 +716,19 @@
flatbuffers::Offset<Movie> CreateMovie(flatbuffers::FlatBufferBuilder &_fbb, const MovieT *_o, const flatbuffers::rehasher_function_t *_rehasher = nullptr);
+
+inline bool operator==(const AttackerT &lhs, const AttackerT &rhs) {
+ return
+ (lhs.sword_attack_damage == rhs.sword_attack_damage);
+}
+
+inline bool operator!=(const AttackerT &lhs, const AttackerT &rhs) {
+ return !(lhs == rhs);
+}
+
+
inline AttackerT *Attacker::UnPack(const flatbuffers::resolver_function_t *_resolver) const {
- flatbuffers::unique_ptr<AttackerT> _o = flatbuffers::unique_ptr<AttackerT>(new AttackerT());
+ auto _o = std::unique_ptr<AttackerT>(new AttackerT());
UnPackTo(_o.get(), _resolver);
return _o.release();
}
@@ -521,8 +753,57 @@
_sword_attack_damage);
}
+
+inline bool operator==(const HandFanT &lhs, const HandFanT &rhs) {
+ return
+ (lhs.length == rhs.length);
+}
+
+inline bool operator!=(const HandFanT &lhs, const HandFanT &rhs) {
+ return !(lhs == rhs);
+}
+
+
+inline HandFanT *HandFan::UnPack(const flatbuffers::resolver_function_t *_resolver) const {
+ auto _o = std::unique_ptr<HandFanT>(new HandFanT());
+ UnPackTo(_o.get(), _resolver);
+ return _o.release();
+}
+
+inline void HandFan::UnPackTo(HandFanT *_o, const flatbuffers::resolver_function_t *_resolver) const {
+ (void)_o;
+ (void)_resolver;
+ { auto _e = length(); _o->length = _e; }
+}
+
+inline flatbuffers::Offset<HandFan> HandFan::Pack(flatbuffers::FlatBufferBuilder &_fbb, const HandFanT* _o, const flatbuffers::rehasher_function_t *_rehasher) {
+ return CreateHandFan(_fbb, _o, _rehasher);
+}
+
+inline flatbuffers::Offset<HandFan> CreateHandFan(flatbuffers::FlatBufferBuilder &_fbb, const HandFanT *_o, const flatbuffers::rehasher_function_t *_rehasher) {
+ (void)_rehasher;
+ (void)_o;
+ struct _VectorArgs { flatbuffers::FlatBufferBuilder *__fbb; const HandFanT* __o; const flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va;
+ auto _length = _o->length;
+ return CreateHandFan(
+ _fbb,
+ _length);
+}
+
+
+inline bool operator==(const MovieT &lhs, const MovieT &rhs) {
+ return
+ (lhs.main_character == rhs.main_character) &&
+ (lhs.characters == rhs.characters);
+}
+
+inline bool operator!=(const MovieT &lhs, const MovieT &rhs) {
+ return !(lhs == rhs);
+}
+
+
inline MovieT *Movie::UnPack(const flatbuffers::resolver_function_t *_resolver) const {
- flatbuffers::unique_ptr<MovieT> _o = flatbuffers::unique_ptr<MovieT>(new MovieT());
+ auto _o = std::unique_ptr<MovieT>(new MovieT());
UnPackTo(_o.get(), _resolver);
return _o.release();
}
@@ -566,13 +847,13 @@
return verifier.VerifyTable(ptr);
}
case Character_Rapunzel: {
- return verifier.Verify<Rapunzel>(static_cast<const uint8_t *>(obj), 0);
+ return verifier.VerifyField<Rapunzel>(static_cast<const uint8_t *>(obj), 0, 4);
}
case Character_Belle: {
- return verifier.Verify<BookReader>(static_cast<const uint8_t *>(obj), 0);
+ return verifier.VerifyField<BookReader>(static_cast<const uint8_t *>(obj), 0, 4);
}
case Character_BookFan: {
- return verifier.Verify<BookReader>(static_cast<const uint8_t *>(obj), 0);
+ return verifier.VerifyField<BookReader>(static_cast<const uint8_t *>(obj), 0, 4);
}
case Character_Other: {
auto ptr = reinterpret_cast<const flatbuffers::String *>(obj);
@@ -599,6 +880,7 @@
}
inline void *CharacterUnion::UnPack(const void *obj, Character type, const flatbuffers::resolver_function_t *resolver) {
+ (void)resolver;
switch (type) {
case Character_MuLan: {
auto ptr = reinterpret_cast<const Attacker *>(obj);
@@ -629,6 +911,7 @@
}
inline flatbuffers::Offset<void> CharacterUnion::Pack(flatbuffers::FlatBufferBuilder &_fbb, const flatbuffers::rehasher_function_t *_rehasher) const {
+ (void)_rehasher;
switch (type) {
case Character_MuLan: {
auto ptr = reinterpret_cast<const AttackerT *>(value);
@@ -727,6 +1010,97 @@
type = Character_NONE;
}
+inline bool VerifyGadget(flatbuffers::Verifier &verifier, const void *obj, Gadget type) {
+ switch (type) {
+ case Gadget_NONE: {
+ return true;
+ }
+ case Gadget_FallingTub: {
+ return verifier.VerifyField<FallingTub>(static_cast<const uint8_t *>(obj), 0, 4);
+ }
+ case Gadget_HandFan: {
+ auto ptr = reinterpret_cast<const HandFan *>(obj);
+ return verifier.VerifyTable(ptr);
+ }
+ default: return true;
+ }
+}
+
+inline bool VerifyGadgetVector(flatbuffers::Verifier &verifier, const flatbuffers::Vector<flatbuffers::Offset<void>> *values, const flatbuffers::Vector<uint8_t> *types) {
+ if (!values || !types) return !values && !types;
+ if (values->size() != types->size()) return false;
+ for (flatbuffers::uoffset_t i = 0; i < values->size(); ++i) {
+ if (!VerifyGadget(
+ verifier, values->Get(i), types->GetEnum<Gadget>(i))) {
+ return false;
+ }
+ }
+ return true;
+}
+
+inline void *GadgetUnion::UnPack(const void *obj, Gadget type, const flatbuffers::resolver_function_t *resolver) {
+ (void)resolver;
+ switch (type) {
+ case Gadget_FallingTub: {
+ auto ptr = reinterpret_cast<const FallingTub *>(obj);
+ return new FallingTub(*ptr);
+ }
+ case Gadget_HandFan: {
+ auto ptr = reinterpret_cast<const HandFan *>(obj);
+ return ptr->UnPack(resolver);
+ }
+ default: return nullptr;
+ }
+}
+
+inline flatbuffers::Offset<void> GadgetUnion::Pack(flatbuffers::FlatBufferBuilder &_fbb, const flatbuffers::rehasher_function_t *_rehasher) const {
+ (void)_rehasher;
+ switch (type) {
+ case Gadget_FallingTub: {
+ auto ptr = reinterpret_cast<const FallingTub *>(value);
+ return _fbb.CreateStruct(*ptr).Union();
+ }
+ case Gadget_HandFan: {
+ auto ptr = reinterpret_cast<const HandFanT *>(value);
+ return CreateHandFan(_fbb, ptr, _rehasher).Union();
+ }
+ default: return 0;
+ }
+}
+
+inline GadgetUnion::GadgetUnion(const GadgetUnion &u) : type(u.type), value(nullptr) {
+ switch (type) {
+ case Gadget_FallingTub: {
+ value = new FallingTub(*reinterpret_cast<FallingTub *>(u.value));
+ break;
+ }
+ case Gadget_HandFan: {
+ value = new HandFanT(*reinterpret_cast<HandFanT *>(u.value));
+ break;
+ }
+ default:
+ break;
+ }
+}
+
+inline void GadgetUnion::Reset() {
+ switch (type) {
+ case Gadget_FallingTub: {
+ auto ptr = reinterpret_cast<FallingTub *>(value);
+ delete ptr;
+ break;
+ }
+ case Gadget_HandFan: {
+ auto ptr = reinterpret_cast<HandFanT *>(value);
+ delete ptr;
+ break;
+ }
+ default: break;
+ }
+ value = nullptr;
+ type = Gadget_NONE;
+}
+
inline const flatbuffers::TypeTable *CharacterTypeTable() {
static const flatbuffers::TypeCode type_codes[] = {
{ flatbuffers::ET_SEQUENCE, 0, -1 },
@@ -757,6 +1131,27 @@
return &tt;
}
+inline const flatbuffers::TypeTable *GadgetTypeTable() {
+ static const flatbuffers::TypeCode type_codes[] = {
+ { flatbuffers::ET_SEQUENCE, 0, -1 },
+ { flatbuffers::ET_SEQUENCE, 0, 0 },
+ { flatbuffers::ET_SEQUENCE, 0, 1 }
+ };
+ static const flatbuffers::TypeFunction type_refs[] = {
+ FallingTubTypeTable,
+ HandFanTypeTable
+ };
+ static const char * const names[] = {
+ "NONE",
+ "FallingTub",
+ "HandFan"
+ };
+ static const flatbuffers::TypeTable tt = {
+ flatbuffers::ST_UNION, 3, type_codes, type_refs, nullptr, nullptr, names
+ };
+ return &tt;
+}
+
inline const flatbuffers::TypeTable *AttackerTypeTable() {
static const flatbuffers::TypeCode type_codes[] = {
{ flatbuffers::ET_INT, 0, -1 }
@@ -798,6 +1193,33 @@
return &tt;
}
+inline const flatbuffers::TypeTable *FallingTubTypeTable() {
+ static const flatbuffers::TypeCode type_codes[] = {
+ { flatbuffers::ET_INT, 0, -1 }
+ };
+ static const int64_t values[] = { 0, 4 };
+ static const char * const names[] = {
+ "weight"
+ };
+ static const flatbuffers::TypeTable tt = {
+ flatbuffers::ST_STRUCT, 1, type_codes, nullptr, nullptr, values, names
+ };
+ return &tt;
+}
+
+inline const flatbuffers::TypeTable *HandFanTypeTable() {
+ static const flatbuffers::TypeCode type_codes[] = {
+ { flatbuffers::ET_INT, 0, -1 }
+ };
+ static const char * const names[] = {
+ "length"
+ };
+ static const flatbuffers::TypeTable tt = {
+ flatbuffers::ST_TABLE, 1, type_codes, nullptr, nullptr, nullptr, names
+ };
+ return &tt;
+}
+
inline const flatbuffers::TypeTable *MovieTypeTable() {
static const flatbuffers::TypeCode type_codes[] = {
{ flatbuffers::ET_UTYPE, 0, 0 },
@@ -832,6 +1254,10 @@
return flatbuffers::GetMutableRoot<Movie>(buf);
}
+inline Movie *GetMutableSizePrefixedMovie(void *buf) {
+ return flatbuffers::GetMutableSizePrefixedRoot<Movie>(buf);
+}
+
inline const char *MovieIdentifier() {
return "MOVI";
}
@@ -841,6 +1267,11 @@
buf, MovieIdentifier());
}
+inline bool SizePrefixedMovieBufferHasIdentifier(const void *buf) {
+ return flatbuffers::BufferHasIdentifier(
+ buf, MovieIdentifier(), true);
+}
+
inline bool VerifyMovieBuffer(
flatbuffers::Verifier &verifier) {
return verifier.VerifyBuffer<Movie>(MovieIdentifier());
diff --git a/tests/union_vector/union_vector_generated.js b/tests/union_vector/union_vector_generated.js
deleted file mode 100644
index 9e8b76e..0000000
--- a/tests/union_vector/union_vector_generated.js
+++ /dev/null
@@ -1,522 +0,0 @@
-// automatically generated by the FlatBuffers compiler, do not modify
-
-/**
- * @enum {number}
- */
-var Character = {
- NONE: 0,
- MuLan: 1,
- Rapunzel: 2,
- Belle: 3,
- BookFan: 4,
- Other: 5,
- Unused: 6
-};
-
-/**
- * @enum {string}
- */
-var CharacterName = {
- '0': 'NONE',
- '1': 'MuLan',
- '2': 'Rapunzel',
- '3': 'Belle',
- '4': 'BookFan',
- '5': 'Other',
- '6': 'Unused'
-};
-
-/**
- * @constructor
- */
-function Attacker() {
- /**
- * @type {flatbuffers.ByteBuffer}
- */
- this.bb = null;
-
- /**
- * @type {number}
- */
- this.bb_pos = 0;
-}
-
-/**
- * @param {number} i
- * @param {flatbuffers.ByteBuffer} bb
- * @returns {Attacker}
- */
-Attacker.prototype.__init = function(i, bb) {
- this.bb_pos = i;
- this.bb = bb;
- return this;
-};
-
-/**
- * @param {flatbuffers.ByteBuffer} bb
- * @param {Attacker=} obj
- * @returns {Attacker}
- */
-Attacker.getRootAsAttacker = function(bb, obj) {
- return (obj || new Attacker).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param {flatbuffers.ByteBuffer} bb
- * @param {Attacker=} obj
- * @returns {Attacker}
- */
-Attacker.getSizePrefixedRootAsAttacker = function(bb, obj) {
- bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
- return (obj || new Attacker).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @returns {number}
- */
-Attacker.prototype.swordAttackDamage = function() {
- var offset = this.bb.__offset(this.bb_pos, 4);
- return offset ? this.bb.readInt32(this.bb_pos + offset) : 0;
-};
-
-/**
- * @param {number} value
- * @returns {boolean}
- */
-Attacker.prototype.mutate_sword_attack_damage = function(value) {
- var offset = this.bb.__offset(this.bb_pos, 4);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb.writeInt32(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @returns {string}
- */
-Attacker.getFullyQualifiedName = function() {
- return 'Attacker';
-}
-
-/**
- * @param {flatbuffers.Builder} builder
- */
-Attacker.startAttacker = function(builder) {
- builder.startObject(1);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} swordAttackDamage
- */
-Attacker.addSwordAttackDamage = function(builder, swordAttackDamage) {
- builder.addFieldInt32(0, swordAttackDamage, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @returns {flatbuffers.Offset}
- */
-Attacker.endAttacker = function(builder) {
- var offset = builder.endObject();
- return offset;
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} swordAttackDamage
- * @returns {flatbuffers.Offset}
- */
-Attacker.createAttacker = function(builder, swordAttackDamage) {
- Attacker.startAttacker(builder);
- Attacker.addSwordAttackDamage(builder, swordAttackDamage);
- return Attacker.endAttacker(builder);
-}
-
-/**
- * @constructor
- */
-function Rapunzel() {
- /**
- * @type {flatbuffers.ByteBuffer}
- */
- this.bb = null;
-
- /**
- * @type {number}
- */
- this.bb_pos = 0;
-}
-
-/**
- * @param {number} i
- * @param {flatbuffers.ByteBuffer} bb
- * @returns {Rapunzel}
- */
-Rapunzel.prototype.__init = function(i, bb) {
- this.bb_pos = i;
- this.bb = bb;
- return this;
-};
-
-/**
- * @returns {number}
- */
-Rapunzel.prototype.hairLength = function() {
- return this.bb.readInt32(this.bb_pos);
-};
-
-/**
- * @param {number} value
- * @returns {boolean}
- */
-Rapunzel.prototype.mutate_hair_length = function(value) {
- this.bb.writeInt32(this.bb_pos + 0, value);
- return true;
-};
-
-/**
- * @returns {string}
- */
-Rapunzel.getFullyQualifiedName = function() {
- return 'Rapunzel';
-}
-
-/**
- * @returns {number}
- */
-Rapunzel.sizeOf = function() {
- return 4;
-}
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} hair_length
- * @returns {flatbuffers.Offset}
- */
-Rapunzel.createRapunzel = function(builder, hair_length) {
- builder.prep(4, 4);
- builder.writeInt32(hair_length);
- return builder.offset();
-};
-
-/**
- * @constructor
- */
-function BookReader() {
- /**
- * @type {flatbuffers.ByteBuffer}
- */
- this.bb = null;
-
- /**
- * @type {number}
- */
- this.bb_pos = 0;
-}
-
-/**
- * @param {number} i
- * @param {flatbuffers.ByteBuffer} bb
- * @returns {BookReader}
- */
-BookReader.prototype.__init = function(i, bb) {
- this.bb_pos = i;
- this.bb = bb;
- return this;
-};
-
-/**
- * @returns {number}
- */
-BookReader.prototype.booksRead = function() {
- return this.bb.readInt32(this.bb_pos);
-};
-
-/**
- * @param {number} value
- * @returns {boolean}
- */
-BookReader.prototype.mutate_books_read = function(value) {
- this.bb.writeInt32(this.bb_pos + 0, value);
- return true;
-};
-
-/**
- * @returns {string}
- */
-BookReader.getFullyQualifiedName = function() {
- return 'BookReader';
-}
-
-/**
- * @returns {number}
- */
-BookReader.sizeOf = function() {
- return 4;
-}
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} books_read
- * @returns {flatbuffers.Offset}
- */
-BookReader.createBookReader = function(builder, books_read) {
- builder.prep(4, 4);
- builder.writeInt32(books_read);
- return builder.offset();
-};
-
-/**
- * @constructor
- */
-function Movie() {
- /**
- * @type {flatbuffers.ByteBuffer}
- */
- this.bb = null;
-
- /**
- * @type {number}
- */
- this.bb_pos = 0;
-}
-
-/**
- * @param {number} i
- * @param {flatbuffers.ByteBuffer} bb
- * @returns {Movie}
- */
-Movie.prototype.__init = function(i, bb) {
- this.bb_pos = i;
- this.bb = bb;
- return this;
-};
-
-/**
- * @param {flatbuffers.ByteBuffer} bb
- * @param {Movie=} obj
- * @returns {Movie}
- */
-Movie.getRootAsMovie = function(bb, obj) {
- return (obj || new Movie).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param {flatbuffers.ByteBuffer} bb
- * @param {Movie=} obj
- * @returns {Movie}
- */
-Movie.getSizePrefixedRootAsMovie = function(bb, obj) {
- bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
- return (obj || new Movie).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param {flatbuffers.ByteBuffer} bb
- * @returns {boolean}
- */
-Movie.bufferHasIdentifier = function(bb) {
- return bb.__has_identifier('MOVI');
-};
-
-/**
- * @returns {Character}
- */
-Movie.prototype.mainCharacterType = function() {
- var offset = this.bb.__offset(this.bb_pos, 4);
- return offset ? /** @type {Character} */ (this.bb.readUint8(this.bb_pos + offset)) : Character.NONE;
-};
-
-/**
- * @param {flatbuffers.Table} obj
- * @returns {?flatbuffers.Table}
- */
-Movie.prototype.mainCharacter = function(obj) {
- var offset = this.bb.__offset(this.bb_pos, 6);
- return offset ? this.bb.__union(obj, this.bb_pos + offset) : null;
-};
-
-/**
- * @param {number} index
- * @returns {Character}
- */
-Movie.prototype.charactersType = function(index) {
- var offset = this.bb.__offset(this.bb_pos, 8);
- return offset ? /** @type {Character} */ (this.bb.readUint8(this.bb.__vector(this.bb_pos + offset) + index)) : /** @type {Character} */ (0);
-};
-
-/**
- * @returns {number}
- */
-Movie.prototype.charactersTypeLength = function() {
- var offset = this.bb.__offset(this.bb_pos, 8);
- return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
-};
-
-/**
- * @returns {Uint8Array}
- */
-Movie.prototype.charactersTypeArray = function() {
- var offset = this.bb.__offset(this.bb_pos, 8);
- return offset ? new Uint8Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null;
-};
-
-/**
- * @param {number} index
- * @param {flatbuffers.Table=} obj
- * @returns {?flatbuffers.Table}
- */
-Movie.prototype.characters = function(index, obj) {
- var offset = this.bb.__offset(this.bb_pos, 10);
- return offset ? this.bb.__union(obj, this.bb.__vector(this.bb_pos + offset) + index * 4) : null;
-};
-
-/**
- * @returns {number}
- */
-Movie.prototype.charactersLength = function() {
- var offset = this.bb.__offset(this.bb_pos, 10);
- return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
-};
-
-/**
- * @returns {string}
- */
-Movie.getFullyQualifiedName = function() {
- return 'Movie';
-}
-
-/**
- * @param {flatbuffers.Builder} builder
- */
-Movie.startMovie = function(builder) {
- builder.startObject(4);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {Character} mainCharacterType
- */
-Movie.addMainCharacterType = function(builder, mainCharacterType) {
- builder.addFieldInt8(0, mainCharacterType, Character.NONE);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Offset} mainCharacterOffset
- */
-Movie.addMainCharacter = function(builder, mainCharacterOffset) {
- builder.addFieldOffset(1, mainCharacterOffset, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Offset} charactersTypeOffset
- */
-Movie.addCharactersType = function(builder, charactersTypeOffset) {
- builder.addFieldOffset(2, charactersTypeOffset, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {Array.<Character>} data
- * @returns {flatbuffers.Offset}
- */
-Movie.createCharactersTypeVector = function(builder, data) {
- builder.startVector(1, data.length, 1);
- for (var i = data.length - 1; i >= 0; i--) {
- builder.addInt8(data[i]);
- }
- return builder.endVector();
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} numElems
- */
-Movie.startCharactersTypeVector = function(builder, numElems) {
- builder.startVector(1, numElems, 1);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Offset} charactersOffset
- */
-Movie.addCharacters = function(builder, charactersOffset) {
- builder.addFieldOffset(3, charactersOffset, 0);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {Array.<flatbuffers.Offset>} data
- * @returns {flatbuffers.Offset}
- */
-Movie.createCharactersVector = function(builder, data) {
- builder.startVector(4, data.length, 4);
- for (var i = data.length - 1; i >= 0; i--) {
- builder.addOffset(data[i]);
- }
- return builder.endVector();
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {number} numElems
- */
-Movie.startCharactersVector = function(builder, numElems) {
- builder.startVector(4, numElems, 4);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @returns {flatbuffers.Offset}
- */
-Movie.endMovie = function(builder) {
- var offset = builder.endObject();
- return offset;
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Offset} offset
- */
-Movie.finishMovieBuffer = function(builder, offset) {
- builder.finish(offset, 'MOVI');
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {flatbuffers.Offset} offset
- */
-Movie.finishSizePrefixedMovieBuffer = function(builder, offset) {
- builder.finish(offset, 'MOVI', true);
-};
-
-/**
- * @param {flatbuffers.Builder} builder
- * @param {Character} mainCharacterType
- * @param {flatbuffers.Offset} mainCharacterOffset
- * @param {flatbuffers.Offset} charactersTypeOffset
- * @param {flatbuffers.Offset} charactersOffset
- * @returns {flatbuffers.Offset}
- */
-Movie.createMovie = function(builder, mainCharacterType, mainCharacterOffset, charactersTypeOffset, charactersOffset) {
- Movie.startMovie(builder);
- Movie.addMainCharacterType(builder, mainCharacterType);
- Movie.addMainCharacter(builder, mainCharacterOffset);
- Movie.addCharactersType(builder, charactersTypeOffset);
- Movie.addCharacters(builder, charactersOffset);
- return Movie.endMovie(builder);
-}
-
-// Exports for Node.js and RequireJS
-this.Character = Character;
-this.CharacterName = CharacterName;
-this.Attacker = Attacker;
-this.Rapunzel = Rapunzel;
-this.BookReader = BookReader;
-this.Movie = Movie;
diff --git a/tests/union_vector/union_vector_generated.ts b/tests/union_vector/union_vector_generated.ts
deleted file mode 100644
index 806c07f..0000000
--- a/tests/union_vector/union_vector_generated.ts
+++ /dev/null
@@ -1,690 +0,0 @@
-// automatically generated by the FlatBuffers compiler, do not modify
-
-import * as flatbuffers from 'flatbuffers';
-/**
- * @enum {number}
- */
-export enum Character{
- NONE= 0,
- MuLan= 1,
- Rapunzel= 2,
- Belle= 3,
- BookFan= 4,
- Other= 5,
- Unused= 6
-};
-
-export function unionToCharacter(
- type: Character,
- accessor: (obj:Attacker|BookReader|Rapunzel|string) => Attacker|BookReader|Rapunzel|string|null
-): Attacker|BookReader|Rapunzel|string|null {
- switch(Character[type]) {
- case 'NONE': return null;
- case 'MuLan': return accessor(new Attacker())! as Attacker;
- case 'Rapunzel': return accessor(new Rapunzel())! as Rapunzel;
- case 'Belle': return accessor(new BookReader())! as BookReader;
- case 'BookFan': return accessor(new BookReader())! as BookReader;
- case 'Other': return accessor('') as string;
- case 'Unused': return accessor('') as string;
- default: return null;
- }
-}
-
-export function unionListToCharacter(
- type: Character,
- accessor: (index: number, obj:Attacker|BookReader|Rapunzel|string) => Attacker|BookReader|Rapunzel|string|null,
- index: number
-): Attacker|BookReader|Rapunzel|string|null {
- switch(Character[type]) {
- case 'NONE': return null;
- case 'MuLan': return accessor(index, new Attacker())! as Attacker;
- case 'Rapunzel': return accessor(index, new Rapunzel())! as Rapunzel;
- case 'Belle': return accessor(index, new BookReader())! as BookReader;
- case 'BookFan': return accessor(index, new BookReader())! as BookReader;
- case 'Other': return accessor(index, '') as string;
- case 'Unused': return accessor(index, '') as string;
- default: return null;
- }
-}
-
-/**
- * @constructor
- */
-export class Attacker {
- bb: flatbuffers.ByteBuffer|null = null;
-
- bb_pos:number = 0;
-/**
- * @param number i
- * @param flatbuffers.ByteBuffer bb
- * @returns Attacker
- */
-__init(i:number, bb:flatbuffers.ByteBuffer):Attacker {
- this.bb_pos = i;
- this.bb = bb;
- return this;
-};
-
-/**
- * @param flatbuffers.ByteBuffer bb
- * @param Attacker= obj
- * @returns Attacker
- */
-static getRootAsAttacker(bb:flatbuffers.ByteBuffer, obj?:Attacker):Attacker {
- return (obj || new Attacker()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param flatbuffers.ByteBuffer bb
- * @param Attacker= obj
- * @returns Attacker
- */
-static getSizePrefixedRootAsAttacker(bb:flatbuffers.ByteBuffer, obj?:Attacker):Attacker {
- bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
- return (obj || new Attacker()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @returns number
- */
-swordAttackDamage():number {
- var offset = this.bb!.__offset(this.bb_pos, 4);
- return offset ? this.bb!.readInt32(this.bb_pos + offset) : 0;
-};
-
-/**
- * @param number value
- * @returns boolean
- */
-mutate_sword_attack_damage(value:number):boolean {
- var offset = this.bb!.__offset(this.bb_pos, 4);
-
- if (offset === 0) {
- return false;
- }
-
- this.bb!.writeInt32(this.bb_pos + offset, value);
- return true;
-};
-
-/**
- * @returns string
- */
-static getFullyQualifiedName():string {
- return 'Attacker';
-}
-
-/**
- * @param flatbuffers.Builder builder
- */
-static startAttacker(builder:flatbuffers.Builder) {
- builder.startObject(1);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number swordAttackDamage
- */
-static addSwordAttackDamage(builder:flatbuffers.Builder, swordAttackDamage:number) {
- builder.addFieldInt32(0, swordAttackDamage, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @returns flatbuffers.Offset
- */
-static endAttacker(builder:flatbuffers.Builder):flatbuffers.Offset {
- var offset = builder.endObject();
- return offset;
-};
-
-static createAttacker(builder:flatbuffers.Builder, swordAttackDamage:number):flatbuffers.Offset {
- Attacker.startAttacker(builder);
- Attacker.addSwordAttackDamage(builder, swordAttackDamage);
- return Attacker.endAttacker(builder);
-}
-
-/**
- * @returns AttackerT
- */
-unpack(): AttackerT {
- return new AttackerT(
- this.swordAttackDamage()
- );
-};
-
-/**
- * @param AttackerT _o
- */
-unpackTo(_o: AttackerT): void {
- _o.swordAttackDamage = this.swordAttackDamage();
-};
-}
-
-export class AttackerT {
-/**
- * @constructor
- * @param number swordAttackDamage
- */
-constructor(
- public swordAttackDamage: number = 0
-){};
-
-/**
- * @param flatbuffers.Builder builder
- * @returns flatbuffers.Offset
- */
-pack(builder:flatbuffers.Builder): flatbuffers.Offset {
- return Attacker.createAttacker(builder,
- this.swordAttackDamage
- );
-};
-}
-/**
- * @constructor
- */
-export class Rapunzel {
- bb: flatbuffers.ByteBuffer|null = null;
-
- bb_pos:number = 0;
-/**
- * @param number i
- * @param flatbuffers.ByteBuffer bb
- * @returns Rapunzel
- */
-__init(i:number, bb:flatbuffers.ByteBuffer):Rapunzel {
- this.bb_pos = i;
- this.bb = bb;
- return this;
-};
-
-/**
- * @returns number
- */
-hairLength():number {
- return this.bb!.readInt32(this.bb_pos);
-};
-
-/**
- * @param number value
- * @returns boolean
- */
-mutate_hair_length(value:number):boolean {
- this.bb!.writeInt32(this.bb_pos + 0, value);
- return true;
-};
-
-/**
- * @returns string
- */
-static getFullyQualifiedName():string {
- return 'Rapunzel';
-}
-
-/**
- * @returns number
- */
-static sizeOf():number {
- return 4;
-}
-
-/**
- * @param flatbuffers.Builder builder
- * @param number hair_length
- * @returns flatbuffers.Offset
- */
-static createRapunzel(builder:flatbuffers.Builder, hair_length: number):flatbuffers.Offset {
- builder.prep(4, 4);
- builder.writeInt32(hair_length);
- return builder.offset();
-};
-
-
-/**
- * @returns RapunzelT
- */
-unpack(): RapunzelT {
- return new RapunzelT(
- this.hairLength()
- );
-};
-
-/**
- * @param RapunzelT _o
- */
-unpackTo(_o: RapunzelT): void {
- _o.hairLength = this.hairLength();
-};
-}
-
-export class RapunzelT {
-/**
- * @constructor
- * @param number hairLength
- */
-constructor(
- public hairLength: number = 0
-){};
-
-/**
- * @param flatbuffers.Builder builder
- * @returns flatbuffers.Offset
- */
-pack(builder:flatbuffers.Builder): flatbuffers.Offset {
- return Rapunzel.createRapunzel(builder,
- this.hairLength
- );
-};
-}
-/**
- * @constructor
- */
-export class BookReader {
- bb: flatbuffers.ByteBuffer|null = null;
-
- bb_pos:number = 0;
-/**
- * @param number i
- * @param flatbuffers.ByteBuffer bb
- * @returns BookReader
- */
-__init(i:number, bb:flatbuffers.ByteBuffer):BookReader {
- this.bb_pos = i;
- this.bb = bb;
- return this;
-};
-
-/**
- * @returns number
- */
-booksRead():number {
- return this.bb!.readInt32(this.bb_pos);
-};
-
-/**
- * @param number value
- * @returns boolean
- */
-mutate_books_read(value:number):boolean {
- this.bb!.writeInt32(this.bb_pos + 0, value);
- return true;
-};
-
-/**
- * @returns string
- */
-static getFullyQualifiedName():string {
- return 'BookReader';
-}
-
-/**
- * @returns number
- */
-static sizeOf():number {
- return 4;
-}
-
-/**
- * @param flatbuffers.Builder builder
- * @param number books_read
- * @returns flatbuffers.Offset
- */
-static createBookReader(builder:flatbuffers.Builder, books_read: number):flatbuffers.Offset {
- builder.prep(4, 4);
- builder.writeInt32(books_read);
- return builder.offset();
-};
-
-
-/**
- * @returns BookReaderT
- */
-unpack(): BookReaderT {
- return new BookReaderT(
- this.booksRead()
- );
-};
-
-/**
- * @param BookReaderT _o
- */
-unpackTo(_o: BookReaderT): void {
- _o.booksRead = this.booksRead();
-};
-}
-
-export class BookReaderT {
-/**
- * @constructor
- * @param number booksRead
- */
-constructor(
- public booksRead: number = 0
-){};
-
-/**
- * @param flatbuffers.Builder builder
- * @returns flatbuffers.Offset
- */
-pack(builder:flatbuffers.Builder): flatbuffers.Offset {
- return BookReader.createBookReader(builder,
- this.booksRead
- );
-};
-}
-/**
- * @constructor
- */
-export class Movie {
- bb: flatbuffers.ByteBuffer|null = null;
-
- bb_pos:number = 0;
-/**
- * @param number i
- * @param flatbuffers.ByteBuffer bb
- * @returns Movie
- */
-__init(i:number, bb:flatbuffers.ByteBuffer):Movie {
- this.bb_pos = i;
- this.bb = bb;
- return this;
-};
-
-/**
- * @param flatbuffers.ByteBuffer bb
- * @param Movie= obj
- * @returns Movie
- */
-static getRootAsMovie(bb:flatbuffers.ByteBuffer, obj?:Movie):Movie {
- return (obj || new Movie()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param flatbuffers.ByteBuffer bb
- * @param Movie= obj
- * @returns Movie
- */
-static getSizePrefixedRootAsMovie(bb:flatbuffers.ByteBuffer, obj?:Movie):Movie {
- bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
- return (obj || new Movie()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
-};
-
-/**
- * @param flatbuffers.ByteBuffer bb
- * @returns boolean
- */
-static bufferHasIdentifier(bb:flatbuffers.ByteBuffer):boolean {
- return bb.__has_identifier('MOVI');
-};
-
-/**
- * @returns Character
- */
-mainCharacterType():Character {
- var offset = this.bb!.__offset(this.bb_pos, 4);
- return offset ? /** */ (this.bb!.readUint8(this.bb_pos + offset)) : Character.NONE;
-};
-
-/**
- * @param flatbuffers.Table obj
- * @returns ?flatbuffers.Table
- */
-mainCharacter<T extends flatbuffers.Table>(obj:T|string):T|string|null {
- var offset = this.bb!.__offset(this.bb_pos, 6);
- return offset ? this.bb!.__union_with_string(obj, this.bb_pos + offset) : null;
-};
-
-/**
- * @param number index
- * @returns Character
- */
-charactersType(index: number):Character|null {
- var offset = this.bb!.__offset(this.bb_pos, 8);
- return offset ? /** */ (this.bb!.readUint8(this.bb!.__vector(this.bb_pos + offset) + index)) : /** */ (0);
-};
-
-/**
- * @returns number
- */
-charactersTypeLength():number {
- var offset = this.bb!.__offset(this.bb_pos, 8);
- return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
-};
-
-/**
- * @returns Uint8Array
- */
-charactersTypeArray():Uint8Array|null {
- var offset = this.bb!.__offset(this.bb_pos, 8);
- return offset ? new Uint8Array(this.bb!.bytes().buffer, this.bb!.bytes().byteOffset + this.bb!.__vector(this.bb_pos + offset), this.bb!.__vector_len(this.bb_pos + offset)) : null;
-};
-
-/**
- * @param number index
- * @param flatbuffers.Table= obj
- * @returns ?flatbuffers.Table
- */
-characters<T extends flatbuffers.Table>(index: number, obj:T|string):T|string|null {
- var offset = this.bb!.__offset(this.bb_pos, 10);
- return offset ? this.bb!.__union_with_string(obj, this.bb!.__vector(this.bb_pos + offset) + index * 4) : null;
-};
-
-/**
- * @returns number
- */
-charactersLength():number {
- var offset = this.bb!.__offset(this.bb_pos, 10);
- return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
-};
-
-/**
- * @returns string
- */
-static getFullyQualifiedName():string {
- return 'Movie';
-}
-
-/**
- * @param flatbuffers.Builder builder
- */
-static startMovie(builder:flatbuffers.Builder) {
- builder.startObject(4);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param Character mainCharacterType
- */
-static addMainCharacterType(builder:flatbuffers.Builder, mainCharacterType:Character) {
- builder.addFieldInt8(0, mainCharacterType, Character.NONE);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Offset mainCharacterOffset
- */
-static addMainCharacter(builder:flatbuffers.Builder, mainCharacterOffset:flatbuffers.Offset) {
- builder.addFieldOffset(1, mainCharacterOffset, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Offset charactersTypeOffset
- */
-static addCharactersType(builder:flatbuffers.Builder, charactersTypeOffset:flatbuffers.Offset) {
- builder.addFieldOffset(2, charactersTypeOffset, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param Array.<Character> data
- * @returns flatbuffers.Offset
- */
-static createCharactersTypeVector(builder:flatbuffers.Builder, data:Character[]):flatbuffers.Offset {
- builder.startVector(1, data.length, 1);
- for (var i = data.length - 1; i >= 0; i--) {
- builder.addInt8(data[i]);
- }
- return builder.endVector();
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number numElems
- */
-static startCharactersTypeVector(builder:flatbuffers.Builder, numElems:number) {
- builder.startVector(1, numElems, 1);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Offset charactersOffset
- */
-static addCharacters(builder:flatbuffers.Builder, charactersOffset:flatbuffers.Offset) {
- builder.addFieldOffset(3, charactersOffset, 0);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param Array.<flatbuffers.Offset> data
- * @returns flatbuffers.Offset
- */
-static createCharactersVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset {
- builder.startVector(4, data.length, 4);
- for (var i = data.length - 1; i >= 0; i--) {
- builder.addOffset(data[i]);
- }
- return builder.endVector();
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param number numElems
- */
-static startCharactersVector(builder:flatbuffers.Builder, numElems:number) {
- builder.startVector(4, numElems, 4);
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @returns flatbuffers.Offset
- */
-static endMovie(builder:flatbuffers.Builder):flatbuffers.Offset {
- var offset = builder.endObject();
- return offset;
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Offset offset
- */
-static finishMovieBuffer(builder:flatbuffers.Builder, offset:flatbuffers.Offset) {
- builder.finish(offset, 'MOVI');
-};
-
-/**
- * @param flatbuffers.Builder builder
- * @param flatbuffers.Offset offset
- */
-static finishSizePrefixedMovieBuffer(builder:flatbuffers.Builder, offset:flatbuffers.Offset) {
- builder.finish(offset, 'MOVI', true);
-};
-
-static createMovie(builder:flatbuffers.Builder, mainCharacterType:Character, mainCharacterOffset:flatbuffers.Offset, charactersTypeOffset:flatbuffers.Offset, charactersOffset:flatbuffers.Offset):flatbuffers.Offset {
- Movie.startMovie(builder);
- Movie.addMainCharacterType(builder, mainCharacterType);
- Movie.addMainCharacter(builder, mainCharacterOffset);
- Movie.addCharactersType(builder, charactersTypeOffset);
- Movie.addCharacters(builder, charactersOffset);
- return Movie.endMovie(builder);
-}
-
-/**
- * @returns MovieT
- */
-unpack(): MovieT {
- return new MovieT(
- this.mainCharacterType(),
- (() => {
- let temp = unionToCharacter(this.mainCharacterType(), this.mainCharacter.bind(this));
- if(temp === null) { return null; }
- if(typeof temp === 'string') { return temp; }
- return temp.unpack()
- })(),
- this.bb!.createScalarList(this.charactersType.bind(this), this.charactersTypeLength()),
- (() => {
- let ret = [];
- for(let targetEnumIndex = 0; targetEnumIndex < this.charactersTypeLength(); ++targetEnumIndex) {
- let targetEnum = this.charactersType(targetEnumIndex);
- if(targetEnum === null || Character[targetEnum!] === 'NONE') { continue; }
-
- let temp = unionListToCharacter(targetEnum, this.characters.bind(this), targetEnumIndex);
- if(temp === null) { continue; }
- if(typeof temp === 'string') { ret.push(temp); continue; }
- ret.push(temp.unpack());
- }
- return ret;
- })()
- );
-};
-
-/**
- * @param MovieT _o
- */
-unpackTo(_o: MovieT): void {
- _o.mainCharacterType = this.mainCharacterType();
- _o.mainCharacter = (() => {
- let temp = unionToCharacter(this.mainCharacterType(), this.mainCharacter.bind(this));
- if(temp === null) { return null; }
- if(typeof temp === 'string') { return temp; }
- return temp.unpack()
- })();
- _o.charactersType = this.bb!.createScalarList(this.charactersType.bind(this), this.charactersTypeLength());
- _o.characters = (() => {
- let ret = [];
- for(let targetEnumIndex = 0; targetEnumIndex < this.charactersTypeLength(); ++targetEnumIndex) {
- let targetEnum = this.charactersType(targetEnumIndex);
- if(targetEnum === null || Character[targetEnum!] === 'NONE') { continue; }
-
- let temp = unionListToCharacter(targetEnum, this.characters.bind(this), targetEnumIndex);
- if(temp === null) { continue; }
- if(typeof temp === 'string') { ret.push(temp); continue; }
- ret.push(temp.unpack());
- }
- return ret;
- })();
-};
-}
-
-export class MovieT {
-/**
- * @constructor
- * @param Character mainCharacterType
- * @param AttackerT|BookReaderT|RapunzelT|string|null mainCharacter
- * @param (Character)[] charactersType
- * @param (AttackerT|BookReaderT|RapunzelT|string)[] characters
- */
-constructor(
- public mainCharacterType: Character = Character.NONE,
- public mainCharacter: AttackerT|BookReaderT|RapunzelT|string|null = null,
- public charactersType: (Character)[] = [],
- public characters: (AttackerT|BookReaderT|RapunzelT|string)[] = []
-){};
-
-/**
- * @param flatbuffers.Builder builder
- * @returns flatbuffers.Offset
- */
-pack(builder:flatbuffers.Builder): flatbuffers.Offset {
- const mainCharacter = builder.createObjectOffset(this.mainCharacter);
- const charactersType = Movie.createCharactersTypeVector(builder, this.charactersType);
- const characters = Movie.createCharactersVector(builder, builder.createObjectOffsetList(this.characters));
-
- return Movie.createMovie(builder,
- this.mainCharacterType,
- mainCharacter,
- charactersType,
- characters
- );
-};
-}
diff --git a/ts/BUILD.bazel b/ts/BUILD.bazel
new file mode 100644
index 0000000..605329e
--- /dev/null
+++ b/ts/BUILD.bazel
@@ -0,0 +1,39 @@
+load("@npm//@bazel/typescript:index.bzl", "ts_project")
+load("@build_bazel_rules_nodejs//:index.bzl", "js_library")
+
+ts_project(
+ name = "flatbuffers_ts",
+ srcs = [
+ "builder.ts",
+ "byte-buffer.ts",
+ "constants.ts",
+ "encoding.ts",
+ "index.ts",
+ "types.ts",
+ "utils.ts",
+ ],
+ declaration = True,
+ tsconfig = {
+ "compilerOptions": {
+ "module": "commonjs",
+ "declaration": True,
+ "moduleResolution": "node",
+ "lib": [
+ "ES2015",
+ "ES2020.BigInt",
+ "DOM",
+ ],
+ "types": ["node"],
+ "strict": True,
+ },
+ },
+ visibility = ["//visibility:public"],
+ deps = ["@npm//@types/node"],
+)
+
+js_library(
+ name = "flatbuffers",
+ package_name = "flatbuffers",
+ visibility = ["//visibility:public"],
+ deps = [":flatbuffers_ts"],
+)
diff --git a/ts/builder.ts b/ts/builder.ts
index 137031e..344a629 100644
--- a/ts/builder.ts
+++ b/ts/builder.ts
@@ -1,7 +1,6 @@
-import { ByteBuffer } from "./byte-buffer"
-import { SIZEOF_SHORT, SIZE_PREFIX_LENGTH, SIZEOF_INT, FILE_IDENTIFIER_LENGTH } from "./constants"
-import { Offset, IGeneratedObject } from "./types"
-import { Long } from "./long"
+import { ByteBuffer } from "./byte-buffer.js"
+import { SIZEOF_SHORT, SIZE_PREFIX_LENGTH, SIZEOF_INT, FILE_IDENTIFIER_LENGTH } from "./constants.js"
+import { Offset, IGeneratedObject } from "./types.js"
export class Builder {
private bb: ByteBuffer
@@ -136,7 +135,7 @@
this.bb.writeInt32(this.space -= 4, value);
}
- writeInt64(value: Long): void {
+ writeInt64(value: bigint): void {
this.bb.writeInt64(this.space -= 8, value);
}
@@ -179,7 +178,7 @@
* Add an `int64` to the buffer, properly aligned, and grows the buffer (if necessary).
* @param value The `int64` to add the the buffer.
*/
- addInt64(value: Long): void {
+ addInt64(value: bigint): void {
this.prep(8, 0);
this.writeInt64(value);
}
@@ -223,8 +222,8 @@
}
}
- addFieldInt64(voffset: number, value: Long, defaultValue: Long): void {
- if (this.force_defaults || !value.equals(defaultValue)) {
+ addFieldInt64(voffset: number, value: bigint, defaultValue: bigint): void {
+ if (this.force_defaults || value !== defaultValue) {
this.addInt64(value);
this.slot(voffset);
}
@@ -523,8 +522,11 @@
* @param s The string to encode
* @return The offset in the buffer where the encoded string starts
*/
- createString(s: string | Uint8Array): Offset {
- if (!s) { return 0 }
+ createString(s: string | Uint8Array | null | undefined): Offset {
+ if (s === null || s === undefined) {
+ return 0;
+ }
+
let utf8: string | Uint8Array | number[];
if (s instanceof Uint8Array) {
utf8 = s;
@@ -575,18 +577,11 @@
}
/**
- * A helper function to avoid generated code depending on this file directly.
- */
- createLong(low: number, high: number): Long {
- return Long.create(low, high);
- }
-
- /**
* A helper function to pack an object
*
* @returns offset of obj
*/
- createObjectOffset(obj: string | IGeneratedObject): Offset {
+ createObjectOffset(obj: string | any): Offset {
if(obj === null) {
return 0
}
@@ -603,7 +598,7 @@
*
* @returns list of offsets of each non null object
*/
- createObjectOffsetList(list: string[]): Offset[] {
+ createObjectOffsetList(list: string[] | any[]): Offset[] {
const ret: number[] = [];
for(let i = 0; i < list.length; ++i) {
@@ -620,7 +615,7 @@
return ret;
}
- createStructOffsetList(list: string[], startFunc: (builder: Builder, length: number) => void): Offset {
+ createStructOffsetList(list: string[] | any[], startFunc: (builder: Builder, length: number) => void): Offset {
startFunc(this, list.length);
this.createObjectOffsetList(list);
return this.endVector();
diff --git a/ts/byte-buffer.ts b/ts/byte-buffer.ts
index b936c7b..bb77f3b 100644
--- a/ts/byte-buffer.ts
+++ b/ts/byte-buffer.ts
@@ -1,8 +1,7 @@
-import { FILE_IDENTIFIER_LENGTH, SIZEOF_INT } from "./constants";
-import { Long } from "./long";
-import { int32, isLittleEndian, float32, float64 } from "./utils";
-import { Offset, Table, IGeneratedObject } from "./types";
-import { Encoding } from "./encoding";
+import { FILE_IDENTIFIER_LENGTH, SIZEOF_INT } from "./constants.js";
+import { int32, isLittleEndian, float32, float64 } from "./utils.js";
+import { Offset, Table, IGeneratedObject } from "./types.js";
+import { Encoding } from "./encoding.js";
export class ByteBuffer {
private position_ = 0;
@@ -75,12 +74,12 @@
return this.readInt32(offset) >>> 0;
}
- readInt64(offset: number): Long {
- return new Long(this.readInt32(offset), this.readInt32(offset + 4));
+ readInt64(offset: number): bigint {
+ return BigInt.asIntN(64, BigInt(this.readUint32(offset)) + (BigInt(this.readUint32(offset + 4)) << BigInt(32)));
}
- readUint64(offset: number): Long {
- return new Long(this.readUint32(offset), this.readUint32(offset + 4));
+ readUint64(offset: number): bigint {
+ return BigInt.asUintN(64, BigInt(this.readUint32(offset)) + (BigInt(this.readUint32(offset + 4)) << BigInt(32)));
}
readFloat32(offset: number): number {
@@ -108,8 +107,8 @@
}
writeUint16(offset: number, value: number): void {
- this.bytes_[offset] = value;
- this.bytes_[offset + 1] = value >> 8;
+ this.bytes_[offset] = value;
+ this.bytes_[offset + 1] = value >> 8;
}
writeInt32(offset: number, value: number): void {
@@ -120,20 +119,20 @@
}
writeUint32(offset: number, value: number): void {
- this.bytes_[offset] = value;
- this.bytes_[offset + 1] = value >> 8;
- this.bytes_[offset + 2] = value >> 16;
- this.bytes_[offset + 3] = value >> 24;
+ this.bytes_[offset] = value;
+ this.bytes_[offset + 1] = value >> 8;
+ this.bytes_[offset + 2] = value >> 16;
+ this.bytes_[offset + 3] = value >> 24;
}
- writeInt64(offset: number, value: Long): void {
- this.writeInt32(offset, value.low);
- this.writeInt32(offset + 4, value.high);
+ writeInt64(offset: number, value: bigint): void {
+ this.writeInt32(offset, Number(BigInt.asIntN(32, value)));
+ this.writeInt32(offset + 4, Number(BigInt.asIntN(32, value >> BigInt(32))));
}
- writeUint64(offset: number, value: Long): void {
- this.writeUint32(offset, value.low);
- this.writeUint32(offset + 4, value.high);
+ writeUint64(offset: number, value: bigint): void {
+ this.writeUint32(offset, Number(BigInt.asUintN(32, value)));
+ this.writeUint32(offset + 4, Number(BigInt.asUintN(32, value >> BigInt(32))));
}
writeFloat32(offset: number, value: number): void {
@@ -301,19 +300,12 @@
}
return true;
}
-
- /**
- * A helper function to avoid generated code depending on this file directly.
- */
- createLong(low: number, high: number): Long {
- return Long.create(low, high);
- }
-
+
/**
* A helper function for generating list for obj api
*/
- createScalarList(listAccessor: (i: number) => unknown, listLength: number) : unknown[] {
- const ret: unknown[] = [];
+ createScalarList(listAccessor: (i: number) => unknown, listLength: number): any[] {
+ const ret: any[] = [];
for(let i = 0; i < listLength; ++i) {
if(listAccessor(i) !== null) {
ret.push(listAccessor(i));
@@ -324,28 +316,21 @@
}
/**
- * This function is here only to get around typescript type system
- */
- createStringList(listAccessor: (i: number) => unknown, listLength: number): unknown[] {
- return this.createScalarList(listAccessor, listLength);
- }
-
- /**
* A helper function for generating list for obj api
* @param listAccessor function that accepts an index and return data at that index
* @param listLength listLength
* @param res result list
*/
- createObjList(listAccessor: (i: number) => IGeneratedObject, listLength: number): IGeneratedObject[] {
- const ret: IGeneratedObject[] = [];
+ createObjList(listAccessor: (i: number) => unknown, listLength: number): any[] {
+ const ret: any[] = [];
for(let i = 0; i < listLength; ++i) {
const val = listAccessor(i);
if(val !== null) {
- ret.push(val.unpack());
+ ret.push((val as IGeneratedObject).unpack());
}
}
return ret;
}
- }
\ No newline at end of file
+ }
diff --git a/ts/flatbuffers.ts b/ts/flatbuffers.ts
deleted file mode 100644
index 9184527..0000000
--- a/ts/flatbuffers.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-/* eslint-disable @typescript-eslint/no-namespace */
-import * as constants from './constants'
-import * as types from './types'
-import * as utils from './utils'
-
-import { Long as LongClass } from './long'
-import { Encoding as EncodingEnum } from './encoding'
-import { Builder as BuilderClass } from './builder'
-import { ByteBuffer as ByteBufferClass } from './byte-buffer'
-
-export namespace flatbuffers {
-
- export type Offset = types.Offset;
-
- export type Table = types.Table;
-
- export const SIZEOF_SHORT = constants.SIZEOF_SHORT;
- export const SIZEOF_INT = constants.SIZEOF_INT;
- export const FILE_IDENTIFIER_LENGTH = constants.FILE_IDENTIFIER_LENGTH;
- export const SIZE_PREFIX_LENGTH = constants.SIZE_PREFIX_LENGTH;
-
- export const Encoding = EncodingEnum;
-
- export const int32 = utils.int32;
- export const float32 = utils.float32;
- export const float64 = utils.float64;
- export const isLittleEndian = utils.isLittleEndian;
-
- export const Long = LongClass;
- export const Builder = BuilderClass;
- export const ByteBuffer = ByteBufferClass;
-}
-
-export default flatbuffers;
diff --git a/ts/flexbuffers.ts b/ts/flexbuffers.ts
index 40482dc..a59d497 100644
--- a/ts/flexbuffers.ts
+++ b/ts/flexbuffers.ts
@@ -1,13 +1,14 @@
/* eslint-disable @typescript-eslint/no-namespace */
-import { Builder } from './flexbuffers/builder'
-import { toReference as toReferenceFunction } from './flexbuffers/reference';
+import { Builder } from './flexbuffers/builder.js'
+import { toReference } from './flexbuffers/reference.js'
+export { toReference } from './flexbuffers/reference.js'
export function builder(): Builder {
return new Builder();
}
-export function toObject(buffer: Uint8Array): unknown {
- return toReferenceFunction(buffer).toObject();
+export function toObject(buffer: ArrayBuffer): unknown {
+ return toReference(buffer).toObject();
}
export function encode(object: unknown, size = 2048, deduplicateStrings = true, deduplicateKeys = true, deduplicateKeyVectors = true): Uint8Array {
@@ -15,16 +16,3 @@
builder.add(object);
return builder.finish();
}
-
-const builderFunction = builder
-const toObjectFunction = toObject
-const encodeFunction = encode
-
-export namespace flexbuffers {
- export const builder = builderFunction;
- export const toObject = toObjectFunction;
- export const encode = encodeFunction;
- export const toReference = toReferenceFunction;
-}
-
-export default flexbuffers;
diff --git a/ts/flexbuffers/bit-width-util.ts b/ts/flexbuffers/bit-width-util.ts
index acb3c96..3a295fd 100644
--- a/ts/flexbuffers/bit-width-util.ts
+++ b/ts/flexbuffers/bit-width-util.ts
@@ -1,4 +1,4 @@
-import { BitWidth } from './bit-width'
+import { BitWidth } from './bit-width.js'
export function toByteWidth(bitWidth: BitWidth): number {
return 1 << bitWidth;
diff --git a/ts/flexbuffers/builder.ts b/ts/flexbuffers/builder.ts
index 4321547..9c2aa2a 100644
--- a/ts/flexbuffers/builder.ts
+++ b/ts/flexbuffers/builder.ts
@@ -1,9 +1,9 @@
-import { BitWidth } from './bit-width'
-import { paddingSize, iwidth, uwidth, fwidth, toByteWidth, fromByteWidth } from './bit-width-util'
-import { toUTF8Array } from './flexbuffers-util'
-import { ValueType } from './value-type'
-import { isNumber, isTypedVectorElement, toTypedVector } from './value-type-util'
-import { StackValue } from './stack-value'
+import { BitWidth } from './bit-width.js'
+import { paddingSize, iwidth, uwidth, fwidth, toByteWidth, fromByteWidth } from './bit-width-util.js'
+import { toUTF8Array } from './flexbuffers-util.js'
+import { ValueType } from './value-type.js'
+import { isNumber, isTypedVectorElement, toTypedVector } from './value-type-util.js'
+import { StackValue } from './stack-value.js'
interface StackPointer {
stackPosition: number,
diff --git a/ts/flexbuffers/reference-util.ts b/ts/flexbuffers/reference-util.ts
index a5eb48d..c55a941 100644
--- a/ts/flexbuffers/reference-util.ts
+++ b/ts/flexbuffers/reference-util.ts
@@ -1,9 +1,6 @@
-import { BitWidth } from './bit-width'
-import { toByteWidth, fromByteWidth } from './bit-width-util'
-import { toUTF8Array, fromUTF8Array } from './flexbuffers-util'
-import { Reference } from './reference'
-
-import { Long } from '../long'
+import { BitWidth } from './bit-width.js'
+import { toByteWidth, fromByteWidth } from './bit-width-util.js'
+import { toUTF8Array, fromUTF8Array } from './flexbuffers-util.js'
export function validateOffset(dataView: DataView, offset: number, width: number): void {
if (dataView.byteLength <= offset + width || (offset & (toByteWidth(width) - 1)) !== 0) {
@@ -11,7 +8,7 @@
}
}
-export function readInt(dataView: DataView, offset: number, width: number): number | Long | bigint {
+export function readInt(dataView: DataView, offset: number, width: number): number | bigint {
if (width < 2) {
if (width < 1) {
return dataView.getInt8(offset);
@@ -23,14 +20,14 @@
return dataView.getInt32(offset, true)
} else {
if (dataView.setBigInt64 === undefined) {
- return new Long(dataView.getUint32(offset, true), dataView.getUint32(offset + 4, true))
+ return BigInt(dataView.getUint32(offset, true)) + (BigInt(dataView.getUint32(offset + 4, true)) << BigInt(32));
}
return dataView.getBigInt64(offset, true)
}
}
}
-export function readUInt(dataView: DataView, offset: number, width: number): number | Long | bigint {
+export function readUInt(dataView: DataView, offset: number, width: number): number | bigint {
if (width < 2) {
if (width < 1) {
return dataView.getUint8(offset);
@@ -42,7 +39,7 @@
return dataView.getUint32(offset, true)
} else {
if (dataView.getBigUint64 === undefined) {
- return new Long(dataView.getUint32(offset, true), dataView.getUint32(offset + 4, true))
+ return BigInt(dataView.getUint32(offset, true)) + (BigInt(dataView.getUint32(offset + 4, true)) << BigInt(32));
}
return dataView.getBigUint64(offset, true)
}
@@ -97,13 +94,6 @@
return dataView.getUint8(keyIndirectOffset + input.length) === 0 ? 0 : -1;
}
-export function valueForIndexWithKey(index: number, key: string, dataView: DataView, offset: number, parentWidth: number, byteWidth: number, length: number, path: string): Reference {
- const _indirect = indirect(dataView, offset, parentWidth);
- const elementOffset = _indirect + index * byteWidth;
- const packedType = dataView.getUint8(_indirect + length * byteWidth + index);
- return new Reference(dataView, elementOffset, fromByteWidth(byteWidth), packedType, `${path}/${key}`)
-}
-
export function keyForIndex(index: number, dataView: DataView, offset: number, parentWidth: number, byteWidth: number): string {
const keysVectorOffset = indirect(dataView, offset, parentWidth) - byteWidth * 3;
const bitWidth = fromByteWidth(byteWidth);
@@ -116,4 +106,4 @@
length++;
}
return fromUTF8Array(new Uint8Array(dataView.buffer, keyIndirectOffset, length));
-}
\ No newline at end of file
+}
diff --git a/ts/flexbuffers/reference.ts b/ts/flexbuffers/reference.ts
index a93c743..0eff6f4 100644
--- a/ts/flexbuffers/reference.ts
+++ b/ts/flexbuffers/reference.ts
@@ -1,14 +1,13 @@
-import { fromByteWidth } from './bit-width-util'
-import { ValueType } from './value-type'
-import { isNumber, isIndirectNumber, isAVector, fixedTypedVectorElementSize, isFixedTypedVector, isTypedVector, typedVectorElementType, packedType, fixedTypedVectorElementType } from './value-type-util'
-import { indirect, keyForIndex, keyIndex, readFloat, readInt, readUInt, valueForIndexWithKey } from './reference-util'
-import { Long } from '../long';
-import { fromUTF8Array } from './flexbuffers-util';
-import { BitWidth } from './bit-width';
+import { fromByteWidth } from './bit-width-util.js'
+import { ValueType } from './value-type.js'
+import { isNumber, isIndirectNumber, isAVector, fixedTypedVectorElementSize, isFixedTypedVector, isTypedVector, typedVectorElementType, packedType, fixedTypedVectorElementType } from './value-type-util.js'
+import { indirect, keyForIndex, keyIndex, readFloat, readInt, readUInt } from './reference-util.js'
+import { fromUTF8Array } from './flexbuffers-util.js';
+import { BitWidth } from './bit-width.js';
-export function toReference(buffer: Uint8Array): Reference {
+export function toReference(buffer: ArrayBuffer): Reference {
const len = buffer.byteLength;
-
+
if (len < 3) {
throw "Buffer needs to be bigger than 3";
}
@@ -22,6 +21,13 @@
return new Reference(dataView, offset, parentWidth, packedType, "/")
}
+function valueForIndexWithKey(index: number, key: string, dataView: DataView, offset: number, parentWidth: number, byteWidth: number, length: number, path: string): Reference {
+ const _indirect = indirect(dataView, offset, parentWidth);
+ const elementOffset = _indirect + index * byteWidth;
+ const packedType = dataView.getUint8(_indirect + length * byteWidth + index);
+ return new Reference(dataView, elementOffset, fromByteWidth(byteWidth), packedType, `${path}/${key}`)
+}
+
export class Reference {
private readonly byteWidth: number
private readonly valueType: ValueType
@@ -48,7 +54,7 @@
return null;
}
- intValue(): number | Long | bigint | null {
+ intValue(): number | bigint | null {
if (this.valueType === ValueType.INT) {
return readInt(this.dataView, this.offset, this.parentWidth);
}
@@ -74,7 +80,7 @@
return null;
}
- numericValue(): number | Long | bigint | null { return this.floatValue() || this.intValue()}
+ numericValue(): number | bigint | null { return this.floatValue() || this.intValue()}
stringValue(): string | null {
if (this.valueType === ValueType.STRING || this.valueType === ValueType.KEY) {
diff --git a/ts/flexbuffers/stack-value.ts b/ts/flexbuffers/stack-value.ts
index ef8e2f1..0106417 100644
--- a/ts/flexbuffers/stack-value.ts
+++ b/ts/flexbuffers/stack-value.ts
@@ -1,8 +1,8 @@
-import { Builder } from './builder'
-import { BitWidth } from './bit-width'
-import { paddingSize, uwidth, fromByteWidth } from './bit-width-util'
-import { ValueType } from './value-type'
-import { isInline, packedType } from './value-type-util'
+import { Builder } from './builder.js'
+import { BitWidth } from './bit-width.js'
+import { paddingSize, uwidth, fromByteWidth } from './bit-width-util.js'
+import { ValueType } from './value-type.js'
+import { isInline, packedType } from './value-type-util.js'
export class StackValue {
constructor(private builder: Builder, public type: ValueType, public width: number, public value: number | boolean | null = null, public offset: number = 0) {
diff --git a/ts/flexbuffers/value-type-util.ts b/ts/flexbuffers/value-type-util.ts
index da869a9..784977d 100644
--- a/ts/flexbuffers/value-type-util.ts
+++ b/ts/flexbuffers/value-type-util.ts
@@ -1,4 +1,4 @@
-import { ValueType } from './value-type'
+import { ValueType } from './value-type.js'
export function isInline(value: ValueType): boolean {
return value === ValueType.BOOL
diff --git a/ts/index.ts b/ts/index.ts
new file mode 100644
index 0000000..19f44e6
--- /dev/null
+++ b/ts/index.ts
@@ -0,0 +1,12 @@
+export { SIZEOF_SHORT } from './constants.js'
+export { SIZEOF_INT } from './constants.js'
+export { FILE_IDENTIFIER_LENGTH } from './constants.js'
+export { SIZE_PREFIX_LENGTH } from './constants.js'
+
+export { Table, Offset } from './types.js'
+
+export { int32, float32, float64, isLittleEndian } from './utils.js'
+
+export { Encoding } from './encoding.js'
+export { Builder } from './builder.js'
+export { ByteBuffer } from './byte-buffer.js'
diff --git a/ts/long.ts b/ts/long.ts
deleted file mode 100644
index 50a3ea8..0000000
--- a/ts/long.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-export function createLong(low: number, high: number): Long {
- return Long.create(low, high);
-}
-
-export class Long {
- static readonly ZERO = new Long(0, 0)
- low: number
- high: number
- constructor(low: number, high: number) {
- this.low = low | 0;
- this.high = high | 0;
- }
- static create(low: number, high: number): Long {
- // Special-case zero to avoid GC overhead for default values
- return low == 0 && high == 0 ? Long.ZERO : new Long(low, high);
- }
- toFloat64(): number {
- return (this.low >>> 0) + this.high * 0x100000000;
- }
- equals(other: Long): boolean {
- return this.low == other.low && this.high == other.high;
- }
-}
\ No newline at end of file
diff --git a/ts/types.ts b/ts/types.ts
index 30e4050..31fefc1 100644
--- a/ts/types.ts
+++ b/ts/types.ts
@@ -1,5 +1,5 @@
-import { ByteBuffer } from './byte-buffer'
-import { Builder } from './builder'
+import { ByteBuffer } from './byte-buffer.js'
+import { Builder } from './builder.js'
export type Offset = number;
diff --git a/yarn.lock b/yarn.lock
index 0ec94dd..171854d 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -2,192 +2,290 @@
# yarn lockfile v1
-"@babel/code-frame@^7.0.0":
- version "7.10.4"
- resolved "https://registry.yarnpkg.com/@babel/code-frame/-/code-frame-7.10.4.tgz#168da1a36e90da68ae8d49c0f1b48c7c6249213a"
- integrity sha512-vG6SvB6oYEhvgisZNFRmRCUkLz11c7rp+tbNTynGqc6mS1d5ATd/sGyV6W0KZZnXRKMTzZDRgQT3Ou9jhpAfUg==
+"@babel/code-frame@7.12.11":
+ version "7.12.11"
+ resolved "https://registry.yarnpkg.com/@babel/code-frame/-/code-frame-7.12.11.tgz#f4ad435aa263db935b8f10f2c552d23fb716a63f"
+ integrity sha512-Zt1yodBx1UcyiePMSkWnU4hPqhwq7hGi2nFL1LeA3EUl+q2LQx16MISgJ0+z7dnmgvP9QtIleuETGOiOH1RcIw==
dependencies:
"@babel/highlight" "^7.10.4"
-"@babel/helper-validator-identifier@^7.10.4":
- version "7.10.4"
- resolved "https://registry.yarnpkg.com/@babel/helper-validator-identifier/-/helper-validator-identifier-7.10.4.tgz#a78c7a7251e01f616512d31b10adcf52ada5e0d2"
- integrity sha512-3U9y+43hz7ZM+rzG24Qe2mufW5KhvFg/NhnNph+i9mgCtdTCtMJuI1TMkrIUiK7Ix4PYlRF9I5dhqaLYA/ADXw==
+"@babel/helper-validator-identifier@^7.16.7":
+ version "7.16.7"
+ resolved "https://registry.yarnpkg.com/@babel/helper-validator-identifier/-/helper-validator-identifier-7.16.7.tgz#e8c602438c4a8195751243da9031d1607d247cad"
+ integrity sha512-hsEnFemeiW4D08A5gUAZxLBTXpZ39P+a+DGDsHw1yxqyQ/jzFEnxf5uTEGp+3bzAbNOxU1paTgYS4ECU/IgfDw==
"@babel/highlight@^7.10.4":
- version "7.10.4"
- resolved "https://registry.yarnpkg.com/@babel/highlight/-/highlight-7.10.4.tgz#7d1bdfd65753538fabe6c38596cdb76d9ac60143"
- integrity sha512-i6rgnR/YgPEQzZZnbTHHuZdlE8qyoBNalD6F+q4vAFlcMEcqmkoG+mPqJYJCo63qPf74+Y1UZsl3l6f7/RIkmA==
+ version "7.16.10"
+ resolved "https://registry.yarnpkg.com/@babel/highlight/-/highlight-7.16.10.tgz#744f2eb81579d6eea753c227b0f570ad785aba88"
+ integrity sha512-5FnTQLSLswEj6IkgVw5KusNUUFY9ZGqe/TRFnP/BKYHYgfh7tc+C7mwiy95/yNP7Dh9x580Vv8r7u7ZfTBFxdw==
dependencies:
- "@babel/helper-validator-identifier" "^7.10.4"
+ "@babel/helper-validator-identifier" "^7.16.7"
chalk "^2.0.0"
js-tokens "^4.0.0"
-"@eslint/eslintrc@^0.1.3":
- version "0.1.3"
- resolved "https://registry.yarnpkg.com/@eslint/eslintrc/-/eslintrc-0.1.3.tgz#7d1a2b2358552cc04834c0979bd4275362e37085"
- integrity sha512-4YVwPkANLeNtRjMekzux1ci8hIaH5eGKktGqR0d3LWsKNn5B2X/1Z6Trxy7jQXl9EBGE6Yj02O+t09FMeRllaA==
+"@bazel/typescript@^5.2.0":
+ version "5.2.0"
+ resolved "https://registry.yarnpkg.com/@bazel/typescript/-/typescript-5.2.0.tgz#131127c8016c712ef1b291f2b52108e5326f0447"
+ integrity sha512-hNpSCQj5dOX95iC4Yf/fuyxfMU5uTAe84thqPcTCvOJFmpypN6qzxH24S5UiXkwbsL8sQM9DP0+qFyT/TRKdNw==
+ dependencies:
+ "@bazel/worker" "5.2.0"
+ protobufjs "6.8.8"
+ semver "5.6.0"
+ source-map-support "0.5.9"
+ tsutils "3.21.0"
+
+"@bazel/worker@5.2.0":
+ version "5.2.0"
+ resolved "https://registry.yarnpkg.com/@bazel/worker/-/worker-5.2.0.tgz#464726821f9d98b11c6536e2547d44459a321a61"
+ integrity sha512-C9ozvgRP2iug4e9XaVjfXSKmrUMyzsYhDN2/A+MqKl8qlAf5AlveNofCUBASHxJsYiBn3ATbPNUznGsjeMpVWg==
+ dependencies:
+ google-protobuf "^3.6.1"
+
+"@eslint/eslintrc@^0.4.3":
+ version "0.4.3"
+ resolved "https://registry.yarnpkg.com/@eslint/eslintrc/-/eslintrc-0.4.3.tgz#9e42981ef035beb3dd49add17acb96e8ff6f394c"
+ integrity sha512-J6KFFz5QCYUJq3pf0mjEcCJVERbzv71PUIDczuh9JkwGEzced6CO5ADLHB1rbf/+oPBtoPfMYNOpGDzCANlbXw==
dependencies:
ajv "^6.12.4"
debug "^4.1.1"
espree "^7.3.0"
- globals "^12.1.0"
+ globals "^13.9.0"
ignore "^4.0.6"
import-fresh "^3.2.1"
js-yaml "^3.13.1"
- lodash "^4.17.19"
minimatch "^3.0.4"
strip-json-comments "^3.1.1"
-"@nodelib/fs.scandir@2.1.3":
- version "2.1.3"
- resolved "https://registry.yarnpkg.com/@nodelib/fs.scandir/-/fs.scandir-2.1.3.tgz#3a582bdb53804c6ba6d146579c46e52130cf4a3b"
- integrity sha512-eGmwYQn3gxo4r7jdQnkrrN6bY478C3P+a/y72IJukF8LjB6ZHeB3c+Ehacj3sYeSmUXGlnA67/PmbM9CVwL7Dw==
+"@humanwhocodes/config-array@^0.5.0":
+ version "0.5.0"
+ resolved "https://registry.yarnpkg.com/@humanwhocodes/config-array/-/config-array-0.5.0.tgz#1407967d4c6eecd7388f83acf1eaf4d0c6e58ef9"
+ integrity sha512-FagtKFz74XrTl7y6HCzQpwDfXP0yhxe9lHLD1UZxjvZIcbyRz8zTFF/yYNfSfzU414eDwZ1SrO0Qvtyf+wFMQg==
dependencies:
- "@nodelib/fs.stat" "2.0.3"
+ "@humanwhocodes/object-schema" "^1.2.0"
+ debug "^4.1.1"
+ minimatch "^3.0.4"
+
+"@humanwhocodes/object-schema@^1.2.0":
+ version "1.2.1"
+ resolved "https://registry.yarnpkg.com/@humanwhocodes/object-schema/-/object-schema-1.2.1.tgz#b520529ec21d8e5945a1851dfd1c32e94e39ff45"
+ integrity sha512-ZnQMnLV4e7hDlUvw8H+U8ASL02SS2Gn6+9Ac3wGGLIe7+je2AeAOxPY+izIPJDfFDb7eDjev0Us8MO1iFRN8hA==
+
+"@nodelib/fs.scandir@2.1.5":
+ version "2.1.5"
+ resolved "https://registry.yarnpkg.com/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz#7619c2eb21b25483f6d167548b4cfd5a7488c3d5"
+ integrity sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==
+ dependencies:
+ "@nodelib/fs.stat" "2.0.5"
run-parallel "^1.1.9"
-"@nodelib/fs.stat@2.0.3", "@nodelib/fs.stat@^2.0.2":
- version "2.0.3"
- resolved "https://registry.yarnpkg.com/@nodelib/fs.stat/-/fs.stat-2.0.3.tgz#34dc5f4cabbc720f4e60f75a747e7ecd6c175bd3"
- integrity sha512-bQBFruR2TAwoevBEd/NWMoAAtNGzTRgdrqnYCc7dhzfoNvqPzLyqlEQnzZ3kVnNrSp25iyxE00/3h2fqGAGArA==
+"@nodelib/fs.stat@2.0.5", "@nodelib/fs.stat@^2.0.2":
+ version "2.0.5"
+ resolved "https://registry.yarnpkg.com/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz#5bd262af94e9d25bd1e71b05deed44876a222e8b"
+ integrity sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==
"@nodelib/fs.walk@^1.2.3":
- version "1.2.4"
- resolved "https://registry.yarnpkg.com/@nodelib/fs.walk/-/fs.walk-1.2.4.tgz#011b9202a70a6366e436ca5c065844528ab04976"
- integrity sha512-1V9XOY4rDW0rehzbrcqAmHnz8e7SKvX27gh8Gt2WgB0+pdzdiLV83p72kZPU+jvMbS1qU5mauP2iOvO8rhmurQ==
+ version "1.2.8"
+ resolved "https://registry.yarnpkg.com/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz#e95737e8bb6746ddedf69c556953494f196fe69a"
+ integrity sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==
dependencies:
- "@nodelib/fs.scandir" "2.1.3"
+ "@nodelib/fs.scandir" "2.1.5"
fastq "^1.6.0"
-"@types/color-name@^1.1.1":
- version "1.1.1"
- resolved "https://registry.yarnpkg.com/@types/color-name/-/color-name-1.1.1.tgz#1c1261bbeaa10a8055bbc5d8ab84b7b2afc846a0"
- integrity sha512-rr+OQyAjxze7GgWrSaJwydHStIhHq2lvY3BOC2Mj7KnzI7XK0Uw1TOOdI9lDoajEbSWLiYgoo4f1R51erQfhPQ==
+"@protobufjs/aspromise@^1.1.1", "@protobufjs/aspromise@^1.1.2":
+ version "1.1.2"
+ resolved "https://registry.yarnpkg.com/@protobufjs/aspromise/-/aspromise-1.1.2.tgz#9b8b0cc663d669a7d8f6f5d0893a14d348f30fbf"
+ integrity sha1-m4sMxmPWaafY9vXQiToU00jzD78=
-"@types/json-schema@^7.0.3":
- version "7.0.6"
- resolved "https://registry.yarnpkg.com/@types/json-schema/-/json-schema-7.0.6.tgz#f4c7ec43e81b319a9815115031709f26987891f0"
- integrity sha512-3c+yGKvVP5Y9TYBEibGNR+kLtijnj7mYrXRg+WpFb2X9xm04g/DXYkfg4hmzJQosc9snFNUPkbYIhu+KAm6jJw==
+"@protobufjs/base64@^1.1.2":
+ version "1.1.2"
+ resolved "https://registry.yarnpkg.com/@protobufjs/base64/-/base64-1.1.2.tgz#4c85730e59b9a1f1f349047dbf24296034bb2735"
+ integrity sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==
-"@typescript-eslint/eslint-plugin@^4.1.0":
- version "4.1.0"
- resolved "https://registry.yarnpkg.com/@typescript-eslint/eslint-plugin/-/eslint-plugin-4.1.0.tgz#7d309f60815ff35e9627ad85e41928d7b7fd443f"
- integrity sha512-U+nRJx8XDUqJxYF0FCXbpmD9nWt/xHDDG0zsw1vrVYAmEAuD/r49iowfurjSL2uTA2JsgtpsyG7mjO7PHf2dYw==
+"@protobufjs/codegen@^2.0.4":
+ version "2.0.4"
+ resolved "https://registry.yarnpkg.com/@protobufjs/codegen/-/codegen-2.0.4.tgz#7ef37f0d010fb028ad1ad59722e506d9262815cb"
+ integrity sha512-YyFaikqM5sH0ziFZCN3xDC7zeGaB/d0IUb9CATugHWbd1FRFwWwt4ld4OYMPWu5a3Xe01mGAULCdqhMlPl29Jg==
+
+"@protobufjs/eventemitter@^1.1.0":
+ version "1.1.0"
+ resolved "https://registry.yarnpkg.com/@protobufjs/eventemitter/-/eventemitter-1.1.0.tgz#355cbc98bafad5978f9ed095f397621f1d066b70"
+ integrity sha1-NVy8mLr61ZePntCV85diHx0Ga3A=
+
+"@protobufjs/fetch@^1.1.0":
+ version "1.1.0"
+ resolved "https://registry.yarnpkg.com/@protobufjs/fetch/-/fetch-1.1.0.tgz#ba99fb598614af65700c1619ff06d454b0d84c45"
+ integrity sha1-upn7WYYUr2VwDBYZ/wbUVLDYTEU=
dependencies:
- "@typescript-eslint/experimental-utils" "4.1.0"
- "@typescript-eslint/scope-manager" "4.1.0"
- debug "^4.1.1"
+ "@protobufjs/aspromise" "^1.1.1"
+ "@protobufjs/inquire" "^1.1.0"
+
+"@protobufjs/float@^1.0.2":
+ version "1.0.2"
+ resolved "https://registry.yarnpkg.com/@protobufjs/float/-/float-1.0.2.tgz#5e9e1abdcb73fc0a7cb8b291df78c8cbd97b87d1"
+ integrity sha1-Xp4avctz/Ap8uLKR33jIy9l7h9E=
+
+"@protobufjs/inquire@^1.1.0":
+ version "1.1.0"
+ resolved "https://registry.yarnpkg.com/@protobufjs/inquire/-/inquire-1.1.0.tgz#ff200e3e7cf2429e2dcafc1140828e8cc638f089"
+ integrity sha1-/yAOPnzyQp4tyvwRQIKOjMY48Ik=
+
+"@protobufjs/path@^1.1.2":
+ version "1.1.2"
+ resolved "https://registry.yarnpkg.com/@protobufjs/path/-/path-1.1.2.tgz#6cc2b20c5c9ad6ad0dccfd21ca7673d8d7fbf68d"
+ integrity sha1-bMKyDFya1q0NzP0hynZz2Nf79o0=
+
+"@protobufjs/pool@^1.1.0":
+ version "1.1.0"
+ resolved "https://registry.yarnpkg.com/@protobufjs/pool/-/pool-1.1.0.tgz#09fd15f2d6d3abfa9b65bc366506d6ad7846ff54"
+ integrity sha1-Cf0V8tbTq/qbZbw2ZQbWrXhG/1Q=
+
+"@protobufjs/utf8@^1.1.0":
+ version "1.1.0"
+ resolved "https://registry.yarnpkg.com/@protobufjs/utf8/-/utf8-1.1.0.tgz#a777360b5b39a1a2e5106f8e858f2fd2d060c570"
+ integrity sha1-p3c2C1s5oaLlEG+OhY8v0tBgxXA=
+
+"@types/json-schema@^7.0.7":
+ version "7.0.9"
+ resolved "https://registry.yarnpkg.com/@types/json-schema/-/json-schema-7.0.9.tgz#97edc9037ea0c38585320b28964dde3b39e4660d"
+ integrity sha512-qcUXuemtEu+E5wZSJHNxUXeCZhAfXKQ41D+duX+VYPde7xyEVZci+/oXKJL13tnRs9lR2pr4fod59GT6/X1/yQ==
+
+"@types/long@^4.0.0":
+ version "4.0.1"
+ resolved "https://registry.yarnpkg.com/@types/long/-/long-4.0.1.tgz#459c65fa1867dafe6a8f322c4c51695663cc55e9"
+ integrity sha512-5tXH6Bx/kNGd3MgffdmP4dy2Z+G4eaXw0SE81Tq3BNadtnMR5/ySMzX4SLEzHJzSmPNn4HIdpQsBvXMUykr58w==
+
+"@types/node@17.0.21":
+ version "17.0.21"
+ resolved "https://registry.yarnpkg.com/@types/node/-/node-17.0.21.tgz#864b987c0c68d07b4345845c3e63b75edd143644"
+ integrity sha512-DBZCJbhII3r90XbQxI8Y9IjjiiOGlZ0Hr32omXIZvwwZ7p4DMMXGrKXVyPfuoBOri9XNtL0UK69jYIBIsRX3QQ==
+
+"@types/node@^10.1.0":
+ version "10.17.60"
+ resolved "https://registry.yarnpkg.com/@types/node/-/node-10.17.60.tgz#35f3d6213daed95da7f0f73e75bcc6980e90597b"
+ integrity sha512-F0KIgDJfy2nA3zMLmWGKxcH2ZVEtCZXHHdOQs2gSaQ27+lNeEfGxzkIw90aXswATX7AZ33tahPbzy6KAfUreVw==
+
+"@typescript-eslint/eslint-plugin@^4.12.0":
+ version "4.33.0"
+ resolved "https://registry.yarnpkg.com/@typescript-eslint/eslint-plugin/-/eslint-plugin-4.33.0.tgz#c24dc7c8069c7706bc40d99f6fa87edcb2005276"
+ integrity sha512-aINiAxGVdOl1eJyVjaWn/YcVAq4Gi/Yo35qHGCnqbWVz61g39D0h23veY/MA0rFFGfxK7TySg2uwDeNv+JgVpg==
+ dependencies:
+ "@typescript-eslint/experimental-utils" "4.33.0"
+ "@typescript-eslint/scope-manager" "4.33.0"
+ debug "^4.3.1"
functional-red-black-tree "^1.0.1"
- regexpp "^3.0.0"
- semver "^7.3.2"
- tsutils "^3.17.1"
+ ignore "^5.1.8"
+ regexpp "^3.1.0"
+ semver "^7.3.5"
+ tsutils "^3.21.0"
-"@typescript-eslint/experimental-utils@4.1.0":
- version "4.1.0"
- resolved "https://registry.yarnpkg.com/@typescript-eslint/experimental-utils/-/experimental-utils-4.1.0.tgz#263d7225645c09a411c8735eeffd417f50f49026"
- integrity sha512-paEYLA37iqRIDPeQwAmoYSiZ3PiHsaAc3igFeBTeqRHgPnHjHLJ9OGdmP6nwAkF65p2QzEsEBtpjNUBWByNWzA==
+"@typescript-eslint/experimental-utils@4.33.0":
+ version "4.33.0"
+ resolved "https://registry.yarnpkg.com/@typescript-eslint/experimental-utils/-/experimental-utils-4.33.0.tgz#6f2a786a4209fa2222989e9380b5331b2810f7fd"
+ integrity sha512-zeQjOoES5JFjTnAhI5QY7ZviczMzDptls15GFsI6jyUOq0kOf9+WonkhtlIhh0RgHRnqj5gdNxW5j1EvAyYg6Q==
dependencies:
- "@types/json-schema" "^7.0.3"
- "@typescript-eslint/scope-manager" "4.1.0"
- "@typescript-eslint/types" "4.1.0"
- "@typescript-eslint/typescript-estree" "4.1.0"
- eslint-scope "^5.0.0"
- eslint-utils "^2.0.0"
+ "@types/json-schema" "^7.0.7"
+ "@typescript-eslint/scope-manager" "4.33.0"
+ "@typescript-eslint/types" "4.33.0"
+ "@typescript-eslint/typescript-estree" "4.33.0"
+ eslint-scope "^5.1.1"
+ eslint-utils "^3.0.0"
-"@typescript-eslint/parser@^4.1.0":
- version "4.1.0"
- resolved "https://registry.yarnpkg.com/@typescript-eslint/parser/-/parser-4.1.0.tgz#9b0409411725f14cd7faa81a664e5051225961db"
- integrity sha512-hM/WNCQTzDHgS0Ke3cR9zPndL3OTKr9OoN9CL3UqulsAjYDrglSwIIgswSmHBcSbOzLmgaMARwrQEbIumIglvQ==
+"@typescript-eslint/parser@^4.12.0":
+ version "4.33.0"
+ resolved "https://registry.yarnpkg.com/@typescript-eslint/parser/-/parser-4.33.0.tgz#dfe797570d9694e560528d18eecad86c8c744899"
+ integrity sha512-ZohdsbXadjGBSK0/r+d87X0SBmKzOq4/S5nzK6SBgJspFo9/CUDJ7hjayuze+JK7CZQLDMroqytp7pOcFKTxZA==
dependencies:
- "@typescript-eslint/scope-manager" "4.1.0"
- "@typescript-eslint/types" "4.1.0"
- "@typescript-eslint/typescript-estree" "4.1.0"
- debug "^4.1.1"
+ "@typescript-eslint/scope-manager" "4.33.0"
+ "@typescript-eslint/types" "4.33.0"
+ "@typescript-eslint/typescript-estree" "4.33.0"
+ debug "^4.3.1"
-"@typescript-eslint/scope-manager@4.1.0":
- version "4.1.0"
- resolved "https://registry.yarnpkg.com/@typescript-eslint/scope-manager/-/scope-manager-4.1.0.tgz#9e389745ee9cfe12252ed1e9958808abd6b3a683"
- integrity sha512-HD1/u8vFNnxwiHqlWKC/Pigdn0Mvxi84Y6GzbZ5f5sbLrFKu0al02573Er+D63Sw67IffVUXR0uR8rpdfdk+vA==
+"@typescript-eslint/scope-manager@4.33.0":
+ version "4.33.0"
+ resolved "https://registry.yarnpkg.com/@typescript-eslint/scope-manager/-/scope-manager-4.33.0.tgz#d38e49280d983e8772e29121cf8c6e9221f280a3"
+ integrity sha512-5IfJHpgTsTZuONKbODctL4kKuQje/bzBRkwHE8UOZ4f89Zeddg+EGZs8PD8NcN4LdM3ygHWYB3ukPAYjvl/qbQ==
dependencies:
- "@typescript-eslint/types" "4.1.0"
- "@typescript-eslint/visitor-keys" "4.1.0"
+ "@typescript-eslint/types" "4.33.0"
+ "@typescript-eslint/visitor-keys" "4.33.0"
-"@typescript-eslint/types@4.1.0":
- version "4.1.0"
- resolved "https://registry.yarnpkg.com/@typescript-eslint/types/-/types-4.1.0.tgz#edbd3fec346f34e13ce7aa176b03b497a32c496a"
- integrity sha512-rkBqWsO7m01XckP9R2YHVN8mySOKKY2cophGM8K5uDK89ArCgahItQYdbg/3n8xMxzu2elss+an1TphlUpDuJw==
+"@typescript-eslint/types@4.33.0":
+ version "4.33.0"
+ resolved "https://registry.yarnpkg.com/@typescript-eslint/types/-/types-4.33.0.tgz#a1e59036a3b53ae8430ceebf2a919dc7f9af6d72"
+ integrity sha512-zKp7CjQzLQImXEpLt2BUw1tvOMPfNoTAfb8l51evhYbOEEzdWyQNmHWWGPR6hwKJDAi+1VXSBmnhL9kyVTTOuQ==
-"@typescript-eslint/typescript-estree@4.1.0":
- version "4.1.0"
- resolved "https://registry.yarnpkg.com/@typescript-eslint/typescript-estree/-/typescript-estree-4.1.0.tgz#394046ead25164494218c0e3d6b960695ea967f6"
- integrity sha512-r6et57qqKAWU173nWyw31x7OfgmKfMEcjJl9vlJEzS+kf9uKNRr4AVTRXfTCwebr7bdiVEkfRY5xGnpPaNPe4Q==
+"@typescript-eslint/typescript-estree@4.33.0":
+ version "4.33.0"
+ resolved "https://registry.yarnpkg.com/@typescript-eslint/typescript-estree/-/typescript-estree-4.33.0.tgz#0dfb51c2908f68c5c08d82aefeaf166a17c24609"
+ integrity sha512-rkWRY1MPFzjwnEVHsxGemDzqqddw2QbTJlICPD9p9I9LfsO8fdmfQPOX3uKfUaGRDFJbfrtm/sXhVXN4E+bzCA==
dependencies:
- "@typescript-eslint/types" "4.1.0"
- "@typescript-eslint/visitor-keys" "4.1.0"
- debug "^4.1.1"
- globby "^11.0.1"
+ "@typescript-eslint/types" "4.33.0"
+ "@typescript-eslint/visitor-keys" "4.33.0"
+ debug "^4.3.1"
+ globby "^11.0.3"
is-glob "^4.0.1"
- lodash "^4.17.15"
- semver "^7.3.2"
- tsutils "^3.17.1"
+ semver "^7.3.5"
+ tsutils "^3.21.0"
-"@typescript-eslint/visitor-keys@4.1.0":
- version "4.1.0"
- resolved "https://registry.yarnpkg.com/@typescript-eslint/visitor-keys/-/visitor-keys-4.1.0.tgz#b2d528c9484e7eda1aa4f86ccf0432fb16e4d545"
- integrity sha512-+taO0IZGCtCEsuNTTF2Q/5o8+fHrlml8i9YsZt2AiDCdYEJzYlsmRY991l/6f3jNXFyAWepdQj7n8Na6URiDRQ==
+"@typescript-eslint/visitor-keys@4.33.0":
+ version "4.33.0"
+ resolved "https://registry.yarnpkg.com/@typescript-eslint/visitor-keys/-/visitor-keys-4.33.0.tgz#2a22f77a41604289b7a186586e9ec48ca92ef1dd"
+ integrity sha512-uqi/2aSz9g2ftcHWf8uLPJA70rUv6yuMW5Bohw+bwcuzaxQIHaKFZCKGoGXIrc9vkTJ3+0txM73K0Hq3d5wgIg==
dependencies:
- "@typescript-eslint/types" "4.1.0"
+ "@typescript-eslint/types" "4.33.0"
eslint-visitor-keys "^2.0.0"
-acorn-jsx@^5.2.0:
- version "5.3.1"
- resolved "https://registry.yarnpkg.com/acorn-jsx/-/acorn-jsx-5.3.1.tgz#fc8661e11b7ac1539c47dbfea2e72b3af34d267b"
- integrity sha512-K0Ptm/47OKfQRpNQ2J/oIN/3QYiK6FwW+eJbILhsdxh2WTLdl+30o8aGdTbm5JbffpFFAg/g+zi1E+jvJha5ng==
+acorn-jsx@^5.3.1:
+ version "5.3.2"
+ resolved "https://registry.yarnpkg.com/acorn-jsx/-/acorn-jsx-5.3.2.tgz#7ed5bb55908b3b2f1bc55c6af1653bada7f07937"
+ integrity sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==
acorn@^7.4.0:
- version "7.4.0"
- resolved "https://registry.yarnpkg.com/acorn/-/acorn-7.4.0.tgz#e1ad486e6c54501634c6c397c5c121daa383607c"
- integrity sha512-+G7P8jJmCHr+S+cLfQxygbWhXy+8YTVGzAkpEbcLo2mLoL7tij/VG41QSHACSf5QgYRhMZYHuNc6drJaO0Da+w==
+ version "7.4.1"
+ resolved "https://registry.yarnpkg.com/acorn/-/acorn-7.4.1.tgz#feaed255973d2e77555b83dbc08851a6c63520fa"
+ integrity sha512-nQyp0o1/mNdbTO1PO6kHkwSrmgZ0MT/jCCpNiwbUjGoRN4dlBhqJtoQuCnEOKzgTVwg0ZWiCoQy6SxMebQVh8A==
-ajv@^6.10.0, ajv@^6.10.2, ajv@^6.12.4:
- version "6.12.4"
- resolved "https://registry.yarnpkg.com/ajv/-/ajv-6.12.4.tgz#0614facc4522127fa713445c6bfd3ebd376e2234"
- integrity sha512-eienB2c9qVQs2KWexhkrdMLVDoIQCz5KSeLxwg9Lzk4DOfBtIK9PQwwufcsn1jjGuf9WZmqPMbGxOzfcuphJCQ==
+ajv@^6.10.0, ajv@^6.12.4:
+ version "6.12.6"
+ resolved "https://registry.yarnpkg.com/ajv/-/ajv-6.12.6.tgz#baf5a62e802b07d977034586f8c3baf5adf26df4"
+ integrity sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==
dependencies:
fast-deep-equal "^3.1.1"
fast-json-stable-stringify "^2.0.0"
json-schema-traverse "^0.4.1"
uri-js "^4.2.2"
+ajv@^8.0.1:
+ version "8.10.0"
+ resolved "https://registry.yarnpkg.com/ajv/-/ajv-8.10.0.tgz#e573f719bd3af069017e3b66538ab968d040e54d"
+ integrity sha512-bzqAEZOjkrUMl2afH8dknrq5KEk2SrwdBROR+vH1EKVQTqaUbJVPdc/gEdggTMM0Se+s+Ja4ju4TlNcStKl2Hw==
+ dependencies:
+ fast-deep-equal "^3.1.1"
+ json-schema-traverse "^1.0.0"
+ require-from-string "^2.0.2"
+ uri-js "^4.2.2"
+
ansi-colors@^4.1.1:
version "4.1.1"
resolved "https://registry.yarnpkg.com/ansi-colors/-/ansi-colors-4.1.1.tgz#cbb9ae256bf750af1eab344f229aa27fe94ba348"
integrity sha512-JoX0apGbHaUJBNl6yF+p6JAFYZ666/hhCGKN5t9QFjbJQKUU/g8MNbFDbvfrgKXvI1QpZplPOnwIo99lX/AAmA==
-ansi-regex@^4.1.0:
- version "4.1.0"
- resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-4.1.0.tgz#8b9f8f08cf1acb843756a839ca8c7e3168c51997"
- integrity sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==
+ansi-regex@^5.0.1:
+ version "5.0.1"
+ resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-5.0.1.tgz#082cb2c89c9fe8659a311a53bd6a4dc5301db304"
+ integrity sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==
-ansi-regex@^5.0.0:
- version "5.0.0"
- resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-5.0.0.tgz#388539f55179bf39339c81af30a654d69f87cb75"
- integrity sha512-bY6fj56OUQ0hU1KjFNDQuJFezqKdrAyFdIevADiqrWHwSlbmBNMHp5ak2f40Pm8JTFyM2mqxkG6ngkHO11f/lg==
-
-ansi-styles@^3.2.0, ansi-styles@^3.2.1:
+ansi-styles@^3.2.1:
version "3.2.1"
resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-3.2.1.tgz#41fbb20243e50b12be0f04b8dedbf07520ce841d"
integrity sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==
dependencies:
color-convert "^1.9.0"
-ansi-styles@^4.1.0:
- version "4.2.1"
- resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-4.2.1.tgz#90ae75c424d008d2624c5bf29ead3177ebfcf359"
- integrity sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==
+ansi-styles@^4.0.0, ansi-styles@^4.1.0:
+ version "4.3.0"
+ resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-4.3.0.tgz#edd803628ae71c04c85ae7a0906edad34b648937"
+ integrity sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==
dependencies:
- "@types/color-name" "^1.1.1"
color-convert "^2.0.1"
argparse@^1.0.7:
@@ -202,15 +300,15 @@
resolved "https://registry.yarnpkg.com/array-union/-/array-union-2.1.0.tgz#b798420adbeb1de828d84acd8a2e23d3efe85e8d"
integrity sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw==
-astral-regex@^1.0.0:
- version "1.0.0"
- resolved "https://registry.yarnpkg.com/astral-regex/-/astral-regex-1.0.0.tgz#6c8c3fb827dd43ee3918f27b82782ab7658a6fd9"
- integrity sha512-+Ryf6g3BKoRc7jfp7ad8tM4TtMiaWvbF/1/sQcZPkkS7ag3D5nMBCe2UfOTONtAkaG0tO0ij3C5Lwmf1EiyjHg==
+astral-regex@^2.0.0:
+ version "2.0.0"
+ resolved "https://registry.yarnpkg.com/astral-regex/-/astral-regex-2.0.0.tgz#483143c567aeed4785759c0865786dc77d7d2e31"
+ integrity sha512-Z7tMw1ytTXt5jqMcOP+OQteU1VuNK9Y02uuJtKQ1Sv69jXQKKg5cibLwGJow8yzZP+eAc18EmLGPal0bp36rvQ==
balanced-match@^1.0.0:
- version "1.0.0"
- resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.0.tgz#89b4d199ab2bee49de164ea02b89ce462d71b767"
- integrity sha1-ibTRmasr7kneFk6gK4nORi1xt2c=
+ version "1.0.2"
+ resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.2.tgz#e83e3a7e3f300b34cb9d87f615fa0cbf357690ee"
+ integrity sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==
brace-expansion@^1.1.7:
version "1.1.11"
@@ -227,6 +325,11 @@
dependencies:
fill-range "^7.0.1"
+buffer-from@^1.0.0:
+ version "1.1.2"
+ resolved "https://registry.yarnpkg.com/buffer-from/-/buffer-from-1.1.2.tgz#2b146a6fd72e80b4f55d255f35ed59a3a9a41bd5"
+ integrity sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==
+
callsites@^3.0.0:
version "3.1.0"
resolved "https://registry.yarnpkg.com/callsites/-/callsites-3.1.0.tgz#b3630abd8943432f54b3f0519238e33cd7df2f73"
@@ -242,9 +345,9 @@
supports-color "^5.3.0"
chalk@^4.0.0:
- version "4.1.0"
- resolved "https://registry.yarnpkg.com/chalk/-/chalk-4.1.0.tgz#4e14870a618d9e2edd97dd8345fd9d9dc315646a"
- integrity sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A==
+ version "4.1.2"
+ resolved "https://registry.yarnpkg.com/chalk/-/chalk-4.1.2.tgz#aac4e2b7734a740867aeb16bf02aad556a1e7a01"
+ integrity sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==
dependencies:
ansi-styles "^4.1.0"
supports-color "^7.1.0"
@@ -287,17 +390,17 @@
shebang-command "^2.0.0"
which "^2.0.1"
-debug@^4.0.1, debug@^4.1.1:
- version "4.1.1"
- resolved "https://registry.yarnpkg.com/debug/-/debug-4.1.1.tgz#3b72260255109c6b589cee050f1d516139664791"
- integrity sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==
+debug@^4.0.1, debug@^4.1.1, debug@^4.3.1:
+ version "4.3.3"
+ resolved "https://registry.yarnpkg.com/debug/-/debug-4.3.3.tgz#04266e0b70a98d4462e6e288e38259213332b664"
+ integrity sha512-/zxw5+vh1Tfv+4Qn7a5nsbcJKPaSvCDhojn6FEl9vupwK2VCSDtEiEtqr8DFtzYFOdz63LBkxec7DYuc2jon6Q==
dependencies:
- ms "^2.1.1"
+ ms "2.1.2"
deep-is@^0.1.3:
- version "0.1.3"
- resolved "https://registry.yarnpkg.com/deep-is/-/deep-is-0.1.3.tgz#b369d6fb5dbc13eecf524f91b070feedc357cf34"
- integrity sha1-s2nW+128E+7PUk+RsHD+7cNXzzQ=
+ version "0.1.4"
+ resolved "https://registry.yarnpkg.com/deep-is/-/deep-is-0.1.4.tgz#a6f2dce612fadd2ef1f519b73551f17e85199831"
+ integrity sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==
dir-glob@^3.0.1:
version "3.0.1"
@@ -313,10 +416,10 @@
dependencies:
esutils "^2.0.2"
-emoji-regex@^7.0.1:
- version "7.0.3"
- resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-7.0.3.tgz#933a04052860c85e83c122479c4748a8e4c72156"
- integrity sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA==
+emoji-regex@^8.0.0:
+ version "8.0.0"
+ resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-8.0.0.tgz#e818fd69ce5ccfcb404594f842963bf53164cc37"
+ integrity sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==
enquirer@^2.3.5:
version "2.3.6"
@@ -330,54 +433,69 @@
resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz#1b61c0562190a8dff6ae3bb2cf0200ca130b86d4"
integrity sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=
-eslint-scope@^5.0.0, eslint-scope@^5.1.0:
- version "5.1.0"
- resolved "https://registry.yarnpkg.com/eslint-scope/-/eslint-scope-5.1.0.tgz#d0f971dfe59c69e0cada684b23d49dbf82600ce5"
- integrity sha512-iiGRvtxWqgtx5m8EyQUJihBloE4EnYeGE/bz1wSPwJE6tZuJUtHlhqDM4Xj2ukE8Dyy1+HCZ4hE0fzIVMzb58w==
+escape-string-regexp@^4.0.0:
+ version "4.0.0"
+ resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz#14ba83a5d373e3d311e5afca29cf5bfad965bf34"
+ integrity sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==
+
+eslint-scope@^5.1.1:
+ version "5.1.1"
+ resolved "https://registry.yarnpkg.com/eslint-scope/-/eslint-scope-5.1.1.tgz#e786e59a66cb92b3f6c1fb0d508aab174848f48c"
+ integrity sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==
dependencies:
- esrecurse "^4.1.0"
+ esrecurse "^4.3.0"
estraverse "^4.1.1"
-eslint-utils@^2.0.0, eslint-utils@^2.1.0:
+eslint-utils@^2.1.0:
version "2.1.0"
resolved "https://registry.yarnpkg.com/eslint-utils/-/eslint-utils-2.1.0.tgz#d2de5e03424e707dc10c74068ddedae708741b27"
integrity sha512-w94dQYoauyvlDc43XnGB8lU3Zt713vNChgt4EWwhXAP2XkBvndfxF0AgIqKOOasjPIPzj9JqgwkwbCYD0/V3Zg==
dependencies:
eslint-visitor-keys "^1.1.0"
+eslint-utils@^3.0.0:
+ version "3.0.0"
+ resolved "https://registry.yarnpkg.com/eslint-utils/-/eslint-utils-3.0.0.tgz#8aebaface7345bb33559db0a1f13a1d2d48c3672"
+ integrity sha512-uuQC43IGctw68pJA1RgbQS8/NP7rch6Cwd4j3ZBtgo4/8Flj4eGE7ZYSZRN3iq5pVUv6GPdW5Z1RFleo84uLDA==
+ dependencies:
+ eslint-visitor-keys "^2.0.0"
+
eslint-visitor-keys@^1.1.0, eslint-visitor-keys@^1.3.0:
version "1.3.0"
resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-1.3.0.tgz#30ebd1ef7c2fdff01c3a4f151044af25fab0523e"
integrity sha512-6J72N8UNa462wa/KFODt/PJ3IU60SDpC3QXC1Hjc1BXXpfL2C9R5+AU7jhe0F6GREqVMh4Juu+NY7xn+6dipUQ==
eslint-visitor-keys@^2.0.0:
- version "2.0.0"
- resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-2.0.0.tgz#21fdc8fbcd9c795cc0321f0563702095751511a8"
- integrity sha512-QudtT6av5WXels9WjIM7qz1XD1cWGvX4gGXvp/zBn9nXG02D0utdU3Em2m/QjTnrsk6bBjmCygl3rmj118msQQ==
+ version "2.1.0"
+ resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-2.1.0.tgz#f65328259305927392c938ed44eb0a5c9b2bd303"
+ integrity sha512-0rSmRBzXgDzIsD6mGdJgevzgezI534Cer5L/vyMX0kHzT/jiB43jRhd9YUlMGYLQy2zprNmoT8qasCGtY+QaKw==
-eslint@^7.8.1:
- version "7.8.1"
- resolved "https://registry.yarnpkg.com/eslint/-/eslint-7.8.1.tgz#e59de3573fb6a5be8ff526c791571646d124a8fa"
- integrity sha512-/2rX2pfhyUG0y+A123d0ccXtMm7DV7sH1m3lk9nk2DZ2LReq39FXHueR9xZwshE5MdfSf0xunSaMWRqyIA6M1w==
+eslint@^7.17.0:
+ version "7.32.0"
+ resolved "https://registry.yarnpkg.com/eslint/-/eslint-7.32.0.tgz#c6d328a14be3fb08c8d1d21e12c02fdb7a2a812d"
+ integrity sha512-VHZ8gX+EDfz+97jGcgyGCyRia/dPOd6Xh9yPv8Bl1+SoaIwD+a/vlrOmGRUyOYu7MwUhc7CxqeaDZU13S4+EpA==
dependencies:
- "@babel/code-frame" "^7.0.0"
- "@eslint/eslintrc" "^0.1.3"
+ "@babel/code-frame" "7.12.11"
+ "@eslint/eslintrc" "^0.4.3"
+ "@humanwhocodes/config-array" "^0.5.0"
ajv "^6.10.0"
chalk "^4.0.0"
cross-spawn "^7.0.2"
debug "^4.0.1"
doctrine "^3.0.0"
enquirer "^2.3.5"
- eslint-scope "^5.1.0"
+ escape-string-regexp "^4.0.0"
+ eslint-scope "^5.1.1"
eslint-utils "^2.1.0"
- eslint-visitor-keys "^1.3.0"
- espree "^7.3.0"
- esquery "^1.2.0"
+ eslint-visitor-keys "^2.0.0"
+ espree "^7.3.1"
+ esquery "^1.4.0"
esutils "^2.0.2"
- file-entry-cache "^5.0.1"
+ fast-deep-equal "^3.1.3"
+ file-entry-cache "^6.0.1"
functional-red-black-tree "^1.0.1"
- glob-parent "^5.0.0"
- globals "^12.1.0"
+ glob-parent "^5.1.2"
+ globals "^13.6.0"
ignore "^4.0.6"
import-fresh "^3.0.0"
imurmurhash "^0.1.4"
@@ -385,7 +503,7 @@
js-yaml "^3.13.1"
json-stable-stringify-without-jsonify "^1.0.1"
levn "^0.4.1"
- lodash "^4.17.19"
+ lodash.merge "^4.6.2"
minimatch "^3.0.4"
natural-compare "^1.4.0"
optionator "^0.9.1"
@@ -394,17 +512,17 @@
semver "^7.2.1"
strip-ansi "^6.0.0"
strip-json-comments "^3.1.0"
- table "^5.2.3"
+ table "^6.0.9"
text-table "^0.2.0"
v8-compile-cache "^2.0.3"
-espree@^7.3.0:
- version "7.3.0"
- resolved "https://registry.yarnpkg.com/espree/-/espree-7.3.0.tgz#dc30437cf67947cf576121ebd780f15eeac72348"
- integrity sha512-dksIWsvKCixn1yrEXO8UosNSxaDoSYpq9reEjZSbHLpT5hpaCAKTLBwq0RHtLrIr+c0ByiYzWT8KTMRzoRCNlw==
+espree@^7.3.0, espree@^7.3.1:
+ version "7.3.1"
+ resolved "https://registry.yarnpkg.com/espree/-/espree-7.3.1.tgz#f2df330b752c6f55019f8bd89b7660039c1bbbb6"
+ integrity sha512-v3JCNCE64umkFpmkFGqzVKsOT0tN1Zr+ueqLZfpV1Ob8e+CEgPWa+OxCoGH3tnhimMKIaBm4m/vaRpJ/krRz2g==
dependencies:
acorn "^7.4.0"
- acorn-jsx "^5.2.0"
+ acorn-jsx "^5.3.1"
eslint-visitor-keys "^1.3.0"
esprima@^4.0.0:
@@ -412,14 +530,14 @@
resolved "https://registry.yarnpkg.com/esprima/-/esprima-4.0.1.tgz#13b04cdb3e6c5d19df91ab6987a8695619b0aa71"
integrity sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==
-esquery@^1.2.0:
- version "1.3.1"
- resolved "https://registry.yarnpkg.com/esquery/-/esquery-1.3.1.tgz#b78b5828aa8e214e29fb74c4d5b752e1c033da57"
- integrity sha512-olpvt9QG0vniUBZspVRN6lwB7hOZoTRtT+jzR+tS4ffYx2mzbw+z0XCOk44aaLYKApNX5nMm+E+P6o25ip/DHQ==
+esquery@^1.4.0:
+ version "1.4.0"
+ resolved "https://registry.yarnpkg.com/esquery/-/esquery-1.4.0.tgz#2148ffc38b82e8c7057dfed48425b3e61f0f24a5"
+ integrity sha512-cCDispWt5vHHtwMY2YrAQ4ibFkAL8RbH5YGBnZBc90MolvvfkkQcJro/aZiAQUlQ3qgrYS6D6v8Gc5G5CQsc9w==
dependencies:
estraverse "^5.1.0"
-esrecurse@^4.1.0:
+esrecurse@^4.3.0:
version "4.3.0"
resolved "https://registry.yarnpkg.com/esrecurse/-/esrecurse-4.3.0.tgz#7ad7964d679abb28bee72cec63758b1c5d2c9921"
integrity sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==
@@ -432,31 +550,30 @@
integrity sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==
estraverse@^5.1.0, estraverse@^5.2.0:
- version "5.2.0"
- resolved "https://registry.yarnpkg.com/estraverse/-/estraverse-5.2.0.tgz#307df42547e6cc7324d3cf03c155d5cdb8c53880"
- integrity sha512-BxbNGGNm0RyRYvUdHpIwv9IWzeM9XClbOxwoATuFdOE7ZE6wHL+HQ5T8hoPM+zHvmKzzsEqhgy0GrQ5X13afiQ==
+ version "5.3.0"
+ resolved "https://registry.yarnpkg.com/estraverse/-/estraverse-5.3.0.tgz#2eea5290702f26ab8fe5370370ff86c965d21123"
+ integrity sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==
esutils@^2.0.2:
version "2.0.3"
resolved "https://registry.yarnpkg.com/esutils/-/esutils-2.0.3.tgz#74d2eb4de0b8da1293711910d50775b9b710ef64"
integrity sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==
-fast-deep-equal@^3.1.1:
+fast-deep-equal@^3.1.1, fast-deep-equal@^3.1.3:
version "3.1.3"
resolved "https://registry.yarnpkg.com/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz#3a7d56b559d6cbc3eb512325244e619a65c6c525"
integrity sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==
-fast-glob@^3.1.1:
- version "3.2.4"
- resolved "https://registry.yarnpkg.com/fast-glob/-/fast-glob-3.2.4.tgz#d20aefbf99579383e7f3cc66529158c9b98554d3"
- integrity sha512-kr/Oo6PX51265qeuCYsyGypiO5uJFgBS0jksyG7FUeCyQzNwYnzrNIMR1NXfkZXsMYXYLRAHgISHBz8gQcxKHQ==
+fast-glob@^3.2.9:
+ version "3.2.11"
+ resolved "https://registry.yarnpkg.com/fast-glob/-/fast-glob-3.2.11.tgz#a1172ad95ceb8a16e20caa5c5e56480e5129c1d9"
+ integrity sha512-xrO3+1bxSo3ZVHAnqzyuewYT6aMFHRAd4Kcs92MAonjwQZLsK9d0SF1IyQ3k5PoirxTW0Oe/RqFgMQ6TcNE5Ew==
dependencies:
"@nodelib/fs.stat" "^2.0.2"
"@nodelib/fs.walk" "^1.2.3"
- glob-parent "^5.1.0"
+ glob-parent "^5.1.2"
merge2 "^1.3.0"
- micromatch "^4.0.2"
- picomatch "^2.2.1"
+ micromatch "^4.0.4"
fast-json-stable-stringify@^2.0.0:
version "2.1.0"
@@ -469,18 +586,18 @@
integrity sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=
fastq@^1.6.0:
- version "1.8.0"
- resolved "https://registry.yarnpkg.com/fastq/-/fastq-1.8.0.tgz#550e1f9f59bbc65fe185cb6a9b4d95357107f481"
- integrity sha512-SMIZoZdLh/fgofivvIkmknUXyPnvxRE3DhtZ5Me3Mrsk5gyPL42F0xr51TdRXskBxHfMp+07bcYzfsYEsSQA9Q==
+ version "1.13.0"
+ resolved "https://registry.yarnpkg.com/fastq/-/fastq-1.13.0.tgz#616760f88a7526bdfc596b7cab8c18938c36b98c"
+ integrity sha512-YpkpUnK8od0o1hmeSc7UUs/eB/vIPWJYjKck2QKIzAf71Vm1AAQ3EbuZB3g2JIy+pg+ERD0vqI79KyZiB2e2Nw==
dependencies:
reusify "^1.0.4"
-file-entry-cache@^5.0.1:
- version "5.0.1"
- resolved "https://registry.yarnpkg.com/file-entry-cache/-/file-entry-cache-5.0.1.tgz#ca0f6efa6dd3d561333fb14515065c2fafdf439c"
- integrity sha512-bCg29ictuBaKUwwArK4ouCaqDgLZcysCFLmM/Yn/FDoqndh/9vNuQfXRDvTuXKLxfD/JtZQGKFT8MGcJBK644g==
+file-entry-cache@^6.0.1:
+ version "6.0.1"
+ resolved "https://registry.yarnpkg.com/file-entry-cache/-/file-entry-cache-6.0.1.tgz#211b2dd9659cb0394b073e7323ac3c933d522027"
+ integrity sha512-7Gps/XWymbLk2QLYK4NzpMOrYjMhdIxXuIvy2QBsLE6ljuodKvdkWs/cpyJJ3CVIVpH0Oi1Hvg1ovbMzLdFBBg==
dependencies:
- flat-cache "^2.0.1"
+ flat-cache "^3.0.4"
fill-range@^7.0.1:
version "7.0.1"
@@ -489,19 +606,18 @@
dependencies:
to-regex-range "^5.0.1"
-flat-cache@^2.0.1:
- version "2.0.1"
- resolved "https://registry.yarnpkg.com/flat-cache/-/flat-cache-2.0.1.tgz#5d296d6f04bda44a4630a301413bdbc2ec085ec0"
- integrity sha512-LoQe6yDuUMDzQAEH8sgmh4Md6oZnc/7PjtwjNFSzveXqSHt6ka9fPBuso7IGf9Rz4uqnSnWiFH2B/zj24a5ReA==
+flat-cache@^3.0.4:
+ version "3.0.4"
+ resolved "https://registry.yarnpkg.com/flat-cache/-/flat-cache-3.0.4.tgz#61b0338302b2fe9f957dcc32fc2a87f1c3048b11"
+ integrity sha512-dm9s5Pw7Jc0GvMYbshN6zchCA9RgQlzzEZX3vylR9IqFfS8XciblUXOKfW6SiuJ0e13eDYZoZV5wdrev7P3Nwg==
dependencies:
- flatted "^2.0.0"
- rimraf "2.6.3"
- write "1.0.3"
+ flatted "^3.1.0"
+ rimraf "^3.0.2"
-flatted@^2.0.0:
- version "2.0.2"
- resolved "https://registry.yarnpkg.com/flatted/-/flatted-2.0.2.tgz#4575b21e2bcee7434aa9be662f4b7b5f9c2b5138"
- integrity sha512-r5wGx7YeOwNWNlCA0wQ86zKyDLMQr+/RB8xy74M4hTphfmjlijTSSXGuH8rnvKZnfT9i+75zmd8jcKdMR4O6jA==
+flatted@^3.1.0:
+ version "3.2.5"
+ resolved "https://registry.yarnpkg.com/flatted/-/flatted-3.2.5.tgz#76c8584f4fc843db64702a6bd04ab7a8bd666da3"
+ integrity sha512-WIWGi2L3DyTUvUrwRKgGi9TwxQMUEqPOPQBVi71R96jZXJdFskXEmf54BoZaS1kknGODoIGASGEzBUYdyMCBJg==
fs.realpath@^1.0.0:
version "1.0.0"
@@ -513,17 +629,17 @@
resolved "https://registry.yarnpkg.com/functional-red-black-tree/-/functional-red-black-tree-1.0.1.tgz#1b0ab3bd553b2a0d6399d29c0e3ea0b252078327"
integrity sha1-GwqzvVU7Kg1jmdKcDj6gslIHgyc=
-glob-parent@^5.0.0, glob-parent@^5.1.0:
- version "5.1.1"
- resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-5.1.1.tgz#b6c1ef417c4e5663ea498f1c45afac6916bbc229"
- integrity sha512-FnI+VGOpnlGHWZxthPGR+QhR78fuiK0sNLkHQv+bL9fQi57lNNdquIbna/WrfROrolq8GK5Ek6BiMwqL/voRYQ==
+glob-parent@^5.1.2:
+ version "5.1.2"
+ resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-5.1.2.tgz#869832c58034fe68a4093c17dc15e8340d8401c4"
+ integrity sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==
dependencies:
is-glob "^4.0.1"
glob@^7.1.3:
- version "7.1.6"
- resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.6.tgz#141f33b81a7c2492e125594307480c46679278a6"
- integrity sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA==
+ version "7.2.0"
+ resolved "https://registry.yarnpkg.com/glob/-/glob-7.2.0.tgz#d15535af7732e02e948f4c41628bd910293f6023"
+ integrity sha512-lmLf6gtyrPq8tTjSmrO94wBeQbFR3HbLHbuyD69wuyQkImp2hWqMGB47OX65FBkPffO641IP9jWa1z4ivqG26Q==
dependencies:
fs.realpath "^1.0.0"
inflight "^1.0.4"
@@ -532,25 +648,30 @@
once "^1.3.0"
path-is-absolute "^1.0.0"
-globals@^12.1.0:
- version "12.4.0"
- resolved "https://registry.yarnpkg.com/globals/-/globals-12.4.0.tgz#a18813576a41b00a24a97e7f815918c2e19925f8"
- integrity sha512-BWICuzzDvDoH54NHKCseDanAhE3CeDorgDL5MT6LMXXj2WCnd9UC2szdk4AWLfjdgNBCXLUanXYcpBBKOSWGwg==
+globals@^13.6.0, globals@^13.9.0:
+ version "13.12.1"
+ resolved "https://registry.yarnpkg.com/globals/-/globals-13.12.1.tgz#ec206be932e6c77236677127577aa8e50bf1c5cb"
+ integrity sha512-317dFlgY2pdJZ9rspXDks7073GpDmXdfbM3vYYp0HAMKGDh1FfWPleI2ljVNLQX5M5lXcAslTcPTrOrMEFOjyw==
dependencies:
- type-fest "^0.8.1"
+ type-fest "^0.20.2"
-globby@^11.0.1:
- version "11.0.1"
- resolved "https://registry.yarnpkg.com/globby/-/globby-11.0.1.tgz#9a2bf107a068f3ffeabc49ad702c79ede8cfd357"
- integrity sha512-iH9RmgwCmUJHi2z5o2l3eTtGBtXek1OYlHrbcxOYugyHLmAsZrPj43OtHThd62Buh/Vv6VyCBD2bdyWcGNQqoQ==
+globby@^11.0.3:
+ version "11.1.0"
+ resolved "https://registry.yarnpkg.com/globby/-/globby-11.1.0.tgz#bd4be98bb042f83d796f7e3811991fbe82a0d34b"
+ integrity sha512-jhIXaOzy1sb8IyocaruWSn1TjmnBVs8Ayhcy83rmxNJ8q2uWKCAj3CnJY+KpGSXCueAPc0i05kVvVKtP1t9S3g==
dependencies:
array-union "^2.1.0"
dir-glob "^3.0.1"
- fast-glob "^3.1.1"
- ignore "^5.1.4"
- merge2 "^1.3.0"
+ fast-glob "^3.2.9"
+ ignore "^5.2.0"
+ merge2 "^1.4.1"
slash "^3.0.0"
+google-protobuf@^3.6.1:
+ version "3.19.4"
+ resolved "https://registry.yarnpkg.com/google-protobuf/-/google-protobuf-3.19.4.tgz#8d32c3e34be9250956f28c0fb90955d13f311888"
+ integrity sha512-OIPNCxsG2lkIvf+P5FNfJ/Km95CsXOBecS9ZcAU6m2Rq3svc0Apl9nB3GMDNKfQ9asNv4KjyAqGwPQFrVle3Yg==
+
has-flag@^3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-3.0.0.tgz#b5d454dc2199ae225699f3467e5a07f3b955bafd"
@@ -566,15 +687,15 @@
resolved "https://registry.yarnpkg.com/ignore/-/ignore-4.0.6.tgz#750e3db5862087b4737ebac8207ffd1ef27b25fc"
integrity sha512-cyFDKrqc/YdcWFniJhzI42+AzS+gNwmUzOSFcRCQYwySuBBBy/KjuxWLZ/FHEH6Moq1NizMOBWyTcv8O4OZIMg==
-ignore@^5.1.4:
- version "5.1.8"
- resolved "https://registry.yarnpkg.com/ignore/-/ignore-5.1.8.tgz#f150a8b50a34289b33e22f5889abd4d8016f0e57"
- integrity sha512-BMpfD7PpiETpBl/A6S498BaIJ6Y/ABT93ETbby2fP00v4EbvPBXWEoaR1UBPKs3iR53pJY7EtZk5KACI57i1Uw==
+ignore@^5.1.8, ignore@^5.2.0:
+ version "5.2.0"
+ resolved "https://registry.yarnpkg.com/ignore/-/ignore-5.2.0.tgz#6d3bac8fa7fe0d45d9f9be7bac2fc279577e345a"
+ integrity sha512-CmxgYGiEPCLhfLnpPp1MoRmifwEIOgjcHXxOBjv7mY96c+eWScsOP9c112ZyLdWHi0FxHjI+4uVhKYp/gcdRmQ==
import-fresh@^3.0.0, import-fresh@^3.2.1:
- version "3.2.1"
- resolved "https://registry.yarnpkg.com/import-fresh/-/import-fresh-3.2.1.tgz#633ff618506e793af5ac91bf48b72677e15cbe66"
- integrity sha512-6e1q1cnWP2RXD9/keSkxHScg508CdXqXWgWBaETNhyuBFz+kUZlKboh+ISK+bU++DmbHimVBrOz/zzPe0sZ3sQ==
+ version "3.3.0"
+ resolved "https://registry.yarnpkg.com/import-fresh/-/import-fresh-3.3.0.tgz#37162c25fcb9ebaa2e6e53d5b4d88ce17d9e0c2b"
+ integrity sha512-veYYhQa+D1QBKznvhUHxb8faxlrwUnxseDAbAp457E0wLNio2bOSKnjYDhMj+YiAq61xrMGhQk9iXVk5FzgQMw==
dependencies:
parent-module "^1.0.0"
resolve-from "^4.0.0"
@@ -602,15 +723,15 @@
resolved "https://registry.yarnpkg.com/is-extglob/-/is-extglob-2.1.1.tgz#a88c02535791f02ed37c76a1b9ea9773c833f8c2"
integrity sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=
-is-fullwidth-code-point@^2.0.0:
- version "2.0.0"
- resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz#a3b30a5c4f199183167aaab93beefae3ddfb654f"
- integrity sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=
+is-fullwidth-code-point@^3.0.0:
+ version "3.0.0"
+ resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz#f116f8064fe90b3f7844a38997c0b75051269f1d"
+ integrity sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==
is-glob@^4.0.0, is-glob@^4.0.1:
- version "4.0.1"
- resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-4.0.1.tgz#7567dbe9f2f5e2467bc77ab83c4a29482407a5dc"
- integrity sha512-5G0tKtBTFImOqDnLB2hG6Bp2qcKEFduo4tZu9MT/H6NQv/ghhy30o55ufafxJ/LdH79LLs2Kfrn85TLKyA7BUg==
+ version "4.0.3"
+ resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-4.0.3.tgz#64f61e42cbbb2eec2071a9dac0b28ba1e65d5084"
+ integrity sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==
dependencies:
is-extglob "^2.1.1"
@@ -630,9 +751,9 @@
integrity sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==
js-yaml@^3.13.1:
- version "3.14.0"
- resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-3.14.0.tgz#a7a34170f26a21bb162424d8adacb4113a69e482"
- integrity sha512-/4IbIeHcD9VMHFqDR/gQ7EdZdLimOvW2DdcxFjdyyZ9NsbS+ccrXqVWDtab/lRl5AlUqmpBx8EhPaWR+OtY17A==
+ version "3.14.1"
+ resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-3.14.1.tgz#dae812fdb3825fa306609a8717383c50c36a0537"
+ integrity sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==
dependencies:
argparse "^1.0.7"
esprima "^4.0.0"
@@ -642,6 +763,11 @@
resolved "https://registry.yarnpkg.com/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz#69f6a87d9513ab8bb8fe63bdb0979c448e684660"
integrity sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==
+json-schema-traverse@^1.0.0:
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz#ae7bcb3656ab77a73ba5c49bf654f38e6b6860e2"
+ integrity sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==
+
json-stable-stringify-without-jsonify@^1.0.1:
version "1.0.1"
resolved "https://registry.yarnpkg.com/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz#9db7b59496ad3f3cfef30a75142d2d930ad72651"
@@ -655,44 +781,49 @@
prelude-ls "^1.2.1"
type-check "~0.4.0"
-lodash@^4.17.14, lodash@^4.17.15, lodash@^4.17.19:
- version "4.17.20"
- resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.20.tgz#b44a9b6297bcb698f1c51a3545a2b3b368d59c52"
- integrity sha512-PlhdFcillOINfeV7Ni6oF1TAEayyZBoZ8bcshTHqOYJYlrqzRK5hagpagky5o4HfCzzd1TRkXPMFq6cKk9rGmA==
+lodash.merge@^4.6.2:
+ version "4.6.2"
+ resolved "https://registry.yarnpkg.com/lodash.merge/-/lodash.merge-4.6.2.tgz#558aa53b43b661e1925a0afdfa36a9a1085fe57a"
+ integrity sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==
-merge2@^1.3.0:
+lodash.truncate@^4.4.2:
+ version "4.4.2"
+ resolved "https://registry.yarnpkg.com/lodash.truncate/-/lodash.truncate-4.4.2.tgz#5a350da0b1113b837ecfffd5812cbe58d6eae193"
+ integrity sha1-WjUNoLERO4N+z//VgSy+WNbq4ZM=
+
+long@^4.0.0:
+ version "4.0.0"
+ resolved "https://registry.yarnpkg.com/long/-/long-4.0.0.tgz#9a7b71cfb7d361a194ea555241c92f7468d5bf28"
+ integrity sha512-XsP+KhQif4bjX1kbuSiySJFNAehNxgLb6hPRGJ9QsUr8ajHkuXGdrHmFUTUUXhDwVX2R5bY4JNZEwbUiMhV+MA==
+
+lru-cache@^6.0.0:
+ version "6.0.0"
+ resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-6.0.0.tgz#6d6fe6570ebd96aaf90fcad1dafa3b2566db3a94"
+ integrity sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==
+ dependencies:
+ yallist "^4.0.0"
+
+merge2@^1.3.0, merge2@^1.4.1:
version "1.4.1"
resolved "https://registry.yarnpkg.com/merge2/-/merge2-1.4.1.tgz#4368892f885e907455a6fd7dc55c0c9d404990ae"
integrity sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==
-micromatch@^4.0.2:
- version "4.0.2"
- resolved "https://registry.yarnpkg.com/micromatch/-/micromatch-4.0.2.tgz#4fcb0999bf9fbc2fcbdd212f6d629b9a56c39259"
- integrity sha512-y7FpHSbMUMoyPbYUSzO6PaZ6FyRnQOpHuKwbo1G+Knck95XVU4QAiKdGEnj5wwoS7PlOgthX/09u5iFJ+aYf5Q==
+micromatch@^4.0.4:
+ version "4.0.4"
+ resolved "https://registry.yarnpkg.com/micromatch/-/micromatch-4.0.4.tgz#896d519dfe9db25fce94ceb7a500919bf881ebf9"
+ integrity sha512-pRmzw/XUcwXGpD9aI9q/0XOwLNygjETJ8y0ao0wdqprrzDa4YnxLcz7fQRZr8voh8V10kGhABbNcHVk5wHgWwg==
dependencies:
braces "^3.0.1"
- picomatch "^2.0.5"
+ picomatch "^2.2.3"
minimatch@^3.0.4:
- version "3.0.4"
- resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.0.4.tgz#5166e286457f03306064be5497e8dbb0c3d32083"
- integrity sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==
+ version "3.1.2"
+ resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.1.2.tgz#19cd194bfd3e428f049a70817c038d89ab4be35b"
+ integrity sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==
dependencies:
brace-expansion "^1.1.7"
-minimist@^1.2.5:
- version "1.2.5"
- resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.5.tgz#67d66014b66a6a8aaa0c083c5fd58df4e4e97602"
- integrity sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==
-
-mkdirp@^0.5.1:
- version "0.5.5"
- resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.5.5.tgz#d91cefd62d1436ca0f41620e251288d420099def"
- integrity sha512-NKmAlESf6jMGym1++R0Ra7wvhV+wFW63FaSOFPwRahvea0gMUcGUhVeAg/0BC0wiv9ih5NYPB1Wn1UEI1/L+xQ==
- dependencies:
- minimist "^1.2.5"
-
-ms@^2.1.1:
+ms@2.1.2:
version "2.1.2"
resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.2.tgz#d09d1f357b443f493382a8eb3ccd183872ae6009"
integrity sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==
@@ -743,10 +874,10 @@
resolved "https://registry.yarnpkg.com/path-type/-/path-type-4.0.0.tgz#84ed01c0a7ba380afe09d90a8c180dcd9d03043b"
integrity sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==
-picomatch@^2.0.5, picomatch@^2.2.1:
- version "2.2.2"
- resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-2.2.2.tgz#21f333e9b6b8eaff02468f5146ea406d345f4dad"
- integrity sha512-q0M/9eZHzmr0AulXyPwNfZjtwZ/RBZlbN3K3CErVrk50T2ASYI7Bye0EvekFY3IP1Nt2DHu0re+V2ZHIpMkuWg==
+picomatch@^2.2.3:
+ version "2.3.1"
+ resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-2.3.1.tgz#3ba3833733646d9d3e4995946c1365a67fb07a42"
+ integrity sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==
prelude-ls@^1.2.1:
version "1.2.1"
@@ -758,15 +889,44 @@
resolved "https://registry.yarnpkg.com/progress/-/progress-2.0.3.tgz#7e8cf8d8f5b8f239c1bc68beb4eb78567d572ef8"
integrity sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==
+protobufjs@6.8.8:
+ version "6.8.8"
+ resolved "https://registry.yarnpkg.com/protobufjs/-/protobufjs-6.8.8.tgz#c8b4f1282fd7a90e6f5b109ed11c84af82908e7c"
+ integrity sha512-AAmHtD5pXgZfi7GMpllpO3q1Xw1OYldr+dMUlAnffGTAhqkg72WdmSY71uKBF/JuyiKs8psYbtKrhi0ASCD8qw==
+ dependencies:
+ "@protobufjs/aspromise" "^1.1.2"
+ "@protobufjs/base64" "^1.1.2"
+ "@protobufjs/codegen" "^2.0.4"
+ "@protobufjs/eventemitter" "^1.1.0"
+ "@protobufjs/fetch" "^1.1.0"
+ "@protobufjs/float" "^1.0.2"
+ "@protobufjs/inquire" "^1.1.0"
+ "@protobufjs/path" "^1.1.2"
+ "@protobufjs/pool" "^1.1.0"
+ "@protobufjs/utf8" "^1.1.0"
+ "@types/long" "^4.0.0"
+ "@types/node" "^10.1.0"
+ long "^4.0.0"
+
punycode@^2.1.0:
version "2.1.1"
resolved "https://registry.yarnpkg.com/punycode/-/punycode-2.1.1.tgz#b58b010ac40c22c5657616c8d2c2c02c7bf479ec"
integrity sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==
-regexpp@^3.0.0, regexpp@^3.1.0:
- version "3.1.0"
- resolved "https://registry.yarnpkg.com/regexpp/-/regexpp-3.1.0.tgz#206d0ad0a5648cffbdb8ae46438f3dc51c9f78e2"
- integrity sha512-ZOIzd8yVsQQA7j8GCSlPGXwg5PfmA1mrq0JP4nGhh54LaKN3xdai/vHUDu74pKwV8OxseMS65u2NImosQcSD0Q==
+queue-microtask@^1.2.2:
+ version "1.2.3"
+ resolved "https://registry.yarnpkg.com/queue-microtask/-/queue-microtask-1.2.3.tgz#4929228bbc724dfac43e0efb058caf7b6cfb6243"
+ integrity sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==
+
+regexpp@^3.1.0:
+ version "3.2.0"
+ resolved "https://registry.yarnpkg.com/regexpp/-/regexpp-3.2.0.tgz#0425a2768d8f23bad70ca4b90461fa2f1213e1b2"
+ integrity sha512-pq2bWo9mVD43nbts2wGv17XLiNLya+GklZ8kaDLV2Z08gDCsGpnKn9BFMepvWuHCbyVvY7J5o5+BVvoQbmlJLg==
+
+require-from-string@^2.0.2:
+ version "2.0.2"
+ resolved "https://registry.yarnpkg.com/require-from-string/-/require-from-string-2.0.2.tgz#89a7fdd938261267318eafe14f9c32e598c36909"
+ integrity sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==
resolve-from@^4.0.0:
version "4.0.0"
@@ -778,22 +938,31 @@
resolved "https://registry.yarnpkg.com/reusify/-/reusify-1.0.4.tgz#90da382b1e126efc02146e90845a88db12925d76"
integrity sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw==
-rimraf@2.6.3:
- version "2.6.3"
- resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.6.3.tgz#b2d104fe0d8fb27cf9e0a1cda8262dd3833c6cab"
- integrity sha512-mwqeW5XsA2qAejG46gYdENaxXjx9onRNCfn7L0duuP4hCuTIi/QO7PDK07KJfp1d+izWPrzEJDcSqBa0OZQriA==
+rimraf@^3.0.2:
+ version "3.0.2"
+ resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-3.0.2.tgz#f1a5402ba6220ad52cc1282bac1ae3aa49fd061a"
+ integrity sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==
dependencies:
glob "^7.1.3"
run-parallel@^1.1.9:
- version "1.1.9"
- resolved "https://registry.yarnpkg.com/run-parallel/-/run-parallel-1.1.9.tgz#c9dd3a7cf9f4b2c4b6244e173a6ed866e61dd679"
- integrity sha512-DEqnSRTDw/Tc3FXf49zedI638Z9onwUotBMiUFKmrO2sdFKIbXamXGQ3Axd4qgphxKB4kw/qP1w5kTxnfU1B9Q==
+ version "1.2.0"
+ resolved "https://registry.yarnpkg.com/run-parallel/-/run-parallel-1.2.0.tgz#66d1368da7bdf921eb9d95bd1a9229e7f21a43ee"
+ integrity sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==
+ dependencies:
+ queue-microtask "^1.2.2"
-semver@^7.2.1, semver@^7.3.2:
- version "7.3.2"
- resolved "https://registry.yarnpkg.com/semver/-/semver-7.3.2.tgz#604962b052b81ed0786aae84389ffba70ffd3938"
- integrity sha512-OrOb32TeeambH6UrhtShmF7CRDqhL6/5XpPNp2DuRH6+9QLw/orhp72j87v8Qa1ScDkvrrBNpZcDejAirJmfXQ==
+semver@5.6.0:
+ version "5.6.0"
+ resolved "https://registry.yarnpkg.com/semver/-/semver-5.6.0.tgz#7e74256fbaa49c75aa7c7a205cc22799cac80004"
+ integrity sha512-RS9R6R35NYgQn++fkDWaOmqGoj4Ek9gGs+DPxNUZKuwE183xjJroKvyo1IzVFeXvUrvmALy6FWD5xrdJT25gMg==
+
+semver@^7.2.1, semver@^7.3.5:
+ version "7.3.5"
+ resolved "https://registry.yarnpkg.com/semver/-/semver-7.3.5.tgz#0b621c879348d8998e4b0e4be94b3f12e6018ef7"
+ integrity sha512-PoeGJYh8HK4BTO/a9Tf6ZG3veo/A7ZVsYrSA6J8ny9nb3B1VrpkuN+z9OE5wfE5p6H4LchYZsegiQgbJD94ZFQ==
+ dependencies:
+ lru-cache "^6.0.0"
shebang-command@^2.0.0:
version "2.0.0"
@@ -812,42 +981,48 @@
resolved "https://registry.yarnpkg.com/slash/-/slash-3.0.0.tgz#6539be870c165adbd5240220dbe361f1bc4d4634"
integrity sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==
-slice-ansi@^2.1.0:
- version "2.1.0"
- resolved "https://registry.yarnpkg.com/slice-ansi/-/slice-ansi-2.1.0.tgz#cacd7693461a637a5788d92a7dd4fba068e81636"
- integrity sha512-Qu+VC3EwYLldKa1fCxuuvULvSJOKEgk9pi8dZeCVK7TqBfUNTH4sFkk4joj8afVSfAYgJoSOetjx9QWOJ5mYoQ==
+slice-ansi@^4.0.0:
+ version "4.0.0"
+ resolved "https://registry.yarnpkg.com/slice-ansi/-/slice-ansi-4.0.0.tgz#500e8dd0fd55b05815086255b3195adf2a45fe6b"
+ integrity sha512-qMCMfhY040cVHT43K9BFygqYbUPFZKHOg7K73mtTWJRb8pyP3fzf4Ixd5SzdEJQ6MRUg/WBnOLxghZtKKurENQ==
dependencies:
- ansi-styles "^3.2.0"
- astral-regex "^1.0.0"
- is-fullwidth-code-point "^2.0.0"
+ ansi-styles "^4.0.0"
+ astral-regex "^2.0.0"
+ is-fullwidth-code-point "^3.0.0"
+
+source-map-support@0.5.9:
+ version "0.5.9"
+ resolved "https://registry.yarnpkg.com/source-map-support/-/source-map-support-0.5.9.tgz#41bc953b2534267ea2d605bccfa7bfa3111ced5f"
+ integrity sha512-gR6Rw4MvUlYy83vP0vxoVNzM6t8MUXqNuRsuBmBHQDu1Fh6X015FrLdgoDKcNdkwGubozq0P4N0Q37UyFVr1EA==
+ dependencies:
+ buffer-from "^1.0.0"
+ source-map "^0.6.0"
+
+source-map@^0.6.0:
+ version "0.6.1"
+ resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.6.1.tgz#74722af32e9614e9c287a8d0bbde48b5e2f1a263"
+ integrity sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==
sprintf-js@~1.0.2:
version "1.0.3"
resolved "https://registry.yarnpkg.com/sprintf-js/-/sprintf-js-1.0.3.tgz#04e6926f662895354f3dd015203633b857297e2c"
integrity sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=
-string-width@^3.0.0:
- version "3.1.0"
- resolved "https://registry.yarnpkg.com/string-width/-/string-width-3.1.0.tgz#22767be21b62af1081574306f69ac51b62203961"
- integrity sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==
+string-width@^4.2.3:
+ version "4.2.3"
+ resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.3.tgz#269c7117d27b05ad2e536830a8ec895ef9c6d010"
+ integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==
dependencies:
- emoji-regex "^7.0.1"
- is-fullwidth-code-point "^2.0.0"
- strip-ansi "^5.1.0"
+ emoji-regex "^8.0.0"
+ is-fullwidth-code-point "^3.0.0"
+ strip-ansi "^6.0.1"
-strip-ansi@^5.1.0:
- version "5.2.0"
- resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-5.2.0.tgz#8c9a536feb6afc962bdfa5b104a5091c1ad9c0ae"
- integrity sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==
+strip-ansi@^6.0.0, strip-ansi@^6.0.1:
+ version "6.0.1"
+ resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.1.tgz#9e26c63d30f53443e9489495b2105d37b67a85d9"
+ integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==
dependencies:
- ansi-regex "^4.1.0"
-
-strip-ansi@^6.0.0:
- version "6.0.0"
- resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.0.tgz#0b1571dd7669ccd4f3e06e14ef1eed26225ae532"
- integrity sha512-AuvKTrTfQNYNIctbR1K/YGTR1756GycPsg7b9bdV9Duqur4gv6aKqHXah67Z8ImS7WEz5QVcOtlfW2rZEugt6w==
- dependencies:
- ansi-regex "^5.0.0"
+ ansi-regex "^5.0.1"
strip-json-comments@^3.1.0, strip-json-comments@^3.1.1:
version "3.1.1"
@@ -868,15 +1043,16 @@
dependencies:
has-flag "^4.0.0"
-table@^5.2.3:
- version "5.4.6"
- resolved "https://registry.yarnpkg.com/table/-/table-5.4.6.tgz#1292d19500ce3f86053b05f0e8e7e4a3bb21079e"
- integrity sha512-wmEc8m4fjnob4gt5riFRtTu/6+4rSe12TpAELNSqHMfF3IqnA+CH37USM6/YR3qRZv7e56kAEAtd6nKZaxe0Ug==
+table@^6.0.9:
+ version "6.8.0"
+ resolved "https://registry.yarnpkg.com/table/-/table-6.8.0.tgz#87e28f14fa4321c3377ba286f07b79b281a3b3ca"
+ integrity sha512-s/fitrbVeEyHKFa7mFdkuQMWlH1Wgw/yEXMt5xACT4ZpzWFluehAxRtUUQKPuWhaLAWhFcVx6w3oC8VKaUfPGA==
dependencies:
- ajv "^6.10.2"
- lodash "^4.17.14"
- slice-ansi "^2.1.0"
- string-width "^3.0.0"
+ ajv "^8.0.1"
+ lodash.truncate "^4.4.2"
+ slice-ansi "^4.0.0"
+ string-width "^4.2.3"
+ strip-ansi "^6.0.1"
text-table@^0.2.0:
version "0.2.0"
@@ -891,14 +1067,14 @@
is-number "^7.0.0"
tslib@^1.8.1:
- version "1.13.0"
- resolved "https://registry.yarnpkg.com/tslib/-/tslib-1.13.0.tgz#c881e13cc7015894ed914862d276436fa9a47043"
- integrity sha512-i/6DQjL8Xf3be4K/E6Wgpekn5Qasl1usyw++dAA35Ue5orEn65VIxOA+YvNNl9HV3qv70T7CNwjODHZrLwvd1Q==
+ version "1.14.1"
+ resolved "https://registry.yarnpkg.com/tslib/-/tslib-1.14.1.tgz#cf2d38bdc34a134bcaf1091c41f6619e2f672d00"
+ integrity sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==
-tsutils@^3.17.1:
- version "3.17.1"
- resolved "https://registry.yarnpkg.com/tsutils/-/tsutils-3.17.1.tgz#ed719917f11ca0dee586272b2ac49e015a2dd759"
- integrity sha512-kzeQ5B8H3w60nFY2g8cJIuH7JDpsALXySGtwGJ0p2LSjLgay3NdIpqq5SoOBe46bKDW2iq25irHCr8wjomUS2g==
+tsutils@3.21.0, tsutils@^3.21.0:
+ version "3.21.0"
+ resolved "https://registry.yarnpkg.com/tsutils/-/tsutils-3.21.0.tgz#b48717d394cea6c1e096983eed58e9d61715b623"
+ integrity sha512-mHKK3iUXL+3UF6xL5k0PEhKRUBKPBCv/+RkEOpjRWxxx27KKRBmmA60A9pgOUvMi8GKhRMPEmjBRPzs2W7O1OA==
dependencies:
tslib "^1.8.1"
@@ -909,27 +1085,27 @@
dependencies:
prelude-ls "^1.2.1"
-type-fest@^0.8.1:
- version "0.8.1"
- resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.8.1.tgz#09e249ebde851d3b1e48d27c105444667f17b83d"
- integrity sha512-4dbzIzqvjtgiM5rw1k5rEHtBANKmdudhGyBEajN01fEyhaAIhsoKNy6y7+IN93IfpFtwY9iqi7kD+xwKhQsNJA==
+type-fest@^0.20.2:
+ version "0.20.2"
+ resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.20.2.tgz#1bf207f4b28f91583666cb5fbd327887301cd5f4"
+ integrity sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==
-typescript@^4.0.2:
- version "4.0.2"
- resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.0.2.tgz#7ea7c88777c723c681e33bf7988be5d008d05ac2"
- integrity sha512-e4ERvRV2wb+rRZ/IQeb3jm2VxBsirQLpQhdxplZ2MEzGvDkkMmPglecnNDfSUBivMjP93vRbngYYDQqQ/78bcQ==
+typescript@^4.5.5:
+ version "4.6.2"
+ resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.6.2.tgz#fe12d2727b708f4eef40f51598b3398baa9611d4"
+ integrity sha512-HM/hFigTBHZhLXshn9sN37H085+hQGeJHJ/X7LpBWLID/fbc2acUMfU+lGD98X81sKP+pFa9f0DZmCwB9GnbAg==
uri-js@^4.2.2:
- version "4.4.0"
- resolved "https://registry.yarnpkg.com/uri-js/-/uri-js-4.4.0.tgz#aa714261de793e8a82347a7bcc9ce74e86f28602"
- integrity sha512-B0yRTzYdUCCn9n+F4+Gh4yIDtMQcaJsmYBDsTSG8g/OejKBodLQ2IHfN3bM7jUsRXndopT7OIXWdYqc1fjmV6g==
+ version "4.4.1"
+ resolved "https://registry.yarnpkg.com/uri-js/-/uri-js-4.4.1.tgz#9b1a52595225859e55f669d928f88c6c57f2a77e"
+ integrity sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==
dependencies:
punycode "^2.1.0"
v8-compile-cache@^2.0.3:
- version "2.1.1"
- resolved "https://registry.yarnpkg.com/v8-compile-cache/-/v8-compile-cache-2.1.1.tgz#54bc3cdd43317bca91e35dcaf305b1a7237de745"
- integrity sha512-8OQ9CL+VWyt3JStj7HX7/ciTL2V3Rl1Wf5OL+SNTm0yK1KvtReVulksyeRnCANHHuUxHlQig+JJDlUhBt1NQDQ==
+ version "2.3.0"
+ resolved "https://registry.yarnpkg.com/v8-compile-cache/-/v8-compile-cache-2.3.0.tgz#2de19618c66dc247dcfb6f99338035d8245a2cee"
+ integrity sha512-l8lCEmLcLYZh4nbunNZvQCJc5pv7+RCwa8q/LdUx8u7lsWvPDKmpodJAJNwkAhJC//dFY48KuIEmjtd4RViDrA==
which@^2.0.1:
version "2.0.2"
@@ -948,9 +1124,7 @@
resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f"
integrity sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=
-write@1.0.3:
- version "1.0.3"
- resolved "https://registry.yarnpkg.com/write/-/write-1.0.3.tgz#0800e14523b923a387e415123c865616aae0f5c3"
- integrity sha512-/lg70HAjtkUgWPVZhZcm+T4hkL8Zbtp1nFNOn3lRrxnlv50SRBv7cR7RqR+GMsd3hUXy9hWBo4CHTbFTcOYwig==
- dependencies:
- mkdirp "^0.5.1"
+yallist@^4.0.0:
+ version "4.0.0"
+ resolved "https://registry.yarnpkg.com/yallist/-/yallist-4.0.0.tgz#9bb92790d9c0effec63be73519e11a35019a3a72"
+ integrity sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==