diff --git a/.bazelci/presubmit.yml b/.bazelci/presubmit.yml index df480ccd98..7c07ba61e4 100644 --- a/.bazelci/presubmit.yml +++ b/.bazelci/presubmit.yml @@ -1,36 +1,60 @@ --- buildifier: latest -platforms: - ubuntu1804: +matrix: + bazel: + - 7.x + - 8.x +tasks: + verify_ubuntu2004: + platform: ubuntu2004 + bazel: ${{ bazel }} environment: CC: clang - SWIFT_VERSION: "5.5.3" + SWIFT_VERSION: "5.10" SWIFT_HOME: "$HOME/swift-$SWIFT_VERSION" PATH: "$PATH:$SWIFT_HOME/usr/bin" shell_commands: - "echo --- Downloading and extracting Swift $SWIFT_VERSION to $SWIFT_HOME" - "mkdir $SWIFT_HOME" - - "curl https://download.swift.org/swift-${SWIFT_VERSION}-release/ubuntu1804/swift-${SWIFT_VERSION}-RELEASE/swift-${SWIFT_VERSION}-RELEASE-ubuntu18.04.tar.gz | tar xvz --strip-components=1 -C $SWIFT_HOME" + - "curl https://download.swift.org/swift-${SWIFT_VERSION}-release/ubuntu2004/swift-${SWIFT_VERSION}-RELEASE/swift-${SWIFT_VERSION}-RELEASE-ubuntu20.04.tar.gz | tar xvz --strip-components=1 -C $SWIFT_HOME" build_targets: - "//..." test_targets: - "//..." - ubuntu2004: + verify_ubuntu2204: + platform: ubuntu2204 + bazel: ${{ bazel }} environment: CC: clang - SWIFT_VERSION: "5.5.3" + SWIFT_VERSION: "5.10" SWIFT_HOME: "$HOME/swift-$SWIFT_VERSION" PATH: "$PATH:$SWIFT_HOME/usr/bin" shell_commands: - "echo --- Downloading and extracting Swift $SWIFT_VERSION to $SWIFT_HOME" - "mkdir $SWIFT_HOME" - - "curl https://download.swift.org/swift-${SWIFT_VERSION}-release/ubuntu2004/swift-${SWIFT_VERSION}-RELEASE/swift-${SWIFT_VERSION}-RELEASE-ubuntu20.04.tar.gz | tar xvz --strip-components=1 -C $SWIFT_HOME" + - "curl https://download.swift.org/swift-${SWIFT_VERSION}-release/ubuntu2204/swift-${SWIFT_VERSION}-RELEASE/swift-${SWIFT_VERSION}-RELEASE-ubuntu22.04.tar.gz | tar xvz --strip-components=1 -C $SWIFT_HOME" build_targets: - "//..." test_targets: - "//..." - macos: + test_module_cpp: + platform: ubuntu2204 + bazel: ${{ bazel }} + working_directory: tests/bazel_repository_test_dir build_targets: - "//..." + test_module_ts: + platform: ubuntu2204 + bazel: ${{ bazel }} + working_directory: tests/ts/bazel_repository_test_dir test_targets: - "//..." + verify_macos: + platform: macos + bazel: ${{ bazel }} + xcode_version: "15.2" + build_targets: + - "//:flatbuffers" + - "//:flatc" + test_targets: + - "//tests:flatbuffers_test" diff --git a/.bazelignore b/.bazelignore new file mode 100644 index 0000000000..874adf9156 --- /dev/null +++ b/.bazelignore @@ -0,0 +1,5 @@ +ts/node_modules + +# Test workspaces +tests/bazel_repository_test_dir +tests/ts/bazel_repository_test_dir diff --git a/.bazelrc b/.bazelrc new file mode 100644 index 0000000000..a02667e182 --- /dev/null +++ b/.bazelrc @@ -0,0 +1,18 @@ +# We cannot use "common" here because the "version" command doesn't support +# --deleted_packages. We need to specify it for both build and query instead. +build --deleted_packages=tests/bazel_repository_test_dir,tests/ts/bazel_repository_test_dir +query --deleted_packages=tests/bazel_repository_test_dir,tests/ts/bazel_repository_test_dir +# Point tools such as coursier (used in rules_jvm_external) to Bazel's internal JDK +# suggested in https://github.com/bazelbuild/rules_jvm_external/issues/445 +common --repo_env=JAVA_HOME=../bazel_tools/jdk +common --action_env=JAVA_HOME=../bazel_tools/jdk +# Workaround "Error: need --enable_runfiles on Windows for to support rules_js" +common:windows --enable_runfiles +# Swift is not required on Windows +common:windows --deleted_packages=swift +# Ignore warnings in external dependencies +build --per_file_copt=external/.*@-Wno-everything --host_per_file_copt=external/.*@-Wno-everything +# Honor the setting of `skipLibCheck` in the tsconfig.json file. +common --@aspect_rules_ts//ts:skipLibCheck=honor_tsconfig +# Use "tsc" as the transpiler when ts_project has no `transpiler` set. +common --@aspect_rules_ts//ts:default_to_tsc_transpiler diff --git a/.clang-format b/.clang-format index 7da2b4389e..bb2e3440d4 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/.clang-tidy b/.clang-tidy new file mode 100644 index 0000000000..7e9c1b7c7d --- /dev/null +++ b/.clang-tidy @@ -0,0 +1,347 @@ +--- +FormatStyle: "file" +WarningsAsErrors: "*" +HeaderFilterRegex: ".*" +Checks: "google-build-explicit-make-pair, + google-build-namespaces, + google-build-using-namespace, + google-default-arguments, + google-explicit-constructor, + google-global-names-in-headers, + google-objc-avoid-nsobject-new, + google-objc-avoid-throwing-exception, + google-objc-function-naming, + google-objc-global-variable-declaration, + google-readability-avoid-underscore-in-googletest-name, + google-readability-braces-around-statements, + google-readability-casting, + google-readability-function-size, + google-readability-namespace-comments, + google-runtime-int, + google-runtime-operator, + google-upgrade-googletest-case, + clang-analyzer-apiModeling.StdCLibraryFunctions, + clang-analyzer-apiModeling.TrustNonnull, + clang-analyzer-apiModeling.google.GTest, + clang-analyzer-apiModeling.llvm.CastValue, + clang-analyzer-apiModeling.llvm.ReturnValue, + clang-analyzer-core.CallAndMessage, + clang-analyzer-core.CallAndMessageModeling, + clang-analyzer-core.DivideZero, + clang-analyzer-core.DynamicTypePropagation, + clang-analyzer-core.NonNullParamChecker, + clang-analyzer-core.NonnilStringConstants, + clang-analyzer-core.NullDereference, + clang-analyzer-core.StackAddrEscapeBase, + clang-analyzer-core.StackAddressEscape, + clang-analyzer-core.UndefinedBinaryOperatorResult, + clang-analyzer-core.VLASize, + clang-analyzer-core.builtin.BuiltinFunctions, + clang-analyzer-core.builtin.NoReturnFunctions, + clang-analyzer-core.uninitialized.ArraySubscript, + clang-analyzer-core.uninitialized.Assign, + clang-analyzer-core.uninitialized.Branch, + clang-analyzer-core.uninitialized.CapturedBlockVariable, + clang-analyzer-core.uninitialized.UndefReturn, + clang-analyzer-cplusplus.InnerPointer, + clang-analyzer-cplusplus.Move, + clang-analyzer-cplusplus.NewDelete, + clang-analyzer-cplusplus.NewDeleteLeaks, + clang-analyzer-cplusplus.PlacementNew, + clang-analyzer-cplusplus.PureVirtualCall, + clang-analyzer-cplusplus.SelfAssignment, + clang-analyzer-cplusplus.SmartPtrModeling, + clang-analyzer-cplusplus.StringChecker, + clang-analyzer-cplusplus.VirtualCallModeling, + clang-analyzer-deadcode.DeadStores, + clang-analyzer-fuchsia.HandleChecker, + clang-analyzer-nullability.NullPassedToNonnull, + clang-analyzer-nullability.NullReturnedFromNonnull, + clang-analyzer-nullability.NullabilityBase, + clang-analyzer-nullability.NullableDereferenced, + clang-analyzer-nullability.NullablePassedToNonnull, + clang-analyzer-nullability.NullableReturnedFromNonnull, + clang-analyzer-optin.cplusplus.UninitializedObject, + clang-analyzer-optin.cplusplus.VirtualCall, + clang-analyzer-optin.mpi.MPI-Checker, + clang-analyzer-optin.osx.OSObjectCStyleCast, + clang-analyzer-optin.osx.cocoa.localizability.EmptyLocalizationContextChecker, + clang-analyzer-optin.osx.cocoa.localizability.NonLocalizedStringChecker, + clang-analyzer-optin.performance.GCDAntipattern, + clang-analyzer-optin.performance.Padding, + clang-analyzer-optin.portability.UnixAPI, + clang-analyzer-osx.API, + clang-analyzer-osx.MIG, + clang-analyzer-osx.NSOrCFErrorDerefChecker, + clang-analyzer-osx.NumberObjectConversion, + clang-analyzer-osx.OSObjectRetainCount, + clang-analyzer-osx.ObjCProperty, + clang-analyzer-osx.SecKeychainAPI, + clang-analyzer-osx.cocoa.AtSync, + clang-analyzer-osx.cocoa.AutoreleaseWrite, + clang-analyzer-osx.cocoa.ClassRelease, + clang-analyzer-osx.cocoa.Dealloc, + clang-analyzer-osx.cocoa.IncompatibleMethodTypes, + clang-analyzer-osx.cocoa.Loops, + clang-analyzer-osx.cocoa.MissingSuperCall, + clang-analyzer-osx.cocoa.NSAutoreleasePool, + clang-analyzer-osx.cocoa.NSError, + clang-analyzer-osx.cocoa.NilArg, + clang-analyzer-osx.cocoa.NonNilReturnValue, + clang-analyzer-osx.cocoa.ObjCGenerics, + clang-analyzer-osx.cocoa.RetainCount, + clang-analyzer-osx.cocoa.RetainCountBase, + clang-analyzer-osx.cocoa.RunLoopAutoreleaseLeak, + clang-analyzer-osx.cocoa.SelfInit, + clang-analyzer-osx.cocoa.SuperDealloc, + clang-analyzer-osx.cocoa.UnusedIvars, + clang-analyzer-osx.cocoa.VariadicMethodTypes, + clang-analyzer-osx.coreFoundation.CFError, + clang-analyzer-osx.coreFoundation.CFNumber, + clang-analyzer-osx.coreFoundation.CFRetainRelease, + clang-analyzer-osx.coreFoundation.containers.OutOfBounds, + clang-analyzer-osx.coreFoundation.containers.PointerSizedValues, + clang-analyzer-security.FloatLoopCounter, + clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling, + clang-analyzer-security.insecureAPI.SecuritySyntaxChecker, + clang-analyzer-security.insecureAPI.UncheckedReturn, + clang-analyzer-security.insecureAPI.bcmp, + clang-analyzer-security.insecureAPI.bcopy, + clang-analyzer-security.insecureAPI.bzero, + clang-analyzer-security.insecureAPI.decodeValueOfObjCType, + clang-analyzer-security.insecureAPI.getpw, + clang-analyzer-security.insecureAPI.gets, + clang-analyzer-security.insecureAPI.mkstemp, + clang-analyzer-security.insecureAPI.mktemp, + clang-analyzer-security.insecureAPI.rand, + clang-analyzer-security.insecureAPI.strcpy, + clang-analyzer-security.insecureAPI.vfork, + clang-analyzer-unix.API, + clang-analyzer-unix.DynamicMemoryModeling, + clang-analyzer-unix.Malloc, + clang-analyzer-unix.MallocSizeof, + clang-analyzer-unix.MismatchedDeallocator, + clang-analyzer-unix.Vfork, + clang-analyzer-unix.cstring.BadSizeArg, + clang-analyzer-unix.cstring.CStringModeling, + clang-analyzer-unix.cstring.NullArg, + clang-analyzer-valist.CopyToSelf, + clang-analyzer-valist.Uninitialized, + clang-analyzer-valist.Unterminated, + clang-analyzer-valist.ValistBase, + clang-analyzer-webkit.NoUncountedMemberChecker, + clang-analyzer-webkit.RefCntblBaseVirtualDtor, + clang-analyzer-webkit.UncountedLambdaCapturesChecker, + +################################################ Optional checks ################################################ + + #google-readability-todo, + #bugprone-argument-comment, + #bugprone-assert-side-effect, + #bugprone-bad-signal-to-kill-thread, + #bugprone-bool-pointer-implicit-conversion, + #bugprone-branch-clone, + #bugprone-copy-constructor-init, + #bugprone-dangling-handle, + #bugprone-dynamic-static-initializers, + #bugprone-easily-swappable-parameters, + #bugprone-exception-escape, + #bugprone-fold-init-type, + #bugprone-forward-declaration-namespace, + #bugprone-forwarding-reference-overload, + #bugprone-implicit-widening-of-multiplication-result, + #bugprone-inaccurate-erase, + #bugprone-incorrect-roundings, + #bugprone-infinite-loop, + #bugprone-integer-division, + #bugprone-lambda-function-name, + #bugprone-macro-parentheses, + #bugprone-macro-repeated-side-effects, + #bugprone-misplaced-operator-in-strlen-in-alloc, + #bugprone-misplaced-pointer-arithmetic-in-alloc, + #bugprone-misplaced-widening-cast, + #bugprone-move-forwarding-reference, + #bugprone-multiple-statement-macro, + #bugprone-narrowing-conversions, + #bugprone-no-escape, + #bugprone-not-null-terminated-result, + #bugprone-parent-virtual-call, + #bugprone-posix-return, + #bugprone-redundant-branch-condition, + #bugprone-reserved-identifier, + #bugprone-signal-handler, + #bugprone-signed-char-misuse, + #bugprone-sizeof-container, + #bugprone-sizeof-expression, + #bugprone-spuriously-wake-up-functions, + #bugprone-string-constructor, + #bugprone-string-integer-assignment, + #bugprone-string-literal-with-embedded-nul, + #bugprone-stringview-nullptr, + #bugprone-suspicious-enum-usage, + #bugprone-suspicious-include, + #bugprone-suspicious-memory-comparison, + #bugprone-suspicious-memset-usage, + #bugprone-suspicious-missing-comma, + #bugprone-suspicious-semicolon, + #bugprone-suspicious-string-compare, + #bugprone-swapped-arguments, + #bugprone-terminating-continue, + #bugprone-throw-keyword-missing, + #bugprone-too-small-loop-variable, + #bugprone-undefined-memory-manipulation, + #bugprone-undelegated-constructor, + #bugprone-unhandled-exception-at-new, + #bugprone-unhandled-self-assignment, + #bugprone-unused-raii, + #bugprone-unused-return-value, + #bugprone-use-after-move, + #bugprone-virtual-near-miss, + #cppcoreguidelines-avoid-c-arrays, + #cppcoreguidelines-avoid-goto, + #cppcoreguidelines-avoid-magic-numbers, + #cppcoreguidelines-avoid-non-const-global-variables, + #cppcoreguidelines-c-copy-assignment-signature, + #cppcoreguidelines-explicit-virtual-functions, + #cppcoreguidelines-init-variables, + #cppcoreguidelines-interfaces-global-init, + #cppcoreguidelines-macro-usage, + #cppcoreguidelines-narrowing-conversions, + #cppcoreguidelines-no-malloc, + #cppcoreguidelines-non-private-member-variables-in-classes, + #cppcoreguidelines-owning-memory, + #cppcoreguidelines-prefer-member-initializer, + #cppcoreguidelines-pro-bounds-array-to-pointer-decay, + #cppcoreguidelines-pro-bounds-constant-array-index, + #cppcoreguidelines-pro-bounds-pointer-arithmetic, + #cppcoreguidelines-pro-type-const-cast, + #cppcoreguidelines-pro-type-cstyle-cast, + #cppcoreguidelines-pro-type-member-init, + #cppcoreguidelines-pro-type-reinterpret-cast, + #cppcoreguidelines-pro-type-static-cast-downcast, + #cppcoreguidelines-pro-type-union-access, + #cppcoreguidelines-pro-type-vararg, + #cppcoreguidelines-slicing, + #cppcoreguidelines-special-member-functions, + #cppcoreguidelines-virtual-class-destructor, + #hicpp-avoid-c-arrays, + #hicpp-avoid-goto, + #hicpp-braces-around-statements, + #hicpp-deprecated-headers, + #hicpp-exception-baseclass, + #hicpp-explicit-conversions, + #hicpp-function-size, + #hicpp-invalid-access-moved, + #hicpp-member-init, + #hicpp-move-const-arg, + #hicpp-multiway-paths-covered, + #hicpp-named-parameter, + #hicpp-new-delete-operators, + #hicpp-no-array-decay, + #hicpp-no-assembler, + #hicpp-no-malloc, + #hicpp-noexcept-move, + #hicpp-signed-bitwise, + #hicpp-special-member-functions, + #hicpp-static-assert, + #hicpp-undelegated-constructor, + #hicpp-uppercase-literal-suffix, + #hicpp-use-auto, + #hicpp-use-emplace, + #hicpp-use-equals-default, + #hicpp-use-equals-delete, + #hicpp-use-noexcept, + #hicpp-use-nullptr, + #hicpp-use-override, + #hicpp-vararg, + #modernize-avoid-bind, + #modernize-avoid-c-arrays, + #modernize-concat-nested-namespaces, + #modernize-deprecated-headers, + #modernize-deprecated-ios-base-aliases, + #modernize-loop-convert, + #modernize-make-shared, + #modernize-make-unique, + #modernize-pass-by-value, + #modernize-raw-string-literal, + #modernize-redundant-void-arg, + #modernize-replace-auto-ptr, + #modernize-replace-disallow-copy-and-assign-macro, + #modernize-replace-random-shuffle, + #modernize-return-braced-init-list, + #modernize-shrink-to-fit, + #modernize-unary-static-assert, + #modernize-use-auto, + #modernize-use-bool-literals, + #modernize-use-default-member-init, + #modernize-use-emplace, + #modernize-use-equals-default, + #modernize-use-equals-delete, + #modernize-use-nodiscard, + #modernize-use-noexcept, + #modernize-use-nullptr, + #modernize-use-override, + #modernize-use-trailing-return-type, + #modernize-use-transparent-functors, + #modernize-use-uncaught-exceptions, + #modernize-use-using, + #performance-faster-string-find, + #performance-for-range-copy, + #performance-implicit-conversion-in-loop, + #performance-inefficient-algorithm, + #performance-inefficient-string-concatenation, + #performance-inefficient-vector-operation, + #performance-move-const-arg, + #performance-move-constructor-init, + #performance-no-automatic-move, + #performance-no-int-to-ptr, + #performance-noexcept-move-constructor, + #performance-trivially-destructible, + #performance-type-promotion-in-math-fn, + #performance-unnecessary-copy-initialization, + #performance-unnecessary-value-param, + #portability-restrict-system-includes, + #portability-simd-intrinsics, + #readability-avoid-const-params-in-decls, + #readability-braces-around-statements, + #readability-const-return-type, + #readability-container-contains, + #readability-container-data-pointer, + #readability-container-size-empty, + #readability-convert-member-functions-to-static, + #readability-delete-null-pointer, + #readability-duplicate-include, + #readability-else-after-return, + #readability-function-cognitive-complexity, + #readability-function-size, + #readability-identifier-length, + #readability-identifier-naming, + #readability-implicit-bool-conversion, + #readability-inconsistent-declaration-parameter-name, + #readability-isolate-declaration, + #readability-magic-numbers, + #readability-make-member-function-const, + #readability-misleading-indentation, + #readability-misplaced-array-index, + #readability-named-parameter, + #readability-non-const-parameter, + #readability-qualified-auto, + #readability-redundant-access-specifiers, + #readability-redundant-control-flow, + #readability-redundant-declaration, + #readability-redundant-function-ptr-dereference, + #readability-redundant-member-init, + #readability-redundant-preprocessor, + #readability-redundant-smartptr-get, + #readability-redundant-string-cstr, + #readability-redundant-string-init, + #readability-simplify-boolean-expr, + #readability-simplify-subscript-expr, + #readability-static-accessed-through-instance, + #readability-static-definition-in-anonymous-namespace, + #readability-string-compare, + #readability-suspicious-call-argument, + #readability-uniqueptr-delete-release, + #readability-uppercase-literal-suffix, + #readability-use-anyofallof + " diff --git a/.editorconfig b/.editorconfig index 6c549666eb..6689bab231 100644 --- a/.editorconfig +++ b/.editorconfig @@ -5,3 +5,4 @@ root = true indent_style = space indent_size = 2 insert_final_newline = true +trim_trailing_whitespace = true diff --git a/.eslintrc.js b/.eslintrc.js deleted file mode 100644 index 321169b07c..0000000000 --- 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/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000000..bc0b315d22 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1,5 @@ +# Default owner +* @aardappel @dbaileychess derekbailey@google.com + +# Prevent modification of this file +.github/CODEOWNERS @dbaileychess derekbailey@google.com diff --git a/.github/ISSUE_TEMPLATE/404-doc.md b/.github/ISSUE_TEMPLATE/404-doc.md new file mode 100644 index 0000000000..c394d38454 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/404-doc.md @@ -0,0 +1,11 @@ +--- +name: 404 Doc +about: To fix broken documentation links +title: "[Doc 404]" +labels: documentation +assignees: dbaileychess + +--- + +Target URL: +[Optional] Source Site: diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 0f05239861..b8cc0ce1db 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -3,7 +3,7 @@ Thank you for submitting a PR! Please delete this standard text once you've created your own description. If you make changes to any of the code generators (`src/idl_gen*`) be sure to -build your project, as it will generate code based on the changes. If necessary +[build](https://google.github.io/flatbuffers/flatbuffers_guide_building.html) your project, as it will generate code based on the changes. If necessary the code generation script can be directly run (`scripts/generate_code.py`), requires Python3. This allows us to better see the effect of the PR. diff --git a/.github/labeler.yml b/.github/labeler.yml index dcab0447e8..ccc975746c 100644 --- a/.github/labeler.yml +++ b/.github/labeler.yml @@ -5,93 +5,133 @@ # # See .github/workflows/label.yml for Github Action workflow script -c#: - - '**/*.cs' - - net/**/* - - tests/FlatBuffers.Test/**/* - - tests/FlatBuffers.Benchmarks/**/* - - src/idl_gen_csharp.cpp +"c#": + - changed-files: + - any-glob-to-any-file: + - '**/*.cs' + - 'net/**/*' + - 'tests/FlatBuffers.Test/**/*' + - 'tests/FlatBuffers.Benchmarks/**/*' + - 'src/idl_gen_csharp.cpp' swift: - - '**/*.swift' - - swift/**/* - - tests/swift/** - - src/idl_gen_swift.cpp + - changed-files: + - any-glob-to-any-file: + - '**/*.swift' + - 'swift/**/*' + - 'tests/swift/**' + - 'src/idl_gen_swift.cpp' nim: - - '**/*.nim' - - nim/**/* - - src/idl_gen_nim.cpp - - src/bfbs_gen_nim.cpp + - changed-files: + - any-glob-to-any-file: + - '**/*.nim' + - 'nim/**/*' + - 'src/idl_gen_nim.cpp' + - 'src/bfbs_gen_nim.cpp' javascript: - - '**/*.js' - - src/idl_gen_ts.cpp + - changed-files: + - any-glob-to-any-file: + - '**/*.js' + - 'src/idl_gen_ts.cpp' typescript: - - '**/*.ts' - - src/idl_gen_ts.cpp - - grpc/flatbuffers-js-grpc/**/*.ts + - changed-files: + - any-glob-to-any-file: + - '**/*.ts' + - 'src/idl_gen_ts.cpp' + - 'grpc/flatbuffers-js-grpc/**/*.ts' golang: - - '**/*.go' - - src/idl_gen_go.cpp + - changed-files: + - any-glob-to-any-file: + - '**/*.go' + - 'src/idl_gen_go.cpp' python: - - '**/*.py' - - src/idl_gen_python.cpp + - changed-files: + - any-glob-to-any-file: + - '**/*.py' + - 'src/idl_gen_python.cpp' java: - - '**/*.java' - - src/idl_gen_java.cpp + - changed-files: + - any-glob-to-any-file: + - '**/*.java' + - 'src/idl_gen_java.cpp' kotlin: - - '**/*.kt' - - src/idl_gen_kotlin.cpp + - changed-files: + - any-glob-to-any-file: + - '**/*.kt' + - 'src/idl_gen_kotlin.cpp' + - 'src/idl_gen_kotlin_kmp.cpp' lua: - - '**/*.lua' - - lua/**/* - - src/idl_gen_lua.cpp - - src/bfbs_gen_lua.cpp + - changed-files: + - any-glob-to-any-file: + - '**/*.lua' + - 'lua/**/*' + - 'src/bfbs_gen_lua.cpp' lobster: - - '**/*.lobster' - - src/idl_gen_lobster.cpp + - changed-files: + - any-glob-to-any-file: + - '**/*.lobster' + - 'src/idl_gen_lobster.cpp' php: - - '**/*.php' - - src/idl_gen_php.cpp + - changed-files: + - any-glob-to-any-file: + - '**/*.php' + - 'src/idl_gen_php.cpp' rust: - - '**/*.rs' - - rust/**/* - - src/idl_gen_rust.cpp + - changed-files: + - any-glob-to-any-file: + - '**/*.rs' + - 'rust/**/*' + - 'src/idl_gen_rust.cpp' dart: - - '**/*.dart' - - src/idl_gen_dart.cpp - -c++: - - '**/*.cc' - - '**/*.cpp' - - '**/*.h' + - changed-files: + - any-glob-to-any-file: + - '**/*.dart' + - 'src/idl_gen_dart.cpp' + +"c++": + - changed-files: + - any-glob-to-any-file: + - '**/*.cc' + - '**/*.cpp' + - '**/*.h' json: - - '**/*.json' - - src/idl_gen_json_schema.cpp + - changed-files: + - any-glob-to-any-file: + - '**/*.json' + - 'src/idl_gen_json_schema.cpp' codegen: - - src/**/* + - changed-files: + - any-glob-to-any-file: + - 'src/**/*' documentation: - - docs/**/* - - '**/*.md' + - changed-files: + - any-glob-to-any-file: + - 'docs/**/*' + - '**/*.md' CI: - - '.github/**/*' - - '.bazelci/**/*' + - changed-files: + - any-glob-to-any-file: + - '.github/**/*' + - '.bazelci/**/*' grpc: - - grpc/**/* - - src/idl_gen_grpc.cpp + - changed-files: + - any-glob-to-any-file: + - 'grpc/**/*' + - 'src/idl_gen_grpc.cpp' diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 925c3a46d2..8cac69ee7d 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -12,6 +12,9 @@ on: pull_request: branches: - master + schedule: + # Run daily at 4:45 A.M. to catch dependencies that break us. + - cron: '45 4 * * *' jobs: build-linux: @@ -21,15 +24,15 @@ jobs: digests-gcc: ${{ steps.hash-gcc.outputs.hashes }} digests-clang: ${{ steps.hash-clang.outputs.hashes }} name: Build Linux - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 strategy: matrix: - cxx: [g++-10, clang++-12] + cxx: [g++-13, clang++-18] fail-fast: false steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v6 - name: cmake - run: CXX=${{ matrix.cxx }} cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_STRICT_MODE=ON . + run: CXX=${{ matrix.cxx }} cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_STRICT_MODE=ON -DFLATBUFFERS_STATIC_FLATC=ON . - name: build run: make -j - name: test @@ -38,10 +41,8 @@ jobs: run: | chmod +x flatc ./flatc --version - - name: flatc tests - run: python3 tests/flatc/main.py - name: upload build artifacts - uses: actions/upload-artifact@v1 + uses: actions/upload-artifact@v4 with: name: Linux flatc binary ${{ matrix.cxx }} path: flatc @@ -50,37 +51,72 @@ jobs: if: startsWith(github.ref, 'refs/tags/') run: zip Linux.flatc.binary.${{ matrix.cxx }}.zip flatc - name: Release zip file - uses: softprops/action-gh-release@v1 + uses: softprops/action-gh-release@v2 if: startsWith(github.ref, 'refs/tags/') with: files: Linux.flatc.binary.${{ matrix.cxx }}.zip - name: Generate SLSA subjects - clang - if: matrix.cxx == 'clang++-12' && startsWith(github.ref, 'refs/tags/') + if: matrix.cxx == 'clang++-18' && startsWith(github.ref, 'refs/tags/') id: hash-clang - run: echo "::set-output name=hashes::$(sha256sum Linux.flatc.binary.${{ matrix.cxx }}.zip | base64 -w0)" + run: echo "hashes=$(sha256sum Linux.flatc.binary.${{ matrix.cxx }}.zip | base64 -w0)" >> $GITHUB_OUTPUT - name: Generate SLSA subjects - gcc - if: matrix.cxx == 'g++-10' && startsWith(github.ref, 'refs/tags/') + if: matrix.cxx == 'g++-13' && startsWith(github.ref, 'refs/tags/') id: hash-gcc - run: echo "::set-output name=hashes::$(sha256sum Linux.flatc.binary.${{ matrix.cxx }}.zip | base64 -w0)" + run: echo "hashes=$(sha256sum Linux.flatc.binary.${{ matrix.cxx }}.zip | base64 -w0)" >> $GITHUB_OUTPUT + + build-linux-no-file-tests: + name: Build Linux with -DFLATBUFFERS_NO_FILE_TESTS + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v6 + - name: cmake + run: CXX=clang++-18 cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_STRICT_MODE=ON -DFLATBUFFERS_CXX_FLAGS="-DFLATBUFFERS_NO_FILE_TESTS" . + - name: build + run: make -j + - name: test + run: ./flattests + + build-linux-out-of-source: + name: Build Linux with out-of-source build location + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v6 + - name: make build directory + run: mkdir build + - name: cmake + working-directory: build + run: > + CXX=clang++-18 cmake .. -G "Unix Makefiles" -DFLATBUFFERS_STRICT_MODE=ON + -DFLATBUFFERS_BUILD_CPP17=ON -DFLATBUFFERS_CPP_STD=17 + - name: build + working-directory: build + run: make -j + - name: test + working-directory: build + run: pwd && ./flattests + - name: test C++17 + working-directory: build + run: ./flattests_cpp17 build-linux-cpp-std: name: Build Linux C++ - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 strategy: fail-fast: false matrix: std: [11, 14, 17, 20, 23] - cxx: [g++-10, clang++-12] + cxx: [g++-13, clang++-18] exclude: - # GCC 10.3.0 doesn't support std 23 - - cxx: g++-10 + # Clang++15 10.3.0 stdlibc++ doesn't fully support std 23 + - cxx: clang++-18 std: 23 + steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v6 - name: cmake run: > - CXX=${{ matrix.cxx }} cmake -G "Unix Makefiles" - -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_STRICT_MODE=ON + CXX=${{ matrix.cxx }} cmake -G "Unix Makefiles" + -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_STRICT_MODE=ON -DFLATBUFFERS_CPP_STD=${{ matrix.std }} -DFLATBUFFERS_BUILD_CPP17=${{ matrix.std >= 17 && 'On' || 'Off'}} - name: build @@ -91,21 +127,21 @@ jobs: if: matrix.std >= 17 run: ./flattests_cpp17 - build-windows-cpp-std: + build-cpp-std: name: Build Windows C++ - runs-on: windows-2019 + runs-on: windows-2022 strategy: matrix: std: [11, 14, 17, 20, 23] fail-fast: false steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v6 - name: Add msbuild to PATH - uses: microsoft/setup-msbuild@v1.1 + uses: microsoft/setup-msbuild@v2 - name: cmake run: > - cmake -G "Visual Studio 16 2019" -A x64 -DCMAKE_BUILD_TYPE=Release - -DFLATBUFFERS_STRICT_MODE=ON + 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'}} - name: build @@ -121,22 +157,20 @@ 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@v2 + - uses: actions/checkout@v6 - name: Add msbuild to PATH - uses: microsoft/setup-msbuild@v1.1 + uses: microsoft/setup-msbuild@v2 - 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 run: Release\flattests.exe - - name: flatc tests - run: python3 tests/flatc/main.py --flatc Release\flatc.exe - name: upload build artifacts - uses: actions/upload-artifact@v1 + uses: actions/upload-artifact@v4 with: name: Windows flatc binary path: Release\flatc.exe @@ -145,7 +179,7 @@ jobs: if: startsWith(github.ref, 'refs/tags/') run: move Release/flatc.exe . && Compress-Archive flatc.exe Windows.flatc.binary.zip - name: Release binary - uses: softprops/action-gh-release@v1 + uses: softprops/action-gh-release@v2 if: startsWith(github.ref, 'refs/tags/') with: files: Windows.flatc.binary.zip @@ -153,63 +187,40 @@ jobs: if: startsWith(github.ref, 'refs/tags/') id: hash shell: bash - run: echo "::set-output name=hashes::$(sha256sum Windows.flatc.binary.zip | base64 -w0)" - - build-windows-2017: - name: Build Windows 2017 - runs-on: windows-2019 - steps: - - uses: actions/checkout@v2 - - name: Add msbuild to PATH - uses: microsoft/setup-msbuild@v1.1 - - name: cmake - run: cmake -G "Visual Studio 16 2019" -A x64 -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_STRICT_MODE=ON . - - name: build tool version 15 (VS 2017) - run: msbuild.exe FlatBuffers.sln /p:Configuration=Release /p:Platform=x64 /p:VisualStudioVersion=15.0 - - name: test - run: Release\flattests.exe - - build-windows-2015: - name: Build Windows 2015 - runs-on: windows-2019 - steps: - - uses: actions/checkout@v2 - - name: Add msbuild to PATH - uses: microsoft/setup-msbuild@v1.1 - - name: cmake - run: cmake -G "Visual Studio 14 2015" -A x64 -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_STRICT_MODE=ON . - - name: build tool version 14 (VS 2015) - run: msbuild.exe FlatBuffers.sln /p:Configuration=Release /p:Platform=x64 /p:VisualStudioVersion=14.0 - - name: test - run: Release\flattests.exe + run: echo "hashes=$(sha256sum Windows.flatc.binary.zip | base64 -w0)" >> $GITHUB_OUTPUT build-dotnet-windows: name: Build .NET Windows - runs-on: windows-2019 + runs-on: windows-2022-64core strategy: matrix: configuration: [ '', - '-p:UnsafeByteBuffer=true', + '-p:UnsafeByteBuffer=true', # Fails two tests currently. #'-p:EnableSpanT=true,UnsafeByteBuffer=true' ] steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v6 - name: Setup .NET Core SDK - uses: actions/setup-dotnet@v1.9.0 - with: - dotnet-version: '3.1.x' + uses: actions/setup-dotnet@v5 + with: + dotnet-version: '8.0.x' - name: Build run: | cd tests\FlatBuffers.Test - dotnet new sln --force --name FlatBuffers.Core.Test - dotnet sln FlatBuffers.Core.Test.sln add FlatBuffers.Core.Test.csproj - dotnet build -c Release ${{matrix.configuration}} -o out FlatBuffers.Core.Test.sln - - name: Run + dotnet new sln --force --name FlatBuffers.Test + dotnet sln FlatBuffers.Test.sln add FlatBuffers.Test.csproj + dotnet build -c Release ${{matrix.configuration}} FlatBuffers.Test.sln + - name: Run net6.0 run: | - cd tests\FlatBuffers.Test - out\FlatBuffers.Core.Test.exe + cd tests\FlatBuffers.Test\bin\Release\net6.0 + dir + .\FlatBuffers.Test.exe + - name: Run net8.0 + run: | + cd tests\FlatBuffers.Test\bin\Release\net8.0 + .\FlatBuffers.Test.exe build-mac-intel: permissions: @@ -217,45 +228,42 @@ jobs: outputs: digests: ${{ steps.hash.outputs.hashes }} name: Build Mac (for Intel) - runs-on: macos-latest + runs-on: macos-15-intel steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v6 - name: cmake - run: cmake -G "Xcode" -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_FLATC_EXECUTABLE=_build/Release/flatc -DFLATBUFFERS_STRICT_MODE=ON . + run: cmake -G "Xcode" -DCMAKE_OSX_ARCHITECTURES="x86_64" -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_STRICT_MODE=ON . - name: build - # NOTE: we need this _build dir to not have xcodebuild's default ./build dir clash with the BUILD file. - run: xcodebuild -toolchain clang -configuration Release -target flattests SYMROOT=$(PWD)/_build + run: xcodebuild -toolchain clang -configuration Release -target flattests - name: check that the binary is x86_64 run: | - info=$(file _build/Release/flatc) + info=$(file Release/flatc) echo $info echo $info | grep "Mach-O 64-bit executable x86_64" - name: test - run: _build/Release/flattests + run: Release/flattests - name: make flatc executable run: | - chmod +x _build/Release/flatc - ./_build/Release/flatc --version - - name: flatc tests - run: python3 tests/flatc/main.py --flatc ./_build/Release/flatc + chmod +x Release/flatc + Release/flatc --version - name: upload build artifacts - uses: actions/upload-artifact@v1 + uses: actions/upload-artifact@v4 with: - name: Mac flatc binary - path: _build/Release/flatc + name: Mac flatc binary Intel + path: Release/flatc # Below if only for release. - name: Zip file if: startsWith(github.ref, 'refs/tags/') - run: mv _build/Release/flatc . && zip MacIntel.flatc.binary.zip flatc + run: mv Release/flatc . && zip MacIntel.flatc.binary.zip flatc - name: Release binary - uses: softprops/action-gh-release@v1 + uses: softprops/action-gh-release@v2 if: startsWith(github.ref, 'refs/tags/') with: files: MacIntel.flatc.binary.zip - name: Generate SLSA subjects if: startsWith(github.ref, 'refs/tags/') id: hash - run: echo "::set-output name=hashes::$(shasum -a 256 MacIntel.flatc.binary.zip | base64)" + run: echo "hashes=$(shasum -a 256 MacIntel.flatc.binary.zip | base64)" >> $GITHUB_OUTPUT build-mac-universal: permissions: @@ -265,51 +273,54 @@ jobs: name: Build Mac (universal build) runs-on: macos-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v6 - name: cmake - run: cmake -G "Xcode" -DCMAKE_OSX_ARCHITECTURES="arm64;x86_64" -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_FLATC_EXECUTABLE=_build/Release/flatc -DFLATBUFFERS_STRICT_MODE=ON . + run: cmake -G "Xcode" -DCMAKE_OSX_ARCHITECTURES="arm64;x86_64" -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_STRICT_MODE=ON . - name: build - # NOTE: we need this _build dir to not have xcodebuild's default ./build dir clash with the BUILD file. - run: xcodebuild -toolchain clang -configuration Release -target flattests SYMROOT=$(PWD)/_build + run: xcodebuild -toolchain clang -configuration Release -target flattests - name: check that the binary is "universal" run: | - info=$(file _build/Release/flatc) + info=$(file Release/flatc) echo $info echo $info | grep "Mach-O universal binary with 2 architectures" - name: test - run: _build/Release/flattests + run: Release/flattests - name: make flatc executable run: | - chmod +x _build/Release/flatc - ./_build/Release/flatc --version + chmod +x Release/flatc + Release/flatc --version - name: upload build artifacts - uses: actions/upload-artifact@v1 + uses: actions/upload-artifact@v4 with: - name: Mac flatc binary - path: _build/Release/flatc + name: Mac flatc binary Universal + path: Release/flatc # Below if only for release. - name: Zip file if: startsWith(github.ref, 'refs/tags/') - run: mv _build/Release/flatc . && zip Mac.flatc.binary.zip flatc + run: mv Release/flatc . && zip Mac.flatc.binary.zip flatc - name: Release binary - uses: softprops/action-gh-release@v1 + uses: softprops/action-gh-release@v2 if: startsWith(github.ref, 'refs/tags/') with: files: Mac.flatc.binary.zip - name: Generate SLSA subjects if: startsWith(github.ref, 'refs/tags/') id: hash - run: echo "::set-output name=hashes::$(shasum -a 256 Mac.flatc.binary.zip | base64)" + run: echo "hashes=$(shasum -a 256 Mac.flatc.binary.zip | base64)" >> $GITHUB_OUTPUT build-android: name: Build Android (on Linux) - runs-on: ubuntu-latest + if: false #disabled due to continual failure + runs-on: ubuntu-24.04 steps: - - uses: actions/checkout@v2 - - name: set up JDK 1.8 - uses: actions/setup-java@v1 + - uses: actions/checkout@v6 + - name: set up Java + uses: actions/setup-java@v4 with: - java-version: 1.8 + distribution: temurin + java-version: 17 + - name: set up Gradle + uses: gradle/actions/setup-gradle@v5 - name: set up flatc run: | cmake -DFLATBUFFERS_BUILD_TESTS=OFF -DFLATBUFFERS_BUILD_FLATLIB=OFF -DFLATBUFFERS_BUILD_FLATHASH=OFF -DFLATBUFFERS_STRICT_MODE=ON . @@ -321,12 +332,12 @@ jobs: build-generator: name: Check Generated Code - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 strategy: matrix: - cxx: [g++-10, clang++-12] + cxx: [g++-13, clang++-18] steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v6 - name: cmake run: CXX=${{ matrix.cxx }} cmake -G "Unix Makefiles" -DFLATBUFFERS_BUILD_TESTS=OFF -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_STRICT_MODE=ON . && make -j - name: Generate @@ -334,59 +345,90 @@ jobs: - name: Generate gRPC run: scripts/check-grpc-generated-code.py + build-generator-windows: + name: Check Generated Code on Windows + runs-on: windows-2022 + steps: + - uses: actions/checkout@v6 + - name: Add msbuild to PATH + uses: microsoft/setup-msbuild@v2 + - name: cmake + 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 + run: python3 scripts/check_generate_code.py --flatc Release\flatc.exe + - name: Generate gRPC + run: python3 scripts/check-grpc-generated-code.py --flatc Release\flatc.exe + build-benchmarks: name: Build Benchmarks (on Linux) - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 strategy: matrix: - cxx: [g++-10] + cxx: [g++-13] steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v6 - name: cmake run: CXX=${{ matrix.cxx }} cmake -G "Unix Makefiles" -DFLATBUFFERS_CXX_FLAGS="-Wno-unused-parameter -fno-aligned-new" -DFLATBUFFERS_BUILD_BENCHMARKS=ON -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_STRICT_MODE=ON . && make -j - name: Run benchmarks run: ./flatbenchmark --benchmark_repetitions=5 --benchmark_display_aggregates_only=true --benchmark_out_format=console --benchmark_out=benchmarks/results_${{matrix.cxx}} - name: Upload benchmarks results - uses: actions/upload-artifact@v1 + uses: actions/upload-artifact@v4 with: name: Linux flatbenchmark results ${{matrix.cxx}} path: benchmarks/results_${{matrix.cxx}} build-java: name: Build Java - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v6 - name: test working-directory: java run: mvn test build-kotlin-macos: name: Build Kotlin MacOS - runs-on: macos-latest + runs-on: macos-15 steps: - name: Checkout - uses: actions/checkout@v2 - - uses: gradle/wrapper-validation-action@v1.0.5 - - uses: actions/setup-java@v2 + uses: actions/checkout@v6 + - name: set up Java + uses: actions/setup-java@v4 with: - distribution: 'adopt-hotspot' - java-version: '11' + distribution: temurin + java-version: 17 + - name: set up Gradle + uses: gradle/actions/setup-gradle@v5 + - name: Build flatc + run: | + cmake -DFLATBUFFERS_BUILD_TESTS=OFF -DFLATBUFFERS_BUILD_FLATLIB=OFF -DFLATBUFFERS_BUILD_FLATHASH=OFF . + make -j + echo "${PWD}" >> $GITHUB_PATH - name: Build working-directory: kotlin - run: ./gradlew clean iosX64Test macosX64Test + run: ./gradlew clean iosSimulatorArm64Test macosX64Test macosArm64Test build-kotlin-linux: name: Build Kotlin Linux - runs-on: ubuntu-latest + if: false #disabled due to continual failure + runs-on: ubuntu-24.04 steps: - name: Checkout - uses: actions/checkout@v2 - - uses: actions/setup-java@v2 + uses: actions/checkout@v6 + - name: set up Java + uses: actions/setup-java@v4 with: - distribution: 'adopt-hotspot' - 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@v5 + - name: Build flatc + run: | + cmake -DFLATBUFFERS_BUILD_TESTS=OFF -DFLATBUFFERS_BUILD_FLATLIB=OFF -DFLATBUFFERS_BUILD_FLATHASH=OFF . + make -j + echo "${PWD}" >> $GITHUB_PATH - name: Build working-directory: kotlin # we are using docker's version of gradle @@ -394,29 +436,41 @@ jobs: # gradlew run: gradle jvmMainClasses jvmTest jsTest jsBrowserTest - build-rust: - name: Build Rust - runs-on: ubuntu-latest + build-rust-linux: + name: Build Rust Linux + runs-on: ubuntu-24.04 steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v6 - name: test working-directory: tests run: bash RustTest.sh + build-rust-windows: + name: Build Rust Windows + runs-on: windows-2022-64core + steps: + - uses: actions/checkout@v6 + - name: test + working-directory: tests + run: ./RustTest.bat + build-python: name: Build Python - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v6 + - 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 -DFLATBUFFERS_STRICT_MODE=ON . && make -j - name: test working-directory: tests run: bash PythonTest.sh build-go: name: Build Go - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v6 - 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 -DFLATBUFFERS_STRICT_MODE=ON . && make -j @@ -424,49 +478,89 @@ jobs: working-directory: tests run: bash GoTest.sh + build-php: + name: Build PHP + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v6 + - 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 -DFLATBUFFERS_STRICT_MODE=ON . && make -j + - name: test + working-directory: tests + run: | + php phpTest.php + sh phpUnionVectorTest.sh + build-swift: - name: Build Swift - runs-on: ubuntu-latest + name: Test Swift Linux + strategy: + matrix: + swift: ["5.10", "6.1", "6.2"] + runs-on: ubuntu-24.04 steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v6 + - uses: swift-actions/setup-swift@v2 + with: + swift-version: ${{ matrix.swift }} + - name: Get swift version + run: swift --version - name: test - working-directory: tests/swift/tests - run: sh SwiftTest.sh + run: swift test + + build-swift-windows: + name: Test swift windows + runs-on: windows-latest + steps: + - uses: actions/checkout@v6 + - uses: SwiftyLab/setup-swift@latest + with: + swift-version: '6.1' + - run: swift build + - run: swift test build-swift-wasm: - name: Build Swift Wasm - runs-on: ubuntu-latest - container: - image: ghcr.io/swiftwasm/carton:0.15.3 + name: Test Swift Wasm + runs-on: ubuntu-24.04 steps: - - uses: actions/checkout@v2 - - name: Setup Wasmer - uses: wasmerio/setup-wasmer@v1 - - name: Test - working-directory: tests/swift/Wasm.tests - run: carton test + - uses: actions/checkout@v6 + - uses: swift-actions/setup-swift@v2 + with: + swift-version: 6.2.1 + - uses: bytecodealliance/actions/wasmtime/setup@v1 + - name: Install Swift SDK + run: swift sdk install https://download.swift.org/swift-6.2.1-release/wasm-sdk/swift-6.2.1-RELEASE/swift-6.2.1-RELEASE_wasm.artifactbundle.tar.gz --checksum 482b9f95462b87bedfafca94a092cf9ec4496671ca13b43745097122d20f18af + - name: Test + working-directory: tests/swift/Wasm.tests + run: | + swift sdk list + swift build --build-tests --swift-sdk swift-6.2.1-RELEASE_wasm + wasmtime --dir . .build/wasm32-unknown-wasip1/debug/FlatBuffers.Test.Swift.WasmPackageTests.xctest build-ts: name: Build TS - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v6 - 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: python3 TypeScriptTest.py + run: | + python3 TypeScriptTest.py build-dart: name: Build Dart - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v6 - uses: dart-lang/setup-dart@v1 with: sdk: stable @@ -479,26 +573,41 @@ jobs: build-nim: name: Build Nim - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v6 - 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 - - uses: jiro4989/setup-nim-action@v1 + - uses: jiro4989/setup-nim-action@v2 - name: install library working-directory: nim - run: nimble -y develop + run: nimble -y develop && nimble install - name: test working-directory: tests/nim run: python3 testnim.py + bazel: + name: Bazel + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v6 + - name: bazel build + run: > + bazel build + //:flatc + //:flatbuffers + - name: bazel test + run: > + bazel test + //tests:flatbuffers_test + release-digests: if: startsWith(github.ref, 'refs/tags/') needs: [build-linux, build-windows, build-mac-intel, build-mac-universal] outputs: digests: ${{ steps.hash.outputs.digests }} - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 steps: - name: Merge results id: hash @@ -515,7 +624,7 @@ jobs: echo "$MAC_DIGESTS" | base64 -d >> checksums.txt echo "$MACINTEL_DIGESTS" | base64 -d >> checksums.txt echo "$WINDOWS_DIGESTS" | base64 -d >> checksums.txt - echo "::set-output name=digests::$(cat checksums.txt | base64 -w0)" + echo "digests=$(cat checksums.txt | base64 -w0)" >> $GITHUB_OUTPUT provenance: if: startsWith(github.ref, 'refs/tags/') @@ -524,7 +633,8 @@ jobs: actions: read # To read the workflow path. id-token: write # To sign the provenance. contents: write # To add assets to a release. - uses: slsa-framework/slsa-github-generator/.github/workflows/generator_generic_slsa3.yml@v1.2.0 + uses: slsa-framework/slsa-github-generator/.github/workflows/generator_generic_slsa3.yml@v1.2.1 with: base64-subjects: "${{ needs.release-digests.outputs.digests }}" upload-assets: true # Optional: Upload to a new release + compile-generator: true # Workaround for https://github.com/slsa-framework/slsa-github-generator/issues/1163 diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml deleted file mode 100644 index 8dcbab8ba1..0000000000 --- a/.github/workflows/codeql.yml +++ /dev/null @@ -1,71 +0,0 @@ -# For most projects, this workflow file will not need changing; you simply need -# to commit it to your repository. -# -# You may wish to alter this file to override the set of languages analyzed, -# or to provide custom queries or build logic. -# -# ******** NOTE ******** -# We have attempted to detect the languages in your repository. Please check -# the `language` matrix defined below to confirm you have the correct set of -# supported CodeQL languages. -# -name: "CodeQL" -permissions: read-all - -on: - push: - branches: [ master ] - pull_request: - # The branches below must be a subset of the branches above - branches: [ master ] - schedule: - - cron: '16 20 * * 0' - -jobs: - analyze: - name: Analyze - runs-on: ubuntu-latest - permissions: - actions: read - contents: read - security-events: write - - strategy: - fail-fast: false - matrix: - language: [ 'cpp' ] - # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ] - # Learn more about CodeQL language support at https://git.io/codeql-language-support - - steps: - - name: Checkout repository - uses: actions/checkout@v3 - - # Initializes the CodeQL tools for scanning. - - name: Initialize CodeQL - uses: github/codeql-action/init@v2 - with: - languages: ${{ matrix.language }} - # If you wish to specify custom queries, you can do so here or in a config file. - # By default, queries listed here will override any specified in a config file. - # Prefix the list here with "+" to use these queries and those in the config file. - # queries: ./path/to/local/query, your-org/your-repo/queries@main - - # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). - # If this step fails, then you should remove it and run the build manually (see below) - # - name: Autobuild - # uses: github/codeql-action/autobuild@v2 - - # â„šī¸ Command-line programs to run using the OS shell. - # 📚 https://git.io/JvXDl - - # âœī¸ If the Autobuild fails above, remove it and uncomment the following three lines - # and modify them (or add more) to build your code if your project - # uses a compiled language - - - run: | - cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_STRICT_MODE=ON . - make -j - - - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v2 diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml new file mode 100644 index 0000000000..d4c066a8bd --- /dev/null +++ b/.github/workflows/docs.yml @@ -0,0 +1,36 @@ +name: docs +on: + # For manual pushes. + workflow_dispatch: + + # Pushes to main that touch the documentation directory. + push: + branches: + - master + paths: + - 'docs/**' + +permissions: + contents: write +jobs: + deploy: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + - name: Configure Git Credentials + run: | + git config user.name github-actions[bot] + git config user.email 41898282+github-actions[bot]@users.noreply.github.com + - uses: actions/setup-python@v5 + with: + python-version: 3.x + - run: echo "cache_id=$(date --utc '+%V')" >> $GITHUB_ENV + - uses: actions/cache@v4 + with: + key: mkdocs-material-${{ env.cache_id }} + path: .cache + restore-keys: | + mkdocs-material- + - run: pip install mkdocs-material + - run: pip install mkdocs-redirects + - run: mkdocs gh-deploy --force -f docs/mkdocs.yml diff --git a/.github/workflows/label.yml b/.github/workflows/label.yml index 42a9615ef2..d01947be3b 100644 --- a/.github/workflows/label.yml +++ b/.github/workflows/label.yml @@ -19,6 +19,6 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/labeler@main + - uses: actions/labeler@v6 with: - repo-token: "${{ secrets.GITHUB_TOKEN }}" \ No newline at end of file + repo-token: "${{ secrets.GITHUB_TOKEN }}" diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 7394617c00..9a90095392 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -1,7 +1,7 @@ name: OSS-Fuzz permissions: read-all -on: +on: pull_request: branches: - master @@ -27,7 +27,7 @@ jobs: language: c++ fuzz-seconds: 60 - name: Upload Crash - uses: actions/upload-artifact@v1 + uses: actions/upload-artifact@v4 if: failure() && steps.build.outcome == 'success' with: name: artifacts diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index da4ac01e88..309fe12c73 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -5,23 +5,23 @@ on: # For manual tests. workflow_dispatch: release: - types: [created] + types: [published] jobs: publish-npm: name: Publish NPM - runs-on: ubuntu-latest + runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v6 - uses: actions/setup-node@v3 with: - node-version: '16.x' + node-version: '20.x' registry-url: 'https://registry.npmjs.org' - + - run: npm publish env: NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} - + publish-pypi: name: Publish PyPi runs-on: ubuntu-latest @@ -29,20 +29,20 @@ jobs: run: working-directory: ./python steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v6 - uses: actions/setup-python@v4 with: python-version: '3.10' - + - name: Install Dependencies run: | python3 -m pip install --upgrade pip - python3 -m pip install setuptools wheel twine - + python3 -m pip install build twine + - name: Build run: | - python3 setup.py sdist bdist_wheel - + python3 -m build . + - name: Upload to PyPi run: | python3 -m twine upload dist/* @@ -57,23 +57,22 @@ jobs: run: working-directory: ./net/flatbuffers steps: - - uses: actions/checkout@v3 - - uses: actions/setup-dotnet@v3 + - uses: actions/checkout@v6 + - uses: actions/setup-dotnet@v5 with: - dotnet-version: '6.0.x' - + dotnet-version: '8.0.x' - name: Build run: | dotnet build Google.FlatBuffers.csproj -c Release - + - name: Pack run: | dotnet pack Google.FlatBuffers.csproj -c Release - + - name: Upload to NuGet run: | - dotnet nuget push .\bin\Release\Google.FlatBuffers.*.nupkg -k ${{ secrets.NUGET_API_KEY }} -s https://api.nuget.org/v3/index.json - + dotnet nuget push .\bin\Release\Google.FlatBuffers.*.nupkg -k ${{ secrets.NUGET_API_KEY }} -s https://api.nuget.org/v3/index.json + publish-maven: name: Publish Maven runs-on: ubuntu-latest @@ -81,10 +80,10 @@ jobs: run: working-directory: ./java steps: - - uses: actions/checkout@v3 - + - uses: actions/checkout@v6 + - name: Set up Maven Central Repository - uses: actions/setup-java@v3 + uses: actions/setup-java@v5 with: java-version: '11' distribution: 'adopt' @@ -94,13 +93,60 @@ jobs: server-password: OSSRH_PASSWORD gpg-private-key: ${{ secrets.MAVEN_GPG_PRIVATE_KEY }} gpg-passphrase: MAVEN_GPG_PASSPHRASE # this needs to be an env var - + - name: Publish Maven run: mvn --batch-mode clean deploy env: - OSSRH_USERNAME: ${{ secrets.OSSRH_USERNAME }} - OSSRH_PASSWORD: ${{ secrets.OSSRH_TOKEN }} + OSSRH_USERNAME: ${{ secrets.OSSRH_USER_V2 }} + OSSRH_PASSWORD: ${{ secrets.OSSRH_TOKEN_V2 }} + MAVEN_GPG_PASSPHRASE: ${{ secrets.MAVEN_GPG_PASSPHRASE }} + + publish-maven-kotlin: + name: Publish Maven - Kotlin + runs-on: ubuntu-latest + defaults: + run: + working-directory: ./kotlin + steps: + - uses: actions/checkout@v6 + - name: Set up Maven Central Repository + uses: actions/setup-java@v5 + with: + java-version: '11' + distribution: 'adopt' + cache: 'maven' + server-id: ossrh + server-username: OSSRH_USERNAME + server-password: OSSRH_PASSWORD + gpg-private-key: ${{ secrets.MAVEN_GPG_PRIVATE_KEY }} + gpg-passphrase: MAVEN_GPG_PASSPHRASE # this needs to be an env var + + - name: Publish Kotlin Library on Maven + run: ./gradlew publishAllPublicationsToSonatypeRepository + env: + OSSRH_USERNAME: ${{ secrets.OSSRH_USER_V2 }} + OSSRH_PASSWORD: ${{ secrets.OSSRH_TOKEN_V2 }} MAVEN_GPG_PASSPHRASE: ${{ secrets.MAVEN_GPG_PASSPHRASE }} + + + publish-crates: + name: Publish crates.io + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + - uses: actions-rs/toolchain@v1 + with: + toolchain: stable + override: true - - + - name: Publish Flatbuffers + uses: katyo/publish-crates@v2 + with: + path: ./rust/flatbuffers + registry-token: ${{ secrets.CARGO_TOKEN }} + + - name: Publish Flexbuffers + uses: katyo/publish-crates@v2 + with: + path: ./rust/flexbuffers + registry-token: ${{ secrets.CARGO_TOKEN }} diff --git a/.github/workflows/scorecards.yml b/.github/workflows/scorecards.yml deleted file mode 100644 index 8b2be945d6..0000000000 --- a/.github/workflows/scorecards.yml +++ /dev/null @@ -1,55 +0,0 @@ -name: Scorecards supply-chain security -on: - # Only the default branch is supported. - branch_protection_rule: - schedule: - - cron: '21 2 * * 5' - push: - branches: [ master ] - -# Declare default permissions as read only. -permissions: read-all - -jobs: - analysis: - name: Scorecards analysis - runs-on: ubuntu-latest - permissions: - # Needed to upload the results to code-scanning dashboard. - security-events: write - actions: read - contents: read - - steps: - - name: "Checkout code" - uses: actions/checkout@a12a3943b4bdde767164f792f33f40b04645d846 # v3.0.0 - with: - persist-credentials: false - - - name: "Run analysis" - uses: ossf/scorecard-action@ce330fde6b1a5c9c75b417e7efc510b822a35564 # v1.1.2 - with: - results_file: results.sarif - results_format: sarif - # Read-only PAT token. To create it, - # follow the steps in https://github.com/ossf/scorecard-action#pat-token-creation. - repo_token: ${{ secrets.SCORECARD_READ_TOKEN }} - # Publish the results to enable scorecard badges. For more details, see - # https://github.com/ossf/scorecard-action#publishing-results. - # For private repositories, `publish_results` will automatically be set to `false`, - # regardless of the value entered here. - publish_results: true - - # Upload the results as artifacts (optional). - - name: "Upload artifact" - uses: actions/upload-artifact@6673cd052c4cd6fcf4b4e6e60ea986c889389535 # v3.0.0 - with: - name: SARIF file - path: results.sarif - retention-days: 5 - - # Upload the results to GitHub's code scanning dashboard. - - name: "Upload to code-scanning" - uses: github/codeql-action/upload-sarif@5f532563584d71fdef14ee64d17bafb34f751ce5 # v1.0.26 - with: - sarif_file: results.sarif diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml index 45f0119292..1d35cd4781 100644 --- a/.github/workflows/stale.yml +++ b/.github/workflows/stale.yml @@ -1,9 +1,13 @@ name: Mark stale issues and pull requests -permissions: read-all +permissions: + issues: write + pull-requests: write on: + # For manual tests. + workflow_dispatch: schedule: - - cron: "30 20 * * *" + - cron: "30 20 * * *" jobs: stale: @@ -11,14 +15,23 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/stale@v4.0.0 + - uses: actions/stale@v10 with: repo-token: ${{ secrets.GITHUB_TOKEN }} - stale-pr-message: 'This pull request is stale because it has been open 6 months with no activity. Please comment or this will be closed in 14 days.' - stale-issue-message: 'This issue is stale because it has been open 6 months with no activity. Please comment or this will be closed in 14 days.' - days-before-stale: 182 # 6 months - days-before-close: 14 - operations-per-run: 1500 + operations-per-run: 500 + exempt-all-milestones: true + remove-stale-when-updated: true + + stale-issue-message: 'This issue is stale because it has been open 6 months with no activity. Please comment or label `not-stale`, or this will be closed in 14 days.' + close-issue-message: 'This issue was automatically closed due to no activity for 6 months plus the 14 day notice period.' + days-before-issue-stale: 182 # 6 months + days-before-issue-close: 14 # 2 weeks exempt-issue-labels: not-stale + + stale-pr-message: 'This pull request is stale because it has been open 6 months with no activity. Please comment or label `not-stale`, or this will be closed in 14 days.' + close-pr-message: 'This pull request was automatically closed due to no activity for 6 months plus the 14 day notice period.' + days-before-pr-stale: 182 # 6 months + days-before-pr-close: 14 # 2 week exempt-pr-labels: not-stale - exempt-all-milestones: true + exempt-draft-pr: false + diff --git a/.gitignore b/.gitignore index 8c7baf8765..f27c9b41b4 100644 --- a/.gitignore +++ b/.gitignore @@ -149,4 +149,14 @@ flatbuffers.pc **/html/** **/latex/** # https://cmake.org/cmake/help/latest/module/FetchContent.html#variable:FETCHCONTENT_BASE_DIR -_deps/ \ No newline at end of file +cmake-build-debug/ +_deps/ +**/.gradle/** +kotlin/**/generated +MODULE.bazel.lock + +# Ignore the generated docs +docs/site + +# Ignore generated files +*.fbs.h diff --git a/.npmrc b/.npmrc new file mode 100644 index 0000000000..84ff0791f0 --- /dev/null +++ b/.npmrc @@ -0,0 +1 @@ +hoist=false diff --git a/.yamato/Build.yml b/.yamato/Build.yml index 08a649e4f3..04a79a464f 100644 --- a/.yamato/Build.yml +++ b/.yamato/Build.yml @@ -3,8 +3,7 @@ all: dependencies: - .yamato/Build.yml#build_linux - .yamato/Build.yml#build_windows - - .yamato/Build.yml#build_osx_x86_64 - - .yamato/Build.yml#build_osx_arm64 + - .yamato/Build.yml#build_osx_universal build_linux: name: Build - Linux @@ -39,40 +38,19 @@ build_windows: paths: - Release\flatc.exe -build_osx_x86_64: - name: Build - OSX - x86_64 +build_osx_universal: + name: Build - OSX - universal agent: type: Unity::VM::osx - image: slough-ops/macos-13-xcode:stable - flavor: b1.xlarge - config: - env_vars: - - PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin - commands: - - brew install cmake - - cmake -G "Xcode" -DCMAKE_OSX_ARCHITECTURES=x86_64 -DCMAKE_BUILD_TYPE=Release - - cmake --build . --config Release - timeout: 30 - artifacts: - reported_artifacts: - paths: - - Release\flatc - -build_osx_arm64: - name: Build - OSX - arm64 - agent: - type: Unity::VM::osx - image: slough-ops/macos-13-xcode:stable - flavor: b1.xlarge - config: - env_vars: - - PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin + image: slough-ops/macos-15-xcode:v2.0.20 + flavor: m1.mac commands: - brew install cmake - - cmake -G "Xcode" -DFLATBUFFERS_BUILD_TESTS=0 -DCMAKE_OSX_ARCHITECTURES=arm64 -DCMAKE_BUILD_TYPE=Release + - cmake -G "Xcode" -DFLATBUFFERS_BUILD_TESTS=0 -DCMAKE_OSX_ARCHITECTURES="x86_64;arm64" -DCMAKE_BUILD_TYPE=Release - cmake --build . --config Release + - lipo -info Release/flatc timeout: 30 artifacts: reported_artifacts: paths: - - Release\flatc + - Release/flatc diff --git a/BUILD.bazel b/BUILD.bazel index f2aac0ae38..20a4fd60a4 100644 --- a/BUILD.bazel +++ b/BUILD.bazel @@ -25,6 +25,28 @@ config_setting( ], ) +filegroup( + name = "distribution", + srcs = [ + ".bazelignore", + ".npmrc", + "BUILD.bazel", + "MODULE.bazel", + "build_defs.bzl", + "package.json", + "pnpm-lock.yaml", + "typescript.bzl", + "//grpc/src/compiler:distribution", + "//include/codegen:distribution", + "//reflection:distribution", + "//src:distribution", + "//ts:distribution", + ] + glob([ + "include/flatbuffers/*.h", + ]), + visibility = ["//visibility:public"], +) + # Public flatc library to compile flatbuffer files at runtime. cc_library( name = "flatbuffers", @@ -41,12 +63,13 @@ filegroup( "include/flatbuffers/allocator.h", "include/flatbuffers/array.h", "include/flatbuffers/base.h", - "include/flatbuffers/bfbs_generator.h", "include/flatbuffers/buffer.h", "include/flatbuffers/buffer_ref.h", + "include/flatbuffers/code_generator.h", "include/flatbuffers/code_generators.h", "include/flatbuffers/default_allocator.h", "include/flatbuffers/detached_buffer.h", + "include/flatbuffers/file_manager.h", "include/flatbuffers/flatbuffer_builder.h", "include/flatbuffers/flatbuffers.h", "include/flatbuffers/flex_flat_util.h", @@ -98,15 +121,7 @@ filegroup( # Library used by flatbuffer_cc_library rules. cc_library( name = "runtime_cc", - hdrs = [ - "include/flatbuffers/base.h", - "include/flatbuffers/flatbuffers.h", - "include/flatbuffers/flexbuffers.h", - "include/flatbuffers/stl_emulation.h", - "include/flatbuffers/util.h", - "include/flatbuffers/vector.h", - "include/flatbuffers/verifier.h", - ], + hdrs = ["//:public_headers"], linkstatic = 1, strip_include_prefix = "/include", ) diff --git a/CHANGELOG.md b/CHANGELOG.md index 05c153095c..17f7ff7eba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,15 +4,150 @@ 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. -## 22.10.25 (Oct 25 2002) +## [25.12.19] (December 19 2025)(https://github.com/google/flatbuffers/releases/tag/v25.12.19) + +* [C++] Default emptry vector support (#8870) +* [C++] Add --gen-absl-hash option (#8868) +* [Kotlin] Upgrade to MacOS 15 (#8845) +* [C++] Fix vector of table with naked ptrs (#8830) +* [Python] Optimize Offset/Pad/Prep (#8808) +* Implement `--file-names-only` (#8788) +* [C++] Fix size verifer (#8740) + +## [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 +* Swift version 6.0 support (#8414) + +## [25.1.24] (January 24 2025)(https://github.com/google/flatbuffers/releases/tag/v25.1.24) + +* Mostly related to bazel build support. +* Min bazel supported is now 7 or higher, as WORKSPACE files are removed (#8509) +* Minor C++ codegen fix removing extra semicolon (#8488) + +## [25.1.21] (January 21 2025)(https://github.com/google/flatbuffers/releases/tag/v25.1.21) + +* Rust Full Reflection (#8102) +* Mostly documentation updates hosted at https://flatbuffers.dev + +## [24.3.25] (March 25 2024)(https://github.com/google/flatbuffers/releases/tag/v24.3.25) + +* Fixed license metadata parsing (#8253) +* [C++] Allow string_view in `LookUpByKey` in addition to null-terminated c-style strings (#8203) + +## [24.3.7] (March 7 2024)(https://github.com/google/flatbuffers/releases/tag/v24.3.7) + +* Just to fix some of the CI build issues from the 24.3.6 release. + +## [24.3.6] (March 6 2024)(https://github.com/google/flatbuffers/releases/tag/v24.3.6) + +* Fix typescript object API to allow 0 values for null-default scalars (#7864) + +## [23.5.26 (May 26 2023)](https://github.com/google/flatbuffers/releases/tag/v23.5.26) + +* Mostly bug fixing for 64-bit support +* Adds support for specifying underling type of unions in C++ and TS/JS (#7954) + +## [23.5.9 (May 9 2023)](https://github.com/google/flatbuffers/releases/tag/v23.5.9) + +* 64-bit support for C++ (#7935) + +## [23.5.8 (May 8 2023)](https://github.com/google/flatbuffers/releases/tag/v23.5.8) + +* add key_field to compiled tests +* Add golden language directory +* Rework cmake flatc codegeneration (#7938) +* remove defining generated files in test srcs +* Add binary schema reflection (#7932) +* Migrate from rules_nodejs to rules_js/rules_ts (take 2) (#7928) +* `flat_buffers.dart`: mark const variable finals for internal Dart linters +* fixed some windows warnings (#7929) +* inject no long for FBS generation to remove logs in flattests (#7926) +* Revert "Migrate from rules_nodejs to rules_js/rules_ts (#7923)" (#7927) +* Migrate from rules_nodejs to rules_js/rules_ts (#7923) +* Only generate @kotlin.ExperimentalUnsigned annotation on create*Vector methods having an unsigned array type parameter. (#7881) +* additional check for absl::string_view availability (#7897) +* Optionally generate Python type annotations (#7858) +* Replace deprecated command with environment file (#7921) +* drop glibc from runtime dependencies (#7906) +* Make JSON supporting advanced union features (#7869) +* Allow to use functions from `BuildFlatBuffers.cmake` from a flatbuffers installation installed with CMake. (#7912) +* TS/JS: Use TypeError instead of Error when appropriate (#7910) +* Go: make generated code more compliant to "go fmt" (#7907) +* Support file_identifier in Go (#7904) +* Optionally generate type prefixes and suffixes for python code (#7857) +* Go: add test for FinishWithFileIdentifier (#7905) +* Fix go_sample.sh (#7903) +* [TS/JS] Upgrade dependencies (#7889) +* Add a FileWriter interface (#7821) +* TS/JS: Use minvalue from enum if not found (#7888) +* [CS] Verifier (#7850) +* README.md: PyPI case typo (#7880) +* Update go documentation link to point to root module (#7879) +* use Bool for flatbuffers bool instead of Byte (#7876) +* fix using null string in vector (#7872) +* Add `flatbuffers-64` branch to CI for pushes +* made changes to the rust docs so they would compile. new_with_capacity is deprecated should use with_capacity, get_root_as_monster should be root_as_monster (#7871) +* Adding comment for code clarification (#7856) +* ToCamelCase() when kLowerCamel now converts first char to lower. (#7838) +* Fix help output for --java-checkerframework (#7854) +* Update filename to README.md and improve formatting (#7855) +* Update stale.yml +* Updated remaining usages of LICENSE.txt + +## [23.3.3 (Mar 3 2023)](https://github.com/google/flatbuffers/releases/tag/v23.3.3) + +* Refactoring of `flatc` generators to use an interface (#7797). + +* Removed legacy cmake support and set min to 3.8 (#7801). + +## [23.1.21 (Jan 21 2023)](https://github.com/google/flatbuffers/releases/tag/v23.1.20) + +* Reworked entry points for Typescript/Javascript and compatibility for single + file build (#7510) + +## [23.1.20 (Jan 20 2023)](https://github.com/google/flatbuffers/releases/tag/v23.1.20) + +* Removed go.mod files after some versioning issues were being report (#7780). + +## [23.1.4 (Jan 4 2023)](https://github.com/google/flatbuffers/releases/tag/v23.1.4) + +* Major release! Just kidding, we are continuing the + [versioning scheme](https://github.com/google/flatbuffers/wiki/Versioning) of + using a date to signify releases. This results in the first release of the new + year to bump the tradition major version field. + +* Go minimum version is now 1.19 (#7720) with the addition of Go modules. + +* Added CI support for Big Endian regression testing (#7707). + +* Fixed `getFullyQualifiedName` in typescript to return name delimited by '.' + instead of '_' (#7730). + +* Fixed the versioning scheme to not include leading zeros which are not + consistently handled by every package manager. Only the last release + (12.12.06) should have suffered from this. + +## [22.12.06 (Dec 06 2022)](https://github.com/google/flatbuffers/releases/tag/v22.12.06) + +* Bug fixing release, no major changes. + +## [22.10.25 (Oct 25 2022)](https://github.com/google/flatbuffers/releases/tag/v22.10.25) * Added Nim language support with generator and runtime libraries (#7534). -## 22.9.29 (Sept 29 2022) +## [22.9.29 (Sept 29 2022)](https://github.com/google/flatbuffers/releases/tag/v22.9.29) * Rust soundness fixes to avoid the crate from bing labelled unsafe (#7518). -## 22.9.24 (Sept 24 2022) +## [22.9.24 (Sept 24 2022)](https://github.com/google/flatbuffers/releases/tag/v22.9.24) * 20 Major releases in a row? Nope, we switched to a new [versioning scheme](https://github.com/google/flatbuffers/wiki/Versioning) @@ -63,4 +198,4 @@ necessarily listed. * First binary schema generator (Lua) to generate Lua code via a .bfbs file. This is mostly an implementation detail of flatc internals, but will be slowly - applied to the other language generators. \ No newline at end of file + applied to the other language generators. diff --git a/CMake/BuildFlatBuffers.cmake b/CMake/BuildFlatBuffers.cmake index b0c5c8fbcf..631e5adfbf 100644 --- a/CMake/BuildFlatBuffers.cmake +++ b/CMake/BuildFlatBuffers.cmake @@ -59,6 +59,9 @@ function(build_flatbuffers flatbuffers_schemas if(FLATBUFFERS_FLATC_EXECUTABLE) set(FLATC_TARGET "") set(FLATC ${FLATBUFFERS_FLATC_EXECUTABLE}) + elseif(TARGET flatbuffers::flatc) + set(FLATC_TARGET flatbuffers::flatc) + set(FLATC flatbuffers::flatc) else() set(FLATC_TARGET flatc) set(FLATC flatc) @@ -157,6 +160,10 @@ endfunction() # other flagc flags using the FLAGS option to change the behavior of the flatc # tool. # +# When the target_link_libraries is done within a different directory than +# flatbuffers_generate_headers is called, then the target should also be dependent +# the custom generation target called GENERATE_. +# # Arguments: # TARGET: The name of the target to generate. # SCHEMAS: The list of schema files to generate code for. @@ -182,6 +189,9 @@ endfunction() # target_link_libraries(MyExecutableTarget # PRIVATE my_generated_headers_target # ) +# +# Optional (only needed within different directory): +# add_dependencies(app GENERATE_my_generated_headers_target) function(flatbuffers_generate_headers) # Parse function arguments. set(options) @@ -204,6 +214,9 @@ function(flatbuffers_generate_headers) if(FLATBUFFERS_FLATC_EXECUTABLE) set(FLATC_TARGET "") set(FLATC ${FLATBUFFERS_FLATC_EXECUTABLE}) + elseif(TARGET flatbuffers::flatc) + set(FLATC_TARGET flatbuffers::flatc) + set(FLATC flatbuffers::flatc) else() set(FLATC_TARGET flatc) set(FLATC flatc) @@ -226,6 +239,8 @@ function(flatbuffers_generate_headers) "--include-prefix" ${FLATBUFFERS_GENERATE_HEADERS_INCLUDE_PREFIX}) endif() + set(generated_custom_commands) + # Create rules to generate the code for each schema. foreach(schema ${FLATBUFFERS_GENERATE_HEADERS_SCHEMAS}) get_filename_component(filename ${schema} NAME_WE) @@ -254,6 +269,7 @@ function(flatbuffers_generate_headers) COMMENT "Building ${schema} flatbuffers...") list(APPEND all_generated_header_files ${generated_include}) list(APPEND all_generated_source_files ${generated_source_file}) + list(APPEND generated_custom_commands "${generated_include}" "${generated_source_file}") # Geneate the binary flatbuffers schemas if instructed to. if (NOT ${FLATBUFFERS_GENERATE_HEADERS_BINARY_SCHEMAS_DIR} STREQUAL "") @@ -267,10 +283,17 @@ function(flatbuffers_generate_headers) ${schema} DEPENDS ${FLATC_TARGET} ${schema} WORKING_DIRECTORY "${working_dir}") + list(APPEND generated_custom_commands "${binary_schema}") list(APPEND all_generated_binary_files ${binary_schema}) endif() endforeach() + # Create an additional target as add_custom_command scope is only within same directory (CMakeFile.txt) + set(generate_target GENERATE_${FLATBUFFERS_GENERATE_HEADERS_TARGET}) + add_custom_target(${generate_target} ALL + DEPENDS ${generated_custom_commands} + COMMENT "Generating flatbuffer target ${FLATBUFFERS_GENERATE_HEADERS_TARGET}") + # Set up interface library add_library(${FLATBUFFERS_GENERATE_HEADERS_TARGET} INTERFACE) target_sources( @@ -365,6 +388,9 @@ function(flatbuffers_generate_binary_files) if(FLATBUFFERS_FLATC_EXECUTABLE) set(FLATC_TARGET "") set(FLATC ${FLATBUFFERS_FLATC_EXECUTABLE}) + elseif(TARGET flatbuffers::flatc) + set(FLATC_TARGET flatbuffers::flatc) + set(FLATC flatbuffers::flatc) else() set(FLATC_TARGET flatc) set(FLATC flatc) diff --git a/CMake/CMakeLists_legacy.cmake.in b/CMake/CMakeLists_legacy.cmake.in deleted file mode 100644 index 9e1af2bff0..0000000000 --- a/CMake/CMakeLists_legacy.cmake.in +++ /dev/null @@ -1,780 +0,0 @@ -# This was the legacy /CMakeLists.txt that supported cmake version 2.8.12. -# It was originally copied on Jan 30 2022, and is conditionally included in the -# current /CMakeLists.txt if the cmake version used is older than the new -# minimum version. -# -# Only add to this file to fix immediate issues or if a change cannot be made -# /CMakeList.txt in a compatible way. - -if (POLICY CMP0048) - cmake_policy(SET CMP0048 NEW) - if(CMAKE_VERSION VERSION_LESS 3.9) - project(FlatBuffers - VERSION 2.0.0 - LANGUAGES CXX) - else() - project(FlatBuffers - DESCRIPTION "Flatbuffers serialization library" - VERSION 2.0.0 - LANGUAGES CXX) - endif() -else() - project(FlatBuffers) -endif (POLICY CMP0048) - -include(CMake/Version.cmake) - -# generate compile_commands.json -set(CMAKE_EXPORT_COMPILE_COMMANDS ON) - -# NOTE: Code coverage only works on Linux & OSX. -option(FLATBUFFERS_CODE_COVERAGE "Enable the code coverage build option." OFF) -option(FLATBUFFERS_BUILD_TESTS "Enable the build of tests and samples." ON) -option(FLATBUFFERS_INSTALL "Enable the installation of targets." ON) -option(FLATBUFFERS_BUILD_FLATLIB "Enable the build of the flatbuffers library" - ON) -option(FLATBUFFERS_BUILD_FLATC "Enable the build of the flatbuffers compiler" - ON) -option(FLATBUFFERS_STATIC_FLATC "Build flatbuffers compiler with -static flag" - OFF) -option(FLATBUFFERS_BUILD_FLATHASH "Enable the build of flathash" ON) -option(FLATBUFFERS_BUILD_BENCHMARKS "Enable the build of flatbenchmark. \" - Requires C++11." - OFF) -option(FLATBUFFERS_BUILD_GRPCTEST "Enable the build of grpctest" OFF) -option(FLATBUFFERS_BUILD_SHAREDLIB - "Enable the build of the flatbuffers shared library" - OFF) -option(FLATBUFFERS_LIBCXX_WITH_CLANG "Force libc++ when using Clang" ON) -# NOTE: Sanitizer check only works on Linux & OSX (gcc & llvm). -option(FLATBUFFERS_CODE_SANITIZE - "Add '-fsanitize' flags to 'flattests' and 'flatc' targets." - OFF) -option(FLATBUFFERS_PACKAGE_REDHAT - "Build an rpm using the 'package' target." - OFF) -option(FLATBUFFERS_PACKAGE_DEBIAN - "Build an deb using the 'package' target." - OFF) -option(FLATBUFFERS_BUILD_CPP17 - "Enable the build of c++17 test target. \" - Requirements: Clang6, GCC7, MSVC2017 (_MSC_VER >= 1914) or higher." - OFF) -option(FLATBUFFERS_BUILD_LEGACY - "Run C++ code generator with '--cpp-std c++0x' switch." - OFF) -option(FLATBUFFERS_ENABLE_PCH - "Enable precompile headers support for 'flatbuffers' and 'flatc'. \" - Only work if CMake supports 'target_precompile_headers'. \" - This can speed up compilation time." - OFF) -option(FLATBUFFERS_SKIP_MONSTER_EXTRA - "Skip generating monster_extra.fbs that contains non-supported numerical\" - types." OFF) -option(FLATBUFFERS_OSX_BUILD_UNIVERSAL - "Enable the build for multiple architectures on OS X (arm64, x86_64)." - ON) - -if(NOT FLATBUFFERS_BUILD_FLATC AND FLATBUFFERS_BUILD_TESTS) - message(WARNING - "Cannot build tests without building the compiler. Tests will be disabled.") - set(FLATBUFFERS_BUILD_TESTS OFF) -endif() - -if(DEFINED FLATBUFFERS_MAX_PARSING_DEPTH) - # Override the default recursion depth limit. - add_definitions(-DFLATBUFFERS_MAX_PARSING_DEPTH=${FLATBUFFERS_MAX_PARSING_DEPTH}) - message(STATUS "FLATBUFFERS_MAX_PARSING_DEPTH: ${FLATBUFFERS_MAX_PARSING_DEPTH}") -endif() - -# Auto-detect locale-narrow 'strtod_l' and 'strtoull_l' functions. -if(NOT DEFINED FLATBUFFERS_LOCALE_INDEPENDENT) - include(CheckCXXSymbolExists) - - set(FLATBUFFERS_LOCALE_INDEPENDENT 0) - if(MSVC) - check_cxx_symbol_exists(_strtof_l stdlib.h FLATBUFFERS_HAS_STRTOF_L) - check_cxx_symbol_exists(_strtoui64_l stdlib.h FLATBUFFERS_HAS_STRTOULL_L) - else() - check_cxx_symbol_exists(strtof_l stdlib.h FLATBUFFERS_HAS_STRTOF_L) - check_cxx_symbol_exists(strtoull_l stdlib.h FLATBUFFERS_HAS_STRTOULL_L) - endif() - if(FLATBUFFERS_HAS_STRTOF_L AND FLATBUFFERS_HAS_STRTOULL_L) - set(FLATBUFFERS_LOCALE_INDEPENDENT 1) - endif() -endif() -add_definitions(-DFLATBUFFERS_LOCALE_INDEPENDENT=$) - -set(FlatBuffers_Library_SRCS - include/flatbuffers/allocator.h - include/flatbuffers/array.h - include/flatbuffers/base.h - include/flatbuffers/bfbs_generator.h - include/flatbuffers/buffer.h - include/flatbuffers/buffer_ref.h - include/flatbuffers/default_allocator.h - include/flatbuffers/detached_buffer.h - include/flatbuffers/flatbuffer_builder.h - include/flatbuffers/flatbuffers.h - include/flatbuffers/flexbuffers.h - include/flatbuffers/hash.h - include/flatbuffers/idl.h - include/flatbuffers/minireflect.h - include/flatbuffers/reflection.h - include/flatbuffers/reflection_generated.h - include/flatbuffers/registry.h - include/flatbuffers/stl_emulation.h - include/flatbuffers/string.h - include/flatbuffers/struct.h - include/flatbuffers/table.h - include/flatbuffers/util.h - include/flatbuffers/vector.h - include/flatbuffers/vector_downward.h - include/flatbuffers/verifier.h - src/idl_parser.cpp - src/idl_gen_text.cpp - src/reflection.cpp - src/util.cpp -) - -set(FlatBuffers_Compiler_SRCS - ${FlatBuffers_Library_SRCS} - src/idl_gen_cpp.cpp - src/idl_gen_csharp.cpp - src/idl_gen_dart.cpp - src/idl_gen_kotlin.cpp - src/idl_gen_go.cpp - src/idl_gen_java.cpp - src/idl_gen_ts.cpp - src/idl_gen_php.cpp - src/idl_gen_python.cpp - src/idl_gen_lobster.cpp - src/idl_gen_lua.cpp - src/idl_gen_rust.cpp - src/idl_gen_fbs.cpp - src/idl_gen_grpc.cpp - src/idl_gen_json_schema.cpp - src/idl_gen_swift.cpp - src/flatc.cpp - src/flatc_main.cpp - src/bfbs_gen.h - src/bfbs_gen_lua.h - include/flatbuffers/code_generators.h - src/bfbs_gen_lua.cpp - src/code_generators.cpp - grpc/src/compiler/schema_interface.h - grpc/src/compiler/cpp_generator.h - grpc/src/compiler/cpp_generator.cc - grpc/src/compiler/go_generator.h - grpc/src/compiler/go_generator.cc - grpc/src/compiler/java_generator.h - grpc/src/compiler/java_generator.cc - grpc/src/compiler/python_generator.h - grpc/src/compiler/python_generator.cc - grpc/src/compiler/swift_generator.h - grpc/src/compiler/swift_generator.cc - grpc/src/compiler/ts_generator.h - grpc/src/compiler/ts_generator.cc -) - -set(FlatHash_SRCS - include/flatbuffers/hash.h - src/flathash.cpp -) - -set(FlatBuffers_Tests_SRCS - ${FlatBuffers_Library_SRCS} - src/idl_gen_fbs.cpp - tests/test.cpp - tests/test_assert.h - tests/test_assert.cpp - tests/test_builder.h - tests/test_builder.cpp - tests/native_type_test_impl.h - tests/native_type_test_impl.cpp - include/flatbuffers/code_generators.h - src/code_generators.cpp - # file generate by running compiler on tests/monster_test.fbs - ${CMAKE_CURRENT_BINARY_DIR}/tests/monster_test_generated.h - # file generate by running compiler on namespace_test/namespace_test1.fbs - ${CMAKE_CURRENT_BINARY_DIR}/tests/namespace_test/namespace_test1_generated.h - ${CMAKE_CURRENT_BINARY_DIR}/tests/namespace_test/namespace_test2_generated.h - # file generate by running compiler on union_vector/union_vector.fbs - ${CMAKE_CURRENT_BINARY_DIR}/tests/union_vector/union_vector_generated.h - # file generate by running compiler on tests/arrays_test.fbs - ${CMAKE_CURRENT_BINARY_DIR}/tests/arrays_test_generated.h - # file generate by running compiler on tests/native_type_test.fbs - ${CMAKE_CURRENT_BINARY_DIR}/tests/native_type_test_generated.h - # file generate by running compiler on tests/monster_extra.fbs - ${CMAKE_CURRENT_BINARY_DIR}/tests/monster_extra_generated.h - # file generate by running compiler on tests/monster_test.fbs - ${CMAKE_CURRENT_BINARY_DIR}/tests/monster_test_bfbs_generated.h - # file generate by running compiler on tests/optional_scalars.fbs - ${CMAKE_CURRENT_BINARY_DIR}/tests/optional_scalars_generated.h -) - -set(FlatBuffers_Tests_CPP17_SRCS - ${FlatBuffers_Library_SRCS} - tests/test_assert.h - tests/test_assert.cpp - tests/cpp17/test_cpp17.cpp - # file generate by running compiler on tests/monster_test.fbs - ${CMAKE_CURRENT_BINARY_DIR}/tests/cpp17/generated_cpp17/monster_test_generated.h - ${CMAKE_CURRENT_BINARY_DIR}/tests/monster_test_generated.h - ${CMAKE_CURRENT_BINARY_DIR}/tests/cpp17/generated_cpp17/optional_scalars_generated.h - ${CMAKE_CURRENT_BINARY_DIR}/tests/optional_scalars_generated.h -) - -set(FlatBuffers_Sample_Binary_SRCS - include/flatbuffers/flatbuffers.h - samples/sample_binary.cpp - # file generated by running compiler on samples/monster.fbs - ${CMAKE_CURRENT_BINARY_DIR}/samples/monster_generated.h -) - -set(FlatBuffers_Sample_Text_SRCS - ${FlatBuffers_Library_SRCS} - samples/sample_text.cpp - # file generated by running compiler on samples/monster.fbs - ${CMAKE_CURRENT_BINARY_DIR}/samples/monster_generated.h -) - -set(FlatBuffers_Sample_BFBS_SRCS - ${FlatBuffers_Library_SRCS} - samples/sample_bfbs.cpp - # file generated by running compiler on samples/monster.fbs - ${CMAKE_CURRENT_BINARY_DIR}/samples/monster_generated.h -) - -set(FlatBuffers_GRPCTest_SRCS - include/flatbuffers/flatbuffers.h - include/flatbuffers/grpc.h - include/flatbuffers/util.h - src/util.cpp - tests/monster_test.grpc.fb.h - tests/test_assert.h - tests/test_builder.h - tests/monster_test.grpc.fb.cc - tests/test_assert.cpp - tests/test_builder.cpp - grpc/tests/grpctest.cpp - grpc/tests/message_builder_test.cpp - # file generate by running compiler on tests/monster_test.fbs - ${CMAKE_CURRENT_BINARY_DIR}/tests/monster_test_generated.h -) - -# source_group(Compiler FILES ${FlatBuffers_Compiler_SRCS}) -# source_group(Tests FILES ${FlatBuffers_Tests_SRCS}) - -if(EXISTS "${CMAKE_TOOLCHAIN_FILE}") - # do not apply any global settings if the toolchain - # is being configured externally - message(STATUS "Using toolchain file: ${CMAKE_TOOLCHAIN_FILE}.") -elseif(CMAKE_COMPILER_IS_GNUCXX) - if(CYGWIN) - set(CMAKE_CXX_FLAGS - "${CMAKE_CXX_FLAGS} -std=gnu++11") - else(CYGWIN) - set(CMAKE_CXX_FLAGS - "${CMAKE_CXX_FLAGS} -std=c++0x") - endif(CYGWIN) - set(CMAKE_CXX_FLAGS - "${CMAKE_CXX_FLAGS} -Wall -pedantic -Werror -Wextra -Werror=shadow") - set(FLATBUFFERS_PRIVATE_CXX_FLAGS "-Wold-style-cast") - if (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 4.4) - if (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 7.0) - set(CMAKE_CXX_FLAGS - "${CMAKE_CXX_FLAGS} -faligned-new -Werror=implicit-fallthrough=2") - endif() - set(CMAKE_CXX_FLAGS - "${CMAKE_CXX_FLAGS} -Wunused-result -Werror=unused-result -Wunused-parameter -Werror=unused-parameter") - endif() - - # Certain platforms such as ARM do not use signed chars by default - # which causes issues with certain bounds checks. - set(CMAKE_CXX_FLAGS - "${CMAKE_CXX_FLAGS} -fsigned-char") - -# MSVC **MUST** come before the Clang check, as clang-cl is flagged by CMake as "MSVC", but it still textually -# matches as Clang in its Compiler Id :) -# Note: in CMake >= 3.14 we can check CMAKE_CXX_COMPILER_FRONTEND_VARIANT STREQUAL "GNU" or "MSVC" to differentiate... -elseif(MSVC) - # Visual Studio pedantic build settings - # warning C4512: assignment operator could not be generated - # warning C4316: object allocated on the heap may not be aligned - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /W4 /WX /wd4512 /wd4316") - - if(${CMAKE_CXX_COMPILER_ID} MATCHES "Clang") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /D_CRT_SECURE_NO_WARNINGS") - endif() - -elseif(${CMAKE_CXX_COMPILER_ID} MATCHES "Clang") - if(APPLE) - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") - - if(FLATBUFFERS_OSX_BUILD_UNIVERSAL) - set(CMAKE_OSX_ARCHITECTURES "arm64;x86_64") - endif() - else() - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x") - endif() - - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -pedantic -Werror -Wextra -Wno-unused-parameter") - set(FLATBUFFERS_PRIVATE_CXX_FLAGS "-Wold-style-cast") - if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 3.8) - list(APPEND FLATBUFFERS_PRIVATE_CXX_FLAGS "-Wimplicit-fallthrough" "-Wextra-semi" "-Werror=unused-private-field") # enable warning - endif() - if(FLATBUFFERS_LIBCXX_WITH_CLANG) - if(NOT "${CMAKE_SYSTEM_NAME}" MATCHES "Linux") - set(CMAKE_CXX_FLAGS - "${CMAKE_CXX_FLAGS} -stdlib=libc++") - endif() - if(NOT ("${CMAKE_SYSTEM_NAME}" MATCHES "FreeBSD" OR - "${CMAKE_SYSTEM_NAME}" MATCHES "Linux")) - set(CMAKE_EXE_LINKER_FLAGS - "${CMAKE_EXE_LINKER_FLAGS} -lc++abi") - endif() - endif() - - # Certain platforms such as ARM do not use signed chars by default - # which causes issues with certain bounds checks. - set(CMAKE_CXX_FLAGS - "${CMAKE_CXX_FLAGS} -fsigned-char") - -endif() - -# Append FLATBUFFERS_CXX_FLAGS to CMAKE_CXX_FLAGS. -if(DEFINED FLATBUFFERS_CXX_FLAGS AND NOT EXISTS "${CMAKE_TOOLCHAIN_FILE}") - message(STATUS "extend CXX_FLAGS with ${FLATBUFFERS_CXX_FLAGS}") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${FLATBUFFERS_CXX_FLAGS}") -endif() -message(STATUS "CMAKE_CXX_FLAGS: ${CMAKE_CXX_FLAGS}") - -if(FLATBUFFERS_CODE_COVERAGE) - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g -fprofile-arcs -ftest-coverage") - set(CMAKE_EXE_LINKER_FLAGS - "${CMAKE_EXE_LINKER_FLAGS} -fprofile-arcs -ftest-coverage") -endif() - -function(add_fsanitize_to_target _target _sanitizer) - if(WIN32) - target_compile_definitions(${_target} PRIVATE FLATBUFFERS_MEMORY_LEAK_TRACKING) - message(STATUS "Sanitizer MSVC::_CrtDumpMemoryLeaks added to ${_target}") - else() - # FLATBUFFERS_CODE_SANITIZE: boolean {ON,OFF,YES,NO} or string with list of sanitizer. - # List of sanitizer is string starts with '=': "=address,undefined,thread,memory". - if((${CMAKE_CXX_COMPILER_ID} MATCHES "Clang") OR - ((${CMAKE_CXX_COMPILER_ID} MATCHES "GNU") AND NOT (CMAKE_CXX_COMPILER_VERSION VERSION_LESS "4.9")) - ) - set(_sanitizer_flags "=address,undefined") - if(_sanitizer MATCHES "=.*") - # override default by user-defined sanitizer list - set(_sanitizer_flags ${_sanitizer}) - endif() - target_compile_options(${_target} PRIVATE - -g -fsigned-char -fno-omit-frame-pointer - "-fsanitize${_sanitizer_flags}") - target_link_libraries(${_target} PRIVATE - "-fsanitize${_sanitizer_flags}") - set_property(TARGET ${_target} PROPERTY POSITION_INDEPENDENT_CODE ON) - message(STATUS "Sanitizer ${_sanitizer_flags} added to ${_target}") - endif() - endif() -endfunction() - -function(add_pch_to_target _target _pch_header) - if(COMMAND target_precompile_headers) - target_precompile_headers(${_target} PRIVATE ${_pch_header}) - if(NOT MSVC) - set_source_files_properties(src/util.cpp PROPERTIES SKIP_PRECOMPILE_HEADERS ON) - endif() - endif() -endfunction() - -if(BIICODE) - include(biicode/cmake/biicode.cmake) - return() -endif() - -include_directories(include) -include_directories(grpc) - -if(FLATBUFFERS_BUILD_FLATLIB) - add_library(flatbuffers STATIC ${FlatBuffers_Library_SRCS}) - # Attach header directory for when build via add_subdirectory(). - target_include_directories(flatbuffers INTERFACE - $) - target_compile_options(flatbuffers PRIVATE "${FLATBUFFERS_PRIVATE_CXX_FLAGS}") - if(FLATBUFFERS_ENABLE_PCH) - add_pch_to_target(flatbuffers include/flatbuffers/pch/pch.h) - endif() -endif() - -if(FLATBUFFERS_BUILD_FLATC) - add_executable(flatc ${FlatBuffers_Compiler_SRCS}) - if(FLATBUFFERS_ENABLE_PCH) - add_pch_to_target(flatc include/flatbuffers/pch/flatc_pch.h) - endif() - target_compile_options(flatc PRIVATE "${FLATBUFFERS_PRIVATE_CXX_FLAGS}") - if(FLATBUFFERS_CODE_SANITIZE AND NOT WIN32) - add_fsanitize_to_target(flatc ${FLATBUFFERS_CODE_SANITIZE}) - endif() - if(NOT FLATBUFFERS_FLATC_EXECUTABLE) - set(FLATBUFFERS_FLATC_EXECUTABLE $) - endif() - if(MSVC) - # Make flatc.exe not depend on runtime dlls for easy distribution. - target_compile_options(flatc PUBLIC $<$:/MT>) - endif() - if(FLATBUFFERS_STATIC_FLATC AND NOT MSVC) - target_link_libraries(flatc PRIVATE -static) - endif() -endif() - -if(FLATBUFFERS_BUILD_FLATHASH) - add_executable(flathash ${FlatHash_SRCS}) -endif() - -if(FLATBUFFERS_BUILD_SHAREDLIB) - add_library(flatbuffers_shared SHARED ${FlatBuffers_Library_SRCS}) - - # Shared object version: "major.minor.micro" - # - micro updated every release when there is no API/ABI changes - # - minor updated when there are additions in API/ABI - # - major (ABI number) updated when there are changes in ABI (or removals) - set(FlatBuffers_Library_SONAME_MAJOR ${VERSION_MAJOR}) - set(FlatBuffers_Library_SONAME_FULL "${FlatBuffers_Library_SONAME_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}") - set_target_properties(flatbuffers_shared PROPERTIES OUTPUT_NAME flatbuffers - SOVERSION "${FlatBuffers_Library_SONAME_MAJOR}" - VERSION "${FlatBuffers_Library_SONAME_FULL}") - if(FLATBUFFERS_ENABLE_PCH) - add_pch_to_target(flatbuffers_shared include/flatbuffers/pch/pch.h) - endif() -endif() - -# Global list of generated files. -# Use the global property to be independent of PARENT_SCOPE. -set_property(GLOBAL PROPERTY FBS_GENERATED_OUTPUTS) - -function(get_generated_output generated_files) - get_property(tmp GLOBAL PROPERTY FBS_GENERATED_OUTPUTS) - set(${generated_files} ${tmp} PARENT_SCOPE) -endfunction(get_generated_output) - -function(register_generated_output file_name) - get_property(tmp GLOBAL PROPERTY FBS_GENERATED_OUTPUTS) - list(APPEND tmp ${file_name}) - set_property(GLOBAL PROPERTY FBS_GENERATED_OUTPUTS ${tmp}) -endfunction(register_generated_output) - -function(compile_flatbuffers_schema_to_cpp_opt SRC_FBS OPT) - if(FLATBUFFERS_BUILD_LEGACY) - set(OPT ${OPT};--cpp-std c++0x) - else() - # --cpp-std is defined by flatc default settings. - endif() - message(STATUS "`${SRC_FBS}`: add generation of C++ code with '${OPT}'") - get_filename_component(SRC_FBS_DIR ${SRC_FBS} PATH) - string(REGEX REPLACE "\\.fbs$" "_generated.h" GEN_HEADER ${SRC_FBS}) - add_custom_command( - OUTPUT ${GEN_HEADER} - COMMAND "${FLATBUFFERS_FLATC_EXECUTABLE}" - --cpp --gen-mutable --gen-object-api --reflect-names - --cpp-ptr-type flatbuffers::unique_ptr # Used to test with C++98 STLs - ${OPT} - -I "${CMAKE_CURRENT_SOURCE_DIR}/tests/include_test" - -o "${SRC_FBS_DIR}" - "${CMAKE_CURRENT_SOURCE_DIR}/${SRC_FBS}" - DEPENDS flatc - COMMENT "Run generation: '${GEN_HEADER}'") - register_generated_output(${GEN_HEADER}) -endfunction() - -function(compile_flatbuffers_schema_to_cpp SRC_FBS) - compile_flatbuffers_schema_to_cpp_opt(${SRC_FBS} "--no-includes;--gen-compare") -endfunction() - -function(compile_flatbuffers_schema_to_binary SRC_FBS) - message(STATUS "`${SRC_FBS}`: add generation of binary (.bfbs) schema") - get_filename_component(SRC_FBS_DIR ${SRC_FBS} PATH) - string(REGEX REPLACE "\\.fbs$" ".bfbs" GEN_BINARY_SCHEMA ${SRC_FBS}) - # For details about flags see generate_code.py - add_custom_command( - OUTPUT ${GEN_BINARY_SCHEMA} - COMMAND "${FLATBUFFERS_FLATC_EXECUTABLE}" - -b --schema --bfbs-comments --bfbs-builtins - --bfbs-filenames ${SRC_FBS_DIR} - -I "${CMAKE_CURRENT_SOURCE_DIR}/tests/include_test" - -o "${SRC_FBS_DIR}" - "${CMAKE_CURRENT_SOURCE_DIR}/${SRC_FBS}" - DEPENDS flatc - COMMENT "Run generation: '${GEN_BINARY_SCHEMA}'") - register_generated_output(${GEN_BINARY_SCHEMA}) -endfunction() - -function(compile_flatbuffers_schema_to_embedded_binary SRC_FBS OPT) - if(FLATBUFFERS_BUILD_LEGACY) - set(OPT ${OPT};--cpp-std c++0x) - else() - # --cpp-std is defined by flatc default settings. - endif() - message(STATUS "`${SRC_FBS}`: add generation of C++ embedded binary schema code with '${OPT}'") - get_filename_component(SRC_FBS_DIR ${SRC_FBS} PATH) - string(REGEX REPLACE "\\.fbs$" "_bfbs_generated.h" GEN_BFBS_HEADER ${SRC_FBS}) - # For details about flags see generate_code.py - add_custom_command( - OUTPUT ${GEN_BFBS_HEADER} - COMMAND "${FLATBUFFERS_FLATC_EXECUTABLE}" - --cpp --gen-mutable --gen-object-api --reflect-names - --cpp-ptr-type flatbuffers::unique_ptr # Used to test with C++98 STLs - ${OPT} - --bfbs-comments --bfbs-builtins --bfbs-gen-embed - --bfbs-filenames ${SRC_FBS_DIR} - -I "${CMAKE_CURRENT_SOURCE_DIR}/tests/include_test" - -o "${SRC_FBS_DIR}" - "${CMAKE_CURRENT_SOURCE_DIR}/${SRC_FBS}" - DEPENDS flatc - COMMENT "Run generation: '${GEN_BFBS_HEADER}'") - register_generated_output(${GEN_BFBS_HEADER}) -endfunction() - -# Look if we have python 3.5 installed so that we can run the generate code -# python script after flatc is built. -find_package(PythonInterp 3.5) - -if(PYTHONINTERP_FOUND AND - # Skip doing this if the MSVC version is below VS 12. - # https://cmake.org/cmake/help/latest/variable/MSVC_VERSION.html - (NOT MSVC OR MSVC_VERSION GREATER 1800)) - set(GENERATION_SCRIPT ${PYTHON_EXECUTABLE} scripts/generate_code.py) - if(FLATBUFFERS_BUILD_LEGACY) - # Need to set --cpp-std c++-0x options - set(GENERATION_SCRIPT ${GENERATION_SCRIPT} --cpp-0x) - endif() - if(FLATBUFFERS_SKIP_MONSTER_EXTRA) - set(GENERATION_SCRIPT ${GENERATION_SCRIPT} --skip-monster-extra) - endif() - add_custom_command( - TARGET flatc - POST_BUILD - COMMAND ${GENERATION_SCRIPT} --flatc "${FLATBUFFERS_FLATC_EXECUTABLE}" - WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" - COMMENT "Running ${GENERATION_SCRIPT}..." - VERBATIM) -else() - message("No Python3 interpreter found! Unable to generate files automatically.") -endif() - -if(FLATBUFFERS_BUILD_TESTS) - file(COPY "${CMAKE_CURRENT_SOURCE_DIR}/tests" DESTINATION "${CMAKE_CURRENT_BINARY_DIR}") - file(COPY "${CMAKE_CURRENT_SOURCE_DIR}/samples" DESTINATION "${CMAKE_CURRENT_BINARY_DIR}") - - # TODO Add (monster_test.fbs monsterdata_test.json)->monsterdata_test.mon - compile_flatbuffers_schema_to_cpp(tests/monster_test.fbs) - compile_flatbuffers_schema_to_binary(tests/monster_test.fbs) - compile_flatbuffers_schema_to_cpp_opt(tests/namespace_test/namespace_test1.fbs "--no-includes;--gen-compare;--gen-name-strings") - compile_flatbuffers_schema_to_cpp_opt(tests/namespace_test/namespace_test2.fbs "--no-includes;--gen-compare;--gen-name-strings") - compile_flatbuffers_schema_to_cpp_opt(tests/union_vector/union_vector.fbs "--no-includes;--gen-compare;--gen-name-strings") - compile_flatbuffers_schema_to_cpp(tests/optional_scalars.fbs) - compile_flatbuffers_schema_to_cpp_opt(tests/native_type_test.fbs "") - compile_flatbuffers_schema_to_cpp_opt(tests/arrays_test.fbs "--scoped-enums;--gen-compare") - compile_flatbuffers_schema_to_binary(tests/arrays_test.fbs) - compile_flatbuffers_schema_to_embedded_binary(tests/monster_test.fbs "--no-includes;--gen-compare") - if(NOT (MSVC AND (MSVC_VERSION LESS 1900))) - compile_flatbuffers_schema_to_cpp(tests/monster_extra.fbs) # Test floating-point NAN/INF. - endif() - include_directories(${CMAKE_CURRENT_BINARY_DIR}/tests) - add_executable(flattests ${FlatBuffers_Tests_SRCS}) - add_dependencies(flattests generated_code) - set_property(TARGET flattests - PROPERTY COMPILE_DEFINITIONS FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE - FLATBUFFERS_DEBUG_VERIFICATION_FAILURE=1) - if(FLATBUFFERS_CODE_SANITIZE) - add_fsanitize_to_target(flattests ${FLATBUFFERS_CODE_SANITIZE}) - endif() - - compile_flatbuffers_schema_to_cpp(samples/monster.fbs) - compile_flatbuffers_schema_to_binary(samples/monster.fbs) - include_directories(${CMAKE_CURRENT_BINARY_DIR}/samples) - add_executable(flatsamplebinary ${FlatBuffers_Sample_Binary_SRCS}) - add_dependencies(flatsamplebinary generated_code) - add_executable(flatsampletext ${FlatBuffers_Sample_Text_SRCS}) - add_dependencies(flatsampletext generated_code) - add_executable(flatsamplebfbs ${FlatBuffers_Sample_BFBS_SRCS}) - add_dependencies(flatsamplebfbs generated_code) - - if(FLATBUFFERS_BUILD_CPP17) - # Don't generate header for flattests_cpp17 target. - # This target uses "generated_cpp17/monster_test_generated.h" - # produced by direct call of generate_code.py script. - add_executable(flattests_cpp17 ${FlatBuffers_Tests_CPP17_SRCS}) - add_dependencies(flattests_cpp17 generated_code) - target_compile_features(flattests_cpp17 PRIVATE cxx_std_17) - target_compile_definitions(flattests_cpp17 PRIVATE - FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE - FLATBUFFERS_DEBUG_VERIFICATION_FAILURE=1 - ) - if(FLATBUFFERS_CODE_SANITIZE) - add_fsanitize_to_target(flattests_cpp17 ${FLATBUFFERS_CODE_SANITIZE}) - endif() - endif(FLATBUFFERS_BUILD_CPP17) -endif() - -if(FLATBUFFERS_BUILD_GRPCTEST) - if(CMAKE_COMPILER_IS_GNUCXX) - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unused-parameter -Wno-shadow") - endif() - if(NOT GRPC_INSTALL_PATH) - message(SEND_ERROR "GRPC_INSTALL_PATH variable is not defined. See grpc/README.md") - endif() - if(NOT PROTOBUF_DOWNLOAD_PATH) - message(SEND_ERROR "PROTOBUF_DOWNLOAD_PATH variable is not defined. See grpc/README.md") - endif() - INCLUDE_DIRECTORIES(${GRPC_INSTALL_PATH}/include) - INCLUDE_DIRECTORIES(${PROTOBUF_DOWNLOAD_PATH}/src) - find_package(Threads REQUIRED) - list(APPEND CMAKE_PREFIX_PATH ${GRPC_INSTALL_PATH}) - find_package(absl CONFIG REQUIRED) - find_package(protobuf CONFIG REQUIRED) - find_package(gRPC CONFIG REQUIRED) - add_executable(grpctest ${FlatBuffers_GRPCTest_SRCS}) - add_dependencies(grpctest generated_code) - target_link_libraries(grpctest PRIVATE gRPC::grpc++_unsecure gRPC::grpc_unsecure gRPC::gpr pthread dl) - if(FLATBUFFERS_CODE_SANITIZE AND NOT WIN32) - # GRPC test has problems with alignment and will fail under ASAN/UBSAN. - # add_fsanitize_to_target(grpctest ${FLATBUFFERS_CODE_SANITIZE}) - endif() -endif() - - -if(FLATBUFFERS_INSTALL) - include(GNUInstallDirs) - - install(DIRECTORY include/flatbuffers DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) - - set(FB_CMAKE_DIR "${CMAKE_INSTALL_LIBDIR}/cmake/flatbuffers") - - configure_file(CMake/flatbuffers-config-version.cmake.in flatbuffers-config-version.cmake @ONLY) - install( - FILES "CMake/flatbuffers-config.cmake" "${CMAKE_CURRENT_BINARY_DIR}/flatbuffers-config-version.cmake" - DESTINATION ${FB_CMAKE_DIR} - ) - - if(FLATBUFFERS_BUILD_FLATLIB) - if(CMAKE_VERSION VERSION_LESS 3.0) - install( - TARGETS flatbuffers EXPORT FlatBuffersTargets - ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} - ) - else() - install( - TARGETS flatbuffers EXPORT FlatBuffersTargets - ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} - INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} - ) - endif() - - install(EXPORT FlatBuffersTargets - FILE FlatBuffersTargets.cmake - NAMESPACE flatbuffers:: - DESTINATION ${FB_CMAKE_DIR} - ) - endif() - - if(FLATBUFFERS_BUILD_FLATC) - install( - TARGETS flatc EXPORT FlatcTargets - RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} - ) - - install( - EXPORT FlatcTargets - FILE FlatcTargets.cmake - NAMESPACE flatbuffers:: - DESTINATION ${FB_CMAKE_DIR} - ) - endif() - - if(FLATBUFFERS_BUILD_SHAREDLIB) - if(CMAKE_VERSION VERSION_LESS 3.0) - install( - TARGETS flatbuffers_shared EXPORT FlatBuffersSharedTargets - ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} - RUNTIME DESTINATION ${CMAKE_INSTALL_LIBDIR} - LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} - ) - else() - install( - TARGETS flatbuffers_shared EXPORT FlatBuffersSharedTargets - ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} - RUNTIME DESTINATION ${CMAKE_INSTALL_LIBDIR} - LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} - INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} - ) - endif() - - install( - EXPORT FlatBuffersSharedTargets - FILE FlatBuffersSharedTargets.cmake - NAMESPACE flatbuffers:: - DESTINATION ${FB_CMAKE_DIR} - ) - endif() - - if(FLATBUFFERS_BUILD_SHAREDLIB OR FLATBUFFERS_BUILD_FLATLIB) - configure_file(CMake/flatbuffers.pc.in flatbuffers.pc @ONLY) - install( - FILES "${CMAKE_CURRENT_BINARY_DIR}/flatbuffers.pc" - DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig - ) - endif() -endif() - -if(FLATBUFFERS_BUILD_TESTS) - enable_testing() - - add_test(NAME flattests COMMAND flattests) - if(FLATBUFFERS_BUILD_CPP17) - add_test(NAME flattests_cpp17 COMMAND flattests_cpp17) - endif() - if(FLATBUFFERS_BUILD_GRPCTEST) - add_test(NAME grpctest COMMAND grpctest) - endif() -endif() - -# This target is sync-barrier. -# Other generate-dependent targets can depend on 'generated_code' only. -get_generated_output(fbs_generated) -if(fbs_generated) - # message(STATUS "Add generated_code target with files:${fbs_generated}") - add_custom_target(generated_code - DEPENDS ${fbs_generated} - COMMENT "All generated files were updated.") -endif() - -include(CMake/BuildFlatBuffers.cmake) - -if(UNIX) - # Use of CPack only supported on Linux systems. - if(FLATBUFFERS_PACKAGE_DEBIAN) - include(CMake/PackageDebian.cmake) - include(CPack) - endif() - if (FLATBUFFERS_PACKAGE_REDHAT) - include(CMake/PackageRedhat.cmake) - include(CPack) - endif() -endif() - -# Include for running Google Benchmarks. -if(FLATBUFFERS_BUILD_BENCHMARKS AND CMAKE_VERSION VERSION_GREATER 3.13) - add_subdirectory(benchmarks) -endif() - -# Add FlatBuffers::FlatBuffers interface, needed for FetchContent_Declare -add_library(FlatBuffers INTERFACE) -add_library(FlatBuffers::FlatBuffers ALIAS FlatBuffers) -target_include_directories( - FlatBuffers - INTERFACE $ - $) diff --git a/CMake/PackageDebian.cmake b/CMake/PackageDebian.cmake index f587ff7ffe..d8692c63d2 100644 --- a/CMake/PackageDebian.cmake +++ b/CMake/PackageDebian.cmake @@ -17,23 +17,9 @@ if (UNIX) SET(CPACK_PACKAGE_VERSION "${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}-${VERSION_COMMIT}") SET(CPACK_DEBIAN_PACKAGE_VERSION "${CPACK_PACKAGE_VERSION}") - # Derive architecture - IF(NOT CPACK_DEBIAN_PACKAGE_ARCHITECTURE) - FIND_PROGRAM(DPKG_CMD dpkg) - IF(NOT DPKG_CMD) - MESSAGE(STATUS "Can not find dpkg in your path, default to i386.") - SET(CPACK_DEBIAN_PACKAGE_ARCHITECTURE i386) - ENDIF(NOT DPKG_CMD) - EXECUTE_PROCESS(COMMAND "${DPKG_CMD}" --print-architecture - OUTPUT_VARIABLE CPACK_DEBIAN_PACKAGE_ARCHITECTURE - OUTPUT_STRIP_TRAILING_WHITESPACE - ) - ENDIF(NOT CPACK_DEBIAN_PACKAGE_ARCHITECTURE) - # Package name SET(CPACK_DEBIAN_PACKAGE_NAME "flatbuffers") - SET(CPACK_RESOURCE_FILE_LICENSE ${CMAKE_SOURCE_DIR}/LICENSE.txt) - SET(CPACK_PACKAGE_FILE_NAME - "${CPACK_DEBIAN_PACKAGE_NAME}_${CPACK_DEBIAN_PACKAGE_VERSION}_${CPACK_DEBIAN_PACKAGE_ARCHITECTURE}") + SET(CPACK_RESOURCE_FILE_LICENSE ${CMAKE_SOURCE_DIR}/LICENSE) + set(CPACK_DEBIAN_FILE_NAME "DEB-DEFAULT") endif(UNIX) diff --git a/CMake/PackageRedhat.cmake b/CMake/PackageRedhat.cmake index 5b7c6fa4d0..34302882fb 100644 --- a/CMake/PackageRedhat.cmake +++ b/CMake/PackageRedhat.cmake @@ -15,14 +15,14 @@ if (UNIX) set(CPACK_RPM_PACKAGE_NAME "flatbuffers") - # Assume this is not a cross complation build. + # Assume this is not a cross compilation build. if(NOT CPACK_RPM_PACKAGE_ARCHITECTURE) set(CPACK_RPM_PACKAGE_ARCHITECTURE "${CMAKE_SYSTEM_PROCESSOR}") endif(NOT CPACK_RPM_PACKAGE_ARCHITECTURE) set(CPACK_RPM_PACKAGE_VENDOR "Google, Inc.") set(CPACK_RPM_PACKAGE_LICENSE "Apache 2.0") - set(CPACK_RESOURCE_FILE_LICENSE ${CMAKE_SOURCE_DIR}/LICENSE.txt) + set(CPACK_RESOURCE_FILE_LICENSE ${CMAKE_SOURCE_DIR}/LICENSE) set(CPACK_PACKAGE_DESCRIPTION_FILE ${CMAKE_SOURCE_DIR}/CMake/DESCRIPTION.txt) # This may reduce rpm compatiblity with very old systems. diff --git a/CMake/Version.cmake b/CMake/Version.cmake index a713f3413b..21f47f637b 100644 --- a/CMake/Version.cmake +++ b/CMake/Version.cmake @@ -1,37 +1,39 @@ -set(VERSION_MAJOR 22) -set(VERSION_MINOR 10) -set(VERSION_PATCH 26) +set(VERSION_MAJOR 25) +set(VERSION_MINOR 12) +set(VERSION_PATCH 19) set(VERSION_COMMIT 0) -find_program(GIT git) -if(GIT AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/.git") - execute_process( +if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/.git") + find_program(GIT git) + if(GIT) + execute_process( COMMAND ${GIT} describe --tags WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} OUTPUT_VARIABLE GIT_DESCRIBE_DIRTY OUTPUT_STRIP_TRAILING_WHITESPACE RESULT_VARIABLE GIT_DESCRIBE_RESULT - ) + ) - if(GIT_DESCRIBE_RESULT EQUAL 0) - # Test if the most recent Git tag matches the pattern "v..*" - if(GIT_DESCRIBE_DIRTY MATCHES "^v[0-9]+\\.[0-9]+\\.[0-9]+.*") - string(REGEX REPLACE "^v([0-9]+)\\..*" "\\1" VERSION_MAJOR "${GIT_DESCRIBE_DIRTY}") - string(REGEX REPLACE "^v[0-9]+\\.([0-9]+).*" "\\1" VERSION_MINOR "${GIT_DESCRIBE_DIRTY}") - string(REGEX REPLACE "^v[0-9]+\\.[0-9]+\\.([0-9]+).*" "\\1" VERSION_PATCH "${GIT_DESCRIBE_DIRTY}") - string(REGEX REPLACE "^v[0-9]+\\.[0-9]+\\.[0-9]+\\-([0-9]+).*" "\\1" VERSION_COMMIT "${GIT_DESCRIBE_DIRTY}") - # If the tag points to the commit, then only the tag is shown in "git describe" - if(VERSION_COMMIT STREQUAL GIT_DESCRIBE_DIRTY) - set(VERSION_COMMIT 0) + if(GIT_DESCRIBE_RESULT EQUAL 0) + # Test if the most recent Git tag matches the pattern "v..*" + if(GIT_DESCRIBE_DIRTY MATCHES "^v[0-9]+\\.[0-9]+\\.[0-9]+.*") + string(REGEX REPLACE "^v([0-9]+)\\..*" "\\1" VERSION_MAJOR "${GIT_DESCRIBE_DIRTY}") + string(REGEX REPLACE "^v[0-9]+\\.([0-9]+).*" "\\1" VERSION_MINOR "${GIT_DESCRIBE_DIRTY}") + string(REGEX REPLACE "^v[0-9]+\\.[0-9]+\\.([0-9]+).*" "\\1" VERSION_PATCH "${GIT_DESCRIBE_DIRTY}") + string(REGEX REPLACE "^v[0-9]+\\.[0-9]+\\.[0-9]+\\-([0-9]+).*" "\\1" VERSION_COMMIT "${GIT_DESCRIBE_DIRTY}") + # If the tag points to the commit, then only the tag is shown in "git describe" + if(VERSION_COMMIT STREQUAL GIT_DESCRIBE_DIRTY) + set(VERSION_COMMIT 0) + endif() + else() + message(WARNING "\"${GIT_DESCRIBE_DIRTY}\" does not match pattern v..-") endif() else() - message(WARNING "\"${GIT_DESCRIBE_DIRTY}\" does not match pattern v..-") + message(WARNING "git describe failed with exit code: ${GIT_DESCRIBE_RESULT}\nMake sure you cloned with tags or run 'git fetch --tags'.") endif() else() - message(WARNING "git describe failed with exit code: ${GIT_DESCRIBE_RESULT}") + message(WARNING "git is not found") endif() -else() - message(WARNING "git is not found") endif() message(STATUS "Proceeding with version: ${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}.${VERSION_COMMIT}") diff --git a/CMake/flatbuffers-config.cmake b/CMake/flatbuffers-config.cmake index 592fc79b61..0c32c2fe2b 100644 --- a/CMake/flatbuffers-config.cmake +++ b/CMake/flatbuffers-config.cmake @@ -1,3 +1,4 @@ include("${CMAKE_CURRENT_LIST_DIR}/FlatBuffersTargets.cmake" OPTIONAL) include("${CMAKE_CURRENT_LIST_DIR}/FlatcTargets.cmake" OPTIONAL) include("${CMAKE_CURRENT_LIST_DIR}/FlatBuffersSharedTargets.cmake" OPTIONAL) +include("${CMAKE_CURRENT_LIST_DIR}/BuildFlatBuffers.cmake" OPTIONAL) \ No newline at end of file diff --git a/CMakeLists.txt b/CMakeLists.txt index 395ac59e7c..7bf48e6aec 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,32 +1,12 @@ # This is the legacy minimum version flatbuffers supported for a while. -cmake_minimum_required(VERSION 2.8.12...3.22.1) - -# CMake version 3.16 is the 'de-facto' minimum version for flatbuffers. If the -# current cmake is older than this, warn the user and include the legacy file to -# provide some level of support. -if(CMAKE_VERSION VERSION_LESS 3.16) - message(WARNING "Using cmake version ${CMAKE_VERSION} which is older than " - "our target version of 3.16. This will use the legacy CMakeLists.txt that " - "supports version 2.8.12 and higher, but not actively maintained. Consider " - "upgrading cmake to a newer version, as this may become a fatal error in the " - "future.") - # Use the legacy version of CMakeLists.txt - include(CMake/CMakeLists_legacy.cmake.in) - return() -endif() +cmake_minimum_required(VERSION 3.8...3.25.2) # Attempt to read the current version of flatbuffers by looking at the latest tag. include(CMake/Version.cmake) -if (POLICY CMP0048) - cmake_policy(SET CMP0048 NEW) - project(FlatBuffers - DESCRIPTION "Flatbuffers serialization library" +project(FlatBuffers VERSION ${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH} LANGUAGES CXX) -else() - project(FlatBuffers) -endif (POLICY CMP0048) # generate compile_commands.json set(CMAKE_EXPORT_COMPILE_COMMANDS ON) @@ -41,7 +21,7 @@ option(FLATBUFFERS_BUILD_FLATC "Enable the build of the flatbuffers compiler" ON) option(FLATBUFFERS_STATIC_FLATC "Build flatbuffers compiler with -static flag" OFF) -option(FLATBUFFERS_BUILD_FLATHASH "Enable the build of flathash" ON) +option(FLATBUFFERS_BUILD_FLATHASH "Enable the build of flathash" OFF) option(FLATBUFFERS_BUILD_BENCHMARKS "Enable the build of flatbenchmark." OFF) option(FLATBUFFERS_BUILD_GRPCTEST "Enable the build of grpctest" OFF) @@ -71,10 +51,10 @@ option(FLATBUFFERS_ENABLE_PCH Only work if CMake supports 'target_precompile_headers'. \" This can speed up compilation time." OFF) -option(FLATBUFFERS_SKIP_MONSTER_EXTRA +option(FLATBUFFERS_SKIP_MONSTER_EXTRA "Skip generating monster_extra.fbs that contains non-supported numerical\" types." OFF) -option(FLATBUFFERS_STRICT_MODE +option(FLATBUFFERS_STRICT_MODE "Build flatbuffers with all warnings as errors (-Werror or /WX)." OFF) @@ -87,6 +67,12 @@ if(MSVC OR CMAKE_CXX_COMPILER_FRONTEND_VARIANT STREQUAL "MSVC") set(MSVC_LIKE ON) endif() +if(CMAKE_CXX_COMPILER_ID MATCHES "Clang") + set(IS_CLANG ON) +else() + set(IS_CLANG OFF) +endif() + if(DEFINED FLATBUFFERS_COMPILATION_TIMINGS) message("Recording Compilation Timings to ${FLATBUFFERS_COMPILATION_TIMINGS}") file(REMOVE ${FLATBUFFERS_COMPILATION_TIMINGS}) @@ -126,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) @@ -136,11 +123,12 @@ set(FlatBuffers_Library_SRCS include/flatbuffers/allocator.h include/flatbuffers/array.h include/flatbuffers/base.h - include/flatbuffers/bfbs_generator.h include/flatbuffers/buffer.h include/flatbuffers/buffer_ref.h include/flatbuffers/default_allocator.h include/flatbuffers/detached_buffer.h + include/flatbuffers/code_generator.h + include/flatbuffers/file_manager.h include/flatbuffers/flatbuffer_builder.h include/flatbuffers/flatbuffers.h include/flatbuffers/flexbuffers.h @@ -159,6 +147,8 @@ set(FlatBuffers_Library_SRCS include/flatbuffers/vector.h include/flatbuffers/vector_downward.h include/flatbuffers/verifier.h + src/file_manager.cpp + src/file_name_manager.cpp src/idl_parser.cpp src/idl_gen_text.cpp src/reflection.cpp @@ -167,17 +157,19 @@ set(FlatBuffers_Library_SRCS set(FlatBuffers_Compiler_SRCS ${FlatBuffers_Library_SRCS} + src/idl_gen_binary.cpp + src/idl_gen_text.cpp src/idl_gen_cpp.cpp src/idl_gen_csharp.cpp src/idl_gen_dart.cpp src/idl_gen_kotlin.cpp + src/idl_gen_kotlin_kmp.cpp src/idl_gen_go.cpp src/idl_gen_java.cpp src/idl_gen_ts.cpp src/idl_gen_php.cpp src/idl_gen_python.cpp src/idl_gen_lobster.cpp - src/idl_gen_lua.cpp src/idl_gen_rust.cpp src/idl_gen_fbs.cpp src/idl_gen_grpc.cpp @@ -191,6 +183,10 @@ set(FlatBuffers_Compiler_SRCS src/bfbs_gen_lua.h src/bfbs_gen_nim.h src/bfbs_namer.h + include/codegen/idl_namer.h + include/codegen/namer.h + include/codegen/python.h + include/codegen/python.cc include/flatbuffers/code_generators.h src/binary_annotator.h src/binary_annotator.cpp @@ -222,10 +218,13 @@ set(FlatHash_SRCS set(FlatBuffers_Tests_SRCS ${FlatBuffers_Library_SRCS} src/idl_gen_fbs.cpp + tests/default_vectors_strings_test.cpp + tests/default_vectors_strings_test.h tests/evolution_test.cpp tests/flexbuffers_test.cpp tests/fuzz_test.cpp tests/json_test.cpp + tests/key_field_test.cpp tests/monster_test.cpp tests/optional_scalars_test.cpp tests/parser_test.cpp @@ -237,33 +236,16 @@ set(FlatBuffers_Tests_SRCS tests/test_builder.h tests/test_builder.cpp tests/util_test.cpp + tests/vector_table_naked_ptr_test.h + tests/vector_table_naked_ptr_test.cpp tests/native_type_test_impl.h tests/native_type_test_impl.cpp tests/alignment_test.h tests/alignment_test.cpp + tests/64bit/offset64_test.h + tests/64bit/offset64_test.cpp include/flatbuffers/code_generators.h src/code_generators.cpp - # file generate by running compiler on tests/monster_test.fbs - ${CMAKE_CURRENT_BINARY_DIR}/tests/monster_test_generated.h - # file generate by running compiler on namespace_test/namespace_test1.fbs - ${CMAKE_CURRENT_BINARY_DIR}/tests/namespace_test/namespace_test1_generated.h - ${CMAKE_CURRENT_BINARY_DIR}/tests/namespace_test/namespace_test2_generated.h - # file generate by running compiler on union_vector/union_vector.fbs - ${CMAKE_CURRENT_BINARY_DIR}/tests/union_vector/union_vector_generated.h - # file generate by running compiler on tests/arrays_test.fbs - ${CMAKE_CURRENT_BINARY_DIR}/tests/arrays_test_generated.h - # file generate by running compiler on tests/native_type_test.fbs - ${CMAKE_CURRENT_BINARY_DIR}/tests/native_type_test_generated.h - # file generate by running compiler on tests/monster_extra.fbs - ${CMAKE_CURRENT_BINARY_DIR}/tests/monster_extra_generated.h - # file generate by running compiler on tests/monster_test.fbs - ${CMAKE_CURRENT_BINARY_DIR}/tests/monster_test_bfbs_generated.h - # file generate by running compiler on tests/optional_scalars.fbs - ${CMAKE_CURRENT_BINARY_DIR}/tests/optional_scalars_generated.h - # file generate by running compiler on tests/native_inline_table_test.fbs - ${CMAKE_CURRENT_BINARY_DIR}/tests/native_inline_table_test_generated.h - # file generate by running compiler on tests/alignment_test.fbs - ${CMAKE_CURRENT_BINARY_DIR}/tests/alignment_test_generated.h ) set(FlatBuffers_Tests_CPP17_SRCS @@ -271,32 +253,20 @@ set(FlatBuffers_Tests_CPP17_SRCS tests/test_assert.h tests/test_assert.cpp tests/cpp17/test_cpp17.cpp - # file generate by running compiler on tests/monster_test.fbs - ${CMAKE_CURRENT_BINARY_DIR}/tests/cpp17/generated_cpp17/monster_test_generated.h - ${CMAKE_CURRENT_BINARY_DIR}/tests/monster_test_generated.h - ${CMAKE_CURRENT_BINARY_DIR}/tests/cpp17/generated_cpp17/optional_scalars_generated.h - ${CMAKE_CURRENT_BINARY_DIR}/tests/optional_scalars_generated.h ) set(FlatBuffers_Sample_Binary_SRCS - include/flatbuffers/flatbuffers.h samples/sample_binary.cpp - # file generated by running compiler on samples/monster.fbs - ${CMAKE_CURRENT_BINARY_DIR}/samples/monster_generated.h ) set(FlatBuffers_Sample_Text_SRCS ${FlatBuffers_Library_SRCS} samples/sample_text.cpp - # file generated by running compiler on samples/monster.fbs - ${CMAKE_CURRENT_BINARY_DIR}/samples/monster_generated.h ) set(FlatBuffers_Sample_BFBS_SRCS ${FlatBuffers_Library_SRCS} samples/sample_bfbs.cpp - # file generated by running compiler on samples/monster.fbs - ${CMAKE_CURRENT_BINARY_DIR}/samples/monster_generated.h ) set(FlatBuffers_GRPCTest_SRCS @@ -312,14 +282,14 @@ set(FlatBuffers_GRPCTest_SRCS tests/test_builder.cpp grpc/tests/grpctest.cpp grpc/tests/message_builder_test.cpp - # file generate by running compiler on tests/monster_test.fbs - ${CMAKE_CURRENT_BINARY_DIR}/tests/monster_test_generated.h + 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 # https://stackoverflow.com/questions/71772330/override-target-compile-options-via-cmake-command-line. # Append FLATBUFFERS_CXX_FLAGS to CMAKE_CXX_FLAGS. -if(DEFINED FLATBUFFERS_CXX_FLAGS AND NOT EXISTS "${CMAKE_TOOLCHAIN_FILE}") +if(DEFINED FLATBUFFERS_CXX_FLAGS) message(STATUS "extend CXX_FLAGS with ${FLATBUFFERS_CXX_FLAGS}") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${FLATBUFFERS_CXX_FLAGS}") endif() @@ -332,9 +302,7 @@ function(add_fsanitize_to_target _target _sanitizer) else() # FLATBUFFERS_CODE_SANITIZE: boolean {ON,OFF,YES,NO} or string with list of sanitizer. # List of sanitizer is string starts with '=': "=address,undefined,thread,memory". - if((${CMAKE_CXX_COMPILER_ID} MATCHES "Clang") OR - ((${CMAKE_CXX_COMPILER_ID} MATCHES "GNU") AND NOT (CMAKE_CXX_COMPILER_VERSION VERSION_LESS "4.9")) - ) + if(IS_CLANG OR (CMAKE_COMPILER_IS_GNUCXX AND CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 4.9)) set(_sanitizer_flags "=address,undefined") if(_sanitizer MATCHES "=.*") # override default by user-defined sanitizer list @@ -345,13 +313,14 @@ function(add_fsanitize_to_target _target _sanitizer) "-fsanitize${_sanitizer_flags}") target_link_libraries(${_target} PRIVATE "-fsanitize${_sanitizer_flags}") - set_property(TARGET ${_target} PROPERTY POSITION_INDEPENDENT_CODE ON) + set_target_properties(${_target} PROPERTIES POSITION_INDEPENDENT_CODE ON) message(STATUS "Sanitizer ${_sanitizer_flags} added to ${_target}") endif() endif() endfunction() function(add_pch_to_target _target _pch_header) + # the command is available since cmake 3.16 if(COMMAND target_precompile_headers) target_precompile_headers(${_target} PRIVATE ${_pch_header}) if(NOT MSVC) @@ -365,8 +334,8 @@ include_directories(grpc) # Creates an interface library that stores the configuration settings that each # target links too. This is a compromise between setting configuration globally -# with add_compile_options() and the more targetted target_compile_options(). -# This way each target in this file can share settings and override them if +# with add_compile_options() and the more targetted target_compile_options(). +# This way each target in this file can share settings and override them if # needed. add_library(ProjectConfig INTERFACE) target_compile_features(ProjectConfig @@ -382,7 +351,7 @@ set(CMAKE_CXX_EXTENSIONS OFF) if(MSVC_LIKE) target_compile_options(ProjectConfig - INTERFACE + INTERFACE /W4 $<$: /WX # Treat all compiler warnings as errors @@ -395,11 +364,6 @@ if(MSVC_LIKE) > ) else() - if("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang") - set(IS_CLANG ON) - else() - set(IS_CLANG OFF) - endif() target_compile_options(ProjectConfig INTERFACE -Wall @@ -414,8 +378,8 @@ else() -Wno-error=stringop-overflow > > - -pedantic - -Wextra + -pedantic + -Wextra -Wno-unused-parameter -Wold-style-cast -fsigned-char @@ -423,13 +387,14 @@ else() # This isn't working for some reason: $<$: $<$: + -Wnewline-eof -Wno-unknown-warning-option -Wmissing-declarations -Wzero-as-null-pointer-constant $<$,3.8>: -Wimplicit-fallthrough -Wextra-semi - $<$: + $<$: -Werror=unused-private-field > > @@ -438,7 +403,7 @@ else() $<$: $<$,4.4>: -Wunused-result - -Wunused-parameter + -Wunused-parameter -Werror=unused-parameter -Wmissing-declarations > @@ -446,7 +411,7 @@ else() -Wzero-as-null-pointer-constant > $<$,7.0>: - -faligned-new + -faligned-new $<$: -Werror=implicit-fallthrough=2 > @@ -476,7 +441,7 @@ if(FLATBUFFERS_BUILD_FLATLIB) add_library(flatbuffers STATIC ${FlatBuffers_Library_SRCS}) # Attach header directory for when build via add_subdirectory(). - target_include_directories(flatbuffers + target_include_directories(flatbuffers INTERFACE $ ) @@ -494,8 +459,8 @@ if(FLATBUFFERS_BUILD_FLATC) endif() target_link_libraries(flatc PRIVATE $) - target_compile_options(flatc - PUBLIC + target_compile_options(flatc + PRIVATE $<$,$>: /MT > @@ -520,159 +485,111 @@ endif() if(FLATBUFFERS_BUILD_SHAREDLIB) add_library(flatbuffers_shared SHARED ${FlatBuffers_Library_SRCS}) target_link_libraries(flatbuffers_shared PRIVATE $) - # Shared object version: "major.minor.micro" - # - micro updated every release when there is no API/ABI changes - # - minor updated when there are additions in API/ABI - # - major (ABI number) updated when there are changes in ABI (or removals) - set(FlatBuffers_Library_SONAME_MAJOR ${VERSION_MAJOR}) - set(FlatBuffers_Library_SONAME_FULL "${FlatBuffers_Library_SONAME_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}") - set_target_properties(flatbuffers_shared PROPERTIES OUTPUT_NAME flatbuffers - SOVERSION "${FlatBuffers_Library_SONAME_MAJOR}" + # FlatBuffers use calendar-based versioning and do not provide any ABI + # stability guarantees. Therefore, always use the full version as SOVERSION + # in order to avoid breaking reverse dependencies on upgrades. + set(FlatBuffers_Library_SONAME_FULL "${PROJECT_VERSION}") + set_target_properties(flatbuffers_shared PROPERTIES + OUTPUT_NAME flatbuffers + SOVERSION "${FlatBuffers_Library_SONAME_FULL}" VERSION "${FlatBuffers_Library_SONAME_FULL}") if(FLATBUFFERS_ENABLE_PCH) add_pch_to_target(flatbuffers_shared include/flatbuffers/pch/pch.h) endif() endif() -# Global list of generated files. -# Use the global property to be independent of PARENT_SCOPE. -set_property(GLOBAL PROPERTY FBS_GENERATED_OUTPUTS) - -function(get_generated_output generated_files) - get_property(tmp GLOBAL PROPERTY FBS_GENERATED_OUTPUTS) - set(${generated_files} ${tmp} PARENT_SCOPE) -endfunction(get_generated_output) - -function(register_generated_output file_name) - get_property(tmp GLOBAL PROPERTY FBS_GENERATED_OUTPUTS) - list(APPEND tmp ${file_name}) - set_property(GLOBAL PROPERTY FBS_GENERATED_OUTPUTS ${tmp}) -endfunction(register_generated_output) - -function(compile_flatbuffers_schema_to_cpp_opt SRC_FBS OPT) - if(FLATBUFFERS_BUILD_LEGACY) - set(OPT ${OPT};--cpp-std c++0x) - else() - # --cpp-std is defined by flatc default settings. - endif() - message(STATUS "`${SRC_FBS}`: add generation of C++ code with '${OPT}'") +function(compile_schema SRC_FBS OPT SUFFIX OUT_GEN_FILE) get_filename_component(SRC_FBS_DIR ${SRC_FBS} PATH) - string(REGEX REPLACE "\\.fbs$" "_generated.h" GEN_HEADER ${SRC_FBS}) + string(REGEX REPLACE "\\.fbs$" "${SUFFIX}.h" GEN_HEADER ${SRC_FBS}) add_custom_command( OUTPUT ${GEN_HEADER} COMMAND "${FLATBUFFERS_FLATC_EXECUTABLE}" - --cpp --gen-mutable --gen-object-api --reflect-names - --cpp-ptr-type flatbuffers::unique_ptr # Used to test with C++98 STLs - ${OPT} - -I "${CMAKE_CURRENT_SOURCE_DIR}/tests/include_test" - -o "${SRC_FBS_DIR}" - "${CMAKE_CURRENT_SOURCE_DIR}/${SRC_FBS}" - DEPENDS flatc - COMMENT "Run generation: '${GEN_HEADER}'") - register_generated_output(${GEN_HEADER}) + ${OPT} + --filename-suffix ${SUFFIX} + -o "${SRC_FBS_DIR}" + "${CMAKE_CURRENT_SOURCE_DIR}/${SRC_FBS}" + DEPENDS flatc ${SRC_FBS} + COMMENT "flatc generation: `${SRC_FBS}` -> `${GEN_HEADER}`" + ) + set(${OUT_GEN_FILE} ${GEN_HEADER} PARENT_SCOPE) endfunction() -function(compile_flatbuffers_schema_to_cpp SRC_FBS) - compile_flatbuffers_schema_to_cpp_opt(${SRC_FBS} "--no-includes;--gen-compare") +function(compile_schema_for_test SRC_FBS OPT) + compile_schema("${SRC_FBS}" "${OPT}" "_generated" GEN_FILE) + target_sources(flattests PRIVATE ${GEN_FILE}) endfunction() -function(compile_flatbuffers_schema_to_binary SRC_FBS) - message(STATUS "`${SRC_FBS}`: add generation of binary (.bfbs) schema") - get_filename_component(SRC_FBS_DIR ${SRC_FBS} PATH) - string(REGEX REPLACE "\\.fbs$" ".bfbs" GEN_BINARY_SCHEMA ${SRC_FBS}) - # For details about flags see generate_code.py - add_custom_command( - OUTPUT ${GEN_BINARY_SCHEMA} - COMMAND "${FLATBUFFERS_FLATC_EXECUTABLE}" - -b --schema --bfbs-comments --bfbs-builtins - --bfbs-filenames ${SRC_FBS_DIR} - -I "${CMAKE_CURRENT_SOURCE_DIR}/tests/include_test" - -o "${SRC_FBS_DIR}" - "${CMAKE_CURRENT_SOURCE_DIR}/${SRC_FBS}" - DEPENDS flatc - COMMENT "Run generation: '${GEN_BINARY_SCHEMA}'") - register_generated_output(${GEN_BINARY_SCHEMA}) +function(compile_schema_for_test_fbsh SRC_FBS OPT) + compile_schema("${SRC_FBS}" "${OPT}" ".fbs" GEN_FILE) + target_sources(flattests PRIVATE ${GEN_FILE}) endfunction() -function(compile_flatbuffers_schema_to_embedded_binary SRC_FBS OPT) - if(FLATBUFFERS_BUILD_LEGACY) - set(OPT ${OPT};--cpp-std c++0x) - else() - # --cpp-std is defined by flatc default settings. - endif() - message(STATUS "`${SRC_FBS}`: add generation of C++ embedded binary schema code with '${OPT}'") - get_filename_component(SRC_FBS_DIR ${SRC_FBS} PATH) - string(REGEX REPLACE "\\.fbs$" "_bfbs_generated.h" GEN_BFBS_HEADER ${SRC_FBS}) - # For details about flags see generate_code.py - add_custom_command( - OUTPUT ${GEN_BFBS_HEADER} - COMMAND "${FLATBUFFERS_FLATC_EXECUTABLE}" - --cpp --gen-mutable --gen-object-api --reflect-names - --cpp-ptr-type flatbuffers::unique_ptr # Used to test with C++98 STLs - ${OPT} - --bfbs-comments --bfbs-builtins --bfbs-gen-embed - --bfbs-filenames ${SRC_FBS_DIR} - -I "${CMAKE_CURRENT_SOURCE_DIR}/tests/include_test" - -o "${SRC_FBS_DIR}" - "${CMAKE_CURRENT_SOURCE_DIR}/${SRC_FBS}" - DEPENDS flatc - COMMENT "Run generation: '${GEN_BFBS_HEADER}'") - register_generated_output(${GEN_BFBS_HEADER}) +function(compile_schema_for_samples SRC_FBS OPT) + compile_schema("${SRC_FBS}" "${OPT}" "_generated" GEN_FILE) + target_sources(flatsample PRIVATE ${GEN_FILE}) endfunction() if(FLATBUFFERS_BUILD_TESTS) - file(COPY "${CMAKE_CURRENT_SOURCE_DIR}/tests" DESTINATION "${CMAKE_CURRENT_BINARY_DIR}") - file(COPY "${CMAKE_CURRENT_SOURCE_DIR}/samples" DESTINATION "${CMAKE_CURRENT_BINARY_DIR}") - - # TODO Add (monster_test.fbs monsterdata_test.json)->monsterdata_test.mon - compile_flatbuffers_schema_to_cpp(tests/monster_test.fbs) - compile_flatbuffers_schema_to_binary(tests/monster_test.fbs) - compile_flatbuffers_schema_to_cpp_opt(tests/namespace_test/namespace_test1.fbs "--no-includes;--gen-compare;--gen-name-strings") - compile_flatbuffers_schema_to_cpp_opt(tests/namespace_test/namespace_test2.fbs "--no-includes;--gen-compare;--gen-name-strings") - compile_flatbuffers_schema_to_cpp_opt(tests/union_vector/union_vector.fbs "--no-includes;--gen-compare;--gen-name-strings") - compile_flatbuffers_schema_to_cpp(tests/optional_scalars.fbs) - compile_flatbuffers_schema_to_cpp_opt(tests/native_type_test.fbs "") - compile_flatbuffers_schema_to_cpp_opt(tests/arrays_test.fbs "--scoped-enums;--gen-compare") - compile_flatbuffers_schema_to_binary(tests/arrays_test.fbs) - compile_flatbuffers_schema_to_embedded_binary(tests/monster_test.fbs "--no-includes;--gen-compare") - compile_flatbuffers_schema_to_cpp(tests/native_inline_table_test.fbs "--gen-compare") - compile_flatbuffers_schema_to_cpp(tests/alignment_test.fbs "--gen-compare") - if(NOT (MSVC AND (MSVC_VERSION LESS 1900))) - compile_flatbuffers_schema_to_cpp(tests/monster_extra.fbs) # Test floating-point NAN/INF. - endif() - include_directories(${CMAKE_CURRENT_BINARY_DIR}/tests) add_executable(flattests ${FlatBuffers_Tests_SRCS}) target_link_libraries(flattests PRIVATE $) + target_include_directories(flattests PUBLIC + # Ideally everything is fully qualified from the root directories + ${CMAKE_CURRENT_SOURCE_DIR} + ${CMAKE_CURRENT_BINARY_DIR} + # TODO(derekbailey): update includes to fully qualify src/ and tests/ + src + tests + ${CMAKE_CURRENT_BINARY_DIR}/tests + ) + + # Have tests load data from the source directory, not the build directory. + add_definitions(-DFLATBUFFERS_TEST_PATH_PREFIX=${CMAKE_CURRENT_SOURCE_DIR}/) - add_dependencies(flattests generated_code) + # The flattest target needs some generated files + SET(FLATC_OPT_COMP --cpp --gen-compare --gen-mutable --gen-object-api --reflect-names) + SET(FLATC_OPT_SCOPED_ENUMS ${FLATC_OPT_COMP};--scoped-enums) + + compile_schema_for_test(tests/alignment_test.fbs "${FLATC_OPT_COMP}") + compile_schema_for_test_fbsh(tests/default_vectors_strings_test.fbs "${FLATC_OPT_COMP}") + compile_schema_for_test(tests/arrays_test.fbs "${FLATC_OPT_SCOPED_ENUMS}") + compile_schema_for_test(tests/native_inline_table_test.fbs "${FLATC_OPT_COMP}") + compile_schema_for_test(tests/native_type_test.fbs "${FLATC_OPT_COMP}") + compile_schema_for_test(tests/key_field/key_field_sample.fbs "${FLATC_OPT_COMP}") + compile_schema_for_test(tests/64bit/test_64bit.fbs "${FLATC_OPT_COMP};--bfbs-gen-embed") + compile_schema_for_test(tests/64bit/evolution/v1.fbs "${FLATC_OPT_COMP}") + compile_schema_for_test(tests/64bit/evolution/v2.fbs "${FLATC_OPT_COMP}") + compile_schema_for_test(tests/union_underlying_type_test.fbs "${FLATC_OPT_SCOPED_ENUMS}") if(FLATBUFFERS_CODE_SANITIZE) add_fsanitize_to_target(flattests ${FLATBUFFERS_CODE_SANITIZE}) endif() - - compile_flatbuffers_schema_to_cpp(samples/monster.fbs) - compile_flatbuffers_schema_to_binary(samples/monster.fbs) + include_directories(${CMAKE_CURRENT_BINARY_DIR}/samples) add_executable(flatsamplebinary ${FlatBuffers_Sample_Binary_SRCS}) - target_link_libraries(flatsamplebinary PRIVATE $) - add_dependencies(flatsamplebinary generated_code) - add_executable(flatsampletext ${FlatBuffers_Sample_Text_SRCS}) - target_link_libraries(flatsampletext PRIVATE $) - add_dependencies(flatsampletext generated_code) - add_executable(flatsamplebfbs ${FlatBuffers_Sample_BFBS_SRCS}) - target_link_libraries(flatsamplebfbs PRIVATE $) - add_dependencies(flatsamplebfbs generated_code) + + # Add a library so there is a single target that the generated samples can + # link too. + if(MSVC OR ${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.20.0") + add_library(flatsample INTERFACE) + else() + add_library(flatsample STATIC) + endif() + + # Since flatsample has no sources, we have to explicitly set the linker lang. + set_target_properties(flatsample PROPERTIES LINKER_LANGUAGE CXX) + + target_link_libraries(flatsamplebinary PRIVATE $ flatsample) + target_link_libraries(flatsampletext PRIVATE $ flatsample) + target_link_libraries(flatsamplebfbs PRIVATE $ flatsample) if(FLATBUFFERS_BUILD_CPP17) - # Don't generate header for flattests_cpp17 target. - # This target uses "generated_cpp17/monster_test_generated.h" add_executable(flattests_cpp17 ${FlatBuffers_Tests_CPP17_SRCS}) - add_dependencies(flattests_cpp17 generated_code) target_link_libraries(flattests_cpp17 PRIVATE $) - target_compile_features(flattests_cpp17 PRIVATE cxx_std_17) + target_include_directories(flattests_cpp17 PUBLIC src tests) + target_compile_features(flattests_cpp17 PRIVATE cxx_std_17) # requires cmake 3.8 if(FLATBUFFERS_CODE_SANITIZE) add_fsanitize_to_target(flattests_cpp17 ${FLATBUFFERS_CODE_SANITIZE}) @@ -695,14 +612,13 @@ if(FLATBUFFERS_BUILD_GRPCTEST) find_package(protobuf CONFIG REQUIRED) find_package(gRPC CONFIG REQUIRED) add_executable(grpctest ${FlatBuffers_GRPCTest_SRCS}) - add_dependencies(grpctest generated_code) - target_link_libraries(grpctext - PRIVATE + target_link_libraries(grpctest + PRIVATE $ - gRPC::grpc++_unsecure - gRPC::gpr + gRPC::grpc++_unsecure + gRPC::gpr pthread - dl + dl ) endif() @@ -715,8 +631,8 @@ if(FLATBUFFERS_INSTALL) configure_file(CMake/flatbuffers-config-version.cmake.in flatbuffers-config-version.cmake @ONLY) install( - FILES - "CMake/flatbuffers-config.cmake" + FILES + "CMake/flatbuffers-config.cmake" "CMake/BuildFlatBuffers.cmake" "${CMAKE_CURRENT_BINARY_DIR}/flatbuffers-config-version.cmake" DESTINATION ${FB_CMAKE_DIR} @@ -788,16 +704,6 @@ if(FLATBUFFERS_BUILD_TESTS) endif() endif() -# This target is sync-barrier. -# Other generate-dependent targets can depend on 'generated_code' only. -get_generated_output(fbs_generated) -if(fbs_generated) - # message(STATUS "Add generated_code target with files:${fbs_generated}") - add_custom_target(generated_code - DEPENDS ${fbs_generated} - COMMENT "All generated files were updated.") -endif() - include(CMake/BuildFlatBuffers.cmake) if(UNIX) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 17428add54..4353a6c075 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -30,7 +30,7 @@ Some tips for good pull requests: * Write a descriptive commit message. What problem are you solving and what are the consequences? Where and what did you test? Some good tips: [here](http://robots.thoughtbot.com/5-useful-tips-for-a-better-commit-message) - and [here](https://www.kernel.org/doc/Documentation/SubmittingPatches). + and [here](https://www.kernel.org/doc/Documentation/process/submitting-patches.rst). * If your PR consists of multiple commits which are successive improvements / fixes to your first commit, consider squashing them into a single commit (`git rebase -i`) such that your PR is a single commit on top of the current @@ -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 2a39138fee..2935444bda 100644 --- a/FlatBuffers.podspec +++ b/FlatBuffers.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = 'FlatBuffers' - s.version = '22.10.26' + s.version = '25.12.19' s.summary = 'FlatBuffers: Memory Efficient Serialization Library' s.description = "FlatBuffers is a cross platform serialization library architected for @@ -10,12 +10,15 @@ Pod::Spec.new do |s| s.homepage = 'https://github.com/google/flatbuffers' s.license = { :type => 'Apache2.0', :file => 'LICENSE' } - s.author = { 'mustii' => 'mustii@mmk.one' } - s.source = { :git => 'https://github.com/google/flatbuffers.git', :tag => s.version.to_s, :submodules => true } + s.author = { 'mustii' => 'me@mustiikhalil.se' } + s.source = { :git => 'https://github.com/google/flatbuffers.git', :tag => "v" + s.version.to_s, :submodules => true } s.ios.deployment_target = '11.0' s.osx.deployment_target = '10.14' - s.swift_version = '5.0' + s.swift_version = '5.10' s.source_files = 'swift/Sources/Flatbuffers/*.swift' + s.pod_target_xcconfig = { + 'BUILD_LIBRARY_FOR_DISTRIBUTION' => 'YES' + } end diff --git a/Formatters.md b/Formatters.md index 877c5f2010..86ae5016ce 100644 --- a/Formatters.md +++ b/Formatters.md @@ -19,4 +19,4 @@ Swift uses swiftformat as it's formatter. Take a look at [how to install here](h ## Typescript -Typescript uses eslint as it's linter. Take a look at [how to install here](https://eslint.org/docs/user-guide/getting-started). Run the following command `eslint ts/** --ext .ts` in the root directory of the project \ No newline at end of file +Typescript uses eslint as it's linter. Take a look at [how to install here](https://eslint.org/docs/user-guide/getting-started). Run the following command `eslint ts/** --ext .ts` in the root directory of the project diff --git a/LICENSE.txt b/LICENSE similarity index 100% rename from LICENSE.txt rename to LICENSE diff --git a/MODULE.bazel b/MODULE.bazel new file mode 100644 index 0000000000..cc9a5c69a7 --- /dev/null +++ b/MODULE.bazel @@ -0,0 +1,77 @@ +module( + name = "flatbuffers", + version = "25.12.19", + compatibility_level = 1, + repo_name = "com_github_google_flatbuffers", +) + +bazel_dep( + name = "aspect_bazel_lib", + version = "2.11.0", +) +bazel_dep( + name = "aspect_rules_esbuild", + version = "0.21.0", +) +bazel_dep( + name = "aspect_rules_js", + version = "2.3.8", +) +bazel_dep( + name = "aspect_rules_ts", + version = "3.6.0", +) +bazel_dep( + name = "grpc", + version = "1.70.1", + repo_name = "com_github_grpc_grpc", +) +bazel_dep( + name = "platforms", + version = "0.0.10", +) +bazel_dep( + name = "rules_cc", + version = "0.0.16", +) +bazel_dep( + name = "rules_go", + version = "0.50.1", + repo_name = "io_bazel_rules_go", +) +bazel_dep( + name = "rules_nodejs", + version = "6.3.3", +) +bazel_dep( + name = "rules_shell", + version = "0.3.0", +) +bazel_dep( + name = "rules_swift", + version = "2.1.1", + repo_name = "build_bazel_rules_swift", +) +bazel_dep( + name = "bazel_skylib", + version = "1.7.1", +) + +npm = use_extension("@aspect_rules_js//npm:extensions.bzl", "npm") +npm.npm_translate_lock( + name = "flatbuffers_npm", + npmrc = "//:.npmrc", + pnpm_lock = "//ts:pnpm-lock.yaml", + # Override the Bazel package where pnpm-lock.yaml is located and link + # to the specified package instead. + root_package = "ts", + verify_node_modules_ignored = "//:.bazelignore", +) +use_repo(npm, "flatbuffers_npm") + +node = use_extension("@rules_nodejs//nodejs:extensions.bzl", "node") +use_repo(node, "nodejs_linux_amd64") + +rules_ts_ext = use_extension("@aspect_rules_ts//ts:extensions.bzl", "ext", dev_dependency = True) +rules_ts_ext.deps() +use_repo(rules_ts_ext, "npm_typescript") diff --git a/Package.swift b/Package.swift index 982277a921..4f60a8c745 100644 --- a/Package.swift +++ b/Package.swift @@ -1,4 +1,4 @@ -// swift-tools-version:5.2 +// swift-tools-version:5.10 /* * Copyright 2020 Google Inc. All rights reserved. * @@ -20,18 +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", - exclude: ["Documentation.docc/Resources/code/swift"]), + 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 similarity index 54% rename from readme.md rename to README.md index 5056a64729..41a5c44b9c 100644 --- a/readme.md +++ b/README.md @@ -1,10 +1,9 @@ -![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) +[![BuildKite status](https://badge.buildkite.com/7979d93bc6279aa539971f271253c65d5e8fe2fe43c90bbb25.svg)](https://buildkite.com/bazel/flatbuffers) [![Fuzzing Status](https://oss-fuzz-build-logs.storage.googleapis.com/badges/flatbuffers.svg)](https://bugs.chromium.org/p/oss-fuzz/issues/list?sort=-opened&can=1&q=proj:flatbuffers) -[![OpenSSF Scorecard](https://api.securityscorecards.dev/projects/github.com/google/flatbuffers/badge)](https://api.securityscorecards.dev/projects/github.com/google/flatbuffers) -[![Join the chat at https://gitter.im/google/flatbuffers](https://badges.gitter.im/google/flatbuffers.svg)](https://gitter.im/google/flatbuffers?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![Discord Chat](https://img.shields.io/discord/656202785926152206.svg)](https:///discord.gg/6qgKs3R) [![Twitter Follow](https://img.shields.io/twitter/follow/wvo.svg?style=social)](https://twitter.com/wvo) [![Twitter Follow](https://img.shields.io/twitter/follow/dbaileychess.svg?style=social)](https://twitter.com/dbaileychess) @@ -13,14 +12,55 @@ **FlatBuffers** is a cross platform serialization library architected for maximum memory efficiency. It allows you to directly access serialized data without parsing/unpacking it first, while still having great forwards/backwards compatibility. +## Quick Start + +1. Build the compiler for flatbuffers (`flatc`) + + Use `cmake` to create the build files for your platform and then perform the compilation (Linux example). + + ``` + cmake -G "Unix Makefiles" + make -j + ``` + +2. Define your flatbuffer schema (`.fbs`) + + Write the [schema](https://flatbuffers.dev/flatbuffers_guide_writing_schema.html) to define the data you want to serialize. See [monster.fbs](https://github.com/google/flatbuffers/blob/master/samples/monster.fbs) for an example. + +3. Generate code for your language(s) + + Use the `flatc` compiler to take your schema and generate language-specific code: + + ``` + ./flatc --cpp --rust monster.fbs + ``` + + Which generates `monster_generated.h` and `monster_generated.rs` files. + +4. Serialize data + + Use the generated code, as well as the `FlatBufferBuilder` to construct your serialized buffer. ([`C++` example](https://github.com/google/flatbuffers/blob/master/samples/sample_binary.cpp#L24-L56)) + +5. Transmit/store/save Buffer + + Use your serialized buffer however you want. Send it to someone, save it for later, etc... + +6. Read the data + + Use the generated accessors to read the data from the serialized buffer. + + It doesn't need to be the same language/schema version, FlatBuffers ensures the data is readable across languages and schema versions. See the [`Rust` example](https://github.com/google/flatbuffers/blob/master/samples/sample_binary.rs#L92-L106) reading the data written by `C++`. + +## Documentation + **Go to our [landing page][] to browse our documentation.** ## Supported operating systems -* Windows -* MacOS X -* Linux -* Android -* And any others with a recent C++ compiler (C++ 11 and newer) +- Windows +- macOS +- Linux +- Android +- And any others with a recent C++ compiler (C++ 11 and newer) ## Supported programming languages @@ -30,21 +70,22 @@ Code generation and runtime libraries for many popular languages. 1. C++ - [snapcraft.io](https://snapcraft.io/flatbuffers) 1. C# - [nuget.org](https://www.nuget.org/packages/Google.FlatBuffers) 1. Dart - [pub.dev](https://pub.dev/packages/flat_buffers) -1. Go - [go.dev](https://pkg.go.dev/github.com/google/flatbuffers/go) +1. Go - [go.dev](https://pkg.go.dev/github.com/google/flatbuffers) 1. Java - [Maven](https://search.maven.org/artifact/com.google.flatbuffers/flatbuffers-java) 1. JavaScript - [NPM](https://www.npmjs.com/package/flatbuffers) 1. Kotlin 1. Lobster 1. Lua 1. PHP -1. Python - [PyPi](https://pypi.org/project/flatbuffers/) +1. Python - [PyPI](https://pypi.org/project/flatbuffers/) 1. Rust - [crates.io](https://crates.io/crates/flatbuffers) -1. Swift +1. Swift - [swiftpackageindex](https://swiftpackageindex.com/google/flatbuffers) 1. TypeScript - [NPM](https://www.npmjs.com/package/flatbuffers) +1. Nim -*and more in progress...* +## Versioning -1. [Nim](https://github.com/google/flatbuffers/pull/7362) +FlatBuffers does not follow traditional SemVer versioning (see [rationale](https://github.com/google/flatbuffers/wiki/Versioning)) but rather uses a format of the date of the release. ## Contribution @@ -55,10 +96,7 @@ Code generation and runtime libraries for many popular languages. ## Community -* [FlatBuffers Google Group][] to discuss FlatBuffers with other developers and users. * [Discord Server](https:///discord.gg/6qgKs3R) -* [Gitter](https://gitter.im/google/flatbuffers) - ## Security @@ -75,4 +113,4 @@ Please see our [Security Policy](SECURITY.md) for reporting vulnerabilities. [FlatBuffers Issues Tracker]: http://github.com/google/flatbuffers/issues [stackoverflow.com]: http://stackoverflow.com/search?q=flatbuffers [landing page]: https://google.github.io/flatbuffers - [LICENSE]: https://github.com/google/flatbuffers/blob/master/LICENSE.txt + [LICENSE]: https://github.com/google/flatbuffers/blob/master/LICENSE diff --git a/WORKSPACE b/WORKSPACE deleted file mode 100644 index 5b364e0989..0000000000 --- a/WORKSPACE +++ /dev/null @@ -1,101 +0,0 @@ -workspace(name = "com_github_google_flatbuffers") - -load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") - -http_archive( - name = "platforms", - sha256 = "379113459b0feaf6bfbb584a91874c065078aa673222846ac765f86661c27407", - urls = [ - "https://mirror.bazel.build/github.com/bazelbuild/platforms/releases/download/0.0.5/platforms-0.0.5.tar.gz", - "https://github.com/bazelbuild/platforms/releases/download/0.0.5/platforms-0.0.5.tar.gz", - ], -) - -http_archive( - name = "build_bazel_rules_swift", - sha256 = "a2fd565e527f83fb3f9eb07eb9737240e668c9242d3bc318712efa54a7deda97", - url = "https://github.com/bazelbuild/rules_swift/releases/download/0.27.0/rules_swift.0.27.0.tar.gz", -) - -load( - "@build_bazel_rules_swift//swift:repositories.bzl", - "swift_rules_dependencies", -) - -swift_rules_dependencies() - -load( - "@build_bazel_rules_swift//swift:extras.bzl", - "swift_rules_extra_dependencies", -) - -swift_rules_extra_dependencies() - -http_archive( - name = "io_bazel_rules_go", - sha256 = "16e9fca53ed6bd4ff4ad76facc9b7b651a89db1689a2877d6fd7b82aa824e366", - urls = [ - "https://mirror.bazel.build/github.com/bazelbuild/rules_go/releases/download/v0.34.0/rules_go-v0.34.0.zip", - "https://github.com/bazelbuild/rules_go/releases/download/v0.34.0/rules_go-v0.34.0.zip", - ], -) - -load("@io_bazel_rules_go//go:deps.bzl", "go_rules_dependencies") - -go_rules_dependencies() - -##### Protobuf -_PROTOBUF_VERSION = "3.15.2" - -http_archive( - name = "com_google_protobuf", - strip_prefix = "protobuf-" + _PROTOBUF_VERSION, - urls = [ - "https://github.com/protocolbuffers/protobuf/archive/v" + _PROTOBUF_VERSION + ".tar.gz", - ], -) - -##### GRPC -_GRPC_VERSION = "1.49.0" # https://github.com/grpc/grpc/releases/tag/v1.48.0 - -http_archive( - name = "com_github_grpc_grpc", - patch_args = ["-p1"], - patches = ["//grpc:build_grpc_with_cxx14.patch"], - sha256 = "15715e1847cc9e42014f02c727dbcb48e39dbdb90f79ad3d66fe4361709ff935", - strip_prefix = "grpc-" + _GRPC_VERSION, - urls = ["https://github.com/grpc/grpc/archive/refs/tags/v" + _GRPC_VERSION + ".tar.gz"], -) - -load("@com_github_grpc_grpc//bazel:grpc_deps.bzl", "grpc_deps") - -grpc_deps() - -load("@com_github_grpc_grpc//bazel:grpc_extra_deps.bzl", "grpc_extra_deps") - -grpc_extra_deps() - -# rules_go from https://github.com/bazelbuild/rules_go/releases/tag/v0.34.0 -http_archive( - name = "build_bazel_rules_nodejs", - sha256 = "965ee2492a2b087cf9e0f2ca472aeaf1be2eb650e0cfbddf514b9a7d3ea4b02a", - urls = ["https://github.com/bazelbuild/rules_nodejs/releases/download/5.2.0/rules_nodejs-5.2.0.tar.gz"], -) - -load("@build_bazel_rules_nodejs//:repositories.bzl", "build_bazel_rules_nodejs_dependencies") - -build_bazel_rules_nodejs_dependencies() - -load("@build_bazel_rules_nodejs//:index.bzl", "node_repositories", "yarn_install") - -node_repositories() - -yarn_install( - name = "npm", - exports_directories_only = False, - # Unfreeze to add/remove packages. - frozen_lockfile = True, - package_json = "//:package.json", - symlink_node_modules = False, - yarn_lock = "//:yarn.lock", -) diff --git a/android/.project b/android/.project index e7d5931bc8..17f0659d4a 100644 --- a/android/.project +++ b/android/.project @@ -1,20 +1,22 @@ - - FlatBufferTest + FlatBufferTest + + + + + + + + + + 1672434305228 + + 30 + + org.eclipse.core.resources.regexFilterMatcher + node_modules|\.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__ + + + diff --git a/android/AndroidManifest.xml b/android/AndroidManifest.xml index 65ce643095..a6c97492b1 100644 --- a/android/AndroidManifest.xml +++ b/android/AndroidManifest.xml @@ -3,6 +3,7 @@ + diff --git a/android/app/build.gradle b/android/app/build.gradle index 1b035bab4b..9941783099 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -1,15 +1,13 @@ apply plugin: 'com.android.application' apply plugin: 'kotlin-android' -apply plugin: 'kotlin-android-extensions' android { - compileSdkVersion 30 - buildToolsVersion "30.0.2" + compileSdk 33 defaultConfig { applicationId "com.flatbuffers.app" minSdkVersion 26 - targetSdkVersion 30 + targetSdkVersion 33 versionCode 1 versionName "1.0" @@ -113,13 +111,13 @@ android { dependsOn(generateFbsCpp) } } + namespace 'com.flatbuffers.app' } dependencies { implementation fileTree(dir: "libs", include: ["*.jar"]) implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" - implementation 'androidx.core:core-ktx:1.3.2' - implementation 'androidx.appcompat:appcompat:1.2.0' + implementation 'androidx.appcompat:appcompat:1.6.1' // If you using java runtime you can add its dependency as the example below // implementation 'com.google.flatbuffers:flatbuffers-java:$latest_version' diff --git a/android/app/proguard-rules.pro b/android/app/proguard-rules.pro deleted file mode 100644 index f1b424510d..0000000000 --- a/android/app/proguard-rules.pro +++ /dev/null @@ -1,21 +0,0 @@ -# Add project specific ProGuard rules here. -# You can control the set of applied configuration files using the -# proguardFiles setting in build.gradle. -# -# For more details, see -# http://developer.android.com/guide/developing/tools/proguard.html - -# If your project uses WebView with JS, uncomment the following -# and specify the fully qualified class name to the JavaScript interface -# class: -#-keepclassmembers class fqcn.of.javascript.interface.for.webview { -# public *; -#} - -# Uncomment this to preserve the line number information for -# debugging stack traces. -#-keepattributes SourceFile,LineNumberTable - -# If you keep the line number information, uncomment this to -# hide the original source file name. -#-renamesourcefileattribute SourceFile diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index c2dcba9b35..53caca65bc 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -1,6 +1,5 @@ - + - + diff --git a/android/app/src/main/cpp/CMakeLists.txt b/android/app/src/main/cpp/CMakeLists.txt index f30dd4a0af..abb8250bda 100644 --- a/android/app/src/main/cpp/CMakeLists.txt +++ b/android/app/src/main/cpp/CMakeLists.txt @@ -48,7 +48,6 @@ find_library( # Sets the name of the path variable. target_link_libraries( # Specifies the target library. native-lib flatbuffers - flatbuffers_tests # Links the target library to the log library # included in the NDK. ${log-lib} ) diff --git a/android/app/src/main/cpp/animals.cpp b/android/app/src/main/cpp/animals.cpp index bf87b875c6..66a1bf014d 100644 --- a/android/app/src/main/cpp/animals.cpp +++ b/android/app/src/main/cpp/animals.cpp @@ -15,25 +15,27 @@ */ #include -#include #include + +#include + #include "generated/animal_generated.h" using namespace com::fbs::app; using namespace flatbuffers; -extern "C" JNIEXPORT jbyteArray JNICALL Java_com_flatbuffers_app_MainActivity_createAnimalFromJNI( - JNIEnv* env, - jobject /* this */) { - // create a new animal flatbuffers - auto fb = FlatBufferBuilder(1024); - auto tiger = CreateAnimalDirect(fb, "Tiger", "Roar", 300); - fb.Finish(tiger); +extern "C" JNIEXPORT jbyteArray JNICALL +Java_com_flatbuffers_app_MainActivity_createAnimalFromJNI(JNIEnv* env, + jobject /* this */) { + // create a new animal flatbuffers + auto fb = FlatBufferBuilder(1024); + auto tiger = CreateAnimalDirect(fb, "Tiger", "Roar", 300); + fb.Finish(tiger); - // copies it to a Java byte array. - auto buf = reinterpret_cast(fb.GetBufferPointer()); - int size = fb.GetSize(); - auto ret = env->NewByteArray(size); - env->SetByteArrayRegion (ret, 0, fb.GetSize(), buf); + // copies it to a Java byte array. + auto buf = reinterpret_cast(fb.GetBufferPointer()); + int size = fb.GetSize(); + auto ret = env->NewByteArray(size); + env->SetByteArrayRegion(ret, 0, fb.GetSize(), buf); return ret; } diff --git a/android/app/src/main/cpp/flatbuffers/CMakeLists.txt b/android/app/src/main/cpp/flatbuffers/CMakeLists.txt index e1dd1e8d35..144523ee85 100644 --- a/android/app/src/main/cpp/flatbuffers/CMakeLists.txt +++ b/android/app/src/main/cpp/flatbuffers/CMakeLists.txt @@ -18,7 +18,6 @@ set(FlatBuffers_Library_SRCS ${FLATBUFFERS_SRC}/include/flatbuffers/allocator.h ${FLATBUFFERS_SRC}/include/flatbuffers/array.h ${FLATBUFFERS_SRC}/include/flatbuffers/base.h - ${FLATBUFFERS_SRC}/include/flatbuffers/bfbs_generator.h ${FLATBUFFERS_SRC}/include/flatbuffers/buffer.h ${FLATBUFFERS_SRC}/include/flatbuffers/buffer_ref.h ${FLATBUFFERS_SRC}/include/flatbuffers/default_allocator.h @@ -49,26 +48,9 @@ set(FlatBuffers_Library_SRCS ${FLATBUFFERS_SRC}/src/code_generators.cpp ) -set(FlatBuffers_Test_SRCS - ${FLATBUFFERS_SRC}/tests/test.cpp - ${FLATBUFFERS_SRC}/tests/test_assert.h - ${FLATBUFFERS_SRC}/tests/test_builder.h - ${FLATBUFFERS_SRC}/tests/test_assert.cpp - ${FLATBUFFERS_SRC}/tests/test_builder.cpp - ${FLATBUFFERS_SRC}/tests/native_type_test_impl.h - ${FLATBUFFERS_SRC}/tests/native_type_test_impl.cpp -) - add_library( # Sets the name of the library. flatbuffers ${FlatBuffers_Library_SRCS} - ${FlatBuffers_Test_SRCS} ${Generated_SRCS} ) - -add_library( # Sets the name of the library. - flatbuffers_tests - - ${FlatBuffers_Test_SRCS} -) diff --git a/android/app/src/main/cpp/generated/animal_generated.h b/android/app/src/main/cpp/generated/animal_generated.h index 5253f67cca..a34bce4f85 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_ @@ -8,10 +7,10 @@ // 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 == 2 && - FLATBUFFERS_VERSION_MINOR == 0 && - FLATBUFFERS_VERSION_REVISION == 8, - "Non-compatible flatbuffers version included"); +static_assert(FLATBUFFERS_VERSION_MAJOR == 24 && + FLATBUFFERS_VERSION_MINOR == 12 && + FLATBUFFERS_VERSION_REVISION == 23, + "Non-compatible flatbuffers version included"); namespace com { namespace fbs { @@ -20,61 +19,55 @@ namespace app { struct Animal; struct AnimalBuilder; -struct Animal FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table { +struct Animal FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { typedef AnimalBuilder Builder; enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { VT_NAME = 4, 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::uoffset_t start_; - void add_name(flatbuffers::Offset name) { + ::flatbuffers::FlatBufferBuilder& fbb_; + ::flatbuffers::uoffset_t start_; + void add_name(::flatbuffers::Offset<::flatbuffers::String> name) { fbb_.AddOffset(Animal::VT_NAME, name); } - void add_sound(flatbuffers::Offset sound) { + void add_sound(::flatbuffers::Offset<::flatbuffers::String> sound) { fbb_.AddOffset(Animal::VT_SOUND, sound); } 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() { + ::flatbuffers::Offset Finish() { const auto end = fbb_.EndTable(start_); - auto o = flatbuffers::Offset(end); + auto o = ::flatbuffers::Offset(end); return o; } }; -inline flatbuffers::Offset CreateAnimal( - flatbuffers::FlatBufferBuilder &_fbb, - flatbuffers::Offset name = 0, - flatbuffers::Offset sound = 0, +inline ::flatbuffers::Offset CreateAnimal( + ::flatbuffers::FlatBufferBuilder& _fbb, + ::flatbuffers::Offset<::flatbuffers::String> name = 0, + ::flatbuffers::Offset<::flatbuffers::String> sound = 0, uint16_t weight = 0) { AnimalBuilder builder_(_fbb); builder_.add_sound(sound); @@ -83,47 +76,39 @@ inline flatbuffers::Offset CreateAnimal( return builder_.Finish(); } -inline flatbuffers::Offset CreateAnimalDirect( - flatbuffers::FlatBufferBuilder &_fbb, - const char *name = nullptr, - const char *sound = nullptr, - uint16_t weight = 0) { +inline ::flatbuffers::Offset CreateAnimalDirect( + ::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) { - return flatbuffers::GetRoot(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) { - return flatbuffers::GetSizePrefixedRoot(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::Offset root) { + ::flatbuffers::FlatBufferBuilder& fbb, + ::flatbuffers::Offset root) { fbb.Finish(root); } inline void FinishSizePrefixedAnimalBuffer( - flatbuffers::FlatBufferBuilder &fbb, - flatbuffers::Offset root) { + ::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 cdc35730e3..8bf7a1c9a8 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 6ecac60409..711a0d5001 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,62 +2,101 @@ package com.fbs.app -import java.nio.* -import kotlin.math.sign -import com.google.flatbuffers.* +import com.google.flatbuffers.Constants +import com.google.flatbuffers.FlatBufferBuilder +import com.google.flatbuffers.Table +import java.nio.ByteBuffer +import java.nio.ByteOrder @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_12_19() + + 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_22_10_26() - 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/android/build.gradle b/android/build.gradle index d37c10c8d8..7e9cdec519 100644 --- a/android/build.gradle +++ b/android/build.gradle @@ -1,12 +1,12 @@ // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { - ext.kotlin_version = "1.4.10" + ext.kotlin_version = "1.7.21" repositories { google() - jcenter() + mavenCentral() } dependencies { - classpath 'com.android.tools.build:gradle:4.1.0' + classpath 'com.android.tools.build:gradle:7.4.1' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" // NOTE: Do not place your application dependencies here; they belong @@ -17,7 +17,7 @@ buildscript { allprojects { repositories { google() - jcenter() + mavenCentral() } } diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties index aa991fceae..f72df95a7e 100644 --- a/android/gradle/wrapper/gradle-wrapper.properties +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,5 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.0.1-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/benchmarks/CMakeLists.txt b/benchmarks/CMakeLists.txt index 272a2b7b6c..18f6ef9fd4 100644 --- a/benchmarks/CMakeLists.txt +++ b/benchmarks/CMakeLists.txt @@ -1,8 +1,9 @@ # Setup for running Google Benchmarks (https://github.com/google/benchmark) on -# flatbuffers. This requires both that benchmark library and its depenency gtest +# flatbuffers. This requires both that benchmark library and its dependency gtest # to build. Instead of including them here or doing a submodule, this uses # FetchContent (https://cmake.org/cmake/help/latest/module/FetchContent.html) to # grab the dependencies at config time. This requires CMake 3.14 or higher. + cmake_minimum_required(VERSION 3.14) include(FetchContent) @@ -27,7 +28,7 @@ FetchContent_MakeAvailable( googlebenchmark ) -set(CPP_BENCH_DIR cpp) +set(CPP_BENCH_DIR ${CMAKE_CURRENT_SOURCE_DIR}/cpp) set(CPP_FB_BENCH_DIR ${CPP_BENCH_DIR}/flatbuffers) set(CPP_RAW_BENCH_DIR ${CPP_BENCH_DIR}/raw) set(CPP_BENCH_FBS ${CPP_FB_BENCH_DIR}/bench.fbs) @@ -62,8 +63,8 @@ add_custom_command( add_executable(flatbenchmark ${FlatBenchmark_SRCS}) # Benchmark requires C++11 -target_compile_features(flatbenchmark PUBLIC - cxx_std_11 +target_compile_features(flatbenchmark PRIVATE + cxx_std_11 # requires cmake 3.8 ) target_compile_options(flatbenchmark @@ -81,7 +82,7 @@ set_target_properties(flatbenchmark # The includes of the benchmark files are fully qualified from flatbuffers root. target_include_directories(flatbenchmark PUBLIC ${CMAKE_SOURCE_DIR}) -target_link_libraries(flatbenchmark +target_link_libraries(flatbenchmark PRIVATE benchmark::benchmark_main # _main to use their entry point gtest # Link to gtest so we can also assert in the benchmarks ) \ No newline at end of file diff --git a/benchmarks/cpp/bench.h b/benchmarks/cpp/bench.h index ad4baebf51..f358d210d0 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/benchmark_main.cpp b/benchmarks/cpp/benchmark_main.cpp index 63807a5dd5..3bcca106ef 100644 --- a/benchmarks/cpp/benchmark_main.cpp +++ b/benchmarks/cpp/benchmark_main.cpp @@ -5,8 +5,8 @@ #include "benchmarks/cpp/flatbuffers/fb_bench.h" #include "benchmarks/cpp/raw/raw_bench.h" -static inline void Encode(benchmark::State &state, - std::unique_ptr &bench, uint8_t *buffer) { +static inline void Encode(benchmark::State& state, + std::unique_ptr& bench, uint8_t* buffer) { int64_t length; for (auto _ : state) { bench->Encode(buffer, length); @@ -14,31 +14,33 @@ static inline void Encode(benchmark::State &state, } } -static inline void Decode(benchmark::State &state, - std::unique_ptr &bench, uint8_t *buffer) { +static inline void Decode(benchmark::State& state, + std::unique_ptr& bench, uint8_t* buffer) { int64_t length; - uint8_t *encoded = bench->Encode(buffer, length); + uint8_t* encoded = bench->Encode(buffer, length); for (auto _ : state) { - void *decoded = bench->Decode(encoded, length); + void* decoded = bench->Decode(encoded, length); benchmark::DoNotOptimize(decoded); } } -static inline void Use(benchmark::State &state, std::unique_ptr &bench, - uint8_t *buffer, int64_t check_sum) { +static inline void Use(benchmark::State& state, std::unique_ptr& bench, + uint8_t* buffer, int64_t check_sum) { int64_t length; - uint8_t *encoded = bench->Encode(buffer, length); - void *decoded = bench->Decode(encoded, length); + uint8_t* encoded = bench->Encode(buffer, length); + void* decoded = bench->Decode(encoded, length); int64_t sum = 0; - for (auto _ : state) { sum = bench->Use(decoded); } + for (auto _ : state) { + sum = bench->Use(decoded); + } EXPECT_EQ(sum, check_sum); } -static void BM_Flatbuffers_Encode(benchmark::State &state) { +static void BM_Flatbuffers_Encode(benchmark::State& state) { const int64_t kBufferLength = 1024; uint8_t buffer[kBufferLength]; @@ -48,7 +50,7 @@ static void BM_Flatbuffers_Encode(benchmark::State &state) { } BENCHMARK(BM_Flatbuffers_Encode); -static void BM_Flatbuffers_Decode(benchmark::State &state) { +static void BM_Flatbuffers_Decode(benchmark::State& state) { const int64_t kBufferLength = 1024; uint8_t buffer[kBufferLength]; @@ -58,7 +60,7 @@ static void BM_Flatbuffers_Decode(benchmark::State &state) { } BENCHMARK(BM_Flatbuffers_Decode); -static void BM_Flatbuffers_Use(benchmark::State &state) { +static void BM_Flatbuffers_Use(benchmark::State& state) { const int64_t kBufferLength = 1024; uint8_t buffer[kBufferLength]; @@ -68,7 +70,7 @@ static void BM_Flatbuffers_Use(benchmark::State &state) { } BENCHMARK(BM_Flatbuffers_Use); -static void BM_Raw_Encode(benchmark::State &state) { +static void BM_Raw_Encode(benchmark::State& state) { const int64_t kBufferLength = 1024; uint8_t buffer[kBufferLength]; @@ -77,7 +79,7 @@ static void BM_Raw_Encode(benchmark::State &state) { } BENCHMARK(BM_Raw_Encode); -static void BM_Raw_Decode(benchmark::State &state) { +static void BM_Raw_Decode(benchmark::State& state) { const int64_t kBufferLength = 1024; uint8_t buffer[kBufferLength]; @@ -86,7 +88,7 @@ static void BM_Raw_Decode(benchmark::State &state) { } BENCHMARK(BM_Raw_Decode); -static void BM_Raw_Use(benchmark::State &state) { +static void BM_Raw_Use(benchmark::State& state) { const int64_t kBufferLength = 1024; uint8_t buffer[kBufferLength]; diff --git a/benchmarks/cpp/flatbuffers/bench_generated.h b/benchmarks/cpp/flatbuffers/bench_generated.h index 8293759aa2..e53a868c65 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_ @@ -8,10 +7,10 @@ // 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 == 2 && - FLATBUFFERS_VERSION_MINOR == 0 && - FLATBUFFERS_VERSION_REVISION == 6, - "Non-compatible flatbuffers version included"); +static_assert(FLATBUFFERS_VERSION_MAJOR == 24 && + 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.cpp b/benchmarks/cpp/flatbuffers/fb_bench.cpp index 935166745a..cb20629834 100644 --- a/benchmarks/cpp/flatbuffers/fb_bench.cpp +++ b/benchmarks/cpp/flatbuffers/fb_bench.cpp @@ -13,10 +13,10 @@ using namespace benchmarks_flatbuffers; namespace { struct FlatBufferBench : Bench { - explicit FlatBufferBench(int64_t initial_size, Allocator *allocator) + explicit FlatBufferBench(int64_t initial_size, Allocator* allocator) : fbb(initial_size, allocator, false) {} - uint8_t *Encode(void *, int64_t &len) override { + uint8_t* Encode(void*, int64_t& len) override { fbb.Clear(); const int kVectorLength = 3; @@ -40,7 +40,7 @@ struct FlatBufferBench : Bench { return fbb.GetBufferPointer(); } - int64_t Use(void *decoded) override { + int64_t Use(void* decoded) override { sum = 0; auto foobarcontainer = GetFooBarContainer(decoded); sum = 0; @@ -56,7 +56,7 @@ struct FlatBufferBench : Bench { Add(static_cast(bar->ratio())); Add(bar->size()); Add(bar->time()); - auto &foo = bar->parent(); + auto& foo = bar->parent(); Add(foo.count()); Add(foo.id()); Add(foo.length()); @@ -65,8 +65,8 @@ struct FlatBufferBench : Bench { return sum; } - void *Decode(void *buffer, int64_t) override { return buffer; } - void Dealloc(void *) override {}; + void* Decode(void* buffer, int64_t) override { return buffer; } + void Dealloc(void*) override {}; FlatBufferBuilder fbb; }; @@ -74,7 +74,7 @@ struct FlatBufferBench : Bench { } // namespace std::unique_ptr NewFlatBuffersBench(int64_t initial_size, - Allocator *allocator) { + Allocator* allocator) { return std::unique_ptr( new FlatBufferBench(initial_size, allocator)); } diff --git a/benchmarks/cpp/flatbuffers/fb_bench.h b/benchmarks/cpp/flatbuffers/fb_bench.h index ffb5f54c1a..09eb2bac70 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/cpp/raw/raw_bench.cpp b/benchmarks/cpp/raw/raw_bench.cpp index c65bca7f71..4bd4e5748e 100644 --- a/benchmarks/cpp/raw/raw_bench.cpp +++ b/benchmarks/cpp/raw/raw_bench.cpp @@ -45,8 +45,8 @@ struct FooBarContainer { }; struct RawBench : Bench { - uint8_t *Encode(void *buf, int64_t &len) override { - FooBarContainer *fbc = new (buf) FooBarContainer; + uint8_t* Encode(void* buf, int64_t& len) override { + FooBarContainer* fbc = new (buf) FooBarContainer; strcpy(fbc->location, "http://google.com/flatbuffers/"); // Unsafe eek! fbc->location_len = (int)strlen(fbc->location); fbc->fruit = Bananas; @@ -54,16 +54,16 @@ struct RawBench : Bench { for (int i = 0; i < kVectorLength; i++) { // We add + i to not make these identical copies for a more realistic // compression test. - auto &foobar = fbc->list[i]; + auto& foobar = fbc->list[i]; foobar.rating = 3.1415432432445543543 + i; foobar.postfix = '!' + i; strcpy(foobar.name, "Hello, World!"); foobar.name_len = (int)strlen(foobar.name); - auto &bar = foobar.sibling; + auto& bar = foobar.sibling; bar.ratio = 3.14159f + i; bar.size = 10000 + i; bar.time = 123456 + i; - auto &foo = bar.parent; + auto& foo = bar.parent; foo.id = 0xABADCAFEABADCAFE + i; foo.count = 10000 + i; foo.length = 1000000 + i; @@ -71,11 +71,11 @@ struct RawBench : Bench { } len = sizeof(FooBarContainer); - return reinterpret_cast(fbc); + return reinterpret_cast(fbc); }; - int64_t Use(void *decoded) override { - auto foobarcontainer = reinterpret_cast(decoded); + int64_t Use(void* decoded) override { + auto foobarcontainer = reinterpret_cast(decoded); sum = 0; Add(foobarcontainer->initialized); Add(foobarcontainer->location_len); @@ -89,7 +89,7 @@ struct RawBench : Bench { Add(static_cast(bar->ratio)); Add(bar->size); Add(bar->time); - auto &foo = bar->parent; + auto& foo = bar->parent; Add(foo.count); Add(foo.id); Add(foo.length); @@ -98,8 +98,8 @@ struct RawBench : Bench { return sum; } - void *Decode(void *buf, int64_t) override { return buf; } - void Dealloc(void *) override{}; + void* Decode(void* buf, int64_t) override { return buf; } + void Dealloc(void*) override {}; }; } // namespace diff --git a/benchmarks/swift/Benchmarks/FlatbuffersBenchmarks/FlatbuffersBenchmarks.swift b/benchmarks/swift/Benchmarks/FlatbuffersBenchmarks/FlatbuffersBenchmarks.swift new file mode 100644 index 0000000000..4607f58094 --- /dev/null +++ b/benchmarks/swift/Benchmarks/FlatbuffersBenchmarks/FlatbuffersBenchmarks.swift @@ -0,0 +1,250 @@ +/* + * Copyright 2024 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import Benchmark +import FlatBuffers +import Foundation + +@usableFromInline +struct AA: NativeStruct { + public init(a: Double, b: Double) { + self.a = a + self.b = b + } + var a: Double + var b: Double +} + +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() + let str100 = (0...99).map { _ -> String in "x" }.joined() + let array: [AA] = [ + AA(a: 2.4, b: 2.4), + AA(a: 2.4, b: 2.4), + AA(a: 2.4, b: 2.4), + AA(a: 2.4, b: 2.4), + AA(a: 2.4, b: 2.4), + ] + + let metrics: [BenchmarkMetric] = [ + .cpuTotal, + .wallClock, + .mallocCountTotal, + .releaseCount, + .peakMemoryResident, + ] + let maxIterations = 1_000_000 + let maxDuration: Duration = .seconds(3) + let singleConfiguration: Benchmark.Configuration = .init( + metrics: metrics, + warmupIterations: 1, + scalingFactor: .one, + maxDuration: maxDuration, + maxIterations: maxIterations) + let kiloConfiguration: Benchmark.Configuration = .init( + metrics: metrics, + warmupIterations: 1, + scalingFactor: .kilo, + maxDuration: maxDuration, + maxIterations: maxIterations) + let megaConfiguration: Benchmark.Configuration = .init( + metrics: metrics, + warmupIterations: 1, + scalingFactor: .mega, + maxDuration: maxDuration, + maxIterations: maxIterations) + + Benchmark.defaultConfiguration = megaConfiguration + + Benchmark("Allocating 1GB", configuration: singleConfiguration) { benchmark in + for _ in benchmark.scaledIterations { + 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: oneGB) + benchmark.startMeasurement() + for _ in benchmark.scaledIterations { + blackHole(fb.clear()) + } + } + + Benchmark("Strings 10") { benchmark in + var fb = FlatBufferBuilder(initialSize: 1 << 20) + benchmark.startMeasurement() + for _ in benchmark.scaledIterations { + blackHole(fb.create(string: str10)) + } + } + + Benchmark("Strings 100") { benchmark in + var fb = FlatBufferBuilder(initialSize: 1 << 20) + benchmark.startMeasurement() + for _ in benchmark.scaledIterations { + blackHole(fb.create(string: str100)) + } + } + + Benchmark("Vector 1 Bytes") { benchmark in + var fb = FlatBufferBuilder(initialSize: 1 << 20) + benchmark.startMeasurement() + for _ in benchmark.scaledIterations { + blackHole(fb.createVector(bytes: bytes)) + } + } + + Benchmark("Vector 1 Ints") { benchmark in + var fb = FlatBufferBuilder(initialSize: 1 << 20) + benchmark.startMeasurement() + for _ in benchmark.scaledIterations { + blackHole(fb.createVector(ints)) + } + } + + Benchmark("Vector 100 Ints") { benchmark in + var fb = FlatBufferBuilder(initialSize: 1 << 20) + benchmark.startMeasurement() + for i in benchmark.scaledIterations { + blackHole(fb.createVector(ints)) + } + } + + Benchmark("Vector 100 Bytes") { benchmark in + var fb = FlatBufferBuilder(initialSize: 1 << 20) + benchmark.startMeasurement() + for i in benchmark.scaledIterations { + blackHole(fb.createVector(bytes)) + } + } + + Benchmark("Vector 100 ContiguousBytes") { benchmark in + var fb = FlatBufferBuilder(initialSize: 1 << 20) + benchmark.startMeasurement() + for i in benchmark.scaledIterations { + blackHole(fb.createVector(bytes: bytes)) + } + } + + Benchmark( + "FlatBufferBuilder Add", + configuration: kiloConfiguration) + { benchmark in + var fb = FlatBufferBuilder(initialSize: 1024 * 1024 * 32) + benchmark.startMeasurement() + for _ in benchmark.scaledIterations { + let off = fb.create(string: "T") + let s = fb.startTable(with: 4) + fb.add(element: 3.2, def: 0, at: 2) + fb.add(element: 4.2, def: 0, at: 4) + fb.add(element: 5.2, def: 0, at: 6) + fb.add(offset: off, at: 8) + blackHole(fb.endTable(at: s)) + } + } + + 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)) + var offsets: [Offset] = [] + + benchmark.startMeasurement() + for _ in benchmark.scaledIterations { + let vector = fb.createVector( + ofStructs: array) + let start = fb.startTable(with: 1) + fb.add(offset: vector, at: 4) + offsets.append(Offset(offset: fb.endTable(at: start))) + } + + let vector = fb.createVector(ofOffsets: offsets) + let start = fb.startTable(with: 1) + fb.add(offset: vector, at: 4) + let root = Offset(offset: fb.endTable(at: start)) + blackHole(fb.finish(offset: root)) + } + + Benchmark("Vector of Offsets") { benchmark in + let rawSize = ((16 * 5) * benchmark.scaledIterations.count) / 1024 + var fb = FlatBufferBuilder(initialSize: Int32(rawSize * 1600)) + benchmark.startMeasurement() + for _ in benchmark.scaledIterations { + let offsets = [ + fb.create(string: "T"), + fb.create(string: "2"), + fb.create(string: "3"), + ] + let off = fb.createVector(ofOffsets: [ + fb.createVector(ofOffsets: offsets), + fb.createVector(ofOffsets: offsets), + ]) + let s = fb.startTable(with: 2) + fb.add(offset: off, at: 2) + 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/tests/swift/benchmarks/Package.swift b/benchmarks/swift/Package.swift similarity index 58% rename from tests/swift/benchmarks/Package.swift rename to benchmarks/swift/Package.swift index c4913b784a..118732987c 100644 --- a/tests/swift/benchmarks/Package.swift +++ b/benchmarks/swift/Package.swift @@ -1,4 +1,4 @@ -// swift-tools-version:5.1 +// swift-tools-version:5.10 /* * Copyright 2020 Google Inc. All rights reserved. * @@ -20,15 +20,23 @@ import PackageDescription let package = Package( name: "benchmarks", platforms: [ - .macOS(.v10_14), + .macOS(.v13), ], dependencies: [ - .package(path: "../../.."), - .package(url: "https://github.com/google/swift-benchmark", from: "0.1.0"), + .package(path: "../.."), + .package( + url: "https://github.com/ordo-one/package-benchmark", + from: "1.27.0"), ], targets: [ - .target( - name: "benchmarks", - dependencies: ["FlatBuffers", - .product(name: "Benchmark", package: "swift-benchmark")]), + .executableTarget( + name: "FlatbuffersBenchmarks", + dependencies: [ + .product(name: "FlatBuffers", package: "flatbuffers"), + .product(name: "Benchmark", package: "package-benchmark"), + ], + path: "Benchmarks/FlatbuffersBenchmarks", + plugins: [ + .plugin(name: "BenchmarkPlugin", package: "package-benchmark"), + ]), ]) diff --git a/benchmarks/swift/README.md b/benchmarks/swift/README.md new file mode 100644 index 0000000000..d5ee2e8b5d --- /dev/null +++ b/benchmarks/swift/README.md @@ -0,0 +1,9 @@ +# Benchmarks + +To open the benchmarks in xcode use: + +`open --env BENCHMARK_DISABLE_JEMALLOC=true Package.swift` + +or running them directly within terminal using: + +`swift package benchmark` diff --git a/build_defs.bzl b/build_defs.bzl index 22949b9ee1..b22fdfef0f 100644 --- a/build_defs.bzl +++ b/build_defs.bzl @@ -7,15 +7,23 @@ Rules for building C++ flatbuffers with Bazel. load("@rules_cc//cc:defs.bzl", "cc_library") -flatc_path = "@com_github_google_flatbuffers//:flatc" +TRUE_FLATC_PATH = Label("//:flatc") DEFAULT_INCLUDE_PATHS = [ "./", "$(GENDIR)", "$(BINDIR)", - "$(execpath @com_github_google_flatbuffers//:flatc).runfiles/com_github_google_flatbuffers", + "$(execpath %s).runfiles/%s" % (TRUE_FLATC_PATH, TRUE_FLATC_PATH.repo_name), ] +def default_include_paths(flatc_path): + return [ + "./", + "$(GENDIR)", + "$(BINDIR)", + "$(execpath %s).runfiles/%s" % (flatc_path, flatc_path.repo_name), + ] + DEFAULT_FLATC_ARGS = [ "--gen-object-api", "--gen-compare", @@ -32,14 +40,18 @@ def flatbuffer_library_public( language_flag, out_prefix = "", includes = [], - include_paths = DEFAULT_INCLUDE_PATHS, + include_paths = None, flatc_args = DEFAULT_FLATC_ARGS, reflection_name = "", reflection_visibility = None, compatible_with = None, restricted_to = None, target_compatible_with = None, - output_to_bindir = False): + flatc_path = None, + output_to_bindir = False, + tools = None, + extra_env = None, + **kwargs): """Generates code files for reading/writing the given flatbuffers in the requested language using the public compiler. Args: @@ -62,15 +74,31 @@ def flatbuffer_library_public( for, instead of default-supported environments. target_compatible_with: Optional, The list of target platform constraints to use. + flatc_path: Bazel target corresponding to the flatc compiler to use. output_to_bindir: Passed to genrule for output to bin directory. + tools: Optional, passed to genrule for list of tools to make available + during the action. + extra_env: Optional, must be a string of "VAR1=VAL1 VAR2=VAL2". These get + set as environment variables that "flatc_path" sees. + **kwargs: Passed to the underlying genrule. This rule creates a filegroup(name) with all generated source files, and optionally a Fileset([reflection_name]) with all generated reflection binaries. """ + if flatc_path == None: + flatc_path = TRUE_FLATC_PATH + else: + flatc_path = native.package_relative_label(flatc_path) + + reflection_include_paths = include_paths + if include_paths == None: + include_paths = default_include_paths(flatc_path) include_paths_cmd = ["-I %s" % (s) for s in include_paths] + extra_env = extra_env or "" + # '$(@D)' when given a single source target will give the appropriate # directory. Appending 'out_prefix' is only necessary when given a build # target with multiple sources. @@ -80,7 +108,7 @@ def flatbuffer_library_public( genrule_cmd = " ".join([ "SRCS=($(SRCS));", "for f in $${SRCS[@]:0:%s}; do" % len(srcs), - "$(location %s)" % (flatc_path), + "OUTPUT_FILE=\"$(OUTS)\" %s $(location %s)" % (extra_env, flatc_path), " ".join(include_paths_cmd), " ".join(flatc_args), language_flag, @@ -93,36 +121,43 @@ def flatbuffer_library_public( srcs = srcs + includes, outs = outs, output_to_bindir = output_to_bindir, - tools = [flatc_path], + tools = (tools or []) + [flatc_path], cmd = genrule_cmd, compatible_with = compatible_with, target_compatible_with = target_compatible_with, restricted_to = restricted_to, message = "Generating flatbuffer files for %s:" % (name), + **kwargs ) if reflection_name: + if reflection_include_paths == None: + reflection_include_paths = default_include_paths(TRUE_FLATC_PATH) + reflection_include_paths_cmd = ["-I %s" % (s) for s in reflection_include_paths] reflection_genrule_cmd = " ".join([ "SRCS=($(SRCS));", "for f in $${SRCS[@]:0:%s}; do" % len(srcs), - "$(location %s)" % (flatc_path), + # Move the .fbs file into the current package if it is not there already + 'if [[ $$(dirname $$f) != "{0}" ]]; then s="$$f"; f="{0}/$$(basename "$$f")"; mkdir -p "{0}"; mv "$$s" "$$f"; fi;'.format(native.package_relative_label(":invalid").package), + "$(location %s)" % (TRUE_FLATC_PATH), "-b --schema", " ".join(flatc_args), - " ".join(include_paths_cmd), + " ".join(reflection_include_paths_cmd), language_flag, output_directory, "$$f;", "done", ]) reflection_outs = [ - (out_prefix + "%s.bfbs") % (s.replace(".fbs", "").split("/")[-1]) + (out_prefix + "%s.bfbs") % (native.package_relative_label(s).name.removesuffix(".fbs")) for s in srcs ] + native.genrule( name = "%s_srcs" % reflection_name, srcs = srcs + includes, outs = reflection_outs, output_to_bindir = output_to_bindir, - tools = [flatc_path], + tools = [TRUE_FLATC_PATH], compatible_with = compatible_with, restricted_to = restricted_to, target_compatible_with = target_compatible_with, @@ -142,15 +177,17 @@ def flatbuffer_cc_library( name, srcs, srcs_filegroup_name = "", + outs = [], out_prefix = "", deps = [], includes = [], - include_paths = DEFAULT_INCLUDE_PATHS, + include_paths = None, cc_include_paths = [], flatc_args = DEFAULT_FLATC_ARGS, visibility = None, compatible_with = None, restricted_to = None, + filename_suffix = "_generated", target_compatible_with = None, srcs_filegroup_visibility = None, gen_reflections = False): @@ -162,6 +199,7 @@ def flatbuffer_cc_library( srcs_filegroup_name: Name of the output filegroup that holds srcs. Pass this filegroup into the `includes` parameter of any other flatbuffer_cc_library that depends on this one's schemas. + outs: Additional outputs expected to be generated by flatc. out_prefix: Prepend this path to the front of all generated files. Usually is a directory name. deps: Optional, list of other flatbuffer_cc_library's to depend on. Cannot be specified @@ -193,10 +231,13 @@ def flatbuffer_cc_library( Fileset([name]_reflection): (Optional) all generated reflection binaries. cc_library([name]): library with sources and flatbuffers deps. """ - output_headers = [ - (out_prefix + "%s_generated.h") % (s.replace(".fbs", "").split("/")[-1].split(":")[-1]) - for s in srcs - ] + + output_headers = [] + for s in srcs: + base_name = s.split("/")[-1].split(":")[-1].replace(".fbs", "") + header = out_prefix + base_name + filename_suffix + ".h" + output_headers.append(header) + if deps and includes: # There is no inherent reason we couldn't support both, but this discourages # use of includes without good reason. @@ -209,7 +250,7 @@ def flatbuffer_cc_library( flatbuffer_library_public( name = srcs_lib, srcs = srcs, - outs = output_headers, + outs = outs + output_headers, language_flag = "-c", out_prefix = out_prefix, includes = includes, @@ -233,8 +274,8 @@ def flatbuffer_cc_library( "-parse_headers", ], deps = [ - "@com_github_google_flatbuffers//:runtime_cc", - "@com_github_google_flatbuffers//:flatbuffers", + Label("//:runtime_cc"), + Label("//:flatbuffers"), ] + deps, includes = cc_include_paths, compatible_with = compatible_with, diff --git a/conan/CMakeLists.txt b/conan/CMakeLists.txt deleted file mode 100644 index 65f902876e..0000000000 --- a/conan/CMakeLists.txt +++ /dev/null @@ -1,12 +0,0 @@ -cmake_minimum_required(VERSION 2.8) - -message(STATUS "Conan FlatBuffers Wrapper") - -include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake) -conan_basic_setup() - -if (WIN32 AND MSVC_LIKE AND FLATBUFFERS_BUILD_SHAREDLIB) - set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON) -endif(WIN32 AND MSVC_LIKE AND FLATBUFFERS_BUILD_SHAREDLIB) - -include(${CMAKE_SOURCE_DIR}/CMakeListsOriginal.txt) diff --git a/conan/build.py b/conan/build.py deleted file mode 100644 index 62a3799079..0000000000 --- a/conan/build.py +++ /dev/null @@ -1,50 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -import os -import re -import subprocess -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 - return "" - - -def get_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()) - - -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() diff --git a/conan/test_package/CMakeLists.txt b/conan/test_package/CMakeLists.txt deleted file mode 100644 index 9c1c78c582..0000000000 --- a/conan/test_package/CMakeLists.txt +++ /dev/null @@ -1,9 +0,0 @@ -project(test_package CXX) -cmake_minimum_required(VERSION 2.8.11) - -include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake) -conan_basic_setup() - -add_executable(${PROJECT_NAME} test_package.cpp) -target_link_libraries(${PROJECT_NAME} ${CONAN_LIBS}) -set_property(TARGET ${PROJECT_NAME} PROPERTY CXX_STANDARD 11) diff --git a/conan/test_package/conanfile.py b/conan/test_package/conanfile.py deleted file mode 100644 index 735e31d27b..0000000000 --- a/conan/test_package/conanfile.py +++ /dev/null @@ -1,21 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -from conans import ConanFile, CMake -import os - - -class TestPackageConan(ConanFile): - settings = "os", "compiler", "build_type", "arch" - generators = "cmake" - - 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) diff --git a/conanfile.py b/conanfile.py deleted file mode 100644 index bdd832c36b..0000000000 --- a/conanfile.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -"""Conan recipe package for Google FlatBuffers -""" -import os -import shutil -from conans import ConanFile, CMake, 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.txt" - 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 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 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.txt", 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") diff --git a/dart/CHANGELOG.md b/dart/CHANGELOG.md index a582e2eafe..bfd32a7e74 100644 --- a/dart/CHANGELOG.md +++ b/dart/CHANGELOG.md @@ -1,3 +1,23 @@ +# Changelog + +## 25.9.23 + +- use enhanced enums (#8313) +- fix incorrect write in Float64 write method (#8290) +- code format improvements (#8707) + +## 23.5.26 + +- omit type annotationes for local variables (#7067, #7069, #7070) +- remove BSD 3-clause license (#7073) +- correctly parse lists of enums (#7157) +- align naming conventions for generated code (#7187) +- add `putBool` to fix errors when serializing structs with booleans (#7359) +- fix handling of +/-inf defaults in codegen (#7588) +- fix import issues in generated code (#7621) +- Fix incorrect storage of floats as ints in some cases (#7703) +- add final modifiers to the library implementation (#7943) + ## 2.0.5 - switch to null safety (#6696) diff --git a/dart/README.md b/dart/README.md index 123cdc38d6..a07bc258ff 100644 --- a/dart/README.md +++ b/dart/README.md @@ -3,7 +3,7 @@ This package is used to read and write [FlatBuffers](https://google.github.io/flatbuffers/). Most consumers will want to use the [`flatc` - FlatBuffer compiler](https://github.com/google/flatbuffers) binary for your platform. -You can find it in the `generator/{Platform}` directory of the [released package archive](https://pub.dev/packages/flat_buffers/versions/2.0.5.tar.gz). +You can download the flatc version matching your dart package version from [GitHub releases](https://github.com/google/flatbuffers/releases). The FlatBuffer compiler `flatc` reads a FlatBuffers IDL schema and generates Dart code. The generated classes can be used to read or write binary data/files that are interoperable with @@ -13,11 +13,3 @@ examples folder. For more details and documentation, head over to the official site and read the [Tutorial](https://google.github.io/flatbuffers/flatbuffers_guide_tutorial.html) and how to [use FlatBuffers in Dart](https://google.github.io/flatbuffers/flatbuffers_guide_use_dart.html). - -## Dart 2.0 notes -Version 2.0.5 ships with it's own custom build of `flatc` because this is an extraordinary release to catch-up -with FlatBuffers for other platforms. This generator can only generate dart code (to avoid generating code for other platforms which isn't released yet). -On the other hand, the generated code still produces standard binary FlatBuffers compatible with other languages. -In other words: only `flatc --dart ...` works with this generator, but your app will be able to produce and read standard binary (`Uint8List`) FlatBuffers that are fully compotible with other languages supporting FlatBuffers (e.g. Java, C++, ...). - -In the future a common `flatc` binary for all platforms would be shipped through GitHub release page instead. diff --git a/dart/example/example.dart b/dart/example/example.dart index d397bbb3f4..329981357f 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 ba0a81f0d5..612de336b0 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 8ce1ab907e..7590bdba69 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 = {}; } @@ -304,7 +305,7 @@ class Builder { assert(_inVTable); // Prepare for writing the VTable. _prepare(_sizeofInt32, 1); - var tableTail = _tail; + final tableTail = _tail; // Prepare the size of the current table. final currentVTable = _currentVTable!; currentVTable.tableSize = tableTail - _currentTableEndTail; @@ -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; @@ -386,7 +393,7 @@ class Builder { /// Updates the [offset] pointer. This method is intended for use when writing structs to the buffer. void putFloat64(double value) { _prepare(_sizeofFloat64, 1); - _setFloat32AtTail(_tail, value); + _setFloat64AtTail(_tail, value); } /// Writes a Float32 to the tail of the buffer after preparing space for it. @@ -514,7 +521,7 @@ class Builder { var tail = _tail; _setUint32AtTail(tail, values.length); tail -= _sizeofUint32; - for (var value in values) { + for (final value in values) { _setUint32AtTail(tail, tail - value); tail -= _sizeofUint32; } @@ -529,7 +536,7 @@ class Builder { var tail = _tail; _setUint32AtTail(tail, values.length); tail -= _sizeofUint32; - for (var value in values) { + for (final value in values) { _setFloat64AtTail(tail, value); tail -= _sizeofFloat64; } @@ -544,7 +551,7 @@ class Builder { var tail = _tail; _setUint32AtTail(tail, values.length); tail -= _sizeofUint32; - for (var value in values) { + for (final value in values) { _setFloat32AtTail(tail, value); tail -= _sizeofFloat32; } @@ -559,7 +566,7 @@ class Builder { var tail = _tail; _setUint32AtTail(tail, values.length); tail -= _sizeofUint32; - for (var value in values) { + for (final value in values) { _setInt64AtTail(tail, value); tail -= _sizeofInt64; } @@ -574,7 +581,7 @@ class Builder { var tail = _tail; _setUint32AtTail(tail, values.length); tail -= _sizeofUint32; - for (var value in values) { + for (final value in values) { _setUint64AtTail(tail, value); tail -= _sizeofUint64; } @@ -589,7 +596,7 @@ class Builder { var tail = _tail; _setUint32AtTail(tail, values.length); tail -= _sizeofUint32; - for (var value in values) { + for (final value in values) { _setInt32AtTail(tail, value); tail -= _sizeofInt32; } @@ -604,7 +611,7 @@ class Builder { var tail = _tail; _setUint32AtTail(tail, values.length); tail -= _sizeofUint32; - for (var value in values) { + for (final value in values) { _setUint32AtTail(tail, value); tail -= _sizeofUint32; } @@ -619,7 +626,7 @@ class Builder { var tail = _tail; _setUint32AtTail(tail, values.length); tail -= _sizeofUint32; - for (var value in values) { + for (final value in values) { _setInt16AtTail(tail, value); tail -= _sizeofInt16; } @@ -634,7 +641,7 @@ class Builder { var tail = _tail; _setUint32AtTail(tail, values.length); tail -= _sizeofUint32; - for (var value in values) { + for (final value in values) { _setUint16AtTail(tail, value); tail -= _sizeofUint16; } @@ -654,7 +661,7 @@ class Builder { var tail = _tail; _setUint32AtTail(tail, values.length); tail -= _sizeofUint32; - for (var value in values) { + for (final value in values) { _setInt8AtTail(tail, value); tail -= _sizeofUint8; } @@ -669,7 +676,7 @@ class Builder { var tail = _tail; _setUint32AtTail(tail, values.length); tail -= _sizeofUint32; - for (var value in values) { + for (final value in values) { _setUint8AtTail(tail, value); tail -= _sizeofUint8; } @@ -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); } @@ -777,17 +786,17 @@ class Builder { _maxAlign = size; } // Prepare amount of required space. - var dataSize = size * count + additionalBytes; - var alignDelta = (-(_tail + dataSize)) & (size - 1); - var bufSize = alignDelta + dataSize; + final dataSize = size * count + additionalBytes; + final alignDelta = (-(_tail + dataSize)) & (size - 1); + final bufSize = alignDelta + dataSize; // Ensure that we have the required amount of space. { - var oldCapacity = _buf.lengthInBytes; + final oldCapacity = _buf.lengthInBytes; if (_tail + bufSize > oldCapacity) { - var desiredNewCapacity = (oldCapacity + bufSize) * 2; + final desiredNewCapacity = (oldCapacity + bufSize) * 2; var deltaCapacity = desiredNewCapacity - oldCapacity; deltaCapacity += (-deltaCapacity) & (_maxAlign - 1); - var newCapacity = oldCapacity + deltaCapacity; + final newCapacity = oldCapacity + deltaCapacity; _buf = _allocator.resize(_buf, newCapacity, _tail, 0); } } @@ -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, + ); } } @@ -1023,22 +1035,22 @@ abstract class Reader { /// Read the value of the given [field] in the given [object]. @pragma('vm:prefer-inline') T vTableGet(BufferContext object, int offset, int field, T defaultValue) { - var fieldOffset = _vTableFieldOffset(object, offset, field); + final fieldOffset = _vTableFieldOffset(object, offset, field); return fieldOffset == 0 ? defaultValue : read(object, offset + fieldOffset); } /// Read the value of the given [field] in the given [object]. @pragma('vm:prefer-inline') T? vTableGetNullable(BufferContext object, int offset, int field) { - var fieldOffset = _vTableFieldOffset(object, offset, field); + final fieldOffset = _vTableFieldOffset(object, offset, field); return fieldOffset == 0 ? null : read(object, offset + fieldOffset); } @pragma('vm:prefer-inline') int _vTableFieldOffset(BufferContext object, int offset, int field) { - var vTableSOffset = object._getInt32(offset); - var vTableOffset = offset - vTableSOffset; - var vTableSize = object._getUint16(vTableOffset); + final vTableSOffset = object._getInt32(offset); + final vTableOffset = offset - vTableSOffset; + final vTableSize = object._getUint16(vTableOffset); if (field >= vTableSize) return 0; return object._getUint16(vTableOffset + field); } @@ -1057,9 +1069,9 @@ class StringReader extends Reader { @override @pragma('vm:prefer-inline') String read(BufferContext bc, int offset) { - var strOffset = bc.derefObject(offset); - var length = bc._getUint32(strOffset); - var bytes = bc._asUint8List(strOffset + _sizeofUint32, length); + final strOffset = bc.derefObject(offset); + final length = bc._getUint32(strOffset); + final bytes = bc._asUint8List(strOffset + _sizeofUint32, length); if (asciiOptimization && _isLatin(bytes)) { return String.fromCharCodes(bytes); } @@ -1068,7 +1080,7 @@ class StringReader extends Reader { @pragma('vm:prefer-inline') static bool _isLatin(Uint8List bytes) { - var length = bytes.length; + final length = bytes.length; for (var i = 0; i < length; i++) { if (bytes[i] > 127) { return false; @@ -1104,7 +1116,7 @@ abstract class TableReader extends Reader { @override T read(BufferContext bc, int offset) { - var objectOffset = bc.derefObject(offset); + final objectOffset = bc.derefObject(offset); return createObject(bc, objectOffset); } } @@ -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 82681e7ec6..cdd0aec532 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 66195c1bd4..2abba107b3 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 f9eefd8bc0..653eabddae 100644 --- a/dart/lib/src/types.dart +++ b/dart/lib/src/types.dart @@ -9,7 +9,7 @@ class BitWidthUtil { } static BitWidth width(num value) { - if (value.toInt() == value) { + if (value is int) { var v = value.toInt().abs(); if (v >> 7 == 0) return BitWidth.width8; if (v >> 15 == 0) return BitWidth.width16; @@ -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 2bd448d2fc..614e91859d 100644 --- a/dart/pubspec.yaml +++ b/dart/pubspec.yaml @@ -1,15 +1,14 @@ name: flat_buffers -version: 22.10.26 +version: 25.12.19 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 environment: - sdk: '>=2.12.0 <3.0.0' + sdk: '>=2.17.0 <4.0.0' dev_dependencies: test: ^1.17.7 test_reflective_loader: ^0.2.0 path: ^1.8.0 lints: ^1.0.1 - diff --git a/dart/test/bool_structs_generated.dart b/dart/test/bool_structs_generated.dart index cdd8a5ebce..ec4732776f 100644 --- a/dart/test/bool_structs_generated.dart +++ b/dart/test/bool_structs_generated.dart @@ -1,9 +1,9 @@ // automatically generated by the FlatBuffers compiler, do not modify -// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable +// 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/list_of_enums.fbs b/dart/test/enums.fbs similarity index 100% rename from dart/test/list_of_enums.fbs rename to dart/test/enums.fbs diff --git a/dart/test/list_of_enums_generated.dart b/dart/test/enums_generated.dart similarity index 72% rename from dart/test/list_of_enums_generated.dart rename to dart/test/enums_generated.dart index eb837a5bc3..b57e8fa222 100644 --- a/dart/test/list_of_enums_generated.dart +++ b/dart/test/enums_generated.dart @@ -1,43 +1,37 @@ // automatically generated by the FlatBuffers compiler, do not modify -// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable +// 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; +enum OptionsEnum { + A(1), + B(2), + C(3); -class OptionsEnum { final int value; - const OptionsEnum._(this.value); + const OptionsEnum(this.value); factory OptionsEnum.fromValue(int value) { - final result = values[value]; - if (result == null) { - throw StateError('Invalid value $value for bit flag enum OptionsEnum'); + 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'); } - return result; } - static OptionsEnum? _createOrNull(int? value) => + static OptionsEnum? _createOrNull(int? value) => value == null ? null : OptionsEnum.fromValue(value); static const int minValue = 1; static const int maxValue = 3; - static bool containsValue(int value) => values.containsKey(value); - - static const OptionsEnum A = OptionsEnum._(1); - static const OptionsEnum B = OptionsEnum._(2); - static const OptionsEnum C = OptionsEnum._(3); - static const Map values = { - 1: A, - 2: B, - 3: C}; - static const fb.Reader reader = _OptionsEnumReader(); - - @override - String toString() { - return 'OptionsEnum{value: $value}'; - } } class _OptionsEnumReader extends fb.Reader { @@ -63,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() { @@ -71,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; @@ -82,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); @@ -104,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 { @@ -130,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 5298b17088..c4a146f8db 100644 --- a/dart/test/flat_buffers_test.dart +++ b/dart/test/flat_buffers_test.dart @@ -1,17 +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 './monster_test_my_game.example2_generated.dart' as example2; -import './list_of_enums_generated.dart' as example3; import './bool_structs_generated.dart' as example4; -import './keyword_test_keyword_test_generated.dart' as keyword_test; +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; main() { defineReflectiveSuite(() { @@ -30,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); @@ -64,11 +60,11 @@ class CheckOtherLangaugesData { expect( mon.toString(), 'Monster{' - 'pos: Vec3{x: 1.0, y: 2.0, z: 3.0, test1: 3.0, test2: Color{value: 2}, test3: Test{a: 5, b: 6}}, ' + '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{value: 8}, testType: AnyTypeId{value: 1}, ' + 'color: Color.Blue, testType: AnyTypeId.Monster, ' 'test: Monster{pos: null, mana: 150, hp: 100, name: Fred, ' - 'inventory: null, color: Color{value: 8}, testType: null, ' + '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, ' @@ -83,15 +79,18 @@ class CheckOtherLangaugesData { 'coOwningReference: 0, vectorOfCoOwningReferences: null, ' 'nonOwningReference: 0, vectorOfNonOwningReferences: null, ' 'anyUniqueType: null, anyUnique: null, anyAmbiguousType: null, ' - 'anyAmbiguous: null, vectorOfEnums: null, signedEnum: Race{value: -1}, ' + 'anyAmbiguous: null, vectorOfEnums: null, signedEnum: Race.None, ' 'testrequirednestedflatbuffer: null, scalarKeySortedTables: null, ' 'nativeInline: null, ' - 'longEnumNonEnumDefault: LongEnum{value: 0}, ' - 'longEnumNormalDefault: LongEnum{value: 2}}, ' + '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{value: 8}, testType: null, ' + '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, ' @@ -106,11 +105,14 @@ class CheckOtherLangaugesData { 'coOwningReference: 0, vectorOfCoOwningReferences: null, ' 'nonOwningReference: 0, vectorOfNonOwningReferences: null, ' 'anyUniqueType: null, anyUnique: null, anyAmbiguousType: null, ' - 'anyAmbiguous: null, vectorOfEnums: null, signedEnum: Race{value: -1}, ' + 'anyAmbiguous: null, vectorOfEnums: null, signedEnum: Race.None, ' 'testrequirednestedflatbuffer: null, scalarKeySortedTables: null, ' 'nativeInline: null, ' - 'longEnumNonEnumDefault: LongEnum{value: 0}, ' - 'longEnumNormalDefault: LongEnum{value: 2}}, ' + '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, ' @@ -132,12 +134,15 @@ class CheckOtherLangaugesData { 'vectorOfNonOwningReferences: null, ' 'anyUniqueType: null, anyUnique: null, ' 'anyAmbiguousType: null, ' - 'anyAmbiguous: null, vectorOfEnums: null, signedEnum: Race{value: -1}, ' + '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{value: 0}, ' - 'longEnumNormalDefault: LongEnum{value: 2}}', + 'longEnumNonEnumDefault: LongEnum._default, ' + 'longEnumNormalDefault: LongEnum.LongOne, nanDefault: NaN, ' + 'infDefault: Infinity, positiveInfDefault: Infinity, infinityDefault: ' + 'Infinity, positiveInfinityDefault: Infinity, negativeInfDefault: ' + '-Infinity, negativeInfinityDefault: -Infinity, doubleInfDefault: Infinity}', ); } } @@ -208,6 +213,10 @@ class BuilderTest { ..addTestarrayofstringOffset(testArrayOfString); final mon = monBuilder.finish(); fbBuilder.finish(mon); + + final mon3 = example.Monster(fbBuilder.buffer); + expect(mon3.name, 'MyMonster'); + expect(mon3.pos!.test1, 3.0); } void test_error_addInt32_withoutStartTable([Builder? builder]) { @@ -287,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() { @@ -320,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]) { @@ -359,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, + ); } } @@ -369,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); @@ -384,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]) { @@ -414,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() { @@ -585,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); @@ -616,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(); @@ -696,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) { @@ -760,7 +845,6 @@ class BuilderTest { class ObjectAPITest { void test_tableStat() { final object1 = example.StatT(count: 3, id: "foo", val: 4); - expect(object1 is Packable, isTrue); final fbb = Builder(); fbb.finish(object1.pack(fbb)); final object2 = example.Stat(fbb.buffer).unpack(); @@ -773,28 +857,28 @@ 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] ..color = example.Color.Green - // TODO be smarter for unions and automatically set the `type` field? ..testType = example.AnyTypeId.MyGame_Example2_Monster ..test = example2.MonsterT() ..test4 = [example.TestT(a: 3, b: 4), example.TestT(a: 5, b: 6)] ..testarrayofstring = ["foo", "bar"] - ..testarrayoftables = [example.MonsterT(name: 'Oof')] - ..enemy = example.MonsterT(name: 'Enemy') + ..testarrayoftables = [example.MonsterT(name: 'Oof', testf: 2.75)] + ..enemy = example.MonsterT(name: 'Enemy', testf: 2.5) ..testarrayofbools = [false, true, false] - ..testf = 42.24 + ..testf = 42.25 ..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] @@ -809,16 +893,15 @@ class ObjectAPITest { fbBuilder.finish(offset); final data = fbBuilder.buffer; - // TODO currently broken because of struct builder issue, see #6688 - // final monster2 = example.Monster(data); // Monster (reader) - // expect( - // // map Monster => MonsterT, Vec3 => Vec3T, ... - // monster2.toString().replaceAllMapped( - // RegExp('([a-zA-z0-9]+){'), (match) => match.group(1) + 'T{'), - // monster.toString()); - // - // final monster3 = monster2.unpack(); // MonsterT - // expect(monster3.toString(), monster.toString()); + final monster2 = example.Monster(data); // Monster (reader) + expect( + // map Monster => MonsterT, Vec3 => Vec3T, ... + monster2.toString().replaceAllMapped( + RegExp('([a-zA-z0-9]+){'), (match) => match.group(1)! + 'T{'), + monster.toString()); + + final monster3 = monster2.unpack(); // MonsterT + expect(monster3.toString(), monster.toString()); } void test_Lists() { @@ -857,8 +940,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 { @@ -896,10 +980,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), + ); } } @@ -907,11 +995,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); @@ -924,7 +1014,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 66e66384b5..0f766de738 100644 --- a/dart/test/flex_builder_test.dart +++ b/dart/test/flex_builder_test.dart @@ -40,6 +40,10 @@ void main() { flx.addInt(-1025); expect(flx.finish(), [255, 251, 5, 2]); } + { + var builder = Builder()..addDouble(1.0); + expect(builder.finish(), [0, 0, 128, 63, 14, 4]); + } { var flx = Builder(); flx.addDouble(0.1); @@ -58,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, + ]); } }); @@ -113,7 +132,7 @@ void main() { 192, 16, 75, - 1 + 1, ]); } { @@ -173,7 +192,7 @@ void main() { 7, 3, 60, - 1 + 1, ]); } { @@ -211,7 +230,7 @@ void main() { 10, 6, 60, - 1 + 1, ]); } { @@ -296,7 +315,7 @@ void main() { 104, 45, 43, - 1 + 1, ]); } }); @@ -318,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() @@ -363,7 +398,7 @@ void main() { 36, 4, 40, - 1 + 1, ]); } }); @@ -377,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', () { @@ -539,7 +593,7 @@ void main() { 35, 8, 40, - 1 + 1, ]); }); @@ -576,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 875b1c1614..d77d1da462 100644 --- a/dart/test/flex_reader_test.dart +++ b/dart/test/flex_reader_test.dart @@ -20,69 +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])); @@ -94,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); @@ -553,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); @@ -577,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', () { @@ -789,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, @@ -802,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}', + ); }); } @@ -834,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 76ce070498..7ed1f2ab1c 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 new file mode 100644 index 0000000000..2309e45722 --- /dev/null +++ b/dart/test/include_test1_generated.dart @@ -0,0 +1,108 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// 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 './include_test2_my_game.other_name_space_generated.dart' + as my_game_other_name_space; + +class TableA { + TableA._(this._bc, this._bcOffset); + factory TableA(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = _TableAReader(); + + 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); + + @override + String toString() { + return 'TableA{b: ${b}}'; + } + + TableAT unpack() => TableAT(b: b?.unpack()); + + static int pack(fb.Builder fbBuilder, TableAT? object) { + if (object == null) return 0; + return object.pack(fbBuilder); + } +} + +class TableAT implements fb.Packable { + my_game_other_name_space.TableBT? b; + + TableAT({this.b}); + + @override + int pack(fb.Builder fbBuilder) { + final int? bOffset = b?.pack(fbBuilder); + fbBuilder.startTable(1); + fbBuilder.addOffset(0, bOffset); + return fbBuilder.endTable(); + } + + @override + String toString() { + return 'TableAT{b: ${b}}'; + } +} + +class _TableAReader extends fb.TableReader { + const _TableAReader(); + + @override + TableA createObject(fb.BufferContext bc, int offset) => TableA._(bc, offset); +} + +class TableABuilder { + TableABuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(1); + } + + int addBOffset(int? offset) { + fbBuilder.addOffset(0, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class TableAObjectBuilder extends fb.ObjectBuilder { + final my_game_other_name_space.TableBObjectBuilder? _b; + + TableAObjectBuilder({my_game_other_name_space.TableBObjectBuilder? b}) + : _b = b; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? bOffset = _b?.getOrCreateOffset(fbBuilder); + fbBuilder.startTable(1); + fbBuilder.addOffset(0, bOffset); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} 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 new file mode 100644 index 0000000000..975622b8fb --- /dev/null +++ b/dart/test/include_test2_my_game.other_name_space_generated.dart @@ -0,0 +1,221 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable, constant_identifier_names + +library my_game.other_name_space; + +import 'dart:typed_data' show Uint8List; + +import 'package:flat_buffers/flat_buffers.dart' as fb; + +import './include_test1_generated.dart'; + +enum FromInclude { + IncludeVal(0); + + final int value; + const FromInclude(this.value); + + factory FromInclude.fromValue(int value) { + switch (value) { + case 0: + return FromInclude.IncludeVal; + default: + throw StateError('Invalid value $value for bit flag enum'); + } + } + + static FromInclude? _createOrNull(int? value) => + value == null ? null : FromInclude.fromValue(value); + + static const int minValue = 0; + static const int maxValue = 0; + static const fb.Reader reader = _FromIncludeReader(); +} + +class _FromIncludeReader extends fb.Reader { + const _FromIncludeReader(); + + @override + int get size => 8; + + @override + FromInclude read(fb.BufferContext bc, int offset) => + FromInclude.fromValue(const fb.Int64Reader().read(bc, offset)); +} + +class Unused { + Unused._(this._bc, this._bcOffset); + + static const fb.Reader reader = _UnusedReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + int get a => const fb.Int32Reader().read(_bc, _bcOffset + 0); + + @override + String toString() { + return 'Unused{a: ${a}}'; + } + + UnusedT unpack() => UnusedT(a: a); + + static int pack(fb.Builder fbBuilder, UnusedT? object) { + if (object == null) return 0; + return object.pack(fbBuilder); + } +} + +class UnusedT implements fb.Packable { + int a; + + UnusedT({required this.a}); + + @override + int pack(fb.Builder fbBuilder) { + fbBuilder.putInt32(a); + return fbBuilder.offset; + } + + @override + String toString() { + return 'UnusedT{a: ${a}}'; + } +} + +class _UnusedReader extends fb.StructReader { + const _UnusedReader(); + + @override + int get size => 4; + + @override + Unused createObject(fb.BufferContext bc, int offset) => Unused._(bc, offset); +} + +class UnusedBuilder { + UnusedBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + int finish(int a) { + fbBuilder.putInt32(a); + return fbBuilder.offset; + } +} + +class UnusedObjectBuilder extends fb.ObjectBuilder { + final int _a; + + UnusedObjectBuilder({required int a}) : _a = a; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + fbBuilder.putInt32(_a); + return fbBuilder.offset; + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} + +class TableB { + TableB._(this._bc, this._bcOffset); + factory TableB(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = _TableBReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + TableA? get a => TableA.reader.vTableGetNullable(_bc, _bcOffset, 4); + + @override + String toString() { + return 'TableB{a: ${a}}'; + } + + TableBT unpack() => TableBT(a: a?.unpack()); + + static int pack(fb.Builder fbBuilder, TableBT? object) { + if (object == null) return 0; + return object.pack(fbBuilder); + } +} + +class TableBT implements fb.Packable { + TableAT? a; + + TableBT({this.a}); + + @override + int pack(fb.Builder fbBuilder) { + final int? aOffset = a?.pack(fbBuilder); + fbBuilder.startTable(1); + fbBuilder.addOffset(0, aOffset); + return fbBuilder.endTable(); + } + + @override + String toString() { + return 'TableBT{a: ${a}}'; + } +} + +class _TableBReader extends fb.TableReader { + const _TableBReader(); + + @override + TableB createObject(fb.BufferContext bc, int offset) => TableB._(bc, offset); +} + +class TableBBuilder { + TableBBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(1); + } + + int addAOffset(int? offset) { + fbBuilder.addOffset(0, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class TableBObjectBuilder extends fb.ObjectBuilder { + final TableAObjectBuilder? _a; + + TableBObjectBuilder({TableAObjectBuilder? a}) : _a = a; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? aOffset = _a?.getOrCreateOffset(fbBuilder); + fbBuilder.startTable(1); + fbBuilder.addOffset(0, aOffset); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} diff --git a/dart/test/keyword_test_keyword_test_generated.dart b/dart/test/keyword_test_keyword_test_generated.dart index 6cfc2337c4..4f5d464ae0 100644 --- a/dart/test/keyword_test_keyword_test_generated.dart +++ b/dart/test/keyword_test_keyword_test_generated.dart @@ -1,5 +1,5 @@ // automatically generated by the FlatBuffers compiler, do not modify -// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable +// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable, constant_identifier_names library keyword_test; @@ -7,39 +7,30 @@ import 'dart:typed_data' show Uint8List; import 'package:flat_buffers/flat_buffers.dart' as fb; -class Abc { + +enum Abc { + $void(0), + where(1), + stackalloc(2); + final int value; - const Abc._(this.value); + const Abc(this.value); factory Abc.fromValue(int value) { - final result = values[value]; - if (result == null) { - throw StateError('Invalid value $value for bit flag enum Abc'); + switch (value) { + case 0: return Abc.$void; + case 1: return Abc.where; + case 2: return Abc.stackalloc; + default: throw StateError('Invalid value $value for bit flag enum'); } - return result; } - static Abc? _createOrNull(int? value) => + static Abc? _createOrNull(int? value) => value == null ? null : Abc.fromValue(value); static const int minValue = 0; static const int maxValue = 2; - static bool containsValue(int value) => values.containsKey(value); - - static const Abc $void = Abc._(0); - static const Abc where = Abc._(1); - static const Abc stackalloc = Abc._(2); - static const Map values = { - 0: $void, - 1: where, - 2: stackalloc}; - static const fb.Reader reader = _AbcReader(); - - @override - String toString() { - return 'Abc{value: $value}'; - } } class _AbcReader extends fb.Reader { @@ -53,35 +44,25 @@ class _AbcReader extends fb.Reader { Abc.fromValue(const fb.Int32Reader().read(bc, offset)); } -class Public { +enum Public { + NONE(0); + final int value; - const Public._(this.value); + const Public(this.value); factory Public.fromValue(int value) { - final result = values[value]; - if (result == null) { - throw StateError('Invalid value $value for bit flag enum Public'); + switch (value) { + case 0: return Public.NONE; + default: throw StateError('Invalid value $value for bit flag enum'); } - return result; } - static Public? _createOrNull(int? value) => + static Public? _createOrNull(int? value) => value == null ? null : Public.fromValue(value); static const int minValue = 0; static const int maxValue = 0; - static bool containsValue(int value) => values.containsKey(value); - - static const Public NONE = Public._(0); - static const Map values = { - 0: NONE}; - static const fb.Reader reader = _PublicReader(); - - @override - String toString() { - return 'Public{value: $value}'; - } } class _PublicReader extends fb.Reader { @@ -95,39 +76,29 @@ class _PublicReader extends fb.Reader { Public.fromValue(const fb.Int32Reader().read(bc, offset)); } -class KeywordsInUnionTypeId { +enum KeywordsInUnionTypeId { + NONE(0), + $static(1), + internal(2); + final int value; - const KeywordsInUnionTypeId._(this.value); + const KeywordsInUnionTypeId(this.value); factory KeywordsInUnionTypeId.fromValue(int value) { - final result = values[value]; - if (result == null) { - throw StateError('Invalid value $value for bit flag enum KeywordsInUnionTypeId'); + switch (value) { + case 0: return KeywordsInUnionTypeId.NONE; + case 1: return KeywordsInUnionTypeId.$static; + case 2: return KeywordsInUnionTypeId.internal; + default: throw StateError('Invalid value $value for bit flag enum'); } - return result; } - static KeywordsInUnionTypeId? _createOrNull(int? value) => + static KeywordsInUnionTypeId? _createOrNull(int? value) => value == null ? null : KeywordsInUnionTypeId.fromValue(value); static const int minValue = 0; static const int maxValue = 2; - static bool containsValue(int value) => values.containsKey(value); - - static const KeywordsInUnionTypeId NONE = KeywordsInUnionTypeId._(0); - static const KeywordsInUnionTypeId $static = KeywordsInUnionTypeId._(1); - static const KeywordsInUnionTypeId internal = KeywordsInUnionTypeId._(2); - static const Map values = { - 0: NONE, - 1: $static, - 2: internal}; - static const fb.Reader reader = _KeywordsInUnionTypeIdReader(); - - @override - String toString() { - return 'KeywordsInUnionTypeId{value: $value}'; - } } class _KeywordsInUnionTypeIdReader extends fb.Reader { @@ -278,3 +249,122 @@ class KeywordsInTableObjectBuilder extends fb.ObjectBuilder { return fbBuilder.buffer; } } +class Table2 { + Table2._(this._bc, this._bcOffset); + factory Table2(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = _Table2Reader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + KeywordsInUnionTypeId? get typeType => KeywordsInUnionTypeId._createOrNull(const fb.Uint8Reader().vTableGetNullable(_bc, _bcOffset, 4)); + dynamic get type { + switch (typeType?.value) { + case 1: return KeywordsInTable.reader.vTableGetNullable(_bc, _bcOffset, 6); + case 2: return KeywordsInTable.reader.vTableGetNullable(_bc, _bcOffset, 6); + default: return null; + } + } + + @override + String toString() { + return 'Table2{typeType: ${typeType}, type: ${type}}'; + } + + Table2T unpack() => Table2T( + typeType: typeType, + type: type?.unpack()); + + static int pack(fb.Builder fbBuilder, Table2T? object) { + if (object == null) return 0; + return object.pack(fbBuilder); + } +} + +class Table2T implements fb.Packable { + KeywordsInUnionTypeId? typeType; + dynamic type; + + Table2T({ + this.typeType, + this.type}); + + @override + int pack(fb.Builder fbBuilder) { + final int? typeOffset = type?.pack(fbBuilder); + fbBuilder.startTable(2); + fbBuilder.addUint8(0, typeType?.value); + fbBuilder.addOffset(1, typeOffset); + return fbBuilder.endTable(); + } + + @override + String toString() { + return 'Table2T{typeType: ${typeType}, type: ${type}}'; + } +} + +class _Table2Reader extends fb.TableReader { + const _Table2Reader(); + + @override + Table2 createObject(fb.BufferContext bc, int offset) => + Table2._(bc, offset); +} + +class Table2Builder { + Table2Builder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(2); + } + + int addTypeType(KeywordsInUnionTypeId? typeType) { + fbBuilder.addUint8(0, typeType?.value); + return fbBuilder.offset; + } + int addTypeOffset(int? offset) { + fbBuilder.addOffset(1, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class Table2ObjectBuilder extends fb.ObjectBuilder { + final KeywordsInUnionTypeId? _typeType; + final dynamic _type; + + Table2ObjectBuilder({ + KeywordsInUnionTypeId? typeType, + dynamic type, + }) + : _typeType = typeType, + _type = type; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? typeOffset = _type?.getOrCreateOffset(fbBuilder); + fbBuilder.startTable(2); + fbBuilder.addUint8(0, _typeType?.value); + fbBuilder.addOffset(1, typeOffset); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} diff --git a/dart/test/monster_test.fbs b/dart/test/monster_test.fbs index 14d34cb4ab..b40ecf58f9 100644 --- a/dart/test/monster_test.fbs +++ b/dart/test/monster_test.fbs @@ -141,6 +141,15 @@ table Monster { // enum value. long_enum_non_enum_default:LongEnum (id: 52); long_enum_normal_default:LongEnum = LongOne (id: 53); + // Test that default values nan and +/-inf work. + nan_default:float = nan (id: 54); + inf_default:float = inf (id: 55); + positive_inf_default:float = +inf (id: 56); + infinity_default:float = infinity (id: 57); + positive_infinity_default:float = +infinity (id: 58); + negative_inf_default:float = -inf (id: 59); + negative_infinity_default:float = -infinity (id: 60); + double_inf_default:double = inf (id: 61); } table TypeAliases { diff --git a/dart/test/monster_test_my_game.example2_generated.dart b/dart/test/monster_test_my_game.example2_generated.dart index 24ccf72132..8f7893fcd1 100644 --- a/dart/test/monster_test_my_game.example2_generated.dart +++ b/dart/test/monster_test_my_game.example2_generated.dart @@ -1,13 +1,15 @@ // automatically generated by the FlatBuffers compiler, do not modify -// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable +// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable, constant_identifier_names 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 './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); @@ -21,7 +23,6 @@ class Monster { final fb.BufferContext _bc; final int _bcOffset; - @override String toString() { return 'Monster{}'; @@ -52,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 174fe1d8dd..9a791353e3 100644 --- a/dart/test/monster_test_my_game.example_generated.dart +++ b/dart/test/monster_test_my_game.example_generated.dart @@ -1,55 +1,45 @@ // automatically generated by the FlatBuffers compiler, do not modify -// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable +// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable, constant_identifier_names 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 './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. -class Color { +enum Color { + Red(1), + Green(2), + Blue(8), + _default(0); + final int value; - const Color._(this.value); + const Color(this.value); factory Color.fromValue(int value) { - final result = values[value]; - if (result == null) { - if (value == 0) { - return Color._(0); - } else { - throw StateError('Invalid value $value for bit flag enum Color'); - } + 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'); } - return result; } - static Color? _createOrNull(int? value) => + static Color? _createOrNull(int? value) => value == null ? null : Color.fromValue(value); - static bool containsValue(int value) => values.containsKey(value); - - static const Color Red = Color._(1); - - /// \brief color Green - /// Green is bit_flag with value (1u << 1) - static const Color Green = Color._(2); - - /// \brief color Blue (1u << 3) - static const Color Blue = Color._(8); - static const Map values = { - 1: Red, - 2: Green, - 8: Blue}; - static const fb.Reader reader = _ColorReader(); - - @override - String toString() { - return 'Color{value: $value}'; - } } class _ColorReader extends fb.Reader { @@ -63,41 +53,36 @@ class _ColorReader extends fb.Reader { Color.fromValue(const fb.Uint8Reader().read(bc, offset)); } -class Race { +enum Race { + None(-1), + Human(0), + Dwarf(1), + Elf(2); + final int value; - const Race._(this.value); + const Race(this.value); factory Race.fromValue(int value) { - final result = values[value]; - if (result == null) { - throw StateError('Invalid value $value for bit flag enum Race'); + 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'); } - return result; } - static Race? _createOrNull(int? value) => + static Race? _createOrNull(int? value) => value == null ? null : Race.fromValue(value); static const int minValue = -1; static const int maxValue = 2; - static bool containsValue(int value) => values.containsKey(value); - - static const Race None = Race._(-1); - static const Race Human = Race._(0); - static const Race Dwarf = Race._(1); - static const Race Elf = Race._(2); - static const Map values = { - -1: None, - 0: Human, - 1: Dwarf, - 2: Elf}; - static const fb.Reader reader = _RaceReader(); - - @override - String toString() { - return 'Race{value: $value}'; - } } class _RaceReader extends fb.Reader { @@ -111,41 +96,34 @@ class _RaceReader extends fb.Reader { Race.fromValue(const fb.Int8Reader().read(bc, offset)); } -class LongEnum { +enum LongEnum { + LongOne(2), + LongTwo(4), + LongBig(1099511627776), + _default(0); + final int value; - const LongEnum._(this.value); + const LongEnum(this.value); factory LongEnum.fromValue(int value) { - final result = values[value]; - if (result == null) { - if (value == 0) { - return LongEnum._(0); - } else { - throw StateError('Invalid value $value for bit flag enum LongEnum'); - } + 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'); } - return result; } - static LongEnum? _createOrNull(int? value) => + static LongEnum? _createOrNull(int? value) => value == null ? null : LongEnum.fromValue(value); - static bool containsValue(int value) => values.containsKey(value); - - static const LongEnum LongOne = LongEnum._(2); - static const LongEnum LongTwo = LongEnum._(4); - static const LongEnum LongBig = LongEnum._(1099511627776); - static const Map values = { - 2: LongOne, - 4: LongTwo, - 1099511627776: LongBig}; - static const fb.Reader reader = _LongEnumReader(); - - @override - String toString() { - return 'LongEnum{value: $value}'; - } } class _LongEnumReader extends fb.Reader { @@ -159,41 +137,36 @@ class _LongEnumReader extends fb.Reader { LongEnum.fromValue(const fb.Uint64Reader().read(bc, offset)); } -class AnyTypeId { +enum AnyTypeId { + NONE(0), + Monster(1), + TestSimpleTableWithEnum(2), + MyGame_Example2_Monster(3); + final int value; - const AnyTypeId._(this.value); + const AnyTypeId(this.value); factory AnyTypeId.fromValue(int value) { - final result = values[value]; - if (result == null) { - throw StateError('Invalid value $value for bit flag enum AnyTypeId'); + 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'); } - return result; } - static AnyTypeId? _createOrNull(int? value) => + static AnyTypeId? _createOrNull(int? value) => value == null ? null : AnyTypeId.fromValue(value); static const int minValue = 0; static const int maxValue = 3; - static bool containsValue(int value) => values.containsKey(value); - - static const AnyTypeId NONE = AnyTypeId._(0); - static const AnyTypeId Monster = AnyTypeId._(1); - static const AnyTypeId TestSimpleTableWithEnum = AnyTypeId._(2); - static const AnyTypeId MyGame_Example2_Monster = AnyTypeId._(3); - static const Map values = { - 0: NONE, - 1: Monster, - 2: TestSimpleTableWithEnum, - 3: MyGame_Example2_Monster}; - static const fb.Reader reader = _AnyTypeIdReader(); - - @override - String toString() { - return 'AnyTypeId{value: $value}'; - } } class _AnyTypeIdReader extends fb.Reader { @@ -207,41 +180,37 @@ class _AnyTypeIdReader extends fb.Reader { AnyTypeId.fromValue(const fb.Uint8Reader().read(bc, offset)); } -class AnyUniqueAliasesTypeId { +enum AnyUniqueAliasesTypeId { + NONE(0), + M(1), + TS(2), + M2(3); + final int value; - const AnyUniqueAliasesTypeId._(this.value); + const AnyUniqueAliasesTypeId(this.value); factory AnyUniqueAliasesTypeId.fromValue(int value) { - final result = values[value]; - if (result == null) { - throw StateError('Invalid value $value for bit flag enum AnyUniqueAliasesTypeId'); + 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'); } - return result; } - static AnyUniqueAliasesTypeId? _createOrNull(int? value) => + static AnyUniqueAliasesTypeId? _createOrNull(int? value) => value == null ? null : AnyUniqueAliasesTypeId.fromValue(value); static const int minValue = 0; static const int maxValue = 3; - static bool containsValue(int value) => values.containsKey(value); - - static const AnyUniqueAliasesTypeId NONE = AnyUniqueAliasesTypeId._(0); - static const AnyUniqueAliasesTypeId M = AnyUniqueAliasesTypeId._(1); - static const AnyUniqueAliasesTypeId TS = AnyUniqueAliasesTypeId._(2); - static const AnyUniqueAliasesTypeId M2 = AnyUniqueAliasesTypeId._(3); - static const Map values = { - 0: NONE, - 1: M, - 2: TS, - 3: M2}; - - static const fb.Reader reader = _AnyUniqueAliasesTypeIdReader(); - - @override - String toString() { - return 'AnyUniqueAliasesTypeId{value: $value}'; - } + static const fb.Reader reader = + _AnyUniqueAliasesTypeIdReader(); } class _AnyUniqueAliasesTypeIdReader extends fb.Reader { @@ -255,44 +224,41 @@ class _AnyUniqueAliasesTypeIdReader extends fb.Reader { AnyUniqueAliasesTypeId.fromValue(const fb.Uint8Reader().read(bc, offset)); } -class AnyAmbiguousAliasesTypeId { +enum AnyAmbiguousAliasesTypeId { + NONE(0), + M1(1), + M2(2), + M3(3); + final int value; - const AnyAmbiguousAliasesTypeId._(this.value); + const AnyAmbiguousAliasesTypeId(this.value); factory AnyAmbiguousAliasesTypeId.fromValue(int value) { - final result = values[value]; - if (result == null) { - throw StateError('Invalid value $value for bit flag enum AnyAmbiguousAliasesTypeId'); + 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'); } - return result; } - static AnyAmbiguousAliasesTypeId? _createOrNull(int? value) => + static AnyAmbiguousAliasesTypeId? _createOrNull(int? value) => value == null ? null : AnyAmbiguousAliasesTypeId.fromValue(value); static const int minValue = 0; static const int maxValue = 3; - static bool containsValue(int value) => values.containsKey(value); - - static const AnyAmbiguousAliasesTypeId NONE = AnyAmbiguousAliasesTypeId._(0); - static const AnyAmbiguousAliasesTypeId M1 = AnyAmbiguousAliasesTypeId._(1); - static const AnyAmbiguousAliasesTypeId M2 = AnyAmbiguousAliasesTypeId._(2); - static const AnyAmbiguousAliasesTypeId M3 = AnyAmbiguousAliasesTypeId._(3); - static const Map values = { - 0: NONE, - 1: M1, - 2: M2, - 3: M3}; - - static const fb.Reader reader = _AnyAmbiguousAliasesTypeIdReader(); - - @override - String toString() { - return 'AnyAmbiguousAliasesTypeId{value: $value}'; - } + static const fb.Reader reader = + _AnyAmbiguousAliasesTypeIdReader(); } -class _AnyAmbiguousAliasesTypeIdReader extends fb.Reader { +class _AnyAmbiguousAliasesTypeIdReader + extends fb.Reader { const _AnyAmbiguousAliasesTypeIdReader(); @override @@ -300,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 { @@ -319,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; @@ -333,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) { @@ -358,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 { @@ -373,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 @@ -404,6 +361,7 @@ class TestObjectBuilder extends fb.ObjectBuilder { return fbBuilder.buffer; } } + class TestSimpleTableWithEnum { TestSimpleTableWithEnum._(this._bc, this._bcOffset); factory TestSimpleTableWithEnum(List bytes) { @@ -411,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; @@ -435,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) { @@ -451,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 { @@ -481,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 @@ -502,6 +458,7 @@ class TestSimpleTableWithEnumObjectBuilder extends fb.ObjectBuilder { return fbBuilder.buffer; } } + class Vec3 { Vec3._(this._bc, this._bcOffset); @@ -514,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 @@ -523,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; @@ -545,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) { @@ -579,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 { @@ -588,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); @@ -600,7 +566,6 @@ class Vec3Builder { fbBuilder.putFloat32(x); return fbBuilder.offset; } - } class Vec3ObjectBuilder extends fb.ObjectBuilder { @@ -618,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 @@ -649,6 +613,7 @@ class Vec3ObjectBuilder extends fb.ObjectBuilder { return fbBuilder.buffer; } } + class Ability { Ability._(this._bc, this._bcOffset); @@ -665,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; @@ -679,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) { @@ -703,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 { @@ -717,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 @@ -747,6 +704,7 @@ class AbilityObjectBuilder extends fb.ObjectBuilder { return fbBuilder.buffer; } } + class StructOfStructs { StructOfStructs._(this._bc, this._bcOffset); @@ -764,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; @@ -780,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) { @@ -806,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 { @@ -821,7 +774,6 @@ class StructOfStructsBuilder { a(); return fbBuilder.offset; } - } class StructOfStructsObjectBuilder extends fb.ObjectBuilder { @@ -833,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 @@ -855,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; @@ -870,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; @@ -882,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) { @@ -897,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 { @@ -917,7 +870,6 @@ class StructOfStructsOfStructsBuilder { a(); return fbBuilder.offset; } - } class StructOfStructsOfStructsObjectBuilder extends fb.ObjectBuilder { @@ -925,8 +877,7 @@ class StructOfStructsOfStructsObjectBuilder extends fb.ObjectBuilder { StructOfStructsOfStructsObjectBuilder({ required StructOfStructsObjectBuilder a, - }) - : _a = a; + }) : _a = a; /// Finish building, and store into the [fbBuilder]. @override @@ -943,6 +894,7 @@ class StructOfStructsOfStructsObjectBuilder extends fb.ObjectBuilder { return fbBuilder.buffer; } } + class Stat { Stat._(this._bc, this._bcOffset); factory Stat(List bytes) { @@ -955,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); @@ -964,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; @@ -980,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); @@ -1006,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 { @@ -1023,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; @@ -1042,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); @@ -1071,6 +1013,7 @@ class StatObjectBuilder extends fb.ObjectBuilder { return fbBuilder.buffer; } } + class Referrable { Referrable._(this._bc, this._bcOffset); factory Referrable(List bytes) { @@ -1090,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; @@ -1102,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) { @@ -1122,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 { @@ -1148,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 @@ -1169,6 +1107,7 @@ class ReferrableObjectBuilder extends fb.ObjectBuilder { return fbBuilder.buffer; } } + /// an example documentation comment: "monster object" class Monster { Monster._(this._bc, this._bcOffset); @@ -1185,139 +1124,272 @@ 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)); + 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() { - return 'Monster{pos: ${pos}, mana: ${mana}, hp: ${hp}, name: ${name}, inventory: ${inventory}, color: ${color}, testType: ${testType}, test: ${test}, test4: ${test4}, testarrayofstring: ${testarrayofstring}, testarrayoftables: ${testarrayoftables}, enemy: ${enemy}, testnestedflatbuffer: ${testnestedflatbuffer}, testempty: ${testempty}, testbool: ${testbool}, testhashs32Fnv1: ${testhashs32Fnv1}, testhashu32Fnv1: ${testhashu32Fnv1}, testhashs64Fnv1: ${testhashs64Fnv1}, testhashu64Fnv1: ${testhashu64Fnv1}, testhashs32Fnv1a: ${testhashs32Fnv1a}, testhashu32Fnv1a: ${testhashu32Fnv1a}, testhashs64Fnv1a: ${testhashs64Fnv1a}, testhashu64Fnv1a: ${testhashu64Fnv1a}, testarrayofbools: ${testarrayofbools}, testf: ${testf}, testf2: ${testf2}, testf3: ${testf3}, testarrayofstring2: ${testarrayofstring2}, testarrayofsortedstruct: ${testarrayofsortedstruct}, flex: ${flex}, test5: ${test5}, vectorOfLongs: ${vectorOfLongs}, vectorOfDoubles: ${vectorOfDoubles}, parentNamespaceTest: ${parentNamespaceTest}, vectorOfReferrables: ${vectorOfReferrables}, singleWeakReference: ${singleWeakReference}, vectorOfWeakReferences: ${vectorOfWeakReferences}, vectorOfStrongReferrables: ${vectorOfStrongReferrables}, coOwningReference: ${coOwningReference}, vectorOfCoOwningReferences: ${vectorOfCoOwningReferences}, nonOwningReference: ${nonOwningReference}, vectorOfNonOwningReferences: ${vectorOfNonOwningReferences}, anyUniqueType: ${anyUniqueType}, anyUnique: ${anyUnique}, anyAmbiguousType: ${anyAmbiguousType}, anyAmbiguous: ${anyAmbiguous}, vectorOfEnums: ${vectorOfEnums}, signedEnum: ${signedEnum}, testrequirednestedflatbuffer: ${testrequirednestedflatbuffer}, scalarKeySortedTables: ${scalarKeySortedTables}, nativeInline: ${nativeInline}, longEnumNonEnumDefault: ${longEnumNonEnumDefault}, longEnumNormalDefault: ${longEnumNormalDefault}}'; + return 'Monster{pos: ${pos}, mana: ${mana}, hp: ${hp}, name: ${name}, inventory: ${inventory}, color: ${color}, testType: ${testType}, test: ${test}, test4: ${test4}, testarrayofstring: ${testarrayofstring}, testarrayoftables: ${testarrayoftables}, enemy: ${enemy}, testnestedflatbuffer: ${testnestedflatbuffer}, testempty: ${testempty}, testbool: ${testbool}, testhashs32Fnv1: ${testhashs32Fnv1}, testhashu32Fnv1: ${testhashu32Fnv1}, testhashs64Fnv1: ${testhashs64Fnv1}, testhashu64Fnv1: ${testhashu64Fnv1}, testhashs32Fnv1a: ${testhashs32Fnv1a}, testhashu32Fnv1a: ${testhashu32Fnv1a}, testhashs64Fnv1a: ${testhashs64Fnv1a}, testhashu64Fnv1a: ${testhashu64Fnv1a}, testarrayofbools: ${testarrayofbools}, testf: ${testf}, testf2: ${testf2}, testf3: ${testf3}, testarrayofstring2: ${testarrayofstring2}, testarrayofsortedstruct: ${testarrayofsortedstruct}, flex: ${flex}, test5: ${test5}, vectorOfLongs: ${vectorOfLongs}, vectorOfDoubles: ${vectorOfDoubles}, parentNamespaceTest: ${parentNamespaceTest}, vectorOfReferrables: ${vectorOfReferrables}, singleWeakReference: ${singleWeakReference}, vectorOfWeakReferences: ${vectorOfWeakReferences}, vectorOfStrongReferrables: ${vectorOfStrongReferrables}, coOwningReference: ${coOwningReference}, vectorOfCoOwningReferences: ${vectorOfCoOwningReferences}, nonOwningReference: ${nonOwningReference}, vectorOfNonOwningReferences: ${vectorOfNonOwningReferences}, anyUniqueType: ${anyUniqueType}, anyUnique: ${anyUnique}, anyAmbiguousType: ${anyAmbiguousType}, anyAmbiguous: ${anyAmbiguous}, vectorOfEnums: ${vectorOfEnums}, signedEnum: ${signedEnum}, testrequirednestedflatbuffer: ${testrequirednestedflatbuffer}, scalarKeySortedTables: ${scalarKeySortedTables}, nativeInline: ${nativeInline}, longEnumNonEnumDefault: ${longEnumNonEnumDefault}, longEnumNormalDefault: ${longEnumNormalDefault}, nanDefault: ${nanDefault}, infDefault: ${infDefault}, positiveInfDefault: ${positiveInfDefault}, infinityDefault: ${infinityDefault}, positiveInfinityDefault: ${positiveInfinityDefault}, negativeInfDefault: ${negativeInfDefault}, negativeInfinityDefault: ${negativeInfinityDefault}, doubleInfDefault: ${doubleInfDefault}}'; } 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); + pos: pos?.unpack(), + mana: mana, + hp: hp, + name: name, + inventory: inventory?.toList(), + color: color, + testType: testType, + test: test?.unpack(), + test4: test4?.map((e) => e.unpack()).toList(), + testarrayofstring: testarrayofstring?.toList(), + testarrayoftables: testarrayoftables?.map((e) => e.unpack()).toList(), + enemy: enemy?.unpack(), + testnestedflatbuffer: testnestedflatbuffer?.toList(), + testempty: testempty?.unpack(), + testbool: testbool, + testhashs32Fnv1: testhashs32Fnv1, + testhashu32Fnv1: testhashu32Fnv1, + testhashs64Fnv1: testhashs64Fnv1, + testhashu64Fnv1: testhashu64Fnv1, + testhashs32Fnv1a: testhashs32Fnv1a, + testhashu32Fnv1a: testhashu32Fnv1a, + testhashs64Fnv1a: testhashs64Fnv1a, + testhashu64Fnv1a: testhashu64Fnv1a, + testarrayofbools: testarrayofbools?.toList(), + testf: testf, + testf2: testf2, + testf3: testf3, + testarrayofstring2: testarrayofstring2?.toList(), + testarrayofsortedstruct: testarrayofsortedstruct?.map((e) => e.unpack()).toList(), + flex: flex?.toList(), + test5: test5?.map((e) => e.unpack()).toList(), + vectorOfLongs: vectorOfLongs?.toList(), + vectorOfDoubles: vectorOfDoubles?.toList(), + parentNamespaceTest: parentNamespaceTest?.unpack(), + vectorOfReferrables: vectorOfReferrables?.map((e) => e.unpack()).toList(), + singleWeakReference: singleWeakReference, + vectorOfWeakReferences: vectorOfWeakReferences?.toList(), + vectorOfStrongReferrables: vectorOfStrongReferrables?.map((e) => e.unpack()).toList(), + coOwningReference: coOwningReference, + vectorOfCoOwningReferences: vectorOfCoOwningReferences?.toList(), + nonOwningReference: nonOwningReference, + vectorOfNonOwningReferences: vectorOfNonOwningReferences?.toList(), + anyUniqueType: anyUniqueType, + anyUnique: anyUnique?.unpack(), + anyAmbiguousType: anyAmbiguousType, + anyAmbiguous: anyAmbiguous?.unpack(), + vectorOfEnums: vectorOfEnums?.toList(), + signedEnum: signedEnum, + testrequirednestedflatbuffer: testrequirednestedflatbuffer?.toList(), + 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; @@ -1337,6 +1409,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; @@ -1382,122 +1455,179 @@ class MonsterT implements fb.Packable { TestT? nativeInline; LongEnum longEnumNonEnumDefault; LongEnum longEnumNormalDefault; + double nanDefault; + double infDefault; + double positiveInfDefault; + double infinityDefault; + double positiveInfinityDefault; + double negativeInfDefault; + double negativeInfinityDefault; + 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 = const LongEnum._(0), - this.longEnumNormalDefault = LongEnum.LongOne}); + 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!.reversed) { + 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!.reversed) { + 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!.reversed) { + 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()); - fbBuilder.startTable(54); + 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)); } @@ -1555,12 +1685,20 @@ class MonsterT implements fb.Packable { } fbBuilder.addUint64(52, longEnumNonEnumDefault.value); fbBuilder.addUint64(53, longEnumNormalDefault.value); + fbBuilder.addFloat32(54, nanDefault); + fbBuilder.addFloat32(55, infDefault); + fbBuilder.addFloat32(56, positiveInfDefault); + fbBuilder.addFloat32(57, infinityDefault); + fbBuilder.addFloat32(58, positiveInfinityDefault); + fbBuilder.addFloat32(59, negativeInfDefault); + fbBuilder.addFloat32(60, negativeInfinityDefault); + fbBuilder.addFloat64(61, doubleInfDefault); return fbBuilder.endTable(); } @override String toString() { - return 'MonsterT{pos: ${pos}, mana: ${mana}, hp: ${hp}, name: ${name}, inventory: ${inventory}, color: ${color}, testType: ${testType}, test: ${test}, test4: ${test4}, testarrayofstring: ${testarrayofstring}, testarrayoftables: ${testarrayoftables}, enemy: ${enemy}, testnestedflatbuffer: ${testnestedflatbuffer}, testempty: ${testempty}, testbool: ${testbool}, testhashs32Fnv1: ${testhashs32Fnv1}, testhashu32Fnv1: ${testhashu32Fnv1}, testhashs64Fnv1: ${testhashs64Fnv1}, testhashu64Fnv1: ${testhashu64Fnv1}, testhashs32Fnv1a: ${testhashs32Fnv1a}, testhashu32Fnv1a: ${testhashu32Fnv1a}, testhashs64Fnv1a: ${testhashs64Fnv1a}, testhashu64Fnv1a: ${testhashu64Fnv1a}, testarrayofbools: ${testarrayofbools}, testf: ${testf}, testf2: ${testf2}, testf3: ${testf3}, testarrayofstring2: ${testarrayofstring2}, testarrayofsortedstruct: ${testarrayofsortedstruct}, flex: ${flex}, test5: ${test5}, vectorOfLongs: ${vectorOfLongs}, vectorOfDoubles: ${vectorOfDoubles}, parentNamespaceTest: ${parentNamespaceTest}, vectorOfReferrables: ${vectorOfReferrables}, singleWeakReference: ${singleWeakReference}, vectorOfWeakReferences: ${vectorOfWeakReferences}, vectorOfStrongReferrables: ${vectorOfStrongReferrables}, coOwningReference: ${coOwningReference}, vectorOfCoOwningReferences: ${vectorOfCoOwningReferences}, nonOwningReference: ${nonOwningReference}, vectorOfNonOwningReferences: ${vectorOfNonOwningReferences}, anyUniqueType: ${anyUniqueType}, anyUnique: ${anyUnique}, anyAmbiguousType: ${anyAmbiguousType}, anyAmbiguous: ${anyAmbiguous}, vectorOfEnums: ${vectorOfEnums}, signedEnum: ${signedEnum}, testrequirednestedflatbuffer: ${testrequirednestedflatbuffer}, scalarKeySortedTables: ${scalarKeySortedTables}, nativeInline: ${nativeInline}, longEnumNonEnumDefault: ${longEnumNonEnumDefault}, longEnumNormalDefault: ${longEnumNormalDefault}}'; + return 'MonsterT{pos: ${pos}, mana: ${mana}, hp: ${hp}, name: ${name}, inventory: ${inventory}, color: ${color}, testType: ${testType}, test: ${test}, test4: ${test4}, testarrayofstring: ${testarrayofstring}, testarrayoftables: ${testarrayoftables}, enemy: ${enemy}, testnestedflatbuffer: ${testnestedflatbuffer}, testempty: ${testempty}, testbool: ${testbool}, testhashs32Fnv1: ${testhashs32Fnv1}, testhashu32Fnv1: ${testhashu32Fnv1}, testhashs64Fnv1: ${testhashs64Fnv1}, testhashu64Fnv1: ${testhashu64Fnv1}, testhashs32Fnv1a: ${testhashs32Fnv1a}, testhashu32Fnv1a: ${testhashu32Fnv1a}, testhashs64Fnv1a: ${testhashs64Fnv1a}, testhashu64Fnv1a: ${testhashu64Fnv1a}, testarrayofbools: ${testarrayofbools}, testf: ${testf}, testf2: ${testf2}, testf3: ${testf3}, testarrayofstring2: ${testarrayofstring2}, testarrayofsortedstruct: ${testarrayofsortedstruct}, flex: ${flex}, test5: ${test5}, vectorOfLongs: ${vectorOfLongs}, vectorOfDoubles: ${vectorOfDoubles}, parentNamespaceTest: ${parentNamespaceTest}, vectorOfReferrables: ${vectorOfReferrables}, singleWeakReference: ${singleWeakReference}, vectorOfWeakReferences: ${vectorOfWeakReferences}, vectorOfStrongReferrables: ${vectorOfStrongReferrables}, coOwningReference: ${coOwningReference}, vectorOfCoOwningReferences: ${vectorOfCoOwningReferences}, nonOwningReference: ${nonOwningReference}, vectorOfNonOwningReferences: ${vectorOfNonOwningReferences}, anyUniqueType: ${anyUniqueType}, anyUnique: ${anyUnique}, anyAmbiguousType: ${anyAmbiguousType}, anyAmbiguous: ${anyAmbiguous}, vectorOfEnums: ${vectorOfEnums}, signedEnum: ${signedEnum}, testrequirednestedflatbuffer: ${testrequirednestedflatbuffer}, scalarKeySortedTables: ${scalarKeySortedTables}, nativeInline: ${nativeInline}, longEnumNonEnumDefault: ${longEnumNonEnumDefault}, longEnumNormalDefault: ${longEnumNormalDefault}, nanDefault: ${nanDefault}, infDefault: ${infDefault}, positiveInfDefault: ${positiveInfDefault}, infinityDefault: ${infinityDefault}, positiveInfinityDefault: ${positiveInfinityDefault}, negativeInfDefault: ${negativeInfDefault}, negativeInfinityDefault: ${negativeInfinityDefault}, doubleInfDefault: ${doubleInfDefault}}'; } } @@ -1568,8 +1706,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 { @@ -1578,222 +1716,314 @@ class MonsterBuilder { final fb.Builder fbBuilder; void begin() { - fbBuilder.startTable(54); + fbBuilder.startTable(62); } int addPos(int offset) { 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; + } + int finish() { return fbBuilder.endTable(); } @@ -1853,6 +2083,14 @@ class MonsterObjectBuilder extends fb.ObjectBuilder { final TestObjectBuilder? _nativeInline; final LongEnum? _longEnumNonEnumDefault; final LongEnum? _longEnumNormalDefault; + final double? _nanDefault; + final double? _infDefault; + final double? _positiveInfDefault; + final double? _infinityDefault; + final double? _positiveInfinityDefault; + final double? _negativeInfDefault; + final double? _negativeInfinityDefault; + final double? _doubleInfDefault; MonsterObjectBuilder({ Vec3ObjectBuilder? pos, @@ -1908,113 +2146,176 @@ class MonsterObjectBuilder extends fb.ObjectBuilder { TestObjectBuilder? nativeInline, LongEnum? longEnumNonEnumDefault, LongEnum? longEnumNormalDefault, - }) - : _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; + double? nanDefault, + double? infDefault, + double? positiveInfDefault, + double? infinityDefault, + double? positiveInfinityDefault, + 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; /// 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()); - fbBuilder.startTable(54); + 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)); } @@ -2072,6 +2373,14 @@ class MonsterObjectBuilder extends fb.ObjectBuilder { } fbBuilder.addUint64(52, _longEnumNonEnumDefault?.value); fbBuilder.addUint64(53, _longEnumNormalDefault?.value); + fbBuilder.addFloat32(54, _nanDefault); + fbBuilder.addFloat32(55, _infDefault); + fbBuilder.addFloat32(56, _positiveInfDefault); + fbBuilder.addFloat32(57, _infinityDefault); + fbBuilder.addFloat32(58, _positiveInfinityDefault); + fbBuilder.addFloat32(59, _negativeInfDefault); + fbBuilder.addFloat32(60, _negativeInfinityDefault); + fbBuilder.addFloat64(61, _doubleInfDefault); return fbBuilder.endTable(); } @@ -2083,6 +2392,7 @@ class MonsterObjectBuilder extends fb.ObjectBuilder { return fbBuilder.buffer; } } + class TypeAliases { TypeAliases._(this._bc, this._bcOffset); factory TypeAliases(List bytes) { @@ -2105,8 +2415,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() { @@ -2114,18 +2427,19 @@ 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: v8?.toList(), + vf64: vf64?.toList(), + ); static int pack(fb.Builder fbBuilder, TypeAliasesT? object) { if (object == null) return 0; @@ -2148,24 +2462,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); @@ -2193,8 +2508,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 { @@ -2210,46 +2525,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; @@ -2287,26 +2613,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 70e256cab3..7b856bf725 100644 --- a/dart/test/monster_test_my_game_generated.dart +++ b/dart/test/monster_test_my_game_generated.dart @@ -1,13 +1,15 @@ // automatically generated by the FlatBuffers compiler, do not modify -// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable +// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable, constant_identifier_names 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 './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); @@ -21,7 +23,6 @@ class InParentNamespace { final fb.BufferContext _bc; final int _bcOffset; - @override String toString() { return 'InParentNamespace{}'; @@ -52,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 new file mode 100644 index 0000000000..06e4310f27 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,24 @@ +# Documentation + +This is the source of the FlatBuffers documentation, that is served at +https://flatbuffers.dev. + + +## Local Building + +The documentation can be built and served locally during development, see for full details. + +__tl;dr__ + +Install: + +``` +pip install mkdocs-material +pip install mkdocs-redirects +``` + +Build and Serve: + +``` +mkdocs serve -f docs/mkdocs.yml +``` diff --git a/docs/footer.html b/docs/footer.html deleted file mode 100644 index 42bc5f2b90..0000000000 --- a/docs/footer.html +++ /dev/null @@ -1,14 +0,0 @@ - - - - - diff --git a/docs/header.html b/docs/header.html deleted file mode 100644 index 0266e7c4f3..0000000000 --- a/docs/header.html +++ /dev/null @@ -1,62 +0,0 @@ - - - - - - - -$projectname: $title -$title - - - -$treeview -$search -$mathjax - - -$extrastylesheet - - -
- - -
- - - - - - - - - - - - - - - - - - - - - - -
-
$projectname -  $projectnumber -
-
- An open source project by FPL. -
-
$projectbrief
-
-
$projectbrief
-
$searchbox
-
- - diff --git a/docs/images/fpl_logo_small.png b/docs/images/fpl_logo_small.png deleted file mode 100644 index 2c728f3b54..0000000000 Binary files a/docs/images/fpl_logo_small.png and /dev/null differ diff --git a/docs/images/ftv2mnode.png b/docs/images/ftv2mnode.png deleted file mode 100644 index 3caf47df8a..0000000000 Binary files a/docs/images/ftv2mnode.png and /dev/null differ diff --git a/docs/images/ftv2pnode.png b/docs/images/ftv2pnode.png deleted file mode 100644 index f1aaad3786..0000000000 Binary files a/docs/images/ftv2pnode.png and /dev/null differ diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml new file mode 100644 index 0000000000..cbcbb48de2 --- /dev/null +++ b/docs/mkdocs.yml @@ -0,0 +1,159 @@ +site_name: FlatBuffers Docs +docs_dir: source +site_url: https://flatbuffers.dev +repo_name: google/FlatBuffers +repo_url: https://github.com/google/flatbuffers +edit_uri: edit/master/docs/source/ +copyright: Copyright © 2025 Google +theme: + name: material + logo: assets/flatbuffers_logo.svg + icon: + repo: fontawesome/brands/github + custom_dir: overrides + palette: + # Palette toggle for light mode + - scheme: default + toggle: + icon: material/brightness-7 + name: Switch to dark mode + + # Palette toggle for dark mode + - scheme: slate + toggle: + icon: material/brightness-4 + name: Switch to light mode + + features: + # Allows code block annotations + - content.code.annotate + + # Allows content tabs to link together + - content.tabs.link + + # Expand nav folders by default + - navigation.expand + + # Enable the footer + - navigation.footer + + # Auto hide the header after scrolling + - header.autohide + + - content.action.edit + +extra: + social: + - icon: fontawesome/brands/github + link: https://github.com/google/flatbuffers + + - icon: fontawesome/brands/discord + link: https:///discord.gg/6qgKs3R + + - icon: fontawesome/brands/x-twitter + link: https://twitter.com/dbaileychess + +plugins: + # Use redirects to update links from the original docs to the new ones. + # + # https://github.com/mkdocs/mkdocs-redirects + - redirects: + # Note the .html are suffixed with .md to avoid warnings. Got from + # https://github.com/mkdocs/mkdocs-redirects/issues/51#issuecomment-2408548029 + redirect_maps: + 'flatbuffers_guide_building.html.md': 'building.md' + 'flatbuffers_guide_tutorial.html.md': 'tutorial.md' + 'flatbuffers_guide_using_schema_compiler.html.md': 'flatc.md' + 'flatbuffers_guide_writing_schema.html.md': 'schema.md' + 'md__schemas.html.md': 'schema.md' # issue #8485 + 'flatbuffers_guide_use_c.html.md': 'languages/c.md' + 'flatbuffers_guide_use_cpp.html.md': 'languages/cpp.md' + 'flatbuffers_guide_use_c-sharp.html.md': 'languages/c_sharp.md' + 'flatbuffers_guide_use_dart.html.md': 'languages/dart.md' + 'flatbuffers_guide_use_go.html.md': 'languages/go.md' + 'flatbuffers_guide_use_java.html.md': 'languages/java.md' + 'flatbuffers_guide_use_javascript.html.md': 'languages/javascript.md' + 'flatbuffers_guide_use_lobster.html.md': 'languages/lobster.md' + 'flatbuffers_guide_use_lua.html.md': 'languages/lua.md' + 'flatbuffers_guide_use_php.html.md': 'languages/php.md' + 'flatbuffers_guide_use_python.html.md': 'languages/python.md' + 'flatbuffers_guide_use_rust.html.md': 'languages/rust.md' + 'flatbuffers_guide_use_swift.html.md': 'languages/swift.md' + 'flatbuffers_guide_use_typescript.html.md': 'languages/typescript.md' + 'flatbuffers_grpc_guide_use_cpp.html.md' : "languages/cpp.md#grpc" + 'flatbuffers_support.html.md': 'support.md' + 'flatbuffers_white_paper.html.md': 'white_paper.md' + 'flatbuffers_grammar.html.md': 'grammar.md' + 'flatbuffers_internals.html.md': 'internals.md' + 'intermediate_representation.html.md': 'intermediate_representation.md' + 'flatbuffers_benchmarks.html.md': 'benchmarks.md' + 'flexbuffers.html.md': 'flexbuffers.md' + 'contributing.html.md': 'contributing.md' + + +markdown_extensions: + - admonition + - attr_list + - md_in_html + - pymdownx.critic + - pymdownx.details + - pymdownx.emoji: + emoji_index: !!python/name:material.extensions.emoji.twemoji + emoji_generator: !!python/name:material.extensions.emoji.to_svg + - pymdownx.snippets: + # Allows direct embedded of remote files + url_download: true + - pymdownx.superfences + - pymdownx.tabbed: + alternate_style: true + slugify: !!python/object/apply:pymdownx.slugs.slugify + kwds: + case: lower + - pymdownx.highlight: + extend_pygments_lang: + # PHP wasn't highlighting correctly. This is a work around found + # https://github.com/squidfunk/mkdocs-material/issues/138#issuecomment-2294025627 + - name: php + lang: php + options: + startinline: true + - tables + + + +nav: + - Overview: "index.md" + - Quick Start: "quick_start.md" + - Tutorial: "tutorial.md" + - Compiler (flatc): + - Building: "building.md" + - Using: "flatc.md" + - Schema (.fbs): + - Overview: "schema.md" + - Evolution: "evolution.md" + - Grammar: "grammar.md" + - Language Guides: + - C: "languages/c.md" + - C++: "languages/cpp.md" + - C#: "languages/c_sharp.md" + - Dart: "languages/dart.md" + - Go: "languages/go.md" + - Java: "languages/java.md" + - JavaScript: "languages/javascript.md" + - Kotlin: "languages/kotlin.md" + - Lobster: "languages/lobster.md" + - Lua: "languages/lua.md" + - PHP: "languages/php.md" + - Python: "languages/python.md" + - Rust: "languages/rust.md" + - Swift: "languages/swift.md" + - TypeScript: "languages/typescript.md" + - Supported Configurations: "support.md" + - White Paper: "white_paper.md" + - Advanced: + - FlatBuffers Internals: "internals.md" + - Intermediate Representation: "intermediate_representation.md" + - Annotating Buffers (.afb): "annotation.md" + - Benchmarks: "benchmarks.md" + - FlexBuffers (Schema-less version): "flexbuffers.md" + - Contributing: "contributing.md" diff --git a/docs/overrides/404.html b/docs/overrides/404.html new file mode 100644 index 0000000000..f7981fcf4f --- /dev/null +++ b/docs/overrides/404.html @@ -0,0 +1,10 @@ +{% extends "main.html" %} + + +{% block content %} +

404 - Not found

+
+ FlatBuffers has migrated their documentation system recently. + + Please file an issue indicating the broken link. +{% endblock %} \ No newline at end of file diff --git a/docs/overrides/main.html b/docs/overrides/main.html new file mode 100644 index 0000000000..94d9808cc7 --- /dev/null +++ b/docs/overrides/main.html @@ -0,0 +1 @@ +{% extends "base.html" %} diff --git a/docs/source/CNAME b/docs/source/CNAME new file mode 100644 index 0000000000..398878ab79 --- /dev/null +++ b/docs/source/CNAME @@ -0,0 +1 @@ +flatbuffers.dev \ No newline at end of file diff --git a/docs/source/CONTRIBUTING.md b/docs/source/CONTRIBUTING.md deleted file mode 120000 index f939e75f21..0000000000 --- a/docs/source/CONTRIBUTING.md +++ /dev/null @@ -1 +0,0 @@ -../../CONTRIBUTING.md \ No newline at end of file diff --git a/docs/source/FlatBuffers.md b/docs/source/FlatBuffers.md deleted file mode 100644 index bbd2cb0f3f..0000000000 --- a/docs/source/FlatBuffers.md +++ /dev/null @@ -1,188 +0,0 @@ -FlatBuffers {#flatbuffers_index} -=========== - -# Overview {#flatbuffers_overview} - -[FlatBuffers](@ref flatbuffers_overview) is an efficient cross platform -serialization library for C++, C#, C, Go, Java, Kotlin, JavaScript, Lobster, Lua, TypeScript, PHP, Python, Rust and Swift. -It was originally created at Google for game development and other -performance-critical applications. - -It is available as Open Source on [GitHub](http://github.com/google/flatbuffers) -under the Apache license, v2 (see LICENSE.txt). - -## Why use FlatBuffers? - -- **Access to serialized data without parsing/unpacking** - What sets - FlatBuffers apart is that it represents hierarchical data in a flat - binary buffer in such a way that it can still be accessed directly - without parsing/unpacking, while also still supporting data - structure evolution (forwards/backwards compatibility). - -- **Memory efficiency and speed** - The only memory needed to access - your data is that of the buffer. It requires 0 additional allocations - (in C++, other languages may vary). FlatBuffers is also very - suitable for use with mmap (or streaming), requiring only part of the - buffer to be in memory. Access is close to the speed of raw - struct access with only one extra indirection (a kind of vtable) to - allow for format evolution and optional fields. It is aimed at - projects where spending time and space (many memory allocations) to - be able to access or construct serialized data is undesirable, such - as in games or any other performance sensitive applications. See the - [benchmarks](@ref flatbuffers_benchmarks) for details. - -- **Flexible** - Optional fields means not only do you get great - forwards and backwards compatibility (increasingly important for - long-lived games: don't have to update all data with each new - version!). It also means you have a lot of choice in what data you - write and what data you don't, and how you design data structures. - -- **Tiny code footprint** - Small amounts of generated code, and just - a single small header as the minimum dependency, which is very easy - to integrate. Again, see the benchmark section for details. - -- **Strongly typed** - Errors happen at compile time rather than - manually having to write repetitive and error prone run-time checks. - Useful code can be generated for you. - -- **Convenient to use** - Generated C++ code allows for terse access - & construction code. Then there's optional functionality for parsing - schemas and JSON-like text representations at runtime efficiently if - needed (faster and more memory efficient than other JSON - parsers). - - Java, Kotlin and Go code supports object-reuse. C# has efficient struct based - accessors. - -- **Cross platform code with no dependencies** - C++ code will work - with any recent gcc/clang and VS2010. Comes with build files for the tests & - samples (Android .mk files, and cmake for all other platforms). - -### Why not use Protocol Buffers, or .. ? - -Protocol Buffers is indeed relatively similar to FlatBuffers, -with the primary difference being that FlatBuffers does not need a parsing/ -unpacking step to a secondary representation before you can -access data, often coupled with per-object memory allocation. The code -is an order of magnitude bigger, too. Protocol Buffers has no optional -text import/export. - -### But all the cool kids use JSON! - -JSON is very readable (which is why we use it as our optional text -format) and very convenient when used together with dynamically typed -languages (such as JavaScript). When serializing data from statically -typed languages, however, JSON not only has the obvious drawback of runtime -inefficiency, but also forces you to write *more* code to access data -(counterintuitively) due to its dynamic-typing serialization system. -In this context, it is only a better choice for systems that have very -little to no information ahead of time about what data needs to be stored. - -If you do need to store data that doesn't fit a schema, FlatBuffers also -offers a schema-less (self-describing) version! - -Read more about the "why" of FlatBuffers in the -[white paper](@ref flatbuffers_white_paper). - -### Who uses FlatBuffers? -- [Cocos2d-x](http://www.cocos2d-x.org/), the #1 open source mobile game - engine, uses it to serialize all their - [game data](http://www.cocos2d-x.org/reference/native-cpp/V3.5/d7/d2d/namespaceflatbuffers.html). -- [Facebook](http://facebook.com/) uses it for client-server communication in - their Android app. They have a nice - [article](https://code.facebook.com/posts/872547912839369/improving-facebook-s-performance-on-android-with-flatbuffers/) - explaining how it speeds up loading their posts. -- [Fun Propulsion Labs](https://developers.google.com/games/#Tools) - at Google uses it extensively in all their libraries and games. - -## Usage in brief - -This section is a quick rundown of how to use this system. Subsequent -sections provide a more in-depth usage guide. - -- Write a schema file that allows you to define the data structures - you may want to serialize. Fields can have a scalar type - (ints/floats of all sizes), or they can be a: string; array of any type; - reference to yet another object; or, a set of possible objects (unions). - Fields are optional and have defaults, so they don't need to be - present for every object instance. - -- Use `flatc` (the FlatBuffer compiler) to generate a C++ header (or - Java/Kotlin/C#/Go/Python.. classes) with helper classes to access and construct - serialized data. This header (say `mydata_generated.h`) only depends on - `flatbuffers.h`, which defines the core functionality. - -- Use the `FlatBufferBuilder` class to construct a flat binary buffer. - The generated functions allow you to add objects to this - buffer recursively, often as simply as making a single function call. - -- Store or send your buffer somewhere! - -- When reading it back, you can obtain the pointer to the root object - from the binary buffer, and from there traverse it conveniently - in-place with `object->field()`. - -## In-depth documentation - -- How to [build the compiler](@ref flatbuffers_guide_building) and samples on - various platforms. -- How to [use the compiler](@ref flatbuffers_guide_using_schema_compiler). -- How to [write a schema](@ref flatbuffers_guide_writing_schema). -- How to [use the generated C++ code](@ref flatbuffers_guide_use_cpp) in your - own programs. -- How to [use the generated Java code](@ref flatbuffers_guide_use_java) - in your own programs. -- How to [use the generated C# code](@ref flatbuffers_guide_use_c-sharp) - in your own programs. -- How to [use the generated Kotlin code](@ref flatbuffers_guide_use_kotlin) - in your own programs. -- How to [use the generated Go code](@ref flatbuffers_guide_use_go) in your - own programs. -- How to [use the generated Lua code](@ref flatbuffers_guide_use_lua) in your - own programs. -- How to [use the generated JavaScript code](@ref flatbuffers_guide_use_javascript) in your - own programs. -- How to [use the generated TypeScript code](@ref flatbuffers_guide_use_typescript) in your - own programs. -- How to [use FlatBuffers in C with `flatcc`](@ref flatbuffers_guide_use_c) in your - own programs. -- How to [use the generated Lobster code](@ref flatbuffers_guide_use_lobster) in your - own programs. -- How to [use the generated Rust code](@ref flatbuffers_guide_use_rust) in your - own programs. -- How to [use the generated Swift code](@ref flatbuffers_guide_use_swift) in your - own programs. -- [Support matrix](@ref flatbuffers_support) for platforms/languages/features. -- Some [benchmarks](@ref flatbuffers_benchmarks) showing the advantage of - using FlatBuffers. -- A [white paper](@ref flatbuffers_white_paper) explaining the "why" of - FlatBuffers. -- How to use the [schema-less](@ref flexbuffers) version of - FlatBuffers. -- A description of the [internals](@ref flatbuffers_internals) of FlatBuffers. -- A formal [grammar](@ref flatbuffers_grammar) of the schema language. - -## Online resources - -- [GitHub repository](http://github.com/google/flatbuffers) -- [Landing page](http://google.github.io/flatbuffers) -- [FlatBuffers Google Group](https://groups.google.com/forum/#!forum/flatbuffers) -- [Discord](https://discord.gg/6qgKs3R) and [Gitter](https://gitter.im/lobster_programming_language/community) chat. -- [FlatBuffers Issues Tracker](http://github.com/google/flatbuffers/issues) -- Independent implementations & tools: - - [FlatCC](https://github.com/dvidelabs/flatcc) Alternative FlatBuffers - parser, code generator and runtime all in C. -- Videos: - - Colt's [DevByte](https://www.youtube.com/watch?v=iQTxMkSJ1dQ). - - GDC 2015 [Lightning Talk](https://www.youtube.com/watch?v=olmL1fUnQAQ). - - FlatBuffers for [Go](https://www.youtube.com/watch?v=-BPVId_lA5w). - - Evolution of FlatBuffers - [visualization](https://www.youtube.com/watch?v=a0QE0xS8rKM). -- Useful documentation created by others: - - [FlatBuffers in Go](https://rwinslow.com/tags/flatbuffers/) - - [FlatBuffers in Android](http://frogermcs.github.io/flatbuffers-in-android-introdution/) - - [Parsing JSON to FlatBuffers in Java](http://frogermcs.github.io/json-parsing-with-flatbuffers-in-android/) - - [FlatBuffers in Unity](http://exiin.com/blog/flatbuffers-for-unity-sample-code/) - - [FlexBuffers C#](https://github.com/mzaks/FlexBuffers-CSharp) and - [article](https://medium.com/@icex33/flexbuffers-for-unity3d-4d1ab5c53fbe?) - on its use. diff --git a/docs/source/GoApi.md b/docs/source/GoApi.md deleted file mode 100644 index 98be2b6a9e..0000000000 --- a/docs/source/GoApi.md +++ /dev/null @@ -1,26 +0,0 @@ -Go API -====== - -\addtogroup flatbuffers_go_api - - -\snippet GoApi_generated.txt Go API diff --git a/docs/source/GoApi_generated.txt b/docs/source/GoApi_generated.txt deleted file mode 100644 index 3d4e0fc77a..0000000000 --- a/docs/source/GoApi_generated.txt +++ /dev/null @@ -1,125 +0,0 @@ -// This file was generated using `godoc` and customized for use with the -// API Reference documentation. To recreate this file, use the `godoc` tool -// (http://godoc.org) with the files in the `flatbuffers/go` folder. -// -// Note: You may need to ensure that copies of the files exist in the -// `src/` subfolder at the path set by the `$GOROOT` environment variable. -// You can either move the files to `$GOROOT/src/flatbuffers` manually, if -// `$GOROOT` is already set, otherwise you will need to manually set the -// `$GOROOT` variable to a path and create `src/flatbuffers` subfolders at that -// path. Then copy these files into `$GOROOT/src/flatbuffers`. (Some versions of -// `godoc` include a `-path` flag. This could be used instead, if available). -// -// Once the files exist at the `$GOROOT/src/flatbuffers` location, you can -// regenerate this doc using the following command: -// `godoc flatbuffers > GoApi_generated.txt`. -// -// After the documentation is generated, you will have to manually remove any -// non-user facing documentation from this file. - -/// [Go API] -PACKAGE DOCUMENTATION - -package flatbuffers - Package flatbuffers provides facilities to read and write flatbuffers - objects. - -TYPES - -type Builder struct { - // `Bytes` gives raw access to the buffer. Most users will want to use - // FinishedBytes() instead. - Bytes []byte -} - Builder is a state machine for creating FlatBuffer objects. Use a - Builder to construct object(s) starting from leaf nodes. - - A Builder constructs byte buffers in a last-first manner for simplicity - and performance. - -FUNCTIONS - -func NewBuilder(initialSize int) *Builder - NewBuilder initializes a Builder of size `initial_size`. The internal - buffer is grown as needed. - -func (b *Builder) CreateByteString(s []byte) UOffsetT - CreateByteString writes a byte slice as a string (null-terminated). - -func (b *Builder) CreateByteVector(v []byte) UOffsetT - CreateByteVector writes a ubyte vector - -func (b *Builder) CreateString(s string) UOffsetT - CreateString writes a null-terminated string as a vector. - -func (b *Builder) EndVector(vectorNumElems int) UOffsetT - EndVector writes data necessary to finish vector construction. - -func (b *Builder) Finish(rootTable UOffsetT) - Finish finalizes a buffer, pointing to the given `rootTable`. - -func (b *Builder) FinishedBytes() []byte - FinishedBytes returns a pointer to the written data in the byte buffer. - Panics if the builder is not in a finished state (which is caused by - calling `Finish()`). - -func (b *Builder) Head() UOffsetT - Head gives the start of useful data in the underlying byte buffer. Note: - unlike other functions, this value is interpreted as from the left. - -func (b *Builder) PrependBool(x bool) - PrependBool prepends a bool to the Builder buffer. Aligns and checks for - space. - -func (b *Builder) PrependByte(x byte) - PrependByte prepends a byte to the Builder buffer. Aligns and checks for - space. - -func (b *Builder) PrependFloat32(x float32) - PrependFloat32 prepends a float32 to the Builder buffer. Aligns and - checks for space. - -func (b *Builder) PrependFloat64(x float64) - PrependFloat64 prepends a float64 to the Builder buffer. Aligns and - checks for space. - -func (b *Builder) PrependInt16(x int16) - PrependInt16 prepends a int16 to the Builder buffer. Aligns and checks - for space. - -func (b *Builder) PrependInt32(x int32) - PrependInt32 prepends a int32 to the Builder buffer. Aligns and checks - for space. - -func (b *Builder) PrependInt64(x int64) - PrependInt64 prepends a int64 to the Builder buffer. Aligns and checks - for space. - -func (b *Builder) PrependInt8(x int8) - PrependInt8 prepends a int8 to the Builder buffer. Aligns and checks for - space. - -func (b *Builder) PrependUOffsetT(off UOffsetT) - PrependUOffsetT prepends an UOffsetT, relative to where it will be - written. - -func (b *Builder) PrependUint16(x uint16) - PrependUint16 prepends a uint16 to the Builder buffer. Aligns and checks - for space. - -func (b *Builder) PrependUint32(x uint32) - PrependUint32 prepends a uint32 to the Builder buffer. Aligns and checks - for space. - -func (b *Builder) PrependUint64(x uint64) - PrependUint64 prepends a uint64 to the Builder buffer. Aligns and checks - for space. - -func (b *Builder) PrependUint8(x uint8) - PrependUint8 prepends a uint8 to the Builder buffer. Aligns and checks - for space. - -func (b *Builder) Reset() - Reset truncates the underlying Builder buffer, facilitating alloc-free - reuse of a Builder. It also resets bookkeeping data. -/// [Go API] diff --git a/docs/source/Grammar.md b/docs/source/Grammar.md deleted file mode 100644 index a54f4beae5..0000000000 --- a/docs/source/Grammar.md +++ /dev/null @@ -1,74 +0,0 @@ -Grammar of the schema language {#flatbuffers_grammar} -============================== - -schema = include* - ( namespace\_decl | type\_decl | enum\_decl | root\_decl | - file_extension_decl | file_identifier_decl | - attribute\_decl | rpc\_decl | object )* - -include = `include` string\_constant `;` - -namespace\_decl = `namespace` ident ( `.` ident )* `;` - -attribute\_decl = `attribute` ident | `"` ident `"` `;` - -type\_decl = ( `table` | `struct` ) ident metadata `{` field\_decl+ `}` - -enum\_decl = ( `enum` ident `:` type | `union` ident ) metadata `{` -commasep( enumval\_decl ) `}` - -root\_decl = `root_type` ident `;` - -field\_decl = ident `:` type [ `=` scalar ] metadata `;` - -rpc\_decl = `rpc_service` ident `{` rpc\_method+ `}` - -rpc\_method = ident `(` ident `)` `:` ident metadata `;` - -type = `bool` | `byte` | `ubyte` | `short` | `ushort` | `int` | `uint` | -`float` | `long` | `ulong` | `double` | -`int8` | `uint8` | `int16` | `uint16` | `int32` | `uint32`| `int64` | `uint64` | -`float32` | `float64` | -`string` | `[` type `]` | ident - -enumval\_decl = ident [ `=` integer\_constant ] metadata - -metadata = [ `(` commasep( ident [ `:` single\_value ] ) `)` ] - -scalar = boolean\_constant | integer\_constant | float\_constant - -object = `{` commasep( ident `:` value ) `}` - -single\_value = scalar | string\_constant - -value = single\_value | object | `[` commasep( value ) `]` - -commasep(x) = [ x ( `,` x )\* ] - -file_extension_decl = `file_extension` string\_constant `;` - -file_identifier_decl = `file_identifier` string\_constant `;` - -string\_constant = `\".*?\"` - -ident = `[a-zA-Z_][a-zA-Z0-9_]*` - -`[:digit:]` = `[0-9]` - -`[:xdigit:]` = `[0-9a-fA-F]` - -dec\_integer\_constant = `[-+]?[:digit:]+` - -hex\_integer\_constant = `[-+]?0[xX][:xdigit:]+` - -integer\_constant = dec\_integer\_constant | hex\_integer\_constant - -dec\_float\_constant = `[-+]?(([.][:digit:]+)|([:digit:]+[.][:digit:]*)|([:digit:]+))([eE][-+]?[:digit:]+)?` - -hex\_float\_constant = `[-+]?0[xX](([.][:xdigit:]+)|([:xdigit:]+[.][:xdigit:]*)|([:xdigit:]+))([pP][-+]?[:digit:]+)` - -special\_float\_constant = `[-+]?(nan|inf|infinity)` - -float\_constant = dec\_float\_constant | hex\_float\_constant | special\_float\_constant - -boolean\_constant = `true` | `false` diff --git a/docs/source/README_TO_GENERATE_DOCS.md b/docs/source/README_TO_GENERATE_DOCS.md deleted file mode 100644 index 5df0b6a8b9..0000000000 --- a/docs/source/README_TO_GENERATE_DOCS.md +++ /dev/null @@ -1,32 +0,0 @@ -## Prerequisites - -To generate the docs for FlatBuffers from the source files, you -will first need to install two programs. - -1. You will need to install `doxygen`. See - [Download Doxygen](http://www.stack.nl/~dimitri/doxygen/download.html). - -2. You will need to install `doxypypy` to format python comments appropriately. - Install it from [here](https://github.com/Feneric/doxypypy). - -*Note: You will need both `doxygen` and `doxypypy` to be in your -[PATH](https://en.wikipedia.org/wiki/PATH_(variable)) environment variable.* - -After you have both of those files installed and in your path, you need to -set up the `py_filter` to invoke `doxypypy` from `doxygen`. - -Follow the steps -[here](https://github.com/Feneric/doxypypy#invoking-doxypypy-from-doxygen). - -## Generating Docs - -Run the following commands to generate the docs: - -`cd flatbuffers/docs/source` -`doxygen` - -The output is placed in `flatbuffers/docs/html`. - -*Note: The Go API Reference code must be generated ahead of time. For -instructions on how to regenerated this file, please read the comments -in `GoApi.md`.* diff --git a/docs/source/Schemas.md b/docs/source/Schemas.md deleted file mode 100644 index f049cf40b9..0000000000 --- a/docs/source/Schemas.md +++ /dev/null @@ -1,685 +0,0 @@ -Writing a schema {#flatbuffers_guide_writing_schema} -================ - -The syntax of the schema language (aka IDL, [Interface Definition Language][]) -should look quite familiar to users of any of the C family of -languages, and also to users of other IDLs. Let's look at an example -first: - - // example IDL file - - namespace MyGame; - - attribute "priority"; - - enum Color : byte { Red = 1, Green, Blue } - - union Any { Monster, Weapon, Pickup } - - struct Vec3 { - x:float; - y:float; - z:float; - } - - table Monster { - pos:Vec3; - mana:short = 150; - hp:short = 100; - name:string; - friendly:bool = false (deprecated, priority: 1); - inventory:[ubyte]; - color:Color = Blue; - test:Any; - } - - root_type Monster; - -(`Weapon` & `Pickup` not defined as part of this example). - -### Tables - -Tables are the main way of defining objects in FlatBuffers, and consist of a -name (here `Monster`) and a list of fields. Each field has a name, a type, and -optionally a default value. If the default value is not specified in the schema, -it will be `0` for scalar types, or `null` for other types. Some languages -support setting a scalar's default to `null`. This makes the scalar optional. - -Fields do not have to appear in the wire representation, and you can choose -to omit fields when constructing an object. You have the flexibility to add -fields without fear of bloating your data. This design is also FlatBuffer's -mechanism for forward and backwards compatibility. Note that: - -- You can add new fields in the schema ONLY at the end of a table - definition. Older data will still - read correctly, and give you the default value when read. Older code - will simply ignore the new field. - If you want to have flexibility to use any order for fields in your - schema, you can manually assign ids (much like Protocol Buffers), - see the `id` attribute below. - -- You cannot delete fields you don't use anymore from the schema, - but you can simply - stop writing them into your data for almost the same effect. - Additionally you can mark them as `deprecated` as in the example - above, which will prevent the generation of accessors in the - generated C++, as a way to enforce the field not being used any more. - (careful: this may break code!). - -- You may change field names and table names, if you're ok with your - code breaking until you've renamed them there too. - -See "Schema evolution examples" below for more on this -topic. - -### Structs - -Similar to a table, only now none of the fields are optional (so no defaults -either), and fields may not be added or be deprecated. Structs may only contain -scalars or other structs. Use this for -simple objects where you are very sure no changes will ever be made -(as quite clear in the example `Vec3`). Structs use less memory than -tables and are even faster to access (they are always stored in-line in their -parent object, and use no virtual table). - -### Types - -Built-in scalar types are - -- 8 bit: `byte` (`int8`), `ubyte` (`uint8`), `bool` - -- 16 bit: `short` (`int16`), `ushort` (`uint16`) - -- 32 bit: `int` (`int32`), `uint` (`uint32`), `float` (`float32`) - -- 64 bit: `long` (`int64`), `ulong` (`uint64`), `double` (`float64`) - -The type names in parentheses are alias names such that for example -`uint8` can be used in place of `ubyte`, and `int32` can be used in -place of `int` without affecting code generation. - -Built-in non-scalar types: - -- Vector of any other type (denoted with `[type]`). Nesting vectors - is not supported, instead you can wrap the inner vector in a table. - -- `string`, which may only hold UTF-8 or 7-bit ASCII. For other text encodings - or general binary data use vectors (`[byte]` or `[ubyte]`) instead. - -- References to other tables or structs, enums or unions (see - below). - -You can't change types of fields once they're used, with the exception -of same-size data where a `reinterpret_cast` would give you a desirable result, -e.g. you could change a `uint` to an `int` if no values in current data use the -high bit yet. - -### Arrays - -Arrays are a convenience short-hand for a fixed-length collection of elements. -Arrays can be used to replace the following schema: - - struct Vec3 { - x:float; - y:float; - z:float; - } - -with the following schema: - - struct Vec3 { - v:[float:3]; - } - -Both representations are binary equivalent. - -Arrays are currently only supported in a `struct`. - -### Default, Optional and Required Values - -There are three, mutually exclusive, reactions to the non-presence of a table's -field in the binary data: - -1. Default valued fields will return the default value (as defined in the schema). -2. Optional valued fields will return some form of `null` depending on the - local language. (In a sense, `null` is the default value). -3. Required fields will cause an error. Flatbuffer verifiers would - consider the whole buffer invalid. See the `required` tag below. - -When writing a schema, values are a sequence of digits. Values may be optionally -followed by a decimal point (`.`) and more digits, for float constants, or -optionally prefixed by a `-`. Floats may also be in scientific notation; -optionally ending with an `e` or `E`, followed by a `+` or `-` and more digits. -Values can also be the keyword `null`. - -Only scalar values can have defaults, non-scalar (string/vector/table) fields -default to `null` when not present. - -You generally do not want to change default values after they're initially -defined. Fields that have the default value are not actually stored in the -serialized data (see also Gotchas below). Values explicitly written by code -generated by the old schema old version, if they happen to be the default, will -be read as a different value by code generated with the new schema. This is -slightly less bad when converting an optional scalar into a default valued -scalar since non-presence would not be overloaded with a previous default value. -There are situations, however, where this may be desirable, especially if you -can ensure a simultaneous rebuild of all code. - -### Enums - -Define a sequence of named constants, each with a given value, or -increasing by one from the previous one. The default first value -is `0`. As you can see in the enum declaration, you specify the underlying -integral type of the enum with `:` (in this case `byte`), which then determines -the type of any fields declared with this enum type. - -Only integer types are allowed, i.e. `byte`, `ubyte`, `short` `ushort`, `int`, -`uint`, `long` and `ulong`. - -Typically, enum values should only ever be added, never removed (there is no -deprecation for enums). This requires code to handle forwards compatibility -itself, by handling unknown enum values. - -### Unions - -Unions share a lot of properties with enums, but instead of new names -for constants, you use names of tables. You can then declare -a union field, which can hold a reference to any of those types, and -additionally a field with the suffix `_type` is generated that holds -the corresponding enum value, allowing you to know which type to cast -to at runtime. - -It's possible to give an alias name to a type union. This way a type can even be -used to mean different things depending on the name used: - - table PointPosition { x:uint; y:uint; } - table MarkerPosition {} - union Position { - Start:MarkerPosition, - Point:PointPosition, - Finish:MarkerPosition - } - -Unions contain a special `NONE` marker to denote that no value is stored so that -name cannot be used as an alias. - -Unions are a good way to be able to send multiple message types as a FlatBuffer. -Note that because a union field is really two fields, it must always be -part of a table, it cannot be the root of a FlatBuffer by itself. - -If you have a need to distinguish between different FlatBuffers in a more -open-ended way, for example for use as files, see the file identification -feature below. - -There is an experimental support only in C++ for a vector of unions (and -types). In the example IDL file above, use [Any] to add a vector of Any to -Monster table. There is also experimental support for other types besides -tables in unions, in particular structs and strings. There's no direct support -for scalars in unions, but they can be wrapped in a struct at no space cost. - -### Namespaces - -These will generate the corresponding namespace in C++ for all helper -code, and packages in Java. You can use `.` to specify nested namespaces / -packages. - -### Includes - -You can include other schemas files in your current one, e.g.: - - include "mydefinitions.fbs"; - -This makes it easier to refer to types defined elsewhere. `include` -automatically ensures each file is parsed just once, even when referred to -more than once. - -When using the `flatc` compiler to generate code for schema definitions, -only definitions in the current file will be generated, not those from the -included files (those you still generate separately). - -### Root type - -This declares what you consider to be the root table of the serialized -data. This is particularly important for parsing JSON data, which doesn't -include object type information. - -### File identification and extension - -Typically, a FlatBuffer binary buffer is not self-describing, i.e. it -needs you to know its schema to parse it correctly. But if you -want to use a FlatBuffer as a file format, it would be convenient -to be able to have a "magic number" in there, like most file formats -have, to be able to do a sanity check to see if you're reading the -kind of file you're expecting. - -Now, you can always prefix a FlatBuffer with your own file header, -but FlatBuffers has a built-in way to add an identifier to a -FlatBuffer that takes up minimal space, and keeps the buffer -compatible with buffers that don't have such an identifier. - -You can specify in a schema, similar to `root_type`, that you intend -for this type of FlatBuffer to be used as a file format: - - file_identifier "MYFI"; - -Identifiers must always be exactly 4 characters long. These 4 characters -will end up as bytes at offsets 4-7 (inclusive) in the buffer. - -For any schema that has such an identifier, `flatc` will automatically -add the identifier to any binaries it generates (with `-b`), -and generated calls like `FinishMonsterBuffer` also add the identifier. -If you have specified an identifier and wish to generate a buffer -without one, you can always still do so by calling -`FlatBufferBuilder::Finish` explicitly. - -After loading a buffer, you can use a call like -`MonsterBufferHasIdentifier` to check if the identifier is present. - -Note that this is best for open-ended uses such as files. If you simply wanted -to send one of a set of possible messages over a network for example, you'd -be better off with a union. - -Additionally, by default `flatc` will output binary files as `.bin`. -This declaration in the schema will change that to whatever you want: - - file_extension "ext"; - -### RPC interface declarations - -You can declare RPC calls in a schema, that define a set of functions -that take a FlatBuffer as an argument (the request) and return a FlatBuffer -as the response (both of which must be table types): - - rpc_service MonsterStorage { - Store(Monster):StoreResponse; - Retrieve(MonsterId):Monster; - } - -What code this produces and how it is used depends on language and RPC system -used, there is preliminary support for GRPC through the `--grpc` code generator, -see `grpc/tests` for an example. - -### Comments & documentation - -May be written as in most C-based languages. Additionally, a triple -comment (`///`) on a line by itself signals that a comment is documentation -for whatever is declared on the line after it -(table/struct/field/enum/union/element), and the comment is output -in the corresponding C++ code. Multiple such lines per item are allowed. - -### Attributes - -Attributes may be attached to a declaration, behind a field/enum value, -or after the name of a table/struct/enum/union. These may either have -a value or not. Some attributes like `deprecated` are understood by -the compiler; user defined ones need to be declared with the attribute -declaration (like `priority` in the example above), and are -available to query if you parse the schema at runtime. -This is useful if you write your own code generators/editors etc., and -you wish to add additional information specific to your tool (such as a -help text). - -Current understood attributes: - -- `id: n` (on a table field): manually set the field identifier to `n`. - If you use this attribute, you must use it on ALL fields of this table, - and the numbers must be a contiguous range from 0 onwards. - Additionally, since a union type effectively adds two fields, its - id must be that of the second field (the first field is the type - field and not explicitly declared in the schema). - For example, if the last field before the union field had id 6, - the union field should have id 8, and the unions type field will - implicitly be 7. - IDs allow the fields to be placed in any order in the schema. - When a new field is added to the schema it must use the next available ID. -- `deprecated` (on a field): do not generate accessors for this field - anymore, code should stop using this data. Old data may still contain this - field, but it won't be accessible anymore by newer code. Note that if you - deprecate a field that was previous required, old code may fail to validate - new data (when using the optional verifier). -- `required` (on a non-scalar table field): this field must always be set. - By default, fields do not need to be present in the binary. This is - desirable, as it helps with forwards/backwards compatibility, and - flexibility of data structures. By specifying this attribute, you make non- - presence in an error for both reader and writer. The reading code may access - the field directly, without checking for null. If the constructing code does - not initialize this field, they will get an assert, and also the verifier - will fail on buffers that have missing required fields. Both adding and - removing this attribute may be forwards/backwards incompatible as readers - will be unable read old or new data, respectively, unless the data happens to - always have the field set. -- `force_align: size` (on a struct): force the alignment of this struct - to be something higher than what it is naturally aligned to. Causes - these structs to be aligned to that amount inside a buffer, IF that - buffer is allocated with that alignment (which is not necessarily - the case for buffers accessed directly inside a `FlatBufferBuilder`). - Note: currently not guaranteed to have an effect when used with - `--object-api`, since that may allocate objects at alignments less than - what you specify with `force_align`. -- `force_align: size` (on a vector): force the alignment of this vector to be - something different than what the element size would normally dictate. - Note: Now only work for generated C++ code. -- `bit_flags` (on an unsigned enum): the values of this field indicate bits, - meaning that any unsigned value N specified in the schema will end up - representing 1< - -### Testing whether a field is present in a table - -Most serialization formats (e.g. JSON or Protocol Buffers) make it very -explicit in the format whether a field is present in an object or not, -allowing you to use this as "extra" information. - -FlatBuffers will not write fields that are equal to their default value, -sometimes resulting in significant space savings. However, this also means we -cannot disambiguate the meaning of non-presence as "written default value" or -"not written at all". This only applies to scalar fields since only they support -default values. Unless otherwise specified, their default is 0. - -If you care about the presence of scalars, most languages support "optional -scalars." You can set `null` as the default value in the schema. `null` is a -value that's outside of all types, so we will always write if `add_field` is -called. The generated field accessor should use the local language's canonical -optional type. - -Some `FlatBufferBuilder` implementations have an option called `force_defaults` -that circumvents this "not writing defaults" behavior you can then use -`IsFieldPresent` to query presence. -/ -Another option that works in all languages is to wrap a scalar field in a -struct. This way it will return null if it is not present. This will be slightly -less ergonomic but structs don't take up any more space than the scalar they -represent. - - [Interface Definition Language]: https://en.wikipedia.org/wiki/Interface_description_language - -## Writing your own code generator. - -See [our intermediate representation](@ref intermediate_representation). diff --git a/docs/source/Tutorial.md b/docs/source/Tutorial.md deleted file mode 100644 index f633425035..0000000000 --- a/docs/source/Tutorial.md +++ /dev/null @@ -1,3564 +0,0 @@ -Tutorial {#flatbuffers_guide_tutorial} -======== - -## Overview - -This tutorial provides a basic example of how to work with -[FlatBuffers](@ref flatbuffers_overview). We will step through a simple example -application, which shows you how to: - - - Write a FlatBuffer `schema` file. - - Use the `flatc` FlatBuffer compiler. - - Parse [JSON](http://json.org) files that conform to a schema into - FlatBuffer binary files. - - Use the generated files in many of the supported languages (such as C++, - Java, and more.) - -During this example, imagine that you are creating a game where the main -character, the hero of the story, needs to slay some `orc`s. We will walk -through each step necessary to create this monster type using FlatBuffers. - -Please select your desired language for our quest: -\htmlonly -
- C++ - Java - Kotlin - C# - Go - Python - JavaScript - TypeScript - PHP - C - Dart - Lua - Lobster - Rust - Swift -
-\endhtmlonly - -\htmlonly - -\endhtmlonly - -## Where to Find the Example Code - -Samples demonstating the concepts in this example are located in the source code -package, under the `samples` directory. You can browse the samples on GitHub -[here](https://github.com/google/flatbuffers/tree/master/samples). - -
-*Note: The above does not apply to C, instead [look here](https://github.com/dvidelabs/flatcc/tree/master/samples).* -
- -For your chosen language, please cross-reference with: - -
-[sample_binary.cpp](https://github.com/google/flatbuffers/blob/master/samples/sample_binary.cpp) -
-
-[SampleBinary.java](https://github.com/google/flatbuffers/blob/master/samples/SampleBinary.java) -
-
-[SampleBinary.kt](https://github.com/google/flatbuffers/blob/master/samples/SampleBinary.kt) -
-
-[SampleBinary.cs](https://github.com/google/flatbuffers/blob/master/samples/SampleBinary.cs) -
-
-[sample_binary.go](https://github.com/google/flatbuffers/blob/master/samples/sample_binary.go) -
-
-[sample_binary.py](https://github.com/google/flatbuffers/blob/master/samples/sample_binary.py) -
-
-No sample binary is provided, since JS needs to be transpiled from TypeScript. Please see TypeScript support. -
-
-none yet -
-
-[SampleBinary.php](https://github.com/google/flatbuffers/blob/master/samples/SampleBinary.php) -
-
-[monster.c](https://github.com/dvidelabs/flatcc/blob/master/samples/monster/monster.c) -
-
-[example.dart](https://github.com/google/flatbuffers/blob/master/dart/example/example.dart) -
-
-[sample_binary.lua](https://github.com/google/flatbuffers/blob/master/samples/sample_binary.lua) -
-
-[sample_binary.lobster](https://github.com/google/flatbuffers/blob/master/samples/sample_binary.lobster) -
-
-[sample_binary.rs](https://github.com/google/flatbuffers/blob/master/samples/sample_binary.rs) -
-
-[sample_binary.swift](https://github.com/google/flatbuffers/blob/master/samples/sample_binary.swift) -
- - -## Writing the Monsters' FlatBuffer Schema - -To start working with FlatBuffers, you first need to create a `schema` file, -which defines the format for each data structure you wish to serialize. Here is -the `schema` that defines the template for our monsters: - -~~~ - // Example IDL file for our monster's schema. - - namespace MyGame.Sample; - - enum Color:byte { Red = 0, Green, Blue = 2 } - - union Equipment { Weapon } // Optionally add more tables. - - struct Vec3 { - x:float; - y:float; - z:float; - } - - table Monster { - pos:Vec3; // Struct. - mana:short = 150; - hp:short = 100; - name:string; - friendly:bool = false (deprecated); - inventory:[ubyte]; // Vector of scalars. - color:Color = Blue; // Enum. - weapons:[Weapon]; // Vector of tables. - equipped:Equipment; // Union. - path:[Vec3]; // Vector of structs. - } - - table Weapon { - name:string; - damage:short; - } - - root_type Monster; -~~~ - -As you can see, the syntax for the `schema` -[Interface Definition Language (IDL)](https://en.wikipedia.org/wiki/Interface_description_language) -is similar to those of the C family of languages, and other IDL languages. Let's -examine each part of this `schema` to determine what it does. - -The `schema` starts with a `namespace` declaration. This determines the -corresponding package/namespace for the generated code. In our example, we have -the `Sample` namespace inside of the `MyGame` namespace. - -Next, we have an `enum` definition. In this example, we have an `enum` of type -`byte`, named `Color`. We have three values in this `enum`: `Red`, `Green`, and -`Blue`. We specify `Red = 0` and `Blue = 2`, but we do not specify an explicit -value for `Green`. Since the behavior of an `enum` is to increment if -unspecified, `Green` will receive the implicit value of `1`. - -Following the `enum` is a `union`. The `union` in this example is not very -useful, as it only contains the one `table` (named `Weapon`). If we had created -multiple tables that we would want the `union` to be able to reference, we -could add more elements to the `union Equipment`. - -After the `union` comes a `struct Vec3`, which represents a floating point -vector with `3` dimensions. We use a `struct` here, over a `table`, because -`struct`s are ideal for data structures that will not change, since they use -less memory and have faster lookup. - -The `Monster` table is the main object in our FlatBuffer. This will be used as -the template to store our `orc` monster. We specify some default values for -fields, such as `mana:short = 150`. If unspecified, scalar fields (like `int`, -`uint`, or `float`) will be given a default of `0` while strings and tables will -be given a default of `null`. Another thing to note is the line `friendly:bool = -false (deprecated);`. Since you cannot delete fields from a `table` (to support -backwards compatibility), you can set fields as `deprecated`, which will prevent -the generation of accessors for this field in the generated code. Be careful -when using `deprecated`, however, as it may break legacy code that used this -accessor. - -The `Weapon` table is a sub-table used within our FlatBuffer. It is -used twice: once within the `Monster` table and once within the `Equipment` -union. For our `Monster`, it is used to populate a `vector of tables` via the -`weapons` field within our `Monster`. It is also the only table referenced by -the `Equipment` union. - -The last part of the `schema` is the `root_type`. The root type declares what -will be the root table for the serialized data. In our case, the root type is -our `Monster` table. - -The scalar types can also use alias type names such as `int16` instead -of `short` and `float32` instead of `float`. Thus we could also write -the `Weapon` table as: - -~~~ - table Weapon { - name:string; - damage:int16; - } -~~~ - -#### More Information About Schemas - -You can find a complete guide to writing `schema` files in the -[Writing a schema](@ref flatbuffers_guide_writing_schema) section of the -Programmer's Guide. You can also view the formal -[Grammar of the schema language](@ref flatbuffers_grammar). - -## Compiling the Monsters' Schema - -After you have written the FlatBuffers schema, the next step is to compile it. - -If you have not already done so, please follow -[these instructions](@ref flatbuffers_guide_building) to build `flatc`, the -FlatBuffer compiler. - -Once `flatc` is built successfully, compile the schema for your language: - -
-*Note: If you're working in C, you need to use the separate project [FlatCC](https://github.com/dvidelabs/flatcc) which contains a schema compiler and runtime library in C for C.* -
-See [flatcc build instructions](https://github.com/dvidelabs/flatcc#building). -
-Please be aware of the difference between `flatc` and `flatcc` tools. -
-
-
-~~~{.sh} - cd flatbuffers/samples - ./../flatc --cpp monster.fbs -~~~ -
-
-~~~{.sh} - cd flatbuffers/samples - ./../flatc --java monster.fbs -~~~ -
-
-~~~{.sh} - cd flatbuffers/samples - ./../flatc --kotlin monster.fbs -~~~ -
-
-~~~{.sh} - cd flatbuffers/samples - ./../flatc --csharp monster.fbs -~~~ -
-
-~~~{.sh} - cd flatbuffers/samples - ./../flatc --go monster.fbs -~~~ -
-
-~~~{.sh} - cd flatbuffers/samples - ./../flatc --python monster.fbs -~~~ -
-
-~~~{.sh} - cd flatbuffers/samples - ./../flatc --ts monster.fbs - # customize your TS -> JS transpilation - tsc monster_generated.ts -~~~ -
-
-~~~{.sh} - cd flatbuffers/samples - ./../flatc --ts monster.fbs -~~~ -
-
-~~~{.sh} - cd flatbuffers/sample - ./../flatc --php monster.fbs -~~~ -
-
-~~~{.sh} - cd flatcc - mkdir -p build/tmp/samples/monster - bin/flatcc -a -o build/tmp/samples/monster samples/monster/monster.fbs - # or just - flatcc/samples/monster/build.sh -~~~ -
-
-~~~{.sh} - cd flatbuffers/samples - ./../flatc --dart monster.fbs -~~~ -
-
-~~~{.sh} - cd flatbuffers/samples - ./../flatc --lua monster.fbs -~~~ -
-
-~~~{.sh} - cd flatbuffers/samples - ./../flatc --lobster monster.fbs -~~~ -
-
-~~~{.sh} - cd flatbuffers/samples - ./../flatc --rust monster.fbs -~~~ -
-
-~~~{.sh} - cd flatbuffers/samples - ./../flatc --swift monster.fbs -~~~ -
- -For a more complete guide to using the `flatc` compiler, please read the -[Using the schema compiler](@ref flatbuffers_guide_using_schema_compiler) -section of the Programmer's Guide. - -## Reading and Writing Monster FlatBuffers - -Now that we have compiled the schema for our programming language, we can -start creating some monsters and serializing/deserializing them from -FlatBuffers. - -#### Creating and Writing Orc FlatBuffers - -The first step is to import/include the library, generated files, etc. - -
-~~~{.cpp} - #include "monster_generated.h" // This was generated by `flatc`. - - using namespace MyGame::Sample; // Specified in the schema. -~~~ -
-
-~~~{.java} - import MyGame.Sample.*; //The `flatc` generated files. (Monster, Vec3, etc.) - - import com.google.flatbuffers.FlatBufferBuilder; -~~~ -
-
-~~~{.kotlin} - import MyGame.Sample.* //The `flatc` generated files. (Monster, Vec3, etc.) - - import com.google.flatbuffers.FlatBufferBuilder -~~~ -
-
-~~~{.cs} - using FlatBuffers; - using MyGame.Sample; // The `flatc` generated files. (Monster, Vec3, etc.) -~~~ -
-
-~~~{.go} - import ( - flatbuffers "github.com/google/flatbuffers/go" - sample "MyGame/Sample" - ) -~~~ -
-
-~~~{.py} - import flatbuffers - - # Generated by `flatc`. - import MyGame.Sample.Color - import MyGame.Sample.Equipment - import MyGame.Sample.Monster - import MyGame.Sample.Vec3 - import MyGame.Sample.Weapon -~~~ -
-
-~~~{.js} - // The following code is an example - use your desired module flavor by transpiling from TS. - var flatbuffers = require('/js/flatbuffers').flatbuffers; - var MyGame = require('./monster_generated').MyGame; // Generated by `flatc`. - - //--------------------------------------------------------------------------// - - // The following code is for browser-based HTML/JavaScript. Use the above code - // for JavaScript module loaders (e.g. Node.js). - - // Generated by `flatc`. -~~~ -
-
-~~~{.ts} - // note: import flatbuffers with your desired import method - - import { MyGame } from './monster_generated'; -~~~ -
-
-~~~{.php} - // It is recommended that your use PSR autoload when using FlatBuffers in PHP. - // Here is an example from `SampleBinary.php`: - function __autoload($class_name) { - // The last segment of the class name matches the file name. - $class = substr($class_name, strrpos($class_name, "\\") + 1); - $root_dir = join(DIRECTORY_SEPARATOR, array(dirname(dirname(__FILE__)))); // `flatbuffers` root. - - // Contains the `*.php` files for the FlatBuffers library and the `flatc` generated files. - $paths = array(join(DIRECTORY_SEPARATOR, array($root_dir, "php")), - join(DIRECTORY_SEPARATOR, array($root_dir, "samples", "MyGame", "Sample"))); - foreach ($paths as $path) { - $file = join(DIRECTORY_SEPARATOR, array($path, $class . ".php")); - if (file_exists($file)) { - require($file); - break; - } - } - } -~~~ -
-
-~~~{.c} - #include "monster_builder.h" // Generated by `flatcc`. - - // Convenient namespace macro to manage long namespace prefix. - #undef ns - #define ns(x) FLATBUFFERS_WRAP_NAMESPACE(MyGame_Sample, x) // Specified in the schema. - - // A helper to simplify creating vectors from C-arrays. - #define c_vec_len(V) (sizeof(V)/sizeof((V)[0])) -~~~ -
-
-~~~{.dart} - import 'package:flat_buffers/flat_buffers.dart' as fb; - - // Generated by `flatc`. - import 'monster_my_game.sample_generated.dart' as myGame; -~~~ -
-
-~~~{.lua} - -- require the flatbuffers module - local flatbuffers = require("flatbuffers") - - -- require the generated files from `flatc`. - local color = require("MyGame.Sample.Color") - local equipment = require("MyGame.Sample.Equipment") - local monster = require("MyGame.Sample.Monster") - local vec3 = require("MyGame.Sample.Vec3") - local weapon = require("MyGame.Sample.Weapon") -~~~ -
-
-~~~{.lobster} - import from "../lobster/" // Where to find flatbuffers.lobster - import monster_generated -~~~ -
-
-~~~{.rs} - // import the flatbuffers runtime library - extern crate flatbuffers; - - // import the generated code - #[allow(dead_code, unused_imports)] - #[path = "./monster_generated.rs"] - mod monster_generated; - pub use monster_generated::my_game::sample::{get_root_as_monster, - Color, Equipment, - Monster, MonsterArgs, - Vec3, - Weapon, WeaponArgs}; -~~~ -
-
-~~~{.swift} - /** - // make sure that monster_generated.swift is included in your project - */ - import Flatbuffers - - // typealiases for convenience - typealias Monster = MyGame1_Sample_Monster - typealias Weapon = MyGame1_Sample_Weapon - typealias Color = MyGame1_Sample_Color - typealias Vec3 = MyGame1_Sample_Vec3 -~~~ -
- -Now we are ready to start building some buffers. In order to start, we need -to create an instance of the `FlatBufferBuilder`, which will contain the buffer -as it grows. You can pass an initial size of the buffer (here 1024 bytes), -which will grow automatically if needed: - -
-~~~{.cpp} - // Create a `FlatBufferBuilder`, which will be used to create our - // monsters' FlatBuffers. - flatbuffers::FlatBufferBuilder builder(1024); -~~~ -
-
-~~~{.java} - // Create a `FlatBufferBuilder`, which will be used to create our - // monsters' FlatBuffers. - FlatBufferBuilder builder = new FlatBufferBuilder(1024); -~~~ -
-
-~~~{.kt} - // Create a `FlatBufferBuilder`, which will be used to create our - // monsters' FlatBuffers. - val builder = FlatBufferBuilder(1024) -~~~ -
-
-~~~{.cs} - // Create a `FlatBufferBuilder`, which will be used to create our - // monsters' FlatBuffers. - var builder = new FlatBufferBuilder(1024); -~~~ -
-
-~~~{.go} - // Create a `FlatBufferBuilder`, which will be used to create our - // monsters' FlatBuffers. - builder := flatbuffers.NewBuilder(1024) -~~~ -
-
-~~~{.py} - # Create a `FlatBufferBuilder`, which will be used to create our - # monsters' FlatBuffers. - builder = flatbuffers.Builder(1024) -~~~ -
-
-~~~{.js} - // Create a `flatbuffer.Builder`, which will be used to create our - // monsters' FlatBuffers. - var builder = new flatbuffers.Builder(1024); -~~~ -
-
-~~~{.ts} - // Create a `flatbuffer.Builder`, which will be used to create our - // monsters' FlatBuffers. - let builder = new flatbuffers.Builder(1024); -~~~ -
-
-~~~{.php} - // Create a `FlatBufferBuilder`, which will be used to create our - // monsters' FlatBuffers. - $builder = new Google\FlatBuffers\FlatbufferBuilder(1024); -~~~ -
-
-~~~{.c} - flatcc_builder_t builder, *B; - B = &builder; - // Initialize the builder object. - flatcc_builder_init(B); -~~~ -
-
-~~~{.dart} - // Create the fb.Builder object that will be used by our generated builders - // Note that if you are only planning to immediately get the byte array this builder would create, - // you can use the convenience method `toBytes()` on the generated builders. - // For example, you could do something like `new myGame.MonsterBuilder(...).toBytes()` - var builder = new fb.Builder(initialSize: 1024); -~~~ -
-
-~~~{.lua} - -- get access to the builder, providing an array of size 1024 - local builder = flatbuffers.Builder(1024) -~~~ -
-
-~~~{.lobster} - // get access to the builder - let builder = flatbuffers_builder {} -~~~ -
-
-~~~{.rs} - // Build up a serialized buffer algorithmically. - // Initialize it with a capacity of 1024 bytes. - let mut builder = flatbuffers::FlatBufferBuilder::new_with_capacity(1024); -~~~ -
-
-~~~{.swift} - // create a `FlatBufferBuilder`, which will be used to serialize objects - let builder = FlatBufferBuilder(initialSize: 1024) -~~~ -
- -After creating the `builder`, we can start serializing our data. Before we make -our `orc` Monster, let's create some `Weapon`s: a `Sword` and an `Axe`. - -
-~~~{.cpp} - auto weapon_one_name = builder.CreateString("Sword"); - short weapon_one_damage = 3; - - auto weapon_two_name = builder.CreateString("Axe"); - short weapon_two_damage = 5; - - // Use the `CreateWeapon` shortcut to create Weapons with all the fields set. - auto sword = CreateWeapon(builder, weapon_one_name, weapon_one_damage); - auto axe = CreateWeapon(builder, weapon_two_name, weapon_two_damage); -~~~ -
-
-~~~{.java} - int weaponOneName = builder.createString("Sword") - short weaponOneDamage = 3; - - int weaponTwoName = builder.createString("Axe"); - short weaponTwoDamage = 5; - - // Use the `createWeapon()` helper function to create the weapons, since we set every field. - int sword = Weapon.createWeapon(builder, weaponOneName, weaponOneDamage); - int axe = Weapon.createWeapon(builder, weaponTwoName, weaponTwoDamage); -~~~ -
-
-~~~{.kt} - val weaponOneName = builder.createString("Sword") - val weaponOneDamage: Short = 3; - - val weaponTwoName = builder.createString("Axe") - val weaponTwoDamage: Short = 5; - - // Use the `createWeapon()` helper function to create the weapons, since we set every field. - val sword = Weapon.createWeapon(builder, weaponOneName, weaponOneDamage) - val axe = Weapon.createWeapon(builder, weaponTwoName, weaponTwoDamage) -~~~ -
-
-~~~{.cs} - var weaponOneName = builder.CreateString("Sword"); - var weaponOneDamage = 3; - - var weaponTwoName = builder.CreateString("Axe"); - var weaponTwoDamage = 5; - - // Use the `CreateWeapon()` helper function to create the weapons, since we set every field. - var sword = Weapon.CreateWeapon(builder, weaponOneName, (short)weaponOneDamage); - var axe = Weapon.CreateWeapon(builder, weaponTwoName, (short)weaponTwoDamage); -~~~ -
-
-~~~{.go} - weaponOne := builder.CreateString("Sword") - weaponTwo := builder.CreateString("Axe") - - // Create the first `Weapon` ("Sword"). - sample.WeaponStart(builder) - sample.WeaponAddName(builder, weaponOne) - sample.WeaponAddDamage(builder, 3) - sword := sample.WeaponEnd(builder) - - // Create the second `Weapon` ("Axe"). - sample.WeaponStart(builder) - sample.WeaponAddName(builder, weaponTwo) - sample.WeaponAddDamage(builder, 5) - axe := sample.WeaponEnd(builder) -~~~ -
-
-~~~{.py} - weapon_one = builder.CreateString('Sword') - weapon_two = builder.CreateString('Axe') - - # Create the first `Weapon` ('Sword'). - MyGame.Sample.Weapon.Start(builder) - MyGame.Sample.Weapon.AddName(builder, weapon_one) - MyGame.Sample.Weapon.AddDamage(builder, 3) - sword = MyGame.Sample.Weapon.End(builder) - - # Create the second `Weapon` ('Axe'). - MyGame.Sample.Weapon.Start(builder) - MyGame.Sample.Weapon.AddName(builder, weapon_two) - MyGame.Sample.Weapon.AddDamage(builder, 5) - axe = MyGame.Sample.Weapon.End(builder) -~~~ -
-
-~~~{.js} - var weaponOne = builder.createString('Sword'); - var weaponTwo = builder.createString('Axe'); - - // Create the first `Weapon` ('Sword'). - MyGame.Sample.Weapon.startWeapon(builder); - MyGame.Sample.Weapon.addName(builder, weaponOne); - MyGame.Sample.Weapon.addDamage(builder, 3); - var sword = MyGame.Sample.Weapon.endWeapon(builder); - - // Create the second `Weapon` ('Axe'). - MyGame.Sample.Weapon.startWeapon(builder); - MyGame.Sample.Weapon.addName(builder, weaponTwo); - MyGame.Sample.Weapon.addDamage(builder, 5); - var axe = MyGame.Sample.Weapon.endWeapon(builder); -~~~ -
-
-~~~{.ts} - let weaponOne = builder.createString('Sword'); - let weaponTwo = builder.createString('Axe'); - - // Create the first `Weapon` ('Sword'). - MyGame.Sample.Weapon.startWeapon(builder); - MyGame.Sample.Weapon.addName(builder, weaponOne); - MyGame.Sample.Weapon.addDamage(builder, 3); - let sword = MyGame.Sample.Weapon.endWeapon(builder); - - // Create the second `Weapon` ('Axe'). - MyGame.Sample.Weapon.startWeapon(builder); - MyGame.Sample.Weapon.addName(builder, weaponTwo); - MyGame.Sample.Weapon.addDamage(builder, 5); - let axe = MyGame.Sample.Weapon.endWeapon(builder); -~~~ -
-
-~~~{.php} - // Create the `Weapon`s using the `createWeapon()` helper function. - $weapon_one_name = $builder->createString("Sword"); - $sword = \MyGame\Sample\Weapon::CreateWeapon($builder, $weapon_one_name, 3); - - $weapon_two_name = $builder->createString("Axe"); - $axe = \MyGame\Sample\Weapon::CreateWeapon($builder, $weapon_two_name, 5); - - // Create an array from the two `Weapon`s and pass it to the - // `CreateWeaponsVector()` method to create a FlatBuffer vector. - $weaps = array($sword, $axe); - $weapons = \MyGame\Sample\Monster::CreateWeaponsVector($builder, $weaps); -~~~ -
-
-~~~{.c} - flatbuffers_string_ref_t weapon_one_name = flatbuffers_string_create_str(B, "Sword"); - uint16_t weapon_one_damage = 3; - - flatbuffers_string_ref_t weapon_two_name = flatbuffers_string_create_str(B, "Axe"); - uint16_t weapon_two_damage = 5; - - ns(Weapon_ref_t) sword = ns(Weapon_create(B, weapon_one_name, weapon_one_damage)); - ns(Weapon_ref_t) axe = ns(Weapon_create(B, weapon_two_name, weapon_two_damage)); -~~~ -
-
-~~~{.dart} - // The generated Builder classes work much like in other languages, - final int weaponOneName = builder.writeString("Sword"); - final int weaponOneDamage = 3; - - final int weaponTwoName = builder.writeString("Axe"); - final int weaponTwoDamage = 5; - - final swordBuilder = new myGame.WeaponBuilder(builder) - ..begin() - ..addNameOffset(weaponOneName) - ..addDamage(weaponOneDamage); - final int sword = swordBuilder.finish(); - - final axeBuilder = new myGame.WeaponBuilder(builder) - ..begin() - ..addNameOffset(weaponTwoName) - ..addDamage(weaponTwoDamage); - final int axe = axeBuilder.finish(); - - - - // The generated ObjectBuilder classes offer an easier to use alternative - // at the cost of requiring some additional reference allocations. If memory - // usage is critical, or if you'll be working with especially large messages - // or tables, you should prefer using the generated Builder classes. - // The following code would produce an identical buffer as above. - final String weaponOneName = "Sword"; - final int weaponOneDamage = 3; - - final String weaponTwoName = "Axe"; - final int weaponTwoDamage = 5; - - final myGame.WeaponBuilder sword = new myGame.WeaponObjectBuilder( - name: weaponOneName, - damage: weaponOneDamage, - ); - - final myGame.WeaponBuilder axe = new myGame.WeaponObjectBuilder( - name: weaponTwoName, - damage: weaponTwoDamage, - ); -~~~ -
-
-~~~{.lua} - local weaponOne = builder:CreateString("Sword") - local weaponTwo = builder:CreateString("Axe") - - -- Create the first 'Weapon' - weapon.Start(builder) - weapon.AddName(builder, weaponOne) - weapon.AddDamage(builder, 3) - local sword = weapon.End(builder) - - -- Create the second 'Weapon' - weapon.Start(builder) - weapon.AddName(builder, weaponTwo) - weapon.AddDamage(builder, 5) - local axe = weapon.End(builder) -~~~ -
-
-~~~{.lobster} - let weapon_names = [ "Sword", "Axe" ] - let weapon_damages = [ 3, 5 ] - - let weapon_offsets = map(weapon_names) name, i: - let ns = builder.CreateString(name) - MyGame_Sample_WeaponBuilder { b } - .start() - .add_name(ns) - .add_damage(weapon_damages[i]) - .end() -~~~ -
-
-~~~{.rs} - // Serialize some weapons for the Monster: A 'sword' and an 'axe'. - let weapon_one_name = builder.create_string("Sword"); - let weapon_two_name = builder.create_string("Axe"); - - // Use the `Weapon::create` shortcut to create Weapons with named field - // arguments. - let sword = Weapon::create(&mut builder, &WeaponArgs{ - name: Some(weapon_one_name), - damage: 3, - }); - let axe = Weapon::create(&mut builder, &WeaponArgs{ - name: Some(weapon_two_name), - damage: 5, - }); -~~~ -
-
-~~~{.swift} - let weapon1Name = builder.create(string: "Sword") - let weapon2Name = builder.create(string: "Axe") - - // start creating the weapon by calling startWeapon - let weapon1Start = Weapon.startWeapon(&builder) - Weapon.add(name: weapon1Name, &builder) - Weapon.add(damage: 3, &builder) - // end the object by passing the start point for the weapon 1 - let sword = Weapon.endWeapon(&builder, start: weapon1Start) - - let weapon2Start = Weapon.startWeapon(&builder) - Weapon.add(name: weapon2Name, &builder) - Weapon.add(damage: 5, &builder) - let axe = Weapon.endWeapon(&builder, start: weapon2Start) -~~~ -
- -Now let's create our monster, the `orc`. For this `orc`, lets make him -`red` with rage, positioned at `(1.0, 2.0, 3.0)`, and give him -a large pool of hit points with `300`. We can give him a vector of weapons -to choose from (our `Sword` and `Axe` from earlier). In this case, we will -equip him with the `Axe`, since it is the most powerful of the two. Lastly, -let's fill his inventory with some potential treasures that can be taken once he -is defeated. - -Before we serialize a monster, we need to first serialize any objects that are -contained therein, i.e. we serialize the data tree using depth-first, pre-order -traversal. This is generally easy to do on any tree structures. - -
-~~~{.cpp} - // Serialize a name for our monster, called "Orc". - auto name = builder.CreateString("Orc"); - - // Create a `vector` representing the inventory of the Orc. Each number - // could correspond to an item that can be claimed after he is slain. - unsigned char treasure[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; - auto inventory = builder.CreateVector(treasure, 10); -~~~ -
-
-~~~{.java} - // Serialize a name for our monster, called "Orc". - int name = builder.createString("Orc"); - - // Create a `vector` representing the inventory of the Orc. Each number - // could correspond to an item that can be claimed after he is slain. - byte[] treasure = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; - int inv = Monster.createInventoryVector(builder, treasure); -~~~ -
-
-~~~{.kt} - // Serialize a name for our monster, called "Orc". - val name = builder.createString("Orc") - - // Create a `vector` representing the inventory of the Orc. Each number - // could correspond to an item that can be claimed after he is slain. - val treasure = byteArrayOf(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) - val inv = Monster.createInventoryVector(builder, treasure) -~~~ -
-
-~~~{.cs} - // Serialize a name for our monster, called "Orc". - var name = builder.CreateString("Orc"); - - // Create a `vector` representing the inventory of the Orc. Each number - // could correspond to an item that can be claimed after he is slain. - // Note: Since we prepend the bytes, this loop iterates in reverse order. - Monster.StartInventoryVector(builder, 10); - for (int i = 9; i >= 0; i--) - { - builder.AddByte((byte)i); - } - var inv = builder.EndVector(); -~~~ -
-
-~~~{.go} - // Serialize a name for our monster, called "Orc". - name := builder.CreateString("Orc") - - // Create a `vector` representing the inventory of the Orc. Each number - // could correspond to an item that can be claimed after he is slain. - // Note: Since we prepend the bytes, this loop iterates in reverse. - sample.MonsterStartInventoryVector(builder, 10) - for i := 9; i >= 0; i-- { - builder.PrependByte(byte(i)) - } - inv := builder.EndVector(10) -~~~ -
-
-~~~{.py} - # Serialize a name for our monster, called "Orc". - name = builder.CreateString("Orc") - - # Create a `vector` representing the inventory of the Orc. Each number - # could correspond to an item that can be claimed after he is slain. - # Note: Since we prepend the bytes, this loop iterates in reverse. - MyGame.Sample.Monster.StartInventoryVector(builder, 10) - for i in reversed(range(0, 10)): - builder.PrependByte(i) - inv = builder.EndVector() -~~~ -
-
-~~~{.js} - // Serialize a name for our monster, called 'Orc'. - var name = builder.createString('Orc'); - - // Create a `vector` representing the inventory of the Orc. Each number - // could correspond to an item that can be claimed after he is slain. - var treasure = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; - var inv = MyGame.Sample.Monster.createInventoryVector(builder, treasure); -~~~ -
-
-~~~{.ts} - // Serialize a name for our monster, called 'Orc'. - let name = builder.createString('Orc'); - - // Create a `vector` representing the inventory of the Orc. Each number - // could correspond to an item that can be claimed after he is slain. - let treasure = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; - let inv = MyGame.Sample.Monster.createInventoryVector(builder, treasure); -~~~ -
-
-~~~{.php} - // Serialize a name for our monster, called "Orc". - $name = $builder->createString("Orc"); - - // Create a `vector` representing the inventory of the Orc. Each number - // could correspond to an item that can be claimed after he is slain. - $treasure = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); - $inv = \MyGame\Sample\Monster::CreateInventoryVector($builder, $treasure); -~~~ -
-
-~~~{.c} - // Serialize a name for our monster, called "Orc". - // The _str suffix indicates the source is an ascii-z string. - flatbuffers_string_ref_t name = flatbuffers_string_create_str(B, "Orc"); - - // Create a `vector` representing the inventory of the Orc. Each number - // could correspond to an item that can be claimed after he is slain. - uint8_t treasure[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; - flatbuffers_uint8_vec_ref_t inventory; - // `c_vec_len` is the convenience macro we defined earlier. - inventory = flatbuffers_uint8_vec_create(B, treasure, c_vec_len(treasure)); -~~~ -
-
-~~~{.dart} - // Serialize a name for our monster, called "Orc". - final int name = builder.writeString('Orc'); - - // Create a list representing the inventory of the Orc. Each number - // could correspond to an item that can be claimed after he is slain. - final List treasure = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; - final inventory = builder.writeListUint8(treasure); - - // The following code should be used instead if you intend to use the - // ObjectBuilder classes: - // Serialize a name for our monster, called "Orc". - final String name = 'Orc'; - - // Create a list representing the inventory of the Orc. Each number - // could correspond to an item that can be claimed after he is slain. - final List treasure = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; -~~~ -
-
-~~~{.py} - -- Serialize a name for our monster, called 'orc' - local name = builder:CreateString("Orc") - - -- Create a `vector` representing the inventory of the Orc. Each number - -- could correspond to an item that can be claimed after he is slain. - -- Note: Since we prepend the bytes, this loop iterates in reverse. - monster.StartInventoryVector(builder, 10) - for i=10,1,-1 do - builder:PrependByte(i) - end - local inv = builder:EndVector(10) -~~~ -
-
-~~~{.lobster} - // Name of the monster. - let name = builder.CreateString("Orc") - - // Inventory. - let inv = builder.MyGame_Sample_MonsterCreateInventoryVector(map(10): _) -~~~ -
-
-~~~{.rs} - // Name of the Monster. - let name = builder.create_string("Orc"); - - // Inventory. - let inventory = builder.create_vector(&[0u8, 1, 2, 3, 4, 5, 6, 7, 8, 9]); -~~~ -
-
-~~~{.swift} - // Name of the Monster. - let name = builder.create(string: "Orc") - - // create inventory - let inventory: [Byte] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] - let inventoryOffset = builder.createVector(inventory) -~~~ -
- -We serialized two built-in data types (`string` and `vector`) and captured -their return values. These values are offsets into the serialized data, -indicating where they are stored, such that we can refer to them below when -adding fields to our monster. - -*Note: To create a `vector` of nested objects (e.g. `table`s, `string`s, or -other `vector`s), collect their offsets into a temporary data structure, and -then create an additional `vector` containing their offsets.* - -If instead of creating a vector from an existing array you serialize elements -individually one by one, take care to note that this happens in reverse order, -as buffers are built back to front. - -For example, take a look at the two `Weapon`s that we created earlier (`Sword` -and `Axe`). These are both FlatBuffer `table`s, whose offsets we now store in -memory. Therefore we can create a FlatBuffer `vector` to contain these -offsets. - -
-~~~{.cpp} - // Place the weapons into a `std::vector`, then convert that into a FlatBuffer `vector`. - std::vector> weapons_vector; - weapons_vector.push_back(sword); - weapons_vector.push_back(axe); - auto weapons = builder.CreateVector(weapons_vector); -~~~ -
-
-~~~{.java} - // Place the two weapons into an array, and pass it to the `createWeaponsVector()` method to - // create a FlatBuffer vector. - int[] weaps = new int[2]; - weaps[0] = sword; - weaps[1] = axe; - - // Pass the `weaps` array into the `createWeaponsVector()` method to create a FlatBuffer vector. - int weapons = Monster.createWeaponsVector(builder, weaps); -~~~ -
-
-~~~{.kt} - // Place the two weapons into an array, and pass it to the `createWeaponsVector()` method to - // create a FlatBuffer vector. - val weaps = intArrayOf(sword, axe) - - // Pass the `weaps` array into the `createWeaponsVector()` method to create a FlatBuffer vector. - val weapons = Monster.createWeaponsVector(builder, weaps) -~~~ -
-
-~~~{.cs} - var weaps = new Offset[2]; - weaps[0] = sword; - weaps[1] = axe; - - // Pass the `weaps` array into the `CreateWeaponsVector()` method to create a FlatBuffer vector. - var weapons = Monster.CreateWeaponsVector(builder, weaps); -~~~ -
-
-~~~{.go} - // Create a FlatBuffer vector and prepend the weapons. - // Note: Since we prepend the data, prepend them in reverse order. - sample.MonsterStartWeaponsVector(builder, 2) - builder.PrependUOffsetT(axe) - builder.PrependUOffsetT(sword) - weapons := builder.EndVector(2) -~~~ -
-
-~~~{.py} - # Create a FlatBuffer vector and prepend the weapons. - # Note: Since we prepend the data, prepend them in reverse order. - MyGame.Sample.Monster.StartWeaponsVector(builder, 2) - builder.PrependUOffsetTRelative(axe) - builder.PrependUOffsetTRelative(sword) - weapons = builder.EndVector() -~~~ -
-
-~~~{.js} - // Create an array from the two `Weapon`s and pass it to the - // `createWeaponsVector()` method to create a FlatBuffer vector. - var weaps = [sword, axe]; - var weapons = MyGame.Sample.Monster.createWeaponsVector(builder, weaps); -~~~ -
-
-~~~{.ts} - // Create an array from the two `Weapon`s and pass it to the - // `createWeaponsVector()` method to create a FlatBuffer vector. - let weaps = [sword, axe]; - let weapons = MyGame.Sample.Monster.createWeaponsVector(builder, weaps); -~~~ -
-
-~~~{.php} - // Create an array from the two `Weapon`s and pass it to the - // `CreateWeaponsVector()` method to create a FlatBuffer vector. - $weaps = array($sword, $axe); - $weapons = \MyGame\Sample\Monster::CreateWeaponsVector($builder, $weaps); -~~~ -
-
-~~~{.c} - // We use the internal builder stack to implement a dynamic vector. - ns(Weapon_vec_start(B)); - ns(Weapon_vec_push(B, sword)); - ns(Weapon_vec_push(B, axe)); - ns(Weapon_vec_ref_t) weapons = ns(Weapon_vec_end(B)); -~~~ -
-
-~~~{.dart} - // If using the Builder classes, serialize the `[sword,axe]` - final weapons = builder.writeList([sword, axe]); - - // If using the ObjectBuilders, just create an array from the two `Weapon`s - final List weaps = [sword, axe]; -~~~ -
-
-~~~{.lua} - -- Create a FlatBuffer vector and prepend the weapons. - -- Note: Since we prepend the data, prepend them in reverse order. - monster.StartWeaponsVector(builder, 2) - builder:PrependUOffsetTRelative(axe) - builder:PrependUOffsetTRelative(sword) - local weapons = builder:EndVector(2) -~~~ -
-
-~~~{.lobster} - let weapons = builder.MyGame_Sample_MonsterCreateWeaponsVector(weapon_offsets) -~~~ -
-
-~~~{.rs} - // Create a FlatBuffer `vector` that contains offsets to the sword and axe - // we created above. - let weapons = builder.create_vector(&[sword, axe]); -~~~ -
-
-~~~{.swift} - // Create a FlatBuffer `vector` that contains offsets to the sword and axe - // we created above. - let weaponsOffset = builder.createVector(ofOffsets: [sword, axe]) -~~~ -
- -
-Note there are additional convenience overloads of `CreateVector`, allowing you -to work with data that's not in a `std::vector` or allowing you to generate -elements by calling a lambda. For the common case of `std::vector` -there's also `CreateVectorOfStrings`. -
- -Note that vectors of structs are serialized differently from tables, since -structs are stored in-line in the vector. For example, to create a vector -for the `path` field above: - -
-~~~{.cpp} - Vec3 points[] = { Vec3(1.0f, 2.0f, 3.0f), Vec3(4.0f, 5.0f, 6.0f) }; - auto path = builder.CreateVectorOfStructs(points, 2); -~~~ -
-
-~~~{.java} - Monster.startPathVector(fbb, 2); - Vec3.createVec3(builder, 1.0f, 2.0f, 3.0f); - Vec3.createVec3(builder, 4.0f, 5.0f, 6.0f); - int path = fbb.endVector(); -~~~ -
-
-~~~{.kt} - Monster.startPathVector(fbb, 2) - Vec3.createVec3(builder, 1.0f, 2.0f, 3.0f) - Vec3.createVec3(builder, 4.0f, 5.0f, 6.0f) - val path = fbb.endVector() -~~~ -
-
-~~~{.cs} - Monster.StartPathVector(fbb, 2); - Vec3.CreateVec3(builder, 1.0f, 2.0f, 3.0f); - Vec3.CreateVec3(builder, 4.0f, 5.0f, 6.0f); - var path = fbb.EndVector(); -~~~ -
-
-~~~{.go} - sample.MonsterStartPathVector(builder, 2) - sample.CreateVec3(builder, 1.0, 2.0, 3.0) - sample.CreateVec3(builder, 4.0, 5.0, 6.0) - path := builder.EndVector(2) -~~~ -
-
-~~~{.py} - MyGame.Sample.Monster.StartPathVector(builder, 2) - MyGame.Sample.Vec3.CreateVec3(builder, 1.0, 2.0, 3.0) - MyGame.Sample.Vec3.CreateVec3(builder, 4.0, 5.0, 6.0) - path = builder.EndVector() -~~~ -
-
-~~~{.js} - MyGame.Sample.Monster.startPathVector(builder, 2); - MyGame.Sample.Vec3.createVec3(builder, 1.0, 2.0, 3.0); - MyGame.Sample.Vec3.createVec3(builder, 4.0, 5.0, 6.0); - var path = builder.endVector(); -~~~ -
-
-~~~{.ts} - MyGame.Sample.Monster.startPathVector(builder, 2); - MyGame.Sample.Vec3.createVec3(builder, 1.0, 2.0, 3.0); - MyGame.Sample.Vec3.createVec3(builder, 4.0, 5.0, 6.0); - let path = builder.endVector(); -~~~ -
-
-~~~{.php} - \MyGame\Example\Monster::StartPathVector($builder, 2); - \MyGame\Sample\Vec3::CreateVec3($builder, 1.0, 2.0, 3.0); - \MyGame\Sample\Vec3::CreateVec3($builder, 1.0, 2.0, 3.0); - $path = $builder->endVector(); -~~~ -
-
-~~~{.c} - // TBD -~~~ -
-
-~~~{.dart} - // Using the Builder classes, you can write a list of structs like so: - // Note that the intended order should be reversed if order is important. - final vec3Builder = new myGame.Vec3Builder(builder); - vec3Builder.finish(4.0, 5.0, 6.0); - vec3Builder.finish(1.0, 2.0, 3.0); - final int path = builder.endStructVector(2); // the length of the vector - - // Otherwise, using the ObjectBuilder classes: - // The dart implementation provides a simple interface for writing vectors - // of structs, in `writeListOfStructs`. This method takes - // `List` and is used by the generated builder classes. - final List path = [ - new myGame.Vec3ObjectBuilder(x: 1.0, y: 2.0, z: 3.0), - new myGame.Vec3ObjectBuilder(x: 4.0, y: 5.0, z: 6.0) - ]; -~~~ -
-
-~~~{.lua} - -- Create a FlatBuffer vector and prepend the path locations. - -- Note: Since we prepend the data, prepend them in reverse order. - monster.StartPathVector(builder, 2) - vec3.CreateVec3(builder, 1.0, 2.0, 3.0) - vec3.CreateVec3(builder, 4.0, 5.0, 6.0) - local path = builder:EndVector(2) -~~~ -
-
-~~~{.lobster} - builder.MyGame_Sample_MonsterStartPathVector(2) - builder.MyGame_Sample_CreateVec3(1.0, 2.0, 3.0) - builder.MyGame_Sample_CreateVec3(4.0, 5.0, 6.0) - let path = builder.EndVector(2) -~~~ -
-
-~~~{.rs} - // Create the path vector of Vec3 objects. - let x = Vec3::new(1.0, 2.0, 3.0); - let y = Vec3::new(4.0, 5.0, 6.0); - let path = builder.create_vector(&[x, y]); - - // Note that, for convenience, it is also valid to create a vector of - // references to structs, like this: - // let path = builder.create_vector(&[&x, &y]); -~~~ -
-
-~~~{.swift} - // - let points = fbb.createVector(ofStructs: [ - Vec3(x: 1, y: 2, z: 3), - Vec3(x: 4, y: 5, z: 6) - ]) - - // OR - var vec3 = [ - Vec3(x: 1, y: 2, z: 3), - Vec3(x: 4, y: 5, z: 6) - ] - Monster.startVectorOfVec3(2, in: &fbb) - for i in obj { - _ = create(struct: i) - } - let points = fbb.endVector(len: size) -~~~ -
- - -We have now serialized the non-scalar components of the orc, so we -can serialize the monster itself: - -
-~~~{.cpp} - // Create the position struct - auto position = Vec3(1.0f, 2.0f, 3.0f); - - // Set his hit points to 300 and his mana to 150. - int hp = 300; - int mana = 150; - - // Finally, create the monster using the `CreateMonster` helper function - // to set all fields. - auto orc = CreateMonster(builder, &position, mana, hp, name, inventory, - Color_Red, weapons, Equipment_Weapon, axe.Union(), - path); -~~~ -
-
-~~~{.java} - // Create our monster using `startMonster()` and `endMonster()`. - Monster.startMonster(builder); - Monster.addPos(builder, Vec3.createVec3(builder, 1.0f, 2.0f, 3.0f)); - Monster.addName(builder, name); - Monster.addColor(builder, Color.Red); - Monster.addHp(builder, (short)300); - Monster.addInventory(builder, inv); - Monster.addWeapons(builder, weapons); - Monster.addEquippedType(builder, Equipment.Weapon); - Monster.addEquipped(builder, axe); - Monster.addPath(builder, path); - int orc = Monster.endMonster(builder); -~~~ -
-
-~~~{.kt} - // Create our monster using `startMonster()` and `endMonster()`. - Monster.startMonster(builder) - Monster.addPos(builder, Vec3.createVec3(builder, 1.0f, 2.0f, 3.0f)) - Monster.addName(builder, name) - Monster.addColor(builder, Color.Red) - Monster.addHp(builder, 300.toShort()) - Monster.addInventory(builder, inv) - Monster.addWeapons(builder, weapons) - Monster.addEquippedType(builder, Equipment.Weapon) - Monster.addEquipped(builder, axe) - Monster.addPath(builder, path) - val orc = Monster.endMonster(builder) -~~~ -
-
-~~~{.cs} - // Create our monster using `StartMonster()` and `EndMonster()`. - Monster.StartMonster(builder); - Monster.AddPos(builder, Vec3.CreateVec3(builder, 1.0f, 2.0f, 3.0f)); - Monster.AddHp(builder, (short)300); - Monster.AddName(builder, name); - Monster.AddInventory(builder, inv); - Monster.AddColor(builder, Color.Red); - Monster.AddWeapons(builder, weapons); - Monster.AddEquippedType(builder, Equipment.Weapon); - Monster.AddEquipped(builder, axe.Value); // Axe - Monster.AddPath(builder, path); - var orc = Monster.EndMonster(builder); -~~~ -
-
-~~~{.go} - // Create our monster using `MonsterStart()` and `MonsterEnd()`. - sample.MonsterStart(builder) - sample.MonsterAddPos(builder, sample.CreateVec3(builder, 1.0, 2.0, 3.0)) - sample.MonsterAddHp(builder, 300) - sample.MonsterAddName(builder, name) - sample.MonsterAddInventory(builder, inv) - sample.MonsterAddColor(builder, sample.ColorRed) - sample.MonsterAddWeapons(builder, weapons) - sample.MonsterAddEquippedType(builder, sample.EquipmentWeapon) - sample.MonsterAddEquipped(builder, axe) - sample.MonsterAddPath(builder, path) - orc := sample.MonsterEnd(builder) -~~~ -
-
-~~~{.py} - # Create our monster by using `Monster.Start()` and `Monster.End()`. - MyGame.Sample.Monster.Start(builder) - MyGame.Sample.Monster.AddPos(builder, - MyGame.Sample.Vec3.CreateVec3(builder, 1.0, 2.0, 3.0)) - MyGame.Sample.Monster.AddHp(builder, 300) - MyGame.Sample.Monster.AddName(builder, name) - MyGame.Sample.Monster.AddInventory(builder, inv) - MyGame.Sample.Monster.AddColor(builder, - MyGame.Sample.Color.Color().Red) - MyGame.Sample.Monster.AddWeapons(builder, weapons) - MyGame.Sample.Monster.AddEquippedType( - builder, MyGame.Sample.Equipment.Equipment().Weapon) - MyGame.Sample.Monster.AddEquipped(builder, axe) - MyGame.Sample.Monster.AddPath(builder, path) - orc = MyGame.Sample.Monster.End(builder) -~~~ -
-
-~~~{.js} - // Create our monster by using `startMonster()` and `endMonster()`. - MyGame.Sample.Monster.startMonster(builder); - MyGame.Sample.Monster.addPos(builder, - MyGame.Sample.Vec3.createVec3(builder, 1.0, 2.0, 3.0)); - MyGame.Sample.Monster.addHp(builder, 300); - MyGame.Sample.Monster.addColor(builder, MyGame.Sample.Color.Red) - MyGame.Sample.Monster.addName(builder, name); - MyGame.Sample.Monster.addInventory(builder, inv); - MyGame.Sample.Monster.addWeapons(builder, weapons); - MyGame.Sample.Monster.addEquippedType(builder, MyGame.Sample.Equipment.Weapon); - MyGame.Sample.Monster.addEquipped(builder, axe); - MyGame.Sample.Monster.addPath(builder, path); - var orc = MyGame.Sample.Monster.endMonster(builder); -~~~ -
-
-~~~{.ts} - // Create our monster by using `startMonster()` and `endMonster()`. - MyGame.Sample.Monster.startMonster(builder); - MyGame.Sample.Monster.addPos(builder, - MyGame.Sample.Vec3.createVec3(builder, 1.0, 2.0, 3.0)); - MyGame.Sample.Monster.addHp(builder, 300); - MyGame.Sample.Monster.addColor(builder, MyGame.Sample.Color.Red) - MyGame.Sample.Monster.addName(builder, name); - MyGame.Sample.Monster.addInventory(builder, inv); - MyGame.Sample.Monster.addWeapons(builder, weapons); - MyGame.Sample.Monster.addEquippedType(builder, MyGame.Sample.Equipment.Weapon); - MyGame.Sample.Monster.addEquipped(builder, axe); - MyGame.Sample.Monster.addPath(builder, path); - let orc = MyGame.Sample.Monster.endMonster(builder); -~~~ -
-
-~~~{.php} - // Create our monster by using `StartMonster()` and `EndMonster()`. - \MyGame\Sample\Monster::StartMonster($builder); - \MyGame\Sample\Monster::AddPos($builder, - \MyGame\Sample\Vec3::CreateVec3($builder, 1.0, 2.0, 3.0)); - \MyGame\Sample\Monster::AddHp($builder, 300); - \MyGame\Sample\Monster::AddName($builder, $name); - \MyGame\Sample\Monster::AddInventory($builder, $inv); - \MyGame\Sample\Monster::AddColor($builder, \MyGame\Sample\Color::Red); - \MyGame\Sample\Monster::AddWeapons($builder, $weapons); - \MyGame\Sample\Monster::AddEquippedType($builder, \MyGame\Sample\Equipment::Weapon); - \MyGame\Sample\Monster::AddEquipped($builder, $axe); - \MyGame\Sample\Monster::AddPath($builder, $path); - $orc = \MyGame\Sample\Monster::EndMonster($builder); -~~~ -
-
-~~~{.c} - // Set his hit points to 300 and his mana to 150. - uint16_t hp = 300; - uint16_t mana = 150; - - // Define an equipment union. `create` calls in C has a single - // argument for unions where C++ has both a type and a data argument. - ns(Equipment_union_ref_t) equipped = ns(Equipment_as_Weapon(axe)); - ns(Vec3_t) pos = { 1.0f, 2.0f, 3.0f }; - ns(Monster_create_as_root(B, &pos, mana, hp, name, inventory, ns(Color_Red), - weapons, equipped, path)); -~~~ -
-
-~~~{.dart} - // Using the Builder API: - // Set his hit points to 300 and his mana to 150. - final int hp = 300; - final int mana = 150; - - final monster = new myGame.MonsterBuilder(builder) - ..begin() - ..addNameOffset(name) - ..addInventoryOffset(inventory) - ..addWeaponsOffset(weapons) - ..addEquippedType(myGame.EquipmentTypeId.Weapon) - ..addEquippedOffset(axe) - ..addHp(hp) - ..addMana(mana) - ..addPos(vec3Builder.finish(1.0, 2.0, 3.0)) - ..addPathOffset(path) - ..addColor(myGame.Color.Red); - - final int orc = monster.finish(); - - // -Or- using the ObjectBuilder API: - // Set his hit points to 300 and his mana to 150. - final int hp = 300; - final int mana = 150; - - // Note that these parameters are optional - it is not necessary to set - // all of them. - // Also note that it is not necessary to `finish` the builder helpers above - // - the generated code will automatically reuse offsets if the same object - // is used in more than one place (e.g. the axe appearing in `weapons` and - // `equipped`). - final myGame.MonsterBuilder orcBuilder = new myGame.MonsterBuilder( - name: name, - inventory: treasure, - weapons: weaps, - equippedType: myGame.EquipmentTypeId.Weapon, - equipped: axe, - path: path, - hp: hp, - mana: mana, - pos: new myGame.Vec3Builder(x: 1.0, y: 2.0, z: 3.0), - color: myGame.Color.Red, - path: [ - new myGame.Vec3ObjectBuilder(x: 1.0, y: 2.0, z: 3.0), - new myGame.Vec3ObjectBuilder(x: 4.0, y: 5.0, z: 6.0) - ]); - - final int orc = orcBuilder.finish(builder); -~~~ -
-
-~~~{.lua} - -- Create our monster by using Start() andEnd() - monster.Start(builder) - monster.AddPos(builder, vec3.CreateVec3(builder, 1.0, 2.0, 3.0)) - monster.AddHp(builder, 300) - monster.AddName(builder, name) - monster.AddInventory(builder, inv) - monster.AddColor(builder, color.Red) - monster.AddWeapons(builder, weapons) - monster.AddEquippedType(builder, equipment.Weapon) - monster.AddEquipped(builder, axe) - monster.AddPath(builder, path) - local orc = monster.End(builder) -~~~ -
-
-~~~{.lobster} - let orc = MyGame_Sample_MonsterBuilder { b } - .start() - .add_pos(b.MyGame_Sample_CreateVec3(1.0, 2.0, 3.0)) - .add_hp(300) - .add_name(name) - .add_inventory(inv) - .add_color(MyGame_Sample_Color_Red) - .add_weapons(weapons) - .add_equipped_type(MyGame_Sample_Equipment_Weapon) - .add_equipped(weapon_offsets[1]) - .add_path(path) - .end() -~~~ -
-
-~~~{.rs} - // Create the monster using the `Monster::create` helper function. This - // function accepts a `MonsterArgs` struct, which supplies all of the data - // needed to build a `Monster`. To supply empty/default fields, just use the - // Rust built-in `Default::default()` function, as demonstrated below. - let orc = Monster::create(&mut builder, &MonsterArgs{ - pos: Some(&Vec3::new(1.0f32, 2.0f32, 3.0f32)), - mana: 150, - hp: 80, - name: Some(name), - inventory: Some(inventory), - color: Color::Red, - weapons: Some(weapons), - equipped_type: Equipment::Weapon, - equipped: Some(axe.as_union_value()), - path: Some(path), - ..Default::default() - }); -~~~ -
-
-~~~{.swift} - let orc = Monster.createMonster( - &builder, - pos: MyGame_Sample_Vec3(x: 1, y: 2, z: 3), - hp: 300, - nameOffset: name, - inventoryVectorOffset: inventoryOffset, - color: .red, - weaponsVectorOffset: weaponsOffset, - equippedType: .weapon, - equippedOffset: axe) -~~~ -
- -Note how we create `Vec3` struct in-line in the table. Unlike tables, structs -are simple combinations of scalars that are always stored inline, just like -scalars themselves. - -**Important**: Unlike structs, you should not nest tables or other objects, -which is why we created all the strings/vectors/tables that this monster refers -to before `start`. If you try to create any of them between `start` and `end`, -you will get an assert/exception/panic depending on your language. - -*Note: Since we are passing `150` as the `mana` field, which happens to be the -default value, the field will not actually be written to the buffer, since the -default value will be returned on query anyway. This is a nice space savings, -especially if default values are common in your data. It also means that you do -not need to be worried about adding a lot of fields that are only used in a small -number of instances, as it will not bloat the buffer if unused.* - -
-
-If you do not wish to set every field in a `table`, it may be more convenient to -manually set each field of your monster, instead of calling `CreateMonster()`. -The following snippet is functionally equivalent to the above code, but provides -a bit more flexibility. -
-~~~{.cpp} - // You can use this code instead of `CreateMonster()`, to create our orc - // manually. - MonsterBuilder monster_builder(builder); - monster_builder.add_pos(&position); - monster_builder.add_hp(hp); - monster_builder.add_name(name); - monster_builder.add_inventory(inventory); - monster_builder.add_color(Color_Red); - monster_builder.add_weapons(weapons); - monster_builder.add_equipped_type(Equipment_Weapon); - monster_builder.add_equipped(axe.Union()); - auto orc = monster_builder.Finish(); -~~~ -
-
-If you do not wish to set every field in a `table`, it may be more convenient to -manually set each field of your monster, instead of calling `create_monster_as_root()`. -The following snippet is functionally equivalent to the above code, but provides -a bit more flexibility. -
-~~~{.c} - // It is important to pair `start_as_root` with `end_as_root`. - ns(Monster_start_as_root(B)); - ns(Monster_pos_create(B, 1.0f, 2.0f, 3.0f)); - // or alternatively - //ns(Monster_pos_add(&pos); - - ns(Monster_hp_add(B, hp)); - // Notice that `Monser_name_add` adds a string reference unlike the - // add_str and add_strn variants. - ns(Monster_name_add(B, name)); - ns(Monster_inventory_add(B, inventory)); - ns(Monster_color_add(B, ns(Color_Red))); - ns(Monster_weapons_add(B, weapons)); - ns(Monster_equipped_add(B, equipped)); - // Complete the monster object and make it the buffer root object. - ns(Monster_end_as_root(B)); -~~~ -
- -
-~~~{.swift} - let start = Monster.startMonster(&builder) - Monster.add(pos: Vec3(x: 1, y: 2, z: 3), &builder) - Monster.add(hp: 300, &builder) - Monster.add(name: name, &builder) - Monster.addVectorOf(inventory: inventoryOffset, &builder) - Monster.add(color: .red, &builder) - Monster.addVectorOf(weapons: weaponsOffset, &builder) - Monster.add(equippedType: .weapon, &builder) - Monster.add(equipped: axe, &builder) - var orc = Monster.endMonster(&builder, start: start) -~~~ -
- -Before finishing the serialization, let's take a quick look at FlatBuffer -`union Equipped`. There are two parts to each FlatBuffer `union`. The first is -a hidden field `_type` that is generated to hold the type of `table` referred -to by the `union`. This allows you to know which type to cast to at runtime. -Second is the `union`'s data. - -In our example, the last two things we added to our `Monster` were the -`Equipped Type` and the `Equipped` union itself. - -Here is a repetition of these lines, to help highlight them more clearly: - -
- ~~~{.cpp} - monster_builder.add_equipped_type(Equipment_Weapon); // Union type - monster_builder.add_equipped(axe.Union()); // Union data - ~~~ -
-
- ~~~{.java} - Monster.addEquippedType(builder, Equipment.Weapon); // Union type - Monster.addEquipped(axe); // Union data - ~~~ -
-
- ~~~{.kt} - Monster.addEquippedType(builder, Equipment.Weapon) // Union type - Monster.addEquipped(axe) // Union data - ~~~ -
-
- ~~~{.cs} - Monster.AddEquippedType(builder, Equipment.Weapon); // Union type - Monster.AddEquipped(builder, axe.Value); // Union data - ~~~ -
-
- ~~~{.go} - sample.MonsterAddEquippedType(builder, sample.EquipmentWeapon) // Union type - sample.MonsterAddEquipped(builder, axe) // Union data - ~~~ -
-
- ~~~{.py} - MyGame.Sample.Monster.AddEquippedType( # Union type - builder, MyGame.Sample.Equipment.Equipment().Weapon) - MyGame.Sample.Monster.AddEquipped(builder, axe) # Union data - ~~~ -
-
- ~~~{.js} - MyGame.Sample.Monster.addEquippedType(builder, MyGame.Sample.Equipment.Weapon); // Union type - MyGame.Sample.Monster.addEquipped(builder, axe); // Union data - ~~~ -
-
- ~~~{.ts} - MyGame.Sample.Monster.addEquippedType(builder, MyGame.Sample.Equipment.Weapon); // Union type - MyGame.Sample.Monster.addEquipped(builder, axe); // Union data - ~~~ -
-
- ~~~{.php} - \MyGame\Sample\Monster::AddEquippedType($builder, \MyGame\Sample\Equipment::Weapon); // Union type - \MyGame\Sample\Monster::AddEquipped($builder, $axe); // Union data - ~~~ -
-
-~~~{.c} - // Add union type and data simultaneously. - ns(Monster_equipped_Weapon_add(B, axe)); -~~~ -
-
-~~~{.dart} - // using the builder API: - ..addEquippedType(myGame.EquipmentTypeId.Weapon) - ..addEquippedOffset(axe) - - // in the ObjectBuilder API: - equippedTypeId: myGame.EquipmentTypeId.Weapon, // Union type - equipped: axe, // Union data -~~~ -
-
-~~~{.lua} - monster.AddEquippedType(builder, equipment.Weapon) -- Union type - monster.AddEquipped(builder, axe) -- Union data -~~~ -
-
-~~~{.lobster} - .add_equipped_type(MyGame_Sample_Equipment_Weapon) - .add_equipped(axe) -~~~ -
-
- ~~~{.rs} - // You need to call `as_union_value` to turn an object into a type that - // can be used as a union value. - monster_builder.add_equipped_type(Equipment::Weapon); // Union type - monster_builder.add_equipped(axe.as_union_value()); // Union data - ~~~ -
-
- ~~~{.swift} - Monster.add(equippedType: .weapon, builder) // Type of union - Monster.add(equipped: axe, builder) // Union data - ~~~ -
- - -After you have created your buffer, you will have the offset to the root of the -data in the `orc` variable, so you can finish the buffer by calling the -appropriate `finish` method. - - -
-~~~{.cpp} - // Call `Finish()` to instruct the builder that this monster is complete. - // Note: Regardless of how you created the `orc`, you still need to call - // `Finish()` on the `FlatBufferBuilder`. - builder.Finish(orc); // You could also call `FinishMonsterBuffer(builder, orc);`. -~~~ -
-
-~~~{.java} - // Call `finish()` to instruct the builder that this monster is complete. - builder.finish(orc); // You could also call `Monster.finishMonsterBuffer(builder, orc);`. -~~~ -
-
-~~~{.kt} - // Call `finish()` to instruct the builder that this monster is complete. - builder.finish(orc) // You could also call `Monster.finishMonsterBuffer(builder, orc);`. -~~~ -
-
-~~~{.cs} - // Call `Finish()` to instruct the builder that this monster is complete. - builder.Finish(orc.Value); // You could also call `Monster.FinishMonsterBuffer(builder, orc);`. -~~~ -
-
-~~~{.go} - // Call `Finish()` to instruct the builder that this monster is complete. - builder.Finish(orc) -~~~ -
-
-~~~{.py} - # Call `Finish()` to instruct the builder that this monster is complete. - builder.Finish(orc) -~~~ -
-
-~~~{.js} - // Call `finish()` to instruct the builder that this monster is complete. - builder.finish(orc); // You could also call `MyGame.Sample.Monster.finishMonsterBuffer(builder, orc);`. -~~~ -
-
-~~~{.ts} - // Call `finish()` to instruct the builder that this monster is complete. - builder.finish(orc); // You could also call `MyGame.Sample.Monster.finishMonsterBuffer(builder, orc);`. -~~~ -
-
-~~~{.php} - // Call `finish()` to instruct the builder that this monster is complete. - $builder->finish($orc); // You may also call `\MyGame\Sample\Monster::FinishMonsterBuffer($builder, $orc);`. -~~~ -
-
-~~~{.c} - // Because we used `Monster_create_as_root`, we do not need a `finish` call in C`. -~~~ -
-
-~~~{.dart} - // Call `finish()` to instruct the builder that this monster is complete. - // See the next code section, as in Dart `finish` will also return the byte array. -~~~ -
-
-~~~{.lua} - -- Call 'Finish()' to instruct the builder that this monster is complete. - builder:Finish(orc) -~~~ -
-
-~~~{.lobster} - // Call `Finish()` to instruct the builder that this monster is complete. - builder.Finish(orc) -~~~ -
-
-~~~{.rs} - // Call `finish()` to instruct the builder that this monster is complete. - builder.finish(orc, None); -~~~ -
-
-~~~{.swift} - // Call `finish(offset:)` to instruct the builder that this monster is complete. - builder.finish(offset: orc) -~~~ -
- -The buffer is now ready to be stored somewhere, sent over the network, be -compressed, or whatever you'd like to do with it. You can access the buffer -like so: - -
-~~~{.cpp} - // This must be called after `Finish()`. - uint8_t *buf = builder.GetBufferPointer(); - int size = builder.GetSize(); // Returns the size of the buffer that - // `GetBufferPointer()` points to. -~~~ -
-
-~~~{.java} - // This must be called after `finish()`. - java.nio.ByteBuffer buf = builder.dataBuffer(); - // The data in this ByteBuffer does NOT start at 0, but at buf.position(). - // The number of bytes is buf.remaining(). - - // Alternatively this copies the above data out of the ByteBuffer for you: - byte[] buf = builder.sizedByteArray(); -~~~ -
-
-~~~{.kt} - // This must be called after `finish()`. - val buf = builder.dataBuffer() - // The data in this ByteBuffer does NOT start at 0, but at buf.position(). - // The number of bytes is buf.remaining(). - - // Alternatively this copies the above data out of the ByteBuffer for you: - val buf = builder.sizedByteArray() -~~~ -
-
-~~~{.cs} - // This must be called after `Finish()`. - var buf = builder.DataBuffer; // Of type `FlatBuffers.ByteBuffer`. - // The data in this ByteBuffer does NOT start at 0, but at buf.Position. - // The end of the data is marked by buf.Length, so the size is - // buf.Length - buf.Position. - - // Alternatively this copies the above data out of the ByteBuffer for you: - byte[] buf = builder.SizedByteArray(); -~~~ -
-
-~~~{.go} - // This must be called after `Finish()`. - buf := builder.FinishedBytes() // Of type `byte[]`. -~~~ -
-
-~~~{.py} - # This must be called after `Finish()`. - buf = builder.Output() // Of type `bytearray`. -~~~ -
-
-~~~{.js} - // This must be called after `finish()`. - var buf = builder.asUint8Array(); // Of type `Uint8Array`. -~~~ -
-
-~~~{.ts} - // This must be called after `finish()`. - let buf = builder.asUint8Array(); // Of type `Uint8Array`. -~~~ -
-
-~~~{.php} - // This must be called after `finish()`. - $buf = $builder->dataBuffer(); // Of type `Google\FlatBuffers\ByteBuffer` - // The data in this ByteBuffer does NOT start at 0, but at buf->getPosition(). - // The end of the data is marked by buf->capacity(), so the size is - // buf->capacity() - buf->getPosition(). -~~~ -
-
-~~~{.c} - uint8_t *buf; - size_t size; - - // Allocate and extract a readable buffer from internal builder heap. - // The returned buffer must be deallocated using `free`. - // NOTE: Finalizing the buffer does NOT change the builder, it - // just creates a snapshot of the builder content. - buf = flatcc_builder_finalize_buffer(B, &size); - // use buf - free(buf); - - // Optionally reset builder to reuse builder without deallocating - // internal stack and heap. - flatcc_builder_reset(B); - // build next buffer. - // ... - - // Cleanup. - flatcc_builder_clear(B); -~~~ -
-
-~~~{.dart} - final Uint8List buf = builder.finish(orc); -~~~ -
-
-~~~{.lua} - -- Get the flatbuffer as a string containing the binary data - local bufAsString = builder:Output() -~~~ -
-
-~~~{.lobster} - // This must be called after `Finish()`. - let buf = builder.SizedCopy() // Of type `string`. -~~~ -
-
-~~~{.rs} - // This must be called after `finish()`. - // `finished_data` returns a byte slice. - let buf = builder.finished_data(); // Of type `&[u8]` -~~~ -
-
-~~~{.swift} - // This must be called after `finish()`. - // `sizedByteArray` returns the finished buf of type [UInt8]. - let buf = builder.sizedByteArray - // or you can use to get an object of type Data - let bufData = ByteBuffer(data: builder.data) -~~~ -
- -Now you can write the bytes to a file or send them over the network. -**Make sure your file mode (or transfer protocol) is set to BINARY, not text.** -If you transfer a FlatBuffer in text mode, the buffer will be corrupted, -which will lead to hard to find problems when you read the buffer. - -
-For example, in Node you can simply do: -~~~{.js} - writeFileSync('monster.bin', buf, 'binary'); -~~~ -
-
-For example, in Node you can simply do: -~~~{.ts} - writeFileSync('monster.bin', buf, 'binary'); -~~~ -
- -#### Reading Orc FlatBuffers - -Now that we have successfully created an `Orc` FlatBuffer, the monster data can -be saved, sent over a network, etc. Let's now adventure into the inverse, and -access a FlatBuffer. - -This section requires the same import/include, namespace, etc. requirements as -before: - -
-~~~{.cpp} - #include "monster_generated.h" // This was generated by `flatc`. - - using namespace MyGame::Sample; // Specified in the schema. -~~~ -
-
-~~~{.java} - import MyGame.Sample.*; //The `flatc` generated files. (Monster, Vec3, etc.) - - import com.google.flatbuffers.FlatBufferBuilder; -~~~ -
-
-~~~{.kt} - import MyGame.Sample.* //The `flatc` generated files. (Monster, Vec3, etc.) - - import com.google.flatbuffers.FlatBufferBuilder -~~~ -
-
-~~~{.cs} - using FlatBuffers; - using MyGame.Sample; // The `flatc` generated files. (Monster, Vec3, etc.) -~~~ -
-
-~~~{.go} - import ( - flatbuffers "github.com/google/flatbuffers/go" - sample "MyGame/Sample" - ) -~~~ -
-
-~~~{.py} - import flatbuffers - - # Generated by `flatc`. - import MyGame.Sample.Any - import MyGame.Sample.Color - import MyGame.Sample.Monster - import MyGame.Sample.Vec3 -~~~ -
-
-~~~{.js} - // The following code is an example - use your desired module flavor by transpiling from TS. - var flatbuffers = require('/js/flatbuffers').flatbuffers; - var MyGame = require('./monster_generated').MyGame; // Generated by `flatc`. - - //--------------------------------------------------------------------------// - - // The following code an example for browser-based HTML/JavaScript. Use the above code - // for JavaScript module loaders (e.g. Node.js). - - // Generated by `flatc`. -~~~ -
-
-~~~{.ts} - // note: import flatbuffers with your desired import method - - // note: the `./monster_generated.ts` file was previously generated by `flatc` above using the `monster.fbs` schema - import { MyGame } from './monster_generated'; -~~~ -
-
-~~~{.php} - // It is recommended that your use PSR autoload when using FlatBuffers in PHP. - // Here is an example from `SampleBinary.php`: - function __autoload($class_name) { - // The last segment of the class name matches the file name. - $class = substr($class_name, strrpos($class_name, "\\") + 1); - $root_dir = join(DIRECTORY_SEPARATOR, array(dirname(dirname(__FILE__)))); // `flatbuffers` root. - - // Contains the `*.php` files for the FlatBuffers library and the `flatc` generated files. - $paths = array(join(DIRECTORY_SEPARATOR, array($root_dir, "php")), - join(DIRECTORY_SEPARATOR, array($root_dir, "samples", "MyGame", "Sample"))); - foreach ($paths as $path) { - $file = join(DIRECTORY_SEPARATOR, array($path, $class . ".php")); - if (file_exists($file)) { - require($file); - break; - } - } - } -~~~ -
-
-~~~{.c} - // Only needed if we don't have `#include "monster_builder.h"`. - #include "monster_reader.h" - - #undef ns - #define ns(x) FLATBUFFERS_WRAP_NAMESPACE(MyGame_Sample, x) // Specified in the schema. -~~~ -
-
-~~~{.dart} -import 'package:flat_buffers/flat_buffers.dart' as fb; -import './monster_my_game.sample_generated.dart' as myGame; -~~~ -
-
-~~~{.lua} - -- require the flatbuffers module - local flatbuffers = require("flatbuffers") - - -- require the generated files from `flatc`. - local color = require("MyGame.Sample.Color") - local equipment = require("MyGame.Sample.Equipment") - local monster = require("MyGame.Sample.Monster") - local vec3 = require("MyGame.Sample.Vec3") - local weapon = require("MyGame.Sample.Weapon") -~~~ -
-
-~~~{.lobster} - import from "../lobster/" // Where to find flatbuffers.lobster - import monster_generated -~~~ -
-
-~~~{.rs} - // import the flatbuffers runtime library - extern crate flatbuffers; - - // import the generated code - #[allow(dead_code, unused_imports)] - #[path = "./monster_generated.rs"] - mod monster_generated; - pub use monster_generated::my_game::sample::{get_root_as_monster, - Color, Equipment, - Monster, MonsterArgs, - Vec3, - Weapon, WeaponArgs}; -~~~ -
- -Then, assuming you have a buffer of bytes received from disk, -network, etc., you can start accessing the buffer like so: - -**Again, make sure you read the bytes in BINARY mode, otherwise the code below -won't work.** - -
-~~~{.cpp} - uint8_t *buffer_pointer = /* the data you just read */; - - // Get a pointer to the root object inside the buffer. - auto monster = GetMonster(buffer_pointer); - - // `monster` is of type `Monster *`. - // Note: root object pointers are NOT the same as `buffer_pointer`. - // `GetMonster` is a convenience function that calls `GetRoot`, - // the latter is also available for non-root types. -~~~ -
-
-~~~{.java} - byte[] bytes = /* the data you just read */ - java.nio.ByteBuffer buf = java.nio.ByteBuffer.wrap(bytes); - - // Get an accessor to the root object inside the buffer. - Monster monster = Monster.getRootAsMonster(buf); -~~~ -
-
-~~~{.kt} - val bytes = /* the data you just read */ - val buf = java.nio.ByteBuffer.wrap(bytes) - - // Get an accessor to the root object inside the buffer. - Monster monster = Monster.getRootAsMonster(buf) -~~~ -
-
-~~~{.cs} - byte[] bytes = /* the data you just read */ - var buf = new ByteBuffer(bytes); - - // Get an accessor to the root object inside the buffer. - var monster = Monster.GetRootAsMonster(buf); -~~~ -
-
-~~~{.go} - var buf []byte = /* the data you just read */ - - // Get an accessor to the root object inside the buffer. - monster := sample.GetRootAsMonster(buf, 0) - - // Note: We use `0` for the offset here, which is typical for most buffers - // you would read. If you wanted to read from `builder.Bytes` directly, you - // would need to pass in the offset of `builder.Head()`, as the builder - // constructs the buffer backwards, so may not start at offset 0. -~~~ -
-
-~~~{.py} - buf = /* the data you just read, in an object of type "bytearray" */ - - // Get an accessor to the root object inside the buffer. - monster = MyGame.Sample.Monster.Monster.GetRootAs(buf, 0) - - # Note: We use `0` for the offset here, which is typical for most buffers - # you would read. If you wanted to read from the `builder.Bytes` directly, - # you would need to pass in the offset of `builder.Head()`, as the builder - # constructs the buffer backwards, so may not start at offset 0. -~~~ -
-
-~~~{.js} - // the data you just read, as a `Uint8Array` - // Note that the example here uses `readFileSync` from the built-in `fs` module, - // but other methods for accessing the file contents will also work. - var bytes = new Uint8Array(readFileSync('./monsterdata.bin')); - - var buf = new flatbuffers.ByteBuffer(bytes); - - // Get an accessor to the root object inside the buffer. - var monster = MyGame.Sample.Monster.getRootAsMonster(buf); -~~~ -
-
-~~~{.ts} - // the data you just read, as a `Uint8Array`. - // Note that the example here uses `readFileSync` from the built-in `fs` module, - // but other methods for accessing the file contents will also work. - let bytes = new Uint8Array(readFileSync('./monsterdata.bin')); - - let buf = new flatbuffers.ByteBuffer(bytes); - - // Get an accessor to the root object inside the buffer. - let monster = MyGame.Sample.Monster.getRootAsMonster(buf); -~~~ -
-
-~~~{.php} - $bytes = /* the data you just read, in a string */ - $buf = Google\FlatBuffers\ByteBuffer::wrap($bytes); - - // Get an accessor to the root object inside the buffer. - $monster = \MyGame\Sample\Monster::GetRootAsMonster($buf); -~~~ -
-
-~~~{.c} - // Note that we use the `table_t` suffix when reading a table object - // as opposed to the `ref_t` suffix used during the construction of - // the buffer. - ns(Monster_table_t) monster = ns(Monster_as_root(buffer)); - - // Note: root object pointers are NOT the same as the `buffer` pointer. -~~~ -
-
-~~~{.dart} -List data = ... // the data, e.g. from file or network -// A generated factory constructor that will read the data. -myGame.Monster monster = new myGame.Monster(data); -~~~ -
-
-~~~{.lua} - local bufAsString = -- The data you just read in - - -- Convert the string representation into binary array Lua structure - local buf = flatbuffers.binaryArray.New(bufAsString) - - -- Get an accessor to the root object insert the buffer - local mon = monster.GetRootAsMonster(buf, 0) -~~~ -
-
-~~~{.lobster} - buf = /* the data you just read, in a string */ - - // Get an accessor to the root object inside the buffer. - let monster = MyGame_Sample_GetRootAsMonster(buf) -~~~ -
-
-~~~{.rs} - let buf = /* the data you just read, in a &[u8] */ - - // Get an accessor to the root object inside the buffer. - let monster = get_root_as_monster(buf); -~~~ -
-
-~~~{.swift} - // create a ByteBuffer(:) from an [UInt8] or Data() - let buf = // Get your data - - // Get an accessor to the root object inside the buffer. - let monster = Monster.getRootAsMonster(bb: ByteBuffer(bytes: buf)) -~~~ -
- -If you look in the generated files from the schema compiler, you will see it generated -accessors for all non-`deprecated` fields. For example: - -
-~~~{.cpp} - auto hp = monster->hp(); - auto mana = monster->mana(); - auto name = monster->name()->c_str(); -~~~ -
-
-~~~{.java} - short hp = monster.hp(); - short mana = monster.mana(); - String name = monster.name(); -~~~ -
-
-~~~{.kt} - val hp = monster.hp - val mana = monster.mana - val name = monster.name -~~~ -
-
-~~~{.cs} - // For C#, unlike most other languages support by FlatBuffers, most values (except for - // vectors and unions) are available as properties instead of accessor methods. - var hp = monster.Hp - var mana = monster.Mana - var name = monster.Name -~~~ -
-
-~~~{.go} - hp := monster.Hp() - mana := monster.Mana() - name := string(monster.Name()) // Note: `monster.Name()` returns a byte[]. -~~~ -
-
-~~~{.py} - hp = monster.Hp() - mana = monster.Mana() - name = monster.Name() -~~~ -
-
-~~~{.js} - var hp = monster.hp(); - var mana = monster.mana(); - var name = monster.name(); -~~~ -
-
-~~~{.ts} - let hp = monster.hp(); - let mana = monster.mana(); - let name = monster.name(); -~~~ -
-
-~~~{.php} - $hp = $monster->getHp(); - $mana = $monster->getMana(); - $name = monster->getName(); -~~~ -
-
-~~~{.c} - uint16_t hp = ns(Monster_hp(monster)); - uint16_t mana = ns(Monster_mana(monster)); - flatbuffers_string_t name = ns(Monster_name(monster)); -~~~ -
-
-~~~{.dart} - // For Dart, unlike other languages support by FlatBuffers, most values - // are available as properties instead of accessor methods. - var hp = monster.hp; - var mana = monster.mana; - var name = monster.name; -~~~ -
-
-~~~{.lua} - local hp = mon:Hp() - local mana = mon:Mana() - local name = mon:Name() -~~~ -
-
-~~~{.lobster} - let hp = monster.hp - let mana = monster.mana - let name = monster.name -~~~ -
-
-~~~{.rs} - // Get and test some scalar types from the FlatBuffer. - let hp = monster.hp(); - let mana = monster.mana(); - let name = monster.name(); -~~~ -
-
-~~~{.swift} - let hp = monster.hp - let mana = monster.mana - let name = monster.name // returns an optional string -~~~ -
- -These should hold `300`, `150`, and `"Orc"` respectively. - -*Note: The default value `150` wasn't stored in `mana`, but we are still able to retrieve it.* - -To access sub-objects, in the case of our `pos`, which is a `Vec3`: - -
-~~~{.cpp} - auto pos = monster->pos(); - auto x = pos->x(); - auto y = pos->y(); - auto z = pos->z(); -~~~ -
-
-~~~{.java} - Vec3 pos = monster.pos(); - float x = pos.x(); - float y = pos.y(); - float z = pos.z(); -~~~ -
-
-~~~{.kt} - val pos = monster.pos!! - val x = pos.x - val y = pos.y - val z = pos.z -~~~ -
-
-~~~{.cs} - var pos = monster.Pos.Value; - var x = pos.X; - var y = pos.Y; - var z = pos.Z; -~~~ -
-
-~~~{.go} - pos := monster.Pos(nil) - x := pos.X() - y := pos.Y() - z := pos.Z() - - // Note: Whenever you access a new object, like in `Pos()`, a new temporary - // accessor object gets created. If your code is very performance sensitive, - // you can pass in a pointer to an existing `Vec3` instead of `nil`. This - // allows you to reuse it across many calls to reduce the amount of object - // allocation/garbage collection. -~~~ -
-
-~~~{.py} - pos = monster.Pos() - x = pos.X() - y = pos.Y() - z = pos.Z() -~~~ -
-
-~~~{.js} - var pos = monster.pos(); - var x = pos.x(); - var y = pos.y(); - var z = pos.z(); -~~~ -
-
-~~~{.ts} - let pos = monster.pos(); - let x = pos.x(); - let y = pos.y(); - let z = pos.z(); -~~~ -
-
-~~~{.php} - $pos = $monster->getPos(); - $x = $pos->getX(); - $y = $pos->getY(); - $z = $pos->getZ(); -~~~ -
-
-~~~{.c} - ns(Vec3_struct_t) pos = ns(Monster_pos(monster)); - float x = ns(Vec3_x(pos)); - float y = ns(Vec3_y(pos)); - float z = ns(Vec3_z(pos)); -~~~ -
-
-~~~{.dart} - myGame.Vec3 pos = monster.pos; - double x = pos.x; - double y = pos.y; - double z = pos.z; -~~~ -
-
-~~~{.lua} - local pos = mon:Pos() - local x = pos:X() - local y = pos:Y() - local z = pos:Z() -~~~ -
-
-~~~{.lobster} - let pos = monster.pos - let x = pos.x - let y = pos.y - let z = pos.z -~~~ -
-
-~~~{.rs} - let pos = monster.pos().unwrap(); - let x = pos.x(); - let y = pos.y(); - let z = pos.z(); -~~~ -
-
-~~~{.swift} - let pos = monster.pos - let x = pos.x - let y = pos.y - let z = pos.z -~~~ -
- -`x`, `y`, and `z` will contain `1.0`, `2.0`, and `3.0`, respectively. - -*Note: Had we not set `pos` during serialization, it would be a `null`-value.* - -Similarly, we can access elements of the inventory `vector` by indexing it. You -can also iterate over the length of the array/vector representing the -FlatBuffers `vector`. - -
-~~~{.cpp} - auto inv = monster->inventory(); // A pointer to a `flatbuffers::Vector<>`. - auto inv_len = inv->size(); - auto third_item = inv->Get(2); -~~~ -
-
-~~~{.java} - int invLength = monster.inventoryLength(); - byte thirdItem = monster.inventory(2); -~~~ -
-
-~~~{.kotlin} - val invLength = monster.inventoryLength - val thirdItem = monster.inventory(2)!! -~~~ -
-
-~~~{.cs} - int invLength = monster.InventoryLength; - var thirdItem = monster.Inventory(2); -~~~ -
-
-~~~{.go} - invLength := monster.InventoryLength() - thirdItem := monster.Inventory(2) -~~~ -
-
-~~~{.py} - inv_len = monster.InventoryLength() - third_item = monster.Inventory(2) -~~~ -
-
-~~~{.js} - var invLength = monster.inventoryLength(); - var thirdItem = monster.inventory(2); -~~~ -
-
-~~~{.ts} - let invLength = monster.inventoryLength(); - let thirdItem = monster.inventory(2); -~~~ -
-
-~~~{.php} - $inv_len = $monster->getInventoryLength(); - $third_item = $monster->getInventory(2); -~~~ -
-
-~~~{.c} - // If `inv` hasn't been set, it will be null. It is valid get - // the length of null which will be 0, useful for iteration. - flatbuffers_uint8_vec_t inv = ns(Monster_inventory(monster)); - size_t inv_len = flatbuffers_uint8_vec_len(inv); -~~~ -
-
-~~~{.dart} - int invLength = monster.inventory.length; - var thirdItem = monster.inventory[2]; -~~~ -
-
-~~~{.lua} - local invLength = mon:InventoryLength() - local thirdItem = mon:Inventory(3) -- Lua is 1-based -~~~ -
-
-~~~{.lobster} - let inv_len = monster.inventory_length - let third_item = monster.inventory(2) -~~~ -
-
-~~~{.rs} - // Get and test an element from the `inventory` FlatBuffer's `vector`. - let inv = monster.inventory().unwrap(); - - // Note that this vector is returned as a slice, because direct access for - // this type, a `u8` vector, is safe on all platforms: - let third_item = inv[2]; -~~~ -
-
-~~~{.swift} - // Get a the count of objects in the vector - let count = monster.inventoryCount - - // get item at index 4 - let object = monster.inventory(at: 4) - - // or you can fetch the entire array - let inv = monster.inventory - // inv[4] should equal object -~~~ -
- -For `vector`s of `table`s, you can access the elements like any other vector, -except you need to handle the result as a FlatBuffer `table`: - -
-~~~{.cpp} - auto weapons = monster->weapons(); // A pointer to a `flatbuffers::Vector<>`. - auto weapon_len = weapons->size(); - auto second_weapon_name = weapons->Get(1)->name()->str(); - auto second_weapon_damage = weapons->Get(1)->damage() -~~~ -
-
-~~~{.java} - int weaponsLength = monster.weaponsLength(); - String secondWeaponName = monster.weapons(1).name(); - short secondWeaponDamage = monster.weapons(1).damage(); -~~~ -
-
-~~~{.kt} - val weaponsLength = monster.weaponsLength - val secondWeaponName = monster.weapons(1)!!.name - val secondWeaponDamage = monster.weapons(1)!!.damage -~~~ -
-
-~~~{.cs} - int weaponsLength = monster.WeaponsLength; - var secondWeaponName = monster.Weapons(1).Name; - var secondWeaponDamage = monster.Weapons(1).Damage; -~~~ -
-
-~~~{.go} - weaponLength := monster.WeaponsLength() - weapon := new(sample.Weapon) // We need a `sample.Weapon` to pass into `monster.Weapons()` - // to capture the output of the function. - if monster.Weapons(weapon, 1) { - secondWeaponName := weapon.Name() - secondWeaponDamage := weapon.Damage() - } -~~~ -
-
-~~~{.py} - weapons_length = monster.WeaponsLength() - second_weapon_name = monster.Weapons(1).Name() - second_weapon_damage = monster.Weapons(1).Damage() -~~~ -
-
-~~~{.js} - var weaponsLength = monster.weaponsLength(); - var secondWeaponName = monster.weapons(1).name(); - var secondWeaponDamage = monster.weapons(1).damage(); -~~~ -
-
-~~~{.ts} - let weaponsLength = monster.weaponsLength(); - let secondWeaponName = monster.weapons(1).name(); - let secondWeaponDamage = monster.weapons(1).damage(); -~~~ -
-
-~~~{.php} - $weapons_len = $monster->getWeaponsLength(); - $second_weapon_name = $monster->getWeapons(1)->getName(); - $second_weapon_damage = $monster->getWeapons(1)->getDamage(); -~~~ -
-
-~~~{.c} - ns(Weapon_vec_t) weapons = ns(Monster_weapons(monster)); - size_t weapons_len = ns(Weapon_vec_len(weapons)); - // We can use `const char *` instead of `flatbuffers_string_t`. - const char *second_weapon_name = ns(Weapon_name(ns(Weapon_vec_at(weapons, 1)))); - uint16_t second_weapon_damage = ns(Weapon_damage(ns(Weapon_vec_at(weapons, 1)))); -~~~ -
-
-~~~{.dart} - int weaponsLength = monster.weapons.length; - var secondWeaponName = monster.weapons[1].name; - var secondWeaponDamage = monster.Weapons[1].damage; -~~~ -
-
-~~~{.lua} - local weaponsLength = mon:WeaponsLength() - local secondWeaponName = mon:Weapon(2):Name() - local secondWeaponDamage = mon:Weapon(2):Damage() -~~~ -
-
-~~~{.lobster} - let weapons_length = monster.weapons_length - let second_weapon_name = monster.weapons(1).name - let second_weapon_damage = monster.weapons(1).damage -~~~ -
-
-~~~{.rs} - // Get and test the `weapons` FlatBuffers's `vector`. - let weps = monster.weapons().unwrap(); - let weps_len = weps.len(); - - let wep2 = weps.get(1); - let second_weapon_name = wep2.name(); - let second_weapon_damage = wep2.damage(); -~~~ -
-
-~~~{.swift} - // Get the count of weapon objects - let wepsCount = monster.weaponsCount - - let weapon2 = monster.weapons(at: 1) - let weaponName = weapon2.name - let weaponDmg = weapon2.damage -~~~ -
- -Last, we can access our `Equipped` FlatBuffer `union`. Just like when we created -the `union`, we need to get both parts of the `union`: the type and the data. - -We can access the type to dynamically cast the data as needed (since the -`union` only stores a FlatBuffer `table`). - -
-~~~{.cpp} - auto union_type = monster->equipped_type(); - - if (union_type == Equipment_Weapon) { - auto weapon = static_cast(monster->equipped()); // Requires `static_cast` - // to type `const Weapon*`. - - auto weapon_name = weapon->name()->str(); // "Axe" - auto weapon_damage = weapon->damage(); // 5 - } -~~~ -
-
-~~~{.java} - int unionType = monster.EquippedType(); - - if (unionType == Equipment.Weapon) { - Weapon weapon = (Weapon)monster.equipped(new Weapon()); // Requires explicit cast - // to `Weapon`. - - String weaponName = weapon.name(); // "Axe" - short weaponDamage = weapon.damage(); // 5 - } -~~~ -
-
-~~~{.kt} - val unionType = monster.EquippedType - - if (unionType == Equipment.Weapon) { - val weapon = monster.equipped(Weapon()) as Weapon // Requires explicit cast - // to `Weapon`. - - val weaponName = weapon.name // "Axe" - val weaponDamage = weapon.damage // 5 - } -~~~ -
-
-~~~{.cs} - var unionType = monster.EquippedType; - - if (unionType == Equipment.Weapon) { - var weapon = monster.Equipped().Value; - - var weaponName = weapon.Name; // "Axe" - var weaponDamage = weapon.Damage; // 5 - } -~~~ -
-
-~~~{.go} - // We need a `flatbuffers.Table` to capture the output of the - // `monster.Equipped()` function. - unionTable := new(flatbuffers.Table) - - if monster.Equipped(unionTable) { - unionType := monster.EquippedType() - - if unionType == sample.EquipmentWeapon { - // Create a `sample.Weapon` object that can be initialized with the contents - // of the `flatbuffers.Table` (`unionTable`), which was populated by - // `monster.Equipped()`. - unionWeapon = new(sample.Weapon) - unionWeapon.Init(unionTable.Bytes, unionTable.Pos) - - weaponName = unionWeapon.Name() - weaponDamage = unionWeapon.Damage() - } - } -~~~ -
-
-~~~{.py} - union_type = monster.EquippedType() - - if union_type == MyGame.Sample.Equipment.Equipment().Weapon: - # `monster.Equipped()` returns a `flatbuffers.Table`, which can be used to - # initialize a `MyGame.Sample.Weapon.Weapon()`. - union_weapon = MyGame.Sample.Weapon.Weapon() - union_weapon.Init(monster.Equipped().Bytes, monster.Equipped().Pos) - - weapon_name = union_weapon.Name() // 'Axe' - weapon_damage = union_weapon.Damage() // 5 -~~~ -
-
-~~~{.js} - var unionType = monster.equippedType(); - - if (unionType == MyGame.Sample.Equipment.Weapon) { - var weaponName = monster.equipped(new MyGame.Sample.Weapon()).name(); // 'Axe' - var weaponDamage = monster.equipped(new MyGame.Sample.Weapon()).damage(); // 5 - } -~~~ -
-
-~~~{.ts} - let unionType = monster.equippedType(); - - if (unionType == MyGame.Sample.Equipment.Weapon) { - let weaponName = monster.equipped(new MyGame.Sample.Weapon()).name(); // 'Axe' - let weaponDamage = monster.equipped(new MyGame.Sample.Weapon()).damage(); // 5 - } -~~~ -
-
-~~~{.php} - $union_type = $monster->getEquippedType(); - - if ($union_type == \MyGame\Sample\Equipment::Weapon) { - $weapon_name = $monster->getEquipped(new \MyGame\Sample\Weapon())->getName(); // "Axe" - $weapon_damage = $monster->getEquipped(new \MyGame\Sample\Weapon())->getDamage(); // 5 - } -~~~ -
-
-~~~{.c} - // Access union type field. - if (ns(Monster_equipped_type(monster)) == ns(Equipment_Weapon)) { - // Cast to appropriate type: - // C allows for silent void pointer assignment, so we need no explicit cast. - ns(Weapon_table_t) weapon = ns(Monster_equipped(monster)); - const char *weapon_name = ns(Weapon_name(weapon)); // "Axe" - uint16_t weapon_damage = ns(Weapon_damage(weapon)); // 5 - } -~~~ -
-
-~~~{.dart} - var unionType = monster.equippedType.value; - - if (unionType == myGame.EquipmentTypeId.Weapon.value) { - myGame.Weapon weapon = mon.equipped as myGame.Weapon; - - var weaponName = weapon.name; // "Axe" - var weaponDamage = weapon.damage; // 5 - } -~~~ -
-
-~~~{.lua} - local unionType = mon:EquippedType() - - if unionType == equipment.Weapon then - local unionWeapon = weapon.New() - unionWeapon:Init(mon:Equipped().bytes, mon:Equipped().pos) - - local weaponName = unionWeapon:Name() -- 'Axe' - local weaponDamage = unionWeapon:Damage() -- 5 - end -~~~ -
-
-~~~{.lobster} - union_type = monster.equipped_type - - if union_type == MyGame_Sample_Equipment_Weapon: - // `monster.equipped_as_Weapon` returns a FlatBuffer handle much like normal table fields, - // but this is only valid to call if we already know it is the correct type. - let union_weapon = monster.equipped_as_Weapon - - let weapon_name = union_weapon.name // "Axe" - let weapon_damage = union_weapon.damage // 5 -~~~ -
-
-~~~{.rs} - // Get and test the `Equipment` union (`equipped` field). - // `equipped_as_weapon` returns a FlatBuffer handle much like normal table - // fields, but this will return `None` if the union is not actually of that - // type. - if monster.equipped_type() == Equipment::Weapon { - let equipped = monster.equipped_as_weapon().unwrap(); - let weapon_name = equipped.name(); - let weapon_damage = equipped.damage(); -~~~ -
-
-~~~{.swift} - // Get and check if the monster has an equipped item - if monster.equippedType == .weapon { - let _weapon = monster.equipped(type: Weapon.self) - let name = _weapon.name // should return "Axe" - let dmg = _weapon.damage // should return 5 - } -~~~ -
- -## Mutating FlatBuffers - -As you saw above, typically once you have created a FlatBuffer, it is read-only -from that moment on. There are, however, cases where you have just received a -FlatBuffer, and you'd like to modify something about it before sending it on to -another recipient. With the above functionality, you'd have to generate an -entirely new FlatBuffer, while tracking what you modified in your own data -structures. This is inconvenient. - -For this reason FlatBuffers can also be mutated in-place. While this is great -for making small fixes to an existing buffer, you generally want to create -buffers from scratch whenever possible, since it is much more efficient and the -API is much more general purpose. - -To get non-const accessors, invoke `flatc` with `--gen-mutable`. - -Similar to how we read fields using the accessors above, we can now use the -mutators like so: - -
-~~~{.cpp} - auto monster = GetMutableMonster(buffer_pointer); // non-const - monster->mutate_hp(10); // Set the table `hp` field. - monster->mutable_pos()->mutate_z(4); // Set struct field. - monster->mutable_inventory()->Mutate(0, 1); // Set vector element. -~~~ -
-
-~~~{.java} - Monster monster = Monster.getRootAsMonster(buf); - monster.mutateHp(10); // Set table field. - monster.pos().mutateZ(4); // Set struct field. - monster.mutateInventory(0, 1); // Set vector element. -~~~ -
-
-~~~{.kt} - val monster = Monster.getRootAsMonster(buf) - monster.mutateHp(10) // Set table field. - monster.pos!!.mutateZ(4) // Set struct field. - monster.mutateInventory(0, 1) // Set vector element. -~~~ -
-
-~~~{.cs} - var monster = Monster.GetRootAsMonster(buf); - monster.MutateHp(10); // Set table field. - monster.Pos.MutateZ(4); // Set struct field. - monster.MutateInventory(0, 1); // Set vector element. -~~~ -
-
-~~~{.go} - -~~~ -
-
-~~~{.py} - -~~~ -
-
-~~~{.js} - -~~~ -
-
-~~~{.ts} - -~~~ -
-
-~~~{.php} - -~~~ -
-
-~~~{.c} - -~~~ -
-
-~~~{.dart} - -~~~ -
-
-~~~{.lua} - -~~~ -
-
-~~~{.lobster} - -~~~ -
-
-~~~{.rs} - -~~~ -
-
-~~~{.swift} - let monster = Monster.getRootAsMonster(bb: ByteBuffer(bytes: buf)) - monster.mutate(hp: 10) // mutates a value in a table - /// to mutate structs in swift you have to use the mutable accessors - monster.mutablePos.mutate(z: 4) // mutates a value in a struct - monster.mutate(inventory: 6, at index: 0) // mutates a value in an Scalar array -~~~ -
- -We use the somewhat verbose term `mutate` instead of `set` to indicate that this -is a special use case, not to be confused with the default way of constructing -FlatBuffer data. - -After the above mutations, you can send on the FlatBuffer to a new recipient -without any further work! - -Note that any `mutate` functions on a table will return a boolean, which is -`false` if the field we're trying to set is not present in the buffer. Fields -are not present if they weren't set, or even if they happen to be equal to -the default value. For example, in the creation code above, the `mana` -field is equal to `150`, which is the default value, so it was never stored in -the buffer. Trying to call the corresponding `mutate` method for `mana` on such -data will return `false`, and the value won't actually be modified! - -One way to solve this is to call `ForceDefaults` on a FlatBufferBuilder to -force all fields you set to actually be written. This, of course, increases the -size of the buffer somewhat, but this may be acceptable for a mutable buffer. - -If this is not sufficient, other ways of mutating FlatBuffers may be supported -in your language through an object based API (`--gen-object-api`) or reflection. -See the individual language documents for support. - -## Using `flatc` as a JSON Conversion Tool - -If you are working with C, C++, or Lobster, you can parse JSON at runtime. -If your language does not support JSON at the moment, `flatc` may provide an -alternative. Using `flatc` is often the preferred method, as it doesn't require you to -add any new code to your program. It is also efficient, since you can ship with -the binary data. The drawback is that it requires an extra step for your -users/developers to perform (although it may be able to be automated -as part of your compilation). - -#### JSON to binary representation - -Let's say you have a JSON file that describes your monster. In this example, -we will use the file `flatbuffers/samples/monsterdata.json`. - -Here are the contents of the file: - -~~~{.json} -{ - "pos": { - "x": 1.0, - "y": 2.0, - "z": 3.0 - }, - "hp": 300, - "name": "Orc", - "weapons": [ - { - "name": "axe", - "damage": 100 - }, - { - "name": "bow", - "damage": 90 - } - ], - "equipped_type": "Weapon", - "equipped": { - "name": "bow", - "damage": 90 - } -} -~~~ - -You can run this file through the `flatc` compiler with the `-b` flag and -our `monster.fbs` schema to produce a FlatBuffer binary file. - -~~~{.sh} -./../flatc --binary monster.fbs monsterdata.json -~~~ - -The output of this will be a file `monsterdata.bin`, which will contain the -FlatBuffer binary representation of the contents from our `.json` file. - -
-*Note: If you're working in C++, you can also parse JSON at runtime. See the -[Use in C++](@ref flatbuffers_guide_use_cpp) section of the Programmer's -Guide for more information.* -
-
-*Note: If you're working in C, the `flatcc --json` (not `flatc`) -compiler will generate schema specific high performance json parsers and -printers that you can compile and use at runtime. The `flatc` compiler (not -`flatcc`) on the other hand, is still useful for general offline json to -flatbuffer conversion from a given schema. There are no current plans -for `flatcc` to support this.* -
-
-*Note: If you're working in Lobster, you can also parse JSON at runtime. See the -[Use in Lobster](@ref flatbuffers_guide_use_lobster) section of the Programmer's -Guide for more information.* -
- -#### FlatBuffer binary to JSON - -Converting from a FlatBuffer binary representation to JSON is supported as well: -~~~{.sh} -./../flatc --json --raw-binary monster.fbs -- monsterdata.bin -~~~ -This will convert `monsterdata.bin` back to its original JSON representation. -You need to pass the corresponding FlatBuffers schema so that flatc knows how to -interpret the binary buffer. Since `monster.fbs` does not specify an explicit -`file_identifier` for binary buffers, `flatc` needs to be forced into reading -the `.bin` file using the `--raw-binary` option. - -The FlatBuffer binary representation does not explicitly encode default values, -therefore they are not present in the resulting JSON unless you specify -`--defaults-json`. - -If you intend to process the JSON with other tools, you may consider switching -on `--strict-json` so that identifiers are quoted properly. - -*Note: The resulting JSON file is not necessarily identical with the original JSON. -If the binary representation contains floating point numbers, floats and doubles -are rounded to 6 and 12 digits, respectively, in order to represent them as -decimals in the JSON document.* - -## Advanced Features for Each Language - -### Vector of Unions - -Some languages support storing unions directly in a vector. - -~~~ -// File found in tests/union_vector/union_vector.fbs -namespace Example.VectorOfUnions; - -// Demonstrates the ability to have vectors of unions, and also to -// store structs and strings in unions. - -table Attacker { - sword_attack_damage: int; -} - -struct Rapunzel { - hair_length: int; -} - -struct BookReader { - books_read: int; -} - -union Character { - MuLan: Attacker, // Can have name be different from type. - Rapunzel, // Or just both the same, as before. - Belle: BookReader, - BookFan: BookReader, - Other: string, - Unused: string -} - -table Movie { - main_character: Character; - characters: [Character]; -} -~~~ - -#### Creating - -Analagously to how a union adds two fields to a table a vector of unions creates two different vectors: -one for the union data and one for the data types. - -
-C++ supports vectors of unions, but it isn't currently documented. -
-
-Typescript supports vectors of unions, but it isn't currently documented. -
-
-PHP supports vectors of unions, but it isn't currently documented. -
-
-Java supports vectors of unions, but it isn't currently documented. -
-
-~~~{.cs} -using FlatBuffers; -using Example.VectorOfUnions; - -var fbb = new FlatBufferBuilder(100); - -var characterTypes = new[] -{ - Character.MuLan, - Character.Belle, - Character.Other, -}; -var characterTypesOffset = Movie.CreateCharactersTypeVector(fbb, characterTypes); - -var characters = new[] -{ - Attacker.CreateAttacker(fbb, 10).Value, - BookReader.CreateBookReader(fbb, 20).Value, - fbb.CreateSharedString("Chip").Value, -}; -var charactersOffset = Movie.CreateCharactersVector(fbb, characters); - -var movieOffset = Movie.CreateMovie( - fbb, - Character.Rapunzel, - rapunzel, - characterTypesOffset, - charactersOffset); -Movie.FinishMovieBuffer(fbb, movieOffset); -~~~ -
-
-Kotlin supports vectors of unions, but it isn't currently documented. -
-
-Swift supports vectors of unions, but it isn't currently documented. -
- -#### Reading -
-~~~{.cs} -var movie = Movie.GetRootAsMovie(fbb.DataBuffer); - -for (var i = 0; i <= movie.CharactersLength; i++) -{ - if (movie.CharactersType(i) == Character.MuLan) - { - var mulanSwordDamage = movie.Characters(i).Value.SwordAttackDamage; - } - else if (movie.CharactersType(i) == Character.Belle) - { - var belleBooksRead = movie.Characters(i).Value.BooksRead; - } - else if (movie.CharactersType(i) == Character.Other) - { - var otherStr = movie.CharactersAsString(i); - } -} -~~~ -
- -### Further Reading - -Each language has a dedicated `Use in XXX` page in the Programmer's Guide -to cover the nuances of FlatBuffers in that language. - -For your chosen language, see: - -
-[Use in C++](@ref flatbuffers_guide_use_cpp) -
-
-[Use in Java](@ref flatbuffers_guide_use_java) -
-
-[Use in Kotlin](@ref flatbuffers_guide_use_kotlin) -
-
-[Use in C#](@ref flatbuffers_guide_use_c-sharp) -
-
-[Use in Go](@ref flatbuffers_guide_use_go) -
-
-[Use in Python](@ref flatbuffers_guide_use_python) -
-
-[Use in JavaScript](@ref flatbuffers_guide_use_javascript) -
-
-[Use in TypeScript](@ref flatbuffers_guide_use_typescript) -
-
-[Use in PHP](@ref flatbuffers_guide_use_php) -
-
-[Use in C](@ref flatbuffers_guide_use_c) -
-
-[Use in Dart](@ref flatbuffers_guide_use_dart) -
-
-[Use in Lua](@ref flatbuffers_guide_use_lua) -
-
-[Use in Lobster](@ref flatbuffers_guide_use_lobster) -
-
-[Use in Rust](@ref flatbuffers_guide_use_rust) -
-
-[Use in Swift](@ref flatbuffers_guide_use_swift) -
-
diff --git a/docs/source/annotation.md b/docs/source/annotation.md new file mode 100644 index 0000000000..cf404202ed --- /dev/null +++ b/docs/source/annotation.md @@ -0,0 +1,149 @@ +# Annotating FlatBuffers + +This provides a way to annotate flatbuffer binary data, byte-by-byte, with a +schema. It is useful for development purposes and understanding the details of +the internal format. + +## Annotating + +Given a `schema`, as either a plain-text (`.fbs`) or a binary schema (`.bfbs`), +and `binary` file(s) that were created by the `schema`. You can annotate them +using: + +```sh +flatc --annotate SCHEMA -- BINARY_FILES... +``` + +This will produce a set of annotated files (`.afb` Annotated FlatBuffer) +corresponding to the input binary files. + +### Example + +Taken from the [tests/annotated_binary](https://github.com/google/flatbuffers/tree/master/tests/annotated_binary). + +```sh +cd tests/annotated_binary +../../flatc --annotate annotated_binary.fbs -- annotated_binary.bin +``` + +Which will produce a `annotated_binary.afb` file in the current directory. + +The `annotated_binary.bin` is the flatbufer binary of the data contained within +`annotated_binary.json`, which was made by the following command: + +```sh +..\..\flatc -b annotated_binary.fbs annotated_binary.json +``` + +## .afb Text Format + +Currently there is a built-in text-based format for outputting the annotations. +A full example is shown here: +[`annotated_binary.afb`](https://github.com/google/flatbuffers/blob/master/tests/annotated_binary/annotated_binary.afb) + +The data is organized as a table with fixed [columns](#columns) grouped into +Binary [sections](#binary-sections) and [regions](#binary-regions), starting +from the beginning of the binary (offset `0`). + +### Columns + +The columns are as follows: + +1. The offset from the start of the binary, expressed in hexadecimal format + (e.g. `+0x003c`). + + The prefix `+` is added to make searching for the offset (compared to some + random value) a bit easier. + +2. The raw binary data, expressed in hexadecimal format. + + This is in the little endian format the buffer uses internally and what you + would see with a normal binary text viewer. + +3. The type of the data. + + This may be the type specified in the schema or some internally defined + types: + + + | Internal Type | Purpose | + |---------------|----------------------------------------------------| + | `VOffset16` | Virtual table offset, relative to the table offset | + | `UOffset32` | Unsigned offset, relative to the current offset | + | `SOffset32` | Signed offset, relative to the current offset | + + +4. The value of the data. + + This is shown in big endian format that is generally written for humans to + consume (e.g. `0x0013`). As well as the "casted" value (e.g. `0x0013 `is + `19` in decimal) in parentheses. + +5. Notes about the particular data. + + This describes what the data is about, either some internal usage, or tied + to the schema. + +### Binary Sections + +The file is broken up into Binary Sections, which are comprised of contiguous +[binary regions](#binary-regions) that are logically grouped together. For +example, a binary section may be a single instance of a flatbuffer `Table` or +its `vtable`. The sections may be labelled with the name of the associated type, +as defined in the input schema. + +An example of a `vtable` Binary Section that is associated with the user-defined +`AnnotateBinary.Bar` table. + +``` +vtable (AnnotatedBinary.Bar): + +0x00A0 | 08 00 | uint16_t | 0x0008 (8) | size of this vtable + +0x00A2 | 13 00 | uint16_t | 0x0013 (19) | size of referring table + +0x00A4 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `a` (id: 0) + +0x00A6 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `b` (id: 1) +``` + +These are purely annotative, there is no embedded information about these +regions in the flatbuffer itself. + +### Binary Regions + +Binary regions are contiguous bytes regions that are grouped together to form +some sort of value, e.g. a `scalar` or an array of scalars. A binary region may +be split up over multiple text lines, if the size of the region is large. + +#### Annotation Example + +Looking at an example binary region: + +``` +vtable (AnnotatedBinary.Bar): + +0x00A0 | 08 00 | uint16_t | 0x0008 (8) | size of this vtable +``` + +The first column (`+0x00A0`) is the offset to this region from the beginning of +the buffer. + +The second column are the raw bytes (hexadecimal) that make up this region. +These are expressed in the little-endian format that flatbuffers uses for the +wire format. + +The third column is the type to interpret the bytes as. For the above example, +the type is `uint16_t` which is a 16-bit unsigned integer type. + +The fourth column shows the raw bytes as a compacted, big-endian value. The raw +bytes are duplicated in this fashion since it is more intuitive to read the data +in the big-endian format (e.g., `0x0008`). This value is followed by the decimal +representation of the value (e.g., `(8)`). For strings, the raw string value is +shown instead. + +The fifth column is a textual comment on what the value is. As much metadata as +known is provided. + +### Offsets + +If the type in the 3rd column is of an absolute offset (`SOffet32` or +`Offset32`), the fourth column also shows an `Loc: +0x025A` value which shows +where in the binary this region is pointing to. These values are absolute from +the beginning of the file, their calculation from the raw value in the 4th +column depends on the context. diff --git a/docs/source/assets/flatbuffers_logo.svg b/docs/source/assets/flatbuffers_logo.svg new file mode 100644 index 0000000000..e302c07dff --- /dev/null +++ b/docs/source/assets/flatbuffers_logo.svg @@ -0,0 +1,318 @@ + + + + diff --git a/docs/source/Benchmarks.md b/docs/source/benchmarks.md similarity index 100% rename from docs/source/Benchmarks.md rename to docs/source/benchmarks.md diff --git a/docs/source/Building.md b/docs/source/building.md similarity index 57% rename from docs/source/Building.md rename to docs/source/building.md index a12abac0eb..9351c05279 100644 --- a/docs/source/Building.md +++ b/docs/source/building.md @@ -1,52 +1,104 @@ -Building {#flatbuffers_guide_building} -======== +# Building ## Building with CMake -The distribution comes with a `cmake` file that should allow -you to build project/make files for any platform. For details on `cmake`, see -. In brief, depending on your platform, use one of -e.g.: +The distribution main build system is configured by +[`cmake`](https://www.cmake.org) which allows you to build the project for any +platform. +### Configuration + +Use `cmake` to configure a project based on your environment and platform. + +=== "Unix" + + ```sh cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release - cmake -G "Visual Studio 10" -DCMAKE_BUILD_TYPE=Release - cmake -G "Xcode" -DCMAKE_BUILD_TYPE=Release + ``` -Then, build as normal for your platform. This should result in a `flatc` -executable, essential for the next steps. -Note that to use clang instead of gcc, you may need to set up your environment -variables, e.g. -`CC=/usr/bin/clang CXX=/usr/bin/clang++ cmake -G "Unix Makefiles"`. +To use `clang` instead of `gcc` you may need to set prepend some environment +variables e.g. `CC=/usr/bin/clang CXX=/usr/bin/clang++ cmake -G "Unix +MakeFiles"` -Optionally, run the `flattests` executable from the root `flatbuffers/` -directory to ensure everything is working correctly on your system. If this -fails, please contact us! +=== "Windows" -Building should also produce two sample executables, `flatsamplebinary` and -`flatsampletext`, see the corresponding `.cpp` files in the -`flatbuffers/samples` directory. + ```sh + cmake -G "Visual Studio 17 2022" -DCMAKE_BUILD_TYPE=Release + ``` -*Note that you MUST be in the root of the FlatBuffers distribution when you -run 'flattests' or `flatsampletext`, or it will fail to load its files.* +=== "MacOS" -### Make all warnings into errors + ```sh + cmake -G "Xcode" -DCMAKE_BUILD_TYPE=Release + ``` + +#### Strict Mode -By default all Flatbuffers `cmake` targets are **not** built with the `-Werror` -(or `/WX` for MSVC) flag that treats any warning as an error. This allows more -flexibility for users of Flatbuffers to use newer compilers and toolsets that -may add new warnings that would cause a build failure. +By default, `cmake` will configure targets to **not** build with strict warnings +on (e.g. `-Werror` or `/WX`). This may cause into issues when submitting code +changes since our CI requires the code to compile in strict mode. -To enable a stricter build that does treat warnings as errors, set the -`FLATBUFFERS_STRICT_MODE` `cmake` compliation flag to `ON`. +To enable the extra warnings, turn on strict mode with the +`FLATBUFFERS_STRICT_MODE` cmake option. +```cmake +cmake -DFLATBUFFERS_STRICT_MODE=ON ``` -cmake . -DFLATBUFFERS_STRICT_MODE=ON + + +### Building + +Once the project files are generated, build as normal for your platform. + +=== "Unix" + + ```sh + make -j + ``` + +=== "Windows" + + ```sh + msbuild.exe FlatBuffers.sln + ``` + +=== "MacOS" + + ```sh + xcodebuild -toolchain clang -configuration Release + ``` + + + + + + +## Building with Bazel + +You can use [Bazelisk](https://github.com/bazelbuild/bazelisk) to manage your Bazel environment. +For Swift support, you also need Clang and [Swift SDK](https://download.swift.org/). + +```sh +curl -sL --fail https://github.com/bazelbuild/bazelisk/releases/download/v1.25.0/bazelisk-linux-amd64 -o bazelisk && chmod +x bazelisk +sudo apt install -y clang +SWIFT_VERSION="6.0.3" +curl -L https://download.swift.org/swift-${SWIFT_VERSION}-release/debian12/swift-${SWIFT_VERSION}-RELEASE/swift-${SWIFT_VERSION}-RELEASE-debian12.tar.gz | tar xz +CC=clang PATH=$PATH:$(pwd)/swift-${SWIFT_VERSION}-RELEASE-debian12/usr/bin bazel build //... +CC=clang PATH=$PATH:$(pwd)/swift-${SWIFT_VERSION}-RELEASE-debian12/usr/bin bazel test //... ``` -Our CI builds run with strict mode on, ensuring the code that is committed to -the project is as portable and warning free as possible. Thus developers -contributing to the project should enable strict mode locally before making a -PR. +If you are unsure which versions to use, check our CI config at `.bazelci/presubmit.yml`. + +## Building with Conan + +You can download and install flatbuffers using the [Conan](https://conan.io/) dependency manager: + + conan install --requires="flatbuffers/[*]" --build=missing + +The flatbuffers package in Conan Center is maintained by +[ConanCenterIndex](https://github.com/conan-io/conan-center-index) community. +If the version is out of date or the package does not work, +please create an issue or pull request on the [Conan Center Index repository](https://github.com/conan-io/conan-center-index). ## Building with VCPKG @@ -61,17 +113,7 @@ You can download and install flatbuffers using the [vcpkg](https://github.com/Mi The flatbuffers port in vcpkg is kept up to date by Microsoft team members and community contributors. If the version is out of date, please [create an issue or pull request](https://github.com/Microsoft/vcpkg) on the vcpkg repository. -## Downloading binaries -You can download the binaries from the -[GitHub release page](https://github.com/google/flatbuffers/releases). -We generate [SLSA3 signatures](slsa.dev) using the OpenSSF's [slsa-framework/slsa-github-generator](https://github.com/slsa-framework/slsa-github-generator). To verify the binaries: -1. Install the verification tool from [slsa-framework/slsa-verifier#installation](https://github.com/slsa-framework/slsa-verifier#installation) -1. Download the file named `attestation.intoto.jsonl` from the GitHub release -1. Run: -```shell -$ slsa-verifier -artifact-path -provenance attestation.intoto.jsonl -source github.com/google/flatbuffers -tag - PASSED: Verified SLSA provenance ## Building for Android @@ -96,7 +138,7 @@ also compile/link `src/idl_parser.cpp` (and `src/idl_gen_text.cpp` if you also want to be able convert binary to text). To see how to include FlatBuffers in any of our supported languages, please -view the [Tutorial](@ref flatbuffers_guide_tutorial) and select your appropriate +view the [Tutorial](tutorial.md) and select your appropriate language using the radio buttons. ### Using in CMake-based projects @@ -121,13 +163,26 @@ add_subdirectory(${FLATBUFFERS_SRC_DIR} # The flatbuffers target carry header search path automatically if CMake > 2.8.11. target_link_libraries(own_project_target PRIVATE flatbuffers) ``` -When build your project the `flatbuffers` library will be compiled and linked +When build your project the `flatbuffers` library will be compiled and linked to a target as part of your project. #### Override default depth limit of nested objects -To override [the depth limit of recursion](@ref flatbuffers_guide_use_cpp), +To override [the depth limit of recursion](languages/cpp.md), add this directive: ```cmake set(FLATBUFFERS_MAX_PARSING_DEPTH 16) ``` to `CMakeLists.txt` file before `add_subdirectory(${FLATBUFFERS_SRC_DIR})` line. + +## Downloading binaries +You can download the binaries from the +[GitHub release page](https://github.com/google/flatbuffers/releases). + +We generate [SLSA3 signatures](http://slsa.dev) using the OpenSSF's [slsa-framework/slsa-github-generator](https://github.com/slsa-framework/slsa-github-generator). To verify the binaries: +1. Install the verification tool from [slsa-framework/slsa-verifier#installation](https://github.com/slsa-framework/slsa-verifier#installation) +1. Download the file named `attestation.intoto.jsonl` from the GitHub release +1. Run: +```shell +$ slsa-verifier -artifact-path -provenance attestation.intoto.jsonl -source github.com/google/flatbuffers -tag + PASSED: Verified SLSA provenance +``` diff --git a/docs/source/contributing.md b/docs/source/contributing.md new file mode 100644 index 0000000000..147e886cbf --- /dev/null +++ b/docs/source/contributing.md @@ -0,0 +1,80 @@ +# Contributing + +We encourage community contributions to FlatBuffers through pull requests at the +main +[http://github.com/google/flatbuffers](http://github.com/google/flatbuffers) +repository. + +!!! note + + The FlatBuffers project is not staffed by any full time Google employee, and + is managed by a small team of 20%ers. So response time and expertise vary. + +## Before you contribute + +Before we can use your contributions, you __must__ sign one of the following license agreements. The agreements are self-served at the following links. + +Our code review process will automatically check if you have signed the CLA, so +don't fret. Though it may be prudent to check before spending a lot of time on +contribution. + +### Individual Contributions + +For individuals, the [Google Individual +Contributor License Agreement +(CLA)](https://cla.developers.google.com/about/google-individual?csw=1) which is +self served at the link. The CLA is required since you own the copyright to your +changes, even after your contribution becomes part of our codebase, so we need +your permission to use and distribute your code. + +### Corporate Contributions + +Contributions made by corporations are covered by the [Google Software Grant and +Corporate Contributor License +Agreement](https://cla.developers.google.com/about/google-corporate). + +## Code Reviews + +All submissions require a code review via Github Pull Requests. + +1. Please adhere to the [Google Style Guide](https://google.github.io/styleguide/cppguide.html) for the language(s) you are submitting in. +2. Keep PRs small and focused. Its good practice and makes it more likely your PR will be approved. +3. Please add tests if possible. +4. Include descriptive commit messages and context to the change/issues fixed. + +## Documentation + +FlatBuffers uses [MkDocs](https://www.mkdocs.org/) to generate the static +documentation pages served at +[https://flatbuffers.dev](https://flatbuffers.dev). Specifically, we use the +[Material for MkDocs](https://squidfunk.github.io/mkdocs-material/) framework. + +The documentation source is contained in the main repo under the +[docs/](https://github.com/google/flatbuffers/tree/master/docs) directory. This +[automatically](https://github.com/google/flatbuffers/blob/46cc3d6432da17cca7694777dcce12e49dd48387/.github/workflows/docs.yml#L6-L11) get built and published when the commit is made. + +### Local Development + +We encourage contributors to keep the documentation up-to-date as well, and it +is easy to with `MkDocs` local building and serving tools. + +First install `mkdocs-material` (see +[Installation](https://squidfunk.github.io/mkdocs-material/getting-started/) for +other ways) + +``` +pip install mkdocs-material +pip install mkdocs-redirects +``` + +Then, in the `root` directory of flatbuffers, run + +``` +mkdocs serve -f docs/mkdocs.yml +``` + +This will continually watch the repo for changes to the documentation and serve +the rendered pages locally. + +Submit your documentation changes with your code changes and they will +automatically get published when your code is submitted. diff --git a/docs/source/doxyfile b/docs/source/doxyfile deleted file mode 100644 index 8cf9000da3..0000000000 --- a/docs/source/doxyfile +++ /dev/null @@ -1,2374 +0,0 @@ -# Doxyfile 1.8.5 - -# This file describes the settings to be used by the documentation system -# doxygen (www.doxygen.org) for a project. -# -# All text after a double hash (##) is considered a comment and is placed in -# front of the TAG it is preceding. -# -# All text after a single hash (#) is considered a comment and will be ignored. -# The format is: -# TAG = value [value, ...] -# For lists, items can also be appended using: -# TAG += value [value, ...] -# Values that contain spaces should be placed between quotes (\" \"). - -#--------------------------------------------------------------------------- -# Project related configuration options -#--------------------------------------------------------------------------- - -# This tag specifies the encoding used for all characters in the config file -# that follow. The default is UTF-8 which is also the encoding used for all text -# before the first occurrence of this tag. Doxygen uses libiconv (or the iconv -# built into libc) for the transcoding. See http://www.gnu.org/software/libiconv -# for the list of possible encodings. -# The default value is: UTF-8. - -DOXYFILE_ENCODING = UTF-8 - -# The PROJECT_NAME tag is a single word (or a sequence of words surrounded by -# double-quotes, unless you are using Doxywizard) that should identify the -# project for which the documentation is generated. This name is used in the -# title of most generated pages and in a few other places. -# The default value is: My Project. - -PROJECT_NAME = "FlatBuffers" - -# The PROJECT_NUMBER tag can be used to enter a project or revision number. This -# could be handy for archiving the generated documentation or if some version -# control system is used. - -PROJECT_NUMBER = - -# Using the PROJECT_BRIEF tag one can provide an optional one line description -# for a project that appears at the top of each page and should give viewer a -# quick idea about the purpose of the project. Keep the description short. - -PROJECT_BRIEF = - -# With the PROJECT_LOGO tag one can specify an logo or icon that is included in -# the documentation. The maximum height of the logo should not exceed 55 pixels -# and the maximum width should not exceed 200 pixels. Doxygen will copy the logo -# to the output directory. - -PROJECT_LOGO = - -# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path -# into which the generated documentation will be written. If a relative path is -# entered, it will be relative to the location where doxygen was started. If -# left blank the current directory will be used. - -OUTPUT_DIRECTORY = ".." - -# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create 4096 sub- -# directories (in 2 levels) under the output directory of each output format and -# will distribute the generated files over these directories. Enabling this -# option can be useful when feeding doxygen a huge amount of source files, where -# putting all generated files in the same directory would otherwise causes -# performance problems for the file system. -# The default value is: NO. - -CREATE_SUBDIRS = NO - -# The OUTPUT_LANGUAGE tag is used to specify the language in which all -# documentation generated by doxygen is written. Doxygen will use this -# information to generate all constant output in the proper language. -# Possible values are: Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese- -# Traditional, Croatian, Czech, Danish, Dutch, English, Esperanto, Farsi, -# Finnish, French, German, Greek, Hungarian, Italian, Japanese, Japanese-en, -# Korean, Korean-en, Latvian, Norwegian, Macedonian, Persian, Polish, -# Portuguese, Romanian, Russian, Serbian, Slovak, Slovene, Spanish, Swedish, -# Turkish, Ukrainian and Vietnamese. -# The default value is: English. - -OUTPUT_LANGUAGE = English - -# If the BRIEF_MEMBER_DESC tag is set to YES doxygen will include brief member -# descriptions after the members that are listed in the file and class -# documentation (similar to Javadoc). Set to NO to disable this. -# The default value is: YES. - -BRIEF_MEMBER_DESC = YES - -# If the REPEAT_BRIEF tag is set to YES doxygen will prepend the brief -# description of a member or function before the detailed description -# -# Note: If both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the -# brief descriptions will be completely suppressed. -# The default value is: YES. - -REPEAT_BRIEF = YES - -# This tag implements a quasi-intelligent brief description abbreviator that is -# used to form the text in various listings. Each string in this list, if found -# as the leading text of the brief description, will be stripped from the text -# and the result, after processing the whole list, is used as the annotated -# text. Otherwise, the brief description is used as-is. If left blank, the -# following values are used ($name is automatically replaced with the name of -# the entity):The $name class, The $name widget, The $name file, is, provides, -# specifies, contains, represents, a, an and the. - -ABBREVIATE_BRIEF = "The $name class" \ - "The $name widget" \ - "The $name file" \ - is \ - provides \ - specifies \ - contains \ - represents \ - a \ - an \ - the - -# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then -# doxygen will generate a detailed section even if there is only a brief -# description. -# The default value is: NO. - -ALWAYS_DETAILED_SEC = NO - -# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all -# inherited members of a class in the documentation of that class as if those -# members were ordinary class members. Constructors, destructors and assignment -# operators of the base classes will not be shown. -# The default value is: NO. - -INLINE_INHERITED_MEMB = NO - -# If the FULL_PATH_NAMES tag is set to YES doxygen will prepend the full path -# before files name in the file list and in the header files. If set to NO the -# shortest path that makes the file name unique will be used -# The default value is: YES. - -FULL_PATH_NAMES = NO - -# The STRIP_FROM_PATH tag can be used to strip a user-defined part of the path. -# Stripping is only done if one of the specified strings matches the left-hand -# part of the path. The tag can be used to show relative paths in the file list. -# If left blank the directory from which doxygen is run is used as the path to -# strip. -# -# Note that you can specify absolute paths here, but also relative paths, which -# will be relative from the directory where doxygen is started. -# This tag requires that the tag FULL_PATH_NAMES is set to YES. - -STRIP_FROM_PATH = - -# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the -# path mentioned in the documentation of a class, which tells the reader which -# header file to include in order to use a class. If left blank only the name of -# the header file containing the class definition is used. Otherwise one should -# specify the list of include paths that are normally passed to the compiler -# using the -I flag. - -STRIP_FROM_INC_PATH = - -# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but -# less readable) file names. This can be useful is your file systems doesn't -# support long names like on DOS, Mac, or CD-ROM. -# The default value is: NO. - -SHORT_NAMES = NO - -# If the JAVADOC_AUTOBRIEF tag is set to YES then doxygen will interpret the -# first line (until the first dot) of a Javadoc-style comment as the brief -# description. If set to NO, the Javadoc-style will behave just like regular Qt- -# style comments (thus requiring an explicit @brief command for a brief -# description.) -# The default value is: NO. - -JAVADOC_AUTOBRIEF = YES - -# If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first -# line (until the first dot) of a Qt-style comment as the brief description. If -# set to NO, the Qt-style will behave just like regular Qt-style comments (thus -# requiring an explicit \brief command for a brief description.) -# The default value is: NO. - -QT_AUTOBRIEF = NO - -# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make doxygen treat a -# multi-line C++ special comment block (i.e. a block of //! or /// comments) as -# a brief description. This used to be the default behavior. The new default is -# to treat a multi-line C++ comment block as a detailed description. Set this -# tag to YES if you prefer the old behavior instead. -# -# Note that setting this tag to YES also means that rational rose comments are -# not recognized any more. -# The default value is: NO. - -MULTILINE_CPP_IS_BRIEF = NO - -# If the INHERIT_DOCS tag is set to YES then an undocumented member inherits the -# documentation from any documented member that it re-implements. -# The default value is: YES. - -INHERIT_DOCS = YES - -# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce a -# new page for each member. If set to NO, the documentation of a member will be -# part of the file/class/namespace that contains it. -# The default value is: NO. - -SEPARATE_MEMBER_PAGES = NO - -# The TAB_SIZE tag can be used to set the number of spaces in a tab. Doxygen -# uses this value to replace tabs by spaces in code fragments. -# Minimum value: 1, maximum value: 16, default value: 4. - -TAB_SIZE = 2 - -# This tag can be used to specify a number of aliases that act as commands in -# the documentation. An alias has the form: -# name=value -# For example adding -# "sideeffect=@par Side Effects:\n" -# will allow you to put the command \sideeffect (or @sideeffect) in the -# documentation, which will result in a user-defined paragraph with heading -# "Side Effects:". You can put \n's in the value part of an alias to insert -# newlines. - -ALIASES = - -# This tag can be used to specify a number of word-keyword mappings (TCL only). -# A mapping has the form "name=value". For example adding "class=itcl::class" -# will allow you to use the command class in the itcl::class meaning. - -TCL_SUBST = - -# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources -# only. Doxygen will then generate output that is more tailored for C. For -# instance, some of the names that are used will be different. The list of all -# members will be omitted, etc. -# The default value is: NO. - -OPTIMIZE_OUTPUT_FOR_C = NO - -# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or -# Python sources only. Doxygen will then generate output that is more tailored -# for that language. For instance, namespaces will be presented as packages, -# qualified scopes will look different, etc. -# The default value is: NO. - -OPTIMIZE_OUTPUT_JAVA = NO - -# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran -# sources. Doxygen will then generate output that is tailored for Fortran. -# The default value is: NO. - -OPTIMIZE_FOR_FORTRAN = NO - -# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL -# sources. Doxygen will then generate output that is tailored for VHDL. -# The default value is: NO. - -OPTIMIZE_OUTPUT_VHDL = NO - -# Doxygen selects the parser to use depending on the extension of the files it -# parses. With this tag you can assign which parser to use for a given -# extension. Doxygen has a built-in mapping, but you can override or extend it -# using this tag. The format is ext=language, where ext is a file extension, and -# language is one of the parsers supported by doxygen: IDL, Java, Javascript, -# C#, C, C++, D, PHP, Objective-C, Python, Fortran, VHDL. For instance to make -# doxygen treat .inc files as Fortran files (default is PHP), and .f files as C -# (default is Fortran), use: inc=Fortran f=C. -# -# Note For files without extension you can use no_extension as a placeholder. -# -# Note that for custom extensions you also need to set FILE_PATTERNS otherwise -# the files are not read by doxygen. - -EXTENSION_MAPPING = - -# If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments -# according to the Markdown format, which allows for more readable -# documentation. See http://daringfireball.net/projects/markdown/ for details. -# The output of markdown processing is further processed by doxygen, so you can -# mix doxygen, HTML, and XML commands with Markdown formatting. Disable only in -# case of backward compatibilities issues. -# The default value is: YES. - -MARKDOWN_SUPPORT = YES - -# When enabled doxygen tries to link words that correspond to documented -# classes, or namespaces to their corresponding documentation. Such a link can -# be prevented in individual cases by by putting a % sign in front of the word -# or globally by setting AUTOLINK_SUPPORT to NO. -# The default value is: YES. - -AUTOLINK_SUPPORT = NO # Due to the multiple languages included in the API - # reference for FlatBuffers, the Auto-links were - # wrong more often than not. - -# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want -# to include (a tag file for) the STL sources as input, then you should set this -# tag to YES in order to let doxygen match functions declarations and -# definitions whose arguments contain STL classes (e.g. func(std::string); -# versus func(std::string) {}). This also make the inheritance and collaboration -# diagrams that involve STL classes more complete and accurate. -# The default value is: NO. - -BUILTIN_STL_SUPPORT = NO - -# If you use Microsoft's C++/CLI language, you should set this option to YES to -# enable parsing support. -# The default value is: NO. - -CPP_CLI_SUPPORT = NO - -# Set the SIP_SUPPORT tag to YES if your project consists of sip (see: -# http://www.riverbankcomputing.co.uk/software/sip/intro) sources only. Doxygen -# will parse them like normal C++ but will assume all classes use public instead -# of private inheritance when no explicit protection keyword is present. -# The default value is: NO. - -SIP_SUPPORT = NO - -# For Microsoft's IDL there are propget and propput attributes to indicate -# getter and setter methods for a property. Setting this option to YES will make -# doxygen to replace the get and set methods by a property in the documentation. -# This will only work if the methods are indeed getting or setting a simple -# type. If this is not the case, or you want to show the methods anyway, you -# should set this option to NO. -# The default value is: YES. - -IDL_PROPERTY_SUPPORT = NO - -# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC -# tag is set to YES, then doxygen will reuse the documentation of the first -# member in the group (if any) for the other members of the group. By default -# all members of a group must be documented explicitly. -# The default value is: NO. - -DISTRIBUTE_GROUP_DOC = NO - -# Set the SUBGROUPING tag to YES to allow class member groups of the same type -# (for instance a group of public functions) to be put as a subgroup of that -# type (e.g. under the Public Functions section). Set it to NO to prevent -# subgrouping. Alternatively, this can be done per class using the -# \nosubgrouping command. -# The default value is: YES. - -SUBGROUPING = YES - -# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and unions -# are shown inside the group in which they are included (e.g. using \ingroup) -# instead of on a separate page (for HTML and Man pages) or section (for LaTeX -# and RTF). -# -# Note that this feature does not work in combination with -# SEPARATE_MEMBER_PAGES. -# The default value is: NO. - -INLINE_GROUPED_CLASSES = NO - -# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions -# with only public data fields or simple typedef fields will be shown inline in -# the documentation of the scope in which they are defined (i.e. file, -# namespace, or group documentation), provided this scope is documented. If set -# to NO, structs, classes, and unions are shown on a separate page (for HTML and -# Man pages) or section (for LaTeX and RTF). -# The default value is: NO. - -INLINE_SIMPLE_STRUCTS = NO - -# When TYPEDEF_HIDES_STRUCT tag is enabled, a typedef of a struct, union, or -# enum is documented as struct, union, or enum with the name of the typedef. So -# typedef struct TypeS {} TypeT, will appear in the documentation as a struct -# with name TypeT. When disabled the typedef will appear as a member of a file, -# namespace, or class. And the struct will be named TypeS. This can typically be -# useful for C code in case the coding convention dictates that all compound -# types are typedef'ed and only the typedef is referenced, never the tag name. -# The default value is: NO. - -TYPEDEF_HIDES_STRUCT = NO - -# The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This -# cache is used to resolve symbols given their name and scope. Since this can be -# an expensive process and often the same symbol appears multiple times in the -# code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small -# doxygen will become slower. If the cache is too large, memory is wasted. The -# cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range -# is 0..9, the default is 0, corresponding to a cache size of 2^16=65536 -# symbols. At the end of a run doxygen will report the cache usage and suggest -# the optimal cache size from a speed point of view. -# Minimum value: 0, maximum value: 9, default value: 0. - -LOOKUP_CACHE_SIZE = 0 - -#--------------------------------------------------------------------------- -# Build related configuration options -#--------------------------------------------------------------------------- - -# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in -# documentation are documented, even if no documentation was available. Private -# class members and static file members will be hidden unless the -# EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES. -# Note: This will also disable the warnings about undocumented members that are -# normally produced when WARNINGS is set to YES. -# The default value is: NO. - -EXTRACT_ALL = NO - -# If the EXTRACT_PRIVATE tag is set to YES all private members of a class will -# be included in the documentation. -# The default value is: NO. - -EXTRACT_PRIVATE = NO - -# If the EXTRACT_PACKAGE tag is set to YES all members with package or internal -# scope will be included in the documentation. -# The default value is: NO. - -EXTRACT_PACKAGE = NO - -# If the EXTRACT_STATIC tag is set to YES all static members of a file will be -# included in the documentation. -# The default value is: NO. - -EXTRACT_STATIC = YES - -# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) defined -# locally in source files will be included in the documentation. If set to NO -# only classes defined in header files are included. Does not have any effect -# for Java sources. -# The default value is: YES. - -EXTRACT_LOCAL_CLASSES = NO - -# This flag is only useful for Objective-C code. When set to YES local methods, -# which are defined in the implementation section but not in the interface are -# included in the documentation. If set to NO only methods in the interface are -# included. -# The default value is: NO. - -EXTRACT_LOCAL_METHODS = NO - -# If this flag is set to YES, the members of anonymous namespaces will be -# extracted and appear in the documentation as a namespace called -# 'anonymous_namespace{file}', where file will be replaced with the base name of -# the file that contains the anonymous namespace. By default anonymous namespace -# are hidden. -# The default value is: NO. - -EXTRACT_ANON_NSPACES = NO - -# If the HIDE_UNDOC_MEMBERS tag is set to YES, doxygen will hide all -# undocumented members inside documented classes or files. If set to NO these -# members will be included in the various overviews, but no documentation -# section is generated. This option has no effect if EXTRACT_ALL is enabled. -# The default value is: NO. - -HIDE_UNDOC_MEMBERS = NO - -# If the HIDE_UNDOC_CLASSES tag is set to YES, doxygen will hide all -# undocumented classes that are normally visible in the class hierarchy. If set -# to NO these classes will be included in the various overviews. This option has -# no effect if EXTRACT_ALL is enabled. -# The default value is: NO. - -HIDE_UNDOC_CLASSES = NO - -# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, doxygen will hide all friend -# (class|struct|union) declarations. If set to NO these declarations will be -# included in the documentation. -# The default value is: NO. - -HIDE_FRIEND_COMPOUNDS = NO - -# If the HIDE_IN_BODY_DOCS tag is set to YES, doxygen will hide any -# documentation blocks found inside the body of a function. If set to NO these -# blocks will be appended to the function's detailed documentation block. -# The default value is: NO. - -HIDE_IN_BODY_DOCS = NO - -# The INTERNAL_DOCS tag determines if documentation that is typed after a -# \internal command is included. If the tag is set to NO then the documentation -# will be excluded. Set it to YES to include the internal documentation. -# The default value is: NO. - -INTERNAL_DOCS = NO - -# If the CASE_SENSE_NAMES tag is set to NO then doxygen will only generate file -# names in lower-case letters. If set to YES upper-case letters are also -# allowed. This is useful if you have classes or files whose names only differ -# in case and if your file system supports case sensitive file names. Windows -# and Mac users are advised to set this option to NO. -# The default value is: system dependent. - -CASE_SENSE_NAMES = NO - -# If the HIDE_SCOPE_NAMES tag is set to NO then doxygen will show members with -# their full class and namespace scopes in the documentation. If set to YES the -# scope will be hidden. -# The default value is: NO. - -HIDE_SCOPE_NAMES = NO - -# If the SHOW_INCLUDE_FILES tag is set to YES then doxygen will put a list of -# the files that are included by a file in the documentation of that file. -# The default value is: YES. - -SHOW_INCLUDE_FILES = YES - -# If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include -# files with double quotes in the documentation rather than with sharp brackets. -# The default value is: NO. - -FORCE_LOCAL_INCLUDES = NO - -# If the INLINE_INFO tag is set to YES then a tag [inline] is inserted in the -# documentation for inline members. -# The default value is: YES. - -INLINE_INFO = YES - -# If the SORT_MEMBER_DOCS tag is set to YES then doxygen will sort the -# (detailed) documentation of file and class members alphabetically by member -# name. If set to NO the members will appear in declaration order. -# The default value is: YES. - -SORT_MEMBER_DOCS = YES - -# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief -# descriptions of file, namespace and class members alphabetically by member -# name. If set to NO the members will appear in declaration order. -# The default value is: NO. - -SORT_BRIEF_DOCS = YES - -# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the -# (brief and detailed) documentation of class members so that constructors and -# destructors are listed first. If set to NO the constructors will appear in the -# respective orders defined by SORT_BRIEF_DOCS and SORT_MEMBER_DOCS. -# Note: If SORT_BRIEF_DOCS is set to NO this option is ignored for sorting brief -# member documentation. -# Note: If SORT_MEMBER_DOCS is set to NO this option is ignored for sorting -# detailed member documentation. -# The default value is: NO. - -SORT_MEMBERS_CTORS_1ST = NO - -# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the hierarchy -# of group names into alphabetical order. If set to NO the group names will -# appear in their defined order. -# The default value is: NO. - -SORT_GROUP_NAMES = NO - -# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be sorted by -# fully-qualified names, including namespaces. If set to NO, the class list will -# be sorted only by class name, not including the namespace part. -# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. -# Note: This option applies only to the class list, not to the alphabetical -# list. -# The default value is: NO. - -SORT_BY_SCOPE_NAME = NO - -# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper -# type resolution of all parameters of a function it will reject a match between -# the prototype and the implementation of a member function even if there is -# only one candidate or it is obvious which candidate to choose by doing a -# simple string match. By disabling STRICT_PROTO_MATCHING doxygen will still -# accept a match between prototype and implementation in such cases. -# The default value is: NO. - -STRICT_PROTO_MATCHING = NO - -# The GENERATE_TODOLIST tag can be used to enable ( YES) or disable ( NO) the -# todo list. This list is created by putting \todo commands in the -# documentation. -# The default value is: YES. - -GENERATE_TODOLIST = NO - -# The GENERATE_TESTLIST tag can be used to enable ( YES) or disable ( NO) the -# test list. This list is created by putting \test commands in the -# documentation. -# The default value is: YES. - -GENERATE_TESTLIST = NO - -# The GENERATE_BUGLIST tag can be used to enable ( YES) or disable ( NO) the bug -# list. This list is created by putting \bug commands in the documentation. -# The default value is: YES. - -GENERATE_BUGLIST = NO - -# The GENERATE_DEPRECATEDLIST tag can be used to enable ( YES) or disable ( NO) -# the deprecated list. This list is created by putting \deprecated commands in -# the documentation. -# The default value is: YES. - -GENERATE_DEPRECATEDLIST= YES - -# The ENABLED_SECTIONS tag can be used to enable conditional documentation -# sections, marked by \if ... \endif and \cond -# ... \endcond blocks. - -ENABLED_SECTIONS = - -# The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the -# initial value of a variable or macro / define can have for it to appear in the -# documentation. If the initializer consists of more lines than specified here -# it will be hidden. Use a value of 0 to hide initializers completely. The -# appearance of the value of individual variables and macros / defines can be -# controlled using \showinitializer or \hideinitializer command in the -# documentation regardless of this setting. -# Minimum value: 0, maximum value: 10000, default value: 30. - -MAX_INITIALIZER_LINES = 30 - -# Set the SHOW_USED_FILES tag to NO to disable the list of files generated at -# the bottom of the documentation of classes and structs. If set to YES the list -# will mention the files that were used to generate the documentation. -# The default value is: YES. - -SHOW_USED_FILES = YES - -# Set the SHOW_FILES tag to NO to disable the generation of the Files page. This -# will remove the Files entry from the Quick Index and from the Folder Tree View -# (if specified). -# The default value is: YES. - -SHOW_FILES = YES - -# Set the SHOW_NAMESPACES tag to NO to disable the generation of the Namespaces -# page. This will remove the Namespaces entry from the Quick Index and from the -# Folder Tree View (if specified). -# The default value is: YES. - -SHOW_NAMESPACES = YES - -# The FILE_VERSION_FILTER tag can be used to specify a program or script that -# doxygen should invoke to get the current version for each file (typically from -# the version control system). Doxygen will invoke the program by executing (via -# popen()) the command command input-file, where command is the value of the -# FILE_VERSION_FILTER tag, and input-file is the name of an input file provided -# by doxygen. Whatever the program writes to standard output is used as the file -# version. For an example see the documentation. - -FILE_VERSION_FILTER = - -# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed -# by doxygen. The layout file controls the global structure of the generated -# output files in an output format independent way. To create the layout file -# that represents doxygen's defaults, run doxygen with the -l option. You can -# optionally specify a file name after the option, if omitted DoxygenLayout.xml -# will be used as the name of the layout file. -# -# Note that if you run doxygen from a directory containing a file called -# DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE -# tag is left empty. - -LAYOUT_FILE = doxygen_layout.xml - -# The CITE_BIB_FILES tag can be used to specify one or more bib files containing -# the reference definitions. This must be a list of .bib files. The .bib -# extension is automatically appended if omitted. This requires the bibtex tool -# to be installed. See also http://en.wikipedia.org/wiki/BibTeX for more info. -# For LaTeX the style of the bibliography can be controlled using -# LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the -# search path. Do not use file names with spaces, bibtex cannot handle them. See -# also \cite for info how to create references. - -CITE_BIB_FILES = - -#--------------------------------------------------------------------------- -# Configuration options related to warning and progress messages -#--------------------------------------------------------------------------- - -# The QUIET tag can be used to turn on/off the messages that are generated to -# standard output by doxygen. If QUIET is set to YES this implies that the -# messages are off. -# The default value is: NO. - -QUIET = NO - -# The WARNINGS tag can be used to turn on/off the warning messages that are -# generated to standard error ( stderr) by doxygen. If WARNINGS is set to YES -# this implies that the warnings are on. -# -# Tip: Turn warnings on while writing the documentation. -# The default value is: YES. - -WARNINGS = YES - -# If the WARN_IF_UNDOCUMENTED tag is set to YES, then doxygen will generate -# warnings for undocumented members. If EXTRACT_ALL is set to YES then this flag -# will automatically be disabled. -# The default value is: YES. - -WARN_IF_UNDOCUMENTED = YES - -# If the WARN_IF_DOC_ERROR tag is set to YES, doxygen will generate warnings for -# potential errors in the documentation, such as not documenting some parameters -# in a documented function, or documenting parameters that don't exist or using -# markup commands wrongly. -# The default value is: YES. - -WARN_IF_DOC_ERROR = NO - -# This WARN_NO_PARAMDOC option can be enabled to get warnings for functions that -# are documented, but have no documentation for their parameters or return -# value. If set to NO doxygen will only warn about wrong or incomplete parameter -# documentation, but not about the absence of documentation. -# The default value is: NO. - -WARN_NO_PARAMDOC = NO - -# The WARN_FORMAT tag determines the format of the warning messages that doxygen -# can produce. The string should contain the $file, $line, and $text tags, which -# will be replaced by the file and line number from which the warning originated -# and the warning text. Optionally the format may contain $version, which will -# be replaced by the version of the file (if it could be obtained via -# FILE_VERSION_FILTER) -# The default value is: $file:$line: $text. - -WARN_FORMAT = "$file:$line: $text" - -# The WARN_LOGFILE tag can be used to specify a file to which warning and error -# messages should be written. If left blank the output is written to standard -# error (stderr). - -WARN_LOGFILE = - -#--------------------------------------------------------------------------- -# Configuration options related to the input files -#--------------------------------------------------------------------------- - -# The INPUT tag is used to specify the files and/or directories that contain -# documented source files. You may enter file names like myfile.cpp or -# directories like /usr/src/myproject. Separate the files or directories with -# spaces. -# Note: If this tag is empty the current directory is searched. - -INPUT = "FlatBuffers.md" \ - "Building.md" \ - "Compiler.md" \ - "Schemas.md" \ - "CppUsage.md" \ - "CUsage.md" \ - "DartUsage.md" \ - "GoUsage.md" \ - "JavaUsage.md" \ - "CsharpUsage.md" \ - "SwiftUsage.md" \ - "JavaScriptUsage.md" \ - "TypeScriptUsage.md" \ - "PHPUsage.md" \ - "PythonUsage.md" \ - "LuaUsage.md" \ - "LobsterUsage.md" \ - "RustUsage.md" \ - "Support.md" \ - "Benchmarks.md" \ - "WhitePaper.md" \ - "FlexBuffers.md" \ - "Internals.md" \ - "IntermediateRepresentation.md" \ - "Grammar.md" \ - "../../CONTRIBUTING.md" \ - "Tutorial.md" \ - "GoApi.md" \ - "gRPC/CppUsage.md" \ - "groups" \ - "../../java/com/google/flatbuffers" \ - "../../python/flatbuffers/builder.py" \ - "../../js/flatbuffers.js" \ - "../../php/FlatbufferBuilder.php" \ - "../../net/FlatBuffers/FlatBufferBuilder.cs" \ - "../../include/flatbuffers/flatbuffers.h" \ - "../../go/builder.go" \ - "../../rust/flatbuffers/src/builder.rs" - -# This tag can be used to specify the character encoding of the source files -# that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses -# libiconv (or the iconv built into libc) for the transcoding. See the libiconv -# documentation (see: http://www.gnu.org/software/libiconv) for the list of -# possible encodings. -# The default value is: UTF-8. - -INPUT_ENCODING = UTF-8 - -# If the value of the INPUT tag contains directories, you can use the -# FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and -# *.h) to filter out the source-files in the directories. If left blank the -# following patterns are tested:*.c, *.cc, *.cxx, *.cpp, *.c++, *.java, *.ii, -# *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h, *.hh, *.hxx, *.hpp, -# *.h++, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, *.inc, *.m, *.markdown, -# *.md, *.mm, *.dox, *.py, *.f90, *.f, *.for, *.tcl, *.vhd, *.vhdl, *.ucf, -# *.qsf, *.as and *.js. - -FILE_PATTERNS = *.c \ - *.cc \ - *.cxx \ - *.cpp \ - *.c++ \ - *.java \ - *.ii \ - *.ixx \ - *.ipp \ - *.i++ \ - *.inl \ - *.idl \ - *.ddl \ - *.odl \ - *.h \ - *.hh \ - *.hxx \ - *.hpp \ - *.h++ \ - *.cs \ - *.d \ - *.php \ - *.php4 \ - *.php5 \ - *.phtml \ - *.inc \ - *.m \ - *.markdown \ - *.md \ - *.mm \ - *.dox \ - *.py \ - *.f90 \ - *.f \ - *.for \ - *.tcl \ - *.vhd \ - *.vhdl \ - *.ucf \ - *.qsf \ - *.as \ - *.js \ - *.go - -# The RECURSIVE tag can be used to specify whether or not subdirectories should -# be searched for input files as well. -# The default value is: NO. - -RECURSIVE = YES - -# The EXCLUDE tag can be used to specify files and/or directories that should be -# excluded from the INPUT source files. This way you can easily exclude a -# subdirectory from a directory tree whose root is specified with the INPUT tag. -# -# Note that relative paths are relative to the directory from which doxygen is -# run. - -EXCLUDE = - -# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or -# directories that are symbolic links (a Unix file system feature) are excluded -# from the input. -# The default value is: NO. - -EXCLUDE_SYMLINKS = NO - -# If the value of the INPUT tag contains directories, you can use the -# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude -# certain files from those directories. -# -# Note that the wildcards are matched against the file with absolute path, so to -# exclude all test directories for example use the pattern */test/* - -EXCLUDE_PATTERNS = *_test.py | - __init__.py - -# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names -# (namespaces, classes, functions, etc.) that should be excluded from the -# output. The symbol name can be a fully qualified name, a word, or if the -# wildcard * is used, a substring. Examples: ANamespace, AClass, -# AClass::ANamespace, ANamespace::*Test -# -# Note that the wildcards are matched against the file with absolute path, so to -# exclude all test directories use the pattern */test/* - -EXCLUDE_SYMBOLS = - -# The EXAMPLE_PATH tag can be used to specify one or more files or directories -# that contain example code fragments that are included (see the \include -# command). - -EXAMPLE_PATH = "GoApi_generated.txt" "../../grpc/samples" - -# If the value of the EXAMPLE_PATH tag contains directories, you can use the -# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and -# *.h) to filter out the source-files in the directories. If left blank all -# files are included. - -EXAMPLE_PATTERNS = *.cpp *.h *.txt *.fbs - -# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be -# searched for input files to be used with the \include or \dontinclude commands -# irrespective of the value of the RECURSIVE tag. -# The default value is: NO. - -EXAMPLE_RECURSIVE = YES - -# The IMAGE_PATH tag can be used to specify one or more files or directories -# that contain images that are to be included in the documentation (see the -# \image command). - -IMAGE_PATH = - -# The INPUT_FILTER tag can be used to specify a program that doxygen should -# invoke to filter for each input file. Doxygen will invoke the filter program -# by executing (via popen()) the command: -# -# -# -# where is the value of the INPUT_FILTER tag, and is the -# name of an input file. Doxygen will then use the output that the filter -# program writes to standard output. If FILTER_PATTERNS is specified, this tag -# will be ignored. -# -# Note that the filter must not add or remove lines; it is applied before the -# code is scanned, but not when the output code is generated. If lines are added -# or removed, the anchors will not be placed correctly. - -INPUT_FILTER = - -# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern -# basis. Doxygen will compare the file name with each pattern and apply the -# filter if there is a match. The filters are a list of the form: pattern=filter -# (like *.cpp=my_cpp_filter). See INPUT_FILTER for further information on how -# filters are used. If the FILTER_PATTERNS tag is empty or if none of the -# patterns match the file name, INPUT_FILTER is applied. - -FILTER_PATTERNS = *.py=py_filter - -# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using -# INPUT_FILTER ) will also be used to filter the input files that are used for -# producing the source files to browse (i.e. when SOURCE_BROWSER is set to YES). -# The default value is: NO. - -FILTER_SOURCE_FILES = NO - -# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file -# pattern. A pattern will override the setting for FILTER_PATTERN (if any) and -# it is also possible to disable source filtering for a specific pattern using -# *.ext= (so without naming a filter). -# This tag requires that the tag FILTER_SOURCE_FILES is set to YES. - -FILTER_SOURCE_PATTERNS = - -# If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that -# is part of the input, its contents will be placed on the main page -# (index.html). This can be useful if you have a project on for instance GitHub -# and want to reuse the introduction page also for the doxygen output. - -USE_MDFILE_AS_MAINPAGE = FlatBuffers.md - -#--------------------------------------------------------------------------- -# Configuration options related to source browsing -#--------------------------------------------------------------------------- - -# If the SOURCE_BROWSER tag is set to YES then a list of source files will be -# generated. Documented entities will be cross-referenced with these sources. -# -# Note: To get rid of all source code in the generated output, make sure that -# also VERBATIM_HEADERS is set to NO. -# The default value is: NO. - -SOURCE_BROWSER = NO - -# Setting the INLINE_SOURCES tag to YES will include the body of functions, -# classes and enums directly into the documentation. -# The default value is: NO. - -INLINE_SOURCES = NO - -# Setting the STRIP_CODE_COMMENTS tag to YES will instruct doxygen to hide any -# special comment blocks from generated source code fragments. Normal C, C++ and -# Fortran comments will always remain visible. -# The default value is: YES. - -STRIP_CODE_COMMENTS = NO - -# If the REFERENCED_BY_RELATION tag is set to YES then for each documented -# function all documented functions referencing it will be listed. -# The default value is: NO. - -REFERENCED_BY_RELATION = NO - -# If the REFERENCES_RELATION tag is set to YES then for each documented function -# all documented entities called/used by that function will be listed. -# The default value is: NO. - -REFERENCES_RELATION = NO - -# If the REFERENCES_LINK_SOURCE tag is set to YES and SOURCE_BROWSER tag is set -# to YES, then the hyperlinks from functions in REFERENCES_RELATION and -# REFERENCED_BY_RELATION lists will link to the source code. Otherwise they will -# link to the documentation. -# The default value is: YES. - -REFERENCES_LINK_SOURCE = YES - -# If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the -# source code will show a tooltip with additional information such as prototype, -# brief description and links to the definition and documentation. Since this -# will make the HTML file larger and loading of large files a bit slower, you -# can opt to disable this feature. -# The default value is: YES. -# This tag requires that the tag SOURCE_BROWSER is set to YES. - -SOURCE_TOOLTIPS = YES - -# If the USE_HTAGS tag is set to YES then the references to source code will -# point to the HTML generated by the htags(1) tool instead of doxygen built-in -# source browser. The htags tool is part of GNU's global source tagging system -# (see http://www.gnu.org/software/global/global.html). You will need version -# 4.8.6 or higher. -# -# To use it do the following: -# - Install the latest version of global -# - Enable SOURCE_BROWSER and USE_HTAGS in the config file -# - Make sure the INPUT points to the root of the source tree -# - Run doxygen as normal -# -# Doxygen will invoke htags (and that will in turn invoke gtags), so these -# tools must be available from the command line (i.e. in the search path). -# -# The result: instead of the source browser generated by doxygen, the links to -# source code will now point to the output of htags. -# The default value is: NO. -# This tag requires that the tag SOURCE_BROWSER is set to YES. - -USE_HTAGS = NO - -# If the VERBATIM_HEADERS tag is set the YES then doxygen will generate a -# verbatim copy of the header file for each class for which an include is -# specified. Set to NO to disable this. -# See also: Section \class. -# The default value is: YES. - -VERBATIM_HEADERS = YES - -#--------------------------------------------------------------------------- -# Configuration options related to the alphabetical class index -#--------------------------------------------------------------------------- - -# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index of all -# compounds will be generated. Enable this if the project contains a lot of -# classes, structs, unions or interfaces. -# The default value is: YES. - -ALPHABETICAL_INDEX = YES - -# The COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns in -# which the alphabetical index list will be split. -# Minimum value: 1, maximum value: 20, default value: 5. -# This tag requires that the tag ALPHABETICAL_INDEX is set to YES. - -COLS_IN_ALPHA_INDEX = 5 - -# In case all classes in a project start with a common prefix, all classes will -# be put under the same header in the alphabetical index. The IGNORE_PREFIX tag -# can be used to specify a prefix (or a list of prefixes) that should be ignored -# while generating the index headers. -# This tag requires that the tag ALPHABETICAL_INDEX is set to YES. - -IGNORE_PREFIX = - -#--------------------------------------------------------------------------- -# Configuration options related to the HTML output -#--------------------------------------------------------------------------- - -# If the GENERATE_HTML tag is set to YES doxygen will generate HTML output -# The default value is: YES. - -GENERATE_HTML = YES - -# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. If a -# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of -# it. -# The default directory is: html. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_OUTPUT = html - -# The HTML_FILE_EXTENSION tag can be used to specify the file extension for each -# generated HTML page (for example: .htm, .php, .asp). -# The default value is: .html. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_FILE_EXTENSION = .html - -# The HTML_HEADER tag can be used to specify a user-defined HTML header file for -# each generated HTML page. If the tag is left blank doxygen will generate a -# standard header. -# -# To get valid HTML the header file that includes any scripts and style sheets -# that doxygen needs, which is dependent on the configuration options used (e.g. -# the setting GENERATE_TREEVIEW). It is highly recommended to start with a -# default header using -# doxygen -w html new_header.html new_footer.html new_stylesheet.css -# YourConfigFile -# and then modify the file new_header.html. See also section "Doxygen usage" -# for information on how to generate the default header that doxygen normally -# uses. -# Note: The header is subject to change so you typically have to regenerate the -# default header when upgrading to a newer version of doxygen. For a description -# of the possible markers and block names see the documentation. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_HEADER = ../header.html - -# The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each -# generated HTML page. If the tag is left blank doxygen will generate a standard -# footer. See HTML_HEADER for more information on how to generate a default -# footer and what special commands can be used inside the footer. See also -# section "Doxygen usage" for information on how to generate the default footer -# that doxygen normally uses. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_FOOTER = ../footer.html - -# The HTML_STYLESHEET tag can be used to specify a user-defined cascading style -# sheet that is used by each HTML page. It can be used to fine-tune the look of -# the HTML output. If left blank doxygen will generate a default style sheet. -# See also section "Doxygen usage" for information on how to generate the style -# sheet that doxygen normally uses. -# Note: It is recommended to use HTML_EXTRA_STYLESHEET instead of this tag, as -# it is more robust and this tag (HTML_STYLESHEET) will in the future become -# obsolete. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_STYLESHEET = - -# The HTML_EXTRA_STYLESHEET tag can be used to specify an additional user- -# defined cascading style sheet that is included after the standard style sheets -# created by doxygen. Using this option one can overrule certain style aspects. -# This is preferred over using HTML_STYLESHEET since it does not replace the -# standard style sheet and is therefor more robust against future updates. -# Doxygen will copy the style sheet file to the output directory. For an example -# see the documentation. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_EXTRA_STYLESHEET = style.css - -# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or -# other source files which should be copied to the HTML output directory. Note -# that these files will be copied to the base HTML output directory. Use the -# $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these -# files. In the HTML_STYLESHEET file, use the file name only. Also note that the -# files will be copied as-is; there are no commands or markers available. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_EXTRA_FILES = "../images/fpl_logo_small.png" \ - "../images/ftv2mnode.png" \ - "../images/ftv2pnode.png" - -# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen -# will adjust the colors in the stylesheet and background images according to -# this color. Hue is specified as an angle on a colorwheel, see -# http://en.wikipedia.org/wiki/Hue for more information. For instance the value -# 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300 -# purple, and 360 is red again. -# Minimum value: 0, maximum value: 359, default value: 220. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_COLORSTYLE_HUE = 220 - -# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors -# in the HTML output. For a value of 0 the output will use grayscales only. A -# value of 255 will produce the most vivid colors. -# Minimum value: 0, maximum value: 255, default value: 100. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_COLORSTYLE_SAT = 100 - -# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the -# luminance component of the colors in the HTML output. Values below 100 -# gradually make the output lighter, whereas values above 100 make the output -# darker. The value divided by 100 is the actual gamma applied, so 80 represents -# a gamma of 0.8, The value 220 represents a gamma of 2.2, and 100 does not -# change the gamma. -# Minimum value: 40, maximum value: 240, default value: 80. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_COLORSTYLE_GAMMA = 80 - -# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML -# page will contain the date and time when the page was generated. Setting this -# to NO can help when comparing the output of multiple runs. -# The default value is: YES. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_TIMESTAMP = YES - -# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML -# documentation will contain sections that can be hidden and shown after the -# page has loaded. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_DYNAMIC_SECTIONS = NO - -# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries -# shown in the various tree structured indices initially; the user can expand -# and collapse entries dynamically later on. Doxygen will expand the tree to -# such a level that at most the specified number of entries are visible (unless -# a fully collapsed tree already exceeds this amount). So setting the number of -# entries 1 will produce a full collapsed tree by default. 0 is a special value -# representing an infinite number of entries and will result in a full expanded -# tree by default. -# Minimum value: 0, maximum value: 9999, default value: 100. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_INDEX_NUM_ENTRIES = 100 - -# If the GENERATE_DOCSET tag is set to YES, additional index files will be -# generated that can be used as input for Apple's Xcode 3 integrated development -# environment (see: http://developer.apple.com/tools/xcode/), introduced with -# OSX 10.5 (Leopard). To create a documentation set, doxygen will generate a -# Makefile in the HTML output directory. Running make will produce the docset in -# that directory and running make install will install the docset in -# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at -# startup. See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html -# for more information. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -GENERATE_DOCSET = NO - -# This tag determines the name of the docset feed. A documentation feed provides -# an umbrella under which multiple documentation sets from a single provider -# (such as a company or product suite) can be grouped. -# The default value is: Doxygen generated docs. -# This tag requires that the tag GENERATE_DOCSET is set to YES. - -DOCSET_FEEDNAME = "Doxygen generated docs" - -# This tag specifies a string that should uniquely identify the documentation -# set bundle. This should be a reverse domain-name style string, e.g. -# com.mycompany.MyDocSet. Doxygen will append .docset to the name. -# The default value is: org.doxygen.Project. -# This tag requires that the tag GENERATE_DOCSET is set to YES. - -DOCSET_BUNDLE_ID = org.doxygen.Project - -# The DOCSET_PUBLISHER_ID tag specifies a string that should uniquely identify -# the documentation publisher. This should be a reverse domain-name style -# string, e.g. com.mycompany.MyDocSet.documentation. -# The default value is: org.doxygen.Publisher. -# This tag requires that the tag GENERATE_DOCSET is set to YES. - -DOCSET_PUBLISHER_ID = org.doxygen.Publisher - -# The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher. -# The default value is: Publisher. -# This tag requires that the tag GENERATE_DOCSET is set to YES. - -DOCSET_PUBLISHER_NAME = Publisher - -# If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three -# additional HTML index files: index.hhp, index.hhc, and index.hhk. The -# index.hhp is a project file that can be read by Microsoft's HTML Help Workshop -# (see: http://www.microsoft.com/en-us/download/details.aspx?id=21138) on -# Windows. -# -# The HTML Help Workshop contains a compiler that can convert all HTML output -# generated by doxygen into a single compiled HTML file (.chm). Compiled HTML -# files are now used as the Windows 98 help format, and will replace the old -# Windows help format (.hlp) on all Windows platforms in the future. Compressed -# HTML files also contain an index, a table of contents, and you can search for -# words in the documentation. The HTML workshop also contains a viewer for -# compressed HTML files. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -GENERATE_HTMLHELP = NO - -# The CHM_FILE tag can be used to specify the file name of the resulting .chm -# file. You can add a path in front of the file if the result should not be -# written to the html output directory. -# This tag requires that the tag GENERATE_HTMLHELP is set to YES. - -CHM_FILE = - -# The HHC_LOCATION tag can be used to specify the location (absolute path -# including file name) of the HTML help compiler ( hhc.exe). If non-empty -# doxygen will try to run the HTML help compiler on the generated index.hhp. -# The file has to be specified with full path. -# This tag requires that the tag GENERATE_HTMLHELP is set to YES. - -HHC_LOCATION = - -# The GENERATE_CHI flag controls if a separate .chi index file is generated ( -# YES) or that it should be included in the master .chm file ( NO). -# The default value is: NO. -# This tag requires that the tag GENERATE_HTMLHELP is set to YES. - -GENERATE_CHI = NO - -# The CHM_INDEX_ENCODING is used to encode HtmlHelp index ( hhk), content ( hhc) -# and project file content. -# This tag requires that the tag GENERATE_HTMLHELP is set to YES. - -CHM_INDEX_ENCODING = - -# The BINARY_TOC flag controls whether a binary table of contents is generated ( -# YES) or a normal table of contents ( NO) in the .chm file. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTMLHELP is set to YES. - -BINARY_TOC = NO - -# The TOC_EXPAND flag can be set to YES to add extra items for group members to -# the table of contents of the HTML help documentation and to the tree view. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTMLHELP is set to YES. - -TOC_EXPAND = NO - -# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and -# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that -# can be used as input for Qt's qhelpgenerator to generate a Qt Compressed Help -# (.qch) of the generated HTML documentation. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -GENERATE_QHP = NO - -# If the QHG_LOCATION tag is specified, the QCH_FILE tag can be used to specify -# the file name of the resulting .qch file. The path specified is relative to -# the HTML output folder. -# This tag requires that the tag GENERATE_QHP is set to YES. - -QCH_FILE = - -# The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help -# Project output. For more information please see Qt Help Project / Namespace -# (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#namespace). -# The default value is: org.doxygen.Project. -# This tag requires that the tag GENERATE_QHP is set to YES. - -QHP_NAMESPACE = org.doxygen.Project - -# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt -# Help Project output. For more information please see Qt Help Project / Virtual -# Folders (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#virtual- -# folders). -# The default value is: doc. -# This tag requires that the tag GENERATE_QHP is set to YES. - -QHP_VIRTUAL_FOLDER = doc - -# If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom -# filter to add. For more information please see Qt Help Project / Custom -# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom- -# filters). -# This tag requires that the tag GENERATE_QHP is set to YES. - -QHP_CUST_FILTER_NAME = - -# The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the -# custom filter to add. For more information please see Qt Help Project / Custom -# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom- -# filters). -# This tag requires that the tag GENERATE_QHP is set to YES. - -QHP_CUST_FILTER_ATTRS = - -# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this -# project's filter section matches. Qt Help Project / Filter Attributes (see: -# http://qt-project.org/doc/qt-4.8/qthelpproject.html#filter-attributes). -# This tag requires that the tag GENERATE_QHP is set to YES. - -QHP_SECT_FILTER_ATTRS = - -# The QHG_LOCATION tag can be used to specify the location of Qt's -# qhelpgenerator. If non-empty doxygen will try to run qhelpgenerator on the -# generated .qhp file. -# This tag requires that the tag GENERATE_QHP is set to YES. - -QHG_LOCATION = - -# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be -# generated, together with the HTML files, they form an Eclipse help plugin. To -# install this plugin and make it available under the help contents menu in -# Eclipse, the contents of the directory containing the HTML and XML files needs -# to be copied into the plugins directory of eclipse. The name of the directory -# within the plugins directory should be the same as the ECLIPSE_DOC_ID value. -# After copying Eclipse needs to be restarted before the help appears. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -GENERATE_ECLIPSEHELP = NO - -# A unique identifier for the Eclipse help plugin. When installing the plugin -# the directory name containing the HTML and XML files should also have this -# name. Each documentation set should have its own identifier. -# The default value is: org.doxygen.Project. -# This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES. - -ECLIPSE_DOC_ID = org.doxygen.Project - -# If you want full control over the layout of the generated HTML pages it might -# be necessary to disable the index and replace it with your own. The -# DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) at top -# of each HTML page. A value of NO enables the index and the value YES disables -# it. Since the tabs in the index contain the same information as the navigation -# tree, you can set this option to YES if you also set GENERATE_TREEVIEW to YES. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -DISABLE_INDEX = NO - -# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index -# structure should be generated to display hierarchical information. If the tag -# value is set to YES, a side panel will be generated containing a tree-like -# index structure (just like the one that is generated for HTML Help). For this -# to work a browser that supports JavaScript, DHTML, CSS and frames is required -# (i.e. any modern browser). Windows users are probably better off using the -# HTML help feature. Via custom stylesheets (see HTML_EXTRA_STYLESHEET) one can -# further fine-tune the look of the index. As an example, the default style -# sheet generated by doxygen has an example that shows how to put an image at -# the root of the tree instead of the PROJECT_NAME. Since the tree basically has -# the same information as the tab index, you could consider setting -# DISABLE_INDEX to YES when enabling this option. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -GENERATE_TREEVIEW = YES - -# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that -# doxygen will group on one line in the generated HTML documentation. -# -# Note that a value of 0 will completely suppress the enum values from appearing -# in the overview section. -# Minimum value: 0, maximum value: 20, default value: 4. -# This tag requires that the tag GENERATE_HTML is set to YES. - -ENUM_VALUES_PER_LINE = 4 - -# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be used -# to set the initial width (in pixels) of the frame in which the tree is shown. -# Minimum value: 0, maximum value: 1500, default value: 250. -# This tag requires that the tag GENERATE_HTML is set to YES. - -TREEVIEW_WIDTH = 250 - -# When the EXT_LINKS_IN_WINDOW option is set to YES doxygen will open links to -# external symbols imported via tag files in a separate window. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -EXT_LINKS_IN_WINDOW = NO - -# Use this tag to change the font size of LaTeX formulas included as images in -# the HTML documentation. When you change the font size after a successful -# doxygen run you need to manually remove any form_*.png images from the HTML -# output directory to force them to be regenerated. -# Minimum value: 8, maximum value: 50, default value: 10. -# This tag requires that the tag GENERATE_HTML is set to YES. - -FORMULA_FONTSIZE = 10 - -# Use the FORMULA_TRANPARENT tag to determine whether or not the images -# generated for formulas are transparent PNGs. Transparent PNGs are not -# supported properly for IE 6.0, but are supported on all modern browsers. -# -# Note that when changing this option you need to delete any form_*.png files in -# the HTML output directory before the changes have effect. -# The default value is: YES. -# This tag requires that the tag GENERATE_HTML is set to YES. - -FORMULA_TRANSPARENT = YES - -# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see -# http://www.mathjax.org) which uses client side Javascript for the rendering -# instead of using prerendered bitmaps. Use this if you do not have LaTeX -# installed or if you want to formulas look prettier in the HTML output. When -# enabled you may also need to install MathJax separately and configure the path -# to it using the MATHJAX_RELPATH option. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -USE_MATHJAX = NO - -# When MathJax is enabled you can set the default output format to be used for -# the MathJax output. See the MathJax site (see: -# http://docs.mathjax.org/en/latest/output.html) for more details. -# Possible values are: HTML-CSS (which is slower, but has the best -# compatibility), NativeMML (i.e. MathML) and SVG. -# The default value is: HTML-CSS. -# This tag requires that the tag USE_MATHJAX is set to YES. - -MATHJAX_FORMAT = HTML-CSS - -# When MathJax is enabled you need to specify the location relative to the HTML -# output directory using the MATHJAX_RELPATH option. The destination directory -# should contain the MathJax.js script. For instance, if the mathjax directory -# is located at the same level as the HTML output directory, then -# MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax -# Content Delivery Network so you can quickly see the result without installing -# MathJax. However, it is strongly recommended to install a local copy of -# MathJax from http://www.mathjax.org before deployment. -# The default value is: http://cdn.mathjax.org/mathjax/latest. -# This tag requires that the tag USE_MATHJAX is set to YES. - -MATHJAX_RELPATH = http://cdn.mathjax.org/mathjax/latest - -# The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax -# extension names that should be enabled during MathJax rendering. For example -# MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols -# This tag requires that the tag USE_MATHJAX is set to YES. - -MATHJAX_EXTENSIONS = - -# The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces -# of code that will be used on startup of the MathJax code. See the MathJax site -# (see: http://docs.mathjax.org/en/latest/output.html) for more details. For an -# example see the documentation. -# This tag requires that the tag USE_MATHJAX is set to YES. - -MATHJAX_CODEFILE = - -# When the SEARCHENGINE tag is enabled doxygen will generate a search box for -# the HTML output. The underlying search engine uses javascript and DHTML and -# should work on any modern browser. Note that when using HTML help -# (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET) -# there is already a search function so this one should typically be disabled. -# For large projects the javascript based search engine can be slow, then -# enabling SERVER_BASED_SEARCH may provide a better solution. It is possible to -# search using the keyboard; to jump to the search box use + S -# (what the is depends on the OS and browser, but it is typically -# , /