Squashed 'third_party/flatbuffers/' content from commit 595bf0007

git-subtree-dir: third_party/flatbuffers
git-subtree-split: 595bf0007ab1929570c7671f091313c8fc20644e
This commit is contained in:
Siarhei Fedartsou 2024-06-22 13:33:34 +02:00
commit 0f6aab9da6
1814 changed files with 326902 additions and 0 deletions

38
.bazelci/presubmit.yml Normal file
View File

@ -0,0 +1,38 @@
---
buildifier: latest
bazel: 6.4.0
platforms:
ubuntu1804:
environment:
CC: clang
SWIFT_VERSION: "5.5.3"
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"
build_targets:
- "//..."
test_targets:
- "//..."
ubuntu2004:
environment:
CC: clang
SWIFT_VERSION: "5.5.3"
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"
build_targets:
- "//..."
test_targets:
- "//..."
macos:
xcode_version: "14.2"
build_targets:
- "//..."
test_targets:
- "//..."

1
.bazelignore Normal file
View File

@ -0,0 +1 @@
node_modules

4
.bazelrc Normal file
View File

@ -0,0 +1,4 @@
# 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/ts/bazel_repository_test_dir
query --deleted_packages=tests/ts/bazel_repository_test_dir

13
.clang-format Normal file
View File

@ -0,0 +1,13 @@
---
Language: Cpp
BasedOnStyle: Google
DerivePointerAlignment: false
PointerAlignment: Right
IndentPPDirectives: AfterHash
Cpp11BracedListStyle: false
AlwaysBreakTemplateDeclarations: false
AllowShortCaseLabelsOnASingleLine: true
SpaceAfterTemplateKeyword: false
AllowShortBlocksOnASingleLine: true
...

347
.clang-tidy Normal file
View File

@ -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
"

8
.editorconfig Normal file
View File

@ -0,0 +1,8 @@
root = true
# Don't set line endings to avoid conflict with core.autocrlf flag.
# Line endings on checkout/checkin are controlled by .gitattributes file.
[*]
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true

13
.eslintrc.js Normal file
View File

@ -0,0 +1,13 @@
/* eslint-env node */
module.exports = {
root: true,
parser: '@typescript-eslint/parser',
plugins: [
'@typescript-eslint',
],
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
]
};

2
.gitattributes vendored Normal file
View File

@ -0,0 +1,2 @@
# Set the default behavior, in case people don't have core.autocrlf set.
* text=auto

12
.github/ISSUE_TEMPLATE.md vendored Normal file
View File

@ -0,0 +1,12 @@
Thank you for submitting an issue!
Please make sure you include the names of the affected language(s), compiler version(s), operating system version(s), and FlatBuffers version(s) in your issue title.
This helps us get the correct maintainers to look at your issue. Here are examples of good titles:
- Crash when accessing FlatBuffer [C++, gcc 4.8, OS X, master]
- Flatc converts a protobuf 'bytes' field to 'string' in fbs schema file [all languages, FlatBuffers 1.4]
Include other details as appropriate.
Thanks!

19
.github/PULL_REQUEST_TEMPLATE.md vendored Normal file
View File

