diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 7d2cabf73..30e0cecdf 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -42,7 +42,7 @@ jobs: chmod +x flatc ./flatc --version - name: upload build artifacts - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@v4 with: name: Linux flatc binary ${{ matrix.cxx }} path: flatc @@ -170,7 +170,7 @@ jobs: - name: test run: Release\flattests.exe - name: upload build artifacts - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@v4 with: name: Windows flatc binary path: Release\flatc.exe @@ -191,7 +191,7 @@ jobs: build-dotnet-windows: name: Build .NET Windows - runs-on: windows-2022 + runs-on: windows-2022-64core strategy: matrix: configuration: [ @@ -246,7 +246,7 @@ jobs: chmod +x Release/flatc Release/flatc --version - name: upload build artifacts - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@v4 with: name: Mac flatc binary Intel path: Release/flatc @@ -289,7 +289,7 @@ jobs: chmod +x Release/flatc Release/flatc --version - name: upload build artifacts - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@v4 with: name: Mac flatc binary Universal path: Release/flatc @@ -314,7 +314,7 @@ jobs: steps: - uses: actions/checkout@v6 - name: set up Java - uses: actions/setup-java@v5 + uses: actions/setup-java@v4 with: distribution: temurin java-version: 17 @@ -373,7 +373,7 @@ jobs: - name: Run benchmarks run: ./flatbenchmark --benchmark_repetitions=5 --benchmark_display_aggregates_only=true --benchmark_out_format=console --benchmark_out=benchmarks/results_${{matrix.cxx}} - name: Upload benchmarks results - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@v4 with: name: Linux flatbenchmark results ${{matrix.cxx}} path: benchmarks/results_${{matrix.cxx}} @@ -394,7 +394,7 @@ jobs: - name: Checkout uses: actions/checkout@v6 - name: set up Java - uses: actions/setup-java@v5 + uses: actions/setup-java@v4 with: distribution: temurin java-version: 17 @@ -417,7 +417,7 @@ jobs: - name: Checkout uses: actions/checkout@v6 - name: set up Java - uses: actions/setup-java@v5 + uses: actions/setup-java@v4 with: distribution: temurin java-version: 17 @@ -446,7 +446,7 @@ jobs: build-rust-windows: name: Build Rust Windows - runs-on: windows-2022 + runs-on: windows-2022-64core steps: - uses: actions/checkout@v6 - name: test @@ -495,7 +495,7 @@ jobs: name: Test Swift Linux strategy: matrix: - swift: ["6.0", "6.1", "6.2"] + swift: ["5.10", "6.1", "6.2"] runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v6 @@ -534,7 +534,7 @@ jobs: run: | swift sdk list swift build --build-tests --swift-sdk swift-6.2.1-RELEASE_wasm - wasmtime --dir . .build/wasm32-unknown-wasip1/debug/FlatBuffers.Test.Swift.WasmPackageTests.xctest --testing-library swift-testing + wasmtime --dir . .build/wasm32-unknown-wasip1/debug/FlatBuffers.Test.Swift.WasmPackageTests.xctest build-ts: name: Build TS @@ -545,7 +545,7 @@ jobs: # FIXME: make test script not rely on flatc run: cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_BUILD_TESTS=OFF -DFLATBUFFERS_INSTALL=OFF -DFLATBUFFERS_BUILD_FLATLIB=OFF -DFLATBUFFERS_BUILD_FLATHASH=OFF . && make -j - name: pnpm - run: npm install -g pnpm@10 + run: npm install -g pnpm esbuild - name: deps run: pnpm i - name: compile diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index d92859cc7..d4c066a8b 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -21,11 +21,11 @@ jobs: run: | git config user.name github-actions[bot] git config user.email 41898282+github-actions[bot]@users.noreply.github.com - - uses: actions/setup-python@v6 + - uses: actions/setup-python@v5 with: python-version: 3.x - run: echo "cache_id=$(date --utc '+%V')" >> $GITHUB_ENV - - uses: actions/cache@v5 + - uses: actions/cache@v4 with: key: mkdocs-material-${{ env.cache_id }} path: .cache diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index eb08715cf..9a9009539 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -27,7 +27,7 @@ jobs: language: c++ fuzz-seconds: 60 - name: Upload Crash - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@v4 if: failure() && steps.build.outcome == 'success' with: name: artifacts diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 5463e5bfa..309fe12c7 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -13,7 +13,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v6 - - uses: actions/setup-node@v6 + - uses: actions/setup-node@v3 with: node-version: '20.x' registry-url: 'https://registry.npmjs.org' @@ -30,7 +30,7 @@ jobs: working-directory: ./python steps: - uses: actions/checkout@v6 - - uses: actions/setup-python@v6 + - uses: actions/setup-python@v4 with: python-version: '3.10' diff --git a/CMakeLists.txt b/CMakeLists.txt index eb5bed523..91e0bdd31 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -238,8 +238,13 @@ set(FlatBuffers_Tests_SRCS tests/util_test.cpp tests/vector_table_naked_ptr_test.h tests/vector_table_naked_ptr_test.cpp + tests/test_vector_type.h + tests/cpp_vector_type_test.h + tests/cpp_vector_type_test.cpp tests/native_type_test_impl.h tests/native_type_test_impl.cpp + tests/bigfoot_ref_test_impl.h + tests/bigfoot_ref_test_impl.cpp tests/alignment_test.h tests/alignment_test.cpp tests/64bit/offset64_test.h @@ -548,18 +553,20 @@ if(FLATBUFFERS_BUILD_TESTS) # The flattest target needs some generated files SET(FLATC_OPT_COMP --cpp --gen-compare --gen-mutable --gen-object-api --reflect-names) SET(FLATC_OPT_SCOPED_ENUMS ${FLATC_OPT_COMP};--scoped-enums) + SET(FLATC_OPT_CPP_VECTOR_TYPE ${FLATC_OPT_COMP};--cpp-include;test_vector_type.h;--cpp-vector-type;::flatbuffers::tests::CustomVector) compile_schema_for_test(tests/alignment_test.fbs "${FLATC_OPT_COMP}") compile_schema_for_test_fbsh(tests/default_vectors_strings_test.fbs "${FLATC_OPT_COMP}") compile_schema_for_test(tests/arrays_test.fbs "${FLATC_OPT_SCOPED_ENUMS}") compile_schema_for_test(tests/native_inline_table_test.fbs "${FLATC_OPT_COMP}") compile_schema_for_test(tests/native_type_test.fbs "${FLATC_OPT_COMP}") + compile_schema_for_test(tests/bigfoot_ref_test.fbs "${FLATC_OPT_COMP}") compile_schema_for_test(tests/key_field/key_field_sample.fbs "${FLATC_OPT_COMP}") compile_schema_for_test(tests/64bit/test_64bit.fbs "${FLATC_OPT_COMP};--bfbs-gen-embed") compile_schema_for_test(tests/64bit/evolution/v1.fbs "${FLATC_OPT_COMP}") compile_schema_for_test(tests/64bit/evolution/v2.fbs "${FLATC_OPT_COMP}") compile_schema_for_test(tests/union_underlying_type_test.fbs "${FLATC_OPT_SCOPED_ENUMS}") - compile_schema_for_test(tests/cross_namespace_pack_test.fbs "${FLATC_OPT_COMP}") + compile_schema_for_test(tests/cpp_vector_type.fbs "${FLATC_OPT_CPP_VECTOR_TYPE}") if(FLATBUFFERS_CODE_SANITIZE) add_fsanitize_to_target(flattests ${FLATBUFFERS_CODE_SANITIZE}) diff --git a/MODULE.bazel b/MODULE.bazel index 166bd0d97..d6416265c 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -23,7 +23,7 @@ bazel_dep( ) bazel_dep( name = "grpc", - version = "1.76.0", + version = "1.70.1", repo_name = "com_github_grpc_grpc", ) bazel_dep( @@ -49,7 +49,7 @@ bazel_dep( ) bazel_dep( name = "rules_swift", - version = "3.1.2", + version = "2.1.1", max_compatibility_level = 3, repo_name = "build_bazel_rules_swift", ) @@ -63,6 +63,9 @@ npm.npm_translate_lock( name = "flatbuffers_npm", npmrc = "//:.npmrc", pnpm_lock = "//ts:pnpm-lock.yaml", + # Override the Bazel package where pnpm-lock.yaml is located and link + # to the specified package instead. + root_package = "ts", verify_node_modules_ignored = "//:.bazelignore", ) use_repo(npm, "flatbuffers_npm") diff --git a/Package.swift b/Package.swift index 413990384..4f60a8c74 100644 --- a/Package.swift +++ b/Package.swift @@ -1,4 +1,4 @@ -// swift-tools-version:6.0 +// swift-tools-version:5.10 /* * Copyright 2020 Google Inc. All rights reserved. * @@ -36,17 +36,14 @@ let package = Package( .target( name: "FlatBuffers", dependencies: ["Common"], - path: "swift/Sources/FlatBuffers", - swiftSettings: .settings), + path: "swift/Sources/FlatBuffers"), .target( name: "FlexBuffers", dependencies: ["Common"], - path: "swift/Sources/FlexBuffers", - swiftSettings: .settings), + path: "swift/Sources/FlexBuffers"), .target( name: "Common", - path: "swift/Sources/Common", - swiftSettings: .settings), + path: "swift/Sources/Common"), .testTarget( name: "FlatbuffersTests", dependencies: .dependencies, @@ -55,14 +52,7 @@ let package = Package( name: "FlexbuffersTests", dependencies: ["FlexBuffers"], path: "tests/swift/Tests/Flexbuffers"), - ], - swiftLanguageModes: [.v6]) - -extension Array where Element == SwiftSetting { - static var settings: [SwiftSetting] { - [.enableUpcomingFeature("ExistentialAny")] - } -} + ]) extension Array where Element == Package.Dependency { static var dependencies: [Package.Dependency] { @@ -70,12 +60,7 @@ extension Array where Element == Package.Dependency { [] #else // Test only Dependency - [ - .package(url: "https://github.com/grpc/grpc-swift-2.git", from: "2.0.0"), - .package( - url: "https://github.com/grpc/grpc-swift-nio-transport.git", - from: "2.0.0"), - ] + [.package(url: "https://github.com/grpc/grpc-swift.git", from: "1.4.1")] #endif } } @@ -87,10 +72,7 @@ extension Array where Element == PackageDescription.Target.Dependency { #else // Test only Dependency [ - .product(name: "GRPCCore", package: "grpc-swift-2"), - .product( - name: "GRPCNIOTransportHTTP2", - package: "grpc-swift-nio-transport"), + .product(name: "GRPC", package: "grpc-swift"), "FlatBuffers", ] #endif diff --git a/benchmarks/swift/Benchmarks/FlatbuffersBenchmarks/FlatbuffersBenchmarks.swift b/benchmarks/swift/Benchmarks/FlatbuffersBenchmarks/FlatbuffersBenchmarks.swift index aa085686f..4607f5809 100644 --- a/benchmarks/swift/Benchmarks/FlatbuffersBenchmarks/FlatbuffersBenchmarks.swift +++ b/benchmarks/swift/Benchmarks/FlatbuffersBenchmarks/FlatbuffersBenchmarks.swift @@ -97,7 +97,6 @@ let benchmarks = { for _ in benchmark.scaledIterations { blackHole(ByteBuffer(assumingMemoryBound: memory, capacity: Int(oneGB))) } - benchmark.stopMeasurement() } Benchmark("Clearing 1GB", configuration: singleConfiguration) { benchmark in @@ -106,7 +105,6 @@ let benchmarks = { for _ in benchmark.scaledIterations { blackHole(fb.clear()) } - benchmark.stopMeasurement() } Benchmark("Strings 10") { benchmark in @@ -115,7 +113,6 @@ let benchmarks = { for _ in benchmark.scaledIterations { blackHole(fb.create(string: str10)) } - benchmark.stopMeasurement() } Benchmark("Strings 100") { benchmark in @@ -124,7 +121,6 @@ let benchmarks = { for _ in benchmark.scaledIterations { blackHole(fb.create(string: str100)) } - benchmark.stopMeasurement() } Benchmark("Vector 1 Bytes") { benchmark in @@ -133,7 +129,6 @@ let benchmarks = { for _ in benchmark.scaledIterations { blackHole(fb.createVector(bytes: bytes)) } - benchmark.stopMeasurement() } Benchmark("Vector 1 Ints") { benchmark in @@ -142,7 +137,6 @@ let benchmarks = { for _ in benchmark.scaledIterations { blackHole(fb.createVector(ints)) } - benchmark.stopMeasurement() } Benchmark("Vector 100 Ints") { benchmark in @@ -151,7 +145,6 @@ let benchmarks = { for i in benchmark.scaledIterations { blackHole(fb.createVector(ints)) } - benchmark.stopMeasurement() } Benchmark("Vector 100 Bytes") { benchmark in @@ -160,7 +153,6 @@ let benchmarks = { for i in benchmark.scaledIterations { blackHole(fb.createVector(bytes)) } - benchmark.stopMeasurement() } Benchmark("Vector 100 ContiguousBytes") { benchmark in @@ -169,7 +161,6 @@ let benchmarks = { for i in benchmark.scaledIterations { blackHole(fb.createVector(bytes: bytes)) } - benchmark.stopMeasurement() } Benchmark( @@ -187,7 +178,6 @@ let benchmarks = { fb.add(offset: off, at: 8) blackHole(fb.endTable(at: s)) } - benchmark.stopMeasurement() } Benchmark( @@ -200,7 +190,6 @@ let benchmarks = { let s = fb.startTable(with: 4) blackHole(fb.endTable(at: s)) } - benchmark.stopMeasurement() } Benchmark("Struct") { benchmark in @@ -209,7 +198,6 @@ let benchmarks = { for _ in benchmark.scaledIterations { blackHole(fb.create(struct: array.first!)) } - benchmark.stopMeasurement() } Benchmark("Structs") { benchmark in @@ -231,7 +219,6 @@ let benchmarks = { fb.add(offset: vector, at: 4) let root = Offset(offset: fb.endTable(at: start)) blackHole(fb.finish(offset: root)) - benchmark.stopMeasurement() } Benchmark("Vector of Offsets") { benchmark in @@ -252,15 +239,12 @@ let benchmarks = { fb.add(offset: off, at: 2) blackHole(fb.endTable(at: s)) } - benchmark.stopMeasurement() } Benchmark("Reading Doubles") { benchmark in let byteBuffer = ByteBuffer(data: data) - benchmark.startMeasurement() for _ in benchmark.scaledIterations { blackHole(byteBuffer.read(def: Double.self, position: 0)) } - benchmark.stopMeasurement() } } diff --git a/benchmarks/swift/Package.swift b/benchmarks/swift/Package.swift index 41b536cc2..118732987 100644 --- a/benchmarks/swift/Package.swift +++ b/benchmarks/swift/Package.swift @@ -39,14 +39,4 @@ let package = Package( plugins: [ .plugin(name: "BenchmarkPlugin", package: "package-benchmark"), ]), - .executableTarget( - name: "FlexBuffersBenchmarks", - dependencies: [ - .product(name: "FlexBuffers", package: "flatbuffers"), - .product(name: "Benchmark", package: "package-benchmark"), - ], - path: "Benchmarks/FlexBuffersBenchmarks", - plugins: [ - .plugin(name: "BenchmarkPlugin", package: "package-benchmark"), - ]), ]) diff --git a/dart/lib/src/builder.dart b/dart/lib/src/builder.dart index 9e90e4c38..cdd0aec53 100644 --- a/dart/lib/src/builder.dart +++ b/dart/lib/src/builder.dart @@ -5,7 +5,7 @@ import 'types.dart'; /// The main builder class for creation of a FlexBuffer. class Builder { - ByteData _buffer; + final ByteData _buffer; List<_StackValue> _stack = []; List<_StackPointer> _stackPointers = []; int _offset = 0; @@ -506,7 +506,6 @@ class Builder { if (prevSize < size) { final newBuf = ByteData(size); newBuf.buffer.asUint8List().setAll(0, _buffer.buffer.asUint8List()); - _buffer = newBuf; } return newOffset; } diff --git a/dart/test/flex_builder_test.dart b/dart/test/flex_builder_test.dart index 834afe876..0f766de73 100644 --- a/dart/test/flex_builder_test.dart +++ b/dart/test/flex_builder_test.dart @@ -318,21 +318,6 @@ void main() { 1, ]); } - { - // Default buffer is 2048 bytes, add 2300 bytes of strings that force it - // to grow. - final s1 = 'A' * 1000; - final s2 = 'B' * 800; - final s3 = 'C' * 500; - - var flx = Builder() - ..startVector() - ..addString(s1) - ..addString(s2) - ..addString(s3) - ..end(); - expect(flx.finish().length, 2323); - } }); test('build map', () { diff --git a/docs/source/flatc.md b/docs/source/flatc.md index 598992e22..150b3bd83 100644 --- a/docs/source/flatc.md +++ b/docs/source/flatc.md @@ -168,6 +168,12 @@ list of `FILES...`. std::string from Flatbuffers, but (char* + length). This allows efficient construction of custom string types, including zero-copy construction. +- `--cpp-vector-type T` : Set object API vector type (default std::vector). + T must be a template taking a single element type argument and support + resize(), reserve(), size(), data(), operator[], emplace_back() and + begin()/end(), matching the subset of std::vector's interface generated + code relies on. + - `--no-cpp-direct-copy` : Don't generate direct copy methods for C++ object-based API. diff --git a/docs/source/languages/cpp.md b/docs/source/languages/cpp.md index 96be6a3a3..c7ed96a66 100644 --- a/docs/source/languages/cpp.md +++ b/docs/source/languages/cpp.md @@ -57,7 +57,7 @@ a `char *` array, which you pass to `GetMonster()`. ```cpp #include "flatbuffers/flatbuffers.h" - #include "monster_test_generated.h" + #include "monster_test_generate.h" #include // C++ header file for printing #include // C++ header file for file access @@ -242,6 +242,42 @@ provide the following functions to aide in the serialization process: } ``` +- `bigfoot_ref_wrapper("type")` (on a struct) together with `bigfoot_ref("type")` + (on a field of that struct type): Bigfoot-specific sugar for a + UUID-addressed reference to another native type. `bigfoot_ref_wrapper` + marks a struct as a reference-wrapper template (e.g. Bigfoot's + `HardReference`/`SoftReference`); `bigfoot_ref` on a field of that type + names the referenced native type, e.g. `bigfoot_ref: "::Bigfoot::AssetA"` + on a `HardReference`-typed field with `bigfoot_ref_wrapper: + "::Bigfoot::HardReference"` produces the field's native type + `::Bigfoot::HardReference<::Bigfoot::AssetA>` (auto-deriving a + `native_type_pack_name` of `HardReferenceAssetA`, same short-name + convention as `native_type_pack_name`). Unlike a hand-written + `native_type`, `bigfoot_ref` also emits, directly into the generated + header: + - a forward declaration of the referenced type (so the referencing + schema's generated header never needs that type's real definition - + only the wrapper template's constructor and a `GetUUID()` accessor + are used, and those don't require the referenced type to be + complete), and + - `inline` `Pack`/`UnPack` definitions for it (so no + hand-written implementation is required anywhere). + +```cpp + struct HardReference (bigfoot_ref_wrapper: "::Bigfoot::HardReference") { + uuid: UUID; + } + + table AssetB { + ref_a: HardReference (bigfoot_ref: "::Bigfoot::AssetA"); + } +``` + + is enough on its own - no forward declaration of `::Bigfoot::AssetA` and + no `flatbuffers::Pack/UnPackHardReferenceAssetA` implementation need to + be written by hand. `bigfoot_ref` is only valid on fields whose type is a + struct (or vector of structs) that declares `bigfoot_ref_wrapper`. + - `native_type("type")` (on a table): Tables can also be represented with native types. For example, the following schema: @@ -337,6 +373,27 @@ constructor in the following format: `custom_str_class(const char *, size_t)`. Please note that the character array is not guaranteed to be NULL terminated, you should always use the provided size to determine end of string. +## Using different vector type + +By default the object tree's vector fields are built out of `std::vector`, +but you can influence this either globally (using the `--cpp-vector-type` +argument to `flatc`) or per field using the `cpp_vector_type` attribute, to +use any other vector-like template type (e.g. `eastl::vector`). + +The type must be a template taking a single element type argument +(`my_vector`), and must support the following member functions: +`resize()`, `reserve()`, `size()`, `data()`, `operator[]`, `emplace_back()`, +and `begin()`/`end()`. This matches the subset of `std::vector`'s interface +that generated code relies on. + +Note that unlike `std::vector`, the custom vector type must not use a +bit-packed specialization for `bool` elements, since generated code accesses +`data()` as a contiguous `bool` array. + +As with custom string types, the header defining the custom vector type is +not automatically included; use `--cpp-include` to add the necessary +`#include`. + ## Reflection (& Resizing) There is experimental support for reflection in FlatBuffers, allowing you to diff --git a/docs/source/languages/rust.md b/docs/source/languages/rust.md index 2d23987ca..04f7f02e6 100644 --- a/docs/source/languages/rust.md +++ b/docs/source/languages/rust.md @@ -97,61 +97,6 @@ convenient accessors for all fields, e.g. `hp()`, `mana()`, etc: *Note: That we never stored a `mana` value, so it will return the default.* -## Fallible API and Custom Allocators - -Every `FlatBufferBuilder` method that may allocate has a `try_*` counterpart -(e.g. `try_create_string`, `try_push`, `try_finish`) that returns -`Result` instead of panicking. This is useful when allocation -failures must be handled gracefully: for example in `no_std` environments or -with fixed-capacity buffers. - -The existing panicking methods are unchanged and remain the simplest option -when using the default allocator. - -#### Custom allocators - -Implement the `Allocator` trait and pass it to `FlatBufferBuilder::new_in()`: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.rs} - use flatbuffers::{Allocator, FlatBufferBuilder}; - - struct MyAllocator { /* ... */ } - - unsafe impl Allocator for MyAllocator { - type Error = MyError; - fn grow_downwards(&mut self) -> Result<(), Self::Error> { /* ... */ } - fn len(&self) -> usize { /* ... */ } - } - - let alloc = MyAllocator::new(/* ... */); - let mut builder = FlatBufferBuilder::new_in(alloc); -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The built-in `DefaultAllocator` uses `Vec` and sets `Error = Infallible`, -so the `try_*` methods on a default builder can never fail. - -#### Example: building a buffer with error propagation - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.rs} - fn build( - builder: &mut FlatBufferBuilder, - ) -> Result<(), A::Error> { - let name = builder.try_create_string("Orc")?; - let inventory = builder.try_create_vector(&[0u8, 1, 2, 3, 4])?; - - let table_start = builder.start_table(); - builder.try_push_slot_always(Monster::VT_NAME, name)?; - builder.try_push_slot_always(Monster::VT_INVENTORY, inventory)?; - builder.try_push_slot(Monster::VT_HP, 80i16, 100)?; - let root = builder.try_end_table(table_start)?; - - builder.try_finish(root, None)?; - Ok(()) - } -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -See the `FlatBufferBuilder` rustdoc for the full list of `try_*` methods. - ## Direct memory access As you can see from the above examples, all elements in a buffer are @@ -260,47 +205,6 @@ And example of usage, for the time being, can be found in - Safe getters in [SafeBuffer](https://docs.rs/flatbuffers-reflection/latest/flatbuffers_reflection/struct.SafeBuffer.html), which does verification when constructed so you can use it for any data source -## Buffer pre allocation in a latency-sensitive context - -In latency-sensitive applications, dynamic memory allocations can introduce unpredictable latency spikes. The `FlatBufferBuilder` internally uses several `Vec`s that may reallocate during serialization: - -- The backing buffer for the FlatBuffer data -- `field_locs` for tracking field locations within tables -- `written_vtable_revpos` for deduplicating vtables -- `strings_pool` for shared string interning - -To avoid allocations during serialization, you can preallocate all internal vectors upfront using the `with_internal_capacity` constructor: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.rs} - // Preallocate: 1KB buffer, 8 field locations, 16 vtables, 32 shared strings - let mut builder = FlatBufferBuilder::with_internal_capacity(1024, 8, 16, 32); - - // All subsequent operations will not allocate (if capacities are sufficient) - let name = builder.create_shared_string("MyMonster"); - // ... build your FlatBuffer ... -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -There are three variants available: - -- `with_internal_capacity(size, field_locs, vtables, strings)` - Creates a new builder with all capacities preallocated -- `from_vec_with_internal_capacity(buffer, field_locs, vtables, strings)` - Reuses an existing `Vec` as the backing buffer -- `new_in_with_internal_capacity(allocator, field_locs, vtables, strings)` - Uses a custom `Allocator` with preallocated internal vecs - -When combined with `reset()`, you can reuse the same builder across multiple serializations without any allocations after the initial setup: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.rs} - let mut builder = FlatBufferBuilder::with_internal_capacity(1024, 8, 16, 32); - - loop { - // Build a FlatBuffer (allocation-free if capacities are sufficient) - let data = build_message(&mut builder); - send(data); - - // Reset for reuse - clears state but retains allocated capacity - builder.reset(); - } -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ## Useful tools created by others * [flatc-rust](https://github.com/frol/flatc-rust) - FlatBuffers compiler diff --git a/docs/source/schema.md b/docs/source/schema.md index 656eec0d5..2baa5b78a 100644 --- a/docs/source/schema.md +++ b/docs/source/schema.md @@ -427,6 +427,9 @@ Current understood attributes: it won't be accessible anymore by newer code. Note that if you deprecate a field that was previous required, old code may fail to validate new data (when using the optional verifier). + +### `required` + - `required` (on a non-scalar table field): this field must always be set. By default, fields do not need to be present in the binary. This is desirable, as it helps with forwards/backwards compatibility, and flexibility of data diff --git a/docs/source/support.md b/docs/source/support.md index 46648e7d3..bd49e2978 100644 --- a/docs/source/support.md +++ b/docs/source/support.md @@ -26,7 +26,7 @@ Simple mutation | Yes | Yes | Yes | Yes | No | No Reflection | Yes | No | No | No | No | No | No | Basic | No | No | No | No | No Buffer verifier | Yes | No | No | No | No | No | No | Yes | No | No | No | No | Yes Native Object API | Yes | No | Yes | Yes | Yes | Yes | Yes | No | No | Yes | No | No | Yes -Optional Scalars | Yes | Yes | Yes | Yes | No | Yes | Yes | Yes | No | No | Yes | Yes | Yes +Optional Scalars | Yes | Yes | Yes | No | No | Yes | Yes | Yes | No | No | Yes | Yes | Yes Flexbuffers | Yes | Yes | ? | ? | ? | ? | ? | ? | ? | ? | ? | Yes | Yes Testing: basic | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | ? | Yes | Yes | Yes | Yes Testing: fuzz | Yes | No | No | Yes | Yes | No | No | No | ? | No | No | Yes | No diff --git a/goldens/rust/basic_generated.rs b/goldens/rust/basic_generated.rs index b8a699b68..aa251d1c0 100644 --- a/goldens/rust/basic_generated.rs +++ b/goldens/rust/basic_generated.rs @@ -1,322 +1,297 @@ // automatically generated by the FlatBuffers compiler, do not modify // @generated + extern crate alloc; #[allow(unused_imports, dead_code)] pub mod flatbuffers { - extern crate alloc; - #[allow(unused_imports, dead_code)] - pub mod goldens { - extern crate alloc; +extern crate alloc; +#[allow(unused_imports, dead_code)] +pub mod goldens { - pub enum GalaxyOffset {} +extern crate alloc; - #[derive(Copy, Clone, PartialEq)] - pub struct Galaxy<'a> { - pub _tab: ::flatbuffers::Table<'a>, - } +pub enum GalaxyOffset {} +#[derive(Copy, Clone, PartialEq)] - impl<'a> ::flatbuffers::Follow<'a> for Galaxy<'a> { - type Inner = Galaxy<'a>; +pub struct Galaxy<'a> { + pub _tab: ::flatbuffers::Table<'a>, +} - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } - } - } +impl<'a> ::flatbuffers::Follow<'a> for Galaxy<'a> { + type Inner = Galaxy<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } + } +} - impl<'a> Galaxy<'a> { - pub const VT_NUM_STARS: ::flatbuffers::VOffsetT = 4; +impl<'a> Galaxy<'a> { + pub const VT_NUM_STARS: ::flatbuffers::VOffsetT = 4; - #[inline] - pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { - Galaxy { _tab: table } - } - - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args GalaxyArgs - ) -> ::flatbuffers::WIPOffset> { - let mut builder = GalaxyBuilder::new(_fbb); - builder.add_num_stars(args.num_stars); - builder.finish() - } + #[inline] + pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { + Galaxy { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args GalaxyArgs + ) -> ::flatbuffers::WIPOffset> { + let mut builder = GalaxyBuilder::new(_fbb); + builder.add_num_stars(args.num_stars); + builder.finish() + } - #[inline] - pub fn num_stars(&self) -> i64 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Galaxy::VT_NUM_STARS, Some(0)).unwrap()} - } - } + #[inline] + pub fn num_stars(&self) -> i64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Galaxy::VT_NUM_STARS, Some(0)).unwrap()} + } +} - impl ::flatbuffers::Verifiable for Galaxy<'_> { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.visit_table(pos)? - .visit_field::("num_stars", Self::VT_NUM_STARS, false)? - .finish(); - Ok(()) - } - } +impl ::flatbuffers::Verifiable for Galaxy<'_> { + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.visit_table(pos)? + .visit_field::("num_stars", Self::VT_NUM_STARS, false)? + .finish(); + Ok(()) + } +} +pub struct GalaxyArgs { + pub num_stars: i64, +} +impl<'a> Default for GalaxyArgs { + #[inline] + fn default() -> Self { + GalaxyArgs { + num_stars: 0, + } + } +} - pub struct GalaxyArgs { - pub num_stars: i64, - } +pub struct GalaxyBuilder<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> { + fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, + start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, +} +impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> GalaxyBuilder<'a, 'b, A> { + #[inline] + pub fn add_num_stars(&mut self, num_stars: i64) { + self.fbb_.push_slot::(Galaxy::VT_NUM_STARS, num_stars, 0); + } + #[inline] + pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> GalaxyBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + GalaxyBuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> ::flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + ::flatbuffers::WIPOffset::new(o.value()) + } +} - impl<'a> Default for GalaxyArgs { - #[inline] - fn default() -> Self { - GalaxyArgs { - num_stars: 0, - } - } - } +impl ::core::fmt::Debug for Galaxy<'_> { + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + let mut ds = f.debug_struct("Galaxy"); + ds.field("num_stars", &self.num_stars()); + ds.finish() + } +} +pub enum UniverseOffset {} +#[derive(Copy, Clone, PartialEq)] - pub struct GalaxyBuilder<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> { - fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, - } +pub struct Universe<'a> { + pub _tab: ::flatbuffers::Table<'a>, +} - impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> GalaxyBuilder<'a, 'b, A> { - #[inline] - pub fn add_num_stars(&mut self, num_stars: i64) { - self.fbb_.push_slot::(Galaxy::VT_NUM_STARS, num_stars, 0); - } +impl<'a> ::flatbuffers::Follow<'a> for Universe<'a> { + type Inner = Universe<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } + } +} - #[inline] - pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> GalaxyBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - GalaxyBuilder { - fbb_: _fbb, - start_: start, - } - } +impl<'a> Universe<'a> { + pub const VT_AGE: ::flatbuffers::VOffsetT = 4; + pub const VT_GALAXIES: ::flatbuffers::VOffsetT = 6; - #[inline] - pub fn finish(self) -> ::flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - ::flatbuffers::WIPOffset::new(o.value()) - } - } - - impl ::core::fmt::Debug for Galaxy<'_> { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - let mut ds = f.debug_struct("Galaxy"); - ds.field("num_stars", &self.num_stars()); - ds.finish() - } - } - - pub enum UniverseOffset {} - - #[derive(Copy, Clone, PartialEq)] - pub struct Universe<'a> { - pub _tab: ::flatbuffers::Table<'a>, - } - - impl<'a> ::flatbuffers::Follow<'a> for Universe<'a> { - type Inner = Universe<'a>; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } - } - } - - impl<'a> Universe<'a> { - pub const VT_AGE: ::flatbuffers::VOffsetT = 4; - pub const VT_GALAXIES: ::flatbuffers::VOffsetT = 6; - - #[inline] - pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { - Universe { _tab: table } - } - - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args UniverseArgs<'args> - ) -> ::flatbuffers::WIPOffset> { - let mut builder = UniverseBuilder::new(_fbb); - builder.add_age(args.age); - if let Some(x) = args.galaxies { builder.add_galaxies(x); } - builder.finish() - } + #[inline] + pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { + Universe { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args UniverseArgs<'args> + ) -> ::flatbuffers::WIPOffset> { + let mut builder = UniverseBuilder::new(_fbb); + builder.add_age(args.age); + if let Some(x) = args.galaxies { builder.add_galaxies(x); } + builder.finish() + } - #[inline] - pub fn age(&self) -> f64 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Universe::VT_AGE, Some(0.0)).unwrap()} - } + #[inline] + pub fn age(&self) -> f64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Universe::VT_AGE, Some(0.0)).unwrap()} + } + #[inline] + pub fn galaxies(&self) -> Option<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset>>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset>>>(Universe::VT_GALAXIES, None)} + } +} - #[inline] - pub fn galaxies(&self) -> Option<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset>>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset>>>(Universe::VT_GALAXIES, None)} - } - } +impl ::flatbuffers::Verifiable for Universe<'_> { + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.visit_table(pos)? + .visit_field::("age", Self::VT_AGE, false)? + .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, ::flatbuffers::ForwardsUOffset>>>("galaxies", Self::VT_GALAXIES, false)? + .finish(); + Ok(()) + } +} +pub struct UniverseArgs<'a> { + pub age: f64, + pub galaxies: Option<::flatbuffers::WIPOffset<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset>>>>, +} +impl<'a> Default for UniverseArgs<'a> { + #[inline] + fn default() -> Self { + UniverseArgs { + age: 0.0, + galaxies: None, + } + } +} - impl ::flatbuffers::Verifiable for Universe<'_> { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.visit_table(pos)? - .visit_field::("age", Self::VT_AGE, false)? - .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, ::flatbuffers::ForwardsUOffset>>>("galaxies", Self::VT_GALAXIES, false)? - .finish(); - Ok(()) - } - } +pub struct UniverseBuilder<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> { + fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, + start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, +} +impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> UniverseBuilder<'a, 'b, A> { + #[inline] + pub fn add_age(&mut self, age: f64) { + self.fbb_.push_slot::(Universe::VT_AGE, age, 0.0); + } + #[inline] + pub fn add_galaxies(&mut self, galaxies: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , ::flatbuffers::ForwardsUOffset>>>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Universe::VT_GALAXIES, galaxies); + } + #[inline] + pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> UniverseBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + UniverseBuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> ::flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + ::flatbuffers::WIPOffset::new(o.value()) + } +} - pub struct UniverseArgs<'a> { - pub age: f64, - pub galaxies: Option<::flatbuffers::WIPOffset<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset>>>>, - } +impl ::core::fmt::Debug for Universe<'_> { + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + let mut ds = f.debug_struct("Universe"); + ds.field("age", &self.age()); + ds.field("galaxies", &self.galaxies()); + ds.finish() + } +} +#[inline] +/// Verifies that a buffer of bytes contains a `Universe` +/// 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_universe_unchecked`. +pub fn root_as_universe(buf: &[u8]) -> Result, ::flatbuffers::InvalidFlatbuffer> { + ::flatbuffers::root::(buf) +} +#[inline] +/// Verifies that a buffer of bytes contains a size prefixed +/// `Universe` 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_universe_unchecked`. +pub fn size_prefixed_root_as_universe(buf: &[u8]) -> Result, ::flatbuffers::InvalidFlatbuffer> { + ::flatbuffers::size_prefixed_root::(buf) +} +#[inline] +/// Verifies, with the given options, that a buffer of bytes +/// contains a `Universe` 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_universe_unchecked`. +pub fn root_as_universe_with_opts<'b, 'o>( + opts: &'o ::flatbuffers::VerifierOptions, + buf: &'b [u8], +) -> Result, ::flatbuffers::InvalidFlatbuffer> { + ::flatbuffers::root_with_opts::>(opts, buf) +} +#[inline] +/// Verifies, with the given verifier options, that a buffer of +/// bytes contains a size prefixed `Universe` 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_universe_unchecked`. +pub fn size_prefixed_root_as_universe_with_opts<'b, 'o>( + opts: &'o ::flatbuffers::VerifierOptions, + buf: &'b [u8], +) -> Result, ::flatbuffers::InvalidFlatbuffer> { + ::flatbuffers::size_prefixed_root_with_opts::>(opts, buf) +} +#[inline] +/// Assumes, without verification, that a buffer of bytes contains a Universe and returns it. +/// # Safety +/// Callers must trust the given bytes do indeed contain a valid `Universe`. +pub unsafe fn root_as_universe_unchecked(buf: &[u8]) -> Universe<'_> { + unsafe { ::flatbuffers::root_unchecked::(buf) } +} +#[inline] +/// Assumes, without verification, that a buffer of bytes contains a size prefixed Universe and returns it. +/// # Safety +/// Callers must trust the given bytes do indeed contain a valid size prefixed `Universe`. +pub unsafe fn size_prefixed_root_as_universe_unchecked(buf: &[u8]) -> Universe<'_> { + unsafe { ::flatbuffers::size_prefixed_root_unchecked::(buf) } +} +#[inline] +pub fn finish_universe_buffer<'a, 'b, A: ::flatbuffers::Allocator + 'a>( + fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, + root: ::flatbuffers::WIPOffset>) { + fbb.finish(root, None); +} - impl<'a> Default for UniverseArgs<'a> { - #[inline] - fn default() -> Self { - UniverseArgs { - age: 0.0, - galaxies: None, - } - } - } +#[inline] +pub fn finish_size_prefixed_universe_buffer<'a, 'b, A: ::flatbuffers::Allocator + 'a>(fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, root: ::flatbuffers::WIPOffset>) { + fbb.finish_size_prefixed(root, None); +} +} // pub mod goldens +} // pub mod flatbuffers - pub struct UniverseBuilder<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> { - fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, - } - - impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> UniverseBuilder<'a, 'b, A> { - #[inline] - pub fn add_age(&mut self, age: f64) { - self.fbb_.push_slot::(Universe::VT_AGE, age, 0.0); - } - - #[inline] - pub fn add_galaxies(&mut self, galaxies: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , ::flatbuffers::ForwardsUOffset>>>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Universe::VT_GALAXIES, galaxies); - } - - #[inline] - pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> UniverseBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - UniverseBuilder { - fbb_: _fbb, - start_: start, - } - } - - #[inline] - pub fn finish(self) -> ::flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - ::flatbuffers::WIPOffset::new(o.value()) - } - } - - impl ::core::fmt::Debug for Universe<'_> { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - let mut ds = f.debug_struct("Universe"); - ds.field("age", &self.age()); - ds.field("galaxies", &self.galaxies()); - ds.finish() - } - } - - /// Verifies that a buffer of bytes contains a `Universe` - /// 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_universe_unchecked`. - #[inline] - pub fn root_as_universe(buf: &[u8]) -> Result, ::flatbuffers::InvalidFlatbuffer> { - ::flatbuffers::root::(buf) - } - - /// Verifies that a buffer of bytes contains a size prefixed - /// `Universe` 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_universe_unchecked`. - #[inline] - pub fn size_prefixed_root_as_universe(buf: &[u8]) -> Result, ::flatbuffers::InvalidFlatbuffer> { - ::flatbuffers::size_prefixed_root::(buf) - } - - /// Verifies, with the given options, that a buffer of bytes - /// contains a `Universe` 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_universe_unchecked`. - #[inline] - pub fn root_as_universe_with_opts<'b, 'o>( - opts: &'o ::flatbuffers::VerifierOptions, - buf: &'b [u8], - ) -> Result, ::flatbuffers::InvalidFlatbuffer> { - ::flatbuffers::root_with_opts::>(opts, buf) - } - - /// Verifies, with the given verifier options, that a buffer of - /// bytes contains a size prefixed `Universe` 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_universe_unchecked`. - #[inline] - pub fn size_prefixed_root_as_universe_with_opts<'b, 'o>( - opts: &'o ::flatbuffers::VerifierOptions, - buf: &'b [u8], - ) -> Result, ::flatbuffers::InvalidFlatbuffer> { - ::flatbuffers::size_prefixed_root_with_opts::>(opts, buf) - } - - /// Assumes, without verification, that a buffer of bytes contains a Universe and returns it. - /// # Safety - /// Callers must trust the given bytes do indeed contain a valid `Universe`. - #[inline] - pub unsafe fn root_as_universe_unchecked(buf: &[u8]) -> Universe<'_> { - unsafe { ::flatbuffers::root_unchecked::(buf) } - } - - /// Assumes, without verification, that a buffer of bytes contains a size prefixed Universe and returns it. - /// # Safety - /// Callers must trust the given bytes do indeed contain a valid size prefixed `Universe`. - #[inline] - pub unsafe fn size_prefixed_root_as_universe_unchecked(buf: &[u8]) -> Universe<'_> { - unsafe { ::flatbuffers::size_prefixed_root_unchecked::(buf) } - } - - #[inline] - pub fn finish_universe_buffer<'a, 'b, A: ::flatbuffers::Allocator + 'a>( - fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - root: ::flatbuffers::WIPOffset> - ) { - fbb.finish(root, None); - } - - #[inline] - pub fn finish_size_prefixed_universe_buffer<'a, 'b, A: ::flatbuffers::Allocator + 'a>( - fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - root: ::flatbuffers::WIPOffset> - ) { - fbb.finish_size_prefixed(root, None); - } - } // pub mod goldens -} // pub mod flatbuffers diff --git a/goldens/ts/flatbuffers/goldens/universe.ts b/goldens/ts/flatbuffers/goldens/universe.ts index acae67b69..5634d7831 100644 --- a/goldens/ts/flatbuffers/goldens/universe.ts +++ b/goldens/ts/flatbuffers/goldens/universe.ts @@ -4,7 +4,7 @@ import * as flatbuffers from 'flatbuffers'; -import { Galaxy } from './galaxy.js'; +import { Galaxy } from '../../flatbuffers/goldens/galaxy.js'; export class Universe { diff --git a/grpc/examples/swift/Greeter/Package.swift b/grpc/examples/swift/Greeter/Package.swift index 3fc96adc7..664f2a0cd 100644 --- a/grpc/examples/swift/Greeter/Package.swift +++ b/grpc/examples/swift/Greeter/Package.swift @@ -1,4 +1,4 @@ -// swift-tools-version:6.2 +// swift-tools-version:5.10 /* * Copyright 2020 Google Inc. All rights reserved. * @@ -20,43 +20,39 @@ import PackageDescription let package = Package( name: "Greeter", platforms: [ - .iOS(.v18), - .macOS(.v15), + .iOS(.v12), + .macOS(.v10_14), ], dependencies: [ - .package(path: "../../../.."), - .package(url: "https://github.com/grpc/grpc-swift-2.git", from: "2.0.0"), - .package( - url: "https://github.com/grpc/grpc-swift-nio-transport.git", - from: "2.0.0"), - .package( - url: "https://github.com/apple/swift-argument-parser.git", - from: "1.5.0"), + .package(path: "../../../../swift"), + .package(url: "https://github.com/grpc/grpc-swift.git", from: "1.0.0"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages which this package depends on. .target( - name: "Models", + name: "Model", dependencies: [ - .product(name: "FlatBuffers", package: "flatbuffers"), - .product(name: "GRPCCore", package: "grpc-swift-2"), - .product( - name: "GRPCNIOTransportHTTP2", - package: "grpc-swift-nio-transport"), - ]), + "GRPC", + "FlatBuffers", + ], + path: "Sources/Model"), // Client for the Greeter example - .executableTarget( - name: "Commands", + .target( + name: "Client", dependencies: [ - .product(name: "GRPCCore", package: "grpc-swift-2"), - .product( - name: "GRPCNIOTransportHTTP2", - package: "grpc-swift-nio-transport"), - .product( - name: "ArgumentParser", - package: "swift-argument-parser"), - "Models", - ]), + "GRPC", + "Model", + ], + path: "Sources/client"), + + // Server for the Greeter example + .target( + name: "Server", + dependencies: [ + "GRPC", + "Model", + ], + path: "Sources/server"), ]) diff --git a/grpc/examples/swift/Greeter/Sources/Model/greeter.grpc.swift b/grpc/examples/swift/Greeter/Sources/Model/greeter.grpc.swift new file mode 100644 index 000000000..700c5cd59 --- /dev/null +++ b/grpc/examples/swift/Greeter/Sources/Model/greeter.grpc.swift @@ -0,0 +1,147 @@ +// Generated GRPC code for FlatBuffers swift! +/// The following code is generated by the Flatbuffers library which might not be in sync with grpc-swift +/// in case of an issue please open github issue, though it would be maintained + +// swiftlint:disable all +// swiftformat:disable all + +#if !os(Windows) +import Foundation +import GRPC +import NIO +import NIOHTTP1 +import FlatBuffers + +public protocol GRPCFlatBufPayload: GRPCPayload, FlatBufferGRPCMessage {} +public extension GRPCFlatBufPayload { + init(serializedByteBuffer: inout NIO.ByteBuffer) throws { + self.init(byteBuffer: FlatBuffers.ByteBuffer(contiguousBytes: serializedByteBuffer.readableBytesView, count: serializedByteBuffer.readableBytes)) + } + func serialize(into buffer: inout NIO.ByteBuffer) throws { + withUnsafeReadableBytes { buffer.writeBytes($0) } + } +} +extension Message: GRPCFlatBufPayload {} + +/// Usage: instantiate models_GreeterServiceClient, then call methods of this protocol to make API calls. +public protocol models_GreeterClientProtocol: GRPCClient { + + var serviceName: String { get } + + var interceptors: models_GreeterClientInterceptorFactoryProtocol? { get } + + func SayHello( + _ request: Message + , callOptions: CallOptions? + ) -> UnaryCall, Message> + + func SayManyHellos( + _ request: Message + , callOptions: CallOptions?, + handler: @escaping (Message) -> Void + ) -> ServerStreamingCall, Message> + +} + +extension models_GreeterClientProtocol { + + public var serviceName: String { "models.Greeter" } + + public func SayHello( + _ request: Message + , callOptions: CallOptions? = nil + ) -> UnaryCall, Message> { + return self.makeUnaryCall( + path: "/models.Greeter/SayHello", + request: request, + callOptions: callOptions ?? self.defaultCallOptions, + interceptors: self.interceptors?.makeSayHelloInterceptors() ?? [] + ) + } + + public func SayManyHellos( + _ request: Message + , callOptions: CallOptions? = nil, + handler: @escaping (Message) -> Void + ) -> ServerStreamingCall, Message> { + return self.makeServerStreamingCall( + path: "/models.Greeter/SayManyHellos", + request: request, + callOptions: callOptions ?? self.defaultCallOptions, + interceptors: self.interceptors?.makeSayManyHellosInterceptors() ?? [], + handler: handler + ) + } +} + +public protocol models_GreeterClientInterceptorFactoryProtocol { + /// - Returns: Interceptors to use when invoking 'SayHello'. + func makeSayHelloInterceptors() -> [ClientInterceptor, Message>] + + /// - Returns: Interceptors to use when invoking 'SayManyHellos'. + func makeSayManyHellosInterceptors() -> [ClientInterceptor, Message>] + +} + +public final class models_GreeterServiceClient: models_GreeterClientProtocol { + public let channel: GRPCChannel + public var defaultCallOptions: CallOptions + public var interceptors: models_GreeterClientInterceptorFactoryProtocol? + + public init( + channel: GRPCChannel, + defaultCallOptions: CallOptions = CallOptions(), + interceptors: models_GreeterClientInterceptorFactoryProtocol? = nil + ) { + self.channel = channel + self.defaultCallOptions = defaultCallOptions + self.interceptors = interceptors + } +} + +public protocol models_GreeterProvider: CallHandlerProvider { + var interceptors: models_GreeterServerInterceptorFactoryProtocol? { get } + func SayHello(request: Message, context: StatusOnlyCallContext) -> EventLoopFuture> + func SayManyHellos(request: Message, context: StreamingResponseCallContext>) -> EventLoopFuture +} + +public extension models_GreeterProvider { + + var serviceName: Substring { return "models.Greeter" } + + func handle(method name: Substring, context: CallHandlerContext) -> GRPCServerHandlerProtocol? { + switch name { + case "SayHello": + return UnaryServerHandler( + context: context, + requestDeserializer: GRPCPayloadDeserializer>(), + responseSerializer: GRPCPayloadSerializer>(), + interceptors: self.interceptors?.makeSayHelloInterceptors() ?? [], + userFunction: self.SayHello(request:context:)) + + case "SayManyHellos": + return ServerStreamingServerHandler( + context: context, + requestDeserializer: GRPCPayloadDeserializer>(), + responseSerializer: GRPCPayloadSerializer>(), + interceptors: self.interceptors?.makeSayManyHellosInterceptors() ?? [], + userFunction: self.SayManyHellos(request:context:)) + + default: return nil; + } + } + +} + +public protocol models_GreeterServerInterceptorFactoryProtocol { + /// - Returns: Interceptors to use when handling 'SayHello'. + /// Defaults to calling `self.makeInterceptors()`. + func makeSayHelloInterceptors() -> [ServerInterceptor, Message>] + + /// - Returns: Interceptors to use when handling 'SayManyHellos'. + /// Defaults to calling `self.makeInterceptors()`. + func makeSayManyHellosInterceptors() -> [ServerInterceptor, Message>] + +} +#endif + diff --git a/grpc/examples/swift/Greeter/Sources/Model/greeter_generated.swift b/grpc/examples/swift/Greeter/Sources/Model/greeter_generated.swift new file mode 100644 index 000000000..a82e4e858 --- /dev/null +++ b/grpc/examples/swift/Greeter/Sources/Model/greeter_generated.swift @@ -0,0 +1,104 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// swiftlint:disable all +// swiftformat:disable all + +#if canImport(Common) +import Common +#endif + +import FlatBuffers + +public struct models_HelloReply: FlatBufferTable, FlatbuffersVectorInitializable, Verifiable { + + static func validateVersion() { FlatBuffersVersion_25_12_19() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Table + + private init(_ t: Table) { _accessor = t } + public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } + + private enum VTOFFSET: VOffset { + case message = 4 + var v: Int32 { Int32(self.rawValue) } + var p: VOffset { self.rawValue } + } + + public var message: String? { let o = _accessor.offset(VTOFFSET.message.v); return o == 0 ? nil : _accessor.string(at: o) } + public var messageSegmentArray: [UInt8]? { return _accessor.getVector(at: VTOFFSET.message.v) } + public static func startHelloReply(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) } + public static func add(message: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: message, at: VTOFFSET.message.p) } + public static func endHelloReply(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } + public static func createHelloReply( + _ fbb: inout FlatBufferBuilder, + messageOffset message: Offset = Offset() + ) -> Offset { + let __start = models_HelloReply.startHelloReply(&fbb) + models_HelloReply.add(message: message, &fbb) + return models_HelloReply.endHelloReply(&fbb, start: __start) + } + + public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { + var _v = try verifier.visitTable(at: position) + try _v.visit(field: VTOFFSET.message.p, fieldName: "message", required: false, type: ForwardOffset.self) + _v.finish() + } +} + +extension models_HelloReply: Encodable { + + enum CodingKeys: String, CodingKey { + case message = "message" + } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(message, forKey: .message) + } +} + +public struct models_HelloRequest: FlatBufferTable, FlatbuffersVectorInitializable, Verifiable { + + static func validateVersion() { FlatBuffersVersion_25_12_19() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Table + + private init(_ t: Table) { _accessor = t } + public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } + + private enum VTOFFSET: VOffset { + case name = 4 + var v: Int32 { Int32(self.rawValue) } + var p: VOffset { self.rawValue } + } + + public var name: String? { let o = _accessor.offset(VTOFFSET.name.v); return o == 0 ? nil : _accessor.string(at: o) } + public var nameSegmentArray: [UInt8]? { return _accessor.getVector(at: VTOFFSET.name.v) } + public static func startHelloRequest(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) } + public static func add(name: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: name, at: VTOFFSET.name.p) } + public static func endHelloRequest(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } + public static func createHelloRequest( + _ fbb: inout FlatBufferBuilder, + nameOffset name: Offset = Offset() + ) -> Offset { + let __start = models_HelloRequest.startHelloRequest(&fbb) + models_HelloRequest.add(name: name, &fbb) + return models_HelloRequest.endHelloRequest(&fbb, start: __start) + } + + public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { + var _v = try verifier.visitTable(at: position) + try _v.visit(field: VTOFFSET.name.p, fieldName: "name", required: false, type: ForwardOffset.self) + _v.finish() + } +} + +extension models_HelloRequest: Encodable { + + enum CodingKeys: String, CodingKey { + case name = "name" + } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(name, forKey: .name) + } +} + diff --git a/grpc/examples/swift/Greeter/Sources/client/main.swift b/grpc/examples/swift/Greeter/Sources/client/main.swift new file mode 100644 index 000000000..345a0558f --- /dev/null +++ b/grpc/examples/swift/Greeter/Sources/client/main.swift @@ -0,0 +1,108 @@ +/* + * Copyright 2024 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import FlatBuffers +import GRPC +import Logging +import Model +import NIO + +// Quieten the logs. +LoggingSystem.bootstrap { + var handler = StreamLogHandler.standardOutput(label: $0) + handler.logLevel = .critical + return handler +} + +func greet(name: String, client greeter: models_GreeterServiceClient) { + // Form the request with the name, if one was provided. + var builder = FlatBufferBuilder() + let nameOff = builder.create(string: name) + let root = models_HelloRequest.createHelloRequest( + &builder, + nameOffset: nameOff) + builder.finish(offset: root) + + // Make the RPC call to the server. + let sayHello = + greeter + .SayHello(Message(builder: &builder)) + + // wait() on the response to stop the program from exiting before the response is received. + do { + let response = try sayHello.response.wait() + print("Greeter SayHello received: \(response.object.message ?? "Unknown")") + } catch { + print("Greeter failed: \(error)") + } + + let surname = builder.create(string: name) + let manyRoot = models_HelloRequest.createHelloRequest( + &builder, + nameOffset: surname) + builder.finish(offset: manyRoot) + + let call = greeter.SayManyHellos(Message(builder: &builder)) { message in + print( + "Greeter SayManyHellos received: \(message.object.message ?? "Unknown")") + } + + let status = try! call.status.recover { _ in .processingError }.wait() + if status.code != .ok { + print("RPC failed: \(status)") + } +} + +func main(args: [String]) { + // arg0 (dropped) is the program name. We expect arg1 to be the port, and arg2 (optional) to be + // the name sent in the request. + let arg1 = args.dropFirst(1).first + let arg2 = args.dropFirst(2).first + + switch (arg1.flatMap(Int.init), arg2) { + case (.none, _): + print("Usage: PORT [NAME]") + exit(1) + + case (.some(let port), let name): + // Setup an `EventLoopGroup` for the connection to run on. + // + // See: https://github.com/apple/swift-nio#eventloops-and-eventloopgroups + let group = MultiThreadedEventLoopGroup(numberOfThreads: 1) + + // Make sure the group is shutdown when we're done with it. + defer { + try! group.syncShutdownGracefully() + } + + // Configure the channel, we're not using TLS so the connection is `insecure`. + let channel = ClientConnection.insecure(group: group) + .connect(host: "localhost", port: port) + + // Close the connection when we're done with it. + defer { + try! channel.close().wait() + } + + // Provide the connection to the generated client. + let greeter = models_GreeterServiceClient(channel: channel) + + // Do the greeting. + greet(name: name ?? "FlatBuffers!", client: greeter) + } +} + +main(args: CommandLine.arguments) diff --git a/grpc/examples/swift/Greeter/Sources/server/main.swift b/grpc/examples/swift/Greeter/Sources/server/main.swift new file mode 100644 index 000000000..27255e8c9 --- /dev/null +++ b/grpc/examples/swift/Greeter/Sources/server/main.swift @@ -0,0 +1,97 @@ +/* + * Copyright 2024 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import FlatBuffers +import GRPC +import Logging +import Model +import NIO + +class Greeter: models_GreeterProvider { + + var interceptors: models_GreeterServerInterceptorFactoryProtocol? + + let greetings: [String] + + init() { + greetings = ["Hi", "Hallo", "Ciao"] + } + + func SayHello( + request: Message, + context: StatusOnlyCallContext) + -> EventLoopFuture> + { + let recipient = request.object.name ?? "Stranger" + + var builder = FlatBufferBuilder() + let off = builder.create(string: "Hello \(recipient)") + let root = models_HelloReply.createHelloReply(&builder, messageOffset: off) + builder.finish(offset: root) + return context.eventLoop + .makeSucceededFuture(Message(builder: &builder)) + } + + func SayManyHellos( + request: Message, + context: StreamingResponseCallContext>) + -> EventLoopFuture + { + for name in greetings { + var builder = FlatBufferBuilder() + let off = + builder + .create(string: "\(name) \(request.object.name ?? "Unknown")") + let root = models_HelloReply.createHelloReply( + &builder, + messageOffset: off) + builder.finish(offset: root) + _ = context.sendResponse(Message(builder: &builder)) + } + return context.eventLoop.makeSucceededFuture(.ok) + } +} + +// Quieten the logs. +LoggingSystem.bootstrap { + var handler = StreamLogHandler.standardOutput(label: $0) + handler.logLevel = .critical + return handler +} + +let group = MultiThreadedEventLoopGroup(numberOfThreads: 1) +defer { + try! group.syncShutdownGracefully() +} + +// Create some configuration for the server: +let configuration = Server.Configuration( + target: .hostAndPort("localhost", 0), + eventLoopGroup: group, + serviceProviders: [Greeter()]) + +// Start the server and print its address once it has started. +let server = Server.start(configuration: configuration) +server.map { + $0.channel.localAddress +}.whenSuccess { address in + print("server started on port \(address!.port!)") +} + +// Wait on the server's `onClose` future to stop the program from exiting. +_ = try server.flatMap { + $0.onClose +}.wait() diff --git a/grpc/src/compiler/python_generator.cc b/grpc/src/compiler/python_generator.cc index bbd1bd5f1..7e5026635 100644 --- a/grpc/src/compiler/python_generator.cc +++ b/grpc/src/compiler/python_generator.cc @@ -172,7 +172,6 @@ class StubGenerator : public BaseGenerator { << " def __init__(self, channel: grpc.Channel) -> None: ...\n"; for (const RPCCall* method : service->calls.vec) { - imports->Import("typing"); std::string request = "bytes"; std::string response = "bytes"; @@ -184,22 +183,14 @@ class StubGenerator : public BaseGenerator { imports->Import(ModuleFor(method->response), response); } - ss << " def " << method->name << "(\n"; - ss << " self,\n"; + ss << " def " << method->name << "(self, "; if (ClientStreaming(method)) { - ss << " request_iterator: typing.Iterator[" << request << "]\n"; + imports->Import("typing"); + ss << "request_iterator: typing.Iterator[" << request << "]"; } else { - ss << " request: " << request << ",\n"; + ss << "request: " << request; } - - ss << " timeout: float | None = None,\n"; - // https://github.com/python/typeshed/blob/ccf9411fb1f5bee2a8e3d278889de17a08f7bbe3/stubs/grpcio/grpc/__init__.pyi#L37 - ss << " metadata: typing.Sequence[tuple[str, typing.Union[str, bytes]]] | None = None,\n"; - ss << " credentials: grpc.CallCredentials | None = None,\n"; - ss << " wait_for_ready: bool | None = None,\n"; - ss << " compression: grpc.Compression | None = None\n"; - - ss << " ) -> "; + ss << ") -> "; if (ServerStreaming(method)) { imports->Import("typing"); ss << "typing.Iterator[" << response << "]"; diff --git a/grpc/src/compiler/swift_generator.cc b/grpc/src/compiler/swift_generator.cc index 68c6a204c..b74141539 100644 --- a/grpc/src/compiler/swift_generator.cc +++ b/grpc/src/compiler/swift_generator.cc @@ -31,903 +31,349 @@ namespace grpc_swift_generator { namespace { -static std::string ServerResponse() { return "GRPCCore.ServerResponse"; } - -static std::string ServerRequest() { return "GRPCCore.ServerRequest"; } - -static std::string StreamingServerRequest() { - return "GRPCCore.StreamingServerRequest"; -} - -static std::string StreamingServerResponse() { - return "GRPCCore.StreamingServerResponse"; -} - -static std::string QualifiedName(const std::vector& components, - const grpc::string& name, - const std::string& separator = "_") { +static std::string WrapInNameSpace(const std::vector& components, + const grpc::string& name) { std::string qualified_name; for (auto it = components.begin(); it != components.end(); ++it) - qualified_name += *it + separator; + qualified_name += *it + "_"; return qualified_name + name; } -static std::string GenerateGRPCMessage(const std::string& name) { - return "GRPCMessage<" + name + ">"; +static grpc::string GenerateMessage(const std::vector& components, + const grpc::string& name) { + return "Message<" + WrapInNameSpace(components, name) + ">"; } -static std::string GenerateType(const std::string& name, - const std::string& wrapper) { - return wrapper + "<" + GenerateGRPCMessage(name) + ">"; -} +// MARK: - Client -static std::string GenerateInputMethodTypes( - const grpc_generator::Method* method) { - if (method->BidiStreaming()) { - return StreamingServerRequest(); - } else if (method->ClientStreaming()) { - return StreamingServerRequest(); - } else if (method->ServerStreaming()) { - return ServerRequest(); - } else { - return ServerRequest(); +static void GenerateClientFuncName( + const grpc_generator::Method* method, grpc_generator::Printer* printer, + std::map* dictonary) { + auto vars = *dictonary; + if (method->NoStreaming()) { + printer->Print(vars, + " $GenAccess$func $MethodName$(\n" + " _ request: $Input$\n" + " , callOptions: CallOptions?$isNil$\n" + " ) -> UnaryCall<$Input$, $Output$>"); + return; } -} -static std::string GenerateOutputMethodTypes( - const grpc_generator::Method* method) { - if (method->BidiStreaming()) { - return StreamingServerResponse(); - } else if (method->ClientStreaming()) { - return ServerResponse(); - } else if (method->ServerStreaming()) { - return StreamingServerResponse(); - } else { - return ServerResponse(); + if (method->ServerStreaming()) { + printer->Print(vars, + " $GenAccess$func $MethodName$(\n" + " _ request: $Input$\n" + " , callOptions: CallOptions?$isNil$,\n" + " handler: @escaping ($Output$) -> Void\n" + " ) -> ServerStreamingCall<$Input$, $Output$>"); + return; } -} -static std::string GenerateMethodTypes(const grpc_generator::Method* method) { - if (method->BidiStreaming()) { - return "bidirectionalStreaming"; - } else if (method->ClientStreaming()) { - return "clientStreaming"; - } else if (method->ServerStreaming()) { - return "serverStreaming"; - } else { - return "unary"; + if (method->ClientStreaming()) { + printer->Print(vars, + " $GenAccess$func $MethodName$(\n" + " callOptions: CallOptions?$isNil$\n" + " ) -> ClientStreamingCall<$Input$, $Output$>"); + return; } -} -void EnforceOSVersion(grpc_generator::Printer* printer) { - printer->Print( - "@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, " - "*)\n"); -} - -void GenerateMethodDescriptor(grpc_generator::Printer* printer, - std::map* dictionary) { - auto vars = *dictionary; - printer->Print(vars, "$ACCESS$ enum $MethodName$: Sendable {\n"); - printer->Indent(); - printer->Print(vars, "$ACCESS$ typealias Input = FlatBufferBuilder\n"); - printer->Print(vars, "$ACCESS$ typealias Output = $Output$\n"); - printer->Print( - vars, "$ACCESS$ static let descriptor = GRPCCore.MethodDescriptor(\n"); - printer->Indent(); printer->Print(vars, - "service: GRPCCore.ServiceDescriptor(fullyQualifiedService: " - "\"$ServiceQualifiedName$\"),\n"); - printer->Print(vars, "method: \"$MethodName$\"\n"); - printer->Outdent(); - printer->Print(")\n"); - printer->Outdent(); - printer->Print(vars, "}\n"); + " $GenAccess$func $MethodName$(\n" + " callOptions: CallOptions?$isNil$,\n" + " handler: @escaping ($Output$ ) -> Void\n" + " ) -> BidirectionalStreamingCall<$Input$, $Output$>"); } -void GenerateCoders(grpc_generator::Printer* printer) { - EnforceOSVersion(printer); - printer->Print( - "extension FlatBuffersMessageSerializer: MessageSerializer {\n"); - printer->Indent(); - printer->Print( - "public func serialize(_ message: Message) throws -> Bytes where " - "Bytes : GRPCCore.GRPCContiguousBytes {\n"); - printer->Indent(); - printer->Print("do {\n"); - printer->Indent(); - printer->Print( - "return try self.serialize(message: message) { GRPCNIOTransportBytes($0) " - "} as! Bytes\n"); - printer->Outdent(); - printer->Print("} catch let error {\n"); - printer->Indent(); - printer->Print("throw RPCError(\n"); - printer->Indent(); - printer->Print("code: .invalidArgument,\n"); - printer->Print("message: \"Can't serialize message\",\n"); - printer->Print("cause: error\n"); - printer->Outdent(); - printer->Print(")\n"); - printer->Outdent(); - printer->Print("}\n"); - printer->Outdent(); - printer->Print("}\n"); - printer->Outdent(); - printer->Print("}\n\n"); - - EnforceOSVersion(printer); - printer->Print( - "extension FlatBuffersMessageDeserializer: MessageDeserializer {\n"); - printer->Indent(); - printer->Print( - "public func deserialize(_ serializedMessageBytes: Bytes) throws " - "-> Message where Bytes : GRPCCore.GRPCContiguousBytes {\n"); - printer->Indent(); - printer->Print("do {\n"); - printer->Indent(); - printer->Print("return try serializedMessageBytes.withUnsafeBytes {\n"); - printer->Indent(); - printer->Print("try self.deserialize(pointer: $0)\n"); - printer->Outdent(); - printer->Print("}\n"); - printer->Outdent(); - printer->Print("} catch let error {\n"); - printer->Indent(); - printer->Print("throw RPCError(\n"); - printer->Indent(); - printer->Print("code: .invalidArgument,\n"); - printer->Print( - "message: \"Can't Decode message of type \\(Message.self)\",\n"); - printer->Print("cause: error\n"); - printer->Outdent(); - printer->Print(")\n"); - printer->Outdent(); - printer->Print("}\n"); - printer->Outdent(); - printer->Print("}\n"); - printer->Outdent(); - printer->Print("}\n\n"); -} - -void GenerateSharedContent(const grpc_generator::Service* service, - grpc_generator::Printer* printer, - std::map* dictionary) { - auto vars = *dictionary; - EnforceOSVersion(printer); - printer->Print(vars, - "$ACCESS$ enum $SwiftServiceQualifiedName$: Sendable {\n"); - printer->Indent(); - printer->Print(vars, - "$ACCESS$ static let descriptor = " - "GRPCCore.ServiceDescriptor(fullyQualifiedService: " - "\"$ServiceQualifiedName$\")\n"); - printer->Print(vars, "$ACCESS$ enum Method: Sendable {\n"); - printer->Indent(); - - std::vector descriptors; - for (auto it = 0; it < service->method_count(); it++) { - auto method = service->method(it); - vars["Input"] = QualifiedName(method->get_input_namespace_parts(), - method->get_output_type_name()); - vars["Output"] = QualifiedName(method->get_output_namespace_parts(), - method->get_output_type_name()); - auto name = method->name(); - vars["MethodName"] = name; - descriptors.push_back(name); - GenerateMethodDescriptor(printer, &vars); - } - - printer->Print( - vars, - "$ACCESS$ static let descriptors: [GRPCCore.MethodDescriptor] = [\n"); - printer->Indent(); - for (auto it = descriptors.begin(); it < descriptors.end(); it++) { - vars["MethodName"] = *it; - printer->Print(vars, "$MethodName$.descriptor,\n"); - } - printer->Outdent(); - printer->Print("]\n"); - printer->Outdent(); - printer->Print("}\n"); - - printer->Outdent(); - printer->Print("}\n\n"); - - EnforceOSVersion(printer); - printer->Print("extension GRPCCore.ServiceDescriptor {\n"); - printer->Indent(); - printer->Print(vars, - "$ACCESS$ static let $SwiftServiceQualifiedName$ = " - "GRPCCore.ServiceDescriptor(fullyQualifiedService: " - "\"$ServiceQualifiedName$\")\n"); - printer->Outdent(); - printer->Print("}\n"); -} - -// Service Generation - -void GenerateFunction(grpc_generator::Printer* printer, - std::map* dictionary) { - auto vars = *dictionary; - printer->Print(vars, "func $MethodName$(\n"); - printer->Indent(); - - printer->Print(vars, "request: $Input$,\n"); - printer->Print("context: GRPCCore.ServerContext\n"); - - printer->Outdent(); - printer->Print(vars, ") async throws -> $Output$\n\n"); -} - -void GenerateServiceProtocols(const grpc_generator::Service* service, - grpc_generator::Printer* printer, - std::map* dictionary) { - auto vars = *dictionary; - EnforceOSVersion(printer); - printer->Print(vars, "extension $SwiftServiceQualifiedName$ {\n"); - printer->Indent(); - // Base protocol - printer->Print(vars, - "$ACCESS$ protocol StreamingServiceProtocol: " - "GRPCCore.RegistrableRPCService {\n"); - printer->Indent(); - - for (auto it = 0; it < service->method_count(); it++) { - auto method = service->method(it); - vars["Input"] = - GenerateType(QualifiedName(method->get_input_namespace_parts(), - method->get_output_type_name()), - StreamingServerRequest()); - - vars["Output"] = - GenerateType(QualifiedName(method->get_input_namespace_parts(), - method->get_output_type_name()), - StreamingServerResponse()); - auto name = method->name(); - vars["MethodName"] = name; - GenerateFunction(printer, &vars); - } - printer->Outdent(); - printer->Print("}\n\n"); - - // Service - printer->Print(vars, - "$ACCESS$ protocol ServiceProtocol: " - "$SwiftServiceQualifiedName$.StreamingServiceProtocol {\n"); - printer->Indent(); - - for (auto it = 0; it < service->method_count(); it++) { - auto method = service->method(it); - - vars["Input"] = - GenerateType(QualifiedName(method->get_input_namespace_parts(), - method->get_output_type_name()), - GenerateInputMethodTypes(&*method)); - - vars["Output"] = - GenerateType(QualifiedName(method->get_input_namespace_parts(), - method->get_output_type_name()), - GenerateOutputMethodTypes(&*method)); - auto name = method->name(); - vars["MethodName"] = name; - GenerateFunction(printer, &vars); - } - - printer->Outdent(); - printer->Print("}\n\n"); - - // Simple service - printer->Print(vars, - "$ACCESS$ protocol SimpleServiceProtocol: " - "$SwiftServiceQualifiedName$.ServiceProtocol {\n"); - printer->Indent(); - - for (auto it = 0; it < service->method_count(); it++) { - auto method = service->method(it); - - vars["Input"] = GenerateGRPCMessage(QualifiedName( - method->get_input_namespace_parts(), method->get_output_type_name())); - - vars["Output"] = GenerateGRPCMessage(QualifiedName( - method->get_input_namespace_parts(), method->get_output_type_name())); - auto name = method->name(); - vars["MethodName"] = name; - - printer->Print(vars, "func $MethodName$(\n"); - printer->Indent(); - - if (method->ClientStreaming() || method->BidiStreaming()) { - printer->Print( - vars, - "request: GRPCCore.RPCAsyncSequence<$Input$, any Swift.Error>,\n"); - } else { - printer->Print(vars, "request: $Input$,\n"); - } - - if (method->BidiStreaming() || method->ServerStreaming()) { - printer->Print(vars, "response: GRPCCore.RPCWriter<$Output$>,\n"); - } - printer->Print("context: GRPCCore.ServerContext\n"); - - printer->Outdent(); - - if (!method->BidiStreaming() && !method->ServerStreaming()) { - printer->Print(vars, ") async throws -> $Output$\n\n"); - } else { - printer->Print(") async throws\n\n"); - } - } - - printer->Outdent(); - printer->Print("}\n"); - - printer->Outdent(); - printer->Print("}\n\n"); - - EnforceOSVersion(printer); - printer->Print( - vars, - "extension $SwiftServiceQualifiedName$.StreamingServiceProtocol {\n"); - printer->Indent(); - printer->Print( - "public func registerMethods(with router: inout " - "GRPCCore.RPCRouter) where Transport: " - "GRPCCore.ServerTransport {\n"); - printer->Indent(); - - for (auto it = 0; it < service->method_count(); it++) { - auto method = service->method(it); - vars["Input"] = - GenerateType(QualifiedName(method->get_input_namespace_parts(), - method->get_output_type_name()), - "FlatBuffersMessageSerializer"); - - vars["Output"] = - GenerateType(QualifiedName(method->get_input_namespace_parts(), - method->get_output_type_name()), - "FlatBuffersMessageDeserializer"); - - auto name = method->name(); - vars["MethodName"] = name; - - printer->Print("router.registerHandler(\n"); - printer->Indent(); +static void GenerateClientFuncBody( + const grpc_generator::Method* method, grpc_generator::Printer* printer, + std::map* dictonary) { + auto vars = *dictonary; + vars["Interceptor"] = + "interceptors: self.interceptors?.make$MethodName$Interceptors() ?? []"; + if (method->NoStreaming()) { printer->Print( vars, - "forMethod: " - "$SwiftServiceQualifiedName$.Method.$MethodName$.descriptor,\n"); - printer->Print(vars, "deserializer: $Output$(),\n"); - printer->Print(vars, "serializer: $Input$(),\n"); - printer->Print("handler: { request, context in\n"); - printer->Indent(); - printer->Print(vars, "try await self.$MethodName$(\n"); - printer->Indent(); - printer->Print("request: request,\n"); - printer->Print("context: context\n"); - printer->Outdent(); - printer->Print(")\n"); - printer->Outdent(); - printer->Print("}\n"); - printer->Outdent(); - printer->Print(")\n"); + " return self.makeUnaryCall(\n" + " path: \"/$PATH$$ServiceName$/$MethodName$\",\n" + " request: request,\n" + " callOptions: callOptions ?? self.defaultCallOptions,\n" + " $Interceptor$\n" + " )\n"); + return; } - printer->Outdent(); - printer->Print("}\n"); - printer->Outdent(); - printer->Print("}\n\n"); -} - -void CreateServiceProtocolFunctionsImplementations( - grpc_generator::Printer* printer, - std::map* dictionary) { - auto vars = *dictionary; - printer->Print(vars, "$ACCESS$ func $MethodName$(\n"); - printer->Indent(); - printer->Print(vars, "request: $Input$,\n"); - printer->Print("context: GRPCCore.ServerContext\n"); - printer->Outdent(); - printer->Print(vars, ") async throws -> $Output$ {\n"); - printer->Indent(); - printer->Print(vars, "let response = try await self.$MethodName$(\n"); - printer->Indent(); - printer->Print(vars, "request: $InputRequest$,\n"); - printer->Print("context: context\n"); - printer->Outdent(); - printer->Print(")\n"); - printer->Print(vars, "return $OutputResponse$\n"); - printer->Outdent(); - printer->Print("}\n"); -} - -std::string GenerateInputRequest(const grpc_generator::Method* method) { - if (method->NoStreaming() || method->ServerStreaming()) - return ServerRequest() + "(stream: request)"; - return "request"; -} - -std::string GenerateOutputResponse(const grpc_generator::Method* method) { - if (method->NoStreaming() || method->ClientStreaming()) - return StreamingServerResponse() + "(single: response)"; - return "response"; -} - -void GenerateServiceDefaultImplementation( - const grpc_generator::Service* service, grpc_generator::Printer* printer, - std::map* dictionary) { - auto vars = *dictionary; - EnforceOSVersion(printer); - printer->Print(vars, - "extension $SwiftServiceQualifiedName$.ServiceProtocol {\n"); - printer->Indent(); - - for (auto it = 0; it < service->method_count(); it++) { - auto method = service->method(it); - if (method->BidiStreaming()) { - continue; - } - - vars["Input"] = - GenerateType(QualifiedName(method->get_input_namespace_parts(), - method->get_output_type_name()), - StreamingServerRequest()); - - vars["Output"] = - GenerateType(QualifiedName(method->get_input_namespace_parts(), - method->get_output_type_name()), - StreamingServerResponse()); - auto name = method->name(); - vars["MethodName"] = name; - - vars["InputRequest"] = GenerateInputRequest(&*method); - vars["OutputResponse"] = GenerateOutputResponse(&*method); - - CreateServiceProtocolFunctionsImplementations(printer, &vars); - } - printer->Outdent(); - printer->Print("}\n\n"); -} - -void GenerateSimpleServiceImplemetation( - const grpc_generator::Service* service, grpc_generator::Printer* printer, - std::map* dictionary) { - auto vars = *dictionary; - EnforceOSVersion(printer); - printer->Print( - vars, "extension $SwiftServiceQualifiedName$.SimpleServiceProtocol {\n"); - printer->Indent(); - - for (auto it = 0; it < service->method_count(); it++) { - auto method = service->method(it); - - vars["Input"] = - GenerateType(QualifiedName(method->get_input_namespace_parts(), - method->get_output_type_name()), - GenerateInputMethodTypes(&*method)); - - vars["Output"] = - GenerateType(QualifiedName(method->get_input_namespace_parts(), - method->get_output_type_name()), - GenerateOutputMethodTypes(&*method)); - auto name = method->name(); - vars["MethodName"] = name; - - printer->Print(vars, "$ACCESS$ func $MethodName$(\n"); - printer->Indent(); - printer->Print(vars, "request: $Input$,\n"); - printer->Print("context: GRPCCore.ServerContext\n"); - printer->Outdent(); - printer->Print(vars, ") async throws -> $Output$ {\n"); - printer->Indent(); - printer->Print(vars, "return $Output$(\n"); - printer->Indent(); - - if (method->NoStreaming() || method->ClientStreaming()) { - vars["Message"] = method->ClientStreaming() ? "messages" : "message"; - printer->Print(vars, "message: try await self.$MethodName$(\n"); - printer->Indent(); - printer->Print(vars, "request: request.$Message$,\n"); - printer->Print("context: context\n"); - printer->Outdent(); - printer->Print(vars, "),\n"); - printer->Print(vars, "metadata: [:]\n"); - } else { - vars["Message"] = method->BidiStreaming() ? "messages" : "message"; - printer->Print(vars, "metadata: [:],\n"); - printer->Print(vars, "producer: { writer in\n"); - printer->Indent(); - printer->Print(vars, "try await self.$MethodName$(\n"); - printer->Indent(); - printer->Print(vars, "request: request.$Message$,\n"); - printer->Print("response: writer,\n"); - printer->Print("context: context\n"); - printer->Outdent(); - printer->Print(")\n"); - printer->Print("return [:]\n"); - printer->Outdent(); - printer->Print(vars, "}\n"); - } - - printer->Outdent(); - printer->Print(")\n"); - printer->Outdent(); - printer->Print("}\n"); - } - printer->Outdent(); - printer->Print("}\n\n"); -} - -void GenerateService(const grpc_generator::Service* service, - grpc_generator::Printer* printer, - std::map* dictionary) { - GenerateServiceProtocols(service, printer, dictionary); - GenerateServiceDefaultImplementation(service, printer, dictionary); - GenerateSimpleServiceImplemetation(service, printer, dictionary); -} - -// Client Generation - -void GenerateClientProtocols(const grpc_generator::Service* service, - grpc_generator::Printer* printer, - std::map* dictionary) { - auto vars = *dictionary; - EnforceOSVersion(printer); - printer->Print(vars, "extension $SwiftServiceQualifiedName$ {\n"); - printer->Indent(); - // Base protocol - printer->Print(vars, "$ACCESS$ protocol ClientProtocol: Sendable {\n"); - printer->Indent(); - - for (auto it = 0; it < service->method_count(); it++) { - auto method = service->method(it); - auto name = method->name(); - vars["MethodName"] = name; - - vars["serializer"] = - GenerateType(QualifiedName(method->get_input_namespace_parts(), - method->get_output_type_name()), - "GRPCCore.MessageSerializer"); - - vars["deserializer"] = - GenerateType(QualifiedName(method->get_input_namespace_parts(), - method->get_output_type_name()), - "GRPCCore.MessageDeserializer"); - - if (method->ClientStreaming() || method->BidiStreaming()) { - vars["request"] = - GenerateType(QualifiedName(method->get_input_namespace_parts(), - method->get_output_type_name()), - "GRPCCore.StreamingClientRequest"); - } else { - vars["request"] = - GenerateType(QualifiedName(method->get_input_namespace_parts(), - method->get_output_type_name()), - "GRPCCore.ClientRequest"); - } - - if (method->ServerStreaming() || method->BidiStreaming()) { - vars["response"] = - GenerateType(QualifiedName(method->get_input_namespace_parts(), - method->get_output_type_name()), - "GRPCCore.StreamingClientResponse"); - } else { - vars["response"] = - GenerateType(QualifiedName(method->get_input_namespace_parts(), - method->get_output_type_name()), - "GRPCCore.ClientResponse"); - } - - printer->Print(vars, "func $MethodName$(\n"); - printer->Indent(); - printer->Print(vars, "request: $request$,\n"); - printer->Print(vars, "serializer: some $serializer$,\n"); - printer->Print(vars, "deserializer: some $deserializer$,\n"); - printer->Print("options: GRPCCore.CallOptions,\n"); - printer->Print(vars, - "onResponse handleResponse: @Sendable @escaping " - "($response$) async throws -> Result\n"); - printer->Outdent(); - printer->Print(") async throws -> Result where Result: Sendable\n\n"); - } - - printer->Outdent(); - printer->Print("}\n"); - printer->Outdent(); - printer->Print("}\n\n"); -} - -void GenerateClientStruct(const grpc_generator::Service* service, - grpc_generator::Printer* printer, - std::map* dictionary) { - auto vars = *dictionary; - EnforceOSVersion(printer); - printer->Print(vars, "extension $SwiftServiceQualifiedName$ {\n"); - printer->Indent(); - // Base protocol - printer->Print(vars, - "$ACCESS$ struct Client: ClientProtocol where " - "Transport: GRPCCore.ClientTransport {\n"); - printer->Indent(); - printer->Print("private let client: GRPCCore.GRPCClient\n\n"); - printer->Print( - vars, - "$ACCESS$ init(wrapping client: GRPCCore.GRPCClient) {\n"); - printer->Indent(); - printer->Print("self.client = client\n"); - printer->Outdent(); - printer->Print("}\n\n"); - - for (auto it = 0; it < service->method_count(); it++) { - auto method = service->method(it); - auto name = method->name(); - vars["MethodType"] = GenerateMethodTypes(&*method); - vars["MethodName"] = name; - - vars["serializer"] = - GenerateType(QualifiedName(method->get_input_namespace_parts(), - method->get_output_type_name()), - "GRPCCore.MessageSerializer"); - - vars["deserializer"] = - GenerateType(QualifiedName(method->get_input_namespace_parts(), - method->get_output_type_name()), - "GRPCCore.MessageDeserializer"); - - if (method->ClientStreaming() || method->BidiStreaming()) { - vars["request"] = - GenerateType(QualifiedName(method->get_input_namespace_parts(), - method->get_output_type_name()), - "GRPCCore.StreamingClientRequest"); - } else { - vars["request"] = - GenerateType(QualifiedName(method->get_input_namespace_parts(), - method->get_output_type_name()), - "GRPCCore.ClientRequest"); - } - - if (method->ServerStreaming() || method->BidiStreaming()) { - vars["response"] = - GenerateType(QualifiedName(method->get_input_namespace_parts(), - method->get_output_type_name()), - "GRPCCore.StreamingClientResponse"); - vars["CompletionBlock"] = ""; - } else { - vars["response"] = - GenerateType(QualifiedName(method->get_input_namespace_parts(), - method->get_output_type_name()), - "GRPCCore.ClientResponse"); - vars["CompletionBlock"] = " = { response in try response.message }"; - } - - printer->Print(vars, "$ACCESS$ func $MethodName$(\n"); - printer->Indent(); - printer->Print(vars, "request: $request$,\n"); - printer->Print(vars, "serializer: some $serializer$,\n"); - printer->Print(vars, "deserializer: some $deserializer$,\n"); - printer->Print("options: GRPCCore.CallOptions = .defaults,\n"); - printer->Print(vars, - "onResponse handleResponse: @Sendable @escaping " - "($response$) async throws -> Result$CompletionBlock$\n"); - printer->Outdent(); - printer->Print(") async throws -> Result where Result: Sendable {\n"); - printer->Indent(); - printer->Print(vars, "try await self.client.$MethodType$(\n"); - printer->Indent(); - printer->Print("request: request,\n"); + if (method->ServerStreaming()) { printer->Print( vars, - "descriptor: " - "$SwiftServiceQualifiedName$.Method.$MethodName$.descriptor,\n"); - printer->Print("serializer: serializer,\n"); - printer->Print("deserializer: deserializer,\n"); - printer->Print("options: options,\n"); - printer->Print("onResponse: handleResponse\n"); - printer->Outdent(); - printer->Print(")\n"); - printer->Outdent(); - printer->Print("}\n\n"); + " return self.makeServerStreamingCall(\n" + " path: \"/$PATH$$ServiceName$/$MethodName$\",\n" + " request: request,\n" + " callOptions: callOptions ?? self.defaultCallOptions,\n" + " $Interceptor$,\n" + " handler: handler\n" + " )\n"); + return; } - printer->Outdent(); - printer->Print("}\n"); - printer->Outdent(); - printer->Print("}\n\n"); + if (method->ClientStreaming()) { + printer->Print( + vars, + " return self.makeClientStreamingCall(\n" + " path: \"/$PATH$$ServiceName$/$MethodName$\",\n" + " callOptions: callOptions ?? self.defaultCallOptions,\n" + " $Interceptor$\n" + " )\n"); + return; + } + printer->Print(vars, + " return self.makeBidirectionalStreamingCall(\n" + " path: \"/$PATH$$ServiceName$/$MethodName$\",\n" + " callOptions: callOptions ?? self.defaultCallOptions,\n" + " $Interceptor$,\n" + " handler: handler\n" + " )\n"); } -void GenerateClientDefaultImplementation( - const grpc_generator::Service* service, grpc_generator::Printer* printer, - std::map* dictionary) { - auto vars = *dictionary; - EnforceOSVersion(printer); +void GenerateClientProtocol(const grpc_generator::Service* service, + grpc_generator::Printer* printer, + std::map* dictonary) { + auto vars = *dictonary; + printer->Print( + vars, + "$ACCESS$ protocol $ServiceQualifiedName$ClientProtocol: GRPCClient {"); + printer->Print("\n\n"); + printer->Print(" var serviceName: String { get }"); + printer->Print("\n\n"); + printer->Print( + vars, + " var interceptors: " + "$ServiceQualifiedName$ClientInterceptorFactoryProtocol? { get }"); + printer->Print("\n\n"); + + vars["GenAccess"] = ""; + for (auto it = 0; it < service->method_count(); it++) { + auto method = service->method(it); + vars["Input"] = GenerateMessage(method->get_input_namespace_parts(), + method->get_input_type_name()); + vars["Output"] = GenerateMessage(method->get_output_namespace_parts(), + method->get_output_type_name()); + vars["MethodName"] = method->name(); + vars["isNil"] = ""; + GenerateClientFuncName(method.get(), &*printer, &vars); + printer->Print("\n\n"); + } + printer->Print("}\n\n"); + + printer->Print(vars, "extension $ServiceQualifiedName$ClientProtocol {"); + printer->Print("\n\n"); printer->Print(vars, - "extension $SwiftServiceQualifiedName$.ClientProtocol {\n"); - printer->Indent(); + " $ACCESS$ var serviceName: String { " + "\"$PATH$$ServiceName$\" }\n"); + + vars["GenAccess"] = service->is_internal() ? "internal " : "public "; + for (auto it = 0; it < service->method_count(); it++) { + auto method = service->method(it); + vars["Input"] = GenerateMessage(method->get_input_namespace_parts(), + method->get_input_type_name()); + vars["Output"] = GenerateMessage(method->get_output_namespace_parts(), + method->get_output_type_name()); + vars["MethodName"] = method->name(); + vars["isNil"] = " = nil"; + printer->Print("\n"); + GenerateClientFuncName(method.get(), &*printer, &vars); + printer->Print(" {\n"); + GenerateClientFuncBody(method.get(), &*printer, &vars); + printer->Print(" }\n"); + } + printer->Print("}\n\n"); + + printer->Print(vars, + "$ACCESS$ protocol " + "$ServiceQualifiedName$ClientInterceptorFactoryProtocol {\n"); for (auto it = 0; it < service->method_count(); it++) { auto method = service->method(it); - auto name = method->name(); - vars["MethodName"] = name; - - vars["serializer"] = - GenerateType(QualifiedName(method->get_input_namespace_parts(), - method->get_output_type_name()), - "FlatBuffersMessageSerializer"); - - vars["deserializer"] = - GenerateType(QualifiedName(method->get_input_namespace_parts(), - method->get_output_type_name()), - "FlatBuffersMessageDeserializer"); - - if (method->ClientStreaming() || method->BidiStreaming()) { - vars["request"] = - GenerateType(QualifiedName(method->get_input_namespace_parts(), - method->get_output_type_name()), - "GRPCCore.StreamingClientRequest"); - } else { - vars["request"] = - GenerateType(QualifiedName(method->get_input_namespace_parts(), - method->get_output_type_name()), - "GRPCCore.ClientRequest"); - } - - if (method->ServerStreaming() || method->BidiStreaming()) { - vars["response"] = - GenerateType(QualifiedName(method->get_input_namespace_parts(), - method->get_output_type_name()), - "GRPCCore.StreamingClientResponse"); - vars["CompletionBlock"] = ""; - } else { - vars["response"] = - GenerateType(QualifiedName(method->get_input_namespace_parts(), - method->get_output_type_name()), - "GRPCCore.ClientResponse"); - vars["CompletionBlock"] = " = { response in try response.message }"; - } - - printer->Print(vars, "$ACCESS$ func $MethodName$(\n"); - printer->Indent(); - printer->Print(vars, "request: $request$,\n"); - printer->Print("options: GRPCCore.CallOptions = .defaults,\n"); + vars["Input"] = GenerateMessage(method->get_input_namespace_parts(), + method->get_input_type_name()); + vars["Output"] = GenerateMessage(method->get_output_namespace_parts(), + method->get_output_type_name()); + vars["MethodName"] = method->name(); + printer->Print( + vars, + " /// - Returns: Interceptors to use when invoking '$MethodName$'.\n"); printer->Print(vars, - "onResponse handleResponse: @Sendable @escaping " - "($response$) async throws -> Result$CompletionBlock$\n"); - printer->Outdent(); - printer->Print(") async throws -> Result where Result: Sendable {\n"); - printer->Indent(); - printer->Print(vars, "try await self.$MethodName$(\n"); - printer->Indent(); - printer->Print("request: request,\n"); - printer->Print(vars, "serializer: $serializer$(),\n"); - printer->Print(vars, "deserializer: $deserializer$(),\n"); - printer->Print("options: options,\n"); - printer->Print("onResponse: handleResponse\n"); - printer->Outdent(); - printer->Print(")\n"); - printer->Outdent(); - printer->Print("}\n\n"); + " func make$MethodName$Interceptors() -> " + "[ClientInterceptor<$Input$, $Output$>]\n\n"); } - - printer->Outdent(); printer->Print("}\n\n"); } -void GenerateClientHelperMethods( - const grpc_generator::Service* service, grpc_generator::Printer* printer, - std::map* dictionary) { - auto vars = *dictionary; - - EnforceOSVersion(printer); +void GenerateClientClass(grpc_generator::Printer* printer, + std::map* dictonary) { + auto vars = *dictonary; printer->Print(vars, - "extension $SwiftServiceQualifiedName$.ClientProtocol {\n"); - printer->Indent(); + "$ACCESS$ final class $ServiceQualifiedName$ServiceClient: " + "$ServiceQualifiedName$ClientProtocol {\n"); + printer->Print(vars, " $ACCESS$ let channel: GRPCChannel\n"); + printer->Print(vars, " $ACCESS$ var defaultCallOptions: CallOptions\n"); + printer->Print(vars, + " $ACCESS$ var interceptors: " + "$ServiceQualifiedName$ClientInterceptorFactoryProtocol?\n"); + printer->Print("\n"); + printer->Print( + vars, + " $ACCESS$ init(\n" + " channel: GRPCChannel,\n" + " defaultCallOptions: CallOptions = CallOptions(),\n" + " interceptors: " + "$ServiceQualifiedName$ClientInterceptorFactoryProtocol? = nil\n" + " ) {\n"); + printer->Print(" self.channel = channel\n"); + printer->Print(" self.defaultCallOptions = defaultCallOptions\n"); + printer->Print(" self.interceptors = interceptors\n"); + printer->Print(" }"); + printer->Print("\n"); + printer->Print("}\n"); +} +// MARK: - Server + +grpc::string GenerateServerFuncName(const grpc_generator::Method* method) { + if (method->NoStreaming()) { + return "func $MethodName$(request: $Input$" + ", context: StatusOnlyCallContext) -> EventLoopFuture<$Output$>"; + } + + if (method->ClientStreaming()) { + return "func $MethodName$(context: UnaryResponseCallContext<$Output$>) -> " + "EventLoopFuture<(StreamEvent<$Input$" + ">) -> Void>"; + } + + if (method->ServerStreaming()) { + return "func $MethodName$(request: $Input$" + ", context: StreamingResponseCallContext<$Output$>) -> " + "EventLoopFuture"; + } + return "func $MethodName$(context: StreamingResponseCallContext<$Output$>) " + "-> EventLoopFuture<(StreamEvent<$Input$>) -> Void>"; +} + +grpc::string GenerateServerExtensionBody(const grpc_generator::Method* method) { + grpc::string start = " case \"$MethodName$\":\n "; + grpc::string interceptors = + " interceptors: self.interceptors?.make$MethodName$Interceptors() " + "?? [],\n"; + if (method->NoStreaming()) { + return start + + "return UnaryServerHandler(\n" + " context: context,\n" + " requestDeserializer: GRPCPayloadDeserializer<$Input$>(),\n" + " responseSerializer: GRPCPayloadSerializer<$Output$>(),\n" + + interceptors + + " userFunction: self.$MethodName$(request:context:))\n"; + } + if (method->ServerStreaming()) { + return start + + "return ServerStreamingServerHandler(\n" + " context: context,\n" + " requestDeserializer: GRPCPayloadDeserializer<$Input$>(),\n" + " responseSerializer: GRPCPayloadSerializer<$Output$>(),\n" + + interceptors + + " userFunction: self.$MethodName$(request:context:))\n"; + } + if (method->ClientStreaming()) { + return start + + "return ClientStreamingServerHandler(\n" + " context: context,\n" + " requestDeserializer: GRPCPayloadDeserializer<$Input$>(),\n" + " responseSerializer: GRPCPayloadSerializer<$Output$>(),\n" + + interceptors + + " observerFactory: self.$MethodName$(context:))\n"; + } + if (method->BidiStreaming()) { + return start + + "return BidirectionalStreamingServerHandler(\n" + " context: context,\n" + " requestDeserializer: GRPCPayloadDeserializer<$Input$>(),\n" + " responseSerializer: GRPCPayloadSerializer<$Output$>(),\n" + + interceptors + + " observerFactory: self.$MethodName$(context:))\n"; + } + return ""; +} + +void GenerateServerProtocol(const grpc_generator::Service* service, + grpc_generator::Printer* printer, + std::map* dictonary) { + auto vars = *dictonary; + printer->Print(vars, + "$ACCESS$ protocol $ServiceQualifiedName$Provider: " + "CallHandlerProvider {\n"); + printer->Print( + vars, + " var interceptors: " + "$ServiceQualifiedName$ServerInterceptorFactoryProtocol? { get }\n"); for (auto it = 0; it < service->method_count(); it++) { auto method = service->method(it); - auto name = method->name(); - vars["MethodName"] = name; - - vars["serializer"] = - GenerateType(QualifiedName(method->get_input_namespace_parts(), - method->get_output_type_name()), - "FlatBuffersMessageSerializer"); - - vars["deserializer"] = - GenerateType(QualifiedName(method->get_input_namespace_parts(), - method->get_output_type_name()), - "FlatBuffersMessageDeserializer"); - - printer->Print(vars, "$ACCESS$ func $MethodName$(\n"); - printer->Indent(); - - if (method->NoStreaming() || method->ServerStreaming()) { - vars["request"] = GenerateGRPCMessage(QualifiedName( - method->get_input_namespace_parts(), method->get_output_type_name())); - printer->Print(vars, "_ message: $request$,\n"); - } - - printer->Print("metadata: GRPCCore.Metadata = [:],\n"); - printer->Print("options: GRPCCore.CallOptions = .defaults,\n"); - - if (method->ClientStreaming() || method->BidiStreaming()) { - vars["request"] = GenerateGRPCMessage(QualifiedName( - method->get_input_namespace_parts(), method->get_output_type_name())); - printer->Print(vars, - "requestProducer producer: @Sendable @escaping " - "(GRPCCore.RPCWriter<$request$>) async throws -> Void,\n"); - } - - if (method->NoStreaming() || method->ClientStreaming()) { - vars["response"] = GenerateGRPCMessage(QualifiedName( - method->get_input_namespace_parts(), method->get_output_type_name())); - - printer->Print(vars, - "onResponse handleResponse: @Sendable @escaping " - "(GRPCCore.ClientResponse<$response$>) async throws -> " - "Result = { try $0.message }\n"); - } else { - vars["response"] = GenerateGRPCMessage(QualifiedName( - method->get_input_namespace_parts(), method->get_output_type_name())); - - printer->Print(vars, - "onResponse handleResponse: @Sendable @escaping " - "(GRPCCore.StreamingClientResponse<$response$>) async " - "throws -> Result\n"); - } - - printer->Outdent(); - printer->Print(") async throws -> Result where Result: Sendable {\n"); - printer->Indent(); - - if (method->ClientStreaming() || method->BidiStreaming()) { - vars["request"] = - GenerateType(QualifiedName(method->get_input_namespace_parts(), - method->get_output_type_name()), - "GRPCCore.StreamingClientRequest"); - } else { - vars["request"] = - GenerateType(QualifiedName(method->get_input_namespace_parts(), - method->get_output_type_name()), - "GRPCCore.ClientRequest"); - } - - printer->Print(vars, "let request = $request$(\n"); - printer->Indent(); - if (method->NoStreaming() || method->ServerStreaming()) { - printer->Print("message: message,\n"); - printer->Print("metadata: metadata\n"); - } else { - printer->Print("metadata: metadata,\n"); - printer->Print("producer: producer\n"); - } - - printer->Outdent(); - printer->Print(")\n"); - - printer->Print(vars, "return try await self.$MethodName$(\n"); - printer->Indent(); - printer->Print("request: request,\n"); - printer->Print("options: options,\n"); - printer->Print("onResponse: handleResponse\n"); - printer->Outdent(); - printer->Print(")\n"); - printer->Outdent(); - printer->Print("}\n\n"); + vars["Input"] = GenerateMessage(method->get_input_namespace_parts(), + method->get_input_type_name()); + vars["Output"] = GenerateMessage(method->get_output_namespace_parts(), + method->get_output_type_name()); + vars["MethodName"] = method->name(); + printer->Print(" "); + auto func = GenerateServerFuncName(method.get()); + printer->Print(vars, func.c_str()); + printer->Print("\n"); } - - printer->Outdent(); printer->Print("}\n\n"); -} -void GenerateClient(const grpc_generator::Service* service, - grpc_generator::Printer* printer, - std::map* dictionary) { - GenerateClientProtocols(service, printer, dictionary); - GenerateClientStruct(service, printer, dictionary); - GenerateClientDefaultImplementation(service, printer, dictionary); - GenerateClientHelperMethods(service, printer, dictionary); -} + printer->Print(vars, "$ACCESS$ extension $ServiceQualifiedName$Provider {\n"); + printer->Print("\n"); + printer->Print(vars, + " var serviceName: Substring { return " + "\"$PATH$$ServiceName$\" }\n"); + printer->Print("\n"); + printer->Print( + " func handle(method name: Substring, context: " + "CallHandlerContext) -> GRPCServerHandlerProtocol? {\n"); + printer->Print(" switch name {\n"); + for (auto it = 0; it < service->method_count(); it++) { + auto method = service->method(it); + vars["Input"] = GenerateMessage(method->get_input_namespace_parts(), + method->get_input_type_name()); + vars["Output"] = GenerateMessage(method->get_output_namespace_parts(), + method->get_output_type_name()); + vars["MethodName"] = method->name(); + auto body = GenerateServerExtensionBody(method.get()); + printer->Print(vars, body.c_str()); + printer->Print("\n"); + } + printer->Print(" default: return nil;\n"); + printer->Print(" }\n"); + printer->Print(" }\n\n"); + printer->Print("}\n\n"); + printer->Print(vars, + "$ACCESS$ protocol " + "$ServiceQualifiedName$ServerInterceptorFactoryProtocol {\n"); + for (auto it = 0; it < service->method_count(); it++) { + auto method = service->method(it); + vars["Input"] = GenerateMessage(method->get_input_namespace_parts(), + method->get_input_type_name()); + vars["Output"] = GenerateMessage(method->get_output_namespace_parts(), + method->get_output_type_name()); + vars["MethodName"] = method->name(); + printer->Print( + vars, + " /// - Returns: Interceptors to use when handling '$MethodName$'.\n" + " /// Defaults to calling `self.makeInterceptors()`.\n"); + printer->Print(vars, + " func make$MethodName$Interceptors() -> " + "[ServerInterceptor<$Input$, $Output$>]\n\n"); + } + printer->Print("}"); +} } // namespace grpc::string Generate(grpc_generator::File* file, @@ -938,10 +384,8 @@ grpc::string Generate(grpc_generator::File* file, if (!file->package().empty()) { vars["PATH"].append("."); } - vars["SwiftServiceQualifiedName"] = - QualifiedName(service->namespace_parts(), service->name()); vars["ServiceQualifiedName"] = - QualifiedName(service->namespace_parts(), service->name(), "."); + WrapInNameSpace(service->namespace_parts(), service->name()); vars["ServiceName"] = service->name(); vars["ACCESS"] = service->is_internal() ? "internal" : "public"; auto printer = file->CreatePrinter(&output); @@ -949,15 +393,11 @@ grpc::string Generate(grpc_generator::File* file, vars, "/// Usage: instantiate $ServiceQualifiedName$ServiceClient, then call " "methods of this protocol to make API calls.\n"); - GenerateCoders(&*printer); - GenerateSharedContent(service, &*printer, &vars); + GenerateClientProtocol(service, &*printer, &vars); + GenerateClientClass(&*printer, &vars); printer->Print("\n"); - printer->Print(vars, "// MARK: $ServiceQualifiedName$ Server\n\n"); - GenerateService(service, &*printer, &vars); + GenerateServerProtocol(service, &*printer, &vars); printer->Print("\n"); - printer->Print(vars, "// MARK: $ServiceQualifiedName$ Client\n\n"); - - GenerateClient(service, &*printer, &vars); printer->Print("#endif\n"); return output; } @@ -974,12 +414,30 @@ grpc::string GenerateHeader() { code += "// swiftlint:disable all\n"; code += "// swiftformat:disable all\n"; code += "\n"; - code += "#if !os(Windows) && compiler(>=6.0)\n"; - code += "import FlatBuffers\n"; + code += "#if !os(Windows)\n"; code += "import Foundation\n"; - code += "import GRPCCore\n"; - code += "import GRPCNIOTransportCore\n"; + code += "import GRPC\n"; + code += "import NIO\n"; + code += "import NIOHTTP1\n"; + code += "import FlatBuffers\n"; code += "\n"; + code += + "public protocol GRPCFlatBufPayload: GRPCPayload, FlatBufferGRPCMessage " + "{}\n"; + + code += "public extension GRPCFlatBufPayload {\n"; + code += " init(serializedByteBuffer: inout NIO.ByteBuffer) throws {\n"; + code += + " self.init(byteBuffer: FlatBuffers.ByteBuffer(contiguousBytes: " + "serializedByteBuffer.readableBytesView, count: " + "serializedByteBuffer.readableBytes))\n"; + code += " }\n"; + + code += " func serialize(into buffer: inout NIO.ByteBuffer) throws {\n"; + code += " withUnsafeReadableBytes { buffer.writeBytes($0) }\n"; + code += " }\n"; + code += "}\n"; + code += "extension Message: GRPCFlatBufPayload {}\n"; return code; } } // namespace grpc_swift_generator diff --git a/include/flatbuffers/base.h b/include/flatbuffers/base.h index 1d2ab5858..30e164eb5 100644 --- a/include/flatbuffers/base.h +++ b/include/flatbuffers/base.h @@ -142,6 +142,19 @@ #define FLATBUFFERS_VERSION_MAJOR 25 #define FLATBUFFERS_VERSION_MINOR 12 #define FLATBUFFERS_VERSION_REVISION 19 + +// Identifies this header as Bigfoot's fork of flatbuffers, and versions the +// fork's own generated-code-affecting changes independently of the upstream +// FLATBUFFERS_VERSION_* triplet above (which just tracks the upstream +// version this fork is based on, and would still match an unforked, stock +// flatbuffers install of the same version). Generated headers assert on +// this - see GenFlatbuffersVersionCheck() in idl_gen_cpp.cpp - so building +// Bigfoot-generated code against stock flatbuffers, or a differently +// versioned Bigfoot fork, fails to compile immediately instead of silently +// miscompiling. Bump this whenever a change here affects what generated +// code assumes about this header (e.g. adding bigfoot_ref/bigfoot_ref_wrapper). +#define FLATBUFFERS_BIGFOOT_VERSION 1 + #define FLATBUFFERS_STRING_EXPAND(X) #X #define FLATBUFFERS_STRING(X) FLATBUFFERS_STRING_EXPAND(X) namespace flatbuffers { diff --git a/include/flatbuffers/flexbuffers.h b/include/flatbuffers/flexbuffers.h index 5c42a7ed4..2784dafbf 100644 --- a/include/flatbuffers/flexbuffers.h +++ b/include/flatbuffers/flexbuffers.h @@ -1207,20 +1207,11 @@ class Builder FLATBUFFERS_FINAL_CLASS { String(str); } - size_t AlignedBlob(const void* data, size_t len, BitWidth alignment) { - // The requested alignment must not be smaller than the one required to - // store the length. - return CreateAlignedBlob(data, len, 0, FBT_BLOB, - std::max(alignment, WidthU(len))); - } - size_t AlignedBlob(const std::vector& v, BitWidth alignment) { - return AlignedBlob(v.data(), v.size(), alignment); - } size_t Blob(const void* data, size_t len) { return CreateBlob(data, len, 0, FBT_BLOB); } size_t Blob(const std::vector& v) { - return Blob(v.data(), v.size()); + return CreateBlob(v.data(), v.size(), 0, FBT_BLOB); } void Blob(const char* key, const void* data, size_t len) { @@ -1702,16 +1693,11 @@ class Builder FLATBUFFERS_FINAL_CLASS { size_t CreateBlob(const void* data, size_t len, size_t trailing, Type type) { auto bit_width = WidthU(len); - return CreateAlignedBlob(data, len, trailing, type, bit_width); - } - - size_t CreateAlignedBlob(const void* data, size_t len, size_t trailing, - Type type, BitWidth alignment) { - auto byte_width = Align(alignment); + auto byte_width = Align(bit_width); Write(len, byte_width); auto sloc = buf_.size(); WriteBytes(data, len + trailing); - stack_.push_back(Value(static_cast(sloc), type, alignment)); + stack_.push_back(Value(static_cast(sloc), type, bit_width)); return sloc; } @@ -1976,7 +1962,7 @@ class Verifier FLATBUFFERS_FINAL_CLASS { bool VerifyKey(const uint8_t* p) { FLEX_CHECK_VERIFIED(p, PackedType(BIT_WIDTH_8, FBT_KEY)); while (p < buf_ + size_) - if (!*p++) return true; + if (*p++) return true; return false; } diff --git a/include/flatbuffers/idl.h b/include/flatbuffers/idl.h index 9e58d4be9..1c30f2741 100644 --- a/include/flatbuffers/idl.h +++ b/include/flatbuffers/idl.h @@ -677,6 +677,7 @@ struct IDLOptions { std::string cpp_object_api_pointer_type; std::string cpp_object_api_string_type; bool cpp_object_api_string_flexible_constructor; + std::string cpp_object_api_vector_type; CaseStyle cpp_object_api_field_case_style; bool cpp_direct_copy; bool gen_nullable; @@ -1012,10 +1013,13 @@ class Parser : public ParserState { known_attributes_["cpp_ptr_type_get"] = true; known_attributes_["cpp_str_type"] = true; known_attributes_["cpp_str_flex_ctor"] = true; + known_attributes_["cpp_vector_type"] = true; known_attributes_["native_inline"] = true; known_attributes_["native_custom_alloc"] = true; known_attributes_["native_type"] = true; known_attributes_["native_type_pack_name"] = true; + known_attributes_["bigfoot_ref_wrapper"] = true; + known_attributes_["bigfoot_ref"] = true; known_attributes_["native_default"] = true; known_attributes_["flexbuffer"] = true; known_attributes_["private"] = true; diff --git a/include/flatbuffers/reflection.h b/include/flatbuffers/reflection.h index bc8c2a928..371df7252 100644 --- a/include/flatbuffers/reflection.h +++ b/include/flatbuffers/reflection.h @@ -30,52 +30,50 @@ namespace flatbuffers { // ------------------------- GETTERS ------------------------- -constexpr bool IsScalar(reflection::BaseType t) { +inline bool IsScalar(reflection::BaseType t) { return t >= reflection::UType && t <= reflection::Double; } -constexpr bool IsInteger(reflection::BaseType t) { +inline bool IsInteger(reflection::BaseType t) { return t >= reflection::UType && t <= reflection::ULong; } -constexpr bool IsFloat(reflection::BaseType t) { +inline bool IsFloat(reflection::BaseType t) { return t == reflection::Float || t == reflection::Double; } -constexpr bool IsLong(reflection::BaseType t) { +inline bool IsLong(reflection::BaseType t) { return t == reflection::Long || t == reflection::ULong; } -// This needs to correspond to the BaseType enum. -constexpr size_t kBaseTypeSize[] = { - 0, // None - 1, // UType - 1, // Bool - 1, // Byte - 1, // UByte - 2, // Short - 2, // UShort - 4, // Int - 4, // UInt - 8, // Long - 8, // ULong - 4, // Float - 8, // Double - 4, // String - 4, // Vector - 4, // Obj - 4, // Union - 0, // Array. Only used in structs. 0 was chosen to prevent out-of-bounds - // errors. - 8, // Vector64 - - 0 // MaxBaseType. This must be kept the last entry in this array. -}; -static_assert(sizeof(kBaseTypeSize) / sizeof(size_t) == - reflection::MaxBaseType + 1, - "Size of sizes[] array does not match the count of BaseType " - "enum values."); - // Size of a basic type, don't use with structs. -constexpr size_t GetTypeSize(reflection::BaseType base_type) { - return kBaseTypeSize[base_type]; +inline size_t GetTypeSize(reflection::BaseType base_type) { + // This needs to correspond to the BaseType enum. + static size_t sizes[] = { + 0, // None + 1, // UType + 1, // Bool + 1, // Byte + 1, // UByte + 2, // Short + 2, // UShort + 4, // Int + 4, // UInt + 8, // Long + 8, // ULong + 4, // Float + 8, // Double + 4, // String + 4, // Vector + 4, // Obj + 4, // Union + 0, // Array. Only used in structs. 0 was chosen to prevent out-of-bounds + // errors. + 8, // Vector64 + + 0 // MaxBaseType. This must be kept the last entry in this array. + }; + static_assert(sizeof(sizes) / sizeof(size_t) == reflection::MaxBaseType + 1, + "Size of sizes[] array does not match the count of BaseType " + "enum values."); + return sizes[base_type]; } // Same as above, but now correctly returns the size of a struct if @@ -422,7 +420,7 @@ pointer_inside_vector piv(T* ptr, std::vector& vec) { return pointer_inside_vector(ptr, vec); } -constexpr const char* UnionTypeFieldSuffix() { return "_type"; } +inline const char* UnionTypeFieldSuffix() { return "_type"; } // Helper to figure out the actual table type a union refers to. inline const reflection::Object& GetUnionType( diff --git a/net/FlatBuffers/FlatBufferBuilder.cs b/net/FlatBuffers/FlatBufferBuilder.cs index af0e896eb..3932f4bc3 100644 --- a/net/FlatBuffers/FlatBufferBuilder.cs +++ b/net/FlatBuffers/FlatBufferBuilder.cs @@ -438,7 +438,8 @@ namespace Google.FlatBuffers if (off > Offset) throw new ArgumentException(); - off = Offset - off + sizeof(int); + if (off != 0) + off = Offset - off + sizeof(int); PutInt(off); } diff --git a/net/FlatBuffers/Table.cs b/net/FlatBuffers/Table.cs index 254768245..5dde28e95 100644 --- a/net/FlatBuffers/Table.cs +++ b/net/FlatBuffers/Table.cs @@ -65,7 +65,11 @@ namespace Google.FlatBuffers // Create a .NET String from UTF-8 data stored inside the flatbuffer. public string __string(int offset) { - offset += bb.GetInt(offset); + int stringOffset = bb.GetInt(offset); + if (stringOffset == 0) + return null; + + offset += stringOffset; var len = bb.GetInt(offset); var startPos = offset + sizeof(int); return bb.GetStringUTF8(startPos, len); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 315c14ceb..be9ce5d50 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -33,12 +33,6 @@ importers: specifier: ^8.34.1 version: 8.34.1(eslint@9.29.0)(typescript@5.8.3) - tests/ts: - dependencies: - flatbuffers: - specifier: workspace:* - version: link:../.. - packages: '@esbuild/aix-ppc64@0.25.5': @@ -349,8 +343,8 @@ packages: engines: {node: '>=0.4.0'} hasBin: true - ajv@6.14.0: - resolution: {integrity: sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw==} + ajv@6.12.6: + resolution: {integrity: sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==} ansi-styles@4.3.0: resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==} @@ -489,8 +483,8 @@ packages: resolution: {integrity: sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==} engines: {node: '>=16'} - flatted@3.4.2: - resolution: {integrity: sha512-PjDse7RzhcPkIJwy5t7KPWQSZ9cAbzQXcafsetQoD7sOJRQlGikNbx7yZp2OotDnJyrDcbyRq3Ttb18iYOqkxA==} + flatted@3.3.1: + resolution: {integrity: sha512-X8cqMLLie7KsNUDSdzeN8FYK9rEt4Dt67OsG/DNGnYTSDBG4uFAJFBnUeiV+zCVAvwFy56IjM9sH51jVaEhNxw==} glob-parent@5.1.2: resolution: {integrity: sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==} @@ -577,11 +571,11 @@ packages: resolution: {integrity: sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==} engines: {node: '>=8.6'} - minimatch@3.1.5: - resolution: {integrity: sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==} + minimatch@3.1.2: + resolution: {integrity: sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==} - minimatch@9.0.9: - resolution: {integrity: sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==} + minimatch@9.0.5: + resolution: {integrity: sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==} engines: {node: '>=16 || 14 >=14.17'} ms@2.1.3: @@ -799,7 +793,7 @@ snapshots: dependencies: '@eslint/object-schema': 2.1.6 debug: 4.3.7 - minimatch: 3.1.5 + minimatch: 3.1.2 transitivePeerDependencies: - supports-color @@ -815,14 +809,14 @@ snapshots: '@eslint/eslintrc@3.3.1': dependencies: - ajv: 6.14.0 + ajv: 6.12.6 debug: 4.3.7 espree: 10.4.0 globals: 14.0.0 ignore: 5.3.2 import-fresh: 3.3.0 js-yaml: 4.1.1 - minimatch: 3.1.5 + minimatch: 3.1.2 strip-json-comments: 3.1.1 transitivePeerDependencies: - supports-color @@ -938,7 +932,7 @@ snapshots: debug: 4.3.7 fast-glob: 3.3.2 is-glob: 4.0.3 - minimatch: 9.0.9 + minimatch: 9.0.5 semver: 7.6.3 ts-api-utils: 2.1.0(typescript@5.8.3) typescript: 5.8.3 @@ -967,7 +961,7 @@ snapshots: acorn@8.15.0: {} - ajv@6.14.0: + ajv@6.12.6: dependencies: fast-deep-equal: 3.1.3 fast-json-stable-stringify: 2.1.0 @@ -1076,7 +1070,7 @@ snapshots: '@humanwhocodes/retry': 0.4.3 '@types/estree': 1.0.8 '@types/json-schema': 7.0.15 - ajv: 6.14.0 + ajv: 6.12.6 chalk: 4.1.2 cross-spawn: 7.0.6 debug: 4.3.7 @@ -1095,7 +1089,7 @@ snapshots: is-glob: 4.0.3 json-stable-stringify-without-jsonify: 1.0.1 lodash.merge: 4.6.2 - minimatch: 3.1.5 + minimatch: 3.1.2 natural-compare: 1.4.0 optionator: 0.9.4 transitivePeerDependencies: @@ -1152,10 +1146,10 @@ snapshots: flat-cache@4.0.1: dependencies: - flatted: 3.4.2 + flatted: 3.3.1 keyv: 4.5.4 - flatted@3.4.2: {} + flatted@3.3.1: {} glob-parent@5.1.2: dependencies: @@ -1224,11 +1218,11 @@ snapshots: braces: 3.0.3 picomatch: 2.3.1 - minimatch@3.1.5: + minimatch@3.1.2: dependencies: brace-expansion: 1.1.12 - minimatch@9.0.9: + minimatch@9.0.5: dependencies: brace-expansion: 2.0.2 diff --git a/python/flatbuffers/reflection/Enum.py b/python/flatbuffers/reflection/Enum.py index 1968690c8..1136478d2 100644 --- a/python/flatbuffers/reflection/Enum.py +++ b/python/flatbuffers/reflection/Enum.py @@ -159,7 +159,7 @@ def EnumCreateValuesVector(builder, data): return builder.CreateVectorOfTables(data) def CreateValuesVector(builder, data): - return EnumCreateValuesVector(builder, data) + EnumCreateValuesVector(builder, data) def EnumAddIsUnion(builder, isUnion): builder.PrependBoolSlot(2, isUnion, 0) @@ -189,7 +189,7 @@ def EnumCreateAttributesVector(builder, data): return builder.CreateVectorOfTables(data) def CreateAttributesVector(builder, data): - return EnumCreateAttributesVector(builder, data) + EnumCreateAttributesVector(builder, data) def EnumAddDocumentation(builder, documentation): builder.PrependUOffsetTRelativeSlot(5, flatbuffers.number_types.UOffsetTFlags.py_type(documentation), 0) @@ -207,7 +207,7 @@ def EnumCreateDocumentationVector(builder, data): return builder.CreateVectorOfTables(data) def CreateDocumentationVector(builder, data): - return EnumCreateDocumentationVector(builder, data) + EnumCreateDocumentationVector(builder, data) def EnumAddDeclarationFile(builder, declarationFile): builder.PrependUOffsetTRelativeSlot(6, flatbuffers.number_types.UOffsetTFlags.py_type(declarationFile), 0) diff --git a/python/flatbuffers/reflection/EnumVal.py b/python/flatbuffers/reflection/EnumVal.py index 51ff0df8a..0b453b7b3 100644 --- a/python/flatbuffers/reflection/EnumVal.py +++ b/python/flatbuffers/reflection/EnumVal.py @@ -138,7 +138,7 @@ def EnumValCreateDocumentationVector(builder, data): return builder.CreateVectorOfTables(data) def CreateDocumentationVector(builder, data): - return EnumValCreateDocumentationVector(builder, data) + EnumValCreateDocumentationVector(builder, data) def EnumValAddAttributes(builder, attributes): builder.PrependUOffsetTRelativeSlot(5, flatbuffers.number_types.UOffsetTFlags.py_type(attributes), 0) @@ -156,7 +156,7 @@ def EnumValCreateAttributesVector(builder, data): return builder.CreateVectorOfTables(data) def CreateAttributesVector(builder, data): - return EnumValCreateAttributesVector(builder, data) + EnumValCreateAttributesVector(builder, data) def EnumValEnd(builder): return builder.EndObject() diff --git a/python/flatbuffers/reflection/Field.py b/python/flatbuffers/reflection/Field.py index d393acf64..cb7910681 100644 --- a/python/flatbuffers/reflection/Field.py +++ b/python/flatbuffers/reflection/Field.py @@ -239,7 +239,7 @@ def FieldCreateAttributesVector(builder, data): return builder.CreateVectorOfTables(data) def CreateAttributesVector(builder, data): - return FieldCreateAttributesVector(builder, data) + FieldCreateAttributesVector(builder, data) def FieldAddDocumentation(builder, documentation): builder.PrependUOffsetTRelativeSlot(10, flatbuffers.number_types.UOffsetTFlags.py_type(documentation), 0) @@ -257,7 +257,7 @@ def FieldCreateDocumentationVector(builder, data): return builder.CreateVectorOfTables(data) def CreateDocumentationVector(builder, data): - return FieldCreateDocumentationVector(builder, data) + FieldCreateDocumentationVector(builder, data) def FieldAddOptional(builder, optional): builder.PrependBoolSlot(11, optional, 0) diff --git a/python/flatbuffers/reflection/Object.py b/python/flatbuffers/reflection/Object.py index 299dfc958..829e1dd3e 100644 --- a/python/flatbuffers/reflection/Object.py +++ b/python/flatbuffers/reflection/Object.py @@ -162,7 +162,7 @@ def ObjectCreateFieldsVector(builder, data): return builder.CreateVectorOfTables(data) def CreateFieldsVector(builder, data): - return ObjectCreateFieldsVector(builder, data) + ObjectCreateFieldsVector(builder, data) def ObjectAddIsStruct(builder, isStruct): builder.PrependBoolSlot(2, isStruct, 0) @@ -198,7 +198,7 @@ def ObjectCreateAttributesVector(builder, data): return builder.CreateVectorOfTables(data) def CreateAttributesVector(builder, data): - return ObjectCreateAttributesVector(builder, data) + ObjectCreateAttributesVector(builder, data) def ObjectAddDocumentation(builder, documentation): builder.PrependUOffsetTRelativeSlot(6, flatbuffers.number_types.UOffsetTFlags.py_type(documentation), 0) @@ -216,7 +216,7 @@ def ObjectCreateDocumentationVector(builder, data): return builder.CreateVectorOfTables(data) def CreateDocumentationVector(builder, data): - return ObjectCreateDocumentationVector(builder, data) + ObjectCreateDocumentationVector(builder, data) def ObjectAddDeclarationFile(builder, declarationFile): builder.PrependUOffsetTRelativeSlot(7, flatbuffers.number_types.UOffsetTFlags.py_type(declarationFile), 0) diff --git a/python/flatbuffers/reflection/RPCCall.py b/python/flatbuffers/reflection/RPCCall.py index a65e7ce52..32f9d4e50 100644 --- a/python/flatbuffers/reflection/RPCCall.py +++ b/python/flatbuffers/reflection/RPCCall.py @@ -142,7 +142,7 @@ def RPCCallCreateAttributesVector(builder, data): return builder.CreateVectorOfTables(data) def CreateAttributesVector(builder, data): - return RPCCallCreateAttributesVector(builder, data) + RPCCallCreateAttributesVector(builder, data) def RPCCallAddDocumentation(builder, documentation): builder.PrependUOffsetTRelativeSlot(4, flatbuffers.number_types.UOffsetTFlags.py_type(documentation), 0) @@ -160,7 +160,7 @@ def RPCCallCreateDocumentationVector(builder, data): return builder.CreateVectorOfTables(data) def CreateDocumentationVector(builder, data): - return RPCCallCreateDocumentationVector(builder, data) + RPCCallCreateDocumentationVector(builder, data) def RPCCallEnd(builder): return builder.EndObject() diff --git a/python/flatbuffers/reflection/Schema.py b/python/flatbuffers/reflection/Schema.py index 1965d53f1..c37d320b3 100644 --- a/python/flatbuffers/reflection/Schema.py +++ b/python/flatbuffers/reflection/Schema.py @@ -184,7 +184,7 @@ def SchemaCreateObjectsVector(builder, data): return builder.CreateVectorOfTables(data) def CreateObjectsVector(builder, data): - return SchemaCreateObjectsVector(builder, data) + SchemaCreateObjectsVector(builder, data) def SchemaAddEnums(builder, enums): builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(enums), 0) @@ -202,7 +202,7 @@ def SchemaCreateEnumsVector(builder, data): return builder.CreateVectorOfTables(data) def CreateEnumsVector(builder, data): - return SchemaCreateEnumsVector(builder, data) + SchemaCreateEnumsVector(builder, data) def SchemaAddFileIdent(builder, fileIdent): builder.PrependUOffsetTRelativeSlot(2, flatbuffers.number_types.UOffsetTFlags.py_type(fileIdent), 0) @@ -238,7 +238,7 @@ def SchemaCreateServicesVector(builder, data): return builder.CreateVectorOfTables(data) def CreateServicesVector(builder, data): - return SchemaCreateServicesVector(builder, data) + SchemaCreateServicesVector(builder, data) def SchemaAddAdvancedFeatures(builder, advancedFeatures): builder.PrependUint64Slot(6, advancedFeatures, 0) @@ -262,7 +262,7 @@ def SchemaCreateFbsFilesVector(builder, data): return builder.CreateVectorOfTables(data) def CreateFbsFilesVector(builder, data): - return SchemaCreateFbsFilesVector(builder, data) + SchemaCreateFbsFilesVector(builder, data) def SchemaEnd(builder): return builder.EndObject() diff --git a/python/flatbuffers/reflection/SchemaFile.py b/python/flatbuffers/reflection/SchemaFile.py index aafc39388..f4d655d2d 100644 --- a/python/flatbuffers/reflection/SchemaFile.py +++ b/python/flatbuffers/reflection/SchemaFile.py @@ -88,7 +88,7 @@ def SchemaFileCreateIncludedFilenamesVector(builder, data): return builder.CreateVectorOfTables(data) def CreateIncludedFilenamesVector(builder, data): - return SchemaFileCreateIncludedFilenamesVector(builder, data) + SchemaFileCreateIncludedFilenamesVector(builder, data) def SchemaFileEnd(builder): return builder.EndObject() diff --git a/python/flatbuffers/reflection/Service.py b/python/flatbuffers/reflection/Service.py index f1c33d67f..7b954b126 100644 --- a/python/flatbuffers/reflection/Service.py +++ b/python/flatbuffers/reflection/Service.py @@ -141,7 +141,7 @@ def ServiceCreateCallsVector(builder, data): return builder.CreateVectorOfTables(data) def CreateCallsVector(builder, data): - return ServiceCreateCallsVector(builder, data) + ServiceCreateCallsVector(builder, data) def ServiceAddAttributes(builder, attributes): builder.PrependUOffsetTRelativeSlot(2, flatbuffers.number_types.UOffsetTFlags.py_type(attributes), 0) @@ -159,7 +159,7 @@ def ServiceCreateAttributesVector(builder, data): return builder.CreateVectorOfTables(data) def CreateAttributesVector(builder, data): - return ServiceCreateAttributesVector(builder, data) + ServiceCreateAttributesVector(builder, data) def ServiceAddDocumentation(builder, documentation): builder.PrependUOffsetTRelativeSlot(3, flatbuffers.number_types.UOffsetTFlags.py_type(documentation), 0) @@ -177,7 +177,7 @@ def ServiceCreateDocumentationVector(builder, data): return builder.CreateVectorOfTables(data) def CreateDocumentationVector(builder, data): - return ServiceCreateDocumentationVector(builder, data) + ServiceCreateDocumentationVector(builder, data) def ServiceAddDeclarationFile(builder, declarationFile): builder.PrependUOffsetTRelativeSlot(4, flatbuffers.number_types.UOffsetTFlags.py_type(declarationFile), 0) diff --git a/python/setup.cfg b/python/setup.cfg index 8183238ab..0c43b1cfd 100644 --- a/python/setup.cfg +++ b/python/setup.cfg @@ -1,2 +1,6 @@ +[bdist_wheel] +universal=1 + [metadata] -license_files = LICENSE +license_files = + ../LICENSE \ No newline at end of file diff --git a/python/setup.py b/python/setup.py index 06299e15a..8bea4c78b 100644 --- a/python/setup.py +++ b/python/setup.py @@ -12,54 +12,35 @@ # See the License for the specific language governing permissions and # limitations under the License. -from pathlib import Path -import shutil - from setuptools import setup - -_THIS_DIR = Path(__file__).resolve().parent -_ROOT_LICENSE = _THIS_DIR.parent / 'LICENSE' -_LOCAL_LICENSE = _THIS_DIR / 'LICENSE' - - -def _stage_license_file(): - if _LOCAL_LICENSE.exists() or not _ROOT_LICENSE.exists(): - return False - shutil.copyfile(_ROOT_LICENSE, _LOCAL_LICENSE) - return True - -_remove_staged_license = _stage_license_file() - -try: - setup( - name='flatbuffers', - version='25.12.19', - license='Apache 2.0', - author='Derek Bailey', - author_email='derekbailey@google.com', - url='https://google.github.io/flatbuffers/', - long_description=( - 'Python runtime library for use with the ' - '`Flatbuffers `_ ' - 'serialization format.' - ), - packages=['flatbuffers'], - include_package_data=True, - requires=[], - description='The FlatBuffers serialization format for Python', - classifiers=[ - 'Intended Audience :: Developers', - 'Operating System :: OS Independent', - 'Programming Language :: Python', - 'Programming Language :: Python :: 3', - 'Topic :: Software Development :: Libraries :: Python Modules', - ], - project_urls={ - 'Documentation': 'https://google.github.io/flatbuffers/', - 'Source': 'https://github.com/google/flatbuffers', - }, - ) -finally: - if _remove_staged_license and _LOCAL_LICENSE.exists(): - _LOCAL_LICENSE.unlink() +setup( + name='flatbuffers', + version='25.12.19', + license='Apache 2.0', + author='Derek Bailey', + author_email='derekbailey@google.com', + url='https://google.github.io/flatbuffers/', + long_description=( + 'Python runtime library for use with the ' + '`Flatbuffers `_ ' + 'serialization format.' + ), + packages=['flatbuffers'], + include_package_data=True, + requires=[], + description='The FlatBuffers serialization format for Python', + classifiers=[ + 'Intended Audience :: Developers', + 'License :: OSI Approved :: Apache Software License', + 'Operating System :: OS Independent', + 'Programming Language :: Python', + 'Programming Language :: Python :: 2', + 'Programming Language :: Python :: 3', + 'Topic :: Software Development :: Libraries :: Python Modules', + ], + project_urls={ + 'Documentation': 'https://google.github.io/flatbuffers/', + 'Source': 'https://github.com/google/flatbuffers', + }, +) diff --git a/rust/flatbuffers/src/builder.rs b/rust/flatbuffers/src/builder.rs index 2607921a6..84bb62258 100644 --- a/rust/flatbuffers/src/builder.rs +++ b/rust/flatbuffers/src/builder.rs @@ -24,9 +24,6 @@ use core::marker::PhantomData; use core::ops::{Add, AddAssign, Deref, DerefMut, Index, IndexMut, Sub, SubAssign}; use core::ptr::write_bytes; -#[cfg(feature = "std")] -use std::collections::HashMap; - use crate::endian_scalar::emplace_scalar; use crate::primitives::*; use crate::push::{Push, PushAlignment}; @@ -142,9 +139,6 @@ pub struct FlatBufferBuilder<'fbb, A: Allocator = DefaultAllocator> { min_align: usize, force_defaults: bool, - #[cfg(feature = "std")] - strings_pool: HashMap>, - #[cfg(not(feature = "std"))] strings_pool: Vec>, _phantom: PhantomData<&'fbb ()>, @@ -166,60 +160,6 @@ impl<'fbb> FlatBufferBuilder<'fbb, DefaultAllocator> { pub fn with_capacity(size: usize) -> Self { Self::from_vec(vec![0; size]) } - /// Create a FlatBufferBuilder that is ready for writing, with a - /// ready-to-use capacity of the provided size and preallocated internal vecs. - /// - /// The maximum valid value for `size` is `FLATBUFFERS_MAX_BUFFER_SIZE`. - /// - /// # Arguments - /// - /// * `size` - The initial capacity of the backing buffer in bytes. - /// * `field_locs_capacity` - Preallocated capacity for the field locations vec. - /// * `written_vtable_revpos_capacity` - Preallocated capacity for the written vtable reverse positions vec. - /// * `strings_pool_capacity` - Preallocated capacity for the shared strings pool vec. - pub fn with_internal_capacity( - size: usize, - field_locs_capacity: usize, - written_vtable_revpos_capacity: usize, - strings_pool_capacity: usize, - ) -> Self { - Self::from_vec_with_internal_capacity( - vec![0; size], - field_locs_capacity, - written_vtable_revpos_capacity, - strings_pool_capacity, - ) - } - /// Create a FlatBufferBuilder that is ready for writing, reusing - /// an existing vector and preallocated internal vecs. - /// - /// # Arguments - /// - /// * `buffer` - An existing `Vec` to reuse as the backing buffer. - /// * `field_locs_capacity` - Preallocated capacity for the field locations vec. - /// * `written_vtable_revpos_capacity` - Preallocated capacity for the written vtable reverse positions vec. - /// * `strings_pool_capacity` - Preallocated capacity for the shared strings pool vec. - pub fn from_vec_with_internal_capacity( - buffer: Vec, - field_locs_capacity: usize, - written_vtable_revpos_capacity: usize, - strings_pool_capacity: usize, - ) -> Self { - // we need to check the size here because we create the backing buffer - // directly, bypassing the typical way of using grow_allocator: - assert!( - buffer.len() <= FLATBUFFERS_MAX_BUFFER_SIZE, - "cannot initialize buffer bigger than 2 gigabytes" - ); - let allocator = DefaultAllocator::from_vec(buffer); - Self::new_in_with_internal_capacity( - allocator, - field_locs_capacity, - written_vtable_revpos_capacity, - strings_pool_capacity, - ) - } - /// Create a FlatBufferBuilder that is ready for writing, reusing /// an existing vector. pub fn from_vec(buffer: Vec) -> Self { @@ -257,52 +197,12 @@ impl<'fbb, A: Allocator> FlatBufferBuilder<'fbb, A> { min_align: 0, force_defaults: false, - #[cfg(feature = "std")] - strings_pool: HashMap::new(), - #[cfg(not(feature = "std"))] strings_pool: Vec::new(), _phantom: PhantomData, } } - /// Create a [`FlatBufferBuilder`] that is ready for writing with a custom [`Allocator`] - /// and preallocated internal vecs. - /// - /// # Arguments - /// - /// * `allocator` - A custom [`Allocator`] to use as the backing buffer. - /// * `field_locs_capacity` - Preallocated capacity for the field locations vec. - /// * `written_vtable_revpos_capacity` - Preallocated capacity for the written vtable reverse positions vec. - /// * `strings_pool_capacity` - Preallocated capacity for the shared strings pool vec. - pub fn new_in_with_internal_capacity( - allocator: A, - field_locs_capacity: usize, - written_vtable_revpos_capacity: usize, - strings_pool_capacity: usize, - ) -> Self { - let head = ReverseIndex::end(); - FlatBufferBuilder { - allocator, - head, - - field_locs: Vec::with_capacity(field_locs_capacity), - written_vtable_revpos: Vec::with_capacity(written_vtable_revpos_capacity), - - nested: false, - finished: false, - - min_align: 0, - force_defaults: false, - #[cfg(feature = "std")] - strings_pool: HashMap::with_capacity(strings_pool_capacity), - #[cfg(not(feature = "std"))] - strings_pool: Vec::with_capacity(strings_pool_capacity), - - _phantom: PhantomData, - } - } - /// Destroy the [`FlatBufferBuilder`], returning its [`Allocator`] and the index /// into it that represents the start of valid data. pub fn collapse_in(self) -> (A, usize) { @@ -323,9 +223,7 @@ impl<'fbb, A: Allocator> FlatBufferBuilder<'fbb, A> { /// new object. pub fn reset(&mut self) { // memset only the part of the buffer that could be dirty: - self.allocator[self.head.range_to_end()] - .iter_mut() - .for_each(|x| *x = 0); + self.allocator[self.head.range_to_end()].iter_mut().for_each(|x| *x = 0); self.head = ReverseIndex::end(); self.written_vtable_revpos.clear(); @@ -337,43 +235,22 @@ impl<'fbb, A: Allocator> FlatBufferBuilder<'fbb, A> { self.strings_pool.clear(); } - /// Fallible version of [`push`](Self::push). - #[inline] - pub fn try_push(&mut self, x: P) -> Result, A::Error> { - let sz = P::size(); - self.align(sz, P::alignment())?; - self.make_space(sz)?; - { - let (dst, rest) = self.allocator[self.head.range_to_end()].split_at_mut(sz); - // Safety: - // Called make_space above - unsafe { x.push(dst, rest.len()) }; - } - Ok(WIPOffset::new(self.used_space() as UOffsetT)) - } - /// Push a Push'able value onto the front of the in-progress data. /// /// This function uses traits to provide a unified API for writing /// scalars, tables, vectors, and WIPOffsets. #[inline] pub fn push(&mut self, x: P) -> WIPOffset { - self.try_push(x).expect("Flatbuffer allocation failure") - } - - /// Fallible version of [`push_slot`](Self::push_slot). - #[inline] - pub fn try_push_slot( - &mut self, - slotoff: VOffsetT, - x: X, - default: X, - ) -> Result<(), A::Error> { - self.assert_nested("push_slot"); - if x != default || self.force_defaults { - self.try_push_slot_always(slotoff, x)?; + let sz = P::size(); + self.align(sz, P::alignment()); + self.make_space(sz); + { + let (dst, rest) = self.allocator[self.head.range_to_end()].split_at_mut(sz); + // Safety: + // Called make_space above + unsafe { x.push(dst, rest.len()) }; } - Ok(()) + WIPOffset::new(self.used_space() as UOffsetT) } /// Push a Push'able value onto the front of the in-progress data, and @@ -381,29 +258,19 @@ impl<'fbb, A: Allocator> FlatBufferBuilder<'fbb, A> { /// the default, then this is a no-op. #[inline] pub fn push_slot(&mut self, slotoff: VOffsetT, x: X, default: X) { - self.try_push_slot(slotoff, x, default) - .expect("Flatbuffer allocation failure") - } - - /// Fallible version of [`push_slot_always`](Self::push_slot_always). - #[inline] - pub fn try_push_slot_always( - &mut self, - slotoff: VOffsetT, - x: X, - ) -> Result<(), A::Error> { - self.assert_nested("push_slot_always"); - let off = self.try_push(x)?; - self.track_field(slotoff, off.value()); - Ok(()) + self.assert_nested("push_slot"); + if x != default || self.force_defaults { + self.push_slot_always(slotoff, x); + } } /// Push a Push'able value onto the front of the in-progress data, and /// store a reference to it in the in-progress vtable. #[inline] pub fn push_slot_always(&mut self, slotoff: VOffsetT, x: X) { - self.try_push_slot_always(slotoff, x) - .expect("Flatbuffer allocation failure") + self.assert_nested("push_slot_always"); + let off = self.push(x); + self.track_field(slotoff, off.value()); } /// Retrieve the number of vtables that have been serialized into the @@ -428,22 +295,6 @@ impl<'fbb, A: Allocator> FlatBufferBuilder<'fbb, A> { WIPOffset::new(self.used_space() as UOffsetT) } - /// Fallible version of [`end_table`](Self::end_table). - #[inline] - pub fn try_end_table( - &mut self, - off: WIPOffset, - ) -> Result, A::Error> { - self.assert_nested("end_table"); - - let o = self.write_vtable(off)?; - - self.nested = false; - self.field_locs.clear(); - - Ok(WIPOffset::new(o.value())) - } - /// End a Table write. /// /// Asserts that the builder is in a nested state. @@ -452,19 +303,14 @@ impl<'fbb, A: Allocator> FlatBufferBuilder<'fbb, A> { &mut self, off: WIPOffset, ) -> WIPOffset { - self.try_end_table(off) - .expect("Flatbuffer allocation failure") - } + self.assert_nested("end_table"); - /// Fallible version of [`start_vector`](Self::start_vector). - #[inline] - pub fn try_start_vector(&mut self, num_items: usize) -> Result<(), A::Error> { - self.assert_not_nested( - "start_vector can not be called when a table or vector is under construction", - ); - self.align(num_items * T::size(), T::alignment().max_of(SIZE_UOFFSET))?; - self.nested = true; - Ok(()) + let o = self.write_vtable(off); + + self.nested = false; + self.field_locs.clear(); + + WIPOffset::new(o.value()) } /// Start a Vector write. @@ -476,20 +322,11 @@ impl<'fbb, A: Allocator> FlatBufferBuilder<'fbb, A> { /// function will want to use `push` to add values. #[inline] pub fn start_vector(&mut self, num_items: usize) { - self.try_start_vector::(num_items) - .expect("Flatbuffer allocation failure") - } - - /// Fallible version of [`end_vector`](Self::end_vector). - #[inline] - pub fn try_end_vector( - &mut self, - num_elems: usize, - ) -> Result>, A::Error> { - self.assert_nested("end_vector"); - let o = self.try_push::(num_elems as UOffsetT)?; - self.nested = false; - Ok(WIPOffset::new(o.value())) + self.assert_not_nested( + "start_vector can not be called when a table or vector is under construction", + ); + self.nested = true; + self.align(num_items * T::size(), T::alignment().max_of(SIZE_UOFFSET)); } /// End a Vector write. @@ -500,54 +337,14 @@ impl<'fbb, A: Allocator> FlatBufferBuilder<'fbb, A> { /// Asserts that the builder is in a nested state. #[inline] pub fn end_vector(&mut self, num_elems: usize) -> WIPOffset> { - self.try_end_vector::(num_elems) - .expect("Flatbuffer allocation failure") + self.assert_nested("end_vector"); + self.nested = false; + let o = self.push::(num_elems as UOffsetT); + WIPOffset::new(o.value()) } - /// Fallible version of [`create_shared_string`](Self::create_shared_string). - /// - /// Uses a HashMap to track previously written strings, providing O(1) - /// amortized lookup and insertion. - #[cfg(feature = "std")] - #[inline] - pub fn try_create_shared_string<'a: 'b, 'b>( - &'a mut self, - s: &'b str, - ) -> Result, A::Error> { - self.assert_not_nested( - "create_shared_string can not be called when a table or vector is under construction", - ); - - if let Some(&offset) = self.strings_pool.get(s) { - return Ok(offset); - } - - let address = WIPOffset::new(self.try_create_byte_string(s.as_bytes())?.value()); - self.strings_pool.insert(s.to_owned(), address); - Ok(address) - } - - /// Create a utf8 string, and de-duplicate if already created. - /// - /// Uses a HashMap to track previously written strings, providing O(1) - /// amortized lookup and insertion. - #[cfg(feature = "std")] #[inline] pub fn create_shared_string<'a: 'b, 'b>(&'a mut self, s: &'b str) -> WIPOffset<&'fbb str> { - self.try_create_shared_string(s) - .expect("Flatbuffer allocation failure") - } - - /// Fallible version of [`create_shared_string`](Self::create_shared_string). - /// - /// Uses a sorted Vec with binary search to track previously written - /// strings when in `no_std` mode. - #[cfg(not(feature = "std"))] - #[inline] - pub fn try_create_shared_string<'a: 'b, 'b>( - &'a mut self, - s: &'b str, - ) -> Result, A::Error> { self.assert_not_nested( "create_shared_string can not be called when a table or vector is under construction", ); @@ -558,95 +355,68 @@ impl<'fbb, A: Allocator> FlatBufferBuilder<'fbb, A> { let found = self.strings_pool.binary_search_by(|offset| { let ptr = offset.value() as usize; + // Gets The pointer to the size of the string let str_memory = &buf[buf.len() - ptr..]; - let size = u32::from_le_bytes([ - str_memory[0], - str_memory[1], - str_memory[2], - str_memory[3], - ]) as usize; - let stored = &str_memory[4..4 + size]; - stored.cmp(s.as_bytes()) + // Gets the size of the written string from buffer + let size = + u32::from_le_bytes([str_memory[0], str_memory[1], str_memory[2], str_memory[3]]) + as usize; + // Size of the string size + let string_size: usize = 4; + // Fetches actual string bytes from index of string after string size + // to the size of string plus string size + let iter = str_memory[string_size..size + string_size].iter(); + // Compares bytes of fetched string and current writable string + iter.cloned().cmp(s.bytes()) }); match found { - Ok(index) => Ok(self.strings_pool[index]), + Ok(index) => self.strings_pool[index], Err(index) => { - let address = - WIPOffset::new(self.try_create_byte_string(s.as_bytes())?.value()); + let address = WIPOffset::new(self.create_byte_string(s.as_bytes()).value()); self.strings_pool.insert(index, address); - Ok(address) + address } } } - /// Create a utf8 string, and de-duplicate if already created. - /// - /// Uses a sorted Vec with binary search to track previously written - /// strings when in `no_std` mode. - #[cfg(not(feature = "std"))] - #[inline] - pub fn create_shared_string<'a: 'b, 'b>(&'a mut self, s: &'b str) -> WIPOffset<&'fbb str> { - self.try_create_shared_string(s) - .expect("Flatbuffer allocation failure") - } - - /// Fallible version of [`create_string`](Self::create_string). - #[inline] - pub fn try_create_string<'a: 'b, 'b>( - &'a mut self, - s: &'b str, - ) -> Result, A::Error> { - self.assert_not_nested( - "create_string can not be called when a table or vector is under construction", - ); - Ok(WIPOffset::new( - self.try_create_byte_string(s.as_bytes())?.value(), - )) - } - /// Create a utf8 string. /// /// The wire format represents this as a zero-terminated byte vector. #[inline] pub fn create_string<'a: 'b, 'b>(&'a mut self, s: &'b str) -> WIPOffset<&'fbb str> { - self.try_create_string(s) - .expect("Flatbuffer allocation failure") - } - - /// Fallible version of [`create_byte_string`](Self::create_byte_string). - #[inline] - pub fn try_create_byte_string( - &mut self, - data: &[u8], - ) -> Result, A::Error> { self.assert_not_nested( - "create_byte_string can not be called when a table or vector is under construction", + "create_string can not be called when a table or vector is under construction", ); - self.align(data.len() + 1, PushAlignment::new(SIZE_UOFFSET))?; - self.try_push(0u8)?; - self.push_bytes_unprefixed(data)?; - self.try_push(data.len() as UOffsetT)?; - Ok(WIPOffset::new(self.used_space() as UOffsetT)) + WIPOffset::new(self.create_byte_string(s.as_bytes()).value()) } /// Create a zero-terminated byte vector. #[inline] pub fn create_byte_string(&mut self, data: &[u8]) -> WIPOffset<&'fbb [u8]> { - self.try_create_byte_string(data) - .expect("Flatbuffer allocation failure") + self.assert_not_nested( + "create_byte_string can not be called when a table or vector is under construction", + ); + self.align(data.len() + 1, PushAlignment::new(SIZE_UOFFSET)); + self.push(0u8); + self.push_bytes_unprefixed(data); + self.push(data.len() as UOffsetT); + WIPOffset::new(self.used_space() as UOffsetT) } - /// Fallible version of [`create_vector`](Self::create_vector). + /// Create a vector of Push-able objects. + /// + /// Speed-sensitive users may wish to reduce memory usage by creating the + /// vector manually: use `start_vector`, `push`, and `end_vector`. #[inline] - pub fn try_create_vector<'a: 'b, 'b, T: Push + 'b>( + pub fn create_vector<'a: 'b, 'b, T: Push + 'b>( &'a mut self, items: &'b [T], - ) -> Result>, A::Error> { + ) -> WIPOffset> { let elem_size = T::size(); let slice_size = items.len() * elem_size; - self.align(slice_size, T::alignment().max_of(SIZE_UOFFSET))?; - self.ensure_capacity(slice_size + UOffsetT::size())?; + self.align(slice_size, T::alignment().max_of(SIZE_UOFFSET)); + self.ensure_capacity(slice_size + UOffsetT::size()); self.head -= slice_size; let mut written_len = self.head.distance_to_end(); @@ -660,38 +430,7 @@ impl<'fbb, A: Allocator> FlatBufferBuilder<'fbb, A> { unsafe { item.push(out, written_len) }; } - Ok(WIPOffset::new( - self.try_push::(items.len() as UOffsetT)?.value(), - )) - } - - /// Create a vector of Push-able objects. - /// - /// Speed-sensitive users may wish to reduce memory usage by creating the - /// vector manually: use `start_vector`, `push`, and `end_vector`. - #[inline] - pub fn create_vector<'a: 'b, 'b, T: Push + 'b>( - &'a mut self, - items: &'b [T], - ) -> WIPOffset> { - self.try_create_vector(items) - .expect("Flatbuffer allocation failure") - } - - /// Fallible version of [`create_vector_from_iter`](Self::create_vector_from_iter). - #[inline] - pub fn try_create_vector_from_iter( - &mut self, - items: impl ExactSizeIterator + DoubleEndedIterator, - ) -> Result>, A::Error> { - let elem_size = T::size(); - self.align(items.len() * elem_size, T::alignment().max_of(SIZE_UOFFSET))?; - let mut actual = 0; - for item in items.rev() { - self.try_push(item)?; - actual += 1; - } - Ok(WIPOffset::new(self.try_push::(actual)?.value())) + WIPOffset::new(self.push::(items.len() as UOffsetT).value()) } /// Create a vector of Push-able objects. @@ -703,8 +442,14 @@ impl<'fbb, A: Allocator> FlatBufferBuilder<'fbb, A> { &mut self, items: impl ExactSizeIterator + DoubleEndedIterator, ) -> WIPOffset> { - self.try_create_vector_from_iter(items) - .expect("Flatbuffer allocation failure") + let elem_size = T::size(); + self.align(items.len() * elem_size, T::alignment().max_of(SIZE_UOFFSET)); + let mut actual = 0; + for item in items.rev() { + self.push(item); + actual += 1; + } + WIPOffset::new(self.push::(actual).value()) } /// Set whether default values are stored. @@ -767,34 +512,13 @@ impl<'fbb, A: Allocator> FlatBufferBuilder<'fbb, A> { assert!(o != 0, "missing required field {}", assert_msg_name); } - /// Fallible version of [`finish_size_prefixed`](Self::finish_size_prefixed). - #[inline] - pub fn try_finish_size_prefixed( - &mut self, - root: WIPOffset, - file_identifier: Option<&str>, - ) -> Result<(), A::Error> { - self.finish_with_opts(root, file_identifier, true) - } - /// Finalize the FlatBuffer by: aligning it, pushing an optional file /// identifier on to it, pushing a size prefix on to it, and marking the /// internal state of the FlatBufferBuilder as `finished`. Afterwards, /// users can call `finished_data` to get the resulting data. #[inline] pub fn finish_size_prefixed(&mut self, root: WIPOffset, file_identifier: Option<&str>) { - self.try_finish_size_prefixed(root, file_identifier) - .expect("Flatbuffer allocation failure") - } - - /// Fallible version of [`finish`](Self::finish). - #[inline] - pub fn try_finish( - &mut self, - root: WIPOffset, - file_identifier: Option<&str>, - ) -> Result<(), A::Error> { - self.finish_with_opts(root, file_identifier, false) + self.finish_with_opts(root, file_identifier, true); } /// Finalize the FlatBuffer by: aligning it, pushing an optional file @@ -803,14 +527,7 @@ impl<'fbb, A: Allocator> FlatBufferBuilder<'fbb, A> { /// `finished_data` to get the resulting data. #[inline] pub fn finish(&mut self, root: WIPOffset, file_identifier: Option<&str>) { - self.try_finish(root, file_identifier) - .expect("Flatbuffer allocation failure") - } - - /// Fallible version of [`finish_minimal`](Self::finish_minimal). - #[inline] - pub fn try_finish_minimal(&mut self, root: WIPOffset) -> Result<(), A::Error> { - self.finish_with_opts(root, None, false) + self.finish_with_opts(root, file_identifier, false); } /// Finalize the FlatBuffer by: aligning it and marking the internal state @@ -818,8 +535,7 @@ impl<'fbb, A: Allocator> FlatBufferBuilder<'fbb, A> { /// `finished_data` to get the resulting data. #[inline] pub fn finish_minimal(&mut self, root: WIPOffset) { - self.try_finish_minimal(root) - .expect("Flatbuffer allocation failure") + self.finish_with_opts(root, None, false); } #[inline] @@ -837,13 +553,13 @@ impl<'fbb, A: Allocator> FlatBufferBuilder<'fbb, A> { fn write_vtable( &mut self, table_tail_revloc: WIPOffset, - ) -> Result, A::Error> { + ) -> WIPOffset { self.assert_nested("write_vtable"); // Write the vtable offset, which is the start of any Table. // We fill its value later. let object_revloc_to_vtable: WIPOffset = - WIPOffset::new(self.try_push::(0xF0F0_F0F0)?.value()); + WIPOffset::new(self.push::(0xF0F0_F0F0).value()); // Layout of the data this function will create when a new vtable is // needed. @@ -886,7 +602,7 @@ impl<'fbb, A: Allocator> FlatBufferBuilder<'fbb, A> { // fill the WIP vtable with zeros: let vtable_byte_len = get_vtable_byte_len(&self.field_locs); - self.make_space(vtable_byte_len)?; + self.make_space(vtable_byte_len); // compute the length of the table (not vtable!) in bytes: let table_object_size = object_revloc_to_vtable.value() - table_tail_revloc.value(); @@ -911,15 +627,13 @@ impl<'fbb, A: Allocator> FlatBufferBuilder<'fbb, A> { } } let new_vt_bytes = &self.allocator[vt_start_pos.range_to(vt_end_pos)]; - let found = self - .written_vtable_revpos - .binary_search_by(|old_vtable_revpos: &UOffsetT| { - let old_vtable_pos = self.allocator.len() - *old_vtable_revpos as usize; - // Safety: - // Already written vtables are valid by construction - let old_vtable = unsafe { VTable::init(&self.allocator, old_vtable_pos) }; - new_vt_bytes.cmp(old_vtable.as_bytes()) - }); + let found = self.written_vtable_revpos.binary_search_by(|old_vtable_revpos: &UOffsetT| { + let old_vtable_pos = self.allocator.len() - *old_vtable_revpos as usize; + // Safety: + // Already written vtables are valid by construction + let old_vtable = unsafe { VTable::init(&self.allocator, old_vtable_pos) }; + new_vt_bytes.cmp(old_vtable.as_bytes()) + }); let final_vtable_revpos = match found { Ok(i) => { // The new vtable is a duplicate so clear it. @@ -957,18 +671,17 @@ impl<'fbb, A: Allocator> FlatBufferBuilder<'fbb, A> { self.field_locs.clear(); - Ok(object_revloc_to_vtable) + object_revloc_to_vtable } // Only call this when you know it is safe to double the size of the buffer. #[inline] - fn grow_allocator(&mut self) -> Result<(), A::Error> { + fn grow_allocator(&mut self) { let starting_active_size = self.used_space(); - self.allocator.grow_downwards()?; + self.allocator.grow_downwards().expect("Flatbuffer allocation failure"); let ending_active_size = self.used_space(); debug_assert_eq!(starting_active_size, ending_active_size); - Ok(()) } // with or without a size prefix changes how we load the data, so finish* @@ -978,7 +691,7 @@ impl<'fbb, A: Allocator> FlatBufferBuilder<'fbb, A> { root: WIPOffset, file_identifier: Option<&str>, size_prefixed: bool, - ) -> Result<(), A::Error> { + ) { self.assert_not_finished("buffer cannot be finished when it is already finished"); self.assert_not_nested( "buffer cannot be finished when a table or vector is under construction", @@ -991,40 +704,34 @@ impl<'fbb, A: Allocator> FlatBufferBuilder<'fbb, A> { // for the size prefix: let b = if size_prefixed { SIZE_UOFFSET } else { 0 }; // for the file identifier (a string that is not zero-terminated): - let c = if file_identifier.is_some() { - FILE_IDENTIFIER_LENGTH - } else { - 0 - }; + let c = if file_identifier.is_some() { FILE_IDENTIFIER_LENGTH } else { 0 }; a + b + c }; { let ma = PushAlignment::new(self.min_align); - self.align(to_align, ma)?; + self.align(to_align, ma); } if let Some(ident) = file_identifier { debug_assert_eq!(ident.len(), FILE_IDENTIFIER_LENGTH); - self.push_bytes_unprefixed(ident.as_bytes())?; + self.push_bytes_unprefixed(ident.as_bytes()); } - self.try_push(root)?; + self.push(root); if size_prefixed { let sz = self.used_space() as UOffsetT; - self.try_push::(sz)?; + self.push::(sz); } self.finished = true; - Ok(()) } #[inline] - fn align(&mut self, len: usize, alignment: PushAlignment) -> Result<(), A::Error> { + fn align(&mut self, len: usize, alignment: PushAlignment) { self.track_min_align(alignment.value()); let s = self.used_space() as usize; - self.make_space(padding_bytes(s + len, alignment.value()))?; - Ok(()) + self.make_space(padding_bytes(s + len, alignment.value())); } #[inline] @@ -1033,34 +740,31 @@ impl<'fbb, A: Allocator> FlatBufferBuilder<'fbb, A> { } #[inline] - fn push_bytes_unprefixed(&mut self, x: &[u8]) -> Result { - let n = self.make_space(x.len())?; + fn push_bytes_unprefixed(&mut self, x: &[u8]) -> UOffsetT { + let n = self.make_space(x.len()); self.allocator[n.range_to(n + x.len())].copy_from_slice(x); - Ok(n.to_forward_index(&self.allocator) as UOffsetT) + n.to_forward_index(&self.allocator) as UOffsetT } #[inline] - fn make_space(&mut self, want: usize) -> Result { - self.ensure_capacity(want)?; + fn make_space(&mut self, want: usize) -> ReverseIndex { + self.ensure_capacity(want); self.head -= want; - Ok(self.head) + self.head } #[inline] - fn ensure_capacity(&mut self, want: usize) -> Result { + fn ensure_capacity(&mut self, want: usize) -> usize { if self.unused_ready_space() >= want { - return Ok(want); + return want; } - assert!( - want <= FLATBUFFERS_MAX_BUFFER_SIZE, - "cannot grow buffer beyond 2 gigabytes" - ); + assert!(want <= FLATBUFFERS_MAX_BUFFER_SIZE, "cannot grow buffer beyond 2 gigabytes"); while self.unused_ready_space() < want { - self.grow_allocator()?; + self.grow_allocator(); } - Ok(want) + want } #[inline] fn unused_ready_space(&self) -> usize { @@ -1227,33 +931,6 @@ impl IndexMut for [T] { #[cfg(test)] mod tests { use super::*; - use core::sync::atomic::{AtomicUsize, Ordering}; - use std::alloc::{GlobalAlloc, Layout, System}; - - static ALLOC_COUNT: AtomicUsize = AtomicUsize::new(0); - - struct CountingAllocator; - - unsafe impl GlobalAlloc for CountingAllocator { - unsafe fn alloc(&self, layout: Layout) -> *mut u8 { - ALLOC_COUNT.fetch_add(1, Ordering::Relaxed); - unsafe { System.alloc(layout) } - } - unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { - unsafe { System.dealloc(ptr, layout) } - } - } - - #[global_allocator] - static GLOBAL: CountingAllocator = CountingAllocator; - - fn reset_alloc_count() { - ALLOC_COUNT.store(0, Ordering::Relaxed); - } - - fn alloc_count() -> usize { - ALLOC_COUNT.load(Ordering::Relaxed) - } #[test] fn reverse_index_test() { @@ -1263,150 +940,4 @@ mod tests { assert_eq!(&buf[idx.range_to(idx + 1)], &[4]); assert_eq!(idx.to_forward_index(&buf), 4); } - - #[test] - fn with_internal_capacity_preallocates_vecs() { - let mut builder = FlatBufferBuilder::with_internal_capacity(64, 8, 16, 32); - - assert!(builder.allocator.len() >= 64); - assert!(builder.field_locs.capacity() >= 8); - assert!(builder.written_vtable_revpos.capacity() >= 16); - assert!(builder.strings_pool.capacity() >= 32); - - assert!(builder.field_locs.is_empty()); - assert!(builder.written_vtable_revpos.is_empty()); - assert!(builder.strings_pool.is_empty()); - - // Reset the allocation counter after builder construction - reset_alloc_count(); - - // Add a shared string and verify it lands in the pool - let s1 = builder.create_shared_string("hello"); - assert_eq!(builder.strings_pool.len(), 1); - - // Adding the same string again should reuse the pooled entry - let s2 = builder.create_shared_string("hello"); - assert_eq!(builder.strings_pool.len(), 1); - assert_eq!(s1.value(), s2.value()); - - // A different string should add a new entry - let _s3 = builder.create_shared_string("world"); - assert_eq!(builder.strings_pool.len(), 2); - - // With sufficient preallocated capacity, no additional allocations - // should have occurred for the internal vecs during the operations above - let allocs = alloc_count(); - assert_eq!( - allocs, 0, - "expected 0 allocations after builder construction, got {}", - allocs - ); - } - - /// A test allocator that fails after a specified number of grow operations. - struct FailingAllocator { - inner: DefaultAllocator, - grows_remaining: usize, - } - - #[derive(Debug, Clone, PartialEq, Eq)] - struct AllocationError; - - impl core::fmt::Display for AllocationError { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - write!(f, "allocation failed") - } - } - - impl FailingAllocator { - fn new(initial_size: usize, max_grows: usize) -> Self { - Self { - inner: DefaultAllocator::from_vec(vec![0u8; initial_size]), - grows_remaining: max_grows, - } - } - } - - impl Deref for FailingAllocator { - type Target = [u8]; - fn deref(&self) -> &Self::Target { - &self.inner - } - } - - impl DerefMut for FailingAllocator { - fn deref_mut(&mut self) -> &mut Self::Target { - &mut self.inner - } - } - - unsafe impl Allocator for FailingAllocator { - type Error = AllocationError; - - fn grow_downwards(&mut self) -> Result<(), Self::Error> { - if self.grows_remaining == 0 { - return Err(AllocationError); - } - self.grows_remaining -= 1; - // DefaultAllocator returns Infallible, so unwrap is safe - self.inner.grow_downwards().unwrap(); - Ok(()) - } - - fn len(&self) -> usize { - self.inner.len() - } - } - - #[test] - fn try_push_propagates_allocation_error() { - let allocator = FailingAllocator::new(1, 0); - let mut builder = FlatBufferBuilder::new_in(allocator); - - let result = builder.try_push::(0x1234567890ABCDEF); - assert!(result.is_err()); - } - - #[test] - fn try_create_string_propagates_allocation_error() { - let allocator = FailingAllocator::new(1, 0); - let mut builder = FlatBufferBuilder::new_in(allocator); - - let result = builder.try_create_string("hello world"); - assert!(result.is_err()); - } - - #[test] - fn try_create_vector_propagates_allocation_error() { - let allocator = FailingAllocator::new(1, 0); - let mut builder = FlatBufferBuilder::new_in(allocator); - - let result = builder.try_create_vector(&[1u32, 2, 3, 4, 5]); - assert!(result.is_err()); - } - - #[test] - fn try_methods_succeed_with_sufficient_capacity() { - let allocator = FailingAllocator::new(1, 10); - let mut builder = FlatBufferBuilder::new_in(allocator); - - let result = builder.try_create_string("hello"); - assert!(result.is_ok()); - - let result = builder.try_create_vector(&[1u32, 2, 3]); - assert!(result.is_ok()); - } - - #[test] - fn try_finish_propagates_allocation_error() { - let allocator = FailingAllocator::new(1, 3); - let mut builder = FlatBufferBuilder::new_in(allocator); - - let start = builder.start_table(); - let table = builder - .try_end_table(start) - .expect("end_table should succeed with 3 grows"); - let result = builder.try_finish_minimal(table); - assert!(result.is_err(), "finish should fail after grows exhausted"); - } } diff --git a/rust/flatbuffers/src/vector.rs b/rust/flatbuffers/src/vector.rs index 17a3a1698..2078a76df 100644 --- a/rust/flatbuffers/src/vector.rs +++ b/rust/flatbuffers/src/vector.rs @@ -107,20 +107,6 @@ impl<'a, T: Follow<'a> + 'a> Vector<'a, T> { key: K, f: fn(&>::Inner, &K) -> Ordering, ) -> Option { - self.lookup_index_by_key(key, f).map(|idx| self.get(idx)) - } - - /// Binary search by key, returning the index of the matching element. - /// - /// This is similar to `lookup_by_key`, but returns the index of the found - /// element rather than the element itself. This is useful when you need - /// to reference elements by their position in the vector. - #[inline(always)] - pub fn lookup_index_by_key( - &self, - key: K, - f: fn(&>::Inner, &K) -> Ordering, - ) -> Option { if self.is_empty() { return None; } @@ -132,7 +118,7 @@ impl<'a, T: Follow<'a> + 'a> Vector<'a, T> { let mid = (left + right) / 2; let value = self.get(mid); match f(&value, &key) { - Ordering::Equal => return Some(mid), + Ordering::Equal => return Some(value), Ordering::Less => left = mid + 1, Ordering::Greater => { if mid == 0 { diff --git a/rust/flatbuffers/src/verifier.rs b/rust/flatbuffers/src/verifier.rs index e992279d5..a841bf7c9 100644 --- a/rust/flatbuffers/src/verifier.rs +++ b/rust/flatbuffers/src/verifier.rs @@ -492,8 +492,8 @@ impl<'ver, 'opts, 'buf> TableVerifier<'ver, 'opts, 'buf> { Ok(self) } _ => InvalidFlatbuffer::new_inconsistent_union( - val_field_name.into(), key_field_name.into(), + val_field_name.into(), ), } } diff --git a/rust/reflection/src/reflection_verifier.rs b/rust/reflection/src/reflection_verifier.rs index be492c762..524efbd40 100644 --- a/rust/reflection/src/reflection_verifier.rs +++ b/rust/reflection/src/reflection_verifier.rs @@ -397,8 +397,8 @@ fn verify_union<'a, 'b, 'c>( } } else { return InvalidFlatbuffer::new_inconsistent_union( - field.name().to_string(), format!("{}_type", field.name()), + field.name().to_string(), )?; } diff --git a/samples/monster_generated.h b/samples/monster_generated.h index 5266397d3..9cf1abddb 100644 --- a/samples/monster_generated.h +++ b/samples/monster_generated.h @@ -643,7 +643,7 @@ inline ::flatbuffers::Offset Monster::Pack(::flatbuffers::FlatBufferBui auto _name = _o->name.empty() ? 0 : _fbb.CreateString(_o->name); auto _inventory = _o->inventory.size() ? _fbb.CreateVector(_o->inventory) : 0; auto _color = _o->color; - auto _weapons = _o->weapons.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->weapons.size(), [](size_t i, _VectorArgs *__va) { return MyGame::Sample::CreateWeapon(*__va->__fbb, __va->__o->weapons[i].get(), __va->__rehasher); }, &_va ) : 0; + auto _weapons = _o->weapons.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->weapons.size(), [](size_t i, _VectorArgs *__va) { return CreateWeapon(*__va->__fbb, __va->__o->weapons[i].get(), __va->__rehasher); }, &_va ) : 0; auto _equipped_type = _o->equipped.type; auto _equipped = _o->equipped.Pack(_fbb); auto _path = _o->path.size() ? _fbb.CreateVectorOfStructs(_o->path) : 0; diff --git a/samples/monster_generated.swift b/samples/monster_generated.swift index 0ef998757..6f04323d1 100644 --- a/samples/monster_generated.swift +++ b/samples/monster_generated.swift @@ -113,12 +113,12 @@ public struct MyGame_Sample_Vec3: NativeStruct, FlatbuffersVectorInitializable, } extension MyGame_Sample_Vec3: Encodable { + enum CodingKeys: String, CodingKey { case x = "x" case y = "y" case z = "z" } - public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) if x != 0.0 { @@ -161,7 +161,7 @@ public struct MyGame_Sample_Vec3_Mutable: FlatBufferStruct, FlatbuffersVectorIni } } -public struct MyGame_Sample_Monster: FlatBufferVerifiableTable, FlatbuffersVectorInitializable, ObjectAPIPacker { +public struct MyGame_Sample_Monster: FlatBufferTable, FlatbuffersVectorInitializable, Verifiable, ObjectAPIPacker { static func validateVersion() { FlatBuffersVersion_25_12_19() } public var __buffer: ByteBuffer! { return _accessor.bb } @@ -170,49 +170,51 @@ public struct MyGame_Sample_Monster: FlatBufferVerifiableTable, FlatbuffersVecto private init(_ t: Table) { _accessor = t } public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } - private struct VT { - static let pos: VOffset = 4 - static let mana: VOffset = 6 - static let hp: VOffset = 8 - static let name: VOffset = 10 - static let inventory: VOffset = 14 - static let color: VOffset = 16 - static let weapons: VOffset = 18 - static let equippedType: VOffset = 20 - static let equipped: VOffset = 22 - static let path: VOffset = 24 + 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(VT.pos); return o == 0 ? nil : _accessor.readBuffer(of: MyGame_Sample_Vec3.self, at: o) } - public var mutablePos: MyGame_Sample_Vec3_Mutable? { let o = _accessor.offset(VT.pos); return o == 0 ? nil : MyGame_Sample_Vec3_Mutable(_accessor.bb, o: o + _accessor.position) } - public var mana: Int16 { let o = _accessor.offset(VT.mana); return o == 0 ? 150 : _accessor.readBuffer(of: Int16.self, at: o) } - @discardableResult public func mutate(mana: Int16) -> Bool {let o = _accessor.offset(VT.mana); return _accessor.mutate(mana, index: o) } - public var hp: Int16 { let o = _accessor.offset(VT.hp); return o == 0 ? 100 : _accessor.readBuffer(of: Int16.self, at: o) } - @discardableResult public func mutate(hp: Int16) -> Bool {let o = _accessor.offset(VT.hp); return _accessor.mutate(hp, index: o) } - public var name: String? { let o = _accessor.offset(VT.name); return o == 0 ? nil : _accessor.string(at: o) } - public var nameSegmentArray: [UInt8]? { return _accessor.getVector(at: VT.name) } - public var inventory: FlatbufferVector { return _accessor.vector(at: VT.inventory, byteSize: 1) } - public func mutate(inventory: UInt8, at index: Int32) -> Bool { let o = _accessor.offset(VT.inventory); return _accessor.directMutate(inventory, index: _accessor.vector(at: o) + index * 1) } - public func withUnsafePointerToInventory(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VT.inventory, body: body) } - public var color: MyGame_Sample_Color { let o = _accessor.offset(VT.color); 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(VT.color); return _accessor.mutate(color.rawValue, index: o) } - public var weapons: FlatbufferVector { return _accessor.vector(at: VT.weapons, byteSize: 4) } - public var equippedType: MyGame_Sample_Equipment { let o = _accessor.offset(VT.equippedType); return o == 0 ? .none_ : MyGame_Sample_Equipment(rawValue: _accessor.readBuffer(of: UInt8.self, at: o)) ?? .none_ } - public func equipped(type: T.Type) -> T? { let o = _accessor.offset(VT.equipped); return o == 0 ? nil : _accessor.union(o) } - public var path: FlatbufferVector { return _accessor.vector(at: VT.path, byteSize: 12) } - public var mutablePath: FlatbufferVector { return _accessor.vector(at: VT.path, byteSize: 12) } - public func withUnsafePointerToPath(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VT.path, body: body) } + 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.position) } + 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 inventory: FlatbufferVector { return _accessor.vector(at: VTOFFSET.inventory.v, byteSize: 1) } + 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 func withUnsafePointerToInventory(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VTOFFSET.inventory.v, body: body) } + 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 weapons: FlatbufferVector { return _accessor.vector(at: VTOFFSET.weapons.v, byteSize: 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(type: T.Type) -> T? { let o = _accessor.offset(VTOFFSET.equipped.v); return o == 0 ? nil : _accessor.union(o) } + public var path: FlatbufferVector { return _accessor.vector(at: VTOFFSET.path.v, byteSize: 12) } + public var mutablePath: FlatbufferVector { return _accessor.vector(at: VTOFFSET.path.v, byteSize: 12) } + public func withUnsafePointerToPath(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VTOFFSET.path.v, body: body) } 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: VT.pos) } - public static func add(mana: Int16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: mana, def: 150, at: VT.mana) } - public static func add(hp: Int16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: hp, def: 100, at: VT.hp) } - public static func add(name: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: name, at: VT.name) } - public static func addVectorOf(inventory: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: inventory, at: VT.inventory) } - public static func add(color: MyGame_Sample_Color, _ fbb: inout FlatBufferBuilder) { fbb.add(element: color.rawValue, def: 2, at: VT.color) } - public static func addVectorOf(weapons: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: weapons, at: VT.weapons) } - public static func add(equippedType: MyGame_Sample_Equipment, _ fbb: inout FlatBufferBuilder) { fbb.add(element: equippedType.rawValue, def: 0, at: VT.equippedType) } - public static func add(equipped: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: equipped, at: VT.equipped) } - public static func addVectorOf(path: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: path, at: VT.path) } + 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.size, elementSize: MemoryLayout.alignment) } @@ -291,14 +293,14 @@ public struct MyGame_Sample_Monster: FlatBufferVerifiableTable, FlatbuffersVecto public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { var _v = try verifier.visitTable(at: position) - try _v.visit(field: VT.pos, fieldName: "pos", required: false, type: MyGame_Sample_Vec3.self) - try _v.visit(field: VT.mana, fieldName: "mana", required: false, type: Int16.self) - try _v.visit(field: VT.hp, fieldName: "hp", required: false, type: Int16.self) - try _v.visit(field: VT.name, fieldName: "name", required: false, type: ForwardOffset.self) - try _v.visit(field: VT.inventory, fieldName: "inventory", required: false, type: ForwardOffset>.self) - try _v.visit(field: VT.color, fieldName: "color", required: false, type: MyGame_Sample_Color.self) - try _v.visit(field: VT.weapons, fieldName: "weapons", required: false, type: ForwardOffset, MyGame_Sample_Weapon>>.self) - try _v.visit(unionKey: VT.equippedType, unionField: VT.equipped, unionKeyName: "equippedType", fieldName: "equipped", required: false, completion: { (verifier, key: MyGame_Sample_Equipment, pos) in + try _v.visit(field: VTOFFSET.pos.p, fieldName: "pos", required: false, type: MyGame_Sample_Vec3.self) + try _v.visit(field: VTOFFSET.mana.p, fieldName: "mana", required: false, type: Int16.self) + try _v.visit(field: VTOFFSET.hp.p, fieldName: "hp", required: false, type: Int16.self) + try _v.visit(field: VTOFFSET.name.p, fieldName: "name", required: false, type: ForwardOffset.self) + try _v.visit(field: VTOFFSET.inventory.p, fieldName: "inventory", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.color.p, fieldName: "color", required: false, type: MyGame_Sample_Color.self) + try _v.visit(field: VTOFFSET.weapons.p, fieldName: "weapons", required: false, type: ForwardOffset, MyGame_Sample_Weapon>>.self) + try _v.visit(unionKey: VTOFFSET.equippedType.p, unionField: VTOFFSET.equipped.p, unionKeyName: "equippedType", fieldName: "equipped", required: false, completion: { (verifier, key: MyGame_Sample_Equipment, pos) in switch key { case .none_: break // NOTE - SWIFT doesnt support none @@ -306,12 +308,13 @@ public struct MyGame_Sample_Monster: FlatBufferVerifiableTable, FlatbuffersVecto try ForwardOffset.verify(&verifier, at: pos, of: MyGame_Sample_Weapon.self) } }) - try _v.visit(field: VT.path, fieldName: "path", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.path.p, fieldName: "path", required: false, type: ForwardOffset>.self) _v.finish() } } extension MyGame_Sample_Monster: Encodable { + enum CodingKeys: String, CodingKey { case pos = "pos" case mana = "mana" @@ -324,7 +327,6 @@ extension MyGame_Sample_Monster: Encodable { case equipped = "equipped" case path = "path" } - public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(pos, forKey: .pos) @@ -400,7 +402,7 @@ public class MyGame_Sample_MonsterT: NativeObject { public func serialize() -> ByteBuffer { return serialize(type: MyGame_Sample_Monster.self) } } -public struct MyGame_Sample_Weapon: FlatBufferVerifiableTable, FlatbuffersVectorInitializable, ObjectAPIPacker { +public struct MyGame_Sample_Weapon: FlatBufferTable, FlatbuffersVectorInitializable, Verifiable, ObjectAPIPacker { static func validateVersion() { FlatBuffersVersion_25_12_19() } public var __buffer: ByteBuffer! { return _accessor.bb } @@ -409,18 +411,20 @@ public struct MyGame_Sample_Weapon: FlatBufferVerifiableTable, FlatbuffersVector private init(_ t: Table) { _accessor = t } public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } - private struct VT { - static let name: VOffset = 4 - static let damage: VOffset = 6 + 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(VT.name); return o == 0 ? nil : _accessor.string(at: o) } - public var nameSegmentArray: [UInt8]? { return _accessor.getVector(at: VT.name) } - public var damage: Int16 { let o = _accessor.offset(VT.damage); return o == 0 ? 0 : _accessor.readBuffer(of: Int16.self, at: o) } - @discardableResult public func mutate(damage: Int16) -> Bool {let o = _accessor.offset(VT.damage); return _accessor.mutate(damage, 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 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: VT.name) } - public static func add(damage: Int16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: damage, def: 0, at: VT.damage) } + 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, @@ -457,18 +461,18 @@ public struct MyGame_Sample_Weapon: FlatBufferVerifiableTable, FlatbuffersVector public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { var _v = try verifier.visitTable(at: position) - try _v.visit(field: VT.name, fieldName: "name", required: false, type: ForwardOffset.self) - try _v.visit(field: VT.damage, fieldName: "damage", required: false, type: Int16.self) + try _v.visit(field: VTOFFSET.name.p, fieldName: "name", required: false, type: ForwardOffset.self) + try _v.visit(field: VTOFFSET.damage.p, fieldName: "damage", required: false, type: Int16.self) _v.finish() } } extension MyGame_Sample_Weapon: Encodable { + enum CodingKeys: String, CodingKey { case name = "name" case damage = "damage" } - public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(name, forKey: .name) diff --git a/samples/rust_generated/mod.rs b/samples/rust_generated/mod.rs index 50e577aa1..5f7e92453 100644 --- a/samples/rust_generated/mod.rs +++ b/samples/rust_generated/mod.rs @@ -1,18 +1,18 @@ // Automatically generated by the Flatbuffers compiler. Do not modify. // @generated pub mod my_game { + use super::*; + pub mod sample { 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 + 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 index df74180e1..34b82ac7b 100644 --- a/samples/rust_generated/my_game/sample/color_generated.rs +++ b/samples/rust_generated/my_game/sample/color_generated.rs @@ -2,73 +2,64 @@ // @generated extern crate alloc; 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, + 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 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, - } + 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 ::core::fmt::Debug for Color { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - if let Some(name) = self.variant_name() { - f.write_str(name) - } else { - f.write_fmt(format_args!("", self.0)) - } + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) } + } } - impl<'a> ::flatbuffers::Follow<'a> for Color { - type Inner = Self; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; - Self(b) - } + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; + Self(b) + } } impl ::flatbuffers::Push for Color { type Output = Color; - #[inline] unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { unsafe { ::flatbuffers::emplace_scalar::(dst, self.0) }; @@ -76,28 +67,26 @@ impl ::flatbuffers::Push for Color { } impl ::flatbuffers::EndianScalar for Color { - type Scalar = i8; - - #[inline] - fn to_little_endian(self) -> i8 { - self.0.to_le() - } - - #[inline] - #[allow(clippy::wrong_self_convention)] - fn from_little_endian(v: i8) -> Self { - let b = i8::from_le(v); - Self(b) - } + type Scalar = i8; + #[inline] + fn to_little_endian(self) -> i8 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: i8) -> Self { + let b = i8::from_le(v); + Self(b) + } } impl<'a> ::flatbuffers::Verifiable for Color { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - i8::run_verifier(v, pos) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + 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 index e347757e1..f53f8f20b 100644 --- a/samples/rust_generated/my_game/sample/equipment_generated.rs +++ b/samples/rust_generated/my_game/sample/equipment_generated.rs @@ -2,69 +2,60 @@ // @generated extern crate alloc; 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, + 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 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, - } + 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 ::core::fmt::Debug for Equipment { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - if let Some(name) = self.variant_name() { - f.write_str(name) - } else { - f.write_fmt(format_args!("", self.0)) - } + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) } + } } - impl<'a> ::flatbuffers::Follow<'a> for Equipment { - type Inner = Self; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; - Self(b) - } + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; + Self(b) + } } impl ::flatbuffers::Push for Equipment { type Output = Equipment; - #[inline] unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { unsafe { ::flatbuffers::emplace_scalar::(dst, self.0) }; @@ -72,85 +63,75 @@ impl ::flatbuffers::Push for Equipment { } impl ::flatbuffers::EndianScalar for Equipment { - type Scalar = u8; - - #[inline] - fn to_little_endian(self) -> u8 { - self.0.to_le() - } - - #[inline] - #[allow(clippy::wrong_self_convention)] - fn from_little_endian(v: u8) -> Self { - let b = u8::from_le(v); - Self(b) - } + type Scalar = u8; + #[inline] + fn to_little_endian(self) -> u8 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: u8) -> Self { + let b = u8::from_le(v); + Self(b) + } } impl<'a> ::flatbuffers::Verifiable for Equipment { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - u8::run_verifier(v, pos) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + 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(alloc::boxed::Box), + NONE, + Weapon(alloc::boxed::Box), } - impl Default for EquipmentT { - fn default() -> Self { - Self::NONE - } + 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 equipment_type(&self) -> Equipment { + match self { + Self::NONE => Equipment::NONE, + Self::Weapon(_) => Equipment::Weapon, } - - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>(&self, fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A>) -> Option<::flatbuffers::WIPOffset<::flatbuffers::UnionWIPOffset>> { - match self { - Self::NONE => None, - Self::Weapon(v) => Some(v.pack(fbb).as_union_value()), - } + } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>(&self, fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A>) -> 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> { - if let Self::Weapon(_) = self { - let v = ::core::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 } + } + /// If the union variant matches, return the owned WeaponT, setting the union to NONE. + pub fn take_weapon(&mut self) -> Option> { + if let Self::Weapon(_) = self { + let v = ::core::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 index fa36fbf11..381091dd7 100644 --- a/samples/rust_generated/my_game/sample/monster_generated.rs +++ b/samples/rust_generated/my_game/sample/monster_generated.rs @@ -2,225 +2,212 @@ // @generated extern crate alloc; use super::*; - pub enum MonsterOffset {} - #[derive(Copy, Clone, PartialEq)] + pub struct Monster<'a> { - pub _tab: ::flatbuffers::Table<'a>, + pub _tab: ::flatbuffers::Table<'a>, } impl<'a> ::flatbuffers::Follow<'a> for Monster<'a> { - type Inner = Monster<'a>; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } - } + type Inner = Monster<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: unsafe { ::flatbuffers::Table::new(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 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" - } + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Sample.Monster" + } - #[inline] - pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { - Monster { _tab: table } - } + #[inline] + pub unsafe 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, A: ::flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args MonsterArgs<'args> + ) -> ::flatbuffers::WIPOffset> { + 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() + } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args MonsterArgs<'args> - ) -> ::flatbuffers::WIPOffset> { - 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| { + alloc::string::ToString::to_string(x) + }); + let inventory = self.inventory().map(|x| { + x.into_iter().collect() + }); + 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(alloc::boxed::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, } + } - 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| { - alloc::string::ToString::to_string(x) - }); - let inventory = self.inventory().map(|x| { - x.into_iter().collect() - }); - 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(alloc::boxed::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> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_POS, None)} + } + #[inline] + pub fn mana(&self) -> i16 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_MANA, Some(150)).unwrap()} + } + #[inline] + pub fn hp(&self) -> i16 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_HP, Some(100)).unwrap()} + } + #[inline] + pub fn name(&self) -> Option<&'a str> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<&str>>(Monster::VT_NAME, None)} + } + #[inline] + pub fn inventory(&self) -> Option<::flatbuffers::Vector<'a, u8>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, u8>>>(Monster::VT_INVENTORY, None)} + } + #[inline] + pub fn color(&self) -> Color { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_COLOR, Some(Color::Blue)).unwrap()} + } + #[inline] + pub fn weapons(&self) -> Option<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset>>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset>>>(Monster::VT_WEAPONS, None)} + } + #[inline] + pub fn equipped_type(&self) -> Equipment { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_EQUIPPED_TYPE, Some(Equipment::NONE)).unwrap()} + } + #[inline] + pub fn equipped(&self) -> Option<::flatbuffers::Table<'a>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Table<'a>>>(Monster::VT_EQUIPPED, None)} + } + #[inline] + pub fn path(&self) -> Option<::flatbuffers::Vector<'a, Vec3>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, Vec3>>>(Monster::VT_PATH, None)} + } + #[inline] + #[allow(non_snake_case)] + pub fn equipped_as_weapon(&self) -> Option> { + if self.equipped_type() == Equipment::Weapon { + self.equipped().map(|t| { + // Safety: + // Created from a valid Table for this object + // Which contains a valid union in this slot + unsafe { Weapon::init_from_table(t) } + }) + } else { + None } + } - #[inline] - pub fn pos(&self) -> Option<&'a Vec3> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_POS, None)} - } - - #[inline] - pub fn mana(&self) -> i16 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_MANA, Some(150)).unwrap()} - } - - #[inline] - pub fn hp(&self) -> i16 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_HP, Some(100)).unwrap()} - } - - #[inline] - pub fn name(&self) -> Option<&'a str> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<&str>>(Monster::VT_NAME, None)} - } - - #[inline] - pub fn inventory(&self) -> Option<::flatbuffers::Vector<'a, u8>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, u8>>>(Monster::VT_INVENTORY, None)} - } - - #[inline] - pub fn color(&self) -> Color { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_COLOR, Some(Color::Blue)).unwrap()} - } - - #[inline] - pub fn weapons(&self) -> Option<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset>>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset>>>(Monster::VT_WEAPONS, None)} - } - - #[inline] - pub fn equipped_type(&self) -> Equipment { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_EQUIPPED_TYPE, Some(Equipment::NONE)).unwrap()} - } - - #[inline] - pub fn equipped(&self) -> Option<::flatbuffers::Table<'a>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Table<'a>>>(Monster::VT_EQUIPPED, None)} - } - - #[inline] - pub fn path(&self) -> Option<::flatbuffers::Vector<'a, Vec3>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, Vec3>>>(Monster::VT_PATH, None)} - } - - #[inline] - #[allow(non_snake_case)] - pub fn equipped_as_weapon(&self) -> Option> { - if self.equipped_type() == Equipment::Weapon { - self.equipped().map(|t| { - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - unsafe { Weapon::init_from_table(t) } - }) - } else { - None - } - } } impl ::flatbuffers::Verifiable for Monster<'_> { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.visit_table(pos)? - .visit_field::("pos", Self::VT_POS, false)? - .visit_field::("mana", Self::VT_MANA, false)? - .visit_field::("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", Self::VT_COLOR, false)? - .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, ::flatbuffers::ForwardsUOffset>>>("weapons", Self::VT_WEAPONS, false)? - .visit_union::("equipped_type", Self::VT_EQUIPPED_TYPE, "equipped", Self::VT_EQUIPPED, false, |key, v, pos| { - match key { - Equipment::Weapon => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("Equipment::Weapon", pos), - _ => Ok(()), - } - })? - .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, Vec3>>>("path", Self::VT_PATH, false)? - .finish(); - Ok(()) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.visit_table(pos)? + .visit_field::("pos", Self::VT_POS, false)? + .visit_field::("mana", Self::VT_MANA, false)? + .visit_field::("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", Self::VT_COLOR, false)? + .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, ::flatbuffers::ForwardsUOffset>>>("weapons", Self::VT_WEAPONS, false)? + .visit_union::("equipped_type", Self::VT_EQUIPPED_TYPE, "equipped", Self::VT_EQUIPPED, false, |key, v, pos| { + match key { + Equipment::Weapon => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("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, @@ -233,273 +220,246 @@ pub struct MonsterArgs<'a> { 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, - } + #[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, A: ::flatbuffers::Allocator + 'a> { - fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, + fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, + start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, } - impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> MonsterBuilder<'a, 'b, A> { - #[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::(Monster::VT_MANA, mana, 150); - } - - #[inline] - pub fn add_hp(&mut self, hp: i16) { - self.fbb_.push_slot::(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::(Monster::VT_COLOR, color, Color::Blue); - } - - #[inline] - pub fn add_weapons(&mut self, weapons: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , ::flatbuffers::ForwardsUOffset>>>) { - 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::(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, A>) -> MonsterBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - MonsterBuilder { - fbb_: _fbb, - start_: start, - } - } - - #[inline] - pub fn finish(self) -> ::flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - ::flatbuffers::WIPOffset::new(o.value()) + #[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::(Monster::VT_MANA, mana, 150); + } + #[inline] + pub fn add_hp(&mut self, hp: i16) { + self.fbb_.push_slot::(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::(Monster::VT_COLOR, color, Color::Blue); + } + #[inline] + pub fn add_weapons(&mut self, weapons: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , ::flatbuffers::ForwardsUOffset>>>) { + 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::(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, A>) -> MonsterBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + MonsterBuilder { + fbb_: _fbb, + start_: start, } + } + #[inline] + pub fn finish(self) -> ::flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + ::flatbuffers::WIPOffset::new(o.value()) + } } impl ::core::fmt::Debug for Monster<'_> { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::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() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::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, - pub mana: i16, - pub hp: i16, - pub name: Option, - pub inventory: Option>, - pub color: Color, - pub weapons: Option>, - pub equipped: EquipmentT, - pub path: Option>, + pub pos: Option, + pub mana: i16, + pub hp: i16, + pub name: Option, + pub inventory: Option>, + pub color: Color, + pub weapons: Option>, + pub equipped: EquipmentT, + pub path: Option>, } - 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, - } + 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, A: ::flatbuffers::Allocator + 'b>( - &self, - _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> - ) -> ::flatbuffers::WIPOffset> { - 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: alloc::vec::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: alloc::vec::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, - }) - } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> + ) -> ::flatbuffers::WIPOffset> { + 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: alloc::vec::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: alloc::vec::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] /// 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`. -#[inline] pub fn root_as_monster(buf: &[u8]) -> Result, ::flatbuffers::InvalidFlatbuffer> { - ::flatbuffers::root::(buf) + ::flatbuffers::root::(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`. -#[inline] pub fn size_prefixed_root_as_monster(buf: &[u8]) -> Result, ::flatbuffers::InvalidFlatbuffer> { - ::flatbuffers::size_prefixed_root::(buf) + ::flatbuffers::size_prefixed_root::(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`. -#[inline] pub fn root_as_monster_with_opts<'b, 'o>( - opts: &'o ::flatbuffers::VerifierOptions, - buf: &'b [u8], + opts: &'o ::flatbuffers::VerifierOptions, + buf: &'b [u8], ) -> Result, ::flatbuffers::InvalidFlatbuffer> { - ::flatbuffers::root_with_opts::>(opts, buf) + ::flatbuffers::root_with_opts::>(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`. -#[inline] pub fn size_prefixed_root_as_monster_with_opts<'b, 'o>( - opts: &'o ::flatbuffers::VerifierOptions, - buf: &'b [u8], + opts: &'o ::flatbuffers::VerifierOptions, + buf: &'b [u8], ) -> Result, ::flatbuffers::InvalidFlatbuffer> { - ::flatbuffers::size_prefixed_root_with_opts::>(opts, buf) + ::flatbuffers::size_prefixed_root_with_opts::>(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`. -#[inline] pub unsafe fn root_as_monster_unchecked(buf: &[u8]) -> Monster<'_> { - unsafe { ::flatbuffers::root_unchecked::(buf) } + unsafe { ::flatbuffers::root_unchecked::(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`. -#[inline] pub unsafe fn size_prefixed_root_as_monster_unchecked(buf: &[u8]) -> Monster<'_> { - unsafe { ::flatbuffers::size_prefixed_root_unchecked::(buf) } + unsafe { ::flatbuffers::size_prefixed_root_unchecked::(buf) } } - #[inline] pub fn finish_monster_buffer<'a, 'b, A: ::flatbuffers::Allocator + 'a>( fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - root: ::flatbuffers::WIPOffset> -) { - fbb.finish(root, None); + root: ::flatbuffers::WIPOffset>) { + fbb.finish(root, None); } #[inline] -pub fn finish_size_prefixed_monster_buffer<'a, 'b, A: ::flatbuffers::Allocator + 'a>( - fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - root: ::flatbuffers::WIPOffset> -) { - fbb.finish_size_prefixed(root, None); +pub fn finish_size_prefixed_monster_buffer<'a, 'b, A: ::flatbuffers::Allocator + 'a>(fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, root: ::flatbuffers::WIPOffset>) { + 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 index ec5b1ccd1..516246802 100644 --- a/samples/rust_generated/my_game/sample/vec_3_generated.rs +++ b/samples/rust_generated/my_game/sample/vec_3_generated.rs @@ -2,57 +2,47 @@ // @generated extern crate alloc; 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 Default for Vec3 { + fn default() -> Self { + Self([0; 12]) + } } - impl ::core::fmt::Debug for Vec3 { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - f.debug_struct("Vec3") - .field("x", &self.x()) - .field("y", &self.y()) - .field("z", &self.z()) - .finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::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<'a> ::flatbuffers::Follow<'a> for Vec3 { - type Inner = &'a Vec3; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - unsafe { <&'a Vec3>::follow(buf, loc) } - } + type Inner = &'a Vec3; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { <&'a Vec3>::follow(buf, loc) } + } } - impl<'a> ::flatbuffers::Follow<'a> for &'a Vec3 { - type Inner = &'a Vec3; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - unsafe { ::flatbuffers::follow_cast_ref::(buf, loc) } - } + type Inner = &'a Vec3; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { ::flatbuffers::follow_cast_ref::(buf, loc) } + } } - impl<'b> ::flatbuffers::Push for Vec3 { type Output = Vec3; - #[inline] unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { let src = unsafe { ::core::slice::from_raw_parts(self as *const Vec3 as *const u8, ::size()) }; dst.copy_from_slice(src); } - #[inline] fn alignment() -> ::flatbuffers::PushAlignment { ::flatbuffers::PushAlignment::new(4) @@ -60,150 +50,141 @@ impl<'b> ::flatbuffers::Push for Vec3 { } impl<'a> ::flatbuffers::Verifiable for Vec3 { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.in_buffer::(pos) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.in_buffer::(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 - } + #[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 const fn get_fully_qualified_name() -> &'static str { + "MyGame.Sample.Vec3" + } - pub fn x(&self) -> f32 { - let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - ::flatbuffers::EndianScalar::from_little_endian(unsafe { - ::core::ptr::copy_nonoverlapping( - self.0[0..].as_ptr(), - mem.as_mut_ptr() as *mut u8, - ::core::mem::size_of::<::Scalar>(), - ); - mem.assume_init() - }) - } + pub fn x(&self) -> f32 { + let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + ::flatbuffers::EndianScalar::from_little_endian(unsafe { + ::core::ptr::copy_nonoverlapping( + self.0[0..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + ::core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } - pub fn set_x(&mut self, x: f32) { - let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - unsafe { - ::core::ptr::copy_nonoverlapping( - &x_le as *const _ as *const u8, - self.0[0..].as_mut_ptr(), - ::core::mem::size_of::<::Scalar>(), - ); - } + pub fn set_x(&mut self, x: f32) { + let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + ::core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[0..].as_mut_ptr(), + ::core::mem::size_of::<::Scalar>(), + ); } + } - pub fn y(&self) -> f32 { - let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - ::flatbuffers::EndianScalar::from_little_endian(unsafe { - ::core::ptr::copy_nonoverlapping( - self.0[4..].as_ptr(), - mem.as_mut_ptr() as *mut u8, - ::core::mem::size_of::<::Scalar>(), - ); - mem.assume_init() - }) - } + pub fn y(&self) -> f32 { + let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + ::flatbuffers::EndianScalar::from_little_endian(unsafe { + ::core::ptr::copy_nonoverlapping( + self.0[4..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + ::core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } - pub fn set_y(&mut self, x: f32) { - let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - unsafe { - ::core::ptr::copy_nonoverlapping( - &x_le as *const _ as *const u8, - self.0[4..].as_mut_ptr(), - ::core::mem::size_of::<::Scalar>(), - ); - } + pub fn set_y(&mut self, x: f32) { + let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + ::core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[4..].as_mut_ptr(), + ::core::mem::size_of::<::Scalar>(), + ); } + } - pub fn z(&self) -> f32 { - let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - ::flatbuffers::EndianScalar::from_little_endian(unsafe { - ::core::ptr::copy_nonoverlapping( - self.0[8..].as_ptr(), - mem.as_mut_ptr() as *mut u8, - ::core::mem::size_of::<::Scalar>(), - ); - mem.assume_init() - }) - } + pub fn z(&self) -> f32 { + let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + ::flatbuffers::EndianScalar::from_little_endian(unsafe { + ::core::ptr::copy_nonoverlapping( + self.0[8..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + ::core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } - pub fn set_z(&mut self, x: f32) { - let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - unsafe { - ::core::ptr::copy_nonoverlapping( - &x_le as *const _ as *const u8, - self.0[8..].as_mut_ptr(), - ::core::mem::size_of::<::Scalar>(), - ); - } + pub fn set_z(&mut self, x: f32) { + let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + ::core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[8..].as_mut_ptr(), + ::core::mem::size_of::<::Scalar>(), + ); } + } - pub fn unpack(&self) -> Vec3T { - Vec3T { - x: self.x(), - y: self.y(), - z: self.z(), - } + pub fn unpack(&self) -> Vec3T { + Vec3T { + x: self.x(), + y: self.y(), + z: self.z(), } + } } -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Default)] pub struct Vec3T { - pub x: f32, - pub y: f32, - pub z: f32, + pub x: f32, + pub y: f32, + pub z: f32, } -impl Default for Vec3T { - fn default() -> Self { - Self { - x: 0.0, - y: 0.0, - z: 0.0, - } - } +impl Vec3T { + pub fn pack(&self) -> Vec3 { + Vec3::new( + self.x, + self.y, + self.z, + ) + } } -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 index f6598ecd9..7a4c2e79a 100644 --- a/samples/rust_generated/my_game/sample/weapon_generated.rs +++ b/samples/rust_generated/my_game/sample/weapon_generated.rs @@ -2,172 +2,159 @@ // @generated extern crate alloc; use super::*; - pub enum WeaponOffset {} - #[derive(Copy, Clone, PartialEq)] + pub struct Weapon<'a> { - pub _tab: ::flatbuffers::Table<'a>, + pub _tab: ::flatbuffers::Table<'a>, } impl<'a> ::flatbuffers::Follow<'a> for Weapon<'a> { - type Inner = Weapon<'a>; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } - } + type Inner = Weapon<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } + } } impl<'a> Weapon<'a> { - pub const VT_NAME: ::flatbuffers::VOffsetT = 4; - pub const VT_DAMAGE: ::flatbuffers::VOffsetT = 6; + 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" - } + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Sample.Weapon" + } - #[inline] - pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { - Weapon { _tab: table } - } + #[inline] + pub unsafe 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, A: ::flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args WeaponArgs<'args> + ) -> ::flatbuffers::WIPOffset> { + let mut builder = WeaponBuilder::new(_fbb); + if let Some(x) = args.name { builder.add_name(x); } + builder.add_damage(args.damage); + builder.finish() + } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args WeaponArgs<'args> - ) -> ::flatbuffers::WIPOffset> { - 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| { + alloc::string::ToString::to_string(x) + }); + let damage = self.damage(); + WeaponT { + name, + damage, } + } - pub fn unpack(&self) -> WeaponT { - let name = self.name().map(|x| { - alloc::string::ToString::to_string(x) - }); - let damage = self.damage(); - WeaponT { - name, - damage, - } - } - - #[inline] - pub fn name(&self) -> Option<&'a str> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<&str>>(Weapon::VT_NAME, None)} - } - - #[inline] - pub fn damage(&self) -> i16 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Weapon::VT_DAMAGE, Some(0)).unwrap()} - } + #[inline] + pub fn name(&self) -> Option<&'a str> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<&str>>(Weapon::VT_NAME, None)} + } + #[inline] + pub fn damage(&self) -> i16 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Weapon::VT_DAMAGE, Some(0)).unwrap()} + } } impl ::flatbuffers::Verifiable for Weapon<'_> { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.visit_table(pos)? - .visit_field::<::flatbuffers::ForwardsUOffset<&str>>("name", Self::VT_NAME, false)? - .visit_field::("damage", Self::VT_DAMAGE, false)? - .finish(); - Ok(()) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.visit_table(pos)? + .visit_field::<::flatbuffers::ForwardsUOffset<&str>>("name", Self::VT_NAME, false)? + .visit_field::("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, - } + #[inline] + fn default() -> Self { + WeaponArgs { + name: None, + damage: 0, } + } } pub struct WeaponBuilder<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> { - fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, + fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, + start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, } - impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> WeaponBuilder<'a, 'b, A> { - #[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::(Weapon::VT_DAMAGE, damage, 0); - } - - #[inline] - pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> WeaponBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - WeaponBuilder { - fbb_: _fbb, - start_: start, - } - } - - #[inline] - pub fn finish(self) -> ::flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - ::flatbuffers::WIPOffset::new(o.value()) + #[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::(Weapon::VT_DAMAGE, damage, 0); + } + #[inline] + pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> WeaponBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + WeaponBuilder { + fbb_: _fbb, + start_: start, } + } + #[inline] + pub fn finish(self) -> ::flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + ::flatbuffers::WIPOffset::new(o.value()) + } } impl ::core::fmt::Debug for Weapon<'_> { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - let mut ds = f.debug_struct("Weapon"); - ds.field("name", &self.name()); - ds.field("damage", &self.damage()); - ds.finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::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, - pub damage: i16, + pub name: Option, + pub damage: i16, } - impl Default for WeaponT { - fn default() -> Self { - Self { - name: None, - damage: 0, - } + fn default() -> Self { + Self { + name: None, + damage: 0, } + } } - impl WeaponT { - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( - &self, - _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> - ) -> ::flatbuffers::WIPOffset> { - let name = self.name.as_ref().map(|x|{ - _fbb.create_string(x) - }); - let damage = self.damage; - Weapon::create(_fbb, &WeaponArgs{ - name, - damage, - }) - } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> + ) -> ::flatbuffers::WIPOffset> { + 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/scripts/generate_code.py b/scripts/generate_code.py index b754ec58f..c06026c73 100755 --- a/scripts/generate_code.py +++ b/scripts/generate_code.py @@ -251,6 +251,21 @@ flatc( schema="vector_table_naked_ptr.fbs", ) +flatc( + [ + "--cpp", + "--gen-compare", + "--gen-mutable", + "--gen-object-api", + "--reflect-names", + "--cpp-include", + "test_vector_type.h", + "--cpp-vector-type", + "::flatbuffers::tests::CustomVector", + ], + schema="cpp_vector_type.fbs", +) + flatc( BASE_OPTS + CPP_OPTS + CS_OPTS + JAVA_OPTS + KOTLIN_OPTS + PHP_OPTS, prefix="union_vector", @@ -394,11 +409,6 @@ flatc( schema="native_inline_table_test.fbs", ) -flatc( - ["--cpp", "--gen-compare", "--gen-mutable", "--gen-object-api", "--reflect-names"], - schema="cross_namespace_pack_test.fbs", -) - flatc( RUST_OPTS, prefix="arrays_test", @@ -422,11 +432,6 @@ flatc( schema="nested_union_test.fbs", ) -flatc( - ["--python", "--gen-object-api"], - schema="union_name_test.fbs", -) - flatc( NO_INCL_OPTS + CPP_OPTS, schema="default_vectors_strings_test.fbs", @@ -527,13 +532,6 @@ flatc( cwd=swift_code_gen, ) -flatc( - SWIFT_OPTS_CODE_GEN + BASE_OPTS, - schema="empty_vtable.fbs", - cwd=swift_code_gen, - prefix="../../Tests/Flatbuffers/", -) - # Swift Wasm Tests swift_Wasm_prefix = "swift/Wasm.tests/Tests/FlatBuffers.Test.Swift.WasmTests" flatc( diff --git a/scripts/generate_grpc_examples.py b/scripts/generate_grpc_examples.py index 9571a6336..93058e7b3 100755 --- a/scripts/generate_grpc_examples.py +++ b/scripts/generate_grpc_examples.py @@ -20,7 +20,6 @@ from util import flatc, root_path grpc_examples_path = Path(root_path, "grpc/examples") greeter_schema = str(Path(grpc_examples_path, "greeter.fbs")) -greeter_schema_v2 = str(Path(grpc_examples_path, "greeter_v2.fbs")) COMMON_ARGS = [ "--grpc", @@ -55,8 +54,8 @@ def GenerateGRPCExamples(): "--swift", "--gen-json-emit", ], - schema=greeter_schema_v2, - cwd=Path(grpc_examples_path, "swift/Greeter/Sources/Models"), + schema=greeter_schema, + cwd=Path(grpc_examples_path, "swift/Greeter/Sources/Model"), ) flatc( diff --git a/src/binary_annotator.cpp b/src/binary_annotator.cpp index 98a864866..1e1668cd9 100644 --- a/src/binary_annotator.cpp +++ b/src/binary_annotator.cpp @@ -126,7 +126,9 @@ static BinarySection GenerateMissingSection(const uint64_t offset, std::map BinaryAnnotator::Annotate() { if (bfbs_ != nullptr && bfbs_length_ != 0) { flatbuffers::Verifier verifier(bfbs_, static_cast(bfbs_length_)); - if (!reflection::VerifySchemaBuffer(verifier)) { + if ((is_size_prefixed_ && + !reflection::VerifySizePrefixedSchemaBuffer(verifier)) || + !reflection::VerifySchemaBuffer(verifier)) { return {}; } } diff --git a/src/flatc.cpp b/src/flatc.cpp index ee34044fd..5dd306441 100644 --- a/src/flatc.cpp +++ b/src/flatc.cpp @@ -145,6 +145,12 @@ const static FlatCOption flatc_options[] = { {"", "cpp-str-flex-ctor", "", "Don't construct custom string types by passing std::string from " "Flatbuffers, but (char* + length)."}, + {"", "cpp-vector-type", "T", + "Set object API vector type (default std::vector). T must be a " + "template taking a single element type argument and support " + "resize(), reserve(), size(), data(), operator[], emplace_back(), and " + "begin()/end(). The custom type also needs its own header to be " + "included via --cpp-include."}, {"", "cpp-field-case-style", "STYLE", "Generate C++ fields using selected case style. Supported STYLE values: * " "'unchanged' - leave unchanged (default) * 'upper' - schema snake_case " @@ -545,6 +551,9 @@ FlatCOptions FlatCompiler::ParseFromCommandLineArguments(int argc, opts.cpp_object_api_string_type = argv[argi]; } else if (arg == "--cpp-str-flex-ctor") { opts.cpp_object_api_string_flexible_constructor = true; + } else if (arg == "--cpp-vector-type") { + if (++argi >= argc) Error("missing type following: " + arg, true); + opts.cpp_object_api_vector_type = argv[argi]; } else if (arg == "--no-cpp-direct-copy") { opts.cpp_direct_copy = false; } else if (arg == "--cpp-field-case-style") { diff --git a/src/idl_gen_cpp.cpp b/src/idl_gen_cpp.cpp index 9ad18a7b4..767f48073 100644 --- a/src/idl_gen_cpp.cpp +++ b/src/idl_gen_cpp.cpp @@ -257,6 +257,19 @@ class CppGenerator : public BaseGenerator { code_ += " FLATBUFFERS_VERSION_REVISION == " + std::to_string(FLATBUFFERS_VERSION_REVISION) + ","; code_ += " \"Non-compatible flatbuffers version included\");"; + + code_ += "// Ensure the included flatbuffers.h is Bigfoot's fork - stock"; + code_ += "// flatbuffers (or a differently versioned Bigfoot fork) is not compatible."; + code_ += "#ifndef FLATBUFFERS_BIGFOOT_VERSION"; + code_ += + "#error \"This file requires Bigfoot's flatbuffers fork - stock " + "flatbuffers is not compatible\""; + code_ += "#endif"; + code_ += "static_assert(FLATBUFFERS_BIGFOOT_VERSION == " + + std::to_string(FLATBUFFERS_BIGFOOT_VERSION) + ","; + code_ += + " \"Non-compatible Bigfoot flatbuffers fork version " + "included\");"; } void GenIncludeDependencies() { @@ -529,6 +542,8 @@ class CppGenerator : public BaseGenerator { code_ += ""; } + GenerateBigfootRefForwardDecls(); + // Generate preablmle code for mini reflection. if (opts_.mini_reflect != IDLOptions::kNone) { // To break cyclic dependencies, first pre-declare all tables/structs. @@ -758,6 +773,8 @@ class CppGenerator : public BaseGenerator { if (cur_name_space_) SetNameSpace(nullptr); + GenerateBigfootRefImpls(); + // Close the include guard. code_ += "#endif // " + include_guard; @@ -892,6 +909,24 @@ class CppGenerator : public BaseGenerator { return opts_.gen_nullable ? " _Nullable " : ""; } + // A field's `native_type`/`native_type_pack_name` normally come from the + // referenced struct's own declaration. A field can override both (see + // `bigfoot_ref` in idl_parser.cpp, which synthesizes these two attributes + // directly on the field) to instantiate a templated native type + // differently per field. + static const Value* EffectiveNativeType(const FieldDef& field, + const StructDef& struct_def) { + if (const auto v = field.attributes.Lookup("native_type")) return v; + return struct_def.attributes.Lookup("native_type"); + } + + static const Value* EffectiveNativeTypePackName(const FieldDef& field, + const StructDef& struct_def) { + if (const auto v = field.attributes.Lookup("native_type_pack_name")) + return v; + return struct_def.attributes.Lookup("native_type_pack_name"); + } + static std::string NativeName(const std::string& name, const StructDef* sd, const IDLOptions& opts) { // If the table is a native_type, return the native_type name. @@ -937,6 +972,23 @@ class CppGenerator : public BaseGenerator { "std::string"; // Only for custom string types. } + const std::string NativeVectorType(const FieldDef* field) { + auto attr = field ? field->attributes.Lookup("cpp_vector_type") : nullptr; + auto& ret = attr ? attr->constant : opts_.cpp_object_api_vector_type; + if (ret.empty()) { + return "std::vector"; + } + return ret; + } + + // True if this field's native vector uses a custom (non-std::vector) + // container, meaning generated Pack() code can't rely on the std::vector + // specific CreateVector*() overloads and must fall back to data()/size() + // or per-element construction instead. + bool UsesCustomVectorType(const FieldDef* field) { + return NativeVectorType(field) != "std::vector"; + } + std::string GenTypeNativePtr(const std::string& type, const FieldDef* field, bool is_constructor) { auto& ptr_type = PtrType(field); @@ -974,20 +1026,21 @@ class CppGenerator : public BaseGenerator { case BASE_TYPE_VECTOR64: case BASE_TYPE_VECTOR: { const auto type_name = GenTypeNative(type.VectorType(), true, field); - if (type.struct_def && + const auto vector_type = NativeVectorType(&field); + if (vector_type == "std::vector" && type.struct_def && type.struct_def->attributes.Lookup("native_custom_alloc")) { auto native_custom_alloc = type.struct_def->attributes.Lookup("native_custom_alloc"); return "std::vector<" + type_name + "," + native_custom_alloc->constant + "<" + type_name + ">>"; } else { - return "std::vector<" + type_name + ">"; + return vector_type + "<" + type_name + ">"; } } case BASE_TYPE_STRUCT: { auto type_name = WrapInNameSpace(*type.struct_def); if (IsStruct(type)) { - auto native_type = type.struct_def->attributes.Lookup("native_type"); + auto native_type = EffectiveNativeType(field, *type.struct_def); if (native_type) { type_name = native_type->constant; } @@ -1979,7 +2032,7 @@ class CppGenerator : public BaseGenerator { const std::string& full_type = (cpp_type ? (IsVector(field.value.type) - ? "std::vector<" + + ? NativeVectorType(&field) + "<" + GenTypeNativePtr(cpp_type->constant, &field, false) + "> " @@ -2779,17 +2832,15 @@ class CppGenerator : public BaseGenerator { get_call += ">(" + offset_str + ");"; code_ += get_call; } else if (IsString(type) && field.value.constant != "0") { - std::string escaped; - flatbuffers::EscapeString(field.value.constant.c_str(), - field.value.constant.length(), &escaped, - true, false); + // TODO: Add logic to always convert the string to a valid C++ string + // literal by handling string escapes. code_ += " auto* ptr = {{FIELD_VALUE}};"; code_ += " if (ptr) return ptr;"; code_ += " static const struct { uint32_t len; const char s[" + NumToString(field.value.constant.length() + 1) + "]; } bfbs_string = { " + - NumToString(field.value.constant.length()) + ", " + - escaped + " };"; + NumToString(field.value.constant.length()) + ", \"" + + field.value.constant + "\" };"; code_ += " return reinterpret_cast(&bfbs_string);"; @@ -3419,15 +3470,11 @@ class CppGenerator : public BaseGenerator { code_.SetValue("CREATE_STRING", "CreateSharedString"); } if (field->value.constant != "0") { - std::string escaped; - flatbuffers::EscapeString(field->value.constant.c_str(), - field->value.constant.length(), &escaped, - true, false); code_ += " auto {{FIELD_NAME}}__ = {{FIELD_NAME}} ? " "_fbb.{{CREATE_STRING}}({{FIELD_NAME}}) : " - "_fbb.{{CREATE_STRING}}(" + - escaped + ");"; + "_fbb.{{CREATE_STRING}}(\"" + + field->value.constant + "\");"; } else { code_ += " auto {{FIELD_NAME}}__ = {{FIELD_NAME}} ? " @@ -3521,11 +3568,11 @@ class CppGenerator : public BaseGenerator { } case BASE_TYPE_STRUCT: { if (IsStruct(type)) { - const auto& struct_attrs = type.struct_def->attributes; - const auto native_type = struct_attrs.Lookup("native_type"); + const auto native_type = EffectiveNativeType(afield, *type.struct_def); if (native_type) { std::string unpack_call = "::flatbuffers::UnPack"; - const auto pack_name = struct_attrs.Lookup("native_type_pack_name"); + const auto pack_name = + EffectiveNativeTypePackName(afield, *type.struct_def); if (pack_name) { unpack_call += pack_name->constant; } @@ -3778,13 +3825,22 @@ class CppGenerator : public BaseGenerator { case BASE_TYPE_VECTOR64: case BASE_TYPE_VECTOR: { auto vector_type = field.value.type.VectorType(); + // If the field's native container isn't std::vector, the + // std::vector-specific CreateVector*() overloads in + // flatbuffer_builder.h can't be used directly. Fall back to + // data()/size()-based overloads (which only require the container to + // support those, like std::vector does) or, where no such overload + // exists, to the same per-element lambda serialization already used + // above for custom string/table/union element types. + const bool custom_vector = UsesCustomVectorType(&field); switch (vector_type.base_type) { case BASE_TYPE_STRING: { - if (NativeString(&field) == "std::string") { + if (!custom_vector && NativeString(&field) == "std::string") { code += "_fbb.CreateVectorOfStrings(" + value + ")"; } else { // Use by-function serialization to emulate - // CreateVectorOfStrings(); this works also with non-std strings. + // CreateVectorOfStrings(); this works also with non-std strings + // and non-std::vector vector types. code += "_fbb.CreateVector<::flatbuffers::Offset<::flatbuffers::" "String>>" @@ -3799,20 +3855,37 @@ class CppGenerator : public BaseGenerator { } case BASE_TYPE_STRUCT: { if (IsStruct(vector_type)) { - const auto& struct_attrs = - field.value.type.struct_def->attributes; - const auto native_type = struct_attrs.Lookup("native_type"); + const auto native_type = + EffectiveNativeType(field, *field.value.type.struct_def); if (native_type) { code += "_fbb.CreateVectorOfNativeStructs<"; code += WrapInNameSpace(*vector_type.struct_def) + ", " + native_type->constant + ">"; - code += "(" + value; - const auto pack_name = - struct_attrs.Lookup("native_type_pack_name"); + if (custom_vector) { + code += "(" + value + ".data(), " + value + ".size()"; + } else { + code += "(" + value; + } + const auto pack_name = EffectiveNativeTypePackName( + field, *field.value.type.struct_def); if (pack_name) { code += ", ::flatbuffers::Pack" + pack_name->constant; } code += ")"; + } else if (custom_vector && + (field.value.type.base_type == BASE_TYPE_VECTOR64 || + field.offset64)) { + // CreateVectorOfStructs64() (and CreateVectorOfStructs64() + // for offset64) only accept a std::vector; use the + // equivalent explicit-template raw pointer overload instead. + const auto struct_type = WrapInNameSpace(*vector_type.struct_def); + const auto vector_t = field.value.type.base_type == + BASE_TYPE_VECTOR64 + ? "::flatbuffers::Vector64" + : "::flatbuffers::Vector"; + code += "_fbb.CreateVectorOfStructs<" + struct_type + + ", ::flatbuffers::Offset64, " + vector_t + ">(" + + value + ".data(), " + value + ".size())"; } else { // If the field uses 64-bit addressing, create a 64-bit vector. if (field.value.type.base_type == BASE_TYPE_VECTOR64) { @@ -3824,16 +3897,18 @@ class CppGenerator : public BaseGenerator { code += "64<::flatbuffers::Vector>"; } } - code += "(" + value + ")"; + if (custom_vector) { + code += "(" + value + ".data(), " + value + ".size())"; + } else { + code += "(" + value + ")"; + } } } else { code += "_fbb.CreateVector<::flatbuffers::Offset<"; code += WrapInNameSpace(*vector_type.struct_def) + ">> "; code += "(" + value + ".size(), "; code += "[](size_t i, _VectorArgs *__va) { "; - code += "return " + - WrapInNameSpace(vector_type.struct_def->defined_namespace, - "Create" + vector_type.struct_def->name); + code += "return Create" + vector_type.struct_def->name; code += "(*__va->__fbb, "; if (field.native_inline) { code += "&(__va->_" + value + "[i])"; @@ -3845,7 +3920,17 @@ class CppGenerator : public BaseGenerator { break; } case BASE_TYPE_BOOL: { - code += "_fbb.CreateVector(" + value + ")"; + if (custom_vector) { + // Vectors of bool are always stored on the wire as uint8_t + // (there is no Vector); CreateVectorScalarCast() does + // the per-element bool->uint8_t cast from a raw data()/size() + // pointer pair, avoiding any dependency on std::vector's + // bit-packed specialization. + code += "_fbb.CreateVectorScalarCast(" + value + + ".data(), " + value + ".size())"; + } else { + code += "_fbb.CreateVector(" + value + ")"; + } break; } case BASE_TYPE_UNION: { @@ -3881,9 +3966,11 @@ class CppGenerator : public BaseGenerator { // the underlying storage type (eg. uint8_t). const auto basetype = GenTypeBasic( field.value.type.enum_def->underlying_type, false); - code += "_fbb.CreateVectorScalarCast<" + basetype + - ">(::flatbuffers::data(" + value + "), " + value + - ".size())"; + const std::string data_ptr = + custom_vector ? value + ".data()" + : "::flatbuffers::data(" + value + ")"; + code += "_fbb.CreateVectorScalarCast<" + basetype + ">(" + + data_ptr + ", " + value + ".size())"; } else if (field.attributes.Lookup("cpp_type")) { auto type = GenTypeBasic(vector_type, false); code += "_fbb.CreateVector<" + type + ">(" + value + ".size(), "; @@ -3892,6 +3979,27 @@ class CppGenerator : public BaseGenerator { code += "static_cast<" + type + ">((*__va->__rehasher)"; code += "(__va->_" + value + "[i]" + GenPtrGet(field) + ")) : 0"; code += "; }, &_va )"; + } else if (custom_vector) { + // Explicitly specify the element type so it can be deduced + // from a raw data()/size() pointer pair instead of relying on + // the std::vector-specific CreateVector overloads. + // Use the user-facing type (matches what GenTypeNative() + // stores in the native vector, e.g. the enum type itself for + // scoped-enum fields) so it matches data()'s pointee type. + auto type = GenTypeBasic(vector_type, true); + if (field.value.type.base_type == BASE_TYPE_VECTOR64) { + code += "_fbb.CreateVector<" + type + + ", ::flatbuffers::Offset64, ::flatbuffers::Vector64>(" + + value + ".data(), " + value + ".size())"; + } else if (field.offset64) { + // This is normal 32-bit vector, with 64-bit addressing. + code += "_fbb.CreateVector<" + type + + ", ::flatbuffers::Offset64, ::flatbuffers::Vector>(" + + value + ".data(), " + value + ".size())"; + } else { + code += "_fbb.CreateVector(" + value + ".data(), " + value + + ".size())"; + } } else { // If the field uses 64-bit addressing, create a 64-bit vector. if (field.value.type.base_type == BASE_TYPE_VECTOR64) { @@ -3925,12 +4033,12 @@ class CppGenerator : public BaseGenerator { } case BASE_TYPE_STRUCT: { if (IsStruct(field.value.type)) { - const auto& struct_attribs = field.value.type.struct_def->attributes; - const auto native_type = struct_attribs.Lookup("native_type"); + const auto native_type = + EffectiveNativeType(field, *field.value.type.struct_def); if (native_type && field.native_inline) { code += "::flatbuffers::Pack"; const auto pack_name = - struct_attribs.Lookup("native_type_pack_name"); + EffectiveNativeTypePackName(field, *field.value.type.struct_def); if (pack_name) { code += pack_name->constant; } @@ -3946,10 +4054,8 @@ class CppGenerator : public BaseGenerator { } } else { // _o->field ? CreateT(_fbb, _o->field.get(), _rehasher); - const auto& nested_struct = *field.value.type.struct_def; - code += value + " ? " + - WrapInNameSpace(nested_struct.defined_namespace, - "Create" + nested_struct.name); + const std::string& type = field.value.type.struct_def->name; + code += value + " ? Create" + type; code += "(_fbb, " + value; if (!field.native_inline) code += GenPtrGet(field); code += ", _rehasher) : 0"; @@ -4097,8 +4203,7 @@ class CppGenerator : public BaseGenerator { if (field->value.type.base_type == BASE_TYPE_STRUCT) { if (IsStruct(field->value.type)) { auto native_type = - field->value.type.struct_def->attributes.Lookup( - "native_type"); + EffectiveNativeType(*field, *field->value.type.struct_def); auto native_inline = field->attributes.Lookup("native_inline"); if (native_type) { pass_by_address = true; @@ -4453,6 +4558,141 @@ class CppGenerator : public BaseGenerator { } } + // Split a "::"-qualified C++ name into namespace components + final name. + static std::vector SplitQualifiedName(const std::string& qualified) { + std::vector parts; + size_t start = qualified.compare(0, 2, "::") == 0 ? 2 : 0; + for (;;) { + const auto pos = qualified.find("::", start); + if (pos == std::string::npos) { + parts.push_back(qualified.substr(start)); + break; + } + parts.push_back(qualified.substr(start, pos - start)); + start = pos + 2; + } + return parts; + } + + // Bigfoot: for every field annotated `bigfoot_ref: "::Ns::AssetX"` (see + // idl_parser.cpp), forward-declare AssetX plus prototype the Pack/UnPack + // functions for its reference wrapper. Called early (alongside the + // regular struct/table forward declarations), since these prototypes - + // unlike their definitions in GenerateBigfootRefImpls() - only need + // AssetX and the wrapper struct forward-declared, not complete. + void GenerateBigfootRefForwardDecls() { + std::unordered_set declared_assets; + for (const auto& struct_def : parser_.structs_.vec) { + if (struct_def->generated) continue; + for (const auto& field : struct_def->fields.vec) { + const auto* bigfoot_ref = field->attributes.Lookup("bigfoot_ref"); + if (!bigfoot_ref) continue; + if (!declared_assets.insert(bigfoot_ref->constant).second) continue; + + auto parts = SplitQualifiedName(bigfoot_ref->constant); + const std::string class_name = parts.back(); + parts.pop_back(); + + SetNameSpace(nullptr); + for (const auto& ns_part : parts) code_ += "namespace " + ns_part + " {"; + code_ += "class " + class_name + ";"; + for (auto it = parts.rbegin(); it != parts.rend(); ++it) + code_ += "} // namespace " + *it; + code_ += ""; + } + } + + std::unordered_set declared_pairs; + bool opened_flatbuffers_ns = false; + for (const auto& struct_def : parser_.structs_.vec) { + if (struct_def->generated) continue; + for (const auto& field : struct_def->fields.vec) { + const auto* bigfoot_ref = field->attributes.Lookup("bigfoot_ref"); + if (!bigfoot_ref) continue; + + const auto* pack_name = field->attributes.Lookup("native_type_pack_name"); + if (!declared_pairs.insert(pack_name->constant).second) continue; + + if (!opened_flatbuffers_ns) { + SetNameSpace(nullptr); + code_ += "namespace flatbuffers {"; + opened_flatbuffers_ns = true; + } + + const auto* native_type = field->attributes.Lookup("native_type"); + const std::string flat_wrapper = + WrapInNameSpace(*field->value.type.struct_def); + + code_ += flat_wrapper + " Pack" + pack_name->constant + + "(const " + native_type->constant + "& p_asset);"; + code_ += native_type->constant + " UnPack" + pack_name->constant + + "(const " + flat_wrapper + "& p_asset);"; + } + } + + if (opened_flatbuffers_ns) { + code_ += "} // namespace flatbuffers"; + code_ += ""; + } + } + + // Bigfoot: defines the Pack/UnPack functions prototyped by + // GenerateBigfootRefForwardDecls(). Called late (after every struct/table + // in this file has been fully defined), since a wrapper struct (e.g. + // HardReference/SoftReference) may be defined in this same generated file + // rather than one it includes, and these definitions construct it by + // value - they need it complete, unlike the earlier prototypes. + void GenerateBigfootRefImpls() { + std::unordered_set declared_pairs; + bool opened_flatbuffers_ns = false; + for (const auto& struct_def : parser_.structs_.vec) { + if (struct_def->generated) continue; + for (const auto& field : struct_def->fields.vec) { + const auto* bigfoot_ref = field->attributes.Lookup("bigfoot_ref"); + if (!bigfoot_ref) continue; + + const auto* pack_name = field->attributes.Lookup("native_type_pack_name"); + if (!declared_pairs.insert(pack_name->constant).second) continue; + + if (!opened_flatbuffers_ns) { + SetNameSpace(nullptr); + code_ += "namespace flatbuffers {"; + opened_flatbuffers_ns = true; + } + + const auto* native_type = field->attributes.Lookup("native_type"); + const std::string flat_wrapper = + WrapInNameSpace(*field->value.type.struct_def); + + // A single translation unit can end up including two different + // generated headers that both reference the same asset type (e.g. + // AssetB references AssetA, and some other TU includes both + // AssetA_generated.hpp and AssetB_generated.hpp directly) - each + // would otherwise emit an identical, independent definition of these + // functions. `inline` only allows identical definitions to repeat + // across *different* translation units, not twice within the same + // one, so guard against that with a plain macro guard. + std::string guard_name = pack_name->constant; + std::transform(guard_name.begin(), guard_name.end(), guard_name.begin(), CharToUpper); + const std::string guard = "FLATBUFFERS_BIGFOOT_REF_" + guard_name; + code_ += "#ifndef " + guard; + code_ += "#define " + guard; + code_ += "inline " + flat_wrapper + " Pack" + pack_name->constant + + "(const " + native_type->constant + + "& p_asset) { return {Pack(p_asset.GetUUID())}; }"; + code_ += "inline " + native_type->constant + " UnPack" + + pack_name->constant + "(const " + flat_wrapper + + "& p_asset) { return {UnPack(p_asset.uuid())}; }"; + code_ += "#endif // " + guard; + } + } + + if (opened_flatbuffers_ns) { + code_ += "} // namespace flatbuffers"; + code_ += ""; + } + } + // Set up the correct namespace. Only open a namespace if the existing one is // different (closing/opening only what is necessary). // diff --git a/src/idl_gen_dart.cpp b/src/idl_gen_dart.cpp index 5b9070852..e55c46602 100644 --- a/src/idl_gen_dart.cpp +++ b/src/idl_gen_dart.cpp @@ -654,15 +654,34 @@ class DartGenerator : public BaseGenerator { std::string NamespaceAliasFromUnionType(Namespace* root_namespace, const Type& type) { - const Namespace& type_namespace = *type.struct_def->defined_namespace; - if (root_namespace->components == type_namespace.components) { + const std::vector qualified_name_parts = + type.struct_def->defined_namespace->components; + if (std::equal(root_namespace->components.begin(), + root_namespace->components.end(), + qualified_name_parts.begin())) { return namer_.Type(*type.struct_def); } - const std::string ns = namer_.Namespace(type_namespace); - return ns.empty() - ? namer_.Type(*type.struct_def) - : ImportAliasName(ns) + "." + namer_.Type(*type.struct_def); + std::string ns; + + for (auto it = qualified_name_parts.begin(); + it != qualified_name_parts.end(); ++it) { + auto& part = *it; + + for (size_t i = 0; i < part.length(); i++) { + if (i && !isdigit(part[i]) && part[i] == CharToUpper(part[i])) { + ns += "_"; + ns += CharToLower(part[i]); + } else { + ns += CharToLower(part[i]); + } + } + if (it != qualified_name_parts.end() - 1) { + ns += "_"; + } + } + + return ns + "." + namer_.Type(*type.struct_def); } void GenImplementationGetters( diff --git a/src/idl_gen_fbs.cpp b/src/idl_gen_fbs.cpp index 0acd7e49a..da4289587 100644 --- a/src/idl_gen_fbs.cpp +++ b/src/idl_gen_fbs.cpp @@ -368,17 +368,7 @@ static std::string GenerateFBS(const Parser& parser, if (field.value.type.base_type != BASE_TYPE_UTYPE) { GenComment(field.doc_comment, &schema, nullptr, " "); schema += " " + field.name + ":" + GenType(field.value.type); - if (field.value.constant != "0") { - if (IsString(field.value.type)) { - std::string escaped; - flatbuffers::EscapeString(field.value.constant.c_str(), - field.value.constant.length(), &escaped, - true, false); - schema += " = " + escaped; - } else { - schema += " = " + field.value.constant; - } - } + if (field.value.constant != "0") schema += " = " + field.value.constant; std::vector attributes; if (field.IsRequired()) attributes.push_back("required"); if (field.key) attributes.push_back("key"); diff --git a/src/idl_gen_python.cpp b/src/idl_gen_python.cpp index cb25fbc55..21304e263 100644 --- a/src/idl_gen_python.cpp +++ b/src/idl_gen_python.cpp @@ -1528,7 +1528,7 @@ class PythonGenerator : public BaseGenerator { } else { code += "def Create" + field_method + "Vector(builder, data):\n"; } - code += Indent + "return " + helper_name + "(builder, data)\n\n"; + code += Indent + helper_name + "(builder, data)\n\n"; } } @@ -2095,12 +2095,12 @@ class PythonGenerator : public BaseGenerator { const auto field_method = namer_.Method(field); const auto struct_var = namer_.Variable(struct_def); const EnumDef& enum_def = *field.value.type.enum_def; - auto union_fn = namer_.Function(enum_def); + auto union_type = namer_.Type(enum_def); if (parser_.opts.include_dependence_headers) { - union_fn = namer_.NamespacedType(enum_def) + "." + union_fn; + union_type = namer_.NamespacedType(enum_def) + "." + union_type; } - code += GenIndents(2) + "self." + field_field + " = " + union_fn + + code += GenIndents(2) + "self." + field_field + " = " + union_type + "Creator(" + "self." + field_field + "Type, " + struct_var + "." + field_method + "())"; } @@ -2471,7 +2471,7 @@ class PythonGenerator : public BaseGenerator { } else { GenPackForScalarVectorFieldHelper(struct_def, field, code_prefix_ptr, 3); code_prefix += "(self." + field_field + "[i])"; - code_prefix += GenIndents(3) + field_field + " = builder.EndVector()"; + code_prefix += GenIndents(4) + field_field + " = builder.EndVector()"; } } diff --git a/src/idl_gen_rust.cpp b/src/idl_gen_rust.cpp index d62bbffa4..b7a565d00 100644 --- a/src/idl_gen_rust.cpp +++ b/src/idl_gen_rust.cpp @@ -330,7 +330,7 @@ static bool GenerateRustModuleRootFile(const Parser& parser, it++) { root_module.Insert(namer, *it); } - CodeWriter code(" "); + CodeWriter code(" "); // TODO(caspern): Move generated warning out of BaseGenerator. code += "// Automatically generated by the Flatbuffers compiler. " @@ -354,7 +354,7 @@ class RustGenerator : public BaseGenerator { namer_(WithFlagOptions(RustDefaultConfig(), parser.opts, path), RustKeywords()) { // TODO: Namer flag overrides should be in flatc or flatc_main. - code_.SetPadding(" "); + code_.SetPadding(" "); } bool generate() { @@ -429,7 +429,8 @@ class RustGenerator : public BaseGenerator { // Generate imports for the global scope in case no namespace is used // in the schema file. - GenNamespaceImports(); + GenNamespaceImports(0); + code_ += ""; // Generate all code in their namespaces, once, because Rust does not // permit re-opening modules. @@ -707,8 +708,6 @@ class RustGenerator : public BaseGenerator { // an enum match function, // and an enum array of values void GenEnum(const EnumDef& enum_def) { - code_ += ""; - const bool is_private = parser_.opts.no_leak_private_annotations && (enum_def.attributes.Lookup("private") != nullptr); code_.SetValue("ACCESS_TYPE", is_private ? "pub(crate)" : "pub"); @@ -729,19 +728,17 @@ class RustGenerator : public BaseGenerator { // constants but in camel case. code_ += "#[allow(non_upper_case_globals)]"; code_ += "mod bitflags_{{ENUM_NAMESPACE}} {"; - code_ += " ::flatbuffers::bitflags::bitflags! {"; - GenComment(enum_def.doc_comment, " "); - code_ += " #[derive(Default, Debug, Clone, Copy, PartialEq)]"; - code_ += " {{ACCESS_TYPE}} struct {{ENUM_TY}}: {{BASE_TYPE}} {"; + code_ += " ::flatbuffers::bitflags::bitflags! {"; + GenComment(enum_def.doc_comment, " "); + code_ += " #[derive(Default, Debug, Clone, Copy, PartialEq)]"; + code_ += " {{ACCESS_TYPE}} struct {{ENUM_TY}}: {{BASE_TYPE}} {"; ForAllEnumValues1(enum_def, [&](const EnumVal& ev) { - this->GenComment(ev.doc_comment, " "); - code_ += " const {{VARIANT}} = {{VALUE}};"; + this->GenComment(ev.doc_comment, " "); + code_ += " const {{VARIANT}} = {{VALUE}};"; }); - code_ += " }"; code_ += " }"; + code_ += " }"; code_ += "}"; - code_ += ""; - code_ += "pub use self::bitflags_{{ENUM_NAMESPACE}}::{{ENUM_TY}};"; code_ += ""; @@ -756,14 +753,10 @@ class RustGenerator : public BaseGenerator { code_ += "pub const ENUM_MIN_{{ENUM_CONSTANT}}: {{BASE_TYPE}}" " = {{ENUM_MIN_BASE_VALUE}};"; - code_ += ""; - code_ += deprecation_warning; code_ += "pub const ENUM_MAX_{{ENUM_CONSTANT}}: {{BASE_TYPE}}" " = {{ENUM_MAX_BASE_VALUE}};"; - code_ += ""; - auto num_fields = NumToString(enum_def.size()); code_ += deprecation_warning; code_ += "#[allow(non_camel_case_types)]"; @@ -784,8 +777,6 @@ class RustGenerator : public BaseGenerator { "Default)]"; code_ += "#[repr(transparent)]"; code_ += "{{ACCESS_TYPE}} struct {{ENUM_TY}}(pub {{BASE_TYPE}});"; - code_ += ""; - code_ += "#[allow(non_upper_case_globals)]"; code_ += "impl {{ENUM_TY}} {"; ForAllEnumValues1(enum_def, [&](const EnumVal& ev) { @@ -794,41 +785,34 @@ class RustGenerator : public BaseGenerator { }); code_ += ""; // Generate Associated constants - code_ += - " pub const ENUM_MIN: {{BASE_TYPE}} = {{ENUM_MIN_BASE_VALUE}};"; - code_ += - " pub const ENUM_MAX: {{BASE_TYPE}} = {{ENUM_MAX_BASE_VALUE}};"; - code_ += " pub const ENUM_VALUES: &'static [Self] = &["; - ForAllEnumValues(enum_def, [&]() { code_ += " Self::{{VARIANT}},"; }); - code_ += " ];"; - code_ += ""; - - code_ += " /// Returns the variant's name or \"\" if unknown."; - code_ += " pub fn variant_name(self) -> Option<&'static str> {"; - code_ += " match self {"; + code_ += " pub const ENUM_MIN: {{BASE_TYPE}} = {{ENUM_MIN_BASE_VALUE}};"; + code_ += " pub const ENUM_MAX: {{BASE_TYPE}} = {{ENUM_MAX_BASE_VALUE}};"; + code_ += " pub const ENUM_VALUES: &'static [Self] = &["; + ForAllEnumValues(enum_def, [&]() { code_ += " Self::{{VARIANT}},"; }); + code_ += " ];"; + code_ += " /// Returns the variant's name or \"\" if unknown."; + code_ += " pub fn variant_name(self) -> Option<&'static str> {"; + code_ += " match self {"; ForAllEnumValues(enum_def, [&]() { - code_ += " Self::{{VARIANT}} => Some(\"{{VARIANT}}\"),"; + code_ += " Self::{{VARIANT}} => Some(\"{{VARIANT}}\"),"; }); - code_ += " _ => None,"; - code_ += " }"; + code_ += " _ => None,"; code_ += " }"; + code_ += " }"; code_ += "}"; - code_ += ""; // Generate Debug. Unknown variants are printed like "". code_ += "impl ::core::fmt::Debug for {{ENUM_TY}} {"; code_ += - " fn fmt(&self, f: &mut ::core::fmt::Formatter) ->" + " fn fmt(&self, f: &mut ::core::fmt::Formatter) ->" " ::core::fmt::Result {"; - code_ += " if let Some(name) = self.variant_name() {"; - code_ += " f.write_str(name)"; - code_ += " } else {"; - code_ += - " f.write_fmt(format_args!(\"\", self.0))"; - code_ += " }"; + code_ += " if let Some(name) = self.variant_name() {"; + code_ += " f.write_str(name)"; + code_ += " } else {"; + code_ += " f.write_fmt(format_args!(\"\", self.0))"; code_ += " }"; + code_ += " }"; code_ += "}"; - code_ += ""; code_.SetValue("INTO_BASE", "self.0"); } @@ -837,20 +821,19 @@ class RustGenerator : public BaseGenerator { if (parser_.opts.rust_serialize) { code_ += "impl Serialize for {{ENUM_TY}} {"; code_ += - " fn serialize(&self, serializer: S) -> Result"; - code_ += " where"; - code_ += " S: Serializer,"; - code_ += " {"; + " fn serialize(&self, serializer: S) -> Result"; + code_ += " where"; + code_ += " S: Serializer,"; + code_ += " {"; if (IsBitFlagsEnum(enum_def)) { - code_ += " serializer.serialize_u32(self.bits() as u32)"; + code_ += " serializer.serialize_u32(self.bits() as u32)"; } else { code_ += - " serializer.serialize_unit_variant(\"{{ENUM_TY}}\", self.0 " + " serializer.serialize_unit_variant(\"{{ENUM_TY}}\", self.0 " "as " "u32, self.variant_name().unwrap())"; } - code_ += " }"; + code_ += " }"; code_ += "}"; code_ += ""; @@ -863,9 +846,7 @@ class RustGenerator : public BaseGenerator { code_ += " {"; code_ += " let s = String::deserialize(deserializer)?;"; code_ += " for item in {{ENUM_TY}}::ENUM_VALUES {"; - code_ += - " if let Some(item_name) = " - "item.variant_name() {"; + code_ += " if let Some(item_name) = item.variant_name() {"; code_ += " if item_name == s {"; code_ += " return Ok(item.clone());"; code_ += " }"; @@ -882,24 +863,22 @@ class RustGenerator : public BaseGenerator { // Generate Follow and Push so we can serialize and stuff. code_ += "impl<'a> ::flatbuffers::Follow<'a> for {{ENUM_TY}} {"; - code_ += " type Inner = Self;"; - code_ += ""; - code_ += " #[inline]"; - code_ += " unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {"; + code_ += " type Inner = Self;"; + code_ += " #[inline]"; + code_ += " unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {"; code_ += - " let b = unsafe { " + " let b = unsafe { " "::flatbuffers::read_scalar_at::<{{BASE_TYPE}}>(buf, loc) };"; if (IsBitFlagsEnum(enum_def)) { - code_ += " Self::from_bits_retain(b)"; + code_ += " Self::from_bits_retain(b)"; } else { - code_ += " Self(b)"; + code_ += " Self(b)"; } - code_ += " }"; + code_ += " }"; code_ += "}"; code_ += ""; code_ += "impl ::flatbuffers::Push for {{ENUM_TY}} {"; code_ += " type Output = {{ENUM_TY}};"; - code_ += ""; code_ += " #[inline]"; code_ += " unsafe fn push(&self, dst: &mut [u8], _written_len: usize) {"; code_ += @@ -909,34 +888,32 @@ class RustGenerator : public BaseGenerator { code_ += "}"; code_ += ""; code_ += "impl ::flatbuffers::EndianScalar for {{ENUM_TY}} {"; - code_ += " type Scalar = {{BASE_TYPE}};"; - code_ += ""; - code_ += " #[inline]"; - code_ += " fn to_little_endian(self) -> {{BASE_TYPE}} {"; - code_ += " {{INTO_BASE}}.to_le()"; - code_ += " }"; - code_ += ""; - code_ += " #[inline]"; - code_ += " #[allow(clippy::wrong_self_convention)]"; - code_ += " fn from_little_endian(v: {{BASE_TYPE}}) -> Self {"; - code_ += " let b = {{BASE_TYPE}}::from_le(v);"; + code_ += " type Scalar = {{BASE_TYPE}};"; + code_ += " #[inline]"; + code_ += " fn to_little_endian(self) -> {{BASE_TYPE}} {"; + code_ += " {{INTO_BASE}}.to_le()"; + code_ += " }"; + code_ += " #[inline]"; + code_ += " #[allow(clippy::wrong_self_convention)]"; + code_ += " fn from_little_endian(v: {{BASE_TYPE}}) -> Self {"; + code_ += " let b = {{BASE_TYPE}}::from_le(v);"; if (IsBitFlagsEnum(enum_def)) { - code_ += " Self::from_bits_retain(b)"; + code_ += " Self::from_bits_retain(b)"; } else { - code_ += " Self(b)"; + code_ += " Self(b)"; } - code_ += " }"; + code_ += " }"; code_ += "}"; code_ += ""; // Generate verifier - deferring to the base type. code_ += "impl<'a> ::flatbuffers::Verifiable for {{ENUM_TY}} {"; - code_ += " #[inline]"; - code_ += " fn run_verifier("; - code_ += " v: &mut ::flatbuffers::Verifier, pos: usize"; - code_ += " ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> {"; - code_ += " {{BASE_TYPE}}::run_verifier(v, pos)"; - code_ += " }"; + code_ += " #[inline]"; + code_ += " fn run_verifier("; + code_ += " v: &mut ::flatbuffers::Verifier, pos: usize"; + code_ += " ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> {"; + code_ += " {{BASE_TYPE}}::run_verifier(v, pos)"; + code_ += " }"; code_ += "}"; code_ += ""; // Enums are basically integers. @@ -945,8 +922,8 @@ class RustGenerator : public BaseGenerator { if (enum_def.is_union) { // Generate typesafe offset(s) for unions code_.SetValue("UNION_TYPE", namer_.Type(enum_def)); - code_ += ""; code_ += "{{ACCESS_TYPE}} struct {{UNION_TYPE}}UnionTableOffset {}"; + code_ += ""; if (parser_.opts.generate_object_based_api) { GenUnionObject(enum_def); } @@ -978,85 +955,75 @@ class RustGenerator : public BaseGenerator { code_.SetValue("ENUM_OTY", namer_.ObjectType(enum_def)); // Generate native union. - code_ += ""; code_ += "#[allow(clippy::upper_case_acronyms)]"; // NONE's spelling is // intended. code_ += "#[non_exhaustive]"; code_ += "#[derive(Debug, Clone, PartialEq)]"; code_ += "{{ACCESS_TYPE}} enum {{ENUM_OTY}} {"; - code_ += " NONE,"; + code_ += " NONE,"; ForAllUnionObjectVariantsBesidesNone(enum_def, [&] { code_ += "{{NATIVE_VARIANT}}(alloc::boxed::Box<{{U_ELEMENT_TABLE_TYPE}}>),"; }); code_ += "}"; - code_ += ""; - // Generate Default (NONE). code_ += "impl Default for {{ENUM_OTY}} {"; - code_ += " fn default() -> Self {"; - code_ += " Self::NONE"; - code_ += " }"; + code_ += " fn default() -> Self {"; + code_ += " Self::NONE"; + code_ += " }"; code_ += "}"; - code_ += ""; // Generate native union methods. code_ += "impl {{ENUM_OTY}} {"; // Get flatbuffers union key. // TODO(cneo): add docstrings? - code_ += " pub fn {{ENUM_FN}}_type(&self) -> {{ENUM_TY}} {"; - code_ += " match self {"; - code_ += " Self::NONE => {{ENUM_TY}}::NONE,"; + code_ += " pub fn {{ENUM_FN}}_type(&self) -> {{ENUM_TY}} {"; + code_ += " match self {"; + code_ += " Self::NONE => {{ENUM_TY}}::NONE,"; ForAllUnionObjectVariantsBesidesNone(enum_def, [&] { code_ += - " Self::{{NATIVE_VARIANT}}(_) => {{ENUM_TY}}::" + " Self::{{NATIVE_VARIANT}}(_) => {{ENUM_TY}}::" "{{VARIANT_NAME}},"; }); - code_ += " }"; code_ += " }"; - code_ += ""; - + code_ += " }"; // Pack flatbuffers union value code_ += - " pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>(&self, fbb: " - "&mut " + " pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>(&self, fbb: &mut " "::flatbuffers::FlatBufferBuilder<'b, A>)" " -> Option<::flatbuffers::WIPOffset<::flatbuffers::UnionWIPOffset>>" " {"; - code_ += " match self {"; - code_ += " Self::NONE => None,"; + code_ += " match self {"; + code_ += " Self::NONE => None,"; ForAllUnionObjectVariantsBesidesNone(enum_def, [&] { - code_ += " Self::{{NATIVE_VARIANT}}(v) => \\"; + code_ += " Self::{{NATIVE_VARIANT}}(v) => \\"; code_ += "Some(v.pack(fbb).as_union_value()),"; }); - code_ += " }"; code_ += " }"; + code_ += " }"; // Generate some accessors; ForAllUnionObjectVariantsBesidesNone(enum_def, [&] { // Move accessor. - code_ += ""; code_ += "/// If the union variant matches, return the owned " "{{U_ELEMENT_TABLE_TYPE}}, setting the union to NONE."; code_ += "pub fn take_{{U_ELEMENT_NAME}}(&mut self) -> " "Option> {"; - code_ += " if let Self::{{NATIVE_VARIANT}}(_) = self {"; - code_ += " let v = ::core::mem::replace(self, Self::NONE);"; - code_ += " if let Self::{{NATIVE_VARIANT}}(w) = v {"; - code_ += " Some(w)"; - code_ += " } else {"; - code_ += " unreachable!()"; - code_ += " }"; + code_ += " if let Self::{{NATIVE_VARIANT}}(_) = self {"; + code_ += " let v = ::core::mem::replace(self, Self::NONE);"; + code_ += " if let Self::{{NATIVE_VARIANT}}(w) = v {"; + code_ += " Some(w)"; code_ += " } else {"; - code_ += " None"; + code_ += " unreachable!()"; code_ += " }"; + code_ += " } else {"; + code_ += " None"; + code_ += " }"; code_ += "}"; - // Immutable reference accessor. - code_ += ""; code_ += "/// If the union variant matches, return a reference to the " "{{U_ELEMENT_TABLE_TYPE}}."; @@ -1064,12 +1031,10 @@ class RustGenerator : public BaseGenerator { "pub fn as_{{U_ELEMENT_NAME}}(&self) -> " "Option<&{{U_ELEMENT_TABLE_TYPE}}> {"; code_ += - " if let Self::{{NATIVE_VARIANT}}(v) = self " + " if let Self::{{NATIVE_VARIANT}}(v) = self " "{ Some(v.as_ref()) } else { None }"; code_ += "}"; - // Mutable reference accessor. - code_ += ""; code_ += "/// If the union variant matches, return a mutable reference" " to the {{U_ELEMENT_TABLE_TYPE}}."; @@ -1077,13 +1042,11 @@ class RustGenerator : public BaseGenerator { "pub fn as_{{U_ELEMENT_NAME}}_mut(&mut self) -> " "Option<&mut {{U_ELEMENT_TABLE_TYPE}}> {"; code_ += - " if let Self::{{NATIVE_VARIANT}}(v) = self " + " if let Self::{{NATIVE_VARIANT}}(v) = self " "{ Some(v.as_mut()) } else { None }"; code_ += "}"; }); - code_ += "}"; // End union methods impl. - code_ += ""; } enum DefaultContext { kBuilder, kAccessor, kObject }; @@ -1138,14 +1101,9 @@ class RustGenerator : public BaseGenerator { // need one for Rust's Default trait so we use empty string. The usual // value of field.value.constant is `0`, which is non-sensical except // maybe to c++ (nullptr == 0). - std::string defval; - if (field.IsRequired()) { - defval = "\"\""; - } else { - flatbuffers::EscapeString(field.value.constant.c_str(), - field.value.constant.length(), &defval, - true, false); - } + // TODO: Escape strings? + const std::string defval = + field.IsRequired() ? "\"\"" : "\"" + field.value.constant + "\""; if (context == kObject) { return "alloc::string::ToString::to_string(" + defval + ")"; } @@ -1661,9 +1619,9 @@ class RustGenerator : public BaseGenerator { const std::string& name) { const std::string fully_qualified_name = struct_def.defined_namespace->GetFullyQualifiedName(name); - code_ += " pub const fn get_fully_qualified_name() -> &'static str {"; - code_ += " \"" + fully_qualified_name + "\""; - code_ += " }"; + code_ += " pub const fn get_fully_qualified_name() -> &'static str {"; + code_ += " \"" + fully_qualified_name + "\""; + code_ += " }"; code_ += ""; } @@ -1715,8 +1673,6 @@ class RustGenerator : public BaseGenerator { // Generate an accessor struct, builder struct, and create function for a // table. void GenTable(const StructDef& struct_def) { - code_ += ""; - const bool is_private = parser_.opts.no_leak_private_annotations && (struct_def.attributes.Lookup("private") != nullptr); @@ -1727,23 +1683,22 @@ class RustGenerator : public BaseGenerator { // Generate an offset type, the base type, the Follow impl, and the // init_from_table impl. code_ += "{{ACCESS_TYPE}} enum {{STRUCT_TY}}Offset {}"; + code_ += "#[derive(Copy, Clone, PartialEq)]"; code_ += ""; GenComment(struct_def.doc_comment); - code_ += "#[derive(Copy, Clone, PartialEq)]"; code_ += "{{ACCESS_TYPE}} struct {{STRUCT_TY}}<'a> {"; - code_ += " pub _tab: ::flatbuffers::Table<'a>,"; + code_ += " pub _tab: ::flatbuffers::Table<'a>,"; code_ += "}"; code_ += ""; code_ += "impl<'a> ::flatbuffers::Follow<'a> for {{STRUCT_TY}}<'a> {"; - code_ += " type Inner = {{STRUCT_TY}}<'a>;"; - code_ += ""; - code_ += " #[inline]"; - code_ += " unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {"; + code_ += " type Inner = {{STRUCT_TY}}<'a>;"; + code_ += " #[inline]"; + code_ += " unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {"; code_ += - " Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } }"; - code_ += " }"; + " Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } }"; + code_ += " }"; code_ += "}"; code_ += ""; code_ += "impl<'a> {{STRUCT_TY}}<'a> {"; @@ -1755,37 +1710,34 @@ class RustGenerator : public BaseGenerator { "pub const {{OFFSET_NAME}}: ::flatbuffers::VOffsetT = " "{{OFFSET_VALUE}};"; }); - - if (struct_def.fields.vec.size() > 0) { code_ += ""; } + code_ += ""; if (parser_.opts.generate_name_strings) { GenFullyQualifiedNameGetter(struct_def, struct_def.name); } - code_ += " #[inline]"; + code_ += " #[inline]"; code_ += - " pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> " + " pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> " "Self {"; - code_ += " {{STRUCT_TY}} { _tab: table }"; - code_ += " }"; - code_ += ""; + code_ += " {{STRUCT_TY}} { _tab: table }"; + code_ += " }"; // Generate a convenient create* function that uses the above builder // to create a table in one function call. code_.SetValue("MAYBE_US", struct_def.fields.vec.size() == 0 ? "_" : ""); code_.SetValue("MAYBE_LT", TableBuilderArgsNeedsLifetime(struct_def) ? "<'args>" : ""); - code_ += " #[allow(unused_mut)]"; + code_ += " #[allow(unused_mut)]"; code_ += - " pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: " + " pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: " "::flatbuffers::Allocator + 'bldr>("; code_ += - " _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, " - "A>,"; - code_ += " {{MAYBE_US}}args: &'args {{STRUCT_TY}}Args{{MAYBE_LT}}"; - code_ += " ) -> ::flatbuffers::WIPOffset<{{STRUCT_TY}}<'bldr>> {"; + " _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>,"; + code_ += " {{MAYBE_US}}args: &'args {{STRUCT_TY}}Args{{MAYBE_LT}}"; + code_ += " ) -> ::flatbuffers::WIPOffset<{{STRUCT_TY}}<'bldr>> {"; - code_ += " let mut builder = {{STRUCT_TY}}Builder::new(_fbb);"; + code_ += " let mut builder = {{STRUCT_TY}}Builder::new(_fbb);"; for (size_t size = struct_def.sortbysize ? sizeof(largest_scalar_t) : 1; size; size /= 2) { ForAllTableFields( @@ -1796,24 +1748,23 @@ class RustGenerator : public BaseGenerator { return; if (IsOptionalToBuilder(field)) { code_ += - " if let Some(x) = args.{{FIELD}} " + " if let Some(x) = args.{{FIELD}} " "{ builder.add_{{FIELD}}(x); }"; } else { - code_ += " builder.add_{{FIELD}}(args.{{FIELD}});"; + code_ += " builder.add_{{FIELD}}(args.{{FIELD}});"; } }, /*reverse=*/true); } - code_ += " builder.finish()"; - code_ += " }"; + code_ += " builder.finish()"; + code_ += " }"; code_ += ""; - // Generate Object API Packer function. if (parser_.opts.generate_object_based_api) { // TODO(cneo): Replace more for loops with ForAllX stuff. // TODO(cneo): Manage indentation with IncrementIdentLevel? code_.SetValue("STRUCT_OTY", namer_.ObjectType(struct_def)); - code_ += " pub fn unpack(&self) -> {{STRUCT_OTY}} {"; + code_ += " pub fn unpack(&self) -> {{STRUCT_OTY}} {"; ForAllObjectTableFields(struct_def, [&](const FieldDef& field) { const Type& type = field.value.type; switch (GetFullType(type)) { @@ -1821,7 +1772,7 @@ class RustGenerator : public BaseGenerator { case ftBool: case ftFloat: case ftEnumKey: { - code_ += " let {{FIELD}} = self.{{FIELD}}();"; + code_ += " let {{FIELD}} = self.{{FIELD}}();"; return; } case ftUnionKey: @@ -1833,23 +1784,23 @@ class RustGenerator : public BaseGenerator { code_.SetValue("UNION_TYPE_METHOD", namer_.LegacyRustUnionTypeMethod(field)); - code_ += " let {{FIELD}} = match self.{{UNION_TYPE_METHOD}}() {"; - code_ += " {{ENUM_TY}}::NONE => {{NATIVE_ENUM_NAME}}::NONE,"; + code_ += " let {{FIELD}} = match self.{{UNION_TYPE_METHOD}}() {"; + code_ += " {{ENUM_TY}}::NONE => {{NATIVE_ENUM_NAME}}::NONE,"; ForAllUnionObjectVariantsBesidesNone(enum_def, [&] { code_ += - " {{ENUM_TY}}::{{VARIANT_NAME}} => " + " {{ENUM_TY}}::{{VARIANT_NAME}} => " "{{NATIVE_ENUM_NAME}}::{{NATIVE_VARIANT}}(alloc::boxed::Box::" "new("; - code_ += " self.{{FIELD}}_as_{{U_ELEMENT_NAME}}()"; + code_ += " self.{{FIELD}}_as_{{U_ELEMENT_NAME}}()"; code_ += - " .expect(\"Invalid union table, " + " .expect(\"Invalid union table, " "expected `{{ENUM_TY}}::{{VARIANT_NAME}}`.\")"; - code_ += " .unpack()"; - code_ += " )),"; + code_ += " .unpack()"; + code_ += " )),"; }); // Maybe we shouldn't throw away unknown discriminants? - code_ += " _ => {{NATIVE_ENUM_NAME}}::NONE,"; - code_ += " };"; + code_ += " _ => {{NATIVE_ENUM_NAME}}::NONE,"; + code_ += " };"; return; } // The rest of the types need special handling based on if the field @@ -1897,26 +1848,27 @@ class RustGenerator : public BaseGenerator { } } if (field.IsOptional()) { - code_ += " let {{FIELD}} = self.{{FIELD}}().map(|x| {"; - code_ += " {{EXPR}}"; - code_ += " });"; + code_ += " let {{FIELD}} = self.{{FIELD}}().map(|x| {"; + code_ += " {{EXPR}}"; + code_ += " });"; } else { - code_ += " let {{FIELD}} = {"; - code_ += " let x = self.{{FIELD}}();"; - code_ += " {{EXPR}}"; - code_ += " };"; + code_ += " let {{FIELD}} = {"; + code_ += " let x = self.{{FIELD}}();"; + code_ += " {{EXPR}}"; + code_ += " };"; } }); - - code_ += " {{STRUCT_OTY}} {"; + code_ += " {{STRUCT_OTY}} {"; ForAllObjectTableFields(struct_def, [&](const FieldDef& field) { if (field.value.type.base_type == BASE_TYPE_UTYPE) return; - code_ += " {{FIELD}},"; + code_ += " {{FIELD}},"; }); - code_ += " }"; code_ += " }"; + code_ += " }"; } + if (struct_def.fields.vec.size() > 0) code_ += ""; + // Generate the accessors. Each has one of two forms: // // If a value can be None: @@ -1929,17 +1881,16 @@ class RustGenerator : public BaseGenerator { // self._tab.get::(offset, defaultval).unwrap() // } ForAllTableFields(struct_def, [&](const FieldDef& field) { - code_ += ""; code_.SetValue("RETURN_TYPE", GenTableAccessorFuncReturnType(field, "'a")); this->GenComment(field.doc_comment); code_ += "#[inline]"; code_ += "pub fn {{FIELD}}(&self) -> {{RETURN_TYPE}} {"; - code_ += " // Safety:"; - code_ += " // Created from valid Table for this object"; - code_ += " // which contains a valid value in this slot"; - code_ += " " + GenTableAccessorFuncBody(field, "'a"); + code_ += " // Safety:"; + code_ += " // Created from valid Table for this object"; + code_ += " // which contains a valid value in this slot"; + code_ += " " + GenTableAccessorFuncBody(field, "'a"); code_ += "}"; // Generate a comparison function for this field if it is a key. @@ -1960,11 +1911,20 @@ class RustGenerator : public BaseGenerator { FLATBUFFERS_ASSERT(nested_root); // Guaranteed to exist by parser. code_.SetValue("NESTED", WrapInNameSpace(*nested_root)); - code_ += ""; code_ += "pub fn {{FIELD}}_nested_flatbuffer(&'a self) -> \\"; if (field.IsRequired()) { code_ += "{{NESTED}}<'a> {"; - code_ += " let data = self.{{FIELD}}();"; + code_ += " let data = self.{{FIELD}}();"; + code_ += " use ::flatbuffers::Follow;"; + code_ += " // Safety:"; + code_ += " // Created from a valid Table for this object"; + code_ += " // Which contains a valid flatbuffer in this slot"; + code_ += + " unsafe { <::flatbuffers::ForwardsUOffset<{{NESTED}}<'a>>>" + "::follow(data.bytes(), 0) }"; + } else { + code_ += "Option<{{NESTED}}<'a>> {"; + code_ += " self.{{FIELD}}().map(|data| {"; code_ += " use ::flatbuffers::Follow;"; code_ += " // Safety:"; code_ += " // Created from a valid Table for this object"; @@ -1972,18 +1932,7 @@ class RustGenerator : public BaseGenerator { code_ += " unsafe { <::flatbuffers::ForwardsUOffset<{{NESTED}}<'a>>>" "::follow(data.bytes(), 0) }"; - } else { - code_ += "Option<{{NESTED}}<'a>> {"; - code_ += " self.{{FIELD}}().map(|data| {"; - code_ += " use ::flatbuffers::Follow;"; - code_ += " // Safety:"; - code_ += " // Created from a valid Table for this object"; - code_ += " // Which contains a valid flatbuffer in this slot"; - code_ += - " unsafe { " - "<::flatbuffers::ForwardsUOffset<{{NESTED}}<'a>>>" - "::follow(data.bytes(), 0) }"; - code_ += " })"; + code_ += " })"; } code_ += "}"; } @@ -1995,7 +1944,6 @@ class RustGenerator : public BaseGenerator { ForAllUnionVariantsBesidesNone( *field.value.type.enum_def, [&](const EnumVal& unused) { (void)unused; - code_ += ""; code_ += "#[inline]"; code_ += "#[allow(non_snake_case)]"; code_ += @@ -2013,35 +1961,33 @@ class RustGenerator : public BaseGenerator { // // To avoid this problem the type field name is used unescaped here: code_ += - " if self.{{DISCRIMINANT}}() == {{U_ELEMENT_ENUM_TYPE}} {"; + " if self.{{DISCRIMINANT}}() == {{U_ELEMENT_ENUM_TYPE}} {"; // The following logic is not tested in the integration test, // as of April 10, 2020 if (field.IsRequired()) { - code_ += " let u = self.{{FIELD}}();"; - code_ += " // Safety:"; - code_ += " // Created from a valid Table for this object"; - code_ += " // Which contains a valid union in this slot"; + code_ += " let u = self.{{FIELD}}();"; + code_ += " // Safety:"; + code_ += " // Created from a valid Table for this object"; + code_ += " // Which contains a valid union in this slot"; code_ += " Some(unsafe { " "{{U_ELEMENT_TABLE_TYPE}}::init_from_table(u) })"; } else { - code_ += " self.{{FIELD}}().map(|t| {"; - code_ += " // Safety:"; + code_ += " self.{{FIELD}}().map(|t| {"; + code_ += " // Safety:"; + code_ += " // Created from a valid Table for this object"; + code_ += " // Which contains a valid union in this slot"; code_ += - " // Created from a valid Table for this object"; - code_ += - " // Which contains a valid union in this slot"; - code_ += - " unsafe { " - "{{U_ELEMENT_TABLE_TYPE}}::init_from_table(t) " + " unsafe { {{U_ELEMENT_TABLE_TYPE}}::init_from_table(t) " "}"; - code_ += " })"; + code_ += " })"; } - code_ += " } else {"; - code_ += " None"; - code_ += " }"; + code_ += " } else {"; + code_ += " None"; + code_ += " }"; code_ += "}"; + code_ += ""; }); }); code_ += "}"; // End of table impl. @@ -2049,11 +1995,11 @@ class RustGenerator : public BaseGenerator { // Generate Verifier; code_ += "impl ::flatbuffers::Verifiable for {{STRUCT_TY}}<'_> {"; - code_ += " #[inline]"; - code_ += " fn run_verifier("; - code_ += " v: &mut ::flatbuffers::Verifier, pos: usize"; - code_ += " ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> {"; - code_ += " v.visit_table(pos)?"; + code_ += " #[inline]"; + code_ += " fn run_verifier("; + code_ += " v: &mut ::flatbuffers::Verifier, pos: usize"; + code_ += " ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> {"; + code_ += " v.visit_table(pos)?\\"; // Escape newline and insert it onthe next line so we can end the builder // with a nice semicolon. ForAllTableFields(struct_def, [&](const FieldDef& field) { @@ -2064,8 +2010,8 @@ class RustGenerator : public BaseGenerator { // All types besides unions. code_.SetValue("TY", FollowType(field.value.type, "'_")); code_ += - " .visit_field::<{{TY}}>(\"{{FIELD}}\", " - "Self::{{OFFSET_NAME}}, {{IS_REQ}})?"; + "\n .visit_field::<{{TY}}>(\"{{FIELD}}\", " + "Self::{{OFFSET_NAME}}, {{IS_REQ}})?\\"; return; } // Unions. @@ -2076,28 +2022,26 @@ class RustGenerator : public BaseGenerator { code_.SetValue("UNION_TYPE_METHOD", namer_.LegacyRustUnionTypeMethod(field)); code_ += - " .visit_union::<{{UNION_TYPE}}, _>(" + "\n .visit_union::<{{UNION_TYPE}}, _>(" "\"{{UNION_TYPE_METHOD}}\", Self::{{UNION_TYPE_OFFSET_NAME}}, " "\"{{FIELD}}\", Self::{{OFFSET_NAME}}, {{IS_REQ}}, " "|key, v, pos| {"; - code_ += " match key {"; + code_ += " match key {"; ForAllUnionVariantsBesidesNone(union_def, [&](const EnumVal& unused) { (void)unused; code_ += - " {{U_ELEMENT_ENUM_TYPE}} => " - "v.verify_union_variant::" + " {{U_ELEMENT_ENUM_TYPE}} => v.verify_union_variant::" "<::flatbuffers::ForwardsUOffset<{{U_ELEMENT_TABLE_TYPE}}>>(" "\"{{U_ELEMENT_ENUM_TYPE}}\", pos),"; }); - code_ += " _ => Ok(()),"; - code_ += " }"; - code_ += " })?"; + code_ += " _ => Ok(()),"; + code_ += " }"; + code_ += " })?\\"; }); - code_ += " .finish();"; - code_ += " Ok(())"; - code_ += " }"; + code_ += "\n .finish();"; + code_ += " Ok(())"; + code_ += " }"; code_ += "}"; - code_ += ""; // Generate an args struct: code_.SetValue("MAYBE_LT", @@ -2105,22 +2049,21 @@ class RustGenerator : public BaseGenerator { code_ += "{{ACCESS_TYPE}} struct {{STRUCT_TY}}Args{{MAYBE_LT}} {"; ForAllTableFields(struct_def, [&](const FieldDef& field) { code_.SetValue("PARAM_TYPE", TableBuilderArgsDefnType(field, "'a")); - code_ += "pub {{FIELD}}: {{PARAM_TYPE}},"; + code_ += " pub {{FIELD}}: {{PARAM_TYPE}},"; }); code_ += "}"; - code_ += ""; // Generate an impl of Default for the *Args type: code_ += "impl<'a> Default for {{STRUCT_TY}}Args{{MAYBE_LT}} {"; - code_ += " #[inline]"; - code_ += " fn default() -> Self {"; - code_ += " {{STRUCT_TY}}Args {"; + code_ += " #[inline]"; + code_ += " fn default() -> Self {"; + code_ += " {{STRUCT_TY}}Args {"; ForAllTableFields(struct_def, [&](const FieldDef& field) { - code_ += " {{FIELD}}: {{BLDR_DEF_VAL}},\\"; + code_ += " {{FIELD}}: {{BLDR_DEF_VAL}},\\"; code_ += field.IsRequired() ? " // required field" : ""; }); - code_ += " }"; code_ += " }"; + code_ += " }"; code_ += "}"; code_ += ""; @@ -2130,19 +2073,17 @@ class RustGenerator : public BaseGenerator { code_.SetValue("NUM_FIELDS", NumToString(numFields)); code_ += "impl Serialize for {{STRUCT_TY}}<'_> {"; code_ += - " fn serialize(&self, serializer: S) -> Result"; - code_ += " where"; - code_ += " S: Serializer,"; - code_ += " {"; + " fn serialize(&self, serializer: S) -> Result"; + code_ += " where"; + code_ += " S: Serializer,"; + code_ += " {"; if (numFields == 0) { code_ += - " let s = serializer.serialize_struct(\"{{STRUCT_TY}}\", " - "0)?;"; + " let s = serializer.serialize_struct(\"{{STRUCT_TY}}\", 0)?;"; } else { code_ += - " let mut s = " - "serializer.serialize_struct(\"{{STRUCT_TY}}\", {{NUM_FIELDS}})?;"; + " let mut s = serializer.serialize_struct(\"{{STRUCT_TY}}\", " + "{{NUM_FIELDS}})?;"; } ForAllTableFields(struct_def, [&](const FieldDef& field) { const Type& type = field.value.type; @@ -2155,20 +2096,20 @@ class RustGenerator : public BaseGenerator { namer_.LegacyRustUnionTypeMethod(field)); code_ += " match self.{{UNION_TYPE_METHOD}}() {"; - code_ += " {{ENUM_TY}}::NONE => (),"; + code_ += " {{ENUM_TY}}::NONE => (),"; ForAllUnionObjectVariantsBesidesNone(enum_def, [&] { code_.SetValue("FIELD", namer_.Field(field)); - code_ += " {{ENUM_TY}}::{{VARIANT_NAME}} => {"; + code_ += " {{ENUM_TY}}::{{VARIANT_NAME}} => {"; code_ += - " let f = " + " let f = " "self.{{FIELD}}_as_{{U_ELEMENT_NAME}}()"; code_ += - " .expect(\"Invalid union table, expected " + " .expect(\"Invalid union table, expected " "`{{ENUM_TY}}::{{VARIANT_NAME}}`.\");"; - code_ += " s.serialize_field(\"{{FIELD}}\", &f)?;"; - code_ += " }"; + code_ += " s.serialize_field(\"{{FIELD}}\", &f)?;"; + code_ += " }"; }); - code_ += " _ => unimplemented!(),"; + code_ += " _ => unimplemented!(),"; code_ += " }"; } else { code_ += @@ -2178,9 +2119,9 @@ class RustGenerator : public BaseGenerator { } else { if (field.IsOptional()) { code_ += " if let Some(f) = self.{{FIELD}}() {"; - code_ += " s.serialize_field(\"{{FIELD}}\", &f)?;"; + code_ += " s.serialize_field(\"{{FIELD}}\", &f)?;"; code_ += " } else {"; - code_ += " s.skip_field(\"{{FIELD}}\")?;"; + code_ += " s.skip_field(\"{{FIELD}}\")?;"; code_ += " }"; } else { code_ += @@ -2189,8 +2130,8 @@ class RustGenerator : public BaseGenerator { } } }); - code_ += " s.end()"; - code_ += " }"; + code_ += " s.end()"; + code_ += " }"; code_ += "}"; code_ += ""; } @@ -2199,12 +2140,11 @@ class RustGenerator : public BaseGenerator { code_ += "{{ACCESS_TYPE}} struct {{STRUCT_TY}}Builder<'a: 'b, 'b, A: " "::flatbuffers::Allocator + 'a> {"; - code_ += " fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>,"; + code_ += " fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>,"; code_ += - " start_: ::flatbuffers::WIPOffset<" + " start_: ::flatbuffers::WIPOffset<" "::flatbuffers::TableUnfinishedWIPOffset>,"; code_ += "}"; - code_ += ""; // Generate builder functions: code_ += @@ -2234,53 +2174,51 @@ class RustGenerator : public BaseGenerator { "{{FIELD_TYPE}}) {"; if (is_scalar && !field.IsOptional()) { code_ += - " {{FUNC_BODY}}({{FIELD_OFFSET}}, {{FIELD}}, " + " {{FUNC_BODY}}({{FIELD_OFFSET}}, {{FIELD}}, " "{{BLDR_DEF_VAL}});"; } else { - code_ += " {{FUNC_BODY}}({{FIELD_OFFSET}}, {{FIELD}});"; + code_ += " {{FUNC_BODY}}({{FIELD_OFFSET}}, {{FIELD}});"; } code_ += "}"; - code_ += ""; }); // Struct initializer (all fields required); - code_ += " #[inline]"; + code_ += " #[inline]"; code_ += - " pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) " + " pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) " "-> " "{{STRUCT_TY}}Builder<'a, 'b, A> {"; code_.SetValue("NUM_FIELDS", NumToString(struct_def.fields.vec.size())); - code_ += " let start = _fbb.start_table();"; - code_ += " {{STRUCT_TY}}Builder {"; - code_ += " fbb_: _fbb,"; - code_ += " start_: start,"; - code_ += " }"; + code_ += " let start = _fbb.start_table();"; + code_ += " {{STRUCT_TY}}Builder {"; + code_ += " fbb_: _fbb,"; + code_ += " start_: start,"; code_ += " }"; - code_ += ""; + code_ += " }"; // finish() function. - code_ += " #[inline]"; + code_ += " #[inline]"; code_ += - " pub fn finish(self) -> " + " pub fn finish(self) -> " "::flatbuffers::WIPOffset<{{STRUCT_TY}}<'a>> {"; - code_ += " let o = self.fbb_.end_table(self.start_);"; + code_ += " let o = self.fbb_.end_table(self.start_);"; ForAllTableFields(struct_def, [&](const FieldDef& field) { if (!field.IsRequired()) return; code_ += - " self.fbb_.required(o, {{STRUCT_TY}}::{{OFFSET_NAME}}," + " self.fbb_.required(o, {{STRUCT_TY}}::{{OFFSET_NAME}}," "\"{{FIELD}}\");"; }); - code_ += " ::flatbuffers::WIPOffset::new(o.value())"; - code_ += " }"; + code_ += " ::flatbuffers::WIPOffset::new(o.value())"; + code_ += " }"; code_ += "}"; code_ += ""; code_ += "impl ::core::fmt::Debug for {{STRUCT_TY}}<'_> {"; code_ += - " fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>" + " fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>" ") -> ::core::fmt::Result {"; - code_ += " let mut ds = f.debug_struct(\"{{STRUCT_TY}}\");"; + code_ += " let mut ds = f.debug_struct(\"{{STRUCT_TY}}\");"; ForAllTableFields(struct_def, [&](const FieldDef& field) { if (GetFullType(field.value.type) == ftUnionValue) { // Generate a match statement to handle unions properly. @@ -2293,35 +2231,33 @@ class RustGenerator : public BaseGenerator { ForAllUnionVariantsBesidesNone( *field.value.type.enum_def, [&](const EnumVal& unused) { (void)unused; - code_ += " {{U_ELEMENT_ENUM_TYPE}} => {"; + code_ += " {{U_ELEMENT_ENUM_TYPE}} => {"; code_ += - " if let Some(x) = " + " if let Some(x) = " "self.{{FIELD}}_as_" "{{U_ELEMENT_NAME}}() {"; - code_ += " ds.field(\"{{FIELD}}\", &x)"; - code_ += " } else {"; - code_ += " ds.field(\"{{FIELD}}\", {{UNION_ERR}})"; - code_ += " }"; - code_ += " },"; + code_ += " ds.field(\"{{FIELD}}\", &x)"; + code_ += " } else {"; + code_ += " ds.field(\"{{FIELD}}\", {{UNION_ERR}})"; + code_ += " }"; + code_ += " },"; }); - code_ += " _ => {"; - code_ += " let x: Option<()> = None;"; - code_ += " ds.field(\"{{FIELD}}\", &x)"; - code_ += " },"; + code_ += " _ => {"; + code_ += " let x: Option<()> = None;"; + code_ += " ds.field(\"{{FIELD}}\", &x)"; + code_ += " },"; code_ += " };"; } else { // Most fields. code_ += " ds.field(\"{{FIELD}}\", &self.{{FIELD}}());"; } }); - code_ += " ds.finish()"; - code_ += " }"; + code_ += " ds.finish()"; + code_ += " }"; code_ += "}"; } void GenTableObject(const StructDef& table) { - code_ += ""; - code_.SetValue("STRUCT_OTY", namer_.ObjectType(table)); code_.SetValue("STRUCT_TY", namer_.Type(table)); @@ -2336,30 +2272,28 @@ class RustGenerator : public BaseGenerator { code_ += "pub {{FIELD}}: {{FIELD_OTY}},"; }); code_ += "}"; - code_ += ""; code_ += "impl Default for {{STRUCT_OTY}} {"; - code_ += " fn default() -> Self {"; - code_ += " Self {"; + code_ += " fn default() -> Self {"; + code_ += " Self {"; ForAllObjectTableFields(table, [&](const FieldDef& field) { if (field.value.type.base_type == BASE_TYPE_UTYPE) return; std::string default_value = GetDefaultValue(field, kObject); - code_ += " {{FIELD}}: " + default_value + ","; + code_ += " {{FIELD}}: " + default_value + ","; }); - code_ += " }"; code_ += " }"; + code_ += " }"; code_ += "}"; - code_ += ""; // TODO(cneo): Generate defaults for Native tables. However, since structs // may be required, they, and therefore enums need defaults. // Generate pack function. code_ += "impl {{STRUCT_OTY}} {"; - code_ += " pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>("; - code_ += " &self,"; - code_ += " _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A>"; - code_ += " ) -> ::flatbuffers::WIPOffset<{{STRUCT_TY}}<'b>> {"; + code_ += " pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>("; + code_ += " &self,"; + code_ += " _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A>"; + code_ += " ) -> ::flatbuffers::WIPOffset<{{STRUCT_TY}}<'b>> {"; // First we generate variables for each field and then later assemble them // using "StructArgs" to more easily manage ownership of the builder. ForAllObjectTableFields(table, [&](const FieldDef& field) { @@ -2369,7 +2303,7 @@ class RustGenerator : public BaseGenerator { case ftBool: case ftFloat: case ftEnumKey: { - code_ += " let {{FIELD}} = self.{{FIELD}};"; + code_ += " let {{FIELD}} = self.{{FIELD}};"; return; } case ftUnionKey: @@ -2380,9 +2314,9 @@ class RustGenerator : public BaseGenerator { code_.SetValue("DISCRIMINANT", namer_.LegacyRustUnionTypeMethod(field)); code_ += - " let {{DISCRIMINANT}} = " + " let {{DISCRIMINANT}} = " "self.{{FIELD}}.{{ENUM_METHOD}}_type();"; - code_ += " let {{FIELD}} = self.{{FIELD}}.pack(_fbb);"; + code_ += " let {{FIELD}} = self.{{FIELD}}.pack(_fbb);"; return; } // The rest of the types require special casing around optionalness @@ -2394,13 +2328,13 @@ class RustGenerator : public BaseGenerator { case ftStruct: { // Hold the struct in a variable so we can reference it. if (field.IsRequired()) { - code_ += " let {{FIELD}}_tmp = Some(self.{{FIELD}}.pack());"; + code_ += " let {{FIELD}}_tmp = Some(self.{{FIELD}}.pack());"; } else { code_ += - " let {{FIELD}}_tmp = self.{{FIELD}}" + " let {{FIELD}}_tmp = self.{{FIELD}}" ".as_ref().map(|x| x.pack());"; } - code_ += " let {{FIELD}} = {{FIELD}}_tmp.as_ref();"; + code_ += " let {{FIELD}} = {{FIELD}}_tmp.as_ref();"; return; } @@ -2451,13 +2385,13 @@ class RustGenerator : public BaseGenerator { } } }); - code_ += " {{STRUCT_TY}}::create(_fbb, &{{STRUCT_TY}}Args{"; + code_ += " {{STRUCT_TY}}::create(_fbb, &{{STRUCT_TY}}Args{"; ForAllObjectTableFields(table, [&](const FieldDef& field) { (void)field; // Unused. - code_ += " {{FIELD}},"; + code_ += " {{FIELD}},"; }); - code_ += " })"; - code_ += " }"; + code_ += " })"; + code_ += " }"; code_ += "}"; } void ForAllObjectTableFields(const StructDef& table, @@ -2475,16 +2409,16 @@ class RustGenerator : public BaseGenerator { } void MapNativeTableField(const FieldDef& field, const std::string& expr) { if (field.IsOptional()) { - code_ += " let {{FIELD}} = self.{{FIELD}}.as_ref().map(|x|{"; - code_ += " " + expr; - code_ += " });"; + code_ += " let {{FIELD}} = self.{{FIELD}}.as_ref().map(|x|{"; + code_ += " " + expr; + code_ += " });"; } else { // For some reason Args has optional types for required fields. // TODO(cneo): Fix this... but its a breaking change? - code_ += " let {{FIELD}} = Some({"; - code_ += " let x = &self.{{FIELD}};"; - code_ += " " + expr; - code_ += " });"; + code_ += " let {{FIELD}} = Some({"; + code_ += " let x = &self.{{FIELD}};"; + code_ += " " + expr; + code_ += " });"; } } @@ -2496,106 +2430,93 @@ class RustGenerator : public BaseGenerator { code_.SetValue("KEY_TYPE", GenTableAccessorFuncReturnType(field, "")); code_.SetValue("REF", IsString(field.value.type) ? "" : "&"); - code_ += ""; - code_ += "#[inline]"; code_ += "pub fn key_compare_less_than(&self, o: &{{STRUCT_TY}}) -> " "bool {"; - code_ += " self.{{FIELD}}() < o.{{FIELD}}()"; + code_ += " self.{{FIELD}}() < o.{{FIELD}}()"; code_ += "}"; code_ += ""; - code_ += "#[inline]"; code_ += "pub fn key_compare_with_value(&self, val: {{KEY_TYPE}}) -> " "::core::cmp::Ordering {"; - code_ += " let key = self.{{FIELD}}();"; - code_ += " key.cmp({{REF}}val)"; + code_ += " let key = self.{{FIELD}}();"; + code_ += " key.cmp({{REF}}val)"; code_ += "}"; } // Generate functions for accessing the root table object. This function // must only be called if the root table is defined. void GenRootTableFuncs(const StructDef& struct_def) { - code_ += ""; - FLATBUFFERS_ASSERT(parser_.root_struct_def_ && "root table not defined"); code_.SetValue("STRUCT_TY", namer_.Type(struct_def)); code_.SetValue("STRUCT_FN", namer_.Function(struct_def)); code_.SetValue("STRUCT_CONST", namer_.Constant(struct_def.name)); // Default verifier root fns. + code_ += "#[inline]"; code_ += "/// Verifies that a buffer of bytes contains a `{{STRUCT_TY}}`"; code_ += "/// and returns it."; code_ += "/// Note that verification is still experimental and may not"; code_ += "/// catch every error, or be maximally performant. For the"; code_ += "/// previous, unchecked, behavior use"; code_ += "/// `root_as_{{STRUCT_FN}}_unchecked`."; - code_ += "#[inline]"; code_ += "pub fn root_as_{{STRUCT_FN}}(buf: &[u8]) " "-> Result<{{STRUCT_TY}}<'_>, ::flatbuffers::InvalidFlatbuffer> {"; - code_ += " ::flatbuffers::root::<{{STRUCT_TY}}>(buf)"; + code_ += " ::flatbuffers::root::<{{STRUCT_TY}}>(buf)"; code_ += "}"; - code_ += ""; - + code_ += "#[inline]"; code_ += "/// Verifies that a buffer of bytes contains a size prefixed"; code_ += "/// `{{STRUCT_TY}}` and returns it."; code_ += "/// Note that verification is still experimental and may not"; code_ += "/// catch every error, or be maximally performant. For the"; code_ += "/// previous, unchecked, behavior use"; code_ += "/// `size_prefixed_root_as_{{STRUCT_FN}}_unchecked`."; - code_ += "#[inline]"; code_ += "pub fn size_prefixed_root_as_{{STRUCT_FN}}" "(buf: &[u8]) -> Result<{{STRUCT_TY}}<'_>, " "::flatbuffers::InvalidFlatbuffer> {"; - code_ += " ::flatbuffers::size_prefixed_root::<{{STRUCT_TY}}>(buf)"; + code_ += " ::flatbuffers::size_prefixed_root::<{{STRUCT_TY}}>(buf)"; code_ += "}"; - code_ += ""; - // Verifier with options root fns. + code_ += "#[inline]"; code_ += "/// Verifies, with the given options, that a buffer of bytes"; code_ += "/// contains a `{{STRUCT_TY}}` and returns it."; code_ += "/// Note that verification is still experimental and may not"; code_ += "/// catch every error, or be maximally performant. For the"; code_ += "/// previous, unchecked, behavior use"; code_ += "/// `root_as_{{STRUCT_FN}}_unchecked`."; - code_ += "#[inline]"; code_ += "pub fn root_as_{{STRUCT_FN}}_with_opts<'b, 'o>("; - code_ += " opts: &'o ::flatbuffers::VerifierOptions,"; - code_ += " buf: &'b [u8],"; + code_ += " opts: &'o ::flatbuffers::VerifierOptions,"; + code_ += " buf: &'b [u8],"; code_ += ") -> Result<{{STRUCT_TY}}<'b>, ::flatbuffers::InvalidFlatbuffer>" " {"; - code_ += - " ::flatbuffers::root_with_opts::<{{STRUCT_TY}}<'b>>(opts, buf)"; + code_ += " ::flatbuffers::root_with_opts::<{{STRUCT_TY}}<'b>>(opts, buf)"; code_ += "}"; - code_ += ""; - + code_ += "#[inline]"; code_ += "/// Verifies, with the given verifier options, that a buffer of"; code_ += "/// bytes contains a size prefixed `{{STRUCT_TY}}` and returns"; code_ += "/// it. Note that verification is still experimental and may not"; code_ += "/// catch every error, or be maximally performant. For the"; code_ += "/// previous, unchecked, behavior use"; code_ += "/// `root_as_{{STRUCT_FN}}_unchecked`."; - code_ += "#[inline]"; code_ += "pub fn size_prefixed_root_as_{{STRUCT_FN}}_with_opts" "<'b, 'o>("; - code_ += " opts: &'o ::flatbuffers::VerifierOptions,"; - code_ += " buf: &'b [u8],"; + code_ += " opts: &'o ::flatbuffers::VerifierOptions,"; + code_ += " buf: &'b [u8],"; code_ += ") -> Result<{{STRUCT_TY}}<'b>, ::flatbuffers::InvalidFlatbuffer>" " {"; code_ += - " ::flatbuffers::size_prefixed_root_with_opts::<{{STRUCT_TY}}" + " ::flatbuffers::size_prefixed_root_with_opts::<{{STRUCT_TY}}" "<'b>>(opts, buf)"; code_ += "}"; - code_ += ""; - // Unchecked root fns. + code_ += "#[inline]"; code_ += "/// Assumes, without verification, that a buffer of bytes " "contains a {{STRUCT_TY}} and returns it."; @@ -2603,15 +2524,12 @@ class RustGenerator : public BaseGenerator { code_ += "/// Callers must trust the given bytes do indeed contain a valid" " `{{STRUCT_TY}}`."; - code_ += "#[inline]"; code_ += "pub unsafe fn root_as_{{STRUCT_FN}}_unchecked" "(buf: &[u8]) -> {{STRUCT_TY}}<'_> {"; - code_ += - " unsafe { ::flatbuffers::root_unchecked::<{{STRUCT_TY}}>(buf) }"; + code_ += " unsafe { ::flatbuffers::root_unchecked::<{{STRUCT_TY}}>(buf) }"; code_ += "}"; - code_ += ""; - + code_ += "#[inline]"; code_ += "/// Assumes, without verification, that a buffer of bytes " "contains a size prefixed {{STRUCT_TY}} and returns it."; @@ -2619,16 +2537,14 @@ class RustGenerator : public BaseGenerator { code_ += "/// Callers must trust the given bytes do indeed contain a valid" " size prefixed `{{STRUCT_TY}}`."; - code_ += "#[inline]"; code_ += "pub unsafe fn size_prefixed_root_as_{{STRUCT_FN}}" "_unchecked(buf: &[u8]) -> {{STRUCT_TY}}<'_> {"; code_ += - " unsafe { " + " unsafe { " "::flatbuffers::size_prefixed_root_unchecked::<{{STRUCT_TY}}>" "(buf) }"; code_ += "}"; - code_ += ""; if (parser_.file_identifier_.length()) { // Declare the identifier @@ -2641,14 +2557,14 @@ class RustGenerator : public BaseGenerator { code_ += "#[inline]"; code_ += "pub fn {{STRUCT_FN}}_buffer_has_identifier\\"; code_ += "(buf: &[u8]) -> bool {"; - code_ += " ::flatbuffers::buffer_has_identifier(buf, \\"; + code_ += " ::flatbuffers::buffer_has_identifier(buf, \\"; code_ += "{{STRUCT_CONST}}_IDENTIFIER, false)"; code_ += "}"; code_ += ""; code_ += "#[inline]"; code_ += "pub fn {{STRUCT_FN}}_size_prefixed\\"; code_ += "_buffer_has_identifier(buf: &[u8]) -> bool {"; - code_ += " ::flatbuffers::buffer_has_identifier(buf, \\"; + code_ += " ::flatbuffers::buffer_has_identifier(buf, \\"; code_ += "{{STRUCT_CONST}}_IDENTIFIER, true)"; code_ += "}"; code_ += ""; @@ -2667,28 +2583,26 @@ class RustGenerator : public BaseGenerator { "pub fn finish_{{STRUCT_FN}}_buffer<'a, 'b, A: " "::flatbuffers::Allocator + 'a>("; code_ += " fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>,"; - code_ += " root: ::flatbuffers::WIPOffset<{{STRUCT_TY}}<'a>>"; - code_ += ") {"; + code_ += " root: ::flatbuffers::WIPOffset<{{STRUCT_TY}}<'a>>) {"; if (parser_.file_identifier_.length()) { - code_ += " fbb.finish(root, Some({{STRUCT_CONST}}_IDENTIFIER));"; + code_ += " fbb.finish(root, Some({{STRUCT_CONST}}_IDENTIFIER));"; } else { - code_ += " fbb.finish(root, None);"; + code_ += " fbb.finish(root, None);"; } code_ += "}"; code_ += ""; code_ += "#[inline]"; code_ += "pub fn finish_size_prefixed_{{STRUCT_FN}}_buffer" - "<'a, 'b, A: ::flatbuffers::Allocator + 'a>("; - code_ += " fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>,"; - code_ += " root: ::flatbuffers::WIPOffset<{{STRUCT_TY}}<'a>>"; - code_ += ") {"; + "<'a, 'b, A: ::flatbuffers::Allocator + 'a>(" + "fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, " + "root: ::flatbuffers::WIPOffset<{{STRUCT_TY}}<'a>>) {"; if (parser_.file_identifier_.length()) { code_ += - " fbb.finish_size_prefixed(root, " + " fbb.finish_size_prefixed(root, " "Some({{STRUCT_CONST}}_IDENTIFIER));"; } else { - code_ += " fbb.finish_size_prefixed(root, None);"; + code_ += " fbb.finish_size_prefixed(root, None);"; } code_ += "}"; } @@ -2738,8 +2652,6 @@ class RustGenerator : public BaseGenerator { } // Generate an accessor struct with constructor for a flatbuffers struct. void GenStruct(const StructDef& struct_def) { - code_ += ""; - const bool is_private = parser_.opts.no_leak_private_annotations && (struct_def.attributes.Lookup("private") != nullptr); @@ -2762,27 +2674,24 @@ class RustGenerator : public BaseGenerator { code_ += "#[repr(transparent)]"; code_ += "#[derive(Clone, Copy, PartialEq)]"; code_ += "{{ACCESS_TYPE}} struct {{STRUCT_TY}}(pub [u8; {{STRUCT_SIZE}}]);"; - code_ += ""; - - code_ += "impl Default for {{STRUCT_TY}} {"; - code_ += " fn default() -> Self {"; - code_ += " Self([0; {{STRUCT_SIZE}}])"; - code_ += " }"; + code_ += "impl Default for {{STRUCT_TY}} { "; + code_ += " fn default() -> Self { "; + code_ += " Self([0; {{STRUCT_SIZE}}])"; + code_ += " }"; code_ += "}"; - code_ += ""; // Debug for structs. code_ += "impl ::core::fmt::Debug for {{STRUCT_TY}} {"; code_ += - " fn fmt(&self, f: &mut ::core::fmt::Formatter" + " fn fmt(&self, f: &mut ::core::fmt::Formatter" ") -> ::core::fmt::Result {"; - code_ += " f.debug_struct(\"{{STRUCT_TY}}\")"; + code_ += " f.debug_struct(\"{{STRUCT_TY}}\")"; ForAllStructFields(struct_def, [&](const FieldDef& unused) { (void)unused; - code_ += " .field(\"{{FIELD}}\", &self.{{FIELD}}())"; + code_ += " .field(\"{{FIELD}}\", &self.{{FIELD}}())"; }); - code_ += " .finish()"; - code_ += " }"; + code_ += " .finish()"; + code_ += " }"; code_ += "}"; code_ += ""; @@ -2790,33 +2699,24 @@ class RustGenerator : public BaseGenerator { // Follow for the value type, Follow for the reference type, Push for the // value type, and Push for the reference type. code_ += "impl ::flatbuffers::SimpleToVerifyInSlice for {{STRUCT_TY}} {}"; - code_ += ""; - code_ += "impl<'a> ::flatbuffers::Follow<'a> for {{STRUCT_TY}} {"; - code_ += " type Inner = &'a {{STRUCT_TY}};"; - code_ += ""; - code_ += " #[inline]"; - code_ += " unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {"; - code_ += " unsafe { <&'a {{STRUCT_TY}}>::follow(buf, loc) }"; - code_ += " }"; + code_ += " type Inner = &'a {{STRUCT_TY}};"; + code_ += " #[inline]"; + code_ += " unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {"; + code_ += " unsafe { <&'a {{STRUCT_TY}}>::follow(buf, loc) }"; + code_ += " }"; code_ += "}"; - code_ += ""; - code_ += "impl<'a> ::flatbuffers::Follow<'a> for &'a {{STRUCT_TY}} {"; - code_ += " type Inner = &'a {{STRUCT_TY}};"; - code_ += ""; - code_ += " #[inline]"; - code_ += " unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {"; + code_ += " type Inner = &'a {{STRUCT_TY}};"; + code_ += " #[inline]"; + code_ += " unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {"; code_ += - " unsafe { ::flatbuffers::follow_cast_ref::<{{STRUCT_TY}}>(buf, " + " unsafe { ::flatbuffers::follow_cast_ref::<{{STRUCT_TY}}>(buf, " "loc) }"; - code_ += " }"; + code_ += " }"; code_ += "}"; - code_ += ""; - code_ += "impl<'b> ::flatbuffers::Push for {{STRUCT_TY}} {"; code_ += " type Output = {{STRUCT_TY}};"; - code_ += ""; code_ += " #[inline]"; code_ += " unsafe fn push(&self, dst: &mut [u8], _written_len: usize) {"; code_ += @@ -2825,8 +2725,6 @@ class RustGenerator : public BaseGenerator { "{{STRUCT_TY}} as *const u8, ::size()) };"; code_ += " dst.copy_from_slice(src);"; code_ += " }"; - code_ += ""; - code_ += " #[inline]"; code_ += " fn alignment() -> ::flatbuffers::PushAlignment {"; code_ += " ::flatbuffers::PushAlignment::new({{ALIGN}})"; @@ -2837,12 +2735,12 @@ class RustGenerator : public BaseGenerator { // Generate verifier: Structs are simple so presence and alignment are // all that need to be checked. code_ += "impl<'a> ::flatbuffers::Verifiable for {{STRUCT_TY}} {"; - code_ += " #[inline]"; - code_ += " fn run_verifier("; - code_ += " v: &mut ::flatbuffers::Verifier, pos: usize"; - code_ += " ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> {"; - code_ += " v.in_buffer::(pos)"; - code_ += " }"; + code_ += " #[inline]"; + code_ += " fn run_verifier("; + code_ += " v: &mut ::flatbuffers::Verifier, pos: usize"; + code_ += " ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> {"; + code_ += " v.in_buffer::(pos)"; + code_ += " }"; code_ += "}"; code_ += ""; @@ -2852,11 +2750,10 @@ class RustGenerator : public BaseGenerator { code_.SetValue("NUM_FIELDS", NumToString(numFields)); code_ += "impl Serialize for {{STRUCT_TY}} {"; code_ += - " fn serialize(&self, serializer: S) -> Result"; - code_ += " where"; - code_ += " S: Serializer,"; - code_ += " {"; + " fn serialize(&self, serializer: S) -> Result"; + code_ += " where"; + code_ += " S: Serializer,"; + code_ += " {"; if (numFields == 0) { code_ += " let s = serializer.serialize_struct(\"{{STRUCT_TY}}\", 0)?;"; @@ -2871,28 +2768,28 @@ class RustGenerator : public BaseGenerator { " s.serialize_field(\"{{FIELD}}\", " "&self.{{FIELD}}())?;"; }); - code_ += " s.end()"; - code_ += " }"; + code_ += " s.end()"; + code_ += " }"; code_ += "}"; code_ += ""; } // Generate a constructor that takes all fields as arguments. code_ += "impl<'a> {{STRUCT_TY}} {"; - code_ += " #[allow(clippy::too_many_arguments)]"; - code_ += " pub fn new("; + code_ += " #[allow(clippy::too_many_arguments)]"; + code_ += " pub fn new("; ForAllStructFields(struct_def, [&](const FieldDef& unused) { (void)unused; - code_ += " {{FIELD}}: {{REF}}{{FIELD_TYPE}},"; + code_ += " {{FIELD}}: {{REF}}{{FIELD_TYPE}},"; }); - code_ += " ) -> Self {"; - code_ += " let mut s = Self([0; {{STRUCT_SIZE}}]);"; + code_ += " ) -> Self {"; + code_ += " let mut s = Self([0; {{STRUCT_SIZE}}]);"; ForAllStructFields(struct_def, [&](const FieldDef& unused) { (void)unused; - code_ += " s.set_{{FIELD}}({{FIELD}});"; + code_ += " s.set_{{FIELD}}({{FIELD}});"; }); - code_ += " s"; - code_ += " }"; + code_ += " s"; + code_ += " }"; code_ += ""; if (parser_.opts.generate_name_strings) { @@ -2905,11 +2802,11 @@ class RustGenerator : public BaseGenerator { // Getter. if (IsStruct(field.value.type)) { code_ += "pub fn {{FIELD}}(&self) -> &{{FIELD_TYPE}} {"; - code_ += " // Safety:"; - code_ += " // Created from a valid Table for this object"; - code_ += " // Which contains a valid struct in this slot"; + code_ += " // Safety:"; + code_ += " // Created from a valid Table for this object"; + code_ += " // Which contains a valid struct in this slot"; code_ += - " unsafe {" + " unsafe {" " &*(self.0[{{FIELD_OFFSET}}..].as_ptr() as *const" " {{FIELD_TYPE}}) }"; } else if (IsArray(field.value.type)) { @@ -2919,33 +2816,33 @@ class RustGenerator : public BaseGenerator { code_ += "pub fn {{FIELD}}(&'a self) -> " "::flatbuffers::Array<'a, {{ARRAY_ITEM}}, {{ARRAY_SIZE}}> {"; - code_ += " // Safety:"; - code_ += " // Created from a valid Table for this object"; - code_ += " // Which contains a valid array in this slot"; - code_ += " use ::flatbuffers::Follow;"; + code_ += " // Safety:"; + code_ += " // Created from a valid Table for this object"; + code_ += " // Which contains a valid array in this slot"; + code_ += " use ::flatbuffers::Follow;"; code_ += - " unsafe { ::flatbuffers::Array::follow(&self.0, " + " unsafe { ::flatbuffers::Array::follow(&self.0, " "{{FIELD_OFFSET}}) " "}"; } else { code_ += "pub fn {{FIELD}}(&self) -> {{FIELD_TYPE}} {"; code_ += - " let mut mem = ::core::mem::MaybeUninit::" + " let mut mem = ::core::mem::MaybeUninit::" "<<{{FIELD_TYPE}} as " "::flatbuffers::EndianScalar>::Scalar>::uninit();"; - code_ += " // Safety:"; - code_ += " // Created from a valid Table for this object"; - code_ += " // Which contains a valid value in this slot"; - code_ += " ::flatbuffers::EndianScalar::from_little_endian(unsafe {"; - code_ += " ::core::ptr::copy_nonoverlapping("; - code_ += " self.0[{{FIELD_OFFSET}}..].as_ptr(),"; - code_ += " mem.as_mut_ptr() as *mut u8,"; + code_ += " // Safety:"; + code_ += " // Created from a valid Table for this object"; + code_ += " // Which contains a valid value in this slot"; + code_ += " ::flatbuffers::EndianScalar::from_little_endian(unsafe {"; + code_ += " ::core::ptr::copy_nonoverlapping("; + code_ += " self.0[{{FIELD_OFFSET}}..].as_ptr(),"; + code_ += " mem.as_mut_ptr() as *mut u8,"; code_ += - " ::core::mem::size_of::<<{{FIELD_TYPE}} as " + " ::core::mem::size_of::<<{{FIELD_TYPE}} as " "::flatbuffers::EndianScalar>::Scalar>(),"; - code_ += " );"; - code_ += " mem.assume_init()"; - code_ += " })"; + code_ += " );"; + code_ += " mem.assume_init()"; + code_ += " })"; } code_ += "}\n"; // Setter. @@ -2954,7 +2851,7 @@ class RustGenerator : public BaseGenerator { code_ += "#[allow(clippy::identity_op)]"; // If FIELD_OFFSET=0. code_ += "pub fn set_{{FIELD}}(&mut self, x: &{{FIELD_TYPE}}) {"; code_ += - " self.0[{{FIELD_OFFSET}}..{{FIELD_OFFSET}} + {{FIELD_SIZE}}]" + " self.0[{{FIELD_OFFSET}}..{{FIELD_OFFSET}} + {{FIELD_SIZE}}]" ".copy_from_slice(&x.0)"; } else if (IsArray(field.value.type)) { if (GetFullType(field.value.type) == ftArrayOfBuiltin) { @@ -2966,43 +2863,43 @@ class RustGenerator : public BaseGenerator { code_ += "pub fn set_{{FIELD}}(&mut self, items: &{{FIELD_TYPE}}) " "{"; - code_ += " // Safety:"; - code_ += " // Created from a valid Table for this object"; - code_ += " // Which contains a valid array in this slot"; + code_ += " // Safety:"; + code_ += " // Created from a valid Table for this object"; + code_ += " // Which contains a valid array in this slot"; code_ += - " unsafe { ::flatbuffers::emplace_scalar_array(&mut self.0, " + " unsafe { ::flatbuffers::emplace_scalar_array(&mut self.0, " "{{FIELD_OFFSET}}, items) };"; } else { code_.SetValue("FIELD_SIZE", NumToString(InlineSize(field.value.type))); code_ += "pub fn set_{{FIELD}}(&mut self, x: &{{FIELD_TYPE}}) {"; - code_ += " // Safety:"; - code_ += " // Created from a valid Table for this object"; - code_ += " // Which contains a valid array in this slot"; - code_ += " unsafe {"; - code_ += " ::core::ptr::copy("; - code_ += " x.as_ptr() as *const u8,"; - code_ += " self.0.as_mut_ptr().add({{FIELD_OFFSET}}),"; - code_ += " {{FIELD_SIZE}},"; - code_ += " );"; - code_ += " }"; + code_ += " // Safety:"; + code_ += " // Created from a valid Table for this object"; + code_ += " // Which contains a valid array in this slot"; + code_ += " unsafe {"; + code_ += " ::core::ptr::copy("; + code_ += " x.as_ptr() as *const u8,"; + code_ += " self.0.as_mut_ptr().add({{FIELD_OFFSET}}),"; + code_ += " {{FIELD_SIZE}},"; + code_ += " );"; + code_ += " }"; } } else { code_ += "pub fn set_{{FIELD}}(&mut self, x: {{FIELD_TYPE}}) {"; code_ += - " let x_le = ::flatbuffers::EndianScalar::to_little_endian(x);"; - code_ += " // Safety:"; - code_ += " // Created from a valid Table for this object"; - code_ += " // Which contains a valid value in this slot"; - code_ += " unsafe {"; - code_ += " ::core::ptr::copy_nonoverlapping("; - code_ += " &x_le as *const _ as *const u8,"; - code_ += " self.0[{{FIELD_OFFSET}}..].as_mut_ptr(),"; + " let x_le = ::flatbuffers::EndianScalar::to_little_endian(x);"; + code_ += " // Safety:"; + code_ += " // Created from a valid Table for this object"; + code_ += " // Which contains a valid value in this slot"; + code_ += " unsafe {"; + code_ += " ::core::ptr::copy_nonoverlapping("; + code_ += " &x_le as *const _ as *const u8,"; + code_ += " self.0[{{FIELD_OFFSET}}..].as_mut_ptr(),"; code_ += - " ::core::mem::size_of::<<{{FIELD_TYPE}} as " + " ::core::mem::size_of::<<{{FIELD_TYPE}} as " "::flatbuffers::EndianScalar>::Scalar>(),"; - code_ += " );"; - code_ += " }"; + code_ += " );"; + code_ += " }"; } code_ += "}\n"; @@ -3015,8 +2912,8 @@ class RustGenerator : public BaseGenerator { // Generate Object API unpack method. if (parser_.opts.generate_object_based_api) { code_.SetValue("STRUCT_OTY", namer_.ObjectType(struct_def)); - code_ += " pub fn unpack(&self) -> {{STRUCT_OTY}} {"; - code_ += " {{STRUCT_OTY}} {"; + code_ += " pub fn unpack(&self) -> {{STRUCT_OTY}} {"; + code_ += " {{STRUCT_OTY}} {"; ForAllStructFields(struct_def, [&](const FieldDef& field) { if (IsArray(field.value.type)) { if (GetFullType(field.value.type) == ftArrayOfStruct) { @@ -3025,103 +2922,63 @@ class RustGenerator : public BaseGenerator { "self.{{FIELD}}(); ::flatbuffers::array_init(|i| " "{{FIELD}}.get(i).unpack()) },"; } else { - code_ += " {{FIELD}}: self.{{FIELD}}().into(),"; + code_ += " {{FIELD}}: self.{{FIELD}}().into(),"; } } else { std::string unpack = IsStruct(field.value.type) ? ".unpack()" : ""; - code_ += " {{FIELD}}: self.{{FIELD}}()" + unpack + ","; + code_ += " {{FIELD}}: self.{{FIELD}}()" + unpack + ","; } }); - code_ += " }"; code_ += " }"; + code_ += " }"; } code_ += "}"; // End impl Struct methods. + code_ += ""; // Generate Struct Object. if (parser_.opts.generate_object_based_api) { // Struct declaration - code_ += ""; - code_ += "#[derive(Debug, Clone, PartialEq)]"; + code_ += "#[derive(Debug, Clone, PartialEq, Default)]"; code_ += "{{ACCESS_TYPE}} struct {{STRUCT_OTY}} {"; ForAllStructFields(struct_def, [&](const FieldDef& field) { (void)field; // unused. code_ += "pub {{FIELD}}: {{FIELD_OTY}},"; }); code_ += "}"; - // Manual impl Default to avoid issues with arrays > 32 elements - // where #[derive(Default)] fails on older Rust versions. - code_ += "impl Default for {{STRUCT_OTY}} {"; - code_ += " fn default() -> Self {"; - code_ += " Self {"; - ForAllStructFields(struct_def, [&](const FieldDef& field) { - const auto full_type = GetFullType(field.value.type); - switch (full_type) { - case ftArrayOfBuiltin: { - // Use the correct zero literal for each element type: - // bool -> false, float/double -> 0.0, integers -> 0 - const auto elem_type = field.value.type.VectorType().base_type; - std::string zero; - if (elem_type == BASE_TYPE_BOOL) { - zero = "false"; - } else if (IsFloat(elem_type)) { - zero = "0.0"; - } else { - zero = "0"; - } - code_ += " {{FIELD}}: [" + zero + "; " + - NumToString(field.value.type.fixed_length) + "],"; - break; - } - case ftArrayOfEnum: - case ftArrayOfStruct: { - code_ += - " {{FIELD}}: ::flatbuffers::array_init(|_| " - "Default::default()),"; - break; - } - default: { - std::string default_value = - GetDefaultValue(field, kObject); - code_ += " {{FIELD}}: " + default_value + ","; - break; - } - } - }); - code_ += " }"; - code_ += " }"; - code_ += "}"; - code_ += ""; // The `pack` method that turns the native struct into its Flatbuffers // counterpart. code_ += "impl {{STRUCT_OTY}} {"; - code_ += " pub fn pack(&self) -> {{STRUCT_TY}} {"; - code_ += " {{STRUCT_TY}}::new("; + code_ += " pub fn pack(&self) -> {{STRUCT_TY}} {"; + code_ += " {{STRUCT_TY}}::new("; ForAllStructFields(struct_def, [&](const FieldDef& field) { if (IsStruct(field.value.type)) { - code_ += " &self.{{FIELD}}.pack(),"; + code_ += " &self.{{FIELD}}.pack(),"; } else if (IsArray(field.value.type)) { if (GetFullType(field.value.type) == ftArrayOfStruct) { code_ += - " &::flatbuffers::array_init(|i| " + " &::flatbuffers::array_init(|i| " "self.{{FIELD}}[i].pack()),"; } else { - code_ += " &self.{{FIELD}},"; + code_ += " &self.{{FIELD}},"; } } else { - code_ += " self.{{FIELD}},"; + code_ += " self.{{FIELD}},"; } }); - code_ += " )"; - code_ += " }"; + code_ += " )"; + code_ += " }"; code_ += "}"; + code_ += ""; } } - void GenNamespaceImports() { + void GenNamespaceImports(const int white_spaces) { // DO not use global attributes (i.e. #![...]) since it interferes // with users who include! generated files. // See: https://github.com/google/flatbuffers/issues/6261 + std::string indent = std::string(white_spaces, ' '); + code_ += ""; if (!parser_.opts.generate_all) { for (auto it = parser_.included_files_.begin(); it != parser_.included_files_.end(); ++it) { @@ -3130,22 +2987,23 @@ class RustGenerator : public BaseGenerator { auto basename = flatbuffers::StripPath(noext); if (parser_.opts.include_prefix.empty()) { - code_ += - "use crate::" + basename + parser_.opts.filename_suffix + "::*;"; + code_ += indent + "use crate::" + basename + + parser_.opts.filename_suffix + "::*;"; } else { auto prefix = parser_.opts.include_prefix; prefix.pop_back(); - code_ += "use crate::" + prefix + "::" + basename + + code_ += indent + "use crate::" + prefix + "::" + basename + parser_.opts.filename_suffix + "::*;"; } } } - if (parser_.opts.rust_serialize) { - code_ += "extern crate serde;"; + code_ += indent + "extern crate serde;"; code_ += + indent + "use self::serde::ser::{Serialize, Serializer, SerializeStruct};"; + code_ += ""; } code_ += "extern crate alloc;"; } @@ -3178,18 +3036,22 @@ class RustGenerator : public BaseGenerator { // Close cur_name_space in reverse order to reach the common prefix. // In the previous example, D then C are closed. for (size_t j = old_size; j > common_prefix_size; --j) { - code_.DecrementIdentLevel(); - code_ += "} // pub mod " + cur_name_space_->components[j - 1]; + code_ += "} // pub mod " + cur_name_space_->components[j - 1]; + } + if (old_size != common_prefix_size) { + code_ += ""; } // open namespace parts to reach the ns namespace // in the previous example, E, then F, then G are opened for (auto j = common_prefix_size; j != new_size; ++j) { - code_ += ""; code_ += "#[allow(unused_imports, dead_code)]"; code_ += "pub mod " + namer_.Namespace(ns->components[j]) + " {"; - code_.IncrementIdentLevel(); - GenNamespaceImports(); + // Generate local namespace imports. + GenNamespaceImports(2); + } + if (new_size != common_prefix_size) { + code_ += ""; } cur_name_space_ = ns; diff --git a/src/idl_gen_swift.cpp b/src/idl_gen_swift.cpp index 437722f47..0f519b249 100644 --- a/src/idl_gen_swift.cpp +++ b/src/idl_gen_swift.cpp @@ -164,14 +164,15 @@ class SwiftGenerator : public BaseGenerator { bool generate() { code_.Clear(); code_.SetValue("ACCESS", "_accessor"); - code_.SetValue("TABLEOFFSET", "VT"); + code_.SetValue("TABLEOFFSET", "VTOFFSET"); code_ += "// " + std::string(FlatBuffersGeneratedWarning()); code_ += "// swiftlint:disable all"; code_ += "// swiftformat:disable all\n"; if (parser_.opts.include_dependence_headers || parser_.opts.generate_all) { - code_.SetValue("IMPLEMENTONLY", - parser_.opts.swift_implementation_only ? "internal " : ""); + code_.SetValue("IMPLEMENTONLY", parser_.opts.swift_implementation_only + ? "@_implementationOnly " + : ""); code_ += "#if canImport(Common)"; code_ += "{{IMPLEMENTONLY}}import Common"; code_ += "#endif"; @@ -281,16 +282,9 @@ class SwiftGenerator : public BaseGenerator { NumToString(field.value.type.VectorType().fixed_length); code_.SetValue("FIXEDLENGTH", fixed_length); - std::string vector_base_type; - if (IsStruct(field.value.type.VectorType())) { - vector_base_type = type + "()"; - } else if (IsBool(field.value.type.VectorType().base_type)) { - vector_base_type = "false"; - } else if (IsFloat(field.value.type.VectorType().base_type)) { - vector_base_type = "0.0"; - } else { - vector_base_type = SwiftConstant(field); - } + const auto vector_base_type = IsStruct(field.value.type.VectorType()) + ? (type + "()") + : SwiftConstant(field); code_ += "private var _{{FIELDVAR}}: InlineArray<{{FIXEDLENGTH}}, " + valueType + ">"; @@ -524,7 +518,7 @@ class SwiftGenerator : public BaseGenerator { void GenTableAccessors(const StructDef& struct_def) { // Generate field id constants. if (struct_def.fields.vec.size() > 0) { - code_ += "private struct {{TABLEOFFSET}} {"; + code_ += "private enum {{TABLEOFFSET}}: VOffset {"; Indent(); for (auto it = struct_def.fields.vec.begin(); it != struct_def.fields.vec.end(); ++it) { @@ -534,8 +528,10 @@ class SwiftGenerator : public BaseGenerator { } code_.SetValue("OFFSET_NAME", namer_.Variable(field)); code_.SetValue("OFFSET_VALUE", NumToString(field.value.offset)); - code_ += "static let {{OFFSET_NAME}}: VOffset = {{OFFSET_VALUE}}"; + code_ += "case {{OFFSET_NAME}} = {{OFFSET_VALUE}}"; } + code_ += "var v: Int32 { Int32(self.rawValue) }"; + code_ += "var p: VOffset { self.rawValue }"; Outdent(); code_ += "}"; code_ += ""; @@ -548,14 +544,13 @@ class SwiftGenerator : public BaseGenerator { code_.SetValue("SHORT_STRUCTNAME", namer_.Type(struct_def)); code_.SetValue("STRUCTNAME", namer_.NamespacedType(struct_def)); code_.SetValue("OBJECTTYPE", struct_def.fixed ? "Struct" : "Table"); - code_.SetValue("PROTOCOL", struct_def.fixed ? "FlatBufferStruct" - : "FlatBufferVerifiableTable"); code_.SetValue("MUTABLE", struct_def.fixed ? Mutable() : ""); GenOSVersionChecks(); code_ += "{{ACCESS_TYPE}} struct {{STRUCTNAME}}{{MUTABLE}}: " - "{{PROTOCOL}}, FlatbuffersVectorInitializable\\"; + "FlatBuffer{{OBJECTTYPE}}, FlatbuffersVectorInitializable\\"; + if (!struct_def.fixed) code_ += ", Verifiable\\"; if (!struct_def.fixed && parser_.opts.generate_object_based_api) code_ += ", ObjectAPIPacker\\"; code_ += " {\n"; @@ -625,8 +620,7 @@ class SwiftGenerator : public BaseGenerator { if (should_generate_create) { code_ += "{{ACCESS_TYPE}} static func create{{SHORT_STRUCTNAME}}("; Indent(); - code_ += "_ fbb: inout FlatBufferBuilder\\"; - if (create_func_header.empty() == false) code_ += ","; + code_ += "_ fbb: inout FlatBufferBuilder,"; for (auto it = create_func_header.begin(); it < create_func_header.end(); ++it) { code_ += *it + "\\"; @@ -705,7 +699,7 @@ class SwiftGenerator : public BaseGenerator { code_ += field.IsOptional() ? (optional_enum + "\\") : (is_enum + ", def: {{CONSTANT}}\\"); - code_ += ", at: {{TABLEOFFSET}}.{{OFFSET}}) }"; + code_ += ", at: {{TABLEOFFSET}}.{{OFFSET}}.p) }"; const auto default_value = IsEnum(field.value.type) @@ -725,7 +719,7 @@ class SwiftGenerator : public BaseGenerator { code_ += "{{VALUETYPE}}" + builder_string + "fbb.add(element: {{FIELDVAR}},\\"; code_ += field.IsOptional() ? "\\" : " def: {{CONSTANT}},"; - code_ += " at: {{TABLEOFFSET}}.{{OFFSET}}) }"; + code_ += " at: {{TABLEOFFSET}}.{{OFFSET}}.p) }"; create_func_header.push_back( field_var + ": " + nullable_type + " = " + (field.IsOptional() ? "nil" : default_value)); @@ -736,7 +730,7 @@ class SwiftGenerator : public BaseGenerator { const auto create_struct = "guard let {{FIELDVAR}} = {{FIELDVAR}} else { return };" " fbb.create(struct: {{FIELDVAR}}, position: " - "{{TABLEOFFSET}}.{{OFFSET}}) }"; + "{{TABLEOFFSET}}.{{OFFSET}}.p) }"; code_ += type + "?" + builder_string + create_struct; /// Optional hard coded since structs are always optional create_func_header.push_back(field_var + ": " + type + @@ -753,9 +747,8 @@ class SwiftGenerator : public BaseGenerator { (field.IsRequired() ? "" : " = Offset()")); const auto reader_type = IsStruct(field.value.type) && field.value.type.struct_def->fixed - ? "structOffset: {{TABLEOFFSET}}.{{OFFSET}}) }" - : "offset: {{FIELDVAR}}, at: {{TABLEOFFSET}}.{{OFFSET}}) " - "}"; + ? "structOffset: {{TABLEOFFSET}}.{{OFFSET}}.p) }" + : "offset: {{FIELDVAR}}, at: {{TABLEOFFSET}}.{{OFFSET}}.p) }"; code_ += "Offset" + builder_string + "fbb.add(" + reader_type; const auto vectortype = field.value.type.VectorType(); @@ -859,10 +852,7 @@ class SwiftGenerator : public BaseGenerator { break; case BASE_TYPE_STRING: { - const auto sc = SwiftConstant(field); - std::string default_string; - flatbuffers::EscapeString(sc.c_str(), sc.length(), &default_string, - true, false); + const auto default_string = "\"" + SwiftConstant(field) + "\""; code_.SetValue("VALUETYPE", GenType(field.value.type)); code_.SetValue("CONSTANT", field.IsDefault() ? default_string : "nil"); code_ += GenReaderMainBody(is_required) + GenOffset() + @@ -870,7 +860,7 @@ class SwiftGenerator : public BaseGenerator { code_ += "{{ACCESS_TYPE}} var {{FIELDVAR}}SegmentArray: [UInt8]" + is_required + " { return " - "{{ACCESS}}.getVector(at: {{TABLEOFFSET}}.{{OFFSET}}) }"; + "{{ACCESS}}.getVector(at: {{TABLEOFFSET}}.{{OFFSET}}.v) }"; break; } case BASE_TYPE_ARRAY: @@ -904,7 +894,7 @@ class SwiftGenerator : public BaseGenerator { code_ += "{{ACCESS_TYPE}} var {{FIELDVAR}}: " "FlatbufferVector<{{VALUETYPE}}> " - "{ return {{ACCESS}}.vector(at: {{TABLEOFFSET}}.{{OFFSET}}, " + "{ return {{ACCESS}}.vector(at: {{TABLEOFFSET}}.{{OFFSET}}.v, " "byteSize: {{SIZE}}) }"; } @@ -921,7 +911,7 @@ class SwiftGenerator : public BaseGenerator { code_ += "{{ACCESS_TYPE}} var {{FIELDVAR}}: " "FlatbufferVector<{{VALUETYPE}}_Mutable> " - "{ return {{ACCESS}}.vector(at: {{TABLEOFFSET}}.{{OFFSET}}, " + "{ return {{ACCESS}}.vector(at: {{TABLEOFFSET}}.{{OFFSET}}.v, " "byteSize: {{SIZE}}) }"; GenUnsafeBufferPointer(field); return; @@ -930,8 +920,7 @@ class SwiftGenerator : public BaseGenerator { if (vectortype.base_type == BASE_TYPE_UNION) { code_ += "{{ACCESS_TYPE}} var {{FIELDVAR}}: UnionFlatbufferVector " - "{ return {{ACCESS}}.unionVector(at: " - "{{TABLEOFFSET}}.{{OFFSET}}, " + "{ return {{ACCESS}}.unionVector(at: {{TABLEOFFSET}}.{{OFFSET}}.v, " "byteSize: {{SIZE}}) }"; code_ += "{{ACCESS_TYPE}} func {{FIELDVAR}}(at " @@ -965,21 +954,24 @@ class SwiftGenerator : public BaseGenerator { "{{ACCESS_TYPE}} func {{functionName}}(_ body: " "(UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return " "try " - "{{ACCESS}}.withUnsafePointerToSlice(at: " - "{{TABLEOFFSET}}.{{OFFSET}}, " + "{{ACCESS}}.withUnsafePointerToSlice(at: {{TABLEOFFSET}}.{{OFFSET}}.v, " "body: body) }"; } - std::vector GenerateCodingKeys(const StructDef& struct_def) { - std::vector coding_keys; + void GenerateCodingKeys(const StructDef& struct_def) { + code_ += "enum CodingKeys: String, CodingKey {"; + Indent(); for (auto it = struct_def.fields.vec.begin(); it != struct_def.fields.vec.end(); ++it) { const auto& field = **it; if (field.deprecated) continue; - coding_keys.push_back("case " + namer_.Variable(field) + " = \"" + - field.name + "\""); + + code_.SetValue("RAWVALUENAME", field.name); + code_.SetValue("FIELDVAR", namer_.Variable(field)); + code_ += "case {{FIELDVAR}} = \"{{RAWVALUENAME}}\""; } - return coding_keys; + Outdent(); + code_ += "}"; } void GenerateEncoderUnionBody(const FieldDef& field) { @@ -1101,31 +1093,14 @@ class SwiftGenerator : public BaseGenerator { GenOSVersionChecks(); code_ += "extension {{STRUCTNAME}}: Encodable {"; Indent(); - auto coding_keys = GenerateCodingKeys(struct_def); - - if (coding_keys.empty() == false) { - code_ += "enum CodingKeys: String, CodingKey {"; - Indent(); - for (auto it = coding_keys.begin(); it != coding_keys.end(); ++it) { - const auto& field = *it; - code_ += field; - } - Outdent(); - code_ += "}"; - - code_ += ""; - } + code_ += ""; + if (struct_def.fields.vec.empty() == false) GenerateCodingKeys(struct_def); code_ += "{{ACCESS_TYPE}} func encode(to encoder: Encoder) throws {"; - - if (coding_keys.empty() == false) { - Indent(); - GenerateEncoderBody(struct_def); - Outdent(); - } - + Indent(); + if (struct_def.fields.vec.empty() == false) GenerateEncoderBody(struct_def); + Outdent(); code_ += "}"; - Outdent(); code_ += "}"; code_ += ""; @@ -1155,7 +1130,7 @@ class SwiftGenerator : public BaseGenerator { } code_ += - "try _v.visit(field: {{TABLEOFFSET}}.{{OFFSET}}, fieldName: " + "try _v.visit(field: {{TABLEOFFSET}}.{{OFFSET}}.p, fieldName: " "\"{{FIELDVAR}}\", required: {{ISREQUIRED}}, type: " "{{VALUETYPE}}.self)"; } @@ -1175,9 +1150,8 @@ class SwiftGenerator : public BaseGenerator { code_.SetValue("VALUETYPE", namer_.NamespacedType(union_def)); code_.SetValue("FUNCTION_NAME", is_vector ? "visitUnionVector" : "visit"); code_ += - "try _v.{{FUNCTION_NAME}}(unionKey: " - "{{TABLEOFFSET}}.{{OFFSET}}Type, " - "unionField: {{TABLEOFFSET}}.{{OFFSET}}, unionKeyName: " + "try _v.{{FUNCTION_NAME}}(unionKey: {{TABLEOFFSET}}.{{OFFSET}}Type.p, " + "unionField: {{TABLEOFFSET}}.{{OFFSET}}.p, unionKeyName: " "\"{{FIELDVAR}}Type\", fieldName: \"{{FIELDVAR}}\", required: " "{{ISREQUIRED}}, completion: { (verifier, key: {{VALUETYPE}}, pos) in"; Indent(); @@ -1652,23 +1626,15 @@ class SwiftGenerator : public BaseGenerator { buffer_constructor.push_back(field_var + " = _t." + field_field); if (field.IsRequired()) { - std::string default_value; - if (field.IsDefault()) { - const auto sc = SwiftConstant(field); - flatbuffers::EscapeString(sc.c_str(), sc.length(), &default_value, - true, false); - } else { - default_value = "\"\""; - } - base_constructor.push_back(field_var + " = " + default_value); + std::string default_value = + field.IsDefault() ? SwiftConstant(field) : ""; + base_constructor.push_back(field_var + " = \"" + default_value + + "\""); break; } if (field.IsDefault() && !field.IsRequired()) { - const auto sc = SwiftConstant(field); - std::string value; - flatbuffers::EscapeString(sc.c_str(), sc.length(), &value, - true, false); - base_constructor.push_back(field_var + " = " + value); + std::string value = field.IsDefault() ? SwiftConstant(field) : "nil"; + base_constructor.push_back(field_var + " = \"" + value + "\""); } break; } @@ -1927,7 +1893,7 @@ class SwiftGenerator : public BaseGenerator { } std::string GenOffset() { - return "let o = {{ACCESS}}.offset({{TABLEOFFSET}}.{{OFFSET}}); "; + return "let o = {{ACCESS}}.offset({{TABLEOFFSET}}.{{OFFSET}}.v); "; } std::string GenReaderMainBody(const std::string& optional = "") { diff --git a/src/idl_gen_ts.cpp b/src/idl_gen_ts.cpp index 8d02b8eb4..923bca9d9 100644 --- a/src/idl_gen_ts.cpp +++ b/src/idl_gen_ts.cpp @@ -324,10 +324,9 @@ class TsGenerator : public BaseGenerator { export_counter++; } - if (export_counter > 0) { + if (export_counter > 0) parser_.opts.file_saver->SaveFile(it.second.filepath.c_str(), code, false); - } } } @@ -522,20 +521,7 @@ class TsGenerator : public BaseGenerator { case BASE_TYPE_BOOL: return value.constant == "0" ? "false" : "true"; - case BASE_TYPE_STRING: { - // NOTE: Strings without a default value are parsed as "0" by - // the parser, so therefore we have to treat "0" as a null-signifying - // value. - if (value.constant == "0" || value.constant == "null") { - return "null"; - } else { - std::string escaped; - flatbuffers::EscapeString(value.constant.c_str(), - value.constant.length(), &escaped, - true, false); - return escaped; - } - } + case BASE_TYPE_STRING: case BASE_TYPE_UNION: case BASE_TYPE_STRUCT: { return null_keyword_; @@ -661,8 +647,7 @@ class TsGenerator : public BaseGenerator { } void GenStructArgs(import_set& imports, const StructDef& struct_def, - const Definition& owner, std::string* arguments, - const std::string& nameprefix) { + std::string* arguments, const std::string& nameprefix) { for (auto it = struct_def.fields.vec.begin(); it != struct_def.fields.vec.end(); ++it) { auto& field = **it; @@ -670,11 +655,11 @@ class TsGenerator : public BaseGenerator { // Generate arguments for a struct inside a struct. To ensure names // don't clash, and to make it obvious these arguments are constructing // a nested struct, prefix the name with the field name. - GenStructArgs(imports, *field.value.type.struct_def, owner, arguments, + GenStructArgs(imports, *field.value.type.struct_def, arguments, nameprefix + field.name + "_"); } else { *arguments += ", " + nameprefix + field.name + ": " + - GenTypeName(imports, owner, field.value.type, true, + GenTypeName(imports, field, field.value.type, true, field.IsOptional()); } } @@ -936,48 +921,6 @@ class TsGenerator : public BaseGenerator { return symbols_expression; } - std::vector PathComponents(const std::string& path) const { - std::vector components; - size_t start = 0; - while (start < path.size()) { - auto end = path.find(kPathSeparator, start); - if (end == std::string::npos) end = path.size(); - if (end > start) { - components.emplace_back(path.substr(start, end - start)); - } - if (end == path.size()) break; - start = end + 1; - } - return components; - } - - std::string RelativeDirectory(const std::vector& from, - const std::vector& to) const { - size_t common = 0; - while (common < from.size() && common < to.size() && - from[common] == to[common]) { - ++common; - } - - std::string rel; - const size_t ups = from.size() - common; - if (ups == 0) { - rel = "."; - } else { - for (size_t i = 0; i < ups; ++i) { - if (!rel.empty()) rel += kPathSeparator; - rel += ".."; - } - } - - for (size_t i = common; i < to.size(); ++i) { - if (!rel.empty()) rel += kPathSeparator; - rel += to[i]; - } - - return rel; - } - template ImportDefinition AddImport(import_set& imports, const Definition& dependent, const DefinitionT& dependency) { @@ -1005,32 +948,26 @@ class TsGenerator : public BaseGenerator { const std::string symbols_expression = GenSymbolExpression( dependency, has_name_clash, import_name, name, object_name); - const Namespace* dependent_ns = dependent.defined_namespace - ? dependent.defined_namespace - : parser_.empty_namespace_; - const Namespace* dependency_ns = dependency.defined_namespace - ? dependency.defined_namespace - : parser_.empty_namespace_; + std::string bare_file_path; + std::string rel_file_path; + if (dependent.defined_namespace) { + const auto& dep_comps = dependent.defined_namespace->components; + for (size_t i = 0; i < dep_comps.size(); i++) { + rel_file_path += i == 0 ? ".." : (kPathSeparator + std::string("..")); + } + if (dep_comps.size() == 0) { + rel_file_path += "."; + } + } else { + rel_file_path += ".."; + } - const std::string dependent_dirs = - namer_.Directories(*dependent_ns, SkipDir::OutputPath); - const std::string dependency_dirs = - namer_.Directories(*dependency_ns, SkipDir::OutputPath); - - const auto dependent_components = PathComponents(dependent_dirs); - const auto dependency_components = PathComponents(dependency_dirs); - - std::string rel_dir = - RelativeDirectory(dependent_components, dependency_components); - if (rel_dir.empty()) rel_dir = "."; - if (!rel_dir.empty()) rel_dir += kPathSeparator; - - std::string rel_file_path = - rel_dir + namer_.File(dependency, SkipFile::SuffixAndExtension); - - std::string bare_file_path = - kPathSeparator + dependency_dirs + + bare_file_path += + kPathSeparator + + namer_.Directories(dependency.defined_namespace->components, + SkipDir::OutputPath) + namer_.File(dependency, SkipFile::SuffixAndExtension); + rel_file_path += bare_file_path; ImportDefinition import; import.name = name; @@ -1235,10 +1172,9 @@ class TsGenerator : public BaseGenerator { std::string GenNullCheckConditional(const std::string& nullCheckVar, const std::string& trueVal, - const std::string& falseVal = "") { - std::string false_val = falseVal.empty() ? null_keyword_ : falseVal; + const std::string& falseVal) { return "(" + nullCheckVar + " !== " + null_keyword_ + " ? " + trueVal + - " : " + false_val + ")"; + " : " + falseVal + ")"; } std::string GenStructMemberValueTS(const StructDef& struct_def, @@ -1347,9 +1283,10 @@ class TsGenerator : public BaseGenerator { // Emit a scalar field const auto is_string = IsString(field.value.type); if (IsScalar(field.value.type.base_type) || is_string) { - field_type += - GenTypeName(imports, field, field.value.type, false, - !HasDefaultValue(field) || HasNullDefault(field)); + const auto has_null_default = is_string || HasNullDefault(field); + + field_type += GenTypeName(imports, field, field.value.type, false, + has_null_default); field_val = "this." + namer_.Method(field) + "()"; if (field.value.type.base_type != BASE_TYPE_STRING) { @@ -1695,12 +1632,11 @@ class TsGenerator : public BaseGenerator { GenDocComment(struct_def.doc_comment, code_ptr); code += "export class "; code += object_name; - if (parser.opts.generate_object_based_api) { + if (parser.opts.generate_object_based_api) code += " implements flatbuffers.IUnpackableObject<" + object_api_name + "> {\n"; - } else { + else code += " {\n"; - } code += " bb: flatbuffers.ByteBuffer|" + null_keyword_ + " = " + null_keyword_ + ";\n"; code += " bb_pos = 0;\n"; @@ -1743,22 +1679,21 @@ class TsGenerator : public BaseGenerator { offset_prefix = " const offset = " + GenBBAccess() + ".__offset(this.bb_pos, " + NumToString(field.value.offset) + ");\n"; - offset_prefix += " return "; + offset_prefix += " return offset ? "; } // Emit a scalar field const auto is_string = IsString(field.value.type); if (IsScalar(field.value.type.base_type) || is_string) { - const auto has_null_default = - !field.IsRequired() && !HasDefaultValue(field); + const auto has_null_default = is_string || HasNullDefault(field); GenDocComment(field.doc_comment, code_ptr); std::string prefix = namer_.Method(field) + "("; if (is_string) { - code += prefix + "):" + (has_null_default ? "string|" + null_keyword_ : "string") + "\n"; + code += prefix + "):string|" + null_keyword_ + "\n"; code += prefix + "optionalEncoding:flatbuffers.Encoding" + "):" + - GenTypeName(imports, struct_def, field.value.type, false, has_null_default) + + GenTypeName(imports, struct_def, field.value.type, false, true) + "\n"; code += prefix + "optionalEncoding?:any"; } else { @@ -1787,16 +1722,9 @@ class TsGenerator : public BaseGenerator { if (is_string) { index += ", optionalEncoding"; } - if (field.IsRequired()) { - code += - offset_prefix + GenGetter(field.value.type, "(" + index + ")"); - ; - } else { - code += offset_prefix + "offset ? " + - GenGetter(field.value.type, "(" + index + ")"); - } - if (field.value.type.base_type != BASE_TYPE_ARRAY && - !field.IsRequired()) { + code += + offset_prefix + GenGetter(field.value.type, "(" + index + ")"); + if (field.value.type.base_type != BASE_TYPE_ARRAY) { code += " : " + GenDefaultValue(field, imports); } code += ";\n"; @@ -1821,8 +1749,8 @@ class TsGenerator : public BaseGenerator { code += MaybeAdd(field.value.offset) + ", " + GenBBAccess() + ");\n"; } else { - code += offset_prefix + "offset ? (obj || " + - GenerateNewExpression(type) + ").__init("; + code += offset_prefix + "(obj || " + GenerateNewExpression(type) + + ").__init("; code += field.value.type.struct_def->fixed ? "this.bb_pos + offset" : GenBBAccess() + ".__indirect(this.bb_pos + offset)"; @@ -1980,7 +1908,7 @@ class TsGenerator : public BaseGenerator { code += "):" + vectortypename + "|" + null_keyword_ + " {\n"; if (vectortype.base_type == BASE_TYPE_STRUCT) { - code += offset_prefix + "offset ? (obj || " + + code += offset_prefix + "(obj || " + GenerateNewExpression(vectortypename); code += ").__init("; code += vectortype.struct_def->fixed @@ -1993,8 +1921,7 @@ class TsGenerator : public BaseGenerator { } else if (IsString(vectortype)) { index += ", optionalEncoding"; } - code += offset_prefix + "offset ? " + - GenGetter(vectortype, "(" + index + ")"); + code += offset_prefix + GenGetter(vectortype, "(" + index + ")"); } code += " : "; if (field.value.type.element == BASE_TYPE_BOOL) { @@ -2026,7 +1953,7 @@ class TsGenerator : public BaseGenerator { " " "{\n"; - code += offset_prefix + "offset ? " + + code += offset_prefix + GenGetter(field.value.type, "(obj, this.bb_pos + offset)") + " : " + null_keyword_ + ";\n"; break; @@ -2079,7 +2006,7 @@ class TsGenerator : public BaseGenerator { // Emit a length helper GenDocComment(code_ptr); code += namer_.Method(field, "Length"); - code += "():number {\n" + offset_prefix + "offset ? "; + code += "():number {\n" + offset_prefix; code += GenBBAccess() + ".__vector_len(this.bb_pos + offset) : 0;\n}\n\n"; @@ -2090,30 +2017,15 @@ class TsGenerator : public BaseGenerator { GenDocComment(code_ptr); code += namer_.Method(field, "Array"); + code += "():" + GenType(vectorType) + "Array|" + null_keyword_ + + " {\n" + offset_prefix; - std::string return_type = - (field.IsRequired() || HasDefaultValue(field)) - ? "Array" - : ("Array|" + null_keyword_); - if (field.IsRequired()) { - code += "():" + GenType(vectorType) + return_type + " {\n" + - offset_prefix + "new " + GenType(vectorType) + "Array(" + - GenBBAccess() + ".bytes().buffer, " + GenBBAccess() + - ".bytes().byteOffset + " + GenBBAccess() + - ".__vector(this.bb_pos + offset), " + GenBBAccess() + - ".__vector_len(this.bb_pos + offset));\n}\n\n"; - } else { - std::string value = HasDefaultValue(field) - ? "new " + GenType(vectorType) + "Array()" - : "null"; - code += "():" + GenType(vectorType) + return_type + " {\n" + - offset_prefix + "offset ? new " + GenType(vectorType) + - "Array(" + GenBBAccess() + ".bytes().buffer, " + - GenBBAccess() + ".bytes().byteOffset + " + GenBBAccess() + - ".__vector(this.bb_pos + offset), " + GenBBAccess() + - ".__vector_len(this.bb_pos + offset)) : " + value + - ";\n}\n\n"; - } + code += "new " + GenType(vectorType) + "Array(" + GenBBAccess() + + ".bytes().buffer, " + GenBBAccess() + + ".bytes().byteOffset + " + GenBBAccess() + + ".__vector(this.bb_pos + offset), " + GenBBAccess() + + ".__vector_len(this.bb_pos + offset)) : " + null_keyword_ + + ";\n}\n\n"; } } } @@ -2142,7 +2054,7 @@ class TsGenerator : public BaseGenerator { // Emit a factory constructor if (struct_def.fixed) { std::string arguments; - GenStructArgs(imports, struct_def, struct_def, &arguments, ""); + GenStructArgs(imports, struct_def, &arguments, ""); GenDocComment(code_ptr); code += "static create" + GetPrefixedName(struct_def) + @@ -2344,34 +2256,6 @@ class TsGenerator : public BaseGenerator { return field.IsOptional() && field.value.constant == "null"; } - static bool HasDefaultValue(const FieldDef& field) { - switch (field.value.type.base_type) { - // These types can't have defaults - case BASE_TYPE_UNION: - case BASE_TYPE_STRUCT: { - return false; - } - - // Arrays always have a default (empty array) - case BASE_TYPE_ARRAY: - return true; - - // The only supported default for vectors is [] - case BASE_TYPE_VECTOR: - return field.value.constant == "[]"; - - // Even strings are presumed to be null-default if the default value is - // "0", this is intended behavior. - case BASE_TYPE_STRING: { - return field.value.constant != "0" && field.value.constant != "null"; - } - - default: { - return field.value.constant != "null"; - } - } - } - std::string GetArgType(import_set& imports, const Definition& owner, const FieldDef& field, bool allowNull) { return GenTypeName(imports, owner, field.value.type, true, diff --git a/src/idl_parser.cpp b/src/idl_parser.cpp index b1bdffa01..d60ab586f 100644 --- a/src/idl_parser.cpp +++ b/src/idl_parser.cpp @@ -1286,6 +1286,55 @@ CheckedError Parser::ParseField(StructDef& struct_def) { "'native_inline' can only be defined on structs, vector of structs or " "vector of tables"); + // `bigfoot_ref` is Bigfoot's single-purpose replacement for the old, + // general-purpose `native_type_template`/`native_type_template_arg` pair: + // a field typed as a `bigfoot_ref_wrapper`-tagged struct (HardReference or + // SoftReference) and annotated `bigfoot_ref: "::Bigfoot::AssetX"` gets its + // native type instantiated as `<::Bigfoot::AssetX>`, plus (unlike + // the old mechanism) a forward declaration of AssetX and inline Pack/UnPack + // definitions are emitted directly into the generated header - see + // GenerateBigfootRefDecls in idl_gen_cpp.cpp. + auto bigfoot_ref = field->attributes.Lookup("bigfoot_ref"); + if (bigfoot_ref) { + if (!IsStruct(field->value.type) && !IsVectorOfStruct(field->value.type)) + return Error( + "'bigfoot_ref' can only be defined on struct-typed fields or " + "vectors of structs"); + const auto* target_struct = field->value.type.struct_def; + const auto* wrapper = target_struct->attributes.Lookup("bigfoot_ref_wrapper"); + if (!wrapper) + return Error( + "'bigfoot_ref' requires the field's type ('" + target_struct->name + + "') to declare a 'bigfoot_ref_wrapper' attribute"); + if (field->attributes.Lookup("native_type")) + return Error( + "'bigfoot_ref' cannot be combined with an explicit 'native_type' " + "on the same field"); + + const auto b = bigfoot_ref->constant.find_first_not_of(" \t"); + const auto e = bigfoot_ref->constant.find_last_not_of(" \t"); + const std::string asset_type = + b == std::string::npos ? "" : bigfoot_ref->constant.substr(b, e - b + 1); + if (asset_type.empty()) + return Error("'bigfoot_ref' cannot be empty"); + + auto native_type_val = new Value(); + native_type_val->type = bigfoot_ref->type; + native_type_val->constant = wrapper->constant + "<" + asset_type + ">"; + field->attributes.Add("native_type", native_type_val); + + if (!field->attributes.Lookup("native_type_pack_name")) { + const auto last_colon = asset_type.find_last_of(':'); + const std::string asset_short_name = + last_colon == std::string::npos ? asset_type + : asset_type.substr(last_colon + 1); + auto pack_name_val = new Value(); + pack_name_val->type = bigfoot_ref->type; + pack_name_val->constant = target_struct->name + asset_short_name; + field->attributes.Add("native_type_pack_name", pack_name_val); + } + } + auto nested = field->attributes.Lookup("nested_flatbuffer"); if (nested) { if (nested->type.base_type != BASE_TYPE_STRING) @@ -2809,8 +2858,7 @@ bool Parser::SupportsOptionalScalars() const { bool Parser::SupportsDefaultVectorsAndStrings() const { static FLATBUFFERS_CONSTEXPR unsigned long supported_langs = IDLOptions::kRust | IDLOptions::kSwift | IDLOptions::kNim | - IDLOptions::kCpp | IDLOptions::kBinary | IDLOptions::kJson | - IDLOptions::kTs; + IDLOptions::kCpp | IDLOptions::kBinary | IDLOptions::kJson; return !(opts.lang_to_generate & ~supported_langs); } @@ -3172,10 +3220,8 @@ CheckedError Parser::ParseProtoFields(StructDef* struct_def, bool isextend, return Error("Protobuf has non positive number in reserved ids"); if (range) { - for (uint32_t id = static_cast(from) + 1; - id <= static_cast(attribute); id++) { - struct_def->reserved_ids.push_back(static_cast(id)); - } + for (voffset_t id = from + 1; id <= attribute; id++) + struct_def->reserved_ids.push_back(id); range = false; } else { @@ -4132,15 +4178,7 @@ bool StructDef::Deserialize(Parser& parser, const reflection::Object* object) { sortbysize = attributes.Lookup("original_order") == nullptr && !fixed; const auto& of = *(object->fields()); auto indexes = std::vector(of.size()); - for (uoffset_t i = 0; i < of.size(); i++) { - uint16_t field_id = of.Get(i)->id(); - if (field_id >= of.size()) { - parser.error_ = "Field ID " + std::to_string(field_id) + - " exceeds field count " + std::to_string(of.size()); - return false; - } - indexes[field_id] = i; -} + for (uoffset_t i = 0; i < of.size(); i++) indexes[of.Get(i)->id()] = i; size_t tmp_struct_size = 0; for (size_t i = 0; i < indexes.size(); i++) { auto field = of.Get(indexes[i]); diff --git a/src/reflection.cpp b/src/reflection.cpp index 268d7d851..51e07eaa2 100644 --- a/src/reflection.cpp +++ b/src/reflection.cpp @@ -389,7 +389,7 @@ void ForAllFields(const reflection::Object* object, bool reverse, for (size_t i = 0; i < field_to_id_map.size(); ++i) { func(object->fields()->Get( - field_to_id_map[reverse ? field_to_id_map.size() - (i + 1) : i])); + field_to_id_map[reverse ? field_to_id_map.size() - i + 1 : i])); } } @@ -641,10 +641,7 @@ const uint8_t* AddFlatBuffer(std::vector& flatbuf, const uint8_t* newbuf, size_t newlen) { // Align to sizeof(uoffset_t) past sizeof(largest_scalar_t) since we're // going to chop off the root offset. - if (!newbuf || newlen < sizeof(uoffset_t)) return nullptr; FLATBUFFERS_ASSERT(newlen >= sizeof(uoffset_t)); - auto root = ReadScalar(newbuf); - if (root < sizeof(uoffset_t) || root >= newlen) return nullptr; while ((flatbuf.size() & (sizeof(uoffset_t) - 1)) || !(flatbuf.size() & (sizeof(largest_scalar_t) - 1))) { flatbuf.push_back(0); @@ -652,7 +649,7 @@ const uint8_t* AddFlatBuffer(std::vector& flatbuf, auto insertion_point = static_cast(flatbuf.size()); // Insert the entire FlatBuffer minus the root pointer. flatbuf.insert(flatbuf.end(), newbuf + sizeof(uoffset_t), newbuf + newlen); - auto root_offset = root - sizeof(uoffset_t); + auto root_offset = ReadScalar(newbuf) - sizeof(uoffset_t); return flatbuf.data() + insertion_point + root_offset; } diff --git a/swift/Sources/Common/Scalar.swift b/swift/Sources/Common/Scalar.swift index 5c6a6c832..518580a60 100644 --- a/swift/Sources/Common/Scalar.swift +++ b/swift/Sources/Common/Scalar.swift @@ -28,7 +28,7 @@ public let FileIdLength = 4 /// Protocol that All Scalars should conform to /// /// Scalar is used to conform all the numbers that can be represented in a FlatBuffer. It's used to write/read from the buffer. -public protocol Scalar: Equatable, BitwiseCopyable { +public protocol Scalar: Equatable { associatedtype NumericValue var convertedEndian: NumericValue { get } } diff --git a/swift/Sources/FlatBuffers/ByteBuffer.swift b/swift/Sources/FlatBuffers/ByteBuffer.swift index f22ecff57..ec27fd1d7 100644 --- a/swift/Sources/FlatBuffers/ByteBuffer.swift +++ b/swift/Sources/FlatBuffers/ByteBuffer.swift @@ -20,56 +20,22 @@ import Foundation /// it allows users to write and read data directly from memory thus the use of its /// functions should be used @frozen -public struct ByteBuffer: @unchecked Sendable { +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 { @usableFromInline - @frozen enum Blob: ~Copyable { + enum Blob { #if !os(WASI) case data(Data) - case bytes(any ContiguousBytes) + case bytes(ContiguousBytes) #endif case byteBuffer(_InternalByteBuffer) case array([UInt8]) case pointer(UnsafeMutableRawPointer) - - init(_ other: borrowing Blob) { - switch other { - #if !os(WASI) - case .data(let data): - self = .data(data) - case .bytes(let contiguousBytes): - self = .bytes(contiguousBytes) - #endif - case .byteBuffer(let internalByteBuffer): - self = .byteBuffer(internalByteBuffer) - case .array(let array): - self = .array(array) - case .pointer(let unsafeMutableRawPointer): - self = .pointer(unsafeMutableRawPointer) - } - } - - var description: String { - switch self { - #if !os(WASI) - case .data(let data): - "data: \(data)" - case .bytes(let contiguousBytes): - "bytes: \(contiguousBytes)" - #endif - case .byteBuffer(let internalByteBuffer): - "byteBuffer: \(internalByteBuffer)" - case .array(let array): - "array: \(array)" - case .pointer(let unsafeMutableRawPointer): - "pointer: \(unsafeMutableRawPointer)" - } - } } /// This storage doesn't own the memory, therefore, we won't deallocate on deinit. @@ -78,7 +44,7 @@ public struct ByteBuffer: @unchecked Sendable { private let capacity: Int /// Retained blob of data that requires the storage to retain a pointer to. @usableFromInline - let retainedBlob: Blob + var retainedBlob: Blob @usableFromInline init(count: Int) { @@ -91,9 +57,9 @@ public struct ByteBuffer: @unchecked Sendable { } @usableFromInline - init(blob: borrowing Blob, capacity count: Int) { + init(blob: Blob, capacity count: Int) { capacity = count - retainedBlob = .init(blob) + retainedBlob = blob isOwned = false } @@ -184,7 +150,6 @@ public struct ByteBuffer: @unchecked Sendable { @discardableResult @inline(__always) - @inlinable func readWithUnsafeRawPointer( position: Int, _ body: (UnsafeRawPointer) throws -> T) rethrows -> T @@ -313,7 +278,7 @@ public struct ByteBuffer: @unchecked Sendable { /// - removeBytes: Removes a number of bytes from the current size @inline(__always) init( - blob: borrowing Storage.Blob, + blob: Storage.Blob, count: Int, removing removeBytes: Int) { @@ -353,8 +318,7 @@ public struct ByteBuffer: @unchecked Sendable { /// - def: Type of the object /// - position: the index of the object in the buffer @inline(__always) - @inlinable - public func read(def: T.Type, position: Int) -> T { + public func read(def: T.Type, position: Int) -> T { _storage.readWithUnsafeRawPointer(position: position) { $0.bindMemory(to: T.self, capacity: 1) .pointee @@ -448,7 +412,7 @@ public struct ByteBuffer: @unchecked Sendable { /// - Parameter removeBytes: the amount of bytes to remove from the current Size @inline(__always) public func duplicate(removing removeBytes: Int = 0) -> ByteBuffer { - assert(removeBytes >= 0, "Can NOT remove negative bytes") + assert(removeBytes > 0, "Can NOT remove negative bytes") assert( removeBytes < capacity, "Can NOT remove more bytes than the ones allocated") @@ -500,9 +464,8 @@ public struct ByteBuffer: @unchecked Sendable { extension ByteBuffer: CustomDebugStringConvertible { public var debugDescription: String { - let blobDescription = _storage.retainedBlob.description - return """ - buffer located at: \(blobDescription), + """ + buffer located at: \(_storage.retainedBlob), with capacity of \(capacity), { writtenSize: \(_readerIndex), readerSize: \(reader), size: \(size) } diff --git a/swift/Sources/FlatBuffers/Enum.swift b/swift/Sources/FlatBuffers/Enum.swift index feb576250..65e3a4d37 100644 --- a/swift/Sources/FlatBuffers/Enum.swift +++ b/swift/Sources/FlatBuffers/Enum.swift @@ -23,7 +23,7 @@ import Common /// Enum is a protocol that all flatbuffers enums should conform to /// Since it allows us to get the actual `ByteSize` and `Value` from /// a swift enum. -public protocol Enum: Sendable { +public protocol Enum { /// associatedtype that the type of the enum should conform to associatedtype T: Scalar & Verifiable /// Size of the current associatedtype in the enum diff --git a/swift/Sources/FlatBuffers/FlatBufferBuilder.swift b/swift/Sources/FlatBuffers/FlatBufferBuilder.swift index d9cc0a96d..9e778d225 100644 --- a/swift/Sources/FlatBuffers/FlatBufferBuilder.swift +++ b/swift/Sources/FlatBuffers/FlatBufferBuilder.swift @@ -45,10 +45,9 @@ public struct FlatBufferBuilder { /// Dictonary that stores a map of all the strings that were written to the buffer private var stringOffsetMap: [String: Offset] = [:] /// A check to see if finish(::) was ever called to retreive data object - private(set) var finished = false + private var finished = false /// A check to see if the buffer should serialize Default values - @usableFromInline - let serializeDefaults: Bool + private var serializeDefaults: Bool /// Current alignment for the buffer var _minAlignment: Int = 0 { @@ -489,7 +488,7 @@ public struct FlatBufferBuilder { /// /// - Parameter bytes: bytes to be written into the buffer /// - Returns: ``Offset`` of the vector - mutating public func createVector(bytes: any ContiguousBytes) -> Offset { + mutating public func createVector(bytes: ContiguousBytes) -> Offset { bytes.withUnsafeBytes { startVector($0.count, elementSize: MemoryLayout.size) _bb.push(bytes: $0) @@ -757,7 +756,6 @@ public struct FlatBufferBuilder { /// - offset: ``Offset`` of another object to be written /// - position: The predefined position of the object @inline(__always) - @inlinable mutating public func add(offset: Offset, at position: VOffset) { if offset.isEmpty { return } add(element: refer(to: offset.o), def: 0, at: position) @@ -796,7 +794,6 @@ public struct FlatBufferBuilder { /// - def: Default value for that element /// - position: The predefined position of the element @inline(__always) - @inlinable mutating public func add( element: T, def: T, @@ -816,7 +813,6 @@ public struct FlatBufferBuilder { /// - element: Optional element of type scalar /// - position: The predefined position of the element @inline(__always) - @inlinable mutating public func add(element: T?, at position: VOffset) { guard let element = element else { return } track(offset: push(element: element), at: position) @@ -829,7 +825,6 @@ public struct FlatBufferBuilder { /// - Parameter element: Element to insert /// - returns: position of the Element @inline(__always) - @inlinable @discardableResult mutating public func push(element: T) -> UOffset { let size = MemoryLayout.size @@ -841,8 +836,7 @@ public struct FlatBufferBuilder { } @inline(__always) - @inlinable - public func read(def: T.Type, position: Int) -> T { + public func read(def: T.Type, position: Int) -> T { _bb.read(def: def, position: position) } } diff --git a/swift/Sources/FlatBuffers/FlatBufferObject.swift b/swift/Sources/FlatBuffers/FlatBufferObject.swift index dce45128e..0b9f01b07 100644 --- a/swift/Sources/FlatBuffers/FlatBufferObject.swift +++ b/swift/Sources/FlatBuffers/FlatBufferObject.swift @@ -18,9 +18,7 @@ import Foundation /// NativeStruct is a protocol that indicates if the struct is a native `swift` struct /// since now we will be serializing native structs into the buffer. -public protocol NativeStruct: BitwiseCopyable {} - -public protocol FlatBufferVerifiableNativeStruct: NativeStruct, Verifiable {} +public protocol NativeStruct {} /// FlatbuffersInitializable is a protocol that allows any object to be /// Initialized from a ByteBuffer @@ -37,8 +35,6 @@ public protocol FlatBufferTable: FlatbuffersInitializable, var __buffer: ByteBuffer! { get } } -public protocol FlatBufferVerifiableTable: FlatBufferTable, Verifiable {} - /// FlatbufferStruct structures all the Flatbuffers structs public protocol FlatBufferStruct: FlatbuffersInitializable, FlatbuffersVectorInitializable diff --git a/swift/Sources/FlatBuffers/Message.swift b/swift/Sources/FlatBuffers/Message.swift index 37729a063..a8cdbf8f0 100644 --- a/swift/Sources/FlatBuffers/Message.swift +++ b/swift/Sources/FlatBuffers/Message.swift @@ -16,52 +16,50 @@ import Foundation -enum FlatbuffersGRPCError: Error { - case finishedNotCalledOnBuilder -} +/// FlatBufferGRPCMessage protocol that should allow us to invoke +/// initializers directly from the GRPC generated code +public protocol FlatBufferGRPCMessage { + /// Size of readable bytes in the buffer + var size: Int { get } -public protocol GRPCVerifiableMessage { - associatedtype Message - - init(pointer: UnsafeRawBufferPointer) init(byteBuffer: ByteBuffer) - func decode() throws -> Message - func withUnsafeReadableBytes( + @discardableResult + @inline(__always) + func withUnsafeReadableBytes( _ body: (UnsafeRawBufferPointer) throws - -> Data) rethrows -> Data + -> T) rethrows -> T } -public struct GRPCMessage< - Table: FlatBufferVerifiableTable ->: Sendable, GRPCVerifiableMessage { - public typealias Message = Table +/// Message is a wrapper around Buffers to to able to send Flatbuffers `Buffers` through the +/// GRPC library +public struct Message: FlatBufferGRPCMessage { + internal var buffer: ByteBuffer - private let 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 size: Int { Int(buffer.size) } - public init(pointer: UnsafeRawBufferPointer) { - buffer = ByteBuffer( - copyingMemoryBound: pointer.baseAddress!, - capacity: pointer.count) - } - - public init(builder: inout FlatBufferBuilder) throws { - guard builder.finished else { - throw FlatbuffersGRPCError.finishedNotCalledOnBuilder - } - - buffer = builder.sizedBuffer - } - + /// Initializes the message with the type Flatbuffer.Bytebuffer that is transmitted over + /// GRPC + /// - Parameter byteBuffer: Flatbuffer ByteBuffer object public init(byteBuffer: ByteBuffer) { buffer = byteBuffer } - public func decode() throws -> Table { - var buf = buffer - return try getCheckedRoot(byteBuffer: &buf) + /// 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() } @discardableResult @@ -75,30 +73,3 @@ public struct GRPCMessage< } } } - -@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *) -public struct FlatBuffersMessageSerializer< - Message: GRPCVerifiableMessage ->: Sendable { - public init() {} - - public func serialize( - message: Message, - _ completion: (UnsafeRawBufferPointer) throws -> Data) throws -> Data - { - return try message.withUnsafeReadableBytes { - try completion($0) - } - } -} - -@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *) -public struct FlatBuffersMessageDeserializer< - Message: GRPCVerifiableMessage ->: Sendable { - public init() {} - - public func deserialize(pointer: UnsafeRawBufferPointer) throws -> Message { - Message.init(pointer: pointer) - } -} diff --git a/swift/Sources/FlatBuffers/Root.swift b/swift/Sources/FlatBuffers/Root.swift index 807f7b4ef..e176414b0 100644 --- a/swift/Sources/FlatBuffers/Root.swift +++ b/swift/Sources/FlatBuffers/Root.swift @@ -16,30 +16,6 @@ import Foundation -@inline(__always) -private func verifySizePrefix( - byteBuffer: inout ByteBuffer, - requireExactSize: Bool, - options: VerifierOptions) throws -{ - let verifier = try Verifier(buffer: &byteBuffer, options: options) - let prefixPosition = byteBuffer.reader - let prefix: UOffset = try verifier.getValue(at: prefixPosition) - let availableSize = byteBuffer.size &- UOffset(MemoryLayout.size) - - if requireExactSize { - guard prefix == availableSize else { - throw FlatbuffersErrors.prefixedSizeNotEqualToBufferSize - } - } else if prefix > availableSize { - throw FlatbuffersErrors.outOfBounds( - position: UInt(prefixPosition) - &+ UInt(MemoryLayout.size) - &+ UInt(prefix), - end: byteBuffer.capacity) - } -} - /// Takes in a prefixed sized buffer, where the prefixed size would be skipped. /// And would verify that the buffer passed is a valid `Flatbuffers` Object. /// - Parameters: @@ -55,10 +31,6 @@ public func getPrefixedSizeCheckedRoot( fileId: String? = nil, options: VerifierOptions = .init()) throws -> T { - try verifySizePrefix( - byteBuffer: &byteBuffer, - requireExactSize: false, - options: options) byteBuffer.skipPrefix() return try getCheckedRoot( byteBuffer: &byteBuffer, @@ -81,11 +53,10 @@ public func getCheckedPrefixedSizeRoot( fileId: String? = nil, options: VerifierOptions = .init()) throws -> T { - try verifySizePrefix( - byteBuffer: &byteBuffer, - requireExactSize: true, - options: options) - byteBuffer.skipPrefix() + let prefix = byteBuffer.skipPrefix() + if prefix != byteBuffer.size { + throw FlatbuffersErrors.prefixedSizeNotEqualToBufferSize + } return try getCheckedRoot( byteBuffer: &byteBuffer, fileId: fileId, @@ -124,15 +95,14 @@ public func getCheckedRoot( options: VerifierOptions = .init()) throws -> T { var verifier = try Verifier(buffer: &byteBuffer, options: options) - let rootPosition = byteBuffer.reader if let fileId = fileId { - try verifier.verify(id: fileId, at: rootPosition) + try verifier.verify(id: fileId) } - try ForwardOffset.verify(&verifier, at: rootPosition, of: T.self) + try ForwardOffset.verify(&verifier, at: 0, of: T.self) return T.init( byteBuffer, - o: Int32(byteBuffer.read(def: UOffset.self, position: rootPosition)) - &+ Int32(rootPosition)) + o: Int32(byteBuffer.read(def: UOffset.self, position: byteBuffer.reader)) + &+ Int32(byteBuffer.reader)) } /// Returns a `NON-Checked` flatbuffers object diff --git a/swift/Sources/FlatBuffers/Table.swift b/swift/Sources/FlatBuffers/Table.swift index de8762654..4aa08d576 100644 --- a/swift/Sources/FlatBuffers/Table.swift +++ b/swift/Sources/FlatBuffers/Table.swift @@ -49,7 +49,7 @@ public struct Table { /// the vtable /// - Parameter o: current offset /// - Returns: offset of field within buffer - public func offset(_ o: VOffset) -> Int32 { + public func offset(_ o: Int32) -> Int32 { let vtable = position &- bb.read(def: Int32.self, position: Int(position)) return o < bb @@ -57,7 +57,7 @@ public struct Table { ? Int32( bb.read( def: Int16.self, - position: Int(vtable &+ Int32(o)))) : 0 + position: Int(vtable &+ o))) : 0 } /// Gets the indirect offset of the current stored object @@ -82,7 +82,7 @@ public struct Table { /// - Parameters: /// - type: Type of Element that needs to be read from the buffer /// - o: Offset of the Element - public func readBuffer(of type: T.Type, at o: Int32) -> T { + public func readBuffer(of type: T.Type, at o: Int32) -> T { bb.read(def: T.self, position: Int(o &+ position)) } @@ -106,13 +106,13 @@ public struct Table { /// This should only be used by `Scalars` /// - Parameter off: Readable offset /// - Returns: Returns a vector of type [T] - public func getVector(at off: VOffset) -> [T]? { + public func getVector(at off: Int32) -> [T]? { let o = offset(off) guard o != 0 else { return nil } return bb.readSlice(index: Int(vector(at: o)), count: Int(vector(count: o))) } - public func vector(at off: VOffset, byteSize: Int) -> FlatbufferVector { + public func vector(at off: Int32, byteSize: Int) -> FlatbufferVector { let off = offset(off) return FlatbufferVector( bb: bb, @@ -122,7 +122,7 @@ public struct Table { } public func unionVector( - at off: VOffset, + at off: Int32, byteSize: Int) -> UnionFlatbufferVector { let off = offset(off) @@ -146,7 +146,7 @@ public struct Table { /// - Returns: Returns a pointer to the underlying data @inline(__always) public func withUnsafePointerToSlice( - at off: VOffset, + at off: Int32, body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { let o = offset(off) diff --git a/swift/Sources/FlatBuffers/TableVerifier.swift b/swift/Sources/FlatBuffers/TableVerifier.swift index d4c4059dd..b09db49e6 100644 --- a/swift/Sources/FlatBuffers/TableVerifier.swift +++ b/swift/Sources/FlatBuffers/TableVerifier.swift @@ -115,7 +115,7 @@ public struct TableVerifier { unionKeyName: String, fieldName: String, required: Bool, - completion: (inout Verifier, T, Int) throws -> Void) throws + completion: @escaping (inout Verifier, T, Int) throws -> Void) throws where T: UnionEnum { let keyPos = try dereference(key) diff --git a/swift/Sources/FlatBuffers/Vectors/FlatbufferVector.swift b/swift/Sources/FlatBuffers/Vectors/FlatbufferVector.swift index fae8b4c13..a9b03582b 100644 --- a/swift/Sources/FlatBuffers/Vectors/FlatbufferVector.swift +++ b/swift/Sources/FlatBuffers/Vectors/FlatbufferVector.swift @@ -68,7 +68,7 @@ public struct FlatbufferVector< } extension FlatbufferVector: Encodable where Element: Encodable { - public func encode(to encoder: any Encoder) throws { + public func encode(to encoder: Encoder) throws { var container = encoder.unkeyedContainer() for element in self { try container.encode(element) diff --git a/swift/Sources/FlatBuffers/Vectors/UnionFlatbufferVector.swift b/swift/Sources/FlatBuffers/Vectors/UnionFlatbufferVector.swift index 7b595814f..ab61e6fb1 100644 --- a/swift/Sources/FlatBuffers/Vectors/UnionFlatbufferVector.swift +++ b/swift/Sources/FlatBuffers/Vectors/UnionFlatbufferVector.swift @@ -49,8 +49,8 @@ public struct UnionFlatbufferVector { public subscript( position: Int, - Type: any FlatbuffersVectorInitializable - .Type) -> any FlatbuffersVectorInitializable + Type: FlatbuffersVectorInitializable + .Type) -> FlatbuffersVectorInitializable { guard position < count else { fatalError( diff --git a/swift/Sources/FlatBuffers/Verifiable.swift b/swift/Sources/FlatBuffers/Verifiable.swift index 9f4bcf6d7..42259e6f3 100644 --- a/swift/Sources/FlatBuffers/Verifiable.swift +++ b/swift/Sources/FlatBuffers/Verifiable.swift @@ -56,15 +56,8 @@ extension Verifiable { let len: UOffset = try verifier.getValue(at: position) let intLen = Int(len) let start = Int(clamping: (position &+ MemoryLayout.size).magnitude) - let byteCount = intLen.multipliedReportingOverflow( - by: MemoryLayout.size) - guard !byteCount.overflow else { - throw FlatbuffersErrors.outOfBounds( - position: UInt.max, - end: verifier.capacity) - } try verifier.isAligned(position: start, type: type.self) - try verifier.rangeInBuffer(position: start, size: byteCount.partialValue) + try verifier.rangeInBuffer(position: start, size: intLen) return (start, intLen) } } diff --git a/swift/Sources/FlatBuffers/Verifier.swift b/swift/Sources/FlatBuffers/Verifier.swift index 5922ddb51..b0ef3968d 100644 --- a/swift/Sources/FlatBuffers/Verifier.swift +++ b/swift/Sources/FlatBuffers/Verifier.swift @@ -163,7 +163,7 @@ public struct Verifier { /// - Parameter position: Current position to be read /// - Throws: `inBuffer` errors /// - Returns: a value of type `T` usually a `VTable` or a table offset - internal func getValue(at position: Int) throws -> T { + internal func getValue(at position: Int) throws -> T { try inBuffer(position: position, of: T.self) return _buffer.read(def: T.self, position: position) } @@ -215,16 +215,12 @@ public struct Verifier { } @inline(__always) - func verify(id: String, at position: Int) throws { + func verify(id: String) throws { let size = MemoryLayout.size - guard - position >= 0, - position <= storage.capacity, - storage.capacity - position >= size &* 2 - else { + guard storage.capacity >= (size &* 2) else { throw FlatbuffersErrors.bufferDoesntContainID } - let str = _buffer.readString(at: position &+ size, count: size) + let str = _buffer.readString(at: size, count: size) if id == str { return } diff --git a/swift/Sources/FlatBuffers/_InternalByteBuffer.swift b/swift/Sources/FlatBuffers/_InternalByteBuffer.swift index a3d730855..8dced85b4 100644 --- a/swift/Sources/FlatBuffers/_InternalByteBuffer.swift +++ b/swift/Sources/FlatBuffers/_InternalByteBuffer.swift @@ -30,7 +30,7 @@ struct _InternalByteBuffer { @usableFromInline final class Storage { /// pointer to the start of the buffer object in memory - @exclusivity(unchecked) private(set) var memory: UnsafeMutableRawPointer + private(set) var memory: UnsafeMutableRawPointer @usableFromInline init(count: Int, alignment: Int) { @@ -146,7 +146,7 @@ struct _InternalByteBuffer { #if !os(WASI) @inline(__always) @usableFromInline - mutating func push(bytes: any ContiguousBytes) { + mutating func push(bytes: ContiguousBytes) { bytes.withUnsafeBytes { ptr in ensureSpace(size: ptr.count) memcpy( @@ -333,7 +333,6 @@ struct _InternalByteBuffer { @discardableResult @inline(__always) - @usableFromInline func readWithUnsafeRawPointer( position: Int, _ body: (UnsafeRawPointer) throws -> T) rethrows -> T diff --git a/swift/Sources/FlexBuffers/ByteBuffer.swift b/swift/Sources/FlexBuffers/ByteBuffer.swift index 6789618ce..af75631ac 100644 --- a/swift/Sources/FlexBuffers/ByteBuffer.swift +++ b/swift/Sources/FlexBuffers/ByteBuffer.swift @@ -27,32 +27,15 @@ public struct ByteBuffer { @usableFromInline final class Storage { @usableFromInline - @frozen enum Blob: ~Copyable { + enum Blob { #if !os(WASI) case data(Data) - case bytes(any ContiguousBytes) + case bytes(ContiguousBytes) #endif case byteBuffer(_InternalByteBuffer) case array([UInt8]) case pointer(UnsafeMutableRawPointer) - - init(_ other: borrowing Blob) { - switch other { - #if !os(WASI) - case .data(let data): - self = .data(data) - case .bytes(let contiguousBytes): - self = .bytes(contiguousBytes) - #endif - case .byteBuffer(let internalByteBuffer): - self = .byteBuffer(internalByteBuffer) - case .array(let array): - self = .array(array) - case .pointer(let unsafeMutableRawPointer): - self = .pointer(unsafeMutableRawPointer) - } - } } /// This storage doesn't own the memory, therefore, we won't deallocate on deinit. @@ -61,7 +44,7 @@ public struct ByteBuffer { private let capacity: Int /// Retained blob of data that requires the storage to retain a pointer to. @usableFromInline - let retainedBlob: Blob + var retainedBlob: Blob @usableFromInline init(count: Int) { @@ -74,9 +57,9 @@ public struct ByteBuffer { } @usableFromInline - init(blob: borrowing Blob, capacity count: Int) { + init(blob: Blob, capacity count: Int) { capacity = count - retainedBlob = .init(blob) + retainedBlob = blob isOwned = false } @@ -293,7 +276,7 @@ public struct ByteBuffer { /// - removeBytes: Removes a number of bytes from the current size @inline(__always) init( - blob: borrowing Storage.Blob, + blob: Storage.Blob, count: Int, removing removeBytes: Int) { @@ -333,7 +316,7 @@ public struct ByteBuffer { /// - def: Type of the object /// - position: the index of the object in the buffer @inline(__always) - public func read(def: T.Type, position: Int) -> T { + public func read(def: T.Type, position: Int) -> T { _storage.readWithUnsafeRawPointer(position: position) { $0.bindMemory(to: T.self, capacity: 1) .pointee @@ -377,10 +360,10 @@ public struct ByteBuffer { @inline(__always) func readSizedScalar< T: BinaryInteger, - T1: BinaryInteger & BitwiseCopyable, - T2: BinaryInteger & BitwiseCopyable, - T3: BinaryInteger & BitwiseCopyable, - T4: BinaryInteger & BitwiseCopyable + T1: BinaryInteger, + T2: BinaryInteger, + T3: BinaryInteger, + T4: BinaryInteger >( def: T.Type, t1: T1.Type, diff --git a/swift/Sources/FlexBuffers/FlexBufferType.swift b/swift/Sources/FlexBuffers/FlexBufferType.swift index 2d75b2a88..4f51c5d28 100644 --- a/swift/Sources/FlexBuffers/FlexBufferType.swift +++ b/swift/Sources/FlexBuffers/FlexBufferType.swift @@ -16,7 +16,7 @@ import Foundation -public enum FlexBufferType: UInt64, Sendable { +public enum FlexBufferType: UInt64 { case null = 0 /// Variable width signed integer: `Int8, Int16, Int32, Int64` case int = 1 diff --git a/swift/Sources/FlexBuffers/Reader/Reference.swift b/swift/Sources/FlexBuffers/Reader/Reference.swift index e78efecce..f771ba24c 100644 --- a/swift/Sources/FlexBuffers/Reader/Reference.swift +++ b/swift/Sources/FlexBuffers/Reader/Reference.swift @@ -14,7 +14,6 @@ * limitations under the License. */ -import Common import Foundation enum FlexBuffersErrors: Error { @@ -24,10 +23,6 @@ enum FlexBuffersErrors: Error { @inline(__always) public func getRoot(buffer: ByteBuffer) throws -> Reference? { - assert( - isLitteEndian, - "Swift FlexBuffers currently only supports little-endian systems") - let end = buffer.count if buffer.count < 3 { throw FlexBuffersErrors.sizeOfBufferIsTooSmall diff --git a/swift/Sources/FlexBuffers/Utils/BitWidth.swift b/swift/Sources/FlexBuffers/Utils/BitWidth.swift index d4d8431a9..d6205002a 100644 --- a/swift/Sources/FlexBuffers/Utils/BitWidth.swift +++ b/swift/Sources/FlexBuffers/Utils/BitWidth.swift @@ -17,7 +17,7 @@ import Foundation @usableFromInline -enum BitWidth: UInt64, CaseIterable, Sendable { +enum BitWidth: UInt64, CaseIterable { case w8 = 0 case w16 = 1 case w32 = 2 diff --git a/swift/Sources/FlexBuffers/Utils/Value.swift b/swift/Sources/FlexBuffers/Utils/Value.swift index 36bda4a73..b9059feb3 100644 --- a/swift/Sources/FlexBuffers/Utils/Value.swift +++ b/swift/Sources/FlexBuffers/Utils/Value.swift @@ -20,10 +20,10 @@ import Foundation import Common #endif -public struct Value: Equatable, Sendable { +public struct Value: Equatable { @usableFromInline - enum Union: Equatable, Sendable { + enum Union: Equatable { case i(Int64) case u(UInt64) case f(Double) diff --git a/swift/Sources/FlexBuffers/Writer/FlexBuffersWriter.swift b/swift/Sources/FlexBuffers/Writer/FlexBuffersWriter.swift index 77a4db751..6836ec70a 100644 --- a/swift/Sources/FlexBuffers/Writer/FlexBuffersWriter.swift +++ b/swift/Sources/FlexBuffers/Writer/FlexBuffersWriter.swift @@ -37,15 +37,12 @@ public struct FlexBuffersWriter { private var hasDuplicatedKeys = false private var minBitWidth: BitWidth = .w8 private var _bb: _InternalByteBuffer - private var stack: Stack = Stack() + private var stack: [Value] = [] private var keyPool: [Int: UInt] = [:] private var stringPool: [Int: UInt] = [:] private var flags: BuilderFlag public init(initialSize: Int = 1024, flags: BuilderFlag = .shareKeys) { - assert( - isLitteEndian, - "Swift FlexBuffers currently only supports little-endian systems") _bb = _InternalByteBuffer(initialSize: initialSize) self.flags = flags } @@ -151,7 +148,7 @@ public struct FlexBuffersWriter { typed: typed, fixed: fixed, keys: nil) - stack.popLast(start) + stack = Array(stack[...stride - private let storage: Storage - private var capacity: Int - private(set) var count: Int - - var startIndex: Int { - 0 - } - - var endIndex: Int { - count - } - - init() { - count = 0 - capacity = Self.initialCapacity - - storage = Storage( - capacity: capacity, - alignment: MemoryLayout.alignment) - } - - @inline(__always) - subscript(position: Int) -> Value { - get { - storage.memory.advanced(by: position &* MemoryLayout.stride) - .assumingMemoryBound(to: Value.self).pointee - } - set { - storage.memory.advanced(by: position &* MemoryLayout.stride) - .assumingMemoryBound(to: Value.self).pointee = newValue - } - } - - @inline(__always) - mutating func popLast(_ val: Int) { - count = if val < 0 { - 0 - } else { - val - } - } - - mutating func append(_ value: Value) { - let writePosition = count &* MemoryLayout.stride - if writePosition >= capacity { - reallocate(writePosition: writePosition) - } - - storage.memory.advanced(by: writePosition).storeBytes( - of: value, - as: Value.self) - count += 1 - } - - mutating func removeAll(keepingCapacity keepCapacity: Bool = false) { - count = 0 - if !keepCapacity { - let ptr = storage.memory - defer { ptr.deallocate() } - - capacity = Self.initialCapacity - storage.memory = UnsafeMutableRawPointer.allocate( - byteCount: capacity, - alignment: MemoryLayout.alignment) - } - memset(storage.memory, 0, capacity) - } - - @discardableResult - mutating func withUnsafeMutableBytes( - start: Int, - _ body: (UnsafeMutableRawBufferPointer) throws -> R) rethrows -> R - { - let startingPosition = start &* MemoryLayout.stride - let pointer = storage.memory.advanced(by: startingPosition) - return try body(UnsafeMutableRawBufferPointer( - start: pointer, - count: (count &* MemoryLayout.stride) &- startingPosition)) - } - - @discardableResult - mutating func withUnsafeMutableBytes( - _ body: (UnsafeMutableRawBufferPointer) throws - -> R) rethrows -> R - { - return try body(UnsafeMutableRawBufferPointer( - start: storage.memory, - count: count &* MemoryLayout.stride)) - } - - mutating private func reallocate(writePosition: Int) { - while capacity <= writePosition { - capacity = capacity << 1 - } - - /// solution take from Apple-NIO - capacity = capacity.convertToPowerofTwo - - let newData = UnsafeMutableRawPointer.allocate( - byteCount: capacity, - alignment: MemoryLayout.alignment) - memset(newData, 0, capacity) - memcpy( - newData, - storage.memory, - writePosition) - storage.memory.deallocate() - storage.memory = newData - } -} diff --git a/swift/Sources/FlexBuffers/_InternalByteBuffer.swift b/swift/Sources/FlexBuffers/_InternalByteBuffer.swift index e99f95aa1..fcf7577aa 100644 --- a/swift/Sources/FlexBuffers/_InternalByteBuffer.swift +++ b/swift/Sources/FlexBuffers/_InternalByteBuffer.swift @@ -31,7 +31,7 @@ struct _InternalByteBuffer { @usableFromInline final class Storage { /// pointer to the start of the buffer object in memory - @exclusivity(unchecked) private(set) var memory: UnsafeMutableRawPointer + var memory: UnsafeMutableRawPointer @usableFromInline init(count: Int, alignment: Int) { @@ -60,7 +60,7 @@ struct _InternalByteBuffer { let newData = UnsafeMutableRawPointer.allocate( byteCount: capacity, alignment: alignment) - memset(newData, 0, capacity) + memset(newData, 0, capacity &- writerSize) memcpy( newData, memory, diff --git a/tests/BUILD.bazel b/tests/BUILD.bazel index 72d746fbe..5451da940 100644 --- a/tests/BUILD.bazel +++ b/tests/BUILD.bazel @@ -52,7 +52,6 @@ cc_test( "monster_test.cpp", "monster_test.h", "monster_test_bfbs_generated.h", - "cross_namespace_pack_test_generated.h", "namespace_test/namespace_test1_generated.h", "namespace_test/namespace_test2_generated.h", "native_inline_table_test_generated.h", @@ -79,6 +78,9 @@ cc_test( "vector_table_naked_ptr/vector_table_naked_ptr_generated.h", "vector_table_naked_ptr_test.h", "vector_table_naked_ptr_test.cpp", + "test_vector_type.h", + "cpp_vector_type_test.h", + "cpp_vector_type_test.cpp", ], copts = [ "-DFLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE", @@ -137,7 +139,7 @@ cc_test( deps = [ ":alignment_test_cc_fbs", ":arrays_test_cc_fbs", - ":cross_namespace_pack_test_cc_fbs", + ":cpp_vector_type_cc_fbs", ":default_vectors_strings_test_cc_fbs", ":monster_extra_cc_fbs", ":monster_test_cc_fbs", @@ -263,17 +265,6 @@ flatbuffer_cc_library( ], ) -flatbuffer_cc_library( - name = "cross_namespace_pack_test_cc_fbs", - srcs = ["cross_namespace_pack_test.fbs"], - flatc_args = [ - "--gen-object-api", - "--gen-mutable", - "--gen-compare", - "--reflect-names", - ], -) - flatbuffer_cc_library( name = "native_type_test_cc_fbs", srcs = ["native_type_test.fbs"], @@ -284,6 +275,19 @@ flatbuffer_cc_library( ], ) +flatbuffer_cc_library( + name = "cpp_vector_type_cc_fbs", + srcs = ["cpp_vector_type.fbs"], + flatc_args = [ + "--gen-compare", + "--gen-mutable", + "--gen-object-api", + "--reflect-names", + "--cpp-include test_vector_type.h", + "--cpp-vector-type ::flatbuffers::tests::CustomVector", + ], +) + flatbuffer_cc_library( name = "alignment_test_cc_fbs", srcs = ["alignment_test.fbs"], diff --git a/tests/FlatBuffers.Test/FlatBuffers.Test.csproj b/tests/FlatBuffers.Test/FlatBuffers.Test.csproj index c1e723314..f869552ad 100644 --- a/tests/FlatBuffers.Test/FlatBuffers.Test.csproj +++ b/tests/FlatBuffers.Test/FlatBuffers.Test.csproj @@ -106,9 +106,6 @@ MyGame\Example\NestedStruct.cs - - MyGame\Example\LargeArrayStruct.cs - MyGame\Example\LongEnum.cs diff --git a/tests/MyGame/Example/Monster.py b/tests/MyGame/Example/Monster.py index d26dbaea2..3814efe1a 100644 --- a/tests/MyGame/Example/Monster.py +++ b/tests/MyGame/Example/Monster.py @@ -922,7 +922,7 @@ def MonsterCreateInventoryVector(builder, data): return builder.EndVector() def CreateInventoryVector(builder, data): - return MonsterCreateInventoryVector(builder, data) + MonsterCreateInventoryVector(builder, data) def MonsterAddColor(builder, color): builder.PrependUint8Slot(6, color, 8) @@ -962,7 +962,7 @@ def MonsterCreateTest4Vector(builder, data): return builder.EndVector() def CreateTest4Vector(builder, data): - return MonsterCreateTest4Vector(builder, data) + MonsterCreateTest4Vector(builder, data) def MonsterAddTestarrayofstring(builder, testarrayofstring): builder.PrependUOffsetTRelativeSlot(10, flatbuffers.number_types.UOffsetTFlags.py_type(testarrayofstring), 0) @@ -980,7 +980,7 @@ def MonsterCreateTestarrayofstringVector(builder, data): return builder.CreateVectorOfTables(data) def CreateTestarrayofstringVector(builder, data): - return MonsterCreateTestarrayofstringVector(builder, data) + MonsterCreateTestarrayofstringVector(builder, data) def MonsterAddTestarrayoftables(builder, testarrayoftables): builder.PrependUOffsetTRelativeSlot(11, flatbuffers.number_types.UOffsetTFlags.py_type(testarrayoftables), 0) @@ -998,7 +998,7 @@ def MonsterCreateTestarrayoftablesVector(builder, data): return builder.CreateVectorOfTables(data) def CreateTestarrayoftablesVector(builder, data): - return MonsterCreateTestarrayoftablesVector(builder, data) + MonsterCreateTestarrayoftablesVector(builder, data) def MonsterAddEnemy(builder, enemy): builder.PrependUOffsetTRelativeSlot(12, flatbuffers.number_types.UOffsetTFlags.py_type(enemy), 0) @@ -1026,7 +1026,7 @@ def MonsterCreateTestnestedflatbufferVector(builder, data): return builder.EndVector() def CreateTestnestedflatbufferVector(builder, data): - return MonsterCreateTestnestedflatbufferVector(builder, data) + MonsterCreateTestnestedflatbufferVector(builder, data) def MonsterMakeTestnestedflatbufferVectorFromBytes(builder, bytes): builder.StartVector(1, len(bytes), 1) @@ -1115,7 +1115,7 @@ def MonsterCreateTestarrayofboolsVector(builder, data): return builder.EndVector() def CreateTestarrayofboolsVector(builder, data): - return MonsterCreateTestarrayofboolsVector(builder, data) + MonsterCreateTestarrayofboolsVector(builder, data) def MonsterAddTestf(builder, testf): builder.PrependFloat32Slot(25, testf, 3.14159) @@ -1151,7 +1151,7 @@ def MonsterCreateTestarrayofstring2Vector(builder, data): return builder.CreateVectorOfTables(data) def CreateTestarrayofstring2Vector(builder, data): - return MonsterCreateTestarrayofstring2Vector(builder, data) + MonsterCreateTestarrayofstring2Vector(builder, data) def MonsterAddTestarrayofsortedstruct(builder, testarrayofsortedstruct): builder.PrependUOffsetTRelativeSlot(29, flatbuffers.number_types.UOffsetTFlags.py_type(testarrayofsortedstruct), 0) @@ -1173,7 +1173,7 @@ def MonsterCreateTestarrayofsortedstructVector(builder, data): return builder.EndVector() def CreateTestarrayofsortedstructVector(builder, data): - return MonsterCreateTestarrayofsortedstructVector(builder, data) + MonsterCreateTestarrayofsortedstructVector(builder, data) def MonsterAddFlex(builder, flex): builder.PrependUOffsetTRelativeSlot(30, flatbuffers.number_types.UOffsetTFlags.py_type(flex), 0) @@ -1195,7 +1195,7 @@ def MonsterCreateFlexVector(builder, data): return builder.EndVector() def CreateFlexVector(builder, data): - return MonsterCreateFlexVector(builder, data) + MonsterCreateFlexVector(builder, data) def MonsterAddTest5(builder, test5): builder.PrependUOffsetTRelativeSlot(31, flatbuffers.number_types.UOffsetTFlags.py_type(test5), 0) @@ -1217,7 +1217,7 @@ def MonsterCreateTest5Vector(builder, data): return builder.EndVector() def CreateTest5Vector(builder, data): - return MonsterCreateTest5Vector(builder, data) + MonsterCreateTest5Vector(builder, data) def MonsterAddVectorOfLongs(builder, vectorOfLongs): builder.PrependUOffsetTRelativeSlot(32, flatbuffers.number_types.UOffsetTFlags.py_type(vectorOfLongs), 0) @@ -1239,7 +1239,7 @@ def MonsterCreateVectorOfLongsVector(builder, data): return builder.EndVector() def CreateVectorOfLongsVector(builder, data): - return MonsterCreateVectorOfLongsVector(builder, data) + MonsterCreateVectorOfLongsVector(builder, data) def MonsterAddVectorOfDoubles(builder, vectorOfDoubles): builder.PrependUOffsetTRelativeSlot(33, flatbuffers.number_types.UOffsetTFlags.py_type(vectorOfDoubles), 0) @@ -1261,7 +1261,7 @@ def MonsterCreateVectorOfDoublesVector(builder, data): return builder.EndVector() def CreateVectorOfDoublesVector(builder, data): - return MonsterCreateVectorOfDoublesVector(builder, data) + MonsterCreateVectorOfDoublesVector(builder, data) def MonsterAddParentNamespaceTest(builder, parentNamespaceTest): builder.PrependUOffsetTRelativeSlot(34, flatbuffers.number_types.UOffsetTFlags.py_type(parentNamespaceTest), 0) @@ -1285,7 +1285,7 @@ def MonsterCreateVectorOfReferrablesVector(builder, data): return builder.CreateVectorOfTables(data) def CreateVectorOfReferrablesVector(builder, data): - return MonsterCreateVectorOfReferrablesVector(builder, data) + MonsterCreateVectorOfReferrablesVector(builder, data) def MonsterAddSingleWeakReference(builder, singleWeakReference): builder.PrependUint64Slot(36, singleWeakReference, 0) @@ -1313,7 +1313,7 @@ def MonsterCreateVectorOfWeakReferencesVector(builder, data): return builder.EndVector() def CreateVectorOfWeakReferencesVector(builder, data): - return MonsterCreateVectorOfWeakReferencesVector(builder, data) + MonsterCreateVectorOfWeakReferencesVector(builder, data) def MonsterAddVectorOfStrongReferrables(builder, vectorOfStrongReferrables): builder.PrependUOffsetTRelativeSlot(38, flatbuffers.number_types.UOffsetTFlags.py_type(vectorOfStrongReferrables), 0) @@ -1331,7 +1331,7 @@ def MonsterCreateVectorOfStrongReferrablesVector(builder, data): return builder.CreateVectorOfTables(data) def CreateVectorOfStrongReferrablesVector(builder, data): - return MonsterCreateVectorOfStrongReferrablesVector(builder, data) + MonsterCreateVectorOfStrongReferrablesVector(builder, data) def MonsterAddCoOwningReference(builder, coOwningReference): builder.PrependUint64Slot(39, coOwningReference, 0) @@ -1359,7 +1359,7 @@ def MonsterCreateVectorOfCoOwningReferencesVector(builder, data): return builder.EndVector() def CreateVectorOfCoOwningReferencesVector(builder, data): - return MonsterCreateVectorOfCoOwningReferencesVector(builder, data) + MonsterCreateVectorOfCoOwningReferencesVector(builder, data) def MonsterAddNonOwningReference(builder, nonOwningReference): builder.PrependUint64Slot(41, nonOwningReference, 0) @@ -1387,7 +1387,7 @@ def MonsterCreateVectorOfNonOwningReferencesVector(builder, data): return builder.EndVector() def CreateVectorOfNonOwningReferencesVector(builder, data): - return MonsterCreateVectorOfNonOwningReferencesVector(builder, data) + MonsterCreateVectorOfNonOwningReferencesVector(builder, data) def MonsterAddAnyUniqueType(builder, anyUniqueType): builder.PrependUint8Slot(43, anyUniqueType, 0) @@ -1433,7 +1433,7 @@ def MonsterCreateVectorOfEnumsVector(builder, data): return builder.EndVector() def CreateVectorOfEnumsVector(builder, data): - return MonsterCreateVectorOfEnumsVector(builder, data) + MonsterCreateVectorOfEnumsVector(builder, data) def MonsterAddSignedEnum(builder, signedEnum): builder.PrependInt8Slot(48, signedEnum, -1) @@ -1461,7 +1461,7 @@ def MonsterCreateTestrequirednestedflatbufferVector(builder, data): return builder.EndVector() def CreateTestrequirednestedflatbufferVector(builder, data): - return MonsterCreateTestrequirednestedflatbufferVector(builder, data) + MonsterCreateTestrequirednestedflatbufferVector(builder, data) def MonsterMakeTestrequirednestedflatbufferVectorFromBytes(builder, bytes): builder.StartVector(1, len(bytes), 1) @@ -1486,7 +1486,7 @@ def MonsterCreateScalarKeySortedTablesVector(builder, data): return builder.CreateVectorOfTables(data) def CreateScalarKeySortedTablesVector(builder, data): - return MonsterCreateScalarKeySortedTablesVector(builder, data) + MonsterCreateScalarKeySortedTablesVector(builder, data) def MonsterAddNativeInline(builder, nativeInline): builder.PrependStructSlot(51, flatbuffers.number_types.UOffsetTFlags.py_type(nativeInline), 0) diff --git a/tests/MyGame/Example/TypeAliases.py b/tests/MyGame/Example/TypeAliases.py index 048a9b1aa..2b7e6e499 100644 --- a/tests/MyGame/Example/TypeAliases.py +++ b/tests/MyGame/Example/TypeAliases.py @@ -238,7 +238,7 @@ def TypeAliasesCreateV8Vector(builder, data): return builder.EndVector() def CreateV8Vector(builder, data): - return TypeAliasesCreateV8Vector(builder, data) + TypeAliasesCreateV8Vector(builder, data) def TypeAliasesAddVf64(builder, vf64): builder.PrependUOffsetTRelativeSlot(11, flatbuffers.number_types.UOffsetTFlags.py_type(vf64), 0) @@ -260,7 +260,7 @@ def TypeAliasesCreateVf64Vector(builder, data): return builder.EndVector() def CreateVf64Vector(builder, data): - return TypeAliasesCreateVf64Vector(builder, data) + TypeAliasesCreateVf64Vector(builder, data) def TypeAliasesEnd(builder): return builder.EndObject() diff --git a/tests/MyGame/MonsterExtra.py b/tests/MyGame/MonsterExtra.py index 4992abae8..5db29801b 100644 --- a/tests/MyGame/MonsterExtra.py +++ b/tests/MyGame/MonsterExtra.py @@ -214,7 +214,7 @@ def MonsterExtraCreateDvecVector(builder: flatbuffers.Builder, data: Iterable[An return builder.EndVector() def CreateDvecVector(builder: flatbuffers.Builder, data: Iterable[Any]) -> int: - return MonsterExtraCreateDvecVector(builder, data) + MonsterExtraCreateDvecVector(builder, data) def MonsterExtraAddFvec(builder: flatbuffers.Builder, fvec: int): builder.PrependUOffsetTRelativeSlot(9, flatbuffers.number_types.UOffsetTFlags.py_type(fvec), 0) @@ -236,7 +236,7 @@ def MonsterExtraCreateFvecVector(builder: flatbuffers.Builder, data: Iterable[An return builder.EndVector() def CreateFvecVector(builder: flatbuffers.Builder, data: Iterable[Any]) -> int: - return MonsterExtraCreateFvecVector(builder, data) + MonsterExtraCreateFvecVector(builder, data) def MonsterExtraEnd(builder: flatbuffers.Builder) -> int: return builder.EndObject() diff --git a/tests/PythonTest.sh b/tests/PythonTest.sh index e7806bd42..90bee5724 100755 --- a/tests/PythonTest.sh +++ b/tests/PythonTest.sh @@ -28,7 +28,6 @@ ${test_dir}/../flatc -p -o ${gen_code_path} -I include_test monster_extra.fbs -- ${test_dir}/../flatc -p -o ${gen_code_path} -I include_test arrays_test.fbs --gen-object-api --python-typing ${test_dir}/../flatc -p -o ${gen_code_path} -I include_test nested_union_test.fbs --gen-object-api --python-typing --python-decode-obj-api-strings ${test_dir}/../flatc -p -o ${gen_code_path} -I include_test service_test.fbs --grpc --grpc-python-typed-handlers --python-typing --no-python-gen-numpy --gen-onefile -${test_dir}/../flatc -p -o ${gen_code_path} union_name_test.fbs --gen-object-api # Syntax: run_tests # diff --git a/tests/arrays_test.bfbs b/tests/arrays_test.bfbs index 24751b2cc..77ed99f66 100644 Binary files a/tests/arrays_test.bfbs and b/tests/arrays_test.bfbs differ diff --git a/tests/arrays_test.fbs b/tests/arrays_test.fbs index 00764b429..90cb0d726 100644 --- a/tests/arrays_test.fbs +++ b/tests/arrays_test.fbs @@ -18,14 +18,6 @@ struct ArrayStruct{ f:[int64:2]; } -struct LargeArrayStruct { - d:[ubyte:64]; - e:[float:64]; - f:[bool:64]; - g:[NestedStruct:64]; - h:[TestEnum:64]; -} - table ArrayTable{ a:ArrayStruct; } diff --git a/tests/arrays_test.schema.json b/tests/arrays_test.schema.json index 088797062..c33dc6caf 100644 --- a/tests/arrays_test.schema.json +++ b/tests/arrays_test.schema.json @@ -59,37 +59,6 @@ }, "additionalProperties" : false }, - "MyGame_Example_LargeArrayStruct" : { - "type" : "object", - "properties" : { - "d" : { - "type" : "array", "items" : {"type" : "integer", "minimum" : 0, "maximum" :255}, - "minItems": 64, - "maxItems": 64 - }, - "e" : { - "type" : "array", "items" : {"type" : "number"}, - "minItems": 64, - "maxItems": 64 - }, - "f" : { - "type" : "array", "items" : {"type" : "boolean"}, - "minItems": 64, - "maxItems": 64 - }, - "g" : { - "type" : "array", "items" : {"$ref" : "#/definitions/MyGame_Example_NestedStruct"}, - "minItems": 64, - "maxItems": 64 - }, - "h" : { - "type" : "array", "items" : {"$ref" : "#/definitions/MyGame_Example_TestEnum"}, - "minItems": 64, - "maxItems": 64 - } - }, - "additionalProperties" : false - }, "MyGame_Example_ArrayTable" : { "type" : "object", "properties" : { diff --git a/tests/arrays_test/mod.rs b/tests/arrays_test/mod.rs index 844c0729d..5a649d5e8 100644 --- a/tests/arrays_test/mod.rs +++ b/tests/arrays_test/mod.rs @@ -1,18 +1,16 @@ // Automatically generated by the Flatbuffers compiler. Do not modify. // @generated pub mod my_game { + use super::*; + pub mod example { use super::*; - pub mod example { - use super::*; - mod test_enum_generated; - pub use self::test_enum_generated::*; - mod nested_struct_generated; - pub use self::nested_struct_generated::*; - mod array_struct_generated; - pub use self::array_struct_generated::*; - mod large_array_struct_generated; - pub use self::large_array_struct_generated::*; - mod array_table_generated; - pub use self::array_table_generated::*; - } // example + mod test_enum_generated; + pub use self::test_enum_generated::*; + mod nested_struct_generated; + pub use self::nested_struct_generated::*; + mod array_struct_generated; + pub use self::array_struct_generated::*; + mod array_table_generated; + pub use self::array_table_generated::*; + } // example } // my_game diff --git a/tests/arrays_test/my_game/example/array_struct_generated.rs b/tests/arrays_test/my_game/example/array_struct_generated.rs index e7b2222ec..834fec39a 100644 --- a/tests/arrays_test/my_game/example/array_struct_generated.rs +++ b/tests/arrays_test/my_game/example/array_struct_generated.rs @@ -2,60 +2,50 @@ // @generated extern crate alloc; use super::*; - // struct ArrayStruct, aligned to 8 #[repr(transparent)] #[derive(Clone, Copy, PartialEq)] pub struct ArrayStruct(pub [u8; 160]); - -impl Default for ArrayStruct { - fn default() -> Self { - Self([0; 160]) - } +impl Default for ArrayStruct { + fn default() -> Self { + Self([0; 160]) + } } - impl ::core::fmt::Debug for ArrayStruct { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - f.debug_struct("ArrayStruct") - .field("a", &self.a()) - .field("b", &self.b()) - .field("c", &self.c()) - .field("d", &self.d()) - .field("e", &self.e()) - .field("f", &self.f()) - .finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + f.debug_struct("ArrayStruct") + .field("a", &self.a()) + .field("b", &self.b()) + .field("c", &self.c()) + .field("d", &self.d()) + .field("e", &self.e()) + .field("f", &self.f()) + .finish() + } } impl ::flatbuffers::SimpleToVerifyInSlice for ArrayStruct {} - impl<'a> ::flatbuffers::Follow<'a> for ArrayStruct { - type Inner = &'a ArrayStruct; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - unsafe { <&'a ArrayStruct>::follow(buf, loc) } - } + type Inner = &'a ArrayStruct; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { <&'a ArrayStruct>::follow(buf, loc) } + } } - impl<'a> ::flatbuffers::Follow<'a> for &'a ArrayStruct { - type Inner = &'a ArrayStruct; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - unsafe { ::flatbuffers::follow_cast_ref::(buf, loc) } - } + type Inner = &'a ArrayStruct; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { ::flatbuffers::follow_cast_ref::(buf, loc) } + } } - impl<'b> ::flatbuffers::Push for ArrayStruct { type Output = ArrayStruct; - #[inline] unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { let src = unsafe { ::core::slice::from_raw_parts(self as *const ArrayStruct as *const u8, ::size()) }; dst.copy_from_slice(src); } - #[inline] fn alignment() -> ::flatbuffers::PushAlignment { ::flatbuffers::PushAlignment::new(8) @@ -63,219 +53,207 @@ impl<'b> ::flatbuffers::Push for ArrayStruct { } impl<'a> ::flatbuffers::Verifiable for ArrayStruct { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.in_buffer::(pos) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.in_buffer::(pos) + } } impl<'a> ArrayStruct { - #[allow(clippy::too_many_arguments)] - pub fn new( - a: f32, - b: &[i32; 15], - c: i8, - d: &[NestedStruct; 2], - e: i32, - f: &[i64; 2], - ) -> Self { - let mut s = Self([0; 160]); - s.set_a(a); - s.set_b(b); - s.set_c(c); - s.set_d(d); - s.set_e(e); - s.set_f(f); - s - } + #[allow(clippy::too_many_arguments)] + pub fn new( + a: f32, + b: &[i32; 15], + c: i8, + d: &[NestedStruct; 2], + e: i32, + f: &[i64; 2], + ) -> Self { + let mut s = Self([0; 160]); + s.set_a(a); + s.set_b(b); + s.set_c(c); + s.set_d(d); + s.set_e(e); + s.set_f(f); + s + } - pub const fn get_fully_qualified_name() -> &'static str { - "MyGame.Example.ArrayStruct" - } + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Example.ArrayStruct" + } - pub fn a(&self) -> f32 { - let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - ::flatbuffers::EndianScalar::from_little_endian(unsafe { - ::core::ptr::copy_nonoverlapping( - self.0[0..].as_ptr(), - mem.as_mut_ptr() as *mut u8, - ::core::mem::size_of::<::Scalar>(), - ); - mem.assume_init() - }) - } + pub fn a(&self) -> f32 { + let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + ::flatbuffers::EndianScalar::from_little_endian(unsafe { + ::core::ptr::copy_nonoverlapping( + self.0[0..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + ::core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } - pub fn set_a(&mut self, x: f32) { - let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - unsafe { - ::core::ptr::copy_nonoverlapping( - &x_le as *const _ as *const u8, - self.0[0..].as_mut_ptr(), - ::core::mem::size_of::<::Scalar>(), - ); - } + pub fn set_a(&mut self, x: f32) { + let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + ::core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[0..].as_mut_ptr(), + ::core::mem::size_of::<::Scalar>(), + ); } + } - pub fn b(&'a self) -> ::flatbuffers::Array<'a, i32, 15> { - // Safety: - // Created from a valid Table for this object - // Which contains a valid array in this slot - use ::flatbuffers::Follow; - unsafe { ::flatbuffers::Array::follow(&self.0, 4) } - } + pub fn b(&'a self) -> ::flatbuffers::Array<'a, i32, 15> { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + use ::flatbuffers::Follow; + unsafe { ::flatbuffers::Array::follow(&self.0, 4) } + } - pub fn set_b(&mut self, items: &[i32; 15]) { - // Safety: - // Created from a valid Table for this object - // Which contains a valid array in this slot - unsafe { ::flatbuffers::emplace_scalar_array(&mut self.0, 4, items) }; - } + pub fn set_b(&mut self, items: &[i32; 15]) { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + unsafe { ::flatbuffers::emplace_scalar_array(&mut self.0, 4, items) }; + } - pub fn c(&self) -> i8 { - let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - ::flatbuffers::EndianScalar::from_little_endian(unsafe { - ::core::ptr::copy_nonoverlapping( - self.0[64..].as_ptr(), - mem.as_mut_ptr() as *mut u8, - ::core::mem::size_of::<::Scalar>(), - ); - mem.assume_init() - }) - } + pub fn c(&self) -> i8 { + let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + ::flatbuffers::EndianScalar::from_little_endian(unsafe { + ::core::ptr::copy_nonoverlapping( + self.0[64..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + ::core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } - pub fn set_c(&mut self, x: i8) { - let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - unsafe { - ::core::ptr::copy_nonoverlapping( - &x_le as *const _ as *const u8, - self.0[64..].as_mut_ptr(), - ::core::mem::size_of::<::Scalar>(), - ); - } + pub fn set_c(&mut self, x: i8) { + let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + ::core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[64..].as_mut_ptr(), + ::core::mem::size_of::<::Scalar>(), + ); } + } - pub fn d(&'a self) -> ::flatbuffers::Array<'a, NestedStruct, 2> { - // Safety: - // Created from a valid Table for this object - // Which contains a valid array in this slot - use ::flatbuffers::Follow; - unsafe { ::flatbuffers::Array::follow(&self.0, 72) } - } + pub fn d(&'a self) -> ::flatbuffers::Array<'a, NestedStruct, 2> { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + use ::flatbuffers::Follow; + unsafe { ::flatbuffers::Array::follow(&self.0, 72) } + } - pub fn set_d(&mut self, x: &[NestedStruct; 2]) { - // Safety: - // Created from a valid Table for this object - // Which contains a valid array in this slot - unsafe { - ::core::ptr::copy( - x.as_ptr() as *const u8, - self.0.as_mut_ptr().add(72), - 64, - ); - } + pub fn set_d(&mut self, x: &[NestedStruct; 2]) { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + unsafe { + ::core::ptr::copy( + x.as_ptr() as *const u8, + self.0.as_mut_ptr().add(72), + 64, + ); } + } - pub fn e(&self) -> i32 { - let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - ::flatbuffers::EndianScalar::from_little_endian(unsafe { - ::core::ptr::copy_nonoverlapping( - self.0[136..].as_ptr(), - mem.as_mut_ptr() as *mut u8, - ::core::mem::size_of::<::Scalar>(), - ); - mem.assume_init() - }) - } + pub fn e(&self) -> i32 { + let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + ::flatbuffers::EndianScalar::from_little_endian(unsafe { + ::core::ptr::copy_nonoverlapping( + self.0[136..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + ::core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } - pub fn set_e(&mut self, x: i32) { - let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - unsafe { - ::core::ptr::copy_nonoverlapping( - &x_le as *const _ as *const u8, - self.0[136..].as_mut_ptr(), - ::core::mem::size_of::<::Scalar>(), - ); - } + pub fn set_e(&mut self, x: i32) { + let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + ::core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[136..].as_mut_ptr(), + ::core::mem::size_of::<::Scalar>(), + ); } + } - pub fn f(&'a self) -> ::flatbuffers::Array<'a, i64, 2> { - // Safety: - // Created from a valid Table for this object - // Which contains a valid array in this slot - use ::flatbuffers::Follow; - unsafe { ::flatbuffers::Array::follow(&self.0, 144) } - } + pub fn f(&'a self) -> ::flatbuffers::Array<'a, i64, 2> { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + use ::flatbuffers::Follow; + unsafe { ::flatbuffers::Array::follow(&self.0, 144) } + } - pub fn set_f(&mut self, items: &[i64; 2]) { - // Safety: - // Created from a valid Table for this object - // Which contains a valid array in this slot - unsafe { ::flatbuffers::emplace_scalar_array(&mut self.0, 144, items) }; - } + pub fn set_f(&mut self, items: &[i64; 2]) { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + unsafe { ::flatbuffers::emplace_scalar_array(&mut self.0, 144, items) }; + } - pub fn unpack(&self) -> ArrayStructT { - ArrayStructT { - a: self.a(), - b: self.b().into(), - c: self.c(), - d: { let d = self.d(); ::flatbuffers::array_init(|i| d.get(i).unpack()) }, - e: self.e(), - f: self.f().into(), - } + pub fn unpack(&self) -> ArrayStructT { + ArrayStructT { + a: self.a(), + b: self.b().into(), + c: self.c(), + d: { let d = self.d(); ::flatbuffers::array_init(|i| d.get(i).unpack()) }, + e: self.e(), + f: self.f().into(), } + } } -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Default)] pub struct ArrayStructT { - pub a: f32, - pub b: [i32; 15], - pub c: i8, - pub d: [NestedStructT; 2], - pub e: i32, - pub f: [i64; 2], + pub a: f32, + pub b: [i32; 15], + pub c: i8, + pub d: [NestedStructT; 2], + pub e: i32, + pub f: [i64; 2], } -impl Default for ArrayStructT { - fn default() -> Self { - Self { - a: 0.0, - b: [0; 15], - c: 0, - d: ::flatbuffers::array_init(|_| Default::default()), - e: 0, - f: [0; 2], - } - } +impl ArrayStructT { + pub fn pack(&self) -> ArrayStruct { + ArrayStruct::new( + self.a, + &self.b, + self.c, + &::flatbuffers::array_init(|i| self.d[i].pack()), + self.e, + &self.f, + ) + } } -impl ArrayStructT { - pub fn pack(&self) -> ArrayStruct { - ArrayStruct::new( - self.a, - &self.b, - self.c, - &::flatbuffers::array_init(|i| self.d[i].pack()), - self.e, - &self.f, - ) - } -} diff --git a/tests/arrays_test/my_game/example/array_table_generated.rs b/tests/arrays_test/my_game/example/array_table_generated.rs index 525a755da..b0260f601 100644 --- a/tests/arrays_test/my_game/example/array_table_generated.rs +++ b/tests/arrays_test/my_game/example/array_table_generated.rs @@ -2,226 +2,208 @@ // @generated extern crate alloc; use super::*; - pub enum ArrayTableOffset {} - #[derive(Copy, Clone, PartialEq)] + pub struct ArrayTable<'a> { - pub _tab: ::flatbuffers::Table<'a>, + pub _tab: ::flatbuffers::Table<'a>, } impl<'a> ::flatbuffers::Follow<'a> for ArrayTable<'a> { - type Inner = ArrayTable<'a>; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } - } + type Inner = ArrayTable<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } + } } impl<'a> ArrayTable<'a> { - pub const VT_A: ::flatbuffers::VOffsetT = 4; + pub const VT_A: ::flatbuffers::VOffsetT = 4; - pub const fn get_fully_qualified_name() -> &'static str { - "MyGame.Example.ArrayTable" - } + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Example.ArrayTable" + } - #[inline] - pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { - ArrayTable { _tab: table } - } + #[inline] + pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { + ArrayTable { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args ArrayTableArgs<'args> + ) -> ::flatbuffers::WIPOffset> { + let mut builder = ArrayTableBuilder::new(_fbb); + if let Some(x) = args.a { builder.add_a(x); } + builder.finish() + } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args ArrayTableArgs<'args> - ) -> ::flatbuffers::WIPOffset> { - let mut builder = ArrayTableBuilder::new(_fbb); - if let Some(x) = args.a { builder.add_a(x); } - builder.finish() + pub fn unpack(&self) -> ArrayTableT { + let a = self.a().map(|x| { + x.unpack() + }); + ArrayTableT { + a, } + } - pub fn unpack(&self) -> ArrayTableT { - let a = self.a().map(|x| { - x.unpack() - }); - ArrayTableT { - a, - } - } - - #[inline] - pub fn a(&self) -> Option<&'a ArrayStruct> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(ArrayTable::VT_A, None)} - } + #[inline] + pub fn a(&self) -> Option<&'a ArrayStruct> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ArrayTable::VT_A, None)} + } } impl ::flatbuffers::Verifiable for ArrayTable<'_> { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.visit_table(pos)? - .visit_field::("a", Self::VT_A, false)? - .finish(); - Ok(()) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.visit_table(pos)? + .visit_field::("a", Self::VT_A, false)? + .finish(); + Ok(()) + } } - pub struct ArrayTableArgs<'a> { pub a: Option<&'a ArrayStruct>, } - impl<'a> Default for ArrayTableArgs<'a> { - #[inline] - fn default() -> Self { - ArrayTableArgs { - a: None, - } + #[inline] + fn default() -> Self { + ArrayTableArgs { + a: None, } + } } pub struct ArrayTableBuilder<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> { - fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, + fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, + start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, } - impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> ArrayTableBuilder<'a, 'b, A> { - #[inline] - pub fn add_a(&mut self, a: &ArrayStruct) { - self.fbb_.push_slot_always::<&ArrayStruct>(ArrayTable::VT_A, a); - } - - #[inline] - pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> ArrayTableBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - ArrayTableBuilder { - fbb_: _fbb, - start_: start, - } - } - - #[inline] - pub fn finish(self) -> ::flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - ::flatbuffers::WIPOffset::new(o.value()) + #[inline] + pub fn add_a(&mut self, a: &ArrayStruct) { + self.fbb_.push_slot_always::<&ArrayStruct>(ArrayTable::VT_A, a); + } + #[inline] + pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> ArrayTableBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + ArrayTableBuilder { + fbb_: _fbb, + start_: start, } + } + #[inline] + pub fn finish(self) -> ::flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + ::flatbuffers::WIPOffset::new(o.value()) + } } impl ::core::fmt::Debug for ArrayTable<'_> { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - let mut ds = f.debug_struct("ArrayTable"); - ds.field("a", &self.a()); - ds.finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + let mut ds = f.debug_struct("ArrayTable"); + ds.field("a", &self.a()); + ds.finish() + } } - #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub struct ArrayTableT { - pub a: Option, + pub a: Option, } - impl Default for ArrayTableT { - fn default() -> Self { - Self { - a: None, - } + fn default() -> Self { + Self { + a: None, } + } } - impl ArrayTableT { - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( - &self, - _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> - ) -> ::flatbuffers::WIPOffset> { - let a_tmp = self.a.as_ref().map(|x| x.pack()); - let a = a_tmp.as_ref(); - ArrayTable::create(_fbb, &ArrayTableArgs{ - a, - }) - } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> + ) -> ::flatbuffers::WIPOffset> { + let a_tmp = self.a.as_ref().map(|x| x.pack()); + let a = a_tmp.as_ref(); + ArrayTable::create(_fbb, &ArrayTableArgs{ + a, + }) + } } - +#[inline] /// Verifies that a buffer of bytes contains a `ArrayTable` /// and returns it. /// Note that verification is still experimental and may not /// catch every error, or be maximally performant. For the /// previous, unchecked, behavior use /// `root_as_array_table_unchecked`. -#[inline] pub fn root_as_array_table(buf: &[u8]) -> Result, ::flatbuffers::InvalidFlatbuffer> { - ::flatbuffers::root::(buf) + ::flatbuffers::root::(buf) } - +#[inline] /// Verifies that a buffer of bytes contains a size prefixed /// `ArrayTable` and returns it. /// Note that verification is still experimental and may not /// catch every error, or be maximally performant. For the /// previous, unchecked, behavior use /// `size_prefixed_root_as_array_table_unchecked`. -#[inline] pub fn size_prefixed_root_as_array_table(buf: &[u8]) -> Result, ::flatbuffers::InvalidFlatbuffer> { - ::flatbuffers::size_prefixed_root::(buf) + ::flatbuffers::size_prefixed_root::(buf) } - +#[inline] /// Verifies, with the given options, that a buffer of bytes /// contains a `ArrayTable` and returns it. /// Note that verification is still experimental and may not /// catch every error, or be maximally performant. For the /// previous, unchecked, behavior use /// `root_as_array_table_unchecked`. -#[inline] pub fn root_as_array_table_with_opts<'b, 'o>( - opts: &'o ::flatbuffers::VerifierOptions, - buf: &'b [u8], + opts: &'o ::flatbuffers::VerifierOptions, + buf: &'b [u8], ) -> Result, ::flatbuffers::InvalidFlatbuffer> { - ::flatbuffers::root_with_opts::>(opts, buf) + ::flatbuffers::root_with_opts::>(opts, buf) } - +#[inline] /// Verifies, with the given verifier options, that a buffer of /// bytes contains a size prefixed `ArrayTable` and returns /// it. Note that verification is still experimental and may not /// catch every error, or be maximally performant. For the /// previous, unchecked, behavior use /// `root_as_array_table_unchecked`. -#[inline] pub fn size_prefixed_root_as_array_table_with_opts<'b, 'o>( - opts: &'o ::flatbuffers::VerifierOptions, - buf: &'b [u8], + opts: &'o ::flatbuffers::VerifierOptions, + buf: &'b [u8], ) -> Result, ::flatbuffers::InvalidFlatbuffer> { - ::flatbuffers::size_prefixed_root_with_opts::>(opts, buf) + ::flatbuffers::size_prefixed_root_with_opts::>(opts, buf) } - +#[inline] /// Assumes, without verification, that a buffer of bytes contains a ArrayTable and returns it. /// # Safety /// Callers must trust the given bytes do indeed contain a valid `ArrayTable`. -#[inline] pub unsafe fn root_as_array_table_unchecked(buf: &[u8]) -> ArrayTable<'_> { - unsafe { ::flatbuffers::root_unchecked::(buf) } + unsafe { ::flatbuffers::root_unchecked::(buf) } } - +#[inline] /// Assumes, without verification, that a buffer of bytes contains a size prefixed ArrayTable and returns it. /// # Safety /// Callers must trust the given bytes do indeed contain a valid size prefixed `ArrayTable`. -#[inline] pub unsafe fn size_prefixed_root_as_array_table_unchecked(buf: &[u8]) -> ArrayTable<'_> { - unsafe { ::flatbuffers::size_prefixed_root_unchecked::(buf) } + unsafe { ::flatbuffers::size_prefixed_root_unchecked::(buf) } } - pub const ARRAY_TABLE_IDENTIFIER: &str = "ARRT"; #[inline] pub fn array_table_buffer_has_identifier(buf: &[u8]) -> bool { - ::flatbuffers::buffer_has_identifier(buf, ARRAY_TABLE_IDENTIFIER, false) + ::flatbuffers::buffer_has_identifier(buf, ARRAY_TABLE_IDENTIFIER, false) } #[inline] pub fn array_table_size_prefixed_buffer_has_identifier(buf: &[u8]) -> bool { - ::flatbuffers::buffer_has_identifier(buf, ARRAY_TABLE_IDENTIFIER, true) + ::flatbuffers::buffer_has_identifier(buf, ARRAY_TABLE_IDENTIFIER, true) } pub const ARRAY_TABLE_EXTENSION: &str = "mon"; @@ -229,15 +211,11 @@ pub const ARRAY_TABLE_EXTENSION: &str = "mon"; #[inline] pub fn finish_array_table_buffer<'a, 'b, A: ::flatbuffers::Allocator + 'a>( fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - root: ::flatbuffers::WIPOffset> -) { - fbb.finish(root, Some(ARRAY_TABLE_IDENTIFIER)); + root: ::flatbuffers::WIPOffset>) { + fbb.finish(root, Some(ARRAY_TABLE_IDENTIFIER)); } #[inline] -pub fn finish_size_prefixed_array_table_buffer<'a, 'b, A: ::flatbuffers::Allocator + 'a>( - fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - root: ::flatbuffers::WIPOffset> -) { - fbb.finish_size_prefixed(root, Some(ARRAY_TABLE_IDENTIFIER)); +pub fn finish_size_prefixed_array_table_buffer<'a, 'b, A: ::flatbuffers::Allocator + 'a>(fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, root: ::flatbuffers::WIPOffset>) { + fbb.finish_size_prefixed(root, Some(ARRAY_TABLE_IDENTIFIER)); } diff --git a/tests/arrays_test/my_game/example/nested_struct_generated.rs b/tests/arrays_test/my_game/example/nested_struct_generated.rs index bf81a3cc3..db538c211 100644 --- a/tests/arrays_test/my_game/example/nested_struct_generated.rs +++ b/tests/arrays_test/my_game/example/nested_struct_generated.rs @@ -2,58 +2,48 @@ // @generated extern crate alloc; use super::*; - // struct NestedStruct, aligned to 8 #[repr(transparent)] #[derive(Clone, Copy, PartialEq)] pub struct NestedStruct(pub [u8; 32]); - -impl Default for NestedStruct { - fn default() -> Self { - Self([0; 32]) - } +impl Default for NestedStruct { + fn default() -> Self { + Self([0; 32]) + } } - impl ::core::fmt::Debug for NestedStruct { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - f.debug_struct("NestedStruct") - .field("a", &self.a()) - .field("b", &self.b()) - .field("c", &self.c()) - .field("d", &self.d()) - .finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + f.debug_struct("NestedStruct") + .field("a", &self.a()) + .field("b", &self.b()) + .field("c", &self.c()) + .field("d", &self.d()) + .finish() + } } impl ::flatbuffers::SimpleToVerifyInSlice for NestedStruct {} - impl<'a> ::flatbuffers::Follow<'a> for NestedStruct { - type Inner = &'a NestedStruct; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - unsafe { <&'a NestedStruct>::follow(buf, loc) } - } + type Inner = &'a NestedStruct; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { <&'a NestedStruct>::follow(buf, loc) } + } } - impl<'a> ::flatbuffers::Follow<'a> for &'a NestedStruct { - type Inner = &'a NestedStruct; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - unsafe { ::flatbuffers::follow_cast_ref::(buf, loc) } - } + type Inner = &'a NestedStruct; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { ::flatbuffers::follow_cast_ref::(buf, loc) } + } } - impl<'b> ::flatbuffers::Push for NestedStruct { type Output = NestedStruct; - #[inline] unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { let src = unsafe { ::core::slice::from_raw_parts(self as *const NestedStruct as *const u8, ::size()) }; dst.copy_from_slice(src); } - #[inline] fn alignment() -> ::flatbuffers::PushAlignment { ::flatbuffers::PushAlignment::new(8) @@ -61,149 +51,139 @@ impl<'b> ::flatbuffers::Push for NestedStruct { } impl<'a> ::flatbuffers::Verifiable for NestedStruct { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.in_buffer::(pos) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.in_buffer::(pos) + } } impl<'a> NestedStruct { - #[allow(clippy::too_many_arguments)] - pub fn new( - a: &[i32; 2], - b: TestEnum, - c: &[TestEnum; 2], - d: &[i64; 2], - ) -> Self { - let mut s = Self([0; 32]); - s.set_a(a); - s.set_b(b); - s.set_c(c); - s.set_d(d); - s - } + #[allow(clippy::too_many_arguments)] + pub fn new( + a: &[i32; 2], + b: TestEnum, + c: &[TestEnum; 2], + d: &[i64; 2], + ) -> Self { + let mut s = Self([0; 32]); + s.set_a(a); + s.set_b(b); + s.set_c(c); + s.set_d(d); + s + } - pub const fn get_fully_qualified_name() -> &'static str { - "MyGame.Example.NestedStruct" - } + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Example.NestedStruct" + } - pub fn a(&'a self) -> ::flatbuffers::Array<'a, i32, 2> { - // Safety: - // Created from a valid Table for this object - // Which contains a valid array in this slot - use ::flatbuffers::Follow; - unsafe { ::flatbuffers::Array::follow(&self.0, 0) } - } + pub fn a(&'a self) -> ::flatbuffers::Array<'a, i32, 2> { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + use ::flatbuffers::Follow; + unsafe { ::flatbuffers::Array::follow(&self.0, 0) } + } - pub fn set_a(&mut self, items: &[i32; 2]) { - // Safety: - // Created from a valid Table for this object - // Which contains a valid array in this slot - unsafe { ::flatbuffers::emplace_scalar_array(&mut self.0, 0, items) }; - } + pub fn set_a(&mut self, items: &[i32; 2]) { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + unsafe { ::flatbuffers::emplace_scalar_array(&mut self.0, 0, items) }; + } - pub fn b(&self) -> TestEnum { - let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - ::flatbuffers::EndianScalar::from_little_endian(unsafe { - ::core::ptr::copy_nonoverlapping( - self.0[8..].as_ptr(), - mem.as_mut_ptr() as *mut u8, - ::core::mem::size_of::<::Scalar>(), - ); - mem.assume_init() - }) - } + pub fn b(&self) -> TestEnum { + let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + ::flatbuffers::EndianScalar::from_little_endian(unsafe { + ::core::ptr::copy_nonoverlapping( + self.0[8..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + ::core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } - pub fn set_b(&mut self, x: TestEnum) { - let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - unsafe { - ::core::ptr::copy_nonoverlapping( - &x_le as *const _ as *const u8, - self.0[8..].as_mut_ptr(), - ::core::mem::size_of::<::Scalar>(), - ); - } + pub fn set_b(&mut self, x: TestEnum) { + let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + ::core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[8..].as_mut_ptr(), + ::core::mem::size_of::<::Scalar>(), + ); } + } - pub fn c(&'a self) -> ::flatbuffers::Array<'a, TestEnum, 2> { - // Safety: - // Created from a valid Table for this object - // Which contains a valid array in this slot - use ::flatbuffers::Follow; - unsafe { ::flatbuffers::Array::follow(&self.0, 9) } - } + pub fn c(&'a self) -> ::flatbuffers::Array<'a, TestEnum, 2> { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + use ::flatbuffers::Follow; + unsafe { ::flatbuffers::Array::follow(&self.0, 9) } + } - pub fn set_c(&mut self, x: &[TestEnum; 2]) { - // Safety: - // Created from a valid Table for this object - // Which contains a valid array in this slot - unsafe { - ::core::ptr::copy( - x.as_ptr() as *const u8, - self.0.as_mut_ptr().add(9), - 2, - ); - } + pub fn set_c(&mut self, x: &[TestEnum; 2]) { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + unsafe { + ::core::ptr::copy( + x.as_ptr() as *const u8, + self.0.as_mut_ptr().add(9), + 2, + ); } + } - pub fn d(&'a self) -> ::flatbuffers::Array<'a, i64, 2> { - // Safety: - // Created from a valid Table for this object - // Which contains a valid array in this slot - use ::flatbuffers::Follow; - unsafe { ::flatbuffers::Array::follow(&self.0, 16) } - } + pub fn d(&'a self) -> ::flatbuffers::Array<'a, i64, 2> { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + use ::flatbuffers::Follow; + unsafe { ::flatbuffers::Array::follow(&self.0, 16) } + } - pub fn set_d(&mut self, items: &[i64; 2]) { - // Safety: - // Created from a valid Table for this object - // Which contains a valid array in this slot - unsafe { ::flatbuffers::emplace_scalar_array(&mut self.0, 16, items) }; - } + pub fn set_d(&mut self, items: &[i64; 2]) { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + unsafe { ::flatbuffers::emplace_scalar_array(&mut self.0, 16, items) }; + } - pub fn unpack(&self) -> NestedStructT { - NestedStructT { - a: self.a().into(), - b: self.b(), - c: self.c().into(), - d: self.d().into(), - } + pub fn unpack(&self) -> NestedStructT { + NestedStructT { + a: self.a().into(), + b: self.b(), + c: self.c().into(), + d: self.d().into(), } + } } -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Default)] pub struct NestedStructT { - pub a: [i32; 2], - pub b: TestEnum, - pub c: [TestEnum; 2], - pub d: [i64; 2], + pub a: [i32; 2], + pub b: TestEnum, + pub c: [TestEnum; 2], + pub d: [i64; 2], } -impl Default for NestedStructT { - fn default() -> Self { - Self { - a: [0; 2], - b: TestEnum::A, - c: ::flatbuffers::array_init(|_| Default::default()), - d: [0; 2], - } - } +impl NestedStructT { + pub fn pack(&self) -> NestedStruct { + NestedStruct::new( + &self.a, + self.b, + &self.c, + &self.d, + ) + } } -impl NestedStructT { - pub fn pack(&self) -> NestedStruct { - NestedStruct::new( - &self.a, - self.b, - &self.c, - &self.d, - ) - } -} diff --git a/tests/arrays_test/my_game/example/test_enum_generated.rs b/tests/arrays_test/my_game/example/test_enum_generated.rs index ff0f42683..572bdae70 100644 --- a/tests/arrays_test/my_game/example/test_enum_generated.rs +++ b/tests/arrays_test/my_game/example/test_enum_generated.rs @@ -2,73 +2,64 @@ // @generated extern crate alloc; use super::*; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] pub const ENUM_MIN_TEST_ENUM: i8 = 0; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] pub const ENUM_MAX_TEST_ENUM: i8 = 2; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] #[allow(non_camel_case_types)] pub const ENUM_VALUES_TEST_ENUM: [TestEnum; 3] = [ - TestEnum::A, - TestEnum::B, - TestEnum::C, + TestEnum::A, + TestEnum::B, + TestEnum::C, ]; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] #[repr(transparent)] pub struct TestEnum(pub i8); - #[allow(non_upper_case_globals)] impl TestEnum { - pub const A: Self = Self(0); - pub const B: Self = Self(1); - pub const C: Self = Self(2); + pub const A: Self = Self(0); + pub const B: Self = Self(1); + pub const C: Self = Self(2); - pub const ENUM_MIN: i8 = 0; - pub const ENUM_MAX: i8 = 2; - pub const ENUM_VALUES: &'static [Self] = &[ - Self::A, - Self::B, - Self::C, - ]; - - /// Returns the variant's name or "" if unknown. - pub fn variant_name(self) -> Option<&'static str> { - match self { - Self::A => Some("A"), - Self::B => Some("B"), - Self::C => Some("C"), - _ => None, - } + pub const ENUM_MIN: i8 = 0; + pub const ENUM_MAX: i8 = 2; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::A, + Self::B, + Self::C, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::A => Some("A"), + Self::B => Some("B"), + Self::C => Some("C"), + _ => None, } + } } - impl ::core::fmt::Debug for TestEnum { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - if let Some(name) = self.variant_name() { - f.write_str(name) - } else { - f.write_fmt(format_args!("", self.0)) - } + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) } + } } - impl<'a> ::flatbuffers::Follow<'a> for TestEnum { - type Inner = Self; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; - Self(b) - } + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; + Self(b) + } } impl ::flatbuffers::Push for TestEnum { type Output = TestEnum; - #[inline] unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { unsafe { ::flatbuffers::emplace_scalar::(dst, self.0) }; @@ -76,28 +67,26 @@ impl ::flatbuffers::Push for TestEnum { } impl ::flatbuffers::EndianScalar for TestEnum { - type Scalar = i8; - - #[inline] - fn to_little_endian(self) -> i8 { - self.0.to_le() - } - - #[inline] - #[allow(clippy::wrong_self_convention)] - fn from_little_endian(v: i8) -> Self { - let b = i8::from_le(v); - Self(b) - } + type Scalar = i8; + #[inline] + fn to_little_endian(self) -> i8 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: i8) -> Self { + let b = i8::from_le(v); + Self(b) + } } impl<'a> ::flatbuffers::Verifiable for TestEnum { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - i8::run_verifier(v, pos) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + i8::run_verifier(v, pos) + } } impl ::flatbuffers::SimpleToVerifyInSlice for TestEnum {} diff --git a/tests/bigfoot_ref_test.fbs b/tests/bigfoot_ref_test.fbs new file mode 100644 index 000000000..0b51b0b11 --- /dev/null +++ b/tests/bigfoot_ref_test.fbs @@ -0,0 +1,31 @@ +native_include "bigfoot_ref_test_impl.h"; + +namespace BigfootRefTestNS; + +// Stands in for Bigfoot's real UUID - a `native_type` struct so RefId has a +// distinct native/flat representation, matching the shape `bigfoot_ref` +// requires of a wrapper's payload field. +struct RefId (native_type: "Native::RefId") { + value: uint64; +} + +// The reference-wrapper template itself. `bigfoot_ref_wrapper` marks Ref as +// instantiable per referenced type via `bigfoot_ref` below. +struct Ref (bigfoot_ref_wrapper: "Native::Ref") { + uuid: RefId; +} + +// RefHolder references two distinct C++ types (Thing, OtherThing) that are +// *never defined anywhere in this test* - only ever forward-declared, by +// flatc itself, directly into the generated header. This is the property +// `bigfoot_ref` exists to provide: a reference field never requires the +// referenced type to be complete. It also references `Thing` twice (once as +// a plain field, once in a vector), exercising the include-guard dedup for +// two fields that resolve to the identical Pack/UnPack pair. +table RefHolder { + ref_a: Ref (native_inline, bigfoot_ref: "Native::Thing"); + ref_a_again: [Ref] (native_inline, bigfoot_ref: "Native::Thing"); + ref_b: Ref (native_inline, bigfoot_ref: "Native::OtherThing"); +} + +root_type RefHolder; diff --git a/tests/bigfoot_ref_test_impl.cpp b/tests/bigfoot_ref_test_impl.cpp new file mode 100644 index 000000000..bcb386bcb --- /dev/null +++ b/tests/bigfoot_ref_test_impl.cpp @@ -0,0 +1,47 @@ +#include "bigfoot_ref_test_impl.h" + +#include "bigfoot_ref_test_generated.h" +#include "test_assert.h" + +namespace flatbuffers { +BigfootRefTestNS::RefId Pack(const Native::RefId& obj) { + return BigfootRefTestNS::RefId(obj.value); +} + +const Native::RefId UnPack(const BigfootRefTestNS::RefId& obj) { + return Native::RefId(obj.value()); +} +} // namespace flatbuffers + +namespace flatbuffers { +namespace tests { + +// Exercises the --bigfoot_ref/--bigfoot_ref_wrapper flatc attributes (see +// tests/bigfoot_ref_test.fbs): a reference field never requires the +// referenced native type to be complete, and the generated header supplies +// its own forward declaration plus inline Pack/UnPack definitions, with no +// hand-written boilerplate anywhere in this file for `Thing`/`OtherThing`. +void BigfootRefTest() { + using BigfootRefTestNS::RefHolder; + using BigfootRefTestNS::RefHolderT; + + RefHolderT src; + src.ref_a = Native::Ref(Native::RefId(1)); + src.ref_a_again.push_back(Native::Ref(Native::RefId(2))); + src.ref_a_again.push_back(Native::Ref(Native::RefId(3))); + src.ref_b = Native::Ref(Native::RefId(4)); + + flatbuffers::FlatBufferBuilder fbb; + fbb.Finish(RefHolder::Pack(fbb, &src)); + + auto dst = BigfootRefTestNS::UnPackRefHolder(fbb.GetBufferPointer()); + + TEST_EQ(dst->ref_a.uuid.value, 1u); + TEST_EQ(dst->ref_a_again.size(), 2u); + TEST_EQ(dst->ref_a_again[0].uuid.value, 2u); + TEST_EQ(dst->ref_a_again[1].uuid.value, 3u); + TEST_EQ(dst->ref_b.uuid.value, 4u); +} + +} // namespace tests +} // namespace flatbuffers diff --git a/tests/bigfoot_ref_test_impl.h b/tests/bigfoot_ref_test_impl.h new file mode 100644 index 000000000..10d458745 --- /dev/null +++ b/tests/bigfoot_ref_test_impl.h @@ -0,0 +1,55 @@ +#ifndef BIGFOOT_REF_TEST_IMPL_H +#define BIGFOOT_REF_TEST_IMPL_H + +#include + +namespace Native { +// Stands in for Bigfoot's real UUID. +struct RefId { + uint64_t value; + + RefId() : value(0) {} + explicit RefId(uint64_t _value) : value(_value) {} + + bool operator==(const RefId& other) const { return value == other.value; } +}; + +// `Thing`/`OtherThing` are intentionally *never* defined anywhere in this +// test (see bigfoot_ref_test.fbs) - Ref must compile and round-trip +// without T ever being a complete type, exactly like Bigfoot's +// HardReference/SoftReference. Their forward declarations are emitted +// automatically by flatc (GenerateBigfootRefForwardDecls in +// idl_gen_cpp.cpp) directly into bigfoot_ref_test_generated.h - no manual +// forward declaration belongs here. + +// The reference-wrapper template `bigfoot_ref_wrapper`/`bigfoot_ref` (see +// idl_parser.cpp/idl_gen_cpp.cpp) instantiate per referenced type. Only +// needs a `GetUUID()` accessor and a constructor from RefId - never needs T +// complete. +template +struct Ref { + RefId uuid; + + Ref() : uuid() {} + Ref(const RefId& _uuid) : uuid(_uuid) {} + + const RefId& GetUUID() const { return uuid; } + + bool operator==(const Ref& other) const { return uuid == other.uuid; } +}; +} // namespace Native + +namespace BigfootRefTestNS { +struct RefId; +} // namespace BigfootRefTestNS + +namespace flatbuffers { +BigfootRefTestNS::RefId Pack(const Native::RefId& obj); +const Native::RefId UnPack(const BigfootRefTestNS::RefId& obj); + +namespace tests { +void BigfootRefTest(); +} // namespace tests +} // namespace flatbuffers + +#endif // BIGFOOT_REF_TEST_IMPL_H diff --git a/tests/cpp17/generated_cpp17/monster_test_generated.h b/tests/cpp17/generated_cpp17/monster_test_generated.h index 74e11c2ed..bb6efe1b9 100644 --- a/tests/cpp17/generated_cpp17/monster_test_generated.h +++ b/tests/cpp17/generated_cpp17/monster_test_generated.h @@ -3276,10 +3276,10 @@ inline ::flatbuffers::Offset Monster::Pack(::flatbuffers::FlatBufferBui auto _test = _o->test.Pack(_fbb); auto _test4 = _o->test4.size() ? _fbb.CreateVectorOfStructs(_o->test4) : 0; auto _testarrayofstring = _o->testarrayofstring.size() ? _fbb.CreateVectorOfStrings(_o->testarrayofstring) : 0; - auto _testarrayoftables = _o->testarrayoftables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->testarrayoftables.size(), [](size_t i, _VectorArgs *__va) { return MyGame::Example::CreateMonster(*__va->__fbb, __va->__o->testarrayoftables[i].get(), __va->__rehasher); }, &_va ) : 0; - auto _enemy = _o->enemy ? MyGame::Example::CreateMonster(_fbb, _o->enemy.get(), _rehasher) : 0; + auto _testarrayoftables = _o->testarrayoftables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->testarrayoftables.size(), [](size_t i, _VectorArgs *__va) { return CreateMonster(*__va->__fbb, __va->__o->testarrayoftables[i].get(), __va->__rehasher); }, &_va ) : 0; + auto _enemy = _o->enemy ? CreateMonster(_fbb, _o->enemy.get(), _rehasher) : 0; auto _testnestedflatbuffer = _o->testnestedflatbuffer.size() ? _fbb.CreateVector(_o->testnestedflatbuffer) : 0; - auto _testempty = _o->testempty ? MyGame::Example::CreateStat(_fbb, _o->testempty.get(), _rehasher) : 0; + auto _testempty = _o->testempty ? CreateStat(_fbb, _o->testempty.get(), _rehasher) : 0; auto _testbool = _o->testbool; auto _testhashs32_fnv1 = _o->testhashs32_fnv1; auto _testhashu32_fnv1 = _o->testhashu32_fnv1; @@ -3299,11 +3299,11 @@ inline ::flatbuffers::Offset Monster::Pack(::flatbuffers::FlatBufferBui auto _test5 = _o->test5.size() ? _fbb.CreateVectorOfStructs(_o->test5) : 0; auto _vector_of_longs = _o->vector_of_longs.size() ? _fbb.CreateVector(_o->vector_of_longs) : 0; auto _vector_of_doubles = _o->vector_of_doubles.size() ? _fbb.CreateVector(_o->vector_of_doubles) : 0; - auto _parent_namespace_test = _o->parent_namespace_test ? MyGame::CreateInParentNamespace(_fbb, _o->parent_namespace_test.get(), _rehasher) : 0; - auto _vector_of_referrables = _o->vector_of_referrables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->vector_of_referrables.size(), [](size_t i, _VectorArgs *__va) { return MyGame::Example::CreateReferrable(*__va->__fbb, __va->__o->vector_of_referrables[i].get(), __va->__rehasher); }, &_va ) : 0; + auto _parent_namespace_test = _o->parent_namespace_test ? CreateInParentNamespace(_fbb, _o->parent_namespace_test.get(), _rehasher) : 0; + auto _vector_of_referrables = _o->vector_of_referrables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->vector_of_referrables.size(), [](size_t i, _VectorArgs *__va) { return CreateReferrable(*__va->__fbb, __va->__o->vector_of_referrables[i].get(), __va->__rehasher); }, &_va ) : 0; auto _single_weak_reference = _rehasher ? static_cast((*_rehasher)(_o->single_weak_reference)) : 0; auto _vector_of_weak_references = _o->vector_of_weak_references.size() ? _fbb.CreateVector(_o->vector_of_weak_references.size(), [](size_t i, _VectorArgs *__va) { return __va->__rehasher ? static_cast((*__va->__rehasher)(__va->__o->vector_of_weak_references[i])) : 0; }, &_va ) : 0; - auto _vector_of_strong_referrables = _o->vector_of_strong_referrables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->vector_of_strong_referrables.size(), [](size_t i, _VectorArgs *__va) { return MyGame::Example::CreateReferrable(*__va->__fbb, __va->__o->vector_of_strong_referrables[i].get(), __va->__rehasher); }, &_va ) : 0; + auto _vector_of_strong_referrables = _o->vector_of_strong_referrables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->vector_of_strong_referrables.size(), [](size_t i, _VectorArgs *__va) { return CreateReferrable(*__va->__fbb, __va->__o->vector_of_strong_referrables[i].get(), __va->__rehasher); }, &_va ) : 0; auto _co_owning_reference = _rehasher ? static_cast((*_rehasher)(_o->co_owning_reference)) : 0; auto _vector_of_co_owning_references = _o->vector_of_co_owning_references.size() ? _fbb.CreateVector(_o->vector_of_co_owning_references.size(), [](size_t i, _VectorArgs *__va) { return __va->__rehasher ? static_cast((*__va->__rehasher)(__va->__o->vector_of_co_owning_references[i].get())) : 0; }, &_va ) : 0; auto _non_owning_reference = _rehasher ? static_cast((*_rehasher)(_o->non_owning_reference)) : 0; @@ -3315,7 +3315,7 @@ inline ::flatbuffers::Offset Monster::Pack(::flatbuffers::FlatBufferBui auto _vector_of_enums = _o->vector_of_enums.size() ? _fbb.CreateVector(_o->vector_of_enums) : 0; auto _signed_enum = _o->signed_enum; auto _testrequirednestedflatbuffer = _o->testrequirednestedflatbuffer.size() ? _fbb.CreateVector(_o->testrequirednestedflatbuffer) : 0; - auto _scalar_key_sorted_tables = _o->scalar_key_sorted_tables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->scalar_key_sorted_tables.size(), [](size_t i, _VectorArgs *__va) { return MyGame::Example::CreateStat(*__va->__fbb, __va->__o->scalar_key_sorted_tables[i].get(), __va->__rehasher); }, &_va ) : 0; + auto _scalar_key_sorted_tables = _o->scalar_key_sorted_tables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->scalar_key_sorted_tables.size(), [](size_t i, _VectorArgs *__va) { return CreateStat(*__va->__fbb, __va->__o->scalar_key_sorted_tables[i].get(), __va->__rehasher); }, &_va ) : 0; auto _native_inline = &_o->native_inline; auto _long_enum_non_enum_default = _o->long_enum_non_enum_default; auto _long_enum_normal_default = _o->long_enum_normal_default; diff --git a/tests/cpp_vector_type.fbs b/tests/cpp_vector_type.fbs new file mode 100644 index 000000000..4a5b502c3 --- /dev/null +++ b/tests/cpp_vector_type.fbs @@ -0,0 +1,29 @@ +// Schema used to test the --cpp-vector-type flatc option, which lets the +// generated Object API use a custom vector-like container (e.g. +// eastl::vector) instead of std::vector. See tests/test_vector_type.h for +// the stand-in container used by the test, and +// tests/cpp_vector_type_test.cpp for the test itself. + +namespace CppVectorTypeNS; + +enum CppVectorTypeColor : byte { Red = 0, Green, Blue } + +struct CppVectorTypeVec2 { + x: float; + y: float; +} + +table CppVectorTypeMonster { + id: int32; +} + +table CppVectorTypeTest { + ints: [int32]; + flags: [bool]; + colors: [CppVectorTypeColor]; + strings: [string]; + positions: [CppVectorTypeVec2]; + monsters: [CppVectorTypeMonster]; +} + +root_type CppVectorTypeTest; diff --git a/tests/cpp_vector_type_test.cpp b/tests/cpp_vector_type_test.cpp new file mode 100644 index 000000000..fd7bde616 --- /dev/null +++ b/tests/cpp_vector_type_test.cpp @@ -0,0 +1,143 @@ +#include "cpp_vector_type_test.h" + +#include "cpp_vector_type_generated.h" +#include "test_assert.h" + +namespace flatbuffers { +namespace tests { + +// Exercises the --cpp-vector-type flatc option (see +// tests/cpp_vector_type.fbs and tests/test_vector_type.h), which replaces +// std::vector with a custom vector-like container in the generated Object +// API. This covers every CreateVector*-family code path in Pack(): plain +// scalars, bool, enum-cast, vector-of-string, vector-of-struct and +// vector-of-table, then round-trips everything back through UnPackTo(). +void CppVectorTypeTest() { + using CppVectorTypeNS::CppVectorTypeColor_Blue; + using CppVectorTypeNS::CppVectorTypeColor_Green; + using CppVectorTypeNS::CppVectorTypeColor_Red; + using CppVectorTypeNS::CppVectorTypeMonsterT; + using CppVectorTypeNS::CppVectorTypeTest; + using CppVectorTypeNS::CppVectorTypeTestT; + using CppVectorTypeNS::CppVectorTypeVec2; + + // --------------------------------------- + // 1) Build a native object using the custom vector container for every + // vector field (scalars, bools, enums, strings, structs and tables). + // --------------------------------------- + CppVectorTypeTestT src; + src.ints.push_back(1); + src.ints.push_back(2); + src.ints.push_back(3); + + src.flags.push_back(true); + src.flags.push_back(false); + src.flags.push_back(true); + + src.colors.push_back(CppVectorTypeColor_Red); + src.colors.push_back(CppVectorTypeColor_Green); + src.colors.push_back(CppVectorTypeColor_Blue); + + src.strings.push_back("hello"); + src.strings.push_back("world"); + + src.positions.push_back(CppVectorTypeVec2(1.0f, 2.0f)); + src.positions.push_back(CppVectorTypeVec2(3.0f, 4.0f)); + + src.monsters.emplace_back(new CppVectorTypeMonsterT()); + src.monsters[0]->id = 111; + src.monsters.emplace_back(new CppVectorTypeMonsterT()); + src.monsters[1]->id = 222; + + // --------------------------------------- + // 2) Exercise the copy constructor / copy assignment operator generated + // for object-API types (--gen-compare requires these too), which rely + // on the custom vector's own copy ctor plus reserve()/emplace_back() + // for the vector-of-pointer (table) field. + // --------------------------------------- + CppVectorTypeTestT copy_of_src(src); + TEST_EQ(copy_of_src == src, true); + TEST_ASSERT(copy_of_src.monsters[0].get() != src.monsters[0].get()); + TEST_EQ(copy_of_src.monsters[0]->id, 111); + + // --------------------------------------- + // 3) Pack into a FlatBuffer and verify the wire-format contents. + // --------------------------------------- + flatbuffers::FlatBufferBuilder fbb; + fbb.Finish(CppVectorTypeTest::Pack(fbb, &src)); + + const auto* fb = + flatbuffers::GetRoot(fbb.GetBufferPointer()); + + TEST_EQ(fb->ints()->size(), 3u); + TEST_EQ(fb->ints()->Get(0), 1); + TEST_EQ(fb->ints()->Get(1), 2); + TEST_EQ(fb->ints()->Get(2), 3); + + TEST_EQ(fb->flags()->size(), 3u); + TEST_EQ(fb->flags()->Get(0) != 0, true); + TEST_EQ(fb->flags()->Get(1) != 0, false); + TEST_EQ(fb->flags()->Get(2) != 0, true); + + TEST_EQ(fb->colors()->size(), 3u); + TEST_EQ(fb->colors()->Get(0), CppVectorTypeColor_Red); + TEST_EQ(fb->colors()->Get(1), CppVectorTypeColor_Green); + TEST_EQ(fb->colors()->Get(2), CppVectorTypeColor_Blue); + + TEST_EQ(fb->strings()->size(), 2u); + TEST_EQ_STR(fb->strings()->Get(0)->c_str(), "hello"); + TEST_EQ_STR(fb->strings()->Get(1)->c_str(), "world"); + + TEST_EQ(fb->positions()->size(), 2u); + TEST_EQ(fb->positions()->Get(0)->x(), 1.0f); + TEST_EQ(fb->positions()->Get(0)->y(), 2.0f); + TEST_EQ(fb->positions()->Get(1)->x(), 3.0f); + TEST_EQ(fb->positions()->Get(1)->y(), 4.0f); + + TEST_EQ(fb->monsters()->size(), 2u); + TEST_EQ(fb->monsters()->Get(0)->id(), 111); + TEST_EQ(fb->monsters()->Get(1)->id(), 222); + + // --------------------------------------- + // 4) Unpack back into a fresh native object and verify a full round-trip + // through the custom vector container. + // --------------------------------------- + CppVectorTypeTestT dst; + fb->UnPackTo(&dst); + + TEST_EQ(dst == src, true); + + TEST_EQ(dst.ints.size(), 3u); + TEST_EQ(dst.ints[0], 1); + TEST_EQ(dst.ints[1], 2); + TEST_EQ(dst.ints[2], 3); + + TEST_EQ(dst.flags.size(), 3u); + TEST_EQ(dst.flags[0], true); + TEST_EQ(dst.flags[1], false); + TEST_EQ(dst.flags[2], true); + + TEST_EQ(dst.colors.size(), 3u); + TEST_EQ(dst.colors[0], CppVectorTypeColor_Red); + TEST_EQ(dst.colors[1], CppVectorTypeColor_Green); + TEST_EQ(dst.colors[2], CppVectorTypeColor_Blue); + + TEST_EQ(dst.strings.size(), 2u); + TEST_EQ_STR(dst.strings[0].c_str(), "hello"); + TEST_EQ_STR(dst.strings[1].c_str(), "world"); + + TEST_EQ(dst.positions.size(), 2u); + TEST_EQ(dst.positions[0].x(), 1.0f); + TEST_EQ(dst.positions[0].y(), 2.0f); + TEST_EQ(dst.positions[1].x(), 3.0f); + TEST_EQ(dst.positions[1].y(), 4.0f); + + TEST_EQ(dst.monsters.size(), 2u); + TEST_ASSERT(dst.monsters[0] != nullptr); + TEST_ASSERT(dst.monsters[1] != nullptr); + TEST_EQ(dst.monsters[0]->id, 111); + TEST_EQ(dst.monsters[1]->id, 222); +} + +} // namespace tests +} // namespace flatbuffers diff --git a/tests/cpp_vector_type_test.h b/tests/cpp_vector_type_test.h new file mode 100644 index 000000000..e5bcc8f06 --- /dev/null +++ b/tests/cpp_vector_type_test.h @@ -0,0 +1,12 @@ +#ifndef TESTS_CPP_VECTOR_TYPE_TEST_H +#define TESTS_CPP_VECTOR_TYPE_TEST_H + +namespace flatbuffers { +namespace tests { + +void CppVectorTypeTest(); + +} // namespace tests +} // namespace flatbuffers + +#endif // TESTS_CPP_VECTOR_TYPE_TEST_H diff --git a/tests/flexbuffers_test.cpp b/tests/flexbuffers_test.cpp index 6087a0aff..3c87f8c71 100644 --- a/tests/flexbuffers_test.cpp +++ b/tests/flexbuffers_test.cpp @@ -1,6 +1,5 @@ #include "flexbuffers_test.h" -#include #include #include "flatbuffers/flexbuffers.h" @@ -14,13 +13,6 @@ namespace tests { // Shortcuts for the infinity. static const auto infinity_d = std::numeric_limits::infinity(); -static bool IsAligned(const void* ptr, std::size_t alignment) { - void* p = const_cast(ptr); - std::size_t space = 2 * alignment; - void* q = std::align(alignment, alignment, p, space); - return q != nullptr && p == ptr && space == 2 * alignment; -} - void FlexBuffersTest() { flexbuffers::Builder slb(512, flexbuffers::BUILDER_FLAG_SHARE_KEYS_AND_STRINGS); @@ -37,10 +29,7 @@ void FlexBuffersTest() { slb.IndirectFloat(4.0f); auto i_f = slb.LastValue(); uint8_t blob[] = {77}; - uint32_t aligned_blob[] = {88, 99}; - slb.Blob(blob, sizeof blob); - slb.AlignedBlob(aligned_blob, sizeof aligned_blob, - flexbuffers::BIT_WIDTH_32); + slb.Blob(blob, 1); slb += false; slb.ReuseValue(i_f); }); @@ -73,7 +62,7 @@ void FlexBuffersTest() { auto map = flexbuffers::GetRoot(slb.GetBuffer()).AsMap(); TEST_EQ(map.size(), 7); auto vec = map["vec"].AsVector(); - TEST_EQ(vec.size(), 7); + TEST_EQ(vec.size(), 6); TEST_EQ(vec[0].AsInt64(), -100); TEST_EQ_STR(vec[1].AsString().c_str(), "Fred"); TEST_EQ(vec[1].AsInt64(), 0); // Number parsing failed. @@ -91,15 +80,9 @@ void FlexBuffersTest() { auto blob = vec[3].AsBlob(); TEST_EQ(blob.size(), 1); TEST_EQ(blob.data()[0], 77); - TEST_EQ(vec[4].IsBlob(), true); - auto aligned_blob = vec[4].AsBlob(); - TEST_EQ(aligned_blob.size(), 8); - TEST_EQ(reinterpret_cast(aligned_blob.data())[0], 88); - TEST_EQ(reinterpret_cast(aligned_blob.data())[1], 99); - TEST_EQ(IsAligned(aligned_blob.data(), 4), true); - TEST_EQ(vec[5].IsBool(), true); // Check if type is a bool - TEST_EQ(vec[5].AsBool(), false); // Check if value is false - TEST_EQ(vec[6].AsDouble(), 4.0); // This is shared with vec[2] ! + TEST_EQ(vec[4].IsBool(), true); // Check if type is a bool + TEST_EQ(vec[4].AsBool(), false); // Check if value is false + TEST_EQ(vec[5].AsDouble(), 4.0); // This is shared with vec[2] ! auto tvec = map["bar"].AsTypedVector(); TEST_EQ(tvec.size(), 3); TEST_EQ(tvec[2].AsInt8(), 3); @@ -124,9 +107,9 @@ void FlexBuffersTest() { TEST_EQ(vec[2].MutateFloat(2.0f), true); TEST_EQ(vec[2].AsFloat(), 2.0f); TEST_EQ(vec[2].MutateFloat(3.14159), false); // Double does not fit in float. - TEST_EQ(vec[5].AsBool(), false); // Is false before change - TEST_EQ(vec[5].MutateBool(true), true); // Can change a bool - TEST_EQ(vec[5].AsBool(), true); // Changed bool is now true + TEST_EQ(vec[4].AsBool(), false); // Is false before change + TEST_EQ(vec[4].MutateBool(true), true); // Can change a bool + TEST_EQ(vec[4].AsBool(), true); // Changed bool is now true // Parse from JSON: flatbuffers::Parser parser; diff --git a/tests/include_test1/mod.rs b/tests/include_test1/mod.rs index a69094e07..ca4894dc3 100644 --- a/tests/include_test1/mod.rs +++ b/tests/include_test1/mod.rs @@ -1,16 +1,16 @@ // Automatically generated by the Flatbuffers compiler. Do not modify. // @generated pub mod my_game { + use super::*; + pub mod other_name_space { use super::*; - pub mod other_name_space { - use super::*; - mod from_include_generated; - pub use self::from_include_generated::*; - mod unused_generated; - pub use self::unused_generated::*; - mod table_b_generated; - pub use self::table_b_generated::*; - } // other_name_space + mod from_include_generated; + pub use self::from_include_generated::*; + mod unused_generated; + pub use self::unused_generated::*; + mod table_b_generated; + pub use self::table_b_generated::*; + } // other_name_space } // my_game mod table_a_generated; pub use self::table_a_generated::*; diff --git a/tests/include_test1/my_game/other_name_space/from_include_generated.rs b/tests/include_test1/my_game/other_name_space/from_include_generated.rs index ada294725..5eb9adc5e 100644 --- a/tests/include_test1/my_game/other_name_space/from_include_generated.rs +++ b/tests/include_test1/my_game/other_name_space/from_include_generated.rs @@ -2,65 +2,56 @@ // @generated extern crate alloc; use super::*; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] pub const ENUM_MIN_FROM_INCLUDE: i64 = 0; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] pub const ENUM_MAX_FROM_INCLUDE: i64 = 0; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] #[allow(non_camel_case_types)] pub const ENUM_VALUES_FROM_INCLUDE: [FromInclude; 1] = [ - FromInclude::IncludeVal, + FromInclude::IncludeVal, ]; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] #[repr(transparent)] pub struct FromInclude(pub i64); - #[allow(non_upper_case_globals)] impl FromInclude { - pub const IncludeVal: Self = Self(0); + pub const IncludeVal: Self = Self(0); - pub const ENUM_MIN: i64 = 0; - pub const ENUM_MAX: i64 = 0; - pub const ENUM_VALUES: &'static [Self] = &[ - Self::IncludeVal, - ]; - - /// Returns the variant's name or "" if unknown. - pub fn variant_name(self) -> Option<&'static str> { - match self { - Self::IncludeVal => Some("IncludeVal"), - _ => None, - } + pub const ENUM_MIN: i64 = 0; + pub const ENUM_MAX: i64 = 0; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::IncludeVal, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::IncludeVal => Some("IncludeVal"), + _ => None, } + } } - impl ::core::fmt::Debug for FromInclude { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - if let Some(name) = self.variant_name() { - f.write_str(name) - } else { - f.write_fmt(format_args!("", self.0)) - } + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) } + } } - impl<'a> ::flatbuffers::Follow<'a> for FromInclude { - type Inner = Self; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; - Self(b) - } + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; + Self(b) + } } impl ::flatbuffers::Push for FromInclude { type Output = FromInclude; - #[inline] unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { unsafe { ::flatbuffers::emplace_scalar::(dst, self.0) }; @@ -68,28 +59,26 @@ impl ::flatbuffers::Push for FromInclude { } impl ::flatbuffers::EndianScalar for FromInclude { - type Scalar = i64; - - #[inline] - fn to_little_endian(self) -> i64 { - self.0.to_le() - } - - #[inline] - #[allow(clippy::wrong_self_convention)] - fn from_little_endian(v: i64) -> Self { - let b = i64::from_le(v); - Self(b) - } + type Scalar = i64; + #[inline] + fn to_little_endian(self) -> i64 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: i64) -> Self { + let b = i64::from_le(v); + Self(b) + } } impl<'a> ::flatbuffers::Verifiable for FromInclude { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - i64::run_verifier(v, pos) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + i64::run_verifier(v, pos) + } } impl ::flatbuffers::SimpleToVerifyInSlice for FromInclude {} diff --git a/tests/include_test1/my_game/other_name_space/table_b_generated.rs b/tests/include_test1/my_game/other_name_space/table_b_generated.rs index 5434e448a..19a3e66ba 100644 --- a/tests/include_test1/my_game/other_name_space/table_b_generated.rs +++ b/tests/include_test1/my_game/other_name_space/table_b_generated.rs @@ -2,147 +2,136 @@ // @generated extern crate alloc; use super::*; - pub enum TableBOffset {} - #[derive(Copy, Clone, PartialEq)] + pub struct TableB<'a> { - pub _tab: ::flatbuffers::Table<'a>, + pub _tab: ::flatbuffers::Table<'a>, } impl<'a> ::flatbuffers::Follow<'a> for TableB<'a> { - type Inner = TableB<'a>; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } - } + type Inner = TableB<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } + } } impl<'a> TableB<'a> { - pub const VT_A: ::flatbuffers::VOffsetT = 4; + pub const VT_A: ::flatbuffers::VOffsetT = 4; - pub const fn get_fully_qualified_name() -> &'static str { - "MyGame.OtherNameSpace.TableB" - } + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.OtherNameSpace.TableB" + } - #[inline] - pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { - TableB { _tab: table } - } + #[inline] + pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { + TableB { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args TableBArgs<'args> + ) -> ::flatbuffers::WIPOffset> { + let mut builder = TableBBuilder::new(_fbb); + if let Some(x) = args.a { builder.add_a(x); } + builder.finish() + } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args TableBArgs<'args> - ) -> ::flatbuffers::WIPOffset> { - let mut builder = TableBBuilder::new(_fbb); - if let Some(x) = args.a { builder.add_a(x); } - builder.finish() + pub fn unpack(&self) -> TableBT { + let a = self.a().map(|x| { + alloc::boxed::Box::new(x.unpack()) + }); + TableBT { + a, } + } - pub fn unpack(&self) -> TableBT { - let a = self.a().map(|x| { - alloc::boxed::Box::new(x.unpack()) - }); - TableBT { - a, - } - } - - #[inline] - pub fn a(&self) -> Option> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset>(TableB::VT_A, None)} - } + #[inline] + pub fn a(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset>(TableB::VT_A, None)} + } } impl ::flatbuffers::Verifiable for TableB<'_> { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.visit_table(pos)? - .visit_field::<::flatbuffers::ForwardsUOffset>("a", Self::VT_A, false)? - .finish(); - Ok(()) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.visit_table(pos)? + .visit_field::<::flatbuffers::ForwardsUOffset>("a", Self::VT_A, false)? + .finish(); + Ok(()) + } } - pub struct TableBArgs<'a> { pub a: Option<::flatbuffers::WIPOffset>>, } - impl<'a> Default for TableBArgs<'a> { - #[inline] - fn default() -> Self { - TableBArgs { - a: None, - } + #[inline] + fn default() -> Self { + TableBArgs { + a: None, } + } } pub struct TableBBuilder<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> { - fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, + fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, + start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, } - impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> TableBBuilder<'a, 'b, A> { - #[inline] - pub fn add_a(&mut self, a: ::flatbuffers::WIPOffset>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset>(TableB::VT_A, a); - } - - #[inline] - pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> TableBBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - TableBBuilder { - fbb_: _fbb, - start_: start, - } - } - - #[inline] - pub fn finish(self) -> ::flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - ::flatbuffers::WIPOffset::new(o.value()) + #[inline] + pub fn add_a(&mut self, a: ::flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset>(TableB::VT_A, a); + } + #[inline] + pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> TableBBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + TableBBuilder { + fbb_: _fbb, + start_: start, } + } + #[inline] + pub fn finish(self) -> ::flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + ::flatbuffers::WIPOffset::new(o.value()) + } } impl ::core::fmt::Debug for TableB<'_> { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - let mut ds = f.debug_struct("TableB"); - ds.field("a", &self.a()); - ds.finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + let mut ds = f.debug_struct("TableB"); + ds.field("a", &self.a()); + ds.finish() + } } - #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub struct TableBT { - pub a: Option>, + pub a: Option>, } - impl Default for TableBT { - fn default() -> Self { - Self { - a: None, - } + fn default() -> Self { + Self { + a: None, } + } } - impl TableBT { - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( - &self, - _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> - ) -> ::flatbuffers::WIPOffset> { - let a = self.a.as_ref().map(|x|{ - x.pack(_fbb) - }); - TableB::create(_fbb, &TableBArgs{ - a, - }) - } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> + ) -> ::flatbuffers::WIPOffset> { + let a = self.a.as_ref().map(|x|{ + x.pack(_fbb) + }); + TableB::create(_fbb, &TableBArgs{ + a, + }) + } } diff --git a/tests/include_test1/my_game/other_name_space/unused_generated.rs b/tests/include_test1/my_game/other_name_space/unused_generated.rs index d19375f17..b90fb8924 100644 --- a/tests/include_test1/my_game/other_name_space/unused_generated.rs +++ b/tests/include_test1/my_game/other_name_space/unused_generated.rs @@ -2,55 +2,45 @@ // @generated extern crate alloc; use super::*; - // struct Unused, aligned to 4 #[repr(transparent)] #[derive(Clone, Copy, PartialEq)] pub struct Unused(pub [u8; 4]); - -impl Default for Unused { - fn default() -> Self { - Self([0; 4]) - } +impl Default for Unused { + fn default() -> Self { + Self([0; 4]) + } } - impl ::core::fmt::Debug for Unused { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - f.debug_struct("Unused") - .field("a", &self.a()) - .finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + f.debug_struct("Unused") + .field("a", &self.a()) + .finish() + } } impl ::flatbuffers::SimpleToVerifyInSlice for Unused {} - impl<'a> ::flatbuffers::Follow<'a> for Unused { - type Inner = &'a Unused; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - unsafe { <&'a Unused>::follow(buf, loc) } - } + type Inner = &'a Unused; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { <&'a Unused>::follow(buf, loc) } + } } - impl<'a> ::flatbuffers::Follow<'a> for &'a Unused { - type Inner = &'a Unused; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - unsafe { ::flatbuffers::follow_cast_ref::(buf, loc) } - } + type Inner = &'a Unused; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { ::flatbuffers::follow_cast_ref::(buf, loc) } + } } - impl<'b> ::flatbuffers::Push for Unused { type Output = Unused; - #[inline] unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { let src = unsafe { ::core::slice::from_raw_parts(self as *const Unused as *const u8, ::size()) }; dst.copy_from_slice(src); } - #[inline] fn alignment() -> ::flatbuffers::PushAlignment { ::flatbuffers::PushAlignment::new(4) @@ -58,80 +48,73 @@ impl<'b> ::flatbuffers::Push for Unused { } impl<'a> ::flatbuffers::Verifiable for Unused { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.in_buffer::(pos) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.in_buffer::(pos) + } } impl<'a> Unused { - #[allow(clippy::too_many_arguments)] - pub fn new( - a: i32, - ) -> Self { - let mut s = Self([0; 4]); - s.set_a(a); - s - } + #[allow(clippy::too_many_arguments)] + pub fn new( + a: i32, + ) -> Self { + let mut s = Self([0; 4]); + s.set_a(a); + s + } - pub const fn get_fully_qualified_name() -> &'static str { - "MyGame.OtherNameSpace.Unused" - } + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.OtherNameSpace.Unused" + } - pub fn a(&self) -> i32 { - let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - ::flatbuffers::EndianScalar::from_little_endian(unsafe { - ::core::ptr::copy_nonoverlapping( - self.0[0..].as_ptr(), - mem.as_mut_ptr() as *mut u8, - ::core::mem::size_of::<::Scalar>(), - ); - mem.assume_init() - }) - } + pub fn a(&self) -> i32 { + let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + ::flatbuffers::EndianScalar::from_little_endian(unsafe { + ::core::ptr::copy_nonoverlapping( + self.0[0..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + ::core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } - pub fn set_a(&mut self, x: i32) { - let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - unsafe { - ::core::ptr::copy_nonoverlapping( - &x_le as *const _ as *const u8, - self.0[0..].as_mut_ptr(), - ::core::mem::size_of::<::Scalar>(), - ); - } + pub fn set_a(&mut self, x: i32) { + let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + ::core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[0..].as_mut_ptr(), + ::core::mem::size_of::<::Scalar>(), + ); } + } - pub fn unpack(&self) -> UnusedT { - UnusedT { - a: self.a(), - } + pub fn unpack(&self) -> UnusedT { + UnusedT { + a: self.a(), } + } } -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Default)] pub struct UnusedT { - pub a: i32, + pub a: i32, } -impl Default for UnusedT { - fn default() -> Self { - Self { - a: 0, - } - } +impl UnusedT { + pub fn pack(&self) -> Unused { + Unused::new( + self.a, + ) + } } -impl UnusedT { - pub fn pack(&self) -> Unused { - Unused::new( - self.a, - ) - } -} diff --git a/tests/include_test1/table_a_generated.rs b/tests/include_test1/table_a_generated.rs index 467c514a1..ca29250dc 100644 --- a/tests/include_test1/table_a_generated.rs +++ b/tests/include_test1/table_a_generated.rs @@ -2,147 +2,136 @@ // @generated extern crate alloc; use super::*; - pub enum TableAOffset {} - #[derive(Copy, Clone, PartialEq)] + pub struct TableA<'a> { - pub _tab: ::flatbuffers::Table<'a>, + pub _tab: ::flatbuffers::Table<'a>, } impl<'a> ::flatbuffers::Follow<'a> for TableA<'a> { - type Inner = TableA<'a>; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } - } + type Inner = TableA<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } + } } impl<'a> TableA<'a> { - pub const VT_B: ::flatbuffers::VOffsetT = 4; + pub const VT_B: ::flatbuffers::VOffsetT = 4; - pub const fn get_fully_qualified_name() -> &'static str { - "TableA" - } + pub const fn get_fully_qualified_name() -> &'static str { + "TableA" + } - #[inline] - pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { - TableA { _tab: table } - } + #[inline] + pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { + TableA { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args TableAArgs<'args> + ) -> ::flatbuffers::WIPOffset> { + let mut builder = TableABuilder::new(_fbb); + if let Some(x) = args.b { builder.add_b(x); } + builder.finish() + } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args TableAArgs<'args> - ) -> ::flatbuffers::WIPOffset> { - let mut builder = TableABuilder::new(_fbb); - if let Some(x) = args.b { builder.add_b(x); } - builder.finish() + pub fn unpack(&self) -> TableAT { + let b = self.b().map(|x| { + alloc::boxed::Box::new(x.unpack()) + }); + TableAT { + b, } + } - pub fn unpack(&self) -> TableAT { - let b = self.b().map(|x| { - alloc::boxed::Box::new(x.unpack()) - }); - TableAT { - b, - } - } - - #[inline] - pub fn b(&self) -> Option> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset>(TableA::VT_B, None)} - } + #[inline] + pub fn b(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset>(TableA::VT_B, None)} + } } impl ::flatbuffers::Verifiable for TableA<'_> { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.visit_table(pos)? - .visit_field::<::flatbuffers::ForwardsUOffset>("b", Self::VT_B, false)? - .finish(); - Ok(()) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.visit_table(pos)? + .visit_field::<::flatbuffers::ForwardsUOffset>("b", Self::VT_B, false)? + .finish(); + Ok(()) + } } - pub struct TableAArgs<'a> { pub b: Option<::flatbuffers::WIPOffset>>, } - impl<'a> Default for TableAArgs<'a> { - #[inline] - fn default() -> Self { - TableAArgs { - b: None, - } + #[inline] + fn default() -> Self { + TableAArgs { + b: None, } + } } pub struct TableABuilder<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> { - fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, + fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, + start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, } - impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> TableABuilder<'a, 'b, A> { - #[inline] - pub fn add_b(&mut self, b: ::flatbuffers::WIPOffset>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset>(TableA::VT_B, b); - } - - #[inline] - pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> TableABuilder<'a, 'b, A> { - let start = _fbb.start_table(); - TableABuilder { - fbb_: _fbb, - start_: start, - } - } - - #[inline] - pub fn finish(self) -> ::flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - ::flatbuffers::WIPOffset::new(o.value()) + #[inline] + pub fn add_b(&mut self, b: ::flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset>(TableA::VT_B, b); + } + #[inline] + pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> TableABuilder<'a, 'b, A> { + let start = _fbb.start_table(); + TableABuilder { + fbb_: _fbb, + start_: start, } + } + #[inline] + pub fn finish(self) -> ::flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + ::flatbuffers::WIPOffset::new(o.value()) + } } impl ::core::fmt::Debug for TableA<'_> { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - let mut ds = f.debug_struct("TableA"); - ds.field("b", &self.b()); - ds.finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + let mut ds = f.debug_struct("TableA"); + ds.field("b", &self.b()); + ds.finish() + } } - #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub struct TableAT { - pub b: Option>, + pub b: Option>, } - impl Default for TableAT { - fn default() -> Self { - Self { - b: None, - } + fn default() -> Self { + Self { + b: None, } + } } - impl TableAT { - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( - &self, - _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> - ) -> ::flatbuffers::WIPOffset> { - let b = self.b.as_ref().map(|x|{ - x.pack(_fbb) - }); - TableA::create(_fbb, &TableAArgs{ - b, - }) - } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> + ) -> ::flatbuffers::WIPOffset> { + let b = self.b.as_ref().map(|x|{ + x.pack(_fbb) + }); + TableA::create(_fbb, &TableAArgs{ + b, + }) + } } diff --git a/tests/include_test1_generated.rs b/tests/include_test1_generated.rs index a0417f317..c4575b88d 100644 --- a/tests/include_test1_generated.rs +++ b/tests/include_test1_generated.rs @@ -1,525 +1,479 @@ // automatically generated by the FlatBuffers compiler, do not modify // @generated + extern crate alloc; pub enum TableAOffset {} - #[derive(Copy, Clone, PartialEq)] + pub struct TableA<'a> { - pub _tab: ::flatbuffers::Table<'a>, + pub _tab: ::flatbuffers::Table<'a>, } impl<'a> ::flatbuffers::Follow<'a> for TableA<'a> { - type Inner = TableA<'a>; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } - } + type Inner = TableA<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } + } } impl<'a> TableA<'a> { - pub const VT_B: ::flatbuffers::VOffsetT = 4; + pub const VT_B: ::flatbuffers::VOffsetT = 4; - pub const fn get_fully_qualified_name() -> &'static str { - "TableA" - } + pub const fn get_fully_qualified_name() -> &'static str { + "TableA" + } - #[inline] - pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { - TableA { _tab: table } - } + #[inline] + pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { + TableA { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args TableAArgs<'args> + ) -> ::flatbuffers::WIPOffset> { + let mut builder = TableABuilder::new(_fbb); + if let Some(x) = args.b { builder.add_b(x); } + builder.finish() + } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args TableAArgs<'args> - ) -> ::flatbuffers::WIPOffset> { - let mut builder = TableABuilder::new(_fbb); - if let Some(x) = args.b { builder.add_b(x); } - builder.finish() + pub fn unpack(&self) -> TableAT { + let b = self.b().map(|x| { + alloc::boxed::Box::new(x.unpack()) + }); + TableAT { + b, } + } - pub fn unpack(&self) -> TableAT { - let b = self.b().map(|x| { - alloc::boxed::Box::new(x.unpack()) - }); - TableAT { - b, - } - } - - #[inline] - pub fn b(&self) -> Option> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset>(TableA::VT_B, None)} - } + #[inline] + pub fn b(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset>(TableA::VT_B, None)} + } } impl ::flatbuffers::Verifiable for TableA<'_> { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.visit_table(pos)? - .visit_field::<::flatbuffers::ForwardsUOffset>("b", Self::VT_B, false)? - .finish(); - Ok(()) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.visit_table(pos)? + .visit_field::<::flatbuffers::ForwardsUOffset>("b", Self::VT_B, false)? + .finish(); + Ok(()) + } } - pub struct TableAArgs<'a> { pub b: Option<::flatbuffers::WIPOffset>>, } - impl<'a> Default for TableAArgs<'a> { - #[inline] - fn default() -> Self { - TableAArgs { - b: None, - } + #[inline] + fn default() -> Self { + TableAArgs { + b: None, } + } } pub struct TableABuilder<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> { - fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, + fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, + start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, } - impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> TableABuilder<'a, 'b, A> { - #[inline] - pub fn add_b(&mut self, b: ::flatbuffers::WIPOffset>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset>(TableA::VT_B, b); - } - - #[inline] - pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> TableABuilder<'a, 'b, A> { - let start = _fbb.start_table(); - TableABuilder { - fbb_: _fbb, - start_: start, - } - } - - #[inline] - pub fn finish(self) -> ::flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - ::flatbuffers::WIPOffset::new(o.value()) + #[inline] + pub fn add_b(&mut self, b: ::flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset>(TableA::VT_B, b); + } + #[inline] + pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> TableABuilder<'a, 'b, A> { + let start = _fbb.start_table(); + TableABuilder { + fbb_: _fbb, + start_: start, } + } + #[inline] + pub fn finish(self) -> ::flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + ::flatbuffers::WIPOffset::new(o.value()) + } } impl ::core::fmt::Debug for TableA<'_> { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - let mut ds = f.debug_struct("TableA"); - ds.field("b", &self.b()); - ds.finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + let mut ds = f.debug_struct("TableA"); + ds.field("b", &self.b()); + ds.finish() + } } - #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub struct TableAT { - pub b: Option>, + pub b: Option>, } - impl Default for TableAT { - fn default() -> Self { - Self { - b: None, - } + fn default() -> Self { + Self { + b: None, } + } } - impl TableAT { - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( - &self, - _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> - ) -> ::flatbuffers::WIPOffset> { - let b = self.b.as_ref().map(|x|{ - x.pack(_fbb) - }); - TableA::create(_fbb, &TableAArgs{ - b, - }) - } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> + ) -> ::flatbuffers::WIPOffset> { + let b = self.b.as_ref().map(|x|{ + x.pack(_fbb) + }); + TableA::create(_fbb, &TableAArgs{ + b, + }) + } } - #[allow(unused_imports, dead_code)] pub mod my_game { - extern crate alloc; - #[allow(unused_imports, dead_code)] - pub mod other_name_space { - extern crate alloc; +extern crate alloc; +#[allow(unused_imports, dead_code)] +pub mod other_name_space { - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] - pub const ENUM_MIN_FROM_INCLUDE: i64 = 0; +extern crate alloc; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] - pub const ENUM_MAX_FROM_INCLUDE: i64 = 0; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MIN_FROM_INCLUDE: i64 = 0; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MAX_FROM_INCLUDE: i64 = 0; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +#[allow(non_camel_case_types)] +pub const ENUM_VALUES_FROM_INCLUDE: [FromInclude; 1] = [ + FromInclude::IncludeVal, +]; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] - #[allow(non_camel_case_types)] - pub const ENUM_VALUES_FROM_INCLUDE: [FromInclude; 1] = [ - FromInclude::IncludeVal, - ]; +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] +#[repr(transparent)] +pub struct FromInclude(pub i64); +#[allow(non_upper_case_globals)] +impl FromInclude { + pub const IncludeVal: Self = Self(0); - #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] - #[repr(transparent)] - pub struct FromInclude(pub i64); + pub const ENUM_MIN: i64 = 0; + pub const ENUM_MAX: i64 = 0; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::IncludeVal, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::IncludeVal => Some("IncludeVal"), + _ => None, + } + } +} +impl ::core::fmt::Debug for FromInclude { + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) + } + } +} +impl<'a> ::flatbuffers::Follow<'a> for FromInclude { + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; + Self(b) + } +} - #[allow(non_upper_case_globals)] - impl FromInclude { - pub const IncludeVal: Self = Self(0); +impl ::flatbuffers::Push for FromInclude { + type Output = FromInclude; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + unsafe { ::flatbuffers::emplace_scalar::(dst, self.0) }; + } +} - pub const ENUM_MIN: i64 = 0; - pub const ENUM_MAX: i64 = 0; - pub const ENUM_VALUES: &'static [Self] = &[ - Self::IncludeVal, - ]; +impl ::flatbuffers::EndianScalar for FromInclude { + type Scalar = i64; + #[inline] + fn to_little_endian(self) -> i64 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: i64) -> Self { + let b = i64::from_le(v); + Self(b) + } +} - /// Returns the variant's name or "" if unknown. - pub fn variant_name(self) -> Option<&'static str> { - match self { - Self::IncludeVal => Some("IncludeVal"), - _ => None, - } - } - } +impl<'a> ::flatbuffers::Verifiable for FromInclude { + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + i64::run_verifier(v, pos) + } +} - impl ::core::fmt::Debug for FromInclude { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - if let Some(name) = self.variant_name() { - f.write_str(name) - } else { - f.write_fmt(format_args!("", self.0)) - } - } - } +impl ::flatbuffers::SimpleToVerifyInSlice for FromInclude {} +// struct Unused, aligned to 4 +#[repr(transparent)] +#[derive(Clone, Copy, PartialEq)] +pub struct Unused(pub [u8; 4]); +impl Default for Unused { + fn default() -> Self { + Self([0; 4]) + } +} +impl ::core::fmt::Debug for Unused { + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + f.debug_struct("Unused") + .field("a", &self.a()) + .finish() + } +} - impl<'a> ::flatbuffers::Follow<'a> for FromInclude { - type Inner = Self; +impl ::flatbuffers::SimpleToVerifyInSlice for Unused {} +impl<'a> ::flatbuffers::Follow<'a> for Unused { + type Inner = &'a Unused; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { <&'a Unused>::follow(buf, loc) } + } +} +impl<'a> ::flatbuffers::Follow<'a> for &'a Unused { + type Inner = &'a Unused; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { ::flatbuffers::follow_cast_ref::(buf, loc) } + } +} +impl<'b> ::flatbuffers::Push for Unused { + type Output = Unused; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + let src = unsafe { ::core::slice::from_raw_parts(self as *const Unused as *const u8, ::size()) }; + dst.copy_from_slice(src); + } + #[inline] + fn alignment() -> ::flatbuffers::PushAlignment { + ::flatbuffers::PushAlignment::new(4) + } +} - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; - Self(b) - } - } +impl<'a> ::flatbuffers::Verifiable for Unused { + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.in_buffer::(pos) + } +} - impl ::flatbuffers::Push for FromInclude { - type Output = FromInclude; +impl<'a> Unused { + #[allow(clippy::too_many_arguments)] + pub fn new( + a: i32, + ) -> Self { + let mut s = Self([0; 4]); + s.set_a(a); + s + } - #[inline] - unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { - unsafe { ::flatbuffers::emplace_scalar::(dst, self.0) }; - } - } + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.OtherNameSpace.Unused" + } - impl ::flatbuffers::EndianScalar for FromInclude { - type Scalar = i64; + pub fn a(&self) -> i32 { + let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + ::flatbuffers::EndianScalar::from_little_endian(unsafe { + ::core::ptr::copy_nonoverlapping( + self.0[0..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + ::core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } - #[inline] - fn to_little_endian(self) -> i64 { - self.0.to_le() - } + pub fn set_a(&mut self, x: i32) { + let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + ::core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[0..].as_mut_ptr(), + ::core::mem::size_of::<::Scalar>(), + ); + } + } - #[inline] - #[allow(clippy::wrong_self_convention)] - fn from_little_endian(v: i64) -> Self { - let b = i64::from_le(v); - Self(b) - } - } + pub fn unpack(&self) -> UnusedT { + UnusedT { + a: self.a(), + } + } +} - impl<'a> ::flatbuffers::Verifiable for FromInclude { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - i64::run_verifier(v, pos) - } - } +#[derive(Debug, Clone, PartialEq, Default)] +pub struct UnusedT { + pub a: i32, +} +impl UnusedT { + pub fn pack(&self) -> Unused { + Unused::new( + self.a, + ) + } +} - impl ::flatbuffers::SimpleToVerifyInSlice for FromInclude {} +pub enum TableBOffset {} +#[derive(Copy, Clone, PartialEq)] - // struct Unused, aligned to 4 - #[repr(transparent)] - #[derive(Clone, Copy, PartialEq)] - pub struct Unused(pub [u8; 4]); +pub struct TableB<'a> { + pub _tab: ::flatbuffers::Table<'a>, +} - impl Default for Unused { - fn default() -> Self { - Self([0; 4]) - } - } +impl<'a> ::flatbuffers::Follow<'a> for TableB<'a> { + type Inner = TableB<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } + } +} - impl ::core::fmt::Debug for Unused { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - f.debug_struct("Unused") - .field("a", &self.a()) - .finish() - } - } +impl<'a> TableB<'a> { + pub const VT_A: ::flatbuffers::VOffsetT = 4; - impl ::flatbuffers::SimpleToVerifyInSlice for Unused {} + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.OtherNameSpace.TableB" + } - impl<'a> ::flatbuffers::Follow<'a> for Unused { - type Inner = &'a Unused; + #[inline] + pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { + TableB { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args TableBArgs<'args> + ) -> ::flatbuffers::WIPOffset> { + let mut builder = TableBBuilder::new(_fbb); + if let Some(x) = args.a { builder.add_a(x); } + builder.finish() + } - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - unsafe { <&'a Unused>::follow(buf, loc) } - } - } + pub fn unpack(&self) -> TableBT { + let a = self.a().map(|x| { + alloc::boxed::Box::new(x.unpack()) + }); + TableBT { + a, + } + } - impl<'a> ::flatbuffers::Follow<'a> for &'a Unused { - type Inner = &'a Unused; + #[inline] + pub fn a(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset>(TableB::VT_A, None)} + } +} - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - unsafe { ::flatbuffers::follow_cast_ref::(buf, loc) } - } - } +impl ::flatbuffers::Verifiable for TableB<'_> { + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.visit_table(pos)? + .visit_field::<::flatbuffers::ForwardsUOffset>("a", Self::VT_A, false)? + .finish(); + Ok(()) + } +} +pub struct TableBArgs<'a> { + pub a: Option<::flatbuffers::WIPOffset>>, +} +impl<'a> Default for TableBArgs<'a> { + #[inline] + fn default() -> Self { + TableBArgs { + a: None, + } + } +} - impl<'b> ::flatbuffers::Push for Unused { - type Output = Unused; +pub struct TableBBuilder<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> { + fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, + start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, +} +impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> TableBBuilder<'a, 'b, A> { + #[inline] + pub fn add_a(&mut self, a: ::flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset>(TableB::VT_A, a); + } + #[inline] + pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> TableBBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + TableBBuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> ::flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + ::flatbuffers::WIPOffset::new(o.value()) + } +} - #[inline] - unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { - let src = unsafe { ::core::slice::from_raw_parts(self as *const Unused as *const u8, ::size()) }; - dst.copy_from_slice(src); - } +impl ::core::fmt::Debug for TableB<'_> { + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + let mut ds = f.debug_struct("TableB"); + ds.field("a", &self.a()); + ds.finish() + } +} +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub struct TableBT { + pub a: Option>, +} +impl Default for TableBT { + fn default() -> Self { + Self { + a: None, + } + } +} +impl TableBT { + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> + ) -> ::flatbuffers::WIPOffset> { + let a = self.a.as_ref().map(|x|{ + x.pack(_fbb) + }); + TableB::create(_fbb, &TableBArgs{ + a, + }) + } +} +} // pub mod OtherNameSpace +} // pub mod MyGame - #[inline] - fn alignment() -> ::flatbuffers::PushAlignment { - ::flatbuffers::PushAlignment::new(4) - } - } - - impl<'a> ::flatbuffers::Verifiable for Unused { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.in_buffer::(pos) - } - } - - impl<'a> Unused { - #[allow(clippy::too_many_arguments)] - pub fn new( - a: i32, - ) -> Self { - let mut s = Self([0; 4]); - s.set_a(a); - s - } - - pub const fn get_fully_qualified_name() -> &'static str { - "MyGame.OtherNameSpace.Unused" - } - - pub fn a(&self) -> i32 { - let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - ::flatbuffers::EndianScalar::from_little_endian(unsafe { - ::core::ptr::copy_nonoverlapping( - self.0[0..].as_ptr(), - mem.as_mut_ptr() as *mut u8, - ::core::mem::size_of::<::Scalar>(), - ); - mem.assume_init() - }) - } - - pub fn set_a(&mut self, x: i32) { - let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - unsafe { - ::core::ptr::copy_nonoverlapping( - &x_le as *const _ as *const u8, - self.0[0..].as_mut_ptr(), - ::core::mem::size_of::<::Scalar>(), - ); - } - } - - pub fn unpack(&self) -> UnusedT { - UnusedT { - a: self.a(), - } - } - } - - #[derive(Debug, Clone, PartialEq)] - pub struct UnusedT { - pub a: i32, - } - impl Default for UnusedT { - fn default() -> Self { - Self { - a: 0, - } - } - } - - impl UnusedT { - pub fn pack(&self) -> Unused { - Unused::new( - self.a, - ) - } - } - - pub enum TableBOffset {} - - #[derive(Copy, Clone, PartialEq)] - pub struct TableB<'a> { - pub _tab: ::flatbuffers::Table<'a>, - } - - impl<'a> ::flatbuffers::Follow<'a> for TableB<'a> { - type Inner = TableB<'a>; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } - } - } - - impl<'a> TableB<'a> { - pub const VT_A: ::flatbuffers::VOffsetT = 4; - - pub const fn get_fully_qualified_name() -> &'static str { - "MyGame.OtherNameSpace.TableB" - } - - #[inline] - pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { - TableB { _tab: table } - } - - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args TableBArgs<'args> - ) -> ::flatbuffers::WIPOffset> { - let mut builder = TableBBuilder::new(_fbb); - if let Some(x) = args.a { builder.add_a(x); } - builder.finish() - } - - pub fn unpack(&self) -> TableBT { - let a = self.a().map(|x| { - alloc::boxed::Box::new(x.unpack()) - }); - TableBT { - a, - } - } - - #[inline] - pub fn a(&self) -> Option> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset>(TableB::VT_A, None)} - } - } - - impl ::flatbuffers::Verifiable for TableB<'_> { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.visit_table(pos)? - .visit_field::<::flatbuffers::ForwardsUOffset>("a", Self::VT_A, false)? - .finish(); - Ok(()) - } - } - - pub struct TableBArgs<'a> { - pub a: Option<::flatbuffers::WIPOffset>>, - } - - impl<'a> Default for TableBArgs<'a> { - #[inline] - fn default() -> Self { - TableBArgs { - a: None, - } - } - } - - pub struct TableBBuilder<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> { - fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, - } - - impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> TableBBuilder<'a, 'b, A> { - #[inline] - pub fn add_a(&mut self, a: ::flatbuffers::WIPOffset>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset>(TableB::VT_A, a); - } - - #[inline] - pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> TableBBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - TableBBuilder { - fbb_: _fbb, - start_: start, - } - } - - #[inline] - pub fn finish(self) -> ::flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - ::flatbuffers::WIPOffset::new(o.value()) - } - } - - impl ::core::fmt::Debug for TableB<'_> { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - let mut ds = f.debug_struct("TableB"); - ds.field("a", &self.a()); - ds.finish() - } - } - - #[non_exhaustive] - #[derive(Debug, Clone, PartialEq)] - pub struct TableBT { - pub a: Option>, - } - - impl Default for TableBT { - fn default() -> Self { - Self { - a: None, - } - } - } - - impl TableBT { - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( - &self, - _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> - ) -> ::flatbuffers::WIPOffset> { - let a = self.a.as_ref().map(|x|{ - x.pack(_fbb) - }); - TableB::create(_fbb, &TableBArgs{ - a, - }) - } - } - } // pub mod OtherNameSpace -} // pub mod MyGame diff --git a/tests/include_test2/mod.rs b/tests/include_test2/mod.rs index a69094e07..ca4894dc3 100644 --- a/tests/include_test2/mod.rs +++ b/tests/include_test2/mod.rs @@ -1,16 +1,16 @@ // Automatically generated by the Flatbuffers compiler. Do not modify. // @generated pub mod my_game { + use super::*; + pub mod other_name_space { use super::*; - pub mod other_name_space { - use super::*; - mod from_include_generated; - pub use self::from_include_generated::*; - mod unused_generated; - pub use self::unused_generated::*; - mod table_b_generated; - pub use self::table_b_generated::*; - } // other_name_space + mod from_include_generated; + pub use self::from_include_generated::*; + mod unused_generated; + pub use self::unused_generated::*; + mod table_b_generated; + pub use self::table_b_generated::*; + } // other_name_space } // my_game mod table_a_generated; pub use self::table_a_generated::*; diff --git a/tests/include_test2/my_game/other_name_space/from_include_generated.rs b/tests/include_test2/my_game/other_name_space/from_include_generated.rs index ada294725..5eb9adc5e 100644 --- a/tests/include_test2/my_game/other_name_space/from_include_generated.rs +++ b/tests/include_test2/my_game/other_name_space/from_include_generated.rs @@ -2,65 +2,56 @@ // @generated extern crate alloc; use super::*; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] pub const ENUM_MIN_FROM_INCLUDE: i64 = 0; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] pub const ENUM_MAX_FROM_INCLUDE: i64 = 0; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] #[allow(non_camel_case_types)] pub const ENUM_VALUES_FROM_INCLUDE: [FromInclude; 1] = [ - FromInclude::IncludeVal, + FromInclude::IncludeVal, ]; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] #[repr(transparent)] pub struct FromInclude(pub i64); - #[allow(non_upper_case_globals)] impl FromInclude { - pub const IncludeVal: Self = Self(0); + pub const IncludeVal: Self = Self(0); - pub const ENUM_MIN: i64 = 0; - pub const ENUM_MAX: i64 = 0; - pub const ENUM_VALUES: &'static [Self] = &[ - Self::IncludeVal, - ]; - - /// Returns the variant's name or "" if unknown. - pub fn variant_name(self) -> Option<&'static str> { - match self { - Self::IncludeVal => Some("IncludeVal"), - _ => None, - } + pub const ENUM_MIN: i64 = 0; + pub const ENUM_MAX: i64 = 0; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::IncludeVal, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::IncludeVal => Some("IncludeVal"), + _ => None, } + } } - impl ::core::fmt::Debug for FromInclude { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - if let Some(name) = self.variant_name() { - f.write_str(name) - } else { - f.write_fmt(format_args!("", self.0)) - } + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) } + } } - impl<'a> ::flatbuffers::Follow<'a> for FromInclude { - type Inner = Self; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; - Self(b) - } + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; + Self(b) + } } impl ::flatbuffers::Push for FromInclude { type Output = FromInclude; - #[inline] unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { unsafe { ::flatbuffers::emplace_scalar::(dst, self.0) }; @@ -68,28 +59,26 @@ impl ::flatbuffers::Push for FromInclude { } impl ::flatbuffers::EndianScalar for FromInclude { - type Scalar = i64; - - #[inline] - fn to_little_endian(self) -> i64 { - self.0.to_le() - } - - #[inline] - #[allow(clippy::wrong_self_convention)] - fn from_little_endian(v: i64) -> Self { - let b = i64::from_le(v); - Self(b) - } + type Scalar = i64; + #[inline] + fn to_little_endian(self) -> i64 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: i64) -> Self { + let b = i64::from_le(v); + Self(b) + } } impl<'a> ::flatbuffers::Verifiable for FromInclude { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - i64::run_verifier(v, pos) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + i64::run_verifier(v, pos) + } } impl ::flatbuffers::SimpleToVerifyInSlice for FromInclude {} diff --git a/tests/include_test2/my_game/other_name_space/table_b_generated.rs b/tests/include_test2/my_game/other_name_space/table_b_generated.rs index 5434e448a..19a3e66ba 100644 --- a/tests/include_test2/my_game/other_name_space/table_b_generated.rs +++ b/tests/include_test2/my_game/other_name_space/table_b_generated.rs @@ -2,147 +2,136 @@ // @generated extern crate alloc; use super::*; - pub enum TableBOffset {} - #[derive(Copy, Clone, PartialEq)] + pub struct TableB<'a> { - pub _tab: ::flatbuffers::Table<'a>, + pub _tab: ::flatbuffers::Table<'a>, } impl<'a> ::flatbuffers::Follow<'a> for TableB<'a> { - type Inner = TableB<'a>; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } - } + type Inner = TableB<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } + } } impl<'a> TableB<'a> { - pub const VT_A: ::flatbuffers::VOffsetT = 4; + pub const VT_A: ::flatbuffers::VOffsetT = 4; - pub const fn get_fully_qualified_name() -> &'static str { - "MyGame.OtherNameSpace.TableB" - } + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.OtherNameSpace.TableB" + } - #[inline] - pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { - TableB { _tab: table } - } + #[inline] + pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { + TableB { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args TableBArgs<'args> + ) -> ::flatbuffers::WIPOffset> { + let mut builder = TableBBuilder::new(_fbb); + if let Some(x) = args.a { builder.add_a(x); } + builder.finish() + } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args TableBArgs<'args> - ) -> ::flatbuffers::WIPOffset> { - let mut builder = TableBBuilder::new(_fbb); - if let Some(x) = args.a { builder.add_a(x); } - builder.finish() + pub fn unpack(&self) -> TableBT { + let a = self.a().map(|x| { + alloc::boxed::Box::new(x.unpack()) + }); + TableBT { + a, } + } - pub fn unpack(&self) -> TableBT { - let a = self.a().map(|x| { - alloc::boxed::Box::new(x.unpack()) - }); - TableBT { - a, - } - } - - #[inline] - pub fn a(&self) -> Option> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset>(TableB::VT_A, None)} - } + #[inline] + pub fn a(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset>(TableB::VT_A, None)} + } } impl ::flatbuffers::Verifiable for TableB<'_> { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.visit_table(pos)? - .visit_field::<::flatbuffers::ForwardsUOffset>("a", Self::VT_A, false)? - .finish(); - Ok(()) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.visit_table(pos)? + .visit_field::<::flatbuffers::ForwardsUOffset>("a", Self::VT_A, false)? + .finish(); + Ok(()) + } } - pub struct TableBArgs<'a> { pub a: Option<::flatbuffers::WIPOffset>>, } - impl<'a> Default for TableBArgs<'a> { - #[inline] - fn default() -> Self { - TableBArgs { - a: None, - } + #[inline] + fn default() -> Self { + TableBArgs { + a: None, } + } } pub struct TableBBuilder<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> { - fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, + fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, + start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, } - impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> TableBBuilder<'a, 'b, A> { - #[inline] - pub fn add_a(&mut self, a: ::flatbuffers::WIPOffset>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset>(TableB::VT_A, a); - } - - #[inline] - pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> TableBBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - TableBBuilder { - fbb_: _fbb, - start_: start, - } - } - - #[inline] - pub fn finish(self) -> ::flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - ::flatbuffers::WIPOffset::new(o.value()) + #[inline] + pub fn add_a(&mut self, a: ::flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset>(TableB::VT_A, a); + } + #[inline] + pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> TableBBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + TableBBuilder { + fbb_: _fbb, + start_: start, } + } + #[inline] + pub fn finish(self) -> ::flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + ::flatbuffers::WIPOffset::new(o.value()) + } } impl ::core::fmt::Debug for TableB<'_> { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - let mut ds = f.debug_struct("TableB"); - ds.field("a", &self.a()); - ds.finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + let mut ds = f.debug_struct("TableB"); + ds.field("a", &self.a()); + ds.finish() + } } - #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub struct TableBT { - pub a: Option>, + pub a: Option>, } - impl Default for TableBT { - fn default() -> Self { - Self { - a: None, - } + fn default() -> Self { + Self { + a: None, } + } } - impl TableBT { - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( - &self, - _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> - ) -> ::flatbuffers::WIPOffset> { - let a = self.a.as_ref().map(|x|{ - x.pack(_fbb) - }); - TableB::create(_fbb, &TableBArgs{ - a, - }) - } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> + ) -> ::flatbuffers::WIPOffset> { + let a = self.a.as_ref().map(|x|{ + x.pack(_fbb) + }); + TableB::create(_fbb, &TableBArgs{ + a, + }) + } } diff --git a/tests/include_test2/my_game/other_name_space/unused_generated.rs b/tests/include_test2/my_game/other_name_space/unused_generated.rs index d19375f17..b90fb8924 100644 --- a/tests/include_test2/my_game/other_name_space/unused_generated.rs +++ b/tests/include_test2/my_game/other_name_space/unused_generated.rs @@ -2,55 +2,45 @@ // @generated extern crate alloc; use super::*; - // struct Unused, aligned to 4 #[repr(transparent)] #[derive(Clone, Copy, PartialEq)] pub struct Unused(pub [u8; 4]); - -impl Default for Unused { - fn default() -> Self { - Self([0; 4]) - } +impl Default for Unused { + fn default() -> Self { + Self([0; 4]) + } } - impl ::core::fmt::Debug for Unused { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - f.debug_struct("Unused") - .field("a", &self.a()) - .finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + f.debug_struct("Unused") + .field("a", &self.a()) + .finish() + } } impl ::flatbuffers::SimpleToVerifyInSlice for Unused {} - impl<'a> ::flatbuffers::Follow<'a> for Unused { - type Inner = &'a Unused; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - unsafe { <&'a Unused>::follow(buf, loc) } - } + type Inner = &'a Unused; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { <&'a Unused>::follow(buf, loc) } + } } - impl<'a> ::flatbuffers::Follow<'a> for &'a Unused { - type Inner = &'a Unused; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - unsafe { ::flatbuffers::follow_cast_ref::(buf, loc) } - } + type Inner = &'a Unused; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { ::flatbuffers::follow_cast_ref::(buf, loc) } + } } - impl<'b> ::flatbuffers::Push for Unused { type Output = Unused; - #[inline] unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { let src = unsafe { ::core::slice::from_raw_parts(self as *const Unused as *const u8, ::size()) }; dst.copy_from_slice(src); } - #[inline] fn alignment() -> ::flatbuffers::PushAlignment { ::flatbuffers::PushAlignment::new(4) @@ -58,80 +48,73 @@ impl<'b> ::flatbuffers::Push for Unused { } impl<'a> ::flatbuffers::Verifiable for Unused { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.in_buffer::(pos) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.in_buffer::(pos) + } } impl<'a> Unused { - #[allow(clippy::too_many_arguments)] - pub fn new( - a: i32, - ) -> Self { - let mut s = Self([0; 4]); - s.set_a(a); - s - } + #[allow(clippy::too_many_arguments)] + pub fn new( + a: i32, + ) -> Self { + let mut s = Self([0; 4]); + s.set_a(a); + s + } - pub const fn get_fully_qualified_name() -> &'static str { - "MyGame.OtherNameSpace.Unused" - } + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.OtherNameSpace.Unused" + } - pub fn a(&self) -> i32 { - let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - ::flatbuffers::EndianScalar::from_little_endian(unsafe { - ::core::ptr::copy_nonoverlapping( - self.0[0..].as_ptr(), - mem.as_mut_ptr() as *mut u8, - ::core::mem::size_of::<::Scalar>(), - ); - mem.assume_init() - }) - } + pub fn a(&self) -> i32 { + let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + ::flatbuffers::EndianScalar::from_little_endian(unsafe { + ::core::ptr::copy_nonoverlapping( + self.0[0..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + ::core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } - pub fn set_a(&mut self, x: i32) { - let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - unsafe { - ::core::ptr::copy_nonoverlapping( - &x_le as *const _ as *const u8, - self.0[0..].as_mut_ptr(), - ::core::mem::size_of::<::Scalar>(), - ); - } + pub fn set_a(&mut self, x: i32) { + let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + ::core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[0..].as_mut_ptr(), + ::core::mem::size_of::<::Scalar>(), + ); } + } - pub fn unpack(&self) -> UnusedT { - UnusedT { - a: self.a(), - } + pub fn unpack(&self) -> UnusedT { + UnusedT { + a: self.a(), } + } } -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Default)] pub struct UnusedT { - pub a: i32, + pub a: i32, } -impl Default for UnusedT { - fn default() -> Self { - Self { - a: 0, - } - } +impl UnusedT { + pub fn pack(&self) -> Unused { + Unused::new( + self.a, + ) + } } -impl UnusedT { - pub fn pack(&self) -> Unused { - Unused::new( - self.a, - ) - } -} diff --git a/tests/include_test2/table_a_generated.rs b/tests/include_test2/table_a_generated.rs index 467c514a1..ca29250dc 100644 --- a/tests/include_test2/table_a_generated.rs +++ b/tests/include_test2/table_a_generated.rs @@ -2,147 +2,136 @@ // @generated extern crate alloc; use super::*; - pub enum TableAOffset {} - #[derive(Copy, Clone, PartialEq)] + pub struct TableA<'a> { - pub _tab: ::flatbuffers::Table<'a>, + pub _tab: ::flatbuffers::Table<'a>, } impl<'a> ::flatbuffers::Follow<'a> for TableA<'a> { - type Inner = TableA<'a>; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } - } + type Inner = TableA<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } + } } impl<'a> TableA<'a> { - pub const VT_B: ::flatbuffers::VOffsetT = 4; + pub const VT_B: ::flatbuffers::VOffsetT = 4; - pub const fn get_fully_qualified_name() -> &'static str { - "TableA" - } + pub const fn get_fully_qualified_name() -> &'static str { + "TableA" + } - #[inline] - pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { - TableA { _tab: table } - } + #[inline] + pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { + TableA { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args TableAArgs<'args> + ) -> ::flatbuffers::WIPOffset> { + let mut builder = TableABuilder::new(_fbb); + if let Some(x) = args.b { builder.add_b(x); } + builder.finish() + } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args TableAArgs<'args> - ) -> ::flatbuffers::WIPOffset> { - let mut builder = TableABuilder::new(_fbb); - if let Some(x) = args.b { builder.add_b(x); } - builder.finish() + pub fn unpack(&self) -> TableAT { + let b = self.b().map(|x| { + alloc::boxed::Box::new(x.unpack()) + }); + TableAT { + b, } + } - pub fn unpack(&self) -> TableAT { - let b = self.b().map(|x| { - alloc::boxed::Box::new(x.unpack()) - }); - TableAT { - b, - } - } - - #[inline] - pub fn b(&self) -> Option> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset>(TableA::VT_B, None)} - } + #[inline] + pub fn b(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset>(TableA::VT_B, None)} + } } impl ::flatbuffers::Verifiable for TableA<'_> { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.visit_table(pos)? - .visit_field::<::flatbuffers::ForwardsUOffset>("b", Self::VT_B, false)? - .finish(); - Ok(()) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.visit_table(pos)? + .visit_field::<::flatbuffers::ForwardsUOffset>("b", Self::VT_B, false)? + .finish(); + Ok(()) + } } - pub struct TableAArgs<'a> { pub b: Option<::flatbuffers::WIPOffset>>, } - impl<'a> Default for TableAArgs<'a> { - #[inline] - fn default() -> Self { - TableAArgs { - b: None, - } + #[inline] + fn default() -> Self { + TableAArgs { + b: None, } + } } pub struct TableABuilder<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> { - fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, + fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, + start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, } - impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> TableABuilder<'a, 'b, A> { - #[inline] - pub fn add_b(&mut self, b: ::flatbuffers::WIPOffset>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset>(TableA::VT_B, b); - } - - #[inline] - pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> TableABuilder<'a, 'b, A> { - let start = _fbb.start_table(); - TableABuilder { - fbb_: _fbb, - start_: start, - } - } - - #[inline] - pub fn finish(self) -> ::flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - ::flatbuffers::WIPOffset::new(o.value()) + #[inline] + pub fn add_b(&mut self, b: ::flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset>(TableA::VT_B, b); + } + #[inline] + pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> TableABuilder<'a, 'b, A> { + let start = _fbb.start_table(); + TableABuilder { + fbb_: _fbb, + start_: start, } + } + #[inline] + pub fn finish(self) -> ::flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + ::flatbuffers::WIPOffset::new(o.value()) + } } impl ::core::fmt::Debug for TableA<'_> { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - let mut ds = f.debug_struct("TableA"); - ds.field("b", &self.b()); - ds.finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + let mut ds = f.debug_struct("TableA"); + ds.field("b", &self.b()); + ds.finish() + } } - #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub struct TableAT { - pub b: Option>, + pub b: Option>, } - impl Default for TableAT { - fn default() -> Self { - Self { - b: None, - } + fn default() -> Self { + Self { + b: None, } + } } - impl TableAT { - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( - &self, - _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> - ) -> ::flatbuffers::WIPOffset> { - let b = self.b.as_ref().map(|x|{ - x.pack(_fbb) - }); - TableA::create(_fbb, &TableAArgs{ - b, - }) - } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> + ) -> ::flatbuffers::WIPOffset> { + let b = self.b.as_ref().map(|x|{ + x.pack(_fbb) + }); + TableA::create(_fbb, &TableAArgs{ + b, + }) + } } diff --git a/tests/include_test2_generated.rs b/tests/include_test2_generated.rs index a0417f317..c4575b88d 100644 --- a/tests/include_test2_generated.rs +++ b/tests/include_test2_generated.rs @@ -1,525 +1,479 @@ // automatically generated by the FlatBuffers compiler, do not modify // @generated + extern crate alloc; pub enum TableAOffset {} - #[derive(Copy, Clone, PartialEq)] + pub struct TableA<'a> { - pub _tab: ::flatbuffers::Table<'a>, + pub _tab: ::flatbuffers::Table<'a>, } impl<'a> ::flatbuffers::Follow<'a> for TableA<'a> { - type Inner = TableA<'a>; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } - } + type Inner = TableA<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } + } } impl<'a> TableA<'a> { - pub const VT_B: ::flatbuffers::VOffsetT = 4; + pub const VT_B: ::flatbuffers::VOffsetT = 4; - pub const fn get_fully_qualified_name() -> &'static str { - "TableA" - } + pub const fn get_fully_qualified_name() -> &'static str { + "TableA" + } - #[inline] - pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { - TableA { _tab: table } - } + #[inline] + pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { + TableA { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args TableAArgs<'args> + ) -> ::flatbuffers::WIPOffset> { + let mut builder = TableABuilder::new(_fbb); + if let Some(x) = args.b { builder.add_b(x); } + builder.finish() + } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args TableAArgs<'args> - ) -> ::flatbuffers::WIPOffset> { - let mut builder = TableABuilder::new(_fbb); - if let Some(x) = args.b { builder.add_b(x); } - builder.finish() + pub fn unpack(&self) -> TableAT { + let b = self.b().map(|x| { + alloc::boxed::Box::new(x.unpack()) + }); + TableAT { + b, } + } - pub fn unpack(&self) -> TableAT { - let b = self.b().map(|x| { - alloc::boxed::Box::new(x.unpack()) - }); - TableAT { - b, - } - } - - #[inline] - pub fn b(&self) -> Option> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset>(TableA::VT_B, None)} - } + #[inline] + pub fn b(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset>(TableA::VT_B, None)} + } } impl ::flatbuffers::Verifiable for TableA<'_> { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.visit_table(pos)? - .visit_field::<::flatbuffers::ForwardsUOffset>("b", Self::VT_B, false)? - .finish(); - Ok(()) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.visit_table(pos)? + .visit_field::<::flatbuffers::ForwardsUOffset>("b", Self::VT_B, false)? + .finish(); + Ok(()) + } } - pub struct TableAArgs<'a> { pub b: Option<::flatbuffers::WIPOffset>>, } - impl<'a> Default for TableAArgs<'a> { - #[inline] - fn default() -> Self { - TableAArgs { - b: None, - } + #[inline] + fn default() -> Self { + TableAArgs { + b: None, } + } } pub struct TableABuilder<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> { - fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, + fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, + start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, } - impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> TableABuilder<'a, 'b, A> { - #[inline] - pub fn add_b(&mut self, b: ::flatbuffers::WIPOffset>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset>(TableA::VT_B, b); - } - - #[inline] - pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> TableABuilder<'a, 'b, A> { - let start = _fbb.start_table(); - TableABuilder { - fbb_: _fbb, - start_: start, - } - } - - #[inline] - pub fn finish(self) -> ::flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - ::flatbuffers::WIPOffset::new(o.value()) + #[inline] + pub fn add_b(&mut self, b: ::flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset>(TableA::VT_B, b); + } + #[inline] + pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> TableABuilder<'a, 'b, A> { + let start = _fbb.start_table(); + TableABuilder { + fbb_: _fbb, + start_: start, } + } + #[inline] + pub fn finish(self) -> ::flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + ::flatbuffers::WIPOffset::new(o.value()) + } } impl ::core::fmt::Debug for TableA<'_> { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - let mut ds = f.debug_struct("TableA"); - ds.field("b", &self.b()); - ds.finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + let mut ds = f.debug_struct("TableA"); + ds.field("b", &self.b()); + ds.finish() + } } - #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub struct TableAT { - pub b: Option>, + pub b: Option>, } - impl Default for TableAT { - fn default() -> Self { - Self { - b: None, - } + fn default() -> Self { + Self { + b: None, } + } } - impl TableAT { - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( - &self, - _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> - ) -> ::flatbuffers::WIPOffset> { - let b = self.b.as_ref().map(|x|{ - x.pack(_fbb) - }); - TableA::create(_fbb, &TableAArgs{ - b, - }) - } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> + ) -> ::flatbuffers::WIPOffset> { + let b = self.b.as_ref().map(|x|{ + x.pack(_fbb) + }); + TableA::create(_fbb, &TableAArgs{ + b, + }) + } } - #[allow(unused_imports, dead_code)] pub mod my_game { - extern crate alloc; - #[allow(unused_imports, dead_code)] - pub mod other_name_space { - extern crate alloc; +extern crate alloc; +#[allow(unused_imports, dead_code)] +pub mod other_name_space { - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] - pub const ENUM_MIN_FROM_INCLUDE: i64 = 0; +extern crate alloc; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] - pub const ENUM_MAX_FROM_INCLUDE: i64 = 0; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MIN_FROM_INCLUDE: i64 = 0; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MAX_FROM_INCLUDE: i64 = 0; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +#[allow(non_camel_case_types)] +pub const ENUM_VALUES_FROM_INCLUDE: [FromInclude; 1] = [ + FromInclude::IncludeVal, +]; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] - #[allow(non_camel_case_types)] - pub const ENUM_VALUES_FROM_INCLUDE: [FromInclude; 1] = [ - FromInclude::IncludeVal, - ]; +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] +#[repr(transparent)] +pub struct FromInclude(pub i64); +#[allow(non_upper_case_globals)] +impl FromInclude { + pub const IncludeVal: Self = Self(0); - #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] - #[repr(transparent)] - pub struct FromInclude(pub i64); + pub const ENUM_MIN: i64 = 0; + pub const ENUM_MAX: i64 = 0; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::IncludeVal, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::IncludeVal => Some("IncludeVal"), + _ => None, + } + } +} +impl ::core::fmt::Debug for FromInclude { + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) + } + } +} +impl<'a> ::flatbuffers::Follow<'a> for FromInclude { + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; + Self(b) + } +} - #[allow(non_upper_case_globals)] - impl FromInclude { - pub const IncludeVal: Self = Self(0); +impl ::flatbuffers::Push for FromInclude { + type Output = FromInclude; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + unsafe { ::flatbuffers::emplace_scalar::(dst, self.0) }; + } +} - pub const ENUM_MIN: i64 = 0; - pub const ENUM_MAX: i64 = 0; - pub const ENUM_VALUES: &'static [Self] = &[ - Self::IncludeVal, - ]; +impl ::flatbuffers::EndianScalar for FromInclude { + type Scalar = i64; + #[inline] + fn to_little_endian(self) -> i64 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: i64) -> Self { + let b = i64::from_le(v); + Self(b) + } +} - /// Returns the variant's name or "" if unknown. - pub fn variant_name(self) -> Option<&'static str> { - match self { - Self::IncludeVal => Some("IncludeVal"), - _ => None, - } - } - } +impl<'a> ::flatbuffers::Verifiable for FromInclude { + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + i64::run_verifier(v, pos) + } +} - impl ::core::fmt::Debug for FromInclude { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - if let Some(name) = self.variant_name() { - f.write_str(name) - } else { - f.write_fmt(format_args!("", self.0)) - } - } - } +impl ::flatbuffers::SimpleToVerifyInSlice for FromInclude {} +// struct Unused, aligned to 4 +#[repr(transparent)] +#[derive(Clone, Copy, PartialEq)] +pub struct Unused(pub [u8; 4]); +impl Default for Unused { + fn default() -> Self { + Self([0; 4]) + } +} +impl ::core::fmt::Debug for Unused { + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + f.debug_struct("Unused") + .field("a", &self.a()) + .finish() + } +} - impl<'a> ::flatbuffers::Follow<'a> for FromInclude { - type Inner = Self; +impl ::flatbuffers::SimpleToVerifyInSlice for Unused {} +impl<'a> ::flatbuffers::Follow<'a> for Unused { + type Inner = &'a Unused; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { <&'a Unused>::follow(buf, loc) } + } +} +impl<'a> ::flatbuffers::Follow<'a> for &'a Unused { + type Inner = &'a Unused; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { ::flatbuffers::follow_cast_ref::(buf, loc) } + } +} +impl<'b> ::flatbuffers::Push for Unused { + type Output = Unused; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + let src = unsafe { ::core::slice::from_raw_parts(self as *const Unused as *const u8, ::size()) }; + dst.copy_from_slice(src); + } + #[inline] + fn alignment() -> ::flatbuffers::PushAlignment { + ::flatbuffers::PushAlignment::new(4) + } +} - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; - Self(b) - } - } +impl<'a> ::flatbuffers::Verifiable for Unused { + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.in_buffer::(pos) + } +} - impl ::flatbuffers::Push for FromInclude { - type Output = FromInclude; +impl<'a> Unused { + #[allow(clippy::too_many_arguments)] + pub fn new( + a: i32, + ) -> Self { + let mut s = Self([0; 4]); + s.set_a(a); + s + } - #[inline] - unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { - unsafe { ::flatbuffers::emplace_scalar::(dst, self.0) }; - } - } + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.OtherNameSpace.Unused" + } - impl ::flatbuffers::EndianScalar for FromInclude { - type Scalar = i64; + pub fn a(&self) -> i32 { + let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + ::flatbuffers::EndianScalar::from_little_endian(unsafe { + ::core::ptr::copy_nonoverlapping( + self.0[0..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + ::core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } - #[inline] - fn to_little_endian(self) -> i64 { - self.0.to_le() - } + pub fn set_a(&mut self, x: i32) { + let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + ::core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[0..].as_mut_ptr(), + ::core::mem::size_of::<::Scalar>(), + ); + } + } - #[inline] - #[allow(clippy::wrong_self_convention)] - fn from_little_endian(v: i64) -> Self { - let b = i64::from_le(v); - Self(b) - } - } + pub fn unpack(&self) -> UnusedT { + UnusedT { + a: self.a(), + } + } +} - impl<'a> ::flatbuffers::Verifiable for FromInclude { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - i64::run_verifier(v, pos) - } - } +#[derive(Debug, Clone, PartialEq, Default)] +pub struct UnusedT { + pub a: i32, +} +impl UnusedT { + pub fn pack(&self) -> Unused { + Unused::new( + self.a, + ) + } +} - impl ::flatbuffers::SimpleToVerifyInSlice for FromInclude {} +pub enum TableBOffset {} +#[derive(Copy, Clone, PartialEq)] - // struct Unused, aligned to 4 - #[repr(transparent)] - #[derive(Clone, Copy, PartialEq)] - pub struct Unused(pub [u8; 4]); +pub struct TableB<'a> { + pub _tab: ::flatbuffers::Table<'a>, +} - impl Default for Unused { - fn default() -> Self { - Self([0; 4]) - } - } +impl<'a> ::flatbuffers::Follow<'a> for TableB<'a> { + type Inner = TableB<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } + } +} - impl ::core::fmt::Debug for Unused { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - f.debug_struct("Unused") - .field("a", &self.a()) - .finish() - } - } +impl<'a> TableB<'a> { + pub const VT_A: ::flatbuffers::VOffsetT = 4; - impl ::flatbuffers::SimpleToVerifyInSlice for Unused {} + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.OtherNameSpace.TableB" + } - impl<'a> ::flatbuffers::Follow<'a> for Unused { - type Inner = &'a Unused; + #[inline] + pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { + TableB { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args TableBArgs<'args> + ) -> ::flatbuffers::WIPOffset> { + let mut builder = TableBBuilder::new(_fbb); + if let Some(x) = args.a { builder.add_a(x); } + builder.finish() + } - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - unsafe { <&'a Unused>::follow(buf, loc) } - } - } + pub fn unpack(&self) -> TableBT { + let a = self.a().map(|x| { + alloc::boxed::Box::new(x.unpack()) + }); + TableBT { + a, + } + } - impl<'a> ::flatbuffers::Follow<'a> for &'a Unused { - type Inner = &'a Unused; + #[inline] + pub fn a(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset>(TableB::VT_A, None)} + } +} - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - unsafe { ::flatbuffers::follow_cast_ref::(buf, loc) } - } - } +impl ::flatbuffers::Verifiable for TableB<'_> { + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.visit_table(pos)? + .visit_field::<::flatbuffers::ForwardsUOffset>("a", Self::VT_A, false)? + .finish(); + Ok(()) + } +} +pub struct TableBArgs<'a> { + pub a: Option<::flatbuffers::WIPOffset>>, +} +impl<'a> Default for TableBArgs<'a> { + #[inline] + fn default() -> Self { + TableBArgs { + a: None, + } + } +} - impl<'b> ::flatbuffers::Push for Unused { - type Output = Unused; +pub struct TableBBuilder<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> { + fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, + start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, +} +impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> TableBBuilder<'a, 'b, A> { + #[inline] + pub fn add_a(&mut self, a: ::flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset>(TableB::VT_A, a); + } + #[inline] + pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> TableBBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + TableBBuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> ::flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + ::flatbuffers::WIPOffset::new(o.value()) + } +} - #[inline] - unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { - let src = unsafe { ::core::slice::from_raw_parts(self as *const Unused as *const u8, ::size()) }; - dst.copy_from_slice(src); - } +impl ::core::fmt::Debug for TableB<'_> { + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + let mut ds = f.debug_struct("TableB"); + ds.field("a", &self.a()); + ds.finish() + } +} +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub struct TableBT { + pub a: Option>, +} +impl Default for TableBT { + fn default() -> Self { + Self { + a: None, + } + } +} +impl TableBT { + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> + ) -> ::flatbuffers::WIPOffset> { + let a = self.a.as_ref().map(|x|{ + x.pack(_fbb) + }); + TableB::create(_fbb, &TableBArgs{ + a, + }) + } +} +} // pub mod OtherNameSpace +} // pub mod MyGame - #[inline] - fn alignment() -> ::flatbuffers::PushAlignment { - ::flatbuffers::PushAlignment::new(4) - } - } - - impl<'a> ::flatbuffers::Verifiable for Unused { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.in_buffer::(pos) - } - } - - impl<'a> Unused { - #[allow(clippy::too_many_arguments)] - pub fn new( - a: i32, - ) -> Self { - let mut s = Self([0; 4]); - s.set_a(a); - s - } - - pub const fn get_fully_qualified_name() -> &'static str { - "MyGame.OtherNameSpace.Unused" - } - - pub fn a(&self) -> i32 { - let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - ::flatbuffers::EndianScalar::from_little_endian(unsafe { - ::core::ptr::copy_nonoverlapping( - self.0[0..].as_ptr(), - mem.as_mut_ptr() as *mut u8, - ::core::mem::size_of::<::Scalar>(), - ); - mem.assume_init() - }) - } - - pub fn set_a(&mut self, x: i32) { - let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - unsafe { - ::core::ptr::copy_nonoverlapping( - &x_le as *const _ as *const u8, - self.0[0..].as_mut_ptr(), - ::core::mem::size_of::<::Scalar>(), - ); - } - } - - pub fn unpack(&self) -> UnusedT { - UnusedT { - a: self.a(), - } - } - } - - #[derive(Debug, Clone, PartialEq)] - pub struct UnusedT { - pub a: i32, - } - impl Default for UnusedT { - fn default() -> Self { - Self { - a: 0, - } - } - } - - impl UnusedT { - pub fn pack(&self) -> Unused { - Unused::new( - self.a, - ) - } - } - - pub enum TableBOffset {} - - #[derive(Copy, Clone, PartialEq)] - pub struct TableB<'a> { - pub _tab: ::flatbuffers::Table<'a>, - } - - impl<'a> ::flatbuffers::Follow<'a> for TableB<'a> { - type Inner = TableB<'a>; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } - } - } - - impl<'a> TableB<'a> { - pub const VT_A: ::flatbuffers::VOffsetT = 4; - - pub const fn get_fully_qualified_name() -> &'static str { - "MyGame.OtherNameSpace.TableB" - } - - #[inline] - pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { - TableB { _tab: table } - } - - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args TableBArgs<'args> - ) -> ::flatbuffers::WIPOffset> { - let mut builder = TableBBuilder::new(_fbb); - if let Some(x) = args.a { builder.add_a(x); } - builder.finish() - } - - pub fn unpack(&self) -> TableBT { - let a = self.a().map(|x| { - alloc::boxed::Box::new(x.unpack()) - }); - TableBT { - a, - } - } - - #[inline] - pub fn a(&self) -> Option> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset>(TableB::VT_A, None)} - } - } - - impl ::flatbuffers::Verifiable for TableB<'_> { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.visit_table(pos)? - .visit_field::<::flatbuffers::ForwardsUOffset>("a", Self::VT_A, false)? - .finish(); - Ok(()) - } - } - - pub struct TableBArgs<'a> { - pub a: Option<::flatbuffers::WIPOffset>>, - } - - impl<'a> Default for TableBArgs<'a> { - #[inline] - fn default() -> Self { - TableBArgs { - a: None, - } - } - } - - pub struct TableBBuilder<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> { - fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, - } - - impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> TableBBuilder<'a, 'b, A> { - #[inline] - pub fn add_a(&mut self, a: ::flatbuffers::WIPOffset>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset>(TableB::VT_A, a); - } - - #[inline] - pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> TableBBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - TableBBuilder { - fbb_: _fbb, - start_: start, - } - } - - #[inline] - pub fn finish(self) -> ::flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - ::flatbuffers::WIPOffset::new(o.value()) - } - } - - impl ::core::fmt::Debug for TableB<'_> { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - let mut ds = f.debug_struct("TableB"); - ds.field("a", &self.a()); - ds.finish() - } - } - - #[non_exhaustive] - #[derive(Debug, Clone, PartialEq)] - pub struct TableBT { - pub a: Option>, - } - - impl Default for TableBT { - fn default() -> Self { - Self { - a: None, - } - } - } - - impl TableBT { - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( - &self, - _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> - ) -> ::flatbuffers::WIPOffset> { - let a = self.a.as_ref().map(|x|{ - x.pack(_fbb) - }); - TableB::create(_fbb, &TableBArgs{ - a, - }) - } - } - } // pub mod OtherNameSpace -} // pub mod MyGame diff --git a/tests/keyword_test/keyword_test/abc_generated.rs b/tests/keyword_test/keyword_test/abc_generated.rs index cac583257..43df27b6d 100644 --- a/tests/keyword_test/keyword_test/abc_generated.rs +++ b/tests/keyword_test/keyword_test/abc_generated.rs @@ -2,73 +2,64 @@ // @generated extern crate alloc; use super::*; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] pub const ENUM_MIN_ABC: i32 = 0; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] pub const ENUM_MAX_ABC: i32 = 2; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] #[allow(non_camel_case_types)] pub const ENUM_VALUES_ABC: [ABC; 3] = [ - ABC::void, - ABC::where_, - ABC::stackalloc, + ABC::void, + ABC::where_, + ABC::stackalloc, ]; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] #[repr(transparent)] pub struct ABC(pub i32); - #[allow(non_upper_case_globals)] impl ABC { - pub const void: Self = Self(0); - pub const where_: Self = Self(1); - pub const stackalloc: Self = Self(2); + pub const void: Self = Self(0); + pub const where_: Self = Self(1); + pub const stackalloc: Self = Self(2); - pub const ENUM_MIN: i32 = 0; - pub const ENUM_MAX: i32 = 2; - pub const ENUM_VALUES: &'static [Self] = &[ - Self::void, - Self::where_, - Self::stackalloc, - ]; - - /// Returns the variant's name or "" if unknown. - pub fn variant_name(self) -> Option<&'static str> { - match self { - Self::void => Some("void"), - Self::where_ => Some("where_"), - Self::stackalloc => Some("stackalloc"), - _ => None, - } + pub const ENUM_MIN: i32 = 0; + pub const ENUM_MAX: i32 = 2; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::void, + Self::where_, + Self::stackalloc, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::void => Some("void"), + Self::where_ => Some("where_"), + Self::stackalloc => Some("stackalloc"), + _ => None, } + } } - impl ::core::fmt::Debug for ABC { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - if let Some(name) = self.variant_name() { - f.write_str(name) - } else { - f.write_fmt(format_args!("", self.0)) - } + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) } + } } - impl<'a> ::flatbuffers::Follow<'a> for ABC { - type Inner = Self; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; - Self(b) - } + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; + Self(b) + } } impl ::flatbuffers::Push for ABC { type Output = ABC; - #[inline] unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { unsafe { ::flatbuffers::emplace_scalar::(dst, self.0) }; @@ -76,28 +67,26 @@ impl ::flatbuffers::Push for ABC { } impl ::flatbuffers::EndianScalar for ABC { - type Scalar = i32; - - #[inline] - fn to_little_endian(self) -> i32 { - self.0.to_le() - } - - #[inline] - #[allow(clippy::wrong_self_convention)] - fn from_little_endian(v: i32) -> Self { - let b = i32::from_le(v); - Self(b) - } + type Scalar = i32; + #[inline] + fn to_little_endian(self) -> i32 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: i32) -> Self { + let b = i32::from_le(v); + Self(b) + } } impl<'a> ::flatbuffers::Verifiable for ABC { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - i32::run_verifier(v, pos) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + i32::run_verifier(v, pos) + } } impl ::flatbuffers::SimpleToVerifyInSlice for ABC {} diff --git a/tests/keyword_test/keyword_test/keywords_in_table_generated.rs b/tests/keyword_test/keyword_test/keywords_in_table_generated.rs index c8dc45612..1ff91e100 100644 --- a/tests/keyword_test/keyword_test/keywords_in_table_generated.rs +++ b/tests/keyword_test/keyword_test/keywords_in_table_generated.rs @@ -2,218 +2,201 @@ // @generated extern crate alloc; use super::*; - pub enum KeywordsInTableOffset {} - #[derive(Copy, Clone, PartialEq)] + pub struct KeywordsInTable<'a> { - pub _tab: ::flatbuffers::Table<'a>, + pub _tab: ::flatbuffers::Table<'a>, } impl<'a> ::flatbuffers::Follow<'a> for KeywordsInTable<'a> { - type Inner = KeywordsInTable<'a>; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } - } + type Inner = KeywordsInTable<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } + } } impl<'a> KeywordsInTable<'a> { - pub const VT_IS: ::flatbuffers::VOffsetT = 4; - pub const VT_PRIVATE: ::flatbuffers::VOffsetT = 6; - pub const VT_TYPE_: ::flatbuffers::VOffsetT = 8; - pub const VT_DEFAULT: ::flatbuffers::VOffsetT = 10; + pub const VT_IS: ::flatbuffers::VOffsetT = 4; + pub const VT_PRIVATE: ::flatbuffers::VOffsetT = 6; + pub const VT_TYPE_: ::flatbuffers::VOffsetT = 8; + pub const VT_DEFAULT: ::flatbuffers::VOffsetT = 10; - pub const fn get_fully_qualified_name() -> &'static str { - "KeywordTest.KeywordsInTable" - } + pub const fn get_fully_qualified_name() -> &'static str { + "KeywordTest.KeywordsInTable" + } - #[inline] - pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { - KeywordsInTable { _tab: table } - } + #[inline] + pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { + KeywordsInTable { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args KeywordsInTableArgs + ) -> ::flatbuffers::WIPOffset> { + let mut builder = KeywordsInTableBuilder::new(_fbb); + builder.add_type_(args.type_); + builder.add_private(args.private); + builder.add_is(args.is); + builder.add_default(args.default); + builder.finish() + } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args KeywordsInTableArgs - ) -> ::flatbuffers::WIPOffset> { - let mut builder = KeywordsInTableBuilder::new(_fbb); - builder.add_type_(args.type_); - builder.add_private(args.private); - builder.add_is(args.is); - builder.add_default(args.default); - builder.finish() + pub fn unpack(&self) -> KeywordsInTableT { + let is = self.is(); + let private = self.private(); + let type_ = self.type_(); + let default = self.default(); + KeywordsInTableT { + is, + private, + type_, + default, } + } - pub fn unpack(&self) -> KeywordsInTableT { - let is = self.is(); - let private = self.private(); - let type_ = self.type_(); - let default = self.default(); - KeywordsInTableT { - is, - private, - type_, - default, - } - } - - #[inline] - pub fn is(&self) -> ABC { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(KeywordsInTable::VT_IS, Some(ABC::void)).unwrap()} - } - - #[inline] - pub fn private(&self) -> public { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(KeywordsInTable::VT_PRIVATE, Some(public::NONE)).unwrap()} - } - - #[inline] - pub fn type_(&self) -> i32 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(KeywordsInTable::VT_TYPE_, Some(0)).unwrap()} - } - - #[inline] - pub fn default(&self) -> bool { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(KeywordsInTable::VT_DEFAULT, Some(false)).unwrap()} - } + #[inline] + pub fn is(&self) -> ABC { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(KeywordsInTable::VT_IS, Some(ABC::void)).unwrap()} + } + #[inline] + pub fn private(&self) -> public { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(KeywordsInTable::VT_PRIVATE, Some(public::NONE)).unwrap()} + } + #[inline] + pub fn type_(&self) -> i32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(KeywordsInTable::VT_TYPE_, Some(0)).unwrap()} + } + #[inline] + pub fn default(&self) -> bool { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(KeywordsInTable::VT_DEFAULT, Some(false)).unwrap()} + } } impl ::flatbuffers::Verifiable for KeywordsInTable<'_> { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.visit_table(pos)? - .visit_field::("is", Self::VT_IS, false)? - .visit_field::("private", Self::VT_PRIVATE, false)? - .visit_field::("type_", Self::VT_TYPE_, false)? - .visit_field::("default", Self::VT_DEFAULT, false)? - .finish(); - Ok(()) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.visit_table(pos)? + .visit_field::("is", Self::VT_IS, false)? + .visit_field::("private", Self::VT_PRIVATE, false)? + .visit_field::("type_", Self::VT_TYPE_, false)? + .visit_field::("default", Self::VT_DEFAULT, false)? + .finish(); + Ok(()) + } } - pub struct KeywordsInTableArgs { pub is: ABC, pub private: public, pub type_: i32, pub default: bool, } - impl<'a> Default for KeywordsInTableArgs { - #[inline] - fn default() -> Self { - KeywordsInTableArgs { - is: ABC::void, - private: public::NONE, - type_: 0, - default: false, - } + #[inline] + fn default() -> Self { + KeywordsInTableArgs { + is: ABC::void, + private: public::NONE, + type_: 0, + default: false, } + } } pub struct KeywordsInTableBuilder<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> { - fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, + fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, + start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, } - impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> KeywordsInTableBuilder<'a, 'b, A> { - #[inline] - pub fn add_is(&mut self, is: ABC) { - self.fbb_.push_slot::(KeywordsInTable::VT_IS, is, ABC::void); - } - - #[inline] - pub fn add_private(&mut self, private: public) { - self.fbb_.push_slot::(KeywordsInTable::VT_PRIVATE, private, public::NONE); - } - - #[inline] - pub fn add_type_(&mut self, type_: i32) { - self.fbb_.push_slot::(KeywordsInTable::VT_TYPE_, type_, 0); - } - - #[inline] - pub fn add_default(&mut self, default: bool) { - self.fbb_.push_slot::(KeywordsInTable::VT_DEFAULT, default, false); - } - - #[inline] - pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> KeywordsInTableBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - KeywordsInTableBuilder { - fbb_: _fbb, - start_: start, - } - } - - #[inline] - pub fn finish(self) -> ::flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - ::flatbuffers::WIPOffset::new(o.value()) + #[inline] + pub fn add_is(&mut self, is: ABC) { + self.fbb_.push_slot::(KeywordsInTable::VT_IS, is, ABC::void); + } + #[inline] + pub fn add_private(&mut self, private: public) { + self.fbb_.push_slot::(KeywordsInTable::VT_PRIVATE, private, public::NONE); + } + #[inline] + pub fn add_type_(&mut self, type_: i32) { + self.fbb_.push_slot::(KeywordsInTable::VT_TYPE_, type_, 0); + } + #[inline] + pub fn add_default(&mut self, default: bool) { + self.fbb_.push_slot::(KeywordsInTable::VT_DEFAULT, default, false); + } + #[inline] + pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> KeywordsInTableBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + KeywordsInTableBuilder { + fbb_: _fbb, + start_: start, } + } + #[inline] + pub fn finish(self) -> ::flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + ::flatbuffers::WIPOffset::new(o.value()) + } } impl ::core::fmt::Debug for KeywordsInTable<'_> { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - let mut ds = f.debug_struct("KeywordsInTable"); - ds.field("is", &self.is()); - ds.field("private", &self.private()); - ds.field("type_", &self.type_()); - ds.field("default", &self.default()); - ds.finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + let mut ds = f.debug_struct("KeywordsInTable"); + ds.field("is", &self.is()); + ds.field("private", &self.private()); + ds.field("type_", &self.type_()); + ds.field("default", &self.default()); + ds.finish() + } } - #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub struct KeywordsInTableT { - pub is: ABC, - pub private: public, - pub type_: i32, - pub default: bool, + pub is: ABC, + pub private: public, + pub type_: i32, + pub default: bool, } - impl Default for KeywordsInTableT { - fn default() -> Self { - Self { - is: ABC::void, - private: public::NONE, - type_: 0, - default: false, - } + fn default() -> Self { + Self { + is: ABC::void, + private: public::NONE, + type_: 0, + default: false, } + } } - impl KeywordsInTableT { - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( - &self, - _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> - ) -> ::flatbuffers::WIPOffset> { - let is = self.is; - let private = self.private; - let type_ = self.type_; - let default = self.default; - KeywordsInTable::create(_fbb, &KeywordsInTableArgs{ - is, - private, - type_, - default, - }) - } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> + ) -> ::flatbuffers::WIPOffset> { + let is = self.is; + let private = self.private; + let type_ = self.type_; + let default = self.default; + KeywordsInTable::create(_fbb, &KeywordsInTableArgs{ + is, + private, + type_, + default, + }) + } } diff --git a/tests/keyword_test/keyword_test/keywords_in_union_generated.rs b/tests/keyword_test/keyword_test/keywords_in_union_generated.rs index 5ac7f3ecd..88dac0ec6 100644 --- a/tests/keyword_test/keyword_test/keywords_in_union_generated.rs +++ b/tests/keyword_test/keyword_test/keywords_in_union_generated.rs @@ -2,73 +2,64 @@ // @generated extern crate alloc; use super::*; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] pub const ENUM_MIN_KEYWORDS_IN_UNION: u8 = 0; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] pub const ENUM_MAX_KEYWORDS_IN_UNION: u8 = 2; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] #[allow(non_camel_case_types)] pub const ENUM_VALUES_KEYWORDS_IN_UNION: [KeywordsInUnion; 3] = [ - KeywordsInUnion::NONE, - KeywordsInUnion::static_, - KeywordsInUnion::internal, + KeywordsInUnion::NONE, + KeywordsInUnion::static_, + KeywordsInUnion::internal, ]; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] #[repr(transparent)] pub struct KeywordsInUnion(pub u8); - #[allow(non_upper_case_globals)] impl KeywordsInUnion { - pub const NONE: Self = Self(0); - pub const static_: Self = Self(1); - pub const internal: Self = Self(2); + pub const NONE: Self = Self(0); + pub const static_: Self = Self(1); + pub const internal: Self = Self(2); - pub const ENUM_MIN: u8 = 0; - pub const ENUM_MAX: u8 = 2; - pub const ENUM_VALUES: &'static [Self] = &[ - Self::NONE, - Self::static_, - Self::internal, - ]; - - /// Returns the variant's name or "" if unknown. - pub fn variant_name(self) -> Option<&'static str> { - match self { - Self::NONE => Some("NONE"), - Self::static_ => Some("static_"), - Self::internal => Some("internal"), - _ => None, - } + pub const ENUM_MIN: u8 = 0; + pub const ENUM_MAX: u8 = 2; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::NONE, + Self::static_, + Self::internal, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::NONE => Some("NONE"), + Self::static_ => Some("static_"), + Self::internal => Some("internal"), + _ => None, } + } } - impl ::core::fmt::Debug for KeywordsInUnion { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - if let Some(name) = self.variant_name() { - f.write_str(name) - } else { - f.write_fmt(format_args!("", self.0)) - } + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) } + } } - impl<'a> ::flatbuffers::Follow<'a> for KeywordsInUnion { - type Inner = Self; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; - Self(b) - } + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; + Self(b) + } } impl ::flatbuffers::Push for KeywordsInUnion { type Output = KeywordsInUnion; - #[inline] unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { unsafe { ::flatbuffers::emplace_scalar::(dst, self.0) }; @@ -76,112 +67,99 @@ impl ::flatbuffers::Push for KeywordsInUnion { } impl ::flatbuffers::EndianScalar for KeywordsInUnion { - type Scalar = u8; - - #[inline] - fn to_little_endian(self) -> u8 { - self.0.to_le() - } - - #[inline] - #[allow(clippy::wrong_self_convention)] - fn from_little_endian(v: u8) -> Self { - let b = u8::from_le(v); - Self(b) - } + type Scalar = u8; + #[inline] + fn to_little_endian(self) -> u8 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: u8) -> Self { + let b = u8::from_le(v); + Self(b) + } } impl<'a> ::flatbuffers::Verifiable for KeywordsInUnion { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - u8::run_verifier(v, pos) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + u8::run_verifier(v, pos) + } } impl ::flatbuffers::SimpleToVerifyInSlice for KeywordsInUnion {} - pub struct KeywordsInUnionUnionTableOffset {} #[allow(clippy::upper_case_acronyms)] #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub enum KeywordsInUnionT { - NONE, - Static_(alloc::boxed::Box), - Internal(alloc::boxed::Box), + NONE, + Static_(alloc::boxed::Box), + Internal(alloc::boxed::Box), } - impl Default for KeywordsInUnionT { - fn default() -> Self { - Self::NONE - } + fn default() -> Self { + Self::NONE + } } - impl KeywordsInUnionT { - pub fn keywords_in_union_type(&self) -> KeywordsInUnion { - match self { - Self::NONE => KeywordsInUnion::NONE, - Self::Static_(_) => KeywordsInUnion::static_, - Self::Internal(_) => KeywordsInUnion::internal, - } + pub fn keywords_in_union_type(&self) -> KeywordsInUnion { + match self { + Self::NONE => KeywordsInUnion::NONE, + Self::Static_(_) => KeywordsInUnion::static_, + Self::Internal(_) => KeywordsInUnion::internal, } - - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>(&self, fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A>) -> Option<::flatbuffers::WIPOffset<::flatbuffers::UnionWIPOffset>> { - match self { - Self::NONE => None, - Self::Static_(v) => Some(v.pack(fbb).as_union_value()), - Self::Internal(v) => Some(v.pack(fbb).as_union_value()), - } + } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>(&self, fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A>) -> Option<::flatbuffers::WIPOffset<::flatbuffers::UnionWIPOffset>> { + match self { + Self::NONE => None, + Self::Static_(v) => Some(v.pack(fbb).as_union_value()), + Self::Internal(v) => Some(v.pack(fbb).as_union_value()), } - - /// If the union variant matches, return the owned KeywordsInTableT, setting the union to NONE. - pub fn take_static_(&mut self) -> Option> { - if let Self::Static_(_) = self { - let v = ::core::mem::replace(self, Self::NONE); - if let Self::Static_(w) = v { - Some(w) - } else { - unreachable!() - } - } else { - None - } + } + /// If the union variant matches, return the owned KeywordsInTableT, setting the union to NONE. + pub fn take_static_(&mut self) -> Option> { + if let Self::Static_(_) = self { + let v = ::core::mem::replace(self, Self::NONE); + if let Self::Static_(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None } - - /// If the union variant matches, return a reference to the KeywordsInTableT. - pub fn as_static_(&self) -> Option<&KeywordsInTableT> { - if let Self::Static_(v) = self { Some(v.as_ref()) } else { None } - } - - /// If the union variant matches, return a mutable reference to the KeywordsInTableT. - pub fn as_static__mut(&mut self) -> Option<&mut KeywordsInTableT> { - if let Self::Static_(v) = self { Some(v.as_mut()) } else { None } - } - - /// If the union variant matches, return the owned KeywordsInTableT, setting the union to NONE. - pub fn take_internal(&mut self) -> Option> { - if let Self::Internal(_) = self { - let v = ::core::mem::replace(self, Self::NONE); - if let Self::Internal(w) = v { - Some(w) - } else { - unreachable!() - } - } else { - None - } - } - - /// If the union variant matches, return a reference to the KeywordsInTableT. - pub fn as_internal(&self) -> Option<&KeywordsInTableT> { - if let Self::Internal(v) = self { Some(v.as_ref()) } else { None } - } - - /// If the union variant matches, return a mutable reference to the KeywordsInTableT. - pub fn as_internal_mut(&mut self) -> Option<&mut KeywordsInTableT> { - if let Self::Internal(v) = self { Some(v.as_mut()) } else { None } + } + /// If the union variant matches, return a reference to the KeywordsInTableT. + pub fn as_static_(&self) -> Option<&KeywordsInTableT> { + if let Self::Static_(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the KeywordsInTableT. + pub fn as_static__mut(&mut self) -> Option<&mut KeywordsInTableT> { + if let Self::Static_(v) = self { Some(v.as_mut()) } else { None } + } + /// If the union variant matches, return the owned KeywordsInTableT, setting the union to NONE. + pub fn take_internal(&mut self) -> Option> { + if let Self::Internal(_) = self { + let v = ::core::mem::replace(self, Self::NONE); + if let Self::Internal(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None } + } + /// If the union variant matches, return a reference to the KeywordsInTableT. + pub fn as_internal(&self) -> Option<&KeywordsInTableT> { + if let Self::Internal(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the KeywordsInTableT. + pub fn as_internal_mut(&mut self) -> Option<&mut KeywordsInTableT> { + if let Self::Internal(v) = self { Some(v.as_mut()) } else { None } + } } - diff --git a/tests/keyword_test/keyword_test/public_generated.rs b/tests/keyword_test/keyword_test/public_generated.rs index 0799d68b2..be9570cc4 100644 --- a/tests/keyword_test/keyword_test/public_generated.rs +++ b/tests/keyword_test/keyword_test/public_generated.rs @@ -2,65 +2,56 @@ // @generated extern crate alloc; use super::*; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] pub const ENUM_MIN_PUBLIC: i32 = 0; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] pub const ENUM_MAX_PUBLIC: i32 = 0; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] #[allow(non_camel_case_types)] pub const ENUM_VALUES_PUBLIC: [public; 1] = [ - public::NONE, + public::NONE, ]; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] #[repr(transparent)] pub struct public(pub i32); - #[allow(non_upper_case_globals)] impl public { - pub const NONE: Self = Self(0); + pub const NONE: Self = Self(0); - pub const ENUM_MIN: i32 = 0; - pub const ENUM_MAX: i32 = 0; - pub const ENUM_VALUES: &'static [Self] = &[ - Self::NONE, - ]; - - /// Returns the variant's name or "" if unknown. - pub fn variant_name(self) -> Option<&'static str> { - match self { - Self::NONE => Some("NONE"), - _ => None, - } + pub const ENUM_MIN: i32 = 0; + pub const ENUM_MAX: i32 = 0; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::NONE, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::NONE => Some("NONE"), + _ => None, } + } } - impl ::core::fmt::Debug for public { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - if let Some(name) = self.variant_name() { - f.write_str(name) - } else { - f.write_fmt(format_args!("", self.0)) - } + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) } + } } - impl<'a> ::flatbuffers::Follow<'a> for public { - type Inner = Self; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; - Self(b) - } + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; + Self(b) + } } impl ::flatbuffers::Push for public { type Output = public; - #[inline] unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { unsafe { ::flatbuffers::emplace_scalar::(dst, self.0) }; @@ -68,28 +59,26 @@ impl ::flatbuffers::Push for public { } impl ::flatbuffers::EndianScalar for public { - type Scalar = i32; - - #[inline] - fn to_little_endian(self) -> i32 { - self.0.to_le() - } - - #[inline] - #[allow(clippy::wrong_self_convention)] - fn from_little_endian(v: i32) -> Self { - let b = i32::from_le(v); - Self(b) - } + type Scalar = i32; + #[inline] + fn to_little_endian(self) -> i32 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: i32) -> Self { + let b = i32::from_le(v); + Self(b) + } } impl<'a> ::flatbuffers::Verifiable for public { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - i32::run_verifier(v, pos) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + i32::run_verifier(v, pos) + } } impl ::flatbuffers::SimpleToVerifyInSlice for public {} diff --git a/tests/keyword_test/keyword_test/table_2_generated.rs b/tests/keyword_test/keyword_test/table_2_generated.rs index 219ba405e..a8e72bd4d 100644 --- a/tests/keyword_test/keyword_test/table_2_generated.rs +++ b/tests/keyword_test/keyword_test/table_2_generated.rs @@ -2,231 +2,218 @@ // @generated extern crate alloc; use super::*; - pub enum Table2Offset {} - #[derive(Copy, Clone, PartialEq)] + pub struct Table2<'a> { - pub _tab: ::flatbuffers::Table<'a>, + pub _tab: ::flatbuffers::Table<'a>, } impl<'a> ::flatbuffers::Follow<'a> for Table2<'a> { - type Inner = Table2<'a>; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } - } + type Inner = Table2<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } + } } impl<'a> Table2<'a> { - pub const VT_TYPE_TYPE: ::flatbuffers::VOffsetT = 4; - pub const VT_TYPE_: ::flatbuffers::VOffsetT = 6; + pub const VT_TYPE_TYPE: ::flatbuffers::VOffsetT = 4; + pub const VT_TYPE_: ::flatbuffers::VOffsetT = 6; - pub const fn get_fully_qualified_name() -> &'static str { - "KeywordTest.Table2" - } + pub const fn get_fully_qualified_name() -> &'static str { + "KeywordTest.Table2" + } - #[inline] - pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { - Table2 { _tab: table } - } + #[inline] + pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { + Table2 { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args Table2Args + ) -> ::flatbuffers::WIPOffset> { + let mut builder = Table2Builder::new(_fbb); + if let Some(x) = args.type_ { builder.add_type_(x); } + builder.add_type_type(args.type_type); + builder.finish() + } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args Table2Args - ) -> ::flatbuffers::WIPOffset> { - let mut builder = Table2Builder::new(_fbb); - if let Some(x) = args.type_ { builder.add_type_(x); } - builder.add_type_type(args.type_type); - builder.finish() + pub fn unpack(&self) -> Table2T { + let type_ = match self.type_type() { + KeywordsInUnion::NONE => KeywordsInUnionT::NONE, + KeywordsInUnion::static_ => KeywordsInUnionT::Static_(alloc::boxed::Box::new( + self.type__as_static_() + .expect("Invalid union table, expected `KeywordsInUnion::static_`.") + .unpack() + )), + KeywordsInUnion::internal => KeywordsInUnionT::Internal(alloc::boxed::Box::new( + self.type__as_internal() + .expect("Invalid union table, expected `KeywordsInUnion::internal`.") + .unpack() + )), + _ => KeywordsInUnionT::NONE, + }; + Table2T { + type_, } + } - pub fn unpack(&self) -> Table2T { - let type_ = match self.type_type() { - KeywordsInUnion::NONE => KeywordsInUnionT::NONE, - KeywordsInUnion::static_ => KeywordsInUnionT::Static_(alloc::boxed::Box::new( - self.type__as_static_() - .expect("Invalid union table, expected `KeywordsInUnion::static_`.") - .unpack() - )), - KeywordsInUnion::internal => KeywordsInUnionT::Internal(alloc::boxed::Box::new( - self.type__as_internal() - .expect("Invalid union table, expected `KeywordsInUnion::internal`.") - .unpack() - )), - _ => KeywordsInUnionT::NONE, - }; - Table2T { - type_, - } + #[inline] + pub fn type_type(&self) -> KeywordsInUnion { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Table2::VT_TYPE_TYPE, Some(KeywordsInUnion::NONE)).unwrap()} + } + #[inline] + pub fn type_(&self) -> Option<::flatbuffers::Table<'a>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Table<'a>>>(Table2::VT_TYPE_, None)} + } + #[inline] + #[allow(non_snake_case)] + pub fn type__as_static_(&self) -> Option> { + if self.type_type() == KeywordsInUnion::static_ { + self.type_().map(|t| { + // Safety: + // Created from a valid Table for this object + // Which contains a valid union in this slot + unsafe { KeywordsInTable::init_from_table(t) } + }) + } else { + None } + } - #[inline] - pub fn type_type(&self) -> KeywordsInUnion { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Table2::VT_TYPE_TYPE, Some(KeywordsInUnion::NONE)).unwrap()} + #[inline] + #[allow(non_snake_case)] + pub fn type__as_internal(&self) -> Option> { + if self.type_type() == KeywordsInUnion::internal { + self.type_().map(|t| { + // Safety: + // Created from a valid Table for this object + // Which contains a valid union in this slot + unsafe { KeywordsInTable::init_from_table(t) } + }) + } else { + None } + } - #[inline] - pub fn type_(&self) -> Option<::flatbuffers::Table<'a>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Table<'a>>>(Table2::VT_TYPE_, None)} - } - - #[inline] - #[allow(non_snake_case)] - pub fn type__as_static_(&self) -> Option> { - if self.type_type() == KeywordsInUnion::static_ { - self.type_().map(|t| { - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - unsafe { KeywordsInTable::init_from_table(t) } - }) - } else { - None - } - } - - #[inline] - #[allow(non_snake_case)] - pub fn type__as_internal(&self) -> Option> { - if self.type_type() == KeywordsInUnion::internal { - self.type_().map(|t| { - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - unsafe { KeywordsInTable::init_from_table(t) } - }) - } else { - None - } - } } impl ::flatbuffers::Verifiable for Table2<'_> { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.visit_table(pos)? - .visit_union::("type_type", Self::VT_TYPE_TYPE, "type_", Self::VT_TYPE_, false, |key, v, pos| { - match key { - KeywordsInUnion::static_ => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("KeywordsInUnion::static_", pos), - KeywordsInUnion::internal => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("KeywordsInUnion::internal", pos), - _ => Ok(()), - } - })? - .finish(); - Ok(()) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.visit_table(pos)? + .visit_union::("type_type", Self::VT_TYPE_TYPE, "type_", Self::VT_TYPE_, false, |key, v, pos| { + match key { + KeywordsInUnion::static_ => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("KeywordsInUnion::static_", pos), + KeywordsInUnion::internal => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("KeywordsInUnion::internal", pos), + _ => Ok(()), + } + })? + .finish(); + Ok(()) + } } - pub struct Table2Args { pub type_type: KeywordsInUnion, pub type_: Option<::flatbuffers::WIPOffset<::flatbuffers::UnionWIPOffset>>, } - impl<'a> Default for Table2Args { - #[inline] - fn default() -> Self { - Table2Args { - type_type: KeywordsInUnion::NONE, - type_: None, - } + #[inline] + fn default() -> Self { + Table2Args { + type_type: KeywordsInUnion::NONE, + type_: None, } + } } pub struct Table2Builder<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> { - fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, + fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, + start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, } - impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> Table2Builder<'a, 'b, A> { - #[inline] - pub fn add_type_type(&mut self, type_type: KeywordsInUnion) { - self.fbb_.push_slot::(Table2::VT_TYPE_TYPE, type_type, KeywordsInUnion::NONE); - } - - #[inline] - pub fn add_type_(&mut self, type_: ::flatbuffers::WIPOffset<::flatbuffers::UnionWIPOffset>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Table2::VT_TYPE_, type_); - } - - #[inline] - pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> Table2Builder<'a, 'b, A> { - let start = _fbb.start_table(); - Table2Builder { - fbb_: _fbb, - start_: start, - } - } - - #[inline] - pub fn finish(self) -> ::flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - ::flatbuffers::WIPOffset::new(o.value()) + #[inline] + pub fn add_type_type(&mut self, type_type: KeywordsInUnion) { + self.fbb_.push_slot::(Table2::VT_TYPE_TYPE, type_type, KeywordsInUnion::NONE); + } + #[inline] + pub fn add_type_(&mut self, type_: ::flatbuffers::WIPOffset<::flatbuffers::UnionWIPOffset>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Table2::VT_TYPE_, type_); + } + #[inline] + pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> Table2Builder<'a, 'b, A> { + let start = _fbb.start_table(); + Table2Builder { + fbb_: _fbb, + start_: start, } + } + #[inline] + pub fn finish(self) -> ::flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + ::flatbuffers::WIPOffset::new(o.value()) + } } impl ::core::fmt::Debug for Table2<'_> { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - let mut ds = f.debug_struct("Table2"); - ds.field("type_type", &self.type_type()); - match self.type_type() { - KeywordsInUnion::static_ => { - if let Some(x) = self.type__as_static_() { - ds.field("type_", &x) - } else { - ds.field("type_", &"InvalidFlatbuffer: Union discriminant does not match value.") - } - }, - KeywordsInUnion::internal => { - if let Some(x) = self.type__as_internal() { - ds.field("type_", &x) - } else { - ds.field("type_", &"InvalidFlatbuffer: Union discriminant does not match value.") - } - }, - _ => { - let x: Option<()> = None; - ds.field("type_", &x) - }, - }; - ds.finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + let mut ds = f.debug_struct("Table2"); + ds.field("type_type", &self.type_type()); + match self.type_type() { + KeywordsInUnion::static_ => { + if let Some(x) = self.type__as_static_() { + ds.field("type_", &x) + } else { + ds.field("type_", &"InvalidFlatbuffer: Union discriminant does not match value.") + } + }, + KeywordsInUnion::internal => { + if let Some(x) = self.type__as_internal() { + ds.field("type_", &x) + } else { + ds.field("type_", &"InvalidFlatbuffer: Union discriminant does not match value.") + } + }, + _ => { + let x: Option<()> = None; + ds.field("type_", &x) + }, + }; + ds.finish() + } } - #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub struct Table2T { - pub type_: KeywordsInUnionT, + pub type_: KeywordsInUnionT, } - impl Default for Table2T { - fn default() -> Self { - Self { - type_: KeywordsInUnionT::NONE, - } + fn default() -> Self { + Self { + type_: KeywordsInUnionT::NONE, } + } } - impl Table2T { - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( - &self, - _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> - ) -> ::flatbuffers::WIPOffset> { - let type_type = self.type_.keywords_in_union_type(); - let type_ = self.type_.pack(_fbb); - Table2::create(_fbb, &Table2Args{ - type_type, - type_, - }) - } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> + ) -> ::flatbuffers::WIPOffset> { + let type_type = self.type_.keywords_in_union_type(); + let type_ = self.type_.pack(_fbb); + Table2::create(_fbb, &Table2Args{ + type_type, + type_, + }) + } } diff --git a/tests/keyword_test/mod.rs b/tests/keyword_test/mod.rs index b0b522ecd..56f68c40d 100644 --- a/tests/keyword_test/mod.rs +++ b/tests/keyword_test/mod.rs @@ -1,15 +1,15 @@ // Automatically generated by the Flatbuffers compiler. Do not modify. // @generated pub mod keyword_test { - use super::*; - mod abc_generated; - pub use self::abc_generated::*; - mod public_generated; - pub use self::public_generated::*; - mod keywords_in_union_generated; - pub use self::keywords_in_union_generated::*; - mod keywords_in_table_generated; - pub use self::keywords_in_table_generated::*; - mod table_2_generated; - pub use self::table_2_generated::*; + use super::*; + mod abc_generated; + pub use self::abc_generated::*; + mod public_generated; + pub use self::public_generated::*; + mod keywords_in_union_generated; + pub use self::keywords_in_union_generated::*; + mod keywords_in_table_generated; + pub use self::keywords_in_table_generated::*; + mod table_2_generated; + pub use self::table_2_generated::*; } // keyword_test diff --git a/tests/monster_test/mod.rs b/tests/monster_test/mod.rs index 27af0f287..7f1fab136 100644 --- a/tests/monster_test/mod.rs +++ b/tests/monster_test/mod.rs @@ -1,58 +1,58 @@ // Automatically generated by the Flatbuffers compiler. Do not modify. // @generated pub mod my_game { + use super::*; + pub mod example { use super::*; - pub mod example { - use super::*; - mod color_generated; - pub use self::color_generated::*; - mod race_generated; - pub use self::race_generated::*; - mod long_enum_generated; - pub use self::long_enum_generated::*; - mod any_generated; - pub use self::any_generated::*; - mod any_unique_aliases_generated; - pub use self::any_unique_aliases_generated::*; - mod any_ambiguous_aliases_generated; - pub use self::any_ambiguous_aliases_generated::*; - mod test_generated; - pub use self::test_generated::*; - mod test_simple_table_with_enum_generated; - pub use self::test_simple_table_with_enum_generated::*; - mod vec_3_generated; - pub use self::vec_3_generated::*; - mod ability_generated; - pub use self::ability_generated::*; - mod struct_of_structs_generated; - pub use self::struct_of_structs_generated::*; - mod struct_of_structs_of_structs_generated; - pub use self::struct_of_structs_of_structs_generated::*; - mod stat_generated; - pub use self::stat_generated::*; - mod referrable_generated; - pub use self::referrable_generated::*; - mod monster_generated; - pub use self::monster_generated::*; - mod type_aliases_generated; - pub use self::type_aliases_generated::*; - } // example - pub mod example_2 { - use super::*; - mod monster_generated; - pub use self::monster_generated::*; - } // example_2 - pub mod other_name_space { - use super::*; - mod from_include_generated; - pub use self::from_include_generated::*; - mod unused_generated; - pub use self::unused_generated::*; - mod table_b_generated; - pub use self::table_b_generated::*; - } // other_name_space - mod in_parent_namespace_generated; - pub use self::in_parent_namespace_generated::*; + mod color_generated; + pub use self::color_generated::*; + mod race_generated; + pub use self::race_generated::*; + mod long_enum_generated; + pub use self::long_enum_generated::*; + mod any_generated; + pub use self::any_generated::*; + mod any_unique_aliases_generated; + pub use self::any_unique_aliases_generated::*; + mod any_ambiguous_aliases_generated; + pub use self::any_ambiguous_aliases_generated::*; + mod test_generated; + pub use self::test_generated::*; + mod test_simple_table_with_enum_generated; + pub use self::test_simple_table_with_enum_generated::*; + mod vec_3_generated; + pub use self::vec_3_generated::*; + mod ability_generated; + pub use self::ability_generated::*; + mod struct_of_structs_generated; + pub use self::struct_of_structs_generated::*; + mod struct_of_structs_of_structs_generated; + pub use self::struct_of_structs_of_structs_generated::*; + mod stat_generated; + pub use self::stat_generated::*; + mod referrable_generated; + pub use self::referrable_generated::*; + mod monster_generated; + pub use self::monster_generated::*; + mod type_aliases_generated; + pub use self::type_aliases_generated::*; + } // example + pub mod example_2 { + use super::*; + mod monster_generated; + pub use self::monster_generated::*; + } // example_2 + pub mod other_name_space { + use super::*; + mod from_include_generated; + pub use self::from_include_generated::*; + mod unused_generated; + pub use self::unused_generated::*; + mod table_b_generated; + pub use self::table_b_generated::*; + } // other_name_space + mod in_parent_namespace_generated; + pub use self::in_parent_namespace_generated::*; } // my_game mod table_a_generated; pub use self::table_a_generated::*; diff --git a/tests/monster_test/my_game/example/ability_generated.rs b/tests/monster_test/my_game/example/ability_generated.rs index df8c8a6e6..add3b4701 100644 --- a/tests/monster_test/my_game/example/ability_generated.rs +++ b/tests/monster_test/my_game/example/ability_generated.rs @@ -2,56 +2,46 @@ // @generated extern crate alloc; use super::*; - // struct Ability, aligned to 4 #[repr(transparent)] #[derive(Clone, Copy, PartialEq)] pub struct Ability(pub [u8; 8]); - -impl Default for Ability { - fn default() -> Self { - Self([0; 8]) - } +impl Default for Ability { + fn default() -> Self { + Self([0; 8]) + } } - impl ::core::fmt::Debug for Ability { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - f.debug_struct("Ability") - .field("id", &self.id()) - .field("distance", &self.distance()) - .finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + f.debug_struct("Ability") + .field("id", &self.id()) + .field("distance", &self.distance()) + .finish() + } } impl ::flatbuffers::SimpleToVerifyInSlice for Ability {} - impl<'a> ::flatbuffers::Follow<'a> for Ability { - type Inner = &'a Ability; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - unsafe { <&'a Ability>::follow(buf, loc) } - } + type Inner = &'a Ability; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { <&'a Ability>::follow(buf, loc) } + } } - impl<'a> ::flatbuffers::Follow<'a> for &'a Ability { - type Inner = &'a Ability; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - unsafe { ::flatbuffers::follow_cast_ref::(buf, loc) } - } + type Inner = &'a Ability; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { ::flatbuffers::follow_cast_ref::(buf, loc) } + } } - impl<'b> ::flatbuffers::Push for Ability { type Output = Ability; - #[inline] unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { let src = unsafe { ::core::slice::from_raw_parts(self as *const Ability as *const u8, ::size()) }; dst.copy_from_slice(src); } - #[inline] fn alignment() -> ::flatbuffers::PushAlignment { ::flatbuffers::PushAlignment::new(4) @@ -59,126 +49,117 @@ impl<'b> ::flatbuffers::Push for Ability { } impl<'a> ::flatbuffers::Verifiable for Ability { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.in_buffer::(pos) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.in_buffer::(pos) + } } impl<'a> Ability { - #[allow(clippy::too_many_arguments)] - pub fn new( - id: u32, - distance: u32, - ) -> Self { - let mut s = Self([0; 8]); - s.set_id(id); - s.set_distance(distance); - s - } + #[allow(clippy::too_many_arguments)] + pub fn new( + id: u32, + distance: u32, + ) -> Self { + let mut s = Self([0; 8]); + s.set_id(id); + s.set_distance(distance); + s + } - pub const fn get_fully_qualified_name() -> &'static str { - "MyGame.Example.Ability" - } + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Example.Ability" + } - pub fn id(&self) -> u32 { - let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - ::flatbuffers::EndianScalar::from_little_endian(unsafe { - ::core::ptr::copy_nonoverlapping( - self.0[0..].as_ptr(), - mem.as_mut_ptr() as *mut u8, - ::core::mem::size_of::<::Scalar>(), - ); - mem.assume_init() - }) - } + pub fn id(&self) -> u32 { + let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + ::flatbuffers::EndianScalar::from_little_endian(unsafe { + ::core::ptr::copy_nonoverlapping( + self.0[0..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + ::core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } - pub fn set_id(&mut self, x: u32) { - let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - unsafe { - ::core::ptr::copy_nonoverlapping( - &x_le as *const _ as *const u8, - self.0[0..].as_mut_ptr(), - ::core::mem::size_of::<::Scalar>(), - ); - } + pub fn set_id(&mut self, x: u32) { + let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + ::core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[0..].as_mut_ptr(), + ::core::mem::size_of::<::Scalar>(), + ); } + } + #[inline] + pub fn key_compare_less_than(&self, o: &Ability) -> bool { + self.id() < o.id() + } - #[inline] - pub fn key_compare_less_than(&self, o: &Ability) -> bool { - self.id() < o.id() - } + #[inline] + pub fn key_compare_with_value(&self, val: u32) -> ::core::cmp::Ordering { + let key = self.id(); + key.cmp(&val) + } + pub fn distance(&self) -> u32 { + let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + ::flatbuffers::EndianScalar::from_little_endian(unsafe { + ::core::ptr::copy_nonoverlapping( + self.0[4..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + ::core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } - #[inline] - pub fn key_compare_with_value(&self, val: u32) -> ::core::cmp::Ordering { - let key = self.id(); - key.cmp(&val) - } - pub fn distance(&self) -> u32 { - let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - ::flatbuffers::EndianScalar::from_little_endian(unsafe { - ::core::ptr::copy_nonoverlapping( - self.0[4..].as_ptr(), - mem.as_mut_ptr() as *mut u8, - ::core::mem::size_of::<::Scalar>(), - ); - mem.assume_init() - }) + pub fn set_distance(&mut self, x: u32) { + let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + ::core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[4..].as_mut_ptr(), + ::core::mem::size_of::<::Scalar>(), + ); } + } - pub fn set_distance(&mut self, x: u32) { - let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - unsafe { - ::core::ptr::copy_nonoverlapping( - &x_le as *const _ as *const u8, - self.0[4..].as_mut_ptr(), - ::core::mem::size_of::<::Scalar>(), - ); - } - } - - pub fn unpack(&self) -> AbilityT { - AbilityT { - id: self.id(), - distance: self.distance(), - } + pub fn unpack(&self) -> AbilityT { + AbilityT { + id: self.id(), + distance: self.distance(), } + } } -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Default)] pub struct AbilityT { - pub id: u32, - pub distance: u32, + pub id: u32, + pub distance: u32, } -impl Default for AbilityT { - fn default() -> Self { - Self { - id: 0, - distance: 0, - } - } +impl AbilityT { + pub fn pack(&self) -> Ability { + Ability::new( + self.id, + self.distance, + ) + } } -impl AbilityT { - pub fn pack(&self) -> Ability { - Ability::new( - self.id, - self.distance, - ) - } -} diff --git a/tests/monster_test/my_game/example/any_ambiguous_aliases_generated.rs b/tests/monster_test/my_game/example/any_ambiguous_aliases_generated.rs index 0501ade17..af7835dc5 100644 --- a/tests/monster_test/my_game/example/any_ambiguous_aliases_generated.rs +++ b/tests/monster_test/my_game/example/any_ambiguous_aliases_generated.rs @@ -2,77 +2,68 @@ // @generated extern crate alloc; use super::*; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] pub const ENUM_MIN_ANY_AMBIGUOUS_ALIASES: u8 = 0; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] pub const ENUM_MAX_ANY_AMBIGUOUS_ALIASES: u8 = 3; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] #[allow(non_camel_case_types)] pub const ENUM_VALUES_ANY_AMBIGUOUS_ALIASES: [AnyAmbiguousAliases; 4] = [ - AnyAmbiguousAliases::NONE, - AnyAmbiguousAliases::M1, - AnyAmbiguousAliases::M2, - AnyAmbiguousAliases::M3, + AnyAmbiguousAliases::NONE, + AnyAmbiguousAliases::M1, + AnyAmbiguousAliases::M2, + AnyAmbiguousAliases::M3, ]; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] #[repr(transparent)] pub struct AnyAmbiguousAliases(pub u8); - #[allow(non_upper_case_globals)] impl AnyAmbiguousAliases { - pub const NONE: Self = Self(0); - pub const M1: Self = Self(1); - pub const M2: Self = Self(2); - pub const M3: Self = Self(3); + pub const NONE: Self = Self(0); + pub const M1: Self = Self(1); + pub const M2: Self = Self(2); + pub const M3: Self = Self(3); - pub const ENUM_MIN: u8 = 0; - pub const ENUM_MAX: u8 = 3; - pub const ENUM_VALUES: &'static [Self] = &[ - Self::NONE, - Self::M1, - Self::M2, - Self::M3, - ]; - - /// Returns the variant's name or "" if unknown. - pub fn variant_name(self) -> Option<&'static str> { - match self { - Self::NONE => Some("NONE"), - Self::M1 => Some("M1"), - Self::M2 => Some("M2"), - Self::M3 => Some("M3"), - _ => None, - } + pub const ENUM_MIN: u8 = 0; + pub const ENUM_MAX: u8 = 3; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::NONE, + Self::M1, + Self::M2, + Self::M3, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::NONE => Some("NONE"), + Self::M1 => Some("M1"), + Self::M2 => Some("M2"), + Self::M3 => Some("M3"), + _ => None, } + } } - impl ::core::fmt::Debug for AnyAmbiguousAliases { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - if let Some(name) = self.variant_name() { - f.write_str(name) - } else { - f.write_fmt(format_args!("", self.0)) - } + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) } + } } - impl<'a> ::flatbuffers::Follow<'a> for AnyAmbiguousAliases { - type Inner = Self; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; - Self(b) - } + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; + Self(b) + } } impl ::flatbuffers::Push for AnyAmbiguousAliases { type Output = AnyAmbiguousAliases; - #[inline] unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { unsafe { ::flatbuffers::emplace_scalar::(dst, self.0) }; @@ -80,139 +71,123 @@ impl ::flatbuffers::Push for AnyAmbiguousAliases { } impl ::flatbuffers::EndianScalar for AnyAmbiguousAliases { - type Scalar = u8; - - #[inline] - fn to_little_endian(self) -> u8 { - self.0.to_le() - } - - #[inline] - #[allow(clippy::wrong_self_convention)] - fn from_little_endian(v: u8) -> Self { - let b = u8::from_le(v); - Self(b) - } + type Scalar = u8; + #[inline] + fn to_little_endian(self) -> u8 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: u8) -> Self { + let b = u8::from_le(v); + Self(b) + } } impl<'a> ::flatbuffers::Verifiable for AnyAmbiguousAliases { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - u8::run_verifier(v, pos) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + u8::run_verifier(v, pos) + } } impl ::flatbuffers::SimpleToVerifyInSlice for AnyAmbiguousAliases {} - pub struct AnyAmbiguousAliasesUnionTableOffset {} #[allow(clippy::upper_case_acronyms)] #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub enum AnyAmbiguousAliasesT { - NONE, - M1(alloc::boxed::Box), - M2(alloc::boxed::Box), - M3(alloc::boxed::Box), + NONE, + M1(alloc::boxed::Box), + M2(alloc::boxed::Box), + M3(alloc::boxed::Box), } - impl Default for AnyAmbiguousAliasesT { - fn default() -> Self { - Self::NONE - } + fn default() -> Self { + Self::NONE + } } - impl AnyAmbiguousAliasesT { - pub fn any_ambiguous_aliases_type(&self) -> AnyAmbiguousAliases { - match self { - Self::NONE => AnyAmbiguousAliases::NONE, - Self::M1(_) => AnyAmbiguousAliases::M1, - Self::M2(_) => AnyAmbiguousAliases::M2, - Self::M3(_) => AnyAmbiguousAliases::M3, - } + pub fn any_ambiguous_aliases_type(&self) -> AnyAmbiguousAliases { + match self { + Self::NONE => AnyAmbiguousAliases::NONE, + Self::M1(_) => AnyAmbiguousAliases::M1, + Self::M2(_) => AnyAmbiguousAliases::M2, + Self::M3(_) => AnyAmbiguousAliases::M3, } - - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>(&self, fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A>) -> Option<::flatbuffers::WIPOffset<::flatbuffers::UnionWIPOffset>> { - match self { - Self::NONE => None, - Self::M1(v) => Some(v.pack(fbb).as_union_value()), - Self::M2(v) => Some(v.pack(fbb).as_union_value()), - Self::M3(v) => Some(v.pack(fbb).as_union_value()), - } + } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>(&self, fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A>) -> Option<::flatbuffers::WIPOffset<::flatbuffers::UnionWIPOffset>> { + match self { + Self::NONE => None, + Self::M1(v) => Some(v.pack(fbb).as_union_value()), + Self::M2(v) => Some(v.pack(fbb).as_union_value()), + Self::M3(v) => Some(v.pack(fbb).as_union_value()), } - - /// If the union variant matches, return the owned MonsterT, setting the union to NONE. - pub fn take_m1(&mut self) -> Option> { - if let Self::M1(_) = self { - let v = ::core::mem::replace(self, Self::NONE); - if let Self::M1(w) = v { - Some(w) - } else { - unreachable!() - } - } else { - None - } + } + /// If the union variant matches, return the owned MonsterT, setting the union to NONE. + pub fn take_m1(&mut self) -> Option> { + if let Self::M1(_) = self { + let v = ::core::mem::replace(self, Self::NONE); + if let Self::M1(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None } - - /// If the union variant matches, return a reference to the MonsterT. - pub fn as_m1(&self) -> Option<&MonsterT> { - if let Self::M1(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a reference to the MonsterT. + pub fn as_m1(&self) -> Option<&MonsterT> { + if let Self::M1(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the MonsterT. + pub fn as_m1_mut(&mut self) -> Option<&mut MonsterT> { + if let Self::M1(v) = self { Some(v.as_mut()) } else { None } + } + /// If the union variant matches, return the owned MonsterT, setting the union to NONE. + pub fn take_m2(&mut self) -> Option> { + if let Self::M2(_) = self { + let v = ::core::mem::replace(self, Self::NONE); + if let Self::M2(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None } - - /// If the union variant matches, return a mutable reference to the MonsterT. - pub fn as_m1_mut(&mut self) -> Option<&mut MonsterT> { - if let Self::M1(v) = self { Some(v.as_mut()) } else { None } - } - - /// If the union variant matches, return the owned MonsterT, setting the union to NONE. - pub fn take_m2(&mut self) -> Option> { - if let Self::M2(_) = self { - let v = ::core::mem::replace(self, Self::NONE); - if let Self::M2(w) = v { - Some(w) - } else { - unreachable!() - } - } else { - None - } - } - - /// If the union variant matches, return a reference to the MonsterT. - pub fn as_m2(&self) -> Option<&MonsterT> { - if let Self::M2(v) = self { Some(v.as_ref()) } else { None } - } - - /// If the union variant matches, return a mutable reference to the MonsterT. - pub fn as_m2_mut(&mut self) -> Option<&mut MonsterT> { - if let Self::M2(v) = self { Some(v.as_mut()) } else { None } - } - - /// If the union variant matches, return the owned MonsterT, setting the union to NONE. - pub fn take_m3(&mut self) -> Option> { - if let Self::M3(_) = self { - let v = ::core::mem::replace(self, Self::NONE); - if let Self::M3(w) = v { - Some(w) - } else { - unreachable!() - } - } else { - None - } - } - - /// If the union variant matches, return a reference to the MonsterT. - pub fn as_m3(&self) -> Option<&MonsterT> { - if let Self::M3(v) = self { Some(v.as_ref()) } else { None } - } - - /// If the union variant matches, return a mutable reference to the MonsterT. - pub fn as_m3_mut(&mut self) -> Option<&mut MonsterT> { - if let Self::M3(v) = self { Some(v.as_mut()) } else { None } + } + /// If the union variant matches, return a reference to the MonsterT. + pub fn as_m2(&self) -> Option<&MonsterT> { + if let Self::M2(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the MonsterT. + pub fn as_m2_mut(&mut self) -> Option<&mut MonsterT> { + if let Self::M2(v) = self { Some(v.as_mut()) } else { None } + } + /// If the union variant matches, return the owned MonsterT, setting the union to NONE. + pub fn take_m3(&mut self) -> Option> { + if let Self::M3(_) = self { + let v = ::core::mem::replace(self, Self::NONE); + if let Self::M3(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None } + } + /// If the union variant matches, return a reference to the MonsterT. + pub fn as_m3(&self) -> Option<&MonsterT> { + if let Self::M3(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the MonsterT. + pub fn as_m3_mut(&mut self) -> Option<&mut MonsterT> { + if let Self::M3(v) = self { Some(v.as_mut()) } else { None } + } } - diff --git a/tests/monster_test/my_game/example/any_generated.rs b/tests/monster_test/my_game/example/any_generated.rs index 106b029aa..a1da43781 100644 --- a/tests/monster_test/my_game/example/any_generated.rs +++ b/tests/monster_test/my_game/example/any_generated.rs @@ -2,77 +2,68 @@ // @generated extern crate alloc; use super::*; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] pub const ENUM_MIN_ANY: u8 = 0; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] pub const ENUM_MAX_ANY: u8 = 3; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] #[allow(non_camel_case_types)] pub const ENUM_VALUES_ANY: [Any; 4] = [ - Any::NONE, - Any::Monster, - Any::TestSimpleTableWithEnum, - Any::MyGame_Example2_Monster, + Any::NONE, + Any::Monster, + Any::TestSimpleTableWithEnum, + Any::MyGame_Example2_Monster, ]; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] #[repr(transparent)] pub struct Any(pub u8); - #[allow(non_upper_case_globals)] impl Any { - pub const NONE: Self = Self(0); - pub const Monster: Self = Self(1); - pub const TestSimpleTableWithEnum: Self = Self(2); - pub const MyGame_Example2_Monster: Self = Self(3); + pub const NONE: Self = Self(0); + pub const Monster: Self = Self(1); + pub const TestSimpleTableWithEnum: Self = Self(2); + pub const MyGame_Example2_Monster: Self = Self(3); - pub const ENUM_MIN: u8 = 0; - pub const ENUM_MAX: u8 = 3; - pub const ENUM_VALUES: &'static [Self] = &[ - Self::NONE, - Self::Monster, - Self::TestSimpleTableWithEnum, - Self::MyGame_Example2_Monster, - ]; - - /// Returns the variant's name or "" if unknown. - pub fn variant_name(self) -> Option<&'static str> { - match self { - Self::NONE => Some("NONE"), - Self::Monster => Some("Monster"), - Self::TestSimpleTableWithEnum => Some("TestSimpleTableWithEnum"), - Self::MyGame_Example2_Monster => Some("MyGame_Example2_Monster"), - _ => None, - } + pub const ENUM_MIN: u8 = 0; + pub const ENUM_MAX: u8 = 3; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::NONE, + Self::Monster, + Self::TestSimpleTableWithEnum, + Self::MyGame_Example2_Monster, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::NONE => Some("NONE"), + Self::Monster => Some("Monster"), + Self::TestSimpleTableWithEnum => Some("TestSimpleTableWithEnum"), + Self::MyGame_Example2_Monster => Some("MyGame_Example2_Monster"), + _ => None, } + } } - impl ::core::fmt::Debug for Any { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - if let Some(name) = self.variant_name() { - f.write_str(name) - } else { - f.write_fmt(format_args!("", self.0)) - } + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) } + } } - impl<'a> ::flatbuffers::Follow<'a> for Any { - type Inner = Self; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; - Self(b) - } + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; + Self(b) + } } impl ::flatbuffers::Push for Any { type Output = Any; - #[inline] unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { unsafe { ::flatbuffers::emplace_scalar::(dst, self.0) }; @@ -80,139 +71,123 @@ impl ::flatbuffers::Push for Any { } impl ::flatbuffers::EndianScalar for Any { - type Scalar = u8; - - #[inline] - fn to_little_endian(self) -> u8 { - self.0.to_le() - } - - #[inline] - #[allow(clippy::wrong_self_convention)] - fn from_little_endian(v: u8) -> Self { - let b = u8::from_le(v); - Self(b) - } + type Scalar = u8; + #[inline] + fn to_little_endian(self) -> u8 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: u8) -> Self { + let b = u8::from_le(v); + Self(b) + } } impl<'a> ::flatbuffers::Verifiable for Any { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - u8::run_verifier(v, pos) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + u8::run_verifier(v, pos) + } } impl ::flatbuffers::SimpleToVerifyInSlice for Any {} - pub struct AnyUnionTableOffset {} #[allow(clippy::upper_case_acronyms)] #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub enum AnyT { - NONE, - Monster(alloc::boxed::Box), - TestSimpleTableWithEnum(alloc::boxed::Box), - MyGameExample2Monster(alloc::boxed::Box), + NONE, + Monster(alloc::boxed::Box), + TestSimpleTableWithEnum(alloc::boxed::Box), + MyGameExample2Monster(alloc::boxed::Box), } - impl Default for AnyT { - fn default() -> Self { - Self::NONE - } + fn default() -> Self { + Self::NONE + } } - impl AnyT { - pub fn any_type(&self) -> Any { - match self { - Self::NONE => Any::NONE, - Self::Monster(_) => Any::Monster, - Self::TestSimpleTableWithEnum(_) => Any::TestSimpleTableWithEnum, - Self::MyGameExample2Monster(_) => Any::MyGame_Example2_Monster, - } + pub fn any_type(&self) -> Any { + match self { + Self::NONE => Any::NONE, + Self::Monster(_) => Any::Monster, + Self::TestSimpleTableWithEnum(_) => Any::TestSimpleTableWithEnum, + Self::MyGameExample2Monster(_) => Any::MyGame_Example2_Monster, } - - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>(&self, fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A>) -> Option<::flatbuffers::WIPOffset<::flatbuffers::UnionWIPOffset>> { - match self { - Self::NONE => None, - Self::Monster(v) => Some(v.pack(fbb).as_union_value()), - Self::TestSimpleTableWithEnum(v) => Some(v.pack(fbb).as_union_value()), - Self::MyGameExample2Monster(v) => Some(v.pack(fbb).as_union_value()), - } + } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>(&self, fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A>) -> Option<::flatbuffers::WIPOffset<::flatbuffers::UnionWIPOffset>> { + match self { + Self::NONE => None, + Self::Monster(v) => Some(v.pack(fbb).as_union_value()), + Self::TestSimpleTableWithEnum(v) => Some(v.pack(fbb).as_union_value()), + Self::MyGameExample2Monster(v) => Some(v.pack(fbb).as_union_value()), } - - /// If the union variant matches, return the owned MonsterT, setting the union to NONE. - pub fn take_monster(&mut self) -> Option> { - if let Self::Monster(_) = self { - let v = ::core::mem::replace(self, Self::NONE); - if let Self::Monster(w) = v { - Some(w) - } else { - unreachable!() - } - } else { - None - } + } + /// If the union variant matches, return the owned MonsterT, setting the union to NONE. + pub fn take_monster(&mut self) -> Option> { + if let Self::Monster(_) = self { + let v = ::core::mem::replace(self, Self::NONE); + if let Self::Monster(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None } - - /// If the union variant matches, return a reference to the MonsterT. - pub fn as_monster(&self) -> Option<&MonsterT> { - if let Self::Monster(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a reference to the MonsterT. + pub fn as_monster(&self) -> Option<&MonsterT> { + if let Self::Monster(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the MonsterT. + pub fn as_monster_mut(&mut self) -> Option<&mut MonsterT> { + if let Self::Monster(v) = self { Some(v.as_mut()) } else { None } + } + /// If the union variant matches, return the owned TestSimpleTableWithEnumT, setting the union to NONE. + pub fn take_test_simple_table_with_enum(&mut self) -> Option> { + if let Self::TestSimpleTableWithEnum(_) = self { + let v = ::core::mem::replace(self, Self::NONE); + if let Self::TestSimpleTableWithEnum(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None } - - /// If the union variant matches, return a mutable reference to the MonsterT. - pub fn as_monster_mut(&mut self) -> Option<&mut MonsterT> { - if let Self::Monster(v) = self { Some(v.as_mut()) } else { None } - } - - /// If the union variant matches, return the owned TestSimpleTableWithEnumT, setting the union to NONE. - pub fn take_test_simple_table_with_enum(&mut self) -> Option> { - if let Self::TestSimpleTableWithEnum(_) = self { - let v = ::core::mem::replace(self, Self::NONE); - if let Self::TestSimpleTableWithEnum(w) = v { - Some(w) - } else { - unreachable!() - } - } else { - None - } - } - - /// If the union variant matches, return a reference to the TestSimpleTableWithEnumT. - pub fn as_test_simple_table_with_enum(&self) -> Option<&TestSimpleTableWithEnumT> { - if let Self::TestSimpleTableWithEnum(v) = self { Some(v.as_ref()) } else { None } - } - - /// If the union variant matches, return a mutable reference to the TestSimpleTableWithEnumT. - pub fn as_test_simple_table_with_enum_mut(&mut self) -> Option<&mut TestSimpleTableWithEnumT> { - if let Self::TestSimpleTableWithEnum(v) = self { Some(v.as_mut()) } else { None } - } - - /// If the union variant matches, return the owned super::example_2::MonsterT, setting the union to NONE. - pub fn take_my_game_example_2_monster(&mut self) -> Option> { - if let Self::MyGameExample2Monster(_) = self { - let v = ::core::mem::replace(self, Self::NONE); - if let Self::MyGameExample2Monster(w) = v { - Some(w) - } else { - unreachable!() - } - } else { - None - } - } - - /// If the union variant matches, return a reference to the super::example_2::MonsterT. - pub fn as_my_game_example_2_monster(&self) -> Option<&super::example_2::MonsterT> { - if let Self::MyGameExample2Monster(v) = self { Some(v.as_ref()) } else { None } - } - - /// If the union variant matches, return a mutable reference to the super::example_2::MonsterT. - pub fn as_my_game_example_2_monster_mut(&mut self) -> Option<&mut super::example_2::MonsterT> { - if let Self::MyGameExample2Monster(v) = self { Some(v.as_mut()) } else { None } + } + /// If the union variant matches, return a reference to the TestSimpleTableWithEnumT. + pub fn as_test_simple_table_with_enum(&self) -> Option<&TestSimpleTableWithEnumT> { + if let Self::TestSimpleTableWithEnum(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the TestSimpleTableWithEnumT. + pub fn as_test_simple_table_with_enum_mut(&mut self) -> Option<&mut TestSimpleTableWithEnumT> { + if let Self::TestSimpleTableWithEnum(v) = self { Some(v.as_mut()) } else { None } + } + /// If the union variant matches, return the owned super::example_2::MonsterT, setting the union to NONE. + pub fn take_my_game_example_2_monster(&mut self) -> Option> { + if let Self::MyGameExample2Monster(_) = self { + let v = ::core::mem::replace(self, Self::NONE); + if let Self::MyGameExample2Monster(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None } + } + /// If the union variant matches, return a reference to the super::example_2::MonsterT. + pub fn as_my_game_example_2_monster(&self) -> Option<&super::example_2::MonsterT> { + if let Self::MyGameExample2Monster(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the super::example_2::MonsterT. + pub fn as_my_game_example_2_monster_mut(&mut self) -> Option<&mut super::example_2::MonsterT> { + if let Self::MyGameExample2Monster(v) = self { Some(v.as_mut()) } else { None } + } } - diff --git a/tests/monster_test/my_game/example/any_unique_aliases_generated.rs b/tests/monster_test/my_game/example/any_unique_aliases_generated.rs index 8abf5c64b..741f573ee 100644 --- a/tests/monster_test/my_game/example/any_unique_aliases_generated.rs +++ b/tests/monster_test/my_game/example/any_unique_aliases_generated.rs @@ -2,77 +2,68 @@ // @generated extern crate alloc; use super::*; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] pub const ENUM_MIN_ANY_UNIQUE_ALIASES: u8 = 0; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] pub const ENUM_MAX_ANY_UNIQUE_ALIASES: u8 = 3; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] #[allow(non_camel_case_types)] pub const ENUM_VALUES_ANY_UNIQUE_ALIASES: [AnyUniqueAliases; 4] = [ - AnyUniqueAliases::NONE, - AnyUniqueAliases::M, - AnyUniqueAliases::TS, - AnyUniqueAliases::M2, + AnyUniqueAliases::NONE, + AnyUniqueAliases::M, + AnyUniqueAliases::TS, + AnyUniqueAliases::M2, ]; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] #[repr(transparent)] pub struct AnyUniqueAliases(pub u8); - #[allow(non_upper_case_globals)] impl AnyUniqueAliases { - pub const NONE: Self = Self(0); - pub const M: Self = Self(1); - pub const TS: Self = Self(2); - pub const M2: Self = Self(3); + pub const NONE: Self = Self(0); + pub const M: Self = Self(1); + pub const TS: Self = Self(2); + pub const M2: Self = Self(3); - pub const ENUM_MIN: u8 = 0; - pub const ENUM_MAX: u8 = 3; - pub const ENUM_VALUES: &'static [Self] = &[ - Self::NONE, - Self::M, - Self::TS, - Self::M2, - ]; - - /// Returns the variant's name or "" if unknown. - pub fn variant_name(self) -> Option<&'static str> { - match self { - Self::NONE => Some("NONE"), - Self::M => Some("M"), - Self::TS => Some("TS"), - Self::M2 => Some("M2"), - _ => None, - } + pub const ENUM_MIN: u8 = 0; + pub const ENUM_MAX: u8 = 3; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::NONE, + Self::M, + Self::TS, + Self::M2, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::NONE => Some("NONE"), + Self::M => Some("M"), + Self::TS => Some("TS"), + Self::M2 => Some("M2"), + _ => None, } + } } - impl ::core::fmt::Debug for AnyUniqueAliases { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - if let Some(name) = self.variant_name() { - f.write_str(name) - } else { - f.write_fmt(format_args!("", self.0)) - } + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) } + } } - impl<'a> ::flatbuffers::Follow<'a> for AnyUniqueAliases { - type Inner = Self; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; - Self(b) - } + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; + Self(b) + } } impl ::flatbuffers::Push for AnyUniqueAliases { type Output = AnyUniqueAliases; - #[inline] unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { unsafe { ::flatbuffers::emplace_scalar::(dst, self.0) }; @@ -80,139 +71,123 @@ impl ::flatbuffers::Push for AnyUniqueAliases { } impl ::flatbuffers::EndianScalar for AnyUniqueAliases { - type Scalar = u8; - - #[inline] - fn to_little_endian(self) -> u8 { - self.0.to_le() - } - - #[inline] - #[allow(clippy::wrong_self_convention)] - fn from_little_endian(v: u8) -> Self { - let b = u8::from_le(v); - Self(b) - } + type Scalar = u8; + #[inline] + fn to_little_endian(self) -> u8 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: u8) -> Self { + let b = u8::from_le(v); + Self(b) + } } impl<'a> ::flatbuffers::Verifiable for AnyUniqueAliases { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - u8::run_verifier(v, pos) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + u8::run_verifier(v, pos) + } } impl ::flatbuffers::SimpleToVerifyInSlice for AnyUniqueAliases {} - pub struct AnyUniqueAliasesUnionTableOffset {} #[allow(clippy::upper_case_acronyms)] #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub enum AnyUniqueAliasesT { - NONE, - M(alloc::boxed::Box), - TS(alloc::boxed::Box), - M2(alloc::boxed::Box), + NONE, + M(alloc::boxed::Box), + TS(alloc::boxed::Box), + M2(alloc::boxed::Box), } - impl Default for AnyUniqueAliasesT { - fn default() -> Self { - Self::NONE - } + fn default() -> Self { + Self::NONE + } } - impl AnyUniqueAliasesT { - pub fn any_unique_aliases_type(&self) -> AnyUniqueAliases { - match self { - Self::NONE => AnyUniqueAliases::NONE, - Self::M(_) => AnyUniqueAliases::M, - Self::TS(_) => AnyUniqueAliases::TS, - Self::M2(_) => AnyUniqueAliases::M2, - } + pub fn any_unique_aliases_type(&self) -> AnyUniqueAliases { + match self { + Self::NONE => AnyUniqueAliases::NONE, + Self::M(_) => AnyUniqueAliases::M, + Self::TS(_) => AnyUniqueAliases::TS, + Self::M2(_) => AnyUniqueAliases::M2, } - - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>(&self, fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A>) -> Option<::flatbuffers::WIPOffset<::flatbuffers::UnionWIPOffset>> { - match self { - Self::NONE => None, - Self::M(v) => Some(v.pack(fbb).as_union_value()), - Self::TS(v) => Some(v.pack(fbb).as_union_value()), - Self::M2(v) => Some(v.pack(fbb).as_union_value()), - } + } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>(&self, fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A>) -> Option<::flatbuffers::WIPOffset<::flatbuffers::UnionWIPOffset>> { + match self { + Self::NONE => None, + Self::M(v) => Some(v.pack(fbb).as_union_value()), + Self::TS(v) => Some(v.pack(fbb).as_union_value()), + Self::M2(v) => Some(v.pack(fbb).as_union_value()), } - - /// If the union variant matches, return the owned MonsterT, setting the union to NONE. - pub fn take_m(&mut self) -> Option> { - if let Self::M(_) = self { - let v = ::core::mem::replace(self, Self::NONE); - if let Self::M(w) = v { - Some(w) - } else { - unreachable!() - } - } else { - None - } + } + /// If the union variant matches, return the owned MonsterT, setting the union to NONE. + pub fn take_m(&mut self) -> Option> { + if let Self::M(_) = self { + let v = ::core::mem::replace(self, Self::NONE); + if let Self::M(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None } - - /// If the union variant matches, return a reference to the MonsterT. - pub fn as_m(&self) -> Option<&MonsterT> { - if let Self::M(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a reference to the MonsterT. + pub fn as_m(&self) -> Option<&MonsterT> { + if let Self::M(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the MonsterT. + pub fn as_m_mut(&mut self) -> Option<&mut MonsterT> { + if let Self::M(v) = self { Some(v.as_mut()) } else { None } + } + /// If the union variant matches, return the owned TestSimpleTableWithEnumT, setting the union to NONE. + pub fn take_ts(&mut self) -> Option> { + if let Self::TS(_) = self { + let v = ::core::mem::replace(self, Self::NONE); + if let Self::TS(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None } - - /// If the union variant matches, return a mutable reference to the MonsterT. - pub fn as_m_mut(&mut self) -> Option<&mut MonsterT> { - if let Self::M(v) = self { Some(v.as_mut()) } else { None } - } - - /// If the union variant matches, return the owned TestSimpleTableWithEnumT, setting the union to NONE. - pub fn take_ts(&mut self) -> Option> { - if let Self::TS(_) = self { - let v = ::core::mem::replace(self, Self::NONE); - if let Self::TS(w) = v { - Some(w) - } else { - unreachable!() - } - } else { - None - } - } - - /// If the union variant matches, return a reference to the TestSimpleTableWithEnumT. - pub fn as_ts(&self) -> Option<&TestSimpleTableWithEnumT> { - if let Self::TS(v) = self { Some(v.as_ref()) } else { None } - } - - /// If the union variant matches, return a mutable reference to the TestSimpleTableWithEnumT. - pub fn as_ts_mut(&mut self) -> Option<&mut TestSimpleTableWithEnumT> { - if let Self::TS(v) = self { Some(v.as_mut()) } else { None } - } - - /// If the union variant matches, return the owned super::example_2::MonsterT, setting the union to NONE. - pub fn take_m2(&mut self) -> Option> { - if let Self::M2(_) = self { - let v = ::core::mem::replace(self, Self::NONE); - if let Self::M2(w) = v { - Some(w) - } else { - unreachable!() - } - } else { - None - } - } - - /// If the union variant matches, return a reference to the super::example_2::MonsterT. - pub fn as_m2(&self) -> Option<&super::example_2::MonsterT> { - if let Self::M2(v) = self { Some(v.as_ref()) } else { None } - } - - /// If the union variant matches, return a mutable reference to the super::example_2::MonsterT. - pub fn as_m2_mut(&mut self) -> Option<&mut super::example_2::MonsterT> { - if let Self::M2(v) = self { Some(v.as_mut()) } else { None } + } + /// If the union variant matches, return a reference to the TestSimpleTableWithEnumT. + pub fn as_ts(&self) -> Option<&TestSimpleTableWithEnumT> { + if let Self::TS(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the TestSimpleTableWithEnumT. + pub fn as_ts_mut(&mut self) -> Option<&mut TestSimpleTableWithEnumT> { + if let Self::TS(v) = self { Some(v.as_mut()) } else { None } + } + /// If the union variant matches, return the owned super::example_2::MonsterT, setting the union to NONE. + pub fn take_m2(&mut self) -> Option> { + if let Self::M2(_) = self { + let v = ::core::mem::replace(self, Self::NONE); + if let Self::M2(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None } + } + /// If the union variant matches, return a reference to the super::example_2::MonsterT. + pub fn as_m2(&self) -> Option<&super::example_2::MonsterT> { + if let Self::M2(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the super::example_2::MonsterT. + pub fn as_m2_mut(&mut self) -> Option<&mut super::example_2::MonsterT> { + if let Self::M2(v) = self { Some(v.as_mut()) } else { None } + } } - diff --git a/tests/monster_test/my_game/example/color_generated.rs b/tests/monster_test/my_game/example/color_generated.rs index ca3886bba..5bade500f 100644 --- a/tests/monster_test/my_game/example/color_generated.rs +++ b/tests/monster_test/my_game/example/color_generated.rs @@ -2,38 +2,34 @@ // @generated extern crate alloc; use super::*; - #[allow(non_upper_case_globals)] mod bitflags_color { - ::flatbuffers::bitflags::bitflags! { - /// Composite components of Monster color. - #[derive(Default, Debug, Clone, Copy, PartialEq)] - pub struct Color: u8 { - const Red = 1; - /// \brief color Green - /// Green is bit_flag with value (1u << 1) - const Green = 2; - /// \brief color Blue (1u << 3) - const Blue = 8; - } + ::flatbuffers::bitflags::bitflags! { + /// Composite components of Monster color. + #[derive(Default, Debug, Clone, Copy, PartialEq)] + pub struct Color: u8 { + const Red = 1; + /// \brief color Green + /// Green is bit_flag with value (1u << 1) + const Green = 2; + /// \brief color Blue (1u << 3) + const Blue = 8; } + } } - pub use self::bitflags_color::Color; impl<'a> ::flatbuffers::Follow<'a> for Color { - type Inner = Self; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; - Self::from_bits_retain(b) - } + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; + Self::from_bits_retain(b) + } } impl ::flatbuffers::Push for Color { type Output = Color; - #[inline] unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { unsafe { ::flatbuffers::emplace_scalar::(dst, self.bits()) }; @@ -41,28 +37,26 @@ impl ::flatbuffers::Push for Color { } impl ::flatbuffers::EndianScalar for Color { - type Scalar = u8; - - #[inline] - fn to_little_endian(self) -> u8 { - self.bits().to_le() - } - - #[inline] - #[allow(clippy::wrong_self_convention)] - fn from_little_endian(v: u8) -> Self { - let b = u8::from_le(v); - Self::from_bits_retain(b) - } + type Scalar = u8; + #[inline] + fn to_little_endian(self) -> u8 { + self.bits().to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: u8) -> Self { + let b = u8::from_le(v); + Self::from_bits_retain(b) + } } impl<'a> ::flatbuffers::Verifiable for Color { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - u8::run_verifier(v, pos) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + u8::run_verifier(v, pos) + } } impl ::flatbuffers::SimpleToVerifyInSlice for Color {} diff --git a/tests/monster_test/my_game/example/long_enum_generated.rs b/tests/monster_test/my_game/example/long_enum_generated.rs index 7cac7700f..efa8f87ea 100644 --- a/tests/monster_test/my_game/example/long_enum_generated.rs +++ b/tests/monster_test/my_game/example/long_enum_generated.rs @@ -2,34 +2,30 @@ // @generated extern crate alloc; use super::*; - #[allow(non_upper_case_globals)] mod bitflags_long_enum { - ::flatbuffers::bitflags::bitflags! { - #[derive(Default, Debug, Clone, Copy, PartialEq)] - pub struct LongEnum: u64 { - const LongOne = 2; - const LongTwo = 4; - const LongBig = 1099511627776; - } + ::flatbuffers::bitflags::bitflags! { + #[derive(Default, Debug, Clone, Copy, PartialEq)] + pub struct LongEnum: u64 { + const LongOne = 2; + const LongTwo = 4; + const LongBig = 1099511627776; } + } } - pub use self::bitflags_long_enum::LongEnum; impl<'a> ::flatbuffers::Follow<'a> for LongEnum { - type Inner = Self; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; - Self::from_bits_retain(b) - } + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; + Self::from_bits_retain(b) + } } impl ::flatbuffers::Push for LongEnum { type Output = LongEnum; - #[inline] unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { unsafe { ::flatbuffers::emplace_scalar::(dst, self.bits()) }; @@ -37,28 +33,26 @@ impl ::flatbuffers::Push for LongEnum { } impl ::flatbuffers::EndianScalar for LongEnum { - type Scalar = u64; - - #[inline] - fn to_little_endian(self) -> u64 { - self.bits().to_le() - } - - #[inline] - #[allow(clippy::wrong_self_convention)] - fn from_little_endian(v: u64) -> Self { - let b = u64::from_le(v); - Self::from_bits_retain(b) - } + type Scalar = u64; + #[inline] + fn to_little_endian(self) -> u64 { + self.bits().to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: u64) -> Self { + let b = u64::from_le(v); + Self::from_bits_retain(b) + } } impl<'a> ::flatbuffers::Verifiable for LongEnum { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - u64::run_verifier(v, pos) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + u64::run_verifier(v, pos) + } } impl ::flatbuffers::SimpleToVerifyInSlice for LongEnum {} diff --git a/tests/monster_test/my_game/example/monster_generated.rs b/tests/monster_test/my_game/example/monster_generated.rs index d860e0613..db44ea51d 100644 --- a/tests/monster_test/my_game/example/monster_generated.rs +++ b/tests/monster_test/my_game/example/monster_generated.rs @@ -2,1141 +2,1074 @@ // @generated extern crate alloc; use super::*; - pub enum MonsterOffset {} +#[derive(Copy, Clone, PartialEq)] /// an example documentation comment: "monster object" -#[derive(Copy, Clone, PartialEq)] pub struct Monster<'a> { - pub _tab: ::flatbuffers::Table<'a>, + pub _tab: ::flatbuffers::Table<'a>, } impl<'a> ::flatbuffers::Follow<'a> for Monster<'a> { - type Inner = Monster<'a>; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } - } + type Inner = Monster<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } + } } impl<'a> Monster<'a> { - pub const VT_POS: ::flatbuffers::VOffsetT = 4; - pub const VT_MANA: ::flatbuffers::VOffsetT = 6; - pub const VT_HP: ::flatbuffers::VOffsetT = 8; - pub const VT_NAME: ::flatbuffers::VOffsetT = 10; - pub const VT_INVENTORY: ::flatbuffers::VOffsetT = 14; - pub const VT_COLOR: ::flatbuffers::VOffsetT = 16; - pub const VT_TEST_TYPE: ::flatbuffers::VOffsetT = 18; - pub const VT_TEST: ::flatbuffers::VOffsetT = 20; - pub const VT_TEST4: ::flatbuffers::VOffsetT = 22; - pub const VT_TESTARRAYOFSTRING: ::flatbuffers::VOffsetT = 24; - pub const VT_TESTARRAYOFTABLES: ::flatbuffers::VOffsetT = 26; - pub const VT_ENEMY: ::flatbuffers::VOffsetT = 28; - pub const VT_TESTNESTEDFLATBUFFER: ::flatbuffers::VOffsetT = 30; - pub const VT_TESTEMPTY: ::flatbuffers::VOffsetT = 32; - pub const VT_TESTBOOL: ::flatbuffers::VOffsetT = 34; - pub const VT_TESTHASHS32_FNV1: ::flatbuffers::VOffsetT = 36; - pub const VT_TESTHASHU32_FNV1: ::flatbuffers::VOffsetT = 38; - pub const VT_TESTHASHS64_FNV1: ::flatbuffers::VOffsetT = 40; - pub const VT_TESTHASHU64_FNV1: ::flatbuffers::VOffsetT = 42; - pub const VT_TESTHASHS32_FNV1A: ::flatbuffers::VOffsetT = 44; - pub const VT_TESTHASHU32_FNV1A: ::flatbuffers::VOffsetT = 46; - pub const VT_TESTHASHS64_FNV1A: ::flatbuffers::VOffsetT = 48; - pub const VT_TESTHASHU64_FNV1A: ::flatbuffers::VOffsetT = 50; - pub const VT_TESTARRAYOFBOOLS: ::flatbuffers::VOffsetT = 52; - pub const VT_TESTF: ::flatbuffers::VOffsetT = 54; - pub const VT_TESTF2: ::flatbuffers::VOffsetT = 56; - pub const VT_TESTF3: ::flatbuffers::VOffsetT = 58; - pub const VT_TESTARRAYOFSTRING2: ::flatbuffers::VOffsetT = 60; - pub const VT_TESTARRAYOFSORTEDSTRUCT: ::flatbuffers::VOffsetT = 62; - pub const VT_FLEX: ::flatbuffers::VOffsetT = 64; - pub const VT_TEST5: ::flatbuffers::VOffsetT = 66; - pub const VT_VECTOR_OF_LONGS: ::flatbuffers::VOffsetT = 68; - pub const VT_VECTOR_OF_DOUBLES: ::flatbuffers::VOffsetT = 70; - pub const VT_PARENT_NAMESPACE_TEST: ::flatbuffers::VOffsetT = 72; - pub const VT_VECTOR_OF_REFERRABLES: ::flatbuffers::VOffsetT = 74; - pub const VT_SINGLE_WEAK_REFERENCE: ::flatbuffers::VOffsetT = 76; - pub const VT_VECTOR_OF_WEAK_REFERENCES: ::flatbuffers::VOffsetT = 78; - pub const VT_VECTOR_OF_STRONG_REFERRABLES: ::flatbuffers::VOffsetT = 80; - pub const VT_CO_OWNING_REFERENCE: ::flatbuffers::VOffsetT = 82; - pub const VT_VECTOR_OF_CO_OWNING_REFERENCES: ::flatbuffers::VOffsetT = 84; - pub const VT_NON_OWNING_REFERENCE: ::flatbuffers::VOffsetT = 86; - pub const VT_VECTOR_OF_NON_OWNING_REFERENCES: ::flatbuffers::VOffsetT = 88; - pub const VT_ANY_UNIQUE_TYPE: ::flatbuffers::VOffsetT = 90; - pub const VT_ANY_UNIQUE: ::flatbuffers::VOffsetT = 92; - pub const VT_ANY_AMBIGUOUS_TYPE: ::flatbuffers::VOffsetT = 94; - pub const VT_ANY_AMBIGUOUS: ::flatbuffers::VOffsetT = 96; - pub const VT_VECTOR_OF_ENUMS: ::flatbuffers::VOffsetT = 98; - pub const VT_SIGNED_ENUM: ::flatbuffers::VOffsetT = 100; - pub const VT_TESTREQUIREDNESTEDFLATBUFFER: ::flatbuffers::VOffsetT = 102; - pub const VT_SCALAR_KEY_SORTED_TABLES: ::flatbuffers::VOffsetT = 104; - pub const VT_NATIVE_INLINE: ::flatbuffers::VOffsetT = 106; - pub const VT_LONG_ENUM_NON_ENUM_DEFAULT: ::flatbuffers::VOffsetT = 108; - pub const VT_LONG_ENUM_NORMAL_DEFAULT: ::flatbuffers::VOffsetT = 110; - pub const VT_NAN_DEFAULT: ::flatbuffers::VOffsetT = 112; - pub const VT_INF_DEFAULT: ::flatbuffers::VOffsetT = 114; - pub const VT_POSITIVE_INF_DEFAULT: ::flatbuffers::VOffsetT = 116; - pub const VT_INFINITY_DEFAULT: ::flatbuffers::VOffsetT = 118; - pub const VT_POSITIVE_INFINITY_DEFAULT: ::flatbuffers::VOffsetT = 120; - pub const VT_NEGATIVE_INF_DEFAULT: ::flatbuffers::VOffsetT = 122; - pub const VT_NEGATIVE_INFINITY_DEFAULT: ::flatbuffers::VOffsetT = 124; - pub const VT_DOUBLE_INF_DEFAULT: ::flatbuffers::VOffsetT = 126; + pub const VT_POS: ::flatbuffers::VOffsetT = 4; + pub const VT_MANA: ::flatbuffers::VOffsetT = 6; + pub const VT_HP: ::flatbuffers::VOffsetT = 8; + pub const VT_NAME: ::flatbuffers::VOffsetT = 10; + pub const VT_INVENTORY: ::flatbuffers::VOffsetT = 14; + pub const VT_COLOR: ::flatbuffers::VOffsetT = 16; + pub const VT_TEST_TYPE: ::flatbuffers::VOffsetT = 18; + pub const VT_TEST: ::flatbuffers::VOffsetT = 20; + pub const VT_TEST4: ::flatbuffers::VOffsetT = 22; + pub const VT_TESTARRAYOFSTRING: ::flatbuffers::VOffsetT = 24; + pub const VT_TESTARRAYOFTABLES: ::flatbuffers::VOffsetT = 26; + pub const VT_ENEMY: ::flatbuffers::VOffsetT = 28; + pub const VT_TESTNESTEDFLATBUFFER: ::flatbuffers::VOffsetT = 30; + pub const VT_TESTEMPTY: ::flatbuffers::VOffsetT = 32; + pub const VT_TESTBOOL: ::flatbuffers::VOffsetT = 34; + pub const VT_TESTHASHS32_FNV1: ::flatbuffers::VOffsetT = 36; + pub const VT_TESTHASHU32_FNV1: ::flatbuffers::VOffsetT = 38; + pub const VT_TESTHASHS64_FNV1: ::flatbuffers::VOffsetT = 40; + pub const VT_TESTHASHU64_FNV1: ::flatbuffers::VOffsetT = 42; + pub const VT_TESTHASHS32_FNV1A: ::flatbuffers::VOffsetT = 44; + pub const VT_TESTHASHU32_FNV1A: ::flatbuffers::VOffsetT = 46; + pub const VT_TESTHASHS64_FNV1A: ::flatbuffers::VOffsetT = 48; + pub const VT_TESTHASHU64_FNV1A: ::flatbuffers::VOffsetT = 50; + pub const VT_TESTARRAYOFBOOLS: ::flatbuffers::VOffsetT = 52; + pub const VT_TESTF: ::flatbuffers::VOffsetT = 54; + pub const VT_TESTF2: ::flatbuffers::VOffsetT = 56; + pub const VT_TESTF3: ::flatbuffers::VOffsetT = 58; + pub const VT_TESTARRAYOFSTRING2: ::flatbuffers::VOffsetT = 60; + pub const VT_TESTARRAYOFSORTEDSTRUCT: ::flatbuffers::VOffsetT = 62; + pub const VT_FLEX: ::flatbuffers::VOffsetT = 64; + pub const VT_TEST5: ::flatbuffers::VOffsetT = 66; + pub const VT_VECTOR_OF_LONGS: ::flatbuffers::VOffsetT = 68; + pub const VT_VECTOR_OF_DOUBLES: ::flatbuffers::VOffsetT = 70; + pub const VT_PARENT_NAMESPACE_TEST: ::flatbuffers::VOffsetT = 72; + pub const VT_VECTOR_OF_REFERRABLES: ::flatbuffers::VOffsetT = 74; + pub const VT_SINGLE_WEAK_REFERENCE: ::flatbuffers::VOffsetT = 76; + pub const VT_VECTOR_OF_WEAK_REFERENCES: ::flatbuffers::VOffsetT = 78; + pub const VT_VECTOR_OF_STRONG_REFERRABLES: ::flatbuffers::VOffsetT = 80; + pub const VT_CO_OWNING_REFERENCE: ::flatbuffers::VOffsetT = 82; + pub const VT_VECTOR_OF_CO_OWNING_REFERENCES: ::flatbuffers::VOffsetT = 84; + pub const VT_NON_OWNING_REFERENCE: ::flatbuffers::VOffsetT = 86; + pub const VT_VECTOR_OF_NON_OWNING_REFERENCES: ::flatbuffers::VOffsetT = 88; + pub const VT_ANY_UNIQUE_TYPE: ::flatbuffers::VOffsetT = 90; + pub const VT_ANY_UNIQUE: ::flatbuffers::VOffsetT = 92; + pub const VT_ANY_AMBIGUOUS_TYPE: ::flatbuffers::VOffsetT = 94; + pub const VT_ANY_AMBIGUOUS: ::flatbuffers::VOffsetT = 96; + pub const VT_VECTOR_OF_ENUMS: ::flatbuffers::VOffsetT = 98; + pub const VT_SIGNED_ENUM: ::flatbuffers::VOffsetT = 100; + pub const VT_TESTREQUIREDNESTEDFLATBUFFER: ::flatbuffers::VOffsetT = 102; + pub const VT_SCALAR_KEY_SORTED_TABLES: ::flatbuffers::VOffsetT = 104; + pub const VT_NATIVE_INLINE: ::flatbuffers::VOffsetT = 106; + pub const VT_LONG_ENUM_NON_ENUM_DEFAULT: ::flatbuffers::VOffsetT = 108; + pub const VT_LONG_ENUM_NORMAL_DEFAULT: ::flatbuffers::VOffsetT = 110; + pub const VT_NAN_DEFAULT: ::flatbuffers::VOffsetT = 112; + pub const VT_INF_DEFAULT: ::flatbuffers::VOffsetT = 114; + pub const VT_POSITIVE_INF_DEFAULT: ::flatbuffers::VOffsetT = 116; + pub const VT_INFINITY_DEFAULT: ::flatbuffers::VOffsetT = 118; + pub const VT_POSITIVE_INFINITY_DEFAULT: ::flatbuffers::VOffsetT = 120; + pub const VT_NEGATIVE_INF_DEFAULT: ::flatbuffers::VOffsetT = 122; + pub const VT_NEGATIVE_INFINITY_DEFAULT: ::flatbuffers::VOffsetT = 124; + pub const VT_DOUBLE_INF_DEFAULT: ::flatbuffers::VOffsetT = 126; + + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Example.Monster" + } + + #[inline] + pub unsafe 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, A: ::flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args MonsterArgs<'args> + ) -> ::flatbuffers::WIPOffset> { + let mut builder = MonsterBuilder::new(_fbb); + builder.add_double_inf_default(args.double_inf_default); + builder.add_long_enum_normal_default(args.long_enum_normal_default); + builder.add_long_enum_non_enum_default(args.long_enum_non_enum_default); + builder.add_non_owning_reference(args.non_owning_reference); + builder.add_co_owning_reference(args.co_owning_reference); + builder.add_single_weak_reference(args.single_weak_reference); + builder.add_testhashu64_fnv1a(args.testhashu64_fnv1a); + builder.add_testhashs64_fnv1a(args.testhashs64_fnv1a); + builder.add_testhashu64_fnv1(args.testhashu64_fnv1); + builder.add_testhashs64_fnv1(args.testhashs64_fnv1); + builder.add_negative_infinity_default(args.negative_infinity_default); + builder.add_negative_inf_default(args.negative_inf_default); + builder.add_positive_infinity_default(args.positive_infinity_default); + builder.add_infinity_default(args.infinity_default); + builder.add_positive_inf_default(args.positive_inf_default); + builder.add_inf_default(args.inf_default); + builder.add_nan_default(args.nan_default); + if let Some(x) = args.native_inline { builder.add_native_inline(x); } + if let Some(x) = args.scalar_key_sorted_tables { builder.add_scalar_key_sorted_tables(x); } + if let Some(x) = args.testrequirednestedflatbuffer { builder.add_testrequirednestedflatbuffer(x); } + if let Some(x) = args.vector_of_enums { builder.add_vector_of_enums(x); } + if let Some(x) = args.any_ambiguous { builder.add_any_ambiguous(x); } + if let Some(x) = args.any_unique { builder.add_any_unique(x); } + if let Some(x) = args.vector_of_non_owning_references { builder.add_vector_of_non_owning_references(x); } + if let Some(x) = args.vector_of_co_owning_references { builder.add_vector_of_co_owning_references(x); } + if let Some(x) = args.vector_of_strong_referrables { builder.add_vector_of_strong_referrables(x); } + if let Some(x) = args.vector_of_weak_references { builder.add_vector_of_weak_references(x); } + if let Some(x) = args.vector_of_referrables { builder.add_vector_of_referrables(x); } + if let Some(x) = args.parent_namespace_test { builder.add_parent_namespace_test(x); } + if let Some(x) = args.vector_of_doubles { builder.add_vector_of_doubles(x); } + if let Some(x) = args.vector_of_longs { builder.add_vector_of_longs(x); } + if let Some(x) = args.test5 { builder.add_test5(x); } + if let Some(x) = args.flex { builder.add_flex(x); } + if let Some(x) = args.testarrayofsortedstruct { builder.add_testarrayofsortedstruct(x); } + if let Some(x) = args.testarrayofstring2 { builder.add_testarrayofstring2(x); } + builder.add_testf3(args.testf3); + builder.add_testf2(args.testf2); + builder.add_testf(args.testf); + if let Some(x) = args.testarrayofbools { builder.add_testarrayofbools(x); } + builder.add_testhashu32_fnv1a(args.testhashu32_fnv1a); + builder.add_testhashs32_fnv1a(args.testhashs32_fnv1a); + builder.add_testhashu32_fnv1(args.testhashu32_fnv1); + builder.add_testhashs32_fnv1(args.testhashs32_fnv1); + if let Some(x) = args.testempty { builder.add_testempty(x); } + if let Some(x) = args.testnestedflatbuffer { builder.add_testnestedflatbuffer(x); } + if let Some(x) = args.enemy { builder.add_enemy(x); } + if let Some(x) = args.testarrayoftables { builder.add_testarrayoftables(x); } + if let Some(x) = args.testarrayofstring { builder.add_testarrayofstring(x); } + if let Some(x) = args.test4 { builder.add_test4(x); } + if let Some(x) = args.test { builder.add_test(x); } + if let Some(x) = args.inventory { builder.add_inventory(x); } + if let Some(x) = args.name { builder.add_name(x); } + if let Some(x) = args.pos { builder.add_pos(x); } + builder.add_hp(args.hp); + builder.add_mana(args.mana); + builder.add_signed_enum(args.signed_enum); + builder.add_any_ambiguous_type(args.any_ambiguous_type); + builder.add_any_unique_type(args.any_unique_type); + builder.add_testbool(args.testbool); + builder.add_test_type(args.test_type); + builder.add_color(args.color); + builder.finish() + } + + pub fn unpack(&self) -> MonsterT { + let pos = self.pos().map(|x| { + x.unpack() + }); + let mana = self.mana(); + let hp = self.hp(); + let name = { + let x = self.name(); + alloc::string::ToString::to_string(x) + }; + let inventory = self.inventory().map(|x| { + x.into_iter().collect() + }); + let color = self.color(); + let test = match self.test_type() { + Any::NONE => AnyT::NONE, + Any::Monster => AnyT::Monster(alloc::boxed::Box::new( + self.test_as_monster() + .expect("Invalid union table, expected `Any::Monster`.") + .unpack() + )), + Any::TestSimpleTableWithEnum => AnyT::TestSimpleTableWithEnum(alloc::boxed::Box::new( + self.test_as_test_simple_table_with_enum() + .expect("Invalid union table, expected `Any::TestSimpleTableWithEnum`.") + .unpack() + )), + Any::MyGame_Example2_Monster => AnyT::MyGameExample2Monster(alloc::boxed::Box::new( + self.test_as_my_game_example_2_monster() + .expect("Invalid union table, expected `Any::MyGame_Example2_Monster`.") + .unpack() + )), + _ => AnyT::NONE, + }; + let test4 = self.test4().map(|x| { + x.iter().map(|t| t.unpack()).collect() + }); + let testarrayofstring = self.testarrayofstring().map(|x| { + x.iter().map(|s| alloc::string::ToString::to_string(s)).collect() + }); + let testarrayoftables = self.testarrayoftables().map(|x| { + x.iter().map(|t| t.unpack()).collect() + }); + let enemy = self.enemy().map(|x| { + alloc::boxed::Box::new(x.unpack()) + }); + let testnestedflatbuffer = self.testnestedflatbuffer().map(|x| { + x.into_iter().collect() + }); + let testempty = self.testempty().map(|x| { + alloc::boxed::Box::new(x.unpack()) + }); + let testbool = self.testbool(); + let testhashs32_fnv1 = self.testhashs32_fnv1(); + let testhashu32_fnv1 = self.testhashu32_fnv1(); + let testhashs64_fnv1 = self.testhashs64_fnv1(); + let testhashu64_fnv1 = self.testhashu64_fnv1(); + let testhashs32_fnv1a = self.testhashs32_fnv1a(); + let testhashu32_fnv1a = self.testhashu32_fnv1a(); + let testhashs64_fnv1a = self.testhashs64_fnv1a(); + let testhashu64_fnv1a = self.testhashu64_fnv1a(); + let testarrayofbools = self.testarrayofbools().map(|x| { + x.into_iter().collect() + }); + let testf = self.testf(); + let testf2 = self.testf2(); + let testf3 = self.testf3(); + let testarrayofstring2 = self.testarrayofstring2().map(|x| { + x.iter().map(|s| alloc::string::ToString::to_string(s)).collect() + }); + let testarrayofsortedstruct = self.testarrayofsortedstruct().map(|x| { + x.iter().map(|t| t.unpack()).collect() + }); + let flex = self.flex().map(|x| { + x.into_iter().collect() + }); + let test5 = self.test5().map(|x| { + x.iter().map(|t| t.unpack()).collect() + }); + let vector_of_longs = self.vector_of_longs().map(|x| { + x.into_iter().collect() + }); + let vector_of_doubles = self.vector_of_doubles().map(|x| { + x.into_iter().collect() + }); + let parent_namespace_test = self.parent_namespace_test().map(|x| { + alloc::boxed::Box::new(x.unpack()) + }); + let vector_of_referrables = self.vector_of_referrables().map(|x| { + x.iter().map(|t| t.unpack()).collect() + }); + let single_weak_reference = self.single_weak_reference(); + let vector_of_weak_references = self.vector_of_weak_references().map(|x| { + x.into_iter().collect() + }); + let vector_of_strong_referrables = self.vector_of_strong_referrables().map(|x| { + x.iter().map(|t| t.unpack()).collect() + }); + let co_owning_reference = self.co_owning_reference(); + let vector_of_co_owning_references = self.vector_of_co_owning_references().map(|x| { + x.into_iter().collect() + }); + let non_owning_reference = self.non_owning_reference(); + let vector_of_non_owning_references = self.vector_of_non_owning_references().map(|x| { + x.into_iter().collect() + }); + let any_unique = match self.any_unique_type() { + AnyUniqueAliases::NONE => AnyUniqueAliasesT::NONE, + AnyUniqueAliases::M => AnyUniqueAliasesT::M(alloc::boxed::Box::new( + self.any_unique_as_m() + .expect("Invalid union table, expected `AnyUniqueAliases::M`.") + .unpack() + )), + AnyUniqueAliases::TS => AnyUniqueAliasesT::TS(alloc::boxed::Box::new( + self.any_unique_as_ts() + .expect("Invalid union table, expected `AnyUniqueAliases::TS`.") + .unpack() + )), + AnyUniqueAliases::M2 => AnyUniqueAliasesT::M2(alloc::boxed::Box::new( + self.any_unique_as_m2() + .expect("Invalid union table, expected `AnyUniqueAliases::M2`.") + .unpack() + )), + _ => AnyUniqueAliasesT::NONE, + }; + let any_ambiguous = match self.any_ambiguous_type() { + AnyAmbiguousAliases::NONE => AnyAmbiguousAliasesT::NONE, + AnyAmbiguousAliases::M1 => AnyAmbiguousAliasesT::M1(alloc::boxed::Box::new( + self.any_ambiguous_as_m1() + .expect("Invalid union table, expected `AnyAmbiguousAliases::M1`.") + .unpack() + )), + AnyAmbiguousAliases::M2 => AnyAmbiguousAliasesT::M2(alloc::boxed::Box::new( + self.any_ambiguous_as_m2() + .expect("Invalid union table, expected `AnyAmbiguousAliases::M2`.") + .unpack() + )), + AnyAmbiguousAliases::M3 => AnyAmbiguousAliasesT::M3(alloc::boxed::Box::new( + self.any_ambiguous_as_m3() + .expect("Invalid union table, expected `AnyAmbiguousAliases::M3`.") + .unpack() + )), + _ => AnyAmbiguousAliasesT::NONE, + }; + let vector_of_enums = self.vector_of_enums().map(|x| { + x.into_iter().collect() + }); + let signed_enum = self.signed_enum(); + let testrequirednestedflatbuffer = self.testrequirednestedflatbuffer().map(|x| { + x.into_iter().collect() + }); + let scalar_key_sorted_tables = self.scalar_key_sorted_tables().map(|x| { + x.iter().map(|t| t.unpack()).collect() + }); + let native_inline = self.native_inline().map(|x| { + x.unpack() + }); + let long_enum_non_enum_default = self.long_enum_non_enum_default(); + let long_enum_normal_default = self.long_enum_normal_default(); + let nan_default = self.nan_default(); + let inf_default = self.inf_default(); + let positive_inf_default = self.positive_inf_default(); + let infinity_default = self.infinity_default(); + let positive_infinity_default = self.positive_infinity_default(); + let negative_inf_default = self.negative_inf_default(); + let negative_infinity_default = self.negative_infinity_default(); + let double_inf_default = self.double_inf_default(); + MonsterT { + pos, + mana, + hp, + name, + inventory, + color, + test, + test4, + testarrayofstring, + testarrayoftables, + enemy, + testnestedflatbuffer, + testempty, + testbool, + testhashs32_fnv1, + testhashu32_fnv1, + testhashs64_fnv1, + testhashu64_fnv1, + testhashs32_fnv1a, + testhashu32_fnv1a, + testhashs64_fnv1a, + testhashu64_fnv1a, + testarrayofbools, + testf, + testf2, + testf3, + testarrayofstring2, + testarrayofsortedstruct, + flex, + test5, + vector_of_longs, + vector_of_doubles, + parent_namespace_test, + vector_of_referrables, + single_weak_reference, + vector_of_weak_references, + vector_of_strong_referrables, + co_owning_reference, + vector_of_co_owning_references, + non_owning_reference, + vector_of_non_owning_references, + any_unique, + any_ambiguous, + vector_of_enums, + signed_enum, + testrequirednestedflatbuffer, + scalar_key_sorted_tables, + native_inline, + long_enum_non_enum_default, + long_enum_normal_default, + nan_default, + inf_default, + positive_inf_default, + infinity_default, + positive_infinity_default, + negative_inf_default, + negative_infinity_default, + double_inf_default, + } + } + + #[inline] + pub fn pos(&self) -> Option<&'a Vec3> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_POS, None)} + } + #[inline] + pub fn mana(&self) -> i16 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_MANA, Some(150)).unwrap()} + } + #[inline] + pub fn hp(&self) -> i16 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_HP, Some(100)).unwrap()} + } + #[inline] + pub fn name(&self) -> &'a str { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<&str>>(Monster::VT_NAME, None).unwrap()} + } + #[inline] + pub fn key_compare_less_than(&self, o: &Monster) -> bool { + self.name() < o.name() + } + + #[inline] + pub fn key_compare_with_value(&self, val: & str) -> ::core::cmp::Ordering { + let key = self.name(); + key.cmp(val) + } + #[inline] + pub fn inventory(&self) -> Option<::flatbuffers::Vector<'a, u8>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, u8>>>(Monster::VT_INVENTORY, None)} + } + #[inline] + pub fn color(&self) -> Color { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_COLOR, Some(Color::Blue)).unwrap()} + } + #[inline] + pub fn test_type(&self) -> Any { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TEST_TYPE, Some(Any::NONE)).unwrap()} + } + #[inline] + pub fn test(&self) -> Option<::flatbuffers::Table<'a>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Table<'a>>>(Monster::VT_TEST, None)} + } + #[inline] + pub fn test4(&self) -> Option<::flatbuffers::Vector<'a, Test>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, Test>>>(Monster::VT_TEST4, None)} + } + #[inline] + pub fn testarrayofstring(&self) -> Option<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset<&'a str>>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset<&'a str>>>>(Monster::VT_TESTARRAYOFSTRING, None)} + } + /// an example documentation comment: this will end up in the generated code + /// multiline too + #[inline] + pub fn testarrayoftables(&self) -> Option<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset>>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset>>>(Monster::VT_TESTARRAYOFTABLES, None)} + } + #[inline] + pub fn enemy(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset>(Monster::VT_ENEMY, None)} + } + #[inline] + pub fn testnestedflatbuffer(&self) -> Option<::flatbuffers::Vector<'a, u8>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, u8>>>(Monster::VT_TESTNESTEDFLATBUFFER, None)} + } + pub fn testnestedflatbuffer_nested_flatbuffer(&'a self) -> Option> { + self.testnestedflatbuffer().map(|data| { + use ::flatbuffers::Follow; + // Safety: + // Created from a valid Table for this object + // Which contains a valid flatbuffer in this slot + unsafe { <::flatbuffers::ForwardsUOffset>>::follow(data.bytes(), 0) } + }) + } + #[inline] + pub fn testempty(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset>(Monster::VT_TESTEMPTY, None)} + } + #[inline] + pub fn testbool(&self) -> bool { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TESTBOOL, Some(false)).unwrap()} + } + #[inline] + pub fn testhashs32_fnv1(&self) -> i32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TESTHASHS32_FNV1, Some(0)).unwrap()} + } + #[inline] + pub fn testhashu32_fnv1(&self) -> u32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TESTHASHU32_FNV1, Some(0)).unwrap()} + } + #[inline] + pub fn testhashs64_fnv1(&self) -> i64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TESTHASHS64_FNV1, Some(0)).unwrap()} + } + #[inline] + pub fn testhashu64_fnv1(&self) -> u64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TESTHASHU64_FNV1, Some(0)).unwrap()} + } + #[inline] + pub fn testhashs32_fnv1a(&self) -> i32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TESTHASHS32_FNV1A, Some(0)).unwrap()} + } + #[inline] + pub fn testhashu32_fnv1a(&self) -> u32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TESTHASHU32_FNV1A, Some(0)).unwrap()} + } + #[inline] + pub fn testhashs64_fnv1a(&self) -> i64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TESTHASHS64_FNV1A, Some(0)).unwrap()} + } + #[inline] + pub fn testhashu64_fnv1a(&self) -> u64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TESTHASHU64_FNV1A, Some(0)).unwrap()} + } + #[inline] + pub fn testarrayofbools(&self) -> Option<::flatbuffers::Vector<'a, bool>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, bool>>>(Monster::VT_TESTARRAYOFBOOLS, None)} + } + #[inline] + pub fn testf(&self) -> f32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TESTF, Some(3.14159)).unwrap()} + } + #[inline] + pub fn testf2(&self) -> f32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TESTF2, Some(3.0)).unwrap()} + } + #[inline] + pub fn testf3(&self) -> f32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TESTF3, Some(0.0)).unwrap()} + } + #[inline] + pub fn testarrayofstring2(&self) -> Option<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset<&'a str>>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset<&'a str>>>>(Monster::VT_TESTARRAYOFSTRING2, None)} + } + #[inline] + pub fn testarrayofsortedstruct(&self) -> Option<::flatbuffers::Vector<'a, Ability>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, Ability>>>(Monster::VT_TESTARRAYOFSORTEDSTRUCT, None)} + } + #[inline] + pub fn flex(&self) -> Option<::flatbuffers::Vector<'a, u8>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, u8>>>(Monster::VT_FLEX, None)} + } + #[inline] + pub fn test5(&self) -> Option<::flatbuffers::Vector<'a, Test>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, Test>>>(Monster::VT_TEST5, None)} + } + #[inline] + pub fn vector_of_longs(&self) -> Option<::flatbuffers::Vector<'a, i64>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, i64>>>(Monster::VT_VECTOR_OF_LONGS, None)} + } + #[inline] + pub fn vector_of_doubles(&self) -> Option<::flatbuffers::Vector<'a, f64>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, f64>>>(Monster::VT_VECTOR_OF_DOUBLES, None)} + } + #[inline] + pub fn parent_namespace_test(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset>(Monster::VT_PARENT_NAMESPACE_TEST, None)} + } + #[inline] + pub fn vector_of_referrables(&self) -> Option<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset>>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset>>>(Monster::VT_VECTOR_OF_REFERRABLES, None)} + } + #[inline] + pub fn single_weak_reference(&self) -> u64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_SINGLE_WEAK_REFERENCE, Some(0)).unwrap()} + } + #[inline] + pub fn vector_of_weak_references(&self) -> Option<::flatbuffers::Vector<'a, u64>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, u64>>>(Monster::VT_VECTOR_OF_WEAK_REFERENCES, None)} + } + #[inline] + pub fn vector_of_strong_referrables(&self) -> Option<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset>>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset>>>(Monster::VT_VECTOR_OF_STRONG_REFERRABLES, None)} + } + #[inline] + pub fn co_owning_reference(&self) -> u64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_CO_OWNING_REFERENCE, Some(0)).unwrap()} + } + #[inline] + pub fn vector_of_co_owning_references(&self) -> Option<::flatbuffers::Vector<'a, u64>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, u64>>>(Monster::VT_VECTOR_OF_CO_OWNING_REFERENCES, None)} + } + #[inline] + pub fn non_owning_reference(&self) -> u64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_NON_OWNING_REFERENCE, Some(0)).unwrap()} + } + #[inline] + pub fn vector_of_non_owning_references(&self) -> Option<::flatbuffers::Vector<'a, u64>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, u64>>>(Monster::VT_VECTOR_OF_NON_OWNING_REFERENCES, None)} + } + #[inline] + pub fn any_unique_type(&self) -> AnyUniqueAliases { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_ANY_UNIQUE_TYPE, Some(AnyUniqueAliases::NONE)).unwrap()} + } + #[inline] + pub fn any_unique(&self) -> Option<::flatbuffers::Table<'a>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Table<'a>>>(Monster::VT_ANY_UNIQUE, None)} + } + #[inline] + pub fn any_ambiguous_type(&self) -> AnyAmbiguousAliases { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_ANY_AMBIGUOUS_TYPE, Some(AnyAmbiguousAliases::NONE)).unwrap()} + } + #[inline] + pub fn any_ambiguous(&self) -> Option<::flatbuffers::Table<'a>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Table<'a>>>(Monster::VT_ANY_AMBIGUOUS, None)} + } + #[inline] + pub fn vector_of_enums(&self) -> Option<::flatbuffers::Vector<'a, Color>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, Color>>>(Monster::VT_VECTOR_OF_ENUMS, None)} + } + #[inline] + pub fn signed_enum(&self) -> Race { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_SIGNED_ENUM, Some(Race::None)).unwrap()} + } + #[inline] + pub fn testrequirednestedflatbuffer(&self) -> Option<::flatbuffers::Vector<'a, u8>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, u8>>>(Monster::VT_TESTREQUIREDNESTEDFLATBUFFER, None)} + } + pub fn testrequirednestedflatbuffer_nested_flatbuffer(&'a self) -> Option> { + self.testrequirednestedflatbuffer().map(|data| { + use ::flatbuffers::Follow; + // Safety: + // Created from a valid Table for this object + // Which contains a valid flatbuffer in this slot + unsafe { <::flatbuffers::ForwardsUOffset>>::follow(data.bytes(), 0) } + }) + } + #[inline] + pub fn scalar_key_sorted_tables(&self) -> Option<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset>>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset>>>(Monster::VT_SCALAR_KEY_SORTED_TABLES, None)} + } + #[inline] + pub fn native_inline(&self) -> Option<&'a Test> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_NATIVE_INLINE, None)} + } + #[inline] + pub fn long_enum_non_enum_default(&self) -> LongEnum { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_LONG_ENUM_NON_ENUM_DEFAULT, Some(Default::default())).unwrap()} + } + #[inline] + pub fn long_enum_normal_default(&self) -> LongEnum { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_LONG_ENUM_NORMAL_DEFAULT, Some(LongEnum::LongOne)).unwrap()} + } + #[inline] + pub fn nan_default(&self) -> f32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_NAN_DEFAULT, Some(f32::NAN)).unwrap()} + } + #[inline] + pub fn inf_default(&self) -> f32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_INF_DEFAULT, Some(f32::INFINITY)).unwrap()} + } + #[inline] + pub fn positive_inf_default(&self) -> f32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_POSITIVE_INF_DEFAULT, Some(f32::INFINITY)).unwrap()} + } + #[inline] + pub fn infinity_default(&self) -> f32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_INFINITY_DEFAULT, Some(f32::INFINITY)).unwrap()} + } + #[inline] + pub fn positive_infinity_default(&self) -> f32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_POSITIVE_INFINITY_DEFAULT, Some(f32::INFINITY)).unwrap()} + } + #[inline] + pub fn negative_inf_default(&self) -> f32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_NEGATIVE_INF_DEFAULT, Some(f32::NEG_INFINITY)).unwrap()} + } + #[inline] + pub fn negative_infinity_default(&self) -> f32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_NEGATIVE_INFINITY_DEFAULT, Some(f32::NEG_INFINITY)).unwrap()} + } + #[inline] + pub fn double_inf_default(&self) -> f64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_DOUBLE_INF_DEFAULT, Some(f64::INFINITY)).unwrap()} + } + #[inline] + #[allow(non_snake_case)] + pub fn test_as_monster(&self) -> Option> { + if self.test_type() == Any::Monster { + self.test().map(|t| { + // Safety: + // Created from a valid Table for this object + // Which contains a valid union in this slot + unsafe { Monster::init_from_table(t) } + }) + } else { + None + } + } + + #[inline] + #[allow(non_snake_case)] + pub fn test_as_test_simple_table_with_enum(&self) -> Option> { + if self.test_type() == Any::TestSimpleTableWithEnum { + self.test().map(|t| { + // Safety: + // Created from a valid Table for this object + // Which contains a valid union in this slot + unsafe { TestSimpleTableWithEnum::init_from_table(t) } + }) + } else { + None + } + } + + #[inline] + #[allow(non_snake_case)] + pub fn test_as_my_game_example_2_monster(&self) -> Option> { + if self.test_type() == Any::MyGame_Example2_Monster { + self.test().map(|t| { + // Safety: + // Created from a valid Table for this object + // Which contains a valid union in this slot + unsafe { super::example_2::Monster::init_from_table(t) } + }) + } else { + None + } + } + + #[inline] + #[allow(non_snake_case)] + pub fn any_unique_as_m(&self) -> Option> { + if self.any_unique_type() == AnyUniqueAliases::M { + self.any_unique().map(|t| { + // Safety: + // Created from a valid Table for this object + // Which contains a valid union in this slot + unsafe { Monster::init_from_table(t) } + }) + } else { + None + } + } + + #[inline] + #[allow(non_snake_case)] + pub fn any_unique_as_ts(&self) -> Option> { + if self.any_unique_type() == AnyUniqueAliases::TS { + self.any_unique().map(|t| { + // Safety: + // Created from a valid Table for this object + // Which contains a valid union in this slot + unsafe { TestSimpleTableWithEnum::init_from_table(t) } + }) + } else { + None + } + } + + #[inline] + #[allow(non_snake_case)] + pub fn any_unique_as_m2(&self) -> Option> { + if self.any_unique_type() == AnyUniqueAliases::M2 { + self.any_unique().map(|t| { + // Safety: + // Created from a valid Table for this object + // Which contains a valid union in this slot + unsafe { super::example_2::Monster::init_from_table(t) } + }) + } else { + None + } + } + + #[inline] + #[allow(non_snake_case)] + pub fn any_ambiguous_as_m1(&self) -> Option> { + if self.any_ambiguous_type() == AnyAmbiguousAliases::M1 { + self.any_ambiguous().map(|t| { + // Safety: + // Created from a valid Table for this object + // Which contains a valid union in this slot + unsafe { Monster::init_from_table(t) } + }) + } else { + None + } + } + + #[inline] + #[allow(non_snake_case)] + pub fn any_ambiguous_as_m2(&self) -> Option> { + if self.any_ambiguous_type() == AnyAmbiguousAliases::M2 { + self.any_ambiguous().map(|t| { + // Safety: + // Created from a valid Table for this object + // Which contains a valid union in this slot + unsafe { Monster::init_from_table(t) } + }) + } else { + None + } + } + + #[inline] + #[allow(non_snake_case)] + pub fn any_ambiguous_as_m3(&self) -> Option> { + if self.any_ambiguous_type() == AnyAmbiguousAliases::M3 { + self.any_ambiguous().map(|t| { + // Safety: + // Created from a valid Table for this object + // Which contains a valid union in this slot + unsafe { Monster::init_from_table(t) } + }) + } else { + None + } + } - pub const fn get_fully_qualified_name() -> &'static str { - "MyGame.Example.Monster" - } - - #[inline] - pub unsafe 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, A: ::flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args MonsterArgs<'args> - ) -> ::flatbuffers::WIPOffset> { - let mut builder = MonsterBuilder::new(_fbb); - builder.add_double_inf_default(args.double_inf_default); - builder.add_long_enum_normal_default(args.long_enum_normal_default); - builder.add_long_enum_non_enum_default(args.long_enum_non_enum_default); - builder.add_non_owning_reference(args.non_owning_reference); - builder.add_co_owning_reference(args.co_owning_reference); - builder.add_single_weak_reference(args.single_weak_reference); - builder.add_testhashu64_fnv1a(args.testhashu64_fnv1a); - builder.add_testhashs64_fnv1a(args.testhashs64_fnv1a); - builder.add_testhashu64_fnv1(args.testhashu64_fnv1); - builder.add_testhashs64_fnv1(args.testhashs64_fnv1); - builder.add_negative_infinity_default(args.negative_infinity_default); - builder.add_negative_inf_default(args.negative_inf_default); - builder.add_positive_infinity_default(args.positive_infinity_default); - builder.add_infinity_default(args.infinity_default); - builder.add_positive_inf_default(args.positive_inf_default); - builder.add_inf_default(args.inf_default); - builder.add_nan_default(args.nan_default); - if let Some(x) = args.native_inline { builder.add_native_inline(x); } - if let Some(x) = args.scalar_key_sorted_tables { builder.add_scalar_key_sorted_tables(x); } - if let Some(x) = args.testrequirednestedflatbuffer { builder.add_testrequirednestedflatbuffer(x); } - if let Some(x) = args.vector_of_enums { builder.add_vector_of_enums(x); } - if let Some(x) = args.any_ambiguous { builder.add_any_ambiguous(x); } - if let Some(x) = args.any_unique { builder.add_any_unique(x); } - if let Some(x) = args.vector_of_non_owning_references { builder.add_vector_of_non_owning_references(x); } - if let Some(x) = args.vector_of_co_owning_references { builder.add_vector_of_co_owning_references(x); } - if let Some(x) = args.vector_of_strong_referrables { builder.add_vector_of_strong_referrables(x); } - if let Some(x) = args.vector_of_weak_references { builder.add_vector_of_weak_references(x); } - if let Some(x) = args.vector_of_referrables { builder.add_vector_of_referrables(x); } - if let Some(x) = args.parent_namespace_test { builder.add_parent_namespace_test(x); } - if let Some(x) = args.vector_of_doubles { builder.add_vector_of_doubles(x); } - if let Some(x) = args.vector_of_longs { builder.add_vector_of_longs(x); } - if let Some(x) = args.test5 { builder.add_test5(x); } - if let Some(x) = args.flex { builder.add_flex(x); } - if let Some(x) = args.testarrayofsortedstruct { builder.add_testarrayofsortedstruct(x); } - if let Some(x) = args.testarrayofstring2 { builder.add_testarrayofstring2(x); } - builder.add_testf3(args.testf3); - builder.add_testf2(args.testf2); - builder.add_testf(args.testf); - if let Some(x) = args.testarrayofbools { builder.add_testarrayofbools(x); } - builder.add_testhashu32_fnv1a(args.testhashu32_fnv1a); - builder.add_testhashs32_fnv1a(args.testhashs32_fnv1a); - builder.add_testhashu32_fnv1(args.testhashu32_fnv1); - builder.add_testhashs32_fnv1(args.testhashs32_fnv1); - if let Some(x) = args.testempty { builder.add_testempty(x); } - if let Some(x) = args.testnestedflatbuffer { builder.add_testnestedflatbuffer(x); } - if let Some(x) = args.enemy { builder.add_enemy(x); } - if let Some(x) = args.testarrayoftables { builder.add_testarrayoftables(x); } - if let Some(x) = args.testarrayofstring { builder.add_testarrayofstring(x); } - if let Some(x) = args.test4 { builder.add_test4(x); } - if let Some(x) = args.test { builder.add_test(x); } - if let Some(x) = args.inventory { builder.add_inventory(x); } - if let Some(x) = args.name { builder.add_name(x); } - if let Some(x) = args.pos { builder.add_pos(x); } - builder.add_hp(args.hp); - builder.add_mana(args.mana); - builder.add_signed_enum(args.signed_enum); - builder.add_any_ambiguous_type(args.any_ambiguous_type); - builder.add_any_unique_type(args.any_unique_type); - builder.add_testbool(args.testbool); - builder.add_test_type(args.test_type); - builder.add_color(args.color); - builder.finish() - } - - pub fn unpack(&self) -> MonsterT { - let pos = self.pos().map(|x| { - x.unpack() - }); - let mana = self.mana(); - let hp = self.hp(); - let name = { - let x = self.name(); - alloc::string::ToString::to_string(x) - }; - let inventory = self.inventory().map(|x| { - x.into_iter().collect() - }); - let color = self.color(); - let test = match self.test_type() { - Any::NONE => AnyT::NONE, - Any::Monster => AnyT::Monster(alloc::boxed::Box::new( - self.test_as_monster() - .expect("Invalid union table, expected `Any::Monster`.") - .unpack() - )), - Any::TestSimpleTableWithEnum => AnyT::TestSimpleTableWithEnum(alloc::boxed::Box::new( - self.test_as_test_simple_table_with_enum() - .expect("Invalid union table, expected `Any::TestSimpleTableWithEnum`.") - .unpack() - )), - Any::MyGame_Example2_Monster => AnyT::MyGameExample2Monster(alloc::boxed::Box::new( - self.test_as_my_game_example_2_monster() - .expect("Invalid union table, expected `Any::MyGame_Example2_Monster`.") - .unpack() - )), - _ => AnyT::NONE, - }; - let test4 = self.test4().map(|x| { - x.iter().map(|t| t.unpack()).collect() - }); - let testarrayofstring = self.testarrayofstring().map(|x| { - x.iter().map(|s| alloc::string::ToString::to_string(s)).collect() - }); - let testarrayoftables = self.testarrayoftables().map(|x| { - x.iter().map(|t| t.unpack()).collect() - }); - let enemy = self.enemy().map(|x| { - alloc::boxed::Box::new(x.unpack()) - }); - let testnestedflatbuffer = self.testnestedflatbuffer().map(|x| { - x.into_iter().collect() - }); - let testempty = self.testempty().map(|x| { - alloc::boxed::Box::new(x.unpack()) - }); - let testbool = self.testbool(); - let testhashs32_fnv1 = self.testhashs32_fnv1(); - let testhashu32_fnv1 = self.testhashu32_fnv1(); - let testhashs64_fnv1 = self.testhashs64_fnv1(); - let testhashu64_fnv1 = self.testhashu64_fnv1(); - let testhashs32_fnv1a = self.testhashs32_fnv1a(); - let testhashu32_fnv1a = self.testhashu32_fnv1a(); - let testhashs64_fnv1a = self.testhashs64_fnv1a(); - let testhashu64_fnv1a = self.testhashu64_fnv1a(); - let testarrayofbools = self.testarrayofbools().map(|x| { - x.into_iter().collect() - }); - let testf = self.testf(); - let testf2 = self.testf2(); - let testf3 = self.testf3(); - let testarrayofstring2 = self.testarrayofstring2().map(|x| { - x.iter().map(|s| alloc::string::ToString::to_string(s)).collect() - }); - let testarrayofsortedstruct = self.testarrayofsortedstruct().map(|x| { - x.iter().map(|t| t.unpack()).collect() - }); - let flex = self.flex().map(|x| { - x.into_iter().collect() - }); - let test5 = self.test5().map(|x| { - x.iter().map(|t| t.unpack()).collect() - }); - let vector_of_longs = self.vector_of_longs().map(|x| { - x.into_iter().collect() - }); - let vector_of_doubles = self.vector_of_doubles().map(|x| { - x.into_iter().collect() - }); - let parent_namespace_test = self.parent_namespace_test().map(|x| { - alloc::boxed::Box::new(x.unpack()) - }); - let vector_of_referrables = self.vector_of_referrables().map(|x| { - x.iter().map(|t| t.unpack()).collect() - }); - let single_weak_reference = self.single_weak_reference(); - let vector_of_weak_references = self.vector_of_weak_references().map(|x| { - x.into_iter().collect() - }); - let vector_of_strong_referrables = self.vector_of_strong_referrables().map(|x| { - x.iter().map(|t| t.unpack()).collect() - }); - let co_owning_reference = self.co_owning_reference(); - let vector_of_co_owning_references = self.vector_of_co_owning_references().map(|x| { - x.into_iter().collect() - }); - let non_owning_reference = self.non_owning_reference(); - let vector_of_non_owning_references = self.vector_of_non_owning_references().map(|x| { - x.into_iter().collect() - }); - let any_unique = match self.any_unique_type() { - AnyUniqueAliases::NONE => AnyUniqueAliasesT::NONE, - AnyUniqueAliases::M => AnyUniqueAliasesT::M(alloc::boxed::Box::new( - self.any_unique_as_m() - .expect("Invalid union table, expected `AnyUniqueAliases::M`.") - .unpack() - )), - AnyUniqueAliases::TS => AnyUniqueAliasesT::TS(alloc::boxed::Box::new( - self.any_unique_as_ts() - .expect("Invalid union table, expected `AnyUniqueAliases::TS`.") - .unpack() - )), - AnyUniqueAliases::M2 => AnyUniqueAliasesT::M2(alloc::boxed::Box::new( - self.any_unique_as_m2() - .expect("Invalid union table, expected `AnyUniqueAliases::M2`.") - .unpack() - )), - _ => AnyUniqueAliasesT::NONE, - }; - let any_ambiguous = match self.any_ambiguous_type() { - AnyAmbiguousAliases::NONE => AnyAmbiguousAliasesT::NONE, - AnyAmbiguousAliases::M1 => AnyAmbiguousAliasesT::M1(alloc::boxed::Box::new( - self.any_ambiguous_as_m1() - .expect("Invalid union table, expected `AnyAmbiguousAliases::M1`.") - .unpack() - )), - AnyAmbiguousAliases::M2 => AnyAmbiguousAliasesT::M2(alloc::boxed::Box::new( - self.any_ambiguous_as_m2() - .expect("Invalid union table, expected `AnyAmbiguousAliases::M2`.") - .unpack() - )), - AnyAmbiguousAliases::M3 => AnyAmbiguousAliasesT::M3(alloc::boxed::Box::new( - self.any_ambiguous_as_m3() - .expect("Invalid union table, expected `AnyAmbiguousAliases::M3`.") - .unpack() - )), - _ => AnyAmbiguousAliasesT::NONE, - }; - let vector_of_enums = self.vector_of_enums().map(|x| { - x.into_iter().collect() - }); - let signed_enum = self.signed_enum(); - let testrequirednestedflatbuffer = self.testrequirednestedflatbuffer().map(|x| { - x.into_iter().collect() - }); - let scalar_key_sorted_tables = self.scalar_key_sorted_tables().map(|x| { - x.iter().map(|t| t.unpack()).collect() - }); - let native_inline = self.native_inline().map(|x| { - x.unpack() - }); - let long_enum_non_enum_default = self.long_enum_non_enum_default(); - let long_enum_normal_default = self.long_enum_normal_default(); - let nan_default = self.nan_default(); - let inf_default = self.inf_default(); - let positive_inf_default = self.positive_inf_default(); - let infinity_default = self.infinity_default(); - let positive_infinity_default = self.positive_infinity_default(); - let negative_inf_default = self.negative_inf_default(); - let negative_infinity_default = self.negative_infinity_default(); - let double_inf_default = self.double_inf_default(); - MonsterT { - pos, - mana, - hp, - name, - inventory, - color, - test, - test4, - testarrayofstring, - testarrayoftables, - enemy, - testnestedflatbuffer, - testempty, - testbool, - testhashs32_fnv1, - testhashu32_fnv1, - testhashs64_fnv1, - testhashu64_fnv1, - testhashs32_fnv1a, - testhashu32_fnv1a, - testhashs64_fnv1a, - testhashu64_fnv1a, - testarrayofbools, - testf, - testf2, - testf3, - testarrayofstring2, - testarrayofsortedstruct, - flex, - test5, - vector_of_longs, - vector_of_doubles, - parent_namespace_test, - vector_of_referrables, - single_weak_reference, - vector_of_weak_references, - vector_of_strong_referrables, - co_owning_reference, - vector_of_co_owning_references, - non_owning_reference, - vector_of_non_owning_references, - any_unique, - any_ambiguous, - vector_of_enums, - signed_enum, - testrequirednestedflatbuffer, - scalar_key_sorted_tables, - native_inline, - long_enum_non_enum_default, - long_enum_normal_default, - nan_default, - inf_default, - positive_inf_default, - infinity_default, - positive_infinity_default, - negative_inf_default, - negative_infinity_default, - double_inf_default, - } - } - - #[inline] - pub fn pos(&self) -> Option<&'a Vec3> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_POS, None)} - } - - #[inline] - pub fn mana(&self) -> i16 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_MANA, Some(150)).unwrap()} - } - - #[inline] - pub fn hp(&self) -> i16 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_HP, Some(100)).unwrap()} - } - - #[inline] - pub fn name(&self) -> &'a str { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<&str>>(Monster::VT_NAME, None).unwrap()} - } - - #[inline] - pub fn key_compare_less_than(&self, o: &Monster) -> bool { - self.name() < o.name() - } - - #[inline] - pub fn key_compare_with_value(&self, val: & str) -> ::core::cmp::Ordering { - let key = self.name(); - key.cmp(val) - } - - #[inline] - pub fn inventory(&self) -> Option<::flatbuffers::Vector<'a, u8>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, u8>>>(Monster::VT_INVENTORY, None)} - } - - #[inline] - pub fn color(&self) -> Color { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_COLOR, Some(Color::Blue)).unwrap()} - } - - #[inline] - pub fn test_type(&self) -> Any { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_TEST_TYPE, Some(Any::NONE)).unwrap()} - } - - #[inline] - pub fn test(&self) -> Option<::flatbuffers::Table<'a>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Table<'a>>>(Monster::VT_TEST, None)} - } - - #[inline] - pub fn test4(&self) -> Option<::flatbuffers::Vector<'a, Test>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, Test>>>(Monster::VT_TEST4, None)} - } - - #[inline] - pub fn testarrayofstring(&self) -> Option<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset<&'a str>>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset<&'a str>>>>(Monster::VT_TESTARRAYOFSTRING, None)} - } - - /// an example documentation comment: this will end up in the generated code - /// multiline too - #[inline] - pub fn testarrayoftables(&self) -> Option<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset>>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset>>>(Monster::VT_TESTARRAYOFTABLES, None)} - } - - #[inline] - pub fn enemy(&self) -> Option> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset>(Monster::VT_ENEMY, None)} - } - - #[inline] - pub fn testnestedflatbuffer(&self) -> Option<::flatbuffers::Vector<'a, u8>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, u8>>>(Monster::VT_TESTNESTEDFLATBUFFER, None)} - } - - pub fn testnestedflatbuffer_nested_flatbuffer(&'a self) -> Option> { - self.testnestedflatbuffer().map(|data| { - use ::flatbuffers::Follow; - // Safety: - // Created from a valid Table for this object - // Which contains a valid flatbuffer in this slot - unsafe { <::flatbuffers::ForwardsUOffset>>::follow(data.bytes(), 0) } - }) - } - - #[inline] - pub fn testempty(&self) -> Option> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset>(Monster::VT_TESTEMPTY, None)} - } - - #[inline] - pub fn testbool(&self) -> bool { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_TESTBOOL, Some(false)).unwrap()} - } - - #[inline] - pub fn testhashs32_fnv1(&self) -> i32 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_TESTHASHS32_FNV1, Some(0)).unwrap()} - } - - #[inline] - pub fn testhashu32_fnv1(&self) -> u32 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_TESTHASHU32_FNV1, Some(0)).unwrap()} - } - - #[inline] - pub fn testhashs64_fnv1(&self) -> i64 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_TESTHASHS64_FNV1, Some(0)).unwrap()} - } - - #[inline] - pub fn testhashu64_fnv1(&self) -> u64 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_TESTHASHU64_FNV1, Some(0)).unwrap()} - } - - #[inline] - pub fn testhashs32_fnv1a(&self) -> i32 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_TESTHASHS32_FNV1A, Some(0)).unwrap()} - } - - #[inline] - pub fn testhashu32_fnv1a(&self) -> u32 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_TESTHASHU32_FNV1A, Some(0)).unwrap()} - } - - #[inline] - pub fn testhashs64_fnv1a(&self) -> i64 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_TESTHASHS64_FNV1A, Some(0)).unwrap()} - } - - #[inline] - pub fn testhashu64_fnv1a(&self) -> u64 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_TESTHASHU64_FNV1A, Some(0)).unwrap()} - } - - #[inline] - pub fn testarrayofbools(&self) -> Option<::flatbuffers::Vector<'a, bool>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, bool>>>(Monster::VT_TESTARRAYOFBOOLS, None)} - } - - #[inline] - pub fn testf(&self) -> f32 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_TESTF, Some(3.14159)).unwrap()} - } - - #[inline] - pub fn testf2(&self) -> f32 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_TESTF2, Some(3.0)).unwrap()} - } - - #[inline] - pub fn testf3(&self) -> f32 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_TESTF3, Some(0.0)).unwrap()} - } - - #[inline] - pub fn testarrayofstring2(&self) -> Option<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset<&'a str>>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset<&'a str>>>>(Monster::VT_TESTARRAYOFSTRING2, None)} - } - - #[inline] - pub fn testarrayofsortedstruct(&self) -> Option<::flatbuffers::Vector<'a, Ability>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, Ability>>>(Monster::VT_TESTARRAYOFSORTEDSTRUCT, None)} - } - - #[inline] - pub fn flex(&self) -> Option<::flatbuffers::Vector<'a, u8>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, u8>>>(Monster::VT_FLEX, None)} - } - - #[inline] - pub fn test5(&self) -> Option<::flatbuffers::Vector<'a, Test>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, Test>>>(Monster::VT_TEST5, None)} - } - - #[inline] - pub fn vector_of_longs(&self) -> Option<::flatbuffers::Vector<'a, i64>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, i64>>>(Monster::VT_VECTOR_OF_LONGS, None)} - } - - #[inline] - pub fn vector_of_doubles(&self) -> Option<::flatbuffers::Vector<'a, f64>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, f64>>>(Monster::VT_VECTOR_OF_DOUBLES, None)} - } - - #[inline] - pub fn parent_namespace_test(&self) -> Option> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset>(Monster::VT_PARENT_NAMESPACE_TEST, None)} - } - - #[inline] - pub fn vector_of_referrables(&self) -> Option<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset>>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset>>>(Monster::VT_VECTOR_OF_REFERRABLES, None)} - } - - #[inline] - pub fn single_weak_reference(&self) -> u64 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_SINGLE_WEAK_REFERENCE, Some(0)).unwrap()} - } - - #[inline] - pub fn vector_of_weak_references(&self) -> Option<::flatbuffers::Vector<'a, u64>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, u64>>>(Monster::VT_VECTOR_OF_WEAK_REFERENCES, None)} - } - - #[inline] - pub fn vector_of_strong_referrables(&self) -> Option<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset>>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset>>>(Monster::VT_VECTOR_OF_STRONG_REFERRABLES, None)} - } - - #[inline] - pub fn co_owning_reference(&self) -> u64 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_CO_OWNING_REFERENCE, Some(0)).unwrap()} - } - - #[inline] - pub fn vector_of_co_owning_references(&self) -> Option<::flatbuffers::Vector<'a, u64>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, u64>>>(Monster::VT_VECTOR_OF_CO_OWNING_REFERENCES, None)} - } - - #[inline] - pub fn non_owning_reference(&self) -> u64 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_NON_OWNING_REFERENCE, Some(0)).unwrap()} - } - - #[inline] - pub fn vector_of_non_owning_references(&self) -> Option<::flatbuffers::Vector<'a, u64>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, u64>>>(Monster::VT_VECTOR_OF_NON_OWNING_REFERENCES, None)} - } - - #[inline] - pub fn any_unique_type(&self) -> AnyUniqueAliases { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_ANY_UNIQUE_TYPE, Some(AnyUniqueAliases::NONE)).unwrap()} - } - - #[inline] - pub fn any_unique(&self) -> Option<::flatbuffers::Table<'a>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Table<'a>>>(Monster::VT_ANY_UNIQUE, None)} - } - - #[inline] - pub fn any_ambiguous_type(&self) -> AnyAmbiguousAliases { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_ANY_AMBIGUOUS_TYPE, Some(AnyAmbiguousAliases::NONE)).unwrap()} - } - - #[inline] - pub fn any_ambiguous(&self) -> Option<::flatbuffers::Table<'a>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Table<'a>>>(Monster::VT_ANY_AMBIGUOUS, None)} - } - - #[inline] - pub fn vector_of_enums(&self) -> Option<::flatbuffers::Vector<'a, Color>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, Color>>>(Monster::VT_VECTOR_OF_ENUMS, None)} - } - - #[inline] - pub fn signed_enum(&self) -> Race { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_SIGNED_ENUM, Some(Race::None)).unwrap()} - } - - #[inline] - pub fn testrequirednestedflatbuffer(&self) -> Option<::flatbuffers::Vector<'a, u8>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, u8>>>(Monster::VT_TESTREQUIREDNESTEDFLATBUFFER, None)} - } - - pub fn testrequirednestedflatbuffer_nested_flatbuffer(&'a self) -> Option> { - self.testrequirednestedflatbuffer().map(|data| { - use ::flatbuffers::Follow; - // Safety: - // Created from a valid Table for this object - // Which contains a valid flatbuffer in this slot - unsafe { <::flatbuffers::ForwardsUOffset>>::follow(data.bytes(), 0) } - }) - } - - #[inline] - pub fn scalar_key_sorted_tables(&self) -> Option<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset>>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset>>>(Monster::VT_SCALAR_KEY_SORTED_TABLES, None)} - } - - #[inline] - pub fn native_inline(&self) -> Option<&'a Test> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_NATIVE_INLINE, None)} - } - - #[inline] - pub fn long_enum_non_enum_default(&self) -> LongEnum { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_LONG_ENUM_NON_ENUM_DEFAULT, Some(Default::default())).unwrap()} - } - - #[inline] - pub fn long_enum_normal_default(&self) -> LongEnum { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_LONG_ENUM_NORMAL_DEFAULT, Some(LongEnum::LongOne)).unwrap()} - } - - #[inline] - pub fn nan_default(&self) -> f32 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_NAN_DEFAULT, Some(f32::NAN)).unwrap()} - } - - #[inline] - pub fn inf_default(&self) -> f32 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_INF_DEFAULT, Some(f32::INFINITY)).unwrap()} - } - - #[inline] - pub fn positive_inf_default(&self) -> f32 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_POSITIVE_INF_DEFAULT, Some(f32::INFINITY)).unwrap()} - } - - #[inline] - pub fn infinity_default(&self) -> f32 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_INFINITY_DEFAULT, Some(f32::INFINITY)).unwrap()} - } - - #[inline] - pub fn positive_infinity_default(&self) -> f32 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_POSITIVE_INFINITY_DEFAULT, Some(f32::INFINITY)).unwrap()} - } - - #[inline] - pub fn negative_inf_default(&self) -> f32 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_NEGATIVE_INF_DEFAULT, Some(f32::NEG_INFINITY)).unwrap()} - } - - #[inline] - pub fn negative_infinity_default(&self) -> f32 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_NEGATIVE_INFINITY_DEFAULT, Some(f32::NEG_INFINITY)).unwrap()} - } - - #[inline] - pub fn double_inf_default(&self) -> f64 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_DOUBLE_INF_DEFAULT, Some(f64::INFINITY)).unwrap()} - } - - #[inline] - #[allow(non_snake_case)] - pub fn test_as_monster(&self) -> Option> { - if self.test_type() == Any::Monster { - self.test().map(|t| { - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - unsafe { Monster::init_from_table(t) } - }) - } else { - None - } - } - - #[inline] - #[allow(non_snake_case)] - pub fn test_as_test_simple_table_with_enum(&self) -> Option> { - if self.test_type() == Any::TestSimpleTableWithEnum { - self.test().map(|t| { - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - unsafe { TestSimpleTableWithEnum::init_from_table(t) } - }) - } else { - None - } - } - - #[inline] - #[allow(non_snake_case)] - pub fn test_as_my_game_example_2_monster(&self) -> Option> { - if self.test_type() == Any::MyGame_Example2_Monster { - self.test().map(|t| { - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - unsafe { super::example_2::Monster::init_from_table(t) } - }) - } else { - None - } - } - - #[inline] - #[allow(non_snake_case)] - pub fn any_unique_as_m(&self) -> Option> { - if self.any_unique_type() == AnyUniqueAliases::M { - self.any_unique().map(|t| { - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - unsafe { Monster::init_from_table(t) } - }) - } else { - None - } - } - - #[inline] - #[allow(non_snake_case)] - pub fn any_unique_as_ts(&self) -> Option> { - if self.any_unique_type() == AnyUniqueAliases::TS { - self.any_unique().map(|t| { - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - unsafe { TestSimpleTableWithEnum::init_from_table(t) } - }) - } else { - None - } - } - - #[inline] - #[allow(non_snake_case)] - pub fn any_unique_as_m2(&self) -> Option> { - if self.any_unique_type() == AnyUniqueAliases::M2 { - self.any_unique().map(|t| { - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - unsafe { super::example_2::Monster::init_from_table(t) } - }) - } else { - None - } - } - - #[inline] - #[allow(non_snake_case)] - pub fn any_ambiguous_as_m1(&self) -> Option> { - if self.any_ambiguous_type() == AnyAmbiguousAliases::M1 { - self.any_ambiguous().map(|t| { - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - unsafe { Monster::init_from_table(t) } - }) - } else { - None - } - } - - #[inline] - #[allow(non_snake_case)] - pub fn any_ambiguous_as_m2(&self) -> Option> { - if self.any_ambiguous_type() == AnyAmbiguousAliases::M2 { - self.any_ambiguous().map(|t| { - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - unsafe { Monster::init_from_table(t) } - }) - } else { - None - } - } - - #[inline] - #[allow(non_snake_case)] - pub fn any_ambiguous_as_m3(&self) -> Option> { - if self.any_ambiguous_type() == AnyAmbiguousAliases::M3 { - self.any_ambiguous().map(|t| { - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - unsafe { Monster::init_from_table(t) } - }) - } else { - None - } - } } impl ::flatbuffers::Verifiable for Monster<'_> { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.visit_table(pos)? - .visit_field::("pos", Self::VT_POS, false)? - .visit_field::("mana", Self::VT_MANA, false)? - .visit_field::("hp", Self::VT_HP, false)? - .visit_field::<::flatbuffers::ForwardsUOffset<&str>>("name", Self::VT_NAME, true)? - .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, u8>>>("inventory", Self::VT_INVENTORY, false)? - .visit_field::("color", Self::VT_COLOR, false)? - .visit_union::("test_type", Self::VT_TEST_TYPE, "test", Self::VT_TEST, false, |key, v, pos| { - match key { - Any::Monster => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("Any::Monster", pos), - Any::TestSimpleTableWithEnum => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("Any::TestSimpleTableWithEnum", pos), - Any::MyGame_Example2_Monster => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("Any::MyGame_Example2_Monster", pos), - _ => Ok(()), - } - })? - .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, Test>>>("test4", Self::VT_TEST4, false)? - .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, ::flatbuffers::ForwardsUOffset<&'_ str>>>>("testarrayofstring", Self::VT_TESTARRAYOFSTRING, false)? - .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, ::flatbuffers::ForwardsUOffset>>>("testarrayoftables", Self::VT_TESTARRAYOFTABLES, false)? - .visit_field::<::flatbuffers::ForwardsUOffset>("enemy", Self::VT_ENEMY, false)? - .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, u8>>>("testnestedflatbuffer", Self::VT_TESTNESTEDFLATBUFFER, false)? - .visit_field::<::flatbuffers::ForwardsUOffset>("testempty", Self::VT_TESTEMPTY, false)? - .visit_field::("testbool", Self::VT_TESTBOOL, false)? - .visit_field::("testhashs32_fnv1", Self::VT_TESTHASHS32_FNV1, false)? - .visit_field::("testhashu32_fnv1", Self::VT_TESTHASHU32_FNV1, false)? - .visit_field::("testhashs64_fnv1", Self::VT_TESTHASHS64_FNV1, false)? - .visit_field::("testhashu64_fnv1", Self::VT_TESTHASHU64_FNV1, false)? - .visit_field::("testhashs32_fnv1a", Self::VT_TESTHASHS32_FNV1A, false)? - .visit_field::("testhashu32_fnv1a", Self::VT_TESTHASHU32_FNV1A, false)? - .visit_field::("testhashs64_fnv1a", Self::VT_TESTHASHS64_FNV1A, false)? - .visit_field::("testhashu64_fnv1a", Self::VT_TESTHASHU64_FNV1A, false)? - .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, bool>>>("testarrayofbools", Self::VT_TESTARRAYOFBOOLS, false)? - .visit_field::("testf", Self::VT_TESTF, false)? - .visit_field::("testf2", Self::VT_TESTF2, false)? - .visit_field::("testf3", Self::VT_TESTF3, false)? - .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, ::flatbuffers::ForwardsUOffset<&'_ str>>>>("testarrayofstring2", Self::VT_TESTARRAYOFSTRING2, false)? - .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, Ability>>>("testarrayofsortedstruct", Self::VT_TESTARRAYOFSORTEDSTRUCT, false)? - .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, u8>>>("flex", Self::VT_FLEX, false)? - .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, Test>>>("test5", Self::VT_TEST5, false)? - .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, i64>>>("vector_of_longs", Self::VT_VECTOR_OF_LONGS, false)? - .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, f64>>>("vector_of_doubles", Self::VT_VECTOR_OF_DOUBLES, false)? - .visit_field::<::flatbuffers::ForwardsUOffset>("parent_namespace_test", Self::VT_PARENT_NAMESPACE_TEST, false)? - .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, ::flatbuffers::ForwardsUOffset>>>("vector_of_referrables", Self::VT_VECTOR_OF_REFERRABLES, false)? - .visit_field::("single_weak_reference", Self::VT_SINGLE_WEAK_REFERENCE, false)? - .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, u64>>>("vector_of_weak_references", Self::VT_VECTOR_OF_WEAK_REFERENCES, false)? - .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, ::flatbuffers::ForwardsUOffset>>>("vector_of_strong_referrables", Self::VT_VECTOR_OF_STRONG_REFERRABLES, false)? - .visit_field::("co_owning_reference", Self::VT_CO_OWNING_REFERENCE, false)? - .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, u64>>>("vector_of_co_owning_references", Self::VT_VECTOR_OF_CO_OWNING_REFERENCES, false)? - .visit_field::("non_owning_reference", Self::VT_NON_OWNING_REFERENCE, false)? - .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, u64>>>("vector_of_non_owning_references", Self::VT_VECTOR_OF_NON_OWNING_REFERENCES, false)? - .visit_union::("any_unique_type", Self::VT_ANY_UNIQUE_TYPE, "any_unique", Self::VT_ANY_UNIQUE, false, |key, v, pos| { - match key { - AnyUniqueAliases::M => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("AnyUniqueAliases::M", pos), - AnyUniqueAliases::TS => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("AnyUniqueAliases::TS", pos), - AnyUniqueAliases::M2 => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("AnyUniqueAliases::M2", pos), - _ => Ok(()), - } - })? - .visit_union::("any_ambiguous_type", Self::VT_ANY_AMBIGUOUS_TYPE, "any_ambiguous", Self::VT_ANY_AMBIGUOUS, false, |key, v, pos| { - match key { - AnyAmbiguousAliases::M1 => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("AnyAmbiguousAliases::M1", pos), - AnyAmbiguousAliases::M2 => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("AnyAmbiguousAliases::M2", pos), - AnyAmbiguousAliases::M3 => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("AnyAmbiguousAliases::M3", pos), - _ => Ok(()), - } - })? - .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, Color>>>("vector_of_enums", Self::VT_VECTOR_OF_ENUMS, false)? - .visit_field::("signed_enum", Self::VT_SIGNED_ENUM, false)? - .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, u8>>>("testrequirednestedflatbuffer", Self::VT_TESTREQUIREDNESTEDFLATBUFFER, false)? - .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, ::flatbuffers::ForwardsUOffset>>>("scalar_key_sorted_tables", Self::VT_SCALAR_KEY_SORTED_TABLES, false)? - .visit_field::("native_inline", Self::VT_NATIVE_INLINE, false)? - .visit_field::("long_enum_non_enum_default", Self::VT_LONG_ENUM_NON_ENUM_DEFAULT, false)? - .visit_field::("long_enum_normal_default", Self::VT_LONG_ENUM_NORMAL_DEFAULT, false)? - .visit_field::("nan_default", Self::VT_NAN_DEFAULT, false)? - .visit_field::("inf_default", Self::VT_INF_DEFAULT, false)? - .visit_field::("positive_inf_default", Self::VT_POSITIVE_INF_DEFAULT, false)? - .visit_field::("infinity_default", Self::VT_INFINITY_DEFAULT, false)? - .visit_field::("positive_infinity_default", Self::VT_POSITIVE_INFINITY_DEFAULT, false)? - .visit_field::("negative_inf_default", Self::VT_NEGATIVE_INF_DEFAULT, false)? - .visit_field::("negative_infinity_default", Self::VT_NEGATIVE_INFINITY_DEFAULT, false)? - .visit_field::("double_inf_default", Self::VT_DOUBLE_INF_DEFAULT, false)? - .finish(); - Ok(()) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.visit_table(pos)? + .visit_field::("pos", Self::VT_POS, false)? + .visit_field::("mana", Self::VT_MANA, false)? + .visit_field::("hp", Self::VT_HP, false)? + .visit_field::<::flatbuffers::ForwardsUOffset<&str>>("name", Self::VT_NAME, true)? + .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, u8>>>("inventory", Self::VT_INVENTORY, false)? + .visit_field::("color", Self::VT_COLOR, false)? + .visit_union::("test_type", Self::VT_TEST_TYPE, "test", Self::VT_TEST, false, |key, v, pos| { + match key { + Any::Monster => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("Any::Monster", pos), + Any::TestSimpleTableWithEnum => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("Any::TestSimpleTableWithEnum", pos), + Any::MyGame_Example2_Monster => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("Any::MyGame_Example2_Monster", pos), + _ => Ok(()), + } + })? + .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, Test>>>("test4", Self::VT_TEST4, false)? + .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, ::flatbuffers::ForwardsUOffset<&'_ str>>>>("testarrayofstring", Self::VT_TESTARRAYOFSTRING, false)? + .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, ::flatbuffers::ForwardsUOffset>>>("testarrayoftables", Self::VT_TESTARRAYOFTABLES, false)? + .visit_field::<::flatbuffers::ForwardsUOffset>("enemy", Self::VT_ENEMY, false)? + .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, u8>>>("testnestedflatbuffer", Self::VT_TESTNESTEDFLATBUFFER, false)? + .visit_field::<::flatbuffers::ForwardsUOffset>("testempty", Self::VT_TESTEMPTY, false)? + .visit_field::("testbool", Self::VT_TESTBOOL, false)? + .visit_field::("testhashs32_fnv1", Self::VT_TESTHASHS32_FNV1, false)? + .visit_field::("testhashu32_fnv1", Self::VT_TESTHASHU32_FNV1, false)? + .visit_field::("testhashs64_fnv1", Self::VT_TESTHASHS64_FNV1, false)? + .visit_field::("testhashu64_fnv1", Self::VT_TESTHASHU64_FNV1, false)? + .visit_field::("testhashs32_fnv1a", Self::VT_TESTHASHS32_FNV1A, false)? + .visit_field::("testhashu32_fnv1a", Self::VT_TESTHASHU32_FNV1A, false)? + .visit_field::("testhashs64_fnv1a", Self::VT_TESTHASHS64_FNV1A, false)? + .visit_field::("testhashu64_fnv1a", Self::VT_TESTHASHU64_FNV1A, false)? + .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, bool>>>("testarrayofbools", Self::VT_TESTARRAYOFBOOLS, false)? + .visit_field::("testf", Self::VT_TESTF, false)? + .visit_field::("testf2", Self::VT_TESTF2, false)? + .visit_field::("testf3", Self::VT_TESTF3, false)? + .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, ::flatbuffers::ForwardsUOffset<&'_ str>>>>("testarrayofstring2", Self::VT_TESTARRAYOFSTRING2, false)? + .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, Ability>>>("testarrayofsortedstruct", Self::VT_TESTARRAYOFSORTEDSTRUCT, false)? + .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, u8>>>("flex", Self::VT_FLEX, false)? + .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, Test>>>("test5", Self::VT_TEST5, false)? + .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, i64>>>("vector_of_longs", Self::VT_VECTOR_OF_LONGS, false)? + .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, f64>>>("vector_of_doubles", Self::VT_VECTOR_OF_DOUBLES, false)? + .visit_field::<::flatbuffers::ForwardsUOffset>("parent_namespace_test", Self::VT_PARENT_NAMESPACE_TEST, false)? + .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, ::flatbuffers::ForwardsUOffset>>>("vector_of_referrables", Self::VT_VECTOR_OF_REFERRABLES, false)? + .visit_field::("single_weak_reference", Self::VT_SINGLE_WEAK_REFERENCE, false)? + .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, u64>>>("vector_of_weak_references", Self::VT_VECTOR_OF_WEAK_REFERENCES, false)? + .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, ::flatbuffers::ForwardsUOffset>>>("vector_of_strong_referrables", Self::VT_VECTOR_OF_STRONG_REFERRABLES, false)? + .visit_field::("co_owning_reference", Self::VT_CO_OWNING_REFERENCE, false)? + .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, u64>>>("vector_of_co_owning_references", Self::VT_VECTOR_OF_CO_OWNING_REFERENCES, false)? + .visit_field::("non_owning_reference", Self::VT_NON_OWNING_REFERENCE, false)? + .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, u64>>>("vector_of_non_owning_references", Self::VT_VECTOR_OF_NON_OWNING_REFERENCES, false)? + .visit_union::("any_unique_type", Self::VT_ANY_UNIQUE_TYPE, "any_unique", Self::VT_ANY_UNIQUE, false, |key, v, pos| { + match key { + AnyUniqueAliases::M => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("AnyUniqueAliases::M", pos), + AnyUniqueAliases::TS => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("AnyUniqueAliases::TS", pos), + AnyUniqueAliases::M2 => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("AnyUniqueAliases::M2", pos), + _ => Ok(()), + } + })? + .visit_union::("any_ambiguous_type", Self::VT_ANY_AMBIGUOUS_TYPE, "any_ambiguous", Self::VT_ANY_AMBIGUOUS, false, |key, v, pos| { + match key { + AnyAmbiguousAliases::M1 => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("AnyAmbiguousAliases::M1", pos), + AnyAmbiguousAliases::M2 => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("AnyAmbiguousAliases::M2", pos), + AnyAmbiguousAliases::M3 => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("AnyAmbiguousAliases::M3", pos), + _ => Ok(()), + } + })? + .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, Color>>>("vector_of_enums", Self::VT_VECTOR_OF_ENUMS, false)? + .visit_field::("signed_enum", Self::VT_SIGNED_ENUM, false)? + .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, u8>>>("testrequirednestedflatbuffer", Self::VT_TESTREQUIREDNESTEDFLATBUFFER, false)? + .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, ::flatbuffers::ForwardsUOffset>>>("scalar_key_sorted_tables", Self::VT_SCALAR_KEY_SORTED_TABLES, false)? + .visit_field::("native_inline", Self::VT_NATIVE_INLINE, false)? + .visit_field::("long_enum_non_enum_default", Self::VT_LONG_ENUM_NON_ENUM_DEFAULT, false)? + .visit_field::("long_enum_normal_default", Self::VT_LONG_ENUM_NORMAL_DEFAULT, false)? + .visit_field::("nan_default", Self::VT_NAN_DEFAULT, false)? + .visit_field::("inf_default", Self::VT_INF_DEFAULT, false)? + .visit_field::("positive_inf_default", Self::VT_POSITIVE_INF_DEFAULT, false)? + .visit_field::("infinity_default", Self::VT_INFINITY_DEFAULT, false)? + .visit_field::("positive_infinity_default", Self::VT_POSITIVE_INFINITY_DEFAULT, false)? + .visit_field::("negative_inf_default", Self::VT_NEGATIVE_INF_DEFAULT, false)? + .visit_field::("negative_infinity_default", Self::VT_NEGATIVE_INFINITY_DEFAULT, false)? + .visit_field::("double_inf_default", Self::VT_DOUBLE_INF_DEFAULT, false)? + .finish(); + Ok(()) + } } - pub struct MonsterArgs<'a> { pub pos: Option<&'a Vec3>, pub mana: i16, @@ -1200,937 +1133,863 @@ pub struct MonsterArgs<'a> { pub negative_infinity_default: f32, pub double_inf_default: f64, } - impl<'a> Default for MonsterArgs<'a> { - #[inline] - fn default() -> Self { - MonsterArgs { - pos: None, - mana: 150, - hp: 100, - name: None, // required field - inventory: None, - color: Color::Blue, - test_type: Any::NONE, - test: None, - test4: None, - testarrayofstring: None, - testarrayoftables: None, - enemy: None, - testnestedflatbuffer: None, - testempty: None, - testbool: false, - testhashs32_fnv1: 0, - testhashu32_fnv1: 0, - testhashs64_fnv1: 0, - testhashu64_fnv1: 0, - testhashs32_fnv1a: 0, - testhashu32_fnv1a: 0, - testhashs64_fnv1a: 0, - testhashu64_fnv1a: 0, - testarrayofbools: None, - testf: 3.14159, - testf2: 3.0, - testf3: 0.0, - testarrayofstring2: None, - testarrayofsortedstruct: None, - flex: None, - test5: None, - vector_of_longs: None, - vector_of_doubles: None, - parent_namespace_test: None, - vector_of_referrables: None, - single_weak_reference: 0, - vector_of_weak_references: None, - vector_of_strong_referrables: None, - co_owning_reference: 0, - vector_of_co_owning_references: None, - non_owning_reference: 0, - vector_of_non_owning_references: None, - any_unique_type: AnyUniqueAliases::NONE, - any_unique: None, - any_ambiguous_type: AnyAmbiguousAliases::NONE, - any_ambiguous: None, - vector_of_enums: None, - signed_enum: Race::None, - testrequirednestedflatbuffer: None, - scalar_key_sorted_tables: None, - native_inline: None, - long_enum_non_enum_default: Default::default(), - long_enum_normal_default: LongEnum::LongOne, - nan_default: f32::NAN, - inf_default: f32::INFINITY, - positive_inf_default: f32::INFINITY, - infinity_default: f32::INFINITY, - positive_infinity_default: f32::INFINITY, - negative_inf_default: f32::NEG_INFINITY, - negative_infinity_default: f32::NEG_INFINITY, - double_inf_default: f64::INFINITY, - } + #[inline] + fn default() -> Self { + MonsterArgs { + pos: None, + mana: 150, + hp: 100, + name: None, // required field + inventory: None, + color: Color::Blue, + test_type: Any::NONE, + test: None, + test4: None, + testarrayofstring: None, + testarrayoftables: None, + enemy: None, + testnestedflatbuffer: None, + testempty: None, + testbool: false, + testhashs32_fnv1: 0, + testhashu32_fnv1: 0, + testhashs64_fnv1: 0, + testhashu64_fnv1: 0, + testhashs32_fnv1a: 0, + testhashu32_fnv1a: 0, + testhashs64_fnv1a: 0, + testhashu64_fnv1a: 0, + testarrayofbools: None, + testf: 3.14159, + testf2: 3.0, + testf3: 0.0, + testarrayofstring2: None, + testarrayofsortedstruct: None, + flex: None, + test5: None, + vector_of_longs: None, + vector_of_doubles: None, + parent_namespace_test: None, + vector_of_referrables: None, + single_weak_reference: 0, + vector_of_weak_references: None, + vector_of_strong_referrables: None, + co_owning_reference: 0, + vector_of_co_owning_references: None, + non_owning_reference: 0, + vector_of_non_owning_references: None, + any_unique_type: AnyUniqueAliases::NONE, + any_unique: None, + any_ambiguous_type: AnyAmbiguousAliases::NONE, + any_ambiguous: None, + vector_of_enums: None, + signed_enum: Race::None, + testrequirednestedflatbuffer: None, + scalar_key_sorted_tables: None, + native_inline: None, + long_enum_non_enum_default: Default::default(), + long_enum_normal_default: LongEnum::LongOne, + nan_default: f32::NAN, + inf_default: f32::INFINITY, + positive_inf_default: f32::INFINITY, + infinity_default: f32::INFINITY, + positive_infinity_default: f32::INFINITY, + negative_inf_default: f32::NEG_INFINITY, + negative_infinity_default: f32::NEG_INFINITY, + double_inf_default: f64::INFINITY, } + } } pub struct MonsterBuilder<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> { - fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, + fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, + start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, } - impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> MonsterBuilder<'a, 'b, A> { - #[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::(Monster::VT_MANA, mana, 150); - } - - #[inline] - pub fn add_hp(&mut self, hp: i16) { - self.fbb_.push_slot::(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::(Monster::VT_COLOR, color, Color::Blue); - } - - #[inline] - pub fn add_test_type(&mut self, test_type: Any) { - self.fbb_.push_slot::(Monster::VT_TEST_TYPE, test_type, Any::NONE); - } - - #[inline] - pub fn add_test(&mut self, test: ::flatbuffers::WIPOffset<::flatbuffers::UnionWIPOffset>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_TEST, test); - } - - #[inline] - pub fn add_test4(&mut self, test4: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , Test>>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_TEST4, test4); - } - - #[inline] - pub fn add_testarrayofstring(&mut self, testarrayofstring: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , ::flatbuffers::ForwardsUOffset<&'b str>>>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_TESTARRAYOFSTRING, testarrayofstring); - } - - #[inline] - pub fn add_testarrayoftables(&mut self, testarrayoftables: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , ::flatbuffers::ForwardsUOffset>>>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_TESTARRAYOFTABLES, testarrayoftables); - } - - #[inline] - pub fn add_enemy(&mut self, enemy: ::flatbuffers::WIPOffset>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset>(Monster::VT_ENEMY, enemy); - } - - #[inline] - pub fn add_testnestedflatbuffer(&mut self, testnestedflatbuffer: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , u8>>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_TESTNESTEDFLATBUFFER, testnestedflatbuffer); - } - - #[inline] - pub fn add_testempty(&mut self, testempty: ::flatbuffers::WIPOffset>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset>(Monster::VT_TESTEMPTY, testempty); - } - - #[inline] - pub fn add_testbool(&mut self, testbool: bool) { - self.fbb_.push_slot::(Monster::VT_TESTBOOL, testbool, false); - } - - #[inline] - pub fn add_testhashs32_fnv1(&mut self, testhashs32_fnv1: i32) { - self.fbb_.push_slot::(Monster::VT_TESTHASHS32_FNV1, testhashs32_fnv1, 0); - } - - #[inline] - pub fn add_testhashu32_fnv1(&mut self, testhashu32_fnv1: u32) { - self.fbb_.push_slot::(Monster::VT_TESTHASHU32_FNV1, testhashu32_fnv1, 0); - } - - #[inline] - pub fn add_testhashs64_fnv1(&mut self, testhashs64_fnv1: i64) { - self.fbb_.push_slot::(Monster::VT_TESTHASHS64_FNV1, testhashs64_fnv1, 0); - } - - #[inline] - pub fn add_testhashu64_fnv1(&mut self, testhashu64_fnv1: u64) { - self.fbb_.push_slot::(Monster::VT_TESTHASHU64_FNV1, testhashu64_fnv1, 0); - } - - #[inline] - pub fn add_testhashs32_fnv1a(&mut self, testhashs32_fnv1a: i32) { - self.fbb_.push_slot::(Monster::VT_TESTHASHS32_FNV1A, testhashs32_fnv1a, 0); - } - - #[inline] - pub fn add_testhashu32_fnv1a(&mut self, testhashu32_fnv1a: u32) { - self.fbb_.push_slot::(Monster::VT_TESTHASHU32_FNV1A, testhashu32_fnv1a, 0); - } - - #[inline] - pub fn add_testhashs64_fnv1a(&mut self, testhashs64_fnv1a: i64) { - self.fbb_.push_slot::(Monster::VT_TESTHASHS64_FNV1A, testhashs64_fnv1a, 0); - } - - #[inline] - pub fn add_testhashu64_fnv1a(&mut self, testhashu64_fnv1a: u64) { - self.fbb_.push_slot::(Monster::VT_TESTHASHU64_FNV1A, testhashu64_fnv1a, 0); - } - - #[inline] - pub fn add_testarrayofbools(&mut self, testarrayofbools: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , bool>>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_TESTARRAYOFBOOLS, testarrayofbools); - } - - #[inline] - pub fn add_testf(&mut self, testf: f32) { - self.fbb_.push_slot::(Monster::VT_TESTF, testf, 3.14159); - } - - #[inline] - pub fn add_testf2(&mut self, testf2: f32) { - self.fbb_.push_slot::(Monster::VT_TESTF2, testf2, 3.0); - } - - #[inline] - pub fn add_testf3(&mut self, testf3: f32) { - self.fbb_.push_slot::(Monster::VT_TESTF3, testf3, 0.0); - } - - #[inline] - pub fn add_testarrayofstring2(&mut self, testarrayofstring2: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , ::flatbuffers::ForwardsUOffset<&'b str>>>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_TESTARRAYOFSTRING2, testarrayofstring2); - } - - #[inline] - pub fn add_testarrayofsortedstruct(&mut self, testarrayofsortedstruct: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , Ability>>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_TESTARRAYOFSORTEDSTRUCT, testarrayofsortedstruct); - } - - #[inline] - pub fn add_flex(&mut self, flex: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , u8>>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_FLEX, flex); - } - - #[inline] - pub fn add_test5(&mut self, test5: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , Test>>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_TEST5, test5); - } - - #[inline] - pub fn add_vector_of_longs(&mut self, vector_of_longs: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , i64>>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_LONGS, vector_of_longs); - } - - #[inline] - pub fn add_vector_of_doubles(&mut self, vector_of_doubles: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , f64>>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_DOUBLES, vector_of_doubles); - } - - #[inline] - pub fn add_parent_namespace_test(&mut self, parent_namespace_test: ::flatbuffers::WIPOffset>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset>(Monster::VT_PARENT_NAMESPACE_TEST, parent_namespace_test); - } - - #[inline] - pub fn add_vector_of_referrables(&mut self, vector_of_referrables: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , ::flatbuffers::ForwardsUOffset>>>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_REFERRABLES, vector_of_referrables); - } - - #[inline] - pub fn add_single_weak_reference(&mut self, single_weak_reference: u64) { - self.fbb_.push_slot::(Monster::VT_SINGLE_WEAK_REFERENCE, single_weak_reference, 0); - } - - #[inline] - pub fn add_vector_of_weak_references(&mut self, vector_of_weak_references: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , u64>>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_WEAK_REFERENCES, vector_of_weak_references); - } - - #[inline] - pub fn add_vector_of_strong_referrables(&mut self, vector_of_strong_referrables: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , ::flatbuffers::ForwardsUOffset>>>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_STRONG_REFERRABLES, vector_of_strong_referrables); - } - - #[inline] - pub fn add_co_owning_reference(&mut self, co_owning_reference: u64) { - self.fbb_.push_slot::(Monster::VT_CO_OWNING_REFERENCE, co_owning_reference, 0); - } - - #[inline] - pub fn add_vector_of_co_owning_references(&mut self, vector_of_co_owning_references: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , u64>>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_CO_OWNING_REFERENCES, vector_of_co_owning_references); - } - - #[inline] - pub fn add_non_owning_reference(&mut self, non_owning_reference: u64) { - self.fbb_.push_slot::(Monster::VT_NON_OWNING_REFERENCE, non_owning_reference, 0); - } - - #[inline] - pub fn add_vector_of_non_owning_references(&mut self, vector_of_non_owning_references: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , u64>>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_NON_OWNING_REFERENCES, vector_of_non_owning_references); - } - - #[inline] - pub fn add_any_unique_type(&mut self, any_unique_type: AnyUniqueAliases) { - self.fbb_.push_slot::(Monster::VT_ANY_UNIQUE_TYPE, any_unique_type, AnyUniqueAliases::NONE); - } - - #[inline] - pub fn add_any_unique(&mut self, any_unique: ::flatbuffers::WIPOffset<::flatbuffers::UnionWIPOffset>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_ANY_UNIQUE, any_unique); - } - - #[inline] - pub fn add_any_ambiguous_type(&mut self, any_ambiguous_type: AnyAmbiguousAliases) { - self.fbb_.push_slot::(Monster::VT_ANY_AMBIGUOUS_TYPE, any_ambiguous_type, AnyAmbiguousAliases::NONE); - } - - #[inline] - pub fn add_any_ambiguous(&mut self, any_ambiguous: ::flatbuffers::WIPOffset<::flatbuffers::UnionWIPOffset>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_ANY_AMBIGUOUS, any_ambiguous); - } - - #[inline] - pub fn add_vector_of_enums(&mut self, vector_of_enums: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , Color>>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_ENUMS, vector_of_enums); - } - - #[inline] - pub fn add_signed_enum(&mut self, signed_enum: Race) { - self.fbb_.push_slot::(Monster::VT_SIGNED_ENUM, signed_enum, Race::None); - } - - #[inline] - pub fn add_testrequirednestedflatbuffer(&mut self, testrequirednestedflatbuffer: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , u8>>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_TESTREQUIREDNESTEDFLATBUFFER, testrequirednestedflatbuffer); - } - - #[inline] - pub fn add_scalar_key_sorted_tables(&mut self, scalar_key_sorted_tables: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , ::flatbuffers::ForwardsUOffset>>>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_SCALAR_KEY_SORTED_TABLES, scalar_key_sorted_tables); - } - - #[inline] - pub fn add_native_inline(&mut self, native_inline: &Test) { - self.fbb_.push_slot_always::<&Test>(Monster::VT_NATIVE_INLINE, native_inline); - } - - #[inline] - pub fn add_long_enum_non_enum_default(&mut self, long_enum_non_enum_default: LongEnum) { - self.fbb_.push_slot::(Monster::VT_LONG_ENUM_NON_ENUM_DEFAULT, long_enum_non_enum_default, Default::default()); - } - - #[inline] - pub fn add_long_enum_normal_default(&mut self, long_enum_normal_default: LongEnum) { - self.fbb_.push_slot::(Monster::VT_LONG_ENUM_NORMAL_DEFAULT, long_enum_normal_default, LongEnum::LongOne); - } - - #[inline] - pub fn add_nan_default(&mut self, nan_default: f32) { - self.fbb_.push_slot::(Monster::VT_NAN_DEFAULT, nan_default, f32::NAN); - } - - #[inline] - pub fn add_inf_default(&mut self, inf_default: f32) { - self.fbb_.push_slot::(Monster::VT_INF_DEFAULT, inf_default, f32::INFINITY); - } - - #[inline] - pub fn add_positive_inf_default(&mut self, positive_inf_default: f32) { - self.fbb_.push_slot::(Monster::VT_POSITIVE_INF_DEFAULT, positive_inf_default, f32::INFINITY); - } - - #[inline] - pub fn add_infinity_default(&mut self, infinity_default: f32) { - self.fbb_.push_slot::(Monster::VT_INFINITY_DEFAULT, infinity_default, f32::INFINITY); - } - - #[inline] - pub fn add_positive_infinity_default(&mut self, positive_infinity_default: f32) { - self.fbb_.push_slot::(Monster::VT_POSITIVE_INFINITY_DEFAULT, positive_infinity_default, f32::INFINITY); - } - - #[inline] - pub fn add_negative_inf_default(&mut self, negative_inf_default: f32) { - self.fbb_.push_slot::(Monster::VT_NEGATIVE_INF_DEFAULT, negative_inf_default, f32::NEG_INFINITY); - } - - #[inline] - pub fn add_negative_infinity_default(&mut self, negative_infinity_default: f32) { - self.fbb_.push_slot::(Monster::VT_NEGATIVE_INFINITY_DEFAULT, negative_infinity_default, f32::NEG_INFINITY); - } - - #[inline] - pub fn add_double_inf_default(&mut self, double_inf_default: f64) { - self.fbb_.push_slot::(Monster::VT_DOUBLE_INF_DEFAULT, double_inf_default, f64::INFINITY); - } - - #[inline] - pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> MonsterBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - MonsterBuilder { - fbb_: _fbb, - start_: start, - } - } - - #[inline] - pub fn finish(self) -> ::flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - self.fbb_.required(o, Monster::VT_NAME,"name"); - ::flatbuffers::WIPOffset::new(o.value()) + #[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::(Monster::VT_MANA, mana, 150); + } + #[inline] + pub fn add_hp(&mut self, hp: i16) { + self.fbb_.push_slot::(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::(Monster::VT_COLOR, color, Color::Blue); + } + #[inline] + pub fn add_test_type(&mut self, test_type: Any) { + self.fbb_.push_slot::(Monster::VT_TEST_TYPE, test_type, Any::NONE); + } + #[inline] + pub fn add_test(&mut self, test: ::flatbuffers::WIPOffset<::flatbuffers::UnionWIPOffset>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_TEST, test); + } + #[inline] + pub fn add_test4(&mut self, test4: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , Test>>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_TEST4, test4); + } + #[inline] + pub fn add_testarrayofstring(&mut self, testarrayofstring: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , ::flatbuffers::ForwardsUOffset<&'b str>>>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_TESTARRAYOFSTRING, testarrayofstring); + } + #[inline] + pub fn add_testarrayoftables(&mut self, testarrayoftables: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , ::flatbuffers::ForwardsUOffset>>>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_TESTARRAYOFTABLES, testarrayoftables); + } + #[inline] + pub fn add_enemy(&mut self, enemy: ::flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset>(Monster::VT_ENEMY, enemy); + } + #[inline] + pub fn add_testnestedflatbuffer(&mut self, testnestedflatbuffer: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , u8>>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_TESTNESTEDFLATBUFFER, testnestedflatbuffer); + } + #[inline] + pub fn add_testempty(&mut self, testempty: ::flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset>(Monster::VT_TESTEMPTY, testempty); + } + #[inline] + pub fn add_testbool(&mut self, testbool: bool) { + self.fbb_.push_slot::(Monster::VT_TESTBOOL, testbool, false); + } + #[inline] + pub fn add_testhashs32_fnv1(&mut self, testhashs32_fnv1: i32) { + self.fbb_.push_slot::(Monster::VT_TESTHASHS32_FNV1, testhashs32_fnv1, 0); + } + #[inline] + pub fn add_testhashu32_fnv1(&mut self, testhashu32_fnv1: u32) { + self.fbb_.push_slot::(Monster::VT_TESTHASHU32_FNV1, testhashu32_fnv1, 0); + } + #[inline] + pub fn add_testhashs64_fnv1(&mut self, testhashs64_fnv1: i64) { + self.fbb_.push_slot::(Monster::VT_TESTHASHS64_FNV1, testhashs64_fnv1, 0); + } + #[inline] + pub fn add_testhashu64_fnv1(&mut self, testhashu64_fnv1: u64) { + self.fbb_.push_slot::(Monster::VT_TESTHASHU64_FNV1, testhashu64_fnv1, 0); + } + #[inline] + pub fn add_testhashs32_fnv1a(&mut self, testhashs32_fnv1a: i32) { + self.fbb_.push_slot::(Monster::VT_TESTHASHS32_FNV1A, testhashs32_fnv1a, 0); + } + #[inline] + pub fn add_testhashu32_fnv1a(&mut self, testhashu32_fnv1a: u32) { + self.fbb_.push_slot::(Monster::VT_TESTHASHU32_FNV1A, testhashu32_fnv1a, 0); + } + #[inline] + pub fn add_testhashs64_fnv1a(&mut self, testhashs64_fnv1a: i64) { + self.fbb_.push_slot::(Monster::VT_TESTHASHS64_FNV1A, testhashs64_fnv1a, 0); + } + #[inline] + pub fn add_testhashu64_fnv1a(&mut self, testhashu64_fnv1a: u64) { + self.fbb_.push_slot::(Monster::VT_TESTHASHU64_FNV1A, testhashu64_fnv1a, 0); + } + #[inline] + pub fn add_testarrayofbools(&mut self, testarrayofbools: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , bool>>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_TESTARRAYOFBOOLS, testarrayofbools); + } + #[inline] + pub fn add_testf(&mut self, testf: f32) { + self.fbb_.push_slot::(Monster::VT_TESTF, testf, 3.14159); + } + #[inline] + pub fn add_testf2(&mut self, testf2: f32) { + self.fbb_.push_slot::(Monster::VT_TESTF2, testf2, 3.0); + } + #[inline] + pub fn add_testf3(&mut self, testf3: f32) { + self.fbb_.push_slot::(Monster::VT_TESTF3, testf3, 0.0); + } + #[inline] + pub fn add_testarrayofstring2(&mut self, testarrayofstring2: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , ::flatbuffers::ForwardsUOffset<&'b str>>>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_TESTARRAYOFSTRING2, testarrayofstring2); + } + #[inline] + pub fn add_testarrayofsortedstruct(&mut self, testarrayofsortedstruct: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , Ability>>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_TESTARRAYOFSORTEDSTRUCT, testarrayofsortedstruct); + } + #[inline] + pub fn add_flex(&mut self, flex: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , u8>>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_FLEX, flex); + } + #[inline] + pub fn add_test5(&mut self, test5: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , Test>>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_TEST5, test5); + } + #[inline] + pub fn add_vector_of_longs(&mut self, vector_of_longs: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , i64>>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_LONGS, vector_of_longs); + } + #[inline] + pub fn add_vector_of_doubles(&mut self, vector_of_doubles: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , f64>>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_DOUBLES, vector_of_doubles); + } + #[inline] + pub fn add_parent_namespace_test(&mut self, parent_namespace_test: ::flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset>(Monster::VT_PARENT_NAMESPACE_TEST, parent_namespace_test); + } + #[inline] + pub fn add_vector_of_referrables(&mut self, vector_of_referrables: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , ::flatbuffers::ForwardsUOffset>>>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_REFERRABLES, vector_of_referrables); + } + #[inline] + pub fn add_single_weak_reference(&mut self, single_weak_reference: u64) { + self.fbb_.push_slot::(Monster::VT_SINGLE_WEAK_REFERENCE, single_weak_reference, 0); + } + #[inline] + pub fn add_vector_of_weak_references(&mut self, vector_of_weak_references: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , u64>>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_WEAK_REFERENCES, vector_of_weak_references); + } + #[inline] + pub fn add_vector_of_strong_referrables(&mut self, vector_of_strong_referrables: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , ::flatbuffers::ForwardsUOffset>>>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_STRONG_REFERRABLES, vector_of_strong_referrables); + } + #[inline] + pub fn add_co_owning_reference(&mut self, co_owning_reference: u64) { + self.fbb_.push_slot::(Monster::VT_CO_OWNING_REFERENCE, co_owning_reference, 0); + } + #[inline] + pub fn add_vector_of_co_owning_references(&mut self, vector_of_co_owning_references: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , u64>>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_CO_OWNING_REFERENCES, vector_of_co_owning_references); + } + #[inline] + pub fn add_non_owning_reference(&mut self, non_owning_reference: u64) { + self.fbb_.push_slot::(Monster::VT_NON_OWNING_REFERENCE, non_owning_reference, 0); + } + #[inline] + pub fn add_vector_of_non_owning_references(&mut self, vector_of_non_owning_references: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , u64>>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_NON_OWNING_REFERENCES, vector_of_non_owning_references); + } + #[inline] + pub fn add_any_unique_type(&mut self, any_unique_type: AnyUniqueAliases) { + self.fbb_.push_slot::(Monster::VT_ANY_UNIQUE_TYPE, any_unique_type, AnyUniqueAliases::NONE); + } + #[inline] + pub fn add_any_unique(&mut self, any_unique: ::flatbuffers::WIPOffset<::flatbuffers::UnionWIPOffset>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_ANY_UNIQUE, any_unique); + } + #[inline] + pub fn add_any_ambiguous_type(&mut self, any_ambiguous_type: AnyAmbiguousAliases) { + self.fbb_.push_slot::(Monster::VT_ANY_AMBIGUOUS_TYPE, any_ambiguous_type, AnyAmbiguousAliases::NONE); + } + #[inline] + pub fn add_any_ambiguous(&mut self, any_ambiguous: ::flatbuffers::WIPOffset<::flatbuffers::UnionWIPOffset>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_ANY_AMBIGUOUS, any_ambiguous); + } + #[inline] + pub fn add_vector_of_enums(&mut self, vector_of_enums: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , Color>>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_ENUMS, vector_of_enums); + } + #[inline] + pub fn add_signed_enum(&mut self, signed_enum: Race) { + self.fbb_.push_slot::(Monster::VT_SIGNED_ENUM, signed_enum, Race::None); + } + #[inline] + pub fn add_testrequirednestedflatbuffer(&mut self, testrequirednestedflatbuffer: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , u8>>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_TESTREQUIREDNESTEDFLATBUFFER, testrequirednestedflatbuffer); + } + #[inline] + pub fn add_scalar_key_sorted_tables(&mut self, scalar_key_sorted_tables: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , ::flatbuffers::ForwardsUOffset>>>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_SCALAR_KEY_SORTED_TABLES, scalar_key_sorted_tables); + } + #[inline] + pub fn add_native_inline(&mut self, native_inline: &Test) { + self.fbb_.push_slot_always::<&Test>(Monster::VT_NATIVE_INLINE, native_inline); + } + #[inline] + pub fn add_long_enum_non_enum_default(&mut self, long_enum_non_enum_default: LongEnum) { + self.fbb_.push_slot::(Monster::VT_LONG_ENUM_NON_ENUM_DEFAULT, long_enum_non_enum_default, Default::default()); + } + #[inline] + pub fn add_long_enum_normal_default(&mut self, long_enum_normal_default: LongEnum) { + self.fbb_.push_slot::(Monster::VT_LONG_ENUM_NORMAL_DEFAULT, long_enum_normal_default, LongEnum::LongOne); + } + #[inline] + pub fn add_nan_default(&mut self, nan_default: f32) { + self.fbb_.push_slot::(Monster::VT_NAN_DEFAULT, nan_default, f32::NAN); + } + #[inline] + pub fn add_inf_default(&mut self, inf_default: f32) { + self.fbb_.push_slot::(Monster::VT_INF_DEFAULT, inf_default, f32::INFINITY); + } + #[inline] + pub fn add_positive_inf_default(&mut self, positive_inf_default: f32) { + self.fbb_.push_slot::(Monster::VT_POSITIVE_INF_DEFAULT, positive_inf_default, f32::INFINITY); + } + #[inline] + pub fn add_infinity_default(&mut self, infinity_default: f32) { + self.fbb_.push_slot::(Monster::VT_INFINITY_DEFAULT, infinity_default, f32::INFINITY); + } + #[inline] + pub fn add_positive_infinity_default(&mut self, positive_infinity_default: f32) { + self.fbb_.push_slot::(Monster::VT_POSITIVE_INFINITY_DEFAULT, positive_infinity_default, f32::INFINITY); + } + #[inline] + pub fn add_negative_inf_default(&mut self, negative_inf_default: f32) { + self.fbb_.push_slot::(Monster::VT_NEGATIVE_INF_DEFAULT, negative_inf_default, f32::NEG_INFINITY); + } + #[inline] + pub fn add_negative_infinity_default(&mut self, negative_infinity_default: f32) { + self.fbb_.push_slot::(Monster::VT_NEGATIVE_INFINITY_DEFAULT, negative_infinity_default, f32::NEG_INFINITY); + } + #[inline] + pub fn add_double_inf_default(&mut self, double_inf_default: f64) { + self.fbb_.push_slot::(Monster::VT_DOUBLE_INF_DEFAULT, double_inf_default, f64::INFINITY); + } + #[inline] + pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> MonsterBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + MonsterBuilder { + fbb_: _fbb, + start_: start, } + } + #[inline] + pub fn finish(self) -> ::flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + self.fbb_.required(o, Monster::VT_NAME,"name"); + ::flatbuffers::WIPOffset::new(o.value()) + } } impl ::core::fmt::Debug for Monster<'_> { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - let mut ds = f.debug_struct("Monster"); - ds.field("pos", &self.pos()); - ds.field("mana", &self.mana()); - ds.field("hp", &self.hp()); - ds.field("name", &self.name()); - ds.field("inventory", &self.inventory()); - ds.field("color", &self.color()); - ds.field("test_type", &self.test_type()); - match self.test_type() { - Any::Monster => { - if let Some(x) = self.test_as_monster() { - ds.field("test", &x) - } else { - ds.field("test", &"InvalidFlatbuffer: Union discriminant does not match value.") - } - }, - Any::TestSimpleTableWithEnum => { - if let Some(x) = self.test_as_test_simple_table_with_enum() { - ds.field("test", &x) - } else { - ds.field("test", &"InvalidFlatbuffer: Union discriminant does not match value.") - } - }, - Any::MyGame_Example2_Monster => { - if let Some(x) = self.test_as_my_game_example_2_monster() { - ds.field("test", &x) - } else { - ds.field("test", &"InvalidFlatbuffer: Union discriminant does not match value.") - } - }, - _ => { - let x: Option<()> = None; - ds.field("test", &x) - }, - }; - ds.field("test4", &self.test4()); - ds.field("testarrayofstring", &self.testarrayofstring()); - ds.field("testarrayoftables", &self.testarrayoftables()); - ds.field("enemy", &self.enemy()); - ds.field("testnestedflatbuffer", &self.testnestedflatbuffer()); - ds.field("testempty", &self.testempty()); - ds.field("testbool", &self.testbool()); - ds.field("testhashs32_fnv1", &self.testhashs32_fnv1()); - ds.field("testhashu32_fnv1", &self.testhashu32_fnv1()); - ds.field("testhashs64_fnv1", &self.testhashs64_fnv1()); - ds.field("testhashu64_fnv1", &self.testhashu64_fnv1()); - ds.field("testhashs32_fnv1a", &self.testhashs32_fnv1a()); - ds.field("testhashu32_fnv1a", &self.testhashu32_fnv1a()); - ds.field("testhashs64_fnv1a", &self.testhashs64_fnv1a()); - ds.field("testhashu64_fnv1a", &self.testhashu64_fnv1a()); - ds.field("testarrayofbools", &self.testarrayofbools()); - ds.field("testf", &self.testf()); - ds.field("testf2", &self.testf2()); - ds.field("testf3", &self.testf3()); - ds.field("testarrayofstring2", &self.testarrayofstring2()); - ds.field("testarrayofsortedstruct", &self.testarrayofsortedstruct()); - ds.field("flex", &self.flex()); - ds.field("test5", &self.test5()); - ds.field("vector_of_longs", &self.vector_of_longs()); - ds.field("vector_of_doubles", &self.vector_of_doubles()); - ds.field("parent_namespace_test", &self.parent_namespace_test()); - ds.field("vector_of_referrables", &self.vector_of_referrables()); - ds.field("single_weak_reference", &self.single_weak_reference()); - ds.field("vector_of_weak_references", &self.vector_of_weak_references()); - ds.field("vector_of_strong_referrables", &self.vector_of_strong_referrables()); - ds.field("co_owning_reference", &self.co_owning_reference()); - ds.field("vector_of_co_owning_references", &self.vector_of_co_owning_references()); - ds.field("non_owning_reference", &self.non_owning_reference()); - ds.field("vector_of_non_owning_references", &self.vector_of_non_owning_references()); - ds.field("any_unique_type", &self.any_unique_type()); - match self.any_unique_type() { - AnyUniqueAliases::M => { - if let Some(x) = self.any_unique_as_m() { - ds.field("any_unique", &x) - } else { - ds.field("any_unique", &"InvalidFlatbuffer: Union discriminant does not match value.") - } - }, - AnyUniqueAliases::TS => { - if let Some(x) = self.any_unique_as_ts() { - ds.field("any_unique", &x) - } else { - ds.field("any_unique", &"InvalidFlatbuffer: Union discriminant does not match value.") - } - }, - AnyUniqueAliases::M2 => { - if let Some(x) = self.any_unique_as_m2() { - ds.field("any_unique", &x) - } else { - ds.field("any_unique", &"InvalidFlatbuffer: Union discriminant does not match value.") - } - }, - _ => { - let x: Option<()> = None; - ds.field("any_unique", &x) - }, - }; - ds.field("any_ambiguous_type", &self.any_ambiguous_type()); - match self.any_ambiguous_type() { - AnyAmbiguousAliases::M1 => { - if let Some(x) = self.any_ambiguous_as_m1() { - ds.field("any_ambiguous", &x) - } else { - ds.field("any_ambiguous", &"InvalidFlatbuffer: Union discriminant does not match value.") - } - }, - AnyAmbiguousAliases::M2 => { - if let Some(x) = self.any_ambiguous_as_m2() { - ds.field("any_ambiguous", &x) - } else { - ds.field("any_ambiguous", &"InvalidFlatbuffer: Union discriminant does not match value.") - } - }, - AnyAmbiguousAliases::M3 => { - if let Some(x) = self.any_ambiguous_as_m3() { - ds.field("any_ambiguous", &x) - } else { - ds.field("any_ambiguous", &"InvalidFlatbuffer: Union discriminant does not match value.") - } - }, - _ => { - let x: Option<()> = None; - ds.field("any_ambiguous", &x) - }, - }; - ds.field("vector_of_enums", &self.vector_of_enums()); - ds.field("signed_enum", &self.signed_enum()); - ds.field("testrequirednestedflatbuffer", &self.testrequirednestedflatbuffer()); - ds.field("scalar_key_sorted_tables", &self.scalar_key_sorted_tables()); - ds.field("native_inline", &self.native_inline()); - ds.field("long_enum_non_enum_default", &self.long_enum_non_enum_default()); - ds.field("long_enum_normal_default", &self.long_enum_normal_default()); - ds.field("nan_default", &self.nan_default()); - ds.field("inf_default", &self.inf_default()); - ds.field("positive_inf_default", &self.positive_inf_default()); - ds.field("infinity_default", &self.infinity_default()); - ds.field("positive_infinity_default", &self.positive_infinity_default()); - ds.field("negative_inf_default", &self.negative_inf_default()); - ds.field("negative_infinity_default", &self.negative_infinity_default()); - ds.field("double_inf_default", &self.double_inf_default()); - ds.finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + let mut ds = f.debug_struct("Monster"); + ds.field("pos", &self.pos()); + ds.field("mana", &self.mana()); + ds.field("hp", &self.hp()); + ds.field("name", &self.name()); + ds.field("inventory", &self.inventory()); + ds.field("color", &self.color()); + ds.field("test_type", &self.test_type()); + match self.test_type() { + Any::Monster => { + if let Some(x) = self.test_as_monster() { + ds.field("test", &x) + } else { + ds.field("test", &"InvalidFlatbuffer: Union discriminant does not match value.") + } + }, + Any::TestSimpleTableWithEnum => { + if let Some(x) = self.test_as_test_simple_table_with_enum() { + ds.field("test", &x) + } else { + ds.field("test", &"InvalidFlatbuffer: Union discriminant does not match value.") + } + }, + Any::MyGame_Example2_Monster => { + if let Some(x) = self.test_as_my_game_example_2_monster() { + ds.field("test", &x) + } else { + ds.field("test", &"InvalidFlatbuffer: Union discriminant does not match value.") + } + }, + _ => { + let x: Option<()> = None; + ds.field("test", &x) + }, + }; + ds.field("test4", &self.test4()); + ds.field("testarrayofstring", &self.testarrayofstring()); + ds.field("testarrayoftables", &self.testarrayoftables()); + ds.field("enemy", &self.enemy()); + ds.field("testnestedflatbuffer", &self.testnestedflatbuffer()); + ds.field("testempty", &self.testempty()); + ds.field("testbool", &self.testbool()); + ds.field("testhashs32_fnv1", &self.testhashs32_fnv1()); + ds.field("testhashu32_fnv1", &self.testhashu32_fnv1()); + ds.field("testhashs64_fnv1", &self.testhashs64_fnv1()); + ds.field("testhashu64_fnv1", &self.testhashu64_fnv1()); + ds.field("testhashs32_fnv1a", &self.testhashs32_fnv1a()); + ds.field("testhashu32_fnv1a", &self.testhashu32_fnv1a()); + ds.field("testhashs64_fnv1a", &self.testhashs64_fnv1a()); + ds.field("testhashu64_fnv1a", &self.testhashu64_fnv1a()); + ds.field("testarrayofbools", &self.testarrayofbools()); + ds.field("testf", &self.testf()); + ds.field("testf2", &self.testf2()); + ds.field("testf3", &self.testf3()); + ds.field("testarrayofstring2", &self.testarrayofstring2()); + ds.field("testarrayofsortedstruct", &self.testarrayofsortedstruct()); + ds.field("flex", &self.flex()); + ds.field("test5", &self.test5()); + ds.field("vector_of_longs", &self.vector_of_longs()); + ds.field("vector_of_doubles", &self.vector_of_doubles()); + ds.field("parent_namespace_test", &self.parent_namespace_test()); + ds.field("vector_of_referrables", &self.vector_of_referrables()); + ds.field("single_weak_reference", &self.single_weak_reference()); + ds.field("vector_of_weak_references", &self.vector_of_weak_references()); + ds.field("vector_of_strong_referrables", &self.vector_of_strong_referrables()); + ds.field("co_owning_reference", &self.co_owning_reference()); + ds.field("vector_of_co_owning_references", &self.vector_of_co_owning_references()); + ds.field("non_owning_reference", &self.non_owning_reference()); + ds.field("vector_of_non_owning_references", &self.vector_of_non_owning_references()); + ds.field("any_unique_type", &self.any_unique_type()); + match self.any_unique_type() { + AnyUniqueAliases::M => { + if let Some(x) = self.any_unique_as_m() { + ds.field("any_unique", &x) + } else { + ds.field("any_unique", &"InvalidFlatbuffer: Union discriminant does not match value.") + } + }, + AnyUniqueAliases::TS => { + if let Some(x) = self.any_unique_as_ts() { + ds.field("any_unique", &x) + } else { + ds.field("any_unique", &"InvalidFlatbuffer: Union discriminant does not match value.") + } + }, + AnyUniqueAliases::M2 => { + if let Some(x) = self.any_unique_as_m2() { + ds.field("any_unique", &x) + } else { + ds.field("any_unique", &"InvalidFlatbuffer: Union discriminant does not match value.") + } + }, + _ => { + let x: Option<()> = None; + ds.field("any_unique", &x) + }, + }; + ds.field("any_ambiguous_type", &self.any_ambiguous_type()); + match self.any_ambiguous_type() { + AnyAmbiguousAliases::M1 => { + if let Some(x) = self.any_ambiguous_as_m1() { + ds.field("any_ambiguous", &x) + } else { + ds.field("any_ambiguous", &"InvalidFlatbuffer: Union discriminant does not match value.") + } + }, + AnyAmbiguousAliases::M2 => { + if let Some(x) = self.any_ambiguous_as_m2() { + ds.field("any_ambiguous", &x) + } else { + ds.field("any_ambiguous", &"InvalidFlatbuffer: Union discriminant does not match value.") + } + }, + AnyAmbiguousAliases::M3 => { + if let Some(x) = self.any_ambiguous_as_m3() { + ds.field("any_ambiguous", &x) + } else { + ds.field("any_ambiguous", &"InvalidFlatbuffer: Union discriminant does not match value.") + } + }, + _ => { + let x: Option<()> = None; + ds.field("any_ambiguous", &x) + }, + }; + ds.field("vector_of_enums", &self.vector_of_enums()); + ds.field("signed_enum", &self.signed_enum()); + ds.field("testrequirednestedflatbuffer", &self.testrequirednestedflatbuffer()); + ds.field("scalar_key_sorted_tables", &self.scalar_key_sorted_tables()); + ds.field("native_inline", &self.native_inline()); + ds.field("long_enum_non_enum_default", &self.long_enum_non_enum_default()); + ds.field("long_enum_normal_default", &self.long_enum_normal_default()); + ds.field("nan_default", &self.nan_default()); + ds.field("inf_default", &self.inf_default()); + ds.field("positive_inf_default", &self.positive_inf_default()); + ds.field("infinity_default", &self.infinity_default()); + ds.field("positive_infinity_default", &self.positive_infinity_default()); + ds.field("negative_inf_default", &self.negative_inf_default()); + ds.field("negative_infinity_default", &self.negative_infinity_default()); + ds.field("double_inf_default", &self.double_inf_default()); + ds.finish() + } } - #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub struct MonsterT { - pub pos: Option, - pub mana: i16, - pub hp: i16, - pub name: alloc::string::String, - pub inventory: Option>, - pub color: Color, - pub test: AnyT, - pub test4: Option>, - pub testarrayofstring: Option>, - pub testarrayoftables: Option>, - pub enemy: Option>, - pub testnestedflatbuffer: Option>, - pub testempty: Option>, - pub testbool: bool, - pub testhashs32_fnv1: i32, - pub testhashu32_fnv1: u32, - pub testhashs64_fnv1: i64, - pub testhashu64_fnv1: u64, - pub testhashs32_fnv1a: i32, - pub testhashu32_fnv1a: u32, - pub testhashs64_fnv1a: i64, - pub testhashu64_fnv1a: u64, - pub testarrayofbools: Option>, - pub testf: f32, - pub testf2: f32, - pub testf3: f32, - pub testarrayofstring2: Option>, - pub testarrayofsortedstruct: Option>, - pub flex: Option>, - pub test5: Option>, - pub vector_of_longs: Option>, - pub vector_of_doubles: Option>, - pub parent_namespace_test: Option>, - pub vector_of_referrables: Option>, - pub single_weak_reference: u64, - pub vector_of_weak_references: Option>, - pub vector_of_strong_referrables: Option>, - pub co_owning_reference: u64, - pub vector_of_co_owning_references: Option>, - pub non_owning_reference: u64, - pub vector_of_non_owning_references: Option>, - pub any_unique: AnyUniqueAliasesT, - pub any_ambiguous: AnyAmbiguousAliasesT, - pub vector_of_enums: Option>, - pub signed_enum: Race, - pub testrequirednestedflatbuffer: Option>, - pub scalar_key_sorted_tables: Option>, - pub native_inline: Option, - pub long_enum_non_enum_default: LongEnum, - pub long_enum_normal_default: LongEnum, - pub nan_default: f32, - pub inf_default: f32, - pub positive_inf_default: f32, - pub infinity_default: f32, - pub positive_infinity_default: f32, - pub negative_inf_default: f32, - pub negative_infinity_default: f32, - pub double_inf_default: f64, + pub pos: Option, + pub mana: i16, + pub hp: i16, + pub name: alloc::string::String, + pub inventory: Option>, + pub color: Color, + pub test: AnyT, + pub test4: Option>, + pub testarrayofstring: Option>, + pub testarrayoftables: Option>, + pub enemy: Option>, + pub testnestedflatbuffer: Option>, + pub testempty: Option>, + pub testbool: bool, + pub testhashs32_fnv1: i32, + pub testhashu32_fnv1: u32, + pub testhashs64_fnv1: i64, + pub testhashu64_fnv1: u64, + pub testhashs32_fnv1a: i32, + pub testhashu32_fnv1a: u32, + pub testhashs64_fnv1a: i64, + pub testhashu64_fnv1a: u64, + pub testarrayofbools: Option>, + pub testf: f32, + pub testf2: f32, + pub testf3: f32, + pub testarrayofstring2: Option>, + pub testarrayofsortedstruct: Option>, + pub flex: Option>, + pub test5: Option>, + pub vector_of_longs: Option>, + pub vector_of_doubles: Option>, + pub parent_namespace_test: Option>, + pub vector_of_referrables: Option>, + pub single_weak_reference: u64, + pub vector_of_weak_references: Option>, + pub vector_of_strong_referrables: Option>, + pub co_owning_reference: u64, + pub vector_of_co_owning_references: Option>, + pub non_owning_reference: u64, + pub vector_of_non_owning_references: Option>, + pub any_unique: AnyUniqueAliasesT, + pub any_ambiguous: AnyAmbiguousAliasesT, + pub vector_of_enums: Option>, + pub signed_enum: Race, + pub testrequirednestedflatbuffer: Option>, + pub scalar_key_sorted_tables: Option>, + pub native_inline: Option, + pub long_enum_non_enum_default: LongEnum, + pub long_enum_normal_default: LongEnum, + pub nan_default: f32, + pub inf_default: f32, + pub positive_inf_default: f32, + pub infinity_default: f32, + pub positive_infinity_default: f32, + pub negative_inf_default: f32, + pub negative_infinity_default: f32, + pub double_inf_default: f64, } - impl Default for MonsterT { - fn default() -> Self { - Self { - pos: None, - mana: 150, - hp: 100, - name: alloc::string::ToString::to_string(""), - inventory: None, - color: Color::Blue, - test: AnyT::NONE, - test4: None, - testarrayofstring: None, - testarrayoftables: None, - enemy: None, - testnestedflatbuffer: None, - testempty: None, - testbool: false, - testhashs32_fnv1: 0, - testhashu32_fnv1: 0, - testhashs64_fnv1: 0, - testhashu64_fnv1: 0, - testhashs32_fnv1a: 0, - testhashu32_fnv1a: 0, - testhashs64_fnv1a: 0, - testhashu64_fnv1a: 0, - testarrayofbools: None, - testf: 3.14159, - testf2: 3.0, - testf3: 0.0, - testarrayofstring2: None, - testarrayofsortedstruct: None, - flex: None, - test5: None, - vector_of_longs: None, - vector_of_doubles: None, - parent_namespace_test: None, - vector_of_referrables: None, - single_weak_reference: 0, - vector_of_weak_references: None, - vector_of_strong_referrables: None, - co_owning_reference: 0, - vector_of_co_owning_references: None, - non_owning_reference: 0, - vector_of_non_owning_references: None, - any_unique: AnyUniqueAliasesT::NONE, - any_ambiguous: AnyAmbiguousAliasesT::NONE, - vector_of_enums: None, - signed_enum: Race::None, - testrequirednestedflatbuffer: None, - scalar_key_sorted_tables: None, - native_inline: None, - long_enum_non_enum_default: Default::default(), - long_enum_normal_default: LongEnum::LongOne, - nan_default: f32::NAN, - inf_default: f32::INFINITY, - positive_inf_default: f32::INFINITY, - infinity_default: f32::INFINITY, - positive_infinity_default: f32::INFINITY, - negative_inf_default: f32::NEG_INFINITY, - negative_infinity_default: f32::NEG_INFINITY, - double_inf_default: f64::INFINITY, - } + fn default() -> Self { + Self { + pos: None, + mana: 150, + hp: 100, + name: alloc::string::ToString::to_string(""), + inventory: None, + color: Color::Blue, + test: AnyT::NONE, + test4: None, + testarrayofstring: None, + testarrayoftables: None, + enemy: None, + testnestedflatbuffer: None, + testempty: None, + testbool: false, + testhashs32_fnv1: 0, + testhashu32_fnv1: 0, + testhashs64_fnv1: 0, + testhashu64_fnv1: 0, + testhashs32_fnv1a: 0, + testhashu32_fnv1a: 0, + testhashs64_fnv1a: 0, + testhashu64_fnv1a: 0, + testarrayofbools: None, + testf: 3.14159, + testf2: 3.0, + testf3: 0.0, + testarrayofstring2: None, + testarrayofsortedstruct: None, + flex: None, + test5: None, + vector_of_longs: None, + vector_of_doubles: None, + parent_namespace_test: None, + vector_of_referrables: None, + single_weak_reference: 0, + vector_of_weak_references: None, + vector_of_strong_referrables: None, + co_owning_reference: 0, + vector_of_co_owning_references: None, + non_owning_reference: 0, + vector_of_non_owning_references: None, + any_unique: AnyUniqueAliasesT::NONE, + any_ambiguous: AnyAmbiguousAliasesT::NONE, + vector_of_enums: None, + signed_enum: Race::None, + testrequirednestedflatbuffer: None, + scalar_key_sorted_tables: None, + native_inline: None, + long_enum_non_enum_default: Default::default(), + long_enum_normal_default: LongEnum::LongOne, + nan_default: f32::NAN, + inf_default: f32::INFINITY, + positive_inf_default: f32::INFINITY, + infinity_default: f32::INFINITY, + positive_infinity_default: f32::INFINITY, + negative_inf_default: f32::NEG_INFINITY, + negative_infinity_default: f32::NEG_INFINITY, + double_inf_default: f64::INFINITY, } + } } - impl MonsterT { - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( - &self, - _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> - ) -> ::flatbuffers::WIPOffset> { - let pos_tmp = self.pos.as_ref().map(|x| x.pack()); - let pos = pos_tmp.as_ref(); - let mana = self.mana; - let hp = self.hp; - let name = Some({ - let x = &self.name; - _fbb.create_string(x) - }); - let inventory = self.inventory.as_ref().map(|x|{ - _fbb.create_vector(x) - }); - let color = self.color; - let test_type = self.test.any_type(); - let test = self.test.pack(_fbb); - let test4 = self.test4.as_ref().map(|x|{ - let w: alloc::vec::Vec<_> = x.iter().map(|t| t.pack()).collect();_fbb.create_vector(&w) - }); - let testarrayofstring = self.testarrayofstring.as_ref().map(|x|{ - let w: alloc::vec::Vec<_> = x.iter().map(|s| _fbb.create_string(s)).collect();_fbb.create_vector(&w) - }); - let testarrayoftables = self.testarrayoftables.as_ref().map(|x|{ - let w: alloc::vec::Vec<_> = x.iter().map(|t| t.pack(_fbb)).collect();_fbb.create_vector(&w) - }); - let enemy = self.enemy.as_ref().map(|x|{ - x.pack(_fbb) - }); - let testnestedflatbuffer = self.testnestedflatbuffer.as_ref().map(|x|{ - _fbb.create_vector(x) - }); - let testempty = self.testempty.as_ref().map(|x|{ - x.pack(_fbb) - }); - let testbool = self.testbool; - let testhashs32_fnv1 = self.testhashs32_fnv1; - let testhashu32_fnv1 = self.testhashu32_fnv1; - let testhashs64_fnv1 = self.testhashs64_fnv1; - let testhashu64_fnv1 = self.testhashu64_fnv1; - let testhashs32_fnv1a = self.testhashs32_fnv1a; - let testhashu32_fnv1a = self.testhashu32_fnv1a; - let testhashs64_fnv1a = self.testhashs64_fnv1a; - let testhashu64_fnv1a = self.testhashu64_fnv1a; - let testarrayofbools = self.testarrayofbools.as_ref().map(|x|{ - _fbb.create_vector(x) - }); - let testf = self.testf; - let testf2 = self.testf2; - let testf3 = self.testf3; - let testarrayofstring2 = self.testarrayofstring2.as_ref().map(|x|{ - let w: alloc::vec::Vec<_> = x.iter().map(|s| _fbb.create_string(s)).collect();_fbb.create_vector(&w) - }); - let testarrayofsortedstruct = self.testarrayofsortedstruct.as_ref().map(|x|{ - let w: alloc::vec::Vec<_> = x.iter().map(|t| t.pack()).collect();_fbb.create_vector(&w) - }); - let flex = self.flex.as_ref().map(|x|{ - _fbb.create_vector(x) - }); - let test5 = self.test5.as_ref().map(|x|{ - let w: alloc::vec::Vec<_> = x.iter().map(|t| t.pack()).collect();_fbb.create_vector(&w) - }); - let vector_of_longs = self.vector_of_longs.as_ref().map(|x|{ - _fbb.create_vector(x) - }); - let vector_of_doubles = self.vector_of_doubles.as_ref().map(|x|{ - _fbb.create_vector(x) - }); - let parent_namespace_test = self.parent_namespace_test.as_ref().map(|x|{ - x.pack(_fbb) - }); - let vector_of_referrables = self.vector_of_referrables.as_ref().map(|x|{ - let w: alloc::vec::Vec<_> = x.iter().map(|t| t.pack(_fbb)).collect();_fbb.create_vector(&w) - }); - let single_weak_reference = self.single_weak_reference; - let vector_of_weak_references = self.vector_of_weak_references.as_ref().map(|x|{ - _fbb.create_vector(x) - }); - let vector_of_strong_referrables = self.vector_of_strong_referrables.as_ref().map(|x|{ - let w: alloc::vec::Vec<_> = x.iter().map(|t| t.pack(_fbb)).collect();_fbb.create_vector(&w) - }); - let co_owning_reference = self.co_owning_reference; - let vector_of_co_owning_references = self.vector_of_co_owning_references.as_ref().map(|x|{ - _fbb.create_vector(x) - }); - let non_owning_reference = self.non_owning_reference; - let vector_of_non_owning_references = self.vector_of_non_owning_references.as_ref().map(|x|{ - _fbb.create_vector(x) - }); - let any_unique_type = self.any_unique.any_unique_aliases_type(); - let any_unique = self.any_unique.pack(_fbb); - let any_ambiguous_type = self.any_ambiguous.any_ambiguous_aliases_type(); - let any_ambiguous = self.any_ambiguous.pack(_fbb); - let vector_of_enums = self.vector_of_enums.as_ref().map(|x|{ - _fbb.create_vector(x) - }); - let signed_enum = self.signed_enum; - let testrequirednestedflatbuffer = self.testrequirednestedflatbuffer.as_ref().map(|x|{ - _fbb.create_vector(x) - }); - let scalar_key_sorted_tables = self.scalar_key_sorted_tables.as_ref().map(|x|{ - let w: alloc::vec::Vec<_> = x.iter().map(|t| t.pack(_fbb)).collect();_fbb.create_vector(&w) - }); - let native_inline_tmp = self.native_inline.as_ref().map(|x| x.pack()); - let native_inline = native_inline_tmp.as_ref(); - let long_enum_non_enum_default = self.long_enum_non_enum_default; - let long_enum_normal_default = self.long_enum_normal_default; - let nan_default = self.nan_default; - let inf_default = self.inf_default; - let positive_inf_default = self.positive_inf_default; - let infinity_default = self.infinity_default; - let positive_infinity_default = self.positive_infinity_default; - let negative_inf_default = self.negative_inf_default; - let negative_infinity_default = self.negative_infinity_default; - let double_inf_default = self.double_inf_default; - Monster::create(_fbb, &MonsterArgs{ - pos, - mana, - hp, - name, - inventory, - color, - test_type, - test, - test4, - testarrayofstring, - testarrayoftables, - enemy, - testnestedflatbuffer, - testempty, - testbool, - testhashs32_fnv1, - testhashu32_fnv1, - testhashs64_fnv1, - testhashu64_fnv1, - testhashs32_fnv1a, - testhashu32_fnv1a, - testhashs64_fnv1a, - testhashu64_fnv1a, - testarrayofbools, - testf, - testf2, - testf3, - testarrayofstring2, - testarrayofsortedstruct, - flex, - test5, - vector_of_longs, - vector_of_doubles, - parent_namespace_test, - vector_of_referrables, - single_weak_reference, - vector_of_weak_references, - vector_of_strong_referrables, - co_owning_reference, - vector_of_co_owning_references, - non_owning_reference, - vector_of_non_owning_references, - any_unique_type, - any_unique, - any_ambiguous_type, - any_ambiguous, - vector_of_enums, - signed_enum, - testrequirednestedflatbuffer, - scalar_key_sorted_tables, - native_inline, - long_enum_non_enum_default, - long_enum_normal_default, - nan_default, - inf_default, - positive_inf_default, - infinity_default, - positive_infinity_default, - negative_inf_default, - negative_infinity_default, - double_inf_default, - }) - } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> + ) -> ::flatbuffers::WIPOffset> { + let pos_tmp = self.pos.as_ref().map(|x| x.pack()); + let pos = pos_tmp.as_ref(); + let mana = self.mana; + let hp = self.hp; + let name = Some({ + let x = &self.name; + _fbb.create_string(x) + }); + let inventory = self.inventory.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + let color = self.color; + let test_type = self.test.any_type(); + let test = self.test.pack(_fbb); + let test4 = self.test4.as_ref().map(|x|{ + let w: alloc::vec::Vec<_> = x.iter().map(|t| t.pack()).collect();_fbb.create_vector(&w) + }); + let testarrayofstring = self.testarrayofstring.as_ref().map(|x|{ + let w: alloc::vec::Vec<_> = x.iter().map(|s| _fbb.create_string(s)).collect();_fbb.create_vector(&w) + }); + let testarrayoftables = self.testarrayoftables.as_ref().map(|x|{ + let w: alloc::vec::Vec<_> = x.iter().map(|t| t.pack(_fbb)).collect();_fbb.create_vector(&w) + }); + let enemy = self.enemy.as_ref().map(|x|{ + x.pack(_fbb) + }); + let testnestedflatbuffer = self.testnestedflatbuffer.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + let testempty = self.testempty.as_ref().map(|x|{ + x.pack(_fbb) + }); + let testbool = self.testbool; + let testhashs32_fnv1 = self.testhashs32_fnv1; + let testhashu32_fnv1 = self.testhashu32_fnv1; + let testhashs64_fnv1 = self.testhashs64_fnv1; + let testhashu64_fnv1 = self.testhashu64_fnv1; + let testhashs32_fnv1a = self.testhashs32_fnv1a; + let testhashu32_fnv1a = self.testhashu32_fnv1a; + let testhashs64_fnv1a = self.testhashs64_fnv1a; + let testhashu64_fnv1a = self.testhashu64_fnv1a; + let testarrayofbools = self.testarrayofbools.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + let testf = self.testf; + let testf2 = self.testf2; + let testf3 = self.testf3; + let testarrayofstring2 = self.testarrayofstring2.as_ref().map(|x|{ + let w: alloc::vec::Vec<_> = x.iter().map(|s| _fbb.create_string(s)).collect();_fbb.create_vector(&w) + }); + let testarrayofsortedstruct = self.testarrayofsortedstruct.as_ref().map(|x|{ + let w: alloc::vec::Vec<_> = x.iter().map(|t| t.pack()).collect();_fbb.create_vector(&w) + }); + let flex = self.flex.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + let test5 = self.test5.as_ref().map(|x|{ + let w: alloc::vec::Vec<_> = x.iter().map(|t| t.pack()).collect();_fbb.create_vector(&w) + }); + let vector_of_longs = self.vector_of_longs.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + let vector_of_doubles = self.vector_of_doubles.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + let parent_namespace_test = self.parent_namespace_test.as_ref().map(|x|{ + x.pack(_fbb) + }); + let vector_of_referrables = self.vector_of_referrables.as_ref().map(|x|{ + let w: alloc::vec::Vec<_> = x.iter().map(|t| t.pack(_fbb)).collect();_fbb.create_vector(&w) + }); + let single_weak_reference = self.single_weak_reference; + let vector_of_weak_references = self.vector_of_weak_references.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + let vector_of_strong_referrables = self.vector_of_strong_referrables.as_ref().map(|x|{ + let w: alloc::vec::Vec<_> = x.iter().map(|t| t.pack(_fbb)).collect();_fbb.create_vector(&w) + }); + let co_owning_reference = self.co_owning_reference; + let vector_of_co_owning_references = self.vector_of_co_owning_references.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + let non_owning_reference = self.non_owning_reference; + let vector_of_non_owning_references = self.vector_of_non_owning_references.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + let any_unique_type = self.any_unique.any_unique_aliases_type(); + let any_unique = self.any_unique.pack(_fbb); + let any_ambiguous_type = self.any_ambiguous.any_ambiguous_aliases_type(); + let any_ambiguous = self.any_ambiguous.pack(_fbb); + let vector_of_enums = self.vector_of_enums.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + let signed_enum = self.signed_enum; + let testrequirednestedflatbuffer = self.testrequirednestedflatbuffer.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + let scalar_key_sorted_tables = self.scalar_key_sorted_tables.as_ref().map(|x|{ + let w: alloc::vec::Vec<_> = x.iter().map(|t| t.pack(_fbb)).collect();_fbb.create_vector(&w) + }); + let native_inline_tmp = self.native_inline.as_ref().map(|x| x.pack()); + let native_inline = native_inline_tmp.as_ref(); + let long_enum_non_enum_default = self.long_enum_non_enum_default; + let long_enum_normal_default = self.long_enum_normal_default; + let nan_default = self.nan_default; + let inf_default = self.inf_default; + let positive_inf_default = self.positive_inf_default; + let infinity_default = self.infinity_default; + let positive_infinity_default = self.positive_infinity_default; + let negative_inf_default = self.negative_inf_default; + let negative_infinity_default = self.negative_infinity_default; + let double_inf_default = self.double_inf_default; + Monster::create(_fbb, &MonsterArgs{ + pos, + mana, + hp, + name, + inventory, + color, + test_type, + test, + test4, + testarrayofstring, + testarrayoftables, + enemy, + testnestedflatbuffer, + testempty, + testbool, + testhashs32_fnv1, + testhashu32_fnv1, + testhashs64_fnv1, + testhashu64_fnv1, + testhashs32_fnv1a, + testhashu32_fnv1a, + testhashs64_fnv1a, + testhashu64_fnv1a, + testarrayofbools, + testf, + testf2, + testf3, + testarrayofstring2, + testarrayofsortedstruct, + flex, + test5, + vector_of_longs, + vector_of_doubles, + parent_namespace_test, + vector_of_referrables, + single_weak_reference, + vector_of_weak_references, + vector_of_strong_referrables, + co_owning_reference, + vector_of_co_owning_references, + non_owning_reference, + vector_of_non_owning_references, + any_unique_type, + any_unique, + any_ambiguous_type, + any_ambiguous, + vector_of_enums, + signed_enum, + testrequirednestedflatbuffer, + scalar_key_sorted_tables, + native_inline, + long_enum_non_enum_default, + long_enum_normal_default, + nan_default, + inf_default, + positive_inf_default, + infinity_default, + positive_infinity_default, + negative_inf_default, + negative_infinity_default, + double_inf_default, + }) + } } - +#[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`. -#[inline] pub fn root_as_monster(buf: &[u8]) -> Result, ::flatbuffers::InvalidFlatbuffer> { - ::flatbuffers::root::(buf) + ::flatbuffers::root::(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`. -#[inline] pub fn size_prefixed_root_as_monster(buf: &[u8]) -> Result, ::flatbuffers::InvalidFlatbuffer> { - ::flatbuffers::size_prefixed_root::(buf) + ::flatbuffers::size_prefixed_root::(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`. -#[inline] pub fn root_as_monster_with_opts<'b, 'o>( - opts: &'o ::flatbuffers::VerifierOptions, - buf: &'b [u8], + opts: &'o ::flatbuffers::VerifierOptions, + buf: &'b [u8], ) -> Result, ::flatbuffers::InvalidFlatbuffer> { - ::flatbuffers::root_with_opts::>(opts, buf) + ::flatbuffers::root_with_opts::>(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`. -#[inline] pub fn size_prefixed_root_as_monster_with_opts<'b, 'o>( - opts: &'o ::flatbuffers::VerifierOptions, - buf: &'b [u8], + opts: &'o ::flatbuffers::VerifierOptions, + buf: &'b [u8], ) -> Result, ::flatbuffers::InvalidFlatbuffer> { - ::flatbuffers::size_prefixed_root_with_opts::>(opts, buf) + ::flatbuffers::size_prefixed_root_with_opts::>(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`. -#[inline] pub unsafe fn root_as_monster_unchecked(buf: &[u8]) -> Monster<'_> { - unsafe { ::flatbuffers::root_unchecked::(buf) } + unsafe { ::flatbuffers::root_unchecked::(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`. -#[inline] pub unsafe fn size_prefixed_root_as_monster_unchecked(buf: &[u8]) -> Monster<'_> { - unsafe { ::flatbuffers::size_prefixed_root_unchecked::(buf) } + unsafe { ::flatbuffers::size_prefixed_root_unchecked::(buf) } } - pub const MONSTER_IDENTIFIER: &str = "MONS"; #[inline] pub fn monster_buffer_has_identifier(buf: &[u8]) -> bool { - ::flatbuffers::buffer_has_identifier(buf, MONSTER_IDENTIFIER, false) + ::flatbuffers::buffer_has_identifier(buf, MONSTER_IDENTIFIER, false) } #[inline] pub fn monster_size_prefixed_buffer_has_identifier(buf: &[u8]) -> bool { - ::flatbuffers::buffer_has_identifier(buf, MONSTER_IDENTIFIER, true) + ::flatbuffers::buffer_has_identifier(buf, MONSTER_IDENTIFIER, true) } pub const MONSTER_EXTENSION: &str = "mon"; @@ -2138,15 +1997,11 @@ pub const MONSTER_EXTENSION: &str = "mon"; #[inline] pub fn finish_monster_buffer<'a, 'b, A: ::flatbuffers::Allocator + 'a>( fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - root: ::flatbuffers::WIPOffset> -) { - fbb.finish(root, Some(MONSTER_IDENTIFIER)); + root: ::flatbuffers::WIPOffset>) { + fbb.finish(root, Some(MONSTER_IDENTIFIER)); } #[inline] -pub fn finish_size_prefixed_monster_buffer<'a, 'b, A: ::flatbuffers::Allocator + 'a>( - fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - root: ::flatbuffers::WIPOffset> -) { - fbb.finish_size_prefixed(root, Some(MONSTER_IDENTIFIER)); +pub fn finish_size_prefixed_monster_buffer<'a, 'b, A: ::flatbuffers::Allocator + 'a>(fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, root: ::flatbuffers::WIPOffset>) { + fbb.finish_size_prefixed(root, Some(MONSTER_IDENTIFIER)); } diff --git a/tests/monster_test/my_game/example/race_generated.rs b/tests/monster_test/my_game/example/race_generated.rs index 18516548e..095647f31 100644 --- a/tests/monster_test/my_game/example/race_generated.rs +++ b/tests/monster_test/my_game/example/race_generated.rs @@ -2,77 +2,68 @@ // @generated extern crate alloc; use super::*; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] pub const ENUM_MIN_RACE: i8 = -1; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] pub const ENUM_MAX_RACE: i8 = 2; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] #[allow(non_camel_case_types)] pub const ENUM_VALUES_RACE: [Race; 4] = [ - Race::None, - Race::Human, - Race::Dwarf, - Race::Elf, + Race::None, + Race::Human, + Race::Dwarf, + Race::Elf, ]; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] #[repr(transparent)] pub struct Race(pub i8); - #[allow(non_upper_case_globals)] impl Race { - pub const None: Self = Self(-1); - pub const Human: Self = Self(0); - pub const Dwarf: Self = Self(1); - pub const Elf: Self = Self(2); + pub const None: Self = Self(-1); + pub const Human: Self = Self(0); + pub const Dwarf: Self = Self(1); + pub const Elf: Self = Self(2); - pub const ENUM_MIN: i8 = -1; - pub const ENUM_MAX: i8 = 2; - pub const ENUM_VALUES: &'static [Self] = &[ - Self::None, - Self::Human, - Self::Dwarf, - Self::Elf, - ]; - - /// Returns the variant's name or "" if unknown. - pub fn variant_name(self) -> Option<&'static str> { - match self { - Self::None => Some("None"), - Self::Human => Some("Human"), - Self::Dwarf => Some("Dwarf"), - Self::Elf => Some("Elf"), - _ => None, - } + pub const ENUM_MIN: i8 = -1; + pub const ENUM_MAX: i8 = 2; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::None, + Self::Human, + Self::Dwarf, + Self::Elf, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::None => Some("None"), + Self::Human => Some("Human"), + Self::Dwarf => Some("Dwarf"), + Self::Elf => Some("Elf"), + _ => None, } + } } - impl ::core::fmt::Debug for Race { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - if let Some(name) = self.variant_name() { - f.write_str(name) - } else { - f.write_fmt(format_args!("", self.0)) - } + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) } + } } - impl<'a> ::flatbuffers::Follow<'a> for Race { - type Inner = Self; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; - Self(b) - } + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; + Self(b) + } } impl ::flatbuffers::Push for Race { type Output = Race; - #[inline] unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { unsafe { ::flatbuffers::emplace_scalar::(dst, self.0) }; @@ -80,28 +71,26 @@ impl ::flatbuffers::Push for Race { } impl ::flatbuffers::EndianScalar for Race { - type Scalar = i8; - - #[inline] - fn to_little_endian(self) -> i8 { - self.0.to_le() - } - - #[inline] - #[allow(clippy::wrong_self_convention)] - fn from_little_endian(v: i8) -> Self { - let b = i8::from_le(v); - Self(b) - } + type Scalar = i8; + #[inline] + fn to_little_endian(self) -> i8 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: i8) -> Self { + let b = i8::from_le(v); + Self(b) + } } impl<'a> ::flatbuffers::Verifiable for Race { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - i8::run_verifier(v, pos) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + i8::run_verifier(v, pos) + } } impl ::flatbuffers::SimpleToVerifyInSlice for Race {} diff --git a/tests/monster_test/my_game/example/referrable_generated.rs b/tests/monster_test/my_game/example/referrable_generated.rs index 38e259a3e..08e1f843f 100644 --- a/tests/monster_test/my_game/example/referrable_generated.rs +++ b/tests/monster_test/my_game/example/referrable_generated.rs @@ -2,154 +2,142 @@ // @generated extern crate alloc; use super::*; - pub enum ReferrableOffset {} - #[derive(Copy, Clone, PartialEq)] + pub struct Referrable<'a> { - pub _tab: ::flatbuffers::Table<'a>, + pub _tab: ::flatbuffers::Table<'a>, } impl<'a> ::flatbuffers::Follow<'a> for Referrable<'a> { - type Inner = Referrable<'a>; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } - } + type Inner = Referrable<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } + } } impl<'a> Referrable<'a> { - pub const VT_ID: ::flatbuffers::VOffsetT = 4; + pub const VT_ID: ::flatbuffers::VOffsetT = 4; - pub const fn get_fully_qualified_name() -> &'static str { - "MyGame.Example.Referrable" - } + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Example.Referrable" + } - #[inline] - pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { - Referrable { _tab: table } - } + #[inline] + pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { + Referrable { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args ReferrableArgs + ) -> ::flatbuffers::WIPOffset> { + let mut builder = ReferrableBuilder::new(_fbb); + builder.add_id(args.id); + builder.finish() + } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args ReferrableArgs - ) -> ::flatbuffers::WIPOffset> { - let mut builder = ReferrableBuilder::new(_fbb); - builder.add_id(args.id); - builder.finish() + pub fn unpack(&self) -> ReferrableT { + let id = self.id(); + ReferrableT { + id, } + } - pub fn unpack(&self) -> ReferrableT { - let id = self.id(); - ReferrableT { - id, - } - } + #[inline] + pub fn id(&self) -> u64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Referrable::VT_ID, Some(0)).unwrap()} + } + #[inline] + pub fn key_compare_less_than(&self, o: &Referrable) -> bool { + self.id() < o.id() + } - #[inline] - pub fn id(&self) -> u64 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Referrable::VT_ID, Some(0)).unwrap()} - } - - #[inline] - pub fn key_compare_less_than(&self, o: &Referrable) -> bool { - self.id() < o.id() - } - - #[inline] - pub fn key_compare_with_value(&self, val: u64) -> ::core::cmp::Ordering { - let key = self.id(); - key.cmp(&val) - } + #[inline] + pub fn key_compare_with_value(&self, val: u64) -> ::core::cmp::Ordering { + let key = self.id(); + key.cmp(&val) + } } impl ::flatbuffers::Verifiable for Referrable<'_> { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.visit_table(pos)? - .visit_field::("id", Self::VT_ID, false)? - .finish(); - Ok(()) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.visit_table(pos)? + .visit_field::("id", Self::VT_ID, false)? + .finish(); + Ok(()) + } } - pub struct ReferrableArgs { pub id: u64, } - impl<'a> Default for ReferrableArgs { - #[inline] - fn default() -> Self { - ReferrableArgs { - id: 0, - } + #[inline] + fn default() -> Self { + ReferrableArgs { + id: 0, } + } } pub struct ReferrableBuilder<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> { - fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, + fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, + start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, } - impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> ReferrableBuilder<'a, 'b, A> { - #[inline] - pub fn add_id(&mut self, id: u64) { - self.fbb_.push_slot::(Referrable::VT_ID, id, 0); - } - - #[inline] - pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> ReferrableBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - ReferrableBuilder { - fbb_: _fbb, - start_: start, - } - } - - #[inline] - pub fn finish(self) -> ::flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - ::flatbuffers::WIPOffset::new(o.value()) + #[inline] + pub fn add_id(&mut self, id: u64) { + self.fbb_.push_slot::(Referrable::VT_ID, id, 0); + } + #[inline] + pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> ReferrableBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + ReferrableBuilder { + fbb_: _fbb, + start_: start, } + } + #[inline] + pub fn finish(self) -> ::flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + ::flatbuffers::WIPOffset::new(o.value()) + } } impl ::core::fmt::Debug for Referrable<'_> { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - let mut ds = f.debug_struct("Referrable"); - ds.field("id", &self.id()); - ds.finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + let mut ds = f.debug_struct("Referrable"); + ds.field("id", &self.id()); + ds.finish() + } } - #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub struct ReferrableT { - pub id: u64, + pub id: u64, } - impl Default for ReferrableT { - fn default() -> Self { - Self { - id: 0, - } + fn default() -> Self { + Self { + id: 0, } + } } - impl ReferrableT { - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( - &self, - _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> - ) -> ::flatbuffers::WIPOffset> { - let id = self.id; - Referrable::create(_fbb, &ReferrableArgs{ - id, - }) - } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> + ) -> ::flatbuffers::WIPOffset> { + let id = self.id; + Referrable::create(_fbb, &ReferrableArgs{ + id, + }) + } } diff --git a/tests/monster_test/my_game/example/stat_generated.rs b/tests/monster_test/my_game/example/stat_generated.rs index 939461343..5f330356c 100644 --- a/tests/monster_test/my_game/example/stat_generated.rs +++ b/tests/monster_test/my_game/example/stat_generated.rs @@ -2,208 +2,192 @@ // @generated extern crate alloc; use super::*; - pub enum StatOffset {} - #[derive(Copy, Clone, PartialEq)] + pub struct Stat<'a> { - pub _tab: ::flatbuffers::Table<'a>, + pub _tab: ::flatbuffers::Table<'a>, } impl<'a> ::flatbuffers::Follow<'a> for Stat<'a> { - type Inner = Stat<'a>; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } - } + type Inner = Stat<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } + } } impl<'a> Stat<'a> { - pub const VT_ID: ::flatbuffers::VOffsetT = 4; - pub const VT_VAL: ::flatbuffers::VOffsetT = 6; - pub const VT_COUNT: ::flatbuffers::VOffsetT = 8; + pub const VT_ID: ::flatbuffers::VOffsetT = 4; + pub const VT_VAL: ::flatbuffers::VOffsetT = 6; + pub const VT_COUNT: ::flatbuffers::VOffsetT = 8; - pub const fn get_fully_qualified_name() -> &'static str { - "MyGame.Example.Stat" - } + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Example.Stat" + } - #[inline] - pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { - Stat { _tab: table } - } + #[inline] + pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { + Stat { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args StatArgs<'args> + ) -> ::flatbuffers::WIPOffset> { + let mut builder = StatBuilder::new(_fbb); + builder.add_val(args.val); + if let Some(x) = args.id { builder.add_id(x); } + builder.add_count(args.count); + builder.finish() + } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args StatArgs<'args> - ) -> ::flatbuffers::WIPOffset> { - let mut builder = StatBuilder::new(_fbb); - builder.add_val(args.val); - if let Some(x) = args.id { builder.add_id(x); } - builder.add_count(args.count); - builder.finish() + pub fn unpack(&self) -> StatT { + let id = self.id().map(|x| { + alloc::string::ToString::to_string(x) + }); + let val = self.val(); + let count = self.count(); + StatT { + id, + val, + count, } + } - pub fn unpack(&self) -> StatT { - let id = self.id().map(|x| { - alloc::string::ToString::to_string(x) - }); - let val = self.val(); - let count = self.count(); - StatT { - id, - val, - count, - } - } + #[inline] + pub fn id(&self) -> Option<&'a str> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<&str>>(Stat::VT_ID, None)} + } + #[inline] + pub fn val(&self) -> i64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Stat::VT_VAL, Some(0)).unwrap()} + } + #[inline] + pub fn count(&self) -> u16 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Stat::VT_COUNT, Some(0)).unwrap()} + } + #[inline] + pub fn key_compare_less_than(&self, o: &Stat) -> bool { + self.count() < o.count() + } - #[inline] - pub fn id(&self) -> Option<&'a str> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<&str>>(Stat::VT_ID, None)} - } - - #[inline] - pub fn val(&self) -> i64 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Stat::VT_VAL, Some(0)).unwrap()} - } - - #[inline] - pub fn count(&self) -> u16 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Stat::VT_COUNT, Some(0)).unwrap()} - } - - #[inline] - pub fn key_compare_less_than(&self, o: &Stat) -> bool { - self.count() < o.count() - } - - #[inline] - pub fn key_compare_with_value(&self, val: u16) -> ::core::cmp::Ordering { - let key = self.count(); - key.cmp(&val) - } + #[inline] + pub fn key_compare_with_value(&self, val: u16) -> ::core::cmp::Ordering { + let key = self.count(); + key.cmp(&val) + } } impl ::flatbuffers::Verifiable for Stat<'_> { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.visit_table(pos)? - .visit_field::<::flatbuffers::ForwardsUOffset<&str>>("id", Self::VT_ID, false)? - .visit_field::("val", Self::VT_VAL, false)? - .visit_field::("count", Self::VT_COUNT, false)? - .finish(); - Ok(()) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.visit_table(pos)? + .visit_field::<::flatbuffers::ForwardsUOffset<&str>>("id", Self::VT_ID, false)? + .visit_field::("val", Self::VT_VAL, false)? + .visit_field::("count", Self::VT_COUNT, false)? + .finish(); + Ok(()) + } } - pub struct StatArgs<'a> { pub id: Option<::flatbuffers::WIPOffset<&'a str>>, pub val: i64, pub count: u16, } - impl<'a> Default for StatArgs<'a> { - #[inline] - fn default() -> Self { - StatArgs { - id: None, - val: 0, - count: 0, - } + #[inline] + fn default() -> Self { + StatArgs { + id: None, + val: 0, + count: 0, } + } } pub struct StatBuilder<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> { - fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, + fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, + start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, } - impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> StatBuilder<'a, 'b, A> { - #[inline] - pub fn add_id(&mut self, id: ::flatbuffers::WIPOffset<&'b str>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Stat::VT_ID, id); - } - - #[inline] - pub fn add_val(&mut self, val: i64) { - self.fbb_.push_slot::(Stat::VT_VAL, val, 0); - } - - #[inline] - pub fn add_count(&mut self, count: u16) { - self.fbb_.push_slot::(Stat::VT_COUNT, count, 0); - } - - #[inline] - pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> StatBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - StatBuilder { - fbb_: _fbb, - start_: start, - } - } - - #[inline] - pub fn finish(self) -> ::flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - ::flatbuffers::WIPOffset::new(o.value()) + #[inline] + pub fn add_id(&mut self, id: ::flatbuffers::WIPOffset<&'b str>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Stat::VT_ID, id); + } + #[inline] + pub fn add_val(&mut self, val: i64) { + self.fbb_.push_slot::(Stat::VT_VAL, val, 0); + } + #[inline] + pub fn add_count(&mut self, count: u16) { + self.fbb_.push_slot::(Stat::VT_COUNT, count, 0); + } + #[inline] + pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> StatBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + StatBuilder { + fbb_: _fbb, + start_: start, } + } + #[inline] + pub fn finish(self) -> ::flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + ::flatbuffers::WIPOffset::new(o.value()) + } } impl ::core::fmt::Debug for Stat<'_> { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - let mut ds = f.debug_struct("Stat"); - ds.field("id", &self.id()); - ds.field("val", &self.val()); - ds.field("count", &self.count()); - ds.finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + let mut ds = f.debug_struct("Stat"); + ds.field("id", &self.id()); + ds.field("val", &self.val()); + ds.field("count", &self.count()); + ds.finish() + } } - #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub struct StatT { - pub id: Option, - pub val: i64, - pub count: u16, + pub id: Option, + pub val: i64, + pub count: u16, } - impl Default for StatT { - fn default() -> Self { - Self { - id: None, - val: 0, - count: 0, - } + fn default() -> Self { + Self { + id: None, + val: 0, + count: 0, } + } } - impl StatT { - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( - &self, - _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> - ) -> ::flatbuffers::WIPOffset> { - let id = self.id.as_ref().map(|x|{ - _fbb.create_string(x) - }); - let val = self.val; - let count = self.count; - Stat::create(_fbb, &StatArgs{ - id, - val, - count, - }) - } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> + ) -> ::flatbuffers::WIPOffset> { + let id = self.id.as_ref().map(|x|{ + _fbb.create_string(x) + }); + let val = self.val; + let count = self.count; + Stat::create(_fbb, &StatArgs{ + id, + val, + count, + }) + } } diff --git a/tests/monster_test/my_game/example/struct_of_structs_generated.rs b/tests/monster_test/my_game/example/struct_of_structs_generated.rs index 8231985d1..05d1a4fef 100644 --- a/tests/monster_test/my_game/example/struct_of_structs_generated.rs +++ b/tests/monster_test/my_game/example/struct_of_structs_generated.rs @@ -2,57 +2,47 @@ // @generated extern crate alloc; use super::*; - // struct StructOfStructs, aligned to 4 #[repr(transparent)] #[derive(Clone, Copy, PartialEq)] pub struct StructOfStructs(pub [u8; 20]); - -impl Default for StructOfStructs { - fn default() -> Self { - Self([0; 20]) - } +impl Default for StructOfStructs { + fn default() -> Self { + Self([0; 20]) + } } - impl ::core::fmt::Debug for StructOfStructs { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - f.debug_struct("StructOfStructs") - .field("a", &self.a()) - .field("b", &self.b()) - .field("c", &self.c()) - .finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + f.debug_struct("StructOfStructs") + .field("a", &self.a()) + .field("b", &self.b()) + .field("c", &self.c()) + .finish() + } } impl ::flatbuffers::SimpleToVerifyInSlice for StructOfStructs {} - impl<'a> ::flatbuffers::Follow<'a> for StructOfStructs { - type Inner = &'a StructOfStructs; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - unsafe { <&'a StructOfStructs>::follow(buf, loc) } - } + type Inner = &'a StructOfStructs; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { <&'a StructOfStructs>::follow(buf, loc) } + } } - impl<'a> ::flatbuffers::Follow<'a> for &'a StructOfStructs { - type Inner = &'a StructOfStructs; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - unsafe { ::flatbuffers::follow_cast_ref::(buf, loc) } - } + type Inner = &'a StructOfStructs; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { ::flatbuffers::follow_cast_ref::(buf, loc) } + } } - impl<'b> ::flatbuffers::Push for StructOfStructs { type Output = StructOfStructs; - #[inline] unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { let src = unsafe { ::core::slice::from_raw_parts(self as *const StructOfStructs as *const u8, ::size()) }; dst.copy_from_slice(src); } - #[inline] fn alignment() -> ::flatbuffers::PushAlignment { ::flatbuffers::PushAlignment::new(4) @@ -60,99 +50,90 @@ impl<'b> ::flatbuffers::Push for StructOfStructs { } impl<'a> ::flatbuffers::Verifiable for StructOfStructs { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.in_buffer::(pos) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.in_buffer::(pos) + } } impl<'a> StructOfStructs { - #[allow(clippy::too_many_arguments)] - pub fn new( - a: &Ability, - b: &Test, - c: &Ability, - ) -> Self { - let mut s = Self([0; 20]); - s.set_a(a); - s.set_b(b); - s.set_c(c); - s - } + #[allow(clippy::too_many_arguments)] + pub fn new( + a: &Ability, + b: &Test, + c: &Ability, + ) -> Self { + let mut s = Self([0; 20]); + s.set_a(a); + s.set_b(b); + s.set_c(c); + s + } - pub const fn get_fully_qualified_name() -> &'static str { - "MyGame.Example.StructOfStructs" - } + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Example.StructOfStructs" + } - pub fn a(&self) -> &Ability { - // Safety: - // Created from a valid Table for this object - // Which contains a valid struct in this slot - unsafe { &*(self.0[0..].as_ptr() as *const Ability) } - } + pub fn a(&self) -> &Ability { + // Safety: + // Created from a valid Table for this object + // Which contains a valid struct in this slot + unsafe { &*(self.0[0..].as_ptr() as *const Ability) } + } - #[allow(clippy::identity_op)] - pub fn set_a(&mut self, x: &Ability) { - self.0[0..0 + 8].copy_from_slice(&x.0) - } + #[allow(clippy::identity_op)] + pub fn set_a(&mut self, x: &Ability) { + self.0[0..0 + 8].copy_from_slice(&x.0) + } - pub fn b(&self) -> &Test { - // Safety: - // Created from a valid Table for this object - // Which contains a valid struct in this slot - unsafe { &*(self.0[8..].as_ptr() as *const Test) } - } + pub fn b(&self) -> &Test { + // Safety: + // Created from a valid Table for this object + // Which contains a valid struct in this slot + unsafe { &*(self.0[8..].as_ptr() as *const Test) } + } - #[allow(clippy::identity_op)] - pub fn set_b(&mut self, x: &Test) { - self.0[8..8 + 4].copy_from_slice(&x.0) - } + #[allow(clippy::identity_op)] + pub fn set_b(&mut self, x: &Test) { + self.0[8..8 + 4].copy_from_slice(&x.0) + } - pub fn c(&self) -> &Ability { - // Safety: - // Created from a valid Table for this object - // Which contains a valid struct in this slot - unsafe { &*(self.0[12..].as_ptr() as *const Ability) } - } + pub fn c(&self) -> &Ability { + // Safety: + // Created from a valid Table for this object + // Which contains a valid struct in this slot + unsafe { &*(self.0[12..].as_ptr() as *const Ability) } + } - #[allow(clippy::identity_op)] - pub fn set_c(&mut self, x: &Ability) { - self.0[12..12 + 8].copy_from_slice(&x.0) - } + #[allow(clippy::identity_op)] + pub fn set_c(&mut self, x: &Ability) { + self.0[12..12 + 8].copy_from_slice(&x.0) + } - pub fn unpack(&self) -> StructOfStructsT { - StructOfStructsT { - a: self.a().unpack(), - b: self.b().unpack(), - c: self.c().unpack(), - } + pub fn unpack(&self) -> StructOfStructsT { + StructOfStructsT { + a: self.a().unpack(), + b: self.b().unpack(), + c: self.c().unpack(), } + } } -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Default)] pub struct StructOfStructsT { - pub a: AbilityT, - pub b: TestT, - pub c: AbilityT, + pub a: AbilityT, + pub b: TestT, + pub c: AbilityT, } -impl Default for StructOfStructsT { - fn default() -> Self { - Self { - a: Default::default(), - b: Default::default(), - c: Default::default(), - } - } +impl StructOfStructsT { + pub fn pack(&self) -> StructOfStructs { + StructOfStructs::new( + &self.a.pack(), + &self.b.pack(), + &self.c.pack(), + ) + } } -impl StructOfStructsT { - pub fn pack(&self) -> StructOfStructs { - StructOfStructs::new( - &self.a.pack(), - &self.b.pack(), - &self.c.pack(), - ) - } -} diff --git a/tests/monster_test/my_game/example/struct_of_structs_of_structs_generated.rs b/tests/monster_test/my_game/example/struct_of_structs_of_structs_generated.rs index 3f972894b..a0fd05524 100644 --- a/tests/monster_test/my_game/example/struct_of_structs_of_structs_generated.rs +++ b/tests/monster_test/my_game/example/struct_of_structs_of_structs_generated.rs @@ -2,55 +2,45 @@ // @generated extern crate alloc; use super::*; - // struct StructOfStructsOfStructs, aligned to 4 #[repr(transparent)] #[derive(Clone, Copy, PartialEq)] pub struct StructOfStructsOfStructs(pub [u8; 20]); - -impl Default for StructOfStructsOfStructs { - fn default() -> Self { - Self([0; 20]) - } +impl Default for StructOfStructsOfStructs { + fn default() -> Self { + Self([0; 20]) + } } - impl ::core::fmt::Debug for StructOfStructsOfStructs { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - f.debug_struct("StructOfStructsOfStructs") - .field("a", &self.a()) - .finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + f.debug_struct("StructOfStructsOfStructs") + .field("a", &self.a()) + .finish() + } } impl ::flatbuffers::SimpleToVerifyInSlice for StructOfStructsOfStructs {} - impl<'a> ::flatbuffers::Follow<'a> for StructOfStructsOfStructs { - type Inner = &'a StructOfStructsOfStructs; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - unsafe { <&'a StructOfStructsOfStructs>::follow(buf, loc) } - } + type Inner = &'a StructOfStructsOfStructs; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { <&'a StructOfStructsOfStructs>::follow(buf, loc) } + } } - impl<'a> ::flatbuffers::Follow<'a> for &'a StructOfStructsOfStructs { - type Inner = &'a StructOfStructsOfStructs; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - unsafe { ::flatbuffers::follow_cast_ref::(buf, loc) } - } + type Inner = &'a StructOfStructsOfStructs; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { ::flatbuffers::follow_cast_ref::(buf, loc) } + } } - impl<'b> ::flatbuffers::Push for StructOfStructsOfStructs { type Output = StructOfStructsOfStructs; - #[inline] unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { let src = unsafe { ::core::slice::from_raw_parts(self as *const StructOfStructsOfStructs as *const u8, ::size()) }; dst.copy_from_slice(src); } - #[inline] fn alignment() -> ::flatbuffers::PushAlignment { ::flatbuffers::PushAlignment::new(4) @@ -58,63 +48,56 @@ impl<'b> ::flatbuffers::Push for StructOfStructsOfStructs { } impl<'a> ::flatbuffers::Verifiable for StructOfStructsOfStructs { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.in_buffer::(pos) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.in_buffer::(pos) + } } impl<'a> StructOfStructsOfStructs { - #[allow(clippy::too_many_arguments)] - pub fn new( - a: &StructOfStructs, - ) -> Self { - let mut s = Self([0; 20]); - s.set_a(a); - s - } + #[allow(clippy::too_many_arguments)] + pub fn new( + a: &StructOfStructs, + ) -> Self { + let mut s = Self([0; 20]); + s.set_a(a); + s + } - pub const fn get_fully_qualified_name() -> &'static str { - "MyGame.Example.StructOfStructsOfStructs" - } + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Example.StructOfStructsOfStructs" + } - pub fn a(&self) -> &StructOfStructs { - // Safety: - // Created from a valid Table for this object - // Which contains a valid struct in this slot - unsafe { &*(self.0[0..].as_ptr() as *const StructOfStructs) } - } + pub fn a(&self) -> &StructOfStructs { + // Safety: + // Created from a valid Table for this object + // Which contains a valid struct in this slot + unsafe { &*(self.0[0..].as_ptr() as *const StructOfStructs) } + } - #[allow(clippy::identity_op)] - pub fn set_a(&mut self, x: &StructOfStructs) { - self.0[0..0 + 20].copy_from_slice(&x.0) - } + #[allow(clippy::identity_op)] + pub fn set_a(&mut self, x: &StructOfStructs) { + self.0[0..0 + 20].copy_from_slice(&x.0) + } - pub fn unpack(&self) -> StructOfStructsOfStructsT { - StructOfStructsOfStructsT { - a: self.a().unpack(), - } + pub fn unpack(&self) -> StructOfStructsOfStructsT { + StructOfStructsOfStructsT { + a: self.a().unpack(), } + } } -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Default)] pub struct StructOfStructsOfStructsT { - pub a: StructOfStructsT, + pub a: StructOfStructsT, } -impl Default for StructOfStructsOfStructsT { - fn default() -> Self { - Self { - a: Default::default(), - } - } +impl StructOfStructsOfStructsT { + pub fn pack(&self) -> StructOfStructsOfStructs { + StructOfStructsOfStructs::new( + &self.a.pack(), + ) + } } -impl StructOfStructsOfStructsT { - pub fn pack(&self) -> StructOfStructsOfStructs { - StructOfStructsOfStructs::new( - &self.a.pack(), - ) - } -} diff --git a/tests/monster_test/my_game/example/test_generated.rs b/tests/monster_test/my_game/example/test_generated.rs index ae5341a28..178cbe99c 100644 --- a/tests/monster_test/my_game/example/test_generated.rs +++ b/tests/monster_test/my_game/example/test_generated.rs @@ -2,56 +2,46 @@ // @generated extern crate alloc; use super::*; - // struct Test, aligned to 2 #[repr(transparent)] #[derive(Clone, Copy, PartialEq)] pub struct Test(pub [u8; 4]); - -impl Default for Test { - fn default() -> Self { - Self([0; 4]) - } +impl Default for Test { + fn default() -> Self { + Self([0; 4]) + } } - impl ::core::fmt::Debug for Test { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - f.debug_struct("Test") - .field("a", &self.a()) - .field("b", &self.b()) - .finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + f.debug_struct("Test") + .field("a", &self.a()) + .field("b", &self.b()) + .finish() + } } impl ::flatbuffers::SimpleToVerifyInSlice for Test {} - impl<'a> ::flatbuffers::Follow<'a> for Test { - type Inner = &'a Test; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - unsafe { <&'a Test>::follow(buf, loc) } - } + type Inner = &'a Test; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { <&'a Test>::follow(buf, loc) } + } } - impl<'a> ::flatbuffers::Follow<'a> for &'a Test { - type Inner = &'a Test; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - unsafe { ::flatbuffers::follow_cast_ref::(buf, loc) } - } + type Inner = &'a Test; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { ::flatbuffers::follow_cast_ref::(buf, loc) } + } } - impl<'b> ::flatbuffers::Push for Test { type Output = Test; - #[inline] unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { let src = unsafe { ::core::slice::from_raw_parts(self as *const Test as *const u8, ::size()) }; dst.copy_from_slice(src); } - #[inline] fn alignment() -> ::flatbuffers::PushAlignment { ::flatbuffers::PushAlignment::new(2) @@ -59,115 +49,107 @@ impl<'b> ::flatbuffers::Push for Test { } impl<'a> ::flatbuffers::Verifiable for Test { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.in_buffer::(pos) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.in_buffer::(pos) + } } impl<'a> Test { - #[allow(clippy::too_many_arguments)] - pub fn new( - a: i16, - b: i8, - ) -> Self { - let mut s = Self([0; 4]); - s.set_a(a); - s.set_b(b); - s - } + #[allow(clippy::too_many_arguments)] + pub fn new( + a: i16, + b: i8, + ) -> Self { + let mut s = Self([0; 4]); + s.set_a(a); + s.set_b(b); + s + } - pub const fn get_fully_qualified_name() -> &'static str { - "MyGame.Example.Test" - } + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Example.Test" + } - pub fn a(&self) -> i16 { - let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - ::flatbuffers::EndianScalar::from_little_endian(unsafe { - ::core::ptr::copy_nonoverlapping( - self.0[0..].as_ptr(), - mem.as_mut_ptr() as *mut u8, - ::core::mem::size_of::<::Scalar>(), - ); - mem.assume_init() - }) - } + pub fn a(&self) -> i16 { + let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + ::flatbuffers::EndianScalar::from_little_endian(unsafe { + ::core::ptr::copy_nonoverlapping( + self.0[0..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + ::core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } - pub fn set_a(&mut self, x: i16) { - let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - unsafe { - ::core::ptr::copy_nonoverlapping( - &x_le as *const _ as *const u8, - self.0[0..].as_mut_ptr(), - ::core::mem::size_of::<::Scalar>(), - ); - } + pub fn set_a(&mut self, x: i16) { + let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + ::core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[0..].as_mut_ptr(), + ::core::mem::size_of::<::Scalar>(), + ); } + } - pub fn b(&self) -> i8 { - let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - ::flatbuffers::EndianScalar::from_little_endian(unsafe { - ::core::ptr::copy_nonoverlapping( - self.0[2..].as_ptr(), - mem.as_mut_ptr() as *mut u8, - ::core::mem::size_of::<::Scalar>(), - ); - mem.assume_init() - }) - } + pub fn b(&self) -> i8 { + let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + ::flatbuffers::EndianScalar::from_little_endian(unsafe { + ::core::ptr::copy_nonoverlapping( + self.0[2..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + ::core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } - pub fn set_b(&mut self, x: i8) { - let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - unsafe { - ::core::ptr::copy_nonoverlapping( - &x_le as *const _ as *const u8, - self.0[2..].as_mut_ptr(), - ::core::mem::size_of::<::Scalar>(), - ); - } + pub fn set_b(&mut self, x: i8) { + let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + ::core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[2..].as_mut_ptr(), + ::core::mem::size_of::<::Scalar>(), + ); } + } - pub fn unpack(&self) -> TestT { - TestT { - a: self.a(), - b: self.b(), - } + pub fn unpack(&self) -> TestT { + TestT { + a: self.a(), + b: self.b(), } + } } -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Default)] pub struct TestT { - pub a: i16, - pub b: i8, + pub a: i16, + pub b: i8, } -impl Default for TestT { - fn default() -> Self { - Self { - a: 0, - b: 0, - } - } +impl TestT { + pub fn pack(&self) -> Test { + Test::new( + self.a, + self.b, + ) + } } -impl TestT { - pub fn pack(&self) -> Test { - Test::new( - self.a, - self.b, - ) - } -} diff --git a/tests/monster_test/my_game/example/test_simple_table_with_enum_generated.rs b/tests/monster_test/my_game/example/test_simple_table_with_enum_generated.rs index bbb18acbd..c264d4969 100644 --- a/tests/monster_test/my_game/example/test_simple_table_with_enum_generated.rs +++ b/tests/monster_test/my_game/example/test_simple_table_with_enum_generated.rs @@ -2,143 +2,132 @@ // @generated extern crate alloc; use super::*; - pub enum TestSimpleTableWithEnumOffset {} - #[derive(Copy, Clone, PartialEq)] + pub struct TestSimpleTableWithEnum<'a> { - pub _tab: ::flatbuffers::Table<'a>, + pub _tab: ::flatbuffers::Table<'a>, } impl<'a> ::flatbuffers::Follow<'a> for TestSimpleTableWithEnum<'a> { - type Inner = TestSimpleTableWithEnum<'a>; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } - } + type Inner = TestSimpleTableWithEnum<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } + } } impl<'a> TestSimpleTableWithEnum<'a> { - pub const VT_COLOR: ::flatbuffers::VOffsetT = 4; + pub const VT_COLOR: ::flatbuffers::VOffsetT = 4; - pub const fn get_fully_qualified_name() -> &'static str { - "MyGame.Example.TestSimpleTableWithEnum" - } + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Example.TestSimpleTableWithEnum" + } - #[inline] - pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { - TestSimpleTableWithEnum { _tab: table } - } + #[inline] + pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { + TestSimpleTableWithEnum { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args TestSimpleTableWithEnumArgs + ) -> ::flatbuffers::WIPOffset> { + let mut builder = TestSimpleTableWithEnumBuilder::new(_fbb); + builder.add_color(args.color); + builder.finish() + } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args TestSimpleTableWithEnumArgs - ) -> ::flatbuffers::WIPOffset> { - let mut builder = TestSimpleTableWithEnumBuilder::new(_fbb); - builder.add_color(args.color); - builder.finish() + pub fn unpack(&self) -> TestSimpleTableWithEnumT { + let color = self.color(); + TestSimpleTableWithEnumT { + color, } + } - pub fn unpack(&self) -> TestSimpleTableWithEnumT { - let color = self.color(); - TestSimpleTableWithEnumT { - color, - } - } - - #[inline] - pub fn color(&self) -> Color { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(TestSimpleTableWithEnum::VT_COLOR, Some(Color::Green)).unwrap()} - } + #[inline] + pub fn color(&self) -> Color { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TestSimpleTableWithEnum::VT_COLOR, Some(Color::Green)).unwrap()} + } } impl ::flatbuffers::Verifiable for TestSimpleTableWithEnum<'_> { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.visit_table(pos)? - .visit_field::("color", Self::VT_COLOR, false)? - .finish(); - Ok(()) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.visit_table(pos)? + .visit_field::("color", Self::VT_COLOR, false)? + .finish(); + Ok(()) + } } - pub struct TestSimpleTableWithEnumArgs { pub color: Color, } - impl<'a> Default for TestSimpleTableWithEnumArgs { - #[inline] - fn default() -> Self { - TestSimpleTableWithEnumArgs { - color: Color::Green, - } + #[inline] + fn default() -> Self { + TestSimpleTableWithEnumArgs { + color: Color::Green, } + } } pub struct TestSimpleTableWithEnumBuilder<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> { - fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, + fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, + start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, } - impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> TestSimpleTableWithEnumBuilder<'a, 'b, A> { - #[inline] - pub fn add_color(&mut self, color: Color) { - self.fbb_.push_slot::(TestSimpleTableWithEnum::VT_COLOR, color, Color::Green); - } - - #[inline] - pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> TestSimpleTableWithEnumBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - TestSimpleTableWithEnumBuilder { - fbb_: _fbb, - start_: start, - } - } - - #[inline] - pub fn finish(self) -> ::flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - ::flatbuffers::WIPOffset::new(o.value()) + #[inline] + pub fn add_color(&mut self, color: Color) { + self.fbb_.push_slot::(TestSimpleTableWithEnum::VT_COLOR, color, Color::Green); + } + #[inline] + pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> TestSimpleTableWithEnumBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + TestSimpleTableWithEnumBuilder { + fbb_: _fbb, + start_: start, } + } + #[inline] + pub fn finish(self) -> ::flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + ::flatbuffers::WIPOffset::new(o.value()) + } } impl ::core::fmt::Debug for TestSimpleTableWithEnum<'_> { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - let mut ds = f.debug_struct("TestSimpleTableWithEnum"); - ds.field("color", &self.color()); - ds.finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + let mut ds = f.debug_struct("TestSimpleTableWithEnum"); + ds.field("color", &self.color()); + ds.finish() + } } - #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub struct TestSimpleTableWithEnumT { - pub color: Color, + pub color: Color, } - impl Default for TestSimpleTableWithEnumT { - fn default() -> Self { - Self { - color: Color::Green, - } + fn default() -> Self { + Self { + color: Color::Green, } + } } - impl TestSimpleTableWithEnumT { - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( - &self, - _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> - ) -> ::flatbuffers::WIPOffset> { - let color = self.color; - TestSimpleTableWithEnum::create(_fbb, &TestSimpleTableWithEnumArgs{ - color, - }) - } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> + ) -> ::flatbuffers::WIPOffset> { + let color = self.color; + TestSimpleTableWithEnum::create(_fbb, &TestSimpleTableWithEnumArgs{ + color, + }) + } } diff --git a/tests/monster_test/my_game/example/type_aliases_generated.rs b/tests/monster_test/my_game/example/type_aliases_generated.rs index 35d064d05..b7788ebdf 100644 --- a/tests/monster_test/my_game/example/type_aliases_generated.rs +++ b/tests/monster_test/my_game/example/type_aliases_generated.rs @@ -2,220 +2,205 @@ // @generated extern crate alloc; use super::*; - pub enum TypeAliasesOffset {} - #[derive(Copy, Clone, PartialEq)] + pub struct TypeAliases<'a> { - pub _tab: ::flatbuffers::Table<'a>, + pub _tab: ::flatbuffers::Table<'a>, } impl<'a> ::flatbuffers::Follow<'a> for TypeAliases<'a> { - type Inner = TypeAliases<'a>; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } - } + type Inner = TypeAliases<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } + } } impl<'a> TypeAliases<'a> { - pub const VT_I8_: ::flatbuffers::VOffsetT = 4; - pub const VT_U8_: ::flatbuffers::VOffsetT = 6; - pub const VT_I16_: ::flatbuffers::VOffsetT = 8; - pub const VT_U16_: ::flatbuffers::VOffsetT = 10; - pub const VT_I32_: ::flatbuffers::VOffsetT = 12; - pub const VT_U32_: ::flatbuffers::VOffsetT = 14; - pub const VT_I64_: ::flatbuffers::VOffsetT = 16; - pub const VT_U64_: ::flatbuffers::VOffsetT = 18; - pub const VT_F32_: ::flatbuffers::VOffsetT = 20; - pub const VT_F64_: ::flatbuffers::VOffsetT = 22; - pub const VT_V8: ::flatbuffers::VOffsetT = 24; - pub const VT_VF64: ::flatbuffers::VOffsetT = 26; + pub const VT_I8_: ::flatbuffers::VOffsetT = 4; + pub const VT_U8_: ::flatbuffers::VOffsetT = 6; + pub const VT_I16_: ::flatbuffers::VOffsetT = 8; + pub const VT_U16_: ::flatbuffers::VOffsetT = 10; + pub const VT_I32_: ::flatbuffers::VOffsetT = 12; + pub const VT_U32_: ::flatbuffers::VOffsetT = 14; + pub const VT_I64_: ::flatbuffers::VOffsetT = 16; + pub const VT_U64_: ::flatbuffers::VOffsetT = 18; + pub const VT_F32_: ::flatbuffers::VOffsetT = 20; + pub const VT_F64_: ::flatbuffers::VOffsetT = 22; + pub const VT_V8: ::flatbuffers::VOffsetT = 24; + pub const VT_VF64: ::flatbuffers::VOffsetT = 26; - pub const fn get_fully_qualified_name() -> &'static str { - "MyGame.Example.TypeAliases" - } + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Example.TypeAliases" + } - #[inline] - pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { - TypeAliases { _tab: table } - } + #[inline] + pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { + TypeAliases { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args TypeAliasesArgs<'args> + ) -> ::flatbuffers::WIPOffset> { + let mut builder = TypeAliasesBuilder::new(_fbb); + builder.add_f64_(args.f64_); + builder.add_u64_(args.u64_); + builder.add_i64_(args.i64_); + if let Some(x) = args.vf64 { builder.add_vf64(x); } + if let Some(x) = args.v8 { builder.add_v8(x); } + builder.add_f32_(args.f32_); + builder.add_u32_(args.u32_); + builder.add_i32_(args.i32_); + builder.add_u16_(args.u16_); + builder.add_i16_(args.i16_); + builder.add_u8_(args.u8_); + builder.add_i8_(args.i8_); + builder.finish() + } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args TypeAliasesArgs<'args> - ) -> ::flatbuffers::WIPOffset> { - let mut builder = TypeAliasesBuilder::new(_fbb); - builder.add_f64_(args.f64_); - builder.add_u64_(args.u64_); - builder.add_i64_(args.i64_); - if let Some(x) = args.vf64 { builder.add_vf64(x); } - if let Some(x) = args.v8 { builder.add_v8(x); } - builder.add_f32_(args.f32_); - builder.add_u32_(args.u32_); - builder.add_i32_(args.i32_); - builder.add_u16_(args.u16_); - builder.add_i16_(args.i16_); - builder.add_u8_(args.u8_); - builder.add_i8_(args.i8_); - builder.finish() + pub fn unpack(&self) -> TypeAliasesT { + let i8_ = self.i8_(); + let u8_ = self.u8_(); + let i16_ = self.i16_(); + let u16_ = self.u16_(); + let i32_ = self.i32_(); + let u32_ = self.u32_(); + let i64_ = self.i64_(); + let u64_ = self.u64_(); + let f32_ = self.f32_(); + let f64_ = self.f64_(); + let v8 = self.v8().map(|x| { + x.into_iter().collect() + }); + let vf64 = self.vf64().map(|x| { + x.into_iter().collect() + }); + TypeAliasesT { + i8_, + u8_, + i16_, + u16_, + i32_, + u32_, + i64_, + u64_, + f32_, + f64_, + v8, + vf64, } + } - pub fn unpack(&self) -> TypeAliasesT { - let i8_ = self.i8_(); - let u8_ = self.u8_(); - let i16_ = self.i16_(); - let u16_ = self.u16_(); - let i32_ = self.i32_(); - let u32_ = self.u32_(); - let i64_ = self.i64_(); - let u64_ = self.u64_(); - let f32_ = self.f32_(); - let f64_ = self.f64_(); - let v8 = self.v8().map(|x| { - x.into_iter().collect() - }); - let vf64 = self.vf64().map(|x| { - x.into_iter().collect() - }); - TypeAliasesT { - i8_, - u8_, - i16_, - u16_, - i32_, - u32_, - i64_, - u64_, - f32_, - f64_, - v8, - vf64, - } - } - - #[inline] - pub fn i8_(&self) -> i8 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(TypeAliases::VT_I8_, Some(0)).unwrap()} - } - - #[inline] - pub fn u8_(&self) -> u8 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(TypeAliases::VT_U8_, Some(0)).unwrap()} - } - - #[inline] - pub fn i16_(&self) -> i16 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(TypeAliases::VT_I16_, Some(0)).unwrap()} - } - - #[inline] - pub fn u16_(&self) -> u16 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(TypeAliases::VT_U16_, Some(0)).unwrap()} - } - - #[inline] - pub fn i32_(&self) -> i32 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(TypeAliases::VT_I32_, Some(0)).unwrap()} - } - - #[inline] - pub fn u32_(&self) -> u32 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(TypeAliases::VT_U32_, Some(0)).unwrap()} - } - - #[inline] - pub fn i64_(&self) -> i64 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(TypeAliases::VT_I64_, Some(0)).unwrap()} - } - - #[inline] - pub fn u64_(&self) -> u64 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(TypeAliases::VT_U64_, Some(0)).unwrap()} - } - - #[inline] - pub fn f32_(&self) -> f32 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(TypeAliases::VT_F32_, Some(0.0)).unwrap()} - } - - #[inline] - pub fn f64_(&self) -> f64 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(TypeAliases::VT_F64_, Some(0.0)).unwrap()} - } - - #[inline] - pub fn v8(&self) -> Option<::flatbuffers::Vector<'a, i8>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, i8>>>(TypeAliases::VT_V8, None)} - } - - #[inline] - pub fn vf64(&self) -> Option<::flatbuffers::Vector<'a, f64>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, f64>>>(TypeAliases::VT_VF64, None)} - } + #[inline] + pub fn i8_(&self) -> i8 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TypeAliases::VT_I8_, Some(0)).unwrap()} + } + #[inline] + pub fn u8_(&self) -> u8 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TypeAliases::VT_U8_, Some(0)).unwrap()} + } + #[inline] + pub fn i16_(&self) -> i16 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TypeAliases::VT_I16_, Some(0)).unwrap()} + } + #[inline] + pub fn u16_(&self) -> u16 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TypeAliases::VT_U16_, Some(0)).unwrap()} + } + #[inline] + pub fn i32_(&self) -> i32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TypeAliases::VT_I32_, Some(0)).unwrap()} + } + #[inline] + pub fn u32_(&self) -> u32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TypeAliases::VT_U32_, Some(0)).unwrap()} + } + #[inline] + pub fn i64_(&self) -> i64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TypeAliases::VT_I64_, Some(0)).unwrap()} + } + #[inline] + pub fn u64_(&self) -> u64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TypeAliases::VT_U64_, Some(0)).unwrap()} + } + #[inline] + pub fn f32_(&self) -> f32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TypeAliases::VT_F32_, Some(0.0)).unwrap()} + } + #[inline] + pub fn f64_(&self) -> f64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TypeAliases::VT_F64_, Some(0.0)).unwrap()} + } + #[inline] + pub fn v8(&self) -> Option<::flatbuffers::Vector<'a, i8>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, i8>>>(TypeAliases::VT_V8, None)} + } + #[inline] + pub fn vf64(&self) -> Option<::flatbuffers::Vector<'a, f64>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, f64>>>(TypeAliases::VT_VF64, None)} + } } impl ::flatbuffers::Verifiable for TypeAliases<'_> { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.visit_table(pos)? - .visit_field::("i8_", Self::VT_I8_, false)? - .visit_field::("u8_", Self::VT_U8_, false)? - .visit_field::("i16_", Self::VT_I16_, false)? - .visit_field::("u16_", Self::VT_U16_, false)? - .visit_field::("i32_", Self::VT_I32_, false)? - .visit_field::("u32_", Self::VT_U32_, false)? - .visit_field::("i64_", Self::VT_I64_, false)? - .visit_field::("u64_", Self::VT_U64_, false)? - .visit_field::("f32_", Self::VT_F32_, false)? - .visit_field::("f64_", Self::VT_F64_, false)? - .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, i8>>>("v8", Self::VT_V8, false)? - .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, f64>>>("vf64", Self::VT_VF64, false)? - .finish(); - Ok(()) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.visit_table(pos)? + .visit_field::("i8_", Self::VT_I8_, false)? + .visit_field::("u8_", Self::VT_U8_, false)? + .visit_field::("i16_", Self::VT_I16_, false)? + .visit_field::("u16_", Self::VT_U16_, false)? + .visit_field::("i32_", Self::VT_I32_, false)? + .visit_field::("u32_", Self::VT_U32_, false)? + .visit_field::("i64_", Self::VT_I64_, false)? + .visit_field::("u64_", Self::VT_U64_, false)? + .visit_field::("f32_", Self::VT_F32_, false)? + .visit_field::("f64_", Self::VT_F64_, false)? + .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, i8>>>("v8", Self::VT_V8, false)? + .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, f64>>>("vf64", Self::VT_VF64, false)? + .finish(); + Ok(()) + } } - pub struct TypeAliasesArgs<'a> { pub i8_: i8, pub u8_: u8, @@ -230,198 +215,180 @@ pub struct TypeAliasesArgs<'a> { pub v8: Option<::flatbuffers::WIPOffset<::flatbuffers::Vector<'a, i8>>>, pub vf64: Option<::flatbuffers::WIPOffset<::flatbuffers::Vector<'a, f64>>>, } - impl<'a> Default for TypeAliasesArgs<'a> { - #[inline] - fn default() -> Self { - TypeAliasesArgs { - i8_: 0, - u8_: 0, - i16_: 0, - u16_: 0, - i32_: 0, - u32_: 0, - i64_: 0, - u64_: 0, - f32_: 0.0, - f64_: 0.0, - v8: None, - vf64: None, - } + #[inline] + fn default() -> Self { + TypeAliasesArgs { + i8_: 0, + u8_: 0, + i16_: 0, + u16_: 0, + i32_: 0, + u32_: 0, + i64_: 0, + u64_: 0, + f32_: 0.0, + f64_: 0.0, + v8: None, + vf64: None, } + } } pub struct TypeAliasesBuilder<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> { - fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, + fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, + start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, } - impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> TypeAliasesBuilder<'a, 'b, A> { - #[inline] - pub fn add_i8_(&mut self, i8_: i8) { - self.fbb_.push_slot::(TypeAliases::VT_I8_, i8_, 0); - } - - #[inline] - pub fn add_u8_(&mut self, u8_: u8) { - self.fbb_.push_slot::(TypeAliases::VT_U8_, u8_, 0); - } - - #[inline] - pub fn add_i16_(&mut self, i16_: i16) { - self.fbb_.push_slot::(TypeAliases::VT_I16_, i16_, 0); - } - - #[inline] - pub fn add_u16_(&mut self, u16_: u16) { - self.fbb_.push_slot::(TypeAliases::VT_U16_, u16_, 0); - } - - #[inline] - pub fn add_i32_(&mut self, i32_: i32) { - self.fbb_.push_slot::(TypeAliases::VT_I32_, i32_, 0); - } - - #[inline] - pub fn add_u32_(&mut self, u32_: u32) { - self.fbb_.push_slot::(TypeAliases::VT_U32_, u32_, 0); - } - - #[inline] - pub fn add_i64_(&mut self, i64_: i64) { - self.fbb_.push_slot::(TypeAliases::VT_I64_, i64_, 0); - } - - #[inline] - pub fn add_u64_(&mut self, u64_: u64) { - self.fbb_.push_slot::(TypeAliases::VT_U64_, u64_, 0); - } - - #[inline] - pub fn add_f32_(&mut self, f32_: f32) { - self.fbb_.push_slot::(TypeAliases::VT_F32_, f32_, 0.0); - } - - #[inline] - pub fn add_f64_(&mut self, f64_: f64) { - self.fbb_.push_slot::(TypeAliases::VT_F64_, f64_, 0.0); - } - - #[inline] - pub fn add_v8(&mut self, v8: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , i8>>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(TypeAliases::VT_V8, v8); - } - - #[inline] - pub fn add_vf64(&mut self, vf64: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , f64>>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(TypeAliases::VT_VF64, vf64); - } - - #[inline] - pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> TypeAliasesBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - TypeAliasesBuilder { - fbb_: _fbb, - start_: start, - } - } - - #[inline] - pub fn finish(self) -> ::flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - ::flatbuffers::WIPOffset::new(o.value()) + #[inline] + pub fn add_i8_(&mut self, i8_: i8) { + self.fbb_.push_slot::(TypeAliases::VT_I8_, i8_, 0); + } + #[inline] + pub fn add_u8_(&mut self, u8_: u8) { + self.fbb_.push_slot::(TypeAliases::VT_U8_, u8_, 0); + } + #[inline] + pub fn add_i16_(&mut self, i16_: i16) { + self.fbb_.push_slot::(TypeAliases::VT_I16_, i16_, 0); + } + #[inline] + pub fn add_u16_(&mut self, u16_: u16) { + self.fbb_.push_slot::(TypeAliases::VT_U16_, u16_, 0); + } + #[inline] + pub fn add_i32_(&mut self, i32_: i32) { + self.fbb_.push_slot::(TypeAliases::VT_I32_, i32_, 0); + } + #[inline] + pub fn add_u32_(&mut self, u32_: u32) { + self.fbb_.push_slot::(TypeAliases::VT_U32_, u32_, 0); + } + #[inline] + pub fn add_i64_(&mut self, i64_: i64) { + self.fbb_.push_slot::(TypeAliases::VT_I64_, i64_, 0); + } + #[inline] + pub fn add_u64_(&mut self, u64_: u64) { + self.fbb_.push_slot::(TypeAliases::VT_U64_, u64_, 0); + } + #[inline] + pub fn add_f32_(&mut self, f32_: f32) { + self.fbb_.push_slot::(TypeAliases::VT_F32_, f32_, 0.0); + } + #[inline] + pub fn add_f64_(&mut self, f64_: f64) { + self.fbb_.push_slot::(TypeAliases::VT_F64_, f64_, 0.0); + } + #[inline] + pub fn add_v8(&mut self, v8: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , i8>>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(TypeAliases::VT_V8, v8); + } + #[inline] + pub fn add_vf64(&mut self, vf64: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , f64>>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(TypeAliases::VT_VF64, vf64); + } + #[inline] + pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> TypeAliasesBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + TypeAliasesBuilder { + fbb_: _fbb, + start_: start, } + } + #[inline] + pub fn finish(self) -> ::flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + ::flatbuffers::WIPOffset::new(o.value()) + } } impl ::core::fmt::Debug for TypeAliases<'_> { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - let mut ds = f.debug_struct("TypeAliases"); - ds.field("i8_", &self.i8_()); - ds.field("u8_", &self.u8_()); - ds.field("i16_", &self.i16_()); - ds.field("u16_", &self.u16_()); - ds.field("i32_", &self.i32_()); - ds.field("u32_", &self.u32_()); - ds.field("i64_", &self.i64_()); - ds.field("u64_", &self.u64_()); - ds.field("f32_", &self.f32_()); - ds.field("f64_", &self.f64_()); - ds.field("v8", &self.v8()); - ds.field("vf64", &self.vf64()); - ds.finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + let mut ds = f.debug_struct("TypeAliases"); + ds.field("i8_", &self.i8_()); + ds.field("u8_", &self.u8_()); + ds.field("i16_", &self.i16_()); + ds.field("u16_", &self.u16_()); + ds.field("i32_", &self.i32_()); + ds.field("u32_", &self.u32_()); + ds.field("i64_", &self.i64_()); + ds.field("u64_", &self.u64_()); + ds.field("f32_", &self.f32_()); + ds.field("f64_", &self.f64_()); + ds.field("v8", &self.v8()); + ds.field("vf64", &self.vf64()); + ds.finish() + } } - #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub struct TypeAliasesT { - pub i8_: i8, - pub u8_: u8, - pub i16_: i16, - pub u16_: u16, - pub i32_: i32, - pub u32_: u32, - pub i64_: i64, - pub u64_: u64, - pub f32_: f32, - pub f64_: f64, - pub v8: Option>, - pub vf64: Option>, + pub i8_: i8, + pub u8_: u8, + pub i16_: i16, + pub u16_: u16, + pub i32_: i32, + pub u32_: u32, + pub i64_: i64, + pub u64_: u64, + pub f32_: f32, + pub f64_: f64, + pub v8: Option>, + pub vf64: Option>, } - impl Default for TypeAliasesT { - fn default() -> Self { - Self { - i8_: 0, - u8_: 0, - i16_: 0, - u16_: 0, - i32_: 0, - u32_: 0, - i64_: 0, - u64_: 0, - f32_: 0.0, - f64_: 0.0, - v8: None, - vf64: None, - } + fn default() -> Self { + Self { + i8_: 0, + u8_: 0, + i16_: 0, + u16_: 0, + i32_: 0, + u32_: 0, + i64_: 0, + u64_: 0, + f32_: 0.0, + f64_: 0.0, + v8: None, + vf64: None, } + } } - impl TypeAliasesT { - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( - &self, - _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> - ) -> ::flatbuffers::WIPOffset> { - let i8_ = self.i8_; - let u8_ = self.u8_; - let i16_ = self.i16_; - let u16_ = self.u16_; - let i32_ = self.i32_; - let u32_ = self.u32_; - let i64_ = self.i64_; - let u64_ = self.u64_; - let f32_ = self.f32_; - let f64_ = self.f64_; - let v8 = self.v8.as_ref().map(|x|{ - _fbb.create_vector(x) - }); - let vf64 = self.vf64.as_ref().map(|x|{ - _fbb.create_vector(x) - }); - TypeAliases::create(_fbb, &TypeAliasesArgs{ - i8_, - u8_, - i16_, - u16_, - i32_, - u32_, - i64_, - u64_, - f32_, - f64_, - v8, - vf64, - }) - } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> + ) -> ::flatbuffers::WIPOffset> { + let i8_ = self.i8_; + let u8_ = self.u8_; + let i16_ = self.i16_; + let u16_ = self.u16_; + let i32_ = self.i32_; + let u32_ = self.u32_; + let i64_ = self.i64_; + let u64_ = self.u64_; + let f32_ = self.f32_; + let f64_ = self.f64_; + let v8 = self.v8.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + let vf64 = self.vf64.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + TypeAliases::create(_fbb, &TypeAliasesArgs{ + i8_, + u8_, + i16_, + u16_, + i32_, + u32_, + i64_, + u64_, + f32_, + f64_, + v8, + vf64, + }) + } } diff --git a/tests/monster_test/my_game/example/vec_3_generated.rs b/tests/monster_test/my_game/example/vec_3_generated.rs index 53e7677ea..2b2872bc6 100644 --- a/tests/monster_test/my_game/example/vec_3_generated.rs +++ b/tests/monster_test/my_game/example/vec_3_generated.rs @@ -2,60 +2,50 @@ // @generated extern crate alloc; use super::*; - // struct Vec3, aligned to 8 #[repr(transparent)] #[derive(Clone, Copy, PartialEq)] pub struct Vec3(pub [u8; 32]); - -impl Default for Vec3 { - fn default() -> Self { - Self([0; 32]) - } +impl Default for Vec3 { + fn default() -> Self { + Self([0; 32]) + } } - impl ::core::fmt::Debug for Vec3 { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - f.debug_struct("Vec3") - .field("x", &self.x()) - .field("y", &self.y()) - .field("z", &self.z()) - .field("test1", &self.test1()) - .field("test2", &self.test2()) - .field("test3", &self.test3()) - .finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + f.debug_struct("Vec3") + .field("x", &self.x()) + .field("y", &self.y()) + .field("z", &self.z()) + .field("test1", &self.test1()) + .field("test2", &self.test2()) + .field("test3", &self.test3()) + .finish() + } } impl ::flatbuffers::SimpleToVerifyInSlice for Vec3 {} - impl<'a> ::flatbuffers::Follow<'a> for Vec3 { - type Inner = &'a Vec3; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - unsafe { <&'a Vec3>::follow(buf, loc) } - } + type Inner = &'a Vec3; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { <&'a Vec3>::follow(buf, loc) } + } } - impl<'a> ::flatbuffers::Follow<'a> for &'a Vec3 { - type Inner = &'a Vec3; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - unsafe { ::flatbuffers::follow_cast_ref::(buf, loc) } - } + type Inner = &'a Vec3; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { ::flatbuffers::follow_cast_ref::(buf, loc) } + } } - impl<'b> ::flatbuffers::Push for Vec3 { type Output = Vec3; - #[inline] unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { let src = unsafe { ::core::slice::from_raw_parts(self as *const Vec3 as *const u8, ::size()) }; dst.copy_from_slice(src); } - #[inline] fn alignment() -> ::flatbuffers::PushAlignment { ::flatbuffers::PushAlignment::new(8) @@ -63,238 +53,226 @@ impl<'b> ::flatbuffers::Push for Vec3 { } impl<'a> ::flatbuffers::Verifiable for Vec3 { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.in_buffer::(pos) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.in_buffer::(pos) + } } impl<'a> Vec3 { - #[allow(clippy::too_many_arguments)] - pub fn new( - x: f32, - y: f32, - z: f32, - test1: f64, - test2: Color, - test3: &Test, - ) -> Self { - let mut s = Self([0; 32]); - s.set_x(x); - s.set_y(y); - s.set_z(z); - s.set_test1(test1); - s.set_test2(test2); - s.set_test3(test3); - s - } + #[allow(clippy::too_many_arguments)] + pub fn new( + x: f32, + y: f32, + z: f32, + test1: f64, + test2: Color, + test3: &Test, + ) -> Self { + let mut s = Self([0; 32]); + s.set_x(x); + s.set_y(y); + s.set_z(z); + s.set_test1(test1); + s.set_test2(test2); + s.set_test3(test3); + s + } - pub const fn get_fully_qualified_name() -> &'static str { - "MyGame.Example.Vec3" - } + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Example.Vec3" + } - pub fn x(&self) -> f32 { - let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - ::flatbuffers::EndianScalar::from_little_endian(unsafe { - ::core::ptr::copy_nonoverlapping( - self.0[0..].as_ptr(), - mem.as_mut_ptr() as *mut u8, - ::core::mem::size_of::<::Scalar>(), - ); - mem.assume_init() - }) - } + pub fn x(&self) -> f32 { + let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + ::flatbuffers::EndianScalar::from_little_endian(unsafe { + ::core::ptr::copy_nonoverlapping( + self.0[0..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + ::core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } - pub fn set_x(&mut self, x: f32) { - let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - unsafe { - ::core::ptr::copy_nonoverlapping( - &x_le as *const _ as *const u8, - self.0[0..].as_mut_ptr(), - ::core::mem::size_of::<::Scalar>(), - ); - } + pub fn set_x(&mut self, x: f32) { + let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + ::core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[0..].as_mut_ptr(), + ::core::mem::size_of::<::Scalar>(), + ); } + } - pub fn y(&self) -> f32 { - let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - ::flatbuffers::EndianScalar::from_little_endian(unsafe { - ::core::ptr::copy_nonoverlapping( - self.0[4..].as_ptr(), - mem.as_mut_ptr() as *mut u8, - ::core::mem::size_of::<::Scalar>(), - ); - mem.assume_init() - }) - } + pub fn y(&self) -> f32 { + let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + ::flatbuffers::EndianScalar::from_little_endian(unsafe { + ::core::ptr::copy_nonoverlapping( + self.0[4..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + ::core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } - pub fn set_y(&mut self, x: f32) { - let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - unsafe { - ::core::ptr::copy_nonoverlapping( - &x_le as *const _ as *const u8, - self.0[4..].as_mut_ptr(), - ::core::mem::size_of::<::Scalar>(), - ); - } + pub fn set_y(&mut self, x: f32) { + let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + ::core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[4..].as_mut_ptr(), + ::core::mem::size_of::<::Scalar>(), + ); } + } - pub fn z(&self) -> f32 { - let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - ::flatbuffers::EndianScalar::from_little_endian(unsafe { - ::core::ptr::copy_nonoverlapping( - self.0[8..].as_ptr(), - mem.as_mut_ptr() as *mut u8, - ::core::mem::size_of::<::Scalar>(), - ); - mem.assume_init() - }) - } + pub fn z(&self) -> f32 { + let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + ::flatbuffers::EndianScalar::from_little_endian(unsafe { + ::core::ptr::copy_nonoverlapping( + self.0[8..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + ::core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } - pub fn set_z(&mut self, x: f32) { - let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - unsafe { - ::core::ptr::copy_nonoverlapping( - &x_le as *const _ as *const u8, - self.0[8..].as_mut_ptr(), - ::core::mem::size_of::<::Scalar>(), - ); - } + pub fn set_z(&mut self, x: f32) { + let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + ::core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[8..].as_mut_ptr(), + ::core::mem::size_of::<::Scalar>(), + ); } + } - pub fn test1(&self) -> f64 { - let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - ::flatbuffers::EndianScalar::from_little_endian(unsafe { - ::core::ptr::copy_nonoverlapping( - self.0[16..].as_ptr(), - mem.as_mut_ptr() as *mut u8, - ::core::mem::size_of::<::Scalar>(), - ); - mem.assume_init() - }) - } + pub fn test1(&self) -> f64 { + let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + ::flatbuffers::EndianScalar::from_little_endian(unsafe { + ::core::ptr::copy_nonoverlapping( + self.0[16..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + ::core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } - pub fn set_test1(&mut self, x: f64) { - let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - unsafe { - ::core::ptr::copy_nonoverlapping( - &x_le as *const _ as *const u8, - self.0[16..].as_mut_ptr(), - ::core::mem::size_of::<::Scalar>(), - ); - } + pub fn set_test1(&mut self, x: f64) { + let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + ::core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[16..].as_mut_ptr(), + ::core::mem::size_of::<::Scalar>(), + ); } + } - pub fn test2(&self) -> Color { - let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - ::flatbuffers::EndianScalar::from_little_endian(unsafe { - ::core::ptr::copy_nonoverlapping( - self.0[24..].as_ptr(), - mem.as_mut_ptr() as *mut u8, - ::core::mem::size_of::<::Scalar>(), - ); - mem.assume_init() - }) - } + pub fn test2(&self) -> Color { + let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + ::flatbuffers::EndianScalar::from_little_endian(unsafe { + ::core::ptr::copy_nonoverlapping( + self.0[24..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + ::core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } - pub fn set_test2(&mut self, x: Color) { - let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - unsafe { - ::core::ptr::copy_nonoverlapping( - &x_le as *const _ as *const u8, - self.0[24..].as_mut_ptr(), - ::core::mem::size_of::<::Scalar>(), - ); - } + pub fn set_test2(&mut self, x: Color) { + let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + ::core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[24..].as_mut_ptr(), + ::core::mem::size_of::<::Scalar>(), + ); } + } - pub fn test3(&self) -> &Test { - // Safety: - // Created from a valid Table for this object - // Which contains a valid struct in this slot - unsafe { &*(self.0[26..].as_ptr() as *const Test) } - } + pub fn test3(&self) -> &Test { + // Safety: + // Created from a valid Table for this object + // Which contains a valid struct in this slot + unsafe { &*(self.0[26..].as_ptr() as *const Test) } + } - #[allow(clippy::identity_op)] - pub fn set_test3(&mut self, x: &Test) { - self.0[26..26 + 4].copy_from_slice(&x.0) - } + #[allow(clippy::identity_op)] + pub fn set_test3(&mut self, x: &Test) { + self.0[26..26 + 4].copy_from_slice(&x.0) + } - pub fn unpack(&self) -> Vec3T { - Vec3T { - x: self.x(), - y: self.y(), - z: self.z(), - test1: self.test1(), - test2: self.test2(), - test3: self.test3().unpack(), - } + pub fn unpack(&self) -> Vec3T { + Vec3T { + x: self.x(), + y: self.y(), + z: self.z(), + test1: self.test1(), + test2: self.test2(), + test3: self.test3().unpack(), } + } } -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Default)] pub struct Vec3T { - pub x: f32, - pub y: f32, - pub z: f32, - pub test1: f64, - pub test2: Color, - pub test3: TestT, + pub x: f32, + pub y: f32, + pub z: f32, + pub test1: f64, + pub test2: Color, + pub test3: TestT, } -impl Default for Vec3T { - fn default() -> Self { - Self { - x: 0.0, - y: 0.0, - z: 0.0, - test1: 0.0, - test2: Default::default(), - test3: Default::default(), - } - } +impl Vec3T { + pub fn pack(&self) -> Vec3 { + Vec3::new( + self.x, + self.y, + self.z, + self.test1, + self.test2, + &self.test3.pack(), + ) + } } -impl Vec3T { - pub fn pack(&self) -> Vec3 { - Vec3::new( - self.x, - self.y, - self.z, - self.test1, - self.test2, - &self.test3.pack(), - ) - } -} diff --git a/tests/monster_test/my_game/example_2/monster_generated.rs b/tests/monster_test/my_game/example_2/monster_generated.rs index c908f0a2b..7e2409ff5 100644 --- a/tests/monster_test/my_game/example_2/monster_generated.rs +++ b/tests/monster_test/my_game/example_2/monster_generated.rs @@ -2,117 +2,108 @@ // @generated extern crate alloc; use super::*; - pub enum MonsterOffset {} - #[derive(Copy, Clone, PartialEq)] + pub struct Monster<'a> { - pub _tab: ::flatbuffers::Table<'a>, + pub _tab: ::flatbuffers::Table<'a>, } impl<'a> ::flatbuffers::Follow<'a> for Monster<'a> { - type Inner = Monster<'a>; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } - } + type Inner = Monster<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } + } } impl<'a> Monster<'a> { - pub const fn get_fully_qualified_name() -> &'static str { - "MyGame.Example2.Monster" - } - #[inline] - pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { - Monster { _tab: table } - } + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Example2.Monster" + } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, - _args: &'args MonsterArgs - ) -> ::flatbuffers::WIPOffset> { - let mut builder = MonsterBuilder::new(_fbb); - builder.finish() - } + #[inline] + pub unsafe 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, A: ::flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, + _args: &'args MonsterArgs + ) -> ::flatbuffers::WIPOffset> { + let mut builder = MonsterBuilder::new(_fbb); + builder.finish() + } - pub fn unpack(&self) -> MonsterT { - MonsterT { - } + pub fn unpack(&self) -> MonsterT { + MonsterT { } + } } impl ::flatbuffers::Verifiable for Monster<'_> { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.visit_table(pos)? - .finish(); - Ok(()) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.visit_table(pos)? + .finish(); + Ok(()) + } } - pub struct MonsterArgs { } - impl<'a> Default for MonsterArgs { - #[inline] - fn default() -> Self { - MonsterArgs { - } + #[inline] + fn default() -> Self { + MonsterArgs { } + } } pub struct MonsterBuilder<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> { - fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, + fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, + start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, } - impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> MonsterBuilder<'a, 'b, A> { - #[inline] - pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> MonsterBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - MonsterBuilder { - fbb_: _fbb, - start_: start, - } - } - - #[inline] - pub fn finish(self) -> ::flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - ::flatbuffers::WIPOffset::new(o.value()) + #[inline] + pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> MonsterBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + MonsterBuilder { + fbb_: _fbb, + start_: start, } + } + #[inline] + pub fn finish(self) -> ::flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + ::flatbuffers::WIPOffset::new(o.value()) + } } impl ::core::fmt::Debug for Monster<'_> { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - let mut ds = f.debug_struct("Monster"); - ds.finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + let mut ds = f.debug_struct("Monster"); + ds.finish() + } } - #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub struct MonsterT { } - impl Default for MonsterT { - fn default() -> Self { - Self { - } + fn default() -> Self { + Self { } + } } - impl MonsterT { - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( - &self, - _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> - ) -> ::flatbuffers::WIPOffset> { - Monster::create(_fbb, &MonsterArgs{ - }) - } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> + ) -> ::flatbuffers::WIPOffset> { + Monster::create(_fbb, &MonsterArgs{ + }) + } } diff --git a/tests/monster_test/my_game/in_parent_namespace_generated.rs b/tests/monster_test/my_game/in_parent_namespace_generated.rs index 72c1ed530..7bcb4be7f 100644 --- a/tests/monster_test/my_game/in_parent_namespace_generated.rs +++ b/tests/monster_test/my_game/in_parent_namespace_generated.rs @@ -2,117 +2,108 @@ // @generated extern crate alloc; use super::*; - pub enum InParentNamespaceOffset {} - #[derive(Copy, Clone, PartialEq)] + pub struct InParentNamespace<'a> { - pub _tab: ::flatbuffers::Table<'a>, + pub _tab: ::flatbuffers::Table<'a>, } impl<'a> ::flatbuffers::Follow<'a> for InParentNamespace<'a> { - type Inner = InParentNamespace<'a>; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } - } + type Inner = InParentNamespace<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } + } } impl<'a> InParentNamespace<'a> { - pub const fn get_fully_qualified_name() -> &'static str { - "MyGame.InParentNamespace" - } - #[inline] - pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { - InParentNamespace { _tab: table } - } + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.InParentNamespace" + } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, - _args: &'args InParentNamespaceArgs - ) -> ::flatbuffers::WIPOffset> { - let mut builder = InParentNamespaceBuilder::new(_fbb); - builder.finish() - } + #[inline] + pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { + InParentNamespace { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, + _args: &'args InParentNamespaceArgs + ) -> ::flatbuffers::WIPOffset> { + let mut builder = InParentNamespaceBuilder::new(_fbb); + builder.finish() + } - pub fn unpack(&self) -> InParentNamespaceT { - InParentNamespaceT { - } + pub fn unpack(&self) -> InParentNamespaceT { + InParentNamespaceT { } + } } impl ::flatbuffers::Verifiable for InParentNamespace<'_> { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.visit_table(pos)? - .finish(); - Ok(()) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.visit_table(pos)? + .finish(); + Ok(()) + } } - pub struct InParentNamespaceArgs { } - impl<'a> Default for InParentNamespaceArgs { - #[inline] - fn default() -> Self { - InParentNamespaceArgs { - } + #[inline] + fn default() -> Self { + InParentNamespaceArgs { } + } } pub struct InParentNamespaceBuilder<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> { - fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, + fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, + start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, } - impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> InParentNamespaceBuilder<'a, 'b, A> { - #[inline] - pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> InParentNamespaceBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - InParentNamespaceBuilder { - fbb_: _fbb, - start_: start, - } - } - - #[inline] - pub fn finish(self) -> ::flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - ::flatbuffers::WIPOffset::new(o.value()) + #[inline] + pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> InParentNamespaceBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + InParentNamespaceBuilder { + fbb_: _fbb, + start_: start, } + } + #[inline] + pub fn finish(self) -> ::flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + ::flatbuffers::WIPOffset::new(o.value()) + } } impl ::core::fmt::Debug for InParentNamespace<'_> { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - let mut ds = f.debug_struct("InParentNamespace"); - ds.finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + let mut ds = f.debug_struct("InParentNamespace"); + ds.finish() + } } - #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub struct InParentNamespaceT { } - impl Default for InParentNamespaceT { - fn default() -> Self { - Self { - } + fn default() -> Self { + Self { } + } } - impl InParentNamespaceT { - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( - &self, - _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> - ) -> ::flatbuffers::WIPOffset> { - InParentNamespace::create(_fbb, &InParentNamespaceArgs{ - }) - } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> + ) -> ::flatbuffers::WIPOffset> { + InParentNamespace::create(_fbb, &InParentNamespaceArgs{ + }) + } } diff --git a/tests/monster_test/my_game/other_name_space/from_include_generated.rs b/tests/monster_test/my_game/other_name_space/from_include_generated.rs index ada294725..5eb9adc5e 100644 --- a/tests/monster_test/my_game/other_name_space/from_include_generated.rs +++ b/tests/monster_test/my_game/other_name_space/from_include_generated.rs @@ -2,65 +2,56 @@ // @generated extern crate alloc; use super::*; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] pub const ENUM_MIN_FROM_INCLUDE: i64 = 0; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] pub const ENUM_MAX_FROM_INCLUDE: i64 = 0; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] #[allow(non_camel_case_types)] pub const ENUM_VALUES_FROM_INCLUDE: [FromInclude; 1] = [ - FromInclude::IncludeVal, + FromInclude::IncludeVal, ]; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] #[repr(transparent)] pub struct FromInclude(pub i64); - #[allow(non_upper_case_globals)] impl FromInclude { - pub const IncludeVal: Self = Self(0); + pub const IncludeVal: Self = Self(0); - pub const ENUM_MIN: i64 = 0; - pub const ENUM_MAX: i64 = 0; - pub const ENUM_VALUES: &'static [Self] = &[ - Self::IncludeVal, - ]; - - /// Returns the variant's name or "" if unknown. - pub fn variant_name(self) -> Option<&'static str> { - match self { - Self::IncludeVal => Some("IncludeVal"), - _ => None, - } + pub const ENUM_MIN: i64 = 0; + pub const ENUM_MAX: i64 = 0; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::IncludeVal, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::IncludeVal => Some("IncludeVal"), + _ => None, } + } } - impl ::core::fmt::Debug for FromInclude { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - if let Some(name) = self.variant_name() { - f.write_str(name) - } else { - f.write_fmt(format_args!("", self.0)) - } + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) } + } } - impl<'a> ::flatbuffers::Follow<'a> for FromInclude { - type Inner = Self; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; - Self(b) - } + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; + Self(b) + } } impl ::flatbuffers::Push for FromInclude { type Output = FromInclude; - #[inline] unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { unsafe { ::flatbuffers::emplace_scalar::(dst, self.0) }; @@ -68,28 +59,26 @@ impl ::flatbuffers::Push for FromInclude { } impl ::flatbuffers::EndianScalar for FromInclude { - type Scalar = i64; - - #[inline] - fn to_little_endian(self) -> i64 { - self.0.to_le() - } - - #[inline] - #[allow(clippy::wrong_self_convention)] - fn from_little_endian(v: i64) -> Self { - let b = i64::from_le(v); - Self(b) - } + type Scalar = i64; + #[inline] + fn to_little_endian(self) -> i64 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: i64) -> Self { + let b = i64::from_le(v); + Self(b) + } } impl<'a> ::flatbuffers::Verifiable for FromInclude { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - i64::run_verifier(v, pos) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + i64::run_verifier(v, pos) + } } impl ::flatbuffers::SimpleToVerifyInSlice for FromInclude {} diff --git a/tests/monster_test/my_game/other_name_space/table_b_generated.rs b/tests/monster_test/my_game/other_name_space/table_b_generated.rs index 5434e448a..19a3e66ba 100644 --- a/tests/monster_test/my_game/other_name_space/table_b_generated.rs +++ b/tests/monster_test/my_game/other_name_space/table_b_generated.rs @@ -2,147 +2,136 @@ // @generated extern crate alloc; use super::*; - pub enum TableBOffset {} - #[derive(Copy, Clone, PartialEq)] + pub struct TableB<'a> { - pub _tab: ::flatbuffers::Table<'a>, + pub _tab: ::flatbuffers::Table<'a>, } impl<'a> ::flatbuffers::Follow<'a> for TableB<'a> { - type Inner = TableB<'a>; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } - } + type Inner = TableB<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } + } } impl<'a> TableB<'a> { - pub const VT_A: ::flatbuffers::VOffsetT = 4; + pub const VT_A: ::flatbuffers::VOffsetT = 4; - pub const fn get_fully_qualified_name() -> &'static str { - "MyGame.OtherNameSpace.TableB" - } + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.OtherNameSpace.TableB" + } - #[inline] - pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { - TableB { _tab: table } - } + #[inline] + pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { + TableB { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args TableBArgs<'args> + ) -> ::flatbuffers::WIPOffset> { + let mut builder = TableBBuilder::new(_fbb); + if let Some(x) = args.a { builder.add_a(x); } + builder.finish() + } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args TableBArgs<'args> - ) -> ::flatbuffers::WIPOffset> { - let mut builder = TableBBuilder::new(_fbb); - if let Some(x) = args.a { builder.add_a(x); } - builder.finish() + pub fn unpack(&self) -> TableBT { + let a = self.a().map(|x| { + alloc::boxed::Box::new(x.unpack()) + }); + TableBT { + a, } + } - pub fn unpack(&self) -> TableBT { - let a = self.a().map(|x| { - alloc::boxed::Box::new(x.unpack()) - }); - TableBT { - a, - } - } - - #[inline] - pub fn a(&self) -> Option> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset>(TableB::VT_A, None)} - } + #[inline] + pub fn a(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset>(TableB::VT_A, None)} + } } impl ::flatbuffers::Verifiable for TableB<'_> { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.visit_table(pos)? - .visit_field::<::flatbuffers::ForwardsUOffset>("a", Self::VT_A, false)? - .finish(); - Ok(()) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.visit_table(pos)? + .visit_field::<::flatbuffers::ForwardsUOffset>("a", Self::VT_A, false)? + .finish(); + Ok(()) + } } - pub struct TableBArgs<'a> { pub a: Option<::flatbuffers::WIPOffset>>, } - impl<'a> Default for TableBArgs<'a> { - #[inline] - fn default() -> Self { - TableBArgs { - a: None, - } + #[inline] + fn default() -> Self { + TableBArgs { + a: None, } + } } pub struct TableBBuilder<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> { - fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, + fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, + start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, } - impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> TableBBuilder<'a, 'b, A> { - #[inline] - pub fn add_a(&mut self, a: ::flatbuffers::WIPOffset>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset>(TableB::VT_A, a); - } - - #[inline] - pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> TableBBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - TableBBuilder { - fbb_: _fbb, - start_: start, - } - } - - #[inline] - pub fn finish(self) -> ::flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - ::flatbuffers::WIPOffset::new(o.value()) + #[inline] + pub fn add_a(&mut self, a: ::flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset>(TableB::VT_A, a); + } + #[inline] + pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> TableBBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + TableBBuilder { + fbb_: _fbb, + start_: start, } + } + #[inline] + pub fn finish(self) -> ::flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + ::flatbuffers::WIPOffset::new(o.value()) + } } impl ::core::fmt::Debug for TableB<'_> { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - let mut ds = f.debug_struct("TableB"); - ds.field("a", &self.a()); - ds.finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + let mut ds = f.debug_struct("TableB"); + ds.field("a", &self.a()); + ds.finish() + } } - #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub struct TableBT { - pub a: Option>, + pub a: Option>, } - impl Default for TableBT { - fn default() -> Self { - Self { - a: None, - } + fn default() -> Self { + Self { + a: None, } + } } - impl TableBT { - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( - &self, - _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> - ) -> ::flatbuffers::WIPOffset> { - let a = self.a.as_ref().map(|x|{ - x.pack(_fbb) - }); - TableB::create(_fbb, &TableBArgs{ - a, - }) - } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> + ) -> ::flatbuffers::WIPOffset> { + let a = self.a.as_ref().map(|x|{ + x.pack(_fbb) + }); + TableB::create(_fbb, &TableBArgs{ + a, + }) + } } diff --git a/tests/monster_test/my_game/other_name_space/unused_generated.rs b/tests/monster_test/my_game/other_name_space/unused_generated.rs index d19375f17..b90fb8924 100644 --- a/tests/monster_test/my_game/other_name_space/unused_generated.rs +++ b/tests/monster_test/my_game/other_name_space/unused_generated.rs @@ -2,55 +2,45 @@ // @generated extern crate alloc; use super::*; - // struct Unused, aligned to 4 #[repr(transparent)] #[derive(Clone, Copy, PartialEq)] pub struct Unused(pub [u8; 4]); - -impl Default for Unused { - fn default() -> Self { - Self([0; 4]) - } +impl Default for Unused { + fn default() -> Self { + Self([0; 4]) + } } - impl ::core::fmt::Debug for Unused { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - f.debug_struct("Unused") - .field("a", &self.a()) - .finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + f.debug_struct("Unused") + .field("a", &self.a()) + .finish() + } } impl ::flatbuffers::SimpleToVerifyInSlice for Unused {} - impl<'a> ::flatbuffers::Follow<'a> for Unused { - type Inner = &'a Unused; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - unsafe { <&'a Unused>::follow(buf, loc) } - } + type Inner = &'a Unused; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { <&'a Unused>::follow(buf, loc) } + } } - impl<'a> ::flatbuffers::Follow<'a> for &'a Unused { - type Inner = &'a Unused; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - unsafe { ::flatbuffers::follow_cast_ref::(buf, loc) } - } + type Inner = &'a Unused; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { ::flatbuffers::follow_cast_ref::(buf, loc) } + } } - impl<'b> ::flatbuffers::Push for Unused { type Output = Unused; - #[inline] unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { let src = unsafe { ::core::slice::from_raw_parts(self as *const Unused as *const u8, ::size()) }; dst.copy_from_slice(src); } - #[inline] fn alignment() -> ::flatbuffers::PushAlignment { ::flatbuffers::PushAlignment::new(4) @@ -58,80 +48,73 @@ impl<'b> ::flatbuffers::Push for Unused { } impl<'a> ::flatbuffers::Verifiable for Unused { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.in_buffer::(pos) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.in_buffer::(pos) + } } impl<'a> Unused { - #[allow(clippy::too_many_arguments)] - pub fn new( - a: i32, - ) -> Self { - let mut s = Self([0; 4]); - s.set_a(a); - s - } + #[allow(clippy::too_many_arguments)] + pub fn new( + a: i32, + ) -> Self { + let mut s = Self([0; 4]); + s.set_a(a); + s + } - pub const fn get_fully_qualified_name() -> &'static str { - "MyGame.OtherNameSpace.Unused" - } + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.OtherNameSpace.Unused" + } - pub fn a(&self) -> i32 { - let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - ::flatbuffers::EndianScalar::from_little_endian(unsafe { - ::core::ptr::copy_nonoverlapping( - self.0[0..].as_ptr(), - mem.as_mut_ptr() as *mut u8, - ::core::mem::size_of::<::Scalar>(), - ); - mem.assume_init() - }) - } + pub fn a(&self) -> i32 { + let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + ::flatbuffers::EndianScalar::from_little_endian(unsafe { + ::core::ptr::copy_nonoverlapping( + self.0[0..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + ::core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } - pub fn set_a(&mut self, x: i32) { - let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - unsafe { - ::core::ptr::copy_nonoverlapping( - &x_le as *const _ as *const u8, - self.0[0..].as_mut_ptr(), - ::core::mem::size_of::<::Scalar>(), - ); - } + pub fn set_a(&mut self, x: i32) { + let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + ::core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[0..].as_mut_ptr(), + ::core::mem::size_of::<::Scalar>(), + ); } + } - pub fn unpack(&self) -> UnusedT { - UnusedT { - a: self.a(), - } + pub fn unpack(&self) -> UnusedT { + UnusedT { + a: self.a(), } + } } -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Default)] pub struct UnusedT { - pub a: i32, + pub a: i32, } -impl Default for UnusedT { - fn default() -> Self { - Self { - a: 0, - } - } +impl UnusedT { + pub fn pack(&self) -> Unused { + Unused::new( + self.a, + ) + } } -impl UnusedT { - pub fn pack(&self) -> Unused { - Unused::new( - self.a, - ) - } -} diff --git a/tests/monster_test/table_a_generated.rs b/tests/monster_test/table_a_generated.rs index 467c514a1..ca29250dc 100644 --- a/tests/monster_test/table_a_generated.rs +++ b/tests/monster_test/table_a_generated.rs @@ -2,147 +2,136 @@ // @generated extern crate alloc; use super::*; - pub enum TableAOffset {} - #[derive(Copy, Clone, PartialEq)] + pub struct TableA<'a> { - pub _tab: ::flatbuffers::Table<'a>, + pub _tab: ::flatbuffers::Table<'a>, } impl<'a> ::flatbuffers::Follow<'a> for TableA<'a> { - type Inner = TableA<'a>; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } - } + type Inner = TableA<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } + } } impl<'a> TableA<'a> { - pub const VT_B: ::flatbuffers::VOffsetT = 4; + pub const VT_B: ::flatbuffers::VOffsetT = 4; - pub const fn get_fully_qualified_name() -> &'static str { - "TableA" - } + pub const fn get_fully_qualified_name() -> &'static str { + "TableA" + } - #[inline] - pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { - TableA { _tab: table } - } + #[inline] + pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { + TableA { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args TableAArgs<'args> + ) -> ::flatbuffers::WIPOffset> { + let mut builder = TableABuilder::new(_fbb); + if let Some(x) = args.b { builder.add_b(x); } + builder.finish() + } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args TableAArgs<'args> - ) -> ::flatbuffers::WIPOffset> { - let mut builder = TableABuilder::new(_fbb); - if let Some(x) = args.b { builder.add_b(x); } - builder.finish() + pub fn unpack(&self) -> TableAT { + let b = self.b().map(|x| { + alloc::boxed::Box::new(x.unpack()) + }); + TableAT { + b, } + } - pub fn unpack(&self) -> TableAT { - let b = self.b().map(|x| { - alloc::boxed::Box::new(x.unpack()) - }); - TableAT { - b, - } - } - - #[inline] - pub fn b(&self) -> Option> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset>(TableA::VT_B, None)} - } + #[inline] + pub fn b(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset>(TableA::VT_B, None)} + } } impl ::flatbuffers::Verifiable for TableA<'_> { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.visit_table(pos)? - .visit_field::<::flatbuffers::ForwardsUOffset>("b", Self::VT_B, false)? - .finish(); - Ok(()) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.visit_table(pos)? + .visit_field::<::flatbuffers::ForwardsUOffset>("b", Self::VT_B, false)? + .finish(); + Ok(()) + } } - pub struct TableAArgs<'a> { pub b: Option<::flatbuffers::WIPOffset>>, } - impl<'a> Default for TableAArgs<'a> { - #[inline] - fn default() -> Self { - TableAArgs { - b: None, - } + #[inline] + fn default() -> Self { + TableAArgs { + b: None, } + } } pub struct TableABuilder<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> { - fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, + fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, + start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, } - impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> TableABuilder<'a, 'b, A> { - #[inline] - pub fn add_b(&mut self, b: ::flatbuffers::WIPOffset>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset>(TableA::VT_B, b); - } - - #[inline] - pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> TableABuilder<'a, 'b, A> { - let start = _fbb.start_table(); - TableABuilder { - fbb_: _fbb, - start_: start, - } - } - - #[inline] - pub fn finish(self) -> ::flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - ::flatbuffers::WIPOffset::new(o.value()) + #[inline] + pub fn add_b(&mut self, b: ::flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset>(TableA::VT_B, b); + } + #[inline] + pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> TableABuilder<'a, 'b, A> { + let start = _fbb.start_table(); + TableABuilder { + fbb_: _fbb, + start_: start, } + } + #[inline] + pub fn finish(self) -> ::flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + ::flatbuffers::WIPOffset::new(o.value()) + } } impl ::core::fmt::Debug for TableA<'_> { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - let mut ds = f.debug_struct("TableA"); - ds.field("b", &self.b()); - ds.finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + let mut ds = f.debug_struct("TableA"); + ds.field("b", &self.b()); + ds.finish() + } } - #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub struct TableAT { - pub b: Option>, + pub b: Option>, } - impl Default for TableAT { - fn default() -> Self { - Self { - b: None, - } + fn default() -> Self { + Self { + b: None, } + } } - impl TableAT { - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( - &self, - _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> - ) -> ::flatbuffers::WIPOffset> { - let b = self.b.as_ref().map(|x|{ - x.pack(_fbb) - }); - TableA::create(_fbb, &TableAArgs{ - b, - }) - } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> + ) -> ::flatbuffers::WIPOffset> { + let b = self.b.as_ref().map(|x|{ + x.pack(_fbb) + }); + TableA::create(_fbb, &TableAArgs{ + b, + }) + } } diff --git a/tests/monster_test_generated.h b/tests/monster_test_generated.h index cd57d512e..7c994e5c1 100644 --- a/tests/monster_test_generated.h +++ b/tests/monster_test_generated.h @@ -3237,10 +3237,10 @@ inline ::flatbuffers::Offset Monster::Pack(::flatbuffers::FlatBufferBui auto _test = _o->test.Pack(_fbb); auto _test4 = _o->test4.size() ? _fbb.CreateVectorOfStructs(_o->test4) : 0; auto _testarrayofstring = _o->testarrayofstring.size() ? _fbb.CreateVectorOfStrings(_o->testarrayofstring) : 0; - auto _testarrayoftables = _o->testarrayoftables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->testarrayoftables.size(), [](size_t i, _VectorArgs *__va) { return MyGame::Example::CreateMonster(*__va->__fbb, __va->__o->testarrayoftables[i].get(), __va->__rehasher); }, &_va ) : 0; - auto _enemy = _o->enemy ? MyGame::Example::CreateMonster(_fbb, _o->enemy.get(), _rehasher) : 0; + auto _testarrayoftables = _o->testarrayoftables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->testarrayoftables.size(), [](size_t i, _VectorArgs *__va) { return CreateMonster(*__va->__fbb, __va->__o->testarrayoftables[i].get(), __va->__rehasher); }, &_va ) : 0; + auto _enemy = _o->enemy ? CreateMonster(_fbb, _o->enemy.get(), _rehasher) : 0; auto _testnestedflatbuffer = _o->testnestedflatbuffer.size() ? _fbb.CreateVector(_o->testnestedflatbuffer) : 0; - auto _testempty = _o->testempty ? MyGame::Example::CreateStat(_fbb, _o->testempty.get(), _rehasher) : 0; + auto _testempty = _o->testempty ? CreateStat(_fbb, _o->testempty.get(), _rehasher) : 0; auto _testbool = _o->testbool; auto _testhashs32_fnv1 = _o->testhashs32_fnv1; auto _testhashu32_fnv1 = _o->testhashu32_fnv1; @@ -3260,11 +3260,11 @@ inline ::flatbuffers::Offset Monster::Pack(::flatbuffers::FlatBufferBui auto _test5 = _o->test5.size() ? _fbb.CreateVectorOfStructs(_o->test5) : 0; auto _vector_of_longs = _o->vector_of_longs.size() ? _fbb.CreateVector(_o->vector_of_longs) : 0; auto _vector_of_doubles = _o->vector_of_doubles.size() ? _fbb.CreateVector(_o->vector_of_doubles) : 0; - auto _parent_namespace_test = _o->parent_namespace_test ? MyGame::CreateInParentNamespace(_fbb, _o->parent_namespace_test.get(), _rehasher) : 0; - auto _vector_of_referrables = _o->vector_of_referrables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->vector_of_referrables.size(), [](size_t i, _VectorArgs *__va) { return MyGame::Example::CreateReferrable(*__va->__fbb, __va->__o->vector_of_referrables[i].get(), __va->__rehasher); }, &_va ) : 0; + auto _parent_namespace_test = _o->parent_namespace_test ? CreateInParentNamespace(_fbb, _o->parent_namespace_test.get(), _rehasher) : 0; + auto _vector_of_referrables = _o->vector_of_referrables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->vector_of_referrables.size(), [](size_t i, _VectorArgs *__va) { return CreateReferrable(*__va->__fbb, __va->__o->vector_of_referrables[i].get(), __va->__rehasher); }, &_va ) : 0; auto _single_weak_reference = _rehasher ? static_cast((*_rehasher)(_o->single_weak_reference)) : 0; auto _vector_of_weak_references = _o->vector_of_weak_references.size() ? _fbb.CreateVector(_o->vector_of_weak_references.size(), [](size_t i, _VectorArgs *__va) { return __va->__rehasher ? static_cast((*__va->__rehasher)(__va->__o->vector_of_weak_references[i])) : 0; }, &_va ) : 0; - auto _vector_of_strong_referrables = _o->vector_of_strong_referrables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->vector_of_strong_referrables.size(), [](size_t i, _VectorArgs *__va) { return MyGame::Example::CreateReferrable(*__va->__fbb, __va->__o->vector_of_strong_referrables[i].get(), __va->__rehasher); }, &_va ) : 0; + auto _vector_of_strong_referrables = _o->vector_of_strong_referrables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->vector_of_strong_referrables.size(), [](size_t i, _VectorArgs *__va) { return CreateReferrable(*__va->__fbb, __va->__o->vector_of_strong_referrables[i].get(), __va->__rehasher); }, &_va ) : 0; auto _co_owning_reference = _rehasher ? static_cast((*_rehasher)(_o->co_owning_reference)) : 0; auto _vector_of_co_owning_references = _o->vector_of_co_owning_references.size() ? _fbb.CreateVector(_o->vector_of_co_owning_references.size(), [](size_t i, _VectorArgs *__va) { return __va->__rehasher ? static_cast((*__va->__rehasher)(__va->__o->vector_of_co_owning_references[i].get())) : 0; }, &_va ) : 0; auto _non_owning_reference = _rehasher ? static_cast((*_rehasher)(_o->non_owning_reference)) : 0; @@ -3276,7 +3276,7 @@ inline ::flatbuffers::Offset Monster::Pack(::flatbuffers::FlatBufferBui auto _vector_of_enums = _o->vector_of_enums.size() ? _fbb.CreateVectorScalarCast(::flatbuffers::data(_o->vector_of_enums), _o->vector_of_enums.size()) : 0; auto _signed_enum = _o->signed_enum; auto _testrequirednestedflatbuffer = _o->testrequirednestedflatbuffer.size() ? _fbb.CreateVector(_o->testrequirednestedflatbuffer) : 0; - auto _scalar_key_sorted_tables = _o->scalar_key_sorted_tables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->scalar_key_sorted_tables.size(), [](size_t i, _VectorArgs *__va) { return MyGame::Example::CreateStat(*__va->__fbb, __va->__o->scalar_key_sorted_tables[i].get(), __va->__rehasher); }, &_va ) : 0; + auto _scalar_key_sorted_tables = _o->scalar_key_sorted_tables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->scalar_key_sorted_tables.size(), [](size_t i, _VectorArgs *__va) { return CreateStat(*__va->__fbb, __va->__o->scalar_key_sorted_tables[i].get(), __va->__rehasher); }, &_va ) : 0; auto _native_inline = &_o->native_inline; auto _long_enum_non_enum_default = _o->long_enum_non_enum_default; auto _long_enum_normal_default = _o->long_enum_normal_default; diff --git a/tests/monster_test_serialize/mod.rs b/tests/monster_test_serialize/mod.rs index 27af0f287..7f1fab136 100644 --- a/tests/monster_test_serialize/mod.rs +++ b/tests/monster_test_serialize/mod.rs @@ -1,58 +1,58 @@ // Automatically generated by the Flatbuffers compiler. Do not modify. // @generated pub mod my_game { + use super::*; + pub mod example { use super::*; - pub mod example { - use super::*; - mod color_generated; - pub use self::color_generated::*; - mod race_generated; - pub use self::race_generated::*; - mod long_enum_generated; - pub use self::long_enum_generated::*; - mod any_generated; - pub use self::any_generated::*; - mod any_unique_aliases_generated; - pub use self::any_unique_aliases_generated::*; - mod any_ambiguous_aliases_generated; - pub use self::any_ambiguous_aliases_generated::*; - mod test_generated; - pub use self::test_generated::*; - mod test_simple_table_with_enum_generated; - pub use self::test_simple_table_with_enum_generated::*; - mod vec_3_generated; - pub use self::vec_3_generated::*; - mod ability_generated; - pub use self::ability_generated::*; - mod struct_of_structs_generated; - pub use self::struct_of_structs_generated::*; - mod struct_of_structs_of_structs_generated; - pub use self::struct_of_structs_of_structs_generated::*; - mod stat_generated; - pub use self::stat_generated::*; - mod referrable_generated; - pub use self::referrable_generated::*; - mod monster_generated; - pub use self::monster_generated::*; - mod type_aliases_generated; - pub use self::type_aliases_generated::*; - } // example - pub mod example_2 { - use super::*; - mod monster_generated; - pub use self::monster_generated::*; - } // example_2 - pub mod other_name_space { - use super::*; - mod from_include_generated; - pub use self::from_include_generated::*; - mod unused_generated; - pub use self::unused_generated::*; - mod table_b_generated; - pub use self::table_b_generated::*; - } // other_name_space - mod in_parent_namespace_generated; - pub use self::in_parent_namespace_generated::*; + mod color_generated; + pub use self::color_generated::*; + mod race_generated; + pub use self::race_generated::*; + mod long_enum_generated; + pub use self::long_enum_generated::*; + mod any_generated; + pub use self::any_generated::*; + mod any_unique_aliases_generated; + pub use self::any_unique_aliases_generated::*; + mod any_ambiguous_aliases_generated; + pub use self::any_ambiguous_aliases_generated::*; + mod test_generated; + pub use self::test_generated::*; + mod test_simple_table_with_enum_generated; + pub use self::test_simple_table_with_enum_generated::*; + mod vec_3_generated; + pub use self::vec_3_generated::*; + mod ability_generated; + pub use self::ability_generated::*; + mod struct_of_structs_generated; + pub use self::struct_of_structs_generated::*; + mod struct_of_structs_of_structs_generated; + pub use self::struct_of_structs_of_structs_generated::*; + mod stat_generated; + pub use self::stat_generated::*; + mod referrable_generated; + pub use self::referrable_generated::*; + mod monster_generated; + pub use self::monster_generated::*; + mod type_aliases_generated; + pub use self::type_aliases_generated::*; + } // example + pub mod example_2 { + use super::*; + mod monster_generated; + pub use self::monster_generated::*; + } // example_2 + pub mod other_name_space { + use super::*; + mod from_include_generated; + pub use self::from_include_generated::*; + mod unused_generated; + pub use self::unused_generated::*; + mod table_b_generated; + pub use self::table_b_generated::*; + } // other_name_space + mod in_parent_namespace_generated; + pub use self::in_parent_namespace_generated::*; } // my_game mod table_a_generated; pub use self::table_a_generated::*; diff --git a/tests/monster_test_serialize/my_game/example/ability_generated.rs b/tests/monster_test_serialize/my_game/example/ability_generated.rs index aba446c6d..eb9846058 100644 --- a/tests/monster_test_serialize/my_game/example/ability_generated.rs +++ b/tests/monster_test_serialize/my_game/example/ability_generated.rs @@ -4,56 +4,46 @@ extern crate alloc; extern crate serde; use self::serde::ser::{Serialize, Serializer, SerializeStruct}; use super::*; - // struct Ability, aligned to 4 #[repr(transparent)] #[derive(Clone, Copy, PartialEq)] pub struct Ability(pub [u8; 8]); - -impl Default for Ability { - fn default() -> Self { - Self([0; 8]) - } +impl Default for Ability { + fn default() -> Self { + Self([0; 8]) + } } - impl ::core::fmt::Debug for Ability { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - f.debug_struct("Ability") - .field("id", &self.id()) - .field("distance", &self.distance()) - .finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + f.debug_struct("Ability") + .field("id", &self.id()) + .field("distance", &self.distance()) + .finish() + } } impl ::flatbuffers::SimpleToVerifyInSlice for Ability {} - impl<'a> ::flatbuffers::Follow<'a> for Ability { - type Inner = &'a Ability; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - unsafe { <&'a Ability>::follow(buf, loc) } - } + type Inner = &'a Ability; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { <&'a Ability>::follow(buf, loc) } + } } - impl<'a> ::flatbuffers::Follow<'a> for &'a Ability { - type Inner = &'a Ability; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - unsafe { ::flatbuffers::follow_cast_ref::(buf, loc) } - } + type Inner = &'a Ability; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { ::flatbuffers::follow_cast_ref::(buf, loc) } + } } - impl<'b> ::flatbuffers::Push for Ability { type Output = Ability; - #[inline] unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { let src = unsafe { ::core::slice::from_raw_parts(self as *const Ability as *const u8, ::size()) }; dst.copy_from_slice(src); } - #[inline] fn alignment() -> ::flatbuffers::PushAlignment { ::flatbuffers::PushAlignment::new(4) @@ -61,138 +51,129 @@ impl<'b> ::flatbuffers::Push for Ability { } impl<'a> ::flatbuffers::Verifiable for Ability { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.in_buffer::(pos) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.in_buffer::(pos) + } } impl Serialize for Ability { - fn serialize(&self, serializer: S) -> Result - where - S: Serializer, - { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { let mut s = serializer.serialize_struct("Ability", 2)?; - s.serialize_field("id", &self.id())?; - s.serialize_field("distance", &self.distance())?; - s.end() - } + s.serialize_field("id", &self.id())?; + s.serialize_field("distance", &self.distance())?; + s.end() + } } impl<'a> Ability { - #[allow(clippy::too_many_arguments)] - pub fn new( - id: u32, - distance: u32, - ) -> Self { - let mut s = Self([0; 8]); - s.set_id(id); - s.set_distance(distance); - s - } + #[allow(clippy::too_many_arguments)] + pub fn new( + id: u32, + distance: u32, + ) -> Self { + let mut s = Self([0; 8]); + s.set_id(id); + s.set_distance(distance); + s + } - pub const fn get_fully_qualified_name() -> &'static str { - "MyGame.Example.Ability" - } + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Example.Ability" + } - pub fn id(&self) -> u32 { - let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - ::flatbuffers::EndianScalar::from_little_endian(unsafe { - ::core::ptr::copy_nonoverlapping( - self.0[0..].as_ptr(), - mem.as_mut_ptr() as *mut u8, - ::core::mem::size_of::<::Scalar>(), - ); - mem.assume_init() - }) - } + pub fn id(&self) -> u32 { + let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + ::flatbuffers::EndianScalar::from_little_endian(unsafe { + ::core::ptr::copy_nonoverlapping( + self.0[0..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + ::core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } - pub fn set_id(&mut self, x: u32) { - let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - unsafe { - ::core::ptr::copy_nonoverlapping( - &x_le as *const _ as *const u8, - self.0[0..].as_mut_ptr(), - ::core::mem::size_of::<::Scalar>(), - ); - } + pub fn set_id(&mut self, x: u32) { + let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + ::core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[0..].as_mut_ptr(), + ::core::mem::size_of::<::Scalar>(), + ); } + } + #[inline] + pub fn key_compare_less_than(&self, o: &Ability) -> bool { + self.id() < o.id() + } - #[inline] - pub fn key_compare_less_than(&self, o: &Ability) -> bool { - self.id() < o.id() - } + #[inline] + pub fn key_compare_with_value(&self, val: u32) -> ::core::cmp::Ordering { + let key = self.id(); + key.cmp(&val) + } + pub fn distance(&self) -> u32 { + let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + ::flatbuffers::EndianScalar::from_little_endian(unsafe { + ::core::ptr::copy_nonoverlapping( + self.0[4..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + ::core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } - #[inline] - pub fn key_compare_with_value(&self, val: u32) -> ::core::cmp::Ordering { - let key = self.id(); - key.cmp(&val) - } - pub fn distance(&self) -> u32 { - let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - ::flatbuffers::EndianScalar::from_little_endian(unsafe { - ::core::ptr::copy_nonoverlapping( - self.0[4..].as_ptr(), - mem.as_mut_ptr() as *mut u8, - ::core::mem::size_of::<::Scalar>(), - ); - mem.assume_init() - }) + pub fn set_distance(&mut self, x: u32) { + let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + ::core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[4..].as_mut_ptr(), + ::core::mem::size_of::<::Scalar>(), + ); } + } - pub fn set_distance(&mut self, x: u32) { - let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - unsafe { - ::core::ptr::copy_nonoverlapping( - &x_le as *const _ as *const u8, - self.0[4..].as_mut_ptr(), - ::core::mem::size_of::<::Scalar>(), - ); - } - } - - pub fn unpack(&self) -> AbilityT { - AbilityT { - id: self.id(), - distance: self.distance(), - } + pub fn unpack(&self) -> AbilityT { + AbilityT { + id: self.id(), + distance: self.distance(), } + } } -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Default)] pub struct AbilityT { - pub id: u32, - pub distance: u32, + pub id: u32, + pub distance: u32, } -impl Default for AbilityT { - fn default() -> Self { - Self { - id: 0, - distance: 0, - } - } +impl AbilityT { + pub fn pack(&self) -> Ability { + Ability::new( + self.id, + self.distance, + ) + } } -impl AbilityT { - pub fn pack(&self) -> Ability { - Ability::new( - self.id, - self.distance, - ) - } -} diff --git a/tests/monster_test_serialize/my_game/example/any_ambiguous_aliases_generated.rs b/tests/monster_test_serialize/my_game/example/any_ambiguous_aliases_generated.rs index 415961c78..647e85416 100644 --- a/tests/monster_test_serialize/my_game/example/any_ambiguous_aliases_generated.rs +++ b/tests/monster_test_serialize/my_game/example/any_ambiguous_aliases_generated.rs @@ -4,71 +4,64 @@ extern crate alloc; extern crate serde; use self::serde::ser::{Serialize, Serializer, SerializeStruct}; use super::*; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] pub const ENUM_MIN_ANY_AMBIGUOUS_ALIASES: u8 = 0; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] pub const ENUM_MAX_ANY_AMBIGUOUS_ALIASES: u8 = 3; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] #[allow(non_camel_case_types)] pub const ENUM_VALUES_ANY_AMBIGUOUS_ALIASES: [AnyAmbiguousAliases; 4] = [ - AnyAmbiguousAliases::NONE, - AnyAmbiguousAliases::M1, - AnyAmbiguousAliases::M2, - AnyAmbiguousAliases::M3, + AnyAmbiguousAliases::NONE, + AnyAmbiguousAliases::M1, + AnyAmbiguousAliases::M2, + AnyAmbiguousAliases::M3, ]; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] #[repr(transparent)] pub struct AnyAmbiguousAliases(pub u8); - #[allow(non_upper_case_globals)] impl AnyAmbiguousAliases { - pub const NONE: Self = Self(0); - pub const M1: Self = Self(1); - pub const M2: Self = Self(2); - pub const M3: Self = Self(3); + pub const NONE: Self = Self(0); + pub const M1: Self = Self(1); + pub const M2: Self = Self(2); + pub const M3: Self = Self(3); - pub const ENUM_MIN: u8 = 0; - pub const ENUM_MAX: u8 = 3; - pub const ENUM_VALUES: &'static [Self] = &[ - Self::NONE, - Self::M1, - Self::M2, - Self::M3, - ]; - - /// Returns the variant's name or "" if unknown. - pub fn variant_name(self) -> Option<&'static str> { - match self { - Self::NONE => Some("NONE"), - Self::M1 => Some("M1"), - Self::M2 => Some("M2"), - Self::M3 => Some("M3"), - _ => None, - } + pub const ENUM_MIN: u8 = 0; + pub const ENUM_MAX: u8 = 3; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::NONE, + Self::M1, + Self::M2, + Self::M3, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::NONE => Some("NONE"), + Self::M1 => Some("M1"), + Self::M2 => Some("M2"), + Self::M3 => Some("M3"), + _ => None, } + } } - impl ::core::fmt::Debug for AnyAmbiguousAliases { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - if let Some(name) = self.variant_name() { - f.write_str(name) - } else { - f.write_fmt(format_args!("", self.0)) - } + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) } + } } - impl Serialize for AnyAmbiguousAliases { - fn serialize(&self, serializer: S) -> Result - where - S: Serializer, - { - serializer.serialize_unit_variant("AnyAmbiguousAliases", self.0 as u32, self.variant_name().unwrap()) - } + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_unit_variant("AnyAmbiguousAliases", self.0 as u32, self.variant_name().unwrap()) + } } impl<'de> serde::Deserialize<'de> for AnyAmbiguousAliases { @@ -91,18 +84,16 @@ impl<'de> serde::Deserialize<'de> for AnyAmbiguousAliases { } impl<'a> ::flatbuffers::Follow<'a> for AnyAmbiguousAliases { - type Inner = Self; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; - Self(b) - } + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; + Self(b) + } } impl ::flatbuffers::Push for AnyAmbiguousAliases { type Output = AnyAmbiguousAliases; - #[inline] unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { unsafe { ::flatbuffers::emplace_scalar::(dst, self.0) }; @@ -110,139 +101,123 @@ impl ::flatbuffers::Push for AnyAmbiguousAliases { } impl ::flatbuffers::EndianScalar for AnyAmbiguousAliases { - type Scalar = u8; - - #[inline] - fn to_little_endian(self) -> u8 { - self.0.to_le() - } - - #[inline] - #[allow(clippy::wrong_self_convention)] - fn from_little_endian(v: u8) -> Self { - let b = u8::from_le(v); - Self(b) - } + type Scalar = u8; + #[inline] + fn to_little_endian(self) -> u8 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: u8) -> Self { + let b = u8::from_le(v); + Self(b) + } } impl<'a> ::flatbuffers::Verifiable for AnyAmbiguousAliases { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - u8::run_verifier(v, pos) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + u8::run_verifier(v, pos) + } } impl ::flatbuffers::SimpleToVerifyInSlice for AnyAmbiguousAliases {} - pub struct AnyAmbiguousAliasesUnionTableOffset {} #[allow(clippy::upper_case_acronyms)] #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub enum AnyAmbiguousAliasesT { - NONE, - M1(alloc::boxed::Box), - M2(alloc::boxed::Box), - M3(alloc::boxed::Box), + NONE, + M1(alloc::boxed::Box), + M2(alloc::boxed::Box), + M3(alloc::boxed::Box), } - impl Default for AnyAmbiguousAliasesT { - fn default() -> Self { - Self::NONE - } + fn default() -> Self { + Self::NONE + } } - impl AnyAmbiguousAliasesT { - pub fn any_ambiguous_aliases_type(&self) -> AnyAmbiguousAliases { - match self { - Self::NONE => AnyAmbiguousAliases::NONE, - Self::M1(_) => AnyAmbiguousAliases::M1, - Self::M2(_) => AnyAmbiguousAliases::M2, - Self::M3(_) => AnyAmbiguousAliases::M3, - } + pub fn any_ambiguous_aliases_type(&self) -> AnyAmbiguousAliases { + match self { + Self::NONE => AnyAmbiguousAliases::NONE, + Self::M1(_) => AnyAmbiguousAliases::M1, + Self::M2(_) => AnyAmbiguousAliases::M2, + Self::M3(_) => AnyAmbiguousAliases::M3, } - - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>(&self, fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A>) -> Option<::flatbuffers::WIPOffset<::flatbuffers::UnionWIPOffset>> { - match self { - Self::NONE => None, - Self::M1(v) => Some(v.pack(fbb).as_union_value()), - Self::M2(v) => Some(v.pack(fbb).as_union_value()), - Self::M3(v) => Some(v.pack(fbb).as_union_value()), - } + } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>(&self, fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A>) -> Option<::flatbuffers::WIPOffset<::flatbuffers::UnionWIPOffset>> { + match self { + Self::NONE => None, + Self::M1(v) => Some(v.pack(fbb).as_union_value()), + Self::M2(v) => Some(v.pack(fbb).as_union_value()), + Self::M3(v) => Some(v.pack(fbb).as_union_value()), } - - /// If the union variant matches, return the owned MonsterT, setting the union to NONE. - pub fn take_m1(&mut self) -> Option> { - if let Self::M1(_) = self { - let v = ::core::mem::replace(self, Self::NONE); - if let Self::M1(w) = v { - Some(w) - } else { - unreachable!() - } - } else { - None - } + } + /// If the union variant matches, return the owned MonsterT, setting the union to NONE. + pub fn take_m1(&mut self) -> Option> { + if let Self::M1(_) = self { + let v = ::core::mem::replace(self, Self::NONE); + if let Self::M1(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None } - - /// If the union variant matches, return a reference to the MonsterT. - pub fn as_m1(&self) -> Option<&MonsterT> { - if let Self::M1(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a reference to the MonsterT. + pub fn as_m1(&self) -> Option<&MonsterT> { + if let Self::M1(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the MonsterT. + pub fn as_m1_mut(&mut self) -> Option<&mut MonsterT> { + if let Self::M1(v) = self { Some(v.as_mut()) } else { None } + } + /// If the union variant matches, return the owned MonsterT, setting the union to NONE. + pub fn take_m2(&mut self) -> Option> { + if let Self::M2(_) = self { + let v = ::core::mem::replace(self, Self::NONE); + if let Self::M2(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None } - - /// If the union variant matches, return a mutable reference to the MonsterT. - pub fn as_m1_mut(&mut self) -> Option<&mut MonsterT> { - if let Self::M1(v) = self { Some(v.as_mut()) } else { None } - } - - /// If the union variant matches, return the owned MonsterT, setting the union to NONE. - pub fn take_m2(&mut self) -> Option> { - if let Self::M2(_) = self { - let v = ::core::mem::replace(self, Self::NONE); - if let Self::M2(w) = v { - Some(w) - } else { - unreachable!() - } - } else { - None - } - } - - /// If the union variant matches, return a reference to the MonsterT. - pub fn as_m2(&self) -> Option<&MonsterT> { - if let Self::M2(v) = self { Some(v.as_ref()) } else { None } - } - - /// If the union variant matches, return a mutable reference to the MonsterT. - pub fn as_m2_mut(&mut self) -> Option<&mut MonsterT> { - if let Self::M2(v) = self { Some(v.as_mut()) } else { None } - } - - /// If the union variant matches, return the owned MonsterT, setting the union to NONE. - pub fn take_m3(&mut self) -> Option> { - if let Self::M3(_) = self { - let v = ::core::mem::replace(self, Self::NONE); - if let Self::M3(w) = v { - Some(w) - } else { - unreachable!() - } - } else { - None - } - } - - /// If the union variant matches, return a reference to the MonsterT. - pub fn as_m3(&self) -> Option<&MonsterT> { - if let Self::M3(v) = self { Some(v.as_ref()) } else { None } - } - - /// If the union variant matches, return a mutable reference to the MonsterT. - pub fn as_m3_mut(&mut self) -> Option<&mut MonsterT> { - if let Self::M3(v) = self { Some(v.as_mut()) } else { None } + } + /// If the union variant matches, return a reference to the MonsterT. + pub fn as_m2(&self) -> Option<&MonsterT> { + if let Self::M2(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the MonsterT. + pub fn as_m2_mut(&mut self) -> Option<&mut MonsterT> { + if let Self::M2(v) = self { Some(v.as_mut()) } else { None } + } + /// If the union variant matches, return the owned MonsterT, setting the union to NONE. + pub fn take_m3(&mut self) -> Option> { + if let Self::M3(_) = self { + let v = ::core::mem::replace(self, Self::NONE); + if let Self::M3(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None } + } + /// If the union variant matches, return a reference to the MonsterT. + pub fn as_m3(&self) -> Option<&MonsterT> { + if let Self::M3(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the MonsterT. + pub fn as_m3_mut(&mut self) -> Option<&mut MonsterT> { + if let Self::M3(v) = self { Some(v.as_mut()) } else { None } + } } - diff --git a/tests/monster_test_serialize/my_game/example/any_generated.rs b/tests/monster_test_serialize/my_game/example/any_generated.rs index 5f4ab10c0..f5b40b5e3 100644 --- a/tests/monster_test_serialize/my_game/example/any_generated.rs +++ b/tests/monster_test_serialize/my_game/example/any_generated.rs @@ -4,71 +4,64 @@ extern crate alloc; extern crate serde; use self::serde::ser::{Serialize, Serializer, SerializeStruct}; use super::*; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] pub const ENUM_MIN_ANY: u8 = 0; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] pub const ENUM_MAX_ANY: u8 = 3; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] #[allow(non_camel_case_types)] pub const ENUM_VALUES_ANY: [Any; 4] = [ - Any::NONE, - Any::Monster, - Any::TestSimpleTableWithEnum, - Any::MyGame_Example2_Monster, + Any::NONE, + Any::Monster, + Any::TestSimpleTableWithEnum, + Any::MyGame_Example2_Monster, ]; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] #[repr(transparent)] pub struct Any(pub u8); - #[allow(non_upper_case_globals)] impl Any { - pub const NONE: Self = Self(0); - pub const Monster: Self = Self(1); - pub const TestSimpleTableWithEnum: Self = Self(2); - pub const MyGame_Example2_Monster: Self = Self(3); + pub const NONE: Self = Self(0); + pub const Monster: Self = Self(1); + pub const TestSimpleTableWithEnum: Self = Self(2); + pub const MyGame_Example2_Monster: Self = Self(3); - pub const ENUM_MIN: u8 = 0; - pub const ENUM_MAX: u8 = 3; - pub const ENUM_VALUES: &'static [Self] = &[ - Self::NONE, - Self::Monster, - Self::TestSimpleTableWithEnum, - Self::MyGame_Example2_Monster, - ]; - - /// Returns the variant's name or "" if unknown. - pub fn variant_name(self) -> Option<&'static str> { - match self { - Self::NONE => Some("NONE"), - Self::Monster => Some("Monster"), - Self::TestSimpleTableWithEnum => Some("TestSimpleTableWithEnum"), - Self::MyGame_Example2_Monster => Some("MyGame_Example2_Monster"), - _ => None, - } + pub const ENUM_MIN: u8 = 0; + pub const ENUM_MAX: u8 = 3; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::NONE, + Self::Monster, + Self::TestSimpleTableWithEnum, + Self::MyGame_Example2_Monster, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::NONE => Some("NONE"), + Self::Monster => Some("Monster"), + Self::TestSimpleTableWithEnum => Some("TestSimpleTableWithEnum"), + Self::MyGame_Example2_Monster => Some("MyGame_Example2_Monster"), + _ => None, } + } } - impl ::core::fmt::Debug for Any { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - if let Some(name) = self.variant_name() { - f.write_str(name) - } else { - f.write_fmt(format_args!("", self.0)) - } + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) } + } } - impl Serialize for Any { - fn serialize(&self, serializer: S) -> Result - where - S: Serializer, - { - serializer.serialize_unit_variant("Any", self.0 as u32, self.variant_name().unwrap()) - } + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_unit_variant("Any", self.0 as u32, self.variant_name().unwrap()) + } } impl<'de> serde::Deserialize<'de> for Any { @@ -91,18 +84,16 @@ impl<'de> serde::Deserialize<'de> for Any { } impl<'a> ::flatbuffers::Follow<'a> for Any { - type Inner = Self; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; - Self(b) - } + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; + Self(b) + } } impl ::flatbuffers::Push for Any { type Output = Any; - #[inline] unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { unsafe { ::flatbuffers::emplace_scalar::(dst, self.0) }; @@ -110,139 +101,123 @@ impl ::flatbuffers::Push for Any { } impl ::flatbuffers::EndianScalar for Any { - type Scalar = u8; - - #[inline] - fn to_little_endian(self) -> u8 { - self.0.to_le() - } - - #[inline] - #[allow(clippy::wrong_self_convention)] - fn from_little_endian(v: u8) -> Self { - let b = u8::from_le(v); - Self(b) - } + type Scalar = u8; + #[inline] + fn to_little_endian(self) -> u8 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: u8) -> Self { + let b = u8::from_le(v); + Self(b) + } } impl<'a> ::flatbuffers::Verifiable for Any { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - u8::run_verifier(v, pos) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + u8::run_verifier(v, pos) + } } impl ::flatbuffers::SimpleToVerifyInSlice for Any {} - pub struct AnyUnionTableOffset {} #[allow(clippy::upper_case_acronyms)] #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub enum AnyT { - NONE, - Monster(alloc::boxed::Box), - TestSimpleTableWithEnum(alloc::boxed::Box), - MyGameExample2Monster(alloc::boxed::Box), + NONE, + Monster(alloc::boxed::Box), + TestSimpleTableWithEnum(alloc::boxed::Box), + MyGameExample2Monster(alloc::boxed::Box), } - impl Default for AnyT { - fn default() -> Self { - Self::NONE - } + fn default() -> Self { + Self::NONE + } } - impl AnyT { - pub fn any_type(&self) -> Any { - match self { - Self::NONE => Any::NONE, - Self::Monster(_) => Any::Monster, - Self::TestSimpleTableWithEnum(_) => Any::TestSimpleTableWithEnum, - Self::MyGameExample2Monster(_) => Any::MyGame_Example2_Monster, - } + pub fn any_type(&self) -> Any { + match self { + Self::NONE => Any::NONE, + Self::Monster(_) => Any::Monster, + Self::TestSimpleTableWithEnum(_) => Any::TestSimpleTableWithEnum, + Self::MyGameExample2Monster(_) => Any::MyGame_Example2_Monster, } - - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>(&self, fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A>) -> Option<::flatbuffers::WIPOffset<::flatbuffers::UnionWIPOffset>> { - match self { - Self::NONE => None, - Self::Monster(v) => Some(v.pack(fbb).as_union_value()), - Self::TestSimpleTableWithEnum(v) => Some(v.pack(fbb).as_union_value()), - Self::MyGameExample2Monster(v) => Some(v.pack(fbb).as_union_value()), - } + } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>(&self, fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A>) -> Option<::flatbuffers::WIPOffset<::flatbuffers::UnionWIPOffset>> { + match self { + Self::NONE => None, + Self::Monster(v) => Some(v.pack(fbb).as_union_value()), + Self::TestSimpleTableWithEnum(v) => Some(v.pack(fbb).as_union_value()), + Self::MyGameExample2Monster(v) => Some(v.pack(fbb).as_union_value()), } - - /// If the union variant matches, return the owned MonsterT, setting the union to NONE. - pub fn take_monster(&mut self) -> Option> { - if let Self::Monster(_) = self { - let v = ::core::mem::replace(self, Self::NONE); - if let Self::Monster(w) = v { - Some(w) - } else { - unreachable!() - } - } else { - None - } + } + /// If the union variant matches, return the owned MonsterT, setting the union to NONE. + pub fn take_monster(&mut self) -> Option> { + if let Self::Monster(_) = self { + let v = ::core::mem::replace(self, Self::NONE); + if let Self::Monster(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None } - - /// If the union variant matches, return a reference to the MonsterT. - pub fn as_monster(&self) -> Option<&MonsterT> { - if let Self::Monster(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a reference to the MonsterT. + pub fn as_monster(&self) -> Option<&MonsterT> { + if let Self::Monster(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the MonsterT. + pub fn as_monster_mut(&mut self) -> Option<&mut MonsterT> { + if let Self::Monster(v) = self { Some(v.as_mut()) } else { None } + } + /// If the union variant matches, return the owned TestSimpleTableWithEnumT, setting the union to NONE. + pub fn take_test_simple_table_with_enum(&mut self) -> Option> { + if let Self::TestSimpleTableWithEnum(_) = self { + let v = ::core::mem::replace(self, Self::NONE); + if let Self::TestSimpleTableWithEnum(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None } - - /// If the union variant matches, return a mutable reference to the MonsterT. - pub fn as_monster_mut(&mut self) -> Option<&mut MonsterT> { - if let Self::Monster(v) = self { Some(v.as_mut()) } else { None } - } - - /// If the union variant matches, return the owned TestSimpleTableWithEnumT, setting the union to NONE. - pub fn take_test_simple_table_with_enum(&mut self) -> Option> { - if let Self::TestSimpleTableWithEnum(_) = self { - let v = ::core::mem::replace(self, Self::NONE); - if let Self::TestSimpleTableWithEnum(w) = v { - Some(w) - } else { - unreachable!() - } - } else { - None - } - } - - /// If the union variant matches, return a reference to the TestSimpleTableWithEnumT. - pub fn as_test_simple_table_with_enum(&self) -> Option<&TestSimpleTableWithEnumT> { - if let Self::TestSimpleTableWithEnum(v) = self { Some(v.as_ref()) } else { None } - } - - /// If the union variant matches, return a mutable reference to the TestSimpleTableWithEnumT. - pub fn as_test_simple_table_with_enum_mut(&mut self) -> Option<&mut TestSimpleTableWithEnumT> { - if let Self::TestSimpleTableWithEnum(v) = self { Some(v.as_mut()) } else { None } - } - - /// If the union variant matches, return the owned super::example_2::MonsterT, setting the union to NONE. - pub fn take_my_game_example_2_monster(&mut self) -> Option> { - if let Self::MyGameExample2Monster(_) = self { - let v = ::core::mem::replace(self, Self::NONE); - if let Self::MyGameExample2Monster(w) = v { - Some(w) - } else { - unreachable!() - } - } else { - None - } - } - - /// If the union variant matches, return a reference to the super::example_2::MonsterT. - pub fn as_my_game_example_2_monster(&self) -> Option<&super::example_2::MonsterT> { - if let Self::MyGameExample2Monster(v) = self { Some(v.as_ref()) } else { None } - } - - /// If the union variant matches, return a mutable reference to the super::example_2::MonsterT. - pub fn as_my_game_example_2_monster_mut(&mut self) -> Option<&mut super::example_2::MonsterT> { - if let Self::MyGameExample2Monster(v) = self { Some(v.as_mut()) } else { None } + } + /// If the union variant matches, return a reference to the TestSimpleTableWithEnumT. + pub fn as_test_simple_table_with_enum(&self) -> Option<&TestSimpleTableWithEnumT> { + if let Self::TestSimpleTableWithEnum(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the TestSimpleTableWithEnumT. + pub fn as_test_simple_table_with_enum_mut(&mut self) -> Option<&mut TestSimpleTableWithEnumT> { + if let Self::TestSimpleTableWithEnum(v) = self { Some(v.as_mut()) } else { None } + } + /// If the union variant matches, return the owned super::example_2::MonsterT, setting the union to NONE. + pub fn take_my_game_example_2_monster(&mut self) -> Option> { + if let Self::MyGameExample2Monster(_) = self { + let v = ::core::mem::replace(self, Self::NONE); + if let Self::MyGameExample2Monster(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None } + } + /// If the union variant matches, return a reference to the super::example_2::MonsterT. + pub fn as_my_game_example_2_monster(&self) -> Option<&super::example_2::MonsterT> { + if let Self::MyGameExample2Monster(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the super::example_2::MonsterT. + pub fn as_my_game_example_2_monster_mut(&mut self) -> Option<&mut super::example_2::MonsterT> { + if let Self::MyGameExample2Monster(v) = self { Some(v.as_mut()) } else { None } + } } - diff --git a/tests/monster_test_serialize/my_game/example/any_unique_aliases_generated.rs b/tests/monster_test_serialize/my_game/example/any_unique_aliases_generated.rs index 12286c683..2128e4779 100644 --- a/tests/monster_test_serialize/my_game/example/any_unique_aliases_generated.rs +++ b/tests/monster_test_serialize/my_game/example/any_unique_aliases_generated.rs @@ -4,71 +4,64 @@ extern crate alloc; extern crate serde; use self::serde::ser::{Serialize, Serializer, SerializeStruct}; use super::*; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] pub const ENUM_MIN_ANY_UNIQUE_ALIASES: u8 = 0; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] pub const ENUM_MAX_ANY_UNIQUE_ALIASES: u8 = 3; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] #[allow(non_camel_case_types)] pub const ENUM_VALUES_ANY_UNIQUE_ALIASES: [AnyUniqueAliases; 4] = [ - AnyUniqueAliases::NONE, - AnyUniqueAliases::M, - AnyUniqueAliases::TS, - AnyUniqueAliases::M2, + AnyUniqueAliases::NONE, + AnyUniqueAliases::M, + AnyUniqueAliases::TS, + AnyUniqueAliases::M2, ]; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] #[repr(transparent)] pub struct AnyUniqueAliases(pub u8); - #[allow(non_upper_case_globals)] impl AnyUniqueAliases { - pub const NONE: Self = Self(0); - pub const M: Self = Self(1); - pub const TS: Self = Self(2); - pub const M2: Self = Self(3); + pub const NONE: Self = Self(0); + pub const M: Self = Self(1); + pub const TS: Self = Self(2); + pub const M2: Self = Self(3); - pub const ENUM_MIN: u8 = 0; - pub const ENUM_MAX: u8 = 3; - pub const ENUM_VALUES: &'static [Self] = &[ - Self::NONE, - Self::M, - Self::TS, - Self::M2, - ]; - - /// Returns the variant's name or "" if unknown. - pub fn variant_name(self) -> Option<&'static str> { - match self { - Self::NONE => Some("NONE"), - Self::M => Some("M"), - Self::TS => Some("TS"), - Self::M2 => Some("M2"), - _ => None, - } + pub const ENUM_MIN: u8 = 0; + pub const ENUM_MAX: u8 = 3; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::NONE, + Self::M, + Self::TS, + Self::M2, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::NONE => Some("NONE"), + Self::M => Some("M"), + Self::TS => Some("TS"), + Self::M2 => Some("M2"), + _ => None, } + } } - impl ::core::fmt::Debug for AnyUniqueAliases { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - if let Some(name) = self.variant_name() { - f.write_str(name) - } else { - f.write_fmt(format_args!("", self.0)) - } + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) } + } } - impl Serialize for AnyUniqueAliases { - fn serialize(&self, serializer: S) -> Result - where - S: Serializer, - { - serializer.serialize_unit_variant("AnyUniqueAliases", self.0 as u32, self.variant_name().unwrap()) - } + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_unit_variant("AnyUniqueAliases", self.0 as u32, self.variant_name().unwrap()) + } } impl<'de> serde::Deserialize<'de> for AnyUniqueAliases { @@ -91,18 +84,16 @@ impl<'de> serde::Deserialize<'de> for AnyUniqueAliases { } impl<'a> ::flatbuffers::Follow<'a> for AnyUniqueAliases { - type Inner = Self; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; - Self(b) - } + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; + Self(b) + } } impl ::flatbuffers::Push for AnyUniqueAliases { type Output = AnyUniqueAliases; - #[inline] unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { unsafe { ::flatbuffers::emplace_scalar::(dst, self.0) }; @@ -110,139 +101,123 @@ impl ::flatbuffers::Push for AnyUniqueAliases { } impl ::flatbuffers::EndianScalar for AnyUniqueAliases { - type Scalar = u8; - - #[inline] - fn to_little_endian(self) -> u8 { - self.0.to_le() - } - - #[inline] - #[allow(clippy::wrong_self_convention)] - fn from_little_endian(v: u8) -> Self { - let b = u8::from_le(v); - Self(b) - } + type Scalar = u8; + #[inline] + fn to_little_endian(self) -> u8 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: u8) -> Self { + let b = u8::from_le(v); + Self(b) + } } impl<'a> ::flatbuffers::Verifiable for AnyUniqueAliases { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - u8::run_verifier(v, pos) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + u8::run_verifier(v, pos) + } } impl ::flatbuffers::SimpleToVerifyInSlice for AnyUniqueAliases {} - pub struct AnyUniqueAliasesUnionTableOffset {} #[allow(clippy::upper_case_acronyms)] #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub enum AnyUniqueAliasesT { - NONE, - M(alloc::boxed::Box), - TS(alloc::boxed::Box), - M2(alloc::boxed::Box), + NONE, + M(alloc::boxed::Box), + TS(alloc::boxed::Box), + M2(alloc::boxed::Box), } - impl Default for AnyUniqueAliasesT { - fn default() -> Self { - Self::NONE - } + fn default() -> Self { + Self::NONE + } } - impl AnyUniqueAliasesT { - pub fn any_unique_aliases_type(&self) -> AnyUniqueAliases { - match self { - Self::NONE => AnyUniqueAliases::NONE, - Self::M(_) => AnyUniqueAliases::M, - Self::TS(_) => AnyUniqueAliases::TS, - Self::M2(_) => AnyUniqueAliases::M2, - } + pub fn any_unique_aliases_type(&self) -> AnyUniqueAliases { + match self { + Self::NONE => AnyUniqueAliases::NONE, + Self::M(_) => AnyUniqueAliases::M, + Self::TS(_) => AnyUniqueAliases::TS, + Self::M2(_) => AnyUniqueAliases::M2, } - - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>(&self, fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A>) -> Option<::flatbuffers::WIPOffset<::flatbuffers::UnionWIPOffset>> { - match self { - Self::NONE => None, - Self::M(v) => Some(v.pack(fbb).as_union_value()), - Self::TS(v) => Some(v.pack(fbb).as_union_value()), - Self::M2(v) => Some(v.pack(fbb).as_union_value()), - } + } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>(&self, fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A>) -> Option<::flatbuffers::WIPOffset<::flatbuffers::UnionWIPOffset>> { + match self { + Self::NONE => None, + Self::M(v) => Some(v.pack(fbb).as_union_value()), + Self::TS(v) => Some(v.pack(fbb).as_union_value()), + Self::M2(v) => Some(v.pack(fbb).as_union_value()), } - - /// If the union variant matches, return the owned MonsterT, setting the union to NONE. - pub fn take_m(&mut self) -> Option> { - if let Self::M(_) = self { - let v = ::core::mem::replace(self, Self::NONE); - if let Self::M(w) = v { - Some(w) - } else { - unreachable!() - } - } else { - None - } + } + /// If the union variant matches, return the owned MonsterT, setting the union to NONE. + pub fn take_m(&mut self) -> Option> { + if let Self::M(_) = self { + let v = ::core::mem::replace(self, Self::NONE); + if let Self::M(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None } - - /// If the union variant matches, return a reference to the MonsterT. - pub fn as_m(&self) -> Option<&MonsterT> { - if let Self::M(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a reference to the MonsterT. + pub fn as_m(&self) -> Option<&MonsterT> { + if let Self::M(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the MonsterT. + pub fn as_m_mut(&mut self) -> Option<&mut MonsterT> { + if let Self::M(v) = self { Some(v.as_mut()) } else { None } + } + /// If the union variant matches, return the owned TestSimpleTableWithEnumT, setting the union to NONE. + pub fn take_ts(&mut self) -> Option> { + if let Self::TS(_) = self { + let v = ::core::mem::replace(self, Self::NONE); + if let Self::TS(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None } - - /// If the union variant matches, return a mutable reference to the MonsterT. - pub fn as_m_mut(&mut self) -> Option<&mut MonsterT> { - if let Self::M(v) = self { Some(v.as_mut()) } else { None } - } - - /// If the union variant matches, return the owned TestSimpleTableWithEnumT, setting the union to NONE. - pub fn take_ts(&mut self) -> Option> { - if let Self::TS(_) = self { - let v = ::core::mem::replace(self, Self::NONE); - if let Self::TS(w) = v { - Some(w) - } else { - unreachable!() - } - } else { - None - } - } - - /// If the union variant matches, return a reference to the TestSimpleTableWithEnumT. - pub fn as_ts(&self) -> Option<&TestSimpleTableWithEnumT> { - if let Self::TS(v) = self { Some(v.as_ref()) } else { None } - } - - /// If the union variant matches, return a mutable reference to the TestSimpleTableWithEnumT. - pub fn as_ts_mut(&mut self) -> Option<&mut TestSimpleTableWithEnumT> { - if let Self::TS(v) = self { Some(v.as_mut()) } else { None } - } - - /// If the union variant matches, return the owned super::example_2::MonsterT, setting the union to NONE. - pub fn take_m2(&mut self) -> Option> { - if let Self::M2(_) = self { - let v = ::core::mem::replace(self, Self::NONE); - if let Self::M2(w) = v { - Some(w) - } else { - unreachable!() - } - } else { - None - } - } - - /// If the union variant matches, return a reference to the super::example_2::MonsterT. - pub fn as_m2(&self) -> Option<&super::example_2::MonsterT> { - if let Self::M2(v) = self { Some(v.as_ref()) } else { None } - } - - /// If the union variant matches, return a mutable reference to the super::example_2::MonsterT. - pub fn as_m2_mut(&mut self) -> Option<&mut super::example_2::MonsterT> { - if let Self::M2(v) = self { Some(v.as_mut()) } else { None } + } + /// If the union variant matches, return a reference to the TestSimpleTableWithEnumT. + pub fn as_ts(&self) -> Option<&TestSimpleTableWithEnumT> { + if let Self::TS(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the TestSimpleTableWithEnumT. + pub fn as_ts_mut(&mut self) -> Option<&mut TestSimpleTableWithEnumT> { + if let Self::TS(v) = self { Some(v.as_mut()) } else { None } + } + /// If the union variant matches, return the owned super::example_2::MonsterT, setting the union to NONE. + pub fn take_m2(&mut self) -> Option> { + if let Self::M2(_) = self { + let v = ::core::mem::replace(self, Self::NONE); + if let Self::M2(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None } + } + /// If the union variant matches, return a reference to the super::example_2::MonsterT. + pub fn as_m2(&self) -> Option<&super::example_2::MonsterT> { + if let Self::M2(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the super::example_2::MonsterT. + pub fn as_m2_mut(&mut self) -> Option<&mut super::example_2::MonsterT> { + if let Self::M2(v) = self { Some(v.as_mut()) } else { None } + } } - diff --git a/tests/monster_test_serialize/my_game/example/color_generated.rs b/tests/monster_test_serialize/my_game/example/color_generated.rs index 12ea6d5aa..5a540612b 100644 --- a/tests/monster_test_serialize/my_game/example/color_generated.rs +++ b/tests/monster_test_serialize/my_game/example/color_generated.rs @@ -4,47 +4,43 @@ extern crate alloc; extern crate serde; use self::serde::ser::{Serialize, Serializer, SerializeStruct}; use super::*; - #[allow(non_upper_case_globals)] mod bitflags_color { - ::flatbuffers::bitflags::bitflags! { - /// Composite components of Monster color. - #[derive(Default, Debug, Clone, Copy, PartialEq)] - pub struct Color: u8 { - const Red = 1; - /// \brief color Green - /// Green is bit_flag with value (1u << 1) - const Green = 2; - /// \brief color Blue (1u << 3) - const Blue = 8; - } + ::flatbuffers::bitflags::bitflags! { + /// Composite components of Monster color. + #[derive(Default, Debug, Clone, Copy, PartialEq)] + pub struct Color: u8 { + const Red = 1; + /// \brief color Green + /// Green is bit_flag with value (1u << 1) + const Green = 2; + /// \brief color Blue (1u << 3) + const Blue = 8; } + } } - pub use self::bitflags_color::Color; impl Serialize for Color { - fn serialize(&self, serializer: S) -> Result - where - S: Serializer, - { - serializer.serialize_u32(self.bits() as u32) - } + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_u32(self.bits() as u32) + } } impl<'a> ::flatbuffers::Follow<'a> for Color { - type Inner = Self; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; - Self::from_bits_retain(b) - } + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; + Self::from_bits_retain(b) + } } impl ::flatbuffers::Push for Color { type Output = Color; - #[inline] unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { unsafe { ::flatbuffers::emplace_scalar::(dst, self.bits()) }; @@ -52,28 +48,26 @@ impl ::flatbuffers::Push for Color { } impl ::flatbuffers::EndianScalar for Color { - type Scalar = u8; - - #[inline] - fn to_little_endian(self) -> u8 { - self.bits().to_le() - } - - #[inline] - #[allow(clippy::wrong_self_convention)] - fn from_little_endian(v: u8) -> Self { - let b = u8::from_le(v); - Self::from_bits_retain(b) - } + type Scalar = u8; + #[inline] + fn to_little_endian(self) -> u8 { + self.bits().to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: u8) -> Self { + let b = u8::from_le(v); + Self::from_bits_retain(b) + } } impl<'a> ::flatbuffers::Verifiable for Color { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - u8::run_verifier(v, pos) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + u8::run_verifier(v, pos) + } } impl ::flatbuffers::SimpleToVerifyInSlice for Color {} diff --git a/tests/monster_test_serialize/my_game/example/long_enum_generated.rs b/tests/monster_test_serialize/my_game/example/long_enum_generated.rs index 90ad8e4f5..bff530afe 100644 --- a/tests/monster_test_serialize/my_game/example/long_enum_generated.rs +++ b/tests/monster_test_serialize/my_game/example/long_enum_generated.rs @@ -4,43 +4,39 @@ extern crate alloc; extern crate serde; use self::serde::ser::{Serialize, Serializer, SerializeStruct}; use super::*; - #[allow(non_upper_case_globals)] mod bitflags_long_enum { - ::flatbuffers::bitflags::bitflags! { - #[derive(Default, Debug, Clone, Copy, PartialEq)] - pub struct LongEnum: u64 { - const LongOne = 2; - const LongTwo = 4; - const LongBig = 1099511627776; - } + ::flatbuffers::bitflags::bitflags! { + #[derive(Default, Debug, Clone, Copy, PartialEq)] + pub struct LongEnum: u64 { + const LongOne = 2; + const LongTwo = 4; + const LongBig = 1099511627776; } + } } - pub use self::bitflags_long_enum::LongEnum; impl Serialize for LongEnum { - fn serialize(&self, serializer: S) -> Result - where - S: Serializer, - { - serializer.serialize_u32(self.bits() as u32) - } + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_u32(self.bits() as u32) + } } impl<'a> ::flatbuffers::Follow<'a> for LongEnum { - type Inner = Self; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; - Self::from_bits_retain(b) - } + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; + Self::from_bits_retain(b) + } } impl ::flatbuffers::Push for LongEnum { type Output = LongEnum; - #[inline] unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { unsafe { ::flatbuffers::emplace_scalar::(dst, self.bits()) }; @@ -48,28 +44,26 @@ impl ::flatbuffers::Push for LongEnum { } impl ::flatbuffers::EndianScalar for LongEnum { - type Scalar = u64; - - #[inline] - fn to_little_endian(self) -> u64 { - self.bits().to_le() - } - - #[inline] - #[allow(clippy::wrong_self_convention)] - fn from_little_endian(v: u64) -> Self { - let b = u64::from_le(v); - Self::from_bits_retain(b) - } + type Scalar = u64; + #[inline] + fn to_little_endian(self) -> u64 { + self.bits().to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: u64) -> Self { + let b = u64::from_le(v); + Self::from_bits_retain(b) + } } impl<'a> ::flatbuffers::Verifiable for LongEnum { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - u64::run_verifier(v, pos) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + u64::run_verifier(v, pos) + } } impl ::flatbuffers::SimpleToVerifyInSlice for LongEnum {} diff --git a/tests/monster_test_serialize/my_game/example/monster_generated.rs b/tests/monster_test_serialize/my_game/example/monster_generated.rs index 26652e1c9..749098f56 100644 --- a/tests/monster_test_serialize/my_game/example/monster_generated.rs +++ b/tests/monster_test_serialize/my_game/example/monster_generated.rs @@ -4,1141 +4,1074 @@ extern crate alloc; extern crate serde; use self::serde::ser::{Serialize, Serializer, SerializeStruct}; use super::*; - pub enum MonsterOffset {} +#[derive(Copy, Clone, PartialEq)] /// an example documentation comment: "monster object" -#[derive(Copy, Clone, PartialEq)] pub struct Monster<'a> { - pub _tab: ::flatbuffers::Table<'a>, + pub _tab: ::flatbuffers::Table<'a>, } impl<'a> ::flatbuffers::Follow<'a> for Monster<'a> { - type Inner = Monster<'a>; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } - } + type Inner = Monster<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } + } } impl<'a> Monster<'a> { - pub const VT_POS: ::flatbuffers::VOffsetT = 4; - pub const VT_MANA: ::flatbuffers::VOffsetT = 6; - pub const VT_HP: ::flatbuffers::VOffsetT = 8; - pub const VT_NAME: ::flatbuffers::VOffsetT = 10; - pub const VT_INVENTORY: ::flatbuffers::VOffsetT = 14; - pub const VT_COLOR: ::flatbuffers::VOffsetT = 16; - pub const VT_TEST_TYPE: ::flatbuffers::VOffsetT = 18; - pub const VT_TEST: ::flatbuffers::VOffsetT = 20; - pub const VT_TEST4: ::flatbuffers::VOffsetT = 22; - pub const VT_TESTARRAYOFSTRING: ::flatbuffers::VOffsetT = 24; - pub const VT_TESTARRAYOFTABLES: ::flatbuffers::VOffsetT = 26; - pub const VT_ENEMY: ::flatbuffers::VOffsetT = 28; - pub const VT_TESTNESTEDFLATBUFFER: ::flatbuffers::VOffsetT = 30; - pub const VT_TESTEMPTY: ::flatbuffers::VOffsetT = 32; - pub const VT_TESTBOOL: ::flatbuffers::VOffsetT = 34; - pub const VT_TESTHASHS32_FNV1: ::flatbuffers::VOffsetT = 36; - pub const VT_TESTHASHU32_FNV1: ::flatbuffers::VOffsetT = 38; - pub const VT_TESTHASHS64_FNV1: ::flatbuffers::VOffsetT = 40; - pub const VT_TESTHASHU64_FNV1: ::flatbuffers::VOffsetT = 42; - pub const VT_TESTHASHS32_FNV1A: ::flatbuffers::VOffsetT = 44; - pub const VT_TESTHASHU32_FNV1A: ::flatbuffers::VOffsetT = 46; - pub const VT_TESTHASHS64_FNV1A: ::flatbuffers::VOffsetT = 48; - pub const VT_TESTHASHU64_FNV1A: ::flatbuffers::VOffsetT = 50; - pub const VT_TESTARRAYOFBOOLS: ::flatbuffers::VOffsetT = 52; - pub const VT_TESTF: ::flatbuffers::VOffsetT = 54; - pub const VT_TESTF2: ::flatbuffers::VOffsetT = 56; - pub const VT_TESTF3: ::flatbuffers::VOffsetT = 58; - pub const VT_TESTARRAYOFSTRING2: ::flatbuffers::VOffsetT = 60; - pub const VT_TESTARRAYOFSORTEDSTRUCT: ::flatbuffers::VOffsetT = 62; - pub const VT_FLEX: ::flatbuffers::VOffsetT = 64; - pub const VT_TEST5: ::flatbuffers::VOffsetT = 66; - pub const VT_VECTOR_OF_LONGS: ::flatbuffers::VOffsetT = 68; - pub const VT_VECTOR_OF_DOUBLES: ::flatbuffers::VOffsetT = 70; - pub const VT_PARENT_NAMESPACE_TEST: ::flatbuffers::VOffsetT = 72; - pub const VT_VECTOR_OF_REFERRABLES: ::flatbuffers::VOffsetT = 74; - pub const VT_SINGLE_WEAK_REFERENCE: ::flatbuffers::VOffsetT = 76; - pub const VT_VECTOR_OF_WEAK_REFERENCES: ::flatbuffers::VOffsetT = 78; - pub const VT_VECTOR_OF_STRONG_REFERRABLES: ::flatbuffers::VOffsetT = 80; - pub const VT_CO_OWNING_REFERENCE: ::flatbuffers::VOffsetT = 82; - pub const VT_VECTOR_OF_CO_OWNING_REFERENCES: ::flatbuffers::VOffsetT = 84; - pub const VT_NON_OWNING_REFERENCE: ::flatbuffers::VOffsetT = 86; - pub const VT_VECTOR_OF_NON_OWNING_REFERENCES: ::flatbuffers::VOffsetT = 88; - pub const VT_ANY_UNIQUE_TYPE: ::flatbuffers::VOffsetT = 90; - pub const VT_ANY_UNIQUE: ::flatbuffers::VOffsetT = 92; - pub const VT_ANY_AMBIGUOUS_TYPE: ::flatbuffers::VOffsetT = 94; - pub const VT_ANY_AMBIGUOUS: ::flatbuffers::VOffsetT = 96; - pub const VT_VECTOR_OF_ENUMS: ::flatbuffers::VOffsetT = 98; - pub const VT_SIGNED_ENUM: ::flatbuffers::VOffsetT = 100; - pub const VT_TESTREQUIREDNESTEDFLATBUFFER: ::flatbuffers::VOffsetT = 102; - pub const VT_SCALAR_KEY_SORTED_TABLES: ::flatbuffers::VOffsetT = 104; - pub const VT_NATIVE_INLINE: ::flatbuffers::VOffsetT = 106; - pub const VT_LONG_ENUM_NON_ENUM_DEFAULT: ::flatbuffers::VOffsetT = 108; - pub const VT_LONG_ENUM_NORMAL_DEFAULT: ::flatbuffers::VOffsetT = 110; - pub const VT_NAN_DEFAULT: ::flatbuffers::VOffsetT = 112; - pub const VT_INF_DEFAULT: ::flatbuffers::VOffsetT = 114; - pub const VT_POSITIVE_INF_DEFAULT: ::flatbuffers::VOffsetT = 116; - pub const VT_INFINITY_DEFAULT: ::flatbuffers::VOffsetT = 118; - pub const VT_POSITIVE_INFINITY_DEFAULT: ::flatbuffers::VOffsetT = 120; - pub const VT_NEGATIVE_INF_DEFAULT: ::flatbuffers::VOffsetT = 122; - pub const VT_NEGATIVE_INFINITY_DEFAULT: ::flatbuffers::VOffsetT = 124; - pub const VT_DOUBLE_INF_DEFAULT: ::flatbuffers::VOffsetT = 126; + pub const VT_POS: ::flatbuffers::VOffsetT = 4; + pub const VT_MANA: ::flatbuffers::VOffsetT = 6; + pub const VT_HP: ::flatbuffers::VOffsetT = 8; + pub const VT_NAME: ::flatbuffers::VOffsetT = 10; + pub const VT_INVENTORY: ::flatbuffers::VOffsetT = 14; + pub const VT_COLOR: ::flatbuffers::VOffsetT = 16; + pub const VT_TEST_TYPE: ::flatbuffers::VOffsetT = 18; + pub const VT_TEST: ::flatbuffers::VOffsetT = 20; + pub const VT_TEST4: ::flatbuffers::VOffsetT = 22; + pub const VT_TESTARRAYOFSTRING: ::flatbuffers::VOffsetT = 24; + pub const VT_TESTARRAYOFTABLES: ::flatbuffers::VOffsetT = 26; + pub const VT_ENEMY: ::flatbuffers::VOffsetT = 28; + pub const VT_TESTNESTEDFLATBUFFER: ::flatbuffers::VOffsetT = 30; + pub const VT_TESTEMPTY: ::flatbuffers::VOffsetT = 32; + pub const VT_TESTBOOL: ::flatbuffers::VOffsetT = 34; + pub const VT_TESTHASHS32_FNV1: ::flatbuffers::VOffsetT = 36; + pub const VT_TESTHASHU32_FNV1: ::flatbuffers::VOffsetT = 38; + pub const VT_TESTHASHS64_FNV1: ::flatbuffers::VOffsetT = 40; + pub const VT_TESTHASHU64_FNV1: ::flatbuffers::VOffsetT = 42; + pub const VT_TESTHASHS32_FNV1A: ::flatbuffers::VOffsetT = 44; + pub const VT_TESTHASHU32_FNV1A: ::flatbuffers::VOffsetT = 46; + pub const VT_TESTHASHS64_FNV1A: ::flatbuffers::VOffsetT = 48; + pub const VT_TESTHASHU64_FNV1A: ::flatbuffers::VOffsetT = 50; + pub const VT_TESTARRAYOFBOOLS: ::flatbuffers::VOffsetT = 52; + pub const VT_TESTF: ::flatbuffers::VOffsetT = 54; + pub const VT_TESTF2: ::flatbuffers::VOffsetT = 56; + pub const VT_TESTF3: ::flatbuffers::VOffsetT = 58; + pub const VT_TESTARRAYOFSTRING2: ::flatbuffers::VOffsetT = 60; + pub const VT_TESTARRAYOFSORTEDSTRUCT: ::flatbuffers::VOffsetT = 62; + pub const VT_FLEX: ::flatbuffers::VOffsetT = 64; + pub const VT_TEST5: ::flatbuffers::VOffsetT = 66; + pub const VT_VECTOR_OF_LONGS: ::flatbuffers::VOffsetT = 68; + pub const VT_VECTOR_OF_DOUBLES: ::flatbuffers::VOffsetT = 70; + pub const VT_PARENT_NAMESPACE_TEST: ::flatbuffers::VOffsetT = 72; + pub const VT_VECTOR_OF_REFERRABLES: ::flatbuffers::VOffsetT = 74; + pub const VT_SINGLE_WEAK_REFERENCE: ::flatbuffers::VOffsetT = 76; + pub const VT_VECTOR_OF_WEAK_REFERENCES: ::flatbuffers::VOffsetT = 78; + pub const VT_VECTOR_OF_STRONG_REFERRABLES: ::flatbuffers::VOffsetT = 80; + pub const VT_CO_OWNING_REFERENCE: ::flatbuffers::VOffsetT = 82; + pub const VT_VECTOR_OF_CO_OWNING_REFERENCES: ::flatbuffers::VOffsetT = 84; + pub const VT_NON_OWNING_REFERENCE: ::flatbuffers::VOffsetT = 86; + pub const VT_VECTOR_OF_NON_OWNING_REFERENCES: ::flatbuffers::VOffsetT = 88; + pub const VT_ANY_UNIQUE_TYPE: ::flatbuffers::VOffsetT = 90; + pub const VT_ANY_UNIQUE: ::flatbuffers::VOffsetT = 92; + pub const VT_ANY_AMBIGUOUS_TYPE: ::flatbuffers::VOffsetT = 94; + pub const VT_ANY_AMBIGUOUS: ::flatbuffers::VOffsetT = 96; + pub const VT_VECTOR_OF_ENUMS: ::flatbuffers::VOffsetT = 98; + pub const VT_SIGNED_ENUM: ::flatbuffers::VOffsetT = 100; + pub const VT_TESTREQUIREDNESTEDFLATBUFFER: ::flatbuffers::VOffsetT = 102; + pub const VT_SCALAR_KEY_SORTED_TABLES: ::flatbuffers::VOffsetT = 104; + pub const VT_NATIVE_INLINE: ::flatbuffers::VOffsetT = 106; + pub const VT_LONG_ENUM_NON_ENUM_DEFAULT: ::flatbuffers::VOffsetT = 108; + pub const VT_LONG_ENUM_NORMAL_DEFAULT: ::flatbuffers::VOffsetT = 110; + pub const VT_NAN_DEFAULT: ::flatbuffers::VOffsetT = 112; + pub const VT_INF_DEFAULT: ::flatbuffers::VOffsetT = 114; + pub const VT_POSITIVE_INF_DEFAULT: ::flatbuffers::VOffsetT = 116; + pub const VT_INFINITY_DEFAULT: ::flatbuffers::VOffsetT = 118; + pub const VT_POSITIVE_INFINITY_DEFAULT: ::flatbuffers::VOffsetT = 120; + pub const VT_NEGATIVE_INF_DEFAULT: ::flatbuffers::VOffsetT = 122; + pub const VT_NEGATIVE_INFINITY_DEFAULT: ::flatbuffers::VOffsetT = 124; + pub const VT_DOUBLE_INF_DEFAULT: ::flatbuffers::VOffsetT = 126; + + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Example.Monster" + } + + #[inline] + pub unsafe 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, A: ::flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args MonsterArgs<'args> + ) -> ::flatbuffers::WIPOffset> { + let mut builder = MonsterBuilder::new(_fbb); + builder.add_double_inf_default(args.double_inf_default); + builder.add_long_enum_normal_default(args.long_enum_normal_default); + builder.add_long_enum_non_enum_default(args.long_enum_non_enum_default); + builder.add_non_owning_reference(args.non_owning_reference); + builder.add_co_owning_reference(args.co_owning_reference); + builder.add_single_weak_reference(args.single_weak_reference); + builder.add_testhashu64_fnv1a(args.testhashu64_fnv1a); + builder.add_testhashs64_fnv1a(args.testhashs64_fnv1a); + builder.add_testhashu64_fnv1(args.testhashu64_fnv1); + builder.add_testhashs64_fnv1(args.testhashs64_fnv1); + builder.add_negative_infinity_default(args.negative_infinity_default); + builder.add_negative_inf_default(args.negative_inf_default); + builder.add_positive_infinity_default(args.positive_infinity_default); + builder.add_infinity_default(args.infinity_default); + builder.add_positive_inf_default(args.positive_inf_default); + builder.add_inf_default(args.inf_default); + builder.add_nan_default(args.nan_default); + if let Some(x) = args.native_inline { builder.add_native_inline(x); } + if let Some(x) = args.scalar_key_sorted_tables { builder.add_scalar_key_sorted_tables(x); } + if let Some(x) = args.testrequirednestedflatbuffer { builder.add_testrequirednestedflatbuffer(x); } + if let Some(x) = args.vector_of_enums { builder.add_vector_of_enums(x); } + if let Some(x) = args.any_ambiguous { builder.add_any_ambiguous(x); } + if let Some(x) = args.any_unique { builder.add_any_unique(x); } + if let Some(x) = args.vector_of_non_owning_references { builder.add_vector_of_non_owning_references(x); } + if let Some(x) = args.vector_of_co_owning_references { builder.add_vector_of_co_owning_references(x); } + if let Some(x) = args.vector_of_strong_referrables { builder.add_vector_of_strong_referrables(x); } + if let Some(x) = args.vector_of_weak_references { builder.add_vector_of_weak_references(x); } + if let Some(x) = args.vector_of_referrables { builder.add_vector_of_referrables(x); } + if let Some(x) = args.parent_namespace_test { builder.add_parent_namespace_test(x); } + if let Some(x) = args.vector_of_doubles { builder.add_vector_of_doubles(x); } + if let Some(x) = args.vector_of_longs { builder.add_vector_of_longs(x); } + if let Some(x) = args.test5 { builder.add_test5(x); } + if let Some(x) = args.flex { builder.add_flex(x); } + if let Some(x) = args.testarrayofsortedstruct { builder.add_testarrayofsortedstruct(x); } + if let Some(x) = args.testarrayofstring2 { builder.add_testarrayofstring2(x); } + builder.add_testf3(args.testf3); + builder.add_testf2(args.testf2); + builder.add_testf(args.testf); + if let Some(x) = args.testarrayofbools { builder.add_testarrayofbools(x); } + builder.add_testhashu32_fnv1a(args.testhashu32_fnv1a); + builder.add_testhashs32_fnv1a(args.testhashs32_fnv1a); + builder.add_testhashu32_fnv1(args.testhashu32_fnv1); + builder.add_testhashs32_fnv1(args.testhashs32_fnv1); + if let Some(x) = args.testempty { builder.add_testempty(x); } + if let Some(x) = args.testnestedflatbuffer { builder.add_testnestedflatbuffer(x); } + if let Some(x) = args.enemy { builder.add_enemy(x); } + if let Some(x) = args.testarrayoftables { builder.add_testarrayoftables(x); } + if let Some(x) = args.testarrayofstring { builder.add_testarrayofstring(x); } + if let Some(x) = args.test4 { builder.add_test4(x); } + if let Some(x) = args.test { builder.add_test(x); } + if let Some(x) = args.inventory { builder.add_inventory(x); } + if let Some(x) = args.name { builder.add_name(x); } + if let Some(x) = args.pos { builder.add_pos(x); } + builder.add_hp(args.hp); + builder.add_mana(args.mana); + builder.add_signed_enum(args.signed_enum); + builder.add_any_ambiguous_type(args.any_ambiguous_type); + builder.add_any_unique_type(args.any_unique_type); + builder.add_testbool(args.testbool); + builder.add_test_type(args.test_type); + builder.add_color(args.color); + builder.finish() + } + + pub fn unpack(&self) -> MonsterT { + let pos = self.pos().map(|x| { + x.unpack() + }); + let mana = self.mana(); + let hp = self.hp(); + let name = { + let x = self.name(); + alloc::string::ToString::to_string(x) + }; + let inventory = self.inventory().map(|x| { + x.into_iter().collect() + }); + let color = self.color(); + let test = match self.test_type() { + Any::NONE => AnyT::NONE, + Any::Monster => AnyT::Monster(alloc::boxed::Box::new( + self.test_as_monster() + .expect("Invalid union table, expected `Any::Monster`.") + .unpack() + )), + Any::TestSimpleTableWithEnum => AnyT::TestSimpleTableWithEnum(alloc::boxed::Box::new( + self.test_as_test_simple_table_with_enum() + .expect("Invalid union table, expected `Any::TestSimpleTableWithEnum`.") + .unpack() + )), + Any::MyGame_Example2_Monster => AnyT::MyGameExample2Monster(alloc::boxed::Box::new( + self.test_as_my_game_example_2_monster() + .expect("Invalid union table, expected `Any::MyGame_Example2_Monster`.") + .unpack() + )), + _ => AnyT::NONE, + }; + let test4 = self.test4().map(|x| { + x.iter().map(|t| t.unpack()).collect() + }); + let testarrayofstring = self.testarrayofstring().map(|x| { + x.iter().map(|s| alloc::string::ToString::to_string(s)).collect() + }); + let testarrayoftables = self.testarrayoftables().map(|x| { + x.iter().map(|t| t.unpack()).collect() + }); + let enemy = self.enemy().map(|x| { + alloc::boxed::Box::new(x.unpack()) + }); + let testnestedflatbuffer = self.testnestedflatbuffer().map(|x| { + x.into_iter().collect() + }); + let testempty = self.testempty().map(|x| { + alloc::boxed::Box::new(x.unpack()) + }); + let testbool = self.testbool(); + let testhashs32_fnv1 = self.testhashs32_fnv1(); + let testhashu32_fnv1 = self.testhashu32_fnv1(); + let testhashs64_fnv1 = self.testhashs64_fnv1(); + let testhashu64_fnv1 = self.testhashu64_fnv1(); + let testhashs32_fnv1a = self.testhashs32_fnv1a(); + let testhashu32_fnv1a = self.testhashu32_fnv1a(); + let testhashs64_fnv1a = self.testhashs64_fnv1a(); + let testhashu64_fnv1a = self.testhashu64_fnv1a(); + let testarrayofbools = self.testarrayofbools().map(|x| { + x.into_iter().collect() + }); + let testf = self.testf(); + let testf2 = self.testf2(); + let testf3 = self.testf3(); + let testarrayofstring2 = self.testarrayofstring2().map(|x| { + x.iter().map(|s| alloc::string::ToString::to_string(s)).collect() + }); + let testarrayofsortedstruct = self.testarrayofsortedstruct().map(|x| { + x.iter().map(|t| t.unpack()).collect() + }); + let flex = self.flex().map(|x| { + x.into_iter().collect() + }); + let test5 = self.test5().map(|x| { + x.iter().map(|t| t.unpack()).collect() + }); + let vector_of_longs = self.vector_of_longs().map(|x| { + x.into_iter().collect() + }); + let vector_of_doubles = self.vector_of_doubles().map(|x| { + x.into_iter().collect() + }); + let parent_namespace_test = self.parent_namespace_test().map(|x| { + alloc::boxed::Box::new(x.unpack()) + }); + let vector_of_referrables = self.vector_of_referrables().map(|x| { + x.iter().map(|t| t.unpack()).collect() + }); + let single_weak_reference = self.single_weak_reference(); + let vector_of_weak_references = self.vector_of_weak_references().map(|x| { + x.into_iter().collect() + }); + let vector_of_strong_referrables = self.vector_of_strong_referrables().map(|x| { + x.iter().map(|t| t.unpack()).collect() + }); + let co_owning_reference = self.co_owning_reference(); + let vector_of_co_owning_references = self.vector_of_co_owning_references().map(|x| { + x.into_iter().collect() + }); + let non_owning_reference = self.non_owning_reference(); + let vector_of_non_owning_references = self.vector_of_non_owning_references().map(|x| { + x.into_iter().collect() + }); + let any_unique = match self.any_unique_type() { + AnyUniqueAliases::NONE => AnyUniqueAliasesT::NONE, + AnyUniqueAliases::M => AnyUniqueAliasesT::M(alloc::boxed::Box::new( + self.any_unique_as_m() + .expect("Invalid union table, expected `AnyUniqueAliases::M`.") + .unpack() + )), + AnyUniqueAliases::TS => AnyUniqueAliasesT::TS(alloc::boxed::Box::new( + self.any_unique_as_ts() + .expect("Invalid union table, expected `AnyUniqueAliases::TS`.") + .unpack() + )), + AnyUniqueAliases::M2 => AnyUniqueAliasesT::M2(alloc::boxed::Box::new( + self.any_unique_as_m2() + .expect("Invalid union table, expected `AnyUniqueAliases::M2`.") + .unpack() + )), + _ => AnyUniqueAliasesT::NONE, + }; + let any_ambiguous = match self.any_ambiguous_type() { + AnyAmbiguousAliases::NONE => AnyAmbiguousAliasesT::NONE, + AnyAmbiguousAliases::M1 => AnyAmbiguousAliasesT::M1(alloc::boxed::Box::new( + self.any_ambiguous_as_m1() + .expect("Invalid union table, expected `AnyAmbiguousAliases::M1`.") + .unpack() + )), + AnyAmbiguousAliases::M2 => AnyAmbiguousAliasesT::M2(alloc::boxed::Box::new( + self.any_ambiguous_as_m2() + .expect("Invalid union table, expected `AnyAmbiguousAliases::M2`.") + .unpack() + )), + AnyAmbiguousAliases::M3 => AnyAmbiguousAliasesT::M3(alloc::boxed::Box::new( + self.any_ambiguous_as_m3() + .expect("Invalid union table, expected `AnyAmbiguousAliases::M3`.") + .unpack() + )), + _ => AnyAmbiguousAliasesT::NONE, + }; + let vector_of_enums = self.vector_of_enums().map(|x| { + x.into_iter().collect() + }); + let signed_enum = self.signed_enum(); + let testrequirednestedflatbuffer = self.testrequirednestedflatbuffer().map(|x| { + x.into_iter().collect() + }); + let scalar_key_sorted_tables = self.scalar_key_sorted_tables().map(|x| { + x.iter().map(|t| t.unpack()).collect() + }); + let native_inline = self.native_inline().map(|x| { + x.unpack() + }); + let long_enum_non_enum_default = self.long_enum_non_enum_default(); + let long_enum_normal_default = self.long_enum_normal_default(); + let nan_default = self.nan_default(); + let inf_default = self.inf_default(); + let positive_inf_default = self.positive_inf_default(); + let infinity_default = self.infinity_default(); + let positive_infinity_default = self.positive_infinity_default(); + let negative_inf_default = self.negative_inf_default(); + let negative_infinity_default = self.negative_infinity_default(); + let double_inf_default = self.double_inf_default(); + MonsterT { + pos, + mana, + hp, + name, + inventory, + color, + test, + test4, + testarrayofstring, + testarrayoftables, + enemy, + testnestedflatbuffer, + testempty, + testbool, + testhashs32_fnv1, + testhashu32_fnv1, + testhashs64_fnv1, + testhashu64_fnv1, + testhashs32_fnv1a, + testhashu32_fnv1a, + testhashs64_fnv1a, + testhashu64_fnv1a, + testarrayofbools, + testf, + testf2, + testf3, + testarrayofstring2, + testarrayofsortedstruct, + flex, + test5, + vector_of_longs, + vector_of_doubles, + parent_namespace_test, + vector_of_referrables, + single_weak_reference, + vector_of_weak_references, + vector_of_strong_referrables, + co_owning_reference, + vector_of_co_owning_references, + non_owning_reference, + vector_of_non_owning_references, + any_unique, + any_ambiguous, + vector_of_enums, + signed_enum, + testrequirednestedflatbuffer, + scalar_key_sorted_tables, + native_inline, + long_enum_non_enum_default, + long_enum_normal_default, + nan_default, + inf_default, + positive_inf_default, + infinity_default, + positive_infinity_default, + negative_inf_default, + negative_infinity_default, + double_inf_default, + } + } + + #[inline] + pub fn pos(&self) -> Option<&'a Vec3> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_POS, None)} + } + #[inline] + pub fn mana(&self) -> i16 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_MANA, Some(150)).unwrap()} + } + #[inline] + pub fn hp(&self) -> i16 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_HP, Some(100)).unwrap()} + } + #[inline] + pub fn name(&self) -> &'a str { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<&str>>(Monster::VT_NAME, None).unwrap()} + } + #[inline] + pub fn key_compare_less_than(&self, o: &Monster) -> bool { + self.name() < o.name() + } + + #[inline] + pub fn key_compare_with_value(&self, val: & str) -> ::core::cmp::Ordering { + let key = self.name(); + key.cmp(val) + } + #[inline] + pub fn inventory(&self) -> Option<::flatbuffers::Vector<'a, u8>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, u8>>>(Monster::VT_INVENTORY, None)} + } + #[inline] + pub fn color(&self) -> Color { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_COLOR, Some(Color::Blue)).unwrap()} + } + #[inline] + pub fn test_type(&self) -> Any { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TEST_TYPE, Some(Any::NONE)).unwrap()} + } + #[inline] + pub fn test(&self) -> Option<::flatbuffers::Table<'a>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Table<'a>>>(Monster::VT_TEST, None)} + } + #[inline] + pub fn test4(&self) -> Option<::flatbuffers::Vector<'a, Test>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, Test>>>(Monster::VT_TEST4, None)} + } + #[inline] + pub fn testarrayofstring(&self) -> Option<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset<&'a str>>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset<&'a str>>>>(Monster::VT_TESTARRAYOFSTRING, None)} + } + /// an example documentation comment: this will end up in the generated code + /// multiline too + #[inline] + pub fn testarrayoftables(&self) -> Option<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset>>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset>>>(Monster::VT_TESTARRAYOFTABLES, None)} + } + #[inline] + pub fn enemy(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset>(Monster::VT_ENEMY, None)} + } + #[inline] + pub fn testnestedflatbuffer(&self) -> Option<::flatbuffers::Vector<'a, u8>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, u8>>>(Monster::VT_TESTNESTEDFLATBUFFER, None)} + } + pub fn testnestedflatbuffer_nested_flatbuffer(&'a self) -> Option> { + self.testnestedflatbuffer().map(|data| { + use ::flatbuffers::Follow; + // Safety: + // Created from a valid Table for this object + // Which contains a valid flatbuffer in this slot + unsafe { <::flatbuffers::ForwardsUOffset>>::follow(data.bytes(), 0) } + }) + } + #[inline] + pub fn testempty(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset>(Monster::VT_TESTEMPTY, None)} + } + #[inline] + pub fn testbool(&self) -> bool { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TESTBOOL, Some(false)).unwrap()} + } + #[inline] + pub fn testhashs32_fnv1(&self) -> i32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TESTHASHS32_FNV1, Some(0)).unwrap()} + } + #[inline] + pub fn testhashu32_fnv1(&self) -> u32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TESTHASHU32_FNV1, Some(0)).unwrap()} + } + #[inline] + pub fn testhashs64_fnv1(&self) -> i64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TESTHASHS64_FNV1, Some(0)).unwrap()} + } + #[inline] + pub fn testhashu64_fnv1(&self) -> u64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TESTHASHU64_FNV1, Some(0)).unwrap()} + } + #[inline] + pub fn testhashs32_fnv1a(&self) -> i32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TESTHASHS32_FNV1A, Some(0)).unwrap()} + } + #[inline] + pub fn testhashu32_fnv1a(&self) -> u32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TESTHASHU32_FNV1A, Some(0)).unwrap()} + } + #[inline] + pub fn testhashs64_fnv1a(&self) -> i64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TESTHASHS64_FNV1A, Some(0)).unwrap()} + } + #[inline] + pub fn testhashu64_fnv1a(&self) -> u64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TESTHASHU64_FNV1A, Some(0)).unwrap()} + } + #[inline] + pub fn testarrayofbools(&self) -> Option<::flatbuffers::Vector<'a, bool>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, bool>>>(Monster::VT_TESTARRAYOFBOOLS, None)} + } + #[inline] + pub fn testf(&self) -> f32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TESTF, Some(3.14159)).unwrap()} + } + #[inline] + pub fn testf2(&self) -> f32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TESTF2, Some(3.0)).unwrap()} + } + #[inline] + pub fn testf3(&self) -> f32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TESTF3, Some(0.0)).unwrap()} + } + #[inline] + pub fn testarrayofstring2(&self) -> Option<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset<&'a str>>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset<&'a str>>>>(Monster::VT_TESTARRAYOFSTRING2, None)} + } + #[inline] + pub fn testarrayofsortedstruct(&self) -> Option<::flatbuffers::Vector<'a, Ability>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, Ability>>>(Monster::VT_TESTARRAYOFSORTEDSTRUCT, None)} + } + #[inline] + pub fn flex(&self) -> Option<::flatbuffers::Vector<'a, u8>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, u8>>>(Monster::VT_FLEX, None)} + } + #[inline] + pub fn test5(&self) -> Option<::flatbuffers::Vector<'a, Test>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, Test>>>(Monster::VT_TEST5, None)} + } + #[inline] + pub fn vector_of_longs(&self) -> Option<::flatbuffers::Vector<'a, i64>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, i64>>>(Monster::VT_VECTOR_OF_LONGS, None)} + } + #[inline] + pub fn vector_of_doubles(&self) -> Option<::flatbuffers::Vector<'a, f64>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, f64>>>(Monster::VT_VECTOR_OF_DOUBLES, None)} + } + #[inline] + pub fn parent_namespace_test(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset>(Monster::VT_PARENT_NAMESPACE_TEST, None)} + } + #[inline] + pub fn vector_of_referrables(&self) -> Option<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset>>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset>>>(Monster::VT_VECTOR_OF_REFERRABLES, None)} + } + #[inline] + pub fn single_weak_reference(&self) -> u64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_SINGLE_WEAK_REFERENCE, Some(0)).unwrap()} + } + #[inline] + pub fn vector_of_weak_references(&self) -> Option<::flatbuffers::Vector<'a, u64>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, u64>>>(Monster::VT_VECTOR_OF_WEAK_REFERENCES, None)} + } + #[inline] + pub fn vector_of_strong_referrables(&self) -> Option<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset>>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset>>>(Monster::VT_VECTOR_OF_STRONG_REFERRABLES, None)} + } + #[inline] + pub fn co_owning_reference(&self) -> u64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_CO_OWNING_REFERENCE, Some(0)).unwrap()} + } + #[inline] + pub fn vector_of_co_owning_references(&self) -> Option<::flatbuffers::Vector<'a, u64>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, u64>>>(Monster::VT_VECTOR_OF_CO_OWNING_REFERENCES, None)} + } + #[inline] + pub fn non_owning_reference(&self) -> u64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_NON_OWNING_REFERENCE, Some(0)).unwrap()} + } + #[inline] + pub fn vector_of_non_owning_references(&self) -> Option<::flatbuffers::Vector<'a, u64>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, u64>>>(Monster::VT_VECTOR_OF_NON_OWNING_REFERENCES, None)} + } + #[inline] + pub fn any_unique_type(&self) -> AnyUniqueAliases { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_ANY_UNIQUE_TYPE, Some(AnyUniqueAliases::NONE)).unwrap()} + } + #[inline] + pub fn any_unique(&self) -> Option<::flatbuffers::Table<'a>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Table<'a>>>(Monster::VT_ANY_UNIQUE, None)} + } + #[inline] + pub fn any_ambiguous_type(&self) -> AnyAmbiguousAliases { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_ANY_AMBIGUOUS_TYPE, Some(AnyAmbiguousAliases::NONE)).unwrap()} + } + #[inline] + pub fn any_ambiguous(&self) -> Option<::flatbuffers::Table<'a>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Table<'a>>>(Monster::VT_ANY_AMBIGUOUS, None)} + } + #[inline] + pub fn vector_of_enums(&self) -> Option<::flatbuffers::Vector<'a, Color>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, Color>>>(Monster::VT_VECTOR_OF_ENUMS, None)} + } + #[inline] + pub fn signed_enum(&self) -> Race { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_SIGNED_ENUM, Some(Race::None)).unwrap()} + } + #[inline] + pub fn testrequirednestedflatbuffer(&self) -> Option<::flatbuffers::Vector<'a, u8>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, u8>>>(Monster::VT_TESTREQUIREDNESTEDFLATBUFFER, None)} + } + pub fn testrequirednestedflatbuffer_nested_flatbuffer(&'a self) -> Option> { + self.testrequirednestedflatbuffer().map(|data| { + use ::flatbuffers::Follow; + // Safety: + // Created from a valid Table for this object + // Which contains a valid flatbuffer in this slot + unsafe { <::flatbuffers::ForwardsUOffset>>::follow(data.bytes(), 0) } + }) + } + #[inline] + pub fn scalar_key_sorted_tables(&self) -> Option<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset>>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset>>>(Monster::VT_SCALAR_KEY_SORTED_TABLES, None)} + } + #[inline] + pub fn native_inline(&self) -> Option<&'a Test> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_NATIVE_INLINE, None)} + } + #[inline] + pub fn long_enum_non_enum_default(&self) -> LongEnum { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_LONG_ENUM_NON_ENUM_DEFAULT, Some(Default::default())).unwrap()} + } + #[inline] + pub fn long_enum_normal_default(&self) -> LongEnum { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_LONG_ENUM_NORMAL_DEFAULT, Some(LongEnum::LongOne)).unwrap()} + } + #[inline] + pub fn nan_default(&self) -> f32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_NAN_DEFAULT, Some(f32::NAN)).unwrap()} + } + #[inline] + pub fn inf_default(&self) -> f32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_INF_DEFAULT, Some(f32::INFINITY)).unwrap()} + } + #[inline] + pub fn positive_inf_default(&self) -> f32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_POSITIVE_INF_DEFAULT, Some(f32::INFINITY)).unwrap()} + } + #[inline] + pub fn infinity_default(&self) -> f32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_INFINITY_DEFAULT, Some(f32::INFINITY)).unwrap()} + } + #[inline] + pub fn positive_infinity_default(&self) -> f32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_POSITIVE_INFINITY_DEFAULT, Some(f32::INFINITY)).unwrap()} + } + #[inline] + pub fn negative_inf_default(&self) -> f32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_NEGATIVE_INF_DEFAULT, Some(f32::NEG_INFINITY)).unwrap()} + } + #[inline] + pub fn negative_infinity_default(&self) -> f32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_NEGATIVE_INFINITY_DEFAULT, Some(f32::NEG_INFINITY)).unwrap()} + } + #[inline] + pub fn double_inf_default(&self) -> f64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_DOUBLE_INF_DEFAULT, Some(f64::INFINITY)).unwrap()} + } + #[inline] + #[allow(non_snake_case)] + pub fn test_as_monster(&self) -> Option> { + if self.test_type() == Any::Monster { + self.test().map(|t| { + // Safety: + // Created from a valid Table for this object + // Which contains a valid union in this slot + unsafe { Monster::init_from_table(t) } + }) + } else { + None + } + } + + #[inline] + #[allow(non_snake_case)] + pub fn test_as_test_simple_table_with_enum(&self) -> Option> { + if self.test_type() == Any::TestSimpleTableWithEnum { + self.test().map(|t| { + // Safety: + // Created from a valid Table for this object + // Which contains a valid union in this slot + unsafe { TestSimpleTableWithEnum::init_from_table(t) } + }) + } else { + None + } + } + + #[inline] + #[allow(non_snake_case)] + pub fn test_as_my_game_example_2_monster(&self) -> Option> { + if self.test_type() == Any::MyGame_Example2_Monster { + self.test().map(|t| { + // Safety: + // Created from a valid Table for this object + // Which contains a valid union in this slot + unsafe { super::example_2::Monster::init_from_table(t) } + }) + } else { + None + } + } + + #[inline] + #[allow(non_snake_case)] + pub fn any_unique_as_m(&self) -> Option> { + if self.any_unique_type() == AnyUniqueAliases::M { + self.any_unique().map(|t| { + // Safety: + // Created from a valid Table for this object + // Which contains a valid union in this slot + unsafe { Monster::init_from_table(t) } + }) + } else { + None + } + } + + #[inline] + #[allow(non_snake_case)] + pub fn any_unique_as_ts(&self) -> Option> { + if self.any_unique_type() == AnyUniqueAliases::TS { + self.any_unique().map(|t| { + // Safety: + // Created from a valid Table for this object + // Which contains a valid union in this slot + unsafe { TestSimpleTableWithEnum::init_from_table(t) } + }) + } else { + None + } + } + + #[inline] + #[allow(non_snake_case)] + pub fn any_unique_as_m2(&self) -> Option> { + if self.any_unique_type() == AnyUniqueAliases::M2 { + self.any_unique().map(|t| { + // Safety: + // Created from a valid Table for this object + // Which contains a valid union in this slot + unsafe { super::example_2::Monster::init_from_table(t) } + }) + } else { + None + } + } + + #[inline] + #[allow(non_snake_case)] + pub fn any_ambiguous_as_m1(&self) -> Option> { + if self.any_ambiguous_type() == AnyAmbiguousAliases::M1 { + self.any_ambiguous().map(|t| { + // Safety: + // Created from a valid Table for this object + // Which contains a valid union in this slot + unsafe { Monster::init_from_table(t) } + }) + } else { + None + } + } + + #[inline] + #[allow(non_snake_case)] + pub fn any_ambiguous_as_m2(&self) -> Option> { + if self.any_ambiguous_type() == AnyAmbiguousAliases::M2 { + self.any_ambiguous().map(|t| { + // Safety: + // Created from a valid Table for this object + // Which contains a valid union in this slot + unsafe { Monster::init_from_table(t) } + }) + } else { + None + } + } + + #[inline] + #[allow(non_snake_case)] + pub fn any_ambiguous_as_m3(&self) -> Option> { + if self.any_ambiguous_type() == AnyAmbiguousAliases::M3 { + self.any_ambiguous().map(|t| { + // Safety: + // Created from a valid Table for this object + // Which contains a valid union in this slot + unsafe { Monster::init_from_table(t) } + }) + } else { + None + } + } - pub const fn get_fully_qualified_name() -> &'static str { - "MyGame.Example.Monster" - } - - #[inline] - pub unsafe 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, A: ::flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args MonsterArgs<'args> - ) -> ::flatbuffers::WIPOffset> { - let mut builder = MonsterBuilder::new(_fbb); - builder.add_double_inf_default(args.double_inf_default); - builder.add_long_enum_normal_default(args.long_enum_normal_default); - builder.add_long_enum_non_enum_default(args.long_enum_non_enum_default); - builder.add_non_owning_reference(args.non_owning_reference); - builder.add_co_owning_reference(args.co_owning_reference); - builder.add_single_weak_reference(args.single_weak_reference); - builder.add_testhashu64_fnv1a(args.testhashu64_fnv1a); - builder.add_testhashs64_fnv1a(args.testhashs64_fnv1a); - builder.add_testhashu64_fnv1(args.testhashu64_fnv1); - builder.add_testhashs64_fnv1(args.testhashs64_fnv1); - builder.add_negative_infinity_default(args.negative_infinity_default); - builder.add_negative_inf_default(args.negative_inf_default); - builder.add_positive_infinity_default(args.positive_infinity_default); - builder.add_infinity_default(args.infinity_default); - builder.add_positive_inf_default(args.positive_inf_default); - builder.add_inf_default(args.inf_default); - builder.add_nan_default(args.nan_default); - if let Some(x) = args.native_inline { builder.add_native_inline(x); } - if let Some(x) = args.scalar_key_sorted_tables { builder.add_scalar_key_sorted_tables(x); } - if let Some(x) = args.testrequirednestedflatbuffer { builder.add_testrequirednestedflatbuffer(x); } - if let Some(x) = args.vector_of_enums { builder.add_vector_of_enums(x); } - if let Some(x) = args.any_ambiguous { builder.add_any_ambiguous(x); } - if let Some(x) = args.any_unique { builder.add_any_unique(x); } - if let Some(x) = args.vector_of_non_owning_references { builder.add_vector_of_non_owning_references(x); } - if let Some(x) = args.vector_of_co_owning_references { builder.add_vector_of_co_owning_references(x); } - if let Some(x) = args.vector_of_strong_referrables { builder.add_vector_of_strong_referrables(x); } - if let Some(x) = args.vector_of_weak_references { builder.add_vector_of_weak_references(x); } - if let Some(x) = args.vector_of_referrables { builder.add_vector_of_referrables(x); } - if let Some(x) = args.parent_namespace_test { builder.add_parent_namespace_test(x); } - if let Some(x) = args.vector_of_doubles { builder.add_vector_of_doubles(x); } - if let Some(x) = args.vector_of_longs { builder.add_vector_of_longs(x); } - if let Some(x) = args.test5 { builder.add_test5(x); } - if let Some(x) = args.flex { builder.add_flex(x); } - if let Some(x) = args.testarrayofsortedstruct { builder.add_testarrayofsortedstruct(x); } - if let Some(x) = args.testarrayofstring2 { builder.add_testarrayofstring2(x); } - builder.add_testf3(args.testf3); - builder.add_testf2(args.testf2); - builder.add_testf(args.testf); - if let Some(x) = args.testarrayofbools { builder.add_testarrayofbools(x); } - builder.add_testhashu32_fnv1a(args.testhashu32_fnv1a); - builder.add_testhashs32_fnv1a(args.testhashs32_fnv1a); - builder.add_testhashu32_fnv1(args.testhashu32_fnv1); - builder.add_testhashs32_fnv1(args.testhashs32_fnv1); - if let Some(x) = args.testempty { builder.add_testempty(x); } - if let Some(x) = args.testnestedflatbuffer { builder.add_testnestedflatbuffer(x); } - if let Some(x) = args.enemy { builder.add_enemy(x); } - if let Some(x) = args.testarrayoftables { builder.add_testarrayoftables(x); } - if let Some(x) = args.testarrayofstring { builder.add_testarrayofstring(x); } - if let Some(x) = args.test4 { builder.add_test4(x); } - if let Some(x) = args.test { builder.add_test(x); } - if let Some(x) = args.inventory { builder.add_inventory(x); } - if let Some(x) = args.name { builder.add_name(x); } - if let Some(x) = args.pos { builder.add_pos(x); } - builder.add_hp(args.hp); - builder.add_mana(args.mana); - builder.add_signed_enum(args.signed_enum); - builder.add_any_ambiguous_type(args.any_ambiguous_type); - builder.add_any_unique_type(args.any_unique_type); - builder.add_testbool(args.testbool); - builder.add_test_type(args.test_type); - builder.add_color(args.color); - builder.finish() - } - - pub fn unpack(&self) -> MonsterT { - let pos = self.pos().map(|x| { - x.unpack() - }); - let mana = self.mana(); - let hp = self.hp(); - let name = { - let x = self.name(); - alloc::string::ToString::to_string(x) - }; - let inventory = self.inventory().map(|x| { - x.into_iter().collect() - }); - let color = self.color(); - let test = match self.test_type() { - Any::NONE => AnyT::NONE, - Any::Monster => AnyT::Monster(alloc::boxed::Box::new( - self.test_as_monster() - .expect("Invalid union table, expected `Any::Monster`.") - .unpack() - )), - Any::TestSimpleTableWithEnum => AnyT::TestSimpleTableWithEnum(alloc::boxed::Box::new( - self.test_as_test_simple_table_with_enum() - .expect("Invalid union table, expected `Any::TestSimpleTableWithEnum`.") - .unpack() - )), - Any::MyGame_Example2_Monster => AnyT::MyGameExample2Monster(alloc::boxed::Box::new( - self.test_as_my_game_example_2_monster() - .expect("Invalid union table, expected `Any::MyGame_Example2_Monster`.") - .unpack() - )), - _ => AnyT::NONE, - }; - let test4 = self.test4().map(|x| { - x.iter().map(|t| t.unpack()).collect() - }); - let testarrayofstring = self.testarrayofstring().map(|x| { - x.iter().map(|s| alloc::string::ToString::to_string(s)).collect() - }); - let testarrayoftables = self.testarrayoftables().map(|x| { - x.iter().map(|t| t.unpack()).collect() - }); - let enemy = self.enemy().map(|x| { - alloc::boxed::Box::new(x.unpack()) - }); - let testnestedflatbuffer = self.testnestedflatbuffer().map(|x| { - x.into_iter().collect() - }); - let testempty = self.testempty().map(|x| { - alloc::boxed::Box::new(x.unpack()) - }); - let testbool = self.testbool(); - let testhashs32_fnv1 = self.testhashs32_fnv1(); - let testhashu32_fnv1 = self.testhashu32_fnv1(); - let testhashs64_fnv1 = self.testhashs64_fnv1(); - let testhashu64_fnv1 = self.testhashu64_fnv1(); - let testhashs32_fnv1a = self.testhashs32_fnv1a(); - let testhashu32_fnv1a = self.testhashu32_fnv1a(); - let testhashs64_fnv1a = self.testhashs64_fnv1a(); - let testhashu64_fnv1a = self.testhashu64_fnv1a(); - let testarrayofbools = self.testarrayofbools().map(|x| { - x.into_iter().collect() - }); - let testf = self.testf(); - let testf2 = self.testf2(); - let testf3 = self.testf3(); - let testarrayofstring2 = self.testarrayofstring2().map(|x| { - x.iter().map(|s| alloc::string::ToString::to_string(s)).collect() - }); - let testarrayofsortedstruct = self.testarrayofsortedstruct().map(|x| { - x.iter().map(|t| t.unpack()).collect() - }); - let flex = self.flex().map(|x| { - x.into_iter().collect() - }); - let test5 = self.test5().map(|x| { - x.iter().map(|t| t.unpack()).collect() - }); - let vector_of_longs = self.vector_of_longs().map(|x| { - x.into_iter().collect() - }); - let vector_of_doubles = self.vector_of_doubles().map(|x| { - x.into_iter().collect() - }); - let parent_namespace_test = self.parent_namespace_test().map(|x| { - alloc::boxed::Box::new(x.unpack()) - }); - let vector_of_referrables = self.vector_of_referrables().map(|x| { - x.iter().map(|t| t.unpack()).collect() - }); - let single_weak_reference = self.single_weak_reference(); - let vector_of_weak_references = self.vector_of_weak_references().map(|x| { - x.into_iter().collect() - }); - let vector_of_strong_referrables = self.vector_of_strong_referrables().map(|x| { - x.iter().map(|t| t.unpack()).collect() - }); - let co_owning_reference = self.co_owning_reference(); - let vector_of_co_owning_references = self.vector_of_co_owning_references().map(|x| { - x.into_iter().collect() - }); - let non_owning_reference = self.non_owning_reference(); - let vector_of_non_owning_references = self.vector_of_non_owning_references().map(|x| { - x.into_iter().collect() - }); - let any_unique = match self.any_unique_type() { - AnyUniqueAliases::NONE => AnyUniqueAliasesT::NONE, - AnyUniqueAliases::M => AnyUniqueAliasesT::M(alloc::boxed::Box::new( - self.any_unique_as_m() - .expect("Invalid union table, expected `AnyUniqueAliases::M`.") - .unpack() - )), - AnyUniqueAliases::TS => AnyUniqueAliasesT::TS(alloc::boxed::Box::new( - self.any_unique_as_ts() - .expect("Invalid union table, expected `AnyUniqueAliases::TS`.") - .unpack() - )), - AnyUniqueAliases::M2 => AnyUniqueAliasesT::M2(alloc::boxed::Box::new( - self.any_unique_as_m2() - .expect("Invalid union table, expected `AnyUniqueAliases::M2`.") - .unpack() - )), - _ => AnyUniqueAliasesT::NONE, - }; - let any_ambiguous = match self.any_ambiguous_type() { - AnyAmbiguousAliases::NONE => AnyAmbiguousAliasesT::NONE, - AnyAmbiguousAliases::M1 => AnyAmbiguousAliasesT::M1(alloc::boxed::Box::new( - self.any_ambiguous_as_m1() - .expect("Invalid union table, expected `AnyAmbiguousAliases::M1`.") - .unpack() - )), - AnyAmbiguousAliases::M2 => AnyAmbiguousAliasesT::M2(alloc::boxed::Box::new( - self.any_ambiguous_as_m2() - .expect("Invalid union table, expected `AnyAmbiguousAliases::M2`.") - .unpack() - )), - AnyAmbiguousAliases::M3 => AnyAmbiguousAliasesT::M3(alloc::boxed::Box::new( - self.any_ambiguous_as_m3() - .expect("Invalid union table, expected `AnyAmbiguousAliases::M3`.") - .unpack() - )), - _ => AnyAmbiguousAliasesT::NONE, - }; - let vector_of_enums = self.vector_of_enums().map(|x| { - x.into_iter().collect() - }); - let signed_enum = self.signed_enum(); - let testrequirednestedflatbuffer = self.testrequirednestedflatbuffer().map(|x| { - x.into_iter().collect() - }); - let scalar_key_sorted_tables = self.scalar_key_sorted_tables().map(|x| { - x.iter().map(|t| t.unpack()).collect() - }); - let native_inline = self.native_inline().map(|x| { - x.unpack() - }); - let long_enum_non_enum_default = self.long_enum_non_enum_default(); - let long_enum_normal_default = self.long_enum_normal_default(); - let nan_default = self.nan_default(); - let inf_default = self.inf_default(); - let positive_inf_default = self.positive_inf_default(); - let infinity_default = self.infinity_default(); - let positive_infinity_default = self.positive_infinity_default(); - let negative_inf_default = self.negative_inf_default(); - let negative_infinity_default = self.negative_infinity_default(); - let double_inf_default = self.double_inf_default(); - MonsterT { - pos, - mana, - hp, - name, - inventory, - color, - test, - test4, - testarrayofstring, - testarrayoftables, - enemy, - testnestedflatbuffer, - testempty, - testbool, - testhashs32_fnv1, - testhashu32_fnv1, - testhashs64_fnv1, - testhashu64_fnv1, - testhashs32_fnv1a, - testhashu32_fnv1a, - testhashs64_fnv1a, - testhashu64_fnv1a, - testarrayofbools, - testf, - testf2, - testf3, - testarrayofstring2, - testarrayofsortedstruct, - flex, - test5, - vector_of_longs, - vector_of_doubles, - parent_namespace_test, - vector_of_referrables, - single_weak_reference, - vector_of_weak_references, - vector_of_strong_referrables, - co_owning_reference, - vector_of_co_owning_references, - non_owning_reference, - vector_of_non_owning_references, - any_unique, - any_ambiguous, - vector_of_enums, - signed_enum, - testrequirednestedflatbuffer, - scalar_key_sorted_tables, - native_inline, - long_enum_non_enum_default, - long_enum_normal_default, - nan_default, - inf_default, - positive_inf_default, - infinity_default, - positive_infinity_default, - negative_inf_default, - negative_infinity_default, - double_inf_default, - } - } - - #[inline] - pub fn pos(&self) -> Option<&'a Vec3> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_POS, None)} - } - - #[inline] - pub fn mana(&self) -> i16 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_MANA, Some(150)).unwrap()} - } - - #[inline] - pub fn hp(&self) -> i16 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_HP, Some(100)).unwrap()} - } - - #[inline] - pub fn name(&self) -> &'a str { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<&str>>(Monster::VT_NAME, None).unwrap()} - } - - #[inline] - pub fn key_compare_less_than(&self, o: &Monster) -> bool { - self.name() < o.name() - } - - #[inline] - pub fn key_compare_with_value(&self, val: & str) -> ::core::cmp::Ordering { - let key = self.name(); - key.cmp(val) - } - - #[inline] - pub fn inventory(&self) -> Option<::flatbuffers::Vector<'a, u8>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, u8>>>(Monster::VT_INVENTORY, None)} - } - - #[inline] - pub fn color(&self) -> Color { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_COLOR, Some(Color::Blue)).unwrap()} - } - - #[inline] - pub fn test_type(&self) -> Any { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_TEST_TYPE, Some(Any::NONE)).unwrap()} - } - - #[inline] - pub fn test(&self) -> Option<::flatbuffers::Table<'a>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Table<'a>>>(Monster::VT_TEST, None)} - } - - #[inline] - pub fn test4(&self) -> Option<::flatbuffers::Vector<'a, Test>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, Test>>>(Monster::VT_TEST4, None)} - } - - #[inline] - pub fn testarrayofstring(&self) -> Option<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset<&'a str>>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset<&'a str>>>>(Monster::VT_TESTARRAYOFSTRING, None)} - } - - /// an example documentation comment: this will end up in the generated code - /// multiline too - #[inline] - pub fn testarrayoftables(&self) -> Option<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset>>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset>>>(Monster::VT_TESTARRAYOFTABLES, None)} - } - - #[inline] - pub fn enemy(&self) -> Option> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset>(Monster::VT_ENEMY, None)} - } - - #[inline] - pub fn testnestedflatbuffer(&self) -> Option<::flatbuffers::Vector<'a, u8>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, u8>>>(Monster::VT_TESTNESTEDFLATBUFFER, None)} - } - - pub fn testnestedflatbuffer_nested_flatbuffer(&'a self) -> Option> { - self.testnestedflatbuffer().map(|data| { - use ::flatbuffers::Follow; - // Safety: - // Created from a valid Table for this object - // Which contains a valid flatbuffer in this slot - unsafe { <::flatbuffers::ForwardsUOffset>>::follow(data.bytes(), 0) } - }) - } - - #[inline] - pub fn testempty(&self) -> Option> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset>(Monster::VT_TESTEMPTY, None)} - } - - #[inline] - pub fn testbool(&self) -> bool { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_TESTBOOL, Some(false)).unwrap()} - } - - #[inline] - pub fn testhashs32_fnv1(&self) -> i32 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_TESTHASHS32_FNV1, Some(0)).unwrap()} - } - - #[inline] - pub fn testhashu32_fnv1(&self) -> u32 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_TESTHASHU32_FNV1, Some(0)).unwrap()} - } - - #[inline] - pub fn testhashs64_fnv1(&self) -> i64 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_TESTHASHS64_FNV1, Some(0)).unwrap()} - } - - #[inline] - pub fn testhashu64_fnv1(&self) -> u64 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_TESTHASHU64_FNV1, Some(0)).unwrap()} - } - - #[inline] - pub fn testhashs32_fnv1a(&self) -> i32 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_TESTHASHS32_FNV1A, Some(0)).unwrap()} - } - - #[inline] - pub fn testhashu32_fnv1a(&self) -> u32 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_TESTHASHU32_FNV1A, Some(0)).unwrap()} - } - - #[inline] - pub fn testhashs64_fnv1a(&self) -> i64 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_TESTHASHS64_FNV1A, Some(0)).unwrap()} - } - - #[inline] - pub fn testhashu64_fnv1a(&self) -> u64 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_TESTHASHU64_FNV1A, Some(0)).unwrap()} - } - - #[inline] - pub fn testarrayofbools(&self) -> Option<::flatbuffers::Vector<'a, bool>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, bool>>>(Monster::VT_TESTARRAYOFBOOLS, None)} - } - - #[inline] - pub fn testf(&self) -> f32 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_TESTF, Some(3.14159)).unwrap()} - } - - #[inline] - pub fn testf2(&self) -> f32 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_TESTF2, Some(3.0)).unwrap()} - } - - #[inline] - pub fn testf3(&self) -> f32 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_TESTF3, Some(0.0)).unwrap()} - } - - #[inline] - pub fn testarrayofstring2(&self) -> Option<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset<&'a str>>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset<&'a str>>>>(Monster::VT_TESTARRAYOFSTRING2, None)} - } - - #[inline] - pub fn testarrayofsortedstruct(&self) -> Option<::flatbuffers::Vector<'a, Ability>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, Ability>>>(Monster::VT_TESTARRAYOFSORTEDSTRUCT, None)} - } - - #[inline] - pub fn flex(&self) -> Option<::flatbuffers::Vector<'a, u8>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, u8>>>(Monster::VT_FLEX, None)} - } - - #[inline] - pub fn test5(&self) -> Option<::flatbuffers::Vector<'a, Test>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, Test>>>(Monster::VT_TEST5, None)} - } - - #[inline] - pub fn vector_of_longs(&self) -> Option<::flatbuffers::Vector<'a, i64>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, i64>>>(Monster::VT_VECTOR_OF_LONGS, None)} - } - - #[inline] - pub fn vector_of_doubles(&self) -> Option<::flatbuffers::Vector<'a, f64>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, f64>>>(Monster::VT_VECTOR_OF_DOUBLES, None)} - } - - #[inline] - pub fn parent_namespace_test(&self) -> Option> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset>(Monster::VT_PARENT_NAMESPACE_TEST, None)} - } - - #[inline] - pub fn vector_of_referrables(&self) -> Option<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset>>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset>>>(Monster::VT_VECTOR_OF_REFERRABLES, None)} - } - - #[inline] - pub fn single_weak_reference(&self) -> u64 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_SINGLE_WEAK_REFERENCE, Some(0)).unwrap()} - } - - #[inline] - pub fn vector_of_weak_references(&self) -> Option<::flatbuffers::Vector<'a, u64>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, u64>>>(Monster::VT_VECTOR_OF_WEAK_REFERENCES, None)} - } - - #[inline] - pub fn vector_of_strong_referrables(&self) -> Option<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset>>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset>>>(Monster::VT_VECTOR_OF_STRONG_REFERRABLES, None)} - } - - #[inline] - pub fn co_owning_reference(&self) -> u64 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_CO_OWNING_REFERENCE, Some(0)).unwrap()} - } - - #[inline] - pub fn vector_of_co_owning_references(&self) -> Option<::flatbuffers::Vector<'a, u64>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, u64>>>(Monster::VT_VECTOR_OF_CO_OWNING_REFERENCES, None)} - } - - #[inline] - pub fn non_owning_reference(&self) -> u64 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_NON_OWNING_REFERENCE, Some(0)).unwrap()} - } - - #[inline] - pub fn vector_of_non_owning_references(&self) -> Option<::flatbuffers::Vector<'a, u64>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, u64>>>(Monster::VT_VECTOR_OF_NON_OWNING_REFERENCES, None)} - } - - #[inline] - pub fn any_unique_type(&self) -> AnyUniqueAliases { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_ANY_UNIQUE_TYPE, Some(AnyUniqueAliases::NONE)).unwrap()} - } - - #[inline] - pub fn any_unique(&self) -> Option<::flatbuffers::Table<'a>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Table<'a>>>(Monster::VT_ANY_UNIQUE, None)} - } - - #[inline] - pub fn any_ambiguous_type(&self) -> AnyAmbiguousAliases { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_ANY_AMBIGUOUS_TYPE, Some(AnyAmbiguousAliases::NONE)).unwrap()} - } - - #[inline] - pub fn any_ambiguous(&self) -> Option<::flatbuffers::Table<'a>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Table<'a>>>(Monster::VT_ANY_AMBIGUOUS, None)} - } - - #[inline] - pub fn vector_of_enums(&self) -> Option<::flatbuffers::Vector<'a, Color>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, Color>>>(Monster::VT_VECTOR_OF_ENUMS, None)} - } - - #[inline] - pub fn signed_enum(&self) -> Race { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_SIGNED_ENUM, Some(Race::None)).unwrap()} - } - - #[inline] - pub fn testrequirednestedflatbuffer(&self) -> Option<::flatbuffers::Vector<'a, u8>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, u8>>>(Monster::VT_TESTREQUIREDNESTEDFLATBUFFER, None)} - } - - pub fn testrequirednestedflatbuffer_nested_flatbuffer(&'a self) -> Option> { - self.testrequirednestedflatbuffer().map(|data| { - use ::flatbuffers::Follow; - // Safety: - // Created from a valid Table for this object - // Which contains a valid flatbuffer in this slot - unsafe { <::flatbuffers::ForwardsUOffset>>::follow(data.bytes(), 0) } - }) - } - - #[inline] - pub fn scalar_key_sorted_tables(&self) -> Option<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset>>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, ::flatbuffers::ForwardsUOffset>>>(Monster::VT_SCALAR_KEY_SORTED_TABLES, None)} - } - - #[inline] - pub fn native_inline(&self) -> Option<&'a Test> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_NATIVE_INLINE, None)} - } - - #[inline] - pub fn long_enum_non_enum_default(&self) -> LongEnum { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_LONG_ENUM_NON_ENUM_DEFAULT, Some(Default::default())).unwrap()} - } - - #[inline] - pub fn long_enum_normal_default(&self) -> LongEnum { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_LONG_ENUM_NORMAL_DEFAULT, Some(LongEnum::LongOne)).unwrap()} - } - - #[inline] - pub fn nan_default(&self) -> f32 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_NAN_DEFAULT, Some(f32::NAN)).unwrap()} - } - - #[inline] - pub fn inf_default(&self) -> f32 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_INF_DEFAULT, Some(f32::INFINITY)).unwrap()} - } - - #[inline] - pub fn positive_inf_default(&self) -> f32 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_POSITIVE_INF_DEFAULT, Some(f32::INFINITY)).unwrap()} - } - - #[inline] - pub fn infinity_default(&self) -> f32 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_INFINITY_DEFAULT, Some(f32::INFINITY)).unwrap()} - } - - #[inline] - pub fn positive_infinity_default(&self) -> f32 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_POSITIVE_INFINITY_DEFAULT, Some(f32::INFINITY)).unwrap()} - } - - #[inline] - pub fn negative_inf_default(&self) -> f32 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_NEGATIVE_INF_DEFAULT, Some(f32::NEG_INFINITY)).unwrap()} - } - - #[inline] - pub fn negative_infinity_default(&self) -> f32 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_NEGATIVE_INFINITY_DEFAULT, Some(f32::NEG_INFINITY)).unwrap()} - } - - #[inline] - pub fn double_inf_default(&self) -> f64 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Monster::VT_DOUBLE_INF_DEFAULT, Some(f64::INFINITY)).unwrap()} - } - - #[inline] - #[allow(non_snake_case)] - pub fn test_as_monster(&self) -> Option> { - if self.test_type() == Any::Monster { - self.test().map(|t| { - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - unsafe { Monster::init_from_table(t) } - }) - } else { - None - } - } - - #[inline] - #[allow(non_snake_case)] - pub fn test_as_test_simple_table_with_enum(&self) -> Option> { - if self.test_type() == Any::TestSimpleTableWithEnum { - self.test().map(|t| { - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - unsafe { TestSimpleTableWithEnum::init_from_table(t) } - }) - } else { - None - } - } - - #[inline] - #[allow(non_snake_case)] - pub fn test_as_my_game_example_2_monster(&self) -> Option> { - if self.test_type() == Any::MyGame_Example2_Monster { - self.test().map(|t| { - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - unsafe { super::example_2::Monster::init_from_table(t) } - }) - } else { - None - } - } - - #[inline] - #[allow(non_snake_case)] - pub fn any_unique_as_m(&self) -> Option> { - if self.any_unique_type() == AnyUniqueAliases::M { - self.any_unique().map(|t| { - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - unsafe { Monster::init_from_table(t) } - }) - } else { - None - } - } - - #[inline] - #[allow(non_snake_case)] - pub fn any_unique_as_ts(&self) -> Option> { - if self.any_unique_type() == AnyUniqueAliases::TS { - self.any_unique().map(|t| { - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - unsafe { TestSimpleTableWithEnum::init_from_table(t) } - }) - } else { - None - } - } - - #[inline] - #[allow(non_snake_case)] - pub fn any_unique_as_m2(&self) -> Option> { - if self.any_unique_type() == AnyUniqueAliases::M2 { - self.any_unique().map(|t| { - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - unsafe { super::example_2::Monster::init_from_table(t) } - }) - } else { - None - } - } - - #[inline] - #[allow(non_snake_case)] - pub fn any_ambiguous_as_m1(&self) -> Option> { - if self.any_ambiguous_type() == AnyAmbiguousAliases::M1 { - self.any_ambiguous().map(|t| { - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - unsafe { Monster::init_from_table(t) } - }) - } else { - None - } - } - - #[inline] - #[allow(non_snake_case)] - pub fn any_ambiguous_as_m2(&self) -> Option> { - if self.any_ambiguous_type() == AnyAmbiguousAliases::M2 { - self.any_ambiguous().map(|t| { - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - unsafe { Monster::init_from_table(t) } - }) - } else { - None - } - } - - #[inline] - #[allow(non_snake_case)] - pub fn any_ambiguous_as_m3(&self) -> Option> { - if self.any_ambiguous_type() == AnyAmbiguousAliases::M3 { - self.any_ambiguous().map(|t| { - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - unsafe { Monster::init_from_table(t) } - }) - } else { - None - } - } } impl ::flatbuffers::Verifiable for Monster<'_> { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.visit_table(pos)? - .visit_field::("pos", Self::VT_POS, false)? - .visit_field::("mana", Self::VT_MANA, false)? - .visit_field::("hp", Self::VT_HP, false)? - .visit_field::<::flatbuffers::ForwardsUOffset<&str>>("name", Self::VT_NAME, true)? - .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, u8>>>("inventory", Self::VT_INVENTORY, false)? - .visit_field::("color", Self::VT_COLOR, false)? - .visit_union::("test_type", Self::VT_TEST_TYPE, "test", Self::VT_TEST, false, |key, v, pos| { - match key { - Any::Monster => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("Any::Monster", pos), - Any::TestSimpleTableWithEnum => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("Any::TestSimpleTableWithEnum", pos), - Any::MyGame_Example2_Monster => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("Any::MyGame_Example2_Monster", pos), - _ => Ok(()), - } - })? - .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, Test>>>("test4", Self::VT_TEST4, false)? - .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, ::flatbuffers::ForwardsUOffset<&'_ str>>>>("testarrayofstring", Self::VT_TESTARRAYOFSTRING, false)? - .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, ::flatbuffers::ForwardsUOffset>>>("testarrayoftables", Self::VT_TESTARRAYOFTABLES, false)? - .visit_field::<::flatbuffers::ForwardsUOffset>("enemy", Self::VT_ENEMY, false)? - .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, u8>>>("testnestedflatbuffer", Self::VT_TESTNESTEDFLATBUFFER, false)? - .visit_field::<::flatbuffers::ForwardsUOffset>("testempty", Self::VT_TESTEMPTY, false)? - .visit_field::("testbool", Self::VT_TESTBOOL, false)? - .visit_field::("testhashs32_fnv1", Self::VT_TESTHASHS32_FNV1, false)? - .visit_field::("testhashu32_fnv1", Self::VT_TESTHASHU32_FNV1, false)? - .visit_field::("testhashs64_fnv1", Self::VT_TESTHASHS64_FNV1, false)? - .visit_field::("testhashu64_fnv1", Self::VT_TESTHASHU64_FNV1, false)? - .visit_field::("testhashs32_fnv1a", Self::VT_TESTHASHS32_FNV1A, false)? - .visit_field::("testhashu32_fnv1a", Self::VT_TESTHASHU32_FNV1A, false)? - .visit_field::("testhashs64_fnv1a", Self::VT_TESTHASHS64_FNV1A, false)? - .visit_field::("testhashu64_fnv1a", Self::VT_TESTHASHU64_FNV1A, false)? - .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, bool>>>("testarrayofbools", Self::VT_TESTARRAYOFBOOLS, false)? - .visit_field::("testf", Self::VT_TESTF, false)? - .visit_field::("testf2", Self::VT_TESTF2, false)? - .visit_field::("testf3", Self::VT_TESTF3, false)? - .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, ::flatbuffers::ForwardsUOffset<&'_ str>>>>("testarrayofstring2", Self::VT_TESTARRAYOFSTRING2, false)? - .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, Ability>>>("testarrayofsortedstruct", Self::VT_TESTARRAYOFSORTEDSTRUCT, false)? - .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, u8>>>("flex", Self::VT_FLEX, false)? - .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, Test>>>("test5", Self::VT_TEST5, false)? - .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, i64>>>("vector_of_longs", Self::VT_VECTOR_OF_LONGS, false)? - .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, f64>>>("vector_of_doubles", Self::VT_VECTOR_OF_DOUBLES, false)? - .visit_field::<::flatbuffers::ForwardsUOffset>("parent_namespace_test", Self::VT_PARENT_NAMESPACE_TEST, false)? - .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, ::flatbuffers::ForwardsUOffset>>>("vector_of_referrables", Self::VT_VECTOR_OF_REFERRABLES, false)? - .visit_field::("single_weak_reference", Self::VT_SINGLE_WEAK_REFERENCE, false)? - .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, u64>>>("vector_of_weak_references", Self::VT_VECTOR_OF_WEAK_REFERENCES, false)? - .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, ::flatbuffers::ForwardsUOffset>>>("vector_of_strong_referrables", Self::VT_VECTOR_OF_STRONG_REFERRABLES, false)? - .visit_field::("co_owning_reference", Self::VT_CO_OWNING_REFERENCE, false)? - .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, u64>>>("vector_of_co_owning_references", Self::VT_VECTOR_OF_CO_OWNING_REFERENCES, false)? - .visit_field::("non_owning_reference", Self::VT_NON_OWNING_REFERENCE, false)? - .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, u64>>>("vector_of_non_owning_references", Self::VT_VECTOR_OF_NON_OWNING_REFERENCES, false)? - .visit_union::("any_unique_type", Self::VT_ANY_UNIQUE_TYPE, "any_unique", Self::VT_ANY_UNIQUE, false, |key, v, pos| { - match key { - AnyUniqueAliases::M => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("AnyUniqueAliases::M", pos), - AnyUniqueAliases::TS => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("AnyUniqueAliases::TS", pos), - AnyUniqueAliases::M2 => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("AnyUniqueAliases::M2", pos), - _ => Ok(()), - } - })? - .visit_union::("any_ambiguous_type", Self::VT_ANY_AMBIGUOUS_TYPE, "any_ambiguous", Self::VT_ANY_AMBIGUOUS, false, |key, v, pos| { - match key { - AnyAmbiguousAliases::M1 => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("AnyAmbiguousAliases::M1", pos), - AnyAmbiguousAliases::M2 => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("AnyAmbiguousAliases::M2", pos), - AnyAmbiguousAliases::M3 => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("AnyAmbiguousAliases::M3", pos), - _ => Ok(()), - } - })? - .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, Color>>>("vector_of_enums", Self::VT_VECTOR_OF_ENUMS, false)? - .visit_field::("signed_enum", Self::VT_SIGNED_ENUM, false)? - .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, u8>>>("testrequirednestedflatbuffer", Self::VT_TESTREQUIREDNESTEDFLATBUFFER, false)? - .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, ::flatbuffers::ForwardsUOffset>>>("scalar_key_sorted_tables", Self::VT_SCALAR_KEY_SORTED_TABLES, false)? - .visit_field::("native_inline", Self::VT_NATIVE_INLINE, false)? - .visit_field::("long_enum_non_enum_default", Self::VT_LONG_ENUM_NON_ENUM_DEFAULT, false)? - .visit_field::("long_enum_normal_default", Self::VT_LONG_ENUM_NORMAL_DEFAULT, false)? - .visit_field::("nan_default", Self::VT_NAN_DEFAULT, false)? - .visit_field::("inf_default", Self::VT_INF_DEFAULT, false)? - .visit_field::("positive_inf_default", Self::VT_POSITIVE_INF_DEFAULT, false)? - .visit_field::("infinity_default", Self::VT_INFINITY_DEFAULT, false)? - .visit_field::("positive_infinity_default", Self::VT_POSITIVE_INFINITY_DEFAULT, false)? - .visit_field::("negative_inf_default", Self::VT_NEGATIVE_INF_DEFAULT, false)? - .visit_field::("negative_infinity_default", Self::VT_NEGATIVE_INFINITY_DEFAULT, false)? - .visit_field::("double_inf_default", Self::VT_DOUBLE_INF_DEFAULT, false)? - .finish(); - Ok(()) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.visit_table(pos)? + .visit_field::("pos", Self::VT_POS, false)? + .visit_field::("mana", Self::VT_MANA, false)? + .visit_field::("hp", Self::VT_HP, false)? + .visit_field::<::flatbuffers::ForwardsUOffset<&str>>("name", Self::VT_NAME, true)? + .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, u8>>>("inventory", Self::VT_INVENTORY, false)? + .visit_field::("color", Self::VT_COLOR, false)? + .visit_union::("test_type", Self::VT_TEST_TYPE, "test", Self::VT_TEST, false, |key, v, pos| { + match key { + Any::Monster => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("Any::Monster", pos), + Any::TestSimpleTableWithEnum => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("Any::TestSimpleTableWithEnum", pos), + Any::MyGame_Example2_Monster => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("Any::MyGame_Example2_Monster", pos), + _ => Ok(()), + } + })? + .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, Test>>>("test4", Self::VT_TEST4, false)? + .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, ::flatbuffers::ForwardsUOffset<&'_ str>>>>("testarrayofstring", Self::VT_TESTARRAYOFSTRING, false)? + .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, ::flatbuffers::ForwardsUOffset>>>("testarrayoftables", Self::VT_TESTARRAYOFTABLES, false)? + .visit_field::<::flatbuffers::ForwardsUOffset>("enemy", Self::VT_ENEMY, false)? + .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, u8>>>("testnestedflatbuffer", Self::VT_TESTNESTEDFLATBUFFER, false)? + .visit_field::<::flatbuffers::ForwardsUOffset>("testempty", Self::VT_TESTEMPTY, false)? + .visit_field::("testbool", Self::VT_TESTBOOL, false)? + .visit_field::("testhashs32_fnv1", Self::VT_TESTHASHS32_FNV1, false)? + .visit_field::("testhashu32_fnv1", Self::VT_TESTHASHU32_FNV1, false)? + .visit_field::("testhashs64_fnv1", Self::VT_TESTHASHS64_FNV1, false)? + .visit_field::("testhashu64_fnv1", Self::VT_TESTHASHU64_FNV1, false)? + .visit_field::("testhashs32_fnv1a", Self::VT_TESTHASHS32_FNV1A, false)? + .visit_field::("testhashu32_fnv1a", Self::VT_TESTHASHU32_FNV1A, false)? + .visit_field::("testhashs64_fnv1a", Self::VT_TESTHASHS64_FNV1A, false)? + .visit_field::("testhashu64_fnv1a", Self::VT_TESTHASHU64_FNV1A, false)? + .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, bool>>>("testarrayofbools", Self::VT_TESTARRAYOFBOOLS, false)? + .visit_field::("testf", Self::VT_TESTF, false)? + .visit_field::("testf2", Self::VT_TESTF2, false)? + .visit_field::("testf3", Self::VT_TESTF3, false)? + .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, ::flatbuffers::ForwardsUOffset<&'_ str>>>>("testarrayofstring2", Self::VT_TESTARRAYOFSTRING2, false)? + .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, Ability>>>("testarrayofsortedstruct", Self::VT_TESTARRAYOFSORTEDSTRUCT, false)? + .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, u8>>>("flex", Self::VT_FLEX, false)? + .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, Test>>>("test5", Self::VT_TEST5, false)? + .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, i64>>>("vector_of_longs", Self::VT_VECTOR_OF_LONGS, false)? + .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, f64>>>("vector_of_doubles", Self::VT_VECTOR_OF_DOUBLES, false)? + .visit_field::<::flatbuffers::ForwardsUOffset>("parent_namespace_test", Self::VT_PARENT_NAMESPACE_TEST, false)? + .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, ::flatbuffers::ForwardsUOffset>>>("vector_of_referrables", Self::VT_VECTOR_OF_REFERRABLES, false)? + .visit_field::("single_weak_reference", Self::VT_SINGLE_WEAK_REFERENCE, false)? + .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, u64>>>("vector_of_weak_references", Self::VT_VECTOR_OF_WEAK_REFERENCES, false)? + .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, ::flatbuffers::ForwardsUOffset>>>("vector_of_strong_referrables", Self::VT_VECTOR_OF_STRONG_REFERRABLES, false)? + .visit_field::("co_owning_reference", Self::VT_CO_OWNING_REFERENCE, false)? + .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, u64>>>("vector_of_co_owning_references", Self::VT_VECTOR_OF_CO_OWNING_REFERENCES, false)? + .visit_field::("non_owning_reference", Self::VT_NON_OWNING_REFERENCE, false)? + .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, u64>>>("vector_of_non_owning_references", Self::VT_VECTOR_OF_NON_OWNING_REFERENCES, false)? + .visit_union::("any_unique_type", Self::VT_ANY_UNIQUE_TYPE, "any_unique", Self::VT_ANY_UNIQUE, false, |key, v, pos| { + match key { + AnyUniqueAliases::M => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("AnyUniqueAliases::M", pos), + AnyUniqueAliases::TS => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("AnyUniqueAliases::TS", pos), + AnyUniqueAliases::M2 => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("AnyUniqueAliases::M2", pos), + _ => Ok(()), + } + })? + .visit_union::("any_ambiguous_type", Self::VT_ANY_AMBIGUOUS_TYPE, "any_ambiguous", Self::VT_ANY_AMBIGUOUS, false, |key, v, pos| { + match key { + AnyAmbiguousAliases::M1 => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("AnyAmbiguousAliases::M1", pos), + AnyAmbiguousAliases::M2 => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("AnyAmbiguousAliases::M2", pos), + AnyAmbiguousAliases::M3 => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("AnyAmbiguousAliases::M3", pos), + _ => Ok(()), + } + })? + .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, Color>>>("vector_of_enums", Self::VT_VECTOR_OF_ENUMS, false)? + .visit_field::("signed_enum", Self::VT_SIGNED_ENUM, false)? + .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, u8>>>("testrequirednestedflatbuffer", Self::VT_TESTREQUIREDNESTEDFLATBUFFER, false)? + .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, ::flatbuffers::ForwardsUOffset>>>("scalar_key_sorted_tables", Self::VT_SCALAR_KEY_SORTED_TABLES, false)? + .visit_field::("native_inline", Self::VT_NATIVE_INLINE, false)? + .visit_field::("long_enum_non_enum_default", Self::VT_LONG_ENUM_NON_ENUM_DEFAULT, false)? + .visit_field::("long_enum_normal_default", Self::VT_LONG_ENUM_NORMAL_DEFAULT, false)? + .visit_field::("nan_default", Self::VT_NAN_DEFAULT, false)? + .visit_field::("inf_default", Self::VT_INF_DEFAULT, false)? + .visit_field::("positive_inf_default", Self::VT_POSITIVE_INF_DEFAULT, false)? + .visit_field::("infinity_default", Self::VT_INFINITY_DEFAULT, false)? + .visit_field::("positive_infinity_default", Self::VT_POSITIVE_INFINITY_DEFAULT, false)? + .visit_field::("negative_inf_default", Self::VT_NEGATIVE_INF_DEFAULT, false)? + .visit_field::("negative_infinity_default", Self::VT_NEGATIVE_INFINITY_DEFAULT, false)? + .visit_field::("double_inf_default", Self::VT_DOUBLE_INF_DEFAULT, false)? + .finish(); + Ok(()) + } } - pub struct MonsterArgs<'a> { pub pos: Option<&'a Vec3>, pub mana: i16, @@ -1202,1162 +1135,1088 @@ pub struct MonsterArgs<'a> { pub negative_infinity_default: f32, pub double_inf_default: f64, } - impl<'a> Default for MonsterArgs<'a> { - #[inline] - fn default() -> Self { - MonsterArgs { - pos: None, - mana: 150, - hp: 100, - name: None, // required field - inventory: None, - color: Color::Blue, - test_type: Any::NONE, - test: None, - test4: None, - testarrayofstring: None, - testarrayoftables: None, - enemy: None, - testnestedflatbuffer: None, - testempty: None, - testbool: false, - testhashs32_fnv1: 0, - testhashu32_fnv1: 0, - testhashs64_fnv1: 0, - testhashu64_fnv1: 0, - testhashs32_fnv1a: 0, - testhashu32_fnv1a: 0, - testhashs64_fnv1a: 0, - testhashu64_fnv1a: 0, - testarrayofbools: None, - testf: 3.14159, - testf2: 3.0, - testf3: 0.0, - testarrayofstring2: None, - testarrayofsortedstruct: None, - flex: None, - test5: None, - vector_of_longs: None, - vector_of_doubles: None, - parent_namespace_test: None, - vector_of_referrables: None, - single_weak_reference: 0, - vector_of_weak_references: None, - vector_of_strong_referrables: None, - co_owning_reference: 0, - vector_of_co_owning_references: None, - non_owning_reference: 0, - vector_of_non_owning_references: None, - any_unique_type: AnyUniqueAliases::NONE, - any_unique: None, - any_ambiguous_type: AnyAmbiguousAliases::NONE, - any_ambiguous: None, - vector_of_enums: None, - signed_enum: Race::None, - testrequirednestedflatbuffer: None, - scalar_key_sorted_tables: None, - native_inline: None, - long_enum_non_enum_default: Default::default(), - long_enum_normal_default: LongEnum::LongOne, - nan_default: f32::NAN, - inf_default: f32::INFINITY, - positive_inf_default: f32::INFINITY, - infinity_default: f32::INFINITY, - positive_infinity_default: f32::INFINITY, - negative_inf_default: f32::NEG_INFINITY, - negative_infinity_default: f32::NEG_INFINITY, - double_inf_default: f64::INFINITY, - } + #[inline] + fn default() -> Self { + MonsterArgs { + pos: None, + mana: 150, + hp: 100, + name: None, // required field + inventory: None, + color: Color::Blue, + test_type: Any::NONE, + test: None, + test4: None, + testarrayofstring: None, + testarrayoftables: None, + enemy: None, + testnestedflatbuffer: None, + testempty: None, + testbool: false, + testhashs32_fnv1: 0, + testhashu32_fnv1: 0, + testhashs64_fnv1: 0, + testhashu64_fnv1: 0, + testhashs32_fnv1a: 0, + testhashu32_fnv1a: 0, + testhashs64_fnv1a: 0, + testhashu64_fnv1a: 0, + testarrayofbools: None, + testf: 3.14159, + testf2: 3.0, + testf3: 0.0, + testarrayofstring2: None, + testarrayofsortedstruct: None, + flex: None, + test5: None, + vector_of_longs: None, + vector_of_doubles: None, + parent_namespace_test: None, + vector_of_referrables: None, + single_weak_reference: 0, + vector_of_weak_references: None, + vector_of_strong_referrables: None, + co_owning_reference: 0, + vector_of_co_owning_references: None, + non_owning_reference: 0, + vector_of_non_owning_references: None, + any_unique_type: AnyUniqueAliases::NONE, + any_unique: None, + any_ambiguous_type: AnyAmbiguousAliases::NONE, + any_ambiguous: None, + vector_of_enums: None, + signed_enum: Race::None, + testrequirednestedflatbuffer: None, + scalar_key_sorted_tables: None, + native_inline: None, + long_enum_non_enum_default: Default::default(), + long_enum_normal_default: LongEnum::LongOne, + nan_default: f32::NAN, + inf_default: f32::INFINITY, + positive_inf_default: f32::INFINITY, + infinity_default: f32::INFINITY, + positive_infinity_default: f32::INFINITY, + negative_inf_default: f32::NEG_INFINITY, + negative_infinity_default: f32::NEG_INFINITY, + double_inf_default: f64::INFINITY, } + } } impl Serialize for Monster<'_> { - fn serialize(&self, serializer: S) -> Result - where - S: Serializer, - { - let mut s = serializer.serialize_struct("Monster", 62)?; - if let Some(f) = self.pos() { - s.serialize_field("pos", &f)?; - } else { - s.skip_field("pos")?; - } - s.serialize_field("mana", &self.mana())?; - s.serialize_field("hp", &self.hp())?; - s.serialize_field("name", &self.name())?; - if let Some(f) = self.inventory() { - s.serialize_field("inventory", &f)?; - } else { - s.skip_field("inventory")?; - } - s.serialize_field("color", &self.color())?; - s.serialize_field("test_type", &self.test_type())?; - match self.test_type() { - Any::NONE => (), - Any::Monster => { - let f = self.test_as_monster() - .expect("Invalid union table, expected `Any::Monster`."); - s.serialize_field("test", &f)?; - } - Any::TestSimpleTableWithEnum => { - let f = self.test_as_test_simple_table_with_enum() - .expect("Invalid union table, expected `Any::TestSimpleTableWithEnum`."); - s.serialize_field("test", &f)?; - } - Any::MyGame_Example2_Monster => { - let f = self.test_as_my_game_example_2_monster() - .expect("Invalid union table, expected `Any::MyGame_Example2_Monster`."); - s.serialize_field("test", &f)?; - } - _ => unimplemented!(), - } - if let Some(f) = self.test4() { - s.serialize_field("test4", &f)?; - } else { - s.skip_field("test4")?; - } - if let Some(f) = self.testarrayofstring() { - s.serialize_field("testarrayofstring", &f)?; - } else { - s.skip_field("testarrayofstring")?; - } - if let Some(f) = self.testarrayoftables() { - s.serialize_field("testarrayoftables", &f)?; - } else { - s.skip_field("testarrayoftables")?; - } - if let Some(f) = self.enemy() { - s.serialize_field("enemy", &f)?; - } else { - s.skip_field("enemy")?; - } - if let Some(f) = self.testnestedflatbuffer() { - s.serialize_field("testnestedflatbuffer", &f)?; - } else { - s.skip_field("testnestedflatbuffer")?; - } - if let Some(f) = self.testempty() { - s.serialize_field("testempty", &f)?; - } else { - s.skip_field("testempty")?; - } - s.serialize_field("testbool", &self.testbool())?; - s.serialize_field("testhashs32_fnv1", &self.testhashs32_fnv1())?; - s.serialize_field("testhashu32_fnv1", &self.testhashu32_fnv1())?; - s.serialize_field("testhashs64_fnv1", &self.testhashs64_fnv1())?; - s.serialize_field("testhashu64_fnv1", &self.testhashu64_fnv1())?; - s.serialize_field("testhashs32_fnv1a", &self.testhashs32_fnv1a())?; - s.serialize_field("testhashu32_fnv1a", &self.testhashu32_fnv1a())?; - s.serialize_field("testhashs64_fnv1a", &self.testhashs64_fnv1a())?; - s.serialize_field("testhashu64_fnv1a", &self.testhashu64_fnv1a())?; - if let Some(f) = self.testarrayofbools() { - s.serialize_field("testarrayofbools", &f)?; - } else { - s.skip_field("testarrayofbools")?; - } - s.serialize_field("testf", &self.testf())?; - s.serialize_field("testf2", &self.testf2())?; - s.serialize_field("testf3", &self.testf3())?; - if let Some(f) = self.testarrayofstring2() { - s.serialize_field("testarrayofstring2", &f)?; - } else { - s.skip_field("testarrayofstring2")?; - } - if let Some(f) = self.testarrayofsortedstruct() { - s.serialize_field("testarrayofsortedstruct", &f)?; - } else { - s.skip_field("testarrayofsortedstruct")?; - } - if let Some(f) = self.flex() { - s.serialize_field("flex", &f)?; - } else { - s.skip_field("flex")?; - } - if let Some(f) = self.test5() { - s.serialize_field("test5", &f)?; - } else { - s.skip_field("test5")?; - } - if let Some(f) = self.vector_of_longs() { - s.serialize_field("vector_of_longs", &f)?; - } else { - s.skip_field("vector_of_longs")?; - } - if let Some(f) = self.vector_of_doubles() { - s.serialize_field("vector_of_doubles", &f)?; - } else { - s.skip_field("vector_of_doubles")?; - } - if let Some(f) = self.parent_namespace_test() { - s.serialize_field("parent_namespace_test", &f)?; - } else { - s.skip_field("parent_namespace_test")?; - } - if let Some(f) = self.vector_of_referrables() { - s.serialize_field("vector_of_referrables", &f)?; - } else { - s.skip_field("vector_of_referrables")?; - } - s.serialize_field("single_weak_reference", &self.single_weak_reference())?; - if let Some(f) = self.vector_of_weak_references() { - s.serialize_field("vector_of_weak_references", &f)?; - } else { - s.skip_field("vector_of_weak_references")?; - } - if let Some(f) = self.vector_of_strong_referrables() { - s.serialize_field("vector_of_strong_referrables", &f)?; - } else { - s.skip_field("vector_of_strong_referrables")?; - } - s.serialize_field("co_owning_reference", &self.co_owning_reference())?; - if let Some(f) = self.vector_of_co_owning_references() { - s.serialize_field("vector_of_co_owning_references", &f)?; - } else { - s.skip_field("vector_of_co_owning_references")?; - } - s.serialize_field("non_owning_reference", &self.non_owning_reference())?; - if let Some(f) = self.vector_of_non_owning_references() { - s.serialize_field("vector_of_non_owning_references", &f)?; - } else { - s.skip_field("vector_of_non_owning_references")?; - } - s.serialize_field("any_unique_type", &self.any_unique_type())?; - match self.any_unique_type() { - AnyUniqueAliases::NONE => (), - AnyUniqueAliases::M => { - let f = self.any_unique_as_m() - .expect("Invalid union table, expected `AnyUniqueAliases::M`."); - s.serialize_field("any_unique", &f)?; - } - AnyUniqueAliases::TS => { - let f = self.any_unique_as_ts() - .expect("Invalid union table, expected `AnyUniqueAliases::TS`."); - s.serialize_field("any_unique", &f)?; - } - AnyUniqueAliases::M2 => { - let f = self.any_unique_as_m2() - .expect("Invalid union table, expected `AnyUniqueAliases::M2`."); - s.serialize_field("any_unique", &f)?; - } - _ => unimplemented!(), - } - s.serialize_field("any_ambiguous_type", &self.any_ambiguous_type())?; - match self.any_ambiguous_type() { - AnyAmbiguousAliases::NONE => (), - AnyAmbiguousAliases::M1 => { - let f = self.any_ambiguous_as_m1() - .expect("Invalid union table, expected `AnyAmbiguousAliases::M1`."); - s.serialize_field("any_ambiguous", &f)?; - } - AnyAmbiguousAliases::M2 => { - let f = self.any_ambiguous_as_m2() - .expect("Invalid union table, expected `AnyAmbiguousAliases::M2`."); - s.serialize_field("any_ambiguous", &f)?; - } - AnyAmbiguousAliases::M3 => { - let f = self.any_ambiguous_as_m3() - .expect("Invalid union table, expected `AnyAmbiguousAliases::M3`."); - s.serialize_field("any_ambiguous", &f)?; - } - _ => unimplemented!(), - } - if let Some(f) = self.vector_of_enums() { - s.serialize_field("vector_of_enums", &f)?; - } else { - s.skip_field("vector_of_enums")?; - } - s.serialize_field("signed_enum", &self.signed_enum())?; - if let Some(f) = self.testrequirednestedflatbuffer() { - s.serialize_field("testrequirednestedflatbuffer", &f)?; - } else { - s.skip_field("testrequirednestedflatbuffer")?; - } - if let Some(f) = self.scalar_key_sorted_tables() { - s.serialize_field("scalar_key_sorted_tables", &f)?; - } else { - s.skip_field("scalar_key_sorted_tables")?; - } - if let Some(f) = self.native_inline() { - s.serialize_field("native_inline", &f)?; - } else { - s.skip_field("native_inline")?; - } - s.serialize_field("long_enum_non_enum_default", &self.long_enum_non_enum_default())?; - s.serialize_field("long_enum_normal_default", &self.long_enum_normal_default())?; - s.serialize_field("nan_default", &self.nan_default())?; - s.serialize_field("inf_default", &self.inf_default())?; - s.serialize_field("positive_inf_default", &self.positive_inf_default())?; - s.serialize_field("infinity_default", &self.infinity_default())?; - s.serialize_field("positive_infinity_default", &self.positive_infinity_default())?; - s.serialize_field("negative_inf_default", &self.negative_inf_default())?; - s.serialize_field("negative_infinity_default", &self.negative_infinity_default())?; - s.serialize_field("double_inf_default", &self.double_inf_default())?; - s.end() - } + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let mut s = serializer.serialize_struct("Monster", 62)?; + if let Some(f) = self.pos() { + s.serialize_field("pos", &f)?; + } else { + s.skip_field("pos")?; + } + s.serialize_field("mana", &self.mana())?; + s.serialize_field("hp", &self.hp())?; + s.serialize_field("name", &self.name())?; + if let Some(f) = self.inventory() { + s.serialize_field("inventory", &f)?; + } else { + s.skip_field("inventory")?; + } + s.serialize_field("color", &self.color())?; + s.serialize_field("test_type", &self.test_type())?; + match self.test_type() { + Any::NONE => (), + Any::Monster => { + let f = self.test_as_monster() + .expect("Invalid union table, expected `Any::Monster`."); + s.serialize_field("test", &f)?; + } + Any::TestSimpleTableWithEnum => { + let f = self.test_as_test_simple_table_with_enum() + .expect("Invalid union table, expected `Any::TestSimpleTableWithEnum`."); + s.serialize_field("test", &f)?; + } + Any::MyGame_Example2_Monster => { + let f = self.test_as_my_game_example_2_monster() + .expect("Invalid union table, expected `Any::MyGame_Example2_Monster`."); + s.serialize_field("test", &f)?; + } + _ => unimplemented!(), + } + if let Some(f) = self.test4() { + s.serialize_field("test4", &f)?; + } else { + s.skip_field("test4")?; + } + if let Some(f) = self.testarrayofstring() { + s.serialize_field("testarrayofstring", &f)?; + } else { + s.skip_field("testarrayofstring")?; + } + if let Some(f) = self.testarrayoftables() { + s.serialize_field("testarrayoftables", &f)?; + } else { + s.skip_field("testarrayoftables")?; + } + if let Some(f) = self.enemy() { + s.serialize_field("enemy", &f)?; + } else { + s.skip_field("enemy")?; + } + if let Some(f) = self.testnestedflatbuffer() { + s.serialize_field("testnestedflatbuffer", &f)?; + } else { + s.skip_field("testnestedflatbuffer")?; + } + if let Some(f) = self.testempty() { + s.serialize_field("testempty", &f)?; + } else { + s.skip_field("testempty")?; + } + s.serialize_field("testbool", &self.testbool())?; + s.serialize_field("testhashs32_fnv1", &self.testhashs32_fnv1())?; + s.serialize_field("testhashu32_fnv1", &self.testhashu32_fnv1())?; + s.serialize_field("testhashs64_fnv1", &self.testhashs64_fnv1())?; + s.serialize_field("testhashu64_fnv1", &self.testhashu64_fnv1())?; + s.serialize_field("testhashs32_fnv1a", &self.testhashs32_fnv1a())?; + s.serialize_field("testhashu32_fnv1a", &self.testhashu32_fnv1a())?; + s.serialize_field("testhashs64_fnv1a", &self.testhashs64_fnv1a())?; + s.serialize_field("testhashu64_fnv1a", &self.testhashu64_fnv1a())?; + if let Some(f) = self.testarrayofbools() { + s.serialize_field("testarrayofbools", &f)?; + } else { + s.skip_field("testarrayofbools")?; + } + s.serialize_field("testf", &self.testf())?; + s.serialize_field("testf2", &self.testf2())?; + s.serialize_field("testf3", &self.testf3())?; + if let Some(f) = self.testarrayofstring2() { + s.serialize_field("testarrayofstring2", &f)?; + } else { + s.skip_field("testarrayofstring2")?; + } + if let Some(f) = self.testarrayofsortedstruct() { + s.serialize_field("testarrayofsortedstruct", &f)?; + } else { + s.skip_field("testarrayofsortedstruct")?; + } + if let Some(f) = self.flex() { + s.serialize_field("flex", &f)?; + } else { + s.skip_field("flex")?; + } + if let Some(f) = self.test5() { + s.serialize_field("test5", &f)?; + } else { + s.skip_field("test5")?; + } + if let Some(f) = self.vector_of_longs() { + s.serialize_field("vector_of_longs", &f)?; + } else { + s.skip_field("vector_of_longs")?; + } + if let Some(f) = self.vector_of_doubles() { + s.serialize_field("vector_of_doubles", &f)?; + } else { + s.skip_field("vector_of_doubles")?; + } + if let Some(f) = self.parent_namespace_test() { + s.serialize_field("parent_namespace_test", &f)?; + } else { + s.skip_field("parent_namespace_test")?; + } + if let Some(f) = self.vector_of_referrables() { + s.serialize_field("vector_of_referrables", &f)?; + } else { + s.skip_field("vector_of_referrables")?; + } + s.serialize_field("single_weak_reference", &self.single_weak_reference())?; + if let Some(f) = self.vector_of_weak_references() { + s.serialize_field("vector_of_weak_references", &f)?; + } else { + s.skip_field("vector_of_weak_references")?; + } + if let Some(f) = self.vector_of_strong_referrables() { + s.serialize_field("vector_of_strong_referrables", &f)?; + } else { + s.skip_field("vector_of_strong_referrables")?; + } + s.serialize_field("co_owning_reference", &self.co_owning_reference())?; + if let Some(f) = self.vector_of_co_owning_references() { + s.serialize_field("vector_of_co_owning_references", &f)?; + } else { + s.skip_field("vector_of_co_owning_references")?; + } + s.serialize_field("non_owning_reference", &self.non_owning_reference())?; + if let Some(f) = self.vector_of_non_owning_references() { + s.serialize_field("vector_of_non_owning_references", &f)?; + } else { + s.skip_field("vector_of_non_owning_references")?; + } + s.serialize_field("any_unique_type", &self.any_unique_type())?; + match self.any_unique_type() { + AnyUniqueAliases::NONE => (), + AnyUniqueAliases::M => { + let f = self.any_unique_as_m() + .expect("Invalid union table, expected `AnyUniqueAliases::M`."); + s.serialize_field("any_unique", &f)?; + } + AnyUniqueAliases::TS => { + let f = self.any_unique_as_ts() + .expect("Invalid union table, expected `AnyUniqueAliases::TS`."); + s.serialize_field("any_unique", &f)?; + } + AnyUniqueAliases::M2 => { + let f = self.any_unique_as_m2() + .expect("Invalid union table, expected `AnyUniqueAliases::M2`."); + s.serialize_field("any_unique", &f)?; + } + _ => unimplemented!(), + } + s.serialize_field("any_ambiguous_type", &self.any_ambiguous_type())?; + match self.any_ambiguous_type() { + AnyAmbiguousAliases::NONE => (), + AnyAmbiguousAliases::M1 => { + let f = self.any_ambiguous_as_m1() + .expect("Invalid union table, expected `AnyAmbiguousAliases::M1`."); + s.serialize_field("any_ambiguous", &f)?; + } + AnyAmbiguousAliases::M2 => { + let f = self.any_ambiguous_as_m2() + .expect("Invalid union table, expected `AnyAmbiguousAliases::M2`."); + s.serialize_field("any_ambiguous", &f)?; + } + AnyAmbiguousAliases::M3 => { + let f = self.any_ambiguous_as_m3() + .expect("Invalid union table, expected `AnyAmbiguousAliases::M3`."); + s.serialize_field("any_ambiguous", &f)?; + } + _ => unimplemented!(), + } + if let Some(f) = self.vector_of_enums() { + s.serialize_field("vector_of_enums", &f)?; + } else { + s.skip_field("vector_of_enums")?; + } + s.serialize_field("signed_enum", &self.signed_enum())?; + if let Some(f) = self.testrequirednestedflatbuffer() { + s.serialize_field("testrequirednestedflatbuffer", &f)?; + } else { + s.skip_field("testrequirednestedflatbuffer")?; + } + if let Some(f) = self.scalar_key_sorted_tables() { + s.serialize_field("scalar_key_sorted_tables", &f)?; + } else { + s.skip_field("scalar_key_sorted_tables")?; + } + if let Some(f) = self.native_inline() { + s.serialize_field("native_inline", &f)?; + } else { + s.skip_field("native_inline")?; + } + s.serialize_field("long_enum_non_enum_default", &self.long_enum_non_enum_default())?; + s.serialize_field("long_enum_normal_default", &self.long_enum_normal_default())?; + s.serialize_field("nan_default", &self.nan_default())?; + s.serialize_field("inf_default", &self.inf_default())?; + s.serialize_field("positive_inf_default", &self.positive_inf_default())?; + s.serialize_field("infinity_default", &self.infinity_default())?; + s.serialize_field("positive_infinity_default", &self.positive_infinity_default())?; + s.serialize_field("negative_inf_default", &self.negative_inf_default())?; + s.serialize_field("negative_infinity_default", &self.negative_infinity_default())?; + s.serialize_field("double_inf_default", &self.double_inf_default())?; + s.end() + } } pub struct MonsterBuilder<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> { - fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, + fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, + start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, } - impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> MonsterBuilder<'a, 'b, A> { - #[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::(Monster::VT_MANA, mana, 150); - } - - #[inline] - pub fn add_hp(&mut self, hp: i16) { - self.fbb_.push_slot::(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::(Monster::VT_COLOR, color, Color::Blue); - } - - #[inline] - pub fn add_test_type(&mut self, test_type: Any) { - self.fbb_.push_slot::(Monster::VT_TEST_TYPE, test_type, Any::NONE); - } - - #[inline] - pub fn add_test(&mut self, test: ::flatbuffers::WIPOffset<::flatbuffers::UnionWIPOffset>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_TEST, test); - } - - #[inline] - pub fn add_test4(&mut self, test4: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , Test>>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_TEST4, test4); - } - - #[inline] - pub fn add_testarrayofstring(&mut self, testarrayofstring: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , ::flatbuffers::ForwardsUOffset<&'b str>>>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_TESTARRAYOFSTRING, testarrayofstring); - } - - #[inline] - pub fn add_testarrayoftables(&mut self, testarrayoftables: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , ::flatbuffers::ForwardsUOffset>>>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_TESTARRAYOFTABLES, testarrayoftables); - } - - #[inline] - pub fn add_enemy(&mut self, enemy: ::flatbuffers::WIPOffset>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset>(Monster::VT_ENEMY, enemy); - } - - #[inline] - pub fn add_testnestedflatbuffer(&mut self, testnestedflatbuffer: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , u8>>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_TESTNESTEDFLATBUFFER, testnestedflatbuffer); - } - - #[inline] - pub fn add_testempty(&mut self, testempty: ::flatbuffers::WIPOffset>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset>(Monster::VT_TESTEMPTY, testempty); - } - - #[inline] - pub fn add_testbool(&mut self, testbool: bool) { - self.fbb_.push_slot::(Monster::VT_TESTBOOL, testbool, false); - } - - #[inline] - pub fn add_testhashs32_fnv1(&mut self, testhashs32_fnv1: i32) { - self.fbb_.push_slot::(Monster::VT_TESTHASHS32_FNV1, testhashs32_fnv1, 0); - } - - #[inline] - pub fn add_testhashu32_fnv1(&mut self, testhashu32_fnv1: u32) { - self.fbb_.push_slot::(Monster::VT_TESTHASHU32_FNV1, testhashu32_fnv1, 0); - } - - #[inline] - pub fn add_testhashs64_fnv1(&mut self, testhashs64_fnv1: i64) { - self.fbb_.push_slot::(Monster::VT_TESTHASHS64_FNV1, testhashs64_fnv1, 0); - } - - #[inline] - pub fn add_testhashu64_fnv1(&mut self, testhashu64_fnv1: u64) { - self.fbb_.push_slot::(Monster::VT_TESTHASHU64_FNV1, testhashu64_fnv1, 0); - } - - #[inline] - pub fn add_testhashs32_fnv1a(&mut self, testhashs32_fnv1a: i32) { - self.fbb_.push_slot::(Monster::VT_TESTHASHS32_FNV1A, testhashs32_fnv1a, 0); - } - - #[inline] - pub fn add_testhashu32_fnv1a(&mut self, testhashu32_fnv1a: u32) { - self.fbb_.push_slot::(Monster::VT_TESTHASHU32_FNV1A, testhashu32_fnv1a, 0); - } - - #[inline] - pub fn add_testhashs64_fnv1a(&mut self, testhashs64_fnv1a: i64) { - self.fbb_.push_slot::(Monster::VT_TESTHASHS64_FNV1A, testhashs64_fnv1a, 0); - } - - #[inline] - pub fn add_testhashu64_fnv1a(&mut self, testhashu64_fnv1a: u64) { - self.fbb_.push_slot::(Monster::VT_TESTHASHU64_FNV1A, testhashu64_fnv1a, 0); - } - - #[inline] - pub fn add_testarrayofbools(&mut self, testarrayofbools: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , bool>>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_TESTARRAYOFBOOLS, testarrayofbools); - } - - #[inline] - pub fn add_testf(&mut self, testf: f32) { - self.fbb_.push_slot::(Monster::VT_TESTF, testf, 3.14159); - } - - #[inline] - pub fn add_testf2(&mut self, testf2: f32) { - self.fbb_.push_slot::(Monster::VT_TESTF2, testf2, 3.0); - } - - #[inline] - pub fn add_testf3(&mut self, testf3: f32) { - self.fbb_.push_slot::(Monster::VT_TESTF3, testf3, 0.0); - } - - #[inline] - pub fn add_testarrayofstring2(&mut self, testarrayofstring2: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , ::flatbuffers::ForwardsUOffset<&'b str>>>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_TESTARRAYOFSTRING2, testarrayofstring2); - } - - #[inline] - pub fn add_testarrayofsortedstruct(&mut self, testarrayofsortedstruct: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , Ability>>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_TESTARRAYOFSORTEDSTRUCT, testarrayofsortedstruct); - } - - #[inline] - pub fn add_flex(&mut self, flex: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , u8>>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_FLEX, flex); - } - - #[inline] - pub fn add_test5(&mut self, test5: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , Test>>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_TEST5, test5); - } - - #[inline] - pub fn add_vector_of_longs(&mut self, vector_of_longs: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , i64>>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_LONGS, vector_of_longs); - } - - #[inline] - pub fn add_vector_of_doubles(&mut self, vector_of_doubles: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , f64>>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_DOUBLES, vector_of_doubles); - } - - #[inline] - pub fn add_parent_namespace_test(&mut self, parent_namespace_test: ::flatbuffers::WIPOffset>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset>(Monster::VT_PARENT_NAMESPACE_TEST, parent_namespace_test); - } - - #[inline] - pub fn add_vector_of_referrables(&mut self, vector_of_referrables: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , ::flatbuffers::ForwardsUOffset>>>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_REFERRABLES, vector_of_referrables); - } - - #[inline] - pub fn add_single_weak_reference(&mut self, single_weak_reference: u64) { - self.fbb_.push_slot::(Monster::VT_SINGLE_WEAK_REFERENCE, single_weak_reference, 0); - } - - #[inline] - pub fn add_vector_of_weak_references(&mut self, vector_of_weak_references: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , u64>>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_WEAK_REFERENCES, vector_of_weak_references); - } - - #[inline] - pub fn add_vector_of_strong_referrables(&mut self, vector_of_strong_referrables: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , ::flatbuffers::ForwardsUOffset>>>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_STRONG_REFERRABLES, vector_of_strong_referrables); - } - - #[inline] - pub fn add_co_owning_reference(&mut self, co_owning_reference: u64) { - self.fbb_.push_slot::(Monster::VT_CO_OWNING_REFERENCE, co_owning_reference, 0); - } - - #[inline] - pub fn add_vector_of_co_owning_references(&mut self, vector_of_co_owning_references: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , u64>>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_CO_OWNING_REFERENCES, vector_of_co_owning_references); - } - - #[inline] - pub fn add_non_owning_reference(&mut self, non_owning_reference: u64) { - self.fbb_.push_slot::(Monster::VT_NON_OWNING_REFERENCE, non_owning_reference, 0); - } - - #[inline] - pub fn add_vector_of_non_owning_references(&mut self, vector_of_non_owning_references: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , u64>>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_NON_OWNING_REFERENCES, vector_of_non_owning_references); - } - - #[inline] - pub fn add_any_unique_type(&mut self, any_unique_type: AnyUniqueAliases) { - self.fbb_.push_slot::(Monster::VT_ANY_UNIQUE_TYPE, any_unique_type, AnyUniqueAliases::NONE); - } - - #[inline] - pub fn add_any_unique(&mut self, any_unique: ::flatbuffers::WIPOffset<::flatbuffers::UnionWIPOffset>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_ANY_UNIQUE, any_unique); - } - - #[inline] - pub fn add_any_ambiguous_type(&mut self, any_ambiguous_type: AnyAmbiguousAliases) { - self.fbb_.push_slot::(Monster::VT_ANY_AMBIGUOUS_TYPE, any_ambiguous_type, AnyAmbiguousAliases::NONE); - } - - #[inline] - pub fn add_any_ambiguous(&mut self, any_ambiguous: ::flatbuffers::WIPOffset<::flatbuffers::UnionWIPOffset>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_ANY_AMBIGUOUS, any_ambiguous); - } - - #[inline] - pub fn add_vector_of_enums(&mut self, vector_of_enums: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , Color>>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_ENUMS, vector_of_enums); - } - - #[inline] - pub fn add_signed_enum(&mut self, signed_enum: Race) { - self.fbb_.push_slot::(Monster::VT_SIGNED_ENUM, signed_enum, Race::None); - } - - #[inline] - pub fn add_testrequirednestedflatbuffer(&mut self, testrequirednestedflatbuffer: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , u8>>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_TESTREQUIREDNESTEDFLATBUFFER, testrequirednestedflatbuffer); - } - - #[inline] - pub fn add_scalar_key_sorted_tables(&mut self, scalar_key_sorted_tables: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , ::flatbuffers::ForwardsUOffset>>>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_SCALAR_KEY_SORTED_TABLES, scalar_key_sorted_tables); - } - - #[inline] - pub fn add_native_inline(&mut self, native_inline: &Test) { - self.fbb_.push_slot_always::<&Test>(Monster::VT_NATIVE_INLINE, native_inline); - } - - #[inline] - pub fn add_long_enum_non_enum_default(&mut self, long_enum_non_enum_default: LongEnum) { - self.fbb_.push_slot::(Monster::VT_LONG_ENUM_NON_ENUM_DEFAULT, long_enum_non_enum_default, Default::default()); - } - - #[inline] - pub fn add_long_enum_normal_default(&mut self, long_enum_normal_default: LongEnum) { - self.fbb_.push_slot::(Monster::VT_LONG_ENUM_NORMAL_DEFAULT, long_enum_normal_default, LongEnum::LongOne); - } - - #[inline] - pub fn add_nan_default(&mut self, nan_default: f32) { - self.fbb_.push_slot::(Monster::VT_NAN_DEFAULT, nan_default, f32::NAN); - } - - #[inline] - pub fn add_inf_default(&mut self, inf_default: f32) { - self.fbb_.push_slot::(Monster::VT_INF_DEFAULT, inf_default, f32::INFINITY); - } - - #[inline] - pub fn add_positive_inf_default(&mut self, positive_inf_default: f32) { - self.fbb_.push_slot::(Monster::VT_POSITIVE_INF_DEFAULT, positive_inf_default, f32::INFINITY); - } - - #[inline] - pub fn add_infinity_default(&mut self, infinity_default: f32) { - self.fbb_.push_slot::(Monster::VT_INFINITY_DEFAULT, infinity_default, f32::INFINITY); - } - - #[inline] - pub fn add_positive_infinity_default(&mut self, positive_infinity_default: f32) { - self.fbb_.push_slot::(Monster::VT_POSITIVE_INFINITY_DEFAULT, positive_infinity_default, f32::INFINITY); - } - - #[inline] - pub fn add_negative_inf_default(&mut self, negative_inf_default: f32) { - self.fbb_.push_slot::(Monster::VT_NEGATIVE_INF_DEFAULT, negative_inf_default, f32::NEG_INFINITY); - } - - #[inline] - pub fn add_negative_infinity_default(&mut self, negative_infinity_default: f32) { - self.fbb_.push_slot::(Monster::VT_NEGATIVE_INFINITY_DEFAULT, negative_infinity_default, f32::NEG_INFINITY); - } - - #[inline] - pub fn add_double_inf_default(&mut self, double_inf_default: f64) { - self.fbb_.push_slot::(Monster::VT_DOUBLE_INF_DEFAULT, double_inf_default, f64::INFINITY); - } - - #[inline] - pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> MonsterBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - MonsterBuilder { - fbb_: _fbb, - start_: start, - } - } - - #[inline] - pub fn finish(self) -> ::flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - self.fbb_.required(o, Monster::VT_NAME,"name"); - ::flatbuffers::WIPOffset::new(o.value()) + #[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::(Monster::VT_MANA, mana, 150); + } + #[inline] + pub fn add_hp(&mut self, hp: i16) { + self.fbb_.push_slot::(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::(Monster::VT_COLOR, color, Color::Blue); + } + #[inline] + pub fn add_test_type(&mut self, test_type: Any) { + self.fbb_.push_slot::(Monster::VT_TEST_TYPE, test_type, Any::NONE); + } + #[inline] + pub fn add_test(&mut self, test: ::flatbuffers::WIPOffset<::flatbuffers::UnionWIPOffset>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_TEST, test); + } + #[inline] + pub fn add_test4(&mut self, test4: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , Test>>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_TEST4, test4); + } + #[inline] + pub fn add_testarrayofstring(&mut self, testarrayofstring: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , ::flatbuffers::ForwardsUOffset<&'b str>>>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_TESTARRAYOFSTRING, testarrayofstring); + } + #[inline] + pub fn add_testarrayoftables(&mut self, testarrayoftables: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , ::flatbuffers::ForwardsUOffset>>>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_TESTARRAYOFTABLES, testarrayoftables); + } + #[inline] + pub fn add_enemy(&mut self, enemy: ::flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset>(Monster::VT_ENEMY, enemy); + } + #[inline] + pub fn add_testnestedflatbuffer(&mut self, testnestedflatbuffer: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , u8>>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_TESTNESTEDFLATBUFFER, testnestedflatbuffer); + } + #[inline] + pub fn add_testempty(&mut self, testempty: ::flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset>(Monster::VT_TESTEMPTY, testempty); + } + #[inline] + pub fn add_testbool(&mut self, testbool: bool) { + self.fbb_.push_slot::(Monster::VT_TESTBOOL, testbool, false); + } + #[inline] + pub fn add_testhashs32_fnv1(&mut self, testhashs32_fnv1: i32) { + self.fbb_.push_slot::(Monster::VT_TESTHASHS32_FNV1, testhashs32_fnv1, 0); + } + #[inline] + pub fn add_testhashu32_fnv1(&mut self, testhashu32_fnv1: u32) { + self.fbb_.push_slot::(Monster::VT_TESTHASHU32_FNV1, testhashu32_fnv1, 0); + } + #[inline] + pub fn add_testhashs64_fnv1(&mut self, testhashs64_fnv1: i64) { + self.fbb_.push_slot::(Monster::VT_TESTHASHS64_FNV1, testhashs64_fnv1, 0); + } + #[inline] + pub fn add_testhashu64_fnv1(&mut self, testhashu64_fnv1: u64) { + self.fbb_.push_slot::(Monster::VT_TESTHASHU64_FNV1, testhashu64_fnv1, 0); + } + #[inline] + pub fn add_testhashs32_fnv1a(&mut self, testhashs32_fnv1a: i32) { + self.fbb_.push_slot::(Monster::VT_TESTHASHS32_FNV1A, testhashs32_fnv1a, 0); + } + #[inline] + pub fn add_testhashu32_fnv1a(&mut self, testhashu32_fnv1a: u32) { + self.fbb_.push_slot::(Monster::VT_TESTHASHU32_FNV1A, testhashu32_fnv1a, 0); + } + #[inline] + pub fn add_testhashs64_fnv1a(&mut self, testhashs64_fnv1a: i64) { + self.fbb_.push_slot::(Monster::VT_TESTHASHS64_FNV1A, testhashs64_fnv1a, 0); + } + #[inline] + pub fn add_testhashu64_fnv1a(&mut self, testhashu64_fnv1a: u64) { + self.fbb_.push_slot::(Monster::VT_TESTHASHU64_FNV1A, testhashu64_fnv1a, 0); + } + #[inline] + pub fn add_testarrayofbools(&mut self, testarrayofbools: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , bool>>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_TESTARRAYOFBOOLS, testarrayofbools); + } + #[inline] + pub fn add_testf(&mut self, testf: f32) { + self.fbb_.push_slot::(Monster::VT_TESTF, testf, 3.14159); + } + #[inline] + pub fn add_testf2(&mut self, testf2: f32) { + self.fbb_.push_slot::(Monster::VT_TESTF2, testf2, 3.0); + } + #[inline] + pub fn add_testf3(&mut self, testf3: f32) { + self.fbb_.push_slot::(Monster::VT_TESTF3, testf3, 0.0); + } + #[inline] + pub fn add_testarrayofstring2(&mut self, testarrayofstring2: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , ::flatbuffers::ForwardsUOffset<&'b str>>>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_TESTARRAYOFSTRING2, testarrayofstring2); + } + #[inline] + pub fn add_testarrayofsortedstruct(&mut self, testarrayofsortedstruct: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , Ability>>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_TESTARRAYOFSORTEDSTRUCT, testarrayofsortedstruct); + } + #[inline] + pub fn add_flex(&mut self, flex: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , u8>>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_FLEX, flex); + } + #[inline] + pub fn add_test5(&mut self, test5: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , Test>>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_TEST5, test5); + } + #[inline] + pub fn add_vector_of_longs(&mut self, vector_of_longs: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , i64>>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_LONGS, vector_of_longs); + } + #[inline] + pub fn add_vector_of_doubles(&mut self, vector_of_doubles: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , f64>>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_DOUBLES, vector_of_doubles); + } + #[inline] + pub fn add_parent_namespace_test(&mut self, parent_namespace_test: ::flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset>(Monster::VT_PARENT_NAMESPACE_TEST, parent_namespace_test); + } + #[inline] + pub fn add_vector_of_referrables(&mut self, vector_of_referrables: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , ::flatbuffers::ForwardsUOffset>>>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_REFERRABLES, vector_of_referrables); + } + #[inline] + pub fn add_single_weak_reference(&mut self, single_weak_reference: u64) { + self.fbb_.push_slot::(Monster::VT_SINGLE_WEAK_REFERENCE, single_weak_reference, 0); + } + #[inline] + pub fn add_vector_of_weak_references(&mut self, vector_of_weak_references: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , u64>>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_WEAK_REFERENCES, vector_of_weak_references); + } + #[inline] + pub fn add_vector_of_strong_referrables(&mut self, vector_of_strong_referrables: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , ::flatbuffers::ForwardsUOffset>>>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_STRONG_REFERRABLES, vector_of_strong_referrables); + } + #[inline] + pub fn add_co_owning_reference(&mut self, co_owning_reference: u64) { + self.fbb_.push_slot::(Monster::VT_CO_OWNING_REFERENCE, co_owning_reference, 0); + } + #[inline] + pub fn add_vector_of_co_owning_references(&mut self, vector_of_co_owning_references: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , u64>>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_CO_OWNING_REFERENCES, vector_of_co_owning_references); + } + #[inline] + pub fn add_non_owning_reference(&mut self, non_owning_reference: u64) { + self.fbb_.push_slot::(Monster::VT_NON_OWNING_REFERENCE, non_owning_reference, 0); + } + #[inline] + pub fn add_vector_of_non_owning_references(&mut self, vector_of_non_owning_references: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , u64>>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_NON_OWNING_REFERENCES, vector_of_non_owning_references); + } + #[inline] + pub fn add_any_unique_type(&mut self, any_unique_type: AnyUniqueAliases) { + self.fbb_.push_slot::(Monster::VT_ANY_UNIQUE_TYPE, any_unique_type, AnyUniqueAliases::NONE); + } + #[inline] + pub fn add_any_unique(&mut self, any_unique: ::flatbuffers::WIPOffset<::flatbuffers::UnionWIPOffset>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_ANY_UNIQUE, any_unique); + } + #[inline] + pub fn add_any_ambiguous_type(&mut self, any_ambiguous_type: AnyAmbiguousAliases) { + self.fbb_.push_slot::(Monster::VT_ANY_AMBIGUOUS_TYPE, any_ambiguous_type, AnyAmbiguousAliases::NONE); + } + #[inline] + pub fn add_any_ambiguous(&mut self, any_ambiguous: ::flatbuffers::WIPOffset<::flatbuffers::UnionWIPOffset>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_ANY_AMBIGUOUS, any_ambiguous); + } + #[inline] + pub fn add_vector_of_enums(&mut self, vector_of_enums: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , Color>>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_VECTOR_OF_ENUMS, vector_of_enums); + } + #[inline] + pub fn add_signed_enum(&mut self, signed_enum: Race) { + self.fbb_.push_slot::(Monster::VT_SIGNED_ENUM, signed_enum, Race::None); + } + #[inline] + pub fn add_testrequirednestedflatbuffer(&mut self, testrequirednestedflatbuffer: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , u8>>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_TESTREQUIREDNESTEDFLATBUFFER, testrequirednestedflatbuffer); + } + #[inline] + pub fn add_scalar_key_sorted_tables(&mut self, scalar_key_sorted_tables: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , ::flatbuffers::ForwardsUOffset>>>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Monster::VT_SCALAR_KEY_SORTED_TABLES, scalar_key_sorted_tables); + } + #[inline] + pub fn add_native_inline(&mut self, native_inline: &Test) { + self.fbb_.push_slot_always::<&Test>(Monster::VT_NATIVE_INLINE, native_inline); + } + #[inline] + pub fn add_long_enum_non_enum_default(&mut self, long_enum_non_enum_default: LongEnum) { + self.fbb_.push_slot::(Monster::VT_LONG_ENUM_NON_ENUM_DEFAULT, long_enum_non_enum_default, Default::default()); + } + #[inline] + pub fn add_long_enum_normal_default(&mut self, long_enum_normal_default: LongEnum) { + self.fbb_.push_slot::(Monster::VT_LONG_ENUM_NORMAL_DEFAULT, long_enum_normal_default, LongEnum::LongOne); + } + #[inline] + pub fn add_nan_default(&mut self, nan_default: f32) { + self.fbb_.push_slot::(Monster::VT_NAN_DEFAULT, nan_default, f32::NAN); + } + #[inline] + pub fn add_inf_default(&mut self, inf_default: f32) { + self.fbb_.push_slot::(Monster::VT_INF_DEFAULT, inf_default, f32::INFINITY); + } + #[inline] + pub fn add_positive_inf_default(&mut self, positive_inf_default: f32) { + self.fbb_.push_slot::(Monster::VT_POSITIVE_INF_DEFAULT, positive_inf_default, f32::INFINITY); + } + #[inline] + pub fn add_infinity_default(&mut self, infinity_default: f32) { + self.fbb_.push_slot::(Monster::VT_INFINITY_DEFAULT, infinity_default, f32::INFINITY); + } + #[inline] + pub fn add_positive_infinity_default(&mut self, positive_infinity_default: f32) { + self.fbb_.push_slot::(Monster::VT_POSITIVE_INFINITY_DEFAULT, positive_infinity_default, f32::INFINITY); + } + #[inline] + pub fn add_negative_inf_default(&mut self, negative_inf_default: f32) { + self.fbb_.push_slot::(Monster::VT_NEGATIVE_INF_DEFAULT, negative_inf_default, f32::NEG_INFINITY); + } + #[inline] + pub fn add_negative_infinity_default(&mut self, negative_infinity_default: f32) { + self.fbb_.push_slot::(Monster::VT_NEGATIVE_INFINITY_DEFAULT, negative_infinity_default, f32::NEG_INFINITY); + } + #[inline] + pub fn add_double_inf_default(&mut self, double_inf_default: f64) { + self.fbb_.push_slot::(Monster::VT_DOUBLE_INF_DEFAULT, double_inf_default, f64::INFINITY); + } + #[inline] + pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> MonsterBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + MonsterBuilder { + fbb_: _fbb, + start_: start, } + } + #[inline] + pub fn finish(self) -> ::flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + self.fbb_.required(o, Monster::VT_NAME,"name"); + ::flatbuffers::WIPOffset::new(o.value()) + } } impl ::core::fmt::Debug for Monster<'_> { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - let mut ds = f.debug_struct("Monster"); - ds.field("pos", &self.pos()); - ds.field("mana", &self.mana()); - ds.field("hp", &self.hp()); - ds.field("name", &self.name()); - ds.field("inventory", &self.inventory()); - ds.field("color", &self.color()); - ds.field("test_type", &self.test_type()); - match self.test_type() { - Any::Monster => { - if let Some(x) = self.test_as_monster() { - ds.field("test", &x) - } else { - ds.field("test", &"InvalidFlatbuffer: Union discriminant does not match value.") - } - }, - Any::TestSimpleTableWithEnum => { - if let Some(x) = self.test_as_test_simple_table_with_enum() { - ds.field("test", &x) - } else { - ds.field("test", &"InvalidFlatbuffer: Union discriminant does not match value.") - } - }, - Any::MyGame_Example2_Monster => { - if let Some(x) = self.test_as_my_game_example_2_monster() { - ds.field("test", &x) - } else { - ds.field("test", &"InvalidFlatbuffer: Union discriminant does not match value.") - } - }, - _ => { - let x: Option<()> = None; - ds.field("test", &x) - }, - }; - ds.field("test4", &self.test4()); - ds.field("testarrayofstring", &self.testarrayofstring()); - ds.field("testarrayoftables", &self.testarrayoftables()); - ds.field("enemy", &self.enemy()); - ds.field("testnestedflatbuffer", &self.testnestedflatbuffer()); - ds.field("testempty", &self.testempty()); - ds.field("testbool", &self.testbool()); - ds.field("testhashs32_fnv1", &self.testhashs32_fnv1()); - ds.field("testhashu32_fnv1", &self.testhashu32_fnv1()); - ds.field("testhashs64_fnv1", &self.testhashs64_fnv1()); - ds.field("testhashu64_fnv1", &self.testhashu64_fnv1()); - ds.field("testhashs32_fnv1a", &self.testhashs32_fnv1a()); - ds.field("testhashu32_fnv1a", &self.testhashu32_fnv1a()); - ds.field("testhashs64_fnv1a", &self.testhashs64_fnv1a()); - ds.field("testhashu64_fnv1a", &self.testhashu64_fnv1a()); - ds.field("testarrayofbools", &self.testarrayofbools()); - ds.field("testf", &self.testf()); - ds.field("testf2", &self.testf2()); - ds.field("testf3", &self.testf3()); - ds.field("testarrayofstring2", &self.testarrayofstring2()); - ds.field("testarrayofsortedstruct", &self.testarrayofsortedstruct()); - ds.field("flex", &self.flex()); - ds.field("test5", &self.test5()); - ds.field("vector_of_longs", &self.vector_of_longs()); - ds.field("vector_of_doubles", &self.vector_of_doubles()); - ds.field("parent_namespace_test", &self.parent_namespace_test()); - ds.field("vector_of_referrables", &self.vector_of_referrables()); - ds.field("single_weak_reference", &self.single_weak_reference()); - ds.field("vector_of_weak_references", &self.vector_of_weak_references()); - ds.field("vector_of_strong_referrables", &self.vector_of_strong_referrables()); - ds.field("co_owning_reference", &self.co_owning_reference()); - ds.field("vector_of_co_owning_references", &self.vector_of_co_owning_references()); - ds.field("non_owning_reference", &self.non_owning_reference()); - ds.field("vector_of_non_owning_references", &self.vector_of_non_owning_references()); - ds.field("any_unique_type", &self.any_unique_type()); - match self.any_unique_type() { - AnyUniqueAliases::M => { - if let Some(x) = self.any_unique_as_m() { - ds.field("any_unique", &x) - } else { - ds.field("any_unique", &"InvalidFlatbuffer: Union discriminant does not match value.") - } - }, - AnyUniqueAliases::TS => { - if let Some(x) = self.any_unique_as_ts() { - ds.field("any_unique", &x) - } else { - ds.field("any_unique", &"InvalidFlatbuffer: Union discriminant does not match value.") - } - }, - AnyUniqueAliases::M2 => { - if let Some(x) = self.any_unique_as_m2() { - ds.field("any_unique", &x) - } else { - ds.field("any_unique", &"InvalidFlatbuffer: Union discriminant does not match value.") - } - }, - _ => { - let x: Option<()> = None; - ds.field("any_unique", &x) - }, - }; - ds.field("any_ambiguous_type", &self.any_ambiguous_type()); - match self.any_ambiguous_type() { - AnyAmbiguousAliases::M1 => { - if let Some(x) = self.any_ambiguous_as_m1() { - ds.field("any_ambiguous", &x) - } else { - ds.field("any_ambiguous", &"InvalidFlatbuffer: Union discriminant does not match value.") - } - }, - AnyAmbiguousAliases::M2 => { - if let Some(x) = self.any_ambiguous_as_m2() { - ds.field("any_ambiguous", &x) - } else { - ds.field("any_ambiguous", &"InvalidFlatbuffer: Union discriminant does not match value.") - } - }, - AnyAmbiguousAliases::M3 => { - if let Some(x) = self.any_ambiguous_as_m3() { - ds.field("any_ambiguous", &x) - } else { - ds.field("any_ambiguous", &"InvalidFlatbuffer: Union discriminant does not match value.") - } - }, - _ => { - let x: Option<()> = None; - ds.field("any_ambiguous", &x) - }, - }; - ds.field("vector_of_enums", &self.vector_of_enums()); - ds.field("signed_enum", &self.signed_enum()); - ds.field("testrequirednestedflatbuffer", &self.testrequirednestedflatbuffer()); - ds.field("scalar_key_sorted_tables", &self.scalar_key_sorted_tables()); - ds.field("native_inline", &self.native_inline()); - ds.field("long_enum_non_enum_default", &self.long_enum_non_enum_default()); - ds.field("long_enum_normal_default", &self.long_enum_normal_default()); - ds.field("nan_default", &self.nan_default()); - ds.field("inf_default", &self.inf_default()); - ds.field("positive_inf_default", &self.positive_inf_default()); - ds.field("infinity_default", &self.infinity_default()); - ds.field("positive_infinity_default", &self.positive_infinity_default()); - ds.field("negative_inf_default", &self.negative_inf_default()); - ds.field("negative_infinity_default", &self.negative_infinity_default()); - ds.field("double_inf_default", &self.double_inf_default()); - ds.finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + let mut ds = f.debug_struct("Monster"); + ds.field("pos", &self.pos()); + ds.field("mana", &self.mana()); + ds.field("hp", &self.hp()); + ds.field("name", &self.name()); + ds.field("inventory", &self.inventory()); + ds.field("color", &self.color()); + ds.field("test_type", &self.test_type()); + match self.test_type() { + Any::Monster => { + if let Some(x) = self.test_as_monster() { + ds.field("test", &x) + } else { + ds.field("test", &"InvalidFlatbuffer: Union discriminant does not match value.") + } + }, + Any::TestSimpleTableWithEnum => { + if let Some(x) = self.test_as_test_simple_table_with_enum() { + ds.field("test", &x) + } else { + ds.field("test", &"InvalidFlatbuffer: Union discriminant does not match value.") + } + }, + Any::MyGame_Example2_Monster => { + if let Some(x) = self.test_as_my_game_example_2_monster() { + ds.field("test", &x) + } else { + ds.field("test", &"InvalidFlatbuffer: Union discriminant does not match value.") + } + }, + _ => { + let x: Option<()> = None; + ds.field("test", &x) + }, + }; + ds.field("test4", &self.test4()); + ds.field("testarrayofstring", &self.testarrayofstring()); + ds.field("testarrayoftables", &self.testarrayoftables()); + ds.field("enemy", &self.enemy()); + ds.field("testnestedflatbuffer", &self.testnestedflatbuffer()); + ds.field("testempty", &self.testempty()); + ds.field("testbool", &self.testbool()); + ds.field("testhashs32_fnv1", &self.testhashs32_fnv1()); + ds.field("testhashu32_fnv1", &self.testhashu32_fnv1()); + ds.field("testhashs64_fnv1", &self.testhashs64_fnv1()); + ds.field("testhashu64_fnv1", &self.testhashu64_fnv1()); + ds.field("testhashs32_fnv1a", &self.testhashs32_fnv1a()); + ds.field("testhashu32_fnv1a", &self.testhashu32_fnv1a()); + ds.field("testhashs64_fnv1a", &self.testhashs64_fnv1a()); + ds.field("testhashu64_fnv1a", &self.testhashu64_fnv1a()); + ds.field("testarrayofbools", &self.testarrayofbools()); + ds.field("testf", &self.testf()); + ds.field("testf2", &self.testf2()); + ds.field("testf3", &self.testf3()); + ds.field("testarrayofstring2", &self.testarrayofstring2()); + ds.field("testarrayofsortedstruct", &self.testarrayofsortedstruct()); + ds.field("flex", &self.flex()); + ds.field("test5", &self.test5()); + ds.field("vector_of_longs", &self.vector_of_longs()); + ds.field("vector_of_doubles", &self.vector_of_doubles()); + ds.field("parent_namespace_test", &self.parent_namespace_test()); + ds.field("vector_of_referrables", &self.vector_of_referrables()); + ds.field("single_weak_reference", &self.single_weak_reference()); + ds.field("vector_of_weak_references", &self.vector_of_weak_references()); + ds.field("vector_of_strong_referrables", &self.vector_of_strong_referrables()); + ds.field("co_owning_reference", &self.co_owning_reference()); + ds.field("vector_of_co_owning_references", &self.vector_of_co_owning_references()); + ds.field("non_owning_reference", &self.non_owning_reference()); + ds.field("vector_of_non_owning_references", &self.vector_of_non_owning_references()); + ds.field("any_unique_type", &self.any_unique_type()); + match self.any_unique_type() { + AnyUniqueAliases::M => { + if let Some(x) = self.any_unique_as_m() { + ds.field("any_unique", &x) + } else { + ds.field("any_unique", &"InvalidFlatbuffer: Union discriminant does not match value.") + } + }, + AnyUniqueAliases::TS => { + if let Some(x) = self.any_unique_as_ts() { + ds.field("any_unique", &x) + } else { + ds.field("any_unique", &"InvalidFlatbuffer: Union discriminant does not match value.") + } + }, + AnyUniqueAliases::M2 => { + if let Some(x) = self.any_unique_as_m2() { + ds.field("any_unique", &x) + } else { + ds.field("any_unique", &"InvalidFlatbuffer: Union discriminant does not match value.") + } + }, + _ => { + let x: Option<()> = None; + ds.field("any_unique", &x) + }, + }; + ds.field("any_ambiguous_type", &self.any_ambiguous_type()); + match self.any_ambiguous_type() { + AnyAmbiguousAliases::M1 => { + if let Some(x) = self.any_ambiguous_as_m1() { + ds.field("any_ambiguous", &x) + } else { + ds.field("any_ambiguous", &"InvalidFlatbuffer: Union discriminant does not match value.") + } + }, + AnyAmbiguousAliases::M2 => { + if let Some(x) = self.any_ambiguous_as_m2() { + ds.field("any_ambiguous", &x) + } else { + ds.field("any_ambiguous", &"InvalidFlatbuffer: Union discriminant does not match value.") + } + }, + AnyAmbiguousAliases::M3 => { + if let Some(x) = self.any_ambiguous_as_m3() { + ds.field("any_ambiguous", &x) + } else { + ds.field("any_ambiguous", &"InvalidFlatbuffer: Union discriminant does not match value.") + } + }, + _ => { + let x: Option<()> = None; + ds.field("any_ambiguous", &x) + }, + }; + ds.field("vector_of_enums", &self.vector_of_enums()); + ds.field("signed_enum", &self.signed_enum()); + ds.field("testrequirednestedflatbuffer", &self.testrequirednestedflatbuffer()); + ds.field("scalar_key_sorted_tables", &self.scalar_key_sorted_tables()); + ds.field("native_inline", &self.native_inline()); + ds.field("long_enum_non_enum_default", &self.long_enum_non_enum_default()); + ds.field("long_enum_normal_default", &self.long_enum_normal_default()); + ds.field("nan_default", &self.nan_default()); + ds.field("inf_default", &self.inf_default()); + ds.field("positive_inf_default", &self.positive_inf_default()); + ds.field("infinity_default", &self.infinity_default()); + ds.field("positive_infinity_default", &self.positive_infinity_default()); + ds.field("negative_inf_default", &self.negative_inf_default()); + ds.field("negative_infinity_default", &self.negative_infinity_default()); + ds.field("double_inf_default", &self.double_inf_default()); + ds.finish() + } } - #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub struct MonsterT { - pub pos: Option, - pub mana: i16, - pub hp: i16, - pub name: alloc::string::String, - pub inventory: Option>, - pub color: Color, - pub test: AnyT, - pub test4: Option>, - pub testarrayofstring: Option>, - pub testarrayoftables: Option>, - pub enemy: Option>, - pub testnestedflatbuffer: Option>, - pub testempty: Option>, - pub testbool: bool, - pub testhashs32_fnv1: i32, - pub testhashu32_fnv1: u32, - pub testhashs64_fnv1: i64, - pub testhashu64_fnv1: u64, - pub testhashs32_fnv1a: i32, - pub testhashu32_fnv1a: u32, - pub testhashs64_fnv1a: i64, - pub testhashu64_fnv1a: u64, - pub testarrayofbools: Option>, - pub testf: f32, - pub testf2: f32, - pub testf3: f32, - pub testarrayofstring2: Option>, - pub testarrayofsortedstruct: Option>, - pub flex: Option>, - pub test5: Option>, - pub vector_of_longs: Option>, - pub vector_of_doubles: Option>, - pub parent_namespace_test: Option>, - pub vector_of_referrables: Option>, - pub single_weak_reference: u64, - pub vector_of_weak_references: Option>, - pub vector_of_strong_referrables: Option>, - pub co_owning_reference: u64, - pub vector_of_co_owning_references: Option>, - pub non_owning_reference: u64, - pub vector_of_non_owning_references: Option>, - pub any_unique: AnyUniqueAliasesT, - pub any_ambiguous: AnyAmbiguousAliasesT, - pub vector_of_enums: Option>, - pub signed_enum: Race, - pub testrequirednestedflatbuffer: Option>, - pub scalar_key_sorted_tables: Option>, - pub native_inline: Option, - pub long_enum_non_enum_default: LongEnum, - pub long_enum_normal_default: LongEnum, - pub nan_default: f32, - pub inf_default: f32, - pub positive_inf_default: f32, - pub infinity_default: f32, - pub positive_infinity_default: f32, - pub negative_inf_default: f32, - pub negative_infinity_default: f32, - pub double_inf_default: f64, + pub pos: Option, + pub mana: i16, + pub hp: i16, + pub name: alloc::string::String, + pub inventory: Option>, + pub color: Color, + pub test: AnyT, + pub test4: Option>, + pub testarrayofstring: Option>, + pub testarrayoftables: Option>, + pub enemy: Option>, + pub testnestedflatbuffer: Option>, + pub testempty: Option>, + pub testbool: bool, + pub testhashs32_fnv1: i32, + pub testhashu32_fnv1: u32, + pub testhashs64_fnv1: i64, + pub testhashu64_fnv1: u64, + pub testhashs32_fnv1a: i32, + pub testhashu32_fnv1a: u32, + pub testhashs64_fnv1a: i64, + pub testhashu64_fnv1a: u64, + pub testarrayofbools: Option>, + pub testf: f32, + pub testf2: f32, + pub testf3: f32, + pub testarrayofstring2: Option>, + pub testarrayofsortedstruct: Option>, + pub flex: Option>, + pub test5: Option>, + pub vector_of_longs: Option>, + pub vector_of_doubles: Option>, + pub parent_namespace_test: Option>, + pub vector_of_referrables: Option>, + pub single_weak_reference: u64, + pub vector_of_weak_references: Option>, + pub vector_of_strong_referrables: Option>, + pub co_owning_reference: u64, + pub vector_of_co_owning_references: Option>, + pub non_owning_reference: u64, + pub vector_of_non_owning_references: Option>, + pub any_unique: AnyUniqueAliasesT, + pub any_ambiguous: AnyAmbiguousAliasesT, + pub vector_of_enums: Option>, + pub signed_enum: Race, + pub testrequirednestedflatbuffer: Option>, + pub scalar_key_sorted_tables: Option>, + pub native_inline: Option, + pub long_enum_non_enum_default: LongEnum, + pub long_enum_normal_default: LongEnum, + pub nan_default: f32, + pub inf_default: f32, + pub positive_inf_default: f32, + pub infinity_default: f32, + pub positive_infinity_default: f32, + pub negative_inf_default: f32, + pub negative_infinity_default: f32, + pub double_inf_default: f64, } - impl Default for MonsterT { - fn default() -> Self { - Self { - pos: None, - mana: 150, - hp: 100, - name: alloc::string::ToString::to_string(""), - inventory: None, - color: Color::Blue, - test: AnyT::NONE, - test4: None, - testarrayofstring: None, - testarrayoftables: None, - enemy: None, - testnestedflatbuffer: None, - testempty: None, - testbool: false, - testhashs32_fnv1: 0, - testhashu32_fnv1: 0, - testhashs64_fnv1: 0, - testhashu64_fnv1: 0, - testhashs32_fnv1a: 0, - testhashu32_fnv1a: 0, - testhashs64_fnv1a: 0, - testhashu64_fnv1a: 0, - testarrayofbools: None, - testf: 3.14159, - testf2: 3.0, - testf3: 0.0, - testarrayofstring2: None, - testarrayofsortedstruct: None, - flex: None, - test5: None, - vector_of_longs: None, - vector_of_doubles: None, - parent_namespace_test: None, - vector_of_referrables: None, - single_weak_reference: 0, - vector_of_weak_references: None, - vector_of_strong_referrables: None, - co_owning_reference: 0, - vector_of_co_owning_references: None, - non_owning_reference: 0, - vector_of_non_owning_references: None, - any_unique: AnyUniqueAliasesT::NONE, - any_ambiguous: AnyAmbiguousAliasesT::NONE, - vector_of_enums: None, - signed_enum: Race::None, - testrequirednestedflatbuffer: None, - scalar_key_sorted_tables: None, - native_inline: None, - long_enum_non_enum_default: Default::default(), - long_enum_normal_default: LongEnum::LongOne, - nan_default: f32::NAN, - inf_default: f32::INFINITY, - positive_inf_default: f32::INFINITY, - infinity_default: f32::INFINITY, - positive_infinity_default: f32::INFINITY, - negative_inf_default: f32::NEG_INFINITY, - negative_infinity_default: f32::NEG_INFINITY, - double_inf_default: f64::INFINITY, - } + fn default() -> Self { + Self { + pos: None, + mana: 150, + hp: 100, + name: alloc::string::ToString::to_string(""), + inventory: None, + color: Color::Blue, + test: AnyT::NONE, + test4: None, + testarrayofstring: None, + testarrayoftables: None, + enemy: None, + testnestedflatbuffer: None, + testempty: None, + testbool: false, + testhashs32_fnv1: 0, + testhashu32_fnv1: 0, + testhashs64_fnv1: 0, + testhashu64_fnv1: 0, + testhashs32_fnv1a: 0, + testhashu32_fnv1a: 0, + testhashs64_fnv1a: 0, + testhashu64_fnv1a: 0, + testarrayofbools: None, + testf: 3.14159, + testf2: 3.0, + testf3: 0.0, + testarrayofstring2: None, + testarrayofsortedstruct: None, + flex: None, + test5: None, + vector_of_longs: None, + vector_of_doubles: None, + parent_namespace_test: None, + vector_of_referrables: None, + single_weak_reference: 0, + vector_of_weak_references: None, + vector_of_strong_referrables: None, + co_owning_reference: 0, + vector_of_co_owning_references: None, + non_owning_reference: 0, + vector_of_non_owning_references: None, + any_unique: AnyUniqueAliasesT::NONE, + any_ambiguous: AnyAmbiguousAliasesT::NONE, + vector_of_enums: None, + signed_enum: Race::None, + testrequirednestedflatbuffer: None, + scalar_key_sorted_tables: None, + native_inline: None, + long_enum_non_enum_default: Default::default(), + long_enum_normal_default: LongEnum::LongOne, + nan_default: f32::NAN, + inf_default: f32::INFINITY, + positive_inf_default: f32::INFINITY, + infinity_default: f32::INFINITY, + positive_infinity_default: f32::INFINITY, + negative_inf_default: f32::NEG_INFINITY, + negative_infinity_default: f32::NEG_INFINITY, + double_inf_default: f64::INFINITY, } + } } - impl MonsterT { - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( - &self, - _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> - ) -> ::flatbuffers::WIPOffset> { - let pos_tmp = self.pos.as_ref().map(|x| x.pack()); - let pos = pos_tmp.as_ref(); - let mana = self.mana; - let hp = self.hp; - let name = Some({ - let x = &self.name; - _fbb.create_string(x) - }); - let inventory = self.inventory.as_ref().map(|x|{ - _fbb.create_vector(x) - }); - let color = self.color; - let test_type = self.test.any_type(); - let test = self.test.pack(_fbb); - let test4 = self.test4.as_ref().map(|x|{ - let w: alloc::vec::Vec<_> = x.iter().map(|t| t.pack()).collect();_fbb.create_vector(&w) - }); - let testarrayofstring = self.testarrayofstring.as_ref().map(|x|{ - let w: alloc::vec::Vec<_> = x.iter().map(|s| _fbb.create_string(s)).collect();_fbb.create_vector(&w) - }); - let testarrayoftables = self.testarrayoftables.as_ref().map(|x|{ - let w: alloc::vec::Vec<_> = x.iter().map(|t| t.pack(_fbb)).collect();_fbb.create_vector(&w) - }); - let enemy = self.enemy.as_ref().map(|x|{ - x.pack(_fbb) - }); - let testnestedflatbuffer = self.testnestedflatbuffer.as_ref().map(|x|{ - _fbb.create_vector(x) - }); - let testempty = self.testempty.as_ref().map(|x|{ - x.pack(_fbb) - }); - let testbool = self.testbool; - let testhashs32_fnv1 = self.testhashs32_fnv1; - let testhashu32_fnv1 = self.testhashu32_fnv1; - let testhashs64_fnv1 = self.testhashs64_fnv1; - let testhashu64_fnv1 = self.testhashu64_fnv1; - let testhashs32_fnv1a = self.testhashs32_fnv1a; - let testhashu32_fnv1a = self.testhashu32_fnv1a; - let testhashs64_fnv1a = self.testhashs64_fnv1a; - let testhashu64_fnv1a = self.testhashu64_fnv1a; - let testarrayofbools = self.testarrayofbools.as_ref().map(|x|{ - _fbb.create_vector(x) - }); - let testf = self.testf; - let testf2 = self.testf2; - let testf3 = self.testf3; - let testarrayofstring2 = self.testarrayofstring2.as_ref().map(|x|{ - let w: alloc::vec::Vec<_> = x.iter().map(|s| _fbb.create_string(s)).collect();_fbb.create_vector(&w) - }); - let testarrayofsortedstruct = self.testarrayofsortedstruct.as_ref().map(|x|{ - let w: alloc::vec::Vec<_> = x.iter().map(|t| t.pack()).collect();_fbb.create_vector(&w) - }); - let flex = self.flex.as_ref().map(|x|{ - _fbb.create_vector(x) - }); - let test5 = self.test5.as_ref().map(|x|{ - let w: alloc::vec::Vec<_> = x.iter().map(|t| t.pack()).collect();_fbb.create_vector(&w) - }); - let vector_of_longs = self.vector_of_longs.as_ref().map(|x|{ - _fbb.create_vector(x) - }); - let vector_of_doubles = self.vector_of_doubles.as_ref().map(|x|{ - _fbb.create_vector(x) - }); - let parent_namespace_test = self.parent_namespace_test.as_ref().map(|x|{ - x.pack(_fbb) - }); - let vector_of_referrables = self.vector_of_referrables.as_ref().map(|x|{ - let w: alloc::vec::Vec<_> = x.iter().map(|t| t.pack(_fbb)).collect();_fbb.create_vector(&w) - }); - let single_weak_reference = self.single_weak_reference; - let vector_of_weak_references = self.vector_of_weak_references.as_ref().map(|x|{ - _fbb.create_vector(x) - }); - let vector_of_strong_referrables = self.vector_of_strong_referrables.as_ref().map(|x|{ - let w: alloc::vec::Vec<_> = x.iter().map(|t| t.pack(_fbb)).collect();_fbb.create_vector(&w) - }); - let co_owning_reference = self.co_owning_reference; - let vector_of_co_owning_references = self.vector_of_co_owning_references.as_ref().map(|x|{ - _fbb.create_vector(x) - }); - let non_owning_reference = self.non_owning_reference; - let vector_of_non_owning_references = self.vector_of_non_owning_references.as_ref().map(|x|{ - _fbb.create_vector(x) - }); - let any_unique_type = self.any_unique.any_unique_aliases_type(); - let any_unique = self.any_unique.pack(_fbb); - let any_ambiguous_type = self.any_ambiguous.any_ambiguous_aliases_type(); - let any_ambiguous = self.any_ambiguous.pack(_fbb); - let vector_of_enums = self.vector_of_enums.as_ref().map(|x|{ - _fbb.create_vector(x) - }); - let signed_enum = self.signed_enum; - let testrequirednestedflatbuffer = self.testrequirednestedflatbuffer.as_ref().map(|x|{ - _fbb.create_vector(x) - }); - let scalar_key_sorted_tables = self.scalar_key_sorted_tables.as_ref().map(|x|{ - let w: alloc::vec::Vec<_> = x.iter().map(|t| t.pack(_fbb)).collect();_fbb.create_vector(&w) - }); - let native_inline_tmp = self.native_inline.as_ref().map(|x| x.pack()); - let native_inline = native_inline_tmp.as_ref(); - let long_enum_non_enum_default = self.long_enum_non_enum_default; - let long_enum_normal_default = self.long_enum_normal_default; - let nan_default = self.nan_default; - let inf_default = self.inf_default; - let positive_inf_default = self.positive_inf_default; - let infinity_default = self.infinity_default; - let positive_infinity_default = self.positive_infinity_default; - let negative_inf_default = self.negative_inf_default; - let negative_infinity_default = self.negative_infinity_default; - let double_inf_default = self.double_inf_default; - Monster::create(_fbb, &MonsterArgs{ - pos, - mana, - hp, - name, - inventory, - color, - test_type, - test, - test4, - testarrayofstring, - testarrayoftables, - enemy, - testnestedflatbuffer, - testempty, - testbool, - testhashs32_fnv1, - testhashu32_fnv1, - testhashs64_fnv1, - testhashu64_fnv1, - testhashs32_fnv1a, - testhashu32_fnv1a, - testhashs64_fnv1a, - testhashu64_fnv1a, - testarrayofbools, - testf, - testf2, - testf3, - testarrayofstring2, - testarrayofsortedstruct, - flex, - test5, - vector_of_longs, - vector_of_doubles, - parent_namespace_test, - vector_of_referrables, - single_weak_reference, - vector_of_weak_references, - vector_of_strong_referrables, - co_owning_reference, - vector_of_co_owning_references, - non_owning_reference, - vector_of_non_owning_references, - any_unique_type, - any_unique, - any_ambiguous_type, - any_ambiguous, - vector_of_enums, - signed_enum, - testrequirednestedflatbuffer, - scalar_key_sorted_tables, - native_inline, - long_enum_non_enum_default, - long_enum_normal_default, - nan_default, - inf_default, - positive_inf_default, - infinity_default, - positive_infinity_default, - negative_inf_default, - negative_infinity_default, - double_inf_default, - }) - } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> + ) -> ::flatbuffers::WIPOffset> { + let pos_tmp = self.pos.as_ref().map(|x| x.pack()); + let pos = pos_tmp.as_ref(); + let mana = self.mana; + let hp = self.hp; + let name = Some({ + let x = &self.name; + _fbb.create_string(x) + }); + let inventory = self.inventory.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + let color = self.color; + let test_type = self.test.any_type(); + let test = self.test.pack(_fbb); + let test4 = self.test4.as_ref().map(|x|{ + let w: alloc::vec::Vec<_> = x.iter().map(|t| t.pack()).collect();_fbb.create_vector(&w) + }); + let testarrayofstring = self.testarrayofstring.as_ref().map(|x|{ + let w: alloc::vec::Vec<_> = x.iter().map(|s| _fbb.create_string(s)).collect();_fbb.create_vector(&w) + }); + let testarrayoftables = self.testarrayoftables.as_ref().map(|x|{ + let w: alloc::vec::Vec<_> = x.iter().map(|t| t.pack(_fbb)).collect();_fbb.create_vector(&w) + }); + let enemy = self.enemy.as_ref().map(|x|{ + x.pack(_fbb) + }); + let testnestedflatbuffer = self.testnestedflatbuffer.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + let testempty = self.testempty.as_ref().map(|x|{ + x.pack(_fbb) + }); + let testbool = self.testbool; + let testhashs32_fnv1 = self.testhashs32_fnv1; + let testhashu32_fnv1 = self.testhashu32_fnv1; + let testhashs64_fnv1 = self.testhashs64_fnv1; + let testhashu64_fnv1 = self.testhashu64_fnv1; + let testhashs32_fnv1a = self.testhashs32_fnv1a; + let testhashu32_fnv1a = self.testhashu32_fnv1a; + let testhashs64_fnv1a = self.testhashs64_fnv1a; + let testhashu64_fnv1a = self.testhashu64_fnv1a; + let testarrayofbools = self.testarrayofbools.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + let testf = self.testf; + let testf2 = self.testf2; + let testf3 = self.testf3; + let testarrayofstring2 = self.testarrayofstring2.as_ref().map(|x|{ + let w: alloc::vec::Vec<_> = x.iter().map(|s| _fbb.create_string(s)).collect();_fbb.create_vector(&w) + }); + let testarrayofsortedstruct = self.testarrayofsortedstruct.as_ref().map(|x|{ + let w: alloc::vec::Vec<_> = x.iter().map(|t| t.pack()).collect();_fbb.create_vector(&w) + }); + let flex = self.flex.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + let test5 = self.test5.as_ref().map(|x|{ + let w: alloc::vec::Vec<_> = x.iter().map(|t| t.pack()).collect();_fbb.create_vector(&w) + }); + let vector_of_longs = self.vector_of_longs.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + let vector_of_doubles = self.vector_of_doubles.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + let parent_namespace_test = self.parent_namespace_test.as_ref().map(|x|{ + x.pack(_fbb) + }); + let vector_of_referrables = self.vector_of_referrables.as_ref().map(|x|{ + let w: alloc::vec::Vec<_> = x.iter().map(|t| t.pack(_fbb)).collect();_fbb.create_vector(&w) + }); + let single_weak_reference = self.single_weak_reference; + let vector_of_weak_references = self.vector_of_weak_references.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + let vector_of_strong_referrables = self.vector_of_strong_referrables.as_ref().map(|x|{ + let w: alloc::vec::Vec<_> = x.iter().map(|t| t.pack(_fbb)).collect();_fbb.create_vector(&w) + }); + let co_owning_reference = self.co_owning_reference; + let vector_of_co_owning_references = self.vector_of_co_owning_references.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + let non_owning_reference = self.non_owning_reference; + let vector_of_non_owning_references = self.vector_of_non_owning_references.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + let any_unique_type = self.any_unique.any_unique_aliases_type(); + let any_unique = self.any_unique.pack(_fbb); + let any_ambiguous_type = self.any_ambiguous.any_ambiguous_aliases_type(); + let any_ambiguous = self.any_ambiguous.pack(_fbb); + let vector_of_enums = self.vector_of_enums.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + let signed_enum = self.signed_enum; + let testrequirednestedflatbuffer = self.testrequirednestedflatbuffer.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + let scalar_key_sorted_tables = self.scalar_key_sorted_tables.as_ref().map(|x|{ + let w: alloc::vec::Vec<_> = x.iter().map(|t| t.pack(_fbb)).collect();_fbb.create_vector(&w) + }); + let native_inline_tmp = self.native_inline.as_ref().map(|x| x.pack()); + let native_inline = native_inline_tmp.as_ref(); + let long_enum_non_enum_default = self.long_enum_non_enum_default; + let long_enum_normal_default = self.long_enum_normal_default; + let nan_default = self.nan_default; + let inf_default = self.inf_default; + let positive_inf_default = self.positive_inf_default; + let infinity_default = self.infinity_default; + let positive_infinity_default = self.positive_infinity_default; + let negative_inf_default = self.negative_inf_default; + let negative_infinity_default = self.negative_infinity_default; + let double_inf_default = self.double_inf_default; + Monster::create(_fbb, &MonsterArgs{ + pos, + mana, + hp, + name, + inventory, + color, + test_type, + test, + test4, + testarrayofstring, + testarrayoftables, + enemy, + testnestedflatbuffer, + testempty, + testbool, + testhashs32_fnv1, + testhashu32_fnv1, + testhashs64_fnv1, + testhashu64_fnv1, + testhashs32_fnv1a, + testhashu32_fnv1a, + testhashs64_fnv1a, + testhashu64_fnv1a, + testarrayofbools, + testf, + testf2, + testf3, + testarrayofstring2, + testarrayofsortedstruct, + flex, + test5, + vector_of_longs, + vector_of_doubles, + parent_namespace_test, + vector_of_referrables, + single_weak_reference, + vector_of_weak_references, + vector_of_strong_referrables, + co_owning_reference, + vector_of_co_owning_references, + non_owning_reference, + vector_of_non_owning_references, + any_unique_type, + any_unique, + any_ambiguous_type, + any_ambiguous, + vector_of_enums, + signed_enum, + testrequirednestedflatbuffer, + scalar_key_sorted_tables, + native_inline, + long_enum_non_enum_default, + long_enum_normal_default, + nan_default, + inf_default, + positive_inf_default, + infinity_default, + positive_infinity_default, + negative_inf_default, + negative_infinity_default, + double_inf_default, + }) + } } - +#[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`. -#[inline] pub fn root_as_monster(buf: &[u8]) -> Result, ::flatbuffers::InvalidFlatbuffer> { - ::flatbuffers::root::(buf) + ::flatbuffers::root::(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`. -#[inline] pub fn size_prefixed_root_as_monster(buf: &[u8]) -> Result, ::flatbuffers::InvalidFlatbuffer> { - ::flatbuffers::size_prefixed_root::(buf) + ::flatbuffers::size_prefixed_root::(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`. -#[inline] pub fn root_as_monster_with_opts<'b, 'o>( - opts: &'o ::flatbuffers::VerifierOptions, - buf: &'b [u8], + opts: &'o ::flatbuffers::VerifierOptions, + buf: &'b [u8], ) -> Result, ::flatbuffers::InvalidFlatbuffer> { - ::flatbuffers::root_with_opts::>(opts, buf) + ::flatbuffers::root_with_opts::>(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`. -#[inline] pub fn size_prefixed_root_as_monster_with_opts<'b, 'o>( - opts: &'o ::flatbuffers::VerifierOptions, - buf: &'b [u8], + opts: &'o ::flatbuffers::VerifierOptions, + buf: &'b [u8], ) -> Result, ::flatbuffers::InvalidFlatbuffer> { - ::flatbuffers::size_prefixed_root_with_opts::>(opts, buf) + ::flatbuffers::size_prefixed_root_with_opts::>(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`. -#[inline] pub unsafe fn root_as_monster_unchecked(buf: &[u8]) -> Monster<'_> { - unsafe { ::flatbuffers::root_unchecked::(buf) } + unsafe { ::flatbuffers::root_unchecked::(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`. -#[inline] pub unsafe fn size_prefixed_root_as_monster_unchecked(buf: &[u8]) -> Monster<'_> { - unsafe { ::flatbuffers::size_prefixed_root_unchecked::(buf) } + unsafe { ::flatbuffers::size_prefixed_root_unchecked::(buf) } } - pub const MONSTER_IDENTIFIER: &str = "MONS"; #[inline] pub fn monster_buffer_has_identifier(buf: &[u8]) -> bool { - ::flatbuffers::buffer_has_identifier(buf, MONSTER_IDENTIFIER, false) + ::flatbuffers::buffer_has_identifier(buf, MONSTER_IDENTIFIER, false) } #[inline] pub fn monster_size_prefixed_buffer_has_identifier(buf: &[u8]) -> bool { - ::flatbuffers::buffer_has_identifier(buf, MONSTER_IDENTIFIER, true) + ::flatbuffers::buffer_has_identifier(buf, MONSTER_IDENTIFIER, true) } pub const MONSTER_EXTENSION: &str = "mon"; @@ -2365,15 +2224,11 @@ pub const MONSTER_EXTENSION: &str = "mon"; #[inline] pub fn finish_monster_buffer<'a, 'b, A: ::flatbuffers::Allocator + 'a>( fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - root: ::flatbuffers::WIPOffset> -) { - fbb.finish(root, Some(MONSTER_IDENTIFIER)); + root: ::flatbuffers::WIPOffset>) { + fbb.finish(root, Some(MONSTER_IDENTIFIER)); } #[inline] -pub fn finish_size_prefixed_monster_buffer<'a, 'b, A: ::flatbuffers::Allocator + 'a>( - fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - root: ::flatbuffers::WIPOffset> -) { - fbb.finish_size_prefixed(root, Some(MONSTER_IDENTIFIER)); +pub fn finish_size_prefixed_monster_buffer<'a, 'b, A: ::flatbuffers::Allocator + 'a>(fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, root: ::flatbuffers::WIPOffset>) { + fbb.finish_size_prefixed(root, Some(MONSTER_IDENTIFIER)); } diff --git a/tests/monster_test_serialize/my_game/example/race_generated.rs b/tests/monster_test_serialize/my_game/example/race_generated.rs index b3e0e13d6..c91c401a3 100644 --- a/tests/monster_test_serialize/my_game/example/race_generated.rs +++ b/tests/monster_test_serialize/my_game/example/race_generated.rs @@ -4,71 +4,64 @@ extern crate alloc; extern crate serde; use self::serde::ser::{Serialize, Serializer, SerializeStruct}; use super::*; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] pub const ENUM_MIN_RACE: i8 = -1; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] pub const ENUM_MAX_RACE: i8 = 2; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] #[allow(non_camel_case_types)] pub const ENUM_VALUES_RACE: [Race; 4] = [ - Race::None, - Race::Human, - Race::Dwarf, - Race::Elf, + Race::None, + Race::Human, + Race::Dwarf, + Race::Elf, ]; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] #[repr(transparent)] pub struct Race(pub i8); - #[allow(non_upper_case_globals)] impl Race { - pub const None: Self = Self(-1); - pub const Human: Self = Self(0); - pub const Dwarf: Self = Self(1); - pub const Elf: Self = Self(2); + pub const None: Self = Self(-1); + pub const Human: Self = Self(0); + pub const Dwarf: Self = Self(1); + pub const Elf: Self = Self(2); - pub const ENUM_MIN: i8 = -1; - pub const ENUM_MAX: i8 = 2; - pub const ENUM_VALUES: &'static [Self] = &[ - Self::None, - Self::Human, - Self::Dwarf, - Self::Elf, - ]; - - /// Returns the variant's name or "" if unknown. - pub fn variant_name(self) -> Option<&'static str> { - match self { - Self::None => Some("None"), - Self::Human => Some("Human"), - Self::Dwarf => Some("Dwarf"), - Self::Elf => Some("Elf"), - _ => None, - } + pub const ENUM_MIN: i8 = -1; + pub const ENUM_MAX: i8 = 2; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::None, + Self::Human, + Self::Dwarf, + Self::Elf, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::None => Some("None"), + Self::Human => Some("Human"), + Self::Dwarf => Some("Dwarf"), + Self::Elf => Some("Elf"), + _ => None, } + } } - impl ::core::fmt::Debug for Race { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - if let Some(name) = self.variant_name() { - f.write_str(name) - } else { - f.write_fmt(format_args!("", self.0)) - } + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) } + } } - impl Serialize for Race { - fn serialize(&self, serializer: S) -> Result - where - S: Serializer, - { - serializer.serialize_unit_variant("Race", self.0 as u32, self.variant_name().unwrap()) - } + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_unit_variant("Race", self.0 as u32, self.variant_name().unwrap()) + } } impl<'de> serde::Deserialize<'de> for Race { @@ -91,18 +84,16 @@ impl<'de> serde::Deserialize<'de> for Race { } impl<'a> ::flatbuffers::Follow<'a> for Race { - type Inner = Self; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; - Self(b) - } + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; + Self(b) + } } impl ::flatbuffers::Push for Race { type Output = Race; - #[inline] unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { unsafe { ::flatbuffers::emplace_scalar::(dst, self.0) }; @@ -110,28 +101,26 @@ impl ::flatbuffers::Push for Race { } impl ::flatbuffers::EndianScalar for Race { - type Scalar = i8; - - #[inline] - fn to_little_endian(self) -> i8 { - self.0.to_le() - } - - #[inline] - #[allow(clippy::wrong_self_convention)] - fn from_little_endian(v: i8) -> Self { - let b = i8::from_le(v); - Self(b) - } + type Scalar = i8; + #[inline] + fn to_little_endian(self) -> i8 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: i8) -> Self { + let b = i8::from_le(v); + Self(b) + } } impl<'a> ::flatbuffers::Verifiable for Race { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - i8::run_verifier(v, pos) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + i8::run_verifier(v, pos) + } } impl ::flatbuffers::SimpleToVerifyInSlice for Race {} diff --git a/tests/monster_test_serialize/my_game/example/referrable_generated.rs b/tests/monster_test_serialize/my_game/example/referrable_generated.rs index d7224c45d..eed359a01 100644 --- a/tests/monster_test_serialize/my_game/example/referrable_generated.rs +++ b/tests/monster_test_serialize/my_game/example/referrable_generated.rs @@ -4,165 +4,153 @@ extern crate alloc; extern crate serde; use self::serde::ser::{Serialize, Serializer, SerializeStruct}; use super::*; - pub enum ReferrableOffset {} - #[derive(Copy, Clone, PartialEq)] + pub struct Referrable<'a> { - pub _tab: ::flatbuffers::Table<'a>, + pub _tab: ::flatbuffers::Table<'a>, } impl<'a> ::flatbuffers::Follow<'a> for Referrable<'a> { - type Inner = Referrable<'a>; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } - } + type Inner = Referrable<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } + } } impl<'a> Referrable<'a> { - pub const VT_ID: ::flatbuffers::VOffsetT = 4; + pub const VT_ID: ::flatbuffers::VOffsetT = 4; - pub const fn get_fully_qualified_name() -> &'static str { - "MyGame.Example.Referrable" - } + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Example.Referrable" + } - #[inline] - pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { - Referrable { _tab: table } - } + #[inline] + pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { + Referrable { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args ReferrableArgs + ) -> ::flatbuffers::WIPOffset> { + let mut builder = ReferrableBuilder::new(_fbb); + builder.add_id(args.id); + builder.finish() + } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args ReferrableArgs - ) -> ::flatbuffers::WIPOffset> { - let mut builder = ReferrableBuilder::new(_fbb); - builder.add_id(args.id); - builder.finish() + pub fn unpack(&self) -> ReferrableT { + let id = self.id(); + ReferrableT { + id, } + } - pub fn unpack(&self) -> ReferrableT { - let id = self.id(); - ReferrableT { - id, - } - } + #[inline] + pub fn id(&self) -> u64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Referrable::VT_ID, Some(0)).unwrap()} + } + #[inline] + pub fn key_compare_less_than(&self, o: &Referrable) -> bool { + self.id() < o.id() + } - #[inline] - pub fn id(&self) -> u64 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Referrable::VT_ID, Some(0)).unwrap()} - } - - #[inline] - pub fn key_compare_less_than(&self, o: &Referrable) -> bool { - self.id() < o.id() - } - - #[inline] - pub fn key_compare_with_value(&self, val: u64) -> ::core::cmp::Ordering { - let key = self.id(); - key.cmp(&val) - } + #[inline] + pub fn key_compare_with_value(&self, val: u64) -> ::core::cmp::Ordering { + let key = self.id(); + key.cmp(&val) + } } impl ::flatbuffers::Verifiable for Referrable<'_> { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.visit_table(pos)? - .visit_field::("id", Self::VT_ID, false)? - .finish(); - Ok(()) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.visit_table(pos)? + .visit_field::("id", Self::VT_ID, false)? + .finish(); + Ok(()) + } } - pub struct ReferrableArgs { pub id: u64, } - impl<'a> Default for ReferrableArgs { - #[inline] - fn default() -> Self { - ReferrableArgs { - id: 0, - } + #[inline] + fn default() -> Self { + ReferrableArgs { + id: 0, } + } } impl Serialize for Referrable<'_> { - fn serialize(&self, serializer: S) -> Result - where - S: Serializer, - { - let mut s = serializer.serialize_struct("Referrable", 1)?; - s.serialize_field("id", &self.id())?; - s.end() - } + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let mut s = serializer.serialize_struct("Referrable", 1)?; + s.serialize_field("id", &self.id())?; + s.end() + } } pub struct ReferrableBuilder<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> { - fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, + fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, + start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, } - impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> ReferrableBuilder<'a, 'b, A> { - #[inline] - pub fn add_id(&mut self, id: u64) { - self.fbb_.push_slot::(Referrable::VT_ID, id, 0); - } - - #[inline] - pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> ReferrableBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - ReferrableBuilder { - fbb_: _fbb, - start_: start, - } - } - - #[inline] - pub fn finish(self) -> ::flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - ::flatbuffers::WIPOffset::new(o.value()) + #[inline] + pub fn add_id(&mut self, id: u64) { + self.fbb_.push_slot::(Referrable::VT_ID, id, 0); + } + #[inline] + pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> ReferrableBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + ReferrableBuilder { + fbb_: _fbb, + start_: start, } + } + #[inline] + pub fn finish(self) -> ::flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + ::flatbuffers::WIPOffset::new(o.value()) + } } impl ::core::fmt::Debug for Referrable<'_> { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - let mut ds = f.debug_struct("Referrable"); - ds.field("id", &self.id()); - ds.finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + let mut ds = f.debug_struct("Referrable"); + ds.field("id", &self.id()); + ds.finish() + } } - #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub struct ReferrableT { - pub id: u64, + pub id: u64, } - impl Default for ReferrableT { - fn default() -> Self { - Self { - id: 0, - } + fn default() -> Self { + Self { + id: 0, } + } } - impl ReferrableT { - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( - &self, - _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> - ) -> ::flatbuffers::WIPOffset> { - let id = self.id; - Referrable::create(_fbb, &ReferrableArgs{ - id, - }) - } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> + ) -> ::flatbuffers::WIPOffset> { + let id = self.id; + Referrable::create(_fbb, &ReferrableArgs{ + id, + }) + } } diff --git a/tests/monster_test_serialize/my_game/example/stat_generated.rs b/tests/monster_test_serialize/my_game/example/stat_generated.rs index eb81b1cdf..af34edba8 100644 --- a/tests/monster_test_serialize/my_game/example/stat_generated.rs +++ b/tests/monster_test_serialize/my_game/example/stat_generated.rs @@ -4,225 +4,209 @@ extern crate alloc; extern crate serde; use self::serde::ser::{Serialize, Serializer, SerializeStruct}; use super::*; - pub enum StatOffset {} - #[derive(Copy, Clone, PartialEq)] + pub struct Stat<'a> { - pub _tab: ::flatbuffers::Table<'a>, + pub _tab: ::flatbuffers::Table<'a>, } impl<'a> ::flatbuffers::Follow<'a> for Stat<'a> { - type Inner = Stat<'a>; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } - } + type Inner = Stat<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } + } } impl<'a> Stat<'a> { - pub const VT_ID: ::flatbuffers::VOffsetT = 4; - pub const VT_VAL: ::flatbuffers::VOffsetT = 6; - pub const VT_COUNT: ::flatbuffers::VOffsetT = 8; + pub const VT_ID: ::flatbuffers::VOffsetT = 4; + pub const VT_VAL: ::flatbuffers::VOffsetT = 6; + pub const VT_COUNT: ::flatbuffers::VOffsetT = 8; - pub const fn get_fully_qualified_name() -> &'static str { - "MyGame.Example.Stat" - } + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Example.Stat" + } - #[inline] - pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { - Stat { _tab: table } - } + #[inline] + pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { + Stat { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args StatArgs<'args> + ) -> ::flatbuffers::WIPOffset> { + let mut builder = StatBuilder::new(_fbb); + builder.add_val(args.val); + if let Some(x) = args.id { builder.add_id(x); } + builder.add_count(args.count); + builder.finish() + } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args StatArgs<'args> - ) -> ::flatbuffers::WIPOffset> { - let mut builder = StatBuilder::new(_fbb); - builder.add_val(args.val); - if let Some(x) = args.id { builder.add_id(x); } - builder.add_count(args.count); - builder.finish() + pub fn unpack(&self) -> StatT { + let id = self.id().map(|x| { + alloc::string::ToString::to_string(x) + }); + let val = self.val(); + let count = self.count(); + StatT { + id, + val, + count, } + } - pub fn unpack(&self) -> StatT { - let id = self.id().map(|x| { - alloc::string::ToString::to_string(x) - }); - let val = self.val(); - let count = self.count(); - StatT { - id, - val, - count, - } - } + #[inline] + pub fn id(&self) -> Option<&'a str> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<&str>>(Stat::VT_ID, None)} + } + #[inline] + pub fn val(&self) -> i64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Stat::VT_VAL, Some(0)).unwrap()} + } + #[inline] + pub fn count(&self) -> u16 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Stat::VT_COUNT, Some(0)).unwrap()} + } + #[inline] + pub fn key_compare_less_than(&self, o: &Stat) -> bool { + self.count() < o.count() + } - #[inline] - pub fn id(&self) -> Option<&'a str> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<&str>>(Stat::VT_ID, None)} - } - - #[inline] - pub fn val(&self) -> i64 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Stat::VT_VAL, Some(0)).unwrap()} - } - - #[inline] - pub fn count(&self) -> u16 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Stat::VT_COUNT, Some(0)).unwrap()} - } - - #[inline] - pub fn key_compare_less_than(&self, o: &Stat) -> bool { - self.count() < o.count() - } - - #[inline] - pub fn key_compare_with_value(&self, val: u16) -> ::core::cmp::Ordering { - let key = self.count(); - key.cmp(&val) - } + #[inline] + pub fn key_compare_with_value(&self, val: u16) -> ::core::cmp::Ordering { + let key = self.count(); + key.cmp(&val) + } } impl ::flatbuffers::Verifiable for Stat<'_> { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.visit_table(pos)? - .visit_field::<::flatbuffers::ForwardsUOffset<&str>>("id", Self::VT_ID, false)? - .visit_field::("val", Self::VT_VAL, false)? - .visit_field::("count", Self::VT_COUNT, false)? - .finish(); - Ok(()) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.visit_table(pos)? + .visit_field::<::flatbuffers::ForwardsUOffset<&str>>("id", Self::VT_ID, false)? + .visit_field::("val", Self::VT_VAL, false)? + .visit_field::("count", Self::VT_COUNT, false)? + .finish(); + Ok(()) + } } - pub struct StatArgs<'a> { pub id: Option<::flatbuffers::WIPOffset<&'a str>>, pub val: i64, pub count: u16, } - impl<'a> Default for StatArgs<'a> { - #[inline] - fn default() -> Self { - StatArgs { - id: None, - val: 0, - count: 0, - } + #[inline] + fn default() -> Self { + StatArgs { + id: None, + val: 0, + count: 0, } + } } impl Serialize for Stat<'_> { - fn serialize(&self, serializer: S) -> Result - where - S: Serializer, - { - let mut s = serializer.serialize_struct("Stat", 3)?; - if let Some(f) = self.id() { - s.serialize_field("id", &f)?; - } else { - s.skip_field("id")?; - } - s.serialize_field("val", &self.val())?; - s.serialize_field("count", &self.count())?; - s.end() - } + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let mut s = serializer.serialize_struct("Stat", 3)?; + if let Some(f) = self.id() { + s.serialize_field("id", &f)?; + } else { + s.skip_field("id")?; + } + s.serialize_field("val", &self.val())?; + s.serialize_field("count", &self.count())?; + s.end() + } } pub struct StatBuilder<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> { - fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, + fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, + start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, } - impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> StatBuilder<'a, 'b, A> { - #[inline] - pub fn add_id(&mut self, id: ::flatbuffers::WIPOffset<&'b str>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Stat::VT_ID, id); - } - - #[inline] - pub fn add_val(&mut self, val: i64) { - self.fbb_.push_slot::(Stat::VT_VAL, val, 0); - } - - #[inline] - pub fn add_count(&mut self, count: u16) { - self.fbb_.push_slot::(Stat::VT_COUNT, count, 0); - } - - #[inline] - pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> StatBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - StatBuilder { - fbb_: _fbb, - start_: start, - } - } - - #[inline] - pub fn finish(self) -> ::flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - ::flatbuffers::WIPOffset::new(o.value()) + #[inline] + pub fn add_id(&mut self, id: ::flatbuffers::WIPOffset<&'b str>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(Stat::VT_ID, id); + } + #[inline] + pub fn add_val(&mut self, val: i64) { + self.fbb_.push_slot::(Stat::VT_VAL, val, 0); + } + #[inline] + pub fn add_count(&mut self, count: u16) { + self.fbb_.push_slot::(Stat::VT_COUNT, count, 0); + } + #[inline] + pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> StatBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + StatBuilder { + fbb_: _fbb, + start_: start, } + } + #[inline] + pub fn finish(self) -> ::flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + ::flatbuffers::WIPOffset::new(o.value()) + } } impl ::core::fmt::Debug for Stat<'_> { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - let mut ds = f.debug_struct("Stat"); - ds.field("id", &self.id()); - ds.field("val", &self.val()); - ds.field("count", &self.count()); - ds.finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + let mut ds = f.debug_struct("Stat"); + ds.field("id", &self.id()); + ds.field("val", &self.val()); + ds.field("count", &self.count()); + ds.finish() + } } - #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub struct StatT { - pub id: Option, - pub val: i64, - pub count: u16, + pub id: Option, + pub val: i64, + pub count: u16, } - impl Default for StatT { - fn default() -> Self { - Self { - id: None, - val: 0, - count: 0, - } + fn default() -> Self { + Self { + id: None, + val: 0, + count: 0, } + } } - impl StatT { - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( - &self, - _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> - ) -> ::flatbuffers::WIPOffset> { - let id = self.id.as_ref().map(|x|{ - _fbb.create_string(x) - }); - let val = self.val; - let count = self.count; - Stat::create(_fbb, &StatArgs{ - id, - val, - count, - }) - } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> + ) -> ::flatbuffers::WIPOffset> { + let id = self.id.as_ref().map(|x|{ + _fbb.create_string(x) + }); + let val = self.val; + let count = self.count; + Stat::create(_fbb, &StatArgs{ + id, + val, + count, + }) + } } diff --git a/tests/monster_test_serialize/my_game/example/struct_of_structs_generated.rs b/tests/monster_test_serialize/my_game/example/struct_of_structs_generated.rs index 17b8d7cf0..23236d77d 100644 --- a/tests/monster_test_serialize/my_game/example/struct_of_structs_generated.rs +++ b/tests/monster_test_serialize/my_game/example/struct_of_structs_generated.rs @@ -4,57 +4,47 @@ extern crate alloc; extern crate serde; use self::serde::ser::{Serialize, Serializer, SerializeStruct}; use super::*; - // struct StructOfStructs, aligned to 4 #[repr(transparent)] #[derive(Clone, Copy, PartialEq)] pub struct StructOfStructs(pub [u8; 20]); - -impl Default for StructOfStructs { - fn default() -> Self { - Self([0; 20]) - } +impl Default for StructOfStructs { + fn default() -> Self { + Self([0; 20]) + } } - impl ::core::fmt::Debug for StructOfStructs { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - f.debug_struct("StructOfStructs") - .field("a", &self.a()) - .field("b", &self.b()) - .field("c", &self.c()) - .finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + f.debug_struct("StructOfStructs") + .field("a", &self.a()) + .field("b", &self.b()) + .field("c", &self.c()) + .finish() + } } impl ::flatbuffers::SimpleToVerifyInSlice for StructOfStructs {} - impl<'a> ::flatbuffers::Follow<'a> for StructOfStructs { - type Inner = &'a StructOfStructs; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - unsafe { <&'a StructOfStructs>::follow(buf, loc) } - } + type Inner = &'a StructOfStructs; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { <&'a StructOfStructs>::follow(buf, loc) } + } } - impl<'a> ::flatbuffers::Follow<'a> for &'a StructOfStructs { - type Inner = &'a StructOfStructs; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - unsafe { ::flatbuffers::follow_cast_ref::(buf, loc) } - } + type Inner = &'a StructOfStructs; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { ::flatbuffers::follow_cast_ref::(buf, loc) } + } } - impl<'b> ::flatbuffers::Push for StructOfStructs { type Output = StructOfStructs; - #[inline] unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { let src = unsafe { ::core::slice::from_raw_parts(self as *const StructOfStructs as *const u8, ::size()) }; dst.copy_from_slice(src); } - #[inline] fn alignment() -> ::flatbuffers::PushAlignment { ::flatbuffers::PushAlignment::new(4) @@ -62,112 +52,103 @@ impl<'b> ::flatbuffers::Push for StructOfStructs { } impl<'a> ::flatbuffers::Verifiable for StructOfStructs { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.in_buffer::(pos) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.in_buffer::(pos) + } } impl Serialize for StructOfStructs { - fn serialize(&self, serializer: S) -> Result - where - S: Serializer, - { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { let mut s = serializer.serialize_struct("StructOfStructs", 3)?; - s.serialize_field("a", &self.a())?; - s.serialize_field("b", &self.b())?; - s.serialize_field("c", &self.c())?; - s.end() - } + s.serialize_field("a", &self.a())?; + s.serialize_field("b", &self.b())?; + s.serialize_field("c", &self.c())?; + s.end() + } } impl<'a> StructOfStructs { - #[allow(clippy::too_many_arguments)] - pub fn new( - a: &Ability, - b: &Test, - c: &Ability, - ) -> Self { - let mut s = Self([0; 20]); - s.set_a(a); - s.set_b(b); - s.set_c(c); - s - } + #[allow(clippy::too_many_arguments)] + pub fn new( + a: &Ability, + b: &Test, + c: &Ability, + ) -> Self { + let mut s = Self([0; 20]); + s.set_a(a); + s.set_b(b); + s.set_c(c); + s + } - pub const fn get_fully_qualified_name() -> &'static str { - "MyGame.Example.StructOfStructs" - } + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Example.StructOfStructs" + } - pub fn a(&self) -> &Ability { - // Safety: - // Created from a valid Table for this object - // Which contains a valid struct in this slot - unsafe { &*(self.0[0..].as_ptr() as *const Ability) } - } + pub fn a(&self) -> &Ability { + // Safety: + // Created from a valid Table for this object + // Which contains a valid struct in this slot + unsafe { &*(self.0[0..].as_ptr() as *const Ability) } + } - #[allow(clippy::identity_op)] - pub fn set_a(&mut self, x: &Ability) { - self.0[0..0 + 8].copy_from_slice(&x.0) - } + #[allow(clippy::identity_op)] + pub fn set_a(&mut self, x: &Ability) { + self.0[0..0 + 8].copy_from_slice(&x.0) + } - pub fn b(&self) -> &Test { - // Safety: - // Created from a valid Table for this object - // Which contains a valid struct in this slot - unsafe { &*(self.0[8..].as_ptr() as *const Test) } - } + pub fn b(&self) -> &Test { + // Safety: + // Created from a valid Table for this object + // Which contains a valid struct in this slot + unsafe { &*(self.0[8..].as_ptr() as *const Test) } + } - #[allow(clippy::identity_op)] - pub fn set_b(&mut self, x: &Test) { - self.0[8..8 + 4].copy_from_slice(&x.0) - } + #[allow(clippy::identity_op)] + pub fn set_b(&mut self, x: &Test) { + self.0[8..8 + 4].copy_from_slice(&x.0) + } - pub fn c(&self) -> &Ability { - // Safety: - // Created from a valid Table for this object - // Which contains a valid struct in this slot - unsafe { &*(self.0[12..].as_ptr() as *const Ability) } - } + pub fn c(&self) -> &Ability { + // Safety: + // Created from a valid Table for this object + // Which contains a valid struct in this slot + unsafe { &*(self.0[12..].as_ptr() as *const Ability) } + } - #[allow(clippy::identity_op)] - pub fn set_c(&mut self, x: &Ability) { - self.0[12..12 + 8].copy_from_slice(&x.0) - } + #[allow(clippy::identity_op)] + pub fn set_c(&mut self, x: &Ability) { + self.0[12..12 + 8].copy_from_slice(&x.0) + } - pub fn unpack(&self) -> StructOfStructsT { - StructOfStructsT { - a: self.a().unpack(), - b: self.b().unpack(), - c: self.c().unpack(), - } + pub fn unpack(&self) -> StructOfStructsT { + StructOfStructsT { + a: self.a().unpack(), + b: self.b().unpack(), + c: self.c().unpack(), } + } } -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Default)] pub struct StructOfStructsT { - pub a: AbilityT, - pub b: TestT, - pub c: AbilityT, + pub a: AbilityT, + pub b: TestT, + pub c: AbilityT, } -impl Default for StructOfStructsT { - fn default() -> Self { - Self { - a: Default::default(), - b: Default::default(), - c: Default::default(), - } - } +impl StructOfStructsT { + pub fn pack(&self) -> StructOfStructs { + StructOfStructs::new( + &self.a.pack(), + &self.b.pack(), + &self.c.pack(), + ) + } } -impl StructOfStructsT { - pub fn pack(&self) -> StructOfStructs { - StructOfStructs::new( - &self.a.pack(), - &self.b.pack(), - &self.c.pack(), - ) - } -} diff --git a/tests/monster_test_serialize/my_game/example/struct_of_structs_of_structs_generated.rs b/tests/monster_test_serialize/my_game/example/struct_of_structs_of_structs_generated.rs index 743baba23..0751e5b33 100644 --- a/tests/monster_test_serialize/my_game/example/struct_of_structs_of_structs_generated.rs +++ b/tests/monster_test_serialize/my_game/example/struct_of_structs_of_structs_generated.rs @@ -4,55 +4,45 @@ extern crate alloc; extern crate serde; use self::serde::ser::{Serialize, Serializer, SerializeStruct}; use super::*; - // struct StructOfStructsOfStructs, aligned to 4 #[repr(transparent)] #[derive(Clone, Copy, PartialEq)] pub struct StructOfStructsOfStructs(pub [u8; 20]); - -impl Default for StructOfStructsOfStructs { - fn default() -> Self { - Self([0; 20]) - } +impl Default for StructOfStructsOfStructs { + fn default() -> Self { + Self([0; 20]) + } } - impl ::core::fmt::Debug for StructOfStructsOfStructs { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - f.debug_struct("StructOfStructsOfStructs") - .field("a", &self.a()) - .finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + f.debug_struct("StructOfStructsOfStructs") + .field("a", &self.a()) + .finish() + } } impl ::flatbuffers::SimpleToVerifyInSlice for StructOfStructsOfStructs {} - impl<'a> ::flatbuffers::Follow<'a> for StructOfStructsOfStructs { - type Inner = &'a StructOfStructsOfStructs; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - unsafe { <&'a StructOfStructsOfStructs>::follow(buf, loc) } - } + type Inner = &'a StructOfStructsOfStructs; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { <&'a StructOfStructsOfStructs>::follow(buf, loc) } + } } - impl<'a> ::flatbuffers::Follow<'a> for &'a StructOfStructsOfStructs { - type Inner = &'a StructOfStructsOfStructs; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - unsafe { ::flatbuffers::follow_cast_ref::(buf, loc) } - } + type Inner = &'a StructOfStructsOfStructs; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { ::flatbuffers::follow_cast_ref::(buf, loc) } + } } - impl<'b> ::flatbuffers::Push for StructOfStructsOfStructs { type Output = StructOfStructsOfStructs; - #[inline] unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { let src = unsafe { ::core::slice::from_raw_parts(self as *const StructOfStructsOfStructs as *const u8, ::size()) }; dst.copy_from_slice(src); } - #[inline] fn alignment() -> ::flatbuffers::PushAlignment { ::flatbuffers::PushAlignment::new(4) @@ -60,74 +50,67 @@ impl<'b> ::flatbuffers::Push for StructOfStructsOfStructs { } impl<'a> ::flatbuffers::Verifiable for StructOfStructsOfStructs { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.in_buffer::(pos) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.in_buffer::(pos) + } } impl Serialize for StructOfStructsOfStructs { - fn serialize(&self, serializer: S) -> Result - where - S: Serializer, - { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { let mut s = serializer.serialize_struct("StructOfStructsOfStructs", 1)?; - s.serialize_field("a", &self.a())?; - s.end() - } + s.serialize_field("a", &self.a())?; + s.end() + } } impl<'a> StructOfStructsOfStructs { - #[allow(clippy::too_many_arguments)] - pub fn new( - a: &StructOfStructs, - ) -> Self { - let mut s = Self([0; 20]); - s.set_a(a); - s - } + #[allow(clippy::too_many_arguments)] + pub fn new( + a: &StructOfStructs, + ) -> Self { + let mut s = Self([0; 20]); + s.set_a(a); + s + } - pub const fn get_fully_qualified_name() -> &'static str { - "MyGame.Example.StructOfStructsOfStructs" - } + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Example.StructOfStructsOfStructs" + } - pub fn a(&self) -> &StructOfStructs { - // Safety: - // Created from a valid Table for this object - // Which contains a valid struct in this slot - unsafe { &*(self.0[0..].as_ptr() as *const StructOfStructs) } - } + pub fn a(&self) -> &StructOfStructs { + // Safety: + // Created from a valid Table for this object + // Which contains a valid struct in this slot + unsafe { &*(self.0[0..].as_ptr() as *const StructOfStructs) } + } - #[allow(clippy::identity_op)] - pub fn set_a(&mut self, x: &StructOfStructs) { - self.0[0..0 + 20].copy_from_slice(&x.0) - } + #[allow(clippy::identity_op)] + pub fn set_a(&mut self, x: &StructOfStructs) { + self.0[0..0 + 20].copy_from_slice(&x.0) + } - pub fn unpack(&self) -> StructOfStructsOfStructsT { - StructOfStructsOfStructsT { - a: self.a().unpack(), - } + pub fn unpack(&self) -> StructOfStructsOfStructsT { + StructOfStructsOfStructsT { + a: self.a().unpack(), } + } } -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Default)] pub struct StructOfStructsOfStructsT { - pub a: StructOfStructsT, + pub a: StructOfStructsT, } -impl Default for StructOfStructsOfStructsT { - fn default() -> Self { - Self { - a: Default::default(), - } - } +impl StructOfStructsOfStructsT { + pub fn pack(&self) -> StructOfStructsOfStructs { + StructOfStructsOfStructs::new( + &self.a.pack(), + ) + } } -impl StructOfStructsOfStructsT { - pub fn pack(&self) -> StructOfStructsOfStructs { - StructOfStructsOfStructs::new( - &self.a.pack(), - ) - } -} diff --git a/tests/monster_test_serialize/my_game/example/test_generated.rs b/tests/monster_test_serialize/my_game/example/test_generated.rs index ed1bffa03..b8c2e041f 100644 --- a/tests/monster_test_serialize/my_game/example/test_generated.rs +++ b/tests/monster_test_serialize/my_game/example/test_generated.rs @@ -4,56 +4,46 @@ extern crate alloc; extern crate serde; use self::serde::ser::{Serialize, Serializer, SerializeStruct}; use super::*; - // struct Test, aligned to 2 #[repr(transparent)] #[derive(Clone, Copy, PartialEq)] pub struct Test(pub [u8; 4]); - -impl Default for Test { - fn default() -> Self { - Self([0; 4]) - } +impl Default for Test { + fn default() -> Self { + Self([0; 4]) + } } - impl ::core::fmt::Debug for Test { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - f.debug_struct("Test") - .field("a", &self.a()) - .field("b", &self.b()) - .finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + f.debug_struct("Test") + .field("a", &self.a()) + .field("b", &self.b()) + .finish() + } } impl ::flatbuffers::SimpleToVerifyInSlice for Test {} - impl<'a> ::flatbuffers::Follow<'a> for Test { - type Inner = &'a Test; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - unsafe { <&'a Test>::follow(buf, loc) } - } + type Inner = &'a Test; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { <&'a Test>::follow(buf, loc) } + } } - impl<'a> ::flatbuffers::Follow<'a> for &'a Test { - type Inner = &'a Test; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - unsafe { ::flatbuffers::follow_cast_ref::(buf, loc) } - } + type Inner = &'a Test; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { ::flatbuffers::follow_cast_ref::(buf, loc) } + } } - impl<'b> ::flatbuffers::Push for Test { type Output = Test; - #[inline] unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { let src = unsafe { ::core::slice::from_raw_parts(self as *const Test as *const u8, ::size()) }; dst.copy_from_slice(src); } - #[inline] fn alignment() -> ::flatbuffers::PushAlignment { ::flatbuffers::PushAlignment::new(2) @@ -61,127 +51,119 @@ impl<'b> ::flatbuffers::Push for Test { } impl<'a> ::flatbuffers::Verifiable for Test { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.in_buffer::(pos) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.in_buffer::(pos) + } } impl Serialize for Test { - fn serialize(&self, serializer: S) -> Result - where - S: Serializer, - { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { let mut s = serializer.serialize_struct("Test", 2)?; - s.serialize_field("a", &self.a())?; - s.serialize_field("b", &self.b())?; - s.end() - } + s.serialize_field("a", &self.a())?; + s.serialize_field("b", &self.b())?; + s.end() + } } impl<'a> Test { - #[allow(clippy::too_many_arguments)] - pub fn new( - a: i16, - b: i8, - ) -> Self { - let mut s = Self([0; 4]); - s.set_a(a); - s.set_b(b); - s - } + #[allow(clippy::too_many_arguments)] + pub fn new( + a: i16, + b: i8, + ) -> Self { + let mut s = Self([0; 4]); + s.set_a(a); + s.set_b(b); + s + } - pub const fn get_fully_qualified_name() -> &'static str { - "MyGame.Example.Test" - } + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Example.Test" + } - pub fn a(&self) -> i16 { - let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - ::flatbuffers::EndianScalar::from_little_endian(unsafe { - ::core::ptr::copy_nonoverlapping( - self.0[0..].as_ptr(), - mem.as_mut_ptr() as *mut u8, - ::core::mem::size_of::<::Scalar>(), - ); - mem.assume_init() - }) - } + pub fn a(&self) -> i16 { + let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + ::flatbuffers::EndianScalar::from_little_endian(unsafe { + ::core::ptr::copy_nonoverlapping( + self.0[0..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + ::core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } - pub fn set_a(&mut self, x: i16) { - let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - unsafe { - ::core::ptr::copy_nonoverlapping( - &x_le as *const _ as *const u8, - self.0[0..].as_mut_ptr(), - ::core::mem::size_of::<::Scalar>(), - ); - } + pub fn set_a(&mut self, x: i16) { + let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + ::core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[0..].as_mut_ptr(), + ::core::mem::size_of::<::Scalar>(), + ); } + } - pub fn b(&self) -> i8 { - let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - ::flatbuffers::EndianScalar::from_little_endian(unsafe { - ::core::ptr::copy_nonoverlapping( - self.0[2..].as_ptr(), - mem.as_mut_ptr() as *mut u8, - ::core::mem::size_of::<::Scalar>(), - ); - mem.assume_init() - }) - } + pub fn b(&self) -> i8 { + let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + ::flatbuffers::EndianScalar::from_little_endian(unsafe { + ::core::ptr::copy_nonoverlapping( + self.0[2..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + ::core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } - pub fn set_b(&mut self, x: i8) { - let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - unsafe { - ::core::ptr::copy_nonoverlapping( - &x_le as *const _ as *const u8, - self.0[2..].as_mut_ptr(), - ::core::mem::size_of::<::Scalar>(), - ); - } + pub fn set_b(&mut self, x: i8) { + let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + ::core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[2..].as_mut_ptr(), + ::core::mem::size_of::<::Scalar>(), + ); } + } - pub fn unpack(&self) -> TestT { - TestT { - a: self.a(), - b: self.b(), - } + pub fn unpack(&self) -> TestT { + TestT { + a: self.a(), + b: self.b(), } + } } -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Default)] pub struct TestT { - pub a: i16, - pub b: i8, + pub a: i16, + pub b: i8, } -impl Default for TestT { - fn default() -> Self { - Self { - a: 0, - b: 0, - } - } +impl TestT { + pub fn pack(&self) -> Test { + Test::new( + self.a, + self.b, + ) + } } -impl TestT { - pub fn pack(&self) -> Test { - Test::new( - self.a, - self.b, - ) - } -} diff --git a/tests/monster_test_serialize/my_game/example/test_simple_table_with_enum_generated.rs b/tests/monster_test_serialize/my_game/example/test_simple_table_with_enum_generated.rs index 6cd14b1e7..df0a46892 100644 --- a/tests/monster_test_serialize/my_game/example/test_simple_table_with_enum_generated.rs +++ b/tests/monster_test_serialize/my_game/example/test_simple_table_with_enum_generated.rs @@ -4,154 +4,143 @@ extern crate alloc; extern crate serde; use self::serde::ser::{Serialize, Serializer, SerializeStruct}; use super::*; - pub enum TestSimpleTableWithEnumOffset {} - #[derive(Copy, Clone, PartialEq)] + pub struct TestSimpleTableWithEnum<'a> { - pub _tab: ::flatbuffers::Table<'a>, + pub _tab: ::flatbuffers::Table<'a>, } impl<'a> ::flatbuffers::Follow<'a> for TestSimpleTableWithEnum<'a> { - type Inner = TestSimpleTableWithEnum<'a>; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } - } + type Inner = TestSimpleTableWithEnum<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } + } } impl<'a> TestSimpleTableWithEnum<'a> { - pub const VT_COLOR: ::flatbuffers::VOffsetT = 4; + pub const VT_COLOR: ::flatbuffers::VOffsetT = 4; - pub const fn get_fully_qualified_name() -> &'static str { - "MyGame.Example.TestSimpleTableWithEnum" - } + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Example.TestSimpleTableWithEnum" + } - #[inline] - pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { - TestSimpleTableWithEnum { _tab: table } - } + #[inline] + pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { + TestSimpleTableWithEnum { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args TestSimpleTableWithEnumArgs + ) -> ::flatbuffers::WIPOffset> { + let mut builder = TestSimpleTableWithEnumBuilder::new(_fbb); + builder.add_color(args.color); + builder.finish() + } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args TestSimpleTableWithEnumArgs - ) -> ::flatbuffers::WIPOffset> { - let mut builder = TestSimpleTableWithEnumBuilder::new(_fbb); - builder.add_color(args.color); - builder.finish() + pub fn unpack(&self) -> TestSimpleTableWithEnumT { + let color = self.color(); + TestSimpleTableWithEnumT { + color, } + } - pub fn unpack(&self) -> TestSimpleTableWithEnumT { - let color = self.color(); - TestSimpleTableWithEnumT { - color, - } - } - - #[inline] - pub fn color(&self) -> Color { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(TestSimpleTableWithEnum::VT_COLOR, Some(Color::Green)).unwrap()} - } + #[inline] + pub fn color(&self) -> Color { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TestSimpleTableWithEnum::VT_COLOR, Some(Color::Green)).unwrap()} + } } impl ::flatbuffers::Verifiable for TestSimpleTableWithEnum<'_> { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.visit_table(pos)? - .visit_field::("color", Self::VT_COLOR, false)? - .finish(); - Ok(()) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.visit_table(pos)? + .visit_field::("color", Self::VT_COLOR, false)? + .finish(); + Ok(()) + } } - pub struct TestSimpleTableWithEnumArgs { pub color: Color, } - impl<'a> Default for TestSimpleTableWithEnumArgs { - #[inline] - fn default() -> Self { - TestSimpleTableWithEnumArgs { - color: Color::Green, - } + #[inline] + fn default() -> Self { + TestSimpleTableWithEnumArgs { + color: Color::Green, } + } } impl Serialize for TestSimpleTableWithEnum<'_> { - fn serialize(&self, serializer: S) -> Result - where - S: Serializer, - { - let mut s = serializer.serialize_struct("TestSimpleTableWithEnum", 1)?; - s.serialize_field("color", &self.color())?; - s.end() - } + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let mut s = serializer.serialize_struct("TestSimpleTableWithEnum", 1)?; + s.serialize_field("color", &self.color())?; + s.end() + } } pub struct TestSimpleTableWithEnumBuilder<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> { - fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, + fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, + start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, } - impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> TestSimpleTableWithEnumBuilder<'a, 'b, A> { - #[inline] - pub fn add_color(&mut self, color: Color) { - self.fbb_.push_slot::(TestSimpleTableWithEnum::VT_COLOR, color, Color::Green); - } - - #[inline] - pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> TestSimpleTableWithEnumBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - TestSimpleTableWithEnumBuilder { - fbb_: _fbb, - start_: start, - } - } - - #[inline] - pub fn finish(self) -> ::flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - ::flatbuffers::WIPOffset::new(o.value()) + #[inline] + pub fn add_color(&mut self, color: Color) { + self.fbb_.push_slot::(TestSimpleTableWithEnum::VT_COLOR, color, Color::Green); + } + #[inline] + pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> TestSimpleTableWithEnumBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + TestSimpleTableWithEnumBuilder { + fbb_: _fbb, + start_: start, } + } + #[inline] + pub fn finish(self) -> ::flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + ::flatbuffers::WIPOffset::new(o.value()) + } } impl ::core::fmt::Debug for TestSimpleTableWithEnum<'_> { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - let mut ds = f.debug_struct("TestSimpleTableWithEnum"); - ds.field("color", &self.color()); - ds.finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + let mut ds = f.debug_struct("TestSimpleTableWithEnum"); + ds.field("color", &self.color()); + ds.finish() + } } - #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub struct TestSimpleTableWithEnumT { - pub color: Color, + pub color: Color, } - impl Default for TestSimpleTableWithEnumT { - fn default() -> Self { - Self { - color: Color::Green, - } + fn default() -> Self { + Self { + color: Color::Green, } + } } - impl TestSimpleTableWithEnumT { - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( - &self, - _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> - ) -> ::flatbuffers::WIPOffset> { - let color = self.color; - TestSimpleTableWithEnum::create(_fbb, &TestSimpleTableWithEnumArgs{ - color, - }) - } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> + ) -> ::flatbuffers::WIPOffset> { + let color = self.color; + TestSimpleTableWithEnum::create(_fbb, &TestSimpleTableWithEnumArgs{ + color, + }) + } } diff --git a/tests/monster_test_serialize/my_game/example/type_aliases_generated.rs b/tests/monster_test_serialize/my_game/example/type_aliases_generated.rs index 698b5f729..7ec1728b7 100644 --- a/tests/monster_test_serialize/my_game/example/type_aliases_generated.rs +++ b/tests/monster_test_serialize/my_game/example/type_aliases_generated.rs @@ -4,220 +4,205 @@ extern crate alloc; extern crate serde; use self::serde::ser::{Serialize, Serializer, SerializeStruct}; use super::*; - pub enum TypeAliasesOffset {} - #[derive(Copy, Clone, PartialEq)] + pub struct TypeAliases<'a> { - pub _tab: ::flatbuffers::Table<'a>, + pub _tab: ::flatbuffers::Table<'a>, } impl<'a> ::flatbuffers::Follow<'a> for TypeAliases<'a> { - type Inner = TypeAliases<'a>; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } - } + type Inner = TypeAliases<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } + } } impl<'a> TypeAliases<'a> { - pub const VT_I8_: ::flatbuffers::VOffsetT = 4; - pub const VT_U8_: ::flatbuffers::VOffsetT = 6; - pub const VT_I16_: ::flatbuffers::VOffsetT = 8; - pub const VT_U16_: ::flatbuffers::VOffsetT = 10; - pub const VT_I32_: ::flatbuffers::VOffsetT = 12; - pub const VT_U32_: ::flatbuffers::VOffsetT = 14; - pub const VT_I64_: ::flatbuffers::VOffsetT = 16; - pub const VT_U64_: ::flatbuffers::VOffsetT = 18; - pub const VT_F32_: ::flatbuffers::VOffsetT = 20; - pub const VT_F64_: ::flatbuffers::VOffsetT = 22; - pub const VT_V8: ::flatbuffers::VOffsetT = 24; - pub const VT_VF64: ::flatbuffers::VOffsetT = 26; + pub const VT_I8_: ::flatbuffers::VOffsetT = 4; + pub const VT_U8_: ::flatbuffers::VOffsetT = 6; + pub const VT_I16_: ::flatbuffers::VOffsetT = 8; + pub const VT_U16_: ::flatbuffers::VOffsetT = 10; + pub const VT_I32_: ::flatbuffers::VOffsetT = 12; + pub const VT_U32_: ::flatbuffers::VOffsetT = 14; + pub const VT_I64_: ::flatbuffers::VOffsetT = 16; + pub const VT_U64_: ::flatbuffers::VOffsetT = 18; + pub const VT_F32_: ::flatbuffers::VOffsetT = 20; + pub const VT_F64_: ::flatbuffers::VOffsetT = 22; + pub const VT_V8: ::flatbuffers::VOffsetT = 24; + pub const VT_VF64: ::flatbuffers::VOffsetT = 26; - pub const fn get_fully_qualified_name() -> &'static str { - "MyGame.Example.TypeAliases" - } + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Example.TypeAliases" + } - #[inline] - pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { - TypeAliases { _tab: table } - } + #[inline] + pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { + TypeAliases { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args TypeAliasesArgs<'args> + ) -> ::flatbuffers::WIPOffset> { + let mut builder = TypeAliasesBuilder::new(_fbb); + builder.add_f64_(args.f64_); + builder.add_u64_(args.u64_); + builder.add_i64_(args.i64_); + if let Some(x) = args.vf64 { builder.add_vf64(x); } + if let Some(x) = args.v8 { builder.add_v8(x); } + builder.add_f32_(args.f32_); + builder.add_u32_(args.u32_); + builder.add_i32_(args.i32_); + builder.add_u16_(args.u16_); + builder.add_i16_(args.i16_); + builder.add_u8_(args.u8_); + builder.add_i8_(args.i8_); + builder.finish() + } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args TypeAliasesArgs<'args> - ) -> ::flatbuffers::WIPOffset> { - let mut builder = TypeAliasesBuilder::new(_fbb); - builder.add_f64_(args.f64_); - builder.add_u64_(args.u64_); - builder.add_i64_(args.i64_); - if let Some(x) = args.vf64 { builder.add_vf64(x); } - if let Some(x) = args.v8 { builder.add_v8(x); } - builder.add_f32_(args.f32_); - builder.add_u32_(args.u32_); - builder.add_i32_(args.i32_); - builder.add_u16_(args.u16_); - builder.add_i16_(args.i16_); - builder.add_u8_(args.u8_); - builder.add_i8_(args.i8_); - builder.finish() + pub fn unpack(&self) -> TypeAliasesT { + let i8_ = self.i8_(); + let u8_ = self.u8_(); + let i16_ = self.i16_(); + let u16_ = self.u16_(); + let i32_ = self.i32_(); + let u32_ = self.u32_(); + let i64_ = self.i64_(); + let u64_ = self.u64_(); + let f32_ = self.f32_(); + let f64_ = self.f64_(); + let v8 = self.v8().map(|x| { + x.into_iter().collect() + }); + let vf64 = self.vf64().map(|x| { + x.into_iter().collect() + }); + TypeAliasesT { + i8_, + u8_, + i16_, + u16_, + i32_, + u32_, + i64_, + u64_, + f32_, + f64_, + v8, + vf64, } + } - pub fn unpack(&self) -> TypeAliasesT { - let i8_ = self.i8_(); - let u8_ = self.u8_(); - let i16_ = self.i16_(); - let u16_ = self.u16_(); - let i32_ = self.i32_(); - let u32_ = self.u32_(); - let i64_ = self.i64_(); - let u64_ = self.u64_(); - let f32_ = self.f32_(); - let f64_ = self.f64_(); - let v8 = self.v8().map(|x| { - x.into_iter().collect() - }); - let vf64 = self.vf64().map(|x| { - x.into_iter().collect() - }); - TypeAliasesT { - i8_, - u8_, - i16_, - u16_, - i32_, - u32_, - i64_, - u64_, - f32_, - f64_, - v8, - vf64, - } - } - - #[inline] - pub fn i8_(&self) -> i8 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(TypeAliases::VT_I8_, Some(0)).unwrap()} - } - - #[inline] - pub fn u8_(&self) -> u8 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(TypeAliases::VT_U8_, Some(0)).unwrap()} - } - - #[inline] - pub fn i16_(&self) -> i16 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(TypeAliases::VT_I16_, Some(0)).unwrap()} - } - - #[inline] - pub fn u16_(&self) -> u16 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(TypeAliases::VT_U16_, Some(0)).unwrap()} - } - - #[inline] - pub fn i32_(&self) -> i32 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(TypeAliases::VT_I32_, Some(0)).unwrap()} - } - - #[inline] - pub fn u32_(&self) -> u32 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(TypeAliases::VT_U32_, Some(0)).unwrap()} - } - - #[inline] - pub fn i64_(&self) -> i64 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(TypeAliases::VT_I64_, Some(0)).unwrap()} - } - - #[inline] - pub fn u64_(&self) -> u64 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(TypeAliases::VT_U64_, Some(0)).unwrap()} - } - - #[inline] - pub fn f32_(&self) -> f32 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(TypeAliases::VT_F32_, Some(0.0)).unwrap()} - } - - #[inline] - pub fn f64_(&self) -> f64 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(TypeAliases::VT_F64_, Some(0.0)).unwrap()} - } - - #[inline] - pub fn v8(&self) -> Option<::flatbuffers::Vector<'a, i8>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, i8>>>(TypeAliases::VT_V8, None)} - } - - #[inline] - pub fn vf64(&self) -> Option<::flatbuffers::Vector<'a, f64>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, f64>>>(TypeAliases::VT_VF64, None)} - } + #[inline] + pub fn i8_(&self) -> i8 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TypeAliases::VT_I8_, Some(0)).unwrap()} + } + #[inline] + pub fn u8_(&self) -> u8 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TypeAliases::VT_U8_, Some(0)).unwrap()} + } + #[inline] + pub fn i16_(&self) -> i16 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TypeAliases::VT_I16_, Some(0)).unwrap()} + } + #[inline] + pub fn u16_(&self) -> u16 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TypeAliases::VT_U16_, Some(0)).unwrap()} + } + #[inline] + pub fn i32_(&self) -> i32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TypeAliases::VT_I32_, Some(0)).unwrap()} + } + #[inline] + pub fn u32_(&self) -> u32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TypeAliases::VT_U32_, Some(0)).unwrap()} + } + #[inline] + pub fn i64_(&self) -> i64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TypeAliases::VT_I64_, Some(0)).unwrap()} + } + #[inline] + pub fn u64_(&self) -> u64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TypeAliases::VT_U64_, Some(0)).unwrap()} + } + #[inline] + pub fn f32_(&self) -> f32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TypeAliases::VT_F32_, Some(0.0)).unwrap()} + } + #[inline] + pub fn f64_(&self) -> f64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TypeAliases::VT_F64_, Some(0.0)).unwrap()} + } + #[inline] + pub fn v8(&self) -> Option<::flatbuffers::Vector<'a, i8>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, i8>>>(TypeAliases::VT_V8, None)} + } + #[inline] + pub fn vf64(&self) -> Option<::flatbuffers::Vector<'a, f64>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, f64>>>(TypeAliases::VT_VF64, None)} + } } impl ::flatbuffers::Verifiable for TypeAliases<'_> { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.visit_table(pos)? - .visit_field::("i8_", Self::VT_I8_, false)? - .visit_field::("u8_", Self::VT_U8_, false)? - .visit_field::("i16_", Self::VT_I16_, false)? - .visit_field::("u16_", Self::VT_U16_, false)? - .visit_field::("i32_", Self::VT_I32_, false)? - .visit_field::("u32_", Self::VT_U32_, false)? - .visit_field::("i64_", Self::VT_I64_, false)? - .visit_field::("u64_", Self::VT_U64_, false)? - .visit_field::("f32_", Self::VT_F32_, false)? - .visit_field::("f64_", Self::VT_F64_, false)? - .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, i8>>>("v8", Self::VT_V8, false)? - .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, f64>>>("vf64", Self::VT_VF64, false)? - .finish(); - Ok(()) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.visit_table(pos)? + .visit_field::("i8_", Self::VT_I8_, false)? + .visit_field::("u8_", Self::VT_U8_, false)? + .visit_field::("i16_", Self::VT_I16_, false)? + .visit_field::("u16_", Self::VT_U16_, false)? + .visit_field::("i32_", Self::VT_I32_, false)? + .visit_field::("u32_", Self::VT_U32_, false)? + .visit_field::("i64_", Self::VT_I64_, false)? + .visit_field::("u64_", Self::VT_U64_, false)? + .visit_field::("f32_", Self::VT_F32_, false)? + .visit_field::("f64_", Self::VT_F64_, false)? + .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, i8>>>("v8", Self::VT_V8, false)? + .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, f64>>>("vf64", Self::VT_VF64, false)? + .finish(); + Ok(()) + } } - pub struct TypeAliasesArgs<'a> { pub i8_: i8, pub u8_: u8, @@ -232,228 +217,210 @@ pub struct TypeAliasesArgs<'a> { pub v8: Option<::flatbuffers::WIPOffset<::flatbuffers::Vector<'a, i8>>>, pub vf64: Option<::flatbuffers::WIPOffset<::flatbuffers::Vector<'a, f64>>>, } - impl<'a> Default for TypeAliasesArgs<'a> { - #[inline] - fn default() -> Self { - TypeAliasesArgs { - i8_: 0, - u8_: 0, - i16_: 0, - u16_: 0, - i32_: 0, - u32_: 0, - i64_: 0, - u64_: 0, - f32_: 0.0, - f64_: 0.0, - v8: None, - vf64: None, - } + #[inline] + fn default() -> Self { + TypeAliasesArgs { + i8_: 0, + u8_: 0, + i16_: 0, + u16_: 0, + i32_: 0, + u32_: 0, + i64_: 0, + u64_: 0, + f32_: 0.0, + f64_: 0.0, + v8: None, + vf64: None, } + } } impl Serialize for TypeAliases<'_> { - fn serialize(&self, serializer: S) -> Result - where - S: Serializer, - { - let mut s = serializer.serialize_struct("TypeAliases", 12)?; - s.serialize_field("i8_", &self.i8_())?; - s.serialize_field("u8_", &self.u8_())?; - s.serialize_field("i16_", &self.i16_())?; - s.serialize_field("u16_", &self.u16_())?; - s.serialize_field("i32_", &self.i32_())?; - s.serialize_field("u32_", &self.u32_())?; - s.serialize_field("i64_", &self.i64_())?; - s.serialize_field("u64_", &self.u64_())?; - s.serialize_field("f32_", &self.f32_())?; - s.serialize_field("f64_", &self.f64_())?; - if let Some(f) = self.v8() { - s.serialize_field("v8", &f)?; - } else { - s.skip_field("v8")?; - } - if let Some(f) = self.vf64() { - s.serialize_field("vf64", &f)?; - } else { - s.skip_field("vf64")?; - } - s.end() - } + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let mut s = serializer.serialize_struct("TypeAliases", 12)?; + s.serialize_field("i8_", &self.i8_())?; + s.serialize_field("u8_", &self.u8_())?; + s.serialize_field("i16_", &self.i16_())?; + s.serialize_field("u16_", &self.u16_())?; + s.serialize_field("i32_", &self.i32_())?; + s.serialize_field("u32_", &self.u32_())?; + s.serialize_field("i64_", &self.i64_())?; + s.serialize_field("u64_", &self.u64_())?; + s.serialize_field("f32_", &self.f32_())?; + s.serialize_field("f64_", &self.f64_())?; + if let Some(f) = self.v8() { + s.serialize_field("v8", &f)?; + } else { + s.skip_field("v8")?; + } + if let Some(f) = self.vf64() { + s.serialize_field("vf64", &f)?; + } else { + s.skip_field("vf64")?; + } + s.end() + } } pub struct TypeAliasesBuilder<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> { - fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, + fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, + start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, } - impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> TypeAliasesBuilder<'a, 'b, A> { - #[inline] - pub fn add_i8_(&mut self, i8_: i8) { - self.fbb_.push_slot::(TypeAliases::VT_I8_, i8_, 0); - } - - #[inline] - pub fn add_u8_(&mut self, u8_: u8) { - self.fbb_.push_slot::(TypeAliases::VT_U8_, u8_, 0); - } - - #[inline] - pub fn add_i16_(&mut self, i16_: i16) { - self.fbb_.push_slot::(TypeAliases::VT_I16_, i16_, 0); - } - - #[inline] - pub fn add_u16_(&mut self, u16_: u16) { - self.fbb_.push_slot::(TypeAliases::VT_U16_, u16_, 0); - } - - #[inline] - pub fn add_i32_(&mut self, i32_: i32) { - self.fbb_.push_slot::(TypeAliases::VT_I32_, i32_, 0); - } - - #[inline] - pub fn add_u32_(&mut self, u32_: u32) { - self.fbb_.push_slot::(TypeAliases::VT_U32_, u32_, 0); - } - - #[inline] - pub fn add_i64_(&mut self, i64_: i64) { - self.fbb_.push_slot::(TypeAliases::VT_I64_, i64_, 0); - } - - #[inline] - pub fn add_u64_(&mut self, u64_: u64) { - self.fbb_.push_slot::(TypeAliases::VT_U64_, u64_, 0); - } - - #[inline] - pub fn add_f32_(&mut self, f32_: f32) { - self.fbb_.push_slot::(TypeAliases::VT_F32_, f32_, 0.0); - } - - #[inline] - pub fn add_f64_(&mut self, f64_: f64) { - self.fbb_.push_slot::(TypeAliases::VT_F64_, f64_, 0.0); - } - - #[inline] - pub fn add_v8(&mut self, v8: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , i8>>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(TypeAliases::VT_V8, v8); - } - - #[inline] - pub fn add_vf64(&mut self, vf64: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , f64>>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(TypeAliases::VT_VF64, vf64); - } - - #[inline] - pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> TypeAliasesBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - TypeAliasesBuilder { - fbb_: _fbb, - start_: start, - } - } - - #[inline] - pub fn finish(self) -> ::flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - ::flatbuffers::WIPOffset::new(o.value()) + #[inline] + pub fn add_i8_(&mut self, i8_: i8) { + self.fbb_.push_slot::(TypeAliases::VT_I8_, i8_, 0); + } + #[inline] + pub fn add_u8_(&mut self, u8_: u8) { + self.fbb_.push_slot::(TypeAliases::VT_U8_, u8_, 0); + } + #[inline] + pub fn add_i16_(&mut self, i16_: i16) { + self.fbb_.push_slot::(TypeAliases::VT_I16_, i16_, 0); + } + #[inline] + pub fn add_u16_(&mut self, u16_: u16) { + self.fbb_.push_slot::(TypeAliases::VT_U16_, u16_, 0); + } + #[inline] + pub fn add_i32_(&mut self, i32_: i32) { + self.fbb_.push_slot::(TypeAliases::VT_I32_, i32_, 0); + } + #[inline] + pub fn add_u32_(&mut self, u32_: u32) { + self.fbb_.push_slot::(TypeAliases::VT_U32_, u32_, 0); + } + #[inline] + pub fn add_i64_(&mut self, i64_: i64) { + self.fbb_.push_slot::(TypeAliases::VT_I64_, i64_, 0); + } + #[inline] + pub fn add_u64_(&mut self, u64_: u64) { + self.fbb_.push_slot::(TypeAliases::VT_U64_, u64_, 0); + } + #[inline] + pub fn add_f32_(&mut self, f32_: f32) { + self.fbb_.push_slot::(TypeAliases::VT_F32_, f32_, 0.0); + } + #[inline] + pub fn add_f64_(&mut self, f64_: f64) { + self.fbb_.push_slot::(TypeAliases::VT_F64_, f64_, 0.0); + } + #[inline] + pub fn add_v8(&mut self, v8: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , i8>>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(TypeAliases::VT_V8, v8); + } + #[inline] + pub fn add_vf64(&mut self, vf64: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , f64>>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(TypeAliases::VT_VF64, vf64); + } + #[inline] + pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> TypeAliasesBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + TypeAliasesBuilder { + fbb_: _fbb, + start_: start, } + } + #[inline] + pub fn finish(self) -> ::flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + ::flatbuffers::WIPOffset::new(o.value()) + } } impl ::core::fmt::Debug for TypeAliases<'_> { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - let mut ds = f.debug_struct("TypeAliases"); - ds.field("i8_", &self.i8_()); - ds.field("u8_", &self.u8_()); - ds.field("i16_", &self.i16_()); - ds.field("u16_", &self.u16_()); - ds.field("i32_", &self.i32_()); - ds.field("u32_", &self.u32_()); - ds.field("i64_", &self.i64_()); - ds.field("u64_", &self.u64_()); - ds.field("f32_", &self.f32_()); - ds.field("f64_", &self.f64_()); - ds.field("v8", &self.v8()); - ds.field("vf64", &self.vf64()); - ds.finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + let mut ds = f.debug_struct("TypeAliases"); + ds.field("i8_", &self.i8_()); + ds.field("u8_", &self.u8_()); + ds.field("i16_", &self.i16_()); + ds.field("u16_", &self.u16_()); + ds.field("i32_", &self.i32_()); + ds.field("u32_", &self.u32_()); + ds.field("i64_", &self.i64_()); + ds.field("u64_", &self.u64_()); + ds.field("f32_", &self.f32_()); + ds.field("f64_", &self.f64_()); + ds.field("v8", &self.v8()); + ds.field("vf64", &self.vf64()); + ds.finish() + } } - #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub struct TypeAliasesT { - pub i8_: i8, - pub u8_: u8, - pub i16_: i16, - pub u16_: u16, - pub i32_: i32, - pub u32_: u32, - pub i64_: i64, - pub u64_: u64, - pub f32_: f32, - pub f64_: f64, - pub v8: Option>, - pub vf64: Option>, + pub i8_: i8, + pub u8_: u8, + pub i16_: i16, + pub u16_: u16, + pub i32_: i32, + pub u32_: u32, + pub i64_: i64, + pub u64_: u64, + pub f32_: f32, + pub f64_: f64, + pub v8: Option>, + pub vf64: Option>, } - impl Default for TypeAliasesT { - fn default() -> Self { - Self { - i8_: 0, - u8_: 0, - i16_: 0, - u16_: 0, - i32_: 0, - u32_: 0, - i64_: 0, - u64_: 0, - f32_: 0.0, - f64_: 0.0, - v8: None, - vf64: None, - } + fn default() -> Self { + Self { + i8_: 0, + u8_: 0, + i16_: 0, + u16_: 0, + i32_: 0, + u32_: 0, + i64_: 0, + u64_: 0, + f32_: 0.0, + f64_: 0.0, + v8: None, + vf64: None, } + } } - impl TypeAliasesT { - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( - &self, - _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> - ) -> ::flatbuffers::WIPOffset> { - let i8_ = self.i8_; - let u8_ = self.u8_; - let i16_ = self.i16_; - let u16_ = self.u16_; - let i32_ = self.i32_; - let u32_ = self.u32_; - let i64_ = self.i64_; - let u64_ = self.u64_; - let f32_ = self.f32_; - let f64_ = self.f64_; - let v8 = self.v8.as_ref().map(|x|{ - _fbb.create_vector(x) - }); - let vf64 = self.vf64.as_ref().map(|x|{ - _fbb.create_vector(x) - }); - TypeAliases::create(_fbb, &TypeAliasesArgs{ - i8_, - u8_, - i16_, - u16_, - i32_, - u32_, - i64_, - u64_, - f32_, - f64_, - v8, - vf64, - }) - } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> + ) -> ::flatbuffers::WIPOffset> { + let i8_ = self.i8_; + let u8_ = self.u8_; + let i16_ = self.i16_; + let u16_ = self.u16_; + let i32_ = self.i32_; + let u32_ = self.u32_; + let i64_ = self.i64_; + let u64_ = self.u64_; + let f32_ = self.f32_; + let f64_ = self.f64_; + let v8 = self.v8.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + let vf64 = self.vf64.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + TypeAliases::create(_fbb, &TypeAliasesArgs{ + i8_, + u8_, + i16_, + u16_, + i32_, + u32_, + i64_, + u64_, + f32_, + f64_, + v8, + vf64, + }) + } } diff --git a/tests/monster_test_serialize/my_game/example/vec_3_generated.rs b/tests/monster_test_serialize/my_game/example/vec_3_generated.rs index 3d2d61199..a1afa8251 100644 --- a/tests/monster_test_serialize/my_game/example/vec_3_generated.rs +++ b/tests/monster_test_serialize/my_game/example/vec_3_generated.rs @@ -4,60 +4,50 @@ extern crate alloc; extern crate serde; use self::serde::ser::{Serialize, Serializer, SerializeStruct}; use super::*; - // struct Vec3, aligned to 8 #[repr(transparent)] #[derive(Clone, Copy, PartialEq)] pub struct Vec3(pub [u8; 32]); - -impl Default for Vec3 { - fn default() -> Self { - Self([0; 32]) - } +impl Default for Vec3 { + fn default() -> Self { + Self([0; 32]) + } } - impl ::core::fmt::Debug for Vec3 { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - f.debug_struct("Vec3") - .field("x", &self.x()) - .field("y", &self.y()) - .field("z", &self.z()) - .field("test1", &self.test1()) - .field("test2", &self.test2()) - .field("test3", &self.test3()) - .finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + f.debug_struct("Vec3") + .field("x", &self.x()) + .field("y", &self.y()) + .field("z", &self.z()) + .field("test1", &self.test1()) + .field("test2", &self.test2()) + .field("test3", &self.test3()) + .finish() + } } impl ::flatbuffers::SimpleToVerifyInSlice for Vec3 {} - impl<'a> ::flatbuffers::Follow<'a> for Vec3 { - type Inner = &'a Vec3; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - unsafe { <&'a Vec3>::follow(buf, loc) } - } + type Inner = &'a Vec3; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { <&'a Vec3>::follow(buf, loc) } + } } - impl<'a> ::flatbuffers::Follow<'a> for &'a Vec3 { - type Inner = &'a Vec3; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - unsafe { ::flatbuffers::follow_cast_ref::(buf, loc) } - } + type Inner = &'a Vec3; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { ::flatbuffers::follow_cast_ref::(buf, loc) } + } } - impl<'b> ::flatbuffers::Push for Vec3 { type Output = Vec3; - #[inline] unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { let src = unsafe { ::core::slice::from_raw_parts(self as *const Vec3 as *const u8, ::size()) }; dst.copy_from_slice(src); } - #[inline] fn alignment() -> ::flatbuffers::PushAlignment { ::flatbuffers::PushAlignment::new(8) @@ -65,254 +55,242 @@ impl<'b> ::flatbuffers::Push for Vec3 { } impl<'a> ::flatbuffers::Verifiable for Vec3 { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.in_buffer::(pos) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.in_buffer::(pos) + } } impl Serialize for Vec3 { - fn serialize(&self, serializer: S) -> Result - where - S: Serializer, - { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { let mut s = serializer.serialize_struct("Vec3", 6)?; - s.serialize_field("x", &self.x())?; - s.serialize_field("y", &self.y())?; - s.serialize_field("z", &self.z())?; - s.serialize_field("test1", &self.test1())?; - s.serialize_field("test2", &self.test2())?; - s.serialize_field("test3", &self.test3())?; - s.end() - } + s.serialize_field("x", &self.x())?; + s.serialize_field("y", &self.y())?; + s.serialize_field("z", &self.z())?; + s.serialize_field("test1", &self.test1())?; + s.serialize_field("test2", &self.test2())?; + s.serialize_field("test3", &self.test3())?; + s.end() + } } impl<'a> Vec3 { - #[allow(clippy::too_many_arguments)] - pub fn new( - x: f32, - y: f32, - z: f32, - test1: f64, - test2: Color, - test3: &Test, - ) -> Self { - let mut s = Self([0; 32]); - s.set_x(x); - s.set_y(y); - s.set_z(z); - s.set_test1(test1); - s.set_test2(test2); - s.set_test3(test3); - s - } + #[allow(clippy::too_many_arguments)] + pub fn new( + x: f32, + y: f32, + z: f32, + test1: f64, + test2: Color, + test3: &Test, + ) -> Self { + let mut s = Self([0; 32]); + s.set_x(x); + s.set_y(y); + s.set_z(z); + s.set_test1(test1); + s.set_test2(test2); + s.set_test3(test3); + s + } - pub const fn get_fully_qualified_name() -> &'static str { - "MyGame.Example.Vec3" - } + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Example.Vec3" + } - pub fn x(&self) -> f32 { - let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - ::flatbuffers::EndianScalar::from_little_endian(unsafe { - ::core::ptr::copy_nonoverlapping( - self.0[0..].as_ptr(), - mem.as_mut_ptr() as *mut u8, - ::core::mem::size_of::<::Scalar>(), - ); - mem.assume_init() - }) - } + pub fn x(&self) -> f32 { + let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + ::flatbuffers::EndianScalar::from_little_endian(unsafe { + ::core::ptr::copy_nonoverlapping( + self.0[0..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + ::core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } - pub fn set_x(&mut self, x: f32) { - let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - unsafe { - ::core::ptr::copy_nonoverlapping( - &x_le as *const _ as *const u8, - self.0[0..].as_mut_ptr(), - ::core::mem::size_of::<::Scalar>(), - ); - } + pub fn set_x(&mut self, x: f32) { + let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + ::core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[0..].as_mut_ptr(), + ::core::mem::size_of::<::Scalar>(), + ); } + } - pub fn y(&self) -> f32 { - let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - ::flatbuffers::EndianScalar::from_little_endian(unsafe { - ::core::ptr::copy_nonoverlapping( - self.0[4..].as_ptr(), - mem.as_mut_ptr() as *mut u8, - ::core::mem::size_of::<::Scalar>(), - ); - mem.assume_init() - }) - } + pub fn y(&self) -> f32 { + let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + ::flatbuffers::EndianScalar::from_little_endian(unsafe { + ::core::ptr::copy_nonoverlapping( + self.0[4..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + ::core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } - pub fn set_y(&mut self, x: f32) { - let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - unsafe { - ::core::ptr::copy_nonoverlapping( - &x_le as *const _ as *const u8, - self.0[4..].as_mut_ptr(), - ::core::mem::size_of::<::Scalar>(), - ); - } + pub fn set_y(&mut self, x: f32) { + let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + ::core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[4..].as_mut_ptr(), + ::core::mem::size_of::<::Scalar>(), + ); } + } - pub fn z(&self) -> f32 { - let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - ::flatbuffers::EndianScalar::from_little_endian(unsafe { - ::core::ptr::copy_nonoverlapping( - self.0[8..].as_ptr(), - mem.as_mut_ptr() as *mut u8, - ::core::mem::size_of::<::Scalar>(), - ); - mem.assume_init() - }) - } + pub fn z(&self) -> f32 { + let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + ::flatbuffers::EndianScalar::from_little_endian(unsafe { + ::core::ptr::copy_nonoverlapping( + self.0[8..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + ::core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } - pub fn set_z(&mut self, x: f32) { - let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - unsafe { - ::core::ptr::copy_nonoverlapping( - &x_le as *const _ as *const u8, - self.0[8..].as_mut_ptr(), - ::core::mem::size_of::<::Scalar>(), - ); - } + pub fn set_z(&mut self, x: f32) { + let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + ::core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[8..].as_mut_ptr(), + ::core::mem::size_of::<::Scalar>(), + ); } + } - pub fn test1(&self) -> f64 { - let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - ::flatbuffers::EndianScalar::from_little_endian(unsafe { - ::core::ptr::copy_nonoverlapping( - self.0[16..].as_ptr(), - mem.as_mut_ptr() as *mut u8, - ::core::mem::size_of::<::Scalar>(), - ); - mem.assume_init() - }) - } + pub fn test1(&self) -> f64 { + let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + ::flatbuffers::EndianScalar::from_little_endian(unsafe { + ::core::ptr::copy_nonoverlapping( + self.0[16..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + ::core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } - pub fn set_test1(&mut self, x: f64) { - let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - unsafe { - ::core::ptr::copy_nonoverlapping( - &x_le as *const _ as *const u8, - self.0[16..].as_mut_ptr(), - ::core::mem::size_of::<::Scalar>(), - ); - } + pub fn set_test1(&mut self, x: f64) { + let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + ::core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[16..].as_mut_ptr(), + ::core::mem::size_of::<::Scalar>(), + ); } + } - pub fn test2(&self) -> Color { - let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - ::flatbuffers::EndianScalar::from_little_endian(unsafe { - ::core::ptr::copy_nonoverlapping( - self.0[24..].as_ptr(), - mem.as_mut_ptr() as *mut u8, - ::core::mem::size_of::<::Scalar>(), - ); - mem.assume_init() - }) - } + pub fn test2(&self) -> Color { + let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + ::flatbuffers::EndianScalar::from_little_endian(unsafe { + ::core::ptr::copy_nonoverlapping( + self.0[24..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + ::core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } - pub fn set_test2(&mut self, x: Color) { - let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - unsafe { - ::core::ptr::copy_nonoverlapping( - &x_le as *const _ as *const u8, - self.0[24..].as_mut_ptr(), - ::core::mem::size_of::<::Scalar>(), - ); - } + pub fn set_test2(&mut self, x: Color) { + let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + ::core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[24..].as_mut_ptr(), + ::core::mem::size_of::<::Scalar>(), + ); } + } - pub fn test3(&self) -> &Test { - // Safety: - // Created from a valid Table for this object - // Which contains a valid struct in this slot - unsafe { &*(self.0[26..].as_ptr() as *const Test) } - } + pub fn test3(&self) -> &Test { + // Safety: + // Created from a valid Table for this object + // Which contains a valid struct in this slot + unsafe { &*(self.0[26..].as_ptr() as *const Test) } + } - #[allow(clippy::identity_op)] - pub fn set_test3(&mut self, x: &Test) { - self.0[26..26 + 4].copy_from_slice(&x.0) - } + #[allow(clippy::identity_op)] + pub fn set_test3(&mut self, x: &Test) { + self.0[26..26 + 4].copy_from_slice(&x.0) + } - pub fn unpack(&self) -> Vec3T { - Vec3T { - x: self.x(), - y: self.y(), - z: self.z(), - test1: self.test1(), - test2: self.test2(), - test3: self.test3().unpack(), - } + pub fn unpack(&self) -> Vec3T { + Vec3T { + x: self.x(), + y: self.y(), + z: self.z(), + test1: self.test1(), + test2: self.test2(), + test3: self.test3().unpack(), } + } } -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Default)] pub struct Vec3T { - pub x: f32, - pub y: f32, - pub z: f32, - pub test1: f64, - pub test2: Color, - pub test3: TestT, + pub x: f32, + pub y: f32, + pub z: f32, + pub test1: f64, + pub test2: Color, + pub test3: TestT, } -impl Default for Vec3T { - fn default() -> Self { - Self { - x: 0.0, - y: 0.0, - z: 0.0, - test1: 0.0, - test2: Default::default(), - test3: Default::default(), - } - } +impl Vec3T { + pub fn pack(&self) -> Vec3 { + Vec3::new( + self.x, + self.y, + self.z, + self.test1, + self.test2, + &self.test3.pack(), + ) + } } -impl Vec3T { - pub fn pack(&self) -> Vec3 { - Vec3::new( - self.x, - self.y, - self.z, - self.test1, - self.test2, - &self.test3.pack(), - ) - } -} diff --git a/tests/monster_test_serialize/my_game/example_2/monster_generated.rs b/tests/monster_test_serialize/my_game/example_2/monster_generated.rs index 7c5856e6c..4faf31089 100644 --- a/tests/monster_test_serialize/my_game/example_2/monster_generated.rs +++ b/tests/monster_test_serialize/my_game/example_2/monster_generated.rs @@ -4,127 +4,118 @@ extern crate alloc; extern crate serde; use self::serde::ser::{Serialize, Serializer, SerializeStruct}; use super::*; - pub enum MonsterOffset {} - #[derive(Copy, Clone, PartialEq)] + pub struct Monster<'a> { - pub _tab: ::flatbuffers::Table<'a>, + pub _tab: ::flatbuffers::Table<'a>, } impl<'a> ::flatbuffers::Follow<'a> for Monster<'a> { - type Inner = Monster<'a>; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } - } + type Inner = Monster<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } + } } impl<'a> Monster<'a> { - pub const fn get_fully_qualified_name() -> &'static str { - "MyGame.Example2.Monster" - } - #[inline] - pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { - Monster { _tab: table } - } + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Example2.Monster" + } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, - _args: &'args MonsterArgs - ) -> ::flatbuffers::WIPOffset> { - let mut builder = MonsterBuilder::new(_fbb); - builder.finish() - } + #[inline] + pub unsafe 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, A: ::flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, + _args: &'args MonsterArgs + ) -> ::flatbuffers::WIPOffset> { + let mut builder = MonsterBuilder::new(_fbb); + builder.finish() + } - pub fn unpack(&self) -> MonsterT { - MonsterT { - } + pub fn unpack(&self) -> MonsterT { + MonsterT { } + } } impl ::flatbuffers::Verifiable for Monster<'_> { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.visit_table(pos)? - .finish(); - Ok(()) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.visit_table(pos)? + .finish(); + Ok(()) + } } - pub struct MonsterArgs { } - impl<'a> Default for MonsterArgs { - #[inline] - fn default() -> Self { - MonsterArgs { - } + #[inline] + fn default() -> Self { + MonsterArgs { } + } } impl Serialize for Monster<'_> { - fn serialize(&self, serializer: S) -> Result - where - S: Serializer, - { - let s = serializer.serialize_struct("Monster", 0)?; - s.end() - } + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let s = serializer.serialize_struct("Monster", 0)?; + s.end() + } } pub struct MonsterBuilder<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> { - fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, + fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, + start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, } - impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> MonsterBuilder<'a, 'b, A> { - #[inline] - pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> MonsterBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - MonsterBuilder { - fbb_: _fbb, - start_: start, - } - } - - #[inline] - pub fn finish(self) -> ::flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - ::flatbuffers::WIPOffset::new(o.value()) + #[inline] + pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> MonsterBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + MonsterBuilder { + fbb_: _fbb, + start_: start, } + } + #[inline] + pub fn finish(self) -> ::flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + ::flatbuffers::WIPOffset::new(o.value()) + } } impl ::core::fmt::Debug for Monster<'_> { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - let mut ds = f.debug_struct("Monster"); - ds.finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + let mut ds = f.debug_struct("Monster"); + ds.finish() + } } - #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub struct MonsterT { } - impl Default for MonsterT { - fn default() -> Self { - Self { - } + fn default() -> Self { + Self { } + } } - impl MonsterT { - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( - &self, - _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> - ) -> ::flatbuffers::WIPOffset> { - Monster::create(_fbb, &MonsterArgs{ - }) - } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> + ) -> ::flatbuffers::WIPOffset> { + Monster::create(_fbb, &MonsterArgs{ + }) + } } diff --git a/tests/monster_test_serialize/my_game/in_parent_namespace_generated.rs b/tests/monster_test_serialize/my_game/in_parent_namespace_generated.rs index 2b4bcc169..2f3723ea5 100644 --- a/tests/monster_test_serialize/my_game/in_parent_namespace_generated.rs +++ b/tests/monster_test_serialize/my_game/in_parent_namespace_generated.rs @@ -4,127 +4,118 @@ extern crate alloc; extern crate serde; use self::serde::ser::{Serialize, Serializer, SerializeStruct}; use super::*; - pub enum InParentNamespaceOffset {} - #[derive(Copy, Clone, PartialEq)] + pub struct InParentNamespace<'a> { - pub _tab: ::flatbuffers::Table<'a>, + pub _tab: ::flatbuffers::Table<'a>, } impl<'a> ::flatbuffers::Follow<'a> for InParentNamespace<'a> { - type Inner = InParentNamespace<'a>; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } - } + type Inner = InParentNamespace<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } + } } impl<'a> InParentNamespace<'a> { - pub const fn get_fully_qualified_name() -> &'static str { - "MyGame.InParentNamespace" - } - #[inline] - pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { - InParentNamespace { _tab: table } - } + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.InParentNamespace" + } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, - _args: &'args InParentNamespaceArgs - ) -> ::flatbuffers::WIPOffset> { - let mut builder = InParentNamespaceBuilder::new(_fbb); - builder.finish() - } + #[inline] + pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { + InParentNamespace { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, + _args: &'args InParentNamespaceArgs + ) -> ::flatbuffers::WIPOffset> { + let mut builder = InParentNamespaceBuilder::new(_fbb); + builder.finish() + } - pub fn unpack(&self) -> InParentNamespaceT { - InParentNamespaceT { - } + pub fn unpack(&self) -> InParentNamespaceT { + InParentNamespaceT { } + } } impl ::flatbuffers::Verifiable for InParentNamespace<'_> { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.visit_table(pos)? - .finish(); - Ok(()) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.visit_table(pos)? + .finish(); + Ok(()) + } } - pub struct InParentNamespaceArgs { } - impl<'a> Default for InParentNamespaceArgs { - #[inline] - fn default() -> Self { - InParentNamespaceArgs { - } + #[inline] + fn default() -> Self { + InParentNamespaceArgs { } + } } impl Serialize for InParentNamespace<'_> { - fn serialize(&self, serializer: S) -> Result - where - S: Serializer, - { - let s = serializer.serialize_struct("InParentNamespace", 0)?; - s.end() - } + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let s = serializer.serialize_struct("InParentNamespace", 0)?; + s.end() + } } pub struct InParentNamespaceBuilder<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> { - fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, + fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, + start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, } - impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> InParentNamespaceBuilder<'a, 'b, A> { - #[inline] - pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> InParentNamespaceBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - InParentNamespaceBuilder { - fbb_: _fbb, - start_: start, - } - } - - #[inline] - pub fn finish(self) -> ::flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - ::flatbuffers::WIPOffset::new(o.value()) + #[inline] + pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> InParentNamespaceBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + InParentNamespaceBuilder { + fbb_: _fbb, + start_: start, } + } + #[inline] + pub fn finish(self) -> ::flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + ::flatbuffers::WIPOffset::new(o.value()) + } } impl ::core::fmt::Debug for InParentNamespace<'_> { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - let mut ds = f.debug_struct("InParentNamespace"); - ds.finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + let mut ds = f.debug_struct("InParentNamespace"); + ds.finish() + } } - #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub struct InParentNamespaceT { } - impl Default for InParentNamespaceT { - fn default() -> Self { - Self { - } + fn default() -> Self { + Self { } + } } - impl InParentNamespaceT { - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( - &self, - _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> - ) -> ::flatbuffers::WIPOffset> { - InParentNamespace::create(_fbb, &InParentNamespaceArgs{ - }) - } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> + ) -> ::flatbuffers::WIPOffset> { + InParentNamespace::create(_fbb, &InParentNamespaceArgs{ + }) + } } diff --git a/tests/monster_test_serialize/my_game/other_name_space/from_include_generated.rs b/tests/monster_test_serialize/my_game/other_name_space/from_include_generated.rs index 1ee5da78f..84d5602ae 100644 --- a/tests/monster_test_serialize/my_game/other_name_space/from_include_generated.rs +++ b/tests/monster_test_serialize/my_game/other_name_space/from_include_generated.rs @@ -4,59 +4,52 @@ extern crate alloc; extern crate serde; use self::serde::ser::{Serialize, Serializer, SerializeStruct}; use super::*; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] pub const ENUM_MIN_FROM_INCLUDE: i64 = 0; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] pub const ENUM_MAX_FROM_INCLUDE: i64 = 0; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] #[allow(non_camel_case_types)] pub const ENUM_VALUES_FROM_INCLUDE: [FromInclude; 1] = [ - FromInclude::IncludeVal, + FromInclude::IncludeVal, ]; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] #[repr(transparent)] pub struct FromInclude(pub i64); - #[allow(non_upper_case_globals)] impl FromInclude { - pub const IncludeVal: Self = Self(0); + pub const IncludeVal: Self = Self(0); - pub const ENUM_MIN: i64 = 0; - pub const ENUM_MAX: i64 = 0; - pub const ENUM_VALUES: &'static [Self] = &[ - Self::IncludeVal, - ]; - - /// Returns the variant's name or "" if unknown. - pub fn variant_name(self) -> Option<&'static str> { - match self { - Self::IncludeVal => Some("IncludeVal"), - _ => None, - } + pub const ENUM_MIN: i64 = 0; + pub const ENUM_MAX: i64 = 0; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::IncludeVal, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::IncludeVal => Some("IncludeVal"), + _ => None, } + } } - impl ::core::fmt::Debug for FromInclude { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - if let Some(name) = self.variant_name() { - f.write_str(name) - } else { - f.write_fmt(format_args!("", self.0)) - } + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) } + } } - impl Serialize for FromInclude { - fn serialize(&self, serializer: S) -> Result - where - S: Serializer, - { - serializer.serialize_unit_variant("FromInclude", self.0 as u32, self.variant_name().unwrap()) - } + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_unit_variant("FromInclude", self.0 as u32, self.variant_name().unwrap()) + } } impl<'de> serde::Deserialize<'de> for FromInclude { @@ -79,18 +72,16 @@ impl<'de> serde::Deserialize<'de> for FromInclude { } impl<'a> ::flatbuffers::Follow<'a> for FromInclude { - type Inner = Self; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; - Self(b) - } + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; + Self(b) + } } impl ::flatbuffers::Push for FromInclude { type Output = FromInclude; - #[inline] unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { unsafe { ::flatbuffers::emplace_scalar::(dst, self.0) }; @@ -98,28 +89,26 @@ impl ::flatbuffers::Push for FromInclude { } impl ::flatbuffers::EndianScalar for FromInclude { - type Scalar = i64; - - #[inline] - fn to_little_endian(self) -> i64 { - self.0.to_le() - } - - #[inline] - #[allow(clippy::wrong_self_convention)] - fn from_little_endian(v: i64) -> Self { - let b = i64::from_le(v); - Self(b) - } + type Scalar = i64; + #[inline] + fn to_little_endian(self) -> i64 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: i64) -> Self { + let b = i64::from_le(v); + Self(b) + } } impl<'a> ::flatbuffers::Verifiable for FromInclude { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - i64::run_verifier(v, pos) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + i64::run_verifier(v, pos) + } } impl ::flatbuffers::SimpleToVerifyInSlice for FromInclude {} diff --git a/tests/monster_test_serialize/my_game/other_name_space/table_b_generated.rs b/tests/monster_test_serialize/my_game/other_name_space/table_b_generated.rs index 177cfeb48..ecb57c54f 100644 --- a/tests/monster_test_serialize/my_game/other_name_space/table_b_generated.rs +++ b/tests/monster_test_serialize/my_game/other_name_space/table_b_generated.rs @@ -4,162 +4,151 @@ extern crate alloc; extern crate serde; use self::serde::ser::{Serialize, Serializer, SerializeStruct}; use super::*; - pub enum TableBOffset {} - #[derive(Copy, Clone, PartialEq)] + pub struct TableB<'a> { - pub _tab: ::flatbuffers::Table<'a>, + pub _tab: ::flatbuffers::Table<'a>, } impl<'a> ::flatbuffers::Follow<'a> for TableB<'a> { - type Inner = TableB<'a>; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } - } + type Inner = TableB<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } + } } impl<'a> TableB<'a> { - pub const VT_A: ::flatbuffers::VOffsetT = 4; + pub const VT_A: ::flatbuffers::VOffsetT = 4; - pub const fn get_fully_qualified_name() -> &'static str { - "MyGame.OtherNameSpace.TableB" - } + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.OtherNameSpace.TableB" + } - #[inline] - pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { - TableB { _tab: table } - } + #[inline] + pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { + TableB { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args TableBArgs<'args> + ) -> ::flatbuffers::WIPOffset> { + let mut builder = TableBBuilder::new(_fbb); + if let Some(x) = args.a { builder.add_a(x); } + builder.finish() + } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args TableBArgs<'args> - ) -> ::flatbuffers::WIPOffset> { - let mut builder = TableBBuilder::new(_fbb); - if let Some(x) = args.a { builder.add_a(x); } - builder.finish() + pub fn unpack(&self) -> TableBT { + let a = self.a().map(|x| { + alloc::boxed::Box::new(x.unpack()) + }); + TableBT { + a, } + } - pub fn unpack(&self) -> TableBT { - let a = self.a().map(|x| { - alloc::boxed::Box::new(x.unpack()) - }); - TableBT { - a, - } - } - - #[inline] - pub fn a(&self) -> Option> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset>(TableB::VT_A, None)} - } + #[inline] + pub fn a(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset>(TableB::VT_A, None)} + } } impl ::flatbuffers::Verifiable for TableB<'_> { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.visit_table(pos)? - .visit_field::<::flatbuffers::ForwardsUOffset>("a", Self::VT_A, false)? - .finish(); - Ok(()) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.visit_table(pos)? + .visit_field::<::flatbuffers::ForwardsUOffset>("a", Self::VT_A, false)? + .finish(); + Ok(()) + } } - pub struct TableBArgs<'a> { pub a: Option<::flatbuffers::WIPOffset>>, } - impl<'a> Default for TableBArgs<'a> { - #[inline] - fn default() -> Self { - TableBArgs { - a: None, - } + #[inline] + fn default() -> Self { + TableBArgs { + a: None, } + } } impl Serialize for TableB<'_> { - fn serialize(&self, serializer: S) -> Result - where - S: Serializer, - { - let mut s = serializer.serialize_struct("TableB", 1)?; - if let Some(f) = self.a() { - s.serialize_field("a", &f)?; - } else { - s.skip_field("a")?; - } - s.end() - } + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let mut s = serializer.serialize_struct("TableB", 1)?; + if let Some(f) = self.a() { + s.serialize_field("a", &f)?; + } else { + s.skip_field("a")?; + } + s.end() + } } pub struct TableBBuilder<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> { - fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, + fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, + start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, } - impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> TableBBuilder<'a, 'b, A> { - #[inline] - pub fn add_a(&mut self, a: ::flatbuffers::WIPOffset>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset>(TableB::VT_A, a); - } - - #[inline] - pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> TableBBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - TableBBuilder { - fbb_: _fbb, - start_: start, - } - } - - #[inline] - pub fn finish(self) -> ::flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - ::flatbuffers::WIPOffset::new(o.value()) + #[inline] + pub fn add_a(&mut self, a: ::flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset>(TableB::VT_A, a); + } + #[inline] + pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> TableBBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + TableBBuilder { + fbb_: _fbb, + start_: start, } + } + #[inline] + pub fn finish(self) -> ::flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + ::flatbuffers::WIPOffset::new(o.value()) + } } impl ::core::fmt::Debug for TableB<'_> { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - let mut ds = f.debug_struct("TableB"); - ds.field("a", &self.a()); - ds.finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + let mut ds = f.debug_struct("TableB"); + ds.field("a", &self.a()); + ds.finish() + } } - #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub struct TableBT { - pub a: Option>, + pub a: Option>, } - impl Default for TableBT { - fn default() -> Self { - Self { - a: None, - } + fn default() -> Self { + Self { + a: None, } + } } - impl TableBT { - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( - &self, - _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> - ) -> ::flatbuffers::WIPOffset> { - let a = self.a.as_ref().map(|x|{ - x.pack(_fbb) - }); - TableB::create(_fbb, &TableBArgs{ - a, - }) - } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> + ) -> ::flatbuffers::WIPOffset> { + let a = self.a.as_ref().map(|x|{ + x.pack(_fbb) + }); + TableB::create(_fbb, &TableBArgs{ + a, + }) + } } diff --git a/tests/monster_test_serialize/my_game/other_name_space/unused_generated.rs b/tests/monster_test_serialize/my_game/other_name_space/unused_generated.rs index 99540dba5..0d5f2240a 100644 --- a/tests/monster_test_serialize/my_game/other_name_space/unused_generated.rs +++ b/tests/monster_test_serialize/my_game/other_name_space/unused_generated.rs @@ -4,55 +4,45 @@ extern crate alloc; extern crate serde; use self::serde::ser::{Serialize, Serializer, SerializeStruct}; use super::*; - // struct Unused, aligned to 4 #[repr(transparent)] #[derive(Clone, Copy, PartialEq)] pub struct Unused(pub [u8; 4]); - -impl Default for Unused { - fn default() -> Self { - Self([0; 4]) - } +impl Default for Unused { + fn default() -> Self { + Self([0; 4]) + } } - impl ::core::fmt::Debug for Unused { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - f.debug_struct("Unused") - .field("a", &self.a()) - .finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + f.debug_struct("Unused") + .field("a", &self.a()) + .finish() + } } impl ::flatbuffers::SimpleToVerifyInSlice for Unused {} - impl<'a> ::flatbuffers::Follow<'a> for Unused { - type Inner = &'a Unused; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - unsafe { <&'a Unused>::follow(buf, loc) } - } + type Inner = &'a Unused; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { <&'a Unused>::follow(buf, loc) } + } } - impl<'a> ::flatbuffers::Follow<'a> for &'a Unused { - type Inner = &'a Unused; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - unsafe { ::flatbuffers::follow_cast_ref::(buf, loc) } - } + type Inner = &'a Unused; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { ::flatbuffers::follow_cast_ref::(buf, loc) } + } } - impl<'b> ::flatbuffers::Push for Unused { type Output = Unused; - #[inline] unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { let src = unsafe { ::core::slice::from_raw_parts(self as *const Unused as *const u8, ::size()) }; dst.copy_from_slice(src); } - #[inline] fn alignment() -> ::flatbuffers::PushAlignment { ::flatbuffers::PushAlignment::new(4) @@ -60,91 +50,84 @@ impl<'b> ::flatbuffers::Push for Unused { } impl<'a> ::flatbuffers::Verifiable for Unused { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.in_buffer::(pos) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.in_buffer::(pos) + } } impl Serialize for Unused { - fn serialize(&self, serializer: S) -> Result - where - S: Serializer, - { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { let mut s = serializer.serialize_struct("Unused", 1)?; - s.serialize_field("a", &self.a())?; - s.end() - } + s.serialize_field("a", &self.a())?; + s.end() + } } impl<'a> Unused { - #[allow(clippy::too_many_arguments)] - pub fn new( - a: i32, - ) -> Self { - let mut s = Self([0; 4]); - s.set_a(a); - s - } + #[allow(clippy::too_many_arguments)] + pub fn new( + a: i32, + ) -> Self { + let mut s = Self([0; 4]); + s.set_a(a); + s + } - pub const fn get_fully_qualified_name() -> &'static str { - "MyGame.OtherNameSpace.Unused" - } + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.OtherNameSpace.Unused" + } - pub fn a(&self) -> i32 { - let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - ::flatbuffers::EndianScalar::from_little_endian(unsafe { - ::core::ptr::copy_nonoverlapping( - self.0[0..].as_ptr(), - mem.as_mut_ptr() as *mut u8, - ::core::mem::size_of::<::Scalar>(), - ); - mem.assume_init() - }) - } + pub fn a(&self) -> i32 { + let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + ::flatbuffers::EndianScalar::from_little_endian(unsafe { + ::core::ptr::copy_nonoverlapping( + self.0[0..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + ::core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } - pub fn set_a(&mut self, x: i32) { - let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - unsafe { - ::core::ptr::copy_nonoverlapping( - &x_le as *const _ as *const u8, - self.0[0..].as_mut_ptr(), - ::core::mem::size_of::<::Scalar>(), - ); - } + pub fn set_a(&mut self, x: i32) { + let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + ::core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[0..].as_mut_ptr(), + ::core::mem::size_of::<::Scalar>(), + ); } + } - pub fn unpack(&self) -> UnusedT { - UnusedT { - a: self.a(), - } + pub fn unpack(&self) -> UnusedT { + UnusedT { + a: self.a(), } + } } -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Default)] pub struct UnusedT { - pub a: i32, + pub a: i32, } -impl Default for UnusedT { - fn default() -> Self { - Self { - a: 0, - } - } +impl UnusedT { + pub fn pack(&self) -> Unused { + Unused::new( + self.a, + ) + } } -impl UnusedT { - pub fn pack(&self) -> Unused { - Unused::new( - self.a, - ) - } -} diff --git a/tests/monster_test_serialize/table_a_generated.rs b/tests/monster_test_serialize/table_a_generated.rs index d079d5f9b..a3c1ba608 100644 --- a/tests/monster_test_serialize/table_a_generated.rs +++ b/tests/monster_test_serialize/table_a_generated.rs @@ -4,162 +4,151 @@ extern crate alloc; extern crate serde; use self::serde::ser::{Serialize, Serializer, SerializeStruct}; use super::*; - pub enum TableAOffset {} - #[derive(Copy, Clone, PartialEq)] + pub struct TableA<'a> { - pub _tab: ::flatbuffers::Table<'a>, + pub _tab: ::flatbuffers::Table<'a>, } impl<'a> ::flatbuffers::Follow<'a> for TableA<'a> { - type Inner = TableA<'a>; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } - } + type Inner = TableA<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } + } } impl<'a> TableA<'a> { - pub const VT_B: ::flatbuffers::VOffsetT = 4; + pub const VT_B: ::flatbuffers::VOffsetT = 4; - pub const fn get_fully_qualified_name() -> &'static str { - "TableA" - } + pub const fn get_fully_qualified_name() -> &'static str { + "TableA" + } - #[inline] - pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { - TableA { _tab: table } - } + #[inline] + pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { + TableA { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args TableAArgs<'args> + ) -> ::flatbuffers::WIPOffset> { + let mut builder = TableABuilder::new(_fbb); + if let Some(x) = args.b { builder.add_b(x); } + builder.finish() + } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args TableAArgs<'args> - ) -> ::flatbuffers::WIPOffset> { - let mut builder = TableABuilder::new(_fbb); - if let Some(x) = args.b { builder.add_b(x); } - builder.finish() + pub fn unpack(&self) -> TableAT { + let b = self.b().map(|x| { + alloc::boxed::Box::new(x.unpack()) + }); + TableAT { + b, } + } - pub fn unpack(&self) -> TableAT { - let b = self.b().map(|x| { - alloc::boxed::Box::new(x.unpack()) - }); - TableAT { - b, - } - } - - #[inline] - pub fn b(&self) -> Option> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset>(TableA::VT_B, None)} - } + #[inline] + pub fn b(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset>(TableA::VT_B, None)} + } } impl ::flatbuffers::Verifiable for TableA<'_> { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.visit_table(pos)? - .visit_field::<::flatbuffers::ForwardsUOffset>("b", Self::VT_B, false)? - .finish(); - Ok(()) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.visit_table(pos)? + .visit_field::<::flatbuffers::ForwardsUOffset>("b", Self::VT_B, false)? + .finish(); + Ok(()) + } } - pub struct TableAArgs<'a> { pub b: Option<::flatbuffers::WIPOffset>>, } - impl<'a> Default for TableAArgs<'a> { - #[inline] - fn default() -> Self { - TableAArgs { - b: None, - } + #[inline] + fn default() -> Self { + TableAArgs { + b: None, } + } } impl Serialize for TableA<'_> { - fn serialize(&self, serializer: S) -> Result - where - S: Serializer, - { - let mut s = serializer.serialize_struct("TableA", 1)?; - if let Some(f) = self.b() { - s.serialize_field("b", &f)?; - } else { - s.skip_field("b")?; - } - s.end() - } + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let mut s = serializer.serialize_struct("TableA", 1)?; + if let Some(f) = self.b() { + s.serialize_field("b", &f)?; + } else { + s.skip_field("b")?; + } + s.end() + } } pub struct TableABuilder<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> { - fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, + fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, + start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, } - impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> TableABuilder<'a, 'b, A> { - #[inline] - pub fn add_b(&mut self, b: ::flatbuffers::WIPOffset>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset>(TableA::VT_B, b); - } - - #[inline] - pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> TableABuilder<'a, 'b, A> { - let start = _fbb.start_table(); - TableABuilder { - fbb_: _fbb, - start_: start, - } - } - - #[inline] - pub fn finish(self) -> ::flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - ::flatbuffers::WIPOffset::new(o.value()) + #[inline] + pub fn add_b(&mut self, b: ::flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset>(TableA::VT_B, b); + } + #[inline] + pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> TableABuilder<'a, 'b, A> { + let start = _fbb.start_table(); + TableABuilder { + fbb_: _fbb, + start_: start, } + } + #[inline] + pub fn finish(self) -> ::flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + ::flatbuffers::WIPOffset::new(o.value()) + } } impl ::core::fmt::Debug for TableA<'_> { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - let mut ds = f.debug_struct("TableA"); - ds.field("b", &self.b()); - ds.finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + let mut ds = f.debug_struct("TableA"); + ds.field("b", &self.b()); + ds.finish() + } } - #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub struct TableAT { - pub b: Option>, + pub b: Option>, } - impl Default for TableAT { - fn default() -> Self { - Self { - b: None, - } + fn default() -> Self { + Self { + b: None, } + } } - impl TableAT { - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( - &self, - _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> - ) -> ::flatbuffers::WIPOffset> { - let b = self.b.as_ref().map(|x|{ - x.pack(_fbb) - }); - TableA::create(_fbb, &TableAArgs{ - b, - }) - } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> + ) -> ::flatbuffers::WIPOffset> { + let b = self.b.as_ref().map(|x|{ + x.pack(_fbb) + }); + TableA::create(_fbb, &TableAArgs{ + b, + }) + } } diff --git a/tests/monster_test_suffix/ext_only/monster_test_generated.hpp b/tests/monster_test_suffix/ext_only/monster_test_generated.hpp index 83ed1c811..91c5e32f1 100644 --- a/tests/monster_test_suffix/ext_only/monster_test_generated.hpp +++ b/tests/monster_test_suffix/ext_only/monster_test_generated.hpp @@ -3227,10 +3227,10 @@ inline ::flatbuffers::Offset Monster::Pack(::flatbuffers::FlatBufferBui auto _test = _o->test.Pack(_fbb); auto _test4 = _o->test4.size() ? _fbb.CreateVectorOfStructs(_o->test4) : 0; auto _testarrayofstring = _o->testarrayofstring.size() ? _fbb.CreateVectorOfStrings(_o->testarrayofstring) : 0; - auto _testarrayoftables = _o->testarrayoftables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->testarrayoftables.size(), [](size_t i, _VectorArgs *__va) { return MyGame::Example::CreateMonster(*__va->__fbb, __va->__o->testarrayoftables[i].get(), __va->__rehasher); }, &_va ) : 0; - auto _enemy = _o->enemy ? MyGame::Example::CreateMonster(_fbb, _o->enemy.get(), _rehasher) : 0; + auto _testarrayoftables = _o->testarrayoftables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->testarrayoftables.size(), [](size_t i, _VectorArgs *__va) { return CreateMonster(*__va->__fbb, __va->__o->testarrayoftables[i].get(), __va->__rehasher); }, &_va ) : 0; + auto _enemy = _o->enemy ? CreateMonster(_fbb, _o->enemy.get(), _rehasher) : 0; auto _testnestedflatbuffer = _o->testnestedflatbuffer.size() ? _fbb.CreateVector(_o->testnestedflatbuffer) : 0; - auto _testempty = _o->testempty ? MyGame::Example::CreateStat(_fbb, _o->testempty.get(), _rehasher) : 0; + auto _testempty = _o->testempty ? CreateStat(_fbb, _o->testempty.get(), _rehasher) : 0; auto _testbool = _o->testbool; auto _testhashs32_fnv1 = _o->testhashs32_fnv1; auto _testhashu32_fnv1 = _o->testhashu32_fnv1; @@ -3250,11 +3250,11 @@ inline ::flatbuffers::Offset Monster::Pack(::flatbuffers::FlatBufferBui auto _test5 = _o->test5.size() ? _fbb.CreateVectorOfStructs(_o->test5) : 0; auto _vector_of_longs = _o->vector_of_longs.size() ? _fbb.CreateVector(_o->vector_of_longs) : 0; auto _vector_of_doubles = _o->vector_of_doubles.size() ? _fbb.CreateVector(_o->vector_of_doubles) : 0; - auto _parent_namespace_test = _o->parent_namespace_test ? MyGame::CreateInParentNamespace(_fbb, _o->parent_namespace_test.get(), _rehasher) : 0; - auto _vector_of_referrables = _o->vector_of_referrables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->vector_of_referrables.size(), [](size_t i, _VectorArgs *__va) { return MyGame::Example::CreateReferrable(*__va->__fbb, __va->__o->vector_of_referrables[i].get(), __va->__rehasher); }, &_va ) : 0; + auto _parent_namespace_test = _o->parent_namespace_test ? CreateInParentNamespace(_fbb, _o->parent_namespace_test.get(), _rehasher) : 0; + auto _vector_of_referrables = _o->vector_of_referrables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->vector_of_referrables.size(), [](size_t i, _VectorArgs *__va) { return CreateReferrable(*__va->__fbb, __va->__o->vector_of_referrables[i].get(), __va->__rehasher); }, &_va ) : 0; auto _single_weak_reference = _rehasher ? static_cast((*_rehasher)(_o->single_weak_reference)) : 0; auto _vector_of_weak_references = _o->vector_of_weak_references.size() ? _fbb.CreateVector(_o->vector_of_weak_references.size(), [](size_t i, _VectorArgs *__va) { return __va->__rehasher ? static_cast((*__va->__rehasher)(__va->__o->vector_of_weak_references[i])) : 0; }, &_va ) : 0; - auto _vector_of_strong_referrables = _o->vector_of_strong_referrables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->vector_of_strong_referrables.size(), [](size_t i, _VectorArgs *__va) { return MyGame::Example::CreateReferrable(*__va->__fbb, __va->__o->vector_of_strong_referrables[i].get(), __va->__rehasher); }, &_va ) : 0; + auto _vector_of_strong_referrables = _o->vector_of_strong_referrables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->vector_of_strong_referrables.size(), [](size_t i, _VectorArgs *__va) { return CreateReferrable(*__va->__fbb, __va->__o->vector_of_strong_referrables[i].get(), __va->__rehasher); }, &_va ) : 0; auto _co_owning_reference = _rehasher ? static_cast((*_rehasher)(_o->co_owning_reference)) : 0; auto _vector_of_co_owning_references = _o->vector_of_co_owning_references.size() ? _fbb.CreateVector(_o->vector_of_co_owning_references.size(), [](size_t i, _VectorArgs *__va) { return __va->__rehasher ? static_cast((*__va->__rehasher)(__va->__o->vector_of_co_owning_references[i].get())) : 0; }, &_va ) : 0; auto _non_owning_reference = _rehasher ? static_cast((*_rehasher)(_o->non_owning_reference)) : 0; @@ -3266,7 +3266,7 @@ inline ::flatbuffers::Offset Monster::Pack(::flatbuffers::FlatBufferBui auto _vector_of_enums = _o->vector_of_enums.size() ? _fbb.CreateVectorScalarCast(::flatbuffers::data(_o->vector_of_enums), _o->vector_of_enums.size()) : 0; auto _signed_enum = _o->signed_enum; auto _testrequirednestedflatbuffer = _o->testrequirednestedflatbuffer.size() ? _fbb.CreateVector(_o->testrequirednestedflatbuffer) : 0; - auto _scalar_key_sorted_tables = _o->scalar_key_sorted_tables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->scalar_key_sorted_tables.size(), [](size_t i, _VectorArgs *__va) { return MyGame::Example::CreateStat(*__va->__fbb, __va->__o->scalar_key_sorted_tables[i].get(), __va->__rehasher); }, &_va ) : 0; + auto _scalar_key_sorted_tables = _o->scalar_key_sorted_tables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->scalar_key_sorted_tables.size(), [](size_t i, _VectorArgs *__va) { return CreateStat(*__va->__fbb, __va->__o->scalar_key_sorted_tables[i].get(), __va->__rehasher); }, &_va ) : 0; auto _native_inline = &_o->native_inline; auto _long_enum_non_enum_default = _o->long_enum_non_enum_default; auto _long_enum_normal_default = _o->long_enum_normal_default; diff --git a/tests/monster_test_suffix/filesuffix_only/monster_test_suffix.h b/tests/monster_test_suffix/filesuffix_only/monster_test_suffix.h index 83ed1c811..91c5e32f1 100644 --- a/tests/monster_test_suffix/filesuffix_only/monster_test_suffix.h +++ b/tests/monster_test_suffix/filesuffix_only/monster_test_suffix.h @@ -3227,10 +3227,10 @@ inline ::flatbuffers::Offset Monster::Pack(::flatbuffers::FlatBufferBui auto _test = _o->test.Pack(_fbb); auto _test4 = _o->test4.size() ? _fbb.CreateVectorOfStructs(_o->test4) : 0; auto _testarrayofstring = _o->testarrayofstring.size() ? _fbb.CreateVectorOfStrings(_o->testarrayofstring) : 0; - auto _testarrayoftables = _o->testarrayoftables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->testarrayoftables.size(), [](size_t i, _VectorArgs *__va) { return MyGame::Example::CreateMonster(*__va->__fbb, __va->__o->testarrayoftables[i].get(), __va->__rehasher); }, &_va ) : 0; - auto _enemy = _o->enemy ? MyGame::Example::CreateMonster(_fbb, _o->enemy.get(), _rehasher) : 0; + auto _testarrayoftables = _o->testarrayoftables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->testarrayoftables.size(), [](size_t i, _VectorArgs *__va) { return CreateMonster(*__va->__fbb, __va->__o->testarrayoftables[i].get(), __va->__rehasher); }, &_va ) : 0; + auto _enemy = _o->enemy ? CreateMonster(_fbb, _o->enemy.get(), _rehasher) : 0; auto _testnestedflatbuffer = _o->testnestedflatbuffer.size() ? _fbb.CreateVector(_o->testnestedflatbuffer) : 0; - auto _testempty = _o->testempty ? MyGame::Example::CreateStat(_fbb, _o->testempty.get(), _rehasher) : 0; + auto _testempty = _o->testempty ? CreateStat(_fbb, _o->testempty.get(), _rehasher) : 0; auto _testbool = _o->testbool; auto _testhashs32_fnv1 = _o->testhashs32_fnv1; auto _testhashu32_fnv1 = _o->testhashu32_fnv1; @@ -3250,11 +3250,11 @@ inline ::flatbuffers::Offset Monster::Pack(::flatbuffers::FlatBufferBui auto _test5 = _o->test5.size() ? _fbb.CreateVectorOfStructs(_o->test5) : 0; auto _vector_of_longs = _o->vector_of_longs.size() ? _fbb.CreateVector(_o->vector_of_longs) : 0; auto _vector_of_doubles = _o->vector_of_doubles.size() ? _fbb.CreateVector(_o->vector_of_doubles) : 0; - auto _parent_namespace_test = _o->parent_namespace_test ? MyGame::CreateInParentNamespace(_fbb, _o->parent_namespace_test.get(), _rehasher) : 0; - auto _vector_of_referrables = _o->vector_of_referrables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->vector_of_referrables.size(), [](size_t i, _VectorArgs *__va) { return MyGame::Example::CreateReferrable(*__va->__fbb, __va->__o->vector_of_referrables[i].get(), __va->__rehasher); }, &_va ) : 0; + auto _parent_namespace_test = _o->parent_namespace_test ? CreateInParentNamespace(_fbb, _o->parent_namespace_test.get(), _rehasher) : 0; + auto _vector_of_referrables = _o->vector_of_referrables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->vector_of_referrables.size(), [](size_t i, _VectorArgs *__va) { return CreateReferrable(*__va->__fbb, __va->__o->vector_of_referrables[i].get(), __va->__rehasher); }, &_va ) : 0; auto _single_weak_reference = _rehasher ? static_cast((*_rehasher)(_o->single_weak_reference)) : 0; auto _vector_of_weak_references = _o->vector_of_weak_references.size() ? _fbb.CreateVector(_o->vector_of_weak_references.size(), [](size_t i, _VectorArgs *__va) { return __va->__rehasher ? static_cast((*__va->__rehasher)(__va->__o->vector_of_weak_references[i])) : 0; }, &_va ) : 0; - auto _vector_of_strong_referrables = _o->vector_of_strong_referrables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->vector_of_strong_referrables.size(), [](size_t i, _VectorArgs *__va) { return MyGame::Example::CreateReferrable(*__va->__fbb, __va->__o->vector_of_strong_referrables[i].get(), __va->__rehasher); }, &_va ) : 0; + auto _vector_of_strong_referrables = _o->vector_of_strong_referrables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->vector_of_strong_referrables.size(), [](size_t i, _VectorArgs *__va) { return CreateReferrable(*__va->__fbb, __va->__o->vector_of_strong_referrables[i].get(), __va->__rehasher); }, &_va ) : 0; auto _co_owning_reference = _rehasher ? static_cast((*_rehasher)(_o->co_owning_reference)) : 0; auto _vector_of_co_owning_references = _o->vector_of_co_owning_references.size() ? _fbb.CreateVector(_o->vector_of_co_owning_references.size(), [](size_t i, _VectorArgs *__va) { return __va->__rehasher ? static_cast((*__va->__rehasher)(__va->__o->vector_of_co_owning_references[i].get())) : 0; }, &_va ) : 0; auto _non_owning_reference = _rehasher ? static_cast((*_rehasher)(_o->non_owning_reference)) : 0; @@ -3266,7 +3266,7 @@ inline ::flatbuffers::Offset Monster::Pack(::flatbuffers::FlatBufferBui auto _vector_of_enums = _o->vector_of_enums.size() ? _fbb.CreateVectorScalarCast(::flatbuffers::data(_o->vector_of_enums), _o->vector_of_enums.size()) : 0; auto _signed_enum = _o->signed_enum; auto _testrequirednestedflatbuffer = _o->testrequirednestedflatbuffer.size() ? _fbb.CreateVector(_o->testrequirednestedflatbuffer) : 0; - auto _scalar_key_sorted_tables = _o->scalar_key_sorted_tables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->scalar_key_sorted_tables.size(), [](size_t i, _VectorArgs *__va) { return MyGame::Example::CreateStat(*__va->__fbb, __va->__o->scalar_key_sorted_tables[i].get(), __va->__rehasher); }, &_va ) : 0; + auto _scalar_key_sorted_tables = _o->scalar_key_sorted_tables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->scalar_key_sorted_tables.size(), [](size_t i, _VectorArgs *__va) { return CreateStat(*__va->__fbb, __va->__o->scalar_key_sorted_tables[i].get(), __va->__rehasher); }, &_va ) : 0; auto _native_inline = &_o->native_inline; auto _long_enum_non_enum_default = _o->long_enum_non_enum_default; auto _long_enum_normal_default = _o->long_enum_normal_default; diff --git a/tests/monster_test_suffix/monster_test_suffix.hpp b/tests/monster_test_suffix/monster_test_suffix.hpp index 83ed1c811..91c5e32f1 100644 --- a/tests/monster_test_suffix/monster_test_suffix.hpp +++ b/tests/monster_test_suffix/monster_test_suffix.hpp @@ -3227,10 +3227,10 @@ inline ::flatbuffers::Offset Monster::Pack(::flatbuffers::FlatBufferBui auto _test = _o->test.Pack(_fbb); auto _test4 = _o->test4.size() ? _fbb.CreateVectorOfStructs(_o->test4) : 0; auto _testarrayofstring = _o->testarrayofstring.size() ? _fbb.CreateVectorOfStrings(_o->testarrayofstring) : 0; - auto _testarrayoftables = _o->testarrayoftables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->testarrayoftables.size(), [](size_t i, _VectorArgs *__va) { return MyGame::Example::CreateMonster(*__va->__fbb, __va->__o->testarrayoftables[i].get(), __va->__rehasher); }, &_va ) : 0; - auto _enemy = _o->enemy ? MyGame::Example::CreateMonster(_fbb, _o->enemy.get(), _rehasher) : 0; + auto _testarrayoftables = _o->testarrayoftables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->testarrayoftables.size(), [](size_t i, _VectorArgs *__va) { return CreateMonster(*__va->__fbb, __va->__o->testarrayoftables[i].get(), __va->__rehasher); }, &_va ) : 0; + auto _enemy = _o->enemy ? CreateMonster(_fbb, _o->enemy.get(), _rehasher) : 0; auto _testnestedflatbuffer = _o->testnestedflatbuffer.size() ? _fbb.CreateVector(_o->testnestedflatbuffer) : 0; - auto _testempty = _o->testempty ? MyGame::Example::CreateStat(_fbb, _o->testempty.get(), _rehasher) : 0; + auto _testempty = _o->testempty ? CreateStat(_fbb, _o->testempty.get(), _rehasher) : 0; auto _testbool = _o->testbool; auto _testhashs32_fnv1 = _o->testhashs32_fnv1; auto _testhashu32_fnv1 = _o->testhashu32_fnv1; @@ -3250,11 +3250,11 @@ inline ::flatbuffers::Offset Monster::Pack(::flatbuffers::FlatBufferBui auto _test5 = _o->test5.size() ? _fbb.CreateVectorOfStructs(_o->test5) : 0; auto _vector_of_longs = _o->vector_of_longs.size() ? _fbb.CreateVector(_o->vector_of_longs) : 0; auto _vector_of_doubles = _o->vector_of_doubles.size() ? _fbb.CreateVector(_o->vector_of_doubles) : 0; - auto _parent_namespace_test = _o->parent_namespace_test ? MyGame::CreateInParentNamespace(_fbb, _o->parent_namespace_test.get(), _rehasher) : 0; - auto _vector_of_referrables = _o->vector_of_referrables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->vector_of_referrables.size(), [](size_t i, _VectorArgs *__va) { return MyGame::Example::CreateReferrable(*__va->__fbb, __va->__o->vector_of_referrables[i].get(), __va->__rehasher); }, &_va ) : 0; + auto _parent_namespace_test = _o->parent_namespace_test ? CreateInParentNamespace(_fbb, _o->parent_namespace_test.get(), _rehasher) : 0; + auto _vector_of_referrables = _o->vector_of_referrables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->vector_of_referrables.size(), [](size_t i, _VectorArgs *__va) { return CreateReferrable(*__va->__fbb, __va->__o->vector_of_referrables[i].get(), __va->__rehasher); }, &_va ) : 0; auto _single_weak_reference = _rehasher ? static_cast((*_rehasher)(_o->single_weak_reference)) : 0; auto _vector_of_weak_references = _o->vector_of_weak_references.size() ? _fbb.CreateVector(_o->vector_of_weak_references.size(), [](size_t i, _VectorArgs *__va) { return __va->__rehasher ? static_cast((*__va->__rehasher)(__va->__o->vector_of_weak_references[i])) : 0; }, &_va ) : 0; - auto _vector_of_strong_referrables = _o->vector_of_strong_referrables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->vector_of_strong_referrables.size(), [](size_t i, _VectorArgs *__va) { return MyGame::Example::CreateReferrable(*__va->__fbb, __va->__o->vector_of_strong_referrables[i].get(), __va->__rehasher); }, &_va ) : 0; + auto _vector_of_strong_referrables = _o->vector_of_strong_referrables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->vector_of_strong_referrables.size(), [](size_t i, _VectorArgs *__va) { return CreateReferrable(*__va->__fbb, __va->__o->vector_of_strong_referrables[i].get(), __va->__rehasher); }, &_va ) : 0; auto _co_owning_reference = _rehasher ? static_cast((*_rehasher)(_o->co_owning_reference)) : 0; auto _vector_of_co_owning_references = _o->vector_of_co_owning_references.size() ? _fbb.CreateVector(_o->vector_of_co_owning_references.size(), [](size_t i, _VectorArgs *__va) { return __va->__rehasher ? static_cast((*__va->__rehasher)(__va->__o->vector_of_co_owning_references[i].get())) : 0; }, &_va ) : 0; auto _non_owning_reference = _rehasher ? static_cast((*_rehasher)(_o->non_owning_reference)) : 0; @@ -3266,7 +3266,7 @@ inline ::flatbuffers::Offset Monster::Pack(::flatbuffers::FlatBufferBui auto _vector_of_enums = _o->vector_of_enums.size() ? _fbb.CreateVectorScalarCast(::flatbuffers::data(_o->vector_of_enums), _o->vector_of_enums.size()) : 0; auto _signed_enum = _o->signed_enum; auto _testrequirednestedflatbuffer = _o->testrequirednestedflatbuffer.size() ? _fbb.CreateVector(_o->testrequirednestedflatbuffer) : 0; - auto _scalar_key_sorted_tables = _o->scalar_key_sorted_tables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->scalar_key_sorted_tables.size(), [](size_t i, _VectorArgs *__va) { return MyGame::Example::CreateStat(*__va->__fbb, __va->__o->scalar_key_sorted_tables[i].get(), __va->__rehasher); }, &_va ) : 0; + auto _scalar_key_sorted_tables = _o->scalar_key_sorted_tables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->scalar_key_sorted_tables.size(), [](size_t i, _VectorArgs *__va) { return CreateStat(*__va->__fbb, __va->__o->scalar_key_sorted_tables[i].get(), __va->__rehasher); }, &_va ) : 0; auto _native_inline = &_o->native_inline; auto _long_enum_non_enum_default = _o->long_enum_non_enum_default; auto _long_enum_normal_default = _o->long_enum_normal_default; diff --git a/tests/more_defaults/abc_generated.rs b/tests/more_defaults/abc_generated.rs index 5a87917b7..c41b40600 100644 --- a/tests/more_defaults/abc_generated.rs +++ b/tests/more_defaults/abc_generated.rs @@ -2,73 +2,64 @@ // @generated extern crate alloc; use super::*; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] pub const ENUM_MIN_ABC: i32 = 0; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] pub const ENUM_MAX_ABC: i32 = 2; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] #[allow(non_camel_case_types)] pub const ENUM_VALUES_ABC: [ABC; 3] = [ - ABC::A, - ABC::B, - ABC::C, + ABC::A, + ABC::B, + ABC::C, ]; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] #[repr(transparent)] pub struct ABC(pub i32); - #[allow(non_upper_case_globals)] impl ABC { - pub const A: Self = Self(0); - pub const B: Self = Self(1); - pub const C: Self = Self(2); + pub const A: Self = Self(0); + pub const B: Self = Self(1); + pub const C: Self = Self(2); - pub const ENUM_MIN: i32 = 0; - pub const ENUM_MAX: i32 = 2; - pub const ENUM_VALUES: &'static [Self] = &[ - Self::A, - Self::B, - Self::C, - ]; - - /// Returns the variant's name or "" if unknown. - pub fn variant_name(self) -> Option<&'static str> { - match self { - Self::A => Some("A"), - Self::B => Some("B"), - Self::C => Some("C"), - _ => None, - } + pub const ENUM_MIN: i32 = 0; + pub const ENUM_MAX: i32 = 2; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::A, + Self::B, + Self::C, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::A => Some("A"), + Self::B => Some("B"), + Self::C => Some("C"), + _ => None, } + } } - impl ::core::fmt::Debug for ABC { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - if let Some(name) = self.variant_name() { - f.write_str(name) - } else { - f.write_fmt(format_args!("", self.0)) - } + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) } + } } - impl<'a> ::flatbuffers::Follow<'a> for ABC { - type Inner = Self; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; - Self(b) - } + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; + Self(b) + } } impl ::flatbuffers::Push for ABC { type Output = ABC; - #[inline] unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { unsafe { ::flatbuffers::emplace_scalar::(dst, self.0) }; @@ -76,28 +67,26 @@ impl ::flatbuffers::Push for ABC { } impl ::flatbuffers::EndianScalar for ABC { - type Scalar = i32; - - #[inline] - fn to_little_endian(self) -> i32 { - self.0.to_le() - } - - #[inline] - #[allow(clippy::wrong_self_convention)] - fn from_little_endian(v: i32) -> Self { - let b = i32::from_le(v); - Self(b) - } + type Scalar = i32; + #[inline] + fn to_little_endian(self) -> i32 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: i32) -> Self { + let b = i32::from_le(v); + Self(b) + } } impl<'a> ::flatbuffers::Verifiable for ABC { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - i32::run_verifier(v, pos) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + i32::run_verifier(v, pos) + } } impl ::flatbuffers::SimpleToVerifyInSlice for ABC {} diff --git a/tests/more_defaults/more_defaults_generated.rs b/tests/more_defaults/more_defaults_generated.rs index 709987577..72dd9dbcb 100644 --- a/tests/more_defaults/more_defaults_generated.rs +++ b/tests/more_defaults/more_defaults_generated.rs @@ -2,156 +2,147 @@ // @generated extern crate alloc; use super::*; - pub enum MoreDefaultsOffset {} - #[derive(Copy, Clone, PartialEq)] + pub struct MoreDefaults<'a> { - pub _tab: ::flatbuffers::Table<'a>, + pub _tab: ::flatbuffers::Table<'a>, } impl<'a> ::flatbuffers::Follow<'a> for MoreDefaults<'a> { - type Inner = MoreDefaults<'a>; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } - } + type Inner = MoreDefaults<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } + } } impl<'a> MoreDefaults<'a> { - pub const VT_INTS: ::flatbuffers::VOffsetT = 4; - pub const VT_FLOATS: ::flatbuffers::VOffsetT = 6; - pub const VT_EMPTY_STRING: ::flatbuffers::VOffsetT = 8; - pub const VT_SOME_STRING: ::flatbuffers::VOffsetT = 10; - pub const VT_ABCS: ::flatbuffers::VOffsetT = 12; - pub const VT_BOOLS: ::flatbuffers::VOffsetT = 14; + pub const VT_INTS: ::flatbuffers::VOffsetT = 4; + pub const VT_FLOATS: ::flatbuffers::VOffsetT = 6; + pub const VT_EMPTY_STRING: ::flatbuffers::VOffsetT = 8; + pub const VT_SOME_STRING: ::flatbuffers::VOffsetT = 10; + pub const VT_ABCS: ::flatbuffers::VOffsetT = 12; + pub const VT_BOOLS: ::flatbuffers::VOffsetT = 14; - pub const fn get_fully_qualified_name() -> &'static str { - "MoreDefaults" - } + pub const fn get_fully_qualified_name() -> &'static str { + "MoreDefaults" + } - #[inline] - pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { - MoreDefaults { _tab: table } - } + #[inline] + pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { + MoreDefaults { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args MoreDefaultsArgs<'args> + ) -> ::flatbuffers::WIPOffset> { + let mut builder = MoreDefaultsBuilder::new(_fbb); + if let Some(x) = args.bools { builder.add_bools(x); } + if let Some(x) = args.abcs { builder.add_abcs(x); } + if let Some(x) = args.some_string { builder.add_some_string(x); } + if let Some(x) = args.empty_string { builder.add_empty_string(x); } + if let Some(x) = args.floats { builder.add_floats(x); } + if let Some(x) = args.ints { builder.add_ints(x); } + builder.finish() + } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args MoreDefaultsArgs<'args> - ) -> ::flatbuffers::WIPOffset> { - let mut builder = MoreDefaultsBuilder::new(_fbb); - if let Some(x) = args.bools { builder.add_bools(x); } - if let Some(x) = args.abcs { builder.add_abcs(x); } - if let Some(x) = args.some_string { builder.add_some_string(x); } - if let Some(x) = args.empty_string { builder.add_empty_string(x); } - if let Some(x) = args.floats { builder.add_floats(x); } - if let Some(x) = args.ints { builder.add_ints(x); } - builder.finish() + pub fn unpack(&self) -> MoreDefaultsT { + let ints = { + let x = self.ints(); + x.into_iter().collect() + }; + let floats = { + let x = self.floats(); + x.into_iter().collect() + }; + let empty_string = { + let x = self.empty_string(); + alloc::string::ToString::to_string(x) + }; + let some_string = { + let x = self.some_string(); + alloc::string::ToString::to_string(x) + }; + let abcs = { + let x = self.abcs(); + x.into_iter().collect() + }; + let bools = { + let x = self.bools(); + x.into_iter().collect() + }; + MoreDefaultsT { + ints, + floats, + empty_string, + some_string, + abcs, + bools, } + } - pub fn unpack(&self) -> MoreDefaultsT { - let ints = { - let x = self.ints(); - x.into_iter().collect() - }; - let floats = { - let x = self.floats(); - x.into_iter().collect() - }; - let empty_string = { - let x = self.empty_string(); - alloc::string::ToString::to_string(x) - }; - let some_string = { - let x = self.some_string(); - alloc::string::ToString::to_string(x) - }; - let abcs = { - let x = self.abcs(); - x.into_iter().collect() - }; - let bools = { - let x = self.bools(); - x.into_iter().collect() - }; - MoreDefaultsT { - ints, - floats, - empty_string, - some_string, - abcs, - bools, - } - } - - #[inline] - pub fn ints(&self) -> ::flatbuffers::Vector<'a, i32> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, i32>>>(MoreDefaults::VT_INTS, Some(Default::default())).unwrap()} - } - - #[inline] - pub fn floats(&self) -> ::flatbuffers::Vector<'a, f32> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, f32>>>(MoreDefaults::VT_FLOATS, Some(Default::default())).unwrap()} - } - - #[inline] - pub fn empty_string(&self) -> &'a str { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<&str>>(MoreDefaults::VT_EMPTY_STRING, Some(&"")).unwrap()} - } - - #[inline] - pub fn some_string(&self) -> &'a str { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<&str>>(MoreDefaults::VT_SOME_STRING, Some(&"some")).unwrap()} - } - - #[inline] - pub fn abcs(&self) -> ::flatbuffers::Vector<'a, ABC> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, ABC>>>(MoreDefaults::VT_ABCS, Some(Default::default())).unwrap()} - } - - #[inline] - pub fn bools(&self) -> ::flatbuffers::Vector<'a, bool> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, bool>>>(MoreDefaults::VT_BOOLS, Some(Default::default())).unwrap()} - } + #[inline] + pub fn ints(&self) -> ::flatbuffers::Vector<'a, i32> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, i32>>>(MoreDefaults::VT_INTS, Some(Default::default())).unwrap()} + } + #[inline] + pub fn floats(&self) -> ::flatbuffers::Vector<'a, f32> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, f32>>>(MoreDefaults::VT_FLOATS, Some(Default::default())).unwrap()} + } + #[inline] + pub fn empty_string(&self) -> &'a str { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<&str>>(MoreDefaults::VT_EMPTY_STRING, Some(&"")).unwrap()} + } + #[inline] + pub fn some_string(&self) -> &'a str { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<&str>>(MoreDefaults::VT_SOME_STRING, Some(&"some")).unwrap()} + } + #[inline] + pub fn abcs(&self) -> ::flatbuffers::Vector<'a, ABC> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, ABC>>>(MoreDefaults::VT_ABCS, Some(Default::default())).unwrap()} + } + #[inline] + pub fn bools(&self) -> ::flatbuffers::Vector<'a, bool> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'a, bool>>>(MoreDefaults::VT_BOOLS, Some(Default::default())).unwrap()} + } } impl ::flatbuffers::Verifiable for MoreDefaults<'_> { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.visit_table(pos)? - .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, i32>>>("ints", Self::VT_INTS, false)? - .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, f32>>>("floats", Self::VT_FLOATS, false)? - .visit_field::<::flatbuffers::ForwardsUOffset<&str>>("empty_string", Self::VT_EMPTY_STRING, false)? - .visit_field::<::flatbuffers::ForwardsUOffset<&str>>("some_string", Self::VT_SOME_STRING, false)? - .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, ABC>>>("abcs", Self::VT_ABCS, false)? - .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, bool>>>("bools", Self::VT_BOOLS, false)? - .finish(); - Ok(()) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.visit_table(pos)? + .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, i32>>>("ints", Self::VT_INTS, false)? + .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, f32>>>("floats", Self::VT_FLOATS, false)? + .visit_field::<::flatbuffers::ForwardsUOffset<&str>>("empty_string", Self::VT_EMPTY_STRING, false)? + .visit_field::<::flatbuffers::ForwardsUOffset<&str>>("some_string", Self::VT_SOME_STRING, false)? + .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, ABC>>>("abcs", Self::VT_ABCS, false)? + .visit_field::<::flatbuffers::ForwardsUOffset<::flatbuffers::Vector<'_, bool>>>("bools", Self::VT_BOOLS, false)? + .finish(); + Ok(()) + } } - pub struct MoreDefaultsArgs<'a> { pub ints: Option<::flatbuffers::WIPOffset<::flatbuffers::Vector<'a, i32>>>, pub floats: Option<::flatbuffers::WIPOffset<::flatbuffers::Vector<'a, f32>>>, @@ -160,146 +151,134 @@ pub struct MoreDefaultsArgs<'a> { pub abcs: Option<::flatbuffers::WIPOffset<::flatbuffers::Vector<'a, ABC>>>, pub bools: Option<::flatbuffers::WIPOffset<::flatbuffers::Vector<'a, bool>>>, } - impl<'a> Default for MoreDefaultsArgs<'a> { - #[inline] - fn default() -> Self { - MoreDefaultsArgs { - ints: None, - floats: None, - empty_string: None, - some_string: None, - abcs: None, - bools: None, - } + #[inline] + fn default() -> Self { + MoreDefaultsArgs { + ints: None, + floats: None, + empty_string: None, + some_string: None, + abcs: None, + bools: None, } + } } pub struct MoreDefaultsBuilder<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> { - fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, + fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, + start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, } - impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> MoreDefaultsBuilder<'a, 'b, A> { - #[inline] - pub fn add_ints(&mut self, ints: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , i32>>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(MoreDefaults::VT_INTS, ints); - } - - #[inline] - pub fn add_floats(&mut self, floats: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , f32>>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(MoreDefaults::VT_FLOATS, floats); - } - - #[inline] - pub fn add_empty_string(&mut self, empty_string: ::flatbuffers::WIPOffset<&'b str>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(MoreDefaults::VT_EMPTY_STRING, empty_string); - } - - #[inline] - pub fn add_some_string(&mut self, some_string: ::flatbuffers::WIPOffset<&'b str>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(MoreDefaults::VT_SOME_STRING, some_string); - } - - #[inline] - pub fn add_abcs(&mut self, abcs: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , ABC>>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(MoreDefaults::VT_ABCS, abcs); - } - - #[inline] - pub fn add_bools(&mut self, bools: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , bool>>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(MoreDefaults::VT_BOOLS, bools); - } - - #[inline] - pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> MoreDefaultsBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - MoreDefaultsBuilder { - fbb_: _fbb, - start_: start, - } - } - - #[inline] - pub fn finish(self) -> ::flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - ::flatbuffers::WIPOffset::new(o.value()) + #[inline] + pub fn add_ints(&mut self, ints: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , i32>>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(MoreDefaults::VT_INTS, ints); + } + #[inline] + pub fn add_floats(&mut self, floats: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , f32>>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(MoreDefaults::VT_FLOATS, floats); + } + #[inline] + pub fn add_empty_string(&mut self, empty_string: ::flatbuffers::WIPOffset<&'b str>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(MoreDefaults::VT_EMPTY_STRING, empty_string); + } + #[inline] + pub fn add_some_string(&mut self, some_string: ::flatbuffers::WIPOffset<&'b str>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(MoreDefaults::VT_SOME_STRING, some_string); + } + #[inline] + pub fn add_abcs(&mut self, abcs: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , ABC>>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(MoreDefaults::VT_ABCS, abcs); + } + #[inline] + pub fn add_bools(&mut self, bools: ::flatbuffers::WIPOffset<::flatbuffers::Vector<'b , bool>>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(MoreDefaults::VT_BOOLS, bools); + } + #[inline] + pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> MoreDefaultsBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + MoreDefaultsBuilder { + fbb_: _fbb, + start_: start, } + } + #[inline] + pub fn finish(self) -> ::flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + ::flatbuffers::WIPOffset::new(o.value()) + } } impl ::core::fmt::Debug for MoreDefaults<'_> { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - let mut ds = f.debug_struct("MoreDefaults"); - ds.field("ints", &self.ints()); - ds.field("floats", &self.floats()); - ds.field("empty_string", &self.empty_string()); - ds.field("some_string", &self.some_string()); - ds.field("abcs", &self.abcs()); - ds.field("bools", &self.bools()); - ds.finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + let mut ds = f.debug_struct("MoreDefaults"); + ds.field("ints", &self.ints()); + ds.field("floats", &self.floats()); + ds.field("empty_string", &self.empty_string()); + ds.field("some_string", &self.some_string()); + ds.field("abcs", &self.abcs()); + ds.field("bools", &self.bools()); + ds.finish() + } } - #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub struct MoreDefaultsT { - pub ints: alloc::vec::Vec, - pub floats: alloc::vec::Vec, - pub empty_string: alloc::string::String, - pub some_string: alloc::string::String, - pub abcs: alloc::vec::Vec, - pub bools: alloc::vec::Vec, + pub ints: alloc::vec::Vec, + pub floats: alloc::vec::Vec, + pub empty_string: alloc::string::String, + pub some_string: alloc::string::String, + pub abcs: alloc::vec::Vec, + pub bools: alloc::vec::Vec, } - impl Default for MoreDefaultsT { - fn default() -> Self { - Self { - ints: Default::default(), - floats: Default::default(), - empty_string: alloc::string::ToString::to_string(""), - some_string: alloc::string::ToString::to_string("some"), - abcs: Default::default(), - bools: Default::default(), - } + fn default() -> Self { + Self { + ints: Default::default(), + floats: Default::default(), + empty_string: alloc::string::ToString::to_string(""), + some_string: alloc::string::ToString::to_string("some"), + abcs: Default::default(), + bools: Default::default(), } + } } - impl MoreDefaultsT { - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( - &self, - _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> - ) -> ::flatbuffers::WIPOffset> { - let ints = Some({ - let x = &self.ints; - _fbb.create_vector(x) - }); - let floats = Some({ - let x = &self.floats; - _fbb.create_vector(x) - }); - let empty_string = Some({ - let x = &self.empty_string; - _fbb.create_string(x) - }); - let some_string = Some({ - let x = &self.some_string; - _fbb.create_string(x) - }); - let abcs = Some({ - let x = &self.abcs; - _fbb.create_vector(x) - }); - let bools = Some({ - let x = &self.bools; - _fbb.create_vector(x) - }); - MoreDefaults::create(_fbb, &MoreDefaultsArgs{ - ints, - floats, - empty_string, - some_string, - abcs, - bools, - }) - } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> + ) -> ::flatbuffers::WIPOffset> { + let ints = Some({ + let x = &self.ints; + _fbb.create_vector(x) + }); + let floats = Some({ + let x = &self.floats; + _fbb.create_vector(x) + }); + let empty_string = Some({ + let x = &self.empty_string; + _fbb.create_string(x) + }); + let some_string = Some({ + let x = &self.some_string; + _fbb.create_string(x) + }); + let abcs = Some({ + let x = &self.abcs; + _fbb.create_vector(x) + }); + let bools = Some({ + let x = &self.bools; + _fbb.create_vector(x) + }); + MoreDefaults::create(_fbb, &MoreDefaultsArgs{ + ints, + floats, + empty_string, + some_string, + abcs, + bools, + }) + } } diff --git a/tests/namespace_test/mod.rs b/tests/namespace_test/mod.rs index 1a0c58c5d..22c667e8b 100644 --- a/tests/namespace_test/mod.rs +++ b/tests/namespace_test/mod.rs @@ -1,25 +1,25 @@ // Automatically generated by the Flatbuffers compiler. Do not modify. // @generated pub mod namespace_a { + use super::*; + pub mod namespace_b { use super::*; - pub mod namespace_b { - use super::*; - mod union_in_nested_ns_generated; - pub use self::union_in_nested_ns_generated::*; - mod enum_in_nested_ns_generated; - pub use self::enum_in_nested_ns_generated::*; - mod table_in_nested_ns_generated; - pub use self::table_in_nested_ns_generated::*; - mod struct_in_nested_ns_generated; - pub use self::struct_in_nested_ns_generated::*; - } // namespace_b - mod table_in_first_ns_generated; - pub use self::table_in_first_ns_generated::*; - mod second_table_in_a_generated; - pub use self::second_table_in_a_generated::*; + mod union_in_nested_ns_generated; + pub use self::union_in_nested_ns_generated::*; + mod enum_in_nested_ns_generated; + pub use self::enum_in_nested_ns_generated::*; + mod table_in_nested_ns_generated; + pub use self::table_in_nested_ns_generated::*; + mod struct_in_nested_ns_generated; + pub use self::struct_in_nested_ns_generated::*; + } // namespace_b + mod table_in_first_ns_generated; + pub use self::table_in_first_ns_generated::*; + mod second_table_in_a_generated; + pub use self::second_table_in_a_generated::*; } // namespace_a pub mod namespace_c { - use super::*; - mod table_in_c_generated; - pub use self::table_in_c_generated::*; + use super::*; + mod table_in_c_generated; + pub use self::table_in_c_generated::*; } // namespace_c diff --git a/tests/namespace_test/namespace_a/namespace_b/enum_in_nested_ns_generated.rs b/tests/namespace_test/namespace_a/namespace_b/enum_in_nested_ns_generated.rs index e466ac869..51724c62a 100644 --- a/tests/namespace_test/namespace_a/namespace_b/enum_in_nested_ns_generated.rs +++ b/tests/namespace_test/namespace_a/namespace_b/enum_in_nested_ns_generated.rs @@ -2,73 +2,64 @@ // @generated extern crate alloc; use super::*; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] pub const ENUM_MIN_ENUM_IN_NESTED_NS: i8 = 0; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] pub const ENUM_MAX_ENUM_IN_NESTED_NS: i8 = 2; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] #[allow(non_camel_case_types)] pub const ENUM_VALUES_ENUM_IN_NESTED_NS: [EnumInNestedNS; 3] = [ - EnumInNestedNS::A, - EnumInNestedNS::B, - EnumInNestedNS::C, + EnumInNestedNS::A, + EnumInNestedNS::B, + EnumInNestedNS::C, ]; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] #[repr(transparent)] pub struct EnumInNestedNS(pub i8); - #[allow(non_upper_case_globals)] impl EnumInNestedNS { - pub const A: Self = Self(0); - pub const B: Self = Self(1); - pub const C: Self = Self(2); + pub const A: Self = Self(0); + pub const B: Self = Self(1); + pub const C: Self = Self(2); - pub const ENUM_MIN: i8 = 0; - pub const ENUM_MAX: i8 = 2; - pub const ENUM_VALUES: &'static [Self] = &[ - Self::A, - Self::B, - Self::C, - ]; - - /// Returns the variant's name or "" if unknown. - pub fn variant_name(self) -> Option<&'static str> { - match self { - Self::A => Some("A"), - Self::B => Some("B"), - Self::C => Some("C"), - _ => None, - } + pub const ENUM_MIN: i8 = 0; + pub const ENUM_MAX: i8 = 2; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::A, + Self::B, + Self::C, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::A => Some("A"), + Self::B => Some("B"), + Self::C => Some("C"), + _ => None, } + } } - impl ::core::fmt::Debug for EnumInNestedNS { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - if let Some(name) = self.variant_name() { - f.write_str(name) - } else { - f.write_fmt(format_args!("", self.0)) - } + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) } + } } - impl<'a> ::flatbuffers::Follow<'a> for EnumInNestedNS { - type Inner = Self; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; - Self(b) - } + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; + Self(b) + } } impl ::flatbuffers::Push for EnumInNestedNS { type Output = EnumInNestedNS; - #[inline] unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { unsafe { ::flatbuffers::emplace_scalar::(dst, self.0) }; @@ -76,28 +67,26 @@ impl ::flatbuffers::Push for EnumInNestedNS { } impl ::flatbuffers::EndianScalar for EnumInNestedNS { - type Scalar = i8; - - #[inline] - fn to_little_endian(self) -> i8 { - self.0.to_le() - } - - #[inline] - #[allow(clippy::wrong_self_convention)] - fn from_little_endian(v: i8) -> Self { - let b = i8::from_le(v); - Self(b) - } + type Scalar = i8; + #[inline] + fn to_little_endian(self) -> i8 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: i8) -> Self { + let b = i8::from_le(v); + Self(b) + } } impl<'a> ::flatbuffers::Verifiable for EnumInNestedNS { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - i8::run_verifier(v, pos) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + i8::run_verifier(v, pos) + } } impl ::flatbuffers::SimpleToVerifyInSlice for EnumInNestedNS {} diff --git a/tests/namespace_test/namespace_a/namespace_b/struct_in_nested_ns_generated.rs b/tests/namespace_test/namespace_a/namespace_b/struct_in_nested_ns_generated.rs index 79034a6c1..b6b8c3812 100644 --- a/tests/namespace_test/namespace_a/namespace_b/struct_in_nested_ns_generated.rs +++ b/tests/namespace_test/namespace_a/namespace_b/struct_in_nested_ns_generated.rs @@ -2,56 +2,46 @@ // @generated extern crate alloc; use super::*; - // struct StructInNestedNS, aligned to 4 #[repr(transparent)] #[derive(Clone, Copy, PartialEq)] pub struct StructInNestedNS(pub [u8; 8]); - -impl Default for StructInNestedNS { - fn default() -> Self { - Self([0; 8]) - } +impl Default for StructInNestedNS { + fn default() -> Self { + Self([0; 8]) + } } - impl ::core::fmt::Debug for StructInNestedNS { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - f.debug_struct("StructInNestedNS") - .field("a", &self.a()) - .field("b", &self.b()) - .finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + f.debug_struct("StructInNestedNS") + .field("a", &self.a()) + .field("b", &self.b()) + .finish() + } } impl ::flatbuffers::SimpleToVerifyInSlice for StructInNestedNS {} - impl<'a> ::flatbuffers::Follow<'a> for StructInNestedNS { - type Inner = &'a StructInNestedNS; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - unsafe { <&'a StructInNestedNS>::follow(buf, loc) } - } + type Inner = &'a StructInNestedNS; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { <&'a StructInNestedNS>::follow(buf, loc) } + } } - impl<'a> ::flatbuffers::Follow<'a> for &'a StructInNestedNS { - type Inner = &'a StructInNestedNS; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - unsafe { ::flatbuffers::follow_cast_ref::(buf, loc) } - } + type Inner = &'a StructInNestedNS; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { ::flatbuffers::follow_cast_ref::(buf, loc) } + } } - impl<'b> ::flatbuffers::Push for StructInNestedNS { type Output = StructInNestedNS; - #[inline] unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { let src = unsafe { ::core::slice::from_raw_parts(self as *const StructInNestedNS as *const u8, ::size()) }; dst.copy_from_slice(src); } - #[inline] fn alignment() -> ::flatbuffers::PushAlignment { ::flatbuffers::PushAlignment::new(4) @@ -59,115 +49,107 @@ impl<'b> ::flatbuffers::Push for StructInNestedNS { } impl<'a> ::flatbuffers::Verifiable for StructInNestedNS { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.in_buffer::(pos) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.in_buffer::(pos) + } } impl<'a> StructInNestedNS { - #[allow(clippy::too_many_arguments)] - pub fn new( - a: i32, - b: i32, - ) -> Self { - let mut s = Self([0; 8]); - s.set_a(a); - s.set_b(b); - s - } + #[allow(clippy::too_many_arguments)] + pub fn new( + a: i32, + b: i32, + ) -> Self { + let mut s = Self([0; 8]); + s.set_a(a); + s.set_b(b); + s + } - pub const fn get_fully_qualified_name() -> &'static str { - "NamespaceA.NamespaceB.StructInNestedNS" - } + pub const fn get_fully_qualified_name() -> &'static str { + "NamespaceA.NamespaceB.StructInNestedNS" + } - pub fn a(&self) -> i32 { - let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - ::flatbuffers::EndianScalar::from_little_endian(unsafe { - ::core::ptr::copy_nonoverlapping( - self.0[0..].as_ptr(), - mem.as_mut_ptr() as *mut u8, - ::core::mem::size_of::<::Scalar>(), - ); - mem.assume_init() - }) - } + pub fn a(&self) -> i32 { + let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + ::flatbuffers::EndianScalar::from_little_endian(unsafe { + ::core::ptr::copy_nonoverlapping( + self.0[0..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + ::core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } - pub fn set_a(&mut self, x: i32) { - let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - unsafe { - ::core::ptr::copy_nonoverlapping( - &x_le as *const _ as *const u8, - self.0[0..].as_mut_ptr(), - ::core::mem::size_of::<::Scalar>(), - ); - } + pub fn set_a(&mut self, x: i32) { + let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + ::core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[0..].as_mut_ptr(), + ::core::mem::size_of::<::Scalar>(), + ); } + } - pub fn b(&self) -> i32 { - let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - ::flatbuffers::EndianScalar::from_little_endian(unsafe { - ::core::ptr::copy_nonoverlapping( - self.0[4..].as_ptr(), - mem.as_mut_ptr() as *mut u8, - ::core::mem::size_of::<::Scalar>(), - ); - mem.assume_init() - }) - } + pub fn b(&self) -> i32 { + let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + ::flatbuffers::EndianScalar::from_little_endian(unsafe { + ::core::ptr::copy_nonoverlapping( + self.0[4..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + ::core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } - pub fn set_b(&mut self, x: i32) { - let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - unsafe { - ::core::ptr::copy_nonoverlapping( - &x_le as *const _ as *const u8, - self.0[4..].as_mut_ptr(), - ::core::mem::size_of::<::Scalar>(), - ); - } + pub fn set_b(&mut self, x: i32) { + let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + ::core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[4..].as_mut_ptr(), + ::core::mem::size_of::<::Scalar>(), + ); } + } - pub fn unpack(&self) -> StructInNestedNST { - StructInNestedNST { - a: self.a(), - b: self.b(), - } + pub fn unpack(&self) -> StructInNestedNST { + StructInNestedNST { + a: self.a(), + b: self.b(), } + } } -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Default)] pub struct StructInNestedNST { - pub a: i32, - pub b: i32, + pub a: i32, + pub b: i32, } -impl Default for StructInNestedNST { - fn default() -> Self { - Self { - a: 0, - b: 0, - } - } +impl StructInNestedNST { + pub fn pack(&self) -> StructInNestedNS { + StructInNestedNS::new( + self.a, + self.b, + ) + } } -impl StructInNestedNST { - pub fn pack(&self) -> StructInNestedNS { - StructInNestedNS::new( - self.a, - self.b, - ) - } -} diff --git a/tests/namespace_test/namespace_a/namespace_b/table_in_nested_ns_generated.rs b/tests/namespace_test/namespace_a/namespace_b/table_in_nested_ns_generated.rs index f85b0d231..e90a74975 100644 --- a/tests/namespace_test/namespace_a/namespace_b/table_in_nested_ns_generated.rs +++ b/tests/namespace_test/namespace_a/namespace_b/table_in_nested_ns_generated.rs @@ -2,143 +2,132 @@ // @generated extern crate alloc; use super::*; - pub enum TableInNestedNSOffset {} - #[derive(Copy, Clone, PartialEq)] + pub struct TableInNestedNS<'a> { - pub _tab: ::flatbuffers::Table<'a>, + pub _tab: ::flatbuffers::Table<'a>, } impl<'a> ::flatbuffers::Follow<'a> for TableInNestedNS<'a> { - type Inner = TableInNestedNS<'a>; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } - } + type Inner = TableInNestedNS<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } + } } impl<'a> TableInNestedNS<'a> { - pub const VT_FOO: ::flatbuffers::VOffsetT = 4; + pub const VT_FOO: ::flatbuffers::VOffsetT = 4; - pub const fn get_fully_qualified_name() -> &'static str { - "NamespaceA.NamespaceB.TableInNestedNS" - } + pub const fn get_fully_qualified_name() -> &'static str { + "NamespaceA.NamespaceB.TableInNestedNS" + } - #[inline] - pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { - TableInNestedNS { _tab: table } - } + #[inline] + pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { + TableInNestedNS { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args TableInNestedNSArgs + ) -> ::flatbuffers::WIPOffset> { + let mut builder = TableInNestedNSBuilder::new(_fbb); + builder.add_foo(args.foo); + builder.finish() + } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args TableInNestedNSArgs - ) -> ::flatbuffers::WIPOffset> { - let mut builder = TableInNestedNSBuilder::new(_fbb); - builder.add_foo(args.foo); - builder.finish() + pub fn unpack(&self) -> TableInNestedNST { + let foo = self.foo(); + TableInNestedNST { + foo, } + } - pub fn unpack(&self) -> TableInNestedNST { - let foo = self.foo(); - TableInNestedNST { - foo, - } - } - - #[inline] - pub fn foo(&self) -> i32 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(TableInNestedNS::VT_FOO, Some(0)).unwrap()} - } + #[inline] + pub fn foo(&self) -> i32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TableInNestedNS::VT_FOO, Some(0)).unwrap()} + } } impl ::flatbuffers::Verifiable for TableInNestedNS<'_> { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.visit_table(pos)? - .visit_field::("foo", Self::VT_FOO, false)? - .finish(); - Ok(()) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.visit_table(pos)? + .visit_field::("foo", Self::VT_FOO, false)? + .finish(); + Ok(()) + } } - pub struct TableInNestedNSArgs { pub foo: i32, } - impl<'a> Default for TableInNestedNSArgs { - #[inline] - fn default() -> Self { - TableInNestedNSArgs { - foo: 0, - } + #[inline] + fn default() -> Self { + TableInNestedNSArgs { + foo: 0, } + } } pub struct TableInNestedNSBuilder<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> { - fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, + fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, + start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, } - impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> TableInNestedNSBuilder<'a, 'b, A> { - #[inline] - pub fn add_foo(&mut self, foo: i32) { - self.fbb_.push_slot::(TableInNestedNS::VT_FOO, foo, 0); - } - - #[inline] - pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> TableInNestedNSBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - TableInNestedNSBuilder { - fbb_: _fbb, - start_: start, - } - } - - #[inline] - pub fn finish(self) -> ::flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - ::flatbuffers::WIPOffset::new(o.value()) + #[inline] + pub fn add_foo(&mut self, foo: i32) { + self.fbb_.push_slot::(TableInNestedNS::VT_FOO, foo, 0); + } + #[inline] + pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> TableInNestedNSBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + TableInNestedNSBuilder { + fbb_: _fbb, + start_: start, } + } + #[inline] + pub fn finish(self) -> ::flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + ::flatbuffers::WIPOffset::new(o.value()) + } } impl ::core::fmt::Debug for TableInNestedNS<'_> { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - let mut ds = f.debug_struct("TableInNestedNS"); - ds.field("foo", &self.foo()); - ds.finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + let mut ds = f.debug_struct("TableInNestedNS"); + ds.field("foo", &self.foo()); + ds.finish() + } } - #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub struct TableInNestedNST { - pub foo: i32, + pub foo: i32, } - impl Default for TableInNestedNST { - fn default() -> Self { - Self { - foo: 0, - } + fn default() -> Self { + Self { + foo: 0, } + } } - impl TableInNestedNST { - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( - &self, - _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> - ) -> ::flatbuffers::WIPOffset> { - let foo = self.foo; - TableInNestedNS::create(_fbb, &TableInNestedNSArgs{ - foo, - }) - } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> + ) -> ::flatbuffers::WIPOffset> { + let foo = self.foo; + TableInNestedNS::create(_fbb, &TableInNestedNSArgs{ + foo, + }) + } } diff --git a/tests/namespace_test/namespace_a/namespace_b/union_in_nested_ns_generated.rs b/tests/namespace_test/namespace_a/namespace_b/union_in_nested_ns_generated.rs index 0ac41c032..3e636d1e7 100644 --- a/tests/namespace_test/namespace_a/namespace_b/union_in_nested_ns_generated.rs +++ b/tests/namespace_test/namespace_a/namespace_b/union_in_nested_ns_generated.rs @@ -2,69 +2,60 @@ // @generated extern crate alloc; use super::*; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] pub const ENUM_MIN_UNION_IN_NESTED_NS: u8 = 0; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] pub const ENUM_MAX_UNION_IN_NESTED_NS: u8 = 1; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] #[allow(non_camel_case_types)] pub const ENUM_VALUES_UNION_IN_NESTED_NS: [UnionInNestedNS; 2] = [ - UnionInNestedNS::NONE, - UnionInNestedNS::TableInNestedNS, + UnionInNestedNS::NONE, + UnionInNestedNS::TableInNestedNS, ]; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] #[repr(transparent)] pub struct UnionInNestedNS(pub u8); - #[allow(non_upper_case_globals)] impl UnionInNestedNS { - pub const NONE: Self = Self(0); - pub const TableInNestedNS: Self = Self(1); + pub const NONE: Self = Self(0); + pub const TableInNestedNS: Self = Self(1); - pub const ENUM_MIN: u8 = 0; - pub const ENUM_MAX: u8 = 1; - pub const ENUM_VALUES: &'static [Self] = &[ - Self::NONE, - Self::TableInNestedNS, - ]; - - /// Returns the variant's name or "" if unknown. - pub fn variant_name(self) -> Option<&'static str> { - match self { - Self::NONE => Some("NONE"), - Self::TableInNestedNS => Some("TableInNestedNS"), - _ => None, - } + pub const ENUM_MIN: u8 = 0; + pub const ENUM_MAX: u8 = 1; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::NONE, + Self::TableInNestedNS, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::NONE => Some("NONE"), + Self::TableInNestedNS => Some("TableInNestedNS"), + _ => None, } + } } - impl ::core::fmt::Debug for UnionInNestedNS { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - if let Some(name) = self.variant_name() { - f.write_str(name) - } else { - f.write_fmt(format_args!("", self.0)) - } + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) } + } } - impl<'a> ::flatbuffers::Follow<'a> for UnionInNestedNS { - type Inner = Self; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; - Self(b) - } + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; + Self(b) + } } impl ::flatbuffers::Push for UnionInNestedNS { type Output = UnionInNestedNS; - #[inline] unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { unsafe { ::flatbuffers::emplace_scalar::(dst, self.0) }; @@ -72,85 +63,75 @@ impl ::flatbuffers::Push for UnionInNestedNS { } impl ::flatbuffers::EndianScalar for UnionInNestedNS { - type Scalar = u8; - - #[inline] - fn to_little_endian(self) -> u8 { - self.0.to_le() - } - - #[inline] - #[allow(clippy::wrong_self_convention)] - fn from_little_endian(v: u8) -> Self { - let b = u8::from_le(v); - Self(b) - } + type Scalar = u8; + #[inline] + fn to_little_endian(self) -> u8 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: u8) -> Self { + let b = u8::from_le(v); + Self(b) + } } impl<'a> ::flatbuffers::Verifiable for UnionInNestedNS { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - u8::run_verifier(v, pos) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + u8::run_verifier(v, pos) + } } impl ::flatbuffers::SimpleToVerifyInSlice for UnionInNestedNS {} - pub struct UnionInNestedNSUnionTableOffset {} #[allow(clippy::upper_case_acronyms)] #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub enum UnionInNestedNST { - NONE, - TableInNestedNS(alloc::boxed::Box), + NONE, + TableInNestedNS(alloc::boxed::Box), } - impl Default for UnionInNestedNST { - fn default() -> Self { - Self::NONE - } + fn default() -> Self { + Self::NONE + } } - impl UnionInNestedNST { - pub fn union_in_nested_ns_type(&self) -> UnionInNestedNS { - match self { - Self::NONE => UnionInNestedNS::NONE, - Self::TableInNestedNS(_) => UnionInNestedNS::TableInNestedNS, - } + pub fn union_in_nested_ns_type(&self) -> UnionInNestedNS { + match self { + Self::NONE => UnionInNestedNS::NONE, + Self::TableInNestedNS(_) => UnionInNestedNS::TableInNestedNS, } - - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>(&self, fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A>) -> Option<::flatbuffers::WIPOffset<::flatbuffers::UnionWIPOffset>> { - match self { - Self::NONE => None, - Self::TableInNestedNS(v) => Some(v.pack(fbb).as_union_value()), - } + } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>(&self, fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A>) -> Option<::flatbuffers::WIPOffset<::flatbuffers::UnionWIPOffset>> { + match self { + Self::NONE => None, + Self::TableInNestedNS(v) => Some(v.pack(fbb).as_union_value()), } - - /// If the union variant matches, return the owned TableInNestedNST, setting the union to NONE. - pub fn take_table_in_nested_ns(&mut self) -> Option> { - if let Self::TableInNestedNS(_) = self { - let v = ::core::mem::replace(self, Self::NONE); - if let Self::TableInNestedNS(w) = v { - Some(w) - } else { - unreachable!() - } - } else { - None - } - } - - /// If the union variant matches, return a reference to the TableInNestedNST. - pub fn as_table_in_nested_ns(&self) -> Option<&TableInNestedNST> { - if let Self::TableInNestedNS(v) = self { Some(v.as_ref()) } else { None } - } - - /// If the union variant matches, return a mutable reference to the TableInNestedNST. - pub fn as_table_in_nested_ns_mut(&mut self) -> Option<&mut TableInNestedNST> { - if let Self::TableInNestedNS(v) = self { Some(v.as_mut()) } else { None } + } + /// If the union variant matches, return the owned TableInNestedNST, setting the union to NONE. + pub fn take_table_in_nested_ns(&mut self) -> Option> { + if let Self::TableInNestedNS(_) = self { + let v = ::core::mem::replace(self, Self::NONE); + if let Self::TableInNestedNS(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None } + } + /// If the union variant matches, return a reference to the TableInNestedNST. + pub fn as_table_in_nested_ns(&self) -> Option<&TableInNestedNST> { + if let Self::TableInNestedNS(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the TableInNestedNST. + pub fn as_table_in_nested_ns_mut(&mut self) -> Option<&mut TableInNestedNST> { + if let Self::TableInNestedNS(v) = self { Some(v.as_mut()) } else { None } + } } - diff --git a/tests/namespace_test/namespace_a/second_table_in_a_generated.rs b/tests/namespace_test/namespace_a/second_table_in_a_generated.rs index 0c0a754e1..d4a2abf91 100644 --- a/tests/namespace_test/namespace_a/second_table_in_a_generated.rs +++ b/tests/namespace_test/namespace_a/second_table_in_a_generated.rs @@ -2,147 +2,136 @@ // @generated extern crate alloc; use super::*; - pub enum SecondTableInAOffset {} - #[derive(Copy, Clone, PartialEq)] + pub struct SecondTableInA<'a> { - pub _tab: ::flatbuffers::Table<'a>, + pub _tab: ::flatbuffers::Table<'a>, } impl<'a> ::flatbuffers::Follow<'a> for SecondTableInA<'a> { - type Inner = SecondTableInA<'a>; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } - } + type Inner = SecondTableInA<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } + } } impl<'a> SecondTableInA<'a> { - pub const VT_REFER_TO_C: ::flatbuffers::VOffsetT = 4; + pub const VT_REFER_TO_C: ::flatbuffers::VOffsetT = 4; - pub const fn get_fully_qualified_name() -> &'static str { - "NamespaceA.SecondTableInA" - } + pub const fn get_fully_qualified_name() -> &'static str { + "NamespaceA.SecondTableInA" + } - #[inline] - pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { - SecondTableInA { _tab: table } - } + #[inline] + pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { + SecondTableInA { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args SecondTableInAArgs<'args> + ) -> ::flatbuffers::WIPOffset> { + let mut builder = SecondTableInABuilder::new(_fbb); + if let Some(x) = args.refer_to_c { builder.add_refer_to_c(x); } + builder.finish() + } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args SecondTableInAArgs<'args> - ) -> ::flatbuffers::WIPOffset> { - let mut builder = SecondTableInABuilder::new(_fbb); - if let Some(x) = args.refer_to_c { builder.add_refer_to_c(x); } - builder.finish() + pub fn unpack(&self) -> SecondTableInAT { + let refer_to_c = self.refer_to_c().map(|x| { + alloc::boxed::Box::new(x.unpack()) + }); + SecondTableInAT { + refer_to_c, } + } - pub fn unpack(&self) -> SecondTableInAT { - let refer_to_c = self.refer_to_c().map(|x| { - alloc::boxed::Box::new(x.unpack()) - }); - SecondTableInAT { - refer_to_c, - } - } - - #[inline] - pub fn refer_to_c(&self) -> Option> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset>(SecondTableInA::VT_REFER_TO_C, None)} - } + #[inline] + pub fn refer_to_c(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset>(SecondTableInA::VT_REFER_TO_C, None)} + } } impl ::flatbuffers::Verifiable for SecondTableInA<'_> { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.visit_table(pos)? - .visit_field::<::flatbuffers::ForwardsUOffset>("refer_to_c", Self::VT_REFER_TO_C, false)? - .finish(); - Ok(()) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.visit_table(pos)? + .visit_field::<::flatbuffers::ForwardsUOffset>("refer_to_c", Self::VT_REFER_TO_C, false)? + .finish(); + Ok(()) + } } - pub struct SecondTableInAArgs<'a> { pub refer_to_c: Option<::flatbuffers::WIPOffset>>, } - impl<'a> Default for SecondTableInAArgs<'a> { - #[inline] - fn default() -> Self { - SecondTableInAArgs { - refer_to_c: None, - } + #[inline] + fn default() -> Self { + SecondTableInAArgs { + refer_to_c: None, } + } } pub struct SecondTableInABuilder<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> { - fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, + fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, + start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, } - impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> SecondTableInABuilder<'a, 'b, A> { - #[inline] - pub fn add_refer_to_c(&mut self, refer_to_c: ::flatbuffers::WIPOffset>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset>(SecondTableInA::VT_REFER_TO_C, refer_to_c); - } - - #[inline] - pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> SecondTableInABuilder<'a, 'b, A> { - let start = _fbb.start_table(); - SecondTableInABuilder { - fbb_: _fbb, - start_: start, - } - } - - #[inline] - pub fn finish(self) -> ::flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - ::flatbuffers::WIPOffset::new(o.value()) + #[inline] + pub fn add_refer_to_c(&mut self, refer_to_c: ::flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset>(SecondTableInA::VT_REFER_TO_C, refer_to_c); + } + #[inline] + pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> SecondTableInABuilder<'a, 'b, A> { + let start = _fbb.start_table(); + SecondTableInABuilder { + fbb_: _fbb, + start_: start, } + } + #[inline] + pub fn finish(self) -> ::flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + ::flatbuffers::WIPOffset::new(o.value()) + } } impl ::core::fmt::Debug for SecondTableInA<'_> { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - let mut ds = f.debug_struct("SecondTableInA"); - ds.field("refer_to_c", &self.refer_to_c()); - ds.finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + let mut ds = f.debug_struct("SecondTableInA"); + ds.field("refer_to_c", &self.refer_to_c()); + ds.finish() + } } - #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub struct SecondTableInAT { - pub refer_to_c: Option>, + pub refer_to_c: Option>, } - impl Default for SecondTableInAT { - fn default() -> Self { - Self { - refer_to_c: None, - } + fn default() -> Self { + Self { + refer_to_c: None, } + } } - impl SecondTableInAT { - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( - &self, - _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> - ) -> ::flatbuffers::WIPOffset> { - let refer_to_c = self.refer_to_c.as_ref().map(|x|{ - x.pack(_fbb) - }); - SecondTableInA::create(_fbb, &SecondTableInAArgs{ - refer_to_c, - }) - } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> + ) -> ::flatbuffers::WIPOffset> { + let refer_to_c = self.refer_to_c.as_ref().map(|x|{ + x.pack(_fbb) + }); + SecondTableInA::create(_fbb, &SecondTableInAArgs{ + refer_to_c, + }) + } } diff --git a/tests/namespace_test/namespace_a/table_in_first_ns_generated.rs b/tests/namespace_test/namespace_a/table_in_first_ns_generated.rs index 10b14c4af..b3d0cfe1c 100644 --- a/tests/namespace_test/namespace_a/table_in_first_ns_generated.rs +++ b/tests/namespace_test/namespace_a/table_in_first_ns_generated.rs @@ -2,154 +2,146 @@ // @generated extern crate alloc; use super::*; - pub enum TableInFirstNSOffset {} - #[derive(Copy, Clone, PartialEq)] + pub struct TableInFirstNS<'a> { - pub _tab: ::flatbuffers::Table<'a>, + pub _tab: ::flatbuffers::Table<'a>, } impl<'a> ::flatbuffers::Follow<'a> for TableInFirstNS<'a> { - type Inner = TableInFirstNS<'a>; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } - } + type Inner = TableInFirstNS<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } + } } impl<'a> TableInFirstNS<'a> { - pub const VT_FOO_TABLE: ::flatbuffers::VOffsetT = 4; - pub const VT_FOO_ENUM: ::flatbuffers::VOffsetT = 6; - pub const VT_FOO_UNION_TYPE: ::flatbuffers::VOffsetT = 8; - pub const VT_FOO_UNION: ::flatbuffers::VOffsetT = 10; - pub const VT_FOO_STRUCT: ::flatbuffers::VOffsetT = 12; + pub const VT_FOO_TABLE: ::flatbuffers::VOffsetT = 4; + pub const VT_FOO_ENUM: ::flatbuffers::VOffsetT = 6; + pub const VT_FOO_UNION_TYPE: ::flatbuffers::VOffsetT = 8; + pub const VT_FOO_UNION: ::flatbuffers::VOffsetT = 10; + pub const VT_FOO_STRUCT: ::flatbuffers::VOffsetT = 12; - pub const fn get_fully_qualified_name() -> &'static str { - "NamespaceA.TableInFirstNS" - } + pub const fn get_fully_qualified_name() -> &'static str { + "NamespaceA.TableInFirstNS" + } - #[inline] - pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { - TableInFirstNS { _tab: table } - } + #[inline] + pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { + TableInFirstNS { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args TableInFirstNSArgs<'args> + ) -> ::flatbuffers::WIPOffset> { + let mut builder = TableInFirstNSBuilder::new(_fbb); + if let Some(x) = args.foo_struct { builder.add_foo_struct(x); } + if let Some(x) = args.foo_union { builder.add_foo_union(x); } + if let Some(x) = args.foo_table { builder.add_foo_table(x); } + builder.add_foo_union_type(args.foo_union_type); + builder.add_foo_enum(args.foo_enum); + builder.finish() + } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args TableInFirstNSArgs<'args> - ) -> ::flatbuffers::WIPOffset> { - let mut builder = TableInFirstNSBuilder::new(_fbb); - if let Some(x) = args.foo_struct { builder.add_foo_struct(x); } - if let Some(x) = args.foo_union { builder.add_foo_union(x); } - if let Some(x) = args.foo_table { builder.add_foo_table(x); } - builder.add_foo_union_type(args.foo_union_type); - builder.add_foo_enum(args.foo_enum); - builder.finish() + pub fn unpack(&self) -> TableInFirstNST { + let foo_table = self.foo_table().map(|x| { + alloc::boxed::Box::new(x.unpack()) + }); + let foo_enum = self.foo_enum(); + let foo_union = match self.foo_union_type() { + namespace_b::UnionInNestedNS::NONE => namespace_b::UnionInNestedNST::NONE, + namespace_b::UnionInNestedNS::TableInNestedNS => namespace_b::UnionInNestedNST::TableInNestedNS(alloc::boxed::Box::new( + self.foo_union_as_table_in_nested_ns() + .expect("Invalid union table, expected `namespace_b::UnionInNestedNS::TableInNestedNS`.") + .unpack() + )), + _ => namespace_b::UnionInNestedNST::NONE, + }; + let foo_struct = self.foo_struct().map(|x| { + x.unpack() + }); + TableInFirstNST { + foo_table, + foo_enum, + foo_union, + foo_struct, } + } - pub fn unpack(&self) -> TableInFirstNST { - let foo_table = self.foo_table().map(|x| { - alloc::boxed::Box::new(x.unpack()) - }); - let foo_enum = self.foo_enum(); - let foo_union = match self.foo_union_type() { - namespace_b::UnionInNestedNS::NONE => namespace_b::UnionInNestedNST::NONE, - namespace_b::UnionInNestedNS::TableInNestedNS => namespace_b::UnionInNestedNST::TableInNestedNS(alloc::boxed::Box::new( - self.foo_union_as_table_in_nested_ns() - .expect("Invalid union table, expected `namespace_b::UnionInNestedNS::TableInNestedNS`.") - .unpack() - )), - _ => namespace_b::UnionInNestedNST::NONE, - }; - let foo_struct = self.foo_struct().map(|x| { - x.unpack() - }); - TableInFirstNST { - foo_table, - foo_enum, - foo_union, - foo_struct, - } + #[inline] + pub fn foo_table(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset>(TableInFirstNS::VT_FOO_TABLE, None)} + } + #[inline] + pub fn foo_enum(&self) -> namespace_b::EnumInNestedNS { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TableInFirstNS::VT_FOO_ENUM, Some(namespace_b::EnumInNestedNS::A)).unwrap()} + } + #[inline] + pub fn foo_union_type(&self) -> namespace_b::UnionInNestedNS { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TableInFirstNS::VT_FOO_UNION_TYPE, Some(namespace_b::UnionInNestedNS::NONE)).unwrap()} + } + #[inline] + pub fn foo_union(&self) -> Option<::flatbuffers::Table<'a>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Table<'a>>>(TableInFirstNS::VT_FOO_UNION, None)} + } + #[inline] + pub fn foo_struct(&self) -> Option<&'a namespace_b::StructInNestedNS> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TableInFirstNS::VT_FOO_STRUCT, None)} + } + #[inline] + #[allow(non_snake_case)] + pub fn foo_union_as_table_in_nested_ns(&self) -> Option> { + if self.foo_union_type() == namespace_b::UnionInNestedNS::TableInNestedNS { + self.foo_union().map(|t| { + // Safety: + // Created from a valid Table for this object + // Which contains a valid union in this slot + unsafe { namespace_b::TableInNestedNS::init_from_table(t) } + }) + } else { + None } + } - #[inline] - pub fn foo_table(&self) -> Option> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset>(TableInFirstNS::VT_FOO_TABLE, None)} - } - - #[inline] - pub fn foo_enum(&self) -> namespace_b::EnumInNestedNS { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(TableInFirstNS::VT_FOO_ENUM, Some(namespace_b::EnumInNestedNS::A)).unwrap()} - } - - #[inline] - pub fn foo_union_type(&self) -> namespace_b::UnionInNestedNS { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(TableInFirstNS::VT_FOO_UNION_TYPE, Some(namespace_b::UnionInNestedNS::NONE)).unwrap()} - } - - #[inline] - pub fn foo_union(&self) -> Option<::flatbuffers::Table<'a>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Table<'a>>>(TableInFirstNS::VT_FOO_UNION, None)} - } - - #[inline] - pub fn foo_struct(&self) -> Option<&'a namespace_b::StructInNestedNS> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(TableInFirstNS::VT_FOO_STRUCT, None)} - } - - #[inline] - #[allow(non_snake_case)] - pub fn foo_union_as_table_in_nested_ns(&self) -> Option> { - if self.foo_union_type() == namespace_b::UnionInNestedNS::TableInNestedNS { - self.foo_union().map(|t| { - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - unsafe { namespace_b::TableInNestedNS::init_from_table(t) } - }) - } else { - None - } - } } impl ::flatbuffers::Verifiable for TableInFirstNS<'_> { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.visit_table(pos)? - .visit_field::<::flatbuffers::ForwardsUOffset>("foo_table", Self::VT_FOO_TABLE, false)? - .visit_field::("foo_enum", Self::VT_FOO_ENUM, false)? - .visit_union::("foo_union_type", Self::VT_FOO_UNION_TYPE, "foo_union", Self::VT_FOO_UNION, false, |key, v, pos| { - match key { - namespace_b::UnionInNestedNS::TableInNestedNS => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("namespace_b::UnionInNestedNS::TableInNestedNS", pos), - _ => Ok(()), - } - })? - .visit_field::("foo_struct", Self::VT_FOO_STRUCT, false)? - .finish(); - Ok(()) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.visit_table(pos)? + .visit_field::<::flatbuffers::ForwardsUOffset>("foo_table", Self::VT_FOO_TABLE, false)? + .visit_field::("foo_enum", Self::VT_FOO_ENUM, false)? + .visit_union::("foo_union_type", Self::VT_FOO_UNION_TYPE, "foo_union", Self::VT_FOO_UNION, false, |key, v, pos| { + match key { + namespace_b::UnionInNestedNS::TableInNestedNS => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("namespace_b::UnionInNestedNS::TableInNestedNS", pos), + _ => Ok(()), + } + })? + .visit_field::("foo_struct", Self::VT_FOO_STRUCT, false)? + .finish(); + Ok(()) + } } - pub struct TableInFirstNSArgs<'a> { pub foo_table: Option<::flatbuffers::WIPOffset>>, pub foo_enum: namespace_b::EnumInNestedNS, @@ -157,130 +149,119 @@ pub struct TableInFirstNSArgs<'a> { pub foo_union: Option<::flatbuffers::WIPOffset<::flatbuffers::UnionWIPOffset>>, pub foo_struct: Option<&'a namespace_b::StructInNestedNS>, } - impl<'a> Default for TableInFirstNSArgs<'a> { - #[inline] - fn default() -> Self { - TableInFirstNSArgs { - foo_table: None, - foo_enum: namespace_b::EnumInNestedNS::A, - foo_union_type: namespace_b::UnionInNestedNS::NONE, - foo_union: None, - foo_struct: None, - } + #[inline] + fn default() -> Self { + TableInFirstNSArgs { + foo_table: None, + foo_enum: namespace_b::EnumInNestedNS::A, + foo_union_type: namespace_b::UnionInNestedNS::NONE, + foo_union: None, + foo_struct: None, } + } } pub struct TableInFirstNSBuilder<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> { - fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, + fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, + start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, } - impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> TableInFirstNSBuilder<'a, 'b, A> { - #[inline] - pub fn add_foo_table(&mut self, foo_table: ::flatbuffers::WIPOffset>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset>(TableInFirstNS::VT_FOO_TABLE, foo_table); - } - - #[inline] - pub fn add_foo_enum(&mut self, foo_enum: namespace_b::EnumInNestedNS) { - self.fbb_.push_slot::(TableInFirstNS::VT_FOO_ENUM, foo_enum, namespace_b::EnumInNestedNS::A); - } - - #[inline] - pub fn add_foo_union_type(&mut self, foo_union_type: namespace_b::UnionInNestedNS) { - self.fbb_.push_slot::(TableInFirstNS::VT_FOO_UNION_TYPE, foo_union_type, namespace_b::UnionInNestedNS::NONE); - } - - #[inline] - pub fn add_foo_union(&mut self, foo_union: ::flatbuffers::WIPOffset<::flatbuffers::UnionWIPOffset>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(TableInFirstNS::VT_FOO_UNION, foo_union); - } - - #[inline] - pub fn add_foo_struct(&mut self, foo_struct: &namespace_b::StructInNestedNS) { - self.fbb_.push_slot_always::<&namespace_b::StructInNestedNS>(TableInFirstNS::VT_FOO_STRUCT, foo_struct); - } - - #[inline] - pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> TableInFirstNSBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - TableInFirstNSBuilder { - fbb_: _fbb, - start_: start, - } - } - - #[inline] - pub fn finish(self) -> ::flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - ::flatbuffers::WIPOffset::new(o.value()) + #[inline] + pub fn add_foo_table(&mut self, foo_table: ::flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset>(TableInFirstNS::VT_FOO_TABLE, foo_table); + } + #[inline] + pub fn add_foo_enum(&mut self, foo_enum: namespace_b::EnumInNestedNS) { + self.fbb_.push_slot::(TableInFirstNS::VT_FOO_ENUM, foo_enum, namespace_b::EnumInNestedNS::A); + } + #[inline] + pub fn add_foo_union_type(&mut self, foo_union_type: namespace_b::UnionInNestedNS) { + self.fbb_.push_slot::(TableInFirstNS::VT_FOO_UNION_TYPE, foo_union_type, namespace_b::UnionInNestedNS::NONE); + } + #[inline] + pub fn add_foo_union(&mut self, foo_union: ::flatbuffers::WIPOffset<::flatbuffers::UnionWIPOffset>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(TableInFirstNS::VT_FOO_UNION, foo_union); + } + #[inline] + pub fn add_foo_struct(&mut self, foo_struct: &namespace_b::StructInNestedNS) { + self.fbb_.push_slot_always::<&namespace_b::StructInNestedNS>(TableInFirstNS::VT_FOO_STRUCT, foo_struct); + } + #[inline] + pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> TableInFirstNSBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + TableInFirstNSBuilder { + fbb_: _fbb, + start_: start, } + } + #[inline] + pub fn finish(self) -> ::flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + ::flatbuffers::WIPOffset::new(o.value()) + } } impl ::core::fmt::Debug for TableInFirstNS<'_> { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - let mut ds = f.debug_struct("TableInFirstNS"); - ds.field("foo_table", &self.foo_table()); - ds.field("foo_enum", &self.foo_enum()); - ds.field("foo_union_type", &self.foo_union_type()); - match self.foo_union_type() { - namespace_b::UnionInNestedNS::TableInNestedNS => { - if let Some(x) = self.foo_union_as_table_in_nested_ns() { - ds.field("foo_union", &x) - } else { - ds.field("foo_union", &"InvalidFlatbuffer: Union discriminant does not match value.") - } - }, - _ => { - let x: Option<()> = None; - ds.field("foo_union", &x) - }, - }; - ds.field("foo_struct", &self.foo_struct()); - ds.finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + let mut ds = f.debug_struct("TableInFirstNS"); + ds.field("foo_table", &self.foo_table()); + ds.field("foo_enum", &self.foo_enum()); + ds.field("foo_union_type", &self.foo_union_type()); + match self.foo_union_type() { + namespace_b::UnionInNestedNS::TableInNestedNS => { + if let Some(x) = self.foo_union_as_table_in_nested_ns() { + ds.field("foo_union", &x) + } else { + ds.field("foo_union", &"InvalidFlatbuffer: Union discriminant does not match value.") + } + }, + _ => { + let x: Option<()> = None; + ds.field("foo_union", &x) + }, + }; + ds.field("foo_struct", &self.foo_struct()); + ds.finish() + } } - #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub struct TableInFirstNST { - pub foo_table: Option>, - pub foo_enum: namespace_b::EnumInNestedNS, - pub foo_union: namespace_b::UnionInNestedNST, - pub foo_struct: Option, + pub foo_table: Option>, + pub foo_enum: namespace_b::EnumInNestedNS, + pub foo_union: namespace_b::UnionInNestedNST, + pub foo_struct: Option, } - impl Default for TableInFirstNST { - fn default() -> Self { - Self { - foo_table: None, - foo_enum: namespace_b::EnumInNestedNS::A, - foo_union: namespace_b::UnionInNestedNST::NONE, - foo_struct: None, - } + fn default() -> Self { + Self { + foo_table: None, + foo_enum: namespace_b::EnumInNestedNS::A, + foo_union: namespace_b::UnionInNestedNST::NONE, + foo_struct: None, } + } } - impl TableInFirstNST { - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( - &self, - _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> - ) -> ::flatbuffers::WIPOffset> { - let foo_table = self.foo_table.as_ref().map(|x|{ - x.pack(_fbb) - }); - let foo_enum = self.foo_enum; - let foo_union_type = self.foo_union.union_in_nested_ns_type(); - let foo_union = self.foo_union.pack(_fbb); - let foo_struct_tmp = self.foo_struct.as_ref().map(|x| x.pack()); - let foo_struct = foo_struct_tmp.as_ref(); - TableInFirstNS::create(_fbb, &TableInFirstNSArgs{ - foo_table, - foo_enum, - foo_union_type, - foo_union, - foo_struct, - }) - } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> + ) -> ::flatbuffers::WIPOffset> { + let foo_table = self.foo_table.as_ref().map(|x|{ + x.pack(_fbb) + }); + let foo_enum = self.foo_enum; + let foo_union_type = self.foo_union.union_in_nested_ns_type(); + let foo_union = self.foo_union.pack(_fbb); + let foo_struct_tmp = self.foo_struct.as_ref().map(|x| x.pack()); + let foo_struct = foo_struct_tmp.as_ref(); + TableInFirstNS::create(_fbb, &TableInFirstNSArgs{ + foo_table, + foo_enum, + foo_union_type, + foo_union, + foo_struct, + }) + } } diff --git a/tests/namespace_test/namespace_c/table_in_c_generated.rs b/tests/namespace_test/namespace_c/table_in_c_generated.rs index 99886869c..f1e2e6697 100644 --- a/tests/namespace_test/namespace_c/table_in_c_generated.rs +++ b/tests/namespace_test/namespace_c/table_in_c_generated.rs @@ -2,176 +2,163 @@ // @generated extern crate alloc; use super::*; - pub enum TableInCOffset {} - #[derive(Copy, Clone, PartialEq)] + pub struct TableInC<'a> { - pub _tab: ::flatbuffers::Table<'a>, + pub _tab: ::flatbuffers::Table<'a>, } impl<'a> ::flatbuffers::Follow<'a> for TableInC<'a> { - type Inner = TableInC<'a>; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } - } + type Inner = TableInC<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } + } } impl<'a> TableInC<'a> { - pub const VT_REFER_TO_A1: ::flatbuffers::VOffsetT = 4; - pub const VT_REFER_TO_A2: ::flatbuffers::VOffsetT = 6; + pub const VT_REFER_TO_A1: ::flatbuffers::VOffsetT = 4; + pub const VT_REFER_TO_A2: ::flatbuffers::VOffsetT = 6; - pub const fn get_fully_qualified_name() -> &'static str { - "NamespaceC.TableInC" - } + pub const fn get_fully_qualified_name() -> &'static str { + "NamespaceC.TableInC" + } - #[inline] - pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { - TableInC { _tab: table } - } + #[inline] + pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { + TableInC { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args TableInCArgs<'args> + ) -> ::flatbuffers::WIPOffset> { + let mut builder = TableInCBuilder::new(_fbb); + if let Some(x) = args.refer_to_a2 { builder.add_refer_to_a2(x); } + if let Some(x) = args.refer_to_a1 { builder.add_refer_to_a1(x); } + builder.finish() + } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args TableInCArgs<'args> - ) -> ::flatbuffers::WIPOffset> { - let mut builder = TableInCBuilder::new(_fbb); - if let Some(x) = args.refer_to_a2 { builder.add_refer_to_a2(x); } - if let Some(x) = args.refer_to_a1 { builder.add_refer_to_a1(x); } - builder.finish() + pub fn unpack(&self) -> TableInCT { + let refer_to_a1 = self.refer_to_a1().map(|x| { + alloc::boxed::Box::new(x.unpack()) + }); + let refer_to_a2 = self.refer_to_a2().map(|x| { + alloc::boxed::Box::new(x.unpack()) + }); + TableInCT { + refer_to_a1, + refer_to_a2, } + } - pub fn unpack(&self) -> TableInCT { - let refer_to_a1 = self.refer_to_a1().map(|x| { - alloc::boxed::Box::new(x.unpack()) - }); - let refer_to_a2 = self.refer_to_a2().map(|x| { - alloc::boxed::Box::new(x.unpack()) - }); - TableInCT { - refer_to_a1, - refer_to_a2, - } - } - - #[inline] - pub fn refer_to_a1(&self) -> Option> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset>(TableInC::VT_REFER_TO_A1, None)} - } - - #[inline] - pub fn refer_to_a2(&self) -> Option> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset>(TableInC::VT_REFER_TO_A2, None)} - } + #[inline] + pub fn refer_to_a1(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset>(TableInC::VT_REFER_TO_A1, None)} + } + #[inline] + pub fn refer_to_a2(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset>(TableInC::VT_REFER_TO_A2, None)} + } } impl ::flatbuffers::Verifiable for TableInC<'_> { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.visit_table(pos)? - .visit_field::<::flatbuffers::ForwardsUOffset>("refer_to_a1", Self::VT_REFER_TO_A1, false)? - .visit_field::<::flatbuffers::ForwardsUOffset>("refer_to_a2", Self::VT_REFER_TO_A2, false)? - .finish(); - Ok(()) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.visit_table(pos)? + .visit_field::<::flatbuffers::ForwardsUOffset>("refer_to_a1", Self::VT_REFER_TO_A1, false)? + .visit_field::<::flatbuffers::ForwardsUOffset>("refer_to_a2", Self::VT_REFER_TO_A2, false)? + .finish(); + Ok(()) + } } - pub struct TableInCArgs<'a> { pub refer_to_a1: Option<::flatbuffers::WIPOffset>>, pub refer_to_a2: Option<::flatbuffers::WIPOffset>>, } - impl<'a> Default for TableInCArgs<'a> { - #[inline] - fn default() -> Self { - TableInCArgs { - refer_to_a1: None, - refer_to_a2: None, - } + #[inline] + fn default() -> Self { + TableInCArgs { + refer_to_a1: None, + refer_to_a2: None, } + } } pub struct TableInCBuilder<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> { - fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, + fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, + start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, } - impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> TableInCBuilder<'a, 'b, A> { - #[inline] - pub fn add_refer_to_a1(&mut self, refer_to_a1: ::flatbuffers::WIPOffset>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset>(TableInC::VT_REFER_TO_A1, refer_to_a1); - } - - #[inline] - pub fn add_refer_to_a2(&mut self, refer_to_a2: ::flatbuffers::WIPOffset>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset>(TableInC::VT_REFER_TO_A2, refer_to_a2); - } - - #[inline] - pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> TableInCBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - TableInCBuilder { - fbb_: _fbb, - start_: start, - } - } - - #[inline] - pub fn finish(self) -> ::flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - ::flatbuffers::WIPOffset::new(o.value()) + #[inline] + pub fn add_refer_to_a1(&mut self, refer_to_a1: ::flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset>(TableInC::VT_REFER_TO_A1, refer_to_a1); + } + #[inline] + pub fn add_refer_to_a2(&mut self, refer_to_a2: ::flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset>(TableInC::VT_REFER_TO_A2, refer_to_a2); + } + #[inline] + pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> TableInCBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + TableInCBuilder { + fbb_: _fbb, + start_: start, } + } + #[inline] + pub fn finish(self) -> ::flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + ::flatbuffers::WIPOffset::new(o.value()) + } } impl ::core::fmt::Debug for TableInC<'_> { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - let mut ds = f.debug_struct("TableInC"); - ds.field("refer_to_a1", &self.refer_to_a1()); - ds.field("refer_to_a2", &self.refer_to_a2()); - ds.finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + let mut ds = f.debug_struct("TableInC"); + ds.field("refer_to_a1", &self.refer_to_a1()); + ds.field("refer_to_a2", &self.refer_to_a2()); + ds.finish() + } } - #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub struct TableInCT { - pub refer_to_a1: Option>, - pub refer_to_a2: Option>, + pub refer_to_a1: Option>, + pub refer_to_a2: Option>, } - impl Default for TableInCT { - fn default() -> Self { - Self { - refer_to_a1: None, - refer_to_a2: None, - } + fn default() -> Self { + Self { + refer_to_a1: None, + refer_to_a2: None, } + } } - impl TableInCT { - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( - &self, - _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> - ) -> ::flatbuffers::WIPOffset> { - let refer_to_a1 = self.refer_to_a1.as_ref().map(|x|{ - x.pack(_fbb) - }); - let refer_to_a2 = self.refer_to_a2.as_ref().map(|x|{ - x.pack(_fbb) - }); - TableInC::create(_fbb, &TableInCArgs{ - refer_to_a1, - refer_to_a2, - }) - } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> + ) -> ::flatbuffers::WIPOffset> { + let refer_to_a1 = self.refer_to_a1.as_ref().map(|x|{ + x.pack(_fbb) + }); + let refer_to_a2 = self.refer_to_a2.as_ref().map(|x|{ + x.pack(_fbb) + }); + TableInC::create(_fbb, &TableInCArgs{ + refer_to_a1, + refer_to_a2, + }) + } } diff --git a/tests/namespace_test/namespace_test2_generated.h b/tests/namespace_test/namespace_test2_generated.h index 9c7dd1f85..416c9ffbc 100644 --- a/tests/namespace_test/namespace_test2_generated.h +++ b/tests/namespace_test/namespace_test2_generated.h @@ -419,7 +419,7 @@ inline ::flatbuffers::Offset TableInFirstNS::Pack(::flatbuffers: (void)_rehasher; (void)_o; struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const TableInFirstNST* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; - auto _foo_table = _o->foo_table ? NamespaceA::NamespaceB::CreateTableInNestedNS(_fbb, _o->foo_table.get(), _rehasher) : 0; + auto _foo_table = _o->foo_table ? CreateTableInNestedNS(_fbb, _o->foo_table.get(), _rehasher) : 0; auto _foo_enum = _o->foo_enum; auto _foo_union_type = _o->foo_union.type; auto _foo_union = _o->foo_union.Pack(_fbb); @@ -481,8 +481,8 @@ inline ::flatbuffers::Offset TableInC::Pack(::flatbuffers::FlatBufferB (void)_rehasher; (void)_o; struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const TableInCT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; - auto _refer_to_a1 = _o->refer_to_a1 ? NamespaceA::CreateTableInFirstNS(_fbb, _o->refer_to_a1.get(), _rehasher) : 0; - auto _refer_to_a2 = _o->refer_to_a2 ? NamespaceA::CreateSecondTableInA(_fbb, _o->refer_to_a2.get(), _rehasher) : 0; + auto _refer_to_a1 = _o->refer_to_a1 ? CreateTableInFirstNS(_fbb, _o->refer_to_a1.get(), _rehasher) : 0; + auto _refer_to_a2 = _o->refer_to_a2 ? CreateSecondTableInA(_fbb, _o->refer_to_a2.get(), _rehasher) : 0; return NamespaceC::CreateTableInC( _fbb, _refer_to_a1, @@ -533,7 +533,7 @@ inline ::flatbuffers::Offset SecondTableInA::Pack(::flatbuffers: (void)_rehasher; (void)_o; struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const SecondTableInAT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; - auto _refer_to_c = _o->refer_to_c ? NamespaceC::CreateTableInC(_fbb, _o->refer_to_c.get(), _rehasher) : 0; + auto _refer_to_c = _o->refer_to_c ? CreateTableInC(_fbb, _o->refer_to_c.get(), _rehasher) : 0; return NamespaceA::CreateSecondTableInA( _fbb, _refer_to_c); diff --git a/tests/native_type_test_generated.h b/tests/native_type_test_generated.h index d7ea8093b..c610af251 100644 --- a/tests/native_type_test_generated.h +++ b/tests/native_type_test_generated.h @@ -31,14 +31,6 @@ struct ApplicationDataT; bool operator==(const ApplicationDataT &lhs, const ApplicationDataT &rhs); bool operator!=(const ApplicationDataT &lhs, const ApplicationDataT &rhs); -inline const ::flatbuffers::TypeTable *Vector3DTypeTable(); - -inline const ::flatbuffers::TypeTable *Vector3DAltTypeTable(); - -inline const ::flatbuffers::TypeTable *MatrixTypeTable(); - -inline const ::flatbuffers::TypeTable *ApplicationDataTypeTable(); - FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) Vector3D FLATBUFFERS_FINAL_CLASS { private: float x_; @@ -46,9 +38,7 @@ FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) Vector3D FLATBUFFERS_FINAL_CLASS { float z_; public: - static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { - return Vector3DTypeTable(); - } + struct Traits; Vector3D() : x_(0), y_(0), @@ -62,24 +52,19 @@ FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) Vector3D FLATBUFFERS_FINAL_CLASS { float x() const { return ::flatbuffers::EndianScalar(x_); } - void mutate_x(float _x) { - ::flatbuffers::WriteScalar(&x_, _x); - } float y() const { return ::flatbuffers::EndianScalar(y_); } - void mutate_y(float _y) { - ::flatbuffers::WriteScalar(&y_, _y); - } float z() const { return ::flatbuffers::EndianScalar(z_); } - void mutate_z(float _z) { - ::flatbuffers::WriteScalar(&z_, _z); - } }; FLATBUFFERS_STRUCT_END(Vector3D, 12); +struct Vector3D::Traits { + using type = Vector3D; +}; + FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) Vector3DAlt FLATBUFFERS_FINAL_CLASS { private: float a_; @@ -87,9 +72,7 @@ FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) Vector3DAlt FLATBUFFERS_FINAL_CLASS { float c_; public: - static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { - return Vector3DAltTypeTable(); - } + struct Traits; Vector3DAlt() : a_(0), b_(0), @@ -103,30 +86,23 @@ FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) Vector3DAlt FLATBUFFERS_FINAL_CLASS { float a() const { return ::flatbuffers::EndianScalar(a_); } - void mutate_a(float _a) { - ::flatbuffers::WriteScalar(&a_, _a); - } float b() const { return ::flatbuffers::EndianScalar(b_); } - void mutate_b(float _b) { - ::flatbuffers::WriteScalar(&b_, _b); - } float c() const { return ::flatbuffers::EndianScalar(c_); } - void mutate_c(float _c) { - ::flatbuffers::WriteScalar(&c_, _c); - } }; FLATBUFFERS_STRUCT_END(Vector3DAlt, 12); +struct Vector3DAlt::Traits { + using type = Vector3DAlt; +}; + struct Matrix FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { typedef Native::Matrix NativeTableType; typedef MatrixBuilder Builder; - static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { - return MatrixTypeTable(); - } + struct Traits; enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { VT_ROWS = 4, VT_COLUMNS = 6, @@ -135,21 +111,12 @@ struct Matrix FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { int32_t rows() const { return GetField(VT_ROWS, 0); } - bool mutate_rows(int32_t _rows = 0) { - return SetField(VT_ROWS, _rows, 0); - } int32_t columns() const { return GetField(VT_COLUMNS, 0); } - bool mutate_columns(int32_t _columns = 0) { - return SetField(VT_COLUMNS, _columns, 0); - } const ::flatbuffers::Vector *values() const { return GetPointer *>(VT_VALUES); } - ::flatbuffers::Vector *mutable_values() { - return GetPointer<::flatbuffers::Vector *>(VT_VALUES); - } template bool Verify(::flatbuffers::VerifierTemplate &verifier) const { return VerifyTableStart(verifier) && @@ -200,6 +167,11 @@ inline ::flatbuffers::Offset CreateMatrix( return builder_.Finish(); } +struct Matrix::Traits { + using type = Matrix; + static auto constexpr Create = CreateMatrix; +}; + inline ::flatbuffers::Offset CreateMatrixDirect( ::flatbuffers::FlatBufferBuilder &_fbb, int32_t rows = 0, @@ -232,9 +204,7 @@ struct ApplicationDataT : public ::flatbuffers::NativeTable { struct ApplicationData FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { typedef ApplicationDataT NativeTableType; typedef ApplicationDataBuilder Builder; - static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { - return ApplicationDataTypeTable(); - } + struct Traits; enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { VT_VECTORS = 4, VT_VECTORS_ALT = 6, @@ -246,39 +216,21 @@ struct ApplicationData FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { const ::flatbuffers::Vector *vectors() const { return GetPointer *>(VT_VECTORS); } - ::flatbuffers::Vector *mutable_vectors() { - return GetPointer<::flatbuffers::Vector *>(VT_VECTORS); - } const ::flatbuffers::Vector *vectors_alt() const { return GetPointer *>(VT_VECTORS_ALT); } - ::flatbuffers::Vector *mutable_vectors_alt() { - return GetPointer<::flatbuffers::Vector *>(VT_VECTORS_ALT); - } const Geometry::Vector3D *position() const { return GetStruct(VT_POSITION); } - Geometry::Vector3D *mutable_position() { - return GetStruct(VT_POSITION); - } const Geometry::Vector3D *position_inline() const { return GetStruct(VT_POSITION_INLINE); } - Geometry::Vector3D *mutable_position_inline() { - return GetStruct(VT_POSITION_INLINE); - } const Geometry::Matrix *matrix() const { return GetPointer(VT_MATRIX); } - Geometry::Matrix *mutable_matrix() { - return GetPointer(VT_MATRIX); - } const ::flatbuffers::Vector<::flatbuffers::Offset> *matrices() const { return GetPointer> *>(VT_MATRICES); } - ::flatbuffers::Vector<::flatbuffers::Offset> *mutable_matrices() { - return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset> *>(VT_MATRICES); - } template bool Verify(::flatbuffers::VerifierTemplate &verifier) const { return VerifyTableStart(verifier) && @@ -351,6 +303,11 @@ inline ::flatbuffers::Offset CreateApplicationData( return builder_.Finish(); } +struct ApplicationData::Traits { + using type = ApplicationData; + static auto constexpr Create = CreateApplicationData; +}; + inline ::flatbuffers::Offset CreateApplicationDataDirect( ::flatbuffers::FlatBufferBuilder &_fbb, const std::vector *vectors = nullptr, @@ -375,7 +332,7 @@ inline ::flatbuffers::Offset CreateApplicationDataDirect( ::flatbuffers::Offset CreateApplicationData(::flatbuffers::FlatBufferBuilder &_fbb, const ApplicationDataT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); inline Native::Matrix *Matrix::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { - auto _o = std::unique_ptr(new Native::Matrix()); + auto _o = std::make_unique(); UnPackTo(_o.get(), _resolver); return _o.release(); } @@ -421,7 +378,7 @@ inline ApplicationDataT &ApplicationDataT::operator=(ApplicationDataT o) FLATBUF } inline ApplicationDataT *ApplicationData::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { - auto _o = std::unique_ptr(new ApplicationDataT()); + auto _o = std::make_unique(); UnPackTo(_o.get(), _resolver); return _o.release(); } @@ -449,8 +406,8 @@ inline ::flatbuffers::Offset ApplicationData::Pack(::flatbuffer auto _vectors_alt = _o->vectors_alt.size() ? _fbb.CreateVectorOfNativeStructs(_o->vectors_alt, ::flatbuffers::PackVector3DAlt) : 0; auto _position = Geometry::Vector3D{}; if (_o->position) _position = ::flatbuffers::Pack(*_o->position); auto _position_inline = ::flatbuffers::Pack(_o->position_inline); - auto _matrix = _o->matrix ? Geometry::CreateMatrix(_fbb, _o->matrix.get(), _rehasher) : 0; - auto _matrices = _o->matrices.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->matrices.size(), [](size_t i, _VectorArgs *__va) { return Geometry::CreateMatrix(*__va->__fbb, __va->__o->matrices[i].get(), __va->__rehasher); }, &_va ) : 0; + auto _matrix = _o->matrix ? CreateMatrix(_fbb, _o->matrix.get(), _rehasher) : 0; + auto _matrices = _o->matrices.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->matrices.size(), [](size_t i, _VectorArgs *__va) { return CreateMatrix(*__va->__fbb, __va->__o->matrices[i].get(), __va->__rehasher); }, &_va ) : 0; return Geometry::CreateApplicationData( _fbb, _vectors, @@ -461,87 +418,6 @@ inline ::flatbuffers::Offset ApplicationData::Pack(::flatbuffer _matrices); } -inline const ::flatbuffers::TypeTable *Vector3DTypeTable() { - static const ::flatbuffers::TypeCode type_codes[] = { - { ::flatbuffers::ET_FLOAT, 0, -1 }, - { ::flatbuffers::ET_FLOAT, 0, -1 }, - { ::flatbuffers::ET_FLOAT, 0, -1 } - }; - static const int64_t values[] = { 0, 4, 8, 12 }; - static const char * const names[] = { - "x", - "y", - "z" - }; - static const ::flatbuffers::TypeTable tt = { - ::flatbuffers::ST_STRUCT, 3, type_codes, nullptr, nullptr, values, names - }; - return &tt; -} - -inline const ::flatbuffers::TypeTable *Vector3DAltTypeTable() { - static const ::flatbuffers::TypeCode type_codes[] = { - { ::flatbuffers::ET_FLOAT, 0, -1 }, - { ::flatbuffers::ET_FLOAT, 0, -1 }, - { ::flatbuffers::ET_FLOAT, 0, -1 } - }; - static const int64_t values[] = { 0, 4, 8, 12 }; - static const char * const names[] = { - "a", - "b", - "c" - }; - static const ::flatbuffers::TypeTable tt = { - ::flatbuffers::ST_STRUCT, 3, type_codes, nullptr, nullptr, values, names - }; - return &tt; -} - -inline const ::flatbuffers::TypeTable *MatrixTypeTable() { - static const ::flatbuffers::TypeCode type_codes[] = { - { ::flatbuffers::ET_INT, 0, -1 }, - { ::flatbuffers::ET_INT, 0, -1 }, - { ::flatbuffers::ET_FLOAT, 1, -1 } - }; - static const char * const names[] = { - "rows", - "columns", - "values" - }; - static const ::flatbuffers::TypeTable tt = { - ::flatbuffers::ST_TABLE, 3, type_codes, nullptr, nullptr, nullptr, names - }; - return &tt; -} - -inline const ::flatbuffers::TypeTable *ApplicationDataTypeTable() { - static const ::flatbuffers::TypeCode type_codes[] = { - { ::flatbuffers::ET_SEQUENCE, 1, 0 }, - { ::flatbuffers::ET_SEQUENCE, 1, 1 }, - { ::flatbuffers::ET_SEQUENCE, 0, 0 }, - { ::flatbuffers::ET_SEQUENCE, 0, 0 }, - { ::flatbuffers::ET_SEQUENCE, 0, 2 }, - { ::flatbuffers::ET_SEQUENCE, 1, 2 } - }; - static const ::flatbuffers::TypeFunction type_refs[] = { - Geometry::Vector3DTypeTable, - Geometry::Vector3DAltTypeTable, - Geometry::MatrixTypeTable - }; - static const char * const names[] = { - "vectors", - "vectors_alt", - "position", - "position_inline", - "matrix", - "matrices" - }; - static const ::flatbuffers::TypeTable tt = { - ::flatbuffers::ST_TABLE, 6, type_codes, type_refs, nullptr, nullptr, names - }; - return &tt; -} - inline const Geometry::ApplicationData *GetApplicationData(const void *buf) { return ::flatbuffers::GetRoot(buf); } @@ -550,14 +426,6 @@ inline const Geometry::ApplicationData *GetSizePrefixedApplicationData(const voi return ::flatbuffers::GetSizePrefixedRoot(buf); } -inline ApplicationData *GetMutableApplicationData(void *buf) { - return ::flatbuffers::GetMutableRoot(buf); -} - -inline Geometry::ApplicationData *GetMutableSizePrefixedApplicationData(void *buf) { - return ::flatbuffers::GetMutableSizePrefixedRoot(buf); -} - template inline bool VerifyApplicationDataBuffer( ::flatbuffers::VerifierTemplate &verifier) { @@ -570,6 +438,10 @@ inline bool VerifySizePrefixedApplicationDataBuffer( return verifier.template VerifySizePrefixedBuffer(nullptr); } +inline const char *ApplicationDataExtension() { + return "bfbs"; +} + inline void FinishApplicationDataBuffer( ::flatbuffers::FlatBufferBuilder &fbb, ::flatbuffers::Offset root) { diff --git a/tests/native_type_test_impl.h b/tests/native_type_test_impl.h index 88781f9fe..6a5a7b339 100644 --- a/tests/native_type_test_impl.h +++ b/tests/native_type_test_impl.h @@ -43,6 +43,7 @@ struct Matrix { (values == other.values); } }; + } // namespace Native namespace Geometry { diff --git a/tests/optional_scalars/mod.rs b/tests/optional_scalars/mod.rs index cbd72e360..84291e3ef 100644 --- a/tests/optional_scalars/mod.rs +++ b/tests/optional_scalars/mod.rs @@ -1,9 +1,9 @@ // Automatically generated by the Flatbuffers compiler. Do not modify. // @generated pub mod optional_scalars { - use super::*; - mod optional_byte_generated; - pub use self::optional_byte_generated::*; - mod scalar_stuff_generated; - pub use self::scalar_stuff_generated::*; + use super::*; + mod optional_byte_generated; + pub use self::optional_byte_generated::*; + mod scalar_stuff_generated; + pub use self::scalar_stuff_generated::*; } // optional_scalars diff --git a/tests/optional_scalars/optional_scalars/optional_byte_generated.rs b/tests/optional_scalars/optional_scalars/optional_byte_generated.rs index 4da704ef7..a0b1c4d39 100644 --- a/tests/optional_scalars/optional_scalars/optional_byte_generated.rs +++ b/tests/optional_scalars/optional_scalars/optional_byte_generated.rs @@ -2,73 +2,64 @@ // @generated extern crate alloc; use super::*; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] pub const ENUM_MIN_OPTIONAL_BYTE: i8 = 0; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] pub const ENUM_MAX_OPTIONAL_BYTE: i8 = 2; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] #[allow(non_camel_case_types)] pub const ENUM_VALUES_OPTIONAL_BYTE: [OptionalByte; 3] = [ - OptionalByte::None, - OptionalByte::One, - OptionalByte::Two, + OptionalByte::None, + OptionalByte::One, + OptionalByte::Two, ]; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] #[repr(transparent)] pub struct OptionalByte(pub i8); - #[allow(non_upper_case_globals)] impl OptionalByte { - pub const None: Self = Self(0); - pub const One: Self = Self(1); - pub const Two: Self = Self(2); + pub const None: Self = Self(0); + pub const One: Self = Self(1); + pub const Two: Self = Self(2); - pub const ENUM_MIN: i8 = 0; - pub const ENUM_MAX: i8 = 2; - pub const ENUM_VALUES: &'static [Self] = &[ - Self::None, - Self::One, - Self::Two, - ]; - - /// Returns the variant's name or "" if unknown. - pub fn variant_name(self) -> Option<&'static str> { - match self { - Self::None => Some("None"), - Self::One => Some("One"), - Self::Two => Some("Two"), - _ => None, - } + pub const ENUM_MIN: i8 = 0; + pub const ENUM_MAX: i8 = 2; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::None, + Self::One, + Self::Two, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::None => Some("None"), + Self::One => Some("One"), + Self::Two => Some("Two"), + _ => None, } + } } - impl ::core::fmt::Debug for OptionalByte { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - if let Some(name) = self.variant_name() { - f.write_str(name) - } else { - f.write_fmt(format_args!("", self.0)) - } + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) } + } } - impl<'a> ::flatbuffers::Follow<'a> for OptionalByte { - type Inner = Self; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; - Self(b) - } + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; + Self(b) + } } impl ::flatbuffers::Push for OptionalByte { type Output = OptionalByte; - #[inline] unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { unsafe { ::flatbuffers::emplace_scalar::(dst, self.0) }; @@ -76,28 +67,26 @@ impl ::flatbuffers::Push for OptionalByte { } impl ::flatbuffers::EndianScalar for OptionalByte { - type Scalar = i8; - - #[inline] - fn to_little_endian(self) -> i8 { - self.0.to_le() - } - - #[inline] - #[allow(clippy::wrong_self_convention)] - fn from_little_endian(v: i8) -> Self { - let b = i8::from_le(v); - Self(b) - } + type Scalar = i8; + #[inline] + fn to_little_endian(self) -> i8 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: i8) -> Self { + let b = i8::from_le(v); + Self(b) + } } impl<'a> ::flatbuffers::Verifiable for OptionalByte { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - i8::run_verifier(v, pos) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + i8::run_verifier(v, pos) + } } impl ::flatbuffers::SimpleToVerifyInSlice for OptionalByte {} diff --git a/tests/optional_scalars/optional_scalars/scalar_stuff_generated.rs b/tests/optional_scalars/optional_scalars/scalar_stuff_generated.rs index 4524bec28..79052ff4b 100644 --- a/tests/optional_scalars/optional_scalars/scalar_stuff_generated.rs +++ b/tests/optional_scalars/optional_scalars/scalar_stuff_generated.rs @@ -2,528 +2,489 @@ // @generated extern crate alloc; use super::*; - pub enum ScalarStuffOffset {} - #[derive(Copy, Clone, PartialEq)] + pub struct ScalarStuff<'a> { - pub _tab: ::flatbuffers::Table<'a>, + pub _tab: ::flatbuffers::Table<'a>, } impl<'a> ::flatbuffers::Follow<'a> for ScalarStuff<'a> { - type Inner = ScalarStuff<'a>; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } - } + type Inner = ScalarStuff<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } + } } impl<'a> ScalarStuff<'a> { - pub const VT_JUST_I8: ::flatbuffers::VOffsetT = 4; - pub const VT_MAYBE_I8: ::flatbuffers::VOffsetT = 6; - pub const VT_DEFAULT_I8: ::flatbuffers::VOffsetT = 8; - pub const VT_JUST_U8: ::flatbuffers::VOffsetT = 10; - pub const VT_MAYBE_U8: ::flatbuffers::VOffsetT = 12; - pub const VT_DEFAULT_U8: ::flatbuffers::VOffsetT = 14; - pub const VT_JUST_I16: ::flatbuffers::VOffsetT = 16; - pub const VT_MAYBE_I16: ::flatbuffers::VOffsetT = 18; - pub const VT_DEFAULT_I16: ::flatbuffers::VOffsetT = 20; - pub const VT_JUST_U16: ::flatbuffers::VOffsetT = 22; - pub const VT_MAYBE_U16: ::flatbuffers::VOffsetT = 24; - pub const VT_DEFAULT_U16: ::flatbuffers::VOffsetT = 26; - pub const VT_JUST_I32: ::flatbuffers::VOffsetT = 28; - pub const VT_MAYBE_I32: ::flatbuffers::VOffsetT = 30; - pub const VT_DEFAULT_I32: ::flatbuffers::VOffsetT = 32; - pub const VT_JUST_U32: ::flatbuffers::VOffsetT = 34; - pub const VT_MAYBE_U32: ::flatbuffers::VOffsetT = 36; - pub const VT_DEFAULT_U32: ::flatbuffers::VOffsetT = 38; - pub const VT_JUST_I64: ::flatbuffers::VOffsetT = 40; - pub const VT_MAYBE_I64: ::flatbuffers::VOffsetT = 42; - pub const VT_DEFAULT_I64: ::flatbuffers::VOffsetT = 44; - pub const VT_JUST_U64: ::flatbuffers::VOffsetT = 46; - pub const VT_MAYBE_U64: ::flatbuffers::VOffsetT = 48; - pub const VT_DEFAULT_U64: ::flatbuffers::VOffsetT = 50; - pub const VT_JUST_F32: ::flatbuffers::VOffsetT = 52; - pub const VT_MAYBE_F32: ::flatbuffers::VOffsetT = 54; - pub const VT_DEFAULT_F32: ::flatbuffers::VOffsetT = 56; - pub const VT_JUST_F64: ::flatbuffers::VOffsetT = 58; - pub const VT_MAYBE_F64: ::flatbuffers::VOffsetT = 60; - pub const VT_DEFAULT_F64: ::flatbuffers::VOffsetT = 62; - pub const VT_JUST_BOOL: ::flatbuffers::VOffsetT = 64; - pub const VT_MAYBE_BOOL: ::flatbuffers::VOffsetT = 66; - pub const VT_DEFAULT_BOOL: ::flatbuffers::VOffsetT = 68; - pub const VT_JUST_ENUM: ::flatbuffers::VOffsetT = 70; - pub const VT_MAYBE_ENUM: ::flatbuffers::VOffsetT = 72; - pub const VT_DEFAULT_ENUM: ::flatbuffers::VOffsetT = 74; + pub const VT_JUST_I8: ::flatbuffers::VOffsetT = 4; + pub const VT_MAYBE_I8: ::flatbuffers::VOffsetT = 6; + pub const VT_DEFAULT_I8: ::flatbuffers::VOffsetT = 8; + pub const VT_JUST_U8: ::flatbuffers::VOffsetT = 10; + pub const VT_MAYBE_U8: ::flatbuffers::VOffsetT = 12; + pub const VT_DEFAULT_U8: ::flatbuffers::VOffsetT = 14; + pub const VT_JUST_I16: ::flatbuffers::VOffsetT = 16; + pub const VT_MAYBE_I16: ::flatbuffers::VOffsetT = 18; + pub const VT_DEFAULT_I16: ::flatbuffers::VOffsetT = 20; + pub const VT_JUST_U16: ::flatbuffers::VOffsetT = 22; + pub const VT_MAYBE_U16: ::flatbuffers::VOffsetT = 24; + pub const VT_DEFAULT_U16: ::flatbuffers::VOffsetT = 26; + pub const VT_JUST_I32: ::flatbuffers::VOffsetT = 28; + pub const VT_MAYBE_I32: ::flatbuffers::VOffsetT = 30; + pub const VT_DEFAULT_I32: ::flatbuffers::VOffsetT = 32; + pub const VT_JUST_U32: ::flatbuffers::VOffsetT = 34; + pub const VT_MAYBE_U32: ::flatbuffers::VOffsetT = 36; + pub const VT_DEFAULT_U32: ::flatbuffers::VOffsetT = 38; + pub const VT_JUST_I64: ::flatbuffers::VOffsetT = 40; + pub const VT_MAYBE_I64: ::flatbuffers::VOffsetT = 42; + pub const VT_DEFAULT_I64: ::flatbuffers::VOffsetT = 44; + pub const VT_JUST_U64: ::flatbuffers::VOffsetT = 46; + pub const VT_MAYBE_U64: ::flatbuffers::VOffsetT = 48; + pub const VT_DEFAULT_U64: ::flatbuffers::VOffsetT = 50; + pub const VT_JUST_F32: ::flatbuffers::VOffsetT = 52; + pub const VT_MAYBE_F32: ::flatbuffers::VOffsetT = 54; + pub const VT_DEFAULT_F32: ::flatbuffers::VOffsetT = 56; + pub const VT_JUST_F64: ::flatbuffers::VOffsetT = 58; + pub const VT_MAYBE_F64: ::flatbuffers::VOffsetT = 60; + pub const VT_DEFAULT_F64: ::flatbuffers::VOffsetT = 62; + pub const VT_JUST_BOOL: ::flatbuffers::VOffsetT = 64; + pub const VT_MAYBE_BOOL: ::flatbuffers::VOffsetT = 66; + pub const VT_DEFAULT_BOOL: ::flatbuffers::VOffsetT = 68; + pub const VT_JUST_ENUM: ::flatbuffers::VOffsetT = 70; + pub const VT_MAYBE_ENUM: ::flatbuffers::VOffsetT = 72; + pub const VT_DEFAULT_ENUM: ::flatbuffers::VOffsetT = 74; - pub const fn get_fully_qualified_name() -> &'static str { - "optional_scalars.ScalarStuff" - } + pub const fn get_fully_qualified_name() -> &'static str { + "optional_scalars.ScalarStuff" + } - #[inline] - pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { - ScalarStuff { _tab: table } - } + #[inline] + pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { + ScalarStuff { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args ScalarStuffArgs + ) -> ::flatbuffers::WIPOffset> { + let mut builder = ScalarStuffBuilder::new(_fbb); + builder.add_default_f64(args.default_f64); + if let Some(x) = args.maybe_f64 { builder.add_maybe_f64(x); } + builder.add_just_f64(args.just_f64); + builder.add_default_u64(args.default_u64); + if let Some(x) = args.maybe_u64 { builder.add_maybe_u64(x); } + builder.add_just_u64(args.just_u64); + builder.add_default_i64(args.default_i64); + if let Some(x) = args.maybe_i64 { builder.add_maybe_i64(x); } + builder.add_just_i64(args.just_i64); + builder.add_default_f32(args.default_f32); + if let Some(x) = args.maybe_f32 { builder.add_maybe_f32(x); } + builder.add_just_f32(args.just_f32); + builder.add_default_u32(args.default_u32); + if let Some(x) = args.maybe_u32 { builder.add_maybe_u32(x); } + builder.add_just_u32(args.just_u32); + builder.add_default_i32(args.default_i32); + if let Some(x) = args.maybe_i32 { builder.add_maybe_i32(x); } + builder.add_just_i32(args.just_i32); + builder.add_default_u16(args.default_u16); + if let Some(x) = args.maybe_u16 { builder.add_maybe_u16(x); } + builder.add_just_u16(args.just_u16); + builder.add_default_i16(args.default_i16); + if let Some(x) = args.maybe_i16 { builder.add_maybe_i16(x); } + builder.add_just_i16(args.just_i16); + builder.add_default_enum(args.default_enum); + if let Some(x) = args.maybe_enum { builder.add_maybe_enum(x); } + builder.add_just_enum(args.just_enum); + builder.add_default_bool(args.default_bool); + if let Some(x) = args.maybe_bool { builder.add_maybe_bool(x); } + builder.add_just_bool(args.just_bool); + builder.add_default_u8(args.default_u8); + if let Some(x) = args.maybe_u8 { builder.add_maybe_u8(x); } + builder.add_just_u8(args.just_u8); + builder.add_default_i8(args.default_i8); + if let Some(x) = args.maybe_i8 { builder.add_maybe_i8(x); } + builder.add_just_i8(args.just_i8); + builder.finish() + } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args ScalarStuffArgs - ) -> ::flatbuffers::WIPOffset> { - let mut builder = ScalarStuffBuilder::new(_fbb); - builder.add_default_f64(args.default_f64); - if let Some(x) = args.maybe_f64 { builder.add_maybe_f64(x); } - builder.add_just_f64(args.just_f64); - builder.add_default_u64(args.default_u64); - if let Some(x) = args.maybe_u64 { builder.add_maybe_u64(x); } - builder.add_just_u64(args.just_u64); - builder.add_default_i64(args.default_i64); - if let Some(x) = args.maybe_i64 { builder.add_maybe_i64(x); } - builder.add_just_i64(args.just_i64); - builder.add_default_f32(args.default_f32); - if let Some(x) = args.maybe_f32 { builder.add_maybe_f32(x); } - builder.add_just_f32(args.just_f32); - builder.add_default_u32(args.default_u32); - if let Some(x) = args.maybe_u32 { builder.add_maybe_u32(x); } - builder.add_just_u32(args.just_u32); - builder.add_default_i32(args.default_i32); - if let Some(x) = args.maybe_i32 { builder.add_maybe_i32(x); } - builder.add_just_i32(args.just_i32); - builder.add_default_u16(args.default_u16); - if let Some(x) = args.maybe_u16 { builder.add_maybe_u16(x); } - builder.add_just_u16(args.just_u16); - builder.add_default_i16(args.default_i16); - if let Some(x) = args.maybe_i16 { builder.add_maybe_i16(x); } - builder.add_just_i16(args.just_i16); - builder.add_default_enum(args.default_enum); - if let Some(x) = args.maybe_enum { builder.add_maybe_enum(x); } - builder.add_just_enum(args.just_enum); - builder.add_default_bool(args.default_bool); - if let Some(x) = args.maybe_bool { builder.add_maybe_bool(x); } - builder.add_just_bool(args.just_bool); - builder.add_default_u8(args.default_u8); - if let Some(x) = args.maybe_u8 { builder.add_maybe_u8(x); } - builder.add_just_u8(args.just_u8); - builder.add_default_i8(args.default_i8); - if let Some(x) = args.maybe_i8 { builder.add_maybe_i8(x); } - builder.add_just_i8(args.just_i8); - builder.finish() + pub fn unpack(&self) -> ScalarStuffT { + let just_i8 = self.just_i8(); + let maybe_i8 = self.maybe_i8(); + let default_i8 = self.default_i8(); + let just_u8 = self.just_u8(); + let maybe_u8 = self.maybe_u8(); + let default_u8 = self.default_u8(); + let just_i16 = self.just_i16(); + let maybe_i16 = self.maybe_i16(); + let default_i16 = self.default_i16(); + let just_u16 = self.just_u16(); + let maybe_u16 = self.maybe_u16(); + let default_u16 = self.default_u16(); + let just_i32 = self.just_i32(); + let maybe_i32 = self.maybe_i32(); + let default_i32 = self.default_i32(); + let just_u32 = self.just_u32(); + let maybe_u32 = self.maybe_u32(); + let default_u32 = self.default_u32(); + let just_i64 = self.just_i64(); + let maybe_i64 = self.maybe_i64(); + let default_i64 = self.default_i64(); + let just_u64 = self.just_u64(); + let maybe_u64 = self.maybe_u64(); + let default_u64 = self.default_u64(); + let just_f32 = self.just_f32(); + let maybe_f32 = self.maybe_f32(); + let default_f32 = self.default_f32(); + let just_f64 = self.just_f64(); + let maybe_f64 = self.maybe_f64(); + let default_f64 = self.default_f64(); + let just_bool = self.just_bool(); + let maybe_bool = self.maybe_bool(); + let default_bool = self.default_bool(); + let just_enum = self.just_enum(); + let maybe_enum = self.maybe_enum(); + let default_enum = self.default_enum(); + ScalarStuffT { + just_i8, + maybe_i8, + default_i8, + just_u8, + maybe_u8, + default_u8, + just_i16, + maybe_i16, + default_i16, + just_u16, + maybe_u16, + default_u16, + just_i32, + maybe_i32, + default_i32, + just_u32, + maybe_u32, + default_u32, + just_i64, + maybe_i64, + default_i64, + just_u64, + maybe_u64, + default_u64, + just_f32, + maybe_f32, + default_f32, + just_f64, + maybe_f64, + default_f64, + just_bool, + maybe_bool, + default_bool, + just_enum, + maybe_enum, + default_enum, } + } - pub fn unpack(&self) -> ScalarStuffT { - let just_i8 = self.just_i8(); - let maybe_i8 = self.maybe_i8(); - let default_i8 = self.default_i8(); - let just_u8 = self.just_u8(); - let maybe_u8 = self.maybe_u8(); - let default_u8 = self.default_u8(); - let just_i16 = self.just_i16(); - let maybe_i16 = self.maybe_i16(); - let default_i16 = self.default_i16(); - let just_u16 = self.just_u16(); - let maybe_u16 = self.maybe_u16(); - let default_u16 = self.default_u16(); - let just_i32 = self.just_i32(); - let maybe_i32 = self.maybe_i32(); - let default_i32 = self.default_i32(); - let just_u32 = self.just_u32(); - let maybe_u32 = self.maybe_u32(); - let default_u32 = self.default_u32(); - let just_i64 = self.just_i64(); - let maybe_i64 = self.maybe_i64(); - let default_i64 = self.default_i64(); - let just_u64 = self.just_u64(); - let maybe_u64 = self.maybe_u64(); - let default_u64 = self.default_u64(); - let just_f32 = self.just_f32(); - let maybe_f32 = self.maybe_f32(); - let default_f32 = self.default_f32(); - let just_f64 = self.just_f64(); - let maybe_f64 = self.maybe_f64(); - let default_f64 = self.default_f64(); - let just_bool = self.just_bool(); - let maybe_bool = self.maybe_bool(); - let default_bool = self.default_bool(); - let just_enum = self.just_enum(); - let maybe_enum = self.maybe_enum(); - let default_enum = self.default_enum(); - ScalarStuffT { - just_i8, - maybe_i8, - default_i8, - just_u8, - maybe_u8, - default_u8, - just_i16, - maybe_i16, - default_i16, - just_u16, - maybe_u16, - default_u16, - just_i32, - maybe_i32, - default_i32, - just_u32, - maybe_u32, - default_u32, - just_i64, - maybe_i64, - default_i64, - just_u64, - maybe_u64, - default_u64, - just_f32, - maybe_f32, - default_f32, - just_f64, - maybe_f64, - default_f64, - just_bool, - maybe_bool, - default_bool, - just_enum, - maybe_enum, - default_enum, - } - } - - #[inline] - pub fn just_i8(&self) -> i8 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(ScalarStuff::VT_JUST_I8, Some(0)).unwrap()} - } - - #[inline] - pub fn maybe_i8(&self) -> Option { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(ScalarStuff::VT_MAYBE_I8, None)} - } - - #[inline] - pub fn default_i8(&self) -> i8 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(ScalarStuff::VT_DEFAULT_I8, Some(42)).unwrap()} - } - - #[inline] - pub fn just_u8(&self) -> u8 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(ScalarStuff::VT_JUST_U8, Some(0)).unwrap()} - } - - #[inline] - pub fn maybe_u8(&self) -> Option { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(ScalarStuff::VT_MAYBE_U8, None)} - } - - #[inline] - pub fn default_u8(&self) -> u8 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(ScalarStuff::VT_DEFAULT_U8, Some(42)).unwrap()} - } - - #[inline] - pub fn just_i16(&self) -> i16 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(ScalarStuff::VT_JUST_I16, Some(0)).unwrap()} - } - - #[inline] - pub fn maybe_i16(&self) -> Option { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(ScalarStuff::VT_MAYBE_I16, None)} - } - - #[inline] - pub fn default_i16(&self) -> i16 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(ScalarStuff::VT_DEFAULT_I16, Some(42)).unwrap()} - } - - #[inline] - pub fn just_u16(&self) -> u16 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(ScalarStuff::VT_JUST_U16, Some(0)).unwrap()} - } - - #[inline] - pub fn maybe_u16(&self) -> Option { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(ScalarStuff::VT_MAYBE_U16, None)} - } - - #[inline] - pub fn default_u16(&self) -> u16 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(ScalarStuff::VT_DEFAULT_U16, Some(42)).unwrap()} - } - - #[inline] - pub fn just_i32(&self) -> i32 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(ScalarStuff::VT_JUST_I32, Some(0)).unwrap()} - } - - #[inline] - pub fn maybe_i32(&self) -> Option { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(ScalarStuff::VT_MAYBE_I32, None)} - } - - #[inline] - pub fn default_i32(&self) -> i32 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(ScalarStuff::VT_DEFAULT_I32, Some(42)).unwrap()} - } - - #[inline] - pub fn just_u32(&self) -> u32 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(ScalarStuff::VT_JUST_U32, Some(0)).unwrap()} - } - - #[inline] - pub fn maybe_u32(&self) -> Option { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(ScalarStuff::VT_MAYBE_U32, None)} - } - - #[inline] - pub fn default_u32(&self) -> u32 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(ScalarStuff::VT_DEFAULT_U32, Some(42)).unwrap()} - } - - #[inline] - pub fn just_i64(&self) -> i64 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(ScalarStuff::VT_JUST_I64, Some(0)).unwrap()} - } - - #[inline] - pub fn maybe_i64(&self) -> Option { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(ScalarStuff::VT_MAYBE_I64, None)} - } - - #[inline] - pub fn default_i64(&self) -> i64 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(ScalarStuff::VT_DEFAULT_I64, Some(42)).unwrap()} - } - - #[inline] - pub fn just_u64(&self) -> u64 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(ScalarStuff::VT_JUST_U64, Some(0)).unwrap()} - } - - #[inline] - pub fn maybe_u64(&self) -> Option { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(ScalarStuff::VT_MAYBE_U64, None)} - } - - #[inline] - pub fn default_u64(&self) -> u64 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(ScalarStuff::VT_DEFAULT_U64, Some(42)).unwrap()} - } - - #[inline] - pub fn just_f32(&self) -> f32 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(ScalarStuff::VT_JUST_F32, Some(0.0)).unwrap()} - } - - #[inline] - pub fn maybe_f32(&self) -> Option { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(ScalarStuff::VT_MAYBE_F32, None)} - } - - #[inline] - pub fn default_f32(&self) -> f32 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(ScalarStuff::VT_DEFAULT_F32, Some(42.0)).unwrap()} - } - - #[inline] - pub fn just_f64(&self) -> f64 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(ScalarStuff::VT_JUST_F64, Some(0.0)).unwrap()} - } - - #[inline] - pub fn maybe_f64(&self) -> Option { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(ScalarStuff::VT_MAYBE_F64, None)} - } - - #[inline] - pub fn default_f64(&self) -> f64 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(ScalarStuff::VT_DEFAULT_F64, Some(42.0)).unwrap()} - } - - #[inline] - pub fn just_bool(&self) -> bool { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(ScalarStuff::VT_JUST_BOOL, Some(false)).unwrap()} - } - - #[inline] - pub fn maybe_bool(&self) -> Option { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(ScalarStuff::VT_MAYBE_BOOL, None)} - } - - #[inline] - pub fn default_bool(&self) -> bool { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(ScalarStuff::VT_DEFAULT_BOOL, Some(true)).unwrap()} - } - - #[inline] - pub fn just_enum(&self) -> OptionalByte { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(ScalarStuff::VT_JUST_ENUM, Some(OptionalByte::None)).unwrap()} - } - - #[inline] - pub fn maybe_enum(&self) -> Option { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(ScalarStuff::VT_MAYBE_ENUM, None)} - } - - #[inline] - pub fn default_enum(&self) -> OptionalByte { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(ScalarStuff::VT_DEFAULT_ENUM, Some(OptionalByte::One)).unwrap()} - } + #[inline] + pub fn just_i8(&self) -> i8 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_JUST_I8, Some(0)).unwrap()} + } + #[inline] + pub fn maybe_i8(&self) -> Option { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_MAYBE_I8, None)} + } + #[inline] + pub fn default_i8(&self) -> i8 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_DEFAULT_I8, Some(42)).unwrap()} + } + #[inline] + pub fn just_u8(&self) -> u8 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_JUST_U8, Some(0)).unwrap()} + } + #[inline] + pub fn maybe_u8(&self) -> Option { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_MAYBE_U8, None)} + } + #[inline] + pub fn default_u8(&self) -> u8 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_DEFAULT_U8, Some(42)).unwrap()} + } + #[inline] + pub fn just_i16(&self) -> i16 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_JUST_I16, Some(0)).unwrap()} + } + #[inline] + pub fn maybe_i16(&self) -> Option { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_MAYBE_I16, None)} + } + #[inline] + pub fn default_i16(&self) -> i16 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_DEFAULT_I16, Some(42)).unwrap()} + } + #[inline] + pub fn just_u16(&self) -> u16 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_JUST_U16, Some(0)).unwrap()} + } + #[inline] + pub fn maybe_u16(&self) -> Option { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_MAYBE_U16, None)} + } + #[inline] + pub fn default_u16(&self) -> u16 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_DEFAULT_U16, Some(42)).unwrap()} + } + #[inline] + pub fn just_i32(&self) -> i32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_JUST_I32, Some(0)).unwrap()} + } + #[inline] + pub fn maybe_i32(&self) -> Option { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_MAYBE_I32, None)} + } + #[inline] + pub fn default_i32(&self) -> i32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_DEFAULT_I32, Some(42)).unwrap()} + } + #[inline] + pub fn just_u32(&self) -> u32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_JUST_U32, Some(0)).unwrap()} + } + #[inline] + pub fn maybe_u32(&self) -> Option { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_MAYBE_U32, None)} + } + #[inline] + pub fn default_u32(&self) -> u32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_DEFAULT_U32, Some(42)).unwrap()} + } + #[inline] + pub fn just_i64(&self) -> i64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_JUST_I64, Some(0)).unwrap()} + } + #[inline] + pub fn maybe_i64(&self) -> Option { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_MAYBE_I64, None)} + } + #[inline] + pub fn default_i64(&self) -> i64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_DEFAULT_I64, Some(42)).unwrap()} + } + #[inline] + pub fn just_u64(&self) -> u64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_JUST_U64, Some(0)).unwrap()} + } + #[inline] + pub fn maybe_u64(&self) -> Option { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_MAYBE_U64, None)} + } + #[inline] + pub fn default_u64(&self) -> u64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_DEFAULT_U64, Some(42)).unwrap()} + } + #[inline] + pub fn just_f32(&self) -> f32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_JUST_F32, Some(0.0)).unwrap()} + } + #[inline] + pub fn maybe_f32(&self) -> Option { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_MAYBE_F32, None)} + } + #[inline] + pub fn default_f32(&self) -> f32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_DEFAULT_F32, Some(42.0)).unwrap()} + } + #[inline] + pub fn just_f64(&self) -> f64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_JUST_F64, Some(0.0)).unwrap()} + } + #[inline] + pub fn maybe_f64(&self) -> Option { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_MAYBE_F64, None)} + } + #[inline] + pub fn default_f64(&self) -> f64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_DEFAULT_F64, Some(42.0)).unwrap()} + } + #[inline] + pub fn just_bool(&self) -> bool { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_JUST_BOOL, Some(false)).unwrap()} + } + #[inline] + pub fn maybe_bool(&self) -> Option { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_MAYBE_BOOL, None)} + } + #[inline] + pub fn default_bool(&self) -> bool { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_DEFAULT_BOOL, Some(true)).unwrap()} + } + #[inline] + pub fn just_enum(&self) -> OptionalByte { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_JUST_ENUM, Some(OptionalByte::None)).unwrap()} + } + #[inline] + pub fn maybe_enum(&self) -> Option { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_MAYBE_ENUM, None)} + } + #[inline] + pub fn default_enum(&self) -> OptionalByte { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_DEFAULT_ENUM, Some(OptionalByte::One)).unwrap()} + } } impl ::flatbuffers::Verifiable for ScalarStuff<'_> { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.visit_table(pos)? - .visit_field::("just_i8", Self::VT_JUST_I8, false)? - .visit_field::("maybe_i8", Self::VT_MAYBE_I8, false)? - .visit_field::("default_i8", Self::VT_DEFAULT_I8, false)? - .visit_field::("just_u8", Self::VT_JUST_U8, false)? - .visit_field::("maybe_u8", Self::VT_MAYBE_U8, false)? - .visit_field::("default_u8", Self::VT_DEFAULT_U8, false)? - .visit_field::("just_i16", Self::VT_JUST_I16, false)? - .visit_field::("maybe_i16", Self::VT_MAYBE_I16, false)? - .visit_field::("default_i16", Self::VT_DEFAULT_I16, false)? - .visit_field::("just_u16", Self::VT_JUST_U16, false)? - .visit_field::("maybe_u16", Self::VT_MAYBE_U16, false)? - .visit_field::("default_u16", Self::VT_DEFAULT_U16, false)? - .visit_field::("just_i32", Self::VT_JUST_I32, false)? - .visit_field::("maybe_i32", Self::VT_MAYBE_I32, false)? - .visit_field::("default_i32", Self::VT_DEFAULT_I32, false)? - .visit_field::("just_u32", Self::VT_JUST_U32, false)? - .visit_field::("maybe_u32", Self::VT_MAYBE_U32, false)? - .visit_field::("default_u32", Self::VT_DEFAULT_U32, false)? - .visit_field::("just_i64", Self::VT_JUST_I64, false)? - .visit_field::("maybe_i64", Self::VT_MAYBE_I64, false)? - .visit_field::("default_i64", Self::VT_DEFAULT_I64, false)? - .visit_field::("just_u64", Self::VT_JUST_U64, false)? - .visit_field::("maybe_u64", Self::VT_MAYBE_U64, false)? - .visit_field::("default_u64", Self::VT_DEFAULT_U64, false)? - .visit_field::("just_f32", Self::VT_JUST_F32, false)? - .visit_field::("maybe_f32", Self::VT_MAYBE_F32, false)? - .visit_field::("default_f32", Self::VT_DEFAULT_F32, false)? - .visit_field::("just_f64", Self::VT_JUST_F64, false)? - .visit_field::("maybe_f64", Self::VT_MAYBE_F64, false)? - .visit_field::("default_f64", Self::VT_DEFAULT_F64, false)? - .visit_field::("just_bool", Self::VT_JUST_BOOL, false)? - .visit_field::("maybe_bool", Self::VT_MAYBE_BOOL, false)? - .visit_field::("default_bool", Self::VT_DEFAULT_BOOL, false)? - .visit_field::("just_enum", Self::VT_JUST_ENUM, false)? - .visit_field::("maybe_enum", Self::VT_MAYBE_ENUM, false)? - .visit_field::("default_enum", Self::VT_DEFAULT_ENUM, false)? - .finish(); - Ok(()) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.visit_table(pos)? + .visit_field::("just_i8", Self::VT_JUST_I8, false)? + .visit_field::("maybe_i8", Self::VT_MAYBE_I8, false)? + .visit_field::("default_i8", Self::VT_DEFAULT_I8, false)? + .visit_field::("just_u8", Self::VT_JUST_U8, false)? + .visit_field::("maybe_u8", Self::VT_MAYBE_U8, false)? + .visit_field::("default_u8", Self::VT_DEFAULT_U8, false)? + .visit_field::("just_i16", Self::VT_JUST_I16, false)? + .visit_field::("maybe_i16", Self::VT_MAYBE_I16, false)? + .visit_field::("default_i16", Self::VT_DEFAULT_I16, false)? + .visit_field::("just_u16", Self::VT_JUST_U16, false)? + .visit_field::("maybe_u16", Self::VT_MAYBE_U16, false)? + .visit_field::("default_u16", Self::VT_DEFAULT_U16, false)? + .visit_field::("just_i32", Self::VT_JUST_I32, false)? + .visit_field::("maybe_i32", Self::VT_MAYBE_I32, false)? + .visit_field::("default_i32", Self::VT_DEFAULT_I32, false)? + .visit_field::("just_u32", Self::VT_JUST_U32, false)? + .visit_field::("maybe_u32", Self::VT_MAYBE_U32, false)? + .visit_field::("default_u32", Self::VT_DEFAULT_U32, false)? + .visit_field::("just_i64", Self::VT_JUST_I64, false)? + .visit_field::("maybe_i64", Self::VT_MAYBE_I64, false)? + .visit_field::("default_i64", Self::VT_DEFAULT_I64, false)? + .visit_field::("just_u64", Self::VT_JUST_U64, false)? + .visit_field::("maybe_u64", Self::VT_MAYBE_U64, false)? + .visit_field::("default_u64", Self::VT_DEFAULT_U64, false)? + .visit_field::("just_f32", Self::VT_JUST_F32, false)? + .visit_field::("maybe_f32", Self::VT_MAYBE_F32, false)? + .visit_field::("default_f32", Self::VT_DEFAULT_F32, false)? + .visit_field::("just_f64", Self::VT_JUST_F64, false)? + .visit_field::("maybe_f64", Self::VT_MAYBE_F64, false)? + .visit_field::("default_f64", Self::VT_DEFAULT_F64, false)? + .visit_field::("just_bool", Self::VT_JUST_BOOL, false)? + .visit_field::("maybe_bool", Self::VT_MAYBE_BOOL, false)? + .visit_field::("default_bool", Self::VT_DEFAULT_BOOL, false)? + .visit_field::("just_enum", Self::VT_JUST_ENUM, false)? + .visit_field::("maybe_enum", Self::VT_MAYBE_ENUM, false)? + .visit_field::("default_enum", Self::VT_DEFAULT_ENUM, false)? + .finish(); + Ok(()) + } } - pub struct ScalarStuffArgs { pub just_i8: i8, pub maybe_i8: Option, @@ -562,538 +523,489 @@ pub struct ScalarStuffArgs { pub maybe_enum: Option, pub default_enum: OptionalByte, } - impl<'a> Default for ScalarStuffArgs { - #[inline] - fn default() -> Self { - ScalarStuffArgs { - just_i8: 0, - maybe_i8: None, - default_i8: 42, - just_u8: 0, - maybe_u8: None, - default_u8: 42, - just_i16: 0, - maybe_i16: None, - default_i16: 42, - just_u16: 0, - maybe_u16: None, - default_u16: 42, - just_i32: 0, - maybe_i32: None, - default_i32: 42, - just_u32: 0, - maybe_u32: None, - default_u32: 42, - just_i64: 0, - maybe_i64: None, - default_i64: 42, - just_u64: 0, - maybe_u64: None, - default_u64: 42, - just_f32: 0.0, - maybe_f32: None, - default_f32: 42.0, - just_f64: 0.0, - maybe_f64: None, - default_f64: 42.0, - just_bool: false, - maybe_bool: None, - default_bool: true, - just_enum: OptionalByte::None, - maybe_enum: None, - default_enum: OptionalByte::One, - } + #[inline] + fn default() -> Self { + ScalarStuffArgs { + just_i8: 0, + maybe_i8: None, + default_i8: 42, + just_u8: 0, + maybe_u8: None, + default_u8: 42, + just_i16: 0, + maybe_i16: None, + default_i16: 42, + just_u16: 0, + maybe_u16: None, + default_u16: 42, + just_i32: 0, + maybe_i32: None, + default_i32: 42, + just_u32: 0, + maybe_u32: None, + default_u32: 42, + just_i64: 0, + maybe_i64: None, + default_i64: 42, + just_u64: 0, + maybe_u64: None, + default_u64: 42, + just_f32: 0.0, + maybe_f32: None, + default_f32: 42.0, + just_f64: 0.0, + maybe_f64: None, + default_f64: 42.0, + just_bool: false, + maybe_bool: None, + default_bool: true, + just_enum: OptionalByte::None, + maybe_enum: None, + default_enum: OptionalByte::One, } + } } pub struct ScalarStuffBuilder<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> { - fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, + fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, + start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, } - impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> ScalarStuffBuilder<'a, 'b, A> { - #[inline] - pub fn add_just_i8(&mut self, just_i8: i8) { - self.fbb_.push_slot::(ScalarStuff::VT_JUST_I8, just_i8, 0); - } - - #[inline] - pub fn add_maybe_i8(&mut self, maybe_i8: i8) { - self.fbb_.push_slot_always::(ScalarStuff::VT_MAYBE_I8, maybe_i8); - } - - #[inline] - pub fn add_default_i8(&mut self, default_i8: i8) { - self.fbb_.push_slot::(ScalarStuff::VT_DEFAULT_I8, default_i8, 42); - } - - #[inline] - pub fn add_just_u8(&mut self, just_u8: u8) { - self.fbb_.push_slot::(ScalarStuff::VT_JUST_U8, just_u8, 0); - } - - #[inline] - pub fn add_maybe_u8(&mut self, maybe_u8: u8) { - self.fbb_.push_slot_always::(ScalarStuff::VT_MAYBE_U8, maybe_u8); - } - - #[inline] - pub fn add_default_u8(&mut self, default_u8: u8) { - self.fbb_.push_slot::(ScalarStuff::VT_DEFAULT_U8, default_u8, 42); - } - - #[inline] - pub fn add_just_i16(&mut self, just_i16: i16) { - self.fbb_.push_slot::(ScalarStuff::VT_JUST_I16, just_i16, 0); - } - - #[inline] - pub fn add_maybe_i16(&mut self, maybe_i16: i16) { - self.fbb_.push_slot_always::(ScalarStuff::VT_MAYBE_I16, maybe_i16); - } - - #[inline] - pub fn add_default_i16(&mut self, default_i16: i16) { - self.fbb_.push_slot::(ScalarStuff::VT_DEFAULT_I16, default_i16, 42); - } - - #[inline] - pub fn add_just_u16(&mut self, just_u16: u16) { - self.fbb_.push_slot::(ScalarStuff::VT_JUST_U16, just_u16, 0); - } - - #[inline] - pub fn add_maybe_u16(&mut self, maybe_u16: u16) { - self.fbb_.push_slot_always::(ScalarStuff::VT_MAYBE_U16, maybe_u16); - } - - #[inline] - pub fn add_default_u16(&mut self, default_u16: u16) { - self.fbb_.push_slot::(ScalarStuff::VT_DEFAULT_U16, default_u16, 42); - } - - #[inline] - pub fn add_just_i32(&mut self, just_i32: i32) { - self.fbb_.push_slot::(ScalarStuff::VT_JUST_I32, just_i32, 0); - } - - #[inline] - pub fn add_maybe_i32(&mut self, maybe_i32: i32) { - self.fbb_.push_slot_always::(ScalarStuff::VT_MAYBE_I32, maybe_i32); - } - - #[inline] - pub fn add_default_i32(&mut self, default_i32: i32) { - self.fbb_.push_slot::(ScalarStuff::VT_DEFAULT_I32, default_i32, 42); - } - - #[inline] - pub fn add_just_u32(&mut self, just_u32: u32) { - self.fbb_.push_slot::(ScalarStuff::VT_JUST_U32, just_u32, 0); - } - - #[inline] - pub fn add_maybe_u32(&mut self, maybe_u32: u32) { - self.fbb_.push_slot_always::(ScalarStuff::VT_MAYBE_U32, maybe_u32); - } - - #[inline] - pub fn add_default_u32(&mut self, default_u32: u32) { - self.fbb_.push_slot::(ScalarStuff::VT_DEFAULT_U32, default_u32, 42); - } - - #[inline] - pub fn add_just_i64(&mut self, just_i64: i64) { - self.fbb_.push_slot::(ScalarStuff::VT_JUST_I64, just_i64, 0); - } - - #[inline] - pub fn add_maybe_i64(&mut self, maybe_i64: i64) { - self.fbb_.push_slot_always::(ScalarStuff::VT_MAYBE_I64, maybe_i64); - } - - #[inline] - pub fn add_default_i64(&mut self, default_i64: i64) { - self.fbb_.push_slot::(ScalarStuff::VT_DEFAULT_I64, default_i64, 42); - } - - #[inline] - pub fn add_just_u64(&mut self, just_u64: u64) { - self.fbb_.push_slot::(ScalarStuff::VT_JUST_U64, just_u64, 0); - } - - #[inline] - pub fn add_maybe_u64(&mut self, maybe_u64: u64) { - self.fbb_.push_slot_always::(ScalarStuff::VT_MAYBE_U64, maybe_u64); - } - - #[inline] - pub fn add_default_u64(&mut self, default_u64: u64) { - self.fbb_.push_slot::(ScalarStuff::VT_DEFAULT_U64, default_u64, 42); - } - - #[inline] - pub fn add_just_f32(&mut self, just_f32: f32) { - self.fbb_.push_slot::(ScalarStuff::VT_JUST_F32, just_f32, 0.0); - } - - #[inline] - pub fn add_maybe_f32(&mut self, maybe_f32: f32) { - self.fbb_.push_slot_always::(ScalarStuff::VT_MAYBE_F32, maybe_f32); - } - - #[inline] - pub fn add_default_f32(&mut self, default_f32: f32) { - self.fbb_.push_slot::(ScalarStuff::VT_DEFAULT_F32, default_f32, 42.0); - } - - #[inline] - pub fn add_just_f64(&mut self, just_f64: f64) { - self.fbb_.push_slot::(ScalarStuff::VT_JUST_F64, just_f64, 0.0); - } - - #[inline] - pub fn add_maybe_f64(&mut self, maybe_f64: f64) { - self.fbb_.push_slot_always::(ScalarStuff::VT_MAYBE_F64, maybe_f64); - } - - #[inline] - pub fn add_default_f64(&mut self, default_f64: f64) { - self.fbb_.push_slot::(ScalarStuff::VT_DEFAULT_F64, default_f64, 42.0); - } - - #[inline] - pub fn add_just_bool(&mut self, just_bool: bool) { - self.fbb_.push_slot::(ScalarStuff::VT_JUST_BOOL, just_bool, false); - } - - #[inline] - pub fn add_maybe_bool(&mut self, maybe_bool: bool) { - self.fbb_.push_slot_always::(ScalarStuff::VT_MAYBE_BOOL, maybe_bool); - } - - #[inline] - pub fn add_default_bool(&mut self, default_bool: bool) { - self.fbb_.push_slot::(ScalarStuff::VT_DEFAULT_BOOL, default_bool, true); - } - - #[inline] - pub fn add_just_enum(&mut self, just_enum: OptionalByte) { - self.fbb_.push_slot::(ScalarStuff::VT_JUST_ENUM, just_enum, OptionalByte::None); - } - - #[inline] - pub fn add_maybe_enum(&mut self, maybe_enum: OptionalByte) { - self.fbb_.push_slot_always::(ScalarStuff::VT_MAYBE_ENUM, maybe_enum); - } - - #[inline] - pub fn add_default_enum(&mut self, default_enum: OptionalByte) { - self.fbb_.push_slot::(ScalarStuff::VT_DEFAULT_ENUM, default_enum, OptionalByte::One); - } - - #[inline] - pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> ScalarStuffBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - ScalarStuffBuilder { - fbb_: _fbb, - start_: start, - } - } - - #[inline] - pub fn finish(self) -> ::flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - ::flatbuffers::WIPOffset::new(o.value()) + #[inline] + pub fn add_just_i8(&mut self, just_i8: i8) { + self.fbb_.push_slot::(ScalarStuff::VT_JUST_I8, just_i8, 0); + } + #[inline] + pub fn add_maybe_i8(&mut self, maybe_i8: i8) { + self.fbb_.push_slot_always::(ScalarStuff::VT_MAYBE_I8, maybe_i8); + } + #[inline] + pub fn add_default_i8(&mut self, default_i8: i8) { + self.fbb_.push_slot::(ScalarStuff::VT_DEFAULT_I8, default_i8, 42); + } + #[inline] + pub fn add_just_u8(&mut self, just_u8: u8) { + self.fbb_.push_slot::(ScalarStuff::VT_JUST_U8, just_u8, 0); + } + #[inline] + pub fn add_maybe_u8(&mut self, maybe_u8: u8) { + self.fbb_.push_slot_always::(ScalarStuff::VT_MAYBE_U8, maybe_u8); + } + #[inline] + pub fn add_default_u8(&mut self, default_u8: u8) { + self.fbb_.push_slot::(ScalarStuff::VT_DEFAULT_U8, default_u8, 42); + } + #[inline] + pub fn add_just_i16(&mut self, just_i16: i16) { + self.fbb_.push_slot::(ScalarStuff::VT_JUST_I16, just_i16, 0); + } + #[inline] + pub fn add_maybe_i16(&mut self, maybe_i16: i16) { + self.fbb_.push_slot_always::(ScalarStuff::VT_MAYBE_I16, maybe_i16); + } + #[inline] + pub fn add_default_i16(&mut self, default_i16: i16) { + self.fbb_.push_slot::(ScalarStuff::VT_DEFAULT_I16, default_i16, 42); + } + #[inline] + pub fn add_just_u16(&mut self, just_u16: u16) { + self.fbb_.push_slot::(ScalarStuff::VT_JUST_U16, just_u16, 0); + } + #[inline] + pub fn add_maybe_u16(&mut self, maybe_u16: u16) { + self.fbb_.push_slot_always::(ScalarStuff::VT_MAYBE_U16, maybe_u16); + } + #[inline] + pub fn add_default_u16(&mut self, default_u16: u16) { + self.fbb_.push_slot::(ScalarStuff::VT_DEFAULT_U16, default_u16, 42); + } + #[inline] + pub fn add_just_i32(&mut self, just_i32: i32) { + self.fbb_.push_slot::(ScalarStuff::VT_JUST_I32, just_i32, 0); + } + #[inline] + pub fn add_maybe_i32(&mut self, maybe_i32: i32) { + self.fbb_.push_slot_always::(ScalarStuff::VT_MAYBE_I32, maybe_i32); + } + #[inline] + pub fn add_default_i32(&mut self, default_i32: i32) { + self.fbb_.push_slot::(ScalarStuff::VT_DEFAULT_I32, default_i32, 42); + } + #[inline] + pub fn add_just_u32(&mut self, just_u32: u32) { + self.fbb_.push_slot::(ScalarStuff::VT_JUST_U32, just_u32, 0); + } + #[inline] + pub fn add_maybe_u32(&mut self, maybe_u32: u32) { + self.fbb_.push_slot_always::(ScalarStuff::VT_MAYBE_U32, maybe_u32); + } + #[inline] + pub fn add_default_u32(&mut self, default_u32: u32) { + self.fbb_.push_slot::(ScalarStuff::VT_DEFAULT_U32, default_u32, 42); + } + #[inline] + pub fn add_just_i64(&mut self, just_i64: i64) { + self.fbb_.push_slot::(ScalarStuff::VT_JUST_I64, just_i64, 0); + } + #[inline] + pub fn add_maybe_i64(&mut self, maybe_i64: i64) { + self.fbb_.push_slot_always::(ScalarStuff::VT_MAYBE_I64, maybe_i64); + } + #[inline] + pub fn add_default_i64(&mut self, default_i64: i64) { + self.fbb_.push_slot::(ScalarStuff::VT_DEFAULT_I64, default_i64, 42); + } + #[inline] + pub fn add_just_u64(&mut self, just_u64: u64) { + self.fbb_.push_slot::(ScalarStuff::VT_JUST_U64, just_u64, 0); + } + #[inline] + pub fn add_maybe_u64(&mut self, maybe_u64: u64) { + self.fbb_.push_slot_always::(ScalarStuff::VT_MAYBE_U64, maybe_u64); + } + #[inline] + pub fn add_default_u64(&mut self, default_u64: u64) { + self.fbb_.push_slot::(ScalarStuff::VT_DEFAULT_U64, default_u64, 42); + } + #[inline] + pub fn add_just_f32(&mut self, just_f32: f32) { + self.fbb_.push_slot::(ScalarStuff::VT_JUST_F32, just_f32, 0.0); + } + #[inline] + pub fn add_maybe_f32(&mut self, maybe_f32: f32) { + self.fbb_.push_slot_always::(ScalarStuff::VT_MAYBE_F32, maybe_f32); + } + #[inline] + pub fn add_default_f32(&mut self, default_f32: f32) { + self.fbb_.push_slot::(ScalarStuff::VT_DEFAULT_F32, default_f32, 42.0); + } + #[inline] + pub fn add_just_f64(&mut self, just_f64: f64) { + self.fbb_.push_slot::(ScalarStuff::VT_JUST_F64, just_f64, 0.0); + } + #[inline] + pub fn add_maybe_f64(&mut self, maybe_f64: f64) { + self.fbb_.push_slot_always::(ScalarStuff::VT_MAYBE_F64, maybe_f64); + } + #[inline] + pub fn add_default_f64(&mut self, default_f64: f64) { + self.fbb_.push_slot::(ScalarStuff::VT_DEFAULT_F64, default_f64, 42.0); + } + #[inline] + pub fn add_just_bool(&mut self, just_bool: bool) { + self.fbb_.push_slot::(ScalarStuff::VT_JUST_BOOL, just_bool, false); + } + #[inline] + pub fn add_maybe_bool(&mut self, maybe_bool: bool) { + self.fbb_.push_slot_always::(ScalarStuff::VT_MAYBE_BOOL, maybe_bool); + } + #[inline] + pub fn add_default_bool(&mut self, default_bool: bool) { + self.fbb_.push_slot::(ScalarStuff::VT_DEFAULT_BOOL, default_bool, true); + } + #[inline] + pub fn add_just_enum(&mut self, just_enum: OptionalByte) { + self.fbb_.push_slot::(ScalarStuff::VT_JUST_ENUM, just_enum, OptionalByte::None); + } + #[inline] + pub fn add_maybe_enum(&mut self, maybe_enum: OptionalByte) { + self.fbb_.push_slot_always::(ScalarStuff::VT_MAYBE_ENUM, maybe_enum); + } + #[inline] + pub fn add_default_enum(&mut self, default_enum: OptionalByte) { + self.fbb_.push_slot::(ScalarStuff::VT_DEFAULT_ENUM, default_enum, OptionalByte::One); + } + #[inline] + pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> ScalarStuffBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + ScalarStuffBuilder { + fbb_: _fbb, + start_: start, } + } + #[inline] + pub fn finish(self) -> ::flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + ::flatbuffers::WIPOffset::new(o.value()) + } } impl ::core::fmt::Debug for ScalarStuff<'_> { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - let mut ds = f.debug_struct("ScalarStuff"); - ds.field("just_i8", &self.just_i8()); - ds.field("maybe_i8", &self.maybe_i8()); - ds.field("default_i8", &self.default_i8()); - ds.field("just_u8", &self.just_u8()); - ds.field("maybe_u8", &self.maybe_u8()); - ds.field("default_u8", &self.default_u8()); - ds.field("just_i16", &self.just_i16()); - ds.field("maybe_i16", &self.maybe_i16()); - ds.field("default_i16", &self.default_i16()); - ds.field("just_u16", &self.just_u16()); - ds.field("maybe_u16", &self.maybe_u16()); - ds.field("default_u16", &self.default_u16()); - ds.field("just_i32", &self.just_i32()); - ds.field("maybe_i32", &self.maybe_i32()); - ds.field("default_i32", &self.default_i32()); - ds.field("just_u32", &self.just_u32()); - ds.field("maybe_u32", &self.maybe_u32()); - ds.field("default_u32", &self.default_u32()); - ds.field("just_i64", &self.just_i64()); - ds.field("maybe_i64", &self.maybe_i64()); - ds.field("default_i64", &self.default_i64()); - ds.field("just_u64", &self.just_u64()); - ds.field("maybe_u64", &self.maybe_u64()); - ds.field("default_u64", &self.default_u64()); - ds.field("just_f32", &self.just_f32()); - ds.field("maybe_f32", &self.maybe_f32()); - ds.field("default_f32", &self.default_f32()); - ds.field("just_f64", &self.just_f64()); - ds.field("maybe_f64", &self.maybe_f64()); - ds.field("default_f64", &self.default_f64()); - ds.field("just_bool", &self.just_bool()); - ds.field("maybe_bool", &self.maybe_bool()); - ds.field("default_bool", &self.default_bool()); - ds.field("just_enum", &self.just_enum()); - ds.field("maybe_enum", &self.maybe_enum()); - ds.field("default_enum", &self.default_enum()); - ds.finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + let mut ds = f.debug_struct("ScalarStuff"); + ds.field("just_i8", &self.just_i8()); + ds.field("maybe_i8", &self.maybe_i8()); + ds.field("default_i8", &self.default_i8()); + ds.field("just_u8", &self.just_u8()); + ds.field("maybe_u8", &self.maybe_u8()); + ds.field("default_u8", &self.default_u8()); + ds.field("just_i16", &self.just_i16()); + ds.field("maybe_i16", &self.maybe_i16()); + ds.field("default_i16", &self.default_i16()); + ds.field("just_u16", &self.just_u16()); + ds.field("maybe_u16", &self.maybe_u16()); + ds.field("default_u16", &self.default_u16()); + ds.field("just_i32", &self.just_i32()); + ds.field("maybe_i32", &self.maybe_i32()); + ds.field("default_i32", &self.default_i32()); + ds.field("just_u32", &self.just_u32()); + ds.field("maybe_u32", &self.maybe_u32()); + ds.field("default_u32", &self.default_u32()); + ds.field("just_i64", &self.just_i64()); + ds.field("maybe_i64", &self.maybe_i64()); + ds.field("default_i64", &self.default_i64()); + ds.field("just_u64", &self.just_u64()); + ds.field("maybe_u64", &self.maybe_u64()); + ds.field("default_u64", &self.default_u64()); + ds.field("just_f32", &self.just_f32()); + ds.field("maybe_f32", &self.maybe_f32()); + ds.field("default_f32", &self.default_f32()); + ds.field("just_f64", &self.just_f64()); + ds.field("maybe_f64", &self.maybe_f64()); + ds.field("default_f64", &self.default_f64()); + ds.field("just_bool", &self.just_bool()); + ds.field("maybe_bool", &self.maybe_bool()); + ds.field("default_bool", &self.default_bool()); + ds.field("just_enum", &self.just_enum()); + ds.field("maybe_enum", &self.maybe_enum()); + ds.field("default_enum", &self.default_enum()); + ds.finish() + } } - #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub struct ScalarStuffT { - pub just_i8: i8, - pub maybe_i8: Option, - pub default_i8: i8, - pub just_u8: u8, - pub maybe_u8: Option, - pub default_u8: u8, - pub just_i16: i16, - pub maybe_i16: Option, - pub default_i16: i16, - pub just_u16: u16, - pub maybe_u16: Option, - pub default_u16: u16, - pub just_i32: i32, - pub maybe_i32: Option, - pub default_i32: i32, - pub just_u32: u32, - pub maybe_u32: Option, - pub default_u32: u32, - pub just_i64: i64, - pub maybe_i64: Option, - pub default_i64: i64, - pub just_u64: u64, - pub maybe_u64: Option, - pub default_u64: u64, - pub just_f32: f32, - pub maybe_f32: Option, - pub default_f32: f32, - pub just_f64: f64, - pub maybe_f64: Option, - pub default_f64: f64, - pub just_bool: bool, - pub maybe_bool: Option, - pub default_bool: bool, - pub just_enum: OptionalByte, - pub maybe_enum: Option, - pub default_enum: OptionalByte, + pub just_i8: i8, + pub maybe_i8: Option, + pub default_i8: i8, + pub just_u8: u8, + pub maybe_u8: Option, + pub default_u8: u8, + pub just_i16: i16, + pub maybe_i16: Option, + pub default_i16: i16, + pub just_u16: u16, + pub maybe_u16: Option, + pub default_u16: u16, + pub just_i32: i32, + pub maybe_i32: Option, + pub default_i32: i32, + pub just_u32: u32, + pub maybe_u32: Option, + pub default_u32: u32, + pub just_i64: i64, + pub maybe_i64: Option, + pub default_i64: i64, + pub just_u64: u64, + pub maybe_u64: Option, + pub default_u64: u64, + pub just_f32: f32, + pub maybe_f32: Option, + pub default_f32: f32, + pub just_f64: f64, + pub maybe_f64: Option, + pub default_f64: f64, + pub just_bool: bool, + pub maybe_bool: Option, + pub default_bool: bool, + pub just_enum: OptionalByte, + pub maybe_enum: Option, + pub default_enum: OptionalByte, } - impl Default for ScalarStuffT { - fn default() -> Self { - Self { - just_i8: 0, - maybe_i8: None, - default_i8: 42, - just_u8: 0, - maybe_u8: None, - default_u8: 42, - just_i16: 0, - maybe_i16: None, - default_i16: 42, - just_u16: 0, - maybe_u16: None, - default_u16: 42, - just_i32: 0, - maybe_i32: None, - default_i32: 42, - just_u32: 0, - maybe_u32: None, - default_u32: 42, - just_i64: 0, - maybe_i64: None, - default_i64: 42, - just_u64: 0, - maybe_u64: None, - default_u64: 42, - just_f32: 0.0, - maybe_f32: None, - default_f32: 42.0, - just_f64: 0.0, - maybe_f64: None, - default_f64: 42.0, - just_bool: false, - maybe_bool: None, - default_bool: true, - just_enum: OptionalByte::None, - maybe_enum: None, - default_enum: OptionalByte::One, - } + fn default() -> Self { + Self { + just_i8: 0, + maybe_i8: None, + default_i8: 42, + just_u8: 0, + maybe_u8: None, + default_u8: 42, + just_i16: 0, + maybe_i16: None, + default_i16: 42, + just_u16: 0, + maybe_u16: None, + default_u16: 42, + just_i32: 0, + maybe_i32: None, + default_i32: 42, + just_u32: 0, + maybe_u32: None, + default_u32: 42, + just_i64: 0, + maybe_i64: None, + default_i64: 42, + just_u64: 0, + maybe_u64: None, + default_u64: 42, + just_f32: 0.0, + maybe_f32: None, + default_f32: 42.0, + just_f64: 0.0, + maybe_f64: None, + default_f64: 42.0, + just_bool: false, + maybe_bool: None, + default_bool: true, + just_enum: OptionalByte::None, + maybe_enum: None, + default_enum: OptionalByte::One, } + } } - impl ScalarStuffT { - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( - &self, - _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> - ) -> ::flatbuffers::WIPOffset> { - let just_i8 = self.just_i8; - let maybe_i8 = self.maybe_i8; - let default_i8 = self.default_i8; - let just_u8 = self.just_u8; - let maybe_u8 = self.maybe_u8; - let default_u8 = self.default_u8; - let just_i16 = self.just_i16; - let maybe_i16 = self.maybe_i16; - let default_i16 = self.default_i16; - let just_u16 = self.just_u16; - let maybe_u16 = self.maybe_u16; - let default_u16 = self.default_u16; - let just_i32 = self.just_i32; - let maybe_i32 = self.maybe_i32; - let default_i32 = self.default_i32; - let just_u32 = self.just_u32; - let maybe_u32 = self.maybe_u32; - let default_u32 = self.default_u32; - let just_i64 = self.just_i64; - let maybe_i64 = self.maybe_i64; - let default_i64 = self.default_i64; - let just_u64 = self.just_u64; - let maybe_u64 = self.maybe_u64; - let default_u64 = self.default_u64; - let just_f32 = self.just_f32; - let maybe_f32 = self.maybe_f32; - let default_f32 = self.default_f32; - let just_f64 = self.just_f64; - let maybe_f64 = self.maybe_f64; - let default_f64 = self.default_f64; - let just_bool = self.just_bool; - let maybe_bool = self.maybe_bool; - let default_bool = self.default_bool; - let just_enum = self.just_enum; - let maybe_enum = self.maybe_enum; - let default_enum = self.default_enum; - ScalarStuff::create(_fbb, &ScalarStuffArgs{ - just_i8, - maybe_i8, - default_i8, - just_u8, - maybe_u8, - default_u8, - just_i16, - maybe_i16, - default_i16, - just_u16, - maybe_u16, - default_u16, - just_i32, - maybe_i32, - default_i32, - just_u32, - maybe_u32, - default_u32, - just_i64, - maybe_i64, - default_i64, - just_u64, - maybe_u64, - default_u64, - just_f32, - maybe_f32, - default_f32, - just_f64, - maybe_f64, - default_f64, - just_bool, - maybe_bool, - default_bool, - just_enum, - maybe_enum, - default_enum, - }) - } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> + ) -> ::flatbuffers::WIPOffset> { + let just_i8 = self.just_i8; + let maybe_i8 = self.maybe_i8; + let default_i8 = self.default_i8; + let just_u8 = self.just_u8; + let maybe_u8 = self.maybe_u8; + let default_u8 = self.default_u8; + let just_i16 = self.just_i16; + let maybe_i16 = self.maybe_i16; + let default_i16 = self.default_i16; + let just_u16 = self.just_u16; + let maybe_u16 = self.maybe_u16; + let default_u16 = self.default_u16; + let just_i32 = self.just_i32; + let maybe_i32 = self.maybe_i32; + let default_i32 = self.default_i32; + let just_u32 = self.just_u32; + let maybe_u32 = self.maybe_u32; + let default_u32 = self.default_u32; + let just_i64 = self.just_i64; + let maybe_i64 = self.maybe_i64; + let default_i64 = self.default_i64; + let just_u64 = self.just_u64; + let maybe_u64 = self.maybe_u64; + let default_u64 = self.default_u64; + let just_f32 = self.just_f32; + let maybe_f32 = self.maybe_f32; + let default_f32 = self.default_f32; + let just_f64 = self.just_f64; + let maybe_f64 = self.maybe_f64; + let default_f64 = self.default_f64; + let just_bool = self.just_bool; + let maybe_bool = self.maybe_bool; + let default_bool = self.default_bool; + let just_enum = self.just_enum; + let maybe_enum = self.maybe_enum; + let default_enum = self.default_enum; + ScalarStuff::create(_fbb, &ScalarStuffArgs{ + just_i8, + maybe_i8, + default_i8, + just_u8, + maybe_u8, + default_u8, + just_i16, + maybe_i16, + default_i16, + just_u16, + maybe_u16, + default_u16, + just_i32, + maybe_i32, + default_i32, + just_u32, + maybe_u32, + default_u32, + just_i64, + maybe_i64, + default_i64, + just_u64, + maybe_u64, + default_u64, + just_f32, + maybe_f32, + default_f32, + just_f64, + maybe_f64, + default_f64, + just_bool, + maybe_bool, + default_bool, + just_enum, + maybe_enum, + default_enum, + }) + } } - +#[inline] /// Verifies that a buffer of bytes contains a `ScalarStuff` /// and returns it. /// Note that verification is still experimental and may not /// catch every error, or be maximally performant. For the /// previous, unchecked, behavior use /// `root_as_scalar_stuff_unchecked`. -#[inline] pub fn root_as_scalar_stuff(buf: &[u8]) -> Result, ::flatbuffers::InvalidFlatbuffer> { - ::flatbuffers::root::(buf) + ::flatbuffers::root::(buf) } - +#[inline] /// Verifies that a buffer of bytes contains a size prefixed /// `ScalarStuff` and returns it. /// Note that verification is still experimental and may not /// catch every error, or be maximally performant. For the /// previous, unchecked, behavior use /// `size_prefixed_root_as_scalar_stuff_unchecked`. -#[inline] pub fn size_prefixed_root_as_scalar_stuff(buf: &[u8]) -> Result, ::flatbuffers::InvalidFlatbuffer> { - ::flatbuffers::size_prefixed_root::(buf) + ::flatbuffers::size_prefixed_root::(buf) } - +#[inline] /// Verifies, with the given options, that a buffer of bytes /// contains a `ScalarStuff` and returns it. /// Note that verification is still experimental and may not /// catch every error, or be maximally performant. For the /// previous, unchecked, behavior use /// `root_as_scalar_stuff_unchecked`. -#[inline] pub fn root_as_scalar_stuff_with_opts<'b, 'o>( - opts: &'o ::flatbuffers::VerifierOptions, - buf: &'b [u8], + opts: &'o ::flatbuffers::VerifierOptions, + buf: &'b [u8], ) -> Result, ::flatbuffers::InvalidFlatbuffer> { - ::flatbuffers::root_with_opts::>(opts, buf) + ::flatbuffers::root_with_opts::>(opts, buf) } - +#[inline] /// Verifies, with the given verifier options, that a buffer of /// bytes contains a size prefixed `ScalarStuff` and returns /// it. Note that verification is still experimental and may not /// catch every error, or be maximally performant. For the /// previous, unchecked, behavior use /// `root_as_scalar_stuff_unchecked`. -#[inline] pub fn size_prefixed_root_as_scalar_stuff_with_opts<'b, 'o>( - opts: &'o ::flatbuffers::VerifierOptions, - buf: &'b [u8], + opts: &'o ::flatbuffers::VerifierOptions, + buf: &'b [u8], ) -> Result, ::flatbuffers::InvalidFlatbuffer> { - ::flatbuffers::size_prefixed_root_with_opts::>(opts, buf) + ::flatbuffers::size_prefixed_root_with_opts::>(opts, buf) } - +#[inline] /// Assumes, without verification, that a buffer of bytes contains a ScalarStuff and returns it. /// # Safety /// Callers must trust the given bytes do indeed contain a valid `ScalarStuff`. -#[inline] pub unsafe fn root_as_scalar_stuff_unchecked(buf: &[u8]) -> ScalarStuff<'_> { - unsafe { ::flatbuffers::root_unchecked::(buf) } + unsafe { ::flatbuffers::root_unchecked::(buf) } } - +#[inline] /// Assumes, without verification, that a buffer of bytes contains a size prefixed ScalarStuff and returns it. /// # Safety /// Callers must trust the given bytes do indeed contain a valid size prefixed `ScalarStuff`. -#[inline] pub unsafe fn size_prefixed_root_as_scalar_stuff_unchecked(buf: &[u8]) -> ScalarStuff<'_> { - unsafe { ::flatbuffers::size_prefixed_root_unchecked::(buf) } + unsafe { ::flatbuffers::size_prefixed_root_unchecked::(buf) } } - pub const SCALAR_STUFF_IDENTIFIER: &str = "NULL"; #[inline] pub fn scalar_stuff_buffer_has_identifier(buf: &[u8]) -> bool { - ::flatbuffers::buffer_has_identifier(buf, SCALAR_STUFF_IDENTIFIER, false) + ::flatbuffers::buffer_has_identifier(buf, SCALAR_STUFF_IDENTIFIER, false) } #[inline] pub fn scalar_stuff_size_prefixed_buffer_has_identifier(buf: &[u8]) -> bool { - ::flatbuffers::buffer_has_identifier(buf, SCALAR_STUFF_IDENTIFIER, true) + ::flatbuffers::buffer_has_identifier(buf, SCALAR_STUFF_IDENTIFIER, true) } pub const SCALAR_STUFF_EXTENSION: &str = "mon"; @@ -1101,15 +1013,11 @@ pub const SCALAR_STUFF_EXTENSION: &str = "mon"; #[inline] pub fn finish_scalar_stuff_buffer<'a, 'b, A: ::flatbuffers::Allocator + 'a>( fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - root: ::flatbuffers::WIPOffset> -) { - fbb.finish(root, Some(SCALAR_STUFF_IDENTIFIER)); + root: ::flatbuffers::WIPOffset>) { + fbb.finish(root, Some(SCALAR_STUFF_IDENTIFIER)); } #[inline] -pub fn finish_size_prefixed_scalar_stuff_buffer<'a, 'b, A: ::flatbuffers::Allocator + 'a>( - fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - root: ::flatbuffers::WIPOffset> -) { - fbb.finish_size_prefixed(root, Some(SCALAR_STUFF_IDENTIFIER)); +pub fn finish_size_prefixed_scalar_stuff_buffer<'a, 'b, A: ::flatbuffers::Allocator + 'a>(fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, root: ::flatbuffers::WIPOffset>) { + fbb.finish_size_prefixed(root, Some(SCALAR_STUFF_IDENTIFIER)); } diff --git a/tests/parser_test.cpp b/tests/parser_test.cpp index e03fd9623..2ca1873fd 100644 --- a/tests/parser_test.cpp +++ b/tests/parser_test.cpp @@ -97,6 +97,17 @@ void ErrorTest() { "datatype already"); TestError("struct X (force_align: 7) { Y:int; }", "force_align"); TestError("struct X {}", "size 0"); + TestError( + "struct X { Y:int; } table T { y:X (bigfoot_ref:\"::Foo::Bar\"); " + "}", + "'bigfoot_ref_wrapper' attribute"); + TestError( + "table T { y:int (bigfoot_ref:\"::Foo::Bar\"); }", + "struct-typed fields"); + TestError( + "struct X (bigfoot_ref_wrapper: \"Foo\") { Y:int; } " + "table T { y:X (bigfoot_ref:\"\"); }", + "cannot be empty"); TestError("{}", "no root"); TestError("table X { Y:byte; } root_type X; { Y:1 } { Y:1 }", "end of file"); TestError("table X { Y:byte; } root_type X; { Y:1 } table Y{ Z:int }", diff --git a/tests/private_annotation_test/ab_generated.rs b/tests/private_annotation_test/ab_generated.rs index 099893f50..c8fd77cc0 100644 --- a/tests/private_annotation_test/ab_generated.rs +++ b/tests/private_annotation_test/ab_generated.rs @@ -2,69 +2,60 @@ // @generated extern crate alloc; use super::*; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] pub const ENUM_MIN_AB: i8 = 0; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] pub const ENUM_MAX_AB: i8 = 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_AB: [AB; 2] = [ - AB::A, - AB::B, + AB::A, + AB::B, ]; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] #[repr(transparent)] pub(crate) struct AB(pub i8); - #[allow(non_upper_case_globals)] impl AB { - pub const A: Self = Self(0); - pub const B: Self = Self(1); + pub const A: Self = Self(0); + pub const B: Self = Self(1); - pub const ENUM_MIN: i8 = 0; - pub const ENUM_MAX: i8 = 1; - pub const ENUM_VALUES: &'static [Self] = &[ - Self::A, - Self::B, - ]; - - /// Returns the variant's name or "" if unknown. - pub fn variant_name(self) -> Option<&'static str> { - match self { - Self::A => Some("A"), - Self::B => Some("B"), - _ => None, - } + pub const ENUM_MIN: i8 = 0; + pub const ENUM_MAX: i8 = 1; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::A, + Self::B, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::A => Some("A"), + Self::B => Some("B"), + _ => None, } + } } - impl ::core::fmt::Debug for AB { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - if let Some(name) = self.variant_name() { - f.write_str(name) - } else { - f.write_fmt(format_args!("", self.0)) - } + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) } + } } - impl<'a> ::flatbuffers::Follow<'a> for AB { - type Inner = Self; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; - Self(b) - } + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; + Self(b) + } } impl ::flatbuffers::Push for AB { type Output = AB; - #[inline] unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { unsafe { ::flatbuffers::emplace_scalar::(dst, self.0) }; @@ -72,28 +63,26 @@ impl ::flatbuffers::Push for AB { } impl ::flatbuffers::EndianScalar for AB { - type Scalar = i8; - - #[inline] - fn to_little_endian(self) -> i8 { - self.0.to_le() - } - - #[inline] - #[allow(clippy::wrong_self_convention)] - fn from_little_endian(v: i8) -> Self { - let b = i8::from_le(v); - Self(b) - } + type Scalar = i8; + #[inline] + fn to_little_endian(self) -> i8 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: i8) -> Self { + let b = i8::from_le(v); + Self(b) + } } impl<'a> ::flatbuffers::Verifiable for AB { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - i8::run_verifier(v, pos) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + i8::run_verifier(v, pos) + } } impl ::flatbuffers::SimpleToVerifyInSlice for AB {} diff --git a/tests/private_annotation_test/annotations_generated.rs b/tests/private_annotation_test/annotations_generated.rs index 3c6a7a758..3db01a9fb 100644 --- a/tests/private_annotation_test/annotations_generated.rs +++ b/tests/private_annotation_test/annotations_generated.rs @@ -2,143 +2,132 @@ // @generated extern crate alloc; use super::*; - pub(crate) enum AnnotationsOffset {} - #[derive(Copy, Clone, PartialEq)] + pub(crate) struct Annotations<'a> { - pub _tab: ::flatbuffers::Table<'a>, + pub _tab: ::flatbuffers::Table<'a>, } impl<'a> ::flatbuffers::Follow<'a> for Annotations<'a> { - type Inner = Annotations<'a>; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } - } + type Inner = Annotations<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } + } } impl<'a> Annotations<'a> { - pub const VT_VALUE: ::flatbuffers::VOffsetT = 4; + pub const VT_VALUE: ::flatbuffers::VOffsetT = 4; - pub const fn get_fully_qualified_name() -> &'static str { - "Annotations" - } + pub const fn get_fully_qualified_name() -> &'static str { + "Annotations" + } - #[inline] - pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { - Annotations { _tab: table } - } + #[inline] + pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { + Annotations { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args AnnotationsArgs + ) -> ::flatbuffers::WIPOffset> { + let mut builder = AnnotationsBuilder::new(_fbb); + builder.add_value(args.value); + builder.finish() + } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args AnnotationsArgs - ) -> ::flatbuffers::WIPOffset> { - let mut builder = AnnotationsBuilder::new(_fbb); - builder.add_value(args.value); - builder.finish() + pub fn unpack(&self) -> AnnotationsT { + let value = self.value(); + AnnotationsT { + value, } + } - pub fn unpack(&self) -> AnnotationsT { - let value = self.value(); - AnnotationsT { - value, - } - } - - #[inline] - pub fn value(&self) -> i32 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Annotations::VT_VALUE, Some(0)).unwrap()} - } + #[inline] + pub fn value(&self) -> i32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Annotations::VT_VALUE, Some(0)).unwrap()} + } } impl ::flatbuffers::Verifiable for Annotations<'_> { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.visit_table(pos)? - .visit_field::("value", Self::VT_VALUE, false)? - .finish(); - Ok(()) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.visit_table(pos)? + .visit_field::("value", Self::VT_VALUE, false)? + .finish(); + Ok(()) + } } - pub(crate) struct AnnotationsArgs { pub value: i32, } - impl<'a> Default for AnnotationsArgs { - #[inline] - fn default() -> Self { - AnnotationsArgs { - value: 0, - } + #[inline] + fn default() -> Self { + AnnotationsArgs { + value: 0, } + } } pub(crate) struct AnnotationsBuilder<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> { - fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, + fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, + start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, } - impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> AnnotationsBuilder<'a, 'b, A> { - #[inline] - pub fn add_value(&mut self, value: i32) { - self.fbb_.push_slot::(Annotations::VT_VALUE, value, 0); - } - - #[inline] - pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> AnnotationsBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - AnnotationsBuilder { - fbb_: _fbb, - start_: start, - } - } - - #[inline] - pub fn finish(self) -> ::flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - ::flatbuffers::WIPOffset::new(o.value()) + #[inline] + pub fn add_value(&mut self, value: i32) { + self.fbb_.push_slot::(Annotations::VT_VALUE, value, 0); + } + #[inline] + pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> AnnotationsBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + AnnotationsBuilder { + fbb_: _fbb, + start_: start, } + } + #[inline] + pub fn finish(self) -> ::flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + ::flatbuffers::WIPOffset::new(o.value()) + } } impl ::core::fmt::Debug for Annotations<'_> { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - let mut ds = f.debug_struct("Annotations"); - ds.field("value", &self.value()); - ds.finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + let mut ds = f.debug_struct("Annotations"); + ds.field("value", &self.value()); + ds.finish() + } } - #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub(crate) struct AnnotationsT { - pub value: i32, + pub value: i32, } - impl Default for AnnotationsT { - fn default() -> Self { - Self { - value: 0, - } + fn default() -> Self { + Self { + value: 0, } + } } - impl AnnotationsT { - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( - &self, - _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> - ) -> ::flatbuffers::WIPOffset> { - let value = self.value; - Annotations::create(_fbb, &AnnotationsArgs{ - value, - }) - } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> + ) -> ::flatbuffers::WIPOffset> { + let value = self.value; + Annotations::create(_fbb, &AnnotationsArgs{ + value, + }) + } } diff --git a/tests/private_annotation_test/any_generated.rs b/tests/private_annotation_test/any_generated.rs index 33f6764ad..dd6aed8a2 100644 --- a/tests/private_annotation_test/any_generated.rs +++ b/tests/private_annotation_test/any_generated.rs @@ -2,73 +2,64 @@ // @generated extern crate alloc; use super::*; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] pub const ENUM_MIN_ANY: u8 = 0; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] pub const ENUM_MAX_ANY: u8 = 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_ANY: [Any; 3] = [ - Any::NONE, - Any::Game, - Any::Annotations, + Any::NONE, + Any::Game, + Any::Annotations, ]; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] #[repr(transparent)] pub(crate) struct Any(pub u8); - #[allow(non_upper_case_globals)] impl Any { - pub const NONE: Self = Self(0); - pub const Game: Self = Self(1); - pub const Annotations: Self = Self(2); + pub const NONE: Self = Self(0); + pub const Game: Self = Self(1); + pub const Annotations: Self = Self(2); - pub const ENUM_MIN: u8 = 0; - pub const ENUM_MAX: u8 = 2; - pub const ENUM_VALUES: &'static [Self] = &[ - Self::NONE, - Self::Game, - Self::Annotations, - ]; - - /// Returns the variant's name or "" if unknown. - pub fn variant_name(self) -> Option<&'static str> { - match self { - Self::NONE => Some("NONE"), - Self::Game => Some("Game"), - Self::Annotations => Some("Annotations"), - _ => None, - } + pub const ENUM_MIN: u8 = 0; + pub const ENUM_MAX: u8 = 2; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::NONE, + Self::Game, + Self::Annotations, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::NONE => Some("NONE"), + Self::Game => Some("Game"), + Self::Annotations => Some("Annotations"), + _ => None, } + } } - impl ::core::fmt::Debug for Any { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - if let Some(name) = self.variant_name() { - f.write_str(name) - } else { - f.write_fmt(format_args!("", self.0)) - } + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) } + } } - impl<'a> ::flatbuffers::Follow<'a> for Any { - type Inner = Self; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; - Self(b) - } + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; + Self(b) + } } impl ::flatbuffers::Push for Any { type Output = Any; - #[inline] unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { unsafe { ::flatbuffers::emplace_scalar::(dst, self.0) }; @@ -76,112 +67,99 @@ impl ::flatbuffers::Push for Any { } impl ::flatbuffers::EndianScalar for Any { - type Scalar = u8; - - #[inline] - fn to_little_endian(self) -> u8 { - self.0.to_le() - } - - #[inline] - #[allow(clippy::wrong_self_convention)] - fn from_little_endian(v: u8) -> Self { - let b = u8::from_le(v); - Self(b) - } + type Scalar = u8; + #[inline] + fn to_little_endian(self) -> u8 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: u8) -> Self { + let b = u8::from_le(v); + Self(b) + } } impl<'a> ::flatbuffers::Verifiable for Any { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - u8::run_verifier(v, pos) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + u8::run_verifier(v, pos) + } } impl ::flatbuffers::SimpleToVerifyInSlice for Any {} - pub(crate) struct AnyUnionTableOffset {} #[allow(clippy::upper_case_acronyms)] #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub(crate) enum AnyT { - NONE, - Game(alloc::boxed::Box), - Annotations(alloc::boxed::Box), + NONE, + Game(alloc::boxed::Box), + Annotations(alloc::boxed::Box), } - impl Default for AnyT { - fn default() -> Self { - Self::NONE - } + fn default() -> Self { + Self::NONE + } } - impl AnyT { - pub fn any_type(&self) -> Any { - match self { - Self::NONE => Any::NONE, - Self::Game(_) => Any::Game, - Self::Annotations(_) => Any::Annotations, - } + pub fn any_type(&self) -> Any { + match self { + Self::NONE => Any::NONE, + Self::Game(_) => Any::Game, + Self::Annotations(_) => Any::Annotations, } - - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>(&self, fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A>) -> Option<::flatbuffers::WIPOffset<::flatbuffers::UnionWIPOffset>> { - match self { - Self::NONE => None, - Self::Game(v) => Some(v.pack(fbb).as_union_value()), - Self::Annotations(v) => Some(v.pack(fbb).as_union_value()), - } + } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>(&self, fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A>) -> Option<::flatbuffers::WIPOffset<::flatbuffers::UnionWIPOffset>> { + match self { + Self::NONE => None, + Self::Game(v) => Some(v.pack(fbb).as_union_value()), + Self::Annotations(v) => Some(v.pack(fbb).as_union_value()), } - - /// If the union variant matches, return the owned GameT, setting the union to NONE. - pub fn take_game(&mut self) -> Option> { - if let Self::Game(_) = self { - let v = ::core::mem::replace(self, Self::NONE); - if let Self::Game(w) = v { - Some(w) - } else { - unreachable!() - } - } else { - None - } + } + /// If the union variant matches, return the owned GameT, setting the union to NONE. + pub fn take_game(&mut self) -> Option> { + if let Self::Game(_) = self { + let v = ::core::mem::replace(self, Self::NONE); + if let Self::Game(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None } - - /// If the union variant matches, return a reference to the GameT. - pub fn as_game(&self) -> Option<&GameT> { - if let Self::Game(v) = self { Some(v.as_ref()) } else { None } - } - - /// If the union variant matches, return a mutable reference to the GameT. - pub fn as_game_mut(&mut self) -> Option<&mut GameT> { - if let Self::Game(v) = self { Some(v.as_mut()) } else { None } - } - - /// If the union variant matches, return the owned AnnotationsT, setting the union to NONE. - pub fn take_annotations(&mut self) -> Option> { - if let Self::Annotations(_) = self { - let v = ::core::mem::replace(self, Self::NONE); - if let Self::Annotations(w) = v { - Some(w) - } else { - unreachable!() - } - } else { - None - } - } - - /// If the union variant matches, return a reference to the AnnotationsT. - pub fn as_annotations(&self) -> Option<&AnnotationsT> { - if let Self::Annotations(v) = self { Some(v.as_ref()) } else { None } - } - - /// If the union variant matches, return a mutable reference to the AnnotationsT. - pub fn as_annotations_mut(&mut self) -> Option<&mut AnnotationsT> { - if let Self::Annotations(v) = self { Some(v.as_mut()) } else { None } + } + /// If the union variant matches, return a reference to the GameT. + pub fn as_game(&self) -> Option<&GameT> { + if let Self::Game(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the GameT. + pub fn as_game_mut(&mut self) -> Option<&mut GameT> { + if let Self::Game(v) = self { Some(v.as_mut()) } else { None } + } + /// If the union variant matches, return the owned AnnotationsT, setting the union to NONE. + pub fn take_annotations(&mut self) -> Option> { + if let Self::Annotations(_) = self { + let v = ::core::mem::replace(self, Self::NONE); + if let Self::Annotations(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None } + } + /// If the union variant matches, return a reference to the AnnotationsT. + pub fn as_annotations(&self) -> Option<&AnnotationsT> { + if let Self::Annotations(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the AnnotationsT. + pub fn as_annotations_mut(&mut self) -> Option<&mut AnnotationsT> { + if let Self::Annotations(v) = self { Some(v.as_mut()) } else { None } + } } - diff --git a/tests/private_annotation_test/game_generated.rs b/tests/private_annotation_test/game_generated.rs index c15574d6a..b43ce1885 100644 --- a/tests/private_annotation_test/game_generated.rs +++ b/tests/private_annotation_test/game_generated.rs @@ -2,143 +2,132 @@ // @generated extern crate alloc; use super::*; - pub(crate) enum GameOffset {} - #[derive(Copy, Clone, PartialEq)] + pub(crate) struct Game<'a> { - pub _tab: ::flatbuffers::Table<'a>, + pub _tab: ::flatbuffers::Table<'a>, } impl<'a> ::flatbuffers::Follow<'a> for Game<'a> { - type Inner = Game<'a>; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } - } + type Inner = Game<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } + } } impl<'a> Game<'a> { - pub const VT_VALUE: ::flatbuffers::VOffsetT = 4; + pub const VT_VALUE: ::flatbuffers::VOffsetT = 4; - pub const fn get_fully_qualified_name() -> &'static str { - "Game" - } + pub const fn get_fully_qualified_name() -> &'static str { + "Game" + } - #[inline] - pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { - Game { _tab: table } - } + #[inline] + pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { + Game { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args GameArgs + ) -> ::flatbuffers::WIPOffset> { + let mut builder = GameBuilder::new(_fbb); + builder.add_value(args.value); + builder.finish() + } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args GameArgs - ) -> ::flatbuffers::WIPOffset> { - let mut builder = GameBuilder::new(_fbb); - builder.add_value(args.value); - builder.finish() + pub fn unpack(&self) -> GameT { + let value = self.value(); + GameT { + value, } + } - pub fn unpack(&self) -> GameT { - let value = self.value(); - GameT { - value, - } - } - - #[inline] - pub fn value(&self) -> i32 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(Game::VT_VALUE, Some(0)).unwrap()} - } + #[inline] + pub fn value(&self) -> i32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Game::VT_VALUE, Some(0)).unwrap()} + } } impl ::flatbuffers::Verifiable for Game<'_> { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.visit_table(pos)? - .visit_field::("value", Self::VT_VALUE, false)? - .finish(); - Ok(()) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.visit_table(pos)? + .visit_field::("value", Self::VT_VALUE, false)? + .finish(); + Ok(()) + } } - pub(crate) struct GameArgs { pub value: i32, } - impl<'a> Default for GameArgs { - #[inline] - fn default() -> Self { - GameArgs { - value: 0, - } + #[inline] + fn default() -> Self { + GameArgs { + value: 0, } + } } pub(crate) struct GameBuilder<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> { - fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, + fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, + start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, } - impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> GameBuilder<'a, 'b, A> { - #[inline] - pub fn add_value(&mut self, value: i32) { - self.fbb_.push_slot::(Game::VT_VALUE, value, 0); - } - - #[inline] - pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> GameBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - GameBuilder { - fbb_: _fbb, - start_: start, - } - } - - #[inline] - pub fn finish(self) -> ::flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - ::flatbuffers::WIPOffset::new(o.value()) + #[inline] + pub fn add_value(&mut self, value: i32) { + self.fbb_.push_slot::(Game::VT_VALUE, value, 0); + } + #[inline] + pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> GameBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + GameBuilder { + fbb_: _fbb, + start_: start, } + } + #[inline] + pub fn finish(self) -> ::flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + ::flatbuffers::WIPOffset::new(o.value()) + } } impl ::core::fmt::Debug for Game<'_> { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - let mut ds = f.debug_struct("Game"); - ds.field("value", &self.value()); - ds.finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + let mut ds = f.debug_struct("Game"); + ds.field("value", &self.value()); + ds.finish() + } } - #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub(crate) struct GameT { - pub value: i32, + pub value: i32, } - impl Default for GameT { - fn default() -> Self { - Self { - value: 0, - } + fn default() -> Self { + Self { + value: 0, } + } } - impl GameT { - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( - &self, - _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> - ) -> ::flatbuffers::WIPOffset> { - let value = self.value; - Game::create(_fbb, &GameArgs{ - value, - }) - } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> + ) -> ::flatbuffers::WIPOffset> { + let value = self.value; + Game::create(_fbb, &GameArgs{ + value, + }) + } } diff --git a/tests/private_annotation_test/object_generated.rs b/tests/private_annotation_test/object_generated.rs index 05c18ac07..5e98d9927 100644 --- a/tests/private_annotation_test/object_generated.rs +++ b/tests/private_annotation_test/object_generated.rs @@ -2,55 +2,45 @@ // @generated extern crate alloc; use super::*; - // struct Object, aligned to 4 #[repr(transparent)] #[derive(Clone, Copy, PartialEq)] pub(crate) struct Object(pub [u8; 4]); - -impl Default for Object { - fn default() -> Self { - Self([0; 4]) - } +impl Default for Object { + fn default() -> Self { + Self([0; 4]) + } } - impl ::core::fmt::Debug for Object { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - f.debug_struct("Object") - .field("value", &self.value()) - .finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + f.debug_struct("Object") + .field("value", &self.value()) + .finish() + } } impl ::flatbuffers::SimpleToVerifyInSlice for Object {} - impl<'a> ::flatbuffers::Follow<'a> for Object { - type Inner = &'a Object; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - unsafe { <&'a Object>::follow(buf, loc) } - } + type Inner = &'a Object; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { <&'a Object>::follow(buf, loc) } + } } - impl<'a> ::flatbuffers::Follow<'a> for &'a Object { - type Inner = &'a Object; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - unsafe { ::flatbuffers::follow_cast_ref::(buf, loc) } - } + type Inner = &'a Object; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { ::flatbuffers::follow_cast_ref::(buf, loc) } + } } - impl<'b> ::flatbuffers::Push for Object { type Output = Object; - #[inline] unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { let src = unsafe { ::core::slice::from_raw_parts(self as *const Object as *const u8, ::size()) }; dst.copy_from_slice(src); } - #[inline] fn alignment() -> ::flatbuffers::PushAlignment { ::flatbuffers::PushAlignment::new(4) @@ -58,80 +48,73 @@ impl<'b> ::flatbuffers::Push for Object { } impl<'a> ::flatbuffers::Verifiable for Object { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.in_buffer::(pos) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.in_buffer::(pos) + } } impl<'a> Object { - #[allow(clippy::too_many_arguments)] - pub fn new( - value: i32, - ) -> Self { - let mut s = Self([0; 4]); - s.set_value(value); - s - } + #[allow(clippy::too_many_arguments)] + pub fn new( + value: i32, + ) -> Self { + let mut s = Self([0; 4]); + s.set_value(value); + s + } - pub const fn get_fully_qualified_name() -> &'static str { - "Object" - } + pub const fn get_fully_qualified_name() -> &'static str { + "Object" + } - pub fn value(&self) -> i32 { - let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - ::flatbuffers::EndianScalar::from_little_endian(unsafe { - ::core::ptr::copy_nonoverlapping( - self.0[0..].as_ptr(), - mem.as_mut_ptr() as *mut u8, - ::core::mem::size_of::<::Scalar>(), - ); - mem.assume_init() - }) - } + pub fn value(&self) -> i32 { + let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + ::flatbuffers::EndianScalar::from_little_endian(unsafe { + ::core::ptr::copy_nonoverlapping( + self.0[0..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + ::core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } - pub fn set_value(&mut self, x: i32) { - let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - unsafe { - ::core::ptr::copy_nonoverlapping( - &x_le as *const _ as *const u8, - self.0[0..].as_mut_ptr(), - ::core::mem::size_of::<::Scalar>(), - ); - } + pub fn set_value(&mut self, x: i32) { + let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + ::core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[0..].as_mut_ptr(), + ::core::mem::size_of::<::Scalar>(), + ); } + } - pub fn unpack(&self) -> ObjectT { - ObjectT { - value: self.value(), - } + pub fn unpack(&self) -> ObjectT { + ObjectT { + value: self.value(), } + } } -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Default)] pub(crate) struct ObjectT { - pub value: i32, + pub value: i32, } -impl Default for ObjectT { - fn default() -> Self { - Self { - value: 0, - } - } +impl ObjectT { + pub fn pack(&self) -> Object { + Object::new( + self.value, + ) + } } -impl ObjectT { - pub fn pack(&self) -> Object { - Object::new( - self.value, - ) - } -} diff --git a/tests/py_test.py b/tests/py_test.py index 0be617785..fb483816b 100644 --- a/tests/py_test.py +++ b/tests/py_test.py @@ -55,10 +55,6 @@ import MyGame.Example.NestedUnion.Color # refers to generated code import monster_test_generated # the one-file version import optional_scalars import optional_scalars.ScalarStuff -import union_name_test.Container # refers to generated code -import union_name_test.Foo # refers to generated code -import union_name_test.Bar # refers to generated code -import union_name_test.my_test_union # refers to generated code def create_namespace_shortcut(is_onefile): @@ -3024,50 +3020,6 @@ class TestNestedUnionTables(unittest.TestCase): ) -class TestUnionCreatorNaming(unittest.TestCase): - """Tests that union creator functions use consistent naming (issue #8843). - - Uses a schema with a snake_case union name (my_test_union) to verify that - the generated creator function name matches between definition and call site. - """ - - def test_union_creator_pack_unpack(self): - """Pack and UnPack a table with a non-UpperCamel union name.""" - containerT = union_name_test.Container.ContainerT() - containerT.uType = union_name_test.my_test_union.my_test_union.Foo - containerT.u = union_name_test.Foo.FooT() - containerT.u.val = 42 - - b = flatbuffers.Builder(0) - b.Finish(containerT.Pack(b)) - - container = union_name_test.Container.Container.GetRootAs( - b.Bytes, b.Head() - ) - containerT2 = union_name_test.Container.ContainerT.InitFromObj(container) - - self.assertEqual(containerT2.uType, union_name_test.my_test_union.my_test_union.Foo) - self.assertEqual(containerT2.u.val, 42) - - def test_union_creator_with_bar(self): - """Test the other union variant to ensure all branches work.""" - containerT = union_name_test.Container.ContainerT() - containerT.uType = union_name_test.my_test_union.my_test_union.Bar - containerT.u = union_name_test.Bar.BarT() - containerT.u.name = "hello" - - b = flatbuffers.Builder(0) - b.Finish(containerT.Pack(b)) - - container = union_name_test.Container.Container.GetRootAs( - b.Bytes, b.Head() - ) - containerT2 = union_name_test.Container.ContainerT.InitFromObj(container) - - self.assertEqual(containerT2.uType, union_name_test.my_test_union.my_test_union.Bar) - self.assertEqual(containerT2.u.name, b"hello") - - class TestBuilderClear(unittest.TestCase): def test_consistency(self): diff --git a/tests/reflection_test.cpp b/tests/reflection_test.cpp index 9f80b936c..1c4891852 100644 --- a/tests/reflection_test.cpp +++ b/tests/reflection_test.cpp @@ -248,93 +248,6 @@ void ReflectionTest(const std::string& tests_data_path, uint8_t* flatbuf, true); } -// Test that ForAllFields with reverse=true iterates fields in descending -// ID order. This exercises a fix for an operator precedence bug where the -// expression `size() - i + 1` was evaluated as `(size() - i) + 1` instead -// of the correct `size() - (i + 1)`, causing an out-of-bounds read. -void ForAllFieldsReverseTest(const std::string& tests_data_path) { - // Load the binary schema. - std::string bfbsfile; - TEST_EQ(flatbuffers::LoadFile((tests_data_path + "monster_test.bfbs").c_str(), - true, &bfbsfile), - true); - - // Verify the schema. - flatbuffers::Verifier verifier( - reinterpret_cast(bfbsfile.c_str()), bfbsfile.length()); - TEST_EQ(reflection::VerifySchemaBuffer(verifier), true); - - auto& schema = *reflection::GetSchema(bfbsfile.c_str()); - - // Use the Stat table which has 3 fields with sequential IDs: - // id:string (id: 0) - // val:long (id: 1) - // count:ushort (id: 2) - auto stat_object = schema.objects()->LookupByKey("MyGame.Example.Stat"); - TEST_NOTNULL(stat_object); - TEST_EQ(stat_object->fields()->size(), 3u); - - // Test forward iteration: fields should come in ascending ID order (0,1,2). - { - std::vector forward_ids; - flatbuffers::ForAllFields( - stat_object, /*reverse=*/false, - [&forward_ids](const reflection::Field* field) { - forward_ids.push_back(field->id()); - }); - TEST_EQ(forward_ids.size(), 3u); - TEST_EQ(forward_ids[0], 0); // id - TEST_EQ(forward_ids[1], 1); // val - TEST_EQ(forward_ids[2], 2); // count - } - - // Test reverse iteration: fields should come in descending ID order (2,1,0). - // With the old buggy code `size() - i + 1`, at i=0 this would compute - // index 3 - 0 + 1 = 4, which is out of bounds for a size-3 vector. - { - std::vector reverse_ids; - flatbuffers::ForAllFields( - stat_object, /*reverse=*/true, - [&reverse_ids](const reflection::Field* field) { - reverse_ids.push_back(field->id()); - }); - TEST_EQ(reverse_ids.size(), 3u); - TEST_EQ(reverse_ids[0], 2); // count (highest ID first) - TEST_EQ(reverse_ids[1], 1); // val - TEST_EQ(reverse_ids[2], 0); // id (lowest ID last) - } - - // Also test with the root Monster table which has many fields and - // non-sequential definition order vs. ID order (e.g., pos=id:0, hp=id:2, - // mana=id:1). This ensures the ID-to-index mapping works correctly. - auto root_table = schema.root_table(); - TEST_NOTNULL(root_table); - { - std::vector forward_ids; - flatbuffers::ForAllFields( - root_table, /*reverse=*/false, - [&forward_ids](const reflection::Field* field) { - forward_ids.push_back(field->id()); - }); - // Verify ascending order. - for (size_t i = 1; i < forward_ids.size(); ++i) { - TEST_ASSERT(forward_ids[i - 1] < forward_ids[i]); - } - } - { - std::vector reverse_ids; - flatbuffers::ForAllFields( - root_table, /*reverse=*/true, - [&reverse_ids](const reflection::Field* field) { - reverse_ids.push_back(field->id()); - }); - // Verify descending order. - for (size_t i = 1; i < reverse_ids.size(); ++i) { - TEST_ASSERT(reverse_ids[i - 1] > reverse_ids[i]); - } - } -} - void MiniReflectFlatBuffersTest(uint8_t* flatbuf) { auto s = flatbuffers::FlatBufferToString(flatbuf, Monster::MiniReflectTypeTable()); diff --git a/tests/reflection_test.h b/tests/reflection_test.h index da6fb1ff6..fa6f470c6 100644 --- a/tests/reflection_test.h +++ b/tests/reflection_test.h @@ -10,7 +10,6 @@ namespace tests { void ReflectionTest(const std::string& tests_data_path, uint8_t* flatbuf, size_t length); -void ForAllFieldsReverseTest(const std::string& tests_data_path); void MiniReflectFixedLengthArrayTest(); void MiniReflectFlatBuffersTest(uint8_t* flatbuf); diff --git a/tests/rust_namer_test/mod.rs b/tests/rust_namer_test/mod.rs index 81c761650..f395a5003 100644 --- a/tests/rust_namer_test/mod.rs +++ b/tests/rust_namer_test/mod.rs @@ -1,23 +1,23 @@ // Automatically generated by the Flatbuffers compiler. Do not modify. // @generated pub mod rust_namer_test { - use super::*; - mod field_union_generated; - pub use self::field_union_generated::*; - mod game_message_generated; - pub use self::game_message_generated::*; - mod field_table_generated; - pub use self::field_table_generated::*; - mod root_table_generated; - pub use self::root_table_generated::*; - mod player_stat_event_generated; - pub use self::player_stat_event_generated::*; - mod player_spectate_generated; - pub use self::player_spectate_generated::*; - mod player_input_change_generated; - pub use self::player_input_change_generated::*; - mod game_message_wrapper_generated; - pub use self::game_message_wrapper_generated::*; - mod possibly_reserved_words_generated; - pub use self::possibly_reserved_words_generated::*; + use super::*; + mod field_union_generated; + pub use self::field_union_generated::*; + mod game_message_generated; + pub use self::game_message_generated::*; + mod field_table_generated; + pub use self::field_table_generated::*; + mod root_table_generated; + pub use self::root_table_generated::*; + mod player_stat_event_generated; + pub use self::player_stat_event_generated::*; + mod player_spectate_generated; + pub use self::player_spectate_generated::*; + mod player_input_change_generated; + pub use self::player_input_change_generated::*; + mod game_message_wrapper_generated; + pub use self::game_message_wrapper_generated::*; + mod possibly_reserved_words_generated; + pub use self::possibly_reserved_words_generated::*; } // rust_namer_test diff --git a/tests/rust_namer_test/rust_namer_test/field_table_generated.rs b/tests/rust_namer_test/rust_namer_test/field_table_generated.rs index 5b21b2eb3..63256505b 100644 --- a/tests/rust_namer_test/rust_namer_test/field_table_generated.rs +++ b/tests/rust_namer_test/rust_namer_test/field_table_generated.rs @@ -2,117 +2,108 @@ // @generated extern crate alloc; use super::*; - pub enum FieldTableOffset {} - #[derive(Copy, Clone, PartialEq)] + pub struct FieldTable<'a> { - pub _tab: ::flatbuffers::Table<'a>, + pub _tab: ::flatbuffers::Table<'a>, } impl<'a> ::flatbuffers::Follow<'a> for FieldTable<'a> { - type Inner = FieldTable<'a>; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } - } + type Inner = FieldTable<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } + } } impl<'a> FieldTable<'a> { - pub const fn get_fully_qualified_name() -> &'static str { - "RustNamerTest.FieldTable" - } - #[inline] - pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { - FieldTable { _tab: table } - } + pub const fn get_fully_qualified_name() -> &'static str { + "RustNamerTest.FieldTable" + } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, - _args: &'args FieldTableArgs - ) -> ::flatbuffers::WIPOffset> { - let mut builder = FieldTableBuilder::new(_fbb); - builder.finish() - } + #[inline] + pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { + FieldTable { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, + _args: &'args FieldTableArgs + ) -> ::flatbuffers::WIPOffset> { + let mut builder = FieldTableBuilder::new(_fbb); + builder.finish() + } - pub fn unpack(&self) -> FieldTableT { - FieldTableT { - } + pub fn unpack(&self) -> FieldTableT { + FieldTableT { } + } } impl ::flatbuffers::Verifiable for FieldTable<'_> { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.visit_table(pos)? - .finish(); - Ok(()) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.visit_table(pos)? + .finish(); + Ok(()) + } } - pub struct FieldTableArgs { } - impl<'a> Default for FieldTableArgs { - #[inline] - fn default() -> Self { - FieldTableArgs { - } + #[inline] + fn default() -> Self { + FieldTableArgs { } + } } pub struct FieldTableBuilder<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> { - fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, + fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, + start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, } - impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> FieldTableBuilder<'a, 'b, A> { - #[inline] - pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> FieldTableBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - FieldTableBuilder { - fbb_: _fbb, - start_: start, - } - } - - #[inline] - pub fn finish(self) -> ::flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - ::flatbuffers::WIPOffset::new(o.value()) + #[inline] + pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> FieldTableBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + FieldTableBuilder { + fbb_: _fbb, + start_: start, } + } + #[inline] + pub fn finish(self) -> ::flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + ::flatbuffers::WIPOffset::new(o.value()) + } } impl ::core::fmt::Debug for FieldTable<'_> { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - let mut ds = f.debug_struct("FieldTable"); - ds.finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + let mut ds = f.debug_struct("FieldTable"); + ds.finish() + } } - #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub struct FieldTableT { } - impl Default for FieldTableT { - fn default() -> Self { - Self { - } + fn default() -> Self { + Self { } + } } - impl FieldTableT { - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( - &self, - _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> - ) -> ::flatbuffers::WIPOffset> { - FieldTable::create(_fbb, &FieldTableArgs{ - }) - } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> + ) -> ::flatbuffers::WIPOffset> { + FieldTable::create(_fbb, &FieldTableArgs{ + }) + } } diff --git a/tests/rust_namer_test/rust_namer_test/field_union_generated.rs b/tests/rust_namer_test/rust_namer_test/field_union_generated.rs index 22fa546df..70883590b 100644 --- a/tests/rust_namer_test/rust_namer_test/field_union_generated.rs +++ b/tests/rust_namer_test/rust_namer_test/field_union_generated.rs @@ -2,69 +2,60 @@ // @generated extern crate alloc; use super::*; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] pub const ENUM_MIN_FIELD_UNION: u8 = 0; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] pub const ENUM_MAX_FIELD_UNION: 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_FIELD_UNION: [FieldUnion; 2] = [ - FieldUnion::NONE, - FieldUnion::f, + FieldUnion::NONE, + FieldUnion::f, ]; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] #[repr(transparent)] pub struct FieldUnion(pub u8); - #[allow(non_upper_case_globals)] impl FieldUnion { - pub const NONE: Self = Self(0); - pub const f: Self = Self(1); + pub const NONE: Self = Self(0); + pub const f: Self = Self(1); - pub const ENUM_MIN: u8 = 0; - pub const ENUM_MAX: u8 = 1; - pub const ENUM_VALUES: &'static [Self] = &[ - Self::NONE, - Self::f, - ]; - - /// Returns the variant's name or "" if unknown. - pub fn variant_name(self) -> Option<&'static str> { - match self { - Self::NONE => Some("NONE"), - Self::f => Some("f"), - _ => None, - } + pub const ENUM_MIN: u8 = 0; + pub const ENUM_MAX: u8 = 1; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::NONE, + Self::f, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::NONE => Some("NONE"), + Self::f => Some("f"), + _ => None, } + } } - impl ::core::fmt::Debug for FieldUnion { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - if let Some(name) = self.variant_name() { - f.write_str(name) - } else { - f.write_fmt(format_args!("", self.0)) - } + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) } + } } - impl<'a> ::flatbuffers::Follow<'a> for FieldUnion { - type Inner = Self; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; - Self(b) - } + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; + Self(b) + } } impl ::flatbuffers::Push for FieldUnion { type Output = FieldUnion; - #[inline] unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { unsafe { ::flatbuffers::emplace_scalar::(dst, self.0) }; @@ -72,85 +63,75 @@ impl ::flatbuffers::Push for FieldUnion { } impl ::flatbuffers::EndianScalar for FieldUnion { - type Scalar = u8; - - #[inline] - fn to_little_endian(self) -> u8 { - self.0.to_le() - } - - #[inline] - #[allow(clippy::wrong_self_convention)] - fn from_little_endian(v: u8) -> Self { - let b = u8::from_le(v); - Self(b) - } + type Scalar = u8; + #[inline] + fn to_little_endian(self) -> u8 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: u8) -> Self { + let b = u8::from_le(v); + Self(b) + } } impl<'a> ::flatbuffers::Verifiable for FieldUnion { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - u8::run_verifier(v, pos) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + u8::run_verifier(v, pos) + } } impl ::flatbuffers::SimpleToVerifyInSlice for FieldUnion {} - pub struct FieldUnionUnionTableOffset {} #[allow(clippy::upper_case_acronyms)] #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub enum FieldUnionT { - NONE, - F(alloc::boxed::Box), + NONE, + F(alloc::boxed::Box), } - impl Default for FieldUnionT { - fn default() -> Self { - Self::NONE - } + fn default() -> Self { + Self::NONE + } } - impl FieldUnionT { - pub fn field_union_type(&self) -> FieldUnion { - match self { - Self::NONE => FieldUnion::NONE, - Self::F(_) => FieldUnion::f, - } + pub fn field_union_type(&self) -> FieldUnion { + match self { + Self::NONE => FieldUnion::NONE, + Self::F(_) => FieldUnion::f, } - - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>(&self, fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A>) -> Option<::flatbuffers::WIPOffset<::flatbuffers::UnionWIPOffset>> { - match self { - Self::NONE => None, - Self::F(v) => Some(v.pack(fbb).as_union_value()), - } + } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>(&self, fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A>) -> Option<::flatbuffers::WIPOffset<::flatbuffers::UnionWIPOffset>> { + match self { + Self::NONE => None, + Self::F(v) => Some(v.pack(fbb).as_union_value()), } - - /// If the union variant matches, return the owned FieldTableT, setting the union to NONE. - pub fn take_f(&mut self) -> Option> { - if let Self::F(_) = self { - let v = ::core::mem::replace(self, Self::NONE); - if let Self::F(w) = v { - Some(w) - } else { - unreachable!() - } - } else { - None - } - } - - /// If the union variant matches, return a reference to the FieldTableT. - pub fn as_f(&self) -> Option<&FieldTableT> { - if let Self::F(v) = self { Some(v.as_ref()) } else { None } - } - - /// If the union variant matches, return a mutable reference to the FieldTableT. - pub fn as_f_mut(&mut self) -> Option<&mut FieldTableT> { - if let Self::F(v) = self { Some(v.as_mut()) } else { None } + } + /// If the union variant matches, return the owned FieldTableT, setting the union to NONE. + pub fn take_f(&mut self) -> Option> { + if let Self::F(_) = self { + let v = ::core::mem::replace(self, Self::NONE); + if let Self::F(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None } + } + /// If the union variant matches, return a reference to the FieldTableT. + pub fn as_f(&self) -> Option<&FieldTableT> { + if let Self::F(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the FieldTableT. + pub fn as_f_mut(&mut self) -> Option<&mut FieldTableT> { + if let Self::F(v) = self { Some(v.as_mut()) } else { None } + } } - diff --git a/tests/rust_namer_test/rust_namer_test/game_message_generated.rs b/tests/rust_namer_test/rust_namer_test/game_message_generated.rs index 563cdcd87..47d0a990a 100644 --- a/tests/rust_namer_test/rust_namer_test/game_message_generated.rs +++ b/tests/rust_namer_test/rust_namer_test/game_message_generated.rs @@ -2,77 +2,68 @@ // @generated extern crate alloc; use super::*; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] pub const ENUM_MIN_GAME_MESSAGE: u8 = 0; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] pub const ENUM_MAX_GAME_MESSAGE: u8 = 3; - #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] #[allow(non_camel_case_types)] pub const ENUM_VALUES_GAME_MESSAGE: [GameMessage; 4] = [ - GameMessage::NONE, - GameMessage::PlayerStatEvent, - GameMessage::PlayerSpectate, - GameMessage::PlayerInputChange, + GameMessage::NONE, + GameMessage::PlayerStatEvent, + GameMessage::PlayerSpectate, + GameMessage::PlayerInputChange, ]; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] #[repr(transparent)] pub struct GameMessage(pub u8); - #[allow(non_upper_case_globals)] impl GameMessage { - pub const NONE: Self = Self(0); - pub const PlayerStatEvent: Self = Self(1); - pub const PlayerSpectate: Self = Self(2); - pub const PlayerInputChange: Self = Self(3); + pub const NONE: Self = Self(0); + pub const PlayerStatEvent: Self = Self(1); + pub const PlayerSpectate: Self = Self(2); + pub const PlayerInputChange: Self = Self(3); - pub const ENUM_MIN: u8 = 0; - pub const ENUM_MAX: u8 = 3; - pub const ENUM_VALUES: &'static [Self] = &[ - Self::NONE, - Self::PlayerStatEvent, - Self::PlayerSpectate, - Self::PlayerInputChange, - ]; - - /// Returns the variant's name or "" if unknown. - pub fn variant_name(self) -> Option<&'static str> { - match self { - Self::NONE => Some("NONE"), - Self::PlayerStatEvent => Some("PlayerStatEvent"), - Self::PlayerSpectate => Some("PlayerSpectate"), - Self::PlayerInputChange => Some("PlayerInputChange"), - _ => None, - } + pub const ENUM_MIN: u8 = 0; + pub const ENUM_MAX: u8 = 3; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::NONE, + Self::PlayerStatEvent, + Self::PlayerSpectate, + Self::PlayerInputChange, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::NONE => Some("NONE"), + Self::PlayerStatEvent => Some("PlayerStatEvent"), + Self::PlayerSpectate => Some("PlayerSpectate"), + Self::PlayerInputChange => Some("PlayerInputChange"), + _ => None, } + } } - impl ::core::fmt::Debug for GameMessage { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - if let Some(name) = self.variant_name() { - f.write_str(name) - } else { - f.write_fmt(format_args!("", self.0)) - } + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) } + } } - impl<'a> ::flatbuffers::Follow<'a> for GameMessage { - type Inner = Self; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; - Self(b) - } + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; + Self(b) + } } impl ::flatbuffers::Push for GameMessage { type Output = GameMessage; - #[inline] unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { unsafe { ::flatbuffers::emplace_scalar::(dst, self.0) }; @@ -80,139 +71,123 @@ impl ::flatbuffers::Push for GameMessage { } impl ::flatbuffers::EndianScalar for GameMessage { - type Scalar = u8; - - #[inline] - fn to_little_endian(self) -> u8 { - self.0.to_le() - } - - #[inline] - #[allow(clippy::wrong_self_convention)] - fn from_little_endian(v: u8) -> Self { - let b = u8::from_le(v); - Self(b) - } + type Scalar = u8; + #[inline] + fn to_little_endian(self) -> u8 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: u8) -> Self { + let b = u8::from_le(v); + Self(b) + } } impl<'a> ::flatbuffers::Verifiable for GameMessage { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - u8::run_verifier(v, pos) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + u8::run_verifier(v, pos) + } } impl ::flatbuffers::SimpleToVerifyInSlice for GameMessage {} - pub struct GameMessageUnionTableOffset {} #[allow(clippy::upper_case_acronyms)] #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub enum GameMessageT { - NONE, - PlayerStatEvent(alloc::boxed::Box), - PlayerSpectate(alloc::boxed::Box), - PlayerInputChange(alloc::boxed::Box), + NONE, + PlayerStatEvent(alloc::boxed::Box), + PlayerSpectate(alloc::boxed::Box), + PlayerInputChange(alloc::boxed::Box), } - impl Default for GameMessageT { - fn default() -> Self { - Self::NONE - } + fn default() -> Self { + Self::NONE + } } - impl GameMessageT { - pub fn game_message_type(&self) -> GameMessage { - match self { - Self::NONE => GameMessage::NONE, - Self::PlayerStatEvent(_) => GameMessage::PlayerStatEvent, - Self::PlayerSpectate(_) => GameMessage::PlayerSpectate, - Self::PlayerInputChange(_) => GameMessage::PlayerInputChange, - } + pub fn game_message_type(&self) -> GameMessage { + match self { + Self::NONE => GameMessage::NONE, + Self::PlayerStatEvent(_) => GameMessage::PlayerStatEvent, + Self::PlayerSpectate(_) => GameMessage::PlayerSpectate, + Self::PlayerInputChange(_) => GameMessage::PlayerInputChange, } - - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>(&self, fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A>) -> Option<::flatbuffers::WIPOffset<::flatbuffers::UnionWIPOffset>> { - match self { - Self::NONE => None, - Self::PlayerStatEvent(v) => Some(v.pack(fbb).as_union_value()), - Self::PlayerSpectate(v) => Some(v.pack(fbb).as_union_value()), - Self::PlayerInputChange(v) => Some(v.pack(fbb).as_union_value()), - } + } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>(&self, fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A>) -> Option<::flatbuffers::WIPOffset<::flatbuffers::UnionWIPOffset>> { + match self { + Self::NONE => None, + Self::PlayerStatEvent(v) => Some(v.pack(fbb).as_union_value()), + Self::PlayerSpectate(v) => Some(v.pack(fbb).as_union_value()), + Self::PlayerInputChange(v) => Some(v.pack(fbb).as_union_value()), } - - /// If the union variant matches, return the owned PlayerStatEventT, setting the union to NONE. - pub fn take_player_stat_event(&mut self) -> Option> { - if let Self::PlayerStatEvent(_) = self { - let v = ::core::mem::replace(self, Self::NONE); - if let Self::PlayerStatEvent(w) = v { - Some(w) - } else { - unreachable!() - } - } else { - None - } + } + /// If the union variant matches, return the owned PlayerStatEventT, setting the union to NONE. + pub fn take_player_stat_event(&mut self) -> Option> { + if let Self::PlayerStatEvent(_) = self { + let v = ::core::mem::replace(self, Self::NONE); + if let Self::PlayerStatEvent(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None } - - /// If the union variant matches, return a reference to the PlayerStatEventT. - pub fn as_player_stat_event(&self) -> Option<&PlayerStatEventT> { - if let Self::PlayerStatEvent(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a reference to the PlayerStatEventT. + pub fn as_player_stat_event(&self) -> Option<&PlayerStatEventT> { + if let Self::PlayerStatEvent(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the PlayerStatEventT. + pub fn as_player_stat_event_mut(&mut self) -> Option<&mut PlayerStatEventT> { + if let Self::PlayerStatEvent(v) = self { Some(v.as_mut()) } else { None } + } + /// If the union variant matches, return the owned PlayerSpectateT, setting the union to NONE. + pub fn take_player_spectate(&mut self) -> Option> { + if let Self::PlayerSpectate(_) = self { + let v = ::core::mem::replace(self, Self::NONE); + if let Self::PlayerSpectate(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None } - - /// If the union variant matches, return a mutable reference to the PlayerStatEventT. - pub fn as_player_stat_event_mut(&mut self) -> Option<&mut PlayerStatEventT> { - if let Self::PlayerStatEvent(v) = self { Some(v.as_mut()) } else { None } - } - - /// If the union variant matches, return the owned PlayerSpectateT, setting the union to NONE. - pub fn take_player_spectate(&mut self) -> Option> { - if let Self::PlayerSpectate(_) = self { - let v = ::core::mem::replace(self, Self::NONE); - if let Self::PlayerSpectate(w) = v { - Some(w) - } else { - unreachable!() - } - } else { - None - } - } - - /// If the union variant matches, return a reference to the PlayerSpectateT. - pub fn as_player_spectate(&self) -> Option<&PlayerSpectateT> { - if let Self::PlayerSpectate(v) = self { Some(v.as_ref()) } else { None } - } - - /// If the union variant matches, return a mutable reference to the PlayerSpectateT. - pub fn as_player_spectate_mut(&mut self) -> Option<&mut PlayerSpectateT> { - if let Self::PlayerSpectate(v) = self { Some(v.as_mut()) } else { None } - } - - /// If the union variant matches, return the owned PlayerInputChangeT, setting the union to NONE. - pub fn take_player_input_change(&mut self) -> Option> { - if let Self::PlayerInputChange(_) = self { - let v = ::core::mem::replace(self, Self::NONE); - if let Self::PlayerInputChange(w) = v { - Some(w) - } else { - unreachable!() - } - } else { - None - } - } - - /// If the union variant matches, return a reference to the PlayerInputChangeT. - pub fn as_player_input_change(&self) -> Option<&PlayerInputChangeT> { - if let Self::PlayerInputChange(v) = self { Some(v.as_ref()) } else { None } - } - - /// If the union variant matches, return a mutable reference to the PlayerInputChangeT. - pub fn as_player_input_change_mut(&mut self) -> Option<&mut PlayerInputChangeT> { - if let Self::PlayerInputChange(v) = self { Some(v.as_mut()) } else { None } + } + /// If the union variant matches, return a reference to the PlayerSpectateT. + pub fn as_player_spectate(&self) -> Option<&PlayerSpectateT> { + if let Self::PlayerSpectate(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the PlayerSpectateT. + pub fn as_player_spectate_mut(&mut self) -> Option<&mut PlayerSpectateT> { + if let Self::PlayerSpectate(v) = self { Some(v.as_mut()) } else { None } + } + /// If the union variant matches, return the owned PlayerInputChangeT, setting the union to NONE. + pub fn take_player_input_change(&mut self) -> Option> { + if let Self::PlayerInputChange(_) = self { + let v = ::core::mem::replace(self, Self::NONE); + if let Self::PlayerInputChange(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None } + } + /// If the union variant matches, return a reference to the PlayerInputChangeT. + pub fn as_player_input_change(&self) -> Option<&PlayerInputChangeT> { + if let Self::PlayerInputChange(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the PlayerInputChangeT. + pub fn as_player_input_change_mut(&mut self) -> Option<&mut PlayerInputChangeT> { + if let Self::PlayerInputChange(v) = self { Some(v.as_mut()) } else { None } + } } - diff --git a/tests/rust_namer_test/rust_namer_test/game_message_wrapper_generated.rs b/tests/rust_namer_test/rust_namer_test/game_message_wrapper_generated.rs index a72cbc539..9c8adbee4 100644 --- a/tests/rust_namer_test/rust_namer_test/game_message_wrapper_generated.rs +++ b/tests/rust_namer_test/rust_namer_test/game_message_wrapper_generated.rs @@ -2,259 +2,246 @@ // @generated extern crate alloc; use super::*; - pub enum GameMessageWrapperOffset {} - #[derive(Copy, Clone, PartialEq)] + pub struct GameMessageWrapper<'a> { - pub _tab: ::flatbuffers::Table<'a>, + pub _tab: ::flatbuffers::Table<'a>, } impl<'a> ::flatbuffers::Follow<'a> for GameMessageWrapper<'a> { - type Inner = GameMessageWrapper<'a>; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } - } + type Inner = GameMessageWrapper<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } + } } impl<'a> GameMessageWrapper<'a> { - pub const VT_MESSAGE_TYPE: ::flatbuffers::VOffsetT = 4; - pub const VT_MESSAGE: ::flatbuffers::VOffsetT = 6; + pub const VT_MESSAGE_TYPE: ::flatbuffers::VOffsetT = 4; + pub const VT_MESSAGE: ::flatbuffers::VOffsetT = 6; - pub const fn get_fully_qualified_name() -> &'static str { - "RustNamerTest.GameMessageWrapper" - } + pub const fn get_fully_qualified_name() -> &'static str { + "RustNamerTest.GameMessageWrapper" + } - #[inline] - pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { - GameMessageWrapper { _tab: table } - } + #[inline] + pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { + GameMessageWrapper { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args GameMessageWrapperArgs + ) -> ::flatbuffers::WIPOffset> { + let mut builder = GameMessageWrapperBuilder::new(_fbb); + if let Some(x) = args.Message { builder.add_Message(x); } + builder.add_Message_type(args.Message_type); + builder.finish() + } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args GameMessageWrapperArgs - ) -> ::flatbuffers::WIPOffset> { - let mut builder = GameMessageWrapperBuilder::new(_fbb); - if let Some(x) = args.Message { builder.add_Message(x); } - builder.add_Message_type(args.Message_type); - builder.finish() + pub fn unpack(&self) -> GameMessageWrapperT { + let Message = match self.Message_type() { + GameMessage::NONE => GameMessageT::NONE, + GameMessage::PlayerStatEvent => GameMessageT::PlayerStatEvent(alloc::boxed::Box::new( + self.Message_as_player_stat_event() + .expect("Invalid union table, expected `GameMessage::PlayerStatEvent`.") + .unpack() + )), + GameMessage::PlayerSpectate => GameMessageT::PlayerSpectate(alloc::boxed::Box::new( + self.Message_as_player_spectate() + .expect("Invalid union table, expected `GameMessage::PlayerSpectate`.") + .unpack() + )), + GameMessage::PlayerInputChange => GameMessageT::PlayerInputChange(alloc::boxed::Box::new( + self.Message_as_player_input_change() + .expect("Invalid union table, expected `GameMessage::PlayerInputChange`.") + .unpack() + )), + _ => GameMessageT::NONE, + }; + GameMessageWrapperT { + Message, } + } - pub fn unpack(&self) -> GameMessageWrapperT { - let Message = match self.Message_type() { - GameMessage::NONE => GameMessageT::NONE, - GameMessage::PlayerStatEvent => GameMessageT::PlayerStatEvent(alloc::boxed::Box::new( - self.Message_as_player_stat_event() - .expect("Invalid union table, expected `GameMessage::PlayerStatEvent`.") - .unpack() - )), - GameMessage::PlayerSpectate => GameMessageT::PlayerSpectate(alloc::boxed::Box::new( - self.Message_as_player_spectate() - .expect("Invalid union table, expected `GameMessage::PlayerSpectate`.") - .unpack() - )), - GameMessage::PlayerInputChange => GameMessageT::PlayerInputChange(alloc::boxed::Box::new( - self.Message_as_player_input_change() - .expect("Invalid union table, expected `GameMessage::PlayerInputChange`.") - .unpack() - )), - _ => GameMessageT::NONE, - }; - GameMessageWrapperT { - Message, - } + #[inline] + pub fn Message_type(&self) -> GameMessage { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(GameMessageWrapper::VT_MESSAGE_TYPE, Some(GameMessage::NONE)).unwrap()} + } + #[inline] + pub fn Message(&self) -> Option<::flatbuffers::Table<'a>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Table<'a>>>(GameMessageWrapper::VT_MESSAGE, None)} + } + #[inline] + #[allow(non_snake_case)] + pub fn Message_as_player_stat_event(&self) -> Option> { + if self.Message_type() == GameMessage::PlayerStatEvent { + self.Message().map(|t| { + // Safety: + // Created from a valid Table for this object + // Which contains a valid union in this slot + unsafe { PlayerStatEvent::init_from_table(t) } + }) + } else { + None } + } - #[inline] - pub fn Message_type(&self) -> GameMessage { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(GameMessageWrapper::VT_MESSAGE_TYPE, Some(GameMessage::NONE)).unwrap()} + #[inline] + #[allow(non_snake_case)] + pub fn Message_as_player_spectate(&self) -> Option> { + if self.Message_type() == GameMessage::PlayerSpectate { + self.Message().map(|t| { + // Safety: + // Created from a valid Table for this object + // Which contains a valid union in this slot + unsafe { PlayerSpectate::init_from_table(t) } + }) + } else { + None } + } - #[inline] - pub fn Message(&self) -> Option<::flatbuffers::Table<'a>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Table<'a>>>(GameMessageWrapper::VT_MESSAGE, None)} + #[inline] + #[allow(non_snake_case)] + pub fn Message_as_player_input_change(&self) -> Option> { + if self.Message_type() == GameMessage::PlayerInputChange { + self.Message().map(|t| { + // Safety: + // Created from a valid Table for this object + // Which contains a valid union in this slot + unsafe { PlayerInputChange::init_from_table(t) } + }) + } else { + None } + } - #[inline] - #[allow(non_snake_case)] - pub fn Message_as_player_stat_event(&self) -> Option> { - if self.Message_type() == GameMessage::PlayerStatEvent { - self.Message().map(|t| { - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - unsafe { PlayerStatEvent::init_from_table(t) } - }) - } else { - None - } - } - - #[inline] - #[allow(non_snake_case)] - pub fn Message_as_player_spectate(&self) -> Option> { - if self.Message_type() == GameMessage::PlayerSpectate { - self.Message().map(|t| { - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - unsafe { PlayerSpectate::init_from_table(t) } - }) - } else { - None - } - } - - #[inline] - #[allow(non_snake_case)] - pub fn Message_as_player_input_change(&self) -> Option> { - if self.Message_type() == GameMessage::PlayerInputChange { - self.Message().map(|t| { - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - unsafe { PlayerInputChange::init_from_table(t) } - }) - } else { - None - } - } } impl ::flatbuffers::Verifiable for GameMessageWrapper<'_> { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.visit_table(pos)? - .visit_union::("Message_type", Self::VT_MESSAGE_TYPE, "Message", Self::VT_MESSAGE, false, |key, v, pos| { - match key { - GameMessage::PlayerStatEvent => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("GameMessage::PlayerStatEvent", pos), - GameMessage::PlayerSpectate => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("GameMessage::PlayerSpectate", pos), - GameMessage::PlayerInputChange => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("GameMessage::PlayerInputChange", pos), - _ => Ok(()), - } - })? - .finish(); - Ok(()) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.visit_table(pos)? + .visit_union::("Message_type", Self::VT_MESSAGE_TYPE, "Message", Self::VT_MESSAGE, false, |key, v, pos| { + match key { + GameMessage::PlayerStatEvent => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("GameMessage::PlayerStatEvent", pos), + GameMessage::PlayerSpectate => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("GameMessage::PlayerSpectate", pos), + GameMessage::PlayerInputChange => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("GameMessage::PlayerInputChange", pos), + _ => Ok(()), + } + })? + .finish(); + Ok(()) + } } - pub struct GameMessageWrapperArgs { pub Message_type: GameMessage, pub Message: Option<::flatbuffers::WIPOffset<::flatbuffers::UnionWIPOffset>>, } - impl<'a> Default for GameMessageWrapperArgs { - #[inline] - fn default() -> Self { - GameMessageWrapperArgs { - Message_type: GameMessage::NONE, - Message: None, - } + #[inline] + fn default() -> Self { + GameMessageWrapperArgs { + Message_type: GameMessage::NONE, + Message: None, } + } } pub struct GameMessageWrapperBuilder<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> { - fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, + fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, + start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, } - impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> GameMessageWrapperBuilder<'a, 'b, A> { - #[inline] - pub fn add_Message_type(&mut self, Message_type: GameMessage) { - self.fbb_.push_slot::(GameMessageWrapper::VT_MESSAGE_TYPE, Message_type, GameMessage::NONE); - } - - #[inline] - pub fn add_Message(&mut self, Message: ::flatbuffers::WIPOffset<::flatbuffers::UnionWIPOffset>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(GameMessageWrapper::VT_MESSAGE, Message); - } - - #[inline] - pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> GameMessageWrapperBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - GameMessageWrapperBuilder { - fbb_: _fbb, - start_: start, - } - } - - #[inline] - pub fn finish(self) -> ::flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - ::flatbuffers::WIPOffset::new(o.value()) + #[inline] + pub fn add_Message_type(&mut self, Message_type: GameMessage) { + self.fbb_.push_slot::(GameMessageWrapper::VT_MESSAGE_TYPE, Message_type, GameMessage::NONE); + } + #[inline] + pub fn add_Message(&mut self, Message: ::flatbuffers::WIPOffset<::flatbuffers::UnionWIPOffset>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(GameMessageWrapper::VT_MESSAGE, Message); + } + #[inline] + pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> GameMessageWrapperBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + GameMessageWrapperBuilder { + fbb_: _fbb, + start_: start, } + } + #[inline] + pub fn finish(self) -> ::flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + ::flatbuffers::WIPOffset::new(o.value()) + } } impl ::core::fmt::Debug for GameMessageWrapper<'_> { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - let mut ds = f.debug_struct("GameMessageWrapper"); - ds.field("Message_type", &self.Message_type()); - match self.Message_type() { - GameMessage::PlayerStatEvent => { - if let Some(x) = self.Message_as_player_stat_event() { - ds.field("Message", &x) - } else { - ds.field("Message", &"InvalidFlatbuffer: Union discriminant does not match value.") - } - }, - GameMessage::PlayerSpectate => { - if let Some(x) = self.Message_as_player_spectate() { - ds.field("Message", &x) - } else { - ds.field("Message", &"InvalidFlatbuffer: Union discriminant does not match value.") - } - }, - GameMessage::PlayerInputChange => { - if let Some(x) = self.Message_as_player_input_change() { - ds.field("Message", &x) - } else { - ds.field("Message", &"InvalidFlatbuffer: Union discriminant does not match value.") - } - }, - _ => { - let x: Option<()> = None; - ds.field("Message", &x) - }, - }; - ds.finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + let mut ds = f.debug_struct("GameMessageWrapper"); + ds.field("Message_type", &self.Message_type()); + match self.Message_type() { + GameMessage::PlayerStatEvent => { + if let Some(x) = self.Message_as_player_stat_event() { + ds.field("Message", &x) + } else { + ds.field("Message", &"InvalidFlatbuffer: Union discriminant does not match value.") + } + }, + GameMessage::PlayerSpectate => { + if let Some(x) = self.Message_as_player_spectate() { + ds.field("Message", &x) + } else { + ds.field("Message", &"InvalidFlatbuffer: Union discriminant does not match value.") + } + }, + GameMessage::PlayerInputChange => { + if let Some(x) = self.Message_as_player_input_change() { + ds.field("Message", &x) + } else { + ds.field("Message", &"InvalidFlatbuffer: Union discriminant does not match value.") + } + }, + _ => { + let x: Option<()> = None; + ds.field("Message", &x) + }, + }; + ds.finish() + } } - #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub struct GameMessageWrapperT { - pub Message: GameMessageT, + pub Message: GameMessageT, } - impl Default for GameMessageWrapperT { - fn default() -> Self { - Self { - Message: GameMessageT::NONE, - } + fn default() -> Self { + Self { + Message: GameMessageT::NONE, } + } } - impl GameMessageWrapperT { - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( - &self, - _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> - ) -> ::flatbuffers::WIPOffset> { - let Message_type = self.Message.game_message_type(); - let Message = self.Message.pack(_fbb); - GameMessageWrapper::create(_fbb, &GameMessageWrapperArgs{ - Message_type, - Message, - }) - } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> + ) -> ::flatbuffers::WIPOffset> { + let Message_type = self.Message.game_message_type(); + let Message = self.Message.pack(_fbb); + GameMessageWrapper::create(_fbb, &GameMessageWrapperArgs{ + Message_type, + Message, + }) + } } diff --git a/tests/rust_namer_test/rust_namer_test/player_input_change_generated.rs b/tests/rust_namer_test/rust_namer_test/player_input_change_generated.rs index ede5f7fd6..ef0645421 100644 --- a/tests/rust_namer_test/rust_namer_test/player_input_change_generated.rs +++ b/tests/rust_namer_test/rust_namer_test/player_input_change_generated.rs @@ -2,117 +2,108 @@ // @generated extern crate alloc; use super::*; - pub enum PlayerInputChangeOffset {} - #[derive(Copy, Clone, PartialEq)] + pub struct PlayerInputChange<'a> { - pub _tab: ::flatbuffers::Table<'a>, + pub _tab: ::flatbuffers::Table<'a>, } impl<'a> ::flatbuffers::Follow<'a> for PlayerInputChange<'a> { - type Inner = PlayerInputChange<'a>; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } - } + type Inner = PlayerInputChange<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } + } } impl<'a> PlayerInputChange<'a> { - pub const fn get_fully_qualified_name() -> &'static str { - "RustNamerTest.PlayerInputChange" - } - #[inline] - pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { - PlayerInputChange { _tab: table } - } + pub const fn get_fully_qualified_name() -> &'static str { + "RustNamerTest.PlayerInputChange" + } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, - _args: &'args PlayerInputChangeArgs - ) -> ::flatbuffers::WIPOffset> { - let mut builder = PlayerInputChangeBuilder::new(_fbb); - builder.finish() - } + #[inline] + pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { + PlayerInputChange { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, + _args: &'args PlayerInputChangeArgs + ) -> ::flatbuffers::WIPOffset> { + let mut builder = PlayerInputChangeBuilder::new(_fbb); + builder.finish() + } - pub fn unpack(&self) -> PlayerInputChangeT { - PlayerInputChangeT { - } + pub fn unpack(&self) -> PlayerInputChangeT { + PlayerInputChangeT { } + } } impl ::flatbuffers::Verifiable for PlayerInputChange<'_> { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.visit_table(pos)? - .finish(); - Ok(()) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.visit_table(pos)? + .finish(); + Ok(()) + } } - pub struct PlayerInputChangeArgs { } - impl<'a> Default for PlayerInputChangeArgs { - #[inline] - fn default() -> Self { - PlayerInputChangeArgs { - } + #[inline] + fn default() -> Self { + PlayerInputChangeArgs { } + } } pub struct PlayerInputChangeBuilder<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> { - fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, + fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, + start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, } - impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> PlayerInputChangeBuilder<'a, 'b, A> { - #[inline] - pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> PlayerInputChangeBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - PlayerInputChangeBuilder { - fbb_: _fbb, - start_: start, - } - } - - #[inline] - pub fn finish(self) -> ::flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - ::flatbuffers::WIPOffset::new(o.value()) + #[inline] + pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> PlayerInputChangeBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + PlayerInputChangeBuilder { + fbb_: _fbb, + start_: start, } + } + #[inline] + pub fn finish(self) -> ::flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + ::flatbuffers::WIPOffset::new(o.value()) + } } impl ::core::fmt::Debug for PlayerInputChange<'_> { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - let mut ds = f.debug_struct("PlayerInputChange"); - ds.finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + let mut ds = f.debug_struct("PlayerInputChange"); + ds.finish() + } } - #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub struct PlayerInputChangeT { } - impl Default for PlayerInputChangeT { - fn default() -> Self { - Self { - } + fn default() -> Self { + Self { } + } } - impl PlayerInputChangeT { - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( - &self, - _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> - ) -> ::flatbuffers::WIPOffset> { - PlayerInputChange::create(_fbb, &PlayerInputChangeArgs{ - }) - } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> + ) -> ::flatbuffers::WIPOffset> { + PlayerInputChange::create(_fbb, &PlayerInputChangeArgs{ + }) + } } diff --git a/tests/rust_namer_test/rust_namer_test/player_spectate_generated.rs b/tests/rust_namer_test/rust_namer_test/player_spectate_generated.rs index 13b9de44c..40b2066c0 100644 --- a/tests/rust_namer_test/rust_namer_test/player_spectate_generated.rs +++ b/tests/rust_namer_test/rust_namer_test/player_spectate_generated.rs @@ -2,117 +2,108 @@ // @generated extern crate alloc; use super::*; - pub enum PlayerSpectateOffset {} - #[derive(Copy, Clone, PartialEq)] + pub struct PlayerSpectate<'a> { - pub _tab: ::flatbuffers::Table<'a>, + pub _tab: ::flatbuffers::Table<'a>, } impl<'a> ::flatbuffers::Follow<'a> for PlayerSpectate<'a> { - type Inner = PlayerSpectate<'a>; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } - } + type Inner = PlayerSpectate<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } + } } impl<'a> PlayerSpectate<'a> { - pub const fn get_fully_qualified_name() -> &'static str { - "RustNamerTest.PlayerSpectate" - } - #[inline] - pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { - PlayerSpectate { _tab: table } - } + pub const fn get_fully_qualified_name() -> &'static str { + "RustNamerTest.PlayerSpectate" + } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, - _args: &'args PlayerSpectateArgs - ) -> ::flatbuffers::WIPOffset> { - let mut builder = PlayerSpectateBuilder::new(_fbb); - builder.finish() - } + #[inline] + pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { + PlayerSpectate { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, + _args: &'args PlayerSpectateArgs + ) -> ::flatbuffers::WIPOffset> { + let mut builder = PlayerSpectateBuilder::new(_fbb); + builder.finish() + } - pub fn unpack(&self) -> PlayerSpectateT { - PlayerSpectateT { - } + pub fn unpack(&self) -> PlayerSpectateT { + PlayerSpectateT { } + } } impl ::flatbuffers::Verifiable for PlayerSpectate<'_> { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.visit_table(pos)? - .finish(); - Ok(()) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.visit_table(pos)? + .finish(); + Ok(()) + } } - pub struct PlayerSpectateArgs { } - impl<'a> Default for PlayerSpectateArgs { - #[inline] - fn default() -> Self { - PlayerSpectateArgs { - } + #[inline] + fn default() -> Self { + PlayerSpectateArgs { } + } } pub struct PlayerSpectateBuilder<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> { - fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, + fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, + start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, } - impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> PlayerSpectateBuilder<'a, 'b, A> { - #[inline] - pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> PlayerSpectateBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - PlayerSpectateBuilder { - fbb_: _fbb, - start_: start, - } - } - - #[inline] - pub fn finish(self) -> ::flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - ::flatbuffers::WIPOffset::new(o.value()) + #[inline] + pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> PlayerSpectateBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + PlayerSpectateBuilder { + fbb_: _fbb, + start_: start, } + } + #[inline] + pub fn finish(self) -> ::flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + ::flatbuffers::WIPOffset::new(o.value()) + } } impl ::core::fmt::Debug for PlayerSpectate<'_> { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - let mut ds = f.debug_struct("PlayerSpectate"); - ds.finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + let mut ds = f.debug_struct("PlayerSpectate"); + ds.finish() + } } - #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub struct PlayerSpectateT { } - impl Default for PlayerSpectateT { - fn default() -> Self { - Self { - } + fn default() -> Self { + Self { } + } } - impl PlayerSpectateT { - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( - &self, - _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> - ) -> ::flatbuffers::WIPOffset> { - PlayerSpectate::create(_fbb, &PlayerSpectateArgs{ - }) - } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> + ) -> ::flatbuffers::WIPOffset> { + PlayerSpectate::create(_fbb, &PlayerSpectateArgs{ + }) + } } diff --git a/tests/rust_namer_test/rust_namer_test/player_stat_event_generated.rs b/tests/rust_namer_test/rust_namer_test/player_stat_event_generated.rs index ba57cc239..7fe60fad9 100644 --- a/tests/rust_namer_test/rust_namer_test/player_stat_event_generated.rs +++ b/tests/rust_namer_test/rust_namer_test/player_stat_event_generated.rs @@ -2,117 +2,108 @@ // @generated extern crate alloc; use super::*; - pub enum PlayerStatEventOffset {} - #[derive(Copy, Clone, PartialEq)] + pub struct PlayerStatEvent<'a> { - pub _tab: ::flatbuffers::Table<'a>, + pub _tab: ::flatbuffers::Table<'a>, } impl<'a> ::flatbuffers::Follow<'a> for PlayerStatEvent<'a> { - type Inner = PlayerStatEvent<'a>; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } - } + type Inner = PlayerStatEvent<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } + } } impl<'a> PlayerStatEvent<'a> { - pub const fn get_fully_qualified_name() -> &'static str { - "RustNamerTest.PlayerStatEvent" - } - #[inline] - pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { - PlayerStatEvent { _tab: table } - } + pub const fn get_fully_qualified_name() -> &'static str { + "RustNamerTest.PlayerStatEvent" + } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, - _args: &'args PlayerStatEventArgs - ) -> ::flatbuffers::WIPOffset> { - let mut builder = PlayerStatEventBuilder::new(_fbb); - builder.finish() - } + #[inline] + pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { + PlayerStatEvent { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, + _args: &'args PlayerStatEventArgs + ) -> ::flatbuffers::WIPOffset> { + let mut builder = PlayerStatEventBuilder::new(_fbb); + builder.finish() + } - pub fn unpack(&self) -> PlayerStatEventT { - PlayerStatEventT { - } + pub fn unpack(&self) -> PlayerStatEventT { + PlayerStatEventT { } + } } impl ::flatbuffers::Verifiable for PlayerStatEvent<'_> { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.visit_table(pos)? - .finish(); - Ok(()) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.visit_table(pos)? + .finish(); + Ok(()) + } } - pub struct PlayerStatEventArgs { } - impl<'a> Default for PlayerStatEventArgs { - #[inline] - fn default() -> Self { - PlayerStatEventArgs { - } + #[inline] + fn default() -> Self { + PlayerStatEventArgs { } + } } pub struct PlayerStatEventBuilder<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> { - fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, + fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, + start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, } - impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> PlayerStatEventBuilder<'a, 'b, A> { - #[inline] - pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> PlayerStatEventBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - PlayerStatEventBuilder { - fbb_: _fbb, - start_: start, - } - } - - #[inline] - pub fn finish(self) -> ::flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - ::flatbuffers::WIPOffset::new(o.value()) + #[inline] + pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> PlayerStatEventBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + PlayerStatEventBuilder { + fbb_: _fbb, + start_: start, } + } + #[inline] + pub fn finish(self) -> ::flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + ::flatbuffers::WIPOffset::new(o.value()) + } } impl ::core::fmt::Debug for PlayerStatEvent<'_> { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - let mut ds = f.debug_struct("PlayerStatEvent"); - ds.finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + let mut ds = f.debug_struct("PlayerStatEvent"); + ds.finish() + } } - #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub struct PlayerStatEventT { } - impl Default for PlayerStatEventT { - fn default() -> Self { - Self { - } + fn default() -> Self { + Self { } + } } - impl PlayerStatEventT { - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( - &self, - _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> - ) -> ::flatbuffers::WIPOffset> { - PlayerStatEvent::create(_fbb, &PlayerStatEventArgs{ - }) - } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> + ) -> ::flatbuffers::WIPOffset> { + PlayerStatEvent::create(_fbb, &PlayerStatEventArgs{ + }) + } } diff --git a/tests/rust_namer_test/rust_namer_test/possibly_reserved_words_generated.rs b/tests/rust_namer_test/rust_namer_test/possibly_reserved_words_generated.rs index 4d4200234..6d4ec11e2 100644 --- a/tests/rust_namer_test/rust_namer_test/possibly_reserved_words_generated.rs +++ b/tests/rust_namer_test/rust_namer_test/possibly_reserved_words_generated.rs @@ -2,58 +2,48 @@ // @generated extern crate alloc; use super::*; - // struct PossiblyReservedWords, aligned to 4 #[repr(transparent)] #[derive(Clone, Copy, PartialEq)] pub struct PossiblyReservedWords(pub [u8; 16]); - -impl Default for PossiblyReservedWords { - fn default() -> Self { - Self([0; 16]) - } +impl Default for PossiblyReservedWords { + fn default() -> Self { + Self([0; 16]) + } } - impl ::core::fmt::Debug for PossiblyReservedWords { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - f.debug_struct("PossiblyReservedWords") - .field("follow_", &self.follow_()) - .field("push_", &self.push_()) - .field("size", &self.size()) - .field("alignment", &self.alignment()) - .finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + f.debug_struct("PossiblyReservedWords") + .field("follow_", &self.follow_()) + .field("push_", &self.push_()) + .field("size", &self.size()) + .field("alignment", &self.alignment()) + .finish() + } } impl ::flatbuffers::SimpleToVerifyInSlice for PossiblyReservedWords {} - impl<'a> ::flatbuffers::Follow<'a> for PossiblyReservedWords { - type Inner = &'a PossiblyReservedWords; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - unsafe { <&'a PossiblyReservedWords>::follow(buf, loc) } - } + type Inner = &'a PossiblyReservedWords; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { <&'a PossiblyReservedWords>::follow(buf, loc) } + } } - impl<'a> ::flatbuffers::Follow<'a> for &'a PossiblyReservedWords { - type Inner = &'a PossiblyReservedWords; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - unsafe { ::flatbuffers::follow_cast_ref::(buf, loc) } - } + type Inner = &'a PossiblyReservedWords; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { ::flatbuffers::follow_cast_ref::(buf, loc) } + } } - impl<'b> ::flatbuffers::Push for PossiblyReservedWords { type Output = PossiblyReservedWords; - #[inline] unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { let src = unsafe { ::core::slice::from_raw_parts(self as *const PossiblyReservedWords as *const u8, ::size()) }; dst.copy_from_slice(src); } - #[inline] fn alignment() -> ::flatbuffers::PushAlignment { ::flatbuffers::PushAlignment::new(4) @@ -61,185 +51,175 @@ impl<'b> ::flatbuffers::Push for PossiblyReservedWords { } impl<'a> ::flatbuffers::Verifiable for PossiblyReservedWords { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.in_buffer::(pos) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.in_buffer::(pos) + } } impl<'a> PossiblyReservedWords { - #[allow(clippy::too_many_arguments)] - pub fn new( - follow_: f32, - push_: f32, - size: f32, - alignment: f32, - ) -> Self { - let mut s = Self([0; 16]); - s.set_follow_(follow_); - s.set_push_(push_); - s.set_size(size); - s.set_alignment(alignment); - s - } + #[allow(clippy::too_many_arguments)] + pub fn new( + follow_: f32, + push_: f32, + size: f32, + alignment: f32, + ) -> Self { + let mut s = Self([0; 16]); + s.set_follow_(follow_); + s.set_push_(push_); + s.set_size(size); + s.set_alignment(alignment); + s + } - pub const fn get_fully_qualified_name() -> &'static str { - "RustNamerTest.PossiblyReservedWords" - } + pub const fn get_fully_qualified_name() -> &'static str { + "RustNamerTest.PossiblyReservedWords" + } - pub fn follow_(&self) -> f32 { - let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - ::flatbuffers::EndianScalar::from_little_endian(unsafe { - ::core::ptr::copy_nonoverlapping( - self.0[0..].as_ptr(), - mem.as_mut_ptr() as *mut u8, - ::core::mem::size_of::<::Scalar>(), - ); - mem.assume_init() - }) - } + pub fn follow_(&self) -> f32 { + let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + ::flatbuffers::EndianScalar::from_little_endian(unsafe { + ::core::ptr::copy_nonoverlapping( + self.0[0..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + ::core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } - pub fn set_follow_(&mut self, x: f32) { - let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - unsafe { - ::core::ptr::copy_nonoverlapping( - &x_le as *const _ as *const u8, - self.0[0..].as_mut_ptr(), - ::core::mem::size_of::<::Scalar>(), - ); - } + pub fn set_follow_(&mut self, x: f32) { + let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + ::core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[0..].as_mut_ptr(), + ::core::mem::size_of::<::Scalar>(), + ); } + } - pub fn push_(&self) -> f32 { - let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - ::flatbuffers::EndianScalar::from_little_endian(unsafe { - ::core::ptr::copy_nonoverlapping( - self.0[4..].as_ptr(), - mem.as_mut_ptr() as *mut u8, - ::core::mem::size_of::<::Scalar>(), - ); - mem.assume_init() - }) - } + pub fn push_(&self) -> f32 { + let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + ::flatbuffers::EndianScalar::from_little_endian(unsafe { + ::core::ptr::copy_nonoverlapping( + self.0[4..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + ::core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } - pub fn set_push_(&mut self, x: f32) { - let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - unsafe { - ::core::ptr::copy_nonoverlapping( - &x_le as *const _ as *const u8, - self.0[4..].as_mut_ptr(), - ::core::mem::size_of::<::Scalar>(), - ); - } + pub fn set_push_(&mut self, x: f32) { + let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + ::core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[4..].as_mut_ptr(), + ::core::mem::size_of::<::Scalar>(), + ); } + } - pub fn size(&self) -> f32 { - let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - ::flatbuffers::EndianScalar::from_little_endian(unsafe { - ::core::ptr::copy_nonoverlapping( - self.0[8..].as_ptr(), - mem.as_mut_ptr() as *mut u8, - ::core::mem::size_of::<::Scalar>(), - ); - mem.assume_init() - }) - } + pub fn size(&self) -> f32 { + let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + ::flatbuffers::EndianScalar::from_little_endian(unsafe { + ::core::ptr::copy_nonoverlapping( + self.0[8..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + ::core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } - pub fn set_size(&mut self, x: f32) { - let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - unsafe { - ::core::ptr::copy_nonoverlapping( - &x_le as *const _ as *const u8, - self.0[8..].as_mut_ptr(), - ::core::mem::size_of::<::Scalar>(), - ); - } + pub fn set_size(&mut self, x: f32) { + let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + ::core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[8..].as_mut_ptr(), + ::core::mem::size_of::<::Scalar>(), + ); } + } - pub fn alignment(&self) -> f32 { - let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - ::flatbuffers::EndianScalar::from_little_endian(unsafe { - ::core::ptr::copy_nonoverlapping( - self.0[12..].as_ptr(), - mem.as_mut_ptr() as *mut u8, - ::core::mem::size_of::<::Scalar>(), - ); - mem.assume_init() - }) - } + pub fn alignment(&self) -> f32 { + let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + ::flatbuffers::EndianScalar::from_little_endian(unsafe { + ::core::ptr::copy_nonoverlapping( + self.0[12..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + ::core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } - pub fn set_alignment(&mut self, x: f32) { - let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); - // Safety: - // Created from a valid Table for this object - // Which contains a valid value in this slot - unsafe { - ::core::ptr::copy_nonoverlapping( - &x_le as *const _ as *const u8, - self.0[12..].as_mut_ptr(), - ::core::mem::size_of::<::Scalar>(), - ); - } + pub fn set_alignment(&mut self, x: f32) { + let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + ::core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[12..].as_mut_ptr(), + ::core::mem::size_of::<::Scalar>(), + ); } + } - pub fn unpack(&self) -> PossiblyReservedWordsT { - PossiblyReservedWordsT { - follow_: self.follow_(), - push_: self.push_(), - size: self.size(), - alignment: self.alignment(), - } + pub fn unpack(&self) -> PossiblyReservedWordsT { + PossiblyReservedWordsT { + follow_: self.follow_(), + push_: self.push_(), + size: self.size(), + alignment: self.alignment(), } + } } -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Default)] pub struct PossiblyReservedWordsT { - pub follow_: f32, - pub push_: f32, - pub size: f32, - pub alignment: f32, + pub follow_: f32, + pub push_: f32, + pub size: f32, + pub alignment: f32, } -impl Default for PossiblyReservedWordsT { - fn default() -> Self { - Self { - follow_: 0.0, - push_: 0.0, - size: 0.0, - alignment: 0.0, - } - } +impl PossiblyReservedWordsT { + pub fn pack(&self) -> PossiblyReservedWords { + PossiblyReservedWords::new( + self.follow_, + self.push_, + self.size, + self.alignment, + ) + } } -impl PossiblyReservedWordsT { - pub fn pack(&self) -> PossiblyReservedWords { - PossiblyReservedWords::new( - self.follow_, - self.push_, - self.size, - self.alignment, - ) - } -} diff --git a/tests/rust_namer_test/rust_namer_test/root_table_generated.rs b/tests/rust_namer_test/rust_namer_test/root_table_generated.rs index 0ff2e5c63..c3d458e07 100644 --- a/tests/rust_namer_test/rust_namer_test/root_table_generated.rs +++ b/tests/rust_namer_test/rust_namer_test/root_table_generated.rs @@ -2,203 +2,190 @@ // @generated extern crate alloc; use super::*; - pub enum RootTableOffset {} - #[derive(Copy, Clone, PartialEq)] + pub struct RootTable<'a> { - pub _tab: ::flatbuffers::Table<'a>, + pub _tab: ::flatbuffers::Table<'a>, } impl<'a> ::flatbuffers::Follow<'a> for RootTable<'a> { - type Inner = RootTable<'a>; - - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } - } + type Inner = RootTable<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } + } } impl<'a> RootTable<'a> { - pub const VT_FIELD42_TYPE: ::flatbuffers::VOffsetT = 4; - pub const VT_FIELD42: ::flatbuffers::VOffsetT = 6; + pub const VT_FIELD42_TYPE: ::flatbuffers::VOffsetT = 4; + pub const VT_FIELD42: ::flatbuffers::VOffsetT = 6; - pub const fn get_fully_qualified_name() -> &'static str { - "RustNamerTest.RootTable" - } + pub const fn get_fully_qualified_name() -> &'static str { + "RustNamerTest.RootTable" + } - #[inline] - pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { - RootTable { _tab: table } - } + #[inline] + pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { + RootTable { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args RootTableArgs + ) -> ::flatbuffers::WIPOffset> { + let mut builder = RootTableBuilder::new(_fbb); + if let Some(x) = args.field42 { builder.add_field42(x); } + builder.add_field42_type(args.field42_type); + builder.finish() + } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args RootTableArgs - ) -> ::flatbuffers::WIPOffset> { - let mut builder = RootTableBuilder::new(_fbb); - if let Some(x) = args.field42 { builder.add_field42(x); } - builder.add_field42_type(args.field42_type); - builder.finish() + pub fn unpack(&self) -> RootTableT { + let field42 = match self.field42_type() { + FieldUnion::NONE => FieldUnionT::NONE, + FieldUnion::f => FieldUnionT::F(alloc::boxed::Box::new( + self.field42_as_f() + .expect("Invalid union table, expected `FieldUnion::f`.") + .unpack() + )), + _ => FieldUnionT::NONE, + }; + RootTableT { + field42, } + } - pub fn unpack(&self) -> RootTableT { - let field42 = match self.field42_type() { - FieldUnion::NONE => FieldUnionT::NONE, - FieldUnion::f => FieldUnionT::F(alloc::boxed::Box::new( - self.field42_as_f() - .expect("Invalid union table, expected `FieldUnion::f`.") - .unpack() - )), - _ => FieldUnionT::NONE, - }; - RootTableT { - field42, - } + #[inline] + pub fn field42_type(&self) -> FieldUnion { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(RootTable::VT_FIELD42_TYPE, Some(FieldUnion::NONE)).unwrap()} + } + #[inline] + pub fn field42(&self) -> Option<::flatbuffers::Table<'a>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Table<'a>>>(RootTable::VT_FIELD42, None)} + } + #[inline] + #[allow(non_snake_case)] + pub fn field42_as_f(&self) -> Option> { + if self.field42_type() == FieldUnion::f { + self.field42().map(|t| { + // Safety: + // Created from a valid Table for this object + // Which contains a valid union in this slot + unsafe { FieldTable::init_from_table(t) } + }) + } else { + None } + } - #[inline] - pub fn field42_type(&self) -> FieldUnion { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(RootTable::VT_FIELD42_TYPE, Some(FieldUnion::NONE)).unwrap()} - } - - #[inline] - pub fn field42(&self) -> Option<::flatbuffers::Table<'a>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::<::flatbuffers::ForwardsUOffset<::flatbuffers::Table<'a>>>(RootTable::VT_FIELD42, None)} - } - - #[inline] - #[allow(non_snake_case)] - pub fn field42_as_f(&self) -> Option> { - if self.field42_type() == FieldUnion::f { - self.field42().map(|t| { - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - unsafe { FieldTable::init_from_table(t) } - }) - } else { - None - } - } } impl ::flatbuffers::Verifiable for RootTable<'_> { - #[inline] - fn run_verifier( - v: &mut ::flatbuffers::Verifier, pos: usize - ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { - v.visit_table(pos)? - .visit_union::("field42_type", Self::VT_FIELD42_TYPE, "field42", Self::VT_FIELD42, false, |key, v, pos| { - match key { - FieldUnion::f => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("FieldUnion::f", pos), - _ => Ok(()), - } - })? - .finish(); - Ok(()) - } + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.visit_table(pos)? + .visit_union::("field42_type", Self::VT_FIELD42_TYPE, "field42", Self::VT_FIELD42, false, |key, v, pos| { + match key { + FieldUnion::f => v.verify_union_variant::<::flatbuffers::ForwardsUOffset>("FieldUnion::f", pos), + _ => Ok(()), + } + })? + .finish(); + Ok(()) + } } - pub struct RootTableArgs { pub field42_type: FieldUnion, pub field42: Option<::flatbuffers::WIPOffset<::flatbuffers::UnionWIPOffset>>, } - impl<'a> Default for RootTableArgs { - #[inline] - fn default() -> Self { - RootTableArgs { - field42_type: FieldUnion::NONE, - field42: None, - } + #[inline] + fn default() -> Self { + RootTableArgs { + field42_type: FieldUnion::NONE, + field42: None, } + } } pub struct RootTableBuilder<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> { - fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, - start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, + fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, + start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, } - impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> RootTableBuilder<'a, 'b, A> { - #[inline] - pub fn add_field42_type(&mut self, field42_type: FieldUnion) { - self.fbb_.push_slot::(RootTable::VT_FIELD42_TYPE, field42_type, FieldUnion::NONE); - } - - #[inline] - pub fn add_field42(&mut self, field42: ::flatbuffers::WIPOffset<::flatbuffers::UnionWIPOffset>) { - self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(RootTable::VT_FIELD42, field42); - } - - #[inline] - pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> RootTableBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - RootTableBuilder { - fbb_: _fbb, - start_: start, - } - } - - #[inline] - pub fn finish(self) -> ::flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - ::flatbuffers::WIPOffset::new(o.value()) + #[inline] + pub fn add_field42_type(&mut self, field42_type: FieldUnion) { + self.fbb_.push_slot::(RootTable::VT_FIELD42_TYPE, field42_type, FieldUnion::NONE); + } + #[inline] + pub fn add_field42(&mut self, field42: ::flatbuffers::WIPOffset<::flatbuffers::UnionWIPOffset>) { + self.fbb_.push_slot_always::<::flatbuffers::WIPOffset<_>>(RootTable::VT_FIELD42, field42); + } + #[inline] + pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> RootTableBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + RootTableBuilder { + fbb_: _fbb, + start_: start, } + } + #[inline] + pub fn finish(self) -> ::flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + ::flatbuffers::WIPOffset::new(o.value()) + } } impl ::core::fmt::Debug for RootTable<'_> { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { - let mut ds = f.debug_struct("RootTable"); - ds.field("field42_type", &self.field42_type()); - match self.field42_type() { - FieldUnion::f => { - if let Some(x) = self.field42_as_f() { - ds.field("field42", &x) - } else { - ds.field("field42", &"InvalidFlatbuffer: Union discriminant does not match value.") - } - }, - _ => { - let x: Option<()> = None; - ds.field("field42", &x) - }, - }; - ds.finish() - } + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + let mut ds = f.debug_struct("RootTable"); + ds.field("field42_type", &self.field42_type()); + match self.field42_type() { + FieldUnion::f => { + if let Some(x) = self.field42_as_f() { + ds.field("field42", &x) + } else { + ds.field("field42", &"InvalidFlatbuffer: Union discriminant does not match value.") + } + }, + _ => { + let x: Option<()> = None; + ds.field("field42", &x) + }, + }; + ds.finish() + } } - #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub struct RootTableT { - pub field42: FieldUnionT, + pub field42: FieldUnionT, } - impl Default for RootTableT { - fn default() -> Self { - Self { - field42: FieldUnionT::NONE, - } + fn default() -> Self { + Self { + field42: FieldUnionT::NONE, } + } } - impl RootTableT { - pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( - &self, - _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> - ) -> ::flatbuffers::WIPOffset> { - let field42_type = self.field42.field_union_type(); - let field42 = self.field42.pack(_fbb); - RootTable::create(_fbb, &RootTableArgs{ - field42_type, - field42, - }) - } + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> + ) -> ::flatbuffers::WIPOffset> { + let field42_type = self.field42.field_union_type(); + let field42 = self.field42.pack(_fbb); + RootTable::create(_fbb, &RootTableArgs{ + field42_type, + field42, + }) + } } diff --git a/tests/rust_usage_test/Cargo.toml b/tests/rust_usage_test/Cargo.toml index 828224dd9..5b7152b9c 100644 --- a/tests/rust_usage_test/Cargo.toml +++ b/tests/rust_usage_test/Cargo.toml @@ -25,12 +25,10 @@ path = "bin/monster_example.rs" [[bin]] name = "flatbuffers_alloc_check" path = "bin/flatbuffers_alloc_check.rs" -test = false [[bin]] name = "flexbuffers_alloc_check" path = "bin/flexbuffers_alloc_check.rs" -test = false [[bin]] name = "sample_flexbuffers" diff --git a/tests/rust_usage_test/tests/integration_test.rs b/tests/rust_usage_test/tests/integration_test.rs index 21e5faf02..d97bf88cf 100644 --- a/tests/rust_usage_test/tests/integration_test.rs +++ b/tests/rust_usage_test/tests/integration_test.rs @@ -3224,474 +3224,4 @@ fn test_shared_strings() { assert_eq!(string_vector.get(1), "foo"); } -#[test] -fn lookup_index_by_key_returns_correct_index() { - let b = &mut flatbuffers::FlatBufferBuilder::new(); - // Abilities are sorted by id (the key field). - let v = b.create_vector(&[ - my_game::example::Ability::new(1, 10), - my_game::example::Ability::new(3, 30), - my_game::example::Ability::new(5, 50), - ]); - let name = b.create_string("test"); - let mon = my_game::example::Monster::create(b, &my_game::example::MonsterArgs { - name: Some(name), - testarrayofsortedstruct: Some(v), - ..Default::default() - }); - my_game::example::finish_monster_buffer(b, mon); - let buf = b.finished_data(); - let mon = my_game::example::root_as_monster(buf).unwrap(); - let abilities = mon.testarrayofsortedstruct().unwrap(); - - // Lookup each element and verify the returned index. - assert_eq!( - abilities.lookup_index_by_key(1u32, |a, key| a.key_compare_with_value(*key)), - Some(0) - ); - assert_eq!( - abilities.lookup_index_by_key(3u32, |a, key| a.key_compare_with_value(*key)), - Some(1) - ); - assert_eq!( - abilities.lookup_index_by_key(5u32, |a, key| a.key_compare_with_value(*key)), - Some(2) - ); -} - -#[test] -fn lookup_index_by_key_returns_none_for_missing_key() { - let b = &mut flatbuffers::FlatBufferBuilder::new(); - let v = b.create_vector(&[ - my_game::example::Ability::new(1, 10), - my_game::example::Ability::new(3, 30), - my_game::example::Ability::new(5, 50), - ]); - let name = b.create_string("test"); - let mon = my_game::example::Monster::create(b, &my_game::example::MonsterArgs { - name: Some(name), - testarrayofsortedstruct: Some(v), - ..Default::default() - }); - my_game::example::finish_monster_buffer(b, mon); - let buf = b.finished_data(); - let mon = my_game::example::root_as_monster(buf).unwrap(); - let abilities = mon.testarrayofsortedstruct().unwrap(); - - // Keys that do not exist in the vector. - assert_eq!( - abilities.lookup_index_by_key(0u32, |a, key| a.key_compare_with_value(*key)), - None - ); - assert_eq!( - abilities.lookup_index_by_key(2u32, |a, key| a.key_compare_with_value(*key)), - None - ); - assert_eq!( - abilities.lookup_index_by_key(99u32, |a, key| a.key_compare_with_value(*key)), - None - ); -} - -#[test] -fn lookup_index_by_key_on_empty_vector() { - let b = &mut flatbuffers::FlatBufferBuilder::new(); - let v = b.create_vector::(&[]); - let name = b.create_string("test"); - let mon = my_game::example::Monster::create(b, &my_game::example::MonsterArgs { - name: Some(name), - testarrayofsortedstruct: Some(v), - ..Default::default() - }); - my_game::example::finish_monster_buffer(b, mon); - let buf = b.finished_data(); - let mon = my_game::example::root_as_monster(buf).unwrap(); - let abilities = mon.testarrayofsortedstruct().unwrap(); - - assert_eq!( - abilities.lookup_index_by_key(1u32, |a, key| a.key_compare_with_value(*key)), - None - ); -} - -#[test] -fn lookup_index_by_key_single_element() { - let b = &mut flatbuffers::FlatBufferBuilder::new(); - let v = b.create_vector(&[my_game::example::Ability::new(42, 100)]); - let name = b.create_string("test"); - let mon = my_game::example::Monster::create(b, &my_game::example::MonsterArgs { - name: Some(name), - testarrayofsortedstruct: Some(v), - ..Default::default() - }); - my_game::example::finish_monster_buffer(b, mon); - let buf = b.finished_data(); - let mon = my_game::example::root_as_monster(buf).unwrap(); - let abilities = mon.testarrayofsortedstruct().unwrap(); - - assert_eq!( - abilities.lookup_index_by_key(42u32, |a, key| a.key_compare_with_value(*key)), - Some(0) - ); - assert_eq!( - abilities.lookup_index_by_key(1u32, |a, key| a.key_compare_with_value(*key)), - None - ); -} - -#[test] -fn lookup_index_by_key_consistent_with_lookup_by_key() { - let b = &mut flatbuffers::FlatBufferBuilder::new(); - let v = b.create_vector(&[ - my_game::example::Ability::new(2, 20), - my_game::example::Ability::new(4, 40), - my_game::example::Ability::new(6, 60), - my_game::example::Ability::new(8, 80), - my_game::example::Ability::new(10, 100), - ]); - let name = b.create_string("test"); - let mon = my_game::example::Monster::create(b, &my_game::example::MonsterArgs { - name: Some(name), - testarrayofsortedstruct: Some(v), - ..Default::default() - }); - my_game::example::finish_monster_buffer(b, mon); - let buf = b.finished_data(); - let mon = my_game::example::root_as_monster(buf).unwrap(); - let abilities = mon.testarrayofsortedstruct().unwrap(); - - // For every key that exists, lookup_index_by_key should return an index - // whose element matches lookup_by_key. - for key in &[2u32, 4, 6, 8, 10] { - let obj = abilities.lookup_by_key(*key, |a, k| a.key_compare_with_value(*k)); - let idx = abilities.lookup_index_by_key(*key, |a, k| a.key_compare_with_value(*k)); - assert!(obj.is_some()); - assert!(idx.is_some()); - assert_eq!(abilities.get(idx.unwrap()).id(), obj.unwrap().id()); - } - - // For keys that don't exist, both should return None. - for key in &[0u32, 1, 3, 5, 7, 9, 11] { - assert!(abilities.lookup_by_key(*key, |a, k| a.key_compare_with_value(*k)).is_none()); - assert!(abilities.lookup_index_by_key(*key, |a, k| a.key_compare_with_value(*k)).is_none()); - } -fn test_shared_strings_pool_deduplication() { - // Verifies that create_shared_string correctly deduplicates across many - // unique strings and that the resulting buffer contains valid data. - let mut builder = flatbuffers::FlatBufferBuilder::with_capacity(1024); - - // Insert multiple unique strings and verify each gets a distinct offset. - let animals = ["cat", "dog", "bird", "fish", "snake"]; - let offsets: Vec<_> = animals - .iter() - .map(|s| builder.create_shared_string(s)) - .collect(); - for i in 0..offsets.len() { - for j in (i + 1)..offsets.len() { - assert_ne!( - offsets[i].value(), - offsets[j].value(), - "unique strings '{}' and '{}' must have different offsets", - animals[i], - animals[j], - ); - } - } - - // Re-insert the same strings and verify they return the original offsets. - for (i, s) in animals.iter().enumerate() { - let offset = builder.create_shared_string(s); - assert_eq!( - offset.value(), - offsets[i].value(), - "duplicate string '{}' must return the same offset", - s, - ); - } - - // Verify that reset clears the pool: a previously shared string is no - // longer deduplicated against strings from before the reset. - builder.reset(); - let a = builder.create_shared_string("cat"); - let b = builder.create_shared_string("cat"); - assert_eq!(a.value(), b.value(), "same string after reset must still deduplicate"); - - // Verify that shared strings produce a valid, readable buffer. - builder.reset(); - let shared_name = builder.create_shared_string("goblin"); - let shared_name_dup = builder.create_shared_string("goblin"); - assert_eq!(shared_name.value(), shared_name_dup.value()); - - let enemy = my_game::example::Monster::create( - &mut builder, - &my_game::example::MonsterArgs { - name: Some(shared_name), - ..Default::default() - }, - ); - let main_name = builder.create_shared_string("goblin"); - assert_eq!(main_name.value(), shared_name.value()); - - let monster = my_game::example::Monster::create( - &mut builder, - &my_game::example::MonsterArgs { - name: Some(main_name), - enemy: Some(enemy), - ..Default::default() - }, - ); - builder.finish(monster, None); - - let m = my_game::example::root_as_monster(builder.finished_data()).unwrap(); - assert_eq!(m.name(), "goblin"); - assert_eq!(m.enemy().unwrap().name(), "goblin"); -} - -} // mod flatbuffers_tests - -#[cfg(test)] -mod try_api { - extern crate flatbuffers; - - use alloc::vec::Vec; - use flatbuffers::Follow; - use super::my_game; - use super::serialized_example_is_accessible_and_correct; - - #[test] - fn try_api_full_table_roundtrip() { - // Build a Monster using exclusively try_* API (mirrors library_code example). - let mut builder = flatbuffers::FlatBufferBuilder::new(); - - let nested_union_mon = { - let name = builder.try_create_string("Fred").unwrap(); - let table_start = builder.start_table(); - builder - .try_push_slot_always(my_game::example::Monster::VT_NAME, name) - .unwrap(); - builder.try_end_table(table_start).unwrap() - }; - let pos = my_game::example::Vec3::new( - 1.0, - 2.0, - 3.0, - 3.0, - my_game::example::Color::Green, - &my_game::example::Test::new(5i16, 6i8), - ); - let inv = builder.try_create_vector(&[0u8, 1, 2, 3, 4]).unwrap(); - let test4 = builder - .try_create_vector( - &[ - my_game::example::Test::new(10, 20), - my_game::example::Test::new(30, 40), - ][..], - ) - .unwrap(); - - let name = builder.try_create_string("MyMonster").unwrap(); - let test1 = builder.try_create_string("test1").unwrap(); - let test2 = builder.try_create_string("test2").unwrap(); - let testarrayofstring = builder.try_create_vector(&[test1, test2]).unwrap(); - - let table_start = builder.start_table(); - builder - .try_push_slot(my_game::example::Monster::VT_HP, 80i16, 100) - .unwrap(); - builder - .try_push_slot_always(my_game::example::Monster::VT_NAME, name) - .unwrap(); - builder - .try_push_slot_always(my_game::example::Monster::VT_POS, &pos) - .unwrap(); - builder - .try_push_slot( - my_game::example::Monster::VT_TEST_TYPE, - my_game::example::Any::Monster, - my_game::example::Any::NONE, - ) - .unwrap(); - builder - .try_push_slot_always(my_game::example::Monster::VT_TEST, nested_union_mon) - .unwrap(); - builder - .try_push_slot_always(my_game::example::Monster::VT_INVENTORY, inv) - .unwrap(); - builder - .try_push_slot_always(my_game::example::Monster::VT_TEST4, test4) - .unwrap(); - builder - .try_push_slot_always( - my_game::example::Monster::VT_TESTARRAYOFSTRING, - testarrayofstring, - ) - .unwrap(); - let root = builder.try_end_table(table_start).unwrap(); - builder - .try_finish(root, Some(my_game::example::MONSTER_IDENTIFIER)) - .unwrap(); - - let buf = builder.finished_data(); - serialized_example_is_accessible_and_correct(buf, true, false).unwrap(); - } - - #[test] - fn try_shared_string_deduplication() { - let mut builder = flatbuffers::FlatBufferBuilder::new(); - let offset1 = builder - .try_create_shared_string("welcome to flatbuffers!!") - .unwrap(); - let offset2 = builder.try_create_shared_string("welcome").unwrap(); - let offset3 = builder - .try_create_shared_string("welcome to flatbuffers!!") - .unwrap(); - assert_ne!(offset2.value(), offset3.value()); - assert_eq!(offset1.value(), offset3.value()); - - builder.reset(); - let offset4 = builder.try_create_shared_string("welcome").unwrap(); - let offset5 = builder - .try_create_shared_string("welcome to flatbuffers!!") - .unwrap(); - assert_ne!(offset2.value(), offset4.value()); - assert_ne!(offset5.value(), offset1.value()); - - builder.reset(); - // Shared strings work with an object in between writes - let name = builder.try_create_shared_string("foo").unwrap(); - let enemy = - my_game::example::Monster::create(&mut builder, &my_game::example::MonsterArgs { - name: Some(name), - ..Default::default() - }); - let secondary_name = builder.try_create_shared_string("foo").unwrap(); - assert_eq!(name.value(), secondary_name.value()); - - let args = my_game::example::MonsterArgs { - name: Some(secondary_name), - enemy: Some(enemy), - testarrayofstring: Some(builder.try_create_vector(&[name, secondary_name]).unwrap()), - ..Default::default() - }; - let main_monster = my_game::example::Monster::create(&mut builder, &args); - builder.try_finish(main_monster, None).unwrap(); - let monster = - my_game::example::root_as_monster(builder.finished_data()).unwrap(); - - assert_eq!(monster.enemy().unwrap().name(), "foo"); - let string_vector = monster.testarrayofstring().unwrap(); - assert_eq!(string_vector.get(0), "foo"); - assert_eq!(string_vector.get(1), "foo"); - } - - #[test] - fn try_vector_manual_build_roundtrip() { - // Build a vector of scalars manually using try_start_vector / try_push / try_end_vector. - let mut builder = flatbuffers::FlatBufferBuilder::new(); - let items: Vec = vec![10, 20, 30, 40, 50]; - - builder - .try_start_vector::(items.len()) - .unwrap(); - for &v in items.iter().rev() { - builder.try_push::(v).unwrap(); - } - let vecend = builder.try_end_vector::(items.len()).unwrap(); - builder.try_finish_minimal(vecend).unwrap(); - - let buf = builder.finished_data(); - let got = unsafe { - >>::follow(&buf[..], 0) - }; - let result: Vec = got.iter().collect(); - assert_eq!(result, items); - } - - #[test] - fn try_create_vector_roundtrip() { - let mut builder = flatbuffers::FlatBufferBuilder::new(); - let items: Vec = vec![-1, 0, 1, i64::MIN, i64::MAX]; - let offset = builder.try_create_vector(&items).unwrap(); - builder.try_finish_minimal(offset).unwrap(); - - let buf = builder.finished_data(); - let got = unsafe { - >>::follow(&buf[..], 0) - }; - let result: Vec = got.iter().collect(); - assert_eq!(result, items); - } - - #[test] - fn try_create_vector_from_iter_roundtrip() { - let mut builder = flatbuffers::FlatBufferBuilder::new(); - let items: Vec = vec![1.0, 2.5, -3.14, 0.0]; - let offset = builder - .try_create_vector_from_iter(items.iter().copied()) - .unwrap(); - builder.try_finish_minimal(offset).unwrap(); - - let buf = builder.finished_data(); - let got = unsafe { - >>::follow(&buf[..], 0) - }; - let result: Vec = got.iter().collect(); - assert_eq!(result, items); - } - - #[test] - fn try_create_byte_string_roundtrip() { - let mut builder = flatbuffers::FlatBufferBuilder::new(); - let data = b"hello bytes"; - let offset = builder.try_create_byte_string(data).unwrap(); - builder.try_finish_minimal(offset).unwrap(); - - let buf = builder.finished_data(); - let got = unsafe { - >::follow(&buf[..], 0) - }; - assert_eq!(got, data); - } - - #[test] - fn try_finish_size_prefixed_roundtrip() { - let mut builder = flatbuffers::FlatBufferBuilder::new(); - let args = &my_game::example::MonsterArgs { - mana: 200, - hp: 300, - name: Some(builder.try_create_string("bob").unwrap()), - ..Default::default() - }; - let mon = my_game::example::Monster::create(&mut builder, &args); - builder.try_finish_size_prefixed(mon, None).unwrap(); - - let buf = builder.finished_data(); - let m = flatbuffers::size_prefixed_root::(buf).unwrap(); - assert_eq!(m.mana(), 200); - assert_eq!(m.hp(), 300); - assert_eq!(m.name(), "bob"); - } - - #[test] - fn try_finish_with_file_identifier() { - let mut builder = flatbuffers::FlatBufferBuilder::new(); - let name = builder.try_create_string("foo").unwrap(); - let args = &my_game::example::MonsterArgs { - name: Some(name), - hp: 42, - ..Default::default() - }; - let mon = my_game::example::Monster::create(&mut builder, &args); - builder - .try_finish(mon, Some(my_game::example::MONSTER_IDENTIFIER)) - .unwrap(); - - let buf = builder.finished_data(); - assert!(my_game::example::monster_buffer_has_identifier(buf)); - let m = my_game::example::root_as_monster(buf).unwrap(); - assert_eq!(m.name(), "foo"); - assert_eq!(m.hp(), 42); - } -} - } diff --git a/tests/swift/Tests/Flatbuffers/ByteBufferTests.swift b/tests/swift/Tests/Flatbuffers/ByteBufferTests.swift index 1fc1d3c85..4851e990a 100644 --- a/tests/swift/Tests/Flatbuffers/ByteBufferTests.swift +++ b/tests/swift/Tests/Flatbuffers/ByteBufferTests.swift @@ -14,58 +14,51 @@ * limitations under the License. */ -import Foundation -import Testing +import XCTest @testable import FlatBuffers -struct ByteBufferTests { - - @Test +final class ByteBufferTests: XCTestCase { func testCopyingMemory() { let count = 100 let ptr = UnsafeMutableRawPointer.allocate(byteCount: count, alignment: 1) let byteBuffer = ByteBuffer(copyingMemoryBound: ptr, capacity: count) byteBuffer.withUnsafeBytes { memory in - #expect(memory.baseAddress! != ptr) + XCTAssertNotEqual(memory.baseAddress, ptr) } } - @Test func testSamePointer() { let count = 100 let ptr = UnsafeMutableRawPointer.allocate(byteCount: count, alignment: 1) let byteBuffer = ByteBuffer(assumingMemoryBound: ptr, capacity: count) byteBuffer.withUnsafeBytes { memory in - #expect(memory.baseAddress! == ptr) + XCTAssertEqual(memory.baseAddress!, ptr) } } - @Test func testSameDataPtr() { let count = 100 let ptr = Data(repeating: 0, count: count) let byteBuffer = ByteBuffer(data: ptr) byteBuffer.withUnsafeBytes { memory in ptr.withUnsafeBytes { ptr in - #expect(memory.baseAddress! == ptr.baseAddress!) + XCTAssertEqual(memory.baseAddress!, ptr.baseAddress!) } } } - @Test func testSameArrayPtr() { let count = 100 let ptr: [UInt8] = Array(repeating: 0, count: count) let byteBuffer = ByteBuffer(bytes: ptr) ptr.withUnsafeBytes { ptr in byteBuffer.withUnsafeBytes { memory in - #expect(memory.baseAddress == ptr.baseAddress) + XCTAssertEqual(memory.baseAddress, ptr.baseAddress) } } } - @Test func testReadingDoubleBuffer() { let count = 8 let array: [Double] = Array(repeating: 8.8, count: count) @@ -76,16 +69,15 @@ struct ByteBufferTests { } let byteBuffer = ByteBuffer(bytes: bytes) byteBuffer.withUnsafePointerToSlice(index: 0, count: count) { ptr in - #expect(ptr.count == count) + XCTAssertEqual(ptr.count, count) bytes.withUnsafeBufferPointer { - #expect( - UnsafeRawPointer($0.baseAddress) == - UnsafeRawPointer(ptr.baseAddress)) + XCTAssertEqual( + UnsafeRawPointer($0.baseAddress), + UnsafeRawPointer(ptr.baseAddress)) } } } - @Test func testReadingNativeStructs() { let array = [ MyGame_Example_Vec3( @@ -119,11 +111,11 @@ struct ByteBufferTests { let byteBuffer = ByteBuffer(bytes: bytes) byteBuffer .withUnsafePointerToSlice(index: 0, count: count) { bufferPointer in - #expect(bufferPointer.count == count) + XCTAssertEqual(bufferPointer.count, count) bytes.withUnsafeBufferPointer { ptr in - #expect( - UnsafeRawPointer(ptr.baseAddress) == - UnsafeRawPointer(bufferPointer.baseAddress)) + XCTAssertEqual( + UnsafeRawPointer(ptr.baseAddress), + UnsafeRawPointer(bufferPointer.baseAddress)) } } } @@ -134,3 +126,7 @@ private struct TestNativeStructs: NativeStruct { let y: Double let z: Int } + +extension MyGame_Example_Color: CaseIterable { + public static var allCases: [MyGame_Example_Color] = [.red, .blue, .green] +} diff --git a/tests/swift/Tests/Flatbuffers/FlatBuffersArraysTests.swift b/tests/swift/Tests/Flatbuffers/FlatBuffersArraysTests.swift index 79b40ddb7..7ea7b5b2d 100644 --- a/tests/swift/Tests/Flatbuffers/FlatBuffersArraysTests.swift +++ b/tests/swift/Tests/Flatbuffers/FlatBuffersArraysTests.swift @@ -16,22 +16,18 @@ #if compiler(>=6.2) -import Testing +import XCTest @testable import FlatBuffers -struct FlatBuffersArraysTests { +@available(macOS 26.0, iOS 26.0, watchOS 26.0, tvOS 26.0, *) +final class FlatBuffersArraysTests: XCTestCase { - @available(macOS 26.0, iOS 26.0, watchOS 26.0, tvOS 26.0, *) - @Test func testStructSizes() { - #expect(MemoryLayout.size == 32) - #expect(MemoryLayout.size == 160) - #expect((MemoryLayout.size == 2496)) + XCTAssertEqual(MemoryLayout.size, 32) + XCTAssertEqual(MemoryLayout.size, 160) } - @available(macOS 26.0, iOS 26.0, watchOS 26.0, tvOS 26.0, *) - @Test func testGoldenData() { // swiftformat:disable all let data: [UInt8] = [ @@ -48,11 +44,9 @@ struct FlatBuffersArraysTests { ] // swiftformat:enable all - #expect(data == createArrayTable()) + XCTAssertEqual(data, createArrayTable()) } - @available(macOS 26.0, iOS 26.0, watchOS 26.0, tvOS 26.0, *) - @Test func testData() throws { var buf = ByteBuffer(bytes: createArrayTable()) let table: MyGame_Example_ArrayTable = try getCheckedRoot( @@ -63,8 +57,6 @@ struct FlatBuffersArraysTests { verifyNativeStruct(a: table.a) } - @available(macOS 26.0, iOS 26.0, watchOS 26.0, tvOS 26.0, *) - @Test func testObjectAPI() throws { var buf = ByteBuffer(bytes: createArrayTable()) let table: MyGame_Example_ArrayTable = try getCheckedRoot( @@ -73,110 +65,105 @@ struct FlatBuffersArraysTests { verifyNativeStruct(a: table.unpack().a) } - @available(macOS 26.0, iOS 26.0, watchOS 26.0, tvOS 26.0, *) - @Test func testDefaults() { - #expect( - MyGame_Example_NestedStruct() == - MyGame_Example_NestedStruct( - a: [0, 0], - b: .a, - c: [0, 0], - d: [0, 0])) + XCTAssertEqual( + MyGame_Example_NestedStruct(), + MyGame_Example_NestedStruct( + a: [0, 0], + b: .a, + c: [0, 0], + d: [0, 0])) } - @available(macOS 26.0, iOS 26.0, watchOS 26.0, tvOS 26.0, *) func verifyNativeStruct(a: MyGame_Example_ArrayStruct?) { let a = a! - #expect(a.a == 12.34) - #expect(a.b.count == 15) + XCTAssertEqual(a.a, 12.34) + XCTAssertEqual(a.b.count, 15) var sum: Int32 = 0 for i in a.b.startIndex.. [UInt8] { var builder = FlatBufferBuilder(initialSize: 1024) @@ -246,3 +233,4 @@ extension InlineArray: @retroactive Equatable where Element: Equatable { } #endif + diff --git a/tests/swift/Tests/Flatbuffers/FlatBuffersMonsterWriterTests.swift b/tests/swift/Tests/Flatbuffers/FlatBuffersMonsterWriterTests.swift index 567d16ac9..d5e541c3e 100644 --- a/tests/swift/Tests/Flatbuffers/FlatBuffersMonsterWriterTests.swift +++ b/tests/swift/Tests/Flatbuffers/FlatBuffersMonsterWriterTests.swift @@ -15,7 +15,7 @@ */ import Foundation -import Testing +import XCTest @testable import FlatBuffers @@ -24,9 +24,8 @@ typealias Monster = MyGame_Example_Monster typealias Vec3 = MyGame_Example_Vec3 typealias Stat = MyGame_Example_Stat -struct FlatBuffersMonsterWriterTests { +class FlatBuffersMonsterWriterTests: XCTestCase { - @Test func testData() { // swiftformat:disable all let data = Data([ @@ -48,13 +47,12 @@ struct FlatBuffersMonsterWriterTests { readVerifiedMonster(fb: _data) } - @Test func testReadFromOtherLanguages() { let path = { #if os(macOS) // Gets the current path of this test file then // strips out the nested directories. - let filePath = URL(filePath: #filePath) + let filePath = URL(filePath: #file) .deletingLastPathComponent() return filePath.absoluteString #else @@ -73,7 +71,6 @@ struct FlatBuffersMonsterWriterTests { readVerifiedMonster(fb: _data) } - @Test func testCreateMonsterData() { let bytes = createMonster(withPrefix: false) var buffer = ByteBuffer(data: bytes.data) @@ -83,32 +80,30 @@ struct FlatBuffersMonsterWriterTests { readMonster(monster: monster) } - @Test(.bug("https://github.com/google/flatbuffers/issues/8642")) func testCreateMonsterResetTests() { var builder = createMonster(withPrefix: false) var buffer = ByteBuffer(data: builder.data) let monster: MyGame_Example_Monster = getRoot(byteBuffer: &buffer) readMonster(monster: monster) builder.clear() - #expect(builder.capacity == 1) - #expect(builder.size == 0) + XCTAssertEqual(builder.capacity, 1) + XCTAssertEqual(builder.size, 0) write(fbb: &builder, prefix: false) var _buffer = ByteBuffer(data: builder.data) - #expect(_buffer.capacity == 304) + XCTAssertEqual(_buffer.capacity, 304) let _monster: MyGame_Example_Monster = getRoot(byteBuffer: &_buffer) readMonster(monster: _monster) builder.clear(keepingCapacity: true) - #expect(builder.capacity == 512) - #expect(builder.size == 0) + XCTAssertEqual(builder.capacity, 512) + XCTAssertEqual(builder.size, 0) } - @Test func testCreateMonster() { let bytes = createMonster(withPrefix: false) // swiftformat:disable all - #expect( - bytes.sizedByteArray == + XCTAssertEqual( + bytes.sizedByteArray, [ 48, 0, 0, 0, 77, 79, 78, 83, 0, 0, 0, 0, 36, 0, 72, 0, 40, 0, 0, 0, 38, 0, 32, 0, 0, 0, 28, 0, 0, 0, 27, 0, 20, 0, 16, 0, 12, 0, 4, 0, 0, 0, 0, 0, 0, 0, 11, 0, 36, 0, 0, 0, 164, 0, 0, @@ -132,12 +127,11 @@ struct FlatBuffersMonsterWriterTests { readMonster(monster: monster) } - @Test func testCreateMonsterResizedBuffer() { let bytes = createMonster(withPrefix: false) // swiftformat:disable all - #expect( - bytes.sizedByteArray == + XCTAssertEqual( + bytes.sizedByteArray, [ 48, 0, 0, 0, 77, 79, 78, 83, 0, 0, 0, 0, 36, 0, 72, 0, 40, 0, 0, 0, 38, 0, 32, 0, 0, 0, 28, 0, 0, 0, 27, 0, 20, 0, 16, 0, 12, 0, 4, 0, 0, 0, 0, 0, 0, 0, 11, 0, 36, 0, 0, 0, 164, 0, 0, @@ -156,12 +150,11 @@ struct FlatBuffersMonsterWriterTests { readVerifiedMonster(fb: bytes.sizedBuffer) } - @Test func testCreateMonsterPrefixed() { let bytes = createMonster(withPrefix: true) // swiftformat:disable all - #expect( - bytes.sizedByteArray == + XCTAssertEqual( + bytes.sizedByteArray, [ 44, 1, 0, 0, 44, 0, 0, 0, 77, 79, 78, 83, 36, 0, 72, 0, 40, 0, 0, 0, 38, 0, 32, 0, 0, 0, 28, 0, 0, 0, 27, 0, 20, 0, 16, 0, 12, 0, 4, 0, 0, 0, 0, 0, 0, 0, 11, 0, 36, 0, 0, 0, 164, 0, 0, @@ -182,7 +175,6 @@ struct FlatBuffersMonsterWriterTests { readMonster(monster: getPrefixedSizeRoot(byteBuffer: &buffer)) } - @Test func testCreateMonsterUsingCreateMonsterMethodWithNilPos() { var fbb = FlatBufferBuilder(initialSize: 1) let name = fbb.create(string: "Frodo") @@ -192,11 +184,10 @@ struct FlatBuffersMonsterWriterTests { fbb.finish(offset: root) var buffer = fbb.sizedBuffer let newMonster: Monster = getRoot(byteBuffer: &buffer) - #expect(newMonster.pos == nil) - #expect(newMonster.name == "Frodo") + XCTAssertNil(newMonster.pos) + XCTAssertEqual(newMonster.name, "Frodo") } - @Test func testCreateMonsterUsingCreateMonsterMethodWithPosX() { var fbb = FlatBufferBuilder(initialSize: 1) let name = fbb.create(string: "Barney") @@ -216,11 +207,10 @@ struct FlatBuffersMonsterWriterTests { var buffer = fbb.sizedBuffer let newMonster: Monster = getRoot(byteBuffer: &buffer) - #expect(newMonster.pos!.x == 10) - #expect(newMonster.name == "Barney") + XCTAssertEqual(newMonster.pos!.x, 10) + XCTAssertEqual(newMonster.name, "Barney") } - @Test func testReadMonsterFromUnsafePointerWithoutCopying() { // swiftformat:disable all var array: [UInt8] = [ @@ -252,7 +242,6 @@ struct FlatBuffersMonsterWriterTests { readObjectApi(monster: unpacked) } - @Test func testArrayOfBools() { let boolArray = [false, true, false, true, false, true, false] var fbb = FlatBufferBuilder(initialSize: 1) @@ -268,41 +257,37 @@ struct FlatBuffersMonsterWriterTests { let monster: Monster = getRoot(byteBuffer: &buffer) let values = monster.testarrayofbools - #expect(boolArray.count == values.count) + XCTAssertEqual(boolArray.count, values.count) for (index, bool) in monster.testarrayofbools.enumerated() { - #expect(bool == boolArray[index]) + XCTAssertEqual(bool, boolArray[index]) } } func readVerifiedMonster(fb: ByteBuffer) { var byteBuffer = fb - do { + XCTAssertNoThrow( try readMonster( monster: getCheckedRoot( - byteBuffer: &byteBuffer) as MyGame_Example_Monster) - } catch { - Issue.record(error) - } + byteBuffer: &byteBuffer) as MyGame_Example_Monster)) } - @Test(.bug("https://github.com/google/flatbuffers/issues/8133")) func testUnalignedRead() { // Aligned read let fbb = createMonster(withPrefix: false) let testAligned: () -> Bool = { var buffer = fbb.sizedBuffer var monster: Monster = getRoot(byteBuffer: &buffer) - readFlatbufferMonster(monster: &monster) + self.readFlatbufferMonster(monster: &monster) return true } - #expect(testAligned() == true) + XCTAssertEqual(testAligned(), true) let testUnaligned: () -> Bool = { var bytes: [UInt8] = [0x00] bytes.append(contentsOf: fbb.sizedByteArray) return bytes.withUnsafeMutableBytes { ptr in guard var baseAddress = ptr.baseAddress else { - Issue.record("Base pointer is not defined") + XCTFail("Base pointer is not defined") return false } baseAddress = baseAddress.advanced(by: 1) @@ -311,14 +296,13 @@ struct FlatBuffersMonsterWriterTests { assumingMemoryBound: unlignedPtr, capacity: ptr.count - 1) var monster: Monster = getRoot(byteBuffer: &bytes) - readFlatbufferMonster(monster: &monster) + self.readFlatbufferMonster(monster: &monster) return true } } - #expect(testUnaligned() == true) + XCTAssertEqual(testUnaligned(), true) } - @Test func testReadingRemovedSizeUnalignedBuffer() { // Aligned read let fbb = createMonster(withPrefix: true) @@ -327,7 +311,7 @@ struct FlatBuffersMonsterWriterTests { bytes.append(contentsOf: fbb.sizedByteArray) return bytes.withUnsafeMutableBytes { ptr in guard var baseAddress = ptr.baseAddress else { - Issue.record("Base pointer is not defined") + XCTFail("Base pointer is not defined") return false } baseAddress = baseAddress.advanced(by: 1) @@ -337,34 +321,32 @@ struct FlatBuffersMonsterWriterTests { capacity: ptr.count - 1) var newBuf = FlatBuffersUtils.removeSizePrefix(bb: bytes) var monster: Monster = getRoot(byteBuffer: &newBuf) - readFlatbufferMonster(monster: &monster) + self.readFlatbufferMonster(monster: &monster) return true } } - #expect(testUnaligned() == true) + XCTAssertEqual(testUnaligned(), true) } - @Test func testCreateMessage() { let fbb = createMonster(withPrefix: false) let byteBuffer = fbb.buffer - let firstMessage = GRPCMessage(byteBuffer: byteBuffer) + let firstMessage = Message(byteBuffer: byteBuffer) firstMessage.withUnsafeReadableBytes { ptr in var bytes = ByteBuffer(contiguousBytes: ptr, count: ptr.count) var monster: Monster = getRoot(byteBuffer: &bytes) - readFlatbufferMonster(monster: &monster) + self.readFlatbufferMonster(monster: &monster) } let secondByteBuffer = fbb.sizedBuffer - let secondMessage = GRPCMessage(byteBuffer: secondByteBuffer) + let secondMessage = Message(byteBuffer: secondByteBuffer) secondMessage.withUnsafeReadableBytes { ptr in var bytes = ByteBuffer(contiguousBytes: ptr, count: ptr.count) var monster: Monster = getRoot(byteBuffer: &bytes) - readFlatbufferMonster(monster: &monster) + self.readFlatbufferMonster(monster: &monster) } } - @Test func testForceRetainedObject() { let byteBuffer = { // swiftformat:disable all @@ -470,95 +452,95 @@ struct FlatBuffersMonsterWriterTests { var fb = fb let monster: Monster = getRoot(byteBuffer: &fb) - #expect(monster.mutate(mana: 10) == false) - #expect(monster.testarrayoftables[0].name == "Barney") - #expect(monster.testarrayoftables[1].name == "Frodo") - #expect(monster.testarrayoftables[2].name == "Wilma") + XCTAssertFalse(monster.mutate(mana: 10)) + XCTAssertEqual(monster.testarrayoftables[0].name, "Barney") + XCTAssertEqual(monster.testarrayoftables[1].name, "Frodo") + XCTAssertEqual(monster.testarrayoftables[2].name, "Wilma") // Example of searching for a table by the key - #expect(monster.testarrayoftablesBy(key: "Frodo") != nil) - #expect(monster.testarrayoftablesBy(key: "Barney") != nil) - #expect(monster.testarrayoftablesBy(key: "Wilma") != nil) + XCTAssertNotNil(monster.testarrayoftablesBy(key: "Frodo")) + XCTAssertNotNil(monster.testarrayoftablesBy(key: "Barney")) + XCTAssertNotNil(monster.testarrayoftablesBy(key: "Wilma")) - #expect(monster.testType == .monster) + XCTAssertEqual(monster.testType, .monster) - #expect(monster.mutate(inventory: 1, at: 0) == true) - #expect(monster.mutate(inventory: 2, at: 1) == true) - #expect(monster.mutate(inventory: 3, at: 2) == true) - #expect(monster.mutate(inventory: 4, at: 3) == true) - #expect(monster.mutate(inventory: 5, at: 4) == true) + XCTAssertEqual(monster.mutate(inventory: 1, at: 0), true) + XCTAssertEqual(monster.mutate(inventory: 2, at: 1), true) + XCTAssertEqual(monster.mutate(inventory: 3, at: 2), true) + XCTAssertEqual(monster.mutate(inventory: 4, at: 3), true) + XCTAssertEqual(monster.mutate(inventory: 5, at: 4), true) for i in 0.. FlatBufferBuilder { var fbb = FlatBufferBuilder() @@ -79,4 +31,54 @@ struct FlatBuffersNanInfTests { fbb.finish(offset: msg) return fbb } + + func testInfNanBinary() { + let fbb = createTestTable() + let data = fbb.sizedByteArray + + var buffer = ByteBuffer(bytes: data) + let table: Swift_Tests_NanInfTable = getRoot(byteBuffer: &buffer) + XCTAssert(table.defaultNan.isNaN) + XCTAssertEqual(table.defaultInf, .infinity) + XCTAssertEqual(table.defaultNinf, -.infinity) + XCTAssert(table.valueNan.isNaN) + XCTAssertEqual(table.valueInf, .infinity) + XCTAssertEqual(table.valueNinf, -.infinity) + XCTAssertEqual(table.value, 100.0) + } + + func testInfNanJSON() { + let fbb = createTestTable() + var bb = fbb.sizedBuffer + do { + struct Test: Decodable { + let valueInf: Double + let value: Int + let valueNan: Double + let valueNinf: Double + } + let reader: Swift_Tests_NanInfTable = try getCheckedRoot(byteBuffer: &bb) + let encoder = JSONEncoder() + encoder.keyEncodingStrategy = .convertToSnakeCase + encoder.nonConformingFloatEncodingStrategy = + .convertToString( + positiveInfinity: "inf", + negativeInfinity: "-inf", + nan: "nan") + let data = try encoder.encode(reader) + let decoder = JSONDecoder() + decoder.nonConformingFloatDecodingStrategy = .convertFromString( + positiveInfinity: "inf", + negativeInfinity: "-inf", + nan: "nan") + decoder.keyDecodingStrategy = .convertFromSnakeCase + let value = try decoder.decode(Test.self, from: data) + XCTAssertEqual(value.value, 100) + XCTAssertEqual(value.valueInf, .infinity) + XCTAssertEqual(value.valueNinf, -.infinity) + } catch { + XCTFail(error.localizedDescription) + } + } + } diff --git a/tests/swift/Tests/Flatbuffers/FlatBuffersStructsTests.swift b/tests/swift/Tests/Flatbuffers/FlatBuffersStructsTests.swift index 33bbefe7c..b80c93e04 100644 --- a/tests/swift/Tests/Flatbuffers/FlatBuffersStructsTests.swift +++ b/tests/swift/Tests/Flatbuffers/FlatBuffersStructsTests.swift @@ -14,13 +14,12 @@ * limitations under the License. */ -import Testing +import XCTest @testable import FlatBuffers -struct FlatBuffersStructsTests { +final class FlatBuffersStructsTests: XCTestCase { - @Test func testWritingAndMutatingBools() { var fbb = FlatBufferBuilder() let start = TestMutatingBool.startTestMutatingBool(&fbb) @@ -31,11 +30,11 @@ struct FlatBuffersStructsTests { var buffer = fbb.sizedBuffer let testMutatingBool: TestMutatingBool = getRoot(byteBuffer: &buffer) let property = testMutatingBool.mutableB - #expect(property?.property == false) + XCTAssertEqual(property?.property, false) property?.mutate(property: false) - #expect(property?.property == false) + XCTAssertEqual(property?.property, false) property?.mutate(property: true) - #expect(property?.property == true) + XCTAssertEqual(property?.property, true) } } diff --git a/tests/swift/Tests/Flatbuffers/FlatBuffersTests.swift b/tests/swift/Tests/Flatbuffers/FlatBuffersTests.swift index 7dc4a34d4..7a01ecce0 100644 --- a/tests/swift/Tests/Flatbuffers/FlatBuffersTests.swift +++ b/tests/swift/Tests/Flatbuffers/FlatBuffersTests.swift @@ -14,49 +14,44 @@ * limitations under the License. */ -import Testing +import XCTest @testable import Common @testable import FlatBuffers -struct FlatBuffersTests { +final class FlatBuffersTests: XCTestCase { let country = "Norway" - @Test - func testEndian() { #expect(isLitteEndian == true) } + func testEndian() { XCTAssertEqual(isLitteEndian, true) } - @Test func testOffset() { let o = Offset() let b = Offset(offset: 1) - #expect(o.isEmpty == true) - #expect(b.isEmpty == false) + XCTAssertEqual(o.isEmpty, true) + XCTAssertEqual(b.isEmpty, false) } - @Test func testCreateString() { let helloWorld = "Hello, world!" var b = FlatBufferBuilder(initialSize: 16) - #expect(b.create(string: country).o == 12) - #expect(b.create(string: helloWorld).o == 32) + XCTAssertEqual(b.create(string: country).o, 12) + XCTAssertEqual(b.create(string: helloWorld).o, 32) b.clear() - #expect(b.create(string: helloWorld).o == 20) - #expect(b.create(string: country).o == 32) + XCTAssertEqual(b.create(string: helloWorld).o, 20) + XCTAssertEqual(b.create(string: country).o, 32) b.clear() - #expect(b.create(string: String(repeating: "a", count: 257)).o == 264) + XCTAssertEqual(b.create(string: String(repeating: "a", count: 257)).o, 264) } - @Test func testStartTable() { var b = FlatBufferBuilder(initialSize: 16) - _ = b.startTable(with: 0) + XCTAssertNoThrow(b.startTable(with: 0)) b.clear() - #expect(b.create(string: country).o == 12) - #expect(b.startTable(with: 0) == 12) + XCTAssertEqual(b.create(string: country).o, 12) + XCTAssertEqual(b.startTable(with: 0), 12) } - @Test func testCreateFinish() { var b = FlatBufferBuilder(initialSize: 16) let countryOff = Country.createCountry( @@ -71,10 +66,9 @@ struct FlatBuffersTests { 200, 0, 0, 0, 6, 0, 0, 0, 78, 111, 114, 119, 97, 121, 0, 0, ] // swiftformat:enable all - #expect(b.sizedByteArray == v) + XCTAssertEqual(b.sizedByteArray, v) } - @Test func testCreateFinishWithPrefix() { var b = FlatBufferBuilder(initialSize: 16) let countryOff = Country.createCountry( @@ -89,10 +83,9 @@ struct FlatBuffersTests { 100, 0, 0, 0, 200, 0, 0, 0, 6, 0, 0, 0, 78, 111, 114, 119, 97, 121, 0, 0, ] // swiftformat:enable all - #expect(b.sizedByteArray == v) + XCTAssertEqual(b.sizedByteArray, v) } - @Test func testReadCountry() { // swiftformat:disable all let v: [UInt8] = [ @@ -102,20 +95,18 @@ struct FlatBuffersTests { // swiftformat:enable all let buffer = ByteBuffer(bytes: v) let c = Country.getRootAsCountry(buffer) - #expect(c.lan == 100) - #expect(c.log == 200) - #expect(c.nameVector == [78, 111, 114, 119, 97, 121]) - #expect(c.name == country) + XCTAssertEqual(c.lan, 100) + XCTAssertEqual(c.log, 200) + XCTAssertEqual(c.nameVector, [78, 111, 114, 119, 97, 121]) + XCTAssertEqual(c.name, country) } - @Test func testWriteNullableStrings() { var b = FlatBufferBuilder() - #expect(b.create(string: nil).isEmpty) - #expect(b.createShared(string: nil).isEmpty) + XCTAssertTrue(b.create(string: nil).isEmpty) + XCTAssertTrue(b.createShared(string: nil).isEmpty) } - @Test func testWriteOptionalValues() { var b = FlatBufferBuilder() let root = optional_scalars_ScalarStuff.createScalarStuff( @@ -130,17 +121,16 @@ struct FlatBuffersTests { b.finish(offset: root) var buffer = b.sizedBuffer let scalarTable: optional_scalars_ScalarStuff = getRoot(byteBuffer: &buffer) - #expect(scalarTable.justI8 == 80) - #expect(scalarTable.maybeI8 == nil) - #expect(scalarTable.maybeBool == true) - #expect(scalarTable.defaultI8 == 42) - #expect(scalarTable.justU8 == 100) - #expect(scalarTable.maybeU8 == 10) - #expect(scalarTable.justEnum == .one) - #expect(scalarTable.maybeEnum == nil) + XCTAssertEqual(scalarTable.justI8, 80) + XCTAssertNil(scalarTable.maybeI8) + XCTAssertEqual(scalarTable.maybeBool, true) + XCTAssertEqual(scalarTable.defaultI8, 42) + XCTAssertEqual(scalarTable.justU8, 100) + XCTAssertEqual(scalarTable.maybeU8, 10) + XCTAssertEqual(scalarTable.justEnum, .one) + XCTAssertNil(scalarTable.maybeEnum) } - @Test func testAlignmentCrash() { var builder = FlatBufferBuilder(initialSize: 256) diff --git a/tests/swift/Tests/Flatbuffers/FlatBuffersUnionTests.swift b/tests/swift/Tests/Flatbuffers/FlatBuffersUnionTests.swift index faf8f93a1..bf43d592a 100644 --- a/tests/swift/Tests/Flatbuffers/FlatBuffersUnionTests.swift +++ b/tests/swift/Tests/Flatbuffers/FlatBuffersUnionTests.swift @@ -14,14 +14,12 @@ * limitations under the License. */ -import Foundation -import Testing +import XCTest @testable import FlatBuffers -struct FlatBuffersUnionTests { +final class FlatBuffersUnionTests: XCTestCase { - @Test func testCreateMonstor() { var b = FlatBufferBuilder(initialSize: 20) @@ -38,8 +36,8 @@ struct FlatBuffersUnionTests { b.finish(offset: root) let buffer = b.sizedByteArray // swiftformat:disable all - #expect( - buffer == + XCTAssertEqual( + buffer, [ 16, 0, 0, 0, 0, 0, 10, 0, 16, 0, 8, 0, 7, 0, 12, 0, 10, 0, 0, 0, 0, 0, 0, 1, 8, 0, 0, 0, 20, 0, 0, 0, 1, 0, 0, 0, 12, 0, 0, 0, 8, 0, 12, 0, 8, 0, 6, 0, 8, 0, 0, 0, 0, 0, 5, 0, 4, 0, 0, @@ -47,16 +45,15 @@ struct FlatBuffersUnionTests { ]) // swiftformat:enable all let monster = LocalMonster.getRootAsMonster(bb: ByteBuffer(bytes: buffer)) - #expect(monster.weapon(at: 0)?.dmg == dmg) - #expect(monster.weapon(at: 0)?.name == str) - #expect(monster.weapon(at: 0)?.nameVector == [65, 120, 101]) + XCTAssertEqual(monster.weapon(at: 0)?.dmg, dmg) + XCTAssertEqual(monster.weapon(at: 0)?.name, str) + XCTAssertEqual(monster.weapon(at: 0)?.nameVector, [65, 120, 101]) let p: Weapon? = monster.equiped() - #expect(p?.dmg == dmg) - #expect(p?.name == str) - #expect(p?.nameVector == [65, 120, 101]) + XCTAssertEqual(p?.dmg, dmg) + XCTAssertEqual(p?.name, str) + XCTAssertEqual(p?.nameVector, [65, 120, 101]) } - @Test func testEndTableFinish() { var builder = FlatBufferBuilder(initialSize: 20) let sword = builder.create(string: "Sword") @@ -87,8 +84,8 @@ struct FlatBuffersUnionTests { path: path) builder.finish(offset: orc) // swiftformat:disable all - #expect( - builder.sizedByteArray == + XCTAssertEqual( + builder.sizedByteArray, [ 32, 0, 0, 0, 0, 0, 26, 0, 48, 0, 36, 0, 0, 0, 34, 0, 28, 0, 0, 0, 24, 0, 23, 0, 16, 0, 15, 0, 8, 0, 4, 0, 26, 0, 0, 0, 44, 0, 0, 0, 104, 0, 0, 0, 0, 0, 0, 1, 60, 0, 0, 0, 0, 0, 0, 0, @@ -102,7 +99,6 @@ struct FlatBuffersUnionTests { // swiftformat:enable all } - @Test func testEnumVector() { let vectorOfEnums: [ColorsNameSpace.RGB] = [.blue, .green] @@ -113,8 +109,8 @@ struct FlatBuffersUnionTests { let end = ColorsNameSpace.Monster.endMonster(&builder, start: start) builder.finish(offset: end) // swiftformat:disable all - #expect( - builder.sizedByteArray == + XCTAssertEqual( + builder.sizedByteArray, [ 12, 0, 0, 0, 0, 0, 6, 0, 8, 0, 4, 0, 6, 0, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, 1, 0, 0, 0, @@ -122,13 +118,12 @@ struct FlatBuffersUnionTests { // swiftformat:enable all let monster = ColorsNameSpace.Monster .getRootAsMonster(bb: builder.sizedBuffer) - #expect(monster.colorsCount == 2) + XCTAssertEqual(monster.colorsCount, 2) let colors = monster.colors - #expect(colors[0] == .blue) - #expect(colors[1] == .green) + XCTAssertEqual(colors[0], .blue) + XCTAssertEqual(colors[1], .green) } - @Test func testUnionVector() { var fb = FlatBufferBuilder() @@ -154,30 +149,30 @@ struct FlatBuffersUnionTests { var buffer = fb.sizedBuffer let movie: Movie = getRoot(byteBuffer: &buffer) - #expect(movie.charactersType.count == characterType.count) - #expect(movie.characters.count == characters.count) + XCTAssertEqual(movie.charactersType.count, characterType.count) + XCTAssertEqual(movie.characters.count, characters.count) let bufferCharactersType = movie.charactersType for (index, element) in bufferCharactersType.enumerated() { - #expect(element == characterType[index]) + XCTAssertEqual(element, characterType[index]) } - #expect( - movie.characters(at: 0, type: BookReader_Mutable.self)?.booksRead == - 7) - #expect( - movie.characters(at: 1, type: Attacker.self)?.swordAttackDamage == - swordDmg) - #expect( - movie.characters(at: 2, type: BookReader_Mutable.self)?.booksRead == - 2) + XCTAssertEqual( + movie.characters(at: 0, type: BookReader_Mutable.self)?.booksRead, + 7) + XCTAssertEqual( + movie.characters(at: 1, type: Attacker.self)?.swordAttackDamage, + swordDmg) + XCTAssertEqual( + movie.characters(at: 2, type: BookReader_Mutable.self)?.booksRead, + 2) var objc: MovieT? = movie.unpack() - #expect( - movie.charactersType.count == objc?.characters.count ?? 0) - #expect( - movie.characters(at: 0, type: BookReader_Mutable.self)?.booksRead == - (objc?.characters[0]?.value as? BookReader)?.booksRead) + XCTAssertEqual( + movie.charactersType.count, objc?.characters.count ?? 0) + XCTAssertEqual( + movie.characters(at: 0, type: BookReader_Mutable.self)?.booksRead, + (objc?.characters[0]?.value as? BookReader)?.booksRead) fb.clear() let newMovie = Movie.pack(&fb, obj: &objc) fb.finish(offset: newMovie) @@ -185,18 +180,17 @@ struct FlatBuffersUnionTests { var _buffer = fb.sizedBuffer let packedMovie: Movie = getRoot(byteBuffer: &_buffer) - #expect( - packedMovie.characters(at: 0, type: BookReader_Mutable.self)?.booksRead == - movie.characters(at: 0, type: BookReader_Mutable.self)?.booksRead) - #expect( - packedMovie.characters(at: 1, type: Attacker.self)?.swordAttackDamage == - movie.characters(at: 1, type: Attacker.self)?.swordAttackDamage) - #expect( - packedMovie.characters(at: 2, type: BookReader_Mutable.self)?.booksRead == - movie.characters(at: 2, type: BookReader_Mutable.self)?.booksRead) + XCTAssertEqual( + packedMovie.characters(at: 0, type: BookReader_Mutable.self)?.booksRead, + movie.characters(at: 0, type: BookReader_Mutable.self)?.booksRead) + XCTAssertEqual( + packedMovie.characters(at: 1, type: Attacker.self)?.swordAttackDamage, + movie.characters(at: 1, type: Attacker.self)?.swordAttackDamage) + XCTAssertEqual( + packedMovie.characters(at: 2, type: BookReader_Mutable.self)?.booksRead, + movie.characters(at: 2, type: BookReader_Mutable.self)?.booksRead) } - @Test func testStringUnion() { let string = "Awesome \\\\t\t\nstring!" var fb = FlatBufferBuilder() @@ -220,31 +214,30 @@ struct FlatBuffersUnionTests { var buffer = fb.sizedBuffer let movie: Movie = getRoot(byteBuffer: &buffer) - #expect(movie.mainCharacter(type: String.self) == string) - #expect( - movie.characters(at: 0, type: BookReader_Mutable.self)?.booksRead == - 7) - #expect(movie.characters(at: 1, type: String.self) == string) + XCTAssertEqual(movie.mainCharacter(type: String.self), string) + XCTAssertEqual( + movie.characters(at: 0, type: BookReader_Mutable.self)?.booksRead, + 7) + XCTAssertEqual(movie.characters(at: 1, type: String.self), string) var objc: MovieT? = movie.unpack() - #expect(objc?.mainCharacter?.value as? String == string) - #expect((objc?.characters[0]?.value as? BookReader)?.booksRead == 7) - #expect(objc?.characters[1]?.value as? String == string) + XCTAssertEqual(objc?.mainCharacter?.value as? String, string) + XCTAssertEqual((objc?.characters[0]?.value as? BookReader)?.booksRead, 7) + XCTAssertEqual(objc?.characters[1]?.value as? String, string) fb.clear() let newMovie = Movie.pack(&fb, obj: &objc) fb.finish(offset: newMovie) var _buffer = fb.sizedBuffer let packedMovie: Movie = getRoot(byteBuffer: &_buffer) - #expect(packedMovie.mainCharacter(type: String.self) == string) - #expect( - packedMovie.characters(at: 0, type: BookReader_Mutable.self)?.booksRead == - 7) - #expect(packedMovie.characters(at: 1, type: String.self) == string) + XCTAssertEqual(packedMovie.mainCharacter(type: String.self), string) + XCTAssertEqual( + packedMovie.characters(at: 0, type: BookReader_Mutable.self)?.booksRead, + 7) + XCTAssertEqual(packedMovie.characters(at: 1, type: String.self), string) } - @Test - func testEncoding() throws { + func testEncoding() { let string = "Awesome \\\\t\t\nstring!" var fb = FlatBufferBuilder() @@ -272,12 +265,16 @@ struct FlatBuffersUnionTests { Movie.finish(&fb, end: end) var sizedBuffer = fb.sizedBuffer - let reader: Movie = try getCheckedRoot(byteBuffer: &sizedBuffer) - let encoder = JSONEncoder() - encoder.keyEncodingStrategy = .convertToSnakeCase - encoder.outputFormatting = [.sortedKeys] - let data = try encoder.encode(reader) - #expect(String(data: data, encoding: .utf8) == jsonData) + do { + let reader: Movie = try getCheckedRoot(byteBuffer: &sizedBuffer) + let encoder = JSONEncoder() + encoder.keyEncodingStrategy = .convertToSnakeCase + encoder.outputFormatting = [.sortedKeys] + let data = try encoder.encode(reader) + XCTAssertEqual(String(data: data, encoding: .utf8), jsonData) + } catch { + XCTFail(error.localizedDescription) + } } var jsonData: String { diff --git a/tests/swift/Tests/Flatbuffers/FlatBuffersVectorsTests.swift b/tests/swift/Tests/Flatbuffers/FlatBuffersVectorsTests.swift index 5ebcd528a..27d3a4610 100644 --- a/tests/swift/Tests/Flatbuffers/FlatBuffersVectorsTests.swift +++ b/tests/swift/Tests/Flatbuffers/FlatBuffersVectorsTests.swift @@ -14,13 +14,12 @@ * limitations under the License. */ -import Testing +import XCTest @testable import FlatBuffers -struct FlatBuffersVectors { +final class FlatBuffersVectors: XCTestCase { - @Test func testCreatingTwoCountries() { let norway = "Norway" let denmark = "Denmark" @@ -41,8 +40,8 @@ struct FlatBuffersVectors { let vectorOffset = b.createVector(ofOffsets: vector) b.finish(offset: vectorOffset) // swiftformat:disable all - #expect( - b.sizedByteArray == + XCTAssertEqual( + b.sizedByteArray, [ 4, 0, 0, 0, 2, 0, 0, 0, 48, 0, 0, 0, 16, 0, 0, 0, 0, 0, 10, 0, 18, 0, 4, 0, 8, 0, 12, 0, 10, 0, 0, 0, 40, 0, 0, 0, 100, 0, 0, 0, 200, 0, 0, 0, 0, 0, 10, 0, 16, 0, 4, 0, 8, 0, 12, 0, 10, @@ -52,20 +51,18 @@ struct FlatBuffersVectors { // swiftformat:enable all } - @Test func testCreateIntArray() { let numbers: [Int32] = [1, 2, 3, 4, 5] var b = FlatBufferBuilder(initialSize: 20) let o = b.createVector(numbers, size: numbers.count) b.finish(offset: o) // swiftformat:disable all - #expect( - b.sizedByteArray == + XCTAssertEqual( + b.sizedByteArray, [4, 0, 0, 0, 5, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0, 5, 0, 0, 0]) // swiftformat:enable all } - @Test func testCreateStructArray() { struct Vec: NativeStruct { let x, y, z: Float32 @@ -79,8 +76,8 @@ struct FlatBuffersVectors { let o = b.createVector(ofStructs: vector) b.finish(offset: o) // swiftformat:disable all - #expect( - b.sizedByteArray == + XCTAssertEqual( + b.sizedByteArray, [ 4, 0, 0, 0, 3, 0, 0, 0, 0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 64, 64, 0, 0, 128, 64, 0, 0, 160, 64, 0, 0, 192, 64, 0, 0, 224, 64, 0, 0, 0, 65, 0, 0, 16, 65, @@ -88,31 +85,28 @@ struct FlatBuffersVectors { // swiftformat:enable all } - @Test func testCreateEmptyIntArray() { let numbers: [Int32] = [] var b = FlatBufferBuilder(initialSize: 20) let o = b.createVector(numbers, size: numbers.count) b.finish(offset: o) - #expect(b.sizedByteArray == [4, 0, 0, 0, 0, 0, 0, 0]) + XCTAssertEqual(b.sizedByteArray, [4, 0, 0, 0, 0, 0, 0, 0]) } - @Test func testCreateVectorOfStrings() { let strs = ["Denmark", "Norway"] var b = FlatBufferBuilder(initialSize: 20) let o = b.createVector(ofStrings: strs) b.finish(offset: o) // swiftformat:disable all - #expect( - b.sizedByteArray == + XCTAssertEqual( + b.sizedByteArray, [ 4, 0, 0, 0, 2, 0, 0, 0, 20, 0, 0, 0, 4, 0, 0, 0, 6, 0, 0, 0, 78, 111, 114, 119, 97, 121, 0, 0, 7, 0, 0, 0, 68, 101, 110, 109, 97, 114, 107, 0, ]) // swiftformat:enable all } - @Test func testCreateSharedStringVector() { let norway = "Norway" let denmark = "Denmark" @@ -125,8 +119,8 @@ struct FlatBuffersVectors { let end = b.createVector(ofOffsets: v) b.finish(offset: end) // swiftformat:disable all - #expect( - b.sizedByteArray == + XCTAssertEqual( + b.sizedByteArray, [ 4, 0, 0, 0, 4, 0, 0, 0, 28, 0, 0, 0, 12, 0, 0, 0, 20, 0, 0, 0, 4, 0, 0, 0, 7, 0, 0, 0, 68, 101, 110, 109, 97, 114, 107, 0, 6, 0, 0, 0, 78, 111, 114, 119, 97, 121, 0, 0, @@ -134,7 +128,6 @@ struct FlatBuffersVectors { // swiftformat:enable all } - @Test func testReadInt32Array() { let data: [Int32] = [1, 2, 3, 4, 5] var b = FlatBufferBuilder(initialSize: 20) @@ -143,11 +136,10 @@ struct FlatBuffersVectors { b.finish(offset: end) let number = Numbers.getRootAsNumbers(ByteBuffer(bytes: b.sizedByteArray)) for (index, num) in number.vArrayInt32.enumerated() { - #expect(num == data[index]) + XCTAssertEqual(num, data[index]) } } - @Test func testReadDoubleArray() { let data: [Double] = [1, 2, 3, 4, 5] var b = FlatBufferBuilder(initialSize: 20) @@ -156,11 +148,10 @@ struct FlatBuffersVectors { b.finish(offset: end) let number = Numbers.getRootAsNumbers(ByteBuffer(bytes: b.sizedByteArray)) for (index, num) in number.vArrayDouble.enumerated() { - #expect(num == data[index]) + XCTAssertEqual(num, data[index]) } } - @Test func testHasForArray() { var builder = FlatBufferBuilder(initialSize: 20) let emptyVector = [UInt8]() @@ -175,14 +166,14 @@ struct FlatBuffersVectors { var byteBuffer = ByteBuffer(bytes: builder.sizedByteArray) let msg: Swift_Tests_Vectors = getRoot(byteBuffer: &byteBuffer) - #expect(msg.none_.isEmpty == true) - #expect(msg.empty.isEmpty == true) - #expect(msg.empty.count == 0) - #expect(msg.array.isEmpty == false) - #expect(msg.array.count == 3) + XCTAssertEqual(msg.none_.isEmpty, true) + XCTAssertEqual(msg.empty.isEmpty, true) + XCTAssertEqual(msg.empty.count, 0) + XCTAssertEqual(msg.array.isEmpty, false) + XCTAssertEqual(msg.array.count, 3) for i in msg.array.startIndex...size - try verifier.rangeInBuffer(position: 24, size: size) - #expect(throws: FlatbuffersErrors.outOfBounds(position: 34, end: 32)) { - try verifier.rangeInBuffer(position: 26, size: size) - } - #expect(throws: FlatbuffersErrors.outOfBounds(position: 34, end: 32)) { - try verifier.rangeInBuffer( - position: 26, - size: size) - } - #expect(throws: FlatbuffersErrors.outOfBounds(position: 38, end: 32)) { - try verifier.rangeInBuffer( - position: 30, - size: size) - } - #expect(throws: FlatbuffersErrors.outOfBounds(position: 40, end: 32)) { - try verifier.rangeInBuffer( - position: 32, - size: size) - } - #expect(throws: FlatbuffersErrors.outOfBounds(position: 42, end: 32)) { - try verifier.rangeInBuffer( - position: 34, - size: size) - } + XCTAssertNoThrow(try verifier.rangeInBuffer(position: 24, size: size)) + XCTAssertThrowsError(try verifier.rangeInBuffer(position: 26, size: size)) + XCTAssertThrowsError(try verifier.rangeInBuffer(position: 26, size: size)) + XCTAssertThrowsError(try verifier.rangeInBuffer(position: 30, size: size)) + XCTAssertThrowsError(try verifier.rangeInBuffer(position: 32, size: size)) + XCTAssertThrowsError(try verifier.rangeInBuffer(position: 34, size: size)) verifier = try! Verifier( buffer: &buffer, options: .init(maxDepth: 0, maxTableCount: 0, maxApparentSize: 4)) - - #expect(throws: FlatbuffersErrors.apparentSizeTooLarge) { + do { try verifier.rangeInBuffer(position: 24, size: size) + } catch { + XCTAssertEqual( + error as! FlatbuffersErrors, + .apparentSizeTooLarge) } } - @Test - func testPositionInBuffer() throws { + func testPositionInBuffer() { let verifier = try! Verifier(buffer: &buffer) - try verifier.inBuffer(position: 0, of: Int64.self) - try verifier.inBuffer(position: 24, of: Int64.self) - - #expect( - throws: FlatbuffersErrors.missAlignedPointer( - position: -9, - type: "Int64")) - { - try verifier.inBuffer(position: -9, of: Int64.self) - } - #expect( - throws: FlatbuffersErrors.missAlignedPointer( - position: 25, - type: "Int64")) - { - try verifier.inBuffer(position: 25, of: Int64.self) - } - #expect( - throws: FlatbuffersErrors.missAlignedPointer( - position: 26, - type: "Int32")) - { - try verifier.inBuffer(position: 26, of: Int32.self) - } - #expect( - throws: FlatbuffersErrors.missAlignedPointer( - position: 26, - type: "Int64")) - { - try verifier.inBuffer(position: 26, of: Int64.self) - } - #expect( - throws: FlatbuffersErrors.missAlignedPointer( - position: 30, - type: "Int64")) - { - try verifier.inBuffer(position: 30, of: Int64.self) - } - #expect(throws: FlatbuffersErrors.outOfBounds(position: 40, end: 32)) { - try verifier.inBuffer( - position: 32, - of: Int64.self) - } - #expect( - throws: FlatbuffersErrors.missAlignedPointer( - position: 34, - type: "Int64")) - { - try verifier.inBuffer(position: 34, of: Int64.self) - } + XCTAssertNoThrow(try verifier.inBuffer(position: 0, of: Int64.self)) + XCTAssertNoThrow(try verifier.inBuffer(position: 24, of: Int64.self)) + XCTAssertThrowsError(try verifier.inBuffer(position: -9, of: Int64.self)) + XCTAssertThrowsError(try verifier.inBuffer(position: 25, of: Int64.self)) + XCTAssertThrowsError(try verifier.inBuffer(position: 26, of: Int32.self)) + XCTAssertThrowsError(try verifier.inBuffer(position: 26, of: Int64.self)) + XCTAssertThrowsError(try verifier.inBuffer(position: 30, of: Int64.self)) + XCTAssertThrowsError(try verifier.inBuffer(position: 32, of: Int64.self)) + XCTAssertThrowsError(try verifier.inBuffer(position: 34, of: Int64.self)) } - @Test - func testVisitTable() throws { + func testVisitTable() { var verifier = try! Verifier(buffer: &validFlatbuffersObject) - _ = try verifier.visitTable(at: 48) + XCTAssertNoThrow(try verifier.visitTable(at: 48)) verifier.reset() } - @Test - func testTableVerifier() throws { + func testTableVerifier() { var verifier = try! Verifier(buffer: &validFlatbuffersObject) var tableVerifer = try! verifier.visitTable(at: 48) - #expect(verifier.depth == 1) - #expect(verifier.tableCount == 1) + XCTAssertEqual(verifier.depth, 1) + XCTAssertEqual(verifier.tableCount, 1) - try tableVerifer.visit( - field: 4, - fieldName: "Vec", - required: false, - type: Vec3.self) + XCTAssertNoThrow( + try tableVerifer.visit( + field: 4, + fieldName: "Vec", + required: false, + type: Vec3.self)) + XCTAssertNoThrow( + try tableVerifer.visit( + field: 8, + fieldName: "hp", + required: false, + type: Int16.self)) - try tableVerifer.visit( - field: 8, - fieldName: "hp", - required: false, - type: Int16.self) + XCTAssertNoThrow( + try tableVerifer.visit( + field: 10, + fieldName: "name", + required: true, + type: ForwardOffset.self)) - try tableVerifer.visit( - field: 10, - fieldName: "name", - required: true, - type: ForwardOffset.self) + XCTAssertNoThrow( + try tableVerifer.visit( + field: 14, + fieldName: "inventory", + required: false, + type: ForwardOffset>.self)) - try tableVerifer.visit( - field: 14, - fieldName: "inventory", - required: false, - type: ForwardOffset>.self) + XCTAssertNoThrow( + try tableVerifer.visit( + field: 22, + fieldName: "test4", + required: false, + type: ForwardOffset> + .self)) - try tableVerifer.visit( - field: 22, - fieldName: "test4", - required: false, - type: ForwardOffset> - .self) + XCTAssertNoThrow( + try tableVerifer.visit( + field: 24, + fieldName: "Vector of strings", + required: false, + type: ForwardOffset, String>>.self)) - try tableVerifer.visit( - field: 24, - fieldName: "Vector of strings", - required: false, - type: ForwardOffset, String>>.self) - - #expect(throws: FlatbuffersErrors.missAlignedPointer( - position: 25, - type: "UInt16")) - { + do { try tableVerifer.visit( field: 13, fieldName: "notvalid", required: false, type: Int16.self) + } catch { + XCTAssertEqual( + error as! FlatbuffersErrors, + .missAlignedPointer(position: 25, type: "UInt16")) } - try tableVerifer.visit( - unionKey: 18, - unionField: 20, - unionKeyName: "testType", - fieldName: "test", - required: false, - completion: { (verifier, key: MyGame_Example_Any_, pos) in - switch key { - case .none_: - break // NOTE - SWIFT doesnt support none - case .monster: - try ForwardOffset.verify( - &verifier, - at: pos, - of: MyGame_Example_Monster.self) - case .testsimpletablewithenum: - try ForwardOffset.verify( - &verifier, - at: pos, - of: MyGame_Example_TestSimpleTableWithEnum.self) - case .mygameExample2Monster: - try ForwardOffset.verify( - &verifier, - at: pos, - of: MyGame_Example2_Monster.self) - } - }) + do { + try tableVerifer.visit( + unionKey: 18, + unionField: 20, + unionKeyName: "testType", + fieldName: "test", + required: false, + completion: { (verifier, key: MyGame_Example_Any_, pos) in + switch key { + case .none_: + break + case .monster: + try ForwardOffset.verify( + &verifier, + at: pos, + of: MyGame_Example_Monster.self) + case .testsimpletablewithenum: + break + case .mygameExample2Monster: + break + } + }) + } catch { + XCTAssertEqual( + error as! FlatbuffersErrors, + .missAlignedPointer(position: 25, type: "UInt16")) + } tableVerifer.finish() - #expect(verifier.depth == 0) + XCTAssertEqual(verifier.depth, 0) } - @Test - func testVerifyUnionVectors() throws { + func testVerifyUnionVectors() { // swiftformat:disable all var byteBuffer = ByteBuffer(bytes: [ 20, 0, 0, 0, 77, 79, 86, 73, 12, 0, 12, 0, 0, 0, 0, 0, 8, 0, 4, 0, 12, 0, 0, 0, 8, 0, 0, 0, @@ -340,11 +281,10 @@ final class FlatbuffersVerifierTests { 0, 0, 7, 0, 0, 0, 0, 0, 6, 0, 8, 0, 4, 0, 6, 0, 0, 0, 8, 0, 0, 0, ]) // swiftformat:enable all - _ = try getCheckedRoot(byteBuffer: &byteBuffer) as Movie + XCTAssertNoThrow(try getCheckedRoot(byteBuffer: &byteBuffer) as Movie) } - @Test - func testErrorWrongFileId() throws{ + func testErrorWrongFileId() { // swiftformat:disable all var byteBuffer = ByteBuffer(bytes: [ 20, 0, 0, 0, 77, 79, 86, 73, 12, 0, 12, 0, 0, 0, 0, 0, 8, 0, 4, 0, 12, 0, 0, 0, 8, 0, 0, 0, @@ -352,14 +292,12 @@ final class FlatbuffersVerifierTests { 0, 0, 7, 0, 0, 0, 0, 0, 6, 0, 8, 0, 4, 0, 6, 0, 0, 0, 8, 0, 0, 0, ]) // swiftformat:enable all - #expect(throws: FlatbuffersErrors.bufferIdDidntMatchPassedId) { + XCTAssertThrowsError( try getCheckedRoot( byteBuffer: &byteBuffer, - fileId: "FLEX") as Movie - } + fileId: "FLEX") as Movie) } - @Test func testVerifyPrefixedBuffer() { // swiftformat:disable all var byteBuffer = ByteBuffer(bytes: [ @@ -368,123 +306,41 @@ final class FlatbuffersVerifierTests { 0, 2, 0, 0, 0, 7, 0, 0, 0, 0, 0, 6, 0, 8, 0, 4, 0, 6, 0, 0, 0, 8, 0, 0, 0, ]) // swiftformat:enable all - #expect(throws: FlatbuffersErrors.prefixedSizeNotEqualToBufferSize) { - try getCheckedPrefixedSizeRoot(byteBuffer: &byteBuffer) as Movie - } + XCTAssertThrowsError( + try getCheckedPrefixedSizeRoot(byteBuffer: &byteBuffer) as Movie) } - @Test - func testSizePrefixedVerifierUsesPostPrefixRoot() throws { - // The size prefix points to a valid empty decoy table at byte 44. The real - // root at byte 4 points to a truncated UInt64 vector that must be rejected. - let bytes: [UInt8] = [ - 44, 0, 0, 0, - 16, 0, 0, 0, - 6, 0, 8, 0, 4, 0, - 0, 0, 0, 0, 0, 0, - 12, 0, 0, 0, - 8, 0, 0, 0, 0, 0, 0, 0, - 2, 0, 0, 0, 65, 66, - 0, 0, - 4, 0, 4, 0, - 4, 0, 0, 0, - ] - - var strictBuffer = ByteBuffer(bytes: bytes) - #expect(throws: FlatbuffersErrors.self) { - try getCheckedPrefixedSizeRoot( - byteBuffer: &strictBuffer) as Swift_Tests_Vectors - } - - var prefixedBuffer = ByteBuffer(bytes: bytes) - #expect(throws: FlatbuffersErrors.self) { - try getPrefixedSizeCheckedRoot( - byteBuffer: &prefixedBuffer) as Swift_Tests_Vectors - } - - var builder = FlatBufferBuilder() - let movie = Movie.createMovie(&builder) - Movie.finish(&builder, end: movie, prefix: true) - var validBuffer = builder.sizedBuffer - let _: Movie = try getCheckedPrefixedSizeRoot( - byteBuffer: &validBuffer, - fileId: Movie.id) - - var shortBuffer = ByteBuffer(bytes: [0, 0, 0, 0]) - #expect(throws: FlatbuffersErrors.bufferDoesntContainID) { + func testFullVerifier() { + XCTAssertNoThrow( try getCheckedRoot( - byteBuffer: &shortBuffer, - fileId: Movie.id) as Movie - } - - var oversizedPrefix = ByteBuffer(bytes: [5, 0, 0, 0, 0, 0, 0, 0]) - #expect(throws: FlatbuffersErrors.outOfBounds(position: 9, end: 8)) { - try getPrefixedSizeCheckedRoot( - byteBuffer: &oversizedPrefix) as Movie - } - #expect(oversizedPrefix.reader == 0) + byteBuffer: &validFlatbuffersObject) as MyGame_Example_Monster) } - @Test - func testFullVerifier() throws { - _ = + func testFullVerifierWithFileId() { + XCTAssertNoThrow( try getCheckedRoot( - byteBuffer: &validFlatbuffersObject) as MyGame_Example_Monster + byteBuffer: &validFlatbuffersObject, + fileId: MyGame_Example_Monster.id) as MyGame_Example_Monster) } - @Test - func testFullVerifierWithFileId() throws { - _ = try getCheckedRoot( - byteBuffer: &validFlatbuffersObject, - fileId: MyGame_Example_Monster.id) as MyGame_Example_Monster - } - - @Test func testInvalidBuffer() { - #expect(throws: FlatbuffersErrors.self) { + XCTAssertThrowsError( try getCheckedRoot( - byteBuffer: &self.invalidFlatbuffersObject) as MyGame_Example_Monster - } + byteBuffer: &invalidFlatbuffersObject) as MyGame_Example_Monster) } - @Test func testInvalidBuffer2() { - #expect(throws: FlatbuffersErrors.self) { + XCTAssertThrowsError( try getCheckedRoot( - byteBuffer: &self.invalidFlatbuffersObject2) as MyGame_Example_Monster - } + byteBuffer: &invalidFlatbuffersObject2) as MyGame_Example_Monster) } - @Test func testInvalidBuffer3() { - #expect(throws: FlatbuffersErrors.self) { + XCTAssertThrowsError( try getCheckedRoot( - byteBuffer: &self.invalidFlatbuffersObject3) as MyGame_Example_Monster - } + byteBuffer: &invalidFlatbuffersObject3) as MyGame_Example_Monster) } - @Test(.bug("https://github.com/google/flatbuffers/issues/9082")) - func testRejectsTruncatedScalarVector() { - // swiftformat:disable all - var byteBuffer = ByteBuffer(bytes: [ - 16, 0, 0, 0, - 6, 0, 8, 0, - 4, 0, 0, 0, - 0, 0, 0, 0, - 12, 0, 0, 0, - 8, 0, 0, 0, - 0, 0, 0, 0, - 2, 0, 0, 0, - 65, 66, - ]) - // swiftformat:enable all - - #expect(throws: FlatbuffersErrors.self) { - try getCheckedRoot(byteBuffer: &byteBuffer) as Swift_Tests_Vectors - } - } - - @Test func testValidUnionBuffer() { let string = "Awesome \\\\t\t\nstring!" var fb = FlatBufferBuilder() @@ -506,14 +362,9 @@ final class FlatbuffersVerifierTests { charactersVectorOffset: characterVector) Movie.finish(&fb, end: end) var buf = fb.sizedBuffer - do { - _ = try getCheckedRoot(byteBuffer: &buf) as Movie - } catch { - Issue.record(error) - } + XCTAssertNoThrow(try getCheckedRoot(byteBuffer: &buf) as Movie) } - @Test func testNestedTables() throws { var builder = FlatBufferBuilder() let name = builder.create(string: "Monster") @@ -532,22 +383,22 @@ final class FlatbuffersVerifierTests { var verifier = try! Verifier(buffer: &sizedBuffer) var tableVerifer = try! verifier.visitTable( at: try getOffset(at: 0, within: verifier)) - #expect(verifier.depth == 1) - #expect(verifier.tableCount == 1) + XCTAssertEqual(verifier.depth, 1) + XCTAssertEqual(verifier.tableCount, 1) let position = try tableVerifer.dereference(28)! var nestedTable = try verifier.visitTable( at: try getOffset(at: position, within: verifier)) - #expect(verifier.depth == 2) - #expect(verifier.tableCount == 2) + XCTAssertEqual(verifier.depth, 2) + XCTAssertEqual(verifier.tableCount, 2) nestedTable.finish() - #expect(verifier.depth == 1) - #expect(verifier.tableCount == 2) + XCTAssertEqual(verifier.depth, 1) + XCTAssertEqual(verifier.tableCount, 2) tableVerifer.finish() - #expect(verifier.depth == 0) - #expect(verifier.tableCount == 2) + XCTAssertEqual(verifier.depth, 0) + XCTAssertEqual(verifier.tableCount, 2) } func add(buffer: inout ByteBuffer, v: Int32, p: Int) { diff --git a/tests/swift/Tests/Flatbuffers/MutatingBool_generated.swift b/tests/swift/Tests/Flatbuffers/MutatingBool_generated.swift index e2de1a1f6..b47159a4f 100644 --- a/tests/swift/Tests/Flatbuffers/MutatingBool_generated.swift +++ b/tests/swift/Tests/Flatbuffers/MutatingBool_generated.swift @@ -38,10 +38,10 @@ public struct Property: NativeStruct, FlatbuffersVectorInitializable, Verifiable } extension Property: Encodable { + enum CodingKeys: String, CodingKey { case property = "property" } - public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) if property != false { @@ -74,7 +74,7 @@ public struct Property_Mutable: FlatBufferStruct, FlatbuffersVectorInitializable } } -public struct TestMutatingBool: FlatBufferVerifiableTable, FlatbuffersVectorInitializable, ObjectAPIPacker { +public struct TestMutatingBool: FlatBufferTable, FlatbuffersVectorInitializable, Verifiable, ObjectAPIPacker { static func validateVersion() { FlatBuffersVersion_25_12_19() } public var __buffer: ByteBuffer! { return _accessor.bb } @@ -83,14 +83,16 @@ public struct TestMutatingBool: FlatBufferVerifiableTable, FlatbuffersVectorInit private init(_ t: Table) { _accessor = t } public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } - private struct VT { - static let b: VOffset = 4 + private enum VTOFFSET: VOffset { + case b = 4 + var v: Int32 { Int32(self.rawValue) } + var p: VOffset { self.rawValue } } - public var b: Property? { let o = _accessor.offset(VT.b); return o == 0 ? nil : _accessor.readBuffer(of: Property.self, at: o) } - public var mutableB: Property_Mutable? { let o = _accessor.offset(VT.b); return o == 0 ? nil : Property_Mutable(_accessor.bb, o: o + _accessor.position) } + public var b: Property? { let o = _accessor.offset(VTOFFSET.b.v); return o == 0 ? nil : _accessor.readBuffer(of: Property.self, at: o) } + public var mutableB: Property_Mutable? { let o = _accessor.offset(VTOFFSET.b.v); return o == 0 ? nil : Property_Mutable(_accessor.bb, o: o + _accessor.position) } public static func startTestMutatingBool(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) } - public static func add(b: Property?, _ fbb: inout FlatBufferBuilder) { guard let b = b else { return }; fbb.create(struct: b, position: VT.b) } + public static func add(b: Property?, _ fbb: inout FlatBufferBuilder) { guard let b = b else { return }; fbb.create(struct: b, position: VTOFFSET.b.p) } public static func endTestMutatingBool(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } public static func createTestMutatingBool( _ fbb: inout FlatBufferBuilder, @@ -117,16 +119,16 @@ public struct TestMutatingBool: FlatBufferVerifiableTable, FlatbuffersVectorInit public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { var _v = try verifier.visitTable(at: position) - try _v.visit(field: VT.b, fieldName: "b", required: false, type: Property.self) + try _v.visit(field: VTOFFSET.b.p, fieldName: "b", required: false, type: Property.self) _v.finish() } } extension TestMutatingBool: Encodable { + enum CodingKeys: String, CodingKey { case b = "b" } - public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(b, forKey: .b) diff --git a/tests/swift/Tests/Flatbuffers/arrays_test_generated.swift b/tests/swift/Tests/Flatbuffers/arrays_test_generated.swift index 01a1391bf..f433559f6 100644 --- a/tests/swift/Tests/Flatbuffers/arrays_test_generated.swift +++ b/tests/swift/Tests/Flatbuffers/arrays_test_generated.swift @@ -84,13 +84,13 @@ public struct MyGame_Example_NestedStruct: NativeStruct, FlatbuffersVectorInitia @available(macOS 26.0, iOS 26.0, watchOS 26.0, tvOS 26.0, *) extension MyGame_Example_NestedStruct: Encodable { + enum CodingKeys: String, CodingKey { case a = "a" case b = "b" case c = "c" case d = "d" } - public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) var aContainer = container.nestedUnkeyedContainer(forKey: .a) @@ -206,6 +206,7 @@ public struct MyGame_Example_ArrayStruct: NativeStruct, FlatbuffersVectorInitial @available(macOS 26.0, iOS 26.0, watchOS 26.0, tvOS 26.0, *) extension MyGame_Example_ArrayStruct: Encodable { + enum CodingKeys: String, CodingKey { case a = "a" case b = "b" @@ -214,7 +215,6 @@ extension MyGame_Example_ArrayStruct: Encodable { case e = "e" case f = "f" } - public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) if a != 0.0 { @@ -276,129 +276,7 @@ public struct MyGame_Example_ArrayStruct_Mutable: FlatBufferStruct, FlatbuffersV } @available(macOS 26.0, iOS 26.0, watchOS 26.0, tvOS 26.0, *) -public struct MyGame_Example_LargeArrayStruct: NativeStruct, FlatbuffersVectorInitializable, Verifiable, FlatbuffersInitializable, NativeObject { - - static func validateVersion() { FlatBuffersVersion_25_12_19() } - - private var _d: InlineArray<64, UInt8> - private var _e: InlineArray<64, Float32> - private var _f: InlineArray<64, Bool> - private var _g: InlineArray<64, MyGame_Example_NestedStruct> - private var _h: InlineArray<64, Int8> - - public init(_ bb: ByteBuffer, o: Int32) { - self = bb.read(def: Self.self, position: Int(o)) - } - - public init(d: InlineArray<64, UInt8>, e: InlineArray<64, Float32>, f: InlineArray<64, Bool>, g: InlineArray<64, MyGame_Example_NestedStruct>, h: InlineArray<64, Int8>) { - _d = d - _e = e - _f = f - _g = g - _h = h - } - - public init() { - _d = InlineArray(repeating: 0) - _e = InlineArray(repeating: 0.0) - _f = InlineArray(repeating: false) - _g = InlineArray(repeating: MyGame_Example_NestedStruct()) - _h = InlineArray(repeating: 0) - } - - public init(_ _t: borrowing MyGame_Example_LargeArrayStruct_Mutable) { - let _vd = _t.d - _d = InlineArray { _vd[$0] } - let _ve = _t.e - _e = InlineArray { _ve[$0] } - let _vf = _t.f - _f = InlineArray { _vf[$0] } - let _vg = _t.g - _g = InlineArray { _vg[$0].unpack() } - let _vh = _t.h - _h = InlineArray { _vh[$0].rawValue } - } - - public var d: InlineArray<64, UInt8> { _d } - public var e: InlineArray<64, Float32> { _e } - public var f: InlineArray<64, Bool> { _f } - public var g: InlineArray<64, MyGame_Example_NestedStruct> { _g } - public var h: InlineArray<64, MyGame_Example_TestEnum> { InlineArray { MyGame_Example_TestEnum(rawValue: _h[$0])! } } - - public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { - try verifier.inBuffer(position: position, of: MyGame_Example_LargeArrayStruct.self) - } -} - -@available(macOS 26.0, iOS 26.0, watchOS 26.0, tvOS 26.0, *) -extension MyGame_Example_LargeArrayStruct: Encodable { - enum CodingKeys: String, CodingKey { - case d = "d" - case e = "e" - case f = "f" - case g = "g" - case h = "h" - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - var dContainer = container.nestedUnkeyedContainer(forKey: .d) - for index in d.startIndex.. { return _accessor.vector(at: 0, count: 64, size: 1) } - @discardableResult public func mutate(d: UInt8, at index: Int32) -> Bool { return _accessor.mutate(d, index: 0 + (index * 1)) } - public var e: FlatbufferVector { return _accessor.vector(at: 64, count: 64, size: 4) } - @discardableResult public func mutate(e: Float32, at index: Int32) -> Bool { return _accessor.mutate(e, index: 64 + (index * 4)) } - public var f: FlatbufferVector { return _accessor.vector(at: 320, count: 64, size: 1) } - @discardableResult public func mutate(f: Bool, at index: Int32) -> Bool { return _accessor.mutate(f, index: 320 + (index * 1)) } - public var g: FlatbufferVector { return _accessor.vector(at: 384, count: 64, size: 32) } - public var h: FlatbufferVector { return _accessor.vector(at: 2432, count: 64, size: 1) } - @discardableResult public func mutate(h: MyGame_Example_TestEnum, at index: Int32) -> Bool { return _accessor.mutate(h.rawValue, index: 2432 + (index * 1)) } - - public func unpack() -> MyGame_Example_LargeArrayStruct { - return MyGame_Example_LargeArrayStruct(self) - } - public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_LargeArrayStruct?) -> Offset { - guard var obj = obj else { return Offset() } - return pack(&builder, obj: &obj) - } - - public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_LargeArrayStruct) -> Offset { - return builder.create(struct: obj) - } -} - -@available(macOS 26.0, iOS 26.0, watchOS 26.0, tvOS 26.0, *) -public struct MyGame_Example_ArrayTable: FlatBufferVerifiableTable, FlatbuffersVectorInitializable, ObjectAPIPacker { +public struct MyGame_Example_ArrayTable: FlatBufferTable, FlatbuffersVectorInitializable, Verifiable, ObjectAPIPacker { static func validateVersion() { FlatBuffersVersion_25_12_19() } public var __buffer: ByteBuffer! { return _accessor.bb } @@ -409,14 +287,16 @@ public struct MyGame_Example_ArrayTable: FlatBufferVerifiableTable, FlatbuffersV private init(_ t: Table) { _accessor = t } public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } - private struct VT { - static let a: VOffset = 4 + private enum VTOFFSET: VOffset { + case a = 4 + var v: Int32 { Int32(self.rawValue) } + var p: VOffset { self.rawValue } } - public var a: MyGame_Example_ArrayStruct? { let o = _accessor.offset(VT.a); return o == 0 ? nil : _accessor.readBuffer(of: MyGame_Example_ArrayStruct.self, at: o) } - public var mutableA: MyGame_Example_ArrayStruct_Mutable? { let o = _accessor.offset(VT.a); return o == 0 ? nil : MyGame_Example_ArrayStruct_Mutable(_accessor.bb, o: o + _accessor.position) } + public var a: MyGame_Example_ArrayStruct? { let o = _accessor.offset(VTOFFSET.a.v); return o == 0 ? nil : _accessor.readBuffer(of: MyGame_Example_ArrayStruct.self, at: o) } + public var mutableA: MyGame_Example_ArrayStruct_Mutable? { let o = _accessor.offset(VTOFFSET.a.v); return o == 0 ? nil : MyGame_Example_ArrayStruct_Mutable(_accessor.bb, o: o + _accessor.position) } public static func startArrayTable(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) } - public static func add(a: MyGame_Example_ArrayStruct?, _ fbb: inout FlatBufferBuilder) { guard let a = a else { return }; fbb.create(struct: a, position: VT.a) } + public static func add(a: MyGame_Example_ArrayStruct?, _ fbb: inout FlatBufferBuilder) { guard let a = a else { return }; fbb.create(struct: a, position: VTOFFSET.a.p) } public static func endArrayTable(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } public static func createArrayTable( _ fbb: inout FlatBufferBuilder, @@ -443,17 +323,17 @@ public struct MyGame_Example_ArrayTable: FlatBufferVerifiableTable, FlatbuffersV public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { var _v = try verifier.visitTable(at: position) - try _v.visit(field: VT.a, fieldName: "a", required: false, type: MyGame_Example_ArrayStruct.self) + try _v.visit(field: VTOFFSET.a.p, fieldName: "a", required: false, type: MyGame_Example_ArrayStruct.self) _v.finish() } } @available(macOS 26.0, iOS 26.0, watchOS 26.0, tvOS 26.0, *) extension MyGame_Example_ArrayTable: Encodable { + enum CodingKeys: String, CodingKey { case a = "a" } - public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(a, forKey: .a) diff --git a/tests/swift/Tests/Flatbuffers/monster_test.grpc.swift b/tests/swift/Tests/Flatbuffers/monster_test.grpc.swift index 2829c6734..cf7332ebf 100644 --- a/tests/swift/Tests/Flatbuffers/monster_test.grpc.swift +++ b/tests/swift/Tests/Flatbuffers/monster_test.grpc.swift @@ -5,568 +5,206 @@ // swiftlint:disable all // swiftformat:disable all -#if !os(Windows) && compiler(>=6.0) -import FlatBuffers +#if !os(Windows) import Foundation -import GRPCCore -import GRPCNIOTransportCore +import GRPC +import NIO +import NIOHTTP1 +import FlatBuffers - -/// Usage: instantiate MyGame.Example.MonsterStorageServiceClient, then call methods of this protocol to make API calls. -@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *) -extension FlatBuffersMessageSerializer: MessageSerializer { - public func serialize(_ message: Message) throws -> Bytes where Bytes : GRPCCore.GRPCContiguousBytes { - do { - return try self.serialize(message: message) { GRPCNIOTransportBytes($0) } as! Bytes - } catch let error { - throw RPCError( - code: .invalidArgument, - message: "Can't serialize message", - cause: error - ) - } +public protocol GRPCFlatBufPayload: GRPCPayload, FlatBufferGRPCMessage {} +public extension GRPCFlatBufPayload { + init(serializedByteBuffer: inout NIO.ByteBuffer) throws { + self.init(byteBuffer: FlatBuffers.ByteBuffer(contiguousBytes: serializedByteBuffer.readableBytesView, count: serializedByteBuffer.readableBytes)) + } + func serialize(into buffer: inout NIO.ByteBuffer) throws { + withUnsafeReadableBytes { buffer.writeBytes($0) } } } +extension Message: GRPCFlatBufPayload {} + +/// Usage: instantiate MyGame_Example_MonsterStorageServiceClient, then call methods of this protocol to make API calls. +public protocol MyGame_Example_MonsterStorageClientProtocol: GRPCClient { + + var serviceName: String { get } + + var interceptors: MyGame_Example_MonsterStorageClientInterceptorFactoryProtocol? { get } + + func Store( + _ request: Message + , callOptions: CallOptions? + ) -> UnaryCall, Message> + + func Retrieve( + _ request: Message + , callOptions: CallOptions?, + handler: @escaping (Message) -> Void + ) -> ServerStreamingCall, Message> + + func GetMaxHitPoint( + callOptions: CallOptions? + ) -> ClientStreamingCall, Message> + + func GetMinMaxHitPoints( + callOptions: CallOptions?, + handler: @escaping (Message ) -> Void + ) -> BidirectionalStreamingCall, Message> -@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *) -extension FlatBuffersMessageDeserializer: MessageDeserializer { - public func deserialize(_ serializedMessageBytes: Bytes) throws -> Message where Bytes : GRPCCore.GRPCContiguousBytes { - do { - return try serializedMessageBytes.withUnsafeBytes { - try self.deserialize(pointer: $0) - } - } catch let error { - throw RPCError( - code: .invalidArgument, - message: "Can't Decode message of type \(Message.self)", - cause: error - ) - } - } } -@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *) -public enum MyGame_Example_MonsterStorage: Sendable { - public static let descriptor = GRPCCore.ServiceDescriptor(fullyQualifiedService: "MyGame.Example.MonsterStorage") - public enum Method: Sendable { - public enum Store: Sendable { - public typealias Input = FlatBufferBuilder - public typealias Output = MyGame_Example_Stat - public static let descriptor = GRPCCore.MethodDescriptor( - service: GRPCCore.ServiceDescriptor(fullyQualifiedService: "MyGame.Example.MonsterStorage"), - method: "Store" - ) - } - public enum Retrieve: Sendable { - public typealias Input = FlatBufferBuilder - public typealias Output = MyGame_Example_Monster - public static let descriptor = GRPCCore.MethodDescriptor( - service: GRPCCore.ServiceDescriptor(fullyQualifiedService: "MyGame.Example.MonsterStorage"), - method: "Retrieve" - ) - } - public enum GetMaxHitPoint: Sendable { - public typealias Input = FlatBufferBuilder - public typealias Output = MyGame_Example_Stat - public static let descriptor = GRPCCore.MethodDescriptor( - service: GRPCCore.ServiceDescriptor(fullyQualifiedService: "MyGame.Example.MonsterStorage"), - method: "GetMaxHitPoint" - ) - } - public enum GetMinMaxHitPoints: Sendable { - public typealias Input = FlatBufferBuilder - public typealias Output = MyGame_Example_Stat - public static let descriptor = GRPCCore.MethodDescriptor( - service: GRPCCore.ServiceDescriptor(fullyQualifiedService: "MyGame.Example.MonsterStorage"), - method: "GetMinMaxHitPoints" - ) - } - public static let descriptors: [GRPCCore.MethodDescriptor] = [ - Store.descriptor, - Retrieve.descriptor, - GetMaxHitPoint.descriptor, - GetMinMaxHitPoints.descriptor, - ] - } -} +extension MyGame_Example_MonsterStorageClientProtocol { -@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *) -extension GRPCCore.ServiceDescriptor { - public static let MyGame_Example_MonsterStorage = GRPCCore.ServiceDescriptor(fullyQualifiedService: "MyGame.Example.MonsterStorage") -} + public var serviceName: String { "MyGame.Example.MonsterStorage" } -// MARK: MyGame.Example.MonsterStorage Server - -@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *) -extension MyGame_Example_MonsterStorage { - public protocol StreamingServiceProtocol: GRPCCore.RegistrableRPCService { - func Store( - request: GRPCCore.StreamingServerRequest>, - context: GRPCCore.ServerContext - ) async throws -> GRPCCore.StreamingServerResponse> - - func Retrieve( - request: GRPCCore.StreamingServerRequest>, - context: GRPCCore.ServerContext - ) async throws -> GRPCCore.StreamingServerResponse> - - func GetMaxHitPoint( - request: GRPCCore.StreamingServerRequest>, - context: GRPCCore.ServerContext - ) async throws -> GRPCCore.StreamingServerResponse> - - func GetMinMaxHitPoints( - request: GRPCCore.StreamingServerRequest>, - context: GRPCCore.ServerContext - ) async throws -> GRPCCore.StreamingServerResponse> - - } - - public protocol ServiceProtocol: MyGame_Example_MonsterStorage.StreamingServiceProtocol { - func Store( - request: GRPCCore.ServerRequest>, - context: GRPCCore.ServerContext - ) async throws -> GRPCCore.ServerResponse> - - func Retrieve( - request: GRPCCore.ServerRequest>, - context: GRPCCore.ServerContext - ) async throws -> GRPCCore.StreamingServerResponse> - - func GetMaxHitPoint( - request: GRPCCore.StreamingServerRequest>, - context: GRPCCore.ServerContext - ) async throws -> GRPCCore.ServerResponse> - - func GetMinMaxHitPoints( - request: GRPCCore.StreamingServerRequest>, - context: GRPCCore.ServerContext - ) async throws -> GRPCCore.StreamingServerResponse> - - } - - public protocol SimpleServiceProtocol: MyGame_Example_MonsterStorage.ServiceProtocol { - func Store( - request: GRPCMessage, - context: GRPCCore.ServerContext - ) async throws -> GRPCMessage - - func Retrieve( - request: GRPCMessage, - response: GRPCCore.RPCWriter>, - context: GRPCCore.ServerContext - ) async throws - - func GetMaxHitPoint( - request: GRPCCore.RPCAsyncSequence, any Swift.Error>, - context: GRPCCore.ServerContext - ) async throws -> GRPCMessage - - func GetMinMaxHitPoints( - request: GRPCCore.RPCAsyncSequence, any Swift.Error>, - response: GRPCCore.RPCWriter>, - context: GRPCCore.ServerContext - ) async throws - - } -} - -@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *) -extension MyGame_Example_MonsterStorage.StreamingServiceProtocol { - public func registerMethods(with router: inout GRPCCore.RPCRouter) where Transport: GRPCCore.ServerTransport { - router.registerHandler( - forMethod: MyGame_Example_MonsterStorage.Method.Store.descriptor, - deserializer: FlatBuffersMessageDeserializer>(), - serializer: FlatBuffersMessageSerializer>(), - handler: { request, context in - try await self.Store( - request: request, - context: context - ) - } - ) - router.registerHandler( - forMethod: MyGame_Example_MonsterStorage.Method.Retrieve.descriptor, - deserializer: FlatBuffersMessageDeserializer>(), - serializer: FlatBuffersMessageSerializer>(), - handler: { request, context in - try await self.Retrieve( - request: request, - context: context - ) - } - ) - router.registerHandler( - forMethod: MyGame_Example_MonsterStorage.Method.GetMaxHitPoint.descriptor, - deserializer: FlatBuffersMessageDeserializer>(), - serializer: FlatBuffersMessageSerializer>(), - handler: { request, context in - try await self.GetMaxHitPoint( - request: request, - context: context - ) - } - ) - router.registerHandler( - forMethod: MyGame_Example_MonsterStorage.Method.GetMinMaxHitPoints.descriptor, - deserializer: FlatBuffersMessageDeserializer>(), - serializer: FlatBuffersMessageSerializer>(), - handler: { request, context in - try await self.GetMinMaxHitPoints( - request: request, - context: context - ) - } - ) - } -} - -@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *) -extension MyGame_Example_MonsterStorage.ServiceProtocol { public func Store( - request: GRPCCore.StreamingServerRequest>, - context: GRPCCore.ServerContext - ) async throws -> GRPCCore.StreamingServerResponse> { - let response = try await self.Store( - request: GRPCCore.ServerRequest(stream: request), - context: context - ) - return GRPCCore.StreamingServerResponse(single: response) - } - public func Retrieve( - request: GRPCCore.StreamingServerRequest>, - context: GRPCCore.ServerContext - ) async throws -> GRPCCore.StreamingServerResponse> { - let response = try await self.Retrieve( - request: GRPCCore.ServerRequest(stream: request), - context: context - ) - return response - } - public func GetMaxHitPoint( - request: GRPCCore.StreamingServerRequest>, - context: GRPCCore.ServerContext - ) async throws -> GRPCCore.StreamingServerResponse> { - let response = try await self.GetMaxHitPoint( + _ request: Message + , callOptions: CallOptions? = nil + ) -> UnaryCall, Message> { + return self.makeUnaryCall( + path: "/MyGame.Example.MonsterStorage/Store", request: request, - context: context + callOptions: callOptions ?? self.defaultCallOptions, + interceptors: self.interceptors?.makeStoreInterceptors() ?? [] ) - return GRPCCore.StreamingServerResponse(single: response) } -} -@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *) -extension MyGame_Example_MonsterStorage.SimpleServiceProtocol { - public func Store( - request: GRPCCore.ServerRequest>, - context: GRPCCore.ServerContext - ) async throws -> GRPCCore.ServerResponse> { - return GRPCCore.ServerResponse>( - message: try await self.Store( - request: request.message, - context: context - ), - metadata: [:] - ) - } public func Retrieve( - request: GRPCCore.ServerRequest>, - context: GRPCCore.ServerContext - ) async throws -> GRPCCore.StreamingServerResponse> { - return GRPCCore.StreamingServerResponse>( - metadata: [:], - producer: { writer in - try await self.Retrieve( - request: request.message, - response: writer, - context: context - ) - return [:] - } + _ request: Message + , callOptions: CallOptions? = nil, + handler: @escaping (Message) -> Void + ) -> ServerStreamingCall, Message> { + return self.makeServerStreamingCall( + path: "/MyGame.Example.MonsterStorage/Retrieve", + request: request, + callOptions: callOptions ?? self.defaultCallOptions, + interceptors: self.interceptors?.makeRetrieveInterceptors() ?? [], + handler: handler ) } + public func GetMaxHitPoint( - request: GRPCCore.StreamingServerRequest>, - context: GRPCCore.ServerContext - ) async throws -> GRPCCore.ServerResponse> { - return GRPCCore.ServerResponse>( - message: try await self.GetMaxHitPoint( - request: request.messages, - context: context - ), - metadata: [:] + callOptions: CallOptions? = nil + ) -> ClientStreamingCall, Message> { + return self.makeClientStreamingCall( + path: "/MyGame.Example.MonsterStorage/GetMaxHitPoint", + callOptions: callOptions ?? self.defaultCallOptions, + interceptors: self.interceptors?.makeGetMaxHitPointInterceptors() ?? [] ) } + public func GetMinMaxHitPoints( - request: GRPCCore.StreamingServerRequest>, - context: GRPCCore.ServerContext - ) async throws -> GRPCCore.StreamingServerResponse> { - return GRPCCore.StreamingServerResponse>( - metadata: [:], - producer: { writer in - try await self.GetMinMaxHitPoints( - request: request.messages, - response: writer, - context: context - ) - return [:] - } + callOptions: CallOptions? = nil, + handler: @escaping (Message ) -> Void + ) -> BidirectionalStreamingCall, Message> { + return self.makeBidirectionalStreamingCall( + path: "/MyGame.Example.MonsterStorage/GetMinMaxHitPoints", + callOptions: callOptions ?? self.defaultCallOptions, + interceptors: self.interceptors?.makeGetMinMaxHitPointsInterceptors() ?? [], + handler: handler ) } } +public protocol MyGame_Example_MonsterStorageClientInterceptorFactoryProtocol { + /// - Returns: Interceptors to use when invoking 'Store'. + func makeStoreInterceptors() -> [ClientInterceptor, Message>] -// MARK: MyGame.Example.MonsterStorage Client + /// - Returns: Interceptors to use when invoking 'Retrieve'. + func makeRetrieveInterceptors() -> [ClientInterceptor, Message>] -@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *) -extension MyGame_Example_MonsterStorage { - public protocol ClientProtocol: Sendable { - func Store( - request: GRPCCore.ClientRequest>, - serializer: some GRPCCore.MessageSerializer>, - deserializer: some GRPCCore.MessageDeserializer>, - options: GRPCCore.CallOptions, - onResponse handleResponse: @Sendable @escaping (GRPCCore.ClientResponse>) async throws -> Result - ) async throws -> Result where Result: Sendable - - func Retrieve( - request: GRPCCore.ClientRequest>, - serializer: some GRPCCore.MessageSerializer>, - deserializer: some GRPCCore.MessageDeserializer>, - options: GRPCCore.CallOptions, - onResponse handleResponse: @Sendable @escaping (GRPCCore.StreamingClientResponse>) async throws -> Result - ) async throws -> Result where Result: Sendable - - func GetMaxHitPoint( - request: GRPCCore.StreamingClientRequest>, - serializer: some GRPCCore.MessageSerializer>, - deserializer: some GRPCCore.MessageDeserializer>, - options: GRPCCore.CallOptions, - onResponse handleResponse: @Sendable @escaping (GRPCCore.ClientResponse>) async throws -> Result - ) async throws -> Result where Result: Sendable - - func GetMinMaxHitPoints( - request: GRPCCore.StreamingClientRequest>, - serializer: some GRPCCore.MessageSerializer>, - deserializer: some GRPCCore.MessageDeserializer>, - options: GRPCCore.CallOptions, - onResponse handleResponse: @Sendable @escaping (GRPCCore.StreamingClientResponse>) async throws -> Result - ) async throws -> Result where Result: Sendable - + /// - Returns: Interceptors to use when invoking 'GetMaxHitPoint'. + func makeGetMaxHitPointInterceptors() -> [ClientInterceptor, Message>] + + /// - Returns: Interceptors to use when invoking 'GetMinMaxHitPoints'. + func makeGetMinMaxHitPointsInterceptors() -> [ClientInterceptor, Message>] + +} + +public final class MyGame_Example_MonsterStorageServiceClient: MyGame_Example_MonsterStorageClientProtocol { + public let channel: GRPCChannel + public var defaultCallOptions: CallOptions + public var interceptors: MyGame_Example_MonsterStorageClientInterceptorFactoryProtocol? + + public init( + channel: GRPCChannel, + defaultCallOptions: CallOptions = CallOptions(), + interceptors: MyGame_Example_MonsterStorageClientInterceptorFactoryProtocol? = nil + ) { + self.channel = channel + self.defaultCallOptions = defaultCallOptions + self.interceptors = interceptors } } -@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *) -extension MyGame_Example_MonsterStorage { - public struct Client: ClientProtocol where Transport: GRPCCore.ClientTransport { - private let client: GRPCCore.GRPCClient - - public init(wrapping client: GRPCCore.GRPCClient) { - self.client = client - } - - public func Store( - request: GRPCCore.ClientRequest>, - serializer: some GRPCCore.MessageSerializer>, - deserializer: some GRPCCore.MessageDeserializer>, - options: GRPCCore.CallOptions = .defaults, - onResponse handleResponse: @Sendable @escaping (GRPCCore.ClientResponse>) async throws -> Result = { response in try response.message } - ) async throws -> Result where Result: Sendable { - try await self.client.unary( - request: request, - descriptor: MyGame_Example_MonsterStorage.Method.Store.descriptor, - serializer: serializer, - deserializer: deserializer, - options: options, - onResponse: handleResponse - ) - } - - public func Retrieve( - request: GRPCCore.ClientRequest>, - serializer: some GRPCCore.MessageSerializer>, - deserializer: some GRPCCore.MessageDeserializer>, - options: GRPCCore.CallOptions = .defaults, - onResponse handleResponse: @Sendable @escaping (GRPCCore.StreamingClientResponse>) async throws -> Result - ) async throws -> Result where Result: Sendable { - try await self.client.serverStreaming( - request: request, - descriptor: MyGame_Example_MonsterStorage.Method.Retrieve.descriptor, - serializer: serializer, - deserializer: deserializer, - options: options, - onResponse: handleResponse - ) - } - - public func GetMaxHitPoint( - request: GRPCCore.StreamingClientRequest>, - serializer: some GRPCCore.MessageSerializer>, - deserializer: some GRPCCore.MessageDeserializer>, - options: GRPCCore.CallOptions = .defaults, - onResponse handleResponse: @Sendable @escaping (GRPCCore.ClientResponse>) async throws -> Result = { response in try response.message } - ) async throws -> Result where Result: Sendable { - try await self.client.clientStreaming( - request: request, - descriptor: MyGame_Example_MonsterStorage.Method.GetMaxHitPoint.descriptor, - serializer: serializer, - deserializer: deserializer, - options: options, - onResponse: handleResponse - ) - } - - public func GetMinMaxHitPoints( - request: GRPCCore.StreamingClientRequest>, - serializer: some GRPCCore.MessageSerializer>, - deserializer: some GRPCCore.MessageDeserializer>, - options: GRPCCore.CallOptions = .defaults, - onResponse handleResponse: @Sendable @escaping (GRPCCore.StreamingClientResponse>) async throws -> Result - ) async throws -> Result where Result: Sendable { - try await self.client.bidirectionalStreaming( - request: request, - descriptor: MyGame_Example_MonsterStorage.Method.GetMinMaxHitPoints.descriptor, - serializer: serializer, - deserializer: deserializer, - options: options, - onResponse: handleResponse - ) - } - - } +public protocol MyGame_Example_MonsterStorageProvider: CallHandlerProvider { + var interceptors: MyGame_Example_MonsterStorageServerInterceptorFactoryProtocol? { get } + func Store(request: Message, context: StatusOnlyCallContext) -> EventLoopFuture> + func Retrieve(request: Message, context: StreamingResponseCallContext>) -> EventLoopFuture + func GetMaxHitPoint(context: UnaryResponseCallContext>) -> EventLoopFuture<(StreamEvent>) -> Void> + func GetMinMaxHitPoints(context: StreamingResponseCallContext>) -> EventLoopFuture<(StreamEvent>) -> Void> } -@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *) -extension MyGame_Example_MonsterStorage.ClientProtocol { - public func Store( - request: GRPCCore.ClientRequest>, - options: GRPCCore.CallOptions = .defaults, - onResponse handleResponse: @Sendable @escaping (GRPCCore.ClientResponse>) async throws -> Result = { response in try response.message } - ) async throws -> Result where Result: Sendable { - try await self.Store( - request: request, - serializer: FlatBuffersMessageSerializer>(), - deserializer: FlatBuffersMessageDeserializer>(), - options: options, - onResponse: handleResponse - ) +public extension MyGame_Example_MonsterStorageProvider { + + var serviceName: Substring { return "MyGame.Example.MonsterStorage" } + + func handle(method name: Substring, context: CallHandlerContext) -> GRPCServerHandlerProtocol? { + switch name { + case "Store": + return UnaryServerHandler( + context: context, + requestDeserializer: GRPCPayloadDeserializer>(), + responseSerializer: GRPCPayloadSerializer>(), + interceptors: self.interceptors?.makeStoreInterceptors() ?? [], + userFunction: self.Store(request:context:)) + + case "Retrieve": + return ServerStreamingServerHandler( + context: context, + requestDeserializer: GRPCPayloadDeserializer>(), + responseSerializer: GRPCPayloadSerializer>(), + interceptors: self.interceptors?.makeRetrieveInterceptors() ?? [], + userFunction: self.Retrieve(request:context:)) + + case "GetMaxHitPoint": + return ClientStreamingServerHandler( + context: context, + requestDeserializer: GRPCPayloadDeserializer>(), + responseSerializer: GRPCPayloadSerializer>(), + interceptors: self.interceptors?.makeGetMaxHitPointInterceptors() ?? [], + observerFactory: self.GetMaxHitPoint(context:)) + + case "GetMinMaxHitPoints": + return BidirectionalStreamingServerHandler( + context: context, + requestDeserializer: GRPCPayloadDeserializer>(), + responseSerializer: GRPCPayloadSerializer>(), + interceptors: self.interceptors?.makeGetMinMaxHitPointsInterceptors() ?? [], + observerFactory: self.GetMinMaxHitPoints(context:)) + + default: return nil; + } } - - public func Retrieve( - request: GRPCCore.ClientRequest>, - options: GRPCCore.CallOptions = .defaults, - onResponse handleResponse: @Sendable @escaping (GRPCCore.StreamingClientResponse>) async throws -> Result - ) async throws -> Result where Result: Sendable { - try await self.Retrieve( - request: request, - serializer: FlatBuffersMessageSerializer>(), - deserializer: FlatBuffersMessageDeserializer>(), - options: options, - onResponse: handleResponse - ) - } - - public func GetMaxHitPoint( - request: GRPCCore.StreamingClientRequest>, - options: GRPCCore.CallOptions = .defaults, - onResponse handleResponse: @Sendable @escaping (GRPCCore.ClientResponse>) async throws -> Result = { response in try response.message } - ) async throws -> Result where Result: Sendable { - try await self.GetMaxHitPoint( - request: request, - serializer: FlatBuffersMessageSerializer>(), - deserializer: FlatBuffersMessageDeserializer>(), - options: options, - onResponse: handleResponse - ) - } - - public func GetMinMaxHitPoints( - request: GRPCCore.StreamingClientRequest>, - options: GRPCCore.CallOptions = .defaults, - onResponse handleResponse: @Sendable @escaping (GRPCCore.StreamingClientResponse>) async throws -> Result - ) async throws -> Result where Result: Sendable { - try await self.GetMinMaxHitPoints( - request: request, - serializer: FlatBuffersMessageSerializer>(), - deserializer: FlatBuffersMessageDeserializer>(), - options: options, - onResponse: handleResponse - ) - } - + } -@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *) -extension MyGame_Example_MonsterStorage.ClientProtocol { - public func Store( - _ message: GRPCMessage, - metadata: GRPCCore.Metadata = [:], - options: GRPCCore.CallOptions = .defaults, - onResponse handleResponse: @Sendable @escaping (GRPCCore.ClientResponse>) async throws -> Result = { try $0.message } - ) async throws -> Result where Result: Sendable { - let request = GRPCCore.ClientRequest>( - message: message, - metadata: metadata - ) - return try await self.Store( - request: request, - options: options, - onResponse: handleResponse - ) - } - - public func Retrieve( - _ message: GRPCMessage, - metadata: GRPCCore.Metadata = [:], - options: GRPCCore.CallOptions = .defaults, - onResponse handleResponse: @Sendable @escaping (GRPCCore.StreamingClientResponse>) async throws -> Result - ) async throws -> Result where Result: Sendable { - let request = GRPCCore.ClientRequest>( - message: message, - metadata: metadata - ) - return try await self.Retrieve( - request: request, - options: options, - onResponse: handleResponse - ) - } - - public func GetMaxHitPoint( - metadata: GRPCCore.Metadata = [:], - options: GRPCCore.CallOptions = .defaults, - requestProducer producer: @Sendable @escaping (GRPCCore.RPCWriter>) async throws -> Void, - onResponse handleResponse: @Sendable @escaping (GRPCCore.ClientResponse>) async throws -> Result = { try $0.message } - ) async throws -> Result where Result: Sendable { - let request = GRPCCore.StreamingClientRequest>( - metadata: metadata, - producer: producer - ) - return try await self.GetMaxHitPoint( - request: request, - options: options, - onResponse: handleResponse - ) - } - - public func GetMinMaxHitPoints( - metadata: GRPCCore.Metadata = [:], - options: GRPCCore.CallOptions = .defaults, - requestProducer producer: @Sendable @escaping (GRPCCore.RPCWriter>) async throws -> Void, - onResponse handleResponse: @Sendable @escaping (GRPCCore.StreamingClientResponse>) async throws -> Result - ) async throws -> Result where Result: Sendable { - let request = GRPCCore.StreamingClientRequest>( - metadata: metadata, - producer: producer - ) - return try await self.GetMinMaxHitPoints( - request: request, - options: options, - onResponse: handleResponse - ) - } - -} +public protocol MyGame_Example_MonsterStorageServerInterceptorFactoryProtocol { + /// - Returns: Interceptors to use when handling 'Store'. + /// Defaults to calling `self.makeInterceptors()`. + func makeStoreInterceptors() -> [ServerInterceptor, Message>] + /// - Returns: Interceptors to use when handling 'Retrieve'. + /// Defaults to calling `self.makeInterceptors()`. + func makeRetrieveInterceptors() -> [ServerInterceptor, Message>] + + /// - Returns: Interceptors to use when handling 'GetMaxHitPoint'. + /// Defaults to calling `self.makeInterceptors()`. + func makeGetMaxHitPointInterceptors() -> [ServerInterceptor, Message>] + + /// - Returns: Interceptors to use when handling 'GetMinMaxHitPoints'. + /// Defaults to calling `self.makeInterceptors()`. + func makeGetMinMaxHitPointsInterceptors() -> [ServerInterceptor, Message>] + +} #endif diff --git a/tests/swift/Tests/Flatbuffers/monster_test_generated.swift b/tests/swift/Tests/Flatbuffers/monster_test_generated.swift index 0dc49b02d..1702d8158 100644 --- a/tests/swift/Tests/Flatbuffers/monster_test_generated.swift +++ b/tests/swift/Tests/Flatbuffers/monster_test_generated.swift @@ -275,11 +275,11 @@ public struct MyGame_Example_Test: NativeStruct, FlatbuffersVectorInitializable, } extension MyGame_Example_Test: Encodable { + enum CodingKeys: String, CodingKey { case a = "a" case b = "b" } - public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) if a != 0 { @@ -376,6 +376,7 @@ public struct MyGame_Example_Vec3: NativeStruct, FlatbuffersVectorInitializable, } extension MyGame_Example_Vec3: Encodable { + enum CodingKeys: String, CodingKey { case x = "x" case y = "y" @@ -384,7 +385,6 @@ extension MyGame_Example_Vec3: Encodable { case test2 = "test2" case test3 = "test3" } - public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) if x != 0.0 { @@ -474,11 +474,11 @@ public struct MyGame_Example_Ability: NativeStruct, FlatbuffersVectorInitializab } extension MyGame_Example_Ability: Encodable { + enum CodingKeys: String, CodingKey { case id = "id" case distance = "distance" } - public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) if id != 0 { @@ -559,12 +559,12 @@ public struct MyGame_Example_StructOfStructs: NativeStruct, FlatbuffersVectorIni } extension MyGame_Example_StructOfStructs: Encodable { + enum CodingKeys: String, CodingKey { case a = "a" case b = "b" case c = "c" } - public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(a, forKey: .a) @@ -629,10 +629,10 @@ public struct MyGame_Example_StructOfStructsOfStructs: NativeStruct, Flatbuffers } extension MyGame_Example_StructOfStructsOfStructs: Encodable { + enum CodingKeys: String, CodingKey { case a = "a" } - public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(a, forKey: .a) @@ -662,7 +662,7 @@ public struct MyGame_Example_StructOfStructsOfStructs_Mutable: FlatBufferStruct, } } -public struct MyGame_InParentNamespace: FlatBufferVerifiableTable, FlatbuffersVectorInitializable, ObjectAPIPacker { +public struct MyGame_InParentNamespace: FlatBufferTable, FlatbuffersVectorInitializable, Verifiable, ObjectAPIPacker { static func validateVersion() { FlatBuffersVersion_25_12_19() } public var __buffer: ByteBuffer! { return _accessor.bb } @@ -696,6 +696,7 @@ public struct MyGame_InParentNamespace: FlatBufferVerifiableTable, FlatbuffersVe } extension MyGame_InParentNamespace: Encodable { + public func encode(to encoder: Encoder) throws { } } @@ -712,7 +713,7 @@ public class MyGame_InParentNamespaceT: NativeObject { public func serialize() -> ByteBuffer { return serialize(type: MyGame_InParentNamespace.self) } } -public struct MyGame_Example2_Monster: FlatBufferVerifiableTable, FlatbuffersVectorInitializable, ObjectAPIPacker { +public struct MyGame_Example2_Monster: FlatBufferTable, FlatbuffersVectorInitializable, Verifiable, ObjectAPIPacker { static func validateVersion() { FlatBuffersVersion_25_12_19() } public var __buffer: ByteBuffer! { return _accessor.bb } @@ -746,6 +747,7 @@ public struct MyGame_Example2_Monster: FlatBufferVerifiableTable, FlatbuffersVec } extension MyGame_Example2_Monster: Encodable { + public func encode(to encoder: Encoder) throws { } } @@ -762,7 +764,7 @@ public class MyGame_Example2_MonsterT: NativeObject { public func serialize() -> ByteBuffer { return serialize(type: MyGame_Example2_Monster.self) } } -internal struct MyGame_Example_TestSimpleTableWithEnum: FlatBufferVerifiableTable, FlatbuffersVectorInitializable, ObjectAPIPacker { +internal struct MyGame_Example_TestSimpleTableWithEnum: FlatBufferTable, FlatbuffersVectorInitializable, Verifiable, ObjectAPIPacker { static func validateVersion() { FlatBuffersVersion_25_12_19() } internal var __buffer: ByteBuffer! { return _accessor.bb } @@ -773,14 +775,16 @@ internal struct MyGame_Example_TestSimpleTableWithEnum: FlatBufferVerifiableTabl private init(_ t: Table) { _accessor = t } internal init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } - private struct VT { - static let color: VOffset = 4 + private enum VTOFFSET: VOffset { + case color = 4 + var v: Int32 { Int32(self.rawValue) } + var p: VOffset { self.rawValue } } - internal var color: MyGame_Example_Color { let o = _accessor.offset(VT.color); return o == 0 ? .green : MyGame_Example_Color(rawValue: _accessor.readBuffer(of: UInt8.self, at: o)) ?? .green } - @discardableResult internal func mutate(color: MyGame_Example_Color) -> Bool {let o = _accessor.offset(VT.color); return _accessor.mutate(color.rawValue, index: o) } + internal var color: MyGame_Example_Color { let o = _accessor.offset(VTOFFSET.color.v); return o == 0 ? .green : MyGame_Example_Color(rawValue: _accessor.readBuffer(of: UInt8.self, at: o)) ?? .green } + @discardableResult internal func mutate(color: MyGame_Example_Color) -> Bool {let o = _accessor.offset(VTOFFSET.color.v); return _accessor.mutate(color.rawValue, index: o) } internal static func startTestSimpleTableWithEnum(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) } - internal static func add(color: MyGame_Example_Color, _ fbb: inout FlatBufferBuilder) { fbb.add(element: color.rawValue, def: 2, at: VT.color) } + internal static func add(color: MyGame_Example_Color, _ fbb: inout FlatBufferBuilder) { fbb.add(element: color.rawValue, def: 2, at: VTOFFSET.color.p) } internal static func endTestSimpleTableWithEnum(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } internal static func createTestSimpleTableWithEnum( _ fbb: inout FlatBufferBuilder, @@ -807,16 +811,16 @@ internal struct MyGame_Example_TestSimpleTableWithEnum: FlatBufferVerifiableTabl internal static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { var _v = try verifier.visitTable(at: position) - try _v.visit(field: VT.color, fieldName: "color", required: false, type: MyGame_Example_Color.self) + try _v.visit(field: VTOFFSET.color.p, fieldName: "color", required: false, type: MyGame_Example_Color.self) _v.finish() } } extension MyGame_Example_TestSimpleTableWithEnum: Encodable { + enum CodingKeys: String, CodingKey { case color = "color" } - internal func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) if color != .green { @@ -840,7 +844,7 @@ internal class MyGame_Example_TestSimpleTableWithEnumT: NativeObject { internal func serialize() -> ByteBuffer { return serialize(type: MyGame_Example_TestSimpleTableWithEnum.self) } } -public struct MyGame_Example_Stat: FlatBufferVerifiableTable, FlatbuffersVectorInitializable, ObjectAPIPacker { +public struct MyGame_Example_Stat: FlatBufferTable, FlatbuffersVectorInitializable, Verifiable, ObjectAPIPacker { static func validateVersion() { FlatBuffersVersion_25_12_19() } public var __buffer: ByteBuffer! { return _accessor.bb } @@ -851,22 +855,24 @@ public struct MyGame_Example_Stat: FlatBufferVerifiableTable, FlatbuffersVectorI private init(_ t: Table) { _accessor = t } public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } - private struct VT { - static let id: VOffset = 4 - static let val: VOffset = 6 - static let count: VOffset = 8 + private enum VTOFFSET: VOffset { + case id = 4 + case val = 6 + case count = 8 + var v: Int32 { Int32(self.rawValue) } + var p: VOffset { self.rawValue } } - public var id: String? { let o = _accessor.offset(VT.id); return o == 0 ? nil : _accessor.string(at: o) } - public var idSegmentArray: [UInt8]? { return _accessor.getVector(at: VT.id) } - public var val: Int64 { let o = _accessor.offset(VT.val); return o == 0 ? 0 : _accessor.readBuffer(of: Int64.self, at: o) } - @discardableResult public func mutate(val: Int64) -> Bool {let o = _accessor.offset(VT.val); return _accessor.mutate(val, index: o) } - public var count: UInt16 { let o = _accessor.offset(VT.count); return o == 0 ? 0 : _accessor.readBuffer(of: UInt16.self, at: o) } - @discardableResult public func mutate(count: UInt16) -> Bool {let o = _accessor.offset(VT.count); return _accessor.mutate(count, index: o) } + public var id: String? { let o = _accessor.offset(VTOFFSET.id.v); return o == 0 ? nil : _accessor.string(at: o) } + public var idSegmentArray: [UInt8]? { return _accessor.getVector(at: VTOFFSET.id.v) } + public var val: Int64 { let o = _accessor.offset(VTOFFSET.val.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int64.self, at: o) } + @discardableResult public func mutate(val: Int64) -> Bool {let o = _accessor.offset(VTOFFSET.val.v); return _accessor.mutate(val, index: o) } + public var count: UInt16 { let o = _accessor.offset(VTOFFSET.count.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt16.self, at: o) } + @discardableResult public func mutate(count: UInt16) -> Bool {let o = _accessor.offset(VTOFFSET.count.v); return _accessor.mutate(count, index: o) } public static func startStat(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 3) } - public static func add(id: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: id, at: VT.id) } - public static func add(val: Int64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: val, def: 0, at: VT.val) } - public static func add(count: UInt16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: count, def: 0, at: VT.count) } + public static func add(id: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: id, at: VTOFFSET.id.p) } + public static func add(val: Int64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: val, def: 0, at: VTOFFSET.val.p) } + public static func add(count: UInt16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: count, def: 0, at: VTOFFSET.count.p) } public static func endStat(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } public static func createStat( _ fbb: inout FlatBufferBuilder, @@ -930,20 +936,20 @@ public struct MyGame_Example_Stat: FlatBufferVerifiableTable, FlatbuffersVectorI public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { var _v = try verifier.visitTable(at: position) - try _v.visit(field: VT.id, fieldName: "id", required: false, type: ForwardOffset.self) - try _v.visit(field: VT.val, fieldName: "val", required: false, type: Int64.self) - try _v.visit(field: VT.count, fieldName: "count", required: false, type: UInt16.self) + try _v.visit(field: VTOFFSET.id.p, fieldName: "id", required: false, type: ForwardOffset.self) + try _v.visit(field: VTOFFSET.val.p, fieldName: "val", required: false, type: Int64.self) + try _v.visit(field: VTOFFSET.count.p, fieldName: "count", required: false, type: UInt16.self) _v.finish() } } extension MyGame_Example_Stat: Encodable { + enum CodingKeys: String, CodingKey { case id = "id" case val = "val" case count = "count" } - public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(id, forKey: .id) @@ -976,7 +982,7 @@ public class MyGame_Example_StatT: NativeObject { public func serialize() -> ByteBuffer { return serialize(type: MyGame_Example_Stat.self) } } -public struct MyGame_Example_Referrable: FlatBufferVerifiableTable, FlatbuffersVectorInitializable, ObjectAPIPacker { +public struct MyGame_Example_Referrable: FlatBufferTable, FlatbuffersVectorInitializable, Verifiable, ObjectAPIPacker { static func validateVersion() { FlatBuffersVersion_25_12_19() } public var __buffer: ByteBuffer! { return _accessor.bb } @@ -987,14 +993,16 @@ public struct MyGame_Example_Referrable: FlatBufferVerifiableTable, FlatbuffersV private init(_ t: Table) { _accessor = t } public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } - private struct VT { - static let id: VOffset = 4 + private enum VTOFFSET: VOffset { + case id = 4 + var v: Int32 { Int32(self.rawValue) } + var p: VOffset { self.rawValue } } - public var id: UInt64 { let o = _accessor.offset(VT.id); return o == 0 ? 0 : _accessor.readBuffer(of: UInt64.self, at: o) } - @discardableResult public func mutate(id: UInt64) -> Bool {let o = _accessor.offset(VT.id); return _accessor.mutate(id, index: o) } + public var id: UInt64 { let o = _accessor.offset(VTOFFSET.id.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt64.self, at: o) } + @discardableResult public func mutate(id: UInt64) -> Bool {let o = _accessor.offset(VTOFFSET.id.v); return _accessor.mutate(id, index: o) } public static func startReferrable(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) } - public static func add(id: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: id, def: 0, at: VT.id) } + public static func add(id: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: id, def: 0, at: VTOFFSET.id.p) } public static func endReferrable(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } public static func createReferrable( _ fbb: inout FlatBufferBuilder, @@ -1045,16 +1053,16 @@ public struct MyGame_Example_Referrable: FlatBufferVerifiableTable, FlatbuffersV public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { var _v = try verifier.visitTable(at: position) - try _v.visit(field: VT.id, fieldName: "id", required: false, type: UInt64.self) + try _v.visit(field: VTOFFSET.id.p, fieldName: "id", required: false, type: UInt64.self) _v.finish() } } extension MyGame_Example_Referrable: Encodable { + enum CodingKeys: String, CodingKey { case id = "id" } - public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) if id != 0 { @@ -1079,7 +1087,7 @@ public class MyGame_Example_ReferrableT: NativeObject { } /// an example documentation comment: "monster object" -public struct MyGame_Example_Monster: FlatBufferVerifiableTable, FlatbuffersVectorInitializable, ObjectAPIPacker { +public struct MyGame_Example_Monster: FlatBufferTable, FlatbuffersVectorInitializable, Verifiable, ObjectAPIPacker { static func validateVersion() { FlatBuffersVersion_25_12_19() } public var __buffer: ByteBuffer! { return _accessor.bb } @@ -1090,267 +1098,269 @@ public struct MyGame_Example_Monster: FlatBufferVerifiableTable, FlatbuffersVect private init(_ t: Table) { _accessor = t } public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } - private struct VT { - static let pos: VOffset = 4 - static let mana: VOffset = 6 - static let hp: VOffset = 8 - static let name: VOffset = 10 - static let inventory: VOffset = 14 - static let color: VOffset = 16 - static let testType: VOffset = 18 - static let test: VOffset = 20 - static let test4: VOffset = 22 - static let testarrayofstring: VOffset = 24 - static let testarrayoftables: VOffset = 26 - static let enemy: VOffset = 28 - static let testnestedflatbuffer: VOffset = 30 - static let testempty: VOffset = 32 - static let testbool: VOffset = 34 - static let testhashs32Fnv1: VOffset = 36 - static let testhashu32Fnv1: VOffset = 38 - static let testhashs64Fnv1: VOffset = 40 - static let testhashu64Fnv1: VOffset = 42 - static let testhashs32Fnv1a: VOffset = 44 - static let testhashu32Fnv1a: VOffset = 46 - static let testhashs64Fnv1a: VOffset = 48 - static let testhashu64Fnv1a: VOffset = 50 - static let testarrayofbools: VOffset = 52 - static let testf: VOffset = 54 - static let testf2: VOffset = 56 - static let testf3: VOffset = 58 - static let testarrayofstring2: VOffset = 60 - static let testarrayofsortedstruct: VOffset = 62 - static let flex: VOffset = 64 - static let test5: VOffset = 66 - static let vectorOfLongs: VOffset = 68 - static let vectorOfDoubles: VOffset = 70 - static let parentNamespaceTest: VOffset = 72 - static let vectorOfReferrables: VOffset = 74 - static let singleWeakReference: VOffset = 76 - static let vectorOfWeakReferences: VOffset = 78 - static let vectorOfStrongReferrables: VOffset = 80 - static let coOwningReference: VOffset = 82 - static let vectorOfCoOwningReferences: VOffset = 84 - static let nonOwningReference: VOffset = 86 - static let vectorOfNonOwningReferences: VOffset = 88 - static let anyUniqueType: VOffset = 90 - static let anyUnique: VOffset = 92 - static let anyAmbiguousType: VOffset = 94 - static let anyAmbiguous: VOffset = 96 - static let vectorOfEnums: VOffset = 98 - static let signedEnum: VOffset = 100 - static let testrequirednestedflatbuffer: VOffset = 102 - static let scalarKeySortedTables: VOffset = 104 - static let nativeInline: VOffset = 106 - static let longEnumNonEnumDefault: VOffset = 108 - static let longEnumNormalDefault: VOffset = 110 - static let nanDefault: VOffset = 112 - static let infDefault: VOffset = 114 - static let positiveInfDefault: VOffset = 116 - static let infinityDefault: VOffset = 118 - static let positiveInfinityDefault: VOffset = 120 - static let negativeInfDefault: VOffset = 122 - static let negativeInfinityDefault: VOffset = 124 - static let doubleInfDefault: VOffset = 126 + private enum VTOFFSET: VOffset { + case pos = 4 + case mana = 6 + case hp = 8 + case name = 10 + case inventory = 14 + case color = 16 + case testType = 18 + case test = 20 + case test4 = 22 + case testarrayofstring = 24 + case testarrayoftables = 26 + case enemy = 28 + case testnestedflatbuffer = 30 + case testempty = 32 + case testbool = 34 + case testhashs32Fnv1 = 36 + case testhashu32Fnv1 = 38 + case testhashs64Fnv1 = 40 + case testhashu64Fnv1 = 42 + case testhashs32Fnv1a = 44 + case testhashu32Fnv1a = 46 + case testhashs64Fnv1a = 48 + case testhashu64Fnv1a = 50 + case testarrayofbools = 52 + case testf = 54 + case testf2 = 56 + case testf3 = 58 + case testarrayofstring2 = 60 + case testarrayofsortedstruct = 62 + case flex = 64 + case test5 = 66 + case vectorOfLongs = 68 + case vectorOfDoubles = 70 + case parentNamespaceTest = 72 + case vectorOfReferrables = 74 + case singleWeakReference = 76 + case vectorOfWeakReferences = 78 + case vectorOfStrongReferrables = 80 + case coOwningReference = 82 + case vectorOfCoOwningReferences = 84 + case nonOwningReference = 86 + case vectorOfNonOwningReferences = 88 + case anyUniqueType = 90 + case anyUnique = 92 + case anyAmbiguousType = 94 + case anyAmbiguous = 96 + case vectorOfEnums = 98 + case signedEnum = 100 + case testrequirednestedflatbuffer = 102 + case scalarKeySortedTables = 104 + case nativeInline = 106 + case longEnumNonEnumDefault = 108 + case longEnumNormalDefault = 110 + case nanDefault = 112 + case infDefault = 114 + case positiveInfDefault = 116 + case infinityDefault = 118 + case positiveInfinityDefault = 120 + case negativeInfDefault = 122 + case negativeInfinityDefault = 124 + case doubleInfDefault = 126 + var v: Int32 { Int32(self.rawValue) } + var p: VOffset { self.rawValue } } - public var pos: MyGame_Example_Vec3? { let o = _accessor.offset(VT.pos); return o == 0 ? nil : _accessor.readBuffer(of: MyGame_Example_Vec3.self, at: o) } - public var mutablePos: MyGame_Example_Vec3_Mutable? { let o = _accessor.offset(VT.pos); return o == 0 ? nil : MyGame_Example_Vec3_Mutable(_accessor.bb, o: o + _accessor.position) } - public var mana: Int16 { let o = _accessor.offset(VT.mana); return o == 0 ? 150 : _accessor.readBuffer(of: Int16.self, at: o) } - @discardableResult public func mutate(mana: Int16) -> Bool {let o = _accessor.offset(VT.mana); return _accessor.mutate(mana, index: o) } - public var hp: Int16 { let o = _accessor.offset(VT.hp); return o == 0 ? 100 : _accessor.readBuffer(of: Int16.self, at: o) } - @discardableResult public func mutate(hp: Int16) -> Bool {let o = _accessor.offset(VT.hp); return _accessor.mutate(hp, index: o) } - public var name: String! { let o = _accessor.offset(VT.name); return _accessor.string(at: o) } - public var nameSegmentArray: [UInt8]! { return _accessor.getVector(at: VT.name) } - public var inventory: FlatbufferVector { return _accessor.vector(at: VT.inventory, byteSize: 1) } - public func mutate(inventory: UInt8, at index: Int32) -> Bool { let o = _accessor.offset(VT.inventory); return _accessor.directMutate(inventory, index: _accessor.vector(at: o) + index * 1) } - public func withUnsafePointerToInventory(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VT.inventory, body: body) } - public var color: MyGame_Example_Color { let o = _accessor.offset(VT.color); return o == 0 ? .blue : MyGame_Example_Color(rawValue: _accessor.readBuffer(of: UInt8.self, at: o)) ?? .blue } - @discardableResult public func mutate(color: MyGame_Example_Color) -> Bool {let o = _accessor.offset(VT.color); return _accessor.mutate(color.rawValue, index: o) } - public var testType: MyGame_Example_Any_ { let o = _accessor.offset(VT.testType); return o == 0 ? .none_ : MyGame_Example_Any_(rawValue: _accessor.readBuffer(of: UInt8.self, at: o)) ?? .none_ } - public func test(type: T.Type) -> T? { let o = _accessor.offset(VT.test); return o == 0 ? nil : _accessor.union(o) } - public var test4: FlatbufferVector { return _accessor.vector(at: VT.test4, byteSize: 4) } - public var mutableTest4: FlatbufferVector { return _accessor.vector(at: VT.test4, byteSize: 4) } - public func withUnsafePointerToTest4(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VT.test4, body: body) } - public var testarrayofstring: FlatbufferVector { return _accessor.vector(at: VT.testarrayofstring, byteSize: 4) } + public var pos: MyGame_Example_Vec3? { let o = _accessor.offset(VTOFFSET.pos.v); return o == 0 ? nil : _accessor.readBuffer(of: MyGame_Example_Vec3.self, at: o) } + public var mutablePos: MyGame_Example_Vec3_Mutable? { let o = _accessor.offset(VTOFFSET.pos.v); return o == 0 ? nil : MyGame_Example_Vec3_Mutable(_accessor.bb, o: o + _accessor.position) } + 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 _accessor.string(at: o) } + public var nameSegmentArray: [UInt8]! { return _accessor.getVector(at: VTOFFSET.name.v) } + public var inventory: FlatbufferVector { return _accessor.vector(at: VTOFFSET.inventory.v, byteSize: 1) } + 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 func withUnsafePointerToInventory(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VTOFFSET.inventory.v, body: body) } + public var color: MyGame_Example_Color { let o = _accessor.offset(VTOFFSET.color.v); return o == 0 ? .blue : MyGame_Example_Color(rawValue: _accessor.readBuffer(of: UInt8.self, at: o)) ?? .blue } + @discardableResult public func mutate(color: MyGame_Example_Color) -> Bool {let o = _accessor.offset(VTOFFSET.color.v); return _accessor.mutate(color.rawValue, index: o) } + public var testType: MyGame_Example_Any_ { let o = _accessor.offset(VTOFFSET.testType.v); return o == 0 ? .none_ : MyGame_Example_Any_(rawValue: _accessor.readBuffer(of: UInt8.self, at: o)) ?? .none_ } + public func test(type: T.Type) -> T? { let o = _accessor.offset(VTOFFSET.test.v); return o == 0 ? nil : _accessor.union(o) } + public var test4: FlatbufferVector { return _accessor.vector(at: VTOFFSET.test4.v, byteSize: 4) } + public var mutableTest4: FlatbufferVector { return _accessor.vector(at: VTOFFSET.test4.v, byteSize: 4) } + public func withUnsafePointerToTest4(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VTOFFSET.test4.v, body: body) } + public var testarrayofstring: FlatbufferVector { return _accessor.vector(at: VTOFFSET.testarrayofstring.v, byteSize: 4) } /// an example documentation comment: this will end up in the generated code /// multiline too - public var testarrayoftables: FlatbufferVector { return _accessor.vector(at: VT.testarrayoftables, byteSize: 4) } - public func testarrayoftablesBy(key: String) -> MyGame_Example_Monster? { let o = _accessor.offset(VT.testarrayoftables); return o == 0 ? nil : MyGame_Example_Monster.lookupByKey(vector: _accessor.vector(at: o), key: key, fbb: _accessor.bb) } - public var enemy: MyGame_Example_Monster? { let o = _accessor.offset(VT.enemy); return o == 0 ? nil : MyGame_Example_Monster(_accessor.bb, o: _accessor.indirect(o + _accessor.position)) } - public var testnestedflatbuffer: FlatbufferVector { return _accessor.vector(at: VT.testnestedflatbuffer, byteSize: 1) } - public func mutate(testnestedflatbuffer: UInt8, at index: Int32) -> Bool { let o = _accessor.offset(VT.testnestedflatbuffer); return _accessor.directMutate(testnestedflatbuffer, index: _accessor.vector(at: o) + index * 1) } - public func withUnsafePointerToTestnestedflatbuffer(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VT.testnestedflatbuffer, body: body) } - public var testempty: MyGame_Example_Stat? { let o = _accessor.offset(VT.testempty); return o == 0 ? nil : MyGame_Example_Stat(_accessor.bb, o: _accessor.indirect(o + _accessor.position)) } - public var testbool: Bool { let o = _accessor.offset(VT.testbool); return o == 0 ? false : _accessor.readBuffer(of: Bool.self, at: o) } - @discardableResult public func mutate(testbool: Bool) -> Bool {let o = _accessor.offset(VT.testbool); return _accessor.mutate(testbool, index: o) } - public var testhashs32Fnv1: Int32 { let o = _accessor.offset(VT.testhashs32Fnv1); return o == 0 ? 0 : _accessor.readBuffer(of: Int32.self, at: o) } - @discardableResult public func mutate(testhashs32Fnv1: Int32) -> Bool {let o = _accessor.offset(VT.testhashs32Fnv1); return _accessor.mutate(testhashs32Fnv1, index: o) } - public var testhashu32Fnv1: UInt32 { let o = _accessor.offset(VT.testhashu32Fnv1); return o == 0 ? 0 : _accessor.readBuffer(of: UInt32.self, at: o) } - @discardableResult public func mutate(testhashu32Fnv1: UInt32) -> Bool {let o = _accessor.offset(VT.testhashu32Fnv1); return _accessor.mutate(testhashu32Fnv1, index: o) } - public var testhashs64Fnv1: Int64 { let o = _accessor.offset(VT.testhashs64Fnv1); return o == 0 ? 0 : _accessor.readBuffer(of: Int64.self, at: o) } - @discardableResult public func mutate(testhashs64Fnv1: Int64) -> Bool {let o = _accessor.offset(VT.testhashs64Fnv1); return _accessor.mutate(testhashs64Fnv1, index: o) } - public var testhashu64Fnv1: UInt64 { let o = _accessor.offset(VT.testhashu64Fnv1); return o == 0 ? 0 : _accessor.readBuffer(of: UInt64.self, at: o) } - @discardableResult public func mutate(testhashu64Fnv1: UInt64) -> Bool {let o = _accessor.offset(VT.testhashu64Fnv1); return _accessor.mutate(testhashu64Fnv1, index: o) } - public var testhashs32Fnv1a: Int32 { let o = _accessor.offset(VT.testhashs32Fnv1a); return o == 0 ? 0 : _accessor.readBuffer(of: Int32.self, at: o) } - @discardableResult public func mutate(testhashs32Fnv1a: Int32) -> Bool {let o = _accessor.offset(VT.testhashs32Fnv1a); return _accessor.mutate(testhashs32Fnv1a, index: o) } - public var testhashu32Fnv1a: UInt32 { let o = _accessor.offset(VT.testhashu32Fnv1a); return o == 0 ? 0 : _accessor.readBuffer(of: UInt32.self, at: o) } - @discardableResult public func mutate(testhashu32Fnv1a: UInt32) -> Bool {let o = _accessor.offset(VT.testhashu32Fnv1a); return _accessor.mutate(testhashu32Fnv1a, index: o) } - public var testhashs64Fnv1a: Int64 { let o = _accessor.offset(VT.testhashs64Fnv1a); return o == 0 ? 0 : _accessor.readBuffer(of: Int64.self, at: o) } - @discardableResult public func mutate(testhashs64Fnv1a: Int64) -> Bool {let o = _accessor.offset(VT.testhashs64Fnv1a); return _accessor.mutate(testhashs64Fnv1a, index: o) } - public var testhashu64Fnv1a: UInt64 { let o = _accessor.offset(VT.testhashu64Fnv1a); return o == 0 ? 0 : _accessor.readBuffer(of: UInt64.self, at: o) } - @discardableResult public func mutate(testhashu64Fnv1a: UInt64) -> Bool {let o = _accessor.offset(VT.testhashu64Fnv1a); return _accessor.mutate(testhashu64Fnv1a, index: o) } - public var testarrayofbools: FlatbufferVector { return _accessor.vector(at: VT.testarrayofbools, byteSize: 1) } - public func mutate(testarrayofbools: Bool, at index: Int32) -> Bool { let o = _accessor.offset(VT.testarrayofbools); return _accessor.directMutate(testarrayofbools, index: _accessor.vector(at: o) + index * 1) } - public func withUnsafePointerToTestarrayofbools(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VT.testarrayofbools, body: body) } - public var testf: Float32 { let o = _accessor.offset(VT.testf); return o == 0 ? 3.14159 : _accessor.readBuffer(of: Float32.self, at: o) } - @discardableResult public func mutate(testf: Float32) -> Bool {let o = _accessor.offset(VT.testf); return _accessor.mutate(testf, index: o) } - public var testf2: Float32 { let o = _accessor.offset(VT.testf2); return o == 0 ? 3.0 : _accessor.readBuffer(of: Float32.self, at: o) } - @discardableResult public func mutate(testf2: Float32) -> Bool {let o = _accessor.offset(VT.testf2); return _accessor.mutate(testf2, index: o) } - public var testf3: Float32 { let o = _accessor.offset(VT.testf3); return o == 0 ? 0.0 : _accessor.readBuffer(of: Float32.self, at: o) } - @discardableResult public func mutate(testf3: Float32) -> Bool {let o = _accessor.offset(VT.testf3); return _accessor.mutate(testf3, index: o) } - public var testarrayofstring2: FlatbufferVector { return _accessor.vector(at: VT.testarrayofstring2, byteSize: 4) } - public var testarrayofsortedstruct: FlatbufferVector { return _accessor.vector(at: VT.testarrayofsortedstruct, byteSize: 8) } - public var mutableTestarrayofsortedstruct: FlatbufferVector { return _accessor.vector(at: VT.testarrayofsortedstruct, byteSize: 8) } - public func withUnsafePointerToTestarrayofsortedstruct(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VT.testarrayofsortedstruct, body: body) } - public var flex: FlatbufferVector { return _accessor.vector(at: VT.flex, byteSize: 1) } - public func mutate(flex: UInt8, at index: Int32) -> Bool { let o = _accessor.offset(VT.flex); return _accessor.directMutate(flex, index: _accessor.vector(at: o) + index * 1) } - public func withUnsafePointerToFlex(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VT.flex, body: body) } - public var test5: FlatbufferVector { return _accessor.vector(at: VT.test5, byteSize: 4) } - public var mutableTest5: FlatbufferVector { return _accessor.vector(at: VT.test5, byteSize: 4) } - public func withUnsafePointerToTest5(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VT.test5, body: body) } - public var vectorOfLongs: FlatbufferVector { return _accessor.vector(at: VT.vectorOfLongs, byteSize: 8) } - public func mutate(vectorOfLongs: Int64, at index: Int32) -> Bool { let o = _accessor.offset(VT.vectorOfLongs); return _accessor.directMutate(vectorOfLongs, index: _accessor.vector(at: o) + index * 8) } - public func withUnsafePointerToVectorOfLongs(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VT.vectorOfLongs, body: body) } - public var vectorOfDoubles: FlatbufferVector { return _accessor.vector(at: VT.vectorOfDoubles, byteSize: 8) } - public func mutate(vectorOfDoubles: Double, at index: Int32) -> Bool { let o = _accessor.offset(VT.vectorOfDoubles); return _accessor.directMutate(vectorOfDoubles, index: _accessor.vector(at: o) + index * 8) } - public func withUnsafePointerToVectorOfDoubles(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VT.vectorOfDoubles, body: body) } - public var parentNamespaceTest: MyGame_InParentNamespace? { let o = _accessor.offset(VT.parentNamespaceTest); return o == 0 ? nil : MyGame_InParentNamespace(_accessor.bb, o: _accessor.indirect(o + _accessor.position)) } - public var vectorOfReferrables: FlatbufferVector { return _accessor.vector(at: VT.vectorOfReferrables, byteSize: 4) } - public func vectorOfReferrablesBy(key: UInt64) -> MyGame_Example_Referrable? { let o = _accessor.offset(VT.vectorOfReferrables); return o == 0 ? nil : MyGame_Example_Referrable.lookupByKey(vector: _accessor.vector(at: o), key: key, fbb: _accessor.bb) } - public var singleWeakReference: UInt64 { let o = _accessor.offset(VT.singleWeakReference); return o == 0 ? 0 : _accessor.readBuffer(of: UInt64.self, at: o) } - @discardableResult public func mutate(singleWeakReference: UInt64) -> Bool {let o = _accessor.offset(VT.singleWeakReference); return _accessor.mutate(singleWeakReference, index: o) } - public var vectorOfWeakReferences: FlatbufferVector { return _accessor.vector(at: VT.vectorOfWeakReferences, byteSize: 8) } - public func mutate(vectorOfWeakReferences: UInt64, at index: Int32) -> Bool { let o = _accessor.offset(VT.vectorOfWeakReferences); return _accessor.directMutate(vectorOfWeakReferences, index: _accessor.vector(at: o) + index * 8) } - public func withUnsafePointerToVectorOfWeakReferences(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VT.vectorOfWeakReferences, body: body) } - public var vectorOfStrongReferrables: FlatbufferVector { return _accessor.vector(at: VT.vectorOfStrongReferrables, byteSize: 4) } - public func vectorOfStrongReferrablesBy(key: UInt64) -> MyGame_Example_Referrable? { let o = _accessor.offset(VT.vectorOfStrongReferrables); return o == 0 ? nil : MyGame_Example_Referrable.lookupByKey(vector: _accessor.vector(at: o), key: key, fbb: _accessor.bb) } - public var coOwningReference: UInt64 { let o = _accessor.offset(VT.coOwningReference); return o == 0 ? 0 : _accessor.readBuffer(of: UInt64.self, at: o) } - @discardableResult public func mutate(coOwningReference: UInt64) -> Bool {let o = _accessor.offset(VT.coOwningReference); return _accessor.mutate(coOwningReference, index: o) } - public var vectorOfCoOwningReferences: FlatbufferVector { return _accessor.vector(at: VT.vectorOfCoOwningReferences, byteSize: 8) } - public func mutate(vectorOfCoOwningReferences: UInt64, at index: Int32) -> Bool { let o = _accessor.offset(VT.vectorOfCoOwningReferences); return _accessor.directMutate(vectorOfCoOwningReferences, index: _accessor.vector(at: o) + index * 8) } - public func withUnsafePointerToVectorOfCoOwningReferences(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VT.vectorOfCoOwningReferences, body: body) } - public var nonOwningReference: UInt64 { let o = _accessor.offset(VT.nonOwningReference); return o == 0 ? 0 : _accessor.readBuffer(of: UInt64.self, at: o) } - @discardableResult public func mutate(nonOwningReference: UInt64) -> Bool {let o = _accessor.offset(VT.nonOwningReference); return _accessor.mutate(nonOwningReference, index: o) } - public var vectorOfNonOwningReferences: FlatbufferVector { return _accessor.vector(at: VT.vectorOfNonOwningReferences, byteSize: 8) } - public func mutate(vectorOfNonOwningReferences: UInt64, at index: Int32) -> Bool { let o = _accessor.offset(VT.vectorOfNonOwningReferences); return _accessor.directMutate(vectorOfNonOwningReferences, index: _accessor.vector(at: o) + index * 8) } - public func withUnsafePointerToVectorOfNonOwningReferences(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VT.vectorOfNonOwningReferences, body: body) } - public var anyUniqueType: MyGame_Example_AnyUniqueAliases { let o = _accessor.offset(VT.anyUniqueType); return o == 0 ? .none_ : MyGame_Example_AnyUniqueAliases(rawValue: _accessor.readBuffer(of: UInt8.self, at: o)) ?? .none_ } - public func anyUnique(type: T.Type) -> T? { let o = _accessor.offset(VT.anyUnique); return o == 0 ? nil : _accessor.union(o) } - public var anyAmbiguousType: MyGame_Example_AnyAmbiguousAliases { let o = _accessor.offset(VT.anyAmbiguousType); return o == 0 ? .none_ : MyGame_Example_AnyAmbiguousAliases(rawValue: _accessor.readBuffer(of: UInt8.self, at: o)) ?? .none_ } - public func anyAmbiguous(type: T.Type) -> T? { let o = _accessor.offset(VT.anyAmbiguous); return o == 0 ? nil : _accessor.union(o) } - public var vectorOfEnums: FlatbufferVector { return _accessor.vector(at: VT.vectorOfEnums, byteSize: 1) } - public var signedEnum: MyGame_Example_Race { let o = _accessor.offset(VT.signedEnum); return o == 0 ? .none_ : MyGame_Example_Race(rawValue: _accessor.readBuffer(of: Int8.self, at: o)) ?? .none_ } - @discardableResult public func mutate(signedEnum: MyGame_Example_Race) -> Bool {let o = _accessor.offset(VT.signedEnum); return _accessor.mutate(signedEnum.rawValue, index: o) } - public var testrequirednestedflatbuffer: FlatbufferVector { return _accessor.vector(at: VT.testrequirednestedflatbuffer, byteSize: 1) } - public func mutate(testrequirednestedflatbuffer: UInt8, at index: Int32) -> Bool { let o = _accessor.offset(VT.testrequirednestedflatbuffer); return _accessor.directMutate(testrequirednestedflatbuffer, index: _accessor.vector(at: o) + index * 1) } - public func withUnsafePointerToTestrequirednestedflatbuffer(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VT.testrequirednestedflatbuffer, body: body) } - public var scalarKeySortedTables: FlatbufferVector { return _accessor.vector(at: VT.scalarKeySortedTables, byteSize: 4) } - public func scalarKeySortedTablesBy(key: UInt16) -> MyGame_Example_Stat? { let o = _accessor.offset(VT.scalarKeySortedTables); return o == 0 ? nil : MyGame_Example_Stat.lookupByKey(vector: _accessor.vector(at: o), key: key, fbb: _accessor.bb) } - public var nativeInline: MyGame_Example_Test? { let o = _accessor.offset(VT.nativeInline); return o == 0 ? nil : _accessor.readBuffer(of: MyGame_Example_Test.self, at: o) } - public var mutableNativeInline: MyGame_Example_Test_Mutable? { let o = _accessor.offset(VT.nativeInline); return o == 0 ? nil : MyGame_Example_Test_Mutable(_accessor.bb, o: o + _accessor.position) } - public var longEnumNonEnumDefault: MyGame_Example_LongEnum { let o = _accessor.offset(VT.longEnumNonEnumDefault); return o == 0 ? .longone : MyGame_Example_LongEnum(rawValue: _accessor.readBuffer(of: UInt64.self, at: o)) ?? .longone } - @discardableResult public func mutate(longEnumNonEnumDefault: MyGame_Example_LongEnum) -> Bool {let o = _accessor.offset(VT.longEnumNonEnumDefault); return _accessor.mutate(longEnumNonEnumDefault.rawValue, index: o) } - public var longEnumNormalDefault: MyGame_Example_LongEnum { let o = _accessor.offset(VT.longEnumNormalDefault); return o == 0 ? .longone : MyGame_Example_LongEnum(rawValue: _accessor.readBuffer(of: UInt64.self, at: o)) ?? .longone } - @discardableResult public func mutate(longEnumNormalDefault: MyGame_Example_LongEnum) -> Bool {let o = _accessor.offset(VT.longEnumNormalDefault); return _accessor.mutate(longEnumNormalDefault.rawValue, index: o) } - public var nanDefault: Float32 { let o = _accessor.offset(VT.nanDefault); return o == 0 ? .nan : _accessor.readBuffer(of: Float32.self, at: o) } - @discardableResult public func mutate(nanDefault: Float32) -> Bool {let o = _accessor.offset(VT.nanDefault); return _accessor.mutate(nanDefault, index: o) } - public var infDefault: Float32 { let o = _accessor.offset(VT.infDefault); return o == 0 ? .infinity : _accessor.readBuffer(of: Float32.self, at: o) } - @discardableResult public func mutate(infDefault: Float32) -> Bool {let o = _accessor.offset(VT.infDefault); return _accessor.mutate(infDefault, index: o) } - public var positiveInfDefault: Float32 { let o = _accessor.offset(VT.positiveInfDefault); return o == 0 ? .infinity : _accessor.readBuffer(of: Float32.self, at: o) } - @discardableResult public func mutate(positiveInfDefault: Float32) -> Bool {let o = _accessor.offset(VT.positiveInfDefault); return _accessor.mutate(positiveInfDefault, index: o) } - public var infinityDefault: Float32 { let o = _accessor.offset(VT.infinityDefault); return o == 0 ? .infinity : _accessor.readBuffer(of: Float32.self, at: o) } - @discardableResult public func mutate(infinityDefault: Float32) -> Bool {let o = _accessor.offset(VT.infinityDefault); return _accessor.mutate(infinityDefault, index: o) } - public var positiveInfinityDefault: Float32 { let o = _accessor.offset(VT.positiveInfinityDefault); return o == 0 ? .infinity : _accessor.readBuffer(of: Float32.self, at: o) } - @discardableResult public func mutate(positiveInfinityDefault: Float32) -> Bool {let o = _accessor.offset(VT.positiveInfinityDefault); return _accessor.mutate(positiveInfinityDefault, index: o) } - public var negativeInfDefault: Float32 { let o = _accessor.offset(VT.negativeInfDefault); return o == 0 ? -.infinity : _accessor.readBuffer(of: Float32.self, at: o) } - @discardableResult public func mutate(negativeInfDefault: Float32) -> Bool {let o = _accessor.offset(VT.negativeInfDefault); return _accessor.mutate(negativeInfDefault, index: o) } - public var negativeInfinityDefault: Float32 { let o = _accessor.offset(VT.negativeInfinityDefault); return o == 0 ? -.infinity : _accessor.readBuffer(of: Float32.self, at: o) } - @discardableResult public func mutate(negativeInfinityDefault: Float32) -> Bool {let o = _accessor.offset(VT.negativeInfinityDefault); return _accessor.mutate(negativeInfinityDefault, index: o) } - public var doubleInfDefault: Double { let o = _accessor.offset(VT.doubleInfDefault); return o == 0 ? .infinity : _accessor.readBuffer(of: Double.self, at: o) } - @discardableResult public func mutate(doubleInfDefault: Double) -> Bool {let o = _accessor.offset(VT.doubleInfDefault); return _accessor.mutate(doubleInfDefault, index: o) } + public var testarrayoftables: FlatbufferVector { return _accessor.vector(at: VTOFFSET.testarrayoftables.v, byteSize: 4) } + public func testarrayoftablesBy(key: String) -> MyGame_Example_Monster? { let o = _accessor.offset(VTOFFSET.testarrayoftables.v); return o == 0 ? nil : MyGame_Example_Monster.lookupByKey(vector: _accessor.vector(at: o), key: key, fbb: _accessor.bb) } + public var enemy: MyGame_Example_Monster? { let o = _accessor.offset(VTOFFSET.enemy.v); return o == 0 ? nil : MyGame_Example_Monster(_accessor.bb, o: _accessor.indirect(o + _accessor.position)) } + public var testnestedflatbuffer: FlatbufferVector { return _accessor.vector(at: VTOFFSET.testnestedflatbuffer.v, byteSize: 1) } + public func mutate(testnestedflatbuffer: UInt8, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.testnestedflatbuffer.v); return _accessor.directMutate(testnestedflatbuffer, index: _accessor.vector(at: o) + index * 1) } + public func withUnsafePointerToTestnestedflatbuffer(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VTOFFSET.testnestedflatbuffer.v, body: body) } + public var testempty: MyGame_Example_Stat? { let o = _accessor.offset(VTOFFSET.testempty.v); return o == 0 ? nil : MyGame_Example_Stat(_accessor.bb, o: _accessor.indirect(o + _accessor.position)) } + public var testbool: Bool { let o = _accessor.offset(VTOFFSET.testbool.v); return o == 0 ? false : _accessor.readBuffer(of: Bool.self, at: o) } + @discardableResult public func mutate(testbool: Bool) -> Bool {let o = _accessor.offset(VTOFFSET.testbool.v); return _accessor.mutate(testbool, index: o) } + public var testhashs32Fnv1: Int32 { let o = _accessor.offset(VTOFFSET.testhashs32Fnv1.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int32.self, at: o) } + @discardableResult public func mutate(testhashs32Fnv1: Int32) -> Bool {let o = _accessor.offset(VTOFFSET.testhashs32Fnv1.v); return _accessor.mutate(testhashs32Fnv1, index: o) } + public var testhashu32Fnv1: UInt32 { let o = _accessor.offset(VTOFFSET.testhashu32Fnv1.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt32.self, at: o) } + @discardableResult public func mutate(testhashu32Fnv1: UInt32) -> Bool {let o = _accessor.offset(VTOFFSET.testhashu32Fnv1.v); return _accessor.mutate(testhashu32Fnv1, index: o) } + public var testhashs64Fnv1: Int64 { let o = _accessor.offset(VTOFFSET.testhashs64Fnv1.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int64.self, at: o) } + @discardableResult public func mutate(testhashs64Fnv1: Int64) -> Bool {let o = _accessor.offset(VTOFFSET.testhashs64Fnv1.v); return _accessor.mutate(testhashs64Fnv1, index: o) } + public var testhashu64Fnv1: UInt64 { let o = _accessor.offset(VTOFFSET.testhashu64Fnv1.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt64.self, at: o) } + @discardableResult public func mutate(testhashu64Fnv1: UInt64) -> Bool {let o = _accessor.offset(VTOFFSET.testhashu64Fnv1.v); return _accessor.mutate(testhashu64Fnv1, index: o) } + public var testhashs32Fnv1a: Int32 { let o = _accessor.offset(VTOFFSET.testhashs32Fnv1a.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int32.self, at: o) } + @discardableResult public func mutate(testhashs32Fnv1a: Int32) -> Bool {let o = _accessor.offset(VTOFFSET.testhashs32Fnv1a.v); return _accessor.mutate(testhashs32Fnv1a, index: o) } + public var testhashu32Fnv1a: UInt32 { let o = _accessor.offset(VTOFFSET.testhashu32Fnv1a.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt32.self, at: o) } + @discardableResult public func mutate(testhashu32Fnv1a: UInt32) -> Bool {let o = _accessor.offset(VTOFFSET.testhashu32Fnv1a.v); return _accessor.mutate(testhashu32Fnv1a, index: o) } + public var testhashs64Fnv1a: Int64 { let o = _accessor.offset(VTOFFSET.testhashs64Fnv1a.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int64.self, at: o) } + @discardableResult public func mutate(testhashs64Fnv1a: Int64) -> Bool {let o = _accessor.offset(VTOFFSET.testhashs64Fnv1a.v); return _accessor.mutate(testhashs64Fnv1a, index: o) } + public var testhashu64Fnv1a: UInt64 { let o = _accessor.offset(VTOFFSET.testhashu64Fnv1a.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt64.self, at: o) } + @discardableResult public func mutate(testhashu64Fnv1a: UInt64) -> Bool {let o = _accessor.offset(VTOFFSET.testhashu64Fnv1a.v); return _accessor.mutate(testhashu64Fnv1a, index: o) } + public var testarrayofbools: FlatbufferVector { return _accessor.vector(at: VTOFFSET.testarrayofbools.v, byteSize: 1) } + public func mutate(testarrayofbools: Bool, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.testarrayofbools.v); return _accessor.directMutate(testarrayofbools, index: _accessor.vector(at: o) + index * 1) } + public func withUnsafePointerToTestarrayofbools(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VTOFFSET.testarrayofbools.v, body: body) } + public var testf: Float32 { let o = _accessor.offset(VTOFFSET.testf.v); return o == 0 ? 3.14159 : _accessor.readBuffer(of: Float32.self, at: o) } + @discardableResult public func mutate(testf: Float32) -> Bool {let o = _accessor.offset(VTOFFSET.testf.v); return _accessor.mutate(testf, index: o) } + public var testf2: Float32 { let o = _accessor.offset(VTOFFSET.testf2.v); return o == 0 ? 3.0 : _accessor.readBuffer(of: Float32.self, at: o) } + @discardableResult public func mutate(testf2: Float32) -> Bool {let o = _accessor.offset(VTOFFSET.testf2.v); return _accessor.mutate(testf2, index: o) } + public var testf3: Float32 { let o = _accessor.offset(VTOFFSET.testf3.v); return o == 0 ? 0.0 : _accessor.readBuffer(of: Float32.self, at: o) } + @discardableResult public func mutate(testf3: Float32) -> Bool {let o = _accessor.offset(VTOFFSET.testf3.v); return _accessor.mutate(testf3, index: o) } + public var testarrayofstring2: FlatbufferVector { return _accessor.vector(at: VTOFFSET.testarrayofstring2.v, byteSize: 4) } + public var testarrayofsortedstruct: FlatbufferVector { return _accessor.vector(at: VTOFFSET.testarrayofsortedstruct.v, byteSize: 8) } + public var mutableTestarrayofsortedstruct: FlatbufferVector { return _accessor.vector(at: VTOFFSET.testarrayofsortedstruct.v, byteSize: 8) } + public func withUnsafePointerToTestarrayofsortedstruct(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VTOFFSET.testarrayofsortedstruct.v, body: body) } + public var flex: FlatbufferVector { return _accessor.vector(at: VTOFFSET.flex.v, byteSize: 1) } + public func mutate(flex: UInt8, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.flex.v); return _accessor.directMutate(flex, index: _accessor.vector(at: o) + index * 1) } + public func withUnsafePointerToFlex(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VTOFFSET.flex.v, body: body) } + public var test5: FlatbufferVector { return _accessor.vector(at: VTOFFSET.test5.v, byteSize: 4) } + public var mutableTest5: FlatbufferVector { return _accessor.vector(at: VTOFFSET.test5.v, byteSize: 4) } + public func withUnsafePointerToTest5(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VTOFFSET.test5.v, body: body) } + public var vectorOfLongs: FlatbufferVector { return _accessor.vector(at: VTOFFSET.vectorOfLongs.v, byteSize: 8) } + public func mutate(vectorOfLongs: Int64, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.vectorOfLongs.v); return _accessor.directMutate(vectorOfLongs, index: _accessor.vector(at: o) + index * 8) } + public func withUnsafePointerToVectorOfLongs(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VTOFFSET.vectorOfLongs.v, body: body) } + public var vectorOfDoubles: FlatbufferVector { return _accessor.vector(at: VTOFFSET.vectorOfDoubles.v, byteSize: 8) } + public func mutate(vectorOfDoubles: Double, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.vectorOfDoubles.v); return _accessor.directMutate(vectorOfDoubles, index: _accessor.vector(at: o) + index * 8) } + public func withUnsafePointerToVectorOfDoubles(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VTOFFSET.vectorOfDoubles.v, body: body) } + public var parentNamespaceTest: MyGame_InParentNamespace? { let o = _accessor.offset(VTOFFSET.parentNamespaceTest.v); return o == 0 ? nil : MyGame_InParentNamespace(_accessor.bb, o: _accessor.indirect(o + _accessor.position)) } + public var vectorOfReferrables: FlatbufferVector { return _accessor.vector(at: VTOFFSET.vectorOfReferrables.v, byteSize: 4) } + public func vectorOfReferrablesBy(key: UInt64) -> MyGame_Example_Referrable? { let o = _accessor.offset(VTOFFSET.vectorOfReferrables.v); return o == 0 ? nil : MyGame_Example_Referrable.lookupByKey(vector: _accessor.vector(at: o), key: key, fbb: _accessor.bb) } + public var singleWeakReference: UInt64 { let o = _accessor.offset(VTOFFSET.singleWeakReference.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt64.self, at: o) } + @discardableResult public func mutate(singleWeakReference: UInt64) -> Bool {let o = _accessor.offset(VTOFFSET.singleWeakReference.v); return _accessor.mutate(singleWeakReference, index: o) } + public var vectorOfWeakReferences: FlatbufferVector { return _accessor.vector(at: VTOFFSET.vectorOfWeakReferences.v, byteSize: 8) } + public func mutate(vectorOfWeakReferences: UInt64, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.vectorOfWeakReferences.v); return _accessor.directMutate(vectorOfWeakReferences, index: _accessor.vector(at: o) + index * 8) } + public func withUnsafePointerToVectorOfWeakReferences(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VTOFFSET.vectorOfWeakReferences.v, body: body) } + public var vectorOfStrongReferrables: FlatbufferVector { return _accessor.vector(at: VTOFFSET.vectorOfStrongReferrables.v, byteSize: 4) } + public func vectorOfStrongReferrablesBy(key: UInt64) -> MyGame_Example_Referrable? { let o = _accessor.offset(VTOFFSET.vectorOfStrongReferrables.v); return o == 0 ? nil : MyGame_Example_Referrable.lookupByKey(vector: _accessor.vector(at: o), key: key, fbb: _accessor.bb) } + public var coOwningReference: UInt64 { let o = _accessor.offset(VTOFFSET.coOwningReference.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt64.self, at: o) } + @discardableResult public func mutate(coOwningReference: UInt64) -> Bool {let o = _accessor.offset(VTOFFSET.coOwningReference.v); return _accessor.mutate(coOwningReference, index: o) } + public var vectorOfCoOwningReferences: FlatbufferVector { return _accessor.vector(at: VTOFFSET.vectorOfCoOwningReferences.v, byteSize: 8) } + public func mutate(vectorOfCoOwningReferences: UInt64, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.vectorOfCoOwningReferences.v); return _accessor.directMutate(vectorOfCoOwningReferences, index: _accessor.vector(at: o) + index * 8) } + public func withUnsafePointerToVectorOfCoOwningReferences(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VTOFFSET.vectorOfCoOwningReferences.v, body: body) } + public var nonOwningReference: UInt64 { let o = _accessor.offset(VTOFFSET.nonOwningReference.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt64.self, at: o) } + @discardableResult public func mutate(nonOwningReference: UInt64) -> Bool {let o = _accessor.offset(VTOFFSET.nonOwningReference.v); return _accessor.mutate(nonOwningReference, index: o) } + public var vectorOfNonOwningReferences: FlatbufferVector { return _accessor.vector(at: VTOFFSET.vectorOfNonOwningReferences.v, byteSize: 8) } + public func mutate(vectorOfNonOwningReferences: UInt64, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.vectorOfNonOwningReferences.v); return _accessor.directMutate(vectorOfNonOwningReferences, index: _accessor.vector(at: o) + index * 8) } + public func withUnsafePointerToVectorOfNonOwningReferences(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VTOFFSET.vectorOfNonOwningReferences.v, body: body) } + public var anyUniqueType: MyGame_Example_AnyUniqueAliases { let o = _accessor.offset(VTOFFSET.anyUniqueType.v); return o == 0 ? .none_ : MyGame_Example_AnyUniqueAliases(rawValue: _accessor.readBuffer(of: UInt8.self, at: o)) ?? .none_ } + public func anyUnique(type: T.Type) -> T? { let o = _accessor.offset(VTOFFSET.anyUnique.v); return o == 0 ? nil : _accessor.union(o) } + public var anyAmbiguousType: MyGame_Example_AnyAmbiguousAliases { let o = _accessor.offset(VTOFFSET.anyAmbiguousType.v); return o == 0 ? .none_ : MyGame_Example_AnyAmbiguousAliases(rawValue: _accessor.readBuffer(of: UInt8.self, at: o)) ?? .none_ } + public func anyAmbiguous(type: T.Type) -> T? { let o = _accessor.offset(VTOFFSET.anyAmbiguous.v); return o == 0 ? nil : _accessor.union(o) } + public var vectorOfEnums: FlatbufferVector { return _accessor.vector(at: VTOFFSET.vectorOfEnums.v, byteSize: 1) } + public var signedEnum: MyGame_Example_Race { let o = _accessor.offset(VTOFFSET.signedEnum.v); return o == 0 ? .none_ : MyGame_Example_Race(rawValue: _accessor.readBuffer(of: Int8.self, at: o)) ?? .none_ } + @discardableResult public func mutate(signedEnum: MyGame_Example_Race) -> Bool {let o = _accessor.offset(VTOFFSET.signedEnum.v); return _accessor.mutate(signedEnum.rawValue, index: o) } + public var testrequirednestedflatbuffer: FlatbufferVector { return _accessor.vector(at: VTOFFSET.testrequirednestedflatbuffer.v, byteSize: 1) } + public func mutate(testrequirednestedflatbuffer: UInt8, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.testrequirednestedflatbuffer.v); return _accessor.directMutate(testrequirednestedflatbuffer, index: _accessor.vector(at: o) + index * 1) } + public func withUnsafePointerToTestrequirednestedflatbuffer(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VTOFFSET.testrequirednestedflatbuffer.v, body: body) } + public var scalarKeySortedTables: FlatbufferVector { return _accessor.vector(at: VTOFFSET.scalarKeySortedTables.v, byteSize: 4) } + public func scalarKeySortedTablesBy(key: UInt16) -> MyGame_Example_Stat? { let o = _accessor.offset(VTOFFSET.scalarKeySortedTables.v); return o == 0 ? nil : MyGame_Example_Stat.lookupByKey(vector: _accessor.vector(at: o), key: key, fbb: _accessor.bb) } + public var nativeInline: MyGame_Example_Test? { let o = _accessor.offset(VTOFFSET.nativeInline.v); return o == 0 ? nil : _accessor.readBuffer(of: MyGame_Example_Test.self, at: o) } + public var mutableNativeInline: MyGame_Example_Test_Mutable? { let o = _accessor.offset(VTOFFSET.nativeInline.v); return o == 0 ? nil : MyGame_Example_Test_Mutable(_accessor.bb, o: o + _accessor.position) } + public var longEnumNonEnumDefault: MyGame_Example_LongEnum { let o = _accessor.offset(VTOFFSET.longEnumNonEnumDefault.v); return o == 0 ? .longone : MyGame_Example_LongEnum(rawValue: _accessor.readBuffer(of: UInt64.self, at: o)) ?? .longone } + @discardableResult public func mutate(longEnumNonEnumDefault: MyGame_Example_LongEnum) -> Bool {let o = _accessor.offset(VTOFFSET.longEnumNonEnumDefault.v); return _accessor.mutate(longEnumNonEnumDefault.rawValue, index: o) } + public var longEnumNormalDefault: MyGame_Example_LongEnum { let o = _accessor.offset(VTOFFSET.longEnumNormalDefault.v); return o == 0 ? .longone : MyGame_Example_LongEnum(rawValue: _accessor.readBuffer(of: UInt64.self, at: o)) ?? .longone } + @discardableResult public func mutate(longEnumNormalDefault: MyGame_Example_LongEnum) -> Bool {let o = _accessor.offset(VTOFFSET.longEnumNormalDefault.v); return _accessor.mutate(longEnumNormalDefault.rawValue, index: o) } + public var nanDefault: Float32 { let o = _accessor.offset(VTOFFSET.nanDefault.v); return o == 0 ? .nan : _accessor.readBuffer(of: Float32.self, at: o) } + @discardableResult public func mutate(nanDefault: Float32) -> Bool {let o = _accessor.offset(VTOFFSET.nanDefault.v); return _accessor.mutate(nanDefault, index: o) } + public var infDefault: Float32 { let o = _accessor.offset(VTOFFSET.infDefault.v); return o == 0 ? .infinity : _accessor.readBuffer(of: Float32.self, at: o) } + @discardableResult public func mutate(infDefault: Float32) -> Bool {let o = _accessor.offset(VTOFFSET.infDefault.v); return _accessor.mutate(infDefault, index: o) } + public var positiveInfDefault: Float32 { let o = _accessor.offset(VTOFFSET.positiveInfDefault.v); return o == 0 ? .infinity : _accessor.readBuffer(of: Float32.self, at: o) } + @discardableResult public func mutate(positiveInfDefault: Float32) -> Bool {let o = _accessor.offset(VTOFFSET.positiveInfDefault.v); return _accessor.mutate(positiveInfDefault, index: o) } + public var infinityDefault: Float32 { let o = _accessor.offset(VTOFFSET.infinityDefault.v); return o == 0 ? .infinity : _accessor.readBuffer(of: Float32.self, at: o) } + @discardableResult public func mutate(infinityDefault: Float32) -> Bool {let o = _accessor.offset(VTOFFSET.infinityDefault.v); return _accessor.mutate(infinityDefault, index: o) } + public var positiveInfinityDefault: Float32 { let o = _accessor.offset(VTOFFSET.positiveInfinityDefault.v); return o == 0 ? .infinity : _accessor.readBuffer(of: Float32.self, at: o) } + @discardableResult public func mutate(positiveInfinityDefault: Float32) -> Bool {let o = _accessor.offset(VTOFFSET.positiveInfinityDefault.v); return _accessor.mutate(positiveInfinityDefault, index: o) } + public var negativeInfDefault: Float32 { let o = _accessor.offset(VTOFFSET.negativeInfDefault.v); return o == 0 ? -.infinity : _accessor.readBuffer(of: Float32.self, at: o) } + @discardableResult public func mutate(negativeInfDefault: Float32) -> Bool {let o = _accessor.offset(VTOFFSET.negativeInfDefault.v); return _accessor.mutate(negativeInfDefault, index: o) } + public var negativeInfinityDefault: Float32 { let o = _accessor.offset(VTOFFSET.negativeInfinityDefault.v); return o == 0 ? -.infinity : _accessor.readBuffer(of: Float32.self, at: o) } + @discardableResult public func mutate(negativeInfinityDefault: Float32) -> Bool {let o = _accessor.offset(VTOFFSET.negativeInfinityDefault.v); return _accessor.mutate(negativeInfinityDefault, index: o) } + public var doubleInfDefault: Double { let o = _accessor.offset(VTOFFSET.doubleInfDefault.v); return o == 0 ? .infinity : _accessor.readBuffer(of: Double.self, at: o) } + @discardableResult public func mutate(doubleInfDefault: Double) -> Bool {let o = _accessor.offset(VTOFFSET.doubleInfDefault.v); return _accessor.mutate(doubleInfDefault, index: o) } public static func startMonster(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 62) } - public static func add(pos: MyGame_Example_Vec3?, _ fbb: inout FlatBufferBuilder) { guard let pos = pos else { return }; fbb.create(struct: pos, position: VT.pos) } - public static func add(mana: Int16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: mana, def: 150, at: VT.mana) } - public static func add(hp: Int16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: hp, def: 100, at: VT.hp) } - public static func add(name: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: name, at: VT.name) } - public static func addVectorOf(inventory: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: inventory, at: VT.inventory) } - public static func add(color: MyGame_Example_Color, _ fbb: inout FlatBufferBuilder) { fbb.add(element: color.rawValue, def: 8, at: VT.color) } - public static func add(testType: MyGame_Example_Any_, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testType.rawValue, def: 0, at: VT.testType) } - public static func add(test: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: test, at: VT.test) } - public static func addVectorOf(test4: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: test4, at: VT.test4) } + public static func add(pos: MyGame_Example_Vec3?, _ fbb: inout FlatBufferBuilder) { guard let pos = pos else { return }; fbb.create(struct: pos, position: VTOFFSET.pos.p) } + public static func add(mana: Int16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: mana, def: 150, at: VTOFFSET.mana.p) } + public static func add(hp: Int16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: hp, def: 100, at: VTOFFSET.hp.p) } + public static func add(name: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: name, at: VTOFFSET.name.p) } + public static func addVectorOf(inventory: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: inventory, at: VTOFFSET.inventory.p) } + public static func add(color: MyGame_Example_Color, _ fbb: inout FlatBufferBuilder) { fbb.add(element: color.rawValue, def: 8, at: VTOFFSET.color.p) } + public static func add(testType: MyGame_Example_Any_, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testType.rawValue, def: 0, at: VTOFFSET.testType.p) } + public static func add(test: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: test, at: VTOFFSET.test.p) } + public static func addVectorOf(test4: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: test4, at: VTOFFSET.test4.p) } public static func startVectorOfTest4(_ size: Int, in builder: inout FlatBufferBuilder) { builder.startVector(size * MemoryLayout.size, elementSize: MemoryLayout.alignment) } - public static func addVectorOf(testarrayofstring: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testarrayofstring, at: VT.testarrayofstring) } - public static func addVectorOf(testarrayoftables: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testarrayoftables, at: VT.testarrayoftables) } - public static func add(enemy: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: enemy, at: VT.enemy) } - public static func addVectorOf(testnestedflatbuffer: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testnestedflatbuffer, at: VT.testnestedflatbuffer) } - public static func add(testempty: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testempty, at: VT.testempty) } + public static func addVectorOf(testarrayofstring: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testarrayofstring, at: VTOFFSET.testarrayofstring.p) } + public static func addVectorOf(testarrayoftables: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testarrayoftables, at: VTOFFSET.testarrayoftables.p) } + public static func add(enemy: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: enemy, at: VTOFFSET.enemy.p) } + public static func addVectorOf(testnestedflatbuffer: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testnestedflatbuffer, at: VTOFFSET.testnestedflatbuffer.p) } + public static func add(testempty: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testempty, at: VTOFFSET.testempty.p) } public static func add(testbool: Bool, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testbool, def: false, - at: VT.testbool) } - public static func add(testhashs32Fnv1: Int32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashs32Fnv1, def: 0, at: VT.testhashs32Fnv1) } - public static func add(testhashu32Fnv1: UInt32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashu32Fnv1, def: 0, at: VT.testhashu32Fnv1) } - public static func add(testhashs64Fnv1: Int64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashs64Fnv1, def: 0, at: VT.testhashs64Fnv1) } - public static func add(testhashu64Fnv1: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashu64Fnv1, def: 0, at: VT.testhashu64Fnv1) } - public static func add(testhashs32Fnv1a: Int32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashs32Fnv1a, def: 0, at: VT.testhashs32Fnv1a) } - public static func add(testhashu32Fnv1a: UInt32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashu32Fnv1a, def: 0, at: VT.testhashu32Fnv1a) } - public static func add(testhashs64Fnv1a: Int64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashs64Fnv1a, def: 0, at: VT.testhashs64Fnv1a) } - public static func add(testhashu64Fnv1a: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashu64Fnv1a, def: 0, at: VT.testhashu64Fnv1a) } - public static func addVectorOf(testarrayofbools: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testarrayofbools, at: VT.testarrayofbools) } - public static func add(testf: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testf, def: 3.14159, at: VT.testf) } - public static func add(testf2: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testf2, def: 3.0, at: VT.testf2) } - public static func add(testf3: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testf3, def: 0.0, at: VT.testf3) } - public static func addVectorOf(testarrayofstring2: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testarrayofstring2, at: VT.testarrayofstring2) } - public static func addVectorOf(testarrayofsortedstruct: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testarrayofsortedstruct, at: VT.testarrayofsortedstruct) } + at: VTOFFSET.testbool.p) } + public static func add(testhashs32Fnv1: Int32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashs32Fnv1, def: 0, at: VTOFFSET.testhashs32Fnv1.p) } + public static func add(testhashu32Fnv1: UInt32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashu32Fnv1, def: 0, at: VTOFFSET.testhashu32Fnv1.p) } + public static func add(testhashs64Fnv1: Int64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashs64Fnv1, def: 0, at: VTOFFSET.testhashs64Fnv1.p) } + public static func add(testhashu64Fnv1: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashu64Fnv1, def: 0, at: VTOFFSET.testhashu64Fnv1.p) } + public static func add(testhashs32Fnv1a: Int32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashs32Fnv1a, def: 0, at: VTOFFSET.testhashs32Fnv1a.p) } + public static func add(testhashu32Fnv1a: UInt32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashu32Fnv1a, def: 0, at: VTOFFSET.testhashu32Fnv1a.p) } + public static func add(testhashs64Fnv1a: Int64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashs64Fnv1a, def: 0, at: VTOFFSET.testhashs64Fnv1a.p) } + public static func add(testhashu64Fnv1a: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashu64Fnv1a, def: 0, at: VTOFFSET.testhashu64Fnv1a.p) } + public static func addVectorOf(testarrayofbools: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testarrayofbools, at: VTOFFSET.testarrayofbools.p) } + public static func add(testf: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testf, def: 3.14159, at: VTOFFSET.testf.p) } + public static func add(testf2: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testf2, def: 3.0, at: VTOFFSET.testf2.p) } + public static func add(testf3: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testf3, def: 0.0, at: VTOFFSET.testf3.p) } + public static func addVectorOf(testarrayofstring2: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testarrayofstring2, at: VTOFFSET.testarrayofstring2.p) } + public static func addVectorOf(testarrayofsortedstruct: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testarrayofsortedstruct, at: VTOFFSET.testarrayofsortedstruct.p) } public static func startVectorOfTestarrayofsortedstruct(_ size: Int, in builder: inout FlatBufferBuilder) { builder.startVector(size * MemoryLayout.size, elementSize: MemoryLayout.alignment) } - public static func addVectorOf(flex: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: flex, at: VT.flex) } - public static func addVectorOf(test5: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: test5, at: VT.test5) } + public static func addVectorOf(flex: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: flex, at: VTOFFSET.flex.p) } + public static func addVectorOf(test5: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: test5, at: VTOFFSET.test5.p) } public static func startVectorOfTest5(_ size: Int, in builder: inout FlatBufferBuilder) { builder.startVector(size * MemoryLayout.size, elementSize: MemoryLayout.alignment) } - public static func addVectorOf(vectorOfLongs: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfLongs, at: VT.vectorOfLongs) } - public static func addVectorOf(vectorOfDoubles: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfDoubles, at: VT.vectorOfDoubles) } - public static func add(parentNamespaceTest: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: parentNamespaceTest, at: VT.parentNamespaceTest) } - public static func addVectorOf(vectorOfReferrables: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfReferrables, at: VT.vectorOfReferrables) } - public static func add(singleWeakReference: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: singleWeakReference, def: 0, at: VT.singleWeakReference) } - public static func addVectorOf(vectorOfWeakReferences: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfWeakReferences, at: VT.vectorOfWeakReferences) } - public static func addVectorOf(vectorOfStrongReferrables: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfStrongReferrables, at: VT.vectorOfStrongReferrables) } - public static func add(coOwningReference: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: coOwningReference, def: 0, at: VT.coOwningReference) } - public static func addVectorOf(vectorOfCoOwningReferences: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfCoOwningReferences, at: VT.vectorOfCoOwningReferences) } - public static func add(nonOwningReference: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: nonOwningReference, def: 0, at: VT.nonOwningReference) } - public static func addVectorOf(vectorOfNonOwningReferences: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfNonOwningReferences, at: VT.vectorOfNonOwningReferences) } - public static func add(anyUniqueType: MyGame_Example_AnyUniqueAliases, _ fbb: inout FlatBufferBuilder) { fbb.add(element: anyUniqueType.rawValue, def: 0, at: VT.anyUniqueType) } - public static func add(anyUnique: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: anyUnique, at: VT.anyUnique) } - public static func add(anyAmbiguousType: MyGame_Example_AnyAmbiguousAliases, _ fbb: inout FlatBufferBuilder) { fbb.add(element: anyAmbiguousType.rawValue, def: 0, at: VT.anyAmbiguousType) } - public static func add(anyAmbiguous: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: anyAmbiguous, at: VT.anyAmbiguous) } - public static func addVectorOf(vectorOfEnums: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfEnums, at: VT.vectorOfEnums) } - public static func add(signedEnum: MyGame_Example_Race, _ fbb: inout FlatBufferBuilder) { fbb.add(element: signedEnum.rawValue, def: -1, at: VT.signedEnum) } - public static func addVectorOf(testrequirednestedflatbuffer: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testrequirednestedflatbuffer, at: VT.testrequirednestedflatbuffer) } - public static func addVectorOf(scalarKeySortedTables: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: scalarKeySortedTables, at: VT.scalarKeySortedTables) } - public static func add(nativeInline: MyGame_Example_Test?, _ fbb: inout FlatBufferBuilder) { guard let nativeInline = nativeInline else { return }; fbb.create(struct: nativeInline, position: VT.nativeInline) } - public static func add(longEnumNonEnumDefault: MyGame_Example_LongEnum, _ fbb: inout FlatBufferBuilder) { fbb.add(element: longEnumNonEnumDefault.rawValue, def: 0, at: VT.longEnumNonEnumDefault) } - public static func add(longEnumNormalDefault: MyGame_Example_LongEnum, _ fbb: inout FlatBufferBuilder) { fbb.add(element: longEnumNormalDefault.rawValue, def: 2, at: VT.longEnumNormalDefault) } - public static func add(nanDefault: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: nanDefault, def: .nan, at: VT.nanDefault) } - public static func add(infDefault: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: infDefault, def: .infinity, at: VT.infDefault) } - public static func add(positiveInfDefault: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: positiveInfDefault, def: .infinity, at: VT.positiveInfDefault) } - public static func add(infinityDefault: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: infinityDefault, def: .infinity, at: VT.infinityDefault) } - public static func add(positiveInfinityDefault: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: positiveInfinityDefault, def: .infinity, at: VT.positiveInfinityDefault) } - public static func add(negativeInfDefault: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: negativeInfDefault, def: -.infinity, at: VT.negativeInfDefault) } - public static func add(negativeInfinityDefault: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: negativeInfinityDefault, def: -.infinity, at: VT.negativeInfinityDefault) } - public static func add(doubleInfDefault: Double, _ fbb: inout FlatBufferBuilder) { fbb.add(element: doubleInfDefault, def: .infinity, at: VT.doubleInfDefault) } + public static func addVectorOf(vectorOfLongs: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfLongs, at: VTOFFSET.vectorOfLongs.p) } + public static func addVectorOf(vectorOfDoubles: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfDoubles, at: VTOFFSET.vectorOfDoubles.p) } + public static func add(parentNamespaceTest: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: parentNamespaceTest, at: VTOFFSET.parentNamespaceTest.p) } + public static func addVectorOf(vectorOfReferrables: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfReferrables, at: VTOFFSET.vectorOfReferrables.p) } + public static func add(singleWeakReference: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: singleWeakReference, def: 0, at: VTOFFSET.singleWeakReference.p) } + public static func addVectorOf(vectorOfWeakReferences: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfWeakReferences, at: VTOFFSET.vectorOfWeakReferences.p) } + public static func addVectorOf(vectorOfStrongReferrables: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfStrongReferrables, at: VTOFFSET.vectorOfStrongReferrables.p) } + public static func add(coOwningReference: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: coOwningReference, def: 0, at: VTOFFSET.coOwningReference.p) } + public static func addVectorOf(vectorOfCoOwningReferences: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfCoOwningReferences, at: VTOFFSET.vectorOfCoOwningReferences.p) } + public static func add(nonOwningReference: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: nonOwningReference, def: 0, at: VTOFFSET.nonOwningReference.p) } + public static func addVectorOf(vectorOfNonOwningReferences: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfNonOwningReferences, at: VTOFFSET.vectorOfNonOwningReferences.p) } + public static func add(anyUniqueType: MyGame_Example_AnyUniqueAliases, _ fbb: inout FlatBufferBuilder) { fbb.add(element: anyUniqueType.rawValue, def: 0, at: VTOFFSET.anyUniqueType.p) } + public static func add(anyUnique: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: anyUnique, at: VTOFFSET.anyUnique.p) } + public static func add(anyAmbiguousType: MyGame_Example_AnyAmbiguousAliases, _ fbb: inout FlatBufferBuilder) { fbb.add(element: anyAmbiguousType.rawValue, def: 0, at: VTOFFSET.anyAmbiguousType.p) } + public static func add(anyAmbiguous: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: anyAmbiguous, at: VTOFFSET.anyAmbiguous.p) } + public static func addVectorOf(vectorOfEnums: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfEnums, at: VTOFFSET.vectorOfEnums.p) } + public static func add(signedEnum: MyGame_Example_Race, _ fbb: inout FlatBufferBuilder) { fbb.add(element: signedEnum.rawValue, def: -1, at: VTOFFSET.signedEnum.p) } + public static func addVectorOf(testrequirednestedflatbuffer: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testrequirednestedflatbuffer, at: VTOFFSET.testrequirednestedflatbuffer.p) } + public static func addVectorOf(scalarKeySortedTables: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: scalarKeySortedTables, at: VTOFFSET.scalarKeySortedTables.p) } + public static func add(nativeInline: MyGame_Example_Test?, _ fbb: inout FlatBufferBuilder) { guard let nativeInline = nativeInline else { return }; fbb.create(struct: nativeInline, position: VTOFFSET.nativeInline.p) } + public static func add(longEnumNonEnumDefault: MyGame_Example_LongEnum, _ fbb: inout FlatBufferBuilder) { fbb.add(element: longEnumNonEnumDefault.rawValue, def: 0, at: VTOFFSET.longEnumNonEnumDefault.p) } + public static func add(longEnumNormalDefault: MyGame_Example_LongEnum, _ fbb: inout FlatBufferBuilder) { fbb.add(element: longEnumNormalDefault.rawValue, def: 2, at: VTOFFSET.longEnumNormalDefault.p) } + public static func add(nanDefault: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: nanDefault, def: .nan, at: VTOFFSET.nanDefault.p) } + public static func add(infDefault: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: infDefault, def: .infinity, at: VTOFFSET.infDefault.p) } + public static func add(positiveInfDefault: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: positiveInfDefault, def: .infinity, at: VTOFFSET.positiveInfDefault.p) } + public static func add(infinityDefault: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: infinityDefault, def: .infinity, at: VTOFFSET.infinityDefault.p) } + public static func add(positiveInfinityDefault: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: positiveInfinityDefault, def: .infinity, at: VTOFFSET.positiveInfinityDefault.p) } + public static func add(negativeInfDefault: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: negativeInfDefault, def: -.infinity, at: VTOFFSET.negativeInfDefault.p) } + public static func add(negativeInfinityDefault: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: negativeInfinityDefault, def: -.infinity, at: VTOFFSET.negativeInfinityDefault.p) } + public static func add(doubleInfDefault: Double, _ fbb: inout FlatBufferBuilder) { fbb.add(element: doubleInfDefault, def: .infinity, at: VTOFFSET.doubleInfDefault.p) } public static func endMonster(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); fbb.require(table: end, fields: [10]); return end } public static func createMonster( _ fbb: inout FlatBufferBuilder, @@ -1646,13 +1656,13 @@ public struct MyGame_Example_Monster: FlatBufferVerifiableTable, FlatbuffersVect public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { var _v = try verifier.visitTable(at: position) - try _v.visit(field: VT.pos, fieldName: "pos", required: false, type: MyGame_Example_Vec3.self) - try _v.visit(field: VT.mana, fieldName: "mana", required: false, type: Int16.self) - try _v.visit(field: VT.hp, fieldName: "hp", required: false, type: Int16.self) - try _v.visit(field: VT.name, fieldName: "name", required: true, type: ForwardOffset.self) - try _v.visit(field: VT.inventory, fieldName: "inventory", required: false, type: ForwardOffset>.self) - try _v.visit(field: VT.color, fieldName: "color", required: false, type: MyGame_Example_Color.self) - try _v.visit(unionKey: VT.testType, unionField: VT.test, unionKeyName: "testType", fieldName: "test", required: false, completion: { (verifier, key: MyGame_Example_Any_, pos) in + try _v.visit(field: VTOFFSET.pos.p, fieldName: "pos", required: false, type: MyGame_Example_Vec3.self) + try _v.visit(field: VTOFFSET.mana.p, fieldName: "mana", required: false, type: Int16.self) + try _v.visit(field: VTOFFSET.hp.p, fieldName: "hp", required: false, type: Int16.self) + try _v.visit(field: VTOFFSET.name.p, fieldName: "name", required: true, type: ForwardOffset.self) + try _v.visit(field: VTOFFSET.inventory.p, fieldName: "inventory", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.color.p, fieldName: "color", required: false, type: MyGame_Example_Color.self) + try _v.visit(unionKey: VTOFFSET.testType.p, unionField: VTOFFSET.test.p, unionKeyName: "testType", fieldName: "test", required: false, completion: { (verifier, key: MyGame_Example_Any_, pos) in switch key { case .none_: break // NOTE - SWIFT doesnt support none @@ -1664,41 +1674,41 @@ public struct MyGame_Example_Monster: FlatBufferVerifiableTable, FlatbuffersVect try ForwardOffset.verify(&verifier, at: pos, of: MyGame_Example2_Monster.self) } }) - try _v.visit(field: VT.test4, fieldName: "test4", required: false, type: ForwardOffset>.self) - try _v.visit(field: VT.testarrayofstring, fieldName: "testarrayofstring", required: false, type: ForwardOffset, String>>.self) - try _v.visit(field: VT.testarrayoftables, fieldName: "testarrayoftables", required: false, type: ForwardOffset, MyGame_Example_Monster>>.self) - try _v.visit(field: VT.enemy, fieldName: "enemy", required: false, type: ForwardOffset.self) - try _v.visit(field: VT.testnestedflatbuffer, fieldName: "testnestedflatbuffer", required: false, type: ForwardOffset>.self) - try _v.visit(field: VT.testempty, fieldName: "testempty", required: false, type: ForwardOffset.self) - try _v.visit(field: VT.testbool, fieldName: "testbool", required: false, type: Bool.self) - try _v.visit(field: VT.testhashs32Fnv1, fieldName: "testhashs32Fnv1", required: false, type: Int32.self) - try _v.visit(field: VT.testhashu32Fnv1, fieldName: "testhashu32Fnv1", required: false, type: UInt32.self) - try _v.visit(field: VT.testhashs64Fnv1, fieldName: "testhashs64Fnv1", required: false, type: Int64.self) - try _v.visit(field: VT.testhashu64Fnv1, fieldName: "testhashu64Fnv1", required: false, type: UInt64.self) - try _v.visit(field: VT.testhashs32Fnv1a, fieldName: "testhashs32Fnv1a", required: false, type: Int32.self) - try _v.visit(field: VT.testhashu32Fnv1a, fieldName: "testhashu32Fnv1a", required: false, type: UInt32.self) - try _v.visit(field: VT.testhashs64Fnv1a, fieldName: "testhashs64Fnv1a", required: false, type: Int64.self) - try _v.visit(field: VT.testhashu64Fnv1a, fieldName: "testhashu64Fnv1a", required: false, type: UInt64.self) - try _v.visit(field: VT.testarrayofbools, fieldName: "testarrayofbools", required: false, type: ForwardOffset>.self) - try _v.visit(field: VT.testf, fieldName: "testf", required: false, type: Float32.self) - try _v.visit(field: VT.testf2, fieldName: "testf2", required: false, type: Float32.self) - try _v.visit(field: VT.testf3, fieldName: "testf3", required: false, type: Float32.self) - try _v.visit(field: VT.testarrayofstring2, fieldName: "testarrayofstring2", required: false, type: ForwardOffset, String>>.self) - try _v.visit(field: VT.testarrayofsortedstruct, fieldName: "testarrayofsortedstruct", required: false, type: ForwardOffset>.self) - try _v.visit(field: VT.flex, fieldName: "flex", required: false, type: ForwardOffset>.self) - try _v.visit(field: VT.test5, fieldName: "test5", required: false, type: ForwardOffset>.self) - try _v.visit(field: VT.vectorOfLongs, fieldName: "vectorOfLongs", required: false, type: ForwardOffset>.self) - try _v.visit(field: VT.vectorOfDoubles, fieldName: "vectorOfDoubles", required: false, type: ForwardOffset>.self) - try _v.visit(field: VT.parentNamespaceTest, fieldName: "parentNamespaceTest", required: false, type: ForwardOffset.self) - try _v.visit(field: VT.vectorOfReferrables, fieldName: "vectorOfReferrables", required: false, type: ForwardOffset, MyGame_Example_Referrable>>.self) - try _v.visit(field: VT.singleWeakReference, fieldName: "singleWeakReference", required: false, type: UInt64.self) - try _v.visit(field: VT.vectorOfWeakReferences, fieldName: "vectorOfWeakReferences", required: false, type: ForwardOffset>.self) - try _v.visit(field: VT.vectorOfStrongReferrables, fieldName: "vectorOfStrongReferrables", required: false, type: ForwardOffset, MyGame_Example_Referrable>>.self) - try _v.visit(field: VT.coOwningReference, fieldName: "coOwningReference", required: false, type: UInt64.self) - try _v.visit(field: VT.vectorOfCoOwningReferences, fieldName: "vectorOfCoOwningReferences", required: false, type: ForwardOffset>.self) - try _v.visit(field: VT.nonOwningReference, fieldName: "nonOwningReference", required: false, type: UInt64.self) - try _v.visit(field: VT.vectorOfNonOwningReferences, fieldName: "vectorOfNonOwningReferences", required: false, type: ForwardOffset>.self) - try _v.visit(unionKey: VT.anyUniqueType, unionField: VT.anyUnique, unionKeyName: "anyUniqueType", fieldName: "anyUnique", required: false, completion: { (verifier, key: MyGame_Example_AnyUniqueAliases, pos) in + try _v.visit(field: VTOFFSET.test4.p, fieldName: "test4", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.testarrayofstring.p, fieldName: "testarrayofstring", required: false, type: ForwardOffset, String>>.self) + try _v.visit(field: VTOFFSET.testarrayoftables.p, fieldName: "testarrayoftables", required: false, type: ForwardOffset, MyGame_Example_Monster>>.self) + try _v.visit(field: VTOFFSET.enemy.p, fieldName: "enemy", required: false, type: ForwardOffset.self) + try _v.visit(field: VTOFFSET.testnestedflatbuffer.p, fieldName: "testnestedflatbuffer", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.testempty.p, fieldName: "testempty", required: false, type: ForwardOffset.self) + try _v.visit(field: VTOFFSET.testbool.p, fieldName: "testbool", required: false, type: Bool.self) + try _v.visit(field: VTOFFSET.testhashs32Fnv1.p, fieldName: "testhashs32Fnv1", required: false, type: Int32.self) + try _v.visit(field: VTOFFSET.testhashu32Fnv1.p, fieldName: "testhashu32Fnv1", required: false, type: UInt32.self) + try _v.visit(field: VTOFFSET.testhashs64Fnv1.p, fieldName: "testhashs64Fnv1", required: false, type: Int64.self) + try _v.visit(field: VTOFFSET.testhashu64Fnv1.p, fieldName: "testhashu64Fnv1", required: false, type: UInt64.self) + try _v.visit(field: VTOFFSET.testhashs32Fnv1a.p, fieldName: "testhashs32Fnv1a", required: false, type: Int32.self) + try _v.visit(field: VTOFFSET.testhashu32Fnv1a.p, fieldName: "testhashu32Fnv1a", required: false, type: UInt32.self) + try _v.visit(field: VTOFFSET.testhashs64Fnv1a.p, fieldName: "testhashs64Fnv1a", required: false, type: Int64.self) + try _v.visit(field: VTOFFSET.testhashu64Fnv1a.p, fieldName: "testhashu64Fnv1a", required: false, type: UInt64.self) + try _v.visit(field: VTOFFSET.testarrayofbools.p, fieldName: "testarrayofbools", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.testf.p, fieldName: "testf", required: false, type: Float32.self) + try _v.visit(field: VTOFFSET.testf2.p, fieldName: "testf2", required: false, type: Float32.self) + try _v.visit(field: VTOFFSET.testf3.p, fieldName: "testf3", required: false, type: Float32.self) + try _v.visit(field: VTOFFSET.testarrayofstring2.p, fieldName: "testarrayofstring2", required: false, type: ForwardOffset, String>>.self) + try _v.visit(field: VTOFFSET.testarrayofsortedstruct.p, fieldName: "testarrayofsortedstruct", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.flex.p, fieldName: "flex", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.test5.p, fieldName: "test5", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.vectorOfLongs.p, fieldName: "vectorOfLongs", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.vectorOfDoubles.p, fieldName: "vectorOfDoubles", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.parentNamespaceTest.p, fieldName: "parentNamespaceTest", required: false, type: ForwardOffset.self) + try _v.visit(field: VTOFFSET.vectorOfReferrables.p, fieldName: "vectorOfReferrables", required: false, type: ForwardOffset, MyGame_Example_Referrable>>.self) + try _v.visit(field: VTOFFSET.singleWeakReference.p, fieldName: "singleWeakReference", required: false, type: UInt64.self) + try _v.visit(field: VTOFFSET.vectorOfWeakReferences.p, fieldName: "vectorOfWeakReferences", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.vectorOfStrongReferrables.p, fieldName: "vectorOfStrongReferrables", required: false, type: ForwardOffset, MyGame_Example_Referrable>>.self) + try _v.visit(field: VTOFFSET.coOwningReference.p, fieldName: "coOwningReference", required: false, type: UInt64.self) + try _v.visit(field: VTOFFSET.vectorOfCoOwningReferences.p, fieldName: "vectorOfCoOwningReferences", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.nonOwningReference.p, fieldName: "nonOwningReference", required: false, type: UInt64.self) + try _v.visit(field: VTOFFSET.vectorOfNonOwningReferences.p, fieldName: "vectorOfNonOwningReferences", required: false, type: ForwardOffset>.self) + try _v.visit(unionKey: VTOFFSET.anyUniqueType.p, unionField: VTOFFSET.anyUnique.p, unionKeyName: "anyUniqueType", fieldName: "anyUnique", required: false, completion: { (verifier, key: MyGame_Example_AnyUniqueAliases, pos) in switch key { case .none_: break // NOTE - SWIFT doesnt support none @@ -1710,7 +1720,7 @@ public struct MyGame_Example_Monster: FlatBufferVerifiableTable, FlatbuffersVect try ForwardOffset.verify(&verifier, at: pos, of: MyGame_Example2_Monster.self) } }) - try _v.visit(unionKey: VT.anyAmbiguousType, unionField: VT.anyAmbiguous, unionKeyName: "anyAmbiguousType", fieldName: "anyAmbiguous", required: false, completion: { (verifier, key: MyGame_Example_AnyAmbiguousAliases, pos) in + try _v.visit(unionKey: VTOFFSET.anyAmbiguousType.p, unionField: VTOFFSET.anyAmbiguous.p, unionKeyName: "anyAmbiguousType", fieldName: "anyAmbiguous", required: false, completion: { (verifier, key: MyGame_Example_AnyAmbiguousAliases, pos) in switch key { case .none_: break // NOTE - SWIFT doesnt support none @@ -1722,26 +1732,27 @@ public struct MyGame_Example_Monster: FlatBufferVerifiableTable, FlatbuffersVect try ForwardOffset.verify(&verifier, at: pos, of: MyGame_Example_Monster.self) } }) - try _v.visit(field: VT.vectorOfEnums, fieldName: "vectorOfEnums", required: false, type: ForwardOffset>.self) - try _v.visit(field: VT.signedEnum, fieldName: "signedEnum", required: false, type: MyGame_Example_Race.self) - try _v.visit(field: VT.testrequirednestedflatbuffer, fieldName: "testrequirednestedflatbuffer", required: false, type: ForwardOffset>.self) - try _v.visit(field: VT.scalarKeySortedTables, fieldName: "scalarKeySortedTables", required: false, type: ForwardOffset, MyGame_Example_Stat>>.self) - try _v.visit(field: VT.nativeInline, fieldName: "nativeInline", required: false, type: MyGame_Example_Test.self) - try _v.visit(field: VT.longEnumNonEnumDefault, fieldName: "longEnumNonEnumDefault", required: false, type: MyGame_Example_LongEnum.self) - try _v.visit(field: VT.longEnumNormalDefault, fieldName: "longEnumNormalDefault", required: false, type: MyGame_Example_LongEnum.self) - try _v.visit(field: VT.nanDefault, fieldName: "nanDefault", required: false, type: Float32.self) - try _v.visit(field: VT.infDefault, fieldName: "infDefault", required: false, type: Float32.self) - try _v.visit(field: VT.positiveInfDefault, fieldName: "positiveInfDefault", required: false, type: Float32.self) - try _v.visit(field: VT.infinityDefault, fieldName: "infinityDefault", required: false, type: Float32.self) - try _v.visit(field: VT.positiveInfinityDefault, fieldName: "positiveInfinityDefault", required: false, type: Float32.self) - try _v.visit(field: VT.negativeInfDefault, fieldName: "negativeInfDefault", required: false, type: Float32.self) - try _v.visit(field: VT.negativeInfinityDefault, fieldName: "negativeInfinityDefault", required: false, type: Float32.self) - try _v.visit(field: VT.doubleInfDefault, fieldName: "doubleInfDefault", required: false, type: Double.self) + try _v.visit(field: VTOFFSET.vectorOfEnums.p, fieldName: "vectorOfEnums", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.signedEnum.p, fieldName: "signedEnum", required: false, type: MyGame_Example_Race.self) + try _v.visit(field: VTOFFSET.testrequirednestedflatbuffer.p, fieldName: "testrequirednestedflatbuffer", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.scalarKeySortedTables.p, fieldName: "scalarKeySortedTables", required: false, type: ForwardOffset, MyGame_Example_Stat>>.self) + try _v.visit(field: VTOFFSET.nativeInline.p, fieldName: "nativeInline", required: false, type: MyGame_Example_Test.self) + try _v.visit(field: VTOFFSET.longEnumNonEnumDefault.p, fieldName: "longEnumNonEnumDefault", required: false, type: MyGame_Example_LongEnum.self) + try _v.visit(field: VTOFFSET.longEnumNormalDefault.p, fieldName: "longEnumNormalDefault", required: false, type: MyGame_Example_LongEnum.self) + try _v.visit(field: VTOFFSET.nanDefault.p, fieldName: "nanDefault", required: false, type: Float32.self) + try _v.visit(field: VTOFFSET.infDefault.p, fieldName: "infDefault", required: false, type: Float32.self) + try _v.visit(field: VTOFFSET.positiveInfDefault.p, fieldName: "positiveInfDefault", required: false, type: Float32.self) + try _v.visit(field: VTOFFSET.infinityDefault.p, fieldName: "infinityDefault", required: false, type: Float32.self) + try _v.visit(field: VTOFFSET.positiveInfinityDefault.p, fieldName: "positiveInfinityDefault", required: false, type: Float32.self) + try _v.visit(field: VTOFFSET.negativeInfDefault.p, fieldName: "negativeInfDefault", required: false, type: Float32.self) + try _v.visit(field: VTOFFSET.negativeInfinityDefault.p, fieldName: "negativeInfinityDefault", required: false, type: Float32.self) + try _v.visit(field: VTOFFSET.doubleInfDefault.p, fieldName: "doubleInfDefault", required: false, type: Double.self) _v.finish() } } extension MyGame_Example_Monster: Encodable { + enum CodingKeys: String, CodingKey { case pos = "pos" case mana = "mana" @@ -1805,7 +1816,6 @@ extension MyGame_Example_Monster: Encodable { case negativeInfinityDefault = "negative_infinity_default" case doubleInfDefault = "double_inf_default" } - public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(pos, forKey: .pos) @@ -2213,7 +2223,7 @@ public class MyGame_Example_MonsterT: NativeObject { public func serialize() -> ByteBuffer { return serialize(type: MyGame_Example_Monster.self) } } -public struct MyGame_Example_TypeAliases: FlatBufferVerifiableTable, FlatbuffersVectorInitializable, ObjectAPIPacker { +public struct MyGame_Example_TypeAliases: FlatBufferTable, FlatbuffersVectorInitializable, Verifiable, ObjectAPIPacker { static func validateVersion() { FlatBuffersVersion_25_12_19() } public var __buffer: ByteBuffer! { return _accessor.bb } @@ -2224,60 +2234,62 @@ public struct MyGame_Example_TypeAliases: FlatBufferVerifiableTable, Flatbuffers private init(_ t: Table) { _accessor = t } public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } - private struct VT { - static let i8: VOffset = 4 - static let u8: VOffset = 6 - static let i16: VOffset = 8 - static let u16: VOffset = 10 - static let i32: VOffset = 12 - static let u32: VOffset = 14 - static let i64: VOffset = 16 - static let u64: VOffset = 18 - static let f32: VOffset = 20 - static let f64: VOffset = 22 - static let v8: VOffset = 24 - static let vf64: VOffset = 26 + private enum VTOFFSET: VOffset { + case i8 = 4 + case u8 = 6 + case i16 = 8 + case u16 = 10 + case i32 = 12 + case u32 = 14 + case i64 = 16 + case u64 = 18 + case f32 = 20 + case f64 = 22 + case v8 = 24 + case vf64 = 26 + var v: Int32 { Int32(self.rawValue) } + var p: VOffset { self.rawValue } } - public var i8: Int8 { let o = _accessor.offset(VT.i8); return o == 0 ? 0 : _accessor.readBuffer(of: Int8.self, at: o) } - @discardableResult public func mutate(i8: Int8) -> Bool {let o = _accessor.offset(VT.i8); return _accessor.mutate(i8, index: o) } - public var u8: UInt8 { let o = _accessor.offset(VT.u8); return o == 0 ? 0 : _accessor.readBuffer(of: UInt8.self, at: o) } - @discardableResult public func mutate(u8: UInt8) -> Bool {let o = _accessor.offset(VT.u8); return _accessor.mutate(u8, index: o) } - public var i16: Int16 { let o = _accessor.offset(VT.i16); return o == 0 ? 0 : _accessor.readBuffer(of: Int16.self, at: o) } - @discardableResult public func mutate(i16: Int16) -> Bool {let o = _accessor.offset(VT.i16); return _accessor.mutate(i16, index: o) } - public var u16: UInt16 { let o = _accessor.offset(VT.u16); return o == 0 ? 0 : _accessor.readBuffer(of: UInt16.self, at: o) } - @discardableResult public func mutate(u16: UInt16) -> Bool {let o = _accessor.offset(VT.u16); return _accessor.mutate(u16, index: o) } - public var i32: Int32 { let o = _accessor.offset(VT.i32); return o == 0 ? 0 : _accessor.readBuffer(of: Int32.self, at: o) } - @discardableResult public func mutate(i32: Int32) -> Bool {let o = _accessor.offset(VT.i32); return _accessor.mutate(i32, index: o) } - public var u32: UInt32 { let o = _accessor.offset(VT.u32); return o == 0 ? 0 : _accessor.readBuffer(of: UInt32.self, at: o) } - @discardableResult public func mutate(u32: UInt32) -> Bool {let o = _accessor.offset(VT.u32); return _accessor.mutate(u32, index: o) } - public var i64: Int64 { let o = _accessor.offset(VT.i64); return o == 0 ? 0 : _accessor.readBuffer(of: Int64.self, at: o) } - @discardableResult public func mutate(i64: Int64) -> Bool {let o = _accessor.offset(VT.i64); return _accessor.mutate(i64, index: o) } - public var u64: UInt64 { let o = _accessor.offset(VT.u64); return o == 0 ? 0 : _accessor.readBuffer(of: UInt64.self, at: o) } - @discardableResult public func mutate(u64: UInt64) -> Bool {let o = _accessor.offset(VT.u64); return _accessor.mutate(u64, index: o) } - public var f32: Float32 { let o = _accessor.offset(VT.f32); return o == 0 ? 0.0 : _accessor.readBuffer(of: Float32.self, at: o) } - @discardableResult public func mutate(f32: Float32) -> Bool {let o = _accessor.offset(VT.f32); return _accessor.mutate(f32, index: o) } - public var f64: Double { let o = _accessor.offset(VT.f64); return o == 0 ? 0.0 : _accessor.readBuffer(of: Double.self, at: o) } - @discardableResult public func mutate(f64: Double) -> Bool {let o = _accessor.offset(VT.f64); return _accessor.mutate(f64, index: o) } - public var v8: FlatbufferVector { return _accessor.vector(at: VT.v8, byteSize: 1) } - public func mutate(v8: Int8, at index: Int32) -> Bool { let o = _accessor.offset(VT.v8); return _accessor.directMutate(v8, index: _accessor.vector(at: o) + index * 1) } - public func withUnsafePointerToV8(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VT.v8, body: body) } - public var vf64: FlatbufferVector { return _accessor.vector(at: VT.vf64, byteSize: 8) } - public func mutate(vf64: Double, at index: Int32) -> Bool { let o = _accessor.offset(VT.vf64); return _accessor.directMutate(vf64, index: _accessor.vector(at: o) + index * 8) } - public func withUnsafePointerToVf64(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VT.vf64, body: body) } + public var i8: Int8 { let o = _accessor.offset(VTOFFSET.i8.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int8.self, at: o) } + @discardableResult public func mutate(i8: Int8) -> Bool {let o = _accessor.offset(VTOFFSET.i8.v); return _accessor.mutate(i8, index: o) } + public var u8: UInt8 { let o = _accessor.offset(VTOFFSET.u8.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt8.self, at: o) } + @discardableResult public func mutate(u8: UInt8) -> Bool {let o = _accessor.offset(VTOFFSET.u8.v); return _accessor.mutate(u8, index: o) } + public var i16: Int16 { let o = _accessor.offset(VTOFFSET.i16.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int16.self, at: o) } + @discardableResult public func mutate(i16: Int16) -> Bool {let o = _accessor.offset(VTOFFSET.i16.v); return _accessor.mutate(i16, index: o) } + public var u16: UInt16 { let o = _accessor.offset(VTOFFSET.u16.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt16.self, at: o) } + @discardableResult public func mutate(u16: UInt16) -> Bool {let o = _accessor.offset(VTOFFSET.u16.v); return _accessor.mutate(u16, index: o) } + public var i32: Int32 { let o = _accessor.offset(VTOFFSET.i32.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int32.self, at: o) } + @discardableResult public func mutate(i32: Int32) -> Bool {let o = _accessor.offset(VTOFFSET.i32.v); return _accessor.mutate(i32, index: o) } + public var u32: UInt32 { let o = _accessor.offset(VTOFFSET.u32.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt32.self, at: o) } + @discardableResult public func mutate(u32: UInt32) -> Bool {let o = _accessor.offset(VTOFFSET.u32.v); return _accessor.mutate(u32, index: o) } + public var i64: Int64 { let o = _accessor.offset(VTOFFSET.i64.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int64.self, at: o) } + @discardableResult public func mutate(i64: Int64) -> Bool {let o = _accessor.offset(VTOFFSET.i64.v); return _accessor.mutate(i64, index: o) } + public var u64: UInt64 { let o = _accessor.offset(VTOFFSET.u64.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt64.self, at: o) } + @discardableResult public func mutate(u64: UInt64) -> Bool {let o = _accessor.offset(VTOFFSET.u64.v); return _accessor.mutate(u64, index: o) } + public var f32: Float32 { let o = _accessor.offset(VTOFFSET.f32.v); return o == 0 ? 0.0 : _accessor.readBuffer(of: Float32.self, at: o) } + @discardableResult public func mutate(f32: Float32) -> Bool {let o = _accessor.offset(VTOFFSET.f32.v); return _accessor.mutate(f32, index: o) } + public var f64: Double { let o = _accessor.offset(VTOFFSET.f64.v); return o == 0 ? 0.0 : _accessor.readBuffer(of: Double.self, at: o) } + @discardableResult public func mutate(f64: Double) -> Bool {let o = _accessor.offset(VTOFFSET.f64.v); return _accessor.mutate(f64, index: o) } + public var v8: FlatbufferVector { return _accessor.vector(at: VTOFFSET.v8.v, byteSize: 1) } + public func mutate(v8: Int8, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.v8.v); return _accessor.directMutate(v8, index: _accessor.vector(at: o) + index * 1) } + public func withUnsafePointerToV8(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VTOFFSET.v8.v, body: body) } + public var vf64: FlatbufferVector { return _accessor.vector(at: VTOFFSET.vf64.v, byteSize: 8) } + public func mutate(vf64: Double, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.vf64.v); return _accessor.directMutate(vf64, index: _accessor.vector(at: o) + index * 8) } + public func withUnsafePointerToVf64(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VTOFFSET.vf64.v, body: body) } public static func startTypeAliases(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 12) } - public static func add(i8: Int8, _ fbb: inout FlatBufferBuilder) { fbb.add(element: i8, def: 0, at: VT.i8) } - public static func add(u8: UInt8, _ fbb: inout FlatBufferBuilder) { fbb.add(element: u8, def: 0, at: VT.u8) } - public static func add(i16: Int16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: i16, def: 0, at: VT.i16) } - public static func add(u16: UInt16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: u16, def: 0, at: VT.u16) } - public static func add(i32: Int32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: i32, def: 0, at: VT.i32) } - public static func add(u32: UInt32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: u32, def: 0, at: VT.u32) } - public static func add(i64: Int64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: i64, def: 0, at: VT.i64) } - public static func add(u64: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: u64, def: 0, at: VT.u64) } - public static func add(f32: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: f32, def: 0.0, at: VT.f32) } - public static func add(f64: Double, _ fbb: inout FlatBufferBuilder) { fbb.add(element: f64, def: 0.0, at: VT.f64) } - public static func addVectorOf(v8: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: v8, at: VT.v8) } - public static func addVectorOf(vf64: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vf64, at: VT.vf64) } + public static func add(i8: Int8, _ fbb: inout FlatBufferBuilder) { fbb.add(element: i8, def: 0, at: VTOFFSET.i8.p) } + public static func add(u8: UInt8, _ fbb: inout FlatBufferBuilder) { fbb.add(element: u8, def: 0, at: VTOFFSET.u8.p) } + public static func add(i16: Int16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: i16, def: 0, at: VTOFFSET.i16.p) } + public static func add(u16: UInt16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: u16, def: 0, at: VTOFFSET.u16.p) } + public static func add(i32: Int32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: i32, def: 0, at: VTOFFSET.i32.p) } + public static func add(u32: UInt32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: u32, def: 0, at: VTOFFSET.u32.p) } + public static func add(i64: Int64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: i64, def: 0, at: VTOFFSET.i64.p) } + public static func add(u64: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: u64, def: 0, at: VTOFFSET.u64.p) } + public static func add(f32: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: f32, def: 0.0, at: VTOFFSET.f32.p) } + public static func add(f64: Double, _ fbb: inout FlatBufferBuilder) { fbb.add(element: f64, def: 0.0, at: VTOFFSET.f64.p) } + public static func addVectorOf(v8: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: v8, at: VTOFFSET.v8.p) } + public static func addVectorOf(vf64: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vf64, at: VTOFFSET.vf64.p) } public static func endTypeAliases(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } public static func createTypeAliases( _ fbb: inout FlatBufferBuilder, @@ -2339,23 +2351,24 @@ public struct MyGame_Example_TypeAliases: FlatBufferVerifiableTable, Flatbuffers public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { var _v = try verifier.visitTable(at: position) - try _v.visit(field: VT.i8, fieldName: "i8", required: false, type: Int8.self) - try _v.visit(field: VT.u8, fieldName: "u8", required: false, type: UInt8.self) - try _v.visit(field: VT.i16, fieldName: "i16", required: false, type: Int16.self) - try _v.visit(field: VT.u16, fieldName: "u16", required: false, type: UInt16.self) - try _v.visit(field: VT.i32, fieldName: "i32", required: false, type: Int32.self) - try _v.visit(field: VT.u32, fieldName: "u32", required: false, type: UInt32.self) - try _v.visit(field: VT.i64, fieldName: "i64", required: false, type: Int64.self) - try _v.visit(field: VT.u64, fieldName: "u64", required: false, type: UInt64.self) - try _v.visit(field: VT.f32, fieldName: "f32", required: false, type: Float32.self) - try _v.visit(field: VT.f64, fieldName: "f64", required: false, type: Double.self) - try _v.visit(field: VT.v8, fieldName: "v8", required: false, type: ForwardOffset>.self) - try _v.visit(field: VT.vf64, fieldName: "vf64", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.i8.p, fieldName: "i8", required: false, type: Int8.self) + try _v.visit(field: VTOFFSET.u8.p, fieldName: "u8", required: false, type: UInt8.self) + try _v.visit(field: VTOFFSET.i16.p, fieldName: "i16", required: false, type: Int16.self) + try _v.visit(field: VTOFFSET.u16.p, fieldName: "u16", required: false, type: UInt16.self) + try _v.visit(field: VTOFFSET.i32.p, fieldName: "i32", required: false, type: Int32.self) + try _v.visit(field: VTOFFSET.u32.p, fieldName: "u32", required: false, type: UInt32.self) + try _v.visit(field: VTOFFSET.i64.p, fieldName: "i64", required: false, type: Int64.self) + try _v.visit(field: VTOFFSET.u64.p, fieldName: "u64", required: false, type: UInt64.self) + try _v.visit(field: VTOFFSET.f32.p, fieldName: "f32", required: false, type: Float32.self) + try _v.visit(field: VTOFFSET.f64.p, fieldName: "f64", required: false, type: Double.self) + try _v.visit(field: VTOFFSET.v8.p, fieldName: "v8", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.vf64.p, fieldName: "vf64", required: false, type: ForwardOffset>.self) _v.finish() } } extension MyGame_Example_TypeAliases: Encodable { + enum CodingKeys: String, CodingKey { case i8 = "i8" case u8 = "u8" @@ -2370,7 +2383,6 @@ extension MyGame_Example_TypeAliases: Encodable { case v8 = "v8" case vf64 = "vf64" } - public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) if i8 != 0 { diff --git a/tests/swift/Tests/Flatbuffers/more_defaults_generated.swift b/tests/swift/Tests/Flatbuffers/more_defaults_generated.swift index e1806cfe6..2756aade6 100644 --- a/tests/swift/Tests/Flatbuffers/more_defaults_generated.swift +++ b/tests/swift/Tests/Flatbuffers/more_defaults_generated.swift @@ -31,7 +31,7 @@ extension ABC: Encodable { } } -public struct MoreDefaults: FlatBufferVerifiableTable, FlatbuffersVectorInitializable, ObjectAPIPacker { +public struct MoreDefaults: FlatBufferTable, FlatbuffersVectorInitializable, Verifiable, ObjectAPIPacker { static func validateVersion() { FlatBuffersVersion_25_12_19() } public var __buffer: ByteBuffer! { return _accessor.bb } @@ -40,33 +40,35 @@ public struct MoreDefaults: FlatBufferVerifiableTable, FlatbuffersVectorInitiali private init(_ t: Table) { _accessor = t } public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } - private struct VT { - static let ints: VOffset = 4 - static let floats: VOffset = 6 - static let emptyString: VOffset = 8 - static let someString: VOffset = 10 - static let abcs: VOffset = 12 - static let bools: VOffset = 14 + private enum VTOFFSET: VOffset { + case ints = 4 + case floats = 6 + case emptyString = 8 + case someString = 10 + case abcs = 12 + case bools = 14 + var v: Int32 { Int32(self.rawValue) } + var p: VOffset { self.rawValue } } - public var ints: FlatbufferVector { return _accessor.vector(at: VT.ints, byteSize: 4) } - public func withUnsafePointerToInts(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VT.ints, body: body) } - public var floats: FlatbufferVector { return _accessor.vector(at: VT.floats, byteSize: 4) } - public func withUnsafePointerToFloats(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VT.floats, body: body) } - public var emptyString: String? { let o = _accessor.offset(VT.emptyString); return o == 0 ? "" : _accessor.string(at: o) } - public var emptyStringSegmentArray: [UInt8]? { return _accessor.getVector(at: VT.emptyString) } - public var someString: String? { let o = _accessor.offset(VT.someString); return o == 0 ? "some" : _accessor.string(at: o) } - public var someStringSegmentArray: [UInt8]? { return _accessor.getVector(at: VT.someString) } - public var abcs: FlatbufferVector { return _accessor.vector(at: VT.abcs, byteSize: 4) } - public var bools: FlatbufferVector { return _accessor.vector(at: VT.bools, byteSize: 1) } - public func withUnsafePointerToBools(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VT.bools, body: body) } + public var ints: FlatbufferVector { return _accessor.vector(at: VTOFFSET.ints.v, byteSize: 4) } + public func withUnsafePointerToInts(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VTOFFSET.ints.v, body: body) } + public var floats: FlatbufferVector { return _accessor.vector(at: VTOFFSET.floats.v, byteSize: 4) } + public func withUnsafePointerToFloats(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VTOFFSET.floats.v, body: body) } + public var emptyString: String? { let o = _accessor.offset(VTOFFSET.emptyString.v); return o == 0 ? "" : _accessor.string(at: o) } + public var emptyStringSegmentArray: [UInt8]? { return _accessor.getVector(at: VTOFFSET.emptyString.v) } + public var someString: String? { let o = _accessor.offset(VTOFFSET.someString.v); return o == 0 ? "some" : _accessor.string(at: o) } + public var someStringSegmentArray: [UInt8]? { return _accessor.getVector(at: VTOFFSET.someString.v) } + public var abcs: FlatbufferVector { return _accessor.vector(at: VTOFFSET.abcs.v, byteSize: 4) } + public var bools: FlatbufferVector { return _accessor.vector(at: VTOFFSET.bools.v, byteSize: 1) } + public func withUnsafePointerToBools(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VTOFFSET.bools.v, body: body) } public static func startMoreDefaults(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 6) } - public static func addVectorOf(ints: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: ints, at: VT.ints) } - public static func addVectorOf(floats: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: floats, at: VT.floats) } - public static func add(emptyString: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: emptyString, at: VT.emptyString) } - public static func add(someString: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: someString, at: VT.someString) } - public static func addVectorOf(abcs: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: abcs, at: VT.abcs) } - public static func addVectorOf(bools: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: bools, at: VT.bools) } + public static func addVectorOf(ints: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: ints, at: VTOFFSET.ints.p) } + public static func addVectorOf(floats: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: floats, at: VTOFFSET.floats.p) } + public static func add(emptyString: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: emptyString, at: VTOFFSET.emptyString.p) } + public static func add(someString: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: someString, at: VTOFFSET.someString.p) } + public static func addVectorOf(abcs: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: abcs, at: VTOFFSET.abcs.p) } + public static func addVectorOf(bools: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: bools, at: VTOFFSET.bools.p) } public static func endMoreDefaults(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } public static func createMoreDefaults( _ fbb: inout FlatBufferBuilder, @@ -126,17 +128,18 @@ public struct MoreDefaults: FlatBufferVerifiableTable, FlatbuffersVectorInitiali public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { var _v = try verifier.visitTable(at: position) - try _v.visit(field: VT.ints, fieldName: "ints", required: false, type: ForwardOffset>.self) - try _v.visit(field: VT.floats, fieldName: "floats", required: false, type: ForwardOffset>.self) - try _v.visit(field: VT.emptyString, fieldName: "emptyString", required: false, type: ForwardOffset.self) - try _v.visit(field: VT.someString, fieldName: "someString", required: false, type: ForwardOffset.self) - try _v.visit(field: VT.abcs, fieldName: "abcs", required: false, type: ForwardOffset>.self) - try _v.visit(field: VT.bools, fieldName: "bools", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.ints.p, fieldName: "ints", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.floats.p, fieldName: "floats", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.emptyString.p, fieldName: "emptyString", required: false, type: ForwardOffset.self) + try _v.visit(field: VTOFFSET.someString.p, fieldName: "someString", required: false, type: ForwardOffset.self) + try _v.visit(field: VTOFFSET.abcs.p, fieldName: "abcs", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.bools.p, fieldName: "bools", required: false, type: ForwardOffset>.self) _v.finish() } } extension MoreDefaults: Encodable { + enum CodingKeys: String, CodingKey { case ints = "ints" case floats = "floats" @@ -145,7 +148,6 @@ extension MoreDefaults: Encodable { case abcs = "abcs" case bools = "bools" } - public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(ints, forKey: .ints) diff --git a/tests/swift/Tests/Flatbuffers/nan_inf_test_generated.swift b/tests/swift/Tests/Flatbuffers/nan_inf_test_generated.swift index 8c15bc1bc..0e8c49b46 100644 --- a/tests/swift/Tests/Flatbuffers/nan_inf_test_generated.swift +++ b/tests/swift/Tests/Flatbuffers/nan_inf_test_generated.swift @@ -8,7 +8,7 @@ import Common import FlatBuffers -public struct Swift_Tests_NanInfTable: FlatBufferVerifiableTable, FlatbuffersVectorInitializable { +public struct Swift_Tests_NanInfTable: FlatBufferTable, FlatbuffersVectorInitializable, Verifiable { static func validateVersion() { FlatBuffersVersion_25_12_19() } public var __buffer: ByteBuffer! { return _accessor.bb } @@ -17,31 +17,33 @@ public struct Swift_Tests_NanInfTable: FlatBufferVerifiableTable, FlatbuffersVec private init(_ t: Table) { _accessor = t } public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } - private struct VT { - static let defaultNan: VOffset = 4 - static let defaultInf: VOffset = 6 - static let defaultNinf: VOffset = 8 - static let valueNan: VOffset = 10 - static let valueInf: VOffset = 12 - static let valueNinf: VOffset = 14 - static let value: VOffset = 16 + private enum VTOFFSET: VOffset { + case defaultNan = 4 + case defaultInf = 6 + case defaultNinf = 8 + case valueNan = 10 + case valueInf = 12 + case valueNinf = 14 + case value = 16 + var v: Int32 { Int32(self.rawValue) } + var p: VOffset { self.rawValue } } - public var defaultNan: Double { let o = _accessor.offset(VT.defaultNan); return o == 0 ? .nan : _accessor.readBuffer(of: Double.self, at: o) } - public var defaultInf: Double { let o = _accessor.offset(VT.defaultInf); return o == 0 ? .infinity : _accessor.readBuffer(of: Double.self, at: o) } - public var defaultNinf: Double { let o = _accessor.offset(VT.defaultNinf); return o == 0 ? -.infinity : _accessor.readBuffer(of: Double.self, at: o) } - public var valueNan: Double { let o = _accessor.offset(VT.valueNan); return o == 0 ? 0.0 : _accessor.readBuffer(of: Double.self, at: o) } - public var valueInf: Double { let o = _accessor.offset(VT.valueInf); return o == 0 ? 0.0 : _accessor.readBuffer(of: Double.self, at: o) } - public var valueNinf: Double { let o = _accessor.offset(VT.valueNinf); return o == 0 ? 0.0 : _accessor.readBuffer(of: Double.self, at: o) } - public var value: Double { let o = _accessor.offset(VT.value); return o == 0 ? 0.0 : _accessor.readBuffer(of: Double.self, at: o) } + public var defaultNan: Double { let o = _accessor.offset(VTOFFSET.defaultNan.v); return o == 0 ? .nan : _accessor.readBuffer(of: Double.self, at: o) } + public var defaultInf: Double { let o = _accessor.offset(VTOFFSET.defaultInf.v); return o == 0 ? .infinity : _accessor.readBuffer(of: Double.self, at: o) } + public var defaultNinf: Double { let o = _accessor.offset(VTOFFSET.defaultNinf.v); return o == 0 ? -.infinity : _accessor.readBuffer(of: Double.self, at: o) } + public var valueNan: Double { let o = _accessor.offset(VTOFFSET.valueNan.v); return o == 0 ? 0.0 : _accessor.readBuffer(of: Double.self, at: o) } + public var valueInf: Double { let o = _accessor.offset(VTOFFSET.valueInf.v); return o == 0 ? 0.0 : _accessor.readBuffer(of: Double.self, at: o) } + public var valueNinf: Double { let o = _accessor.offset(VTOFFSET.valueNinf.v); return o == 0 ? 0.0 : _accessor.readBuffer(of: Double.self, at: o) } + public var value: Double { let o = _accessor.offset(VTOFFSET.value.v); return o == 0 ? 0.0 : _accessor.readBuffer(of: Double.self, at: o) } public static func startNanInfTable(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 7) } - public static func add(defaultNan: Double, _ fbb: inout FlatBufferBuilder) { fbb.add(element: defaultNan, def: .nan, at: VT.defaultNan) } - public static func add(defaultInf: Double, _ fbb: inout FlatBufferBuilder) { fbb.add(element: defaultInf, def: .infinity, at: VT.defaultInf) } - public static func add(defaultNinf: Double, _ fbb: inout FlatBufferBuilder) { fbb.add(element: defaultNinf, def: -.infinity, at: VT.defaultNinf) } - public static func add(valueNan: Double, _ fbb: inout FlatBufferBuilder) { fbb.add(element: valueNan, def: 0.0, at: VT.valueNan) } - public static func add(valueInf: Double, _ fbb: inout FlatBufferBuilder) { fbb.add(element: valueInf, def: 0.0, at: VT.valueInf) } - public static func add(valueNinf: Double, _ fbb: inout FlatBufferBuilder) { fbb.add(element: valueNinf, def: 0.0, at: VT.valueNinf) } - public static func add(value: Double, _ fbb: inout FlatBufferBuilder) { fbb.add(element: value, def: 0.0, at: VT.value) } + public static func add(defaultNan: Double, _ fbb: inout FlatBufferBuilder) { fbb.add(element: defaultNan, def: .nan, at: VTOFFSET.defaultNan.p) } + public static func add(defaultInf: Double, _ fbb: inout FlatBufferBuilder) { fbb.add(element: defaultInf, def: .infinity, at: VTOFFSET.defaultInf.p) } + public static func add(defaultNinf: Double, _ fbb: inout FlatBufferBuilder) { fbb.add(element: defaultNinf, def: -.infinity, at: VTOFFSET.defaultNinf.p) } + public static func add(valueNan: Double, _ fbb: inout FlatBufferBuilder) { fbb.add(element: valueNan, def: 0.0, at: VTOFFSET.valueNan.p) } + public static func add(valueInf: Double, _ fbb: inout FlatBufferBuilder) { fbb.add(element: valueInf, def: 0.0, at: VTOFFSET.valueInf.p) } + public static func add(valueNinf: Double, _ fbb: inout FlatBufferBuilder) { fbb.add(element: valueNinf, def: 0.0, at: VTOFFSET.valueNinf.p) } + public static func add(value: Double, _ fbb: inout FlatBufferBuilder) { fbb.add(element: value, def: 0.0, at: VTOFFSET.value.p) } public static func endNanInfTable(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } public static func createNanInfTable( _ fbb: inout FlatBufferBuilder, @@ -66,18 +68,19 @@ public struct Swift_Tests_NanInfTable: FlatBufferVerifiableTable, FlatbuffersVec public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { var _v = try verifier.visitTable(at: position) - try _v.visit(field: VT.defaultNan, fieldName: "defaultNan", required: false, type: Double.self) - try _v.visit(field: VT.defaultInf, fieldName: "defaultInf", required: false, type: Double.self) - try _v.visit(field: VT.defaultNinf, fieldName: "defaultNinf", required: false, type: Double.self) - try _v.visit(field: VT.valueNan, fieldName: "valueNan", required: false, type: Double.self) - try _v.visit(field: VT.valueInf, fieldName: "valueInf", required: false, type: Double.self) - try _v.visit(field: VT.valueNinf, fieldName: "valueNinf", required: false, type: Double.self) - try _v.visit(field: VT.value, fieldName: "value", required: false, type: Double.self) + try _v.visit(field: VTOFFSET.defaultNan.p, fieldName: "defaultNan", required: false, type: Double.self) + try _v.visit(field: VTOFFSET.defaultInf.p, fieldName: "defaultInf", required: false, type: Double.self) + try _v.visit(field: VTOFFSET.defaultNinf.p, fieldName: "defaultNinf", required: false, type: Double.self) + try _v.visit(field: VTOFFSET.valueNan.p, fieldName: "valueNan", required: false, type: Double.self) + try _v.visit(field: VTOFFSET.valueInf.p, fieldName: "valueInf", required: false, type: Double.self) + try _v.visit(field: VTOFFSET.valueNinf.p, fieldName: "valueNinf", required: false, type: Double.self) + try _v.visit(field: VTOFFSET.value.p, fieldName: "value", required: false, type: Double.self) _v.finish() } } extension Swift_Tests_NanInfTable: Encodable { + enum CodingKeys: String, CodingKey { case defaultNan = "default_nan" case defaultInf = "default_inf" @@ -87,7 +90,6 @@ extension Swift_Tests_NanInfTable: Encodable { case valueNinf = "value_ninf" case value = "value" } - public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) if !defaultNan.isNaN { diff --git a/tests/swift/Tests/Flatbuffers/optional_scalars_generated.swift b/tests/swift/Tests/Flatbuffers/optional_scalars_generated.swift index 7c1e68287..899847da9 100644 --- a/tests/swift/Tests/Flatbuffers/optional_scalars_generated.swift +++ b/tests/swift/Tests/Flatbuffers/optional_scalars_generated.swift @@ -31,7 +31,7 @@ extension optional_scalars_OptionalByte: Encodable { } } -public struct optional_scalars_ScalarStuff: FlatBufferVerifiableTable, FlatbuffersVectorInitializable { +public struct optional_scalars_ScalarStuff: FlatBufferTable, FlatbuffersVectorInitializable, Verifiable { static func validateVersion() { FlatBuffersVersion_25_12_19() } public var __buffer: ByteBuffer! { return _accessor.bb } @@ -42,120 +42,122 @@ public struct optional_scalars_ScalarStuff: FlatBufferVerifiableTable, Flatbuffe private init(_ t: Table) { _accessor = t } public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } - private struct VT { - static let justI8: VOffset = 4 - static let maybeI8: VOffset = 6 - static let defaultI8: VOffset = 8 - static let justU8: VOffset = 10 - static let maybeU8: VOffset = 12 - static let defaultU8: VOffset = 14 - static let justI16: VOffset = 16 - static let maybeI16: VOffset = 18 - static let defaultI16: VOffset = 20 - static let justU16: VOffset = 22 - static let maybeU16: VOffset = 24 - static let defaultU16: VOffset = 26 - static let justI32: VOffset = 28 - static let maybeI32: VOffset = 30 - static let defaultI32: VOffset = 32 - static let justU32: VOffset = 34 - static let maybeU32: VOffset = 36 - static let defaultU32: VOffset = 38 - static let justI64: VOffset = 40 - static let maybeI64: VOffset = 42 - static let defaultI64: VOffset = 44 - static let justU64: VOffset = 46 - static let maybeU64: VOffset = 48 - static let defaultU64: VOffset = 50 - static let justF32: VOffset = 52 - static let maybeF32: VOffset = 54 - static let defaultF32: VOffset = 56 - static let justF64: VOffset = 58 - static let maybeF64: VOffset = 60 - static let defaultF64: VOffset = 62 - static let justBool: VOffset = 64 - static let maybeBool: VOffset = 66 - static let defaultBool: VOffset = 68 - static let justEnum: VOffset = 70 - static let maybeEnum: VOffset = 72 - static let defaultEnum: VOffset = 74 + private enum VTOFFSET: VOffset { + case justI8 = 4 + case maybeI8 = 6 + case defaultI8 = 8 + case justU8 = 10 + case maybeU8 = 12 + case defaultU8 = 14 + case justI16 = 16 + case maybeI16 = 18 + case defaultI16 = 20 + case justU16 = 22 + case maybeU16 = 24 + case defaultU16 = 26 + case justI32 = 28 + case maybeI32 = 30 + case defaultI32 = 32 + case justU32 = 34 + case maybeU32 = 36 + case defaultU32 = 38 + case justI64 = 40 + case maybeI64 = 42 + case defaultI64 = 44 + case justU64 = 46 + case maybeU64 = 48 + case defaultU64 = 50 + case justF32 = 52 + case maybeF32 = 54 + case defaultF32 = 56 + case justF64 = 58 + case maybeF64 = 60 + case defaultF64 = 62 + case justBool = 64 + case maybeBool = 66 + case defaultBool = 68 + case justEnum = 70 + case maybeEnum = 72 + case defaultEnum = 74 + var v: Int32 { Int32(self.rawValue) } + var p: VOffset { self.rawValue } } - public var justI8: Int8 { let o = _accessor.offset(VT.justI8); return o == 0 ? 0 : _accessor.readBuffer(of: Int8.self, at: o) } - public var maybeI8: Int8? { let o = _accessor.offset(VT.maybeI8); return o == 0 ? nil : _accessor.readBuffer(of: Int8.self, at: o) } - public var defaultI8: Int8 { let o = _accessor.offset(VT.defaultI8); return o == 0 ? 42 : _accessor.readBuffer(of: Int8.self, at: o) } - public var justU8: UInt8 { let o = _accessor.offset(VT.justU8); return o == 0 ? 0 : _accessor.readBuffer(of: UInt8.self, at: o) } - public var maybeU8: UInt8? { let o = _accessor.offset(VT.maybeU8); return o == 0 ? nil : _accessor.readBuffer(of: UInt8.self, at: o) } - public var defaultU8: UInt8 { let o = _accessor.offset(VT.defaultU8); return o == 0 ? 42 : _accessor.readBuffer(of: UInt8.self, at: o) } - public var justI16: Int16 { let o = _accessor.offset(VT.justI16); return o == 0 ? 0 : _accessor.readBuffer(of: Int16.self, at: o) } - public var maybeI16: Int16? { let o = _accessor.offset(VT.maybeI16); return o == 0 ? nil : _accessor.readBuffer(of: Int16.self, at: o) } - public var defaultI16: Int16 { let o = _accessor.offset(VT.defaultI16); return o == 0 ? 42 : _accessor.readBuffer(of: Int16.self, at: o) } - public var justU16: UInt16 { let o = _accessor.offset(VT.justU16); return o == 0 ? 0 : _accessor.readBuffer(of: UInt16.self, at: o) } - public var maybeU16: UInt16? { let o = _accessor.offset(VT.maybeU16); return o == 0 ? nil : _accessor.readBuffer(of: UInt16.self, at: o) } - public var defaultU16: UInt16 { let o = _accessor.offset(VT.defaultU16); return o == 0 ? 42 : _accessor.readBuffer(of: UInt16.self, at: o) } - public var justI32: Int32 { let o = _accessor.offset(VT.justI32); return o == 0 ? 0 : _accessor.readBuffer(of: Int32.self, at: o) } - public var maybeI32: Int32? { let o = _accessor.offset(VT.maybeI32); return o == 0 ? nil : _accessor.readBuffer(of: Int32.self, at: o) } - public var defaultI32: Int32 { let o = _accessor.offset(VT.defaultI32); return o == 0 ? 42 : _accessor.readBuffer(of: Int32.self, at: o) } - public var justU32: UInt32 { let o = _accessor.offset(VT.justU32); return o == 0 ? 0 : _accessor.readBuffer(of: UInt32.self, at: o) } - public var maybeU32: UInt32? { let o = _accessor.offset(VT.maybeU32); return o == 0 ? nil : _accessor.readBuffer(of: UInt32.self, at: o) } - public var defaultU32: UInt32 { let o = _accessor.offset(VT.defaultU32); return o == 0 ? 42 : _accessor.readBuffer(of: UInt32.self, at: o) } - public var justI64: Int64 { let o = _accessor.offset(VT.justI64); return o == 0 ? 0 : _accessor.readBuffer(of: Int64.self, at: o) } - public var maybeI64: Int64? { let o = _accessor.offset(VT.maybeI64); return o == 0 ? nil : _accessor.readBuffer(of: Int64.self, at: o) } - public var defaultI64: Int64 { let o = _accessor.offset(VT.defaultI64); return o == 0 ? 42 : _accessor.readBuffer(of: Int64.self, at: o) } - public var justU64: UInt64 { let o = _accessor.offset(VT.justU64); return o == 0 ? 0 : _accessor.readBuffer(of: UInt64.self, at: o) } - public var maybeU64: UInt64? { let o = _accessor.offset(VT.maybeU64); return o == 0 ? nil : _accessor.readBuffer(of: UInt64.self, at: o) } - public var defaultU64: UInt64 { let o = _accessor.offset(VT.defaultU64); return o == 0 ? 42 : _accessor.readBuffer(of: UInt64.self, at: o) } - public var justF32: Float32 { let o = _accessor.offset(VT.justF32); return o == 0 ? 0.0 : _accessor.readBuffer(of: Float32.self, at: o) } - public var maybeF32: Float32? { let o = _accessor.offset(VT.maybeF32); return o == 0 ? nil : _accessor.readBuffer(of: Float32.self, at: o) } - public var defaultF32: Float32 { let o = _accessor.offset(VT.defaultF32); return o == 0 ? 42.0 : _accessor.readBuffer(of: Float32.self, at: o) } - public var justF64: Double { let o = _accessor.offset(VT.justF64); return o == 0 ? 0.0 : _accessor.readBuffer(of: Double.self, at: o) } - public var maybeF64: Double? { let o = _accessor.offset(VT.maybeF64); return o == 0 ? nil : _accessor.readBuffer(of: Double.self, at: o) } - public var defaultF64: Double { let o = _accessor.offset(VT.defaultF64); return o == 0 ? 42.0 : _accessor.readBuffer(of: Double.self, at: o) } - public var justBool: Bool { let o = _accessor.offset(VT.justBool); return o == 0 ? false : _accessor.readBuffer(of: Bool.self, at: o) } - public var maybeBool: Bool? { let o = _accessor.offset(VT.maybeBool); return o == 0 ? nil : _accessor.readBuffer(of: Bool.self, at: o) } - public var defaultBool: Bool { let o = _accessor.offset(VT.defaultBool); return o == 0 ? true : _accessor.readBuffer(of: Bool.self, at: o) } - public var justEnum: optional_scalars_OptionalByte { let o = _accessor.offset(VT.justEnum); return o == 0 ? .none_ : optional_scalars_OptionalByte(rawValue: _accessor.readBuffer(of: Int8.self, at: o)) ?? .none_ } - public var maybeEnum: optional_scalars_OptionalByte? { let o = _accessor.offset(VT.maybeEnum); return o == 0 ? nil : optional_scalars_OptionalByte(rawValue: _accessor.readBuffer(of: Int8.self, at: o)) ?? nil } - public var defaultEnum: optional_scalars_OptionalByte { let o = _accessor.offset(VT.defaultEnum); return o == 0 ? .one : optional_scalars_OptionalByte(rawValue: _accessor.readBuffer(of: Int8.self, at: o)) ?? .one } + public var justI8: Int8 { let o = _accessor.offset(VTOFFSET.justI8.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int8.self, at: o) } + public var maybeI8: Int8? { let o = _accessor.offset(VTOFFSET.maybeI8.v); return o == 0 ? nil : _accessor.readBuffer(of: Int8.self, at: o) } + public var defaultI8: Int8 { let o = _accessor.offset(VTOFFSET.defaultI8.v); return o == 0 ? 42 : _accessor.readBuffer(of: Int8.self, at: o) } + public var justU8: UInt8 { let o = _accessor.offset(VTOFFSET.justU8.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt8.self, at: o) } + public var maybeU8: UInt8? { let o = _accessor.offset(VTOFFSET.maybeU8.v); return o == 0 ? nil : _accessor.readBuffer(of: UInt8.self, at: o) } + public var defaultU8: UInt8 { let o = _accessor.offset(VTOFFSET.defaultU8.v); return o == 0 ? 42 : _accessor.readBuffer(of: UInt8.self, at: o) } + public var justI16: Int16 { let o = _accessor.offset(VTOFFSET.justI16.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int16.self, at: o) } + public var maybeI16: Int16? { let o = _accessor.offset(VTOFFSET.maybeI16.v); return o == 0 ? nil : _accessor.readBuffer(of: Int16.self, at: o) } + public var defaultI16: Int16 { let o = _accessor.offset(VTOFFSET.defaultI16.v); return o == 0 ? 42 : _accessor.readBuffer(of: Int16.self, at: o) } + public var justU16: UInt16 { let o = _accessor.offset(VTOFFSET.justU16.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt16.self, at: o) } + public var maybeU16: UInt16? { let o = _accessor.offset(VTOFFSET.maybeU16.v); return o == 0 ? nil : _accessor.readBuffer(of: UInt16.self, at: o) } + public var defaultU16: UInt16 { let o = _accessor.offset(VTOFFSET.defaultU16.v); return o == 0 ? 42 : _accessor.readBuffer(of: UInt16.self, at: o) } + public var justI32: Int32 { let o = _accessor.offset(VTOFFSET.justI32.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int32.self, at: o) } + public var maybeI32: Int32? { let o = _accessor.offset(VTOFFSET.maybeI32.v); return o == 0 ? nil : _accessor.readBuffer(of: Int32.self, at: o) } + public var defaultI32: Int32 { let o = _accessor.offset(VTOFFSET.defaultI32.v); return o == 0 ? 42 : _accessor.readBuffer(of: Int32.self, at: o) } + public var justU32: UInt32 { let o = _accessor.offset(VTOFFSET.justU32.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt32.self, at: o) } + public var maybeU32: UInt32? { let o = _accessor.offset(VTOFFSET.maybeU32.v); return o == 0 ? nil : _accessor.readBuffer(of: UInt32.self, at: o) } + public var defaultU32: UInt32 { let o = _accessor.offset(VTOFFSET.defaultU32.v); return o == 0 ? 42 : _accessor.readBuffer(of: UInt32.self, at: o) } + public var justI64: Int64 { let o = _accessor.offset(VTOFFSET.justI64.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int64.self, at: o) } + public var maybeI64: Int64? { let o = _accessor.offset(VTOFFSET.maybeI64.v); return o == 0 ? nil : _accessor.readBuffer(of: Int64.self, at: o) } + public var defaultI64: Int64 { let o = _accessor.offset(VTOFFSET.defaultI64.v); return o == 0 ? 42 : _accessor.readBuffer(of: Int64.self, at: o) } + public var justU64: UInt64 { let o = _accessor.offset(VTOFFSET.justU64.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt64.self, at: o) } + public var maybeU64: UInt64? { let o = _accessor.offset(VTOFFSET.maybeU64.v); return o == 0 ? nil : _accessor.readBuffer(of: UInt64.self, at: o) } + public var defaultU64: UInt64 { let o = _accessor.offset(VTOFFSET.defaultU64.v); return o == 0 ? 42 : _accessor.readBuffer(of: UInt64.self, at: o) } + public var justF32: Float32 { let o = _accessor.offset(VTOFFSET.justF32.v); return o == 0 ? 0.0 : _accessor.readBuffer(of: Float32.self, at: o) } + public var maybeF32: Float32? { let o = _accessor.offset(VTOFFSET.maybeF32.v); return o == 0 ? nil : _accessor.readBuffer(of: Float32.self, at: o) } + public var defaultF32: Float32 { let o = _accessor.offset(VTOFFSET.defaultF32.v); return o == 0 ? 42.0 : _accessor.readBuffer(of: Float32.self, at: o) } + public var justF64: Double { let o = _accessor.offset(VTOFFSET.justF64.v); return o == 0 ? 0.0 : _accessor.readBuffer(of: Double.self, at: o) } + public var maybeF64: Double? { let o = _accessor.offset(VTOFFSET.maybeF64.v); return o == 0 ? nil : _accessor.readBuffer(of: Double.self, at: o) } + public var defaultF64: Double { let o = _accessor.offset(VTOFFSET.defaultF64.v); return o == 0 ? 42.0 : _accessor.readBuffer(of: Double.self, at: o) } + public var justBool: Bool { let o = _accessor.offset(VTOFFSET.justBool.v); return o == 0 ? false : _accessor.readBuffer(of: Bool.self, at: o) } + public var maybeBool: Bool? { let o = _accessor.offset(VTOFFSET.maybeBool.v); return o == 0 ? nil : _accessor.readBuffer(of: Bool.self, at: o) } + public var defaultBool: Bool { let o = _accessor.offset(VTOFFSET.defaultBool.v); return o == 0 ? true : _accessor.readBuffer(of: Bool.self, at: o) } + public var justEnum: optional_scalars_OptionalByte { let o = _accessor.offset(VTOFFSET.justEnum.v); return o == 0 ? .none_ : optional_scalars_OptionalByte(rawValue: _accessor.readBuffer(of: Int8.self, at: o)) ?? .none_ } + public var maybeEnum: optional_scalars_OptionalByte? { let o = _accessor.offset(VTOFFSET.maybeEnum.v); return o == 0 ? nil : optional_scalars_OptionalByte(rawValue: _accessor.readBuffer(of: Int8.self, at: o)) ?? nil } + public var defaultEnum: optional_scalars_OptionalByte { let o = _accessor.offset(VTOFFSET.defaultEnum.v); return o == 0 ? .one : optional_scalars_OptionalByte(rawValue: _accessor.readBuffer(of: Int8.self, at: o)) ?? .one } public static func startScalarStuff(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 36) } - public static func add(justI8: Int8, _ fbb: inout FlatBufferBuilder) { fbb.add(element: justI8, def: 0, at: VT.justI8) } - public static func add(maybeI8: Int8?, _ fbb: inout FlatBufferBuilder) { fbb.add(element: maybeI8, at: VT.maybeI8) } - public static func add(defaultI8: Int8, _ fbb: inout FlatBufferBuilder) { fbb.add(element: defaultI8, def: 42, at: VT.defaultI8) } - public static func add(justU8: UInt8, _ fbb: inout FlatBufferBuilder) { fbb.add(element: justU8, def: 0, at: VT.justU8) } - public static func add(maybeU8: UInt8?, _ fbb: inout FlatBufferBuilder) { fbb.add(element: maybeU8, at: VT.maybeU8) } - public static func add(defaultU8: UInt8, _ fbb: inout FlatBufferBuilder) { fbb.add(element: defaultU8, def: 42, at: VT.defaultU8) } - public static func add(justI16: Int16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: justI16, def: 0, at: VT.justI16) } - public static func add(maybeI16: Int16?, _ fbb: inout FlatBufferBuilder) { fbb.add(element: maybeI16, at: VT.maybeI16) } - public static func add(defaultI16: Int16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: defaultI16, def: 42, at: VT.defaultI16) } - public static func add(justU16: UInt16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: justU16, def: 0, at: VT.justU16) } - public static func add(maybeU16: UInt16?, _ fbb: inout FlatBufferBuilder) { fbb.add(element: maybeU16, at: VT.maybeU16) } - public static func add(defaultU16: UInt16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: defaultU16, def: 42, at: VT.defaultU16) } - public static func add(justI32: Int32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: justI32, def: 0, at: VT.justI32) } - public static func add(maybeI32: Int32?, _ fbb: inout FlatBufferBuilder) { fbb.add(element: maybeI32, at: VT.maybeI32) } - public static func add(defaultI32: Int32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: defaultI32, def: 42, at: VT.defaultI32) } - public static func add(justU32: UInt32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: justU32, def: 0, at: VT.justU32) } - public static func add(maybeU32: UInt32?, _ fbb: inout FlatBufferBuilder) { fbb.add(element: maybeU32, at: VT.maybeU32) } - public static func add(defaultU32: UInt32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: defaultU32, def: 42, at: VT.defaultU32) } - public static func add(justI64: Int64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: justI64, def: 0, at: VT.justI64) } - public static func add(maybeI64: Int64?, _ fbb: inout FlatBufferBuilder) { fbb.add(element: maybeI64, at: VT.maybeI64) } - public static func add(defaultI64: Int64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: defaultI64, def: 42, at: VT.defaultI64) } - public static func add(justU64: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: justU64, def: 0, at: VT.justU64) } - public static func add(maybeU64: UInt64?, _ fbb: inout FlatBufferBuilder) { fbb.add(element: maybeU64, at: VT.maybeU64) } - public static func add(defaultU64: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: defaultU64, def: 42, at: VT.defaultU64) } - public static func add(justF32: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: justF32, def: 0.0, at: VT.justF32) } - public static func add(maybeF32: Float32?, _ fbb: inout FlatBufferBuilder) { fbb.add(element: maybeF32, at: VT.maybeF32) } - public static func add(defaultF32: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: defaultF32, def: 42.0, at: VT.defaultF32) } - public static func add(justF64: Double, _ fbb: inout FlatBufferBuilder) { fbb.add(element: justF64, def: 0.0, at: VT.justF64) } - public static func add(maybeF64: Double?, _ fbb: inout FlatBufferBuilder) { fbb.add(element: maybeF64, at: VT.maybeF64) } - public static func add(defaultF64: Double, _ fbb: inout FlatBufferBuilder) { fbb.add(element: defaultF64, def: 42.0, at: VT.defaultF64) } + public static func add(justI8: Int8, _ fbb: inout FlatBufferBuilder) { fbb.add(element: justI8, def: 0, at: VTOFFSET.justI8.p) } + public static func add(maybeI8: Int8?, _ fbb: inout FlatBufferBuilder) { fbb.add(element: maybeI8, at: VTOFFSET.maybeI8.p) } + public static func add(defaultI8: Int8, _ fbb: inout FlatBufferBuilder) { fbb.add(element: defaultI8, def: 42, at: VTOFFSET.defaultI8.p) } + public static func add(justU8: UInt8, _ fbb: inout FlatBufferBuilder) { fbb.add(element: justU8, def: 0, at: VTOFFSET.justU8.p) } + public static func add(maybeU8: UInt8?, _ fbb: inout FlatBufferBuilder) { fbb.add(element: maybeU8, at: VTOFFSET.maybeU8.p) } + public static func add(defaultU8: UInt8, _ fbb: inout FlatBufferBuilder) { fbb.add(element: defaultU8, def: 42, at: VTOFFSET.defaultU8.p) } + public static func add(justI16: Int16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: justI16, def: 0, at: VTOFFSET.justI16.p) } + public static func add(maybeI16: Int16?, _ fbb: inout FlatBufferBuilder) { fbb.add(element: maybeI16, at: VTOFFSET.maybeI16.p) } + public static func add(defaultI16: Int16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: defaultI16, def: 42, at: VTOFFSET.defaultI16.p) } + public static func add(justU16: UInt16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: justU16, def: 0, at: VTOFFSET.justU16.p) } + public static func add(maybeU16: UInt16?, _ fbb: inout FlatBufferBuilder) { fbb.add(element: maybeU16, at: VTOFFSET.maybeU16.p) } + public static func add(defaultU16: UInt16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: defaultU16, def: 42, at: VTOFFSET.defaultU16.p) } + public static func add(justI32: Int32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: justI32, def: 0, at: VTOFFSET.justI32.p) } + public static func add(maybeI32: Int32?, _ fbb: inout FlatBufferBuilder) { fbb.add(element: maybeI32, at: VTOFFSET.maybeI32.p) } + public static func add(defaultI32: Int32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: defaultI32, def: 42, at: VTOFFSET.defaultI32.p) } + public static func add(justU32: UInt32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: justU32, def: 0, at: VTOFFSET.justU32.p) } + public static func add(maybeU32: UInt32?, _ fbb: inout FlatBufferBuilder) { fbb.add(element: maybeU32, at: VTOFFSET.maybeU32.p) } + public static func add(defaultU32: UInt32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: defaultU32, def: 42, at: VTOFFSET.defaultU32.p) } + public static func add(justI64: Int64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: justI64, def: 0, at: VTOFFSET.justI64.p) } + public static func add(maybeI64: Int64?, _ fbb: inout FlatBufferBuilder) { fbb.add(element: maybeI64, at: VTOFFSET.maybeI64.p) } + public static func add(defaultI64: Int64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: defaultI64, def: 42, at: VTOFFSET.defaultI64.p) } + public static func add(justU64: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: justU64, def: 0, at: VTOFFSET.justU64.p) } + public static func add(maybeU64: UInt64?, _ fbb: inout FlatBufferBuilder) { fbb.add(element: maybeU64, at: VTOFFSET.maybeU64.p) } + public static func add(defaultU64: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: defaultU64, def: 42, at: VTOFFSET.defaultU64.p) } + public static func add(justF32: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: justF32, def: 0.0, at: VTOFFSET.justF32.p) } + public static func add(maybeF32: Float32?, _ fbb: inout FlatBufferBuilder) { fbb.add(element: maybeF32, at: VTOFFSET.maybeF32.p) } + public static func add(defaultF32: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: defaultF32, def: 42.0, at: VTOFFSET.defaultF32.p) } + public static func add(justF64: Double, _ fbb: inout FlatBufferBuilder) { fbb.add(element: justF64, def: 0.0, at: VTOFFSET.justF64.p) } + public static func add(maybeF64: Double?, _ fbb: inout FlatBufferBuilder) { fbb.add(element: maybeF64, at: VTOFFSET.maybeF64.p) } + public static func add(defaultF64: Double, _ fbb: inout FlatBufferBuilder) { fbb.add(element: defaultF64, def: 42.0, at: VTOFFSET.defaultF64.p) } public static func add(justBool: Bool, _ fbb: inout FlatBufferBuilder) { fbb.add(element: justBool, def: false, - at: VT.justBool) } - public static func add(maybeBool: Bool?, _ fbb: inout FlatBufferBuilder) { fbb.add(element: maybeBool, at: VT.maybeBool) } + at: VTOFFSET.justBool.p) } + public static func add(maybeBool: Bool?, _ fbb: inout FlatBufferBuilder) { fbb.add(element: maybeBool, at: VTOFFSET.maybeBool.p) } public static func add(defaultBool: Bool, _ fbb: inout FlatBufferBuilder) { fbb.add(element: defaultBool, def: true, - at: VT.defaultBool) } - public static func add(justEnum: optional_scalars_OptionalByte, _ fbb: inout FlatBufferBuilder) { fbb.add(element: justEnum.rawValue, def: 0, at: VT.justEnum) } - public static func add(maybeEnum: optional_scalars_OptionalByte?, _ fbb: inout FlatBufferBuilder) { fbb.add(element: maybeEnum?.rawValue, at: VT.maybeEnum) } - public static func add(defaultEnum: optional_scalars_OptionalByte, _ fbb: inout FlatBufferBuilder) { fbb.add(element: defaultEnum.rawValue, def: 1, at: VT.defaultEnum) } + at: VTOFFSET.defaultBool.p) } + public static func add(justEnum: optional_scalars_OptionalByte, _ fbb: inout FlatBufferBuilder) { fbb.add(element: justEnum.rawValue, def: 0, at: VTOFFSET.justEnum.p) } + public static func add(maybeEnum: optional_scalars_OptionalByte?, _ fbb: inout FlatBufferBuilder) { fbb.add(element: maybeEnum?.rawValue, at: VTOFFSET.maybeEnum.p) } + public static func add(defaultEnum: optional_scalars_OptionalByte, _ fbb: inout FlatBufferBuilder) { fbb.add(element: defaultEnum.rawValue, def: 1, at: VTOFFSET.defaultEnum.p) } public static func endScalarStuff(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } public static func createScalarStuff( _ fbb: inout FlatBufferBuilder, @@ -238,47 +240,48 @@ public struct optional_scalars_ScalarStuff: FlatBufferVerifiableTable, Flatbuffe public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { var _v = try verifier.visitTable(at: position) - try _v.visit(field: VT.justI8, fieldName: "justI8", required: false, type: Int8.self) - try _v.visit(field: VT.maybeI8, fieldName: "maybeI8", required: false, type: Int8.self) - try _v.visit(field: VT.defaultI8, fieldName: "defaultI8", required: false, type: Int8.self) - try _v.visit(field: VT.justU8, fieldName: "justU8", required: false, type: UInt8.self) - try _v.visit(field: VT.maybeU8, fieldName: "maybeU8", required: false, type: UInt8.self) - try _v.visit(field: VT.defaultU8, fieldName: "defaultU8", required: false, type: UInt8.self) - try _v.visit(field: VT.justI16, fieldName: "justI16", required: false, type: Int16.self) - try _v.visit(field: VT.maybeI16, fieldName: "maybeI16", required: false, type: Int16.self) - try _v.visit(field: VT.defaultI16, fieldName: "defaultI16", required: false, type: Int16.self) - try _v.visit(field: VT.justU16, fieldName: "justU16", required: false, type: UInt16.self) - try _v.visit(field: VT.maybeU16, fieldName: "maybeU16", required: false, type: UInt16.self) - try _v.visit(field: VT.defaultU16, fieldName: "defaultU16", required: false, type: UInt16.self) - try _v.visit(field: VT.justI32, fieldName: "justI32", required: false, type: Int32.self) - try _v.visit(field: VT.maybeI32, fieldName: "maybeI32", required: false, type: Int32.self) - try _v.visit(field: VT.defaultI32, fieldName: "defaultI32", required: false, type: Int32.self) - try _v.visit(field: VT.justU32, fieldName: "justU32", required: false, type: UInt32.self) - try _v.visit(field: VT.maybeU32, fieldName: "maybeU32", required: false, type: UInt32.self) - try _v.visit(field: VT.defaultU32, fieldName: "defaultU32", required: false, type: UInt32.self) - try _v.visit(field: VT.justI64, fieldName: "justI64", required: false, type: Int64.self) - try _v.visit(field: VT.maybeI64, fieldName: "maybeI64", required: false, type: Int64.self) - try _v.visit(field: VT.defaultI64, fieldName: "defaultI64", required: false, type: Int64.self) - try _v.visit(field: VT.justU64, fieldName: "justU64", required: false, type: UInt64.self) - try _v.visit(field: VT.maybeU64, fieldName: "maybeU64", required: false, type: UInt64.self) - try _v.visit(field: VT.defaultU64, fieldName: "defaultU64", required: false, type: UInt64.self) - try _v.visit(field: VT.justF32, fieldName: "justF32", required: false, type: Float32.self) - try _v.visit(field: VT.maybeF32, fieldName: "maybeF32", required: false, type: Float32.self) - try _v.visit(field: VT.defaultF32, fieldName: "defaultF32", required: false, type: Float32.self) - try _v.visit(field: VT.justF64, fieldName: "justF64", required: false, type: Double.self) - try _v.visit(field: VT.maybeF64, fieldName: "maybeF64", required: false, type: Double.self) - try _v.visit(field: VT.defaultF64, fieldName: "defaultF64", required: false, type: Double.self) - try _v.visit(field: VT.justBool, fieldName: "justBool", required: false, type: Bool.self) - try _v.visit(field: VT.maybeBool, fieldName: "maybeBool", required: false, type: Bool.self) - try _v.visit(field: VT.defaultBool, fieldName: "defaultBool", required: false, type: Bool.self) - try _v.visit(field: VT.justEnum, fieldName: "justEnum", required: false, type: optional_scalars_OptionalByte.self) - try _v.visit(field: VT.maybeEnum, fieldName: "maybeEnum", required: false, type: optional_scalars_OptionalByte.self) - try _v.visit(field: VT.defaultEnum, fieldName: "defaultEnum", required: false, type: optional_scalars_OptionalByte.self) + try _v.visit(field: VTOFFSET.justI8.p, fieldName: "justI8", required: false, type: Int8.self) + try _v.visit(field: VTOFFSET.maybeI8.p, fieldName: "maybeI8", required: false, type: Int8.self) + try _v.visit(field: VTOFFSET.defaultI8.p, fieldName: "defaultI8", required: false, type: Int8.self) + try _v.visit(field: VTOFFSET.justU8.p, fieldName: "justU8", required: false, type: UInt8.self) + try _v.visit(field: VTOFFSET.maybeU8.p, fieldName: "maybeU8", required: false, type: UInt8.self) + try _v.visit(field: VTOFFSET.defaultU8.p, fieldName: "defaultU8", required: false, type: UInt8.self) + try _v.visit(field: VTOFFSET.justI16.p, fieldName: "justI16", required: false, type: Int16.self) + try _v.visit(field: VTOFFSET.maybeI16.p, fieldName: "maybeI16", required: false, type: Int16.self) + try _v.visit(field: VTOFFSET.defaultI16.p, fieldName: "defaultI16", required: false, type: Int16.self) + try _v.visit(field: VTOFFSET.justU16.p, fieldName: "justU16", required: false, type: UInt16.self) + try _v.visit(field: VTOFFSET.maybeU16.p, fieldName: "maybeU16", required: false, type: UInt16.self) + try _v.visit(field: VTOFFSET.defaultU16.p, fieldName: "defaultU16", required: false, type: UInt16.self) + try _v.visit(field: VTOFFSET.justI32.p, fieldName: "justI32", required: false, type: Int32.self) + try _v.visit(field: VTOFFSET.maybeI32.p, fieldName: "maybeI32", required: false, type: Int32.self) + try _v.visit(field: VTOFFSET.defaultI32.p, fieldName: "defaultI32", required: false, type: Int32.self) + try _v.visit(field: VTOFFSET.justU32.p, fieldName: "justU32", required: false, type: UInt32.self) + try _v.visit(field: VTOFFSET.maybeU32.p, fieldName: "maybeU32", required: false, type: UInt32.self) + try _v.visit(field: VTOFFSET.defaultU32.p, fieldName: "defaultU32", required: false, type: UInt32.self) + try _v.visit(field: VTOFFSET.justI64.p, fieldName: "justI64", required: false, type: Int64.self) + try _v.visit(field: VTOFFSET.maybeI64.p, fieldName: "maybeI64", required: false, type: Int64.self) + try _v.visit(field: VTOFFSET.defaultI64.p, fieldName: "defaultI64", required: false, type: Int64.self) + try _v.visit(field: VTOFFSET.justU64.p, fieldName: "justU64", required: false, type: UInt64.self) + try _v.visit(field: VTOFFSET.maybeU64.p, fieldName: "maybeU64", required: false, type: UInt64.self) + try _v.visit(field: VTOFFSET.defaultU64.p, fieldName: "defaultU64", required: false, type: UInt64.self) + try _v.visit(field: VTOFFSET.justF32.p, fieldName: "justF32", required: false, type: Float32.self) + try _v.visit(field: VTOFFSET.maybeF32.p, fieldName: "maybeF32", required: false, type: Float32.self) + try _v.visit(field: VTOFFSET.defaultF32.p, fieldName: "defaultF32", required: false, type: Float32.self) + try _v.visit(field: VTOFFSET.justF64.p, fieldName: "justF64", required: false, type: Double.self) + try _v.visit(field: VTOFFSET.maybeF64.p, fieldName: "maybeF64", required: false, type: Double.self) + try _v.visit(field: VTOFFSET.defaultF64.p, fieldName: "defaultF64", required: false, type: Double.self) + try _v.visit(field: VTOFFSET.justBool.p, fieldName: "justBool", required: false, type: Bool.self) + try _v.visit(field: VTOFFSET.maybeBool.p, fieldName: "maybeBool", required: false, type: Bool.self) + try _v.visit(field: VTOFFSET.defaultBool.p, fieldName: "defaultBool", required: false, type: Bool.self) + try _v.visit(field: VTOFFSET.justEnum.p, fieldName: "justEnum", required: false, type: optional_scalars_OptionalByte.self) + try _v.visit(field: VTOFFSET.maybeEnum.p, fieldName: "maybeEnum", required: false, type: optional_scalars_OptionalByte.self) + try _v.visit(field: VTOFFSET.defaultEnum.p, fieldName: "defaultEnum", required: false, type: optional_scalars_OptionalByte.self) _v.finish() } } extension optional_scalars_ScalarStuff: Encodable { + enum CodingKeys: String, CodingKey { case justI8 = "just_i8" case maybeI8 = "maybe_i8" @@ -317,7 +320,6 @@ extension optional_scalars_ScalarStuff: Encodable { case maybeEnum = "maybe_enum" case defaultEnum = "default_enum" } - public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) if justI8 != 0 { diff --git a/tests/swift/Tests/Flatbuffers/union_vector_generated.swift b/tests/swift/Tests/Flatbuffers/union_vector_generated.swift index fd12ffeca..a0e3a1e1e 100644 --- a/tests/swift/Tests/Flatbuffers/union_vector_generated.swift +++ b/tests/swift/Tests/Flatbuffers/union_vector_generated.swift @@ -152,10 +152,10 @@ public struct Rapunzel: NativeStruct, FlatbuffersVectorInitializable, Verifiable } extension Rapunzel: Encodable { + enum CodingKeys: String, CodingKey { case hairLength = "hair_length" } - public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) if hairLength != 0 { @@ -218,10 +218,10 @@ public struct BookReader: NativeStruct, FlatbuffersVectorInitializable, Verifiab } extension BookReader: Encodable { + enum CodingKeys: String, CodingKey { case booksRead = "books_read" } - public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) if booksRead != 0 { @@ -284,10 +284,10 @@ public struct FallingTub: NativeStruct, FlatbuffersVectorInitializable, Verifiab } extension FallingTub: Encodable { + enum CodingKeys: String, CodingKey { case weight = "weight" } - public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) if weight != 0 { @@ -320,7 +320,7 @@ public struct FallingTub_Mutable: FlatBufferStruct, FlatbuffersVectorInitializab } } -public struct Attacker: FlatBufferVerifiableTable, FlatbuffersVectorInitializable, ObjectAPIPacker { +public struct Attacker: FlatBufferTable, FlatbuffersVectorInitializable, Verifiable, ObjectAPIPacker { static func validateVersion() { FlatBuffersVersion_25_12_19() } public var __buffer: ByteBuffer! { return _accessor.bb } @@ -331,14 +331,16 @@ public struct Attacker: FlatBufferVerifiableTable, FlatbuffersVectorInitializabl private init(_ t: Table) { _accessor = t } public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } - private struct VT { - static let swordAttackDamage: VOffset = 4 + private enum VTOFFSET: VOffset { + case swordAttackDamage = 4 + var v: Int32 { Int32(self.rawValue) } + var p: VOffset { self.rawValue } } - public var swordAttackDamage: Int32 { let o = _accessor.offset(VT.swordAttackDamage); return o == 0 ? 0 : _accessor.readBuffer(of: Int32.self, at: o) } - @discardableResult public func mutate(swordAttackDamage: Int32) -> Bool {let o = _accessor.offset(VT.swordAttackDamage); return _accessor.mutate(swordAttackDamage, index: o) } + public var swordAttackDamage: Int32 { let o = _accessor.offset(VTOFFSET.swordAttackDamage.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int32.self, at: o) } + @discardableResult public func mutate(swordAttackDamage: Int32) -> Bool {let o = _accessor.offset(VTOFFSET.swordAttackDamage.v); return _accessor.mutate(swordAttackDamage, index: o) } public static func startAttacker(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) } - public static func add(swordAttackDamage: Int32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: swordAttackDamage, def: 0, at: VT.swordAttackDamage) } + public static func add(swordAttackDamage: Int32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: swordAttackDamage, def: 0, at: VTOFFSET.swordAttackDamage.p) } public static func endAttacker(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } public static func createAttacker( _ fbb: inout FlatBufferBuilder, @@ -365,16 +367,16 @@ public struct Attacker: FlatBufferVerifiableTable, FlatbuffersVectorInitializabl public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { var _v = try verifier.visitTable(at: position) - try _v.visit(field: VT.swordAttackDamage, fieldName: "swordAttackDamage", required: false, type: Int32.self) + try _v.visit(field: VTOFFSET.swordAttackDamage.p, fieldName: "swordAttackDamage", required: false, type: Int32.self) _v.finish() } } extension Attacker: Encodable { + enum CodingKeys: String, CodingKey { case swordAttackDamage = "sword_attack_damage" } - public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) if swordAttackDamage != 0 { @@ -398,7 +400,7 @@ public class AttackerT: NativeObject { public func serialize() -> ByteBuffer { return serialize(type: Attacker.self) } } -public struct HandFan: FlatBufferVerifiableTable, FlatbuffersVectorInitializable, ObjectAPIPacker { +public struct HandFan: FlatBufferTable, FlatbuffersVectorInitializable, Verifiable, ObjectAPIPacker { static func validateVersion() { FlatBuffersVersion_25_12_19() } public var __buffer: ByteBuffer! { return _accessor.bb } @@ -409,14 +411,16 @@ public struct HandFan: FlatBufferVerifiableTable, FlatbuffersVectorInitializable private init(_ t: Table) { _accessor = t } public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } - private struct VT { - static let length: VOffset = 4 + private enum VTOFFSET: VOffset { + case length = 4 + var v: Int32 { Int32(self.rawValue) } + var p: VOffset { self.rawValue } } - public var length: Int32 { let o = _accessor.offset(VT.length); return o == 0 ? 0 : _accessor.readBuffer(of: Int32.self, at: o) } - @discardableResult public func mutate(length: Int32) -> Bool {let o = _accessor.offset(VT.length); return _accessor.mutate(length, index: o) } + public var length: Int32 { let o = _accessor.offset(VTOFFSET.length.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int32.self, at: o) } + @discardableResult public func mutate(length: Int32) -> Bool {let o = _accessor.offset(VTOFFSET.length.v); return _accessor.mutate(length, index: o) } public static func startHandFan(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) } - public static func add(length: Int32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: length, def: 0, at: VT.length) } + public static func add(length: Int32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: length, def: 0, at: VTOFFSET.length.p) } public static func endHandFan(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } public static func createHandFan( _ fbb: inout FlatBufferBuilder, @@ -443,16 +447,16 @@ public struct HandFan: FlatBufferVerifiableTable, FlatbuffersVectorInitializable public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { var _v = try verifier.visitTable(at: position) - try _v.visit(field: VT.length, fieldName: "length", required: false, type: Int32.self) + try _v.visit(field: VTOFFSET.length.p, fieldName: "length", required: false, type: Int32.self) _v.finish() } } extension HandFan: Encodable { + enum CodingKeys: String, CodingKey { case length = "length" } - public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) if length != 0 { @@ -476,7 +480,7 @@ public class HandFanT: NativeObject { public func serialize() -> ByteBuffer { return serialize(type: HandFan.self) } } -public struct Movie: FlatBufferVerifiableTable, FlatbuffersVectorInitializable, ObjectAPIPacker { +public struct Movie: FlatBufferTable, FlatbuffersVectorInitializable, Verifiable, ObjectAPIPacker { static func validateVersion() { FlatBuffersVersion_25_12_19() } public var __buffer: ByteBuffer! { return _accessor.bb } @@ -487,23 +491,25 @@ public struct Movie: FlatBufferVerifiableTable, FlatbuffersVectorInitializable, private init(_ t: Table) { _accessor = t } public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } - private struct VT { - static let mainCharacterType: VOffset = 4 - static let mainCharacter: VOffset = 6 - static let charactersType: VOffset = 8 - static let characters: VOffset = 10 + private enum VTOFFSET: VOffset { + case mainCharacterType = 4 + case mainCharacter = 6 + case charactersType = 8 + case characters = 10 + var v: Int32 { Int32(self.rawValue) } + var p: VOffset { self.rawValue } } - public var mainCharacterType: Character { let o = _accessor.offset(VT.mainCharacterType); return o == 0 ? .none_ : Character(rawValue: _accessor.readBuffer(of: UInt8.self, at: o)) ?? .none_ } - public func mainCharacter(type: T.Type) -> T? { let o = _accessor.offset(VT.mainCharacter); return o == 0 ? nil : _accessor.union(o) } - public var charactersType: FlatbufferVector { return _accessor.vector(at: VT.charactersType, byteSize: 1) } - public var characters: UnionFlatbufferVector { return _accessor.unionVector(at: VT.characters, byteSize: 4) } - public func characters(at index: Int32, type: T.Type) -> T? { let o = _accessor.offset(VT.characters); return o == 0 ? nil : _accessor.directUnion(_accessor.vector(at: o) + index * 4) } + public var mainCharacterType: Character { let o = _accessor.offset(VTOFFSET.mainCharacterType.v); return o == 0 ? .none_ : Character(rawValue: _accessor.readBuffer(of: UInt8.self, at: o)) ?? .none_ } + public func mainCharacter(type: T.Type) -> T? { let o = _accessor.offset(VTOFFSET.mainCharacter.v); return o == 0 ? nil : _accessor.union(o) } + public var charactersType: FlatbufferVector { return _accessor.vector(at: VTOFFSET.charactersType.v, byteSize: 1) } + public var characters: UnionFlatbufferVector { return _accessor.unionVector(at: VTOFFSET.characters.v, byteSize: 4) } + public func characters(at index: Int32, type: T.Type) -> T? { let o = _accessor.offset(VTOFFSET.characters.v); return o == 0 ? nil : _accessor.directUnion(_accessor.vector(at: o) + index * 4) } public static func startMovie(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 4) } - public static func add(mainCharacterType: Character, _ fbb: inout FlatBufferBuilder) { fbb.add(element: mainCharacterType.rawValue, def: 0, at: VT.mainCharacterType) } - public static func add(mainCharacter: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: mainCharacter, at: VT.mainCharacter) } - public static func addVectorOf(charactersType: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: charactersType, at: VT.charactersType) } - public static func addVectorOf(characters: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: characters, at: VT.characters) } + public static func add(mainCharacterType: Character, _ fbb: inout FlatBufferBuilder) { fbb.add(element: mainCharacterType.rawValue, def: 0, at: VTOFFSET.mainCharacterType.p) } + public static func add(mainCharacter: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: mainCharacter, at: VTOFFSET.mainCharacter.p) } + public static func addVectorOf(charactersType: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: charactersType, at: VTOFFSET.charactersType.p) } + public static func addVectorOf(characters: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: characters, at: VTOFFSET.characters.p) } public static func endMovie(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } public static func createMovie( _ fbb: inout FlatBufferBuilder, @@ -550,7 +556,7 @@ public struct Movie: FlatBufferVerifiableTable, FlatbuffersVectorInitializable, public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { var _v = try verifier.visitTable(at: position) - try _v.visit(unionKey: VT.mainCharacterType, unionField: VT.mainCharacter, unionKeyName: "mainCharacterType", fieldName: "mainCharacter", required: false, completion: { (verifier, key: Character, pos) in + try _v.visit(unionKey: VTOFFSET.mainCharacterType.p, unionField: VTOFFSET.mainCharacter.p, unionKeyName: "mainCharacterType", fieldName: "mainCharacter", required: false, completion: { (verifier, key: Character, pos) in switch key { case .none_: break // NOTE - SWIFT doesnt support none @@ -568,7 +574,7 @@ public struct Movie: FlatBufferVerifiableTable, FlatbuffersVectorInitializable, try ForwardOffset.verify(&verifier, at: pos, of: String.self) } }) - try _v.visitUnionVector(unionKey: VT.charactersType, unionField: VT.characters, unionKeyName: "charactersType", fieldName: "characters", required: false, completion: { (verifier, key: Character, pos) in + try _v.visitUnionVector(unionKey: VTOFFSET.charactersType.p, unionField: VTOFFSET.characters.p, unionKeyName: "charactersType", fieldName: "characters", required: false, completion: { (verifier, key: Character, pos) in switch key { case .none_: break // NOTE - SWIFT doesnt support none @@ -591,13 +597,13 @@ public struct Movie: FlatBufferVerifiableTable, FlatbuffersVectorInitializable, } extension Movie: Encodable { + enum CodingKeys: String, CodingKey { case mainCharacterType = "main_character_type" case mainCharacter = "main_character" case charactersType = "characters_type" case characters = "characters" } - public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) if mainCharacterType != .none_ { diff --git a/tests/swift/Tests/Flatbuffers/vector_has_test_generated.swift b/tests/swift/Tests/Flatbuffers/vector_has_test_generated.swift index 2466703e4..0cdec52de 100644 --- a/tests/swift/Tests/Flatbuffers/vector_has_test_generated.swift +++ b/tests/swift/Tests/Flatbuffers/vector_has_test_generated.swift @@ -8,7 +8,7 @@ import Common import FlatBuffers -public struct Swift_Tests_Vectors: FlatBufferVerifiableTable, FlatbuffersVectorInitializable { +public struct Swift_Tests_Vectors: FlatBufferTable, FlatbuffersVectorInitializable, Verifiable { static func validateVersion() { FlatBuffersVersion_25_12_19() } public var __buffer: ByteBuffer! { return _accessor.bb } @@ -17,22 +17,24 @@ public struct Swift_Tests_Vectors: FlatBufferVerifiableTable, FlatbuffersVectorI private init(_ t: Table) { _accessor = t } public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } - private struct VT { - static let none_: VOffset = 4 - static let empty: VOffset = 6 - static let array: VOffset = 8 + private enum VTOFFSET: VOffset { + case none_ = 4 + case empty = 6 + case array = 8 + var v: Int32 { Int32(self.rawValue) } + var p: VOffset { self.rawValue } } - public var none_: FlatbufferVector { return _accessor.vector(at: VT.none_, byteSize: 8) } - public func withUnsafePointerToNone(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VT.none_, body: body) } - public var empty: FlatbufferVector { return _accessor.vector(at: VT.empty, byteSize: 8) } - public func withUnsafePointerToEmpty(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VT.empty, body: body) } - public var array: FlatbufferVector { return _accessor.vector(at: VT.array, byteSize: 8) } - public func withUnsafePointerToArray(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VT.array, body: body) } + public var none_: FlatbufferVector { return _accessor.vector(at: VTOFFSET.none_.v, byteSize: 8) } + public func withUnsafePointerToNone(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VTOFFSET.none_.v, body: body) } + public var empty: FlatbufferVector { return _accessor.vector(at: VTOFFSET.empty.v, byteSize: 8) } + public func withUnsafePointerToEmpty(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VTOFFSET.empty.v, body: body) } + public var array: FlatbufferVector { return _accessor.vector(at: VTOFFSET.array.v, byteSize: 8) } + public func withUnsafePointerToArray(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VTOFFSET.array.v, body: body) } public static func startVectors(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 3) } - public static func addVectorOf(none_: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: none_, at: VT.none_) } - public static func addVectorOf(empty: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: empty, at: VT.empty) } - public static func addVectorOf(array: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: array, at: VT.array) } + public static func addVectorOf(none_: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: none_, at: VTOFFSET.none_.p) } + public static func addVectorOf(empty: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: empty, at: VTOFFSET.empty.p) } + public static func addVectorOf(array: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: array, at: VTOFFSET.array.p) } public static func endVectors(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } public static func createVectors( _ fbb: inout FlatBufferBuilder, @@ -49,20 +51,20 @@ public struct Swift_Tests_Vectors: FlatBufferVerifiableTable, FlatbuffersVectorI public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { var _v = try verifier.visitTable(at: position) - try _v.visit(field: VT.none_, fieldName: "none_", required: false, type: ForwardOffset>.self) - try _v.visit(field: VT.empty, fieldName: "empty", required: false, type: ForwardOffset>.self) - try _v.visit(field: VT.array, fieldName: "array", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.none_.p, fieldName: "none_", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.empty.p, fieldName: "empty", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.array.p, fieldName: "array", required: false, type: ForwardOffset>.self) _v.finish() } } extension Swift_Tests_Vectors: Encodable { + enum CodingKeys: String, CodingKey { case none_ = "none" case empty = "empty" case array = "array" } - public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(none_, forKey: .none_) diff --git a/tests/swift/Tests/Flexbuffers/FlexBuffersJSONTests.swift b/tests/swift/Tests/Flexbuffers/FlexBuffersJSONTests.swift index 8cb5ca9b5..c25466666 100644 --- a/tests/swift/Tests/Flexbuffers/FlexBuffersJSONTests.swift +++ b/tests/swift/Tests/Flexbuffers/FlexBuffersJSONTests.swift @@ -16,19 +16,17 @@ import Common import FlexBuffers -import Foundation -import Testing +import XCTest -struct FlexBuffersJSONTests { - @Test +final class FlexBuffersJSONTests: XCTestCase { func testEncodingJSON() throws { let buf: ByteBuffer = createProperBuffer().sizedByteBuffer let reference = try getRoot(buffer: buf)! let json = reference.jsonString() // swiftformat:disable all - #expect( - json == + XCTAssertEqual( + json, "{\"bar\": [1, 2, 3], \"bar3\": [1, 2, 3], \"bool\": true, \"bools\": [true, false, true, false], \"foo\": 100.0, \"mymap\": {\"foo\": \"Fred\"}, \"vec\": [-100, \"Fred\", 4.0, \"M\", false, 4.0]}" ) // swiftformat:enable all @@ -39,15 +37,15 @@ struct FlexBuffersJSONTests { with: data, options: []) as! [String: Any] - #expect(decodedData["bar"] as! [Int] == [1, 2, 3]) - #expect(decodedData["bar3"] as! [Int] == [1, 2, 3]) + XCTAssertEqual(decodedData["bar"] as! [Int], [1, 2, 3]) + XCTAssertEqual(decodedData["bar3"] as! [Int], [1, 2, 3]) let vec: [Any] = decodedData["vec"] as! [Any] - #expect(vec[0] as! Int == -100) - #expect(vec[1] as! String == "Fred") - #expect(vec[2] as! Double == 4.0) - #expect(vec[3] as! String == "M") - #expect(vec[4] as! Bool == false) - #expect(vec[5] as! Double == 4.0) + XCTAssertEqual(vec[0] as! Int, -100) + XCTAssertEqual(vec[1] as! String, "Fred") + XCTAssertEqual(vec[2] as! Double, 4.0) + XCTAssertEqual(vec[3] as! String, "M") + XCTAssertEqual(vec[4] as! Bool, false) + XCTAssertEqual(vec[5] as! Double, 4.0) } } diff --git a/tests/swift/Tests/Flexbuffers/FlexBuffersReaderTests.swift b/tests/swift/Tests/Flexbuffers/FlexBuffersReaderTests.swift index 12cc82060..dbbc637fd 100644 --- a/tests/swift/Tests/Flexbuffers/FlexBuffersReaderTests.swift +++ b/tests/swift/Tests/Flexbuffers/FlexBuffersReaderTests.swift @@ -15,26 +15,22 @@ */ import Common -import Foundation -import Testing +import XCTest @testable import FlexBuffers -struct FlexBuffersReaderTests { +final class FlexBuffersReaderTests: XCTestCase { - @Test func testReadingProperBuffer() throws { let buf: ByteBuffer = createProperBuffer().byteBuffer try validate(buffer: buf) } - @Test func testReadingSizedBuffer() throws { let buf: ByteBuffer = createSizedBuffer() try validate(buffer: buf) } - @Test(.bug("https://github.com/google/flatbuffers/issues/8642")) func testReset() throws { var fbx = FlexBuffersWriter( initialSize: 8, @@ -42,87 +38,87 @@ struct FlexBuffersReaderTests { write(fbx: &fbx) try validate(buffer: ByteBuffer(data: fbx.data)) - #expect(fbx.capacity == 512) + XCTAssertEqual(fbx.capacity, 512) fbx.reset() - #expect(fbx.writerIndex == 0) - #expect(fbx.capacity == 8) + XCTAssertEqual(fbx.writerIndex, 0) + XCTAssertEqual(fbx.capacity, 8) write(fbx: &fbx) try validate(buffer: ByteBuffer(data: fbx.data)) fbx.reset(keepingCapacity: true) - #expect(fbx.writerIndex == 0) - #expect(fbx.capacity == 512) + XCTAssertEqual(fbx.writerIndex, 0) + XCTAssertEqual(fbx.capacity, 512) write(fbx: &fbx) try validate(buffer: ByteBuffer(data: fbx.data)) - #expect(fbx.capacity == 512) + XCTAssertEqual(fbx.capacity, 512) } private func validate(buffer buf: ByteBuffer) throws { let reference = try getRoot(buffer: buf)! - #expect(reference.type == .map) + XCTAssertEqual(reference.type, .map) let map = reference.map! - #expect(map.count == 7) + XCTAssertEqual(map.count, 7) let vecRef = map["vec"]! - #expect(vecRef.type == .vector) + XCTAssertEqual(vecRef.type, .vector) let vec = vecRef.vector! - #expect(vec.count == 6) - #expect(vec[0]?.type == .int) - #expect(vec[0]?.int == -100) - #expect(vec[1]?.type == .string) - #expect(vec[1]?.cString == "Fred") - #expect(vec[1]?.int == nil) - #expect(vec[2]?.double == 4.0) - #expect(vec[3]?.type == .blob) + XCTAssertEqual(vec.count, 6) + XCTAssertEqual(vec[0]?.type, .int) + XCTAssertEqual(vec[0]?.int, -100) + XCTAssertEqual(vec[1]?.type, .string) + XCTAssertEqual(vec[1]?.cString, "Fred") + XCTAssertNil(vec[1]?.int) + XCTAssertEqual(vec[2]?.double, 4.0) + XCTAssertTrue(vec[3]?.type == .blob) let blob = vec[3]!.blob { pointer in Array(pointer) } - #expect(blob?.count == 1) - #expect(blob?[0] == 77) - #expect(vec[4]?.type == .bool) - #expect(vec[4]?.bool == false) - #expect(vec[5]?.double == 4.0) // Shared with vec[2] + XCTAssertEqual(blob?.count, 1) + XCTAssertEqual(blob?[0], 77) + XCTAssertEqual(vec[4]?.type, .bool) + XCTAssertEqual(vec[4]?.bool, false) + XCTAssertEqual(vec[5]?.double, 4.0) // Shared with vec[2] let barVec = map["bar"]!.typedVector! - #expect(barVec.count == 3) - #expect(barVec[2]?.int == 3) - #expect(barVec[2]?.asInt() == UInt8(3)) + XCTAssertEqual(barVec.count, 3) + XCTAssertEqual(barVec[2]?.int, 3) + XCTAssertEqual(barVec[2]?.asInt(), UInt8(3)) let fixedVec = map["bar3"]!.fixedTypedVector! - #expect(fixedVec.count == 3) - #expect(fixedVec[2]?.int == 3) - #expect(fixedVec[2]?.asInt() == UInt8(3)) - #expect(map["bool"]?.bool == true) + XCTAssertEqual(fixedVec.count, 3) + XCTAssertEqual(fixedVec[2]?.int, 3) + XCTAssertEqual(fixedVec[2]?.asInt(), UInt8(3)) + XCTAssertEqual(map["bool"]?.bool, true) let boolsVector = map["bools"]!.typedVector! - #expect(boolsVector.type == .bool) - #expect(boolsVector[0]?.bool == true) - #expect(boolsVector[1]?.bool == false) + XCTAssertEqual(boolsVector.type, .bool) + XCTAssertEqual(boolsVector[0]?.bool, true) + XCTAssertEqual(boolsVector[1]?.bool, false) let bools = [true, false, true, false] boolsVector.withUnsafeRawBufferPointer { buff in for i in 0.. Bool = { var buffer = fbb.sizedBuffer var monster: Monster = getRoot(byteBuffer: &buffer) - readFlatbufferMonster(monster: &monster) + self.readFlatbufferMonster(monster: &monster) return true } - #expect(testAligned() == true) + XCTAssertEqual(testAligned(), true) let testUnaligned: () -> Bool = { var bytes: [UInt8] = [0x00] bytes.append(contentsOf: fbb.sizedByteArray) return bytes.withUnsafeMutableBytes { ptr in guard var baseAddress = ptr.baseAddress else { - Issue.record("Base pointer is not defined") + XCTFail("Base pointer is not defined") return false } baseAddress = baseAddress.advanced(by: 1) @@ -256,14 +244,13 @@ struct FlatBuffersMonsterWriterTests { assumingMemoryBound: unlignedPtr, capacity: ptr.count - 1) var monster: Monster = getRoot(byteBuffer: &bytes) - readFlatbufferMonster(monster: &monster) + self.readFlatbufferMonster(monster: &monster) return true } } - #expect(testUnaligned() == true) + XCTAssertEqual(testUnaligned(), true) } - @Test func testReadingRemovedSizeUnalignedBuffer() { // Aligned read let fbb = createMonster(withPrefix: true) @@ -272,7 +259,7 @@ struct FlatBuffersMonsterWriterTests { bytes.append(contentsOf: fbb.sizedByteArray) return bytes.withUnsafeMutableBytes { ptr in guard var baseAddress = ptr.baseAddress else { - Issue.record("Base pointer is not defined") + XCTFail("Base pointer is not defined") return false } baseAddress = baseAddress.advanced(by: 1) @@ -282,14 +269,13 @@ struct FlatBuffersMonsterWriterTests { capacity: ptr.count - 1) var newBuf = FlatBuffersUtils.removeSizePrefix(bb: bytes) var monster: Monster = getRoot(byteBuffer: &newBuf) - readFlatbufferMonster(monster: &monster) + self.readFlatbufferMonster(monster: &monster) return true } } - #expect(testUnaligned() == true) + XCTAssertEqual(testUnaligned(), true) } - @Test func testForceRetainedObject() { let byteBuffer = { // swiftformat:disable all @@ -395,95 +381,95 @@ struct FlatBuffersMonsterWriterTests { var fb = fb let monster: Monster = getRoot(byteBuffer: &fb) - #expect(monster.mutate(mana: 10) == false) - #expect(monster.testarrayoftables[0].name == "Barney") - #expect(monster.testarrayoftables[1].name == "Frodo") - #expect(monster.testarrayoftables[2].name == "Wilma") + XCTAssertFalse(monster.mutate(mana: 10)) + XCTAssertEqual(monster.testarrayoftables[0].name, "Barney") + XCTAssertEqual(monster.testarrayoftables[1].name, "Frodo") + XCTAssertEqual(monster.testarrayoftables[2].name, "Wilma") // Example of searching for a table by the key - #expect(monster.testarrayoftablesBy(key: "Frodo") != nil) - #expect(monster.testarrayoftablesBy(key: "Barney") != nil) - #expect(monster.testarrayoftablesBy(key: "Wilma") != nil) + XCTAssertNotNil(monster.testarrayoftablesBy(key: "Frodo")) + XCTAssertNotNil(monster.testarrayoftablesBy(key: "Barney")) + XCTAssertNotNil(monster.testarrayoftablesBy(key: "Wilma")) - #expect(monster.testType == .monster) + XCTAssertEqual(monster.testType, .monster) - #expect(monster.mutate(inventory: 1, at: 0) == true) - #expect(monster.mutate(inventory: 2, at: 1) == true) - #expect(monster.mutate(inventory: 3, at: 2) == true) - #expect(monster.mutate(inventory: 4, at: 3) == true) - #expect(monster.mutate(inventory: 5, at: 4) == true) + XCTAssertEqual(monster.mutate(inventory: 1, at: 0), true) + XCTAssertEqual(monster.mutate(inventory: 2, at: 1), true) + XCTAssertEqual(monster.mutate(inventory: 3, at: 2), true) + XCTAssertEqual(monster.mutate(inventory: 4, at: 3), true) + XCTAssertEqual(monster.mutate(inventory: 5, at: 4), true) for i in 0.. ByteBuffer { return serialize(type: MyGame_InParentNamespace.self) } } -public struct MyGame_Example2_Monster: FlatBufferVerifiableTable, FlatbuffersVectorInitializable, ObjectAPIPacker { +public struct MyGame_Example2_Monster: FlatBufferTable, FlatbuffersVectorInitializable, Verifiable, ObjectAPIPacker { static func validateVersion() { FlatBuffersVersion_25_12_19() } public var __buffer: ByteBuffer! { return _accessor.bb } @@ -746,6 +747,7 @@ public struct MyGame_Example2_Monster: FlatBufferVerifiableTable, FlatbuffersVec } extension MyGame_Example2_Monster: Encodable { + public func encode(to encoder: Encoder) throws { } } @@ -762,7 +764,7 @@ public class MyGame_Example2_MonsterT: NativeObject { public func serialize() -> ByteBuffer { return serialize(type: MyGame_Example2_Monster.self) } } -internal struct MyGame_Example_TestSimpleTableWithEnum: FlatBufferVerifiableTable, FlatbuffersVectorInitializable, ObjectAPIPacker { +internal struct MyGame_Example_TestSimpleTableWithEnum: FlatBufferTable, FlatbuffersVectorInitializable, Verifiable, ObjectAPIPacker { static func validateVersion() { FlatBuffersVersion_25_12_19() } internal var __buffer: ByteBuffer! { return _accessor.bb } @@ -773,14 +775,16 @@ internal struct MyGame_Example_TestSimpleTableWithEnum: FlatBufferVerifiableTabl private init(_ t: Table) { _accessor = t } internal init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } - private struct VT { - static let color: VOffset = 4 + private enum VTOFFSET: VOffset { + case color = 4 + var v: Int32 { Int32(self.rawValue) } + var p: VOffset { self.rawValue } } - internal var color: MyGame_Example_Color { let o = _accessor.offset(VT.color); return o == 0 ? .green : MyGame_Example_Color(rawValue: _accessor.readBuffer(of: UInt8.self, at: o)) ?? .green } - @discardableResult internal func mutate(color: MyGame_Example_Color) -> Bool {let o = _accessor.offset(VT.color); return _accessor.mutate(color.rawValue, index: o) } + internal var color: MyGame_Example_Color { let o = _accessor.offset(VTOFFSET.color.v); return o == 0 ? .green : MyGame_Example_Color(rawValue: _accessor.readBuffer(of: UInt8.self, at: o)) ?? .green } + @discardableResult internal func mutate(color: MyGame_Example_Color) -> Bool {let o = _accessor.offset(VTOFFSET.color.v); return _accessor.mutate(color.rawValue, index: o) } internal static func startTestSimpleTableWithEnum(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) } - internal static func add(color: MyGame_Example_Color, _ fbb: inout FlatBufferBuilder) { fbb.add(element: color.rawValue, def: 2, at: VT.color) } + internal static func add(color: MyGame_Example_Color, _ fbb: inout FlatBufferBuilder) { fbb.add(element: color.rawValue, def: 2, at: VTOFFSET.color.p) } internal static func endTestSimpleTableWithEnum(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } internal static func createTestSimpleTableWithEnum( _ fbb: inout FlatBufferBuilder, @@ -807,16 +811,16 @@ internal struct MyGame_Example_TestSimpleTableWithEnum: FlatBufferVerifiableTabl internal static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { var _v = try verifier.visitTable(at: position) - try _v.visit(field: VT.color, fieldName: "color", required: false, type: MyGame_Example_Color.self) + try _v.visit(field: VTOFFSET.color.p, fieldName: "color", required: false, type: MyGame_Example_Color.self) _v.finish() } } extension MyGame_Example_TestSimpleTableWithEnum: Encodable { + enum CodingKeys: String, CodingKey { case color = "color" } - internal func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) if color != .green { @@ -840,7 +844,7 @@ internal class MyGame_Example_TestSimpleTableWithEnumT: NativeObject { internal func serialize() -> ByteBuffer { return serialize(type: MyGame_Example_TestSimpleTableWithEnum.self) } } -public struct MyGame_Example_Stat: FlatBufferVerifiableTable, FlatbuffersVectorInitializable, ObjectAPIPacker { +public struct MyGame_Example_Stat: FlatBufferTable, FlatbuffersVectorInitializable, Verifiable, ObjectAPIPacker { static func validateVersion() { FlatBuffersVersion_25_12_19() } public var __buffer: ByteBuffer! { return _accessor.bb } @@ -851,22 +855,24 @@ public struct MyGame_Example_Stat: FlatBufferVerifiableTable, FlatbuffersVectorI private init(_ t: Table) { _accessor = t } public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } - private struct VT { - static let id: VOffset = 4 - static let val: VOffset = 6 - static let count: VOffset = 8 + private enum VTOFFSET: VOffset { + case id = 4 + case val = 6 + case count = 8 + var v: Int32 { Int32(self.rawValue) } + var p: VOffset { self.rawValue } } - public var id: String? { let o = _accessor.offset(VT.id); return o == 0 ? nil : _accessor.string(at: o) } - public var idSegmentArray: [UInt8]? { return _accessor.getVector(at: VT.id) } - public var val: Int64 { let o = _accessor.offset(VT.val); return o == 0 ? 0 : _accessor.readBuffer(of: Int64.self, at: o) } - @discardableResult public func mutate(val: Int64) -> Bool {let o = _accessor.offset(VT.val); return _accessor.mutate(val, index: o) } - public var count: UInt16 { let o = _accessor.offset(VT.count); return o == 0 ? 0 : _accessor.readBuffer(of: UInt16.self, at: o) } - @discardableResult public func mutate(count: UInt16) -> Bool {let o = _accessor.offset(VT.count); return _accessor.mutate(count, index: o) } + public var id: String? { let o = _accessor.offset(VTOFFSET.id.v); return o == 0 ? nil : _accessor.string(at: o) } + public var idSegmentArray: [UInt8]? { return _accessor.getVector(at: VTOFFSET.id.v) } + public var val: Int64 { let o = _accessor.offset(VTOFFSET.val.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int64.self, at: o) } + @discardableResult public func mutate(val: Int64) -> Bool {let o = _accessor.offset(VTOFFSET.val.v); return _accessor.mutate(val, index: o) } + public var count: UInt16 { let o = _accessor.offset(VTOFFSET.count.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt16.self, at: o) } + @discardableResult public func mutate(count: UInt16) -> Bool {let o = _accessor.offset(VTOFFSET.count.v); return _accessor.mutate(count, index: o) } public static func startStat(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 3) } - public static func add(id: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: id, at: VT.id) } - public static func add(val: Int64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: val, def: 0, at: VT.val) } - public static func add(count: UInt16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: count, def: 0, at: VT.count) } + public static func add(id: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: id, at: VTOFFSET.id.p) } + public static func add(val: Int64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: val, def: 0, at: VTOFFSET.val.p) } + public static func add(count: UInt16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: count, def: 0, at: VTOFFSET.count.p) } public static func endStat(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } public static func createStat( _ fbb: inout FlatBufferBuilder, @@ -930,20 +936,20 @@ public struct MyGame_Example_Stat: FlatBufferVerifiableTable, FlatbuffersVectorI public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { var _v = try verifier.visitTable(at: position) - try _v.visit(field: VT.id, fieldName: "id", required: false, type: ForwardOffset.self) - try _v.visit(field: VT.val, fieldName: "val", required: false, type: Int64.self) - try _v.visit(field: VT.count, fieldName: "count", required: false, type: UInt16.self) + try _v.visit(field: VTOFFSET.id.p, fieldName: "id", required: false, type: ForwardOffset.self) + try _v.visit(field: VTOFFSET.val.p, fieldName: "val", required: false, type: Int64.self) + try _v.visit(field: VTOFFSET.count.p, fieldName: "count", required: false, type: UInt16.self) _v.finish() } } extension MyGame_Example_Stat: Encodable { + enum CodingKeys: String, CodingKey { case id = "id" case val = "val" case count = "count" } - public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(id, forKey: .id) @@ -976,7 +982,7 @@ public class MyGame_Example_StatT: NativeObject { public func serialize() -> ByteBuffer { return serialize(type: MyGame_Example_Stat.self) } } -public struct MyGame_Example_Referrable: FlatBufferVerifiableTable, FlatbuffersVectorInitializable, ObjectAPIPacker { +public struct MyGame_Example_Referrable: FlatBufferTable, FlatbuffersVectorInitializable, Verifiable, ObjectAPIPacker { static func validateVersion() { FlatBuffersVersion_25_12_19() } public var __buffer: ByteBuffer! { return _accessor.bb } @@ -987,14 +993,16 @@ public struct MyGame_Example_Referrable: FlatBufferVerifiableTable, FlatbuffersV private init(_ t: Table) { _accessor = t } public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } - private struct VT { - static let id: VOffset = 4 + private enum VTOFFSET: VOffset { + case id = 4 + var v: Int32 { Int32(self.rawValue) } + var p: VOffset { self.rawValue } } - public var id: UInt64 { let o = _accessor.offset(VT.id); return o == 0 ? 0 : _accessor.readBuffer(of: UInt64.self, at: o) } - @discardableResult public func mutate(id: UInt64) -> Bool {let o = _accessor.offset(VT.id); return _accessor.mutate(id, index: o) } + public var id: UInt64 { let o = _accessor.offset(VTOFFSET.id.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt64.self, at: o) } + @discardableResult public func mutate(id: UInt64) -> Bool {let o = _accessor.offset(VTOFFSET.id.v); return _accessor.mutate(id, index: o) } public static func startReferrable(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) } - public static func add(id: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: id, def: 0, at: VT.id) } + public static func add(id: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: id, def: 0, at: VTOFFSET.id.p) } public static func endReferrable(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } public static func createReferrable( _ fbb: inout FlatBufferBuilder, @@ -1045,16 +1053,16 @@ public struct MyGame_Example_Referrable: FlatBufferVerifiableTable, FlatbuffersV public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { var _v = try verifier.visitTable(at: position) - try _v.visit(field: VT.id, fieldName: "id", required: false, type: UInt64.self) + try _v.visit(field: VTOFFSET.id.p, fieldName: "id", required: false, type: UInt64.self) _v.finish() } } extension MyGame_Example_Referrable: Encodable { + enum CodingKeys: String, CodingKey { case id = "id" } - public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) if id != 0 { @@ -1079,7 +1087,7 @@ public class MyGame_Example_ReferrableT: NativeObject { } /// an example documentation comment: "monster object" -public struct MyGame_Example_Monster: FlatBufferVerifiableTable, FlatbuffersVectorInitializable, ObjectAPIPacker { +public struct MyGame_Example_Monster: FlatBufferTable, FlatbuffersVectorInitializable, Verifiable, ObjectAPIPacker { static func validateVersion() { FlatBuffersVersion_25_12_19() } public var __buffer: ByteBuffer! { return _accessor.bb } @@ -1090,267 +1098,269 @@ public struct MyGame_Example_Monster: FlatBufferVerifiableTable, FlatbuffersVect private init(_ t: Table) { _accessor = t } public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } - private struct VT { - static let pos: VOffset = 4 - static let mana: VOffset = 6 - static let hp: VOffset = 8 - static let name: VOffset = 10 - static let inventory: VOffset = 14 - static let color: VOffset = 16 - static let testType: VOffset = 18 - static let test: VOffset = 20 - static let test4: VOffset = 22 - static let testarrayofstring: VOffset = 24 - static let testarrayoftables: VOffset = 26 - static let enemy: VOffset = 28 - static let testnestedflatbuffer: VOffset = 30 - static let testempty: VOffset = 32 - static let testbool: VOffset = 34 - static let testhashs32Fnv1: VOffset = 36 - static let testhashu32Fnv1: VOffset = 38 - static let testhashs64Fnv1: VOffset = 40 - static let testhashu64Fnv1: VOffset = 42 - static let testhashs32Fnv1a: VOffset = 44 - static let testhashu32Fnv1a: VOffset = 46 - static let testhashs64Fnv1a: VOffset = 48 - static let testhashu64Fnv1a: VOffset = 50 - static let testarrayofbools: VOffset = 52 - static let testf: VOffset = 54 - static let testf2: VOffset = 56 - static let testf3: VOffset = 58 - static let testarrayofstring2: VOffset = 60 - static let testarrayofsortedstruct: VOffset = 62 - static let flex: VOffset = 64 - static let test5: VOffset = 66 - static let vectorOfLongs: VOffset = 68 - static let vectorOfDoubles: VOffset = 70 - static let parentNamespaceTest: VOffset = 72 - static let vectorOfReferrables: VOffset = 74 - static let singleWeakReference: VOffset = 76 - static let vectorOfWeakReferences: VOffset = 78 - static let vectorOfStrongReferrables: VOffset = 80 - static let coOwningReference: VOffset = 82 - static let vectorOfCoOwningReferences: VOffset = 84 - static let nonOwningReference: VOffset = 86 - static let vectorOfNonOwningReferences: VOffset = 88 - static let anyUniqueType: VOffset = 90 - static let anyUnique: VOffset = 92 - static let anyAmbiguousType: VOffset = 94 - static let anyAmbiguous: VOffset = 96 - static let vectorOfEnums: VOffset = 98 - static let signedEnum: VOffset = 100 - static let testrequirednestedflatbuffer: VOffset = 102 - static let scalarKeySortedTables: VOffset = 104 - static let nativeInline: VOffset = 106 - static let longEnumNonEnumDefault: VOffset = 108 - static let longEnumNormalDefault: VOffset = 110 - static let nanDefault: VOffset = 112 - static let infDefault: VOffset = 114 - static let positiveInfDefault: VOffset = 116 - static let infinityDefault: VOffset = 118 - static let positiveInfinityDefault: VOffset = 120 - static let negativeInfDefault: VOffset = 122 - static let negativeInfinityDefault: VOffset = 124 - static let doubleInfDefault: VOffset = 126 + private enum VTOFFSET: VOffset { + case pos = 4 + case mana = 6 + case hp = 8 + case name = 10 + case inventory = 14 + case color = 16 + case testType = 18 + case test = 20 + case test4 = 22 + case testarrayofstring = 24 + case testarrayoftables = 26 + case enemy = 28 + case testnestedflatbuffer = 30 + case testempty = 32 + case testbool = 34 + case testhashs32Fnv1 = 36 + case testhashu32Fnv1 = 38 + case testhashs64Fnv1 = 40 + case testhashu64Fnv1 = 42 + case testhashs32Fnv1a = 44 + case testhashu32Fnv1a = 46 + case testhashs64Fnv1a = 48 + case testhashu64Fnv1a = 50 + case testarrayofbools = 52 + case testf = 54 + case testf2 = 56 + case testf3 = 58 + case testarrayofstring2 = 60 + case testarrayofsortedstruct = 62 + case flex = 64 + case test5 = 66 + case vectorOfLongs = 68 + case vectorOfDoubles = 70 + case parentNamespaceTest = 72 + case vectorOfReferrables = 74 + case singleWeakReference = 76 + case vectorOfWeakReferences = 78 + case vectorOfStrongReferrables = 80 + case coOwningReference = 82 + case vectorOfCoOwningReferences = 84 + case nonOwningReference = 86 + case vectorOfNonOwningReferences = 88 + case anyUniqueType = 90 + case anyUnique = 92 + case anyAmbiguousType = 94 + case anyAmbiguous = 96 + case vectorOfEnums = 98 + case signedEnum = 100 + case testrequirednestedflatbuffer = 102 + case scalarKeySortedTables = 104 + case nativeInline = 106 + case longEnumNonEnumDefault = 108 + case longEnumNormalDefault = 110 + case nanDefault = 112 + case infDefault = 114 + case positiveInfDefault = 116 + case infinityDefault = 118 + case positiveInfinityDefault = 120 + case negativeInfDefault = 122 + case negativeInfinityDefault = 124 + case doubleInfDefault = 126 + var v: Int32 { Int32(self.rawValue) } + var p: VOffset { self.rawValue } } - public var pos: MyGame_Example_Vec3? { let o = _accessor.offset(VT.pos); return o == 0 ? nil : _accessor.readBuffer(of: MyGame_Example_Vec3.self, at: o) } - public var mutablePos: MyGame_Example_Vec3_Mutable? { let o = _accessor.offset(VT.pos); return o == 0 ? nil : MyGame_Example_Vec3_Mutable(_accessor.bb, o: o + _accessor.position) } - public var mana: Int16 { let o = _accessor.offset(VT.mana); return o == 0 ? 150 : _accessor.readBuffer(of: Int16.self, at: o) } - @discardableResult public func mutate(mana: Int16) -> Bool {let o = _accessor.offset(VT.mana); return _accessor.mutate(mana, index: o) } - public var hp: Int16 { let o = _accessor.offset(VT.hp); return o == 0 ? 100 : _accessor.readBuffer(of: Int16.self, at: o) } - @discardableResult public func mutate(hp: Int16) -> Bool {let o = _accessor.offset(VT.hp); return _accessor.mutate(hp, index: o) } - public var name: String! { let o = _accessor.offset(VT.name); return _accessor.string(at: o) } - public var nameSegmentArray: [UInt8]! { return _accessor.getVector(at: VT.name) } - public var inventory: FlatbufferVector { return _accessor.vector(at: VT.inventory, byteSize: 1) } - public func mutate(inventory: UInt8, at index: Int32) -> Bool { let o = _accessor.offset(VT.inventory); return _accessor.directMutate(inventory, index: _accessor.vector(at: o) + index * 1) } - public func withUnsafePointerToInventory(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VT.inventory, body: body) } - public var color: MyGame_Example_Color { let o = _accessor.offset(VT.color); return o == 0 ? .blue : MyGame_Example_Color(rawValue: _accessor.readBuffer(of: UInt8.self, at: o)) ?? .blue } - @discardableResult public func mutate(color: MyGame_Example_Color) -> Bool {let o = _accessor.offset(VT.color); return _accessor.mutate(color.rawValue, index: o) } - public var testType: MyGame_Example_Any_ { let o = _accessor.offset(VT.testType); return o == 0 ? .none_ : MyGame_Example_Any_(rawValue: _accessor.readBuffer(of: UInt8.self, at: o)) ?? .none_ } - public func test(type: T.Type) -> T? { let o = _accessor.offset(VT.test); return o == 0 ? nil : _accessor.union(o) } - public var test4: FlatbufferVector { return _accessor.vector(at: VT.test4, byteSize: 4) } - public var mutableTest4: FlatbufferVector { return _accessor.vector(at: VT.test4, byteSize: 4) } - public func withUnsafePointerToTest4(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VT.test4, body: body) } - public var testarrayofstring: FlatbufferVector { return _accessor.vector(at: VT.testarrayofstring, byteSize: 4) } + public var pos: MyGame_Example_Vec3? { let o = _accessor.offset(VTOFFSET.pos.v); return o == 0 ? nil : _accessor.readBuffer(of: MyGame_Example_Vec3.self, at: o) } + public var mutablePos: MyGame_Example_Vec3_Mutable? { let o = _accessor.offset(VTOFFSET.pos.v); return o == 0 ? nil : MyGame_Example_Vec3_Mutable(_accessor.bb, o: o + _accessor.position) } + 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 _accessor.string(at: o) } + public var nameSegmentArray: [UInt8]! { return _accessor.getVector(at: VTOFFSET.name.v) } + public var inventory: FlatbufferVector { return _accessor.vector(at: VTOFFSET.inventory.v, byteSize: 1) } + 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 func withUnsafePointerToInventory(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VTOFFSET.inventory.v, body: body) } + public var color: MyGame_Example_Color { let o = _accessor.offset(VTOFFSET.color.v); return o == 0 ? .blue : MyGame_Example_Color(rawValue: _accessor.readBuffer(of: UInt8.self, at: o)) ?? .blue } + @discardableResult public func mutate(color: MyGame_Example_Color) -> Bool {let o = _accessor.offset(VTOFFSET.color.v); return _accessor.mutate(color.rawValue, index: o) } + public var testType: MyGame_Example_Any_ { let o = _accessor.offset(VTOFFSET.testType.v); return o == 0 ? .none_ : MyGame_Example_Any_(rawValue: _accessor.readBuffer(of: UInt8.self, at: o)) ?? .none_ } + public func test(type: T.Type) -> T? { let o = _accessor.offset(VTOFFSET.test.v); return o == 0 ? nil : _accessor.union(o) } + public var test4: FlatbufferVector { return _accessor.vector(at: VTOFFSET.test4.v, byteSize: 4) } + public var mutableTest4: FlatbufferVector { return _accessor.vector(at: VTOFFSET.test4.v, byteSize: 4) } + public func withUnsafePointerToTest4(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VTOFFSET.test4.v, body: body) } + public var testarrayofstring: FlatbufferVector { return _accessor.vector(at: VTOFFSET.testarrayofstring.v, byteSize: 4) } /// an example documentation comment: this will end up in the generated code /// multiline too - public var testarrayoftables: FlatbufferVector { return _accessor.vector(at: VT.testarrayoftables, byteSize: 4) } - public func testarrayoftablesBy(key: String) -> MyGame_Example_Monster? { let o = _accessor.offset(VT.testarrayoftables); return o == 0 ? nil : MyGame_Example_Monster.lookupByKey(vector: _accessor.vector(at: o), key: key, fbb: _accessor.bb) } - public var enemy: MyGame_Example_Monster? { let o = _accessor.offset(VT.enemy); return o == 0 ? nil : MyGame_Example_Monster(_accessor.bb, o: _accessor.indirect(o + _accessor.position)) } - public var testnestedflatbuffer: FlatbufferVector { return _accessor.vector(at: VT.testnestedflatbuffer, byteSize: 1) } - public func mutate(testnestedflatbuffer: UInt8, at index: Int32) -> Bool { let o = _accessor.offset(VT.testnestedflatbuffer); return _accessor.directMutate(testnestedflatbuffer, index: _accessor.vector(at: o) + index * 1) } - public func withUnsafePointerToTestnestedflatbuffer(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VT.testnestedflatbuffer, body: body) } - public var testempty: MyGame_Example_Stat? { let o = _accessor.offset(VT.testempty); return o == 0 ? nil : MyGame_Example_Stat(_accessor.bb, o: _accessor.indirect(o + _accessor.position)) } - public var testbool: Bool { let o = _accessor.offset(VT.testbool); return o == 0 ? false : _accessor.readBuffer(of: Bool.self, at: o) } - @discardableResult public func mutate(testbool: Bool) -> Bool {let o = _accessor.offset(VT.testbool); return _accessor.mutate(testbool, index: o) } - public var testhashs32Fnv1: Int32 { let o = _accessor.offset(VT.testhashs32Fnv1); return o == 0 ? 0 : _accessor.readBuffer(of: Int32.self, at: o) } - @discardableResult public func mutate(testhashs32Fnv1: Int32) -> Bool {let o = _accessor.offset(VT.testhashs32Fnv1); return _accessor.mutate(testhashs32Fnv1, index: o) } - public var testhashu32Fnv1: UInt32 { let o = _accessor.offset(VT.testhashu32Fnv1); return o == 0 ? 0 : _accessor.readBuffer(of: UInt32.self, at: o) } - @discardableResult public func mutate(testhashu32Fnv1: UInt32) -> Bool {let o = _accessor.offset(VT.testhashu32Fnv1); return _accessor.mutate(testhashu32Fnv1, index: o) } - public var testhashs64Fnv1: Int64 { let o = _accessor.offset(VT.testhashs64Fnv1); return o == 0 ? 0 : _accessor.readBuffer(of: Int64.self, at: o) } - @discardableResult public func mutate(testhashs64Fnv1: Int64) -> Bool {let o = _accessor.offset(VT.testhashs64Fnv1); return _accessor.mutate(testhashs64Fnv1, index: o) } - public var testhashu64Fnv1: UInt64 { let o = _accessor.offset(VT.testhashu64Fnv1); return o == 0 ? 0 : _accessor.readBuffer(of: UInt64.self, at: o) } - @discardableResult public func mutate(testhashu64Fnv1: UInt64) -> Bool {let o = _accessor.offset(VT.testhashu64Fnv1); return _accessor.mutate(testhashu64Fnv1, index: o) } - public var testhashs32Fnv1a: Int32 { let o = _accessor.offset(VT.testhashs32Fnv1a); return o == 0 ? 0 : _accessor.readBuffer(of: Int32.self, at: o) } - @discardableResult public func mutate(testhashs32Fnv1a: Int32) -> Bool {let o = _accessor.offset(VT.testhashs32Fnv1a); return _accessor.mutate(testhashs32Fnv1a, index: o) } - public var testhashu32Fnv1a: UInt32 { let o = _accessor.offset(VT.testhashu32Fnv1a); return o == 0 ? 0 : _accessor.readBuffer(of: UInt32.self, at: o) } - @discardableResult public func mutate(testhashu32Fnv1a: UInt32) -> Bool {let o = _accessor.offset(VT.testhashu32Fnv1a); return _accessor.mutate(testhashu32Fnv1a, index: o) } - public var testhashs64Fnv1a: Int64 { let o = _accessor.offset(VT.testhashs64Fnv1a); return o == 0 ? 0 : _accessor.readBuffer(of: Int64.self, at: o) } - @discardableResult public func mutate(testhashs64Fnv1a: Int64) -> Bool {let o = _accessor.offset(VT.testhashs64Fnv1a); return _accessor.mutate(testhashs64Fnv1a, index: o) } - public var testhashu64Fnv1a: UInt64 { let o = _accessor.offset(VT.testhashu64Fnv1a); return o == 0 ? 0 : _accessor.readBuffer(of: UInt64.self, at: o) } - @discardableResult public func mutate(testhashu64Fnv1a: UInt64) -> Bool {let o = _accessor.offset(VT.testhashu64Fnv1a); return _accessor.mutate(testhashu64Fnv1a, index: o) } - public var testarrayofbools: FlatbufferVector { return _accessor.vector(at: VT.testarrayofbools, byteSize: 1) } - public func mutate(testarrayofbools: Bool, at index: Int32) -> Bool { let o = _accessor.offset(VT.testarrayofbools); return _accessor.directMutate(testarrayofbools, index: _accessor.vector(at: o) + index * 1) } - public func withUnsafePointerToTestarrayofbools(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VT.testarrayofbools, body: body) } - public var testf: Float32 { let o = _accessor.offset(VT.testf); return o == 0 ? 3.14159 : _accessor.readBuffer(of: Float32.self, at: o) } - @discardableResult public func mutate(testf: Float32) -> Bool {let o = _accessor.offset(VT.testf); return _accessor.mutate(testf, index: o) } - public var testf2: Float32 { let o = _accessor.offset(VT.testf2); return o == 0 ? 3.0 : _accessor.readBuffer(of: Float32.self, at: o) } - @discardableResult public func mutate(testf2: Float32) -> Bool {let o = _accessor.offset(VT.testf2); return _accessor.mutate(testf2, index: o) } - public var testf3: Float32 { let o = _accessor.offset(VT.testf3); return o == 0 ? 0.0 : _accessor.readBuffer(of: Float32.self, at: o) } - @discardableResult public func mutate(testf3: Float32) -> Bool {let o = _accessor.offset(VT.testf3); return _accessor.mutate(testf3, index: o) } - public var testarrayofstring2: FlatbufferVector { return _accessor.vector(at: VT.testarrayofstring2, byteSize: 4) } - public var testarrayofsortedstruct: FlatbufferVector { return _accessor.vector(at: VT.testarrayofsortedstruct, byteSize: 8) } - public var mutableTestarrayofsortedstruct: FlatbufferVector { return _accessor.vector(at: VT.testarrayofsortedstruct, byteSize: 8) } - public func withUnsafePointerToTestarrayofsortedstruct(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VT.testarrayofsortedstruct, body: body) } - public var flex: FlatbufferVector { return _accessor.vector(at: VT.flex, byteSize: 1) } - public func mutate(flex: UInt8, at index: Int32) -> Bool { let o = _accessor.offset(VT.flex); return _accessor.directMutate(flex, index: _accessor.vector(at: o) + index * 1) } - public func withUnsafePointerToFlex(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VT.flex, body: body) } - public var test5: FlatbufferVector { return _accessor.vector(at: VT.test5, byteSize: 4) } - public var mutableTest5: FlatbufferVector { return _accessor.vector(at: VT.test5, byteSize: 4) } - public func withUnsafePointerToTest5(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VT.test5, body: body) } - public var vectorOfLongs: FlatbufferVector { return _accessor.vector(at: VT.vectorOfLongs, byteSize: 8) } - public func mutate(vectorOfLongs: Int64, at index: Int32) -> Bool { let o = _accessor.offset(VT.vectorOfLongs); return _accessor.directMutate(vectorOfLongs, index: _accessor.vector(at: o) + index * 8) } - public func withUnsafePointerToVectorOfLongs(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VT.vectorOfLongs, body: body) } - public var vectorOfDoubles: FlatbufferVector { return _accessor.vector(at: VT.vectorOfDoubles, byteSize: 8) } - public func mutate(vectorOfDoubles: Double, at index: Int32) -> Bool { let o = _accessor.offset(VT.vectorOfDoubles); return _accessor.directMutate(vectorOfDoubles, index: _accessor.vector(at: o) + index * 8) } - public func withUnsafePointerToVectorOfDoubles(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VT.vectorOfDoubles, body: body) } - public var parentNamespaceTest: MyGame_InParentNamespace? { let o = _accessor.offset(VT.parentNamespaceTest); return o == 0 ? nil : MyGame_InParentNamespace(_accessor.bb, o: _accessor.indirect(o + _accessor.position)) } - public var vectorOfReferrables: FlatbufferVector { return _accessor.vector(at: VT.vectorOfReferrables, byteSize: 4) } - public func vectorOfReferrablesBy(key: UInt64) -> MyGame_Example_Referrable? { let o = _accessor.offset(VT.vectorOfReferrables); return o == 0 ? nil : MyGame_Example_Referrable.lookupByKey(vector: _accessor.vector(at: o), key: key, fbb: _accessor.bb) } - public var singleWeakReference: UInt64 { let o = _accessor.offset(VT.singleWeakReference); return o == 0 ? 0 : _accessor.readBuffer(of: UInt64.self, at: o) } - @discardableResult public func mutate(singleWeakReference: UInt64) -> Bool {let o = _accessor.offset(VT.singleWeakReference); return _accessor.mutate(singleWeakReference, index: o) } - public var vectorOfWeakReferences: FlatbufferVector { return _accessor.vector(at: VT.vectorOfWeakReferences, byteSize: 8) } - public func mutate(vectorOfWeakReferences: UInt64, at index: Int32) -> Bool { let o = _accessor.offset(VT.vectorOfWeakReferences); return _accessor.directMutate(vectorOfWeakReferences, index: _accessor.vector(at: o) + index * 8) } - public func withUnsafePointerToVectorOfWeakReferences(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VT.vectorOfWeakReferences, body: body) } - public var vectorOfStrongReferrables: FlatbufferVector { return _accessor.vector(at: VT.vectorOfStrongReferrables, byteSize: 4) } - public func vectorOfStrongReferrablesBy(key: UInt64) -> MyGame_Example_Referrable? { let o = _accessor.offset(VT.vectorOfStrongReferrables); return o == 0 ? nil : MyGame_Example_Referrable.lookupByKey(vector: _accessor.vector(at: o), key: key, fbb: _accessor.bb) } - public var coOwningReference: UInt64 { let o = _accessor.offset(VT.coOwningReference); return o == 0 ? 0 : _accessor.readBuffer(of: UInt64.self, at: o) } - @discardableResult public func mutate(coOwningReference: UInt64) -> Bool {let o = _accessor.offset(VT.coOwningReference); return _accessor.mutate(coOwningReference, index: o) } - public var vectorOfCoOwningReferences: FlatbufferVector { return _accessor.vector(at: VT.vectorOfCoOwningReferences, byteSize: 8) } - public func mutate(vectorOfCoOwningReferences: UInt64, at index: Int32) -> Bool { let o = _accessor.offset(VT.vectorOfCoOwningReferences); return _accessor.directMutate(vectorOfCoOwningReferences, index: _accessor.vector(at: o) + index * 8) } - public func withUnsafePointerToVectorOfCoOwningReferences(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VT.vectorOfCoOwningReferences, body: body) } - public var nonOwningReference: UInt64 { let o = _accessor.offset(VT.nonOwningReference); return o == 0 ? 0 : _accessor.readBuffer(of: UInt64.self, at: o) } - @discardableResult public func mutate(nonOwningReference: UInt64) -> Bool {let o = _accessor.offset(VT.nonOwningReference); return _accessor.mutate(nonOwningReference, index: o) } - public var vectorOfNonOwningReferences: FlatbufferVector { return _accessor.vector(at: VT.vectorOfNonOwningReferences, byteSize: 8) } - public func mutate(vectorOfNonOwningReferences: UInt64, at index: Int32) -> Bool { let o = _accessor.offset(VT.vectorOfNonOwningReferences); return _accessor.directMutate(vectorOfNonOwningReferences, index: _accessor.vector(at: o) + index * 8) } - public func withUnsafePointerToVectorOfNonOwningReferences(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VT.vectorOfNonOwningReferences, body: body) } - public var anyUniqueType: MyGame_Example_AnyUniqueAliases { let o = _accessor.offset(VT.anyUniqueType); return o == 0 ? .none_ : MyGame_Example_AnyUniqueAliases(rawValue: _accessor.readBuffer(of: UInt8.self, at: o)) ?? .none_ } - public func anyUnique(type: T.Type) -> T? { let o = _accessor.offset(VT.anyUnique); return o == 0 ? nil : _accessor.union(o) } - public var anyAmbiguousType: MyGame_Example_AnyAmbiguousAliases { let o = _accessor.offset(VT.anyAmbiguousType); return o == 0 ? .none_ : MyGame_Example_AnyAmbiguousAliases(rawValue: _accessor.readBuffer(of: UInt8.self, at: o)) ?? .none_ } - public func anyAmbiguous(type: T.Type) -> T? { let o = _accessor.offset(VT.anyAmbiguous); return o == 0 ? nil : _accessor.union(o) } - public var vectorOfEnums: FlatbufferVector { return _accessor.vector(at: VT.vectorOfEnums, byteSize: 1) } - public var signedEnum: MyGame_Example_Race { let o = _accessor.offset(VT.signedEnum); return o == 0 ? .none_ : MyGame_Example_Race(rawValue: _accessor.readBuffer(of: Int8.self, at: o)) ?? .none_ } - @discardableResult public func mutate(signedEnum: MyGame_Example_Race) -> Bool {let o = _accessor.offset(VT.signedEnum); return _accessor.mutate(signedEnum.rawValue, index: o) } - public var testrequirednestedflatbuffer: FlatbufferVector { return _accessor.vector(at: VT.testrequirednestedflatbuffer, byteSize: 1) } - public func mutate(testrequirednestedflatbuffer: UInt8, at index: Int32) -> Bool { let o = _accessor.offset(VT.testrequirednestedflatbuffer); return _accessor.directMutate(testrequirednestedflatbuffer, index: _accessor.vector(at: o) + index * 1) } - public func withUnsafePointerToTestrequirednestedflatbuffer(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VT.testrequirednestedflatbuffer, body: body) } - public var scalarKeySortedTables: FlatbufferVector { return _accessor.vector(at: VT.scalarKeySortedTables, byteSize: 4) } - public func scalarKeySortedTablesBy(key: UInt16) -> MyGame_Example_Stat? { let o = _accessor.offset(VT.scalarKeySortedTables); return o == 0 ? nil : MyGame_Example_Stat.lookupByKey(vector: _accessor.vector(at: o), key: key, fbb: _accessor.bb) } - public var nativeInline: MyGame_Example_Test? { let o = _accessor.offset(VT.nativeInline); return o == 0 ? nil : _accessor.readBuffer(of: MyGame_Example_Test.self, at: o) } - public var mutableNativeInline: MyGame_Example_Test_Mutable? { let o = _accessor.offset(VT.nativeInline); return o == 0 ? nil : MyGame_Example_Test_Mutable(_accessor.bb, o: o + _accessor.position) } - public var longEnumNonEnumDefault: MyGame_Example_LongEnum { let o = _accessor.offset(VT.longEnumNonEnumDefault); return o == 0 ? .longone : MyGame_Example_LongEnum(rawValue: _accessor.readBuffer(of: UInt64.self, at: o)) ?? .longone } - @discardableResult public func mutate(longEnumNonEnumDefault: MyGame_Example_LongEnum) -> Bool {let o = _accessor.offset(VT.longEnumNonEnumDefault); return _accessor.mutate(longEnumNonEnumDefault.rawValue, index: o) } - public var longEnumNormalDefault: MyGame_Example_LongEnum { let o = _accessor.offset(VT.longEnumNormalDefault); return o == 0 ? .longone : MyGame_Example_LongEnum(rawValue: _accessor.readBuffer(of: UInt64.self, at: o)) ?? .longone } - @discardableResult public func mutate(longEnumNormalDefault: MyGame_Example_LongEnum) -> Bool {let o = _accessor.offset(VT.longEnumNormalDefault); return _accessor.mutate(longEnumNormalDefault.rawValue, index: o) } - public var nanDefault: Float32 { let o = _accessor.offset(VT.nanDefault); return o == 0 ? .nan : _accessor.readBuffer(of: Float32.self, at: o) } - @discardableResult public func mutate(nanDefault: Float32) -> Bool {let o = _accessor.offset(VT.nanDefault); return _accessor.mutate(nanDefault, index: o) } - public var infDefault: Float32 { let o = _accessor.offset(VT.infDefault); return o == 0 ? .infinity : _accessor.readBuffer(of: Float32.self, at: o) } - @discardableResult public func mutate(infDefault: Float32) -> Bool {let o = _accessor.offset(VT.infDefault); return _accessor.mutate(infDefault, index: o) } - public var positiveInfDefault: Float32 { let o = _accessor.offset(VT.positiveInfDefault); return o == 0 ? .infinity : _accessor.readBuffer(of: Float32.self, at: o) } - @discardableResult public func mutate(positiveInfDefault: Float32) -> Bool {let o = _accessor.offset(VT.positiveInfDefault); return _accessor.mutate(positiveInfDefault, index: o) } - public var infinityDefault: Float32 { let o = _accessor.offset(VT.infinityDefault); return o == 0 ? .infinity : _accessor.readBuffer(of: Float32.self, at: o) } - @discardableResult public func mutate(infinityDefault: Float32) -> Bool {let o = _accessor.offset(VT.infinityDefault); return _accessor.mutate(infinityDefault, index: o) } - public var positiveInfinityDefault: Float32 { let o = _accessor.offset(VT.positiveInfinityDefault); return o == 0 ? .infinity : _accessor.readBuffer(of: Float32.self, at: o) } - @discardableResult public func mutate(positiveInfinityDefault: Float32) -> Bool {let o = _accessor.offset(VT.positiveInfinityDefault); return _accessor.mutate(positiveInfinityDefault, index: o) } - public var negativeInfDefault: Float32 { let o = _accessor.offset(VT.negativeInfDefault); return o == 0 ? -.infinity : _accessor.readBuffer(of: Float32.self, at: o) } - @discardableResult public func mutate(negativeInfDefault: Float32) -> Bool {let o = _accessor.offset(VT.negativeInfDefault); return _accessor.mutate(negativeInfDefault, index: o) } - public var negativeInfinityDefault: Float32 { let o = _accessor.offset(VT.negativeInfinityDefault); return o == 0 ? -.infinity : _accessor.readBuffer(of: Float32.self, at: o) } - @discardableResult public func mutate(negativeInfinityDefault: Float32) -> Bool {let o = _accessor.offset(VT.negativeInfinityDefault); return _accessor.mutate(negativeInfinityDefault, index: o) } - public var doubleInfDefault: Double { let o = _accessor.offset(VT.doubleInfDefault); return o == 0 ? .infinity : _accessor.readBuffer(of: Double.self, at: o) } - @discardableResult public func mutate(doubleInfDefault: Double) -> Bool {let o = _accessor.offset(VT.doubleInfDefault); return _accessor.mutate(doubleInfDefault, index: o) } + public var testarrayoftables: FlatbufferVector { return _accessor.vector(at: VTOFFSET.testarrayoftables.v, byteSize: 4) } + public func testarrayoftablesBy(key: String) -> MyGame_Example_Monster? { let o = _accessor.offset(VTOFFSET.testarrayoftables.v); return o == 0 ? nil : MyGame_Example_Monster.lookupByKey(vector: _accessor.vector(at: o), key: key, fbb: _accessor.bb) } + public var enemy: MyGame_Example_Monster? { let o = _accessor.offset(VTOFFSET.enemy.v); return o == 0 ? nil : MyGame_Example_Monster(_accessor.bb, o: _accessor.indirect(o + _accessor.position)) } + public var testnestedflatbuffer: FlatbufferVector { return _accessor.vector(at: VTOFFSET.testnestedflatbuffer.v, byteSize: 1) } + public func mutate(testnestedflatbuffer: UInt8, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.testnestedflatbuffer.v); return _accessor.directMutate(testnestedflatbuffer, index: _accessor.vector(at: o) + index * 1) } + public func withUnsafePointerToTestnestedflatbuffer(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VTOFFSET.testnestedflatbuffer.v, body: body) } + public var testempty: MyGame_Example_Stat? { let o = _accessor.offset(VTOFFSET.testempty.v); return o == 0 ? nil : MyGame_Example_Stat(_accessor.bb, o: _accessor.indirect(o + _accessor.position)) } + public var testbool: Bool { let o = _accessor.offset(VTOFFSET.testbool.v); return o == 0 ? false : _accessor.readBuffer(of: Bool.self, at: o) } + @discardableResult public func mutate(testbool: Bool) -> Bool {let o = _accessor.offset(VTOFFSET.testbool.v); return _accessor.mutate(testbool, index: o) } + public var testhashs32Fnv1: Int32 { let o = _accessor.offset(VTOFFSET.testhashs32Fnv1.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int32.self, at: o) } + @discardableResult public func mutate(testhashs32Fnv1: Int32) -> Bool {let o = _accessor.offset(VTOFFSET.testhashs32Fnv1.v); return _accessor.mutate(testhashs32Fnv1, index: o) } + public var testhashu32Fnv1: UInt32 { let o = _accessor.offset(VTOFFSET.testhashu32Fnv1.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt32.self, at: o) } + @discardableResult public func mutate(testhashu32Fnv1: UInt32) -> Bool {let o = _accessor.offset(VTOFFSET.testhashu32Fnv1.v); return _accessor.mutate(testhashu32Fnv1, index: o) } + public var testhashs64Fnv1: Int64 { let o = _accessor.offset(VTOFFSET.testhashs64Fnv1.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int64.self, at: o) } + @discardableResult public func mutate(testhashs64Fnv1: Int64) -> Bool {let o = _accessor.offset(VTOFFSET.testhashs64Fnv1.v); return _accessor.mutate(testhashs64Fnv1, index: o) } + public var testhashu64Fnv1: UInt64 { let o = _accessor.offset(VTOFFSET.testhashu64Fnv1.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt64.self, at: o) } + @discardableResult public func mutate(testhashu64Fnv1: UInt64) -> Bool {let o = _accessor.offset(VTOFFSET.testhashu64Fnv1.v); return _accessor.mutate(testhashu64Fnv1, index: o) } + public var testhashs32Fnv1a: Int32 { let o = _accessor.offset(VTOFFSET.testhashs32Fnv1a.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int32.self, at: o) } + @discardableResult public func mutate(testhashs32Fnv1a: Int32) -> Bool {let o = _accessor.offset(VTOFFSET.testhashs32Fnv1a.v); return _accessor.mutate(testhashs32Fnv1a, index: o) } + public var testhashu32Fnv1a: UInt32 { let o = _accessor.offset(VTOFFSET.testhashu32Fnv1a.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt32.self, at: o) } + @discardableResult public func mutate(testhashu32Fnv1a: UInt32) -> Bool {let o = _accessor.offset(VTOFFSET.testhashu32Fnv1a.v); return _accessor.mutate(testhashu32Fnv1a, index: o) } + public var testhashs64Fnv1a: Int64 { let o = _accessor.offset(VTOFFSET.testhashs64Fnv1a.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int64.self, at: o) } + @discardableResult public func mutate(testhashs64Fnv1a: Int64) -> Bool {let o = _accessor.offset(VTOFFSET.testhashs64Fnv1a.v); return _accessor.mutate(testhashs64Fnv1a, index: o) } + public var testhashu64Fnv1a: UInt64 { let o = _accessor.offset(VTOFFSET.testhashu64Fnv1a.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt64.self, at: o) } + @discardableResult public func mutate(testhashu64Fnv1a: UInt64) -> Bool {let o = _accessor.offset(VTOFFSET.testhashu64Fnv1a.v); return _accessor.mutate(testhashu64Fnv1a, index: o) } + public var testarrayofbools: FlatbufferVector { return _accessor.vector(at: VTOFFSET.testarrayofbools.v, byteSize: 1) } + public func mutate(testarrayofbools: Bool, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.testarrayofbools.v); return _accessor.directMutate(testarrayofbools, index: _accessor.vector(at: o) + index * 1) } + public func withUnsafePointerToTestarrayofbools(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VTOFFSET.testarrayofbools.v, body: body) } + public var testf: Float32 { let o = _accessor.offset(VTOFFSET.testf.v); return o == 0 ? 3.14159 : _accessor.readBuffer(of: Float32.self, at: o) } + @discardableResult public func mutate(testf: Float32) -> Bool {let o = _accessor.offset(VTOFFSET.testf.v); return _accessor.mutate(testf, index: o) } + public var testf2: Float32 { let o = _accessor.offset(VTOFFSET.testf2.v); return o == 0 ? 3.0 : _accessor.readBuffer(of: Float32.self, at: o) } + @discardableResult public func mutate(testf2: Float32) -> Bool {let o = _accessor.offset(VTOFFSET.testf2.v); return _accessor.mutate(testf2, index: o) } + public var testf3: Float32 { let o = _accessor.offset(VTOFFSET.testf3.v); return o == 0 ? 0.0 : _accessor.readBuffer(of: Float32.self, at: o) } + @discardableResult public func mutate(testf3: Float32) -> Bool {let o = _accessor.offset(VTOFFSET.testf3.v); return _accessor.mutate(testf3, index: o) } + public var testarrayofstring2: FlatbufferVector { return _accessor.vector(at: VTOFFSET.testarrayofstring2.v, byteSize: 4) } + public var testarrayofsortedstruct: FlatbufferVector { return _accessor.vector(at: VTOFFSET.testarrayofsortedstruct.v, byteSize: 8) } + public var mutableTestarrayofsortedstruct: FlatbufferVector { return _accessor.vector(at: VTOFFSET.testarrayofsortedstruct.v, byteSize: 8) } + public func withUnsafePointerToTestarrayofsortedstruct(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VTOFFSET.testarrayofsortedstruct.v, body: body) } + public var flex: FlatbufferVector { return _accessor.vector(at: VTOFFSET.flex.v, byteSize: 1) } + public func mutate(flex: UInt8, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.flex.v); return _accessor.directMutate(flex, index: _accessor.vector(at: o) + index * 1) } + public func withUnsafePointerToFlex(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VTOFFSET.flex.v, body: body) } + public var test5: FlatbufferVector { return _accessor.vector(at: VTOFFSET.test5.v, byteSize: 4) } + public var mutableTest5: FlatbufferVector { return _accessor.vector(at: VTOFFSET.test5.v, byteSize: 4) } + public func withUnsafePointerToTest5(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VTOFFSET.test5.v, body: body) } + public var vectorOfLongs: FlatbufferVector { return _accessor.vector(at: VTOFFSET.vectorOfLongs.v, byteSize: 8) } + public func mutate(vectorOfLongs: Int64, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.vectorOfLongs.v); return _accessor.directMutate(vectorOfLongs, index: _accessor.vector(at: o) + index * 8) } + public func withUnsafePointerToVectorOfLongs(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VTOFFSET.vectorOfLongs.v, body: body) } + public var vectorOfDoubles: FlatbufferVector { return _accessor.vector(at: VTOFFSET.vectorOfDoubles.v, byteSize: 8) } + public func mutate(vectorOfDoubles: Double, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.vectorOfDoubles.v); return _accessor.directMutate(vectorOfDoubles, index: _accessor.vector(at: o) + index * 8) } + public func withUnsafePointerToVectorOfDoubles(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VTOFFSET.vectorOfDoubles.v, body: body) } + public var parentNamespaceTest: MyGame_InParentNamespace? { let o = _accessor.offset(VTOFFSET.parentNamespaceTest.v); return o == 0 ? nil : MyGame_InParentNamespace(_accessor.bb, o: _accessor.indirect(o + _accessor.position)) } + public var vectorOfReferrables: FlatbufferVector { return _accessor.vector(at: VTOFFSET.vectorOfReferrables.v, byteSize: 4) } + public func vectorOfReferrablesBy(key: UInt64) -> MyGame_Example_Referrable? { let o = _accessor.offset(VTOFFSET.vectorOfReferrables.v); return o == 0 ? nil : MyGame_Example_Referrable.lookupByKey(vector: _accessor.vector(at: o), key: key, fbb: _accessor.bb) } + public var singleWeakReference: UInt64 { let o = _accessor.offset(VTOFFSET.singleWeakReference.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt64.self, at: o) } + @discardableResult public func mutate(singleWeakReference: UInt64) -> Bool {let o = _accessor.offset(VTOFFSET.singleWeakReference.v); return _accessor.mutate(singleWeakReference, index: o) } + public var vectorOfWeakReferences: FlatbufferVector { return _accessor.vector(at: VTOFFSET.vectorOfWeakReferences.v, byteSize: 8) } + public func mutate(vectorOfWeakReferences: UInt64, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.vectorOfWeakReferences.v); return _accessor.directMutate(vectorOfWeakReferences, index: _accessor.vector(at: o) + index * 8) } + public func withUnsafePointerToVectorOfWeakReferences(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VTOFFSET.vectorOfWeakReferences.v, body: body) } + public var vectorOfStrongReferrables: FlatbufferVector { return _accessor.vector(at: VTOFFSET.vectorOfStrongReferrables.v, byteSize: 4) } + public func vectorOfStrongReferrablesBy(key: UInt64) -> MyGame_Example_Referrable? { let o = _accessor.offset(VTOFFSET.vectorOfStrongReferrables.v); return o == 0 ? nil : MyGame_Example_Referrable.lookupByKey(vector: _accessor.vector(at: o), key: key, fbb: _accessor.bb) } + public var coOwningReference: UInt64 { let o = _accessor.offset(VTOFFSET.coOwningReference.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt64.self, at: o) } + @discardableResult public func mutate(coOwningReference: UInt64) -> Bool {let o = _accessor.offset(VTOFFSET.coOwningReference.v); return _accessor.mutate(coOwningReference, index: o) } + public var vectorOfCoOwningReferences: FlatbufferVector { return _accessor.vector(at: VTOFFSET.vectorOfCoOwningReferences.v, byteSize: 8) } + public func mutate(vectorOfCoOwningReferences: UInt64, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.vectorOfCoOwningReferences.v); return _accessor.directMutate(vectorOfCoOwningReferences, index: _accessor.vector(at: o) + index * 8) } + public func withUnsafePointerToVectorOfCoOwningReferences(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VTOFFSET.vectorOfCoOwningReferences.v, body: body) } + public var nonOwningReference: UInt64 { let o = _accessor.offset(VTOFFSET.nonOwningReference.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt64.self, at: o) } + @discardableResult public func mutate(nonOwningReference: UInt64) -> Bool {let o = _accessor.offset(VTOFFSET.nonOwningReference.v); return _accessor.mutate(nonOwningReference, index: o) } + public var vectorOfNonOwningReferences: FlatbufferVector { return _accessor.vector(at: VTOFFSET.vectorOfNonOwningReferences.v, byteSize: 8) } + public func mutate(vectorOfNonOwningReferences: UInt64, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.vectorOfNonOwningReferences.v); return _accessor.directMutate(vectorOfNonOwningReferences, index: _accessor.vector(at: o) + index * 8) } + public func withUnsafePointerToVectorOfNonOwningReferences(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VTOFFSET.vectorOfNonOwningReferences.v, body: body) } + public var anyUniqueType: MyGame_Example_AnyUniqueAliases { let o = _accessor.offset(VTOFFSET.anyUniqueType.v); return o == 0 ? .none_ : MyGame_Example_AnyUniqueAliases(rawValue: _accessor.readBuffer(of: UInt8.self, at: o)) ?? .none_ } + public func anyUnique(type: T.Type) -> T? { let o = _accessor.offset(VTOFFSET.anyUnique.v); return o == 0 ? nil : _accessor.union(o) } + public var anyAmbiguousType: MyGame_Example_AnyAmbiguousAliases { let o = _accessor.offset(VTOFFSET.anyAmbiguousType.v); return o == 0 ? .none_ : MyGame_Example_AnyAmbiguousAliases(rawValue: _accessor.readBuffer(of: UInt8.self, at: o)) ?? .none_ } + public func anyAmbiguous(type: T.Type) -> T? { let o = _accessor.offset(VTOFFSET.anyAmbiguous.v); return o == 0 ? nil : _accessor.union(o) } + public var vectorOfEnums: FlatbufferVector { return _accessor.vector(at: VTOFFSET.vectorOfEnums.v, byteSize: 1) } + public var signedEnum: MyGame_Example_Race { let o = _accessor.offset(VTOFFSET.signedEnum.v); return o == 0 ? .none_ : MyGame_Example_Race(rawValue: _accessor.readBuffer(of: Int8.self, at: o)) ?? .none_ } + @discardableResult public func mutate(signedEnum: MyGame_Example_Race) -> Bool {let o = _accessor.offset(VTOFFSET.signedEnum.v); return _accessor.mutate(signedEnum.rawValue, index: o) } + public var testrequirednestedflatbuffer: FlatbufferVector { return _accessor.vector(at: VTOFFSET.testrequirednestedflatbuffer.v, byteSize: 1) } + public func mutate(testrequirednestedflatbuffer: UInt8, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.testrequirednestedflatbuffer.v); return _accessor.directMutate(testrequirednestedflatbuffer, index: _accessor.vector(at: o) + index * 1) } + public func withUnsafePointerToTestrequirednestedflatbuffer(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VTOFFSET.testrequirednestedflatbuffer.v, body: body) } + public var scalarKeySortedTables: FlatbufferVector { return _accessor.vector(at: VTOFFSET.scalarKeySortedTables.v, byteSize: 4) } + public func scalarKeySortedTablesBy(key: UInt16) -> MyGame_Example_Stat? { let o = _accessor.offset(VTOFFSET.scalarKeySortedTables.v); return o == 0 ? nil : MyGame_Example_Stat.lookupByKey(vector: _accessor.vector(at: o), key: key, fbb: _accessor.bb) } + public var nativeInline: MyGame_Example_Test? { let o = _accessor.offset(VTOFFSET.nativeInline.v); return o == 0 ? nil : _accessor.readBuffer(of: MyGame_Example_Test.self, at: o) } + public var mutableNativeInline: MyGame_Example_Test_Mutable? { let o = _accessor.offset(VTOFFSET.nativeInline.v); return o == 0 ? nil : MyGame_Example_Test_Mutable(_accessor.bb, o: o + _accessor.position) } + public var longEnumNonEnumDefault: MyGame_Example_LongEnum { let o = _accessor.offset(VTOFFSET.longEnumNonEnumDefault.v); return o == 0 ? .longone : MyGame_Example_LongEnum(rawValue: _accessor.readBuffer(of: UInt64.self, at: o)) ?? .longone } + @discardableResult public func mutate(longEnumNonEnumDefault: MyGame_Example_LongEnum) -> Bool {let o = _accessor.offset(VTOFFSET.longEnumNonEnumDefault.v); return _accessor.mutate(longEnumNonEnumDefault.rawValue, index: o) } + public var longEnumNormalDefault: MyGame_Example_LongEnum { let o = _accessor.offset(VTOFFSET.longEnumNormalDefault.v); return o == 0 ? .longone : MyGame_Example_LongEnum(rawValue: _accessor.readBuffer(of: UInt64.self, at: o)) ?? .longone } + @discardableResult public func mutate(longEnumNormalDefault: MyGame_Example_LongEnum) -> Bool {let o = _accessor.offset(VTOFFSET.longEnumNormalDefault.v); return _accessor.mutate(longEnumNormalDefault.rawValue, index: o) } + public var nanDefault: Float32 { let o = _accessor.offset(VTOFFSET.nanDefault.v); return o == 0 ? .nan : _accessor.readBuffer(of: Float32.self, at: o) } + @discardableResult public func mutate(nanDefault: Float32) -> Bool {let o = _accessor.offset(VTOFFSET.nanDefault.v); return _accessor.mutate(nanDefault, index: o) } + public var infDefault: Float32 { let o = _accessor.offset(VTOFFSET.infDefault.v); return o == 0 ? .infinity : _accessor.readBuffer(of: Float32.self, at: o) } + @discardableResult public func mutate(infDefault: Float32) -> Bool {let o = _accessor.offset(VTOFFSET.infDefault.v); return _accessor.mutate(infDefault, index: o) } + public var positiveInfDefault: Float32 { let o = _accessor.offset(VTOFFSET.positiveInfDefault.v); return o == 0 ? .infinity : _accessor.readBuffer(of: Float32.self, at: o) } + @discardableResult public func mutate(positiveInfDefault: Float32) -> Bool {let o = _accessor.offset(VTOFFSET.positiveInfDefault.v); return _accessor.mutate(positiveInfDefault, index: o) } + public var infinityDefault: Float32 { let o = _accessor.offset(VTOFFSET.infinityDefault.v); return o == 0 ? .infinity : _accessor.readBuffer(of: Float32.self, at: o) } + @discardableResult public func mutate(infinityDefault: Float32) -> Bool {let o = _accessor.offset(VTOFFSET.infinityDefault.v); return _accessor.mutate(infinityDefault, index: o) } + public var positiveInfinityDefault: Float32 { let o = _accessor.offset(VTOFFSET.positiveInfinityDefault.v); return o == 0 ? .infinity : _accessor.readBuffer(of: Float32.self, at: o) } + @discardableResult public func mutate(positiveInfinityDefault: Float32) -> Bool {let o = _accessor.offset(VTOFFSET.positiveInfinityDefault.v); return _accessor.mutate(positiveInfinityDefault, index: o) } + public var negativeInfDefault: Float32 { let o = _accessor.offset(VTOFFSET.negativeInfDefault.v); return o == 0 ? -.infinity : _accessor.readBuffer(of: Float32.self, at: o) } + @discardableResult public func mutate(negativeInfDefault: Float32) -> Bool {let o = _accessor.offset(VTOFFSET.negativeInfDefault.v); return _accessor.mutate(negativeInfDefault, index: o) } + public var negativeInfinityDefault: Float32 { let o = _accessor.offset(VTOFFSET.negativeInfinityDefault.v); return o == 0 ? -.infinity : _accessor.readBuffer(of: Float32.self, at: o) } + @discardableResult public func mutate(negativeInfinityDefault: Float32) -> Bool {let o = _accessor.offset(VTOFFSET.negativeInfinityDefault.v); return _accessor.mutate(negativeInfinityDefault, index: o) } + public var doubleInfDefault: Double { let o = _accessor.offset(VTOFFSET.doubleInfDefault.v); return o == 0 ? .infinity : _accessor.readBuffer(of: Double.self, at: o) } + @discardableResult public func mutate(doubleInfDefault: Double) -> Bool {let o = _accessor.offset(VTOFFSET.doubleInfDefault.v); return _accessor.mutate(doubleInfDefault, index: o) } public static func startMonster(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 62) } - public static func add(pos: MyGame_Example_Vec3?, _ fbb: inout FlatBufferBuilder) { guard let pos = pos else { return }; fbb.create(struct: pos, position: VT.pos) } - public static func add(mana: Int16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: mana, def: 150, at: VT.mana) } - public static func add(hp: Int16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: hp, def: 100, at: VT.hp) } - public static func add(name: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: name, at: VT.name) } - public static func addVectorOf(inventory: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: inventory, at: VT.inventory) } - public static func add(color: MyGame_Example_Color, _ fbb: inout FlatBufferBuilder) { fbb.add(element: color.rawValue, def: 8, at: VT.color) } - public static func add(testType: MyGame_Example_Any_, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testType.rawValue, def: 0, at: VT.testType) } - public static func add(test: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: test, at: VT.test) } - public static func addVectorOf(test4: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: test4, at: VT.test4) } + public static func add(pos: MyGame_Example_Vec3?, _ fbb: inout FlatBufferBuilder) { guard let pos = pos else { return }; fbb.create(struct: pos, position: VTOFFSET.pos.p) } + public static func add(mana: Int16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: mana, def: 150, at: VTOFFSET.mana.p) } + public static func add(hp: Int16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: hp, def: 100, at: VTOFFSET.hp.p) } + public static func add(name: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: name, at: VTOFFSET.name.p) } + public static func addVectorOf(inventory: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: inventory, at: VTOFFSET.inventory.p) } + public static func add(color: MyGame_Example_Color, _ fbb: inout FlatBufferBuilder) { fbb.add(element: color.rawValue, def: 8, at: VTOFFSET.color.p) } + public static func add(testType: MyGame_Example_Any_, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testType.rawValue, def: 0, at: VTOFFSET.testType.p) } + public static func add(test: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: test, at: VTOFFSET.test.p) } + public static func addVectorOf(test4: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: test4, at: VTOFFSET.test4.p) } public static func startVectorOfTest4(_ size: Int, in builder: inout FlatBufferBuilder) { builder.startVector(size * MemoryLayout.size, elementSize: MemoryLayout.alignment) } - public static func addVectorOf(testarrayofstring: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testarrayofstring, at: VT.testarrayofstring) } - public static func addVectorOf(testarrayoftables: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testarrayoftables, at: VT.testarrayoftables) } - public static func add(enemy: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: enemy, at: VT.enemy) } - public static func addVectorOf(testnestedflatbuffer: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testnestedflatbuffer, at: VT.testnestedflatbuffer) } - public static func add(testempty: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testempty, at: VT.testempty) } + public static func addVectorOf(testarrayofstring: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testarrayofstring, at: VTOFFSET.testarrayofstring.p) } + public static func addVectorOf(testarrayoftables: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testarrayoftables, at: VTOFFSET.testarrayoftables.p) } + public static func add(enemy: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: enemy, at: VTOFFSET.enemy.p) } + public static func addVectorOf(testnestedflatbuffer: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testnestedflatbuffer, at: VTOFFSET.testnestedflatbuffer.p) } + public static func add(testempty: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testempty, at: VTOFFSET.testempty.p) } public static func add(testbool: Bool, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testbool, def: false, - at: VT.testbool) } - public static func add(testhashs32Fnv1: Int32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashs32Fnv1, def: 0, at: VT.testhashs32Fnv1) } - public static func add(testhashu32Fnv1: UInt32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashu32Fnv1, def: 0, at: VT.testhashu32Fnv1) } - public static func add(testhashs64Fnv1: Int64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashs64Fnv1, def: 0, at: VT.testhashs64Fnv1) } - public static func add(testhashu64Fnv1: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashu64Fnv1, def: 0, at: VT.testhashu64Fnv1) } - public static func add(testhashs32Fnv1a: Int32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashs32Fnv1a, def: 0, at: VT.testhashs32Fnv1a) } - public static func add(testhashu32Fnv1a: UInt32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashu32Fnv1a, def: 0, at: VT.testhashu32Fnv1a) } - public static func add(testhashs64Fnv1a: Int64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashs64Fnv1a, def: 0, at: VT.testhashs64Fnv1a) } - public static func add(testhashu64Fnv1a: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashu64Fnv1a, def: 0, at: VT.testhashu64Fnv1a) } - public static func addVectorOf(testarrayofbools: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testarrayofbools, at: VT.testarrayofbools) } - public static func add(testf: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testf, def: 3.14159, at: VT.testf) } - public static func add(testf2: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testf2, def: 3.0, at: VT.testf2) } - public static func add(testf3: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testf3, def: 0.0, at: VT.testf3) } - public static func addVectorOf(testarrayofstring2: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testarrayofstring2, at: VT.testarrayofstring2) } - public static func addVectorOf(testarrayofsortedstruct: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testarrayofsortedstruct, at: VT.testarrayofsortedstruct) } + at: VTOFFSET.testbool.p) } + public static func add(testhashs32Fnv1: Int32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashs32Fnv1, def: 0, at: VTOFFSET.testhashs32Fnv1.p) } + public static func add(testhashu32Fnv1: UInt32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashu32Fnv1, def: 0, at: VTOFFSET.testhashu32Fnv1.p) } + public static func add(testhashs64Fnv1: Int64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashs64Fnv1, def: 0, at: VTOFFSET.testhashs64Fnv1.p) } + public static func add(testhashu64Fnv1: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashu64Fnv1, def: 0, at: VTOFFSET.testhashu64Fnv1.p) } + public static func add(testhashs32Fnv1a: Int32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashs32Fnv1a, def: 0, at: VTOFFSET.testhashs32Fnv1a.p) } + public static func add(testhashu32Fnv1a: UInt32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashu32Fnv1a, def: 0, at: VTOFFSET.testhashu32Fnv1a.p) } + public static func add(testhashs64Fnv1a: Int64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashs64Fnv1a, def: 0, at: VTOFFSET.testhashs64Fnv1a.p) } + public static func add(testhashu64Fnv1a: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashu64Fnv1a, def: 0, at: VTOFFSET.testhashu64Fnv1a.p) } + public static func addVectorOf(testarrayofbools: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testarrayofbools, at: VTOFFSET.testarrayofbools.p) } + public static func add(testf: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testf, def: 3.14159, at: VTOFFSET.testf.p) } + public static func add(testf2: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testf2, def: 3.0, at: VTOFFSET.testf2.p) } + public static func add(testf3: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testf3, def: 0.0, at: VTOFFSET.testf3.p) } + public static func addVectorOf(testarrayofstring2: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testarrayofstring2, at: VTOFFSET.testarrayofstring2.p) } + public static func addVectorOf(testarrayofsortedstruct: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testarrayofsortedstruct, at: VTOFFSET.testarrayofsortedstruct.p) } public static func startVectorOfTestarrayofsortedstruct(_ size: Int, in builder: inout FlatBufferBuilder) { builder.startVector(size * MemoryLayout.size, elementSize: MemoryLayout.alignment) } - public static func addVectorOf(flex: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: flex, at: VT.flex) } - public static func addVectorOf(test5: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: test5, at: VT.test5) } + public static func addVectorOf(flex: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: flex, at: VTOFFSET.flex.p) } + public static func addVectorOf(test5: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: test5, at: VTOFFSET.test5.p) } public static func startVectorOfTest5(_ size: Int, in builder: inout FlatBufferBuilder) { builder.startVector(size * MemoryLayout.size, elementSize: MemoryLayout.alignment) } - public static func addVectorOf(vectorOfLongs: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfLongs, at: VT.vectorOfLongs) } - public static func addVectorOf(vectorOfDoubles: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfDoubles, at: VT.vectorOfDoubles) } - public static func add(parentNamespaceTest: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: parentNamespaceTest, at: VT.parentNamespaceTest) } - public static func addVectorOf(vectorOfReferrables: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfReferrables, at: VT.vectorOfReferrables) } - public static func add(singleWeakReference: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: singleWeakReference, def: 0, at: VT.singleWeakReference) } - public static func addVectorOf(vectorOfWeakReferences: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfWeakReferences, at: VT.vectorOfWeakReferences) } - public static func addVectorOf(vectorOfStrongReferrables: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfStrongReferrables, at: VT.vectorOfStrongReferrables) } - public static func add(coOwningReference: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: coOwningReference, def: 0, at: VT.coOwningReference) } - public static func addVectorOf(vectorOfCoOwningReferences: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfCoOwningReferences, at: VT.vectorOfCoOwningReferences) } - public static func add(nonOwningReference: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: nonOwningReference, def: 0, at: VT.nonOwningReference) } - public static func addVectorOf(vectorOfNonOwningReferences: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfNonOwningReferences, at: VT.vectorOfNonOwningReferences) } - public static func add(anyUniqueType: MyGame_Example_AnyUniqueAliases, _ fbb: inout FlatBufferBuilder) { fbb.add(element: anyUniqueType.rawValue, def: 0, at: VT.anyUniqueType) } - public static func add(anyUnique: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: anyUnique, at: VT.anyUnique) } - public static func add(anyAmbiguousType: MyGame_Example_AnyAmbiguousAliases, _ fbb: inout FlatBufferBuilder) { fbb.add(element: anyAmbiguousType.rawValue, def: 0, at: VT.anyAmbiguousType) } - public static func add(anyAmbiguous: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: anyAmbiguous, at: VT.anyAmbiguous) } - public static func addVectorOf(vectorOfEnums: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfEnums, at: VT.vectorOfEnums) } - public static func add(signedEnum: MyGame_Example_Race, _ fbb: inout FlatBufferBuilder) { fbb.add(element: signedEnum.rawValue, def: -1, at: VT.signedEnum) } - public static func addVectorOf(testrequirednestedflatbuffer: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testrequirednestedflatbuffer, at: VT.testrequirednestedflatbuffer) } - public static func addVectorOf(scalarKeySortedTables: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: scalarKeySortedTables, at: VT.scalarKeySortedTables) } - public static func add(nativeInline: MyGame_Example_Test?, _ fbb: inout FlatBufferBuilder) { guard let nativeInline = nativeInline else { return }; fbb.create(struct: nativeInline, position: VT.nativeInline) } - public static func add(longEnumNonEnumDefault: MyGame_Example_LongEnum, _ fbb: inout FlatBufferBuilder) { fbb.add(element: longEnumNonEnumDefault.rawValue, def: 0, at: VT.longEnumNonEnumDefault) } - public static func add(longEnumNormalDefault: MyGame_Example_LongEnum, _ fbb: inout FlatBufferBuilder) { fbb.add(element: longEnumNormalDefault.rawValue, def: 2, at: VT.longEnumNormalDefault) } - public static func add(nanDefault: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: nanDefault, def: .nan, at: VT.nanDefault) } - public static func add(infDefault: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: infDefault, def: .infinity, at: VT.infDefault) } - public static func add(positiveInfDefault: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: positiveInfDefault, def: .infinity, at: VT.positiveInfDefault) } - public static func add(infinityDefault: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: infinityDefault, def: .infinity, at: VT.infinityDefault) } - public static func add(positiveInfinityDefault: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: positiveInfinityDefault, def: .infinity, at: VT.positiveInfinityDefault) } - public static func add(negativeInfDefault: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: negativeInfDefault, def: -.infinity, at: VT.negativeInfDefault) } - public static func add(negativeInfinityDefault: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: negativeInfinityDefault, def: -.infinity, at: VT.negativeInfinityDefault) } - public static func add(doubleInfDefault: Double, _ fbb: inout FlatBufferBuilder) { fbb.add(element: doubleInfDefault, def: .infinity, at: VT.doubleInfDefault) } + public static func addVectorOf(vectorOfLongs: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfLongs, at: VTOFFSET.vectorOfLongs.p) } + public static func addVectorOf(vectorOfDoubles: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfDoubles, at: VTOFFSET.vectorOfDoubles.p) } + public static func add(parentNamespaceTest: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: parentNamespaceTest, at: VTOFFSET.parentNamespaceTest.p) } + public static func addVectorOf(vectorOfReferrables: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfReferrables, at: VTOFFSET.vectorOfReferrables.p) } + public static func add(singleWeakReference: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: singleWeakReference, def: 0, at: VTOFFSET.singleWeakReference.p) } + public static func addVectorOf(vectorOfWeakReferences: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfWeakReferences, at: VTOFFSET.vectorOfWeakReferences.p) } + public static func addVectorOf(vectorOfStrongReferrables: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfStrongReferrables, at: VTOFFSET.vectorOfStrongReferrables.p) } + public static func add(coOwningReference: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: coOwningReference, def: 0, at: VTOFFSET.coOwningReference.p) } + public static func addVectorOf(vectorOfCoOwningReferences: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfCoOwningReferences, at: VTOFFSET.vectorOfCoOwningReferences.p) } + public static func add(nonOwningReference: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: nonOwningReference, def: 0, at: VTOFFSET.nonOwningReference.p) } + public static func addVectorOf(vectorOfNonOwningReferences: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfNonOwningReferences, at: VTOFFSET.vectorOfNonOwningReferences.p) } + public static func add(anyUniqueType: MyGame_Example_AnyUniqueAliases, _ fbb: inout FlatBufferBuilder) { fbb.add(element: anyUniqueType.rawValue, def: 0, at: VTOFFSET.anyUniqueType.p) } + public static func add(anyUnique: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: anyUnique, at: VTOFFSET.anyUnique.p) } + public static func add(anyAmbiguousType: MyGame_Example_AnyAmbiguousAliases, _ fbb: inout FlatBufferBuilder) { fbb.add(element: anyAmbiguousType.rawValue, def: 0, at: VTOFFSET.anyAmbiguousType.p) } + public static func add(anyAmbiguous: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: anyAmbiguous, at: VTOFFSET.anyAmbiguous.p) } + public static func addVectorOf(vectorOfEnums: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfEnums, at: VTOFFSET.vectorOfEnums.p) } + public static func add(signedEnum: MyGame_Example_Race, _ fbb: inout FlatBufferBuilder) { fbb.add(element: signedEnum.rawValue, def: -1, at: VTOFFSET.signedEnum.p) } + public static func addVectorOf(testrequirednestedflatbuffer: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testrequirednestedflatbuffer, at: VTOFFSET.testrequirednestedflatbuffer.p) } + public static func addVectorOf(scalarKeySortedTables: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: scalarKeySortedTables, at: VTOFFSET.scalarKeySortedTables.p) } + public static func add(nativeInline: MyGame_Example_Test?, _ fbb: inout FlatBufferBuilder) { guard let nativeInline = nativeInline else { return }; fbb.create(struct: nativeInline, position: VTOFFSET.nativeInline.p) } + public static func add(longEnumNonEnumDefault: MyGame_Example_LongEnum, _ fbb: inout FlatBufferBuilder) { fbb.add(element: longEnumNonEnumDefault.rawValue, def: 0, at: VTOFFSET.longEnumNonEnumDefault.p) } + public static func add(longEnumNormalDefault: MyGame_Example_LongEnum, _ fbb: inout FlatBufferBuilder) { fbb.add(element: longEnumNormalDefault.rawValue, def: 2, at: VTOFFSET.longEnumNormalDefault.p) } + public static func add(nanDefault: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: nanDefault, def: .nan, at: VTOFFSET.nanDefault.p) } + public static func add(infDefault: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: infDefault, def: .infinity, at: VTOFFSET.infDefault.p) } + public static func add(positiveInfDefault: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: positiveInfDefault, def: .infinity, at: VTOFFSET.positiveInfDefault.p) } + public static func add(infinityDefault: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: infinityDefault, def: .infinity, at: VTOFFSET.infinityDefault.p) } + public static func add(positiveInfinityDefault: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: positiveInfinityDefault, def: .infinity, at: VTOFFSET.positiveInfinityDefault.p) } + public static func add(negativeInfDefault: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: negativeInfDefault, def: -.infinity, at: VTOFFSET.negativeInfDefault.p) } + public static func add(negativeInfinityDefault: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: negativeInfinityDefault, def: -.infinity, at: VTOFFSET.negativeInfinityDefault.p) } + public static func add(doubleInfDefault: Double, _ fbb: inout FlatBufferBuilder) { fbb.add(element: doubleInfDefault, def: .infinity, at: VTOFFSET.doubleInfDefault.p) } public static func endMonster(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); fbb.require(table: end, fields: [10]); return end } public static func createMonster( _ fbb: inout FlatBufferBuilder, @@ -1646,13 +1656,13 @@ public struct MyGame_Example_Monster: FlatBufferVerifiableTable, FlatbuffersVect public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { var _v = try verifier.visitTable(at: position) - try _v.visit(field: VT.pos, fieldName: "pos", required: false, type: MyGame_Example_Vec3.self) - try _v.visit(field: VT.mana, fieldName: "mana", required: false, type: Int16.self) - try _v.visit(field: VT.hp, fieldName: "hp", required: false, type: Int16.self) - try _v.visit(field: VT.name, fieldName: "name", required: true, type: ForwardOffset.self) - try _v.visit(field: VT.inventory, fieldName: "inventory", required: false, type: ForwardOffset>.self) - try _v.visit(field: VT.color, fieldName: "color", required: false, type: MyGame_Example_Color.self) - try _v.visit(unionKey: VT.testType, unionField: VT.test, unionKeyName: "testType", fieldName: "test", required: false, completion: { (verifier, key: MyGame_Example_Any_, pos) in + try _v.visit(field: VTOFFSET.pos.p, fieldName: "pos", required: false, type: MyGame_Example_Vec3.self) + try _v.visit(field: VTOFFSET.mana.p, fieldName: "mana", required: false, type: Int16.self) + try _v.visit(field: VTOFFSET.hp.p, fieldName: "hp", required: false, type: Int16.self) + try _v.visit(field: VTOFFSET.name.p, fieldName: "name", required: true, type: ForwardOffset.self) + try _v.visit(field: VTOFFSET.inventory.p, fieldName: "inventory", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.color.p, fieldName: "color", required: false, type: MyGame_Example_Color.self) + try _v.visit(unionKey: VTOFFSET.testType.p, unionField: VTOFFSET.test.p, unionKeyName: "testType", fieldName: "test", required: false, completion: { (verifier, key: MyGame_Example_Any_, pos) in switch key { case .none_: break // NOTE - SWIFT doesnt support none @@ -1664,41 +1674,41 @@ public struct MyGame_Example_Monster: FlatBufferVerifiableTable, FlatbuffersVect try ForwardOffset.verify(&verifier, at: pos, of: MyGame_Example2_Monster.self) } }) - try _v.visit(field: VT.test4, fieldName: "test4", required: false, type: ForwardOffset>.self) - try _v.visit(field: VT.testarrayofstring, fieldName: "testarrayofstring", required: false, type: ForwardOffset, String>>.self) - try _v.visit(field: VT.testarrayoftables, fieldName: "testarrayoftables", required: false, type: ForwardOffset, MyGame_Example_Monster>>.self) - try _v.visit(field: VT.enemy, fieldName: "enemy", required: false, type: ForwardOffset.self) - try _v.visit(field: VT.testnestedflatbuffer, fieldName: "testnestedflatbuffer", required: false, type: ForwardOffset>.self) - try _v.visit(field: VT.testempty, fieldName: "testempty", required: false, type: ForwardOffset.self) - try _v.visit(field: VT.testbool, fieldName: "testbool", required: false, type: Bool.self) - try _v.visit(field: VT.testhashs32Fnv1, fieldName: "testhashs32Fnv1", required: false, type: Int32.self) - try _v.visit(field: VT.testhashu32Fnv1, fieldName: "testhashu32Fnv1", required: false, type: UInt32.self) - try _v.visit(field: VT.testhashs64Fnv1, fieldName: "testhashs64Fnv1", required: false, type: Int64.self) - try _v.visit(field: VT.testhashu64Fnv1, fieldName: "testhashu64Fnv1", required: false, type: UInt64.self) - try _v.visit(field: VT.testhashs32Fnv1a, fieldName: "testhashs32Fnv1a", required: false, type: Int32.self) - try _v.visit(field: VT.testhashu32Fnv1a, fieldName: "testhashu32Fnv1a", required: false, type: UInt32.self) - try _v.visit(field: VT.testhashs64Fnv1a, fieldName: "testhashs64Fnv1a", required: false, type: Int64.self) - try _v.visit(field: VT.testhashu64Fnv1a, fieldName: "testhashu64Fnv1a", required: false, type: UInt64.self) - try _v.visit(field: VT.testarrayofbools, fieldName: "testarrayofbools", required: false, type: ForwardOffset>.self) - try _v.visit(field: VT.testf, fieldName: "testf", required: false, type: Float32.self) - try _v.visit(field: VT.testf2, fieldName: "testf2", required: false, type: Float32.self) - try _v.visit(field: VT.testf3, fieldName: "testf3", required: false, type: Float32.self) - try _v.visit(field: VT.testarrayofstring2, fieldName: "testarrayofstring2", required: false, type: ForwardOffset, String>>.self) - try _v.visit(field: VT.testarrayofsortedstruct, fieldName: "testarrayofsortedstruct", required: false, type: ForwardOffset>.self) - try _v.visit(field: VT.flex, fieldName: "flex", required: false, type: ForwardOffset>.self) - try _v.visit(field: VT.test5, fieldName: "test5", required: false, type: ForwardOffset>.self) - try _v.visit(field: VT.vectorOfLongs, fieldName: "vectorOfLongs", required: false, type: ForwardOffset>.self) - try _v.visit(field: VT.vectorOfDoubles, fieldName: "vectorOfDoubles", required: false, type: ForwardOffset>.self) - try _v.visit(field: VT.parentNamespaceTest, fieldName: "parentNamespaceTest", required: false, type: ForwardOffset.self) - try _v.visit(field: VT.vectorOfReferrables, fieldName: "vectorOfReferrables", required: false, type: ForwardOffset, MyGame_Example_Referrable>>.self) - try _v.visit(field: VT.singleWeakReference, fieldName: "singleWeakReference", required: false, type: UInt64.self) - try _v.visit(field: VT.vectorOfWeakReferences, fieldName: "vectorOfWeakReferences", required: false, type: ForwardOffset>.self) - try _v.visit(field: VT.vectorOfStrongReferrables, fieldName: "vectorOfStrongReferrables", required: false, type: ForwardOffset, MyGame_Example_Referrable>>.self) - try _v.visit(field: VT.coOwningReference, fieldName: "coOwningReference", required: false, type: UInt64.self) - try _v.visit(field: VT.vectorOfCoOwningReferences, fieldName: "vectorOfCoOwningReferences", required: false, type: ForwardOffset>.self) - try _v.visit(field: VT.nonOwningReference, fieldName: "nonOwningReference", required: false, type: UInt64.self) - try _v.visit(field: VT.vectorOfNonOwningReferences, fieldName: "vectorOfNonOwningReferences", required: false, type: ForwardOffset>.self) - try _v.visit(unionKey: VT.anyUniqueType, unionField: VT.anyUnique, unionKeyName: "anyUniqueType", fieldName: "anyUnique", required: false, completion: { (verifier, key: MyGame_Example_AnyUniqueAliases, pos) in + try _v.visit(field: VTOFFSET.test4.p, fieldName: "test4", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.testarrayofstring.p, fieldName: "testarrayofstring", required: false, type: ForwardOffset, String>>.self) + try _v.visit(field: VTOFFSET.testarrayoftables.p, fieldName: "testarrayoftables", required: false, type: ForwardOffset, MyGame_Example_Monster>>.self) + try _v.visit(field: VTOFFSET.enemy.p, fieldName: "enemy", required: false, type: ForwardOffset.self) + try _v.visit(field: VTOFFSET.testnestedflatbuffer.p, fieldName: "testnestedflatbuffer", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.testempty.p, fieldName: "testempty", required: false, type: ForwardOffset.self) + try _v.visit(field: VTOFFSET.testbool.p, fieldName: "testbool", required: false, type: Bool.self) + try _v.visit(field: VTOFFSET.testhashs32Fnv1.p, fieldName: "testhashs32Fnv1", required: false, type: Int32.self) + try _v.visit(field: VTOFFSET.testhashu32Fnv1.p, fieldName: "testhashu32Fnv1", required: false, type: UInt32.self) + try _v.visit(field: VTOFFSET.testhashs64Fnv1.p, fieldName: "testhashs64Fnv1", required: false, type: Int64.self) + try _v.visit(field: VTOFFSET.testhashu64Fnv1.p, fieldName: "testhashu64Fnv1", required: false, type: UInt64.self) + try _v.visit(field: VTOFFSET.testhashs32Fnv1a.p, fieldName: "testhashs32Fnv1a", required: false, type: Int32.self) + try _v.visit(field: VTOFFSET.testhashu32Fnv1a.p, fieldName: "testhashu32Fnv1a", required: false, type: UInt32.self) + try _v.visit(field: VTOFFSET.testhashs64Fnv1a.p, fieldName: "testhashs64Fnv1a", required: false, type: Int64.self) + try _v.visit(field: VTOFFSET.testhashu64Fnv1a.p, fieldName: "testhashu64Fnv1a", required: false, type: UInt64.self) + try _v.visit(field: VTOFFSET.testarrayofbools.p, fieldName: "testarrayofbools", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.testf.p, fieldName: "testf", required: false, type: Float32.self) + try _v.visit(field: VTOFFSET.testf2.p, fieldName: "testf2", required: false, type: Float32.self) + try _v.visit(field: VTOFFSET.testf3.p, fieldName: "testf3", required: false, type: Float32.self) + try _v.visit(field: VTOFFSET.testarrayofstring2.p, fieldName: "testarrayofstring2", required: false, type: ForwardOffset, String>>.self) + try _v.visit(field: VTOFFSET.testarrayofsortedstruct.p, fieldName: "testarrayofsortedstruct", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.flex.p, fieldName: "flex", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.test5.p, fieldName: "test5", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.vectorOfLongs.p, fieldName: "vectorOfLongs", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.vectorOfDoubles.p, fieldName: "vectorOfDoubles", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.parentNamespaceTest.p, fieldName: "parentNamespaceTest", required: false, type: ForwardOffset.self) + try _v.visit(field: VTOFFSET.vectorOfReferrables.p, fieldName: "vectorOfReferrables", required: false, type: ForwardOffset, MyGame_Example_Referrable>>.self) + try _v.visit(field: VTOFFSET.singleWeakReference.p, fieldName: "singleWeakReference", required: false, type: UInt64.self) + try _v.visit(field: VTOFFSET.vectorOfWeakReferences.p, fieldName: "vectorOfWeakReferences", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.vectorOfStrongReferrables.p, fieldName: "vectorOfStrongReferrables", required: false, type: ForwardOffset, MyGame_Example_Referrable>>.self) + try _v.visit(field: VTOFFSET.coOwningReference.p, fieldName: "coOwningReference", required: false, type: UInt64.self) + try _v.visit(field: VTOFFSET.vectorOfCoOwningReferences.p, fieldName: "vectorOfCoOwningReferences", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.nonOwningReference.p, fieldName: "nonOwningReference", required: false, type: UInt64.self) + try _v.visit(field: VTOFFSET.vectorOfNonOwningReferences.p, fieldName: "vectorOfNonOwningReferences", required: false, type: ForwardOffset>.self) + try _v.visit(unionKey: VTOFFSET.anyUniqueType.p, unionField: VTOFFSET.anyUnique.p, unionKeyName: "anyUniqueType", fieldName: "anyUnique", required: false, completion: { (verifier, key: MyGame_Example_AnyUniqueAliases, pos) in switch key { case .none_: break // NOTE - SWIFT doesnt support none @@ -1710,7 +1720,7 @@ public struct MyGame_Example_Monster: FlatBufferVerifiableTable, FlatbuffersVect try ForwardOffset.verify(&verifier, at: pos, of: MyGame_Example2_Monster.self) } }) - try _v.visit(unionKey: VT.anyAmbiguousType, unionField: VT.anyAmbiguous, unionKeyName: "anyAmbiguousType", fieldName: "anyAmbiguous", required: false, completion: { (verifier, key: MyGame_Example_AnyAmbiguousAliases, pos) in + try _v.visit(unionKey: VTOFFSET.anyAmbiguousType.p, unionField: VTOFFSET.anyAmbiguous.p, unionKeyName: "anyAmbiguousType", fieldName: "anyAmbiguous", required: false, completion: { (verifier, key: MyGame_Example_AnyAmbiguousAliases, pos) in switch key { case .none_: break // NOTE - SWIFT doesnt support none @@ -1722,26 +1732,27 @@ public struct MyGame_Example_Monster: FlatBufferVerifiableTable, FlatbuffersVect try ForwardOffset.verify(&verifier, at: pos, of: MyGame_Example_Monster.self) } }) - try _v.visit(field: VT.vectorOfEnums, fieldName: "vectorOfEnums", required: false, type: ForwardOffset>.self) - try _v.visit(field: VT.signedEnum, fieldName: "signedEnum", required: false, type: MyGame_Example_Race.self) - try _v.visit(field: VT.testrequirednestedflatbuffer, fieldName: "testrequirednestedflatbuffer", required: false, type: ForwardOffset>.self) - try _v.visit(field: VT.scalarKeySortedTables, fieldName: "scalarKeySortedTables", required: false, type: ForwardOffset, MyGame_Example_Stat>>.self) - try _v.visit(field: VT.nativeInline, fieldName: "nativeInline", required: false, type: MyGame_Example_Test.self) - try _v.visit(field: VT.longEnumNonEnumDefault, fieldName: "longEnumNonEnumDefault", required: false, type: MyGame_Example_LongEnum.self) - try _v.visit(field: VT.longEnumNormalDefault, fieldName: "longEnumNormalDefault", required: false, type: MyGame_Example_LongEnum.self) - try _v.visit(field: VT.nanDefault, fieldName: "nanDefault", required: false, type: Float32.self) - try _v.visit(field: VT.infDefault, fieldName: "infDefault", required: false, type: Float32.self) - try _v.visit(field: VT.positiveInfDefault, fieldName: "positiveInfDefault", required: false, type: Float32.self) - try _v.visit(field: VT.infinityDefault, fieldName: "infinityDefault", required: false, type: Float32.self) - try _v.visit(field: VT.positiveInfinityDefault, fieldName: "positiveInfinityDefault", required: false, type: Float32.self) - try _v.visit(field: VT.negativeInfDefault, fieldName: "negativeInfDefault", required: false, type: Float32.self) - try _v.visit(field: VT.negativeInfinityDefault, fieldName: "negativeInfinityDefault", required: false, type: Float32.self) - try _v.visit(field: VT.doubleInfDefault, fieldName: "doubleInfDefault", required: false, type: Double.self) + try _v.visit(field: VTOFFSET.vectorOfEnums.p, fieldName: "vectorOfEnums", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.signedEnum.p, fieldName: "signedEnum", required: false, type: MyGame_Example_Race.self) + try _v.visit(field: VTOFFSET.testrequirednestedflatbuffer.p, fieldName: "testrequirednestedflatbuffer", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.scalarKeySortedTables.p, fieldName: "scalarKeySortedTables", required: false, type: ForwardOffset, MyGame_Example_Stat>>.self) + try _v.visit(field: VTOFFSET.nativeInline.p, fieldName: "nativeInline", required: false, type: MyGame_Example_Test.self) + try _v.visit(field: VTOFFSET.longEnumNonEnumDefault.p, fieldName: "longEnumNonEnumDefault", required: false, type: MyGame_Example_LongEnum.self) + try _v.visit(field: VTOFFSET.longEnumNormalDefault.p, fieldName: "longEnumNormalDefault", required: false, type: MyGame_Example_LongEnum.self) + try _v.visit(field: VTOFFSET.nanDefault.p, fieldName: "nanDefault", required: false, type: Float32.self) + try _v.visit(field: VTOFFSET.infDefault.p, fieldName: "infDefault", required: false, type: Float32.self) + try _v.visit(field: VTOFFSET.positiveInfDefault.p, fieldName: "positiveInfDefault", required: false, type: Float32.self) + try _v.visit(field: VTOFFSET.infinityDefault.p, fieldName: "infinityDefault", required: false, type: Float32.self) + try _v.visit(field: VTOFFSET.positiveInfinityDefault.p, fieldName: "positiveInfinityDefault", required: false, type: Float32.self) + try _v.visit(field: VTOFFSET.negativeInfDefault.p, fieldName: "negativeInfDefault", required: false, type: Float32.self) + try _v.visit(field: VTOFFSET.negativeInfinityDefault.p, fieldName: "negativeInfinityDefault", required: false, type: Float32.self) + try _v.visit(field: VTOFFSET.doubleInfDefault.p, fieldName: "doubleInfDefault", required: false, type: Double.self) _v.finish() } } extension MyGame_Example_Monster: Encodable { + enum CodingKeys: String, CodingKey { case pos = "pos" case mana = "mana" @@ -1805,7 +1816,6 @@ extension MyGame_Example_Monster: Encodable { case negativeInfinityDefault = "negative_infinity_default" case doubleInfDefault = "double_inf_default" } - public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(pos, forKey: .pos) @@ -2213,7 +2223,7 @@ public class MyGame_Example_MonsterT: NativeObject { public func serialize() -> ByteBuffer { return serialize(type: MyGame_Example_Monster.self) } } -public struct MyGame_Example_TypeAliases: FlatBufferVerifiableTable, FlatbuffersVectorInitializable, ObjectAPIPacker { +public struct MyGame_Example_TypeAliases: FlatBufferTable, FlatbuffersVectorInitializable, Verifiable, ObjectAPIPacker { static func validateVersion() { FlatBuffersVersion_25_12_19() } public var __buffer: ByteBuffer! { return _accessor.bb } @@ -2224,60 +2234,62 @@ public struct MyGame_Example_TypeAliases: FlatBufferVerifiableTable, Flatbuffers private init(_ t: Table) { _accessor = t } public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } - private struct VT { - static let i8: VOffset = 4 - static let u8: VOffset = 6 - static let i16: VOffset = 8 - static let u16: VOffset = 10 - static let i32: VOffset = 12 - static let u32: VOffset = 14 - static let i64: VOffset = 16 - static let u64: VOffset = 18 - static let f32: VOffset = 20 - static let f64: VOffset = 22 - static let v8: VOffset = 24 - static let vf64: VOffset = 26 + private enum VTOFFSET: VOffset { + case i8 = 4 + case u8 = 6 + case i16 = 8 + case u16 = 10 + case i32 = 12 + case u32 = 14 + case i64 = 16 + case u64 = 18 + case f32 = 20 + case f64 = 22 + case v8 = 24 + case vf64 = 26 + var v: Int32 { Int32(self.rawValue) } + var p: VOffset { self.rawValue } } - public var i8: Int8 { let o = _accessor.offset(VT.i8); return o == 0 ? 0 : _accessor.readBuffer(of: Int8.self, at: o) } - @discardableResult public func mutate(i8: Int8) -> Bool {let o = _accessor.offset(VT.i8); return _accessor.mutate(i8, index: o) } - public var u8: UInt8 { let o = _accessor.offset(VT.u8); return o == 0 ? 0 : _accessor.readBuffer(of: UInt8.self, at: o) } - @discardableResult public func mutate(u8: UInt8) -> Bool {let o = _accessor.offset(VT.u8); return _accessor.mutate(u8, index: o) } - public var i16: Int16 { let o = _accessor.offset(VT.i16); return o == 0 ? 0 : _accessor.readBuffer(of: Int16.self, at: o) } - @discardableResult public func mutate(i16: Int16) -> Bool {let o = _accessor.offset(VT.i16); return _accessor.mutate(i16, index: o) } - public var u16: UInt16 { let o = _accessor.offset(VT.u16); return o == 0 ? 0 : _accessor.readBuffer(of: UInt16.self, at: o) } - @discardableResult public func mutate(u16: UInt16) -> Bool {let o = _accessor.offset(VT.u16); return _accessor.mutate(u16, index: o) } - public var i32: Int32 { let o = _accessor.offset(VT.i32); return o == 0 ? 0 : _accessor.readBuffer(of: Int32.self, at: o) } - @discardableResult public func mutate(i32: Int32) -> Bool {let o = _accessor.offset(VT.i32); return _accessor.mutate(i32, index: o) } - public var u32: UInt32 { let o = _accessor.offset(VT.u32); return o == 0 ? 0 : _accessor.readBuffer(of: UInt32.self, at: o) } - @discardableResult public func mutate(u32: UInt32) -> Bool {let o = _accessor.offset(VT.u32); return _accessor.mutate(u32, index: o) } - public var i64: Int64 { let o = _accessor.offset(VT.i64); return o == 0 ? 0 : _accessor.readBuffer(of: Int64.self, at: o) } - @discardableResult public func mutate(i64: Int64) -> Bool {let o = _accessor.offset(VT.i64); return _accessor.mutate(i64, index: o) } - public var u64: UInt64 { let o = _accessor.offset(VT.u64); return o == 0 ? 0 : _accessor.readBuffer(of: UInt64.self, at: o) } - @discardableResult public func mutate(u64: UInt64) -> Bool {let o = _accessor.offset(VT.u64); return _accessor.mutate(u64, index: o) } - public var f32: Float32 { let o = _accessor.offset(VT.f32); return o == 0 ? 0.0 : _accessor.readBuffer(of: Float32.self, at: o) } - @discardableResult public func mutate(f32: Float32) -> Bool {let o = _accessor.offset(VT.f32); return _accessor.mutate(f32, index: o) } - public var f64: Double { let o = _accessor.offset(VT.f64); return o == 0 ? 0.0 : _accessor.readBuffer(of: Double.self, at: o) } - @discardableResult public func mutate(f64: Double) -> Bool {let o = _accessor.offset(VT.f64); return _accessor.mutate(f64, index: o) } - public var v8: FlatbufferVector { return _accessor.vector(at: VT.v8, byteSize: 1) } - public func mutate(v8: Int8, at index: Int32) -> Bool { let o = _accessor.offset(VT.v8); return _accessor.directMutate(v8, index: _accessor.vector(at: o) + index * 1) } - public func withUnsafePointerToV8(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VT.v8, body: body) } - public var vf64: FlatbufferVector { return _accessor.vector(at: VT.vf64, byteSize: 8) } - public func mutate(vf64: Double, at index: Int32) -> Bool { let o = _accessor.offset(VT.vf64); return _accessor.directMutate(vf64, index: _accessor.vector(at: o) + index * 8) } - public func withUnsafePointerToVf64(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VT.vf64, body: body) } + public var i8: Int8 { let o = _accessor.offset(VTOFFSET.i8.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int8.self, at: o) } + @discardableResult public func mutate(i8: Int8) -> Bool {let o = _accessor.offset(VTOFFSET.i8.v); return _accessor.mutate(i8, index: o) } + public var u8: UInt8 { let o = _accessor.offset(VTOFFSET.u8.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt8.self, at: o) } + @discardableResult public func mutate(u8: UInt8) -> Bool {let o = _accessor.offset(VTOFFSET.u8.v); return _accessor.mutate(u8, index: o) } + public var i16: Int16 { let o = _accessor.offset(VTOFFSET.i16.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int16.self, at: o) } + @discardableResult public func mutate(i16: Int16) -> Bool {let o = _accessor.offset(VTOFFSET.i16.v); return _accessor.mutate(i16, index: o) } + public var u16: UInt16 { let o = _accessor.offset(VTOFFSET.u16.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt16.self, at: o) } + @discardableResult public func mutate(u16: UInt16) -> Bool {let o = _accessor.offset(VTOFFSET.u16.v); return _accessor.mutate(u16, index: o) } + public var i32: Int32 { let o = _accessor.offset(VTOFFSET.i32.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int32.self, at: o) } + @discardableResult public func mutate(i32: Int32) -> Bool {let o = _accessor.offset(VTOFFSET.i32.v); return _accessor.mutate(i32, index: o) } + public var u32: UInt32 { let o = _accessor.offset(VTOFFSET.u32.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt32.self, at: o) } + @discardableResult public func mutate(u32: UInt32) -> Bool {let o = _accessor.offset(VTOFFSET.u32.v); return _accessor.mutate(u32, index: o) } + public var i64: Int64 { let o = _accessor.offset(VTOFFSET.i64.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int64.self, at: o) } + @discardableResult public func mutate(i64: Int64) -> Bool {let o = _accessor.offset(VTOFFSET.i64.v); return _accessor.mutate(i64, index: o) } + public var u64: UInt64 { let o = _accessor.offset(VTOFFSET.u64.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt64.self, at: o) } + @discardableResult public func mutate(u64: UInt64) -> Bool {let o = _accessor.offset(VTOFFSET.u64.v); return _accessor.mutate(u64, index: o) } + public var f32: Float32 { let o = _accessor.offset(VTOFFSET.f32.v); return o == 0 ? 0.0 : _accessor.readBuffer(of: Float32.self, at: o) } + @discardableResult public func mutate(f32: Float32) -> Bool {let o = _accessor.offset(VTOFFSET.f32.v); return _accessor.mutate(f32, index: o) } + public var f64: Double { let o = _accessor.offset(VTOFFSET.f64.v); return o == 0 ? 0.0 : _accessor.readBuffer(of: Double.self, at: o) } + @discardableResult public func mutate(f64: Double) -> Bool {let o = _accessor.offset(VTOFFSET.f64.v); return _accessor.mutate(f64, index: o) } + public var v8: FlatbufferVector { return _accessor.vector(at: VTOFFSET.v8.v, byteSize: 1) } + public func mutate(v8: Int8, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.v8.v); return _accessor.directMutate(v8, index: _accessor.vector(at: o) + index * 1) } + public func withUnsafePointerToV8(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VTOFFSET.v8.v, body: body) } + public var vf64: FlatbufferVector { return _accessor.vector(at: VTOFFSET.vf64.v, byteSize: 8) } + public func mutate(vf64: Double, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.vf64.v); return _accessor.directMutate(vf64, index: _accessor.vector(at: o) + index * 8) } + public func withUnsafePointerToVf64(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VTOFFSET.vf64.v, body: body) } public static func startTypeAliases(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 12) } - public static func add(i8: Int8, _ fbb: inout FlatBufferBuilder) { fbb.add(element: i8, def: 0, at: VT.i8) } - public static func add(u8: UInt8, _ fbb: inout FlatBufferBuilder) { fbb.add(element: u8, def: 0, at: VT.u8) } - public static func add(i16: Int16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: i16, def: 0, at: VT.i16) } - public static func add(u16: UInt16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: u16, def: 0, at: VT.u16) } - public static func add(i32: Int32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: i32, def: 0, at: VT.i32) } - public static func add(u32: UInt32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: u32, def: 0, at: VT.u32) } - public static func add(i64: Int64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: i64, def: 0, at: VT.i64) } - public static func add(u64: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: u64, def: 0, at: VT.u64) } - public static func add(f32: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: f32, def: 0.0, at: VT.f32) } - public static func add(f64: Double, _ fbb: inout FlatBufferBuilder) { fbb.add(element: f64, def: 0.0, at: VT.f64) } - public static func addVectorOf(v8: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: v8, at: VT.v8) } - public static func addVectorOf(vf64: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vf64, at: VT.vf64) } + public static func add(i8: Int8, _ fbb: inout FlatBufferBuilder) { fbb.add(element: i8, def: 0, at: VTOFFSET.i8.p) } + public static func add(u8: UInt8, _ fbb: inout FlatBufferBuilder) { fbb.add(element: u8, def: 0, at: VTOFFSET.u8.p) } + public static func add(i16: Int16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: i16, def: 0, at: VTOFFSET.i16.p) } + public static func add(u16: UInt16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: u16, def: 0, at: VTOFFSET.u16.p) } + public static func add(i32: Int32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: i32, def: 0, at: VTOFFSET.i32.p) } + public static func add(u32: UInt32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: u32, def: 0, at: VTOFFSET.u32.p) } + public static func add(i64: Int64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: i64, def: 0, at: VTOFFSET.i64.p) } + public static func add(u64: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: u64, def: 0, at: VTOFFSET.u64.p) } + public static func add(f32: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: f32, def: 0.0, at: VTOFFSET.f32.p) } + public static func add(f64: Double, _ fbb: inout FlatBufferBuilder) { fbb.add(element: f64, def: 0.0, at: VTOFFSET.f64.p) } + public static func addVectorOf(v8: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: v8, at: VTOFFSET.v8.p) } + public static func addVectorOf(vf64: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vf64, at: VTOFFSET.vf64.p) } public static func endTypeAliases(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } public static func createTypeAliases( _ fbb: inout FlatBufferBuilder, @@ -2339,23 +2351,24 @@ public struct MyGame_Example_TypeAliases: FlatBufferVerifiableTable, Flatbuffers public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { var _v = try verifier.visitTable(at: position) - try _v.visit(field: VT.i8, fieldName: "i8", required: false, type: Int8.self) - try _v.visit(field: VT.u8, fieldName: "u8", required: false, type: UInt8.self) - try _v.visit(field: VT.i16, fieldName: "i16", required: false, type: Int16.self) - try _v.visit(field: VT.u16, fieldName: "u16", required: false, type: UInt16.self) - try _v.visit(field: VT.i32, fieldName: "i32", required: false, type: Int32.self) - try _v.visit(field: VT.u32, fieldName: "u32", required: false, type: UInt32.self) - try _v.visit(field: VT.i64, fieldName: "i64", required: false, type: Int64.self) - try _v.visit(field: VT.u64, fieldName: "u64", required: false, type: UInt64.self) - try _v.visit(field: VT.f32, fieldName: "f32", required: false, type: Float32.self) - try _v.visit(field: VT.f64, fieldName: "f64", required: false, type: Double.self) - try _v.visit(field: VT.v8, fieldName: "v8", required: false, type: ForwardOffset>.self) - try _v.visit(field: VT.vf64, fieldName: "vf64", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.i8.p, fieldName: "i8", required: false, type: Int8.self) + try _v.visit(field: VTOFFSET.u8.p, fieldName: "u8", required: false, type: UInt8.self) + try _v.visit(field: VTOFFSET.i16.p, fieldName: "i16", required: false, type: Int16.self) + try _v.visit(field: VTOFFSET.u16.p, fieldName: "u16", required: false, type: UInt16.self) + try _v.visit(field: VTOFFSET.i32.p, fieldName: "i32", required: false, type: Int32.self) + try _v.visit(field: VTOFFSET.u32.p, fieldName: "u32", required: false, type: UInt32.self) + try _v.visit(field: VTOFFSET.i64.p, fieldName: "i64", required: false, type: Int64.self) + try _v.visit(field: VTOFFSET.u64.p, fieldName: "u64", required: false, type: UInt64.self) + try _v.visit(field: VTOFFSET.f32.p, fieldName: "f32", required: false, type: Float32.self) + try _v.visit(field: VTOFFSET.f64.p, fieldName: "f64", required: false, type: Double.self) + try _v.visit(field: VTOFFSET.v8.p, fieldName: "v8", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.vf64.p, fieldName: "vf64", required: false, type: ForwardOffset>.self) _v.finish() } } extension MyGame_Example_TypeAliases: Encodable { + enum CodingKeys: String, CodingKey { case i8 = "i8" case u8 = "u8" @@ -2370,7 +2383,6 @@ extension MyGame_Example_TypeAliases: Encodable { case v8 = "v8" case vf64 = "vf64" } - public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) if i8 != 0 { diff --git a/tests/swift/Wasm.tests/Tests/FlexBuffers.Test.Swift.WasmTests/FlexBuffersJSONTests.swift b/tests/swift/Wasm.tests/Tests/FlexBuffers.Test.Swift.WasmTests/FlexBuffersJSONTests.swift index 8cb5ca9b5..c25466666 100644 --- a/tests/swift/Wasm.tests/Tests/FlexBuffers.Test.Swift.WasmTests/FlexBuffersJSONTests.swift +++ b/tests/swift/Wasm.tests/Tests/FlexBuffers.Test.Swift.WasmTests/FlexBuffersJSONTests.swift @@ -16,19 +16,17 @@ import Common import FlexBuffers -import Foundation -import Testing +import XCTest -struct FlexBuffersJSONTests { - @Test +final class FlexBuffersJSONTests: XCTestCase { func testEncodingJSON() throws { let buf: ByteBuffer = createProperBuffer().sizedByteBuffer let reference = try getRoot(buffer: buf)! let json = reference.jsonString() // swiftformat:disable all - #expect( - json == + XCTAssertEqual( + json, "{\"bar\": [1, 2, 3], \"bar3\": [1, 2, 3], \"bool\": true, \"bools\": [true, false, true, false], \"foo\": 100.0, \"mymap\": {\"foo\": \"Fred\"}, \"vec\": [-100, \"Fred\", 4.0, \"M\", false, 4.0]}" ) // swiftformat:enable all @@ -39,15 +37,15 @@ struct FlexBuffersJSONTests { with: data, options: []) as! [String: Any] - #expect(decodedData["bar"] as! [Int] == [1, 2, 3]) - #expect(decodedData["bar3"] as! [Int] == [1, 2, 3]) + XCTAssertEqual(decodedData["bar"] as! [Int], [1, 2, 3]) + XCTAssertEqual(decodedData["bar3"] as! [Int], [1, 2, 3]) let vec: [Any] = decodedData["vec"] as! [Any] - #expect(vec[0] as! Int == -100) - #expect(vec[1] as! String == "Fred") - #expect(vec[2] as! Double == 4.0) - #expect(vec[3] as! String == "M") - #expect(vec[4] as! Bool == false) - #expect(vec[5] as! Double == 4.0) + XCTAssertEqual(vec[0] as! Int, -100) + XCTAssertEqual(vec[1] as! String, "Fred") + XCTAssertEqual(vec[2] as! Double, 4.0) + XCTAssertEqual(vec[3] as! String, "M") + XCTAssertEqual(vec[4] as! Bool, false) + XCTAssertEqual(vec[5] as! Double, 4.0) } } diff --git a/tests/swift/Wasm.tests/Tests/FlexBuffers.Test.Swift.WasmTests/FlexBuffersReaderTests.swift b/tests/swift/Wasm.tests/Tests/FlexBuffers.Test.Swift.WasmTests/FlexBuffersReaderTests.swift index 96243e63e..06f01421f 100644 --- a/tests/swift/Wasm.tests/Tests/FlexBuffers.Test.Swift.WasmTests/FlexBuffersReaderTests.swift +++ b/tests/swift/Wasm.tests/Tests/FlexBuffers.Test.Swift.WasmTests/FlexBuffersReaderTests.swift @@ -15,26 +15,22 @@ */ import Common -import Foundation -import Testing +import XCTest @testable import FlexBuffers -struct FlexBuffersReaderTests { +final class FlexBuffersReaderTests: XCTestCase { - @Test func testReadingProperBuffer() throws { let buf: ByteBuffer = createProperBuffer().byteBuffer try validate(buffer: buf) } - @Test func testReadingSizedBuffer() throws { let buf: ByteBuffer = createSizedBuffer() try validate(buffer: buf) } - @Test(.bug("https://github.com/google/flatbuffers/issues/8642")) func testReset() throws { var fbx = FlexBuffersWriter( initialSize: 8, @@ -42,87 +38,87 @@ struct FlexBuffersReaderTests { write(fbx: &fbx) try validate(buffer: ByteBuffer(bytes: fbx.sizedByteArray)) - #expect(fbx.capacity == 512) + XCTAssertEqual(fbx.capacity, 512) fbx.reset() - #expect(fbx.writerIndex == 0) - #expect(fbx.capacity == 8) + XCTAssertEqual(fbx.writerIndex, 0) + XCTAssertEqual(fbx.capacity, 8) write(fbx: &fbx) try validate(buffer: ByteBuffer(bytes: fbx.sizedByteArray)) fbx.reset(keepingCapacity: true) - #expect(fbx.writerIndex == 0) - #expect(fbx.capacity == 512) + XCTAssertEqual(fbx.writerIndex, 0) + XCTAssertEqual(fbx.capacity, 512) write(fbx: &fbx) try validate(buffer: ByteBuffer(bytes: fbx.sizedByteArray)) - #expect(fbx.capacity == 512) + XCTAssertEqual(fbx.capacity, 512) } private func validate(buffer buf: ByteBuffer) throws { let reference = try getRoot(buffer: buf)! - #expect(reference.type == .map) + XCTAssertEqual(reference.type, .map) let map = reference.map! - #expect(map.count == 7) + XCTAssertEqual(map.count, 7) let vecRef = map["vec"]! - #expect(vecRef.type == .vector) + XCTAssertEqual(vecRef.type, .vector) let vec = vecRef.vector! - #expect(vec.count == 6) - #expect(vec[0]?.type == .int) - #expect(vec[0]?.int == -100) - #expect(vec[1]?.type == .string) - #expect(vec[1]?.cString == "Fred") - #expect(vec[1]?.int == nil) - #expect(vec[2]?.double == 4.0) - #expect(vec[3]?.type == .blob) + XCTAssertEqual(vec.count, 6) + XCTAssertEqual(vec[0]?.type, .int) + XCTAssertEqual(vec[0]?.int, -100) + XCTAssertEqual(vec[1]?.type, .string) + XCTAssertEqual(vec[1]?.cString, "Fred") + XCTAssertNil(vec[1]?.int) + XCTAssertEqual(vec[2]?.double, 4.0) + XCTAssertTrue(vec[3]?.type == .blob) let blob = vec[3]!.blob { pointer in Array(pointer) } - #expect(blob?.count == 1) - #expect(blob?[0] == 77) - #expect(vec[4]?.type == .bool) - #expect(vec[4]?.bool == false) - #expect(vec[5]?.double == 4.0) // Shared with vec[2] + XCTAssertEqual(blob?.count, 1) + XCTAssertEqual(blob?[0], 77) + XCTAssertEqual(vec[4]?.type, .bool) + XCTAssertEqual(vec[4]?.bool, false) + XCTAssertEqual(vec[5]?.double, 4.0) // Shared with vec[2] let barVec = map["bar"]!.typedVector! - #expect(barVec.count == 3) - #expect(barVec[2]?.int == 3) - #expect(barVec[2]?.asInt() == UInt8(3)) + XCTAssertEqual(barVec.count, 3) + XCTAssertEqual(barVec[2]?.int, 3) + XCTAssertEqual(barVec[2]?.asInt(), UInt8(3)) let fixedVec = map["bar3"]!.fixedTypedVector! - #expect(fixedVec.count == 3) - #expect(fixedVec[2]?.int == 3) - #expect(fixedVec[2]?.asInt() == UInt8(3)) - #expect(map["bool"]?.bool == true) + XCTAssertEqual(fixedVec.count, 3) + XCTAssertEqual(fixedVec[2]?.int, 3) + XCTAssertEqual(fixedVec[2]?.asInt(), UInt8(3)) + XCTAssertEqual(map["bool"]?.bool, true) let boolsVector = map["bools"]!.typedVector! - #expect(boolsVector.type == .bool) - #expect(boolsVector[0]?.bool == true) - #expect(boolsVector[1]?.bool == false) + XCTAssertEqual(boolsVector.type, .bool) + XCTAssertEqual(boolsVector[0]?.bool, true) + XCTAssertEqual(boolsVector[1]?.bool, false) let bools = [true, false, true, false] boolsVector.withUnsafeRawBufferPointer { buff in for i in 0.. UOffset { fbb.startTable(with: 1) } - internal static func add(internalMessage: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: internalMessage, at: VT.internalMessage) } + internal static func add(internalMessage: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: internalMessage, at: VTOFFSET.internalMessage.p) } internal static func endMessage(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } internal static func createMessage( _ fbb: inout FlatBufferBuilder, @@ -58,16 +60,16 @@ internal struct Message: FlatBufferVerifiableTable, FlatbuffersVectorInitializab internal static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { var _v = try verifier.visitTable(at: position) - try _v.visit(field: VT.internalMessage, fieldName: "internalMessage", required: false, type: ForwardOffset.self) + try _v.visit(field: VTOFFSET.internalMessage.p, fieldName: "internalMessage", required: false, type: ForwardOffset.self) _v.finish() } } extension Message: Encodable { + enum CodingKeys: String, CodingKey { case internalMessage = "internal_message" } - internal func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(internalMessage, forKey: .internalMessage) diff --git a/tests/swift/fuzzer/CodeGenerationTests/test_no_include_generated.swift b/tests/swift/fuzzer/CodeGenerationTests/test_no_include_generated.swift index 0cd9933d3..843de3116 100644 --- a/tests/swift/fuzzer/CodeGenerationTests/test_no_include_generated.swift +++ b/tests/swift/fuzzer/CodeGenerationTests/test_no_include_generated.swift @@ -32,10 +32,10 @@ public struct BytesCount: NativeStruct, FlatbuffersVectorInitializable, Verifiab } extension BytesCount: Encodable { + enum CodingKeys: String, CodingKey { case x = "x" } - public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) if x != 0 { @@ -68,7 +68,7 @@ public struct BytesCount_Mutable: FlatBufferStruct, FlatbuffersVectorInitializab } } -public struct InternalMessage: FlatBufferVerifiableTable, FlatbuffersVectorInitializable, ObjectAPIPacker { +public struct InternalMessage: FlatBufferTable, FlatbuffersVectorInitializable, Verifiable, ObjectAPIPacker { static func validateVersion() { FlatBuffersVersion_25_12_19() } public var __buffer: ByteBuffer! { return _accessor.bb } @@ -77,14 +77,16 @@ public struct InternalMessage: FlatBufferVerifiableTable, FlatbuffersVectorIniti private init(_ t: Table) { _accessor = t } public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } - private struct VT { - static let str: VOffset = 4 + private enum VTOFFSET: VOffset { + case str = 4 + var v: Int32 { Int32(self.rawValue) } + var p: VOffset { self.rawValue } } - public var str: String? { let o = _accessor.offset(VT.str); return o == 0 ? nil : _accessor.string(at: o) } - public var strSegmentArray: [UInt8]? { return _accessor.getVector(at: VT.str) } + public var str: String? { let o = _accessor.offset(VTOFFSET.str.v); return o == 0 ? nil : _accessor.string(at: o) } + public var strSegmentArray: [UInt8]? { return _accessor.getVector(at: VTOFFSET.str.v) } public static func startInternalMessage(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) } - public static func add(str: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: str, at: VT.str) } + public static func add(str: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: str, at: VTOFFSET.str.p) } public static func endInternalMessage(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } public static func createInternalMessage( _ fbb: inout FlatBufferBuilder, @@ -118,16 +120,16 @@ public struct InternalMessage: FlatBufferVerifiableTable, FlatbuffersVectorIniti public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { var _v = try verifier.visitTable(at: position) - try _v.visit(field: VT.str, fieldName: "str", required: false, type: ForwardOffset.self) + try _v.visit(field: VTOFFSET.str.p, fieldName: "str", required: false, type: ForwardOffset.self) _v.finish() } } extension InternalMessage: Encodable { + enum CodingKeys: String, CodingKey { case str = "str" } - public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(str, forKey: .str) @@ -148,7 +150,7 @@ public class InternalMessageT: NativeObject { public func serialize() -> ByteBuffer { return serialize(type: InternalMessage.self) } } -public struct Message: FlatBufferVerifiableTable, FlatbuffersVectorInitializable, ObjectAPIPacker { +public struct Message: FlatBufferTable, FlatbuffersVectorInitializable, Verifiable, ObjectAPIPacker { static func validateVersion() { FlatBuffersVersion_25_12_19() } public var __buffer: ByteBuffer! { return _accessor.bb } @@ -157,21 +159,23 @@ public struct Message: FlatBufferVerifiableTable, FlatbuffersVectorInitializable private init(_ t: Table) { _accessor = t } public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } - private struct VT { - static let id: VOffset = 4 - static let position: VOffset = 6 - static let pointer: VOffset = 8 + private enum VTOFFSET: VOffset { + case id = 4 + case position = 6 + case pointer = 8 + var v: Int32 { Int32(self.rawValue) } + var p: VOffset { self.rawValue } } - public var id: Int64 { let o = _accessor.offset(VT.id); return o == 0 ? 0 : _accessor.readBuffer(of: Int64.self, at: o) } - @discardableResult public func mutate(id: Int64) -> Bool {let o = _accessor.offset(VT.id); return _accessor.mutate(id, index: o) } - public var position: BytesCount! { let o = _accessor.offset(VT.position); return _accessor.readBuffer(of: BytesCount.self, at: o) } - public var mutablePosition: BytesCount_Mutable! { let o = _accessor.offset(VT.position); return BytesCount_Mutable(_accessor.bb, o: o + _accessor.position) } - public var pointer: InternalMessage! { let o = _accessor.offset(VT.pointer); return InternalMessage(_accessor.bb, o: _accessor.indirect(o + _accessor.position)) } + public var id: Int64 { let o = _accessor.offset(VTOFFSET.id.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int64.self, at: o) } + @discardableResult public func mutate(id: Int64) -> Bool {let o = _accessor.offset(VTOFFSET.id.v); return _accessor.mutate(id, index: o) } + public var position: BytesCount! { let o = _accessor.offset(VTOFFSET.position.v); return _accessor.readBuffer(of: BytesCount.self, at: o) } + public var mutablePosition: BytesCount_Mutable! { let o = _accessor.offset(VTOFFSET.position.v); return BytesCount_Mutable(_accessor.bb, o: o + _accessor.position) } + public var pointer: InternalMessage! { let o = _accessor.offset(VTOFFSET.pointer.v); return InternalMessage(_accessor.bb, o: _accessor.indirect(o + _accessor.position)) } public static func startMessage(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 3) } - public static func add(id: Int64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: id, def: 0, at: VT.id) } - public static func add(position: BytesCount?, _ fbb: inout FlatBufferBuilder) { guard let position = position else { return }; fbb.create(struct: position, position: VT.position) } - public static func add(pointer: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: pointer, at: VT.pointer) } + public static func add(id: Int64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: id, def: 0, at: VTOFFSET.id.p) } + public static func add(position: BytesCount?, _ fbb: inout FlatBufferBuilder) { guard let position = position else { return }; fbb.create(struct: position, position: VTOFFSET.position.p) } + public static func add(pointer: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: pointer, at: VTOFFSET.pointer.p) } public static func endMessage(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); fbb.require(table: end, fields: [6, 8]); return end } public static func createMessage( _ fbb: inout FlatBufferBuilder, @@ -205,20 +209,20 @@ public struct Message: FlatBufferVerifiableTable, FlatbuffersVectorInitializable public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { var _v = try verifier.visitTable(at: position) - try _v.visit(field: VT.id, fieldName: "id", required: false, type: Int64.self) - try _v.visit(field: VT.position, fieldName: "position", required: true, type: BytesCount.self) - try _v.visit(field: VT.pointer, fieldName: "pointer", required: true, type: ForwardOffset.self) + try _v.visit(field: VTOFFSET.id.p, fieldName: "id", required: false, type: Int64.self) + try _v.visit(field: VTOFFSET.position.p, fieldName: "position", required: true, type: BytesCount.self) + try _v.visit(field: VTOFFSET.pointer.p, fieldName: "pointer", required: true, type: ForwardOffset.self) _v.finish() } } extension Message: Encodable { + enum CodingKeys: String, CodingKey { case id = "id" case position = "position" case pointer = "pointer" } - public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) if id != 0 { diff --git a/tests/test.cpp b/tests/test.cpp index 5a43546f5..a068c2b2a 100644 --- a/tests/test.cpp +++ b/tests/test.cpp @@ -34,7 +34,6 @@ #include "third_party/absl/container/flat_hash_set.h" #endif #include "alignment_test.h" -#include "cross_namespace_pack_test_generated.h" #include "default_vectors_strings_test.h" #include "evolution_test.h" #include "flatbuffers/flatbuffers.h" @@ -67,6 +66,8 @@ #include "native_type_test_generated.h" #include "test_assert.h" #include "util_test.h" +#include "cpp_vector_type_test.h" +#include "bigfoot_ref_test_impl.h" #include "vector_table_naked_ptr_test.h" void FlatBufferBuilderTest(); @@ -951,7 +952,6 @@ void NativeTypeTest() { TEST_EQ(dstDataT->position_inline.x, 4.0f); TEST_EQ(dstDataT->position_inline.y, 5.0f); TEST_EQ(dstDataT->position_inline.z, 6.0f); - for (int i = 0; i < N; ++i) { const Native::Vector3D& v = dstDataT->vectors[i]; TEST_EQ(v.x, 10 * i + 0.1f); @@ -1722,29 +1722,6 @@ static void Offset64Tests() { #endif } -// Test that Pack() generates correctly namespace-qualified Create* calls -// when referencing tables from different namespaces. (issue #8948) -void CrossNamespacePackTest() { - // Build a Consumer with a cross-namespace TableWithNative reference. - foo::ConsumerT consumer; - consumer.c1 = std::make_unique(); - consumer.c1->value = 42; - - // Add a vector element too. - consumer.c2.push_back(std::make_unique()); - consumer.c2[0]->value = 99; - - // Pack and verify round-trip. - flatbuffers::FlatBufferBuilder fbb; - fbb.Finish(foo::Consumer::Pack(fbb, &consumer)); - - auto* packed = flatbuffers::GetRoot(fbb.GetBufferPointer()); - auto unpacked = packed->UnPack(); - TEST_EQ(unpacked->c1->value, 42); - TEST_EQ(unpacked->c2.size(), 1); - TEST_EQ(unpacked->c2[0]->value, 99); -} - int FlatBufferTests(const std::string& tests_data_path) { // Run our various test suites: @@ -1768,13 +1745,14 @@ int FlatBufferTests(const std::string& tests_data_path) { AlignmentTest(); + CppVectorTypeTest(); + #ifndef FLATBUFFERS_NO_FILE_TESTS ParseAndGenerateTextTest(tests_data_path, false); ParseAndGenerateTextTest(tests_data_path, true); FixedLengthArrayJsonTest(tests_data_path, false); FixedLengthArrayJsonTest(tests_data_path, true); ReflectionTest(tests_data_path, flatbuf.data(), flatbuf.size()); - ForAllFieldsReverseTest(tests_data_path); ParseProtoTest(tests_data_path); EvolutionTest(tests_data_path); UnionDeprecationTest(tests_data_path); @@ -1838,6 +1816,7 @@ int FlatBufferTests(const std::string& tests_data_path) { InvalidFloatTest(); FixedLengthArrayTest(); NativeTypeTest(); + flatbuffers::tests::BigfootRefTest(); OptionalScalarsTest(); ParseFlexbuffersFromJsonWithNullTest(); FlatbuffersSpanTest(); @@ -1863,7 +1842,6 @@ int FlatBufferTests(const std::string& tests_data_path) { UnionUnderlyingTypeTest(); StructsInHashTableTest(); DefaultVectorsStringsTest(); - CrossNamespacePackTest(); return 0; } } // namespace diff --git a/tests/test_vector_type.h b/tests/test_vector_type.h new file mode 100644 index 000000000..9a40d5dfc --- /dev/null +++ b/tests/test_vector_type.h @@ -0,0 +1,152 @@ +#ifndef TESTS_TEST_VECTOR_TYPE_H_ +#define TESTS_TEST_VECTOR_TYPE_H_ + +#include +#include +#include + +namespace flatbuffers { +namespace tests { + +// A minimal stand-in for a custom vector-like container (e.g. +// eastl::vector), used to exercise the --cpp-vector-type flatc option. +// +// This is deliberately its own contiguous container rather than a wrapper +// around std::vector, so that: +// - generated code can't silently keep depending on any of the +// std::vector-specific overloads in flatbuffer_builder.h (e.g. +// CreateVector(const std::vector&)), and +// - CustomVector stores plain contiguous bools accessible via +// data(), unlike std::vector's bit-packed specialization, matching +// how real alternative containers such as eastl::vector behave. +template +class CustomVector { + public: + using value_type = T; + using iterator = T*; + using const_iterator = const T*; + + CustomVector() = default; + CustomVector(const CustomVector& o) { assign_copy(o); } + CustomVector(CustomVector&& o) noexcept { steal(o); } + + CustomVector& operator=(const CustomVector& o) { + if (this != &o) { + destroy_all(); + deallocate(); + assign_copy(o); + } + return *this; + } + + CustomVector& operator=(CustomVector&& o) noexcept { + if (this != &o) { + destroy_all(); + deallocate(); + steal(o); + } + return *this; + } + + ~CustomVector() { + destroy_all(); + deallocate(); + } + + void reserve(size_t n) { + if (n > capacity_) grow_to(n); + } + + void resize(size_t n) { + if (n > capacity_) grow_to(n); + for (size_t i = n; i < size_; ++i) data_[i].~T(); + for (size_t i = size_; i < n; ++i) new (&data_[i]) T(); + size_ = n; + } + + size_t size() const { return size_; } + bool empty() const { return size_ == 0; } + + T* data() { return data_; } + const T* data() const { return data_; } + + T& operator[](size_t i) { return data_[i]; } + const T& operator[](size_t i) const { return data_[i]; } + + template + void emplace_back(Args&&... args) { + if (size_ == capacity_) grow_to(capacity_ == 0 ? 1 : capacity_ * 2); + new (&data_[size_]) T(std::forward(args)...); + ++size_; + } + void push_back(const T& v) { emplace_back(v); } + + iterator begin() { return data_; } + iterator end() { return data_ + size_; } + const_iterator begin() const { return data_; } + const_iterator end() const { return data_ + size_; } + const_iterator cbegin() const { return data_; } + const_iterator cend() const { return data_ + size_; } + + private: + void grow_to(size_t n) { + T* new_data = static_cast(::operator new(n * sizeof(T))); + for (size_t i = 0; i < size_; ++i) { + new (&new_data[i]) T(std::move(data_[i])); + data_[i].~T(); + } + ::operator delete(data_); + data_ = new_data; + capacity_ = n; + } + + void assign_copy(const CustomVector& o) { + data_ = o.size_ ? static_cast(::operator new(o.size_ * sizeof(T))) + : nullptr; + capacity_ = o.size_; + for (size_t i = 0; i < o.size_; ++i) new (&data_[i]) T(o.data_[i]); + size_ = o.size_; + } + + void steal(CustomVector& o) { + data_ = o.data_; + size_ = o.size_; + capacity_ = o.capacity_; + o.data_ = nullptr; + o.size_ = o.capacity_ = 0; + } + + void destroy_all() { + for (size_t i = 0; i < size_; ++i) data_[i].~T(); + size_ = 0; + } + + void deallocate() { + ::operator delete(data_); + data_ = nullptr; + capacity_ = 0; + } + + T* data_ = nullptr; + size_t size_ = 0; + size_t capacity_ = 0; +}; + +template +bool operator==(const CustomVector& lhs, const CustomVector& rhs) { + if (lhs.size() != rhs.size()) return false; + for (size_t i = 0; i < lhs.size(); ++i) { + if (!(lhs[i] == rhs[i])) return false; + } + return true; +} + +template +bool operator!=(const CustomVector& lhs, const CustomVector& rhs) { + return !(lhs == rhs); +} + +} // namespace tests +} // namespace flatbuffers + +#endif // TESTS_TEST_VECTOR_TYPE_H_ diff --git a/tests/ts/TypeScriptTest.py b/tests/ts/TypeScriptTest.py index 7bf4317f0..6870ff995 100755 --- a/tests/ts/TypeScriptTest.py +++ b/tests/ts/TypeScriptTest.py @@ -62,10 +62,16 @@ def flatc( # Execute esbuild with the specified parameters def esbuild(input, output): - cmd = ["../../node_modules/.bin/esbuild", input, "--outfile=" + output] + cmd = ["esbuild", input, "--outfile=" + output] cmd += ["--format=cjs", "--bundle", "--external:flatbuffers"] check_call(cmd) + +print("Removing node_modules/ directory...") +shutil.rmtree(Path(tests_path, "node_modules"), ignore_errors=True) + +check_call(["npm", "install", "--silent"]) + flatc( options=[ "--ts", @@ -81,20 +87,6 @@ flatc( ) esbuild("monster_test.ts", "monster_test_generated.cjs") -flatc( - options=[ - "--ts", - "--reflect-names", - "--gen-name-strings", - "--gen-mutable", - "--gen-object-api", - "--ts-entry-points", - "--ts-flat-files", - ], - schema="../even_more_defaults.fbs", - include="../include_test", -) - flatc( options=["--gen-object-api", "-b"], schema="../monster_test.fbs", @@ -207,27 +199,13 @@ flatc( flatc(options=["--ts"], schema="../long_namespace.fbs") flatc(options=["--ts"], schema="../longer_namespace.fbs") - -flatc( - options=[ - "--ts", - "--reflect-names", - "--gen-name-strings", - "--gen-object-api", - "--ts-entry-points", - "--ts-flat-files", - ], - schema="relative_imports/relative_imports.fbs", - prefix="relative_imports", -) - print("Running TypeScript Compiler...") -check_call(["../../node_modules/.bin/tsc"]) +check_call(["tsc"]) print( "Running TypeScript Compiler in old node resolution mode for" " no_import_ext..." ) -check_call(["../../node_modules/.bin/tsc", "-p", "./tsconfig.node.json"]) +check_call(["tsc", "-p", "./tsconfig.node.json"]) NODE_CMD = ["node"] @@ -237,7 +215,6 @@ check_call(NODE_CMD + ["JavaScriptUnionVectorTest"]) check_call(NODE_CMD + ["JavaScriptFlexBuffersTest"]) check_call(NODE_CMD + ["JavaScriptComplexArraysTest"]) check_call(NODE_CMD + ["JavaScriptUnionUnderlyingTypeTest"]) -check_call(NODE_CMD + ["JavaScriptRelativeImportPathTest"]) check_call(NODE_CMD + ["JavaScriptUndefinedForOptionals"]) print("Running old v1 TypeScript Tests...") diff --git a/tests/ts/bazel_repository_test_dir/package.json b/tests/ts/bazel_repository_test_dir/package.json index f7b22d187..2988b7e80 100644 --- a/tests/ts/bazel_repository_test_dir/package.json +++ b/tests/ts/bazel_repository_test_dir/package.json @@ -3,6 +3,6 @@ "type": "module", "private": true, "devDependencies": { - "lodash": "4.17.23" + "lodash": "4.17.21" } } diff --git a/tests/ts/bazel_repository_test_dir/pnpm-lock.yaml b/tests/ts/bazel_repository_test_dir/pnpm-lock.yaml index 7d65a402d..091839109 100644 --- a/tests/ts/bazel_repository_test_dir/pnpm-lock.yaml +++ b/tests/ts/bazel_repository_test_dir/pnpm-lock.yaml @@ -1,16 +1,12 @@ lockfileVersion: '6.0' -settings: - autoInstallPeers: true - excludeLinksFromLockfile: false - devDependencies: lodash: - specifier: 4.17.23 - version: 4.17.23 + specifier: 4.17.21 + version: 4.17.21 packages: - /lodash@4.17.23: - resolution: {integrity: sha512-LgVTMpQtIopCi79SJeDiP0TfWi5CNEc/L/aRdTh3yIvmZXTnheWpKjSZhnvMl8iXbC1tFg9gdHHDMLoV7CnG+w==} + /lodash@4.17.21: + resolution: {integrity: sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==} dev: true diff --git a/tests/ts/my-game/example/any-ambiguous-aliases.ts b/tests/ts/my-game/example/any-ambiguous-aliases.ts index 7510e3056..8e7a3a3b6 100644 --- a/tests/ts/my-game/example/any-ambiguous-aliases.ts +++ b/tests/ts/my-game/example/any-ambiguous-aliases.ts @@ -2,7 +2,7 @@ /* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ -import { Monster, MonsterT } from './monster.js'; +import { Monster, MonsterT } from '../../my-game/example/monster.js'; export enum AnyAmbiguousAliases { diff --git a/tests/ts/my-game/example/any-unique-aliases.ts b/tests/ts/my-game/example/any-unique-aliases.ts index c0b7e15c7..ae85ea00b 100644 --- a/tests/ts/my-game/example/any-unique-aliases.ts +++ b/tests/ts/my-game/example/any-unique-aliases.ts @@ -2,9 +2,9 @@ /* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ -import { Monster as MyGame_Example2_Monster, MonsterT as MyGame_Example2_MonsterT } from '../example2/monster.js'; -import { Monster, MonsterT } from './monster.js'; -import { TestSimpleTableWithEnum, TestSimpleTableWithEnumT } from './test-simple-table-with-enum.js'; +import { Monster as MyGame_Example2_Monster, MonsterT as MyGame_Example2_MonsterT } from '../../my-game/example2/monster.js'; +import { Monster, MonsterT } from '../../my-game/example/monster.js'; +import { TestSimpleTableWithEnum, TestSimpleTableWithEnumT } from '../../my-game/example/test-simple-table-with-enum.js'; export enum AnyUniqueAliases { diff --git a/tests/ts/my-game/example/any.ts b/tests/ts/my-game/example/any.ts index ea886c787..5e484fa0a 100644 --- a/tests/ts/my-game/example/any.ts +++ b/tests/ts/my-game/example/any.ts @@ -2,9 +2,9 @@ /* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ -import { Monster as MyGame_Example2_Monster, MonsterT as MyGame_Example2_MonsterT } from '../example2/monster.js'; -import { Monster, MonsterT } from './monster.js'; -import { TestSimpleTableWithEnum, TestSimpleTableWithEnumT } from './test-simple-table-with-enum.js'; +import { Monster as MyGame_Example2_Monster, MonsterT as MyGame_Example2_MonsterT } from '../../my-game/example2/monster.js'; +import { Monster, MonsterT } from '../../my-game/example/monster.js'; +import { TestSimpleTableWithEnum, TestSimpleTableWithEnumT } from '../../my-game/example/test-simple-table-with-enum.js'; export enum Any { diff --git a/tests/ts/my-game/example/monster.ts b/tests/ts/my-game/example/monster.ts index dd7333ccb..bd64dd121 100644 --- a/tests/ts/my-game/example/monster.ts +++ b/tests/ts/my-game/example/monster.ts @@ -4,19 +4,19 @@ import * as flatbuffers from 'flatbuffers'; -import { Monster as MyGame_Example2_Monster, MonsterT as MyGame_Example2_MonsterT } from '../example2/monster.js'; -import { Ability, AbilityT } from './ability.js'; -import { Any, unionToAny, unionListToAny } from './any.js'; -import { AnyAmbiguousAliases, unionToAnyAmbiguousAliases, unionListToAnyAmbiguousAliases } from './any-ambiguous-aliases.js'; -import { AnyUniqueAliases, unionToAnyUniqueAliases, unionListToAnyUniqueAliases } from './any-unique-aliases.js'; -import { Color } from './color.js'; -import { Race } from './race.js'; -import { Referrable, ReferrableT } from './referrable.js'; -import { Stat, StatT } from './stat.js'; -import { Test, TestT } from './test.js'; -import { TestSimpleTableWithEnum, TestSimpleTableWithEnumT } from './test-simple-table-with-enum.js'; -import { Vec3, Vec3T } from './vec3.js'; -import { InParentNamespace, InParentNamespaceT } from '../in-parent-namespace.js'; +import { Monster as MyGame_Example2_Monster, MonsterT as MyGame_Example2_MonsterT } from '../../my-game/example2/monster.js'; +import { Ability, AbilityT } from '../../my-game/example/ability.js'; +import { Any, unionToAny, unionListToAny } from '../../my-game/example/any.js'; +import { AnyAmbiguousAliases, unionToAnyAmbiguousAliases, unionListToAnyAmbiguousAliases } from '../../my-game/example/any-ambiguous-aliases.js'; +import { AnyUniqueAliases, unionToAnyUniqueAliases, unionListToAnyUniqueAliases } from '../../my-game/example/any-unique-aliases.js'; +import { Color } from '../../my-game/example/color.js'; +import { Race } from '../../my-game/example/race.js'; +import { Referrable, ReferrableT } from '../../my-game/example/referrable.js'; +import { Stat, StatT } from '../../my-game/example/stat.js'; +import { Test, TestT } from '../../my-game/example/test.js'; +import { TestSimpleTableWithEnum, TestSimpleTableWithEnumT } from '../../my-game/example/test-simple-table-with-enum.js'; +import { Vec3, Vec3T } from '../../my-game/example/vec3.js'; +import { InParentNamespace, InParentNamespaceT } from '../../my-game/in-parent-namespace.js'; /** @@ -81,11 +81,11 @@ mutate_hp(value:number):boolean { return true; } -name():string -name(optionalEncoding:flatbuffers.Encoding):string|Uint8Array -name(optionalEncoding?:any):string|Uint8Array { +name():string|null +name(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null +name(optionalEncoding?:any):string|Uint8Array|null { const offset = this.bb!.__offset(this.bb_pos, 10); - return this.bb!.__string(this.bb_pos + offset, optionalEncoding); + return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null; } inventory(index: number):number|null { diff --git a/tests/ts/my-game/example/struct-of-structs-of-structs.ts b/tests/ts/my-game/example/struct-of-structs-of-structs.ts index f47d42d24..af3519a01 100644 --- a/tests/ts/my-game/example/struct-of-structs-of-structs.ts +++ b/tests/ts/my-game/example/struct-of-structs-of-structs.ts @@ -4,7 +4,7 @@ import * as flatbuffers from 'flatbuffers'; -import { StructOfStructs, StructOfStructsT } from './struct-of-structs.js'; +import { StructOfStructs, StructOfStructsT } from '../../my-game/example/struct-of-structs.js'; export class StructOfStructsOfStructs implements flatbuffers.IUnpackableObject { diff --git a/tests/ts/my-game/example/struct-of-structs.ts b/tests/ts/my-game/example/struct-of-structs.ts index c3ff69da3..2f4a36748 100644 --- a/tests/ts/my-game/example/struct-of-structs.ts +++ b/tests/ts/my-game/example/struct-of-structs.ts @@ -4,8 +4,8 @@ import * as flatbuffers from 'flatbuffers'; -import { Ability, AbilityT } from './ability.js'; -import { Test, TestT } from './test.js'; +import { Ability, AbilityT } from '../../my-game/example/ability.js'; +import { Test, TestT } from '../../my-game/example/test.js'; export class StructOfStructs implements flatbuffers.IUnpackableObject { diff --git a/tests/ts/my-game/example/test-simple-table-with-enum.ts b/tests/ts/my-game/example/test-simple-table-with-enum.ts index ac9d7add2..3e8b4c03f 100644 --- a/tests/ts/my-game/example/test-simple-table-with-enum.ts +++ b/tests/ts/my-game/example/test-simple-table-with-enum.ts @@ -4,7 +4,7 @@ import * as flatbuffers from 'flatbuffers'; -import { Color } from './color.js'; +import { Color } from '../../my-game/example/color.js'; export class TestSimpleTableWithEnum implements flatbuffers.IUnpackableObject { diff --git a/tests/ts/my-game/example/vec3.ts b/tests/ts/my-game/example/vec3.ts index a5fd359fe..a2092d700 100644 --- a/tests/ts/my-game/example/vec3.ts +++ b/tests/ts/my-game/example/vec3.ts @@ -4,8 +4,8 @@ import * as flatbuffers from 'flatbuffers'; -import { Color } from './color.js'; -import { Test, TestT } from './test.js'; +import { Color } from '../../my-game/example/color.js'; +import { Test, TestT } from '../../my-game/example/test.js'; export class Vec3 implements flatbuffers.IUnpackableObject { diff --git a/tests/ts/optional-scalars/scalar-stuff.ts b/tests/ts/optional-scalars/scalar-stuff.ts index 69961af26..7f6fdcaae 100644 --- a/tests/ts/optional-scalars/scalar-stuff.ts +++ b/tests/ts/optional-scalars/scalar-stuff.ts @@ -4,7 +4,7 @@ import * as flatbuffers from 'flatbuffers'; -import { OptionalByte } from './optional-byte.js'; +import { OptionalByte } from '../optional-scalars/optional-byte.js'; export class ScalarStuff { diff --git a/tests/ts/package.json b/tests/ts/package.json index 6afc78544..1639cf831 100644 --- a/tests/ts/package.json +++ b/tests/ts/package.json @@ -1,6 +1,6 @@ { "type": "module", "dependencies": { - "flatbuffers": "workspace:*" + "flatbuffers": "../../" } } diff --git a/tests/ts/pnpm-lock.yaml b/tests/ts/pnpm-lock.yaml new file mode 100644 index 000000000..730e4d7b2 --- /dev/null +++ b/tests/ts/pnpm-lock.yaml @@ -0,0 +1,10 @@ +lockfileVersion: '6.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +dependencies: + flatbuffers: + specifier: ../../ + version: link:../.. diff --git a/tests/ts/tsconfig.json b/tests/ts/tsconfig.json index 113fb3767..62a31c438 100644 --- a/tests/ts/tsconfig.json +++ b/tests/ts/tsconfig.json @@ -1,10 +1,7 @@ { "compilerOptions": { "target": "ES2020", - "lib": [ - "ES2020", - "DOM" - ], + "lib": ["ES2020", "DOM"], "module": "NodeNext", "declaration": true, "strict": true @@ -20,7 +17,6 @@ "arrays_test_complex/**/*.ts", "union_underlying_type_test.ts", "long-namespace/**/*.ts", - "longer-namespace/**/*.ts", - "relative_imports/**/*.ts" + "longer-namespace/**/*.ts" ] -} \ No newline at end of file +}