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/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();