@ -0,0 +1,19 @@
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](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.
If your PR includes C++ code, please adhere to the
[Google C++ Style Guide](https://google.github.io/styleguide/cppguide.html),
and don't forget we try to support older compilers (e.g. VS2010, GCC 4.6.3),
so only some C++11 support is available.
For any C++ changes, please make sure to run `sh scripts/clang-format-git.sh`
Include other details as appropriate.
Thanks!

97
.github/labeler.yml vendored Normal file
View File

@ -0,0 +1,97 @@
# Configuration for Auto Labeler during pull request
#
# See https://github.com/actions/labeler for file format
# and https://github.com/google/flatbuffers/labels for a list of valid labels
#
# See .github/workflows/label.yml for Github Action workflow script
c#:
- '**/*.cs'
- net/**/*
- tests/FlatBuffers.Test/**/*
- tests/FlatBuffers.Benchmarks/**/*
- src/idl_gen_csharp.cpp
swift:
- '**/*.swift'
- swift/**/*
- tests/swift/**
- src/idl_gen_swift.cpp
nim:
- '**/*.nim'
- nim/**/*
- src/idl_gen_nim.cpp
- src/bfbs_gen_nim.cpp
javascript:
- '**/*.js'
- src/idl_gen_ts.cpp
typescript:
- '**/*.ts'
- src/idl_gen_ts.cpp
- grpc/flatbuffers-js-grpc/**/*.ts
golang:
- '**/*.go'
- src/idl_gen_go.cpp
python:
- '**/*.py'
- src/idl_gen_python.cpp
java:
- '**/*.java'
- src/idl_gen_java.cpp
kotlin:
- '**/*.kt'
- src/idl_gen_kotlin.cpp
- src/idl_gen_kotlin_kmp.cpp
lua:
- '**/*.lua'
- lua/**/*
- src/bfbs_gen_lua.cpp
lobster:
- '**/*.lobster'
- src/idl_gen_lobster.cpp
php:
- '**/*.php'
- src/idl_gen_php.cpp
rust:
- '**/*.rs'
- rust/**/*
- src/idl_gen_rust.cpp
dart:
- '**/*.dart'
- src/idl_gen_dart.cpp
c++:
- '**/*.cc'
- '**/*.cpp'
- '**/*.h'
json:
- '**/*.json'
- src/idl_gen_json_schema.cpp
codegen:
- src/**/*
documentation:
- docs/**/*
- '**/*.md'
CI:
- '.github/**/*'
- '.bazelci/**/*'
grpc:
- grpc/**/*
- src/idl_gen_grpc.cpp

587
.github/workflows/build.yml vendored Normal file
View File

@ -0,0 +1,587 @@
name: CI
permissions: read-all
on:
# For manual tests.
workflow_dispatch:
push:
tags:
- "*" # new tag version, like `0.8.4` or else
branches:
- master
pull_request:
branches:
- master
jobs:
build-linux:
permissions:
contents: write
outputs:
digests-gcc: ${{ steps.hash-gcc.outputs.hashes }}
digests-clang: ${{ steps.hash-clang.outputs.hashes }}
name: Build Linux
runs-on: ubuntu-22.04-64core
strategy:
matrix:
cxx: [g++-13, clang++-15]
fail-fast: false
steps:
- uses: actions/checkout@v3
- name: cmake
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
run: ./flattests
- name: make flatc executable
run: |
chmod +x flatc
./flatc --version
- name: upload build artifacts
uses: actions/upload-artifact@v1
with:
name: Linux flatc binary ${{ matrix.cxx }}
path: flatc
# Below if only for release.
- name: Zip file
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
if: startsWith(github.ref, 'refs/tags/')
with:
files: Linux.flatc.binary.${{ matrix.cxx }}.zip
- name: Generate SLSA subjects - clang
if: matrix.cxx == 'clang++-15' && startsWith(github.ref, 'refs/tags/')
id: hash-clang
run: echo "hashes=$(sha256sum Linux.flatc.binary.${{ matrix.cxx }}.zip | base64 -w0)" >> $GITHUB_OUTPUT
- name: Generate SLSA subjects - gcc
if: matrix.cxx == 'g++-13' && startsWith(github.ref, 'refs/tags/')
id: hash-gcc
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-22.04-64core
steps:
- uses: actions/checkout@v3
- name: cmake
run: CXX=clang++-15 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-22.04-64core
steps:
- uses: actions/checkout@v3
- name: make build directory
run: mkdir build
- name: cmake
working-directory: build
run: >
CXX=clang++-15 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-22.04-64core
strategy:
fail-fast: false
matrix:
std: [11, 14, 17, 20, 23]
cxx: [g++-13, clang++-15]
exclude:
# Clang++15 10.3.0 stdlibc++ doesn't fully support std 23
- cxx: clang++-15
std: 23
steps:
- uses: actions/checkout@v3
- name: cmake
run: >
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
run: make -j
- name: test
run: ./flattests
- name: test C++17
if: matrix.std >= 17
run: ./flattests_cpp17
build-cpp-std:
name: Build Windows C++
runs-on: windows-2019
strategy:
matrix:
std: [11, 14, 17, 20, 23]
fail-fast: false
steps:
- uses: actions/checkout@v3
- name: Add msbuild to PATH
uses: microsoft/setup-msbuild@v1.1
- name: cmake
run: >
cmake -G "Visual Studio 16 2019" -A x64 -DCMAKE_BUILD_TYPE=Release
-DFLATBUFFERS_STRICT_MODE=ON
-DFLATBUFFERS_CPP_STD=${{ matrix.std }}
-DFLATBUFFERS_BUILD_CPP17=${{ matrix.std >= 17 && 'On' || 'Off'}}
- name: build
run: msbuild.exe FlatBuffers.sln /p:Configuration=Release /p:Platform=x64
- name: test
run: Release\flattests.exe
- name: test C++17
if: matrix.std >= 17
run: Release\flattests_cpp17.exe
build-windows:
permissions:
contents: write
outputs:
digests: ${{ steps.hash.outputs.hashes }}
name: Build Windows 2019
runs-on: windows-2019
steps:
- uses: actions/checkout@v3
- name: Add msbuild to PATH
uses: microsoft/setup-msbuild@v1.1
- name: cmake
run: cmake -G "Visual Studio 16 2019" -A x64 -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_BUILD_CPP17=ON -DFLATBUFFERS_STRICT_MODE=ON .
- name: build
run: msbuild.exe FlatBuffers.sln /p:Configuration=Release /p:Platform=x64
- name: test
run: Release\flattests.exe
- name: upload build artifacts
uses: actions/upload-artifact@v1
with:
name: Windows flatc binary
path: Release\flatc.exe
# Below if only for release.
- name: Zip file
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
if: startsWith(github.ref, 'refs/tags/')
with:
files: Windows.flatc.binary.zip
- name: Generate SLSA subjects
if: startsWith(github.ref, 'refs/tags/')
id: hash
shell: bash
run: echo "hashes=$(sha256sum Windows.flatc.binary.zip | base64 -w0)" >> $GITHUB_OUTPUT
build-dotnet-windows:
name: Build .NET Windows
runs-on: windows-2022-64core
strategy:
matrix:
configuration: [
'',
'-p:UnsafeByteBuffer=true',
# Fails two tests currently.
#'-p:EnableSpanT=true,UnsafeByteBuffer=true'
]
steps:
- uses: actions/checkout@v3
- name: Setup .NET Core SDK
uses: actions/setup-dotnet@v3
with:
dotnet-version: '8.0.x'
- name: Build
run: |
cd tests\FlatBuffers.Test
dotnet new sln --force --name FlatBuffers.Test
dotnet sln FlatBuffers.Test.sln add FlatBuffers.Test.csproj
dotnet build -c Release ${{matrix.configuration}} -o out FlatBuffers.Test.sln
- name: Run
run: |
cd tests\FlatBuffers.Test
out\FlatBuffers.Test.exe
build-mac-intel:
permissions:
contents: write
outputs:
digests: ${{ steps.hash.outputs.hashes }}
name: Build Mac (for Intel)
runs-on: macos-latest
steps:
- uses: actions/checkout@v3
- name: cmake
run: cmake -G "Xcode" -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_STRICT_MODE=ON .
- name: build
run: xcodebuild -toolchain clang -configuration Release -target flattests
- name: check that the binary is x86_64
run: |
info=$(file Release/flatc)
echo $info
echo $info | grep "Mach-O 64-bit executable x86_64"
- name: test
run: Release/flattests
- name: make flatc executable
run: |
chmod +x Release/flatc
Release/flatc --version
- name: upload build artifacts
uses: actions/upload-artifact@v1
with:
name: Mac flatc binary
path: Release/flatc
# Below if only for release.
- name: Zip file
if: startsWith(github.ref, 'refs/tags/')
run: mv Release/flatc . && zip MacIntel.flatc.binary.zip flatc
- name: Release binary
uses: softprops/action-gh-release@v1
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 "hashes=$(shasum -a 256 MacIntel.flatc.binary.zip | base64)" >> $GITHUB_OUTPUT
build-mac-universal:
permissions:
contents: write
outputs:
digests: ${{ steps.hash.outputs.hashes }}
name: Build Mac (universal build)
runs-on: macos-latest
steps:
- uses: actions/checkout@v3
- name: cmake
run: cmake -G "Xcode" -DCMAKE_OSX_ARCHITECTURES="arm64;x86_64" -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_STRICT_MODE=ON .
- name: build
run: xcodebuild -toolchain clang -configuration Release -target flattests
- name: check that the binary is "universal"
run: |
info=$(file Release/flatc)
echo $info
echo $info | grep "Mach-O universal binary with 2 architectures"
- name: test
run: Release/flattests
- name: make flatc executable
run: |
chmod +x Release/flatc
Release/flatc --version
- name: upload build artifacts
uses: actions/upload-artifact@v1
with:
name: Mac flatc binary
path: Release/flatc
# Below if only for release.
- name: Zip file
if: startsWith(github.ref, 'refs/tags/')
run: mv Release/flatc . && zip Mac.flatc.binary.zip flatc
- name: Release binary
uses: softprops/action-gh-release@v1
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 "hashes=$(shasum -a 256 Mac.flatc.binary.zip | base64)" >> $GITHUB_OUTPUT
build-android:
name: Build Android (on Linux)
runs-on: ubuntu-22.04-64core
steps:
- uses: actions/checkout@v3
- name: set up Java
uses: actions/setup-java@v3
with:
distribution: 'temurin'
java-version: '11'
- name: set up flatc
run: |
cmake -DFLATBUFFERS_BUILD_TESTS=OFF -DFLATBUFFERS_BUILD_FLATLIB=OFF -DFLATBUFFERS_BUILD_FLATHASH=OFF -DFLATBUFFERS_STRICT_MODE=ON .
make -j
echo "${PWD}" >> $GITHUB_PATH
- name: build
working-directory: android
run: gradle clean build
build-generator:
name: Check Generated Code
runs-on: ubuntu-22.04-64core
strategy:
matrix:
cxx: [g++-13, clang++-15]
steps:
- uses: actions/checkout@v3
- 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
run: scripts/check_generate_code.py
- name: Generate gRPC
run: scripts/check-grpc-generated-code.py
build-generator-windows:
name: Check Generated Code on Windows
runs-on: windows-2019
steps:
- uses: actions/checkout@v3
- name: Add msbuild to PATH
uses: microsoft/setup-msbuild@v1.1
- name: cmake
run: cmake -G "Visual Studio 16 2019" -A x64 -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_BUILD_CPP17=ON -DFLATBUFFERS_STRICT_MODE=ON .
- 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-22.04-64core
strategy:
matrix:
cxx: [g++-13]
steps:
- uses: actions/checkout@v3
- 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
with:
name: Linux flatbenchmark results ${{matrix.cxx}}
path: benchmarks/results_${{matrix.cxx}}
build-java:
name: Build Java
runs-on: ubuntu-22.04-64core
steps:
- uses: actions/checkout@v3
- name: test
working-directory: java
run: mvn test
build-kotlin-macos:
name: Build Kotlin MacOS
runs-on: macos-latest
steps:
- name: Checkout
uses: actions/checkout@v3
- uses: gradle/wrapper-validation-action@v1.0.5
- uses: actions/setup-java@v3
with:
distribution: 'temurin'
java-version: '11'
- 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 iosSimulatorArm64Test macosX64Test macosArm64Test
build-kotlin-linux:
name: Build Kotlin Linux
runs-on: ubuntu-22.04-64core
steps:
- name: Checkout
uses: actions/checkout@v3
- uses: actions/setup-java@v3
with:
distribution: 'temurin'
java-version: '11'
- uses: gradle/wrapper-validation-action@v1.0.5
- 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
# so no need for wrapper validation or user
# gradlew
run: gradle jvmMainClasses jvmTest jsTest jsBrowserTest
build-rust-linux:
name: Build Rust Linux
runs-on: ubuntu-22.04-64core
steps:
- uses: actions/checkout@v3
- 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@v3
- name: test
working-directory: tests
run: ./RustTest.bat
build-python:
name: Build Python
runs-on: ubuntu-22.04-64core
steps:
- uses: actions/checkout@v3
- 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-22.04-64core
steps:
- uses: actions/checkout@v3
- 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 GoTest.sh
build-php:
name: Build PHP
runs-on: ubuntu-22.04-64core
steps:
- uses: actions/checkout@v3
- 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-22.04-64core
steps:
- uses: actions/checkout@v3
- name: test
working-directory: tests/swift/tests
run: |
swift build --build-tests
swift test
build-swift-wasm:
name: Build Swift Wasm
runs-on: ubuntu-22.04-64core
container:
image: ghcr.io/swiftwasm/carton:0.15.3
steps:
- uses: actions/checkout@v3
- name: Setup Wasmer
uses: wasmerio/setup-wasmer@v2
- name: Test
working-directory: tests/swift/Wasm.tests
run: carton test
build-ts:
name: Build TS
runs-on: ubuntu-22.04-64core
steps:
- uses: actions/checkout@v3
- 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: deps
run: yarn
- name: compile
run: yarn compile
- name: test
working-directory: tests/ts
run: |
yarn global add esbuild
python3 TypeScriptTest.py
build-dart:
name: Build Dart
runs-on: ubuntu-22.04-64core
steps:
- uses: actions/checkout@v3
- uses: dart-lang/setup-dart@v1
with:
sdk: stable
- 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 DartTest.sh
build-nim:
name: Build Nim
runs-on: ubuntu-22.04-64core
steps:
- uses: actions/checkout@v3
- 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
- name: install library
working-directory: nim
run: nimble -y develop && nimble install
- name: test
working-directory: tests/nim
run: python3 testnim.py
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-22.04-64core
steps:
- name: Merge results
id: hash
env:
LINUXGCC_DIGESTS: "${{ needs.build-linux.outputs.digests-gcc }}"
LINUXCLANG_DIGESTS: "${{ needs.build-linux.outputs.digests-clang }}"
MAC_DIGESTS: "${{ needs.build-mac-universal.outputs.digests }}"
MACINTEL_DIGESTS: "${{ needs.build-mac-intel.outputs.digests }}"
WINDOWS_DIGESTS: "${{ needs.build-windows.outputs.digests }}"
run: |
set -euo pipefail
echo "$LINUXGCC_DIGESTS" | base64 -d > checksums.txt
echo "$LINUXCLANG_DIGESTS" | base64 -d >> checksums.txt
echo "$MAC_DIGESTS" | base64 -d >> checksums.txt
echo "$MACINTEL_DIGESTS" | base64 -d >> checksums.txt
echo "$WINDOWS_DIGESTS" | base64 -d >> checksums.txt
echo "digests=$(cat checksums.txt | base64 -w0)" >> $GITHUB_OUTPUT
provenance:
if: startsWith(github.ref, 'refs/tags/')
needs: [release-digests]
permissions:
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.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

71
.github/workflows/codeql.yml vendored Normal file
View File

@ -0,0 +1,71 @@
# 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

35
.github/workflows/extrabuild.yml vendored Normal file
View File

@ -0,0 +1,35 @@
name: Build and unit tests that are more time consuming
permissions: read-all
on:
# For manual tests.
workflow_dispatch:
pull_request:
types:
- closed
schedule:
- cron: "30 20 * * *"
jobs:
build-linux-s390x:
name: Build Linux on s390x arch and run unit tests
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: uraimo/run-on-arch-action@v2
name: Run commands
id: runcmd
with:
arch: s390x
distro: ubuntu_latest
install: |
apt-get update -q -y
apt-get -y install cmake
apt-get -y install make
apt-get -y install g++
run: |
lscpu | grep Endian
cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release
make -j
./flattests

24
.github/workflows/label.yml vendored Normal file
View File

@ -0,0 +1,24 @@
# This workflow will triage pull requests and apply a label based on the
# paths that are modified in the pull request.
#
# To use this workflow, you will need to set up a .github/labeler.yml
# file with configuration. For more information, see:
# https://github.com/actions/labeler
name: Labeler
permissions: read-all
on: [pull_request_target]
jobs:
label:
permissions:
contents: read
pull-requests: write
runs-on: ubuntu-latest
steps:
- uses: actions/labeler@ee18d5d34efd9b4f7dafdb0e363cb688eb438044 # 4.1.0
with:
repo-token: "${{ secrets.GITHUB_TOKEN }}"

34
.github/workflows/main.yml vendored Normal file
View File

@ -0,0 +1,34 @@
name: OSS-Fuzz
permissions: read-all
on:
pull_request:
branches:
- master
paths:
- include/**
- src/**
- tests/**.cpp
- tests/**.h
jobs:
Fuzzing:
runs-on: ubuntu-latest
steps:
- name: Build Fuzzers
id: build
uses: google/oss-fuzz/infra/cifuzz/actions/build_fuzzers@master
with:
oss-fuzz-project-name: 'flatbuffers'
language: c++
- name: Run Fuzzers
uses: google/oss-fuzz/infra/cifuzz/actions/run_fuzzers@master
with:
oss-fuzz-project-name: 'flatbuffers'
language: c++
fuzz-seconds: 60
- name: Upload Crash
uses: actions/upload-artifact@v1
if: failure() && steps.build.outcome == 'success'
with:
name: artifacts
path: ./out/artifacts

105
.github/workflows/release.yml vendored Normal file
View File

@ -0,0 +1,105 @@
name: Release
permissions: read-all
on:
# For manual tests.
workflow_dispatch:
release:
types: [created]
jobs:
publish-npm:
name: Publish NPM
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
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
defaults:
run:
working-directory: ./python
steps:
- uses: actions/checkout@v3
- 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
- name: Build
run: |
python3 setup.py sdist bdist_wheel
- name: Upload to PyPi
run: |
python3 -m twine upload dist/*
env:
TWINE_USERNAME: __token__
TWINE_PASSWORD: ${{ secrets.TWINE_TOKEN }}
publish-nuget:
name: Publish NuGet
runs-on: windows-latest
defaults:
run:
working-directory: ./net/flatbuffers
steps:
- uses: actions/checkout@v3
- uses: actions/setup-dotnet@v3
with:
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
publish-maven:
name: Publish Maven
runs-on: ubuntu-latest
defaults:
run:
working-directory: ./java
steps:
- uses: actions/checkout@v3
- name: Set up Maven Central Repository
uses: actions/setup-java@v3
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 Maven
run: mvn --batch-mode clean deploy
env:
OSSRH_USERNAME: ${{ secrets.OSSRH_USERNAME }}
OSSRH_PASSWORD: ${{ secrets.OSSRH_TOKEN }}
MAVEN_GPG_PASSPHRASE: ${{ secrets.MAVEN_GPG_PASSPHRASE }}

55
.github/workflows/scorecards.yml vendored Normal file
View File

@ -0,0 +1,55 @@
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

37
.github/workflows/stale.yml vendored Normal file
View File

@ -0,0 +1,37 @@
name: Mark stale issues and pull requests
permissions:
issues: write
pull-requests: write
on:
# For manual tests.
workflow_dispatch:
schedule:
- cron: "30 20 * * *"
jobs:
stale:
runs-on: ubuntu-latest
steps:
- uses: actions/stale@v7.0.0
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
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-draft-pr: false

155
.gitignore vendored Normal file
View File

@ -0,0 +1,155 @@
*_wire.txt
*_wire.bin
.DS_Store
**/.build
build
**/Packages
/*.xcodeproj
**/xcuserdata/
**/xcshareddata/
**/.swiftpm/
*.o
*.o.d
*.class
*.a
*.swp
*~
*.vcxproj
*.vcxproj.filters
*.vcxproj.user
*.sln
*.suo
*.opendb
*.keystore
**/.vs/**
**/bin/**
!tests/rust_usage_test/bin/**
**/gen/**
**/libs/**
**/obj/**
**/*.dir/**
**/CMakeFiles/**
**/cmake_install.cmake
**/install_manifest.txt
**/CMakeCache.txt
**/CMakeTestfile.cmake
**/CPackConfig.cmake
**/CPackSourceConfig.cmake
**/compile_commands.json
**/Debug/**
**/Release/**
**/RelWithDebInfo/**
**/x64/ #build artifacts from VS
build.xml
local.properties
project.properties
proguard-project.txt
linklint_results
Makefile
flatbenchmark
flatbenchmark.exe
flatc
flatc.exe
flathash
flathash.exe
flattests
flattests.exe
flattests_cpp17
flattests_cpp17.exe
flatsamplebinary
flatsamplebinary.exe
flatsampletext
flatsampletext.exe
flatsamplebfbs
flatsamplebfbs.exe
grpctest
grpctest.exe
snapshot.sh
tags
tests/dart_gen
tests/go_gen
tests/monsterdata_java_wire.mon
tests/monsterdata_java_wire_sp.mon
tests/monsterdata_go_wire.mon
tests/monsterdata_javascript_wire.mon
tests/monsterdata_lobster_wire.mon
tests/monsterdata_rust_wire.mon
tests/php/
CMakeLists.txt.user
CMakeScripts/**
CTestTestfile.cmake
flatbuffers-config-version.cmake
FlatBuffers.cbp
build/Xcode/FlatBuffers.xcodeproj/project.xcworkspace/**
build/Xcode/FlatBuffers.xcodeproj/xcuserdata/**
FlatBuffers.xcodeproj/
java/.idea
java/*.iml
.idea
*.iml
target
java/target
**/*.pyc
build/VS2010/FlatBuffers.sdf
build/VS2010/FlatBuffers.opensdf
build/VS2010/ipch/**/*.ipch
*.so
Testing/Temporary
.cproject
.settings/
.project
net/**/obj
node_modules/
android/.externalNativeBuild/
android/.gradle/
android/build/
samples/android/.externalNativeBuild/
samples/android/.gradle/
samples/android/build/
js/**/*.js
js/**/*.d.ts
mjs/**/*.js
mjs/**/*.d.ts
/bazel-bin
/bazel-flatbuffers
/bazel-genfiles
/bazel-out
/bazel-testlogs
.ninja_deps
.ninja_log
build.ninja
rules.ninja
.vscode
dart/.pub/
dart/.packages
dart/pubspec.lock
dart/.dart_tool/
dart/build/
dart/doc/api/
Cargo.lock
.corpus**
.seed**
.crash**
grpc/google/
**/Package.resolved
.clangd/**
package-lock.json
/*.ilk
/*.pdb
.clwb
yarn-error.log
.cache/
/flatbuffers.lib
.cmake/
**/dist
**/vendor
**/go.sum
flatbuffers.pc
**/FlatBuffers.Test.Swift.xcodeproj
**/html/**
**/latex/**
# https://cmake.org/cmake/help/latest/module/FetchContent.html#variable:FETCHCONTENT_BASE_DIR
cmake-build-debug/
_deps/
**/.gradle/**
kotlin/**/generated

1
.npmrc Normal file
View File

@ -0,0 +1 @@
hoist=false

139
BUILD.bazel Normal file
View File

@ -0,0 +1,139 @@
load("@aspect_rules_js//npm:defs.bzl", "npm_link_package")
load("@npm//:defs.bzl", "npm_link_all_packages")
load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library")
licenses(["notice"])
package(
default_visibility = ["//visibility:public"],
)
npm_link_all_packages(name = "node_modules")
npm_link_package(
name = "node_modules/flatbuffers",
src = "//ts:flatbuffers",
)
exports_files([
"LICENSE",
"tsconfig.json",
])
config_setting(
name = "platform_freebsd",
constraint_values = [
"@platforms//os:freebsd",
],
)
config_setting(
name = "platform_openbsd",
constraint_values = [
"@platforms//os:openbsd",
],
)
filegroup(
name = "distribution",
srcs = [
"BUILD.bazel",
"WORKSPACE",
"build_defs.bzl",
"typescript.bzl",
"//grpc/src/compiler: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",
hdrs = ["//:public_headers"],
linkstatic = 1,
strip_include_prefix = "/include",
deps = ["//src:flatbuffers"],
)
# Public C++ headers for the Flatbuffers library.
filegroup(
name = "public_headers",
srcs = [
"include/flatbuffers/allocator.h",
"include/flatbuffers/array.h",
"include/flatbuffers/base.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",
"include/flatbuffers/flexbuffers.h",
"include/flatbuffers/grpc.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",
],
)
# Public flatc compiler library.
cc_library(
name = "flatc_library",
linkstatic = 1,
deps = [
"//src:flatc_library",
],
)
# Public flatc compiler.
cc_binary(
name = "flatc",
data = ["//reflection:reflection_fbs_schema"],
deps = [
"//src:flatc",
],
)
filegroup(
name = "flatc_headers",
srcs = [
"include/flatbuffers/flatc.h",
],
visibility = ["//:__subpackages__"],
)
# 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",
],
linkstatic = 1,
strip_include_prefix = "/include",
)

168
CHANGELOG.md Normal file
View File

@ -0,0 +1,168 @@
# Flatbuffers Change Log
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.
## [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)](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)](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)
that is based on date.
* Python supports fixed size arrays now (#7529).
* Behavior change in how C++ object API uses `UnPackTo`. The original intent of
this was to reduce allocations by reusing an existing object to pack data
into. At some point, this logic started to merge the states of the two objects
instead of clearing the state of the packee. This change goes back to the
original intention, the packed object is cleared when getting data packed into
it (#7527).
* Fixed a bug in C++ alignment that was using `sizeof()` instead of the intended
`AlignOf()` for structs (#7520).
* C# has an
[official Nuget package](https://www.nuget.org/packages/Google.FlatBuffers)
now (#7496).
## 2.0.8 (Aug 29 2022)
* Fix for `--keep-prefix` the was generating the wrong include statements for
C++ (#7469). The bug was introduced in 2.0.7.
* Added the `Verifier::Options` option struct to allow specifying runtime
configuration settings for the verifier (#7489). This allows to skip verifying
nested flatbuffers, a on-by-default change that was introduced in 2.0.7. This
deprecates the existing `Verifier` constructor, which may be removed in a
future version.
* Refactor of `tests/test.cpp` that lead to ~10% speedup in compilation of the
entire project (#7487).
## 2.0.7 (Aug 22 2022)
* This is the first version with an explicit change log, so all the previous
features will not be listed.
* Verifier now checks that buffers are at least the minimum size required to be
a flatbuffers (12 bytes). This includes nested flatbuffers, which previously
could be declared valid at size 0.
* Annotated binaries. Given a flatbuffer binary and a schema (or binary schema)
one can generate an annotated flatbuffer (.afb) to describe each byte in the
binary with schema metadata and value.
* 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.

View File

@ -0,0 +1,449 @@
# Copyright 2015 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# General function to create FlatBuffer build rules for the given list of
# schemas.
#
# flatbuffers_schemas: A list of flatbuffer schema files to process.
#
# schema_include_dirs: A list of schema file include directories, which will be
# passed to flatc via the -I parameter.
#
# custom_target_name: The generated files will be added as dependencies for a
# new custom target with this name. You should add that target as a dependency
# for your main target to ensure these files are built. You can also retrieve
# various properties from this target, such as GENERATED_INCLUDES_DIR,
# BINARY_SCHEMAS_DIR, and COPY_TEXT_SCHEMAS_DIR.
#
# additional_dependencies: A list of additional dependencies that you'd like
# all generated files to depend on. Pass in a blank string if you have none.
#
# generated_includes_dir: Where to generate the C++ header files for these
# schemas. The generated includes directory will automatically be added to
# CMake's include directories, and will be where generated header files are
# placed. This parameter is optional; pass in empty string if you don't want to
# generate include files for these schemas.
#
# binary_schemas_dir: If you specify an optional binary schema directory, binary
# schemas will be generated for these schemas as well, and placed into the given
# directory.
#
# copy_text_schemas_dir: If you want all text schemas (including schemas from
# all schema include directories) copied into a directory (for example, if you
# need them within your project to build JSON files), you can specify that
# folder here. All text schemas will be copied to that folder.
#
# IMPORTANT: Make sure you quote all list arguments you pass to this function!
# Otherwise CMake will only pass in the first element.
# Example: build_flatbuffers("${fb_files}" "${include_dirs}" target_name ...)
function(build_flatbuffers flatbuffers_schemas
schema_include_dirs
custom_target_name
additional_dependencies
generated_includes_dir
binary_schemas_dir
copy_text_schemas_dir)
# Test if including from FindFlatBuffers
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)
endif()
set(FLATC_SCHEMA_ARGS --gen-mutable)
if(FLATBUFFERS_FLATC_SCHEMA_EXTRA_ARGS)
set(FLATC_SCHEMA_ARGS
${FLATBUFFERS_FLATC_SCHEMA_EXTRA_ARGS}
${FLATC_SCHEMA_ARGS}
)
endif()
set(working_dir "${CMAKE_CURRENT_SOURCE_DIR}")
set(schema_glob "*.fbs")
# Generate the include files parameters.
set(include_params "")
set(all_generated_files "")
foreach (include_dir ${schema_include_dirs})
set(include_params -I ${include_dir} ${include_params})
if (NOT ${copy_text_schemas_dir} STREQUAL "")
# Copy text schemas from dependent folders.
file(GLOB_RECURSE dependent_schemas ${include_dir}/${schema_glob})
foreach (dependent_schema ${dependent_schemas})
file(COPY ${dependent_schema} DESTINATION ${copy_text_schemas_dir})
endforeach()
endif()
endforeach()
foreach(schema ${flatbuffers_schemas})
get_filename_component(filename ${schema} NAME_WE)
# For each schema, do the things we requested.
if (NOT ${generated_includes_dir} STREQUAL "")
set(generated_include ${generated_includes_dir}/${filename}_generated.h)
add_custom_command(
OUTPUT ${generated_include}
COMMAND ${FLATC} ${FLATC_SCHEMA_ARGS}
-o ${generated_includes_dir}
${include_params}
-c ${schema}
DEPENDS ${FLATC_TARGET} ${schema} ${additional_dependencies}
WORKING_DIRECTORY "${working_dir}")
list(APPEND all_generated_files ${generated_include})
endif()
if (NOT ${binary_schemas_dir} STREQUAL "")
set(binary_schema ${binary_schemas_dir}/${filename}.bfbs)
add_custom_command(
OUTPUT ${binary_schema}
COMMAND ${FLATC} -b --schema
-o ${binary_schemas_dir}
${include_params}
${schema}
DEPENDS ${FLATC_TARGET} ${schema} ${additional_dependencies}
WORKING_DIRECTORY "${working_dir}")
list(APPEND all_generated_files ${binary_schema})
endif()
if (NOT ${copy_text_schemas_dir} STREQUAL "")
file(COPY ${schema} DESTINATION ${copy_text_schemas_dir})
endif()
endforeach()
# Create a custom target that depends on all the generated files.
# This is the target that you can depend on to trigger all these
# to be built.
add_custom_target(${custom_target_name}
DEPENDS ${all_generated_files} ${additional_dependencies})
# Register the include directory we are using.
if (NOT ${generated_includes_dir} STREQUAL "")
include_directories(${generated_includes_dir})
set_property(TARGET ${custom_target_name}
PROPERTY GENERATED_INCLUDES_DIR
${generated_includes_dir})
endif()
# Register the binary schemas dir we are using.
if (NOT ${binary_schemas_dir} STREQUAL "")
set_property(TARGET ${custom_target_name}
PROPERTY BINARY_SCHEMAS_DIR
${binary_schemas_dir})
endif()
# Register the text schema copy dir we are using.
if (NOT ${copy_text_schemas_dir} STREQUAL "")
set_property(TARGET ${custom_target_name}
PROPERTY COPY_TEXT_SCHEMAS_DIR
${copy_text_schemas_dir})
endif()
endfunction()
# Creates a target that can be linked against that generates flatbuffer headers.
#
# This function takes a target name and a list of schemas. You can also specify
# 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_<TARGET>.
#
# Arguments:
# TARGET: The name of the target to generate.
# SCHEMAS: The list of schema files to generate code for.
# BINARY_SCHEMAS_DIR: Optional. The directory in which to generate binary
# schemas. Binary schemas will only be generated if a path is provided.
# INCLUDE: Optional. Search for includes in the specified paths. (Use this
# instead of "-I <path>" and the FLAGS option so that CMake is aware of
# the directories that need to be searched).
# INCLUDE_PREFIX: Optional. The directory in which to place the generated
# files. Use this instead of the --include-prefix option.
# FLAGS: Optional. A list of any additional flags that you would like to pass
# to flatc.
#
# Example:
#
# flatbuffers_generate_headers(
# TARGET my_generated_headers_target
# INCLUDE_PREFIX ${MY_INCLUDE_PREFIX}"
# SCHEMAS ${MY_SCHEMA_FILES}
# BINARY_SCHEMAS_DIR "${MY_BINARY_SCHEMA_DIRECTORY}"
# FLAGS --gen-object-api)
#
# 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)
set(one_value_args
"TARGET"
"INCLUDE_PREFIX"
"BINARY_SCHEMAS_DIR")
set(multi_value_args
"SCHEMAS"
"INCLUDE"
"FLAGS")
cmake_parse_arguments(
PARSE_ARGV 0
FLATBUFFERS_GENERATE_HEADERS
"${options}"
"${one_value_args}"
"${multi_value_args}")
# Test if including from FindFlatBuffers
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)
endif()
set(working_dir "${CMAKE_CURRENT_SOURCE_DIR}")
# Generate the include files parameters.
set(include_params "")
foreach (include_dir ${FLATBUFFERS_GENERATE_HEADERS_INCLUDE})
set(include_params -I ${include_dir} ${include_params})
endforeach()
# Create a directory to place the generated code.
set(generated_target_dir "${CMAKE_CURRENT_BINARY_DIR}/${FLATBUFFERS_GENERATE_HEADERS_TARGET}")
set(generated_include_dir "${generated_target_dir}")
if (NOT ${FLATBUFFERS_GENERATE_HEADERS_INCLUDE_PREFIX} STREQUAL "")
set(generated_include_dir "${generated_include_dir}/${FLATBUFFERS_GENERATE_HEADERS_INCLUDE_PREFIX}")
list(APPEND FLATBUFFERS_GENERATE_HEADERS_FLAGS
"--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)
set(generated_include "${generated_include_dir}/${filename}_generated.h")
# Generate files for grpc if needed
set(generated_source_file)
if("${FLATBUFFERS_GENERATE_HEADERS_FLAGS}" MATCHES "--grpc")
# Check if schema file contain a rpc_service definition
file(STRINGS ${schema} has_grpc REGEX "rpc_service")
if(has_grpc)
list(APPEND generated_include "${generated_include_dir}/${filename}.grpc.fb.h")
set(generated_source_file "${generated_include_dir}/${filename}.grpc.fb.cc")
endif()
endif()
add_custom_command(
OUTPUT ${generated_include} ${generated_source_file}
COMMAND ${FLATC} ${FLATC_ARGS}
-o ${generated_include_dir}
${include_params}
-c ${schema}
${FLATBUFFERS_GENERATE_HEADERS_FLAGS}
DEPENDS ${FLATC_TARGET} ${schema}
WORKING_DIRECTORY "${working_dir}"
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 "")
set(binary_schema
"${FLATBUFFERS_GENERATE_HEADERS_BINARY_SCHEMAS_DIR}/${filename}.bfbs")
add_custom_command(
OUTPUT ${binary_schema}
COMMAND ${FLATC} -b --schema
-o ${FLATBUFFERS_GENERATE_HEADERS_BINARY_SCHEMAS_DIR}
${include_params}
${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(
${FLATBUFFERS_GENERATE_HEADERS_TARGET}
INTERFACE
${all_generated_header_files}
${all_generated_binary_files}
${all_generated_source_files}
${FLATBUFFERS_GENERATE_HEADERS_SCHEMAS})
add_dependencies(
${FLATBUFFERS_GENERATE_HEADERS_TARGET}
${FLATC}
${FLATBUFFERS_GENERATE_HEADERS_SCHEMAS})
target_include_directories(
${FLATBUFFERS_GENERATE_HEADERS_TARGET}
INTERFACE ${generated_target_dir})
# Organize file layout for IDEs.
source_group(
TREE "${generated_target_dir}"
PREFIX "Flatbuffers/Generated/Headers Files"
FILES ${all_generated_header_files})
source_group(
TREE "${generated_target_dir}"
PREFIX "Flatbuffers/Generated/Source Files"
FILES ${all_generated_source_files})
source_group(
TREE ${working_dir}
PREFIX "Flatbuffers/Schemas"
FILES ${FLATBUFFERS_GENERATE_HEADERS_SCHEMAS})
if (NOT ${FLATBUFFERS_GENERATE_HEADERS_BINARY_SCHEMAS_DIR} STREQUAL "")
source_group(
TREE "${FLATBUFFERS_GENERATE_HEADERS_BINARY_SCHEMAS_DIR}"
PREFIX "Flatbuffers/Generated/Binary Schemas"
FILES ${all_generated_binary_files})
endif()
endfunction()
# Creates a target that can be linked against that generates flatbuffer binaries
# from json files.
#
# This function takes a target name and a list of schemas and Json files. You
# can also specify other flagc flags and options to change the behavior of the
# flatc compiler.
#
# Adding this target to your executable ensurses that the flatbuffer binaries
# are compiled before your executable is run.
#
# Arguments:
# TARGET: The name of the target to generate.
# JSON_FILES: The list of json files to compile to flatbuffers binaries.
# SCHEMA: The flatbuffers schema of the Json files to be compiled.
# INCLUDE: Optional. Search for includes in the specified paths. (Use this
# instead of "-I <path>" and the FLAGS option so that CMake is aware of
# the directories that need to be searched).
# OUTPUT_DIR: The directly where the generated flatbuffers binaries should be
# placed.
# FLAGS: Optional. A list of any additional flags that you would like to pass
# to flatc.
#
# Example:
#
# flatbuffers_generate_binary_files(
# TARGET my_binary_data
# SCHEMA "${MY_SCHEMA_DIR}/my_example_schema.fbs"
# JSON_FILES ${MY_JSON_FILES}
# OUTPUT_DIR "${MY_BINARY_DATA_DIRECTORY}"
# FLAGS --strict-json)
#
# target_link_libraries(MyExecutableTarget
# PRIVATE my_binary_data
# )
function(flatbuffers_generate_binary_files)
# Parse function arguments.
set(options)
set(one_value_args
"TARGET"
"SCHEMA"
"OUTPUT_DIR")
set(multi_value_args
"JSON_FILES"
"INCLUDE"
"FLAGS")
cmake_parse_arguments(
PARSE_ARGV 0
FLATBUFFERS_GENERATE_BINARY_FILES
"${options}"
"${one_value_args}"
"${multi_value_args}")
# Test if including from FindFlatBuffers
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)
endif()
set(working_dir "${CMAKE_CURRENT_SOURCE_DIR}")
# Generate the include files parameters.
set(include_params "")
foreach (include_dir ${FLATBUFFERS_GENERATE_BINARY_FILES_INCLUDE})
set(include_params -I ${include_dir} ${include_params})
endforeach()
# Create rules to generate the flatbuffers binary for each json file.
foreach(json_file ${FLATBUFFERS_GENERATE_BINARY_FILES_JSON_FILES})
get_filename_component(filename ${json_file} NAME_WE)
set(generated_binary_file "${FLATBUFFERS_GENERATE_BINARY_FILES_OUTPUT_DIR}/${filename}.bin")
add_custom_command(
OUTPUT ${generated_binary_file}
COMMAND ${FLATC} ${FLATC_ARGS}
-o ${FLATBUFFERS_GENERATE_BINARY_FILES_OUTPUT_DIR}
${include_params}
-b ${FLATBUFFERS_GENERATE_BINARY_FILES_SCHEMA} ${json_file}
${FLATBUFFERS_GENERATE_BINARY_FILES_FLAGS}
DEPENDS ${FLATC_TARGET} ${json_file}
WORKING_DIRECTORY "${working_dir}"
COMMENT "Building ${json_file} binary flatbuffers...")
list(APPEND all_generated_binary_files ${generated_binary_file})
endforeach()
# Set up interface library
add_library(${FLATBUFFERS_GENERATE_BINARY_FILES_TARGET} INTERFACE)
target_sources(
${FLATBUFFERS_GENERATE_BINARY_FILES_TARGET}
INTERFACE
${all_generated_binary_files}
${FLATBUFFERS_GENERATE_BINARY_FILES_JSON_FILES}
${FLATBUFFERS_GENERATE_BINARY_FILES_SCHEMA})
add_dependencies(
${FLATBUFFERS_GENERATE_BINARY_FILES_TARGET}
${FLATC})
# Organize file layout for IDEs.
source_group(
TREE ${working_dir}
PREFIX "Flatbuffers/JSON Files"
FILES ${FLATBUFFERS_GENERATE_BINARY_FILES_JSON_FILES})
source_group(
TREE ${working_dir}
PREFIX "Flatbuffers/Schemas"
FILES ${FLATBUFFERS_GENERATE_BINARY_FILES_SCHEMA})
source_group(
TREE ${FLATBUFFERS_GENERATE_BINARY_FILES_OUTPUT_DIR}
PREFIX "Flatbuffers/Generated/Binary Files"
FILES ${all_generated_binary_files})
endfunction()

4
CMake/DESCRIPTION.txt Normal file
View File

@ -0,0 +1,4 @@
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.

View File

@ -0,0 +1,61 @@
# Copyright 2014 Stefan.Eilemann@epfl.ch
# Copyright 2014 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.
# Find the flatbuffers schema compiler
#
# Output Variables:
# * FLATBUFFERS_FLATC_EXECUTABLE the flatc compiler executable
# * FLATBUFFERS_FOUND
#
# Provides:
# * FLATBUFFERS_GENERATE_C_HEADERS(Name <files>) creates the C++ headers
# for the given flatbuffer schema files.
# Returns the header files in ${Name}_OUTPUTS
set(FLATBUFFERS_CMAKE_DIR ${CMAKE_CURRENT_LIST_DIR})
find_program(FLATBUFFERS_FLATC_EXECUTABLE NAMES flatc)
find_path(FLATBUFFERS_INCLUDE_DIR NAMES flatbuffers/flatbuffers.h)
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(FlatBuffers
DEFAULT_MSG FLATBUFFERS_FLATC_EXECUTABLE FLATBUFFERS_INCLUDE_DIR)
if(FLATBUFFERS_FOUND)
function(FLATBUFFERS_GENERATE_C_HEADERS Name)
set(FLATC_OUTPUTS)
foreach(FILE ${ARGN})
get_filename_component(FLATC_OUTPUT ${FILE} NAME_WE)
set(FLATC_OUTPUT
"${CMAKE_CURRENT_BINARY_DIR}/${FLATC_OUTPUT}_generated.h")
list(APPEND FLATC_OUTPUTS ${FLATC_OUTPUT})
add_custom_command(OUTPUT ${FLATC_OUTPUT}
COMMAND ${FLATBUFFERS_FLATC_EXECUTABLE}
ARGS -c -o "${CMAKE_CURRENT_BINARY_DIR}/" ${FILE}
DEPENDS ${FILE}
COMMENT "Building C++ header for ${FILE}"
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})
endforeach()
set(${Name}_OUTPUTS ${FLATC_OUTPUTS} PARENT_SCOPE)
endfunction()
set(FLATBUFFERS_INCLUDE_DIRS ${FLATBUFFERS_INCLUDE_DIR})
include_directories(${CMAKE_BINARY_DIR})
else()
set(FLATBUFFERS_INCLUDE_DIR)
endif()
include("${FLATBUFFERS_CMAKE_DIR}/BuildFlatBuffers.cmake")

25
CMake/PackageDebian.cmake Normal file
View File

@ -0,0 +1,25 @@
# ------------------- Debianization ---------------------
if (UNIX)
# Set build environment
SET(CPACK_GENERATOR "TGZ;DEB")
SET(CPACK_SOURCE_TGZ "ON")
# Common package information
SET(CPACK_PACKAGE_DESCRIPTION_SUMMARY
"FlatBuffers is an efficient cross platform serialization library for C++, with support for Java, C# and Go. It was created at Google specifically for game development and other performance-critical applications.")
SET(CPACK_DEBIAN_PACKAGE_HOMEPAGE "https://github.com/google/flatbuffers")
SET(CPACK_DEBIAN_PACKAGE_MAINTAINER "Vitaly Isaev <vitalyisaev2@gmail.com>")
SET(CPACK_PACKAGE_VERSION_MAJOR ${VERSION_MAJOR})
SET(CPACK_PACKAGE_VERSION_MINOR ${VERSION_MINOR})
SET(CPACK_PACKAGE_VERSION_PATCH ${VERSION_PATCH})
SET(CPACK_PACKAGE_VERSION "${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}-${VERSION_COMMIT}")
SET(CPACK_DEBIAN_PACKAGE_VERSION "${CPACK_PACKAGE_VERSION}")
# Package name
SET(CPACK_DEBIAN_PACKAGE_NAME "flatbuffers")
SET(CPACK_RESOURCE_FILE_LICENSE ${CMAKE_SOURCE_DIR}/LICENSE)
set(CPACK_DEBIAN_FILE_NAME "DEB-DEFAULT")
endif(UNIX)

44
CMake/PackageRedhat.cmake Normal file
View File

@ -0,0 +1,44 @@
if (UNIX)
set(CPACK_GENERATOR "RPM")
set(CPACK_SOURCE_TGZ "ON")
set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "FlatBuffers serialization library and schema compiler.")
set(CPACK_RPM_PACKAGE_HOMEPAGE "https://github.com/google/flatbuffers")
set(CPACK_RPM_PACKAGE_MAINTAINER "Marc Butler <mockbutler@gmail.com>")
set(CPACK_PACKAGE_VERSION_MAJOR ${VERSION_MAJOR})
set(CPACK_PACKAGE_VERSION_MINOR ${VERSION_MINOR})
set(CPACK_PACKAGE_VERSION_PATCH ${VERSION_PATCH})
set(CPACK_PACKAGE_VERSION "${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}-${VERSION_COMMIT}")
set(CPACK_RPM_PACKAGE_VERSION "${CPACK_PACKAGE_VERSION}")
set(CPACK_RPM_PACKAGE_NAME "flatbuffers")
# 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)
set(CPACK_PACKAGE_DESCRIPTION_FILE ${CMAKE_SOURCE_DIR}/CMake/DESCRIPTION.txt)
# This may reduce rpm compatiblity with very old systems.
set(CPACK_RPM_COMPRESSION_TYPE lzma)
set(CPACK_RPM_PACKAGE_NAME "flatbuffers")
set(CPACK_PACKAGE_FILE_NAME
"${CPACK_RPM_PACKAGE_NAME}_${CPACK_RPM_PACKAGE_VERSION}_${CPACK_RPM_PACKAGE_ARCHITECTURE}")
if(NOT DEFINED ${CPACK_PACKAGING_INSTALL_PREFIX})
# Default packaging install prefix on RedHat systems is /usr.
# This is the assumed value when this variable is not defined.
# There is currently a conflict with
# /usr/${CMAKE_INSTALL_LIBDIR}/cmake which is installed by default
# by other packages on RedHat (most notably cmake-filesystem). Ensure
# that on these systems, flatbuffers does not package this path.
# This patch is required for cmake pre-3.17.
list(APPEND CPACK_RPM_EXCLUDE_FROM_AUTO_FILELIST_ADDITION "/usr/${CMAKE_INSTALL_LIBDIR}/cmake")
endif()
endif(UNIX)

39
CMake/Version.cmake Normal file
View File

@ -0,0 +1,39 @@
set(VERSION_MAJOR 24)
set(VERSION_MINOR 3)
set(VERSION_PATCH 25)
set(VERSION_COMMIT 0)
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<major>.<minor>.<patch>*"
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<major>.<minor>.<patch>-<commit>")
endif()
else()
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 is not found")
endif()
endif()
message(STATUS "Proceeding with version: ${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}.${VERSION_COMMIT}")

View File

@ -0,0 +1,11 @@
set(PACKAGE_VERSION "@VERSION_MAJOR@.@VERSION_MINOR@.@VERSION_PATCH@")
# Check whether the requested PACKAGE_FIND_VERSION is compatible
if("${PACKAGE_VERSION}" VERSION_LESS "${PACKAGE_FIND_VERSION}")
set(PACKAGE_VERSION_COMPATIBLE FALSE)
else()
set(PACKAGE_VERSION_COMPATIBLE TRUE)
if ("${PACKAGE_VERSION}" VERSION_EQUAL "${PACKAGE_FIND_VERSION}")
set(PACKAGE_VERSION_EXACT TRUE)
endif()
endif()

View File

@ -0,0 +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)

9
CMake/flatbuffers.pc.in Normal file
View File

@ -0,0 +1,9 @@
libdir=@CMAKE_INSTALL_FULL_LIBDIR@
includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@
Name: FlatBuffers
Description: Memory Efficient Serialization Library
Version: @VERSION_MAJOR@.@VERSION_MINOR@.@VERSION_PATCH@
Libs: -L${libdir} -lflatbuffers
Cflags: -I${includedir}

718
CMakeLists.txt Normal file
View File

@ -0,0 +1,718 @@
# This is the legacy minimum version flatbuffers supported for a while.
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)
project(FlatBuffers
VERSION ${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}
LANGUAGES CXX)
# 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" OFF)
option(FLATBUFFERS_BUILD_BENCHMARKS "Enable the build of flatbenchmark."
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_STRICT_MODE
"Build flatbuffers with all warnings as errors (-Werror or /WX)."
OFF)
if(NOT DEFINED FLATBUFFERS_CPP_STD)
set(FLATBUFFERS_CPP_STD 11)
endif()
set(MSVC_LIKE OFF)
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})
set_property(GLOBAL PROPERTY RULE_LAUNCH_COMPILE "time -f 'Wall: %E User: %U Sys: %S | %C' -q -a -o ${FLATBUFFERS_COMPILATION_TIMINGS}")
set_property(GLOBAL PROPERTY RULE_LAUNCH_CUSTOM "time -f 'Wall: %E User: %U Sys: %S | %C' -q -a -o ${FLATBUFFERS_COMPILATION_TIMINGS}")
set_property(GLOBAL PROPERTY RULE_LAUNCH_LINK "time -f 'Wall: %E User: %U Sys: %S | %C' -q -a -o ${FLATBUFFERS_COMPILATION_TIMINGS}")
endif()
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_LIKE)
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=$<BOOL:${FLATBUFFERS_LOCALE_INDEPENDENT}>)
if(NOT WIN32)
check_symbol_exists(realpath "stdlib.h" HAVE_REALPATH)
if(NOT HAVE_REALPATH)
add_definitions(-DFLATBUFFERS_NO_ABSOLUTE_PATH_RESOLUTION)
endif()
endif()
set(FlatBuffers_Library_SRCS
include/flatbuffers/allocator.h
include/flatbuffers/array.h
include/flatbuffers/base.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
include/flatbuffers/flex_flat_util.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_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_rust.cpp
src/idl_gen_fbs.cpp
src/idl_gen_grpc.cpp
src/idl_gen_json_schema.cpp
src/idl_gen_swift.cpp
src/file_name_saving_file_manager.cpp
src/file_binary_writer.cpp
src/file_writer.cpp
src/idl_namer.h
src/namer.h
src/flatc.cpp
src/flatc_main.cpp
src/bfbs_gen.h
src/bfbs_gen_lua.h
src/bfbs_gen_nim.h
src/bfbs_namer.h
include/flatbuffers/code_generators.h
src/binary_annotator.h
src/binary_annotator.cpp
src/annotated_binary_text_gen.h
src/annotated_binary_text_gen.cpp
src/bfbs_gen_lua.cpp
src/bfbs_gen_nim.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/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
tests/proto_test.cpp
tests/reflection_test.cpp
tests/test.cpp
tests/test_assert.h
tests/test_assert.cpp
tests/test_builder.h
tests/test_builder.cpp
tests/util_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
)
set(FlatBuffers_Tests_CPP17_SRCS
${FlatBuffers_Library_SRCS}
tests/test_assert.h
tests/test_assert.cpp
tests/cpp17/test_cpp17.cpp
)
set(FlatBuffers_Sample_Binary_SRCS
samples/sample_binary.cpp
)
set(FlatBuffers_Sample_Text_SRCS
${FlatBuffers_Library_SRCS}
samples/sample_text.cpp
)
set(FlatBuffers_Sample_BFBS_SRCS
${FlatBuffers_Library_SRCS}
samples/sample_bfbs.cpp
)
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
)
# 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)
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}")
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(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
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_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)
set_source_files_properties(src/util.cpp PROPERTIES SKIP_PRECOMPILE_HEADERS ON)
endif()
endif()
endfunction()
include_directories(include)
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
# needed.
add_library(ProjectConfig INTERFACE)
target_compile_features(ProjectConfig
INTERFACE
cxx_std_${FLATBUFFERS_CPP_STD}
)
# Force the standard to be met.
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# We shouldn't rely on any compiler-extensions to make things work.
set(CMAKE_CXX_EXTENSIONS OFF)
if(MSVC_LIKE)
target_compile_options(ProjectConfig
INTERFACE
/W4
$<$<BOOL:${FLATBUFFERS_STRICT_MODE}>:
/WX # Treat all compiler warnings as errors
>
/wd4512 # C4512: assignment operator could not be generated
/wd4316 # C4316: object allocated on the heap may not be aligned
/wd4456 # C4456: hides previous local declaration
$<$<CXX_COMPILER_ID:Clang>:
/D_CRT_SECURE_NO_WARNINGS
>
)
else()
target_compile_options(ProjectConfig
INTERFACE
-Wall
$<$<BOOL:${FLATBUFFERS_STRICT_MODE}>:
-Werror # Treat all compiler warnings as errors
-fno-rtti # Disable runtime type information
$<$<CXX_COMPILER_ID:GNU>:
# False positive string overflow
# https://github.com/google/flatbuffers/issues/7366
-Wno-error=stringop-overflow
>
>
-pedantic
-Wextra
-Wno-unused-parameter
-Wold-style-cast
-fsigned-char
-Wnon-virtual-dtor
# This isn't working for some reason: $<$<CXX_COMPILER_ID:CLANG>:
$<$<BOOL:${IS_CLANG}>:
-Wnewline-eof
-Wno-unknown-warning-option
-Wmissing-declarations
-Wzero-as-null-pointer-constant
$<$<VERSION_GREATER:$<CXX_COMPILER_VERSION>,3.8>:
-Wimplicit-fallthrough
-Wextra-semi
$<$<BOOL:${FLATBUFFERS_STRICT_MODE}>:
-Werror=unused-private-field
>
>
>
$<$<CXX_COMPILER_ID:GNU>:
$<$<VERSION_GREATER:$<CXX_COMPILER_VERSION>,4.4>:
-Wunused-result
-Wunused-parameter
-Werror=unused-parameter
-Wmissing-declarations
>
$<$<VERSION_GREATER:$<CXX_COMPILER_VERSION>,4.7>:
-Wzero-as-null-pointer-constant
>
$<$<VERSION_GREATER:$<CXX_COMPILER_VERSION>,7.0>:
-faligned-new
$<$<BOOL:${FLATBUFFERS_STRICT_MODE}>:
-Werror=implicit-fallthrough=2
>
>
$<$<VERSION_GREATER:$<CXX_COMPILER_VERSION>,8.0>:
-Wextra-semi
>
>
$<$<BOOL:${FLATBUFFERS_CODE_COVERAGE}>:
-g
-fprofile-arcs
-ftest-coverage
>
)
if(FLATBUFFERS_CODE_COVERAGE)
target_link_options(ProjectConfig
INTERFACE
-fprofile-arcs
-ftest-coverage
)
endif()
endif()
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
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
)
target_link_libraries(flatbuffers PRIVATE $<BUILD_INTERFACE:ProjectConfig>)
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_link_libraries(flatc PRIVATE $<BUILD_INTERFACE:ProjectConfig>)
target_compile_options(flatc
PRIVATE
$<$<AND:$<BOOL:${MSVC_LIKE}>,$<CONFIG:Release>>:
/MT
>
)
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 $<TARGET_FILE:flatc>)
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})
target_link_libraries(flathash PRIVATE $<BUILD_INTERFACE:ProjectConfig>)
endif()
if(FLATBUFFERS_BUILD_SHAREDLIB)
add_library(flatbuffers_shared SHARED ${FlatBuffers_Library_SRCS})
target_link_libraries(flatbuffers_shared PRIVATE $<BUILD_INTERFACE:ProjectConfig>)
# 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()
function(compile_schema SRC_FBS OPT OUT_GEN_FILE)
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}"
${OPT}
-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_schema_for_test SRC_FBS OPT)
compile_schema("${SRC_FBS}" "${OPT}" GEN_FILE)
target_sources(flattests PRIVATE ${GEN_FILE})
endfunction()
function(compile_schema_for_samples SRC_FBS OPT)
compile_schema("${SRC_FBS}" "${OPT}" GEN_FILE)
target_sources(flatsample PRIVATE ${GEN_FILE})
endfunction()
if(FLATBUFFERS_BUILD_TESTS)
add_executable(flattests ${FlatBuffers_Tests_SRCS})
target_link_libraries(flattests PRIVATE $<BUILD_INTERFACE:ProjectConfig>)
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}/)
# The flattest target needs some generated files
SET(FLATC_OPT --cpp --gen-mutable --gen-object-api --reflect-names)
SET(FLATC_OPT_COMP ${FLATC_OPT};--gen-compare)
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(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}")
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()
include_directories(${CMAKE_CURRENT_BINARY_DIR}/samples)
add_executable(flatsamplebinary ${FlatBuffers_Sample_Binary_SRCS})
add_executable(flatsampletext ${FlatBuffers_Sample_Text_SRCS})
add_executable(flatsamplebfbs ${FlatBuffers_Sample_BFBS_SRCS})
# 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)
compile_schema_for_samples(samples/monster.fbs "${FLATC_OPT_COMP}")
target_link_libraries(flatsamplebinary PRIVATE $<BUILD_INTERFACE:ProjectConfig> flatsample)
target_link_libraries(flatsampletext PRIVATE $<BUILD_INTERFACE:ProjectConfig> flatsample)
target_link_libraries(flatsamplebfbs PRIVATE $<BUILD_INTERFACE:ProjectConfig> flatsample)
if(FLATBUFFERS_BUILD_CPP17)
add_executable(flattests_cpp17 ${FlatBuffers_Tests_CPP17_SRCS})
target_link_libraries(flattests_cpp17 PRIVATE $<BUILD_INTERFACE:ProjectConfig>)
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})
endif()
endif(FLATBUFFERS_BUILD_CPP17)
endif()
if(FLATBUFFERS_BUILD_GRPCTEST)
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})
target_link_libraries(grpctest
PRIVATE
$<BUILD_INTERFACE:ProjectConfig>
gRPC::grpc++_unsecure
gRPC::gpr
pthread
dl
)
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/BuildFlatBuffers.cmake"
"${CMAKE_CURRENT_BINARY_DIR}/flatbuffers-config-version.cmake"
DESTINATION ${FB_CMAKE_DIR}
)
if(FLATBUFFERS_BUILD_FLATLIB)
install(
TARGETS flatbuffers EXPORT FlatBuffersTargets
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
)
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)
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}
)
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()
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)
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 $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}/include>)

