mirror of
https://github.com/google/flatbuffers.git
synced 2026-06-07 22:03:40 +00:00
Compare commits
279 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
06c5c7ed0b | ||
|
|
b190ce11b0 | ||
|
|
bf5d23230a | ||
|
|
ce382d6dd3 | ||
|
|
41d9add7ef | ||
|
|
6a87427540 | ||
|
|
694add668b | ||
|
|
7edf8c9084 | ||
|
|
b86387442e | ||
|
|
e2eb5ee670 | ||
|
|
994502b6dd | ||
|
|
fa41e83679 | ||
|
|
799cc8f7b9 | ||
|
|
b7eb441470 | ||
|
|
8d01c5859c | ||
|
|
237e8b71fe | ||
|
|
eeb8fd60d5 | ||
|
|
fef2ffc4d0 | ||
|
|
8367664f15 | ||
|
|
d6f06c33f7 | ||
|
|
627e8bf364 | ||
|
|
883c42b7db | ||
|
|
7aae0af305 | ||
|
|
b057aa917f | ||
|
|
f1b26ff7fb | ||
|
|
9610a666b1 | ||
|
|
1e0f75a647 | ||
|
|
82b75407a3 | ||
|
|
f7c511957f | ||
|
|
a66de58af9 | ||
|
|
a3508f36d5 | ||
|
|
137fec7164 | ||
|
|
214125e417 | ||
|
|
44a7dc9995 | ||
|
|
3cc2daa78f | ||
|
|
fa1174aa7b | ||
|
|
83d4e2a100 | ||
|
|
8a09f3fb0b | ||
|
|
9dbe819efd | ||
|
|
67c4149588 | ||
|
|
8b8c7dbdfc | ||
|
|
2ee20a5f3d | ||
|
|
4be605604e | ||
|
|
fc5d86f1e7 | ||
|
|
9dce287adb | ||
|
|
7798be3bb6 | ||
|
|
966362e074 | ||
|
|
a89c279ed6 | ||
|
|
a212b3c036 | ||
|
|
9230f600d7 | ||
|
|
c793621567 | ||
|
|
ee2ced236d | ||
|
|
468c00a3fe | ||
|
|
47c757f714 | ||
|
|
9a5ff89003 | ||
|
|
950444a343 | ||
|
|
30d76198c7 | ||
|
|
cce3a66f0d | ||
|
|
8d1cc6ac7d | ||
|
|
5b207639a1 | ||
|
|
359e0f9d66 | ||
|
|
ebbed05137 | ||
|
|
aa395e5a59 | ||
|
|
32328075d8 | ||
|
|
97e89c5acd | ||
|
|
5f6672be44 | ||
|
|
28e858c855 | ||
|
|
987bebe678 | ||
|
|
ec0129369c | ||
|
|
50dd385b30 | ||
|
|
da702cfd8f | ||
|
|
6e2791640e | ||
|
|
52fce5e532 | ||
|
|
b7f13cd8e8 | ||
|
|
e42985e5aa | ||
|
|
0a80646371 | ||
|
|
b9eea76a86 | ||
|
|
1b90300150 | ||
|
|
83a43fc797 | ||
|
|
5f01376027 | ||
|
|
9a1913a87a | ||
|
|
b4647beb8f | ||
|
|
d6060977ad | ||
|
|
987aa5b5ee | ||
|
|
42acdb63c3 | ||
|
|
0cc1aeb8ca | ||
|
|
ba6c671705 | ||
|
|
d2f33fc454 | ||
|
|
0d1b72cbc2 | ||
|
|
9fce2fbf2a | ||
|
|
a18ea40d6a | ||
|
|
090caa2809 | ||
|
|
49e1ea3335 | ||
|
|
11a1988705 | ||
|
|
967df08b1d | ||
|
|
9aa08a429e | ||
|
|
9e8c758f54 | ||
|
|
74a25536be | ||
|
|
12917af8a2 | ||
|
|
1ea2472f7a | ||
|
|
0fe13cb28c | ||
|
|
385dddc66a | ||
|
|
750dde7669 | ||
|
|
9917a168cd | ||
|
|
76d3cca19c | ||
|
|
c86e6d0e30 | ||
|
|
d34dc32c20 | ||
|
|
234d86c92a | ||
|
|
746c73b910 | ||
|
|
0bbfd4b2e3 | ||
|
|
7165219535 | ||
|
|
a45f564cf1 | ||
|
|
9d45a64036 | ||
|
|
ccfb4c20bf | ||
|
|
7bcd857b87 | ||
|
|
23c8ab34c1 | ||
|
|
70002dc5ca | ||
|
|
6e0e79f24f | ||
|
|
b856368d75 | ||
|
|
e37156a305 | ||
|
|
a10b0e5464 | ||
|
|
275b739944 | ||
|
|
9d1ce9a100 | ||
|
|
79afe6c3d2 | ||
|
|
c6dbb22300 | ||
|
|
18bacd3ea5 | ||
|
|
a2c913aec3 | ||
|
|
67b33b2942 | ||
|
|
7b5fd2bd05 | ||
|
|
7181d77700 | ||
|
|
7f663b1204 | ||
|
|
173ebb6944 | ||
|
|
d658239484 | ||
|
|
ab4bf59e8c | ||
|
|
eee44bbb26 | ||
|
|
a63fa51a15 | ||
|
|
2049e52101 | ||
|
|
832c618f5f | ||
|
|
14615699fa | ||
|
|
20aad0c41e | ||
|
|
f083b33f2a | ||
|
|
bf17df346e | ||
|
|
35281dedb5 | ||
|
|
c9651b7420 | ||
|
|
26c3b3adab | ||
|
|
da6e1b9856 | ||
|
|
ad27d751e3 | ||
|
|
0aab623cb1 | ||
|
|
6a446bdd83 | ||
|
|
21fb5cbbc9 | ||
|
|
0da6f94867 | ||
|
|
59e9713081 | ||
|
|
40866a8927 | ||
|
|
b71d968fad | ||
|
|
fac0d7be02 | ||
|
|
6c5603fd98 | ||
|
|
2d21853a7e | ||
|
|
fec1a8d015 | ||
|
|
7fd8576233 | ||
|
|
a4cb1599d8 | ||
|
|
ae4ce72651 | ||
|
|
e2be0c0b06 | ||
|
|
2ad408697f | ||
|
|
4213d91054 | ||
|
|
5a13f622cf | ||
|
|
23a7e4e0b0 | ||
|
|
eeb49c2757 | ||
|
|
824763b316 | ||
|
|
d3aeee32bb | ||
|
|
0bceba24db | ||
|
|
b8c77d4041 | ||
|
|
8468eab83b | ||
|
|
2b2e8d4aec | ||
|
|
b80b32bfaf | ||
|
|
e5f331db99 | ||
|
|
2f84c60385 | ||
|
|
d648396515 | ||
|
|
777e78d8dd | ||
|
|
4016c549d3 | ||
|
|
40827b21b2 | ||
|
|
65a10b6e32 | ||
|
|
8db2fef3f7 | ||
|
|
9ed1323044 | ||
|
|
1a4c405662 | ||
|
|
318594e4b4 | ||
|
|
3d903302c3 | ||
|
|
c9571d9897 | ||
|
|
3694b830a2 | ||
|
|
0471fa807c | ||
|
|
914344ea9b | ||
|
|
b40266c56f | ||
|
|
8a9303d464 | ||
|
|
30c4bf47f9 | ||
|
|
46ce45601b | ||
|
|
433312c55a | ||
|
|
9c52ec3744 | ||
|
|
70e2f49bff | ||
|
|
5ac0367ed3 | ||
|
|
5d101afb52 | ||
|
|
06f4af11b6 | ||
|
|
57e338f819 | ||
|
|
615616cb55 | ||
|
|
3413c33004 | ||
|
|
69f5660a44 | ||
|
|
d5add9fca5 | ||
|
|
15df50eb7f | ||
|
|
a94132a45f | ||
|
|
48befb6bef | ||
|
|
b300691336 | ||
|
|
faadbc10ea | ||
|
|
ed6ae8d322 | ||
|
|
e910bddbcc | ||
|
|
c85fb690f4 | ||
|
|
c1daa6ba0c | ||
|
|
4c71c7b023 | ||
|
|
f5664d33fb | ||
|
|
39c8a19ce2 | ||
|
|
826193ff68 | ||
|
|
fd0d1ed929 | ||
|
|
424988f308 | ||
|
|
b2550dbaa9 | ||
|
|
a2b238960f | ||
|
|
619b784374 | ||
|
|
68a7661546 | ||
|
|
7dac9961f0 | ||
|
|
c65c389c6d | ||
|
|
6446dcf3d6 | ||
|
|
e090d8da17 | ||
|
|
bc901436db | ||
|
|
240be9b5ae | ||
|
|
bc366a7f9e | ||
|
|
14b19d446f | ||
|
|
9e6f17b94d | ||
|
|
c3801ad375 | ||
|
|
4f3b24db09 | ||
|
|
1d294a31b8 | ||
|
|
dd8fccfb1b | ||
|
|
7089c9ecdd | ||
|
|
43203984f7 | ||
|
|
5993338ee3 | ||
|
|
19920db39f | ||
|
|
dbbaeac85c | ||
|
|
028f0fde62 | ||
|
|
87343631b9 | ||
|
|
1fbfaf5c5e | ||
|
|
4421375bb6 | ||
|
|
162ad7a37e | ||
|
|
a0a6c3f8c6 | ||
|
|
a2d38fbb98 | ||
|
|
9ef1524d3f | ||
|
|
0c9de0352a | ||
|
|
a783bc9267 | ||
|
|
aff818cebf | ||
|
|
d7b75417fc | ||
|
|
a42e898979 | ||
|
|
96cc2f3ee3 | ||
|
|
3250a1f8dd | ||
|
|
ace4a37f22 | ||
|
|
f28c2b2936 | ||
|
|
96f3cf690f | ||
|
|
b3edfdbfb7 | ||
|
|
b8aaccee82 | ||
|
|
2dc8ae7742 | ||
|
|
5b0d491127 | ||
|
|
d8b7041d7e | ||
|
|
5a0c3366c3 | ||
|
|
f8148b8dad | ||
|
|
a22b1b6267 | ||
|
|
4264daadd2 | ||
|
|
3cbc120a08 | ||
|
|
8dcd2682c7 | ||
|
|
b78002ff3e | ||
|
|
c555ee8fac | ||
|
|
b92bb0584d | ||
|
|
956d11569e | ||
|
|
e367ca32ad | ||
|
|
705f27f6ee | ||
|
|
5fc87f4c4b | ||
|
|
11749095a1 |
@@ -2,11 +2,29 @@
|
|||||||
buildifier: latest
|
buildifier: latest
|
||||||
platforms:
|
platforms:
|
||||||
ubuntu1804:
|
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:
|
build_targets:
|
||||||
- "//..."
|
- "//..."
|
||||||
test_targets:
|
test_targets:
|
||||||
- "//..."
|
- "//..."
|
||||||
ubuntu2004:
|
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:
|
build_targets:
|
||||||
- "//..."
|
- "//..."
|
||||||
test_targets:
|
test_targets:
|
||||||
|
|||||||
2
.github/labeler.yml
vendored
2
.github/labeler.yml
vendored
@@ -86,11 +86,9 @@ documentation:
|
|||||||
|
|
||||||
CI:
|
CI:
|
||||||
- '.github/**/*'
|
- '.github/**/*'
|
||||||
- '.appveyor/**/*'
|
|
||||||
- '.travis/**/*'
|
- '.travis/**/*'
|
||||||
- '.bazelci/**/*'
|
- '.bazelci/**/*'
|
||||||
- .travis.yml
|
- .travis.yml
|
||||||
- appveyor.yml
|
|
||||||
|
|
||||||
grpc:
|
grpc:
|
||||||
- grpc/**/*
|
- grpc/**/*
|
||||||
|
|||||||
342
.github/workflows/build.yml
vendored
342
.github/workflows/build.yml
vendored
@@ -1,7 +1,12 @@
|
|||||||
name: CI
|
name: CI
|
||||||
|
permissions: read-all
|
||||||
|
|
||||||
on:
|
on:
|
||||||
|
# For manual tests.
|
||||||
|
workflow_dispatch:
|
||||||
push:
|
push:
|
||||||
|
tags:
|
||||||
|
- "*" # new tag version, like `0.8.4` or else
|
||||||
branches:
|
branches:
|
||||||
- master
|
- master
|
||||||
pull_request:
|
pull_request:
|
||||||
@@ -10,57 +15,147 @@ on:
|
|||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build-linux:
|
build-linux:
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
outputs:
|
||||||
|
digests-gcc: ${{ steps.hash-gcc.outputs.hashes }}
|
||||||
|
digests-clang: ${{ steps.hash-clang.outputs.hashes }}
|
||||||
name: Build Linux
|
name: Build Linux
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
strategy:
|
strategy:
|
||||||
matrix:
|
matrix:
|
||||||
cxx: [g++-10, clang++-12]
|
cxx: [g++-10, clang++-12]
|
||||||
|
fail-fast: false
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v1
|
- uses: actions/checkout@v2
|
||||||
- name: cmake
|
- name: cmake
|
||||||
run: CXX=${{ matrix.cxx }} cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release .
|
run: CXX=${{ matrix.cxx }} cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_STRICT_MODE=ON .
|
||||||
- name: build
|
- name: build
|
||||||
run: make -j4
|
run: make -j
|
||||||
- name: test
|
- name: test
|
||||||
run: ./flattests
|
run: ./flattests
|
||||||
- name: make flatc executable
|
- name: make flatc executable
|
||||||
run: |
|
run: |
|
||||||
chmod +x flatc
|
chmod +x flatc
|
||||||
./flatc --version
|
./flatc --version
|
||||||
|
- name: flatc tests
|
||||||
|
run: python3 tests/flatc/main.py
|
||||||
- name: upload build artifacts
|
- name: upload build artifacts
|
||||||
uses: actions/upload-artifact@v1
|
uses: actions/upload-artifact@v1
|
||||||
with:
|
with:
|
||||||
name: Linux flatc binary ${{ matrix.cxx }}
|
name: Linux flatc binary ${{ matrix.cxx }}
|
||||||
path: flatc
|
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++-12' && startsWith(github.ref, 'refs/tags/')
|
||||||
|
id: hash-clang
|
||||||
|
run: echo "::set-output name=hashes::$(sha256sum Linux.flatc.binary.${{ matrix.cxx }}.zip | base64 -w0)"
|
||||||
|
- name: Generate SLSA subjects - gcc
|
||||||
|
if: matrix.cxx == 'g++-10' && startsWith(github.ref, 'refs/tags/')
|
||||||
|
id: hash-gcc
|
||||||
|
run: echo "::set-output name=hashes::$(sha256sum Linux.flatc.binary.${{ matrix.cxx }}.zip | base64 -w0)"
|
||||||
|
|
||||||
build-windows:
|
build-linux-cpp-std:
|
||||||
name: Build Windows 2019
|
name: Build Linux C++
|
||||||
runs-on: windows-latest
|
runs-on: ubuntu-latest
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
std: [11, 14, 17, 20, 23]
|
||||||
|
cxx: [g++-10, clang++-12]
|
||||||
|
exclude:
|
||||||
|
# GCC 10.3.0 doesn't support std 23
|
||||||
|
- cxx: g++-10
|
||||||
|
std: 23
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v1
|
- uses: actions/checkout@v2
|
||||||
|
- name: cmake
|
||||||
|
run: >
|
||||||
|
CXX=${{ matrix.cxx }} cmake -G "Unix Makefiles"
|
||||||
|
-DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_STRICT_MODE=ON
|
||||||
|
-DFLATBUFFERS_CPP_STD=${{ matrix.std }}
|
||||||
|
- name: build
|
||||||
|
run: make -j
|
||||||
|
- name: test
|
||||||
|
run: ./flattests
|
||||||
|
|
||||||
|
build-windows-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@v2
|
||||||
- name: Add msbuild to PATH
|
- name: Add msbuild to PATH
|
||||||
uses: microsoft/setup-msbuild@v1.1
|
uses: microsoft/setup-msbuild@v1.1
|
||||||
- name: cmake
|
- name: cmake
|
||||||
run: cmake -G "Visual Studio 16 2019" -A x64 -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_BUILD_CPP17=ON .
|
run: >
|
||||||
|
cmake -G "Visual Studio 16 2019" -A x64 -DCMAKE_BUILD_TYPE=Release
|
||||||
|
-DFLATBUFFERS_STRICT_MODE=ON
|
||||||
|
-DFLATBUFFERS_CPP_STD=${{ matrix.std }}
|
||||||
- name: build
|
- name: build
|
||||||
run: msbuild.exe FlatBuffers.sln /p:Configuration=Release /p:Platform=x64
|
run: msbuild.exe FlatBuffers.sln /p:Configuration=Release /p:Platform=x64
|
||||||
- name: test
|
- name: test
|
||||||
run: Release\flattests.exe
|
run: Release\flattests.exe
|
||||||
|
|
||||||
|
build-windows:
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
outputs:
|
||||||
|
digests: ${{ steps.hash.outputs.hashes }}
|
||||||
|
name: Build Windows 2019
|
||||||
|
runs-on: windows-2019
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v2
|
||||||
|
- name: Add msbuild to PATH
|
||||||
|
uses: microsoft/setup-msbuild@v1.1
|
||||||
|
- name: cmake
|
||||||
|
run: cmake -G "Visual Studio 16 2019" -A x64 -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_BUILD_CPP17=ON -DFLATBUFFERS_STRICT_MODE=ON .
|
||||||
|
- name: build
|
||||||
|
run: msbuild.exe FlatBuffers.sln /p:Configuration=Release /p:Platform=x64
|
||||||
|
- name: test
|
||||||
|
run: Release\flattests.exe
|
||||||
|
- name: flatc tests
|
||||||
|
run: python3 tests/flatc/main.py --flatc Release\flatc.exe
|
||||||
- name: upload build artifacts
|
- name: upload build artifacts
|
||||||
uses: actions/upload-artifact@v1
|
uses: actions/upload-artifact@v1
|
||||||
with:
|
with:
|
||||||
name: Windows flatc binary
|
name: Windows flatc binary
|
||||||
path: Release\flatc.exe
|
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 "::set-output name=hashes::$(sha256sum Windows.flatc.binary.zip | base64 -w0)"
|
||||||
|
|
||||||
build-windows-2017:
|
build-windows-2017:
|
||||||
name: Build Windows 2017
|
name: Build Windows 2017
|
||||||
runs-on: windows-latest
|
runs-on: windows-2019
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v1
|
- uses: actions/checkout@v2
|
||||||
- name: Add msbuild to PATH
|
- name: Add msbuild to PATH
|
||||||
uses: microsoft/setup-msbuild@v1.1
|
uses: microsoft/setup-msbuild@v1.1
|
||||||
- name: cmake
|
- name: cmake
|
||||||
run: cmake -G "Visual Studio 16 2019" -A x64 -DCMAKE_BUILD_TYPE=Release .
|
run: cmake -G "Visual Studio 16 2019" -A x64 -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_STRICT_MODE=ON .
|
||||||
- name: build tool version 15 (VS 2017)
|
- name: build tool version 15 (VS 2017)
|
||||||
run: msbuild.exe FlatBuffers.sln /p:Configuration=Release /p:Platform=x64 /p:VisualStudioVersion=15.0
|
run: msbuild.exe FlatBuffers.sln /p:Configuration=Release /p:Platform=x64 /p:VisualStudioVersion=15.0
|
||||||
- name: test
|
- name: test
|
||||||
@@ -68,25 +163,103 @@ jobs:
|
|||||||
|
|
||||||
build-windows-2015:
|
build-windows-2015:
|
||||||
name: Build Windows 2015
|
name: Build Windows 2015
|
||||||
runs-on: windows-latest
|
runs-on: windows-2019
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v1
|
- uses: actions/checkout@v2
|
||||||
- name: Add msbuild to PATH
|
- name: Add msbuild to PATH
|
||||||
uses: microsoft/setup-msbuild@v1.1
|
uses: microsoft/setup-msbuild@v1.1
|
||||||
- name: cmake
|
- name: cmake
|
||||||
run: cmake -G "Visual Studio 14 2015" -A x64 -DCMAKE_BUILD_TYPE=Release .
|
run: cmake -G "Visual Studio 14 2015" -A x64 -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_STRICT_MODE=ON .
|
||||||
- name: build tool version 14 (VS 2015)
|
- name: build tool version 14 (VS 2015)
|
||||||
run: msbuild.exe FlatBuffers.sln /p:Configuration=Release /p:Platform=x64 /p:VisualStudioVersion=14.0
|
run: msbuild.exe FlatBuffers.sln /p:Configuration=Release /p:Platform=x64 /p:VisualStudioVersion=14.0
|
||||||
- name: test
|
- name: test
|
||||||
run: Release\flattests.exe
|
run: Release\flattests.exe
|
||||||
|
|
||||||
build-mac:
|
build-dotnet-windows:
|
||||||
name: Build Mac
|
name: Build .NET Windows
|
||||||
|
runs-on: windows-2019
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
configuration: [
|
||||||
|
'',
|
||||||
|
'-p:UnsafeByteBuffer=true',
|
||||||
|
# Fails two tests currently.
|
||||||
|
#'-p:EnableSpanT=true,UnsafeByteBuffer=true'
|
||||||
|
]
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v2
|
||||||
|
- name: Setup .NET Core SDK
|
||||||
|
uses: actions/setup-dotnet@v1.9.0
|
||||||
|
with:
|
||||||
|
dotnet-version: '3.1.x'
|
||||||
|
- name: Build
|
||||||
|
run: |
|
||||||
|
cd tests\FlatBuffers.Test
|
||||||
|
dotnet new sln --force --name FlatBuffers.Core.Test
|
||||||
|
dotnet sln FlatBuffers.Core.Test.sln add FlatBuffers.Core.Test.csproj
|
||||||
|
dotnet build -c Release ${{matrix.configuration}} -o out FlatBuffers.Core.Test.sln
|
||||||
|
- name: Run
|
||||||
|
run: |
|
||||||
|
cd tests\FlatBuffers.Test
|
||||||
|
out\FlatBuffers.Core.Test.exe
|
||||||
|
|
||||||
|
build-mac-intel:
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
outputs:
|
||||||
|
digests: ${{ steps.hash.outputs.hashes }}
|
||||||
|
name: Build Mac (for Intel)
|
||||||
runs-on: macos-latest
|
runs-on: macos-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v1
|
- uses: actions/checkout@v2
|
||||||
- name: cmake
|
- name: cmake
|
||||||
run: cmake -G "Xcode" -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_FLATC_EXECUTABLE=_build/Release/flatc .
|
run: cmake -G "Xcode" -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_FLATC_EXECUTABLE=_build/Release/flatc -DFLATBUFFERS_STRICT_MODE=ON .
|
||||||
|
- name: build
|
||||||
|
# NOTE: we need this _build dir to not have xcodebuild's default ./build dir clash with the BUILD file.
|
||||||
|
run: xcodebuild -toolchain clang -configuration Release -target flattests SYMROOT=$(PWD)/_build
|
||||||
|
- name: check that the binary is x86_64
|
||||||
|
run: |
|
||||||
|
info=$(file _build/Release/flatc)
|
||||||
|
echo $info
|
||||||
|
echo $info | grep "Mach-O 64-bit executable x86_64"
|
||||||
|
- name: test
|
||||||
|
run: _build/Release/flattests
|
||||||
|
- name: make flatc executable
|
||||||
|
run: |
|
||||||
|
chmod +x _build/Release/flatc
|
||||||
|
./_build/Release/flatc --version
|
||||||
|
- name: flatc tests
|
||||||
|
run: python3 tests/flatc/main.py --flatc ./_build/Release/flatc
|
||||||
|
- name: upload build artifacts
|
||||||
|
uses: actions/upload-artifact@v1
|
||||||
|
with:
|
||||||
|
name: Mac flatc binary
|
||||||
|
path: _build/Release/flatc
|
||||||
|
# Below if only for release.
|
||||||
|
- name: Zip file
|
||||||
|
if: startsWith(github.ref, 'refs/tags/')
|
||||||
|
run: mv _build/Release/flatc . && zip MacIntel.flatc.binary.zip flatc
|
||||||
|
- 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 "::set-output name=hashes::$(shasum -a 256 MacIntel.flatc.binary.zip | base64)"
|
||||||
|
|
||||||
|
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@v2
|
||||||
|
- name: cmake
|
||||||
|
run: cmake -G "Xcode" -DCMAKE_OSX_ARCHITECTURES="arm64;x86_64" -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_FLATC_EXECUTABLE=_build/Release/flatc -DFLATBUFFERS_STRICT_MODE=ON .
|
||||||
- name: build
|
- name: build
|
||||||
# NOTE: we need this _build dir to not have xcodebuild's default ./build dir clash with the BUILD file.
|
# NOTE: we need this _build dir to not have xcodebuild's default ./build dir clash with the BUILD file.
|
||||||
run: xcodebuild -toolchain clang -configuration Release -target flattests SYMROOT=$(PWD)/_build
|
run: xcodebuild -toolchain clang -configuration Release -target flattests SYMROOT=$(PWD)/_build
|
||||||
@@ -94,7 +267,7 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
info=$(file _build/Release/flatc)
|
info=$(file _build/Release/flatc)
|
||||||
echo $info
|
echo $info
|
||||||
echo $info | grep "universal binary with 2 architectures"
|
echo $info | grep "Mach-O universal binary with 2 architectures"
|
||||||
- name: test
|
- name: test
|
||||||
run: _build/Release/flattests
|
run: _build/Release/flattests
|
||||||
- name: make flatc executable
|
- name: make flatc executable
|
||||||
@@ -106,24 +279,37 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
name: Mac flatc binary
|
name: Mac flatc binary
|
||||||
path: _build/Release/flatc
|
path: _build/Release/flatc
|
||||||
|
# Below if only for release.
|
||||||
|
- name: Zip file
|
||||||
|
if: startsWith(github.ref, 'refs/tags/')
|
||||||
|
run: mv _build/Release/flatc . && zip Mac.flatc.binary.zip flatc
|
||||||
|
- 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 "::set-output name=hashes::$(shasum -a 256 Mac.flatc.binary.zip | base64)"
|
||||||
|
|
||||||
build-android:
|
build-android:
|
||||||
name: Build Android (on Linux)
|
name: Build Android (on Linux)
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v1
|
- uses: actions/checkout@v2
|
||||||
- name: set up JDK 1.8
|
- name: set up JDK 1.8
|
||||||
uses: actions/setup-java@v1
|
uses: actions/setup-java@v1
|
||||||
with:
|
with:
|
||||||
java-version: 1.8
|
java-version: 1.8
|
||||||
- name: set up flatc
|
- name: set up flatc
|
||||||
run: |
|
run: |
|
||||||
cmake -DFLATBUFFERS_BUILD_TESTS=OFF -DFLATBUFFERS_BUILD_FLATLIB=OFF -DFLATBUFFERS_BUILD_FLATHASH=OFF .
|
cmake -DFLATBUFFERS_BUILD_TESTS=OFF -DFLATBUFFERS_BUILD_FLATLIB=OFF -DFLATBUFFERS_BUILD_FLATHASH=OFF -DFLATBUFFERS_STRICT_MODE=ON .
|
||||||
make
|
make -j
|
||||||
echo "${PWD}" >> $GITHUB_PATH
|
echo "${PWD}" >> $GITHUB_PATH
|
||||||
- name: build
|
- name: build
|
||||||
working-directory: android
|
working-directory: android
|
||||||
run: bash ./gradlew clean build
|
run: gradle clean build
|
||||||
|
|
||||||
build-generator:
|
build-generator:
|
||||||
name: Check Generated Code
|
name: Check Generated Code
|
||||||
@@ -132,13 +318,13 @@ jobs:
|
|||||||
matrix:
|
matrix:
|
||||||
cxx: [g++-10, clang++-12]
|
cxx: [g++-10, clang++-12]
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v1
|
- uses: actions/checkout@v2
|
||||||
- name: cmake
|
- name: cmake
|
||||||
run: CXX=${{ matrix.cxx }} cmake -G "Unix Makefiles" -DFLATBUFFERS_BUILD_TESTS=OFF -DCMAKE_BUILD_TYPE=Release . && make -j4
|
run: CXX=${{ matrix.cxx }} cmake -G "Unix Makefiles" -DFLATBUFFERS_BUILD_TESTS=OFF -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_STRICT_MODE=ON . && make -j
|
||||||
- name: Generate
|
- name: Generate
|
||||||
run: scripts/check_generate_code.py
|
run: scripts/check_generate_code.py
|
||||||
- name: Generate gRPC
|
- name: Generate gRPC
|
||||||
run: bash scripts/check-grpc-generated-code.sh
|
run: scripts/check-grpc-generated-code.py
|
||||||
|
|
||||||
build-benchmarks:
|
build-benchmarks:
|
||||||
name: Build Benchmarks (on Linux)
|
name: Build Benchmarks (on Linux)
|
||||||
@@ -147,9 +333,9 @@ jobs:
|
|||||||
matrix:
|
matrix:
|
||||||
cxx: [g++-10]
|
cxx: [g++-10]
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v1
|
- uses: actions/checkout@v2
|
||||||
- name: cmake
|
- 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 . && make -j4
|
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
|
- name: Run benchmarks
|
||||||
run: ./flatbenchmark --benchmark_repetitions=5 --benchmark_display_aggregates_only=true --benchmark_out_format=console --benchmark_out=benchmarks/results_${{matrix.cxx}}
|
run: ./flatbenchmark --benchmark_repetitions=5 --benchmark_display_aggregates_only=true --benchmark_out_format=console --benchmark_out=benchmarks/results_${{matrix.cxx}}
|
||||||
- name: Upload benchmarks results
|
- name: Upload benchmarks results
|
||||||
@@ -162,7 +348,7 @@ jobs:
|
|||||||
name: Build Java
|
name: Build Java
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v1
|
- uses: actions/checkout@v2
|
||||||
- name: test
|
- name: test
|
||||||
working-directory: tests
|
working-directory: tests
|
||||||
run: bash JavaTest.sh
|
run: bash JavaTest.sh
|
||||||
@@ -173,13 +359,14 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v2
|
uses: actions/checkout@v2
|
||||||
|
- uses: gradle/wrapper-validation-action@v1
|
||||||
- uses: actions/setup-java@v2
|
- uses: actions/setup-java@v2
|
||||||
with:
|
with:
|
||||||
distribution: 'adopt-hotspot'
|
distribution: 'adopt-hotspot'
|
||||||
java-version: '11'
|
java-version: '11'
|
||||||
- name: Build
|
- name: Build
|
||||||
working-directory: kotlin
|
working-directory: kotlin
|
||||||
run: ./gradlew clean iosX64Test macosX64Test jsTest jsBrowserTest
|
run: ./gradlew clean iosX64Test macosX64Test
|
||||||
|
|
||||||
build-kotlin-linux:
|
build-kotlin-linux:
|
||||||
name: Build Kotlin Linux
|
name: Build Kotlin Linux
|
||||||
@@ -190,29 +377,20 @@ jobs:
|
|||||||
- uses: actions/setup-java@v2
|
- uses: actions/setup-java@v2
|
||||||
with:
|
with:
|
||||||
distribution: 'adopt-hotspot'
|
distribution: 'adopt-hotspot'
|
||||||
java-version: '8'
|
java-version: '11'
|
||||||
|
- uses: gradle/wrapper-validation-action@v1
|
||||||
- name: Build
|
- name: Build
|
||||||
working-directory: kotlin
|
working-directory: kotlin
|
||||||
run: ./gradlew jvmMainClasses jvmTest
|
# we are using docker's version of gradle
|
||||||
- name: Run Benchmark
|
# so no need for wrapper validadation or user
|
||||||
working-directory: kotlin
|
# gradlew
|
||||||
run: ./gradlew jvmBenchmark
|
run: gradle jvmMainClasses jvmTest jsTest jsBrowserTest
|
||||||
- name: Generate Benchmark Report
|
|
||||||
working-directory: kotlin
|
|
||||||
run: |
|
|
||||||
./gradlew jmhReport;
|
|
||||||
mv benchmark/build/reports/benchmarks/main/* benchmark_latest
|
|
||||||
- name: Archive benchmark report
|
|
||||||
uses: actions/upload-artifact@v1
|
|
||||||
with:
|
|
||||||
name: Kotlin Benchmark Report
|
|
||||||
path: kotlin/benchmark_latest
|
|
||||||
|
|
||||||
build-rust:
|
build-rust:
|
||||||
name: Build Rust
|
name: Build Rust
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v1
|
- uses: actions/checkout@v2
|
||||||
- name: test
|
- name: test
|
||||||
working-directory: tests
|
working-directory: tests
|
||||||
run: bash RustTest.sh
|
run: bash RustTest.sh
|
||||||
@@ -221,7 +399,7 @@ jobs:
|
|||||||
name: Build Python
|
name: Build Python
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v1
|
- uses: actions/checkout@v2
|
||||||
- name: test
|
- name: test
|
||||||
working-directory: tests
|
working-directory: tests
|
||||||
run: bash PythonTest.sh
|
run: bash PythonTest.sh
|
||||||
@@ -230,10 +408,10 @@ jobs:
|
|||||||
name: Build Go
|
name: Build Go
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v1
|
- uses: actions/checkout@v2
|
||||||
- name: flatc
|
- name: flatc
|
||||||
# FIXME: make test script not rely on 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 -j4
|
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
|
- name: test
|
||||||
working-directory: tests
|
working-directory: tests
|
||||||
run: bash GoTest.sh
|
run: bash GoTest.sh
|
||||||
@@ -242,33 +420,87 @@ jobs:
|
|||||||
name: Build Swift
|
name: Build Swift
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v1
|
- uses: actions/checkout@v2
|
||||||
- name: test
|
- name: test
|
||||||
working-directory: tests/FlatBuffers.Test.Swift
|
working-directory: tests/FlatBuffers.Test.Swift
|
||||||
run: sh SwiftTest.sh
|
run: sh SwiftTest.sh
|
||||||
|
|
||||||
|
build-swift-wasm:
|
||||||
|
name: Build Swift Wasm
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
container:
|
||||||
|
image: ghcr.io/swiftwasm/carton:0.15.3
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v2
|
||||||
|
- name: Setup Wasmer
|
||||||
|
uses: wasmerio/setup-wasmer@v1
|
||||||
|
- name: Test
|
||||||
|
working-directory: tests/FlatBuffers.Test.Swift.Wasm
|
||||||
|
run: carton test
|
||||||
|
|
||||||
build-ts:
|
build-ts:
|
||||||
name: Build TS
|
name: Build TS
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v1
|
- uses: actions/checkout@v2
|
||||||
|
- 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
|
- name: compile
|
||||||
run: npm run compile
|
run: yarn compile
|
||||||
- name: test
|
- name: test
|
||||||
working-directory: tests
|
working-directory: tests
|
||||||
run: sh TypeScriptTest.sh
|
run: python3 TypeScriptTest.py
|
||||||
|
|
||||||
build-dart:
|
build-dart:
|
||||||
name: Build Dart
|
name: Build Dart
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v1
|
- uses: actions/checkout@v2
|
||||||
- uses: dart-lang/setup-dart@v1
|
- uses: dart-lang/setup-dart@v1
|
||||||
with:
|
with:
|
||||||
sdk: stable
|
sdk: stable
|
||||||
- name: flatc
|
- name: flatc
|
||||||
# FIXME: make test script not rely on 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 -j4
|
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
|
- name: test
|
||||||
working-directory: tests
|
working-directory: tests
|
||||||
run: bash DartTest.sh
|
run: bash DartTest.sh
|
||||||
|
|
||||||
|
release-digests:
|
||||||
|
if: startsWith(github.ref, 'refs/tags/')
|
||||||
|
needs: [build-linux, build-windows, build-mac-intel, build-mac-universal]
|
||||||
|
outputs:
|
||||||
|
digests: ${{ steps.hash.outputs.digests }}
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
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 "::set-output name=digests::$(cat checksums.txt | base64 -w0)"
|
||||||
|
|
||||||
|
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.0
|
||||||
|
with:
|
||||||
|
base64-subjects: "${{ needs.release-digests.outputs.digests }}"
|
||||||
|
upload-assets: true # Optional: Upload to a new release
|
||||||
|
|||||||
71
.github/workflows/codeql.yml
vendored
Normal file
71
.github/workflows/codeql.yml
vendored
Normal 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
|
||||||
7
.github/workflows/label.yml
vendored
7
.github/workflows/label.yml
vendored
@@ -6,11 +6,16 @@
|
|||||||
# https://github.com/actions/labeler
|
# https://github.com/actions/labeler
|
||||||
|
|
||||||
name: Labeler
|
name: Labeler
|
||||||
|
permissions: read-all
|
||||||
|
|
||||||
on: [pull_request_target]
|
on: [pull_request_target]
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
label:
|
label:
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
pull-requests: write
|
||||||
|
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
|
|||||||
34
.github/workflows/main.yml
vendored
Normal file
34
.github/workflows/main.yml
vendored
Normal 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
|
||||||
55
.github/workflows/scorecards.yml
vendored
Normal file
55
.github/workflows/scorecards.yml
vendored
Normal 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
|
||||||
1
.github/workflows/stale.yml
vendored
1
.github/workflows/stale.yml
vendored
@@ -1,4 +1,5 @@
|
|||||||
name: Mark stale issues and pull requests
|
name: Mark stale issues and pull requests
|
||||||
|
permissions: read-all
|
||||||
|
|
||||||
on:
|
on:
|
||||||
schedule:
|
schedule:
|
||||||
|
|||||||
4
.gitignore
vendored
4
.gitignore
vendored
@@ -54,6 +54,8 @@ flathash
|
|||||||
flathash.exe
|
flathash.exe
|
||||||
flattests
|
flattests
|
||||||
flattests.exe
|
flattests.exe
|
||||||
|
flattests_cpp17
|
||||||
|
flattests_cpp17.exe
|
||||||
flatsamplebinary
|
flatsamplebinary
|
||||||
flatsamplebinary.exe
|
flatsamplebinary.exe
|
||||||
flatsampletext
|
flatsampletext
|
||||||
@@ -76,7 +78,7 @@ tests/php/
|
|||||||
CMakeLists.txt.user
|
CMakeLists.txt.user
|
||||||
CMakeScripts/**
|
CMakeScripts/**
|
||||||
CTestTestfile.cmake
|
CTestTestfile.cmake
|
||||||
FlatbuffersConfigVersion.cmake
|
FlatBuffersConfigVersion.cmake
|
||||||
FlatBuffers.cbp
|
FlatBuffers.cbp
|
||||||
build/Xcode/FlatBuffers.xcodeproj/project.xcworkspace/**
|
build/Xcode/FlatBuffers.xcodeproj/project.xcworkspace/**
|
||||||
build/Xcode/FlatBuffers.xcodeproj/xcuserdata/**
|
build/Xcode/FlatBuffers.xcodeproj/xcuserdata/**
|
||||||
|
|||||||
@@ -1,45 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
#
|
|
||||||
# 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.
|
|
||||||
set -e
|
|
||||||
|
|
||||||
docker build -t build_cpp_image -f tests/docker/Dockerfile.testing.cpp.debian_buster .
|
|
||||||
# Run tests with sanitizers (--cap-add SYS_PTRACE), both GCC and Clang.
|
|
||||||
cpp_test_args="--cap-add SYS_PTRACE build_cpp_image sh ./tests/docker/cpp_test.run.sh Debug"
|
|
||||||
docker run --rm $cpp_test_args
|
|
||||||
docker run --rm --env CC=/usr/bin/clang --env CXX=/usr/bin/clang++ $cpp_test_args
|
|
||||||
# Build flatc on debian once to speed up the test loop below.
|
|
||||||
docker run --name flatc_container build_cpp_image sh ./tests/docker/build_flatc.run.sh Debug
|
|
||||||
# All dependent dockers refer to 'flatc_debian_stretch'.
|
|
||||||
docker cp flatc_container:/flatbuffers/flatc flatc_debian_stretch
|
|
||||||
|
|
||||||
for f in $(ls tests/docker/languages | sort)
|
|
||||||
do
|
|
||||||
# docker pull sometimes fails for unknown reasons, probably travisci-related. this retries the pull we need a few times.
|
|
||||||
REQUIRED_BASE_IMAGE=$(cat tests/docker/languages/${f} | head -n 1 | awk ' { print $2 } ')
|
|
||||||
|
|
||||||
set +e
|
|
||||||
n=0
|
|
||||||
until [ $n -ge 5 ]
|
|
||||||
do
|
|
||||||
docker pull $REQUIRED_BASE_IMAGE && break
|
|
||||||
n=$[$n+1]
|
|
||||||
sleep 1
|
|
||||||
done
|
|
||||||
set -e
|
|
||||||
|
|
||||||
docker build -t $(echo ${f} | cut -f 3- -d .) -f tests/docker/languages/${f} .
|
|
||||||
echo "TEST OK: ${f}"
|
|
||||||
done
|
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
#
|
|
||||||
# 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.
|
|
||||||
set -e
|
|
||||||
|
|
||||||
if [ -n "$1" ]; then
|
|
||||||
scan_dir="$1"
|
|
||||||
else
|
|
||||||
scan_dir="$( pwd )"
|
|
||||||
fi
|
|
||||||
|
|
||||||
py_checker="$0.py"
|
|
||||||
|
|
||||||
echo "scan root directory = '$scan_dir'"
|
|
||||||
python3 --version
|
|
||||||
# Scan recursively and search all *.cpp and *.h files using regex patterns.
|
|
||||||
# Assume that script running from a root of Flatbuffers working dir.
|
|
||||||
python3 $py_checker "ascii" "$scan_dir/include" "\.h$"
|
|
||||||
python3 $py_checker "ascii" "$scan_dir/src" "\.cpp$"
|
|
||||||
python3 $py_checker "ascii" "$scan_dir/tests" "\.h$"
|
|
||||||
python3 $py_checker "utf-8" "$scan_dir/tests" "\.cpp$"
|
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
import os
|
|
||||||
import re
|
|
||||||
import sys
|
|
||||||
|
|
||||||
def check_encoding(encoding, scan_dir, regex_pattern):
|
|
||||||
fname = None
|
|
||||||
try:
|
|
||||||
assert encoding in ['ascii', 'utf-8'], "unexpected encoding"
|
|
||||||
cmp = re.compile(regex_pattern)
|
|
||||||
for root, dirs, files in os.walk(scan_dir):
|
|
||||||
fname = root
|
|
||||||
cmp_list = [f for f in files if cmp.search(f) is not None]
|
|
||||||
for f in cmp_list:
|
|
||||||
fname = os.path.join(root, f)
|
|
||||||
with open(fname, mode='rb') as test_file:
|
|
||||||
btext = test_file.read()
|
|
||||||
# check encoding
|
|
||||||
btext.decode(encoding=encoding, errors="strict")
|
|
||||||
if encoding == "utf-8" and btext.startswith(b'\xEF\xBB\xBF'):
|
|
||||||
raise ValueError("unexpected BOM in file")
|
|
||||||
# check LF line endings
|
|
||||||
LF = btext.count(b'\n')
|
|
||||||
CR = btext.count(b'\r')
|
|
||||||
if CR!=0:
|
|
||||||
raise ValueError("invalid line endings: LF({})/CR({})".format(LF, CR))
|
|
||||||
except Exception as err:
|
|
||||||
print("ERROR with [{}]: {}".format(fname, err))
|
|
||||||
return -1
|
|
||||||
else:
|
|
||||||
return 0
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
# python check-sources.sh.py 'ascii' '.' '.*\.(cpp|h)$'
|
|
||||||
res = check_encoding(sys.argv[1], sys.argv[2], sys.argv[3])
|
|
||||||
sys.exit(0 if res == 0 else -1)
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
|
|
||||||
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
|
|
||||||
PROD_REPOSITORY="https://upload.pypi.org/legacy/"
|
|
||||||
TEST_REPOSITORY="https://test.pypi.org/legacy/"
|
|
||||||
|
|
||||||
twine upload \
|
|
||||||
--username "$PYPI_USERNAME" \
|
|
||||||
--password "$PYPI_PASSWORD" \
|
|
||||||
--repository-url "$PROD_REPOSITORY" \
|
|
||||||
"$DIR/../python/dist/"*
|
|
||||||
|
|
||||||
@@ -1,52 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
#
|
|
||||||
# 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.
|
|
||||||
|
|
||||||
set -e
|
|
||||||
|
|
||||||
# HACKY solution to make nodejs work.
|
|
||||||
source ~/.nvm/nvm.sh
|
|
||||||
nvm alias default node
|
|
||||||
nvm use default
|
|
||||||
|
|
||||||
sh scripts/clang-format-git.sh
|
|
||||||
|
|
||||||
# Check formatting for go lang
|
|
||||||
|
|
||||||
cd go
|
|
||||||
gofmt -w .
|
|
||||||
cd ..
|
|
||||||
cd grpc/examples/go
|
|
||||||
sh format.sh
|
|
||||||
cd ../../..
|
|
||||||
|
|
||||||
node_modules/.bin/eslint ts/** --ext .ts --quiet --fix
|
|
||||||
|
|
||||||
#PYTHON IS DISABLED UNTIL WE CREATE A .pylintrc FILE FOR IT
|
|
||||||
pylint python/** --disable=all
|
|
||||||
|
|
||||||
swiftformat --config swift.swiftformat .
|
|
||||||
|
|
||||||
|
|
||||||
if ! git diff --quiet; then
|
|
||||||
echo >&2
|
|
||||||
echo "ERROR: ********************************************************" >&2
|
|
||||||
echo "ERROR: The following differences were found after running" >&2
|
|
||||||
echo "ERROR: .travis/format_check.sh script. Maybe you forgot to format" >&2
|
|
||||||
echo "ERROR: the code after making changes? please check Formatters.md" >&2
|
|
||||||
echo "ERROR: ********************************************************" >&2
|
|
||||||
echo >&2
|
|
||||||
git diff --binary --exit-code
|
|
||||||
fi
|
|
||||||
@@ -1,90 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
#
|
|
||||||
# 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.
|
|
||||||
|
|
||||||
set -e
|
|
||||||
set -x
|
|
||||||
|
|
||||||
# install devtools
|
|
||||||
install_languages() {
|
|
||||||
sudo apt update
|
|
||||||
|
|
||||||
# Install nodeJS and yarn
|
|
||||||
wget https://raw.githubusercontent.com/creationix/nvm/v0.31.0/nvm.sh -O ~/.nvm/nvm.sh
|
|
||||||
source ~/.nvm/nvm.sh
|
|
||||||
nvm install node
|
|
||||||
node --version
|
|
||||||
curl -o- -L https://yarnpkg.com/install.sh | bash
|
|
||||||
export PATH="$HOME/.yarn/bin:$PATH"
|
|
||||||
yarn config set prefix ~/.yarn -g
|
|
||||||
export PATH="$HOME/.yarn/bin:$HOME/.config/yarn/global/node_modules/.bin:$PATH"
|
|
||||||
|
|
||||||
# Install swift
|
|
||||||
sudo apt-get install \
|
|
||||||
binutils \
|
|
||||||
git \
|
|
||||||
libc6-dev \
|
|
||||||
libcurl3 \
|
|
||||||
libedit2 \
|
|
||||||
libgcc-5-dev \
|
|
||||||
libpython2.7 \
|
|
||||||
libsqlite3-0 \
|
|
||||||
libstdc++-5-dev \
|
|
||||||
libxml2 \
|
|
||||||
pkg-config \
|
|
||||||
tzdata \
|
|
||||||
zlib1g-dev
|
|
||||||
|
|
||||||
SWIFT_URL=https://swift.org/builds/swift-5.3.1-release/ubuntu1604/swift-5.3.1-RELEASE/swift-5.3.1-RELEASE-ubuntu16.04.tar.gz
|
|
||||||
curl -fSsL "$SWIFT_URL" -o swift.tar.gz
|
|
||||||
|
|
||||||
mkdir ~/swiftbuild
|
|
||||||
tar -xvzf swift.tar.gz -C ~/swiftbuild
|
|
||||||
|
|
||||||
export PATH="~/swiftbuild/swift-5.3.1-RELEASE-ubuntu16.04/usr/bin:$PATH"
|
|
||||||
|
|
||||||
|
|
||||||
mkdir ~/gobuild
|
|
||||||
wget -c https://golang.org/dl/go1.15.2.linux-amd64.tar.gz
|
|
||||||
tar -xvzf go1.15.2.linux-amd64.tar.gz -C ~/gobuild
|
|
||||||
|
|
||||||
export PATH="~/gobuild/go/bin:$PATH"
|
|
||||||
|
|
||||||
swift --version
|
|
||||||
go version
|
|
||||||
yarn -v
|
|
||||||
node -v
|
|
||||||
}
|
|
||||||
|
|
||||||
install_formatters() {
|
|
||||||
# installing swift formatter
|
|
||||||
git clone --depth 1 --branch 0.47.4 https://github.com/nicklockwood/SwiftFormat.git
|
|
||||||
cd SwiftFormat
|
|
||||||
swift build -c release
|
|
||||||
sudo cp .build/release/swiftformat /usr/local/bin/swiftformat
|
|
||||||
cd ..
|
|
||||||
|
|
||||||
which yarn
|
|
||||||
which node
|
|
||||||
yarn -v
|
|
||||||
node -v
|
|
||||||
|
|
||||||
yarn install
|
|
||||||
pip install pylint
|
|
||||||
}
|
|
||||||
|
|
||||||
install_languages
|
|
||||||
export PATH="~/swift/swift/usr/bin:$PATH"
|
|
||||||
install_formatters
|
|
||||||
@@ -8,6 +8,7 @@ package(
|
|||||||
|
|
||||||
exports_files([
|
exports_files([
|
||||||
"LICENSE",
|
"LICENSE",
|
||||||
|
"tsconfig.json",
|
||||||
])
|
])
|
||||||
|
|
||||||
config_setting(
|
config_setting(
|
||||||
@@ -48,6 +49,7 @@ filegroup(
|
|||||||
"include/flatbuffers/detached_buffer.h",
|
"include/flatbuffers/detached_buffer.h",
|
||||||
"include/flatbuffers/flatbuffer_builder.h",
|
"include/flatbuffers/flatbuffer_builder.h",
|
||||||
"include/flatbuffers/flatbuffers.h",
|
"include/flatbuffers/flatbuffers.h",
|
||||||
|
"include/flatbuffers/flex_flat_util.h",
|
||||||
"include/flatbuffers/flexbuffers.h",
|
"include/flatbuffers/flexbuffers.h",
|
||||||
"include/flatbuffers/grpc.h",
|
"include/flatbuffers/grpc.h",
|
||||||
"include/flatbuffers/hash.h",
|
"include/flatbuffers/hash.h",
|
||||||
@@ -79,6 +81,7 @@ cc_library(
|
|||||||
# Public flatc compiler.
|
# Public flatc compiler.
|
||||||
cc_binary(
|
cc_binary(
|
||||||
name = "flatc",
|
name = "flatc",
|
||||||
|
data = ["//reflection:reflection_fbs_schema"],
|
||||||
deps = [
|
deps = [
|
||||||
"//src:flatc",
|
"//src:flatc",
|
||||||
],
|
],
|
||||||
|
|||||||
36
CHANGELOG.md
Normal file
36
CHANGELOG.md
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
# 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.
|
||||||
|
|
||||||
|
## 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.
|
||||||
@@ -95,7 +95,7 @@ function(build_flatbuffers flatbuffers_schemas
|
|||||||
set(generated_include ${generated_includes_dir}/${filename}_generated.h)
|
set(generated_include ${generated_includes_dir}/${filename}_generated.h)
|
||||||
add_custom_command(
|
add_custom_command(
|
||||||
OUTPUT ${generated_include}
|
OUTPUT ${generated_include}
|
||||||
COMMAND ${FLATC} ${FLATC_ARGS}
|
COMMAND ${FLATC} ${FLATC_SCHEMA_ARGS}
|
||||||
-o ${generated_includes_dir}
|
-o ${generated_includes_dir}
|
||||||
${include_params}
|
${include_params}
|
||||||
-c ${schema}
|
-c ${schema}
|
||||||
@@ -230,16 +230,30 @@ function(flatbuffers_generate_headers)
|
|||||||
foreach(schema ${FLATBUFFERS_GENERATE_HEADERS_SCHEMAS})
|
foreach(schema ${FLATBUFFERS_GENERATE_HEADERS_SCHEMAS})
|
||||||
get_filename_component(filename ${schema} NAME_WE)
|
get_filename_component(filename ${schema} NAME_WE)
|
||||||
set(generated_include "${generated_include_dir}/${filename}_generated.h")
|
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(
|
add_custom_command(
|
||||||
OUTPUT ${generated_include}
|
OUTPUT ${generated_include} ${generated_source_file}
|
||||||
COMMAND ${FLATC} ${FLATC_ARGS}
|
COMMAND ${FLATC} ${FLATC_ARGS}
|
||||||
-o ${generated_include_dir}
|
-o ${generated_include_dir}
|
||||||
${include_params}
|
${include_params}
|
||||||
-c ${schema}
|
-c ${schema}
|
||||||
${FLATBUFFERS_GENERATE_HEADERS_FLAGS}
|
${FLATBUFFERS_GENERATE_HEADERS_FLAGS}
|
||||||
DEPENDS ${FLATC_TARGET} ${schema}
|
DEPENDS ${FLATC_TARGET} ${schema}
|
||||||
WORKING_DIRECTORY "${working_dir}")
|
WORKING_DIRECTORY "${working_dir}"
|
||||||
|
COMMENT "Building ${schema} flatbuffers...")
|
||||||
list(APPEND all_generated_header_files ${generated_include})
|
list(APPEND all_generated_header_files ${generated_include})
|
||||||
|
list(APPEND all_generated_source_files ${generated_source_file})
|
||||||
|
|
||||||
# Geneate the binary flatbuffers schemas if instructed to.
|
# Geneate the binary flatbuffers schemas if instructed to.
|
||||||
if (NOT ${FLATBUFFERS_GENERATE_HEADERS_BINARY_SCHEMAS_DIR} STREQUAL "")
|
if (NOT ${FLATBUFFERS_GENERATE_HEADERS_BINARY_SCHEMAS_DIR} STREQUAL "")
|
||||||
@@ -264,6 +278,7 @@ function(flatbuffers_generate_headers)
|
|||||||
INTERFACE
|
INTERFACE
|
||||||
${all_generated_header_files}
|
${all_generated_header_files}
|
||||||
${all_generated_binary_files}
|
${all_generated_binary_files}
|
||||||
|
${all_generated_source_files}
|
||||||
${FLATBUFFERS_GENERATE_HEADERS_SCHEMAS})
|
${FLATBUFFERS_GENERATE_HEADERS_SCHEMAS})
|
||||||
add_dependencies(
|
add_dependencies(
|
||||||
${FLATBUFFERS_GENERATE_HEADERS_TARGET}
|
${FLATBUFFERS_GENERATE_HEADERS_TARGET}
|
||||||
@@ -278,6 +293,10 @@ function(flatbuffers_generate_headers)
|
|||||||
TREE "${generated_target_dir}"
|
TREE "${generated_target_dir}"
|
||||||
PREFIX "Flatbuffers/Generated/Headers Files"
|
PREFIX "Flatbuffers/Generated/Headers Files"
|
||||||
FILES ${all_generated_header_files})
|
FILES ${all_generated_header_files})
|
||||||
|
source_group(
|
||||||
|
TREE "${generated_target_dir}"
|
||||||
|
PREFIX "Flatbuffers/Generated/Source Files"
|
||||||
|
FILES ${all_generated_source_files})
|
||||||
source_group(
|
source_group(
|
||||||
TREE ${working_dir}
|
TREE ${working_dir}
|
||||||
PREFIX "Flatbuffers/Schemas"
|
PREFIX "Flatbuffers/Schemas"
|
||||||
@@ -371,7 +390,8 @@ function(flatbuffers_generate_binary_files)
|
|||||||
-b ${FLATBUFFERS_GENERATE_BINARY_FILES_SCHEMA} ${json_file}
|
-b ${FLATBUFFERS_GENERATE_BINARY_FILES_SCHEMA} ${json_file}
|
||||||
${FLATBUFFERS_GENERATE_BINARY_FILES_FLAGS}
|
${FLATBUFFERS_GENERATE_BINARY_FILES_FLAGS}
|
||||||
DEPENDS ${FLATC_TARGET} ${json_file}
|
DEPENDS ${FLATC_TARGET} ${json_file}
|
||||||
WORKING_DIRECTORY "${working_dir}")
|
WORKING_DIRECTORY "${working_dir}"
|
||||||
|
COMMENT "Building ${json_file} binary flatbuffers...")
|
||||||
list(APPEND all_generated_binary_files ${generated_binary_file})
|
list(APPEND all_generated_binary_files ${generated_binary_file})
|
||||||
endforeach()
|
endforeach()
|
||||||
|
|
||||||
|
|||||||
780
CMake/CMakeLists_legacy.cmake.in
Normal file
780
CMake/CMakeLists_legacy.cmake.in
Normal file
@@ -0,0 +1,780 @@
|
|||||||
|
# This was the legacy <root>/CMakeLists.txt that supported cmake version 2.8.12.
|
||||||
|
# It was originally copied on Jan 30 2022, and is conditionally included in the
|
||||||
|
# current <root>/CMakeLists.txt if the cmake version used is older than the new
|
||||||
|
# minimum version.
|
||||||
|
#
|
||||||
|
# Only add to this file to fix immediate issues or if a change cannot be made
|
||||||
|
# <root>/CMakeList.txt in a compatible way.
|
||||||
|
|
||||||
|
if (POLICY CMP0048)
|
||||||
|
cmake_policy(SET CMP0048 NEW)
|
||||||
|
if(CMAKE_VERSION VERSION_LESS 3.9)
|
||||||
|
project(FlatBuffers
|
||||||
|
VERSION 2.0.0
|
||||||
|
LANGUAGES CXX)
|
||||||
|
else()
|
||||||
|
project(FlatBuffers
|
||||||
|
DESCRIPTION "Flatbuffers serialization library"
|
||||||
|
VERSION 2.0.0
|
||||||
|
LANGUAGES CXX)
|
||||||
|
endif()
|
||||||
|
else()
|
||||||
|
project(FlatBuffers)
|
||||||
|
endif (POLICY CMP0048)
|
||||||
|
|
||||||
|
include(CMake/Version.cmake)
|
||||||
|
|
||||||
|
# generate compile_commands.json
|
||||||
|
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
|
||||||
|
|
||||||
|
# NOTE: Code coverage only works on Linux & OSX.
|
||||||
|
option(FLATBUFFERS_CODE_COVERAGE "Enable the code coverage build option." OFF)
|
||||||
|
option(FLATBUFFERS_BUILD_TESTS "Enable the build of tests and samples." ON)
|
||||||
|
option(FLATBUFFERS_INSTALL "Enable the installation of targets." ON)
|
||||||
|
option(FLATBUFFERS_BUILD_FLATLIB "Enable the build of the flatbuffers library"
|
||||||
|
ON)
|
||||||
|
option(FLATBUFFERS_BUILD_FLATC "Enable the build of the flatbuffers compiler"
|
||||||
|
ON)
|
||||||
|
option(FLATBUFFERS_STATIC_FLATC "Build flatbuffers compiler with -static flag"
|
||||||
|
OFF)
|
||||||
|
option(FLATBUFFERS_BUILD_FLATHASH "Enable the build of flathash" ON)
|
||||||
|
option(FLATBUFFERS_BUILD_BENCHMARKS "Enable the build of flatbenchmark. \"
|
||||||
|
Requires C++11."
|
||||||
|
OFF)
|
||||||
|
option(FLATBUFFERS_BUILD_GRPCTEST "Enable the build of grpctest" OFF)
|
||||||
|
option(FLATBUFFERS_BUILD_SHAREDLIB
|
||||||
|
"Enable the build of the flatbuffers shared library"
|
||||||
|
OFF)
|
||||||
|
option(FLATBUFFERS_LIBCXX_WITH_CLANG "Force libc++ when using Clang" ON)
|
||||||
|
# NOTE: Sanitizer check only works on Linux & OSX (gcc & llvm).
|
||||||
|
option(FLATBUFFERS_CODE_SANITIZE
|
||||||
|
"Add '-fsanitize' flags to 'flattests' and 'flatc' targets."
|
||||||
|
OFF)
|
||||||
|
option(FLATBUFFERS_PACKAGE_REDHAT
|
||||||
|
"Build an rpm using the 'package' target."
|
||||||
|
OFF)
|
||||||
|
option(FLATBUFFERS_PACKAGE_DEBIAN
|
||||||
|
"Build an deb using the 'package' target."
|
||||||
|
OFF)
|
||||||
|
option(FLATBUFFERS_BUILD_CPP17
|
||||||
|
"Enable the build of c++17 test target. \"
|
||||||
|
Requirements: Clang6, GCC7, MSVC2017 (_MSC_VER >= 1914) or higher."
|
||||||
|
OFF)
|
||||||
|
option(FLATBUFFERS_BUILD_LEGACY
|
||||||
|
"Run C++ code generator with '--cpp-std c++0x' switch."
|
||||||
|
OFF)
|
||||||
|
option(FLATBUFFERS_ENABLE_PCH
|
||||||
|
"Enable precompile headers support for 'flatbuffers' and 'flatc'. \"
|
||||||
|
Only work if CMake supports 'target_precompile_headers'. \"
|
||||||
|
This can speed up compilation time."
|
||||||
|
OFF)
|
||||||
|
option(FLATBUFFERS_SKIP_MONSTER_EXTRA
|
||||||
|
"Skip generating monster_extra.fbs that contains non-supported numerical\"
|
||||||
|
types." OFF)
|
||||||
|
option(FLATBUFFERS_OSX_BUILD_UNIVERSAL
|
||||||
|
"Enable the build for multiple architectures on OS X (arm64, x86_64)."
|
||||||
|
ON)
|
||||||
|
|
||||||
|
if(NOT FLATBUFFERS_BUILD_FLATC AND FLATBUFFERS_BUILD_TESTS)
|
||||||
|
message(WARNING
|
||||||
|
"Cannot build tests without building the compiler. Tests will be disabled.")
|
||||||
|
set(FLATBUFFERS_BUILD_TESTS OFF)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if(DEFINED FLATBUFFERS_MAX_PARSING_DEPTH)
|
||||||
|
# Override the default recursion depth limit.
|
||||||
|
add_definitions(-DFLATBUFFERS_MAX_PARSING_DEPTH=${FLATBUFFERS_MAX_PARSING_DEPTH})
|
||||||
|
message(STATUS "FLATBUFFERS_MAX_PARSING_DEPTH: ${FLATBUFFERS_MAX_PARSING_DEPTH}")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
# Auto-detect locale-narrow 'strtod_l' and 'strtoull_l' functions.
|
||||||
|
if(NOT DEFINED FLATBUFFERS_LOCALE_INDEPENDENT)
|
||||||
|
include(CheckCXXSymbolExists)
|
||||||
|
|
||||||
|
set(FLATBUFFERS_LOCALE_INDEPENDENT 0)
|
||||||
|
if(MSVC)
|
||||||
|
check_cxx_symbol_exists(_strtof_l stdlib.h FLATBUFFERS_HAS_STRTOF_L)
|
||||||
|
check_cxx_symbol_exists(_strtoui64_l stdlib.h FLATBUFFERS_HAS_STRTOULL_L)
|
||||||
|
else()
|
||||||
|
check_cxx_symbol_exists(strtof_l stdlib.h FLATBUFFERS_HAS_STRTOF_L)
|
||||||
|
check_cxx_symbol_exists(strtoull_l stdlib.h FLATBUFFERS_HAS_STRTOULL_L)
|
||||||
|
endif()
|
||||||
|
if(FLATBUFFERS_HAS_STRTOF_L AND FLATBUFFERS_HAS_STRTOULL_L)
|
||||||
|
set(FLATBUFFERS_LOCALE_INDEPENDENT 1)
|
||||||
|
endif()
|
||||||
|
endif()
|
||||||
|
add_definitions(-DFLATBUFFERS_LOCALE_INDEPENDENT=$<BOOL:${FLATBUFFERS_LOCALE_INDEPENDENT}>)
|
||||||
|
|
||||||
|
set(FlatBuffers_Library_SRCS
|
||||||
|
include/flatbuffers/allocator.h
|
||||||
|
include/flatbuffers/array.h
|
||||||
|
include/flatbuffers/base.h
|
||||||
|
include/flatbuffers/bfbs_generator.h
|
||||||
|
include/flatbuffers/buffer.h
|
||||||
|
include/flatbuffers/buffer_ref.h
|
||||||
|
include/flatbuffers/default_allocator.h
|
||||||
|
include/flatbuffers/detached_buffer.h
|
||||||
|
include/flatbuffers/flatbuffer_builder.h
|
||||||
|
include/flatbuffers/flatbuffers.h
|
||||||
|
include/flatbuffers/flexbuffers.h
|
||||||
|
include/flatbuffers/hash.h
|
||||||
|
include/flatbuffers/idl.h
|
||||||
|
include/flatbuffers/minireflect.h
|
||||||
|
include/flatbuffers/reflection.h
|
||||||
|
include/flatbuffers/reflection_generated.h
|
||||||
|
include/flatbuffers/registry.h
|
||||||
|
include/flatbuffers/stl_emulation.h
|
||||||
|
include/flatbuffers/string.h
|
||||||
|
include/flatbuffers/struct.h
|
||||||
|
include/flatbuffers/table.h
|
||||||
|
include/flatbuffers/util.h
|
||||||
|
include/flatbuffers/vector.h
|
||||||
|
include/flatbuffers/vector_downward.h
|
||||||
|
include/flatbuffers/verifier.h
|
||||||
|
src/idl_parser.cpp
|
||||||
|
src/idl_gen_text.cpp
|
||||||
|
src/reflection.cpp
|
||||||
|
src/util.cpp
|
||||||
|
)
|
||||||
|
|
||||||
|
set(FlatBuffers_Compiler_SRCS
|
||||||
|
${FlatBuffers_Library_SRCS}
|
||||||
|
src/idl_gen_cpp.cpp
|
||||||
|
src/idl_gen_csharp.cpp
|
||||||
|
src/idl_gen_dart.cpp
|
||||||
|
src/idl_gen_kotlin.cpp
|
||||||
|
src/idl_gen_go.cpp
|
||||||
|
src/idl_gen_java.cpp
|
||||||
|
src/idl_gen_ts.cpp
|
||||||
|
src/idl_gen_php.cpp
|
||||||
|
src/idl_gen_python.cpp
|
||||||
|
src/idl_gen_lobster.cpp
|
||||||
|
src/idl_gen_lua.cpp
|
||||||
|
src/idl_gen_rust.cpp
|
||||||
|
src/idl_gen_fbs.cpp
|
||||||
|
src/idl_gen_grpc.cpp
|
||||||
|
src/idl_gen_json_schema.cpp
|
||||||
|
src/idl_gen_swift.cpp
|
||||||
|
src/flatc.cpp
|
||||||
|
src/flatc_main.cpp
|
||||||
|
src/bfbs_gen.h
|
||||||
|
src/bfbs_gen_lua.h
|
||||||
|
include/flatbuffers/code_generators.h
|
||||||
|
src/bfbs_gen_lua.cpp
|
||||||
|
src/code_generators.cpp
|
||||||
|
grpc/src/compiler/schema_interface.h
|
||||||
|
grpc/src/compiler/cpp_generator.h
|
||||||
|
grpc/src/compiler/cpp_generator.cc
|
||||||
|
grpc/src/compiler/go_generator.h
|
||||||
|
grpc/src/compiler/go_generator.cc
|
||||||
|
grpc/src/compiler/java_generator.h
|
||||||
|
grpc/src/compiler/java_generator.cc
|
||||||
|
grpc/src/compiler/python_generator.h
|
||||||
|
grpc/src/compiler/python_generator.cc
|
||||||
|
grpc/src/compiler/swift_generator.h
|
||||||
|
grpc/src/compiler/swift_generator.cc
|
||||||
|
grpc/src/compiler/ts_generator.h
|
||||||
|
grpc/src/compiler/ts_generator.cc
|
||||||
|
)
|
||||||
|
|
||||||
|
set(FlatHash_SRCS
|
||||||
|
include/flatbuffers/hash.h
|
||||||
|
src/flathash.cpp
|
||||||
|
)
|
||||||
|
|
||||||
|
set(FlatBuffers_Tests_SRCS
|
||||||
|
${FlatBuffers_Library_SRCS}
|
||||||
|
src/idl_gen_fbs.cpp
|
||||||
|
tests/test.cpp
|
||||||
|
tests/test_assert.h
|
||||||
|
tests/test_assert.cpp
|
||||||
|
tests/test_builder.h
|
||||||
|
tests/test_builder.cpp
|
||||||
|
tests/native_type_test_impl.h
|
||||||
|
tests/native_type_test_impl.cpp
|
||||||
|
include/flatbuffers/code_generators.h
|
||||||
|
src/code_generators.cpp
|
||||||
|
# file generate by running compiler on tests/monster_test.fbs
|
||||||
|
${CMAKE_CURRENT_BINARY_DIR}/tests/monster_test_generated.h
|
||||||
|
# file generate by running compiler on namespace_test/namespace_test1.fbs
|
||||||
|
${CMAKE_CURRENT_BINARY_DIR}/tests/namespace_test/namespace_test1_generated.h
|
||||||
|
${CMAKE_CURRENT_BINARY_DIR}/tests/namespace_test/namespace_test2_generated.h
|
||||||
|
# file generate by running compiler on union_vector/union_vector.fbs
|
||||||
|
${CMAKE_CURRENT_BINARY_DIR}/tests/union_vector/union_vector_generated.h
|
||||||
|
# file generate by running compiler on tests/arrays_test.fbs
|
||||||
|
${CMAKE_CURRENT_BINARY_DIR}/tests/arrays_test_generated.h
|
||||||
|
# file generate by running compiler on tests/native_type_test.fbs
|
||||||
|
${CMAKE_CURRENT_BINARY_DIR}/tests/native_type_test_generated.h
|
||||||
|
# file generate by running compiler on tests/monster_extra.fbs
|
||||||
|
${CMAKE_CURRENT_BINARY_DIR}/tests/monster_extra_generated.h
|
||||||
|
# file generate by running compiler on tests/monster_test.fbs
|
||||||
|
${CMAKE_CURRENT_BINARY_DIR}/tests/monster_test_bfbs_generated.h
|
||||||
|
# file generate by running compiler on tests/optional_scalars.fbs
|
||||||
|
${CMAKE_CURRENT_BINARY_DIR}/tests/optional_scalars_generated.h
|
||||||
|
)
|
||||||
|
|
||||||
|
set(FlatBuffers_Tests_CPP17_SRCS
|
||||||
|
${FlatBuffers_Library_SRCS}
|
||||||
|
tests/test_assert.h
|
||||||
|
tests/test_assert.cpp
|
||||||
|
tests/cpp17/test_cpp17.cpp
|
||||||
|
# file generate by running compiler on tests/monster_test.fbs
|
||||||
|
${CMAKE_CURRENT_BINARY_DIR}/tests/cpp17/generated_cpp17/monster_test_generated.h
|
||||||
|
${CMAKE_CURRENT_BINARY_DIR}/tests/monster_test_generated.h
|
||||||
|
${CMAKE_CURRENT_BINARY_DIR}/tests/cpp17/generated_cpp17/optional_scalars_generated.h
|
||||||
|
${CMAKE_CURRENT_BINARY_DIR}/tests/optional_scalars_generated.h
|
||||||
|
)
|
||||||
|
|
||||||
|
set(FlatBuffers_Sample_Binary_SRCS
|
||||||
|
include/flatbuffers/flatbuffers.h
|
||||||
|
samples/sample_binary.cpp
|
||||||
|
# file generated by running compiler on samples/monster.fbs
|
||||||
|
${CMAKE_CURRENT_BINARY_DIR}/samples/monster_generated.h
|
||||||
|
)
|
||||||
|
|
||||||
|
set(FlatBuffers_Sample_Text_SRCS
|
||||||
|
${FlatBuffers_Library_SRCS}
|
||||||
|
samples/sample_text.cpp
|
||||||
|
# file generated by running compiler on samples/monster.fbs
|
||||||
|
${CMAKE_CURRENT_BINARY_DIR}/samples/monster_generated.h
|
||||||
|
)
|
||||||
|
|
||||||
|
set(FlatBuffers_Sample_BFBS_SRCS
|
||||||
|
${FlatBuffers_Library_SRCS}
|
||||||
|
samples/sample_bfbs.cpp
|
||||||
|
# file generated by running compiler on samples/monster.fbs
|
||||||
|
${CMAKE_CURRENT_BINARY_DIR}/samples/monster_generated.h
|
||||||
|
)
|
||||||
|
|
||||||
|
set(FlatBuffers_GRPCTest_SRCS
|
||||||
|
include/flatbuffers/flatbuffers.h
|
||||||
|
include/flatbuffers/grpc.h
|
||||||
|
include/flatbuffers/util.h
|
||||||
|
src/util.cpp
|
||||||
|
tests/monster_test.grpc.fb.h
|
||||||
|
tests/test_assert.h
|
||||||
|
tests/test_builder.h
|
||||||
|
tests/monster_test.grpc.fb.cc
|
||||||
|
tests/test_assert.cpp
|
||||||
|
tests/test_builder.cpp
|
||||||
|
grpc/tests/grpctest.cpp
|
||||||
|
grpc/tests/message_builder_test.cpp
|
||||||
|
# file generate by running compiler on tests/monster_test.fbs
|
||||||
|
${CMAKE_CURRENT_BINARY_DIR}/tests/monster_test_generated.h
|
||||||
|
)
|
||||||
|
|
||||||
|
# source_group(Compiler FILES ${FlatBuffers_Compiler_SRCS})
|
||||||
|
# source_group(Tests FILES ${FlatBuffers_Tests_SRCS})
|
||||||
|
|
||||||
|
if(EXISTS "${CMAKE_TOOLCHAIN_FILE}")
|
||||||
|
# do not apply any global settings if the toolchain
|
||||||
|
# is being configured externally
|
||||||
|
message(STATUS "Using toolchain file: ${CMAKE_TOOLCHAIN_FILE}.")
|
||||||
|
elseif(CMAKE_COMPILER_IS_GNUCXX)
|
||||||
|
if(CYGWIN)
|
||||||
|
set(CMAKE_CXX_FLAGS
|
||||||
|
"${CMAKE_CXX_FLAGS} -std=gnu++11")
|
||||||
|
else(CYGWIN)
|
||||||
|
set(CMAKE_CXX_FLAGS
|
||||||
|
"${CMAKE_CXX_FLAGS} -std=c++0x")
|
||||||
|
endif(CYGWIN)
|
||||||
|
set(CMAKE_CXX_FLAGS
|
||||||
|
"${CMAKE_CXX_FLAGS} -Wall -pedantic -Werror -Wextra -Werror=shadow")
|
||||||
|
set(FLATBUFFERS_PRIVATE_CXX_FLAGS "-Wold-style-cast")
|
||||||
|
if (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 4.4)
|
||||||
|
if (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 7.0)
|
||||||
|
set(CMAKE_CXX_FLAGS
|
||||||
|
"${CMAKE_CXX_FLAGS} -faligned-new -Werror=implicit-fallthrough=2")
|
||||||
|
endif()
|
||||||
|
set(CMAKE_CXX_FLAGS
|
||||||
|
"${CMAKE_CXX_FLAGS} -Wunused-result -Werror=unused-result -Wunused-parameter -Werror=unused-parameter")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
# Certain platforms such as ARM do not use signed chars by default
|
||||||
|
# which causes issues with certain bounds checks.
|
||||||
|
set(CMAKE_CXX_FLAGS
|
||||||
|
"${CMAKE_CXX_FLAGS} -fsigned-char")
|
||||||
|
|
||||||
|
# MSVC **MUST** come before the Clang check, as clang-cl is flagged by CMake as "MSVC", but it still textually
|
||||||
|
# matches as Clang in its Compiler Id :)
|
||||||
|
# Note: in CMake >= 3.14 we can check CMAKE_CXX_COMPILER_FRONTEND_VARIANT STREQUAL "GNU" or "MSVC" to differentiate...
|
||||||
|
elseif(MSVC)
|
||||||
|
# Visual Studio pedantic build settings
|
||||||
|
# warning C4512: assignment operator could not be generated
|
||||||
|
# warning C4316: object allocated on the heap may not be aligned
|
||||||
|
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /W4 /WX /wd4512 /wd4316")
|
||||||
|
|
||||||
|
if(${CMAKE_CXX_COMPILER_ID} MATCHES "Clang")
|
||||||
|
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /D_CRT_SECURE_NO_WARNINGS")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
elseif(${CMAKE_CXX_COMPILER_ID} MATCHES "Clang")
|
||||||
|
if(APPLE)
|
||||||
|
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
|
||||||
|
|
||||||
|
if(FLATBUFFERS_OSX_BUILD_UNIVERSAL)
|
||||||
|
set(CMAKE_OSX_ARCHITECTURES "arm64;x86_64")
|
||||||
|
endif()
|
||||||
|
else()
|
||||||
|
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -pedantic -Werror -Wextra -Wno-unused-parameter")
|
||||||
|
set(FLATBUFFERS_PRIVATE_CXX_FLAGS "-Wold-style-cast")
|
||||||
|
if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 3.8)
|
||||||
|
list(APPEND FLATBUFFERS_PRIVATE_CXX_FLAGS "-Wimplicit-fallthrough" "-Wextra-semi" "-Werror=unused-private-field") # enable warning
|
||||||
|
endif()
|
||||||
|
if(FLATBUFFERS_LIBCXX_WITH_CLANG)
|
||||||
|
if(NOT "${CMAKE_SYSTEM_NAME}" MATCHES "Linux")
|
||||||
|
set(CMAKE_CXX_FLAGS
|
||||||
|
"${CMAKE_CXX_FLAGS} -stdlib=libc++")
|
||||||
|
endif()
|
||||||
|
if(NOT ("${CMAKE_SYSTEM_NAME}" MATCHES "FreeBSD" OR
|
||||||
|
"${CMAKE_SYSTEM_NAME}" MATCHES "Linux"))
|
||||||
|
set(CMAKE_EXE_LINKER_FLAGS
|
||||||
|
"${CMAKE_EXE_LINKER_FLAGS} -lc++abi")
|
||||||
|
endif()
|
||||||
|
endif()
|
||||||
|
|
||||||
|
# Certain platforms such as ARM do not use signed chars by default
|
||||||
|
# which causes issues with certain bounds checks.
|
||||||
|
set(CMAKE_CXX_FLAGS
|
||||||
|
"${CMAKE_CXX_FLAGS} -fsigned-char")
|
||||||
|
|
||||||
|
endif()
|
||||||
|
|
||||||
|
# Append FLATBUFFERS_CXX_FLAGS to CMAKE_CXX_FLAGS.
|
||||||
|
if(DEFINED FLATBUFFERS_CXX_FLAGS AND NOT EXISTS "${CMAKE_TOOLCHAIN_FILE}")
|
||||||
|
message(STATUS "extend CXX_FLAGS with ${FLATBUFFERS_CXX_FLAGS}")
|
||||||
|
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${FLATBUFFERS_CXX_FLAGS}")
|
||||||
|
endif()
|
||||||
|
message(STATUS "CMAKE_CXX_FLAGS: ${CMAKE_CXX_FLAGS}")
|
||||||
|
|
||||||
|
if(FLATBUFFERS_CODE_COVERAGE)
|
||||||
|
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g -fprofile-arcs -ftest-coverage")
|
||||||
|
set(CMAKE_EXE_LINKER_FLAGS
|
||||||
|
"${CMAKE_EXE_LINKER_FLAGS} -fprofile-arcs -ftest-coverage")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
function(add_fsanitize_to_target _target _sanitizer)
|
||||||
|
if(WIN32)
|
||||||
|
target_compile_definitions(${_target} PRIVATE FLATBUFFERS_MEMORY_LEAK_TRACKING)
|
||||||
|
message(STATUS "Sanitizer MSVC::_CrtDumpMemoryLeaks added to ${_target}")
|
||||||
|
else()
|
||||||
|
# FLATBUFFERS_CODE_SANITIZE: boolean {ON,OFF,YES,NO} or string with list of sanitizer.
|
||||||
|
# List of sanitizer is string starts with '=': "=address,undefined,thread,memory".
|
||||||
|
if((${CMAKE_CXX_COMPILER_ID} MATCHES "Clang") OR
|
||||||
|
((${CMAKE_CXX_COMPILER_ID} MATCHES "GNU") AND NOT (CMAKE_CXX_COMPILER_VERSION VERSION_LESS "4.9"))
|
||||||
|
)
|
||||||
|
set(_sanitizer_flags "=address,undefined")
|
||||||
|
if(_sanitizer MATCHES "=.*")
|
||||||
|
# override default by user-defined sanitizer list
|
||||||
|
set(_sanitizer_flags ${_sanitizer})
|
||||||
|
endif()
|
||||||
|
target_compile_options(${_target} PRIVATE
|
||||||
|
-g -fsigned-char -fno-omit-frame-pointer
|
||||||
|
"-fsanitize${_sanitizer_flags}")
|
||||||
|
target_link_libraries(${_target} PRIVATE
|
||||||
|
"-fsanitize${_sanitizer_flags}")
|
||||||
|
set_property(TARGET ${_target} PROPERTY POSITION_INDEPENDENT_CODE ON)
|
||||||
|
message(STATUS "Sanitizer ${_sanitizer_flags} added to ${_target}")
|
||||||
|
endif()
|
||||||
|
endif()
|
||||||
|
endfunction()
|
||||||
|
|
||||||
|
function(add_pch_to_target _target _pch_header)
|
||||||
|
if(COMMAND target_precompile_headers)
|
||||||
|
target_precompile_headers(${_target} PRIVATE ${_pch_header})
|
||||||
|
if(NOT MSVC)
|
||||||
|
set_source_files_properties(src/util.cpp PROPERTIES SKIP_PRECOMPILE_HEADERS ON)
|
||||||
|
endif()
|
||||||
|
endif()
|
||||||
|
endfunction()
|
||||||
|
|
||||||
|
if(BIICODE)
|
||||||
|
include(biicode/cmake/biicode.cmake)
|
||||||
|
return()
|
||||||
|
endif()
|
||||||
|
|
||||||
|
include_directories(include)
|
||||||
|
include_directories(grpc)
|
||||||
|
|
||||||
|
if(FLATBUFFERS_BUILD_FLATLIB)
|
||||||
|
add_library(flatbuffers STATIC ${FlatBuffers_Library_SRCS})
|
||||||
|
# Attach header directory for when build via add_subdirectory().
|
||||||
|
target_include_directories(flatbuffers INTERFACE
|
||||||
|
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>)
|
||||||
|
target_compile_options(flatbuffers PRIVATE "${FLATBUFFERS_PRIVATE_CXX_FLAGS}")
|
||||||
|
if(FLATBUFFERS_ENABLE_PCH)
|
||||||
|
add_pch_to_target(flatbuffers include/flatbuffers/pch/pch.h)
|
||||||
|
endif()
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if(FLATBUFFERS_BUILD_FLATC)
|
||||||
|
add_executable(flatc ${FlatBuffers_Compiler_SRCS})
|
||||||
|
if(FLATBUFFERS_ENABLE_PCH)
|
||||||
|
add_pch_to_target(flatc include/flatbuffers/pch/flatc_pch.h)
|
||||||
|
endif()
|
||||||
|
target_compile_options(flatc PRIVATE "${FLATBUFFERS_PRIVATE_CXX_FLAGS}")
|
||||||
|
if(FLATBUFFERS_CODE_SANITIZE AND NOT WIN32)
|
||||||
|
add_fsanitize_to_target(flatc ${FLATBUFFERS_CODE_SANITIZE})
|
||||||
|
endif()
|
||||||
|
if(NOT FLATBUFFERS_FLATC_EXECUTABLE)
|
||||||
|
set(FLATBUFFERS_FLATC_EXECUTABLE $<TARGET_FILE:flatc>)
|
||||||
|
endif()
|
||||||
|
if(MSVC)
|
||||||
|
# Make flatc.exe not depend on runtime dlls for easy distribution.
|
||||||
|
target_compile_options(flatc PUBLIC $<$<CONFIG:Release>:/MT>)
|
||||||
|
endif()
|
||||||
|
if(FLATBUFFERS_STATIC_FLATC AND NOT MSVC)
|
||||||
|
target_link_libraries(flatc PRIVATE -static)
|
||||||
|
endif()
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if(FLATBUFFERS_BUILD_FLATHASH)
|
||||||
|
add_executable(flathash ${FlatHash_SRCS})
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if(FLATBUFFERS_BUILD_SHAREDLIB)
|
||||||
|
add_library(flatbuffers_shared SHARED ${FlatBuffers_Library_SRCS})
|
||||||
|
|
||||||
|
# Shared object version: "major.minor.micro"
|
||||||
|
# - micro updated every release when there is no API/ABI changes
|
||||||
|
# - minor updated when there are additions in API/ABI
|
||||||
|
# - major (ABI number) updated when there are changes in ABI (or removals)
|
||||||
|
set(FlatBuffers_Library_SONAME_MAJOR ${VERSION_MAJOR})
|
||||||
|
set(FlatBuffers_Library_SONAME_FULL "${FlatBuffers_Library_SONAME_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}")
|
||||||
|
set_target_properties(flatbuffers_shared PROPERTIES OUTPUT_NAME flatbuffers
|
||||||
|
SOVERSION "${FlatBuffers_Library_SONAME_MAJOR}"
|
||||||
|
VERSION "${FlatBuffers_Library_SONAME_FULL}")
|
||||||
|
if(FLATBUFFERS_ENABLE_PCH)
|
||||||
|
add_pch_to_target(flatbuffers_shared include/flatbuffers/pch/pch.h)
|
||||||
|
endif()
|
||||||
|
endif()
|
||||||
|
|
||||||
|
# Global list of generated files.
|
||||||
|
# Use the global property to be independent of PARENT_SCOPE.
|
||||||
|
set_property(GLOBAL PROPERTY FBS_GENERATED_OUTPUTS)
|
||||||
|
|
||||||
|
function(get_generated_output generated_files)
|
||||||
|
get_property(tmp GLOBAL PROPERTY FBS_GENERATED_OUTPUTS)
|
||||||
|
set(${generated_files} ${tmp} PARENT_SCOPE)
|
||||||
|
endfunction(get_generated_output)
|
||||||
|
|
||||||
|
function(register_generated_output file_name)
|
||||||
|
get_property(tmp GLOBAL PROPERTY FBS_GENERATED_OUTPUTS)
|
||||||
|
list(APPEND tmp ${file_name})
|
||||||
|
set_property(GLOBAL PROPERTY FBS_GENERATED_OUTPUTS ${tmp})
|
||||||
|
endfunction(register_generated_output)
|
||||||
|
|
||||||
|
function(compile_flatbuffers_schema_to_cpp_opt SRC_FBS OPT)
|
||||||
|
if(FLATBUFFERS_BUILD_LEGACY)
|
||||||
|
set(OPT ${OPT};--cpp-std c++0x)
|
||||||
|
else()
|
||||||
|
# --cpp-std is defined by flatc default settings.
|
||||||
|
endif()
|
||||||
|
message(STATUS "`${SRC_FBS}`: add generation of C++ code with '${OPT}'")
|
||||||
|
get_filename_component(SRC_FBS_DIR ${SRC_FBS} PATH)
|
||||||
|
string(REGEX REPLACE "\\.fbs$" "_generated.h" GEN_HEADER ${SRC_FBS})
|
||||||
|
add_custom_command(
|
||||||
|
OUTPUT ${GEN_HEADER}
|
||||||
|
COMMAND "${FLATBUFFERS_FLATC_EXECUTABLE}"
|
||||||
|
--cpp --gen-mutable --gen-object-api --reflect-names
|
||||||
|
--cpp-ptr-type flatbuffers::unique_ptr # Used to test with C++98 STLs
|
||||||
|
${OPT}
|
||||||
|
-I "${CMAKE_CURRENT_SOURCE_DIR}/tests/include_test"
|
||||||
|
-o "${SRC_FBS_DIR}"
|
||||||
|
"${CMAKE_CURRENT_SOURCE_DIR}/${SRC_FBS}"
|
||||||
|
DEPENDS flatc
|
||||||
|
COMMENT "Run generation: '${GEN_HEADER}'")
|
||||||
|
register_generated_output(${GEN_HEADER})
|
||||||
|
endfunction()
|
||||||
|
|
||||||
|
function(compile_flatbuffers_schema_to_cpp SRC_FBS)
|
||||||
|
compile_flatbuffers_schema_to_cpp_opt(${SRC_FBS} "--no-includes;--gen-compare")
|
||||||
|
endfunction()
|
||||||
|
|
||||||
|
function(compile_flatbuffers_schema_to_binary SRC_FBS)
|
||||||
|
message(STATUS "`${SRC_FBS}`: add generation of binary (.bfbs) schema")
|
||||||
|
get_filename_component(SRC_FBS_DIR ${SRC_FBS} PATH)
|
||||||
|
string(REGEX REPLACE "\\.fbs$" ".bfbs" GEN_BINARY_SCHEMA ${SRC_FBS})
|
||||||
|
# For details about flags see generate_code.py
|
||||||
|
add_custom_command(
|
||||||
|
OUTPUT ${GEN_BINARY_SCHEMA}
|
||||||
|
COMMAND "${FLATBUFFERS_FLATC_EXECUTABLE}"
|
||||||
|
-b --schema --bfbs-comments --bfbs-builtins
|
||||||
|
--bfbs-filenames ${SRC_FBS_DIR}
|
||||||
|
-I "${CMAKE_CURRENT_SOURCE_DIR}/tests/include_test"
|
||||||
|
-o "${SRC_FBS_DIR}"
|
||||||
|
"${CMAKE_CURRENT_SOURCE_DIR}/${SRC_FBS}"
|
||||||
|
DEPENDS flatc
|
||||||
|
COMMENT "Run generation: '${GEN_BINARY_SCHEMA}'")
|
||||||
|
register_generated_output(${GEN_BINARY_SCHEMA})
|
||||||
|
endfunction()
|
||||||
|
|
||||||
|
function(compile_flatbuffers_schema_to_embedded_binary SRC_FBS OPT)
|
||||||
|
if(FLATBUFFERS_BUILD_LEGACY)
|
||||||
|
set(OPT ${OPT};--cpp-std c++0x)
|
||||||
|
else()
|
||||||
|
# --cpp-std is defined by flatc default settings.
|
||||||
|
endif()
|
||||||
|
message(STATUS "`${SRC_FBS}`: add generation of C++ embedded binary schema code with '${OPT}'")
|
||||||
|
get_filename_component(SRC_FBS_DIR ${SRC_FBS} PATH)
|
||||||
|
string(REGEX REPLACE "\\.fbs$" "_bfbs_generated.h" GEN_BFBS_HEADER ${SRC_FBS})
|
||||||
|
# For details about flags see generate_code.py
|
||||||
|
add_custom_command(
|
||||||
|
OUTPUT ${GEN_BFBS_HEADER}
|
||||||
|
COMMAND "${FLATBUFFERS_FLATC_EXECUTABLE}"
|
||||||
|
--cpp --gen-mutable --gen-object-api --reflect-names
|
||||||
|
--cpp-ptr-type flatbuffers::unique_ptr # Used to test with C++98 STLs
|
||||||
|
${OPT}
|
||||||
|
--bfbs-comments --bfbs-builtins --bfbs-gen-embed
|
||||||
|
--bfbs-filenames ${SRC_FBS_DIR}
|
||||||
|
-I "${CMAKE_CURRENT_SOURCE_DIR}/tests/include_test"
|
||||||
|
-o "${SRC_FBS_DIR}"
|
||||||
|
"${CMAKE_CURRENT_SOURCE_DIR}/${SRC_FBS}"
|
||||||
|
DEPENDS flatc
|
||||||
|
COMMENT "Run generation: '${GEN_BFBS_HEADER}'")
|
||||||
|
register_generated_output(${GEN_BFBS_HEADER})
|
||||||
|
endfunction()
|
||||||
|
|
||||||
|
# Look if we have python 3.5 installed so that we can run the generate code
|
||||||
|
# python script after flatc is built.
|
||||||
|
find_package(PythonInterp 3.5)
|
||||||
|
|
||||||
|
if(PYTHONINTERP_FOUND AND
|
||||||
|
# Skip doing this if the MSVC version is below VS 12.
|
||||||
|
# https://cmake.org/cmake/help/latest/variable/MSVC_VERSION.html
|
||||||
|
(NOT MSVC OR MSVC_VERSION GREATER 1800))
|
||||||
|
set(GENERATION_SCRIPT ${PYTHON_EXECUTABLE} scripts/generate_code.py)
|
||||||
|
if(FLATBUFFERS_BUILD_LEGACY)
|
||||||
|
# Need to set --cpp-std c++-0x options
|
||||||
|
set(GENERATION_SCRIPT ${GENERATION_SCRIPT} --cpp-0x)
|
||||||
|
endif()
|
||||||
|
if(FLATBUFFERS_SKIP_MONSTER_EXTRA)
|
||||||
|
set(GENERATION_SCRIPT ${GENERATION_SCRIPT} --skip-monster-extra)
|
||||||
|
endif()
|
||||||
|
add_custom_command(
|
||||||
|
TARGET flatc
|
||||||
|
POST_BUILD
|
||||||
|
COMMAND ${GENERATION_SCRIPT} --flatc "${FLATBUFFERS_FLATC_EXECUTABLE}"
|
||||||
|
WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
|
||||||
|
COMMENT "Running ${GENERATION_SCRIPT}..."
|
||||||
|
VERBATIM)
|
||||||
|
else()
|
||||||
|
message("No Python3 interpreter found! Unable to generate files automatically.")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if(FLATBUFFERS_BUILD_TESTS)
|
||||||
|
file(COPY "${CMAKE_CURRENT_SOURCE_DIR}/tests" DESTINATION "${CMAKE_CURRENT_BINARY_DIR}")
|
||||||
|
file(COPY "${CMAKE_CURRENT_SOURCE_DIR}/samples" DESTINATION "${CMAKE_CURRENT_BINARY_DIR}")
|
||||||
|
|
||||||
|
# TODO Add (monster_test.fbs monsterdata_test.json)->monsterdata_test.mon
|
||||||
|
compile_flatbuffers_schema_to_cpp(tests/monster_test.fbs)
|
||||||
|
compile_flatbuffers_schema_to_binary(tests/monster_test.fbs)
|
||||||
|
compile_flatbuffers_schema_to_cpp_opt(tests/namespace_test/namespace_test1.fbs "--no-includes;--gen-compare;--gen-name-strings")
|
||||||
|
compile_flatbuffers_schema_to_cpp_opt(tests/namespace_test/namespace_test2.fbs "--no-includes;--gen-compare;--gen-name-strings")
|
||||||
|
compile_flatbuffers_schema_to_cpp_opt(tests/union_vector/union_vector.fbs "--no-includes;--gen-compare;--gen-name-strings")
|
||||||
|
compile_flatbuffers_schema_to_cpp(tests/optional_scalars.fbs)
|
||||||
|
compile_flatbuffers_schema_to_cpp_opt(tests/native_type_test.fbs "")
|
||||||
|
compile_flatbuffers_schema_to_cpp_opt(tests/arrays_test.fbs "--scoped-enums;--gen-compare")
|
||||||
|
compile_flatbuffers_schema_to_binary(tests/arrays_test.fbs)
|
||||||
|
compile_flatbuffers_schema_to_embedded_binary(tests/monster_test.fbs "--no-includes;--gen-compare")
|
||||||
|
if(NOT (MSVC AND (MSVC_VERSION LESS 1900)))
|
||||||
|
compile_flatbuffers_schema_to_cpp(tests/monster_extra.fbs) # Test floating-point NAN/INF.
|
||||||
|
endif()
|
||||||
|
include_directories(${CMAKE_CURRENT_BINARY_DIR}/tests)
|
||||||
|
add_executable(flattests ${FlatBuffers_Tests_SRCS})
|
||||||
|
add_dependencies(flattests generated_code)
|
||||||
|
set_property(TARGET flattests
|
||||||
|
PROPERTY COMPILE_DEFINITIONS FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
|
||||||
|
FLATBUFFERS_DEBUG_VERIFICATION_FAILURE=1)
|
||||||
|
if(FLATBUFFERS_CODE_SANITIZE)
|
||||||
|
add_fsanitize_to_target(flattests ${FLATBUFFERS_CODE_SANITIZE})
|
||||||
|
endif()
|
||||||
|
|
||||||
|
compile_flatbuffers_schema_to_cpp(samples/monster.fbs)
|
||||||
|
compile_flatbuffers_schema_to_binary(samples/monster.fbs)
|
||||||
|
include_directories(${CMAKE_CURRENT_BINARY_DIR}/samples)
|
||||||
|
add_executable(flatsamplebinary ${FlatBuffers_Sample_Binary_SRCS})
|
||||||
|
add_dependencies(flatsamplebinary generated_code)
|
||||||
|
add_executable(flatsampletext ${FlatBuffers_Sample_Text_SRCS})
|
||||||
|
add_dependencies(flatsampletext generated_code)
|
||||||
|
add_executable(flatsamplebfbs ${FlatBuffers_Sample_BFBS_SRCS})
|
||||||
|
add_dependencies(flatsamplebfbs generated_code)
|
||||||
|
|
||||||
|
if(FLATBUFFERS_BUILD_CPP17)
|
||||||
|
# Don't generate header for flattests_cpp17 target.
|
||||||
|
# This target uses "generated_cpp17/monster_test_generated.h"
|
||||||
|
# produced by direct call of generate_code.py script.
|
||||||
|
add_executable(flattests_cpp17 ${FlatBuffers_Tests_CPP17_SRCS})
|
||||||
|
add_dependencies(flattests_cpp17 generated_code)
|
||||||
|
target_compile_features(flattests_cpp17 PRIVATE cxx_std_17)
|
||||||
|
target_compile_definitions(flattests_cpp17 PRIVATE
|
||||||
|
FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
|
||||||
|
FLATBUFFERS_DEBUG_VERIFICATION_FAILURE=1
|
||||||
|
)
|
||||||
|
if(FLATBUFFERS_CODE_SANITIZE)
|
||||||
|
add_fsanitize_to_target(flattests_cpp17 ${FLATBUFFERS_CODE_SANITIZE})
|
||||||
|
endif()
|
||||||
|
endif(FLATBUFFERS_BUILD_CPP17)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if(FLATBUFFERS_BUILD_GRPCTEST)
|
||||||
|
if(CMAKE_COMPILER_IS_GNUCXX)
|
||||||
|
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unused-parameter -Wno-shadow")
|
||||||
|
endif()
|
||||||
|
if(NOT GRPC_INSTALL_PATH)
|
||||||
|
message(SEND_ERROR "GRPC_INSTALL_PATH variable is not defined. See grpc/README.md")
|
||||||
|
endif()
|
||||||
|
if(NOT PROTOBUF_DOWNLOAD_PATH)
|
||||||
|
message(SEND_ERROR "PROTOBUF_DOWNLOAD_PATH variable is not defined. See grpc/README.md")
|
||||||
|
endif()
|
||||||
|
INCLUDE_DIRECTORIES(${GRPC_INSTALL_PATH}/include)
|
||||||
|
INCLUDE_DIRECTORIES(${PROTOBUF_DOWNLOAD_PATH}/src)
|
||||||
|
find_package(Threads REQUIRED)
|
||||||
|
list(APPEND CMAKE_PREFIX_PATH ${GRPC_INSTALL_PATH})
|
||||||
|
find_package(absl CONFIG REQUIRED)
|
||||||
|
find_package(protobuf CONFIG REQUIRED)
|
||||||
|
find_package(gRPC CONFIG REQUIRED)
|
||||||
|
add_executable(grpctest ${FlatBuffers_GRPCTest_SRCS})
|
||||||
|
add_dependencies(grpctest generated_code)
|
||||||
|
target_link_libraries(grpctest PRIVATE gRPC::grpc++_unsecure gRPC::grpc_unsecure gRPC::gpr pthread dl)
|
||||||
|
if(FLATBUFFERS_CODE_SANITIZE AND NOT WIN32)
|
||||||
|
# GRPC test has problems with alignment and will fail under ASAN/UBSAN.
|
||||||
|
# add_fsanitize_to_target(grpctest ${FLATBUFFERS_CODE_SANITIZE})
|
||||||
|
endif()
|
||||||
|
endif()
|
||||||
|
|
||||||
|
|
||||||
|
if(FLATBUFFERS_INSTALL)
|
||||||
|
include(GNUInstallDirs)
|
||||||
|
|
||||||
|
install(DIRECTORY include/flatbuffers DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
|
||||||
|
|
||||||
|
set(FB_CMAKE_DIR "${CMAKE_INSTALL_LIBDIR}/cmake/flatbuffers")
|
||||||
|
|
||||||
|
configure_file(CMake/FlatBuffersConfigVersion.cmake.in FlatBuffersConfigVersion.cmake @ONLY)
|
||||||
|
install(
|
||||||
|
FILES "CMake/FlatBuffersConfig.cmake" "${CMAKE_CURRENT_BINARY_DIR}/FlatBuffersConfigVersion.cmake"
|
||||||
|
DESTINATION ${FB_CMAKE_DIR}
|
||||||
|
)
|
||||||
|
|
||||||
|
if(FLATBUFFERS_BUILD_FLATLIB)
|
||||||
|
if(CMAKE_VERSION VERSION_LESS 3.0)
|
||||||
|
install(
|
||||||
|
TARGETS flatbuffers EXPORT FlatBuffersTargets
|
||||||
|
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
|
||||||
|
)
|
||||||
|
else()
|
||||||
|
install(
|
||||||
|
TARGETS flatbuffers EXPORT FlatBuffersTargets
|
||||||
|
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
|
||||||
|
INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
|
||||||
|
)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
install(EXPORT FlatBuffersTargets
|
||||||
|
FILE FlatBuffersTargets.cmake
|
||||||
|
NAMESPACE flatbuffers::
|
||||||
|
DESTINATION ${FB_CMAKE_DIR}
|
||||||
|
)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if(FLATBUFFERS_BUILD_FLATC)
|
||||||
|
install(
|
||||||
|
TARGETS flatc EXPORT FlatcTargets
|
||||||
|
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
|
||||||
|
)
|
||||||
|
|
||||||
|
install(
|
||||||
|
EXPORT FlatcTargets
|
||||||
|
FILE FlatcTargets.cmake
|
||||||
|
NAMESPACE flatbuffers::
|
||||||
|
DESTINATION ${FB_CMAKE_DIR}
|
||||||
|
)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if(FLATBUFFERS_BUILD_SHAREDLIB)
|
||||||
|
if(CMAKE_VERSION VERSION_LESS 3.0)
|
||||||
|
install(
|
||||||
|
TARGETS flatbuffers_shared EXPORT FlatBuffersSharedTargets
|
||||||
|
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
|
||||||
|
RUNTIME DESTINATION ${CMAKE_INSTALL_LIBDIR}
|
||||||
|
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
|
||||||
|
)
|
||||||
|
else()
|
||||||
|
install(
|
||||||
|
TARGETS flatbuffers_shared EXPORT FlatBuffersSharedTargets
|
||||||
|
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
|
||||||
|
RUNTIME DESTINATION ${CMAKE_INSTALL_LIBDIR}
|
||||||
|
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
|
||||||
|
INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
|
||||||
|
)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
install(
|
||||||
|
EXPORT FlatBuffersSharedTargets
|
||||||
|
FILE FlatBuffersSharedTargets.cmake
|
||||||
|
NAMESPACE flatbuffers::
|
||||||
|
DESTINATION ${FB_CMAKE_DIR}
|
||||||
|
)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if(FLATBUFFERS_BUILD_SHAREDLIB OR FLATBUFFERS_BUILD_FLATLIB)
|
||||||
|
configure_file(CMake/flatbuffers.pc.in flatbuffers.pc @ONLY)
|
||||||
|
install(
|
||||||
|
FILES "${CMAKE_CURRENT_BINARY_DIR}/flatbuffers.pc"
|
||||||
|
DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig
|
||||||
|
)
|
||||||
|
endif()
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if(FLATBUFFERS_BUILD_TESTS)
|
||||||
|
enable_testing()
|
||||||
|
|
||||||
|
add_test(NAME flattests COMMAND flattests)
|
||||||
|
if(FLATBUFFERS_BUILD_CPP17)
|
||||||
|
add_test(NAME flattests_cpp17 COMMAND flattests_cpp17)
|
||||||
|
endif()
|
||||||
|
if(FLATBUFFERS_BUILD_GRPCTEST)
|
||||||
|
add_test(NAME grpctest COMMAND grpctest)
|
||||||
|
endif()
|
||||||
|
endif()
|
||||||
|
|
||||||
|
# This target is sync-barrier.
|
||||||
|
# Other generate-dependent targets can depend on 'generated_code' only.
|
||||||
|
get_generated_output(fbs_generated)
|
||||||
|
if(fbs_generated)
|
||||||
|
# message(STATUS "Add generated_code target with files:${fbs_generated}")
|
||||||
|
add_custom_target(generated_code
|
||||||
|
DEPENDS ${fbs_generated}
|
||||||
|
COMMENT "All generated files were updated.")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
include(CMake/BuildFlatBuffers.cmake)
|
||||||
|
|
||||||
|
if(UNIX)
|
||||||
|
# Use of CPack only supported on Linux systems.
|
||||||
|
if(FLATBUFFERS_PACKAGE_DEBIAN)
|
||||||
|
include(CMake/PackageDebian.cmake)
|
||||||
|
include(CPack)
|
||||||
|
endif()
|
||||||
|
if (FLATBUFFERS_PACKAGE_REDHAT)
|
||||||
|
include(CMake/PackageRedhat.cmake)
|
||||||
|
include(CPack)
|
||||||
|
endif()
|
||||||
|
endif()
|
||||||
|
|
||||||
|
# Include for running Google Benchmarks.
|
||||||
|
if(FLATBUFFERS_BUILD_BENCHMARKS AND CMAKE_VERSION VERSION_GREATER 3.13)
|
||||||
|
add_subdirectory(benchmarks)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
# Add FlatBuffers::FlatBuffers interface, needed for FetchContent_Declare
|
||||||
|
add_library(FlatBuffers INTERFACE)
|
||||||
|
add_library(FlatBuffers::FlatBuffers ALIAS FlatBuffers)
|
||||||
|
target_include_directories(
|
||||||
|
FlatBuffers
|
||||||
|
INTERFACE $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||||
|
$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}/include>)
|
||||||
3
CMake/FlatBuffersConfig.cmake
Normal file
3
CMake/FlatBuffersConfig.cmake
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
include("${CMAKE_CURRENT_LIST_DIR}/FlatBuffersTargets.cmake" OPTIONAL)
|
||||||
|
include("${CMAKE_CURRENT_LIST_DIR}/FlatcTargets.cmake" OPTIONAL)
|
||||||
|
include("${CMAKE_CURRENT_LIST_DIR}/FlatBuffersSharedTargets.cmake" OPTIONAL)
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
include("${CMAKE_CURRENT_LIST_DIR}/FlatbuffersTargets.cmake" OPTIONAL)
|
|
||||||
include("${CMAKE_CURRENT_LIST_DIR}/FlatcTargets.cmake" OPTIONAL)
|
|
||||||
include("${CMAKE_CURRENT_LIST_DIR}/FlatbuffersSharedTargets.cmake" OPTIONAL)
|
|
||||||
|
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
set(VERSION_MAJOR 2)
|
set(VERSION_MAJOR 2)
|
||||||
set(VERSION_MINOR 0)
|
set(VERSION_MINOR 0)
|
||||||
set(VERSION_PATCH 5)
|
set(VERSION_PATCH 8)
|
||||||
set(VERSION_COMMIT 0)
|
set(VERSION_COMMIT 0)
|
||||||
|
|
||||||
find_program(GIT git)
|
find_program(GIT git)
|
||||||
if(GIT)
|
if(GIT AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/.git")
|
||||||
execute_process(
|
execute_process(
|
||||||
COMMAND ${GIT} describe --tags
|
COMMAND ${GIT} describe --tags
|
||||||
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
|
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
|
||||||
@@ -14,10 +14,19 @@ if(GIT)
|
|||||||
)
|
)
|
||||||
|
|
||||||
if(GIT_DESCRIBE_RESULT EQUAL 0)
|
if(GIT_DESCRIBE_RESULT EQUAL 0)
|
||||||
string(REGEX REPLACE "^v([0-9]+)\\..*" "\\1" VERSION_MAJOR "${GIT_DESCRIBE_DIRTY}")
|
# Test if the most recent Git tag matches the pattern "v<major>.<minor>.<patch>*"
|
||||||
string(REGEX REPLACE "^v[0-9]+\\.([0-9]+).*" "\\1" VERSION_MINOR "${GIT_DESCRIBE_DIRTY}")
|
if(GIT_DESCRIBE_DIRTY MATCHES "^v[0-9]+\\.[0-9]+\\.[0-9]+.*")
|
||||||
string(REGEX REPLACE "^v[0-9]+\\.[0-9]+\\.([0-9]+).*" "\\1" VERSION_PATCH "${GIT_DESCRIBE_DIRTY}")
|
string(REGEX REPLACE "^v([0-9]+)\\..*" "\\1" VERSION_MAJOR "${GIT_DESCRIBE_DIRTY}")
|
||||||
string(REGEX REPLACE "^v[0-9]+\\.[0-9]+\\.[0-9]+\\-([0-9]+).*" "\\1" VERSION_COMMIT "${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()
|
else()
|
||||||
message(WARNING "git describe failed with exit code: ${GIT_DESCRIBE_RESULT}")
|
message(WARNING "git describe failed with exit code: ${GIT_DESCRIBE_RESULT}")
|
||||||
endif()
|
endif()
|
||||||
|
|||||||
424
CMakeLists.txt
424
CMakeLists.txt
@@ -1,17 +1,33 @@
|
|||||||
cmake_minimum_required(VERSION 2.8.12)
|
# This is the legacy minimum version flatbuffers supported for a while.
|
||||||
|
cmake_minimum_required(VERSION 2.8.12...3.22.1)
|
||||||
|
|
||||||
|
# CMake version 3.16 is the 'de-facto' minimum version for flatbuffers. If the
|
||||||
|
# current cmake is older than this, warn the user and include the legacy file to
|
||||||
|
# provide some level of support.
|
||||||
|
if(CMAKE_VERSION VERSION_LESS 3.16)
|
||||||
|
message(WARNING "Using cmake version ${CMAKE_VERSION} which is older than "
|
||||||
|
"our target version of 3.16. This will use the legacy CMakeLists.txt that "
|
||||||
|
"supports version 2.8.12 and higher, but not actively maintained. Consider "
|
||||||
|
"upgrading cmake to a newer version, as this may become a fatal error in the "
|
||||||
|
"future.")
|
||||||
|
# Use the legacy version of CMakeLists.txt
|
||||||
|
include(CMake/CMakeLists_legacy.cmake.in)
|
||||||
|
return()
|
||||||
|
endif()
|
||||||
|
|
||||||
|
# Attempt to read the current version of flatbuffers by looking at the latest tag.
|
||||||
|
include(CMake/Version.cmake)
|
||||||
|
|
||||||
if (POLICY CMP0048)
|
if (POLICY CMP0048)
|
||||||
cmake_policy(SET CMP0048 NEW)
|
cmake_policy(SET CMP0048 NEW)
|
||||||
project(FlatBuffers
|
project(FlatBuffers
|
||||||
DESCRIPTION "Flatbuffers serialization library"
|
DESCRIPTION "Flatbuffers serialization library"
|
||||||
VERSION 2.0.0
|
VERSION ${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}
|
||||||
LANGUAGES CXX)
|
LANGUAGES CXX)
|
||||||
else()
|
else()
|
||||||
project(FlatBuffers)
|
project(FlatBuffers)
|
||||||
endif (POLICY CMP0048)
|
endif (POLICY CMP0048)
|
||||||
|
|
||||||
include(CMake/Version.cmake)
|
|
||||||
|
|
||||||
# generate compile_commands.json
|
# generate compile_commands.json
|
||||||
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
|
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
|
||||||
|
|
||||||
@@ -26,8 +42,7 @@ option(FLATBUFFERS_BUILD_FLATC "Enable the build of the flatbuffers compiler"
|
|||||||
option(FLATBUFFERS_STATIC_FLATC "Build flatbuffers compiler with -static flag"
|
option(FLATBUFFERS_STATIC_FLATC "Build flatbuffers compiler with -static flag"
|
||||||
OFF)
|
OFF)
|
||||||
option(FLATBUFFERS_BUILD_FLATHASH "Enable the build of flathash" ON)
|
option(FLATBUFFERS_BUILD_FLATHASH "Enable the build of flathash" ON)
|
||||||
option(FLATBUFFERS_BUILD_BENCHMARKS "Enable the build of flatbenchmark. \"
|
option(FLATBUFFERS_BUILD_BENCHMARKS "Enable the build of flatbenchmark."
|
||||||
Requires C++11."
|
|
||||||
OFF)
|
OFF)
|
||||||
option(FLATBUFFERS_BUILD_GRPCTEST "Enable the build of grpctest" OFF)
|
option(FLATBUFFERS_BUILD_GRPCTEST "Enable the build of grpctest" OFF)
|
||||||
option(FLATBUFFERS_BUILD_SHAREDLIB
|
option(FLATBUFFERS_BUILD_SHAREDLIB
|
||||||
@@ -59,6 +74,26 @@ option(FLATBUFFERS_ENABLE_PCH
|
|||||||
option(FLATBUFFERS_SKIP_MONSTER_EXTRA
|
option(FLATBUFFERS_SKIP_MONSTER_EXTRA
|
||||||
"Skip generating monster_extra.fbs that contains non-supported numerical\"
|
"Skip generating monster_extra.fbs that contains non-supported numerical\"
|
||||||
types." OFF)
|
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(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)
|
if(NOT FLATBUFFERS_BUILD_FLATC AND FLATBUFFERS_BUILD_TESTS)
|
||||||
message(WARNING
|
message(WARNING
|
||||||
@@ -77,7 +112,7 @@ if(NOT DEFINED FLATBUFFERS_LOCALE_INDEPENDENT)
|
|||||||
include(CheckCXXSymbolExists)
|
include(CheckCXXSymbolExists)
|
||||||
|
|
||||||
set(FLATBUFFERS_LOCALE_INDEPENDENT 0)
|
set(FLATBUFFERS_LOCALE_INDEPENDENT 0)
|
||||||
if(MSVC)
|
if(MSVC_LIKE)
|
||||||
check_cxx_symbol_exists(_strtof_l stdlib.h FLATBUFFERS_HAS_STRTOF_L)
|
check_cxx_symbol_exists(_strtof_l stdlib.h FLATBUFFERS_HAS_STRTOF_L)
|
||||||
check_cxx_symbol_exists(_strtoui64_l stdlib.h FLATBUFFERS_HAS_STRTOULL_L)
|
check_cxx_symbol_exists(_strtoui64_l stdlib.h FLATBUFFERS_HAS_STRTOULL_L)
|
||||||
else()
|
else()
|
||||||
@@ -102,6 +137,7 @@ set(FlatBuffers_Library_SRCS
|
|||||||
include/flatbuffers/flatbuffer_builder.h
|
include/flatbuffers/flatbuffer_builder.h
|
||||||
include/flatbuffers/flatbuffers.h
|
include/flatbuffers/flatbuffers.h
|
||||||
include/flatbuffers/flexbuffers.h
|
include/flatbuffers/flexbuffers.h
|
||||||
|
include/flatbuffers/flex_flat_util.h
|
||||||
include/flatbuffers/hash.h
|
include/flatbuffers/hash.h
|
||||||
include/flatbuffers/idl.h
|
include/flatbuffers/idl.h
|
||||||
include/flatbuffers/minireflect.h
|
include/flatbuffers/minireflect.h
|
||||||
@@ -140,11 +176,18 @@ set(FlatBuffers_Compiler_SRCS
|
|||||||
src/idl_gen_grpc.cpp
|
src/idl_gen_grpc.cpp
|
||||||
src/idl_gen_json_schema.cpp
|
src/idl_gen_json_schema.cpp
|
||||||
src/idl_gen_swift.cpp
|
src/idl_gen_swift.cpp
|
||||||
|
src/idl_namer.h
|
||||||
|
src/namer.h
|
||||||
src/flatc.cpp
|
src/flatc.cpp
|
||||||
src/flatc_main.cpp
|
src/flatc_main.cpp
|
||||||
src/bfbs_gen.h
|
src/bfbs_gen.h
|
||||||
src/bfbs_gen_lua.h
|
src/bfbs_gen_lua.h
|
||||||
|
src/bfbs_namer.h
|
||||||
include/flatbuffers/code_generators.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_lua.cpp
|
||||||
src/code_generators.cpp
|
src/code_generators.cpp
|
||||||
grpc/src/compiler/schema_interface.h
|
grpc/src/compiler/schema_interface.h
|
||||||
@@ -170,11 +213,21 @@ set(FlatHash_SRCS
|
|||||||
set(FlatBuffers_Tests_SRCS
|
set(FlatBuffers_Tests_SRCS
|
||||||
${FlatBuffers_Library_SRCS}
|
${FlatBuffers_Library_SRCS}
|
||||||
src/idl_gen_fbs.cpp
|
src/idl_gen_fbs.cpp
|
||||||
|
tests/evolution_test.cpp
|
||||||
|
tests/flexbuffers_test.cpp
|
||||||
|
tests/fuzz_test.cpp
|
||||||
|
tests/json_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.cpp
|
||||||
tests/test_assert.h
|
tests/test_assert.h
|
||||||
tests/test_assert.cpp
|
tests/test_assert.cpp
|
||||||
tests/test_builder.h
|
tests/test_builder.h
|
||||||
tests/test_builder.cpp
|
tests/test_builder.cpp
|
||||||
|
tests/util_test.cpp
|
||||||
tests/native_type_test_impl.h
|
tests/native_type_test_impl.h
|
||||||
tests/native_type_test_impl.cpp
|
tests/native_type_test_impl.cpp
|
||||||
include/flatbuffers/code_generators.h
|
include/flatbuffers/code_generators.h
|
||||||
@@ -196,6 +249,8 @@ set(FlatBuffers_Tests_SRCS
|
|||||||
${CMAKE_CURRENT_BINARY_DIR}/tests/monster_test_bfbs_generated.h
|
${CMAKE_CURRENT_BINARY_DIR}/tests/monster_test_bfbs_generated.h
|
||||||
# file generate by running compiler on tests/optional_scalars.fbs
|
# file generate by running compiler on tests/optional_scalars.fbs
|
||||||
${CMAKE_CURRENT_BINARY_DIR}/tests/optional_scalars_generated.h
|
${CMAKE_CURRENT_BINARY_DIR}/tests/optional_scalars_generated.h
|
||||||
|
# file generate by running compiler on tests/native_inline_table_test.fbs
|
||||||
|
${CMAKE_CURRENT_BINARY_DIR}/tests/native_inline_table_test_generated.h
|
||||||
)
|
)
|
||||||
|
|
||||||
set(FlatBuffers_Tests_CPP17_SRCS
|
set(FlatBuffers_Tests_CPP17_SRCS
|
||||||
@@ -248,78 +303,8 @@ set(FlatBuffers_GRPCTest_SRCS
|
|||||||
${CMAKE_CURRENT_BINARY_DIR}/tests/monster_test_generated.h
|
${CMAKE_CURRENT_BINARY_DIR}/tests/monster_test_generated.h
|
||||||
)
|
)
|
||||||
|
|
||||||
# source_group(Compiler FILES ${FlatBuffers_Compiler_SRCS})
|
# TODO(dbaileychess): Figure out how this would now work. I posted a question on
|
||||||
# source_group(Tests FILES ${FlatBuffers_Tests_SRCS})
|
# https://stackoverflow.com/questions/71772330/override-target-compile-options-via-cmake-command-line.
|
||||||
|
|
||||||
if(EXISTS "${CMAKE_TOOLCHAIN_FILE}")
|
|
||||||
# do not apply any global settings if the toolchain
|
|
||||||
# is being configured externally
|
|
||||||
message(STATUS "Using toolchain file: ${CMAKE_TOOLCHAIN_FILE}.")
|
|
||||||
elseif(CMAKE_COMPILER_IS_GNUCXX)
|
|
||||||
if(CYGWIN)
|
|
||||||
set(CMAKE_CXX_FLAGS
|
|
||||||
"${CMAKE_CXX_FLAGS} -std=gnu++11")
|
|
||||||
else(CYGWIN)
|
|
||||||
set(CMAKE_CXX_FLAGS
|
|
||||||
"${CMAKE_CXX_FLAGS} -std=c++0x")
|
|
||||||
endif(CYGWIN)
|
|
||||||
set(CMAKE_CXX_FLAGS
|
|
||||||
"${CMAKE_CXX_FLAGS} -Wall -pedantic -Werror -Wextra -Werror=shadow")
|
|
||||||
set(FLATBUFFERS_PRIVATE_CXX_FLAGS "-Wold-style-cast")
|
|
||||||
if (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 4.4)
|
|
||||||
if (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 7.0)
|
|
||||||
set(CMAKE_CXX_FLAGS
|
|
||||||
"${CMAKE_CXX_FLAGS} -faligned-new -Werror=implicit-fallthrough=2")
|
|
||||||
endif()
|
|
||||||
set(CMAKE_CXX_FLAGS
|
|
||||||
"${CMAKE_CXX_FLAGS} -Wunused-result -Werror=unused-result -Wunused-parameter -Werror=unused-parameter")
|
|
||||||
endif()
|
|
||||||
|
|
||||||
# Certain platforms such as ARM do not use signed chars by default
|
|
||||||
# which causes issues with certain bounds checks.
|
|
||||||
set(CMAKE_CXX_FLAGS
|
|
||||||
"${CMAKE_CXX_FLAGS} -fsigned-char")
|
|
||||||
|
|
||||||
elseif(${CMAKE_CXX_COMPILER_ID} MATCHES "Clang")
|
|
||||||
if(APPLE)
|
|
||||||
set(CMAKE_OSX_ARCHITECTURES "arm64;x86_64")
|
|
||||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
|
|
||||||
else()
|
|
||||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x")
|
|
||||||
endif()
|
|
||||||
|
|
||||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -pedantic -Werror -Wextra -Wno-unused-parameter")
|
|
||||||
set(FLATBUFFERS_PRIVATE_CXX_FLAGS "-Wold-style-cast")
|
|
||||||
if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 3.8)
|
|
||||||
list(APPEND FLATBUFFERS_PRIVATE_CXX_FLAGS "-Wimplicit-fallthrough" "-Wextra-semi" "-Werror=unused-private-field") # enable warning
|
|
||||||
endif()
|
|
||||||
if(FLATBUFFERS_LIBCXX_WITH_CLANG)
|
|
||||||
if(NOT "${CMAKE_SYSTEM_NAME}" MATCHES "Linux")
|
|
||||||
set(CMAKE_CXX_FLAGS
|
|
||||||
"${CMAKE_CXX_FLAGS} -stdlib=libc++")
|
|
||||||
endif()
|
|
||||||
if(NOT ("${CMAKE_SYSTEM_NAME}" MATCHES "FreeBSD" OR
|
|
||||||
"${CMAKE_SYSTEM_NAME}" MATCHES "Linux"))
|
|
||||||
set(CMAKE_EXE_LINKER_FLAGS
|
|
||||||
"${CMAKE_EXE_LINKER_FLAGS} -lc++abi")
|
|
||||||
endif()
|
|
||||||
endif()
|
|
||||||
|
|
||||||
# Certain platforms such as ARM do not use signed chars by default
|
|
||||||
# which causes issues with certain bounds checks.
|
|
||||||
set(CMAKE_CXX_FLAGS
|
|
||||||
"${CMAKE_CXX_FLAGS} -fsigned-char")
|
|
||||||
|
|
||||||
elseif(MSVC)
|
|
||||||
# Visual Studio pedantic build settings
|
|
||||||
# warning C4512: assignment operator could not be generated
|
|
||||||
# warning C4316: object allocated on the heap may not be aligned
|
|
||||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /W4 /WX /wd4512 /wd4316")
|
|
||||||
|
|
||||||
# multi-core build.
|
|
||||||
add_definitions("/MP")
|
|
||||||
endif()
|
|
||||||
|
|
||||||
# Append FLATBUFFERS_CXX_FLAGS to CMAKE_CXX_FLAGS.
|
# Append FLATBUFFERS_CXX_FLAGS to CMAKE_CXX_FLAGS.
|
||||||
if(DEFINED FLATBUFFERS_CXX_FLAGS AND NOT EXISTS "${CMAKE_TOOLCHAIN_FILE}")
|
if(DEFINED FLATBUFFERS_CXX_FLAGS AND NOT EXISTS "${CMAKE_TOOLCHAIN_FILE}")
|
||||||
message(STATUS "extend CXX_FLAGS with ${FLATBUFFERS_CXX_FLAGS}")
|
message(STATUS "extend CXX_FLAGS with ${FLATBUFFERS_CXX_FLAGS}")
|
||||||
@@ -327,12 +312,6 @@ if(DEFINED FLATBUFFERS_CXX_FLAGS AND NOT EXISTS "${CMAKE_TOOLCHAIN_FILE}")
|
|||||||
endif()
|
endif()
|
||||||
message(STATUS "CMAKE_CXX_FLAGS: ${CMAKE_CXX_FLAGS}")
|
message(STATUS "CMAKE_CXX_FLAGS: ${CMAKE_CXX_FLAGS}")
|
||||||
|
|
||||||
if(FLATBUFFERS_CODE_COVERAGE)
|
|
||||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g -fprofile-arcs -ftest-coverage")
|
|
||||||
set(CMAKE_EXE_LINKER_FLAGS
|
|
||||||
"${CMAKE_EXE_LINKER_FLAGS} -fprofile-arcs -ftest-coverage")
|
|
||||||
endif()
|
|
||||||
|
|
||||||
function(add_fsanitize_to_target _target _sanitizer)
|
function(add_fsanitize_to_target _target _sanitizer)
|
||||||
if(WIN32)
|
if(WIN32)
|
||||||
target_compile_definitions(${_target} PRIVATE FLATBUFFERS_MEMORY_LEAK_TRACKING)
|
target_compile_definitions(${_target} PRIVATE FLATBUFFERS_MEMORY_LEAK_TRACKING)
|
||||||
@@ -368,20 +347,128 @@ function(add_pch_to_target _target _pch_header)
|
|||||||
endif()
|
endif()
|
||||||
endfunction()
|
endfunction()
|
||||||
|
|
||||||
if(BIICODE)
|
|
||||||
include(biicode/cmake/biicode.cmake)
|
|
||||||
return()
|
|
||||||
endif()
|
|
||||||
|
|
||||||
include_directories(include)
|
include_directories(include)
|
||||||
include_directories(grpc)
|
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()
|
||||||
|
if("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang")
|
||||||
|
set(IS_CLANG ON)
|
||||||
|
else()
|
||||||
|
set(IS_CLANG OFF)
|
||||||
|
endif()
|
||||||
|
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}>:
|
||||||
|
-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)
|
if(FLATBUFFERS_BUILD_FLATLIB)
|
||||||
add_library(flatbuffers STATIC ${FlatBuffers_Library_SRCS})
|
add_library(flatbuffers STATIC ${FlatBuffers_Library_SRCS})
|
||||||
|
|
||||||
# Attach header directory for when build via add_subdirectory().
|
# Attach header directory for when build via add_subdirectory().
|
||||||
target_include_directories(flatbuffers INTERFACE
|
target_include_directories(flatbuffers
|
||||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>)
|
INTERFACE
|
||||||
target_compile_options(flatbuffers PRIVATE "${FLATBUFFERS_PRIVATE_CXX_FLAGS}")
|
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||||
|
)
|
||||||
|
target_link_libraries(flatbuffers PRIVATE $<BUILD_INTERFACE:ProjectConfig>)
|
||||||
|
|
||||||
if(FLATBUFFERS_ENABLE_PCH)
|
if(FLATBUFFERS_ENABLE_PCH)
|
||||||
add_pch_to_target(flatbuffers include/flatbuffers/pch/pch.h)
|
add_pch_to_target(flatbuffers include/flatbuffers/pch/pch.h)
|
||||||
endif()
|
endif()
|
||||||
@@ -392,17 +479,21 @@ if(FLATBUFFERS_BUILD_FLATC)
|
|||||||
if(FLATBUFFERS_ENABLE_PCH)
|
if(FLATBUFFERS_ENABLE_PCH)
|
||||||
add_pch_to_target(flatc include/flatbuffers/pch/flatc_pch.h)
|
add_pch_to_target(flatc include/flatbuffers/pch/flatc_pch.h)
|
||||||
endif()
|
endif()
|
||||||
target_compile_options(flatc PRIVATE "${FLATBUFFERS_PRIVATE_CXX_FLAGS}")
|
|
||||||
|
target_link_libraries(flatc PRIVATE $<BUILD_INTERFACE:ProjectConfig>)
|
||||||
|
target_compile_options(flatc
|
||||||
|
PUBLIC
|
||||||
|
$<$<AND:$<BOOL:${MSVC_LIKE}>,$<CONFIG:Release>>:
|
||||||
|
/MT
|
||||||
|
>
|
||||||
|
)
|
||||||
|
|
||||||
if(FLATBUFFERS_CODE_SANITIZE AND NOT WIN32)
|
if(FLATBUFFERS_CODE_SANITIZE AND NOT WIN32)
|
||||||
add_fsanitize_to_target(flatc ${FLATBUFFERS_CODE_SANITIZE})
|
add_fsanitize_to_target(flatc ${FLATBUFFERS_CODE_SANITIZE})
|
||||||
endif()
|
endif()
|
||||||
if(NOT FLATBUFFERS_FLATC_EXECUTABLE)
|
if(NOT FLATBUFFERS_FLATC_EXECUTABLE)
|
||||||
set(FLATBUFFERS_FLATC_EXECUTABLE $<TARGET_FILE:flatc>)
|
set(FLATBUFFERS_FLATC_EXECUTABLE $<TARGET_FILE:flatc>)
|
||||||
endif()
|
endif()
|
||||||
if(MSVC)
|
|
||||||
# Make flatc.exe not depend on runtime dlls for easy distribution.
|
|
||||||
target_compile_options(flatc PUBLIC $<$<CONFIG:Release>:/MT>)
|
|
||||||
endif()
|
|
||||||
if(FLATBUFFERS_STATIC_FLATC AND NOT MSVC)
|
if(FLATBUFFERS_STATIC_FLATC AND NOT MSVC)
|
||||||
target_link_libraries(flatc PRIVATE -static)
|
target_link_libraries(flatc PRIVATE -static)
|
||||||
endif()
|
endif()
|
||||||
@@ -410,11 +501,12 @@ endif()
|
|||||||
|
|
||||||
if(FLATBUFFERS_BUILD_FLATHASH)
|
if(FLATBUFFERS_BUILD_FLATHASH)
|
||||||
add_executable(flathash ${FlatHash_SRCS})
|
add_executable(flathash ${FlatHash_SRCS})
|
||||||
|
target_link_libraries(flathash PRIVATE $<BUILD_INTERFACE:ProjectConfig>)
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
if(FLATBUFFERS_BUILD_SHAREDLIB)
|
if(FLATBUFFERS_BUILD_SHAREDLIB)
|
||||||
add_library(flatbuffers_shared SHARED ${FlatBuffers_Library_SRCS})
|
add_library(flatbuffers_shared SHARED ${FlatBuffers_Library_SRCS})
|
||||||
|
target_link_libraries(flatbuffers_shared PRIVATE $<BUILD_INTERFACE:ProjectConfig>)
|
||||||
# Shared object version: "major.minor.micro"
|
# Shared object version: "major.minor.micro"
|
||||||
# - micro updated every release when there is no API/ABI changes
|
# - micro updated every release when there is no API/ABI changes
|
||||||
# - minor updated when there are additions in API/ABI
|
# - minor updated when there are additions in API/ABI
|
||||||
@@ -515,37 +607,6 @@ function(compile_flatbuffers_schema_to_embedded_binary SRC_FBS OPT)
|
|||||||
register_generated_output(${GEN_BFBS_HEADER})
|
register_generated_output(${GEN_BFBS_HEADER})
|
||||||
endfunction()
|
endfunction()
|
||||||
|
|
||||||
# Look if we have python 3 installed so that we can run the generate code python
|
|
||||||
# script after flatc is built.
|
|
||||||
find_package(PythonInterp 3)
|
|
||||||
|
|
||||||
if(PYTHONINTERP_FOUND AND
|
|
||||||
# Skip doing this if the MSVC version is below VS 12.
|
|
||||||
# https://cmake.org/cmake/help/latest/variable/MSVC_VERSION.html
|
|
||||||
(NOT MSVC OR MSVC_VERSION GREATER 1800))
|
|
||||||
if(WIN32)
|
|
||||||
set(GENERATION_SCRIPT py scripts/generate_code.py)
|
|
||||||
else()
|
|
||||||
set(GENERATION_SCRIPT scripts/generate_code.py)
|
|
||||||
endif()
|
|
||||||
if(FLATBUFFERS_BUILD_LEGACY)
|
|
||||||
# Need to set --cpp-std c++-0x options
|
|
||||||
set(GENERATION_SCRIPT ${GENERATION_SCRIPT} --cpp-0x)
|
|
||||||
endif()
|
|
||||||
if(FLATBUFFERS_SKIP_MONSTER_EXTRA)
|
|
||||||
set(GENERATION_SCRIPT ${GENERATION_SCRIPT} --skip-monster-extra)
|
|
||||||
endif()
|
|
||||||
add_custom_command(
|
|
||||||
TARGET flatc
|
|
||||||
POST_BUILD
|
|
||||||
COMMAND ${GENERATION_SCRIPT} --flatc "${FLATBUFFERS_FLATC_EXECUTABLE}"
|
|
||||||
WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
|
|
||||||
COMMENT "Running ${GENERATION_SCRIPT}..."
|
|
||||||
VERBATIM)
|
|
||||||
else()
|
|
||||||
message("No Python3 interpreter found! Unable to generate files automatically.")
|
|
||||||
endif()
|
|
||||||
|
|
||||||
if(FLATBUFFERS_BUILD_TESTS)
|
if(FLATBUFFERS_BUILD_TESTS)
|
||||||
file(COPY "${CMAKE_CURRENT_SOURCE_DIR}/tests" DESTINATION "${CMAKE_CURRENT_BINARY_DIR}")
|
file(COPY "${CMAKE_CURRENT_SOURCE_DIR}/tests" DESTINATION "${CMAKE_CURRENT_BINARY_DIR}")
|
||||||
file(COPY "${CMAKE_CURRENT_SOURCE_DIR}/samples" DESTINATION "${CMAKE_CURRENT_BINARY_DIR}")
|
file(COPY "${CMAKE_CURRENT_SOURCE_DIR}/samples" DESTINATION "${CMAKE_CURRENT_BINARY_DIR}")
|
||||||
@@ -561,15 +622,16 @@ if(FLATBUFFERS_BUILD_TESTS)
|
|||||||
compile_flatbuffers_schema_to_cpp_opt(tests/arrays_test.fbs "--scoped-enums;--gen-compare")
|
compile_flatbuffers_schema_to_cpp_opt(tests/arrays_test.fbs "--scoped-enums;--gen-compare")
|
||||||
compile_flatbuffers_schema_to_binary(tests/arrays_test.fbs)
|
compile_flatbuffers_schema_to_binary(tests/arrays_test.fbs)
|
||||||
compile_flatbuffers_schema_to_embedded_binary(tests/monster_test.fbs "--no-includes;--gen-compare")
|
compile_flatbuffers_schema_to_embedded_binary(tests/monster_test.fbs "--no-includes;--gen-compare")
|
||||||
|
compile_flatbuffers_schema_to_cpp(tests/native_inline_table_test.fbs "--gen-compare")
|
||||||
if(NOT (MSVC AND (MSVC_VERSION LESS 1900)))
|
if(NOT (MSVC AND (MSVC_VERSION LESS 1900)))
|
||||||
compile_flatbuffers_schema_to_cpp(tests/monster_extra.fbs) # Test floating-point NAN/INF.
|
compile_flatbuffers_schema_to_cpp(tests/monster_extra.fbs) # Test floating-point NAN/INF.
|
||||||
endif()
|
endif()
|
||||||
include_directories(${CMAKE_CURRENT_BINARY_DIR}/tests)
|
include_directories(${CMAKE_CURRENT_BINARY_DIR}/tests)
|
||||||
add_executable(flattests ${FlatBuffers_Tests_SRCS})
|
add_executable(flattests ${FlatBuffers_Tests_SRCS})
|
||||||
|
target_link_libraries(flattests PRIVATE $<BUILD_INTERFACE:ProjectConfig>)
|
||||||
|
|
||||||
add_dependencies(flattests generated_code)
|
add_dependencies(flattests generated_code)
|
||||||
set_property(TARGET flattests
|
|
||||||
PROPERTY COMPILE_DEFINITIONS FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
|
|
||||||
FLATBUFFERS_DEBUG_VERIFICATION_FAILURE=1)
|
|
||||||
if(FLATBUFFERS_CODE_SANITIZE)
|
if(FLATBUFFERS_CODE_SANITIZE)
|
||||||
add_fsanitize_to_target(flattests ${FLATBUFFERS_CODE_SANITIZE})
|
add_fsanitize_to_target(flattests ${FLATBUFFERS_CODE_SANITIZE})
|
||||||
endif()
|
endif()
|
||||||
@@ -577,24 +639,27 @@ if(FLATBUFFERS_BUILD_TESTS)
|
|||||||
compile_flatbuffers_schema_to_cpp(samples/monster.fbs)
|
compile_flatbuffers_schema_to_cpp(samples/monster.fbs)
|
||||||
compile_flatbuffers_schema_to_binary(samples/monster.fbs)
|
compile_flatbuffers_schema_to_binary(samples/monster.fbs)
|
||||||
include_directories(${CMAKE_CURRENT_BINARY_DIR}/samples)
|
include_directories(${CMAKE_CURRENT_BINARY_DIR}/samples)
|
||||||
|
|
||||||
add_executable(flatsamplebinary ${FlatBuffers_Sample_Binary_SRCS})
|
add_executable(flatsamplebinary ${FlatBuffers_Sample_Binary_SRCS})
|
||||||
|
target_link_libraries(flatsamplebinary PRIVATE $<BUILD_INTERFACE:ProjectConfig>)
|
||||||
add_dependencies(flatsamplebinary generated_code)
|
add_dependencies(flatsamplebinary generated_code)
|
||||||
|
|
||||||
add_executable(flatsampletext ${FlatBuffers_Sample_Text_SRCS})
|
add_executable(flatsampletext ${FlatBuffers_Sample_Text_SRCS})
|
||||||
|
target_link_libraries(flatsampletext PRIVATE $<BUILD_INTERFACE:ProjectConfig>)
|
||||||
add_dependencies(flatsampletext generated_code)
|
add_dependencies(flatsampletext generated_code)
|
||||||
|
|
||||||
add_executable(flatsamplebfbs ${FlatBuffers_Sample_BFBS_SRCS})
|
add_executable(flatsamplebfbs ${FlatBuffers_Sample_BFBS_SRCS})
|
||||||
|
target_link_libraries(flatsamplebfbs PRIVATE $<BUILD_INTERFACE:ProjectConfig>)
|
||||||
add_dependencies(flatsamplebfbs generated_code)
|
add_dependencies(flatsamplebfbs generated_code)
|
||||||
|
|
||||||
if(FLATBUFFERS_BUILD_CPP17)
|
if(FLATBUFFERS_BUILD_CPP17)
|
||||||
# Don't generate header for flattests_cpp17 target.
|
# Don't generate header for flattests_cpp17 target.
|
||||||
# This target uses "generated_cpp17/monster_test_generated.h"
|
# This target uses "generated_cpp17/monster_test_generated.h"
|
||||||
# produced by direct call of generate_code.py script.
|
|
||||||
add_executable(flattests_cpp17 ${FlatBuffers_Tests_CPP17_SRCS})
|
add_executable(flattests_cpp17 ${FlatBuffers_Tests_CPP17_SRCS})
|
||||||
add_dependencies(flattests_cpp17 generated_code)
|
add_dependencies(flattests_cpp17 generated_code)
|
||||||
|
target_link_libraries(flattests_cpp17 PRIVATE $<BUILD_INTERFACE:ProjectConfig>)
|
||||||
target_compile_features(flattests_cpp17 PRIVATE cxx_std_17)
|
target_compile_features(flattests_cpp17 PRIVATE cxx_std_17)
|
||||||
target_compile_definitions(flattests_cpp17 PRIVATE
|
|
||||||
FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
|
|
||||||
FLATBUFFERS_DEBUG_VERIFICATION_FAILURE=1
|
|
||||||
)
|
|
||||||
if(FLATBUFFERS_CODE_SANITIZE)
|
if(FLATBUFFERS_CODE_SANITIZE)
|
||||||
add_fsanitize_to_target(flattests_cpp17 ${FLATBUFFERS_CODE_SANITIZE})
|
add_fsanitize_to_target(flattests_cpp17 ${FLATBUFFERS_CODE_SANITIZE})
|
||||||
endif()
|
endif()
|
||||||
@@ -602,9 +667,6 @@ if(FLATBUFFERS_BUILD_TESTS)
|
|||||||
endif()
|
endif()
|
||||||
|
|
||||||
if(FLATBUFFERS_BUILD_GRPCTEST)
|
if(FLATBUFFERS_BUILD_GRPCTEST)
|
||||||
if(CMAKE_COMPILER_IS_GNUCXX)
|
|
||||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unused-parameter -Wno-shadow")
|
|
||||||
endif()
|
|
||||||
if(NOT GRPC_INSTALL_PATH)
|
if(NOT GRPC_INSTALL_PATH)
|
||||||
message(SEND_ERROR "GRPC_INSTALL_PATH variable is not defined. See grpc/README.md")
|
message(SEND_ERROR "GRPC_INSTALL_PATH variable is not defined. See grpc/README.md")
|
||||||
endif()
|
endif()
|
||||||
@@ -620,14 +682,16 @@ if(FLATBUFFERS_BUILD_GRPCTEST)
|
|||||||
find_package(gRPC CONFIG REQUIRED)
|
find_package(gRPC CONFIG REQUIRED)
|
||||||
add_executable(grpctest ${FlatBuffers_GRPCTest_SRCS})
|
add_executable(grpctest ${FlatBuffers_GRPCTest_SRCS})
|
||||||
add_dependencies(grpctest generated_code)
|
add_dependencies(grpctest generated_code)
|
||||||
target_link_libraries(grpctest PRIVATE gRPC::grpc++_unsecure gRPC::grpc_unsecure gRPC::gpr pthread dl)
|
target_link_libraries(grpctext
|
||||||
if(FLATBUFFERS_CODE_SANITIZE AND NOT WIN32)
|
PRIVATE
|
||||||
# GRPC test has problems with alignment and will fail under ASAN/UBSAN.
|
$<BUILD_INTERFACE:ProjectConfig>
|
||||||
# add_fsanitize_to_target(grpctest ${FLATBUFFERS_CODE_SANITIZE})
|
gRPC::grpc++_unsecure
|
||||||
endif()
|
gRPC::gpr
|
||||||
|
pthread
|
||||||
|
dl
|
||||||
|
)
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
|
|
||||||
if(FLATBUFFERS_INSTALL)
|
if(FLATBUFFERS_INSTALL)
|
||||||
include(GNUInstallDirs)
|
include(GNUInstallDirs)
|
||||||
|
|
||||||
@@ -635,28 +699,21 @@ if(FLATBUFFERS_INSTALL)
|
|||||||
|
|
||||||
set(FB_CMAKE_DIR "${CMAKE_INSTALL_LIBDIR}/cmake/flatbuffers")
|
set(FB_CMAKE_DIR "${CMAKE_INSTALL_LIBDIR}/cmake/flatbuffers")
|
||||||
|
|
||||||
configure_file(CMake/FlatbuffersConfigVersion.cmake.in FlatbuffersConfigVersion.cmake @ONLY)
|
configure_file(CMake/FlatBuffersConfigVersion.cmake.in FlatBuffersConfigVersion.cmake @ONLY)
|
||||||
install(
|
install(
|
||||||
FILES "CMake/FlatbuffersConfig.cmake" "${CMAKE_CURRENT_BINARY_DIR}/FlatbuffersConfigVersion.cmake"
|
FILES "CMake/FlatBuffersConfig.cmake" "${CMAKE_CURRENT_BINARY_DIR}/FlatBuffersConfigVersion.cmake"
|
||||||
DESTINATION ${FB_CMAKE_DIR}
|
DESTINATION ${FB_CMAKE_DIR}
|
||||||
)
|
)
|
||||||
|
|
||||||
if(FLATBUFFERS_BUILD_FLATLIB)
|
if(FLATBUFFERS_BUILD_FLATLIB)
|
||||||
if(CMAKE_VERSION VERSION_LESS 3.0)
|
install(
|
||||||
install(
|
TARGETS flatbuffers EXPORT FlatBuffersTargets
|
||||||
TARGETS flatbuffers EXPORT FlatbuffersTargets
|
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
|
||||||
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
|
INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
|
||||||
)
|
)
|
||||||
else()
|
|
||||||
install(
|
|
||||||
TARGETS flatbuffers EXPORT FlatbuffersTargets
|
|
||||||
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
|
|
||||||
INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
|
|
||||||
)
|
|
||||||
endif()
|
|
||||||
|
|
||||||
install(EXPORT FlatbuffersTargets
|
install(EXPORT FlatBuffersTargets
|
||||||
FILE FlatbuffersTargets.cmake
|
FILE FlatBuffersTargets.cmake
|
||||||
NAMESPACE flatbuffers::
|
NAMESPACE flatbuffers::
|
||||||
DESTINATION ${FB_CMAKE_DIR}
|
DESTINATION ${FB_CMAKE_DIR}
|
||||||
)
|
)
|
||||||
@@ -677,26 +734,17 @@ if(FLATBUFFERS_INSTALL)
|
|||||||
endif()
|
endif()
|
||||||
|
|
||||||
if(FLATBUFFERS_BUILD_SHAREDLIB)
|
if(FLATBUFFERS_BUILD_SHAREDLIB)
|
||||||
if(CMAKE_VERSION VERSION_LESS 3.0)
|
install(
|
||||||
install(
|
TARGETS flatbuffers_shared EXPORT FlatBuffersSharedTargets
|
||||||
TARGETS flatbuffers_shared EXPORT FlatbuffersSharedTargets
|
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
|
||||||
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
|
RUNTIME DESTINATION ${CMAKE_INSTALL_LIBDIR}
|
||||||
RUNTIME DESTINATION ${CMAKE_INSTALL_LIBDIR}
|
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
|
||||||
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
|
INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
|
||||||
)
|
)
|
||||||
else()
|
|
||||||
install(
|
|
||||||
TARGETS flatbuffers_shared EXPORT FlatbuffersSharedTargets
|
|
||||||
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
|
|
||||||
RUNTIME DESTINATION ${CMAKE_INSTALL_LIBDIR}
|
|
||||||
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
|
|
||||||
INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
|
|
||||||
)
|
|
||||||
endif()
|
|
||||||
|
|
||||||
install(
|
install(
|
||||||
EXPORT FlatbuffersSharedTargets
|
EXPORT FlatBuffersSharedTargets
|
||||||
FILE FlatbuffersSharedTargets.cmake
|
FILE FlatBuffersSharedTargets.cmake
|
||||||
NAMESPACE flatbuffers::
|
NAMESPACE flatbuffers::
|
||||||
DESTINATION ${FB_CMAKE_DIR}
|
DESTINATION ${FB_CMAKE_DIR}
|
||||||
)
|
)
|
||||||
@@ -748,6 +796,14 @@ if(UNIX)
|
|||||||
endif()
|
endif()
|
||||||
|
|
||||||
# Include for running Google Benchmarks.
|
# Include for running Google Benchmarks.
|
||||||
if(FLATBUFFERS_BUILD_BENCHMARKS AND CMAKE_VERSION VERSION_GREATER 3.13)
|
if(FLATBUFFERS_BUILD_BENCHMARKS)
|
||||||
add_subdirectory(benchmarks)
|
add_subdirectory(benchmarks)
|
||||||
endif()
|
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>)
|
||||||
|
|||||||
70
WORKSPACE
70
WORKSPACE
@@ -3,20 +3,47 @@ workspace(name = "com_github_google_flatbuffers")
|
|||||||
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
|
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
|
||||||
|
|
||||||
http_archive(
|
http_archive(
|
||||||
name = "io_bazel_rules_go",
|
name = "platforms",
|
||||||
sha256 = "d1ffd055969c8f8d431e2d439813e42326961d0942bdf734d2c95dc30c369566",
|
sha256 = "379113459b0feaf6bfbb584a91874c065078aa673222846ac765f86661c27407",
|
||||||
urls = [
|
urls = [
|
||||||
"https://mirror.bazel.build/github.com/bazelbuild/rules_go/releases/download/v0.24.5/rules_go-v0.24.5.tar.gz",
|
"https://mirror.bazel.build/github.com/bazelbuild/platforms/releases/download/0.0.5/platforms-0.0.5.tar.gz",
|
||||||
"https://github.com/bazelbuild/rules_go/releases/download/v0.24.5/rules_go-v0.24.5.tar.gz",
|
"https://github.com/bazelbuild/platforms/releases/download/0.0.5/platforms-0.0.5.tar.gz",
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
|
|
||||||
load("@io_bazel_rules_go//go:deps.bzl", "go_register_toolchains", "go_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 = "16e9fca53ed6bd4ff4ad76facc9b7b651a89db1689a2877d6fd7b82aa824e366",
|
||||||
|
urls = [
|
||||||
|
"https://mirror.bazel.build/github.com/bazelbuild/rules_go/releases/download/v0.34.0/rules_go-v0.34.0.zip",
|
||||||
|
"https://github.com/bazelbuild/rules_go/releases/download/v0.34.0/rules_go-v0.34.0.zip",
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
load("@io_bazel_rules_go//go:deps.bzl", "go_rules_dependencies")
|
||||||
|
|
||||||
go_rules_dependencies()
|
go_rules_dependencies()
|
||||||
|
|
||||||
go_register_toolchains()
|
|
||||||
|
|
||||||
##### Protobuf
|
##### Protobuf
|
||||||
_PROTOBUF_VERSION = "3.15.2"
|
_PROTOBUF_VERSION = "3.15.2"
|
||||||
|
|
||||||
@@ -29,12 +56,12 @@ http_archive(
|
|||||||
)
|
)
|
||||||
|
|
||||||
##### GRPC
|
##### GRPC
|
||||||
_GRPC_VERSION = "1.39.0"
|
_GRPC_VERSION = "1.48.0" # https://github.com/grpc/grpc/releases/tag/v1.48.0
|
||||||
|
|
||||||
http_archive(
|
http_archive(
|
||||||
name = "com_github_grpc_grpc",
|
name = "com_github_grpc_grpc",
|
||||||
strip_prefix = "grpc-" + _GRPC_VERSION,
|
strip_prefix = "grpc-" + _GRPC_VERSION,
|
||||||
urls = ["https://github.com/grpc/grpc/archive/v" + _GRPC_VERSION + ".tar.gz"],
|
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")
|
load("@com_github_grpc_grpc//bazel:grpc_deps.bzl", "grpc_deps")
|
||||||
@@ -44,3 +71,28 @@ grpc_deps()
|
|||||||
load("@com_github_grpc_grpc//bazel:grpc_extra_deps.bzl", "grpc_extra_deps")
|
load("@com_github_grpc_grpc//bazel:grpc_extra_deps.bzl", "grpc_extra_deps")
|
||||||
|
|
||||||
grpc_extra_deps()
|
grpc_extra_deps()
|
||||||
|
|
||||||
|
# rules_go from https://github.com/bazelbuild/rules_go/releases/tag/v0.34.0
|
||||||
|
http_archive(
|
||||||
|
name = "build_bazel_rules_nodejs",
|
||||||
|
sha256 = "965ee2492a2b087cf9e0f2ca472aeaf1be2eb650e0cfbddf514b9a7d3ea4b02a",
|
||||||
|
urls = ["https://github.com/bazelbuild/rules_nodejs/releases/download/5.2.0/rules_nodejs-5.2.0.tar.gz"],
|
||||||
|
)
|
||||||
|
|
||||||
|
load("@build_bazel_rules_nodejs//:repositories.bzl", "build_bazel_rules_nodejs_dependencies")
|
||||||
|
|
||||||
|
build_bazel_rules_nodejs_dependencies()
|
||||||
|
|
||||||
|
load("@build_bazel_rules_nodejs//:index.bzl", "node_repositories", "yarn_install")
|
||||||
|
|
||||||
|
node_repositories()
|
||||||
|
|
||||||
|
yarn_install(
|
||||||
|
name = "npm",
|
||||||
|
exports_directories_only = False,
|
||||||
|
# Unfreeze to add/remove packages.
|
||||||
|
frozen_lockfile = True,
|
||||||
|
package_json = "//:package.json",
|
||||||
|
symlink_node_modules = False,
|
||||||
|
yarn_lock = "//:yarn.lock",
|
||||||
|
)
|
||||||
|
|||||||
@@ -1,20 +1,4 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<!-- Copyright (c) 2013 Google, Inc.
|
|
||||||
|
|
||||||
This software is provided 'as-is', without any express or implied
|
|
||||||
warranty. In no event will the authors be held liable for any damages
|
|
||||||
arising from the use of this software.
|
|
||||||
Permission is granted to anyone to use this software for any purpose,
|
|
||||||
including commercial applications, and to alter it and redistribute it
|
|
||||||
freely, subject to the following restrictions:
|
|
||||||
1. The origin of this software must not be misrepresented; you must not
|
|
||||||
claim that you wrote the original software. If you use this software
|
|
||||||
in a product, an acknowledgment in the product documentation would be
|
|
||||||
appreciated but is not required.
|
|
||||||
2. Altered source versions must be plainly marked as such, and must not be
|
|
||||||
misrepresented as being the original software.
|
|
||||||
3. This notice may not be removed or altered from any source distribution.
|
|
||||||
-->
|
|
||||||
<!-- BEGIN_INCLUDE(manifest) -->
|
<!-- BEGIN_INCLUDE(manifest) -->
|
||||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
package="com.example.FlatBufferTest">
|
package="com.example.FlatBufferTest">
|
||||||
|
|||||||
@@ -18,6 +18,10 @@ android {
|
|||||||
targetCompatibility JavaVersion.VERSION_1_8
|
targetCompatibility JavaVersion.VERSION_1_8
|
||||||
}
|
}
|
||||||
|
|
||||||
|
ndk {
|
||||||
|
abiFilters 'arm64-v8a', 'armeabi-v7a'
|
||||||
|
}
|
||||||
|
|
||||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||||
externalNativeBuild {
|
externalNativeBuild {
|
||||||
cmake {
|
cmake {
|
||||||
@@ -33,7 +37,6 @@ android {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
ndkVersion "21.3.6528147"
|
|
||||||
externalNativeBuild {
|
externalNativeBuild {
|
||||||
cmake {
|
cmake {
|
||||||
path "src/main/cpp/CMakeLists.txt"
|
path "src/main/cpp/CMakeLists.txt"
|
||||||
@@ -52,16 +55,17 @@ android {
|
|||||||
fbsFiles.forEach{
|
fbsFiles.forEach{
|
||||||
commandLineArgs.add(it.path)
|
commandLineArgs.add(it.path)
|
||||||
}
|
}
|
||||||
|
|
||||||
commandLine commandLineArgs
|
commandLine commandLineArgs
|
||||||
|
|
||||||
doFirst {
|
doFirst {
|
||||||
delete "$outputCppDir/"
|
delete "$outputCppDir/"
|
||||||
mkdir "$outputCppDir/"
|
mkdir "$outputCppDir/"
|
||||||
}
|
}
|
||||||
|
|
||||||
doLast {
|
doLast {
|
||||||
if (execResult.getExitValue() != 0) {
|
if (executionResult.get().exitValue != 0) {
|
||||||
println(standardOutput.toString())
|
throw new GradleException("flatc failed with: ${executionResult.get().toString()}")
|
||||||
throw new GradleException("flatc command line failed")
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -74,6 +78,10 @@ android {
|
|||||||
|
|
||||||
standardOutput = new ByteArrayOutputStream()
|
standardOutput = new ByteArrayOutputStream()
|
||||||
errorOutput = new ByteArrayOutputStream()
|
errorOutput = new ByteArrayOutputStream()
|
||||||
|
|
||||||
|
setErrorOutput(errorOutput)
|
||||||
|
setStandardOutput(standardOutput)
|
||||||
|
|
||||||
def commandLineArgs = ['flatc', '-o', outputKotlinDir, '--kotlin']
|
def commandLineArgs = ['flatc', '-o', outputKotlinDir, '--kotlin']
|
||||||
fbsFiles.forEach{
|
fbsFiles.forEach{
|
||||||
commandLineArgs.add(it.path)
|
commandLineArgs.add(it.path)
|
||||||
@@ -85,43 +93,42 @@ android {
|
|||||||
mkdir "$outputKotlinDir/"
|
mkdir "$outputKotlinDir/"
|
||||||
}
|
}
|
||||||
doLast {
|
doLast {
|
||||||
if (execResult.getExitValue() != 0) {
|
if (executionResult.get().exitValue != 0) {
|
||||||
println(standardOutput.toString())
|
throw new GradleException("flatc failed with: ${executionResult.get().toString()}")
|
||||||
throw new GradleException("flatc command line failed")
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
afterEvaluate {
|
afterEvaluate {
|
||||||
android.applicationVariants.all { variant ->
|
tasks.named("preBuild") {
|
||||||
variant.javaCompiler.dependsOn(generateFbsKotlin)
|
dependsOn(generateFbsKotlin)
|
||||||
variant.javaCompiler.dependsOn(generateFbsCpp)
|
dependsOn(generateFbsCpp)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
flavorDimensions "stl-variant"
|
// flavorDimensions "stl-variant"
|
||||||
productFlavors {
|
// productFlavors {
|
||||||
gnustl {
|
// gnustl {
|
||||||
dimension "stl-variant"
|
// dimension "stl-variant"
|
||||||
applicationIdSuffix ".gnustl"
|
// applicationIdSuffix ".gnustl"
|
||||||
versionNameSuffix "-gnustl"
|
// versionNameSuffix "-gnustl"
|
||||||
externalNativeBuild {
|
// externalNativeBuild {
|
||||||
ndkBuild {
|
// ndkBuild {
|
||||||
arguments "APP_STL=gnustl_static"
|
// arguments "APP_STL=gnustl_static"
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
libcpp {
|
// libcpp {
|
||||||
dimension "stl-variant"
|
// dimension "stl-variant"
|
||||||
applicationIdSuffix ".libcpp"
|
// applicationIdSuffix ".libcpp"
|
||||||
versionNameSuffix "-libcpp"
|
// versionNameSuffix "-libcpp"
|
||||||
externalNativeBuild {
|
// externalNativeBuild {
|
||||||
ndkBuild {
|
// ndkBuild {
|
||||||
arguments "APP_STL=c++_static"
|
// arguments "APP_STL=c++_static"
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
}
|
}
|
||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ set(FlatBuffers_Library_SRCS
|
|||||||
${FLATBUFFERS_SRC}/include/flatbuffers/flatbuffer_builder.h
|
${FLATBUFFERS_SRC}/include/flatbuffers/flatbuffer_builder.h
|
||||||
${FLATBUFFERS_SRC}/include/flatbuffers/flatbuffers.h
|
${FLATBUFFERS_SRC}/include/flatbuffers/flatbuffers.h
|
||||||
${FLATBUFFERS_SRC}/include/flatbuffers/flexbuffers.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/hash.h
|
||||||
${FLATBUFFERS_SRC}/include/flatbuffers/idl.h
|
${FLATBUFFERS_SRC}/include/flatbuffers/idl.h
|
||||||
${FLATBUFFERS_SRC}/include/flatbuffers/minireflect.h
|
${FLATBUFFERS_SRC}/include/flatbuffers/minireflect.h
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ struct Animal FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
|
|||||||
verifier.VerifyString(name()) &&
|
verifier.VerifyString(name()) &&
|
||||||
VerifyOffset(verifier, VT_SOUND) &&
|
VerifyOffset(verifier, VT_SOUND) &&
|
||||||
verifier.VerifyString(sound()) &&
|
verifier.VerifyString(sound()) &&
|
||||||
VerifyField<uint16_t>(verifier, VT_WEIGHT) &&
|
VerifyField<uint16_t>(verifier, VT_WEIGHT, 2) &&
|
||||||
verifier.EndTable();
|
verifier.EndTable();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -57,7 +57,6 @@ struct AnimalBuilder {
|
|||||||
: fbb_(_fbb) {
|
: fbb_(_fbb) {
|
||||||
start_ = fbb_.StartTable();
|
start_ = fbb_.StartTable();
|
||||||
}
|
}
|
||||||
AnimalBuilder &operator=(const AnimalBuilder &);
|
|
||||||
flatbuffers::Offset<Animal> Finish() {
|
flatbuffers::Offset<Animal> Finish() {
|
||||||
const auto end = fbb_.EndTable(start_);
|
const auto end = fbb_.EndTable(start_);
|
||||||
auto o = flatbuffers::Offset<Animal>(end);
|
auto o = flatbuffers::Offset<Animal>(end);
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import kotlin.math.sign
|
|||||||
import com.google.flatbuffers.*
|
import com.google.flatbuffers.*
|
||||||
|
|
||||||
@Suppress("unused")
|
@Suppress("unused")
|
||||||
@ExperimentalUnsignedTypes
|
|
||||||
class Animal : Table() {
|
class Animal : Table() {
|
||||||
|
|
||||||
fun __init(_i: Int, _bb: ByteBuffer) {
|
fun __init(_i: Int, _bb: ByteBuffer) {
|
||||||
|
|||||||
@@ -19,3 +19,5 @@ android.useAndroidX=true
|
|||||||
android.enableJetifier=true
|
android.enableJetifier=true
|
||||||
# Kotlin code style for this project: "official" or "obsolete":
|
# Kotlin code style for this project: "official" or "obsolete":
|
||||||
kotlin.code.style=official
|
kotlin.code.style=official
|
||||||
|
# Use parallel builds
|
||||||
|
org.gradle.parallel=true
|
||||||
BIN
android/gradle/wrapper/gradle-wrapper.jar
vendored
BIN
android/gradle/wrapper/gradle-wrapper.jar
vendored
Binary file not shown.
@@ -1,6 +1,5 @@
|
|||||||
#Thu Oct 29 19:47:23 CET 2020
|
|
||||||
distributionBase=GRADLE_USER_HOME
|
distributionBase=GRADLE_USER_HOME
|
||||||
distributionPath=wrapper/dists
|
distributionPath=wrapper/dists
|
||||||
|
distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-bin.zip
|
||||||
zipStoreBase=GRADLE_USER_HOME
|
zipStoreBase=GRADLE_USER_HOME
|
||||||
zipStorePath=wrapper/dists
|
zipStorePath=wrapper/dists
|
||||||
distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-all.zip
|
|
||||||
|
|||||||
76
appveyor.yml
76
appveyor.yml
@@ -1,76 +0,0 @@
|
|||||||
branches:
|
|
||||||
only:
|
|
||||||
- master
|
|
||||||
|
|
||||||
environment:
|
|
||||||
nodejs_version: "14"
|
|
||||||
|
|
||||||
global:
|
|
||||||
# Workaround for https://github.com/conda/conda-build/issues/636
|
|
||||||
PYTHONIOENCODING: UTF-8
|
|
||||||
CONDA_INSTALL_LOCN: "C:\\Miniconda35-x64"
|
|
||||||
CMAKE_OPTIONS: ""
|
|
||||||
CPP_TEST_OPTIONS: ""
|
|
||||||
CHECK_GEN_CODE: 1
|
|
||||||
|
|
||||||
matrix:
|
|
||||||
- APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2015
|
|
||||||
CMAKE_VS_VERSION: "14 2015"
|
|
||||||
|
|
||||||
platform:
|
|
||||||
- x86
|
|
||||||
- x64
|
|
||||||
|
|
||||||
configuration:
|
|
||||||
- Debug
|
|
||||||
- Release
|
|
||||||
|
|
||||||
before_build:
|
|
||||||
- cmake . -G"Visual Studio %CMAKE_VS_VERSION%" -DFLATBUFFERS_CODE_SANITIZE=1 %CMAKE_OPTIONS%
|
|
||||||
# This cuts down on a lot of noise generated by xamarin warnings.
|
|
||||||
- if exist "C:\Program Files (x86)\MSBuild\14.0\Microsoft.Common.targets\ImportAfter\Xamarin.Common.targets" del "C:\Program Files (x86)\MSBuild\14.0\Microsoft.Common.targets\ImportAfter\Xamarin.Common.targets"
|
|
||||||
|
|
||||||
build:
|
|
||||||
project: ALL_BUILD.vcxproj
|
|
||||||
verbosity: minimal
|
|
||||||
|
|
||||||
after_build:
|
|
||||||
- python conan/appveyor/install.py
|
|
||||||
- python conan/appveyor/build.py
|
|
||||||
|
|
||||||
install:
|
|
||||||
- set PATH=%CONDA_INSTALL_LOCN%;%CONDA_INSTALL_LOCN%\scripts;%PATH%;
|
|
||||||
- ps: Install-Product node $env:nodejs_version
|
|
||||||
|
|
||||||
test_script:
|
|
||||||
- if [%CHECK_GEN_CODE%]==[1] (call py scripts/check_generate_code.py "%CPP_TEST_OPTIONS%")
|
|
||||||
- "cd tests"
|
|
||||||
- 7z a GeneratedMyGameCode.zip MyGame\
|
|
||||||
- rem "---------------- C++ -----------------"
|
|
||||||
- "cd .."
|
|
||||||
- "%CONFIGURATION%\\flattests.exe"
|
|
||||||
- rem "---------------- JS -----------------"
|
|
||||||
- "node --version"
|
|
||||||
- "npm install"
|
|
||||||
- "npm run compile"
|
|
||||||
- "cd tests"
|
|
||||||
- "TypeScriptTest.bat"
|
|
||||||
- rem "---------------- C# -----------------"
|
|
||||||
# Have to compile this here rather than in "build" above because AppVeyor only
|
|
||||||
# supports building one project??
|
|
||||||
- "cd FlatBuffers.Test"
|
|
||||||
- "dotnet new sln"
|
|
||||||
- "dotnet sln add FlatBuffers.Test.csproj"
|
|
||||||
- "nuget restore"
|
|
||||||
- "mkdir .tmp"
|
|
||||||
- "msbuild.exe /property:Configuration=Release;OutputPath=.tmp /verbosity:minimal FlatBuffers.Test.csproj"
|
|
||||||
- ".tmp\\FlatBuffers.Test.exe"
|
|
||||||
# Run tests with UNSAFE_BYTEBUFFER
|
|
||||||
- "msbuild.exe /property:Configuration=Release;UnsafeByteBuffer=true;OutputPath=.tmp /verbosity:minimal FlatBuffers.Test.csproj"
|
|
||||||
- ".tmp\\FlatBuffers.Test.exe"
|
|
||||||
|
|
||||||
artifacts:
|
|
||||||
- path: $(CONFIGURATION)\flatc.exe
|
|
||||||
name: flatc.exe
|
|
||||||
- path: tests\GeneratedMyGameCode.zip
|
|
||||||
name: GeneratedMyGameCode.zip
|
|
||||||
@@ -16,7 +16,7 @@ FetchContent_Declare(
|
|||||||
FetchContent_Declare(
|
FetchContent_Declare(
|
||||||
googlebenchmark
|
googlebenchmark
|
||||||
GIT_REPOSITORY https://github.com/google/benchmark.git
|
GIT_REPOSITORY https://github.com/google/benchmark.git
|
||||||
GIT_TAG f91b6b42b1b9854772a90ae9501464a161707d1e # v1.6.0
|
GIT_TAG 0d98dba29d66e93259db7daa53a9327df767a415 # v1.6.1
|
||||||
)
|
)
|
||||||
|
|
||||||
# For Windows: Prevent overriding the parent project's compiler/linker
|
# For Windows: Prevent overriding the parent project's compiler/linker
|
||||||
@@ -66,6 +66,12 @@ target_compile_features(flatbenchmark PUBLIC
|
|||||||
cxx_std_11
|
cxx_std_11
|
||||||
)
|
)
|
||||||
|
|
||||||
|
target_compile_options(flatbenchmark
|
||||||
|
PRIVATE
|
||||||
|
-fno-aligned-new
|
||||||
|
-Wno-deprecated-declarations
|
||||||
|
)
|
||||||
|
|
||||||
# Set the output directory to the root binary directory
|
# Set the output directory to the root binary directory
|
||||||
set_target_properties(flatbenchmark
|
set_target_properties(flatbenchmark
|
||||||
PROPERTIES RUNTIME_OUTPUT_DIRECTORY
|
PROPERTIES RUNTIME_OUTPUT_DIRECTORY
|
||||||
|
|||||||
@@ -6,6 +6,13 @@
|
|||||||
|
|
||||||
#include "flatbuffers/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 {
|
namespace benchmarks_flatbuffers {
|
||||||
|
|
||||||
struct Foo;
|
struct Foo;
|
||||||
@@ -157,11 +164,11 @@ struct FooBar FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
|
|||||||
}
|
}
|
||||||
bool Verify(flatbuffers::Verifier &verifier) const {
|
bool Verify(flatbuffers::Verifier &verifier) const {
|
||||||
return VerifyTableStart(verifier) &&
|
return VerifyTableStart(verifier) &&
|
||||||
VerifyField<benchmarks_flatbuffers::Bar>(verifier, VT_SIBLING) &&
|
VerifyField<benchmarks_flatbuffers::Bar>(verifier, VT_SIBLING, 8) &&
|
||||||
VerifyOffset(verifier, VT_NAME) &&
|
VerifyOffset(verifier, VT_NAME) &&
|
||||||
verifier.VerifyString(name()) &&
|
verifier.VerifyString(name()) &&
|
||||||
VerifyField<double>(verifier, VT_RATING) &&
|
VerifyField<double>(verifier, VT_RATING, 8) &&
|
||||||
VerifyField<uint8_t>(verifier, VT_POSTFIX) &&
|
VerifyField<uint8_t>(verifier, VT_POSTFIX, 1) &&
|
||||||
verifier.EndTable();
|
verifier.EndTable();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -247,8 +254,8 @@ struct FooBarContainer FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
|
|||||||
VerifyOffset(verifier, VT_LIST) &&
|
VerifyOffset(verifier, VT_LIST) &&
|
||||||
verifier.VerifyVector(list()) &&
|
verifier.VerifyVector(list()) &&
|
||||||
verifier.VerifyVectorOfTables(list()) &&
|
verifier.VerifyVectorOfTables(list()) &&
|
||||||
VerifyField<uint8_t>(verifier, VT_INITIALIZED) &&
|
VerifyField<uint8_t>(verifier, VT_INITIALIZED, 1) &&
|
||||||
VerifyField<int16_t>(verifier, VT_FRUIT) &&
|
VerifyField<int16_t>(verifier, VT_FRUIT, 2) &&
|
||||||
VerifyOffset(verifier, VT_LOCATION) &&
|
VerifyOffset(verifier, VT_LOCATION) &&
|
||||||
verifier.VerifyString(location()) &&
|
verifier.VerifyString(location()) &&
|
||||||
verifier.EndTable();
|
verifier.EndTable();
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ struct FlatBufferBench : Bench {
|
|||||||
explicit FlatBufferBench(int64_t initial_size, Allocator *allocator)
|
explicit FlatBufferBench(int64_t initial_size, Allocator *allocator)
|
||||||
: fbb(initial_size, allocator, false) {}
|
: fbb(initial_size, allocator, false) {}
|
||||||
|
|
||||||
uint8_t *Encode(void *, int64_t &len) {
|
uint8_t *Encode(void *, int64_t &len) override {
|
||||||
fbb.Clear();
|
fbb.Clear();
|
||||||
|
|
||||||
const int kVectorLength = 3;
|
const int kVectorLength = 3;
|
||||||
@@ -40,7 +40,7 @@ struct FlatBufferBench : Bench {
|
|||||||
return fbb.GetBufferPointer();
|
return fbb.GetBufferPointer();
|
||||||
}
|
}
|
||||||
|
|
||||||
int64_t Use(void *decoded) {
|
int64_t Use(void *decoded) override {
|
||||||
sum = 0;
|
sum = 0;
|
||||||
auto foobarcontainer = GetFooBarContainer(decoded);
|
auto foobarcontainer = GetFooBarContainer(decoded);
|
||||||
sum = 0;
|
sum = 0;
|
||||||
@@ -65,8 +65,8 @@ struct FlatBufferBench : Bench {
|
|||||||
return sum;
|
return sum;
|
||||||
}
|
}
|
||||||
|
|
||||||
void *Decode(void *buffer, int64_t) { return buffer; }
|
void *Decode(void *buffer, int64_t) override { return buffer; }
|
||||||
void Dealloc(void *) override{};
|
void Dealloc(void *) override {};
|
||||||
|
|
||||||
FlatBufferBuilder fbb;
|
FlatBufferBuilder fbb;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -45,7 +45,7 @@ struct FooBarContainer {
|
|||||||
};
|
};
|
||||||
|
|
||||||
struct RawBench : Bench {
|
struct RawBench : Bench {
|
||||||
uint8_t *Encode(void *buf, int64_t &len) {
|
uint8_t *Encode(void *buf, int64_t &len) override {
|
||||||
FooBarContainer *fbc = new (buf) FooBarContainer;
|
FooBarContainer *fbc = new (buf) FooBarContainer;
|
||||||
strcpy(fbc->location, "http://google.com/flatbuffers/"); // Unsafe eek!
|
strcpy(fbc->location, "http://google.com/flatbuffers/"); // Unsafe eek!
|
||||||
fbc->location_len = (int)strlen(fbc->location);
|
fbc->location_len = (int)strlen(fbc->location);
|
||||||
@@ -74,7 +74,7 @@ struct RawBench : Bench {
|
|||||||
return reinterpret_cast<uint8_t *>(fbc);
|
return reinterpret_cast<uint8_t *>(fbc);
|
||||||
};
|
};
|
||||||
|
|
||||||
int64_t Use(void *decoded) {
|
int64_t Use(void *decoded) override {
|
||||||
auto foobarcontainer = reinterpret_cast<FooBarContainer *>(decoded);
|
auto foobarcontainer = reinterpret_cast<FooBarContainer *>(decoded);
|
||||||
sum = 0;
|
sum = 0;
|
||||||
Add(foobarcontainer->initialized);
|
Add(foobarcontainer->initialized);
|
||||||
@@ -98,7 +98,7 @@ struct RawBench : Bench {
|
|||||||
return sum;
|
return sum;
|
||||||
}
|
}
|
||||||
|
|
||||||
void *Decode(void *buf, int64_t) { return buf; }
|
void *Decode(void *buf, int64_t) override { return buf; }
|
||||||
void Dealloc(void *) override{};
|
void Dealloc(void *) override{};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ DEFAULT_INCLUDE_PATHS = [
|
|||||||
"./",
|
"./",
|
||||||
"$(GENDIR)",
|
"$(GENDIR)",
|
||||||
"$(BINDIR)",
|
"$(BINDIR)",
|
||||||
|
"$(execpath @com_github_google_flatbuffers//:flatc).runfiles/com_github_google_flatbuffers",
|
||||||
]
|
]
|
||||||
|
|
||||||
DEFAULT_FLATC_ARGS = [
|
DEFAULT_FLATC_ARGS = [
|
||||||
@@ -37,6 +38,7 @@ def flatbuffer_library_public(
|
|||||||
reflection_visibility = None,
|
reflection_visibility = None,
|
||||||
compatible_with = None,
|
compatible_with = None,
|
||||||
restricted_to = None,
|
restricted_to = None,
|
||||||
|
target_compatible_with = None,
|
||||||
output_to_bindir = False):
|
output_to_bindir = False):
|
||||||
"""Generates code files for reading/writing the given flatbuffers in the requested language using the public compiler.
|
"""Generates code files for reading/writing the given flatbuffers in the requested language using the public compiler.
|
||||||
|
|
||||||
@@ -58,6 +60,8 @@ def flatbuffer_library_public(
|
|||||||
built for, in addition to default-supported environments.
|
built for, in addition to default-supported environments.
|
||||||
restricted_to: Optional, The list of environments this rule can be built
|
restricted_to: Optional, The list of environments this rule can be built
|
||||||
for, instead of default-supported environments.
|
for, instead of default-supported environments.
|
||||||
|
target_compatible_with: Optional, The list of target platform constraints
|
||||||
|
to use.
|
||||||
output_to_bindir: Passed to genrule for output to bin directory.
|
output_to_bindir: Passed to genrule for output to bin directory.
|
||||||
|
|
||||||
|
|
||||||
@@ -92,6 +96,7 @@ def flatbuffer_library_public(
|
|||||||
tools = [flatc_path],
|
tools = [flatc_path],
|
||||||
cmd = genrule_cmd,
|
cmd = genrule_cmd,
|
||||||
compatible_with = compatible_with,
|
compatible_with = compatible_with,
|
||||||
|
target_compatible_with = target_compatible_with,
|
||||||
restricted_to = restricted_to,
|
restricted_to = restricted_to,
|
||||||
message = "Generating flatbuffer files for %s:" % (name),
|
message = "Generating flatbuffer files for %s:" % (name),
|
||||||
)
|
)
|
||||||
@@ -120,8 +125,10 @@ def flatbuffer_library_public(
|
|||||||
tools = [flatc_path],
|
tools = [flatc_path],
|
||||||
compatible_with = compatible_with,
|
compatible_with = compatible_with,
|
||||||
restricted_to = restricted_to,
|
restricted_to = restricted_to,
|
||||||
|
target_compatible_with = target_compatible_with,
|
||||||
cmd = reflection_genrule_cmd,
|
cmd = reflection_genrule_cmd,
|
||||||
message = "Generating flatbuffer reflection binary for %s:" % (name),
|
message = "Generating flatbuffer reflection binary for %s:" % (name),
|
||||||
|
visibility = reflection_visibility,
|
||||||
)
|
)
|
||||||
native.filegroup(
|
native.filegroup(
|
||||||
name = "%s_out" % reflection_name,
|
name = "%s_out" % reflection_name,
|
||||||
@@ -136,15 +143,18 @@ def flatbuffer_cc_library(
|
|||||||
srcs,
|
srcs,
|
||||||
srcs_filegroup_name = "",
|
srcs_filegroup_name = "",
|
||||||
out_prefix = "",
|
out_prefix = "",
|
||||||
|
deps = [],
|
||||||
includes = [],
|
includes = [],
|
||||||
include_paths = DEFAULT_INCLUDE_PATHS,
|
include_paths = DEFAULT_INCLUDE_PATHS,
|
||||||
|
cc_include_paths = [],
|
||||||
flatc_args = DEFAULT_FLATC_ARGS,
|
flatc_args = DEFAULT_FLATC_ARGS,
|
||||||
visibility = None,
|
visibility = None,
|
||||||
compatible_with = None,
|
compatible_with = None,
|
||||||
restricted_to = None,
|
restricted_to = None,
|
||||||
|
target_compatible_with = None,
|
||||||
srcs_filegroup_visibility = None,
|
srcs_filegroup_visibility = None,
|
||||||
gen_reflections = False):
|
gen_reflections = False):
|
||||||
'''A cc_library with the generated reader/writers for the given flatbuffer definitions.
|
"""A cc_library with the generated reader/writers for the given flatbuffer definitions.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
name: Rule name.
|
name: Rule name.
|
||||||
@@ -154,9 +164,12 @@ def flatbuffer_cc_library(
|
|||||||
flatbuffer_cc_library that depends on this one's schemas.
|
flatbuffer_cc_library that depends on this one's schemas.
|
||||||
out_prefix: Prepend this path to the front of all generated files. Usually
|
out_prefix: Prepend this path to the front of all generated files. Usually
|
||||||
is a directory name.
|
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.
|
includes: Optional, list of filegroups of schemas that the srcs depend on.
|
||||||
** SEE REMARKS BELOW **
|
Use of this is discouraged, and may be deprecated.
|
||||||
include_paths: Optional, list of paths the includes files can be found in.
|
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
|
flatc_args: Optional list of additional arguments to pass to flatc
|
||||||
(e.g. --gen-mutable).
|
(e.g. --gen-mutable).
|
||||||
visibility: The visibility of the generated cc_library. By default, use the
|
visibility: The visibility of the generated cc_library. By default, use the
|
||||||
@@ -169,6 +182,8 @@ def flatbuffer_cc_library(
|
|||||||
for, in addition to default-supported environments.
|
for, in addition to default-supported environments.
|
||||||
restricted_to: Optional, The list of environments this rule can be built
|
restricted_to: Optional, The list of environments this rule can be built
|
||||||
for, instead of default-supported environments.
|
for, instead of default-supported environments.
|
||||||
|
target_compatible_with: Optional, The list of target platform constraints
|
||||||
|
to use.
|
||||||
|
|
||||||
This produces:
|
This produces:
|
||||||
filegroup([name]_srcs): all generated .h files.
|
filegroup([name]_srcs): all generated .h files.
|
||||||
@@ -177,41 +192,17 @@ def flatbuffer_cc_library(
|
|||||||
parameter, if they depend on the schemas in this library.
|
parameter, if they depend on the schemas in this library.
|
||||||
Fileset([name]_reflection): (Optional) all generated reflection binaries.
|
Fileset([name]_reflection): (Optional) all generated reflection binaries.
|
||||||
cc_library([name]): library with sources and flatbuffers deps.
|
cc_library([name]): library with sources and flatbuffers deps.
|
||||||
|
"""
|
||||||
Remarks:
|
|
||||||
** Because the genrule used to call flatc does not have any trivial way of
|
|
||||||
computing the output list of files transitively generated by includes and
|
|
||||||
--gen-includes (the default) being defined for flatc, the --gen-includes
|
|
||||||
flag will not work as expected. The way around this is to add a dependency
|
|
||||||
to the flatbuffer_cc_library defined alongside the flatc included Fileset.
|
|
||||||
For example you might define:
|
|
||||||
|
|
||||||
flatbuffer_cc_library(
|
|
||||||
name = "my_fbs",
|
|
||||||
srcs = [ "schemas/foo.fbs" ],
|
|
||||||
includes = [ "//third_party/bazz:bazz_fbs_includes" ],
|
|
||||||
)
|
|
||||||
|
|
||||||
In which foo.fbs includes a few files from the Fileset defined at
|
|
||||||
//third_party/bazz:bazz_fbs_includes. When compiling the library that
|
|
||||||
includes foo_generated.h, and therefore has my_fbs as a dependency, it
|
|
||||||
will fail to find any of the bazz *_generated.h files unless you also
|
|
||||||
add bazz's flatbuffer_cc_library to your own dependency list, e.g.:
|
|
||||||
|
|
||||||
cc_library(
|
|
||||||
name = "my_lib",
|
|
||||||
deps = [
|
|
||||||
":my_fbs",
|
|
||||||
"//third_party/bazz:bazz_fbs"
|
|
||||||
],
|
|
||||||
)
|
|
||||||
|
|
||||||
Happy dependent Flatbuffering!
|
|
||||||
'''
|
|
||||||
output_headers = [
|
output_headers = [
|
||||||
(out_prefix + "%s_generated.h") % (s.replace(".fbs", "").split("/")[-1].split(":")[-1])
|
(out_prefix + "%s_generated.h") % (s.replace(".fbs", "").split("/")[-1].split(":")[-1])
|
||||||
for s in srcs
|
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 ""
|
reflection_name = "%s_reflection" % name if gen_reflections else ""
|
||||||
|
|
||||||
srcs_lib = "%s_srcs" % (name)
|
srcs_lib = "%s_srcs" % (name)
|
||||||
@@ -226,6 +217,7 @@ def flatbuffer_cc_library(
|
|||||||
flatc_args = flatc_args,
|
flatc_args = flatc_args,
|
||||||
compatible_with = compatible_with,
|
compatible_with = compatible_with,
|
||||||
restricted_to = restricted_to,
|
restricted_to = restricted_to,
|
||||||
|
target_compatible_with = target_compatible_with,
|
||||||
reflection_name = reflection_name,
|
reflection_name = reflection_name,
|
||||||
reflection_visibility = visibility,
|
reflection_visibility = visibility,
|
||||||
)
|
)
|
||||||
@@ -242,10 +234,12 @@ def flatbuffer_cc_library(
|
|||||||
],
|
],
|
||||||
deps = [
|
deps = [
|
||||||
"@com_github_google_flatbuffers//:runtime_cc",
|
"@com_github_google_flatbuffers//:runtime_cc",
|
||||||
],
|
"@com_github_google_flatbuffers//:flatbuffers",
|
||||||
includes = [],
|
] + deps,
|
||||||
|
includes = cc_include_paths,
|
||||||
compatible_with = compatible_with,
|
compatible_with = compatible_with,
|
||||||
restricted_to = restricted_to,
|
restricted_to = restricted_to,
|
||||||
|
target_compatible_with = target_compatible_with,
|
||||||
linkstatic = 1,
|
linkstatic = 1,
|
||||||
visibility = visibility,
|
visibility = visibility,
|
||||||
)
|
)
|
||||||
@@ -254,7 +248,7 @@ def flatbuffer_cc_library(
|
|||||||
# Flatbuffer set.
|
# Flatbuffer set.
|
||||||
native.filegroup(
|
native.filegroup(
|
||||||
name = srcs_filegroup_name if srcs_filegroup_name else "%s_includes" % (name),
|
name = srcs_filegroup_name if srcs_filegroup_name else "%s_includes" % (name),
|
||||||
srcs = srcs,
|
srcs = srcs + includes,
|
||||||
compatible_with = compatible_with,
|
compatible_with = compatible_with,
|
||||||
restricted_to = restricted_to,
|
restricted_to = restricted_to,
|
||||||
visibility = srcs_filegroup_visibility if srcs_filegroup_visibility != None else visibility,
|
visibility = srcs_filegroup_visibility if srcs_filegroup_visibility != None else visibility,
|
||||||
|
|||||||
@@ -5,8 +5,8 @@ message(STATUS "Conan FlatBuffers Wrapper")
|
|||||||
include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake)
|
include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake)
|
||||||
conan_basic_setup()
|
conan_basic_setup()
|
||||||
|
|
||||||
if (WIN32 AND MSVC AND FLATBUFFERS_BUILD_SHAREDLIB)
|
if (WIN32 AND MSVC_LIKE AND FLATBUFFERS_BUILD_SHAREDLIB)
|
||||||
set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON)
|
set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON)
|
||||||
endif(WIN32 AND MSVC AND FLATBUFFERS_BUILD_SHAREDLIB)
|
endif(WIN32 AND MSVC_LIKE AND FLATBUFFERS_BUILD_SHAREDLIB)
|
||||||
|
|
||||||
include(${CMAKE_SOURCE_DIR}/CMakeListsOriginal.txt)
|
include(${CMAKE_SOURCE_DIR}/CMakeListsOriginal.txt)
|
||||||
|
|||||||
@@ -6,16 +6,6 @@ import subprocess
|
|||||||
from cpt.packager import ConanMultiPackager
|
from cpt.packager import ConanMultiPackager
|
||||||
|
|
||||||
|
|
||||||
def set_appveyor_environment():
|
|
||||||
if os.getenv("APPVEYOR") is not None:
|
|
||||||
compiler_version = os.getenv("CMAKE_VS_VERSION").split(" ")[0].replace('"', '')
|
|
||||||
os.environ["CONAN_VISUAL_VERSIONS"] = compiler_version
|
|
||||||
os.environ["CONAN_STABLE_BRANCH_PATTERN"] = "master"
|
|
||||||
ci_platform = os.getenv("Platform").replace('"', '')
|
|
||||||
ci_platform = "x86" if ci_platform == "x86" else "x86_64"
|
|
||||||
os.environ["CONAN_ARCHS"] = ci_platform
|
|
||||||
os.environ["CONAN_BUILD_TYPES"] = os.getenv("Configuration").replace('"', '')
|
|
||||||
|
|
||||||
|
|
||||||
def get_branch():
|
def get_branch():
|
||||||
try:
|
try:
|
||||||
@@ -56,7 +46,6 @@ if __name__ == "__main__":
|
|||||||
stable_branch_pattern = os.getenv("CONAN_STABLE_BRANCH_PATTERN", r"v\d+\.\d+\.\d+.*")
|
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"))
|
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)
|
upload_only_when_stable = os.getenv("CONAN_UPLOAD_ONLY_WHEN_STABLE", True)
|
||||||
set_appveyor_environment()
|
|
||||||
|
|
||||||
builder = ConanMultiPackager(reference=get_reference(username),
|
builder = ConanMultiPackager(reference=get_reference(username),
|
||||||
username=username,
|
username=username,
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
## 2.0.0
|
## 2.0.5
|
||||||
|
|
||||||
- switch to null safety (#6696)
|
- switch to null safety (#6696)
|
||||||
- add Object APIs (pack/unpack) (#6682, #6723, #6846)
|
- add Object APIs (pack/unpack) (#6682, #6723, #6846)
|
||||||
|
|||||||
32
dart/LICENSE
32
dart/LICENSE
@@ -1,35 +1,3 @@
|
|||||||
The code in lib/flat_buffers.dart is based on code that was releases under the
|
|
||||||
following license:
|
|
||||||
|
|
||||||
Copyright 2012, the Dart project authors. All rights reserved.
|
|
||||||
Redistribution and use in source and binary forms, with or without
|
|
||||||
modification, are permitted provided that the following conditions are
|
|
||||||
met:
|
|
||||||
* Redistributions of source code must retain the above copyright
|
|
||||||
notice, this list of conditions and the following disclaimer.
|
|
||||||
* Redistributions in binary form must reproduce the above
|
|
||||||
copyright notice, this list of conditions and the following
|
|
||||||
disclaimer in the documentation and/or other materials provided
|
|
||||||
with the distribution.
|
|
||||||
* Neither the name of Google Inc. nor the names of its
|
|
||||||
contributors may be used to endorse or promote products derived
|
|
||||||
from this software without specific prior written permission.
|
|
||||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
|
||||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
|
||||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
|
||||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
|
||||||
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
|
||||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
|
||||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
|
||||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
|
||||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
|
||||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
||||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
||||||
|
|
||||||
To the extent permissible, the changes to that code and the other assets in
|
|
||||||
this package are licensed under the Apache2 license:
|
|
||||||
|
|
||||||
|
|
||||||
Apache License
|
Apache License
|
||||||
Version 2.0, January 2004
|
Version 2.0, January 2004
|
||||||
http://www.apache.org/licenses/
|
http://www.apache.org/licenses/
|
||||||
|
|||||||
@@ -2,10 +2,8 @@
|
|||||||
|
|
||||||
This package is used to read and write [FlatBuffers](https://google.github.io/flatbuffers/).
|
This package is used to read and write [FlatBuffers](https://google.github.io/flatbuffers/).
|
||||||
|
|
||||||
Most consumers will want to use the [`flatc` - FlatBuffer compiler](https://github.com/google/flatbuffers) binary for your platform:
|
Most consumers will want to use the [`flatc` - FlatBuffer compiler](https://github.com/google/flatbuffers) binary for your platform.
|
||||||
* [Linux](https://github.com/google/flatbuffers/suites/4363603985/artifacts/114682272)
|
You can find it in the `generator/{Platform}` directory of the [released package archive](https://pub.dev/packages/flat_buffers/versions/2.0.5.tar.gz).
|
||||||
* [macOS](https://github.com/google/flatbuffers/suites/4363603985/artifacts/114682273)
|
|
||||||
* [Windows](https://github.com/google/flatbuffers/suites/4363603985/artifacts/114682274)
|
|
||||||
|
|
||||||
The FlatBuffer compiler `flatc` reads a FlatBuffers IDL schema and generates Dart code.
|
The FlatBuffer compiler `flatc` reads a FlatBuffers IDL schema and generates Dart code.
|
||||||
The generated classes can be used to read or write binary data/files that are interoperable with
|
The generated classes can be used to read or write binary data/files that are interoperable with
|
||||||
@@ -14,4 +12,12 @@ examples folder.
|
|||||||
|
|
||||||
For more details and documentation, head over to the official site and read the
|
For more details and documentation, head over to the official site and read the
|
||||||
[Tutorial](https://google.github.io/flatbuffers/flatbuffers_guide_tutorial.html) and how to
|
[Tutorial](https://google.github.io/flatbuffers/flatbuffers_guide_tutorial.html) and how to
|
||||||
[use FlatBuffers in Dart](https://google.github.io/flatbuffers/flatbuffers_guide_use_dart.html).
|
[use FlatBuffers in Dart](https://google.github.io/flatbuffers/flatbuffers_guide_use_dart.html).
|
||||||
|
|
||||||
|
## Dart 2.0 notes
|
||||||
|
Version 2.0.5 ships with it's own custom build of `flatc` because this is an extraordinary release to catch-up
|
||||||
|
with FlatBuffers for other platforms. This generator can only generate dart code (to avoid generating code for other platforms which isn't released yet).
|
||||||
|
On the other hand, the generated code still produces standard binary FlatBuffers compatible with other languages.
|
||||||
|
In other words: only `flatc --dart ...` works with this generator, but your app will be able to produce and read standard binary (`Uint8List`) FlatBuffers that are fully compotible with other languages supporting FlatBuffers (e.g. Java, C++, ...).
|
||||||
|
|
||||||
|
In the future a common `flatc` binary for all platforms would be shipped through GitHub release page instead.
|
||||||
|
|||||||
@@ -1,7 +1,3 @@
|
|||||||
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
|
|
||||||
// for details. All rights reserved. Use of this source code is governed by a
|
|
||||||
// BSD-style license that can be found in the LICENSE file.
|
|
||||||
|
|
||||||
import 'dart:collection';
|
import 'dart:collection';
|
||||||
import 'dart:convert';
|
import 'dart:convert';
|
||||||
import 'dart:math';
|
import 'dart:math';
|
||||||
@@ -308,7 +304,7 @@ class Builder {
|
|||||||
assert(_inVTable);
|
assert(_inVTable);
|
||||||
// Prepare for writing the VTable.
|
// Prepare for writing the VTable.
|
||||||
_prepare(_sizeofInt32, 1);
|
_prepare(_sizeofInt32, 1);
|
||||||
int tableTail = _tail;
|
var tableTail = _tail;
|
||||||
// Prepare the size of the current table.
|
// Prepare the size of the current table.
|
||||||
final currentVTable = _currentVTable!;
|
final currentVTable = _currentVTable!;
|
||||||
currentVTable.tableSize = tableTail - _currentTableEndTail;
|
currentVTable.tableSize = tableTail - _currentTableEndTail;
|
||||||
@@ -320,10 +316,10 @@ class Builder {
|
|||||||
// Try to find an existing compatible VTable.
|
// Try to find an existing compatible VTable.
|
||||||
if (deduplicateTables) {
|
if (deduplicateTables) {
|
||||||
// Search backward - more likely to have recently used one
|
// Search backward - more likely to have recently used one
|
||||||
for (int i = _vTables.length - 1; i >= 0; i--) {
|
for (var i = _vTables.length - 1; i >= 0; i--) {
|
||||||
final int vt2Offset = _vTables[i];
|
final vt2Offset = _vTables[i];
|
||||||
final int vt2Start = _buf.lengthInBytes - vt2Offset;
|
final vt2Start = _buf.lengthInBytes - vt2Offset;
|
||||||
final int vt2Size = _buf.getUint16(vt2Start, Endian.little);
|
final vt2Size = _buf.getUint16(vt2Start, Endian.little);
|
||||||
|
|
||||||
if (currentVTable._vTableSize == vt2Size &&
|
if (currentVTable._vTableSize == vt2Size &&
|
||||||
currentVTable._offsetsMatch(vt2Start, _buf)) {
|
currentVTable._offsetsMatch(vt2Start, _buf)) {
|
||||||
@@ -370,7 +366,7 @@ class Builder {
|
|||||||
final finishedSize = size();
|
final finishedSize = size();
|
||||||
_setUint32AtTail(finishedSize, finishedSize - offset);
|
_setUint32AtTail(finishedSize, finishedSize - offset);
|
||||||
if (fileIdentifier != null) {
|
if (fileIdentifier != null) {
|
||||||
for (int i = 0; i < 4; i++) {
|
for (var i = 0; i < 4; i++) {
|
||||||
_setUint8AtTail(
|
_setUint8AtTail(
|
||||||
finishedSize - _sizeofUint32 - i, fileIdentifier.codeUnitAt(i));
|
finishedSize - _sizeofUint32 - i, fileIdentifier.codeUnitAt(i));
|
||||||
}
|
}
|
||||||
@@ -401,6 +397,15 @@ class Builder {
|
|||||||
_setFloat32AtTail(_tail, value);
|
_setFloat32AtTail(_tail, value);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Writes a bool to the tail of the buffer after preparing space for it.
|
||||||
|
/// Bools are represented as a Uint8, with the value set to '1' for true, and '0' for false
|
||||||
|
///
|
||||||
|
/// Updates the [offset] pointer. This method is intended for use when writing structs to the buffer.
|
||||||
|
void putBool(bool value) {
|
||||||
|
_prepare(_sizeofUint8, 1);
|
||||||
|
_buf.setInt8(_buf.lengthInBytes - _tail, value ? 1 : 0);
|
||||||
|
}
|
||||||
|
|
||||||
/// Writes a Int64 to the tail of the buffer after preparing space for it.
|
/// Writes a Int64 to the tail of the buffer after preparing space for it.
|
||||||
///
|
///
|
||||||
/// Updates the [offset] pointer. This method is intended for use when writing structs to the buffer.
|
/// Updates the [offset] pointer. This method is intended for use when writing structs to the buffer.
|
||||||
@@ -495,7 +500,7 @@ class Builder {
|
|||||||
/// Writes a list of Structs to the buffer, returning the offset
|
/// Writes a list of Structs to the buffer, returning the offset
|
||||||
int writeListOfStructs(List<ObjectBuilder> structBuilders) {
|
int writeListOfStructs(List<ObjectBuilder> structBuilders) {
|
||||||
assert(!_inVTable);
|
assert(!_inVTable);
|
||||||
for (int i = structBuilders.length - 1; i >= 0; i--) {
|
for (var i = structBuilders.length - 1; i >= 0; i--) {
|
||||||
structBuilders[i].finish(this);
|
structBuilders[i].finish(this);
|
||||||
}
|
}
|
||||||
return endStructVector(structBuilders.length);
|
return endStructVector(structBuilders.length);
|
||||||
@@ -505,11 +510,11 @@ class Builder {
|
|||||||
int writeList(List<int> values) {
|
int writeList(List<int> values) {
|
||||||
assert(!_inVTable);
|
assert(!_inVTable);
|
||||||
_prepare(_sizeofUint32, 1 + values.length);
|
_prepare(_sizeofUint32, 1 + values.length);
|
||||||
final int result = _tail;
|
final result = _tail;
|
||||||
int tail = _tail;
|
var tail = _tail;
|
||||||
_setUint32AtTail(tail, values.length);
|
_setUint32AtTail(tail, values.length);
|
||||||
tail -= _sizeofUint32;
|
tail -= _sizeofUint32;
|
||||||
for (int value in values) {
|
for (var value in values) {
|
||||||
_setUint32AtTail(tail, tail - value);
|
_setUint32AtTail(tail, tail - value);
|
||||||
tail -= _sizeofUint32;
|
tail -= _sizeofUint32;
|
||||||
}
|
}
|
||||||
@@ -520,11 +525,11 @@ class Builder {
|
|||||||
int writeListFloat64(List<double> values) {
|
int writeListFloat64(List<double> values) {
|
||||||
assert(!_inVTable);
|
assert(!_inVTable);
|
||||||
_prepare(_sizeofFloat64, values.length, additionalBytes: _sizeofUint32);
|
_prepare(_sizeofFloat64, values.length, additionalBytes: _sizeofUint32);
|
||||||
final int result = _tail;
|
final result = _tail;
|
||||||
int tail = _tail;
|
var tail = _tail;
|
||||||
_setUint32AtTail(tail, values.length);
|
_setUint32AtTail(tail, values.length);
|
||||||
tail -= _sizeofUint32;
|
tail -= _sizeofUint32;
|
||||||
for (double value in values) {
|
for (var value in values) {
|
||||||
_setFloat64AtTail(tail, value);
|
_setFloat64AtTail(tail, value);
|
||||||
tail -= _sizeofFloat64;
|
tail -= _sizeofFloat64;
|
||||||
}
|
}
|
||||||
@@ -535,11 +540,11 @@ class Builder {
|
|||||||
int writeListFloat32(List<double> values) {
|
int writeListFloat32(List<double> values) {
|
||||||
assert(!_inVTable);
|
assert(!_inVTable);
|
||||||
_prepare(_sizeofFloat32, 1 + values.length);
|
_prepare(_sizeofFloat32, 1 + values.length);
|
||||||
final int result = _tail;
|
final result = _tail;
|
||||||
int tail = _tail;
|
var tail = _tail;
|
||||||
_setUint32AtTail(tail, values.length);
|
_setUint32AtTail(tail, values.length);
|
||||||
tail -= _sizeofUint32;
|
tail -= _sizeofUint32;
|
||||||
for (double value in values) {
|
for (var value in values) {
|
||||||
_setFloat32AtTail(tail, value);
|
_setFloat32AtTail(tail, value);
|
||||||
tail -= _sizeofFloat32;
|
tail -= _sizeofFloat32;
|
||||||
}
|
}
|
||||||
@@ -550,11 +555,11 @@ class Builder {
|
|||||||
int writeListInt64(List<int> values) {
|
int writeListInt64(List<int> values) {
|
||||||
assert(!_inVTable);
|
assert(!_inVTable);
|
||||||
_prepare(_sizeofInt64, values.length, additionalBytes: _sizeofUint32);
|
_prepare(_sizeofInt64, values.length, additionalBytes: _sizeofUint32);
|
||||||
final int result = _tail;
|
final result = _tail;
|
||||||
int tail = _tail;
|
var tail = _tail;
|
||||||
_setUint32AtTail(tail, values.length);
|
_setUint32AtTail(tail, values.length);
|
||||||
tail -= _sizeofUint32;
|
tail -= _sizeofUint32;
|
||||||
for (int value in values) {
|
for (var value in values) {
|
||||||
_setInt64AtTail(tail, value);
|
_setInt64AtTail(tail, value);
|
||||||
tail -= _sizeofInt64;
|
tail -= _sizeofInt64;
|
||||||
}
|
}
|
||||||
@@ -565,11 +570,11 @@ class Builder {
|
|||||||
int writeListUint64(List<int> values) {
|
int writeListUint64(List<int> values) {
|
||||||
assert(!_inVTable);
|
assert(!_inVTable);
|
||||||
_prepare(_sizeofUint64, values.length, additionalBytes: _sizeofUint32);
|
_prepare(_sizeofUint64, values.length, additionalBytes: _sizeofUint32);
|
||||||
final int result = _tail;
|
final result = _tail;
|
||||||
int tail = _tail;
|
var tail = _tail;
|
||||||
_setUint32AtTail(tail, values.length);
|
_setUint32AtTail(tail, values.length);
|
||||||
tail -= _sizeofUint32;
|
tail -= _sizeofUint32;
|
||||||
for (int value in values) {
|
for (var value in values) {
|
||||||
_setUint64AtTail(tail, value);
|
_setUint64AtTail(tail, value);
|
||||||
tail -= _sizeofUint64;
|
tail -= _sizeofUint64;
|
||||||
}
|
}
|
||||||
@@ -580,11 +585,11 @@ class Builder {
|
|||||||
int writeListInt32(List<int> values) {
|
int writeListInt32(List<int> values) {
|
||||||
assert(!_inVTable);
|
assert(!_inVTable);
|
||||||
_prepare(_sizeofUint32, 1 + values.length);
|
_prepare(_sizeofUint32, 1 + values.length);
|
||||||
final int result = _tail;
|
final result = _tail;
|
||||||
int tail = _tail;
|
var tail = _tail;
|
||||||
_setUint32AtTail(tail, values.length);
|
_setUint32AtTail(tail, values.length);
|
||||||
tail -= _sizeofUint32;
|
tail -= _sizeofUint32;
|
||||||
for (int value in values) {
|
for (var value in values) {
|
||||||
_setInt32AtTail(tail, value);
|
_setInt32AtTail(tail, value);
|
||||||
tail -= _sizeofInt32;
|
tail -= _sizeofInt32;
|
||||||
}
|
}
|
||||||
@@ -595,11 +600,11 @@ class Builder {
|
|||||||
int writeListUint32(List<int> values) {
|
int writeListUint32(List<int> values) {
|
||||||
assert(!_inVTable);
|
assert(!_inVTable);
|
||||||
_prepare(_sizeofUint32, 1 + values.length);
|
_prepare(_sizeofUint32, 1 + values.length);
|
||||||
final int result = _tail;
|
final result = _tail;
|
||||||
int tail = _tail;
|
var tail = _tail;
|
||||||
_setUint32AtTail(tail, values.length);
|
_setUint32AtTail(tail, values.length);
|
||||||
tail -= _sizeofUint32;
|
tail -= _sizeofUint32;
|
||||||
for (int value in values) {
|
for (var value in values) {
|
||||||
_setUint32AtTail(tail, value);
|
_setUint32AtTail(tail, value);
|
||||||
tail -= _sizeofUint32;
|
tail -= _sizeofUint32;
|
||||||
}
|
}
|
||||||
@@ -610,11 +615,11 @@ class Builder {
|
|||||||
int writeListInt16(List<int> values) {
|
int writeListInt16(List<int> values) {
|
||||||
assert(!_inVTable);
|
assert(!_inVTable);
|
||||||
_prepare(_sizeofUint32, 1, additionalBytes: 2 * values.length);
|
_prepare(_sizeofUint32, 1, additionalBytes: 2 * values.length);
|
||||||
final int result = _tail;
|
final result = _tail;
|
||||||
int tail = _tail;
|
var tail = _tail;
|
||||||
_setUint32AtTail(tail, values.length);
|
_setUint32AtTail(tail, values.length);
|
||||||
tail -= _sizeofUint32;
|
tail -= _sizeofUint32;
|
||||||
for (int value in values) {
|
for (var value in values) {
|
||||||
_setInt16AtTail(tail, value);
|
_setInt16AtTail(tail, value);
|
||||||
tail -= _sizeofInt16;
|
tail -= _sizeofInt16;
|
||||||
}
|
}
|
||||||
@@ -625,11 +630,11 @@ class Builder {
|
|||||||
int writeListUint16(List<int> values) {
|
int writeListUint16(List<int> values) {
|
||||||
assert(!_inVTable);
|
assert(!_inVTable);
|
||||||
_prepare(_sizeofUint32, 1, additionalBytes: 2 * values.length);
|
_prepare(_sizeofUint32, 1, additionalBytes: 2 * values.length);
|
||||||
final int result = _tail;
|
final result = _tail;
|
||||||
int tail = _tail;
|
var tail = _tail;
|
||||||
_setUint32AtTail(tail, values.length);
|
_setUint32AtTail(tail, values.length);
|
||||||
tail -= _sizeofUint32;
|
tail -= _sizeofUint32;
|
||||||
for (int value in values) {
|
for (var value in values) {
|
||||||
_setUint16AtTail(tail, value);
|
_setUint16AtTail(tail, value);
|
||||||
tail -= _sizeofUint16;
|
tail -= _sizeofUint16;
|
||||||
}
|
}
|
||||||
@@ -645,11 +650,11 @@ class Builder {
|
|||||||
int writeListInt8(List<int> values) {
|
int writeListInt8(List<int> values) {
|
||||||
assert(!_inVTable);
|
assert(!_inVTable);
|
||||||
_prepare(_sizeofUint32, 1, additionalBytes: values.length);
|
_prepare(_sizeofUint32, 1, additionalBytes: values.length);
|
||||||
final int result = _tail;
|
final result = _tail;
|
||||||
int tail = _tail;
|
var tail = _tail;
|
||||||
_setUint32AtTail(tail, values.length);
|
_setUint32AtTail(tail, values.length);
|
||||||
tail -= _sizeofUint32;
|
tail -= _sizeofUint32;
|
||||||
for (int value in values) {
|
for (var value in values) {
|
||||||
_setInt8AtTail(tail, value);
|
_setInt8AtTail(tail, value);
|
||||||
tail -= _sizeofUint8;
|
tail -= _sizeofUint8;
|
||||||
}
|
}
|
||||||
@@ -660,11 +665,11 @@ class Builder {
|
|||||||
int writeListUint8(List<int> values) {
|
int writeListUint8(List<int> values) {
|
||||||
assert(!_inVTable);
|
assert(!_inVTable);
|
||||||
_prepare(_sizeofUint32, 1, additionalBytes: values.length);
|
_prepare(_sizeofUint32, 1, additionalBytes: values.length);
|
||||||
final int result = _tail;
|
final result = _tail;
|
||||||
int tail = _tail;
|
var tail = _tail;
|
||||||
_setUint32AtTail(tail, values.length);
|
_setUint32AtTail(tail, values.length);
|
||||||
tail -= _sizeofUint32;
|
tail -= _sizeofUint32;
|
||||||
for (int value in values) {
|
for (var value in values) {
|
||||||
_setUint8AtTail(tail, value);
|
_setUint8AtTail(tail, value);
|
||||||
tail -= _sizeofUint8;
|
tail -= _sizeofUint8;
|
||||||
}
|
}
|
||||||
@@ -729,7 +734,7 @@ class Builder {
|
|||||||
_prepare(4, 1, additionalBytes: length + 1);
|
_prepare(4, 1, additionalBytes: length + 1);
|
||||||
_setUint32AtTail(_tail, length);
|
_setUint32AtTail(_tail, length);
|
||||||
var offset = _buf.lengthInBytes - _tail + 4;
|
var offset = _buf.lengthInBytes - _tail + 4;
|
||||||
for (int i = 0; i < length; i++) {
|
for (var i = 0; i < length; i++) {
|
||||||
_buf.setUint8(offset++, bytes[i]);
|
_buf.setUint8(offset++, bytes[i]);
|
||||||
}
|
}
|
||||||
_buf.setUint8(offset, 0); // trailing zero
|
_buf.setUint8(offset, 0); // trailing zero
|
||||||
@@ -756,7 +761,7 @@ class Builder {
|
|||||||
/// Zero-pads the buffer, which may be required for some struct layouts.
|
/// Zero-pads the buffer, which may be required for some struct layouts.
|
||||||
@pragma('vm:prefer-inline')
|
@pragma('vm:prefer-inline')
|
||||||
void pad(int howManyBytes) {
|
void pad(int howManyBytes) {
|
||||||
for (int i = 0; i < howManyBytes; i++) {
|
for (var i = 0; i < howManyBytes; i++) {
|
||||||
putUint8(0);
|
putUint8(0);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -772,17 +777,17 @@ class Builder {
|
|||||||
_maxAlign = size;
|
_maxAlign = size;
|
||||||
}
|
}
|
||||||
// Prepare amount of required space.
|
// Prepare amount of required space.
|
||||||
int dataSize = size * count + additionalBytes;
|
var dataSize = size * count + additionalBytes;
|
||||||
int alignDelta = (-(_tail + dataSize)) & (size - 1);
|
var alignDelta = (-(_tail + dataSize)) & (size - 1);
|
||||||
int bufSize = alignDelta + dataSize;
|
var bufSize = alignDelta + dataSize;
|
||||||
// Ensure that we have the required amount of space.
|
// Ensure that we have the required amount of space.
|
||||||
{
|
{
|
||||||
int oldCapacity = _buf.lengthInBytes;
|
var oldCapacity = _buf.lengthInBytes;
|
||||||
if (_tail + bufSize > oldCapacity) {
|
if (_tail + bufSize > oldCapacity) {
|
||||||
int desiredNewCapacity = (oldCapacity + bufSize) * 2;
|
var desiredNewCapacity = (oldCapacity + bufSize) * 2;
|
||||||
int deltaCapacity = desiredNewCapacity - oldCapacity;
|
var deltaCapacity = desiredNewCapacity - oldCapacity;
|
||||||
deltaCapacity += (-deltaCapacity) & (_maxAlign - 1);
|
deltaCapacity += (-deltaCapacity) & (_maxAlign - 1);
|
||||||
int newCapacity = oldCapacity + deltaCapacity;
|
var newCapacity = oldCapacity + deltaCapacity;
|
||||||
_buf = _allocator.resize(_buf, newCapacity, _tail, 0);
|
_buf = _allocator.resize(_buf, newCapacity, _tail, 0);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1018,22 +1023,22 @@ abstract class Reader<T> {
|
|||||||
/// Read the value of the given [field] in the given [object].
|
/// Read the value of the given [field] in the given [object].
|
||||||
@pragma('vm:prefer-inline')
|
@pragma('vm:prefer-inline')
|
||||||
T vTableGet(BufferContext object, int offset, int field, T defaultValue) {
|
T vTableGet(BufferContext object, int offset, int field, T defaultValue) {
|
||||||
int fieldOffset = _vTableFieldOffset(object, offset, field);
|
var fieldOffset = _vTableFieldOffset(object, offset, field);
|
||||||
return fieldOffset == 0 ? defaultValue : read(object, offset + fieldOffset);
|
return fieldOffset == 0 ? defaultValue : read(object, offset + fieldOffset);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Read the value of the given [field] in the given [object].
|
/// Read the value of the given [field] in the given [object].
|
||||||
@pragma('vm:prefer-inline')
|
@pragma('vm:prefer-inline')
|
||||||
T? vTableGetNullable(BufferContext object, int offset, int field) {
|
T? vTableGetNullable(BufferContext object, int offset, int field) {
|
||||||
int fieldOffset = _vTableFieldOffset(object, offset, field);
|
var fieldOffset = _vTableFieldOffset(object, offset, field);
|
||||||
return fieldOffset == 0 ? null : read(object, offset + fieldOffset);
|
return fieldOffset == 0 ? null : read(object, offset + fieldOffset);
|
||||||
}
|
}
|
||||||
|
|
||||||
@pragma('vm:prefer-inline')
|
@pragma('vm:prefer-inline')
|
||||||
int _vTableFieldOffset(BufferContext object, int offset, int field) {
|
int _vTableFieldOffset(BufferContext object, int offset, int field) {
|
||||||
int vTableSOffset = object._getInt32(offset);
|
var vTableSOffset = object._getInt32(offset);
|
||||||
int vTableOffset = offset - vTableSOffset;
|
var vTableOffset = offset - vTableSOffset;
|
||||||
int vTableSize = object._getUint16(vTableOffset);
|
var vTableSize = object._getUint16(vTableOffset);
|
||||||
if (field >= vTableSize) return 0;
|
if (field >= vTableSize) return 0;
|
||||||
return object._getUint16(vTableOffset + field);
|
return object._getUint16(vTableOffset + field);
|
||||||
}
|
}
|
||||||
@@ -1052,9 +1057,9 @@ class StringReader extends Reader<String> {
|
|||||||
@override
|
@override
|
||||||
@pragma('vm:prefer-inline')
|
@pragma('vm:prefer-inline')
|
||||||
String read(BufferContext bc, int offset) {
|
String read(BufferContext bc, int offset) {
|
||||||
int strOffset = bc.derefObject(offset);
|
var strOffset = bc.derefObject(offset);
|
||||||
int length = bc._getUint32(strOffset);
|
var length = bc._getUint32(strOffset);
|
||||||
Uint8List bytes = bc._asUint8List(strOffset + _sizeofUint32, length);
|
var bytes = bc._asUint8List(strOffset + _sizeofUint32, length);
|
||||||
if (asciiOptimization && _isLatin(bytes)) {
|
if (asciiOptimization && _isLatin(bytes)) {
|
||||||
return String.fromCharCodes(bytes);
|
return String.fromCharCodes(bytes);
|
||||||
}
|
}
|
||||||
@@ -1063,8 +1068,8 @@ class StringReader extends Reader<String> {
|
|||||||
|
|
||||||
@pragma('vm:prefer-inline')
|
@pragma('vm:prefer-inline')
|
||||||
static bool _isLatin(Uint8List bytes) {
|
static bool _isLatin(Uint8List bytes) {
|
||||||
int length = bytes.length;
|
var length = bytes.length;
|
||||||
for (int i = 0; i < length; i++) {
|
for (var i = 0; i < length; i++) {
|
||||||
if (bytes[i] > 127) {
|
if (bytes[i] > 127) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -1099,7 +1104,7 @@ abstract class TableReader<T> extends Reader<T> {
|
|||||||
|
|
||||||
@override
|
@override
|
||||||
T read(BufferContext bc, int offset) {
|
T read(BufferContext bc, int offset) {
|
||||||
int objectOffset = bc.derefObject(offset);
|
var objectOffset = bc.derefObject(offset);
|
||||||
return createObject(bc, objectOffset);
|
return createObject(bc, objectOffset);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1285,7 +1290,7 @@ class _FbGenericList<E> extends _FbList<E> {
|
|||||||
@pragma('vm:prefer-inline')
|
@pragma('vm:prefer-inline')
|
||||||
E operator [](int i) {
|
E operator [](int i) {
|
||||||
_items ??= List<E?>.filled(length, null);
|
_items ??= List<E?>.filled(length, null);
|
||||||
E? item = _items![i];
|
var item = _items![i];
|
||||||
if (item == null) {
|
if (item == null) {
|
||||||
item = elementReader.read(bc, offset + 4 + elementReader.size * i);
|
item = elementReader.read(bc, offset + 4 + elementReader.size * i);
|
||||||
_items![i] = item;
|
_items![i] = item;
|
||||||
@@ -1394,7 +1399,7 @@ class _VTable {
|
|||||||
@pragma('vm:prefer-inline')
|
@pragma('vm:prefer-inline')
|
||||||
bool _offsetsMatch(int vt2Start, ByteData buf) {
|
bool _offsetsMatch(int vt2Start, ByteData buf) {
|
||||||
assert(offsetsComputed);
|
assert(offsetsComputed);
|
||||||
for (int i = 0; i < numFields; i++) {
|
for (var i = 0; i < numFields; i++) {
|
||||||
if (fieldOffsets[i] !=
|
if (fieldOffsets[i] !=
|
||||||
buf.getUint16(vt2Start + _metadataLength + (2 * i), Endian.little)) {
|
buf.getUint16(vt2Start + _metadataLength + (2 * i), Endian.little)) {
|
||||||
return false;
|
return false;
|
||||||
@@ -1427,7 +1432,7 @@ class _VTable {
|
|||||||
buf.setUint16(bufOffset, tableSize, Endian.little);
|
buf.setUint16(bufOffset, tableSize, Endian.little);
|
||||||
bufOffset += 2;
|
bufOffset += 2;
|
||||||
// Field offsets.
|
// Field offsets.
|
||||||
for (int i = 0; i < numFields; i++) {
|
for (var i = 0; i < numFields; i++) {
|
||||||
buf.setUint16(bufOffset, fieldOffsets[i], Endian.little);
|
buf.setUint16(bufOffset, fieldOffsets[i], Endian.little);
|
||||||
bufOffset += 2;
|
bufOffset += 2;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ class Builder {
|
|||||||
final Map<double, _StackValue> _indirectDoubleCache = {};
|
final Map<double, _StackValue> _indirectDoubleCache = {};
|
||||||
|
|
||||||
/// Instantiate the builder if you intent to gradually build up the buffer by calling
|
/// Instantiate the builder if you intent to gradually build up the buffer by calling
|
||||||
/// add... methods and calling [finish] to receive the the resulting byte array.
|
/// add... methods and calling [finish] to receive the resulting byte array.
|
||||||
///
|
///
|
||||||
/// The default size of internal buffer is set to 2048. Provide a different value in order to avoid buffer copies.
|
/// The default size of internal buffer is set to 2048. Provide a different value in order to avoid buffer copies.
|
||||||
Builder({int size = 2048}) : _buffer = ByteData(size);
|
Builder({int size = 2048}) : _buffer = ByteData(size);
|
||||||
|
|||||||
@@ -199,7 +199,7 @@ class Reference {
|
|||||||
return _MapValueIterator(this);
|
return _MapValueIterator(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the length of the the underlying FlexBuffer value.
|
/// Returns the length of the underlying FlexBuffer value.
|
||||||
/// If the underlying value is [null] the length is 0.
|
/// If the underlying value is [null] the length is 0.
|
||||||
/// If the underlying value is a number, or a bool, the length is 1.
|
/// If the underlying value is a number, or a bool, the length is 1.
|
||||||
/// If the underlying value is a vector, or map, the length reflects number of elements / element pairs.
|
/// If the underlying value is a vector, or map, the length reflects number of elements / element pairs.
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
name: flat_buffers
|
name: flat_buffers
|
||||||
version: 2.0.0
|
version: 2.0.8
|
||||||
description: FlatBuffers reading and writing library for Dart. Based on original work by Konstantin Scheglov and Paul Berry of the Dart SDK team.
|
description: FlatBuffers reading and writing library for Dart. Based on original work by Konstantin Scheglov and Paul Berry of the Dart SDK team.
|
||||||
homepage: https://github.com/google/flatbuffers
|
homepage: https://github.com/google/flatbuffers
|
||||||
documentation: https://google.github.io/flatbuffers/index.html
|
documentation: https://google.github.io/flatbuffers/index.html
|
||||||
|
|||||||
10
dart/test/bool_structs.fbs
Normal file
10
dart/test/bool_structs.fbs
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
// Test for #7355
|
||||||
|
table Foo {
|
||||||
|
my_foo : foo_properties;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct foo_properties
|
||||||
|
{
|
||||||
|
a : bool;
|
||||||
|
b : bool;
|
||||||
|
}
|
||||||
@@ -1,7 +1,3 @@
|
|||||||
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
|
|
||||||
// for details. All rights reserved. Use of this source code is governed by a
|
|
||||||
// BSD-style license that can be found in the LICENSE file.
|
|
||||||
|
|
||||||
import 'dart:typed_data';
|
import 'dart:typed_data';
|
||||||
import 'dart:io' as io;
|
import 'dart:io' as io;
|
||||||
|
|
||||||
@@ -13,6 +9,9 @@ import 'package:test_reflective_loader/test_reflective_loader.dart';
|
|||||||
|
|
||||||
import './monster_test_my_game.example_generated.dart' as example;
|
import './monster_test_my_game.example_generated.dart' as example;
|
||||||
import './monster_test_my_game.example2_generated.dart' as example2;
|
import './monster_test_my_game.example2_generated.dart' as example2;
|
||||||
|
import './list_of_enums_generated.dart' as example3;
|
||||||
|
import './bool_structs_generated.dart' as example4;
|
||||||
|
import './keyword_test_keyword_test_generated.dart' as keyword_test;
|
||||||
|
|
||||||
main() {
|
main() {
|
||||||
defineReflectiveSuite(() {
|
defineReflectiveSuite(() {
|
||||||
@@ -20,6 +19,7 @@ main() {
|
|||||||
defineReflectiveTests(ObjectAPITest);
|
defineReflectiveTests(ObjectAPITest);
|
||||||
defineReflectiveTests(CheckOtherLangaugesData);
|
defineReflectiveTests(CheckOtherLangaugesData);
|
||||||
defineReflectiveTests(GeneratorTest);
|
defineReflectiveTests(GeneratorTest);
|
||||||
|
defineReflectiveTests(ListOfEnumsTest);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -84,7 +84,10 @@ class CheckOtherLangaugesData {
|
|||||||
'nonOwningReference: 0, vectorOfNonOwningReferences: null, '
|
'nonOwningReference: 0, vectorOfNonOwningReferences: null, '
|
||||||
'anyUniqueType: null, anyUnique: null, anyAmbiguousType: null, '
|
'anyUniqueType: null, anyUnique: null, anyAmbiguousType: null, '
|
||||||
'anyAmbiguous: null, vectorOfEnums: null, signedEnum: Race{value: -1}, '
|
'anyAmbiguous: null, vectorOfEnums: null, signedEnum: Race{value: -1}, '
|
||||||
'testrequirednestedflatbuffer: null, scalarKeySortedTables: null}, '
|
'testrequirednestedflatbuffer: null, scalarKeySortedTables: null, '
|
||||||
|
'nativeInline: null, '
|
||||||
|
'longEnumNonEnumDefault: LongEnum{value: 0}, '
|
||||||
|
'longEnumNormalDefault: LongEnum{value: 2}}, '
|
||||||
'test4: [Test{a: 10, b: 20}, Test{a: 30, b: 40}], '
|
'test4: [Test{a: 10, b: 20}, Test{a: 30, b: 40}], '
|
||||||
'testarrayofstring: [test1, test2], testarrayoftables: null, '
|
'testarrayofstring: [test1, test2], testarrayoftables: null, '
|
||||||
'enemy: Monster{pos: null, mana: 150, hp: 100, name: Fred, '
|
'enemy: Monster{pos: null, mana: 150, hp: 100, name: Fred, '
|
||||||
@@ -104,7 +107,10 @@ class CheckOtherLangaugesData {
|
|||||||
'nonOwningReference: 0, vectorOfNonOwningReferences: null, '
|
'nonOwningReference: 0, vectorOfNonOwningReferences: null, '
|
||||||
'anyUniqueType: null, anyUnique: null, anyAmbiguousType: null, '
|
'anyUniqueType: null, anyUnique: null, anyAmbiguousType: null, '
|
||||||
'anyAmbiguous: null, vectorOfEnums: null, signedEnum: Race{value: -1}, '
|
'anyAmbiguous: null, vectorOfEnums: null, signedEnum: Race{value: -1}, '
|
||||||
'testrequirednestedflatbuffer: null, scalarKeySortedTables: null}, '
|
'testrequirednestedflatbuffer: null, scalarKeySortedTables: null, '
|
||||||
|
'nativeInline: null, '
|
||||||
|
'longEnumNonEnumDefault: LongEnum{value: 0}, '
|
||||||
|
'longEnumNormalDefault: LongEnum{value: 2}}, '
|
||||||
'testnestedflatbuffer: null, testempty: null, testbool: true, '
|
'testnestedflatbuffer: null, testempty: null, testbool: true, '
|
||||||
'testhashs32Fnv1: -579221183, testhashu32Fnv1: 3715746113, '
|
'testhashs32Fnv1: -579221183, testhashu32Fnv1: 3715746113, '
|
||||||
'testhashs64Fnv1: 7930699090847568257, '
|
'testhashs64Fnv1: 7930699090847568257, '
|
||||||
@@ -128,7 +134,10 @@ class CheckOtherLangaugesData {
|
|||||||
'anyAmbiguousType: null, '
|
'anyAmbiguousType: null, '
|
||||||
'anyAmbiguous: null, vectorOfEnums: null, signedEnum: Race{value: -1}, '
|
'anyAmbiguous: null, vectorOfEnums: null, signedEnum: Race{value: -1}, '
|
||||||
'testrequirednestedflatbuffer: null, scalarKeySortedTables: [Stat{id: '
|
'testrequirednestedflatbuffer: null, scalarKeySortedTables: [Stat{id: '
|
||||||
'miss, val: 0, count: 0}, Stat{id: hit, val: 10, count: 1}]}',
|
'miss, val: 0, count: 0}, Stat{id: hit, val: 10, count: 1}], '
|
||||||
|
'nativeInline: Test{a: 1, b: 2}, '
|
||||||
|
'longEnumNonEnumDefault: LongEnum{value: 0}, '
|
||||||
|
'longEnumNormalDefault: LongEnum{value: 2}}',
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -893,3 +902,32 @@ class GeneratorTest {
|
|||||||
same(example.AnyAmbiguousAliasesTypeId.values));
|
same(example.AnyAmbiguousAliasesTypeId.values));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// See #6869
|
||||||
|
@reflectiveTest
|
||||||
|
class ListOfEnumsTest {
|
||||||
|
void test_listOfEnums() async {
|
||||||
|
var mytable = example3.MyTableObjectBuilder(options: [
|
||||||
|
example3.OptionsEnum.A,
|
||||||
|
example3.OptionsEnum.B,
|
||||||
|
example3.OptionsEnum.C
|
||||||
|
]);
|
||||||
|
var bytes = mytable.toBytes();
|
||||||
|
var mytable_read = example3.MyTable(bytes);
|
||||||
|
expect(mytable_read.options![0].value, example3.OptionsEnum.A.value);
|
||||||
|
expect(mytable_read.options![1].value, example3.OptionsEnum.B.value);
|
||||||
|
expect(mytable_read.options![2].value, example3.OptionsEnum.C.value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@reflectiveTest
|
||||||
|
class BoolInStructTest {
|
||||||
|
void test_boolInStruct() async {
|
||||||
|
var mystruct = example4.FooObjectBuilder(
|
||||||
|
myFoo: example4.FooPropertiesObjectBuilder(a: true, b: false));
|
||||||
|
var bytes = mystruct.toBytes();
|
||||||
|
var mystruct_read = example4.Foo(bytes);
|
||||||
|
expect(mystruct_read.myFoo!.a, true);
|
||||||
|
expect(mystruct_read.myFoo!.b, false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
280
dart/test/keyword_test_keyword_test_generated.dart
Normal file
280
dart/test/keyword_test_keyword_test_generated.dart
Normal file
@@ -0,0 +1,280 @@
|
|||||||
|
// automatically generated by the FlatBuffers compiler, do not modify
|
||||||
|
// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable
|
||||||
|
|
||||||
|
library keyword_test;
|
||||||
|
|
||||||
|
import 'dart:typed_data' show Uint8List;
|
||||||
|
import 'package:flat_buffers/flat_buffers.dart' as fb;
|
||||||
|
|
||||||
|
|
||||||
|
class Abc {
|
||||||
|
final int value;
|
||||||
|
const Abc._(this.value);
|
||||||
|
|
||||||
|
factory Abc.fromValue(int value) {
|
||||||
|
final result = values[value];
|
||||||
|
if (result == null) {
|
||||||
|
throw StateError('Invalid value $value for bit flag enum Abc');
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
static Abc? _createOrNull(int? value) =>
|
||||||
|
value == null ? null : Abc.fromValue(value);
|
||||||
|
|
||||||
|
static const int minValue = 0;
|
||||||
|
static const int maxValue = 2;
|
||||||
|
static bool containsValue(int value) => values.containsKey(value);
|
||||||
|
|
||||||
|
static const Abc $void = Abc._(0);
|
||||||
|
static const Abc where = Abc._(1);
|
||||||
|
static const Abc stackalloc = Abc._(2);
|
||||||
|
static const Map<int, Abc> values = {
|
||||||
|
0: $void,
|
||||||
|
1: where,
|
||||||
|
2: stackalloc};
|
||||||
|
|
||||||
|
static const fb.Reader<Abc> reader = _AbcReader();
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return 'Abc{value: $value}';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _AbcReader extends fb.Reader<Abc> {
|
||||||
|
const _AbcReader();
|
||||||
|
|
||||||
|
@override
|
||||||
|
int get size => 4;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Abc read(fb.BufferContext bc, int offset) =>
|
||||||
|
Abc.fromValue(const fb.Int32Reader().read(bc, offset));
|
||||||
|
}
|
||||||
|
|
||||||
|
class Public {
|
||||||
|
final int value;
|
||||||
|
const Public._(this.value);
|
||||||
|
|
||||||
|
factory Public.fromValue(int value) {
|
||||||
|
final result = values[value];
|
||||||
|
if (result == null) {
|
||||||
|
throw StateError('Invalid value $value for bit flag enum Public');
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
static Public? _createOrNull(int? value) =>
|
||||||
|
value == null ? null : Public.fromValue(value);
|
||||||
|
|
||||||
|
static const int minValue = 0;
|
||||||
|
static const int maxValue = 0;
|
||||||
|
static bool containsValue(int value) => values.containsKey(value);
|
||||||
|
|
||||||
|
static const Public NONE = Public._(0);
|
||||||
|
static const Map<int, Public> values = {
|
||||||
|
0: NONE};
|
||||||
|
|
||||||
|
static const fb.Reader<Public> reader = _PublicReader();
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return 'Public{value: $value}';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _PublicReader extends fb.Reader<Public> {
|
||||||
|
const _PublicReader();
|
||||||
|
|
||||||
|
@override
|
||||||
|
int get size => 4;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Public read(fb.BufferContext bc, int offset) =>
|
||||||
|
Public.fromValue(const fb.Int32Reader().read(bc, offset));
|
||||||
|
}
|
||||||
|
|
||||||
|
class KeywordsInUnionTypeId {
|
||||||
|
final int value;
|
||||||
|
const KeywordsInUnionTypeId._(this.value);
|
||||||
|
|
||||||
|
factory KeywordsInUnionTypeId.fromValue(int value) {
|
||||||
|
final result = values[value];
|
||||||
|
if (result == null) {
|
||||||
|
throw StateError('Invalid value $value for bit flag enum KeywordsInUnionTypeId');
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
static KeywordsInUnionTypeId? _createOrNull(int? value) =>
|
||||||
|
value == null ? null : KeywordsInUnionTypeId.fromValue(value);
|
||||||
|
|
||||||
|
static const int minValue = 0;
|
||||||
|
static const int maxValue = 2;
|
||||||
|
static bool containsValue(int value) => values.containsKey(value);
|
||||||
|
|
||||||
|
static const KeywordsInUnionTypeId NONE = KeywordsInUnionTypeId._(0);
|
||||||
|
static const KeywordsInUnionTypeId $static = KeywordsInUnionTypeId._(1);
|
||||||
|
static const KeywordsInUnionTypeId internal = KeywordsInUnionTypeId._(2);
|
||||||
|
static const Map<int, KeywordsInUnionTypeId> values = {
|
||||||
|
0: NONE,
|
||||||
|
1: $static,
|
||||||
|
2: internal};
|
||||||
|
|
||||||
|
static const fb.Reader<KeywordsInUnionTypeId> reader = _KeywordsInUnionTypeIdReader();
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return 'KeywordsInUnionTypeId{value: $value}';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _KeywordsInUnionTypeIdReader extends fb.Reader<KeywordsInUnionTypeId> {
|
||||||
|
const _KeywordsInUnionTypeIdReader();
|
||||||
|
|
||||||
|
@override
|
||||||
|
int get size => 1;
|
||||||
|
|
||||||
|
@override
|
||||||
|
KeywordsInUnionTypeId read(fb.BufferContext bc, int offset) =>
|
||||||
|
KeywordsInUnionTypeId.fromValue(const fb.Uint8Reader().read(bc, offset));
|
||||||
|
}
|
||||||
|
|
||||||
|
class KeywordsInTable {
|
||||||
|
KeywordsInTable._(this._bc, this._bcOffset);
|
||||||
|
factory KeywordsInTable(List<int> bytes) {
|
||||||
|
final rootRef = fb.BufferContext.fromBytes(bytes);
|
||||||
|
return reader.read(rootRef, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
static const fb.Reader<KeywordsInTable> reader = _KeywordsInTableReader();
|
||||||
|
|
||||||
|
final fb.BufferContext _bc;
|
||||||
|
final int _bcOffset;
|
||||||
|
|
||||||
|
Abc get $is => Abc.fromValue(const fb.Int32Reader().vTableGet(_bc, _bcOffset, 4, 0));
|
||||||
|
Public get private => Public.fromValue(const fb.Int32Reader().vTableGet(_bc, _bcOffset, 6, 0));
|
||||||
|
int get type => const fb.Int32Reader().vTableGet(_bc, _bcOffset, 8, 0);
|
||||||
|
bool get $default => const fb.BoolReader().vTableGet(_bc, _bcOffset, 10, false);
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return 'KeywordsInTable{\$is: ${$is}, private: ${private}, type: ${type}, \$default: ${$default}}';
|
||||||
|
}
|
||||||
|
|
||||||
|
KeywordsInTableT unpack() => KeywordsInTableT(
|
||||||
|
$is: $is,
|
||||||
|
private: private,
|
||||||
|
type: type,
|
||||||
|
$default: $default);
|
||||||
|
|
||||||
|
static int pack(fb.Builder fbBuilder, KeywordsInTableT? object) {
|
||||||
|
if (object == null) return 0;
|
||||||
|
return object.pack(fbBuilder);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class KeywordsInTableT implements fb.Packable {
|
||||||
|
Abc $is;
|
||||||
|
Public private;
|
||||||
|
int type;
|
||||||
|
bool $default;
|
||||||
|
|
||||||
|
KeywordsInTableT({
|
||||||
|
this.$is = Abc.$void,
|
||||||
|
this.private = Public.NONE,
|
||||||
|
this.type = 0,
|
||||||
|
this.$default = false});
|
||||||
|
|
||||||
|
@override
|
||||||
|
int pack(fb.Builder fbBuilder) {
|
||||||
|
fbBuilder.startTable(4);
|
||||||
|
fbBuilder.addInt32(0, $is.value);
|
||||||
|
fbBuilder.addInt32(1, private.value);
|
||||||
|
fbBuilder.addInt32(2, type);
|
||||||
|
fbBuilder.addBool(3, $default);
|
||||||
|
return fbBuilder.endTable();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return 'KeywordsInTableT{\$is: ${$is}, private: ${private}, type: ${type}, \$default: ${$default}}';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _KeywordsInTableReader extends fb.TableReader<KeywordsInTable> {
|
||||||
|
const _KeywordsInTableReader();
|
||||||
|
|
||||||
|
@override
|
||||||
|
KeywordsInTable createObject(fb.BufferContext bc, int offset) =>
|
||||||
|
KeywordsInTable._(bc, offset);
|
||||||
|
}
|
||||||
|
|
||||||
|
class KeywordsInTableBuilder {
|
||||||
|
KeywordsInTableBuilder(this.fbBuilder);
|
||||||
|
|
||||||
|
final fb.Builder fbBuilder;
|
||||||
|
|
||||||
|
void begin() {
|
||||||
|
fbBuilder.startTable(4);
|
||||||
|
}
|
||||||
|
|
||||||
|
int addIs(Abc? $is) {
|
||||||
|
fbBuilder.addInt32(0, $is?.value);
|
||||||
|
return fbBuilder.offset;
|
||||||
|
}
|
||||||
|
int addPrivate(Public? private) {
|
||||||
|
fbBuilder.addInt32(1, private?.value);
|
||||||
|
return fbBuilder.offset;
|
||||||
|
}
|
||||||
|
int addType(int? type) {
|
||||||
|
fbBuilder.addInt32(2, type);
|
||||||
|
return fbBuilder.offset;
|
||||||
|
}
|
||||||
|
int addDefault(bool? $default) {
|
||||||
|
fbBuilder.addBool(3, $default);
|
||||||
|
return fbBuilder.offset;
|
||||||
|
}
|
||||||
|
|
||||||
|
int finish() {
|
||||||
|
return fbBuilder.endTable();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class KeywordsInTableObjectBuilder extends fb.ObjectBuilder {
|
||||||
|
final Abc? _$is;
|
||||||
|
final Public? _private;
|
||||||
|
final int? _type;
|
||||||
|
final bool? _$default;
|
||||||
|
|
||||||
|
KeywordsInTableObjectBuilder({
|
||||||
|
Abc? $is,
|
||||||
|
Public? private,
|
||||||
|
int? type,
|
||||||
|
bool? $default,
|
||||||
|
})
|
||||||
|
: _$is = $is,
|
||||||
|
_private = private,
|
||||||
|
_type = type,
|
||||||
|
_$default = $default;
|
||||||
|
|
||||||
|
/// Finish building, and store into the [fbBuilder].
|
||||||
|
@override
|
||||||
|
int finish(fb.Builder fbBuilder) {
|
||||||
|
fbBuilder.startTable(4);
|
||||||
|
fbBuilder.addInt32(0, _$is?.value);
|
||||||
|
fbBuilder.addInt32(1, _private?.value);
|
||||||
|
fbBuilder.addInt32(2, _type);
|
||||||
|
fbBuilder.addBool(3, _$default);
|
||||||
|
return fbBuilder.endTable();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Convenience method to serialize to byte list.
|
||||||
|
@override
|
||||||
|
Uint8List toBytes([String? fileIdentifier]) {
|
||||||
|
final fbBuilder = fb.Builder(deduplicateTables: false);
|
||||||
|
fbBuilder.finish(finish(fbBuilder), fileIdentifier);
|
||||||
|
return fbBuilder.buffer;
|
||||||
|
}
|
||||||
|
}
|
||||||
10
dart/test/list_of_enums.fbs
Normal file
10
dart/test/list_of_enums.fbs
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
enum OptionsEnum : uint32
|
||||||
|
{
|
||||||
|
A = 1,
|
||||||
|
B = 2,
|
||||||
|
C = 3
|
||||||
|
}
|
||||||
|
|
||||||
|
table MyTable {
|
||||||
|
options : [OptionsEnum];
|
||||||
|
}
|
||||||
@@ -31,24 +31,22 @@ run 'flattests' or `flatsampletext`, or it will fail to load its files.*
|
|||||||
|
|
||||||
### Make all warnings into errors
|
### Make all warnings into errors
|
||||||
|
|
||||||
By default all Flatbuffers `cmake` targets are build with `-Werror` flag.
|
By default all Flatbuffers `cmake` targets are **not** built with the `-Werror`
|
||||||
With this flag (or `/WX` for MSVC) C++ compiler will treat all warnings as errors.
|
(or `/WX` for MSVC) flag that treats any warning as an error. This allows more
|
||||||
Additionally `-Wall -pedantic -Wextra` (or `/W4` form MSVC) flags are set.
|
flexibility for users of Flatbuffers to use newer compilers and toolsets that
|
||||||
These flags minimize the number of possible defects in code and keep code highly portable.
|
may add new warnings that would cause a build failure.
|
||||||
Using these flags is considered good practice but sometimes it can break dependent projects
|
|
||||||
if a compiler is upgraded or a toolset is changed.
|
|
||||||
Usually, newer compiler versions add new compile-time diagnostics that were unavailable before.
|
|
||||||
These new diagnostic warnings could stop the build process if `-Werror` flag is set.
|
|
||||||
|
|
||||||
It is possible to cancel `warnings as errors` flag at `cmake` configuration stage using
|
To enable a stricter build that does treat warnings as errors, set the
|
||||||
`FLATBUFFERS_CXX_FLAGS` option. Compilation flags declared in `FLATBUFFERS_CXX_FLAGS` will be
|
`FLATBUFFERS_STRICT_MODE` `cmake` compliation flag to `ON`.
|
||||||
appended to the project-level `CMAKE_CXX_FLAGS` variable.
|
|
||||||
Examples:
|
|
||||||
|
|
||||||
- GCC and Clang: `cmake . -D FLATBUFFERS_CXX_FLAGS="-Wno-error"`
|
```
|
||||||
- MSVC: `cmake . -D FLATBUFFERS_CXX_FLAGS="/WX-"`
|
cmake . -DFLATBUFFERS_STRICT_MODE=ON
|
||||||
- MSVC: `cmake . -D FLATBUFFERS_CXX_FLAGS="/Wv <compiler.version>"`
|
```
|
||||||
|
|
||||||
|
Our CI builds run with strict mode on, ensuring the code that is committed to
|
||||||
|
the project is as portable and warning free as possible. Thus developers
|
||||||
|
contributing to the project should enable strict mode locally before making a
|
||||||
|
PR.
|
||||||
|
|
||||||
## Building with VCPKG
|
## Building with VCPKG
|
||||||
|
|
||||||
@@ -63,6 +61,18 @@ You can download and install flatbuffers using the [vcpkg](https://github.com/Mi
|
|||||||
The flatbuffers port in vcpkg is kept up to date by Microsoft team members and community contributors.
|
The flatbuffers port in vcpkg is kept up to date by Microsoft team members and community contributors.
|
||||||
If the version is out of date, please [create an issue or pull request](https://github.com/Microsoft/vcpkg) on the vcpkg repository.
|
If the version is out of date, please [create an issue or pull request](https://github.com/Microsoft/vcpkg) on the vcpkg repository.
|
||||||
|
|
||||||
|
## Downloading binaries
|
||||||
|
You can download the binaries from the
|
||||||
|
[GitHub release page](https://github.com/google/flatbuffers/releases).
|
||||||
|
|
||||||
|
We generate [SLSA3 signatures](slsa.dev) using the OpenSSF's [slsa-framework/slsa-github-generator](https://github.com/slsa-framework/slsa-github-generator). To verify the binaries:
|
||||||
|
1. Install the verification tool from [slsa-framework/slsa-verifier#installation](https://github.com/slsa-framework/slsa-verifier#installation)
|
||||||
|
1. Download the file named `attestation.intoto.jsonl` from the GitHub release
|
||||||
|
1. Run:
|
||||||
|
```shell
|
||||||
|
$ slsa-verifier -artifact-path <downloaded.zip> -provenance attestation.intoto.jsonl -source github.com/google/flatbuffers -tag <version>
|
||||||
|
PASSED: Verified SLSA provenance
|
||||||
|
|
||||||
## Building for Android
|
## Building for Android
|
||||||
|
|
||||||
There is a `flatbuffers/android` directory that contains all you need to build
|
There is a `flatbuffers/android` directory that contains all you need to build
|
||||||
@@ -121,14 +131,3 @@ add this directive:
|
|||||||
set(FLATBUFFERS_MAX_PARSING_DEPTH 16)
|
set(FLATBUFFERS_MAX_PARSING_DEPTH 16)
|
||||||
```
|
```
|
||||||
to `CMakeLists.txt` file before `add_subdirectory(${FLATBUFFERS_SRC_DIR})` line.
|
to `CMakeLists.txt` file before `add_subdirectory(${FLATBUFFERS_SRC_DIR})` line.
|
||||||
|
|
||||||
#### For Google Play apps
|
|
||||||
|
|
||||||
For applications on Google Play that integrate this library, usage is tracked.
|
|
||||||
This tracking is done automatically using the embedded version string
|
|
||||||
(flatbuffer_version_string), and helps us continue to optimize it.
|
|
||||||
Aside from consuming a few extra bytes in your application binary, it shouldn't
|
|
||||||
affect your application at all. We use this information to let us know if
|
|
||||||
FlatBuffers is useful and if we should continue to invest in it. Since this is
|
|
||||||
open source, you are free to remove the version string but we would appreciate
|
|
||||||
if you would leave it in.
|
|
||||||
|
|||||||
@@ -101,7 +101,7 @@ Additional options:
|
|||||||
- `--gen-mutable` : Generate additional non-const accessors for mutating
|
- `--gen-mutable` : Generate additional non-const accessors for mutating
|
||||||
FlatBuffers in-place.
|
FlatBuffers in-place.
|
||||||
|
|
||||||
- `--gen-onefile` : Generate single output file for C# and Go.
|
- `--gen-onefile` : Generate single output file for C#, Go, and Python.
|
||||||
|
|
||||||
- `--gen-name-strings` : Generate type name functions for C++.
|
- `--gen-name-strings` : Generate type name functions for C++.
|
||||||
|
|
||||||
@@ -220,5 +220,9 @@ Additional options:
|
|||||||
|
|
||||||
- `--cs-global-alias` : Prepend `global::` to all user generated csharp classes and structs.
|
- `--cs-global-alias` : Prepend `global::` to all user generated csharp classes and structs.
|
||||||
|
|
||||||
|
- `--json-nested-bytes` : Allow a nested_flatbuffer field to be parsed as a
|
||||||
|
vector of bytes in JSON, which is unsafe unless checked by a verifier
|
||||||
|
afterwards.
|
||||||
|
|
||||||
NOTE: short-form options for generators are deprecated, use the long form
|
NOTE: short-form options for generators are deprecated, use the long form
|
||||||
whenever possible.
|
whenever possible.
|
||||||
|
|||||||
@@ -180,7 +180,8 @@ To use:
|
|||||||
An additional feature of the object API is the ability to allow you to
|
An additional feature of the object API is the ability to allow you to
|
||||||
serialize & deserialize a JSON text.
|
serialize & deserialize a JSON text.
|
||||||
To use Json Serialization, add `--cs-gen-json-serializer` option to `flatc` and
|
To use Json Serialization, add `--cs-gen-json-serializer` option to `flatc` and
|
||||||
add `Newtonsoft.Json` nuget package to csproj.
|
add `Newtonsoft.Json` nuget package to csproj. This requires explicitly setting
|
||||||
|
the `--gen-object-api` option as well.
|
||||||
|
|
||||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cs}
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cs}
|
||||||
// Deserialize MonsterT from json
|
// Deserialize MonsterT from json
|
||||||
@@ -192,7 +193,7 @@ add `Newtonsoft.Json` nuget package to csproj.
|
|||||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
* Limitation
|
* Limitation
|
||||||
* `hash` attribute currentry not supported.
|
* `hash` attribute currently not supported.
|
||||||
* NuGet package Dependency
|
* NuGet package Dependency
|
||||||
* [Newtonsoft.Json](https://github.com/JamesNK/Newtonsoft.Json)
|
* [Newtonsoft.Json](https://github.com/JamesNK/Newtonsoft.Json)
|
||||||
|
|
||||||
|
|||||||
@@ -52,10 +52,10 @@ a `[]byte`, which you pass to the `GetRootAsMonster` function:
|
|||||||
example "MyGame/Example"
|
example "MyGame/Example"
|
||||||
flatbuffers "github.com/google/flatbuffers/go"
|
flatbuffers "github.com/google/flatbuffers/go"
|
||||||
|
|
||||||
io/ioutil
|
"os"
|
||||||
)
|
)
|
||||||
|
|
||||||
buf, err := ioutil.ReadFile("monster.dat")
|
buf, err := os.ReadFile("monster.dat")
|
||||||
// handle err
|
// handle err
|
||||||
monster := example.GetRootAsMonster(buf, 0)
|
monster := example.GetRootAsMonster(buf, 0)
|
||||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||||
|
|||||||
@@ -58,7 +58,7 @@ and the generated code to read or write FlatBuffers.
|
|||||||
|
|
||||||
For example, here is how you would read a FlatBuffer binary file in Rust:
|
For example, here is how you would read a FlatBuffer binary file in Rust:
|
||||||
First, include the library and generated code. Then read the file into
|
First, include the library and generated code. Then read the file into
|
||||||
a `u8` vector, which you pass, as a byte slice, to `get_root_as_monster()`.
|
a `u8` vector, which you pass, as a byte slice, to `root_as_monster()`.
|
||||||
|
|
||||||
This full example program is available in the Rust test suite:
|
This full example program is available in the Rust test suite:
|
||||||
[monster_example.rs](https://github.com/google/flatbuffers/blob/master/tests/rust_usage_test/bin/monster_example.rs)
|
[monster_example.rs](https://github.com/google/flatbuffers/blob/master/tests/rust_usage_test/bin/monster_example.rs)
|
||||||
@@ -80,7 +80,7 @@ It can be run by `cd`ing to the `rust_usage_test` directory and executing: `carg
|
|||||||
let mut buf = Vec::new();
|
let mut buf = Vec::new();
|
||||||
f.read_to_end(&mut buf).expect("file reading failed");
|
f.read_to_end(&mut buf).expect("file reading failed");
|
||||||
|
|
||||||
let monster = my_game::example::get_root_as_monster(&buf[..]);
|
let monster = my_game::example::root_as_monster(&buf[..]);
|
||||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
`monster` is of type `Monster`, and points to somewhere *inside* your
|
`monster` is of type `Monster`, and points to somewhere *inside* your
|
||||||
@@ -108,7 +108,7 @@ the layout of things is generally not known to the user.
|
|||||||
For structs, layout is deterministic and guaranteed to be the same
|
For structs, layout is deterministic and guaranteed to be the same
|
||||||
across platforms (scalars are aligned to their
|
across platforms (scalars are aligned to their
|
||||||
own size, and structs themselves to their largest member), and you
|
own size, and structs themselves to their largest member), and you
|
||||||
are allowed to access this memory directly by using `safe_slice` and
|
are allowed to access this memory directly by using `safe_slice`
|
||||||
on the reference to a struct, or even an array of structs.
|
on the reference to a struct, or even an array of structs.
|
||||||
|
|
||||||
To compute offsets to sub-elements of a struct, make sure they
|
To compute offsets to sub-elements of a struct, make sure they
|
||||||
@@ -118,9 +118,10 @@ handy for use of arrays of structs with calls like `glVertexAttribPointer`
|
|||||||
in OpenGL or similar APIs.
|
in OpenGL or similar APIs.
|
||||||
|
|
||||||
It is important to note is that structs are still little endian on all
|
It is important to note is that structs are still little endian on all
|
||||||
machines, so only use tricks like this if you can guarantee you're not
|
machines, so the functions to enable tricks like this are only exposed on little
|
||||||
shipping on a big endian machine (using an `#[cfg(target_endian = "little")]`
|
endian machines. If you also ship on big endian machines, using an
|
||||||
attribute would be wise).
|
`#[cfg(target_endian = "little")]` attribute would be wise or your code will not
|
||||||
|
compile.
|
||||||
|
|
||||||
The special function `safe_slice` is implemented on Vector objects that are
|
The special function `safe_slice` is implemented on Vector objects that are
|
||||||
represented in memory the same way as they are represented on the wire. This
|
represented in memory the same way as they are represented on the wire. This
|
||||||
@@ -134,22 +135,22 @@ of `safe_slice`.
|
|||||||
|
|
||||||
## Access of untrusted buffers
|
## Access of untrusted buffers
|
||||||
|
|
||||||
|
The safe Rust functions to interpret a slice as a table (`root`,
|
||||||
|
`size_prefixed_root`, `root_with_opts`, and `size_prefixed_root_with_opts`)
|
||||||
|
verify the data first. This has some performance cost, but is intended to be
|
||||||
|
safe for use on flatbuffers from untrusted sources. There are corresponding
|
||||||
|
`unsafe` versions with names ending in `_unchecked` which skip this
|
||||||
|
verification, and may access arbitrary memory.
|
||||||
|
|
||||||
The generated accessor functions access fields over offsets, which is
|
The generated accessor functions access fields over offsets, which is
|
||||||
very quick. These offsets are used to index into Rust slices, so they are
|
very quick. The current implementation uses these to access memory without any
|
||||||
bounds-checked by the Rust runtime. However, our Rust implementation may
|
further bounds checking. All of the safe Rust APIs ensure the verifier is run
|
||||||
change: we may convert access functions to use direct pointer dereferencing, to
|
over these flatbuffers before accessing them.
|
||||||
improve lookup speed. As a result, users should not rely on the aforementioned
|
|
||||||
bounds-checking behavior.
|
|
||||||
|
|
||||||
When you're processing large amounts of data from a source you know (e.g.
|
When you're processing large amounts of data from a source you know (e.g.
|
||||||
your own generated data on disk), this is acceptable, but when reading
|
your own generated data on disk), the `_unchecked` versions are acceptable, but
|
||||||
data from the network that can potentially have been modified by an
|
when reading data from the network that can potentially have been modified by an
|
||||||
attacker, this is undesirable.
|
attacker, it is desirable to use the safe versions which use the verifier.
|
||||||
|
|
||||||
The C++ port provides a buffer verifier. At this time, Rust does not. Rust may
|
|
||||||
provide a verifier in a future version. In the meantime, Rust users can access
|
|
||||||
the buffer verifier generated by the C++ port through a foreign function
|
|
||||||
interface (FFI).
|
|
||||||
|
|
||||||
## Threading
|
## Threading
|
||||||
|
|
||||||
@@ -165,6 +166,17 @@ manually wrap it in synchronisation primitives. There's no automatic way to
|
|||||||
accomplish this, by design, as we feel multithreaded construction
|
accomplish this, by design, as we feel multithreaded construction
|
||||||
of a single buffer will be rare, and synchronisation overhead would be costly.
|
of a single buffer will be rare, and synchronisation overhead would be costly.
|
||||||
|
|
||||||
|
Unlike most other languages, in Rust these properties are exposed to and
|
||||||
|
enforced by the type system. `flatbuffers::Table` and the generated table types
|
||||||
|
are `Send + Sync`, indicating they may be freely shared across threads and data
|
||||||
|
may be accessed from any thread which receives a const (aka shared) reference.
|
||||||
|
There are no functions which require a mutable (aka exclusive) reference, which
|
||||||
|
means all the available functions may be called like this.
|
||||||
|
`flatbuffers::FlatBufferBuilder` is also `Send + Sync`, but all of the mutating
|
||||||
|
functions require a mutable (aka exclusive) reference which can only be created
|
||||||
|
when no other references to the `FlatBufferBuilder` exist, and may not be copied
|
||||||
|
within the same thread, let alone to a second thread.
|
||||||
|
|
||||||
## Useful tools created by others
|
## Useful tools created by others
|
||||||
|
|
||||||
* [flatc-rust](https://github.com/frol/flatc-rust) - FlatBuffers compiler
|
* [flatc-rust](https://github.com/frol/flatc-rust) - FlatBuffers compiler
|
||||||
|
|||||||
@@ -3392,6 +3392,125 @@ decimals in the JSON document.*
|
|||||||
|
|
||||||
## Advanced Features for Each Language
|
## Advanced Features for Each Language
|
||||||
|
|
||||||
|
### Vector of Unions
|
||||||
|
|
||||||
|
Some languages support storing unions directly in a vector.
|
||||||
|
|
||||||
|
~~~
|
||||||
|
// File found in tests/union_vector/union_vector.fbs
|
||||||
|
namespace Example.VectorOfUnions;
|
||||||
|
|
||||||
|
// Demonstrates the ability to have vectors of unions, and also to
|
||||||
|
// store structs and strings in unions.
|
||||||
|
|
||||||
|
table Attacker {
|
||||||
|
sword_attack_damage: int;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Rapunzel {
|
||||||
|
hair_length: int;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct BookReader {
|
||||||
|
books_read: int;
|
||||||
|
}
|
||||||
|
|
||||||
|
union Character {
|
||||||
|
MuLan: Attacker, // Can have name be different from type.
|
||||||
|
Rapunzel, // Or just both the same, as before.
|
||||||
|
Belle: BookReader,
|
||||||
|
BookFan: BookReader,
|
||||||
|
Other: string,
|
||||||
|
Unused: string
|
||||||
|
}
|
||||||
|
|
||||||
|
table Movie {
|
||||||
|
main_character: Character;
|
||||||
|
characters: [Character];
|
||||||
|
}
|
||||||
|
~~~
|
||||||
|
|
||||||
|
#### Creating
|
||||||
|
|
||||||
|
Analagously to how a union adds two fields to a table a vector of unions creates two different vectors:
|
||||||
|
one for the union data and one for the data types.
|
||||||
|
|
||||||
|
<div class="language-cpp">
|
||||||
|
C++ supports vectors of unions, but it isn't currently documented.
|
||||||
|
</div>
|
||||||
|
<div class="language-typescript">
|
||||||
|
Typescript supports vectors of unions, but it isn't currently documented.
|
||||||
|
</div>
|
||||||
|
<div class="language-php">
|
||||||
|
PHP supports vectors of unions, but it isn't currently documented.
|
||||||
|
</div>
|
||||||
|
<div class="language-java">
|
||||||
|
Java supports vectors of unions, but it isn't currently documented.
|
||||||
|
</div>
|
||||||
|
<div class="language-csharp">
|
||||||
|
~~~{.cs}
|
||||||
|
using FlatBuffers;
|
||||||
|
using Example.VectorOfUnions;
|
||||||
|
|
||||||
|
var fbb = new FlatBufferBuilder(100);
|
||||||
|
|
||||||
|
var characterTypes = new[]
|
||||||
|
{
|
||||||
|
Character.MuLan,
|
||||||
|
Character.Belle,
|
||||||
|
Character.Other,
|
||||||
|
};
|
||||||
|
var characterTypesOffset = Movie.CreateCharactersTypeVector(fbb, characterTypes);
|
||||||
|
|
||||||
|
var characters = new[]
|
||||||
|
{
|
||||||
|
Attacker.CreateAttacker(fbb, 10).Value,
|
||||||
|
BookReader.CreateBookReader(fbb, 20).Value,
|
||||||
|
fbb.CreateSharedString("Chip").Value,
|
||||||
|
};
|
||||||
|
var charactersOffset = Movie.CreateCharactersVector(fbb, characters);
|
||||||
|
|
||||||
|
var movieOffset = Movie.CreateMovie(
|
||||||
|
fbb,
|
||||||
|
Character.Rapunzel,
|
||||||
|
rapunzel,
|
||||||
|
characterTypesOffset,
|
||||||
|
charactersOffset);
|
||||||
|
Movie.FinishMovieBuffer(fbb, movieOffset);
|
||||||
|
~~~
|
||||||
|
</div>
|
||||||
|
<div class="language-kotlin">
|
||||||
|
Kotlin supports vectors of unions, but it isn't currently documented.
|
||||||
|
</div>
|
||||||
|
<div class="language-swift">
|
||||||
|
Swift supports vectors of unions, but it isn't currently documented.
|
||||||
|
</div>
|
||||||
|
|
||||||
|
#### Reading
|
||||||
|
<div class="language-csharp">
|
||||||
|
~~~{.cs}
|
||||||
|
var movie = Movie.GetRootAsMovie(fbb.DataBuffer);
|
||||||
|
|
||||||
|
for (var i = 0; i <= movie.CharactersLength; i++)
|
||||||
|
{
|
||||||
|
if (movie.CharactersType(i) == Character.MuLan)
|
||||||
|
{
|
||||||
|
var mulanSwordDamage = movie.Characters<Attacker>(i).Value.SwordAttackDamage;
|
||||||
|
}
|
||||||
|
else if (movie.CharactersType(i) == Character.Belle)
|
||||||
|
{
|
||||||
|
var belleBooksRead = movie.Characters<BookReader>(i).Value.BooksRead;
|
||||||
|
}
|
||||||
|
else if (movie.CharactersType(i) == Character.Other)
|
||||||
|
{
|
||||||
|
var otherStr = movie.CharactersAsString(i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
~~~
|
||||||
|
</div>
|
||||||
|
|
||||||
|
### Further Reading
|
||||||
|
|
||||||
Each language has a dedicated `Use in XXX` page in the Programmer's Guide
|
Each language has a dedicated `Use in XXX` page in the Programmer's Guide
|
||||||
to cover the nuances of FlatBuffers in that language.
|
to cover the nuances of FlatBuffers in that language.
|
||||||
|
|
||||||
|
|||||||
@@ -21,8 +21,8 @@ https://www.npmjs.com/package/flatbuffers.
|
|||||||
|
|
||||||
## Testing the FlatBuffers TypeScript library
|
## Testing the FlatBuffers TypeScript library
|
||||||
|
|
||||||
To run the tests, use the [TypeScriptTest.sh](https://github.com/google/
|
To run the tests, use the [TypeScriptTest.py](https://github.com/google/
|
||||||
flatbuffers/blob/master/tests/TypeScriptTest.sh) shell script.
|
flatbuffers/blob/master/tests/TypeScriptTest.py) Python3 script.
|
||||||
|
|
||||||
*Note: The TypeScript test file requires [Node.js](https://nodejs.org/en/).*
|
*Note: The TypeScript test file requires [Node.js](https://nodejs.org/en/).*
|
||||||
|
|
||||||
|
|||||||
@@ -64,7 +64,7 @@ through a *vtable*. Each table comes with a vtable (which may be shared
|
|||||||
between multiple tables with the same layout), and contains information
|
between multiple tables with the same layout), and contains information
|
||||||
where fields for this particular kind of instance of vtable are stored.
|
where fields for this particular kind of instance of vtable are stored.
|
||||||
The vtable may also indicate that the field is not present (because this
|
The vtable may also indicate that the field is not present (because this
|
||||||
FlatBuffer was written with an older version of the software, of simply
|
FlatBuffer was written with an older version of the software, or simply
|
||||||
because the information was not necessary for this instance, or deemed
|
because the information was not necessary for this instance, or deemed
|
||||||
deprecated), in which case a default value is returned.
|
deprecated), in which case a default value is returned.
|
||||||
|
|
||||||
|
|||||||
@@ -1,71 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
#
|
|
||||||
# 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.
|
|
||||||
|
|
||||||
set -e
|
|
||||||
|
|
||||||
current_dir=`pwd`
|
|
||||||
|
|
||||||
cd ../..
|
|
||||||
|
|
||||||
main_dir=`pwd`
|
|
||||||
|
|
||||||
cd ${current_dir}
|
|
||||||
|
|
||||||
# Looks for flatc within the root dir & debug
|
|
||||||
if [ -e ${main_dir}/flatc ]; then
|
|
||||||
alias fbc='${main_dir}/flatc'
|
|
||||||
elif [ -e ${main_dir}/Debug/flatc ]; then
|
|
||||||
alias fbc='${main_dir}/Debug/flatc'
|
|
||||||
else
|
|
||||||
echo 'flatc' could not be found. Make sure to build FlatBuffers from the \
|
|
||||||
$rootdir directory.
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
generator="--grpc $current_dir/greeter.fbs"
|
|
||||||
|
|
||||||
# Regenerate Go lang code
|
|
||||||
cd go
|
|
||||||
|
|
||||||
cd greeter
|
|
||||||
fbc --bfbs-filenames ../.. --go ${generator}
|
|
||||||
|
|
||||||
cd ${current_dir}
|
|
||||||
|
|
||||||
# Regenerate Python code
|
|
||||||
cd python
|
|
||||||
|
|
||||||
cd greeter
|
|
||||||
|
|
||||||
fbc --bfbs-filenames ../.. --python ${generator}
|
|
||||||
|
|
||||||
cd ${current_dir}
|
|
||||||
|
|
||||||
# Regenerate Swift code
|
|
||||||
cd swift
|
|
||||||
|
|
||||||
cd Greeter/Sources/Model
|
|
||||||
fbc --bfbs-filenames ../../../.. --swift --gen-json-emit ${generator}
|
|
||||||
|
|
||||||
cd ${current_dir}
|
|
||||||
|
|
||||||
# Regenerate Typescript code
|
|
||||||
cd ts
|
|
||||||
|
|
||||||
cd greeter/src
|
|
||||||
fbc --bfbs-filenames ../../.. --ts ${generator}
|
|
||||||
|
|
||||||
cd ${current_dir}
|
|
||||||
@@ -9,8 +9,10 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
flatbuffers "github.com/google/flatbuffers/go"
|
flatbuffers "github.com/google/flatbuffers/go"
|
||||||
models "github.com/google/flatbuffers/grpc/examples/go/greeter/models"
|
|
||||||
"google.golang.org/grpc"
|
"google.golang.org/grpc"
|
||||||
|
"google.golang.org/grpc/credentials/insecure"
|
||||||
|
|
||||||
|
models "github.com/google/flatbuffers/grpc/examples/go/greeter/models"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -63,7 +65,9 @@ func printSayManyHello(client models.GreeterClient, name string) {
|
|||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
flag.Parse()
|
flag.Parse()
|
||||||
conn, err := grpc.Dial(fmt.Sprintf("localhost:%d", 3000), grpc.WithInsecure(), grpc.WithCodec(flatbuffers.FlatbuffersCodec{}))
|
conn, err := grpc.Dial(fmt.Sprintf("localhost:%d", 3000),
|
||||||
|
grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||||
|
grpc.WithDefaultCallOptions(grpc.ForceCodec(flatbuffers.FlatbuffersCodec{})))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("fail to dial: %v", err)
|
log.Fatalf("fail to dial: %v", err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import FlatBuffers
|
|||||||
|
|
||||||
public struct models_HelloReply: FlatBufferObject, Verifiable {
|
public struct models_HelloReply: FlatBufferObject, Verifiable {
|
||||||
|
|
||||||
static func validateVersion() { FlatBuffersVersion_2_0_0() }
|
static func validateVersion() { FlatBuffersVersion_2_0_8() }
|
||||||
public var __buffer: ByteBuffer! { return _accessor.bb }
|
public var __buffer: ByteBuffer! { return _accessor.bb }
|
||||||
private var _accessor: Table
|
private var _accessor: Table
|
||||||
|
|
||||||
@@ -55,7 +55,7 @@ extension models_HelloReply: Encodable {
|
|||||||
|
|
||||||
public struct models_HelloRequest: FlatBufferObject, Verifiable {
|
public struct models_HelloRequest: FlatBufferObject, Verifiable {
|
||||||
|
|
||||||
static func validateVersion() { FlatBuffersVersion_2_0_0() }
|
static func validateVersion() { FlatBuffersVersion_2_0_8() }
|
||||||
public var __buffer: ByteBuffer! { return _accessor.bb }
|
public var __buffer: ByteBuffer! { return _accessor.bb }
|
||||||
private var _accessor: Table
|
private var _accessor: Table
|
||||||
|
|
||||||
|
|||||||
4
grpc/examples/ts/greeter/src/greeter_generated.ts
Normal file
4
grpc/examples/ts/greeter/src/greeter_generated.ts
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
// automatically generated by the FlatBuffers compiler, do not modify
|
||||||
|
|
||||||
|
export { HelloReply } from './models/hello-reply';
|
||||||
|
export { HelloRequest } from './models/hello-request';
|
||||||
@@ -7,7 +7,7 @@ import * as flatbuffers from 'flatbuffers';
|
|||||||
export class HelloReply {
|
export class HelloReply {
|
||||||
bb: flatbuffers.ByteBuffer|null = null;
|
bb: flatbuffers.ByteBuffer|null = null;
|
||||||
bb_pos = 0;
|
bb_pos = 0;
|
||||||
__init(i:number, bb:flatbuffers.ByteBuffer):HelloReply {
|
__init(i:number, bb:flatbuffers.ByteBuffer):HelloReply {
|
||||||
this.bb_pos = i;
|
this.bb_pos = i;
|
||||||
this.bb = bb;
|
this.bb = bb;
|
||||||
return this;
|
return this;
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import * as flatbuffers from 'flatbuffers';
|
|||||||
export class HelloRequest {
|
export class HelloRequest {
|
||||||
bb: flatbuffers.ByteBuffer|null = null;
|
bb: flatbuffers.ByteBuffer|null = null;
|
||||||
bb_pos = 0;
|
bb_pos = 0;
|
||||||
__init(i:number, bb:flatbuffers.ByteBuffer):HelloRequest {
|
__init(i:number, bb:flatbuffers.ByteBuffer):HelloRequest {
|
||||||
this.bb_pos = i;
|
this.bb_pos = i;
|
||||||
this.bb = bb;
|
this.bb = bb;
|
||||||
return this;
|
return this;
|
||||||
|
|||||||
@@ -4,11 +4,11 @@ LDFLAGS ?=
|
|||||||
.PHONY: all
|
.PHONY: all
|
||||||
all: server client
|
all: server client
|
||||||
|
|
||||||
greeter_generated.h: greeter.fbs
|
greeter_generated: greeter.fbs
|
||||||
flatc --grpc --cpp $<
|
flatc --grpc --cpp $<
|
||||||
|
|
||||||
server: server.cpp greeter.grpc.fb.cc greeter_generated.h greeter.grpc.fb.h
|
server: greeter_generated server.cpp greeter.grpc.fb.cc greeter.grpc.fb.h
|
||||||
g++ -std=c++11 -O2 $(CXXFLAGS) $(LDFLAGS) -lgpr -lgrpc -lgrpc++ server.cpp greeter.grpc.fb.cc -o $@
|
g++ -std=c++11 -O2 $(CXXFLAGS) $(LDFLAGS) -lgpr -lgrpc -lgrpc++ server.cpp greeter.grpc.fb.cc -o $@
|
||||||
|
|
||||||
client: client.cpp greeter.grpc.fb.cc greeter_generated.h greeter.grpc.fb.h
|
client: greeter_generated client.cpp greeter.grpc.fb.cc greeter.grpc.fb.h
|
||||||
g++ -std=c++11 -O2 $(CXXFLAGS) $(LDFLAGS) -lgpr -lgrpc -lgrpc++ client.cpp greeter.grpc.fb.cc -o $@
|
g++ -std=c++11 -O2 $(CXXFLAGS) $(LDFLAGS) -lgpr -lgrpc -lgrpc++ client.cpp greeter.grpc.fb.cc -o $@
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ package(
|
|||||||
filegroup(
|
filegroup(
|
||||||
name = "common_headers",
|
name = "common_headers",
|
||||||
srcs = [
|
srcs = [
|
||||||
"config.h",
|
|
||||||
"schema_interface.h",
|
"schema_interface.h",
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,40 +0,0 @@
|
|||||||
/*
|
|
||||||
*
|
|
||||||
* Copyright 2015, Google Inc.
|
|
||||||
* All rights reserved.
|
|
||||||
*
|
|
||||||
* Redistribution and use in source and binary forms, with or without
|
|
||||||
* modification, are permitted provided that the following conditions are
|
|
||||||
* met:
|
|
||||||
*
|
|
||||||
* * Redistributions of source code must retain the above copyright
|
|
||||||
* notice, this list of conditions and the following disclaimer.
|
|
||||||
* * Redistributions in binary form must reproduce the above
|
|
||||||
* copyright notice, this list of conditions and the following disclaimer
|
|
||||||
* in the documentation and/or other materials provided with the
|
|
||||||
* distribution.
|
|
||||||
* * Neither the name of Google Inc. nor the names of its
|
|
||||||
* contributors may be used to endorse or promote products derived from
|
|
||||||
* this software without specific prior written permission.
|
|
||||||
*
|
|
||||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
|
||||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
|
||||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
|
||||||
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
|
||||||
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
|
||||||
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
|
||||||
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
|
||||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
|
||||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
|
||||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
||||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
|
|
||||||
#ifndef SRC_COMPILER_CONFIG_H
|
|
||||||
#define SRC_COMPILER_CONFIG_H
|
|
||||||
|
|
||||||
// This file is here only because schema_interface.h, which is copied from gRPC,
|
|
||||||
// includes it. There is nothing for Flatbuffers to configure.
|
|
||||||
|
|
||||||
#endif // SRC_COMPILER_CONFIG_H
|
|
||||||
@@ -1,65 +1,31 @@
|
|||||||
/*
|
#include "src/compiler/cpp_generator.h"
|
||||||
*
|
|
||||||
* Copyright 2015, Google Inc.
|
|
||||||
* All rights reserved.
|
|
||||||
*
|
|
||||||
* Redistribution and use in source and binary forms, with or without
|
|
||||||
* modification, are permitted provided that the following conditions are
|
|
||||||
* met:
|
|
||||||
*
|
|
||||||
* * Redistributions of source code must retain the above copyright
|
|
||||||
* notice, this list of conditions and the following disclaimer.
|
|
||||||
* * Redistributions in binary form must reproduce the above
|
|
||||||
* copyright notice, this list of conditions and the following disclaimer
|
|
||||||
* in the documentation and/or other materials provided with the
|
|
||||||
* distribution.
|
|
||||||
* * Neither the name of Google Inc. nor the names of its
|
|
||||||
* contributors may be used to endorse or promote products derived from
|
|
||||||
* this software without specific prior written permission.
|
|
||||||
*
|
|
||||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
|
||||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
|
||||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
|
||||||
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
|
||||||
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
|
||||||
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
|
||||||
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
|
||||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
|
||||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
|
||||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
||||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
|
|
||||||
#include <map>
|
#include <map>
|
||||||
|
|
||||||
#include "src/compiler/cpp_generator.h"
|
|
||||||
#include "flatbuffers/util.h"
|
|
||||||
|
|
||||||
#include <sstream>
|
#include <sstream>
|
||||||
|
|
||||||
|
#include "flatbuffers/util.h"
|
||||||
|
|
||||||
namespace grpc_cpp_generator {
|
namespace grpc_cpp_generator {
|
||||||
namespace {
|
namespace {
|
||||||
|
|
||||||
grpc::string message_header_ext() { return "_generated.h"; }
|
static grpc::string service_header_ext() { return ".grpc.fb.h"; }
|
||||||
grpc::string service_header_ext() { return ".grpc.fb.h"; }
|
|
||||||
|
|
||||||
template <class T>
|
template<class T>
|
||||||
grpc::string as_string(T x) {
|
static grpc::string as_string(T x) {
|
||||||
std::ostringstream out;
|
std::ostringstream out;
|
||||||
out << x;
|
out << x;
|
||||||
return out.str();
|
return out.str();
|
||||||
}
|
}
|
||||||
|
|
||||||
inline bool ClientOnlyStreaming(const grpc_generator::Method *method) {
|
static inline bool ClientOnlyStreaming(const grpc_generator::Method *method) {
|
||||||
return method->ClientStreaming() && !method->ServerStreaming();
|
return method->ClientStreaming() && !method->ServerStreaming();
|
||||||
}
|
}
|
||||||
|
|
||||||
inline bool ServerOnlyStreaming(const grpc_generator::Method *method) {
|
static inline bool ServerOnlyStreaming(const grpc_generator::Method *method) {
|
||||||
return !method->ClientStreaming() && method->ServerStreaming();
|
return !method->ClientStreaming() && method->ServerStreaming();
|
||||||
}
|
}
|
||||||
|
|
||||||
grpc::string FilenameIdentifier(const grpc::string &filename) {
|
static grpc::string FilenameIdentifier(const grpc::string &filename) {
|
||||||
grpc::string result;
|
grpc::string result;
|
||||||
for (unsigned i = 0; i < filename.size(); i++) {
|
for (unsigned i = 0; i < filename.size(); i++) {
|
||||||
char c = filename[i];
|
char c = filename[i];
|
||||||
@@ -74,14 +40,11 @@ grpc::string FilenameIdentifier(const grpc::string &filename) {
|
|||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
} // namespace
|
|
||||||
|
|
||||||
template <class T, size_t N>
|
template<class T, size_t N>
|
||||||
T *array_end(T (&array)[N]) {
|
static T *array_end(T (&array)[N]) { return array + N; }
|
||||||
return array + N;
|
|
||||||
}
|
|
||||||
|
|
||||||
void PrintIncludes(grpc_generator::Printer *printer,
|
static void PrintIncludes(grpc_generator::Printer *printer,
|
||||||
const std::vector<grpc::string> &headers,
|
const std::vector<grpc::string> &headers,
|
||||||
const Parameters ¶ms) {
|
const Parameters ¶ms) {
|
||||||
std::map<grpc::string, grpc::string> vars;
|
std::map<grpc::string, grpc::string> vars;
|
||||||
@@ -92,9 +55,7 @@ void PrintIncludes(grpc_generator::Printer *printer,
|
|||||||
auto &s = params.grpc_search_path;
|
auto &s = params.grpc_search_path;
|
||||||
if (!s.empty()) {
|
if (!s.empty()) {
|
||||||
vars["l"] += s;
|
vars["l"] += s;
|
||||||
if (s[s.size() - 1] != '/') {
|
if (s[s.size() - 1] != '/') { vars["l"] += '/'; }
|
||||||
vars["l"] += '/';
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
for (auto i = headers.begin(); i != headers.end(); i++) {
|
for (auto i = headers.begin(); i != headers.end(); i++) {
|
||||||
@@ -103,8 +64,10 @@ void PrintIncludes(grpc_generator::Printer *printer,
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
grpc::string GetHeaderPrologue(grpc_generator::File *file,
|
grpc::string GetHeaderPrologue(grpc_generator::File *file,
|
||||||
const Parameters & /*params*/) {
|
const Parameters ¶ms) {
|
||||||
grpc::string output;
|
grpc::string output;
|
||||||
{
|
{
|
||||||
// Scope the output stream so it closes and finalizes output to the string.
|
// Scope the output stream so it closes and finalizes output to the string.
|
||||||
@@ -114,7 +77,7 @@ grpc::string GetHeaderPrologue(grpc_generator::File *file,
|
|||||||
vars["filename"] = file->filename();
|
vars["filename"] = file->filename();
|
||||||
vars["filename_identifier"] = FilenameIdentifier(file->filename());
|
vars["filename_identifier"] = FilenameIdentifier(file->filename());
|
||||||
vars["filename_base"] = file->filename_without_ext();
|
vars["filename_base"] = file->filename_without_ext();
|
||||||
vars["message_header_ext"] = file->message_header_ext();
|
vars["message_header_ext"] = params.message_header_extension;
|
||||||
|
|
||||||
printer->Print(vars, "// Generated by the gRPC C++ plugin.\n");
|
printer->Print(vars, "// Generated by the gRPC C++ plugin.\n");
|
||||||
printer->Print(vars,
|
printer->Print(vars,
|
||||||
@@ -144,15 +107,16 @@ grpc::string GetHeaderIncludes(grpc_generator::File *file,
|
|||||||
std::map<grpc::string, grpc::string> vars;
|
std::map<grpc::string, grpc::string> vars;
|
||||||
|
|
||||||
static const char *headers_strs[] = {
|
static const char *headers_strs[] = {
|
||||||
"grpcpp/impl/codegen/async_stream.h",
|
"grpcpp/impl/codegen/async_stream.h",
|
||||||
"grpcpp/impl/codegen/async_unary_call.h",
|
"grpcpp/impl/codegen/async_unary_call.h",
|
||||||
"grpcpp/impl/codegen/method_handler.h",
|
"grpcpp/impl/codegen/method_handler.h",
|
||||||
"grpcpp/impl/codegen/proto_utils.h",
|
"grpcpp/impl/codegen/proto_utils.h",
|
||||||
"grpcpp/impl/codegen/rpc_method.h",
|
"grpcpp/impl/codegen/rpc_method.h",
|
||||||
"grpcpp/impl/codegen/service_type.h",
|
"grpcpp/impl/codegen/service_type.h",
|
||||||
"grpcpp/impl/codegen/status.h",
|
"grpcpp/impl/codegen/status.h",
|
||||||
"grpcpp/impl/codegen/stub_options.h",
|
"grpcpp/impl/codegen/stub_options.h",
|
||||||
"grpcpp/impl/codegen/sync_stream.h"};
|
"grpcpp/impl/codegen/sync_stream.h"
|
||||||
|
};
|
||||||
std::vector<grpc::string> headers(headers_strs, array_end(headers_strs));
|
std::vector<grpc::string> headers(headers_strs, array_end(headers_strs));
|
||||||
PrintIncludes(printer.get(), headers, params);
|
PrintIncludes(printer.get(), headers, params);
|
||||||
printer->Print(vars, "\n");
|
printer->Print(vars, "\n");
|
||||||
@@ -176,7 +140,10 @@ grpc::string GetHeaderIncludes(grpc_generator::File *file,
|
|||||||
return output;
|
return output;
|
||||||
}
|
}
|
||||||
|
|
||||||
void PrintHeaderClientMethodInterfaces(
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
static void PrintHeaderClientMethodInterfaces(
|
||||||
grpc_generator::Printer *printer, const grpc_generator::Method *method,
|
grpc_generator::Printer *printer, const grpc_generator::Method *method,
|
||||||
std::map<grpc::string, grpc::string> *vars, bool is_public) {
|
std::map<grpc::string, grpc::string> *vars, bool is_public) {
|
||||||
(*vars)["Method"] = method->name();
|
(*vars)["Method"] = method->name();
|
||||||
@@ -187,8 +154,8 @@ void PrintHeaderClientMethodInterfaces(
|
|||||||
grpc::string prefix;
|
grpc::string prefix;
|
||||||
grpc::string method_params; // extra arguments to method
|
grpc::string method_params; // extra arguments to method
|
||||||
grpc::string raw_args; // extra arguments to raw version of method
|
grpc::string raw_args; // extra arguments to raw version of method
|
||||||
} async_prefixes[] = {{"Async", ", void* tag", ", tag"},
|
} async_prefixes[] = { { "Async", ", void* tag", ", tag" },
|
||||||
{"PrepareAsync", "", ""}};
|
{ "PrepareAsync", "", "" } };
|
||||||
|
|
||||||
if (is_public) {
|
if (is_public) {
|
||||||
if (method->NoStreaming()) {
|
if (method->NoStreaming()) {
|
||||||
@@ -196,8 +163,9 @@ void PrintHeaderClientMethodInterfaces(
|
|||||||
*vars,
|
*vars,
|
||||||
"virtual ::grpc::Status $Method$(::grpc::ClientContext* context, "
|
"virtual ::grpc::Status $Method$(::grpc::ClientContext* context, "
|
||||||
"const $Request$& request, $Response$* response) = 0;\n");
|
"const $Request$& request, $Response$* response) = 0;\n");
|
||||||
for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
|
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
|
||||||
auto& async_prefix = async_prefixes[i];
|
i++) {
|
||||||
|
auto &async_prefix = async_prefixes[i];
|
||||||
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
||||||
printer->Print(
|
printer->Print(
|
||||||
*vars,
|
*vars,
|
||||||
@@ -228,8 +196,9 @@ void PrintHeaderClientMethodInterfaces(
|
|||||||
"($Method$Raw(context, response));\n");
|
"($Method$Raw(context, response));\n");
|
||||||
printer->Outdent();
|
printer->Outdent();
|
||||||
printer->Print("}\n");
|
printer->Print("}\n");
|
||||||
for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
|
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
|
||||||
auto& async_prefix = async_prefixes[i];
|
i++) {
|
||||||
|
auto &async_prefix = async_prefixes[i];
|
||||||
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
||||||
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
||||||
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
|
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
|
||||||
@@ -262,8 +231,9 @@ void PrintHeaderClientMethodInterfaces(
|
|||||||
"($Method$Raw(context, request));\n");
|
"($Method$Raw(context, request));\n");
|
||||||
printer->Outdent();
|
printer->Outdent();
|
||||||
printer->Print("}\n");
|
printer->Print("}\n");
|
||||||
for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
|
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
|
||||||
auto& async_prefix = async_prefixes[i];
|
i++) {
|
||||||
|
auto &async_prefix = async_prefixes[i];
|
||||||
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
||||||
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
||||||
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
|
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
|
||||||
@@ -295,8 +265,9 @@ void PrintHeaderClientMethodInterfaces(
|
|||||||
"$Method$Raw(context));\n");
|
"$Method$Raw(context));\n");
|
||||||
printer->Outdent();
|
printer->Outdent();
|
||||||
printer->Print("}\n");
|
printer->Print("}\n");
|
||||||
for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
|
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
|
||||||
auto& async_prefix = async_prefixes[i];
|
i++) {
|
||||||
|
auto &async_prefix = async_prefixes[i];
|
||||||
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
||||||
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
||||||
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
|
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
|
||||||
@@ -318,8 +289,9 @@ void PrintHeaderClientMethodInterfaces(
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if (method->NoStreaming()) {
|
if (method->NoStreaming()) {
|
||||||
for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
|
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
|
||||||
auto& async_prefix = async_prefixes[i];
|
i++) {
|
||||||
|
auto &async_prefix = async_prefixes[i];
|
||||||
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
||||||
printer->Print(
|
printer->Print(
|
||||||
*vars,
|
*vars,
|
||||||
@@ -334,8 +306,9 @@ void PrintHeaderClientMethodInterfaces(
|
|||||||
"virtual ::grpc::ClientWriterInterface< $Request$>*"
|
"virtual ::grpc::ClientWriterInterface< $Request$>*"
|
||||||
" $Method$Raw("
|
" $Method$Raw("
|
||||||
"::grpc::ClientContext* context, $Response$* response) = 0;\n");
|
"::grpc::ClientContext* context, $Response$* response) = 0;\n");
|
||||||
for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
|
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
|
||||||
auto& async_prefix = async_prefixes[i];
|
i++) {
|
||||||
|
auto &async_prefix = async_prefixes[i];
|
||||||
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
||||||
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
||||||
printer->Print(
|
printer->Print(
|
||||||
@@ -351,8 +324,9 @@ void PrintHeaderClientMethodInterfaces(
|
|||||||
"virtual ::grpc::ClientReaderInterface< $Response$>* "
|
"virtual ::grpc::ClientReaderInterface< $Response$>* "
|
||||||
"$Method$Raw("
|
"$Method$Raw("
|
||||||
"::grpc::ClientContext* context, const $Request$& request) = 0;\n");
|
"::grpc::ClientContext* context, const $Request$& request) = 0;\n");
|
||||||
for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
|
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
|
||||||
auto& async_prefix = async_prefixes[i];
|
i++) {
|
||||||
|
auto &async_prefix = async_prefixes[i];
|
||||||
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
||||||
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
||||||
printer->Print(
|
printer->Print(
|
||||||
@@ -367,8 +341,9 @@ void PrintHeaderClientMethodInterfaces(
|
|||||||
"virtual ::grpc::ClientReaderWriterInterface< $Request$, "
|
"virtual ::grpc::ClientReaderWriterInterface< $Request$, "
|
||||||
"$Response$>* "
|
"$Response$>* "
|
||||||
"$Method$Raw(::grpc::ClientContext* context) = 0;\n");
|
"$Method$Raw(::grpc::ClientContext* context) = 0;\n");
|
||||||
for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
|
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
|
||||||
auto& async_prefix = async_prefixes[i];
|
i++) {
|
||||||
|
auto &async_prefix = async_prefixes[i];
|
||||||
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
||||||
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
||||||
printer->Print(
|
printer->Print(
|
||||||
@@ -382,7 +357,9 @@ void PrintHeaderClientMethodInterfaces(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void PrintHeaderClientMethod(grpc_generator::Printer *printer,
|
|
||||||
|
|
||||||
|
static void PrintHeaderClientMethod(grpc_generator::Printer *printer,
|
||||||
const grpc_generator::Method *method,
|
const grpc_generator::Method *method,
|
||||||
std::map<grpc::string, grpc::string> *vars,
|
std::map<grpc::string, grpc::string> *vars,
|
||||||
bool is_public) {
|
bool is_public) {
|
||||||
@@ -393,8 +370,8 @@ void PrintHeaderClientMethod(grpc_generator::Printer *printer,
|
|||||||
grpc::string prefix;
|
grpc::string prefix;
|
||||||
grpc::string method_params; // extra arguments to method
|
grpc::string method_params; // extra arguments to method
|
||||||
grpc::string raw_args; // extra arguments to raw version of method
|
grpc::string raw_args; // extra arguments to raw version of method
|
||||||
} async_prefixes[] = {{"Async", ", void* tag", ", tag"},
|
} async_prefixes[] = { { "Async", ", void* tag", ", tag" },
|
||||||
{"PrepareAsync", "", ""}};
|
{ "PrepareAsync", "", "" } };
|
||||||
|
|
||||||
if (is_public) {
|
if (is_public) {
|
||||||
if (method->NoStreaming()) {
|
if (method->NoStreaming()) {
|
||||||
@@ -402,8 +379,9 @@ void PrintHeaderClientMethod(grpc_generator::Printer *printer,
|
|||||||
*vars,
|
*vars,
|
||||||
"::grpc::Status $Method$(::grpc::ClientContext* context, "
|
"::grpc::Status $Method$(::grpc::ClientContext* context, "
|
||||||
"const $Request$& request, $Response$* response) override;\n");
|
"const $Request$& request, $Response$* response) override;\n");
|
||||||
for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
|
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
|
||||||
auto& async_prefix = async_prefixes[i];
|
i++) {
|
||||||
|
auto &async_prefix = async_prefixes[i];
|
||||||
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
||||||
printer->Print(
|
printer->Print(
|
||||||
*vars,
|
*vars,
|
||||||
@@ -431,8 +409,9 @@ void PrintHeaderClientMethod(grpc_generator::Printer *printer,
|
|||||||
"($Method$Raw(context, response));\n");
|
"($Method$Raw(context, response));\n");
|
||||||
printer->Outdent();
|
printer->Outdent();
|
||||||
printer->Print("}\n");
|
printer->Print("}\n");
|
||||||
for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
|
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
|
||||||
auto& async_prefix = async_prefixes[i];
|
i++) {
|
||||||
|
auto &async_prefix = async_prefixes[i];
|
||||||
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
||||||
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
||||||
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
|
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
|
||||||
@@ -463,8 +442,9 @@ void PrintHeaderClientMethod(grpc_generator::Printer *printer,
|
|||||||
"($Method$Raw(context, request));\n");
|
"($Method$Raw(context, request));\n");
|
||||||
printer->Outdent();
|
printer->Outdent();
|
||||||
printer->Print("}\n");
|
printer->Print("}\n");
|
||||||
for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
|
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
|
||||||
auto& async_prefix = async_prefixes[i];
|
i++) {
|
||||||
|
auto &async_prefix = async_prefixes[i];
|
||||||
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
||||||
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
||||||
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
|
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
|
||||||
@@ -494,8 +474,9 @@ void PrintHeaderClientMethod(grpc_generator::Printer *printer,
|
|||||||
"$Method$Raw(context));\n");
|
"$Method$Raw(context));\n");
|
||||||
printer->Outdent();
|
printer->Outdent();
|
||||||
printer->Print("}\n");
|
printer->Print("}\n");
|
||||||
for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
|
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
|
||||||
auto& async_prefix = async_prefixes[i];
|
i++) {
|
||||||
|
auto &async_prefix = async_prefixes[i];
|
||||||
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
||||||
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
||||||
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
|
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
|
||||||
@@ -516,8 +497,9 @@ void PrintHeaderClientMethod(grpc_generator::Printer *printer,
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if (method->NoStreaming()) {
|
if (method->NoStreaming()) {
|
||||||
for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
|
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
|
||||||
auto& async_prefix = async_prefixes[i];
|
i++) {
|
||||||
|
auto &async_prefix = async_prefixes[i];
|
||||||
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
||||||
printer->Print(
|
printer->Print(
|
||||||
*vars,
|
*vars,
|
||||||
@@ -531,8 +513,9 @@ void PrintHeaderClientMethod(grpc_generator::Printer *printer,
|
|||||||
"::grpc::ClientWriter< $Request$>* $Method$Raw("
|
"::grpc::ClientWriter< $Request$>* $Method$Raw("
|
||||||
"::grpc::ClientContext* context, $Response$* response) "
|
"::grpc::ClientContext* context, $Response$* response) "
|
||||||
"override;\n");
|
"override;\n");
|
||||||
for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
|
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
|
||||||
auto& async_prefix = async_prefixes[i];
|
i++) {
|
||||||
|
auto &async_prefix = async_prefixes[i];
|
||||||
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
||||||
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
||||||
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
|
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
|
||||||
@@ -547,8 +530,9 @@ void PrintHeaderClientMethod(grpc_generator::Printer *printer,
|
|||||||
"::grpc::ClientReader< $Response$>* $Method$Raw("
|
"::grpc::ClientReader< $Response$>* $Method$Raw("
|
||||||
"::grpc::ClientContext* context, const $Request$& request)"
|
"::grpc::ClientContext* context, const $Request$& request)"
|
||||||
" override;\n");
|
" override;\n");
|
||||||
for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
|
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
|
||||||
auto& async_prefix = async_prefixes[i];
|
i++) {
|
||||||
|
auto &async_prefix = async_prefixes[i];
|
||||||
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
||||||
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
||||||
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
|
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
|
||||||
@@ -562,8 +546,9 @@ void PrintHeaderClientMethod(grpc_generator::Printer *printer,
|
|||||||
printer->Print(*vars,
|
printer->Print(*vars,
|
||||||
"::grpc::ClientReaderWriter< $Request$, $Response$>* "
|
"::grpc::ClientReaderWriter< $Request$, $Response$>* "
|
||||||
"$Method$Raw(::grpc::ClientContext* context) override;\n");
|
"$Method$Raw(::grpc::ClientContext* context) override;\n");
|
||||||
for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
|
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
|
||||||
auto& async_prefix = async_prefixes[i];
|
i++) {
|
||||||
|
auto &async_prefix = async_prefixes[i];
|
||||||
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
||||||
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
||||||
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
|
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
|
||||||
@@ -577,7 +562,7 @@ void PrintHeaderClientMethod(grpc_generator::Printer *printer,
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void PrintHeaderClientMethodData(grpc_generator::Printer *printer,
|
static void PrintHeaderClientMethodData(grpc_generator::Printer *printer,
|
||||||
const grpc_generator::Method *method,
|
const grpc_generator::Method *method,
|
||||||
std::map<grpc::string, grpc::string> *vars) {
|
std::map<grpc::string, grpc::string> *vars) {
|
||||||
(*vars)["Method"] = method->name();
|
(*vars)["Method"] = method->name();
|
||||||
@@ -585,7 +570,7 @@ void PrintHeaderClientMethodData(grpc_generator::Printer *printer,
|
|||||||
"const ::grpc::internal::RpcMethod rpcmethod_$Method$_;\n");
|
"const ::grpc::internal::RpcMethod rpcmethod_$Method$_;\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
void PrintHeaderServerMethodSync(grpc_generator::Printer *printer,
|
static void PrintHeaderServerMethodSync(grpc_generator::Printer *printer,
|
||||||
const grpc_generator::Method *method,
|
const grpc_generator::Method *method,
|
||||||
std::map<grpc::string, grpc::string> *vars) {
|
std::map<grpc::string, grpc::string> *vars) {
|
||||||
(*vars)["Method"] = method->name();
|
(*vars)["Method"] = method->name();
|
||||||
@@ -619,7 +604,7 @@ void PrintHeaderServerMethodSync(grpc_generator::Printer *printer,
|
|||||||
printer->Print(method->GetTrailingComments("//").c_str());
|
printer->Print(method->GetTrailingComments("//").c_str());
|
||||||
}
|
}
|
||||||
|
|
||||||
void PrintHeaderServerMethodAsync(grpc_generator::Printer *printer,
|
static void PrintHeaderServerMethodAsync(grpc_generator::Printer *printer,
|
||||||
const grpc_generator::Method *method,
|
const grpc_generator::Method *method,
|
||||||
std::map<grpc::string, grpc::string> *vars) {
|
std::map<grpc::string, grpc::string> *vars) {
|
||||||
(*vars)["Method"] = method->name();
|
(*vars)["Method"] = method->name();
|
||||||
@@ -630,7 +615,8 @@ void PrintHeaderServerMethodAsync(grpc_generator::Printer *printer,
|
|||||||
"class WithAsyncMethod_$Method$ : public BaseClass {\n");
|
"class WithAsyncMethod_$Method$ : public BaseClass {\n");
|
||||||
printer->Print(
|
printer->Print(
|
||||||
" private:\n"
|
" private:\n"
|
||||||
" void BaseClassMustBeDerivedFromService(const Service */*service*/) {}\n");
|
" void BaseClassMustBeDerivedFromService(const Service */*service*/) "
|
||||||
|
"{}\n");
|
||||||
printer->Print(" public:\n");
|
printer->Print(" public:\n");
|
||||||
printer->Indent();
|
printer->Indent();
|
||||||
printer->Print(*vars,
|
printer->Print(*vars,
|
||||||
@@ -669,7 +655,7 @@ void PrintHeaderServerMethodAsync(grpc_generator::Printer *printer,
|
|||||||
"::grpc::Status $Method$("
|
"::grpc::Status $Method$("
|
||||||
"::grpc::ServerContext* /*context*/, "
|
"::grpc::ServerContext* /*context*/, "
|
||||||
"::grpc::ServerReader< $Request$>* /*reader*/, "
|
"::grpc::ServerReader< $Request$>* /*reader*/, "
|
||||||
"$Response$* response) final override {\n"
|
"$Response$* /*response*/) final override {\n"
|
||||||
" abort();\n"
|
" abort();\n"
|
||||||
" return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n"
|
" return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n"
|
||||||
"}\n");
|
"}\n");
|
||||||
@@ -734,7 +720,7 @@ void PrintHeaderServerMethodAsync(grpc_generator::Printer *printer,
|
|||||||
printer->Print(*vars, "};\n");
|
printer->Print(*vars, "};\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
void PrintHeaderServerMethodStreamedUnary(
|
static void PrintHeaderServerMethodStreamedUnary(
|
||||||
grpc_generator::Printer *printer, const grpc_generator::Method *method,
|
grpc_generator::Printer *printer, const grpc_generator::Method *method,
|
||||||
std::map<grpc::string, grpc::string> *vars) {
|
std::map<grpc::string, grpc::string> *vars) {
|
||||||
(*vars)["Method"] = method->name();
|
(*vars)["Method"] = method->name();
|
||||||
@@ -785,7 +771,7 @@ void PrintHeaderServerMethodStreamedUnary(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void PrintHeaderServerMethodSplitStreaming(
|
static void PrintHeaderServerMethodSplitStreaming(
|
||||||
grpc_generator::Printer *printer, const grpc_generator::Method *method,
|
grpc_generator::Printer *printer, const grpc_generator::Method *method,
|
||||||
std::map<grpc::string, grpc::string> *vars) {
|
std::map<grpc::string, grpc::string> *vars) {
|
||||||
(*vars)["Method"] = method->name();
|
(*vars)["Method"] = method->name();
|
||||||
@@ -838,7 +824,7 @@ void PrintHeaderServerMethodSplitStreaming(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void PrintHeaderServerMethodGeneric(
|
static void PrintHeaderServerMethodGeneric(
|
||||||
grpc_generator::Printer *printer, const grpc_generator::Method *method,
|
grpc_generator::Printer *printer, const grpc_generator::Method *method,
|
||||||
std::map<grpc::string, grpc::string> *vars) {
|
std::map<grpc::string, grpc::string> *vars) {
|
||||||
(*vars)["Method"] = method->name();
|
(*vars)["Method"] = method->name();
|
||||||
@@ -849,7 +835,8 @@ void PrintHeaderServerMethodGeneric(
|
|||||||
"class WithGenericMethod_$Method$ : public BaseClass {\n");
|
"class WithGenericMethod_$Method$ : public BaseClass {\n");
|
||||||
printer->Print(
|
printer->Print(
|
||||||
" private:\n"
|
" private:\n"
|
||||||
" void BaseClassMustBeDerivedFromService(const Service */*service*/) {}\n");
|
" void BaseClassMustBeDerivedFromService(const Service */*service*/) "
|
||||||
|
"{}\n");
|
||||||
printer->Print(" public:\n");
|
printer->Print(" public:\n");
|
||||||
printer->Indent();
|
printer->Indent();
|
||||||
printer->Print(*vars,
|
printer->Print(*vars,
|
||||||
@@ -908,7 +895,7 @@ void PrintHeaderServerMethodGeneric(
|
|||||||
printer->Print(*vars, "};\n");
|
printer->Print(*vars, "};\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
void PrintHeaderService(grpc_generator::Printer *printer,
|
static void PrintHeaderService(grpc_generator::Printer *printer,
|
||||||
const grpc_generator::Service *service,
|
const grpc_generator::Service *service,
|
||||||
std::map<grpc::string, grpc::string> *vars) {
|
std::map<grpc::string, grpc::string> *vars) {
|
||||||
(*vars)["Service"] = service->name();
|
(*vars)["Service"] = service->name();
|
||||||
@@ -1001,9 +988,7 @@ void PrintHeaderService(grpc_generator::Printer *printer,
|
|||||||
printer->Print(*vars, "WithAsyncMethod_$method_name$<");
|
printer->Print(*vars, "WithAsyncMethod_$method_name$<");
|
||||||
}
|
}
|
||||||
printer->Print("Service");
|
printer->Print("Service");
|
||||||
for (int i = 0; i < service->method_count(); ++i) {
|
for (int i = 0; i < service->method_count(); ++i) { printer->Print(" >"); }
|
||||||
printer->Print(" >");
|
|
||||||
}
|
|
||||||
printer->Print(" AsyncService;\n");
|
printer->Print(" AsyncService;\n");
|
||||||
|
|
||||||
// Server side - Generic
|
// Server side - Generic
|
||||||
@@ -1028,9 +1013,7 @@ void PrintHeaderService(grpc_generator::Printer *printer,
|
|||||||
}
|
}
|
||||||
printer->Print("Service");
|
printer->Print("Service");
|
||||||
for (int i = 0; i < service->method_count(); ++i) {
|
for (int i = 0; i < service->method_count(); ++i) {
|
||||||
if (service->method(i)->NoStreaming()) {
|
if (service->method(i)->NoStreaming()) { printer->Print(" >"); }
|
||||||
printer->Print(" >");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
printer->Print(" StreamedUnaryService;\n");
|
printer->Print(" StreamedUnaryService;\n");
|
||||||
|
|
||||||
@@ -1052,9 +1035,7 @@ void PrintHeaderService(grpc_generator::Printer *printer,
|
|||||||
printer->Print("Service");
|
printer->Print("Service");
|
||||||
for (int i = 0; i < service->method_count(); ++i) {
|
for (int i = 0; i < service->method_count(); ++i) {
|
||||||
auto method = service->method(i);
|
auto method = service->method(i);
|
||||||
if (ServerOnlyStreaming(method.get())) {
|
if (ServerOnlyStreaming(method.get())) { printer->Print(" >"); }
|
||||||
printer->Print(" >");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
printer->Print(" SplitStreamedService;\n");
|
printer->Print(" SplitStreamedService;\n");
|
||||||
|
|
||||||
@@ -1085,6 +1066,8 @@ void PrintHeaderService(grpc_generator::Printer *printer,
|
|||||||
printer->Print(service->GetTrailingComments("//").c_str());
|
printer->Print(service->GetTrailingComments("//").c_str());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
grpc::string GetHeaderServices(grpc_generator::File *file,
|
grpc::string GetHeaderServices(grpc_generator::File *file,
|
||||||
const Parameters ¶ms) {
|
const Parameters ¶ms) {
|
||||||
grpc::string output;
|
grpc::string output;
|
||||||
@@ -1095,9 +1078,7 @@ grpc::string GetHeaderServices(grpc_generator::File *file,
|
|||||||
// Package string is empty or ends with a dot. It is used to fully qualify
|
// Package string is empty or ends with a dot. It is used to fully qualify
|
||||||
// method names.
|
// method names.
|
||||||
vars["Package"] = file->package();
|
vars["Package"] = file->package();
|
||||||
if (!file->package().empty()) {
|
if (!file->package().empty()) { vars["Package"].append("."); }
|
||||||
vars["Package"].append(".");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!params.services_namespace.empty()) {
|
if (!params.services_namespace.empty()) {
|
||||||
vars["services_namespace"] = params.services_namespace;
|
vars["services_namespace"] = params.services_namespace;
|
||||||
@@ -1146,7 +1127,7 @@ grpc::string GetHeaderEpilogue(grpc_generator::File *file,
|
|||||||
}
|
}
|
||||||
|
|
||||||
grpc::string GetSourcePrologue(grpc_generator::File *file,
|
grpc::string GetSourcePrologue(grpc_generator::File *file,
|
||||||
const Parameters & /*params*/) {
|
const Parameters ¶ms) {
|
||||||
grpc::string output;
|
grpc::string output;
|
||||||
{
|
{
|
||||||
// Scope the output stream so it closes and finalizes output to the string.
|
// Scope the output stream so it closes and finalizes output to the string.
|
||||||
@@ -1155,13 +1136,15 @@ grpc::string GetSourcePrologue(grpc_generator::File *file,
|
|||||||
|
|
||||||
vars["filename"] = file->filename();
|
vars["filename"] = file->filename();
|
||||||
vars["filename_base"] = file->filename_without_ext();
|
vars["filename_base"] = file->filename_without_ext();
|
||||||
vars["service_header_ext"] = file->service_header_ext();
|
vars["message_header_ext"] = params.message_header_extension;
|
||||||
|
vars["service_header_ext"] = service_header_ext();
|
||||||
|
|
||||||
printer->Print(vars, "// Generated by the gRPC C++ plugin.\n");
|
printer->Print(vars, "// Generated by the gRPC C++ plugin.\n");
|
||||||
printer->Print(vars,
|
printer->Print(vars,
|
||||||
"// If you make any local change, they will be lost.\n");
|
"// If you make any local change, they will be lost.\n");
|
||||||
printer->Print(vars, "// source: $filename$\n\n");
|
printer->Print(vars, "// source: $filename$\n\n");
|
||||||
|
|
||||||
|
printer->Print(vars, "#include \"$filename_base$$message_header_ext$\"\n");
|
||||||
printer->Print(vars, "#include \"$filename_base$$service_header_ext$\"\n");
|
printer->Print(vars, "#include \"$filename_base$$service_header_ext$\"\n");
|
||||||
printer->Print(vars, "\n");
|
printer->Print(vars, "\n");
|
||||||
}
|
}
|
||||||
@@ -1177,14 +1160,15 @@ grpc::string GetSourceIncludes(grpc_generator::File *file,
|
|||||||
std::map<grpc::string, grpc::string> vars;
|
std::map<grpc::string, grpc::string> vars;
|
||||||
|
|
||||||
static const char *headers_strs[] = {
|
static const char *headers_strs[] = {
|
||||||
"grpcpp/impl/codegen/async_stream.h",
|
"grpcpp/impl/codegen/async_stream.h",
|
||||||
"grpcpp/impl/codegen/async_unary_call.h",
|
"grpcpp/impl/codegen/async_unary_call.h",
|
||||||
"grpcpp/impl/codegen/channel_interface.h",
|
"grpcpp/impl/codegen/channel_interface.h",
|
||||||
"grpcpp/impl/codegen/client_unary_call.h",
|
"grpcpp/impl/codegen/client_unary_call.h",
|
||||||
"grpcpp/impl/codegen/method_handler.h",
|
"grpcpp/impl/codegen/method_handler.h",
|
||||||
"grpcpp/impl/codegen/rpc_service_method.h",
|
"grpcpp/impl/codegen/rpc_service_method.h",
|
||||||
"grpcpp/impl/codegen/service_type.h",
|
"grpcpp/impl/codegen/service_type.h",
|
||||||
"grpcpp/impl/codegen/sync_stream.h"};
|
"grpcpp/impl/codegen/sync_stream.h"
|
||||||
|
};
|
||||||
std::vector<grpc::string> headers(headers_strs, array_end(headers_strs));
|
std::vector<grpc::string> headers(headers_strs, array_end(headers_strs));
|
||||||
PrintIncludes(printer.get(), headers, params);
|
PrintIncludes(printer.get(), headers, params);
|
||||||
|
|
||||||
@@ -1202,7 +1186,10 @@ grpc::string GetSourceIncludes(grpc_generator::File *file,
|
|||||||
return output;
|
return output;
|
||||||
}
|
}
|
||||||
|
|
||||||
void PrintSourceClientMethod(grpc_generator::Printer *printer,
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
static void PrintSourceClientMethod(grpc_generator::Printer *printer,
|
||||||
const grpc_generator::Method *method,
|
const grpc_generator::Method *method,
|
||||||
std::map<grpc::string, grpc::string> *vars) {
|
std::map<grpc::string, grpc::string> *vars) {
|
||||||
(*vars)["Method"] = method->name();
|
(*vars)["Method"] = method->name();
|
||||||
@@ -1213,8 +1200,8 @@ void PrintSourceClientMethod(grpc_generator::Printer *printer,
|
|||||||
grpc::string start; // bool literal expressed as string
|
grpc::string start; // bool literal expressed as string
|
||||||
grpc::string method_params; // extra arguments to method
|
grpc::string method_params; // extra arguments to method
|
||||||
grpc::string create_args; // extra arguments to creator
|
grpc::string create_args; // extra arguments to creator
|
||||||
} async_prefixes[] = {{"Async", "true", ", void* tag", ", tag"},
|
} async_prefixes[] = { { "Async", "true", ", void* tag", ", tag" },
|
||||||
{"PrepareAsync", "false", "", ", nullptr"}};
|
{ "PrepareAsync", "false", "", ", nullptr" } };
|
||||||
if (method->NoStreaming()) {
|
if (method->NoStreaming()) {
|
||||||
printer->Print(*vars,
|
printer->Print(*vars,
|
||||||
"::grpc::Status $ns$$Service$::Stub::$Method$("
|
"::grpc::Status $ns$$Service$::Stub::$Method$("
|
||||||
@@ -1224,8 +1211,9 @@ void PrintSourceClientMethod(grpc_generator::Printer *printer,
|
|||||||
" return ::grpc::internal::BlockingUnaryCall"
|
" return ::grpc::internal::BlockingUnaryCall"
|
||||||
"(channel_.get(), rpcmethod_$Method$_, "
|
"(channel_.get(), rpcmethod_$Method$_, "
|
||||||
"context, request, response);\n}\n\n");
|
"context, request, response);\n}\n\n");
|
||||||
for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
|
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
|
||||||
auto& async_prefix = async_prefixes[i];
|
i++) {
|
||||||
|
auto &async_prefix = async_prefixes[i];
|
||||||
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
||||||
(*vars)["AsyncStart"] = async_prefix.start;
|
(*vars)["AsyncStart"] = async_prefix.start;
|
||||||
printer->Print(*vars,
|
printer->Print(*vars,
|
||||||
@@ -1255,8 +1243,9 @@ void PrintSourceClientMethod(grpc_generator::Printer *printer,
|
|||||||
"rpcmethod_$Method$_, "
|
"rpcmethod_$Method$_, "
|
||||||
"context, response);\n"
|
"context, response);\n"
|
||||||
"}\n\n");
|
"}\n\n");
|
||||||
for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
|
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
|
||||||
auto& async_prefix = async_prefixes[i];
|
i++) {
|
||||||
|
auto &async_prefix = async_prefixes[i];
|
||||||
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
||||||
(*vars)["AsyncStart"] = async_prefix.start;
|
(*vars)["AsyncStart"] = async_prefix.start;
|
||||||
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
||||||
@@ -1287,8 +1276,9 @@ void PrintSourceClientMethod(grpc_generator::Printer *printer,
|
|||||||
"rpcmethod_$Method$_, "
|
"rpcmethod_$Method$_, "
|
||||||
"context, request);\n"
|
"context, request);\n"
|
||||||
"}\n\n");
|
"}\n\n");
|
||||||
for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
|
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
|
||||||
auto& async_prefix = async_prefixes[i];
|
i++) {
|
||||||
|
auto &async_prefix = async_prefixes[i];
|
||||||
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
||||||
(*vars)["AsyncStart"] = async_prefix.start;
|
(*vars)["AsyncStart"] = async_prefix.start;
|
||||||
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
||||||
@@ -1319,8 +1309,9 @@ void PrintSourceClientMethod(grpc_generator::Printer *printer,
|
|||||||
"rpcmethod_$Method$_, "
|
"rpcmethod_$Method$_, "
|
||||||
"context);\n"
|
"context);\n"
|
||||||
"}\n\n");
|
"}\n\n");
|
||||||
for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
|
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
|
||||||
auto& async_prefix = async_prefixes[i];
|
i++) {
|
||||||
|
auto &async_prefix = async_prefixes[i];
|
||||||
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
||||||
(*vars)["AsyncStart"] = async_prefix.start;
|
(*vars)["AsyncStart"] = async_prefix.start;
|
||||||
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
||||||
@@ -1342,17 +1333,18 @@ void PrintSourceClientMethod(grpc_generator::Printer *printer,
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void PrintSourceServerMethod(grpc_generator::Printer *printer,
|
static void PrintSourceServerMethod(grpc_generator::Printer *printer,
|
||||||
const grpc_generator::Method *method,
|
const grpc_generator::Method *method,
|
||||||
std::map<grpc::string, grpc::string> *vars) {
|
std::map<grpc::string, grpc::string> *vars) {
|
||||||
(*vars)["Method"] = method->name();
|
(*vars)["Method"] = method->name();
|
||||||
(*vars)["Request"] = method->input_type_name();
|
(*vars)["Request"] = method->input_type_name();
|
||||||
(*vars)["Response"] = method->output_type_name();
|
(*vars)["Response"] = method->output_type_name();
|
||||||
if (method->NoStreaming()) {
|
if (method->NoStreaming()) {
|
||||||
printer->Print(*vars,
|
printer->Print(
|
||||||
"::grpc::Status $ns$$Service$::Service::$Method$("
|
*vars,
|
||||||
"::grpc::ServerContext* /*context*/, "
|
"::grpc::Status $ns$$Service$::Service::$Method$("
|
||||||
"const $Request$* /*request*/, $Response$* /*response*/) {\n");
|
"::grpc::ServerContext* /*context*/, "
|
||||||
|
"const $Request$* /*request*/, $Response$* /*response*/) {\n");
|
||||||
printer->Print(
|
printer->Print(
|
||||||
" return ::grpc::Status("
|
" return ::grpc::Status("
|
||||||
"::grpc::StatusCode::UNIMPLEMENTED, \"\");\n");
|
"::grpc::StatusCode::UNIMPLEMENTED, \"\");\n");
|
||||||
@@ -1390,7 +1382,7 @@ void PrintSourceServerMethod(grpc_generator::Printer *printer,
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void PrintSourceService(grpc_generator::Printer *printer,
|
static void PrintSourceService(grpc_generator::Printer *printer,
|
||||||
const grpc_generator::Service *service,
|
const grpc_generator::Service *service,
|
||||||
std::map<grpc::string, grpc::string> *vars) {
|
std::map<grpc::string, grpc::string> *vars) {
|
||||||
(*vars)["Service"] = service->name();
|
(*vars)["Service"] = service->name();
|
||||||
@@ -1507,6 +1499,8 @@ void PrintSourceService(grpc_generator::Printer *printer,
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
grpc::string GetSourceServices(grpc_generator::File *file,
|
grpc::string GetSourceServices(grpc_generator::File *file,
|
||||||
const Parameters ¶ms) {
|
const Parameters ¶ms) {
|
||||||
grpc::string output;
|
grpc::string output;
|
||||||
@@ -1517,9 +1511,7 @@ grpc::string GetSourceServices(grpc_generator::File *file,
|
|||||||
// Package string is empty or ends with a dot. It is used to fully qualify
|
// Package string is empty or ends with a dot. It is used to fully qualify
|
||||||
// method names.
|
// method names.
|
||||||
vars["Package"] = file->package();
|
vars["Package"] = file->package();
|
||||||
if (!file->package().empty()) {
|
if (!file->package().empty()) { vars["Package"].append("."); }
|
||||||
vars["Package"].append(".");
|
|
||||||
}
|
|
||||||
if (!params.services_namespace.empty()) {
|
if (!params.services_namespace.empty()) {
|
||||||
vars["ns"] = params.services_namespace + "::";
|
vars["ns"] = params.services_namespace + "::";
|
||||||
vars["prefix"] = params.services_namespace;
|
vars["prefix"] = params.services_namespace;
|
||||||
@@ -1554,9 +1546,8 @@ grpc::string GetSourceEpilogue(grpc_generator::File *file,
|
|||||||
return temp;
|
return temp;
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO(mmukhi): Make sure we need parameters or not.
|
|
||||||
grpc::string GetMockPrologue(grpc_generator::File *file,
|
grpc::string GetMockPrologue(grpc_generator::File *file,
|
||||||
const Parameters & /*params*/) {
|
const Parameters ¶ms) {
|
||||||
grpc::string output;
|
grpc::string output;
|
||||||
{
|
{
|
||||||
// Scope the output stream so it closes and finalizes output to the string.
|
// Scope the output stream so it closes and finalizes output to the string.
|
||||||
@@ -1565,7 +1556,7 @@ grpc::string GetMockPrologue(grpc_generator::File *file,
|
|||||||
|
|
||||||
vars["filename"] = file->filename();
|
vars["filename"] = file->filename();
|
||||||
vars["filename_base"] = file->filename_without_ext();
|
vars["filename_base"] = file->filename_without_ext();
|
||||||
vars["message_header_ext"] = message_header_ext();
|
vars["message_header_ext"] = params.message_header_extension;
|
||||||
vars["service_header_ext"] = service_header_ext();
|
vars["service_header_ext"] = service_header_ext();
|
||||||
|
|
||||||
printer->Print(vars, "// Generated by the gRPC C++ plugin.\n");
|
printer->Print(vars, "// Generated by the gRPC C++ plugin.\n");
|
||||||
@@ -1591,9 +1582,9 @@ grpc::string GetMockIncludes(grpc_generator::File *file,
|
|||||||
std::map<grpc::string, grpc::string> vars;
|
std::map<grpc::string, grpc::string> vars;
|
||||||
|
|
||||||
static const char *headers_strs[] = {
|
static const char *headers_strs[] = {
|
||||||
"grpcpp/impl/codegen/async_stream.h",
|
"grpcpp/impl/codegen/async_stream.h",
|
||||||
"grpcpp/impl/codegen/sync_stream.h",
|
"grpcpp/impl/codegen/sync_stream.h",
|
||||||
"gmock/gmock.h",
|
"gmock/gmock.h",
|
||||||
};
|
};
|
||||||
std::vector<grpc::string> headers(headers_strs, array_end(headers_strs));
|
std::vector<grpc::string> headers(headers_strs, array_end(headers_strs));
|
||||||
PrintIncludes(printer.get(), headers, params);
|
PrintIncludes(printer.get(), headers, params);
|
||||||
@@ -1612,7 +1603,10 @@ grpc::string GetMockIncludes(grpc_generator::File *file,
|
|||||||
return output;
|
return output;
|
||||||
}
|
}
|
||||||
|
|
||||||
void PrintMockClientMethods(grpc_generator::Printer *printer,
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
static void PrintMockClientMethods(grpc_generator::Printer *printer,
|
||||||
const grpc_generator::Method *method,
|
const grpc_generator::Method *method,
|
||||||
std::map<grpc::string, grpc::string> *vars) {
|
std::map<grpc::string, grpc::string> *vars) {
|
||||||
(*vars)["Method"] = method->name();
|
(*vars)["Method"] = method->name();
|
||||||
@@ -1623,15 +1617,17 @@ void PrintMockClientMethods(grpc_generator::Printer *printer,
|
|||||||
grpc::string prefix;
|
grpc::string prefix;
|
||||||
grpc::string method_params; // extra arguments to method
|
grpc::string method_params; // extra arguments to method
|
||||||
int extra_method_param_count;
|
int extra_method_param_count;
|
||||||
} async_prefixes[] = {{"Async", ", void* tag", 1}, {"PrepareAsync", "", 0}};
|
} async_prefixes[] = { { "Async", ", void* tag", 1 },
|
||||||
|
{ "PrepareAsync", "", 0 } };
|
||||||
|
|
||||||
if (method->NoStreaming()) {
|
if (method->NoStreaming()) {
|
||||||
printer->Print(
|
printer->Print(
|
||||||
*vars,
|
*vars,
|
||||||
"MOCK_METHOD3($Method$, ::grpc::Status(::grpc::ClientContext* context, "
|
"MOCK_METHOD3($Method$, ::grpc::Status(::grpc::ClientContext* context, "
|
||||||
"const $Request$& request, $Response$* response));\n");
|
"const $Request$& request, $Response$* response));\n");
|
||||||
for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
|
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
|
||||||
auto& async_prefix = async_prefixes[i];
|
i++) {
|
||||||
|
auto &async_prefix = async_prefixes[i];
|
||||||
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
||||||
printer->Print(
|
printer->Print(
|
||||||
*vars,
|
*vars,
|
||||||
@@ -1646,12 +1642,13 @@ void PrintMockClientMethods(grpc_generator::Printer *printer,
|
|||||||
"MOCK_METHOD2($Method$Raw, "
|
"MOCK_METHOD2($Method$Raw, "
|
||||||
"::grpc::ClientWriterInterface< $Request$>*"
|
"::grpc::ClientWriterInterface< $Request$>*"
|
||||||
"(::grpc::ClientContext* context, $Response$* response));\n");
|
"(::grpc::ClientContext* context, $Response$* response));\n");
|
||||||
for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
|
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
|
||||||
auto& async_prefix = async_prefixes[i];
|
i++) {
|
||||||
|
auto &async_prefix = async_prefixes[i];
|
||||||
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
||||||
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
||||||
(*vars)["MockArgs"] =
|
(*vars)["MockArgs"] =
|
||||||
flatbuffers::NumToString(3 + async_prefix.extra_method_param_count);
|
flatbuffers::NumToString(3 + async_prefix.extra_method_param_count);
|
||||||
printer->Print(*vars,
|
printer->Print(*vars,
|
||||||
"MOCK_METHOD$MockArgs$($AsyncPrefix$$Method$Raw, "
|
"MOCK_METHOD$MockArgs$($AsyncPrefix$$Method$Raw, "
|
||||||
"::grpc::ClientAsyncWriterInterface< $Request$>*"
|
"::grpc::ClientAsyncWriterInterface< $Request$>*"
|
||||||
@@ -1664,8 +1661,9 @@ void PrintMockClientMethods(grpc_generator::Printer *printer,
|
|||||||
"MOCK_METHOD2($Method$Raw, "
|
"MOCK_METHOD2($Method$Raw, "
|
||||||
"::grpc::ClientReaderInterface< $Response$>*"
|
"::grpc::ClientReaderInterface< $Response$>*"
|
||||||
"(::grpc::ClientContext* context, const $Request$& request));\n");
|
"(::grpc::ClientContext* context, const $Request$& request));\n");
|
||||||
for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
|
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
|
||||||
auto& async_prefix = async_prefixes[i];
|
i++) {
|
||||||
|
auto &async_prefix = async_prefixes[i];
|
||||||
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
||||||
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
||||||
(*vars)["MockArgs"] =
|
(*vars)["MockArgs"] =
|
||||||
@@ -1683,8 +1681,9 @@ void PrintMockClientMethods(grpc_generator::Printer *printer,
|
|||||||
"MOCK_METHOD1($Method$Raw, "
|
"MOCK_METHOD1($Method$Raw, "
|
||||||
"::grpc::ClientReaderWriterInterface< $Request$, $Response$>*"
|
"::grpc::ClientReaderWriterInterface< $Request$, $Response$>*"
|
||||||
"(::grpc::ClientContext* context));\n");
|
"(::grpc::ClientContext* context));\n");
|
||||||
for (size_t i = 0; i < sizeof(async_prefixes)/sizeof(async_prefixes[0]); i ++) {
|
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
|
||||||
auto& async_prefix = async_prefixes[i];
|
i++) {
|
||||||
|
auto &async_prefix = async_prefixes[i];
|
||||||
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
||||||
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
||||||
(*vars)["MockArgs"] =
|
(*vars)["MockArgs"] =
|
||||||
@@ -1699,7 +1698,7 @@ void PrintMockClientMethods(grpc_generator::Printer *printer,
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void PrintMockService(grpc_generator::Printer *printer,
|
static void PrintMockService(grpc_generator::Printer *printer,
|
||||||
const grpc_generator::Service *service,
|
const grpc_generator::Service *service,
|
||||||
std::map<grpc::string, grpc::string> *vars) {
|
std::map<grpc::string, grpc::string> *vars) {
|
||||||
(*vars)["Service"] = service->name();
|
(*vars)["Service"] = service->name();
|
||||||
@@ -1715,6 +1714,8 @@ void PrintMockService(grpc_generator::Printer *printer,
|
|||||||
printer->Print("};\n");
|
printer->Print("};\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
grpc::string GetMockServices(grpc_generator::File *file,
|
grpc::string GetMockServices(grpc_generator::File *file,
|
||||||
const Parameters ¶ms) {
|
const Parameters ¶ms) {
|
||||||
grpc::string output;
|
grpc::string output;
|
||||||
@@ -1725,9 +1726,7 @@ grpc::string GetMockServices(grpc_generator::File *file,
|
|||||||
// Package string is empty or ends with a dot. It is used to fully qualify
|
// Package string is empty or ends with a dot. It is used to fully qualify
|
||||||
// method names.
|
// method names.
|
||||||
vars["Package"] = file->package();
|
vars["Package"] = file->package();
|
||||||
if (!file->package().empty()) {
|
if (!file->package().empty()) { vars["Package"].append("."); }
|
||||||
vars["Package"].append(".");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!params.services_namespace.empty()) {
|
if (!params.services_namespace.empty()) {
|
||||||
vars["services_namespace"] = params.services_namespace;
|
vars["services_namespace"] = params.services_namespace;
|
||||||
|
|||||||
@@ -1,36 +1,3 @@
|
|||||||
/*
|
|
||||||
*
|
|
||||||
* Copyright 2015, Google Inc.
|
|
||||||
* All rights reserved.
|
|
||||||
*
|
|
||||||
* Redistribution and use in source and binary forms, with or without
|
|
||||||
* modification, are permitted provided that the following conditions are
|
|
||||||
* met:
|
|
||||||
*
|
|
||||||
* * Redistributions of source code must retain the above copyright
|
|
||||||
* notice, this list of conditions and the following disclaimer.
|
|
||||||
* * Redistributions in binary form must reproduce the above
|
|
||||||
* copyright notice, this list of conditions and the following disclaimer
|
|
||||||
* in the documentation and/or other materials provided with the
|
|
||||||
* distribution.
|
|
||||||
* * Neither the name of Google Inc. nor the names of its
|
|
||||||
* contributors may be used to endorse or promote products derived from
|
|
||||||
* this software without specific prior written permission.
|
|
||||||
*
|
|
||||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
|
||||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
|
||||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
|
||||||
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
|
||||||
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
|
||||||
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
|
||||||
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
|
||||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
|
||||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
|
||||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
||||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
|
|
||||||
#ifndef GRPC_INTERNAL_COMPILER_CPP_GENERATOR_H
|
#ifndef GRPC_INTERNAL_COMPILER_CPP_GENERATOR_H
|
||||||
#define GRPC_INTERNAL_COMPILER_CPP_GENERATOR_H
|
#define GRPC_INTERNAL_COMPILER_CPP_GENERATOR_H
|
||||||
|
|
||||||
@@ -41,12 +8,11 @@
|
|||||||
#include <memory>
|
#include <memory>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
#include "src/compiler/config.h"
|
|
||||||
#include "src/compiler/schema_interface.h"
|
#include "src/compiler/schema_interface.h"
|
||||||
|
|
||||||
#ifndef GRPC_CUSTOM_STRING
|
#ifndef GRPC_CUSTOM_STRING
|
||||||
#include <string>
|
# include <string>
|
||||||
#define GRPC_CUSTOM_STRING std::string
|
# define GRPC_CUSTOM_STRING std::string
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
namespace grpc {
|
namespace grpc {
|
||||||
@@ -67,6 +33,8 @@ struct Parameters {
|
|||||||
grpc::string grpc_search_path;
|
grpc::string grpc_search_path;
|
||||||
// Generate GMOCK code to facilitate unit testing.
|
// Generate GMOCK code to facilitate unit testing.
|
||||||
bool generate_mock_code;
|
bool generate_mock_code;
|
||||||
|
// By default, use "_generated.h"
|
||||||
|
std::string message_header_extension;
|
||||||
};
|
};
|
||||||
|
|
||||||
// Return the prologue of the generated header file.
|
// Return the prologue of the generated header file.
|
||||||
|
|||||||
@@ -1,47 +1,13 @@
|
|||||||
/*
|
|
||||||
*
|
|
||||||
* Copyright 2015, Google Inc.
|
|
||||||
* All rights reserved.
|
|
||||||
*
|
|
||||||
* Redistribution and use in source and binary forms, with or without
|
|
||||||
* modification, are permitted provided that the following conditions are
|
|
||||||
* met:
|
|
||||||
*
|
|
||||||
* * Redistributions of source code must retain the above copyright
|
|
||||||
* notice, this list of conditions and the following disclaimer.
|
|
||||||
* * Redistributions in binary form must reproduce the above
|
|
||||||
* copyright notice, this list of conditions and the following disclaimer
|
|
||||||
* in the documentation AN/or other materials provided with the
|
|
||||||
* distribution.
|
|
||||||
* * Neither the name of Google Inc. nor the names of its
|
|
||||||
* contributors may be used to endorse or promote products derived from
|
|
||||||
* this software without specific prior written permission.
|
|
||||||
*
|
|
||||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
|
||||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
|
||||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
|
||||||
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
|
||||||
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
|
||||||
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
|
||||||
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
|
||||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
|
||||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
|
||||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
||||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
|
|
||||||
#include <map>
|
|
||||||
#include <cctype>
|
|
||||||
#include <sstream>
|
|
||||||
|
|
||||||
#include "src/compiler/go_generator.h"
|
#include "src/compiler/go_generator.h"
|
||||||
|
|
||||||
template <class T>
|
#include <cctype>
|
||||||
grpc::string as_string(T x) {
|
#include <map>
|
||||||
std::ostringstream out;
|
#include <sstream>
|
||||||
out << x;
|
|
||||||
return out.str();
|
template<class T> grpc::string as_string(T x) {
|
||||||
|
std::ostringstream out;
|
||||||
|
out << x;
|
||||||
|
return out.str();
|
||||||
}
|
}
|
||||||
|
|
||||||
inline bool ClientOnlyStreaming(const grpc_generator::Method *method) {
|
inline bool ClientOnlyStreaming(const grpc_generator::Method *method) {
|
||||||
@@ -53,24 +19,23 @@ inline bool ServerOnlyStreaming(const grpc_generator::Method *method) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
namespace grpc_go_generator {
|
namespace grpc_go_generator {
|
||||||
|
namespace {
|
||||||
|
|
||||||
// Returns string with first letter to lowerCase
|
// Returns string with first letter to lowerCase
|
||||||
grpc::string unexportName(grpc::string s) {
|
static grpc::string unexportName(grpc::string s) {
|
||||||
if (s.empty())
|
if (s.empty()) return s;
|
||||||
return s;
|
s[0] = static_cast<char>(std::tolower(s[0]));
|
||||||
s[0] = static_cast<char>(std::tolower(s[0]));
|
return s;
|
||||||
return s;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Returns string with first letter to uppercase
|
// Returns string with first letter to uppercase
|
||||||
grpc::string exportName(grpc::string s) {
|
static grpc::string exportName(grpc::string s) {
|
||||||
if (s.empty())
|
if (s.empty()) return s;
|
||||||
return s;
|
s[0] = static_cast<char>(std::toupper(s[0]));
|
||||||
s[0] = static_cast<char>(std::toupper(s[0]));
|
return s;
|
||||||
return s;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void GenerateError(grpc_generator::Printer *printer,
|
static void GenerateError(grpc_generator::Printer *printer,
|
||||||
std::map<grpc::string, grpc::string> vars,
|
std::map<grpc::string, grpc::string> vars,
|
||||||
const bool multiple_return = true) {
|
const bool multiple_return = true) {
|
||||||
printer->Print(vars, "if $Error_Check$ {\n");
|
printer->Print(vars, "if $Error_Check$ {\n");
|
||||||
@@ -82,50 +47,65 @@ void GenerateError(grpc_generator::Printer *printer,
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Generates imports for the service
|
// Generates imports for the service
|
||||||
void GenerateImports(grpc_generator::File *file, grpc_generator::Printer *printer,
|
static void GenerateImports(grpc_generator::File *file,
|
||||||
|
grpc_generator::Printer *printer,
|
||||||
std::map<grpc::string, grpc::string> vars) {
|
std::map<grpc::string, grpc::string> vars) {
|
||||||
vars["filename"] = file->filename();
|
vars["filename"] = file->filename();
|
||||||
printer->Print("//Generated by gRPC Go plugin\n");
|
printer->Print("//Generated by gRPC Go plugin\n");
|
||||||
printer->Print("//If you make any local changes, they will be lost\n");
|
printer->Print("//If you make any local changes, they will be lost\n");
|
||||||
printer->Print(vars, "//source: $filename$\n\n");
|
printer->Print(vars, "//source: $filename$\n\n");
|
||||||
printer->Print(vars, "package $Package$\n\n");
|
printer->Print(vars, "package $Package$\n\n");
|
||||||
printer->Print("import (\n");
|
printer->Print("import (\n");
|
||||||
printer->Indent();
|
printer->Indent();
|
||||||
printer->Print(vars, "$context$ \"context\"\n");
|
printer->Print(vars, "$context$ \"context\"\n");
|
||||||
printer->Print("flatbuffers \"github.com/google/flatbuffers/go\"\n");
|
printer->Print("flatbuffers \"github.com/google/flatbuffers/go\"\n");
|
||||||
printer->Print(vars, "$grpc$ \"google.golang.org/grpc\"\n");
|
printer->Print(vars, "$grpc$ \"google.golang.org/grpc\"\n");
|
||||||
printer->Print("\"google.golang.org/grpc/codes\"\n");
|
printer->Print("\"google.golang.org/grpc/codes\"\n");
|
||||||
printer->Print("\"google.golang.org/grpc/status\"\n");
|
printer->Print("\"google.golang.org/grpc/status\"\n");
|
||||||
printer->Outdent();
|
printer->Outdent();
|
||||||
printer->Print(")\n\n");
|
printer->Print(")\n\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Generates Server method signature source
|
// Generates Server method signature source
|
||||||
void GenerateServerMethodSignature(const grpc_generator::Method *method, grpc_generator::Printer *printer,
|
static void GenerateServerMethodSignature(const grpc_generator::Method *method,
|
||||||
|
grpc_generator::Printer *printer,
|
||||||
std::map<grpc::string, grpc::string> vars) {
|
std::map<grpc::string, grpc::string> vars) {
|
||||||
vars["Method"] = exportName(method->name());
|
vars["Method"] = exportName(method->name());
|
||||||
vars["Request"] = method->get_input_type_name();
|
vars["Request"] = method->get_input_type_name();
|
||||||
vars["Response"] = (vars["CustomMethodIO"] == "") ? method->get_output_type_name() : vars["CustomMethodIO"];
|
vars["Response"] = (vars["CustomMethodIO"] == "")
|
||||||
if (method->NoStreaming()) {
|
? method->get_output_type_name()
|
||||||
printer->Print(vars, "$Method$($context$.Context, *$Request$) (*$Response$, error)$Ending$");
|
: vars["CustomMethodIO"];
|
||||||
} else if (ServerOnlyStreaming(method)) {
|
if (method->NoStreaming()) {
|
||||||
printer->Print(vars, "$Method$(*$Request$, $Service$_$Method$Server) error$Ending$");
|
printer->Print(
|
||||||
} else {
|
vars,
|
||||||
printer->Print(vars, "$Method$($Service$_$Method$Server) error$Ending$");
|
"$Method$($context$.Context, *$Request$) (*$Response$, error)$Ending$");
|
||||||
}
|
} else if (ServerOnlyStreaming(method)) {
|
||||||
|
printer->Print(
|
||||||
|
vars, "$Method$(*$Request$, $Service$_$Method$Server) error$Ending$");
|
||||||
|
} else {
|
||||||
|
printer->Print(vars, "$Method$($Service$_$Method$Server) error$Ending$");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void GenerateServerMethod(const grpc_generator::Method *method, grpc_generator::Printer *printer,
|
static void GenerateServerMethod(const grpc_generator::Method *method,
|
||||||
|
grpc_generator::Printer *printer,
|
||||||
std::map<grpc::string, grpc::string> vars) {
|
std::map<grpc::string, grpc::string> vars) {
|
||||||
vars["Method"] = exportName(method->name());
|
vars["Method"] = exportName(method->name());
|
||||||
vars["Request"] = method->get_input_type_name();
|
vars["Request"] = method->get_input_type_name();
|
||||||
vars["Response"] = (vars["CustomMethodIO"] == "") ? method->get_output_type_name() : vars["CustomMethodIO"];
|
vars["Response"] = (vars["CustomMethodIO"] == "")
|
||||||
vars["FullMethodName"] = "/" + vars["ServicePrefix"] + vars["Service"] + "/" + vars["Method"];
|
? method->get_output_type_name()
|
||||||
vars["Handler"] = "_" + vars["Service"] + "_" + vars["Method"] + "_Handler";
|
: vars["CustomMethodIO"];
|
||||||
if (method->NoStreaming()) {
|
vars["FullMethodName"] =
|
||||||
printer->Print(vars, "func $Handler$(srv interface{}, ctx $context$.Context,\n\tdec func(interface{}) error, interceptor $grpc$.UnaryServerInterceptor) (interface{}, error) {\n");
|
"/" + vars["ServicePrefix"] + vars["Service"] + "/" + vars["Method"];
|
||||||
printer->Indent();
|
vars["Handler"] = "_" + vars["Service"] + "_" + vars["Method"] + "_Handler";
|
||||||
printer->Print(vars, "in := new($Request$)\n");
|
if (method->NoStreaming()) {
|
||||||
|
printer->Print(
|
||||||
|
vars,
|
||||||
|
"func $Handler$(srv interface{}, ctx $context$.Context,\n\tdec "
|
||||||
|
"func(interface{}) error, interceptor $grpc$.UnaryServerInterceptor) "
|
||||||
|
"(interface{}, error) {\n");
|
||||||
|
printer->Indent();
|
||||||
|
printer->Print(vars, "in := new($Request$)\n");
|
||||||
vars["Error_Check"] = "err := dec(in); err != nil";
|
vars["Error_Check"] = "err := dec(in); err != nil";
|
||||||
GenerateError(printer, vars);
|
GenerateError(printer, vars);
|
||||||
printer->Print("if interceptor == nil {\n");
|
printer->Print("if interceptor == nil {\n");
|
||||||
@@ -133,258 +113,281 @@ void GenerateServerMethod(const grpc_generator::Method *method, grpc_generator::
|
|||||||
printer->Print(vars, "return srv.($Service$Server).$Method$(ctx, in)\n");
|
printer->Print(vars, "return srv.($Service$Server).$Method$(ctx, in)\n");
|
||||||
printer->Outdent();
|
printer->Outdent();
|
||||||
printer->Print("}\n");
|
printer->Print("}\n");
|
||||||
printer->Print(vars, "info := &$grpc$.UnaryServerInfo{\n");
|
printer->Print(vars, "info := &$grpc$.UnaryServerInfo{\n");
|
||||||
printer->Indent();
|
printer->Indent();
|
||||||
printer->Print("Server: srv,\n");
|
printer->Print("Server: srv,\n");
|
||||||
printer->Print(vars, "FullMethod: \"$FullMethodName$\",\n");
|
printer->Print(vars, "FullMethod: \"$FullMethodName$\",\n");
|
||||||
printer->Outdent();
|
printer->Outdent();
|
||||||
printer->Print("}\n");
|
printer->Print("}\n");
|
||||||
printer->Outdent();
|
printer->Outdent();
|
||||||
printer->Print("\n");
|
printer->Print("\n");
|
||||||
printer->Indent();
|
printer->Indent();
|
||||||
printer->Print(vars, "handler := func(ctx $context$.Context, req interface{}) (interface{}, error) {\n");
|
printer->Print(vars,
|
||||||
printer->Indent();
|
"handler := func(ctx $context$.Context, req interface{}) "
|
||||||
printer->Print(vars, "return srv.($Service$Server).$Method$(ctx, req.(*$Request$))\n");
|
"(interface{}, error) {\n");
|
||||||
printer->Outdent();
|
printer->Indent();
|
||||||
printer->Print("}\n");
|
printer->Print(
|
||||||
printer->Print("return interceptor(ctx, in, info, handler)\n");
|
vars, "return srv.($Service$Server).$Method$(ctx, req.(*$Request$))\n");
|
||||||
printer->Outdent();
|
printer->Outdent();
|
||||||
printer->Print("}\n");
|
printer->Print("}\n");
|
||||||
return;
|
printer->Print("return interceptor(ctx, in, info, handler)\n");
|
||||||
}
|
printer->Outdent();
|
||||||
vars["StreamType"] = vars["ServiceUnexported"] + vars["Method"] + "Server";
|
printer->Print("}\n");
|
||||||
printer->Print(vars, "func $Handler$(srv interface{}, stream $grpc$.ServerStream) error {\n");
|
return;
|
||||||
printer->Indent();
|
}
|
||||||
if (ServerOnlyStreaming(method)) {
|
vars["StreamType"] = vars["ServiceUnexported"] + vars["Method"] + "Server";
|
||||||
printer->Print(vars, "m := new($Request$)\n");
|
printer->Print(
|
||||||
|
vars,
|
||||||
|
"func $Handler$(srv interface{}, stream $grpc$.ServerStream) error {\n");
|
||||||
|
printer->Indent();
|
||||||
|
if (ServerOnlyStreaming(method)) {
|
||||||
|
printer->Print(vars, "m := new($Request$)\n");
|
||||||
vars["Error_Check"] = "err := stream.RecvMsg(m); err != nil";
|
vars["Error_Check"] = "err := stream.RecvMsg(m); err != nil";
|
||||||
GenerateError(printer, vars, false);
|
GenerateError(printer, vars, false);
|
||||||
printer->Print(vars, "return srv.($Service$Server).$Method$(m, &$StreamType${stream})\n");
|
printer->Print(
|
||||||
} else {
|
vars,
|
||||||
printer->Print(vars, "return srv.($Service$Server).$Method$(&$StreamType${stream})\n");
|
"return srv.($Service$Server).$Method$(m, &$StreamType${stream})\n");
|
||||||
}
|
} else {
|
||||||
printer->Outdent();
|
printer->Print(
|
||||||
printer->Print("}\n\n");
|
vars, "return srv.($Service$Server).$Method$(&$StreamType${stream})\n");
|
||||||
|
}
|
||||||
|
printer->Outdent();
|
||||||
|
printer->Print("}\n\n");
|
||||||
|
|
||||||
bool genSend = method->BidiStreaming() || ServerOnlyStreaming(method);
|
bool genSend = method->BidiStreaming() || ServerOnlyStreaming(method);
|
||||||
bool genRecv = method->BidiStreaming() || ClientOnlyStreaming(method);
|
bool genRecv = method->BidiStreaming() || ClientOnlyStreaming(method);
|
||||||
bool genSendAndClose = ClientOnlyStreaming(method);
|
bool genSendAndClose = ClientOnlyStreaming(method);
|
||||||
|
|
||||||
printer->Print(vars, "type $Service$_$Method$Server interface {\n");
|
printer->Print(vars, "type $Service$_$Method$Server interface {\n");
|
||||||
printer->Indent();
|
printer->Indent();
|
||||||
if (genSend) {
|
if (genSend) { printer->Print(vars, "Send(*$Response$) error\n"); }
|
||||||
printer->Print(vars, "Send(*$Response$) error\n");
|
if (genRecv) { printer->Print(vars, "Recv() (*$Request$, error)\n"); }
|
||||||
}
|
if (genSendAndClose) {
|
||||||
if (genRecv) {
|
printer->Print(vars, "SendAndClose(*$Response$) error\n");
|
||||||
printer->Print(vars, "Recv() (*$Request$, error)\n");
|
}
|
||||||
}
|
printer->Print(vars, "$grpc$.ServerStream\n");
|
||||||
if (genSendAndClose) {
|
printer->Outdent();
|
||||||
printer->Print(vars, "SendAndClose(*$Response$) error\n");
|
printer->Print("}\n\n");
|
||||||
}
|
|
||||||
printer->Print(vars, "$grpc$.ServerStream\n");
|
|
||||||
printer->Outdent();
|
|
||||||
printer->Print("}\n\n");
|
|
||||||
|
|
||||||
printer->Print(vars, "type $StreamType$ struct {\n");
|
printer->Print(vars, "type $StreamType$ struct {\n");
|
||||||
printer->Indent();
|
printer->Indent();
|
||||||
printer->Print(vars, "$grpc$.ServerStream\n");
|
printer->Print(vars, "$grpc$.ServerStream\n");
|
||||||
printer->Outdent();
|
printer->Outdent();
|
||||||
printer->Print("}\n\n");
|
printer->Print("}\n\n");
|
||||||
|
|
||||||
if (genSend) {
|
if (genSend) {
|
||||||
printer->Print(vars, "func (x *$StreamType$) Send(m *$Response$) error {\n");
|
printer->Print(vars,
|
||||||
printer->Indent();
|
"func (x *$StreamType$) Send(m *$Response$) error {\n");
|
||||||
printer->Print("return x.ServerStream.SendMsg(m)\n");
|
printer->Indent();
|
||||||
printer->Outdent();
|
printer->Print("return x.ServerStream.SendMsg(m)\n");
|
||||||
printer->Print("}\n\n");
|
printer->Outdent();
|
||||||
}
|
printer->Print("}\n\n");
|
||||||
if (genRecv) {
|
}
|
||||||
printer->Print(vars, "func (x *$StreamType$) Recv() (*$Request$, error) {\n");
|
if (genRecv) {
|
||||||
printer->Indent();
|
printer->Print(vars,
|
||||||
printer->Print(vars, "m := new($Request$)\n");
|
"func (x *$StreamType$) Recv() (*$Request$, error) {\n");
|
||||||
|
printer->Indent();
|
||||||
|
printer->Print(vars, "m := new($Request$)\n");
|
||||||
vars["Error_Check"] = "err := x.ServerStream.RecvMsg(m); err != nil";
|
vars["Error_Check"] = "err := x.ServerStream.RecvMsg(m); err != nil";
|
||||||
GenerateError(printer, vars);
|
GenerateError(printer, vars);
|
||||||
printer->Print("return m, nil\n");
|
printer->Print("return m, nil\n");
|
||||||
printer->Outdent();
|
printer->Outdent();
|
||||||
printer->Print("}\n\n");
|
printer->Print("}\n\n");
|
||||||
}
|
}
|
||||||
if (genSendAndClose) {
|
if (genSendAndClose) {
|
||||||
printer->Print(vars, "func (x *$StreamType$) SendAndClose(m *$Response$) error {\n");
|
printer->Print(
|
||||||
printer->Indent();
|
vars, "func (x *$StreamType$) SendAndClose(m *$Response$) error {\n");
|
||||||
printer->Print("return x.ServerStream.SendMsg(m)\n");
|
printer->Indent();
|
||||||
printer->Outdent();
|
printer->Print("return x.ServerStream.SendMsg(m)\n");
|
||||||
printer->Print("}\n\n");
|
printer->Outdent();
|
||||||
}
|
printer->Print("}\n\n");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Generates Client method signature source
|
// Generates Client method signature source
|
||||||
void GenerateClientMethodSignature(const grpc_generator::Method *method, grpc_generator::Printer *printer,
|
static void GenerateClientMethodSignature(const grpc_generator::Method *method,
|
||||||
|
grpc_generator::Printer *printer,
|
||||||
std::map<grpc::string, grpc::string> vars) {
|
std::map<grpc::string, grpc::string> vars) {
|
||||||
vars["Method"] = exportName(method->name());
|
vars["Method"] = exportName(method->name());
|
||||||
vars["Request"] = ", in *" + ((vars["CustomMethodIO"] == "") ? method->get_input_type_name() : vars["CustomMethodIO"]);
|
vars["Request"] =
|
||||||
if (ClientOnlyStreaming(method) || method->BidiStreaming()) {
|
", in *" + ((vars["CustomMethodIO"] == "") ? method->get_input_type_name()
|
||||||
vars["Request"] = "";
|
: vars["CustomMethodIO"]);
|
||||||
}
|
if (ClientOnlyStreaming(method) || method->BidiStreaming()) {
|
||||||
vars["Response"] = "*" + method->get_output_type_name();
|
vars["Request"] = "";
|
||||||
if (ClientOnlyStreaming(method) || method->BidiStreaming() || ServerOnlyStreaming(method)) {
|
}
|
||||||
vars["Response"] = vars["Service"] + "_" + vars["Method"] + "Client" ;
|
vars["Response"] = "*" + method->get_output_type_name();
|
||||||
}
|
if (ClientOnlyStreaming(method) || method->BidiStreaming() ||
|
||||||
printer->Print(vars, "$Method$(ctx $context$.Context$Request$,\n\topts ...$grpc$.CallOption) ($Response$, error)$Ending$");
|
ServerOnlyStreaming(method)) {
|
||||||
|
vars["Response"] = vars["Service"] + "_" + vars["Method"] + "Client";
|
||||||
|
}
|
||||||
|
printer->Print(vars,
|
||||||
|
"$Method$(ctx $context$.Context$Request$,\n\topts "
|
||||||
|
"...$grpc$.CallOption) ($Response$, error)$Ending$");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Generates Client method source
|
// Generates Client method source
|
||||||
void GenerateClientMethod(const grpc_generator::Method *method, grpc_generator::Printer *printer,
|
static void GenerateClientMethod(const grpc_generator::Method *method,
|
||||||
|
grpc_generator::Printer *printer,
|
||||||
std::map<grpc::string, grpc::string> vars) {
|
std::map<grpc::string, grpc::string> vars) {
|
||||||
printer->Print(vars, "func (c *$ServiceUnexported$Client) ");
|
printer->Print(vars, "func (c *$ServiceUnexported$Client) ");
|
||||||
vars["Ending"] = " {\n";
|
vars["Ending"] = " {\n";
|
||||||
GenerateClientMethodSignature(method, printer, vars);
|
GenerateClientMethodSignature(method, printer, vars);
|
||||||
printer->Indent();
|
printer->Indent();
|
||||||
vars["Method"] = exportName(method->name());
|
vars["Method"] = exportName(method->name());
|
||||||
vars["Request"] = (vars["CustomMethodIO"] == "") ? method->get_input_type_name() : vars["CustomMethodIO"];
|
vars["Request"] = (vars["CustomMethodIO"] == "")
|
||||||
vars["Response"] = method->get_output_type_name();
|
? method->get_input_type_name()
|
||||||
vars["FullMethodName"] = "/" + vars["ServicePrefix"] + vars["Service"] + "/" + vars["Method"];
|
: vars["CustomMethodIO"];
|
||||||
if (method->NoStreaming()) {
|
vars["Response"] = method->get_output_type_name();
|
||||||
printer->Print(vars, "out := new($Response$)\n");
|
vars["FullMethodName"] =
|
||||||
printer->Print(vars, "err := c.cc.Invoke(ctx, \"$FullMethodName$\", in, out, opts...)\n");
|
"/" + vars["ServicePrefix"] + vars["Service"] + "/" + vars["Method"];
|
||||||
|
if (method->NoStreaming()) {
|
||||||
|
printer->Print(vars, "out := new($Response$)\n");
|
||||||
|
printer->Print(
|
||||||
|
vars,
|
||||||
|
"err := c.cc.Invoke(ctx, \"$FullMethodName$\", in, out, opts...)\n");
|
||||||
vars["Error_Check"] = "err != nil";
|
vars["Error_Check"] = "err != nil";
|
||||||
GenerateError(printer, vars);
|
GenerateError(printer, vars);
|
||||||
printer->Print("return out, nil\n");
|
printer->Print("return out, nil\n");
|
||||||
printer->Outdent();
|
printer->Outdent();
|
||||||
printer->Print("}\n\n");
|
printer->Print("}\n\n");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
vars["StreamType"] = vars["ServiceUnexported"] + vars["Method"] + "Client";
|
vars["StreamType"] = vars["ServiceUnexported"] + vars["Method"] + "Client";
|
||||||
printer->Print(vars, "stream, err := c.cc.NewStream(ctx, &$MethodDesc$, \"$FullMethodName$\", opts...)\n");
|
printer->Print(vars,
|
||||||
|
"stream, err := c.cc.NewStream(ctx, &$MethodDesc$, "
|
||||||
|
"\"$FullMethodName$\", opts...)\n");
|
||||||
vars["Error_Check"] = "err != nil";
|
vars["Error_Check"] = "err != nil";
|
||||||
GenerateError(printer, vars);
|
GenerateError(printer, vars);
|
||||||
|
|
||||||
printer->Print(vars, "x := &$StreamType${stream}\n");
|
printer->Print(vars, "x := &$StreamType${stream}\n");
|
||||||
if (ServerOnlyStreaming(method)) {
|
if (ServerOnlyStreaming(method)) {
|
||||||
vars["Error_Check"] = "err := x.ClientStream.SendMsg(in); err != nil";
|
vars["Error_Check"] = "err := x.ClientStream.SendMsg(in); err != nil";
|
||||||
GenerateError(printer, vars);
|
GenerateError(printer, vars);
|
||||||
vars["Error_Check"] = "err := x.ClientStream.CloseSend(); err != nil";
|
vars["Error_Check"] = "err := x.ClientStream.CloseSend(); err != nil";
|
||||||
GenerateError(printer, vars);
|
GenerateError(printer, vars);
|
||||||
}
|
}
|
||||||
printer->Print("return x, nil\n");
|
printer->Print("return x, nil\n");
|
||||||
printer->Outdent();
|
printer->Outdent();
|
||||||
printer->Print("}\n\n");
|
printer->Print("}\n\n");
|
||||||
|
|
||||||
bool genSend = method->BidiStreaming() || ClientOnlyStreaming(method);
|
bool genSend = method->BidiStreaming() || ClientOnlyStreaming(method);
|
||||||
bool genRecv = method->BidiStreaming() || ServerOnlyStreaming(method);
|
bool genRecv = method->BidiStreaming() || ServerOnlyStreaming(method);
|
||||||
bool genCloseAndRecv = ClientOnlyStreaming(method);
|
bool genCloseAndRecv = ClientOnlyStreaming(method);
|
||||||
|
|
||||||
//Stream interface
|
// Stream interface
|
||||||
printer->Print(vars, "type $Service$_$Method$Client interface {\n");
|
printer->Print(vars, "type $Service$_$Method$Client interface {\n");
|
||||||
printer->Indent();
|
printer->Indent();
|
||||||
if (genSend) {
|
if (genSend) { printer->Print(vars, "Send(*$Request$) error\n"); }
|
||||||
printer->Print(vars, "Send(*$Request$) error\n");
|
if (genRecv) { printer->Print(vars, "Recv() (*$Response$, error)\n"); }
|
||||||
}
|
if (genCloseAndRecv) {
|
||||||
if (genRecv) {
|
printer->Print(vars, "CloseAndRecv() (*$Response$, error)\n");
|
||||||
printer->Print(vars, "Recv() (*$Response$, error)\n");
|
}
|
||||||
}
|
printer->Print(vars, "$grpc$.ClientStream\n");
|
||||||
if (genCloseAndRecv) {
|
printer->Outdent();
|
||||||
printer->Print(vars, "CloseAndRecv() (*$Response$, error)\n");
|
printer->Print("}\n\n");
|
||||||
}
|
|
||||||
printer->Print(vars, "$grpc$.ClientStream\n");
|
|
||||||
printer->Outdent();
|
|
||||||
printer->Print("}\n\n");
|
|
||||||
|
|
||||||
//Stream Client
|
// Stream Client
|
||||||
printer->Print(vars, "type $StreamType$ struct {\n");
|
printer->Print(vars, "type $StreamType$ struct {\n");
|
||||||
printer->Indent();
|
printer->Indent();
|
||||||
printer->Print(vars, "$grpc$.ClientStream\n");
|
printer->Print(vars, "$grpc$.ClientStream\n");
|
||||||
printer->Outdent();
|
printer->Outdent();
|
||||||
printer->Print("}\n\n");
|
printer->Print("}\n\n");
|
||||||
|
|
||||||
if (genSend) {
|
if (genSend) {
|
||||||
printer->Print(vars, "func (x *$StreamType$) Send(m *$Request$) error {\n");
|
printer->Print(vars, "func (x *$StreamType$) Send(m *$Request$) error {\n");
|
||||||
printer->Indent();
|
printer->Indent();
|
||||||
printer->Print("return x.ClientStream.SendMsg(m)\n");
|
printer->Print("return x.ClientStream.SendMsg(m)\n");
|
||||||
printer->Outdent();
|
printer->Outdent();
|
||||||
printer->Print("}\n\n");
|
printer->Print("}\n\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (genRecv) {
|
if (genRecv) {
|
||||||
printer->Print(vars, "func (x *$StreamType$) Recv() (*$Response$, error) {\n");
|
printer->Print(vars,
|
||||||
printer->Indent();
|
"func (x *$StreamType$) Recv() (*$Response$, error) {\n");
|
||||||
printer->Print(vars, "m := new($Response$)\n");
|
printer->Indent();
|
||||||
|
printer->Print(vars, "m := new($Response$)\n");
|
||||||
vars["Error_Check"] = "err := x.ClientStream.RecvMsg(m); err != nil";
|
vars["Error_Check"] = "err := x.ClientStream.RecvMsg(m); err != nil";
|
||||||
GenerateError(printer, vars);
|
GenerateError(printer, vars);
|
||||||
printer->Print("return m, nil\n");
|
printer->Print("return m, nil\n");
|
||||||
printer->Outdent();
|
printer->Outdent();
|
||||||
printer->Print("}\n\n");
|
printer->Print("}\n\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (genCloseAndRecv) {
|
if (genCloseAndRecv) {
|
||||||
printer->Print(vars, "func (x *$StreamType$) CloseAndRecv() (*$Response$, error) {\n");
|
printer->Print(
|
||||||
printer->Indent();
|
vars, "func (x *$StreamType$) CloseAndRecv() (*$Response$, error) {\n");
|
||||||
|
printer->Indent();
|
||||||
vars["Error_Check"] = "err := x.ClientStream.CloseSend(); err != nil";
|
vars["Error_Check"] = "err := x.ClientStream.CloseSend(); err != nil";
|
||||||
GenerateError(printer, vars);
|
GenerateError(printer, vars);
|
||||||
printer->Print(vars, "m := new($Response$)\n");
|
printer->Print(vars, "m := new($Response$)\n");
|
||||||
vars["Error_Check"] = "err := x.ClientStream.RecvMsg(m); err != nil";
|
vars["Error_Check"] = "err := x.ClientStream.RecvMsg(m); err != nil";
|
||||||
GenerateError(printer, vars);
|
GenerateError(printer, vars);
|
||||||
printer->Print("return m, nil\n");
|
printer->Print("return m, nil\n");
|
||||||
printer->Outdent();
|
printer->Outdent();
|
||||||
printer->Print("}\n\n");
|
printer->Print("}\n\n");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Generates client API for the service
|
// Generates client API for the service
|
||||||
void GenerateService(const grpc_generator::Service *service, grpc_generator::Printer* printer,
|
void GenerateService(const grpc_generator::Service *service,
|
||||||
|
grpc_generator::Printer *printer,
|
||||||
std::map<grpc::string, grpc::string> vars) {
|
std::map<grpc::string, grpc::string> vars) {
|
||||||
vars["Service"] = exportName(service->name());
|
vars["Service"] = exportName(service->name());
|
||||||
// Client Interface
|
// Client Interface
|
||||||
printer->Print(vars, "// Client API for $Service$ service\n");
|
printer->Print(vars, "// Client API for $Service$ service\n");
|
||||||
printer->Print(vars, "type $Service$Client interface {\n");
|
printer->Print(vars, "type $Service$Client interface {\n");
|
||||||
printer->Indent();
|
printer->Indent();
|
||||||
vars["Ending"] = "\n";
|
vars["Ending"] = "\n";
|
||||||
for (int i = 0; i < service->method_count(); i++) {
|
for (int i = 0; i < service->method_count(); i++) {
|
||||||
GenerateClientMethodSignature(service->method(i).get(), printer, vars);
|
GenerateClientMethodSignature(service->method(i).get(), printer, vars);
|
||||||
}
|
}
|
||||||
printer->Outdent();
|
printer->Outdent();
|
||||||
printer->Print("}\n\n");
|
printer->Print("}\n\n");
|
||||||
|
|
||||||
// Client structure
|
// Client structure
|
||||||
vars["ServiceUnexported"] = unexportName(vars["Service"]);
|
vars["ServiceUnexported"] = unexportName(vars["Service"]);
|
||||||
printer->Print(vars, "type $ServiceUnexported$Client struct {\n");
|
printer->Print(vars, "type $ServiceUnexported$Client struct {\n");
|
||||||
printer->Indent();
|
printer->Indent();
|
||||||
printer->Print(vars, "cc $grpc$.ClientConnInterface\n");
|
printer->Print(vars, "cc $grpc$.ClientConnInterface\n");
|
||||||
printer->Outdent();
|
printer->Outdent();
|
||||||
printer->Print("}\n\n");
|
printer->Print("}\n\n");
|
||||||
|
|
||||||
// NewClient
|
// NewClient
|
||||||
printer->Print(vars, "func New$Service$Client(cc $grpc$.ClientConnInterface) $Service$Client {\n");
|
printer->Print(vars,
|
||||||
printer->Indent();
|
"func New$Service$Client(cc $grpc$.ClientConnInterface) "
|
||||||
printer->Print(vars, "return &$ServiceUnexported$Client{cc}");
|
"$Service$Client {\n");
|
||||||
printer->Outdent();
|
printer->Indent();
|
||||||
printer->Print("\n}\n\n");
|
printer->Print(vars, "return &$ServiceUnexported$Client{cc}");
|
||||||
|
printer->Outdent();
|
||||||
|
printer->Print("\n}\n\n");
|
||||||
|
|
||||||
int unary_methods = 0, streaming_methods = 0;
|
int unary_methods = 0, streaming_methods = 0;
|
||||||
vars["ServiceDesc"] = "_" + vars["Service"] + "_serviceDesc";
|
vars["ServiceDesc"] = "_" + vars["Service"] + "_serviceDesc";
|
||||||
for (int i = 0; i < service->method_count(); i++) {
|
for (int i = 0; i < service->method_count(); i++) {
|
||||||
auto method = service->method(i);
|
auto method = service->method(i);
|
||||||
if (method->NoStreaming()) {
|
if (method->NoStreaming()) {
|
||||||
vars["MethodDesc"] = vars["ServiceDesc"] + ".Method[" + as_string(unary_methods) + "]";
|
vars["MethodDesc"] =
|
||||||
unary_methods++;
|
vars["ServiceDesc"] + ".Method[" + as_string(unary_methods) + "]";
|
||||||
} else {
|
unary_methods++;
|
||||||
vars["MethodDesc"] = vars["ServiceDesc"] + ".Streams[" + as_string(streaming_methods) + "]";
|
} else {
|
||||||
streaming_methods++;
|
vars["MethodDesc"] = vars["ServiceDesc"] + ".Streams[" +
|
||||||
}
|
as_string(streaming_methods) + "]";
|
||||||
GenerateClientMethod(method.get(), printer, vars);
|
streaming_methods++;
|
||||||
}
|
}
|
||||||
|
GenerateClientMethod(method.get(), printer, vars);
|
||||||
|
}
|
||||||
|
|
||||||
//Server Interface
|
// Server Interface
|
||||||
printer->Print(vars, "// Server API for $Service$ service\n");
|
printer->Print(vars, "// Server API for $Service$ service\n");
|
||||||
printer->Print(vars, "type $Service$Server interface {\n");
|
printer->Print(vars, "type $Service$Server interface {\n");
|
||||||
printer->Indent();
|
printer->Indent();
|
||||||
vars["Ending"] = "\n";
|
vars["Ending"] = "\n";
|
||||||
for (int i = 0; i < service->method_count(); i++) {
|
for (int i = 0; i < service->method_count(); i++) {
|
||||||
GenerateServerMethodSignature(service->method(i).get(), printer, vars);
|
GenerateServerMethodSignature(service->method(i).get(), printer, vars);
|
||||||
}
|
}
|
||||||
printer->Print(vars, "mustEmbedUnimplemented$Service$Server()\n");
|
printer->Print(vars, "mustEmbedUnimplemented$Service$Server()\n");
|
||||||
printer->Outdent();
|
printer->Outdent();
|
||||||
printer->Print("}\n\n");
|
printer->Print("}\n\n");
|
||||||
|
|
||||||
printer->Print(vars, "type Unimplemented$Service$Server struct {\n");
|
printer->Print(vars, "type Unimplemented$Service$Server struct {\n");
|
||||||
printer->Print("}\n\n");
|
printer->Print("}\n\n");
|
||||||
@@ -397,13 +400,17 @@ void GenerateService(const grpc_generator::Service *service, grpc_generator::Pri
|
|||||||
printer->Print(vars, "func (Unimplemented$Service$Server) ");
|
printer->Print(vars, "func (Unimplemented$Service$Server) ");
|
||||||
GenerateServerMethodSignature(method.get(), printer, vars);
|
GenerateServerMethodSignature(method.get(), printer, vars);
|
||||||
printer->Indent();
|
printer->Indent();
|
||||||
printer->Print(vars, "return $Nil$status.Errorf(codes.Unimplemented, \"method $Method$ not implemented\")\n");
|
printer->Print(vars,
|
||||||
|
"return $Nil$status.Errorf(codes.Unimplemented, \"method "
|
||||||
|
"$Method$ not implemented\")\n");
|
||||||
printer->Outdent();
|
printer->Outdent();
|
||||||
printer->Print("}\n");
|
printer->Print("}\n");
|
||||||
printer->Print("\n");
|
printer->Print("\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
printer->Print(vars, "func (Unimplemented$Service$Server) mustEmbedUnimplemented$Service$Server() {}");
|
printer->Print(vars,
|
||||||
|
"func (Unimplemented$Service$Server) "
|
||||||
|
"mustEmbedUnimplemented$Service$Server() {}");
|
||||||
printer->Print("\n\n");
|
printer->Print("\n\n");
|
||||||
|
|
||||||
printer->Print(vars, "type Unsafe$Service$Server interface {\n");
|
printer->Print(vars, "type Unsafe$Service$Server interface {\n");
|
||||||
@@ -411,91 +418,90 @@ void GenerateService(const grpc_generator::Service *service, grpc_generator::Pri
|
|||||||
printer->Print(vars, "mustEmbedUnimplemented$Service$Server()\n");
|
printer->Print(vars, "mustEmbedUnimplemented$Service$Server()\n");
|
||||||
printer->Outdent();
|
printer->Outdent();
|
||||||
printer->Print("}\n\n");
|
printer->Print("}\n\n");
|
||||||
// Server registration.
|
// Server registration.
|
||||||
printer->Print(vars, "func Register$Service$Server(s $grpc$.ServiceRegistrar, srv $Service$Server) {\n");
|
printer->Print(vars,
|
||||||
printer->Indent();
|
"func Register$Service$Server(s $grpc$.ServiceRegistrar, srv "
|
||||||
printer->Print(vars, "s.RegisterService(&$ServiceDesc$, srv)\n");
|
"$Service$Server) {\n");
|
||||||
printer->Outdent();
|
printer->Indent();
|
||||||
printer->Print("}\n\n");
|
printer->Print(vars, "s.RegisterService(&$ServiceDesc$, srv)\n");
|
||||||
|
printer->Outdent();
|
||||||
|
printer->Print("}\n\n");
|
||||||
|
|
||||||
for (int i = 0; i < service->method_count(); i++) {
|
for (int i = 0; i < service->method_count(); i++) {
|
||||||
GenerateServerMethod(service->method(i).get(), printer, vars);
|
GenerateServerMethod(service->method(i).get(), printer, vars);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
//Service Descriptor
|
|
||||||
printer->Print(vars, "var $ServiceDesc$ = $grpc$.ServiceDesc{\n");
|
|
||||||
printer->Indent();
|
|
||||||
printer->Print(vars, "ServiceName: \"$ServicePrefix$$Service$\",\n");
|
|
||||||
printer->Print(vars, "HandlerType: (*$Service$Server)(nil),\n");
|
|
||||||
printer->Print(vars, "Methods: []$grpc$.MethodDesc{\n");
|
|
||||||
printer->Indent();
|
|
||||||
for (int i = 0; i < service->method_count(); i++) {
|
|
||||||
auto method = service->method(i);
|
|
||||||
vars["Method"] = exportName(method->name());
|
|
||||||
vars["Handler"] = "_" + vars["Service"] + "_" + vars["Method"] + "_Handler";
|
|
||||||
if (method->NoStreaming()) {
|
|
||||||
printer->Print("{\n");
|
|
||||||
printer->Indent();
|
|
||||||
printer->Print(vars, "MethodName: \"$Method$\",\n");
|
|
||||||
printer->Print(vars, "Handler: $Handler$,\n");
|
|
||||||
printer->Outdent();
|
|
||||||
printer->Print("},\n");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
printer->Outdent();
|
|
||||||
printer->Print("},\n");
|
|
||||||
printer->Print(vars, "Streams: []$grpc$.StreamDesc{\n");
|
|
||||||
printer->Indent();
|
|
||||||
for (int i = 0; i < service->method_count(); i++) {
|
|
||||||
auto method = service->method(i);
|
|
||||||
vars["Method"] = exportName(method->name());
|
|
||||||
vars["Handler"] = "_" + vars["Service"] + "_" + vars["Method"] + "_Handler";
|
|
||||||
if (!method->NoStreaming()) {
|
|
||||||
printer->Print("{\n");
|
|
||||||
printer->Indent();
|
|
||||||
printer->Print(vars, "StreamName: \"$Method$\",\n");
|
|
||||||
printer->Print(vars, "Handler: $Handler$,\n");
|
|
||||||
if (ClientOnlyStreaming(method.get())) {
|
|
||||||
printer->Print("ClientStreams: true,\n");
|
|
||||||
} else if (ServerOnlyStreaming(method.get())) {
|
|
||||||
printer->Print("ServerStreams: true,\n");
|
|
||||||
} else {
|
|
||||||
printer->Print("ServerStreams: true,\n");
|
|
||||||
printer->Print("ClientStreams: true,\n");
|
|
||||||
}
|
|
||||||
printer->Outdent();
|
|
||||||
printer->Print("},\n");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
printer->Outdent();
|
|
||||||
printer->Print("},\n");
|
|
||||||
printer->Outdent();
|
|
||||||
printer->Print("}\n");
|
|
||||||
|
|
||||||
|
// Service Descriptor
|
||||||
|
printer->Print(vars, "var $ServiceDesc$ = $grpc$.ServiceDesc{\n");
|
||||||
|
printer->Indent();
|
||||||
|
printer->Print(vars, "ServiceName: \"$ServicePrefix$$Service$\",\n");
|
||||||
|
printer->Print(vars, "HandlerType: (*$Service$Server)(nil),\n");
|
||||||
|
printer->Print(vars, "Methods: []$grpc$.MethodDesc{\n");
|
||||||
|
printer->Indent();
|
||||||
|
for (int i = 0; i < service->method_count(); i++) {
|
||||||
|
auto method = service->method(i);
|
||||||
|
vars["Method"] = exportName(method->name());
|
||||||
|
vars["Handler"] = "_" + vars["Service"] + "_" + vars["Method"] + "_Handler";
|
||||||
|
if (method->NoStreaming()) {
|
||||||
|
printer->Print("{\n");
|
||||||
|
printer->Indent();
|
||||||
|
printer->Print(vars, "MethodName: \"$Method$\",\n");
|
||||||
|
printer->Print(vars, "Handler: $Handler$,\n");
|
||||||
|
printer->Outdent();
|
||||||
|
printer->Print("},\n");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
printer->Outdent();
|
||||||
|
printer->Print("},\n");
|
||||||
|
printer->Print(vars, "Streams: []$grpc$.StreamDesc{\n");
|
||||||
|
printer->Indent();
|
||||||
|
for (int i = 0; i < service->method_count(); i++) {
|
||||||
|
auto method = service->method(i);
|
||||||
|
vars["Method"] = exportName(method->name());
|
||||||
|
vars["Handler"] = "_" + vars["Service"] + "_" + vars["Method"] + "_Handler";
|
||||||
|
if (!method->NoStreaming()) {
|
||||||
|
printer->Print("{\n");
|
||||||
|
printer->Indent();
|
||||||
|
printer->Print(vars, "StreamName: \"$Method$\",\n");
|
||||||
|
printer->Print(vars, "Handler: $Handler$,\n");
|
||||||
|
if (ClientOnlyStreaming(method.get())) {
|
||||||
|
printer->Print("ClientStreams: true,\n");
|
||||||
|
} else if (ServerOnlyStreaming(method.get())) {
|
||||||
|
printer->Print("ServerStreams: true,\n");
|
||||||
|
} else {
|
||||||
|
printer->Print("ServerStreams: true,\n");
|
||||||
|
printer->Print("ClientStreams: true,\n");
|
||||||
|
}
|
||||||
|
printer->Outdent();
|
||||||
|
printer->Print("},\n");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
printer->Outdent();
|
||||||
|
printer->Print("},\n");
|
||||||
|
printer->Outdent();
|
||||||
|
printer->Print("}\n");
|
||||||
}
|
}
|
||||||
|
} // namespace
|
||||||
|
|
||||||
// Returns source for the service
|
// Returns source for the service
|
||||||
grpc::string GenerateServiceSource(grpc_generator::File *file,
|
grpc::string GenerateServiceSource(grpc_generator::File *file,
|
||||||
const grpc_generator::Service *service,
|
const grpc_generator::Service *service,
|
||||||
grpc_go_generator::Parameters *parameters) {
|
grpc_go_generator::Parameters *parameters) {
|
||||||
grpc::string out;
|
grpc::string out;
|
||||||
auto p = file->CreatePrinter(&out, '\t');
|
auto p = file->CreatePrinter(&out, '\t');
|
||||||
p->SetIndentationSize(1);
|
p->SetIndentationSize(1);
|
||||||
auto printer = p.get();
|
auto printer = p.get();
|
||||||
std::map<grpc::string, grpc::string> vars;
|
std::map<grpc::string, grpc::string> vars;
|
||||||
vars["Package"] = parameters->package_name;
|
vars["Package"] = parameters->package_name;
|
||||||
vars["ServicePrefix"] = parameters->service_prefix;
|
vars["ServicePrefix"] = parameters->service_prefix;
|
||||||
if (!parameters->service_prefix.empty())
|
if (!parameters->service_prefix.empty()) vars["ServicePrefix"].append(".");
|
||||||
vars["ServicePrefix"].append(".");
|
vars["grpc"] = "grpc";
|
||||||
vars["grpc"] = "grpc";
|
vars["context"] = "context";
|
||||||
vars["context"] = "context";
|
GenerateImports(file, printer, vars);
|
||||||
GenerateImports(file, printer, vars);
|
if (parameters->custom_method_io_type != "") {
|
||||||
if (parameters->custom_method_io_type != "") {
|
vars["CustomMethodIO"] = parameters->custom_method_io_type;
|
||||||
vars["CustomMethodIO"] = parameters->custom_method_io_type;
|
}
|
||||||
}
|
GenerateService(service, printer, vars);
|
||||||
GenerateService(service, printer, vars);
|
return out;
|
||||||
return out;
|
|
||||||
}
|
}
|
||||||
}// Namespace grpc_go_generator
|
} // Namespace grpc_go_generator
|
||||||
|
|||||||
@@ -1,40 +1,8 @@
|
|||||||
/*
|
|
||||||
*
|
|
||||||
* Copyright 2015, Google Inc.
|
|
||||||
* All rights reserved.
|
|
||||||
*
|
|
||||||
* Redistribution and use in source and binary forms, with or without
|
|
||||||
* modification, are permitted provided that the following conditions are
|
|
||||||
* met:
|
|
||||||
*
|
|
||||||
* * Redistributions of source code must retain the above copyright
|
|
||||||
* notice, this list of conditions and the following disclaimer.
|
|
||||||
* * Redistributions in binary form must reproduce the above
|
|
||||||
* copyright notice, this list of conditions and the following disclaimer
|
|
||||||
* in the documentation and/or other materials provided with the
|
|
||||||
* distribution.
|
|
||||||
* * Neither the name of Google Inc. nor the names of its
|
|
||||||
* contributors may be used to endorse or promote products derived from
|
|
||||||
* this software without specific prior written permission.
|
|
||||||
*
|
|
||||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
|
||||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
|
||||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
|
||||||
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
|
||||||
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
|
||||||
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
|
||||||
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
|
||||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
|
||||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
|
||||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
||||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
|
|
||||||
#ifndef GRPC_INTERNAL_COMPILER_GO_GENERATOR_H
|
#ifndef GRPC_INTERNAL_COMPILER_GO_GENERATOR_H
|
||||||
#define GRPC_INTERNAL_COMPILER_GO_GENERATOR_H
|
#define GRPC_INTERNAL_COMPILER_GO_GENERATOR_H
|
||||||
|
|
||||||
//go generator is used to generate GRPC code for serialization system, such as flatbuffers
|
// go generator is used to generate GRPC code for serialization system, such as
|
||||||
|
// flatbuffers
|
||||||
#include <memory>
|
#include <memory>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
@@ -43,14 +11,15 @@
|
|||||||
namespace grpc_go_generator {
|
namespace grpc_go_generator {
|
||||||
|
|
||||||
struct Parameters {
|
struct Parameters {
|
||||||
//Defines the custom parameter types for methods
|
// Defines the custom parameter types for methods
|
||||||
//eg: flatbuffers uses flatbuffers.Builder as input for the client and output for the server
|
// eg: flatbuffers uses flatbuffers.Builder as input for the client and output
|
||||||
|
// for the server
|
||||||
grpc::string custom_method_io_type;
|
grpc::string custom_method_io_type;
|
||||||
|
|
||||||
//Package name for the service
|
// Package name for the service
|
||||||
grpc::string package_name;
|
grpc::string package_name;
|
||||||
|
|
||||||
//Prefix for RPC Calls
|
// Prefix for RPC Calls
|
||||||
grpc::string service_prefix;
|
grpc::string service_prefix;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -59,6 +28,6 @@ grpc::string GenerateServiceSource(grpc_generator::File *file,
|
|||||||
const grpc_generator::Service *service,
|
const grpc_generator::Service *service,
|
||||||
grpc_go_generator::Parameters *parameters);
|
grpc_go_generator::Parameters *parameters);
|
||||||
|
|
||||||
}
|
} // namespace grpc_go_generator
|
||||||
|
|
||||||
#endif // GRPC_INTERNAL_COMPILER_GO_GENERATOR_H
|
#endif // GRPC_INTERNAL_COMPILER_GO_GENERATOR_H
|
||||||
|
|||||||
@@ -23,21 +23,18 @@
|
|||||||
#include <utility>
|
#include <utility>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
// just to get flatbuffer_version_string()
|
#include "flatbuffers/util.h"
|
||||||
#include <flatbuffers/flatbuffers.h>
|
|
||||||
#include <flatbuffers/util.h>
|
|
||||||
#define to_string flatbuffers::NumToString
|
#define to_string flatbuffers::NumToString
|
||||||
|
|
||||||
// Stringify helpers used solely to cast GRPC_VERSION
|
// Stringify helpers used solely to cast GRPC_VERSION
|
||||||
#ifndef STR
|
#ifndef STR
|
||||||
#define STR(s) #s
|
# define STR(s) # s
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#ifndef XSTR
|
#ifndef XSTR
|
||||||
#define XSTR(s) STR(s)
|
# define XSTR(s) STR(s)
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
|
||||||
typedef grpc_generator::Printer Printer;
|
typedef grpc_generator::Printer Printer;
|
||||||
typedef std::map<grpc::string, grpc::string> VARS;
|
typedef std::map<grpc::string, grpc::string> VARS;
|
||||||
typedef grpc_generator::Service ServiceDescriptor;
|
typedef grpc_generator::Service ServiceDescriptor;
|
||||||
@@ -47,13 +44,13 @@ typedef grpc_generator::Method MethodDescriptor;
|
|||||||
|
|
||||||
namespace grpc_java_generator {
|
namespace grpc_java_generator {
|
||||||
typedef std::string string;
|
typedef std::string string;
|
||||||
|
namespace {
|
||||||
// Generates imports for the service
|
// Generates imports for the service
|
||||||
void GenerateImports(grpc_generator::File* file,
|
static void GenerateImports(grpc_generator::File *file,
|
||||||
grpc_generator::Printer* printer, VARS& vars) {
|
grpc_generator::Printer *printer, VARS &vars) {
|
||||||
vars["filename"] = file->filename();
|
vars["filename"] = file->filename();
|
||||||
printer->Print(
|
printer->Print(vars,
|
||||||
vars,
|
"//Generated by flatc compiler (version $flatc_version$)\n");
|
||||||
"//Generated by flatc compiler (version $flatc_version$)\n");
|
|
||||||
printer->Print("//If you make any local changes, they will be lost\n");
|
printer->Print("//If you make any local changes, they will be lost\n");
|
||||||
printer->Print(vars, "//source: $filename$.fbs\n\n");
|
printer->Print(vars, "//source: $filename$.fbs\n\n");
|
||||||
printer->Print(vars, "package $Package$;\n\n");
|
printer->Print(vars, "package $Package$;\n\n");
|
||||||
@@ -67,7 +64,7 @@ void GenerateImports(grpc_generator::File* file,
|
|||||||
// Adjust a method name prefix identifier to follow the JavaBean spec:
|
// Adjust a method name prefix identifier to follow the JavaBean spec:
|
||||||
// - decapitalize the first letter
|
// - decapitalize the first letter
|
||||||
// - remove embedded underscores & capitalize the following letter
|
// - remove embedded underscores & capitalize the following letter
|
||||||
static string MixedLower(const string& word) {
|
static string MixedLower(const string &word) {
|
||||||
string w;
|
string w;
|
||||||
w += static_cast<string::value_type>(tolower(word[0]));
|
w += static_cast<string::value_type>(tolower(word[0]));
|
||||||
bool after_underscore = false;
|
bool after_underscore = false;
|
||||||
@@ -87,7 +84,7 @@ static string MixedLower(const string& word) {
|
|||||||
// - An underscore is inserted where a lower case letter is followed by an
|
// - An underscore is inserted where a lower case letter is followed by an
|
||||||
// upper case letter.
|
// upper case letter.
|
||||||
// - All letters are converted to upper case
|
// - All letters are converted to upper case
|
||||||
static string ToAllUpperCase(const string& word) {
|
static string ToAllUpperCase(const string &word) {
|
||||||
string w;
|
string w;
|
||||||
for (size_t i = 0; i < word.length(); ++i) {
|
for (size_t i = 0; i < word.length(); ++i) {
|
||||||
w += static_cast<string::value_type>(toupper(word[i]));
|
w += static_cast<string::value_type>(toupper(word[i]));
|
||||||
@@ -98,47 +95,47 @@ static string ToAllUpperCase(const string& word) {
|
|||||||
return w;
|
return w;
|
||||||
}
|
}
|
||||||
|
|
||||||
static inline string LowerMethodName(const MethodDescriptor* method) {
|
static inline string LowerMethodName(const MethodDescriptor *method) {
|
||||||
return MixedLower(method->name());
|
return MixedLower(method->name());
|
||||||
}
|
}
|
||||||
|
|
||||||
static inline string MethodPropertiesFieldName(const MethodDescriptor* method) {
|
static inline string MethodPropertiesFieldName(const MethodDescriptor *method) {
|
||||||
return "METHOD_" + ToAllUpperCase(method->name());
|
return "METHOD_" + ToAllUpperCase(method->name());
|
||||||
}
|
}
|
||||||
|
|
||||||
static inline string MethodPropertiesGetterName(
|
static inline string MethodPropertiesGetterName(
|
||||||
const MethodDescriptor* method) {
|
const MethodDescriptor *method) {
|
||||||
return MixedLower("get_" + method->name() + "_method");
|
return MixedLower("get_" + method->name() + "_method");
|
||||||
}
|
}
|
||||||
|
|
||||||
static inline string MethodIdFieldName(const MethodDescriptor* method) {
|
static inline string MethodIdFieldName(const MethodDescriptor *method) {
|
||||||
return "METHODID_" + ToAllUpperCase(method->name());
|
return "METHODID_" + ToAllUpperCase(method->name());
|
||||||
}
|
}
|
||||||
|
|
||||||
static inline string JavaClassName(VARS& vars, const string& name) {
|
static inline string JavaClassName(VARS &vars, const string &name) {
|
||||||
// string name = google::protobuf::compiler::java::ClassName(desc);
|
// string name = google::protobuf::compiler::java::ClassName(desc);
|
||||||
return vars["Package"] + name;
|
return vars["Package"] + name;
|
||||||
}
|
}
|
||||||
|
|
||||||
static inline string ServiceClassName(const string& service_name) {
|
static inline string ServiceClassName(const string &service_name) {
|
||||||
return service_name + "Grpc";
|
return service_name + "Grpc";
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO(nmittler): Remove once protobuf includes javadoc methods in
|
// TODO(nmittler): Remove once protobuf includes javadoc methods in
|
||||||
// distribution.
|
// distribution.
|
||||||
template <typename ITR>
|
template<typename ITR>
|
||||||
static void GrpcSplitStringToIteratorUsing(const string& full,
|
static void GrpcSplitStringToIteratorUsing(const string &full,
|
||||||
const char* delim, ITR& result) {
|
const char *delim, ITR &result) {
|
||||||
// Optimize the common case where delim is a single character.
|
// Optimize the common case where delim is a single character.
|
||||||
if (delim[0] != '\0' && delim[1] == '\0') {
|
if (delim[0] != '\0' && delim[1] == '\0') {
|
||||||
char c = delim[0];
|
char c = delim[0];
|
||||||
const char* p = full.data();
|
const char *p = full.data();
|
||||||
const char* end = p + full.size();
|
const char *end = p + full.size();
|
||||||
while (p != end) {
|
while (p != end) {
|
||||||
if (*p == c) {
|
if (*p == c) {
|
||||||
++p;
|
++p;
|
||||||
} else {
|
} else {
|
||||||
const char* start = p;
|
const char *start = p;
|
||||||
while (++p != end && *p != c)
|
while (++p != end && *p != c)
|
||||||
;
|
;
|
||||||
*result++ = string(start, p - start);
|
*result++ = string(start, p - start);
|
||||||
@@ -160,13 +157,13 @@ static void GrpcSplitStringToIteratorUsing(const string& full,
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
static void GrpcSplitStringUsing(const string& full, const char* delim,
|
static void GrpcSplitStringUsing(const string &full, const char *delim,
|
||||||
std::vector<string>* result) {
|
std::vector<string> *result) {
|
||||||
std::back_insert_iterator<std::vector<string>> it(*result);
|
std::back_insert_iterator<std::vector<string>> it(*result);
|
||||||
GrpcSplitStringToIteratorUsing(full, delim, it);
|
GrpcSplitStringToIteratorUsing(full, delim, it);
|
||||||
}
|
}
|
||||||
|
|
||||||
static std::vector<string> GrpcSplit(const string& full, const char* delim) {
|
static std::vector<string> GrpcSplit(const string &full, const char *delim) {
|
||||||
std::vector<string> result;
|
std::vector<string> result;
|
||||||
GrpcSplitStringUsing(full, delim, &result);
|
GrpcSplitStringUsing(full, delim, &result);
|
||||||
return result;
|
return result;
|
||||||
@@ -174,7 +171,7 @@ static std::vector<string> GrpcSplit(const string& full, const char* delim) {
|
|||||||
|
|
||||||
// TODO(nmittler): Remove once protobuf includes javadoc methods in
|
// TODO(nmittler): Remove once protobuf includes javadoc methods in
|
||||||
// distribution.
|
// distribution.
|
||||||
static string GrpcEscapeJavadoc(const string& input) {
|
static string GrpcEscapeJavadoc(const string &input) {
|
||||||
string result;
|
string result;
|
||||||
result.reserve(input.size() * 2);
|
result.reserve(input.size() * 2);
|
||||||
|
|
||||||
@@ -221,9 +218,7 @@ static string GrpcEscapeJavadoc(const string& input) {
|
|||||||
// Java interprets Unicode escape sequences anywhere!
|
// Java interprets Unicode escape sequences anywhere!
|
||||||
result.append("\");
|
result.append("\");
|
||||||
break;
|
break;
|
||||||
default:
|
default: result.push_back(c); break;
|
||||||
result.push_back(c);
|
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
prev = c;
|
prev = c;
|
||||||
@@ -232,7 +227,7 @@ static string GrpcEscapeJavadoc(const string& input) {
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
static std::vector<string> GrpcGetDocLines(const string& comments) {
|
static std::vector<string> GrpcGetDocLines(const string &comments) {
|
||||||
if (!comments.empty()) {
|
if (!comments.empty()) {
|
||||||
// TODO(kenton): Ideally we should parse the comment text as Markdown and
|
// TODO(kenton): Ideally we should parse the comment text as Markdown and
|
||||||
// write it back as HTML, but this requires a Markdown parser. For now
|
// write it back as HTML, but this requires a Markdown parser. For now
|
||||||
@@ -243,27 +238,23 @@ static std::vector<string> GrpcGetDocLines(const string& comments) {
|
|||||||
string escapedComments = GrpcEscapeJavadoc(comments);
|
string escapedComments = GrpcEscapeJavadoc(comments);
|
||||||
|
|
||||||
std::vector<string> lines = GrpcSplit(escapedComments, "\n");
|
std::vector<string> lines = GrpcSplit(escapedComments, "\n");
|
||||||
while (!lines.empty() && lines.back().empty()) {
|
while (!lines.empty() && lines.back().empty()) { lines.pop_back(); }
|
||||||
lines.pop_back();
|
|
||||||
}
|
|
||||||
return lines;
|
return lines;
|
||||||
}
|
}
|
||||||
return std::vector<string>();
|
return std::vector<string>();
|
||||||
}
|
}
|
||||||
|
|
||||||
static std::vector<string> GrpcGetDocLinesForDescriptor(
|
static std::vector<string> GrpcGetDocLinesForDescriptor(
|
||||||
const DescriptorType* descriptor) {
|
const DescriptorType *descriptor) {
|
||||||
return descriptor->GetAllComments();
|
return descriptor->GetAllComments();
|
||||||
// return GrpcGetDocLines(descriptor->GetLeadingComments("///"));
|
// return GrpcGetDocLines(descriptor->GetLeadingComments("///"));
|
||||||
}
|
}
|
||||||
|
|
||||||
static void GrpcWriteDocCommentBody(Printer* printer, VARS& vars,
|
static void GrpcWriteDocCommentBody(Printer *printer, VARS &vars,
|
||||||
const std::vector<string>& lines,
|
const std::vector<string> &lines,
|
||||||
bool surroundWithPreTag) {
|
bool surroundWithPreTag) {
|
||||||
if (!lines.empty()) {
|
if (!lines.empty()) {
|
||||||
if (surroundWithPreTag) {
|
if (surroundWithPreTag) { printer->Print(" * <pre>\n"); }
|
||||||
printer->Print(" * <pre>\n");
|
|
||||||
}
|
|
||||||
|
|
||||||
for (size_t i = 0; i < lines.size(); i++) {
|
for (size_t i = 0; i < lines.size(); i++) {
|
||||||
// Most lines should start with a space. Watch out for lines that start
|
// Most lines should start with a space. Watch out for lines that start
|
||||||
@@ -277,73 +268,72 @@ static void GrpcWriteDocCommentBody(Printer* printer, VARS& vars,
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (surroundWithPreTag) {
|
if (surroundWithPreTag) { printer->Print(" * </pre>\n"); }
|
||||||
printer->Print(" * </pre>\n");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
static void GrpcWriteDocComment(Printer* printer, VARS& vars,
|
static void GrpcWriteDocComment(Printer *printer, VARS &vars,
|
||||||
const string& comments) {
|
const string &comments) {
|
||||||
printer->Print("/**\n");
|
printer->Print("/**\n");
|
||||||
std::vector<string> lines = GrpcGetDocLines(comments);
|
std::vector<string> lines = GrpcGetDocLines(comments);
|
||||||
GrpcWriteDocCommentBody(printer, vars, lines, false);
|
GrpcWriteDocCommentBody(printer, vars, lines, false);
|
||||||
printer->Print(" */\n");
|
printer->Print(" */\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
static void GrpcWriteServiceDocComment(Printer* printer, VARS& vars,
|
static void GrpcWriteServiceDocComment(Printer *printer, VARS &vars,
|
||||||
const ServiceDescriptor* service) {
|
const ServiceDescriptor *service) {
|
||||||
printer->Print("/**\n");
|
printer->Print("/**\n");
|
||||||
std::vector<string> lines = GrpcGetDocLinesForDescriptor(service);
|
std::vector<string> lines = GrpcGetDocLinesForDescriptor(service);
|
||||||
GrpcWriteDocCommentBody(printer, vars, lines, true);
|
GrpcWriteDocCommentBody(printer, vars, lines, true);
|
||||||
printer->Print(" */\n");
|
printer->Print(" */\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
void GrpcWriteMethodDocComment(Printer* printer, VARS& vars,
|
static void GrpcWriteMethodDocComment(Printer *printer, VARS &vars,
|
||||||
const MethodDescriptor* method) {
|
const MethodDescriptor *method) {
|
||||||
printer->Print("/**\n");
|
printer->Print("/**\n");
|
||||||
std::vector<string> lines = GrpcGetDocLinesForDescriptor(method);
|
std::vector<string> lines = GrpcGetDocLinesForDescriptor(method);
|
||||||
GrpcWriteDocCommentBody(printer, vars, lines, true);
|
GrpcWriteDocCommentBody(printer, vars, lines, true);
|
||||||
printer->Print(" */\n");
|
printer->Print(" */\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
//outputs static singleton extractor for type stored in "extr_type" and "extr_type_name" vars
|
// outputs static singleton extractor for type stored in "extr_type" and
|
||||||
static void PrintTypeExtractor(Printer* p, VARS& vars) {
|
// "extr_type_name" vars
|
||||||
p->Print(
|
static void PrintTypeExtractor(Printer *p, VARS &vars) {
|
||||||
vars,
|
p->Print(vars,
|
||||||
"private static volatile FlatbuffersUtils.FBExtactor<$extr_type$> "
|
"private static volatile FlatbuffersUtils.FBExtactor<$extr_type$> "
|
||||||
"extractorOf$extr_type_name$;\n"
|
"extractorOf$extr_type_name$;\n"
|
||||||
"private static FlatbuffersUtils.FBExtactor<$extr_type$> "
|
"private static FlatbuffersUtils.FBExtactor<$extr_type$> "
|
||||||
"getExtractorOf$extr_type_name$() {\n"
|
"getExtractorOf$extr_type_name$() {\n"
|
||||||
" if (extractorOf$extr_type_name$ != null) return "
|
" if (extractorOf$extr_type_name$ != null) return "
|
||||||
"extractorOf$extr_type_name$;\n"
|
"extractorOf$extr_type_name$;\n"
|
||||||
" synchronized ($service_class_name$.class) {\n"
|
" synchronized ($service_class_name$.class) {\n"
|
||||||
" if (extractorOf$extr_type_name$ != null) return "
|
" if (extractorOf$extr_type_name$ != null) return "
|
||||||
"extractorOf$extr_type_name$;\n"
|
"extractorOf$extr_type_name$;\n"
|
||||||
" extractorOf$extr_type_name$ = new "
|
" extractorOf$extr_type_name$ = new "
|
||||||
"FlatbuffersUtils.FBExtactor<$extr_type$>() {\n"
|
"FlatbuffersUtils.FBExtactor<$extr_type$>() {\n"
|
||||||
" public $extr_type$ extract (ByteBuffer buffer) {\n"
|
" public $extr_type$ extract (ByteBuffer buffer) {\n"
|
||||||
" return "
|
" return "
|
||||||
"$extr_type$.getRootAs$extr_type_name$(buffer);\n"
|
"$extr_type$.getRootAs$extr_type_name$(buffer);\n"
|
||||||
" }\n"
|
" }\n"
|
||||||
" };\n"
|
" };\n"
|
||||||
" return extractorOf$extr_type_name$;\n"
|
" return extractorOf$extr_type_name$;\n"
|
||||||
" }\n"
|
" }\n"
|
||||||
"}\n\n");
|
"}\n\n");
|
||||||
}
|
}
|
||||||
static void PrintMethodFields(Printer* p, VARS& vars,
|
static void PrintMethodFields(Printer *p, VARS &vars,
|
||||||
const ServiceDescriptor* service) {
|
const ServiceDescriptor *service) {
|
||||||
p->Print("// Static method descriptors that strictly reflect the proto.\n");
|
p->Print("// Static method descriptors that strictly reflect the proto.\n");
|
||||||
vars["service_name"] = service->name();
|
vars["service_name"] = service->name();
|
||||||
|
|
||||||
//set of names of rpc input- and output- types that were already encountered.
|
// set of names of rpc input- and output- types that were already encountered.
|
||||||
//this is needed to avoid duplicating type extractor since it's possible that
|
// this is needed to avoid duplicating type extractor since it's possible that
|
||||||
//the same type is used as an input or output type of more than a single RPC method
|
// the same type is used as an input or output type of more than a single RPC
|
||||||
|
// method
|
||||||
std::set<std::string> encounteredTypes;
|
std::set<std::string> encounteredTypes;
|
||||||
|
|
||||||
for (int i = 0; i < service->method_count(); ++i) {
|
for (int i = 0; i < service->method_count(); ++i) {
|
||||||
auto method = service->method(i);
|
auto method = service->method(i);
|
||||||
vars["arg_in_id"] = to_string(2L * i); //trying to make msvc 10 happy
|
vars["arg_in_id"] = to_string(2L * i); // trying to make msvc 10 happy
|
||||||
vars["arg_out_id"] = to_string(2L * i + 1);
|
vars["arg_out_id"] = to_string(2L * i + 1);
|
||||||
vars["method_name"] = method->name();
|
vars["method_name"] = method->name();
|
||||||
vars["input_type_name"] = method->get_input_type_name();
|
vars["input_type_name"] = method->get_input_type_name();
|
||||||
@@ -353,8 +343,10 @@ static void PrintMethodFields(Printer* p, VARS& vars,
|
|||||||
vars["method_field_name"] = MethodPropertiesFieldName(method.get());
|
vars["method_field_name"] = MethodPropertiesFieldName(method.get());
|
||||||
vars["method_new_field_name"] = MethodPropertiesGetterName(method.get());
|
vars["method_new_field_name"] = MethodPropertiesGetterName(method.get());
|
||||||
vars["method_method_name"] = MethodPropertiesGetterName(method.get());
|
vars["method_method_name"] = MethodPropertiesGetterName(method.get());
|
||||||
bool client_streaming = method->ClientStreaming() || method->BidiStreaming();
|
bool client_streaming =
|
||||||
bool server_streaming = method->ServerStreaming() || method->BidiStreaming();
|
method->ClientStreaming() || method->BidiStreaming();
|
||||||
|
bool server_streaming =
|
||||||
|
method->ServerStreaming() || method->BidiStreaming();
|
||||||
if (client_streaming) {
|
if (client_streaming) {
|
||||||
if (server_streaming) {
|
if (server_streaming) {
|
||||||
vars["method_type"] = "BIDI_STREAMING";
|
vars["method_type"] = "BIDI_STREAMING";
|
||||||
@@ -394,32 +386,32 @@ static void PrintMethodFields(Printer* p, VARS& vars,
|
|||||||
}
|
}
|
||||||
|
|
||||||
p->Print(
|
p->Print(
|
||||||
vars,
|
vars,
|
||||||
"@$ExperimentalApi$(\"https://github.com/grpc/grpc-java/issues/"
|
"@$ExperimentalApi$(\"https://github.com/grpc/grpc-java/issues/"
|
||||||
"1901\")\n"
|
"1901\")\n"
|
||||||
"public static $MethodDescriptor$<$input_type$,\n"
|
"public static $MethodDescriptor$<$input_type$,\n"
|
||||||
" $output_type$> $method_method_name$() {\n"
|
" $output_type$> $method_method_name$() {\n"
|
||||||
" $MethodDescriptor$<$input_type$, $output_type$> "
|
" $MethodDescriptor$<$input_type$, $output_type$> "
|
||||||
"$method_new_field_name$;\n"
|
"$method_new_field_name$;\n"
|
||||||
" if (($method_new_field_name$ = "
|
" if (($method_new_field_name$ = "
|
||||||
"$service_class_name$.$method_new_field_name$) == null) {\n"
|
"$service_class_name$.$method_new_field_name$) == null) {\n"
|
||||||
" synchronized ($service_class_name$.class) {\n"
|
" synchronized ($service_class_name$.class) {\n"
|
||||||
" if (($method_new_field_name$ = "
|
" if (($method_new_field_name$ = "
|
||||||
"$service_class_name$.$method_new_field_name$) == null) {\n"
|
"$service_class_name$.$method_new_field_name$) == null) {\n"
|
||||||
" $service_class_name$.$method_new_field_name$ = "
|
" $service_class_name$.$method_new_field_name$ = "
|
||||||
"$method_new_field_name$ = \n"
|
"$method_new_field_name$ = \n"
|
||||||
" $MethodDescriptor$.<$input_type$, "
|
" $MethodDescriptor$.<$input_type$, "
|
||||||
"$output_type$>newBuilder()\n"
|
"$output_type$>newBuilder()\n"
|
||||||
" .setType($MethodType$.$method_type$)\n"
|
" .setType($MethodType$.$method_type$)\n"
|
||||||
" .setFullMethodName(generateFullMethodName(\n"
|
" .setFullMethodName(generateFullMethodName(\n"
|
||||||
" \"$Package$$service_name$\", \"$method_name$\"))\n"
|
" \"$Package$$service_name$\", \"$method_name$\"))\n"
|
||||||
" .setSampledToLocalTracing(true)\n"
|
" .setSampledToLocalTracing(true)\n"
|
||||||
" .setRequestMarshaller(FlatbuffersUtils.marshaller(\n"
|
" .setRequestMarshaller(FlatbuffersUtils.marshaller(\n"
|
||||||
" $input_type$.class, "
|
" $input_type$.class, "
|
||||||
"getExtractorOf$input_type_name$()))\n"
|
"getExtractorOf$input_type_name$()))\n"
|
||||||
" .setResponseMarshaller(FlatbuffersUtils.marshaller(\n"
|
" .setResponseMarshaller(FlatbuffersUtils.marshaller(\n"
|
||||||
" $output_type$.class, "
|
" $output_type$.class, "
|
||||||
"getExtractorOf$output_type_name$()))\n");
|
"getExtractorOf$output_type_name$()))\n");
|
||||||
|
|
||||||
// vars["proto_method_descriptor_supplier"] = service->name() +
|
// vars["proto_method_descriptor_supplier"] = service->name() +
|
||||||
// "MethodDescriptorSupplier";
|
// "MethodDescriptorSupplier";
|
||||||
@@ -451,11 +443,11 @@ enum StubType {
|
|||||||
|
|
||||||
enum CallType { ASYNC_CALL = 0, BLOCKING_CALL = 1, FUTURE_CALL = 2 };
|
enum CallType { ASYNC_CALL = 0, BLOCKING_CALL = 1, FUTURE_CALL = 2 };
|
||||||
|
|
||||||
static void PrintBindServiceMethodBody(Printer* p, VARS& vars,
|
static void PrintBindServiceMethodBody(Printer *p, VARS &vars,
|
||||||
const ServiceDescriptor* service);
|
const ServiceDescriptor *service);
|
||||||
|
|
||||||
// Prints a client interface or implementation class, or a server interface.
|
// Prints a client interface or implementation class, or a server interface.
|
||||||
static void PrintStub(Printer* p, VARS& vars, const ServiceDescriptor* service,
|
static void PrintStub(Printer *p, VARS &vars, const ServiceDescriptor *service,
|
||||||
StubType type) {
|
StubType type) {
|
||||||
const string service_name = service->name();
|
const string service_name = service->name();
|
||||||
vars["service_name"] = service_name;
|
vars["service_name"] = service_name;
|
||||||
@@ -476,7 +468,7 @@ static void PrintStub(Printer* p, VARS& vars, const ServiceDescriptor* service,
|
|||||||
break;
|
break;
|
||||||
case BLOCKING_CLIENT_INTERFACE:
|
case BLOCKING_CLIENT_INTERFACE:
|
||||||
interface = true;
|
interface = true;
|
||||||
FLATBUFFERS_FALLTHROUGH(); // fall thru
|
FLATBUFFERS_FALLTHROUGH(); // fall thru
|
||||||
case BLOCKING_CLIENT_IMPL:
|
case BLOCKING_CLIENT_IMPL:
|
||||||
call_type = BLOCKING_CALL;
|
call_type = BLOCKING_CALL;
|
||||||
stub_name += "BlockingStub";
|
stub_name += "BlockingStub";
|
||||||
@@ -484,7 +476,7 @@ static void PrintStub(Printer* p, VARS& vars, const ServiceDescriptor* service,
|
|||||||
break;
|
break;
|
||||||
case FUTURE_CLIENT_INTERFACE:
|
case FUTURE_CLIENT_INTERFACE:
|
||||||
interface = true;
|
interface = true;
|
||||||
FLATBUFFERS_FALLTHROUGH(); // fall thru
|
FLATBUFFERS_FALLTHROUGH(); // fall thru
|
||||||
case FUTURE_CLIENT_IMPL:
|
case FUTURE_CLIENT_IMPL:
|
||||||
call_type = FUTURE_CALL;
|
call_type = FUTURE_CALL;
|
||||||
stub_name += "FutureStub";
|
stub_name += "FutureStub";
|
||||||
@@ -501,9 +493,7 @@ static void PrintStub(Printer* p, VARS& vars, const ServiceDescriptor* service,
|
|||||||
vars["client_name"] = client_name;
|
vars["client_name"] = client_name;
|
||||||
|
|
||||||
// Class head
|
// Class head
|
||||||
if (!interface) {
|
if (!interface) { GrpcWriteServiceDocComment(p, vars, service); }
|
||||||
GrpcWriteServiceDocComment(p, vars, service);
|
|
||||||
}
|
|
||||||
if (impl_base) {
|
if (impl_base) {
|
||||||
p->Print(vars,
|
p->Print(vars,
|
||||||
"public static abstract class $abstract_name$ implements "
|
"public static abstract class $abstract_name$ implements "
|
||||||
@@ -546,8 +536,10 @@ static void PrintStub(Printer* p, VARS& vars, const ServiceDescriptor* service,
|
|||||||
vars["output_type"] = JavaClassName(vars, method->get_output_type_name());
|
vars["output_type"] = JavaClassName(vars, method->get_output_type_name());
|
||||||
vars["lower_method_name"] = LowerMethodName(&*method);
|
vars["lower_method_name"] = LowerMethodName(&*method);
|
||||||
vars["method_method_name"] = MethodPropertiesGetterName(&*method);
|
vars["method_method_name"] = MethodPropertiesGetterName(&*method);
|
||||||
bool client_streaming = method->ClientStreaming() || method->BidiStreaming();
|
bool client_streaming =
|
||||||
bool server_streaming = method->ServerStreaming() || method->BidiStreaming();
|
method->ClientStreaming() || method->BidiStreaming();
|
||||||
|
bool server_streaming =
|
||||||
|
method->ServerStreaming() || method->BidiStreaming();
|
||||||
|
|
||||||
if (call_type == BLOCKING_CALL && client_streaming) {
|
if (call_type == BLOCKING_CALL && client_streaming) {
|
||||||
// Blocking client interface with client streaming is not available
|
// Blocking client interface with client streaming is not available
|
||||||
@@ -563,9 +555,7 @@ static void PrintStub(Printer* p, VARS& vars, const ServiceDescriptor* service,
|
|||||||
p->Print("\n");
|
p->Print("\n");
|
||||||
// TODO(nmittler): Replace with WriteMethodDocComment once included by the
|
// TODO(nmittler): Replace with WriteMethodDocComment once included by the
|
||||||
// protobuf distro.
|
// protobuf distro.
|
||||||
if (!interface) {
|
if (!interface) { GrpcWriteMethodDocComment(p, vars, &*method); }
|
||||||
GrpcWriteMethodDocComment(p, vars, &*method);
|
|
||||||
}
|
|
||||||
p->Print("public ");
|
p->Print("public ");
|
||||||
switch (call_type) {
|
switch (call_type) {
|
||||||
case BLOCKING_CALL:
|
case BLOCKING_CALL:
|
||||||
@@ -630,8 +620,7 @@ static void PrintStub(Printer* p, VARS& vars, const ServiceDescriptor* service,
|
|||||||
"responseObserver);\n");
|
"responseObserver);\n");
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
default:
|
default: break;
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
} else if (!interface) {
|
} else if (!interface) {
|
||||||
switch (call_type) {
|
switch (call_type) {
|
||||||
@@ -706,15 +695,15 @@ static void PrintStub(Printer* p, VARS& vars, const ServiceDescriptor* service,
|
|||||||
}
|
}
|
||||||
|
|
||||||
static bool CompareMethodClientStreaming(
|
static bool CompareMethodClientStreaming(
|
||||||
const std::unique_ptr<const grpc_generator::Method>& method1,
|
const std::unique_ptr<const grpc_generator::Method> &method1,
|
||||||
const std::unique_ptr<const grpc_generator::Method>& method2) {
|
const std::unique_ptr<const grpc_generator::Method> &method2) {
|
||||||
return method1->ClientStreaming() < method2->ClientStreaming();
|
return method1->ClientStreaming() < method2->ClientStreaming();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Place all method invocations into a single class to reduce memory footprint
|
// Place all method invocations into a single class to reduce memory footprint
|
||||||
// on Android.
|
// on Android.
|
||||||
static void PrintMethodHandlerClass(Printer* p, VARS& vars,
|
static void PrintMethodHandlerClass(Printer *p, VARS &vars,
|
||||||
const ServiceDescriptor* service) {
|
const ServiceDescriptor *service) {
|
||||||
// Sort method ids based on ClientStreaming() so switch tables are compact.
|
// Sort method ids based on ClientStreaming() so switch tables are compact.
|
||||||
std::vector<std::unique_ptr<const grpc_generator::Method>> sorted_methods(
|
std::vector<std::unique_ptr<const grpc_generator::Method>> sorted_methods(
|
||||||
service->method_count());
|
service->method_count());
|
||||||
@@ -724,7 +713,7 @@ static void PrintMethodHandlerClass(Printer* p, VARS& vars,
|
|||||||
stable_sort(sorted_methods.begin(), sorted_methods.end(),
|
stable_sort(sorted_methods.begin(), sorted_methods.end(),
|
||||||
CompareMethodClientStreaming);
|
CompareMethodClientStreaming);
|
||||||
for (size_t i = 0; i < sorted_methods.size(); i++) {
|
for (size_t i = 0; i < sorted_methods.size(); i++) {
|
||||||
auto& method = sorted_methods[i];
|
auto &method = sorted_methods[i];
|
||||||
vars["method_id"] = to_string(i);
|
vars["method_id"] = to_string(i);
|
||||||
vars["method_id_name"] = MethodIdFieldName(&*method);
|
vars["method_id_name"] = MethodIdFieldName(&*method);
|
||||||
p->Print(vars,
|
p->Print(vars,
|
||||||
@@ -757,9 +746,7 @@ static void PrintMethodHandlerClass(Printer* p, VARS& vars,
|
|||||||
|
|
||||||
for (int i = 0; i < service->method_count(); ++i) {
|
for (int i = 0; i < service->method_count(); ++i) {
|
||||||
auto method = service->method(i);
|
auto method = service->method(i);
|
||||||
if (method->ClientStreaming() || method->BidiStreaming()) {
|
if (method->ClientStreaming() || method->BidiStreaming()) { continue; }
|
||||||
continue;
|
|
||||||
}
|
|
||||||
vars["method_id_name"] = MethodIdFieldName(&*method);
|
vars["method_id_name"] = MethodIdFieldName(&*method);
|
||||||
vars["lower_method_name"] = LowerMethodName(&*method);
|
vars["lower_method_name"] = LowerMethodName(&*method);
|
||||||
vars["input_type"] = JavaClassName(vars, method->get_input_type_name());
|
vars["input_type"] = JavaClassName(vars, method->get_input_type_name());
|
||||||
@@ -791,9 +778,7 @@ static void PrintMethodHandlerClass(Printer* p, VARS& vars,
|
|||||||
|
|
||||||
for (int i = 0; i < service->method_count(); ++i) {
|
for (int i = 0; i < service->method_count(); ++i) {
|
||||||
auto method = service->method(i);
|
auto method = service->method(i);
|
||||||
if (!(method->ClientStreaming() || method->BidiStreaming())) {
|
if (!(method->ClientStreaming() || method->BidiStreaming())) { continue; }
|
||||||
continue;
|
|
||||||
}
|
|
||||||
vars["method_id_name"] = MethodIdFieldName(&*method);
|
vars["method_id_name"] = MethodIdFieldName(&*method);
|
||||||
vars["lower_method_name"] = LowerMethodName(&*method);
|
vars["lower_method_name"] = LowerMethodName(&*method);
|
||||||
vars["input_type"] = JavaClassName(vars, method->get_input_type_name());
|
vars["input_type"] = JavaClassName(vars, method->get_input_type_name());
|
||||||
@@ -818,8 +803,8 @@ static void PrintMethodHandlerClass(Printer* p, VARS& vars,
|
|||||||
p->Print("}\n\n");
|
p->Print("}\n\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
static void PrintGetServiceDescriptorMethod(Printer* p, VARS& vars,
|
static void PrintGetServiceDescriptorMethod(Printer *p, VARS &vars,
|
||||||
const ServiceDescriptor* service) {
|
const ServiceDescriptor *service) {
|
||||||
vars["service_name"] = service->name();
|
vars["service_name"] = service->name();
|
||||||
// vars["proto_base_descriptor_supplier"] = service->name() +
|
// vars["proto_base_descriptor_supplier"] = service->name() +
|
||||||
// "BaseDescriptorSupplier"; vars["proto_file_descriptor_supplier"] =
|
// "BaseDescriptorSupplier"; vars["proto_file_descriptor_supplier"] =
|
||||||
@@ -911,8 +896,8 @@ static void PrintGetServiceDescriptorMethod(Printer* p, VARS& vars,
|
|||||||
p->Print("}\n");
|
p->Print("}\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
static void PrintBindServiceMethodBody(Printer* p, VARS& vars,
|
static void PrintBindServiceMethodBody(Printer *p, VARS &vars,
|
||||||
const ServiceDescriptor* service) {
|
const ServiceDescriptor *service) {
|
||||||
vars["service_name"] = service->name();
|
vars["service_name"] = service->name();
|
||||||
p->Indent();
|
p->Indent();
|
||||||
p->Print(vars,
|
p->Print(vars,
|
||||||
@@ -927,8 +912,10 @@ static void PrintBindServiceMethodBody(Printer* p, VARS& vars,
|
|||||||
vars["input_type"] = JavaClassName(vars, method->get_input_type_name());
|
vars["input_type"] = JavaClassName(vars, method->get_input_type_name());
|
||||||
vars["output_type"] = JavaClassName(vars, method->get_output_type_name());
|
vars["output_type"] = JavaClassName(vars, method->get_output_type_name());
|
||||||
vars["method_id_name"] = MethodIdFieldName(&*method);
|
vars["method_id_name"] = MethodIdFieldName(&*method);
|
||||||
bool client_streaming = method->ClientStreaming() || method->BidiStreaming();
|
bool client_streaming =
|
||||||
bool server_streaming = method->ServerStreaming() || method->BidiStreaming();
|
method->ClientStreaming() || method->BidiStreaming();
|
||||||
|
bool server_streaming =
|
||||||
|
method->ServerStreaming() || method->BidiStreaming();
|
||||||
if (client_streaming) {
|
if (client_streaming) {
|
||||||
if (server_streaming) {
|
if (server_streaming) {
|
||||||
vars["calls_method"] = "asyncBidiStreamingCall";
|
vars["calls_method"] = "asyncBidiStreamingCall";
|
||||||
@@ -962,8 +949,8 @@ static void PrintBindServiceMethodBody(Printer* p, VARS& vars,
|
|||||||
p->Outdent();
|
p->Outdent();
|
||||||
}
|
}
|
||||||
|
|
||||||
static void PrintService(Printer* p, VARS& vars,
|
static void PrintService(Printer *p, VARS &vars,
|
||||||
const ServiceDescriptor* service,
|
const ServiceDescriptor *service,
|
||||||
bool disable_version) {
|
bool disable_version) {
|
||||||
vars["service_name"] = service->name();
|
vars["service_name"] = service->name();
|
||||||
vars["service_class_name"] = ServiceClassName(service->name());
|
vars["service_class_name"] = ServiceClassName(service->name());
|
||||||
@@ -1043,7 +1030,7 @@ static void PrintService(Printer* p, VARS& vars,
|
|||||||
p->Print("}\n");
|
p->Print("}\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
void PrintStaticImports(Printer* p) {
|
static void PrintStaticImports(Printer *p) {
|
||||||
p->Print(
|
p->Print(
|
||||||
"import java.nio.ByteBuffer;\n"
|
"import java.nio.ByteBuffer;\n"
|
||||||
"import static "
|
"import static "
|
||||||
@@ -1076,8 +1063,8 @@ void PrintStaticImports(Printer* p) {
|
|||||||
"io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall;\n\n");
|
"io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall;\n\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
void GenerateService(const grpc_generator::Service* service,
|
static void GenerateService(const grpc_generator::Service *service,
|
||||||
grpc_generator::Printer* printer, VARS& vars,
|
grpc_generator::Printer *printer, VARS &vars,
|
||||||
bool disable_version) {
|
bool disable_version) {
|
||||||
// All non-generated classes must be referred by fully qualified names to
|
// All non-generated classes must be referred by fully qualified names to
|
||||||
// avoid collision with generated classes.
|
// avoid collision with generated classes.
|
||||||
@@ -1111,10 +1098,11 @@ void GenerateService(const grpc_generator::Service* service,
|
|||||||
|
|
||||||
PrintService(printer, vars, service, disable_version);
|
PrintService(printer, vars, service, disable_version);
|
||||||
}
|
}
|
||||||
|
} // namespace
|
||||||
|
|
||||||
grpc::string GenerateServiceSource(
|
grpc::string GenerateServiceSource(
|
||||||
grpc_generator::File* file, const grpc_generator::Service* service,
|
grpc_generator::File *file, const grpc_generator::Service *service,
|
||||||
grpc_java_generator::Parameters* parameters) {
|
grpc_java_generator::Parameters *parameters) {
|
||||||
grpc::string out;
|
grpc::string out;
|
||||||
auto printer = file->CreatePrinter(&out);
|
auto printer = file->CreatePrinter(&out);
|
||||||
VARS vars;
|
VARS vars;
|
||||||
|
|||||||
@@ -23,8 +23,9 @@
|
|||||||
#include "src/compiler/python_generator.h"
|
#include "src/compiler/python_generator.h"
|
||||||
|
|
||||||
namespace grpc_python_generator {
|
namespace grpc_python_generator {
|
||||||
|
namespace {
|
||||||
|
|
||||||
grpc::string GenerateMethodType(const grpc_generator::Method *method) {
|
static grpc::string GenerateMethodType(const grpc_generator::Method *method) {
|
||||||
|
|
||||||
if (method->NoStreaming())
|
if (method->NoStreaming())
|
||||||
return "unary_unary";
|
return "unary_unary";
|
||||||
@@ -131,6 +132,7 @@ void GenerateRegister(const grpc_generator::Service *service,
|
|||||||
printer->Outdent();
|
printer->Outdent();
|
||||||
printer->Print("\n");
|
printer->Print("\n");
|
||||||
}
|
}
|
||||||
|
} // namespace
|
||||||
|
|
||||||
grpc::string Generate(grpc_generator::File *file,
|
grpc::string Generate(grpc_generator::File *file,
|
||||||
const grpc_generator::Service *service) {
|
const grpc_generator::Service *service) {
|
||||||
|
|||||||
@@ -21,7 +21,6 @@
|
|||||||
|
|
||||||
#include <utility>
|
#include <utility>
|
||||||
|
|
||||||
#include "src/compiler/config.h"
|
|
||||||
#include "src/compiler/schema_interface.h"
|
#include "src/compiler/schema_interface.h"
|
||||||
|
|
||||||
namespace grpc_python_generator {
|
namespace grpc_python_generator {
|
||||||
|
|||||||
@@ -19,11 +19,10 @@
|
|||||||
#ifndef GRPC_INTERNAL_COMPILER_SCHEMA_INTERFACE_H
|
#ifndef GRPC_INTERNAL_COMPILER_SCHEMA_INTERFACE_H
|
||||||
#define GRPC_INTERNAL_COMPILER_SCHEMA_INTERFACE_H
|
#define GRPC_INTERNAL_COMPILER_SCHEMA_INTERFACE_H
|
||||||
|
|
||||||
|
#include <map>
|
||||||
#include <memory>
|
#include <memory>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
#include "src/compiler/config.h"
|
|
||||||
|
|
||||||
#ifndef GRPC_CUSTOM_STRING
|
#ifndef GRPC_CUSTOM_STRING
|
||||||
# include <string>
|
# include <string>
|
||||||
# define GRPC_CUSTOM_STRING std::string
|
# define GRPC_CUSTOM_STRING std::string
|
||||||
@@ -108,8 +107,6 @@ struct File : public CommentHolder {
|
|||||||
virtual grpc::string package() const = 0;
|
virtual grpc::string package() const = 0;
|
||||||
virtual std::vector<grpc::string> package_parts() const = 0;
|
virtual std::vector<grpc::string> package_parts() const = 0;
|
||||||
virtual grpc::string additional_headers() const = 0;
|
virtual grpc::string additional_headers() const = 0;
|
||||||
virtual std::string message_header_ext() const = 0;
|
|
||||||
virtual std::string service_header_ext() const = 0;
|
|
||||||
|
|
||||||
virtual int service_count() const = 0;
|
virtual int service_count() const = 0;
|
||||||
virtual std::unique_ptr<const Service> service(int i) const = 0;
|
virtual std::unique_ptr<const Service> service(int i) const = 0;
|
||||||
|
|||||||
@@ -28,8 +28,9 @@
|
|||||||
#include "src/compiler/swift_generator.h"
|
#include "src/compiler/swift_generator.h"
|
||||||
|
|
||||||
namespace grpc_swift_generator {
|
namespace grpc_swift_generator {
|
||||||
|
namespace {
|
||||||
|
|
||||||
std::string WrapInNameSpace(const std::vector<std::string> &components,
|
static std::string WrapInNameSpace(const std::vector<std::string> &components,
|
||||||
const grpc::string &name) {
|
const grpc::string &name) {
|
||||||
std::string qualified_name;
|
std::string qualified_name;
|
||||||
for (auto it = components.begin(); it != components.end(); ++it)
|
for (auto it = components.begin(); it != components.end(); ++it)
|
||||||
@@ -37,14 +38,14 @@ std::string WrapInNameSpace(const std::vector<std::string> &components,
|
|||||||
return qualified_name + name;
|
return qualified_name + name;
|
||||||
}
|
}
|
||||||
|
|
||||||
grpc::string GenerateMessage(const std::vector<std::string> &components,
|
static grpc::string GenerateMessage(const std::vector<std::string> &components,
|
||||||
const grpc::string &name) {
|
const grpc::string &name) {
|
||||||
return "Message<" + WrapInNameSpace(components, name) + ">";
|
return "Message<" + WrapInNameSpace(components, name) + ">";
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Client
|
// MARK: - Client
|
||||||
|
|
||||||
void GenerateClientFuncName(const grpc_generator::Method *method,
|
static void GenerateClientFuncName(const grpc_generator::Method *method,
|
||||||
grpc_generator::Printer *printer,
|
grpc_generator::Printer *printer,
|
||||||
std::map<grpc::string, grpc::string> *dictonary) {
|
std::map<grpc::string, grpc::string> *dictonary) {
|
||||||
auto vars = *dictonary;
|
auto vars = *dictonary;
|
||||||
@@ -82,7 +83,7 @@ void GenerateClientFuncName(const grpc_generator::Method *method,
|
|||||||
" ) -> BidirectionalStreamingCall<$Input$, $Output$>");
|
" ) -> BidirectionalStreamingCall<$Input$, $Output$>");
|
||||||
}
|
}
|
||||||
|
|
||||||
void GenerateClientFuncBody(const grpc_generator::Method *method,
|
static void GenerateClientFuncBody(const grpc_generator::Method *method,
|
||||||
grpc_generator::Printer *printer,
|
grpc_generator::Printer *printer,
|
||||||
std::map<grpc::string, grpc::string> *dictonary) {
|
std::map<grpc::string, grpc::string> *dictonary) {
|
||||||
auto vars = *dictonary;
|
auto vars = *dictonary;
|
||||||
@@ -372,6 +373,7 @@ void GenerateServerProtocol(const grpc_generator::Service *service,
|
|||||||
}
|
}
|
||||||
printer->Print("}");
|
printer->Print("}");
|
||||||
}
|
}
|
||||||
|
} // namespace
|
||||||
|
|
||||||
grpc::string Generate(grpc_generator::File *file,
|
grpc::string Generate(grpc_generator::File *file,
|
||||||
const grpc_generator::Service *service) {
|
const grpc_generator::Service *service) {
|
||||||
|
|||||||
@@ -1,40 +1,22 @@
|
|||||||
/*
|
/*
|
||||||
|
* Copyright 2020 Google Inc. All rights reserved.
|
||||||
*
|
*
|
||||||
* Copyright 2020, Google Inc.
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
* All rights reserved.
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
*
|
*
|
||||||
* Redistribution and use in source and binary forms, with or without
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
* modification, are permitted provided that the following conditions are
|
|
||||||
* met:
|
|
||||||
*
|
|
||||||
* * Redistributions of source code must retain the above copyright
|
|
||||||
* notice, this list of conditions and the following disclaimer.
|
|
||||||
* * Redistributions in binary form must reproduce the above
|
|
||||||
* copyright notice, this list of conditions and the following disclaimer
|
|
||||||
* in the documentation and/or other materials provided with the
|
|
||||||
* distribution.
|
|
||||||
* * Neither the name of Google Inc. nor the names of its
|
|
||||||
* contributors may be used to endorse or promote products derived from
|
|
||||||
* this software without specific prior written permission.
|
|
||||||
*
|
|
||||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
|
||||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
|
||||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
|
||||||
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
|
||||||
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
|
||||||
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
|
||||||
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
|
||||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
|
||||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
|
||||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
||||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
||||||
*
|
*
|
||||||
|
* 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 <memory>
|
#include <memory>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
#include "src/compiler/config.h"
|
|
||||||
#include "src/compiler/schema_interface.h"
|
#include "src/compiler/schema_interface.h"
|
||||||
|
|
||||||
#ifndef GRPC_CUSTOM_STRING
|
#ifndef GRPC_CUSTOM_STRING
|
||||||
|
|||||||
@@ -21,33 +21,18 @@
|
|||||||
* be maintained according to the Swift-grpc repository
|
* be maintained according to the Swift-grpc repository
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
#include "src/compiler/ts_generator.h"
|
||||||
|
|
||||||
#include <map>
|
#include <map>
|
||||||
#include <sstream>
|
#include <sstream>
|
||||||
|
|
||||||
#include "flatbuffers/util.h"
|
#include "flatbuffers/util.h"
|
||||||
#include "src/compiler/schema_interface.h"
|
#include "src/compiler/schema_interface.h"
|
||||||
#include "src/compiler/ts_generator.h"
|
|
||||||
|
|
||||||
namespace grpc_ts_generator {
|
namespace grpc_ts_generator {
|
||||||
|
namespace {
|
||||||
|
|
||||||
grpc::string ToDasherizedCase(const grpc::string pascal_case) {
|
static grpc::string GenerateNamespace(const std::vector<std::string> ns,
|
||||||
std::string dasherized_case;
|
|
||||||
char p = 0;
|
|
||||||
for (size_t i = 0; i < pascal_case.length(); i++) {
|
|
||||||
char const &c = pascal_case[i];
|
|
||||||
if (flatbuffers::is_alpha_upper(c)) {
|
|
||||||
if (i > 0 && p != flatbuffers::kPathSeparator) dasherized_case += "-";
|
|
||||||
dasherized_case += flatbuffers::CharToLower(c);
|
|
||||||
} else {
|
|
||||||
dasherized_case += c;
|
|
||||||
}
|
|
||||||
p = c;
|
|
||||||
}
|
|
||||||
return dasherized_case;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
grpc::string GenerateNamespace(const std::vector<std::string> ns,
|
|
||||||
const std::string filename,
|
const std::string filename,
|
||||||
const bool include_separator) {
|
const bool include_separator) {
|
||||||
grpc::string path = "";
|
grpc::string path = "";
|
||||||
@@ -55,17 +40,23 @@ grpc::string GenerateNamespace(const std::vector<std::string> ns,
|
|||||||
|
|
||||||
for (auto it = ns.begin(); it < ns.end(); it++) {
|
for (auto it = ns.begin(); it < ns.end(); it++) {
|
||||||
if (include_separator) path += "/";
|
if (include_separator) path += "/";
|
||||||
path += include_separator ? ToDasherizedCase(*it) : *it + "_";
|
path += include_separator
|
||||||
|
? flatbuffers::ConvertCase(*it, flatbuffers::Case::kDasher,
|
||||||
|
flatbuffers::Case::kUpperCamel)
|
||||||
|
: *it + "_";
|
||||||
}
|
}
|
||||||
|
|
||||||
if (include_separator) path += "/";
|
if (include_separator) path += "/";
|
||||||
path += include_separator ? ToDasherizedCase(filename) : filename;
|
path += include_separator
|
||||||
|
? flatbuffers::ConvertCase(filename, flatbuffers::Case::kDasher,
|
||||||
|
flatbuffers::Case::kUpperCamel)
|
||||||
|
: filename;
|
||||||
return path;
|
return path;
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Shared code
|
// MARK: - Shared code
|
||||||
|
|
||||||
void GenerateImports(const grpc_generator::Service *service,
|
static void GenerateImports(const grpc_generator::Service *service,
|
||||||
grpc_generator::Printer *printer,
|
grpc_generator::Printer *printer,
|
||||||
std::map<grpc::string, grpc::string> *dictonary,
|
std::map<grpc::string, grpc::string> *dictonary,
|
||||||
const bool grpc_var_import) {
|
const bool grpc_var_import) {
|
||||||
@@ -114,7 +105,7 @@ void GenerateImports(const grpc_generator::Service *service,
|
|||||||
|
|
||||||
// MARK: - Generate Main GRPC Code
|
// MARK: - Generate Main GRPC Code
|
||||||
|
|
||||||
void GetStreamType(grpc_generator::Printer *printer,
|
static void GetStreamType(grpc_generator::Printer *printer,
|
||||||
const grpc_generator::Method *method,
|
const grpc_generator::Method *method,
|
||||||
std::map<grpc::string, grpc::string> *dictonary) {
|
std::map<grpc::string, grpc::string> *dictonary) {
|
||||||
auto vars = *dictonary;
|
auto vars = *dictonary;
|
||||||
@@ -126,7 +117,7 @@ void GetStreamType(grpc_generator::Printer *printer,
|
|||||||
printer->Print(vars, "responseStream: $ServerStreaming$,\n");
|
printer->Print(vars, "responseStream: $ServerStreaming$,\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
void GenerateSerializeMethod(grpc_generator::Printer *printer,
|
static void GenerateSerializeMethod(grpc_generator::Printer *printer,
|
||||||
std::map<grpc::string, grpc::string> *dictonary) {
|
std::map<grpc::string, grpc::string> *dictonary) {
|
||||||
auto vars = *dictonary;
|
auto vars = *dictonary;
|
||||||
printer->Print(vars, "function serialize_$Type$(buffer_args) {\n");
|
printer->Print(vars, "function serialize_$Type$(buffer_args) {\n");
|
||||||
@@ -142,7 +133,7 @@ void GenerateSerializeMethod(grpc_generator::Printer *printer,
|
|||||||
printer->Print("}\n\n");
|
printer->Print("}\n\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
void GenerateDeserializeMethod(
|
static void GenerateDeserializeMethod(
|
||||||
grpc_generator::Printer *printer,
|
grpc_generator::Printer *printer,
|
||||||
std::map<grpc::string, grpc::string> *dictonary) {
|
std::map<grpc::string, grpc::string> *dictonary) {
|
||||||
auto vars = *dictonary;
|
auto vars = *dictonary;
|
||||||
@@ -155,7 +146,7 @@ void GenerateDeserializeMethod(
|
|||||||
printer->Print("}\n\n");
|
printer->Print("}\n\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
void GenerateMethods(const grpc_generator::Service *service,
|
static void GenerateMethods(const grpc_generator::Service *service,
|
||||||
grpc_generator::Printer *printer,
|
grpc_generator::Printer *printer,
|
||||||
std::map<grpc::string, grpc::string> *dictonary) {
|
std::map<grpc::string, grpc::string> *dictonary) {
|
||||||
auto vars = *dictonary;
|
auto vars = *dictonary;
|
||||||
@@ -187,7 +178,7 @@ void GenerateMethods(const grpc_generator::Service *service,
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void GenerateService(const grpc_generator::Service *service,
|
static void GenerateService(const grpc_generator::Service *service,
|
||||||
grpc_generator::Printer *printer,
|
grpc_generator::Printer *printer,
|
||||||
std::map<grpc::string, grpc::string> *dictonary) {
|
std::map<grpc::string, grpc::string> *dictonary) {
|
||||||
auto vars = *dictonary;
|
auto vars = *dictonary;
|
||||||
@@ -222,6 +213,8 @@ void GenerateService(const grpc_generator::Service *service,
|
|||||||
"grpc.makeGenericClientConstructor($NAME$);");
|
"grpc.makeGenericClientConstructor($NAME$);");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
grpc::string Generate(grpc_generator::File *file,
|
grpc::string Generate(grpc_generator::File *file,
|
||||||
const grpc_generator::Service *service,
|
const grpc_generator::Service *service,
|
||||||
const grpc::string &filename) {
|
const grpc::string &filename) {
|
||||||
@@ -243,9 +236,11 @@ grpc::string Generate(grpc_generator::File *file,
|
|||||||
return output;
|
return output;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
// MARK: - Generate Interface
|
// MARK: - Generate Interface
|
||||||
|
|
||||||
void FillInterface(grpc_generator::Printer *printer,
|
static void FillInterface(grpc_generator::Printer *printer,
|
||||||
std::map<grpc::string, grpc::string> *dictonary) {
|
std::map<grpc::string, grpc::string> *dictonary) {
|
||||||
auto vars = *dictonary;
|
auto vars = *dictonary;
|
||||||
printer->Print(vars,
|
printer->Print(vars,
|
||||||
@@ -263,7 +258,7 @@ void FillInterface(grpc_generator::Printer *printer,
|
|||||||
printer->Print("}\n");
|
printer->Print("}\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
void GenerateInterfaces(const grpc_generator::Service *service,
|
static void GenerateInterfaces(const grpc_generator::Service *service,
|
||||||
grpc_generator::Printer *printer,
|
grpc_generator::Printer *printer,
|
||||||
std::map<grpc::string, grpc::string> *dictonary) {
|
std::map<grpc::string, grpc::string> *dictonary) {
|
||||||
auto vars = *dictonary;
|
auto vars = *dictonary;
|
||||||
@@ -285,7 +280,7 @@ void GenerateInterfaces(const grpc_generator::Service *service,
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void GenerateExportedInterface(
|
static void GenerateExportedInterface(
|
||||||
const grpc_generator::Service *service, grpc_generator::Printer *printer,
|
const grpc_generator::Service *service, grpc_generator::Printer *printer,
|
||||||
std::map<grpc::string, grpc::string> *dictonary) {
|
std::map<grpc::string, grpc::string> *dictonary) {
|
||||||
auto vars = *dictonary;
|
auto vars = *dictonary;
|
||||||
@@ -329,7 +324,7 @@ void GenerateExportedInterface(
|
|||||||
printer->Print("}\n");
|
printer->Print("}\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
void GenerateMainInterface(const grpc_generator::Service *service,
|
static void GenerateMainInterface(const grpc_generator::Service *service,
|
||||||
grpc_generator::Printer *printer,
|
grpc_generator::Printer *printer,
|
||||||
std::map<grpc::string, grpc::string> *dictonary) {
|
std::map<grpc::string, grpc::string> *dictonary) {
|
||||||
auto vars = *dictonary;
|
auto vars = *dictonary;
|
||||||
@@ -354,11 +349,11 @@ void GenerateMainInterface(const grpc_generator::Service *service,
|
|||||||
GenerateExportedInterface(service, printer, &vars);
|
GenerateExportedInterface(service, printer, &vars);
|
||||||
}
|
}
|
||||||
|
|
||||||
grpc::string GenerateMetaData() { return "metadata: grpc.Metadata"; }
|
static grpc::string GenerateMetaData() { return "metadata: grpc.Metadata"; }
|
||||||
|
|
||||||
grpc::string GenerateOptions() { return "options: Partial<grpc.CallOptions>"; }
|
static grpc::string GenerateOptions() { return "options: Partial<grpc.CallOptions>"; }
|
||||||
|
|
||||||
void GenerateUnaryClientInterface(
|
static void GenerateUnaryClientInterface(
|
||||||
grpc_generator::Printer *printer,
|
grpc_generator::Printer *printer,
|
||||||
std::map<grpc::string, grpc::string> *dictonary) {
|
std::map<grpc::string, grpc::string> *dictonary) {
|
||||||
auto vars = *dictonary;
|
auto vars = *dictonary;
|
||||||
@@ -373,7 +368,7 @@ void GenerateUnaryClientInterface(
|
|||||||
printer->Print(vars, (main + meta_data + options + callback).c_str());
|
printer->Print(vars, (main + meta_data + options + callback).c_str());
|
||||||
}
|
}
|
||||||
|
|
||||||
void GenerateClientWriteStreamInterface(
|
static void GenerateClientWriteStreamInterface(
|
||||||
grpc_generator::Printer *printer,
|
grpc_generator::Printer *printer,
|
||||||
std::map<grpc::string, grpc::string> *dictonary) {
|
std::map<grpc::string, grpc::string> *dictonary) {
|
||||||
auto vars = *dictonary;
|
auto vars = *dictonary;
|
||||||
@@ -390,7 +385,7 @@ void GenerateClientWriteStreamInterface(
|
|||||||
printer->Print(vars, (main + meta_data + options + callback).c_str());
|
printer->Print(vars, (main + meta_data + options + callback).c_str());
|
||||||
}
|
}
|
||||||
|
|
||||||
void GenerateClientReadableStreamInterface(
|
static void GenerateClientReadableStreamInterface(
|
||||||
grpc_generator::Printer *printer,
|
grpc_generator::Printer *printer,
|
||||||
std::map<grpc::string, grpc::string> *dictonary) {
|
std::map<grpc::string, grpc::string> *dictonary) {
|
||||||
auto vars = *dictonary;
|
auto vars = *dictonary;
|
||||||
@@ -402,7 +397,7 @@ void GenerateClientReadableStreamInterface(
|
|||||||
printer->Print(vars, (main + options + end_function).c_str());
|
printer->Print(vars, (main + options + end_function).c_str());
|
||||||
}
|
}
|
||||||
|
|
||||||
void GenerateDepluxStreamInterface(
|
static void GenerateDepluxStreamInterface(
|
||||||
grpc_generator::Printer *printer,
|
grpc_generator::Printer *printer,
|
||||||
std::map<grpc::string, grpc::string> *dictonary) {
|
std::map<grpc::string, grpc::string> *dictonary) {
|
||||||
auto vars = *dictonary;
|
auto vars = *dictonary;
|
||||||
@@ -418,7 +413,7 @@ void GenerateDepluxStreamInterface(
|
|||||||
.c_str());
|
.c_str());
|
||||||
}
|
}
|
||||||
|
|
||||||
void GenerateClientInterface(const grpc_generator::Service *service,
|
static void GenerateClientInterface(const grpc_generator::Service *service,
|
||||||
grpc_generator::Printer *printer,
|
grpc_generator::Printer *printer,
|
||||||
std::map<grpc::string, grpc::string> *dictonary) {
|
std::map<grpc::string, grpc::string> *dictonary) {
|
||||||
auto vars = *dictonary;
|
auto vars = *dictonary;
|
||||||
@@ -456,7 +451,7 @@ void GenerateClientInterface(const grpc_generator::Service *service,
|
|||||||
printer->Print("}\n");
|
printer->Print("}\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
void GenerateClientClassInterface(
|
static void GenerateClientClassInterface(
|
||||||
const grpc_generator::Service *service, grpc_generator::Printer *printer,
|
const grpc_generator::Service *service, grpc_generator::Printer *printer,
|
||||||
std::map<grpc::string, grpc::string> *dictonary) {
|
std::map<grpc::string, grpc::string> *dictonary) {
|
||||||
auto vars = *dictonary;
|
auto vars = *dictonary;
|
||||||
@@ -497,6 +492,8 @@ void GenerateClientClassInterface(
|
|||||||
printer->Outdent();
|
printer->Outdent();
|
||||||
printer->Print("}\n");
|
printer->Print("}\n");
|
||||||
}
|
}
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
|
||||||
grpc::string GenerateInterface(grpc_generator::File *file,
|
grpc::string GenerateInterface(grpc_generator::File *file,
|
||||||
const grpc_generator::Service *service,
|
const grpc_generator::Service *service,
|
||||||
|
|||||||
@@ -1,41 +1,7 @@
|
|||||||
/*
|
|
||||||
*
|
|
||||||
* Copyright 2020, Google Inc.
|
|
||||||
* All rights reserved.
|
|
||||||
*
|
|
||||||
* Redistribution and use in source and binary forms, with or without
|
|
||||||
* modification, are permitted provided that the following conditions are
|
|
||||||
* met:
|
|
||||||
*
|
|
||||||
* * Redistributions of source code must retain the above copyright
|
|
||||||
* notice, this list of conditions and the following disclaimer.
|
|
||||||
* * Redistributions in binary form must reproduce the above
|
|
||||||
* copyright notice, this list of conditions and the following disclaimer
|
|
||||||
* in the documentation and/or other materials provided with the
|
|
||||||
* distribution.
|
|
||||||
* * Neither the name of Google Inc. nor the names of its
|
|
||||||
* contributors may be used to endorse or promote products derived from
|
|
||||||
* this software without specific prior written permission.
|
|
||||||
*
|
|
||||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
|
||||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
|
||||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
|
||||||
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
|
||||||
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
|
||||||
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
|
||||||
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
|
||||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
|
||||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
|
||||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
||||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
|
|
||||||
#include <memory>
|
#include <memory>
|
||||||
#include <vector>
|
|
||||||
#include <set>
|
#include <set>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
#include "src/compiler/config.h"
|
|
||||||
#include "src/compiler/schema_interface.h"
|
#include "src/compiler/schema_interface.h"
|
||||||
|
|
||||||
#ifndef GRPC_CUSTOM_STRING
|
#ifndef GRPC_CUSTOM_STRING
|
||||||
@@ -58,4 +24,3 @@ grpc::string GenerateInterface(grpc_generator::File *file,
|
|||||||
const grpc_generator::Service *service,
|
const grpc_generator::Service *service,
|
||||||
const grpc::string &filename);
|
const grpc::string &filename);
|
||||||
} // namespace grpc_ts_generator
|
} // namespace grpc_ts_generator
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
package testing
|
package testing
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"../../tests/MyGame/Example"
|
|
||||||
flatbuffers "github.com/google/flatbuffers/go"
|
flatbuffers "github.com/google/flatbuffers/go"
|
||||||
|
"github.com/google/flatbuffers/tests/MyGame/Example"
|
||||||
|
|
||||||
"context"
|
"context"
|
||||||
"net"
|
"net"
|
||||||
@@ -12,7 +12,9 @@ import (
|
|||||||
"google.golang.org/grpc/encoding"
|
"google.golang.org/grpc/encoding"
|
||||||
)
|
)
|
||||||
|
|
||||||
type server struct{}
|
type server struct {
|
||||||
|
Example.UnimplementedMonsterStorageServer
|
||||||
|
}
|
||||||
|
|
||||||
// test used to send and receive in grpc methods
|
// test used to send and receive in grpc methods
|
||||||
var test = "Flatbuffers"
|
var test = "Flatbuffers"
|
||||||
@@ -65,8 +67,12 @@ func RetrieveClient(c Example.MonsterStorageClient, t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Retrieve client failed: %v", err)
|
t.Fatalf("Retrieve client failed: %v", err)
|
||||||
}
|
}
|
||||||
if string(out.Name()) != test {
|
monster, err := out.Recv()
|
||||||
t.Errorf("RetrieveClient failed: expected=%s, got=%s\n", test, out.Name())
|
if err != nil {
|
||||||
|
t.Fatalf("Recv failed: %v", err)
|
||||||
|
}
|
||||||
|
if string(monster.Name()) != test {
|
||||||
|
t.Errorf("RetrieveClient failed: expected=%s, got=%s\n", test, monster.Name())
|
||||||
t.Fail()
|
t.Fail()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -140,7 +140,7 @@
|
|||||||
|
|
||||||
#define FLATBUFFERS_VERSION_MAJOR 2
|
#define FLATBUFFERS_VERSION_MAJOR 2
|
||||||
#define FLATBUFFERS_VERSION_MINOR 0
|
#define FLATBUFFERS_VERSION_MINOR 0
|
||||||
#define FLATBUFFERS_VERSION_REVISION 5
|
#define FLATBUFFERS_VERSION_REVISION 8
|
||||||
#define FLATBUFFERS_STRING_EXPAND(X) #X
|
#define FLATBUFFERS_STRING_EXPAND(X) #X
|
||||||
#define FLATBUFFERS_STRING(X) FLATBUFFERS_STRING_EXPAND(X)
|
#define FLATBUFFERS_STRING(X) FLATBUFFERS_STRING_EXPAND(X)
|
||||||
namespace flatbuffers {
|
namespace flatbuffers {
|
||||||
@@ -260,9 +260,12 @@ namespace flatbuffers {
|
|||||||
#endif // !FLATBUFFERS_HAS_NEW_STRTOD
|
#endif // !FLATBUFFERS_HAS_NEW_STRTOD
|
||||||
|
|
||||||
#ifndef FLATBUFFERS_LOCALE_INDEPENDENT
|
#ifndef FLATBUFFERS_LOCALE_INDEPENDENT
|
||||||
// Enable locale independent functions {strtof_l, strtod_l,strtoll_l, strtoull_l}.
|
// Enable locale independent functions {strtof_l, strtod_l,strtoll_l,
|
||||||
#if ((defined(_MSC_VER) && _MSC_VER >= 1800) || \
|
// strtoull_l}.
|
||||||
(defined(_XOPEN_VERSION) && (_XOPEN_VERSION>=700)) && (!defined(__ANDROID_API__) || (defined(__ANDROID_API__) && (__ANDROID_API__>=21))))
|
#if (defined(_MSC_VER) && _MSC_VER >= 1800) || \
|
||||||
|
(defined(__ANDROID_API__) && __ANDROID_API__>= 21) || \
|
||||||
|
(defined(_XOPEN_VERSION) && (_XOPEN_VERSION >= 700)) && \
|
||||||
|
(!defined(__Fuchsia__) && !defined(__ANDROID_API__))
|
||||||
#define FLATBUFFERS_LOCALE_INDEPENDENT 1
|
#define FLATBUFFERS_LOCALE_INDEPENDENT 1
|
||||||
#else
|
#else
|
||||||
#define FLATBUFFERS_LOCALE_INDEPENDENT 0
|
#define FLATBUFFERS_LOCALE_INDEPENDENT 0
|
||||||
@@ -270,14 +273,14 @@ namespace flatbuffers {
|
|||||||
#endif // !FLATBUFFERS_LOCALE_INDEPENDENT
|
#endif // !FLATBUFFERS_LOCALE_INDEPENDENT
|
||||||
|
|
||||||
// Suppress Undefined Behavior Sanitizer (recoverable only). Usage:
|
// Suppress Undefined Behavior Sanitizer (recoverable only). Usage:
|
||||||
// - __supress_ubsan__("undefined")
|
// - __suppress_ubsan__("undefined")
|
||||||
// - __supress_ubsan__("signed-integer-overflow")
|
// - __suppress_ubsan__("signed-integer-overflow")
|
||||||
#if defined(__clang__) && (__clang_major__ > 3 || (__clang_major__ == 3 && __clang_minor__ >=7))
|
#if defined(__clang__) && (__clang_major__ > 3 || (__clang_major__ == 3 && __clang_minor__ >=7))
|
||||||
#define __supress_ubsan__(type) __attribute__((no_sanitize(type)))
|
#define __suppress_ubsan__(type) __attribute__((no_sanitize(type)))
|
||||||
#elif defined(__GNUC__) && (__GNUC__ * 100 + __GNUC_MINOR__ >= 409)
|
#elif defined(__GNUC__) && (__GNUC__ * 100 + __GNUC_MINOR__ >= 409)
|
||||||
#define __supress_ubsan__(type) __attribute__((no_sanitize_undefined))
|
#define __suppress_ubsan__(type) __attribute__((no_sanitize_undefined))
|
||||||
#else
|
#else
|
||||||
#define __supress_ubsan__(type)
|
#define __suppress_ubsan__(type)
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
// This is constexpr function used for checking compile-time constants.
|
// This is constexpr function used for checking compile-time constants.
|
||||||
@@ -328,8 +331,17 @@ typedef uintmax_t largest_scalar_t;
|
|||||||
// In 32bits, this evaluates to 2GB - 1
|
// In 32bits, this evaluates to 2GB - 1
|
||||||
#define FLATBUFFERS_MAX_BUFFER_SIZE ((1ULL << (sizeof(::flatbuffers::soffset_t) * 8 - 1)) - 1)
|
#define FLATBUFFERS_MAX_BUFFER_SIZE ((1ULL << (sizeof(::flatbuffers::soffset_t) * 8 - 1)) - 1)
|
||||||
|
|
||||||
|
// The minimum size buffer that can be a valid flatbuffer.
|
||||||
|
// Includes the offset to the root table (uoffset_t), the offset to the vtable
|
||||||
|
// of the root table (soffset_t), the size of the vtable (uint16_t), and the
|
||||||
|
// size of the referring table (uint16_t).
|
||||||
|
#define FLATBUFFERS_MIN_BUFFER_SIZE sizeof(uoffset_t) + sizeof(soffset_t) + \
|
||||||
|
sizeof(uint16_t) + sizeof(uint16_t)
|
||||||
|
|
||||||
// We support aligning the contents of buffers up to this size.
|
// We support aligning the contents of buffers up to this size.
|
||||||
#define FLATBUFFERS_MAX_ALIGNMENT 16
|
#ifndef FLATBUFFERS_MAX_ALIGNMENT
|
||||||
|
#define FLATBUFFERS_MAX_ALIGNMENT 32
|
||||||
|
#endif
|
||||||
|
|
||||||
/// @brief The length of a FlatBuffer file header.
|
/// @brief The length of a FlatBuffer file header.
|
||||||
static const size_t kFileIdentifierLength = 4;
|
static const size_t kFileIdentifierLength = 4;
|
||||||
@@ -401,7 +413,7 @@ template<typename T> T EndianScalar(T t) {
|
|||||||
|
|
||||||
template<typename T>
|
template<typename T>
|
||||||
// UBSAN: C++ aliasing type rules, see std::bit_cast<> for details.
|
// UBSAN: C++ aliasing type rules, see std::bit_cast<> for details.
|
||||||
__supress_ubsan__("alignment")
|
__suppress_ubsan__("alignment")
|
||||||
T ReadScalar(const void *p) {
|
T ReadScalar(const void *p) {
|
||||||
return EndianScalar(*reinterpret_cast<const T *>(p));
|
return EndianScalar(*reinterpret_cast<const T *>(p));
|
||||||
}
|
}
|
||||||
@@ -415,13 +427,13 @@ T ReadScalar(const void *p) {
|
|||||||
|
|
||||||
template<typename T>
|
template<typename T>
|
||||||
// UBSAN: C++ aliasing type rules, see std::bit_cast<> for details.
|
// UBSAN: C++ aliasing type rules, see std::bit_cast<> for details.
|
||||||
__supress_ubsan__("alignment")
|
__suppress_ubsan__("alignment")
|
||||||
void WriteScalar(void *p, T t) {
|
void WriteScalar(void *p, T t) {
|
||||||
*reinterpret_cast<T *>(p) = EndianScalar(t);
|
*reinterpret_cast<T *>(p) = EndianScalar(t);
|
||||||
}
|
}
|
||||||
|
|
||||||
template<typename T> struct Offset;
|
template<typename T> struct Offset;
|
||||||
template<typename T> __supress_ubsan__("alignment") void WriteScalar(void *p, Offset<T> t) {
|
template<typename T> __suppress_ubsan__("alignment") void WriteScalar(void *p, Offset<T> t) {
|
||||||
*reinterpret_cast<uoffset_t *>(p) = EndianScalar(t.o);
|
*reinterpret_cast<uoffset_t *>(p) = EndianScalar(t.o);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -432,7 +444,7 @@ template<typename T> __supress_ubsan__("alignment") void WriteScalar(void *p, Of
|
|||||||
// Computes how many bytes you'd have to pad to be able to write an
|
// Computes how many bytes you'd have to pad to be able to write an
|
||||||
// "scalar_size" scalar if the buffer had grown to "buf_size" (downwards in
|
// "scalar_size" scalar if the buffer had grown to "buf_size" (downwards in
|
||||||
// memory).
|
// memory).
|
||||||
__supress_ubsan__("unsigned-integer-overflow")
|
__suppress_ubsan__("unsigned-integer-overflow")
|
||||||
inline size_t PaddingBytes(size_t buf_size, size_t scalar_size) {
|
inline size_t PaddingBytes(size_t buf_size, size_t scalar_size) {
|
||||||
return ((~buf_size) + 1) & (scalar_size - 1);
|
return ((~buf_size) + 1) & (scalar_size - 1);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -95,7 +95,7 @@ template<typename T> struct IndirectHelper<const T *> {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
/// @brief Get a pointer to the the file_identifier section of the buffer.
|
/// @brief Get a pointer to the file_identifier section of the buffer.
|
||||||
/// @return Returns a const char pointer to the start of the file_identifier
|
/// @return Returns a const char pointer to the start of the file_identifier
|
||||||
/// characters in the buffer. The returned char * has length
|
/// characters in the buffer. The returned char * has length
|
||||||
/// 'flatbuffers::FlatBufferBuilder::kFileIdentifierLength'.
|
/// 'flatbuffers::FlatBufferBuilder::kFileIdentifierLength'.
|
||||||
|
|||||||
@@ -97,8 +97,6 @@ class BaseGenerator {
|
|||||||
const Namespace &ns,
|
const Namespace &ns,
|
||||||
const bool dasherize = false);
|
const bool dasherize = false);
|
||||||
|
|
||||||
static std::string ToDasherizedCase(const std::string pascal_case);
|
|
||||||
|
|
||||||
std::string GeneratedFileName(const std::string &path,
|
std::string GeneratedFileName(const std::string &path,
|
||||||
const std::string &file_name,
|
const std::string &file_name,
|
||||||
const IDLOptions &options) const;
|
const IDLOptions &options) const;
|
||||||
@@ -140,7 +138,8 @@ class BaseGenerator {
|
|||||||
std::string WrapInNameSpace(const Namespace *ns,
|
std::string WrapInNameSpace(const Namespace *ns,
|
||||||
const std::string &name) const;
|
const std::string &name) const;
|
||||||
|
|
||||||
std::string WrapInNameSpace(const Definition &def) const;
|
std::string WrapInNameSpace(const Definition &def,
|
||||||
|
const std::string &suffix = "") const;
|
||||||
|
|
||||||
std::string GetNameSpace(const Definition &def) const;
|
std::string GetNameSpace(const Definition &def) const;
|
||||||
|
|
||||||
|
|||||||
@@ -18,6 +18,7 @@
|
|||||||
#define FLATBUFFERS_FLATBUFFER_BUILDER_H_
|
#define FLATBUFFERS_FLATBUFFER_BUILDER_H_
|
||||||
|
|
||||||
#include <functional>
|
#include <functional>
|
||||||
|
#include <initializer_list>
|
||||||
|
|
||||||
#include "flatbuffers/allocator.h"
|
#include "flatbuffers/allocator.h"
|
||||||
#include "flatbuffers/array.h"
|
#include "flatbuffers/array.h"
|
||||||
@@ -42,14 +43,15 @@ inline voffset_t FieldIndexToOffset(voffset_t field_id) {
|
|||||||
return static_cast<voffset_t>((field_id + fixed_fields) * sizeof(voffset_t));
|
return static_cast<voffset_t>((field_id + fixed_fields) * sizeof(voffset_t));
|
||||||
}
|
}
|
||||||
|
|
||||||
template<typename T, typename Alloc>
|
template<typename T, typename Alloc = std::allocator<T>>
|
||||||
const T *data(const std::vector<T, Alloc> &v) {
|
const T *data(const std::vector<T, Alloc> &v) {
|
||||||
// Eventually the returned pointer gets passed down to memcpy, so
|
// Eventually the returned pointer gets passed down to memcpy, so
|
||||||
// we need it to be non-null to avoid undefined behavior.
|
// we need it to be non-null to avoid undefined behavior.
|
||||||
static uint8_t t;
|
static uint8_t t;
|
||||||
return v.empty() ? reinterpret_cast<const T *>(&t) : &v.front();
|
return v.empty() ? reinterpret_cast<const T *>(&t) : &v.front();
|
||||||
}
|
}
|
||||||
template<typename T, typename Alloc> T *data(std::vector<T, Alloc> &v) {
|
template<typename T, typename Alloc = std::allocator<T>>
|
||||||
|
T *data(std::vector<T, Alloc> &v) {
|
||||||
// Eventually the returned pointer gets passed down to memcpy, so
|
// Eventually the returned pointer gets passed down to memcpy, so
|
||||||
// we need it to be non-null to avoid undefined behavior.
|
// we need it to be non-null to avoid undefined behavior.
|
||||||
static uint8_t t;
|
static uint8_t t;
|
||||||
@@ -285,9 +287,7 @@ class FlatBufferBuilder {
|
|||||||
FieldLoc fl = { off, field };
|
FieldLoc fl = { off, field };
|
||||||
buf_.scratch_push_small(fl);
|
buf_.scratch_push_small(fl);
|
||||||
num_field_loc++;
|
num_field_loc++;
|
||||||
if (field > max_voffset_) {
|
if (field > max_voffset_) { max_voffset_ = field; }
|
||||||
max_voffset_ = field;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Like PushElement, but additionally tracks the field this represents.
|
// Like PushElement, but additionally tracks the field this represents.
|
||||||
@@ -358,7 +358,7 @@ class FlatBufferBuilder {
|
|||||||
// If you get this assert, a corresponding StartTable wasn't called.
|
// If you get this assert, a corresponding StartTable wasn't called.
|
||||||
FLATBUFFERS_ASSERT(nested);
|
FLATBUFFERS_ASSERT(nested);
|
||||||
// Write the vtable offset, which is the start of any Table.
|
// Write the vtable offset, which is the start of any Table.
|
||||||
// We fill it's value later.
|
// We fill its value later.
|
||||||
auto vtableoffsetloc = PushElement<soffset_t>(0);
|
auto vtableoffsetloc = PushElement<soffset_t>(0);
|
||||||
// Write a vtable, which consists entirely of voffset_t elements.
|
// Write a vtable, which consists entirely of voffset_t elements.
|
||||||
// It starts with the number of offsets, followed by a type id, followed
|
// It starts with the number of offsets, followed by a type id, followed
|
||||||
@@ -443,6 +443,7 @@ class FlatBufferBuilder {
|
|||||||
// Aligns such that when "len" bytes are written, an object can be written
|
// Aligns such that when "len" bytes are written, an object can be written
|
||||||
// after it with "alignment" without padding.
|
// after it with "alignment" without padding.
|
||||||
void PreAlign(size_t len, size_t alignment) {
|
void PreAlign(size_t len, size_t alignment) {
|
||||||
|
if (len == 0) return;
|
||||||
TrackMinAlign(alignment);
|
TrackMinAlign(alignment);
|
||||||
buf_.fill(PaddingBytes(GetSize() + len, alignment));
|
buf_.fill(PaddingBytes(GetSize() + len, alignment));
|
||||||
}
|
}
|
||||||
@@ -578,7 +579,7 @@ class FlatBufferBuilder {
|
|||||||
/// @param[in] str A const pointer to a `String` struct to add to the buffer.
|
/// @param[in] str A const pointer to a `String` struct to add to the buffer.
|
||||||
/// @return Returns the offset in the buffer where the string starts
|
/// @return Returns the offset in the buffer where the string starts
|
||||||
Offset<String> CreateSharedString(const String *str) {
|
Offset<String> CreateSharedString(const String *str) {
|
||||||
return CreateSharedString(str->c_str(), str->size());
|
return str ? CreateSharedString(str->c_str(), str->size()) : 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// @cond FLATBUFFERS_INTERNAL
|
/// @cond FLATBUFFERS_INTERNAL
|
||||||
@@ -601,12 +602,14 @@ class FlatBufferBuilder {
|
|||||||
// This is useful when storing a nested_flatbuffer in a vector of bytes,
|
// This is useful when storing a nested_flatbuffer in a vector of bytes,
|
||||||
// or when storing SIMD floats, etc.
|
// or when storing SIMD floats, etc.
|
||||||
void ForceVectorAlignment(size_t len, size_t elemsize, size_t alignment) {
|
void ForceVectorAlignment(size_t len, size_t elemsize, size_t alignment) {
|
||||||
|
if (len == 0) return;
|
||||||
FLATBUFFERS_ASSERT(VerifyAlignmentRequirements(alignment));
|
FLATBUFFERS_ASSERT(VerifyAlignmentRequirements(alignment));
|
||||||
PreAlign(len * elemsize, alignment);
|
PreAlign(len * elemsize, alignment);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Similar to ForceVectorAlignment but for String fields.
|
// Similar to ForceVectorAlignment but for String fields.
|
||||||
void ForceStringAlignment(size_t len, size_t alignment) {
|
void ForceStringAlignment(size_t len, size_t alignment) {
|
||||||
|
if (len == 0) return;
|
||||||
FLATBUFFERS_ASSERT(VerifyAlignmentRequirements(alignment));
|
FLATBUFFERS_ASSERT(VerifyAlignmentRequirements(alignment));
|
||||||
PreAlign((len + 1) * sizeof(char), alignment);
|
PreAlign((len + 1) * sizeof(char), alignment);
|
||||||
}
|
}
|
||||||
@@ -642,6 +645,27 @@ class FlatBufferBuilder {
|
|||||||
return Offset<Vector<T>>(EndVector(len));
|
return Offset<Vector<T>>(EndVector(len));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// @brief Serialize an array like object into a FlatBuffer `vector`.
|
||||||
|
/// @tparam T The data type of the array elements.
|
||||||
|
/// @tparam C The type of the array.
|
||||||
|
/// @param[in] array A reference to an array like object of type `T` to
|
||||||
|
/// serialize into the buffer as a `vector`.
|
||||||
|
/// @return Returns a typed `Offset` into the serialized data indicating
|
||||||
|
/// where the vector is stored.
|
||||||
|
template<typename T, class C> Offset<Vector<T>> CreateVector(const C &array) {
|
||||||
|
return CreateVector(array.data(), array.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @brief Serialize an initializer list into a FlatBuffer `vector`.
|
||||||
|
/// @tparam T The data type of the initializer list elements.
|
||||||
|
/// @param[in] v The value of the initializer list.
|
||||||
|
/// @return Returns a typed `Offset` into the serialized data indicating
|
||||||
|
/// where the vector is stored.
|
||||||
|
template<typename T>
|
||||||
|
Offset<Vector<T>> CreateVector(std::initializer_list<T> v) {
|
||||||
|
return CreateVector(v.begin(), v.size());
|
||||||
|
}
|
||||||
|
|
||||||
template<typename T>
|
template<typename T>
|
||||||
Offset<Vector<Offset<T>>> CreateVector(const Offset<T> *v, size_t len) {
|
Offset<Vector<Offset<T>>> CreateVector(const Offset<T> *v, size_t len) {
|
||||||
StartVector(len, sizeof(Offset<T>));
|
StartVector(len, sizeof(Offset<T>));
|
||||||
@@ -655,7 +679,7 @@ class FlatBufferBuilder {
|
|||||||
/// buffer as a `vector`.
|
/// buffer as a `vector`.
|
||||||
/// @return Returns a typed `Offset` into the serialized data indicating
|
/// @return Returns a typed `Offset` into the serialized data indicating
|
||||||
/// where the vector is stored.
|
/// where the vector is stored.
|
||||||
template<typename T, typename Alloc>
|
template<typename T, typename Alloc = std::allocator<T>>
|
||||||
Offset<Vector<T>> CreateVector(const std::vector<T, Alloc> &v) {
|
Offset<Vector<T>> CreateVector(const std::vector<T, Alloc> &v) {
|
||||||
return CreateVector(data(v), v.size());
|
return CreateVector(data(v), v.size());
|
||||||
}
|
}
|
||||||
@@ -706,21 +730,24 @@ class FlatBufferBuilder {
|
|||||||
return CreateVector(elems);
|
return CreateVector(elems);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// @brief Serialize a `std::vector<std::string>` into a FlatBuffer `vector`.
|
/// @brief Serialize a `std::vector<StringType>` into a FlatBuffer `vector`.
|
||||||
|
/// whereas StringType is any type that is accepted by the CreateString()
|
||||||
|
/// overloads.
|
||||||
/// This is a convenience function for a common case.
|
/// This is a convenience function for a common case.
|
||||||
/// @param v A const reference to the `std::vector` to serialize into the
|
/// @param v A const reference to the `std::vector` to serialize into the
|
||||||
/// buffer as a `vector`.
|
/// buffer as a `vector`.
|
||||||
/// @return Returns a typed `Offset` into the serialized data indicating
|
/// @return Returns a typed `Offset` into the serialized data indicating
|
||||||
/// where the vector is stored.
|
/// where the vector is stored.
|
||||||
template<typename Alloc>
|
template<typename StringType = std::string,
|
||||||
|
typename Alloc = std::allocator<StringType>>
|
||||||
Offset<Vector<Offset<String>>> CreateVectorOfStrings(
|
Offset<Vector<Offset<String>>> CreateVectorOfStrings(
|
||||||
const std::vector<std::string, Alloc> &v) {
|
const std::vector<StringType, Alloc> &v) {
|
||||||
return CreateVectorOfStrings(v.cbegin(), v.cend());
|
return CreateVectorOfStrings(v.cbegin(), v.cend());
|
||||||
}
|
}
|
||||||
|
|
||||||
/// @brief Serialize a collection of Strings into a FlatBuffer `vector`.
|
/// @brief Serialize a collection of Strings into a FlatBuffer `vector`.
|
||||||
/// This is a convenience function for a common case.
|
/// This is a convenience function for a common case.
|
||||||
/// @param begin The begining iterator of the collection
|
/// @param begin The beginning iterator of the collection
|
||||||
/// @param end The ending iterator of the collection
|
/// @param end The ending iterator of the collection
|
||||||
/// @return Returns a typed `Offset` into the serialized data indicating
|
/// @return Returns a typed `Offset` into the serialized data indicating
|
||||||
/// where the vector is stored.
|
/// where the vector is stored.
|
||||||
@@ -730,7 +757,7 @@ class FlatBufferBuilder {
|
|||||||
auto scratch_buffer_usage = size * sizeof(Offset<String>);
|
auto scratch_buffer_usage = size * sizeof(Offset<String>);
|
||||||
// If there is not enough space to store the offsets, there definitely won't
|
// If there is not enough space to store the offsets, there definitely won't
|
||||||
// be enough space to store all the strings. So ensuring space for the
|
// be enough space to store all the strings. So ensuring space for the
|
||||||
// scratch region is OK, for it it fails, it would have failed later.
|
// scratch region is OK, for if it fails, it would have failed later.
|
||||||
buf_.ensure_space(scratch_buffer_usage);
|
buf_.ensure_space(scratch_buffer_usage);
|
||||||
for (auto it = begin; it != end; ++it) {
|
for (auto it = begin; it != end; ++it) {
|
||||||
buf_.scratch_push_small(CreateString(*it));
|
buf_.scratch_push_small(CreateString(*it));
|
||||||
@@ -841,7 +868,7 @@ class FlatBufferBuilder {
|
|||||||
/// serialize into the buffer as a `vector`.
|
/// serialize into the buffer as a `vector`.
|
||||||
/// @return Returns a typed `Offset` into the serialized data indicating
|
/// @return Returns a typed `Offset` into the serialized data indicating
|
||||||
/// where the vector is stored.
|
/// where the vector is stored.
|
||||||
template<typename T, typename Alloc>
|
template<typename T, typename Alloc = std::allocator<T>>
|
||||||
Offset<Vector<const T *>> CreateVectorOfStructs(
|
Offset<Vector<const T *>> CreateVectorOfStructs(
|
||||||
const std::vector<T, Alloc> &v) {
|
const std::vector<T, Alloc> &v) {
|
||||||
return CreateVectorOfStructs(data(v), v.size());
|
return CreateVectorOfStructs(data(v), v.size());
|
||||||
@@ -857,7 +884,7 @@ class FlatBufferBuilder {
|
|||||||
/// to the FlatBuffer struct.
|
/// to the FlatBuffer struct.
|
||||||
/// @return Returns a typed `Offset` into the serialized data indicating
|
/// @return Returns a typed `Offset` into the serialized data indicating
|
||||||
/// where the vector is stored.
|
/// where the vector is stored.
|
||||||
template<typename T, typename S, typename Alloc>
|
template<typename T, typename S, typename Alloc = std::allocator<T>>
|
||||||
Offset<Vector<const T *>> CreateVectorOfNativeStructs(
|
Offset<Vector<const T *>> CreateVectorOfNativeStructs(
|
||||||
const std::vector<S, Alloc> &v, T (*const pack_func)(const S &)) {
|
const std::vector<S, Alloc> &v, T (*const pack_func)(const S &)) {
|
||||||
return CreateVectorOfNativeStructs<T, S>(data(v), v.size(), pack_func);
|
return CreateVectorOfNativeStructs<T, S>(data(v), v.size(), pack_func);
|
||||||
@@ -871,7 +898,7 @@ class FlatBufferBuilder {
|
|||||||
/// serialize into the buffer as a `vector`.
|
/// serialize into the buffer as a `vector`.
|
||||||
/// @return Returns a typed `Offset` into the serialized data indicating
|
/// @return Returns a typed `Offset` into the serialized data indicating
|
||||||
/// where the vector is stored.
|
/// where the vector is stored.
|
||||||
template<typename T, typename S, typename Alloc>
|
template<typename T, typename S, typename Alloc = std::allocator<S>>
|
||||||
Offset<Vector<const T *>> CreateVectorOfNativeStructs(
|
Offset<Vector<const T *>> CreateVectorOfNativeStructs(
|
||||||
const std::vector<S, Alloc> &v) {
|
const std::vector<S, Alloc> &v) {
|
||||||
return CreateVectorOfNativeStructs<T, S>(data(v), v.size());
|
return CreateVectorOfNativeStructs<T, S>(data(v), v.size());
|
||||||
@@ -892,7 +919,7 @@ class FlatBufferBuilder {
|
|||||||
/// serialize into the buffer as a `vector`.
|
/// serialize into the buffer as a `vector`.
|
||||||
/// @return Returns a typed `Offset` into the serialized data indicating
|
/// @return Returns a typed `Offset` into the serialized data indicating
|
||||||
/// where the vector is stored.
|
/// where the vector is stored.
|
||||||
template<typename T, typename Alloc>
|
template<typename T, typename Alloc = std::allocator<T>>
|
||||||
Offset<Vector<const T *>> CreateVectorOfSortedStructs(
|
Offset<Vector<const T *>> CreateVectorOfSortedStructs(
|
||||||
std::vector<T, Alloc> *v) {
|
std::vector<T, Alloc> *v) {
|
||||||
return CreateVectorOfSortedStructs(data(*v), v->size());
|
return CreateVectorOfSortedStructs(data(*v), v->size());
|
||||||
@@ -906,7 +933,7 @@ class FlatBufferBuilder {
|
|||||||
/// serialize into the buffer as a `vector`.
|
/// serialize into the buffer as a `vector`.
|
||||||
/// @return Returns a typed `Offset` into the serialized data indicating
|
/// @return Returns a typed `Offset` into the serialized data indicating
|
||||||
/// where the vector is stored.
|
/// where the vector is stored.
|
||||||
template<typename T, typename S, typename Alloc>
|
template<typename T, typename S, typename Alloc = std::allocator<T>>
|
||||||
Offset<Vector<const T *>> CreateVectorOfSortedNativeStructs(
|
Offset<Vector<const T *>> CreateVectorOfSortedNativeStructs(
|
||||||
std::vector<S, Alloc> *v) {
|
std::vector<S, Alloc> *v) {
|
||||||
return CreateVectorOfSortedNativeStructs<T, S>(data(*v), v->size());
|
return CreateVectorOfSortedNativeStructs<T, S>(data(*v), v->size());
|
||||||
@@ -922,7 +949,7 @@ class FlatBufferBuilder {
|
|||||||
/// where the vector is stored.
|
/// where the vector is stored.
|
||||||
template<typename T>
|
template<typename T>
|
||||||
Offset<Vector<const T *>> CreateVectorOfSortedStructs(T *v, size_t len) {
|
Offset<Vector<const T *>> CreateVectorOfSortedStructs(T *v, size_t len) {
|
||||||
std::sort(v, v + len, StructKeyComparator<T>());
|
std::stable_sort(v, v + len, StructKeyComparator<T>());
|
||||||
return CreateVectorOfStructs(v, len);
|
return CreateVectorOfStructs(v, len);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -941,7 +968,7 @@ class FlatBufferBuilder {
|
|||||||
extern T Pack(const S &);
|
extern T Pack(const S &);
|
||||||
auto structs = StartVectorOfStructs<T>(len);
|
auto structs = StartVectorOfStructs<T>(len);
|
||||||
for (size_t i = 0; i < len; i++) { structs[i] = Pack(v[i]); }
|
for (size_t i = 0; i < len; i++) { structs[i] = Pack(v[i]); }
|
||||||
std::sort(structs, structs + len, StructKeyComparator<T>());
|
std::stable_sort(structs, structs + len, StructKeyComparator<T>());
|
||||||
return EndVectorOfStructs<T>(len);
|
return EndVectorOfStructs<T>(len);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -973,7 +1000,7 @@ class FlatBufferBuilder {
|
|||||||
template<typename T>
|
template<typename T>
|
||||||
Offset<Vector<Offset<T>>> CreateVectorOfSortedTables(Offset<T> *v,
|
Offset<Vector<Offset<T>>> CreateVectorOfSortedTables(Offset<T> *v,
|
||||||
size_t len) {
|
size_t len) {
|
||||||
std::sort(v, v + len, TableKeyComparator<T>(buf_));
|
std::stable_sort(v, v + len, TableKeyComparator<T>(buf_));
|
||||||
return CreateVector(v, len);
|
return CreateVector(v, len);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -984,7 +1011,7 @@ class FlatBufferBuilder {
|
|||||||
/// offsets to store in the buffer in sorted order.
|
/// offsets to store in the buffer in sorted order.
|
||||||
/// @return Returns a typed `Offset` into the serialized data indicating
|
/// @return Returns a typed `Offset` into the serialized data indicating
|
||||||
/// where the vector is stored.
|
/// where the vector is stored.
|
||||||
template<typename T, typename Alloc>
|
template<typename T, typename Alloc = std::allocator<T>>
|
||||||
Offset<Vector<Offset<T>>> CreateVectorOfSortedTables(
|
Offset<Vector<Offset<T>>> CreateVectorOfSortedTables(
|
||||||
std::vector<Offset<T>, Alloc> *v) {
|
std::vector<Offset<T>, Alloc> *v) {
|
||||||
return CreateVectorOfSortedTables(data(*v), v->size());
|
return CreateVectorOfSortedTables(data(*v), v->size());
|
||||||
@@ -1074,7 +1101,7 @@ class FlatBufferBuilder {
|
|||||||
void SwapBufAllocator(FlatBufferBuilder &other) {
|
void SwapBufAllocator(FlatBufferBuilder &other) {
|
||||||
buf_.swap_allocator(other.buf_);
|
buf_.swap_allocator(other.buf_);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// @brief The length of a FlatBuffer file header.
|
/// @brief The length of a FlatBuffer file header.
|
||||||
static const size_t kFileIdentifierLength =
|
static const size_t kFileIdentifierLength =
|
||||||
::flatbuffers::kFileIdentifierLength;
|
::flatbuffers::kFileIdentifierLength;
|
||||||
|
|||||||
@@ -226,27 +226,13 @@ struct TypeTable {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// String which identifies the current version of FlatBuffers.
|
// String which identifies the current version of FlatBuffers.
|
||||||
// flatbuffer_version_string is used by Google developers to identify which
|
inline const char *flatbuffers_version_string() {
|
||||||
// applications uploaded to Google Play are using this library. This allows
|
return "FlatBuffers " FLATBUFFERS_STRING(FLATBUFFERS_VERSION_MAJOR) "."
|
||||||
// the development team at Google to determine the popularity of the library.
|
FLATBUFFERS_STRING(FLATBUFFERS_VERSION_MINOR) "."
|
||||||
// How it works: Applications that are uploaded to the Google Play Store are
|
FLATBUFFERS_STRING(FLATBUFFERS_VERSION_REVISION);
|
||||||
// scanned for this version string. We track which applications are using it
|
}
|
||||||
// to measure popularity. You are free to remove it (of course) but we would
|
|
||||||
// appreciate if you left it in.
|
|
||||||
|
|
||||||
// Weak linkage is culled by VS & doesn't work on cygwin.
|
|
||||||
// clang-format off
|
// clang-format off
|
||||||
#if !defined(_WIN32) && !defined(__CYGWIN__)
|
|
||||||
|
|
||||||
extern volatile __attribute__((weak)) const char *flatbuffer_version_string;
|
|
||||||
volatile __attribute__((weak)) const char *flatbuffer_version_string =
|
|
||||||
"FlatBuffers "
|
|
||||||
FLATBUFFERS_STRING(FLATBUFFERS_VERSION_MAJOR) "."
|
|
||||||
FLATBUFFERS_STRING(FLATBUFFERS_VERSION_MINOR) "."
|
|
||||||
FLATBUFFERS_STRING(FLATBUFFERS_VERSION_REVISION);
|
|
||||||
|
|
||||||
#endif // !defined(_WIN32) && !defined(__CYGWIN__)
|
|
||||||
|
|
||||||
#define FLATBUFFERS_DEFINE_BITMASK_OPERATORS(E, T)\
|
#define FLATBUFFERS_DEFINE_BITMASK_OPERATORS(E, T)\
|
||||||
inline E operator | (E lhs, E rhs){\
|
inline E operator | (E lhs, E rhs){\
|
||||||
return E(T(lhs) | T(rhs));\
|
return E(T(lhs) | T(rhs));\
|
||||||
|
|||||||
@@ -31,6 +31,13 @@ namespace flatbuffers {
|
|||||||
extern void LogCompilerWarn(const std::string &warn);
|
extern void LogCompilerWarn(const std::string &warn);
|
||||||
extern void LogCompilerError(const std::string &err);
|
extern void LogCompilerError(const std::string &err);
|
||||||
|
|
||||||
|
struct FlatCOption {
|
||||||
|
std::string short_opt;
|
||||||
|
std::string long_opt;
|
||||||
|
std::string parameter;
|
||||||
|
std::string description;
|
||||||
|
};
|
||||||
|
|
||||||
class FlatCompiler {
|
class FlatCompiler {
|
||||||
public:
|
public:
|
||||||
// Output generator for the various programming languages and formats we
|
// Output generator for the various programming languages and formats we
|
||||||
@@ -42,17 +49,18 @@ class FlatCompiler {
|
|||||||
typedef std::string (*MakeRuleFn)(const flatbuffers::Parser &parser,
|
typedef std::string (*MakeRuleFn)(const flatbuffers::Parser &parser,
|
||||||
const std::string &path,
|
const std::string &path,
|
||||||
const std::string &file_name);
|
const std::string &file_name);
|
||||||
|
typedef bool (*ParsingCompletedFn)(const flatbuffers::Parser &parser,
|
||||||
|
const std::string &output_path);
|
||||||
|
|
||||||
GenerateFn generate;
|
GenerateFn generate;
|
||||||
const char *generator_opt_short;
|
|
||||||
const char *generator_opt_long;
|
|
||||||
const char *lang_name;
|
const char *lang_name;
|
||||||
bool schema_only;
|
bool schema_only;
|
||||||
GenerateFn generateGRPC;
|
GenerateFn generateGRPC;
|
||||||
flatbuffers::IDLOptions::Language lang;
|
flatbuffers::IDLOptions::Language lang;
|
||||||
const char *generator_help;
|
FlatCOption option;
|
||||||
MakeRuleFn make_rule;
|
MakeRuleFn make_rule;
|
||||||
BfbsGenerator *bfbs_generator;
|
BfbsGenerator *bfbs_generator;
|
||||||
|
ParsingCompletedFn parsing_completed;
|
||||||
};
|
};
|
||||||
|
|
||||||
typedef void (*WarnFn)(const FlatCompiler *flatc, const std::string &warn,
|
typedef void (*WarnFn)(const FlatCompiler *flatc, const std::string &warn,
|
||||||
@@ -79,6 +87,7 @@ class FlatCompiler {
|
|||||||
|
|
||||||
int Compile(int argc, const char **argv);
|
int Compile(int argc, const char **argv);
|
||||||
|
|
||||||
|
std::string GetShortUsageString(const char *program_name) const;
|
||||||
std::string GetUsageString(const char *program_name) const;
|
std::string GetUsageString(const char *program_name) const;
|
||||||
|
|
||||||
private:
|
private:
|
||||||
@@ -94,6 +103,11 @@ class FlatCompiler {
|
|||||||
void Error(const std::string &err, bool usage = true,
|
void Error(const std::string &err, bool usage = true,
|
||||||
bool show_exe_name = true) const;
|
bool show_exe_name = true) const;
|
||||||
|
|
||||||
|
void AnnotateBinaries(const uint8_t *binary_schema,
|
||||||
|
uint64_t binary_schema_size,
|
||||||
|
const std::string & schema_filename,
|
||||||
|
const std::vector<std::string> &binary_files);
|
||||||
|
|
||||||
InitParams params_;
|
InitParams params_;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
36
include/flatbuffers/flex_flat_util.h
Normal file
36
include/flatbuffers/flex_flat_util.h
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2022 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.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef FLATBUFFERS_FLEX_FLAT_UTIL_H_
|
||||||
|
#define FLATBUFFERS_FLEX_FLAT_UTIL_H_
|
||||||
|
|
||||||
|
#include "flatbuffers/flatbuffers.h"
|
||||||
|
#include "flatbuffers/flexbuffers.h"
|
||||||
|
|
||||||
|
namespace flexbuffers {
|
||||||
|
|
||||||
|
// Verifies the `nested` flexbuffer within a flatbuffer vector is valid.
|
||||||
|
inline bool VerifyNestedFlexBuffer(
|
||||||
|
const flatbuffers::Vector<uint8_t> *const nested,
|
||||||
|
flatbuffers::Verifier &verifier) {
|
||||||
|
if (!nested) return true;
|
||||||
|
return verifier.Check(flexbuffers::VerifyBuffer(
|
||||||
|
nested->data(), nested->size(), verifier.GetFlexReuseTracker()));
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace flexbuffers
|
||||||
|
|
||||||
|
#endif // FLATBUFFERS_FLEX_FLAT_UTIL_H_
|
||||||
@@ -53,7 +53,7 @@ enum Type {
|
|||||||
FBT_INT = 1,
|
FBT_INT = 1,
|
||||||
FBT_UINT = 2,
|
FBT_UINT = 2,
|
||||||
FBT_FLOAT = 3,
|
FBT_FLOAT = 3,
|
||||||
// Types above stored inline, types below store an offset.
|
// Types above stored inline, types below (except FBT_BOOL) store an offset.
|
||||||
FBT_KEY = 4,
|
FBT_KEY = 4,
|
||||||
FBT_STRING = 5,
|
FBT_STRING = 5,
|
||||||
FBT_INDIRECT_INT = 6,
|
FBT_INDIRECT_INT = 6,
|
||||||
@@ -81,6 +81,8 @@ enum Type {
|
|||||||
FBT_BOOL = 26,
|
FBT_BOOL = 26,
|
||||||
FBT_VECTOR_BOOL =
|
FBT_VECTOR_BOOL =
|
||||||
36, // To Allow the same type of conversion of type to vector type
|
36, // To Allow the same type of conversion of type to vector type
|
||||||
|
|
||||||
|
FBT_MAX_TYPE = 37
|
||||||
};
|
};
|
||||||
|
|
||||||
inline bool IsInline(Type t) { return t <= FBT_FLOAT || t == FBT_BOOL; }
|
inline bool IsInline(Type t) { return t <= FBT_FLOAT || t == FBT_BOOL; }
|
||||||
@@ -154,6 +156,7 @@ inline uint64_t ReadUInt64(const uint8_t *data, uint8_t byte_width) {
|
|||||||
// TODO: GCC apparently replaces memcpy by a rep movsb, but only if count is a
|
// TODO: GCC apparently replaces memcpy by a rep movsb, but only if count is a
|
||||||
// constant, which here it isn't. Test if memcpy is still faster than
|
// constant, which here it isn't. Test if memcpy is still faster than
|
||||||
// the conditionals in ReadSizedScalar. Can also use inline asm.
|
// the conditionals in ReadSizedScalar. Can also use inline asm.
|
||||||
|
|
||||||
// clang-format off
|
// clang-format off
|
||||||
#if defined(_MSC_VER) && defined(_M_X64) && !defined(_M_ARM64EC)
|
#if defined(_MSC_VER) && defined(_M_X64) && !defined(_M_ARM64EC)
|
||||||
// This is 64-bit Windows only, __movsb does not work on 32-bit Windows.
|
// This is 64-bit Windows only, __movsb does not work on 32-bit Windows.
|
||||||
@@ -369,10 +372,7 @@ void AppendToString(std::string &s, T &&v, bool keys_quoted) {
|
|||||||
class Reference {
|
class Reference {
|
||||||
public:
|
public:
|
||||||
Reference()
|
Reference()
|
||||||
: data_(nullptr),
|
: data_(nullptr), parent_width_(0), byte_width_(0), type_(FBT_NULL) {}
|
||||||
parent_width_(0),
|
|
||||||
byte_width_(BIT_WIDTH_8),
|
|
||||||
type_(FBT_NULL) {}
|
|
||||||
|
|
||||||
Reference(const uint8_t *data, uint8_t parent_width, uint8_t byte_width,
|
Reference(const uint8_t *data, uint8_t parent_width, uint8_t byte_width,
|
||||||
Type type)
|
Type type)
|
||||||
@@ -573,7 +573,23 @@ class Reference {
|
|||||||
auto keys = m.Keys();
|
auto keys = m.Keys();
|
||||||
auto vals = m.Values();
|
auto vals = m.Values();
|
||||||
for (size_t i = 0; i < keys.size(); i++) {
|
for (size_t i = 0; i < keys.size(); i++) {
|
||||||
keys[i].ToString(true, keys_quoted, s);
|
bool kq = keys_quoted;
|
||||||
|
if (!kq) {
|
||||||
|
// FlexBuffers keys may contain arbitrary characters, only allow
|
||||||
|
// unquoted if it looks like an "identifier":
|
||||||
|
const char *p = keys[i].AsKey();
|
||||||
|
if (!flatbuffers::is_alpha(*p) && *p != '_') {
|
||||||
|
kq = true;
|
||||||
|
} else {
|
||||||
|
while (*++p) {
|
||||||
|
if (!flatbuffers::is_alnum(*p) && *p != '_') {
|
||||||
|
kq = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
keys[i].ToString(true, kq, s);
|
||||||
s += ": ";
|
s += ": ";
|
||||||
vals[i].ToString(true, keys_quoted, s);
|
vals[i].ToString(true, keys_quoted, s);
|
||||||
if (i < keys.size() - 1) s += ", ";
|
if (i < keys.size() - 1) s += ", ";
|
||||||
@@ -757,6 +773,8 @@ class Reference {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
friend class Verifier;
|
||||||
|
|
||||||
const uint8_t *data_;
|
const uint8_t *data_;
|
||||||
uint8_t parent_width_;
|
uint8_t parent_width_;
|
||||||
uint8_t byte_width_;
|
uint8_t byte_width_;
|
||||||
@@ -1405,10 +1423,12 @@ class Builder FLATBUFFERS_FINAL_CLASS {
|
|||||||
|
|
||||||
template<typename T> static Type GetScalarType() {
|
template<typename T> static Type GetScalarType() {
|
||||||
static_assert(flatbuffers::is_scalar<T>::value, "Unrelated types");
|
static_assert(flatbuffers::is_scalar<T>::value, "Unrelated types");
|
||||||
return flatbuffers::is_floating_point<T>::value ? FBT_FLOAT
|
return flatbuffers::is_floating_point<T>::value
|
||||||
: flatbuffers::is_same<T, bool>::value
|
? FBT_FLOAT
|
||||||
? FBT_BOOL
|
: flatbuffers::is_same<T, bool>::value
|
||||||
: (flatbuffers::is_unsigned<T>::value ? FBT_UINT : FBT_INT);
|
? FBT_BOOL
|
||||||
|
: (flatbuffers::is_unsigned<T>::value ? FBT_UINT
|
||||||
|
: FBT_INT);
|
||||||
}
|
}
|
||||||
|
|
||||||
public:
|
public:
|
||||||
@@ -1558,9 +1578,9 @@ class Builder FLATBUFFERS_FINAL_CLASS {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// If you get this assert, your fixed types are not one of:
|
// If you get this assert, your typed types are not one of:
|
||||||
// Int / UInt / Float / Key.
|
// Int / UInt / Float / Key.
|
||||||
FLATBUFFERS_ASSERT(!fixed || IsTypedVectorElementType(vector_type));
|
FLATBUFFERS_ASSERT(!typed || IsTypedVectorElementType(vector_type));
|
||||||
auto byte_width = Align(bit_width);
|
auto byte_width = Align(bit_width);
|
||||||
// Write vector. First the keys width/offset if available, and size.
|
// Write vector. First the keys width/offset if available, and size.
|
||||||
if (keys) {
|
if (keys) {
|
||||||
@@ -1615,9 +1635,10 @@ class Builder FLATBUFFERS_FINAL_CLASS {
|
|||||||
explicit StringOffsetCompare(const std::vector<uint8_t> &buf)
|
explicit StringOffsetCompare(const std::vector<uint8_t> &buf)
|
||||||
: buf_(&buf) {}
|
: buf_(&buf) {}
|
||||||
bool operator()(const StringOffset &a, const StringOffset &b) const {
|
bool operator()(const StringOffset &a, const StringOffset &b) const {
|
||||||
auto stra = reinterpret_cast<const char *>(buf_->data() + a.first);
|
auto stra = buf_->data() + a.first;
|
||||||
auto strb = reinterpret_cast<const char *>(buf_->data() + b.first);
|
auto strb = buf_->data() + b.first;
|
||||||
return strncmp(stra, strb, (std::min)(a.second, b.second) + 1) < 0;
|
auto cr = memcmp(stra, strb, (std::min)(a.second, b.second) + 1);
|
||||||
|
return cr < 0 || (cr == 0 && a.second < b.second);
|
||||||
}
|
}
|
||||||
const std::vector<uint8_t> *buf_;
|
const std::vector<uint8_t> *buf_;
|
||||||
};
|
};
|
||||||
@@ -1627,8 +1648,237 @@ class Builder FLATBUFFERS_FINAL_CLASS {
|
|||||||
|
|
||||||
KeyOffsetMap key_pool;
|
KeyOffsetMap key_pool;
|
||||||
StringOffsetMap string_pool;
|
StringOffsetMap string_pool;
|
||||||
|
|
||||||
|
friend class Verifier;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Helper class to verify the integrity of a FlexBuffer
|
||||||
|
class Verifier FLATBUFFERS_FINAL_CLASS {
|
||||||
|
public:
|
||||||
|
Verifier(const uint8_t *buf, size_t buf_len,
|
||||||
|
// Supplying this vector likely results in faster verification
|
||||||
|
// of larger buffers with many shared keys/strings, but
|
||||||
|
// comes at the cost of using additional memory the same size of
|
||||||
|
// the buffer being verified, so it is by default off.
|
||||||
|
std::vector<uint8_t> *reuse_tracker = nullptr,
|
||||||
|
bool _check_alignment = true, size_t max_depth = 64)
|
||||||
|
: buf_(buf),
|
||||||
|
size_(buf_len),
|
||||||
|
depth_(0),
|
||||||
|
max_depth_(max_depth),
|
||||||
|
num_vectors_(0),
|
||||||
|
max_vectors_(buf_len),
|
||||||
|
check_alignment_(_check_alignment),
|
||||||
|
reuse_tracker_(reuse_tracker) {
|
||||||
|
FLATBUFFERS_ASSERT(size_ < FLATBUFFERS_MAX_BUFFER_SIZE);
|
||||||
|
if (reuse_tracker_) {
|
||||||
|
reuse_tracker_->clear();
|
||||||
|
reuse_tracker_->resize(size_, PackedType(BIT_WIDTH_8, FBT_NULL));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
// Central location where any verification failures register.
|
||||||
|
bool Check(bool ok) const {
|
||||||
|
// clang-format off
|
||||||
|
#ifdef FLATBUFFERS_DEBUG_VERIFICATION_FAILURE
|
||||||
|
FLATBUFFERS_ASSERT(ok);
|
||||||
|
#endif
|
||||||
|
// clang-format on
|
||||||
|
return ok;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify any range within the buffer.
|
||||||
|
bool VerifyFrom(size_t elem, size_t elem_len) const {
|
||||||
|
return Check(elem_len < size_ && elem <= size_ - elem_len);
|
||||||
|
}
|
||||||
|
bool VerifyBefore(size_t elem, size_t elem_len) const {
|
||||||
|
return Check(elem_len <= elem);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool VerifyFromPointer(const uint8_t *p, size_t len) {
|
||||||
|
auto o = static_cast<size_t>(p - buf_);
|
||||||
|
return VerifyFrom(o, len);
|
||||||
|
}
|
||||||
|
bool VerifyBeforePointer(const uint8_t *p, size_t len) {
|
||||||
|
auto o = static_cast<size_t>(p - buf_);
|
||||||
|
return VerifyBefore(o, len);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool VerifyByteWidth(size_t width) {
|
||||||
|
return Check(width == 1 || width == 2 || width == 4 || width == 8);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool VerifyType(int type) { return Check(type >= 0 && type < FBT_MAX_TYPE); }
|
||||||
|
|
||||||
|
bool VerifyOffset(uint64_t off, const uint8_t *p) {
|
||||||
|
return Check(off <= static_cast<uint64_t>(size_)) &&
|
||||||
|
off <= static_cast<uint64_t>(p - buf_);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool VerifyAlignment(const uint8_t *p, size_t size) const {
|
||||||
|
auto o = static_cast<size_t>(p - buf_);
|
||||||
|
return Check((o & (size - 1)) == 0 || !check_alignment_);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Macro, since we want to escape from parent function & use lazy args.
|
||||||
|
#define FLEX_CHECK_VERIFIED(P, PACKED_TYPE) \
|
||||||
|
if (reuse_tracker_) { \
|
||||||
|
auto packed_type = PACKED_TYPE; \
|
||||||
|
auto existing = (*reuse_tracker_)[P - buf_]; \
|
||||||
|
if (existing == packed_type) return true; \
|
||||||
|
/* Fail verification if already set with different type! */ \
|
||||||
|
if (!Check(existing == 0)) return false; \
|
||||||
|
(*reuse_tracker_)[P - buf_] = packed_type; \
|
||||||
|
}
|
||||||
|
|
||||||
|
bool VerifyVector(Reference r, const uint8_t *p, Type elem_type) {
|
||||||
|
// Any kind of nesting goes thru this function, so guard against that
|
||||||
|
// here, both with simple nesting checks, and the reuse tracker if on.
|
||||||
|
depth_++;
|
||||||
|
num_vectors_++;
|
||||||
|
if (!Check(depth_ <= max_depth_ && num_vectors_ <= max_vectors_))
|
||||||
|
return false;
|
||||||
|
auto size_byte_width = r.byte_width_;
|
||||||
|
if (!VerifyBeforePointer(p, size_byte_width)) return false;
|
||||||
|
FLEX_CHECK_VERIFIED(p - size_byte_width,
|
||||||
|
PackedType(Builder::WidthB(size_byte_width), r.type_));
|
||||||
|
auto sized = Sized(p, size_byte_width);
|
||||||
|
auto num_elems = sized.size();
|
||||||
|
auto elem_byte_width = r.type_ == FBT_STRING || r.type_ == FBT_BLOB
|
||||||
|
? uint8_t(1)
|
||||||
|
: r.byte_width_;
|
||||||
|
auto max_elems = SIZE_MAX / elem_byte_width;
|
||||||
|
if (!Check(num_elems < max_elems))
|
||||||
|
return false; // Protect against byte_size overflowing.
|
||||||
|
auto byte_size = num_elems * elem_byte_width;
|
||||||
|
if (!VerifyFromPointer(p, byte_size)) return false;
|
||||||
|
if (elem_type == FBT_NULL) {
|
||||||
|
// Verify type bytes after the vector.
|
||||||
|
if (!VerifyFromPointer(p + byte_size, num_elems)) return false;
|
||||||
|
auto v = Vector(p, size_byte_width);
|
||||||
|
for (size_t i = 0; i < num_elems; i++)
|
||||||
|
if (!VerifyRef(v[i])) return false;
|
||||||
|
} else if (elem_type == FBT_KEY) {
|
||||||
|
auto v = TypedVector(p, elem_byte_width, FBT_KEY);
|
||||||
|
for (size_t i = 0; i < num_elems; i++)
|
||||||
|
if (!VerifyRef(v[i])) return false;
|
||||||
|
} else {
|
||||||
|
FLATBUFFERS_ASSERT(IsInline(elem_type));
|
||||||
|
}
|
||||||
|
depth_--;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool VerifyKeys(const uint8_t *p, uint8_t byte_width) {
|
||||||
|
// The vector part of the map has already been verified.
|
||||||
|
const size_t num_prefixed_fields = 3;
|
||||||
|
if (!VerifyBeforePointer(p, byte_width * num_prefixed_fields)) return false;
|
||||||
|
p -= byte_width * num_prefixed_fields;
|
||||||
|
auto off = ReadUInt64(p, byte_width);
|
||||||
|
if (!VerifyOffset(off, p)) return false;
|
||||||
|
auto key_byte_with =
|
||||||
|
static_cast<uint8_t>(ReadUInt64(p + byte_width, byte_width));
|
||||||
|
if (!VerifyByteWidth(key_byte_with)) return false;
|
||||||
|
return VerifyVector(Reference(p, byte_width, key_byte_with, FBT_VECTOR_KEY),
|
||||||
|
p - off, FBT_KEY);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool VerifyKey(const uint8_t *p) {
|
||||||
|
FLEX_CHECK_VERIFIED(p, PackedType(BIT_WIDTH_8, FBT_KEY));
|
||||||
|
while (p < buf_ + size_)
|
||||||
|
if (*p++) return true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
#undef FLEX_CHECK_VERIFIED
|
||||||
|
|
||||||
|
bool VerifyTerminator(const String &s) {
|
||||||
|
return VerifyFromPointer(reinterpret_cast<const uint8_t *>(s.c_str()),
|
||||||
|
s.size() + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool VerifyRef(Reference r) {
|
||||||
|
// r.parent_width_ and r.data_ already verified.
|
||||||
|
if (!VerifyByteWidth(r.byte_width_) || !VerifyType(r.type_)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (IsInline(r.type_)) {
|
||||||
|
// Inline scalars, don't require further verification.
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
// All remaining types are an offset.
|
||||||
|
auto off = ReadUInt64(r.data_, r.parent_width_);
|
||||||
|
if (!VerifyOffset(off, r.data_)) return false;
|
||||||
|
auto p = r.Indirect();
|
||||||
|
if (!VerifyAlignment(p, r.byte_width_)) return false;
|
||||||
|
switch (r.type_) {
|
||||||
|
case FBT_INDIRECT_INT:
|
||||||
|
case FBT_INDIRECT_UINT:
|
||||||
|
case FBT_INDIRECT_FLOAT: return VerifyFromPointer(p, r.byte_width_);
|
||||||
|
case FBT_KEY: return VerifyKey(p);
|
||||||
|
case FBT_MAP:
|
||||||
|
return VerifyVector(r, p, FBT_NULL) && VerifyKeys(p, r.byte_width_);
|
||||||
|
case FBT_VECTOR: return VerifyVector(r, p, FBT_NULL);
|
||||||
|
case FBT_VECTOR_INT: return VerifyVector(r, p, FBT_INT);
|
||||||
|
case FBT_VECTOR_BOOL:
|
||||||
|
case FBT_VECTOR_UINT: return VerifyVector(r, p, FBT_UINT);
|
||||||
|
case FBT_VECTOR_FLOAT: return VerifyVector(r, p, FBT_FLOAT);
|
||||||
|
case FBT_VECTOR_KEY: return VerifyVector(r, p, FBT_KEY);
|
||||||
|
case FBT_VECTOR_STRING_DEPRECATED:
|
||||||
|
// Use of FBT_KEY here intentional, see elsewhere.
|
||||||
|
return VerifyVector(r, p, FBT_KEY);
|
||||||
|
case FBT_BLOB: return VerifyVector(r, p, FBT_UINT);
|
||||||
|
case FBT_STRING:
|
||||||
|
return VerifyVector(r, p, FBT_UINT) &&
|
||||||
|
VerifyTerminator(String(p, r.byte_width_));
|
||||||
|
case FBT_VECTOR_INT2:
|
||||||
|
case FBT_VECTOR_UINT2:
|
||||||
|
case FBT_VECTOR_FLOAT2:
|
||||||
|
case FBT_VECTOR_INT3:
|
||||||
|
case FBT_VECTOR_UINT3:
|
||||||
|
case FBT_VECTOR_FLOAT3:
|
||||||
|
case FBT_VECTOR_INT4:
|
||||||
|
case FBT_VECTOR_UINT4:
|
||||||
|
case FBT_VECTOR_FLOAT4: {
|
||||||
|
uint8_t len = 0;
|
||||||
|
auto vtype = ToFixedTypedVectorElementType(r.type_, &len);
|
||||||
|
if (!VerifyType(vtype)) return false;
|
||||||
|
return VerifyFromPointer(p, r.byte_width_ * len);
|
||||||
|
}
|
||||||
|
default: return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public:
|
||||||
|
bool VerifyBuffer() {
|
||||||
|
if (!Check(size_ >= 3)) return false;
|
||||||
|
auto end = buf_ + size_;
|
||||||
|
auto byte_width = *--end;
|
||||||
|
auto packed_type = *--end;
|
||||||
|
return VerifyByteWidth(byte_width) && Check(end - buf_ >= byte_width) &&
|
||||||
|
VerifyRef(Reference(end - byte_width, byte_width, packed_type));
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
const uint8_t *buf_;
|
||||||
|
size_t size_;
|
||||||
|
size_t depth_;
|
||||||
|
const size_t max_depth_;
|
||||||
|
size_t num_vectors_;
|
||||||
|
const size_t max_vectors_;
|
||||||
|
bool check_alignment_;
|
||||||
|
std::vector<uint8_t> *reuse_tracker_;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Utility function that constructs the Verifier for you, see above for
|
||||||
|
// parameters.
|
||||||
|
inline bool VerifyBuffer(const uint8_t *buf, size_t buf_len,
|
||||||
|
std::vector<uint8_t> *reuse_tracker = nullptr) {
|
||||||
|
Verifier verifier(buf, buf_len, reuse_tracker);
|
||||||
|
return verifier.VerifyBuffer();
|
||||||
|
}
|
||||||
|
|
||||||
} // namespace flexbuffers
|
} // namespace flexbuffers
|
||||||
|
|
||||||
#if defined(_MSC_VER)
|
#if defined(_MSC_VER)
|
||||||
|
|||||||
@@ -72,8 +72,8 @@ namespace flatbuffers {
|
|||||||
// - Go type.
|
// - Go type.
|
||||||
// - C# / .Net type.
|
// - C# / .Net type.
|
||||||
// - Python type.
|
// - Python type.
|
||||||
// - Rust type.
|
|
||||||
// - Kotlin type.
|
// - Kotlin type.
|
||||||
|
// - Rust type.
|
||||||
|
|
||||||
// using these macros, we can now write code dealing with types just once, e.g.
|
// using these macros, we can now write code dealing with types just once, e.g.
|
||||||
|
|
||||||
@@ -164,7 +164,7 @@ struct Type {
|
|||||||
enum_def(_ed),
|
enum_def(_ed),
|
||||||
fixed_length(_fixed_length) {}
|
fixed_length(_fixed_length) {}
|
||||||
|
|
||||||
bool operator==(const Type &o) {
|
bool operator==(const Type &o) const {
|
||||||
return base_type == o.base_type && element == o.element &&
|
return base_type == o.base_type && element == o.element &&
|
||||||
struct_def == o.struct_def && enum_def == o.enum_def;
|
struct_def == o.struct_def && enum_def == o.enum_def;
|
||||||
}
|
}
|
||||||
@@ -295,7 +295,7 @@ struct FieldDef : public Definition {
|
|||||||
native_inline(false),
|
native_inline(false),
|
||||||
flexbuffer(false),
|
flexbuffer(false),
|
||||||
presence(kDefault),
|
presence(kDefault),
|
||||||
nested_flatbuffer(NULL),
|
nested_flatbuffer(nullptr),
|
||||||
padding(0) {}
|
padding(0) {}
|
||||||
|
|
||||||
Offset<reflection::Field> Serialize(FlatBufferBuilder *builder, uint16_t id,
|
Offset<reflection::Field> Serialize(FlatBufferBuilder *builder, uint16_t id,
|
||||||
@@ -464,14 +464,30 @@ inline bool IsStruct(const Type &type) {
|
|||||||
return type.base_type == BASE_TYPE_STRUCT && type.struct_def->fixed;
|
return type.base_type == BASE_TYPE_STRUCT && type.struct_def->fixed;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
inline bool IsTable(const Type &type) {
|
||||||
|
return type.base_type == BASE_TYPE_STRUCT && !type.struct_def->fixed;
|
||||||
|
}
|
||||||
|
|
||||||
inline bool IsUnion(const Type &type) {
|
inline bool IsUnion(const Type &type) {
|
||||||
return type.enum_def != nullptr && type.enum_def->is_union;
|
return type.enum_def != nullptr && type.enum_def->is_union;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
inline bool IsUnionType(const Type &type) {
|
||||||
|
return IsUnion(type) && IsInteger(type.base_type);
|
||||||
|
}
|
||||||
|
|
||||||
inline bool IsVector(const Type &type) {
|
inline bool IsVector(const Type &type) {
|
||||||
return type.base_type == BASE_TYPE_VECTOR;
|
return type.base_type == BASE_TYPE_VECTOR;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
inline bool IsVectorOfStruct(const Type& type) {
|
||||||
|
return IsVector(type) && IsStruct(type.VectorType());
|
||||||
|
}
|
||||||
|
|
||||||
|
inline bool IsVectorOfTable(const Type& type) {
|
||||||
|
return IsVector(type) && IsTable(type.VectorType());
|
||||||
|
}
|
||||||
|
|
||||||
inline bool IsArray(const Type &type) {
|
inline bool IsArray(const Type &type) {
|
||||||
return type.base_type == BASE_TYPE_ARRAY;
|
return type.base_type == BASE_TYPE_ARRAY;
|
||||||
}
|
}
|
||||||
@@ -533,6 +549,24 @@ struct ServiceDef : public Definition {
|
|||||||
SymbolTable<RPCCall> calls;
|
SymbolTable<RPCCall> calls;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
struct IncludedFile {
|
||||||
|
// The name of the schema file being included, as defined in the .fbs file.
|
||||||
|
// This includes the prefix (e.g., include "foo/bar/baz.fbs" would mean this
|
||||||
|
// value is "foo/bar/baz.fbs").
|
||||||
|
std::string schema_name;
|
||||||
|
|
||||||
|
// The filename of where the included file was found, after searching the
|
||||||
|
// relative paths plus any other paths included with `flatc -I ...`. Note,
|
||||||
|
// while this is sometimes the same as schema_name, it is not always, since it
|
||||||
|
// can be defined relative to where flatc was invoked.
|
||||||
|
std::string filename;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Since IncludedFile is contained within a std::set, need to provide ordering.
|
||||||
|
inline bool operator<(const IncludedFile &a, const IncludedFile &b) {
|
||||||
|
return a.filename < b.filename;
|
||||||
|
}
|
||||||
|
|
||||||
// Container of options that may apply to any of the source/text generators.
|
// Container of options that may apply to any of the source/text generators.
|
||||||
struct IDLOptions {
|
struct IDLOptions {
|
||||||
// field case style options for C++
|
// field case style options for C++
|
||||||
@@ -547,6 +581,7 @@ struct IDLOptions {
|
|||||||
bool output_enum_identifiers;
|
bool output_enum_identifiers;
|
||||||
bool prefixed_enums;
|
bool prefixed_enums;
|
||||||
bool scoped_enums;
|
bool scoped_enums;
|
||||||
|
bool swift_implementation_only;
|
||||||
bool include_dependence_headers;
|
bool include_dependence_headers;
|
||||||
bool mutable_buffer;
|
bool mutable_buffer;
|
||||||
bool one_file;
|
bool one_file;
|
||||||
@@ -572,7 +607,7 @@ struct IDLOptions {
|
|||||||
bool allow_non_utf8;
|
bool allow_non_utf8;
|
||||||
bool natural_utf8;
|
bool natural_utf8;
|
||||||
std::string include_prefix;
|
std::string include_prefix;
|
||||||
bool keep_include_path;
|
bool keep_prefix;
|
||||||
bool binary_schema_comments;
|
bool binary_schema_comments;
|
||||||
bool binary_schema_builtins;
|
bool binary_schema_builtins;
|
||||||
bool binary_schema_gen_embed;
|
bool binary_schema_gen_embed;
|
||||||
@@ -591,10 +626,14 @@ struct IDLOptions {
|
|||||||
std::string filename_suffix;
|
std::string filename_suffix;
|
||||||
std::string filename_extension;
|
std::string filename_extension;
|
||||||
bool no_warnings;
|
bool no_warnings;
|
||||||
|
bool warnings_as_errors;
|
||||||
std::string project_root;
|
std::string project_root;
|
||||||
bool cs_global_alias;
|
bool cs_global_alias;
|
||||||
bool json_nested_flatbuffers;
|
bool json_nested_flatbuffers;
|
||||||
bool json_nested_flexbuffers;
|
bool json_nested_flexbuffers;
|
||||||
|
bool json_nested_legacy_flatbuffers;
|
||||||
|
bool ts_flat_file;
|
||||||
|
bool no_leak_private_annotations;
|
||||||
|
|
||||||
// Possible options for the more general generator below.
|
// Possible options for the more general generator below.
|
||||||
enum Language {
|
enum Language {
|
||||||
@@ -624,6 +663,12 @@ struct IDLOptions {
|
|||||||
// If set, require all fields in a table to be explicitly numbered.
|
// If set, require all fields in a table to be explicitly numbered.
|
||||||
bool require_explicit_ids;
|
bool require_explicit_ids;
|
||||||
|
|
||||||
|
// If set, implement serde::Serialize for generated Rust types
|
||||||
|
bool rust_serialize;
|
||||||
|
|
||||||
|
// If set, generate rust types in individual files with a root module file.
|
||||||
|
bool rust_module_root_file;
|
||||||
|
|
||||||
// The corresponding language bit will be set if a language is included
|
// The corresponding language bit will be set if a language is included
|
||||||
// for code generation.
|
// for code generation.
|
||||||
unsigned long lang_to_generate;
|
unsigned long lang_to_generate;
|
||||||
@@ -645,6 +690,7 @@ struct IDLOptions {
|
|||||||
output_enum_identifiers(true),
|
output_enum_identifiers(true),
|
||||||
prefixed_enums(true),
|
prefixed_enums(true),
|
||||||
scoped_enums(false),
|
scoped_enums(false),
|
||||||
|
swift_implementation_only(false),
|
||||||
include_dependence_headers(true),
|
include_dependence_headers(true),
|
||||||
mutable_buffer(false),
|
mutable_buffer(false),
|
||||||
one_file(false),
|
one_file(false),
|
||||||
@@ -667,7 +713,7 @@ struct IDLOptions {
|
|||||||
union_value_namespacing(true),
|
union_value_namespacing(true),
|
||||||
allow_non_utf8(false),
|
allow_non_utf8(false),
|
||||||
natural_utf8(false),
|
natural_utf8(false),
|
||||||
keep_include_path(false),
|
keep_prefix(false),
|
||||||
binary_schema_comments(false),
|
binary_schema_comments(false),
|
||||||
binary_schema_builtins(false),
|
binary_schema_builtins(false),
|
||||||
binary_schema_gen_embed(false),
|
binary_schema_gen_embed(false),
|
||||||
@@ -680,12 +726,18 @@ struct IDLOptions {
|
|||||||
filename_suffix("_generated"),
|
filename_suffix("_generated"),
|
||||||
filename_extension(),
|
filename_extension(),
|
||||||
no_warnings(false),
|
no_warnings(false),
|
||||||
|
warnings_as_errors(false),
|
||||||
project_root(""),
|
project_root(""),
|
||||||
cs_global_alias(false),
|
cs_global_alias(false),
|
||||||
json_nested_flatbuffers(true),
|
json_nested_flatbuffers(true),
|
||||||
json_nested_flexbuffers(true),
|
json_nested_flexbuffers(true),
|
||||||
|
json_nested_legacy_flatbuffers(false),
|
||||||
|
ts_flat_file(false),
|
||||||
|
no_leak_private_annotations(false),
|
||||||
mini_reflect(IDLOptions::kNone),
|
mini_reflect(IDLOptions::kNone),
|
||||||
require_explicit_ids(false),
|
require_explicit_ids(false),
|
||||||
|
rust_serialize(false),
|
||||||
|
rust_module_root_file(false),
|
||||||
lang_to_generate(0),
|
lang_to_generate(0),
|
||||||
set_empty_strings_to_null(true),
|
set_empty_strings_to_null(true),
|
||||||
set_empty_vectors_to_null(true) {}
|
set_empty_vectors_to_null(true) {}
|
||||||
@@ -785,6 +837,7 @@ class Parser : public ParserState {
|
|||||||
root_struct_def_(nullptr),
|
root_struct_def_(nullptr),
|
||||||
opts(options),
|
opts(options),
|
||||||
uses_flexbuffers_(false),
|
uses_flexbuffers_(false),
|
||||||
|
has_warning_(false),
|
||||||
advanced_features_(0),
|
advanced_features_(0),
|
||||||
source_(nullptr),
|
source_(nullptr),
|
||||||
anonymous_counter_(0),
|
anonymous_counter_(0),
|
||||||
@@ -888,6 +941,11 @@ class Parser : public ParserState {
|
|||||||
// @param opts Options used to parce a schema and generate code.
|
// @param opts Options used to parce a schema and generate code.
|
||||||
static bool SupportsOptionalScalars(const flatbuffers::IDLOptions &opts);
|
static bool SupportsOptionalScalars(const flatbuffers::IDLOptions &opts);
|
||||||
|
|
||||||
|
// Get the set of included files that are directly referenced by the file
|
||||||
|
// being parsed. This does not include files that are transitively included by
|
||||||
|
// others includes.
|
||||||
|
std::vector<IncludedFile> GetIncludedFiles() const;
|
||||||
|
|
||||||
private:
|
private:
|
||||||
class ParseDepthGuard;
|
class ParseDepthGuard;
|
||||||
|
|
||||||
@@ -972,6 +1030,9 @@ class Parser : public ParserState {
|
|||||||
FLATBUFFERS_CHECKED_ERROR ParseRoot(const char *_source,
|
FLATBUFFERS_CHECKED_ERROR ParseRoot(const char *_source,
|
||||||
const char **include_paths,
|
const char **include_paths,
|
||||||
const char *source_filename);
|
const char *source_filename);
|
||||||
|
FLATBUFFERS_CHECKED_ERROR CheckPrivateLeak();
|
||||||
|
FLATBUFFERS_CHECKED_ERROR CheckPrivatelyLeakedFields(
|
||||||
|
const Definition &def, const Definition &value_type);
|
||||||
FLATBUFFERS_CHECKED_ERROR DoParse(const char *_source,
|
FLATBUFFERS_CHECKED_ERROR DoParse(const char *_source,
|
||||||
const char **include_paths,
|
const char **include_paths,
|
||||||
const char *source_filename,
|
const char *source_filename,
|
||||||
@@ -1012,21 +1073,22 @@ class Parser : public ParserState {
|
|||||||
std::string file_extension_;
|
std::string file_extension_;
|
||||||
|
|
||||||
std::map<uint64_t, std::string> included_files_;
|
std::map<uint64_t, std::string> included_files_;
|
||||||
std::map<std::string, std::set<std::string>> files_included_per_file_;
|
std::map<std::string, std::set<IncludedFile>> files_included_per_file_;
|
||||||
std::vector<std::string> native_included_files_;
|
std::vector<std::string> native_included_files_;
|
||||||
|
|
||||||
std::map<std::string, bool> known_attributes_;
|
std::map<std::string, bool> known_attributes_;
|
||||||
|
|
||||||
IDLOptions opts;
|
IDLOptions opts;
|
||||||
bool uses_flexbuffers_;
|
bool uses_flexbuffers_;
|
||||||
|
bool has_warning_;
|
||||||
|
|
||||||
uint64_t advanced_features_;
|
uint64_t advanced_features_;
|
||||||
|
|
||||||
|
std::string file_being_parsed_;
|
||||||
|
|
||||||
private:
|
private:
|
||||||
const char *source_;
|
const char *source_;
|
||||||
|
|
||||||
std::string file_being_parsed_;
|
|
||||||
|
|
||||||
std::vector<std::pair<Value, FieldDef *>> field_stack_;
|
std::vector<std::pair<Value, FieldDef *>> field_stack_;
|
||||||
|
|
||||||
// TODO(cneo): Refactor parser to use string_cache more often to save
|
// TODO(cneo): Refactor parser to use string_cache more often to save
|
||||||
@@ -1039,10 +1101,6 @@ class Parser : public ParserState {
|
|||||||
|
|
||||||
// Utility functions for multiple generators:
|
// Utility functions for multiple generators:
|
||||||
|
|
||||||
extern std::string MakeCamel(const std::string &in, bool first = true);
|
|
||||||
|
|
||||||
extern std::string MakeScreamingCamel(const std::string &in);
|
|
||||||
|
|
||||||
// Generate text (JSON) from a given FlatBuffer, and a given Parser
|
// Generate text (JSON) from a given FlatBuffer, and a given Parser
|
||||||
// object that has been populated with the corresponding schema.
|
// object that has been populated with the corresponding schema.
|
||||||
// If ident_step is 0, no indentation will be generated. Additionally,
|
// If ident_step is 0, no indentation will be generated. Additionally,
|
||||||
|
|||||||
@@ -88,13 +88,22 @@ inline size_t GetTypeSizeInline(reflection::BaseType base_type, int type_index,
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Get the root, regardless of what type it is.
|
// Get the root, regardless of what type it is.
|
||||||
inline Table *GetAnyRoot(uint8_t *flatbuf) {
|
inline Table *GetAnyRoot(uint8_t *const flatbuf) {
|
||||||
return GetMutableRoot<Table>(flatbuf);
|
return GetMutableRoot<Table>(flatbuf);
|
||||||
}
|
}
|
||||||
inline const Table *GetAnyRoot(const uint8_t *flatbuf) {
|
|
||||||
|
inline const Table *GetAnyRoot(const uint8_t *const flatbuf) {
|
||||||
return GetRoot<Table>(flatbuf);
|
return GetRoot<Table>(flatbuf);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
inline Table *GetAnySizePrefixedRoot(uint8_t *const flatbuf) {
|
||||||
|
return GetMutableSizePrefixedRoot<Table>(flatbuf);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline const Table *GetAnySizePrefixedRoot(const uint8_t *const flatbuf) {
|
||||||
|
return GetSizePrefixedRoot<Table>(flatbuf);
|
||||||
|
}
|
||||||
|
|
||||||
// Get a field's default, if you know it's an integer, and its exact type.
|
// Get a field's default, if you know it's an integer, and its exact type.
|
||||||
template<typename T> T GetFieldDefaultI(const reflection::Field &field) {
|
template<typename T> T GetFieldDefaultI(const reflection::Field &field) {
|
||||||
FLATBUFFERS_ASSERT(sizeof(T) == GetTypeSize(field.type()->base_type()));
|
FLATBUFFERS_ASSERT(sizeof(T) == GetTypeSize(field.type()->base_type()));
|
||||||
@@ -279,6 +288,12 @@ T *GetAnyFieldAddressOf(const Struct &st, const reflection::Field &field) {
|
|||||||
return reinterpret_cast<T *>(st.GetAddressOf(field.offset()));
|
return reinterpret_cast<T *>(st.GetAddressOf(field.offset()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Loop over all the fields of the provided `object` and call `func` on each one
|
||||||
|
// in increasing order by their field->id(). If `reverse` is true, `func` is
|
||||||
|
// called in descending order
|
||||||
|
void ForAllFields(const reflection::Object *object, bool reverse,
|
||||||
|
std::function<void(const reflection::Field *)> func);
|
||||||
|
|
||||||
// ------------------------- SETTERS -------------------------
|
// ------------------------- SETTERS -------------------------
|
||||||
|
|
||||||
// Set any scalar field, if you know its exact type.
|
// Set any scalar field, if you know its exact type.
|
||||||
@@ -497,6 +512,11 @@ bool Verify(const reflection::Schema &schema, const reflection::Object &root,
|
|||||||
const uint8_t *buf, size_t length, uoffset_t max_depth = 64,
|
const uint8_t *buf, size_t length, uoffset_t max_depth = 64,
|
||||||
uoffset_t max_tables = 1000000);
|
uoffset_t max_tables = 1000000);
|
||||||
|
|
||||||
|
bool VerifySizePrefixed(const reflection::Schema &schema,
|
||||||
|
const reflection::Object &root, const uint8_t *buf,
|
||||||
|
size_t length, uoffset_t max_depth = 64,
|
||||||
|
uoffset_t max_tables = 1000000);
|
||||||
|
|
||||||
} // namespace flatbuffers
|
} // namespace flatbuffers
|
||||||
|
|
||||||
#endif // FLATBUFFERS_REFLECTION_H_
|
#endif // FLATBUFFERS_REFLECTION_H_
|
||||||
|
|||||||
@@ -6,6 +6,13 @@
|
|||||||
|
|
||||||
#include "flatbuffers/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 == 8,
|
||||||
|
"Non-compatible flatbuffers version included");
|
||||||
|
|
||||||
namespace reflection {
|
namespace reflection {
|
||||||
|
|
||||||
struct Type;
|
struct Type;
|
||||||
@@ -188,12 +195,12 @@ struct Type FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
|
|||||||
}
|
}
|
||||||
bool Verify(flatbuffers::Verifier &verifier) const {
|
bool Verify(flatbuffers::Verifier &verifier) const {
|
||||||
return VerifyTableStart(verifier) &&
|
return VerifyTableStart(verifier) &&
|
||||||
VerifyField<int8_t>(verifier, VT_BASE_TYPE) &&
|
VerifyField<int8_t>(verifier, VT_BASE_TYPE, 1) &&
|
||||||
VerifyField<int8_t>(verifier, VT_ELEMENT) &&
|
VerifyField<int8_t>(verifier, VT_ELEMENT, 1) &&
|
||||||
VerifyField<int32_t>(verifier, VT_INDEX) &&
|
VerifyField<int32_t>(verifier, VT_INDEX, 4) &&
|
||||||
VerifyField<uint16_t>(verifier, VT_FIXED_LENGTH) &&
|
VerifyField<uint16_t>(verifier, VT_FIXED_LENGTH, 2) &&
|
||||||
VerifyField<uint32_t>(verifier, VT_BASE_SIZE) &&
|
VerifyField<uint32_t>(verifier, VT_BASE_SIZE, 4) &&
|
||||||
VerifyField<uint32_t>(verifier, VT_ELEMENT_SIZE) &&
|
VerifyField<uint32_t>(verifier, VT_ELEMENT_SIZE, 4) &&
|
||||||
verifier.EndTable();
|
verifier.EndTable();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -261,8 +268,8 @@ struct KeyValue FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
|
|||||||
bool KeyCompareLessThan(const KeyValue *o) const {
|
bool KeyCompareLessThan(const KeyValue *o) const {
|
||||||
return *key() < *o->key();
|
return *key() < *o->key();
|
||||||
}
|
}
|
||||||
int KeyCompareWithValue(const char *val) const {
|
int KeyCompareWithValue(const char *_key) const {
|
||||||
return strcmp(key()->c_str(), val);
|
return strcmp(key()->c_str(), _key);
|
||||||
}
|
}
|
||||||
const flatbuffers::String *value() const {
|
const flatbuffers::String *value() const {
|
||||||
return GetPointer<const flatbuffers::String *>(VT_VALUE);
|
return GetPointer<const flatbuffers::String *>(VT_VALUE);
|
||||||
@@ -338,8 +345,8 @@ struct EnumVal FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
|
|||||||
bool KeyCompareLessThan(const EnumVal *o) const {
|
bool KeyCompareLessThan(const EnumVal *o) const {
|
||||||
return value() < o->value();
|
return value() < o->value();
|
||||||
}
|
}
|
||||||
int KeyCompareWithValue(int64_t val) const {
|
int KeyCompareWithValue(int64_t _value) const {
|
||||||
return static_cast<int>(value() > val) - static_cast<int>(value() < val);
|
return static_cast<int>(value() > _value) - static_cast<int>(value() < _value);
|
||||||
}
|
}
|
||||||
const reflection::Type *union_type() const {
|
const reflection::Type *union_type() const {
|
||||||
return GetPointer<const reflection::Type *>(VT_UNION_TYPE);
|
return GetPointer<const reflection::Type *>(VT_UNION_TYPE);
|
||||||
@@ -351,7 +358,7 @@ struct EnumVal FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
|
|||||||
return VerifyTableStart(verifier) &&
|
return VerifyTableStart(verifier) &&
|
||||||
VerifyOffsetRequired(verifier, VT_NAME) &&
|
VerifyOffsetRequired(verifier, VT_NAME) &&
|
||||||
verifier.VerifyString(name()) &&
|
verifier.VerifyString(name()) &&
|
||||||
VerifyField<int64_t>(verifier, VT_VALUE) &&
|
VerifyField<int64_t>(verifier, VT_VALUE, 8) &&
|
||||||
VerifyOffset(verifier, VT_UNION_TYPE) &&
|
VerifyOffset(verifier, VT_UNION_TYPE) &&
|
||||||
verifier.VerifyTable(union_type()) &&
|
verifier.VerifyTable(union_type()) &&
|
||||||
VerifyOffset(verifier, VT_DOCUMENTATION) &&
|
VerifyOffset(verifier, VT_DOCUMENTATION) &&
|
||||||
@@ -436,8 +443,8 @@ struct Enum FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
|
|||||||
bool KeyCompareLessThan(const Enum *o) const {
|
bool KeyCompareLessThan(const Enum *o) const {
|
||||||
return *name() < *o->name();
|
return *name() < *o->name();
|
||||||
}
|
}
|
||||||
int KeyCompareWithValue(const char *val) const {
|
int KeyCompareWithValue(const char *_name) const {
|
||||||
return strcmp(name()->c_str(), val);
|
return strcmp(name()->c_str(), _name);
|
||||||
}
|
}
|
||||||
const flatbuffers::Vector<flatbuffers::Offset<reflection::EnumVal>> *values() const {
|
const flatbuffers::Vector<flatbuffers::Offset<reflection::EnumVal>> *values() const {
|
||||||
return GetPointer<const flatbuffers::Vector<flatbuffers::Offset<reflection::EnumVal>> *>(VT_VALUES);
|
return GetPointer<const flatbuffers::Vector<flatbuffers::Offset<reflection::EnumVal>> *>(VT_VALUES);
|
||||||
@@ -465,7 +472,7 @@ struct Enum FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
|
|||||||
VerifyOffsetRequired(verifier, VT_VALUES) &&
|
VerifyOffsetRequired(verifier, VT_VALUES) &&
|
||||||
verifier.VerifyVector(values()) &&
|
verifier.VerifyVector(values()) &&
|
||||||
verifier.VerifyVectorOfTables(values()) &&
|
verifier.VerifyVectorOfTables(values()) &&
|
||||||
VerifyField<uint8_t>(verifier, VT_IS_UNION) &&
|
VerifyField<uint8_t>(verifier, VT_IS_UNION, 1) &&
|
||||||
VerifyOffsetRequired(verifier, VT_UNDERLYING_TYPE) &&
|
VerifyOffsetRequired(verifier, VT_UNDERLYING_TYPE) &&
|
||||||
verifier.VerifyTable(underlying_type()) &&
|
verifier.VerifyTable(underlying_type()) &&
|
||||||
VerifyOffset(verifier, VT_ATTRIBUTES) &&
|
VerifyOffset(verifier, VT_ATTRIBUTES) &&
|
||||||
@@ -587,8 +594,8 @@ struct Field FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
|
|||||||
bool KeyCompareLessThan(const Field *o) const {
|
bool KeyCompareLessThan(const Field *o) const {
|
||||||
return *name() < *o->name();
|
return *name() < *o->name();
|
||||||
}
|
}
|
||||||
int KeyCompareWithValue(const char *val) const {
|
int KeyCompareWithValue(const char *_name) const {
|
||||||
return strcmp(name()->c_str(), val);
|
return strcmp(name()->c_str(), _name);
|
||||||
}
|
}
|
||||||
const reflection::Type *type() const {
|
const reflection::Type *type() const {
|
||||||
return GetPointer<const reflection::Type *>(VT_TYPE);
|
return GetPointer<const reflection::Type *>(VT_TYPE);
|
||||||
@@ -633,21 +640,21 @@ struct Field FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
|
|||||||
verifier.VerifyString(name()) &&
|
verifier.VerifyString(name()) &&
|
||||||
VerifyOffsetRequired(verifier, VT_TYPE) &&
|
VerifyOffsetRequired(verifier, VT_TYPE) &&
|
||||||
verifier.VerifyTable(type()) &&
|
verifier.VerifyTable(type()) &&
|
||||||
VerifyField<uint16_t>(verifier, VT_ID) &&
|
VerifyField<uint16_t>(verifier, VT_ID, 2) &&
|
||||||
VerifyField<uint16_t>(verifier, VT_OFFSET) &&
|
VerifyField<uint16_t>(verifier, VT_OFFSET, 2) &&
|
||||||
VerifyField<int64_t>(verifier, VT_DEFAULT_INTEGER) &&
|
VerifyField<int64_t>(verifier, VT_DEFAULT_INTEGER, 8) &&
|
||||||
VerifyField<double>(verifier, VT_DEFAULT_REAL) &&
|
VerifyField<double>(verifier, VT_DEFAULT_REAL, 8) &&
|
||||||
VerifyField<uint8_t>(verifier, VT_DEPRECATED) &&
|
VerifyField<uint8_t>(verifier, VT_DEPRECATED, 1) &&
|
||||||
VerifyField<uint8_t>(verifier, VT_REQUIRED) &&
|
VerifyField<uint8_t>(verifier, VT_REQUIRED, 1) &&
|
||||||
VerifyField<uint8_t>(verifier, VT_KEY) &&
|
VerifyField<uint8_t>(verifier, VT_KEY, 1) &&
|
||||||
VerifyOffset(verifier, VT_ATTRIBUTES) &&
|
VerifyOffset(verifier, VT_ATTRIBUTES) &&
|
||||||
verifier.VerifyVector(attributes()) &&
|
verifier.VerifyVector(attributes()) &&
|
||||||
verifier.VerifyVectorOfTables(attributes()) &&
|
verifier.VerifyVectorOfTables(attributes()) &&
|
||||||
VerifyOffset(verifier, VT_DOCUMENTATION) &&
|
VerifyOffset(verifier, VT_DOCUMENTATION) &&
|
||||||
verifier.VerifyVector(documentation()) &&
|
verifier.VerifyVector(documentation()) &&
|
||||||
verifier.VerifyVectorOfStrings(documentation()) &&
|
verifier.VerifyVectorOfStrings(documentation()) &&
|
||||||
VerifyField<uint8_t>(verifier, VT_OPTIONAL) &&
|
VerifyField<uint8_t>(verifier, VT_OPTIONAL, 1) &&
|
||||||
VerifyField<uint16_t>(verifier, VT_PADDING) &&
|
VerifyField<uint16_t>(verifier, VT_PADDING, 2) &&
|
||||||
verifier.EndTable();
|
verifier.EndTable();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -793,8 +800,8 @@ struct Object FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
|
|||||||
bool KeyCompareLessThan(const Object *o) const {
|
bool KeyCompareLessThan(const Object *o) const {
|
||||||
return *name() < *o->name();
|
return *name() < *o->name();
|
||||||
}
|
}
|
||||||
int KeyCompareWithValue(const char *val) const {
|
int KeyCompareWithValue(const char *_name) const {
|
||||||
return strcmp(name()->c_str(), val);
|
return strcmp(name()->c_str(), _name);
|
||||||
}
|
}
|
||||||
const flatbuffers::Vector<flatbuffers::Offset<reflection::Field>> *fields() const {
|
const flatbuffers::Vector<flatbuffers::Offset<reflection::Field>> *fields() const {
|
||||||
return GetPointer<const flatbuffers::Vector<flatbuffers::Offset<reflection::Field>> *>(VT_FIELDS);
|
return GetPointer<const flatbuffers::Vector<flatbuffers::Offset<reflection::Field>> *>(VT_FIELDS);
|
||||||
@@ -825,9 +832,9 @@ struct Object FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
|
|||||||
VerifyOffsetRequired(verifier, VT_FIELDS) &&
|
VerifyOffsetRequired(verifier, VT_FIELDS) &&
|
||||||
verifier.VerifyVector(fields()) &&
|
verifier.VerifyVector(fields()) &&
|
||||||
verifier.VerifyVectorOfTables(fields()) &&
|
verifier.VerifyVectorOfTables(fields()) &&
|
||||||
VerifyField<uint8_t>(verifier, VT_IS_STRUCT) &&
|
VerifyField<uint8_t>(verifier, VT_IS_STRUCT, 1) &&
|
||||||
VerifyField<int32_t>(verifier, VT_MINALIGN) &&
|
VerifyField<int32_t>(verifier, VT_MINALIGN, 4) &&
|
||||||
VerifyField<int32_t>(verifier, VT_BYTESIZE) &&
|
VerifyField<int32_t>(verifier, VT_BYTESIZE, 4) &&
|
||||||
VerifyOffset(verifier, VT_ATTRIBUTES) &&
|
VerifyOffset(verifier, VT_ATTRIBUTES) &&
|
||||||
verifier.VerifyVector(attributes()) &&
|
verifier.VerifyVector(attributes()) &&
|
||||||
verifier.VerifyVectorOfTables(attributes()) &&
|
verifier.VerifyVectorOfTables(attributes()) &&
|
||||||
@@ -945,8 +952,8 @@ struct RPCCall FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
|
|||||||
bool KeyCompareLessThan(const RPCCall *o) const {
|
bool KeyCompareLessThan(const RPCCall *o) const {
|
||||||
return *name() < *o->name();
|
return *name() < *o->name();
|
||||||
}
|
}
|
||||||
int KeyCompareWithValue(const char *val) const {
|
int KeyCompareWithValue(const char *_name) const {
|
||||||
return strcmp(name()->c_str(), val);
|
return strcmp(name()->c_str(), _name);
|
||||||
}
|
}
|
||||||
const reflection::Object *request() const {
|
const reflection::Object *request() const {
|
||||||
return GetPointer<const reflection::Object *>(VT_REQUEST);
|
return GetPointer<const reflection::Object *>(VT_REQUEST);
|
||||||
@@ -1061,8 +1068,8 @@ struct Service FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
|
|||||||
bool KeyCompareLessThan(const Service *o) const {
|
bool KeyCompareLessThan(const Service *o) const {
|
||||||
return *name() < *o->name();
|
return *name() < *o->name();
|
||||||
}
|
}
|
||||||
int KeyCompareWithValue(const char *val) const {
|
int KeyCompareWithValue(const char *_name) const {
|
||||||
return strcmp(name()->c_str(), val);
|
return strcmp(name()->c_str(), _name);
|
||||||
}
|
}
|
||||||
const flatbuffers::Vector<flatbuffers::Offset<reflection::RPCCall>> *calls() const {
|
const flatbuffers::Vector<flatbuffers::Offset<reflection::RPCCall>> *calls() const {
|
||||||
return GetPointer<const flatbuffers::Vector<flatbuffers::Offset<reflection::RPCCall>> *>(VT_CALLS);
|
return GetPointer<const flatbuffers::Vector<flatbuffers::Offset<reflection::RPCCall>> *>(VT_CALLS);
|
||||||
@@ -1180,8 +1187,8 @@ struct SchemaFile FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
|
|||||||
bool KeyCompareLessThan(const SchemaFile *o) const {
|
bool KeyCompareLessThan(const SchemaFile *o) const {
|
||||||
return *filename() < *o->filename();
|
return *filename() < *o->filename();
|
||||||
}
|
}
|
||||||
int KeyCompareWithValue(const char *val) const {
|
int KeyCompareWithValue(const char *_filename) const {
|
||||||
return strcmp(filename()->c_str(), val);
|
return strcmp(filename()->c_str(), _filename);
|
||||||
}
|
}
|
||||||
/// Names of included files, relative to project root.
|
/// Names of included files, relative to project root.
|
||||||
const flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>> *included_filenames() const {
|
const flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>> *included_filenames() const {
|
||||||
@@ -1297,7 +1304,7 @@ struct Schema FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
|
|||||||
VerifyOffset(verifier, VT_SERVICES) &&
|
VerifyOffset(verifier, VT_SERVICES) &&
|
||||||
verifier.VerifyVector(services()) &&
|
verifier.VerifyVector(services()) &&
|
||||||
verifier.VerifyVectorOfTables(services()) &&
|
verifier.VerifyVectorOfTables(services()) &&
|
||||||
VerifyField<uint64_t>(verifier, VT_ADVANCED_FEATURES) &&
|
VerifyField<uint64_t>(verifier, VT_ADVANCED_FEATURES, 8) &&
|
||||||
VerifyOffset(verifier, VT_FBS_FILES) &&
|
VerifyOffset(verifier, VT_FBS_FILES) &&
|
||||||
verifier.VerifyVector(fbs_files()) &&
|
verifier.VerifyVector(fbs_files()) &&
|
||||||
verifier.VerifyVectorOfTables(fbs_files()) &&
|
verifier.VerifyVectorOfTables(fbs_files()) &&
|
||||||
@@ -1413,6 +1420,11 @@ inline bool SchemaBufferHasIdentifier(const void *buf) {
|
|||||||
buf, SchemaIdentifier());
|
buf, SchemaIdentifier());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
inline bool SizePrefixedSchemaBufferHasIdentifier(const void *buf) {
|
||||||
|
return flatbuffers::BufferHasIdentifier(
|
||||||
|
buf, SchemaIdentifier(), true);
|
||||||
|
}
|
||||||
|
|
||||||
inline bool VerifySchemaBuffer(
|
inline bool VerifySchemaBuffer(
|
||||||
flatbuffers::Verifier &verifier) {
|
flatbuffers::Verifier &verifier) {
|
||||||
return verifier.VerifyBuffer<reflection::Schema>(SchemaIdentifier());
|
return verifier.VerifyBuffer<reflection::Schema>(SchemaIdentifier());
|
||||||
|
|||||||
@@ -26,22 +26,27 @@
|
|||||||
#include <memory>
|
#include <memory>
|
||||||
#include <limits>
|
#include <limits>
|
||||||
|
|
||||||
// Detect C++17 compatible compiler.
|
#ifndef FLATBUFFERS_USE_STD_OPTIONAL
|
||||||
// __cplusplus >= 201703L - a compiler has support of 'static inline' variables.
|
// Detect C++17 compatible compiler.
|
||||||
#if defined(FLATBUFFERS_USE_STD_OPTIONAL) \
|
// __cplusplus >= 201703L - a compiler has support of 'static inline' variables.
|
||||||
|| (defined(__cplusplus) && __cplusplus >= 201703L) \
|
#if (defined(__cplusplus) && __cplusplus >= 201703L) \
|
||||||
|| (defined(_MSVC_LANG) && (_MSVC_LANG >= 201703L))
|
|| (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L)
|
||||||
|
#define FLATBUFFERS_USE_STD_OPTIONAL 1
|
||||||
|
#else
|
||||||
|
#define FLATBUFFERS_USE_STD_OPTIONAL 0
|
||||||
|
#endif // (defined(__cplusplus) && __cplusplus >= 201703L) ...
|
||||||
|
#endif // FLATBUFFERS_USE_STD_OPTIONAL
|
||||||
|
|
||||||
|
#if FLATBUFFERS_USE_STD_OPTIONAL
|
||||||
#include <optional>
|
#include <optional>
|
||||||
#ifndef FLATBUFFERS_USE_STD_OPTIONAL
|
#endif
|
||||||
#define FLATBUFFERS_USE_STD_OPTIONAL
|
|
||||||
#endif
|
|
||||||
#endif // defined(FLATBUFFERS_USE_STD_OPTIONAL) ...
|
|
||||||
|
|
||||||
// The __cpp_lib_span is the predefined feature macro.
|
// The __cpp_lib_span is the predefined feature macro.
|
||||||
#if defined(FLATBUFFERS_USE_STD_SPAN)
|
#if defined(FLATBUFFERS_USE_STD_SPAN)
|
||||||
#include <span>
|
#include <span>
|
||||||
#elif defined(__cpp_lib_span) && defined(__has_include)
|
#elif defined(__cpp_lib_span) && defined(__has_include)
|
||||||
#if __has_include(<span>)
|
#if __has_include(<span>)
|
||||||
|
#include <array>
|
||||||
#include <span>
|
#include <span>
|
||||||
#define FLATBUFFERS_USE_STD_SPAN
|
#define FLATBUFFERS_USE_STD_SPAN
|
||||||
#endif
|
#endif
|
||||||
@@ -128,7 +133,7 @@ namespace flatbuffers {
|
|||||||
};
|
};
|
||||||
#endif // defined(FLATBUFFERS_TEMPLATES_ALIASES)
|
#endif // defined(FLATBUFFERS_TEMPLATES_ALIASES)
|
||||||
|
|
||||||
#ifdef FLATBUFFERS_USE_STD_OPTIONAL
|
#if FLATBUFFERS_USE_STD_OPTIONAL
|
||||||
template<class T>
|
template<class T>
|
||||||
using Optional = std::optional<T>;
|
using Optional = std::optional<T>;
|
||||||
using nullopt_t = std::nullopt_t;
|
using nullopt_t = std::nullopt_t;
|
||||||
@@ -284,13 +289,13 @@ FLATBUFFERS_CONSTEXPR std::size_t dynamic_extent = static_cast<std::size_t>(-1);
|
|||||||
namespace internal {
|
namespace internal {
|
||||||
// This is SFINAE helper class for checking of a common condition:
|
// This is SFINAE helper class for checking of a common condition:
|
||||||
// > This overload only participates in overload resolution
|
// > This overload only participates in overload resolution
|
||||||
// > Check whether a pointer to an array of U can be converted
|
// > Check whether a pointer to an array of From can be converted
|
||||||
// > to a pointer to an array of E.
|
// > to a pointer to an array of To.
|
||||||
// This helper is used for checking of 'U -> const U'.
|
// This helper is used for checking of 'From -> const From'.
|
||||||
template<class E, std::size_t Extent, class U, std::size_t N>
|
template<class To, std::size_t Extent, class From, std::size_t N>
|
||||||
struct is_span_convertable {
|
struct is_span_convertible {
|
||||||
using type =
|
using type =
|
||||||
typename std::conditional<std::is_convertible<U (*)[], E (*)[]>::value
|
typename std::conditional<std::is_convertible<From (*)[], To (*)[]>::value
|
||||||
&& (Extent == dynamic_extent || N == Extent),
|
&& (Extent == dynamic_extent || N == Extent),
|
||||||
int, void>::type;
|
int, void>::type;
|
||||||
};
|
};
|
||||||
@@ -362,13 +367,9 @@ class span FLATBUFFERS_FINAL_CLASS {
|
|||||||
|
|
||||||
#if !defined(FLATBUFFERS_SPAN_MINIMAL)
|
#if !defined(FLATBUFFERS_SPAN_MINIMAL)
|
||||||
using Iterator = internal::SpanIterator<T>;
|
using Iterator = internal::SpanIterator<T>;
|
||||||
using ConstIterator = internal::SpanIterator<const T>;
|
|
||||||
|
|
||||||
Iterator begin() const { return Iterator(data()); }
|
Iterator begin() const { return Iterator(data()); }
|
||||||
Iterator end() const { return Iterator(data() + size()); }
|
Iterator end() const { return Iterator(data() + size()); }
|
||||||
|
|
||||||
ConstIterator cbegin() const { return ConstIterator(data()); }
|
|
||||||
ConstIterator cend() const { return ConstIterator(data() + size()); }
|
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
// Returns a reference to the idx-th element of the sequence.
|
// Returns a reference to the idx-th element of the sequence.
|
||||||
@@ -414,7 +415,7 @@ class span FLATBUFFERS_FINAL_CLASS {
|
|||||||
// extent == 0 || extent == flatbuffers::dynamic_extent.
|
// extent == 0 || extent == flatbuffers::dynamic_extent.
|
||||||
// A dummy template argument N is need dependency for SFINAE.
|
// A dummy template argument N is need dependency for SFINAE.
|
||||||
template<std::size_t N = 0,
|
template<std::size_t N = 0,
|
||||||
typename internal::is_span_convertable<element_type, Extent, element_type, (N - N)>::type = 0>
|
typename internal::is_span_convertible<element_type, Extent, element_type, (N - N)>::type = 0>
|
||||||
FLATBUFFERS_CONSTEXPR_CPP11 span() FLATBUFFERS_NOEXCEPT : data_(nullptr),
|
FLATBUFFERS_CONSTEXPR_CPP11 span() FLATBUFFERS_NOEXCEPT : data_(nullptr),
|
||||||
count_(0) {
|
count_(0) {
|
||||||
static_assert(extent == 0 || extent == dynamic_extent, "invalid span");
|
static_assert(extent == 0 || extent == dynamic_extent, "invalid span");
|
||||||
@@ -427,12 +428,12 @@ class span FLATBUFFERS_FINAL_CLASS {
|
|||||||
// std::remove_pointer_t<decltype(std::data(arr))>(*)[]
|
// std::remove_pointer_t<decltype(std::data(arr))>(*)[]
|
||||||
// is convertible to element_type (*)[].
|
// is convertible to element_type (*)[].
|
||||||
template<std::size_t N,
|
template<std::size_t N,
|
||||||
typename internal::is_span_convertable<element_type, Extent, element_type, N>::type = 0>
|
typename internal::is_span_convertible<element_type, Extent, element_type, N>::type = 0>
|
||||||
FLATBUFFERS_CONSTEXPR_CPP11 span(element_type (&arr)[N]) FLATBUFFERS_NOEXCEPT
|
FLATBUFFERS_CONSTEXPR_CPP11 span(element_type (&arr)[N]) FLATBUFFERS_NOEXCEPT
|
||||||
: data_(arr), count_(N) {}
|
: data_(arr), count_(N) {}
|
||||||
|
|
||||||
template<class U, std::size_t N,
|
template<class U, std::size_t N,
|
||||||
typename internal::is_span_convertable<element_type, Extent, U, N>::type = 0>
|
typename internal::is_span_convertible<element_type, Extent, U, N>::type = 0>
|
||||||
FLATBUFFERS_CONSTEXPR_CPP11 span(std::array<U, N> &arr) FLATBUFFERS_NOEXCEPT
|
FLATBUFFERS_CONSTEXPR_CPP11 span(std::array<U, N> &arr) FLATBUFFERS_NOEXCEPT
|
||||||
: data_(arr.data()), count_(N) {}
|
: data_(arr.data()), count_(N) {}
|
||||||
|
|
||||||
@@ -442,7 +443,7 @@ class span FLATBUFFERS_FINAL_CLASS {
|
|||||||
// : data_(arr.data()), count_(N) {}
|
// : data_(arr.data()), count_(N) {}
|
||||||
|
|
||||||
template<class U, std::size_t N,
|
template<class U, std::size_t N,
|
||||||
typename internal::is_span_convertable<element_type, Extent, U, N>::type = 0>
|
typename internal::is_span_convertible<element_type, Extent, U, N>::type = 0>
|
||||||
FLATBUFFERS_CONSTEXPR_CPP11 span(const std::array<U, N> &arr) FLATBUFFERS_NOEXCEPT
|
FLATBUFFERS_CONSTEXPR_CPP11 span(const std::array<U, N> &arr) FLATBUFFERS_NOEXCEPT
|
||||||
: data_(arr.data()), count_(N) {}
|
: data_(arr.data()), count_(N) {}
|
||||||
|
|
||||||
@@ -452,7 +453,7 @@ class span FLATBUFFERS_FINAL_CLASS {
|
|||||||
// if extent == std::dynamic_extent || N == extent is true and U (*)[]
|
// if extent == std::dynamic_extent || N == extent is true and U (*)[]
|
||||||
// is convertible to element_type (*)[].
|
// is convertible to element_type (*)[].
|
||||||
template<class U, std::size_t N,
|
template<class U, std::size_t N,
|
||||||
typename internal::is_span_convertable<element_type, Extent, U, N>::type = 0>
|
typename internal::is_span_convertible<element_type, Extent, U, N>::type = 0>
|
||||||
FLATBUFFERS_CONSTEXPR_CPP11 span(const flatbuffers::span<U, N> &s) FLATBUFFERS_NOEXCEPT
|
FLATBUFFERS_CONSTEXPR_CPP11 span(const flatbuffers::span<U, N> &s) FLATBUFFERS_NOEXCEPT
|
||||||
: span(s.data(), s.size()) {
|
: span(s.data(), s.size()) {
|
||||||
}
|
}
|
||||||
@@ -462,45 +463,45 @@ class span FLATBUFFERS_FINAL_CLASS {
|
|||||||
private:
|
private:
|
||||||
// This is a naive implementation with 'count_' member even if (Extent != dynamic_extent).
|
// This is a naive implementation with 'count_' member even if (Extent != dynamic_extent).
|
||||||
pointer const data_;
|
pointer const data_;
|
||||||
const size_type count_;
|
size_type count_;
|
||||||
};
|
};
|
||||||
#endif // defined(FLATBUFFERS_USE_STD_SPAN)
|
#endif // defined(FLATBUFFERS_USE_STD_SPAN)
|
||||||
|
|
||||||
#if !defined(FLATBUFFERS_SPAN_MINIMAL)
|
#if !defined(FLATBUFFERS_SPAN_MINIMAL)
|
||||||
template<class U, std::size_t N>
|
template<class ElementType, std::size_t Extent>
|
||||||
FLATBUFFERS_CONSTEXPR_CPP11
|
FLATBUFFERS_CONSTEXPR_CPP11
|
||||||
flatbuffers::span<U, N> make_span(U(&arr)[N]) FLATBUFFERS_NOEXCEPT {
|
flatbuffers::span<ElementType, Extent> make_span(ElementType(&arr)[Extent]) FLATBUFFERS_NOEXCEPT {
|
||||||
return span<U, N>(arr);
|
return span<ElementType, Extent>(arr);
|
||||||
}
|
}
|
||||||
|
|
||||||
template<class U, std::size_t N>
|
template<class ElementType, std::size_t Extent>
|
||||||
FLATBUFFERS_CONSTEXPR_CPP11
|
FLATBUFFERS_CONSTEXPR_CPP11
|
||||||
flatbuffers::span<const U, N> make_span(const U(&arr)[N]) FLATBUFFERS_NOEXCEPT {
|
flatbuffers::span<const ElementType, Extent> make_span(const ElementType(&arr)[Extent]) FLATBUFFERS_NOEXCEPT {
|
||||||
return span<const U, N>(arr);
|
return span<const ElementType, Extent>(arr);
|
||||||
}
|
}
|
||||||
|
|
||||||
template<class U, std::size_t N>
|
template<class ElementType, std::size_t Extent>
|
||||||
FLATBUFFERS_CONSTEXPR_CPP11
|
FLATBUFFERS_CONSTEXPR_CPP11
|
||||||
flatbuffers::span<U, N> make_span(std::array<U, N> &arr) FLATBUFFERS_NOEXCEPT {
|
flatbuffers::span<ElementType, Extent> make_span(std::array<ElementType, Extent> &arr) FLATBUFFERS_NOEXCEPT {
|
||||||
return span<U, N>(arr);
|
return span<ElementType, Extent>(arr);
|
||||||
}
|
}
|
||||||
|
|
||||||
template<class U, std::size_t N>
|
template<class ElementType, std::size_t Extent>
|
||||||
FLATBUFFERS_CONSTEXPR_CPP11
|
FLATBUFFERS_CONSTEXPR_CPP11
|
||||||
flatbuffers::span<const U, N> make_span(const std::array<U, N> &arr) FLATBUFFERS_NOEXCEPT {
|
flatbuffers::span<const ElementType, Extent> make_span(const std::array<ElementType, Extent> &arr) FLATBUFFERS_NOEXCEPT {
|
||||||
return span<const U, N>(arr);
|
return span<const ElementType, Extent>(arr);
|
||||||
}
|
}
|
||||||
|
|
||||||
template<class U, std::size_t N>
|
template<class ElementType, std::size_t Extent>
|
||||||
FLATBUFFERS_CONSTEXPR_CPP11
|
FLATBUFFERS_CONSTEXPR_CPP11
|
||||||
flatbuffers::span<U, dynamic_extent> make_span(U *first, std::size_t count) FLATBUFFERS_NOEXCEPT {
|
flatbuffers::span<ElementType, dynamic_extent> make_span(ElementType *first, std::size_t count) FLATBUFFERS_NOEXCEPT {
|
||||||
return span<U, dynamic_extent>(first, count);
|
return span<ElementType, dynamic_extent>(first, count);
|
||||||
}
|
}
|
||||||
|
|
||||||
template<class U, std::size_t N>
|
template<class ElementType, std::size_t Extent>
|
||||||
FLATBUFFERS_CONSTEXPR_CPP11
|
FLATBUFFERS_CONSTEXPR_CPP11
|
||||||
flatbuffers::span<const U, dynamic_extent> make_span(const U *first, std::size_t count) FLATBUFFERS_NOEXCEPT {
|
flatbuffers::span<const ElementType, dynamic_extent> make_span(const ElementType *first, std::size_t count) FLATBUFFERS_NOEXCEPT {
|
||||||
return span<const U, dynamic_extent>(first, count);
|
return span<const ElementType, dynamic_extent>(first, count);
|
||||||
}
|
}
|
||||||
#endif // !defined(FLATBUFFERS_SPAN_MINIMAL)
|
#endif // !defined(FLATBUFFERS_SPAN_MINIMAL)
|
||||||
|
|
||||||
|
|||||||
@@ -112,20 +112,22 @@ class Table {
|
|||||||
|
|
||||||
// Verify a particular field.
|
// Verify a particular field.
|
||||||
template<typename T>
|
template<typename T>
|
||||||
bool VerifyField(const Verifier &verifier, voffset_t field) const {
|
bool VerifyField(const Verifier &verifier, voffset_t field,
|
||||||
|
size_t align) const {
|
||||||
// Calling GetOptionalFieldOffset should be safe now thanks to
|
// Calling GetOptionalFieldOffset should be safe now thanks to
|
||||||
// VerifyTable().
|
// VerifyTable().
|
||||||
auto field_offset = GetOptionalFieldOffset(field);
|
auto field_offset = GetOptionalFieldOffset(field);
|
||||||
// Check the actual field.
|
// Check the actual field.
|
||||||
return !field_offset || verifier.Verify<T>(data_, field_offset);
|
return !field_offset || verifier.VerifyField<T>(data_, field_offset, align);
|
||||||
}
|
}
|
||||||
|
|
||||||
// VerifyField for required fields.
|
// VerifyField for required fields.
|
||||||
template<typename T>
|
template<typename T>
|
||||||
bool VerifyFieldRequired(const Verifier &verifier, voffset_t field) const {
|
bool VerifyFieldRequired(const Verifier &verifier, voffset_t field,
|
||||||
|
size_t align) const {
|
||||||
auto field_offset = GetOptionalFieldOffset(field);
|
auto field_offset = GetOptionalFieldOffset(field);
|
||||||
return verifier.Check(field_offset != 0) &&
|
return verifier.Check(field_offset != 0) &&
|
||||||
verifier.Verify<T>(data_, field_offset);
|
verifier.VerifyField<T>(data_, field_offset, align);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Versions for offsets.
|
// Versions for offsets.
|
||||||
@@ -163,4 +165,4 @@ inline flatbuffers::Optional<bool> Table::GetOptional<uint8_t, bool>(
|
|||||||
|
|
||||||
} // namespace flatbuffers
|
} // namespace flatbuffers
|
||||||
|
|
||||||
#endif // FLATBUFFERS_TABLE_H_
|
#endif // FLATBUFFERS_TABLE_H_
|
||||||
|
|||||||
@@ -17,19 +17,20 @@
|
|||||||
#ifndef FLATBUFFERS_UTIL_H_
|
#ifndef FLATBUFFERS_UTIL_H_
|
||||||
#define FLATBUFFERS_UTIL_H_
|
#define FLATBUFFERS_UTIL_H_
|
||||||
|
|
||||||
|
#include <ctype.h>
|
||||||
#include <errno.h>
|
#include <errno.h>
|
||||||
|
|
||||||
#include "flatbuffers/base.h"
|
#include "flatbuffers/base.h"
|
||||||
#include "flatbuffers/stl_emulation.h"
|
#include "flatbuffers/stl_emulation.h"
|
||||||
|
|
||||||
#ifndef FLATBUFFERS_PREFER_PRINTF
|
#ifndef FLATBUFFERS_PREFER_PRINTF
|
||||||
|
# include <iomanip>
|
||||||
# include <sstream>
|
# include <sstream>
|
||||||
#else // FLATBUFFERS_PREFER_PRINTF
|
#else // FLATBUFFERS_PREFER_PRINTF
|
||||||
# include <float.h>
|
# include <float.h>
|
||||||
# include <stdio.h>
|
# include <stdio.h>
|
||||||
#endif // FLATBUFFERS_PREFER_PRINTF
|
#endif // FLATBUFFERS_PREFER_PRINTF
|
||||||
|
|
||||||
#include <iomanip>
|
|
||||||
#include <string>
|
#include <string>
|
||||||
|
|
||||||
namespace flatbuffers {
|
namespace flatbuffers {
|
||||||
@@ -94,7 +95,7 @@ template<typename T> size_t IntToDigitCount(T t) {
|
|||||||
// Count a single 0 left of the dot for fractional numbers
|
// Count a single 0 left of the dot for fractional numbers
|
||||||
if (-1 < t && t < 1) digit_count++;
|
if (-1 < t && t < 1) digit_count++;
|
||||||
// Count digits until fractional part
|
// Count digits until fractional part
|
||||||
T eps = std::numeric_limits<float>::epsilon();
|
T eps = std::numeric_limits<T>::epsilon();
|
||||||
while (t <= (-1 + eps) || (1 - eps) <= t) {
|
while (t <= (-1 + eps) || (1 - eps) <= t) {
|
||||||
t /= 10;
|
t /= 10;
|
||||||
digit_count++;
|
digit_count++;
|
||||||
@@ -254,7 +255,7 @@ inline void strtoval_impl(double *val, const char *str, char **endptr) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// UBSAN: double to float is safe if numeric_limits<float>::is_iec559 is true.
|
// UBSAN: double to float is safe if numeric_limits<float>::is_iec559 is true.
|
||||||
__supress_ubsan__("float-cast-overflow")
|
__suppress_ubsan__("float-cast-overflow")
|
||||||
inline void strtoval_impl(float *val, const char *str, char **endptr) {
|
inline void strtoval_impl(float *val, const char *str, char **endptr) {
|
||||||
*val = __strtof_impl(str, endptr);
|
*val = __strtof_impl(str, endptr);
|
||||||
}
|
}
|
||||||
@@ -447,6 +448,9 @@ std::string StripPath(const std::string &filepath);
|
|||||||
// Strip the last component of the path + separator.
|
// Strip the last component of the path + separator.
|
||||||
std::string StripFileName(const std::string &filepath);
|
std::string StripFileName(const std::string &filepath);
|
||||||
|
|
||||||
|
std::string StripPrefix(const std::string &filepath,
|
||||||
|
const std::string &prefix_to_remove);
|
||||||
|
|
||||||
// Concatenates a path with a filename, regardless of whether the path
|
// Concatenates a path with a filename, regardless of whether the path
|
||||||
// ends in a separator or not.
|
// ends in a separator or not.
|
||||||
std::string ConCatPathFileName(const std::string &path,
|
std::string ConCatPathFileName(const std::string &path,
|
||||||
@@ -684,6 +688,32 @@ bool ReadEnvironmentVariable(const char *var_name,
|
|||||||
// MSVC specific: Send all assert reports to STDOUT to prevent CI hangs.
|
// MSVC specific: Send all assert reports to STDOUT to prevent CI hangs.
|
||||||
void SetupDefaultCRTReportMode();
|
void SetupDefaultCRTReportMode();
|
||||||
|
|
||||||
|
enum class Case {
|
||||||
|
kUnknown = 0,
|
||||||
|
// TheQuickBrownFox
|
||||||
|
kUpperCamel = 1,
|
||||||
|
// theQuickBrownFox
|
||||||
|
kLowerCamel = 2,
|
||||||
|
// the_quick_brown_fox
|
||||||
|
kSnake = 3,
|
||||||
|
// THE_QUICK_BROWN_FOX
|
||||||
|
kScreamingSnake = 4,
|
||||||
|
// THEQUICKBROWNFOX
|
||||||
|
kAllUpper = 5,
|
||||||
|
// thequickbrownfox
|
||||||
|
kAllLower = 6,
|
||||||
|
// the-quick-brown-fox
|
||||||
|
kDasher = 7,
|
||||||
|
// THEQuiCKBr_ownFox (or whatever you want, we won't change it)
|
||||||
|
kKeep = 8,
|
||||||
|
// the_quick_brown_fox123 (as opposed to the_quick_brown_fox_123)
|
||||||
|
kSnake2 = 9,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Convert the `input` string of case `input_case` to the specified `output_case`.
|
||||||
|
std::string ConvertCase(const std::string &input, Case output_case,
|
||||||
|
Case input_case = Case::kSnake);
|
||||||
|
|
||||||
} // namespace flatbuffers
|
} // namespace flatbuffers
|
||||||
|
|
||||||
#endif // FLATBUFFERS_UTIL_H_
|
#endif // FLATBUFFERS_UTIL_H_
|
||||||
|
|||||||
@@ -19,6 +19,7 @@
|
|||||||
|
|
||||||
#include "flatbuffers/base.h"
|
#include "flatbuffers/base.h"
|
||||||
#include "flatbuffers/buffer.h"
|
#include "flatbuffers/buffer.h"
|
||||||
|
#include "flatbuffers/stl_emulation.h"
|
||||||
|
|
||||||
namespace flatbuffers {
|
namespace flatbuffers {
|
||||||
|
|
||||||
@@ -326,6 +327,24 @@ FLATBUFFERS_CONSTEXPR_CPP11 flatbuffers::span<const uint8_t> make_bytes_span(
|
|||||||
return span<const uint8_t>(vec.Data(), vec.size() * sizeof(U));
|
return span<const uint8_t>(vec.Data(), vec.size() * sizeof(U));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Convenient helper functions to get a span of any vector, regardless
|
||||||
|
// of whether it is null or not (the field is not set).
|
||||||
|
template<class U>
|
||||||
|
FLATBUFFERS_CONSTEXPR_CPP11 flatbuffers::span<U> make_span(Vector<U> *ptr)
|
||||||
|
FLATBUFFERS_NOEXCEPT {
|
||||||
|
static_assert(Vector<U>::is_span_observable,
|
||||||
|
"wrong type U, only LE-scalar, or byte types are allowed");
|
||||||
|
return ptr ? make_span(*ptr) : span<U>();
|
||||||
|
}
|
||||||
|
|
||||||
|
template<class U>
|
||||||
|
FLATBUFFERS_CONSTEXPR_CPP11 flatbuffers::span<const U> make_span(
|
||||||
|
const Vector<U> *ptr) FLATBUFFERS_NOEXCEPT {
|
||||||
|
static_assert(Vector<U>::is_span_observable,
|
||||||
|
"wrong type U, only LE-scalar, or byte types are allowed");
|
||||||
|
return ptr ? make_span(*ptr) : span<const U>();
|
||||||
|
}
|
||||||
|
|
||||||
// Represent a vector much like the template above, but in this case we
|
// Represent a vector much like the template above, but in this case we
|
||||||
// don't know what the element types are (used with reflection.h).
|
// don't know what the element types are (used with reflection.h).
|
||||||
class VectorOfAny {
|
class VectorOfAny {
|
||||||
|
|||||||
@@ -24,7 +24,7 @@
|
|||||||
namespace flatbuffers {
|
namespace flatbuffers {
|
||||||
|
|
||||||
// This is a minimal replication of std::vector<uint8_t> functionality,
|
// This is a minimal replication of std::vector<uint8_t> functionality,
|
||||||
// except growing from higher to lower addresses. i.e push_back() inserts data
|
// except growing from higher to lower addresses. i.e. push_back() inserts data
|
||||||
// in the lowest address in the vector.
|
// in the lowest address in the vector.
|
||||||
// Since this vector leaves the lower part unused, we support a "scratch-pad"
|
// Since this vector leaves the lower part unused, we support a "scratch-pad"
|
||||||
// that can be stored there for temporary data, to share the allocated space.
|
// that can be stored there for temporary data, to share the allocated space.
|
||||||
|
|||||||
@@ -18,7 +18,6 @@
|
|||||||
#define FLATBUFFERS_VERIFIER_H_
|
#define FLATBUFFERS_VERIFIER_H_
|
||||||
|
|
||||||
#include "flatbuffers/base.h"
|
#include "flatbuffers/base.h"
|
||||||
#include "flatbuffers/util.h"
|
|
||||||
#include "flatbuffers/vector.h"
|
#include "flatbuffers/vector.h"
|
||||||
|
|
||||||
namespace flatbuffers {
|
namespace flatbuffers {
|
||||||
@@ -26,21 +25,37 @@ namespace flatbuffers {
|
|||||||
// Helper class to verify the integrity of a FlatBuffer
|
// Helper class to verify the integrity of a FlatBuffer
|
||||||
class Verifier FLATBUFFERS_FINAL_CLASS {
|
class Verifier FLATBUFFERS_FINAL_CLASS {
|
||||||
public:
|
public:
|
||||||
Verifier(const uint8_t *buf, size_t buf_len, uoffset_t _max_depth = 64,
|
struct Options {
|
||||||
uoffset_t _max_tables = 1000000, bool _check_alignment = true)
|
// The maximum nesting of tables and vectors before we call it invalid.
|
||||||
: buf_(buf),
|
uoffset_t max_depth = 64;
|
||||||
size_(buf_len),
|
// The maximum number of tables we will verify before we call it invalid.
|
||||||
depth_(0),
|
uoffset_t max_tables = 1000000;
|
||||||
max_depth_(_max_depth),
|
// If true, verify all data is aligned.
|
||||||
num_tables_(0),
|
bool check_alignment = true;
|
||||||
max_tables_(_max_tables),
|
// If true, run verifier on nested flatbuffers
|
||||||
upper_bound_(0),
|
bool check_nested_flatbuffers = true;
|
||||||
check_alignment_(_check_alignment) {
|
};
|
||||||
|
|
||||||
|
explicit Verifier(const uint8_t *const buf, const size_t buf_len,
|
||||||
|
const Options &opts)
|
||||||
|
: buf_(buf), size_(buf_len), opts_(opts) {
|
||||||
FLATBUFFERS_ASSERT(size_ < FLATBUFFERS_MAX_BUFFER_SIZE);
|
FLATBUFFERS_ASSERT(size_ < FLATBUFFERS_MAX_BUFFER_SIZE);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Deprecated API, please construct with Verifier::Options.
|
||||||
|
Verifier(const uint8_t *const buf, const size_t buf_len,
|
||||||
|
const uoffset_t max_depth = 64, const uoffset_t max_tables = 1000000,
|
||||||
|
const bool check_alignment = true)
|
||||||
|
: Verifier(buf, buf_len, [&] {
|
||||||
|
Options opts;
|
||||||
|
opts.max_depth = max_depth;
|
||||||
|
opts.max_tables = max_tables;
|
||||||
|
opts.check_alignment = check_alignment;
|
||||||
|
return opts;
|
||||||
|
}()) {}
|
||||||
|
|
||||||
// Central location where any verification failures register.
|
// Central location where any verification failures register.
|
||||||
bool Check(bool ok) const {
|
bool Check(const bool ok) const {
|
||||||
// clang-format off
|
// clang-format off
|
||||||
#ifdef FLATBUFFERS_DEBUG_VERIFICATION_FAILURE
|
#ifdef FLATBUFFERS_DEBUG_VERIFICATION_FAILURE
|
||||||
FLATBUFFERS_ASSERT(ok);
|
FLATBUFFERS_ASSERT(ok);
|
||||||
@@ -54,7 +69,7 @@ class Verifier FLATBUFFERS_FINAL_CLASS {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Verify any range within the buffer.
|
// Verify any range within the buffer.
|
||||||
bool Verify(size_t elem, size_t elem_len) const {
|
bool Verify(const size_t elem, const size_t elem_len) const {
|
||||||
// clang-format off
|
// clang-format off
|
||||||
#ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
|
#ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
|
||||||
auto upper_bound = elem + elem_len;
|
auto upper_bound = elem + elem_len;
|
||||||
@@ -65,48 +80,52 @@ class Verifier FLATBUFFERS_FINAL_CLASS {
|
|||||||
return Check(elem_len < size_ && elem <= size_ - elem_len);
|
return Check(elem_len < size_ && elem <= size_ - elem_len);
|
||||||
}
|
}
|
||||||
|
|
||||||
template<typename T> bool VerifyAlignment(size_t elem) const {
|
bool VerifyAlignment(const size_t elem, const size_t align) const {
|
||||||
return Check((elem & (sizeof(T) - 1)) == 0 || !check_alignment_);
|
return Check((elem & (align - 1)) == 0 || !opts_.check_alignment);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Verify a range indicated by sizeof(T).
|
// Verify a range indicated by sizeof(T).
|
||||||
template<typename T> bool Verify(size_t elem) const {
|
template<typename T> bool Verify(const size_t elem) const {
|
||||||
return VerifyAlignment<T>(elem) && Verify(elem, sizeof(T));
|
return VerifyAlignment(elem, sizeof(T)) && Verify(elem, sizeof(T));
|
||||||
}
|
}
|
||||||
|
|
||||||
bool VerifyFromPointer(const uint8_t *p, size_t len) {
|
bool VerifyFromPointer(const uint8_t *const p, const size_t len) {
|
||||||
auto o = static_cast<size_t>(p - buf_);
|
return Verify(static_cast<size_t>(p - buf_), len);
|
||||||
return Verify(o, len);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Verify relative to a known-good base pointer.
|
// Verify relative to a known-good base pointer.
|
||||||
bool Verify(const uint8_t *base, voffset_t elem_off, size_t elem_len) const {
|
bool VerifyFieldStruct(const uint8_t *const base, const voffset_t elem_off,
|
||||||
return Verify(static_cast<size_t>(base - buf_) + elem_off, elem_len);
|
const size_t elem_len, const size_t align) const {
|
||||||
|
const auto f = static_cast<size_t>(base - buf_) + elem_off;
|
||||||
|
return VerifyAlignment(f, align) && Verify(f, elem_len);
|
||||||
}
|
}
|
||||||
|
|
||||||
template<typename T>
|
template<typename T>
|
||||||
bool Verify(const uint8_t *base, voffset_t elem_off) const {
|
bool VerifyField(const uint8_t *const base, const voffset_t elem_off,
|
||||||
return Verify(static_cast<size_t>(base - buf_) + elem_off, sizeof(T));
|
const size_t align) const {
|
||||||
|
const auto f = static_cast<size_t>(base - buf_) + elem_off;
|
||||||
|
return VerifyAlignment(f, align) && Verify(f, sizeof(T));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Verify a pointer (may be NULL) of a table type.
|
// Verify a pointer (may be NULL) of a table type.
|
||||||
template<typename T> bool VerifyTable(const T *table) {
|
template<typename T> bool VerifyTable(const T *const table) {
|
||||||
return !table || table->Verify(*this);
|
return !table || table->Verify(*this);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Verify a pointer (may be NULL) of any vector type.
|
// Verify a pointer (may be NULL) of any vector type.
|
||||||
template<typename T> bool VerifyVector(const Vector<T> *vec) const {
|
template<typename T> bool VerifyVector(const Vector<T> *const vec) const {
|
||||||
return !vec || VerifyVectorOrString(reinterpret_cast<const uint8_t *>(vec),
|
return !vec || VerifyVectorOrString(reinterpret_cast<const uint8_t *>(vec),
|
||||||
sizeof(T));
|
sizeof(T));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Verify a pointer (may be NULL) of a vector to struct.
|
// Verify a pointer (may be NULL) of a vector to struct.
|
||||||
template<typename T> bool VerifyVector(const Vector<const T *> *vec) const {
|
template<typename T>
|
||||||
|
bool VerifyVector(const Vector<const T *> *const vec) const {
|
||||||
return VerifyVector(reinterpret_cast<const Vector<T> *>(vec));
|
return VerifyVector(reinterpret_cast<const Vector<T> *>(vec));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Verify a pointer (may be NULL) to string.
|
// Verify a pointer (may be NULL) to string.
|
||||||
bool VerifyString(const String *str) const {
|
bool VerifyString(const String *const str) const {
|
||||||
size_t end;
|
size_t end;
|
||||||
return !str || (VerifyVectorOrString(reinterpret_cast<const uint8_t *>(str),
|
return !str || (VerifyVectorOrString(reinterpret_cast<const uint8_t *>(str),
|
||||||
1, &end) &&
|
1, &end) &&
|
||||||
@@ -115,24 +134,24 @@ class Verifier FLATBUFFERS_FINAL_CLASS {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Common code between vectors and strings.
|
// Common code between vectors and strings.
|
||||||
bool VerifyVectorOrString(const uint8_t *vec, size_t elem_size,
|
bool VerifyVectorOrString(const uint8_t *const vec, const size_t elem_size,
|
||||||
size_t *end = nullptr) const {
|
size_t *const end = nullptr) const {
|
||||||
auto veco = static_cast<size_t>(vec - buf_);
|
const auto veco = static_cast<size_t>(vec - buf_);
|
||||||
// Check we can read the size field.
|
// Check we can read the size field.
|
||||||
if (!Verify<uoffset_t>(veco)) return false;
|
if (!Verify<uoffset_t>(veco)) return false;
|
||||||
// Check the whole array. If this is a string, the byte past the array
|
// Check the whole array. If this is a string, the byte past the array must
|
||||||
// must be 0.
|
// be 0.
|
||||||
auto size = ReadScalar<uoffset_t>(vec);
|
const auto size = ReadScalar<uoffset_t>(vec);
|
||||||
auto max_elems = FLATBUFFERS_MAX_BUFFER_SIZE / elem_size;
|
const auto max_elems = FLATBUFFERS_MAX_BUFFER_SIZE / elem_size;
|
||||||
if (!Check(size < max_elems))
|
if (!Check(size < max_elems))
|
||||||
return false; // Protect against byte_size overflowing.
|
return false; // Protect against byte_size overflowing.
|
||||||
auto byte_size = sizeof(size) + elem_size * size;
|
const auto byte_size = sizeof(size) + elem_size * size;
|
||||||
if (end) *end = veco + byte_size;
|
if (end) *end = veco + byte_size;
|
||||||
return Verify(veco, byte_size);
|
return Verify(veco, byte_size);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Special case for string contents, after the above has been called.
|
// Special case for string contents, after the above has been called.
|
||||||
bool VerifyVectorOfStrings(const Vector<Offset<String>> *vec) const {
|
bool VerifyVectorOfStrings(const Vector<Offset<String>> *const vec) const {
|
||||||
if (vec) {
|
if (vec) {
|
||||||
for (uoffset_t i = 0; i < vec->size(); i++) {
|
for (uoffset_t i = 0; i < vec->size(); i++) {
|
||||||
if (!VerifyString(vec->Get(i))) return false;
|
if (!VerifyString(vec->Get(i))) return false;
|
||||||
@@ -142,7 +161,8 @@ class Verifier FLATBUFFERS_FINAL_CLASS {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Special case for table contents, after the above has been called.
|
// Special case for table contents, after the above has been called.
|
||||||
template<typename T> bool VerifyVectorOfTables(const Vector<Offset<T>> *vec) {
|
template<typename T>
|
||||||
|
bool VerifyVectorOfTables(const Vector<Offset<T>> *const vec) {
|
||||||
if (vec) {
|
if (vec) {
|
||||||
for (uoffset_t i = 0; i < vec->size(); i++) {
|
for (uoffset_t i = 0; i < vec->size(); i++) {
|
||||||
if (!vec->Get(i)->Verify(*this)) return false;
|
if (!vec->Get(i)->Verify(*this)) return false;
|
||||||
@@ -151,30 +171,41 @@ class Verifier FLATBUFFERS_FINAL_CLASS {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
__supress_ubsan__("unsigned-integer-overflow") bool VerifyTableStart(
|
__suppress_ubsan__("unsigned-integer-overflow") bool VerifyTableStart(
|
||||||
const uint8_t *table) {
|
const uint8_t *const table) {
|
||||||
// Check the vtable offset.
|
// Check the vtable offset.
|
||||||
auto tableo = static_cast<size_t>(table - buf_);
|
const auto tableo = static_cast<size_t>(table - buf_);
|
||||||
if (!Verify<soffset_t>(tableo)) return false;
|
if (!Verify<soffset_t>(tableo)) return false;
|
||||||
// This offset may be signed, but doing the subtraction unsigned always
|
// This offset may be signed, but doing the subtraction unsigned always
|
||||||
// gives the result we want.
|
// gives the result we want.
|
||||||
auto vtableo = tableo - static_cast<size_t>(ReadScalar<soffset_t>(table));
|
const auto vtableo =
|
||||||
|
tableo - static_cast<size_t>(ReadScalar<soffset_t>(table));
|
||||||
// Check the vtable size field, then check vtable fits in its entirety.
|
// Check the vtable size field, then check vtable fits in its entirety.
|
||||||
return VerifyComplexity() && Verify<voffset_t>(vtableo) &&
|
if (!(VerifyComplexity() && Verify<voffset_t>(vtableo) &&
|
||||||
VerifyAlignment<voffset_t>(ReadScalar<voffset_t>(buf_ + vtableo)) &&
|
VerifyAlignment(ReadScalar<voffset_t>(buf_ + vtableo),
|
||||||
Verify(vtableo, ReadScalar<voffset_t>(buf_ + vtableo));
|
sizeof(voffset_t))))
|
||||||
|
return false;
|
||||||
|
const auto vsize = ReadScalar<voffset_t>(buf_ + vtableo);
|
||||||
|
return Check((vsize & 1) == 0) && Verify(vtableo, vsize);
|
||||||
}
|
}
|
||||||
|
|
||||||
template<typename T>
|
template<typename T>
|
||||||
bool VerifyBufferFromStart(const char *identifier, size_t start) {
|
bool VerifyBufferFromStart(const char *const identifier, const size_t start) {
|
||||||
|
// Buffers have to be of some size to be valid. The reason it is a runtime
|
||||||
|
// check instead of static_assert, is that nested flatbuffers go through
|
||||||
|
// this call and their size is determined at runtime.
|
||||||
|
if (!Check(size_ >= FLATBUFFERS_MIN_BUFFER_SIZE)) return false;
|
||||||
|
|
||||||
|
// If an identifier is provided, check that we have a buffer
|
||||||
if (identifier && !Check((size_ >= 2 * sizeof(flatbuffers::uoffset_t) &&
|
if (identifier && !Check((size_ >= 2 * sizeof(flatbuffers::uoffset_t) &&
|
||||||
BufferHasIdentifier(buf_ + start, identifier)))) {
|
BufferHasIdentifier(buf_ + start, identifier)))) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Call T::Verify, which must be in the generated code for this type.
|
// Call T::Verify, which must be in the generated code for this type.
|
||||||
auto o = VerifyOffset(start);
|
const auto o = VerifyOffset(start);
|
||||||
return o && reinterpret_cast<const T *>(buf_ + start + o)->Verify(*this)
|
return Check(o != 0) &&
|
||||||
|
reinterpret_cast<const T *>(buf_ + start + o)->Verify(*this)
|
||||||
// clang-format off
|
// clang-format off
|
||||||
#ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
|
#ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
|
||||||
&& GetComputedSize()
|
&& GetComputedSize()
|
||||||
@@ -184,9 +215,17 @@ class Verifier FLATBUFFERS_FINAL_CLASS {
|
|||||||
}
|
}
|
||||||
|
|
||||||
template<typename T>
|
template<typename T>
|
||||||
bool VerifyNestedFlatBuffer(const Vector<uint8_t> *buf,
|
bool VerifyNestedFlatBuffer(const Vector<uint8_t> *const buf,
|
||||||
const char *identifier) {
|
const char *const identifier) {
|
||||||
|
// Caller opted out of this.
|
||||||
|
if (!opts_.check_nested_flatbuffers) return true;
|
||||||
|
|
||||||
|
// An empty buffer is OK as it indicates not present.
|
||||||
if (!buf) return true;
|
if (!buf) return true;
|
||||||
|
|
||||||
|
// If there is a nested buffer, it must be greater than the min size.
|
||||||
|
if (!Check(buf->size() >= FLATBUFFERS_MIN_BUFFER_SIZE)) return false;
|
||||||
|
|
||||||
Verifier nested_verifier(buf->data(), buf->size());
|
Verifier nested_verifier(buf->data(), buf->size());
|
||||||
return nested_verifier.VerifyBuffer<T>(identifier);
|
return nested_verifier.VerifyBuffer<T>(identifier);
|
||||||
}
|
}
|
||||||
@@ -194,19 +233,20 @@ class Verifier FLATBUFFERS_FINAL_CLASS {
|
|||||||
// Verify this whole buffer, starting with root type T.
|
// Verify this whole buffer, starting with root type T.
|
||||||
template<typename T> bool VerifyBuffer() { return VerifyBuffer<T>(nullptr); }
|
template<typename T> bool VerifyBuffer() { return VerifyBuffer<T>(nullptr); }
|
||||||
|
|
||||||
template<typename T> bool VerifyBuffer(const char *identifier) {
|
template<typename T> bool VerifyBuffer(const char *const identifier) {
|
||||||
return VerifyBufferFromStart<T>(identifier, 0);
|
return VerifyBufferFromStart<T>(identifier, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
template<typename T> bool VerifySizePrefixedBuffer(const char *identifier) {
|
template<typename T>
|
||||||
|
bool VerifySizePrefixedBuffer(const char *const identifier) {
|
||||||
return Verify<uoffset_t>(0U) &&
|
return Verify<uoffset_t>(0U) &&
|
||||||
ReadScalar<uoffset_t>(buf_) == size_ - sizeof(uoffset_t) &&
|
Check(ReadScalar<uoffset_t>(buf_) == size_ - sizeof(uoffset_t)) &&
|
||||||
VerifyBufferFromStart<T>(identifier, sizeof(uoffset_t));
|
VerifyBufferFromStart<T>(identifier, sizeof(uoffset_t));
|
||||||
}
|
}
|
||||||
|
|
||||||
uoffset_t VerifyOffset(size_t start) const {
|
uoffset_t VerifyOffset(const size_t start) const {
|
||||||
if (!Verify<uoffset_t>(start)) return 0;
|
if (!Verify<uoffset_t>(start)) return 0;
|
||||||
auto o = ReadScalar<uoffset_t>(buf_ + start);
|
const auto o = ReadScalar<uoffset_t>(buf_ + start);
|
||||||
// May not point to itself.
|
// May not point to itself.
|
||||||
if (!Check(o != 0)) return 0;
|
if (!Check(o != 0)) return 0;
|
||||||
// Can't wrap around / buffers are max 2GB.
|
// Can't wrap around / buffers are max 2GB.
|
||||||
@@ -217,18 +257,18 @@ class Verifier FLATBUFFERS_FINAL_CLASS {
|
|||||||
return o;
|
return o;
|
||||||
}
|
}
|
||||||
|
|
||||||
uoffset_t VerifyOffset(const uint8_t *base, voffset_t start) const {
|
uoffset_t VerifyOffset(const uint8_t *const base,
|
||||||
|
const voffset_t start) const {
|
||||||
return VerifyOffset(static_cast<size_t>(base - buf_) + start);
|
return VerifyOffset(static_cast<size_t>(base - buf_) + start);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Called at the start of a table to increase counters measuring data
|
// Called at the start of a table to increase counters measuring data
|
||||||
// structure depth and amount, and possibly bails out with false if
|
// structure depth and amount, and possibly bails out with false if limits set
|
||||||
// limits set by the constructor have been hit. Needs to be balanced
|
// by the constructor have been hit. Needs to be balanced with EndTable().
|
||||||
// with EndTable().
|
|
||||||
bool VerifyComplexity() {
|
bool VerifyComplexity() {
|
||||||
depth_++;
|
depth_++;
|
||||||
num_tables_++;
|
num_tables_++;
|
||||||
return Check(depth_ <= max_depth_ && num_tables_ <= max_tables_);
|
return Check(depth_ <= opts_.max_depth && num_tables_ <= opts_.max_tables);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Called at the end of a table to pop the depth count.
|
// Called at the end of a table to pop the depth count.
|
||||||
@@ -254,15 +294,22 @@ class Verifier FLATBUFFERS_FINAL_CLASS {
|
|||||||
// clang-format on
|
// clang-format on
|
||||||
}
|
}
|
||||||
|
|
||||||
|
std::vector<uint8_t> *GetFlexReuseTracker() { return flex_reuse_tracker_; }
|
||||||
|
|
||||||
|
void SetFlexReuseTracker(std::vector<uint8_t> *const rt) {
|
||||||
|
flex_reuse_tracker_ = rt;
|
||||||
|
}
|
||||||
|
|
||||||
private:
|
private:
|
||||||
const uint8_t *buf_;
|
const uint8_t *buf_;
|
||||||
size_t size_;
|
const size_t size_;
|
||||||
uoffset_t depth_;
|
const Options opts_;
|
||||||
uoffset_t max_depth_;
|
|
||||||
uoffset_t num_tables_;
|
mutable size_t upper_bound_ = 0;
|
||||||
uoffset_t max_tables_;
|
|
||||||
mutable size_t upper_bound_;
|
uoffset_t depth_ = 0;
|
||||||
bool check_alignment_;
|
uoffset_t num_tables_ = 0;
|
||||||
|
std::vector<uint8_t> *flex_reuse_tracker_ = nullptr;
|
||||||
};
|
};
|
||||||
|
|
||||||
} // namespace flatbuffers
|
} // namespace flatbuffers
|
||||||
|
|||||||
@@ -46,7 +46,7 @@ public class Constants {
|
|||||||
Changes to the Java implementation need to be sure to change
|
Changes to the Java implementation need to be sure to change
|
||||||
the version here and in the code generator on every possible
|
the version here and in the code generator on every possible
|
||||||
incompatible change */
|
incompatible change */
|
||||||
public static void FLATBUFFERS_2_0_0() {}
|
public static void FLATBUFFERS_2_0_8() {}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// @endcond
|
/// @endcond
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user