Squashed 'third_party/flatbuffers/' changes from acc9990ab..d6a8dbd26
d6a8dbd26 Experimental fix for failing oss-fuzz coverage build (#6259)
ed391e177 BREAKING: Rust flexbuffers serde human readable set to false (#6257)
a49531414 Update to flags in fuzzing-cmake file (#6256)
de1f0342c Remove _POSIX_C_SOURCE and _XOPEN_SOURCE definitions when compiling o… (#6205)
d0d51e2a5 flatc should support --binary --schema with optional scalar fields. (#6252)
33ab26017 Bump version of rules_go to 0.24.5 (#6234)
febb9d87c Union As Accessors for C# (#6251)
8778dc7c2 Resets buffer without deallocating current pointer (#6247)
aae376e9a Add GetBufferSpan() function to bufferbuilder (#6235)
0ff047148 Modernize android build and sample (#6229)
46a8c7e95 Added required-nested-flatbuffer to monster_test and fixed rust (#6236)
bc56c553e Notify based on Labelling issues and PR (#6241)
07d7cd78a Converted globs to use single quotes (#6240)
cdef70e24 More adjustments to the auto labeler (#6239)
9dd44df35 Updated Lua labeller glob (#6238)
c9b29d088 Support size-prefixed buffers and add tests for size-prefixed messages (#6232)
fba93e0ab Removes duplicate swift in labeler (#6228)
d1a545b1f Added more labels for auto labeler (#6227)
ea92a668d [C#] Optional Scalars (#6217)
6034de286 [Label Bot] Add Java and Kotlin support for the label bot (#6226)
b08b0a440 Implement `Debug` trait for Rust flatbuffers. (#6207)
17ae48dec [Label Bot] Adds some languages to labeler bot (#6222)
fc8097925 Auto Labeler Setup, Just C# for now (#6221)
55658f523 Auto Labeler Setup, Just C# for now (#6218)
14ecfe423 Updated comments and fixed a fundamental type error. (#6214)
a0182cdb1 optional scalars for ts/js (#6215)
0dfcc0a37 Adds NetTest.bat to run .NET Core tests on Windows (#6216)
f9a18ea63 [Java] Implement optional scalars (#6212)
c7586e85a Empties the sharedString map on reset on go and csharp (#6187)
914c64601 Removed C# references from java generator. Move annotations closer to definitions (#6204)
42d7c7997 Adds readable size to asserts in read functions (#6210)
e68e8d7de Refactor idl_gen_rust (#6206)
84809be7e Fix typo in flatbuffers::span declaration. (#6202)
1606fb637 Kotlin test optional enum (#6201)
fe8e3c7e5 Mass Refactoring to use `IsString` and other BASE_TYPE helpers (#6193)
8f6fa4b71 Updated SupportsAdvancedUnionFeatures to look out for string (#6190)
b46db38f5 [JS/TS] Rewrite flexbuffers JS to TS (#6148)
9fa1d2705 Rework enums in rust. (#6098)
a402b3aba idl_gen_json_schema Fix generation of arrays of enums (#6184)
0e1415b99 fix(go_test): remove deprecated grpc call (#6183)
5cd713710 Add generation of JSON Schema to library (#6165)
5be777e1d Bump junit from 4.12 to 4.13.1 in /grpc/tests (#6173)
a49d440ec Bump junit from 4.12 to 4.13.1 in /grpc (#6172)
4ec5e8db9 [C++] Add option to not generate direct copy methods. (#6166)
04bec23a3 Add Array initialization from struct constructor (#5865) (#6147)
77d57fd07 Cast to right type for reserved_ subtraction (#6167)
543c1bbeb Fixed rust nested flatbuffers for tables other than self (#6062)
cb971eece [C++] Fix -Wnarrowing and -Woverflow due to signed bitfields on G++ ARM (#6163)
7b9e61fcc [TS] GRPC Implementation (#6141)
3359e3042 Moved C++ to optional_scalars2 and added some tests. (#6162)
187a4787f [Rust] Upgrade flatbuffers library to 2018 edition (#6159)
08943aa26 Flatbuffer C++ UnpackTo optimization for vectors of non-bool bytes. (#6154)
5975658eb Enables optional enums in swift (#6160)
5d3cf440e Updated Lobster test for optional bools/enums
8ec8322f0 Ruopt enum (#6156)
bbcc85fd4 Fix generation of C++ code with Optional<Enum> (#6155)
0bdf2fa15 [C#] Fix and improve project files (#6142)
2eedc769d possibility to create a vector from an iterator (#6135)
ab01ae162 flatc should output a warning, when an attribute is attached more than once (#6146)
689bfafa7 [Python/JS/TS] Codegen SizeOf method for structs (#6136)
641309a5b unix2dos on tests/FlatBuffers.Test/FlatBuffers.Core.Test.csproj (#6133)
52e362879 SpanT is available in .Net Standard 2.0. (#6137)
dca12522a Add static cast to avoid implicit double promotion. (#6132)
e0bbaa6f9 [C#]Change to ENABLE_SPAN_T that doesn't require UNSAFE_BYTEBUFFER. (#6073)
ab139d6be Revert "[C#] Fix and improve project files (#6116)" (#6130)
34d67b425 Minireflect fixed array (#6129)
96d5e3597 [JS/TS] fix flatbuffers default export (#6123)
eb686a86f Add missed file generated by optional_scalar.fbs (#6125)
750281630 [C#] Fix and improve project files (#6116)
fb4e1c34f Add CharToLower and CharToUpper into util.s (#6126)
8c67b5b12 Add support of Optional<T> scalars to C++ code generator (#6092)
6228b66d3 [Kotlin] Support for optional scalars. (#6115)
e1be8aaad Bump version for latest swift version (#6121)
94873e595 [JS/TS] Modernize TypeScript / JavaScript flatbuffers support (#6095)
b8e87fafe [JS] Add getFullyQualifiedName() (#6119)
f96d1ef74 [Java] allowing larger buffer sizes when growing a byte buffer (#6118)
89435303b [Swift] Migrates struct write APIS to write directly to the buffer (#6093)
c75ae2429 Optional-ness in reflection (#6097)
338944d3d Rename Nullable scalars to Optional scalars (#6112)
f5ab24bc4 Avoid memcpy call for empty vectors (#6111)
92a8c1a0f [JS] FlexBuffers Fix for wrong type of offset and length values (#6107)
6cea45dcd fix c# json serializer commandline argument docs (#6104)
fec58aa12 Fix for issue 6100: incorrect shrinking logic in ResizeContext() (#6102)
71aca81ff [JS] FlexBuffers Support (#5973)
04d87ffec [C++] Small refactoring of the C++ code generator (#6091)
bb25956f0 Wrap verify file id condition in Check call (#6085)
49f4948f0 + Add `removable-media` plug to the snapcraft config (#6083)
eeacc53d2 Adds proper access types for swift object api & flatbuffers & grpc (#6081)
f3003e08d [Lobster] missed a test
d713a0084 [CMake] enabled multi-core builds in VS projects
77f966f89 [Lobster] optional scalars support
e86d5b8e9 [Kotlin] Attach JvmStatic annotation to each method in companion object (#6052)
db2aa9b4e [C#] Cleaned up .NET testing script for Mono (#6016)
63cc0eec4 Adds a serialize helper function to native table (#6059)
c30a87de6 [TS] Fix four bugs with imported types in TypeScript. (#6054)
a0fb30575 [Swift] Append namespace for Swift Grpc implementation (#6049)
77c18c1d6 export a __version__ variable for python module (#5309)
f1f23d08e adding fb import when no other imports are present (#6030)
f1025b284 [Feature] Checks for Nullable strings (#6050)
5d052f4e5 [Swift] RFC: Switch Swift namespace from public enum to ordinary concat with _ (#6045)
18b015d25 Rust codegen improvements and lint fixes (#6046)
d76e93f27 adds code gen for optional scalars in swift (#6038)
82fac326c [C++] Fix compiler error from deleted assignment operator (#6036) (#6047)
043b52bd4 Optional Scalars support for Rust (#6034)
c8fa0afdf Allow to run cpp tests under grpc/tests/ using bazel. (#6040)
6d0aae73c Fix git command executed in wrong folder when doing cmake superbuild (#6039)
ff1b73128 [Swift] Optional Scalars Preparation (#6028)
2e48c8dd3 tests: Check for both quiet and signaling NaN on mipsel/hppa (#6029)
6942704f2 support deprecated flag in json schema (#6022)
9ecd2e16c Flatc parser support for nullable scalars (#6026)
33e2d8079 [Dart] Generate constant values map for enums (#6025)
969d0f7a6 Using proper symbol name for reexport (#6021)
515a4052a Silence false positive "-Wstringop-overflow" on GCC 10.0 to 11.0 (#6020)
36fbe6f13 Updated FB import (#6019)
b69fc8cc9 [Java] Add support for shared strings on FlatBufferBuilder. (#6012)
ab6af18d9 Not using non-existent create method for obj api (#6015)
37a5dee10 Code cleanup + updates test and readme (#6004)
8a721f69a Serde with bytes maps to Blob (#6009)
e810635ea [Swift] FlatBuffers createMonster method doesn't treat struct properly (#5992)
4995e1527 Manage grpc dependency in Bazel's WORKSPACE file. (#5995)
60b6066fe Add warning to schema parser if field name is not snake_case. (#6005)
35d45cac7 [Rust] Flexbuffers dependency cleanup and fixes (#5998)
165a6e3d1 Re-added Evolution Schema Code Generation Command (#5999)
13d3fb2ea Fix RPM install conflict (#6003)
d64078eb2 [Swift] Initialize memory when clear ByteBuffer (#5982)
ca1190a3d [TS] Use proper TypedArray in create*Vector (#5991)
7571b2ac5 [C++] Updates real_path to be truly portable (#5787)
e5a8f76a4 [C++] Generate default member initializers for >= C++11 (#5989)
413bb9b55 [Kotlin] Fix Access to union of vector element (#5994)
f35184aef [Swift] Add parsing from unowned UnsafeMutableRawPointer for ByteBuffer (#5981)
b124b7625 Removed requirement that enums be declared in ascending order. (#5887)
0ec7600c6 Do not remove the last digit from float values (#5974)
14baf45c9 Mark GetBufferMinAlignment() const (#5985)
9abb2ec2c TypeScript/JavaScript docs improvements (#5984)
2e57d80b1 [Swift] Internal library improvements (#5965)
cfc7753a4 [Doc] Added missing letters to compiler options (#5976)
12ddc8a92 Rust Flexbuffers Documentation update (#5979)
24ad35709 [docs] typo: updates monsterdata.json to be valid json (#5978)
cc44a4442 [idl_parser] Mark typefield as deprecated (#5958)
9ab4a5c0e Deleted old stale bot
6682cfe87 Increased Operations per run in stale.yml
64922904b Adding Stale Action to clean up PR and Issues
8e505cb67 [C++] Fixed/Enabled --cpp-ptr-type std::shared_ptr [#5813] (#5959)
a28357d7a Propagate boolean default values from proto to fbs (#5964)
7cb4762a6 [Swift] Improving reallocation time by using memcpy and moving reallocation code to storage (#5960)
4e45f7c9e Fix error in SimpleQSort (#5955)
7ac026405 fix error on GRPC Python - ignore namespace tree if not specified (#5862) (#5922)
108e981db Required is now implemented in swift (#5952)
94a78e385 Fixed: Access violation and ASAN/UNSAN failures with sorted tables
53fb453e0 [rust] Add FlatBufferBuilder::force_defaults API (#5946)
17c1f35fa [FlexBuffer][Java] ReadWriteBuf and ReadBuf interface public (#5948)
2eaf57778 [Java] Grow ArrayReadWriteBuf enough to match requested capacity. (#5921)
666800da3 Adds bool support in structs + updates grpc support + CI upgrades (#5943)
38ed69eb3 fixed mutating inline values (#5942)
d026e6f07 Add static asserts to ensure that reflection API arrays are kept in sync (#5934)
988164f6e [C++] Got rid of memset's in constructors (#5938)
7179a5a8b General Codebase clean up (#5939)
a0da0c08c Add GetStringView like GetString, GetCstring (#5937)
ac203b209 [C#] Add file identifier to ObjectAPI Serialization Utility. (#5920)
8dd1bf25b not creating creation methods when using structs (#5919)
5aa443d98 [Dart] Adding FlexBuffers support (#5853)
0fa087657 [Dart] Getting tests/DartTest.sh to work on master. (#5915)
424a473e1 Schema parser: prohibit declaration of an array of pointers inside structs (#5907)
c3faa8346 Fix Cargo.toml dependencies (#5911)
91399ad05 fix union type names (#5902)
32782e4ad Update Rust Flexbuffers metadata before publishing (#5905)
e7f3b1690 [TS] Make Obj-API work with --short-names (#5898)
12ed1fe4a fixed invalid imports with --gen-all (#5895)
85ee4df7a [C#] Thread safe reads of Double and Float values from a ByteBuffer (#5900)
de89bd193 Implement flexbuffers in python (#5880)
8be05f6bd Rust Flexbuffers (#5669)
870ecbc09 [swift] Moves code to use VTablesStorage (#5888)
c2da8d5d8 [Java][FlexBuffers] Make FlexBuffersBuilder reusable by adding clear() (#5889) (#5890)
e84cbff67 Align package name to FindFlatBuffers.cmake (#5899)
f94e6c84e Small tutorial improvements - documentation only (#5894)
f12cca8bc Attempt at adding Github Actions CI
7e4124d6e Handle git program or .git folder absence (#5878)
a875d247a only add native_include_files if object based api is enabled (#5886)
6e9f5d981 Respect shared attribute in Parser (#5885)
ff1c78233 include/flatbuffers: typo fixes in comments (#5884)
2e9a19673 Updates swift docs for package management (#5883)
e3cb07d32 [Rust] idl_gen_rust.cpp: (Option/required-aware codegen for unions) (#5850)
712866d57 Propagate use_string_pooling in CopyTable (#5879)
44c919a9e Not using reexports with --gen-all (#5873)
99aa1ef21 Added INCLUDE_PREFIX option for flatbuffers_generate_headers (#5866)
40ba170c9 Fixed text in internals doc that implied structs can be root
cb4d0f72e [Swift] Object API support (#5826)
003e16405 [TS] Add Obj API (#5788)
21cf300f4 fix cpp usage markdown error (#5845)
9655e12d6 Upgraded swift implementation for grpc (#5843)
fb96fadc2 [C#] Fix nested structs and arrays in Object API (#5765)
408f11fbd [ts] Fix empty source/dest namespaces when reexporting. (#5841)
a83caf591 Improves performance for the swift library by using structs + a storage class (#5835)
925fab6b1 [Java][FlexBuffers] Optimize Map access (#5735)
d9fecc332 [CMake] : Add precompiled header support with FLATBUFFERS_ENABLE_PCH (#5827)
e9d453240 Added flatbuffers_generate_headers and flatbuffers_generate_binary_files cmake functions. (#5830)
c37c989ed Correct calculation of vector element size (#5831)
6b271b7ec Fix Clang-trunk warnings about special members deprecated in C++20. (#5829)
90f3b8e8c Fix `float_constant` definition in './doc/Grammar.md` (#5828)
3af735934 [csharp] flatc should generate a 'Create…' method for tables with struct field… (#5818)
c4231c3cb Updated doxyfile - added missing files (#5824)
9657df184 Update Grammar.md (#5820)
97ffc590e Include CPack only when explictly packaging (#5817)
8b52af65b [C++] Add max_depth and max_tables parameters to reflection::Verify (#5815)
9b034eee1 Fix interpretation of 'nan(number)' by the idl_parser (#5810)
3e9ac3cff [Scripts] Adds swift to generated code (#5806)
697147a2e updated maven build files
6df40a247 pre-tag version bump for 1.12
0dba63909 Removes the inner loop in the endtable check written tables (#5803)
0e3fdd0ee Escape characters in jsonschema descriptions (#5644)
45a2b07cb Remove `noexcept` qualifier copy-ctor of `union` type (#5800) (#5802)
d10c16314 Replace 'assert' by 'FLATBUFFERS_ASSERT' inside idl_parser.cpp (#5799)
35abb7f89 Add non-nullable modifier to return type of functions never returning null (#5797)
9954e09ab [C++] Generate code for vector force_align attribute. (#5796)
95a21327f rust: pub export the VectorIter type (#5736)
89b6183ee Fix Python min alignment
5a98d65e8 [Rust] Add gen-name-strings for Rust (#5757)
f73d205bc Removed assert that wasn't backwards compatible.
7c37abe92 [C#] add ObjectAPI Serialization Utility (#5785)
4749e77b0 Fixed docs on how to obtain parser error.
6ff189841 Added --filename-suffix and --filename-ext to flatc (#5778)
c9a30c9ca Fixed refractoring issue in reflection/generate_code.sh. Also, mv deletes the original file, so I don't need to clean it up manually in that case. (#5777)
8c02d17be Skip writing reflection_generated.h if not changed (#5776)
34305c4ce [Swift] Adds GRPC to Swift (#5758)
cd88e6b2a [Java][FlexBuffers] Abstract buffer access from ByteBuffer (#5743)
3ec7a53c6 Adds cocoapods and a readme of how to get the package (#5771)
6d44cede7 [snap] Fix versioning (#5727)
cc08c0835 [Python] Fixed potential allignment issue (#5768)
54f8b787c Fix memory leak on cpp object api (#5761)
17557f913 [Python] Fixed issue #5499 (#5764)
d54af8cd4 [C++] Use strong enum type for vectors when scoped-enums is on. (#5750)
173e10fdf [C#] support Json Serialization (#5752)
8f56990f6 FlexBuffers: C++: scalar-only typed vectors were not aligned.
6400c9b05 Bump Rust port to 0.6.1 (#5747)
7418d8587 [C#] support Object API (#5710)
c580fa284 Adds min and max, comments, and all of swift's keywords + fix docs (#5737)
f2a127230 Use VS 2017 and 2019 on CI, fix cast issue in dart_idl (#5740)
316d7c208 Creates a flatbuffers validation function + small fix (#5725)
47026ea6b Added the code to embed the binary schema to the source (--bfbs-gen-embed). (#5701)
3f677f241 [Java][FlexBuffers] Deprecate typed vector strings due to design flaw (#5722)
a593a11e5 [Go] Implements a SharedStrings function (#5733)
7cdfc8475 [Swift] Fix padding function overflow when bufSize is 0 (#5721)
bab2b0db4 Add vcpkg installation instructions (#5732)
89418eb84 [Dart] Fix deprecated field support, inf/nan (#5724)
9cadf05d8 [typescript] Size-prefixed root accessors not taking into account size prefix (#5717)
6da1cf79d [rust] Add use declarations to Rust-generated bindings for imported FB definitions (#5645)
bee1df96d [Go] Replace references to hardcoded ”Monster" etc with idiomatic go wherever possible (#5716)
01189d7ed [C++] Fix for printing of enum in case output_enum_identifiers=1. (#5706)
c4b2b0a25 [Swift] Support create long string (#5709)
a4b2884e4 Added create function for swift (#5707)
04d80f255 [Swift] Swift implementation 🎉🎉 (#5603)
55686100a Changed direct calls to strtod to use StringToNumber
718351831 Document JSON compatibility guarantees. (#5704)
d1b34f0f2 Add CMake 'generated_code' target to simplify resolution of build dependencies (#5697)
21b706196 (Optionally) add an additional suffix namespace to generated fbs files. (#5698)
35daaf83d [Java] Replace Table.UTF8_CHARSET with StandardCharsets.UTF_8 (#5696)
3b458f7a1 Rust: Temporarily disable 2 endianness unit tests (#5695)
a5d9d0f7d [C++17] Add Traits class for Tables and Factory function within it. (#5678)
3cd9b6434 Removed code_generators.cpp from library targets
355dfd48d [rust] Make enum names public (#5690)
bcd58a159 Correct inverted logic around include prefixes. (#5689)
a2c12900a Optimize Pack method using numpy (#5662)
901b89e73 [C++] Add Builder and Table typedefs (#5685)
31f879908 Minor doc updates: FlexBuffers C#, Discord, CppUsage.
8023d99e2 Upgrade rules_go (#5684)
b4154405d Fix --incompatible_load_cc_rules_from_bzl (#5683)
04c17c7a7 Add support for absl::string_view when available (#5682)
62ec7d52c [Bazel] Add support for compatible_with and restricted_to (#5681)
7de668053 CI: New Docker tests for Python with numpy (#5677)
3a70e0b30 Fixed struct initialization error on older versions of C#
9b1320135 Fixed warnings in FlexBuffers.java
5e3916050 Fixed out of date licenses on gRPC Python files.
c95755051 Removed test proto output.
44bf71988 Add flatc '--cpp_std' switch (#5656)
3e8f15df9 Fix for FlexBuffers FBT_VECTOR_STRING size bit-width.
602721a73 Added Check to VerifyAlignment (#5675)
13c05f4da Improve import handling for proto conversion (#5673)
ce3a1c43a [Dart] Fix prepare space for writeListInt64 and writeListUint64 (#5654)
aa75e5734 Make Rust constants public (#5659)
2790fee25 Add namespace qualification to union types (#5666)
eddebec1b Bugfix for Rust generation of union fields named with language keywords (#5592)
030fee36a wrap multiple statements in do {} while(!IsConstTrue(true)) (#5655)
f9724d1bd [gRPC] Uncomment MessageBuilder (#5658)
b20801ca4 Supress unsigned-integer-overflow for PaddingBytes (#5647)
a8e800bd7 Add --force-empty-vectors option (#5653)
d7530ae96 Fixed enum min/max values not properly escaped.
99d11e279 Split Bazel targets into multiple packages (#5640)
4fd8eb214 Remove a static_assert (#5643)
65f870357 Flatbuffers Python Object API (#5616)
75823cc27 [Clang 10]: definition of implicit copy constructor for 'TableKeyComparatoris deprecated #5649 (#5650)
58e279244 [docs]: add missing semicolon (#5648)
3c964e10a [GO] Fix support for enums with underscores and Unions with imported members (#5600)
c3c32ec94 Fix ambiguity of a type deduction in TEST_EQ macro if arguments have `enum class` type. (#5630)
075e8d676 Simplify declarations of x-macro FLATBUFFERS_TD (#5638)
bcf1bd5c9 read vtable size through ReadScalar() (#5636)
136d75fa6 Changed null checks in test. Removed verifier pointer usage (#5634)
091fa1fd1 Add testing of C++ with sanitizers (CI-Docker) (#5631)
ff3781dc2 add namespace prefix in FLATBUFFERS_MAX_BUFFER_SIZE (#5629)
6beb9f49c Support for python grpc - continuing the work from the pull request #4270 #4705 (#5613)
80988ea86 Removed idl_gen_general.cpp and move contents to code_generators.cpp (#5625)
0f2ff7eaa Lua cleanup (#5624)
dda095023 [C++] Adds basic schema evolution tests (#5611)
adbcbba5d [C++, C#, Java] Separated C# and Java generators into their own classes (#5618)
cbbd6aca0 add check for root_type specified for json schema generation (#5622)
405c64e07 [Rust] Bump smallvec version to 1.0 (#5621)
42c08cbca Ran src/clang-format-all.sh (#5617)
33d5dd9bd Improved pull request & clang-format instructions.
105dd528e Change monster_extra generation to use flatbuffers::unique_ptr (#5612)
f0f0efe7b [C++] Refactor to conform to Google C++ style guide (#5608)
e837d5a29 Fixed deprecated method in GRPC Java test.
9834ee978 Fixed Apache license not using canonical version.
44b2ab087 include/flatbuffers/base.h: fix no_sanitize issue with old clang (#5610)
46ae3f80a [C++, Java, C#, TypeScript, JavaScript] Skip generation of mutable union types (#5599)
7b38aa71e flatbuffers.h: fix documentation warning (#5607)
661bedd83 Add Lua FlatbufferBuilder Clean() method to enable reuseable builders (#5606)
8526e12d7 [Kotlin] Fix union vector accessor after change in Java API (#5605)
3c7b660d6 [flatc] Remove an always true condition for flexbuffers (#5604)
964365ba6 [Go] Add UnPackTo functions (#5598)
32254b7ac [Go] Object API support (#5339)
521e255ad Rust: Add idiomatic iterator for Vector type (#5579)
1b85292fd Fix typos in comments (#5590)
480815447 C++ verifier for evolved union fields should return true (#5586)
8d5e424c6 Add ByteBuffer copy for vector of bytes in Java (#5587)
b4774d235 Rust: Fix Copy and Clone impls for a few generic types (#5577)
26f238c24 Add `--clean-first` to the cmake-build command (travis) (#5574)
e93c8c46e Fix Follow implementation for bool (#5554)
e21516b9d Fix issue #5557 (#5573)
fbc11e8ae Avoid intentional unsigned integer overflow getting caught by sanitizers (#5572)
e9d29c21a Python: Add forceDefaults opt to python Builder (#5564)
8bfafc76d Java: Don't annotate vector-of-tables item getters with @nullable. (#5562)
df3e8bf4a Fixed warnings generated by recent JSON sorting feature.
5665cfe49 [Java] byte buffer factory returned buffer capcity is used instead of the requested size (#5558)
5797540ed #5544 Fix of Array of table is not sorted if Create<type>Direct() is used (#5546)
7f1af7cb0 Fix build with gcc version 7.4.0 (#5570)
32f47ad24 Fixed JSON parser not sorting vectors of tables/structs with key.
842f672ba [FlexBuffers][Java] Cache size of Sized objects in FlexBuffers (#5551)
d4cae0a62 Fix issue #5542 (#5543)
f1147f65b Fixed Android STLPort related error.
69d3fec48 Fix namespaced struct/field name collision detection (#5540) (#5545)
cfb4ecf6f [flac] Add FlexBuffers option for generating data (#5519)
a92039687 Update Rust versions under test from 1.30.1 to 1.37.0 (#5538)
625338d09 Adds XOPEN_SOURCE for PATH_MAX and POSIX 1993 for stat (#5529)
3f8ce99c5 [FlexBuffers][Java] Add override Key::toString (#5533)
0798b7b69 [FlexBuffers][Java] Fix wrong access to a string using Reference::asString(). (#5532)
cbdf82e2f Fix Mutate() methods of Array<scalar/struct> (override 5508) (#5526)
e365c502f Java: Added access object for vector of struct and vector of tables. (#5233)
97f3aa917 Fixed DetachedBuffer self move assignment (#5521)
2f5bb2eec Fix buildifier warnings found in new bazel (#5517)
917687c7a Fixed Reflection Verifier not handling vectors of unions.
f9277e691 Fixed GenerateText not handling vectors of unions.
2706381ee Add element size parameter to __vector_as_arraysegment [c#] (#5512)
b5560fcd5 [Java][FlexBuffers] Improve documentation for FlexBuffers in Java. (#5506)
782b865c5 Annotate getters with @Pure when --java-checkerframework is specified. (#5510)
3bfc86eaf [Dart]fix: segment fault with empty namespace when generating dart file (#5507)
c0282873f Rust: Fixed cargo clippy on non-generated code (#5485)
4b870aca9 [Javascript] Fix syntax error for signed enum (#5503)
d0e3870c0 [C#] Fix retrieving enumeration vectors as arrays (#5457)
fb25eb87f Doc typo fixes (#5505)
cb35d3a0e Use all of the available space in the buffer returned by ByteBufferFactory to allow the factory to keep a pool of larger than initialsize sized buffers. (#5500)
8e6cabb31 [FlexBuffers][Java] Implementation of FlexBuffers API (#5476)
bd31dd242 Clarified value reuse in FlexBuffers
65b67d213 Fixed test build invocation of arrays_test.fbs
1fbb71132 FlexBuffers: allow any values to be shared.
cd75a3658 Android: remove app_dummy() calls
ec6b0bf29 Fixed STLPort Android compile error
c11b5d744 [bugfix]flexbuffers isvector bugfix (#5488)
4525c91be Fix incorrect padding in arrays of structs (Issue #5484) (#5491)
b97b342f5 Fixed missing generated code.
c1058a903 C++ IDL generation adds superfluous semicolon in GenTablePost, causing (#5483)
303044934 [go]add Name() for ForceCodec interface (#5486)
a2485d4ec reflection: check for valid union enum value during object verification (#5475)
a20e71ac9 has_method support for primitive fields in java runtime. Changed: idl.h, FlatBufferBuilder.java , idl_gen_general.cpp, idl_parser.cpp, flatc.cpp (#5468)
Change-Id: I836f4b43e6818bb16425a87899e6234ac86242aa
git-subtree-dir: third_party/flatbuffers
git-subtree-split: d6a8dbd26ff08a8868e0d0c1b4b67d31b40e4a7f
diff --git a/swift/FlatBuffers.podspec b/swift/FlatBuffers.podspec
new file mode 100644
index 0000000..b106b4c
--- /dev/null
+++ b/swift/FlatBuffers.podspec
@@ -0,0 +1,21 @@
+Pod::Spec.new do |s|
+ s.name = 'FlatBuffers'
+ s.version = '0.8.1'
+ s.summary = 'FlatBuffers: Memory Efficient Serialization Library'
+
+ s.description = "FlatBuffers is a cross platform serialization library architected for
+ maximum memory efficiency. It allows you to directly access serialized
+ data without parsing/unpacking it first, while still having great
+ forwards/backwards compatibility."
+
+ s.homepage = 'https://github.com/google/flatbuffers'
+ s.license = { :type => 'Apache2.0', :file => 'LICENSE' }
+ s.author = { 'mustii' => 'mustii@mmk.one' }
+ s.source = { :git => 'https://github.com/mustiikhalil/flatbuffers.git', :tag => s.version.to_s, :submodules => true }
+
+ s.ios.deployment_target = '11.0'
+ s.osx.deployment_target = '10.14'
+
+ s.swift_version = '5.0'
+ s.source_files = 'Sources/**/*'
+end
diff --git a/swift/LICENSE b/swift/LICENSE
new file mode 100644
index 0000000..d645695
--- /dev/null
+++ b/swift/LICENSE
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/swift/Package.swift b/swift/Package.swift
new file mode 100644
index 0000000..729ad40
--- /dev/null
+++ b/swift/Package.swift
@@ -0,0 +1,22 @@
+// swift-tools-version:5.2
+// The swift-tools-version declares the minimum version of Swift required to build this package.
+
+import PackageDescription
+
+let package = Package(
+ name: "FlatBuffers",
+ platforms: [
+ .iOS(.v11),
+ .macOS(.v10_14),
+ ],
+ products: [
+ .library(
+ name: "FlatBuffers",
+ targets: ["FlatBuffers"]),
+ ],
+ targets: [
+ .target(
+ name: "FlatBuffers",
+ dependencies: []),
+ ]
+)
diff --git a/swift/README.md b/swift/README.md
new file mode 100644
index 0000000..c3060fd
--- /dev/null
+++ b/swift/README.md
@@ -0,0 +1,17 @@
+FlatBuffers swift can be found in both SPM
+
+`.package(url: "https://github.com/mustiikhalil/flatbuffers.git", from: "X.Y.Z"),`
+
+and Cocoapods
+
+`pod 'FlatBuffers'`
+
+### Notes
+
+1- To report any error please use the main repository.
+
+2- `0.6.0` deprecates `add(condition:bool)` for `add(element:bool)`. You can download the [binary here](https://github.com/google/flatbuffers/actions) and select the latest push to master
+
+### Contribute
+
+1- Always run `swift test --generate-linuxmain` whenever new test functions are added or removed
\ No newline at end of file
diff --git a/swift/Sources/FlatBuffers/ByteBuffer.swift b/swift/Sources/FlatBuffers/ByteBuffer.swift
new file mode 100644
index 0000000..46ae1c5
--- /dev/null
+++ b/swift/Sources/FlatBuffers/ByteBuffer.swift
@@ -0,0 +1,345 @@
+import Foundation
+
+public struct ByteBuffer {
+
+ /// Storage is a container that would hold the memory pointer to solve the issue of
+ /// deallocating the memory that was held by (memory: UnsafeMutableRawPointer)
+ @usableFromInline final class Storage {
+ // This storage doesn't own the memory, therefore, we won't deallocate on deinit.
+ private let unowned: Bool
+ /// pointer to the start of the buffer object in memory
+ var memory: UnsafeMutableRawPointer
+ /// Capacity of UInt8 the buffer can hold
+ var capacity: Int
+
+ init(count: Int, alignment: Int) {
+ memory = UnsafeMutableRawPointer.allocate(byteCount: count, alignment: alignment)
+ capacity = count
+ unowned = false
+ }
+
+ init(memory: UnsafeMutableRawPointer, capacity: Int, unowned: Bool) {
+ self.memory = memory
+ self.capacity = capacity
+ self.unowned = unowned
+ }
+
+ deinit {
+ if !unowned {
+ memory.deallocate()
+ }
+ }
+
+ func copy(from ptr: UnsafeRawPointer, count: Int) {
+ assert(!unowned, "copy should NOT be called on a buffer that is built by assumingMemoryBound")
+ memory.copyMemory(from: ptr, byteCount: count)
+ }
+
+ func initialize(for size: Int) {
+ assert(!unowned, "initalize should NOT be called on a buffer that is built by assumingMemoryBound")
+ memset(memory, 0, size)
+ }
+
+ /// Reallocates the buffer incase the object to be written doesnt fit in the current buffer
+ /// - Parameter size: Size of the current object
+ @usableFromInline internal func reallocate(_ size: Int, writerSize: Int, alignment: Int) {
+ let currentWritingIndex = capacity &- writerSize
+ while capacity <= writerSize &+ size {
+ capacity = capacity << 1
+ }
+
+ /// solution take from Apple-NIO
+ capacity = capacity.convertToPowerofTwo
+
+ let newData = UnsafeMutableRawPointer.allocate(byteCount: capacity, alignment: alignment)
+ memset(newData, 0, capacity &- writerSize)
+ memcpy(newData.advanced(by: capacity &- writerSize), memory.advanced(by: currentWritingIndex), writerSize)
+ memory.deallocate()
+ memory = newData
+ }
+ }
+
+ @usableFromInline var _storage: Storage
+
+ /// The size of the elements written to the buffer + their paddings
+ private var _writerSize: Int = 0
+ /// Aliginment of the current memory being written to the buffer
+ internal var alignment = 1
+ /// Current Index which is being used to write to the buffer, it is written from the end to the start of the buffer
+ internal var writerIndex: Int { return _storage.capacity &- _writerSize }
+
+ /// Reader is the position of the current Writer Index (capacity - size)
+ public var reader: Int { return writerIndex }
+ /// Current size of the buffer
+ public var size: UOffset { return UOffset(_writerSize) }
+ /// Public Pointer to the buffer object in memory. This should NOT be modified for any reason
+ public var memory: UnsafeMutableRawPointer { return _storage.memory }
+ /// Current capacity for the buffer
+ public var capacity: Int { return _storage.capacity }
+
+ /// Constructor that creates a Flatbuffer object from a UInt8
+ /// - Parameter bytes: Array of UInt8
+ public init(bytes: [UInt8]) {
+ var b = bytes
+ _storage = Storage(count: bytes.count, alignment: alignment)
+ _writerSize = _storage.capacity
+ b.withUnsafeMutableBytes { bufferPointer in
+ self._storage.copy(from: bufferPointer.baseAddress!, count: bytes.count)
+ }
+ }
+
+ /// Constructor that creates a Flatbuffer from the Swift Data type object
+ /// - Parameter data: Swift data Object
+ public init(data: Data) {
+ var b = data
+ _storage = Storage(count: data.count, alignment: alignment)
+ _writerSize = _storage.capacity
+ b.withUnsafeMutableBytes { bufferPointer in
+ self._storage.copy(from: bufferPointer.baseAddress!, count: data.count)
+ }
+ }
+
+ /// Constructor that creates a Flatbuffer instance with a size
+ /// - Parameter size: Length of the buffer
+ init(initialSize size: Int) {
+ let size = size.convertToPowerofTwo
+ _storage = Storage(count: size, alignment: alignment)
+ _storage.initialize(for: size)
+ }
+
+ #if swift(>=5.0)
+ /// Constructor that creates a Flatbuffer object from a ContiguousBytes
+ /// - Parameters:
+ /// - contiguousBytes: Binary stripe to use as the buffer
+ /// - count: amount of readable bytes
+ public init<Bytes: ContiguousBytes>(
+ contiguousBytes: Bytes,
+ count: Int
+ ) {
+ _storage = Storage(count: count, alignment: alignment)
+ _writerSize = _storage.capacity
+ contiguousBytes.withUnsafeBytes { buf in
+ _storage.copy(from: buf.baseAddress!, count: buf.count)
+ }
+ }
+ #endif
+
+ /// Constructor that creates a Flatbuffer from unsafe memory region without copying
+ /// - Parameter assumingMemoryBound: The unsafe memory region
+ /// - Parameter capacity: The size of the given memory region
+ public init(assumingMemoryBound memory: UnsafeMutableRawPointer, capacity: Int) {
+ _storage = Storage(memory: memory, capacity: capacity, unowned: true)
+ _writerSize = capacity
+ }
+
+ /// Creates a copy of the buffer that's being built by calling sizedBuffer
+ /// - Parameters:
+ /// - memory: Current memory of the buffer
+ /// - count: count of bytes
+ internal init(memory: UnsafeMutableRawPointer, count: Int) {
+ _storage = Storage(count: count, alignment: alignment)
+ _storage.copy(from: memory, count: count)
+ _writerSize = _storage.capacity
+ }
+
+ /// Creates a copy of the existing flatbuffer, by copying it to a different memory.
+ /// - Parameters:
+ /// - memory: Current memory of the buffer
+ /// - count: count of bytes
+ /// - removeBytes: Removes a number of bytes from the current size
+ internal init(memory: UnsafeMutableRawPointer, count: Int, removing removeBytes: Int) {
+ _storage = Storage(count: count, alignment: alignment)
+ _storage.copy(from: memory, count: count)
+ _writerSize = removeBytes
+ }
+
+ /// Fills the buffer with padding by adding to the writersize
+ /// - Parameter padding: Amount of padding between two to be serialized objects
+ @usableFromInline mutating func fill(padding: Int) {
+ assert(padding >= 0, "Fill should be larger than or equal to zero")
+ ensureSpace(size: padding)
+ _writerSize = _writerSize &+ (MemoryLayout<UInt8>.size &* padding)
+ }
+
+ ///Adds an array of type Scalar to the buffer memory
+ /// - Parameter elements: An array of Scalars
+ @usableFromInline mutating func push<T: Scalar>(elements: [T]) {
+ let size = elements.count &* MemoryLayout<T>.size
+ ensureSpace(size: size)
+ elements.reversed().forEach { (s) in
+ push(value: s, len: MemoryLayout.size(ofValue: s))
+ }
+ }
+
+ /// A custom type of structs that are padded according to the flatbuffer padding,
+ /// - Parameters:
+ /// - value: Pointer to the object in memory
+ /// - size: Size of Value being written to the buffer
+ @available(*, deprecated, message: "0.9.0 will be removing the following method. Regenerate the code")
+ @usableFromInline mutating func push(struct value: UnsafeMutableRawPointer, size: Int) {
+ ensureSpace(size: size)
+ memcpy(_storage.memory.advanced(by: writerIndex &- size), value, size)
+ defer { value.deallocate() }
+ _writerSize = _writerSize &+ size
+ }
+
+ /// Prepares the buffer to receive a struct of certian size.
+ /// The alignment of the memory is already handled since we already called preAlign
+ /// - Parameter size: size of the struct
+ @usableFromInline mutating func prepareBufferToReceiveStruct(of size: Int) {
+ ensureSpace(size: size)
+ _writerSize = _writerSize &+ size
+ }
+
+ /// Reverse the input direction to the buffer, since `FlatBuffers` uses a back to front, following method will take current `writerIndex`
+ /// and writes front to back into the buffer, respecting the padding & the alignment
+ /// - Parameters:
+ /// - value: value of type Scalar
+ /// - position: position relative to the `writerIndex`
+ /// - len: length of the value in terms of bytes
+ @usableFromInline mutating func reversePush<T: Scalar>(value: T, position: Int, len: Int) {
+ var v = value
+ memcpy(_storage.memory.advanced(by: writerIndex &+ position), &v, len)
+ }
+
+ /// Adds an object of type Scalar into the buffer
+ /// - Parameters:
+ /// - value: Object that will be written to the buffer
+ /// - len: Offset to subtract from the WriterIndex
+ @usableFromInline mutating func push<T: Scalar>(value: T, len: Int) {
+ ensureSpace(size: len)
+ var v = value
+ memcpy(_storage.memory.advanced(by: writerIndex &- len), &v, len)
+ _writerSize = _writerSize &+ len
+ }
+
+ /// Adds a string to the buffer using swift.utf8 object
+ /// - Parameter str: String that will be added to the buffer
+ /// - Parameter len: length of the string
+ @usableFromInline mutating func push(string str: String, len: Int) {
+ ensureSpace(size: len)
+ if str.utf8.withContiguousStorageIfAvailable({ self.push(bytes: $0, len: len) }) != nil {
+ } else {
+ let utf8View = str.utf8
+ for c in utf8View.reversed() {
+ push(value: c, len: 1)
+ }
+ }
+ }
+
+ /// Writes a string to Bytebuffer using UTF8View
+ /// - Parameters:
+ /// - bytes: Pointer to the view
+ /// - len: Size of string
+ @usableFromInline mutating internal func push(bytes: UnsafeBufferPointer<String.UTF8View.Element>, len: Int) -> Bool {
+ memcpy(_storage.memory.advanced(by: writerIndex &- len), UnsafeRawPointer(bytes.baseAddress!), len)
+ _writerSize = _writerSize &+ len
+ return true
+ }
+
+ /// Write stores an object into the buffer directly or indirectly.
+ ///
+ /// Direct: ignores the capacity of buffer which would mean we are referring to the direct point in memory
+ /// indirect: takes into respect the current capacity of the buffer (capacity - index), writing to the buffer from the end
+ /// - Parameters:
+ /// - value: Value that needs to be written to the buffer
+ /// - index: index to write to
+ /// - direct: Should take into consideration the capacity of the buffer
+ func write<T>(value: T, index: Int, direct: Bool = false) {
+ var index = index
+ if !direct {
+ index = _storage.capacity &- index
+ }
+ assert(index < _storage.capacity, "Write index is out of writing bound")
+ assert(index >= 0, "Writer index should be above zero")
+ _storage.memory.storeBytes(of: value, toByteOffset: index, as: T.self)
+ }
+
+ /// Makes sure that buffer has enouch space for each of the objects that will be written into it
+ /// - Parameter size: size of object
+ @discardableResult
+ @usableFromInline mutating func ensureSpace(size: Int) -> Int {
+ if size &+ _writerSize > _storage.capacity {
+ _storage.reallocate(size, writerSize: _writerSize, alignment: alignment)
+ }
+ assert(size < FlatBufferMaxSize, "Buffer can't grow beyond 2 Gigabytes")
+ return size
+ }
+
+ /// pops the written VTable if it's already written into the buffer
+ /// - Parameter size: size of the `VTable`
+ @usableFromInline mutating internal func pop(_ size: Int) {
+ assert((_writerSize &- size) > 0, "New size should NOT be a negative number")
+ memset(_storage.memory.advanced(by: writerIndex), 0, _writerSize &- size)
+ _writerSize = size
+ }
+
+ /// Clears the current size of the buffer
+ mutating public func clearSize() {
+ _writerSize = 0
+ }
+
+ /// Clears the current instance of the buffer, replacing it with new memory
+ mutating public func clear() {
+ _writerSize = 0
+ alignment = 1
+ _storage.initialize(for: _storage.capacity)
+ }
+
+ /// Reads an object from the buffer
+ /// - Parameters:
+ /// - def: Type of the object
+ /// - position: the index of the object in the buffer
+ public func read<T>(def: T.Type, position: Int) -> T {
+ assert(position + MemoryLayout<T>.size <= _storage.capacity, "Reading out of bounds is illegal")
+ return _storage.memory.advanced(by: position).load(as: T.self)
+ }
+
+ /// Reads a slice from the memory assuming a type of T
+ /// - Parameters:
+ /// - index: index of the object to be read from the buffer
+ /// - count: count of bytes in memory
+ public func readSlice<T>(index: Int32,
+ count: Int32) -> [T] {
+ let _index = Int(index)
+ let _count = Int(count)
+ assert(_index + _count <= _storage.capacity, "Reading out of bounds is illegal")
+ let start = _storage.memory.advanced(by: _index).assumingMemoryBound(to: T.self)
+ let array = UnsafeBufferPointer(start: start, count: _count)
+ return Array(array)
+ }
+
+ /// Reads a string from the buffer and encodes it to a swift string
+ /// - Parameters:
+ /// - index: index of the string in the buffer
+ /// - count: length of the string
+ /// - type: Encoding of the string
+ public func readString(at index: Int32,
+ count: Int32,
+ type: String.Encoding = .utf8) -> String? {
+ let _index = Int(index)
+ let _count = Int(count)
+ assert(_index + _count <= _storage.capacity, "Reading out of bounds is illegal")
+ let start = _storage.memory.advanced(by: _index).assumingMemoryBound(to: UInt8.self)
+ let bufprt = UnsafeBufferPointer(start: start, count: _count)
+ return String(bytes: Array(bufprt), encoding: type)
+ }
+
+ /// Creates a new Flatbuffer object that's duplicated from the current one
+ /// - Parameter removeBytes: the amount of bytes to remove from the current Size
+ public func duplicate(removing removeBytes: Int = 0) -> ByteBuffer {
+ assert(removeBytes > 0, "Can NOT remove negative bytes")
+ assert(removeBytes < _storage.capacity, "Can NOT remove more bytes than the ones allocated")
+ return ByteBuffer(memory: _storage.memory, count: _storage.capacity, removing: _writerSize &- removeBytes)
+ }
+}
+
+extension ByteBuffer: CustomDebugStringConvertible {
+
+ public var debugDescription: String {
+ """
+ buffer located at: \(_storage.memory), with capacity of \(_storage.capacity)
+ { writerSize: \(_writerSize), readerSize: \(reader), writerIndex: \(writerIndex) }
+ """
+ }
+}
diff --git a/swift/Sources/FlatBuffers/Constants.swift b/swift/Sources/FlatBuffers/Constants.swift
new file mode 100644
index 0000000..2b55250
--- /dev/null
+++ b/swift/Sources/FlatBuffers/Constants.swift
@@ -0,0 +1,96 @@
+#if os(Linux)
+import CoreFoundation
+#else
+import Foundation
+#endif
+
+/// A boolean to see if the system is littleEndian
+let isLitteEndian = CFByteOrderGetCurrent() == Int(CFByteOrderLittleEndian.rawValue)
+/// Constant for the file id length
+let FileIdLength = 4
+/// Type aliases
+public typealias Byte = UInt8
+public typealias UOffset = UInt32
+public typealias SOffset = Int32
+public typealias VOffset = UInt16
+/// Maximum size for a buffer
+public let FlatBufferMaxSize = UInt32.max << ((MemoryLayout<SOffset>.size * 8 - 1) - 1)
+
+/// Protocol that confirms all the numbers
+///
+/// Scalar is used to confirm all the numbers that can be represented in a FlatBuffer. It's used to write/read from the buffer.
+public protocol Scalar: Equatable {
+ associatedtype NumericValue
+ var convertedEndian: NumericValue { get }
+}
+
+extension Scalar where Self: FixedWidthInteger {
+ /// Converts the value from BigEndian to LittleEndian
+ ///
+ /// Converts values to little endian on machines that work with BigEndian, however this is NOT TESTED yet.
+ public var convertedEndian: NumericValue {
+ return self as! Self.NumericValue
+ }
+}
+
+extension Double: Scalar {
+ public typealias NumericValue = UInt64
+
+ public var convertedEndian: UInt64 {
+ return self.bitPattern.littleEndian
+ }
+}
+
+extension Float32: Scalar {
+ public typealias NumericValue = UInt32
+
+ public var convertedEndian: UInt32 {
+ return self.bitPattern.littleEndian
+ }
+}
+
+extension Bool: Scalar {
+ public var convertedEndian: UInt8 {
+ return self == true ? 1 : 0
+ }
+
+ public typealias NumericValue = UInt8
+}
+
+extension Int: Scalar {
+ public typealias NumericValue = Int
+}
+
+extension Int8: Scalar {
+ public typealias NumericValue = Int8
+}
+
+extension Int16: Scalar {
+ public typealias NumericValue = Int16
+}
+
+extension Int32: Scalar {
+ public typealias NumericValue = Int32
+}
+
+extension Int64: Scalar {
+ public typealias NumericValue = Int64
+}
+
+extension UInt8: Scalar {
+ public typealias NumericValue = UInt8
+}
+
+extension UInt16: Scalar {
+ public typealias NumericValue = UInt16
+}
+
+extension UInt32: Scalar {
+ public typealias NumericValue = UInt32
+}
+
+extension UInt64: Scalar {
+ public typealias NumericValue = UInt64
+}
+
+public func FlatBuffersVersion_1_12_0() {}
diff --git a/swift/Sources/FlatBuffers/FlatBufferBuilder.swift b/swift/Sources/FlatBuffers/FlatBufferBuilder.swift
new file mode 100644
index 0000000..cfdb20c
--- /dev/null
+++ b/swift/Sources/FlatBuffers/FlatBufferBuilder.swift
@@ -0,0 +1,602 @@
+import Foundation
+
+public struct FlatBufferBuilder {
+
+ /// Storage for the Vtables used in the buffer are stored in here, so they would be written later in EndTable
+ @usableFromInline internal var _vtableStorage = VTableStorage()
+
+ /// Reference Vtables that were already written to the buffer
+ private var _vtables: [UOffset] = []
+ /// Flatbuffer data will be written into
+ private var _bb: ByteBuffer
+ /// A check if the buffer is being written into by a different table
+ private var isNested = false
+ /// Dictonary that stores a map of all the strings that were written to the buffer
+ private var stringOffsetMap: [String: Offset<String>] = [:]
+ /// A check to see if finish(::) was ever called to retreive data object
+ private var finished = false
+ /// A check to see if the buffer should serialize Default values
+ private var serializeDefaults: Bool
+
+ /// Current alignment for the buffer
+ var _minAlignment: Int = 0 {
+ didSet {
+ _bb.alignment = _minAlignment
+ }
+ }
+
+ /// Gives a read access to the buffer's size
+ public var size: UOffset { return _bb.size }
+ /// Data representation of the buffer
+ public var data: Data {
+ assert(finished, "Data shouldn't be called before finish()")
+ return Data(bytes: _bb.memory.advanced(by: _bb.writerIndex),
+ count: _bb.capacity &- _bb.writerIndex)
+ }
+ /// Get's the fully sized buffer stored in memory
+ public var fullSizedByteArray: [UInt8] {
+ let ptr = UnsafeBufferPointer(start: _bb.memory.assumingMemoryBound(to: UInt8.self),
+ count: _bb.capacity)
+ return Array(ptr)
+ }
+ /// Returns the written size of the buffer
+ public var sizedByteArray: [UInt8] {
+ assert(finished, "Data shouldn't be called before finish()")
+ let cp = _bb.capacity &- _bb.writerIndex
+ let start = _bb.memory.advanced(by: _bb.writerIndex)
+ .bindMemory(to: UInt8.self, capacity: cp)
+
+ let ptr = UnsafeBufferPointer(start: start, count: cp)
+ return Array(ptr)
+ }
+ /// Returns the buffer
+ public var buffer: ByteBuffer { return _bb }
+
+ /// Returns A sized Buffer from the readable bytes
+ public var sizedBuffer: ByteBuffer {
+ assert(finished, "Data shouldn't be called before finish()")
+ return ByteBuffer(memory: _bb.memory.advanced(by: _bb.reader), count: Int(_bb.size))
+ }
+
+ // MARK: - Init
+
+ /// initialize the buffer with a size
+ /// - Parameters:
+ /// - initialSize: Initial size for the buffer
+ /// - force: Allows default to be serialized into the buffer
+ public init(initialSize: Int32 = 1024, serializeDefaults force: Bool = false) {
+ assert(initialSize > 0, "Size should be greater than zero!")
+ guard isLitteEndian else {
+ fatalError("Reading/Writing a buffer in big endian machine is not supported on swift")
+ }
+ serializeDefaults = force
+ _bb = ByteBuffer(initialSize: Int(initialSize))
+ }
+
+ /// Clears the buffer and the builder from it's data
+ mutating public func clear() {
+ _minAlignment = 0
+ isNested = false
+ stringOffsetMap = [:]
+ _vtables = []
+ _vtableStorage.clear()
+ _bb.clear()
+ }
+
+ // MARK: - Create Tables
+
+ /// Checks if the required fields were serialized into the buffer
+ /// - Parameters:
+ /// - table: offset for the table
+ /// - fields: Array of all the important fields to be serialized
+ mutating public func require(table: Offset<UOffset>, fields: [Int32]) {
+ for field in fields {
+ let start = _bb.capacity &- Int(table.o)
+ let startTable = start &- Int(_bb.read(def: Int32.self, position: start))
+ let isOkay = _bb.read(def: VOffset.self, position: startTable &+ Int(field)) != 0
+ assert(isOkay, "Flatbuffers requires the following field")
+ }
+ }
+
+ /// Finished the buffer by adding the file id and then calling finish
+ /// - Parameters:
+ /// - offset: Offset of the table
+ /// - fileId: Takes the fileId
+ /// - prefix: if false it wont add the size of the buffer
+ mutating public func finish<T>(offset: Offset<T>, fileId: String, addPrefix prefix: Bool = false) {
+ let size = MemoryLayout<UOffset>.size
+ preAlign(len: size &+ (prefix ? size : 0) &+ FileIdLength, alignment: _minAlignment)
+ assert(fileId.count == FileIdLength, "Flatbuffers requires file id to be 4")
+ _bb.push(string: fileId, len: 4)
+ finish(offset: offset, addPrefix: prefix)
+ }
+
+ /// Finished the buffer by adding the file id, offset, and prefix to it.
+ /// - Parameters:
+ /// - offset: Offset of the table
+ /// - prefix: if false it wont add the size of the buffer
+ mutating public func finish<T>(offset: Offset<T>, addPrefix prefix: Bool = false) {
+ notNested()
+ let size = MemoryLayout<UOffset>.size
+ preAlign(len: size &+ (prefix ? size : 0), alignment: _minAlignment)
+ push(element: refer(to: offset.o))
+ if prefix { push(element: _bb.size) }
+ _vtableStorage.clear()
+ finished = true
+ }
+
+ /// starttable will let the builder know, that a new object is being serialized.
+ ///
+ /// The function will fatalerror if called while there is another object being serialized
+ /// - Parameter numOfFields: Number of elements to be written to the buffer
+ mutating public func startTable(with numOfFields: Int) -> UOffset {
+ notNested()
+ isNested = true
+ _vtableStorage.start(count: numOfFields)
+ return _bb.size
+ }
+
+ /// Endtable will let the builder know that the object that's written to it is completed
+ ///
+ /// This would be called after all the elements are serialized, it will add the vtable into the buffer.
+ /// it will fatalError in case the object is called without starttable, or the object has exceeded the limit of
+ /// 2GB,
+ /// - Parameter startOffset:Start point of the object written
+ /// - returns: The root of the table
+ mutating public func endTable(at startOffset: UOffset) -> UOffset {
+ assert(isNested, "Calling endtable without calling starttable")
+ let sizeofVoffset = MemoryLayout<VOffset>.size
+ let vTableOffset = push(element: SOffset(0))
+
+ let tableObjectSize = vTableOffset &- startOffset
+ assert(tableObjectSize < 0x10000, "Buffer can't grow beyond 2 Gigabytes")
+ let _max = Int(_vtableStorage.maxOffset) &+ sizeofVoffset
+
+ _bb.fill(padding: _max)
+ _bb.write(value: VOffset(tableObjectSize), index: _bb.writerIndex &+ sizeofVoffset, direct: true)
+ _bb.write(value: VOffset(_max), index: _bb.writerIndex, direct: true)
+
+ var itr = 0
+ while itr < _vtableStorage.writtenIndex {
+ let loaded = _vtableStorage.load(at: itr)
+ itr = itr &+ _vtableStorage.size
+ guard loaded.offset != 0 else { continue }
+ let _index = (_bb.writerIndex &+ Int(loaded.position))
+ _bb.write(value: VOffset(vTableOffset &- loaded.offset), index: _index, direct: true)
+ }
+
+ _vtableStorage.clear()
+ let vt_use = _bb.size
+
+ var isAlreadyAdded: Int?
+
+ let vt2 = _bb.memory.advanced(by: _bb.writerIndex)
+ let len2 = vt2.load(fromByteOffset: 0, as: Int16.self)
+
+ for table in _vtables {
+ let position = _bb.capacity &- Int(table)
+ let vt1 = _bb.memory.advanced(by: position)
+ let len1 = _bb.read(def: Int16.self, position: position)
+ if (len2 != len1 || 0 != memcmp(vt1, vt2, Int(len2))) { continue }
+
+ isAlreadyAdded = Int(table)
+ break
+ }
+
+ if let offset = isAlreadyAdded {
+ let vTableOff = Int(vTableOffset)
+ let space = _bb.capacity &- vTableOff
+ _bb.write(value: Int32(offset &- vTableOff), index: space, direct: true)
+ _bb.pop(_bb.capacity &- space)
+ } else {
+ _bb.write(value: Int32(vt_use &- vTableOffset), index: Int(vTableOffset))
+ _vtables.append(_bb.size)
+ }
+ isNested = false
+ return vTableOffset
+ }
+
+ // MARK: - Builds Buffer
+
+ /// asserts to see if the object is not nested
+ @usableFromInline mutating internal func notNested() {
+ assert(!isNested, "Object serialization must not be nested")
+ }
+
+ /// Changes the minimuim alignment of the buffer
+ /// - Parameter size: size of the current alignment
+ @usableFromInline mutating internal func minAlignment(size: Int) {
+ if size > _minAlignment {
+ _minAlignment = size
+ }
+ }
+
+ /// Gets the padding for the current element
+ /// - Parameters:
+ /// - bufSize: Current size of the buffer + the offset of the object to be written
+ /// - elementSize: Element size
+ @usableFromInline mutating internal func padding(bufSize: UInt32, elementSize: UInt32) -> UInt32 {
+ ((~bufSize) &+ 1) & (elementSize - 1)
+ }
+
+ /// Prealigns the buffer before writting a new object into the buffer
+ /// - Parameters:
+ /// - len:Length of the object
+ /// - alignment: Alignment type
+ @usableFromInline mutating internal func preAlign(len: Int, alignment: Int) {
+ minAlignment(size: alignment)
+ _bb.fill(padding: Int(padding(bufSize: _bb.size &+ UOffset(len), elementSize: UOffset(alignment))))
+ }
+
+ /// Prealigns the buffer before writting a new object into the buffer
+ /// - Parameters:
+ /// - len: Length of the object
+ /// - type: Type of the object to be written
+ @usableFromInline mutating internal func preAlign<T: Scalar>(len: Int, type: T.Type) {
+ preAlign(len: len, alignment: MemoryLayout<T>.size)
+ }
+
+ /// Refers to an object that's written in the buffer
+ /// - Parameter off: the objects index value
+ @usableFromInline mutating internal func refer(to off: UOffset) -> UOffset {
+ let size = MemoryLayout<UOffset>.size
+ preAlign(len: size, alignment: size)
+ return _bb.size &- off &+ UInt32(size)
+ }
+
+ /// Tracks the elements written into the buffer
+ /// - Parameters:
+ /// - offset: The offset of the element witten
+ /// - position: The position of the element
+ @usableFromInline mutating internal func track(offset: UOffset, at position: VOffset) {
+ _vtableStorage.add(loc: FieldLoc(offset: offset, position: position))
+ }
+
+ // MARK: - Vectors
+
+ /// Starts a vector of length and Element size
+ mutating public func startVector(_ len: Int, elementSize: Int) {
+ notNested()
+ isNested = true
+ preAlign(len: len &* elementSize, type: UOffset.self)
+ preAlign(len: len &* elementSize, alignment: elementSize)
+ }
+
+ /// Ends the vector of at length
+ ///
+ /// The current function will fatalError if startVector is called before serializing the vector
+ /// - Parameter len: Length of the buffer
+ mutating public func endVector(len: Int) -> UOffset {
+ assert(isNested, "Calling endVector without calling startVector")
+ isNested = false
+ return push(element: Int32(len))
+ }
+
+ /// Creates a vector of type Scalar in the buffer
+ /// - Parameter elements: elements to be written into the buffer
+ /// - returns: Offset of the vector
+ mutating public func createVector<T: Scalar>(_ elements: [T]) -> Offset<UOffset> {
+ return createVector(elements, size: elements.count)
+ }
+
+ /// Creates a vector of type Scalar in the buffer
+ /// - Parameter elements: Elements to be written into the buffer
+ /// - Parameter size: Count of elements
+ /// - returns: Offset of the vector
+ mutating public func createVector<T: Scalar>(_ elements: [T], size: Int) -> Offset<UOffset> {
+ let size = size
+ startVector(size, elementSize: MemoryLayout<T>.size)
+ _bb.push(elements: elements)
+ return Offset(offset: endVector(len: size))
+ }
+
+ /// Creates a vector of type Enums in the buffer
+ /// - Parameter elements: elements to be written into the buffer
+ /// - returns: Offset of the vector
+ mutating public func createVector<T: Enum>(_ elements: [T]) -> Offset<UOffset> {
+ return createVector(elements, size: elements.count)
+ }
+
+ /// Creates a vector of type Enums in the buffer
+ /// - Parameter elements: Elements to be written into the buffer
+ /// - Parameter size: Count of elements
+ /// - returns: Offset of the vector
+ mutating public func createVector<T: Enum>(_ elements: [T], size: Int) -> Offset<UOffset> {
+ let size = size
+ startVector(size, elementSize: T.byteSize)
+ for e in elements.reversed() {
+ _bb.push(value: e.value, len: T.byteSize)
+ }
+ return Offset(offset: endVector(len: size))
+ }
+
+ /// Creates a vector of type Offsets in the buffer
+ /// - Parameter offsets:Array of offsets of type T
+ /// - returns: Offset of the vector
+ mutating public func createVector<T>(ofOffsets offsets: [Offset<T>]) -> Offset<UOffset> {
+ createVector(ofOffsets: offsets, len: offsets.count)
+ }
+
+ /// Creates a vector of type Offsets in the buffer
+ /// - Parameter elements: Array of offsets of type T
+ /// - Parameter size: Count of elements
+ /// - returns: Offset of the vector
+ mutating public func createVector<T>(ofOffsets offsets: [Offset<T>], len: Int) -> Offset<UOffset> {
+ startVector(len, elementSize: MemoryLayout<Offset<T>>.size)
+ for o in offsets.reversed() {
+ push(element: o)
+ }
+ return Offset(offset: endVector(len: len))
+ }
+
+ /// Creates a vector of Strings
+ /// - Parameter str: a vector of strings that will be written into the buffer
+ /// - returns: Offset of the vector
+ mutating public func createVector(ofStrings str: [String]) -> Offset<UOffset> {
+ var offsets: [Offset<String>] = []
+ for s in str {
+ offsets.append(create(string: s))
+ }
+ return createVector(ofOffsets: offsets)
+ }
+
+ /// Creates a vector of Flatbuffer structs.
+ ///
+ /// The function takes a Type to know what size it is, and alignment
+ /// - Parameters:
+ /// - structs: An array of UnsafeMutableRawPointer
+ /// - type: Type of the struct being written
+ /// - returns: Offset of the vector
+ @available(*, deprecated, message: "0.9.0 will be removing the following method. Regenerate the code")
+ mutating public func createVector<T: Readable>(structs: [UnsafeMutableRawPointer],
+ type: T.Type) -> Offset<UOffset> {
+ startVector(structs.count &* T.size, elementSize: T.alignment)
+ for i in structs.reversed() {
+ create(struct: i, type: T.self)
+ }
+ return Offset(offset: endVector(len: structs.count))
+ }
+
+ /// Starts a vector of struct that considers the size and alignment of the struct
+ /// - Parameters:
+ /// - count: number of elements to be written
+ /// - size: size of struct
+ /// - alignment: alignment of the struct
+ mutating public func startVectorOfStructs(count: Int, size: Int, alignment: Int) {
+ startVector(count &* size, elementSize: alignment)
+ }
+
+ /// Ends the vector of structs and writtens the current offset
+ /// - Parameter count: number of written elements
+ /// - Returns: Offset of type UOffset
+ mutating public func endVectorOfStructs(count: Int) -> Offset<UOffset> {
+ return Offset<UOffset>(offset: endVector(len: count))
+ }
+
+ // MARK: - Inserting Structs
+
+ /// Writes a Flatbuffer struct into the buffer
+ /// - Parameters:
+ /// - s: Flatbuffer struct
+ /// - type: Type of the element to be serialized
+ /// - returns: Offset of the Object
+ @available(*, deprecated, message: "0.9.0 will be removing the following method. Regenerate the code")
+ @discardableResult
+ mutating public func create<T: Readable>(struct s: UnsafeMutableRawPointer,
+ type: T.Type) -> Offset<UOffset> {
+ let size = T.size
+ preAlign(len: size, alignment: T.alignment)
+ _bb.push(struct: s, size: size)
+ return Offset(offset: _bb.size)
+ }
+
+ /// prepares the ByteBuffer to receive a struct of size and alignment
+ /// - Parameters:
+ /// - size: size of written struct
+ /// - alignment: alignment of written struct
+ mutating public func createStructOf(size: Int, alignment: Int) {
+ preAlign(len: size, alignment: alignment)
+ _bb.prepareBufferToReceiveStruct(of: size)
+ }
+
+ /// Adds scalars front to back instead of the default behavior of the normal add
+ /// - Parameters:
+ /// - v: element of type Scalar
+ /// - postion: position relative to the `writerIndex`
+ mutating public func reverseAdd<T: Scalar>(v: T, postion: Int) {
+ _bb.reversePush(value: v,
+ position: postion,
+ len: MemoryLayout<T>.size)
+ }
+
+ /// Ends the struct and returns the current buffer size
+ /// - Returns: Offset of type UOffset
+ @discardableResult
+ public func endStruct() -> Offset<UOffset> {
+ return Offset(offset: _bb.size)
+ }
+
+ /// Adds the offset of a struct into the vTable
+ ///
+ /// The function fatalErrors if we pass an offset that is out of range
+ /// - Parameter o: offset
+ mutating public func add(structOffset o: VOffset) {
+ _vtableStorage.add(loc: FieldLoc(offset: _bb.size, position: VOffset(o)))
+ }
+
+ // MARK: - Inserting Strings
+
+ /// Insets a string into the buffer using UTF8
+ /// - Parameter str: String to be serialized
+ /// - returns: The strings offset in the buffer
+ mutating public func create(string str: String?) -> Offset<String> {
+ guard let str = str else { return Offset() }
+ let len = str.utf8.count
+ notNested()
+ preAlign(len: len &+ 1, type: UOffset.self)
+ _bb.fill(padding: 1)
+ _bb.push(string: str, len: len)
+ push(element: UOffset(len))
+ return Offset(offset: _bb.size)
+ }
+
+ /// Inserts a shared string to the buffer
+ ///
+ /// The function checks the stringOffsetmap if it's seen a similar string before
+ /// - Parameter str: String to be serialized
+ /// - returns: The strings offset in the buffer
+ mutating public func createShared(string str: String?) -> Offset<String> {
+ guard let str = str else { return Offset() }
+ if let offset = stringOffsetMap[str] {
+ return offset
+ }
+ let offset = create(string: str)
+ stringOffsetMap[str] = offset
+ return offset
+ }
+
+ // MARK: - Inseting offsets
+
+ /// Adds the offset of an object into the buffer
+ /// - Parameters:
+ /// - offset: Offset of another object to be written
+ /// - position: The predefined position of the object
+ mutating public func add<T>(offset: Offset<T>, at position: VOffset) {
+ if offset.isEmpty { return }
+ add(element: refer(to: offset.o), def: 0, at: position)
+ }
+
+ /// Pushes a value of type offset into the buffer
+ /// - Parameter o: Offset
+ /// - returns: Position of the offset
+ @discardableResult
+ mutating public func push<T>(element o: Offset<T>) -> UOffset {
+ push(element: refer(to: o.o))
+ }
+
+ // MARK: - Inserting Scalars to Buffer
+
+ /// Adds a value into the buffer of type Scalar
+ ///
+ /// - Parameters:
+ /// - element: Element to insert
+ /// - def: Default value for that element
+ /// - position: The predefined position of the element
+ mutating public func add<T: Scalar>(element: T, def: T, at position: VOffset) {
+ if (element == def && !serializeDefaults) { return }
+ track(offset: push(element: element), at: position)
+ }
+
+ /// Adds a value into the buffer of type optional Scalar
+ /// - Parameters:
+ /// - element: Optional element of type scalar
+ /// - position: The predefined position of the element
+ mutating public func add<T: Scalar>(element: T?, at position: VOffset) {
+ guard let element = element else { return }
+ track(offset: push(element: element), at: position)
+ }
+
+ /// Pushes the values into the buffer
+ /// - Parameter element: Element to insert
+ /// - returns: Postion of the Element
+ @discardableResult
+ mutating public func push<T: Scalar>(element: T) -> UOffset {
+ let size = MemoryLayout<T>.size
+ preAlign(len: size,
+ alignment: size)
+ _bb.push(value: element, len: size)
+ return _bb.size
+ }
+
+}
+
+extension FlatBufferBuilder: CustomDebugStringConvertible {
+
+ public var debugDescription: String {
+ """
+ buffer debug:
+ \(_bb)
+ builder debug:
+ { finished: \(finished), serializeDefaults: \(serializeDefaults), isNested: \(isNested) }
+ """
+ }
+
+ /// VTableStorage is a class to contain the VTable buffer that would be serialized into buffer
+ @usableFromInline internal class VTableStorage {
+ /// Memory check since deallocating each time we want to clear would be expensive
+ /// and memory leaks would happen if we dont deallocate the first allocated memory.
+ /// memory is promised to be available before adding `FieldLoc`
+ private var memoryInUse = false
+ /// Size of FieldLoc in memory
+ let size = MemoryLayout<FieldLoc>.stride
+ /// Memeory buffer
+ var memory: UnsafeMutableRawBufferPointer!
+ /// Capacity of the current buffer
+ var capacity: Int = 0
+ /// Maximuim offset written to the class
+ var maxOffset: VOffset = 0
+ /// number of fields written into the buffer
+ var numOfFields: Int = 0
+ /// Last written Index
+ var writtenIndex: Int = 0
+ /// the amount of added elements into the buffer
+ var addedElements: Int { return capacity - (numOfFields &* size) }
+
+ /// Creates the memory to store the buffer in
+ init() {
+ memory = UnsafeMutableRawBufferPointer.allocate(byteCount: 0, alignment: 0)
+ }
+
+ deinit {
+ memory.deallocate()
+ }
+
+ /// Builds a buffer with byte count of fieldloc.size * count of field numbers
+ /// - Parameter count: number of fields to be written
+ func start(count: Int) {
+ assert(count >= 0, "number of fields should NOT be negative")
+ let capacity = count &* size
+ ensure(space: capacity)
+ }
+
+ /// Adds a FieldLoc into the buffer, which would track how many have been written,
+ /// and max offset
+ /// - Parameter loc: Location of encoded element
+ func add(loc: FieldLoc) {
+ memory.baseAddress?.advanced(by: writtenIndex).storeBytes(of: loc, as: FieldLoc.self)
+ writtenIndex = writtenIndex &+ size
+ numOfFields = numOfFields &+ 1
+ maxOffset = max(loc.position, maxOffset)
+ }
+
+ /// Clears the data stored related to the encoded buffer
+ func clear() {
+ maxOffset = 0
+ numOfFields = 0
+ writtenIndex = 0
+ }
+
+ /// Ensure that the buffer has enough space instead of recreating the buffer each time.
+ /// - Parameter space: space required for the new vtable
+ func ensure(space: Int) {
+ guard space &+ writtenIndex > capacity else { return }
+ memory.deallocate()
+ memory = UnsafeMutableRawBufferPointer.allocate(byteCount: space, alignment: size)
+ capacity = space
+ }
+
+ /// Loads an object of type `FieldLoc` from buffer memory
+ /// - Parameter index: index of element
+ /// - Returns: a FieldLoc at index
+ func load(at index: Int) -> FieldLoc {
+ return memory.load(fromByteOffset: index, as: FieldLoc.self)
+ }
+
+ }
+
+ internal struct FieldLoc {
+ var offset: UOffset
+ var position: VOffset
+ }
+
+}
diff --git a/swift/Sources/FlatBuffers/FlatBufferObject.swift b/swift/Sources/FlatBuffers/FlatBufferObject.swift
new file mode 100644
index 0000000..52ca396
--- /dev/null
+++ b/swift/Sources/FlatBuffers/FlatBufferObject.swift
@@ -0,0 +1,28 @@
+import Foundation
+
+/// FlatbufferObject structures all the Flatbuffers objects
+public protocol FlatBufferObject {
+ var __buffer: ByteBuffer! { get }
+ init(_ bb: ByteBuffer, o: Int32)
+}
+
+public protocol ObjectAPI {
+ associatedtype T
+ static func pack(_ builder: inout FlatBufferBuilder, obj: inout T) -> Offset<UOffset>
+ mutating func unpack() -> T
+}
+
+/// Readable is structures all the Flatbuffers structs
+///
+/// Readable is a procotol that each Flatbuffer struct should confirm to since
+/// FlatBufferBuilder would require a Type to both create(struct:) and createVector(structs:) functions
+public protocol Readable: FlatBufferObject {
+ static var size: Int { get }
+ static var alignment: Int { get }
+}
+
+public protocol Enum {
+ associatedtype T: Scalar
+ static var byteSize: Int { get }
+ var value: T { get }
+}
diff --git a/swift/Sources/FlatBuffers/FlatBuffersUtils.swift b/swift/Sources/FlatBuffers/FlatBuffersUtils.swift
new file mode 100644
index 0000000..6838f86
--- /dev/null
+++ b/swift/Sources/FlatBuffers/FlatBuffersUtils.swift
@@ -0,0 +1,16 @@
+import Foundation
+
+public final class FlatBuffersUtils {
+
+ /// Gets the size of the prefix
+ /// - Parameter bb: Flatbuffer object
+ public static func getSizePrefix(bb: ByteBuffer) -> Int32 {
+ return bb.read(def: Int32.self, position: bb.reader)
+ }
+
+ /// Removes the prefix by duplicating the Flatbuffer
+ /// - Parameter bb: Flatbuffer object
+ public static func removeSizePrefix(bb: ByteBuffer) -> ByteBuffer {
+ return bb.duplicate(removing: MemoryLayout<Int32>.size)
+ }
+}
diff --git a/swift/Sources/FlatBuffers/Int+extension.swift b/swift/Sources/FlatBuffers/Int+extension.swift
new file mode 100644
index 0000000..e52bdab
--- /dev/null
+++ b/swift/Sources/FlatBuffers/Int+extension.swift
@@ -0,0 +1,31 @@
+import Foundation
+
+extension Int {
+
+ /// Moves the current int into the nearest power of two
+ ///
+ /// This is used since the UnsafeMutableRawPointer will face issues when writing/reading
+ /// if the buffer alignment exceeds that actual size of the buffer
+ var convertToPowerofTwo: Int {
+ guard self > 0 else { return 1 }
+ var n = UOffset(self)
+
+ #if arch(arm) || arch(i386)
+ let max = UInt32(Int.max)
+ #else
+ let max = UInt32.max
+ #endif
+
+ n -= 1
+ n |= n >> 1
+ n |= n >> 2
+ n |= n >> 4
+ n |= n >> 8
+ n |= n >> 16
+ if n != max {
+ n += 1
+ }
+
+ return Int(n)
+ }
+}
diff --git a/swift/Sources/FlatBuffers/Message.swift b/swift/Sources/FlatBuffers/Message.swift
new file mode 100644
index 0000000..590d3d7
--- /dev/null
+++ b/swift/Sources/FlatBuffers/Message.swift
@@ -0,0 +1,41 @@
+public protocol FlatBufferGRPCMessage {
+
+ /// Raw pointer which would be pointing to the beginning of the readable bytes
+ var rawPointer: UnsafeMutableRawPointer { get }
+
+ /// Size of readable bytes in the buffer
+ var size: Int { get }
+
+ init(byteBuffer: ByteBuffer)
+}
+
+/// Message is a wrapper around Buffers to to able to send Flatbuffers `Buffers` through the
+/// GRPC library
+public final class Message<T: FlatBufferObject>: FlatBufferGRPCMessage {
+ internal var buffer: ByteBuffer
+
+ /// Returns the an object of type T that would be read from the buffer
+ public var object: T {
+ T.init(buffer, o: Int32(buffer.read(def: UOffset.self, position: buffer.reader)) + Int32(buffer.reader))
+ }
+
+ public var rawPointer: UnsafeMutableRawPointer { return buffer.memory.advanced(by: buffer.reader) }
+
+ public var size: Int { return Int(buffer.size) }
+
+ /// Initializes the message with the type Flatbuffer.Bytebuffer that is transmitted over
+ /// GRPC
+ /// - Parameter byteBuffer: Flatbuffer ByteBuffer object
+ public init(byteBuffer: ByteBuffer) {
+ buffer = byteBuffer
+ }
+
+ /// Initializes the message by copying the buffer to the message to be sent.
+ /// from the builder
+ /// - Parameter builder: FlatbufferBuilder that has the bytes created in
+ /// - Note: Use `builder.finish(offset)` before passing the builder without prefixing anything to it
+ public init(builder: inout FlatBufferBuilder) {
+ buffer = builder.sizedBuffer
+ builder.clear()
+ }
+}
diff --git a/swift/Sources/FlatBuffers/Mutable.swift b/swift/Sources/FlatBuffers/Mutable.swift
new file mode 100644
index 0000000..90c1d8b
--- /dev/null
+++ b/swift/Sources/FlatBuffers/Mutable.swift
@@ -0,0 +1,68 @@
+import Foundation
+
+/// Mutable is a protocol that allows us to mutate Scalar values within the buffer
+public protocol Mutable {
+ /// makes Flatbuffer accessed within the Protocol
+ var bb: ByteBuffer { get }
+ /// makes position of the table/struct accessed within the Protocol
+ var postion: Int32 { get }
+}
+
+extension Mutable {
+
+ /// Mutates the memory in the buffer, this is only called from the access function of table and structs
+ /// - Parameters:
+ /// - value: New value to be inserted to the buffer
+ /// - index: index of the Element
+ func mutate<T: Scalar>(value: T, o: Int32) -> Bool {
+ guard o != 0 else { return false }
+ bb.write(value: value, index: Int(o), direct: true)
+ return true
+ }
+}
+
+extension Mutable where Self == Table {
+
+ /// Mutates a value by calling mutate with respect to the position in the table
+ /// - Parameters:
+ /// - value: New value to be inserted to the buffer
+ /// - index: index of the Element
+ public func mutate<T: Scalar>(_ value: T, index: Int32) -> Bool {
+ guard index != 0 else { return false }
+ return mutate(value: value, o: index + postion)
+ }
+
+ /// Directly mutates the element by calling mutate
+ ///
+ /// Mutates the Element at index ignoring the current position by calling mutate
+ /// - Parameters:
+ /// - value: New value to be inserted to the buffer
+ /// - index: index of the Element
+ public func directMutate<T: Scalar>(_ value: T, index: Int32) -> Bool {
+ return mutate(value: value, o: index)
+ }
+}
+
+extension Mutable where Self == Struct {
+
+ /// Mutates a value by calling mutate with respect to the position in the struct
+ /// - Parameters:
+ /// - value: New value to be inserted to the buffer
+ /// - index: index of the Element
+ public func mutate<T: Scalar>(_ value: T, index: Int32) -> Bool {
+ return mutate(value: value, o: index + postion)
+ }
+
+ /// Directly mutates the element by calling mutate
+ ///
+ /// Mutates the Element at index ignoring the current position by calling mutate
+ /// - Parameters:
+ /// - value: New value to be inserted to the buffer
+ /// - index: index of the Element
+ public func directMutate<T: Scalar>(_ value: T, index: Int32) -> Bool {
+ return mutate(value: value, o: index)
+ }
+}
+
+extension Struct: Mutable {}
+extension Table: Mutable {}
diff --git a/swift/Sources/FlatBuffers/NativeTable.swift b/swift/Sources/FlatBuffers/NativeTable.swift
new file mode 100644
index 0000000..057b376
--- /dev/null
+++ b/swift/Sources/FlatBuffers/NativeTable.swift
@@ -0,0 +1,29 @@
+import Foundation
+
+public protocol NativeTable {}
+
+extension NativeTable {
+
+ /// Serialize is a helper function that serailizes the data from the Object API to a bytebuffer directly th
+ /// - Parameter type: Type of the Flatbuffer object
+ /// - Returns: returns the encoded sized ByteBuffer
+ public func serialize<T: ObjectAPI>(type: T.Type) -> ByteBuffer where T.T == Self {
+ var builder = FlatBufferBuilder(initialSize: 1024)
+ return serialize(builder: &builder, type: type.self)
+ }
+
+ /// Serialize is a helper function that serailizes the data from the Object API to a bytebuffer directly.
+ ///
+ /// - Parameters:
+ /// - builder: A FlatBufferBuilder
+ /// - type: Type of the Flatbuffer object
+ /// - Returns: returns the encoded sized ByteBuffer
+ /// - Note: The `serialize(builder:type)` can be considered as a function that allows you to create smaller builder instead of the default `1024`.
+ /// It can be considered less expensive in terms of memory allocation
+ public func serialize<T: ObjectAPI>(builder: inout FlatBufferBuilder, type: T.Type) -> ByteBuffer where T.T == Self {
+ var s = self
+ let root = type.pack(&builder, obj: &s)
+ builder.finish(offset: root)
+ return builder.sizedBuffer
+ }
+}
diff --git a/swift/Sources/FlatBuffers/Offset.swift b/swift/Sources/FlatBuffers/Offset.swift
new file mode 100644
index 0000000..cdb0227
--- /dev/null
+++ b/swift/Sources/FlatBuffers/Offset.swift
@@ -0,0 +1,12 @@
+import Foundation
+
+/// Offset object for all the Objects that are written into the buffer
+public struct Offset<T> {
+ /// Offset of the object in the buffer
+ public var o: UOffset
+ /// Returns false if the offset is equal to zero
+ public var isEmpty: Bool { return o == 0 }
+
+ public init(offset: UOffset) { o = offset }
+ public init() { o = 0 }
+}
diff --git a/swift/Sources/FlatBuffers/Struct.swift b/swift/Sources/FlatBuffers/Struct.swift
new file mode 100644
index 0000000..88e3a41
--- /dev/null
+++ b/swift/Sources/FlatBuffers/Struct.swift
@@ -0,0 +1,16 @@
+import Foundation
+
+public struct Struct {
+ public private(set) var bb: ByteBuffer
+ public private(set) var postion: Int32
+
+ public init(bb: ByteBuffer, position: Int32 = 0) {
+ self.bb = bb
+ self.postion = position
+ }
+
+ public func readBuffer<T: Scalar>(of type: T.Type, at o: Int32) -> T {
+ let r = bb.read(def: T.self, position: Int(o + postion))
+ return r
+ }
+}
diff --git a/swift/Sources/FlatBuffers/Table.swift b/swift/Sources/FlatBuffers/Table.swift
new file mode 100644
index 0000000..0f783bf
--- /dev/null
+++ b/swift/Sources/FlatBuffers/Table.swift
@@ -0,0 +1,144 @@
+import Foundation
+
+public struct Table {
+ public private(set) var bb: ByteBuffer
+ public private(set) var postion: Int32
+
+ public init(bb: ByteBuffer, position: Int32 = 0) {
+ guard isLitteEndian else {
+ fatalError("Reading/Writing a buffer in big endian machine is not supported on swift")
+ }
+ self.bb = bb
+ self.postion = position
+ }
+
+ public func offset(_ o: Int32) -> Int32 {
+ let vtable = postion - bb.read(def: Int32.self, position: Int(postion))
+ return o < bb.read(def: VOffset.self, position: Int(vtable)) ? Int32(bb.read(def: Int16.self, position: Int(vtable + o))) : 0
+ }
+
+ public func indirect(_ o: Int32) -> Int32 { return o + bb.read(def: Int32.self, position: Int(o)) }
+
+ /// String reads from the buffer with respect to position of the current table.
+ /// - Parameter offset: Offset of the string
+ public func string(at offset: Int32) -> String? {
+ return directString(at: offset + postion)
+ }
+
+ /// Direct string reads from the buffer disregarding the position of the table.
+ /// It would be preferable to use string unless the current position of the table is not needed
+ /// - Parameter offset: Offset of the string
+ public func directString(at offset: Int32) -> String? {
+ var offset = offset
+ offset += bb.read(def: Int32.self, position: Int(offset))
+ let count = bb.read(def: Int32.self, position: Int(offset))
+ let position = offset + Int32(MemoryLayout<Int32>.size)
+ return bb.readString(at: position, count: count)
+ }
+
+ /// Reads from the buffer with respect to the position in the table.
+ /// - Parameters:
+ /// - type: Type of Scalar that needs to be read from the buffer
+ /// - o: Offset of the Element
+ public func readBuffer<T: Scalar>(of type: T.Type, at o: Int32) -> T {
+ return directRead(of: T.self, offset: o + postion)
+ }
+
+ /// Reads from the buffer disregarding the position of the table.
+ /// It would be used when reading from an
+ /// ```
+ /// let offset = __t.offset(10)
+ /// //Only used when the we already know what is the
+ /// // position in the table since __t.vector(at:)
+ /// // returns the index with respect to the position
+ /// __t.directRead(of: Byte.self,
+ /// offset: __t.vector(at: offset) + index * 1)
+ /// ```
+ /// - Parameters:
+ /// - type: Type of Scalar that needs to be read from the buffer
+ /// - o: Offset of the Element
+ public func directRead<T: Scalar>(of type: T.Type, offset o: Int32) -> T {
+ let r = bb.read(def: T.self, position: Int(o))
+ return r
+ }
+
+ public func union<T: FlatBufferObject>(_ o: Int32) -> T {
+ let o = o + postion
+ return directUnion(o)
+ }
+
+ public func directUnion<T: FlatBufferObject>(_ o: Int32) -> T {
+ return T.init(bb, o: o + bb.read(def: Int32.self, position: Int(o)))
+ }
+
+ public func getVector<T>(at off: Int32) -> [T]? {
+ let o = offset(off)
+ guard o != 0 else { return nil }
+ return bb.readSlice(index: vector(at: o), count: vector(count: o))
+ }
+
+ /// Vector count gets the count of Elements within the array
+ /// - Parameter o: start offset of the vector
+ /// - returns: Count of elements
+ public func vector(count o: Int32) -> Int32 {
+ var o = o
+ o += postion
+ o += bb.read(def: Int32.self, position: Int(o))
+ return bb.read(def: Int32.self, position: Int(o))
+ }
+
+ /// Vector start index in the buffer
+ /// - Parameter o:start offset of the vector
+ /// - returns: the start index of the vector
+ public func vector(at o: Int32) -> Int32 {
+ var o = o
+ o += postion
+ return o + bb.read(def: Int32.self, position: Int(o)) + 4
+ }
+}
+
+extension Table {
+
+ static public func indirect(_ o: Int32, _ fbb: ByteBuffer) -> Int32 { return o + fbb.read(def: Int32.self, position: Int(o)) }
+
+ static public func offset(_ o: Int32, vOffset: Int32, fbb: ByteBuffer) -> Int32 {
+ let vTable = Int32(fbb.capacity) - o
+ return vTable + Int32(fbb.read(def: Int16.self, position: Int(vTable + vOffset - fbb.read(def: Int32.self, position: Int(vTable)))))
+ }
+
+ static public func compare(_ off1: Int32, _ off2: Int32, fbb: ByteBuffer) -> Int32 {
+ let memorySize = Int32(MemoryLayout<Int32>.size)
+ let _off1 = off1 + fbb.read(def: Int32.self, position: Int(off1))
+ let _off2 = off2 + fbb.read(def: Int32.self, position: Int(off2))
+ let len1 = fbb.read(def: Int32.self, position: Int(_off1))
+ let len2 = fbb.read(def: Int32.self, position: Int(_off2))
+ let startPos1 = _off1 + memorySize
+ let startPos2 = _off2 + memorySize
+ let minValue = min(len1, len2)
+ for i in 0...minValue {
+ let b1 = fbb.read(def: Int8.self, position: Int(i + startPos1))
+ let b2 = fbb.read(def: Int8.self, position: Int(i + startPos2))
+ if b1 != b2 {
+ return Int32(b2 - b1)
+ }
+ }
+ return len1 - len2
+ }
+
+ static public func compare(_ off1: Int32, _ key: [Byte], fbb: ByteBuffer) -> Int32 {
+ let memorySize = Int32(MemoryLayout<Int32>.size)
+ let _off1 = off1 + fbb.read(def: Int32.self, position: Int(off1))
+ let len1 = fbb.read(def: Int32.self, position: Int(_off1))
+ let len2 = Int32(key.count)
+ let startPos1 = _off1 + memorySize
+ let minValue = min(len1, len2)
+ for i in 0..<minValue {
+ let b = fbb.read(def: Int8.self, position: Int(i + startPos1))
+ let byte = key[Int(i)]
+ if b != byte {
+ return Int32(b - Int8(byte))
+ }
+ }
+ return len1 - len2
+ }
+}