42
CONTRIBUTING.md Normal file
View File

@ -0,0 +1,42 @@
Contributing {#contributing}
============
Want to contribute? Great! First, read this page (including the small print at
the end).
# Before you contribute
Before we can use your code, you must sign the
[Google Individual Contributor License Agreement](https://developers.google.com/open-source/cla/individual?csw=1)
(CLA), which you can do online. The CLA is necessary mainly because 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. We also
need to be sure of various other things—for instance that you'll tell us if you
know that your code infringes on other people's patents. You don't have to sign
the CLA until after you've submitted your code for review and a member has
approved it, but you must do it before we can put your code into our codebase.
Before you start working on a larger contribution, you should get in touch with
us first through the issue tracker with your idea so that we can help out and
possibly guide you. Coordinating up front makes it much easier to avoid
frustration later on.
# Code reviews
All submissions, including submissions by project members, require review. We
use Github pull requests for this purpose.
Some tips for good pull requests:
* Use our code
[style guide](https://google.github.io/styleguide/cppguide.html).
When in doubt, try to stay true to the existing code of the project.
* 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).
* 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
HEAD. This make reviewing the code so much easier, and our history more
readable.
# 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.

21
FlatBuffers.podspec Normal file
View File

@ -0,0 +1,21 @@
Pod::Spec.new do |s|
s.name = 'FlatBuffers'
s.version = '24.3.25'
s.summary = 'FlatBuffers: Memory Efficient Serialization Library'
s.description = "FlatBuffers is a cross platform serialization library architected for
maximum memory efficiency. It allows you to directly access serialized
data without parsing/unpacking it first, while still having great
forwards/backwards compatibility."
s.homepage = 'https://github.com/google/flatbuffers'
s.license = { :type => 'Apache2.0', :file => 'LICENSE' }
s.author = { 'mustii' => 'mustii@mmk.one' }
s.source = { :git => 'https://github.com/google/flatbuffers.git', :tag => s.version.to_s, :submodules => true }
s.ios.deployment_target = '11.0'
s.osx.deployment_target = '10.14'
s.swift_version = '5.0'
s.source_files = 'swift/Sources/Flatbuffers/*.swift'
end

22
Formatters.md Normal file
View File

@ -0,0 +1,22 @@
# Format Guidelines
If you are interesting in contributing to the flatbuffers project, please take a second to read this document. Each language has it's own set of rules, that are defined in their respective formatter/linter documents.
# Notes
- Run the linter on the language you are working on before making a Pull Request.
- DONT format/lint the generated code.
# Languages
## C++
C++ uses `clang-format` as it's formatter. Run the following script `sh scripts/clang-format-git.sh`, and it should style the C++ code according to [google style guide](https://google.github.io/styleguide/cppguide.html).
## Swift
Swift uses swiftformat as it's formatter. Take a look at [how to install here](https://github.com/nicklockwood/SwiftFormat/blob/master/README.md#how-do-i-install-it). Run the following command `swiftformat --config swift.swiftformat .` in the root directory of the project
## 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

202
LICENSE Normal file
View File

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

36
Package.swift Normal file
View File

@ -0,0 +1,36 @@
// swift-tools-version:5.6
/*
* Copyright 2020 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 PackageDescription
let package = Package(
name: "FlatBuffers",
platforms: [
.iOS(.v11),
.macOS(.v10_14),
],
products: [
.library(
name: "FlatBuffers",
targets: ["FlatBuffers"]),
],
targets: [
.target(
name: "FlatBuffers",
dependencies: [],
path: "swift/Sources"),
])

37
Package@swift-5.5.swift Normal file
View File

@ -0,0 +1,37 @@
// swift-tools-version:5.5
/*
* Copyright 2020 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 PackageDescription
let package = Package(
name: "FlatBuffers",
platforms: [
.iOS(.v11),
.macOS(.v10_14),
],
products: [
.library(
name: "FlatBuffers",
targets: ["FlatBuffers"]),
],
targets: [
.target(
name: "FlatBuffers",
dependencies: [],
path: "swift/Sources"),
])

118
README.md Normal file
View File

@ -0,0 +1,118 @@
![logo](http://google.github.io/flatbuffers/fpl_logo_small.png) 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)
**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 compliation (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
- Linux
- Android
- And any others with a recent C++ compiler (C++ 11 and newer)
## Supported programming languages
Code generation and runtime libraries for many popular languages.
1. C
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)
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. Rust - [crates.io](https://crates.io/crates/flatbuffers)
1. Swift - [swiftpackageindex](https://swiftpackageindex.com/google/flatbuffers)
1. TypeScript - [NPM](https://www.npmjs.com/package/flatbuffers)
1. Nim
## Versioning
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
* [FlatBuffers Issues Tracker][] to submit an issue.
* [stackoverflow.com][] with [`flatbuffers` tag][] for any questions regarding FlatBuffers.
*To contribute to this project,* see [CONTRIBUTING][].
## Community
* [Discord Server](https:///discord.gg/6qgKs3R)
## Security
Please see our [Security Policy](SECURITY.md) for reporting vulnerabilities.
## Licensing
*Flatbuffers* is licensed under the Apache License, Version 2.0. See [LICENSE][] for the full license text.
<br>
[CONTRIBUTING]: http://github.com/google/flatbuffers/blob/master/CONTRIBUTING.md
[`flatbuffers` tag]: https://stackoverflow.com/questions/tagged/flatbuffers
[FlatBuffers Google Group]: https://groups.google.com/forum/#!forum/flatbuffers
[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

11
SECURITY.md Normal file
View File

@ -0,0 +1,11 @@
# Security Policy
## Reporting a Vulnerability
To report a security issue, please use http://g.co/vulnz. We use
http://g.co/vulnz for our intake, and do coordination and disclosure here on
GitHub (including using GitHub Security Advisory). The Google Security Team will
respond within 5 working days of your report on g.co/vulnz.
Select the `I want to report a technical security or an abuse risk related bug
in a Google product (SQLi, XSS, etc.)` option and complete the form.

169
WORKSPACE Normal file
View File

@ -0,0 +1,169 @@
workspace(name = "com_github_google_flatbuffers")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive", "http_file")
http_archive(
name = "platforms",
sha256 = "3a561c99e7bdbe9173aa653fd579fe849f1d8d67395780ab4770b1f381431d51",
urls = [
"https://mirror.bazel.build/github.com/bazelbuild/platforms/releases/download/0.0.7/platforms-0.0.7.tar.gz",
"https://github.com/bazelbuild/platforms/releases/download/0.0.7/platforms-0.0.7.tar.gz",
],
)
http_archive(
name = "build_bazel_rules_apple",
sha256 = "34c41bfb59cdaea29ac2df5a2fa79e5add609c71bb303b2ebb10985f93fa20e7",
url = "https://github.com/bazelbuild/rules_apple/releases/download/3.1.1/rules_apple.3.1.1.tar.gz",
)
load(
"@build_bazel_rules_apple//apple:repositories.bzl",
"apple_rules_dependencies",
)
apple_rules_dependencies()
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 = "278b7ff5a826f3dc10f04feaf0b70d48b68748ccd512d7f98bf442077f043fe3",
urls = [
"https://mirror.bazel.build/github.com/bazelbuild/rules_go/releases/download/v0.41.0/rules_go-v0.41.0.zip",
"https://github.com/bazelbuild/rules_go/releases/download/v0.41.0/rules_go-v0.41.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 = "aspect_rules_js",
sha256 = "76a04ef2120ee00231d85d1ff012ede23963733339ad8db81f590791a031f643",
strip_prefix = "rules_js-1.34.1",
url = "https://github.com/aspect-build/rules_js/releases/download/v1.34.1/rules_js-v1.34.1.tar.gz",
)
load("@aspect_rules_js//js:repositories.bzl", "rules_js_dependencies")
rules_js_dependencies()
load("@aspect_rules_js//npm:npm_import.bzl", "npm_translate_lock", "pnpm_repository")
pnpm_repository(name = "pnpm")
http_archive(
name = "aspect_rules_ts",
sha256 = "4c3f34fff9f96ffc9c26635d8235a32a23a6797324486c7d23c1dfa477e8b451",
strip_prefix = "rules_ts-1.4.5",
url = "https://github.com/aspect-build/rules_ts/releases/download/v1.4.5/rules_ts-v1.4.5.tar.gz",
)
load("@aspect_rules_ts//ts:repositories.bzl", "rules_ts_dependencies")
rules_ts_dependencies(
# Since rules_ts doesn't always have the newest integrity hashes, we
# compute it manually here.
# $ curl --silent https://registry.npmjs.org/typescript/5.3.3 | jq ._integrity
ts_integrity = "sha512-pXWcraxM0uxAS+tN0AG/BF2TyqmHO014Z070UsJ+pFvYuRSq8KH8DmWpnbXe0pEPDHXZV3FcAbJkijJ5oNEnWw==",
ts_version_from = "//:package.json",
)
load("@rules_nodejs//nodejs:repositories.bzl", "DEFAULT_NODE_VERSION", "nodejs_register_toolchains")
nodejs_register_toolchains(
name = "nodejs",
node_version = DEFAULT_NODE_VERSION,
)
npm_translate_lock(
name = "npm",
npmrc = "//:.npmrc",
pnpm_lock = "//:pnpm-lock.yaml",
# Set this to True when the lock file needs to be updated, commit the
# changes, then set to False again.
update_pnpm_lock = False,
verify_node_modules_ignored = "//:.bazelignore",
)
load("@npm//:repositories.bzl", "npm_repositories")
npm_repositories()
http_archive(
name = "aspect_rules_esbuild",
sha256 = "098e38e5ee868c14a6484ba263b79e57d48afacfc361ba30137c757a9c4716d6",
strip_prefix = "rules_esbuild-0.15.0",
url = "https://github.com/aspect-build/rules_esbuild/releases/download/v0.15.0/rules_esbuild-v0.15.0.tar.gz",
)
# Register a toolchain containing esbuild npm package and native bindings
load("@aspect_rules_esbuild//esbuild:repositories.bzl", "LATEST_ESBUILD_VERSION", "esbuild_register_toolchains")
esbuild_register_toolchains(
name = "esbuild",
esbuild_version = LATEST_ESBUILD_VERSION,
)
http_file(
name = "bazel_linux_x86_64",
downloaded_file_path = "bazel",
executable = True,
sha256 = "e78fc3394deae5408d6f49a15c7b1e615901969ecf6e50d55ef899996b0b8458",
urls = [
"https://github.com/bazelbuild/bazel/releases/download/6.3.2/bazel-6.3.2-linux-x86_64",
],
)

22
android/.project Normal file
View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>FlatBufferTest</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
</buildSpec>
<natures>
</natures>
<filteredResources>
<filter>
<id>1672434305228</id>
<name></name>
<type>30</type>
<matcher>
<id>org.eclipse.core.resources.regexFilterMatcher</id>
<arguments>node_modules|\.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__</arguments>
</matcher>
</filter>
</filteredResources>
</projectDescription>

View File

@ -0,0 +1,31 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- BEGIN_INCLUDE(manifest) -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.FlatBufferTest">
<uses-sdk android:minSdkVersion="14"/>
<uses-feature android:glEsVersion="0x00020000"></uses-feature>
<!-- This .apk has no Java code itself, so set hasCode to false. -->
<application android:name="android.support.multidex.MultiDexApplication"
android:label="@string/app_name"
android:hasCode="false"
android:allowBackup="false">
<!-- Our activity is the built-in NativeActivity framework class.
This will take care of integrating with our NDK code. -->
<activity android:name="android.app.NativeActivity"
android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden"
android:screenOrientation="landscape">
<!-- Tell NativeActivity the name of or .so -->
<meta-data android:name="android.app.lib_name"
android:value="FlatBufferTest" />
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
<!-- END_INCLUDE(manifest) -->

1
android/app/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/build

125
android/app/build.gradle Normal file
View File

@ -0,0 +1,125 @@
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
android {
compileSdk 33
defaultConfig {
applicationId "com.flatbuffers.app"
minSdkVersion 26
targetSdkVersion 33
versionCode 1
versionName "1.0"
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
sourceSets {
main {
java {
srcDir '../../java/src/main/java/'
}
}
}
ndk {
abiFilters 'arm64-v8a', 'armeabi-v7a'
}
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
externalNativeBuild {
cmake {
arguments "-DFLATBUFFERS_SRC=${rootProject.projectDir}/.."
}
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
externalNativeBuild {
cmake {
path "src/main/cpp/CMakeLists.txt"
}
}
task generateFbsCpp(type: Exec) {
def inputDir = file("$projectDir/src/main/fbs")
def outputCppDir = file("$projectDir/src/main/cpp/generated/")
def fbsFiles = layout.files { file(inputDir).listFiles() }.filter { File f -> f.name.endsWith(".fbs") }.toList()
ignoreExitValue(true)
standardOutput = new ByteArrayOutputStream()
errorOutput = new ByteArrayOutputStream()
def commandLineArgs = ['flatc', '-o', outputCppDir, '--cpp']
fbsFiles.forEach{
commandLineArgs.add(it.path)
}
commandLine commandLineArgs
doFirst {
delete "$outputCppDir/"
mkdir "$outputCppDir/"
}
doLast {
if (executionResult.get().exitValue != 0) {
throw new GradleException("flatc failed with: ${executionResult.get().toString()}")
}
}
}
task generateFbsKotlin(type: Exec) {
def inputDir = file("$projectDir/src/main/fbs")
def outputKotlinDir = file("$projectDir/src/main/java/generated/")
def fbsFiles = layout.files { file(inputDir).listFiles() }.filter { File f -> f.name.endsWith(".fbs") }.toList()
ignoreExitValue(true)
standardOutput = new ByteArrayOutputStream()
errorOutput = new ByteArrayOutputStream()
setErrorOutput(errorOutput)
setStandardOutput(standardOutput)
def commandLineArgs = ['flatc', '-o', outputKotlinDir, '--kotlin']
fbsFiles.forEach{
commandLineArgs.add(it.path)
}
commandLine commandLineArgs
doFirst {
delete "$outputKotlinDir/"
mkdir "$outputKotlinDir/"
}
doLast {
if (executionResult.get().exitValue != 0) {
throw new GradleException("flatc failed with: ${executionResult.get().toString()}")
}
}
}
afterEvaluate {
tasks.named("preBuild") {
dependsOn(generateFbsKotlin)
dependsOn(generateFbsCpp)
}
}
namespace 'com.flatbuffers.app'
}
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
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'
}

21
android/app/proguard-rules.pro vendored Normal file
View File

@ -0,0 +1,21 @@
# 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

View File

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

View File

@ -0,0 +1,53 @@
# For more information about using CMake with Android Studio, read the
# documentation: https://d.android.com/studio/projects/add-native-code.html
# Sets the minimum version of CMake required to build the native library.
cmake_minimum_required(VERSION 3.4.1)
# Creates and names a library, sets it as either STATIC
# or SHARED, and provides the relative paths to its source code.
# You can define multiple libraries, and CMake builds them for you.
# Gradle automatically packages shared libraries with your APK.
include_directories(${FLATBUFFERS_SRC}/include)
add_subdirectory(flatbuffers)
FILE(GLOB Generated_SRCS generated/*.h)
add_library( # Sets the name of the library.
native-lib
# Sets the library as a shared library.
SHARED
# Provides a relative path to your source file(s).
animals.cpp
${Generated_SRCS}
)
# Searches for a specified prebuilt library and stores the path as a
# variable. Because CMake includes system libraries in the search path by
# default, you only need to specify the name of the public NDK library
# you want to add. CMake verifies that the library exists before
# completing its build.
find_library( # Sets the name of the path variable.
log-lib
# Specifies the name of the NDK library that
# you want CMake to locate.
log )
# Specifies libraries CMake should link to your target library. You
# can link multiple libraries, such as libraries you define in this
# build script, prebuilt third-party libraries, or system libraries.
target_link_libraries( # Specifies the target library.
native-lib
flatbuffers
# Links the target library to the log library
# included in the NDK.
${log-lib} )

View File

@ -0,0 +1,39 @@
/*
* Copyright 2014 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.
*/
#include <jni.h>
#include <string>
#include <search.h>
#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);
// copies it to a Java byte array.
auto buf = reinterpret_cast<jbyte*>(fb.GetBufferPointer());
int size = fb.GetSize();
auto ret = env->NewByteArray(size);
env->SetByteArrayRegion (ret, 0, fb.GetSize(), buf);
return ret;
}

View File

@ -0,0 +1,56 @@
# For more information about using CMake with Android Studio, read the
# documentation: https://d.android.com/studio/projects/add-native-code.html
# Sets the minimum version of CMake required to build the native library.
cmake_minimum_required(VERSION 3.4.1)
include_directories(${FLATBUFFERS_SRC}/include)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=gnu++11 -fexceptions -Wall -DFLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE")
# 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")
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/buffer.h
${FLATBUFFERS_SRC}/include/flatbuffers/buffer_ref.h
${FLATBUFFERS_SRC}/include/flatbuffers/default_allocator.h
${FLATBUFFERS_SRC}/include/flatbuffers/detached_buffer.h
${FLATBUFFERS_SRC}/include/flatbuffers/flatbuffer_builder.h
${FLATBUFFERS_SRC}/include/flatbuffers/flatbuffers.h
${FLATBUFFERS_SRC}/include/flatbuffers/flexbuffers.h
${FLATBUFFERS_SRC}/include/flatbuffers/flex_flat_util.h
${FLATBUFFERS_SRC}/include/flatbuffers/hash.h
${FLATBUFFERS_SRC}/include/flatbuffers/idl.h
${FLATBUFFERS_SRC}/include/flatbuffers/minireflect.h
${FLATBUFFERS_SRC}/include/flatbuffers/reflection.h
${FLATBUFFERS_SRC}/include/flatbuffers/reflection_generated.h
${FLATBUFFERS_SRC}/include/flatbuffers/registry.h
${FLATBUFFERS_SRC}/include/flatbuffers/stl_emulation.h
${FLATBUFFERS_SRC}/include/flatbuffers/string.h
${FLATBUFFERS_SRC}/include/flatbuffers/struct.h
${FLATBUFFERS_SRC}/include/flatbuffers/table.h
${FLATBUFFERS_SRC}/include/flatbuffers/util.h
${FLATBUFFERS_SRC}/include/flatbuffers/vector.h
${FLATBUFFERS_SRC}/include/flatbuffers/vector_downward.h
${FLATBUFFERS_SRC}/include/flatbuffers/verifier.h
${FLATBUFFERS_SRC}/src/idl_parser.cpp
${FLATBUFFERS_SRC}/src/idl_gen_text.cpp
${FLATBUFFERS_SRC}/src/reflection.cpp
${FLATBUFFERS_SRC}/src/util.cpp
${FLATBUFFERS_SRC}/src/idl_gen_fbs.cpp
${FLATBUFFERS_SRC}/src/code_generators.cpp
)
add_library( # Sets the name of the library.
flatbuffers
${FlatBuffers_Library_SRCS}
${Generated_SRCS}
)

