diff --git a/.clang-format b/.clang-format index 7da2b4389e5..bb2e3440d42 100644 --- a/.clang-format +++ b/.clang-format @@ -1,13 +1,5 @@ --- Language: Cpp BasedOnStyle: Google -DerivePointerAlignment: false -PointerAlignment: Right -IndentPPDirectives: AfterHash -Cpp11BracedListStyle: false -AlwaysBreakTemplateDeclarations: false -AllowShortCaseLabelsOnASingleLine: true -SpaceAfterTemplateKeyword: false -AllowShortBlocksOnASingleLine: true ... diff --git a/.eslintrc.js b/.eslintrc.js deleted file mode 100644 index 321169b07c0..00000000000 --- a/.eslintrc.js +++ /dev/null @@ -1,13 +0,0 @@ -/* eslint-env node */ - -module.exports = { - root: true, - parser: '@typescript-eslint/parser', - plugins: [ - '@typescript-eslint', - ], - extends: [ - 'eslint:recommended', - 'plugin:@typescript-eslint/recommended', - ] -}; \ No newline at end of file diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 2a763167b9f..0d6e6e614a4 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -129,7 +129,7 @@ jobs: build-cpp-std: name: Build Windows C++ - runs-on: windows-2019 + runs-on: windows-2022 strategy: matrix: std: [11, 14, 17, 20, 23] @@ -140,7 +140,7 @@ jobs: uses: microsoft/setup-msbuild@v1.1 - name: cmake run: > - cmake -G "Visual Studio 16 2019" -A x64 -DCMAKE_BUILD_TYPE=Release + cmake -G "Visual Studio 17 2022" -A x64 -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_STRICT_MODE=ON -DFLATBUFFERS_CPP_STD=${{ matrix.std }} -DFLATBUFFERS_BUILD_CPP17=${{ matrix.std >= 17 && 'On' || 'Off'}} @@ -157,14 +157,14 @@ jobs: contents: write outputs: digests: ${{ steps.hash.outputs.hashes }} - name: Build Windows 2019 - runs-on: windows-2019 + name: Build Windows 2022 + runs-on: windows-2022 steps: - uses: actions/checkout@v3 - name: Add msbuild to PATH uses: microsoft/setup-msbuild@v1.1 - name: cmake - run: cmake -G "Visual Studio 16 2019" -A x64 -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_BUILD_CPP17=ON -DFLATBUFFERS_STRICT_MODE=ON . + run: cmake -G "Visual Studio 17 2022" -A x64 -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_BUILD_CPP17=ON -DFLATBUFFERS_STRICT_MODE=ON . - name: build run: msbuild.exe FlatBuffers.sln /p:Configuration=Release /p:Platform=x64 - name: test @@ -310,14 +310,17 @@ jobs: build-android: name: Build Android (on Linux) + if: false #disabled due to continual failure runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v3 - name: set up Java - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: - distribution: 'temurin' - java-version: '11' + distribution: temurin + java-version: 17 + - name: set up Gradle + uses: gradle/actions/setup-gradle@v4 - name: set up flatc run: | cmake -DFLATBUFFERS_BUILD_TESTS=OFF -DFLATBUFFERS_BUILD_FLATLIB=OFF -DFLATBUFFERS_BUILD_FLATHASH=OFF -DFLATBUFFERS_STRICT_MODE=ON . @@ -344,13 +347,13 @@ jobs: build-generator-windows: name: Check Generated Code on Windows - runs-on: windows-2019 + runs-on: windows-2022 steps: - uses: actions/checkout@v3 - name: Add msbuild to PATH uses: microsoft/setup-msbuild@v1.1 - name: cmake - run: cmake -G "Visual Studio 16 2019" -A x64 -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_BUILD_CPP17=ON -DFLATBUFFERS_STRICT_MODE=ON . + run: cmake -G "Visual Studio 17 2022" -A x64 -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_BUILD_CPP17=ON -DFLATBUFFERS_STRICT_MODE=ON . - name: build run: msbuild.exe FlatBuffers.sln /p:Configuration=Release /p:Platform=x64 - name: Generate @@ -394,15 +397,17 @@ jobs: # Force Xcode 14.3 since Xcode 15 doesnt support older versions of # kotlin. For Xcode 15, kotlin should be bumpped to 1.9.10 # https://stackoverflow.com/a/77150623 - # For now, run with macos-13 which has this 14.3 installed: + # For now, run with macos-13 which has this 14.3 installed: # https://github.com/actions/runner-images/blob/main/images/macos/macos-13-Readme.md#xcode - name: Set up Xcode version run: sudo xcode-select -s /Applications/Xcode_14.3.app/Contents/Developer - - uses: gradle/wrapper-validation-action@v1.0.5 - - uses: actions/setup-java@v3 + - name: set up Java + uses: actions/setup-java@v4 with: - distribution: 'temurin' - java-version: '11' + distribution: temurin + java-version: 17 + - name: set up Gradle + uses: gradle/actions/setup-gradle@v4 - name: Build flatc run: | cmake -DFLATBUFFERS_BUILD_TESTS=OFF -DFLATBUFFERS_BUILD_FLATLIB=OFF -DFLATBUFFERS_BUILD_FLATHASH=OFF . @@ -414,15 +419,18 @@ jobs: build-kotlin-linux: name: Build Kotlin Linux + if: false #disabled due to continual failure runs-on: ubuntu-24.04 steps: - name: Checkout uses: actions/checkout@v3 - - uses: actions/setup-java@v3 + - name: set up Java + uses: actions/setup-java@v4 with: - distribution: 'temurin' - java-version: '11' - - uses: gradle/wrapper-validation-action@v1.0.5 + distribution: temurin + java-version: 17 + - name: set up Gradle + uses: gradle/actions/setup-gradle@v4 - name: Build flatc run: | cmake -DFLATBUFFERS_BUILD_TESTS=OFF -DFLATBUFFERS_BUILD_FLATLIB=OFF -DFLATBUFFERS_BUILD_FLATHASH=OFF . @@ -492,27 +500,37 @@ jobs: sh phpUnionVectorTest.sh build-swift: - name: Build Swift + name: Test Swift strategy: matrix: - swift: ["5.9", "5.10", "6.0"] + swift: ["5.9", "5.10", "6.1"] # Only 22.04 has swift at the moment https://github.com/actions/runner-images/blob/main/images/ubuntu/Ubuntu2204-Readme.md?plain=1#L30 runs-on: ubuntu-22.04 steps: - uses: actions/checkout@v3 - - uses: swift-actions/setup-swift@v2 + - uses: vapor/swiftly-action@v0.2 with: - swift-version: ${{ matrix.swift }} + toolchain: ${{ matrix.swift }} - name: Get swift version run: swift --version - name: test - working-directory: tests/swift/tests run: | swift build --build-tests swift test + build-swift-windows: + name: Test swift windows + runs-on: windows-latest + steps: + - uses: actions/checkout@v3 + - uses: SwiftyLab/setup-swift@latest + with: + swift-version: '6.1' + - run: swift build + - run: swift test + build-swift-wasm: - name: Build Swift Wasm + name: Test Swift Wasm runs-on: ubuntu-24.04 container: image: ghcr.io/swiftwasm/carton:0.20.1 @@ -534,14 +552,15 @@ jobs: - name: flatc # FIXME: make test script not rely on flatc run: cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_BUILD_TESTS=OFF -DFLATBUFFERS_INSTALL=OFF -DFLATBUFFERS_BUILD_FLATLIB=OFF -DFLATBUFFERS_BUILD_FLATHASH=OFF . && make -j + - name: pnpm + run: npm install -g pnpm esbuild - name: deps - run: yarn + run: pnpm i - name: compile - run: yarn compile + run: pnpm compile - name: test working-directory: tests/ts run: | - yarn global add esbuild python3 TypeScriptTest.py build-dart: @@ -582,12 +601,12 @@ jobs: - uses: actions/checkout@v3 - name: bazel build run: > - bazel build + bazel build //:flatc //:flatbuffers - name: bazel test run: > - bazel test + bazel test //tests:flatbuffers_test release-digests: diff --git a/CHANGELOG.md b/CHANGELOG.md index bb713fd632e..e38b0835a03 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,13 @@ All major or breaking changes will be documented in this file, as well as any new features that should be highlighted. Minor fixes or improvements are not necessarily listed. +## [25.9.23] (September 23 2025)(https://github.com/google/flatbuffers/releases/tag/v25.9.23) + +* flatc: `--grpc-callback-api` flag generates C++ gRPC Callback API server `CallbackService` skeletons AND client native callback/async stubs (unary + all streaming reactor forms) (opt-in, non-breaking, issue #8596). +* Swift - Adds new API to reduce memory copying within swift (#8484) +* Rust - Support Rust edition 2024 (#8638) +# [:C++] - Use the Google Style for clang-format without exceptions (#8706) + ## [25.2.10] (February 10 2025)(https://github.com/google/flatbuffers/releases/tag/v25.2.10) * Removed the old documentation pages. The new one is live at https://flatbuffers.dev diff --git a/CMake/Version.cmake b/CMake/Version.cmake index fe432980fef..ba784265a28 100644 --- a/CMake/Version.cmake +++ b/CMake/Version.cmake @@ -1,6 +1,6 @@ set(VERSION_MAJOR 25) -set(VERSION_MINOR 2) -set(VERSION_PATCH 10) +set(VERSION_MINOR 9) +set(VERSION_PATCH 23) set(VERSION_COMMIT 0) if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/.git") diff --git a/CMakeLists.txt b/CMakeLists.txt index e7038f89d73..f7f388f83ec 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -112,6 +112,7 @@ endif() add_definitions(-DFLATBUFFERS_LOCALE_INDEPENDENT=$) if(NOT WIN32) + include(CheckSymbolExists) check_symbol_exists(realpath "stdlib.h" HAVE_REALPATH) if(NOT HAVE_REALPATH) add_definitions(-DFLATBUFFERS_NO_ABSOLUTE_PATH_RESOLUTION) @@ -278,6 +279,8 @@ set(FlatBuffers_GRPCTest_SRCS tests/test_builder.cpp grpc/tests/grpctest.cpp grpc/tests/message_builder_test.cpp + grpc/tests/grpctest_callback_compile.cpp + grpc/tests/grpctest_callback_client_compile.cpp ) # TODO(dbaileychess): Figure out how this would now work. I posted a question on diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 17428add545..df4eee55eb6 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -40,3 +40,26 @@ Some tips for good pull requests: # The small print Contributions made by corporations are covered by a different agreement than the one above, the Software Grant and Corporate Contributor License Agreement. + +# Code + +TL/DR + +See [how to build flatc](https://flatbuffers.dev/building/). + +When making changes, build `flatc` and then re-generate the goldens files to see the effect of your changes: + +``` +$ cp build/flatc . +$ goldens/generate_goldens.py +``` + +Re-generate other code files to see the effects of the changes: + +``` +$ scripts/generate_code.py +``` + +Run tests with [TestAll.sh](tests/TestAll.sh) in [tests](tests), or directly any of the sub-scripts run by it. + +[Format the code](Formatters.md) before submitting a PR. diff --git a/FlatBuffers.podspec b/FlatBuffers.podspec index 61c318fd5b9..95e04b8aa59 100644 --- a/FlatBuffers.podspec +++ b/FlatBuffers.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = 'FlatBuffers' - s.version = '25.2.10' + s.version = '25.9.23' s.summary = 'FlatBuffers: Memory Efficient Serialization Library' s.description = "FlatBuffers is a cross platform serialization library architected for diff --git a/MODULE.bazel b/MODULE.bazel index d0f0f5b2773..a2f0d2d6d7a 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -1,6 +1,6 @@ module( name = "flatbuffers", - version = "25.2.10", + version = "25.9.23", compatibility_level = 1, repo_name = "com_github_google_flatbuffers", ) @@ -15,11 +15,11 @@ bazel_dep( ) bazel_dep( name = "aspect_rules_js", - version = "2.1.3", + version = "2.3.8", ) bazel_dep( name = "aspect_rules_ts", - version = "3.4.0", + version = "3.6.0", ) bazel_dep( name = "grpc", diff --git a/Package.swift b/Package.swift index ad6f0e866c2..57ce61e6b1c 100644 --- a/Package.swift +++ b/Package.swift @@ -20,17 +20,61 @@ import PackageDescription let package = Package( name: "FlatBuffers", platforms: [ - .iOS(.v11), + .iOS(.v12), .macOS(.v10_14), ], products: [ .library( name: "FlatBuffers", targets: ["FlatBuffers"]), + .library( + name: "FlexBuffers", + targets: ["FlexBuffers"]), ], + dependencies: .dependencies, targets: [ .target( name: "FlatBuffers", - dependencies: [], - path: "swift/Sources"), + dependencies: ["Common"], + path: "swift/Sources/FlatBuffers"), + .target( + name: "FlexBuffers", + dependencies: ["Common"], + path: "swift/Sources/FlexBuffers"), + .target( + name: "Common", + path: "swift/Sources/Common"), + .testTarget( + name: "FlatbuffersTests", + dependencies: .dependencies, + path: "tests/swift/Tests/Flatbuffers"), + .testTarget( + name: "FlexbuffersTests", + dependencies: ["FlexBuffers"], + path: "tests/swift/Tests/Flexbuffers"), ]) + +extension Array where Element == Package.Dependency { + static var dependencies: [Package.Dependency] { + #if os(Windows) + [] + #else + // Test only Dependency + [.package(url: "https://github.com/grpc/grpc-swift.git", from: "1.4.1")] + #endif + } +} + +extension Array where Element == PackageDescription.Target.Dependency { + static var dependencies: [PackageDescription.Target.Dependency] { + #if os(Windows) + ["FlatBuffers"] + #else + // Test only Dependency + [ + .product(name: "GRPC", package: "grpc-swift"), + "FlatBuffers", + ] + #endif + } +} diff --git a/README.md b/README.md index 7b64a427d08..ed3637afb75 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -![logo](http://google.github.io/flatbuffers/fpl_logo_small.png) FlatBuffers +![logo](https://flatbuffers.dev/assets/flatbuffers_logo.svg) FlatBuffers =========== ![Build status](https://github.com/google/flatbuffers/actions/workflows/build.yml/badge.svg?branch=master) diff --git a/android/app/src/main/cpp/generated/animal_generated.h b/android/app/src/main/cpp/generated/animal_generated.h index 21d92f82f6c..a34bce4f85a 100644 --- a/android/app/src/main/cpp/generated/animal_generated.h +++ b/android/app/src/main/cpp/generated/animal_generated.h @@ -1,6 +1,5 @@ // automatically generated by the FlatBuffers compiler, do not modify - #ifndef FLATBUFFERS_GENERATED_ANIMAL_COM_FBS_APP_H_ #define FLATBUFFERS_GENERATED_ANIMAL_COM_FBS_APP_H_ @@ -9,9 +8,9 @@ // Ensure the included flatbuffers.h is the same version as when this file was // generated, otherwise it may not be compatible. static_assert(FLATBUFFERS_VERSION_MAJOR == 24 && - FLATBUFFERS_VERSION_MINOR == 12 && - FLATBUFFERS_VERSION_REVISION == 23, - "Non-compatible flatbuffers version included"); + FLATBUFFERS_VERSION_MINOR == 12 && + FLATBUFFERS_VERSION_REVISION == 23, + "Non-compatible flatbuffers version included"); namespace com { namespace fbs { @@ -27,29 +26,24 @@ struct Animal FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { VT_SOUND = 6, VT_WEIGHT = 8 }; - const ::flatbuffers::String *name() const { - return GetPointer(VT_NAME); - } - const ::flatbuffers::String *sound() const { - return GetPointer(VT_SOUND); + const ::flatbuffers::String* name() const { + return GetPointer(VT_NAME); } - uint16_t weight() const { - return GetField(VT_WEIGHT, 0); + const ::flatbuffers::String* sound() const { + return GetPointer(VT_SOUND); } - bool Verify(::flatbuffers::Verifier &verifier) const { - return VerifyTableStart(verifier) && - VerifyOffset(verifier, VT_NAME) && - verifier.VerifyString(name()) && - VerifyOffset(verifier, VT_SOUND) && + uint16_t weight() const { return GetField(VT_WEIGHT, 0); } + bool Verify(::flatbuffers::Verifier& verifier) const { + return VerifyTableStart(verifier) && VerifyOffset(verifier, VT_NAME) && + verifier.VerifyString(name()) && VerifyOffset(verifier, VT_SOUND) && verifier.VerifyString(sound()) && - VerifyField(verifier, VT_WEIGHT, 2) && - verifier.EndTable(); + VerifyField(verifier, VT_WEIGHT, 2) && verifier.EndTable(); } }; struct AnimalBuilder { typedef Animal Table; - ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::FlatBufferBuilder& fbb_; ::flatbuffers::uoffset_t start_; void add_name(::flatbuffers::Offset<::flatbuffers::String> name) { fbb_.AddOffset(Animal::VT_NAME, name); @@ -60,8 +54,7 @@ struct AnimalBuilder { void add_weight(uint16_t weight) { fbb_.AddElement(Animal::VT_WEIGHT, weight, 0); } - explicit AnimalBuilder(::flatbuffers::FlatBufferBuilder &_fbb) - : fbb_(_fbb) { + explicit AnimalBuilder(::flatbuffers::FlatBufferBuilder& _fbb) : fbb_(_fbb) { start_ = fbb_.StartTable(); } ::flatbuffers::Offset Finish() { @@ -72,7 +65,7 @@ struct AnimalBuilder { }; inline ::flatbuffers::Offset CreateAnimal( - ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::FlatBufferBuilder& _fbb, ::flatbuffers::Offset<::flatbuffers::String> name = 0, ::flatbuffers::Offset<::flatbuffers::String> sound = 0, uint16_t weight = 0) { @@ -84,45 +77,37 @@ inline ::flatbuffers::Offset CreateAnimal( } inline ::flatbuffers::Offset CreateAnimalDirect( - ::flatbuffers::FlatBufferBuilder &_fbb, - const char *name = nullptr, - const char *sound = nullptr, - uint16_t weight = 0) { + ::flatbuffers::FlatBufferBuilder& _fbb, const char* name = nullptr, + const char* sound = nullptr, uint16_t weight = 0) { auto name__ = name ? _fbb.CreateString(name) : 0; auto sound__ = sound ? _fbb.CreateString(sound) : 0; - return com::fbs::app::CreateAnimal( - _fbb, - name__, - sound__, - weight); + return com::fbs::app::CreateAnimal(_fbb, name__, sound__, weight); } -inline const com::fbs::app::Animal *GetAnimal(const void *buf) { +inline const com::fbs::app::Animal* GetAnimal(const void* buf) { return ::flatbuffers::GetRoot(buf); } -inline const com::fbs::app::Animal *GetSizePrefixedAnimal(const void *buf) { +inline const com::fbs::app::Animal* GetSizePrefixedAnimal(const void* buf) { return ::flatbuffers::GetSizePrefixedRoot(buf); } -inline bool VerifyAnimalBuffer( - ::flatbuffers::Verifier &verifier) { +inline bool VerifyAnimalBuffer(::flatbuffers::Verifier& verifier) { return verifier.VerifyBuffer(nullptr); } -inline bool VerifySizePrefixedAnimalBuffer( - ::flatbuffers::Verifier &verifier) { +inline bool VerifySizePrefixedAnimalBuffer(::flatbuffers::Verifier& verifier) { return verifier.VerifySizePrefixedBuffer(nullptr); } inline void FinishAnimalBuffer( - ::flatbuffers::FlatBufferBuilder &fbb, + ::flatbuffers::FlatBufferBuilder& fbb, ::flatbuffers::Offset root) { fbb.Finish(root); } inline void FinishSizePrefixedAnimalBuffer( - ::flatbuffers::FlatBufferBuilder &fbb, + ::flatbuffers::FlatBufferBuilder& fbb, ::flatbuffers::Offset root) { fbb.FinishSizePrefixed(root); } diff --git a/android/app/src/main/java/com/flatbuffers/app/MainActivity.kt b/android/app/src/main/java/com/flatbuffers/app/MainActivity.kt index cdc35730e3e..8bf7a1c9a8a 100644 --- a/android/app/src/main/java/com/flatbuffers/app/MainActivity.kt +++ b/android/app/src/main/java/com/flatbuffers/app/MainActivity.kt @@ -1,9 +1,9 @@ package com.flatbuffers.app import android.annotation.SuppressLint -import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.TextView +import androidx.appcompat.app.AppCompatActivity import com.fbs.app.Animal import com.google.flatbuffers.FlatBufferBuilder import java.nio.ByteBuffer @@ -27,14 +27,15 @@ class MainActivity : AppCompatActivity() { private external fun createAnimalFromJNI(): ByteArray // Create a "Cow" Animal flatbuffers from Kotlin - private fun createAnimalFromKotlin():Animal { + private fun createAnimalFromKotlin(): Animal { val fb = FlatBufferBuilder(100) - val cowOffset = Animal.createAnimal( - builder = fb, - nameOffset = fb.createString("Cow"), - soundOffset = fb.createString("Moo"), - weight = 720u - ) + val cowOffset = + Animal.createAnimal( + builder = fb, + nameOffset = fb.createString("Cow"), + soundOffset = fb.createString("Moo"), + weight = 720u, + ) fb.finish(cowOffset) return Animal.getRootAsAnimal(fb.dataBuffer()) } diff --git a/android/app/src/main/java/generated/com/fbs/app/Animal.kt b/android/app/src/main/java/generated/com/fbs/app/Animal.kt index ffa8e0a571e..f9243cbd9d9 100644 --- a/android/app/src/main/java/generated/com/fbs/app/Animal.kt +++ b/android/app/src/main/java/generated/com/fbs/app/Animal.kt @@ -2,83 +2,101 @@ package com.fbs.app -import com.google.flatbuffers.BaseVector -import com.google.flatbuffers.BooleanVector -import com.google.flatbuffers.ByteVector import com.google.flatbuffers.Constants -import com.google.flatbuffers.DoubleVector import com.google.flatbuffers.FlatBufferBuilder -import com.google.flatbuffers.FloatVector -import com.google.flatbuffers.LongVector -import com.google.flatbuffers.StringVector -import com.google.flatbuffers.Struct import com.google.flatbuffers.Table -import com.google.flatbuffers.UnionVector import java.nio.ByteBuffer import java.nio.ByteOrder -import kotlin.math.sign @Suppress("unused") @kotlin.ExperimentalUnsignedTypes class Animal : Table() { - fun __init(_i: Int, _bb: ByteBuffer) { - __reset(_i, _bb) + fun __init(_i: Int, _bb: ByteBuffer) { + __reset(_i, _bb) + } + + fun __assign(_i: Int, _bb: ByteBuffer): Animal { + __init(_i, _bb) + return this + } + + val name: String? + get() { + val o = __offset(4) + return if (o != 0) { + __string(o + bb_pos) + } else { + null + } + } + + val nameAsByteBuffer: ByteBuffer + get() = __vector_as_bytebuffer(4, 1) + + fun nameInByteBuffer(_bb: ByteBuffer): ByteBuffer = __vector_in_bytebuffer(_bb, 4, 1) + + val sound: String? + get() { + val o = __offset(6) + return if (o != 0) { + __string(o + bb_pos) + } else { + null + } + } + + val soundAsByteBuffer: ByteBuffer + get() = __vector_as_bytebuffer(6, 1) + + fun soundInByteBuffer(_bb: ByteBuffer): ByteBuffer = __vector_in_bytebuffer(_bb, 6, 1) + + val weight: UShort + get() { + val o = __offset(8) + return if (o != 0) bb.getShort(o + bb_pos).toUShort() else 0u + } + + companion object { + fun validateVersion() = Constants.FLATBUFFERS_25_9_23() + + fun getRootAsAnimal(_bb: ByteBuffer): Animal = getRootAsAnimal(_bb, Animal()) + + fun getRootAsAnimal(_bb: ByteBuffer, obj: Animal): Animal { + _bb.order(ByteOrder.LITTLE_ENDIAN) + return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)) } - fun __assign(_i: Int, _bb: ByteBuffer) : Animal { - __init(_i, _bb) - return this + + fun createAnimal( + builder: FlatBufferBuilder, + nameOffset: Int, + soundOffset: Int, + weight: UShort, + ): Int { + builder.startTable(3) + addSound(builder, soundOffset) + addName(builder, nameOffset) + addWeight(builder, weight) + return endAnimal(builder) } - val name : String? - get() { - val o = __offset(4) - return if (o != 0) { - __string(o + bb_pos) - } else { - null - } - } - val nameAsByteBuffer : ByteBuffer get() = __vector_as_bytebuffer(4, 1) - fun nameInByteBuffer(_bb: ByteBuffer) : ByteBuffer = __vector_in_bytebuffer(_bb, 4, 1) - val sound : String? - get() { - val o = __offset(6) - return if (o != 0) { - __string(o + bb_pos) - } else { - null - } - } - val soundAsByteBuffer : ByteBuffer get() = __vector_as_bytebuffer(6, 1) - fun soundInByteBuffer(_bb: ByteBuffer) : ByteBuffer = __vector_in_bytebuffer(_bb, 6, 1) - val weight : UShort - get() { - val o = __offset(8) - return if(o != 0) bb.getShort(o + bb_pos).toUShort() else 0u - } - companion object { - fun validateVersion() = Constants.FLATBUFFERS_25_2_10() - fun getRootAsAnimal(_bb: ByteBuffer): Animal = getRootAsAnimal(_bb, Animal()) - fun getRootAsAnimal(_bb: ByteBuffer, obj: Animal): Animal { - _bb.order(ByteOrder.LITTLE_ENDIAN) - return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)) - } - fun createAnimal(builder: FlatBufferBuilder, nameOffset: Int, soundOffset: Int, weight: UShort) : Int { - builder.startTable(3) - addSound(builder, soundOffset) - addName(builder, nameOffset) - addWeight(builder, weight) - return endAnimal(builder) - } - fun startAnimal(builder: FlatBufferBuilder) = builder.startTable(3) - fun addName(builder: FlatBufferBuilder, name: Int) = builder.addOffset(0, name, 0) - fun addSound(builder: FlatBufferBuilder, sound: Int) = builder.addOffset(1, sound, 0) - fun addWeight(builder: FlatBufferBuilder, weight: UShort) = builder.addShort(2, weight.toShort(), 0) - fun endAnimal(builder: FlatBufferBuilder) : Int { - val o = builder.endTable() - return o - } - fun finishAnimalBuffer(builder: FlatBufferBuilder, offset: Int) = builder.finish(offset) - fun finishSizePrefixedAnimalBuffer(builder: FlatBufferBuilder, offset: Int) = builder.finishSizePrefixed(offset) + + fun startAnimal(builder: FlatBufferBuilder) = builder.startTable(3) + + fun addName(builder: FlatBufferBuilder, name: Int) = builder.addOffset(0, name, 0) + + fun addSound(builder: FlatBufferBuilder, sound: Int) = builder.addOffset(1, sound, 0) + + fun addWeight(builder: FlatBufferBuilder, weight: UShort) = + builder.addShort(2, weight.toShort(), 0) + + fun endAnimal(builder: FlatBufferBuilder): Int { + val o = builder.endTable() + return o } + + fun finishAnimalBuffer(builder: FlatBufferBuilder, offset: Int) = builder.finish(offset) + + fun finishSizePrefixedAnimalBuffer(builder: FlatBufferBuilder, offset: Int) = + builder.finishSizePrefixed(offset) + } } diff --git a/benchmarks/cpp/bench.h b/benchmarks/cpp/bench.h index ad4baebf51c..f358d210d0c 100644 --- a/benchmarks/cpp/bench.h +++ b/benchmarks/cpp/bench.h @@ -8,12 +8,12 @@ struct Bench { inline void Add(int64_t value) { sum += value; } - virtual uint8_t *Encode(void *buf, int64_t &len) = 0; - virtual void *Decode(void *buf, int64_t len) = 0; - virtual int64_t Use(void *decoded) = 0; - virtual void Dealloc(void *decoded) = 0; + virtual uint8_t* Encode(void* buf, int64_t& len) = 0; + virtual void* Decode(void* buf, int64_t len) = 0; + virtual int64_t Use(void* decoded) = 0; + virtual void Dealloc(void* decoded) = 0; int64_t sum = 0; }; -#endif // BENCHMARKS_CPP_BENCH_H_ \ No newline at end of file +#endif // BENCHMARKS_CPP_BENCH_H_ \ No newline at end of file diff --git a/benchmarks/cpp/flatbuffers/bench_generated.h b/benchmarks/cpp/flatbuffers/bench_generated.h index f5f04bd97d0..e53a868c656 100644 --- a/benchmarks/cpp/flatbuffers/bench_generated.h +++ b/benchmarks/cpp/flatbuffers/bench_generated.h @@ -1,6 +1,5 @@ // automatically generated by the FlatBuffers compiler, do not modify - #ifndef FLATBUFFERS_GENERATED_BENCH_BENCHMARKS_FLATBUFFERS_H_ #define FLATBUFFERS_GENERATED_BENCH_BENCHMARKS_FLATBUFFERS_H_ @@ -9,9 +8,9 @@ // Ensure the included flatbuffers.h is the same version as when this file was // generated, otherwise it may not be compatible. static_assert(FLATBUFFERS_VERSION_MAJOR == 24 && - FLATBUFFERS_VERSION_MINOR == 12 && - FLATBUFFERS_VERSION_REVISION == 23, - "Non-compatible flatbuffers version included"); + FLATBUFFERS_VERSION_MINOR == 12 && + FLATBUFFERS_VERSION_REVISION == 23, + "Non-compatible flatbuffers version included"); namespace benchmarks_flatbuffers { @@ -34,25 +33,16 @@ enum Enum : int16_t { }; inline const Enum (&EnumValuesEnum())[3] { - static const Enum values[] = { - Enum_Apples, - Enum_Pears, - Enum_Bananas - }; + static const Enum values[] = {Enum_Apples, Enum_Pears, Enum_Bananas}; return values; } -inline const char * const *EnumNamesEnum() { - static const char * const names[4] = { - "Apples", - "Pears", - "Bananas", - nullptr - }; +inline const char* const* EnumNamesEnum() { + static const char* const names[4] = {"Apples", "Pears", "Bananas", nullptr}; return names; } -inline const char *EnumNameEnum(Enum e) { +inline const char* EnumNameEnum(Enum e) { if (flatbuffers::IsOutRange(e, Enum_Apples, Enum_Bananas)) return ""; const size_t index = static_cast(e); return EnumNamesEnum()[index]; @@ -67,12 +57,7 @@ FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(8) Foo FLATBUFFERS_FINAL_CLASS { uint32_t length_; public: - Foo() - : id_(0), - count_(0), - prefix_(0), - padding0__(0), - length_(0) { + Foo() : id_(0), count_(0), prefix_(0), padding0__(0), length_(0) { (void)padding0__; } Foo(uint64_t _id, int16_t _count, int8_t _prefix, uint32_t _length) @@ -83,18 +68,10 @@ FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(8) Foo FLATBUFFERS_FINAL_CLASS { length_(flatbuffers::EndianScalar(_length)) { (void)padding0__; } - uint64_t id() const { - return flatbuffers::EndianScalar(id_); - } - int16_t count() const { - return flatbuffers::EndianScalar(count_); - } - int8_t prefix() const { - return flatbuffers::EndianScalar(prefix_); - } - uint32_t length() const { - return flatbuffers::EndianScalar(length_); - } + uint64_t id() const { return flatbuffers::EndianScalar(id_); } + int16_t count() const { return flatbuffers::EndianScalar(count_); } + int8_t prefix() const { return flatbuffers::EndianScalar(prefix_); } + uint32_t length() const { return flatbuffers::EndianScalar(length_); } }; FLATBUFFERS_STRUCT_END(Foo, 16); @@ -104,20 +81,17 @@ FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(8) Bar FLATBUFFERS_FINAL_CLASS { int32_t time_; float ratio_; uint16_t size_; - int16_t padding0__; int32_t padding1__; + int16_t padding0__; + int32_t padding1__; public: Bar() - : parent_(), - time_(0), - ratio_(0), - size_(0), - padding0__(0), - padding1__(0) { + : parent_(), time_(0), ratio_(0), size_(0), padding0__(0), padding1__(0) { (void)padding0__; (void)padding1__; } - Bar(const benchmarks_flatbuffers::Foo &_parent, int32_t _time, float _ratio, uint16_t _size) + Bar(const benchmarks_flatbuffers::Foo& _parent, int32_t _time, float _ratio, + uint16_t _size) : parent_(_parent), time_(flatbuffers::EndianScalar(_time)), ratio_(flatbuffers::EndianScalar(_ratio)), @@ -127,18 +101,10 @@ FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(8) Bar FLATBUFFERS_FINAL_CLASS { (void)padding0__; (void)padding1__; } - const benchmarks_flatbuffers::Foo &parent() const { - return parent_; - } - int32_t time() const { - return flatbuffers::EndianScalar(time_); - } - float ratio() const { - return flatbuffers::EndianScalar(ratio_); - } - uint16_t size() const { - return flatbuffers::EndianScalar(size_); - } + const benchmarks_flatbuffers::Foo& parent() const { return parent_; } + int32_t time() const { return flatbuffers::EndianScalar(time_); } + float ratio() const { return flatbuffers::EndianScalar(ratio_); } + uint16_t size() const { return flatbuffers::EndianScalar(size_); } }; FLATBUFFERS_STRUCT_END(Bar, 32); @@ -150,34 +116,28 @@ struct FooBar FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table { VT_RATING = 8, VT_POSTFIX = 10 }; - const benchmarks_flatbuffers::Bar *sibling() const { - return GetStruct(VT_SIBLING); - } - const flatbuffers::String *name() const { - return GetPointer(VT_NAME); + const benchmarks_flatbuffers::Bar* sibling() const { + return GetStruct(VT_SIBLING); } - double rating() const { - return GetField(VT_RATING, 0.0); + const flatbuffers::String* name() const { + return GetPointer(VT_NAME); } - uint8_t postfix() const { - return GetField(VT_POSTFIX, 0); - } - bool Verify(flatbuffers::Verifier &verifier) const { + double rating() const { return GetField(VT_RATING, 0.0); } + uint8_t postfix() const { return GetField(VT_POSTFIX, 0); } + bool Verify(flatbuffers::Verifier& verifier) const { return VerifyTableStart(verifier) && VerifyField(verifier, VT_SIBLING, 8) && - VerifyOffset(verifier, VT_NAME) && - verifier.VerifyString(name()) && + VerifyOffset(verifier, VT_NAME) && verifier.VerifyString(name()) && VerifyField(verifier, VT_RATING, 8) && - VerifyField(verifier, VT_POSTFIX, 1) && - verifier.EndTable(); + VerifyField(verifier, VT_POSTFIX, 1) && verifier.EndTable(); } }; struct FooBarBuilder { typedef FooBar Table; - flatbuffers::FlatBufferBuilder &fbb_; + flatbuffers::FlatBufferBuilder& fbb_; flatbuffers::uoffset_t start_; - void add_sibling(const benchmarks_flatbuffers::Bar *sibling) { + void add_sibling(const benchmarks_flatbuffers::Bar* sibling) { fbb_.AddStruct(FooBar::VT_SIBLING, sibling); } void add_name(flatbuffers::Offset name) { @@ -189,8 +149,7 @@ struct FooBarBuilder { void add_postfix(uint8_t postfix) { fbb_.AddElement(FooBar::VT_POSTFIX, postfix, 0); } - explicit FooBarBuilder(flatbuffers::FlatBufferBuilder &_fbb) - : fbb_(_fbb) { + explicit FooBarBuilder(flatbuffers::FlatBufferBuilder& _fbb) : fbb_(_fbb) { start_ = fbb_.StartTable(); } flatbuffers::Offset Finish() { @@ -201,10 +160,9 @@ struct FooBarBuilder { }; inline flatbuffers::Offset CreateFooBar( - flatbuffers::FlatBufferBuilder &_fbb, - const benchmarks_flatbuffers::Bar *sibling = nullptr, - flatbuffers::Offset name = 0, - double rating = 0.0, + flatbuffers::FlatBufferBuilder& _fbb, + const benchmarks_flatbuffers::Bar* sibling = nullptr, + flatbuffers::Offset name = 0, double rating = 0.0, uint8_t postfix = 0) { FooBarBuilder builder_(_fbb); builder_.add_rating(rating); @@ -215,18 +173,12 @@ inline flatbuffers::Offset CreateFooBar( } inline flatbuffers::Offset CreateFooBarDirect( - flatbuffers::FlatBufferBuilder &_fbb, - const benchmarks_flatbuffers::Bar *sibling = nullptr, - const char *name = nullptr, - double rating = 0.0, - uint8_t postfix = 0) { + flatbuffers::FlatBufferBuilder& _fbb, + const benchmarks_flatbuffers::Bar* sibling = nullptr, + const char* name = nullptr, double rating = 0.0, uint8_t postfix = 0) { auto name__ = name ? _fbb.CreateString(name) : 0; - return benchmarks_flatbuffers::CreateFooBar( - _fbb, - sibling, - name__, - rating, - postfix); + return benchmarks_flatbuffers::CreateFooBar(_fbb, sibling, name__, rating, + postfix); } struct FooBarContainer FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table { @@ -237,49 +189,53 @@ struct FooBarContainer FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table { VT_FRUIT = 8, VT_LOCATION = 10 }; - const flatbuffers::Vector> *list() const { - return GetPointer> *>(VT_LIST); - } - bool initialized() const { - return GetField(VT_INITIALIZED, 0) != 0; + const flatbuffers::Vector< + flatbuffers::Offset>* + list() const { + return GetPointer>*>(VT_LIST); } + bool initialized() const { return GetField(VT_INITIALIZED, 0) != 0; } benchmarks_flatbuffers::Enum fruit() const { - return static_cast(GetField(VT_FRUIT, 0)); + return static_cast( + GetField(VT_FRUIT, 0)); } - const flatbuffers::String *location() const { - return GetPointer(VT_LOCATION); + const flatbuffers::String* location() const { + return GetPointer(VT_LOCATION); } - bool Verify(flatbuffers::Verifier &verifier) const { - return VerifyTableStart(verifier) && - VerifyOffset(verifier, VT_LIST) && + bool Verify(flatbuffers::Verifier& verifier) const { + return VerifyTableStart(verifier) && VerifyOffset(verifier, VT_LIST) && verifier.VerifyVector(list()) && verifier.VerifyVectorOfTables(list()) && VerifyField(verifier, VT_INITIALIZED, 1) && VerifyField(verifier, VT_FRUIT, 2) && VerifyOffset(verifier, VT_LOCATION) && - verifier.VerifyString(location()) && - verifier.EndTable(); + verifier.VerifyString(location()) && verifier.EndTable(); } }; struct FooBarContainerBuilder { typedef FooBarContainer Table; - flatbuffers::FlatBufferBuilder &fbb_; + flatbuffers::FlatBufferBuilder& fbb_; flatbuffers::uoffset_t start_; - void add_list(flatbuffers::Offset>> list) { + void add_list(flatbuffers::Offset>> + list) { fbb_.AddOffset(FooBarContainer::VT_LIST, list); } void add_initialized(bool initialized) { - fbb_.AddElement(FooBarContainer::VT_INITIALIZED, static_cast(initialized), 0); + fbb_.AddElement(FooBarContainer::VT_INITIALIZED, + static_cast(initialized), 0); } void add_fruit(benchmarks_flatbuffers::Enum fruit) { - fbb_.AddElement(FooBarContainer::VT_FRUIT, static_cast(fruit), 0); + fbb_.AddElement(FooBarContainer::VT_FRUIT, + static_cast(fruit), 0); } void add_location(flatbuffers::Offset location) { fbb_.AddOffset(FooBarContainer::VT_LOCATION, location); } - explicit FooBarContainerBuilder(flatbuffers::FlatBufferBuilder &_fbb) - : fbb_(_fbb) { + explicit FooBarContainerBuilder(flatbuffers::FlatBufferBuilder& _fbb) + : fbb_(_fbb) { start_ = fbb_.StartTable(); } flatbuffers::Offset Finish() { @@ -290,8 +246,10 @@ struct FooBarContainerBuilder { }; inline flatbuffers::Offset CreateFooBarContainer( - flatbuffers::FlatBufferBuilder &_fbb, - flatbuffers::Offset>> list = 0, + flatbuffers::FlatBufferBuilder& _fbb, + flatbuffers::Offset>> + list = 0, bool initialized = false, benchmarks_flatbuffers::Enum fruit = benchmarks_flatbuffers::Enum_Apples, flatbuffers::Offset location = 0) { @@ -304,47 +262,52 @@ inline flatbuffers::Offset CreateFooBarContainer( } inline flatbuffers::Offset CreateFooBarContainerDirect( - flatbuffers::FlatBufferBuilder &_fbb, - const std::vector> *list = nullptr, + flatbuffers::FlatBufferBuilder& _fbb, + const std::vector>* + list = nullptr, bool initialized = false, benchmarks_flatbuffers::Enum fruit = benchmarks_flatbuffers::Enum_Apples, - const char *location = nullptr) { - auto list__ = list ? _fbb.CreateVector>(*list) : 0; + const char* location = nullptr) { + auto list__ = + list ? _fbb.CreateVector< + flatbuffers::Offset>(*list) + : 0; auto location__ = location ? _fbb.CreateString(location) : 0; return benchmarks_flatbuffers::CreateFooBarContainer( - _fbb, - list__, - initialized, - fruit, - location__); + _fbb, list__, initialized, fruit, location__); } -inline const benchmarks_flatbuffers::FooBarContainer *GetFooBarContainer(const void *buf) { +inline const benchmarks_flatbuffers::FooBarContainer* GetFooBarContainer( + const void* buf) { return flatbuffers::GetRoot(buf); } -inline const benchmarks_flatbuffers::FooBarContainer *GetSizePrefixedFooBarContainer(const void *buf) { - return flatbuffers::GetSizePrefixedRoot(buf); +inline const benchmarks_flatbuffers::FooBarContainer* +GetSizePrefixedFooBarContainer(const void* buf) { + return flatbuffers::GetSizePrefixedRoot< + benchmarks_flatbuffers::FooBarContainer>(buf); } -inline bool VerifyFooBarContainerBuffer( - flatbuffers::Verifier &verifier) { - return verifier.VerifyBuffer(nullptr); +inline bool VerifyFooBarContainerBuffer(flatbuffers::Verifier& verifier) { + return verifier.VerifyBuffer( + nullptr); } inline bool VerifySizePrefixedFooBarContainerBuffer( - flatbuffers::Verifier &verifier) { - return verifier.VerifySizePrefixedBuffer(nullptr); + flatbuffers::Verifier& verifier) { + return verifier + .VerifySizePrefixedBuffer( + nullptr); } inline void FinishFooBarContainerBuffer( - flatbuffers::FlatBufferBuilder &fbb, + flatbuffers::FlatBufferBuilder& fbb, flatbuffers::Offset root) { fbb.Finish(root); } inline void FinishSizePrefixedFooBarContainerBuffer( - flatbuffers::FlatBufferBuilder &fbb, + flatbuffers::FlatBufferBuilder& fbb, flatbuffers::Offset root) { fbb.FinishSizePrefixed(root); } diff --git a/benchmarks/cpp/flatbuffers/fb_bench.h b/benchmarks/cpp/flatbuffers/fb_bench.h index ffb5f54c1a1..09eb2bac706 100644 --- a/benchmarks/cpp/flatbuffers/fb_bench.h +++ b/benchmarks/cpp/flatbuffers/fb_bench.h @@ -8,16 +8,16 @@ #include "include/flatbuffers/flatbuffers.h" struct StaticAllocator : public flatbuffers::Allocator { - explicit StaticAllocator(uint8_t *buffer) : buffer_(buffer) {} + explicit StaticAllocator(uint8_t* buffer) : buffer_(buffer) {} - uint8_t *allocate(size_t) override { return buffer_; } + uint8_t* allocate(size_t) override { return buffer_; } - void deallocate(uint8_t *, size_t) override {} + void deallocate(uint8_t*, size_t) override {} - uint8_t *buffer_; + uint8_t* buffer_; }; std::unique_ptr NewFlatBuffersBench( - int64_t initial_size = 1024, flatbuffers::Allocator *allocator = nullptr); + int64_t initial_size = 1024, flatbuffers::Allocator* allocator = nullptr); #endif // BENCHMARKS_CPP_FLATBUFFERS_FB_BENCH_H_ \ No newline at end of file diff --git a/benchmarks/swift/Benchmarks/FlatbuffersBenchmarks/FlatbuffersBenchmarks.swift b/benchmarks/swift/Benchmarks/FlatbuffersBenchmarks/FlatbuffersBenchmarks.swift index 21eff5fac5f..92eaf4afc96 100644 --- a/benchmarks/swift/Benchmarks/FlatbuffersBenchmarks/FlatbuffersBenchmarks.swift +++ b/benchmarks/swift/Benchmarks/FlatbuffersBenchmarks/FlatbuffersBenchmarks.swift @@ -15,8 +15,8 @@ */ import Benchmark -import CoreFoundation import FlatBuffers +import Foundation @usableFromInline struct AA: NativeStruct { @@ -29,6 +29,15 @@ struct AA: NativeStruct { } let benchmarks = { + let oneGB: Int32 = 1_024_000_000 + let data = { + var array = [8888.88, 8888.88] + var data = Data() + array.withUnsafeBytes { ptr in + data.append(contentsOf: ptr) + } + return data + }() let ints: [Int] = Array(repeating: 42, count: 100) let bytes: [UInt8] = Array(repeating: 42, count: 100) let str10 = (0...9).map { _ -> String in "x" }.joined() @@ -73,12 +82,25 @@ let benchmarks = { Benchmark("Allocating 1GB", configuration: singleConfiguration) { benchmark in for _ in benchmark.scaledIterations { - blackHole(FlatBufferBuilder(initialSize: 1_024_000_000)) + blackHole(FlatBufferBuilder(initialSize: oneGB)) + } + } + + Benchmark( + "Allocating ByteBuffer 1GB", + configuration: singleConfiguration + ) { benchmark in + let memory = UnsafeMutableRawPointer.allocate( + byteCount: 1_024_000_000, + alignment: 1) + benchmark.startMeasurement() + for _ in benchmark.scaledIterations { + blackHole(ByteBuffer(assumingMemoryBound: memory, capacity: Int(oneGB))) } } Benchmark("Clearing 1GB", configuration: singleConfiguration) { benchmark in - var fb = FlatBufferBuilder(initialSize: 1_024_000_000) + var fb = FlatBufferBuilder(initialSize: oneGB) benchmark.startMeasurement() for _ in benchmark.scaledIterations { blackHole(fb.clear()) @@ -86,7 +108,7 @@ let benchmarks = { } Benchmark("Strings 10") { benchmark in - var fb = FlatBufferBuilder(initialSize: 1<<20) + var fb = FlatBufferBuilder(initialSize: 1 << 20) benchmark.startMeasurement() for _ in benchmark.scaledIterations { blackHole(fb.create(string: str10)) @@ -94,7 +116,7 @@ let benchmarks = { } Benchmark("Strings 100") { benchmark in - var fb = FlatBufferBuilder(initialSize: 1<<20) + var fb = FlatBufferBuilder(initialSize: 1 << 20) benchmark.startMeasurement() for _ in benchmark.scaledIterations { blackHole(fb.create(string: str100)) @@ -102,7 +124,7 @@ let benchmarks = { } Benchmark("Vector 1 Bytes") { benchmark in - var fb = FlatBufferBuilder(initialSize: 1<<20) + var fb = FlatBufferBuilder(initialSize: 1 << 20) benchmark.startMeasurement() for _ in benchmark.scaledIterations { blackHole(fb.createVector(bytes: bytes)) @@ -110,7 +132,7 @@ let benchmarks = { } Benchmark("Vector 1 Ints") { benchmark in - var fb = FlatBufferBuilder(initialSize: 1<<20) + var fb = FlatBufferBuilder(initialSize: 1 << 20) benchmark.startMeasurement() for _ in benchmark.scaledIterations { blackHole(fb.createVector(ints)) @@ -118,7 +140,7 @@ let benchmarks = { } Benchmark("Vector 100 Ints") { benchmark in - var fb = FlatBufferBuilder(initialSize: 1<<20) + var fb = FlatBufferBuilder(initialSize: 1 << 20) benchmark.startMeasurement() for i in benchmark.scaledIterations { blackHole(fb.createVector(ints)) @@ -126,7 +148,7 @@ let benchmarks = { } Benchmark("Vector 100 Bytes") { benchmark in - var fb = FlatBufferBuilder(initialSize: 1<<20) + var fb = FlatBufferBuilder(initialSize: 1 << 20) benchmark.startMeasurement() for i in benchmark.scaledIterations { blackHole(fb.createVector(bytes)) @@ -134,7 +156,7 @@ let benchmarks = { } Benchmark("Vector 100 ContiguousBytes") { benchmark in - var fb = FlatBufferBuilder(initialSize: 1<<20) + var fb = FlatBufferBuilder(initialSize: 1 << 20) benchmark.startMeasurement() for i in benchmark.scaledIterations { blackHole(fb.createVector(bytes: bytes)) @@ -143,8 +165,8 @@ let benchmarks = { Benchmark( "FlatBufferBuilder Add", - configuration: kiloConfiguration) - { benchmark in + configuration: kiloConfiguration + ) { benchmark in var fb = FlatBufferBuilder(initialSize: 1024 * 1024 * 32) benchmark.startMeasurement() for _ in benchmark.scaledIterations { @@ -158,6 +180,26 @@ let benchmarks = { } } + Benchmark( + "FlatBufferBuilder Start table", + configuration: kiloConfiguration + ) { benchmark in + var fb = FlatBufferBuilder(initialSize: 1024 * 1024 * 32) + benchmark.startMeasurement() + for _ in benchmark.scaledIterations { + let s = fb.startTable(with: 4) + blackHole(fb.endTable(at: s)) + } + } + + Benchmark("Struct") { benchmark in + var fb = FlatBufferBuilder(initialSize: 1024 * 1024 * 32) + benchmark.startMeasurement() + for _ in benchmark.scaledIterations { + blackHole(fb.create(struct: array.first!)) + } + } + Benchmark("Structs") { benchmark in let rawSize = ((16 * 5) * benchmark.scaledIterations.count) / 1024 var fb = FlatBufferBuilder(initialSize: Int32(rawSize * 1600)) @@ -176,7 +218,7 @@ let benchmarks = { let start = fb.startTable(with: 1) fb.add(offset: vector, at: 4) let root = Offset(offset: fb.endTable(at: start)) - fb.finish(offset: root) + blackHole(fb.finish(offset: root)) } Benchmark("Vector of Offsets") { benchmark in @@ -198,4 +240,11 @@ let benchmarks = { blackHole(fb.endTable(at: s)) } } + + Benchmark("Reading Doubles") { benchmark in + let byteBuffer = ByteBuffer(data: data) + for _ in benchmark.scaledIterations { + blackHole(byteBuffer.read(def: Double.self, position: 0)) + } + } } diff --git a/benchmarks/swift/Package.swift b/benchmarks/swift/Package.swift index 4067daf66ae..da2da4fdbe7 100644 --- a/benchmarks/swift/Package.swift +++ b/benchmarks/swift/Package.swift @@ -20,7 +20,7 @@ import PackageDescription let package = Package( name: "benchmarks", platforms: [ - .macOS(.v13), + .macOS(.v13) ], dependencies: [ .package(path: "../.."), @@ -37,6 +37,6 @@ let package = Package( ], path: "Benchmarks/FlatbuffersBenchmarks", plugins: [ - .plugin(name: "BenchmarkPlugin", package: "package-benchmark"), - ]), + .plugin(name: "BenchmarkPlugin", package: "package-benchmark") + ]) ]) diff --git a/conan/build.py b/conan/build.py index 62a37990794..104f9e0f832 100644 --- a/conan/build.py +++ b/conan/build.py @@ -6,45 +6,54 @@ from cpt.packager import ConanMultiPackager - def get_branch(): - try: - for line in subprocess.check_output("git branch", shell=True).decode().splitlines(): - line = line.strip() - if line.startswith("*") and " (HEAD detached" not in line: - return line.replace("*", "", 1).strip() - return "" - except Exception: - pass + try: + for line in ( + subprocess.check_output("git branch", shell=True).decode().splitlines() + ): + line = line.strip() + if line.startswith("*") and " (HEAD detached" not in line: + return line.replace("*", "", 1).strip() return "" + except Exception: + pass + return "" def get_version(): - version = get_branch() - match = re.search(r"v(\d+\.\d+\.\d+.*)", version) - if match: - return match.group(1) - return version + version = get_branch() + match = re.search(r"v(\d+\.\d+\.\d+.*)", version) + if match: + return match.group(1) + return version def get_reference(username): - return "flatbuffers/{}@google/stable".format(get_version()) + return "flatbuffers/{}@google/stable".format(get_version()) if __name__ == "__main__": - login_username = os.getenv("CONAN_LOGIN_USERNAME", "aardappel") - username = os.getenv("CONAN_USERNAME", "google") - upload = os.getenv("CONAN_UPLOAD", "https://api.bintray.com/conan/aardappel/flatbuffers") - stable_branch_pattern = os.getenv("CONAN_STABLE_BRANCH_PATTERN", r"v\d+\.\d+\.\d+.*") - test_folder = os.getenv("CPT_TEST_FOLDER", os.path.join("conan", "test_package")) - upload_only_when_stable = os.getenv("CONAN_UPLOAD_ONLY_WHEN_STABLE", True) - - builder = ConanMultiPackager(reference=get_reference(username), - username=username, - login_username=login_username, - upload=upload, - stable_branch_pattern=stable_branch_pattern, - upload_only_when_stable=upload_only_when_stable, - test_folder=test_folder) - builder.add_common_builds(pure_c=False) - builder.run() + login_username = os.getenv("CONAN_LOGIN_USERNAME", "aardappel") + username = os.getenv("CONAN_USERNAME", "google") + upload = os.getenv( + "CONAN_UPLOAD", "https://api.bintray.com/conan/aardappel/flatbuffers" + ) + stable_branch_pattern = os.getenv( + "CONAN_STABLE_BRANCH_PATTERN", r"v\d+\.\d+\.\d+.*" + ) + test_folder = os.getenv( + "CPT_TEST_FOLDER", os.path.join("conan", "test_package") + ) + upload_only_when_stable = os.getenv("CONAN_UPLOAD_ONLY_WHEN_STABLE", True) + + builder = ConanMultiPackager( + reference=get_reference(username), + username=username, + login_username=login_username, + upload=upload, + stable_branch_pattern=stable_branch_pattern, + upload_only_when_stable=upload_only_when_stable, + test_folder=test_folder, + ) + builder.add_common_builds(pure_c=False) + builder.run() diff --git a/conan/test_package/conanfile.py b/conan/test_package/conanfile.py index 735e31d27bf..afa78945c11 100644 --- a/conan/test_package/conanfile.py +++ b/conan/test_package/conanfile.py @@ -1,21 +1,21 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- -from conans import ConanFile, CMake import os +from conans import CMake, ConanFile class TestPackageConan(ConanFile): - settings = "os", "compiler", "build_type", "arch" - generators = "cmake" + settings = "os", "compiler", "build_type", "arch" + generators = "cmake" - def build(self): - cmake = CMake(self) - cmake.configure() - cmake.build() + def build(self): + cmake = CMake(self) + cmake.configure() + cmake.build() - def test(self): - bin_path = os.path.join("bin", "test_package") - self.run(bin_path, run_environment=True) - self.run("flatc --version", run_environment=True) - self.run("flathash fnv1_16 conan", run_environment=True) + def test(self): + bin_path = os.path.join("bin", "test_package") + self.run(bin_path, run_environment=True) + self.run("flatc --version", run_environment=True) + self.run("flathash fnv1_16 conan", run_environment=True) diff --git a/conanfile.py b/conanfile.py index 9d622908acd..dc63d14e246 100644 --- a/conanfile.py +++ b/conanfile.py @@ -1,75 +1,83 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- -"""Conan recipe package for Google FlatBuffers -""" +"""Conan recipe package for Google FlatBuffers""" import os import shutil -from conans import ConanFile, CMake, tools +from conans import CMake, ConanFile, tools class FlatbuffersConan(ConanFile): - name = "flatbuffers" - license = "Apache-2.0" - url = "https://github.com/google/flatbuffers" - homepage = "http://google.github.io/flatbuffers/" - author = "Wouter van Oortmerssen" - topics = ("conan", "flatbuffers", "serialization", "rpc", "json-parser") - description = "Memory Efficient Serialization Library" - settings = "os", "compiler", "build_type", "arch" - options = {"shared": [True, False], "fPIC": [True, False]} - default_options = {"shared": False, "fPIC": True} - generators = "cmake" - exports = "LICENSE" - exports_sources = ["CMake/*", "include/*", "src/*", "grpc/*", "CMakeLists.txt", "conan/CMakeLists.txt"] + name = "flatbuffers" + license = "Apache-2.0" + url = "https://github.com/google/flatbuffers" + homepage = "http://google.github.io/flatbuffers/" + author = "Wouter van Oortmerssen" + topics = ("conan", "flatbuffers", "serialization", "rpc", "json-parser") + description = "Memory Efficient Serialization Library" + settings = "os", "compiler", "build_type", "arch" + options = {"shared": [True, False], "fPIC": [True, False]} + default_options = {"shared": False, "fPIC": True} + generators = "cmake" + exports = "LICENSE" + exports_sources = [ + "CMake/*", + "include/*", + "src/*", + "grpc/*", + "CMakeLists.txt", + "conan/CMakeLists.txt", + ] - def source(self): - """Wrap the original CMake file to call conan_basic_setup - """ - shutil.move("CMakeLists.txt", "CMakeListsOriginal.txt") - shutil.move(os.path.join("conan", "CMakeLists.txt"), "CMakeLists.txt") + def source(self): + """Wrap the original CMake file to call conan_basic_setup""" + shutil.move("CMakeLists.txt", "CMakeListsOriginal.txt") + shutil.move(os.path.join("conan", "CMakeLists.txt"), "CMakeLists.txt") - def config_options(self): - """Remove fPIC option on Windows platform - """ - if self.settings.os == "Windows": - self.options.remove("fPIC") + def config_options(self): + """Remove fPIC option on Windows platform""" + if self.settings.os == "Windows": + self.options.remove("fPIC") - def configure_cmake(self): - """Create CMake instance and execute configure step - """ - cmake = CMake(self) - cmake.definitions["FLATBUFFERS_BUILD_TESTS"] = False - cmake.definitions["FLATBUFFERS_BUILD_SHAREDLIB"] = self.options.shared - cmake.definitions["FLATBUFFERS_BUILD_FLATLIB"] = not self.options.shared - cmake.configure() - return cmake + def configure_cmake(self): + """Create CMake instance and execute configure step""" + cmake = CMake(self) + cmake.definitions["FLATBUFFERS_BUILD_TESTS"] = False + cmake.definitions["FLATBUFFERS_BUILD_SHAREDLIB"] = self.options.shared + cmake.definitions["FLATBUFFERS_BUILD_FLATLIB"] = not self.options.shared + cmake.configure() + return cmake - def build(self): - """Configure, build and install FlatBuffers using CMake. - """ - cmake = self.configure_cmake() - cmake.build() + def build(self): + """Configure, build and install FlatBuffers using CMake.""" + cmake = self.configure_cmake() + cmake.build() - def package(self): - """Copy Flatbuffers' artifacts to package folder - """ - cmake = self.configure_cmake() - cmake.install() - self.copy(pattern="LICENSE", dst="licenses") - self.copy(pattern="FindFlatBuffers.cmake", dst=os.path.join("lib", "cmake", "flatbuffers"), src="CMake") - self.copy(pattern="flathash*", dst="bin", src="bin") - self.copy(pattern="flatc*", dst="bin", src="bin") - if self.settings.os == "Windows" and self.options.shared: - if self.settings.compiler == "Visual Studio": - shutil.move(os.path.join(self.package_folder, "lib", "%s.dll" % self.name), - os.path.join(self.package_folder, "bin", "%s.dll" % self.name)) - elif self.settings.compiler == "gcc": - shutil.move(os.path.join(self.package_folder, "lib", "lib%s.dll" % self.name), - os.path.join(self.package_folder, "bin", "lib%s.dll" % self.name)) + def package(self): + """Copy Flatbuffers' artifacts to package folder""" + cmake = self.configure_cmake() + cmake.install() + self.copy(pattern="LICENSE", dst="licenses") + self.copy( + pattern="FindFlatBuffers.cmake", + dst=os.path.join("lib", "cmake", "flatbuffers"), + src="CMake", + ) + self.copy(pattern="flathash*", dst="bin", src="bin") + self.copy(pattern="flatc*", dst="bin", src="bin") + if self.settings.os == "Windows" and self.options.shared: + if self.settings.compiler == "Visual Studio": + shutil.move( + os.path.join(self.package_folder, "lib", "%s.dll" % self.name), + os.path.join(self.package_folder, "bin", "%s.dll" % self.name), + ) + elif self.settings.compiler == "gcc": + shutil.move( + os.path.join(self.package_folder, "lib", "lib%s.dll" % self.name), + os.path.join(self.package_folder, "bin", "lib%s.dll" % self.name), + ) - def package_info(self): - """Collect built libraries names and solve flatc path. - """ - self.cpp_info.libs = tools.collect_libs(self) - self.user_info.flatc = os.path.join(self.package_folder, "bin", "flatc") + def package_info(self): + """Collect built libraries names and solve flatc path.""" + self.cpp_info.libs = tools.collect_libs(self) + self.user_info.flatc = os.path.join(self.package_folder, "bin", "flatc") diff --git a/dart/example/example.dart b/dart/example/example.dart index d397bbb3f44..329981357f3 100644 --- a/dart/example/example.dart +++ b/dart/example/example.dart @@ -15,6 +15,7 @@ */ import 'package:flat_buffers/flat_buffers.dart' as fb; + import './monster_my_game.sample_generated.dart' as my_game; // Example how to use FlatBuffers to create and read binary buffers. @@ -78,7 +79,8 @@ void builderTest() { builder.finish(monsteroff); if (verify(builder.buffer)) { print( - "The FlatBuffer was successfully created with a builder and verified!"); + "The FlatBuffer was successfully created with a builder and verified!", + ); } } @@ -94,7 +96,10 @@ void objectBuilderTest() { name: 'Orc', inventory: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], color: my_game.Color.Red, - weapons: [my_game.WeaponObjectBuilder(name: 'Sword', damage: 3), axe], + weapons: [ + my_game.WeaponObjectBuilder(name: 'Sword', damage: 3), + axe, + ], equippedType: my_game.EquipmentTypeId.Weapon, equipped: axe, ); @@ -108,7 +113,8 @@ void objectBuilderTest() { // Instead, we're going to access it right away (as if we just received it). if (verify(buffer)) { print( - "The FlatBuffer was successfully created with an object builder and verified!"); + "The FlatBuffer was successfully created with an object builder and verified!", + ); } } diff --git a/dart/example/monster_my_game.sample_generated.dart b/dart/example/monster_my_game.sample_generated.dart index ba0a81f0d57..612de336b03 100644 --- a/dart/example/monster_my_game.sample_generated.dart +++ b/dart/example/monster_my_game.sample_generated.dart @@ -4,8 +4,8 @@ library my_game.sample; import 'dart:typed_data' show Uint8List; -import 'package:flat_buffers/flat_buffers.dart' as fb; +import 'package:flat_buffers/flat_buffers.dart' as fb; class Color { final int value; @@ -19,7 +19,7 @@ class Color { return result; } - static Color? _createOrNull(int? value) => + static Color? _createOrNull(int? value) => value == null ? null : Color.fromValue(value); static const int minValue = 0; @@ -29,10 +29,7 @@ class Color { static const Color Red = Color._(0); static const Color Green = Color._(1); static const Color Blue = Color._(2); - static const Map values = { - 0: Red, - 1: Green, - 2: Blue}; + static const Map values = {0: Red, 1: Green, 2: Blue}; static const fb.Reader reader = _ColorReader(); @@ -60,12 +57,14 @@ class EquipmentTypeId { factory EquipmentTypeId.fromValue(int value) { final result = values[value]; if (result == null) { - throw StateError('Invalid value $value for bit flag enum EquipmentTypeId'); + throw StateError( + 'Invalid value $value for bit flag enum EquipmentTypeId', + ); } return result; } - static EquipmentTypeId? _createOrNull(int? value) => + static EquipmentTypeId? _createOrNull(int? value) => value == null ? null : EquipmentTypeId.fromValue(value); static const int minValue = 0; @@ -74,9 +73,7 @@ class EquipmentTypeId { static const EquipmentTypeId NONE = EquipmentTypeId._(0); static const EquipmentTypeId Weapon = EquipmentTypeId._(1); - static const Map values = { - 0: NONE, - 1: Weapon}; + static const Map values = {0: NONE, 1: Weapon}; static const fb.Reader reader = _EquipmentTypeIdReader(); @@ -122,8 +119,7 @@ class _Vec3Reader extends fb.StructReader { int get size => 12; @override - Vec3 createObject(fb.BufferContext bc, int offset) => - Vec3._(bc, offset); + Vec3 createObject(fb.BufferContext bc, int offset) => Vec3._(bc, offset); } class Vec3Builder { @@ -137,7 +133,6 @@ class Vec3Builder { fbBuilder.putFloat32(x); return fbBuilder.offset; } - } class Vec3ObjectBuilder extends fb.ObjectBuilder { @@ -145,14 +140,10 @@ class Vec3ObjectBuilder extends fb.ObjectBuilder { final double _y; final double _z; - Vec3ObjectBuilder({ - required double x, - required double y, - required double z, - }) - : _x = x, - _y = y, - _z = z; + Vec3ObjectBuilder({required double x, required double y, required double z}) + : _x = x, + _y = y, + _z = z; /// Finish building, and store into the [fbBuilder]. @override @@ -171,6 +162,7 @@ class Vec3ObjectBuilder extends fb.ObjectBuilder { return fbBuilder.buffer; } } + class Monster { Monster._(this._bc, this._bcOffset); factory Monster(List bytes) { @@ -186,18 +178,30 @@ class Monster { Vec3? get pos => Vec3.reader.vTableGetNullable(_bc, _bcOffset, 4); int get mana => const fb.Int16Reader().vTableGet(_bc, _bcOffset, 6, 150); int get hp => const fb.Int16Reader().vTableGet(_bc, _bcOffset, 8, 100); - String? get name => const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 10); - List? get inventory => const fb.Uint8ListReader().vTableGetNullable(_bc, _bcOffset, 14); - Color get color => Color.fromValue(const fb.Int8Reader().vTableGet(_bc, _bcOffset, 16, 2)); - List? get weapons => const fb.ListReader(Weapon.reader).vTableGetNullable(_bc, _bcOffset, 18); - EquipmentTypeId? get equippedType => EquipmentTypeId._createOrNull(const fb.Uint8Reader().vTableGetNullable(_bc, _bcOffset, 20)); + String? get name => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 10); + List? get inventory => + const fb.Uint8ListReader().vTableGetNullable(_bc, _bcOffset, 14); + Color get color => + Color.fromValue(const fb.Int8Reader().vTableGet(_bc, _bcOffset, 16, 2)); + List? get weapons => const fb.ListReader( + Weapon.reader, + ).vTableGetNullable(_bc, _bcOffset, 18); + EquipmentTypeId? get equippedType => EquipmentTypeId._createOrNull( + const fb.Uint8Reader().vTableGetNullable(_bc, _bcOffset, 20), + ); dynamic get equipped { switch (equippedType?.value) { - case 1: return Weapon.reader.vTableGetNullable(_bc, _bcOffset, 22); - default: return null; + case 1: + return Weapon.reader.vTableGetNullable(_bc, _bcOffset, 22); + default: + return null; } } - List? get path => const fb.ListReader(Vec3.reader).vTableGetNullable(_bc, _bcOffset, 24); + + List? get path => const fb.ListReader( + Vec3.reader, + ).vTableGetNullable(_bc, _bcOffset, 24); @override String toString() { @@ -209,8 +213,8 @@ class _MonsterReader extends fb.TableReader { const _MonsterReader(); @override - Monster createObject(fb.BufferContext bc, int offset) => - Monster._(bc, offset); + Monster createObject(fb.BufferContext bc, int offset) => + Monster._(bc, offset); } class MonsterBuilder { @@ -226,38 +230,47 @@ class MonsterBuilder { fbBuilder.addStruct(0, offset); return fbBuilder.offset; } + int addMana(int? mana) { fbBuilder.addInt16(1, mana); return fbBuilder.offset; } + int addHp(int? hp) { fbBuilder.addInt16(2, hp); return fbBuilder.offset; } + int addNameOffset(int? offset) { fbBuilder.addOffset(3, offset); return fbBuilder.offset; } + int addInventoryOffset(int? offset) { fbBuilder.addOffset(5, offset); return fbBuilder.offset; } + int addColor(Color? color) { fbBuilder.addInt8(6, color?.value); return fbBuilder.offset; } + int addWeaponsOffset(int? offset) { fbBuilder.addOffset(7, offset); return fbBuilder.offset; } + int addEquippedType(EquipmentTypeId? equippedType) { fbBuilder.addUint8(8, equippedType?.value); return fbBuilder.offset; } + int addEquippedOffset(int? offset) { fbBuilder.addOffset(9, offset); return fbBuilder.offset; } + int addPathOffset(int? offset) { fbBuilder.addOffset(10, offset); return fbBuilder.offset; @@ -291,29 +304,34 @@ class MonsterObjectBuilder extends fb.ObjectBuilder { EquipmentTypeId? equippedType, dynamic equipped, List? path, - }) - : _pos = pos, - _mana = mana, - _hp = hp, - _name = name, - _inventory = inventory, - _color = color, - _weapons = weapons, - _equippedType = equippedType, - _equipped = equipped, - _path = path; + }) : _pos = pos, + _mana = mana, + _hp = hp, + _name = name, + _inventory = inventory, + _color = color, + _weapons = weapons, + _equippedType = equippedType, + _equipped = equipped, + _path = path; /// Finish building, and store into the [fbBuilder]. @override int finish(fb.Builder fbBuilder) { - final int? nameOffset = _name == null ? null + final int? nameOffset = _name == null + ? null : fbBuilder.writeString(_name!); - final int? inventoryOffset = _inventory == null ? null + final int? inventoryOffset = _inventory == null + ? null : fbBuilder.writeListUint8(_inventory!); - final int? weaponsOffset = _weapons == null ? null - : fbBuilder.writeList(_weapons!.map((b) => b.getOrCreateOffset(fbBuilder)).toList()); + final int? weaponsOffset = _weapons == null + ? null + : fbBuilder.writeList( + _weapons!.map((b) => b.getOrCreateOffset(fbBuilder)).toList(), + ); final int? equippedOffset = _equipped?.getOrCreateOffset(fbBuilder); - final int? pathOffset = _path == null ? null + final int? pathOffset = _path == null + ? null : fbBuilder.writeListOfStructs(_path!); fbBuilder.startTable(10); if (_pos != null) { @@ -339,6 +357,7 @@ class MonsterObjectBuilder extends fb.ObjectBuilder { return fbBuilder.buffer; } } + class Weapon { Weapon._(this._bc, this._bcOffset); factory Weapon(List bytes) { @@ -351,7 +370,8 @@ class Weapon { final fb.BufferContext _bc; final int _bcOffset; - String? get name => const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 4); + String? get name => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 4); int get damage => const fb.Int16Reader().vTableGet(_bc, _bcOffset, 6, 0); @override @@ -364,8 +384,7 @@ class _WeaponReader extends fb.TableReader { const _WeaponReader(); @override - Weapon createObject(fb.BufferContext bc, int offset) => - Weapon._(bc, offset); + Weapon createObject(fb.BufferContext bc, int offset) => Weapon._(bc, offset); } class WeaponBuilder { @@ -381,6 +400,7 @@ class WeaponBuilder { fbBuilder.addOffset(0, offset); return fbBuilder.offset; } + int addDamage(int? damage) { fbBuilder.addInt16(1, damage); return fbBuilder.offset; @@ -395,17 +415,15 @@ class WeaponObjectBuilder extends fb.ObjectBuilder { final String? _name; final int? _damage; - WeaponObjectBuilder({ - String? name, - int? damage, - }) - : _name = name, - _damage = damage; + WeaponObjectBuilder({String? name, int? damage}) + : _name = name, + _damage = damage; /// Finish building, and store into the [fbBuilder]. @override int finish(fb.Builder fbBuilder) { - final int? nameOffset = _name == null ? null + final int? nameOffset = _name == null + ? null : fbBuilder.writeString(_name!); fbBuilder.startTable(2); fbBuilder.addOffset(0, nameOffset); diff --git a/dart/lib/flat_buffers.dart b/dart/lib/flat_buffers.dart index 2395992ae28..7590bdba690 100644 --- a/dart/lib/flat_buffers.dart +++ b/dart/lib/flat_buffers.dart @@ -27,10 +27,11 @@ class BufferContext { ByteData get buffer => _buffer; /// Create from a FlatBuffer represented by a list of bytes (uint8). - factory BufferContext.fromBytes(List byteList) => - BufferContext(byteList is Uint8List - ? byteList.buffer.asByteData(byteList.offsetInBytes) - : ByteData.view(Uint8List.fromList(byteList).buffer)); + factory BufferContext.fromBytes(List byteList) => BufferContext( + byteList is Uint8List + ? byteList.buffer.asByteData(byteList.offsetInBytes) + : ByteData.view(Uint8List.fromList(byteList).buffer), + ); /// Create from a FlatBuffer represented by ByteData. BufferContext(this._buffer); @@ -149,9 +150,9 @@ class Builder { bool internStrings = false, Allocator allocator = const DefaultAllocator(), this.deduplicateTables = true, - }) : _allocator = allocator, - _buf = allocator.allocate(initialSize), - _vTables = deduplicateTables ? [] : const [] { + }) : _allocator = allocator, + _buf = allocator.allocate(initialSize), + _vTables = deduplicateTables ? [] : const [] { if (internStrings) { _strings = {}; } @@ -350,8 +351,10 @@ class Builder { Uint8List get buffer { assert(_finished); final finishedSize = size(); - return _buf.buffer - .asUint8List(_buf.lengthInBytes - finishedSize, finishedSize); + return _buf.buffer.asUint8List( + _buf.lengthInBytes - finishedSize, + finishedSize, + ); } /// Finish off the creation of the buffer. The given [offset] is used as the @@ -368,14 +371,18 @@ class Builder { if (fileIdentifier != null) { for (var i = 0; i < 4; i++) { _setUint8AtTail( - finishedSize - _sizeofUint32 - i, fileIdentifier.codeUnitAt(i)); + finishedSize - _sizeofUint32 - i, + fileIdentifier.codeUnitAt(i), + ); } } // zero out the added padding - for (var i = sizeBeforePadding + 1; - i <= finishedSize - requiredBytes; - i++) { + for ( + var i = sizeBeforePadding + 1; + i <= finishedSize - requiredBytes; + i++ + ) { _setUint8AtTail(i, 0); } _finished = true; @@ -687,8 +694,10 @@ class Builder { int writeString(String value, {bool asciiOptimization = false}) { assert(!_inVTable); if (_strings != null) { - return _strings! - .putIfAbsent(value, () => _writeString(value, asciiOptimization)); + return _strings!.putIfAbsent( + value, + () => _writeString(value, asciiOptimization), + ); } else { return _writeString(value, asciiOptimization); } @@ -1005,8 +1014,11 @@ class ListReader extends Reader> { : List.generate( bc.buffer.getUint32(listOffset, Endian.little), (int index) => _elementReader.read( - bc, listOffset + size + _elementReader.size * index), - growable: true); + bc, + listOffset + size + _elementReader.size * index, + ), + growable: true, + ); } } @@ -1284,7 +1296,7 @@ class _FbGenericList extends _FbList { List? _items; _FbGenericList(this.elementReader, BufferContext bp, int offset) - : super(bp, offset); + : super(bp, offset); @override @pragma('vm:prefer-inline') @@ -1454,7 +1466,11 @@ abstract class Allocator { /// Params [inUseBack] and [inUseFront] indicate how much of [oldData] is /// actually in use at each end, and needs to be copied. ByteData resize( - ByteData oldData, int newSize, int inUseBack, int inUseFront) { + ByteData oldData, + int newSize, + int inUseBack, + int inUseFront, + ) { final newData = allocate(newSize); _copyDownward(oldData, newData, inUseBack, inUseFront); deallocate(oldData); @@ -1465,17 +1481,25 @@ abstract class Allocator { /// memory of size [inUseFront] and [inUseBack] will be copied from the front /// and back of the old memory allocation. void _copyDownward( - ByteData oldData, ByteData newData, int inUseBack, int inUseFront) { + ByteData oldData, + ByteData newData, + int inUseBack, + int inUseFront, + ) { if (inUseBack != 0) { newData.buffer.asUint8List().setAll( - newData.lengthInBytes - inUseBack, - oldData.buffer.asUint8List().getRange( - oldData.lengthInBytes - inUseBack, oldData.lengthInBytes)); + newData.lengthInBytes - inUseBack, + oldData.buffer.asUint8List().getRange( + oldData.lengthInBytes - inUseBack, + oldData.lengthInBytes, + ), + ); } if (inUseFront != 0) { - newData.buffer - .asUint8List() - .setAll(0, oldData.buffer.asUint8List().getRange(0, inUseFront)); + newData.buffer.asUint8List().setAll( + 0, + oldData.buffer.asUint8List().getRange(0, inUseFront), + ); } } } diff --git a/dart/lib/src/builder.dart b/dart/lib/src/builder.dart index 82681e7ec69..cdd0aec5323 100644 --- a/dart/lib/src/builder.dart +++ b/dart/lib/src/builder.dart @@ -107,8 +107,11 @@ class Builder { final newOffset = _newOffset(length + 1); _pushBuffer(utf8String); _offset = newOffset; - final stackValue = - _StackValue.withOffset(stringOffset, ValueType.String, bitWidth); + final stackValue = _StackValue.withOffset( + stringOffset, + ValueType.String, + bitWidth, + ); _stack.add(stackValue); _stringCache[value] = stackValue; } @@ -128,8 +131,11 @@ class Builder { final newOffset = _newOffset(length + 1); _pushBuffer(utf8String); _offset = newOffset; - final stackValue = - _StackValue.withOffset(keyOffset, ValueType.Key, BitWidth.width8); + final stackValue = _StackValue.withOffset( + keyOffset, + ValueType.Key, + BitWidth.width8, + ); _stack.add(stackValue); _keyCache[value] = stackValue; } @@ -147,8 +153,11 @@ class Builder { final newOffset = _newOffset(length); _pushBuffer(value.asUint8List()); _offset = newOffset; - final stackValue = - _StackValue.withOffset(blobOffset, ValueType.Blob, bitWidth); + final stackValue = _StackValue.withOffset( + blobOffset, + ValueType.Blob, + bitWidth, + ); _stack.add(stackValue); } @@ -170,7 +179,10 @@ class Builder { final valueOffset = _offset; _pushBuffer(stackValue.asU8List(stackValue.width)); final stackOffset = _StackValue.withOffset( - valueOffset, ValueType.IndirectInt, stackValue.width); + valueOffset, + ValueType.IndirectInt, + stackValue.width, + ); _stack.add(stackOffset); _offset = newOffset; if (cache) { @@ -195,7 +207,10 @@ class Builder { final valueOffset = _offset; _pushBuffer(stackValue.asU8List(stackValue.width)); final stackOffset = _StackValue.withOffset( - valueOffset, ValueType.IndirectFloat, stackValue.width); + valueOffset, + ValueType.IndirectFloat, + stackValue.width, + ); _stack.add(stackOffset); _offset = newOffset; if (cache) { @@ -252,9 +267,10 @@ class Builder { tmp._offset = _offset; tmp._stack = List.from(_stack); tmp._stackPointers = List.from(_stackPointers); - tmp._buffer.buffer - .asUint8List() - .setAll(0, _buffer.buffer.asUint8List(0, _offset)); + tmp._buffer.buffer.asUint8List().setAll( + 0, + _buffer.buffer.asUint8List(0, _offset), + ); for (var i = 0; i < tmp._stackPointers.length; i++) { tmp.end(); } @@ -271,7 +287,8 @@ class Builder { if (_stackPointers.isNotEmpty && _stackPointers.last.isVector == false) { if (_stack.last.type != ValueType.Key) { throw StateError( - 'Adding value to a map before adding a key is prohibited'); + 'Adding value to a map before adding a key is prohibited', + ); } } } @@ -288,7 +305,8 @@ class Builder { void _finish() { if (_stack.length != 1) { throw StateError( - 'Stack has to be exactly 1, but is ${_stack.length}. You have to end all started vectors and maps, before calling [finish]'); + 'Stack has to be exactly 1, but is ${_stack.length}. You have to end all started vectors and maps, before calling [finish]', + ); } final value = _stack[0]; final byteWidth = _align(value.elementWidth(_offset, 0)); @@ -298,8 +316,12 @@ class Builder { _finished = true; } - _StackValue _createVector(int start, int vecLength, int step, - [_StackValue? keys]) { + _StackValue _createVector( + int start, + int vecLength, + int step, [ + _StackValue? keys, + ]) { var bitWidth = BitWidthUtil.uwidth(vecLength); var prefixElements = 1; if (keys != null) { @@ -326,7 +348,8 @@ class Builder { } } final byteWidth = _align(bitWidth); - final fix = typed & ValueTypeUtils.isNumber(vectorType) && + final fix = + typed & ValueTypeUtils.isNumber(vectorType) && vecLength >= 2 && vecLength <= 4; if (keys != null) { @@ -349,8 +372,10 @@ class Builder { return _StackValue.withOffset(vecOffset, ValueType.Map, bitWidth); } if (typed) { - final vType = - ValueTypeUtils.toTypedVector(vectorType, fix ? vecLength : 0); + final vType = ValueTypeUtils.toTypedVector( + vectorType, + fix ? vecLength : 0, + ); return _StackValue.withOffset(vecOffset, vType, bitWidth); } return _StackValue.withOffset(vecOffset, ValueType.Vector, bitWidth); @@ -366,7 +391,8 @@ class Builder { void _sortKeysAndEndMap(_StackPointer pointer) { if (((_stack.length - pointer.stackPosition) & 1) == 1) { throw StateError( - 'The stack needs to hold key value pairs (even number of elements). Check if you combined [addKey] with add... method calls properly.'); + 'The stack needs to hold key value pairs (even number of elements). Check if you combined [addKey] with add... method calls properly.', + ); } var sorted = true; @@ -412,8 +438,12 @@ class Builder { keysStackValue = _createVector(pointer.stackPosition, vecLength, 2); _keyVectorCache[keysHash] = keysStackValue; } - final vec = - _createVector(pointer.stackPosition + 1, vecLength, 2, keysStackValue); + final vec = _createVector( + pointer.stackPosition + 1, + vecLength, + 2, + keysStackValue, + ); _stack.removeRange(pointer.stackPosition, _stack.length); _stack.add(vec); } @@ -421,7 +451,8 @@ class Builder { bool _shouldFlip(_StackValue v1, _StackValue v2) { if (v1.type != ValueType.Key || v2.type != ValueType.Key) { throw StateError( - 'Stack values are not keys $v1 | $v2. Check if you combined [addKey] with add... method calls properly.'); + 'Stack values are not keys $v1 | $v2. Check if you combined [addKey] with add... method calls properly.', + ); } late int c1, c2; @@ -450,7 +481,8 @@ class Builder { _writeUInt(relativeOffset, byteWidth); } else { throw StateError( - 'Unexpected size $byteWidth. This might be a bug. Please create an issue https://github.com/google/flatbuffers/issues/new'); + 'Unexpected size $byteWidth. This might be a bug. Please create an issue https://github.com/google/flatbuffers/issues/new', + ); } } else { _pushBuffer(value.asU8List(BitWidthUtil.fromByteWidth(byteWidth))); @@ -523,29 +555,27 @@ class _StackValue { final ValueType _type; final BitWidth _width; - _StackValue.withNull() - : _type = ValueType.Null, - _width = BitWidth.width8; + _StackValue.withNull() : _type = ValueType.Null, _width = BitWidth.width8; _StackValue.withInt(int value) - : _type = ValueType.Int, - _width = BitWidthUtil.width(value), - _value = value; + : _type = ValueType.Int, + _width = BitWidthUtil.width(value), + _value = value; _StackValue.withBool(bool value) - : _type = ValueType.Bool, - _width = BitWidth.width8, - _value = value; + : _type = ValueType.Bool, + _width = BitWidth.width8, + _value = value; _StackValue.withDouble(double value) - : _type = ValueType.Float, - _width = BitWidthUtil.width(value), - _value = value; + : _type = ValueType.Float, + _width = BitWidthUtil.width(value), + _value = value; _StackValue.withOffset(int value, ValueType type, BitWidth width) - : _offset = value, - _type = type, - _width = width; + : _offset = value, + _type = type, + _width = width; BitWidth storedWidth({BitWidth width = BitWidth.width8}) { return ValueTypeUtils.isInline(_type) @@ -562,16 +592,16 @@ class _StackValue { final offset = _offset!; for (var i = 0; i < 4; i++) { final width = 1 << i; - final bitWidth = BitWidthUtil.uwidth(size + - BitWidthUtil.paddingSize(size, width) + - index * width - - offset); + final bitWidth = BitWidthUtil.uwidth( + size + BitWidthUtil.paddingSize(size, width) + index * width - offset, + ); if (1 << bitWidth.index == width) { return bitWidth; } } throw StateError( - 'Element is of unknown. Size: $size at index: $index. This might be a bug. Please create an issue https://github.com/google/flatbuffers/issues/new'); + 'Element is of unknown. Size: $size at index: $index. This might be a bug. Please create an issue https://github.com/google/flatbuffers/issues/new', + ); } List asU8List(BitWidth width) { @@ -619,7 +649,8 @@ class _StackValue { } throw StateError( - 'Unexpected type: $_type. This might be a bug. Please create an issue https://github.com/google/flatbuffers/issues/new'); + 'Unexpected type: $_type. This might be a bug. Please create an issue https://github.com/google/flatbuffers/issues/new', + ); } ValueType get type { diff --git a/dart/lib/src/reference.dart b/dart/lib/src/reference.dart index 66195c1bd4a..2abba107b31 100644 --- a/dart/lib/src/reference.dart +++ b/dart/lib/src/reference.dart @@ -1,6 +1,7 @@ import 'dart:collection'; import 'dart:convert'; import 'dart:typed_data'; + import 'types.dart'; /// Main class to read a value out of a FlexBuffer. @@ -16,10 +17,15 @@ class Reference { int? _length; Reference._( - this._buffer, this._offset, this._parentWidth, int packedType, this._path, - [int? byteWidth, ValueType? valueType]) - : _byteWidth = byteWidth ?? 1 << (packedType & 3), - _valueType = valueType ?? ValueTypeUtils.fromInt(packedType >> 2); + this._buffer, + this._offset, + this._parentWidth, + int packedType, + this._path, [ + int? byteWidth, + ValueType? valueType, + ]) : _byteWidth = byteWidth ?? 1 << (packedType & 3), + _valueType = valueType ?? ValueTypeUtils.fromInt(packedType >> 2); /// Use this method to access the root value of a FlexBuffer. static Reference fromBuffer(ByteBuffer buffer) { @@ -31,8 +37,13 @@ class Reference { final byteWidth = byteData.getUint8(len - 1); final packedType = byteData.getUint8(len - 2); final offset = len - byteWidth - 2; - return Reference._(ByteData.view(buffer), offset, - BitWidthUtil.fromByteWidth(byteWidth), packedType, "/"); + return Reference._( + ByteData.view(buffer), + offset, + BitWidthUtil.fromByteWidth(byteWidth), + packedType, + "/", + ); } /// Returns true if the underlying value is null. @@ -138,7 +149,8 @@ class Reference { final index = key; if (index >= length || index < 0) { throw ArgumentError( - 'Key: [$key] is not applicable on: $_path of: $_valueType length: $length'); + 'Key: [$key] is not applicable on: $_path of: $_valueType length: $length', + ); } final elementOffset = _indirect + index * _byteWidth; int packedType = 0; @@ -154,13 +166,14 @@ class Reference { packedType = _buffer.getUint8(_indirect + length * _byteWidth + index); } return Reference._( - _buffer, - elementOffset, - BitWidthUtil.fromByteWidth(_byteWidth), - packedType, - "$_path[$index]", - byteWidth, - valueType); + _buffer, + elementOffset, + BitWidthUtil.fromByteWidth(_byteWidth), + packedType, + "$_path[$index]", + byteWidth, + valueType, + ); } if (key is String && _valueType == ValueType.Map) { final index = _keyIndex(key); @@ -169,7 +182,8 @@ class Reference { } } throw ArgumentError( - 'Key: [$key] is not applicable on: $_path of: $_valueType'); + 'Key: [$key] is not applicable on: $_path of: $_valueType', + ); } /// Get an iterable if the underlying flexBuffer value is a vector. @@ -213,18 +227,24 @@ class Reference { ValueTypeUtils.isAVector(_valueType) || _valueType == ValueType.Map) { _length = _readUInt( - _indirect - _byteWidth, BitWidthUtil.fromByteWidth(_byteWidth)); + _indirect - _byteWidth, + BitWidthUtil.fromByteWidth(_byteWidth), + ); } else if (_valueType == ValueType.Null) { _length = 0; } else if (_valueType == ValueType.String) { final indirect = _indirect; var sizeByteWidth = _byteWidth; - var size = _readUInt(indirect - sizeByteWidth, - BitWidthUtil.fromByteWidth(sizeByteWidth)); + var size = _readUInt( + indirect - sizeByteWidth, + BitWidthUtil.fromByteWidth(sizeByteWidth), + ); while (_buffer.getInt8(indirect + size) != 0) { sizeByteWidth <<= 1; - size = _readUInt(indirect - sizeByteWidth, - BitWidthUtil.fromByteWidth(sizeByteWidth)); + size = _readUInt( + indirect - sizeByteWidth, + BitWidthUtil.fromByteWidth(sizeByteWidth), + ); } _length = size; } else if (_valueType == ValueType.Key) { @@ -289,7 +309,8 @@ class Reference { return result.toString(); } throw UnsupportedError( - 'Type: $_valueType is not supported for JSON conversion'); + 'Type: $_valueType is not supported for JSON conversion', + ); } /// Computes the indirect offset of the value. @@ -354,10 +375,13 @@ class Reference { int? _keyIndex(String key) { final input = utf8.encode(key); final keysVectorOffset = _indirect - _byteWidth * 3; - final indirectOffset = keysVectorOffset - + final indirectOffset = + keysVectorOffset - _readUInt(keysVectorOffset, BitWidthUtil.fromByteWidth(_byteWidth)); final byteWidth = _readUInt( - keysVectorOffset + _byteWidth, BitWidthUtil.fromByteWidth(_byteWidth)); + keysVectorOffset + _byteWidth, + BitWidthUtil.fromByteWidth(_byteWidth), + ); var low = 0; var high = length - 1; while (low <= high) { @@ -390,24 +414,37 @@ class Reference { final indirect = _indirect; final elementOffset = indirect + index * _byteWidth; final packedType = _buffer.getUint8(indirect + length * _byteWidth + index); - return Reference._(_buffer, elementOffset, - BitWidthUtil.fromByteWidth(_byteWidth), packedType, "$_path/$key"); + return Reference._( + _buffer, + elementOffset, + BitWidthUtil.fromByteWidth(_byteWidth), + packedType, + "$_path/$key", + ); } Reference _valueForIndex(int index) { final indirect = _indirect; final elementOffset = indirect + index * _byteWidth; final packedType = _buffer.getUint8(indirect + length * _byteWidth + index); - return Reference._(_buffer, elementOffset, - BitWidthUtil.fromByteWidth(_byteWidth), packedType, "$_path/[$index]"); + return Reference._( + _buffer, + elementOffset, + BitWidthUtil.fromByteWidth(_byteWidth), + packedType, + "$_path/[$index]", + ); } String _keyForIndex(int index) { final keysVectorOffset = _indirect - _byteWidth * 3; - final indirectOffset = keysVectorOffset - + final indirectOffset = + keysVectorOffset - _readUInt(keysVectorOffset, BitWidthUtil.fromByteWidth(_byteWidth)); final byteWidth = _readUInt( - keysVectorOffset + _byteWidth, BitWidthUtil.fromByteWidth(_byteWidth)); + keysVectorOffset + _byteWidth, + BitWidthUtil.fromByteWidth(_byteWidth), + ); final keyOffset = indirectOffset + index * byteWidth; final keyIndirectOffset = keyOffset - _readUInt(keyOffset, BitWidthUtil.fromByteWidth(byteWidth)); diff --git a/dart/lib/src/types.dart b/dart/lib/src/types.dart index b4d006072df..653eabddae2 100644 --- a/dart/lib/src/types.dart +++ b/dart/lib/src/types.dart @@ -86,7 +86,8 @@ enum ValueType { VectorFloat, VectorKey, @Deprecated( - 'VectorString is deprecated due to a flaw in the binary format (https://github.com/google/flatbuffers/issues/5627)') + 'VectorString is deprecated due to a flaw in the binary format (https://github.com/google/flatbuffers/issues/5627)', + ) VectorString, VectorInt2, VectorUInt2, @@ -99,7 +100,7 @@ enum ValueType { VectorFloat4, Blob, Bool, - VectorBool + VectorBool, } class ValueTypeUtils { @@ -153,31 +154,37 @@ class ValueTypeUtils { static ValueType toTypedVector(ValueType self, int length) { if (length == 0) { return ValueTypeUtils.fromInt( - toInt(self) - toInt(ValueType.Int) + toInt(ValueType.VectorInt)); + toInt(self) - toInt(ValueType.Int) + toInt(ValueType.VectorInt), + ); } if (length == 2) { return ValueTypeUtils.fromInt( - toInt(self) - toInt(ValueType.Int) + toInt(ValueType.VectorInt2)); + toInt(self) - toInt(ValueType.Int) + toInt(ValueType.VectorInt2), + ); } if (length == 3) { return ValueTypeUtils.fromInt( - toInt(self) - toInt(ValueType.Int) + toInt(ValueType.VectorInt3)); + toInt(self) - toInt(ValueType.Int) + toInt(ValueType.VectorInt3), + ); } if (length == 4) { return ValueTypeUtils.fromInt( - toInt(self) - toInt(ValueType.Int) + toInt(ValueType.VectorInt4)); + toInt(self) - toInt(ValueType.Int) + toInt(ValueType.VectorInt4), + ); } throw Exception('unexpected length ' + length.toString()); } static ValueType typedVectorElementType(ValueType self) { return ValueTypeUtils.fromInt( - toInt(self) - toInt(ValueType.VectorInt) + toInt(ValueType.Int)); + toInt(self) - toInt(ValueType.VectorInt) + toInt(ValueType.Int), + ); } static ValueType fixedTypedVectorElementType(ValueType self) { return ValueTypeUtils.fromInt( - (toInt(self) - toInt(ValueType.VectorInt2)) % 3 + toInt(ValueType.Int)); + (toInt(self) - toInt(ValueType.VectorInt2)) % 3 + toInt(ValueType.Int), + ); } static int fixedTypedVectorElementSize(ValueType self) { diff --git a/dart/pubspec.yaml b/dart/pubspec.yaml index 25e8d678d8e..3f3545a9272 100644 --- a/dart/pubspec.yaml +++ b/dart/pubspec.yaml @@ -1,5 +1,5 @@ name: flat_buffers -version: 25.2.10 +version: 25.9.23 description: FlatBuffers reading and writing library for Dart. Based on original work by Konstantin Scheglov and Paul Berry of the Dart SDK team. homepage: https://github.com/google/flatbuffers documentation: https://google.github.io/flatbuffers/index.html diff --git a/dart/test/bool_structs_generated.dart b/dart/test/bool_structs_generated.dart index b123ba12f26..ec4732776f9 100644 --- a/dart/test/bool_structs_generated.dart +++ b/dart/test/bool_structs_generated.dart @@ -2,8 +2,8 @@ // ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable, constant_identifier_names import 'dart:typed_data' show Uint8List; -import 'package:flat_buffers/flat_buffers.dart' as fb; +import 'package:flat_buffers/flat_buffers.dart' as fb; class Foo { Foo._(this._bc, this._bcOffset); @@ -17,15 +17,15 @@ class Foo { final fb.BufferContext _bc; final int _bcOffset; - FooProperties? get myFoo => FooProperties.reader.vTableGetNullable(_bc, _bcOffset, 4); + FooProperties? get myFoo => + FooProperties.reader.vTableGetNullable(_bc, _bcOffset, 4); @override String toString() { return 'Foo{myFoo: ${myFoo}}'; } - FooT unpack() => FooT( - myFoo: myFoo?.unpack()); + FooT unpack() => FooT(myFoo: myFoo?.unpack()); static int pack(fb.Builder fbBuilder, FooT? object) { if (object == null) return 0; @@ -36,8 +36,7 @@ class Foo { class FooT implements fb.Packable { FooPropertiesT? myFoo; - FooT({ - this.myFoo}); + FooT({this.myFoo}); @override int pack(fb.Builder fbBuilder) { @@ -58,8 +57,7 @@ class _FooReader extends fb.TableReader { const _FooReader(); @override - Foo createObject(fb.BufferContext bc, int offset) => - Foo._(bc, offset); + Foo createObject(fb.BufferContext bc, int offset) => Foo._(bc, offset); } class FooBuilder { @@ -84,10 +82,7 @@ class FooBuilder { class FooObjectBuilder extends fb.ObjectBuilder { final FooPropertiesObjectBuilder? _myFoo; - FooObjectBuilder({ - FooPropertiesObjectBuilder? myFoo, - }) - : _myFoo = myFoo; + FooObjectBuilder({FooPropertiesObjectBuilder? myFoo}) : _myFoo = myFoo; /// Finish building, and store into the [fbBuilder]. @override @@ -107,6 +102,7 @@ class FooObjectBuilder extends fb.ObjectBuilder { return fbBuilder.buffer; } } + class FooProperties { FooProperties._(this._bc, this._bcOffset); @@ -123,9 +119,7 @@ class FooProperties { return 'FooProperties{a: ${a}, b: ${b}}'; } - FooPropertiesT unpack() => FooPropertiesT( - a: a, - b: b); + FooPropertiesT unpack() => FooPropertiesT(a: a, b: b); static int pack(fb.Builder fbBuilder, FooPropertiesT? object) { if (object == null) return 0; @@ -137,9 +131,7 @@ class FooPropertiesT implements fb.Packable { bool a; bool b; - FooPropertiesT({ - required this.a, - required this.b}); + FooPropertiesT({required this.a, required this.b}); @override int pack(fb.Builder fbBuilder) { @@ -161,8 +153,8 @@ class _FooPropertiesReader extends fb.StructReader { int get size => 2; @override - FooProperties createObject(fb.BufferContext bc, int offset) => - FooProperties._(bc, offset); + FooProperties createObject(fb.BufferContext bc, int offset) => + FooProperties._(bc, offset); } class FooPropertiesBuilder { @@ -175,19 +167,15 @@ class FooPropertiesBuilder { fbBuilder.putBool(a); return fbBuilder.offset; } - } class FooPropertiesObjectBuilder extends fb.ObjectBuilder { final bool _a; final bool _b; - FooPropertiesObjectBuilder({ - required bool a, - required bool b, - }) - : _a = a, - _b = b; + FooPropertiesObjectBuilder({required bool a, required bool b}) + : _a = a, + _b = b; /// Finish building, and store into the [fbBuilder]. @override diff --git a/dart/test/enums_generated.dart b/dart/test/enums_generated.dart index e2b8c50df7d..b57e8fa2221 100644 --- a/dart/test/enums_generated.dart +++ b/dart/test/enums_generated.dart @@ -2,8 +2,8 @@ // ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable, constant_identifier_names import 'dart:typed_data' show Uint8List; -import 'package:flat_buffers/flat_buffers.dart' as fb; +import 'package:flat_buffers/flat_buffers.dart' as fb; enum OptionsEnum { A(1), @@ -15,10 +15,14 @@ enum OptionsEnum { factory OptionsEnum.fromValue(int value) { switch (value) { - case 1: return OptionsEnum.A; - case 2: return OptionsEnum.B; - case 3: return OptionsEnum.C; - default: throw StateError('Invalid value $value for bit flag enum'); + case 1: + return OptionsEnum.A; + case 2: + return OptionsEnum.B; + case 3: + return OptionsEnum.C; + default: + throw StateError('Invalid value $value for bit flag enum'); } } @@ -53,7 +57,9 @@ class MyTable { final fb.BufferContext _bc; final int _bcOffset; - List? get options => const fb.ListReader(OptionsEnum.reader).vTableGetNullable(_bc, _bcOffset, 4); + List? get options => const fb.ListReader( + OptionsEnum.reader, + ).vTableGetNullable(_bc, _bcOffset, 4); @override String toString() { @@ -61,7 +67,11 @@ class MyTable { } MyTableT unpack() => MyTableT( - options: const fb.ListReader(OptionsEnum.reader, lazy: false).vTableGetNullable(_bc, _bcOffset, 4)); + options: const fb.ListReader( + OptionsEnum.reader, + lazy: false, + ).vTableGetNullable(_bc, _bcOffset, 4), + ); static int pack(fb.Builder fbBuilder, MyTableT? object) { if (object == null) return 0; @@ -72,12 +82,12 @@ class MyTable { class MyTableT implements fb.Packable { List? options; - MyTableT({ - this.options}); + MyTableT({this.options}); @override int pack(fb.Builder fbBuilder) { - final int? optionsOffset = options == null ? null + final int? optionsOffset = options == null + ? null : fbBuilder.writeListUint32(options!.map((f) => f.value).toList()); fbBuilder.startTable(1); fbBuilder.addOffset(0, optionsOffset); @@ -94,8 +104,8 @@ class _MyTableReader extends fb.TableReader { const _MyTableReader(); @override - MyTable createObject(fb.BufferContext bc, int offset) => - MyTable._(bc, offset); + MyTable createObject(fb.BufferContext bc, int offset) => + MyTable._(bc, offset); } class MyTableBuilder { @@ -120,15 +130,13 @@ class MyTableBuilder { class MyTableObjectBuilder extends fb.ObjectBuilder { final List? _options; - MyTableObjectBuilder({ - List? options, - }) - : _options = options; + MyTableObjectBuilder({List? options}) : _options = options; /// Finish building, and store into the [fbBuilder]. @override int finish(fb.Builder fbBuilder) { - final int? optionsOffset = _options == null ? null + final int? optionsOffset = _options == null + ? null : fbBuilder.writeListUint32(_options!.map((f) => f.value).toList()); fbBuilder.startTable(1); fbBuilder.addOffset(0, optionsOffset); diff --git a/dart/test/flat_buffers_test.dart b/dart/test/flat_buffers_test.dart index b872cfbe814..275a2ef4092 100644 --- a/dart/test/flat_buffers_test.dart +++ b/dart/test/flat_buffers_test.dart @@ -1,16 +1,15 @@ -import 'dart:typed_data'; import 'dart:io' as io; - -import 'package:path/path.dart' as path; +import 'dart:typed_data'; import 'package:flat_buffers/flat_buffers.dart'; +import 'package:path/path.dart' as path; import 'package:test/test.dart'; import 'package:test_reflective_loader/test_reflective_loader.dart'; -import './monster_test_my_game.example_generated.dart' as example; +import './bool_structs_generated.dart' as example4; import './monster_test_my_game.example2_generated.dart' as example2; +import './monster_test_my_game.example_generated.dart' as example; import 'enums_generated.dart' as example3; -import './bool_structs_generated.dart' as example4; main() { defineReflectiveSuite(() { @@ -29,11 +28,9 @@ int indexToField(int index) { @reflectiveTest class CheckOtherLangaugesData { test_cppData() async { - List data = await io.File(path.join( - path.context.current, - 'test', - 'monsterdata_test.mon', - )).readAsBytes(); + List data = await io.File( + path.join(path.context.current, 'test', 'monsterdata_test.mon'), + ).readAsBytes(); example.Monster mon = example.Monster(data); expect(mon.hp, 80); expect(mon.mana, 150); @@ -61,91 +58,92 @@ class CheckOtherLangaugesData { // this will fail if accessing any field fails. expect( - mon.toString(), - 'Monster{' - 'pos: Vec3{x: 1.0, y: 2.0, z: 3.0, test1: 3.0, test2: Color.Green, test3: Test{a: 5, b: 6}}, ' - 'mana: 150, hp: 80, name: MyMonster, inventory: [0, 1, 2, 3, 4], ' - 'color: Color.Blue, testType: AnyTypeId.Monster, ' - 'test: Monster{pos: null, mana: 150, hp: 100, name: Fred, ' - 'inventory: null, color: Color.Blue, testType: null, ' - 'test: null, test4: null, testarrayofstring: null, ' - 'testarrayoftables: null, enemy: null, testnestedflatbuffer: null, ' - 'testempty: null, testbool: false, testhashs32Fnv1: 0, ' - 'testhashu32Fnv1: 0, testhashs64Fnv1: 0, testhashu64Fnv1: 0, ' - 'testhashs32Fnv1a: 0, testhashu32Fnv1a: 0, testhashs64Fnv1a: 0, ' - 'testhashu64Fnv1a: 0, testarrayofbools: null, testf: 3.14159, ' - 'testf2: 3.0, testf3: 0.0, testarrayofstring2: null, ' - 'testarrayofsortedstruct: null, flex: null, test5: null, ' - 'vectorOfLongs: null, vectorOfDoubles: null, parentNamespaceTest: null, ' - 'vectorOfReferrables: null, singleWeakReference: 0, ' - 'vectorOfWeakReferences: null, vectorOfStrongReferrables: null, ' - 'coOwningReference: 0, vectorOfCoOwningReferences: null, ' - 'nonOwningReference: 0, vectorOfNonOwningReferences: null, ' - 'anyUniqueType: null, anyUnique: null, anyAmbiguousType: null, ' - 'anyAmbiguous: null, vectorOfEnums: null, signedEnum: Race.None, ' - 'testrequirednestedflatbuffer: null, scalarKeySortedTables: null, ' - 'nativeInline: null, ' - 'longEnumNonEnumDefault: LongEnum._default, ' - 'longEnumNormalDefault: LongEnum.LongOne, nanDefault: NaN, ' - 'infDefault: Infinity, positiveInfDefault: Infinity, infinityDefault: ' - 'Infinity, positiveInfinityDefault: Infinity, negativeInfDefault: ' - '-Infinity, negativeInfinityDefault: -Infinity, doubleInfDefault: Infinity}, ' - 'test4: [Test{a: 10, b: 20}, Test{a: 30, b: 40}], ' - 'testarrayofstring: [test1, test2], testarrayoftables: null, ' - 'enemy: Monster{pos: null, mana: 150, hp: 100, name: Fred, ' - 'inventory: null, color: Color.Blue, testType: null, ' - 'test: null, test4: null, testarrayofstring: null, ' - 'testarrayoftables: null, enemy: null, testnestedflatbuffer: null, ' - 'testempty: null, testbool: false, testhashs32Fnv1: 0, ' - 'testhashu32Fnv1: 0, testhashs64Fnv1: 0, testhashu64Fnv1: 0, ' - 'testhashs32Fnv1a: 0, testhashu32Fnv1a: 0, testhashs64Fnv1a: 0, ' - 'testhashu64Fnv1a: 0, testarrayofbools: null, testf: 3.14159, ' - 'testf2: 3.0, testf3: 0.0, testarrayofstring2: null, ' - 'testarrayofsortedstruct: null, flex: null, test5: null, ' - 'vectorOfLongs: null, vectorOfDoubles: null, parentNamespaceTest: null, ' - 'vectorOfReferrables: null, singleWeakReference: 0, ' - 'vectorOfWeakReferences: null, vectorOfStrongReferrables: null, ' - 'coOwningReference: 0, vectorOfCoOwningReferences: null, ' - 'nonOwningReference: 0, vectorOfNonOwningReferences: null, ' - 'anyUniqueType: null, anyUnique: null, anyAmbiguousType: null, ' - 'anyAmbiguous: null, vectorOfEnums: null, signedEnum: Race.None, ' - 'testrequirednestedflatbuffer: null, scalarKeySortedTables: null, ' - 'nativeInline: null, ' - 'longEnumNonEnumDefault: LongEnum._default, ' - 'longEnumNormalDefault: LongEnum.LongOne, nanDefault: NaN, ' - 'infDefault: Infinity, positiveInfDefault: Infinity, infinityDefault: ' - 'Infinity, positiveInfinityDefault: Infinity, negativeInfDefault: ' - '-Infinity, negativeInfinityDefault: -Infinity, doubleInfDefault: Infinity}, ' - 'testnestedflatbuffer: null, testempty: null, testbool: true, ' - 'testhashs32Fnv1: -579221183, testhashu32Fnv1: 3715746113, ' - 'testhashs64Fnv1: 7930699090847568257, ' - 'testhashu64Fnv1: 7930699090847568257, ' - 'testhashs32Fnv1a: -1904106383, testhashu32Fnv1a: 2390860913, ' - 'testhashs64Fnv1a: 4898026182817603057, ' - 'testhashu64Fnv1a: 4898026182817603057, ' - 'testarrayofbools: [true, false, true], testf: 3.14159, testf2: 3.0, ' - 'testf3: 0.0, testarrayofstring2: null, testarrayofsortedstruct: [' - 'Ability{id: 0, distance: 45}, Ability{id: 1, distance: 21}, ' - 'Ability{id: 5, distance: 12}], ' - 'flex: null, test5: [Test{a: 10, b: 20}, Test{a: 30, b: 40}], ' - 'vectorOfLongs: [1, 100, 10000, 1000000, 100000000], ' - 'vectorOfDoubles: [-1.7976931348623157e+308, 0.0, 1.7976931348623157e+308], ' - 'parentNamespaceTest: null, vectorOfReferrables: null, ' - 'singleWeakReference: 0, vectorOfWeakReferences: null, ' - 'vectorOfStrongReferrables: null, coOwningReference: 0, ' - 'vectorOfCoOwningReferences: null, nonOwningReference: 0, ' - 'vectorOfNonOwningReferences: null, ' - 'anyUniqueType: null, anyUnique: null, ' - 'anyAmbiguousType: null, ' - 'anyAmbiguous: null, vectorOfEnums: null, signedEnum: Race.None, ' - 'testrequirednestedflatbuffer: null, scalarKeySortedTables: [Stat{id: ' - 'miss, val: 0, count: 0}, Stat{id: hit, val: 10, count: 1}], ' - 'nativeInline: Test{a: 1, b: 2}, ' - 'longEnumNonEnumDefault: LongEnum._default, ' - 'longEnumNormalDefault: LongEnum.LongOne, nanDefault: NaN, ' - 'infDefault: Infinity, positiveInfDefault: Infinity, infinityDefault: ' - 'Infinity, positiveInfinityDefault: Infinity, negativeInfDefault: ' - '-Infinity, negativeInfinityDefault: -Infinity, doubleInfDefault: Infinity}'); + mon.toString(), + 'Monster{' + 'pos: Vec3{x: 1.0, y: 2.0, z: 3.0, test1: 3.0, test2: Color.Green, test3: Test{a: 5, b: 6}}, ' + 'mana: 150, hp: 80, name: MyMonster, inventory: [0, 1, 2, 3, 4], ' + 'color: Color.Blue, testType: AnyTypeId.Monster, ' + 'test: Monster{pos: null, mana: 150, hp: 100, name: Fred, ' + 'inventory: null, color: Color.Blue, testType: null, ' + 'test: null, test4: null, testarrayofstring: null, ' + 'testarrayoftables: null, enemy: null, testnestedflatbuffer: null, ' + 'testempty: null, testbool: false, testhashs32Fnv1: 0, ' + 'testhashu32Fnv1: 0, testhashs64Fnv1: 0, testhashu64Fnv1: 0, ' + 'testhashs32Fnv1a: 0, testhashu32Fnv1a: 0, testhashs64Fnv1a: 0, ' + 'testhashu64Fnv1a: 0, testarrayofbools: null, testf: 3.14159, ' + 'testf2: 3.0, testf3: 0.0, testarrayofstring2: null, ' + 'testarrayofsortedstruct: null, flex: null, test5: null, ' + 'vectorOfLongs: null, vectorOfDoubles: null, parentNamespaceTest: null, ' + 'vectorOfReferrables: null, singleWeakReference: 0, ' + 'vectorOfWeakReferences: null, vectorOfStrongReferrables: null, ' + 'coOwningReference: 0, vectorOfCoOwningReferences: null, ' + 'nonOwningReference: 0, vectorOfNonOwningReferences: null, ' + 'anyUniqueType: null, anyUnique: null, anyAmbiguousType: null, ' + 'anyAmbiguous: null, vectorOfEnums: null, signedEnum: Race.None, ' + 'testrequirednestedflatbuffer: null, scalarKeySortedTables: null, ' + 'nativeInline: null, ' + 'longEnumNonEnumDefault: LongEnum._default, ' + 'longEnumNormalDefault: LongEnum.LongOne, nanDefault: NaN, ' + 'infDefault: Infinity, positiveInfDefault: Infinity, infinityDefault: ' + 'Infinity, positiveInfinityDefault: Infinity, negativeInfDefault: ' + '-Infinity, negativeInfinityDefault: -Infinity, doubleInfDefault: Infinity}, ' + 'test4: [Test{a: 10, b: 20}, Test{a: 30, b: 40}], ' + 'testarrayofstring: [test1, test2], testarrayoftables: null, ' + 'enemy: Monster{pos: null, mana: 150, hp: 100, name: Fred, ' + 'inventory: null, color: Color.Blue, testType: null, ' + 'test: null, test4: null, testarrayofstring: null, ' + 'testarrayoftables: null, enemy: null, testnestedflatbuffer: null, ' + 'testempty: null, testbool: false, testhashs32Fnv1: 0, ' + 'testhashu32Fnv1: 0, testhashs64Fnv1: 0, testhashu64Fnv1: 0, ' + 'testhashs32Fnv1a: 0, testhashu32Fnv1a: 0, testhashs64Fnv1a: 0, ' + 'testhashu64Fnv1a: 0, testarrayofbools: null, testf: 3.14159, ' + 'testf2: 3.0, testf3: 0.0, testarrayofstring2: null, ' + 'testarrayofsortedstruct: null, flex: null, test5: null, ' + 'vectorOfLongs: null, vectorOfDoubles: null, parentNamespaceTest: null, ' + 'vectorOfReferrables: null, singleWeakReference: 0, ' + 'vectorOfWeakReferences: null, vectorOfStrongReferrables: null, ' + 'coOwningReference: 0, vectorOfCoOwningReferences: null, ' + 'nonOwningReference: 0, vectorOfNonOwningReferences: null, ' + 'anyUniqueType: null, anyUnique: null, anyAmbiguousType: null, ' + 'anyAmbiguous: null, vectorOfEnums: null, signedEnum: Race.None, ' + 'testrequirednestedflatbuffer: null, scalarKeySortedTables: null, ' + 'nativeInline: null, ' + 'longEnumNonEnumDefault: LongEnum._default, ' + 'longEnumNormalDefault: LongEnum.LongOne, nanDefault: NaN, ' + 'infDefault: Infinity, positiveInfDefault: Infinity, infinityDefault: ' + 'Infinity, positiveInfinityDefault: Infinity, negativeInfDefault: ' + '-Infinity, negativeInfinityDefault: -Infinity, doubleInfDefault: Infinity}, ' + 'testnestedflatbuffer: null, testempty: null, testbool: true, ' + 'testhashs32Fnv1: -579221183, testhashu32Fnv1: 3715746113, ' + 'testhashs64Fnv1: 7930699090847568257, ' + 'testhashu64Fnv1: 7930699090847568257, ' + 'testhashs32Fnv1a: -1904106383, testhashu32Fnv1a: 2390860913, ' + 'testhashs64Fnv1a: 4898026182817603057, ' + 'testhashu64Fnv1a: 4898026182817603057, ' + 'testarrayofbools: [true, false, true], testf: 3.14159, testf2: 3.0, ' + 'testf3: 0.0, testarrayofstring2: null, testarrayofsortedstruct: [' + 'Ability{id: 0, distance: 45}, Ability{id: 1, distance: 21}, ' + 'Ability{id: 5, distance: 12}], ' + 'flex: null, test5: [Test{a: 10, b: 20}, Test{a: 30, b: 40}], ' + 'vectorOfLongs: [1, 100, 10000, 1000000, 100000000], ' + 'vectorOfDoubles: [-1.7976931348623157e+308, 0.0, 1.7976931348623157e+308], ' + 'parentNamespaceTest: null, vectorOfReferrables: null, ' + 'singleWeakReference: 0, vectorOfWeakReferences: null, ' + 'vectorOfStrongReferrables: null, coOwningReference: 0, ' + 'vectorOfCoOwningReferences: null, nonOwningReference: 0, ' + 'vectorOfNonOwningReferences: null, ' + 'anyUniqueType: null, anyUnique: null, ' + 'anyAmbiguousType: null, ' + 'anyAmbiguous: null, vectorOfEnums: null, signedEnum: Race.None, ' + 'testrequirednestedflatbuffer: null, scalarKeySortedTables: [Stat{id: ' + 'miss, val: 0, count: 0}, Stat{id: hit, val: 10, count: 1}], ' + 'nativeInline: Test{a: 1, b: 2}, ' + 'longEnumNonEnumDefault: LongEnum._default, ' + 'longEnumNormalDefault: LongEnum.LongOne, nanDefault: NaN, ' + 'infDefault: Infinity, positiveInfDefault: Infinity, infinityDefault: ' + 'Infinity, positiveInfinityDefault: Infinity, negativeInfDefault: ' + '-Infinity, negativeInfinityDefault: -Infinity, doubleInfDefault: Infinity}', + ); } } @@ -298,20 +296,72 @@ class BuilderTest { expect(allocator.buffer(builder.size()), [2, 0, 0, 0, 0, 0, 0, 1]); builder.putUint8(3); - expect( - allocator.buffer(builder.size()), [0, 0, 0, 3, 2, 0, 0, 0, 0, 0, 0, 1]); + expect(allocator.buffer(builder.size()), [ + 0, + 0, + 0, + 3, + 2, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + ]); builder.putUint8(4); - expect( - allocator.buffer(builder.size()), [0, 0, 4, 3, 2, 0, 0, 0, 0, 0, 0, 1]); + expect(allocator.buffer(builder.size()), [ + 0, + 0, + 4, + 3, + 2, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + ]); builder.putUint8(5); - expect( - allocator.buffer(builder.size()), [0, 5, 4, 3, 2, 0, 0, 0, 0, 0, 0, 1]); + expect(allocator.buffer(builder.size()), [ + 0, + 5, + 4, + 3, + 2, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + ]); builder.putUint32(6); - expect(allocator.buffer(builder.size()), - [6, 0, 0, 0, 0, 5, 4, 3, 2, 0, 0, 0, 0, 0, 0, 1]); + expect(allocator.buffer(builder.size()), [ + 6, + 0, + 0, + 0, + 0, + 5, + 4, + 3, + 2, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + ]); } void test_table_default() { @@ -331,14 +381,14 @@ class BuilderTest { int objectOffset = buffer.derefObject(0); // was not written, so uses the new default value expect( - const Int32Reader() - .vTableGet(buffer, objectOffset, indexToField(0), 15), - 15); + const Int32Reader().vTableGet(buffer, objectOffset, indexToField(0), 15), + 15, + ); // has the written value expect( - const Int32Reader() - .vTableGet(buffer, objectOffset, indexToField(1), 15), - 20); + const Int32Reader().vTableGet(buffer, objectOffset, indexToField(1), 15), + 20, + ); } void test_table_format([Builder? builder]) { @@ -370,7 +420,9 @@ class BuilderTest { for (int i = 0; i < 3; i++) { int offset = byteData.getUint16(vTableLoc + 4 + 2 * i, Endian.little); expect( - byteData.getInt32(tableDataLoc + offset, Endian.little), 10 + 10 * i); + byteData.getInt32(tableDataLoc + offset, Endian.little), + 10 + 10 * i, + ); } } @@ -380,10 +432,14 @@ class BuilderTest { List byteList; { Builder builder = Builder(initialSize: 0); - int? latinStringOffset = - builder.writeString(latinString, asciiOptimization: true); - int? unicodeStringOffset = - builder.writeString(unicodeString, asciiOptimization: true); + int? latinStringOffset = builder.writeString( + latinString, + asciiOptimization: true, + ); + int? unicodeStringOffset = builder.writeString( + unicodeString, + asciiOptimization: true, + ); builder.startTable(2); builder.addOffset(0, latinStringOffset); builder.addOffset(1, unicodeStringOffset); @@ -395,13 +451,19 @@ class BuilderTest { BufferContext buf = BufferContext.fromBytes(byteList); int objectOffset = buf.derefObject(0); expect( - const StringReader() - .vTableGetNullable(buf, objectOffset, indexToField(0)), - latinString); + const StringReader().vTableGetNullable( + buf, + objectOffset, + indexToField(0), + ), + latinString, + ); expect( - const StringReader(asciiOptimization: true) - .vTableGetNullable(buf, objectOffset, indexToField(1)), - unicodeString); + const StringReader( + asciiOptimization: true, + ).vTableGetNullable(buf, objectOffset, indexToField(1)), + unicodeString, + ); } void test_table_types([Builder? builder]) { @@ -425,33 +487,41 @@ class BuilderTest { BufferContext buf = BufferContext.fromBytes(byteList); int objectOffset = buf.derefObject(0); expect( - const BoolReader() - .vTableGetNullable(buf, objectOffset, indexToField(0)), - true); + const BoolReader().vTableGetNullable(buf, objectOffset, indexToField(0)), + true, + ); expect( - const Int8Reader() - .vTableGetNullable(buf, objectOffset, indexToField(1)), - 10); + const Int8Reader().vTableGetNullable(buf, objectOffset, indexToField(1)), + 10, + ); expect( - const Int32Reader() - .vTableGetNullable(buf, objectOffset, indexToField(2)), - 20); + const Int32Reader().vTableGetNullable(buf, objectOffset, indexToField(2)), + 20, + ); expect( - const StringReader() - .vTableGetNullable(buf, objectOffset, indexToField(3)), - '12345'); + const StringReader().vTableGetNullable( + buf, + objectOffset, + indexToField(3), + ), + '12345', + ); expect( - const Int32Reader() - .vTableGetNullable(buf, objectOffset, indexToField(4)), - 40); + const Int32Reader().vTableGetNullable(buf, objectOffset, indexToField(4)), + 40, + ); expect( - const Uint32Reader() - .vTableGetNullable(buf, objectOffset, indexToField(5)), - 0x9ABCDEF0); + const Uint32Reader().vTableGetNullable( + buf, + objectOffset, + indexToField(5), + ), + 0x9ABCDEF0, + ); expect( - const Uint8Reader() - .vTableGetNullable(buf, objectOffset, indexToField(6)), - 0x9A); + const Uint8Reader().vTableGetNullable(buf, objectOffset, indexToField(6)), + 0x9A, + ); } void test_writeList_of_Uint32() { @@ -596,8 +666,9 @@ class BuilderTest { } // read and verify BufferContext buf = BufferContext.fromBytes(byteList); - List items = - const ListReader(TestPointReader()).read(buf, 0); + List items = const ListReader( + TestPointReader(), + ).read(buf, 0); expect(items, hasLength(2)); expect(items[0].x, 10); expect(items[0].y, 20); @@ -627,8 +698,10 @@ class BuilderTest { List byteList; { builder ??= Builder(initialSize: 0); - int listOffset = builder.writeList( - [builder.writeString('12345'), builder.writeString('ABC')]); + int listOffset = builder.writeList([ + builder.writeString('12345'), + builder.writeString('ABC'), + ]); builder.startTable(1); builder.addOffset(0, listOffset); int offset = builder.endTable(); @@ -707,13 +780,14 @@ class BuilderTest { test_table_format, test_table_types, test_writeList_ofObjects, - test_writeList_ofStrings_inObject + test_writeList_ofStrings_inObject, ]; // Execute all test cases in all permutations of their order. // To do that, we generate permutations of test case indexes. - final testCasesPermutations = - _permutationsOf(List.generate(testCases.length, (index) => index)); + final testCasesPermutations = _permutationsOf( + List.generate(testCases.length, (index) => index), + ); expect(testCasesPermutations.length, _factorial(testCases.length)); for (var indexes in testCasesPermutations) { @@ -783,12 +857,13 @@ class ObjectAPITest { void test_tableMonster() { final monster = example.MonsterT() ..pos = example.Vec3T( - x: 1, - y: 2, - z: 3, - test1: 4.0, - test2: example.Color.Red, - test3: example.TestT(a: 1, b: 2)) + x: 1, + y: 2, + z: 3, + test1: 4.0, + test2: example.Color.Red, + test3: example.TestT(a: 1, b: 2), + ) ..mana = 2 ..name = 'Monstrous' ..inventory = [24, 42] @@ -804,7 +879,7 @@ class ObjectAPITest { ..testf = 42.24 ..testarrayofsortedstruct = [ example.AbilityT(id: 1, distance: 5), - example.AbilityT(id: 3, distance: 7) + example.AbilityT(id: 3, distance: 7), ] ..vectorOfLongs = [5, 6, 7] ..vectorOfDoubles = [8.9, 9.0, 10.1, 11.2] @@ -867,8 +942,9 @@ class StringListWrapperImpl { StringListWrapperImpl(this.bp, this.offset); - List? get items => const ListReader(StringReader()) - .vTableGetNullable(bp, offset, indexToField(0)); + List? get items => const ListReader( + StringReader(), + ).vTableGetNullable(bp, offset, indexToField(0)); } class StringListWrapperReader extends TableReader { @@ -906,10 +982,14 @@ class GeneratorTest { expect(example.Color.values, same(example.Color.values)); expect(example.Race.values, same(example.Race.values)); expect(example.AnyTypeId.values, same(example.AnyTypeId.values)); - expect(example.AnyUniqueAliasesTypeId.values, - same(example.AnyUniqueAliasesTypeId.values)); - expect(example.AnyAmbiguousAliasesTypeId.values, - same(example.AnyAmbiguousAliasesTypeId.values)); + expect( + example.AnyUniqueAliasesTypeId.values, + same(example.AnyUniqueAliasesTypeId.values), + ); + expect( + example.AnyAmbiguousAliasesTypeId.values, + same(example.AnyAmbiguousAliasesTypeId.values), + ); } } @@ -917,11 +997,13 @@ class GeneratorTest { @reflectiveTest class ListOfEnumsTest { void test_listOfEnums() async { - var mytable = example3.MyTableObjectBuilder(options: [ - example3.OptionsEnum.A, - example3.OptionsEnum.B, - example3.OptionsEnum.C - ]); + var mytable = example3.MyTableObjectBuilder( + options: [ + example3.OptionsEnum.A, + example3.OptionsEnum.B, + example3.OptionsEnum.C, + ], + ); var bytes = mytable.toBytes(); var mytable_read = example3.MyTable(bytes); expect(mytable_read.options![0].value, example3.OptionsEnum.A.value); @@ -934,7 +1016,8 @@ class ListOfEnumsTest { class BoolInStructTest { void test_boolInStruct() async { var mystruct = example4.FooObjectBuilder( - myFoo: example4.FooPropertiesObjectBuilder(a: true, b: false)); + myFoo: example4.FooPropertiesObjectBuilder(a: true, b: false), + ); var bytes = mystruct.toBytes(); var mystruct_read = example4.Foo(bytes); expect(mystruct_read.myFoo!.a, true); diff --git a/dart/test/flex_builder_test.dart b/dart/test/flex_builder_test.dart index 0c4a18e61d3..0f766de7385 100644 --- a/dart/test/flex_builder_test.dart +++ b/dart/test/flex_builder_test.dart @@ -62,8 +62,23 @@ void main() { { var flx = Builder(); flx.addString('hello 😱'); - expect(flx.finish(), - [10, 104, 101, 108, 108, 111, 32, 240, 159, 152, 177, 0, 11, 20, 1]); + expect(flx.finish(), [ + 10, + 104, + 101, + 108, + 108, + 111, + 32, + 240, + 159, + 152, + 177, + 0, + 11, + 20, + 1, + ]); } }); @@ -117,7 +132,7 @@ void main() { 192, 16, 75, - 1 + 1, ]); } { @@ -177,7 +192,7 @@ void main() { 7, 3, 60, - 1 + 1, ]); } { @@ -215,7 +230,7 @@ void main() { 10, 6, 60, - 1 + 1, ]); } { @@ -300,7 +315,7 @@ void main() { 104, 45, 43, - 1 + 1, ]); } }); @@ -322,8 +337,24 @@ void main() { ..addKey('') ..addInt(45) ..end(); - expect( - flx.finish(), [97, 0, 0, 2, 2, 5, 2, 1, 2, 45, 12, 4, 4, 4, 36, 1]); + expect(flx.finish(), [ + 97, + 0, + 0, + 2, + 2, + 5, + 2, + 1, + 2, + 45, + 12, + 4, + 4, + 4, + 36, + 1, + ]); } { var flx = Builder() @@ -367,7 +398,7 @@ void main() { 36, 4, 40, - 1 + 1, ]); } }); @@ -381,133 +412,152 @@ void main() { test('build from object', () { expect( - Builder.buildFromObject(Uint8List.fromList([1, 2, 3]).buffer) - .asUint8List(), - [3, 1, 2, 3, 3, 100, 1]); + Builder.buildFromObject( + Uint8List.fromList([1, 2, 3]).buffer, + ).asUint8List(), + [3, 1, 2, 3, 3, 100, 1], + ); expect(Builder.buildFromObject(null).asUint8List(), [0, 0, 1]); expect(Builder.buildFromObject(true).asUint8List(), [1, 104, 1]); expect(Builder.buildFromObject(false).asUint8List(), [0, 104, 1]); expect(Builder.buildFromObject(25).asUint8List(), [25, 4, 1]); expect(Builder.buildFromObject(-250).asUint8List(), [6, 255, 5, 2]); + expect(Builder.buildFromObject(-2.50).asUint8List(), [ + 0, + 0, + 32, + 192, + 14, + 4, + ]); + expect(Builder.buildFromObject('Maxim').asUint8List(), [ + 5, + 77, + 97, + 120, + 105, + 109, + 0, + 6, + 20, + 1, + ]); expect( - Builder.buildFromObject(-2.50).asUint8List(), [0, 0, 32, 192, 14, 4]); - expect(Builder.buildFromObject('Maxim').asUint8List(), - [5, 77, 97, 120, 105, 109, 0, 6, 20, 1]); - expect( - Builder.buildFromObject([1, 3.3, 'max', true, null, false]) - .asUint8List(), - [ - 3, - 109, - 97, - 120, - 0, - 0, - 0, - 0, - 6, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 1, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 102, - 102, - 102, - 102, - 102, - 102, - 10, - 64, - 31, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 1, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 4, - 15, - 20, - 104, - 0, - 104, - 54, - 43, - 1 - ]); + Builder.buildFromObject([1, 3.3, 'max', true, null, false]).asUint8List(), + [ + 3, + 109, + 97, + 120, + 0, + 0, + 0, + 0, + 6, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 102, + 102, + 102, + 102, + 102, + 102, + 10, + 64, + 31, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 4, + 15, + 20, + 104, + 0, + 104, + 54, + 43, + 1, + ], + ); expect( - Builder.buildFromObject([ - {'something': 12}, - {'something': 45} - ]).asUint8List(), - [ - 115, - 111, - 109, - 101, - 116, - 104, - 105, - 110, - 103, - 0, - 1, - 11, - 1, - 1, - 1, - 12, - 4, - 6, - 1, - 1, - 45, - 4, - 2, - 8, - 4, - 36, - 36, - 4, - 40, - 1 - ]); + Builder.buildFromObject([ + {'something': 12}, + {'something': 45}, + ]).asUint8List(), + [ + 115, + 111, + 109, + 101, + 116, + 104, + 105, + 110, + 103, + 0, + 1, + 11, + 1, + 1, + 1, + 12, + 4, + 6, + 1, + 1, + 45, + 4, + 2, + 8, + 4, + 36, + 36, + 4, + 40, + 1, + ], + ); }); test('add double indirectly', () { @@ -543,7 +593,7 @@ void main() { 35, 8, 40, - 1 + 1, ]); }); @@ -580,7 +630,7 @@ void main() { 27, 8, 40, - 1 + 1, ]); }); diff --git a/dart/test/flex_reader_test.dart b/dart/test/flex_reader_test.dart index 6e0855fc2b9..d77d1da462c 100644 --- a/dart/test/flex_reader_test.dart +++ b/dart/test/flex_reader_test.dart @@ -20,70 +20,76 @@ void main() { expect(Reference.fromBuffer(b([1, 4, 5, 2])).intValue, 1025); expect(Reference.fromBuffer(b([255, 251, 5, 2])).intValue, -1025); expect(Reference.fromBuffer(b([1, 4, 9, 2])).intValue, 1025); - expect(Reference.fromBuffer(b([255, 255, 255, 127, 6, 4])).intValue, - 2147483647); + expect( + Reference.fromBuffer(b([255, 255, 255, 127, 6, 4])).intValue, + 2147483647, + ); expect(Reference.fromBuffer(b([0, 0, 0, 128, 6, 4])).intValue, -2147483648); expect( - Reference.fromBuffer(b([255, 255, 255, 255, 0, 0, 0, 0, 7, 8])) - .intValue, - 4294967295); + Reference.fromBuffer(b([255, 255, 255, 255, 0, 0, 0, 0, 7, 8])).intValue, + 4294967295, + ); + expect( + Reference.fromBuffer( + b([255, 255, 255, 255, 255, 255, 255, 127, 7, 8]), + ).intValue, + 9223372036854775807, + ); expect( - Reference.fromBuffer(b([255, 255, 255, 255, 255, 255, 255, 127, 7, 8])) - .intValue, - 9223372036854775807); - expect(Reference.fromBuffer(b([0, 0, 0, 0, 0, 0, 0, 128, 7, 8])).intValue, - -9223372036854775808); + Reference.fromBuffer(b([0, 0, 0, 0, 0, 0, 0, 128, 7, 8])).intValue, + -9223372036854775808, + ); // Dart does not really support UInt64 -// expect(FlxValue.fromBuffer(b([255, 255, 255, 255, 255, 255, 255, 255, 11, 8])).intValue, 18446744073709551615); + // expect(FlxValue.fromBuffer(b([255, 255, 255, 255, 255, 255, 255, 255, 11, 8])).intValue, 18446744073709551615); }); test('double value', () { expect(Reference.fromBuffer(b([0, 0, 128, 63, 14, 4])).doubleValue, 1.0); expect(Reference.fromBuffer(b([0, 0, 144, 64, 14, 4])).doubleValue, 4.5); - expect(Reference.fromBuffer(b([205, 204, 204, 61, 14, 4])).doubleValue, - closeTo(.1, .001)); expect( - Reference.fromBuffer(b([154, 153, 153, 153, 153, 153, 185, 63, 15, 8])) - .doubleValue, - .1); + Reference.fromBuffer(b([205, 204, 204, 61, 14, 4])).doubleValue, + closeTo(.1, .001), + ); + expect( + Reference.fromBuffer( + b([154, 153, 153, 153, 153, 153, 185, 63, 15, 8]), + ).doubleValue, + .1, + ); }); test('num value', () { expect(Reference.fromBuffer(b([0, 0, 144, 64, 14, 4])).numValue, 4.5); - expect(Reference.fromBuffer(b([205, 204, 204, 61, 14, 4])).numValue, - closeTo(.1, .001)); expect( - Reference.fromBuffer(b([154, 153, 153, 153, 153, 153, 185, 63, 15, 8])) - .numValue, - .1); + Reference.fromBuffer(b([205, 204, 204, 61, 14, 4])).numValue, + closeTo(.1, .001), + ); + expect( + Reference.fromBuffer( + b([154, 153, 153, 153, 153, 153, 185, 63, 15, 8]), + ).numValue, + .1, + ); expect(Reference.fromBuffer(b([255, 251, 5, 2])).numValue, -1025); }); test('string value', () { expect( - Reference.fromBuffer(b([5, 77, 97, 120, 105, 109, 0, 6, 20, 1])) - .stringValue, - 'Maxim'); + Reference.fromBuffer( + b([5, 77, 97, 120, 105, 109, 0, 6, 20, 1]), + ).stringValue, + 'Maxim', + ); expect( - Reference.fromBuffer(b([ - 10, - 104, - 101, - 108, - 108, - 111, - 32, - 240, - 159, - 152, - 177, - 0, - 11, - 20, - 1 - ])).stringValue, - 'hello 😱'); + Reference.fromBuffer( + b([10, 104, 101, 108, 108, 111, 32, 240, 159, 152, 177, 0, 11, 20, 1]), + ).stringValue, + 'hello 😱', + ); }); test('blob value', () { - expect( - Reference.fromBuffer(b([3, 1, 2, 3, 3, 100, 1])).blobValue, [1, 2, 3]); + expect(Reference.fromBuffer(b([3, 1, 2, 3, 3, 100, 1])).blobValue, [ + 1, + 2, + 3, + ]); }); test('bool vector', () { var flx = Reference.fromBuffer(b([3, 1, 0, 1, 3, 144, 1])); @@ -95,450 +101,443 @@ void main() { testNumbers([3, 1, 2, 3, 3, 44, 1], [1, 2, 3]); testNumbers([3, 255, 2, 3, 3, 44, 1], [-1, 2, 3]); testNumbers([3, 0, 1, 0, 43, 2, 3, 0, 6, 45, 1], [1, 555, 3]); - testNumbers([3, 0, 0, 0, 1, 0, 0, 0, 204, 216, 0, 0, 3, 0, 0, 0, 12, 46, 1], - [1, 55500, 3]); - testNumbers([ - 3, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 1, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 172, - 128, - 94, - 239, - 12, - 0, - 0, - 0, - 3, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 24, - 47, - 1 - ], [ - 1, - 55555555500, - 3 - ]); testNumbers( - [3, 0, 0, 0, 0, 0, 192, 63, 0, 0, 32, 64, 0, 0, 96, 64, 12, 54, 1], - [1.5, 2.5, 3.5]); - testNumbers([ - 3, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 154, - 153, - 153, - 153, - 153, - 153, - 241, - 63, - 154, - 153, - 153, - 153, - 153, - 153, - 1, - 64, - 102, - 102, - 102, - 102, - 102, - 102, - 10, - 64, - 24, - 55, - 1 - ], [ - 1.1, - 2.2, - 3.3 - ]); + [3, 0, 0, 0, 1, 0, 0, 0, 204, 216, 0, 0, 3, 0, 0, 0, 12, 46, 1], + [1, 55500, 3], + ); + testNumbers( + [ + 3, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 172, + 128, + 94, + 239, + 12, + 0, + 0, + 0, + 3, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 24, + 47, + 1, + ], + [1, 55555555500, 3], + ); + testNumbers( + [3, 0, 0, 0, 0, 0, 192, 63, 0, 0, 32, 64, 0, 0, 96, 64, 12, 54, 1], + [1.5, 2.5, 3.5], + ); + testNumbers( + [ + 3, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 154, + 153, + 153, + 153, + 153, + 153, + 241, + 63, + 154, + 153, + 153, + 153, + 153, + 153, + 1, + 64, + 102, + 102, + 102, + 102, + 102, + 102, + 10, + 64, + 24, + 55, + 1, + ], + [1.1, 2.2, 3.3], + ); }); test('number vector, fixed type', () { testNumbers([1, 2, 2, 64, 1], [1, 2]); testNumbers([255, 255, 0, 1, 4, 65, 1], [-1, 256]); testNumbers([211, 255, 255, 255, 0, 232, 3, 0, 8, 66, 1], [-45, 256000]); - testNumbers([ - 211, - 255, - 255, - 255, - 255, - 255, - 255, - 255, - 255, - 255, - 255, - 255, - 255, - 255, - 255, - 127, - 16, - 67, - 1 - ], [ - -45, - 9223372036854775807 - ]); + testNumbers( + [ + 211, + 255, + 255, + 255, + 255, + 255, + 255, + 255, + 255, + 255, + 255, + 255, + 255, + 255, + 255, + 127, + 16, + 67, + 1, + ], + [-45, 9223372036854775807], + ); testNumbers([1, 2, 2, 68, 1], [1, 2]); testNumbers([1, 0, 0, 1, 4, 69, 1], [1, 256]); testNumbers([45, 0, 0, 0, 0, 232, 3, 0, 8, 70, 1], [45, 256000]); testNumbers([205, 204, 140, 63, 0, 0, 0, 192, 8, 74, 1], [1.1, -2]); - testNumbers([ - 154, - 153, - 153, - 153, - 153, - 153, - 241, - 63, - 0, - 0, - 0, - 0, - 0, - 0, - 112, - 192, - 16, - 75, - 1 - ], [ - 1.1, - -256 - ]); + testNumbers( + [ + 154, + 153, + 153, + 153, + 153, + 153, + 241, + 63, + 0, + 0, + 0, + 0, + 0, + 0, + 112, + 192, + 16, + 75, + 1, + ], + [1.1, -256], + ); - testNumbers([211, 255, 255, 255, 0, 232, 3, 0, 4, 0, 0, 0, 12, 78, 1], - [-45, 256000, 4]); + testNumbers( + [211, 255, 255, 255, 0, 232, 3, 0, 4, 0, 0, 0, 12, 78, 1], + [-45, 256000, 4], + ); - testNumbers([ - 211, - 255, - 255, - 255, - 255, - 255, - 255, - 255, - 255, - 255, - 255, - 255, - 255, - 255, - 255, - 127, - 4, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 9, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 32, - 91, - 1 - ], [ - -45, - 9223372036854775807, - 4, - 9 - ]); + testNumbers( + [ + 211, + 255, + 255, + 255, + 255, + 255, + 255, + 255, + 255, + 255, + 255, + 255, + 255, + 255, + 255, + 127, + 4, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 9, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 32, + 91, + 1, + ], + [-45, 9223372036854775807, 4, 9], + ); - testNumbers([ - 45, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 255, - 255, - 255, - 255, - 255, - 255, - 255, - 127, - 4, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 9, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 32, - 95, - 1 - ], [ - 45, - 9223372036854775807, - 4, - 9 - ]); + testNumbers( + [ + 45, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 255, + 255, + 255, + 255, + 255, + 255, + 255, + 127, + 4, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 9, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 32, + 95, + 1, + ], + [45, 9223372036854775807, 4, 9], + ); - testNumbers([ - 154, - 153, - 153, - 153, - 153, - 153, - 241, - 63, - 0, - 0, - 0, - 0, - 0, - 0, - 112, - 64, - 0, - 0, - 0, - 0, - 0, - 0, - 16, - 64, - 24, - 87, - 1 - ], [ - 1.1, - 256, - 4 - ]); + testNumbers( + [ + 154, + 153, + 153, + 153, + 153, + 153, + 241, + 63, + 0, + 0, + 0, + 0, + 0, + 0, + 112, + 64, + 0, + 0, + 0, + 0, + 0, + 0, + 16, + 64, + 24, + 87, + 1, + ], + [1.1, 256, 4], + ); - testNumbers([ - 154, - 153, - 153, - 153, - 153, - 153, - 241, - 63, - 0, - 0, - 0, - 0, - 0, - 0, - 112, - 64, - 0, - 0, - 0, - 0, - 0, - 0, - 16, - 64, - 0, - 0, - 0, - 0, - 0, - 0, - 34, - 64, - 32, - 99, - 1 - ], [ - 1.1, - 256, - 4, - 9 - ]); + testNumbers( + [ + 154, + 153, + 153, + 153, + 153, + 153, + 241, + 63, + 0, + 0, + 0, + 0, + 0, + 0, + 112, + 64, + 0, + 0, + 0, + 0, + 0, + 0, + 16, + 64, + 0, + 0, + 0, + 0, + 0, + 0, + 34, + 64, + 32, + 99, + 1, + ], + [1.1, 256, 4, 9], + ); }); test('string vector', () { - testStrings([ - 3, - 102, - 111, - 111, - 0, - 3, - 98, - 97, - 114, - 0, - 3, - 98, - 97, - 122, - 0, - 3, - 15, - 11, - 7, - 3, - 60, - 1 - ], [ - 'foo', - 'bar', - 'baz' - ]); - testStrings([ - 3, - 102, - 111, - 111, - 0, - 3, - 98, - 97, - 114, - 0, - 3, - 98, - 97, - 122, - 0, - 6, - 15, - 11, - 7, - 18, - 14, - 10, - 6, - 60, - 1 - ], [ - 'foo', - 'bar', - 'baz', - 'foo', - 'bar', - 'baz' - ]); + testStrings( + [ + 3, + 102, + 111, + 111, + 0, + 3, + 98, + 97, + 114, + 0, + 3, + 98, + 97, + 122, + 0, + 3, + 15, + 11, + 7, + 3, + 60, + 1, + ], + ['foo', 'bar', 'baz'], + ); + testStrings( + [ + 3, + 102, + 111, + 111, + 0, + 3, + 98, + 97, + 114, + 0, + 3, + 98, + 97, + 122, + 0, + 6, + 15, + 11, + 7, + 18, + 14, + 10, + 6, + 60, + 1, + ], + ['foo', 'bar', 'baz', 'foo', 'bar', 'baz'], + ); }); test('mixed vector', () { - var flx = Reference.fromBuffer(b([ - 3, - 102, - 111, - 111, - 0, - 0, - 0, - 0, - 5, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 15, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 1, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 251, - 255, - 255, - 255, - 255, - 255, - 255, - 255, - 205, - 204, - 204, - 204, - 204, - 204, - 244, - 63, - 1, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 20, - 4, - 4, - 15, - 104, - 45, - 43, - 1 - ])); + var flx = Reference.fromBuffer( + b([ + 3, + 102, + 111, + 111, + 0, + 0, + 0, + 0, + 5, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 15, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 251, + 255, + 255, + 255, + 255, + 255, + 255, + 255, + 205, + 204, + 204, + 204, + 204, + 204, + 244, + 63, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 20, + 4, + 4, + 15, + 104, + 45, + 43, + 1, + ]), + ); expect(flx.length, 5); expect(flx[0].stringValue, 'foo'); expect(flx[1].numValue, 1); @@ -554,7 +553,8 @@ void main() { }); test('two value map', () { var flx = Reference.fromBuffer( - b([0, 97, 0, 2, 4, 4, 2, 1, 2, 45, 12, 4, 4, 4, 36, 1])); + b([0, 97, 0, 2, 4, 4, 2, 1, 2, 45, 12, 4, 4, 4, 36, 1]), + ); expect(flx.length, 2); expect(flx['a'].numValue, 12); expect(flx[''].numValue, 45); @@ -578,55 +578,90 @@ void main() { expect(flx['address']['countryCode'].stringValue, 'XX'); expect( - () => flx['address']['country'].stringValue, - throwsA(predicate((dynamic e) => - e is ArgumentError && - e.message == - 'Key: [country] is not applicable on: //address of: ValueType.Map'))); + () => flx['address']['country'].stringValue, + throwsA( + predicate( + (dynamic e) => + e is ArgumentError && + e.message == + 'Key: [country] is not applicable on: //address of: ValueType.Map', + ), + ), + ); expect( - () => flx['address']['countryCode'][0], - throwsA(predicate((dynamic e) => - e is ArgumentError && - e.message == - 'Key: [0] is not applicable on: //address/countryCode of: ValueType.String'))); + () => flx['address']['countryCode'][0], + throwsA( + predicate( + (dynamic e) => + e is ArgumentError && + e.message == + 'Key: [0] is not applicable on: //address/countryCode of: ValueType.String', + ), + ), + ); expect( - () => flx[1], - throwsA(predicate((dynamic e) => - e is ArgumentError && - e.message == - 'Key: [1] is not applicable on: / of: ValueType.Map'))); + () => flx[1], + throwsA( + predicate( + (dynamic e) => + e is ArgumentError && + e.message == 'Key: [1] is not applicable on: / of: ValueType.Map', + ), + ), + ); expect( - () => flx['flags'][4], - throwsA(predicate((dynamic e) => - e is ArgumentError && - e.message == - 'Key: [4] is not applicable on: //flags of: ValueType.VectorBool length: 4'))); + () => flx['flags'][4], + throwsA( + predicate( + (dynamic e) => + e is ArgumentError && + e.message == + 'Key: [4] is not applicable on: //flags of: ValueType.VectorBool length: 4', + ), + ), + ); expect( - () => flx['flags'][-1], - throwsA(predicate((dynamic e) => - e is ArgumentError && - e.message == - 'Key: [-1] is not applicable on: //flags of: ValueType.VectorBool length: 4'))); + () => flx['flags'][-1], + throwsA( + predicate( + (dynamic e) => + e is ArgumentError && + e.message == + 'Key: [-1] is not applicable on: //flags of: ValueType.VectorBool length: 4', + ), + ), + ); }); test('complex map to json', () { var flx = complexMap(); - expect(flx.json, - '{"address":{"city":"Bla","countryCode":"XX","zip":"12345"},"age":35,"flags":[true,false,true,true],"name":"Maxim","weight":72.5}'); + expect( + flx.json, + '{"address":{"city":"Bla","countryCode":"XX","zip":"12345"},"age":35,"flags":[true,false,true,true],"name":"Maxim","weight":72.5}', + ); }); test('complex map iterators', () { var flx = complexMap(); - expect(flx.mapKeyIterable.map((e) => e).toList(), - ['address', 'age', 'flags', 'name', 'weight']); + expect(flx.mapKeyIterable.map((e) => e).toList(), [ + 'address', + 'age', + 'flags', + 'name', + 'weight', + ]); expect(flx.mapValueIterable.map((e) => e.json).toList(), [ flx['address'].json, flx['age'].json, flx['flags'].json, flx['name'].json, - flx['weight'].json + flx['weight'].json, + ]); + expect(flx['flags'].vectorIterable.map((e) => e.boolValue).toList(), [ + true, + false, + true, + true, ]); - expect(flx['flags'].vectorIterable.map((e) => e.boolValue).toList(), - [true, false, true, true]); }); test('bug where offest were stored as int instead of uint', () { @@ -790,11 +825,13 @@ void main() { 4, 16, 36, - 1 + 1, ]; var flx = Reference.fromBuffer(b(data)); - expect(flx.json, - '{"channels_in":64,"dilation_height_factor":1,"dilation_width_factor":1,"fused_activation_function":1,"pad_values":1,"padding":0,"stride_height":1,"stride_width":1}'); + expect( + flx.json, + '{"channels_in":64,"dilation_height_factor":1,"dilation_width_factor":1,"fused_activation_function":1,"pad_values":1,"padding":0,"stride_height":1,"stride_width":1}', + ); const object = { "channels_in": 64, "dilation_height_factor": 1, @@ -803,13 +840,15 @@ void main() { "pad_values": 1, "padding": 0, "stride_height": 1, - "stride_width": 1 + "stride_width": 1, }; var data1 = Builder.buildFromObject(object).asUint8List(); expect(data1.length, data.length); var flx1 = Reference.fromBuffer(b(data1)); - expect(flx1.json, - '{"channels_in":64,"dilation_height_factor":1,"dilation_width_factor":1,"fused_activation_function":1,"pad_values":1,"padding":0,"stride_height":1,"stride_width":1}'); + expect( + flx1.json, + '{"channels_in":64,"dilation_height_factor":1,"dilation_width_factor":1,"fused_activation_function":1,"pad_values":1,"padding":0,"stride_height":1,"stride_width":1}', + ); }); } @@ -835,157 +874,159 @@ void testStrings(List buffer, List numbers) { } Reference complexMap() { -// { -// "age": 35, -// "flags": [True, False, True, True], -// "weight": 72.5, -// "name": "Maxim", -// "address": { -// "city": "Bla", -// "zip": "12345", -// "countryCode": "XX", -// } -// } - return Reference.fromBuffer(b([ - 97, - 100, - 100, - 114, - 101, - 115, - 115, - 0, - 99, - 105, - 116, - 121, - 0, - 3, - 66, - 108, - 97, - 0, - 99, - 111, - 117, - 110, - 116, - 114, - 121, - 67, - 111, - 100, - 101, - 0, - 2, - 88, - 88, - 0, - 122, - 105, - 112, - 0, - 5, - 49, - 50, - 51, - 52, - 53, - 0, - 3, - 38, - 29, - 14, - 3, - 1, - 3, - 38, - 22, - 15, - 20, - 20, - 20, - 97, - 103, - 101, - 0, - 102, - 108, - 97, - 103, - 115, - 0, - 4, - 1, - 0, - 1, - 1, - 110, - 97, - 109, - 101, - 0, - 5, - 77, - 97, - 120, - 105, - 109, - 0, - 119, - 101, - 105, - 103, - 104, - 116, - 0, - 5, - 93, - 36, - 33, - 23, - 12, - 0, - 0, - 7, - 0, - 0, - 0, - 1, - 0, - 0, - 0, - 5, - 0, - 0, - 0, - 60, - 0, - 0, - 0, - 35, - 0, - 0, - 0, - 51, - 0, - 0, - 0, - 45, - 0, - 0, - 0, - 0, - 0, - 145, - 66, - 36, - 4, - 144, - 20, - 14, - 25, - 38, - 1 - ])); + // { + // "age": 35, + // "flags": [True, False, True, True], + // "weight": 72.5, + // "name": "Maxim", + // "address": { + // "city": "Bla", + // "zip": "12345", + // "countryCode": "XX", + // } + // } + return Reference.fromBuffer( + b([ + 97, + 100, + 100, + 114, + 101, + 115, + 115, + 0, + 99, + 105, + 116, + 121, + 0, + 3, + 66, + 108, + 97, + 0, + 99, + 111, + 117, + 110, + 116, + 114, + 121, + 67, + 111, + 100, + 101, + 0, + 2, + 88, + 88, + 0, + 122, + 105, + 112, + 0, + 5, + 49, + 50, + 51, + 52, + 53, + 0, + 3, + 38, + 29, + 14, + 3, + 1, + 3, + 38, + 22, + 15, + 20, + 20, + 20, + 97, + 103, + 101, + 0, + 102, + 108, + 97, + 103, + 115, + 0, + 4, + 1, + 0, + 1, + 1, + 110, + 97, + 109, + 101, + 0, + 5, + 77, + 97, + 120, + 105, + 109, + 0, + 119, + 101, + 105, + 103, + 104, + 116, + 0, + 5, + 93, + 36, + 33, + 23, + 12, + 0, + 0, + 7, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 5, + 0, + 0, + 0, + 60, + 0, + 0, + 0, + 35, + 0, + 0, + 0, + 51, + 0, + 0, + 0, + 45, + 0, + 0, + 0, + 0, + 0, + 145, + 66, + 36, + 4, + 144, + 20, + 14, + 25, + 38, + 1, + ]), + ); } diff --git a/dart/test/flex_types_test.dart b/dart/test/flex_types_test.dart index 76ce0704983..7ed1f2ab1c1 100644 --- a/dart/test/flex_types_test.dart +++ b/dart/test/flex_types_test.dart @@ -48,116 +48,210 @@ void main() { expect(ValueTypeUtils.isFixedTypedVector(ValueType.VectorInt), isFalse); }); test('to typed vector', () { - expect(ValueTypeUtils.toTypedVector(ValueType.Int, 0), - equals(ValueType.VectorInt)); - expect(ValueTypeUtils.toTypedVector(ValueType.UInt, 0), - equals(ValueType.VectorUInt)); - expect(ValueTypeUtils.toTypedVector(ValueType.Bool, 0), - equals(ValueType.VectorBool)); - expect(ValueTypeUtils.toTypedVector(ValueType.Float, 0), - equals(ValueType.VectorFloat)); - expect(ValueTypeUtils.toTypedVector(ValueType.Key, 0), - equals(ValueType.VectorKey)); - expect(ValueTypeUtils.toTypedVector(ValueType.String, 0), - equals(ValueType.VectorString)); + expect( + ValueTypeUtils.toTypedVector(ValueType.Int, 0), + equals(ValueType.VectorInt), + ); + expect( + ValueTypeUtils.toTypedVector(ValueType.UInt, 0), + equals(ValueType.VectorUInt), + ); + expect( + ValueTypeUtils.toTypedVector(ValueType.Bool, 0), + equals(ValueType.VectorBool), + ); + expect( + ValueTypeUtils.toTypedVector(ValueType.Float, 0), + equals(ValueType.VectorFloat), + ); + expect( + ValueTypeUtils.toTypedVector(ValueType.Key, 0), + equals(ValueType.VectorKey), + ); + expect( + ValueTypeUtils.toTypedVector(ValueType.String, 0), + equals(ValueType.VectorString), + ); - expect(ValueTypeUtils.toTypedVector(ValueType.Int, 2), - equals(ValueType.VectorInt2)); - expect(ValueTypeUtils.toTypedVector(ValueType.UInt, 2), - equals(ValueType.VectorUInt2)); - expect(ValueTypeUtils.toTypedVector(ValueType.Float, 2), - equals(ValueType.VectorFloat2)); + expect( + ValueTypeUtils.toTypedVector(ValueType.Int, 2), + equals(ValueType.VectorInt2), + ); + expect( + ValueTypeUtils.toTypedVector(ValueType.UInt, 2), + equals(ValueType.VectorUInt2), + ); + expect( + ValueTypeUtils.toTypedVector(ValueType.Float, 2), + equals(ValueType.VectorFloat2), + ); - expect(ValueTypeUtils.toTypedVector(ValueType.Int, 3), - equals(ValueType.VectorInt3)); - expect(ValueTypeUtils.toTypedVector(ValueType.UInt, 3), - equals(ValueType.VectorUInt3)); - expect(ValueTypeUtils.toTypedVector(ValueType.Float, 3), - equals(ValueType.VectorFloat3)); + expect( + ValueTypeUtils.toTypedVector(ValueType.Int, 3), + equals(ValueType.VectorInt3), + ); + expect( + ValueTypeUtils.toTypedVector(ValueType.UInt, 3), + equals(ValueType.VectorUInt3), + ); + expect( + ValueTypeUtils.toTypedVector(ValueType.Float, 3), + equals(ValueType.VectorFloat3), + ); - expect(ValueTypeUtils.toTypedVector(ValueType.Int, 4), - equals(ValueType.VectorInt4)); - expect(ValueTypeUtils.toTypedVector(ValueType.UInt, 4), - equals(ValueType.VectorUInt4)); - expect(ValueTypeUtils.toTypedVector(ValueType.Float, 4), - equals(ValueType.VectorFloat4)); + expect( + ValueTypeUtils.toTypedVector(ValueType.Int, 4), + equals(ValueType.VectorInt4), + ); + expect( + ValueTypeUtils.toTypedVector(ValueType.UInt, 4), + equals(ValueType.VectorUInt4), + ); + expect( + ValueTypeUtils.toTypedVector(ValueType.Float, 4), + equals(ValueType.VectorFloat4), + ); }); test('typed vector element type', () { - expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorInt), - equals(ValueType.Int)); - expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorUInt), - equals(ValueType.UInt)); - expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorFloat), - equals(ValueType.Float)); - expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorString), - equals(ValueType.String)); - expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorKey), - equals(ValueType.Key)); - expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorBool), - equals(ValueType.Bool)); + expect( + ValueTypeUtils.typedVectorElementType(ValueType.VectorInt), + equals(ValueType.Int), + ); + expect( + ValueTypeUtils.typedVectorElementType(ValueType.VectorUInt), + equals(ValueType.UInt), + ); + expect( + ValueTypeUtils.typedVectorElementType(ValueType.VectorFloat), + equals(ValueType.Float), + ); + expect( + ValueTypeUtils.typedVectorElementType(ValueType.VectorString), + equals(ValueType.String), + ); + expect( + ValueTypeUtils.typedVectorElementType(ValueType.VectorKey), + equals(ValueType.Key), + ); + expect( + ValueTypeUtils.typedVectorElementType(ValueType.VectorBool), + equals(ValueType.Bool), + ); }); test('fixed typed vector element type', () { - expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorInt2), - equals(ValueType.Int)); - expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorInt3), - equals(ValueType.Int)); - expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorInt4), - equals(ValueType.Int)); + expect( + ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorInt2), + equals(ValueType.Int), + ); + expect( + ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorInt3), + equals(ValueType.Int), + ); + expect( + ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorInt4), + equals(ValueType.Int), + ); - expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorUInt2), - equals(ValueType.UInt)); - expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorUInt3), - equals(ValueType.UInt)); - expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorUInt4), - equals(ValueType.UInt)); + expect( + ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorUInt2), + equals(ValueType.UInt), + ); + expect( + ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorUInt3), + equals(ValueType.UInt), + ); + expect( + ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorUInt4), + equals(ValueType.UInt), + ); - expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorFloat2), - equals(ValueType.Float)); - expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorFloat3), - equals(ValueType.Float)); - expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorFloat4), - equals(ValueType.Float)); + expect( + ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorFloat2), + equals(ValueType.Float), + ); + expect( + ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorFloat3), + equals(ValueType.Float), + ); + expect( + ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorFloat4), + equals(ValueType.Float), + ); }); test('fixed typed vector element size', () { - expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorInt2), - equals(2)); - expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorInt3), - equals(3)); - expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorInt4), - equals(4)); + expect( + ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorInt2), + equals(2), + ); + expect( + ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorInt3), + equals(3), + ); + expect( + ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorInt4), + equals(4), + ); - expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorUInt2), - equals(2)); - expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorUInt3), - equals(3)); - expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorUInt4), - equals(4)); + expect( + ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorUInt2), + equals(2), + ); + expect( + ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorUInt3), + equals(3), + ); + expect( + ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorUInt4), + equals(4), + ); - expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorFloat2), - equals(2)); - expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorFloat3), - equals(3)); - expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorFloat4), - equals(4)); + expect( + ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorFloat2), + equals(2), + ); + expect( + ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorFloat3), + equals(3), + ); + expect( + ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorFloat4), + equals(4), + ); }); test('packed type', () { expect( - ValueTypeUtils.packedType(ValueType.Null, BitWidth.width8), equals(0)); + ValueTypeUtils.packedType(ValueType.Null, BitWidth.width8), + equals(0), + ); expect( - ValueTypeUtils.packedType(ValueType.Null, BitWidth.width16), equals(1)); + ValueTypeUtils.packedType(ValueType.Null, BitWidth.width16), + equals(1), + ); expect( - ValueTypeUtils.packedType(ValueType.Null, BitWidth.width32), equals(2)); + ValueTypeUtils.packedType(ValueType.Null, BitWidth.width32), + equals(2), + ); expect( - ValueTypeUtils.packedType(ValueType.Null, BitWidth.width64), equals(3)); + ValueTypeUtils.packedType(ValueType.Null, BitWidth.width64), + equals(3), + ); expect( - ValueTypeUtils.packedType(ValueType.Int, BitWidth.width8), equals(4)); + ValueTypeUtils.packedType(ValueType.Int, BitWidth.width8), + equals(4), + ); expect( - ValueTypeUtils.packedType(ValueType.Int, BitWidth.width16), equals(5)); + ValueTypeUtils.packedType(ValueType.Int, BitWidth.width16), + equals(5), + ); expect( - ValueTypeUtils.packedType(ValueType.Int, BitWidth.width32), equals(6)); + ValueTypeUtils.packedType(ValueType.Int, BitWidth.width32), + equals(6), + ); expect( - ValueTypeUtils.packedType(ValueType.Int, BitWidth.width64), equals(7)); + ValueTypeUtils.packedType(ValueType.Int, BitWidth.width64), + equals(7), + ); }); test('bit width', () { expect(BitWidthUtil.width(0), BitWidth.width8); diff --git a/dart/test/include_test1_generated.dart b/dart/test/include_test1_generated.dart index c04bf6b2d22..2309e45722c 100644 --- a/dart/test/include_test1_generated.dart +++ b/dart/test/include_test1_generated.dart @@ -2,10 +2,11 @@ // ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable, constant_identifier_names import 'dart:typed_data' show Uint8List; -import 'package:flat_buffers/flat_buffers.dart' as fb; +import 'package:flat_buffers/flat_buffers.dart' as fb; -import './include_test2_my_game.other_name_space_generated.dart' as my_game_other_name_space; +import './include_test2_my_game.other_name_space_generated.dart' + as my_game_other_name_space; class TableA { TableA._(this._bc, this._bcOffset); @@ -19,15 +20,17 @@ class TableA { final fb.BufferContext _bc; final int _bcOffset; - my_game_other_name_space.TableB? get b => my_game_other_name_space.TableB.reader.vTableGetNullable(_bc, _bcOffset, 4); + my_game_other_name_space.TableB? get b => my_game_other_name_space + .TableB + .reader + .vTableGetNullable(_bc, _bcOffset, 4); @override String toString() { return 'TableA{b: ${b}}'; } - TableAT unpack() => TableAT( - b: b?.unpack()); + TableAT unpack() => TableAT(b: b?.unpack()); static int pack(fb.Builder fbBuilder, TableAT? object) { if (object == null) return 0; @@ -38,8 +41,7 @@ class TableA { class TableAT implements fb.Packable { my_game_other_name_space.TableBT? b; - TableAT({ - this.b}); + TableAT({this.b}); @override int pack(fb.Builder fbBuilder) { @@ -59,8 +61,7 @@ class _TableAReader extends fb.TableReader { const _TableAReader(); @override - TableA createObject(fb.BufferContext bc, int offset) => - TableA._(bc, offset); + TableA createObject(fb.BufferContext bc, int offset) => TableA._(bc, offset); } class TableABuilder { @@ -85,10 +86,8 @@ class TableABuilder { class TableAObjectBuilder extends fb.ObjectBuilder { final my_game_other_name_space.TableBObjectBuilder? _b; - TableAObjectBuilder({ - my_game_other_name_space.TableBObjectBuilder? b, - }) - : _b = b; + TableAObjectBuilder({my_game_other_name_space.TableBObjectBuilder? b}) + : _b = b; /// Finish building, and store into the [fbBuilder]. @override diff --git a/dart/test/include_test2_my_game.other_name_space_generated.dart b/dart/test/include_test2_my_game.other_name_space_generated.dart index 365ed3ceb5d..975622b8fb4 100644 --- a/dart/test/include_test2_my_game.other_name_space_generated.dart +++ b/dart/test/include_test2_my_game.other_name_space_generated.dart @@ -4,8 +4,8 @@ library my_game.other_name_space; import 'dart:typed_data' show Uint8List; -import 'package:flat_buffers/flat_buffers.dart' as fb; +import 'package:flat_buffers/flat_buffers.dart' as fb; import './include_test1_generated.dart'; @@ -17,8 +17,10 @@ enum FromInclude { factory FromInclude.fromValue(int value) { switch (value) { - case 0: return FromInclude.IncludeVal; - default: throw StateError('Invalid value $value for bit flag enum'); + case 0: + return FromInclude.IncludeVal; + default: + throw StateError('Invalid value $value for bit flag enum'); } } @@ -56,8 +58,7 @@ class Unused { return 'Unused{a: ${a}}'; } - UnusedT unpack() => UnusedT( - a: a); + UnusedT unpack() => UnusedT(a: a); static int pack(fb.Builder fbBuilder, UnusedT? object) { if (object == null) return 0; @@ -68,8 +69,7 @@ class Unused { class UnusedT implements fb.Packable { int a; - UnusedT({ - required this.a}); + UnusedT({required this.a}); @override int pack(fb.Builder fbBuilder) { @@ -90,8 +90,7 @@ class _UnusedReader extends fb.StructReader { int get size => 4; @override - Unused createObject(fb.BufferContext bc, int offset) => - Unused._(bc, offset); + Unused createObject(fb.BufferContext bc, int offset) => Unused._(bc, offset); } class UnusedBuilder { @@ -103,16 +102,12 @@ class UnusedBuilder { fbBuilder.putInt32(a); return fbBuilder.offset; } - } class UnusedObjectBuilder extends fb.ObjectBuilder { final int _a; - UnusedObjectBuilder({ - required int a, - }) - : _a = a; + UnusedObjectBuilder({required int a}) : _a = a; /// Finish building, and store into the [fbBuilder]. @override @@ -129,6 +124,7 @@ class UnusedObjectBuilder extends fb.ObjectBuilder { return fbBuilder.buffer; } } + class TableB { TableB._(this._bc, this._bcOffset); factory TableB(List bytes) { @@ -148,8 +144,7 @@ class TableB { return 'TableB{a: ${a}}'; } - TableBT unpack() => TableBT( - a: a?.unpack()); + TableBT unpack() => TableBT(a: a?.unpack()); static int pack(fb.Builder fbBuilder, TableBT? object) { if (object == null) return 0; @@ -160,8 +155,7 @@ class TableB { class TableBT implements fb.Packable { TableAT? a; - TableBT({ - this.a}); + TableBT({this.a}); @override int pack(fb.Builder fbBuilder) { @@ -181,8 +175,7 @@ class _TableBReader extends fb.TableReader { const _TableBReader(); @override - TableB createObject(fb.BufferContext bc, int offset) => - TableB._(bc, offset); + TableB createObject(fb.BufferContext bc, int offset) => TableB._(bc, offset); } class TableBBuilder { @@ -207,10 +200,7 @@ class TableBBuilder { class TableBObjectBuilder extends fb.ObjectBuilder { final TableAObjectBuilder? _a; - TableBObjectBuilder({ - TableAObjectBuilder? a, - }) - : _a = a; + TableBObjectBuilder({TableAObjectBuilder? a}) : _a = a; /// Finish building, and store into the [fbBuilder]. @override diff --git a/dart/test/monster_test_my_game.example2_generated.dart b/dart/test/monster_test_my_game.example2_generated.dart index c266f9ce72b..8f7893fcd17 100644 --- a/dart/test/monster_test_my_game.example2_generated.dart +++ b/dart/test/monster_test_my_game.example2_generated.dart @@ -4,12 +4,12 @@ library my_game.example2; import 'dart:typed_data' show Uint8List; -import 'package:flat_buffers/flat_buffers.dart' as fb; -import './monster_test_my_game_generated.dart' as my_game; -import './monster_test_my_game.example_generated.dart' as my_game_example; +import 'package:flat_buffers/flat_buffers.dart' as fb; import './include_test1_generated.dart'; +import './monster_test_my_game.example_generated.dart' as my_game_example; +import './monster_test_my_game_generated.dart' as my_game; class Monster { Monster._(this._bc, this._bcOffset); @@ -23,7 +23,6 @@ class Monster { final fb.BufferContext _bc; final int _bcOffset; - @override String toString() { return 'Monster{}'; @@ -54,12 +53,11 @@ class _MonsterReader extends fb.TableReader { const _MonsterReader(); @override - Monster createObject(fb.BufferContext bc, int offset) => - Monster._(bc, offset); + Monster createObject(fb.BufferContext bc, int offset) => + Monster._(bc, offset); } class MonsterObjectBuilder extends fb.ObjectBuilder { - MonsterObjectBuilder(); /// Finish building, and store into the [fbBuilder]. diff --git a/dart/test/monster_test_my_game.example_generated.dart b/dart/test/monster_test_my_game.example_generated.dart index 5554c4c4b1d..7be3afa8906 100644 --- a/dart/test/monster_test_my_game.example_generated.dart +++ b/dart/test/monster_test_my_game.example_generated.dart @@ -4,12 +4,12 @@ library my_game.example; import 'dart:typed_data' show Uint8List; -import 'package:flat_buffers/flat_buffers.dart' as fb; -import './monster_test_my_game_generated.dart' as my_game; -import './monster_test_my_game.example2_generated.dart' as my_game_example2; +import 'package:flat_buffers/flat_buffers.dart' as fb; import './include_test1_generated.dart'; +import './monster_test_my_game.example2_generated.dart' as my_game_example2; +import './monster_test_my_game_generated.dart' as my_game; /// Composite components of Monster color. enum Color { @@ -23,11 +23,16 @@ enum Color { factory Color.fromValue(int value) { switch (value) { - case 1: return Color.Red; - case 2: return Color.Green; - case 8: return Color.Blue; - case 0: return Color._default; - default: throw StateError('Invalid value $value for bit flag enum'); + case 1: + return Color.Red; + case 2: + return Color.Green; + case 8: + return Color.Blue; + case 0: + return Color._default; + default: + throw StateError('Invalid value $value for bit flag enum'); } } @@ -59,11 +64,16 @@ enum Race { factory Race.fromValue(int value) { switch (value) { - case -1: return Race.None; - case 0: return Race.Human; - case 1: return Race.Dwarf; - case 2: return Race.Elf; - default: throw StateError('Invalid value $value for bit flag enum'); + case -1: + return Race.None; + case 0: + return Race.Human; + case 1: + return Race.Dwarf; + case 2: + return Race.Elf; + default: + throw StateError('Invalid value $value for bit flag enum'); } } @@ -97,11 +107,16 @@ enum LongEnum { factory LongEnum.fromValue(int value) { switch (value) { - case 2: return LongEnum.LongOne; - case 4: return LongEnum.LongTwo; - case 1099511627776: return LongEnum.LongBig; - case 0: return LongEnum._default; - default: throw StateError('Invalid value $value for bit flag enum'); + case 2: + return LongEnum.LongOne; + case 4: + return LongEnum.LongTwo; + case 1099511627776: + return LongEnum.LongBig; + case 0: + return LongEnum._default; + default: + throw StateError('Invalid value $value for bit flag enum'); } } @@ -133,11 +148,16 @@ enum AnyTypeId { factory AnyTypeId.fromValue(int value) { switch (value) { - case 0: return AnyTypeId.NONE; - case 1: return AnyTypeId.Monster; - case 2: return AnyTypeId.TestSimpleTableWithEnum; - case 3: return AnyTypeId.MyGame_Example2_Monster; - default: throw StateError('Invalid value $value for bit flag enum'); + case 0: + return AnyTypeId.NONE; + case 1: + return AnyTypeId.Monster; + case 2: + return AnyTypeId.TestSimpleTableWithEnum; + case 3: + return AnyTypeId.MyGame_Example2_Monster; + default: + throw StateError('Invalid value $value for bit flag enum'); } } @@ -171,11 +191,16 @@ enum AnyUniqueAliasesTypeId { factory AnyUniqueAliasesTypeId.fromValue(int value) { switch (value) { - case 0: return AnyUniqueAliasesTypeId.NONE; - case 1: return AnyUniqueAliasesTypeId.M; - case 2: return AnyUniqueAliasesTypeId.TS; - case 3: return AnyUniqueAliasesTypeId.M2; - default: throw StateError('Invalid value $value for bit flag enum'); + case 0: + return AnyUniqueAliasesTypeId.NONE; + case 1: + return AnyUniqueAliasesTypeId.M; + case 2: + return AnyUniqueAliasesTypeId.TS; + case 3: + return AnyUniqueAliasesTypeId.M2; + default: + throw StateError('Invalid value $value for bit flag enum'); } } @@ -184,7 +209,8 @@ enum AnyUniqueAliasesTypeId { static const int minValue = 0; static const int maxValue = 3; - static const fb.Reader reader = _AnyUniqueAliasesTypeIdReader(); + static const fb.Reader reader = + _AnyUniqueAliasesTypeIdReader(); } class _AnyUniqueAliasesTypeIdReader extends fb.Reader { @@ -209,11 +235,16 @@ enum AnyAmbiguousAliasesTypeId { factory AnyAmbiguousAliasesTypeId.fromValue(int value) { switch (value) { - case 0: return AnyAmbiguousAliasesTypeId.NONE; - case 1: return AnyAmbiguousAliasesTypeId.M1; - case 2: return AnyAmbiguousAliasesTypeId.M2; - case 3: return AnyAmbiguousAliasesTypeId.M3; - default: throw StateError('Invalid value $value for bit flag enum'); + case 0: + return AnyAmbiguousAliasesTypeId.NONE; + case 1: + return AnyAmbiguousAliasesTypeId.M1; + case 2: + return AnyAmbiguousAliasesTypeId.M2; + case 3: + return AnyAmbiguousAliasesTypeId.M3; + default: + throw StateError('Invalid value $value for bit flag enum'); } } @@ -222,10 +253,12 @@ enum AnyAmbiguousAliasesTypeId { static const int minValue = 0; static const int maxValue = 3; - static const fb.Reader reader = _AnyAmbiguousAliasesTypeIdReader(); + static const fb.Reader reader = + _AnyAmbiguousAliasesTypeIdReader(); } -class _AnyAmbiguousAliasesTypeIdReader extends fb.Reader { +class _AnyAmbiguousAliasesTypeIdReader + extends fb.Reader { const _AnyAmbiguousAliasesTypeIdReader(); @override @@ -233,7 +266,9 @@ class _AnyAmbiguousAliasesTypeIdReader extends fb.Reader - AnyAmbiguousAliasesTypeId.fromValue(const fb.Uint8Reader().read(bc, offset)); + AnyAmbiguousAliasesTypeId.fromValue( + const fb.Uint8Reader().read(bc, offset), + ); } class Test { @@ -252,9 +287,7 @@ class Test { return 'Test{a: ${a}, b: ${b}}'; } - TestT unpack() => TestT( - a: a, - b: b); + TestT unpack() => TestT(a: a, b: b); static int pack(fb.Builder fbBuilder, TestT? object) { if (object == null) return 0; @@ -266,9 +299,7 @@ class TestT implements fb.Packable { int a; int b; - TestT({ - required this.a, - required this.b}); + TestT({required this.a, required this.b}); @override int pack(fb.Builder fbBuilder) { @@ -291,8 +322,7 @@ class _TestReader extends fb.StructReader { int get size => 4; @override - Test createObject(fb.BufferContext bc, int offset) => - Test._(bc, offset); + Test createObject(fb.BufferContext bc, int offset) => Test._(bc, offset); } class TestBuilder { @@ -306,19 +336,13 @@ class TestBuilder { fbBuilder.putInt16(a); return fbBuilder.offset; } - } class TestObjectBuilder extends fb.ObjectBuilder { final int _a; final int _b; - TestObjectBuilder({ - required int a, - required int b, - }) - : _a = a, - _b = b; + TestObjectBuilder({required int a, required int b}) : _a = a, _b = b; /// Finish building, and store into the [fbBuilder]. @override @@ -337,6 +361,7 @@ class TestObjectBuilder extends fb.ObjectBuilder { return fbBuilder.buffer; } } + class TestSimpleTableWithEnum { TestSimpleTableWithEnum._(this._bc, this._bcOffset); factory TestSimpleTableWithEnum(List bytes) { @@ -344,20 +369,21 @@ class TestSimpleTableWithEnum { return reader.read(rootRef, 0); } - static const fb.Reader reader = _TestSimpleTableWithEnumReader(); + static const fb.Reader reader = + _TestSimpleTableWithEnumReader(); final fb.BufferContext _bc; final int _bcOffset; - Color get color => Color.fromValue(const fb.Uint8Reader().vTableGet(_bc, _bcOffset, 4, 2)); + Color get color => + Color.fromValue(const fb.Uint8Reader().vTableGet(_bc, _bcOffset, 4, 2)); @override String toString() { return 'TestSimpleTableWithEnum{color: ${color}}'; } - TestSimpleTableWithEnumT unpack() => TestSimpleTableWithEnumT( - color: color); + TestSimpleTableWithEnumT unpack() => TestSimpleTableWithEnumT(color: color); static int pack(fb.Builder fbBuilder, TestSimpleTableWithEnumT? object) { if (object == null) return 0; @@ -368,8 +394,7 @@ class TestSimpleTableWithEnum { class TestSimpleTableWithEnumT implements fb.Packable { Color color; - TestSimpleTableWithEnumT({ - this.color = Color.Green}); + TestSimpleTableWithEnumT({this.color = Color.Green}); @override int pack(fb.Builder fbBuilder) { @@ -384,12 +409,13 @@ class TestSimpleTableWithEnumT implements fb.Packable { } } -class _TestSimpleTableWithEnumReader extends fb.TableReader { +class _TestSimpleTableWithEnumReader + extends fb.TableReader { const _TestSimpleTableWithEnumReader(); @override - TestSimpleTableWithEnum createObject(fb.BufferContext bc, int offset) => - TestSimpleTableWithEnum._(bc, offset); + TestSimpleTableWithEnum createObject(fb.BufferContext bc, int offset) => + TestSimpleTableWithEnum._(bc, offset); } class TestSimpleTableWithEnumBuilder { @@ -414,10 +440,7 @@ class TestSimpleTableWithEnumBuilder { class TestSimpleTableWithEnumObjectBuilder extends fb.ObjectBuilder { final Color? _color; - TestSimpleTableWithEnumObjectBuilder({ - Color? color, - }) - : _color = color; + TestSimpleTableWithEnumObjectBuilder({Color? color}) : _color = color; /// Finish building, and store into the [fbBuilder]. @override @@ -435,6 +458,7 @@ class TestSimpleTableWithEnumObjectBuilder extends fb.ObjectBuilder { return fbBuilder.buffer; } } + class Vec3 { Vec3._(this._bc, this._bcOffset); @@ -447,7 +471,8 @@ class Vec3 { double get y => const fb.Float32Reader().read(_bc, _bcOffset + 4); double get z => const fb.Float32Reader().read(_bc, _bcOffset + 8); double get test1 => const fb.Float64Reader().read(_bc, _bcOffset + 16); - Color get test2 => Color.fromValue(const fb.Uint8Reader().read(_bc, _bcOffset + 24)); + Color get test2 => + Color.fromValue(const fb.Uint8Reader().read(_bc, _bcOffset + 24)); Test get test3 => Test.reader.read(_bc, _bcOffset + 26); @override @@ -456,12 +481,13 @@ class Vec3 { } Vec3T unpack() => Vec3T( - x: x, - y: y, - z: z, - test1: test1, - test2: test2, - test3: test3.unpack()); + x: x, + y: y, + z: z, + test1: test1, + test2: test2, + test3: test3.unpack(), + ); static int pack(fb.Builder fbBuilder, Vec3T? object) { if (object == null) return 0; @@ -478,12 +504,13 @@ class Vec3T implements fb.Packable { TestT test3; Vec3T({ - required this.x, - required this.y, - required this.z, - required this.test1, - required this.test2, - required this.test3}); + required this.x, + required this.y, + required this.z, + required this.test1, + required this.test2, + required this.test3, + }); @override int pack(fb.Builder fbBuilder) { @@ -512,8 +539,7 @@ class _Vec3Reader extends fb.StructReader { int get size => 32; @override - Vec3 createObject(fb.BufferContext bc, int offset) => - Vec3._(bc, offset); + Vec3 createObject(fb.BufferContext bc, int offset) => Vec3._(bc, offset); } class Vec3Builder { @@ -521,7 +547,14 @@ class Vec3Builder { final fb.Builder fbBuilder; - int finish(double x, double y, double z, double test1, Color test2, fb.StructBuilder test3) { + int finish( + double x, + double y, + double z, + double test1, + Color test2, + fb.StructBuilder test3, + ) { fbBuilder.pad(2); test3(); fbBuilder.pad(1); @@ -533,7 +566,6 @@ class Vec3Builder { fbBuilder.putFloat32(x); return fbBuilder.offset; } - } class Vec3ObjectBuilder extends fb.ObjectBuilder { @@ -551,13 +583,12 @@ class Vec3ObjectBuilder extends fb.ObjectBuilder { required double test1, required Color test2, required TestObjectBuilder test3, - }) - : _x = x, - _y = y, - _z = z, - _test1 = test1, - _test2 = test2, - _test3 = test3; + }) : _x = x, + _y = y, + _z = z, + _test1 = test1, + _test2 = test2, + _test3 = test3; /// Finish building, and store into the [fbBuilder]. @override @@ -582,6 +613,7 @@ class Vec3ObjectBuilder extends fb.ObjectBuilder { return fbBuilder.buffer; } } + class Ability { Ability._(this._bc, this._bcOffset); @@ -598,9 +630,7 @@ class Ability { return 'Ability{id: ${id}, distance: ${distance}}'; } - AbilityT unpack() => AbilityT( - id: id, - distance: distance); + AbilityT unpack() => AbilityT(id: id, distance: distance); static int pack(fb.Builder fbBuilder, AbilityT? object) { if (object == null) return 0; @@ -612,9 +642,7 @@ class AbilityT implements fb.Packable { int id; int distance; - AbilityT({ - required this.id, - required this.distance}); + AbilityT({required this.id, required this.distance}); @override int pack(fb.Builder fbBuilder) { @@ -636,8 +664,8 @@ class _AbilityReader extends fb.StructReader { int get size => 8; @override - Ability createObject(fb.BufferContext bc, int offset) => - Ability._(bc, offset); + Ability createObject(fb.BufferContext bc, int offset) => + Ability._(bc, offset); } class AbilityBuilder { @@ -650,19 +678,15 @@ class AbilityBuilder { fbBuilder.putUint32(id); return fbBuilder.offset; } - } class AbilityObjectBuilder extends fb.ObjectBuilder { final int _id; final int _distance; - AbilityObjectBuilder({ - required int id, - required int distance, - }) - : _id = id, - _distance = distance; + AbilityObjectBuilder({required int id, required int distance}) + : _id = id, + _distance = distance; /// Finish building, and store into the [fbBuilder]. @override @@ -680,6 +704,7 @@ class AbilityObjectBuilder extends fb.ObjectBuilder { return fbBuilder.buffer; } } + class StructOfStructs { StructOfStructs._(this._bc, this._bcOffset); @@ -697,10 +722,8 @@ class StructOfStructs { return 'StructOfStructs{a: ${a}, b: ${b}, c: ${c}}'; } - StructOfStructsT unpack() => StructOfStructsT( - a: a.unpack(), - b: b.unpack(), - c: c.unpack()); + StructOfStructsT unpack() => + StructOfStructsT(a: a.unpack(), b: b.unpack(), c: c.unpack()); static int pack(fb.Builder fbBuilder, StructOfStructsT? object) { if (object == null) return 0; @@ -713,10 +736,7 @@ class StructOfStructsT implements fb.Packable { TestT b; AbilityT c; - StructOfStructsT({ - required this.a, - required this.b, - required this.c}); + StructOfStructsT({required this.a, required this.b, required this.c}); @override int pack(fb.Builder fbBuilder) { @@ -739,8 +759,8 @@ class _StructOfStructsReader extends fb.StructReader { int get size => 20; @override - StructOfStructs createObject(fb.BufferContext bc, int offset) => - StructOfStructs._(bc, offset); + StructOfStructs createObject(fb.BufferContext bc, int offset) => + StructOfStructs._(bc, offset); } class StructOfStructsBuilder { @@ -754,7 +774,6 @@ class StructOfStructsBuilder { a(); return fbBuilder.offset; } - } class StructOfStructsObjectBuilder extends fb.ObjectBuilder { @@ -766,10 +785,9 @@ class StructOfStructsObjectBuilder extends fb.ObjectBuilder { required AbilityObjectBuilder a, required TestObjectBuilder b, required AbilityObjectBuilder c, - }) - : _a = a, - _b = b, - _c = c; + }) : _a = a, + _b = b, + _c = c; /// Finish building, and store into the [fbBuilder]. @override @@ -788,10 +806,12 @@ class StructOfStructsObjectBuilder extends fb.ObjectBuilder { return fbBuilder.buffer; } } + class StructOfStructsOfStructs { StructOfStructsOfStructs._(this._bc, this._bcOffset); - static const fb.Reader reader = _StructOfStructsOfStructsReader(); + static const fb.Reader reader = + _StructOfStructsOfStructsReader(); final fb.BufferContext _bc; final int _bcOffset; @@ -803,8 +823,8 @@ class StructOfStructsOfStructs { return 'StructOfStructsOfStructs{a: ${a}}'; } - StructOfStructsOfStructsT unpack() => StructOfStructsOfStructsT( - a: a.unpack()); + StructOfStructsOfStructsT unpack() => + StructOfStructsOfStructsT(a: a.unpack()); static int pack(fb.Builder fbBuilder, StructOfStructsOfStructsT? object) { if (object == null) return 0; @@ -815,8 +835,7 @@ class StructOfStructsOfStructs { class StructOfStructsOfStructsT implements fb.Packable { StructOfStructsT a; - StructOfStructsOfStructsT({ - required this.a}); + StructOfStructsOfStructsT({required this.a}); @override int pack(fb.Builder fbBuilder) { @@ -830,15 +849,16 @@ class StructOfStructsOfStructsT implements fb.Packable { } } -class _StructOfStructsOfStructsReader extends fb.StructReader { +class _StructOfStructsOfStructsReader + extends fb.StructReader { const _StructOfStructsOfStructsReader(); @override int get size => 20; @override - StructOfStructsOfStructs createObject(fb.BufferContext bc, int offset) => - StructOfStructsOfStructs._(bc, offset); + StructOfStructsOfStructs createObject(fb.BufferContext bc, int offset) => + StructOfStructsOfStructs._(bc, offset); } class StructOfStructsOfStructsBuilder { @@ -850,7 +870,6 @@ class StructOfStructsOfStructsBuilder { a(); return fbBuilder.offset; } - } class StructOfStructsOfStructsObjectBuilder extends fb.ObjectBuilder { @@ -858,8 +877,7 @@ class StructOfStructsOfStructsObjectBuilder extends fb.ObjectBuilder { StructOfStructsOfStructsObjectBuilder({ required StructOfStructsObjectBuilder a, - }) - : _a = a; + }) : _a = a; /// Finish building, and store into the [fbBuilder]. @override @@ -876,6 +894,7 @@ class StructOfStructsOfStructsObjectBuilder extends fb.ObjectBuilder { return fbBuilder.buffer; } } + class Stat { Stat._(this._bc, this._bcOffset); factory Stat(List bytes) { @@ -888,7 +907,8 @@ class Stat { final fb.BufferContext _bc; final int _bcOffset; - String? get id => const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 4); + String? get id => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 4); int get val => const fb.Int64Reader().vTableGet(_bc, _bcOffset, 6, 0); int get count => const fb.Uint16Reader().vTableGet(_bc, _bcOffset, 8, 0); @@ -897,10 +917,7 @@ class Stat { return 'Stat{id: ${id}, val: ${val}, count: ${count}}'; } - StatT unpack() => StatT( - id: id, - val: val, - count: count); + StatT unpack() => StatT(id: id, val: val, count: count); static int pack(fb.Builder fbBuilder, StatT? object) { if (object == null) return 0; @@ -913,15 +930,11 @@ class StatT implements fb.Packable { int val; int count; - StatT({ - this.id, - this.val = 0, - this.count = 0}); + StatT({this.id, this.val = 0, this.count = 0}); @override int pack(fb.Builder fbBuilder) { - final int? idOffset = id == null ? null - : fbBuilder.writeString(id!); + final int? idOffset = id == null ? null : fbBuilder.writeString(id!); fbBuilder.startTable(3); fbBuilder.addOffset(0, idOffset); fbBuilder.addInt64(1, val); @@ -939,8 +952,7 @@ class _StatReader extends fb.TableReader { const _StatReader(); @override - Stat createObject(fb.BufferContext bc, int offset) => - Stat._(bc, offset); + Stat createObject(fb.BufferContext bc, int offset) => Stat._(bc, offset); } class StatBuilder { @@ -956,10 +968,12 @@ class StatBuilder { fbBuilder.addOffset(0, offset); return fbBuilder.offset; } + int addVal(int? val) { fbBuilder.addInt64(1, val); return fbBuilder.offset; } + int addCount(int? count) { fbBuilder.addUint16(2, count); return fbBuilder.offset; @@ -975,20 +989,15 @@ class StatObjectBuilder extends fb.ObjectBuilder { final int? _val; final int? _count; - StatObjectBuilder({ - String? id, - int? val, - int? count, - }) - : _id = id, - _val = val, - _count = count; + StatObjectBuilder({String? id, int? val, int? count}) + : _id = id, + _val = val, + _count = count; /// Finish building, and store into the [fbBuilder]. @override int finish(fb.Builder fbBuilder) { - final int? idOffset = _id == null ? null - : fbBuilder.writeString(_id!); + final int? idOffset = _id == null ? null : fbBuilder.writeString(_id!); fbBuilder.startTable(3); fbBuilder.addOffset(0, idOffset); fbBuilder.addInt64(1, _val); @@ -1004,6 +1013,7 @@ class StatObjectBuilder extends fb.ObjectBuilder { return fbBuilder.buffer; } } + class Referrable { Referrable._(this._bc, this._bcOffset); factory Referrable(List bytes) { @@ -1023,8 +1033,7 @@ class Referrable { return 'Referrable{id: ${id}}'; } - ReferrableT unpack() => ReferrableT( - id: id); + ReferrableT unpack() => ReferrableT(id: id); static int pack(fb.Builder fbBuilder, ReferrableT? object) { if (object == null) return 0; @@ -1035,8 +1044,7 @@ class Referrable { class ReferrableT implements fb.Packable { int id; - ReferrableT({ - this.id = 0}); + ReferrableT({this.id = 0}); @override int pack(fb.Builder fbBuilder) { @@ -1055,8 +1063,8 @@ class _ReferrableReader extends fb.TableReader { const _ReferrableReader(); @override - Referrable createObject(fb.BufferContext bc, int offset) => - Referrable._(bc, offset); + Referrable createObject(fb.BufferContext bc, int offset) => + Referrable._(bc, offset); } class ReferrableBuilder { @@ -1081,10 +1089,7 @@ class ReferrableBuilder { class ReferrableObjectBuilder extends fb.ObjectBuilder { final int? _id; - ReferrableObjectBuilder({ - int? id, - }) - : _id = id; + ReferrableObjectBuilder({int? id}) : _id = id; /// Finish building, and store into the [fbBuilder]. @override @@ -1102,6 +1107,7 @@ class ReferrableObjectBuilder extends fb.ObjectBuilder { return fbBuilder.buffer; } } + /// an example documentation comment: "monster object" class Monster { Monster._(this._bc, this._bcOffset); @@ -1118,87 +1124,203 @@ class Monster { Vec3? get pos => Vec3.reader.vTableGetNullable(_bc, _bcOffset, 4); int get mana => const fb.Int16Reader().vTableGet(_bc, _bcOffset, 6, 150); int get hp => const fb.Int16Reader().vTableGet(_bc, _bcOffset, 8, 100); - String? get name => const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 10); - List? get inventory => const fb.Uint8ListReader().vTableGetNullable(_bc, _bcOffset, 14); - Color get color => Color.fromValue(const fb.Uint8Reader().vTableGet(_bc, _bcOffset, 16, 8)); - AnyTypeId? get testType => AnyTypeId._createOrNull(const fb.Uint8Reader().vTableGetNullable(_bc, _bcOffset, 18)); + String? get name => + const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 10); + List? get inventory => + const fb.Uint8ListReader().vTableGetNullable(_bc, _bcOffset, 14); + Color get color => + Color.fromValue(const fb.Uint8Reader().vTableGet(_bc, _bcOffset, 16, 8)); + AnyTypeId? get testType => AnyTypeId._createOrNull( + const fb.Uint8Reader().vTableGetNullable(_bc, _bcOffset, 18), + ); dynamic get test { switch (testType?.value) { - case 1: return Monster.reader.vTableGetNullable(_bc, _bcOffset, 20); - case 2: return TestSimpleTableWithEnum.reader.vTableGetNullable(_bc, _bcOffset, 20); - case 3: return my_game_example2.Monster.reader.vTableGetNullable(_bc, _bcOffset, 20); - default: return null; + case 1: + return Monster.reader.vTableGetNullable(_bc, _bcOffset, 20); + case 2: + return TestSimpleTableWithEnum.reader.vTableGetNullable( + _bc, + _bcOffset, + 20, + ); + case 3: + return my_game_example2.Monster.reader.vTableGetNullable( + _bc, + _bcOffset, + 20, + ); + default: + return null; } } - List? get test4 => const fb.ListReader(Test.reader).vTableGetNullable(_bc, _bcOffset, 22); - List? get testarrayofstring => const fb.ListReader(fb.StringReader()).vTableGetNullable(_bc, _bcOffset, 24); + + List? get test4 => const fb.ListReader( + Test.reader, + ).vTableGetNullable(_bc, _bcOffset, 22); + List? get testarrayofstring => const fb.ListReader( + fb.StringReader(), + ).vTableGetNullable(_bc, _bcOffset, 24); + /// an example documentation comment: this will end up in the generated code /// multiline too - List? get testarrayoftables => const fb.ListReader(Monster.reader).vTableGetNullable(_bc, _bcOffset, 26); + List? get testarrayoftables => const fb.ListReader( + Monster.reader, + ).vTableGetNullable(_bc, _bcOffset, 26); Monster? get enemy => Monster.reader.vTableGetNullable(_bc, _bcOffset, 28); - List? get testnestedflatbuffer => const fb.Uint8ListReader().vTableGetNullable(_bc, _bcOffset, 30); + List? get testnestedflatbuffer => + const fb.Uint8ListReader().vTableGetNullable(_bc, _bcOffset, 30); Stat? get testempty => Stat.reader.vTableGetNullable(_bc, _bcOffset, 32); - bool get testbool => const fb.BoolReader().vTableGet(_bc, _bcOffset, 34, false); - int get testhashs32Fnv1 => const fb.Int32Reader().vTableGet(_bc, _bcOffset, 36, 0); - int get testhashu32Fnv1 => const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 38, 0); - int get testhashs64Fnv1 => const fb.Int64Reader().vTableGet(_bc, _bcOffset, 40, 0); - int get testhashu64Fnv1 => const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 42, 0); - int get testhashs32Fnv1a => const fb.Int32Reader().vTableGet(_bc, _bcOffset, 44, 0); - int get testhashu32Fnv1a => const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 46, 0); - int get testhashs64Fnv1a => const fb.Int64Reader().vTableGet(_bc, _bcOffset, 48, 0); - int get testhashu64Fnv1a => const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 50, 0); - List? get testarrayofbools => const fb.ListReader(fb.BoolReader()).vTableGetNullable(_bc, _bcOffset, 52); - double get testf => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 54, 3.14159); - double get testf2 => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 56, 3.0); - double get testf3 => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 58, 0.0); - List? get testarrayofstring2 => const fb.ListReader(fb.StringReader()).vTableGetNullable(_bc, _bcOffset, 60); - List? get testarrayofsortedstruct => const fb.ListReader(Ability.reader).vTableGetNullable(_bc, _bcOffset, 62); - List? get flex => const fb.Uint8ListReader().vTableGetNullable(_bc, _bcOffset, 64); - List? get test5 => const fb.ListReader(Test.reader).vTableGetNullable(_bc, _bcOffset, 66); - List? get vectorOfLongs => const fb.ListReader(fb.Int64Reader()).vTableGetNullable(_bc, _bcOffset, 68); - List? get vectorOfDoubles => const fb.ListReader(fb.Float64Reader()).vTableGetNullable(_bc, _bcOffset, 70); - my_game.InParentNamespace? get parentNamespaceTest => my_game.InParentNamespace.reader.vTableGetNullable(_bc, _bcOffset, 72); - List? get vectorOfReferrables => const fb.ListReader(Referrable.reader).vTableGetNullable(_bc, _bcOffset, 74); - int get singleWeakReference => const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 76, 0); - List? get vectorOfWeakReferences => const fb.ListReader(fb.Uint64Reader()).vTableGetNullable(_bc, _bcOffset, 78); - List? get vectorOfStrongReferrables => const fb.ListReader(Referrable.reader).vTableGetNullable(_bc, _bcOffset, 80); - int get coOwningReference => const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 82, 0); - List? get vectorOfCoOwningReferences => const fb.ListReader(fb.Uint64Reader()).vTableGetNullable(_bc, _bcOffset, 84); - int get nonOwningReference => const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 86, 0); - List? get vectorOfNonOwningReferences => const fb.ListReader(fb.Uint64Reader()).vTableGetNullable(_bc, _bcOffset, 88); - AnyUniqueAliasesTypeId? get anyUniqueType => AnyUniqueAliasesTypeId._createOrNull(const fb.Uint8Reader().vTableGetNullable(_bc, _bcOffset, 90)); + bool get testbool => + const fb.BoolReader().vTableGet(_bc, _bcOffset, 34, false); + int get testhashs32Fnv1 => + const fb.Int32Reader().vTableGet(_bc, _bcOffset, 36, 0); + int get testhashu32Fnv1 => + const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 38, 0); + int get testhashs64Fnv1 => + const fb.Int64Reader().vTableGet(_bc, _bcOffset, 40, 0); + int get testhashu64Fnv1 => + const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 42, 0); + int get testhashs32Fnv1a => + const fb.Int32Reader().vTableGet(_bc, _bcOffset, 44, 0); + int get testhashu32Fnv1a => + const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 46, 0); + int get testhashs64Fnv1a => + const fb.Int64Reader().vTableGet(_bc, _bcOffset, 48, 0); + int get testhashu64Fnv1a => + const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 50, 0); + List? get testarrayofbools => const fb.ListReader( + fb.BoolReader(), + ).vTableGetNullable(_bc, _bcOffset, 52); + double get testf => + const fb.Float32Reader().vTableGet(_bc, _bcOffset, 54, 3.14159); + double get testf2 => + const fb.Float32Reader().vTableGet(_bc, _bcOffset, 56, 3.0); + double get testf3 => + const fb.Float32Reader().vTableGet(_bc, _bcOffset, 58, 0.0); + List? get testarrayofstring2 => const fb.ListReader( + fb.StringReader(), + ).vTableGetNullable(_bc, _bcOffset, 60); + List? get testarrayofsortedstruct => const fb.ListReader( + Ability.reader, + ).vTableGetNullable(_bc, _bcOffset, 62); + List? get flex => + const fb.Uint8ListReader().vTableGetNullable(_bc, _bcOffset, 64); + List? get test5 => const fb.ListReader( + Test.reader, + ).vTableGetNullable(_bc, _bcOffset, 66); + List? get vectorOfLongs => const fb.ListReader( + fb.Int64Reader(), + ).vTableGetNullable(_bc, _bcOffset, 68); + List? get vectorOfDoubles => const fb.ListReader( + fb.Float64Reader(), + ).vTableGetNullable(_bc, _bcOffset, 70); + my_game.InParentNamespace? get parentNamespaceTest => + my_game.InParentNamespace.reader.vTableGetNullable(_bc, _bcOffset, 72); + List? get vectorOfReferrables => const fb.ListReader( + Referrable.reader, + ).vTableGetNullable(_bc, _bcOffset, 74); + int get singleWeakReference => + const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 76, 0); + List? get vectorOfWeakReferences => const fb.ListReader( + fb.Uint64Reader(), + ).vTableGetNullable(_bc, _bcOffset, 78); + List? get vectorOfStrongReferrables => + const fb.ListReader( + Referrable.reader, + ).vTableGetNullable(_bc, _bcOffset, 80); + int get coOwningReference => + const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 82, 0); + List? get vectorOfCoOwningReferences => const fb.ListReader( + fb.Uint64Reader(), + ).vTableGetNullable(_bc, _bcOffset, 84); + int get nonOwningReference => + const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 86, 0); + List? get vectorOfNonOwningReferences => const fb.ListReader( + fb.Uint64Reader(), + ).vTableGetNullable(_bc, _bcOffset, 88); + AnyUniqueAliasesTypeId? get anyUniqueType => + AnyUniqueAliasesTypeId._createOrNull( + const fb.Uint8Reader().vTableGetNullable(_bc, _bcOffset, 90), + ); dynamic get anyUnique { switch (anyUniqueType?.value) { - case 1: return Monster.reader.vTableGetNullable(_bc, _bcOffset, 92); - case 2: return TestSimpleTableWithEnum.reader.vTableGetNullable(_bc, _bcOffset, 92); - case 3: return my_game_example2.Monster.reader.vTableGetNullable(_bc, _bcOffset, 92); - default: return null; + case 1: + return Monster.reader.vTableGetNullable(_bc, _bcOffset, 92); + case 2: + return TestSimpleTableWithEnum.reader.vTableGetNullable( + _bc, + _bcOffset, + 92, + ); + case 3: + return my_game_example2.Monster.reader.vTableGetNullable( + _bc, + _bcOffset, + 92, + ); + default: + return null; } } - AnyAmbiguousAliasesTypeId? get anyAmbiguousType => AnyAmbiguousAliasesTypeId._createOrNull(const fb.Uint8Reader().vTableGetNullable(_bc, _bcOffset, 94)); + + AnyAmbiguousAliasesTypeId? get anyAmbiguousType => + AnyAmbiguousAliasesTypeId._createOrNull( + const fb.Uint8Reader().vTableGetNullable(_bc, _bcOffset, 94), + ); dynamic get anyAmbiguous { switch (anyAmbiguousType?.value) { - case 1: return Monster.reader.vTableGetNullable(_bc, _bcOffset, 96); - case 2: return Monster.reader.vTableGetNullable(_bc, _bcOffset, 96); - case 3: return Monster.reader.vTableGetNullable(_bc, _bcOffset, 96); - default: return null; + case 1: + return Monster.reader.vTableGetNullable(_bc, _bcOffset, 96); + case 2: + return Monster.reader.vTableGetNullable(_bc, _bcOffset, 96); + case 3: + return Monster.reader.vTableGetNullable(_bc, _bcOffset, 96); + default: + return null; } } - List? get vectorOfEnums => const fb.ListReader(Color.reader).vTableGetNullable(_bc, _bcOffset, 98); - Race get signedEnum => Race.fromValue(const fb.Int8Reader().vTableGet(_bc, _bcOffset, 100, -1)); - List? get testrequirednestedflatbuffer => const fb.Uint8ListReader().vTableGetNullable(_bc, _bcOffset, 102); - List? get scalarKeySortedTables => const fb.ListReader(Stat.reader).vTableGetNullable(_bc, _bcOffset, 104); + + List? get vectorOfEnums => const fb.ListReader( + Color.reader, + ).vTableGetNullable(_bc, _bcOffset, 98); + Race get signedEnum => + Race.fromValue(const fb.Int8Reader().vTableGet(_bc, _bcOffset, 100, -1)); + List? get testrequirednestedflatbuffer => + const fb.Uint8ListReader().vTableGetNullable(_bc, _bcOffset, 102); + List? get scalarKeySortedTables => const fb.ListReader( + Stat.reader, + ).vTableGetNullable(_bc, _bcOffset, 104); Test? get nativeInline => Test.reader.vTableGetNullable(_bc, _bcOffset, 106); - LongEnum get longEnumNonEnumDefault => LongEnum.fromValue(const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 108, 0)); - LongEnum get longEnumNormalDefault => LongEnum.fromValue(const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 110, 2)); - double get nanDefault => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 112, double.nan); - double get infDefault => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 114, double.infinity); - double get positiveInfDefault => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 116, double.infinity); - double get infinityDefault => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 118, double.infinity); - double get positiveInfinityDefault => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 120, double.infinity); - double get negativeInfDefault => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 122, double.negativeInfinity); - double get negativeInfinityDefault => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 124, double.negativeInfinity); - double get doubleInfDefault => const fb.Float64Reader().vTableGet(_bc, _bcOffset, 126, double.infinity); + LongEnum get longEnumNonEnumDefault => LongEnum.fromValue( + const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 108, 0), + ); + LongEnum get longEnumNormalDefault => LongEnum.fromValue( + const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 110, 2), + ); + double get nanDefault => + const fb.Float32Reader().vTableGet(_bc, _bcOffset, 112, double.nan); + double get infDefault => + const fb.Float32Reader().vTableGet(_bc, _bcOffset, 114, double.infinity); + double get positiveInfDefault => + const fb.Float32Reader().vTableGet(_bc, _bcOffset, 116, double.infinity); + double get infinityDefault => + const fb.Float32Reader().vTableGet(_bc, _bcOffset, 118, double.infinity); + double get positiveInfinityDefault => + const fb.Float32Reader().vTableGet(_bc, _bcOffset, 120, double.infinity); + double get negativeInfDefault => const fb.Float32Reader().vTableGet( + _bc, + _bcOffset, + 122, + double.negativeInfinity, + ); + double get negativeInfinityDefault => const fb.Float32Reader().vTableGet( + _bc, + _bcOffset, + 124, + double.negativeInfinity, + ); + double get doubleInfDefault => + const fb.Float64Reader().vTableGet(_bc, _bcOffset, 126, double.infinity); @override String toString() { @@ -1206,67 +1328,109 @@ class Monster { } MonsterT unpack() => MonsterT( - pos: pos?.unpack(), - mana: mana, - hp: hp, - name: name, - inventory: const fb.Uint8ListReader(lazy: false).vTableGetNullable(_bc, _bcOffset, 14), - color: color, - testType: testType, - test: test, - test4: test4?.map((e) => e.unpack()).toList(), - testarrayofstring: const fb.ListReader(fb.StringReader(), lazy: false).vTableGetNullable(_bc, _bcOffset, 24), - testarrayoftables: testarrayoftables?.map((e) => e.unpack()).toList(), - enemy: enemy?.unpack(), - testnestedflatbuffer: const fb.Uint8ListReader(lazy: false).vTableGetNullable(_bc, _bcOffset, 30), - testempty: testempty?.unpack(), - testbool: testbool, - testhashs32Fnv1: testhashs32Fnv1, - testhashu32Fnv1: testhashu32Fnv1, - testhashs64Fnv1: testhashs64Fnv1, - testhashu64Fnv1: testhashu64Fnv1, - testhashs32Fnv1a: testhashs32Fnv1a, - testhashu32Fnv1a: testhashu32Fnv1a, - testhashs64Fnv1a: testhashs64Fnv1a, - testhashu64Fnv1a: testhashu64Fnv1a, - testarrayofbools: const fb.ListReader(fb.BoolReader(), lazy: false).vTableGetNullable(_bc, _bcOffset, 52), - testf: testf, - testf2: testf2, - testf3: testf3, - testarrayofstring2: const fb.ListReader(fb.StringReader(), lazy: false).vTableGetNullable(_bc, _bcOffset, 60), - testarrayofsortedstruct: testarrayofsortedstruct?.map((e) => e.unpack()).toList(), - flex: const fb.Uint8ListReader(lazy: false).vTableGetNullable(_bc, _bcOffset, 64), - test5: test5?.map((e) => e.unpack()).toList(), - vectorOfLongs: const fb.ListReader(fb.Int64Reader(), lazy: false).vTableGetNullable(_bc, _bcOffset, 68), - vectorOfDoubles: const fb.ListReader(fb.Float64Reader(), lazy: false).vTableGetNullable(_bc, _bcOffset, 70), - parentNamespaceTest: parentNamespaceTest?.unpack(), - vectorOfReferrables: vectorOfReferrables?.map((e) => e.unpack()).toList(), - singleWeakReference: singleWeakReference, - vectorOfWeakReferences: const fb.ListReader(fb.Uint64Reader(), lazy: false).vTableGetNullable(_bc, _bcOffset, 78), - vectorOfStrongReferrables: vectorOfStrongReferrables?.map((e) => e.unpack()).toList(), - coOwningReference: coOwningReference, - vectorOfCoOwningReferences: const fb.ListReader(fb.Uint64Reader(), lazy: false).vTableGetNullable(_bc, _bcOffset, 84), - nonOwningReference: nonOwningReference, - vectorOfNonOwningReferences: const fb.ListReader(fb.Uint64Reader(), lazy: false).vTableGetNullable(_bc, _bcOffset, 88), - anyUniqueType: anyUniqueType, - anyUnique: anyUnique, - anyAmbiguousType: anyAmbiguousType, - anyAmbiguous: anyAmbiguous, - vectorOfEnums: const fb.ListReader(Color.reader, lazy: false).vTableGetNullable(_bc, _bcOffset, 98), - signedEnum: signedEnum, - testrequirednestedflatbuffer: const fb.Uint8ListReader(lazy: false).vTableGetNullable(_bc, _bcOffset, 102), - scalarKeySortedTables: scalarKeySortedTables?.map((e) => e.unpack()).toList(), - nativeInline: nativeInline?.unpack(), - longEnumNonEnumDefault: longEnumNonEnumDefault, - longEnumNormalDefault: longEnumNormalDefault, - nanDefault: nanDefault, - infDefault: infDefault, - positiveInfDefault: positiveInfDefault, - infinityDefault: infinityDefault, - positiveInfinityDefault: positiveInfinityDefault, - negativeInfDefault: negativeInfDefault, - negativeInfinityDefault: negativeInfinityDefault, - doubleInfDefault: doubleInfDefault); + pos: pos?.unpack(), + mana: mana, + hp: hp, + name: name, + inventory: const fb.Uint8ListReader( + lazy: false, + ).vTableGetNullable(_bc, _bcOffset, 14), + color: color, + testType: testType, + test: test, + test4: test4?.map((e) => e.unpack()).toList(), + testarrayofstring: const fb.ListReader( + fb.StringReader(), + lazy: false, + ).vTableGetNullable(_bc, _bcOffset, 24), + testarrayoftables: testarrayoftables?.map((e) => e.unpack()).toList(), + enemy: enemy?.unpack(), + testnestedflatbuffer: const fb.Uint8ListReader( + lazy: false, + ).vTableGetNullable(_bc, _bcOffset, 30), + testempty: testempty?.unpack(), + testbool: testbool, + testhashs32Fnv1: testhashs32Fnv1, + testhashu32Fnv1: testhashu32Fnv1, + testhashs64Fnv1: testhashs64Fnv1, + testhashu64Fnv1: testhashu64Fnv1, + testhashs32Fnv1a: testhashs32Fnv1a, + testhashu32Fnv1a: testhashu32Fnv1a, + testhashs64Fnv1a: testhashs64Fnv1a, + testhashu64Fnv1a: testhashu64Fnv1a, + testarrayofbools: const fb.ListReader( + fb.BoolReader(), + lazy: false, + ).vTableGetNullable(_bc, _bcOffset, 52), + testf: testf, + testf2: testf2, + testf3: testf3, + testarrayofstring2: const fb.ListReader( + fb.StringReader(), + lazy: false, + ).vTableGetNullable(_bc, _bcOffset, 60), + testarrayofsortedstruct: testarrayofsortedstruct + ?.map((e) => e.unpack()) + .toList(), + flex: const fb.Uint8ListReader( + lazy: false, + ).vTableGetNullable(_bc, _bcOffset, 64), + test5: test5?.map((e) => e.unpack()).toList(), + vectorOfLongs: const fb.ListReader( + fb.Int64Reader(), + lazy: false, + ).vTableGetNullable(_bc, _bcOffset, 68), + vectorOfDoubles: const fb.ListReader( + fb.Float64Reader(), + lazy: false, + ).vTableGetNullable(_bc, _bcOffset, 70), + parentNamespaceTest: parentNamespaceTest?.unpack(), + vectorOfReferrables: vectorOfReferrables?.map((e) => e.unpack()).toList(), + singleWeakReference: singleWeakReference, + vectorOfWeakReferences: const fb.ListReader( + fb.Uint64Reader(), + lazy: false, + ).vTableGetNullable(_bc, _bcOffset, 78), + vectorOfStrongReferrables: vectorOfStrongReferrables + ?.map((e) => e.unpack()) + .toList(), + coOwningReference: coOwningReference, + vectorOfCoOwningReferences: const fb.ListReader( + fb.Uint64Reader(), + lazy: false, + ).vTableGetNullable(_bc, _bcOffset, 84), + nonOwningReference: nonOwningReference, + vectorOfNonOwningReferences: const fb.ListReader( + fb.Uint64Reader(), + lazy: false, + ).vTableGetNullable(_bc, _bcOffset, 88), + anyUniqueType: anyUniqueType, + anyUnique: anyUnique, + anyAmbiguousType: anyAmbiguousType, + anyAmbiguous: anyAmbiguous, + vectorOfEnums: const fb.ListReader( + Color.reader, + lazy: false, + ).vTableGetNullable(_bc, _bcOffset, 98), + signedEnum: signedEnum, + testrequirednestedflatbuffer: const fb.Uint8ListReader( + lazy: false, + ).vTableGetNullable(_bc, _bcOffset, 102), + scalarKeySortedTables: scalarKeySortedTables + ?.map((e) => e.unpack()) + .toList(), + nativeInline: nativeInline?.unpack(), + longEnumNonEnumDefault: longEnumNonEnumDefault, + longEnumNormalDefault: longEnumNormalDefault, + nanDefault: nanDefault, + infDefault: infDefault, + positiveInfDefault: positiveInfDefault, + infinityDefault: infinityDefault, + positiveInfinityDefault: positiveInfinityDefault, + negativeInfDefault: negativeInfDefault, + negativeInfinityDefault: negativeInfinityDefault, + doubleInfDefault: doubleInfDefault, + ); static int pack(fb.Builder fbBuilder, MonsterT? object) { if (object == null) return 0; @@ -1286,6 +1450,7 @@ class MonsterT implements fb.Packable { dynamic test; List? test4; List? testarrayofstring; + /// an example documentation comment: this will end up in the generated code /// multiline too List? testarrayoftables; @@ -1341,127 +1506,168 @@ class MonsterT implements fb.Packable { double doubleInfDefault; MonsterT({ - this.pos, - this.mana = 150, - this.hp = 100, - this.name, - this.inventory, - this.color = Color.Blue, - this.testType, - this.test, - this.test4, - this.testarrayofstring, - this.testarrayoftables, - this.enemy, - this.testnestedflatbuffer, - this.testempty, - this.testbool = false, - this.testhashs32Fnv1 = 0, - this.testhashu32Fnv1 = 0, - this.testhashs64Fnv1 = 0, - this.testhashu64Fnv1 = 0, - this.testhashs32Fnv1a = 0, - this.testhashu32Fnv1a = 0, - this.testhashs64Fnv1a = 0, - this.testhashu64Fnv1a = 0, - this.testarrayofbools, - this.testf = 3.14159, - this.testf2 = 3.0, - this.testf3 = 0.0, - this.testarrayofstring2, - this.testarrayofsortedstruct, - this.flex, - this.test5, - this.vectorOfLongs, - this.vectorOfDoubles, - this.parentNamespaceTest, - this.vectorOfReferrables, - this.singleWeakReference = 0, - this.vectorOfWeakReferences, - this.vectorOfStrongReferrables, - this.coOwningReference = 0, - this.vectorOfCoOwningReferences, - this.nonOwningReference = 0, - this.vectorOfNonOwningReferences, - this.anyUniqueType, - this.anyUnique, - this.anyAmbiguousType, - this.anyAmbiguous, - this.vectorOfEnums, - this.signedEnum = Race.None, - this.testrequirednestedflatbuffer, - this.scalarKeySortedTables, - this.nativeInline, - this.longEnumNonEnumDefault = LongEnum._default, - this.longEnumNormalDefault = LongEnum.LongOne, - this.nanDefault = double.nan, - this.infDefault = double.infinity, - this.positiveInfDefault = double.infinity, - this.infinityDefault = double.infinity, - this.positiveInfinityDefault = double.infinity, - this.negativeInfDefault = double.negativeInfinity, - this.negativeInfinityDefault = double.negativeInfinity, - this.doubleInfDefault = double.infinity}); + this.pos, + this.mana = 150, + this.hp = 100, + this.name, + this.inventory, + this.color = Color.Blue, + this.testType, + this.test, + this.test4, + this.testarrayofstring, + this.testarrayoftables, + this.enemy, + this.testnestedflatbuffer, + this.testempty, + this.testbool = false, + this.testhashs32Fnv1 = 0, + this.testhashu32Fnv1 = 0, + this.testhashs64Fnv1 = 0, + this.testhashu64Fnv1 = 0, + this.testhashs32Fnv1a = 0, + this.testhashu32Fnv1a = 0, + this.testhashs64Fnv1a = 0, + this.testhashu64Fnv1a = 0, + this.testarrayofbools, + this.testf = 3.14159, + this.testf2 = 3.0, + this.testf3 = 0.0, + this.testarrayofstring2, + this.testarrayofsortedstruct, + this.flex, + this.test5, + this.vectorOfLongs, + this.vectorOfDoubles, + this.parentNamespaceTest, + this.vectorOfReferrables, + this.singleWeakReference = 0, + this.vectorOfWeakReferences, + this.vectorOfStrongReferrables, + this.coOwningReference = 0, + this.vectorOfCoOwningReferences, + this.nonOwningReference = 0, + this.vectorOfNonOwningReferences, + this.anyUniqueType, + this.anyUnique, + this.anyAmbiguousType, + this.anyAmbiguous, + this.vectorOfEnums, + this.signedEnum = Race.None, + this.testrequirednestedflatbuffer, + this.scalarKeySortedTables, + this.nativeInline, + this.longEnumNonEnumDefault = LongEnum._default, + this.longEnumNormalDefault = LongEnum.LongOne, + this.nanDefault = double.nan, + this.infDefault = double.infinity, + this.positiveInfDefault = double.infinity, + this.infinityDefault = double.infinity, + this.positiveInfinityDefault = double.infinity, + this.negativeInfDefault = double.negativeInfinity, + this.negativeInfinityDefault = double.negativeInfinity, + this.doubleInfDefault = double.infinity, + }); @override int pack(fb.Builder fbBuilder) { - final int? nameOffset = name == null ? null - : fbBuilder.writeString(name!); - final int? inventoryOffset = inventory == null ? null + final int? nameOffset = name == null ? null : fbBuilder.writeString(name!); + final int? inventoryOffset = inventory == null + ? null : fbBuilder.writeListUint8(inventory!); final int? testOffset = test?.pack(fbBuilder); int? test4Offset; if (test4 != null) { - for (var e in test4!) { e.pack(fbBuilder); } + for (var e in test4!) { + e.pack(fbBuilder); + } test4Offset = fbBuilder.endStructVector(test4!.length); } - final int? testarrayofstringOffset = testarrayofstring == null ? null - : fbBuilder.writeList(testarrayofstring!.map(fbBuilder.writeString).toList()); - final int? testarrayoftablesOffset = testarrayoftables == null ? null - : fbBuilder.writeList(testarrayoftables!.map((b) => b.pack(fbBuilder)).toList()); + final int? testarrayofstringOffset = testarrayofstring == null + ? null + : fbBuilder.writeList( + testarrayofstring!.map(fbBuilder.writeString).toList(), + ); + final int? testarrayoftablesOffset = testarrayoftables == null + ? null + : fbBuilder.writeList( + testarrayoftables!.map((b) => b.pack(fbBuilder)).toList(), + ); final int? enemyOffset = enemy?.pack(fbBuilder); - final int? testnestedflatbufferOffset = testnestedflatbuffer == null ? null + final int? testnestedflatbufferOffset = testnestedflatbuffer == null + ? null : fbBuilder.writeListUint8(testnestedflatbuffer!); final int? testemptyOffset = testempty?.pack(fbBuilder); - final int? testarrayofboolsOffset = testarrayofbools == null ? null + final int? testarrayofboolsOffset = testarrayofbools == null + ? null : fbBuilder.writeListBool(testarrayofbools!); - final int? testarrayofstring2Offset = testarrayofstring2 == null ? null - : fbBuilder.writeList(testarrayofstring2!.map(fbBuilder.writeString).toList()); + final int? testarrayofstring2Offset = testarrayofstring2 == null + ? null + : fbBuilder.writeList( + testarrayofstring2!.map(fbBuilder.writeString).toList(), + ); int? testarrayofsortedstructOffset; if (testarrayofsortedstruct != null) { - for (var e in testarrayofsortedstruct!) { e.pack(fbBuilder); } - testarrayofsortedstructOffset = fbBuilder.endStructVector(testarrayofsortedstruct!.length); + for (var e in testarrayofsortedstruct!) { + e.pack(fbBuilder); + } + testarrayofsortedstructOffset = fbBuilder.endStructVector( + testarrayofsortedstruct!.length, + ); } - final int? flexOffset = flex == null ? null + final int? flexOffset = flex == null + ? null : fbBuilder.writeListUint8(flex!); int? test5Offset; if (test5 != null) { - for (var e in test5!) { e.pack(fbBuilder); } + for (var e in test5!) { + e.pack(fbBuilder); + } test5Offset = fbBuilder.endStructVector(test5!.length); } - final int? vectorOfLongsOffset = vectorOfLongs == null ? null + final int? vectorOfLongsOffset = vectorOfLongs == null + ? null : fbBuilder.writeListInt64(vectorOfLongs!); - final int? vectorOfDoublesOffset = vectorOfDoubles == null ? null + final int? vectorOfDoublesOffset = vectorOfDoubles == null + ? null : fbBuilder.writeListFloat64(vectorOfDoubles!); final int? parentNamespaceTestOffset = parentNamespaceTest?.pack(fbBuilder); - final int? vectorOfReferrablesOffset = vectorOfReferrables == null ? null - : fbBuilder.writeList(vectorOfReferrables!.map((b) => b.pack(fbBuilder)).toList()); - final int? vectorOfWeakReferencesOffset = vectorOfWeakReferences == null ? null + final int? vectorOfReferrablesOffset = vectorOfReferrables == null + ? null + : fbBuilder.writeList( + vectorOfReferrables!.map((b) => b.pack(fbBuilder)).toList(), + ); + final int? vectorOfWeakReferencesOffset = vectorOfWeakReferences == null + ? null : fbBuilder.writeListUint64(vectorOfWeakReferences!); - final int? vectorOfStrongReferrablesOffset = vectorOfStrongReferrables == null ? null - : fbBuilder.writeList(vectorOfStrongReferrables!.map((b) => b.pack(fbBuilder)).toList()); - final int? vectorOfCoOwningReferencesOffset = vectorOfCoOwningReferences == null ? null + final int? vectorOfStrongReferrablesOffset = + vectorOfStrongReferrables == null + ? null + : fbBuilder.writeList( + vectorOfStrongReferrables!.map((b) => b.pack(fbBuilder)).toList(), + ); + final int? vectorOfCoOwningReferencesOffset = + vectorOfCoOwningReferences == null + ? null : fbBuilder.writeListUint64(vectorOfCoOwningReferences!); - final int? vectorOfNonOwningReferencesOffset = vectorOfNonOwningReferences == null ? null + final int? vectorOfNonOwningReferencesOffset = + vectorOfNonOwningReferences == null + ? null : fbBuilder.writeListUint64(vectorOfNonOwningReferences!); final int? anyUniqueOffset = anyUnique?.pack(fbBuilder); final int? anyAmbiguousOffset = anyAmbiguous?.pack(fbBuilder); - final int? vectorOfEnumsOffset = vectorOfEnums == null ? null + final int? vectorOfEnumsOffset = vectorOfEnums == null + ? null : fbBuilder.writeListUint8(vectorOfEnums!.map((f) => f.value).toList()); - final int? testrequirednestedflatbufferOffset = testrequirednestedflatbuffer == null ? null + final int? testrequirednestedflatbufferOffset = + testrequirednestedflatbuffer == null + ? null : fbBuilder.writeListUint8(testrequirednestedflatbuffer!); - final int? scalarKeySortedTablesOffset = scalarKeySortedTables == null ? null - : fbBuilder.writeList(scalarKeySortedTables!.map((b) => b.pack(fbBuilder)).toList()); + final int? scalarKeySortedTablesOffset = scalarKeySortedTables == null + ? null + : fbBuilder.writeList( + scalarKeySortedTables!.map((b) => b.pack(fbBuilder)).toList(), + ); fbBuilder.startTable(62); if (pos != null) { fbBuilder.addStruct(0, pos!.pack(fbBuilder)); @@ -1541,8 +1747,8 @@ class _MonsterReader extends fb.TableReader { const _MonsterReader(); @override - Monster createObject(fb.BufferContext bc, int offset) => - Monster._(bc, offset); + Monster createObject(fb.BufferContext bc, int offset) => + Monster._(bc, offset); } class MonsterBuilder { @@ -1558,242 +1764,302 @@ class MonsterBuilder { fbBuilder.addStruct(0, offset); return fbBuilder.offset; } + int addMana(int? mana) { fbBuilder.addInt16(1, mana); return fbBuilder.offset; } + int addHp(int? hp) { fbBuilder.addInt16(2, hp); return fbBuilder.offset; } + int addNameOffset(int? offset) { fbBuilder.addOffset(3, offset); return fbBuilder.offset; } + int addInventoryOffset(int? offset) { fbBuilder.addOffset(5, offset); return fbBuilder.offset; } + int addColor(Color? color) { fbBuilder.addUint8(6, color?.value); return fbBuilder.offset; } + int addTestType(AnyTypeId? testType) { fbBuilder.addUint8(7, testType?.value); return fbBuilder.offset; } + int addTestOffset(int? offset) { fbBuilder.addOffset(8, offset); return fbBuilder.offset; } + int addTest4Offset(int? offset) { fbBuilder.addOffset(9, offset); return fbBuilder.offset; } + int addTestarrayofstringOffset(int? offset) { fbBuilder.addOffset(10, offset); return fbBuilder.offset; } + int addTestarrayoftablesOffset(int? offset) { fbBuilder.addOffset(11, offset); return fbBuilder.offset; } + int addEnemyOffset(int? offset) { fbBuilder.addOffset(12, offset); return fbBuilder.offset; } + int addTestnestedflatbufferOffset(int? offset) { fbBuilder.addOffset(13, offset); return fbBuilder.offset; } + int addTestemptyOffset(int? offset) { fbBuilder.addOffset(14, offset); return fbBuilder.offset; } + int addTestbool(bool? testbool) { fbBuilder.addBool(15, testbool); return fbBuilder.offset; } + int addTesthashs32Fnv1(int? testhashs32Fnv1) { fbBuilder.addInt32(16, testhashs32Fnv1); return fbBuilder.offset; } + int addTesthashu32Fnv1(int? testhashu32Fnv1) { fbBuilder.addUint32(17, testhashu32Fnv1); return fbBuilder.offset; } + int addTesthashs64Fnv1(int? testhashs64Fnv1) { fbBuilder.addInt64(18, testhashs64Fnv1); return fbBuilder.offset; } + int addTesthashu64Fnv1(int? testhashu64Fnv1) { fbBuilder.addUint64(19, testhashu64Fnv1); return fbBuilder.offset; } + int addTesthashs32Fnv1a(int? testhashs32Fnv1a) { fbBuilder.addInt32(20, testhashs32Fnv1a); return fbBuilder.offset; } + int addTesthashu32Fnv1a(int? testhashu32Fnv1a) { fbBuilder.addUint32(21, testhashu32Fnv1a); return fbBuilder.offset; } + int addTesthashs64Fnv1a(int? testhashs64Fnv1a) { fbBuilder.addInt64(22, testhashs64Fnv1a); return fbBuilder.offset; } + int addTesthashu64Fnv1a(int? testhashu64Fnv1a) { fbBuilder.addUint64(23, testhashu64Fnv1a); return fbBuilder.offset; } + int addTestarrayofboolsOffset(int? offset) { fbBuilder.addOffset(24, offset); return fbBuilder.offset; } + int addTestf(double? testf) { fbBuilder.addFloat32(25, testf); return fbBuilder.offset; } + int addTestf2(double? testf2) { fbBuilder.addFloat32(26, testf2); return fbBuilder.offset; } + int addTestf3(double? testf3) { fbBuilder.addFloat32(27, testf3); return fbBuilder.offset; } + int addTestarrayofstring2Offset(int? offset) { fbBuilder.addOffset(28, offset); return fbBuilder.offset; } + int addTestarrayofsortedstructOffset(int? offset) { fbBuilder.addOffset(29, offset); return fbBuilder.offset; } + int addFlexOffset(int? offset) { fbBuilder.addOffset(30, offset); return fbBuilder.offset; } + int addTest5Offset(int? offset) { fbBuilder.addOffset(31, offset); return fbBuilder.offset; } + int addVectorOfLongsOffset(int? offset) { fbBuilder.addOffset(32, offset); return fbBuilder.offset; } + int addVectorOfDoublesOffset(int? offset) { fbBuilder.addOffset(33, offset); return fbBuilder.offset; } + int addParentNamespaceTestOffset(int? offset) { fbBuilder.addOffset(34, offset); return fbBuilder.offset; } + int addVectorOfReferrablesOffset(int? offset) { fbBuilder.addOffset(35, offset); return fbBuilder.offset; } + int addSingleWeakReference(int? singleWeakReference) { fbBuilder.addUint64(36, singleWeakReference); return fbBuilder.offset; } + int addVectorOfWeakReferencesOffset(int? offset) { fbBuilder.addOffset(37, offset); return fbBuilder.offset; } + int addVectorOfStrongReferrablesOffset(int? offset) { fbBuilder.addOffset(38, offset); return fbBuilder.offset; } + int addCoOwningReference(int? coOwningReference) { fbBuilder.addUint64(39, coOwningReference); return fbBuilder.offset; } + int addVectorOfCoOwningReferencesOffset(int? offset) { fbBuilder.addOffset(40, offset); return fbBuilder.offset; } + int addNonOwningReference(int? nonOwningReference) { fbBuilder.addUint64(41, nonOwningReference); return fbBuilder.offset; } + int addVectorOfNonOwningReferencesOffset(int? offset) { fbBuilder.addOffset(42, offset); return fbBuilder.offset; } + int addAnyUniqueType(AnyUniqueAliasesTypeId? anyUniqueType) { fbBuilder.addUint8(43, anyUniqueType?.value); return fbBuilder.offset; } + int addAnyUniqueOffset(int? offset) { fbBuilder.addOffset(44, offset); return fbBuilder.offset; } + int addAnyAmbiguousType(AnyAmbiguousAliasesTypeId? anyAmbiguousType) { fbBuilder.addUint8(45, anyAmbiguousType?.value); return fbBuilder.offset; } + int addAnyAmbiguousOffset(int? offset) { fbBuilder.addOffset(46, offset); return fbBuilder.offset; } + int addVectorOfEnumsOffset(int? offset) { fbBuilder.addOffset(47, offset); return fbBuilder.offset; } + int addSignedEnum(Race? signedEnum) { fbBuilder.addInt8(48, signedEnum?.value); return fbBuilder.offset; } + int addTestrequirednestedflatbufferOffset(int? offset) { fbBuilder.addOffset(49, offset); return fbBuilder.offset; } + int addScalarKeySortedTablesOffset(int? offset) { fbBuilder.addOffset(50, offset); return fbBuilder.offset; } + int addNativeInline(int offset) { fbBuilder.addStruct(51, offset); return fbBuilder.offset; } + int addLongEnumNonEnumDefault(LongEnum? longEnumNonEnumDefault) { fbBuilder.addUint64(52, longEnumNonEnumDefault?.value); return fbBuilder.offset; } + int addLongEnumNormalDefault(LongEnum? longEnumNormalDefault) { fbBuilder.addUint64(53, longEnumNormalDefault?.value); return fbBuilder.offset; } + int addNanDefault(double? nanDefault) { fbBuilder.addFloat32(54, nanDefault); return fbBuilder.offset; } + int addInfDefault(double? infDefault) { fbBuilder.addFloat32(55, infDefault); return fbBuilder.offset; } + int addPositiveInfDefault(double? positiveInfDefault) { fbBuilder.addFloat32(56, positiveInfDefault); return fbBuilder.offset; } + int addInfinityDefault(double? infinityDefault) { fbBuilder.addFloat32(57, infinityDefault); return fbBuilder.offset; } + int addPositiveInfinityDefault(double? positiveInfinityDefault) { fbBuilder.addFloat32(58, positiveInfinityDefault); return fbBuilder.offset; } + int addNegativeInfDefault(double? negativeInfDefault) { fbBuilder.addFloat32(59, negativeInfDefault); return fbBuilder.offset; } + int addNegativeInfinityDefault(double? negativeInfinityDefault) { fbBuilder.addFloat32(60, negativeInfinityDefault); return fbBuilder.offset; } + int addDoubleInfDefault(double? doubleInfDefault) { fbBuilder.addFloat64(61, doubleInfDefault); return fbBuilder.offset; @@ -1929,120 +2195,167 @@ class MonsterObjectBuilder extends fb.ObjectBuilder { double? negativeInfDefault, double? negativeInfinityDefault, double? doubleInfDefault, - }) - : _pos = pos, - _mana = mana, - _hp = hp, - _name = name, - _inventory = inventory, - _color = color, - _testType = testType, - _test = test, - _test4 = test4, - _testarrayofstring = testarrayofstring, - _testarrayoftables = testarrayoftables, - _enemy = enemy, - _testnestedflatbuffer = testnestedflatbuffer, - _testempty = testempty, - _testbool = testbool, - _testhashs32Fnv1 = testhashs32Fnv1, - _testhashu32Fnv1 = testhashu32Fnv1, - _testhashs64Fnv1 = testhashs64Fnv1, - _testhashu64Fnv1 = testhashu64Fnv1, - _testhashs32Fnv1a = testhashs32Fnv1a, - _testhashu32Fnv1a = testhashu32Fnv1a, - _testhashs64Fnv1a = testhashs64Fnv1a, - _testhashu64Fnv1a = testhashu64Fnv1a, - _testarrayofbools = testarrayofbools, - _testf = testf, - _testf2 = testf2, - _testf3 = testf3, - _testarrayofstring2 = testarrayofstring2, - _testarrayofsortedstruct = testarrayofsortedstruct, - _flex = flex, - _test5 = test5, - _vectorOfLongs = vectorOfLongs, - _vectorOfDoubles = vectorOfDoubles, - _parentNamespaceTest = parentNamespaceTest, - _vectorOfReferrables = vectorOfReferrables, - _singleWeakReference = singleWeakReference, - _vectorOfWeakReferences = vectorOfWeakReferences, - _vectorOfStrongReferrables = vectorOfStrongReferrables, - _coOwningReference = coOwningReference, - _vectorOfCoOwningReferences = vectorOfCoOwningReferences, - _nonOwningReference = nonOwningReference, - _vectorOfNonOwningReferences = vectorOfNonOwningReferences, - _anyUniqueType = anyUniqueType, - _anyUnique = anyUnique, - _anyAmbiguousType = anyAmbiguousType, - _anyAmbiguous = anyAmbiguous, - _vectorOfEnums = vectorOfEnums, - _signedEnum = signedEnum, - _testrequirednestedflatbuffer = testrequirednestedflatbuffer, - _scalarKeySortedTables = scalarKeySortedTables, - _nativeInline = nativeInline, - _longEnumNonEnumDefault = longEnumNonEnumDefault, - _longEnumNormalDefault = longEnumNormalDefault, - _nanDefault = nanDefault, - _infDefault = infDefault, - _positiveInfDefault = positiveInfDefault, - _infinityDefault = infinityDefault, - _positiveInfinityDefault = positiveInfinityDefault, - _negativeInfDefault = negativeInfDefault, - _negativeInfinityDefault = negativeInfinityDefault, - _doubleInfDefault = doubleInfDefault; + }) : _pos = pos, + _mana = mana, + _hp = hp, + _name = name, + _inventory = inventory, + _color = color, + _testType = testType, + _test = test, + _test4 = test4, + _testarrayofstring = testarrayofstring, + _testarrayoftables = testarrayoftables, + _enemy = enemy, + _testnestedflatbuffer = testnestedflatbuffer, + _testempty = testempty, + _testbool = testbool, + _testhashs32Fnv1 = testhashs32Fnv1, + _testhashu32Fnv1 = testhashu32Fnv1, + _testhashs64Fnv1 = testhashs64Fnv1, + _testhashu64Fnv1 = testhashu64Fnv1, + _testhashs32Fnv1a = testhashs32Fnv1a, + _testhashu32Fnv1a = testhashu32Fnv1a, + _testhashs64Fnv1a = testhashs64Fnv1a, + _testhashu64Fnv1a = testhashu64Fnv1a, + _testarrayofbools = testarrayofbools, + _testf = testf, + _testf2 = testf2, + _testf3 = testf3, + _testarrayofstring2 = testarrayofstring2, + _testarrayofsortedstruct = testarrayofsortedstruct, + _flex = flex, + _test5 = test5, + _vectorOfLongs = vectorOfLongs, + _vectorOfDoubles = vectorOfDoubles, + _parentNamespaceTest = parentNamespaceTest, + _vectorOfReferrables = vectorOfReferrables, + _singleWeakReference = singleWeakReference, + _vectorOfWeakReferences = vectorOfWeakReferences, + _vectorOfStrongReferrables = vectorOfStrongReferrables, + _coOwningReference = coOwningReference, + _vectorOfCoOwningReferences = vectorOfCoOwningReferences, + _nonOwningReference = nonOwningReference, + _vectorOfNonOwningReferences = vectorOfNonOwningReferences, + _anyUniqueType = anyUniqueType, + _anyUnique = anyUnique, + _anyAmbiguousType = anyAmbiguousType, + _anyAmbiguous = anyAmbiguous, + _vectorOfEnums = vectorOfEnums, + _signedEnum = signedEnum, + _testrequirednestedflatbuffer = testrequirednestedflatbuffer, + _scalarKeySortedTables = scalarKeySortedTables, + _nativeInline = nativeInline, + _longEnumNonEnumDefault = longEnumNonEnumDefault, + _longEnumNormalDefault = longEnumNormalDefault, + _nanDefault = nanDefault, + _infDefault = infDefault, + _positiveInfDefault = positiveInfDefault, + _infinityDefault = infinityDefault, + _positiveInfinityDefault = positiveInfinityDefault, + _negativeInfDefault = negativeInfDefault, + _negativeInfinityDefault = negativeInfinityDefault, + _doubleInfDefault = doubleInfDefault; /// Finish building, and store into the [fbBuilder]. @override int finish(fb.Builder fbBuilder) { - final int? nameOffset = _name == null ? null + final int? nameOffset = _name == null + ? null : fbBuilder.writeString(_name!); - final int? inventoryOffset = _inventory == null ? null + final int? inventoryOffset = _inventory == null + ? null : fbBuilder.writeListUint8(_inventory!); final int? testOffset = _test?.getOrCreateOffset(fbBuilder); - final int? test4Offset = _test4 == null ? null + final int? test4Offset = _test4 == null + ? null : fbBuilder.writeListOfStructs(_test4!); - final int? testarrayofstringOffset = _testarrayofstring == null ? null - : fbBuilder.writeList(_testarrayofstring!.map(fbBuilder.writeString).toList()); - final int? testarrayoftablesOffset = _testarrayoftables == null ? null - : fbBuilder.writeList(_testarrayoftables!.map((b) => b.getOrCreateOffset(fbBuilder)).toList()); + final int? testarrayofstringOffset = _testarrayofstring == null + ? null + : fbBuilder.writeList( + _testarrayofstring!.map(fbBuilder.writeString).toList(), + ); + final int? testarrayoftablesOffset = _testarrayoftables == null + ? null + : fbBuilder.writeList( + _testarrayoftables! + .map((b) => b.getOrCreateOffset(fbBuilder)) + .toList(), + ); final int? enemyOffset = _enemy?.getOrCreateOffset(fbBuilder); - final int? testnestedflatbufferOffset = _testnestedflatbuffer == null ? null + final int? testnestedflatbufferOffset = _testnestedflatbuffer == null + ? null : fbBuilder.writeListUint8(_testnestedflatbuffer!); final int? testemptyOffset = _testempty?.getOrCreateOffset(fbBuilder); - final int? testarrayofboolsOffset = _testarrayofbools == null ? null + final int? testarrayofboolsOffset = _testarrayofbools == null + ? null : fbBuilder.writeListBool(_testarrayofbools!); - final int? testarrayofstring2Offset = _testarrayofstring2 == null ? null - : fbBuilder.writeList(_testarrayofstring2!.map(fbBuilder.writeString).toList()); - final int? testarrayofsortedstructOffset = _testarrayofsortedstruct == null ? null + final int? testarrayofstring2Offset = _testarrayofstring2 == null + ? null + : fbBuilder.writeList( + _testarrayofstring2!.map(fbBuilder.writeString).toList(), + ); + final int? testarrayofsortedstructOffset = _testarrayofsortedstruct == null + ? null : fbBuilder.writeListOfStructs(_testarrayofsortedstruct!); - final int? flexOffset = _flex == null ? null + final int? flexOffset = _flex == null + ? null : fbBuilder.writeListUint8(_flex!); - final int? test5Offset = _test5 == null ? null + final int? test5Offset = _test5 == null + ? null : fbBuilder.writeListOfStructs(_test5!); - final int? vectorOfLongsOffset = _vectorOfLongs == null ? null + final int? vectorOfLongsOffset = _vectorOfLongs == null + ? null : fbBuilder.writeListInt64(_vectorOfLongs!); - final int? vectorOfDoublesOffset = _vectorOfDoubles == null ? null + final int? vectorOfDoublesOffset = _vectorOfDoubles == null + ? null : fbBuilder.writeListFloat64(_vectorOfDoubles!); - final int? parentNamespaceTestOffset = _parentNamespaceTest?.getOrCreateOffset(fbBuilder); - final int? vectorOfReferrablesOffset = _vectorOfReferrables == null ? null - : fbBuilder.writeList(_vectorOfReferrables!.map((b) => b.getOrCreateOffset(fbBuilder)).toList()); - final int? vectorOfWeakReferencesOffset = _vectorOfWeakReferences == null ? null + final int? parentNamespaceTestOffset = _parentNamespaceTest + ?.getOrCreateOffset(fbBuilder); + final int? vectorOfReferrablesOffset = _vectorOfReferrables == null + ? null + : fbBuilder.writeList( + _vectorOfReferrables! + .map((b) => b.getOrCreateOffset(fbBuilder)) + .toList(), + ); + final int? vectorOfWeakReferencesOffset = _vectorOfWeakReferences == null + ? null : fbBuilder.writeListUint64(_vectorOfWeakReferences!); - final int? vectorOfStrongReferrablesOffset = _vectorOfStrongReferrables == null ? null - : fbBuilder.writeList(_vectorOfStrongReferrables!.map((b) => b.getOrCreateOffset(fbBuilder)).toList()); - final int? vectorOfCoOwningReferencesOffset = _vectorOfCoOwningReferences == null ? null + final int? vectorOfStrongReferrablesOffset = + _vectorOfStrongReferrables == null + ? null + : fbBuilder.writeList( + _vectorOfStrongReferrables! + .map((b) => b.getOrCreateOffset(fbBuilder)) + .toList(), + ); + final int? vectorOfCoOwningReferencesOffset = + _vectorOfCoOwningReferences == null + ? null : fbBuilder.writeListUint64(_vectorOfCoOwningReferences!); - final int? vectorOfNonOwningReferencesOffset = _vectorOfNonOwningReferences == null ? null + final int? vectorOfNonOwningReferencesOffset = + _vectorOfNonOwningReferences == null + ? null : fbBuilder.writeListUint64(_vectorOfNonOwningReferences!); final int? anyUniqueOffset = _anyUnique?.getOrCreateOffset(fbBuilder); final int? anyAmbiguousOffset = _anyAmbiguous?.getOrCreateOffset(fbBuilder); - final int? vectorOfEnumsOffset = _vectorOfEnums == null ? null - : fbBuilder.writeListUint8(_vectorOfEnums!.map((f) => f.value).toList()); - final int? testrequirednestedflatbufferOffset = _testrequirednestedflatbuffer == null ? null + final int? vectorOfEnumsOffset = _vectorOfEnums == null + ? null + : fbBuilder.writeListUint8( + _vectorOfEnums!.map((f) => f.value).toList(), + ); + final int? testrequirednestedflatbufferOffset = + _testrequirednestedflatbuffer == null + ? null : fbBuilder.writeListUint8(_testrequirednestedflatbuffer!); - final int? scalarKeySortedTablesOffset = _scalarKeySortedTables == null ? null - : fbBuilder.writeList(_scalarKeySortedTables!.map((b) => b.getOrCreateOffset(fbBuilder)).toList()); + final int? scalarKeySortedTablesOffset = _scalarKeySortedTables == null + ? null + : fbBuilder.writeList( + _scalarKeySortedTables! + .map((b) => b.getOrCreateOffset(fbBuilder)) + .toList(), + ); fbBuilder.startTable(62); if (_pos != null) { fbBuilder.addStruct(0, _pos!.finish(fbBuilder)); @@ -2120,6 +2433,7 @@ class MonsterObjectBuilder extends fb.ObjectBuilder { return fbBuilder.buffer; } } + class TypeAliases { TypeAliases._(this._bc, this._bcOffset); factory TypeAliases(List bytes) { @@ -2142,8 +2456,11 @@ class TypeAliases { int get u64 => const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 18, 0); double get f32 => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 20, 0.0); double get f64 => const fb.Float64Reader().vTableGet(_bc, _bcOffset, 22, 0.0); - List? get v8 => const fb.Int8ListReader().vTableGetNullable(_bc, _bcOffset, 24); - List? get vf64 => const fb.ListReader(fb.Float64Reader()).vTableGetNullable(_bc, _bcOffset, 26); + List? get v8 => + const fb.Int8ListReader().vTableGetNullable(_bc, _bcOffset, 24); + List? get vf64 => const fb.ListReader( + fb.Float64Reader(), + ).vTableGetNullable(_bc, _bcOffset, 26); @override String toString() { @@ -2151,18 +2468,24 @@ class TypeAliases { } TypeAliasesT unpack() => TypeAliasesT( - i8: i8, - u8: u8, - i16: i16, - u16: u16, - i32: i32, - u32: u32, - i64: i64, - u64: u64, - f32: f32, - f64: f64, - v8: const fb.Int8ListReader(lazy: false).vTableGetNullable(_bc, _bcOffset, 24), - vf64: const fb.ListReader(fb.Float64Reader(), lazy: false).vTableGetNullable(_bc, _bcOffset, 26)); + i8: i8, + u8: u8, + i16: i16, + u16: u16, + i32: i32, + u32: u32, + i64: i64, + u64: u64, + f32: f32, + f64: f64, + v8: const fb.Int8ListReader( + lazy: false, + ).vTableGetNullable(_bc, _bcOffset, 24), + vf64: const fb.ListReader( + fb.Float64Reader(), + lazy: false, + ).vTableGetNullable(_bc, _bcOffset, 26), + ); static int pack(fb.Builder fbBuilder, TypeAliasesT? object) { if (object == null) return 0; @@ -2185,24 +2508,25 @@ class TypeAliasesT implements fb.Packable { List? vf64; TypeAliasesT({ - this.i8 = 0, - this.u8 = 0, - this.i16 = 0, - this.u16 = 0, - this.i32 = 0, - this.u32 = 0, - this.i64 = 0, - this.u64 = 0, - this.f32 = 0.0, - this.f64 = 0.0, - this.v8, - this.vf64}); + this.i8 = 0, + this.u8 = 0, + this.i16 = 0, + this.u16 = 0, + this.i32 = 0, + this.u32 = 0, + this.i64 = 0, + this.u64 = 0, + this.f32 = 0.0, + this.f64 = 0.0, + this.v8, + this.vf64, + }); @override int pack(fb.Builder fbBuilder) { - final int? v8Offset = v8 == null ? null - : fbBuilder.writeListInt8(v8!); - final int? vf64Offset = vf64 == null ? null + final int? v8Offset = v8 == null ? null : fbBuilder.writeListInt8(v8!); + final int? vf64Offset = vf64 == null + ? null : fbBuilder.writeListFloat64(vf64!); fbBuilder.startTable(12); fbBuilder.addInt8(0, i8); @@ -2230,8 +2554,8 @@ class _TypeAliasesReader extends fb.TableReader { const _TypeAliasesReader(); @override - TypeAliases createObject(fb.BufferContext bc, int offset) => - TypeAliases._(bc, offset); + TypeAliases createObject(fb.BufferContext bc, int offset) => + TypeAliases._(bc, offset); } class TypeAliasesBuilder { @@ -2247,46 +2571,57 @@ class TypeAliasesBuilder { fbBuilder.addInt8(0, i8); return fbBuilder.offset; } + int addU8(int? u8) { fbBuilder.addUint8(1, u8); return fbBuilder.offset; } + int addI16(int? i16) { fbBuilder.addInt16(2, i16); return fbBuilder.offset; } + int addU16(int? u16) { fbBuilder.addUint16(3, u16); return fbBuilder.offset; } + int addI32(int? i32) { fbBuilder.addInt32(4, i32); return fbBuilder.offset; } + int addU32(int? u32) { fbBuilder.addUint32(5, u32); return fbBuilder.offset; } + int addI64(int? i64) { fbBuilder.addInt64(6, i64); return fbBuilder.offset; } + int addU64(int? u64) { fbBuilder.addUint64(7, u64); return fbBuilder.offset; } + int addF32(double? f32) { fbBuilder.addFloat32(8, f32); return fbBuilder.offset; } + int addF64(double? f64) { fbBuilder.addFloat64(9, f64); return fbBuilder.offset; } + int addV8Offset(int? offset) { fbBuilder.addOffset(10, offset); return fbBuilder.offset; } + int addVf64Offset(int? offset) { fbBuilder.addOffset(11, offset); return fbBuilder.offset; @@ -2324,26 +2659,25 @@ class TypeAliasesObjectBuilder extends fb.ObjectBuilder { double? f64, List? v8, List? vf64, - }) - : _i8 = i8, - _u8 = u8, - _i16 = i16, - _u16 = u16, - _i32 = i32, - _u32 = u32, - _i64 = i64, - _u64 = u64, - _f32 = f32, - _f64 = f64, - _v8 = v8, - _vf64 = vf64; + }) : _i8 = i8, + _u8 = u8, + _i16 = i16, + _u16 = u16, + _i32 = i32, + _u32 = u32, + _i64 = i64, + _u64 = u64, + _f32 = f32, + _f64 = f64, + _v8 = v8, + _vf64 = vf64; /// Finish building, and store into the [fbBuilder]. @override int finish(fb.Builder fbBuilder) { - final int? v8Offset = _v8 == null ? null - : fbBuilder.writeListInt8(_v8!); - final int? vf64Offset = _vf64 == null ? null + final int? v8Offset = _v8 == null ? null : fbBuilder.writeListInt8(_v8!); + final int? vf64Offset = _vf64 == null + ? null : fbBuilder.writeListFloat64(_vf64!); fbBuilder.startTable(12); fbBuilder.addInt8(0, _i8); diff --git a/dart/test/monster_test_my_game_generated.dart b/dart/test/monster_test_my_game_generated.dart index 461d06dfa85..7b856bf725a 100644 --- a/dart/test/monster_test_my_game_generated.dart +++ b/dart/test/monster_test_my_game_generated.dart @@ -4,12 +4,12 @@ library my_game; import 'dart:typed_data' show Uint8List; -import 'package:flat_buffers/flat_buffers.dart' as fb; -import './monster_test_my_game.example_generated.dart' as my_game_example; -import './monster_test_my_game.example2_generated.dart' as my_game_example2; +import 'package:flat_buffers/flat_buffers.dart' as fb; import './include_test1_generated.dart'; +import './monster_test_my_game.example2_generated.dart' as my_game_example2; +import './monster_test_my_game.example_generated.dart' as my_game_example; class InParentNamespace { InParentNamespace._(this._bc, this._bcOffset); @@ -23,7 +23,6 @@ class InParentNamespace { final fb.BufferContext _bc; final int _bcOffset; - @override String toString() { return 'InParentNamespace{}'; @@ -54,12 +53,11 @@ class _InParentNamespaceReader extends fb.TableReader { const _InParentNamespaceReader(); @override - InParentNamespace createObject(fb.BufferContext bc, int offset) => - InParentNamespace._(bc, offset); + InParentNamespace createObject(fb.BufferContext bc, int offset) => + InParentNamespace._(bc, offset); } class InParentNamespaceObjectBuilder extends fb.ObjectBuilder { - InParentNamespaceObjectBuilder(); /// Finish building, and store into the [fbBuilder]. diff --git a/docs/README.md b/docs/README.md index b4695a2eb14..06e4310f270 100644 --- a/docs/README.md +++ b/docs/README.md @@ -6,7 +6,7 @@ https://flatbuffers.dev. ## Local Building -The documentation can be built and served locally during development, see [https//flatbuffers.dev/contributing/#local-development] for full details. +The documentation can be built and served locally during development, see for full details. __tl;dr__ @@ -21,4 +21,4 @@ Build and Serve: ``` mkdocs serve -f docs/mkdocs.yml -``` \ No newline at end of file +``` diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml index ce1496512d1..cbcbb48de28 100644 --- a/docs/mkdocs.yml +++ b/docs/mkdocs.yml @@ -139,7 +139,7 @@ nav: - Dart: "languages/dart.md" - Go: "languages/go.md" - Java: "languages/java.md" - - JavasScript: "languages/javascript.md" + - JavaScript: "languages/javascript.md" - Kotlin: "languages/kotlin.md" - Lobster: "languages/lobster.md" - Lua: "languages/lua.md" diff --git a/docs/source/flatc.md b/docs/source/flatc.md index 6fcbf8f50de..5ef6b4e3387 100644 --- a/docs/source/flatc.md +++ b/docs/source/flatc.md @@ -131,7 +131,7 @@ list of `FILES...`. - `--gen-mutable` : Generate additional non-const accessors for mutating FlatBuffers in-place. -- `--gen-onefile` : Generate single output file for C#, Go, and Python. +- `--gen-onefile` : Generate a single output file for C#, Go, Java, Kotlin and Python. - `--gen-name-strings` : Generate type name functions for C++. @@ -259,6 +259,8 @@ list of `FILES...`. - `--python-typing` : Generate Python type annotations +- `--python-decode-obj-api-strings` : Decode bytes automaticaly with utf-8 + Additional gRPC options: - `--grpc-filename-suffix`: `[C++]` An optional suffix for the generated diff --git a/docs/source/index.md b/docs/source/index.md index 269fda309b1..042ad8bc447 100644 --- a/docs/source/index.md +++ b/docs/source/index.md @@ -21,15 +21,15 @@ It is available as Open Source on - :material-memory:{ .lg .middle } **Memory Efficiency and Speed** --- - The only memory needed to access your data is that of the buffer. No heap is - required. + The only memory needed to access your data is that of the buffer. + No heap is required. - :material-compare-horizontal:{ .lg .middle } **Backwards and Forwards Compatibility** --- - The only memory needed to access your data is that of the buffer. No heap is - required. + FlatBuffers enables the schema to evolve over time while still maintaining + forwards and backwards compatibility with old flatbuffers. - :material-scale-off:{ .lg .middle } **Small Footprint** diff --git a/docs/source/languages/cpp.md b/docs/source/languages/cpp.md index e44e34bbf1b..7e99d4efd15 100644 --- a/docs/source/languages/cpp.md +++ b/docs/source/languages/cpp.md @@ -419,7 +419,8 @@ Each root type will have a verification function generated for it, e.g. for `Monster`, you can call: ```cpp - bool ok = VerifyMonsterBuffer(Verifier(buf, len)); + Verifier verifier(buf, len); + bool ok = VerifyMonsterBuffer(verifier); ``` if `ok` is true, the buffer is safe to read. diff --git a/docs/source/languages/php.md b/docs/source/languages/php.md index 8cb96648180..e4391e03a54 100644 --- a/docs/source/languages/php.md +++ b/docs/source/languages/php.md @@ -48,7 +48,7 @@ function). Then you can read a FlatBuffer binary file, which you pass the contents of to the `GetRootAsMonster` function: ~~~{.php} - // It is recommended that your use PSR autoload when using FlatBuffers in PHP. + // It is recommended that you use PSR autoload when using FlatBuffers in PHP. // Here is an example: function __autoload($class_name) { // The last segment of the class name matches the file name. @@ -69,7 +69,7 @@ pass the contents of to the `GetRootAsMonster` function: // Read the contents of the FlatBuffer binary file. $filename = "monster.dat"; $handle = fopen($filename, "rb"); - $contents = $fread($handle, filesize($filename)); + $contents = fread($handle, filesize($filename)); fclose($handle); // Pass the contents to `GetRootAsMonster`. diff --git a/docs/source/languages/rust.md b/docs/source/languages/rust.md index 0d5af187173..04f7f02e669 100644 --- a/docs/source/languages/rust.md +++ b/docs/source/languages/rust.md @@ -177,6 +177,34 @@ functions require a mutable (aka exclusive) reference which can only be created when no other references to the `FlatBufferBuilder` exist, and may not be copied within the same thread, let alone to a second thread. +## Reflection (& Resizing) + +There is experimental support for reflection in FlatBuffers, allowing you to +read and write data even if you don't know the exact format of a buffer, and +even allows you to change sizes of strings in-place. + +The way this works is very elegant; there is actually a FlatBuffer schema that +describes schemas (\!) which you can find in `reflection/reflection.fbs`. +The compiler, `flatc`, can write out any schemas it has just parsed as a binary +FlatBuffer, corresponding to this meta-schema. + +Loading in one of these binary schemas at runtime allows you to traverse any +FlatBuffer data that corresponds to it without knowing the exact format. You +can query what fields are present, and then read/write them after. + +For convenient field manipulation, you can use the crate +`flatbuffers-reflection` which includes both the generated code from the meta +schema, as well as a lot of helper functions. + +And example of usage, for the time being, can be found in +`tests/rust_reflection_test/src/lib.rs`. Two sets of APIs are provided: + +- [Unsafe getters/setters](https://docs.rs/flatbuffers-reflection/latest/flatbuffers_reflection/#functions), + which you can use when you are processing trusted data (either from a source you know, or has been verified) + +- 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 + ## Useful tools created by others * [flatc-rust](https://github.com/frol/flatc-rust) - FlatBuffers compiler diff --git a/docs/source/languages/swift.md b/docs/source/languages/swift.md index b967c54d19b..78046c0d444 100644 --- a/docs/source/languages/swift.md +++ b/docs/source/languages/swift.md @@ -57,7 +57,7 @@ a data object from the server, which you can pass into the `GetRootAsMonster` fu let url = URL(fileURLWithPath: path, isDirectory: true).appendingPathComponent("monsterdata_test").appendingPathExtension("mon") guard let data = try? Data(contentsOf: url) else { return } - let monster = Monster.getRootAsMonster(bb: ByteBuffer(data: data)) + let monster: Monster = try! getCheckedRoot(byteBuffer: &byteBuffer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Now you can access values like this: diff --git a/docs/source/quick_start.md b/docs/source/quick_start.md index 1be1061ce1f..2f642f34ba6 100644 --- a/docs/source/quick_start.md +++ b/docs/source/quick_start.md @@ -30,7 +30,7 @@ See the [Tutorial](tutorial.md) for a more in depth guide. code: ```sh - ./flatc --cpp --rust mosnter.fbs + ./flatc --cpp --rust monster.fbs ``` Which generates `monster_generated.h` and `monster_generated.rs` files. diff --git a/docs/source/tutorial.md b/docs/source/tutorial.md index cfa0b1c9917..e43e1367cfa 100644 --- a/docs/source/tutorial.md +++ b/docs/source/tutorial.md @@ -2011,6 +2011,8 @@ like so: let buf = builder.sizedByteArray // or you can use to get an object of type Data let bufData = ByteBuffer(data: builder.data) + // or + let buf = builder.sizedBuffer ``` === "TypeScript" diff --git a/eslint.config.mjs b/eslint.config.mjs new file mode 100644 index 00000000000..4cba923cfdf --- /dev/null +++ b/eslint.config.mjs @@ -0,0 +1,10 @@ +import globals from "globals"; +import pluginJs from "@eslint/js"; +import tseslint from "typescript-eslint"; + +export default [ + {files: ["**/*.{js,mjs,cjs,ts}"]}, + {languageOptions: { globals: {...globals.browser, ...globals.node} }}, + pluginJs.configs.recommended, + ...tseslint.configs.recommended, +]; diff --git a/examples/go-echo/client/client.go b/examples/go-echo/client/client.go index be8fd7e8524..c6c1a3926d2 100644 --- a/examples/go-echo/client/client.go +++ b/examples/go-echo/client/client.go @@ -28,12 +28,12 @@ func ReadResponse(r *http.Response) { res := net.GetRootAsResponse(body, 0) player := res.Player(nil) - + fmt.Printf("Got response (name: %v, hp: %v)\n", string(player.Name()), player.Hp()) } func main() { - body := RequestBody() + body := RequestBody() req, err := http.NewRequest("POST", "http://localhost:8080/echo", body) if err != nil { fmt.Println(err) diff --git a/examples/go-echo/hero/Warrior.go b/examples/go-echo/hero/Warrior.go index 0e9802c189a..a369043f0bc 100644 --- a/examples/go-echo/hero/Warrior.go +++ b/examples/go-echo/hero/Warrior.go @@ -8,7 +8,7 @@ import ( type WarriorT struct { Name string `json:"name"` - Hp uint32 `json:"hp"` + Hp uint32 `json:"hp"` } func (t *WarriorT) Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT { diff --git a/go/builder.go b/go/builder.go index 5d90e8ef982..b76e8f9c0ab 100644 --- a/go/builder.go +++ b/go/builder.go @@ -104,15 +104,18 @@ func (b *Builder) StartObject(numfields int) { // logically-equal vtables will be deduplicated. // // A vtable has the following format: -// -// -// * N, where N is the number of fields in -// the schema for this type. Includes deprecated fields. +// +// +// +// * N, where N is the number of fields in +// the schema for this type. Includes deprecated fields. +// // Thus, a vtable is made of 2 + N elements, each SizeVOffsetT bytes wide. // // An object has the following format: -// -// + +// +// +// + func (b *Builder) WriteVtable() (n UOffsetT) { // Prepend a zero scalar to the object. Later in this function we'll // write an offset here that points to the object's vtable: @@ -296,8 +299,9 @@ func (b *Builder) PrependUOffsetT(off UOffsetT) { // StartVector initializes bookkeeping for writing a new vector. // // A vector has the following format: -// -// +, where T is the type of elements of this vector. +// +// +// +, where T is the type of elements of this vector. func (b *Builder) StartVector(elemSize, numElems, alignment int) UOffsetT { b.assertNotNested() b.nested = true diff --git a/go/grpc.go b/go/grpc.go index 15f1a510d3b..56d7e9f2ef0 100644 --- a/go/grpc.go +++ b/go/grpc.go @@ -1,7 +1,17 @@ package flatbuffers -// Codec implements gRPC-go Codec which is used to encode and decode messages. -var Codec = "flatbuffers" +import "errors" + +var ( + // Codec implements gRPC-go Codec which is used to encode and decode messages. + Codec = "flatbuffers" + + // ErrInsufficientData is returned when the data is too short to read the root UOffsetT. + ErrInsufficientData = errors.New("insufficient data") + + // ErrInvalidRootOffset is returned when the root UOffsetT is out of bounds. + ErrInvalidRootOffset = errors.New("invalid root offset") +) // FlatbuffersCodec defines the interface gRPC uses to encode and decode messages. Note // that implementations of this interface must be thread safe; a Codec's @@ -15,7 +25,21 @@ func (FlatbuffersCodec) Marshal(v interface{}) ([]byte, error) { // Unmarshal parses the wire format into v. func (FlatbuffersCodec) Unmarshal(data []byte, v interface{}) error { - v.(flatbuffersInit).Init(data, GetUOffsetT(data)) + // Need at least 4 bytes to read the root table offset (UOffsetT). + // Vtable soffset_t and metadata are read later during field access. + if len(data) < SizeUOffsetT { + return ErrInsufficientData + } + + off := GetUOffsetT(data) + + // The root UOffsetT must be within the data buffer + // Compare in the unsigned domain to avoid signedness pitfalls + if off > UOffsetT(len(data)-SizeUOffsetT) { + return ErrInvalidRootOffset + } + + v.(flatbuffersInit).Init(data, off) return nil } diff --git a/goldens/README.md b/goldens/README.md index 00bbdc01186..856c0efceed 100644 --- a/goldens/README.md +++ b/goldens/README.md @@ -3,8 +3,8 @@ This directory is a repository for the generated files of `flatc`. We check in the generated code so we can see, during a PR review, how the -changes affect the generated output. Its also useful as a reference to point too -as how things work across various languages. +changes affect the generated output. It's also useful as a reference to show +how things work across various languages. These files are **NOT** intended to be depended on by any code, such as tests or or compiled examples. diff --git a/goldens/cpp/basic_generated.h b/goldens/cpp/basic_generated.h index f4600d71124..2c5391fd848 100644 --- a/goldens/cpp/basic_generated.h +++ b/goldens/cpp/basic_generated.h @@ -9,8 +9,8 @@ // Ensure the included flatbuffers.h is the same version as when this file was // generated, otherwise it may not be compatible. static_assert(FLATBUFFERS_VERSION_MAJOR == 25 && - FLATBUFFERS_VERSION_MINOR == 2 && - FLATBUFFERS_VERSION_REVISION == 10, + FLATBUFFERS_VERSION_MINOR == 9 && + FLATBUFFERS_VERSION_REVISION == 23, "Non-compatible flatbuffers version included"); namespace flatbuffers { diff --git a/goldens/cpp/generate.py b/goldens/cpp/generate.py index cdc7e8c37b5..c71dbc61080 100644 --- a/goldens/cpp/generate.py +++ b/goldens/cpp/generate.py @@ -2,9 +2,9 @@ def flatc(options, schema): - # Wrap the golden flatc generator with C++ specifics - flatc_golden(options=["--cpp"] + options, schema=schema, prefix="cpp") + # Wrap the golden flatc generator with C++ specifics + flatc_golden(options=["--cpp"] + options, schema=schema, prefix="cpp") def GenerateCpp(): - flatc([], "basic.fbs") + flatc([], "basic.fbs") diff --git a/goldens/csharp/flatbuffers/goldens/Galaxy.cs b/goldens/csharp/flatbuffers/goldens/Galaxy.cs index f947a1a7af2..471e9b3df7d 100644 --- a/goldens/csharp/flatbuffers/goldens/Galaxy.cs +++ b/goldens/csharp/flatbuffers/goldens/Galaxy.cs @@ -13,7 +13,7 @@ public struct Galaxy : IFlatbufferObject { private Table __p; public ByteBuffer ByteBuffer { get { return __p.bb; } } - public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_25_2_10(); } + public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_25_9_23(); } public static Galaxy GetRootAsGalaxy(ByteBuffer _bb) { return GetRootAsGalaxy(_bb, new Galaxy()); } public static Galaxy GetRootAsGalaxy(ByteBuffer _bb, Galaxy obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); } public void __init(int _i, ByteBuffer _bb) { __p = new Table(_i, _bb); } diff --git a/goldens/csharp/flatbuffers/goldens/Universe.cs b/goldens/csharp/flatbuffers/goldens/Universe.cs index 7e8b80291c1..9f74a1daedd 100644 --- a/goldens/csharp/flatbuffers/goldens/Universe.cs +++ b/goldens/csharp/flatbuffers/goldens/Universe.cs @@ -13,7 +13,7 @@ public struct Universe : IFlatbufferObject { private Table __p; public ByteBuffer ByteBuffer { get { return __p.bb; } } - public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_25_2_10(); } + public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_25_9_23(); } public static Universe GetRootAsUniverse(ByteBuffer _bb) { return GetRootAsUniverse(_bb, new Universe()); } public static Universe GetRootAsUniverse(ByteBuffer _bb, Universe obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); } public static bool VerifyUniverse(ByteBuffer _bb) {Google.FlatBuffers.Verifier verifier = new Google.FlatBuffers.Verifier(_bb); return verifier.VerifyBuffer("", false, UniverseVerify.Verify); } diff --git a/goldens/csharp/generate.py b/goldens/csharp/generate.py index 86a3a80f5ad..11f5b0572f1 100644 --- a/goldens/csharp/generate.py +++ b/goldens/csharp/generate.py @@ -2,9 +2,9 @@ def flatc(options, schema): - # Wrap the golden flatc generator with C# specifics - flatc_golden(options=["--csharp"] + options, schema=schema, prefix="csharp") + # Wrap the golden flatc generator with C# specifics + flatc_golden(options=["--csharp"] + options, schema=schema, prefix="csharp") def GenerateCSharp(): - flatc([], "basic.fbs") + flatc([], "basic.fbs") diff --git a/goldens/dart/generate.py b/goldens/dart/generate.py index a92070c2653..4d667c01b59 100644 --- a/goldens/dart/generate.py +++ b/goldens/dart/generate.py @@ -2,9 +2,9 @@ def flatc(options, schema): - # Wrap the golden flatc generator with Dart specifics - flatc_golden(options=["--dart"] + options, schema=schema, prefix="dart") + # Wrap the golden flatc generator with Dart specifics + flatc_golden(options=["--dart"] + options, schema=schema, prefix="dart") def GenerateDart(): - flatc([], "basic.fbs") + flatc([], "basic.fbs") diff --git a/goldens/go/generate.py b/goldens/go/generate.py index 358c42c30bb..1f809aa64d3 100644 --- a/goldens/go/generate.py +++ b/goldens/go/generate.py @@ -2,9 +2,9 @@ def flatc(options, schema): - # Wrap the golden flatc generator with Go specifics - flatc_golden(options=["--go"] + options, schema=schema, prefix="go") + # Wrap the golden flatc generator with Go specifics + flatc_golden(options=["--go"] + options, schema=schema, prefix="go") def GenerateGo(): - flatc([], "basic.fbs") + flatc([], "basic.fbs") diff --git a/goldens/golden_utils.py b/goldens/golden_utils.py index d2aab1330b6..576178e510b 100644 --- a/goldens/golden_utils.py +++ b/goldens/golden_utils.py @@ -1,5 +1,5 @@ -import sys from pathlib import Path +import sys # Get the path where this script is located so we can invoke the script from # any directory and have the paths work correctly. @@ -18,13 +18,13 @@ def flatc_golden(options, schema, prefix): - # wrap the generic flatc call with specifis for these goldens. - flatc( - options=options, - # where the files are generated, typically the language (e.g. "cpp"). - prefix=prefix, - # The schema are relative to the schema directory. - schema=str(Path(schema_path, schema)), - # Run flatc from this location. - cwd=script_path, - ) + # wrap the generic flatc call with specifis for these goldens. + flatc( + options=options, + # where the files are generated, typically the language (e.g. "cpp"). + prefix=prefix, + # The schema are relative to the schema directory. + schema=str(Path(schema_path, schema)), + # Run flatc from this location. + cwd=script_path, + ) diff --git a/goldens/java/flatbuffers/goldens/Galaxy.java b/goldens/java/flatbuffers/goldens/Galaxy.java index ef90810ea2f..c387318e2b3 100644 --- a/goldens/java/flatbuffers/goldens/Galaxy.java +++ b/goldens/java/flatbuffers/goldens/Galaxy.java @@ -21,7 +21,7 @@ @SuppressWarnings("unused") public final class Galaxy extends Table { - public static void ValidateVersion() { Constants.FLATBUFFERS_25_2_10(); } + public static void ValidateVersion() { Constants.FLATBUFFERS_25_9_23(); } public static Galaxy getRootAsGalaxy(ByteBuffer _bb) { return getRootAsGalaxy(_bb, new Galaxy()); } public static Galaxy getRootAsGalaxy(ByteBuffer _bb, Galaxy obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); } public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } diff --git a/goldens/java/flatbuffers/goldens/Universe.java b/goldens/java/flatbuffers/goldens/Universe.java index e8b46098860..c94db618ea9 100644 --- a/goldens/java/flatbuffers/goldens/Universe.java +++ b/goldens/java/flatbuffers/goldens/Universe.java @@ -21,7 +21,7 @@ @SuppressWarnings("unused") public final class Universe extends Table { - public static void ValidateVersion() { Constants.FLATBUFFERS_25_2_10(); } + public static void ValidateVersion() { Constants.FLATBUFFERS_25_9_23(); } public static Universe getRootAsUniverse(ByteBuffer _bb) { return getRootAsUniverse(_bb, new Universe()); } public static Universe getRootAsUniverse(ByteBuffer _bb, Universe obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); } public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } diff --git a/goldens/java/generate.py b/goldens/java/generate.py index cc1a8b29457..369ceb022be 100644 --- a/goldens/java/generate.py +++ b/goldens/java/generate.py @@ -2,9 +2,9 @@ def flatc(options, schema): - # Wrap the golden flatc generator with Java specifics - flatc_golden(options=["--java"] + options, schema=schema, prefix="java") + # Wrap the golden flatc generator with Java specifics + flatc_golden(options=["--java"] + options, schema=schema, prefix="java") def GenerateJava(): - flatc([], "basic.fbs") + flatc([], "basic.fbs") diff --git a/goldens/kotlin/flatbuffers/goldens/Galaxy.kt b/goldens/kotlin/flatbuffers/goldens/Galaxy.kt index 4307151cd88..4d3035b54f6 100644 --- a/goldens/kotlin/flatbuffers/goldens/Galaxy.kt +++ b/goldens/kotlin/flatbuffers/goldens/Galaxy.kt @@ -34,7 +34,7 @@ class Galaxy : Table() { return if(o != 0) bb.getLong(o + bb_pos) else 0L } companion object { - fun validateVersion() = Constants.FLATBUFFERS_25_2_10() + fun validateVersion() = Constants.FLATBUFFERS_25_9_23() fun getRootAsGalaxy(_bb: ByteBuffer): Galaxy = getRootAsGalaxy(_bb, Galaxy()) fun getRootAsGalaxy(_bb: ByteBuffer, obj: Galaxy): Galaxy { _bb.order(ByteOrder.LITTLE_ENDIAN) diff --git a/goldens/kotlin/flatbuffers/goldens/Universe.kt b/goldens/kotlin/flatbuffers/goldens/Universe.kt index b413b0e440c..b14127a016f 100644 --- a/goldens/kotlin/flatbuffers/goldens/Universe.kt +++ b/goldens/kotlin/flatbuffers/goldens/Universe.kt @@ -47,7 +47,7 @@ class Universe : Table() { val o = __offset(6); return if (o != 0) __vector_len(o) else 0 } companion object { - fun validateVersion() = Constants.FLATBUFFERS_25_2_10() + fun validateVersion() = Constants.FLATBUFFERS_25_9_23() fun getRootAsUniverse(_bb: ByteBuffer): Universe = getRootAsUniverse(_bb, Universe()) fun getRootAsUniverse(_bb: ByteBuffer, obj: Universe): Universe { _bb.order(ByteOrder.LITTLE_ENDIAN) diff --git a/goldens/kotlin/generate.py b/goldens/kotlin/generate.py index ac8b551743d..bab81ae8b17 100644 --- a/goldens/kotlin/generate.py +++ b/goldens/kotlin/generate.py @@ -2,9 +2,9 @@ def flatc(options, schema): - # Wrap the golden flatc generator with Kotlin specifics - flatc_golden(options=["--kotlin"] + options, schema=schema, prefix="kotlin") + # Wrap the golden flatc generator with Kotlin specifics + flatc_golden(options=["--kotlin"] + options, schema=schema, prefix="kotlin") def GenerateKotlin(): - flatc([], "basic.fbs") + flatc([], "basic.fbs") diff --git a/goldens/lobster/generate.py b/goldens/lobster/generate.py index cb75fda4b7a..bcd51509b55 100644 --- a/goldens/lobster/generate.py +++ b/goldens/lobster/generate.py @@ -2,9 +2,9 @@ def flatc(options, schema): - # Wrap the golden flatc generator with Lobster specifics - flatc_golden(options=["--lobster"] + options, schema=schema, prefix="lobster") + # Wrap the golden flatc generator with Lobster specifics + flatc_golden(options=["--lobster"] + options, schema=schema, prefix="lobster") def GenerateLobster(): - flatc([], "basic.fbs") + flatc([], "basic.fbs") diff --git a/goldens/lua/generate.py b/goldens/lua/generate.py index d099118a803..108a4d580ed 100644 --- a/goldens/lua/generate.py +++ b/goldens/lua/generate.py @@ -2,9 +2,9 @@ def flatc(options, schema): - # Wrap the golden flatc generator with Lua specifics - flatc_golden(options=["--lua"] + options, schema=schema, prefix="lua") + # Wrap the golden flatc generator with Lua specifics + flatc_golden(options=["--lua"] + options, schema=schema, prefix="lua") def GenerateLua(): - flatc([], "basic.fbs") + flatc([], "basic.fbs") diff --git a/goldens/nim/generate.py b/goldens/nim/generate.py index 16c0d3bcdb4..5aef75b1bec 100644 --- a/goldens/nim/generate.py +++ b/goldens/nim/generate.py @@ -2,9 +2,9 @@ def flatc(options, schema): - # Wrap the golden flatc generator with Nim specifics - flatc_golden(options=["--nim"] + options, schema=schema, prefix="nim") + # Wrap the golden flatc generator with Nim specifics + flatc_golden(options=["--nim"] + options, schema=schema, prefix="nim") def GenerateNim(): - flatc([], "basic.fbs") + flatc([], "basic.fbs") diff --git a/goldens/php/generate.py b/goldens/php/generate.py index 6e9144c675d..e167b7c8dbb 100644 --- a/goldens/php/generate.py +++ b/goldens/php/generate.py @@ -2,9 +2,9 @@ def flatc(options, schema): - # Wrap the golden flatc generator with PHP specifics - flatc_golden(options=["--php"] + options, schema=schema, prefix="php") + # Wrap the golden flatc generator with PHP specifics + flatc_golden(options=["--php"] + options, schema=schema, prefix="php") def GeneratePhp(): - flatc([], "basic.fbs") + flatc([], "basic.fbs") diff --git a/goldens/py/generate.py b/goldens/py/generate.py index ceff5d2d6b7..9ba58ea9ea3 100644 --- a/goldens/py/generate.py +++ b/goldens/py/generate.py @@ -2,9 +2,9 @@ def flatc(options, schema): - # Wrap the golden flatc generator with Python specifics - flatc_golden(options=["--python"] + options, schema=schema, prefix="py") + # Wrap the golden flatc generator with Python specifics + flatc_golden(options=["--python"] + options, schema=schema, prefix="py") def GeneratePython(): - flatc([], "basic.fbs") + flatc([], "basic.fbs") diff --git a/goldens/rust/basic_generated.rs b/goldens/rust/basic_generated.rs index 0e83305c854..2ed0ad8822c 100644 --- a/goldens/rust/basic_generated.rs +++ b/goldens/rust/basic_generated.rs @@ -37,7 +37,7 @@ 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: flatbuffers::Table::new(buf, loc) } + Self { _tab: unsafe { flatbuffers::Table::new(buf, loc) } } } } @@ -134,7 +134,7 @@ 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: flatbuffers::Table::new(buf, loc) } + Self { _tab: unsafe { flatbuffers::Table::new(buf, loc) } } } } @@ -288,14 +288,14 @@ pub fn size_prefixed_root_as_universe_with_opts<'b, 'o>( /// # Safety /// Callers must trust the given bytes do indeed contain a valid `Universe`. pub unsafe fn root_as_universe_unchecked(buf: &[u8]) -> Universe { - flatbuffers::root_unchecked::(buf) + 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 { - flatbuffers::size_prefixed_root_unchecked::(buf) + unsafe { flatbuffers::size_prefixed_root_unchecked::(buf) } } #[inline] pub fn finish_universe_buffer<'a, 'b, A: flatbuffers::Allocator + 'a>( diff --git a/goldens/rust/generate.py b/goldens/rust/generate.py index f3a568fef89..9d3d874daf1 100644 --- a/goldens/rust/generate.py +++ b/goldens/rust/generate.py @@ -2,9 +2,9 @@ def flatc(options, schema): - # Wrap the golden flatc generator with Rust specifics - flatc_golden(options=["--rust"] + options, schema=schema, prefix="rust") + # Wrap the golden flatc generator with Rust specifics + flatc_golden(options=["--rust"] + options, schema=schema, prefix="rust") def GenerateRust(): - flatc([], "basic.fbs") + flatc([], "basic.fbs") diff --git a/goldens/swift/basic_generated.swift b/goldens/swift/basic_generated.swift index 16ef66363b4..852868bfe7b 100644 --- a/goldens/swift/basic_generated.swift +++ b/goldens/swift/basic_generated.swift @@ -2,11 +2,15 @@ // swiftlint:disable all // swiftformat:disable all +#if canImport(Common) +import Common +#endif + import FlatBuffers public struct flatbuffers_goldens_Galaxy: FlatBufferObject, Verifiable { - static func validateVersion() { FlatBuffersVersion_25_2_10() } + static func validateVersion() { FlatBuffersVersion_25_9_23() } public var __buffer: ByteBuffer! { return _accessor.bb } private var _accessor: Table @@ -41,7 +45,7 @@ public struct flatbuffers_goldens_Galaxy: FlatBufferObject, Verifiable { public struct flatbuffers_goldens_Universe: FlatBufferObject, Verifiable { - static func validateVersion() { FlatBuffersVersion_25_2_10() } + static func validateVersion() { FlatBuffersVersion_25_9_23() } public var __buffer: ByteBuffer! { return _accessor.bb } private var _accessor: Table diff --git a/goldens/swift/generate.py b/goldens/swift/generate.py index ccdb97e7758..b16d83d514b 100644 --- a/goldens/swift/generate.py +++ b/goldens/swift/generate.py @@ -2,9 +2,9 @@ def flatc(options, schema): - # Wrap the golden flatc generator with Swift specifics - flatc_golden(options=["--swift"] + options, schema=schema, prefix="swift") + # Wrap the golden flatc generator with Swift specifics + flatc_golden(options=["--swift"] + options, schema=schema, prefix="swift") def GenerateSwift(): - flatc([], "basic.fbs") + flatc([], "basic.fbs") diff --git a/goldens/ts/basic.ts b/goldens/ts/basic.ts index bf563a0b8d8..ee62cf2d185 100644 --- a/goldens/ts/basic.ts +++ b/goldens/ts/basic.ts @@ -2,5 +2,5 @@ /* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ -export { Galaxy } from './galaxy.js'; -export { Universe } from './universe.js'; +export {Galaxy} from './galaxy.js'; +export {Universe} from './universe.js'; diff --git a/goldens/ts/generate.py b/goldens/ts/generate.py index ee072fdd637..64106388a7f 100644 --- a/goldens/ts/generate.py +++ b/goldens/ts/generate.py @@ -2,9 +2,9 @@ def flatc(options, schema): - # Wrap the golden flatc generator with Swift specifics - flatc_golden(options=["--ts"] + options, schema=schema, prefix="ts") + # Wrap the golden flatc generator with Swift specifics + flatc_golden(options=["--ts"] + options, schema=schema, prefix="ts") def GenerateTs(): - flatc([], "basic.fbs") + flatc([], "basic.fbs") diff --git a/grpc/README.md b/grpc/README.md index f46258fcb16..74aa86b46de 100644 --- a/grpc/README.md +++ b/grpc/README.md @@ -1,5 +1,4 @@ GRPC implementation and test -============================ NOTE: files in `src/` are shared with the GRPC project, and maintained there (any changes should be submitted to GRPC instead). These files are copied @@ -39,4 +38,64 @@ For Bazel users: ```shell $bazel test tests/... -``` \ No newline at end of file +``` + +## C++ Callback API Generation + +FlatBuffers gRPC C++ code generation now optionally supports the modern gRPC Callback API. + +To enable generation of a `CallbackService` skeleton alongside the existing `Service` and async mixins, invoke `flatc` with both `--grpc` and `--grpc-callback-api`: + +```shell +flatc --cpp --grpc --grpc-callback-api your_service.fbs +``` + +This adds (guarded by `#if defined(GRPC_CALLBACK_API_NONEXPERIMENTAL)`) a class: + +```cpp +class YourService::CallbackService : public ::grpc::Service { /* reactor virtuals */ }; +``` + +Each RPC shape maps to the appropriate reactor return type: + +- Unary -> `::grpc::ServerUnaryReactor*` Method(...) +- Client streaming -> `::grpc::ServerReadReactor*` +- Server streaming -> `::grpc::ServerWriteReactor*` +- Bidi streaming -> `::grpc::ServerBidiReactor*` + +Default generated implementations return `nullptr`; override in your derived class and return a reactor instance you manage (see gRPC docs for lifecycle patterns). + +If your gRPC library predates the stable callback API macro, the code inside the guard will be skipped (no breaking changes). Ensure you build against a recent gRPC (1.38+; verify current minimum in grpc repo) to use this feature. + +### Client Callback Stubs + +When `--grpc-callback-api` is supplied, the generated C++ client stub gains native callback / reactor based async methods in addition to the existing synchronous / generic async flavors, guarded by the same macro. For each RPC named `Foo`: + +Unary: + +``` +void async_Foo(::grpc::ClientContext*, const Request&, Response*, std::function); +void async_Foo(::grpc::ClientContext*, const Request&, Response*, ::grpc::ClientUnaryReactor*); +``` + +Client streaming: + +``` +::grpc::ClientWriteReactor* async_Foo(::grpc::ClientContext*, Response*, ::grpc::ClientWriteReactor*); +``` + +Server streaming: + +``` +::grpc::ClientReadReactor* async_Foo(::grpc::ClientContext*, const Request&, ::grpc::ClientReadReactor*); +``` + +Bidirectional streaming: + +``` +::grpc::ClientBidiReactor* async_Foo(::grpc::ClientContext*, ::grpc::ClientBidiReactor*); +``` + +These map directly onto the native gRPC callback API factories (e.g. `CallbackUnaryCall`, `ClientCallbackWriterFactory::Create`, etc.) and do not spawn threads. Override the appropriate reactor callbacks per gRPC's documentation to drive I/O. + +If your build uses an older gRPC lacking the non-experimental macro, these symbols will not be emitted, preserving backwards compatibility. diff --git a/grpc/examples/python/greeter/client.py b/grpc/examples/python/greeter/client.py index d2d718452f1..a373c5a311a 100644 --- a/grpc/examples/python/greeter/client.py +++ b/grpc/examples/python/greeter/client.py @@ -1,40 +1,46 @@ -import sys import argparse +import sys import grpc -sys.path.insert(0, '../../../../../flatbuffers/python') +sys.path.insert(0, "../../../../../flatbuffers/python") import flatbuffers from models import HelloReply, HelloRequest, greeter_grpc_fb parser = argparse.ArgumentParser() parser.add_argument("port", help="server port to connect to", default=3000) -parser.add_argument("name", help="name to be sent to server", default="flatbuffers") +parser.add_argument( + "name", help="name to be sent to server", default="flatbuffers" +) + def say_hello(stub, hello_request): - reply = stub.SayHello(hello_request) - r = HelloReply.HelloReply.GetRootAs(reply) - print(r.Message()) + reply = stub.SayHello(hello_request) + r = HelloReply.HelloReply.GetRootAs(reply) + print(r.Message()) + def say_many_hellos(stub, hello_request): - greetings = stub.SayManyHellos(hello_request) - for greeting in greetings: - r = HelloReply.HelloReply.GetRootAs(greeting) - print(r.Message()) + greetings = stub.SayManyHellos(hello_request) + for greeting in greetings: + r = HelloReply.HelloReply.GetRootAs(greeting) + print(r.Message()) + def main(): - args = parser.parse_args() - - with grpc.insecure_channel('localhost:' + args.port) as channel: - builder = flatbuffers.Builder() - ind = builder.CreateString(args.name) - HelloRequest.HelloRequestStart(builder) - HelloRequest.HelloRequestAddName(builder, ind) - root = HelloRequest.HelloRequestEnd(builder) - builder.Finish(root) - output = bytes(builder.Output()) - stub = greeter_grpc_fb.GreeterStub(channel) - say_hello(stub, output) - say_many_hellos(stub, output) - -main() \ No newline at end of file + args = parser.parse_args() + + with grpc.insecure_channel("localhost:" + args.port) as channel: + builder = flatbuffers.Builder() + ind = builder.CreateString(args.name) + HelloRequest.HelloRequestStart(builder) + HelloRequest.HelloRequestAddName(builder, ind) + root = HelloRequest.HelloRequestEnd(builder) + builder.Finish(root) + output = bytes(builder.Output()) + stub = greeter_grpc_fb.GreeterStub(channel) + say_hello(stub, output) + say_many_hellos(stub, output) + + +main() diff --git a/grpc/examples/python/greeter/greeter_grpc.fb.py b/grpc/examples/python/greeter/greeter_grpc.fb.py index 7d1fec44f8f..8c9f13a4544 100644 --- a/grpc/examples/python/greeter/greeter_grpc.fb.py +++ b/grpc/examples/python/greeter/greeter_grpc.fb.py @@ -2,30 +2,29 @@ import flatbuffers import grpc - from models.HelloReply import HelloReply from models.HelloRequest import HelloRequest class GreeterStub(object): - '''Interface exported by the server.''' + """Interface exported by the server.""" def __init__(self, channel): - '''Constructor. + """Constructor. Args: channel: A grpc.Channel. - ''' + """ - self.SayHello = channel.unary_unary( - method='/models.Greeter/SayHello') + self.SayHello = channel.unary_unary(method='/models.Greeter/SayHello') self.SayManyHellos = channel.unary_stream( - method='/models.Greeter/SayManyHellos') + method='/models.Greeter/SayManyHellos' + ) class GreeterServicer(object): - '''Interface exported by the server.''' + """Interface exported by the server.""" def SayHello(self, request, context): context.set_code(grpc.StatusCode.UNIMPLEMENTED) @@ -40,15 +39,14 @@ def SayManyHellos(self, request, context): def add_GreeterServicer_to_server(servicer, server): rpc_method_handlers = { - 'SayHello': grpc.unary_unary_rpc_method_handler( - servicer.SayHello), - 'SayManyHellos': grpc.unary_stream_rpc_method_handler( - servicer.SayManyHellos), + 'SayHello': grpc.unary_unary_rpc_method_handler(servicer.SayHello), + 'SayManyHellos': grpc.unary_stream_rpc_method_handler( + servicer.SayManyHellos + ), } generic_handler = grpc.method_handlers_generic_handler( - 'models.Greeter', rpc_method_handlers) + 'models.Greeter', rpc_method_handlers + ) server.add_generic_rpc_handlers((generic_handler,)) - - diff --git a/grpc/examples/python/greeter/models/greeter_grpc_fb.py b/grpc/examples/python/greeter/models/greeter_grpc_fb.py index b9f8a4ed233..7d1fec44f8f 100644 --- a/grpc/examples/python/greeter/models/greeter_grpc_fb.py +++ b/grpc/examples/python/greeter/models/greeter_grpc_fb.py @@ -1,52 +1,54 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! +# Generated by the gRPC FlatBuffers compiler. DO NOT EDIT! +import flatbuffers import grpc +from models.HelloReply import HelloReply +from models.HelloRequest import HelloRequest + + class GreeterStub(object): - """ Interface exported by the server. """ - + '''Interface exported by the server.''' + def __init__(self, channel): - """ Constructor. - - Args: - channel: A grpc.Channel. - """ - + '''Constructor. + + Args: + channel: A grpc.Channel. + ''' + self.SayHello = channel.unary_unary( - "/models.Greeter/SayHello" - ) - + method='/models.Greeter/SayHello') + self.SayManyHellos = channel.unary_stream( - "/models.Greeter/SayManyHellos" - ) - + method='/models.Greeter/SayManyHellos') + class GreeterServicer(object): - """ Interface exported by the server. """ - + '''Interface exported by the server.''' + def SayHello(self, request, context): context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') - - + def SayManyHellos(self, request, context): context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') - - + def add_GreeterServicer_to_server(servicer, server): rpc_method_handlers = { 'SayHello': grpc.unary_unary_rpc_method_handler( - servicer.SayHello - ), + servicer.SayHello), 'SayManyHellos': grpc.unary_stream_rpc_method_handler( - servicer.SayManyHellos - ), + servicer.SayManyHellos), } + generic_handler = grpc.method_handlers_generic_handler( 'models.Greeter', rpc_method_handlers) + server.add_generic_rpc_handlers((generic_handler,)) + diff --git a/grpc/examples/python/greeter/server.py b/grpc/examples/python/greeter/server.py index acca880b562..55b0789724e 100644 --- a/grpc/examples/python/greeter/server.py +++ b/grpc/examples/python/greeter/server.py @@ -1,9 +1,9 @@ -from concurrent import futures -import sys import argparse +from concurrent import futures +import sys import grpc -sys.path.insert(0, '../../../../../flatbuffers/python') +sys.path.insert(0, "../../../../../flatbuffers/python") import flatbuffers from models import HelloReply, HelloRequest, greeter_grpc_fb @@ -11,47 +11,48 @@ parser = argparse.ArgumentParser() parser.add_argument("port", help="server on port", default=3000) + def build_reply(message): - builder = flatbuffers.Builder() - ind = builder.CreateString(message) - HelloReply.HelloReplyStart(builder) - HelloReply.HelloReplyAddMessage(builder, ind) - root = HelloReply.HelloReplyEnd(builder) - builder.Finish(root) - return bytes(builder.Output()) + builder = flatbuffers.Builder() + ind = builder.CreateString(message) + HelloReply.HelloReplyStart(builder) + HelloReply.HelloReplyAddMessage(builder, ind) + root = HelloReply.HelloReplyEnd(builder) + builder.Finish(root) + return bytes(builder.Output()) + class GreeterServicer(greeter_grpc_fb.GreeterServicer): - def __init__(self): - self.greetings = ["Hi", "Hallo", "Ciao"] + def __init__(self): + self.greetings = ["Hi", "Hallo", "Ciao"] - def SayHello(self, request, context): - r = HelloRequest.HelloRequest().GetRootAs(request, 0) - reply = "Unknown" - if r.Name(): - reply = r.Name() - return build_reply("welcome " + reply.decode('UTF-8')) + def SayHello(self, request, context): + r = HelloRequest.HelloRequest().GetRootAs(request, 0) + reply = "Unknown" + if r.Name(): + reply = r.Name() + return build_reply("welcome " + reply.decode("UTF-8")) - def SayManyHellos(self, request, context): - r = HelloRequest.HelloRequest().GetRootAs(request, 0) - reply = "Unknown" - if r.Name(): - reply = r.Name() + def SayManyHellos(self, request, context): + r = HelloRequest.HelloRequest().GetRootAs(request, 0) + reply = "Unknown" + if r.Name(): + reply = r.Name() + + for greeting in self.greetings: + print(type(reply)) + yield build_reply(greeting + " " + reply.decode("UTF-8")) - for greeting in self.greetings: - print(type(reply)) - yield build_reply(greeting + " " + reply.decode('UTF-8')) - def serve(): - args = parser.parse_args() - server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) - greeter_grpc_fb.add_GreeterServicer_to_server( - GreeterServicer(), server - ) - server.add_insecure_port('[::]:' + args.port) - server.start() - server.wait_for_termination() - -if __name__ == '__main__': - serve() \ No newline at end of file + args = parser.parse_args() + server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) + greeter_grpc_fb.add_GreeterServicer_to_server(GreeterServicer(), server) + server.add_insecure_port("[::]:" + args.port) + server.start() + server.wait_for_termination() + + +if __name__ == "__main__": + serve() diff --git a/grpc/examples/swift/Greeter/Package.swift b/grpc/examples/swift/Greeter/Package.swift index 392c2798df4..9fd6cab834d 100644 --- a/grpc/examples/swift/Greeter/Package.swift +++ b/grpc/examples/swift/Greeter/Package.swift @@ -20,7 +20,7 @@ import PackageDescription let package = Package( name: "Greeter", platforms: [ - .iOS(.v11), + .iOS(.v12), .macOS(.v10_14), ], dependencies: [ diff --git a/grpc/examples/swift/Greeter/Sources/Model/greeter.grpc.swift b/grpc/examples/swift/Greeter/Sources/Model/greeter.grpc.swift index 0f29f1958a1..700c5cd5952 100644 --- a/grpc/examples/swift/Greeter/Sources/Model/greeter.grpc.swift +++ b/grpc/examples/swift/Greeter/Sources/Model/greeter.grpc.swift @@ -5,6 +5,7 @@ // swiftlint:disable all // swiftformat:disable all +#if !os(Windows) import Foundation import GRPC import NIO @@ -17,8 +18,7 @@ public extension GRPCFlatBufPayload { self.init(byteBuffer: FlatBuffers.ByteBuffer(contiguousBytes: serializedByteBuffer.readableBytesView, count: serializedByteBuffer.readableBytes)) } func serialize(into buffer: inout NIO.ByteBuffer) throws { - let buf = UnsafeRawBufferPointer(start: self.rawPointer, count: Int(self.size)) - buffer.writeBytes(buf) + withUnsafeReadableBytes { buffer.writeBytes($0) } } } extension Message: GRPCFlatBufPayload {} @@ -143,3 +143,5 @@ public protocol models_GreeterServerInterceptorFactoryProtocol { 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 index 5339272510d..160ea747159 100644 --- a/grpc/examples/swift/Greeter/Sources/Model/greeter_generated.swift +++ b/grpc/examples/swift/Greeter/Sources/Model/greeter_generated.swift @@ -2,11 +2,15 @@ // swiftlint:disable all // swiftformat:disable all +#if canImport(Common) +import Common +#endif + import FlatBuffers public struct models_HelloReply: FlatBufferObject, Verifiable { - static func validateVersion() { FlatBuffersVersion_25_2_10() } + static func validateVersion() { FlatBuffersVersion_25_9_23() } public var __buffer: ByteBuffer! { return _accessor.bb } private var _accessor: Table @@ -53,7 +57,7 @@ extension models_HelloReply: Encodable { public struct models_HelloRequest: FlatBufferObject, Verifiable { - static func validateVersion() { FlatBuffersVersion_25_2_10() } + static func validateVersion() { FlatBuffersVersion_25_9_23() } public var __buffer: ByteBuffer! { return _accessor.bb } private var _accessor: Table diff --git a/grpc/examples/swift/Greeter/Sources/client/main.swift b/grpc/examples/swift/Greeter/Sources/client/main.swift index e7065ac9c40..61c809aa87a 100644 --- a/grpc/examples/swift/Greeter/Sources/client/main.swift +++ b/grpc/examples/swift/Greeter/Sources/client/main.swift @@ -37,7 +37,8 @@ func greet(name: String, client greeter: models_GreeterServiceClient) { builder.finish(offset: root) // Make the RPC call to the server. - let sayHello = greeter + let sayHello = + greeter .SayHello(Message(builder: &builder)) // wait() on the response to stop the program from exiting before the response is received. @@ -76,7 +77,7 @@ func main(args: [String]) { print("Usage: PORT [NAME]") exit(1) - case let (.some(port), name): + 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 diff --git a/grpc/examples/swift/Greeter/Sources/server/main.swift b/grpc/examples/swift/Greeter/Sources/server/main.swift index 60deb544a1b..5eedd95fc75 100644 --- a/grpc/examples/swift/Greeter/Sources/server/main.swift +++ b/grpc/examples/swift/Greeter/Sources/server/main.swift @@ -32,7 +32,8 @@ class Greeter: models_GreeterProvider { func SayHello( request: Message, - context: StatusOnlyCallContext) + context: StatusOnlyCallContext + ) -> EventLoopFuture> { let recipient = request.object.name ?? "Stranger" @@ -47,12 +48,14 @@ class Greeter: models_GreeterProvider { func SayManyHellos( request: Message, - context: StreamingResponseCallContext>) + context: StreamingResponseCallContext> + ) -> EventLoopFuture { for name in greetings { var builder = FlatBufferBuilder() - let off = builder + let off = + builder .create(string: "\(name) \(request.object.name ?? "Unknown")") let root = models_HelloReply.createHelloReply( &builder, diff --git a/grpc/examples/ts/greeter/src/client.ts b/grpc/examples/ts/greeter/src/client.ts index 62444f1ebc3..c1bc5bc20c0 100644 --- a/grpc/examples/ts/greeter/src/client.ts +++ b/grpc/examples/ts/greeter/src/client.ts @@ -1,34 +1,39 @@ import * as grpc from '@grpc/grpc-js'; import * as flatbuffers from 'flatbuffers'; -import { HelloReply } from './models/hello-reply'; -import { HelloRequest } from './models/hello-request'; -import { GreeterClient } from './greeter_grpc'; +import {GreeterClient} from './greeter_grpc'; +import {HelloReply} from './models/hello-reply'; +import {HelloRequest} from './models/hello-request'; async function main(PORT: Number, name: string) { - const client = new GreeterClient(`localhost:${PORT}`, grpc.credentials.createInsecure()); - const builder = new flatbuffers.Builder(); - const offset = builder.createString(name); - const root = HelloRequest.createHelloRequest(builder, offset); - builder.finish(root); - const buffer = HelloRequest.getRootAsHelloRequest(new flatbuffers.ByteBuffer(builder.asUint8Array())); + const client = new GreeterClient( + `localhost:${PORT}`, + grpc.credentials.createInsecure(), + ); + const builder = new flatbuffers.Builder(); + const offset = builder.createString(name); + const root = HelloRequest.createHelloRequest(builder, offset); + builder.finish(root); + const buffer = HelloRequest.getRootAsHelloRequest( + new flatbuffers.ByteBuffer(builder.asUint8Array()), + ); - client.SayHello(buffer, (err, response) => { - console.log(response.message()); - }); + client.SayHello(buffer, (err, response) => { + console.log(response.message()); + }); - const data = client.SayManyHellos(buffer, null); + const data = client.SayManyHellos(buffer, null); - data.on('data', (data) => { - console.log(data.message()); - }); + data.on('data', (data) => { + console.log(data.message()); + }); } -const args = process.argv.slice(2) +const args = process.argv.slice(2); const PORT = Number(args[0]); -const name: string = args[1] ?? "flatbuffers"; +const name: string = args[1] ?? 'flatbuffers'; if (PORT) { - main(PORT, name); + main(PORT, name); } else { - throw new Error("Requires a valid port number.") -} \ No newline at end of file + throw new Error('Requires a valid port number.'); +} diff --git a/grpc/examples/ts/greeter/src/greeter_generated.ts b/grpc/examples/ts/greeter/src/greeter_generated.ts index c48afe53845..1d54f718436 100644 --- a/grpc/examples/ts/greeter/src/greeter_generated.ts +++ b/grpc/examples/ts/greeter/src/greeter_generated.ts @@ -1,4 +1,4 @@ // automatically generated by the FlatBuffers compiler, do not modify -export { HelloReply } from './models/hello-reply.js'; -export { HelloRequest } from './models/hello-request.js'; +export {HelloReply} from './models/hello-reply.js'; +export {HelloRequest} from './models/hello-request.js'; diff --git a/grpc/examples/ts/greeter/src/server.ts b/grpc/examples/ts/greeter/src/server.ts index a3f2eeec2ec..b4b360e404c 100644 --- a/grpc/examples/ts/greeter/src/server.ts +++ b/grpc/examples/ts/greeter/src/server.ts @@ -1,49 +1,63 @@ import * as grpc from '@grpc/grpc-js'; import * as flatbuffers from 'flatbuffers'; -import { HelloReply } from './models/hello-reply'; -import { HelloRequest } from './models/hello-request'; -import { IGreeterServer, GreeterService } from './greeter_grpc'; +import {GreeterService, IGreeterServer} from './greeter_grpc'; +import {HelloReply} from './models/hello-reply'; +import {HelloRequest} from './models/hello-request'; const greeter: IGreeterServer = { - SayHello(call: grpc.ServerUnaryCall, callback: grpc.sendUnaryData): void { - console.log(`SayHello ${call.request.name()}`); - const builder = new flatbuffers.Builder(); - const offset = builder.createString(`welcome ${call.request.name()}`); - const root = HelloReply.createHelloReply(builder, offset); - builder.finish(root); - callback(null, HelloReply.getRootAsHelloReply(new flatbuffers.ByteBuffer(builder.asUint8Array()))); - }, - async SayManyHellos(call: grpc.ServerWritableStream): Promise { - const name = call.request.name(); - console.log(`${call.request.name()} saying hi in different langagues`); - ['Hi', 'Hallo', 'Ciao'].forEach(element => { - const builder = new flatbuffers.Builder(); - const offset = builder.createString(`${element} ${name}`); - const root = HelloReply.createHelloReply(builder, offset); - builder.finish(root); - call.write(HelloReply.getRootAsHelloReply(new flatbuffers.ByteBuffer(builder.asUint8Array()))) - }); - call.end(); - } -} + SayHello( + call: grpc.ServerUnaryCall, + callback: grpc.sendUnaryData, + ): void { + console.log(`SayHello ${call.request.name()}`); + const builder = new flatbuffers.Builder(); + const offset = builder.createString(`welcome ${call.request.name()}`); + const root = HelloReply.createHelloReply(builder, offset); + builder.finish(root); + callback( + null, + HelloReply.getRootAsHelloReply( + new flatbuffers.ByteBuffer(builder.asUint8Array()), + ), + ); + }, + async SayManyHellos( + call: grpc.ServerWritableStream, + ): Promise { + const name = call.request.name(); + console.log(`${call.request.name()} saying hi in different langagues`); + ['Hi', 'Hallo', 'Ciao'].forEach((element) => { + const builder = new flatbuffers.Builder(); + const offset = builder.createString(`${element} ${name}`); + const root = HelloReply.createHelloReply(builder, offset); + builder.finish(root); + call.write( + HelloReply.getRootAsHelloReply( + new flatbuffers.ByteBuffer(builder.asUint8Array()), + ), + ); + }); + call.end(); + }, +}; function serve(): void { - const PORT = 3000; - const server = new grpc.Server(); - server.addService(GreeterService, greeter); - console.log(`Listening on ${PORT}`); - server.bindAsync( - `localhost:${PORT}`, - grpc.ServerCredentials.createInsecure(), - (err: Error | null, port: number) => { - if (err) { - console.error(`Server error: ${err.message}`); - } else { - console.log(`Server bound on port: ${port}`); - server.start(); - } - } - ); + const PORT = 3000; + const server = new grpc.Server(); + server.addService(GreeterService, greeter); + console.log(`Listening on ${PORT}`); + server.bindAsync( + `localhost:${PORT}`, + grpc.ServerCredentials.createInsecure(), + (err: Error | null, port: number) => { + if (err) { + console.error(`Server error: ${err.message}`); + } else { + console.log(`Server bound on port: ${port}`); + server.start(); + } + }, + ); } -serve(); \ No newline at end of file +serve(); diff --git a/grpc/flatbuffers-java-grpc/src/main/java/com/google/flatbuffers/grpc/FlatbuffersUtils.java b/grpc/flatbuffers-java-grpc/src/main/java/com/google/flatbuffers/grpc/FlatbuffersUtils.java index 768708b111e..bd2b91a2b80 100644 --- a/grpc/flatbuffers-java-grpc/src/main/java/com/google/flatbuffers/grpc/FlatbuffersUtils.java +++ b/grpc/flatbuffers-java-grpc/src/main/java/com/google/flatbuffers/grpc/FlatbuffersUtils.java @@ -19,99 +19,99 @@ import io.grpc.Drainable; import io.grpc.KnownLength; import io.grpc.MethodDescriptor; - -import javax.annotation.Nullable; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; +import javax.annotation.Nullable; public class FlatbuffersUtils { - abstract public static class FBExtactor { - T extract (InputStream stream) throws IOException { - if (stream instanceof KnownLength) { - int size = stream.available(); - ByteBuffer buffer = ByteBuffer.allocate(size); - stream.read(buffer.array()); - return extract(buffer); - } else - throw new RuntimeException("The class " + stream.getClass().getCanonicalName() + " does not extend from KnownLength "); - } - - public abstract T extract(ByteBuffer buffer); - + public abstract static class FBExtactor { + T extract(InputStream stream) throws IOException { + if (stream instanceof KnownLength) { + int size = stream.available(); + ByteBuffer buffer = ByteBuffer.allocate(size); + stream.read(buffer.array()); + return extract(buffer); + } else + throw new RuntimeException( + "The class " + + stream.getClass().getCanonicalName() + + " does not extend from KnownLength "); } - static class FBInputStream extends InputStream implements Drainable, KnownLength { - private final ByteBuffer buffer; - private final int size; - @Nullable private ByteArrayInputStream inputStream; + public abstract T extract(ByteBuffer buffer); + } - FBInputStream(ByteBuffer buffer) { - this.buffer = buffer; - this.size = buffer.remaining(); - } + static class FBInputStream extends InputStream implements Drainable, KnownLength { + private final ByteBuffer buffer; + private final int size; + @Nullable private ByteArrayInputStream inputStream; - private void makeStreamIfNotAlready() { - if (inputStream == null) - inputStream = new ByteArrayInputStream(buffer.array(), buffer.position(), size); - } + FBInputStream(ByteBuffer buffer) { + this.buffer = buffer; + this.size = buffer.remaining(); + } - @Override - public int drainTo(OutputStream target) throws IOException { - target.write(buffer.array(), buffer.position(), size); - return size; - } + private void makeStreamIfNotAlready() { + if (inputStream == null) + inputStream = new ByteArrayInputStream(buffer.array(), buffer.position(), size); + } - @Override - public int read() throws IOException { - makeStreamIfNotAlready(); - return inputStream.read(); - } + @Override + public int drainTo(OutputStream target) throws IOException { + target.write(buffer.array(), buffer.position(), size); + return size; + } - @Override - public int read(byte[] b, int off, int len) throws IOException { - makeStreamIfNotAlready(); - if (inputStream == null) { - if (len >= size) { - System.arraycopy(buffer.array(), buffer.position(), b, off, size); - return size; - } else { - makeStreamIfNotAlready(); - return inputStream.read(b, off, len); - } - } else - return inputStream.read(b, off, len); - } + @Override + public int read() throws IOException { + makeStreamIfNotAlready(); + return inputStream.read(); + } - @Override - public int available() throws IOException { - return inputStream == null ? size : inputStream.available(); + @Override + public int read(byte[] b, int off, int len) throws IOException { + makeStreamIfNotAlready(); + if (inputStream == null) { + if (len >= size) { + System.arraycopy(buffer.array(), buffer.position(), b, off, size); + return size; + } else { + makeStreamIfNotAlready(); + return inputStream.read(b, off, len); } - + } else return inputStream.read(b, off, len); } - public static MethodDescriptor.Marshaller marshaller(final Class clazz, final FBExtactor extractor) { - return new MethodDescriptor.ReflectableMarshaller() { - @Override - public Class getMessageClass() { - return clazz; - } - - @Override - public InputStream stream(T value) { - return new FBInputStream (value.getByteBuffer()); - } - - @Override - public T parse(InputStream stream) { - try { - return extractor.extract(stream); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - }; + @Override + public int available() throws IOException { + return inputStream == null ? size : inputStream.available(); } + } + + public static MethodDescriptor.Marshaller marshaller( + final Class clazz, final FBExtactor extractor) { + return new MethodDescriptor.ReflectableMarshaller() { + @Override + public Class getMessageClass() { + return clazz; + } + + @Override + public InputStream stream(T value) { + return new FBInputStream(value.getByteBuffer()); + } + + @Override + public T parse(InputStream stream) { + try { + return extractor.extract(stream); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + }; + } } diff --git a/grpc/src/compiler/cpp_generator.cc b/grpc/src/compiler/cpp_generator.cc index 21a94acf545..58cef4f4bd7 100644 --- a/grpc/src/compiler/cpp_generator.cc +++ b/grpc/src/compiler/cpp_generator.cc @@ -8,22 +8,22 @@ namespace grpc_cpp_generator { namespace { -template +template static grpc::string as_string(T x) { std::ostringstream out; out << x; return out.str(); } -static inline bool ClientOnlyStreaming(const grpc_generator::Method *method) { +static inline bool ClientOnlyStreaming(const grpc_generator::Method* method) { return method->ClientStreaming() && !method->ServerStreaming(); } -static inline bool ServerOnlyStreaming(const grpc_generator::Method *method) { +static inline bool ServerOnlyStreaming(const grpc_generator::Method* method) { return !method->ClientStreaming() && method->ServerStreaming(); } -static grpc::string FilenameIdentifier(const grpc::string &filename) { +static grpc::string FilenameIdentifier(const grpc::string& filename) { grpc::string result; for (unsigned i = 0; i < filename.size(); i++) { char c = filename[i]; @@ -39,33 +39,48 @@ static grpc::string FilenameIdentifier(const grpc::string &filename) { return result; } -template -static T *array_end(T (&array)[N]) { return array + N; } +template +static T* array_end(T (&array)[N]) { + return array + N; +} -static void PrintIncludes(grpc_generator::Printer *printer, - const std::vector &headers, - const Parameters ¶ms) { +static void PrintIncludes(grpc_generator::Printer* printer, + const std::vector& headers, + const Parameters& params) { std::map vars; vars["l"] = params.use_system_headers ? '<' : '"'; vars["r"] = params.use_system_headers ? '>' : '"'; - auto &s = params.grpc_search_path; + auto& s = params.grpc_search_path; if (!s.empty()) { vars["l"] += s; - if (s[s.size() - 1] != '/') { vars["l"] += '/'; } + if (s[s.size() - 1] != '/') { + vars["l"] += '/'; + } } for (auto i = headers.begin(); i != headers.end(); i++) { vars["h"] = *i; printer->Print(vars, "#include $l$$h$$r$\n"); } + if (params.generate_callback_api) { + // Callback API headers (guarded later by feature macro in emitted code). + static const char* cb_headers[] = { + "grpcpp/impl/codegen/callback_common.h", + "grpcpp/impl/codegen/server_callback_handlers.h", + "grpcpp/support/client_callback.h"}; + for (auto& h : cb_headers) { + vars["h"] = h; + printer->Print(vars, "#include $l$$h$$r$\n"); + } + } } } // namespace -grpc::string GetHeaderPrologue(grpc_generator::File *file, - const Parameters ¶ms) { +grpc::string GetHeaderPrologue(grpc_generator::File* file, + const Parameters& params) { grpc::string output; { // Scope the output stream so it closes and finalizes output to the string. @@ -96,25 +111,24 @@ grpc::string GetHeaderPrologue(grpc_generator::File *file, return output; } -grpc::string GetHeaderIncludes(grpc_generator::File *file, - const Parameters ¶ms) { +grpc::string GetHeaderIncludes(grpc_generator::File* file, + const Parameters& params) { grpc::string output; { // Scope the output stream so it closes and finalizes output to the string. auto printer = file->CreatePrinter(&output); std::map vars; - static const char *headers_strs[] = { - "grpcpp/impl/codegen/async_stream.h", - "grpcpp/impl/codegen/async_unary_call.h", - "grpcpp/impl/codegen/method_handler.h", - "grpcpp/impl/codegen/proto_utils.h", - "grpcpp/impl/codegen/rpc_method.h", - "grpcpp/impl/codegen/service_type.h", - "grpcpp/impl/codegen/status.h", - "grpcpp/impl/codegen/stub_options.h", - "grpcpp/impl/codegen/sync_stream.h" - }; + static const char* headers_strs[] = { + "grpcpp/impl/codegen/async_stream.h", + "grpcpp/impl/codegen/async_unary_call.h", + "grpcpp/impl/codegen/method_handler.h", + "grpcpp/impl/codegen/proto_utils.h", + "grpcpp/impl/codegen/rpc_method.h", + "grpcpp/impl/codegen/service_type.h", + "grpcpp/impl/codegen/status.h", + "grpcpp/impl/codegen/stub_options.h", + "grpcpp/impl/codegen/sync_stream.h"}; std::vector headers(headers_strs, array_end(headers_strs)); PrintIncludes(printer.get(), headers, params); printer->Print(vars, "\n"); @@ -138,12 +152,11 @@ grpc::string GetHeaderIncludes(grpc_generator::File *file, return output; } - namespace { static void PrintHeaderClientMethodInterfaces( - grpc_generator::Printer *printer, const grpc_generator::Method *method, - std::map *vars, bool is_public) { + grpc_generator::Printer* printer, const grpc_generator::Method* method, + std::map* vars, bool is_public) { (*vars)["Method"] = method->name(); (*vars)["Request"] = method->input_type_name(); (*vars)["Response"] = method->output_type_name(); @@ -152,8 +165,8 @@ static void PrintHeaderClientMethodInterfaces( grpc::string prefix; grpc::string method_params; // extra arguments to method grpc::string raw_args; // extra arguments to raw version of method - } async_prefixes[] = { { "Async", ", void* tag", ", tag" }, - { "PrepareAsync", "", "" } }; + } async_prefixes[] = {{"Async", ", void* tag", ", tag"}, + {"PrepareAsync", "", ""}}; if (is_public) { if (method->NoStreaming()) { @@ -163,7 +176,7 @@ static void PrintHeaderClientMethodInterfaces( "const $Request$& request, $Response$* response) = 0;\n"); for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]); i++) { - auto &async_prefix = async_prefixes[i]; + auto& async_prefix = async_prefixes[i]; (*vars)["AsyncPrefix"] = async_prefix.prefix; printer->Print( *vars, @@ -196,7 +209,7 @@ static void PrintHeaderClientMethodInterfaces( printer->Print("}\n"); for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]); i++) { - auto &async_prefix = async_prefixes[i]; + auto& async_prefix = async_prefixes[i]; (*vars)["AsyncPrefix"] = async_prefix.prefix; (*vars)["AsyncMethodParams"] = async_prefix.method_params; (*vars)["AsyncRawArgs"] = async_prefix.raw_args; @@ -231,7 +244,7 @@ static void PrintHeaderClientMethodInterfaces( printer->Print("}\n"); for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]); i++) { - auto &async_prefix = async_prefixes[i]; + auto& async_prefix = async_prefixes[i]; (*vars)["AsyncPrefix"] = async_prefix.prefix; (*vars)["AsyncMethodParams"] = async_prefix.method_params; (*vars)["AsyncRawArgs"] = async_prefix.raw_args; @@ -265,7 +278,7 @@ static void PrintHeaderClientMethodInterfaces( printer->Print("}\n"); for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]); i++) { - auto &async_prefix = async_prefixes[i]; + auto& async_prefix = async_prefixes[i]; (*vars)["AsyncPrefix"] = async_prefix.prefix; (*vars)["AsyncMethodParams"] = async_prefix.method_params; (*vars)["AsyncRawArgs"] = async_prefix.raw_args; @@ -289,7 +302,7 @@ static void PrintHeaderClientMethodInterfaces( if (method->NoStreaming()) { for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]); i++) { - auto &async_prefix = async_prefixes[i]; + auto& async_prefix = async_prefixes[i]; (*vars)["AsyncPrefix"] = async_prefix.prefix; printer->Print( *vars, @@ -306,7 +319,7 @@ static void PrintHeaderClientMethodInterfaces( "::grpc::ClientContext* context, $Response$* response) = 0;\n"); for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]); i++) { - auto &async_prefix = async_prefixes[i]; + auto& async_prefix = async_prefixes[i]; (*vars)["AsyncPrefix"] = async_prefix.prefix; (*vars)["AsyncMethodParams"] = async_prefix.method_params; printer->Print( @@ -324,7 +337,7 @@ static void PrintHeaderClientMethodInterfaces( "::grpc::ClientContext* context, const $Request$& request) = 0;\n"); for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]); i++) { - auto &async_prefix = async_prefixes[i]; + auto& async_prefix = async_prefixes[i]; (*vars)["AsyncPrefix"] = async_prefix.prefix; (*vars)["AsyncMethodParams"] = async_prefix.method_params; printer->Print( @@ -341,7 +354,7 @@ static void PrintHeaderClientMethodInterfaces( "$Method$Raw(::grpc::ClientContext* context) = 0;\n"); for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]); i++) { - auto &async_prefix = async_prefixes[i]; + auto& async_prefix = async_prefixes[i]; (*vars)["AsyncPrefix"] = async_prefix.prefix; (*vars)["AsyncMethodParams"] = async_prefix.method_params; printer->Print( @@ -355,12 +368,10 @@ static void PrintHeaderClientMethodInterfaces( } } - - -static void PrintHeaderClientMethod(grpc_generator::Printer *printer, - const grpc_generator::Method *method, - std::map *vars, - bool is_public) { +static void PrintHeaderClientMethod(grpc_generator::Printer* printer, + const grpc_generator::Method* method, + std::map* vars, + bool is_public) { (*vars)["Method"] = method->name(); (*vars)["Request"] = method->input_type_name(); (*vars)["Response"] = method->output_type_name(); @@ -368,8 +379,8 @@ static void PrintHeaderClientMethod(grpc_generator::Printer *printer, grpc::string prefix; grpc::string method_params; // extra arguments to method grpc::string raw_args; // extra arguments to raw version of method - } async_prefixes[] = { { "Async", ", void* tag", ", tag" }, - { "PrepareAsync", "", "" } }; + } async_prefixes[] = {{"Async", ", void* tag", ", tag"}, + {"PrepareAsync", "", ""}}; if (is_public) { if (method->NoStreaming()) { @@ -377,9 +388,25 @@ static void PrintHeaderClientMethod(grpc_generator::Printer *printer, *vars, "::grpc::Status $Method$(::grpc::ClientContext* context, " "const $Request$& request, $Response$* response) override;\n"); + if ((*vars)["generate_callback_api"] == "1") { + // Native gRPC callback unary wrappers (function callback & reactor + // variants). + printer->Print(*vars, + "// Callback unary (function form). Request/response " + "must outlive callback.\n"); + printer->Print(*vars, + "void async_$Method$(::grpc::ClientContext* context, " + "const $Request$& request, $Response$* response, " + "std::function on_done);\n"); + printer->Print(*vars, "// Callback unary (reactor form).\n"); + printer->Print(*vars, + "void async_$Method$(::grpc::ClientContext* context, " + "const $Request$& request, $Response$* response, " + "::grpc::ClientUnaryReactor* reactor);\n"); + } for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]); i++) { - auto &async_prefix = async_prefixes[i]; + auto& async_prefix = async_prefixes[i]; (*vars)["AsyncPrefix"] = async_prefix.prefix; printer->Print( *vars, @@ -407,9 +434,16 @@ static void PrintHeaderClientMethod(grpc_generator::Printer *printer, "($Method$Raw(context, response));\n"); printer->Outdent(); printer->Print("}\n"); + if ((*vars)["generate_callback_api"] == "1") { + printer->Print(*vars, "// Client streaming callback reactor entry.\n"); + printer->Print( + *vars, + "void async_$Method$(::grpc::ClientContext* context, $Response$* " + "response, ::grpc::ClientWriteReactor< $Request$ >* reactor);\n"); + } for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]); i++) { - auto &async_prefix = async_prefixes[i]; + auto& async_prefix = async_prefixes[i]; (*vars)["AsyncPrefix"] = async_prefix.prefix; (*vars)["AsyncMethodParams"] = async_prefix.method_params; (*vars)["AsyncRawArgs"] = async_prefix.raw_args; @@ -440,9 +474,16 @@ static void PrintHeaderClientMethod(grpc_generator::Printer *printer, "($Method$Raw(context, request));\n"); printer->Outdent(); printer->Print("}\n"); + if ((*vars)["generate_callback_api"] == "1") { + printer->Print(*vars, "// Server streaming callback reactor entry.\n"); + printer->Print(*vars, + "void async_$Method$(::grpc::ClientContext* context, " + "const $Request$& request, ::grpc::ClientReadReactor< " + "$Response$ >* reactor);\n"); + } for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]); i++) { - auto &async_prefix = async_prefixes[i]; + auto& async_prefix = async_prefixes[i]; (*vars)["AsyncPrefix"] = async_prefix.prefix; (*vars)["AsyncMethodParams"] = async_prefix.method_params; (*vars)["AsyncRawArgs"] = async_prefix.raw_args; @@ -472,9 +513,17 @@ static void PrintHeaderClientMethod(grpc_generator::Printer *printer, "$Method$Raw(context));\n"); printer->Outdent(); printer->Print("}\n"); + if ((*vars)["generate_callback_api"] == "1") { + printer->Print(*vars, + "// Bidirectional streaming callback reactor entry.\n"); + printer->Print( + *vars, + "void async_$Method$(::grpc::ClientContext* context, " + "::grpc::ClientBidiReactor< $Request$, $Response$ >* reactor);\n"); + } for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]); i++) { - auto &async_prefix = async_prefixes[i]; + auto& async_prefix = async_prefixes[i]; (*vars)["AsyncPrefix"] = async_prefix.prefix; (*vars)["AsyncMethodParams"] = async_prefix.method_params; (*vars)["AsyncRawArgs"] = async_prefix.raw_args; @@ -497,7 +546,7 @@ static void PrintHeaderClientMethod(grpc_generator::Printer *printer, if (method->NoStreaming()) { for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]); i++) { - auto &async_prefix = async_prefixes[i]; + auto& async_prefix = async_prefixes[i]; (*vars)["AsyncPrefix"] = async_prefix.prefix; printer->Print( *vars, @@ -506,6 +555,10 @@ static void PrintHeaderClientMethod(grpc_generator::Printer *printer, "const $Request$& request, " "::grpc::CompletionQueue* cq) override;\n"); } + if ((*vars)["generate_callback_api"] == "1") { + // Native callback unary forms declared earlier (no private sync helper + // needed). + } } else if (ClientOnlyStreaming(method)) { printer->Print(*vars, "::grpc::ClientWriter< $Request$>* $Method$Raw(" @@ -513,7 +566,7 @@ static void PrintHeaderClientMethod(grpc_generator::Printer *printer, "override;\n"); for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]); i++) { - auto &async_prefix = async_prefixes[i]; + auto& async_prefix = async_prefixes[i]; (*vars)["AsyncPrefix"] = async_prefix.prefix; (*vars)["AsyncMethodParams"] = async_prefix.method_params; (*vars)["AsyncRawArgs"] = async_prefix.raw_args; @@ -530,7 +583,7 @@ static void PrintHeaderClientMethod(grpc_generator::Printer *printer, " override;\n"); for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]); i++) { - auto &async_prefix = async_prefixes[i]; + auto& async_prefix = async_prefixes[i]; (*vars)["AsyncPrefix"] = async_prefix.prefix; (*vars)["AsyncMethodParams"] = async_prefix.method_params; (*vars)["AsyncRawArgs"] = async_prefix.raw_args; @@ -546,7 +599,7 @@ static void PrintHeaderClientMethod(grpc_generator::Printer *printer, "$Method$Raw(::grpc::ClientContext* context) override;\n"); for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]); i++) { - auto &async_prefix = async_prefixes[i]; + auto& async_prefix = async_prefixes[i]; (*vars)["AsyncPrefix"] = async_prefix.prefix; (*vars)["AsyncMethodParams"] = async_prefix.method_params; (*vars)["AsyncRawArgs"] = async_prefix.raw_args; @@ -560,17 +613,17 @@ static void PrintHeaderClientMethod(grpc_generator::Printer *printer, } } -static void PrintHeaderClientMethodData(grpc_generator::Printer *printer, - const grpc_generator::Method *method, - std::map *vars) { +static void PrintHeaderClientMethodData( + grpc_generator::Printer* printer, const grpc_generator::Method* method, + std::map* vars) { (*vars)["Method"] = method->name(); printer->Print(*vars, "const ::grpc::internal::RpcMethod rpcmethod_$Method$_;\n"); } -static void PrintHeaderServerMethodSync(grpc_generator::Printer *printer, - const grpc_generator::Method *method, - std::map *vars) { +static void PrintHeaderServerMethodSync( + grpc_generator::Printer* printer, const grpc_generator::Method* method, + std::map* vars) { (*vars)["Method"] = method->name(); (*vars)["Request"] = method->input_type_name(); (*vars)["Response"] = method->output_type_name(); @@ -602,9 +655,9 @@ static void PrintHeaderServerMethodSync(grpc_generator::Printer *printer, printer->Print(method->GetTrailingComments("//").c_str()); } -static void PrintHeaderServerMethodAsync(grpc_generator::Printer *printer, - const grpc_generator::Method *method, - std::map *vars) { +static void PrintHeaderServerMethodAsync( + grpc_generator::Printer* printer, const grpc_generator::Method* method, + std::map* vars) { (*vars)["Method"] = method->name(); (*vars)["Request"] = method->input_type_name(); (*vars)["Response"] = method->output_type_name(); @@ -719,8 +772,8 @@ static void PrintHeaderServerMethodAsync(grpc_generator::Printer *printer, } static void PrintHeaderServerMethodStreamedUnary( - grpc_generator::Printer *printer, const grpc_generator::Method *method, - std::map *vars) { + grpc_generator::Printer* printer, const grpc_generator::Method* method, + std::map* vars) { (*vars)["Method"] = method->name(); (*vars)["Request"] = method->input_type_name(); (*vars)["Response"] = method->output_type_name(); @@ -770,8 +823,8 @@ static void PrintHeaderServerMethodStreamedUnary( } static void PrintHeaderServerMethodSplitStreaming( - grpc_generator::Printer *printer, const grpc_generator::Method *method, - std::map *vars) { + grpc_generator::Printer* printer, const grpc_generator::Method* method, + std::map* vars) { (*vars)["Method"] = method->name(); (*vars)["Request"] = method->input_type_name(); (*vars)["Response"] = method->output_type_name(); @@ -823,8 +876,8 @@ static void PrintHeaderServerMethodSplitStreaming( } static void PrintHeaderServerMethodGeneric( - grpc_generator::Printer *printer, const grpc_generator::Method *method, - std::map *vars) { + grpc_generator::Printer* printer, const grpc_generator::Method* method, + std::map* vars) { (*vars)["Method"] = method->name(); (*vars)["Request"] = method->input_type_name(); (*vars)["Response"] = method->output_type_name(); @@ -893,9 +946,9 @@ static void PrintHeaderServerMethodGeneric( printer->Print(*vars, "};\n"); } -static void PrintHeaderService(grpc_generator::Printer *printer, - const grpc_generator::Service *service, - std::map *vars) { +static void PrintHeaderService(grpc_generator::Printer* printer, + const grpc_generator::Service* service, + std::map* vars) { (*vars)["Service"] = service->name(); printer->Print(service->GetLeadingComments("//").c_str()); @@ -930,6 +983,10 @@ static void PrintHeaderService(grpc_generator::Printer *printer, false); } printer->Outdent(); + // Forward declaration of nested CallbackService if callback API enabled. + if ((*vars)["generate_callback_api"] == "1") { + printer->Print("class CallbackService;\n"); + } printer->Print("};\n"); printer->Print( "class Stub final : public StubInterface" @@ -986,7 +1043,9 @@ static void PrintHeaderService(grpc_generator::Printer *printer, printer->Print(*vars, "WithAsyncMethod_$method_name$<"); } printer->Print("Service"); - for (int i = 0; i < service->method_count(); ++i) { printer->Print(" >"); } + for (int i = 0; i < service->method_count(); ++i) { + printer->Print(" >"); + } printer->Print(" AsyncService;\n"); // Server side - Generic @@ -1011,7 +1070,9 @@ static void PrintHeaderService(grpc_generator::Printer *printer, } printer->Print("Service"); for (int i = 0; i < service->method_count(); ++i) { - if (service->method(i)->NoStreaming()) { printer->Print(" >"); } + if (service->method(i)->NoStreaming()) { + printer->Print(" >"); + } } printer->Print(" StreamedUnaryService;\n"); @@ -1033,7 +1094,9 @@ static void PrintHeaderService(grpc_generator::Printer *printer, printer->Print("Service"); for (int i = 0; i < service->method_count(); ++i) { auto method = service->method(i); - if (ServerOnlyStreaming(method.get())) { printer->Print(" >"); } + if (ServerOnlyStreaming(method.get())) { + printer->Print(" >"); + } } printer->Print(" SplitStreamedService;\n"); @@ -1062,12 +1125,54 @@ static void PrintHeaderService(grpc_generator::Printer *printer, printer->Outdent(); printer->Print("};\n"); printer->Print(service->GetTrailingComments("//").c_str()); + + // Optional CallbackService (modern async API) + if ((*vars)["generate_callback_api"] == "1") { + (*vars)["Service"] = service->name(); + printer->Print("\n#if defined(GRPC_CALLBACK_API_NONEXPERIMENTAL)\n"); + printer->Print(*vars, + "class $Service$::CallbackService : public ::grpc::Service " + "{\n public:\n CallbackService();\n virtual " + "~CallbackService();\n"); + printer->Indent(); + for (int i = 0; i < service->method_count(); ++i) { + auto m = service->method(i); + (*vars)["Method"] = m->name(); + (*vars)["Request"] = m->input_type_name(); + (*vars)["Response"] = m->output_type_name(); + if (m->NoStreaming()) { + printer->Print(*vars, + "virtual ::grpc::ServerUnaryReactor* " + "$Method$(::grpc::CallbackServerContext* context, const " + "$Request$* request, $Response$* response);\n"); + } else if (ClientOnlyStreaming(m.get())) { + printer->Print(*vars, + "virtual ::grpc::ServerReadReactor<$Request$>* " + "$Method$(::grpc::CallbackServerContext* context, " + "$Response$* response);\n"); + } else if (ServerOnlyStreaming(m.get())) { + printer->Print(*vars, + "virtual ::grpc::ServerWriteReactor<$Response$>* " + "$Method$(::grpc::CallbackServerContext* context, const " + "$Request$* request);\n"); + } else if (m->BidiStreaming()) { + printer->Print( + *vars, + "virtual ::grpc::ServerBidiReactor<$Request$, $Response$>* " + "$Method$(::grpc::CallbackServerContext* context);\n"); + } + } + printer->Outdent(); + printer->Print( + "};\n#else\n// Callback API requested but not available in this gRPC " + "version.\n#endif // GRPC_CALLBACK_API_NONEXPERIMENTAL\n"); + } } -} // namespace +} // namespace -grpc::string GetHeaderServices(grpc_generator::File *file, - const Parameters ¶ms) { +grpc::string GetHeaderServices(grpc_generator::File* file, + const Parameters& params) { grpc::string output; { // Scope the output stream so it closes and finalizes output to the string. @@ -1076,7 +1181,9 @@ grpc::string GetHeaderServices(grpc_generator::File *file, // Package string is empty or ends with a dot. It is used to fully qualify // method names. vars["Package"] = file->package(); - if (!file->package().empty()) { vars["Package"].append("."); } + if (!file->package().empty()) { + vars["Package"].append("."); + } if (!params.services_namespace.empty()) { vars["services_namespace"] = params.services_namespace; @@ -1084,9 +1191,14 @@ grpc::string GetHeaderServices(grpc_generator::File *file, } for (int i = 0; i < file->service_count(); ++i) { + vars["generate_callback_api"] = params.generate_callback_api ? "1" : "0"; PrintHeaderService(printer.get(), file->service(i).get(), &vars); printer->Print("\n"); } + if (params.generate_callback_api) { + printer->Print("// FlatBuffers: Callback API code generated.\n"); + printer->Print("#define FLATBUFFERS_GENERATED_GRPC_CALLBACK_API 1\n\n"); + } if (!params.services_namespace.empty()) { printer->Print(vars, "} // namespace $services_namespace$\n\n"); @@ -1095,8 +1207,8 @@ grpc::string GetHeaderServices(grpc_generator::File *file, return output; } -grpc::string GetHeaderEpilogue(grpc_generator::File *file, - const Parameters & /*params*/) { +grpc::string GetHeaderEpilogue(grpc_generator::File* file, + const Parameters& /*params*/) { grpc::string output; { // Scope the output stream so it closes and finalizes output to the string. @@ -1124,8 +1236,8 @@ grpc::string GetHeaderEpilogue(grpc_generator::File *file, return output; } -grpc::string GetSourcePrologue(grpc_generator::File *file, - const Parameters ¶ms) { +grpc::string GetSourcePrologue(grpc_generator::File* file, + const Parameters& params) { grpc::string output; { // Scope the output stream so it closes and finalizes output to the string. @@ -1139,7 +1251,8 @@ grpc::string GetSourcePrologue(grpc_generator::File *file, printer->Print(vars, "// Generated by the gRPC C++ plugin.\n"); printer->Print(vars, - "// If you make any local change, they will be lost.\n"); + "// FlatBuffers modified generator: native gRPC callback " + "client API enabled when --grpc-callback-api.\n"); printer->Print(vars, "// source: $filename$\n\n"); printer->Print(vars, "#include \"$filename_base$$message_header_ext$\"\n"); @@ -1149,24 +1262,23 @@ grpc::string GetSourcePrologue(grpc_generator::File *file, return output; } -grpc::string GetSourceIncludes(grpc_generator::File *file, - const Parameters ¶ms) { +grpc::string GetSourceIncludes(grpc_generator::File* file, + const Parameters& params) { grpc::string output; { // Scope the output stream so it closes and finalizes output to the string. auto printer = file->CreatePrinter(&output); std::map vars; - static const char *headers_strs[] = { - "grpcpp/impl/codegen/async_stream.h", - "grpcpp/impl/codegen/async_unary_call.h", - "grpcpp/impl/codegen/channel_interface.h", - "grpcpp/impl/codegen/client_unary_call.h", - "grpcpp/impl/codegen/method_handler.h", - "grpcpp/impl/codegen/rpc_service_method.h", - "grpcpp/impl/codegen/service_type.h", - "grpcpp/impl/codegen/sync_stream.h" - }; + static const char* headers_strs[] = { + "grpcpp/impl/codegen/async_stream.h", + "grpcpp/impl/codegen/async_unary_call.h", + "grpcpp/impl/codegen/channel_interface.h", + "grpcpp/impl/codegen/client_unary_call.h", + "grpcpp/impl/codegen/method_handler.h", + "grpcpp/impl/codegen/rpc_service_method.h", + "grpcpp/impl/codegen/service_type.h", + "grpcpp/impl/codegen/sync_stream.h"}; std::vector headers(headers_strs, array_end(headers_strs)); PrintIncludes(printer.get(), headers, params); @@ -1184,12 +1296,11 @@ grpc::string GetSourceIncludes(grpc_generator::File *file, return output; } - namespace { -static void PrintSourceClientMethod(grpc_generator::Printer *printer, - const grpc_generator::Method *method, - std::map *vars) { +static void PrintSourceClientMethod( + grpc_generator::Printer* printer, const grpc_generator::Method* method, + std::map* vars) { (*vars)["Method"] = method->name(); (*vars)["Request"] = method->input_type_name(); (*vars)["Response"] = method->output_type_name(); @@ -1198,8 +1309,8 @@ static void PrintSourceClientMethod(grpc_generator::Printer *printer, grpc::string start; // bool literal expressed as string grpc::string method_params; // extra arguments to method grpc::string create_args; // extra arguments to creator - } async_prefixes[] = { { "Async", "true", ", void* tag", ", tag" }, - { "PrepareAsync", "false", "", ", nullptr" } }; + } async_prefixes[] = {{"Async", "true", ", void* tag", ", tag"}, + {"PrepareAsync", "false", "", ", nullptr"}}; if (method->NoStreaming()) { printer->Print(*vars, "::grpc::Status $ns$$Service$::Stub::$Method$(" @@ -1209,9 +1320,31 @@ static void PrintSourceClientMethod(grpc_generator::Printer *printer, " return ::grpc::internal::BlockingUnaryCall" "(channel_.get(), rpcmethod_$Method$_, " "context, request, response);\n}\n\n"); + if ((*vars)["generate_callback_api"] == "1") { + printer->Print( + *vars, + "void $ns$$Service$::Stub::async_$Method$(::grpc::ClientContext* " + "context, const $Request$& request, $Response$* response, " + "std::function on_done) {\n"); + printer->Print(*vars, + " ::grpc::internal::CallbackUnaryCall(channel_.get(), " + "rpcmethod_$Method$_, context, &request, response, " + "std::move(on_done));\n}\n\n"); + printer->Print( + *vars, + "void $ns$$Service$::Stub::async_$Method$(::grpc::ClientContext* " + "context, const $Request$& request, $Response$* response, " + "::grpc::ClientUnaryReactor* reactor) {\n"); + printer->Print( + *vars, + " " + "::grpc::internal::ClientCallbackUnaryFactory::Create(channel_.get()," + " rpcmethod_$Method$_, context, &request, response, " + "reactor);\n}\n\n"); + } for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]); i++) { - auto &async_prefix = async_prefixes[i]; + auto& async_prefix = async_prefixes[i]; (*vars)["AsyncPrefix"] = async_prefix.prefix; (*vars)["AsyncStart"] = async_prefix.start; printer->Print(*vars, @@ -1241,9 +1374,20 @@ static void PrintSourceClientMethod(grpc_generator::Printer *printer, "rpcmethod_$Method$_, " "context, response);\n" "}\n\n"); + if ((*vars)["generate_callback_api"] == "1") { + printer->Print( + *vars, + "void $ns$$Service$::Stub::async_$Method$(::grpc::ClientContext* " + "context, $Response$* response, ::grpc::ClientWriteReactor< " + "$Request$ >* reactor) {\n"); + printer->Print(*vars, + " ::grpc::internal::ClientCallbackWriterFactory< " + "$Request$ >::Create(channel_.get(), rpcmethod_$Method$_, " + "context, response, reactor);\n}\n\n"); + } for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]); i++) { - auto &async_prefix = async_prefixes[i]; + auto& async_prefix = async_prefixes[i]; (*vars)["AsyncPrefix"] = async_prefix.prefix; (*vars)["AsyncStart"] = async_prefix.start; (*vars)["AsyncMethodParams"] = async_prefix.method_params; @@ -1274,9 +1418,21 @@ static void PrintSourceClientMethod(grpc_generator::Printer *printer, "rpcmethod_$Method$_, " "context, request);\n" "}\n\n"); + if ((*vars)["generate_callback_api"] == "1") { + printer->Print( + *vars, + "void $ns$$Service$::Stub::async_$Method$(::grpc::ClientContext* " + "context, const $Request$& request, ::grpc::ClientReadReactor< " + "$Response$ >* reactor) {\n"); + printer->Print( + *vars, + " ::grpc::internal::ClientCallbackReaderFactory< " + "$Response$ >::Create(channel_.get(), " + "rpcmethod_$Method$_, context, &request, reactor);\n}\n\n"); + } for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]); i++) { - auto &async_prefix = async_prefixes[i]; + auto& async_prefix = async_prefixes[i]; (*vars)["AsyncPrefix"] = async_prefix.prefix; (*vars)["AsyncStart"] = async_prefix.start; (*vars)["AsyncMethodParams"] = async_prefix.method_params; @@ -1307,9 +1463,20 @@ static void PrintSourceClientMethod(grpc_generator::Printer *printer, "rpcmethod_$Method$_, " "context);\n" "}\n\n"); + if ((*vars)["generate_callback_api"] == "1") { + printer->Print( + *vars, + "void $ns$$Service$::Stub::async_$Method$(::grpc::ClientContext* " + "context, ::grpc::ClientBidiReactor< $Request$, $Response$ >* " + "reactor) {\n"); + printer->Print(*vars, + " ::grpc::internal::ClientCallbackReaderWriterFactory< " + "$Request$, $Response$ >::Create(channel_.get(), " + "rpcmethod_$Method$_, context, reactor);\n}\n\n"); + } for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]); i++) { - auto &async_prefix = async_prefixes[i]; + auto& async_prefix = async_prefixes[i]; (*vars)["AsyncPrefix"] = async_prefix.prefix; (*vars)["AsyncStart"] = async_prefix.start; (*vars)["AsyncMethodParams"] = async_prefix.method_params; @@ -1331,9 +1498,9 @@ static void PrintSourceClientMethod(grpc_generator::Printer *printer, } } -static void PrintSourceServerMethod(grpc_generator::Printer *printer, - const grpc_generator::Method *method, - std::map *vars) { +static void PrintSourceServerMethod( + grpc_generator::Printer* printer, const grpc_generator::Method* method, + std::map* vars) { (*vars)["Method"] = method->name(); (*vars)["Request"] = method->input_type_name(); (*vars)["Response"] = method->output_type_name(); @@ -1380,9 +1547,9 @@ static void PrintSourceServerMethod(grpc_generator::Printer *printer, } } -static void PrintSourceService(grpc_generator::Printer *printer, - const grpc_generator::Service *service, - std::map *vars) { +static void PrintSourceService(grpc_generator::Printer* printer, + const grpc_generator::Service* service, + std::map* vars) { (*vars)["Service"] = service->name(); if (service->method_count() > 0) { @@ -1495,12 +1662,120 @@ static void PrintSourceService(grpc_generator::Printer *printer, (*vars)["Idx"] = as_string(i); PrintSourceServerMethod(printer, service->method(i).get(), vars); } + + // CallbackService implementation (if enabled) + if ((*vars)["generate_callback_api"] == "1") { + (*vars)["Service"] = service->name(); + printer->Print("#if defined(GRPC_CALLBACK_API_NONEXPERIMENTAL)\n"); + printer->Print(*vars, + "$ns$$Service$::CallbackService::CallbackService() {\n"); + printer->Indent(); + for (int i = 0; i < service->method_count(); ++i) { + auto method = service->method(i); + (*vars)["Idx"] = as_string(i); + (*vars)["Method"] = method->name(); + (*vars)["Request"] = method->input_type_name(); + (*vars)["Response"] = method->output_type_name(); + if (method->NoStreaming()) { + printer->Print( + *vars, + "AddMethod(new ::grpc::internal::RpcServiceMethod(\n" + " $prefix$$Service$_method_names[$Idx$],\n" + " ::grpc::internal::RpcMethod::NORMAL_RPC,\n" + " new ::grpc::internal::CallbackUnaryHandler<$Request$, " + "$Response$>(\n" + " [this](::grpc::CallbackServerContext* ctx, const $Request$* " + "req, $Response$* resp) {\n" + " return this->$Method$(ctx, req, resp);\n" + " })));\n"); + } else if (ClientOnlyStreaming(method.get())) { + printer->Print(*vars, + "AddMethod(new ::grpc::internal::RpcServiceMethod(\n" + " $prefix$$Service$_method_names[$Idx$],\n" + " ::grpc::internal::RpcMethod::CLIENT_STREAMING,\n" + " new " + "::grpc::internal::CallbackClientStreamingHandler<$" + "Request$, $Response$>(\n" + " [this](::grpc::CallbackServerContext* ctx, " + "$Response$* resp) {\n" + " return this->$Method$(ctx, resp);\n" + " })));\n"); + } else if (ServerOnlyStreaming(method.get())) { + printer->Print(*vars, + "AddMethod(new ::grpc::internal::RpcServiceMethod(\n" + " $prefix$$Service$_method_names[$Idx$],\n" + " ::grpc::internal::RpcMethod::SERVER_STREAMING,\n" + " new " + "::grpc::internal::CallbackServerStreamingHandler<$" + "Request$, $Response$>(\n" + " [this](::grpc::CallbackServerContext* ctx, const " + "$Request$* req) {\n" + " return this->$Method$(ctx, req);\n" + " })));\n"); + } else if (method->BidiStreaming()) { + printer->Print( + *vars, + "AddMethod(new ::grpc::internal::RpcServiceMethod(\n" + " $prefix$$Service$_method_names[$Idx$],\n" + " ::grpc::internal::RpcMethod::BIDI_STREAMING,\n" + " new ::grpc::internal::CallbackBidiHandler<$Request$, " + "$Response$>(\n" + " [this](::grpc::CallbackServerContext* ctx) {\n" + " return this->$Method$(ctx);\n" + " })));\n"); + } + } + printer->Outdent(); + printer->Print("}\n\n"); + printer->Print(*vars, + "$ns$$Service$::CallbackService::~CallbackService() {}\n\n"); + // Default method bodies returning UNIMPLEMENTED reactors. + for (int i = 0; i < service->method_count(); ++i) { + auto method = service->method(i); + (*vars)["Method"] = method->name(); + (*vars)["Request"] = method->input_type_name(); + (*vars)["Response"] = method->output_type_name(); + if (method->NoStreaming()) { + printer->Print(*vars, + "::grpc::ServerUnaryReactor* " + "$ns$$Service$::CallbackService::$Method$(::grpc::" + "CallbackServerContext* /*context*/, const $Request$* " + "/*request*/, $Response$* /*response*/) {\n" + " return nullptr; // user must override\n" + "}\n\n"); + } else if (ClientOnlyStreaming(method.get())) { + printer->Print( + *vars, + "::grpc::ServerReadReactor<$Request$>* " + "$ns$$Service$::CallbackService::$Method$(::grpc::" + "CallbackServerContext* /*context*/, $Response$* /*response*/) {\n" + " return nullptr; // user must override\n" + "}\n\n"); + } else if (ServerOnlyStreaming(method.get())) { + printer->Print(*vars, + "::grpc::ServerWriteReactor<$Response$>* " + "$ns$$Service$::CallbackService::$Method$(::grpc::" + "CallbackServerContext* /*context*/, const $Request$* " + "/*request*/) {\n" + " return nullptr; // user must override\n" + "}\n\n"); + } else if (method->BidiStreaming()) { + printer->Print(*vars, + "::grpc::ServerBidiReactor<$Request$, $Response$>* " + "$ns$$Service$::CallbackService::$Method$(::grpc::" + "CallbackServerContext* /*context*/) {\n" + " return nullptr; // user must override\n" + "}\n\n"); + } + } + printer->Print("#endif // GRPC_CALLBACK_API_NONEXPERIMENTAL\n"); + } } -} // namespace +} // namespace -grpc::string GetSourceServices(grpc_generator::File *file, - const Parameters ¶ms) { +grpc::string GetSourceServices(grpc_generator::File* file, + const Parameters& params) { grpc::string output; { // Scope the output stream so it closes and finalizes output to the string. @@ -1509,7 +1784,9 @@ grpc::string GetSourceServices(grpc_generator::File *file, // Package string is empty or ends with a dot. It is used to fully qualify // method names. vars["Package"] = file->package(); - if (!file->package().empty()) { vars["Package"].append("."); } + if (!file->package().empty()) { + vars["Package"].append("."); + } if (!params.services_namespace.empty()) { vars["ns"] = params.services_namespace + "::"; vars["prefix"] = params.services_namespace; @@ -1519,6 +1796,7 @@ grpc::string GetSourceServices(grpc_generator::File *file, } for (int i = 0; i < file->service_count(); ++i) { + vars["generate_callback_api"] = params.generate_callback_api ? "1" : "0"; PrintSourceService(printer.get(), file->service(i).get(), &vars); printer->Print("\n"); } @@ -1526,8 +1804,8 @@ grpc::string GetSourceServices(grpc_generator::File *file, return output; } -grpc::string GetSourceEpilogue(grpc_generator::File *file, - const Parameters & /*params*/) { +grpc::string GetSourceEpilogue(grpc_generator::File* file, + const Parameters& /*params*/) { grpc::string temp; if (!file->package().empty()) { @@ -1544,8 +1822,8 @@ grpc::string GetSourceEpilogue(grpc_generator::File *file, return temp; } -grpc::string GetMockPrologue(grpc_generator::File *file, - const Parameters ¶ms) { +grpc::string GetMockPrologue(grpc_generator::File* file, + const Parameters& params) { grpc::string output; { // Scope the output stream so it closes and finalizes output to the string. @@ -1571,18 +1849,18 @@ grpc::string GetMockPrologue(grpc_generator::File *file, } // TODO(mmukhi): Add client-stream and completion-queue headers. -grpc::string GetMockIncludes(grpc_generator::File *file, - const Parameters ¶ms) { +grpc::string GetMockIncludes(grpc_generator::File* file, + const Parameters& params) { grpc::string output; { // Scope the output stream so it closes and finalizes output to the string. auto printer = file->CreatePrinter(&output); std::map vars; - static const char *headers_strs[] = { - "grpcpp/impl/codegen/async_stream.h", - "grpcpp/impl/codegen/sync_stream.h", - "gmock/gmock.h", + static const char* headers_strs[] = { + "grpcpp/impl/codegen/async_stream.h", + "grpcpp/impl/codegen/sync_stream.h", + "gmock/gmock.h", }; std::vector headers(headers_strs, array_end(headers_strs)); PrintIncludes(printer.get(), headers, params); @@ -1601,12 +1879,11 @@ grpc::string GetMockIncludes(grpc_generator::File *file, return output; } - namespace { -static void PrintMockClientMethods(grpc_generator::Printer *printer, - const grpc_generator::Method *method, - std::map *vars) { +static void PrintMockClientMethods(grpc_generator::Printer* printer, + const grpc_generator::Method* method, + std::map* vars) { (*vars)["Method"] = method->name(); (*vars)["Request"] = method->input_type_name(); (*vars)["Response"] = method->output_type_name(); @@ -1615,8 +1892,7 @@ static void PrintMockClientMethods(grpc_generator::Printer *printer, grpc::string prefix; grpc::string method_params; // extra arguments to method int extra_method_param_count; - } async_prefixes[] = { { "Async", ", void* tag", 1 }, - { "PrepareAsync", "", 0 } }; + } async_prefixes[] = {{"Async", ", void* tag", 1}, {"PrepareAsync", "", 0}}; if (method->NoStreaming()) { printer->Print( @@ -1625,7 +1901,7 @@ static void PrintMockClientMethods(grpc_generator::Printer *printer, "const $Request$& request, $Response$* response));\n"); for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]); i++) { - auto &async_prefix = async_prefixes[i]; + auto& async_prefix = async_prefixes[i]; (*vars)["AsyncPrefix"] = async_prefix.prefix; printer->Print( *vars, @@ -1642,7 +1918,7 @@ static void PrintMockClientMethods(grpc_generator::Printer *printer, "(::grpc::ClientContext* context, $Response$* response));\n"); for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]); i++) { - auto &async_prefix = async_prefixes[i]; + auto& async_prefix = async_prefixes[i]; (*vars)["AsyncPrefix"] = async_prefix.prefix; (*vars)["AsyncMethodParams"] = async_prefix.method_params; (*vars)["MockArgs"] = @@ -1661,7 +1937,7 @@ static void PrintMockClientMethods(grpc_generator::Printer *printer, "(::grpc::ClientContext* context, const $Request$& request));\n"); for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]); i++) { - auto &async_prefix = async_prefixes[i]; + auto& async_prefix = async_prefixes[i]; (*vars)["AsyncPrefix"] = async_prefix.prefix; (*vars)["AsyncMethodParams"] = async_prefix.method_params; (*vars)["MockArgs"] = @@ -1681,7 +1957,7 @@ static void PrintMockClientMethods(grpc_generator::Printer *printer, "(::grpc::ClientContext* context));\n"); for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]); i++) { - auto &async_prefix = async_prefixes[i]; + auto& async_prefix = async_prefixes[i]; (*vars)["AsyncPrefix"] = async_prefix.prefix; (*vars)["AsyncMethodParams"] = async_prefix.method_params; (*vars)["MockArgs"] = @@ -1696,9 +1972,9 @@ static void PrintMockClientMethods(grpc_generator::Printer *printer, } } -static void PrintMockService(grpc_generator::Printer *printer, - const grpc_generator::Service *service, - std::map *vars) { +static void PrintMockService(grpc_generator::Printer* printer, + const grpc_generator::Service* service, + std::map* vars) { (*vars)["Service"] = service->name(); printer->Print(*vars, @@ -1712,10 +1988,10 @@ static void PrintMockService(grpc_generator::Printer *printer, printer->Print("};\n"); } -} // namespace +} // namespace -grpc::string GetMockServices(grpc_generator::File *file, - const Parameters ¶ms) { +grpc::string GetMockServices(grpc_generator::File* file, + const Parameters& params) { grpc::string output; { // Scope the output stream so it closes and finalizes output to the string. @@ -1724,7 +2000,9 @@ grpc::string GetMockServices(grpc_generator::File *file, // Package string is empty or ends with a dot. It is used to fully qualify // method names. vars["Package"] = file->package(); - if (!file->package().empty()) { vars["Package"].append("."); } + if (!file->package().empty()) { + vars["Package"].append("."); + } if (!params.services_namespace.empty()) { vars["services_namespace"] = params.services_namespace; @@ -1743,8 +2021,8 @@ grpc::string GetMockServices(grpc_generator::File *file, return output; } -grpc::string GetMockEpilogue(grpc_generator::File *file, - const Parameters & /*params*/) { +grpc::string GetMockEpilogue(grpc_generator::File* file, + const Parameters& /*params*/) { grpc::string temp; if (!file->package().empty()) { diff --git a/grpc/src/compiler/cpp_generator.h b/grpc/src/compiler/cpp_generator.h index 98e37df97ad..c7bfbe81d66 100644 --- a/grpc/src/compiler/cpp_generator.h +++ b/grpc/src/compiler/cpp_generator.h @@ -11,8 +11,8 @@ #include "src/compiler/schema_interface.h" #ifndef GRPC_CUSTOM_STRING -# include -# define GRPC_CUSTOM_STRING std::string +#include +#define GRPC_CUSTOM_STRING std::string #endif namespace grpc { @@ -37,71 +37,73 @@ struct Parameters { std::string message_header_extension; // Default: ".grpc.fb.h" std::string service_header_extension; + // Generate modern callback-based async API service code (CallbackService) + bool generate_callback_api = false; }; // Return the prologue of the generated header file. -grpc::string GetHeaderPrologue(grpc_generator::File *file, - const Parameters ¶ms); +grpc::string GetHeaderPrologue(grpc_generator::File* file, + const Parameters& params); // Return the includes needed for generated header file. -grpc::string GetHeaderIncludes(grpc_generator::File *file, - const Parameters ¶ms); +grpc::string GetHeaderIncludes(grpc_generator::File* file, + const Parameters& params); // Return the includes needed for generated source file. -grpc::string GetSourceIncludes(grpc_generator::File *file, - const Parameters ¶ms); +grpc::string GetSourceIncludes(grpc_generator::File* file, + const Parameters& params); // Return the epilogue of the generated header file. -grpc::string GetHeaderEpilogue(grpc_generator::File *file, - const Parameters ¶ms); +grpc::string GetHeaderEpilogue(grpc_generator::File* file, + const Parameters& params); // Return the prologue of the generated source file. -grpc::string GetSourcePrologue(grpc_generator::File *file, - const Parameters ¶ms); +grpc::string GetSourcePrologue(grpc_generator::File* file, + const Parameters& params); // Return the services for generated header file. -grpc::string GetHeaderServices(grpc_generator::File *file, - const Parameters ¶ms); +grpc::string GetHeaderServices(grpc_generator::File* file, + const Parameters& params); // Return the services for generated source file. -grpc::string GetSourceServices(grpc_generator::File *file, - const Parameters ¶ms); +grpc::string GetSourceServices(grpc_generator::File* file, + const Parameters& params); // Return the epilogue of the generated source file. -grpc::string GetSourceEpilogue(grpc_generator::File *file, - const Parameters ¶ms); +grpc::string GetSourceEpilogue(grpc_generator::File* file, + const Parameters& params); // Return the prologue of the generated mock file. -grpc::string GetMockPrologue(grpc_generator::File *file, - const Parameters ¶ms); +grpc::string GetMockPrologue(grpc_generator::File* file, + const Parameters& params); // Return the includes needed for generated mock file. -grpc::string GetMockIncludes(grpc_generator::File *file, - const Parameters ¶ms); +grpc::string GetMockIncludes(grpc_generator::File* file, + const Parameters& params); // Return the services for generated mock file. -grpc::string GetMockServices(grpc_generator::File *file, - const Parameters ¶ms); +grpc::string GetMockServices(grpc_generator::File* file, + const Parameters& params); // Return the epilogue of generated mock file. -grpc::string GetMockEpilogue(grpc_generator::File *file, - const Parameters ¶ms); +grpc::string GetMockEpilogue(grpc_generator::File* file, + const Parameters& params); // Return the prologue of the generated mock file. -grpc::string GetMockPrologue(grpc_generator::File *file, - const Parameters ¶ms); +grpc::string GetMockPrologue(grpc_generator::File* file, + const Parameters& params); // Return the includes needed for generated mock file. -grpc::string GetMockIncludes(grpc_generator::File *file, - const Parameters ¶ms); +grpc::string GetMockIncludes(grpc_generator::File* file, + const Parameters& params); // Return the services for generated mock file. -grpc::string GetMockServices(grpc_generator::File *file, - const Parameters ¶ms); +grpc::string GetMockServices(grpc_generator::File* file, + const Parameters& params); // Return the epilogue of generated mock file. -grpc::string GetMockEpilogue(grpc_generator::File *file, - const Parameters ¶ms); +grpc::string GetMockEpilogue(grpc_generator::File* file, + const Parameters& params); } // namespace grpc_cpp_generator diff --git a/grpc/src/compiler/go_generator.cc b/grpc/src/compiler/go_generator.cc index ad4694b107f..8cc8951e893 100644 --- a/grpc/src/compiler/go_generator.cc +++ b/grpc/src/compiler/go_generator.cc @@ -4,17 +4,18 @@ #include #include -template grpc::string as_string(T x) { +template +grpc::string as_string(T x) { std::ostringstream out; out << x; return out.str(); } -inline bool ClientOnlyStreaming(const grpc_generator::Method *method) { +inline bool ClientOnlyStreaming(const grpc_generator::Method* method) { return method->ClientStreaming() && !method->ServerStreaming(); } -inline bool ServerOnlyStreaming(const grpc_generator::Method *method) { +inline bool ServerOnlyStreaming(const grpc_generator::Method* method) { return !method->ClientStreaming() && method->ServerStreaming(); } @@ -35,9 +36,9 @@ static grpc::string exportName(grpc::string s) { return s; } -static void GenerateError(grpc_generator::Printer *printer, - std::map vars, - const bool multiple_return = true) { +static void GenerateError(grpc_generator::Printer* printer, + std::map vars, + const bool multiple_return = true) { printer->Print(vars, "if $Error_Check$ {\n"); printer->Indent(); vars["Return"] = multiple_return ? "nil, err" : "err"; @@ -47,9 +48,9 @@ static void GenerateError(grpc_generator::Printer *printer, } // Generates imports for the service -static void GenerateImports(grpc_generator::File *file, - grpc_generator::Printer *printer, - std::map vars) { +static void GenerateImports(grpc_generator::File* file, + grpc_generator::Printer* printer, + std::map vars) { vars["filename"] = file->filename(); printer->Print("//Generated by gRPC Go plugin\n"); printer->Print("//If you make any local changes, they will be lost\n"); @@ -67,9 +68,9 @@ static void GenerateImports(grpc_generator::File *file, } // Generates Server method signature source -static void GenerateServerMethodSignature(const grpc_generator::Method *method, - grpc_generator::Printer *printer, - std::map vars) { +static void GenerateServerMethodSignature( + const grpc_generator::Method* method, grpc_generator::Printer* printer, + std::map vars) { vars["Method"] = exportName(method->name()); vars["Request"] = method->get_input_type_name(); vars["Response"] = (vars["CustomMethodIO"] == "") @@ -87,9 +88,9 @@ static void GenerateServerMethodSignature(const grpc_generator::Method *method, } } -static void GenerateServerMethod(const grpc_generator::Method *method, - grpc_generator::Printer *printer, - std::map vars) { +static void GenerateServerMethod(const grpc_generator::Method* method, + grpc_generator::Printer* printer, + std::map vars) { vars["Method"] = exportName(method->name()); vars["Request"] = method->get_input_type_name(); vars["Response"] = (vars["CustomMethodIO"] == "") @@ -160,8 +161,12 @@ static void GenerateServerMethod(const grpc_generator::Method *method, printer->Print(vars, "type $Service$_$Method$Server interface {\n"); printer->Indent(); - if (genSend) { printer->Print(vars, "Send(*$Response$) error\n"); } - if (genRecv) { printer->Print(vars, "Recv() (*$Request$, error)\n"); } + if (genSend) { + printer->Print(vars, "Send(*$Response$) error\n"); + } + if (genRecv) { + printer->Print(vars, "Recv() (*$Request$, error)\n"); + } if (genSendAndClose) { printer->Print(vars, "SendAndClose(*$Response$) error\n"); } @@ -205,9 +210,9 @@ static void GenerateServerMethod(const grpc_generator::Method *method, } // Generates Client method signature source -static void GenerateClientMethodSignature(const grpc_generator::Method *method, - grpc_generator::Printer *printer, - std::map vars) { +static void GenerateClientMethodSignature( + const grpc_generator::Method* method, grpc_generator::Printer* printer, + std::map vars) { vars["Method"] = exportName(method->name()); vars["Request"] = ", in *" + ((vars["CustomMethodIO"] == "") ? method->get_input_type_name() @@ -226,9 +231,9 @@ static void GenerateClientMethodSignature(const grpc_generator::Method *method, } // Generates Client method source -static void GenerateClientMethod(const grpc_generator::Method *method, - grpc_generator::Printer *printer, - std::map vars) { +static void GenerateClientMethod(const grpc_generator::Method* method, + grpc_generator::Printer* printer, + std::map vars) { printer->Print(vars, "func (c *$ServiceUnexported$Client) "); vars["Ending"] = " {\n"; GenerateClientMethodSignature(method, printer, vars); @@ -277,8 +282,12 @@ static void GenerateClientMethod(const grpc_generator::Method *method, // Stream interface printer->Print(vars, "type $Service$_$Method$Client interface {\n"); printer->Indent(); - if (genSend) { printer->Print(vars, "Send(*$Request$) error\n"); } - if (genRecv) { printer->Print(vars, "Recv() (*$Response$, error)\n"); } + if (genSend) { + printer->Print(vars, "Send(*$Request$) error\n"); + } + if (genRecv) { + printer->Print(vars, "Recv() (*$Response$, error)\n"); + } if (genCloseAndRecv) { printer->Print(vars, "CloseAndRecv() (*$Response$, error)\n"); } @@ -329,8 +338,8 @@ static void GenerateClientMethod(const grpc_generator::Method *method, } // Generates client API for the service -void GenerateService(const grpc_generator::Service *service, - grpc_generator::Printer *printer, +void GenerateService(const grpc_generator::Service* service, + grpc_generator::Printer* printer, std::map vars) { vars["Service"] = exportName(service->name()); // Client Interface @@ -484,9 +493,9 @@ void GenerateService(const grpc_generator::Service *service, } // namespace // Returns source for the service -grpc::string GenerateServiceSource(grpc_generator::File *file, - const grpc_generator::Service *service, - grpc_go_generator::Parameters *parameters) { +grpc::string GenerateServiceSource(grpc_generator::File* file, + const grpc_generator::Service* service, + grpc_go_generator::Parameters* parameters) { grpc::string out; auto p = file->CreatePrinter(&out, '\t'); p->SetIndentationSize(1); diff --git a/grpc/src/compiler/go_generator.h b/grpc/src/compiler/go_generator.h index 766e100c584..f1ced289367 100644 --- a/grpc/src/compiler/go_generator.h +++ b/grpc/src/compiler/go_generator.h @@ -24,9 +24,9 @@ struct Parameters { }; // Return the source of the generated service file. -grpc::string GenerateServiceSource(grpc_generator::File *file, - const grpc_generator::Service *service, - grpc_go_generator::Parameters *parameters); +grpc::string GenerateServiceSource(grpc_generator::File* file, + const grpc_generator::Service* service, + grpc_go_generator::Parameters* parameters); } // namespace grpc_go_generator diff --git a/grpc/src/compiler/java_generator.cc b/grpc/src/compiler/java_generator.cc index bfe2b111dbb..00d3350f3de 100644 --- a/grpc/src/compiler/java_generator.cc +++ b/grpc/src/compiler/java_generator.cc @@ -28,11 +28,11 @@ // Stringify helpers used solely to cast GRPC_VERSION #ifndef STR -# define STR(s) # s +#define STR(s) #s #endif #ifndef XSTR -# define XSTR(s) STR(s) +#define XSTR(s) STR(s) #endif typedef grpc_generator::Printer Printer; @@ -46,8 +46,8 @@ namespace grpc_java_generator { typedef std::string string; namespace { // Generates imports for the service -static void GenerateImports(grpc_generator::File *file, - grpc_generator::Printer *printer, VARS &vars) { +static void GenerateImports(grpc_generator::File* file, + grpc_generator::Printer* printer, VARS& vars) { vars["filename"] = file->filename(); printer->Print(vars, "//Generated by flatc compiler (version $flatc_version$)\n"); @@ -64,7 +64,7 @@ static void GenerateImports(grpc_generator::File *file, // Adjust a method name prefix identifier to follow the JavaBean spec: // - decapitalize the first letter // - remove embedded underscores & capitalize the following letter -static string MixedLower(const string &word) { +static string MixedLower(const string& word) { string w; w += static_cast(tolower(word[0])); bool after_underscore = false; @@ -84,7 +84,7 @@ static string MixedLower(const string &word) { // - An underscore is inserted where a lower case letter is followed by an // upper case letter. // - All letters are converted to upper case -static string ToAllUpperCase(const string &word) { +static string ToAllUpperCase(const string& word) { string w; for (size_t i = 0; i < word.length(); ++i) { w += static_cast(toupper(word[i])); @@ -95,49 +95,48 @@ static string ToAllUpperCase(const string &word) { return w; } -static inline string LowerMethodName(const MethodDescriptor *method) { +static inline string LowerMethodName(const MethodDescriptor* method) { return MixedLower(method->name()); } -static inline string MethodPropertiesFieldName(const MethodDescriptor *method) { +static inline string MethodPropertiesFieldName(const MethodDescriptor* method) { return "METHOD_" + ToAllUpperCase(method->name()); } static inline string MethodPropertiesGetterName( - const MethodDescriptor *method) { + const MethodDescriptor* method) { return MixedLower("get_" + method->name() + "_method"); } -static inline string MethodIdFieldName(const MethodDescriptor *method) { +static inline string MethodIdFieldName(const MethodDescriptor* method) { return "METHODID_" + ToAllUpperCase(method->name()); } -static inline string JavaClassName(VARS &vars, const string &name) { +static inline string JavaClassName(VARS& vars, const string& name) { // string name = google::protobuf::compiler::java::ClassName(desc); return vars["Package"] + name; } -static inline string ServiceClassName(const string &service_name) { +static inline string ServiceClassName(const string& service_name) { return service_name + "Grpc"; } // TODO(nmittler): Remove once protobuf includes javadoc methods in // distribution. -template -static void GrpcSplitStringToIteratorUsing(const string &full, - const char *delim, ITR &result) { +template +static void GrpcSplitStringToIteratorUsing(const string& full, + const char* delim, ITR& result) { // Optimize the common case where delim is a single character. if (delim[0] != '\0' && delim[1] == '\0') { char c = delim[0]; - const char *p = full.data(); - const char *end = p + full.size(); + const char* p = full.data(); + const char* end = p + full.size(); while (p != end) { if (*p == c) { ++p; } else { - const char *start = p; - while (++p != end && *p != c) - ; + const char* start = p; + while (++p != end && *p != c); *result++ = string(start, p - start); } } @@ -157,13 +156,13 @@ static void GrpcSplitStringToIteratorUsing(const string &full, } } -static void GrpcSplitStringUsing(const string &full, const char *delim, - std::vector *result) { +static void GrpcSplitStringUsing(const string& full, const char* delim, + std::vector* result) { std::back_insert_iterator> it(*result); GrpcSplitStringToIteratorUsing(full, delim, it); } -static std::vector GrpcSplit(const string &full, const char *delim) { +static std::vector GrpcSplit(const string& full, const char* delim) { std::vector result; GrpcSplitStringUsing(full, delim, &result); return result; @@ -171,7 +170,7 @@ static std::vector GrpcSplit(const string &full, const char *delim) { // TODO(nmittler): Remove once protobuf includes javadoc methods in // distribution. -static string GrpcEscapeJavadoc(const string &input) { +static string GrpcEscapeJavadoc(const string& input) { string result; result.reserve(input.size() * 2); @@ -218,7 +217,9 @@ static string GrpcEscapeJavadoc(const string &input) { // Java interprets Unicode escape sequences anywhere! result.append("\"); break; - default: result.push_back(c); break; + default: + result.push_back(c); + break; } prev = c; @@ -227,7 +228,7 @@ static string GrpcEscapeJavadoc(const string &input) { return result; } -static std::vector GrpcGetDocLines(const string &comments) { +static std::vector GrpcGetDocLines(const string& comments) { if (!comments.empty()) { // TODO(kenton): Ideally we should parse the comment text as Markdown and // write it back as HTML, but this requires a Markdown parser. For now @@ -238,23 +239,27 @@ static std::vector GrpcGetDocLines(const string &comments) { string escapedComments = GrpcEscapeJavadoc(comments); std::vector lines = GrpcSplit(escapedComments, "\n"); - while (!lines.empty() && lines.back().empty()) { lines.pop_back(); } + while (!lines.empty() && lines.back().empty()) { + lines.pop_back(); + } return lines; } return std::vector(); } static std::vector GrpcGetDocLinesForDescriptor( - const DescriptorType *descriptor) { + const DescriptorType* descriptor) { return descriptor->GetAllComments(); // return GrpcGetDocLines(descriptor->GetLeadingComments("///")); } -static void GrpcWriteDocCommentBody(Printer *printer, VARS &vars, - const std::vector &lines, +static void GrpcWriteDocCommentBody(Printer* printer, VARS& vars, + const std::vector& lines, bool surroundWithPreTag) { if (!lines.empty()) { - if (surroundWithPreTag) { printer->Print(" *
\n"); }
+    if (surroundWithPreTag) {
+      printer->Print(" * 
\n");
+    }
 
     for (size_t i = 0; i < lines.size(); i++) {
       // Most lines should start with a space.  Watch out for lines that start
@@ -268,28 +273,30 @@ static void GrpcWriteDocCommentBody(Printer *printer, VARS &vars,
       }
     }
 
-    if (surroundWithPreTag) { printer->Print(" * 
\n"); } + if (surroundWithPreTag) { + printer->Print(" *
\n"); + } } } -static void GrpcWriteDocComment(Printer *printer, VARS &vars, - const string &comments) { +static void GrpcWriteDocComment(Printer* printer, VARS& vars, + const string& comments) { printer->Print("/**\n"); std::vector lines = GrpcGetDocLines(comments); GrpcWriteDocCommentBody(printer, vars, lines, false); printer->Print(" */\n"); } -static void GrpcWriteServiceDocComment(Printer *printer, VARS &vars, - const ServiceDescriptor *service) { +static void GrpcWriteServiceDocComment(Printer* printer, VARS& vars, + const ServiceDescriptor* service) { printer->Print("/**\n"); std::vector lines = GrpcGetDocLinesForDescriptor(service); GrpcWriteDocCommentBody(printer, vars, lines, true); printer->Print(" */\n"); } -static void GrpcWriteMethodDocComment(Printer *printer, VARS &vars, - const MethodDescriptor *method) { +static void GrpcWriteMethodDocComment(Printer* printer, VARS& vars, + const MethodDescriptor* method) { printer->Print("/**\n"); std::vector lines = GrpcGetDocLinesForDescriptor(method); GrpcWriteDocCommentBody(printer, vars, lines, true); @@ -298,7 +305,7 @@ static void GrpcWriteMethodDocComment(Printer *printer, VARS &vars, // outputs static singleton extractor for type stored in "extr_type" and // "extr_type_name" vars -static void PrintTypeExtractor(Printer *p, VARS &vars) { +static void PrintTypeExtractor(Printer* p, VARS& vars) { p->Print(vars, "private static volatile FlatbuffersUtils.FBExtactor<$extr_type$> " "extractorOf$extr_type_name$;\n" @@ -320,8 +327,8 @@ static void PrintTypeExtractor(Printer *p, VARS &vars) { " }\n" "}\n\n"); } -static void PrintMethodFields(Printer *p, VARS &vars, - const ServiceDescriptor *service) { +static void PrintMethodFields(Printer* p, VARS& vars, + const ServiceDescriptor* service) { p->Print("// Static method descriptors that strictly reflect the proto.\n"); vars["service_name"] = service->name(); @@ -443,11 +450,11 @@ enum StubType { enum CallType { ASYNC_CALL = 0, BLOCKING_CALL = 1, FUTURE_CALL = 2 }; -static void PrintBindServiceMethodBody(Printer *p, VARS &vars, - const ServiceDescriptor *service); +static void PrintBindServiceMethodBody(Printer* p, VARS& vars, + const ServiceDescriptor* service); // Prints a client interface or implementation class, or a server interface. -static void PrintStub(Printer *p, VARS &vars, const ServiceDescriptor *service, +static void PrintStub(Printer* p, VARS& vars, const ServiceDescriptor* service, StubType type) { const string service_name = service->name(); vars["service_name"] = service_name; @@ -493,7 +500,9 @@ static void PrintStub(Printer *p, VARS &vars, const ServiceDescriptor *service, vars["client_name"] = client_name; // Class head - if (!interface) { GrpcWriteServiceDocComment(p, vars, service); } + if (!interface) { + GrpcWriteServiceDocComment(p, vars, service); + } if (impl_base) { p->Print(vars, "public static abstract class $abstract_name$ implements " @@ -555,7 +564,9 @@ static void PrintStub(Printer *p, VARS &vars, const ServiceDescriptor *service, p->Print("\n"); // TODO(nmittler): Replace with WriteMethodDocComment once included by the // protobuf distro. - if (!interface) { GrpcWriteMethodDocComment(p, vars, &*method); } + if (!interface) { + GrpcWriteMethodDocComment(p, vars, &*method); + } p->Print("public "); switch (call_type) { case BLOCKING_CALL: @@ -620,7 +631,8 @@ static void PrintStub(Printer *p, VARS &vars, const ServiceDescriptor *service, "responseObserver);\n"); } break; - default: break; + default: + break; } } else if (!interface) { switch (call_type) { @@ -695,15 +707,15 @@ static void PrintStub(Printer *p, VARS &vars, const ServiceDescriptor *service, } static bool CompareMethodClientStreaming( - const std::unique_ptr &method1, - const std::unique_ptr &method2) { + const std::unique_ptr& method1, + const std::unique_ptr& method2) { return method1->ClientStreaming() < method2->ClientStreaming(); } // Place all method invocations into a single class to reduce memory footprint // on Android. -static void PrintMethodHandlerClass(Printer *p, VARS &vars, - const ServiceDescriptor *service) { +static void PrintMethodHandlerClass(Printer* p, VARS& vars, + const ServiceDescriptor* service) { // Sort method ids based on ClientStreaming() so switch tables are compact. std::vector> sorted_methods( service->method_count()); @@ -713,7 +725,7 @@ static void PrintMethodHandlerClass(Printer *p, VARS &vars, stable_sort(sorted_methods.begin(), sorted_methods.end(), CompareMethodClientStreaming); for (size_t i = 0; i < sorted_methods.size(); i++) { - auto &method = sorted_methods[i]; + auto& method = sorted_methods[i]; vars["method_id"] = to_string(i); vars["method_id_name"] = MethodIdFieldName(&*method); p->Print(vars, @@ -746,7 +758,9 @@ static void PrintMethodHandlerClass(Printer *p, VARS &vars, for (int i = 0; i < service->method_count(); ++i) { auto method = service->method(i); - if (method->ClientStreaming() || method->BidiStreaming()) { continue; } + if (method->ClientStreaming() || method->BidiStreaming()) { + continue; + } vars["method_id_name"] = MethodIdFieldName(&*method); vars["lower_method_name"] = LowerMethodName(&*method); vars["input_type"] = JavaClassName(vars, method->get_input_type_name()); @@ -778,7 +792,9 @@ static void PrintMethodHandlerClass(Printer *p, VARS &vars, for (int i = 0; i < service->method_count(); ++i) { auto method = service->method(i); - if (!(method->ClientStreaming() || method->BidiStreaming())) { continue; } + if (!(method->ClientStreaming() || method->BidiStreaming())) { + continue; + } vars["method_id_name"] = MethodIdFieldName(&*method); vars["lower_method_name"] = LowerMethodName(&*method); vars["input_type"] = JavaClassName(vars, method->get_input_type_name()); @@ -803,8 +819,8 @@ static void PrintMethodHandlerClass(Printer *p, VARS &vars, p->Print("}\n\n"); } -static void PrintGetServiceDescriptorMethod(Printer *p, VARS &vars, - const ServiceDescriptor *service) { +static void PrintGetServiceDescriptorMethod(Printer* p, VARS& vars, + const ServiceDescriptor* service) { vars["service_name"] = service->name(); // vars["proto_base_descriptor_supplier"] = service->name() + // "BaseDescriptorSupplier"; vars["proto_file_descriptor_supplier"] = @@ -896,8 +912,8 @@ static void PrintGetServiceDescriptorMethod(Printer *p, VARS &vars, p->Print("}\n"); } -static void PrintBindServiceMethodBody(Printer *p, VARS &vars, - const ServiceDescriptor *service) { +static void PrintBindServiceMethodBody(Printer* p, VARS& vars, + const ServiceDescriptor* service) { vars["service_name"] = service->name(); p->Indent(); p->Print(vars, @@ -949,8 +965,8 @@ static void PrintBindServiceMethodBody(Printer *p, VARS &vars, p->Outdent(); } -static void PrintService(Printer *p, VARS &vars, - const ServiceDescriptor *service, +static void PrintService(Printer* p, VARS& vars, + const ServiceDescriptor* service, bool disable_version) { vars["service_name"] = service->name(); vars["service_class_name"] = ServiceClassName(service->name()); @@ -1030,7 +1046,7 @@ static void PrintService(Printer *p, VARS &vars, p->Print("}\n"); } -static void PrintStaticImports(Printer *p) { +static void PrintStaticImports(Printer* p) { p->Print( "import java.nio.ByteBuffer;\n" "import static " @@ -1063,9 +1079,9 @@ static void PrintStaticImports(Printer *p) { "io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall;\n\n"); } -static void GenerateService(const grpc_generator::Service *service, - grpc_generator::Printer *printer, VARS &vars, - bool disable_version) { +static void GenerateService(const grpc_generator::Service* service, + grpc_generator::Printer* printer, VARS& vars, + bool disable_version) { // All non-generated classes must be referred by fully qualified names to // avoid collision with generated classes. vars["String"] = "java.lang.String"; @@ -1098,11 +1114,11 @@ static void GenerateService(const grpc_generator::Service *service, PrintService(printer, vars, service, disable_version); } -} // namespace +} // namespace grpc::string GenerateServiceSource( - grpc_generator::File *file, const grpc_generator::Service *service, - grpc_java_generator::Parameters *parameters) { + grpc_generator::File* file, const grpc_generator::Service* service, + grpc_java_generator::Parameters* parameters) { grpc::string out; auto printer = file->CreatePrinter(&out); VARS vars; diff --git a/grpc/src/compiler/java_generator.h b/grpc/src/compiler/java_generator.h index b101fbf565e..00fe3feeb57 100644 --- a/grpc/src/compiler/java_generator.h +++ b/grpc/src/compiler/java_generator.h @@ -18,6 +18,7 @@ #define NET_GRPC_COMPILER_JAVA_GENERATOR_H_ #include // for abort() + #include #include #include @@ -39,8 +40,8 @@ class LogHelper { LogHelper(std::ostream* os) : os_(os) {} #if defined(_MSC_VER) #pragma warning(push) -#pragma warning( \ - disable : 4722) // the flow of control terminates in a destructor +#pragma warning(disable \ + : 4722) // the flow of control terminates in a destructor // (needed to compile ~LogHelper where destructor emits abort intentionally - // inherited from grpc/java code generator). #endif diff --git a/grpc/src/compiler/python_generator.cc b/grpc/src/compiler/python_generator.cc index 91203a28024..f217c9d5e00 100644 --- a/grpc/src/compiler/python_generator.cc +++ b/grpc/src/compiler/python_generator.cc @@ -35,20 +35,22 @@ namespace flatbuffers { namespace python { namespace grpc { namespace { -bool ClientStreaming(const RPCCall *method) { - const Value *val = method->attributes.Lookup("streaming"); - return val != nullptr && (val->constant == "client" || val->constant == "bidi"); +bool ClientStreaming(const RPCCall* method) { + const Value* val = method->attributes.Lookup("streaming"); + return val != nullptr && + (val->constant == "client" || val->constant == "bidi"); } -bool ServerStreaming(const RPCCall *method) { - const Value *val = method->attributes.Lookup("streaming"); - return val != nullptr && (val->constant == "server" || val->constant == "bidi"); +bool ServerStreaming(const RPCCall* method) { + const Value* val = method->attributes.Lookup("streaming"); + return val != nullptr && + (val->constant == "server" || val->constant == "bidi"); } -void FormatImports(std::stringstream &ss, const Imports &imports) { +void FormatImports(std::stringstream& ss, const Imports& imports) { std::set modules; std::map> names_by_module; - for (const Import &import : imports.imports) { + for (const Import& import : imports.imports) { if (import.IsLocal()) continue; // skip all local imports if (import.name == "") { modules.insert(import.module); @@ -57,14 +59,14 @@ void FormatImports(std::stringstream &ss, const Imports &imports) { } } - for (const std::string &module : modules) { + for (const std::string& module : modules) { ss << "import " << module << '\n'; } ss << '\n'; - for (const auto &import : names_by_module) { + for (const auto& import : names_by_module) { ss << "from " << import.first << " import "; size_t i = 0; - for (const std::string &name : import.second) { + for (const std::string& name : import.second) { if (i > 0) ss << ", "; ss << name; ++i; @@ -74,8 +76,8 @@ void FormatImports(std::stringstream &ss, const Imports &imports) { ss << "\n\n"; } -bool SaveStub(const std::string &filename, const Imports &imports, - const std::string &content) { +bool SaveStub(const std::string& filename, const Imports& imports, + const std::string& content) { std::stringstream ss; ss << "# Generated by the gRPC FlatBuffers compiler. DO NOT EDIT!\n" << '\n' @@ -88,8 +90,8 @@ bool SaveStub(const std::string &filename, const Imports &imports, return flatbuffers::SaveFile(filename.c_str(), ss.str(), false); } -bool SaveService(const std::string &filename, const Imports &imports, - const std::string &content) { +bool SaveService(const std::string& filename, const Imports& imports, + const std::string& content) { std::stringstream ss; ss << "# Generated by the gRPC FlatBuffers compiler. DO NOT EDIT!\n" << '\n'; FormatImports(ss, imports); @@ -101,14 +103,15 @@ bool SaveService(const std::string &filename, const Imports &imports, class BaseGenerator { protected: - BaseGenerator(const Parser &parser, const Namer::Config &config, - const std::string &path, const Version &version) + BaseGenerator(const Parser& parser, const Namer::Config& config, + const std::string& path, const Version& version) : parser_{parser}, namer_{WithFlagOptions(config, parser.opts, path), Keywords(version)}, - version_{version} {} + version_{version}, + path_(path) {} protected: - std::string ModuleForFile(const std::string &file) const { + std::string ModuleForFile(const std::string& file) const { std::string module = parser_.opts.include_prefix + StripExtension(file) + parser_.opts.filename_suffix; std::replace(module.begin(), module.end(), '/', '.'); @@ -116,46 +119,70 @@ class BaseGenerator { } template - std::string ModuleFor(const T *def) const { + std::string ModuleFor(const T* def) const { if (parser_.opts.one_file) return ModuleForFile(def->file); return namer_.NamespacedType(*def); } - const Parser &parser_; + std::string NamespaceDir(const Parser& parser, const std::string& path, + const Namespace& ns, const bool dasherize) { + EnsureDirExists(path); + if (parser.opts.one_file) return path; + std::string namespace_dir = path; // Either empty or ends in separator. + auto& namespaces = ns.components; + for (auto it = namespaces.begin(); it != namespaces.end(); ++it) { + namespace_dir += + !dasherize ? *it : ConvertCase(*it, Case::kDasher, Case::kUpperCamel); + namespace_dir += kPathSeparator; + EnsureDirExists(namespace_dir); + } + return namespace_dir; + } + + std::string NamespaceDir(const Namespace& ns, const bool dasherize) { + return NamespaceDir(parser_, path_, ns, dasherize); + } + + const Parser& parser_; const IdlNamer namer_; const Version version_; + const std::string& path_; }; class StubGenerator : public BaseGenerator { public: - StubGenerator(const Parser &parser, const std::string &path, - const Version &version) + StubGenerator(const Parser& parser, const std::string& path, + const Version& version) : BaseGenerator(parser, kStubConfig, path, version) {} bool Generate() { Imports imports; std::stringstream stub; - for (const ServiceDef *service : parser_.services_.vec) { + std::string ns_name{}; + for (const ServiceDef* service : parser_.services_.vec) { Generate(stub, service, &imports); + ns_name = NamespaceDir(*service->defined_namespace, false); } + std::string sanitized_suffix{parser_.opts.grpc_filename_suffix}; + std::replace(sanitized_suffix.begin(), sanitized_suffix.end(), '.', '_'); std::string filename = - namer_.config_.output_path + + ns_name + kPathSeparator + StripPath(StripExtension(parser_.file_being_parsed_)) + "_grpc" + - parser_.opts.grpc_filename_suffix + namer_.config_.filename_extension; + sanitized_suffix + namer_.config_.filename_extension; return SaveStub(filename, imports, stub.str()); } private: - void Generate(std::stringstream &ss, const ServiceDef *service, - Imports *imports) { + void Generate(std::stringstream& ss, const ServiceDef* service, + Imports* imports) { imports->Import("grpc"); ss << "class " << service->name << "Stub(object):\n" << " def __init__(self, channel: grpc.Channel) -> None: ...\n"; - for (const RPCCall *method : service->calls.vec) { + for (const RPCCall* method : service->calls.vec) { std::string request = "bytes"; std::string response = "bytes"; @@ -187,7 +214,7 @@ class StubGenerator : public BaseGenerator { ss << "\n\n"; ss << "class " << service->name << "Servicer(object):\n"; - for (const RPCCall *method : service->calls.vec) { + for (const RPCCall* method : service->calls.vec) { std::string request = "bytes"; std::string response = "bytes"; @@ -226,8 +253,8 @@ class StubGenerator : public BaseGenerator { class ServiceGenerator : public BaseGenerator { public: - ServiceGenerator(const Parser &parser, const std::string &path, - const Version &version) + ServiceGenerator(const Parser& parser, const std::string& path, + const Version& version) : BaseGenerator(parser, kConfig, path, version) {} bool Generate() { @@ -247,23 +274,27 @@ class ServiceGenerator : public BaseGenerator { << '\n'; } - for (const ServiceDef *service : parser_.services_.vec) { + std::string ns_name{}; + for (const ServiceDef* service : parser_.services_.vec) { GenerateStub(ss, service, &imports); GenerateServicer(ss, service, &imports); GenerateRegister(ss, service, &imports); + ns_name = NamespaceDir(*service->defined_namespace, false); } + std::string sanitized_suffix{parser_.opts.grpc_filename_suffix}; + std::replace(sanitized_suffix.begin(), sanitized_suffix.end(), '.', '_'); std::string filename = - namer_.config_.output_path + + ns_name + kPathSeparator + StripPath(StripExtension(parser_.file_being_parsed_)) + "_grpc" + - parser_.opts.grpc_filename_suffix + namer_.config_.filename_extension; + sanitized_suffix + namer_.config_.filename_extension; return SaveService(filename, imports, ss.str()); } private: - void GenerateStub(std::stringstream &ss, const ServiceDef *service, - Imports *imports) { + void GenerateStub(std::stringstream& ss, const ServiceDef* service, + Imports* imports) { ss << "class " << service->name << "Stub"; if (version_.major != 3) ss << "(object)"; ss << ":\n" @@ -277,7 +308,7 @@ class ServiceGenerator : public BaseGenerator { << " '''\n" << '\n'; - for (const RPCCall *method : service->calls.vec) { + for (const RPCCall* method : service->calls.vec) { std::string response = namer_.Type(*method->response); imports->Import(ModuleFor(method->response), response); @@ -300,8 +331,8 @@ class ServiceGenerator : public BaseGenerator { ss << '\n'; } - void GenerateServicer(std::stringstream &ss, const ServiceDef *service, - Imports *imports) { + void GenerateServicer(std::stringstream& ss, const ServiceDef* service, + Imports* imports) { imports->Import("grpc"); ss << "class " << service->name << "Servicer"; @@ -310,7 +341,7 @@ class ServiceGenerator : public BaseGenerator { << " '''Interface exported by the server.'''\n" << '\n'; - for (const RPCCall *method : service->calls.vec) { + for (const RPCCall* method : service->calls.vec) { const std::string request_param = ClientStreaming(method) ? "request_iterator" : "request"; ss << " def " << method->name << "(self, " << request_param @@ -324,15 +355,15 @@ class ServiceGenerator : public BaseGenerator { ss << '\n'; } - void GenerateRegister(std::stringstream &ss, const ServiceDef *service, - Imports *imports) { + void GenerateRegister(std::stringstream& ss, const ServiceDef* service, + Imports* imports) { imports->Import("grpc"); ss << "def add_" << service->name << "Servicer_to_server(servicer, server):\n" << " rpc_method_handlers = {\n"; - for (const RPCCall *method : service->calls.vec) { + for (const RPCCall* method : service->calls.vec) { std::string request = namer_.Type(*method->request); imports->Import(ModuleFor(method->request), request); @@ -363,14 +394,14 @@ class ServiceGenerator : public BaseGenerator { }; } // namespace -bool Generate(const Parser &parser, const std::string &path, - const Version &version) { +bool Generate(const Parser& parser, const std::string& path, + const Version& version) { ServiceGenerator generator{parser, path, version}; return generator.Generate(); } -bool GenerateStub(const Parser &parser, const std::string &path, - const Version &version) { +bool GenerateStub(const Parser& parser, const std::string& path, + const Version& version) { StubGenerator generator{parser, path, version}; return generator.Generate(); } diff --git a/grpc/src/compiler/python_generator.h b/grpc/src/compiler/python_generator.h index 6335ecc9fbe..5967e1f84c3 100644 --- a/grpc/src/compiler/python_generator.h +++ b/grpc/src/compiler/python_generator.h @@ -27,11 +27,11 @@ namespace flatbuffers { namespace python { namespace grpc { -bool Generate(const Parser &parser, const std::string &path, - const Version &version); +bool Generate(const Parser& parser, const std::string& path, + const Version& version); -bool GenerateStub(const Parser &parser, const std::string &path, - const Version &version); +bool GenerateStub(const Parser& parser, const std::string& path, + const Version& version); } // namespace grpc } // namespace python } // namespace flatbuffers diff --git a/grpc/src/compiler/schema_interface.h b/grpc/src/compiler/schema_interface.h index f89288d7560..483d5ac6af3 100644 --- a/grpc/src/compiler/schema_interface.h +++ b/grpc/src/compiler/schema_interface.h @@ -24,8 +24,8 @@ #include #ifndef GRPC_CUSTOM_STRING -# include -# define GRPC_CUSTOM_STRING std::string +#include +#define GRPC_CUSTOM_STRING std::string #endif namespace grpc { @@ -55,10 +55,10 @@ struct Method : public CommentHolder { virtual grpc::string output_type_name() const = 0; virtual bool get_module_and_message_path_input( - grpc::string *str, grpc::string generator_file_name, + grpc::string* str, grpc::string generator_file_name, bool generate_in_pb2_grpc, grpc::string import_prefix) const = 0; virtual bool get_module_and_message_path_output( - grpc::string *str, grpc::string generator_file_name, + grpc::string* str, grpc::string generator_file_name, bool generate_in_pb2_grpc, grpc::string import_prefix) const = 0; virtual std::vector get_input_namespace_parts() const = 0; @@ -89,9 +89,9 @@ struct Service : public CommentHolder { struct Printer { virtual ~Printer() {} - virtual void Print(const std::map &vars, - const char *template_string) = 0; - virtual void Print(const char *string) = 0; + virtual void Print(const std::map& vars, + const char* template_string) = 0; + virtual void Print(const char* string) = 0; virtual void SetIndentationSize(const size_t size) = 0; virtual void Indent() = 0; virtual void Outdent() = 0; @@ -112,7 +112,7 @@ struct File : public CommentHolder { virtual std::unique_ptr service(int i) const = 0; virtual std::unique_ptr CreatePrinter( - grpc::string *str, const char indentation_type = ' ') const = 0; + grpc::string* str, const char indentation_type = ' ') const = 0; }; } // namespace grpc_generator diff --git a/grpc/src/compiler/swift_generator.cc b/grpc/src/compiler/swift_generator.cc index b0a96d869ac..b741415393f 100644 --- a/grpc/src/compiler/swift_generator.cc +++ b/grpc/src/compiler/swift_generator.cc @@ -20,34 +20,35 @@ * please open an issue in the flatbuffers repository. This file should always * be maintained according to the Swift-grpc repository */ +#include "src/compiler/swift_generator.h" + #include #include #include "flatbuffers/util.h" #include "src/compiler/schema_interface.h" -#include "src/compiler/swift_generator.h" namespace grpc_swift_generator { namespace { -static std::string WrapInNameSpace(const std::vector &components, - const grpc::string &name) { +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 + "_"; return qualified_name + name; } -static grpc::string GenerateMessage(const std::vector &components, - const grpc::string &name) { +static grpc::string GenerateMessage(const std::vector& components, + const grpc::string& name) { return "Message<" + WrapInNameSpace(components, name) + ">"; } // MARK: - Client -static void GenerateClientFuncName(const grpc_generator::Method *method, - grpc_generator::Printer *printer, - std::map *dictonary) { +static void GenerateClientFuncName( + const grpc_generator::Method* method, grpc_generator::Printer* printer, + std::map* dictonary) { auto vars = *dictonary; if (method->NoStreaming()) { printer->Print(vars, @@ -83,9 +84,9 @@ static void GenerateClientFuncName(const grpc_generator::Method *method, " ) -> BidirectionalStreamingCall<$Input$, $Output$>"); } -static void GenerateClientFuncBody(const grpc_generator::Method *method, - grpc_generator::Printer *printer, - std::map *dictonary) { +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() ?? []"; @@ -133,9 +134,9 @@ static void GenerateClientFuncBody(const grpc_generator::Method *method, " )\n"); } -void GenerateClientProtocol(const grpc_generator::Service *service, - grpc_generator::Printer *printer, - std::map *dictonary) { +void GenerateClientProtocol(const grpc_generator::Service* service, + grpc_generator::Printer* printer, + std::map* dictonary) { auto vars = *dictonary; printer->Print( vars, @@ -207,8 +208,8 @@ void GenerateClientProtocol(const grpc_generator::Service *service, printer->Print("}\n\n"); } -void GenerateClientClass(grpc_generator::Printer *printer, - std::map *dictonary) { +void GenerateClientClass(grpc_generator::Printer* printer, + std::map* dictonary) { auto vars = *dictonary; printer->Print(vars, "$ACCESS$ final class $ServiceQualifiedName$ServiceClient: " @@ -237,7 +238,7 @@ void GenerateClientClass(grpc_generator::Printer *printer, // MARK: - Server -grpc::string GenerateServerFuncName(const grpc_generator::Method *method) { +grpc::string GenerateServerFuncName(const grpc_generator::Method* method) { if (method->NoStreaming()) { return "func $MethodName$(request: $Input$" ", context: StatusOnlyCallContext) -> EventLoopFuture<$Output$>"; @@ -258,7 +259,7 @@ grpc::string GenerateServerFuncName(const grpc_generator::Method *method) { "-> EventLoopFuture<(StreamEvent<$Input$>) -> Void>"; } -grpc::string GenerateServerExtensionBody(const grpc_generator::Method *method) { +grpc::string GenerateServerExtensionBody(const grpc_generator::Method* method) { grpc::string start = " case \"$MethodName$\":\n "; grpc::string interceptors = " interceptors: self.interceptors?.make$MethodName$Interceptors() " @@ -302,9 +303,9 @@ grpc::string GenerateServerExtensionBody(const grpc_generator::Method *method) { return ""; } -void GenerateServerProtocol(const grpc_generator::Service *service, - grpc_generator::Printer *printer, - std::map *dictonary) { +void GenerateServerProtocol(const grpc_generator::Service* service, + grpc_generator::Printer* printer, + std::map* dictonary) { auto vars = *dictonary; printer->Print(vars, "$ACCESS$ protocol $ServiceQualifiedName$Provider: " @@ -373,14 +374,16 @@ void GenerateServerProtocol(const grpc_generator::Service *service, } printer->Print("}"); } -} // namespace +} // namespace -grpc::string Generate(grpc_generator::File *file, - const grpc_generator::Service *service) { +grpc::string Generate(grpc_generator::File* file, + const grpc_generator::Service* service) { grpc::string output; std::map vars; vars["PATH"] = file->package(); - if (!file->package().empty()) { vars["PATH"].append("."); } + if (!file->package().empty()) { + vars["PATH"].append("."); + } vars["ServiceQualifiedName"] = WrapInNameSpace(service->namespace_parts(), service->name()); vars["ServiceName"] = service->name(); @@ -394,6 +397,8 @@ grpc::string Generate(grpc_generator::File *file, GenerateClientClass(&*printer, &vars); printer->Print("\n"); GenerateServerProtocol(service, &*printer, &vars); + printer->Print("\n"); + printer->Print("#endif\n"); return output; } @@ -409,6 +414,7 @@ grpc::string GenerateHeader() { code += "// swiftlint:disable all\n"; code += "// swiftformat:disable all\n"; code += "\n"; + code += "#if !os(Windows)\n"; code += "import Foundation\n"; code += "import GRPC\n"; code += "import NIO\n"; @@ -428,10 +434,7 @@ grpc::string GenerateHeader() { code += " }\n"; code += " func serialize(into buffer: inout NIO.ByteBuffer) throws {\n"; - code += - " let buf = UnsafeRawBufferPointer(start: self.rawPointer, count: " - "Int(self.size))\n"; - code += " buffer.writeBytes(buf)\n"; + code += " withUnsafeReadableBytes { buffer.writeBytes($0) }\n"; code += " }\n"; code += "}\n"; code += "extension Message: GRPCFlatBufPayload {}\n"; diff --git a/grpc/src/compiler/swift_generator.h b/grpc/src/compiler/swift_generator.h index 2a226fa9409..fea1a311c16 100644 --- a/grpc/src/compiler/swift_generator.h +++ b/grpc/src/compiler/swift_generator.h @@ -20,8 +20,8 @@ #include "src/compiler/schema_interface.h" #ifndef GRPC_CUSTOM_STRING -# include -# define GRPC_CUSTOM_STRING std::string +#include +#define GRPC_CUSTOM_STRING std::string #endif namespace grpc { @@ -31,7 +31,7 @@ typedef GRPC_CUSTOM_STRING string; } // namespace grpc namespace grpc_swift_generator { -grpc::string Generate(grpc_generator::File *file, - const grpc_generator::Service *service); +grpc::string Generate(grpc_generator::File* file, + const grpc_generator::Service* service); grpc::string GenerateHeader(); } // namespace grpc_swift_generator diff --git a/grpc/src/compiler/ts_generator.cc b/grpc/src/compiler/ts_generator.cc index ff362b774a1..a5789887e80 100644 --- a/grpc/src/compiler/ts_generator.cc +++ b/grpc/src/compiler/ts_generator.cc @@ -33,8 +33,8 @@ namespace grpc_ts_generator { namespace { static grpc::string GenerateNamespace(const std::vector ns, - const std::string filename, - const bool include_separator) { + const std::string filename, + const bool include_separator) { grpc::string path = ""; if (include_separator) path += "."; @@ -56,10 +56,10 @@ static grpc::string GenerateNamespace(const std::vector ns, // MARK: - Shared code -static void GenerateImports(const grpc_generator::Service *service, - grpc_generator::Printer *printer, - std::map *dictonary, - const bool grpc_var_import) { +static void GenerateImports(const grpc_generator::Service* service, + grpc_generator::Printer* printer, + std::map* dictonary, + const bool grpc_var_import) { auto vars = *dictonary; printer->Print( "// Generated GRPC code for FlatBuffers TS *** DO NOT EDIT ***\n"); @@ -105,9 +105,9 @@ static void GenerateImports(const grpc_generator::Service *service, // MARK: - Generate Main GRPC Code -static void GetStreamType(grpc_generator::Printer *printer, - const grpc_generator::Method *method, - std::map *dictonary) { +static void GetStreamType(grpc_generator::Printer* printer, + const grpc_generator::Method* method, + std::map* dictonary) { auto vars = *dictonary; auto client_streaming = method->ClientStreaming() || method->BidiStreaming(); auto server_streaming = method->ServerStreaming() || method->BidiStreaming(); @@ -117,8 +117,9 @@ static void GetStreamType(grpc_generator::Printer *printer, printer->Print(vars, "responseStream: $ServerStreaming$,\n"); } -static void GenerateSerializeMethod(grpc_generator::Printer *printer, - std::map *dictonary) { +static void GenerateSerializeMethod( + grpc_generator::Printer* printer, + std::map* dictonary) { auto vars = *dictonary; printer->Print(vars, "function serialize_$Type$(buffer_args) {\n"); printer->Indent(); @@ -134,8 +135,8 @@ static void GenerateSerializeMethod(grpc_generator::Printer *printer, } static void GenerateDeserializeMethod( - grpc_generator::Printer *printer, - std::map *dictonary) { + grpc_generator::Printer* printer, + std::map* dictonary) { auto vars = *dictonary; printer->Print(vars, "function deserialize_$Type$(buffer) {\n"); printer->Indent(); @@ -146,9 +147,9 @@ static void GenerateDeserializeMethod( printer->Print("}\n\n"); } -static void GenerateMethods(const grpc_generator::Service *service, - grpc_generator::Printer *printer, - std::map *dictonary) { +static void GenerateMethods(const grpc_generator::Service* service, + grpc_generator::Printer* printer, + std::map* dictonary) { auto vars = *dictonary; std::set generated_functions; @@ -178,9 +179,9 @@ static void GenerateMethods(const grpc_generator::Service *service, } } -static void GenerateService(const grpc_generator::Service *service, - grpc_generator::Printer *printer, - std::map *dictonary) { +static void GenerateService(const grpc_generator::Service* service, + grpc_generator::Printer* printer, + std::map* dictonary) { auto vars = *dictonary; vars["NAME"] = service->name() + "Service"; @@ -213,17 +214,19 @@ static void GenerateService(const grpc_generator::Service *service, "grpc.makeGenericClientConstructor($NAME$);"); } -} // namespace +} // namespace -grpc::string Generate(grpc_generator::File *file, - const grpc_generator::Service *service, - const grpc::string &filename) { +grpc::string Generate(grpc_generator::File* file, + const grpc_generator::Service* service, + const grpc::string& filename) { grpc::string output; std::map vars; vars["PATH"] = file->package(); - if (!file->package().empty()) { vars["PATH"].append("."); } + if (!file->package().empty()) { + vars["PATH"].append("."); + } vars["ServiceName"] = service->name(); vars["FBSFile"] = service->name() + "_fbs"; @@ -240,8 +243,8 @@ namespace { // MARK: - Generate Interface -static void FillInterface(grpc_generator::Printer *printer, - std::map *dictonary) { +static void FillInterface(grpc_generator::Printer* printer, + std::map* dictonary) { auto vars = *dictonary; printer->Print(vars, "interface I$ServiceName$Service_I$MethodName$ extends " @@ -258,9 +261,9 @@ static void FillInterface(grpc_generator::Printer *printer, printer->Print("}\n"); } -static void GenerateInterfaces(const grpc_generator::Service *service, - grpc_generator::Printer *printer, - std::map *dictonary) { +static void GenerateInterfaces( + const grpc_generator::Service* service, grpc_generator::Printer* printer, + std::map* dictonary) { auto vars = *dictonary; for (auto it = 0; it < service->method_count(); it++) { auto method = service->method(it); @@ -281,8 +284,8 @@ static void GenerateInterfaces(const grpc_generator::Service *service, } static void GenerateExportedInterface( - const grpc_generator::Service *service, grpc_generator::Printer *printer, - std::map *dictonary) { + const grpc_generator::Service* service, grpc_generator::Printer* printer, + std::map* dictonary) { auto vars = *dictonary; printer->Print(vars, "export interface I$ServiceName$Server extends " @@ -324,9 +327,9 @@ static void GenerateExportedInterface( printer->Print("}\n"); } -static void GenerateMainInterface(const grpc_generator::Service *service, - grpc_generator::Printer *printer, - std::map *dictonary) { +static void GenerateMainInterface( + const grpc_generator::Service* service, grpc_generator::Printer* printer, + std::map* dictonary) { auto vars = *dictonary; printer->Print( vars, @@ -351,11 +354,13 @@ static void GenerateMainInterface(const grpc_generator::Service *service, static grpc::string GenerateMetaData() { return "metadata: grpc.Metadata"; } -static grpc::string GenerateOptions() { return "options: Partial"; } +static grpc::string GenerateOptions() { + return "options: Partial"; +} static void GenerateUnaryClientInterface( - grpc_generator::Printer *printer, - std::map *dictonary) { + grpc_generator::Printer* printer, + std::map* dictonary) { auto vars = *dictonary; grpc::string main = "$ISPUBLIC$$MethodName$(request: $INPUT$, "; grpc::string callback = @@ -369,8 +374,8 @@ static void GenerateUnaryClientInterface( } static void GenerateClientWriteStreamInterface( - grpc_generator::Printer *printer, - std::map *dictonary) { + grpc_generator::Printer* printer, + std::map* dictonary) { auto vars = *dictonary; grpc::string main = "$ISPUBLIC$$MethodName$("; grpc::string callback = @@ -386,8 +391,8 @@ static void GenerateClientWriteStreamInterface( } static void GenerateClientReadableStreamInterface( - grpc_generator::Printer *printer, - std::map *dictonary) { + grpc_generator::Printer* printer, + std::map* dictonary) { auto vars = *dictonary; grpc::string main = "$ISPUBLIC$$MethodName$(request: $INPUT$, "; grpc::string end_function = "): grpc.ClientReadableStream<$OUTPUT$>;\n"; @@ -398,8 +403,8 @@ static void GenerateClientReadableStreamInterface( } static void GenerateDepluxStreamInterface( - grpc_generator::Printer *printer, - std::map *dictonary) { + grpc_generator::Printer* printer, + std::map* dictonary) { auto vars = *dictonary; grpc::string main = "$ISPUBLIC$$MethodName$("; grpc::string end_function = @@ -413,9 +418,9 @@ static void GenerateDepluxStreamInterface( .c_str()); } -static void GenerateClientInterface(const grpc_generator::Service *service, - grpc_generator::Printer *printer, - std::map *dictonary) { +static void GenerateClientInterface( + const grpc_generator::Service* service, grpc_generator::Printer* printer, + std::map* dictonary) { auto vars = *dictonary; printer->Print(vars, "export interface I$ServiceName$Client {\n"); printer->Indent(); @@ -452,8 +457,8 @@ static void GenerateClientInterface(const grpc_generator::Service *service, } static void GenerateClientClassInterface( - const grpc_generator::Service *service, grpc_generator::Printer *printer, - std::map *dictonary) { + const grpc_generator::Service* service, grpc_generator::Printer* printer, + std::map* dictonary) { auto vars = *dictonary; printer->Print(vars, "export class $ServiceName$Client extends grpc.Client " @@ -492,12 +497,11 @@ static void GenerateClientClassInterface( printer->Outdent(); printer->Print("}\n"); } -} // namespace +} // namespace - -grpc::string GenerateInterface(grpc_generator::File *file, - const grpc_generator::Service *service, - const grpc::string &filename) { +grpc::string GenerateInterface(grpc_generator::File* file, + const grpc_generator::Service* service, + const grpc::string& filename) { grpc::string output; std::set generated_functions; @@ -505,7 +509,9 @@ grpc::string GenerateInterface(grpc_generator::File *file, vars["PATH"] = file->package(); - if (!file->package().empty()) { vars["PATH"].append("."); } + if (!file->package().empty()) { + vars["PATH"].append("."); + } vars["ServiceName"] = service->name(); vars["FBSFile"] = service->name() + "_fbs"; diff --git a/grpc/src/compiler/ts_generator.h b/grpc/src/compiler/ts_generator.h index a356659daac..655fc8e34fd 100644 --- a/grpc/src/compiler/ts_generator.h +++ b/grpc/src/compiler/ts_generator.h @@ -5,8 +5,8 @@ #include "src/compiler/schema_interface.h" #ifndef GRPC_CUSTOM_STRING -# include -# define GRPC_CUSTOM_STRING std::string +#include +#define GRPC_CUSTOM_STRING std::string #endif namespace grpc { @@ -16,11 +16,11 @@ typedef GRPC_CUSTOM_STRING string; } // namespace grpc namespace grpc_ts_generator { -grpc::string Generate(grpc_generator::File *file, - const grpc_generator::Service *service, - const grpc::string &filename); +grpc::string Generate(grpc_generator::File* file, + const grpc_generator::Service* service, + const grpc::string& filename); -grpc::string GenerateInterface(grpc_generator::File *file, - const grpc_generator::Service *service, - const grpc::string &filename); +grpc::string GenerateInterface(grpc_generator::File* file, + const grpc_generator::Service* service, + const grpc::string& filename); } // namespace grpc_ts_generator diff --git a/grpc/tests/BUILD b/grpc/tests/BUILD index ec7b8c14647..4ae4e7fed94 100644 --- a/grpc/tests/BUILD +++ b/grpc/tests/BUILD @@ -17,3 +17,27 @@ cc_test( "@com_github_grpc_grpc//:grpc++", ], ) + +cc_test( + name = "grpc_callback_compile_test", + srcs = ["grpctest_callback_compile.cpp"], + copts = ["-Itests"], + linkstatic = 1, + deps = [ + "//tests:monster_test_cc_fbs", + "//tests:monster_test_grpc", + "@com_github_grpc_grpc//:grpc++", + ], +) + +cc_test( + name = "grpc_callback_client_compile_test", + srcs = ["grpctest_callback_client_compile.cpp"], + copts = ["-Itests"], + linkstatic = 1, + deps = [ + "//tests:monster_test_cc_fbs", + "//tests:monster_test_grpc", + "@com_github_grpc_grpc//:grpc++", + ], +) diff --git a/grpc/tests/GameFactory.java b/grpc/tests/GameFactory.java index 520ae392090..87e792bc044 100644 --- a/grpc/tests/GameFactory.java +++ b/grpc/tests/GameFactory.java @@ -1,10 +1,11 @@ -import java.nio.ByteBuffer; import MyGame.Example.Monster; import MyGame.Example.Stat; import com.google.flatbuffers.FlatBufferBuilder; +import java.nio.ByteBuffer; class GameFactory { - public static Monster createMonster(String monsterName, short nestedMonsterHp, short nestedMonsterMana) { + public static Monster createMonster( + String monsterName, short nestedMonsterHp, short nestedMonsterMana) { FlatBufferBuilder builder = new FlatBufferBuilder(); int name_offset = builder.createString(monsterName); @@ -31,12 +32,11 @@ public static Monster createMonsterFromStat(Stat stat, int seqNo) { return monster; } - public static Stat createStat(String greeting, long val, int count) { + public static Stat createStat(String greeting, long val, int count) { FlatBufferBuilder builder = new FlatBufferBuilder(); int statOffset = Stat.createStat(builder, builder.createString(greeting), val, count); builder.finish(statOffset); Stat stat = Stat.getRootAsStat(builder.dataBuffer()); return stat; } - } diff --git a/grpc/tests/JavaGrpcTest.java b/grpc/tests/JavaGrpcTest.java index 27329116171..3bce08e6049 100644 --- a/grpc/tests/JavaGrpcTest.java +++ b/grpc/tests/JavaGrpcTest.java @@ -17,226 +17,236 @@ import MyGame.Example.Monster; import MyGame.Example.MonsterStorageGrpc; import MyGame.Example.Stat; -import com.google.flatbuffers.FlatBufferBuilder; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import io.grpc.Server; import io.grpc.ServerBuilder; import io.grpc.stub.StreamObserver; -import org.junit.Assert; - import java.io.IOException; -import java.lang.InterruptedException; -import java.nio.ByteBuffer; import java.util.Iterator; +import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.CountDownLatch; - +import java.util.concurrent.atomic.AtomicReference; +import org.junit.Assert; -/** - * Demonstrates basic client-server interaction using grpc-java over netty. - */ +/** Demonstrates basic client-server interaction using grpc-java over netty. */ public class JavaGrpcTest { - static final String BIG_MONSTER_NAME = "Cyberdemon"; - static final short nestedMonsterHp = 600; - static final short nestedMonsterMana = 1024; - static final int numStreamedMsgs = 10; - static final int timeoutMs = 3000; - static Server server; - static ManagedChannel channel; - static MonsterStorageGrpc.MonsterStorageBlockingStub blockingStub; - static MonsterStorageGrpc.MonsterStorageStub asyncStub; - - static class MyService extends MonsterStorageGrpc.MonsterStorageImplBase { - @Override - public void store(Monster request, io.grpc.stub.StreamObserver responseObserver) { - Assert.assertEquals(request.name(), BIG_MONSTER_NAME); - Assert.assertEquals(request.hp(), nestedMonsterHp); - Assert.assertEquals(request.mana(), nestedMonsterMana); - System.out.println("Received store request from " + request.name()); - // Create a response from the incoming request name. - Stat stat = GameFactory.createStat("Hello " + request.name(), 100, 10); - responseObserver.onNext(stat); - responseObserver.onCompleted(); - } - - @Override - public void retrieve(Stat request, io.grpc.stub.StreamObserver responseObserver) { - // Create 10 monsters for streaming response. - for (int i=0; i getMaxHitPoint(final StreamObserver responseObserver) { - return computeMinMax(responseObserver, false); - } - - @Override - public StreamObserver getMinMaxHitPoints(final StreamObserver responseObserver) { - return computeMinMax(responseObserver, true); - } - - private StreamObserver computeMinMax(final StreamObserver responseObserver, final boolean includeMin) { - final AtomicInteger maxHp = new AtomicInteger(Integer.MIN_VALUE); - final AtomicReference maxHpMonsterName = new AtomicReference(); - final AtomicInteger maxHpCount = new AtomicInteger(); - - final AtomicInteger minHp = new AtomicInteger(Integer.MAX_VALUE); - final AtomicReference minHpMonsterName = new AtomicReference(); - final AtomicInteger minHpCount = new AtomicInteger(); - - return new StreamObserver() { - public void onNext(Monster monster) { - if (monster.hp() > maxHp.get()) { - // Found a monster of higher hit points. - maxHp.set(monster.hp()); - maxHpMonsterName.set(monster.name()); - maxHpCount.set(1); - } - else if (monster.hp() == maxHp.get()) { - // Count how many times we saw a monster of current max hit points. - maxHpCount.getAndIncrement(); - } - - if (monster.hp() < minHp.get()) { - // Found a monster of a lower hit points. - minHp.set(monster.hp()); - minHpMonsterName.set(monster.name()); - minHpCount.set(1); - } - else if (monster.hp() == minHp.get()) { - // Count how many times we saw a monster of current min hit points. - minHpCount.getAndIncrement(); - } - } - public void onCompleted() { - Stat maxHpStat = GameFactory.createStat(maxHpMonsterName.get(), maxHp.get(), maxHpCount.get()); - // Send max hit points first. - responseObserver.onNext(maxHpStat); - if (includeMin) { - // Send min hit points. - Stat minHpStat = GameFactory.createStat(minHpMonsterName.get(), minHp.get(), minHpCount.get()); - responseObserver.onNext(minHpStat); - } - responseObserver.onCompleted(); - } - public void onError(Throwable t) { - // Not expected - Assert.fail(); - }; - }; - } + static final String BIG_MONSTER_NAME = "Cyberdemon"; + static final short nestedMonsterHp = 600; + static final short nestedMonsterMana = 1024; + static final int numStreamedMsgs = 10; + static final int timeoutMs = 3000; + static Server server; + static ManagedChannel channel; + static MonsterStorageGrpc.MonsterStorageBlockingStub blockingStub; + static MonsterStorageGrpc.MonsterStorageStub asyncStub; + + static class MyService extends MonsterStorageGrpc.MonsterStorageImplBase { + @Override + public void store(Monster request, io.grpc.stub.StreamObserver responseObserver) { + Assert.assertEquals(request.name(), BIG_MONSTER_NAME); + Assert.assertEquals(request.hp(), nestedMonsterHp); + Assert.assertEquals(request.mana(), nestedMonsterMana); + System.out.println("Received store request from " + request.name()); + // Create a response from the incoming request name. + Stat stat = GameFactory.createStat("Hello " + request.name(), 100, 10); + responseObserver.onNext(stat); + responseObserver.onCompleted(); } - @org.junit.BeforeClass - public static void startServer() throws IOException { - server = ServerBuilder.forPort(0).addService(new MyService()).build().start(); - int port = server.getPort(); - channel = ManagedChannelBuilder.forAddress("localhost", port) - // Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid - // needing certificates. - .usePlaintext() - .directExecutor() - .build(); - blockingStub = MonsterStorageGrpc.newBlockingStub(channel); - asyncStub = MonsterStorageGrpc.newStub(channel); + @Override + public void retrieve(Stat request, io.grpc.stub.StreamObserver responseObserver) { + // Create 10 monsters for streaming response. + for (int i = 0; i < numStreamedMsgs; i++) { + Monster monster = GameFactory.createMonsterFromStat(request, i); + responseObserver.onNext(monster); + } + responseObserver.onCompleted(); } - @org.junit.Test - public void testUnary() throws IOException { - Monster monsterRequest = GameFactory.createMonster(BIG_MONSTER_NAME, nestedMonsterHp, nestedMonsterMana); - Stat stat = blockingStub.store(monsterRequest); - Assert.assertEquals(stat.id(), "Hello " + BIG_MONSTER_NAME); - System.out.println("Received stat response from service: " + stat.id()); + @Override + public StreamObserver getMaxHitPoint(final StreamObserver responseObserver) { + return computeMinMax(responseObserver, false); } - @org.junit.Test - public void testServerStreaming() throws IOException { - Monster monsterRequest = GameFactory.createMonster(BIG_MONSTER_NAME, nestedMonsterHp, nestedMonsterMana); - Stat stat = blockingStub.store(monsterRequest); - Iterator iterator = blockingStub.retrieve(stat); - int counter = 0; - while(iterator.hasNext()) { - Monster m = iterator.next(); - System.out.println("Received monster " + m.name()); - counter ++; - } - Assert.assertEquals(counter, numStreamedMsgs); - System.out.println("FlatBuffers GRPC client/server test: completed successfully"); + @Override + public StreamObserver getMinMaxHitPoints(final StreamObserver responseObserver) { + return computeMinMax(responseObserver, true); } - @org.junit.Test - public void testClientStreaming() throws IOException, InterruptedException { - final AtomicReference maxHitStat = new AtomicReference(); - final CountDownLatch streamAlive = new CountDownLatch(1); + private StreamObserver computeMinMax( + final StreamObserver responseObserver, final boolean includeMin) { + final AtomicInteger maxHp = new AtomicInteger(Integer.MIN_VALUE); + final AtomicReference maxHpMonsterName = new AtomicReference(); + final AtomicInteger maxHpCount = new AtomicInteger(); + + final AtomicInteger minHp = new AtomicInteger(Integer.MAX_VALUE); + final AtomicReference minHpMonsterName = new AtomicReference(); + final AtomicInteger minHpCount = new AtomicInteger(); + + return new StreamObserver() { + public void onNext(Monster monster) { + if (monster.hp() > maxHp.get()) { + // Found a monster of higher hit points. + maxHp.set(monster.hp()); + maxHpMonsterName.set(monster.name()); + maxHpCount.set(1); + } else if (monster.hp() == maxHp.get()) { + // Count how many times we saw a monster of current max hit points. + maxHpCount.getAndIncrement(); + } + + if (monster.hp() < minHp.get()) { + // Found a monster of a lower hit points. + minHp.set(monster.hp()); + minHpMonsterName.set(monster.name()); + minHpCount.set(1); + } else if (monster.hp() == minHp.get()) { + // Count how many times we saw a monster of current min hit points. + minHpCount.getAndIncrement(); + } + } - StreamObserver statObserver = new StreamObserver() { public void onCompleted() { - streamAlive.countDown(); + Stat maxHpStat = + GameFactory.createStat(maxHpMonsterName.get(), maxHp.get(), maxHpCount.get()); + // Send max hit points first. + responseObserver.onNext(maxHpStat); + if (includeMin) { + // Send min hit points. + Stat minHpStat = + GameFactory.createStat(minHpMonsterName.get(), minHp.get(), minHpCount.get()); + responseObserver.onNext(minHpStat); + } + responseObserver.onCompleted(); } - public void onError(Throwable ex) { } - public void onNext(Stat stat) { - maxHitStat.set(stat); + + public void onError(Throwable t) { + // Not expected + Assert.fail(); } + ; }; - StreamObserver monsterStream = asyncStub.getMaxHitPoint(statObserver); - short count = 10; - for (short i = 0;i < count; ++i) { - Monster monster = GameFactory.createMonster(BIG_MONSTER_NAME + i, (short) (nestedMonsterHp * i), nestedMonsterMana); - monsterStream.onNext(monster); - } - monsterStream.onCompleted(); - // Wait a little bit for the server to send the stats of the monster with the max hit-points. - streamAlive.await(timeoutMs, TimeUnit.MILLISECONDS); - Assert.assertEquals(maxHitStat.get().id(), BIG_MONSTER_NAME + (count - 1)); - Assert.assertEquals(maxHitStat.get().val(), nestedMonsterHp * (count - 1)); - Assert.assertEquals(maxHitStat.get().count(), 1); } + } + + @org.junit.BeforeClass + public static void startServer() throws IOException { + server = ServerBuilder.forPort(0).addService(new MyService()).build().start(); + int port = server.getPort(); + channel = + ManagedChannelBuilder.forAddress("localhost", port) + // Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid + // needing certificates. + .usePlaintext() + .directExecutor() + .build(); + blockingStub = MonsterStorageGrpc.newBlockingStub(channel); + asyncStub = MonsterStorageGrpc.newStub(channel); + } + + @org.junit.Test + public void testUnary() throws IOException { + Monster monsterRequest = + GameFactory.createMonster(BIG_MONSTER_NAME, nestedMonsterHp, nestedMonsterMana); + Stat stat = blockingStub.store(monsterRequest); + Assert.assertEquals(stat.id(), "Hello " + BIG_MONSTER_NAME); + System.out.println("Received stat response from service: " + stat.id()); + } + + @org.junit.Test + public void testServerStreaming() throws IOException { + Monster monsterRequest = + GameFactory.createMonster(BIG_MONSTER_NAME, nestedMonsterHp, nestedMonsterMana); + Stat stat = blockingStub.store(monsterRequest); + Iterator iterator = blockingStub.retrieve(stat); + int counter = 0; + while (iterator.hasNext()) { + Monster m = iterator.next(); + System.out.println("Received monster " + m.name()); + counter++; + } + Assert.assertEquals(counter, numStreamedMsgs); + System.out.println("FlatBuffers GRPC client/server test: completed successfully"); + } + + @org.junit.Test + public void testClientStreaming() throws IOException, InterruptedException { + final AtomicReference maxHitStat = new AtomicReference(); + final CountDownLatch streamAlive = new CountDownLatch(1); + + StreamObserver statObserver = + new StreamObserver() { + public void onCompleted() { + streamAlive.countDown(); + } - @org.junit.Test - public void testBiDiStreaming() throws IOException, InterruptedException { - final AtomicReference maxHitStat = new AtomicReference(); - final AtomicReference minHitStat = new AtomicReference(); - final CountDownLatch streamAlive = new CountDownLatch(1); + public void onError(Throwable ex) {} - StreamObserver statObserver = new StreamObserver() { - public void onCompleted() { - streamAlive.countDown(); - } - public void onError(Throwable ex) { } - public void onNext(Stat stat) { - // We expect the server to send the max stat first and then the min stat. - if (maxHitStat.get() == null) { + public void onNext(Stat stat) { maxHitStat.set(stat); } - else { - minHitStat.set(stat); + }; + StreamObserver monsterStream = asyncStub.getMaxHitPoint(statObserver); + short count = 10; + for (short i = 0; i < count; ++i) { + Monster monster = + GameFactory.createMonster( + BIG_MONSTER_NAME + i, (short) (nestedMonsterHp * i), nestedMonsterMana); + monsterStream.onNext(monster); + } + monsterStream.onCompleted(); + // Wait a little bit for the server to send the stats of the monster with the max hit-points. + streamAlive.await(timeoutMs, TimeUnit.MILLISECONDS); + Assert.assertEquals(maxHitStat.get().id(), BIG_MONSTER_NAME + (count - 1)); + Assert.assertEquals(maxHitStat.get().val(), nestedMonsterHp * (count - 1)); + Assert.assertEquals(maxHitStat.get().count(), 1); + } + + @org.junit.Test + public void testBiDiStreaming() throws IOException, InterruptedException { + final AtomicReference maxHitStat = new AtomicReference(); + final AtomicReference minHitStat = new AtomicReference(); + final CountDownLatch streamAlive = new CountDownLatch(1); + + StreamObserver statObserver = + new StreamObserver() { + public void onCompleted() { + streamAlive.countDown(); } - } - }; - StreamObserver monsterStream = asyncStub.getMinMaxHitPoints(statObserver); - short count = 10; - for (short i = 0;i < count; ++i) { - Monster monster = GameFactory.createMonster(BIG_MONSTER_NAME + i, (short) (nestedMonsterHp * i), nestedMonsterMana); - monsterStream.onNext(monster); - } - monsterStream.onCompleted(); - - // Wait a little bit for the server to send the stats of the monster with the max and min hit-points. - streamAlive.await(timeoutMs, TimeUnit.MILLISECONDS); - Assert.assertEquals(maxHitStat.get().id(), BIG_MONSTER_NAME + (count - 1)); - Assert.assertEquals(maxHitStat.get().val(), nestedMonsterHp * (count - 1)); - Assert.assertEquals(maxHitStat.get().count(), 1); + public void onError(Throwable ex) {} - Assert.assertEquals(minHitStat.get().id(), BIG_MONSTER_NAME + 0); - Assert.assertEquals(minHitStat.get().val(), nestedMonsterHp * 0); - Assert.assertEquals(minHitStat.get().count(), 1); + public void onNext(Stat stat) { + // We expect the server to send the max stat first and then the min stat. + if (maxHitStat.get() == null) { + maxHitStat.set(stat); + } else { + minHitStat.set(stat); + } + } + }; + StreamObserver monsterStream = asyncStub.getMinMaxHitPoints(statObserver); + short count = 10; + for (short i = 0; i < count; ++i) { + Monster monster = + GameFactory.createMonster( + BIG_MONSTER_NAME + i, (short) (nestedMonsterHp * i), nestedMonsterMana); + monsterStream.onNext(monster); } + monsterStream.onCompleted(); + + // Wait a little bit for the server to send the stats of the monster with the max and min + // hit-points. + streamAlive.await(timeoutMs, TimeUnit.MILLISECONDS); + + Assert.assertEquals(maxHitStat.get().id(), BIG_MONSTER_NAME + (count - 1)); + Assert.assertEquals(maxHitStat.get().val(), nestedMonsterHp * (count - 1)); + Assert.assertEquals(maxHitStat.get().count(), 1); + + Assert.assertEquals(minHitStat.get().id(), BIG_MONSTER_NAME + 0); + Assert.assertEquals(minHitStat.get().val(), nestedMonsterHp * 0); + Assert.assertEquals(minHitStat.get().count(), 1); + } } diff --git a/grpc/tests/grpctest.cpp b/grpc/tests/grpctest.cpp index 6991b7ebb87..f4798c9b5f0 100644 --- a/grpc/tests/grpctest.cpp +++ b/grpc/tests/grpctest.cpp @@ -33,9 +33,9 @@ void message_builder_tests(); // code. It implements all rpcs specified in the FlatBuffers schema. class ServiceImpl final : public MyGame::Example::MonsterStorage::Service { virtual ::grpc::Status Store( - ::grpc::ServerContext *context, - const flatbuffers::grpc::Message *request, - flatbuffers::grpc::Message *response) override { + ::grpc::ServerContext* context, + const flatbuffers::grpc::Message* request, + flatbuffers::grpc::Message* response) override { // Create a response from the incoming request name. fbb_.Clear(); auto stat_offset = CreateStat( @@ -46,9 +46,9 @@ class ServiceImpl final : public MyGame::Example::MonsterStorage::Service { return grpc::Status::OK; } virtual ::grpc::Status Retrieve( - ::grpc::ServerContext *context, - const flatbuffers::grpc::Message *request, - ::grpc::ServerWriter> *writer) + ::grpc::ServerContext* context, + const flatbuffers::grpc::Message* request, + ::grpc::ServerWriter>* writer) override { for (int i = 0; i < 5; i++) { fbb_.Clear(); @@ -73,7 +73,7 @@ class ServiceImpl final : public MyGame::Example::MonsterStorage::Service { }; // Track the server instance, so we can terminate it later. -grpc::Server *server_instance = nullptr; +grpc::Server* server_instance = nullptr; // Mutex to protec this variable. std::mutex wait_for_server; std::condition_variable server_instance_cv; @@ -98,7 +98,8 @@ void RunServer() { server_instance->Wait(); } -template void StoreRPC(MonsterStorage::Stub *stub) { +template +void StoreRPC(MonsterStorage::Stub* stub) { Builder fbb; grpc::ClientContext context; // Build a request with the name set. @@ -119,7 +120,8 @@ template void StoreRPC(MonsterStorage::Stub *stub) { } } -template void RetrieveRPC(MonsterStorage::Stub *stub) { +template +void RetrieveRPC(MonsterStorage::Stub* stub) { Builder fbb; grpc::ClientContext context; fbb.Clear(); @@ -179,7 +181,7 @@ int grpc_server_test() { return 0; } -int main(int /*argc*/, const char * /*argv*/[]) { +int main(int /*argc*/, const char* /*argv*/[]) { message_builder_tests(); grpc_server_test(); diff --git a/grpc/tests/grpctest.py b/grpc/tests/grpctest.py index 9cfeda6891b..f2ff261d4dd 100644 --- a/grpc/tests/grpctest.py +++ b/grpc/tests/grpctest.py @@ -1,13 +1,13 @@ from __future__ import print_function +from concurrent import futures import os import sys -import grpc -import flatbuffers -from concurrent import futures +import flatbuffers +import grpc -sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'tests')) +sys.path.append(os.path.join(os.path.dirname(__file__), "..", "..", "tests")) import MyGame.Example.Monster as Monster import MyGame.Example.Stat as Stat import MyGame.Example.Vec3 as Vec3 @@ -39,136 +39,138 @@ class MonsterStorage(monster_grpc_fb.MonsterStorageServicer): - def Store(self, request, context): + def Store(self, request, context): - m = Monster.Monster().GetRootAsMonster(request, 0) + m = Monster.Monster().GetRootAsMonster(request, 0) - assert m.Name().decode("utf-8") == test_monster_name1 + assert m.Name().decode("utf-8") == test_monster_name1 - assert m.Pos().X() == test_X - assert m.Pos().Y() == test_Y - assert m.Pos().Z() == test_Z - assert m.Pos().Test1() == test_test1 - assert m.Pos().Test2() == test_color - test3 = Test.Test() - assert m.Pos().Test3(test3).A() == test_a - assert m.Pos().Test3(test3).B() == test_b + assert m.Pos().X() == test_X + assert m.Pos().Y() == test_Y + assert m.Pos().Z() == test_Z + assert m.Pos().Test1() == test_test1 + assert m.Pos().Test2() == test_color + test3 = Test.Test() + assert m.Pos().Test3(test3).A() == test_a + assert m.Pos().Test3(test3).B() == test_b - assert m.Hp() == test_hp + assert m.Hp() == test_hp - assert m.Color() == test_color + assert m.Color() == test_color - assert m.InventoryLength() == len(test_inventory) - for i in range(0, len(test_inventory)): - assert m.Inventory(i) == test_inventory[len(test_inventory)-i -1] + assert m.InventoryLength() == len(test_inventory) + for i in range(0, len(test_inventory)): + assert m.Inventory(i) == test_inventory[len(test_inventory) - i - 1] - assert m.TestType() == test_testtype + assert m.TestType() == test_testtype - assert m.Test() is not None - table = m.Test() + assert m.Test() is not None + table = m.Test() - m2 = Monster.Monster() - m2.Init(table.Bytes, table.Pos) - assert m2.Name().decode("utf-8") == test_monster_name2 + m2 = Monster.Monster() + m2.Init(table.Bytes, table.Pos) + assert m2.Name().decode("utf-8") == test_monster_name2 - m3 = m.Enemy() - assert m3.Name().decode("utf-8") == test_monster_name2 + m3 = m.Enemy() + assert m3.Name().decode("utf-8") == test_monster_name2 - assert m.Testarrayofstring(0).decode("utf-8") == test_string + assert m.Testarrayofstring(0).decode("utf-8") == test_string - b = flatbuffers.Builder(0) - i = b.CreateString(test_stat_id) - Stat.StatStart(b) - Stat.StatAddId(b, i) - Stat.StatAddVal(b, test_stat_val) - Stat.StatAddCount(b, test_stat_count) - b.Finish(Stat.StatEnd(b)) - return bytes(b.Output()) + b = flatbuffers.Builder(0) + i = b.CreateString(test_stat_id) + Stat.StatStart(b) + Stat.StatAddId(b, i) + Stat.StatAddVal(b, test_stat_val) + Stat.StatAddCount(b, test_stat_count) + b.Finish(Stat.StatEnd(b)) + return bytes(b.Output()) - def Retrieve(self, request, context): + def Retrieve(self, request, context): - s = Stat.Stat().GetRootAsStat(request, 0) + s = Stat.Stat().GetRootAsStat(request, 0) - no_of_monsters = test_no_of_monsters - for i in range(0, no_of_monsters): - b = flatbuffers.Builder(0) - i = b.CreateString(test_monsters_name_retrieve[i]) - Monster.MonsterStart(b) - Monster.MonsterAddName(b, i) - b.Finish(Monster.MonsterEnd(b)) - yield bytes(b.Output()) + no_of_monsters = test_no_of_monsters + for i in range(0, no_of_monsters): + b = flatbuffers.Builder(0) + i = b.CreateString(test_monsters_name_retrieve[i]) + Monster.MonsterStart(b) + Monster.MonsterAddName(b, i) + b.Finish(Monster.MonsterEnd(b)) + yield bytes(b.Output()) def serve(): - server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) - monster_grpc_fb.add_MonsterStorageServicer_to_server(MonsterStorage(), server) - server.add_insecure_port('[::]:50051') + server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) + monster_grpc_fb.add_MonsterStorageServicer_to_server(MonsterStorage(), server) + server.add_insecure_port("[::]:50051") - server.start() + server.start() - run() + run() def run(): - channel = grpc.insecure_channel('127.0.0.1:50051') - stub = monster_grpc_fb.MonsterStorageStub(channel) - - b = flatbuffers.Builder(0) - name2 = b.CreateString(test_monster_name2) - name1 = b.CreateString(test_monster_name1) - Monster.MonsterStart(b) - Monster.MonsterAddName(b, name2) - monster2 = Monster.MonsterEnd(b) - test1 = b.CreateString(test_string) - - Monster.MonsterStartInventoryVector(b, len(test_inventory)) - for i in range(0, len(test_inventory)): - b.PrependByte(test_inventory[i]) - inv = b.EndVector() - - Monster.MonsterStartTest4Vector(b, 2) - Test.CreateTest(b, 10, 20) - Test.CreateTest(b, 30, 40) - test4 = b.EndVector() - - Monster.MonsterStartTestarrayofstringVector(b, 1) - b.PrependUOffsetTRelative(test1) - test_array_of_string = b.EndVector() - - Monster.MonsterStart(b) - - Monster.MonsterAddHp(b, test_hp) - Monster.MonsterAddName(b, name1) - Monster.MonsterAddColor(b, test_color) - pos = Vec3.CreateVec3(b, test_X, test_Y, test_Z, test_test1, test_color, test_a, test_b) - Monster.MonsterAddPos(b, pos) - Monster.MonsterAddInventory(b, inv) - Monster.MonsterAddTestType(b, test_testtype) - Monster.MonsterAddTest(b, monster2) - Monster.MonsterAddTest4(b, test4) - Monster.MonsterAddEnemy(b, monster2) - Monster.MonsterAddTestarrayofstring(b, test_array_of_string) - monster = Monster.MonsterEnd(b) - - b.Finish(monster) - - stat_response = stub.Store(bytes(b.Output())) - - s = Stat.Stat().GetRootAsStat(stat_response, 0) - - assert s.Id().decode("utf-8") == test_stat_id - assert s.Val() == test_stat_val - assert s.Count() == test_stat_count - - monster_reponses = stub.Retrieve(stat_response) - count = 0 - for monster_reponse in monster_reponses: - m = Monster.Monster().GetRootAsMonster(monster_reponse, 0) - assert m.Name().decode("utf-8") == test_monsters_name_retrieve[count] - count = count + 1 - - -if __name__ == '__main__': - serve() + channel = grpc.insecure_channel("127.0.0.1:50051") + stub = monster_grpc_fb.MonsterStorageStub(channel) + + b = flatbuffers.Builder(0) + name2 = b.CreateString(test_monster_name2) + name1 = b.CreateString(test_monster_name1) + Monster.MonsterStart(b) + Monster.MonsterAddName(b, name2) + monster2 = Monster.MonsterEnd(b) + test1 = b.CreateString(test_string) + + Monster.MonsterStartInventoryVector(b, len(test_inventory)) + for i in range(0, len(test_inventory)): + b.PrependByte(test_inventory[i]) + inv = b.EndVector() + + Monster.MonsterStartTest4Vector(b, 2) + Test.CreateTest(b, 10, 20) + Test.CreateTest(b, 30, 40) + test4 = b.EndVector() + + Monster.MonsterStartTestarrayofstringVector(b, 1) + b.PrependUOffsetTRelative(test1) + test_array_of_string = b.EndVector() + + Monster.MonsterStart(b) + + Monster.MonsterAddHp(b, test_hp) + Monster.MonsterAddName(b, name1) + Monster.MonsterAddColor(b, test_color) + pos = Vec3.CreateVec3( + b, test_X, test_Y, test_Z, test_test1, test_color, test_a, test_b + ) + Monster.MonsterAddPos(b, pos) + Monster.MonsterAddInventory(b, inv) + Monster.MonsterAddTestType(b, test_testtype) + Monster.MonsterAddTest(b, monster2) + Monster.MonsterAddTest4(b, test4) + Monster.MonsterAddEnemy(b, monster2) + Monster.MonsterAddTestarrayofstring(b, test_array_of_string) + monster = Monster.MonsterEnd(b) + + b.Finish(monster) + + stat_response = stub.Store(bytes(b.Output())) + + s = Stat.Stat().GetRootAsStat(stat_response, 0) + + assert s.Id().decode("utf-8") == test_stat_id + assert s.Val() == test_stat_val + assert s.Count() == test_stat_count + + monster_reponses = stub.Retrieve(stat_response) + count = 0 + for monster_reponse in monster_reponses: + m = Monster.Monster().GetRootAsMonster(monster_reponse, 0) + assert m.Name().decode("utf-8") == test_monsters_name_retrieve[count] + count = count + 1 + + +if __name__ == "__main__": + serve() diff --git a/grpc/tests/grpctest_callback_client_compile.cpp b/grpc/tests/grpctest_callback_client_compile.cpp new file mode 100644 index 00000000000..b3947ee974e --- /dev/null +++ b/grpc/tests/grpctest_callback_client_compile.cpp @@ -0,0 +1,60 @@ +// Verifies that the generated gRPC callback client stub methods are present. +// This is a compile-time only test: it never performs an actual RPC. +// It supplements grpctest_callback_compile.cpp (server side) by checking +// client-side async_ / reactor entry points. + +#include + +#include "monster_test.grpc.fb.h" + +#if defined(FLATBUFFERS_GENERATED_GRPC_CALLBACK_API) && \ + defined(GRPC_CALLBACK_API_NONEXPERIMENTAL) +using Stub = MyGame::Example::MonsterStorage::Stub; +using namespace MyGame::Example; // NOLINT + +// Unary async overloads +static_assert(std::is_member_function_pointer< + decltype(static_cast&, + flatbuffers::grpc::Message*, + std::function)>( + &Stub::async_Store))>::value, + "Function-form unary async_Store missing"); +static_assert( + std::is_member_function_pointer< + decltype(static_cast&, + flatbuffers::grpc::Message*, + ::grpc::ClientUnaryReactor*)>(&Stub::async_Store))>::value, + "Reactor-form unary async_Store missing"); + +// Streaming reactor entry points +static_assert( + std::is_member_function_pointer< + decltype(static_cast&, + ::grpc::ClientReadReactor >*)>(&Stub::async_Retrieve))>::value, + "Server streaming reactor async_Retrieve missing"); +static_assert( + std::is_member_function_pointer< + decltype(static_cast*, + ::grpc::ClientWriteReactor >*)>(&Stub::async_GetMaxHitPoint))>::value, + "Client streaming reactor async_GetMaxHitPoint missing"); +static_assert(std::is_member_function_pointer< + decltype(static_cast, + flatbuffers::grpc::Message >*)>( + &Stub::async_GetMinMaxHitPoints))>::value, + "Bidi streaming reactor async_GetMinMaxHitPoints missing"); +#endif // FLATBUFFERS_GENERATED_GRPC_CALLBACK_API && + // GRPC_CALLBACK_API_NONEXPERIMENTAL + +int main() { return 0; } diff --git a/grpc/tests/grpctest_callback_compile.cpp b/grpc/tests/grpctest_callback_compile.cpp new file mode 100644 index 00000000000..d65186a4238 --- /dev/null +++ b/grpc/tests/grpctest_callback_compile.cpp @@ -0,0 +1,22 @@ +#include "monster_test.grpc.fb.h" + +// This test only verifies that the generated CallbackService compiles when the +// callback API is available. It does not run any RPCs. + +#if defined(FLATBUFFERS_GENERATED_GRPC_CALLBACK_API) && \ + defined(GRPC_CALLBACK_API_NONEXPERIMENTAL) +class CallbackServiceImpl + : public MyGame::Example::MonsterStorage::CallbackService { + public: + // For brevity we don't override methods; user code will provide reactors. +}; +#endif + +int main() { +#if defined(FLATBUFFERS_GENERATED_GRPC_CALLBACK_API) && \ + defined(GRPC_CALLBACK_API_NONEXPERIMENTAL) + CallbackServiceImpl svc; + (void)svc; // suppress unused +#endif + return 0; +} diff --git a/grpc/tests/message_builder_test.cpp b/grpc/tests/message_builder_test.cpp index 8af0c2141b9..cdaf7cb7da5 100644 --- a/grpc/tests/message_builder_test.cpp +++ b/grpc/tests/message_builder_test.cpp @@ -7,9 +7,9 @@ using MyGame::Example::Any_NONE; using MyGame::Example::CreateStat; using MyGame::Example::Vec3; -bool verify(flatbuffers::grpc::Message &msg, - const std::string &expected_name, Color expected_color) { - const Monster *monster = msg.GetRoot(); +bool verify(flatbuffers::grpc::Message& msg, + const std::string& expected_name, Color expected_color) { + const Monster* monster = msg.GetRoot(); const auto name = monster->name()->str(); const auto color = monster->color(); TEST_EQ(name, expected_name); @@ -17,8 +17,8 @@ bool verify(flatbuffers::grpc::Message &msg, return (name == expected_name) && (color == expected_color); } -bool release_n_verify(flatbuffers::grpc::MessageBuilder &mbb, - const std::string &expected_name, Color expected_color) { +bool release_n_verify(flatbuffers::grpc::MessageBuilder& mbb, + const std::string& expected_name, Color expected_color) { flatbuffers::grpc::Message msg = mbb.ReleaseMessage(); return verify(msg, expected_name, expected_color); } @@ -41,11 +41,13 @@ void builder_move_assign_after_releaseraw_test( TEST_EQ(src.GetSize(), 0); } -template +template struct BuilderReuseTests { static void builder_reusable_after_release_message_test( TestSelector selector) { - if (!selector.count(REUSABLE_AFTER_RELEASE_MESSAGE)) { return; } + if (!selector.count(REUSABLE_AFTER_RELEASE_MESSAGE)) { + return; + } flatbuffers::grpc::MessageBuilder mb; std::vector> buffers; @@ -58,7 +60,9 @@ struct BuilderReuseTests { } static void builder_reusable_after_release_test(TestSelector selector) { - if (!selector.count(REUSABLE_AFTER_RELEASE)) { return; } + if (!selector.count(REUSABLE_AFTER_RELEASE)) { + return; + } // FIXME: Populate-Release loop fails assert(GRPC_SLICE_IS_EMPTY(slice_)) in // SliceAllocator::allocate in the second iteration. @@ -74,7 +78,9 @@ struct BuilderReuseTests { } static void builder_reusable_after_releaseraw_test(TestSelector selector) { - if (!selector.count(REUSABLE_AFTER_RELEASE_RAW)) { return; } + if (!selector.count(REUSABLE_AFTER_RELEASE_RAW)) { + return; + } flatbuffers::grpc::MessageBuilder mb; for (int i = 0; i < 5; ++i) { @@ -82,14 +88,16 @@ struct BuilderReuseTests { mb.Finish(root_offset1); size_t size, offset; ::grpc::Slice slice; - const uint8_t *buf = mb.ReleaseRaw(size, offset, slice); + const uint8_t* buf = mb.ReleaseRaw(size, offset, slice); TEST_ASSERT_FUNC(verify(buf, offset, m1_name(), m1_color())); } } static void builder_reusable_after_release_and_move_assign_test( TestSelector selector) { - if (!selector.count(REUSABLE_AFTER_RELEASE_AND_MOVE_ASSIGN)) { return; } + if (!selector.count(REUSABLE_AFTER_RELEASE_AND_MOVE_ASSIGN)) { + return; + } // FIXME: Release-move_assign loop fails assert(p == // GRPC_SLICE_START_PTR(slice_)) in DetachedBuffer destructor after all the @@ -137,7 +145,9 @@ struct BuilderReuseTests { static void builder_reusable_after_releaseraw_and_move_assign_test( TestSelector selector) { - if (!selector.count(REUSABLE_AFTER_RELEASE_RAW_AND_MOVE_ASSIGN)) { return; } + if (!selector.count(REUSABLE_AFTER_RELEASE_RAW_AND_MOVE_ASSIGN)) { + return; + } flatbuffers::grpc::MessageBuilder dst; for (int i = 0; i < 5; ++i) { @@ -145,7 +155,7 @@ struct BuilderReuseTests { dst.Finish(root_offset1); size_t size, offset; ::grpc::Slice slice; - const uint8_t *buf = dst.ReleaseRaw(size, offset, slice); + const uint8_t* buf = dst.ReleaseRaw(size, offset, slice); TEST_ASSERT_FUNC(verify(buf, offset, m1_name(), m1_color())); SrcBuilder src; @@ -170,7 +180,7 @@ void slice_allocator_tests() { { size_t size = 2048; flatbuffers::grpc::SliceAllocator sa1; - uint8_t *buf = sa1.allocate(size); + uint8_t* buf = sa1.allocate(size); TEST_ASSERT_FUNC(buf != 0); buf[0] = 100; buf[size - 1] = 200; @@ -184,7 +194,7 @@ void slice_allocator_tests() { // move-assign test { flatbuffers::grpc::SliceAllocator sa1, sa2; - uint8_t *buf = sa1.allocate(2048); + uint8_t* buf = sa1.allocate(2048); sa1 = std::move(sa2); // sa1 deletes previously allocated memory in move-assign. // So buf is no longer usable here. @@ -194,7 +204,7 @@ void slice_allocator_tests() { /// This function does not populate exactly the first half of the table. But it /// could. -void populate_first_half(MyGame::Example::MonsterBuilder &wrapper, +void populate_first_half(MyGame::Example::MonsterBuilder& wrapper, flatbuffers::Offset name_offset) { wrapper.add_name(name_offset); wrapper.add_color(m1_color()); @@ -202,7 +212,7 @@ void populate_first_half(MyGame::Example::MonsterBuilder &wrapper, /// This function does not populate exactly the second half of the table. But it /// could. -void populate_second_half(MyGame::Example::MonsterBuilder &wrapper) { +void populate_second_half(MyGame::Example::MonsterBuilder& wrapper) { wrapper.add_hp(77); wrapper.add_mana(88); Vec3 vec3; @@ -216,9 +226,9 @@ void populate_second_half(MyGame::Example::MonsterBuilder &wrapper) { /// between FlatBufferBuilders. If MonsterBuilder had a fbb_ pointer, this hack /// would be unnecessary. That involves a code-generator change though. void test_only_hack_update_fbb_reference( - MyGame::Example::MonsterBuilder &monsterBuilder, - flatbuffers::grpc::MessageBuilder &mb) { - *reinterpret_cast(&monsterBuilder) = &mb; + MyGame::Example::MonsterBuilder& monsterBuilder, + flatbuffers::grpc::MessageBuilder& mb) { + *reinterpret_cast(&monsterBuilder) = &mb; } /// This test validates correctness of move conversion of FlatBufferBuilder to a @@ -351,15 +361,14 @@ void message_builder_tests() { BuilderTests::all_tests(); BuilderReuseTestSelector tests[6] = { - // REUSABLE_AFTER_RELEASE, // Assertion failed: - // (GRPC_SLICE_IS_EMPTY(slice_)) - // REUSABLE_AFTER_RELEASE_AND_MOVE_ASSIGN, // Assertion failed: (p == - // GRPC_SLICE_START_PTR(slice_) - - REUSABLE_AFTER_RELEASE_RAW, REUSABLE_AFTER_RELEASE_MESSAGE, - REUSABLE_AFTER_RELEASE_MESSAGE_AND_MOVE_ASSIGN, - REUSABLE_AFTER_RELEASE_RAW_AND_MOVE_ASSIGN - }; + // REUSABLE_AFTER_RELEASE, // Assertion failed: + // (GRPC_SLICE_IS_EMPTY(slice_)) + // REUSABLE_AFTER_RELEASE_AND_MOVE_ASSIGN, // Assertion failed: (p == + // GRPC_SLICE_START_PTR(slice_) + + REUSABLE_AFTER_RELEASE_RAW, REUSABLE_AFTER_RELEASE_MESSAGE, + REUSABLE_AFTER_RELEASE_MESSAGE_AND_MOVE_ASSIGN, + REUSABLE_AFTER_RELEASE_RAW_AND_MOVE_ASSIGN}; BuilderReuseTests::run_tests( TestSelector(tests, tests + 6)); diff --git a/include/codegen/idl_namer.h b/include/codegen/idl_namer.h index dd2fe3b8afe..2aa716ed386 100644 --- a/include/codegen/idl_namer.h +++ b/include/codegen/idl_namer.h @@ -25,69 +25,69 @@ class IdlNamer : public Namer { using Namer::Variable; using Namer::Variant; - std::string Constant(const FieldDef &d) const { return Constant(d.name); } + std::string Constant(const FieldDef& d) const { return Constant(d.name); } // Types are always structs or enums so we can only expose these two // overloads. - std::string Type(const StructDef &d) const { return Type(d.name); } - std::string Type(const EnumDef &d) const { return Type(d.name); } + std::string Type(const StructDef& d) const { return Type(d.name); } + std::string Type(const EnumDef& d) const { return Type(d.name); } - std::string Function(const Definition &s) const { return Function(s.name); } - std::string Function(const std::string& prefix, const Definition &s) const { + std::string Function(const Definition& s) const { return Function(s.name); } + std::string Function(const std::string& prefix, const Definition& s) const { return Function(prefix + s.name); } - std::string Field(const FieldDef &s) const { return Field(s.name); } - std::string Field(const FieldDef &d, const std::string &s) const { + std::string Field(const FieldDef& s) const { return Field(s.name); } + std::string Field(const FieldDef& d, const std::string& s) const { return Field(d.name + "_" + s); } - std::string Variable(const FieldDef &s) const { return Variable(s.name); } + std::string Variable(const FieldDef& s) const { return Variable(s.name); } - std::string Variable(const StructDef &s) const { return Variable(s.name); } + std::string Variable(const StructDef& s) const { return Variable(s.name); } - std::string Variant(const EnumVal &s) const { return Variant(s.name); } + std::string Variant(const EnumVal& s) const { return Variant(s.name); } - std::string EnumVariant(const EnumDef &e, const EnumVal &v) const { + std::string EnumVariant(const EnumDef& e, const EnumVal& v) const { return Type(e) + config_.enum_variant_seperator + Variant(v); } - std::string ObjectType(const StructDef &d) const { + std::string ObjectType(const StructDef& d) const { return ObjectType(d.name); } - std::string ObjectType(const EnumDef &d) const { return ObjectType(d.name); } + std::string ObjectType(const EnumDef& d) const { return ObjectType(d.name); } - std::string Method(const FieldDef &d, const std::string &suffix) const { + std::string Method(const FieldDef& d, const std::string& suffix) const { return Method(d.name, suffix); } - std::string Method(const std::string &prefix, const StructDef &d) const { + std::string Method(const std::string& prefix, const StructDef& d) const { return Method(prefix, d.name); } - std::string Method(const std::string &prefix, const FieldDef &d) const { + std::string Method(const std::string& prefix, const FieldDef& d) const { return Method(prefix, d.name); } - std::string Method(const std::string &prefix, const FieldDef &d, - const std::string &suffix) const { + std::string Method(const std::string& prefix, const FieldDef& d, + const std::string& suffix) const { return Method(prefix, d.name, suffix); } - std::string Namespace(const struct Namespace &ns) const { + std::string Namespace(const struct Namespace& ns) const { return Namespace(ns.components); } - std::string NamespacedEnumVariant(const EnumDef &e, const EnumVal &v) const { + std::string NamespacedEnumVariant(const EnumDef& e, const EnumVal& v) const { return NamespacedString(e.defined_namespace, EnumVariant(e, v)); } - std::string NamespacedType(const Definition &def) const { + std::string NamespacedType(const Definition& def) const { return NamespacedString(def.defined_namespace, Type(def.name)); } - std::string NamespacedObjectType(const Definition &def) const { + std::string NamespacedObjectType(const Definition& def) const { return NamespacedString(def.defined_namespace, ObjectType(def.name)); } - std::string Directories(const struct Namespace &ns, + std::string Directories(const struct Namespace& ns, SkipDir skips = SkipDir::None, Case input_case = Case::kUpperCamel) const { return Directories(ns.components, skips, input_case); @@ -96,19 +96,19 @@ class IdlNamer : public Namer { // Legacy fields do not really follow the usual config and should be // considered for deprecation. - std::string LegacyRustNativeVariant(const EnumVal &v) const { + std::string LegacyRustNativeVariant(const EnumVal& v) const { return ConvertCase(EscapeKeyword(v.name), Case::kUpperCamel); } - std::string LegacyRustFieldOffsetName(const FieldDef &field) const { + std::string LegacyRustFieldOffsetName(const FieldDef& field) const { return "VT_" + ConvertCase(EscapeKeyword(field.name), Case::kAllUpper); } - std::string LegacyRustUnionTypeOffsetName(const FieldDef &field) const { - return "VT_" + ConvertCase(EscapeKeyword(field.name + "_type"), Case::kAllUpper); + std::string LegacyRustUnionTypeOffsetName(const FieldDef& field) const { + return "VT_" + + ConvertCase(EscapeKeyword(field.name + "_type"), Case::kAllUpper); } - - std::string LegacySwiftVariant(const EnumVal &ev) const { + std::string LegacySwiftVariant(const EnumVal& ev) const { auto name = ev.name; if (isupper(name.front())) { std::transform(name.begin(), name.end(), name.begin(), CharToLower); @@ -117,24 +117,24 @@ class IdlNamer : public Namer { } // Also used by Kotlin, lol. - std::string LegacyJavaMethod2(const std::string &prefix, const StructDef &sd, - const std::string &suffix) const { + std::string LegacyJavaMethod2(const std::string& prefix, const StructDef& sd, + const std::string& suffix) const { return prefix + sd.name + suffix; } - std::string LegacyKotlinVariant(EnumVal &ev) const { + std::string LegacyKotlinVariant(EnumVal& ev) const { // Namer assumes the input case is snake case which is wrong... return ConvertCase(EscapeKeyword(ev.name), Case::kLowerCamel); } // Kotlin methods escapes keywords after case conversion but before // prefixing and suffixing. - std::string LegacyKotlinMethod(const std::string &prefix, const FieldDef &d, - const std::string &suffix) const { + std::string LegacyKotlinMethod(const std::string& prefix, const FieldDef& d, + const std::string& suffix) const { return prefix + ConvertCase(EscapeKeyword(d.name), Case::kUpperCamel) + suffix; } - std::string LegacyKotlinMethod(const std::string &prefix, const StructDef &d, - const std::string &suffix) const { + std::string LegacyKotlinMethod(const std::string& prefix, const StructDef& d, + const std::string& suffix) const { return prefix + ConvertCase(EscapeKeyword(d.name), Case::kUpperCamel) + suffix; } @@ -145,17 +145,19 @@ class IdlNamer : public Namer { return "mutate_" + d.name; } - std::string LegacyRustUnionTypeMethod(const FieldDef &d) { + std::string LegacyRustUnionTypeMethod(const FieldDef& d) { // assert d is a union // d should convert case but not escape keywords due to historical reasons return ConvertCase(d.name, config_.fields, Case::kLowerCamel) + "_type"; } private: - std::string NamespacedString(const struct Namespace *ns, - const std::string &str) const { + std::string NamespacedString(const struct Namespace* ns, + const std::string& str) const { std::string ret; - if (ns != nullptr) { ret += Namespace(ns->components); } + if (ns != nullptr) { + ret += Namespace(ns->components); + } if (!ret.empty()) ret += config_.namespace_seperator; return ret + str; } @@ -163,9 +165,9 @@ class IdlNamer : public Namer { // This is a temporary helper function for code generators to call until all // flag-overriding logic into flatc.cpp -inline Namer::Config WithFlagOptions(const Namer::Config &input, - const IDLOptions &opts, - const std::string &path) { +inline Namer::Config WithFlagOptions(const Namer::Config& input, + const IDLOptions& opts, + const std::string& path) { Namer::Config result = input; result.object_prefix = opts.object_prefix; result.object_suffix = opts.object_suffix; diff --git a/include/codegen/namer.h b/include/codegen/namer.h index e8b4286307b..e99bf744c39 100644 --- a/include/codegen/namer.h +++ b/include/codegen/namer.h @@ -110,49 +110,49 @@ class Namer { virtual ~Namer() {} - template std::string Method(const T &s) const { + template + std::string Method(const T& s) const { return Method(s.name); } - virtual std::string Method(const std::string &pre, - const std::string &mid, - const std::string &suf) const { - return Format(pre + "_" + mid + "_" + suf, config_.methods); + virtual std::string Method(const std::string& pre, const std::string& mid, + const std::string& suf) const { + return Format(pre + "_" + mid + "_" + suf, config_.methods); } - virtual std::string Method(const std::string &pre, - const std::string &suf) const { + virtual std::string Method(const std::string& pre, + const std::string& suf) const { return Format(pre + "_" + suf, config_.methods); } - virtual std::string Method(const std::string &s) const { + virtual std::string Method(const std::string& s) const { return Format(s, config_.methods); } - virtual std::string Constant(const std::string &s) const { + virtual std::string Constant(const std::string& s) const { return Format(s, config_.constants); } - virtual std::string Function(const std::string &s) const { + virtual std::string Function(const std::string& s) const { return Format(s, config_.functions); } - virtual std::string Variable(const std::string &s) const { + virtual std::string Variable(const std::string& s) const { return Format(s, config_.variables); } - template - std::string Variable(const std::string &p, const T &s) const { + template + std::string Variable(const std::string& p, const T& s) const { return Format(p + "_" + s.name, config_.variables); } - virtual std::string Variable(const std::string &p, - const std::string &s) const { + virtual std::string Variable(const std::string& p, + const std::string& s) const { return Format(p + "_" + s, config_.variables); } - virtual std::string Namespace(const std::string &s) const { + virtual std::string Namespace(const std::string& s) const { return Format(s, config_.namespaces); } - virtual std::string Namespace(const std::vector &ns) const { + virtual std::string Namespace(const std::vector& ns) const { std::string result; for (auto it = ns.begin(); it != ns.end(); it++) { if (it != ns.begin()) result += config_.namespace_seperator; @@ -161,14 +161,14 @@ class Namer { return result; } - virtual std::string NamespacedType(const std::vector &ns, - const std::string &s) const { + virtual std::string NamespacedType(const std::vector& ns, + const std::string& s) const { return (ns.empty() ? "" : (Namespace(ns) + config_.namespace_seperator)) + Type(s); } // Returns `filename` with the right casing, suffix, and extension. - virtual std::string File(const std::string &filename, + virtual std::string File(const std::string& filename, SkipFile skips = SkipFile::None) const { const bool skip_suffix = (skips & SkipFile::Suffix) != SkipFile::None; const bool skip_ext = (skips & SkipFile::Extension) != SkipFile::None; @@ -176,8 +176,8 @@ class Namer { (skip_suffix ? "" : config_.filename_suffix) + (skip_ext ? "" : config_.filename_extension); } - template - std::string File(const T &f, SkipFile skips = SkipFile::None) const { + template + std::string File(const T& f, SkipFile skips = SkipFile::None) const { return File(f.name, skips); } @@ -188,7 +188,7 @@ class Namer { // input_case is used to tell how to modify namespace. e.g. kUpperCamel will // add a underscode between case changes, so MyGame turns into My_Game // (depending also on the output_case). - virtual std::string Directories(const std::vector &directories, + virtual std::string Directories(const std::vector& directories, SkipDir skips = SkipDir::None, Case input_case = Case::kUpperCamel) const { const bool skip_output_path = @@ -204,7 +204,7 @@ class Namer { return result; } - virtual std::string EscapeKeyword(const std::string &name) const { + virtual std::string EscapeKeyword(const std::string& name) const { if (keywords_.find(name) == keywords_.end()) { return name; } else { @@ -212,26 +212,26 @@ class Namer { } } - virtual std::string Type(const std::string &s) const { + virtual std::string Type(const std::string& s) const { return Format(s, config_.types); } - virtual std::string Type(const std::string &t, const std::string &s) const { + virtual std::string Type(const std::string& t, const std::string& s) const { return Format(t + "_" + s, config_.types); } - virtual std::string ObjectType(const std::string &s) const { + virtual std::string ObjectType(const std::string& s) const { return config_.object_prefix + Type(s) + config_.object_suffix; } - virtual std::string Field(const std::string &s) const { + virtual std::string Field(const std::string& s) const { return Format(s, config_.fields); } - virtual std::string Variant(const std::string &s) const { + virtual std::string Variant(const std::string& s) const { return Format(s, config_.variants); } - virtual std::string Format(const std::string &s, Case casing) const { + virtual std::string Format(const std::string& s, Case casing) const { if (config_.escape_keywords == Config::Escape::BeforeConvertingCase) { return ConvertCase(EscapeKeyword(s), casing, Case::kLowerCamel); } else { @@ -242,8 +242,8 @@ class Namer { // Denamespaces a string (e.g. The.Quick.Brown.Fox) by returning the last part // after the `delimiter` (Fox) and placing the rest in `namespace_prefix` // (The.Quick.Brown). - virtual std::string Denamespace(const std::string &s, - std::string &namespace_prefix, + virtual std::string Denamespace(const std::string& s, + std::string& namespace_prefix, const char delimiter = '.') const { const size_t pos = s.find_last_of(delimiter); if (pos == std::string::npos) { @@ -255,7 +255,7 @@ class Namer { } // Same as above, but disregards the prefix. - virtual std::string Denamespace(const std::string &s, + virtual std::string Denamespace(const std::string& s, const char delimiter = '.') const { std::string prefix; return Denamespace(s, prefix, delimiter); diff --git a/include/codegen/python.cc b/include/codegen/python.cc index cea95889193..3225371766e 100644 --- a/include/codegen/python.cc +++ b/include/codegen/python.cc @@ -7,7 +7,7 @@ namespace flatbuffers { namespace python { -Version::Version(const std::string &version) { +Version::Version(const std::string& version) { std::stringstream ss(version); char dot; ss >> major >> dot >> minor >> dot >> micro; @@ -17,7 +17,7 @@ bool Version::IsValid() const { return (major == 0 || major == 2 || major == 3) && minor >= 0 && micro >= 0; } -std::set Keywords(const Version &version) { +std::set Keywords(const Version& version) { switch (version.major) { case 2: // https://docs.python.org/2/reference/lexical_analysis.html#keywords @@ -44,20 +44,36 @@ std::set Keywords(const Version &version) { } } -const python::Import &python::Imports::Import(const std::string &module) { +const python::Import& python::Imports::Import(const std::string& module) { python::Import import; import.module = module; imports.push_back(std::move(import)); return imports.back(); } -const python::Import &python::Imports::Import(const std::string &module, - const std::string &name) { +const python::Import& python::Imports::Import(const std::string& module, + const std::string& name) { python::Import import; import.module = module; import.name = name; imports.push_back(std::move(import)); return imports.back(); } + +const python::Import& python::Imports::Export(const std::string& module) { + python::Import import; + import.module = module; + exports.push_back(std::move(import)); + return exports.back(); +} + +const python::Import& python::Imports::Export(const std::string& module, + const std::string& name) { + python::Import import; + import.module = module; + import.name = name; + exports.push_back(std::move(import)); + return exports.back(); +} } // namespace python } // namespace flatbuffers diff --git a/include/codegen/python.h b/include/codegen/python.h index 778eacfc4e5..cc6c241f2d6 100644 --- a/include/codegen/python.h +++ b/include/codegen/python.h @@ -62,7 +62,7 @@ static const Namer::Config kStubConfig = { // // https://docs.python.org/3/faq/general.html#how-does-the-python-version-numbering-scheme-work struct Version { - explicit Version(const std::string &version); + explicit Version(const std::string& version); bool IsValid() const; @@ -71,7 +71,7 @@ struct Version { int16_t micro = 0; }; -std::set Keywords(const Version &version); +std::set Keywords(const Version& version); struct Import { bool IsLocal() const { return module == "."; } @@ -81,11 +81,16 @@ struct Import { }; struct Imports { - const python::Import &Import(const std::string &module); - const python::Import &Import(const std::string &module, - const std::string &name); + const python::Import& Import(const std::string& module); + const python::Import& Import(const std::string& module, + const std::string& name); + + const python::Import& Export(const std::string& module); + const python::Import& Export(const std::string& module, + const std::string& name); std::vector imports; + std::vector exports; }; } // namespace python } // namespace flatbuffers diff --git a/include/flatbuffers/allocator.h b/include/flatbuffers/allocator.h index 30427190b6c..d451818568a 100644 --- a/include/flatbuffers/allocator.h +++ b/include/flatbuffers/allocator.h @@ -28,21 +28,21 @@ class Allocator { virtual ~Allocator() {} // Allocate `size` bytes of memory. - virtual uint8_t *allocate(size_t size) = 0; + virtual uint8_t* allocate(size_t size) = 0; // Deallocate `size` bytes of memory at `p` allocated by this allocator. - virtual void deallocate(uint8_t *p, size_t size) = 0; + virtual void deallocate(uint8_t* p, size_t size) = 0; // Reallocate `new_size` bytes of memory, replacing the old region of size // `old_size` at `p`. In contrast to a normal realloc, this grows downwards, // and is intended specifcally for `vector_downward` use. // `in_use_back` and `in_use_front` indicate how much of `old_size` is // actually in use at each end, and needs to be copied. - virtual uint8_t *reallocate_downward(uint8_t *old_p, size_t old_size, + virtual uint8_t* reallocate_downward(uint8_t* old_p, size_t old_size, size_t new_size, size_t in_use_back, size_t in_use_front) { FLATBUFFERS_ASSERT(new_size > old_size); // vector_downward only grows - uint8_t *new_p = allocate(new_size); + uint8_t* new_p = allocate(new_size); memcpy_downward(old_p, old_size, new_p, new_size, in_use_back, in_use_front); deallocate(old_p, old_size); @@ -54,7 +54,7 @@ class Allocator { // to `new_p` of `new_size`. Only memory of size `in_use_front` and // `in_use_back` will be copied from the front and back of the old memory // allocation. - void memcpy_downward(uint8_t *old_p, size_t old_size, uint8_t *new_p, + void memcpy_downward(uint8_t* old_p, size_t old_size, uint8_t* new_p, size_t new_size, size_t in_use_back, size_t in_use_front) { memcpy(new_p + new_size - in_use_back, old_p + old_size - in_use_back, diff --git a/include/flatbuffers/array.h b/include/flatbuffers/array.h index f4bfbf054c4..914f479aab7 100644 --- a/include/flatbuffers/array.h +++ b/include/flatbuffers/array.h @@ -27,17 +27,15 @@ namespace flatbuffers { // This is used as a helper type for accessing arrays. -template class Array { +template +class Array { // Array can carry only POD data types (scalars or structs). typedef typename flatbuffers::bool_constant::value> scalar_tag; - typedef - typename flatbuffers::conditional::type - IndirectHelperType; public: typedef uint16_t size_type; - typedef typename IndirectHelper::return_type return_type; + typedef typename IndirectHelper::return_type return_type; typedef VectorConstIterator const_iterator; typedef VectorReverseIterator const_reverse_iterator; @@ -50,7 +48,7 @@ template class Array { return_type Get(uoffset_t i) const { FLATBUFFERS_ASSERT(i < size()); - return IndirectHelper::Read(Data(), i); + return IndirectHelper::Read(Data(), i); } return_type operator[](uoffset_t i) const { return Get(i); } @@ -58,7 +56,8 @@ template class Array { // If this is a Vector of enums, T will be its storage type, not the enum // type. This function makes it convenient to retrieve value with enum // type E. - template E GetEnum(uoffset_t i) const { + template + E GetEnum(uoffset_t i) const { return static_cast(Get(i)); } @@ -83,28 +82,28 @@ template class Array { // operation. For primitive types use @p Mutate directly. // @warning Assignments and reads to/from the dereferenced pointer are not // automatically converted to the correct endianness. - typename flatbuffers::conditional::type + typename flatbuffers::conditional::type GetMutablePointer(uoffset_t i) const { FLATBUFFERS_ASSERT(i < size()); - return const_cast(&data()[i]); + return const_cast(&data()[i]); } // Change elements if you have a non-const pointer to this object. - void Mutate(uoffset_t i, const T &val) { MutateImpl(scalar_tag(), i, val); } + void Mutate(uoffset_t i, const T& val) { MutateImpl(scalar_tag(), i, val); } // The raw data in little endian format. Use with care. - const uint8_t *Data() const { return data_; } + const uint8_t* Data() const { return data_; } - uint8_t *Data() { return data_; } + uint8_t* Data() { return data_; } // Similarly, but typed, much like std::vector::data - const T *data() const { return reinterpret_cast(Data()); } - T *data() { return reinterpret_cast(Data()); } + const T* data() const { return reinterpret_cast(Data()); } + T* data() { return reinterpret_cast(Data()); } // Copy data from a span with endian conversion. // If this Array and the span overlap, the behavior is undefined. void CopyFromSpan(flatbuffers::span src) { - const auto p1 = reinterpret_cast(src.data()); + const auto p1 = reinterpret_cast(src.data()); const auto p2 = Data(); FLATBUFFERS_ASSERT(!(p1 >= p2 && p1 < (p2 + length)) && !(p2 >= p1 && p2 < (p1 + length))); @@ -114,12 +113,12 @@ template class Array { } protected: - void MutateImpl(flatbuffers::true_type, uoffset_t i, const T &val) { + void MutateImpl(flatbuffers::true_type, uoffset_t i, const T& val) { FLATBUFFERS_ASSERT(i < size()); WriteScalar(data() + i, val); } - void MutateImpl(flatbuffers::false_type, uoffset_t i, const T &val) { + void MutateImpl(flatbuffers::false_type, uoffset_t i, const T& val) { *(GetMutablePointer(i)) = val; } @@ -134,7 +133,9 @@ template class Array { // Copy data from flatbuffers::span with endian conversion. void CopyFromSpanImpl(flatbuffers::false_type, flatbuffers::span src) { - for (size_type k = 0; k < length; k++) { Mutate(k, src[k]); } + for (size_type k = 0; k < length; k++) { + Mutate(k, src[k]); + } } // This class is only used to access pre-existing data. Don't ever @@ -153,21 +154,21 @@ template class Array { private: // This class is a pointer. Copying will therefore create an invalid object. // Private and unimplemented copy constructor. - Array(const Array &); - Array &operator=(const Array &); + Array(const Array&); + Array& operator=(const Array&); }; // Specialization for Array[struct] with access using Offset pointer. // This specialization used by idl_gen_text.cpp. -template class OffsetT> +template class OffsetT> class Array, length> { static_assert(flatbuffers::is_same::value, "unexpected type T"); public: - typedef const void *return_type; + typedef const void* return_type; typedef uint16_t size_type; - const uint8_t *Data() const { return data_; } + const uint8_t* Data() const { return data_; } // Make idl_gen_text.cpp::PrintContainer happy. return_type operator[](uoffset_t) const { @@ -178,14 +179,14 @@ class Array, length> { private: // This class is only used to access pre-existing data. Array(); - Array(const Array &); - Array &operator=(const Array &); + Array(const Array&); + Array& operator=(const Array&); uint8_t data_[1]; }; -template -FLATBUFFERS_CONSTEXPR_CPP11 flatbuffers::span make_span(Array &arr) +template +FLATBUFFERS_CONSTEXPR_CPP11 flatbuffers::span make_span(Array& arr) FLATBUFFERS_NOEXCEPT { static_assert( Array::is_span_observable, @@ -193,26 +194,26 @@ FLATBUFFERS_CONSTEXPR_CPP11 flatbuffers::span make_span(Array &arr) return span(arr.data(), N); } -template +template FLATBUFFERS_CONSTEXPR_CPP11 flatbuffers::span make_span( - const Array &arr) FLATBUFFERS_NOEXCEPT { + const Array& arr) FLATBUFFERS_NOEXCEPT { static_assert( Array::is_span_observable, "wrong type U, only plain struct, LE-scalar, or byte types are allowed"); return span(arr.data(), N); } -template +template FLATBUFFERS_CONSTEXPR_CPP11 flatbuffers::span -make_bytes_span(Array &arr) FLATBUFFERS_NOEXCEPT { +make_bytes_span(Array& arr) FLATBUFFERS_NOEXCEPT { static_assert(Array::is_span_observable, "internal error, Array might hold only scalars or structs"); return span(arr.Data(), sizeof(U) * N); } -template +template FLATBUFFERS_CONSTEXPR_CPP11 flatbuffers::span -make_bytes_span(const Array &arr) FLATBUFFERS_NOEXCEPT { +make_bytes_span(const Array& arr) FLATBUFFERS_NOEXCEPT { static_assert(Array::is_span_observable, "internal error, Array might hold only scalars or structs"); return span(arr.Data(), sizeof(U) * N); @@ -221,31 +222,31 @@ make_bytes_span(const Array &arr) FLATBUFFERS_NOEXCEPT { // Cast a raw T[length] to a raw flatbuffers::Array // without endian conversion. Use with care. // TODO: move these Cast-methods to `internal` namespace. -template -Array &CastToArray(T (&arr)[length]) { - return *reinterpret_cast *>(arr); +template +Array& CastToArray(T (&arr)[length]) { + return *reinterpret_cast*>(arr); } -template -const Array &CastToArray(const T (&arr)[length]) { - return *reinterpret_cast *>(arr); +template +const Array& CastToArray(const T (&arr)[length]) { + return *reinterpret_cast*>(arr); } -template -Array &CastToArrayOfEnum(T (&arr)[length]) { +template +Array& CastToArrayOfEnum(T (&arr)[length]) { static_assert(sizeof(E) == sizeof(T), "invalid enum type E"); - return *reinterpret_cast *>(arr); + return *reinterpret_cast*>(arr); } -template -const Array &CastToArrayOfEnum(const T (&arr)[length]) { +template +const Array& CastToArrayOfEnum(const T (&arr)[length]) { static_assert(sizeof(E) == sizeof(T), "invalid enum type E"); - return *reinterpret_cast *>(arr); + return *reinterpret_cast*>(arr); } -template -bool operator==(const Array &lhs, - const Array &rhs) noexcept { +template +bool operator==(const Array& lhs, + const Array& rhs) noexcept { return std::addressof(lhs) == std::addressof(rhs) || (lhs.size() == rhs.size() && std::memcmp(lhs.Data(), rhs.Data(), rhs.size() * sizeof(T)) == 0); diff --git a/include/flatbuffers/base.h b/include/flatbuffers/base.h index 84cb0a7d16d..987dcbc4063 100644 --- a/include/flatbuffers/base.h +++ b/include/flatbuffers/base.h @@ -140,8 +140,8 @@ #endif // !defined(FLATBUFFERS_LITTLEENDIAN) #define FLATBUFFERS_VERSION_MAJOR 25 -#define FLATBUFFERS_VERSION_MINOR 2 -#define FLATBUFFERS_VERSION_REVISION 10 +#define FLATBUFFERS_VERSION_MINOR 9 +#define FLATBUFFERS_VERSION_REVISION 23 #define FLATBUFFERS_STRING_EXPAND(X) #X #define FLATBUFFERS_STRING(X) FLATBUFFERS_STRING_EXPAND(X) namespace flatbuffers { diff --git a/include/flatbuffers/buffer.h b/include/flatbuffers/buffer.h index 94d4f7903be..154d187ab75 100644 --- a/include/flatbuffers/buffer.h +++ b/include/flatbuffers/buffer.h @@ -20,12 +20,14 @@ #include #include "flatbuffers/base.h" +#include "flatbuffers/stl_emulation.h" namespace flatbuffers { // Wrapper for uoffset_t to allow safe template specialization. // Value is allowed to be 0 to indicate a null object (see e.g. AddOffset). -template struct Offset { +template +struct Offset { // The type of offset to use. typedef uoffset_t offset_type; @@ -36,8 +38,14 @@ template struct Offset { bool IsNull() const { return !o; } }; +template +struct is_specialisation_of_Offset : false_type {}; +template +struct is_specialisation_of_Offset> : true_type {}; + // Wrapper for uoffset64_t Offsets. -template struct Offset64 { +template +struct Offset64 { // The type of offset to use. typedef uoffset64_t offset_type; @@ -48,6 +56,11 @@ template struct Offset64 { bool IsNull() const { return !o; } }; +template +struct is_specialisation_of_Offset64 : false_type {}; +template +struct is_specialisation_of_Offset64> : true_type {}; + // Litmus check for ensuring the Offsets are the expected size. static_assert(sizeof(Offset<>) == 4, "Offset has wrong size"); static_assert(sizeof(Offset64<>) == 8, "Offset64 has wrong size"); @@ -55,12 +68,13 @@ static_assert(sizeof(Offset64<>) == 8, "Offset64 has wrong size"); inline void EndianCheck() { int endiantest = 1; // If this fails, see FLATBUFFERS_LITTLEENDIAN above. - FLATBUFFERS_ASSERT(*reinterpret_cast(&endiantest) == + FLATBUFFERS_ASSERT(*reinterpret_cast(&endiantest) == FLATBUFFERS_LITTLEENDIAN); (void)endiantest; } -template FLATBUFFERS_CONSTEXPR size_t AlignOf() { +template +FLATBUFFERS_CONSTEXPR size_t AlignOf() { // clang-format off #ifdef _MSC_VER return __alignof(T); @@ -76,8 +90,8 @@ template FLATBUFFERS_CONSTEXPR size_t AlignOf() { // Lexicographically compare two strings (possibly containing nulls), and // return true if the first is less than the second. -static inline bool StringLessThan(const char *a_data, uoffset_t a_size, - const char *b_data, uoffset_t b_size) { +static inline bool StringLessThan(const char* a_data, uoffset_t a_size, + const char* b_data, uoffset_t b_size) { const auto cmp = memcmp(a_data, b_data, (std::min)(a_size, b_size)); return cmp == 0 ? a_size < b_size : cmp < 0; } @@ -90,42 +104,43 @@ static inline bool StringLessThan(const char *a_data, uoffset_t a_size, // return type like this. // The typedef is for the convenience of callers of this function // (avoiding the need for a trailing return decltype) -template struct IndirectHelper { +template +struct IndirectHelper { typedef T return_type; typedef T mutable_return_type; static const size_t element_stride = sizeof(T); - static return_type Read(const uint8_t *p, const size_t i) { - return EndianScalar((reinterpret_cast(p))[i]); + static return_type Read(const uint8_t* p, const size_t i) { + return EndianScalar((reinterpret_cast(p))[i]); } - static mutable_return_type Read(uint8_t *p, const size_t i) { + static mutable_return_type Read(uint8_t* p, const size_t i) { return reinterpret_cast( - Read(const_cast(p), i)); + Read(const_cast(p), i)); } }; // For vector of Offsets. -template class OffsetT> +template class OffsetT> struct IndirectHelper> { - typedef const T *return_type; - typedef T *mutable_return_type; + typedef const T* return_type; + typedef T* mutable_return_type; typedef typename OffsetT::offset_type offset_type; static const offset_type element_stride = sizeof(offset_type); - static return_type Read(const uint8_t *const p, const offset_type i) { + static return_type Read(const uint8_t* const p, const offset_type i) { // Offsets are relative to themselves, so first update the pointer to // point to the offset location. - const uint8_t *const offset_location = p + i * element_stride; + const uint8_t* const offset_location = p + i * element_stride; // Then read the scalar value of the offset (which may be 32 or 64-bits) and // then determine the relative location from the offset location. return reinterpret_cast( offset_location + ReadScalar(offset_location)); } - static mutable_return_type Read(uint8_t *const p, const offset_type i) { + static mutable_return_type Read(uint8_t* const p, const offset_type i) { // Offsets are relative to themselves, so first update the pointer to // point to the offset location. - uint8_t *const offset_location = p + i * element_stride; + uint8_t* const offset_location = p + i * element_stride; // Then read the scalar value of the offset (which may be 32 or 64-bits) and // then determine the relative location from the offset location. @@ -135,16 +150,26 @@ struct IndirectHelper> { }; // For vector of structs. -template struct IndirectHelper { - typedef const T *return_type; - typedef T *mutable_return_type; - static const size_t element_stride = sizeof(T); - - static return_type Read(const uint8_t *const p, const size_t i) { +template +struct IndirectHelper< + T, typename std::enable_if< + !std::is_scalar::type>::value && + !is_specialisation_of_Offset::value && + !is_specialisation_of_Offset64::value>::type> { + private: + typedef typename std::remove_pointer::type>::type + pointee_type; + + public: + typedef const pointee_type* return_type; + typedef pointee_type* mutable_return_type; + static const size_t element_stride = sizeof(pointee_type); + + static return_type Read(const uint8_t* const p, const size_t i) { // Structs are stored inline, relative to the first struct pointer. return reinterpret_cast(p + i * element_stride); } - static mutable_return_type Read(uint8_t *const p, const size_t i) { + static mutable_return_type Read(uint8_t* const p, const size_t i) { // Structs are stored inline, relative to the first struct pointer. return reinterpret_cast(p + i * element_stride); } @@ -157,14 +182,14 @@ template struct IndirectHelper { /// This function is UNDEFINED for FlatBuffers whose schema does not include /// a file_identifier (likely points at padding or the start of a the root /// vtable). -inline const char *GetBufferIdentifier(const void *buf, +inline const char* GetBufferIdentifier(const void* buf, bool size_prefixed = false) { - return reinterpret_cast(buf) + + return reinterpret_cast(buf) + ((size_prefixed) ? 2 * sizeof(uoffset_t) : sizeof(uoffset_t)); } // Helper to see if the identifier in a buffer has the expected value. -inline bool BufferHasIdentifier(const void *buf, const char *identifier, +inline bool BufferHasIdentifier(const void* buf, const char* identifier, bool size_prefixed = false) { return strncmp(GetBufferIdentifier(buf, size_prefixed), identifier, flatbuffers::kFileIdentifierLength) == 0; @@ -172,26 +197,27 @@ inline bool BufferHasIdentifier(const void *buf, const char *identifier, /// @cond FLATBUFFERS_INTERNAL // Helpers to get a typed pointer to the root object contained in the buffer. -template T *GetMutableRoot(void *buf) { +template +T* GetMutableRoot(void* buf) { if (!buf) return nullptr; EndianCheck(); - return reinterpret_cast( - reinterpret_cast(buf) + - EndianScalar(*reinterpret_cast(buf))); + return reinterpret_cast(reinterpret_cast(buf) + + EndianScalar(*reinterpret_cast(buf))); } -template -T *GetMutableSizePrefixedRoot(void *buf) { - return GetMutableRoot(reinterpret_cast(buf) + sizeof(SizeT)); +template +T* GetMutableSizePrefixedRoot(void* buf) { + return GetMutableRoot(reinterpret_cast(buf) + sizeof(SizeT)); } -template const T *GetRoot(const void *buf) { - return GetMutableRoot(const_cast(buf)); +template +const T* GetRoot(const void* buf) { + return GetMutableRoot(const_cast(buf)); } -template -const T *GetSizePrefixedRoot(const void *buf) { - return GetRoot(reinterpret_cast(buf) + sizeof(SizeT)); +template +const T* GetSizePrefixedRoot(const void* buf) { + return GetRoot(reinterpret_cast(buf) + sizeof(SizeT)); } } // namespace flatbuffers diff --git a/include/flatbuffers/buffer_ref.h b/include/flatbuffers/buffer_ref.h index f70941fc64d..746903eb972 100644 --- a/include/flatbuffers/buffer_ref.h +++ b/include/flatbuffers/buffer_ref.h @@ -27,23 +27,24 @@ namespace flatbuffers { // A BufferRef does not own its buffer. struct BufferRefBase {}; // for std::is_base_of -template struct BufferRef : BufferRefBase { +template +struct BufferRef : BufferRefBase { BufferRef() : buf(nullptr), len(0), must_free(false) {} - BufferRef(uint8_t *_buf, uoffset_t _len) + BufferRef(uint8_t* _buf, uoffset_t _len) : buf(_buf), len(_len), must_free(false) {} ~BufferRef() { if (must_free) free(buf); } - const T *GetRoot() const { return flatbuffers::GetRoot(buf); } + const T* GetRoot() const { return flatbuffers::GetRoot(buf); } bool Verify() { Verifier verifier(buf, len); return verifier.VerifyBuffer(nullptr); } - uint8_t *buf; + uint8_t* buf; uoffset_t len; bool must_free; }; diff --git a/include/flatbuffers/code_generator.h b/include/flatbuffers/code_generator.h index 2971e556eec..cc4df7f1c8b 100644 --- a/include/flatbuffers/code_generator.h +++ b/include/flatbuffers/code_generator.h @@ -45,13 +45,13 @@ class CodeGenerator { // Generate code from the provided `parser`. // // DEPRECATED: prefer using the other overload of GenerateCode for bfbs. - virtual Status GenerateCode(const Parser &parser, const std::string &path, - const std::string &filename) = 0; + virtual Status GenerateCode(const Parser& parser, const std::string& path, + const std::string& filename) = 0; // Generate code from the provided `parser` and place it in the output. - virtual Status GenerateCodeString(const Parser &parser, - const std::string &filename, - std::string &output) { + virtual Status GenerateCodeString(const Parser& parser, + const std::string& filename, + std::string& output) { (void)parser; (void)filename; (void)output; @@ -60,18 +60,18 @@ class CodeGenerator { // Generate code from the provided `buffer` of given `length`. The buffer is a // serialized reflection.fbs. - virtual Status GenerateCode(const uint8_t *buffer, int64_t length, - const CodeGenOptions &options) = 0; + virtual Status GenerateCode(const uint8_t* buffer, int64_t length, + const CodeGenOptions& options) = 0; - virtual Status GenerateMakeRule(const Parser &parser, const std::string &path, - const std::string &filename, - std::string &output) = 0; + virtual Status GenerateMakeRule(const Parser& parser, const std::string& path, + const std::string& filename, + std::string& output) = 0; - virtual Status GenerateGrpcCode(const Parser &parser, const std::string &path, - const std::string &filename) = 0; + virtual Status GenerateGrpcCode(const Parser& parser, const std::string& path, + const std::string& filename) = 0; - virtual Status GenerateRootFile(const Parser &parser, - const std::string &path) = 0; + virtual Status GenerateRootFile(const Parser& parser, + const std::string& path) = 0; virtual bool IsSchemaOnly() const = 0; @@ -88,8 +88,8 @@ class CodeGenerator { private: // Copying is not supported. - CodeGenerator(const CodeGenerator &) = delete; - CodeGenerator &operator=(const CodeGenerator &) = delete; + CodeGenerator(const CodeGenerator&) = delete; + CodeGenerator& operator=(const CodeGenerator&) = delete; }; } // namespace flatbuffers diff --git a/include/flatbuffers/code_generators.h b/include/flatbuffers/code_generators.h index fc030d43943..d284ac5a683 100644 --- a/include/flatbuffers/code_generators.h +++ b/include/flatbuffers/code_generators.h @@ -51,11 +51,11 @@ class CodeWriter { // Associates a key with a value. All subsequent calls to operator+=, where // the specified key is contained in {{ and }} delimiters will be replaced by // the given value. - void SetValue(const std::string &key, const std::string &value) { + void SetValue(const std::string& key, const std::string& value) { value_map_[key] = value; } - std::string GetValue(const std::string &key) const { + std::string GetValue(const std::string& key) const { const auto it = value_map_.find(key); return it == value_map_.end() ? "" : it->second; } @@ -76,7 +76,7 @@ class CodeWriter { if (cur_ident_lvl_) cur_ident_lvl_--; } - void SetPadding(const std::string &padding) { pad_ = padding; } + void SetPadding(const std::string& padding) { pad_ = padding; } private: std::map value_map_; @@ -86,24 +86,24 @@ class CodeWriter { bool ignore_ident_; // Add ident padding (tab or space) based on ident level - void AppendIdent(std::stringstream &stream); + void AppendIdent(std::stringstream& stream); }; class BaseGenerator { public: virtual bool generate() = 0; - static std::string NamespaceDir(const Parser &parser, const std::string &path, - const Namespace &ns, + static std::string NamespaceDir(const Parser& parser, const std::string& path, + const Namespace& ns, const bool dasherize = false); - std::string GeneratedFileName(const std::string &path, - const std::string &file_name, - const IDLOptions &options) const; + std::string GeneratedFileName(const std::string& path, + const std::string& file_name, + const IDLOptions& options) const; protected: - BaseGenerator(const Parser &parser, const std::string &path, - const std::string &file_name, std::string qualifying_start, + BaseGenerator(const Parser& parser, const std::string& path, + const std::string& file_name, std::string qualifying_start, std::string qualifying_separator, std::string default_extension) : parser_(parser), path_(path), @@ -114,84 +114,84 @@ class BaseGenerator { virtual ~BaseGenerator() {} // No copy/assign. - BaseGenerator &operator=(const BaseGenerator &); - BaseGenerator(const BaseGenerator &); + BaseGenerator& operator=(const BaseGenerator&); + BaseGenerator(const BaseGenerator&); - std::string NamespaceDir(const Namespace &ns, + std::string NamespaceDir(const Namespace& ns, const bool dasherize = false) const; - static const char *FlatBuffersGeneratedWarning(); + static const char* FlatBuffersGeneratedWarning(); - static std::string FullNamespace(const char *separator, const Namespace &ns); + static std::string FullNamespace(const char* separator, const Namespace& ns); - static std::string LastNamespacePart(const Namespace &ns); + static std::string LastNamespacePart(const Namespace& ns); // tracks the current namespace for early exit in WrapInNameSpace // c++, java and csharp returns a different namespace from // the following default (no early exit, always fully qualify), // which works for js and php - virtual const Namespace *CurrentNameSpace() const { return nullptr; } + virtual const Namespace* CurrentNameSpace() const { return nullptr; } // Ensure that a type is prefixed with its namespace even within // its own namespace to avoid conflict between generated method // names and similarly named classes or structs - std::string WrapInNameSpace(const Namespace *ns, - const std::string &name) const; + std::string WrapInNameSpace(const Namespace* ns, + const std::string& name) const; - std::string WrapInNameSpace(const Definition &def, - const std::string &suffix = "") const; + std::string WrapInNameSpace(const Definition& def, + const std::string& suffix = "") const; - std::string GetNameSpace(const Definition &def) const; + std::string GetNameSpace(const Definition& def) const; - const Parser &parser_; - const std::string &path_; - const std::string &file_name_; + const Parser& parser_; + const std::string& path_; + const std::string& file_name_; const std::string qualifying_start_; const std::string qualifying_separator_; const std::string default_extension_; }; struct CommentConfig { - const char *first_line; - const char *content_line_prefix; - const char *last_line; + const char* first_line; + const char* content_line_prefix; + const char* last_line; }; -extern void GenComment(const std::vector &dc, - std::string *code_ptr, const CommentConfig *config, - const char *prefix = ""); +extern void GenComment(const std::vector& dc, + std::string* code_ptr, const CommentConfig* config, + const char* prefix = ""); class FloatConstantGenerator { public: virtual ~FloatConstantGenerator() {} - std::string GenFloatConstant(const FieldDef &field) const; + std::string GenFloatConstant(const FieldDef& field) const; private: - virtual std::string Value(double v, const std::string &src) const = 0; + virtual std::string Value(double v, const std::string& src) const = 0; virtual std::string Inf(double v) const = 0; virtual std::string NaN(double v) const = 0; - virtual std::string Value(float v, const std::string &src) const = 0; + virtual std::string Value(float v, const std::string& src) const = 0; virtual std::string Inf(float v) const = 0; virtual std::string NaN(float v) const = 0; - template - std::string GenFloatConstantImpl(const FieldDef &field) const; + template + std::string GenFloatConstantImpl(const FieldDef& field) const; }; class SimpleFloatConstantGenerator : public FloatConstantGenerator { public: - SimpleFloatConstantGenerator(const char *nan_number, - const char *pos_inf_number, - const char *neg_inf_number); + SimpleFloatConstantGenerator(const char* nan_number, + const char* pos_inf_number, + const char* neg_inf_number); private: std::string Value(double v, - const std::string &src) const FLATBUFFERS_OVERRIDE; + const std::string& src) const FLATBUFFERS_OVERRIDE; std::string Inf(double v) const FLATBUFFERS_OVERRIDE; std::string NaN(double v) const FLATBUFFERS_OVERRIDE; - std::string Value(float v, const std::string &src) const FLATBUFFERS_OVERRIDE; + std::string Value(float v, const std::string& src) const FLATBUFFERS_OVERRIDE; std::string Inf(float v) const FLATBUFFERS_OVERRIDE; std::string NaN(float v) const FLATBUFFERS_OVERRIDE; @@ -203,24 +203,24 @@ class SimpleFloatConstantGenerator : public FloatConstantGenerator { // C++, C#, Java like generator. class TypedFloatConstantGenerator : public FloatConstantGenerator { public: - TypedFloatConstantGenerator(const char *double_prefix, - const char *single_prefix, const char *nan_number, - const char *pos_inf_number, - const char *neg_inf_number = ""); + TypedFloatConstantGenerator(const char* double_prefix, + const char* single_prefix, const char* nan_number, + const char* pos_inf_number, + const char* neg_inf_number = ""); private: std::string Value(double v, - const std::string &src) const FLATBUFFERS_OVERRIDE; + const std::string& src) const FLATBUFFERS_OVERRIDE; std::string Inf(double v) const FLATBUFFERS_OVERRIDE; std::string NaN(double v) const FLATBUFFERS_OVERRIDE; - std::string Value(float v, const std::string &src) const FLATBUFFERS_OVERRIDE; + std::string Value(float v, const std::string& src) const FLATBUFFERS_OVERRIDE; std::string Inf(float v) const FLATBUFFERS_OVERRIDE; std::string NaN(float v) const FLATBUFFERS_OVERRIDE; - std::string MakeNaN(const std::string &prefix) const; - std::string MakeInf(bool neg, const std::string &prefix) const; + std::string MakeNaN(const std::string& prefix) const; + std::string MakeInf(bool neg, const std::string& prefix) const; const std::string double_prefix_; const std::string single_prefix_; @@ -229,9 +229,9 @@ class TypedFloatConstantGenerator : public FloatConstantGenerator { const std::string neg_inf_number_; }; -std::string JavaCSharpMakeRule(const bool java, const Parser &parser, - const std::string &path, - const std::string &file_name); +std::string JavaCSharpMakeRule(const bool java, const Parser& parser, + const std::string& path, + const std::string& file_name); } // namespace flatbuffers diff --git a/include/flatbuffers/default_allocator.h b/include/flatbuffers/default_allocator.h index d4724122cb5..d1cab08d743 100644 --- a/include/flatbuffers/default_allocator.h +++ b/include/flatbuffers/default_allocator.h @@ -25,32 +25,32 @@ namespace flatbuffers { // DefaultAllocator uses new/delete to allocate memory regions class DefaultAllocator : public Allocator { public: - uint8_t *allocate(size_t size) FLATBUFFERS_OVERRIDE { + uint8_t* allocate(size_t size) FLATBUFFERS_OVERRIDE { return new uint8_t[size]; } - void deallocate(uint8_t *p, size_t) FLATBUFFERS_OVERRIDE { delete[] p; } + void deallocate(uint8_t* p, size_t) FLATBUFFERS_OVERRIDE { delete[] p; } - static void dealloc(void *p, size_t) { delete[] static_cast(p); } + static void dealloc(void* p, size_t) { delete[] static_cast(p); } }; // These functions allow for a null allocator to mean use the default allocator, // as used by DetachedBuffer and vector_downward below. // This is to avoid having a statically or dynamically allocated default // allocator, or having to move it between the classes that may own it. -inline uint8_t *Allocate(Allocator *allocator, size_t size) { +inline uint8_t* Allocate(Allocator* allocator, size_t size) { return allocator ? allocator->allocate(size) : DefaultAllocator().allocate(size); } -inline void Deallocate(Allocator *allocator, uint8_t *p, size_t size) { +inline void Deallocate(Allocator* allocator, uint8_t* p, size_t size) { if (allocator) allocator->deallocate(p, size); else DefaultAllocator().deallocate(p, size); } -inline uint8_t *ReallocateDownward(Allocator *allocator, uint8_t *old_p, +inline uint8_t* ReallocateDownward(Allocator* allocator, uint8_t* old_p, size_t old_size, size_t new_size, size_t in_use_back, size_t in_use_front) { return allocator ? allocator->reallocate_downward(old_p, old_size, new_size, diff --git a/include/flatbuffers/detached_buffer.h b/include/flatbuffers/detached_buffer.h index 36d3f6d6deb..0577a42d969 100644 --- a/include/flatbuffers/detached_buffer.h +++ b/include/flatbuffers/detached_buffer.h @@ -36,8 +36,8 @@ class DetachedBuffer { cur_(nullptr), size_(0) {} - DetachedBuffer(Allocator *allocator, bool own_allocator, uint8_t *buf, - size_t reserved, uint8_t *cur, size_t sz) + DetachedBuffer(Allocator* allocator, bool own_allocator, uint8_t* buf, + size_t reserved, uint8_t* cur, size_t sz) : allocator_(allocator), own_allocator_(own_allocator), buf_(buf), @@ -45,7 +45,7 @@ class DetachedBuffer { cur_(cur), size_(sz) {} - DetachedBuffer(DetachedBuffer &&other) noexcept + DetachedBuffer(DetachedBuffer&& other) noexcept : allocator_(other.allocator_), own_allocator_(other.own_allocator_), buf_(other.buf_), @@ -55,7 +55,7 @@ class DetachedBuffer { other.reset(); } - DetachedBuffer &operator=(DetachedBuffer &&other) noexcept { + DetachedBuffer& operator=(DetachedBuffer&& other) noexcept { if (this == &other) return *this; destroy(); @@ -74,33 +74,35 @@ class DetachedBuffer { ~DetachedBuffer() { destroy(); } - const uint8_t *data() const { return cur_; } + const uint8_t* data() const { return cur_; } - uint8_t *data() { return cur_; } + uint8_t* data() { return cur_; } size_t size() const { return size_; } - uint8_t *begin() { return data(); } - const uint8_t *begin() const { return data(); } - uint8_t *end() { return data() + size(); } - const uint8_t *end() const { return data() + size(); } + uint8_t* begin() { return data(); } + const uint8_t* begin() const { return data(); } + uint8_t* end() { return data() + size(); } + const uint8_t* end() const { return data() + size(); } // These may change access mode, leave these at end of public section - FLATBUFFERS_DELETE_FUNC(DetachedBuffer(const DetachedBuffer &other)); + FLATBUFFERS_DELETE_FUNC(DetachedBuffer(const DetachedBuffer& other)); FLATBUFFERS_DELETE_FUNC( - DetachedBuffer &operator=(const DetachedBuffer &other)); + DetachedBuffer& operator=(const DetachedBuffer& other)); protected: - Allocator *allocator_; + Allocator* allocator_; bool own_allocator_; - uint8_t *buf_; + uint8_t* buf_; size_t reserved_; - uint8_t *cur_; + uint8_t* cur_; size_t size_; inline void destroy() { if (buf_) Deallocate(allocator_, buf_, reserved_); - if (own_allocator_ && allocator_) { delete allocator_; } + if (own_allocator_ && allocator_) { + delete allocator_; + } reset(); } diff --git a/include/flatbuffers/file_manager.h b/include/flatbuffers/file_manager.h index 069df5b8842..0941faef662 100644 --- a/include/flatbuffers/file_manager.h +++ b/include/flatbuffers/file_manager.h @@ -31,16 +31,16 @@ class FileManager { FileManager() = default; virtual ~FileManager() = default; - virtual bool SaveFile(const std::string &absolute_file_name, - const std::string &content) = 0; + virtual bool SaveFile(const std::string& absolute_file_name, + const std::string& content) = 0; - virtual bool LoadFile(const std::string &absolute_file_name, - std::string *buf) = 0; + virtual bool LoadFile(const std::string& absolute_file_name, + std::string* buf) = 0; private: // Copying is not supported. - FileManager(const FileManager &) = delete; - FileManager &operator=(const FileManager &) = delete; + FileManager(const FileManager&) = delete; + FileManager& operator=(const FileManager&) = delete; }; } // namespace flatbuffers diff --git a/include/flatbuffers/flatbuffer_builder.h b/include/flatbuffers/flatbuffer_builder.h index 9ceca8207b6..9eea6bab0c5 100644 --- a/include/flatbuffers/flatbuffer_builder.h +++ b/include/flatbuffers/flatbuffer_builder.h @@ -50,19 +50,19 @@ inline voffset_t FieldIndexToOffset(voffset_t field_id) { return static_cast(offset); } -template> -const T *data(const std::vector &v) { +template > +const T* data(const std::vector& v) { // Eventually the returned pointer gets passed down to memcpy, so // we need it to be non-null to avoid undefined behavior. static uint8_t t; - return v.empty() ? reinterpret_cast(&t) : &v.front(); + return v.empty() ? reinterpret_cast(&t) : &v.front(); } -template> -T *data(std::vector &v) { +template > +T* data(std::vector& v) { // Eventually the returned pointer gets passed down to memcpy, so // we need it to be non-null to avoid undefined behavior. static uint8_t t; - return v.empty() ? reinterpret_cast(&t) : &v.front(); + return v.empty() ? reinterpret_cast(&t) : &v.front(); } /// @addtogroup flatbuffers_cpp_api @@ -74,7 +74,8 @@ T *data(std::vector &v) { /// `PushElement`/`AddElement`/`EndTable`, or the builtin `CreateString`/ /// `CreateVector` functions. Do this is depth-first order to build up a tree to /// the root. `Finish()` wraps up the buffer ready for transport. -template class FlatBufferBuilderImpl { +template +class FlatBufferBuilderImpl { public: // This switches the size type of the builder, based on if its 64-bit aware // (uoffset64_t) or not (uoffset_t). @@ -93,7 +94,7 @@ template class FlatBufferBuilderImpl { /// types with custom alignment AND you wish to read the buffer in-place /// directly after creation. explicit FlatBufferBuilderImpl( - size_t initial_size = 1024, Allocator *allocator = nullptr, + size_t initial_size = 1024, Allocator* allocator = nullptr, bool own_allocator = false, size_t buffer_minalign = AlignOf()) : buf_(initial_size, allocator, own_allocator, buffer_minalign, @@ -112,7 +113,7 @@ template class FlatBufferBuilderImpl { } /// @brief Move constructor for FlatBufferBuilder. - FlatBufferBuilderImpl(FlatBufferBuilderImpl &&other) noexcept + FlatBufferBuilderImpl(FlatBufferBuilderImpl&& other) noexcept : buf_(1024, nullptr, false, AlignOf(), static_cast(Is64Aware ? FLATBUFFERS_MAX_64_BUFFER_SIZE : FLATBUFFERS_MAX_BUFFER_SIZE)), @@ -133,14 +134,14 @@ template class FlatBufferBuilderImpl { } /// @brief Move assignment operator for FlatBufferBuilder. - FlatBufferBuilderImpl &operator=(FlatBufferBuilderImpl &&other) noexcept { + FlatBufferBuilderImpl& operator=(FlatBufferBuilderImpl&& other) noexcept { // Move construct a temporary and swap idiom FlatBufferBuilderImpl temp(std::move(other)); Swap(temp); return *this; } - void Swap(FlatBufferBuilderImpl &other) { + void Swap(FlatBufferBuilderImpl& other) { using std::swap; buf_.swap(other.buf_); swap(num_field_loc, other.num_field_loc); @@ -182,7 +183,7 @@ template class FlatBufferBuilderImpl { /// @brief The current size of the serialized buffer relative to the end of /// the 32-bit region. /// @return Returns an `uoffset_t` with the current size of the buffer. - template + template // Only enable this method for the 64-bit builder, as only that builder is // concerned with the 32/64-bit boundary, and should be the one to bare any // run time costs. @@ -195,7 +196,7 @@ template class FlatBufferBuilderImpl { return static_cast(GetSize() - length_of_64_bit_region_); } - template + template // Only enable this method for the 32-bit builder. typename std::enable_if::type GetSizeRelative32BitRegion() const { @@ -205,7 +206,7 @@ template class FlatBufferBuilderImpl { /// @brief Get the serialized buffer (after you call `Finish()`). /// @return Returns an `uint8_t` pointer to the FlatBuffer data inside the /// buffer. - uint8_t *GetBufferPointer() const { + uint8_t* GetBufferPointer() const { Finished(); return buf_.data(); } @@ -220,7 +221,7 @@ template class FlatBufferBuilderImpl { /// @brief Get a pointer to an unfinished buffer. /// @return Returns a `uint8_t` pointer to the unfinished buffer. - uint8_t *GetCurrentBufferPointer() const { return buf_.data(); } + uint8_t* GetCurrentBufferPointer() const { return buf_.data(); } /// @brief Get the released DetachedBuffer. /// @return A `DetachedBuffer` that owns the buffer and its allocator. @@ -240,9 +241,9 @@ template class FlatBufferBuilderImpl { /// the serialized `FlatBuffer`. /// @remark If the allocator is owned, it gets deleted when the destructor is /// called. - uint8_t *ReleaseRaw(size_t &size, size_t &offset) { + uint8_t* ReleaseRaw(size_t& size, size_t& offset) { Finished(); - uint8_t *raw = buf_.release_raw(size, offset); + uint8_t* raw = buf_.release_raw(size, offset); Clear(); return raw; } @@ -291,22 +292,23 @@ template class FlatBufferBuilderImpl { buf_.fill(PaddingBytes(buf_.size(), elem_size)); } - void PushFlatBuffer(const uint8_t *bytes, size_t size) { + void PushFlatBuffer(const uint8_t* bytes, size_t size) { PushBytes(bytes, size); finished = true; } - void PushBytes(const uint8_t *bytes, size_t size) { buf_.push(bytes, size); } + void PushBytes(const uint8_t* bytes, size_t size) { buf_.push(bytes, size); } void PopBytes(size_t amount) { buf_.pop(amount); } - template void AssertScalarT() { + template + void AssertScalarT() { // The code assumes power of 2 sizes and endian-swap-ability. static_assert(flatbuffers::is_scalar::value, "T must be a scalar type"); } // Write a single aligned scalar to the buffer - template + template ReturnT PushElement(T element) { AssertScalarT(); Align(sizeof(T)); @@ -314,7 +316,7 @@ template class FlatBufferBuilderImpl { return CalculateOffset(); } - template class OffsetT = Offset> + template class OffsetT = Offset> uoffset_t PushElement(OffsetT off) { // Special case for offsets: see ReferTo below. return PushElement(ReferTo(off.o)); @@ -323,34 +325,41 @@ template class FlatBufferBuilderImpl { // When writing fields, we track where they are, so we can create correct // vtables later. void TrackField(voffset_t field, uoffset_t off) { - FieldLoc fl = { off, field }; + FieldLoc fl = {off, field}; buf_.scratch_push_small(fl); num_field_loc++; - if (field > max_voffset_) { max_voffset_ = field; } + if (field > max_voffset_) { + max_voffset_ = field; + } } // Like PushElement, but additionally tracks the field this represents. - template void AddElement(voffset_t field, T e, T def) { + template + void AddElement(voffset_t field, T e, T def) { // We don't serialize values equal to the default. if (IsTheSameAs(e, def) && !force_defaults_) return; TrackField(field, PushElement(e)); } - template void AddElement(voffset_t field, T e) { + template + void AddElement(voffset_t field, T e) { TrackField(field, PushElement(e)); } - template void AddOffset(voffset_t field, Offset off) { + template + void AddOffset(voffset_t field, Offset off) { if (off.IsNull()) return; // Don't store. AddElement(field, ReferTo(off.o), static_cast(0)); } - template void AddOffset(voffset_t field, Offset64 off) { + template + void AddOffset(voffset_t field, Offset64 off) { if (off.IsNull()) return; // Don't store. AddElement(field, ReferTo(off.o), static_cast(0)); } - template void AddStruct(voffset_t field, const T *structptr) { + template + void AddStruct(voffset_t field, const T* structptr) { if (!structptr) return; // Default, don't store. Align(AlignOf()); buf_.push_small(*structptr); @@ -380,12 +389,14 @@ template class FlatBufferBuilderImpl { return ReferTo(off, GetSize()); } - template T ReferTo(const T off, const T2 size) { + template + T ReferTo(const T off, const T2 size) { FLATBUFFERS_ASSERT(off && off <= size); return size - off + static_cast(sizeof(T)); } - template T ReferTo(const T off, const T size) { + template + T ReferTo(const T off, const T size) { FLATBUFFERS_ASSERT(off && off <= size); return size - off + static_cast(sizeof(T)); } @@ -441,7 +452,7 @@ template class FlatBufferBuilderImpl { // Write the offsets into the table for (auto it = buf_.scratch_end() - num_field_loc * sizeof(FieldLoc); it < buf_.scratch_end(); it += sizeof(FieldLoc)) { - auto field_location = reinterpret_cast(it); + auto field_location = reinterpret_cast(it); const voffset_t pos = static_cast(vtable_offset_loc - field_location->off); // If this asserts, it means you've set a field twice. @@ -450,7 +461,7 @@ template class FlatBufferBuilderImpl { WriteScalar(buf_.data() + field_location->id, pos); } ClearOffsets(); - auto vt1 = reinterpret_cast(buf_.data()); + auto vt1 = reinterpret_cast(buf_.data()); auto vt1_size = ReadScalar(vt1); auto vt_use = GetSizeRelative32BitRegion(); // See if we already have generated a vtable with this exact same @@ -458,8 +469,8 @@ template class FlatBufferBuilderImpl { if (dedup_vtables_) { for (auto it = buf_.scratch_data(); it < buf_.scratch_end(); it += sizeof(uoffset_t)) { - auto vt_offset_ptr = reinterpret_cast(it); - auto vt2 = reinterpret_cast(buf_.data_at(*vt_offset_ptr)); + auto vt_offset_ptr = reinterpret_cast(it); + auto vt2 = reinterpret_cast(buf_.data_at(*vt_offset_ptr)); auto vt2_size = ReadScalar(vt2); if (vt1_size != vt2_size || 0 != memcmp(vt2, vt1, vt1_size)) continue; vt_use = *vt_offset_ptr; @@ -490,8 +501,9 @@ template class FlatBufferBuilderImpl { // This checks a required field has been set in a given table that has // just been constructed. - template void Required(Offset table, voffset_t field) { - auto table_ptr = reinterpret_cast(buf_.data_at(table.o)); + template + void Required(Offset table, voffset_t field) { + auto table_ptr = reinterpret_cast(buf_.data_at(table.o)); bool ok = table_ptr->GetOptionalFieldOffset(field) != 0; // If this fails, the caller will show what field needs to be set. FLATBUFFERS_ASSERT(ok); @@ -521,7 +533,8 @@ template class FlatBufferBuilderImpl { // Aligns such than when "len" bytes are written, an object of type `AlignT` // can be written after it (forward in the buffer) without padding. - template void PreAlign(size_t len) { + template + void PreAlign(size_t len) { AssertScalarT(); PreAlign(len, AlignOf()); } @@ -531,8 +544,8 @@ template class FlatBufferBuilderImpl { /// @param[in] str A const char pointer to the data to be stored as a string. /// @param[in] len The number of bytes that should be stored from `str`. /// @return Returns the offset in the buffer where the string starts. - template class OffsetT = Offset> - OffsetT CreateString(const char *str, size_t len) { + template