View File

@ -0,0 +1,134 @@
// 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_
#include "flatbuffers/flatbuffers.h"
// 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 == 23 &&
FLATBUFFERS_VERSION_MINOR == 1 &&
FLATBUFFERS_VERSION_REVISION == 21,
"Non-compatible flatbuffers version included");
namespace com {
namespace fbs {
namespace app {
struct Animal;
struct AnimalBuilder;
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<const ::flatbuffers::String *>(VT_NAME);
}
const ::flatbuffers::String *sound() const {
return GetPointer<const ::flatbuffers::String *>(VT_SOUND);
}
uint16_t weight() const {
return GetField<uint16_t>(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<uint16_t>(verifier, VT_WEIGHT, 2) &&
verifier.EndTable();
}
};
struct AnimalBuilder {
typedef Animal Table;
::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<::flatbuffers::String> sound) {
fbb_.AddOffset(Animal::VT_SOUND, sound);
}
void add_weight(uint16_t weight) {
fbb_.AddElement<uint16_t>(Animal::VT_WEIGHT, weight, 0);
}
explicit AnimalBuilder(::flatbuffers::FlatBufferBuilder &_fbb)
: fbb_(_fbb) {
start_ = fbb_.StartTable();
}
::flatbuffers::Offset<Animal> Finish() {
const auto end = fbb_.EndTable(start_);
auto o = ::flatbuffers::Offset<Animal>(end);
return o;
}
};
inline ::flatbuffers::Offset<Animal> 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);
builder_.add_name(name);
builder_.add_weight(weight);
return builder_.Finish();
}
inline ::flatbuffers::Offset<Animal> 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);
}
inline const com::fbs::app::Animal *GetAnimal(const void *buf) {
return ::flatbuffers::GetRoot<com::fbs::app::Animal>(buf);
}
inline const com::fbs::app::Animal *GetSizePrefixedAnimal(const void *buf) {
return ::flatbuffers::GetSizePrefixedRoot<com::fbs::app::Animal>(buf);
}
inline bool VerifyAnimalBuffer(
::flatbuffers::Verifier &verifier) {
return verifier.VerifyBuffer<com::fbs::app::Animal>(nullptr);
}
inline bool VerifySizePrefixedAnimalBuffer(
::flatbuffers::Verifier &verifier) {
return verifier.VerifySizePrefixedBuffer<com::fbs::app::Animal>(nullptr);
}
inline void FinishAnimalBuffer(
::flatbuffers::FlatBufferBuilder &fbb,
::flatbuffers::Offset<com::fbs::app::Animal> root) {
fbb.Finish(root);
}
inline void FinishSizePrefixedAnimalBuffer(
::flatbuffers::FlatBufferBuilder &fbb,
::flatbuffers::Offset<com::fbs::app::Animal> root) {
fbb.FinishSizePrefixed(root);
}
} // namespace app
} // namespace fbs
} // namespace com
#endif // FLATBUFFERS_GENERATED_ANIMAL_COM_FBS_APP_H_

View File

@ -0,0 +1,23 @@
// Copyright 2015 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace com.fbs.app;
table Animal {
name:string;
sound:string;
weight: uint16;
}
root_type Animal;

View File

@ -0,0 +1,51 @@
package com.flatbuffers.app
import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import com.fbs.app.Animal
import com.google.flatbuffers.FlatBufferBuilder
import java.nio.ByteBuffer
@ExperimentalUnsignedTypes
class MainActivity : AppCompatActivity() {
@SuppressLint("SetTextI18n")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val tiger = Animal.getRootAsAnimal(ByteBuffer.wrap(createAnimalFromJNI()))
findViewById<TextView>(R.id.tv_animal_one).text = animalInfo(tiger)
findViewById<TextView>(R.id.tv_animal_two).text = animalInfo(createAnimalFromKotlin())
}
// This function is a sample of communicating FlatBuffers between JNI (native C++) and Java.
// Implementation can be found on animals.cpp file.
private external fun createAnimalFromJNI(): ByteArray
// Create a "Cow" Animal flatbuffers from Kotlin
private fun createAnimalFromKotlin():Animal {
val fb = FlatBufferBuilder(100)
val cowOffset = Animal.createAnimal(
builder = fb,
nameOffset = fb.createString("Cow"),
soundOffset = fb.createString("Moo"),
weight = 720u
)
fb.finish(cowOffset)
return Animal.getRootAsAnimal(fb.dataBuffer())
}
private fun animalInfo(animal: Animal): String =
"The ${animal.name} sound is ${animal.sound} and it weights ${animal.weight}kg."
companion object {
// Used to load the 'native-lib' library on application startup.
init {
System.loadLibrary("native-lib")
}
}
}

View File

@ -0,0 +1,84 @@
// automatically generated by the FlatBuffers compiler, do not modify
package com.fbs.app
import com.google.flatbuffers.BaseVector
import com.google.flatbuffers.BooleanVector
import com.google.flatbuffers.ByteVector
import com.google.flatbuffers.Constants
import com.google.flatbuffers.DoubleVector
import com.google.flatbuffers.FlatBufferBuilder
import com.google.flatbuffers.FloatVector
import com.google.flatbuffers.LongVector
import com.google.flatbuffers.StringVector
import com.google.flatbuffers.Struct
import com.google.flatbuffers.Table
import com.google.flatbuffers.UnionVector
import java.nio.ByteBuffer
import java.nio.ByteOrder
import kotlin.math.sign
@Suppress("unused")
@kotlin.ExperimentalUnsignedTypes
class Animal : Table() {
fun __init(_i: Int, _bb: ByteBuffer) {
__reset(_i, _bb)
}
fun __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_24_3_25()
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)
}
}

View File

@ -0,0 +1,30 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path android:pathData="M31,63.928c0,0 6.4,-11 12.1,-13.1c7.2,-2.6 26,-1.4 26,-1.4l38.1,38.1L107,108.928l-32,-1L31,63.928z">
<aapt:attr name="android:fillColor">
<gradient
android:endX="85.84757"
android:endY="92.4963"
android:startX="42.9492"
android:startY="49.59793"
android:type="linear">
<item
android:color="#44000000"
android:offset="0.0" />
<item
android:color="#00000000"
android:offset="1.0" />
</gradient>
</aapt:attr>
</path>
<path
android:fillColor="#FFFFFF"
android:fillType="nonZero"
android:pathData="M65.3,45.828l3.8,-6.6c0.2,-0.4 0.1,-0.9 -0.3,-1.1c-0.4,-0.2 -0.9,-0.1 -1.1,0.3l-3.9,6.7c-6.3,-2.8 -13.4,-2.8 -19.7,0l-3.9,-6.7c-0.2,-0.4 -0.7,-0.5 -1.1,-0.3C38.8,38.328 38.7,38.828 38.9,39.228l3.8,6.6C36.2,49.428 31.7,56.028 31,63.928h46C76.3,56.028 71.8,49.428 65.3,45.828zM43.4,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2c-0.3,-0.7 -0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C45.3,56.528 44.5,57.328 43.4,57.328L43.4,57.328zM64.6,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2s-0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C66.5,56.528 65.6,57.328 64.6,57.328L64.6,57.328z"
android:strokeWidth="1"
android:strokeColor="#00000000" />
</vector>

View File

@ -0,0 +1,170 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path
android:fillColor="#3DDC84"
android:pathData="M0,0h108v108h-108z" />
<path
android:fillColor="#00000000"
android:pathData="M9,0L9,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,0L19,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M29,0L29,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M39,0L39,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M49,0L49,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M59,0L59,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M69,0L69,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M79,0L79,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M89,0L89,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M99,0L99,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,9L108,9"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,19L108,19"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,29L108,29"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,39L108,39"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,49L108,49"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,59L108,59"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,69L108,69"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,79L108,79"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,89L108,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,99L108,99"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,29L89,29"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,39L89,39"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,49L89,49"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,59L89,59"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,69L89,69"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,79L89,79"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M29,19L29,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M39,19L39,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M49,19L49,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M59,19L59,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M69,19L69,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M79,19L79,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
</vector>

View File

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
tools:context=".MainActivity">
<TextView
android:id="@+id/tv_animal_one"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:text="Text Sample"/>
<TextView
android:id="@+id/tv_animal_two"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:text="Text Sample 2"/>
</LinearLayout>

View File

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>

View File

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#6200EE</color>
<color name="colorPrimaryDark">#3700B3</color>
<color name="colorAccent">#03DAC5</color>
</resources>

View File

@ -0,0 +1,3 @@
<resources>
<string name="app_name">FlatbuffersTestApp</string>
</resources>

View File

@ -0,0 +1,10 @@
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
</resources>

35
android/build.gradle Normal file
View File

@ -0,0 +1,35 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = "1.7.21"
repositories {
google()
mavenCentral()
}
dependencies {
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
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
mavenCentral()
}
}
tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
compileKotlin {
dependsOn flatbuffer
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}

23
android/gradle.properties Normal file
View File

@ -0,0 +1,23 @@
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx2048m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app"s APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
# Automatically convert third-party libraries to use AndroidX
android.enableJetifier=true
# Kotlin code style for this project: "official" or "obsolete":
kotlin.code.style=official
# Use parallel builds
org.gradle.parallel=true

Binary file not shown.

View File

@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.0.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

172
android/gradlew vendored Executable file
View File

@ -0,0 +1,172 @@
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"

84
android/gradlew.bat vendored Normal file
View File

@ -0,0 +1,84 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

2
android/settings.gradle Normal file
View File

@ -0,0 +1,2 @@
include ':app'
rootProject.name = "FlatbuffersTest"

0
bazel/BUILD.bazel Normal file
View File

88
benchmarks/CMakeLists.txt Normal file
View File

@ -0,0 +1,88 @@
# Setup for running Google Benchmarks (https://github.com/google/benchmark) on
# 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)
# No particular reason for the specific GIT_TAGs for the following repos, they
# were just the latest releases when this was added.
FetchContent_Declare(
googletest
GIT_REPOSITORY https://github.com/google/googletest.git
GIT_TAG e2239ee6043f73722e7aa812a459f54a28552929 # release-1.11.0
)
FetchContent_Declare(
googlebenchmark
GIT_REPOSITORY https://github.com/google/benchmark.git
GIT_TAG 0d98dba29d66e93259db7daa53a9327df767a415 # v1.6.1
)
# For Windows: Prevent overriding the parent project's compiler/linker
# settings.
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
FetchContent_MakeAvailable(
googletest
googlebenchmark
)
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)
set(CPP_BENCH_FB_GEN ${CPP_FB_BENCH_DIR}/bench_generated.h)
set(FlatBenchmark_SRCS
${CPP_BENCH_DIR}/benchmark_main.cpp
${CPP_FB_BENCH_DIR}/fb_bench.cpp
${CPP_RAW_BENCH_DIR}/raw_bench.cpp
${CPP_BENCH_FB_GEN}
)
# Generate the flatbuffers benchmark code from the flatbuffers schema using
# flatc itself, thus it depends on flatc. This also depends on the C++ runtime
# flatbuffers and the schema file itself, so it should auto-generated at the
# correct times.
add_custom_command(
OUTPUT ${CPP_BENCH_FB_GEN}
COMMAND
"${FLATBUFFERS_FLATC_EXECUTABLE}"
--cpp
-o ${CPP_FB_BENCH_DIR}
${CPP_BENCH_FBS}
DEPENDS
flatc
flatbuffers
${CPP_BENCH_FBS}
COMMENT "Run Flatbuffers Benchmark Codegen: ${CPP_BENCH_FB_GEN}"
VERBATIM)
# The main flatbuffers benchmark executable
add_executable(flatbenchmark ${FlatBenchmark_SRCS})
# Benchmark requires C++11
target_compile_features(flatbenchmark PRIVATE
cxx_std_11 # requires cmake 3.8
)
target_compile_options(flatbenchmark
PRIVATE
-fno-aligned-new
-Wno-deprecated-declarations
)
# Set the output directory to the root binary directory
set_target_properties(flatbenchmark
PROPERTIES RUNTIME_OUTPUT_DIRECTORY
"${CMAKE_BINARY_DIR}"
)
# The includes of the benchmark files are fully qualified from flatbuffers root.
target_include_directories(flatbenchmark PUBLIC ${CMAKE_SOURCE_DIR})
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
)

19
benchmarks/cpp/bench.h Normal file
View File

@ -0,0 +1,19 @@
#ifndef BENCHMARKS_CPP_BENCH_H_
#define BENCHMARKS_CPP_BENCH_H_
#include <cstdint>
struct Bench {
virtual ~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;
int64_t sum = 0;
};
#endif // BENCHMARKS_CPP_BENCH_H_

View File

@ -0,0 +1,96 @@
#include <benchmark/benchmark.h>
#include <gtest/gtest.h>
#include "benchmarks/cpp/bench.h"
#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> &bench, uint8_t *buffer) {
int64_t length;
for (auto _ : state) {
bench->Encode(buffer, length);
benchmark::DoNotOptimize(length);
}
}
static inline void Decode(benchmark::State &state,
std::unique_ptr<Bench> &bench, uint8_t *buffer) {
int64_t length;
uint8_t *encoded = bench->Encode(buffer, length);
for (auto _ : state) {
void *decoded = bench->Decode(encoded, length);
benchmark::DoNotOptimize(decoded);
}
}
static inline void Use(benchmark::State &state, std::unique_ptr<Bench> &bench,
uint8_t *buffer, int64_t check_sum) {
int64_t 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); }
EXPECT_EQ(sum, check_sum);
}
static void BM_Flatbuffers_Encode(benchmark::State &state) {
const int64_t kBufferLength = 1024;
uint8_t buffer[kBufferLength];
StaticAllocator allocator(&buffer[0]);
std::unique_ptr<Bench> bench = NewFlatBuffersBench(kBufferLength, &allocator);
Encode(state, bench, buffer);
}
BENCHMARK(BM_Flatbuffers_Encode);
static void BM_Flatbuffers_Decode(benchmark::State &state) {
const int64_t kBufferLength = 1024;
uint8_t buffer[kBufferLength];
StaticAllocator allocator(&buffer[0]);
std::unique_ptr<Bench> bench = NewFlatBuffersBench(kBufferLength, &allocator);
Decode(state, bench, buffer);
}
BENCHMARK(BM_Flatbuffers_Decode);
static void BM_Flatbuffers_Use(benchmark::State &state) {
const int64_t kBufferLength = 1024;
uint8_t buffer[kBufferLength];
StaticAllocator allocator(&buffer[0]);
std::unique_ptr<Bench> bench = NewFlatBuffersBench(kBufferLength, &allocator);
Use(state, bench, buffer, 218812692406581874);
}
BENCHMARK(BM_Flatbuffers_Use);
static void BM_Raw_Encode(benchmark::State &state) {
const int64_t kBufferLength = 1024;
uint8_t buffer[kBufferLength];
std::unique_ptr<Bench> bench = NewRawBench();
Encode(state, bench, buffer);
}
BENCHMARK(BM_Raw_Encode);
static void BM_Raw_Decode(benchmark::State &state) {
const int64_t kBufferLength = 1024;
uint8_t buffer[kBufferLength];
std::unique_ptr<Bench> bench = NewRawBench();
Decode(state, bench, buffer);
}
BENCHMARK(BM_Raw_Decode);
static void BM_Raw_Use(benchmark::State &state) {
const int64_t kBufferLength = 1024;
uint8_t buffer[kBufferLength];
std::unique_ptr<Bench> bench = NewRawBench();
Use(state, bench, buffer, 218812692406581874);
}
BENCHMARK(BM_Raw_Use);

View File

@ -0,0 +1,52 @@
// Copyright 2021 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// 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.
// trying to represent a typical mix of datatypes:
// 1 array of 3 elements, each element: 1 string, 3 nested objects, 9 scalars
// root element has the array, additional string and an enum
namespace benchmarks_flatbuffers;
enum Enum : short { Apples, Pears, Bananas}
struct Foo {
id:ulong;
count:short;
prefix:byte;
length:uint;
}
struct Bar {
parent:Foo;
time:int;
ratio:float;
size:ushort;
}
table FooBar {
sibling:Bar;
name:string;
rating:double;
postfix:ubyte;
}
table FooBarContainer {
list:[FooBar]; // 3 copies of the above
initialized:bool;
fruit:Enum;
location:string;
}
root_type FooBarContainer;

View File

@ -0,0 +1,354 @@
// automatically generated by the FlatBuffers compiler, do not modify
#ifndef FLATBUFFERS_GENERATED_BENCH_BENCHMARKS_FLATBUFFERS_H_
#define FLATBUFFERS_GENERATED_BENCH_BENCHMARKS_FLATBUFFERS_H_
#include "flatbuffers/flatbuffers.h"
// 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");
namespace benchmarks_flatbuffers {
struct Foo;
struct Bar;
struct FooBar;
struct FooBarBuilder;
struct FooBarContainer;
struct FooBarContainerBuilder;
enum Enum : int16_t {
Enum_Apples = 0,
Enum_Pears = 1,
Enum_Bananas = 2,
Enum_MIN = Enum_Apples,
Enum_MAX = Enum_Bananas
};
inline const Enum (&EnumValuesEnum())[3] {
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
};
return names;
}
inline const char *EnumNameEnum(Enum e) {
if (flatbuffers::IsOutRange(e, Enum_Apples, Enum_Bananas)) return "";
const size_t index = static_cast<size_t>(e);
return EnumNamesEnum()[index];
}
FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(8) Foo FLATBUFFERS_FINAL_CLASS {
private:
uint64_t id_;
int16_t count_;
int8_t prefix_;
int8_t padding0__;
uint32_t length_;
public:
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)
: id_(flatbuffers::EndianScalar(_id)),
count_(flatbuffers::EndianScalar(_count)),
prefix_(flatbuffers::EndianScalar(_prefix)),
padding0__(0),
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_);
}
};
FLATBUFFERS_STRUCT_END(Foo, 16);
FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(8) Bar FLATBUFFERS_FINAL_CLASS {
private:
benchmarks_flatbuffers::Foo parent_;
int32_t time_;
float ratio_;
uint16_t size_;
int16_t padding0__; int32_t padding1__;
public:
Bar()
: 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)
: parent_(_parent),
time_(flatbuffers::EndianScalar(_time)),
ratio_(flatbuffers::EndianScalar(_ratio)),
size_(flatbuffers::EndianScalar(_size)),
padding0__(0),
padding1__(0) {
(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_);
}
};
FLATBUFFERS_STRUCT_END(Bar, 32);
struct FooBar FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
typedef FooBarBuilder Builder;
enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE {
VT_SIBLING = 4,
VT_NAME = 6,
VT_RATING = 8,
VT_POSTFIX = 10
};
const benchmarks_flatbuffers::Bar *sibling() const {
return GetStruct<const benchmarks_flatbuffers::Bar *>(VT_SIBLING);
}
const flatbuffers::String *name() const {
return GetPointer<const flatbuffers::String *>(VT_NAME);
}
double rating() const {
return GetField<double>(VT_RATING, 0.0);
}
uint8_t postfix() const {
return GetField<uint8_t>(VT_POSTFIX, 0);
}
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
VerifyField<benchmarks_flatbuffers::Bar>(verifier, VT_SIBLING, 8) &&
VerifyOffset(verifier, VT_NAME) &&
verifier.VerifyString(name()) &&
VerifyField<double>(verifier, VT_RATING, 8) &&
VerifyField<uint8_t>(verifier, VT_POSTFIX, 1) &&
verifier.EndTable();
}
};
struct FooBarBuilder {
typedef FooBar Table;
flatbuffers::FlatBufferBuilder &fbb_;
flatbuffers::uoffset_t start_;
void add_sibling(const benchmarks_flatbuffers::Bar *sibling) {
fbb_.AddStruct(FooBar::VT_SIBLING, sibling);
}
void add_name(flatbuffers::Offset<flatbuffers::String> name) {
fbb_.AddOffset(FooBar::VT_NAME, name);
}
void add_rating(double rating) {
fbb_.AddElement<double>(FooBar::VT_RATING, rating, 0.0);
}
void add_postfix(uint8_t postfix) {
fbb_.AddElement<uint8_t>(FooBar::VT_POSTFIX, postfix, 0);
}
explicit FooBarBuilder(flatbuffers::FlatBufferBuilder &_fbb)
: fbb_(_fbb) {
start_ = fbb_.StartTable();
}
flatbuffers::Offset<FooBar> Finish() {
const auto end = fbb_.EndTable(start_);
auto o = flatbuffers::Offset<FooBar>(end);
return o;
}
};
inline flatbuffers::Offset<FooBar> CreateFooBar(
flatbuffers::FlatBufferBuilder &_fbb,
const benchmarks_flatbuffers::Bar *sibling = nullptr,
flatbuffers::Offset<flatbuffers::String> name = 0,
double rating = 0.0,
uint8_t postfix = 0) {
FooBarBuilder builder_(_fbb);
builder_.add_rating(rating);
builder_.add_name(name);
builder_.add_sibling(sibling);
builder_.add_postfix(postfix);
return builder_.Finish();
}
inline flatbuffers::Offset<FooBar> CreateFooBarDirect(
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);
}
struct FooBarContainer FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
typedef FooBarContainerBuilder Builder;
enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE {
VT_LIST = 4,
VT_INITIALIZED = 6,
VT_FRUIT = 8,
VT_LOCATION = 10
};
const flatbuffers::Vector<flatbuffers::Offset<benchmarks_flatbuffers::FooBar>> *list() const {
return GetPointer<const flatbuffers::Vector<flatbuffers::Offset<benchmarks_flatbuffers::FooBar>> *>(VT_LIST);
}
bool initialized() const {
return GetField<uint8_t>(VT_INITIALIZED, 0) != 0;
}
benchmarks_flatbuffers::Enum fruit() const {
return static_cast<benchmarks_flatbuffers::Enum>(GetField<int16_t>(VT_FRUIT, 0));
}
const flatbuffers::String *location() const {
return GetPointer<const flatbuffers::String *>(VT_LOCATION);
}
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
VerifyOffset(verifier, VT_LIST) &&
verifier.VerifyVector(list()) &&
verifier.VerifyVectorOfTables(list()) &&
VerifyField<uint8_t>(verifier, VT_INITIALIZED, 1) &&
VerifyField<int16_t>(verifier, VT_FRUIT, 2) &&
VerifyOffset(verifier, VT_LOCATION) &&
verifier.VerifyString(location()) &&
verifier.EndTable();
}
};
struct FooBarContainerBuilder {
typedef FooBarContainer Table;
flatbuffers::FlatBufferBuilder &fbb_;
flatbuffers::uoffset_t start_;
void add_list(flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<benchmarks_flatbuffers::FooBar>>> list) {
fbb_.AddOffset(FooBarContainer::VT_LIST, list);
}
void add_initialized(bool initialized) {
fbb_.AddElement<uint8_t>(FooBarContainer::VT_INITIALIZED, static_cast<uint8_t>(initialized), 0);
}
void add_fruit(benchmarks_flatbuffers::Enum fruit) {
fbb_.AddElement<int16_t>(FooBarContainer::VT_FRUIT, static_cast<int16_t>(fruit), 0);
}
void add_location(flatbuffers::Offset<flatbuffers::String> location) {
fbb_.AddOffset(FooBarContainer::VT_LOCATION, location);
}
explicit FooBarContainerBuilder(flatbuffers::FlatBufferBuilder &_fbb)
: fbb_(_fbb) {
start_ = fbb_.StartTable();
}
flatbuffers::Offset<FooBarContainer> Finish() {
const auto end = fbb_.EndTable(start_);
auto o = flatbuffers::Offset<FooBarContainer>(end);
return o;
}
};
inline flatbuffers::Offset<FooBarContainer> CreateFooBarContainer(
flatbuffers::FlatBufferBuilder &_fbb,
flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<benchmarks_flatbuffers::FooBar>>> list = 0,
bool initialized = false,
benchmarks_flatbuffers::Enum fruit = benchmarks_flatbuffers::Enum_Apples,
flatbuffers::Offset<flatbuffers::String> location = 0) {
FooBarContainerBuilder builder_(_fbb);
builder_.add_location(location);
builder_.add_list(list);
builder_.add_fruit(fruit);
builder_.add_initialized(initialized);
return builder_.Finish();
}
inline flatbuffers::Offset<FooBarContainer> CreateFooBarContainerDirect(
flatbuffers::FlatBufferBuilder &_fbb,
const std::vector<flatbuffers::Offset<benchmarks_flatbuffers::FooBar>> *list = nullptr,
bool initialized = false,
benchmarks_flatbuffers::Enum fruit = benchmarks_flatbuffers::Enum_Apples,
const char *location = nullptr) {
auto list__ = list ? _fbb.CreateVector<flatbuffers::Offset<benchmarks_flatbuffers::FooBar>>(*list) : 0;
auto location__ = location ? _fbb.CreateString(location) : 0;
return benchmarks_flatbuffers::CreateFooBarContainer(
_fbb,
list__,
initialized,
fruit,
location__);
}
inline const benchmarks_flatbuffers::FooBarContainer *GetFooBarContainer(const void *buf) {
return flatbuffers::GetRoot<benchmarks_flatbuffers::FooBarContainer>(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<benchmarks_flatbuffers::FooBarContainer>(nullptr);
}
inline bool VerifySizePrefixedFooBarContainerBuffer(
flatbuffers::Verifier &verifier) {
return verifier.VerifySizePrefixedBuffer<benchmarks_flatbuffers::FooBarContainer>(nullptr);
}
inline void FinishFooBarContainerBuffer(
flatbuffers::FlatBufferBuilder &fbb,
flatbuffers::Offset<benchmarks_flatbuffers::FooBarContainer> root) {
fbb.Finish(root);
}
inline void FinishSizePrefixedFooBarContainerBuffer(
flatbuffers::FlatBufferBuilder &fbb,
flatbuffers::Offset<benchmarks_flatbuffers::FooBarContainer> root) {
fbb.FinishSizePrefixed(root);
}
} // namespace benchmarks_flatbuffers
#endif // FLATBUFFERS_GENERATED_BENCH_BENCHMARKS_FLATBUFFERS_H_

View File

@ -0,0 +1,80 @@
#include "benchmarks/cpp/flatbuffers/fb_bench.h"
#include <cstdint>
#include <memory>
#include "benchmarks/cpp/bench.h"
#include "benchmarks/cpp/flatbuffers/bench_generated.h"
#include "flatbuffers/flatbuffers.h"
using namespace flatbuffers;
using namespace benchmarks_flatbuffers;
namespace {
struct FlatBufferBench : Bench {
explicit FlatBufferBench(int64_t initial_size, Allocator *allocator)
: fbb(initial_size, allocator, false) {}
uint8_t *Encode(void *, int64_t &len) override {
fbb.Clear();
const int kVectorLength = 3;
Offset<FooBar> vec[kVectorLength];
for (int i = 0; i < kVectorLength; ++i) {
Foo foo(0xABADCAFEABADCAFE + i, 10000 + i, '@' + i, 1000000 + i);
Bar bar(foo, 123456 + i, 3.14159f + i, 10000 + i);
auto name = fbb.CreateString("Hello, World!");
auto foobar =
CreateFooBar(fbb, &bar, name, 3.1415432432445543543 + i, '!' + i);
vec[i] = foobar;
}
auto location = fbb.CreateString("http://google.com/flatbuffers/");
auto foobarvec = fbb.CreateVector(vec, kVectorLength);
auto foobarcontainer =
CreateFooBarContainer(fbb, foobarvec, true, Enum_Bananas, location);
fbb.Finish(foobarcontainer);
len = fbb.GetSize();
return fbb.GetBufferPointer();
}
int64_t Use(void *decoded) override {
sum = 0;
auto foobarcontainer = GetFooBarContainer(decoded);
sum = 0;
Add(foobarcontainer->initialized());
Add(foobarcontainer->location()->Length());
Add(foobarcontainer->fruit());
for (unsigned int i = 0; i < foobarcontainer->list()->Length(); i++) {
auto foobar = foobarcontainer->list()->Get(i);
Add(foobar->name()->Length());
Add(foobar->postfix());
Add(static_cast<int64_t>(foobar->rating()));
auto bar = foobar->sibling();
Add(static_cast<int64_t>(bar->ratio()));
Add(bar->size());
Add(bar->time());
auto &foo = bar->parent();
Add(foo.count());
Add(foo.id());
Add(foo.length());
Add(foo.prefix());
}
return sum;
}
void *Decode(void *buffer, int64_t) override { return buffer; }
void Dealloc(void *) override {};
FlatBufferBuilder fbb;
};
} // namespace
std::unique_ptr<Bench> NewFlatBuffersBench(int64_t initial_size,
Allocator *allocator) {
return std::unique_ptr<FlatBufferBench>(
new FlatBufferBench(initial_size, allocator));
}

View File

@ -0,0 +1,23 @@
#ifndef BENCHMARKS_CPP_FLATBUFFERS_FB_BENCH_H_
#define BENCHMARKS_CPP_FLATBUFFERS_FB_BENCH_H_
#include <cstdint>
#include <memory>
#include "benchmarks/cpp/bench.h"
#include "include/flatbuffers/flatbuffers.h"
struct StaticAllocator : public flatbuffers::Allocator {
explicit StaticAllocator(uint8_t *buffer) : buffer_(buffer) {}
uint8_t *allocate(size_t) override { return buffer_; }
void deallocate(uint8_t *, size_t) override {}
uint8_t *buffer_;
};
std::unique_ptr<Bench> NewFlatBuffersBench(
int64_t initial_size = 1024, flatbuffers::Allocator *allocator = nullptr);
#endif // BENCHMARKS_CPP_FLATBUFFERS_FB_BENCH_H_

View File

@ -0,0 +1,109 @@
#include "benchmarks/cpp/raw/raw_bench.h"
#include <cstdint>
#include <cstring>
#include <memory>
#include "benchmarks/cpp/bench.h"
namespace {
const int64_t kStringLength = 32;
const int64_t kVectorLength = 3;
enum Enum { Apples, Pears, Bananas };
struct Foo {
int64_t id;
short count;
char prefix;
int length;
};
struct Bar {
Foo parent;
int time;
float ratio;
unsigned short size;
};
struct FooBar {
Bar sibling;
// We have to stick this in, otherwise strlen() will make it slower than
// FlatBuffers:
int name_len;
char name[kStringLength];
double rating;
unsigned char postfix;
};
struct FooBarContainer {
FooBar list[kVectorLength]; // 3 copies of the above
bool initialized;
Enum fruit;
int location_len;
char location[kStringLength];
};
struct RawBench : Bench {
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;
fbc->initialized = true;
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];
foobar.rating = 3.1415432432445543543 + i;
foobar.postfix = '!' + i;
strcpy(foobar.name, "Hello, World!");
foobar.name_len = (int)strlen(foobar.name);
auto &bar = foobar.sibling;
bar.ratio = 3.14159f + i;
bar.size = 10000 + i;
bar.time = 123456 + i;
auto &foo = bar.parent;
foo.id = 0xABADCAFEABADCAFE + i;
foo.count = 10000 + i;
foo.length = 1000000 + i;
foo.prefix = '@' + i;
}
len = sizeof(FooBarContainer);
return reinterpret_cast<uint8_t *>(fbc);
};
int64_t Use(void *decoded) override {
auto foobarcontainer = reinterpret_cast<FooBarContainer *>(decoded);
sum = 0;
Add(foobarcontainer->initialized);
Add(foobarcontainer->location_len);
Add(foobarcontainer->fruit);
for (unsigned int i = 0; i < kVectorLength; i++) {
auto foobar = &foobarcontainer->list[i];
Add(foobar->name_len);
Add(foobar->postfix);
Add(static_cast<int64_t>(foobar->rating));
auto bar = &foobar->sibling;
Add(static_cast<int64_t>(bar->ratio));
Add(bar->size);
Add(bar->time);
auto &foo = bar->parent;
Add(foo.count);
Add(foo.id);
Add(foo.length);
Add(foo.prefix);
}
return sum;
}
void *Decode(void *buf, int64_t) override { return buf; }
void Dealloc(void *) override{};
};
} // namespace
std::unique_ptr<Bench> NewRawBench() {
return std::unique_ptr<RawBench>(new RawBench());
}

View File

@ -0,0 +1,10 @@
#ifndef BENCHMARKS_CPP_RAW_RAW_BENCH_H_
#define BENCHMARKS_CPP_RAW_RAW_BENCH_H_
#include <memory>
#include "benchmarks/cpp/bench.h"
std::unique_ptr<Bench> NewRawBench();
#endif // BENCHMARKS_CPP_RAW_RAW_BENCH_H_

View File

@ -0,0 +1,181 @@
/*
* Copyright 2023 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 CoreFoundation
import FlatBuffers
@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 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: 1_024_000_000))
}
}
Benchmark("Clearing 1GB", configuration: singleConfiguration) { benchmark in
var fb = FlatBufferBuilder(initialSize: 1_024_000_000)
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("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))
fb.finish(offset: root)
}
}

View File

@ -0,0 +1,42 @@
// swift-tools-version:5.8
/*
* Copyright 2020 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 PackageDescription
let package = Package(
name: "benchmarks",
platforms: [
.macOS(.v13),
],
dependencies: [
.package(path: "../.."),
.package(
url: "https://github.com/ordo-one/package-benchmark",
from: "1.12.0"),
],
targets: [
.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"),
]),
])

View File

@ -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`

284
build_defs.bzl Normal file
View File

@ -0,0 +1,284 @@
# Description:
# BUILD rules for generating flatbuffer files in various languages.
"""
Rules for building C++ flatbuffers with Bazel.
"""
load("@rules_cc//cc:defs.bzl", "cc_library")
TRUE_FLATC_PATH = "@com_github_google_flatbuffers//:flatc"
DEFAULT_INCLUDE_PATHS = [
"./",
"$(GENDIR)",
"$(BINDIR)",
"$(execpath @com_github_google_flatbuffers//:flatc).runfiles/com_github_google_flatbuffers",
]
def default_include_paths(flatc_path):
return [
"./",
"$(GENDIR)",
"$(BINDIR)",
"$(execpath %s).runfiles/com_github_google_flatbuffers" % (flatc_path),
]
DEFAULT_FLATC_ARGS = [
"--gen-object-api",
"--gen-compare",
"--no-includes",
"--gen-mutable",
"--reflect-names",
"--cpp-ptr-type flatbuffers::unique_ptr",
]
def flatbuffer_library_public(
name,
srcs,
outs,
language_flag,
out_prefix = "",
includes = [],
include_paths = None,
flatc_args = DEFAULT_FLATC_ARGS,
reflection_name = "",
reflection_visibility = None,
compatible_with = None,
restricted_to = None,
target_compatible_with = None,
flatc_path = "@com_github_google_flatbuffers//:flatc",
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:
name: Rule name.
srcs: Source .fbs files. Sent in order to the compiler.
outs: Output files from flatc.
language_flag: Target language flag. One of [-c, -j, -js].
out_prefix: Prepend this path to the front of all generated files except on
single source targets. Usually is a directory name.
includes: Optional, list of filegroups of schemas that the srcs depend on.
include_paths: Optional, list of paths the includes files can be found in.
flatc_args: Optional, list of additional arguments to pass to flatc.
reflection_name: Optional, if set this will generate the flatbuffer
reflection binaries for the schemas.
reflection_visibility: The visibility of the generated reflection Fileset.
output_to_bindir: Passed to genrule for output to bin directory.
compatible_with: Optional, The list of environments this rule can be
built for, in addition to default-supported environments.
restricted_to: Optional, The list of environments this rule can be built
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.
"""
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.
output_directory = (
("-o $(@D)/%s" % (out_prefix)) if len(srcs) > 1 else ("-o $(@D)")
)
genrule_cmd = " ".join([
"SRCS=($(SRCS));",
"for f in $${SRCS[@]:0:%s}; do" % len(srcs),
"OUTPUT_FILE=\"$(OUTS)\" %s $(location %s)" % (extra_env, flatc_path),
" ".join(include_paths_cmd),
" ".join(flatc_args),
language_flag,
output_directory,
"$$f;",
"done",
])
native.genrule(
name = name,
srcs = srcs + includes,
outs = outs,
output_to_bindir = output_to_bindir,
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)" % (TRUE_FLATC_PATH),
"-b --schema",
" ".join(flatc_args),
" ".join(reflection_include_paths_cmd),
language_flag,
output_directory,
"$$f;",
"done",
])
reflection_outs = [
(out_prefix + "%s.bfbs") % (s.replace(".fbs", "").split("/")[-1])
for s in srcs
]
native.genrule(
name = "%s_srcs" % reflection_name,
srcs = srcs + includes,
outs = reflection_outs,
output_to_bindir = output_to_bindir,
tools = [TRUE_FLATC_PATH],
compatible_with = compatible_with,
restricted_to = restricted_to,
target_compatible_with = target_compatible_with,
cmd = reflection_genrule_cmd,
message = "Generating flatbuffer reflection binary for %s:" % (name),
visibility = reflection_visibility,
)
native.filegroup(
name = "%s_out" % reflection_name,
srcs = reflection_outs,
visibility = reflection_visibility,
compatible_with = compatible_with,
restricted_to = restricted_to,
)
def flatbuffer_cc_library(
name,
srcs,
srcs_filegroup_name = "",
outs = [],
out_prefix = "",
deps = [],
includes = [],
include_paths = None,
cc_include_paths = [],
flatc_args = DEFAULT_FLATC_ARGS,
visibility = None,
compatible_with = None,
restricted_to = None,
target_compatible_with = None,
srcs_filegroup_visibility = None,
gen_reflections = False):
"""A cc_library with the generated reader/writers for the given flatbuffer definitions.
Args:
name: Rule name.
srcs: Source .fbs files. Sent in order to the compiler.
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
alongside includes.
includes: Optional, list of filegroups of schemas that the srcs depend on.
Use of this is discouraged, and may be deprecated.
include_paths: Optional, list of paths the includes files can be found in.
cc_include_paths: Optional, list of paths to add to the cc_library includes attribute.
flatc_args: Optional list of additional arguments to pass to flatc
(e.g. --gen-mutable).
visibility: The visibility of the generated cc_library. By default, use the
default visibility of the project.
srcs_filegroup_visibility: The visibility of the generated srcs filegroup.
By default, use the value of the visibility parameter above.
gen_reflections: Optional, if true this will generate the flatbuffer
reflection binaries for the schemas.
compatible_with: Optional, The list of environments this rule can be built
for, in addition to default-supported environments.
restricted_to: Optional, The list of environments this rule can be built
for, instead of default-supported environments.
target_compatible_with: Optional, The list of target platform constraints
to use.
This produces:
filegroup([name]_srcs): all generated .h files.
filegroup(srcs_filegroup_name if specified, or [name]_includes if not):
Other flatbuffer_cc_library's can pass this in for their `includes`
parameter, if they depend on the schemas in this 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
]
if deps and includes:
# There is no inherent reason we couldn't support both, but this discourages
# use of includes without good reason.
fail("Cannot specify both deps and include in flatbuffer_cc_library.")
if deps:
includes = [d + "_includes" for d in deps]
reflection_name = "%s_reflection" % name if gen_reflections else ""
srcs_lib = "%s_srcs" % (name)
flatbuffer_library_public(
name = srcs_lib,
srcs = srcs,
outs = outs + output_headers,
language_flag = "-c",
out_prefix = out_prefix,
includes = includes,
include_paths = include_paths,
flatc_args = flatc_args,
compatible_with = compatible_with,
restricted_to = restricted_to,
target_compatible_with = target_compatible_with,
reflection_name = reflection_name,
reflection_visibility = visibility,
)
cc_library(
name = name,
hdrs = [
":" + srcs_lib,
],
srcs = [
":" + srcs_lib,
],
features = [
"-parse_headers",
],
deps = [
"@com_github_google_flatbuffers//:runtime_cc",
"@com_github_google_flatbuffers//:flatbuffers",
] + deps,
includes = cc_include_paths,
compatible_with = compatible_with,
restricted_to = restricted_to,
target_compatible_with = target_compatible_with,
linkstatic = 1,
visibility = visibility,
)
# A filegroup for the `srcs`. That is, all the schema files for this
# Flatbuffer set.
native.filegroup(
name = srcs_filegroup_name if srcs_filegroup_name else "%s_includes" % (name),
srcs = srcs + includes,
compatible_with = compatible_with,
restricted_to = restricted_to,
visibility = srcs_filegroup_visibility if srcs_filegroup_visibility != None else visibility,
)

18
composer.json Normal file
View File

@ -0,0 +1,18 @@
{
"name": "google/flatbuffers",
"type": "library",
"description": "FlatBuffers for PHP",
"keywords": ["google", "flatbuffers", "serialization"],
"homepage": "https://github.com/google/flatbuffers",
"license": "Apache-2.0",
"require": {
"php": ">=5.4"
},
"require-dev": {
},
"autoload": {
"psr-4": {
"Google\\FlatBuffers\\": "php"
}
}
}

12
conan/CMakeLists.txt Normal file
View File

@ -0,0 +1,12 @@
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)

50
conan/build.py Normal file
View File

@ -0,0 +1,50 @@
#!/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()

View File

@ -0,0 +1,9 @@
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)

View File

@ -0,0 +1,21 @@
#!/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)

View File

@ -0,0 +1,35 @@
/*
* Copyright 2018 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.
*/
#include <cstdlib>
#include <iostream>
#include "flatbuffers/util.h"
// Test to validate Conan package generated
int main(int /*argc*/, const char * /*argv*/ []) {
const std::string filename("conanbuildinfo.cmake");
if (flatbuffers::FileExists(filename.c_str())) {
std::cout << "File " << filename << " exists.\n";
} else {
std::cout << "File " << filename << " does not exist.\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}

Some files were not shown because too many files have changed in this diff Show More