forked from BigfootDev/flatbuffers
Compare commits
414 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
40b03519c1 | ||
|
|
d236dea13d | ||
|
|
ed88f7de96 | ||
|
|
07478a6700 | ||
|
|
48ff729477 | ||
|
|
7c60937806 | ||
|
|
ace304513f | ||
|
|
1917e577a2 | ||
|
|
9c9fce96c7 | ||
|
|
525130765a | ||
|
|
d890ef9e20 | ||
|
|
9f69d79430 | ||
|
|
9d66af6efc | ||
|
|
8f1729f7df | ||
|
|
4bef5e89c4 | ||
|
|
79222bf100 | ||
|
|
c3bfefca57 | ||
|
|
00fd394d23 | ||
|
|
e1e8d53df6 | ||
|
|
57a6dd472f | ||
|
|
224e33ed09 | ||
|
|
94680f5483 | ||
|
|
b4db88808f | ||
|
|
d9db48257b | ||
|
|
e1e1bced08 | ||
|
|
b56add9520 | ||
|
|
2abe24b9dd | ||
|
|
a35c32e30f | ||
|
|
781c39c708 | ||
|
|
ff9e539cc5 | ||
|
|
feb4816610 | ||
|
|
703b790939 | ||
|
|
811a5c3389 | ||
|
|
2736711d67 | ||
|
|
edb3b9c307 | ||
|
|
477fedccd4 | ||
|
|
5de28c74f9 | ||
|
|
44261ccdf1 | ||
|
|
c02b16e195 | ||
|
|
169df65df4 | ||
|
|
af1487bcfb | ||
|
|
5db12e9907 | ||
|
|
dff07b6f31 | ||
|
|
5dd8795a10 | ||
|
|
be503cb0f2 | ||
|
|
01e06b69a5 | ||
|
|
782e05de55 | ||
|
|
82a71b18f1 | ||
|
|
aeff09d724 | ||
|
|
a5c511576f | ||
|
|
ac10873e26 | ||
|
|
9689d38bef | ||
|
|
d06b2736aa | ||
|
|
a0f3fb44e7 | ||
|
|
d97f628703 | ||
|
|
fb7f27a7c9 | ||
|
|
7bfed4b29a | ||
|
|
a170b69d5d | ||
|
|
33e4ab65e9 | ||
|
|
201699288b | ||
|
|
e9202d85bd | ||
|
|
9a1ab5006f | ||
|
|
25c99273d3 | ||
|
|
7bcbb19569 | ||
|
|
b062af4c8c | ||
|
|
0956719726 | ||
|
|
766eaad4e7 | ||
|
|
3a74c33ba5 | ||
|
|
e4c3bf3d2c | ||
|
|
7196c36842 | ||
|
|
e151160560 | ||
|
|
dac63a227e | ||
|
|
986b52d849 | ||
|
|
45cc503bbd | ||
|
|
6aeb09b297 | ||
|
|
210c0ece54 | ||
|
|
ad84b5b8fa | ||
|
|
7101224d86 | ||
|
|
6be146d67f | ||
|
|
f706a42951 | ||
|
|
e24afd838a | ||
|
|
81c2b185ef | ||
|
|
0e064e415b | ||
|
|
4998ad7365 | ||
|
|
9a30d3d0df | ||
|
|
0b761ece4d | ||
|
|
01249c1d48 | ||
|
|
588564d74f | ||
|
|
6e192fa408 | ||
|
|
12ca3e054e | ||
|
|
62af533820 | ||
|
|
b56020ad3b | ||
|
|
6e160f4c59 | ||
|
|
07e77ad0ff | ||
|
|
b6380aceac | ||
|
|
79d3cb6a6c | ||
|
|
a4de6de700 | ||
|
|
a1d801c375 | ||
|
|
f66e93cd8d | ||
|
|
59a09cb1d0 | ||
|
|
c23c620d26 | ||
|
|
4798456df6 | ||
|
|
147fbb4285 | ||
|
|
a9ae9bdcab | ||
|
|
f7d8102b35 | ||
|
|
d0e9bc6a75 | ||
|
|
d863df8683 | ||
|
|
4834634766 | ||
|
|
a4c893dbe2 | ||
|
|
8833255ed3 | ||
|
|
fb5f9456e9 | ||
|
|
0dacfbbfca | ||
|
|
47aab78233 | ||
|
|
185b9f9792 | ||
|
|
21765bea2e | ||
|
|
36c7e9a962 | ||
|
|
cb2b2be54e | ||
|
|
1c152cc72a | ||
|
|
d67661eb39 | ||
|
|
ea97e1b5e2 | ||
|
|
dca3ccf5fd | ||
|
|
ef7b3ed8f5 | ||
|
|
4d305f5922 | ||
|
|
1e6f8f5b8c | ||
|
|
c967515da5 | ||
|
|
576022c64b | ||
|
|
eab9cfbec9 | ||
|
|
ab4801a82e | ||
|
|
8df4b318bc | ||
|
|
8a98e9ad98 | ||
|
|
eee5628569 | ||
|
|
ad3fd6ecbf | ||
|
|
622b8d05cf | ||
|
|
5faa0ab1be | ||
|
|
81312c2128 | ||
|
|
1808337adc | ||
|
|
5f091c46ce | ||
|
|
a96bfdb369 | ||
|
|
ad3ebb110b | ||
|
|
929105432c | ||
|
|
40fffc8fff | ||
|
|
2f76141813 | ||
|
|
932b22f043 | ||
|
|
ecf5a6a580 | ||
|
|
788acb08d4 | ||
|
|
ddb1d5ffe4 | ||
|
|
7ba29dbe41 | ||
|
|
3b070310f0 | ||
|
|
fbe085601b | ||
|
|
36f9b1ec91 | ||
|
|
7bcd99451f | ||
|
|
2535a3aa3a | ||
|
|
0894c25f2c | ||
|
|
7810fb9ce4 | ||
|
|
c127cf78c2 | ||
|
|
6fffa2a14d | ||
|
|
2b02d330fd | ||
|
|
c8f1682e07 | ||
|
|
f64e040896 | ||
|
|
339376ba67 | ||
|
|
7a1b77322b | ||
|
|
60b6ca5850 | ||
|
|
b8681d8031 | ||
|
|
f8139b05cb | ||
|
|
776c4eb965 | ||
|
|
2746aabcf1 | ||
|
|
04a06781f5 | ||
|
|
48dfc69ee6 | ||
|
|
4d213c2d06 | ||
|
|
361bfb6764 | ||
|
|
3f96eead4c | ||
|
|
8896587faf | ||
|
|
9fa3e2f387 | ||
|
|
e5c21ec666 | ||
|
|
e11da87a24 | ||
|
|
3dd54424c0 | ||
|
|
5d68493df4 | ||
|
|
d322eec3c3 | ||
|
|
221193eaa2 | ||
|
|
f7d24f60a2 | ||
|
|
e5a1a3129d | ||
|
|
39833d7cf0 | ||
|
|
ecb27817ca | ||
|
|
f59bfdd084 | ||
|
|
0ee1b99c5d | ||
|
|
a50711ad13 | ||
|
|
249f71a12b | ||
|
|
1d138fbe07 | ||
|
|
a0bf238b09 | ||
|
|
c49c6da803 | ||
|
|
37e6efe1f9 | ||
|
|
d4d7a84e11 | ||
|
|
fc7e8af55e | ||
|
|
3ec5dddb00 | ||
|
|
f47660f510 | ||
|
|
a8d6962ac2 | ||
|
|
23f75f598e | ||
|
|
e3b432cba8 | ||
|
|
557c57eb9d | ||
|
|
9d368deb05 | ||
|
|
8b99bf614c | ||
|
|
c4a3e2f6bd | ||
|
|
803f9bba27 | ||
|
|
d756efbf76 | ||
|
|
ace7fa8094 | ||
|
|
f02646e357 | ||
|
|
0a3a09aaf3 | ||
|
|
796be3282c | ||
|
|
468124fb9b | ||
|
|
3ad853630c | ||
|
|
b8708beeec | ||
|
|
8fb6c4f764 | ||
|
|
75740c1374 | ||
|
|
e8598950fc | ||
|
|
ca5c9e7496 | ||
|
|
f7818d83d7 | ||
|
|
7ef2fc2517 | ||
|
|
6df9e1c537 | ||
|
|
6a0126340a | ||
|
|
4464405250 | ||
|
|
c3807fa39d | ||
|
|
a360958be3 | ||
|
|
432f3f26a4 | ||
|
|
6ccdfff0af | ||
|
|
71e97b7123 | ||
|
|
c243aa4e15 | ||
|
|
d575321eba | ||
|
|
f353fd8864 | ||
|
|
c9a840e935 | ||
|
|
620fe1c5cf | ||
|
|
69dae32776 | ||
|
|
da0f096ba2 | ||
|
|
36fe9d539f | ||
|
|
6180b5ac7a | ||
|
|
42bfe240e0 | ||
|
|
1fb0f1ef71 | ||
|
|
1c8c9438a2 | ||
|
|
85f64786da | ||
|
|
b0910e75e0 | ||
|
|
ff1ac8ab5a | ||
|
|
4d3db99283 | ||
|
|
72b9501e69 | ||
|
|
9c169083ad | ||
|
|
7bebaab69e | ||
|
|
d8117bb8a3 | ||
|
|
df4909e5f6 | ||
|
|
79c2d80ed4 | ||
|
|
3e1b789d21 | ||
|
|
cf7135ff58 | ||
|
|
f60276f54b | ||
|
|
2b01247b30 | ||
|
|
7cf74cb864 | ||
|
|
4fb5a764df | ||
|
|
6c2dc41e0d | ||
|
|
e568f17096 | ||
|
|
1263e9788e | ||
|
|
f5132b9ee1 | ||
|
|
c95ad9cc55 | ||
|
|
3550899987 | ||
|
|
73582b145c | ||
|
|
b929c62c71 | ||
|
|
3ec8d7f598 | ||
|
|
352b743c71 | ||
|
|
b7cb91c34e | ||
|
|
f79cc460f8 | ||
|
|
757854a6cd | ||
|
|
6f4b4c80a7 | ||
|
|
ae1763e226 | ||
|
|
aa46f0e4c2 | ||
|
|
89d2b0861b | ||
|
|
4390254e6a | ||
|
|
3a27013732 | ||
|
|
d72c478128 | ||
|
|
10f4ecac26 | ||
|
|
27823d5552 | ||
|
|
19361a58ec | ||
|
|
c6c8a9ba29 | ||
|
|
14eaddfdcc | ||
|
|
8833cff911 | ||
|
|
318668aed6 | ||
|
|
9566669245 | ||
|
|
354fd906a5 | ||
|
|
2d9b3ade18 | ||
|
|
ced2cb6ce9 | ||
|
|
285501f7be | ||
|
|
0952143971 | ||
|
|
0ce53c96c3 | ||
|
|
d6f70cdd7d | ||
|
|
07d5965c81 | ||
|
|
6ca102e413 | ||
|
|
8ef6ee2a3e | ||
|
|
118abc2871 | ||
|
|
fbcf063401 | ||
|
|
e97f38e53c | ||
|
|
4cdf3eb19b | ||
|
|
ea592296b8 | ||
|
|
d426890b92 | ||
|
|
1e4d28bf14 | ||
|
|
0eac15c784 | ||
|
|
d38b9af243 | ||
|
|
18cf19f876 | ||
|
|
730c0cadde | ||
|
|
ef03cf46e4 | ||
|
|
7b8053570e | ||
|
|
85c9c83844 | ||
|
|
30642c5a6f | ||
|
|
517c964fe2 | ||
|
|
3f8700b296 | ||
|
|
048638a971 | ||
|
|
d6ed127cf4 | ||
|
|
bdaedebef9 | ||
|
|
557c88c039 | ||
|
|
d01b30cdd6 | ||
|
|
c01c77a7f2 | ||
|
|
0a549e3875 | ||
|
|
e57b86bb9f | ||
|
|
cb58fc6fa1 | ||
|
|
858e9961e2 | ||
|
|
32f2c1c3b9 | ||
|
|
e14bc1d9ac | ||
|
|
9a1f7be6fd | ||
|
|
3f85183c88 | ||
|
|
354aad4bc5 | ||
|
|
f57d012a21 | ||
|
|
f5e343efba | ||
|
|
b5edc2dea5 | ||
|
|
09a2999c66 | ||
|
|
96592d5dbb | ||
|
|
84f86be700 | ||
|
|
417cb878c3 | ||
|
|
11f2538610 | ||
|
|
ea57dfe897 | ||
|
|
9f506f57c0 | ||
|
|
57b614587c | ||
|
|
15dc1a86cd | ||
|
|
766d0df797 | ||
|
|
4507594812 | ||
|
|
8e40902d52 | ||
|
|
bc5fa9d52f | ||
|
|
11b743688c | ||
|
|
ffb3dec573 | ||
|
|
51ba48ae40 | ||
|
|
c553b6b950 | ||
|
|
541b06759f | ||
|
|
30af866e5a | ||
|
|
ebac1e1940 | ||
|
|
f7b0d130b6 | ||
|
|
c2ba7fd251 | ||
|
|
be894f09df | ||
|
|
293a8110c4 | ||
|
|
8c5d7f7dea | ||
|
|
cdb0dca39d | ||
|
|
f2908b7787 | ||
|
|
0b47e69d4d | ||
|
|
620d8d6f7c | ||
|
|
39d4b7e2bf | ||
|
|
5da7bda826 | ||
|
|
be3c874258 | ||
|
|
d8a173ddc7 | ||
|
|
8f80fecc44 | ||
|
|
7057033116 | ||
|
|
15b10dd9f3 | ||
|
|
52f4f4573e | ||
|
|
7a99b3c7cb | ||
|
|
0477a54f65 | ||
|
|
9c3de1e2a0 | ||
|
|
bba042d723 | ||
|
|
63f21cb2a5 | ||
|
|
60acef94e1 | ||
|
|
3f53f73c63 | ||
|
|
d03ba640be | ||
|
|
127d35085a | ||
|
|
bd86bf60ec | ||
|
|
3e201a99b2 | ||
|
|
9143a93312 | ||
|
|
74d5f3701f | ||
|
|
3fb6a86d02 | ||
|
|
2811a3eac8 | ||
|
|
b632f8129f | ||
|
|
df2e0db63d | ||
|
|
cc112ce96f | ||
|
|
d1efa95369 | ||
|
|
362268d2df | ||
|
|
93df5697a0 | ||
|
|
2208de0676 | ||
|
|
75349ae8c3 | ||
|
|
b3ee52c0a7 | ||
|
|
7fcbe723fc | ||
|
|
9140144d51 | ||
|
|
a5f50019bc | ||
|
|
b863ac0171 | ||
|
|
f0b3c75779 | ||
|
|
350011f581 | ||
|
|
1256307a38 | ||
|
|
a0b6ffc25b | ||
|
|
59043114ac | ||
|
|
d58da1db14 | ||
|
|
5b4c39250f | ||
|
|
82ef4ae2e1 | ||
|
|
76227f201d | ||
|
|
ff0d7a89d8 | ||
|
|
e2c02b833e | ||
|
|
65cfa18855 | ||
|
|
58703a4f4c | ||
|
|
0b60ece438 | ||
|
|
69dc8cbbc3 | ||
|
|
fadb71f2a2 | ||
|
|
aab06c6bea | ||
|
|
ad84a663be | ||
|
|
66583e8a3f | ||
|
|
66de19ace8 | ||
|
|
41a6d35e74 | ||
|
|
1485180517 | ||
|
|
f694bf0913 |
26
.gitignore
vendored
26
.gitignore
vendored
@@ -19,7 +19,9 @@
|
||||
**/*.dir/**
|
||||
**/CMakeFiles/**
|
||||
**/cmake_install.cmake
|
||||
**/install_manifest.txt
|
||||
**/CMakeCache.txt
|
||||
**/CMakeTestfile.cmake
|
||||
**/Debug/**
|
||||
**/Release/**
|
||||
build.xml
|
||||
@@ -29,8 +31,30 @@ proguard-project.txt
|
||||
linklint_results
|
||||
Makefile
|
||||
flatc
|
||||
flatc.exe
|
||||
flathash
|
||||
flathash.exe
|
||||
flattests
|
||||
flattests.exe
|
||||
flatsamplebinary
|
||||
flatsamplebinary.exe
|
||||
flatsampletext
|
||||
flatsampletext.exe
|
||||
snapshot.sh
|
||||
|
||||
tests/go_gen
|
||||
tests/monsterdata_java_wire.mon
|
||||
tests/monsterdata_go_wire.mon
|
||||
tests/monsterdata_javascript_wire.mon
|
||||
tests/unicode_test.mon
|
||||
CMakeLists.txt.user
|
||||
CMakeScripts/**
|
||||
CTestTestfile.cmake
|
||||
FlatBuffers.cbp
|
||||
build/Xcode/FlatBuffers.xcodeproj/project.xcworkspace/**
|
||||
build/Xcode/FlatBuffers.xcodeproj/xcuserdata/**
|
||||
FlatBuffers.xcodeproj/
|
||||
java/.idea
|
||||
java/*.iml
|
||||
java/target
|
||||
**/*.pyc
|
||||
.idea
|
||||
|
||||
30
.travis.yml
Normal file
30
.travis.yml
Normal file
@@ -0,0 +1,30 @@
|
||||
language: cpp
|
||||
|
||||
os:
|
||||
- linux
|
||||
- osx
|
||||
|
||||
compiler:
|
||||
- gcc
|
||||
#- clang
|
||||
|
||||
env:
|
||||
matrix:
|
||||
- BUILD_TYPE=Debug BIICODE=false
|
||||
- BUILD_TYPE=Release BIICODE=false
|
||||
- BUILD_TYPE=Release BIICODE=true
|
||||
- BUILD_TYPE=Debug BIICODE=true
|
||||
global:
|
||||
- GCC_VERSION="4.9"
|
||||
|
||||
before_install:
|
||||
- if [ "$TRAVIS_OS_NAME" == "linux" ]; then sudo add-apt-repository -y ppa:ubuntu-toolchain-r/test; fi
|
||||
- if [ "$TRAVIS_OS_NAME" == "linux" ]; then sudo apt-get update -qq; fi
|
||||
- if [ "$TRAVIS_OS_NAME" == "linux" ]; then sudo apt-get install -qq g++-$GCC_VERSION; fi
|
||||
- if [ "$TRAVIS_OS_NAME" == "linux" ]; then sudo apt-get install -qq gcc-$GCC_VERSION; fi
|
||||
- if [ "$TRAVIS_OS_NAME" == "linux" ]; then sudo ln -s -v -f $(which g++-$GCC_VERSION) /usr/bin/g++; fi
|
||||
- if [ "$TRAVIS_OS_NAME" == "linux" ]; then sudo ln -s -v -f $(which gcc-$GCC_VERSION) /usr/bin/gcc; fi
|
||||
|
||||
script:
|
||||
- if [ "$BIICODE" == "false" ]; then cmake -DCMAKE_BUILD_TYPE=$BUILD_TYPE . && make && make test; fi
|
||||
- if [ "$BIICODE" == "true" ] && [ "$TRAVIS_OS_NAME" == "linux" ]; then ./biicode/support/bii-travis.sh $BUILD_TYPE; fi
|
||||
56
CMake/FindFlatBuffers.cmake
Normal file
56
CMake/FindFlatBuffers.cmake
Normal file
@@ -0,0 +1,56 @@
|
||||
# Copyright 2014 Stefan.Eilemann@epfl.ch
|
||||
# Copyright 2014 Google Inc. All rights reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
# Find the flatbuffers schema compiler
|
||||
#
|
||||
# Output Variables:
|
||||
# * FLATBUFFERS_FLATC_EXECUTABLE the flatc compiler executable
|
||||
# * FLATBUFFERS_FOUND
|
||||
#
|
||||
# Provides:
|
||||
# * FLATBUFFERS_GENERATE_C_HEADERS(Name <files>) creates the C++ headers
|
||||
# for the given flatbuffer schema files.
|
||||
# Returns the header files in ${Name}_OUTPUTS
|
||||
|
||||
find_program(FLATBUFFERS_FLATC_EXECUTABLE NAMES flatc)
|
||||
find_path(FLATBUFFERS_INCLUDE_DIR NAMES flatbuffers/flatbuffers.h)
|
||||
|
||||
include(FindPackageHandleStandardArgs)
|
||||
find_package_handle_standard_args(flatbuffers
|
||||
DEFAULT_MSG FLATBUFFERS_FLATC_EXECUTABLE FLATBUFFERS_INCLUDE_DIR)
|
||||
|
||||
if(FLATBUFFERS_FOUND)
|
||||
function(FLATBUFFERS_GENERATE_C_HEADERS Name)
|
||||
set(FLATC_OUTPUTS)
|
||||
foreach(FILE ${ARGN})
|
||||
get_filename_component(FLATC_OUTPUT ${FILE} NAME_WE)
|
||||
set(FLATC_OUTPUT
|
||||
"${CMAKE_CURRENT_BINARY_DIR}/${FLATC_OUTPUT}_generated.h")
|
||||
list(APPEND FLATC_OUTPUTS ${FLATC_OUTPUT})
|
||||
|
||||
add_custom_command(OUTPUT ${FLATC_OUTPUT}
|
||||
COMMAND ${FLATBUFFERS_FLATC_EXECUTABLE}
|
||||
ARGS -c -o "${CMAKE_CURRENT_BINARY_DIR}/" ${FILE}
|
||||
COMMENT "Building C++ header for ${FILE}"
|
||||
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
endforeach()
|
||||
set(${Name}_OUTPUTS ${FLATC_OUTPUTS} PARENT_SCOPE)
|
||||
endfunction()
|
||||
|
||||
set(FLATBUFFERS_INCLUDE_DIRS ${FLATBUFFERS_INCLUDE_DIR})
|
||||
include_directories(${CMAKE_BINARY_DIR})
|
||||
else()
|
||||
set(FLATBUFFERS_INCLUDE_DIR)
|
||||
endif()
|
||||
145
CMakeLists.txt
145
CMakeLists.txt
@@ -4,73 +4,156 @@ project(FlatBuffers)
|
||||
|
||||
# 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_BUILD_FLATHASH "Enable the build of flathash" ON)
|
||||
|
||||
set(FlatBuffers_Compiler_SRCS
|
||||
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()
|
||||
|
||||
set(FlatBuffers_Library_SRCS
|
||||
include/flatbuffers/flatbuffers.h
|
||||
include/flatbuffers/hash.h
|
||||
include/flatbuffers/idl.h
|
||||
include/flatbuffers/util.h
|
||||
include/flatbuffers/reflection.h
|
||||
include/flatbuffers/reflection_generated.h
|
||||
src/idl_parser.cpp
|
||||
src/idl_gen_cpp.cpp
|
||||
src/idl_gen_java.cpp
|
||||
src/idl_gen_text.cpp
|
||||
src/reflection.cpp
|
||||
)
|
||||
|
||||
set(FlatBuffers_Compiler_SRCS
|
||||
${FlatBuffers_Library_SRCS}
|
||||
src/idl_gen_cpp.cpp
|
||||
src/idl_gen_general.cpp
|
||||
src/idl_gen_go.cpp
|
||||
src/idl_gen_js.cpp
|
||||
src/idl_gen_python.cpp
|
||||
src/idl_gen_fbs.cpp
|
||||
src/flatc.cpp
|
||||
)
|
||||
|
||||
set(FlatHash_SRCS
|
||||
include/flatbuffers/hash.h
|
||||
src/flathash.cpp
|
||||
)
|
||||
|
||||
set(FlatBuffers_Tests_SRCS
|
||||
include/flatbuffers/flatbuffers.h
|
||||
include/flatbuffers/idl.h
|
||||
include/flatbuffers/util.h
|
||||
src/idl_parser.cpp
|
||||
src/idl_gen_text.cpp
|
||||
${FlatBuffers_Library_SRCS}
|
||||
src/idl_gen_fbs.cpp
|
||||
src/idl_gen_general.cpp
|
||||
tests/test.cpp
|
||||
# file generate by running compiler on tests/monster_test.fbs
|
||||
tests/monster_test_generated.h
|
||||
${CMAKE_CURRENT_BINARY_DIR}/tests/monster_test_generated.h
|
||||
)
|
||||
|
||||
set(FlatBuffers_Sample_Binary_SRCS
|
||||
include/flatbuffers/flatbuffers.h
|
||||
samples/sample_binary.cpp
|
||||
# file generate by running compiler on samples/monster.fbs
|
||||
samples/monster_generated.h
|
||||
# file generated by running compiler on samples/monster.fbs
|
||||
${CMAKE_CURRENT_BINARY_DIR}/samples/monster_generated.h
|
||||
)
|
||||
|
||||
set(FlatBuffers_Sample_Text_SRCS
|
||||
include/flatbuffers/flatbuffers.h
|
||||
include/flatbuffers/hash.h
|
||||
include/flatbuffers/idl.h
|
||||
include/flatbuffers/util.h
|
||||
src/idl_parser.cpp
|
||||
src/idl_gen_text.cpp
|
||||
samples/sample_text.cpp
|
||||
# file generate by running compiler on samples/monster.fbs
|
||||
samples/monster_generated.h
|
||||
# file generated by running compiler on samples/monster.fbs
|
||||
${CMAKE_CURRENT_BINARY_DIR}/samples/monster_generated.h
|
||||
)
|
||||
|
||||
set(CMAKE_BUILD_TYPE Debug)
|
||||
|
||||
# source_group(Compiler FILES ${FlatBuffers_Compiler_SRCS})
|
||||
# source_group(Tests FILES ${FlatBuffers_Tests_SRCS})
|
||||
|
||||
if(CMAKE_COMPILER_IS_GNUCXX)
|
||||
add_definitions("-std=c++0x")
|
||||
add_definitions("-Wall")
|
||||
endif()
|
||||
if("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang")
|
||||
add_definitions("-std=c++0x")
|
||||
if(APPLE)
|
||||
set(CMAKE_CXX_FLAGS
|
||||
"${CMAKE_CXX_FLAGS} -std=c++11 -stdlib=libc++ -Wall -pedantic -Werror -Wextra")
|
||||
elseif(CMAKE_COMPILER_IS_GNUCXX)
|
||||
set(CMAKE_CXX_FLAGS
|
||||
"${CMAKE_CXX_FLAGS} -std=c++0x -Wall -pedantic -Werror -Wextra")
|
||||
elseif("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang")
|
||||
set(CMAKE_CXX_FLAGS
|
||||
"${CMAKE_CXX_FLAGS} -std=c++0x -stdlib=libc++ -Wall -pedantic -Werror -Wextra")
|
||||
endif()
|
||||
|
||||
if(FLATBUFFERS_CODE_COVERAGE)
|
||||
add_definitions("-g -fprofile-arcs -ftest-coverage")
|
||||
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -fprofile-arcs -ftest-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()
|
||||
|
||||
if(BIICODE)
|
||||
include(biicode/cmake/biicode.cmake)
|
||||
return()
|
||||
endif()
|
||||
|
||||
include_directories(include)
|
||||
|
||||
add_executable(flatc ${FlatBuffers_Compiler_SRCS})
|
||||
add_executable(flattests ${FlatBuffers_Tests_SRCS})
|
||||
add_executable(flatsamplebinary ${FlatBuffers_Sample_Binary_SRCS})
|
||||
add_executable(flatsampletext ${FlatBuffers_Sample_Text_SRCS})
|
||||
if(FLATBUFFERS_BUILD_FLATLIB)
|
||||
add_library(flatbuffers STATIC ${FlatBuffers_Library_SRCS})
|
||||
endif()
|
||||
|
||||
add_test(NAME flattest
|
||||
CONFIGURATIONS Debug
|
||||
WORKING_DIRECTORY tests
|
||||
COMMAND flattests)
|
||||
if(FLATBUFFERS_BUILD_FLATC)
|
||||
add_executable(flatc ${FlatBuffers_Compiler_SRCS})
|
||||
endif()
|
||||
|
||||
if(FLATBUFFERS_BUILD_FLATHASH)
|
||||
add_executable(flathash ${FlatHash_SRCS})
|
||||
endif()
|
||||
|
||||
function(compile_flatbuffers_schema_to_cpp SRC_FBS)
|
||||
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 flatc -c --no-includes --gen-mutable -o "${SRC_FBS_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/${SRC_FBS}"
|
||||
DEPENDS flatc)
|
||||
endfunction()
|
||||
|
||||
function(compile_flatbuffers_schema_to_binary SRC_FBS)
|
||||
get_filename_component(SRC_FBS_DIR ${SRC_FBS} PATH)
|
||||
string(REGEX REPLACE "\\.fbs$" ".bfbs" GEN_BINARY_SCHEMA ${SRC_FBS})
|
||||
add_custom_command(
|
||||
OUTPUT ${GEN_BINARY_SCHEMA}
|
||||
COMMAND flatc -b --schema -o "${SRC_FBS_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/${SRC_FBS}"
|
||||
DEPENDS flatc)
|
||||
endfunction()
|
||||
|
||||
if(FLATBUFFERS_BUILD_TESTS)
|
||||
compile_flatbuffers_schema_to_cpp(tests/monster_test.fbs)
|
||||
include_directories(${CMAKE_CURRENT_BINARY_DIR}/tests)
|
||||
add_executable(flattests ${FlatBuffers_Tests_SRCS})
|
||||
|
||||
compile_flatbuffers_schema_to_cpp(samples/monster.fbs)
|
||||
include_directories(${CMAKE_CURRENT_BINARY_DIR}/samples)
|
||||
add_executable(flatsamplebinary ${FlatBuffers_Sample_Binary_SRCS})
|
||||
add_executable(flatsampletext ${FlatBuffers_Sample_Text_SRCS})
|
||||
endif()
|
||||
|
||||
if(FLATBUFFERS_INSTALL)
|
||||
install(DIRECTORY include/flatbuffers DESTINATION include)
|
||||
if(FLATBUFFERS_BUILD_FLATLIB)
|
||||
install(TARGETS flatbuffers DESTINATION lib)
|
||||
endif()
|
||||
if(FLATBUFFERS_BUILD_FLATC)
|
||||
install(TARGETS flatc DESTINATION bin)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
if(FLATBUFFERS_BUILD_TESTS)
|
||||
enable_testing()
|
||||
|
||||
file(COPY "${CMAKE_CURRENT_SOURCE_DIR}/tests" DESTINATION
|
||||
"${CMAKE_CURRENT_BINARY_DIR}")
|
||||
add_test(NAME flattests COMMAND flattests)
|
||||
endif()
|
||||
|
||||
42
CONTRIBUTING.md
Normal file
42
CONTRIBUTING.md
Normal file
@@ -0,0 +1,42 @@
|
||||
Contributing {#contributing}
|
||||
============
|
||||
|
||||
Want to contribute? Great! First, read this page (including the small print at
|
||||
the end).
|
||||
|
||||
# Before you contribute
|
||||
Before we can use your code, you must sign the
|
||||
[Google Individual Contributor License Agreement](https://developers.google.com/open-source/cla/individual?csw=1)
|
||||
(CLA), which you can do online. The CLA is necessary mainly because you own the
|
||||
copyright to your changes, even after your contribution becomes part of our
|
||||
codebase, so we need your permission to use and distribute your code. We also
|
||||
need to be sure of various other things—for instance that you'll tell us if you
|
||||
know that your code infringes on other people's patents. You don't have to sign
|
||||
the CLA until after you've submitted your code for review and a member has
|
||||
approved it, but you must do it before we can put your code into our codebase.
|
||||
Before you start working on a larger contribution, you should get in touch with
|
||||
us first through the issue tracker with your idea so that we can help out and
|
||||
possibly guide you. Coordinating up front makes it much easier to avoid
|
||||
frustration later on.
|
||||
|
||||
# Code reviews
|
||||
All submissions, including submissions by project members, require review. We
|
||||
use Github pull requests for this purpose.
|
||||
|
||||
Some tips for good pull requests:
|
||||
* Use our code
|
||||
[style guide](http://google-styleguide.googlecode.com/svn/trunk/cppguide.html).
|
||||
When in doubt, try to stay true to the existing code of the project.
|
||||
* Write a descriptive commit message. What problem are you solving and what
|
||||
are the consequences? Where and what did you test? Some good tips:
|
||||
[here](http://robots.thoughtbot.com/5-useful-tips-for-a-better-commit-message)
|
||||
and [here](https://www.kernel.org/doc/Documentation/SubmittingPatches).
|
||||
* If your PR consists of multiple commits which are successive improvements /
|
||||
fixes to your first commit, consider squashing them into a single commit
|
||||
(`git rebase -i`) such that your PR is a single commit on top of the current
|
||||
HEAD. This make reviewing the code so much easier, and our history more
|
||||
readable.
|
||||
|
||||
# The small print
|
||||
Contributions made by corporations are covered by a different agreement than
|
||||
the one above, the Software Grant and Corporate Contributor License Agreement.
|
||||
2
LICENSE.txt
Executable file → Normal file
2
LICENSE.txt
Executable file → Normal file
@@ -187,7 +187,7 @@
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
Copyright 2014 Google Inc.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
|
||||
@@ -235,10 +235,16 @@ select_android_build_target() {
|
||||
local android_build_target=
|
||||
for android_target in $(echo "${android_targets_installed}" | \
|
||||
awk -F- '{ print $2 }' | sort -n); do
|
||||
if [[ $((android_target)) -ge \
|
||||
local isNumber='^[0-9]+$'
|
||||
# skip preview API releases e.g. 'android-L'
|
||||
if [[ $android_target =~ $isNumber ]]; then
|
||||
if [[ $((android_target)) -ge \
|
||||
$((BUILDAPK_ANDROID_TARGET_MINVERSION)) ]]; then
|
||||
android_build_target="android-${android_target}"
|
||||
break
|
||||
android_build_target="android-${android_target}"
|
||||
break
|
||||
fi
|
||||
# else
|
||||
# The API version is a letter, so skip it.
|
||||
fi
|
||||
done
|
||||
if [[ "${android_build_target}" == "" ]]; then
|
||||
@@ -415,14 +421,18 @@ main() {
|
||||
local build_package=1
|
||||
for opt; do
|
||||
case ${opt} in
|
||||
# NDK_DEBUG=0 tells ndk-build to build this as debuggable but to not
|
||||
# modify the underlying code whereas NDK_DEBUG=1 also builds as debuggable
|
||||
# but does modify the code
|
||||
NDK_DEBUG=1) ant_target=debug ;;
|
||||
NDK_DEBUG=0) ant_target=debug ;;
|
||||
ADB_DEVICE*) adb_device="$(\
|
||||
echo "${opt}" | sed -E 's/^ADB_DEVICE=([^ ]+)$/-s \1/;t;s/.*//')" ;;
|
||||
BUILD=0) disable_build=1 ;;
|
||||
DEPLOY=0) disable_deploy=1 ;;
|
||||
RUN_DEBUGGER=1) run_debugger=1 ;;
|
||||
LAUNCH=0) launch=0 ;;
|
||||
clean) build_package=0 ;;
|
||||
clean) build_package=0 disable_deploy=1 launch=0 ;;
|
||||
-h|--help|help) usage ;;
|
||||
esac
|
||||
done
|
||||
|
||||
@@ -16,16 +16,27 @@
|
||||
|
||||
LOCAL_PATH := $(call my-dir)
|
||||
|
||||
# Empty static library so that other projects can include FlatBuffers as a
|
||||
# module.
|
||||
include $(CLEAR_VARS)
|
||||
LOCAL_MODULE := flatbuffers
|
||||
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/../../include
|
||||
LOCAL_EXPORT_CPPFLAGS := -std=c++11 -fexceptions -Wall -Wno-literal-suffix
|
||||
include $(BUILD_STATIC_LIBRARY)
|
||||
|
||||
LOCAL_MODULE := FlatBufferTest
|
||||
LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../include
|
||||
LOCAL_SRC_FILES := main.cpp ../../tests/test.cpp ../../src/idl_parser.cpp ../../src/idl_gen_text.cpp
|
||||
LOCAL_LDLIBS := -llog -landroid
|
||||
LOCAL_STATIC_LIBRARIES := android_native_app_glue
|
||||
LOCAL_ARM_MODE:=arm
|
||||
LOCAL_CPPFLAGS += -std=c++11 -fexceptions -Wall -Wno-literal-suffix
|
||||
|
||||
# FlatBuffers test
|
||||
include $(CLEAR_VARS)
|
||||
LOCAL_MODULE := FlatBufferTest
|
||||
LOCAL_SRC_FILES := main.cpp \
|
||||
../../tests/test.cpp \
|
||||
../../src/idl_parser.cpp \
|
||||
../../src/idl_gen_text.cpp \
|
||||
../../src/idl_gen_fbs.cpp \
|
||||
../../src/idl_gen_general.cpp \
|
||||
../../src/reflection.cpp
|
||||
LOCAL_LDLIBS := -llog -landroid
|
||||
LOCAL_STATIC_LIBRARIES := android_native_app_glue flatbuffers
|
||||
LOCAL_ARM_MODE := arm
|
||||
include $(BUILD_SHARED_LIBRARY)
|
||||
|
||||
$(call import-module,android/native_app_glue)
|
||||
|
||||
208
android/jni/include.mk
Normal file
208
android/jni/include.mk
Normal file
@@ -0,0 +1,208 @@
|
||||
# Copyright 2014 Google Inc. All rights reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
# This file contains utility functions for Android projects using Flatbuffers.
|
||||
# To use this file, include it in your project's Android.mk by calling near the
|
||||
# top of your android makefile like so:
|
||||
#
|
||||
# include $(FLATBUFFERS_DIR)/android/jni/include.mk
|
||||
#
|
||||
# You will also need to import the flatbuffers module using the standard
|
||||
# import-module function.
|
||||
#
|
||||
# The main functionality this file provides are the following functions:
|
||||
# flatbuffers_fbs_to_h: Converts flatbuffer schema paths to header paths.
|
||||
# flatbuffers_header_build_rule:
|
||||
# Creates a build rule for a schema's generated header. This build rule
|
||||
# has a dependency on the flatc compiler which will be built if necessary.
|
||||
# flatbuffers_header_build_rules:
|
||||
# Creates build rules for generated headers for each schema listed and sets
|
||||
# up depenedendies.
|
||||
#
|
||||
# More information and example usage can be found in the comments preceeding
|
||||
# each function.
|
||||
|
||||
# Targets to build the Flatbuffers compiler as well as some utility definitions
|
||||
ifeq (,$(FLATBUFFERS_INCLUDE_MK_))
|
||||
FLATBUFFERS_INCLUDE_MK_ := 1
|
||||
|
||||
PROJECT_OS := $(OS)
|
||||
ifeq (,$(OS))
|
||||
PROJECT_OS := $(shell uname -s)
|
||||
else
|
||||
ifneq ($(findstring Windows,$(PROJECT_OS)),)
|
||||
PROJECT_OS := Windows
|
||||
endif
|
||||
endif
|
||||
|
||||
# The following block generates build rules which result in headers being
|
||||
# rebuilt from flatbuffers schemas.
|
||||
|
||||
FLATBUFFERS_CMAKELISTS_DIR := \
|
||||
$(realpath $(dir $(lastword $(MAKEFILE_LIST)))/../..)
|
||||
|
||||
# Directory that contains the FlatBuffers compiler.
|
||||
ifeq (Windows,$(PROJECT_OS))
|
||||
FLATBUFFERS_FLATC_PATH?=$(CURDIR)/bin
|
||||
FLATBUFFERS_FLATC := $(FLATBUFFERS_FLATC_PATH)/Debug/flatc.exe
|
||||
endif
|
||||
ifeq (Linux,$(PROJECT_OS))
|
||||
FLATBUFFERS_FLATC_PATH?=$(CURDIR)/bin
|
||||
FLATBUFFERS_FLATC := $(FLATBUFFERS_FLATC_PATH)/flatc
|
||||
endif
|
||||
ifeq (Darwin,$(PROJECT_OS))
|
||||
FLATBUFFERS_FLATC_PATH?=$(FLATBUFFERS_CMAKELISTS_DIR)
|
||||
FLATBUFFERS_FLATC := $(FLATBUFFERS_FLATC_PATH)/Debug/flatc
|
||||
endif
|
||||
|
||||
FLATBUFFERS_FLATC_ARGS?=
|
||||
|
||||
# Search for cmake.
|
||||
CMAKE_ROOT := $(realpath $(LOCAL_PATH)/../../../../../../prebuilts/cmake)
|
||||
ifeq (,$(CMAKE))
|
||||
ifeq (Linux,$(PROJECT_OS))
|
||||
CMAKE := $(wildcard $(CMAKE_ROOT)/linux-x86/current/bin/cmake*)
|
||||
endif
|
||||
ifeq (Darwin,$(PROJECT_OS))
|
||||
CMAKE := \
|
||||
$(wildcard $(CMAKE_ROOT)/darwin-x86_64/current/*.app/Contents/bin/cmake)
|
||||
endif
|
||||
ifeq (Windows,$(PROJECT_OS))
|
||||
CMAKE := $(wildcard $(CMAKE_ROOT)/windows/current/bin/cmake*)
|
||||
endif
|
||||
endif
|
||||
ifeq (,$(CMAKE))
|
||||
CMAKE := cmake
|
||||
endif
|
||||
|
||||
# Windows friendly portable local path.
|
||||
# GNU-make doesn't like : in paths, must use relative paths on Windows.
|
||||
ifeq (Windows,$(PROJECT_OS))
|
||||
PORTABLE_LOCAL_PATH =
|
||||
else
|
||||
PORTABLE_LOCAL_PATH = $(LOCAL_PATH)/
|
||||
endif
|
||||
|
||||
# Generate a host build rule for the flatbuffers compiler.
|
||||
ifeq (Windows,$(PROJECT_OS))
|
||||
define build_flatc_recipe
|
||||
cd & jni\build_flatc.bat $(CMAKE)
|
||||
endef
|
||||
endif
|
||||
ifeq (Linux,$(PROJECT_OS))
|
||||
define build_flatc_recipe
|
||||
mkdir -p bin && cd bin && $(CMAKE) $(FLATBUFFERS_CMAKELISTS_DIR) \
|
||||
&& $(MAKE) flatc
|
||||
endef
|
||||
endif
|
||||
ifeq (Darwin,$(PROJECT_OS))
|
||||
define build_flatc_recipe
|
||||
cd $(FLATBUFFERS_CMAKELISTS_DIR) && "$(CMAKE)" -GXcode . && \
|
||||
xcodebuild -target flatc
|
||||
endef
|
||||
endif
|
||||
ifeq (,$(build_flatc_recipe))
|
||||
ifeq (,$(FLATBUFFERS_FLATC))
|
||||
$(error flatc binary not found!)
|
||||
endif
|
||||
endif
|
||||
|
||||
# Generate a build rule for flatc.
|
||||
ifeq ($(strip $(FLATBUFFERS_FLATC)),)
|
||||
flatc_target := build_flatc
|
||||
.PHONY: $(flatc_target)
|
||||
else
|
||||
flatc_target := $(FLATBUFFERS_FLATC)
|
||||
endif
|
||||
$(flatc_target):
|
||||
$(call build_flatc_recipe)
|
||||
|
||||
# $(flatbuffers_fbs_to_h schema_dir,output_dir,path)
|
||||
#
|
||||
# Convert the specified schema path to a Flatbuffers generated header path.
|
||||
# For example:
|
||||
#
|
||||
# $(call flatbuffers_fbs_to_h,$(MY_PROJ_DIR)/schemas,\
|
||||
# $(MY_PROJ_DIR)/gen/include,$(MY_PROJ_DIR)/schemas/example.fbs)
|
||||
#
|
||||
# This will convert the file path `$(MY_PROJ_DIR)/schemas/example.fbs)` to
|
||||
# `$(MY_PROJ_DIR)/gen/include/example_generated.h`
|
||||
define flatbuffers_fbs_to_h
|
||||
$(subst $(1),$(2),$(patsubst %.fbs,%_generated.h,$(3)))
|
||||
endef
|
||||
|
||||
# $(flatbuffers_header_build_rule schema_file,schema_dir,output_dir,\
|
||||
# schema_include_dirs)
|
||||
#
|
||||
# Generate a build rule that will convert a Flatbuffers schema to a generated
|
||||
# header derived from the schema filename using flatbuffers_fbs_to_h. For
|
||||
# example:
|
||||
#
|
||||
# $(call flatbuffers_header_build_rule,$(MY_PROJ_DIR)/schemas/example.fbs,\
|
||||
# $(MY_PROJ_DIR)/schemas,$(MY_PROJ_DIR)/gen/include)
|
||||
#
|
||||
# The final argument, schema_include_dirs, is optional and is only needed when
|
||||
# the schema files depend on other schema files outside their own directory.
|
||||
define flatbuffers_header_build_rule
|
||||
$(eval \
|
||||
$(call flatbuffers_fbs_to_h,$(2),$(3),$(1)): $(1) $(flatc_target)
|
||||
$(call host-echo-build-step,generic,Generate) \
|
||||
$(subst $(LOCAL_PATH)/,,$(call flatbuffers_fbs_to_h,$(2),$(3),$(1)))
|
||||
$(hide) $$(FLATBUFFERS_FLATC) $(FLATBUFFERS_FLATC_ARGS) \
|
||||
$(foreach include,$(4),-I $(include)) -o $$(dir $$@) -c $$<)
|
||||
endef
|
||||
|
||||
# $(flatbuffers_header_build_rules schema_files,schema_dir,output_dir,\
|
||||
# schema_include_dirs,src_files,[build_target],[dependencies]))
|
||||
#
|
||||
# $(1) schema_files: Space separated list of flatbuffer schema files.
|
||||
# $(2) schema_dir: Directory containing the flatbuffer schemas.
|
||||
# $(3) output_dir: Where to place the generated files.
|
||||
# $(4) schema_include_dirs: Directories to include when generating schemas.
|
||||
# $(5) src_files: Files that should depend upon the headers generated from the
|
||||
# flatbuffer schemas.
|
||||
# $(6) build_target: Name of a build target that depends upon all generated
|
||||
# headers.
|
||||
# $(7) dependencies: Space seperated list of additional build targets src_files
|
||||
# should depend upon.
|
||||
#
|
||||
# Use this in your own Android.mk file to generate build rules that will
|
||||
# generate header files for your flatbuffer schemas as well as automatically
|
||||
# set your source files to be dependent on the generated headers. For example:
|
||||
#
|
||||
# $(call flatbuffers_header_build_rules,$(MY_PROJ_SCHEMA_FILES),\
|
||||
# $(MY_PROJ_SCHEMA_DIR),$(MY_PROJ_GENERATED_OUTPUT_DIR),
|
||||
# $(MY_PROJ_SCHEMA_INCLUDE_DIRS),$(LOCAL_SRC_FILES))
|
||||
define flatbuffers_header_build_rules
|
||||
$(foreach schema,$(1),\
|
||||
$(call flatbuffers_header_build_rule,\
|
||||
$(schema),$(strip $(2)),$(strip $(3)),$(strip $(4))))\
|
||||
$(foreach src,$(strip $(5)),\
|
||||
$(eval $(PORTABLE_LOCAL_PATH)$$(src): \
|
||||
$(foreach schema,$(strip $(1)),\
|
||||
$(call flatbuffers_fbs_to_h,$(strip $(2)),$(strip $(3)),$(schema)))))\
|
||||
$(if $(6),\
|
||||
$(foreach schema,$(strip $(1)),\
|
||||
$(eval $(6): \
|
||||
$(call flatbuffers_fbs_to_h,$(strip $(2)),$(strip $(3)),$(schema)))),)\
|
||||
$(if $(7),\
|
||||
$(foreach src,$(strip $(5)),\
|
||||
$(eval $(PORTABLE_LOCAL_PATH)$$(src): $(strip $(7)))),)\
|
||||
$(if $(7),\
|
||||
$(foreach dependency,$(strip $(7)),\
|
||||
$(eval $(6): $(dependency))),)
|
||||
endef
|
||||
|
||||
endif # FLATBUFFERS_INCLUDE_MK_
|
||||
|
||||
0
android/jni/main.cpp
Executable file → Normal file
0
android/jni/main.cpp
Executable file → Normal file
7
biicode.conf
Normal file
7
biicode.conf
Normal file
@@ -0,0 +1,7 @@
|
||||
# Biicode configuration file
|
||||
[paths]
|
||||
include
|
||||
[mains]
|
||||
!android/*
|
||||
[tests]
|
||||
tests/*
|
||||
21
biicode/README.md
Normal file
21
biicode/README.md
Normal file
@@ -0,0 +1,21 @@
|
||||
Biicode C/C++ dependency manager
|
||||
=================================
|
||||
|
||||
[](https://www.biicode.com/fenix/flatbuffers)
|
||||
|
||||
New with biicode? Check the [Getting Started Guide](http://docs.biicode.com/c++/gettingstarted.html).
|
||||
|
||||
How to build it?
|
||||
------------------
|
||||
Building it is too easy:
|
||||
|
||||
$ git clone git@github.com:google/flatbuffers.git
|
||||
$ cd flatbuffers
|
||||
$ bii init -L && bii build
|
||||
$ ./bin/any_executable
|
||||
|
||||
Or run its tests:
|
||||
|
||||
$ bii test
|
||||
|
||||
You can check [the examples/flatbuffers block](https://www.biicode.com/examples/flatbuffers).
|
||||
18
biicode/cmake/biicode.cmake
Normal file
18
biicode/cmake/biicode.cmake
Normal file
@@ -0,0 +1,18 @@
|
||||
set(BII_TESTS_WORKING_DIR ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
# Copying data files to project/bin folder
|
||||
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/samples")
|
||||
file(COPY "${CMAKE_CURRENT_SOURCE_DIR}/samples/monster.fbs"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/samples/monsterdata.json"
|
||||
DESTINATION
|
||||
"${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/samples")
|
||||
endif()
|
||||
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests")
|
||||
file(COPY "${CMAKE_CURRENT_SOURCE_DIR}/tests"
|
||||
DESTINATION
|
||||
"${CMAKE_RUNTIME_OUTPUT_DIRECTORY}")
|
||||
endif()
|
||||
|
||||
ADD_BIICODE_TARGETS()
|
||||
|
||||
string(REPLACE " " ";" REPLACED_FLAGS ${CMAKE_CXX_FLAGS})
|
||||
target_compile_options(${BII_BLOCK_TARGET} INTERFACE ${REPLACED_FLAGS})
|
||||
16
biicode/support/bii-travis.sh
Executable file
16
biicode/support/bii-travis.sh
Executable file
@@ -0,0 +1,16 @@
|
||||
#!/bin/bash
|
||||
|
||||
sudo apt-get update -qq
|
||||
sudo apt-get install libglu1-mesa-dev xorg-dev
|
||||
wget http://www.biicode.com/downloads/latest/ubuntu64
|
||||
mv ubuntu64 bii-ubuntu64.deb
|
||||
(sudo dpkg -i bii-ubuntu64.deb) && sudo apt-get -f install
|
||||
rm bii-ubuntu64.deb
|
||||
wget https://s3.amazonaws.com/biibinaries/thirdparty/cmake-3.0.2-Linux-64.tar.gz
|
||||
tar -xzf cmake-3.0.2-Linux-64.tar.gz
|
||||
sudo cp -fR cmake-3.0.2-Linux-64/* /usr
|
||||
rm -rf cmake-3.0.2-Linux-64
|
||||
rm cmake-3.0.2-Linux-64.tar.gz
|
||||
|
||||
cmake --version
|
||||
bii init -l && bii configure -DCMAKE_BUILD_TYPE=$1 && bii test
|
||||
@@ -11,43 +11,43 @@ EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Win32 = Debug|Win32
|
||||
MinSizeRel|Win32 = MinSizeRel|Win32
|
||||
Debug|x64 = Debug|x64
|
||||
Release|Win32 = Release|Win32
|
||||
RelWithDebInfo|Win32 = RelWithDebInfo|Win32
|
||||
Release|x64 = Release|x64
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{5B5857E1-64E2-4CED-A12E-45E1B3880496}.Debug|Win32.ActiveCfg = Debug|Win32
|
||||
{5B5857E1-64E2-4CED-A12E-45E1B3880496}.Debug|Win32.Build.0 = Debug|Win32
|
||||
{5B5857E1-64E2-4CED-A12E-45E1B3880496}.MinSizeRel|Win32.ActiveCfg = Release|Win32
|
||||
{5B5857E1-64E2-4CED-A12E-45E1B3880496}.MinSizeRel|Win32.Build.0 = Release|Win32
|
||||
{5B5857E1-64E2-4CED-A12E-45E1B3880496}.Debug|x64.ActiveCfg = Debug|x64
|
||||
{5B5857E1-64E2-4CED-A12E-45E1B3880496}.Debug|x64.Build.0 = Debug|x64
|
||||
{5B5857E1-64E2-4CED-A12E-45E1B3880496}.Release|Win32.ActiveCfg = Release|Win32
|
||||
{5B5857E1-64E2-4CED-A12E-45E1B3880496}.Release|Win32.Build.0 = Release|Win32
|
||||
{5B5857E1-64E2-4CED-A12E-45E1B3880496}.RelWithDebInfo|Win32.ActiveCfg = Release|Win32
|
||||
{5B5857E1-64E2-4CED-A12E-45E1B3880496}.RelWithDebInfo|Win32.Build.0 = Release|Win32
|
||||
{5B5857E1-64E2-4CED-A12E-45E1B3880496}.Release|x64.ActiveCfg = Release|x64
|
||||
{5B5857E1-64E2-4CED-A12E-45E1B3880496}.Release|x64.Build.0 = Release|x64
|
||||
{16FA5518-3DE1-4B15-A1E0-F4734C276FB4}.Debug|Win32.ActiveCfg = Debug|Win32
|
||||
{16FA5518-3DE1-4B15-A1E0-F4734C276FB4}.Debug|Win32.Build.0 = Debug|Win32
|
||||
{16FA5518-3DE1-4B15-A1E0-F4734C276FB4}.MinSizeRel|Win32.ActiveCfg = Release|Win32
|
||||
{16FA5518-3DE1-4B15-A1E0-F4734C276FB4}.MinSizeRel|Win32.Build.0 = Release|Win32
|
||||
{16FA5518-3DE1-4B15-A1E0-F4734C276FB4}.Debug|x64.ActiveCfg = Debug|x64
|
||||
{16FA5518-3DE1-4B15-A1E0-F4734C276FB4}.Debug|x64.Build.0 = Debug|x64
|
||||
{16FA5518-3DE1-4B15-A1E0-F4734C276FB4}.Release|Win32.ActiveCfg = Release|Win32
|
||||
{16FA5518-3DE1-4B15-A1E0-F4734C276FB4}.Release|Win32.Build.0 = Release|Win32
|
||||
{16FA5518-3DE1-4B15-A1E0-F4734C276FB4}.RelWithDebInfo|Win32.ActiveCfg = Release|Win32
|
||||
{16FA5518-3DE1-4B15-A1E0-F4734C276FB4}.RelWithDebInfo|Win32.Build.0 = Release|Win32
|
||||
{16FA5518-3DE1-4B15-A1E0-F4734C276FB4}.Release|x64.ActiveCfg = Release|x64
|
||||
{16FA5518-3DE1-4B15-A1E0-F4734C276FB4}.Release|x64.Build.0 = Release|x64
|
||||
{F0A15675-1017-4217-BB5B-3372F2C636AB}.Debug|Win32.ActiveCfg = Debug|Win32
|
||||
{F0A15675-1017-4217-BB5B-3372F2C636AB}.Debug|Win32.Build.0 = Debug|Win32
|
||||
{F0A15675-1017-4217-BB5B-3372F2C636AB}.MinSizeRel|Win32.ActiveCfg = Release|Win32
|
||||
{F0A15675-1017-4217-BB5B-3372F2C636AB}.MinSizeRel|Win32.Build.0 = Release|Win32
|
||||
{F0A15675-1017-4217-BB5B-3372F2C636AB}.Debug|x64.ActiveCfg = Debug|x64
|
||||
{F0A15675-1017-4217-BB5B-3372F2C636AB}.Debug|x64.Build.0 = Debug|x64
|
||||
{F0A15675-1017-4217-BB5B-3372F2C636AB}.Release|Win32.ActiveCfg = Release|Win32
|
||||
{F0A15675-1017-4217-BB5B-3372F2C636AB}.Release|Win32.Build.0 = Release|Win32
|
||||
{F0A15675-1017-4217-BB5B-3372F2C636AB}.RelWithDebInfo|Win32.ActiveCfg = Release|Win32
|
||||
{F0A15675-1017-4217-BB5B-3372F2C636AB}.RelWithDebInfo|Win32.Build.0 = Release|Win32
|
||||
{F0A15675-1017-4217-BB5B-3372F2C636AB}.Release|x64.ActiveCfg = Release|x64
|
||||
{F0A15675-1017-4217-BB5B-3372F2C636AB}.Release|x64.Build.0 = Release|x64
|
||||
{DC7BBA00-9FC6-48AF-B7E9-12CA91AC02AA}.Debug|Win32.ActiveCfg = Debug|Win32
|
||||
{DC7BBA00-9FC6-48AF-B7E9-12CA91AC02AA}.Debug|Win32.Build.0 = Debug|Win32
|
||||
{DC7BBA00-9FC6-48AF-B7E9-12CA91AC02AA}.MinSizeRel|Win32.ActiveCfg = Release|Win32
|
||||
{DC7BBA00-9FC6-48AF-B7E9-12CA91AC02AA}.MinSizeRel|Win32.Build.0 = Release|Win32
|
||||
{DC7BBA00-9FC6-48AF-B7E9-12CA91AC02AA}.Debug|x64.ActiveCfg = Debug|x64
|
||||
{DC7BBA00-9FC6-48AF-B7E9-12CA91AC02AA}.Debug|x64.Build.0 = Debug|x64
|
||||
{DC7BBA00-9FC6-48AF-B7E9-12CA91AC02AA}.Release|Win32.ActiveCfg = Release|Win32
|
||||
{DC7BBA00-9FC6-48AF-B7E9-12CA91AC02AA}.Release|Win32.Build.0 = Release|Win32
|
||||
{DC7BBA00-9FC6-48AF-B7E9-12CA91AC02AA}.RelWithDebInfo|Win32.ActiveCfg = Release|Win32
|
||||
{DC7BBA00-9FC6-48AF-B7E9-12CA91AC02AA}.RelWithDebInfo|Win32.Build.0 = Release|Win32
|
||||
{DC7BBA00-9FC6-48AF-B7E9-12CA91AC02AA}.Release|x64.ActiveCfg = Release|x64
|
||||
{DC7BBA00-9FC6-48AF-B7E9-12CA91AC02AA}.Release|x64.Build.0 = Release|x64
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
|
||||
@@ -5,10 +5,18 @@
|
||||
<Configuration>Debug</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Debug|x64">
|
||||
<Configuration>Debug</Configuration>
|
||||
<Platform>x64</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release|Win32">
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release|x64">
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>x64</Platform>
|
||||
</ProjectConfiguration>
|
||||
</ItemGroup>
|
||||
<PropertyGroup Label="Globals">
|
||||
<ProjectGUID>{5B5857E1-64E2-4CED-A12E-45E1B3880496}</ProjectGUID>
|
||||
@@ -22,11 +30,21 @@
|
||||
<UseOfMfc>false</UseOfMfc>
|
||||
<CharacterSet>MultiByte</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseOfMfc>false</UseOfMfc>
|
||||
<CharacterSet>MultiByte</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseOfMfc>false</UseOfMfc>
|
||||
<CharacterSet>MultiByte</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseOfMfc>false</UseOfMfc>
|
||||
<CharacterSet>MultiByte</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
|
||||
<ImportGroup Label="ExtensionSettings">
|
||||
</ImportGroup>
|
||||
@@ -37,17 +55,29 @@
|
||||
<PropertyGroup>
|
||||
<_ProjectFileVersion>10.0.20506.1</_ProjectFileVersion>
|
||||
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(IntDir)</OutDir>
|
||||
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(IntDir)</OutDir>
|
||||
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">flatc.dir\Debug\</IntDir>
|
||||
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">flatc.dir\Debug\</IntDir>
|
||||
<TargetName Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">flatc</TargetName>
|
||||
<TargetName Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">flatc</TargetName>
|
||||
<TargetExt Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">.exe</TargetExt>
|
||||
<TargetExt Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">.exe</TargetExt>
|
||||
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>
|
||||
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</LinkIncremental>
|
||||
<GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</GenerateManifest>
|
||||
<GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</GenerateManifest>
|
||||
<OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(IntDir)</OutDir>
|
||||
<OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(IntDir)</OutDir>
|
||||
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">flatc.dir\Release\</IntDir>
|
||||
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">flatc.dir\Release\</IntDir>
|
||||
<TargetName Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">flatc</TargetName>
|
||||
<TargetName Condition="'$(Configuration)|$(Platform)'=='Release|x64'">flatc</TargetName>
|
||||
<TargetExt Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">.exe</TargetExt>
|
||||
<TargetExt Condition="'$(Configuration)|$(Platform)'=='Release|x64'">.exe</TargetExt>
|
||||
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>
|
||||
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</LinkIncremental>
|
||||
<GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</GenerateManifest>
|
||||
<GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</GenerateManifest>
|
||||
</PropertyGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
|
||||
<ClCompile>
|
||||
@@ -61,11 +91,12 @@
|
||||
<PrecompiledHeader>NotUsing</PrecompiledHeader>
|
||||
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
|
||||
<RuntimeTypeInfo>true</RuntimeTypeInfo>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<WarningLevel>Level4</WarningLevel>
|
||||
<PreprocessorDefinitions>WIN32;_WINDOWS;_DEBUG;CMAKE_INTDIR="Debug";%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<AssemblerListingLocation>Debug</AssemblerListingLocation>
|
||||
<ObjectFileName>$(IntDir)</ObjectFileName>
|
||||
<ProgramDataBaseFileName>../../Debug/flatc.pdb</ProgramDataBaseFileName>
|
||||
<TreatWarningAsError>true</TreatWarningAsError>
|
||||
</ClCompile>
|
||||
<ResourceCompile>
|
||||
<PreprocessorDefinitions>WIN32;_WINDOWS;_DEBUG;CMAKE_INTDIR=\"Debug\";%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
@@ -94,6 +125,52 @@
|
||||
<LinkLibraryDependencies>false</LinkLibraryDependencies>
|
||||
</ProjectReference>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
|
||||
<ClCompile>
|
||||
<AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
|
||||
<CompileAs>CompileAsCpp</CompileAs>
|
||||
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
|
||||
<ExceptionHandling>Sync</ExceptionHandling>
|
||||
<InlineFunctionExpansion>Disabled</InlineFunctionExpansion>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<PrecompiledHeader>NotUsing</PrecompiledHeader>
|
||||
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
|
||||
<RuntimeTypeInfo>true</RuntimeTypeInfo>
|
||||
<WarningLevel>Level4</WarningLevel>
|
||||
<PreprocessorDefinitions>WIN32;_WINDOWS;_DEBUG;CMAKE_INTDIR="Debug";%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<AssemblerListingLocation>Debug</AssemblerListingLocation>
|
||||
<ObjectFileName>$(IntDir)</ObjectFileName>
|
||||
<ProgramDataBaseFileName>../../Debug/flatc.pdb</ProgramDataBaseFileName>
|
||||
<TreatWarningAsError>true</TreatWarningAsError>
|
||||
</ClCompile>
|
||||
<ResourceCompile>
|
||||
<PreprocessorDefinitions>WIN32;_WINDOWS;_DEBUG;CMAKE_INTDIR=\"Debug\";%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
</ResourceCompile>
|
||||
<Midl>
|
||||
<AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<OutputDirectory>$(IntDir)</OutputDirectory>
|
||||
<HeaderFileName>%(Filename).h</HeaderFileName>
|
||||
<TypeLibraryName>%(Filename).tlb</TypeLibraryName>
|
||||
<InterfaceIdentifierFileName>%(Filename)_i.c</InterfaceIdentifierFileName>
|
||||
<ProxyFileName>%(Filename)_p.c</ProxyFileName>
|
||||
</Midl>
|
||||
<Link>
|
||||
<AdditionalOptions>/debug %(AdditionalOptions)</AdditionalOptions>
|
||||
<AdditionalDependencies>kernel32.lib;user32.lib;gdi32.lib;winspool.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;comdlg32.lib;advapi32.lib</AdditionalDependencies>
|
||||
<AdditionalLibraryDirectories>%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<ImportLibrary>../../Debug/flatc.lib</ImportLibrary>
|
||||
<ProgramDataBaseFile>../../Debug/flatc.pdb</ProgramDataBaseFile>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<Version>
|
||||
</Version>
|
||||
</Link>
|
||||
<ProjectReference>
|
||||
<LinkLibraryDependencies>false</LinkLibraryDependencies>
|
||||
</ProjectReference>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||
<ClCompile>
|
||||
<AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
@@ -104,13 +181,14 @@
|
||||
<PrecompiledHeader>NotUsing</PrecompiledHeader>
|
||||
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
|
||||
<RuntimeTypeInfo>true</RuntimeTypeInfo>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<WarningLevel>Level4</WarningLevel>
|
||||
<DebugInformationFormat>
|
||||
</DebugInformationFormat>
|
||||
<PreprocessorDefinitions>WIN32;_WINDOWS;NDEBUG;CMAKE_INTDIR="Release";%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<AssemblerListingLocation>Release</AssemblerListingLocation>
|
||||
<ObjectFileName>$(IntDir)</ObjectFileName>
|
||||
<ProgramDataBaseFileName>../../Release/flatc.pdb</ProgramDataBaseFileName>
|
||||
<TreatWarningAsError>true</TreatWarningAsError>
|
||||
</ClCompile>
|
||||
<ResourceCompile>
|
||||
<PreprocessorDefinitions>WIN32;_WINDOWS;NDEBUG;CMAKE_INTDIR=\"Release\";%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
@@ -139,21 +217,67 @@
|
||||
<LinkLibraryDependencies>false</LinkLibraryDependencies>
|
||||
</ProjectReference>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
|
||||
<ClCompile>
|
||||
<AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<CompileAs>CompileAsCpp</CompileAs>
|
||||
<ExceptionHandling>Sync</ExceptionHandling>
|
||||
<InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
|
||||
<Optimization>MaxSpeed</Optimization>
|
||||
<PrecompiledHeader>NotUsing</PrecompiledHeader>
|
||||
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
|
||||
<RuntimeTypeInfo>true</RuntimeTypeInfo>
|
||||
<WarningLevel>Level4</WarningLevel>
|
||||
<DebugInformationFormat>
|
||||
</DebugInformationFormat>
|
||||
<PreprocessorDefinitions>WIN32;_WINDOWS;NDEBUG;CMAKE_INTDIR="Release";%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<AssemblerListingLocation>Release</AssemblerListingLocation>
|
||||
<ObjectFileName>$(IntDir)</ObjectFileName>
|
||||
<ProgramDataBaseFileName>../../Release/flatc.pdb</ProgramDataBaseFileName>
|
||||
<TreatWarningAsError>true</TreatWarningAsError>
|
||||
</ClCompile>
|
||||
<ResourceCompile>
|
||||
<PreprocessorDefinitions>WIN32;_WINDOWS;NDEBUG;CMAKE_INTDIR=\"Release\";%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
</ResourceCompile>
|
||||
<Midl>
|
||||
<AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<OutputDirectory>$(IntDir)</OutputDirectory>
|
||||
<HeaderFileName>%(Filename).h</HeaderFileName>
|
||||
<TypeLibraryName>%(Filename).tlb</TypeLibraryName>
|
||||
<InterfaceIdentifierFileName>%(Filename)_i.c</InterfaceIdentifierFileName>
|
||||
<ProxyFileName>%(Filename)_p.c</ProxyFileName>
|
||||
</Midl>
|
||||
<Link>
|
||||
<AdditionalDependencies>kernel32.lib;user32.lib;gdi32.lib;winspool.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;comdlg32.lib;advapi32.lib</AdditionalDependencies>
|
||||
<AdditionalLibraryDirectories>%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
|
||||
<GenerateDebugInformation>false</GenerateDebugInformation>
|
||||
<ImportLibrary>../../Release/flatc.lib</ImportLibrary>
|
||||
<ProgramDataBaseFile>../../Release/flatc.pdb</ProgramDataBaseFile>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<Version>
|
||||
</Version>
|
||||
</Link>
|
||||
<ProjectReference>
|
||||
<LinkLibraryDependencies>false</LinkLibraryDependencies>
|
||||
</ProjectReference>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemGroup>
|
||||
<ClInclude Include="..\..\include\flatbuffers\flatbuffers.h" />
|
||||
<ClInclude Include="..\..\include\flatbuffers\idl.h" />
|
||||
<ClInclude Include="..\..\include\flatbuffers\util.h" />
|
||||
<ClCompile Include="..\..\src\idl_gen_fbs.cpp" />
|
||||
<ClCompile Include="..\..\src\idl_gen_general.cpp" />
|
||||
<ClCompile Include="..\..\src\idl_gen_go.cpp">
|
||||
<WarningLevel Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Level4</WarningLevel>
|
||||
</ClCompile>
|
||||
<ClCompile Include="..\..\src\idl_gen_js.cpp" />
|
||||
<ClCompile Include="..\..\src\idl_gen_python.cpp" />
|
||||
<ClCompile Include="..\..\src\idl_parser.cpp" />
|
||||
<ClCompile Include="..\..\src\idl_gen_cpp.cpp" />
|
||||
<ClCompile Include="..\..\src\idl_gen_java.cpp" />
|
||||
<ClCompile Include="..\..\src\idl_gen_text.cpp" />
|
||||
<ClCompile Include="..\..\src\flatc.cpp" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../../ZERO_CHECK.vcxproj">
|
||||
<Project>71030BD1-9039-4724-A6C4-F7CB2C700B47</Project>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
|
||||
<ImportGroup Label="ExtensionTargets">
|
||||
</ImportGroup>
|
||||
|
||||
@@ -1,11 +1,27 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
|
||||
<LocalDebuggerWorkingDirectory>..\..</LocalDebuggerWorkingDirectory>
|
||||
<LocalDebuggerWorkingDirectory>..\..\tests</LocalDebuggerWorkingDirectory>
|
||||
<DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
|
||||
<LocalDebuggerCommandArguments>-j -c -n -g --no-includes --gen-mutable monster_test.fbs</LocalDebuggerCommandArguments>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||
<LocalDebuggerWorkingDirectory>..\..</LocalDebuggerWorkingDirectory>
|
||||
<DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
|
||||
<LocalDebuggerCommandArguments>-j -c -n -g -b -t monster_test.fbs monsterdata_test.golden</LocalDebuggerCommandArguments>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
|
||||
<LocalDebuggerCommandArguments>-j -c -g -n -b -t monster_test.fbs monsterdata_test.golden</LocalDebuggerCommandArguments>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
|
||||
<LocalDebuggerWorkingDirectory>..\..\tests</LocalDebuggerWorkingDirectory>
|
||||
<DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
|
||||
<LocalDebuggerCommandArguments>-j -c -g -b -t monster_test.fbs monsterdata_test.json</LocalDebuggerCommandArguments>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
|
||||
<LocalDebuggerWorkingDirectory>..\..\tests</LocalDebuggerWorkingDirectory>
|
||||
<DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
@@ -5,10 +5,18 @@
|
||||
<Configuration>Debug</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Debug|x64">
|
||||
<Configuration>Debug</Configuration>
|
||||
<Platform>x64</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release|Win32">
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release|x64">
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>x64</Platform>
|
||||
</ProjectConfiguration>
|
||||
</ItemGroup>
|
||||
<PropertyGroup Label="Globals">
|
||||
<ProjectGUID>{16FA5518-3DE1-4B15-A1E0-F4734C276FB4}</ProjectGUID>
|
||||
@@ -22,11 +30,21 @@
|
||||
<UseOfMfc>false</UseOfMfc>
|
||||
<CharacterSet>MultiByte</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseOfMfc>false</UseOfMfc>
|
||||
<CharacterSet>MultiByte</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseOfMfc>false</UseOfMfc>
|
||||
<CharacterSet>MultiByte</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseOfMfc>false</UseOfMfc>
|
||||
<CharacterSet>MultiByte</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
|
||||
<ImportGroup Label="ExtensionSettings">
|
||||
</ImportGroup>
|
||||
@@ -37,17 +55,29 @@
|
||||
<PropertyGroup>
|
||||
<_ProjectFileVersion>10.0.20506.1</_ProjectFileVersion>
|
||||
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(IntDir)</OutDir>
|
||||
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(IntDir)</OutDir>
|
||||
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">flatsamplebinary.dir\Debug\</IntDir>
|
||||
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">flatsamplebinary.dir\Debug\</IntDir>
|
||||
<TargetName Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">flatsamplebinary</TargetName>
|
||||
<TargetName Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">flatsamplebinary</TargetName>
|
||||
<TargetExt Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">.exe</TargetExt>
|
||||
<TargetExt Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">.exe</TargetExt>
|
||||
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>
|
||||
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</LinkIncremental>
|
||||
<GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</GenerateManifest>
|
||||
<GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</GenerateManifest>
|
||||
<OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(IntDir)</OutDir>
|
||||
<OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(IntDir)</OutDir>
|
||||
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">flatsamplebinary.dir\Release\</IntDir>
|
||||
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">flatsamplebinary.dir\Release\</IntDir>
|
||||
<TargetName Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">flatsamplebinary</TargetName>
|
||||
<TargetName Condition="'$(Configuration)|$(Platform)'=='Release|x64'">flatsamplebinary</TargetName>
|
||||
<TargetExt Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">.exe</TargetExt>
|
||||
<TargetExt Condition="'$(Configuration)|$(Platform)'=='Release|x64'">.exe</TargetExt>
|
||||
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>
|
||||
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</LinkIncremental>
|
||||
<GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</GenerateManifest>
|
||||
<GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</GenerateManifest>
|
||||
</PropertyGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
|
||||
<ClCompile>
|
||||
@@ -61,11 +91,12 @@
|
||||
<PrecompiledHeader>NotUsing</PrecompiledHeader>
|
||||
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
|
||||
<RuntimeTypeInfo>true</RuntimeTypeInfo>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<WarningLevel>Level4</WarningLevel>
|
||||
<PreprocessorDefinitions>WIN32;_WINDOWS;_DEBUG;CMAKE_INTDIR="Debug";%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<AssemblerListingLocation>Debug</AssemblerListingLocation>
|
||||
<ObjectFileName>$(IntDir)</ObjectFileName>
|
||||
<ProgramDataBaseFileName>../../Debug/flatsamplebinary.pdb</ProgramDataBaseFileName>
|
||||
<TreatWarningAsError>true</TreatWarningAsError>
|
||||
</ClCompile>
|
||||
<ResourceCompile>
|
||||
<PreprocessorDefinitions>WIN32;_WINDOWS;_DEBUG;CMAKE_INTDIR=\"Debug\";%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
@@ -94,6 +125,52 @@
|
||||
<LinkLibraryDependencies>false</LinkLibraryDependencies>
|
||||
</ProjectReference>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
|
||||
<ClCompile>
|
||||
<AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
|
||||
<CompileAs>CompileAsCpp</CompileAs>
|
||||
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
|
||||
<ExceptionHandling>Sync</ExceptionHandling>
|
||||
<InlineFunctionExpansion>Disabled</InlineFunctionExpansion>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<PrecompiledHeader>NotUsing</PrecompiledHeader>
|
||||
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
|
||||
<RuntimeTypeInfo>true</RuntimeTypeInfo>
|
||||
<WarningLevel>Level4</WarningLevel>
|
||||
<PreprocessorDefinitions>WIN32;_WINDOWS;_DEBUG;CMAKE_INTDIR="Debug";%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<AssemblerListingLocation>Debug</AssemblerListingLocation>
|
||||
<ObjectFileName>$(IntDir)</ObjectFileName>
|
||||
<ProgramDataBaseFileName>../../Debug/flatsamplebinary.pdb</ProgramDataBaseFileName>
|
||||
<TreatWarningAsError>true</TreatWarningAsError>
|
||||
</ClCompile>
|
||||
<ResourceCompile>
|
||||
<PreprocessorDefinitions>WIN32;_WINDOWS;_DEBUG;CMAKE_INTDIR=\"Debug\";%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
</ResourceCompile>
|
||||
<Midl>
|
||||
<AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<OutputDirectory>$(IntDir)</OutputDirectory>
|
||||
<HeaderFileName>%(Filename).h</HeaderFileName>
|
||||
<TypeLibraryName>%(Filename).tlb</TypeLibraryName>
|
||||
<InterfaceIdentifierFileName>%(Filename)_i.c</InterfaceIdentifierFileName>
|
||||
<ProxyFileName>%(Filename)_p.c</ProxyFileName>
|
||||
</Midl>
|
||||
<Link>
|
||||
<AdditionalOptions>/debug %(AdditionalOptions)</AdditionalOptions>
|
||||
<AdditionalDependencies>kernel32.lib;user32.lib;gdi32.lib;winspool.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;comdlg32.lib;advapi32.lib</AdditionalDependencies>
|
||||
<AdditionalLibraryDirectories>%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<ImportLibrary>../../Debug/flatsamplebinary.lib</ImportLibrary>
|
||||
<ProgramDataBaseFile>../../Debug/flatsamplebinary.pdb</ProgramDataBaseFile>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<Version>
|
||||
</Version>
|
||||
</Link>
|
||||
<ProjectReference>
|
||||
<LinkLibraryDependencies>false</LinkLibraryDependencies>
|
||||
</ProjectReference>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||
<ClCompile>
|
||||
<AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
@@ -104,13 +181,14 @@
|
||||
<PrecompiledHeader>NotUsing</PrecompiledHeader>
|
||||
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
|
||||
<RuntimeTypeInfo>true</RuntimeTypeInfo>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<WarningLevel>Level4</WarningLevel>
|
||||
<DebugInformationFormat>
|
||||
</DebugInformationFormat>
|
||||
<PreprocessorDefinitions>WIN32;_WINDOWS;NDEBUG;CMAKE_INTDIR="Release";%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<AssemblerListingLocation>Release</AssemblerListingLocation>
|
||||
<ObjectFileName>$(IntDir)</ObjectFileName>
|
||||
<ProgramDataBaseFileName>../../Release/flatsamplebinary.pdb</ProgramDataBaseFileName>
|
||||
<TreatWarningAsError>true</TreatWarningAsError>
|
||||
</ClCompile>
|
||||
<ResourceCompile>
|
||||
<PreprocessorDefinitions>WIN32;_WINDOWS;NDEBUG;CMAKE_INTDIR=\"Release\";%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
@@ -139,16 +217,56 @@
|
||||
<LinkLibraryDependencies>false</LinkLibraryDependencies>
|
||||
</ProjectReference>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
|
||||
<ClCompile>
|
||||
<AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<CompileAs>CompileAsCpp</CompileAs>
|
||||
<ExceptionHandling>Sync</ExceptionHandling>
|
||||
<InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
|
||||
<Optimization>MaxSpeed</Optimization>
|
||||
<PrecompiledHeader>NotUsing</PrecompiledHeader>
|
||||
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
|
||||
<RuntimeTypeInfo>true</RuntimeTypeInfo>
|
||||
<WarningLevel>Level4</WarningLevel>
|
||||
<DebugInformationFormat>
|
||||
</DebugInformationFormat>
|
||||
<PreprocessorDefinitions>WIN32;_WINDOWS;NDEBUG;CMAKE_INTDIR="Release";%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<AssemblerListingLocation>Release</AssemblerListingLocation>
|
||||
<ObjectFileName>$(IntDir)</ObjectFileName>
|
||||
<ProgramDataBaseFileName>../../Release/flatsamplebinary.pdb</ProgramDataBaseFileName>
|
||||
<TreatWarningAsError>true</TreatWarningAsError>
|
||||
</ClCompile>
|
||||
<ResourceCompile>
|
||||
<PreprocessorDefinitions>WIN32;_WINDOWS;NDEBUG;CMAKE_INTDIR=\"Release\";%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
</ResourceCompile>
|
||||
<Midl>
|
||||
<AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<OutputDirectory>$(IntDir)</OutputDirectory>
|
||||
<HeaderFileName>%(Filename).h</HeaderFileName>
|
||||
<TypeLibraryName>%(Filename).tlb</TypeLibraryName>
|
||||
<InterfaceIdentifierFileName>%(Filename)_i.c</InterfaceIdentifierFileName>
|
||||
<ProxyFileName>%(Filename)_p.c</ProxyFileName>
|
||||
</Midl>
|
||||
<Link>
|
||||
<AdditionalDependencies>kernel32.lib;user32.lib;gdi32.lib;winspool.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;comdlg32.lib;advapi32.lib</AdditionalDependencies>
|
||||
<AdditionalLibraryDirectories>%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
|
||||
<GenerateDebugInformation>false</GenerateDebugInformation>
|
||||
<ImportLibrary>../../Release/flatsamplebinary.lib</ImportLibrary>
|
||||
<ProgramDataBaseFile>../../Release/flatsamplebinary.pdb</ProgramDataBaseFile>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<Version>
|
||||
</Version>
|
||||
</Link>
|
||||
<ProjectReference>
|
||||
<LinkLibraryDependencies>false</LinkLibraryDependencies>
|
||||
</ProjectReference>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemGroup>
|
||||
<ClInclude Include="..\..\include\flatbuffers\flatbuffers.h" />
|
||||
<ClInclude Include="..\..\samples\monster_generated.h" />
|
||||
<ClCompile Include="..\..\samples\sample_binary.cpp" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../../ZERO_CHECK.vcxproj">
|
||||
<Project>71030BD1-9039-4724-A6C4-F7CB2C700B47</Project>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
|
||||
<ImportGroup Label="ExtensionTargets">
|
||||
</ImportGroup>
|
||||
|
||||
@@ -1,3 +1,11 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
|
||||
<LocalDebuggerWorkingDirectory>..\..</LocalDebuggerWorkingDirectory>
|
||||
<DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
|
||||
<LocalDebuggerWorkingDirectory>..\..</LocalDebuggerWorkingDirectory>
|
||||
<DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
@@ -5,10 +5,18 @@
|
||||
<Configuration>Debug</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Debug|x64">
|
||||
<Configuration>Debug</Configuration>
|
||||
<Platform>x64</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release|Win32">
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release|x64">
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>x64</Platform>
|
||||
</ProjectConfiguration>
|
||||
</ItemGroup>
|
||||
<PropertyGroup Label="Globals">
|
||||
<ProjectGUID>{F0A15675-1017-4217-BB5B-3372F2C636AB}</ProjectGUID>
|
||||
@@ -22,11 +30,21 @@
|
||||
<UseOfMfc>false</UseOfMfc>
|
||||
<CharacterSet>MultiByte</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseOfMfc>false</UseOfMfc>
|
||||
<CharacterSet>MultiByte</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseOfMfc>false</UseOfMfc>
|
||||
<CharacterSet>MultiByte</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseOfMfc>false</UseOfMfc>
|
||||
<CharacterSet>MultiByte</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
|
||||
<ImportGroup Label="ExtensionSettings">
|
||||
</ImportGroup>
|
||||
@@ -37,17 +55,29 @@
|
||||
<PropertyGroup>
|
||||
<_ProjectFileVersion>10.0.20506.1</_ProjectFileVersion>
|
||||
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(IntDir)</OutDir>
|
||||
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(IntDir)</OutDir>
|
||||
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">flatsampletext.dir\Debug\</IntDir>
|
||||
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">flatsampletext.dir\Debug\</IntDir>
|
||||
<TargetName Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">flatsampletext</TargetName>
|
||||
<TargetName Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">flatsampletext</TargetName>
|
||||
<TargetExt Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">.exe</TargetExt>
|
||||
<TargetExt Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">.exe</TargetExt>
|
||||
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>
|
||||
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</LinkIncremental>
|
||||
<GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</GenerateManifest>
|
||||
<GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</GenerateManifest>
|
||||
<OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(IntDir)</OutDir>
|
||||
<OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(IntDir)</OutDir>
|
||||
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">flatsampletext.dir\Release\</IntDir>
|
||||
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">flatsampletext.dir\Release\</IntDir>
|
||||
<TargetName Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">flatsampletext</TargetName>
|
||||
<TargetName Condition="'$(Configuration)|$(Platform)'=='Release|x64'">flatsampletext</TargetName>
|
||||
<TargetExt Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">.exe</TargetExt>
|
||||
<TargetExt Condition="'$(Configuration)|$(Platform)'=='Release|x64'">.exe</TargetExt>
|
||||
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>
|
||||
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</LinkIncremental>
|
||||
<GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</GenerateManifest>
|
||||
<GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</GenerateManifest>
|
||||
</PropertyGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
|
||||
<ClCompile>
|
||||
@@ -61,11 +91,12 @@
|
||||
<PrecompiledHeader>NotUsing</PrecompiledHeader>
|
||||
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
|
||||
<RuntimeTypeInfo>true</RuntimeTypeInfo>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<WarningLevel>Level4</WarningLevel>
|
||||
<PreprocessorDefinitions>WIN32;_WINDOWS;_DEBUG;CMAKE_INTDIR="Debug";%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<AssemblerListingLocation>Debug</AssemblerListingLocation>
|
||||
<ObjectFileName>$(IntDir)</ObjectFileName>
|
||||
<ProgramDataBaseFileName>../../Debug/flatsampletext.pdb</ProgramDataBaseFileName>
|
||||
<TreatWarningAsError>true</TreatWarningAsError>
|
||||
</ClCompile>
|
||||
<ResourceCompile>
|
||||
<PreprocessorDefinitions>WIN32;_WINDOWS;_DEBUG;CMAKE_INTDIR=\"Debug\";%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
@@ -94,6 +125,52 @@
|
||||
<LinkLibraryDependencies>false</LinkLibraryDependencies>
|
||||
</ProjectReference>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
|
||||
<ClCompile>
|
||||
<AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
|
||||
<CompileAs>CompileAsCpp</CompileAs>
|
||||
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
|
||||
<ExceptionHandling>Sync</ExceptionHandling>
|
||||
<InlineFunctionExpansion>Disabled</InlineFunctionExpansion>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<PrecompiledHeader>NotUsing</PrecompiledHeader>
|
||||
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
|
||||
<RuntimeTypeInfo>true</RuntimeTypeInfo>
|
||||
<WarningLevel>Level4</WarningLevel>
|
||||
<PreprocessorDefinitions>WIN32;_WINDOWS;_DEBUG;CMAKE_INTDIR="Debug";%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<AssemblerListingLocation>Debug</AssemblerListingLocation>
|
||||
<ObjectFileName>$(IntDir)</ObjectFileName>
|
||||
<ProgramDataBaseFileName>../../Debug/flatsampletext.pdb</ProgramDataBaseFileName>
|
||||
<TreatWarningAsError>true</TreatWarningAsError>
|
||||
</ClCompile>
|
||||
<ResourceCompile>
|
||||
<PreprocessorDefinitions>WIN32;_WINDOWS;_DEBUG;CMAKE_INTDIR=\"Debug\";%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
</ResourceCompile>
|
||||
<Midl>
|
||||
<AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<OutputDirectory>$(IntDir)</OutputDirectory>
|
||||
<HeaderFileName>%(Filename).h</HeaderFileName>
|
||||
<TypeLibraryName>%(Filename).tlb</TypeLibraryName>
|
||||
<InterfaceIdentifierFileName>%(Filename)_i.c</InterfaceIdentifierFileName>
|
||||
<ProxyFileName>%(Filename)_p.c</ProxyFileName>
|
||||
</Midl>
|
||||
<Link>
|
||||
<AdditionalOptions>/debug %(AdditionalOptions)</AdditionalOptions>
|
||||
<AdditionalDependencies>kernel32.lib;user32.lib;gdi32.lib;winspool.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;comdlg32.lib;advapi32.lib</AdditionalDependencies>
|
||||
<AdditionalLibraryDirectories>%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<ImportLibrary>../../Debug/flatsampletext.lib</ImportLibrary>
|
||||
<ProgramDataBaseFile>../../Debug/flatsampletext.pdb</ProgramDataBaseFile>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<Version>
|
||||
</Version>
|
||||
</Link>
|
||||
<ProjectReference>
|
||||
<LinkLibraryDependencies>false</LinkLibraryDependencies>
|
||||
</ProjectReference>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||
<ClCompile>
|
||||
<AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
@@ -104,13 +181,14 @@
|
||||
<PrecompiledHeader>NotUsing</PrecompiledHeader>
|
||||
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
|
||||
<RuntimeTypeInfo>true</RuntimeTypeInfo>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<WarningLevel>Level4</WarningLevel>
|
||||
<DebugInformationFormat>
|
||||
</DebugInformationFormat>
|
||||
<PreprocessorDefinitions>WIN32;_WINDOWS;NDEBUG;CMAKE_INTDIR="Release";%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<AssemblerListingLocation>Release</AssemblerListingLocation>
|
||||
<ObjectFileName>$(IntDir)</ObjectFileName>
|
||||
<ProgramDataBaseFileName>../../Release/flatsampletext.pdb</ProgramDataBaseFileName>
|
||||
<TreatWarningAsError>true</TreatWarningAsError>
|
||||
</ClCompile>
|
||||
<ResourceCompile>
|
||||
<PreprocessorDefinitions>WIN32;_WINDOWS;NDEBUG;CMAKE_INTDIR=\"Release\";%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
@@ -139,6 +217,51 @@
|
||||
<LinkLibraryDependencies>false</LinkLibraryDependencies>
|
||||
</ProjectReference>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
|
||||
<ClCompile>
|
||||
<AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<CompileAs>CompileAsCpp</CompileAs>
|
||||
<ExceptionHandling>Sync</ExceptionHandling>
|
||||
<InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
|
||||
<Optimization>MaxSpeed</Optimization>
|
||||
<PrecompiledHeader>NotUsing</PrecompiledHeader>
|
||||
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
|
||||
<RuntimeTypeInfo>true</RuntimeTypeInfo>
|
||||
<WarningLevel>Level4</WarningLevel>
|
||||
<DebugInformationFormat>
|
||||
</DebugInformationFormat>
|
||||
<PreprocessorDefinitions>WIN32;_WINDOWS;NDEBUG;CMAKE_INTDIR="Release";%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<AssemblerListingLocation>Release</AssemblerListingLocation>
|
||||
<ObjectFileName>$(IntDir)</ObjectFileName>
|
||||
<ProgramDataBaseFileName>../../Release/flatsampletext.pdb</ProgramDataBaseFileName>
|
||||
<TreatWarningAsError>true</TreatWarningAsError>
|
||||
</ClCompile>
|
||||
<ResourceCompile>
|
||||
<PreprocessorDefinitions>WIN32;_WINDOWS;NDEBUG;CMAKE_INTDIR=\"Release\";%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
</ResourceCompile>
|
||||
<Midl>
|
||||
<AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<OutputDirectory>$(IntDir)</OutputDirectory>
|
||||
<HeaderFileName>%(Filename).h</HeaderFileName>
|
||||
<TypeLibraryName>%(Filename).tlb</TypeLibraryName>
|
||||
<InterfaceIdentifierFileName>%(Filename)_i.c</InterfaceIdentifierFileName>
|
||||
<ProxyFileName>%(Filename)_p.c</ProxyFileName>
|
||||
</Midl>
|
||||
<Link>
|
||||
<AdditionalDependencies>kernel32.lib;user32.lib;gdi32.lib;winspool.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;comdlg32.lib;advapi32.lib</AdditionalDependencies>
|
||||
<AdditionalLibraryDirectories>%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
|
||||
<GenerateDebugInformation>false</GenerateDebugInformation>
|
||||
<ImportLibrary>../../Release/flatsampletext.lib</ImportLibrary>
|
||||
<ProgramDataBaseFile>../../Release/flatsampletext.pdb</ProgramDataBaseFile>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<Version>
|
||||
</Version>
|
||||
</Link>
|
||||
<ProjectReference>
|
||||
<LinkLibraryDependencies>false</LinkLibraryDependencies>
|
||||
</ProjectReference>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemGroup>
|
||||
<ClInclude Include="..\..\include\flatbuffers\flatbuffers.h" />
|
||||
<ClInclude Include="..\..\include\flatbuffers\idl.h" />
|
||||
@@ -148,11 +271,6 @@
|
||||
<ClCompile Include="..\..\src\idl_gen_text.cpp" />
|
||||
<ClCompile Include="..\..\samples\sample_text.cpp" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../../ZERO_CHECK.vcxproj">
|
||||
<Project>71030BD1-9039-4724-A6C4-F7CB2C700B47</Project>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
|
||||
<ImportGroup Label="ExtensionTargets">
|
||||
</ImportGroup>
|
||||
|
||||
@@ -8,4 +8,12 @@
|
||||
<LocalDebuggerWorkingDirectory>..\..</LocalDebuggerWorkingDirectory>
|
||||
<DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
|
||||
<LocalDebuggerWorkingDirectory>..\..</LocalDebuggerWorkingDirectory>
|
||||
<DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
|
||||
<LocalDebuggerWorkingDirectory>..\..</LocalDebuggerWorkingDirectory>
|
||||
<DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
@@ -5,10 +5,18 @@
|
||||
<Configuration>Debug</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Debug|x64">
|
||||
<Configuration>Debug</Configuration>
|
||||
<Platform>x64</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release|Win32">
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release|x64">
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>x64</Platform>
|
||||
</ProjectConfiguration>
|
||||
</ItemGroup>
|
||||
<PropertyGroup Label="Globals">
|
||||
<ProjectGUID>{DC7BBA00-9FC6-48AF-B7E9-12CA91AC02AA}</ProjectGUID>
|
||||
@@ -22,11 +30,21 @@
|
||||
<UseOfMfc>false</UseOfMfc>
|
||||
<CharacterSet>MultiByte</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseOfMfc>false</UseOfMfc>
|
||||
<CharacterSet>MultiByte</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseOfMfc>false</UseOfMfc>
|
||||
<CharacterSet>MultiByte</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseOfMfc>false</UseOfMfc>
|
||||
<CharacterSet>MultiByte</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
|
||||
<ImportGroup Label="ExtensionSettings">
|
||||
</ImportGroup>
|
||||
@@ -37,17 +55,29 @@
|
||||
<PropertyGroup>
|
||||
<_ProjectFileVersion>10.0.20506.1</_ProjectFileVersion>
|
||||
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(IntDir)</OutDir>
|
||||
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(IntDir)</OutDir>
|
||||
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">flattests.dir\Debug\</IntDir>
|
||||
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">flattests.dir\Debug\</IntDir>
|
||||
<TargetName Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">flattests</TargetName>
|
||||
<TargetName Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">flattests</TargetName>
|
||||
<TargetExt Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">.exe</TargetExt>
|
||||
<TargetExt Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">.exe</TargetExt>
|
||||
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>
|
||||
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</LinkIncremental>
|
||||
<GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</GenerateManifest>
|
||||
<GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</GenerateManifest>
|
||||
<OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(IntDir)</OutDir>
|
||||
<OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(IntDir)</OutDir>
|
||||
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">flattests.dir\Release\</IntDir>
|
||||
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">flattests.dir\Release\</IntDir>
|
||||
<TargetName Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">flattests</TargetName>
|
||||
<TargetName Condition="'$(Configuration)|$(Platform)'=='Release|x64'">flattests</TargetName>
|
||||
<TargetExt Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">.exe</TargetExt>
|
||||
<TargetExt Condition="'$(Configuration)|$(Platform)'=='Release|x64'">.exe</TargetExt>
|
||||
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>
|
||||
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</LinkIncremental>
|
||||
<GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</GenerateManifest>
|
||||
<GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</GenerateManifest>
|
||||
</PropertyGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
|
||||
<ClCompile>
|
||||
@@ -61,11 +91,12 @@
|
||||
<PrecompiledHeader>NotUsing</PrecompiledHeader>
|
||||
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
|
||||
<RuntimeTypeInfo>true</RuntimeTypeInfo>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<WarningLevel>Level4</WarningLevel>
|
||||
<PreprocessorDefinitions>WIN32;_WINDOWS;_DEBUG;CMAKE_INTDIR="Debug";%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<AssemblerListingLocation>Debug</AssemblerListingLocation>
|
||||
<ObjectFileName>$(IntDir)</ObjectFileName>
|
||||
<ProgramDataBaseFileName>../../Debug/flattests.pdb</ProgramDataBaseFileName>
|
||||
<TreatWarningAsError>true</TreatWarningAsError>
|
||||
</ClCompile>
|
||||
<ResourceCompile>
|
||||
<PreprocessorDefinitions>WIN32;_WINDOWS;_DEBUG;CMAKE_INTDIR=\"Debug\";%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
@@ -94,6 +125,52 @@
|
||||
<LinkLibraryDependencies>false</LinkLibraryDependencies>
|
||||
</ProjectReference>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
|
||||
<ClCompile>
|
||||
<AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
|
||||
<CompileAs>CompileAsCpp</CompileAs>
|
||||
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
|
||||
<ExceptionHandling>Sync</ExceptionHandling>
|
||||
<InlineFunctionExpansion>Disabled</InlineFunctionExpansion>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<PrecompiledHeader>NotUsing</PrecompiledHeader>
|
||||
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
|
||||
<RuntimeTypeInfo>true</RuntimeTypeInfo>
|
||||
<WarningLevel>Level4</WarningLevel>
|
||||
<PreprocessorDefinitions>WIN32;_WINDOWS;_DEBUG;CMAKE_INTDIR="Debug";%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<AssemblerListingLocation>Debug</AssemblerListingLocation>
|
||||
<ObjectFileName>$(IntDir)</ObjectFileName>
|
||||
<ProgramDataBaseFileName>../../Debug/flattests.pdb</ProgramDataBaseFileName>
|
||||
<TreatWarningAsError>true</TreatWarningAsError>
|
||||
</ClCompile>
|
||||
<ResourceCompile>
|
||||
<PreprocessorDefinitions>WIN32;_WINDOWS;_DEBUG;CMAKE_INTDIR=\"Debug\";%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
</ResourceCompile>
|
||||
<Midl>
|
||||
<AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<OutputDirectory>$(IntDir)</OutputDirectory>
|
||||
<HeaderFileName>%(Filename).h</HeaderFileName>
|
||||
<TypeLibraryName>%(Filename).tlb</TypeLibraryName>
|
||||
<InterfaceIdentifierFileName>%(Filename)_i.c</InterfaceIdentifierFileName>
|
||||
<ProxyFileName>%(Filename)_p.c</ProxyFileName>
|
||||
</Midl>
|
||||
<Link>
|
||||
<AdditionalOptions>/debug %(AdditionalOptions)</AdditionalOptions>
|
||||
<AdditionalDependencies>kernel32.lib;user32.lib;gdi32.lib;winspool.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;comdlg32.lib;advapi32.lib</AdditionalDependencies>
|
||||
<AdditionalLibraryDirectories>%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<ImportLibrary>../../Debug/flattests.lib</ImportLibrary>
|
||||
<ProgramDataBaseFile>../../Debug/flattests.pdb</ProgramDataBaseFile>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<Version>
|
||||
</Version>
|
||||
</Link>
|
||||
<ProjectReference>
|
||||
<LinkLibraryDependencies>false</LinkLibraryDependencies>
|
||||
</ProjectReference>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||
<ClCompile>
|
||||
<AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
@@ -104,13 +181,14 @@
|
||||
<PrecompiledHeader>NotUsing</PrecompiledHeader>
|
||||
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
|
||||
<RuntimeTypeInfo>true</RuntimeTypeInfo>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<WarningLevel>Level4</WarningLevel>
|
||||
<DebugInformationFormat>
|
||||
</DebugInformationFormat>
|
||||
<PreprocessorDefinitions>WIN32;_WINDOWS;NDEBUG;CMAKE_INTDIR="Release";%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<AssemblerListingLocation>Release</AssemblerListingLocation>
|
||||
<ObjectFileName>$(IntDir)</ObjectFileName>
|
||||
<ProgramDataBaseFileName>../../Release/flattests.pdb</ProgramDataBaseFileName>
|
||||
<TreatWarningAsError>true</TreatWarningAsError>
|
||||
</ClCompile>
|
||||
<ResourceCompile>
|
||||
<PreprocessorDefinitions>WIN32;_WINDOWS;NDEBUG;CMAKE_INTDIR=\"Release\";%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
@@ -139,20 +217,64 @@
|
||||
<LinkLibraryDependencies>false</LinkLibraryDependencies>
|
||||
</ProjectReference>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
|
||||
<ClCompile>
|
||||
<AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<CompileAs>CompileAsCpp</CompileAs>
|
||||
<ExceptionHandling>Sync</ExceptionHandling>
|
||||
<InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
|
||||
<Optimization>MaxSpeed</Optimization>
|
||||
<PrecompiledHeader>NotUsing</PrecompiledHeader>
|
||||
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
|
||||
<RuntimeTypeInfo>true</RuntimeTypeInfo>
|
||||
<WarningLevel>Level4</WarningLevel>
|
||||
<DebugInformationFormat>
|
||||
</DebugInformationFormat>
|
||||
<PreprocessorDefinitions>WIN32;_WINDOWS;NDEBUG;CMAKE_INTDIR="Release";%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<AssemblerListingLocation>Release</AssemblerListingLocation>
|
||||
<ObjectFileName>$(IntDir)</ObjectFileName>
|
||||
<ProgramDataBaseFileName>../../Release/flattests.pdb</ProgramDataBaseFileName>
|
||||
<TreatWarningAsError>true</TreatWarningAsError>
|
||||
</ClCompile>
|
||||
<ResourceCompile>
|
||||
<PreprocessorDefinitions>WIN32;_WINDOWS;NDEBUG;CMAKE_INTDIR=\"Release\";%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
</ResourceCompile>
|
||||
<Midl>
|
||||
<AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<OutputDirectory>$(IntDir)</OutputDirectory>
|
||||
<HeaderFileName>%(Filename).h</HeaderFileName>
|
||||
<TypeLibraryName>%(Filename).tlb</TypeLibraryName>
|
||||
<InterfaceIdentifierFileName>%(Filename)_i.c</InterfaceIdentifierFileName>
|
||||
<ProxyFileName>%(Filename)_p.c</ProxyFileName>
|
||||
</Midl>
|
||||
<Link>
|
||||
<AdditionalDependencies>kernel32.lib;user32.lib;gdi32.lib;winspool.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;comdlg32.lib;advapi32.lib</AdditionalDependencies>
|
||||
<AdditionalLibraryDirectories>%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
|
||||
<GenerateDebugInformation>false</GenerateDebugInformation>
|
||||
<ImportLibrary>../../Release/flattests.lib</ImportLibrary>
|
||||
<ProgramDataBaseFile>../../Release/flattests.pdb</ProgramDataBaseFile>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<Version>
|
||||
</Version>
|
||||
</Link>
|
||||
<ProjectReference>
|
||||
<LinkLibraryDependencies>false</LinkLibraryDependencies>
|
||||
</ProjectReference>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemGroup>
|
||||
<ClInclude Include="..\..\include\flatbuffers\flatbuffers.h" />
|
||||
<ClInclude Include="..\..\include\flatbuffers\idl.h" />
|
||||
<ClInclude Include="..\..\include\flatbuffers\reflection.h" />
|
||||
<ClInclude Include="..\..\include\flatbuffers\util.h" />
|
||||
<ClInclude Include="..\..\tests\monster_test_generated.h" />
|
||||
<ClCompile Include="..\..\src\idl_gen_fbs.cpp" />
|
||||
<ClCompile Include="..\..\src\idl_gen_general.cpp" />
|
||||
<ClCompile Include="..\..\src\idl_parser.cpp" />
|
||||
<ClCompile Include="..\..\src\idl_gen_text.cpp" />
|
||||
<ClCompile Include="..\..\src\reflection.cpp" />
|
||||
<ClCompile Include="..\..\tests\test.cpp" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../../ZERO_CHECK.vcxproj">
|
||||
<Project>71030BD1-9039-4724-A6C4-F7CB2C700B47</Project>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
|
||||
<ImportGroup Label="ExtensionTargets">
|
||||
</ImportGroup>
|
||||
|
||||
@@ -8,4 +8,12 @@
|
||||
<LocalDebuggerWorkingDirectory>..\..</LocalDebuggerWorkingDirectory>
|
||||
<DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
|
||||
<LocalDebuggerWorkingDirectory>..\..</LocalDebuggerWorkingDirectory>
|
||||
<DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
|
||||
<LocalDebuggerWorkingDirectory>..\..</LocalDebuggerWorkingDirectory>
|
||||
<DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
@@ -8,9 +8,16 @@
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
1963D7D2A57344A3B1C1713F /* idl_parser.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 3709AC883348409592530AE6 /* idl_parser.cpp */; settings = {COMPILER_FLAGS = ""; }; };
|
||||
3343DD4ED370434BBA148FAB /* idl_gen_java.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 3803689175184C7E8CB3EED0 /* idl_gen_java.cpp */; settings = {COMPILER_FLAGS = ""; }; };
|
||||
5AC48C391ACA9A0A008132C5 /* idl_gen_general.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 8CD8717A19CB937D0012A827 /* idl_gen_general.cpp */; };
|
||||
61823BBC53544106B6DBC38E /* idl_parser.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 3709AC883348409592530AE6 /* idl_parser.cpp */; settings = {COMPILER_FLAGS = ""; }; };
|
||||
61FF3C34FBEC4819A1C30F92 /* sample_text.cpp in Sources */ = {isa = PBXBuildFile; fileRef = ECCEBFFA6977404F858F9739 /* sample_text.cpp */; settings = {COMPILER_FLAGS = ""; }; };
|
||||
8C303C591975D6A700D7C1C5 /* idl_gen_go.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 8C303C581975D6A700D7C1C5 /* idl_gen_go.cpp */; };
|
||||
8C6905FD19F835B400CB8866 /* idl_gen_fbs.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 8C6905EC19F8357300CB8866 /* idl_gen_fbs.cpp */; };
|
||||
8C78573E1BD5AE2C00C53C34 /* idl_gen_js.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 8C78573D1BD5AE2C00C53C34 /* idl_gen_js.cpp */; };
|
||||
8C8774631B703D4800E693F5 /* reflection.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 8C8774621B703D4800E693F5 /* reflection.cpp */; };
|
||||
8C8774641B703E1200E693F5 /* idl_gen_fbs.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 8C6905EC19F8357300CB8866 /* idl_gen_fbs.cpp */; };
|
||||
8CA854B31B04244A00040A06 /* idl_gen_python.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 8CA854B21B04244A00040A06 /* idl_gen_python.cpp */; };
|
||||
8CD8717B19CB937D0012A827 /* idl_gen_general.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 8CD8717A19CB937D0012A827 /* idl_gen_general.cpp */; };
|
||||
A9C9A99F719A4ED58DC2D2FC /* idl_parser.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 3709AC883348409592530AE6 /* idl_parser.cpp */; settings = {COMPILER_FLAGS = ""; }; };
|
||||
AA9BACF55EB3456BA2F633BB /* flatc.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 0DFD29781D8E490284B06504 /* flatc.cpp */; settings = {COMPILER_FLAGS = ""; }; };
|
||||
AD71FEBEE4E846529002C1F0 /* idl_gen_text.cpp in Sources */ = {isa = PBXBuildFile; fileRef = F6C5D81DBF864365B12E269D /* idl_gen_text.cpp */; settings = {COMPILER_FLAGS = ""; }; };
|
||||
@@ -26,15 +33,18 @@
|
||||
0DFD29781D8E490284B06504 /* flatc.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = flatc.cpp; path = src/flatc.cpp; sourceTree = SOURCE_ROOT; };
|
||||
18185F364F604E648CF6EE25 /* flatc */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; path = flatc; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
3709AC883348409592530AE6 /* idl_parser.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = idl_parser.cpp; path = src/idl_parser.cpp; sourceTree = SOURCE_ROOT; };
|
||||
3803689175184C7E8CB3EED0 /* idl_gen_java.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = idl_gen_java.cpp; path = src/idl_gen_java.cpp; sourceTree = SOURCE_ROOT; };
|
||||
3863042BCEC64791BFB48625 /* flatsamplebinary */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; path = flatsamplebinary; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
420E3BC724ED4A008D79297F /* flatsampletext */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; path = flatsampletext; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
423CA92401AE442B91546E63 /* CMakeLists.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; name = CMakeLists.txt; path = /Users/wvo/flatbuffers_snapshot9/CMakeLists.txt; sourceTree = "<absolute>"; };
|
||||
5EE44BFFAF8E43F485859145 /* sample_binary.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = sample_binary.cpp; path = samples/sample_binary.cpp; sourceTree = SOURCE_ROOT; };
|
||||
6AD24EEB3D024825A37741FF /* test.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = test.cpp; path = tests/test.cpp; sourceTree = SOURCE_ROOT; };
|
||||
8C303C581975D6A700D7C1C5 /* idl_gen_go.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = idl_gen_go.cpp; path = src/idl_gen_go.cpp; sourceTree = "<group>"; };
|
||||
8C6905EC19F8357300CB8866 /* idl_gen_fbs.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = idl_gen_fbs.cpp; path = src/idl_gen_fbs.cpp; sourceTree = "<group>"; };
|
||||
8C78573D1BD5AE2C00C53C34 /* idl_gen_js.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = idl_gen_js.cpp; path = src/idl_gen_js.cpp; sourceTree = "<group>"; };
|
||||
8C8774621B703D4800E693F5 /* reflection.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = reflection.cpp; path = src/reflection.cpp; sourceTree = "<group>"; };
|
||||
8CA854B21B04244A00040A06 /* idl_gen_python.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = idl_gen_python.cpp; path = src/idl_gen_python.cpp; sourceTree = "<group>"; };
|
||||
8CD8717A19CB937D0012A827 /* idl_gen_general.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = idl_gen_general.cpp; path = src/idl_gen_general.cpp; sourceTree = "<group>"; };
|
||||
A13F25CDAD23435DA293690D /* flattests */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; path = flattests; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
AB70F1FBA50E4120BCF37C8D /* monster_test_generated.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = monster_test_generated.h; path = tests/monster_test_generated.h; sourceTree = SOURCE_ROOT; };
|
||||
AD3682C6E1DD4EABB822C0CC /* monster_generated.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = monster_generated.h; path = samples/monster_generated.h; sourceTree = SOURCE_ROOT; };
|
||||
C0E7B66C3FF849A0AD9A7168 /* util.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = util.h; path = include/flatbuffers/util.h; sourceTree = SOURCE_ROOT; };
|
||||
CD90A7F6B2BE4D0384294DD1 /* idl_gen_cpp.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = idl_gen_cpp.cpp; path = src/idl_gen_cpp.cpp; sourceTree = SOURCE_ROOT; };
|
||||
DD8B353D4756412195777FBA /* flatbuffers.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = flatbuffers.h; path = include/flatbuffers/flatbuffers.h; sourceTree = SOURCE_ROOT; };
|
||||
@@ -43,31 +53,18 @@
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
194905BCBB5C451DB092EB08 /* Resources */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
);
|
||||
name = Resources;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
28237E300FE042DEADA302D3 /* Source Files */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
0DFD29781D8E490284B06504 /* flatc.cpp */,
|
||||
8C78573D1BD5AE2C00C53C34 /* idl_gen_js.cpp */,
|
||||
8CA854B21B04244A00040A06 /* idl_gen_python.cpp */,
|
||||
8C6905EC19F8357300CB8866 /* idl_gen_fbs.cpp */,
|
||||
8CD8717A19CB937D0012A827 /* idl_gen_general.cpp */,
|
||||
8C303C581975D6A700D7C1C5 /* idl_gen_go.cpp */,
|
||||
F6C5D81DBF864365B12E269D /* idl_gen_text.cpp */,
|
||||
3709AC883348409592530AE6 /* idl_parser.cpp */,
|
||||
CD90A7F6B2BE4D0384294DD1 /* idl_gen_cpp.cpp */,
|
||||
3803689175184C7E8CB3EED0 /* idl_gen_java.cpp */,
|
||||
F6C5D81DBF864365B12E269D /* idl_gen_text.cpp */,
|
||||
3709AC883348409592530AE6 /* idl_parser.cpp */,
|
||||
);
|
||||
name = "Source Files";
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
355DCA17961E4B2FB2C71403 /* Source Files */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
F6C5D81DBF864365B12E269D /* idl_gen_text.cpp */,
|
||||
3709AC883348409592530AE6 /* idl_parser.cpp */,
|
||||
6AD24EEB3D024825A37741FF /* test.cpp */,
|
||||
8C8774621B703D4800E693F5 /* reflection.cpp */,
|
||||
);
|
||||
name = "Source Files";
|
||||
sourceTree = "<group>";
|
||||
@@ -75,52 +72,11 @@
|
||||
378446B9D5EF46EF92B35E21 /* flatc */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
5FEA84E7D39645988300317C /* Header Files */,
|
||||
28237E300FE042DEADA302D3 /* Source Files */,
|
||||
423CA92401AE442B91546E63 /* CMakeLists.txt */,
|
||||
0DFD29781D8E490284B06504 /* flatc.cpp */,
|
||||
);
|
||||
name = flatc;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
40E30B8480BD493EA459E9B4 /* Header Files */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
DD8B353D4756412195777FBA /* flatbuffers.h */,
|
||||
00154BD8654B4B5B9FF45FA6 /* idl.h */,
|
||||
C0E7B66C3FF849A0AD9A7168 /* util.h */,
|
||||
AD3682C6E1DD4EABB822C0CC /* monster_generated.h */,
|
||||
);
|
||||
name = "Header Files";
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
4D1151F6FE594E40A1C177FF /* Header Files */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
DD8B353D4756412195777FBA /* flatbuffers.h */,
|
||||
AD3682C6E1DD4EABB822C0CC /* monster_generated.h */,
|
||||
);
|
||||
name = "Header Files";
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
5235469653ED4BC88A6C504D /* Header Files */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
DD8B353D4756412195777FBA /* flatbuffers.h */,
|
||||
00154BD8654B4B5B9FF45FA6 /* idl.h */,
|
||||
C0E7B66C3FF849A0AD9A7168 /* util.h */,
|
||||
AB70F1FBA50E4120BCF37C8D /* monster_test_generated.h */,
|
||||
);
|
||||
name = "Header Files";
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
5648A71028E14478841372D3 /* Source Files */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
5EE44BFFAF8E43F485859145 /* sample_binary.cpp */,
|
||||
);
|
||||
name = "Source Files";
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
5FEA84E7D39645988300317C /* Header Files */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
@@ -134,6 +90,8 @@
|
||||
866694F9F2F7451382D236B3 /* Sources */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
28237E300FE042DEADA302D3 /* Source Files */,
|
||||
5FEA84E7D39645988300317C /* Header Files */,
|
||||
378446B9D5EF46EF92B35E21 /* flatc */,
|
||||
DB9DE41C20F349F694A488F3 /* flatsamplebinary */,
|
||||
8FA1F43C78914AE5AD04E24E /* flatsampletext */,
|
||||
@@ -145,8 +103,8 @@
|
||||
88421F5F87584EE3B67C979A /* flattests */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
5235469653ED4BC88A6C504D /* Header Files */,
|
||||
355DCA17961E4B2FB2C71403 /* Source Files */,
|
||||
AB70F1FBA50E4120BCF37C8D /* monster_test_generated.h */,
|
||||
6AD24EEB3D024825A37741FF /* test.cpp */,
|
||||
);
|
||||
name = flattests;
|
||||
sourceTree = "<group>";
|
||||
@@ -155,7 +113,6 @@
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
866694F9F2F7451382D236B3 /* Sources */,
|
||||
194905BCBB5C451DB092EB08 /* Resources */,
|
||||
99CC11E382B8420AA79A8A14 /* Products */,
|
||||
);
|
||||
sourceTree = "<group>";
|
||||
@@ -163,8 +120,7 @@
|
||||
8FA1F43C78914AE5AD04E24E /* flatsampletext */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
40E30B8480BD493EA459E9B4 /* Header Files */,
|
||||
A1C826615F904FDE8F0CA154 /* Source Files */,
|
||||
ECCEBFFA6977404F858F9739 /* sample_text.cpp */,
|
||||
);
|
||||
name = flatsampletext;
|
||||
sourceTree = "<group>";
|
||||
@@ -180,22 +136,10 @@
|
||||
name = Products;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
A1C826615F904FDE8F0CA154 /* Source Files */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
ECCEBFFA6977404F858F9739 /* sample_text.cpp */,
|
||||
F6C5D81DBF864365B12E269D /* idl_gen_text.cpp */,
|
||||
3709AC883348409592530AE6 /* idl_parser.cpp */,
|
||||
);
|
||||
name = "Source Files";
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
DB9DE41C20F349F694A488F3 /* flatsamplebinary */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
4D1151F6FE594E40A1C177FF /* Header Files */,
|
||||
5648A71028E14478841372D3 /* Source Files */,
|
||||
423CA92401AE442B91546E63 /* CMakeLists.txt */,
|
||||
5EE44BFFAF8E43F485859145 /* sample_binary.cpp */,
|
||||
);
|
||||
name = flatsamplebinary;
|
||||
sourceTree = "<group>";
|
||||
@@ -270,7 +214,7 @@
|
||||
isa = PBXProject;
|
||||
attributes = {
|
||||
BuildIndependentTargetsInParallel = YES;
|
||||
LastUpgradeCheck = 0510;
|
||||
LastUpgradeCheck = 0700;
|
||||
};
|
||||
buildConfigurationList = 6428BEB363AA4E03A282AA8C /* Build configuration list for PBXProject "FlatBuffers" */;
|
||||
compatibilityVersion = "Xcode 3.2";
|
||||
@@ -314,11 +258,15 @@
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
8C303C591975D6A700D7C1C5 /* idl_gen_go.cpp in Sources */,
|
||||
AA9BACF55EB3456BA2F633BB /* flatc.cpp in Sources */,
|
||||
BE03D7B0C9584DD58B50ED34 /* idl_gen_cpp.cpp in Sources */,
|
||||
3343DD4ED370434BBA148FAB /* idl_gen_java.cpp in Sources */,
|
||||
AD71FEBEE4E846529002C1F0 /* idl_gen_text.cpp in Sources */,
|
||||
8C8774641B703E1200E693F5 /* idl_gen_fbs.cpp in Sources */,
|
||||
A9C9A99F719A4ED58DC2D2FC /* idl_parser.cpp in Sources */,
|
||||
8CA854B31B04244A00040A06 /* idl_gen_python.cpp in Sources */,
|
||||
8CD8717B19CB937D0012A827 /* idl_gen_general.cpp in Sources */,
|
||||
8C78573E1BD5AE2C00C53C34 /* idl_gen_js.cpp in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
@@ -326,6 +274,9 @@
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
8C8774631B703D4800E693F5 /* reflection.cpp in Sources */,
|
||||
5AC48C391ACA9A0A008132C5 /* idl_gen_general.cpp in Sources */,
|
||||
8C6905FD19F835B400CB8866 /* idl_gen_fbs.cpp in Sources */,
|
||||
E0680D6B5BFD484BA9D88EE8 /* idl_gen_text.cpp in Sources */,
|
||||
61823BBC53544106B6DBC38E /* idl_parser.cpp in Sources */,
|
||||
EE4AEE138D684B30A1BF5462 /* test.cpp in Sources */,
|
||||
@@ -340,7 +291,7 @@
|
||||
buildSettings = {
|
||||
CONFIGURATION_BUILD_DIR = .;
|
||||
ONLY_ACTIVE_ARCH = YES;
|
||||
SDKROOT = /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk;
|
||||
SDKROOT = macosx;
|
||||
SYMROOT = build;
|
||||
};
|
||||
name = RelWithDebInfo;
|
||||
@@ -348,6 +299,11 @@
|
||||
04681CC521204B3B87BB1E81 /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CLANG_WARN_ASSIGN_ENUM = YES;
|
||||
CLANG_WARN_EMPTY_BODY = YES;
|
||||
CLANG_WARN_IMPLICIT_SIGN_CONVERSION = NO;
|
||||
CLANG_WARN_SUSPICIOUS_IMPLICIT_CONVERSION = YES;
|
||||
CLANG_WARN_UNREACHABLE_CODE = YES;
|
||||
COMBINE_HIDPI_IMAGES = YES;
|
||||
EXECUTABLE_PREFIX = "";
|
||||
EXECUTABLE_SUFFIX = "";
|
||||
@@ -356,6 +312,25 @@
|
||||
GCC_OPTIMIZATION_LEVEL = 0;
|
||||
GCC_PREPROCESSOR_DEFINITIONS = "'CMAKE_INTDIR=\"$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)\"'";
|
||||
GCC_SYMBOLS_PRIVATE_EXTERN = NO;
|
||||
GCC_TREAT_IMPLICIT_FUNCTION_DECLARATIONS_AS_ERRORS = YES;
|
||||
GCC_TREAT_INCOMPATIBLE_POINTER_TYPE_WARNINGS_AS_ERRORS = YES;
|
||||
GCC_TREAT_WARNINGS_AS_ERRORS = YES;
|
||||
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
|
||||
GCC_WARN_ABOUT_MISSING_FIELD_INITIALIZERS = YES;
|
||||
GCC_WARN_ABOUT_MISSING_NEWLINE = YES;
|
||||
GCC_WARN_ABOUT_MISSING_PROTOTYPES = NO;
|
||||
GCC_WARN_ABOUT_RETURN_TYPE = YES;
|
||||
GCC_WARN_FOUR_CHARACTER_CONSTANTS = YES;
|
||||
GCC_WARN_INITIALIZER_NOT_FULLY_BRACKETED = YES;
|
||||
GCC_WARN_PEDANTIC = YES;
|
||||
GCC_WARN_SHADOW = YES;
|
||||
GCC_WARN_SIGN_COMPARE = YES;
|
||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||
GCC_WARN_UNKNOWN_PRAGMAS = YES;
|
||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||
GCC_WARN_UNUSED_LABEL = YES;
|
||||
GCC_WARN_UNUSED_PARAMETER = YES;
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
HEADER_SEARCH_PATHS = "$(PROJECT_DIR)/include";
|
||||
INSTALL_PATH = "";
|
||||
LIBRARY_SEARCH_PATHS = "";
|
||||
@@ -453,6 +428,11 @@
|
||||
33335DE09CF844709E9E4AA9 /* RelWithDebInfo */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CLANG_WARN_ASSIGN_ENUM = YES;
|
||||
CLANG_WARN_EMPTY_BODY = YES;
|
||||
CLANG_WARN_IMPLICIT_SIGN_CONVERSION = NO;
|
||||
CLANG_WARN_SUSPICIOUS_IMPLICIT_CONVERSION = YES;
|
||||
CLANG_WARN_UNREACHABLE_CODE = YES;
|
||||
COMBINE_HIDPI_IMAGES = YES;
|
||||
EXECUTABLE_PREFIX = "";
|
||||
EXECUTABLE_SUFFIX = "";
|
||||
@@ -461,6 +441,25 @@
|
||||
GCC_OPTIMIZATION_LEVEL = 2;
|
||||
GCC_PREPROCESSOR_DEFINITIONS = "'CMAKE_INTDIR=\"$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)\"'";
|
||||
GCC_SYMBOLS_PRIVATE_EXTERN = NO;
|
||||
GCC_TREAT_IMPLICIT_FUNCTION_DECLARATIONS_AS_ERRORS = YES;
|
||||
GCC_TREAT_INCOMPATIBLE_POINTER_TYPE_WARNINGS_AS_ERRORS = YES;
|
||||
GCC_TREAT_WARNINGS_AS_ERRORS = YES;
|
||||
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
|
||||
GCC_WARN_ABOUT_MISSING_FIELD_INITIALIZERS = YES;
|
||||
GCC_WARN_ABOUT_MISSING_NEWLINE = YES;
|
||||
GCC_WARN_ABOUT_MISSING_PROTOTYPES = NO;
|
||||
GCC_WARN_ABOUT_RETURN_TYPE = YES;
|
||||
GCC_WARN_FOUR_CHARACTER_CONSTANTS = YES;
|
||||
GCC_WARN_INITIALIZER_NOT_FULLY_BRACKETED = YES;
|
||||
GCC_WARN_PEDANTIC = YES;
|
||||
GCC_WARN_SHADOW = YES;
|
||||
GCC_WARN_SIGN_COMPARE = YES;
|
||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||
GCC_WARN_UNKNOWN_PRAGMAS = YES;
|
||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||
GCC_WARN_UNUSED_LABEL = YES;
|
||||
GCC_WARN_UNUSED_PARAMETER = YES;
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
HEADER_SEARCH_PATHS = "$(PROJECT_DIR)/include";
|
||||
INSTALL_PATH = "";
|
||||
LIBRARY_SEARCH_PATHS = "";
|
||||
@@ -492,6 +491,11 @@
|
||||
33B3983234F648E28F058235 /* MinSizeRel */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CLANG_WARN_ASSIGN_ENUM = YES;
|
||||
CLANG_WARN_EMPTY_BODY = YES;
|
||||
CLANG_WARN_IMPLICIT_SIGN_CONVERSION = NO;
|
||||
CLANG_WARN_SUSPICIOUS_IMPLICIT_CONVERSION = YES;
|
||||
CLANG_WARN_UNREACHABLE_CODE = YES;
|
||||
COMBINE_HIDPI_IMAGES = YES;
|
||||
EXECUTABLE_PREFIX = "";
|
||||
EXECUTABLE_SUFFIX = "";
|
||||
@@ -500,6 +504,25 @@
|
||||
GCC_OPTIMIZATION_LEVEL = s;
|
||||
GCC_PREPROCESSOR_DEFINITIONS = "'CMAKE_INTDIR=\"$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)\"'";
|
||||
GCC_SYMBOLS_PRIVATE_EXTERN = NO;
|
||||
GCC_TREAT_IMPLICIT_FUNCTION_DECLARATIONS_AS_ERRORS = YES;
|
||||
GCC_TREAT_INCOMPATIBLE_POINTER_TYPE_WARNINGS_AS_ERRORS = YES;
|
||||
GCC_TREAT_WARNINGS_AS_ERRORS = YES;
|
||||
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
|
||||
GCC_WARN_ABOUT_MISSING_FIELD_INITIALIZERS = YES;
|
||||
GCC_WARN_ABOUT_MISSING_NEWLINE = YES;
|
||||
GCC_WARN_ABOUT_MISSING_PROTOTYPES = NO;
|
||||
GCC_WARN_ABOUT_RETURN_TYPE = YES;
|
||||
GCC_WARN_FOUR_CHARACTER_CONSTANTS = YES;
|
||||
GCC_WARN_INITIALIZER_NOT_FULLY_BRACKETED = YES;
|
||||
GCC_WARN_PEDANTIC = YES;
|
||||
GCC_WARN_SHADOW = YES;
|
||||
GCC_WARN_SIGN_COMPARE = YES;
|
||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||
GCC_WARN_UNKNOWN_PRAGMAS = YES;
|
||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||
GCC_WARN_UNUSED_LABEL = YES;
|
||||
GCC_WARN_UNUSED_PARAMETER = YES;
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
HEADER_SEARCH_PATHS = "$(PROJECT_DIR)/include";
|
||||
INSTALL_PATH = "";
|
||||
LIBRARY_SEARCH_PATHS = "";
|
||||
@@ -570,6 +593,11 @@
|
||||
37C0FFB777CF4C19BD7AA662 /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CLANG_WARN_ASSIGN_ENUM = YES;
|
||||
CLANG_WARN_EMPTY_BODY = YES;
|
||||
CLANG_WARN_IMPLICIT_SIGN_CONVERSION = NO;
|
||||
CLANG_WARN_SUSPICIOUS_IMPLICIT_CONVERSION = YES;
|
||||
CLANG_WARN_UNREACHABLE_CODE = YES;
|
||||
COMBINE_HIDPI_IMAGES = YES;
|
||||
EXECUTABLE_PREFIX = "";
|
||||
EXECUTABLE_SUFFIX = "";
|
||||
@@ -578,6 +606,25 @@
|
||||
GCC_OPTIMIZATION_LEVEL = 3;
|
||||
GCC_PREPROCESSOR_DEFINITIONS = "'CMAKE_INTDIR=\"$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)\"'";
|
||||
GCC_SYMBOLS_PRIVATE_EXTERN = NO;
|
||||
GCC_TREAT_IMPLICIT_FUNCTION_DECLARATIONS_AS_ERRORS = YES;
|
||||
GCC_TREAT_INCOMPATIBLE_POINTER_TYPE_WARNINGS_AS_ERRORS = YES;
|
||||
GCC_TREAT_WARNINGS_AS_ERRORS = YES;
|
||||
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
|
||||
GCC_WARN_ABOUT_MISSING_FIELD_INITIALIZERS = YES;
|
||||
GCC_WARN_ABOUT_MISSING_NEWLINE = YES;
|
||||
GCC_WARN_ABOUT_MISSING_PROTOTYPES = NO;
|
||||
GCC_WARN_ABOUT_RETURN_TYPE = YES;
|
||||
GCC_WARN_FOUR_CHARACTER_CONSTANTS = YES;
|
||||
GCC_WARN_INITIALIZER_NOT_FULLY_BRACKETED = YES;
|
||||
GCC_WARN_PEDANTIC = YES;
|
||||
GCC_WARN_SHADOW = YES;
|
||||
GCC_WARN_SIGN_COMPARE = YES;
|
||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||
GCC_WARN_UNKNOWN_PRAGMAS = YES;
|
||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||
GCC_WARN_UNUSED_LABEL = YES;
|
||||
GCC_WARN_UNUSED_PARAMETER = YES;
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
HEADER_SEARCH_PATHS = "$(PROJECT_DIR)/include";
|
||||
INSTALL_PATH = "";
|
||||
LIBRARY_SEARCH_PATHS = "";
|
||||
@@ -760,8 +807,9 @@
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CONFIGURATION_BUILD_DIR = .;
|
||||
ENABLE_TESTABILITY = YES;
|
||||
ONLY_ACTIVE_ARCH = YES;
|
||||
SDKROOT = /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk;
|
||||
SDKROOT = macosx;
|
||||
SYMROOT = build;
|
||||
};
|
||||
name = Debug;
|
||||
@@ -771,7 +819,7 @@
|
||||
buildSettings = {
|
||||
CONFIGURATION_BUILD_DIR = .;
|
||||
ONLY_ACTIVE_ARCH = YES;
|
||||
SDKROOT = /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk;
|
||||
SDKROOT = macosx;
|
||||
SYMROOT = build;
|
||||
};
|
||||
name = Release;
|
||||
@@ -931,7 +979,7 @@
|
||||
buildSettings = {
|
||||
CONFIGURATION_BUILD_DIR = .;
|
||||
ONLY_ACTIVE_ARCH = YES;
|
||||
SDKROOT = /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk;
|
||||
SDKROOT = macosx;
|
||||
SYMROOT = build;
|
||||
};
|
||||
name = MinSizeRel;
|
||||
|
||||
62
docs/header.html
Normal file
62
docs/header.html
Normal file
@@ -0,0 +1,62 @@
|
||||
<!-- HTML header for doxygen 1.8.6-->
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
||||
<html xmlns="http://www.w3.org/1999/xhtml">
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
|
||||
<meta name="generator" content="Doxygen $doxygenversion"/>
|
||||
<!--BEGIN PROJECT_NAME--><title>$projectname: $title</title><!--END PROJECT_NAME-->
|
||||
<!--BEGIN !PROJECT_NAME--><title>$title</title><!--END !PROJECT_NAME-->
|
||||
<link href="$relpath^tabs.css" rel="stylesheet" type="text/css"/>
|
||||
<script type="text/javascript" src="$relpath^jquery.js"></script>
|
||||
<script type="text/javascript" src="$relpath^dynsections.js"></script>
|
||||
$treeview
|
||||
$search
|
||||
$mathjax
|
||||
<link href="$relpath^$stylesheet" rel="stylesheet" type="text/css" />
|
||||
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,400italic,500,500italic,700,700italic|Roboto+Mono:400,700" rel="stylesheet">
|
||||
$extrastylesheet
|
||||
</head>
|
||||
<body>
|
||||
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
|
||||
|
||||
<!--BEGIN TITLEAREA-->
|
||||
<div id="titlearea" style="height: 110px;">
|
||||
<table cellspacing="0" cellpadding="0">
|
||||
<tbody>
|
||||
<tr style="height: 56px;">
|
||||
<!--BEGIN PROJECT_LOGO-->
|
||||
<td id="projectlogo"><img alt="Logo" src="$relpath^$projectlogo"/></td>
|
||||
<!--END PROJECT_LOGO-->
|
||||
<td id="commonprojectlogo">
|
||||
<img alt="Logo" src="$relpath^fpl_logo_small.png"/>
|
||||
</td>
|
||||
<!--BEGIN PROJECT_NAME-->
|
||||
<td style="padding-left: 0.5em;">
|
||||
<div id="projectname">$projectname
|
||||
<!--BEGIN PROJECT_NUMBER--> <span id="projectnumber">$projectnumber</span><!--END PROJECT_NUMBER-->
|
||||
</div>
|
||||
<div style="font-size:12px;">
|
||||
An open source project by <a href="https://developers.google.com/games/#Tools">FPL</a>.
|
||||
</div>
|
||||
<!--BEGIN PROJECT_BRIEF--><div id="projectbrief">$projectbrief</div><!--END PROJECT_BRIEF-->
|
||||
</td>
|
||||
<!--END PROJECT_NAME-->
|
||||
<!--BEGIN !PROJECT_NAME-->
|
||||
<!--BEGIN PROJECT_BRIEF-->
|
||||
<td style="padding-left: 0.5em;">
|
||||
<div id="projectbrief">$projectbrief</div>
|
||||
</td>
|
||||
<!--END PROJECT_BRIEF-->
|
||||
<!--END !PROJECT_NAME-->
|
||||
<!--BEGIN DISABLE_INDEX-->
|
||||
<!--BEGIN SEARCHENGINE-->
|
||||
<td>$searchbox</td>
|
||||
<!--END SEARCHENGINE-->
|
||||
<!--END DISABLE_INDEX-->
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<!--END TITLEAREA-->
|
||||
<!-- end header part -->
|
||||
@@ -1,4 +1,4 @@
|
||||
/* The standard CSS for doxygen 1.8.5 */
|
||||
/* The standard CSS for doxygen 1.8.7 */
|
||||
|
||||
body, table, div, p, dl {
|
||||
font: 400 14px/22px Roboto,sans-serif;
|
||||
@@ -56,10 +56,14 @@ div.multicol {
|
||||
-webkit-column-count: 3;
|
||||
}
|
||||
|
||||
p.startli, p.startdd, p.starttd {
|
||||
p.startli, p.startdd {
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
p.starttd {
|
||||
margin-top: 0px;
|
||||
}
|
||||
|
||||
p.endli {
|
||||
margin-bottom: 0px;
|
||||
}
|
||||
@@ -169,8 +173,8 @@ pre.fragment {
|
||||
}
|
||||
|
||||
div.fragment {
|
||||
padding: 0px;
|
||||
margin: 0px;
|
||||
padding: 4px 6px;
|
||||
margin: 4px 8px 4px 2px;
|
||||
background-color: #FBFCFD;
|
||||
border: 1px solid #C4CFE5;
|
||||
}
|
||||
@@ -666,12 +670,12 @@ span.mlabel {
|
||||
|
||||
/* @end */
|
||||
|
||||
/* these are for tree view when not used as main index */
|
||||
/* these are for tree view inside a (index) page */
|
||||
|
||||
div.directory {
|
||||
margin: 10px 0px;
|
||||
border-top: 1px solid #A8B8D9;
|
||||
border-bottom: 1px solid #A8B8D9;
|
||||
border-top: 1px solid #9CAFD4;
|
||||
border-bottom: 1px solid #9CAFD4;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
@@ -730,6 +734,80 @@ div.directory {
|
||||
color: #3D578C;
|
||||
}
|
||||
|
||||
.arrow {
|
||||
color: #9CAFD4;
|
||||
-webkit-user-select: none;
|
||||
-khtml-user-select: none;
|
||||
-moz-user-select: none;
|
||||
-ms-user-select: none;
|
||||
user-select: none;
|
||||
cursor: pointer;
|
||||
font-size: 80%;
|
||||
display: inline-block;
|
||||
width: 16px;
|
||||
height: 22px;
|
||||
}
|
||||
|
||||
.icon {
|
||||
font-family: Arial, Helvetica;
|
||||
font-weight: bold;
|
||||
font-size: 12px;
|
||||
height: 14px;
|
||||
width: 16px;
|
||||
display: inline-block;
|
||||
background-color: #728DC1;
|
||||
color: white;
|
||||
text-align: center;
|
||||
border-radius: 4px;
|
||||
margin-left: 2px;
|
||||
margin-right: 2px;
|
||||
}
|
||||
|
||||
.icona {
|
||||
width: 24px;
|
||||
height: 22px;
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
.iconfopen {
|
||||
width: 24px;
|
||||
height: 18px;
|
||||
margin-bottom: 4px;
|
||||
background-image:url('ftv2folderopen.png');
|
||||
background-position: 0px -4px;
|
||||
background-repeat: repeat-y;
|
||||
vertical-align:top;
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
.iconfclosed {
|
||||
width: 24px;
|
||||
height: 18px;
|
||||
margin-bottom: 4px;
|
||||
background-image:url('ftv2folderclosed.png');
|
||||
background-position: 0px -4px;
|
||||
background-repeat: repeat-y;
|
||||
vertical-align:top;
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
.icondoc {
|
||||
width: 24px;
|
||||
height: 18px;
|
||||
margin-bottom: 4px;
|
||||
background-image:url('ftv2doc.png');
|
||||
background-position: 0px -4px;
|
||||
background-repeat: repeat-y;
|
||||
vertical-align:top;
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
table.directory {
|
||||
font: 400 14px Roboto,sans-serif;
|
||||
}
|
||||
|
||||
/* @end */
|
||||
|
||||
div.dynheader {
|
||||
margin-top: 8px;
|
||||
-webkit-touch-callout: none;
|
||||
@@ -1065,6 +1143,11 @@ dl.section dd {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.diagraph
|
||||
{
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.caption
|
||||
{
|
||||
font-weight: bold;
|
||||
|
||||
@@ -24,19 +24,20 @@ function updateStripes()
|
||||
$('table.directory tr').
|
||||
removeClass('even').filter(':visible:even').addClass('even');
|
||||
}
|
||||
|
||||
function toggleLevel(level)
|
||||
{
|
||||
$('table.directory tr').each(function(){
|
||||
$('table.directory tr').each(function() {
|
||||
var l = this.id.split('_').length-1;
|
||||
var i = $('#img'+this.id.substring(3));
|
||||
var a = $('#arr'+this.id.substring(3));
|
||||
if (l<level+1) {
|
||||
i.attr('src','ftv2folderopen.png');
|
||||
a.attr('src','ftv2mnode.png');
|
||||
i.removeClass('iconfopen iconfclosed').addClass('iconfopen');
|
||||
a.html('▼');
|
||||
$(this).show();
|
||||
} else if (l==level+1) {
|
||||
i.attr('src','ftv2folderclosed.png');
|
||||
a.attr('src','ftv2pnode.png');
|
||||
i.removeClass('iconfclosed iconfopen').addClass('iconfclosed');
|
||||
a.html('►');
|
||||
$(this).show();
|
||||
} else {
|
||||
$(this).hide();
|
||||
@@ -47,34 +48,33 @@ function toggleLevel(level)
|
||||
|
||||
function toggleFolder(id)
|
||||
{
|
||||
//The clicked row
|
||||
// the clicked row
|
||||
var currentRow = $('#row_'+id);
|
||||
var currentRowImages = currentRow.find("img");
|
||||
|
||||
//All rows after the clicked row
|
||||
// all rows after the clicked row
|
||||
var rows = currentRow.nextAll("tr");
|
||||
|
||||
//Only match elements AFTER this one (can't hide elements before)
|
||||
var childRows = rows.filter(function() {
|
||||
var re = new RegExp('^row_'+id+'\\d+_$', "i"); //only one sub
|
||||
return this.id.match(re);
|
||||
});
|
||||
var re = new RegExp('^row_'+id+'\\d+_$', "i"); //only one sub
|
||||
|
||||
//First row is visible we are HIDING
|
||||
// only match elements AFTER this one (can't hide elements before)
|
||||
var childRows = rows.filter(function() { return this.id.match(re); });
|
||||
|
||||
// first row is visible we are HIDING
|
||||
if (childRows.filter(':first').is(':visible')===true) {
|
||||
currentRowImages.filter("[id^=arr]").attr('src', 'ftv2pnode.png');
|
||||
currentRowImages.filter("[id^=img]").attr('src', 'ftv2folderclosed.png');
|
||||
rows.filter("[id^=row_"+id+"]").hide();
|
||||
} else { //We are SHOWING
|
||||
//All sub images
|
||||
var childImages = childRows.find("img");
|
||||
var childImg = childImages.filter("[id^=img]");
|
||||
var childArr = childImages.filter("[id^=arr]");
|
||||
|
||||
currentRow.find("[id^=arr]").attr('src', 'ftv2mnode.png'); //open row
|
||||
currentRow.find("[id^=img]").attr('src', 'ftv2folderopen.png'); //open row
|
||||
childImg.attr('src','ftv2folderclosed.png'); //children closed
|
||||
childArr.attr('src','ftv2pnode.png'); //children closed
|
||||
// replace down arrow by right arrow for current row
|
||||
var currentRowSpans = currentRow.find("span");
|
||||
currentRowSpans.filter(".iconfopen").removeClass("iconfopen").addClass("iconfclosed");
|
||||
currentRowSpans.filter(".arrow").html('►');
|
||||
rows.filter("[id^=row_"+id+"]").hide(); // hide all children
|
||||
} else { // we are SHOWING
|
||||
// replace right arrow by down arrow for current row
|
||||
var currentRowSpans = currentRow.find("span");
|
||||
currentRowSpans.filter(".iconfclosed").removeClass("iconfclosed").addClass("iconfopen");
|
||||
currentRowSpans.filter(".arrow").html('▼');
|
||||
// replace down arrows by right arrows for child rows
|
||||
var childRowsSpans = childRows.find("span");
|
||||
childRowsSpans.filter(".iconfopen").removeClass("iconfopen").addClass("iconfclosed");
|
||||
childRowsSpans.filter(".arrow").html('►');
|
||||
childRows.show(); //show all children
|
||||
}
|
||||
updateStripes();
|
||||
|
||||
BIN
docs/html/fpl_logo_small.png
Normal file
BIN
docs/html/fpl_logo_small.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 5.0 KiB |
@@ -1,9 +1,10 @@
|
||||
<!-- HTML header for doxygen 1.8.6-->
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
||||
<html xmlns="http://www.w3.org/1999/xhtml">
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
|
||||
<meta name="generator" content="Doxygen 1.8.5"/>
|
||||
<meta name="generator" content="Doxygen 1.8.7"/>
|
||||
<title>FlatBuffers: Main Page</title>
|
||||
<link href="tabs.css" rel="stylesheet" type="text/css"/>
|
||||
<script type="text/javascript" src="jquery.js"></script>
|
||||
@@ -15,24 +16,31 @@
|
||||
$(document).ready(initResizable);
|
||||
$(window).load(resizeHeight);
|
||||
</script>
|
||||
<link href="doxygen.css" rel="stylesheet" type="text/css" />
|
||||
<link href="style.css" rel="stylesheet" type="text/css" />
|
||||
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,400italic,500,500italic,700,700italic|Roboto+Mono:400,700" rel="stylesheet">
|
||||
</head>
|
||||
<body>
|
||||
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
|
||||
<div id="titlearea">
|
||||
<div id="titlearea" style="height: 110px;">
|
||||
<table cellspacing="0" cellpadding="0">
|
||||
<tbody>
|
||||
<tr style="height: 56px;">
|
||||
<td id="commonprojectlogo">
|
||||
<img alt="Logo" src="fpl_logo_small.png"/>
|
||||
</td>
|
||||
<td style="padding-left: 0.5em;">
|
||||
<div id="projectname">FlatBuffers
|
||||
</div>
|
||||
<div style="font-size:12px;">
|
||||
An open source project by <a href="https://developers.google.com/games/#Tools">FPL</a>.
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<!-- end header part -->
|
||||
<!-- Generated by Doxygen 1.8.5 -->
|
||||
<!-- Generated by Doxygen 1.8.7 -->
|
||||
</div><!-- top -->
|
||||
<div id="side-nav" class="ui-resizable side-nav-resizable">
|
||||
<div id="nav-tree">
|
||||
@@ -53,8 +61,8 @@ $(document).ready(function(){initNavTree('index.html','');});
|
||||
<div class="title">FlatBuffers Documentation</div> </div>
|
||||
</div><!--header-->
|
||||
<div class="contents">
|
||||
<div class="textblock"><p>FlatBuffers is an efficient cross platform serialization library in for C++ and Java. It was created at Google specifically for game development and other performance-critical applications.</p>
|
||||
<p>It is available as open source under the Apache license, v2 (see LICENSE.txt).</p>
|
||||
<div class="textblock"><p>FlatBuffers is an efficient cross platform serialization library for C++, with support for Java, C# and Go. It was created at Google specifically for game development and other performance-critical applications.</p>
|
||||
<p>It is available as Open Source on <a href="http://github.com/google/flatbuffers">GitHub</a> under the Apache license, v2 (see LICENSE.txt).</p>
|
||||
<h2>Why use FlatBuffers?</h2>
|
||||
<ul>
|
||||
<li><b>Access to serialized data without parsing/unpacking</b> - What sets FlatBuffers apart is that it represents hierarchical data in a flat binary buffer in such a way that it can still be accessed directly without parsing/unpacking, while also still supporting data structure evolution (forwards/backwards compatibility).</li>
|
||||
@@ -63,20 +71,26 @@ $(document).ready(function(){initNavTree('index.html','');});
|
||||
<li><b>Tiny code footprint</b> - Small amounts of generated code, and just a single small header as the minimum dependency, which is very easy to integrate. Again, see the benchmark section for details.</li>
|
||||
<li><b>Strongly typed</b> - Errors happen at compile time rather than manually having to write repetitive and error prone run-time checks. Useful code can be generated for you.</li>
|
||||
<li><p class="startli"><b>Convenient to use</b> - Generated C++ code allows for terse access & construction code. Then there's optional functionality for parsing schemas and JSON-like text representations at runtime efficiently if needed (faster and more memory efficient than other JSON parsers).</p>
|
||||
<p class="startli">Java code supports object-reuse.</p>
|
||||
<p class="startli">Java and Go code supports object-reuse.</p>
|
||||
</li>
|
||||
<li><b>Cross platform C++11/Java code with no dependencies</b> - will work with any recent gcc/clang and VS2010. Comes with build files for the tests & samples (Android .mk files, and cmake for all other platforms).</li>
|
||||
<li><b>Cross platform C++11/Java/C#/Go code with no dependencies</b> - will work with any recent gcc/clang and VS2010. Comes with build files for the tests & samples (Android .mk files, and cmake for all other platforms).</li>
|
||||
</ul>
|
||||
<h3>Why not use Protocol Buffers, or .. ?</h3>
|
||||
<p>Protocol Buffers is indeed relatively similar to FlatBuffers, with the primary difference being that FlatBuffers does not need a parsing/ unpacking step to a secondary representation before you can access data, often coupled with per-object memory allocation. The code is an order of magnitude bigger, too. Protocol Buffers has neither optional text import/export nor schema language features like unions.</p>
|
||||
<h3>But all the cool kids use JSON!</h3>
|
||||
<p>JSON is very readable (which is why we use it as our optional text format) and very convenient when used together with dynamically typed languages (such as JavaScript). When serializing data from statically typed languages, however, JSON not only has the obvious drawback of runtime inefficiency, but also forces you to write <em>more</em> code to access data (counterintuitively) due to its dynamic-typing serialization system. In this context, it is only a better choice for systems that have very little to no information ahead of time about what data needs to be stored.</p>
|
||||
<p>Read more about the "why" of FlatBuffers in the <a href="md__white_paper.html">white paper</a>.</p>
|
||||
<h3>Who uses FlatBuffers?</h3>
|
||||
<ul>
|
||||
<li><a href="http://www.cocos2d-x.org/">Cocos2d-x</a>, the #1 open source mobile game engine, uses it to serialize all their <a href="http://www.cocos2d-x.org/reference/native-cpp/V3.5/d7/d2d/namespaceflatbuffers.html">game data</a>.</li>
|
||||
<li><a href="http://facebook.com/">Facebook</a> uses it for client-server communication in their Android app. They have a nice <a href="https://code.facebook.com/posts/872547912839369/improving-facebook-s-performance-on-android-with-flatbuffers/">article</a> explaining how it speeds up loading their posts.</li>
|
||||
<li><a href="https://developers.google.com/games/#Tools">Fun Propulsion Labs</a> at Google uses it extensively in all their libraries and games.</li>
|
||||
</ul>
|
||||
<h2>Usage in brief</h2>
|
||||
<p>This section is a quick rundown of how to use this system. Subsequent sections provide a more in-depth usage guide.</p>
|
||||
<ul>
|
||||
<li>Write a schema file that allows you to define the data structures you may want to serialize. Fields can have a scalar type (ints/floats of all sizes), or they can be a: string; array of any type; reference to yet another object; or, a set of possible objects (unions). Fields are optional and have defaults, so they don't need to be present for every object instance.</li>
|
||||
<li>Use <code>flatc</code> (the FlatBuffer compiler) to generate a C++ header (or Java classes) with helper classes to access and construct serialized data. This header (say <code>mydata_generated.h</code>) only depends on <code>flatbuffers.h</code>, which defines the core functionality.</li>
|
||||
<li>Use <code>flatc</code> (the FlatBuffer compiler) to generate a C++ header (or Java/C#/Go/Python.. classes) with helper classes to access and construct serialized data. This header (say <code>mydata_generated.h</code>) only depends on <code>flatbuffers.h</code>, which defines the core functionality.</li>
|
||||
<li>Use the <code>FlatBufferBuilder</code> class to construct a flat binary buffer. The generated functions allow you to add objects to this buffer recursively, often as simply as making a single function call.</li>
|
||||
<li>Store or send your buffer somewhere!</li>
|
||||
<li>When reading it back, you can obtain the pointer to the root object from the binary buffer, and from there traverse it conveniently in-place with <code>object->field()</code>.</li>
|
||||
@@ -87,7 +101,9 @@ $(document).ready(function(){initNavTree('index.html','');});
|
||||
<li>How to <a href="md__compiler.html">use the compiler</a>.</li>
|
||||
<li>How to <a href="md__schemas.html">write a schema</a>.</li>
|
||||
<li>How to <a href="md__cpp_usage.html">use the generated C++ code</a> in your own programs.</li>
|
||||
<li>How to <a href="md__java_usage.html">use the generated Java code</a> in your own programs.</li>
|
||||
<li>How to <a href="md__java_usage.html">use the generated Java/C# code</a> in your own programs.</li>
|
||||
<li>How to <a href="md__go_usage.html">use the generated Go code</a> in your own programs.</li>
|
||||
<li><a href="md__support.html">Support matrix</a> for platforms/languages/features.</li>
|
||||
<li>Some <a href="md__benchmarks.html">benchmarks</a> showing the advantage of using FlatBuffers.</li>
|
||||
<li>A <a href="md__white_paper.html">white paper</a> explaining the "why" of FlatBuffers.</li>
|
||||
<li>A description of the <a href="md__internals.html">internals</a> of FlatBuffers.</li>
|
||||
@@ -95,10 +111,21 @@ $(document).ready(function(){initNavTree('index.html','');});
|
||||
</ul>
|
||||
<h2>Online resources</h2>
|
||||
<ul>
|
||||
<li><a href="http://github.com/google/flatbuffers">github repository</a></li>
|
||||
<li><a href="http://google.github.io/flatbuffers">landing page</a></li>
|
||||
<li><a href="http://github.com/google/flatbuffers">GitHub repository</a></li>
|
||||
<li><a href="http://google.github.io/flatbuffers">Landing page</a></li>
|
||||
<li><a href="http://group.google.com/group/flatbuffers">FlatBuffers Google Group</a></li>
|
||||
<li><a href="http://github.com/google/flatbuffers/issues">FlatBuffers Issues Tracker</a> </li>
|
||||
<li><a href="http://github.com/google/flatbuffers/issues">FlatBuffers Issues Tracker</a></li>
|
||||
<li>Videos:<ul>
|
||||
<li>Colt's <a href="https://www.youtube.com/watch?v=iQTxMkSJ1dQ">DevByte</a>.</li>
|
||||
<li>GDC 2015 <a href="https://www.youtube.com/watch?v=olmL1fUnQAQ">Lightning Talk</a>.</li>
|
||||
<li>FlatBuffers for <a href="https://www.youtube.com/watch?v=-BPVId_lA5w">Go</a>.</li>
|
||||
<li>Evolution of FlatBuffers <a href="https://www.youtube.com/watch?v=a0QE0xS8rKM">visualization</a>.</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li>Useful documentation created by others:<ul>
|
||||
<li><a href="http://exiin.com/blog/flatbuffers-for-unity-sample-code/">Using FlatBuffers in Unity</a> </li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</div></div><!-- contents -->
|
||||
</div><!-- doc-content -->
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
<!-- HTML header for doxygen 1.8.6-->
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
||||
<html xmlns="http://www.w3.org/1999/xhtml">
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
|
||||
<meta name="generator" content="Doxygen 1.8.5"/>
|
||||
<meta name="generator" content="Doxygen 1.8.7"/>
|
||||
<title>FlatBuffers: Benchmarks</title>
|
||||
<link href="tabs.css" rel="stylesheet" type="text/css"/>
|
||||
<script type="text/javascript" src="jquery.js"></script>
|
||||
@@ -15,24 +16,31 @@
|
||||
$(document).ready(initResizable);
|
||||
$(window).load(resizeHeight);
|
||||
</script>
|
||||
<link href="doxygen.css" rel="stylesheet" type="text/css" />
|
||||
<link href="style.css" rel="stylesheet" type="text/css" />
|
||||
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,400italic,500,500italic,700,700italic|Roboto+Mono:400,700" rel="stylesheet">
|
||||
</head>
|
||||
<body>
|
||||
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
|
||||
<div id="titlearea">
|
||||
<div id="titlearea" style="height: 110px;">
|
||||
<table cellspacing="0" cellpadding="0">
|
||||
<tbody>
|
||||
<tr style="height: 56px;">
|
||||
<td id="commonprojectlogo">
|
||||
<img alt="Logo" src="fpl_logo_small.png"/>
|
||||
</td>
|
||||
<td style="padding-left: 0.5em;">
|
||||
<div id="projectname">FlatBuffers
|
||||
</div>
|
||||
<div style="font-size:12px;">
|
||||
An open source project by <a href="https://developers.google.com/games/#Tools">FPL</a>.
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<!-- end header part -->
|
||||
<!-- Generated by Doxygen 1.8.5 -->
|
||||
<!-- Generated by Doxygen 1.8.7 -->
|
||||
</div><!-- top -->
|
||||
<div id="side-nav" class="ui-resizable side-nav-resizable">
|
||||
<div id="nav-tree">
|
||||
@@ -53,37 +61,37 @@ $(document).ready(function(){initNavTree('md__benchmarks.html','');});
|
||||
<div class="title">Benchmarks </div> </div>
|
||||
</div><!--header-->
|
||||
<div class="contents">
|
||||
<div class="textblock"><p>Comparing against other serialization solutions, running on Windows 7 64bit. We use the LITE runtime for Protocol Buffers (less code / lower overhead), and Rapid JSON, one of the fastest C++ JSON parsers around.</p>
|
||||
<div class="textblock"><p>Comparing against other serialization solutions, running on Windows 7 64bit. We use the LITE runtime for Protocol Buffers (less code / lower overhead), Rapid JSON (one of the fastest C++ JSON parsers around), and pugixml, also one of the fastest XML parsers.</p>
|
||||
<p>We also compare against code that doesn't use a serialization library at all (the column "Raw structs"), which is what you get if you write hardcoded code that just writes structs. This is the fastest possible, but of course is not cross platform nor has any kind of forwards / backwards compatibility.</p>
|
||||
<p>We compare against Flatbuffers with the binary wire format (as intended), and also with JSON as the wire format with the optional JSON parser (which, using a schema, parses JSON into a binary buffer that can then be accessed as before).</p>
|
||||
<p>The benchmark object is a set of about 10 objects containing an array, 4 strings, and a large variety of int/float scalar values of all sizes, meant to be representative of game data, e.g. a scene format.</p>
|
||||
<table class="doxtable">
|
||||
<tr>
|
||||
<th></th><th>FlatBuffers (binary) </th><th>Protocol Buffers LITE </th><th>Rapid JSON </th><th>FlatBuffers (JSON) </th></tr>
|
||||
<th></th><th>FlatBuffers (binary) </th><th>Protocol Buffers LITE </th><th>Rapid JSON </th><th>FlatBuffers (JSON) </th><th>pugixml </th><th>Raw structs </th></tr>
|
||||
<tr>
|
||||
<td>Decode + Traverse + Dealloc (1 million times, seconds) </td><td>0.08 </td><td>305 </td><td>583 </td><td>105 </td></tr>
|
||||
<td>Decode + Traverse + Dealloc (1 million times, seconds) </td><td>0.08 </td><td>302 </td><td>583 </td><td>105 </td><td>196 </td><td>0.02 </td></tr>
|
||||
<tr>
|
||||
<td>Decode / Traverse / Dealloc (breakdown) </td><td>0 / 0.08 / 0 </td><td>220 / 3.6 / 81 </td><td>294 / 0.9 / 287 </td><td>70 / 0.08 / 35 </td></tr>
|
||||
<td>Decode / Traverse / Dealloc (breakdown) </td><td>0 / 0.08 / 0 </td><td>220 / 0.15 / 81 </td><td>294 / 0.9 / 287 </td><td>70 / 0.08 / 35 </td><td>41 / 3.9 / 150 </td><td>0 / 0.02 / 0 </td></tr>
|
||||
<tr>
|
||||
<td>Encode (1 million times, seconds) </td><td>3.2 </td><td>185 </td><td>650 </td><td>169 </td></tr>
|
||||
<td>Encode (1 million times, seconds) </td><td>3.2 </td><td>185 </td><td>650 </td><td>169 </td><td>273 </td><td>0.15 </td></tr>
|
||||
<tr>
|
||||
<td>Wire format size (normal / zlib, bytes) </td><td>344 / 220 </td><td>228 / 174 </td><td>1475 / 322 </td><td>1029 / 298 </td></tr>
|
||||
<td>Wire format size (normal / zlib, bytes) </td><td>344 / 220 </td><td>228 / 174 </td><td>1475 / 322 </td><td>1029 / 298 </td><td>1137 / 341 </td><td>312 / 187 </td></tr>
|
||||
<tr>
|
||||
<td>Memory needed to store decoded wire (bytes / blocks) </td><td>0 / 0 </td><td>760 / 20 </td><td>65689 / 40 </td><td>328 / 1 </td></tr>
|
||||
<td>Memory needed to store decoded wire (bytes / blocks) </td><td>0 / 0 </td><td>760 / 20 </td><td>65689 / 4 </td><td>328 / 1 </td><td>34194 / 3 </td><td>0 / 0 </td></tr>
|
||||
<tr>
|
||||
<td>Transient memory allocated during decode (KB) </td><td>0 </td><td>1 </td><td>131 </td><td>4 </td></tr>
|
||||
<td>Transient memory allocated during decode (KB) </td><td>0 </td><td>1 </td><td>131 </td><td>4 </td><td>34 </td><td>0 </td></tr>
|
||||
<tr>
|
||||
<td>Generated source code size (KB) </td><td>4 </td><td>61 </td><td>0 </td><td>4 </td></tr>
|
||||
<td>Generated source code size (KB) </td><td>4 </td><td>61 </td><td>0 </td><td>4 </td><td>0 </td><td>0 </td></tr>
|
||||
<tr>
|
||||
<td>Field access in handwritten traversal code </td><td>accessors </td><td>accessors </td><td>manual error checking </td><td>accessors </td></tr>
|
||||
<td>Field access in handwritten traversal code </td><td>typed accessors </td><td>typed accessors </td><td>manual error checking </td><td>typed accessors </td><td>manual error checking </td><td>typed but no safety </td></tr>
|
||||
<tr>
|
||||
<td>Library source code (KB) </td><td>15 </td><td>some subset of 3800 </td><td>87 </td><td>43 </td></tr>
|
||||
<td>Library source code (KB) </td><td>15 </td><td>some subset of 3800 </td><td>87 </td><td>43 </td><td>327 </td><td>0 </td></tr>
|
||||
</table>
|
||||
<h3>Some other serialization systems we compared against but did not benchmark (yet), in rough order of applicability:</h3>
|
||||
<ul>
|
||||
<li>Cap'n'Proto promises to reduce Protocol Buffers much like FlatBuffers does, though with a more complicated binary encoding and less flexibility (no optional fields to allow deprecating fields or serializing with missing fields for which defaults exist). It currently also isn't fully cross-platform portable (lack of VS support).</li>
|
||||
<li>msgpack: has very minimal forwards/backwards compatability support when used with the typed C++ interface. Also lacks VS2010 support.</li>
|
||||
<li>msgpack: has very minimal forwards/backwards compatibility support when used with the typed C++ interface. Also lacks VS2010 support.</li>
|
||||
<li>Thrift: very similar to Protocol Buffers, but appears to be less efficient, and have more dependencies.</li>
|
||||
<li>XML: typically even slower than JSON, but has the advantage that it can be parsed with a schema to reduce error-checking boilerplate code.</li>
|
||||
<li>YAML: a superset of JSON and otherwise very similar. Used by e.g. Unity.</li>
|
||||
<li>C# comes with built-in serialization functionality, as used by Unity also. Being tied to the language, and having no automatic versioning support limits its applicability.</li>
|
||||
<li>Project Anarchy (the free mobile engine by Havok) comes with a serialization system, that however does no automatic versioning (have to code around new fields manually), is very much tied to the rest of the engine, and works without a schema to generate code (tied to your C++ class definition). </li>
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
<!-- HTML header for doxygen 1.8.6-->
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
||||
<html xmlns="http://www.w3.org/1999/xhtml">
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
|
||||
<meta name="generator" content="Doxygen 1.8.5"/>
|
||||
<meta name="generator" content="Doxygen 1.8.7"/>
|
||||
<title>FlatBuffers: Building</title>
|
||||
<link href="tabs.css" rel="stylesheet" type="text/css"/>
|
||||
<script type="text/javascript" src="jquery.js"></script>
|
||||
@@ -15,24 +16,31 @@
|
||||
$(document).ready(initResizable);
|
||||
$(window).load(resizeHeight);
|
||||
</script>
|
||||
<link href="doxygen.css" rel="stylesheet" type="text/css" />
|
||||
<link href="style.css" rel="stylesheet" type="text/css" />
|
||||
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,400italic,500,500italic,700,700italic|Roboto+Mono:400,700" rel="stylesheet">
|
||||
</head>
|
||||
<body>
|
||||
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
|
||||
<div id="titlearea">
|
||||
<div id="titlearea" style="height: 110px;">
|
||||
<table cellspacing="0" cellpadding="0">
|
||||
<tbody>
|
||||
<tr style="height: 56px;">
|
||||
<td id="commonprojectlogo">
|
||||
<img alt="Logo" src="fpl_logo_small.png"/>
|
||||
</td>
|
||||
<td style="padding-left: 0.5em;">
|
||||
<div id="projectname">FlatBuffers
|
||||
</div>
|
||||
<div style="font-size:12px;">
|
||||
An open source project by <a href="https://developers.google.com/games/#Tools">FPL</a>.
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<!-- end header part -->
|
||||
<!-- Generated by Doxygen 1.8.5 -->
|
||||
<!-- Generated by Doxygen 1.8.7 -->
|
||||
</div><!-- top -->
|
||||
<div id="side-nav" class="ui-resizable side-nav-resizable">
|
||||
<div id="nav-tree">
|
||||
@@ -54,12 +62,12 @@ $(document).ready(function(){initNavTree('md__building.html','');});
|
||||
</div><!--header-->
|
||||
<div class="contents">
|
||||
<div class="textblock"><p>There are project files for Visual Studio and Xcode that should allow you to build the compiler <code>flatc</code>, the samples and the tests out of the box.</p>
|
||||
<p>Alternatively, the distribution comes with a <code>cmake</code> file that should allow you to build project/make files for any platform. For details on <code>cmake</code>, see <a href="http://www.cmake.org">http://www.cmake.org</a>. In brief, depending on your platform, use one of e.g.: </p>
|
||||
<pre class="fragment">cmake -G "Unix Makefiles"
|
||||
<p>Alternatively, the distribution comes with a <code>cmake</code> file that should allow you to build project/make files for any platform. For details on <code>cmake</code>, see <a href="http://www.cmake.org">http://www.cmake.org</a>. In brief, depending on your platform, use one of e.g.: </p><pre class="fragment">cmake -G "Unix Makefiles"
|
||||
cmake -G "Visual Studio 10"
|
||||
cmake -G "Xcode"
|
||||
</pre><p>Then, build as normal for your platform. This should result in a <code>flatc</code> executable, essential for the next steps. Note that to use clang instead of gcc, you may need to set up your environment variables, e.g. <code>CC=/usr/bin/clang CXX=/usr/bin/clang++ cmake -G "Unix Makefiles"</code>.</p>
|
||||
<p>Optionally, run the <code>flattests</code> executable. to ensure everything is working correctly on your system. If this fails, please contact us!</p>
|
||||
<p>Optionally, run the <code>flattests</code> executable to ensure everything is working correctly on your system. If this fails, please contact us!</p>
|
||||
<p>Note that you MUST be in the root of the FlatBuffers distribution when you run 'flattests' (and the samples), or it will fail to load its files.</p>
|
||||
<p>Building should also produce two sample executables, <code>sample_binary</code> and <code>sample_text</code>, see the corresponding <code>.cpp</code> file in the samples directory.</p>
|
||||
<p>There is an <code>android</code> directory that contains all you need to build the test executable on android (use the included <code>build_apk.sh</code> script, or use <code>ndk_build</code> / <code>adb</code> etc. as usual). Upon running, it will output to the log if tests succeeded or not.</p>
|
||||
<p>There is usually no runtime to compile, as the code consists of a single header, <code>include/flatbuffers/flatbuffers.h</code>. You should add the <code>include</code> folder to your include paths. If you wish to be able to load schemas and/or parse text into binary buffers at runtime, you additionally need the other headers in <code>include/flatbuffers</code>. You must also compile/link <code>src/idl_parser.cpp</code> (and <code>src/idl_gen_text.cpp</code> if you also want to be able convert binary to text).</p>
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
<!-- HTML header for doxygen 1.8.6-->
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
||||
<html xmlns="http://www.w3.org/1999/xhtml">
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
|
||||
<meta name="generator" content="Doxygen 1.8.5"/>
|
||||
<meta name="generator" content="Doxygen 1.8.7"/>
|
||||
<title>FlatBuffers: Using the schema compiler</title>
|
||||
<link href="tabs.css" rel="stylesheet" type="text/css"/>
|
||||
<script type="text/javascript" src="jquery.js"></script>
|
||||
@@ -15,24 +16,31 @@
|
||||
$(document).ready(initResizable);
|
||||
$(window).load(resizeHeight);
|
||||
</script>
|
||||
<link href="doxygen.css" rel="stylesheet" type="text/css" />
|
||||
<link href="style.css" rel="stylesheet" type="text/css" />
|
||||
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,400italic,500,500italic,700,700italic|Roboto+Mono:400,700" rel="stylesheet">
|
||||
</head>
|
||||
<body>
|
||||
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
|
||||
<div id="titlearea">
|
||||
<div id="titlearea" style="height: 110px;">
|
||||
<table cellspacing="0" cellpadding="0">
|
||||
<tbody>
|
||||
<tr style="height: 56px;">
|
||||
<td id="commonprojectlogo">
|
||||
<img alt="Logo" src="fpl_logo_small.png"/>
|
||||
</td>
|
||||
<td style="padding-left: 0.5em;">
|
||||
<div id="projectname">FlatBuffers
|
||||
</div>
|
||||
<div style="font-size:12px;">
|
||||
An open source project by <a href="https://developers.google.com/games/#Tools">FPL</a>.
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<!-- end header part -->
|
||||
<!-- Generated by Doxygen 1.8.5 -->
|
||||
<!-- Generated by Doxygen 1.8.7 -->
|
||||
</div><!-- top -->
|
||||
<div id="side-nav" class="ui-resizable side-nav-resizable">
|
||||
<div id="nav-tree">
|
||||
@@ -53,14 +61,32 @@ $(document).ready(function(){initNavTree('md__compiler.html','');});
|
||||
<div class="title">Using the schema compiler </div> </div>
|
||||
</div><!--header-->
|
||||
<div class="contents">
|
||||
<div class="textblock"><p>Usage: </p>
|
||||
<pre class="fragment">flatc [ -c ] [ -j ] [ -b ] [ -t ] file1 file2 ..
|
||||
</pre><p>The files are read and parsed in order, and can contain either schemas or data (see below). Later files can make use of definitions in earlier files. Depending on the flags passed, additional files may be generated for each file processed:</p>
|
||||
<div class="textblock"><p>Usage: </p><pre class="fragment">flatc [ -c ] [ -j ] [ -b ] [ -t ] [ -o PATH ] [ -I PATH ] [ -S ] FILES...
|
||||
[ -- FILES...]
|
||||
</pre><p>The files are read and parsed in order, and can contain either schemas or data (see below). Later files can make use of definitions in earlier files.</p>
|
||||
<p><code>--</code> indicates that the following files are binary files in FlatBuffer format conforming to the schema(s) indicated before it. Incompatible binary files currently will give unpredictable results (!)</p>
|
||||
<p>Depending on the flags passed, additional files may be generated for each file processed:</p>
|
||||
<ul>
|
||||
<li><code>-c</code> : Generate a C++ header for all definitions in this file (as <code>filename_generated.h</code>). Skips data.</li>
|
||||
<li><code>-j</code> : Generate Java classes.</li>
|
||||
<li><code>-b</code> : If data is contained in this file, generate a <code>filename_wire.bin</code> containing the binary flatbuffer.</li>
|
||||
<li><code>-t</code> : If data is contained in this file, generate a <code>filename_wire.txt</code> (for debugging). </li>
|
||||
<li><code>-c</code> : Generate a C++ header for all definitions in this file (as <code>filename_generated.h</code>). Skipped for data.</li>
|
||||
<li><code>-j</code> : Generate Java classes. Skipped for data.</li>
|
||||
<li><code>-n</code> : Generate C# classes. Skipped for data.</li>
|
||||
<li><code>-g</code> : Generate Go classes. Skipped for data.</li>
|
||||
<li><code>-b</code> : If data is contained in this file, generate a <code>filename.bin</code> containing the binary flatbuffer.</li>
|
||||
<li><code>-t</code> : If data is contained in this file, generate a <code>filename.json</code> representing the data in the flatbuffer.</li>
|
||||
<li><code>-o PATH</code> : Output all generated files to PATH (either absolute, or relative to the current directory). If omitted, PATH will be the current directory. PATH should end in your systems path separator, e.g. <code>/</code> or <code>\</code>.</li>
|
||||
<li><code>-I PATH</code> : when encountering <code>include</code> statements, attempt to load the files from this path. Paths will be tried in the order given, and if all fail (or none are specified) it will try to load relative to the path of the schema file being parsed.</li>
|
||||
<li><code>-M</code> : Print make rules for generated files.</li>
|
||||
<li><code>--strict-json</code> : Require & generate strict JSON (field names are enclosed in quotes, no trailing commas in tables/vectors). By default, no quotes are required/generated, and trailing commas are allowed.</li>
|
||||
<li><code>--defaults-json</code> : Output fields whose value is equal to the default value when writing JSON text.</li>
|
||||
<li><code>--no-prefix</code> : Don't prefix enum values in generated C++ by their enum type.</li>
|
||||
<li><code>--scoped-enums</code> : Use C++11 style scoped and strongly typed enums in generated C++. This also implies <code>--no-prefix</code>.</li>
|
||||
<li><code>--gen-includes</code> : (deprecated), this is the default behavior. If the original behavior is required (no include statements) use <code>--no-includes.</code></li>
|
||||
<li><code>--no-includes</code> : Don't generate include statements for included schemas the generated file depends on (C++).</li>
|
||||
<li><code>--gen-mutable</code> : Generate additional non-const accessors for mutating FlatBuffers in-place.</li>
|
||||
<li><code>--gen-onefile</code> : Generate single output file (useful for C#)</li>
|
||||
<li><code>--raw-binary</code> : Allow binaries without a file_indentifier to be read. This may crash flatc given a mismatched schema.</li>
|
||||
<li><code>--proto</code>: Expect input files to be .proto files (protocol buffers). Output the corresponding .fbs file. Currently supports: <code>package</code>, <code>message</code>, <code>enum</code>, nested declarations, <code>import</code> (use <code>-I</code> for paths), <code>extend</code>, <code>oneof</code>, <code>group</code>. Does not support, but will skip without error: <code>option</code>, <code>service</code>, <code>extensions</code>, and most everything else.</li>
|
||||
<li><code>--schema</code>: Serialize schemas instead of JSON (use with -b). This will output a binary version of the specified schema that itself corresponds to the reflection/reflection.fbs schema. Loading this binary file is the basis for reflection functionality. </li>
|
||||
</ul>
|
||||
</div></div><!-- contents -->
|
||||
</div><!-- doc-content -->
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
<!-- HTML header for doxygen 1.8.6-->
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
||||
<html xmlns="http://www.w3.org/1999/xhtml">
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
|
||||
<meta name="generator" content="Doxygen 1.8.5"/>
|
||||
<meta name="generator" content="Doxygen 1.8.7"/>
|
||||
<title>FlatBuffers: Use in C++</title>
|
||||
<link href="tabs.css" rel="stylesheet" type="text/css"/>
|
||||
<script type="text/javascript" src="jquery.js"></script>
|
||||
@@ -15,24 +16,31 @@
|
||||
$(document).ready(initResizable);
|
||||
$(window).load(resizeHeight);
|
||||
</script>
|
||||
<link href="doxygen.css" rel="stylesheet" type="text/css" />
|
||||
<link href="style.css" rel="stylesheet" type="text/css" />
|
||||
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,400italic,500,500italic,700,700italic|Roboto+Mono:400,700" rel="stylesheet">
|
||||
</head>
|
||||
<body>
|
||||
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
|
||||
<div id="titlearea">
|
||||
<div id="titlearea" style="height: 110px;">
|
||||
<table cellspacing="0" cellpadding="0">
|
||||
<tbody>
|
||||
<tr style="height: 56px;">
|
||||
<td id="commonprojectlogo">
|
||||
<img alt="Logo" src="fpl_logo_small.png"/>
|
||||
</td>
|
||||
<td style="padding-left: 0.5em;">
|
||||
<div id="projectname">FlatBuffers
|
||||
</div>
|
||||
<div style="font-size:12px;">
|
||||
An open source project by <a href="https://developers.google.com/games/#Tools">FPL</a>.
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<!-- end header part -->
|
||||
<!-- Generated by Doxygen 1.8.5 -->
|
||||
<!-- Generated by Doxygen 1.8.7 -->
|
||||
</div><!-- top -->
|
||||
<div id="side-nav" class="ui-resizable side-nav-resizable">
|
||||
<div id="nav-tree">
|
||||
@@ -55,78 +63,120 @@ $(document).ready(function(){initNavTree('md__cpp_usage.html','');});
|
||||
<div class="contents">
|
||||
<div class="textblock"><p>Assuming you have written a schema using the above language in say <code>mygame.fbs</code> (FlatBuffer Schema, though the extension doesn't matter), you've generated a C++ header called <code>mygame_generated.h</code> using the compiler (e.g. <code>flatc -c mygame.fbs</code>), you can now start using this in your program by including the header. As noted, this header relies on <code>flatbuffers/flatbuffers.h</code>, which should be in your include path.</p>
|
||||
<h3>Writing in C++</h3>
|
||||
<p>To start creating a buffer, create an instance of <code>FlatBufferBuilder</code> which will contain the buffer as it grows: </p>
|
||||
<pre class="fragment">FlatBufferBuilder fbb;
|
||||
</pre><p>Before we serialize a Monster, we need to first serialize any objects that are contained there-in, i.e. we serialize the data tree using depth first, pre-order traversal. This is generally easy to do on any tree structures. For example: </p>
|
||||
<pre class="fragment">auto name = fbb.CreateString("MyMonster");
|
||||
|
||||
unsigned char inv[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
|
||||
auto inventory = fbb.CreateVector(inv, 10);
|
||||
</pre><p><code>CreateString</code> and <code>CreateVector</code> serialize these two built-in datatypes, and return offsets into the serialized data indicating where they are stored, such that <code>Monster</code> below can refer to them.</p>
|
||||
<p>To start creating a buffer, create an instance of <code>FlatBufferBuilder</code> which will contain the buffer as it grows:</p>
|
||||
<div class="fragment"><div class="line">FlatBufferBuilder fbb;</div>
|
||||
</div><!-- fragment --><p>Before we serialize a Monster, we need to first serialize any objects that are contained there-in, i.e. we serialize the data tree using depth first, pre-order traversal. This is generally easy to do on any tree structures. For example:</p>
|
||||
<div class="fragment"><div class="line"><span class="keyword">auto</span> name = fbb.CreateString(<span class="stringliteral">"MyMonster"</span>);</div>
|
||||
<div class="line"></div>
|
||||
<div class="line"><span class="keywordtype">unsigned</span> <span class="keywordtype">char</span> inv[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };</div>
|
||||
<div class="line"><span class="keyword">auto</span> inventory = fbb.CreateVector(inv, 10);</div>
|
||||
</div><!-- fragment --><p><code>CreateString</code> and <code>CreateVector</code> serialize these two built-in datatypes, and return offsets into the serialized data indicating where they are stored, such that <code>Monster</code> below can refer to them.</p>
|
||||
<p><code>CreateString</code> can also take an <code>std::string</code>, or a <code>const char *</code> with an explicit length, and is suitable for holding UTF-8 and binary data if needed.</p>
|
||||
<p><code>CreateVector</code> can also take an <code>std::vector</code>. The offset it returns is typed, i.e. can only be used to set fields of the correct type below. To create a vector of struct objects (which will be stored as contiguous memory in the buffer, use <code>CreateVectorOfStructs</code> instead. </p>
|
||||
<pre class="fragment">Vec3 vec(1, 2, 3);
|
||||
</pre><p><code>Vec3</code> is the first example of code from our generated header. Structs (unlike tables) translate to simple structs in C++, so we can construct them in a familiar way.</p>
|
||||
<p>We have now serialized the non-scalar components of of the monster example, so we could create the monster something like this: </p>
|
||||
<pre class="fragment">auto mloc = CreateMonster(fbb, &vec, 150, 80, name, inventory, Color_Red, Offset<void>(0), Any_NONE);
|
||||
</pre><p>Note that we're passing <code>150</code> for the <code>mana</code> field, which happens to be the default value: this means the field will not actually be written to the buffer, since we'll get that value anyway when we query it. This is a nice space savings, since it is very common for fields to be at their default. It means we also don't need to be scared to add fields only used in a minority of cases, since they won't bloat up the buffer sizes if they're not actually used.</p>
|
||||
<p>We do something similarly for the union field <code>test</code> by specifying a <code>0</code> offset and the <code>NONE</code> enum value (part of every union) to indicate we don't actually want to write this field.</p>
|
||||
<p>Tables (like <code>Monster</code>) give you full flexibility on what fields you write (unlike <code>Vec3</code>, which always has all fields set because it is a <code>struct</code>). If you want even more control over this (i.e. skip fields even when they are not default), instead of the convenient <code>CreateMonster</code> call we can also build the object field-by-field manually: </p>
|
||||
<pre class="fragment">MonsterBuilder mb(fbb);
|
||||
mb.add_pos(&vec);
|
||||
mb.add_hp(80);
|
||||
mb.add_name(name);
|
||||
mb.add_inventory(inventory);
|
||||
auto mloc = mb.Finish();
|
||||
</pre><p>We start with a temporary helper class <code>MonsterBuilder</code> (which is defined in our generated code also), then call the various <code>add_</code> methods to set fields, and <code>Finish</code> to complete the object. This is pretty much the same code as you find inside <code>CreateMonster</code>, except we're leaving out a few fields. Fields may also be added in any order, though orderings with fields of the same size adjacent to each other most efficient in size, due to alignment. You should not nest these Builder classes (serialize your data in pre-order).</p>
|
||||
<p>Regardless of whether you used <code>CreateMonster</code> or <code>MonsterBuilder</code>, you now have an offset to the root of your data, and you can finish the buffer using: </p>
|
||||
<pre class="fragment">fbb.Finish(mloc);
|
||||
</pre><p>The buffer is now ready to be stored somewhere, sent over the network, be compressed, or whatever you'd like to do with it. You can access the start of the buffer with <code>fbb.GetBufferPointer()</code>, and it's size from <code>fbb.GetSize()</code>.</p>
|
||||
<p><code>CreateVector</code> can also take an <code>std::vector</code>. The offset it returns is typed, i.e. can only be used to set fields of the correct type below. To create a vector of struct objects (which will be stored as contiguous memory in the buffer, use <code>CreateVectorOfStructs</code> instead.</p>
|
||||
<p>To create a vector of nested objects (e.g. tables, strings or other vectors) collect their offsets in a temporary array/vector, then call <code>CreateVector</code> on that (see e.g. the array of strings example in <code>test.cpp</code> <code>CreateFlatBufferTest</code>).</p>
|
||||
<div class="fragment"><div class="line">Vec3 vec(1, 2, 3);</div>
|
||||
</div><!-- fragment --><p><code>Vec3</code> is the first example of code from our generated header. Structs (unlike tables) translate to simple structs in C++, so we can construct them in a familiar way.</p>
|
||||
<p>We have now serialized the non-scalar components of of the monster example, so we could create the monster something like this:</p>
|
||||
<div class="fragment"><div class="line"><span class="keyword">auto</span> mloc = CreateMonster(fbb, &vec, 150, 80, name, inventory, Color_Red, 0, Any_NONE);</div>
|
||||
</div><!-- fragment --><p>Note that we're passing <code>150</code> for the <code>mana</code> field, which happens to be the default value: this means the field will not actually be written to the buffer, since we'll get that value anyway when we query it. This is a nice space savings, since it is very common for fields to be at their default. It means we also don't need to be scared to add fields only used in a minority of cases, since they won't bloat up the buffer sizes if they're not actually used.</p>
|
||||
<p>We do something similarly for the union field <code>test</code> by specifying a <code>0</code> offset and the <code>NONE</code> enum value (part of every union) to indicate we don't actually want to write this field. You can use <code>0</code> also as a default for other non-scalar types, such as strings, vectors and tables. To pass an actual table, pass a preconstructed table as <code>mytable.Union()</code> that corresponds to union enum you're passing.</p>
|
||||
<p>Tables (like <code>Monster</code>) give you full flexibility on what fields you write (unlike <code>Vec3</code>, which always has all fields set because it is a <code>struct</code>). If you want even more control over this (i.e. skip fields even when they are not default), instead of the convenient <code>CreateMonster</code> call we can also build the object field-by-field manually:</p>
|
||||
<div class="fragment"><div class="line">MonsterBuilder mb(fbb);</div>
|
||||
<div class="line">mb.add_pos(&vec);</div>
|
||||
<div class="line">mb.add_hp(80);</div>
|
||||
<div class="line">mb.add_name(name);</div>
|
||||
<div class="line">mb.add_inventory(inventory);</div>
|
||||
<div class="line"><span class="keyword">auto</span> mloc = mb.Finish();</div>
|
||||
</div><!-- fragment --><p>We start with a temporary helper class <code>MonsterBuilder</code> (which is defined in our generated code also), then call the various <code>add_</code> methods to set fields, and <code>Finish</code> to complete the object. This is pretty much the same code as you find inside <code>CreateMonster</code>, except we're leaving out a few fields. Fields may also be added in any order, though orderings with fields of the same size adjacent to each other most efficient in size, due to alignment. You should not nest these Builder classes (serialize your data in pre-order).</p>
|
||||
<p>Regardless of whether you used <code>CreateMonster</code> or <code>MonsterBuilder</code>, you now have an offset to the root of your data, and you can finish the buffer using:</p>
|
||||
<div class="fragment"><div class="line">FinishMonsterBuffer(fbb, mloc);</div>
|
||||
</div><!-- fragment --><p>The buffer is now ready to be stored somewhere, sent over the network, be compressed, or whatever you'd like to do with it. You can access the start of the buffer with <code>fbb.GetBufferPointer()</code>, and it's size from <code>fbb.GetSize()</code>.</p>
|
||||
<p>Calling code may take ownership of the buffer with <code>fbb.ReleaseBufferPointer()</code>. Should you do it, the <code>FlatBufferBuilder</code> will be in an invalid state, and <em>must</em> be cleared before it can be used again. However, it also means you are able to destroy the builder while keeping the buffer in your application.</p>
|
||||
<p><code>samples/sample_binary.cpp</code> is a complete code sample similar to the code above, that also includes the reading code below.</p>
|
||||
<h3>Reading in C++</h3>
|
||||
<p>If you've received a buffer from somewhere (disk, network, etc.) you can directly start traversing it using: </p>
|
||||
<pre class="fragment">auto monster = GetMonster(buffer_pointer);
|
||||
</pre><p><code>monster</code> is of type <code>Monster *</code>, and points to somewhere inside your buffer. If you look in your generated header, you'll see it has convenient accessors for all fields, e.g. </p>
|
||||
<pre class="fragment">assert(monster->hp() == 80);
|
||||
assert(monster->mana() == 150); // default
|
||||
assert(strcmp(monster->name()->c_str(), "MyMonster") == 0);
|
||||
</pre><p>These should all be true. Note that we never stored a <code>mana</code> value, so it will return the default.</p>
|
||||
<p>To access sub-objects, in this case the <code>Vec3</code>: </p>
|
||||
<pre class="fragment">auto pos = monster->pos();
|
||||
assert(pos);
|
||||
assert(pos->z() == 3);
|
||||
</pre><p>If we had not set the <code>pos</code> field during serialization, it would be <code>NULL</code>.</p>
|
||||
<p>Similarly, we can access elements of the inventory array: </p>
|
||||
<pre class="fragment">auto inv = monster->inventory();
|
||||
assert(inv);
|
||||
assert(inv->Get(9) == 9);
|
||||
</pre><h3>Direct memory access</h3>
|
||||
<p>If you've received a buffer from somewhere (disk, network, etc.) you can directly start traversing it using:</p>
|
||||
<div class="fragment"><div class="line"><span class="keyword">auto</span> monster = GetMonster(buffer_pointer);</div>
|
||||
</div><!-- fragment --><p><code>monster</code> is of type <code>Monster *</code>, and points to somewhere <em>inside</em> your buffer (root object pointers are not the same as <code>buffer_pointer</code> !). If you look in your generated header, you'll see it has convenient accessors for all fields, e.g.</p>
|
||||
<div class="fragment"><div class="line">assert(monster->hp() == 80);</div>
|
||||
<div class="line">assert(monster->mana() == 150); <span class="comment">// default</span></div>
|
||||
<div class="line">assert(strcmp(monster->name()->c_str(), <span class="stringliteral">"MyMonster"</span>) == 0);</div>
|
||||
</div><!-- fragment --><p>These should all be true. Note that we never stored a <code>mana</code> value, so it will return the default.</p>
|
||||
<p>To access sub-objects, in this case the <code>Vec3</code>:</p>
|
||||
<div class="fragment"><div class="line"><span class="keyword">auto</span> pos = monster->pos();</div>
|
||||
<div class="line">assert(pos);</div>
|
||||
<div class="line">assert(pos->z() == 3);</div>
|
||||
</div><!-- fragment --><p>If we had not set the <code>pos</code> field during serialization, it would be <code>NULL</code>.</p>
|
||||
<p>Similarly, we can access elements of the inventory array:</p>
|
||||
<div class="fragment"><div class="line"><span class="keyword">auto</span> inv = monster->inventory();</div>
|
||||
<div class="line">assert(inv);</div>
|
||||
<div class="line">assert(inv->Get(9) == 9);</div>
|
||||
</div><!-- fragment --><h3>Mutating FlatBuffers</h3>
|
||||
<p>As you saw above, typically once you have created a FlatBuffer, it is read-only from that moment on. There are however cases where you have just received a FlatBuffer, and you'd like to modify something about it before sending it on to another recipient. With the above functionality, you'd have to generate an entirely new FlatBuffer, while tracking what you modify in your own data structures. This is inconvenient.</p>
|
||||
<p>For this reason FlatBuffers can also be mutated in-place. While this is great for making small fixes to an existing buffer, you generally want to create buffers from scratch whenever possible, since it is much more efficient and the API is much more general purpose.</p>
|
||||
<p>To get non-const accessors, invoke <code>flatc</code> with <code>--gen-mutable</code>.</p>
|
||||
<p>Similar to the reading API above, you now can:</p>
|
||||
<div class="fragment"><div class="line"><span class="keyword">auto</span> monster = GetMutableMonster(buffer_pointer); <span class="comment">// non-const</span></div>
|
||||
<div class="line">monster->mutate_hp(10); <span class="comment">// Set table field.</span></div>
|
||||
<div class="line">monster->mutable_pos()->mutate_z(4); <span class="comment">// Set struct field.</span></div>
|
||||
<div class="line">monster->mutable_inventory()->Mutate(0, 1); <span class="comment">// Set vector element.</span></div>
|
||||
</div><!-- fragment --><p>We use the somewhat verbose term <code>mutate</code> instead of <code>set</code> to indicate that this is a special use case, not to be confused with the default way of constructing FlatBuffer data.</p>
|
||||
<p>After the above mutations, you can send on the FlatBuffer to a new recipient without any further work!</p>
|
||||
<p>Note that any <code>mutate_</code> functions on tables return a bool, which is false if the field we're trying to set isn't present in the buffer. Fields are not present if they weren't set, or even if they happen to be equal to the default value. For example, in the creation code above we set the <code>mana</code> field to <code>150</code>, which is the default value, so it was never stored in the buffer. Trying to call mutate_mana() on such data will return false, and the value won't actually be modified!</p>
|
||||
<p>One way to solve this is to call <code>ForceDefaults()</code> on a <code>FlatBufferBuilder</code> to force all fields you set to actually be written. This of course increases the size of the buffer somewhat, but this may be acceptable for a mutable buffer.</p>
|
||||
<p>Alternatively, you can use the more powerful reflection functionality:</p>
|
||||
<h3>Reflection (& Resizing)</h3>
|
||||
<p>If the above ways of accessing a buffer are still too static for you, there is experimental support for reflection in FlatBuffers, allowing you to read and write data even if you don't know the exact format of a buffer, and even allows you to change sizes of strings and vectors in-place.</p>
|
||||
<p>The way this works is very elegant, there is actually a FlatBuffer schema that describes schemas (!) which you can find in <code>reflection/reflection.fbs</code>. The compiler <code>flatc</code> can write out any schemas it has just parsed as a binary FlatBuffer, corresponding to this meta-schema.</p>
|
||||
<p>Loading in one of these binary schemas at runtime allows you traverse any FlatBuffer data that corresponds to it without knowing the exact format. You can query what fields are present, and then read/write them after.</p>
|
||||
<p>For convenient field manipulation, you can include the header <code>flatbuffers/reflection.h</code> which includes both the generated code from the meta schema, as well as a lot of helper functions.</p>
|
||||
<p>And example of usage for the moment you can find in <code>test.cpp/ReflectionTest()</code>.</p>
|
||||
<h3>Storing maps / dictionaries in a FlatBuffer</h3>
|
||||
<p>FlatBuffers doesn't support maps natively, but there is support to emulate their behavior with vectors and binary search, which means you can have fast lookups directly from a FlatBuffer without having to unpack your data into a <code>std::map</code> or similar.</p>
|
||||
<p>To use it:</p><ul>
|
||||
<li>Designate one of the fields in a table as they "key" field. You do this by setting the <code>key</code> attribute on this field, e.g. <code>name:string (key)</code>. You may only have one key field, and it must be of string or scalar type.</li>
|
||||
<li>Write out tables of this type as usual, collect their offsets in an array or vector.</li>
|
||||
<li>Instead of <code>CreateVector</code>, call <code>CreateVectorOfSortedTables</code>, which will first sort all offsets such that the tables they refer to are sorted by the key field, then serialize it.</li>
|
||||
<li>Now when you're accessing the FlatBuffer, you can use <code>Vector::LookupByKey</code> instead of just <code>Vector::Get</code> to access elements of the vector, e.g.: <code>myvector->LookupByKey("Fred")</code>, which returns a pointer to the corresponding table type, or <code>nullptr</code> if not found. <code>LookupByKey</code> performs a binary search, so should have a similar speed to <code>std::map</code>, though may be faster because of better caching. <code>LookupByKey</code> only works if the vector has been sorted, it will likely not find elements if it hasn't been sorted.</li>
|
||||
</ul>
|
||||
<h3>Direct memory access</h3>
|
||||
<p>As you can see from the above examples, all elements in a buffer are accessed through generated accessors. This is because everything is stored in little endian format on all platforms (the accessor performs a swap operation on big endian machines), and also because the layout of things is generally not known to the user.</p>
|
||||
<p>For structs, layout is deterministic and guaranteed to be the same accross platforms (scalars are aligned to their own size, and structs themselves to their largest member), and you are allowed to access this memory directly by using <code>sizeof()</code> and <code>memcpy</code> on the pointer to a struct, or even an array of structs.</p>
|
||||
<p>To compute offsets to sub-elements of a struct, make sure they are a structs themselves, as then you can use the pointers to figure out the offset without having to hardcode it. This is handy for use of arrays of structs with calls like <code>glVertexAttribPointer</code> in OpenGL or similar APIs.</p>
|
||||
<p>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 shipping on a big endian machine (an <code>assert(FLATBUFFERS_LITTLEENDIAN)</code> would be wise).</p>
|
||||
<h3>Access of untrusted buffers</h3>
|
||||
<p>The generated accessor functions access fields over offsets, which is very quick. These offsets are not verified at run-time, so a malformed buffer could cause a program to crash by accessing random memory.</p>
|
||||
<p>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 data from the network that can potentially have been modified by an attacker, this is undesirable.</p>
|
||||
<p>For this reason, you can optionally use a buffer verifier before you access the data. This verifier will check all offsets, all sizes of fields, and null termination of strings to ensure that when a buffer is accessed, all reads will end up inside the buffer.</p>
|
||||
<p>Each root type will have a verification function generated for it, e.g. for <code>Monster</code>, you can call:</p>
|
||||
<div class="fragment"><div class="line"><span class="keywordtype">bool</span> ok = VerifyMonsterBuffer(Verifier(buf, len));</div>
|
||||
</div><!-- fragment --><p>if <code>ok</code> is true, the buffer is safe to read.</p>
|
||||
<p>Besides untrusted data, this function may be useful to call in debug mode, as extra insurance against data being corrupted somewhere along the way.</p>
|
||||
<p>While verifying a buffer isn't "free", it is typically faster than a full traversal (since any scalar data is not actually touched), and since it may cause the buffer to be brought into cache before reading, the actual overhead may be even lower than expected.</p>
|
||||
<p>In specialized cases where a denial of service attack is possible, the verifier has two additional constructor arguments that allow you to limit the nesting depth and total amount of tables the verifier may encounter before declaring the buffer malformed. The default is <code>Verifier(buf, len, 64 /* max depth */, 1000000, /* max tables */)</code> which should be sufficient for most uses.</p>
|
||||
<h2>Text & schema parsing</h2>
|
||||
<p>Using binary buffers with the generated header provides a super low overhead use of FlatBuffer data. There are, however, times when you want to use text formats, for example because it interacts better with source control, or you want to give your users easy access to data.</p>
|
||||
<p>Another reason might be that you already have a lot of data in JSON format, or a tool that generates JSON, and if you can write a schema for it, this will provide you an easy way to use that data directly.</p>
|
||||
<p>(see the schema documentation for some specifics on the JSON format accepted).</p>
|
||||
<p>There are two ways to use text formats:</p>
|
||||
<h3>Using the compiler as a conversion tool</h3>
|
||||
<p>This is the preferred path, as it doesn't require you to add any new code to your program, and is maximally efficient since you can ship with binary data. The disadvantage is that it is an extra step for your users/developers to perform, though you might be able to automate it. </p>
|
||||
<pre class="fragment">flatc -b myschema.fbs mydata.json
|
||||
<p>This is the preferred path, as it doesn't require you to add any new code to your program, and is maximally efficient since you can ship with binary data. The disadvantage is that it is an extra step for your users/developers to perform, though you might be able to automate it. </p><pre class="fragment">flatc -b myschema.fbs mydata.json
|
||||
</pre><p>This will generate the binary file <code>mydata_wire.bin</code> which can be loaded as before.</p>
|
||||
<h3>Making your program capable of loading text directly</h3>
|
||||
<p>This gives you maximum flexibility. You could even opt to support both, i.e. check for both files, and regenerate the binary from text when required, otherwise just load the binary.</p>
|
||||
<p>This option is currently only available for C++, or Java through JNI.</p>
|
||||
<p>As mentioned in the section "Building" above, this technique requires you to link a few more files into your program, and you'll want to include <code>flatbuffers/idl.h</code>.</p>
|
||||
<p>Load text (either a schema or json) into an in-memory buffer (there is a convenient <code>LoadFile()</code> utility function in <code>flatbuffers/util.h</code> if you wish). Construct a parser: </p>
|
||||
<pre class="fragment">flatbuffers::Parser parser;
|
||||
</pre><p>Now you can parse any number of text files in sequence: </p>
|
||||
<pre class="fragment">parser.Parse(text_file.c_str());
|
||||
</pre><p>This works similarly to how the command-line compiler works: a sequence of files parsed by the same <code>Parser</code> object allow later files to reference definitions in earlier files. Typically this means you first load a schema file (which populates <code>Parser</code> with definitions), followed by one or more JSON files.</p>
|
||||
<p>Load text (either a schema or json) into an in-memory buffer (there is a convenient <code>LoadFile()</code> utility function in <code>flatbuffers/util.h</code> if you wish). Construct a parser:</p>
|
||||
<div class="fragment"><div class="line">flatbuffers::Parser parser;</div>
|
||||
</div><!-- fragment --><p>Now you can parse any number of text files in sequence:</p>
|
||||
<div class="fragment"><div class="line">parser.Parse(text_file.c_str());</div>
|
||||
</div><!-- fragment --><p>This works similarly to how the command-line compiler works: a sequence of files parsed by the same <code>Parser</code> object allow later files to reference definitions in earlier files. Typically this means you first load a schema file (which populates <code>Parser</code> with definitions), followed by one or more JSON files.</p>
|
||||
<p>As optional argument to <code>Parse</code>, you may specify a null-terminated list of include paths. If not specified, any include statements try to resolve from the current directory.</p>
|
||||
<p>If there were any parsing errors, <code>Parse</code> will return <code>false</code>, and <code>Parser::err</code> contains a human readable error string with a line number etc, which you should present to the creator of that file.</p>
|
||||
<p>After each JSON file, the <code>Parser::fbb</code> member variable is the <code>FlatBufferBuilder</code> that contains the binary buffer version of that file, that you can access as described above.</p>
|
||||
<p><code>samples/sample_text.cpp</code> is a code sample showing the above operations.</p>
|
||||
<h3>Threading</h3>
|
||||
<p>None of the code is thread-safe, by design. That said, since currently a FlatBuffer is read-only and entirely <code>const</code>, reading by multiple threads is possible. </p>
|
||||
<p>Reading a FlatBuffer does not touch any memory outside the original buffer, and is entirely read-only (all const), so is safe to access from multiple threads even without synchronisation primitives.</p>
|
||||
<p>Creating a FlatBuffer is not thread safe. All state related to building a FlatBuffer is contained in a FlatBufferBuilder instance, and no memory outside of it is touched. To make this thread safe, either do not share instances of FlatBufferBuilder between threads (recommended), or manually wrap it in synchronisation primites. There's no automatic way to accomplish this, by design, as we feel multithreaded construction of a single buffer will be rare, and synchronisation overhead would be costly. </p>
|
||||
</div></div><!-- contents -->
|
||||
</div><!-- doc-content -->
|
||||
<!-- Google Analytics -->
|
||||
|
||||
122
docs/html/md__go_usage.html
Normal file
122
docs/html/md__go_usage.html
Normal file
@@ -0,0 +1,122 @@
|
||||
<!-- HTML header for doxygen 1.8.6-->
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
||||
<html xmlns="http://www.w3.org/1999/xhtml">
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
|
||||
<meta name="generator" content="Doxygen 1.8.7"/>
|
||||
<title>FlatBuffers: Use in Go</title>
|
||||
<link href="tabs.css" rel="stylesheet" type="text/css"/>
|
||||
<script type="text/javascript" src="jquery.js"></script>
|
||||
<script type="text/javascript" src="dynsections.js"></script>
|
||||
<link href="navtree.css" rel="stylesheet" type="text/css"/>
|
||||
<script type="text/javascript" src="resize.js"></script>
|
||||
<script type="text/javascript" src="navtree.js"></script>
|
||||
<script type="text/javascript">
|
||||
$(document).ready(initResizable);
|
||||
$(window).load(resizeHeight);
|
||||
</script>
|
||||
<link href="style.css" rel="stylesheet" type="text/css" />
|
||||
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,400italic,500,500italic,700,700italic|Roboto+Mono:400,700" rel="stylesheet">
|
||||
</head>
|
||||
<body>
|
||||
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
|
||||
<div id="titlearea" style="height: 110px;">
|
||||
<table cellspacing="0" cellpadding="0">
|
||||
<tbody>
|
||||
<tr style="height: 56px;">
|
||||
<td id="commonprojectlogo">
|
||||
<img alt="Logo" src="fpl_logo_small.png"/>
|
||||
</td>
|
||||
<td style="padding-left: 0.5em;">
|
||||
<div id="projectname">FlatBuffers
|
||||
</div>
|
||||
<div style="font-size:12px;">
|
||||
An open source project by <a href="https://developers.google.com/games/#Tools">FPL</a>.
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<!-- end header part -->
|
||||
<!-- Generated by Doxygen 1.8.7 -->
|
||||
</div><!-- top -->
|
||||
<div id="side-nav" class="ui-resizable side-nav-resizable">
|
||||
<div id="nav-tree">
|
||||
<div id="nav-tree-contents">
|
||||
<div id="nav-sync" class="sync"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="splitbar" style="-moz-user-select:none;"
|
||||
class="ui-resizable-handle">
|
||||
</div>
|
||||
</div>
|
||||
<script type="text/javascript">
|
||||
$(document).ready(function(){initNavTree('md__go_usage.html','');});
|
||||
</script>
|
||||
<div id="doc-content">
|
||||
<div class="header">
|
||||
<div class="headertitle">
|
||||
<div class="title">Use in Go </div> </div>
|
||||
</div><!--header-->
|
||||
<div class="contents">
|
||||
<div class="textblock"><p>There's experimental support for reading FlatBuffers in Go. Generate code for Go with the <code>-g</code> option to <code>flatc</code>.</p>
|
||||
<p>See <code>go_test.go</code> for an example. You import the generated code, read a FlatBuffer binary file into a <code>[]byte</code>, which you pass to the <code>GetRootAsMonster</code> function:</p>
|
||||
<div class="fragment"><div class="line"><span class="keyword">import</span> (</div>
|
||||
<div class="line"> example <span class="stringliteral">"MyGame/Example"</span></div>
|
||||
<div class="line"> flatbuffers <span class="stringliteral">"github.com/google/flatbuffers/go"</span></div>
|
||||
<div class="line"></div>
|
||||
<div class="line"> io/ioutil</div>
|
||||
<div class="line">)</div>
|
||||
<div class="line"></div>
|
||||
<div class="line">buf, err := ioutil.ReadFile(<span class="stringliteral">"monster.dat"</span>)</div>
|
||||
<div class="line"><span class="comment">// handle err</span></div>
|
||||
<div class="line">monster := example.GetRootAsMonster(buf, 0)</div>
|
||||
</div><!-- fragment --><p>Now you can access values like this:</p>
|
||||
<div class="fragment"><div class="line">hp := monster.Hp()</div>
|
||||
<div class="line">pos := monster.Pos(nil)</div>
|
||||
</div><!-- fragment --><p>Note that whenever you access a new object like in the <code>Pos</code> example above, a new temporary accessor object gets created. If your code is very performance sensitive (you iterate through a lot of objects), you can replace nil with a pointer to a <code>Vec3</code> object you've already created. This allows you to reuse it across many calls and reduce the amount of object allocation (and thus garbage collection) your program does.</p>
|
||||
<p>To access vectors you pass an extra index to the vector field accessor. Then a second method with the same name suffixed by <code>Length</code> let's you know the number of elements you can access:</p>
|
||||
<div class="fragment"><div class="line"><span class="keywordflow">for</span> i := 0; i < monster.InventoryLength(); i++ {</div>
|
||||
<div class="line"> monster.Inventory(i) <span class="comment">// do something here</span></div>
|
||||
<div class="line">}</div>
|
||||
</div><!-- fragment --><p>You can also construct these buffers in Go using the functions found in the generated code, and the FlatBufferBuilder class:</p>
|
||||
<div class="fragment"><div class="line">builder := flatbuffers.NewBuilder(0)</div>
|
||||
</div><!-- fragment --><p>Create strings:</p>
|
||||
<div class="fragment"><div class="line">str := builder.CreateString(<span class="stringliteral">"MyMonster"</span>)</div>
|
||||
</div><!-- fragment --><p>Create a table with a struct contained therein:</p>
|
||||
<div class="fragment"><div class="line">example.MonsterStart(builder)</div>
|
||||
<div class="line">example.MonsterAddPos(builder, example.CreateVec3(builder, 1.0, 2.0, 3.0, 3.0, 4, 5, 6))</div>
|
||||
<div class="line">example.MonsterAddHp(builder, 80)</div>
|
||||
<div class="line">example.MonsterAddName(builder, str)</div>
|
||||
<div class="line">example.MonsterAddInventory(builder, inv)</div>
|
||||
<div class="line">example.MonsterAddTest_Type(builder, 1)</div>
|
||||
<div class="line">example.MonsterAddTest(builder, mon2)</div>
|
||||
<div class="line">example.MonsterAddTest4(builder, test4s)</div>
|
||||
<div class="line">mon := example.MonsterEnd(builder)</div>
|
||||
</div><!-- fragment --><p>Unlike C++, Go does not support table creation functions like 'createMonster()'. This is to create the buffer without using temporary object allocation (since the <code>Vec3</code> is an inline component of <code>Monster</code>, it has to be created right where it is added, whereas the name and the inventory are not inline, and <b>must</b> be created outside of the table creation sequence). Structs do have convenient methods that allow you to construct them in one call. These also have arguments for nested structs, e.g. if a struct has a field <code>a</code> and a nested struct field <code>b</code> (which has fields <code>c</code> and <code>d</code>), then the arguments will be <code>a</code>, <code>c</code> and <code>d</code>.</p>
|
||||
<p>Vectors also use this start/end pattern to allow vectors of both scalar types and structs:</p>
|
||||
<div class="fragment"><div class="line">example.MonsterStartInventoryVector(builder, 5)</div>
|
||||
<div class="line"><span class="keywordflow">for</span> i := 4; i >= 0; i-- {</div>
|
||||
<div class="line"> builder.PrependByte(byte(i))</div>
|
||||
<div class="line">}</div>
|
||||
<div class="line">inv := builder.EndVector(5)</div>
|
||||
</div><!-- fragment --><p>The generated method 'StartInventoryVector' is provided as a convenience function which calls 'StartVector' with the correct element size of the vector type which in this case is 'ubyte' or 1 byte per vector element. You pass the number of elements you want to write. You write the elements backwards since the buffer is being constructed back to front. Use the correct <code>Prepend</code> call for the type, or <code>PrependUOffsetT</code> for offsets. You then pass <code>inv</code> to the corresponding <code>Add</code> call when you construct the table containing it afterwards.</p>
|
||||
<p>There are <code>Prepend</code> functions for all the scalar types. You use <code>PrependUOffset</code> for any previously constructed objects (such as other tables, strings, vectors). For structs, you use the appropriate <code>create</code> function in-line, as shown above in the <code>Monster</code> example.</p>
|
||||
<p>Once you're done constructing a buffer, you call <code>Finish</code> with the root object offset (<code>mon</code> in the example above). Your data now resides in Builder.Bytes. Important to note is that the real data starts at the index indicated by Head(), for Offset() bytes (this is because the buffer is constructed backwards). If you wanted to read the buffer right after creating it (using <code>GetRootAsMonster</code> above), the second argument, instead of <code>0</code> would thus also be <code>Head()</code>.</p>
|
||||
<h2>Text Parsing</h2>
|
||||
<p>There currently is no support for parsing text (Schema's and JSON) directly from Go, though you could use the C++ parser through cgo. Please see the C++ documentation for more on text parsing. </p>
|
||||
</div></div><!-- contents -->
|
||||
</div><!-- doc-content -->
|
||||
<!-- Google Analytics -->
|
||||
<script>
|
||||
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
|
||||
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
|
||||
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
|
||||
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
|
||||
ga('create', 'UA-49880327-7', 'auto');
|
||||
ga('send', 'pageview');
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,10 +1,11 @@
|
||||
<!-- HTML header for doxygen 1.8.6-->
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
||||
<html xmlns="http://www.w3.org/1999/xhtml">
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
|
||||
<meta name="generator" content="Doxygen 1.8.5"/>
|
||||
<title>FlatBuffers: Formal Grammar of the schema language</title>
|
||||
<meta name="generator" content="Doxygen 1.8.7"/>
|
||||
<title>FlatBuffers: Grammar of the schema language</title>
|
||||
<link href="tabs.css" rel="stylesheet" type="text/css"/>
|
||||
<script type="text/javascript" src="jquery.js"></script>
|
||||
<script type="text/javascript" src="dynsections.js"></script>
|
||||
@@ -15,24 +16,31 @@
|
||||
$(document).ready(initResizable);
|
||||
$(window).load(resizeHeight);
|
||||
</script>
|
||||
<link href="doxygen.css" rel="stylesheet" type="text/css" />
|
||||
<link href="style.css" rel="stylesheet" type="text/css" />
|
||||
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,400italic,500,500italic,700,700italic|Roboto+Mono:400,700" rel="stylesheet">
|
||||
</head>
|
||||
<body>
|
||||
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
|
||||
<div id="titlearea">
|
||||
<div id="titlearea" style="height: 110px;">
|
||||
<table cellspacing="0" cellpadding="0">
|
||||
<tbody>
|
||||
<tr style="height: 56px;">
|
||||
<td id="commonprojectlogo">
|
||||
<img alt="Logo" src="fpl_logo_small.png"/>
|
||||
</td>
|
||||
<td style="padding-left: 0.5em;">
|
||||
<div id="projectname">FlatBuffers
|
||||
</div>
|
||||
<div style="font-size:12px;">
|
||||
An open source project by <a href="https://developers.google.com/games/#Tools">FPL</a>.
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<!-- end header part -->
|
||||
<!-- Generated by Doxygen 1.8.5 -->
|
||||
<!-- Generated by Doxygen 1.8.7 -->
|
||||
</div><!-- top -->
|
||||
<div id="side-nav" class="ui-resizable side-nav-resizable">
|
||||
<div id="nav-tree">
|
||||
@@ -50,22 +58,29 @@ $(document).ready(function(){initNavTree('md__grammar.html','');});
|
||||
<div id="doc-content">
|
||||
<div class="header">
|
||||
<div class="headertitle">
|
||||
<div class="title">Formal Grammar of the schema language </div> </div>
|
||||
<div class="title">Grammar of the schema language </div> </div>
|
||||
</div><!--header-->
|
||||
<div class="contents">
|
||||
<div class="textblock"><p>schema = namespace_decl | type_decl | enum_decl | root_decl | object</p>
|
||||
<div class="textblock"><p>schema = include* ( namespace_decl | type_decl | enum_decl | root_decl | file_extension_decl | file_identifier_decl | attribute_decl | object )*</p>
|
||||
<p>include = <code>include</code> string_constant <code>;</code></p>
|
||||
<p>namespace_decl = <code>namespace</code> ident ( <code>.</code> ident )* <code>;</code></p>
|
||||
<p>attribute_decl = <code>attribute</code> string_constant <code>;</code></p>
|
||||
<p>type_decl = ( <code>table</code> | <code>struct</code> ) ident metadata <code>{</code> field_decl+ <code>}</code></p>
|
||||
<p>enum_decl = ( <code>enum</code> | <code>union</code> ) ident [ <code>:</code> type ] metadata <code>{</code> commasep( enumval_decl ) <code>}</code></p>
|
||||
<p>root_decl = <code>root_type</code> ident <code>;</code></p>
|
||||
<p>field_decl = type <code>:</code> ident [ <code>=</code> scalar ] metadata <code>;</code></p>
|
||||
<p>field_decl = ident <code>:</code> type [ <code>=</code> scalar ] metadata <code>;</code></p>
|
||||
<p>type = <code>bool</code> | <code>byte</code> | <code>ubyte</code> | <code>short</code> | <code>ushort</code> | <code>int</code> | <code>uint</code> | <code>float</code> | <code>long</code> | <code>ulong</code> | <code>double</code> | <code>string</code> | <code>[</code> type <code>]</code> | ident</p>
|
||||
<p>enumval_decl = ident [ <code>=</code> integer_constant ]</p>
|
||||
<p>metadata = [ <code>(</code> commasep( ident [ <code>:</code> scalar ] ) <code>)</code> ]</p>
|
||||
<p>scalar = integer_constant | float_constant | <code>true</code> | <code>false</code></p>
|
||||
<p>metadata = [ <code>(</code> commasep( ident [ <code>:</code> single_value ] ) <code>)</code> ]</p>
|
||||
<p>scalar = integer_constant | float_constant</p>
|
||||
<p>object = { commasep( ident <code>:</code> value ) }</p>
|
||||
<p>value = scalar | object | string_constant | <code>[</code> commasep( value ) <code>]</code></p>
|
||||
<p>commasep(x) = [ x ( <code>,</code> x )* ] </p>
|
||||
<p>single_value = scalar | string_constant</p>
|
||||
<p>value = single_value | object | <code>[</code> commasep( value ) <code>]</code></p>
|
||||
<p>commasep(x) = [ x ( <code>,</code> x )* ]</p>
|
||||
<p>file_extension_decl = <code>file_extension</code> string_constant <code>;</code></p>
|
||||
<p>file_identifier_decl = <code>file_identifier</code> string_constant <code>;</code></p>
|
||||
<p>integer_constant = -?[0-9]+ | <code>true</code> | <code>false</code></p>
|
||||
<p>float_constant = -?[0-9]+.[0-9]+((e|E)(+|-)?[0-9]+)? </p>
|
||||
</div></div><!-- contents -->
|
||||
</div><!-- doc-content -->
|
||||
<!-- Google Analytics -->
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
<!-- HTML header for doxygen 1.8.6-->
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
||||
<html xmlns="http://www.w3.org/1999/xhtml">
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
|
||||
<meta name="generator" content="Doxygen 1.8.5"/>
|
||||
<meta name="generator" content="Doxygen 1.8.7"/>
|
||||
<title>FlatBuffers: FlatBuffer Internals</title>
|
||||
<link href="tabs.css" rel="stylesheet" type="text/css"/>
|
||||
<script type="text/javascript" src="jquery.js"></script>
|
||||
@@ -15,24 +16,31 @@
|
||||
$(document).ready(initResizable);
|
||||
$(window).load(resizeHeight);
|
||||
</script>
|
||||
<link href="doxygen.css" rel="stylesheet" type="text/css" />
|
||||
<link href="style.css" rel="stylesheet" type="text/css" />
|
||||
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,400italic,500,500italic,700,700italic|Roboto+Mono:400,700" rel="stylesheet">
|
||||
</head>
|
||||
<body>
|
||||
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
|
||||
<div id="titlearea">
|
||||
<div id="titlearea" style="height: 110px;">
|
||||
<table cellspacing="0" cellpadding="0">
|
||||
<tbody>
|
||||
<tr style="height: 56px;">
|
||||
<td id="commonprojectlogo">
|
||||
<img alt="Logo" src="fpl_logo_small.png"/>
|
||||
</td>
|
||||
<td style="padding-left: 0.5em;">
|
||||
<div id="projectname">FlatBuffers
|
||||
</div>
|
||||
<div style="font-size:12px;">
|
||||
An open source project by <a href="https://developers.google.com/games/#Tools">FPL</a>.
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<!-- end header part -->
|
||||
<!-- Generated by Doxygen 1.8.5 -->
|
||||
<!-- Generated by Doxygen 1.8.7 -->
|
||||
</div><!-- top -->
|
||||
<div id="side-nav" class="ui-resizable side-nav-resizable">
|
||||
<div id="nav-tree">
|
||||
@@ -56,35 +64,33 @@ $(document).ready(function(){initNavTree('md__internals.html','');});
|
||||
<div class="textblock"><p>This section is entirely optional for the use of FlatBuffers. In normal usage, you should never need the information contained herein. If you're interested however, it should give you more of an appreciation of why FlatBuffers is both efficient and convenient.</p>
|
||||
<h3>Format components</h3>
|
||||
<p>A FlatBuffer is a binary file and in-memory format consisting mostly of scalars of various sizes, all aligned to their own size. Each scalar is also always represented in little-endian format, as this corresponds to all commonly used CPUs today. FlatBuffers will also work on big-endian machines, but will be slightly slower because of additional byte-swap intrinsics.</p>
|
||||
<p>On purpose, the format leaves a lot of details about where exactly things live in memory undefined, e.g. fields in a table can have any order, and objects to some extend can be stored in many orders. This is because the format doesn't need this information to be efficient, and it leaves room for optimization and extension (for example, fields can be packed in a way that is most compact). Instead, the format is defined in terms of offsets and adjacency only.</p>
|
||||
<p>On purpose, the format leaves a lot of details about where exactly things live in memory undefined, e.g. fields in a table can have any order, and objects to some extend can be stored in many orders. This is because the format doesn't need this information to be efficient, and it leaves room for optimization and extension (for example, fields can be packed in a way that is most compact). Instead, the format is defined in terms of offsets and adjacency only. This may mean two different implementations may produce different binaries given the same input values, and this is perfectly valid.</p>
|
||||
<h3>Format identification</h3>
|
||||
<p>The format also doesn't contain information for format identification and versioning, which is also by design. FlatBuffers is a statically typed system, meaning the user of a buffer needs to know what kind of buffer it is. FlatBuffers can of course be wrapped inside other containers where needed, or you can use its union feature to dynamically identify multiple possible sub-objects stored. Additionally, it can be used together with the schema parser if full reflective capabilities are desired.</p>
|
||||
<p>Versioning is something that is intrinsically part of the format (the optionality / extensibility of fields), so the format itself does not need a version number (it's a meta-format, in a sense). We're hoping that this format can accommodate all data needed. If format breaking changes are ever necessary, it would become a new kind of format rather than just a variation.</p>
|
||||
<h3>Offsets</h3>
|
||||
<p>The most important and generic offset type (see <code>flatbuffers.h</code>) is <code>offset_t</code>, which is currently always a <code>uint32_t</code>, and is used to refer to all tables/unions/strings/vectors. 32bit is intentional, since we want to keep the format binary compatible between 32 and 64bit systems, and a 64bit offset would bloat the size for almost all uses. A version of this format with 64bit (or 16bit) offsets is easy to set when needed. Unsigned means they can only point in one direction, which typically is forward (towards a higher memory location). Any backwards offsets will be explicitly marked as such.</p>
|
||||
<p>The format starts with an <code>offset_t</code> to the root object in the buffer.</p>
|
||||
<p>The most important and generic offset type (see <code>flatbuffers.h</code>) is <code>uoffset_t</code>, which is currently always a <code>uint32_t</code>, and is used to refer to all tables/unions/strings/vectors (these are never stored in-line). 32bit is intentional, since we want to keep the format binary compatible between 32 and 64bit systems, and a 64bit offset would bloat the size for almost all uses. A version of this format with 64bit (or 16bit) offsets is easy to set when needed. Unsigned means they can only point in one direction, which typically is forward (towards a higher memory location). Any backwards offsets will be explicitly marked as such.</p>
|
||||
<p>The format starts with an <code>uoffset_t</code> to the root object in the buffer.</p>
|
||||
<p>We have two kinds of objects, structs and tables.</p>
|
||||
<h3>Structs</h3>
|
||||
<p>These are the simplest, and as mentioned, intended for simple data that benefits from being extra efficient and doesn't need versioning / extensibility. They are always stored inline in their parent (a struct, table, or vector) for maximum compactness. Structs define a consistent memory layout where all components are aligned to their size, and structs aligned to their largest scalar member. This is done independent of the alignment rules of the underlying compiler to guarantee a cross platform compatible layout. This layout is then enforced in the generated code.</p>
|
||||
<h3>Tables</h3>
|
||||
<p>These start with an <code>soffset_t</code> to a vtable (signed version of <code>offset_t</code>, since vtables may be stored anywhere), followed by all the fields as aligned scalars. Unlike structs, not all fields need to be present. There is no set order and layout.</p>
|
||||
<p>These start with an <code>soffset_t</code> to a vtable. This is a signed version of <code>uoffset_t</code>, since vtables may be stored anywhere relative to the object. This offset is substracted (not added) from the object start to arrive at the vtable start. This offset is followed by all the fields as aligned scalars (or offsets). Unlike structs, not all fields need to be present. There is no set order and layout.</p>
|
||||
<p>To be able to access fields regardless of these uncertainties, we go through a vtable of offsets. Vtables are shared between any objects that happen to have the same vtable values.</p>
|
||||
<p>The elements of a vtable are all of type <code>voffset_t</code>, which is currently a <code>uint16_t</code>. The first element is the number of elements of the vtable, including this one. The second one is the size of the object, in bytes (including the vtable offset). This size is used for streaming, to know how many bytes to read to be able to access all fields of the object. The remaining elements are N the offsets, where N is the amount of field declared in the schema when the code that constructed this buffer was compiled (thus, the size of the table is N + 2).</p>
|
||||
<p>The elements of a vtable are all of type <code>voffset_t</code>, which is a <code>uint16_t</code>. The first element is the size of the vtable in bytes, including the size element. The second one is the size of the object, in bytes (including the vtable offset). This size could be used for streaming, to know how many bytes to read to be able to access all fields of the object. The remaining elements are the N offsets, where N is the amount of fields declared in the schema when the code that constructed this buffer was compiled (thus, the size of the table is N + 2).</p>
|
||||
<p>All accessor functions in the generated code for tables contain the offset into this table as a constant. This offset is checked against the first field (the number of elements), to protect against newer code reading older data. If this offset is out of range, or the vtable entry is 0, that means the field is not present in this object, and the default value is return. Otherwise, the entry is used as offset to the field to be read.</p>
|
||||
<h3>Strings and Vectors</h3>
|
||||
<p>Strings are simply a vector of bytes, and are always null-terminated. Vectors are stored as contiguous aligned scalar elements prefixed by a count.</p>
|
||||
<p>Strings are simply a vector of bytes, and are always null-terminated. Vectors are stored as contiguous aligned scalar elements prefixed by a 32bit element count (not including any null termination).</p>
|
||||
<h3>Construction</h3>
|
||||
<p>The current implementation constructs these buffers backwards, since that significantly reduces the amount of bookkeeping and simplifies the construction API.</p>
|
||||
<p>The current implementation constructs these buffers backwards (starting at the highest memory address of the buffer), since that significantly reduces the amount of bookkeeping and simplifies the construction API.</p>
|
||||
<h3>Code example</h3>
|
||||
<p>Here's an example of the code that gets generated for the <code>samples/monster.fbs</code>. What follows is the entire file, broken up by comments: </p>
|
||||
<pre class="fragment">// automatically generated, do not modify
|
||||
<p>Here's an example of the code that gets generated for the <code>samples/monster.fbs</code>. What follows is the entire file, broken up by comments: </p><pre class="fragment">// automatically generated, do not modify
|
||||
|
||||
#include "flatbuffers/flatbuffers.h"
|
||||
|
||||
namespace MyGame {
|
||||
namespace Sample {
|
||||
</pre><p>Nested namespace support. </p>
|
||||
<pre class="fragment">enum {
|
||||
</pre><p>Nested namespace support. </p><pre class="fragment">enum {
|
||||
Color_Red = 0,
|
||||
Color_Green = 1,
|
||||
Color_Blue = 2,
|
||||
@@ -96,8 +102,7 @@ inline const char **EnumNamesColor() {
|
||||
}
|
||||
|
||||
inline const char *EnumNameColor(int e) { return EnumNamesColor()[e]; }
|
||||
</pre><p>Enums and convenient reverse lookup. </p>
|
||||
<pre class="fragment">enum {
|
||||
</pre><p>Enums and convenient reverse lookup. </p><pre class="fragment">enum {
|
||||
Any_NONE = 0,
|
||||
Any_Monster = 1,
|
||||
};
|
||||
@@ -108,11 +113,9 @@ inline const char **EnumNamesAny() {
|
||||
}
|
||||
|
||||
inline const char *EnumNameAny(int e) { return EnumNamesAny()[e]; }
|
||||
</pre><p>Unions share a lot with enums. </p>
|
||||
<pre class="fragment">struct Vec3;
|
||||
</pre><p>Unions share a lot with enums. </p><pre class="fragment">struct Vec3;
|
||||
struct Monster;
|
||||
</pre><p>Predeclare all datatypes since there may be circular references. </p>
|
||||
<pre class="fragment">MANUALLY_ALIGNED_STRUCT(4) Vec3 {
|
||||
</pre><p>Predeclare all data types since circular references between types are allowed (circular references between object are not, though). </p><pre class="fragment">MANUALLY_ALIGNED_STRUCT(4) Vec3 {
|
||||
private:
|
||||
float x_;
|
||||
float y_;
|
||||
@@ -127,8 +130,7 @@ struct Monster;
|
||||
float z() const { return flatbuffers::EndianScalar(z_); }
|
||||
};
|
||||
STRUCT_END(Vec3, 12);
|
||||
</pre><p>These ugly macros do a couple of things: they turn off any padding the compiler might normally do, since we add padding manually (though none in this example), and they enforce alignment chosen by FlatBuffers. This ensures the layout of this struct will look the same regardless of compiler and platform. Note that the fields are private: this is because these store little endian scalars regardless of platform (since this is part of the serialized data). <code>EndianScalar</code> then converts back and forth, which is a no-op on all current mobile and desktop platforms, and a single machine instruction on the few remaining big endian platforms. </p>
|
||||
<pre class="fragment">struct Monster : private flatbuffers::Table {
|
||||
</pre><p>These ugly macros do a couple of things: they turn off any padding the compiler might normally do, since we add padding manually (though none in this example), and they enforce alignment chosen by FlatBuffers. This ensures the layout of this struct will look the same regardless of compiler and platform. Note that the fields are private: this is because these store little endian scalars regardless of platform (since this is part of the serialized data). <code>EndianScalar</code> then converts back and forth, which is a no-op on all current mobile and desktop platforms, and a single machine instruction on the few remaining big endian platforms. </p><pre class="fragment">struct Monster : private flatbuffers::Table {
|
||||
const Vec3 *pos() const { return GetStruct<const Vec3 *>(4); }
|
||||
int16_t mana() const { return GetField<int16_t>(6, 150); }
|
||||
int16_t hp() const { return GetField<int16_t>(8, 100); }
|
||||
@@ -136,8 +138,7 @@ STRUCT_END(Vec3, 12);
|
||||
const flatbuffers::Vector<uint8_t> *inventory() const { return GetPointer<const flatbuffers::Vector<uint8_t> *>(14); }
|
||||
int8_t color() const { return GetField<int8_t>(16, 2); }
|
||||
};
|
||||
</pre><p>Tables are a bit more complicated. A table accessor struct is used to point at the serialized data for a table, which always starts with an offset to its vtable. It derives from <code>Table</code>, which contains the <code>GetField</code> helper functions. GetField takes a vtable offset, and a default value. It will look in the vtable at that offset. If the offset is out of bounds (data from an older version) or the vtable entry is 0, the field is not present and the default is returned. Otherwise, it uses the entry as an offset into the table to locate the field. </p>
|
||||
<pre class="fragment">struct MonsterBuilder {
|
||||
</pre><p>Tables are a bit more complicated. A table accessor struct is used to point at the serialized data for a table, which always starts with an offset to its vtable. It derives from <code>Table</code>, which contains the <code>GetField</code> helper functions. GetField takes a vtable offset, and a default value. It will look in the vtable at that offset. If the offset is out of bounds (data from an older version) or the vtable entry is 0, the field is not present and the default is returned. Otherwise, it uses the entry as an offset into the table to locate the field. </p><pre class="fragment">struct MonsterBuilder {
|
||||
flatbuffers::FlatBufferBuilder &fbb_;
|
||||
flatbuffers::uoffset_t start_;
|
||||
void add_pos(const Vec3 *pos) { fbb_.AddStruct(4, pos); }
|
||||
@@ -149,8 +150,7 @@ STRUCT_END(Vec3, 12);
|
||||
MonsterBuilder(flatbuffers::FlatBufferBuilder &_fbb) : fbb_(_fbb) { start_ = fbb_.StartTable(); }
|
||||
flatbuffers::Offset<Monster> Finish() { return flatbuffers::Offset<Monster>(fbb_.EndTable(start_, 7)); }
|
||||
};
|
||||
</pre><p><code>MonsterBuilder</code> is the base helper struct to construct a table using a <code>FlatBufferBuilder</code>. You can add the fields in any order, and the <code>Finish</code> call will ensure the correct vtable gets generated. </p>
|
||||
<pre class="fragment">inline flatbuffers::Offset<Monster> CreateMonster(flatbuffers::FlatBufferBuilder &_fbb, const Vec3 *pos, int16_t mana, int16_t hp, flatbuffers::Offset<flatbuffers::String> name, flatbuffers::Offset<flatbuffers::Vector<uint8_t>> inventory, int8_t color) {
|
||||
</pre><p><code>MonsterBuilder</code> is the base helper struct to construct a table using a <code>FlatBufferBuilder</code>. You can add the fields in any order, and the <code>Finish</code> call will ensure the correct vtable gets generated. </p><pre class="fragment">inline flatbuffers::Offset<Monster> CreateMonster(flatbuffers::FlatBufferBuilder &_fbb, const Vec3 *pos, int16_t mana, int16_t hp, flatbuffers::Offset<flatbuffers::String> name, flatbuffers::Offset<flatbuffers::Vector<uint8_t>> inventory, int8_t color) {
|
||||
MonsterBuilder builder_(_fbb);
|
||||
builder_.add_inventory(inventory);
|
||||
builder_.add_name(name);
|
||||
@@ -160,10 +160,8 @@ STRUCT_END(Vec3, 12);
|
||||
builder_.add_color(color);
|
||||
return builder_.Finish();
|
||||
}
|
||||
</pre><p><code>CreateMonster</code> is a convenience function that calls all functions in <code>MonsterBuilder</code> above for you. Note that if you pass values which are defaults as arguments, it will not actually construct that field, so you can probably use this function instead of the builder class in almost all cases. </p>
|
||||
<pre class="fragment">inline const Monster *GetMonster(const void *buf) { return flatbuffers::GetRoot<Monster>(buf); }
|
||||
</pre><p>This function is only generated for the root table type, to be able to start traversing a FlatBuffer from a raw buffer pointer. </p>
|
||||
<pre class="fragment">}; // namespace MyGame
|
||||
</pre><p><code>CreateMonster</code> is a convenience function that calls all functions in <code>MonsterBuilder</code> above for you. Note that if you pass values which are defaults as arguments, it will not actually construct that field, so you can probably use this function instead of the builder class in almost all cases. </p><pre class="fragment">inline const Monster *GetMonster(const void *buf) { return flatbuffers::GetRoot<Monster>(buf); }
|
||||
</pre><p>This function is only generated for the root table type, to be able to start traversing a FlatBuffer from a raw buffer pointer. </p><pre class="fragment">}; // namespace MyGame
|
||||
}; // namespace Sample</pre> </div></div><!-- contents -->
|
||||
</div><!-- doc-content -->
|
||||
<!-- Google Analytics -->
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
<!-- HTML header for doxygen 1.8.6-->
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
||||
<html xmlns="http://www.w3.org/1999/xhtml">
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
|
||||
<meta name="generator" content="Doxygen 1.8.5"/>
|
||||
<title>FlatBuffers: Use in Java</title>
|
||||
<meta name="generator" content="Doxygen 1.8.7"/>
|
||||
<title>FlatBuffers: Use in Java/C-sharp</title>
|
||||
<link href="tabs.css" rel="stylesheet" type="text/css"/>
|
||||
<script type="text/javascript" src="jquery.js"></script>
|
||||
<script type="text/javascript" src="dynsections.js"></script>
|
||||
@@ -15,24 +16,31 @@
|
||||
$(document).ready(initResizable);
|
||||
$(window).load(resizeHeight);
|
||||
</script>
|
||||
<link href="doxygen.css" rel="stylesheet" type="text/css" />
|
||||
<link href="style.css" rel="stylesheet" type="text/css" />
|
||||
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,400italic,500,500italic,700,700italic|Roboto+Mono:400,700" rel="stylesheet">
|
||||
</head>
|
||||
<body>
|
||||
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
|
||||
<div id="titlearea">
|
||||
<div id="titlearea" style="height: 110px;">
|
||||
<table cellspacing="0" cellpadding="0">
|
||||
<tbody>
|
||||
<tr style="height: 56px;">
|
||||
<td id="commonprojectlogo">
|
||||
<img alt="Logo" src="fpl_logo_small.png"/>
|
||||
</td>
|
||||
<td style="padding-left: 0.5em;">
|
||||
<div id="projectname">FlatBuffers
|
||||
</div>
|
||||
<div style="font-size:12px;">
|
||||
An open source project by <a href="https://developers.google.com/games/#Tools">FPL</a>.
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<!-- end header part -->
|
||||
<!-- Generated by Doxygen 1.8.5 -->
|
||||
<!-- Generated by Doxygen 1.8.7 -->
|
||||
</div><!-- top -->
|
||||
<div id="side-nav" class="ui-resizable side-nav-resizable">
|
||||
<div id="nav-tree">
|
||||
@@ -50,43 +58,79 @@ $(document).ready(function(){initNavTree('md__java_usage.html','');});
|
||||
<div id="doc-content">
|
||||
<div class="header">
|
||||
<div class="headertitle">
|
||||
<div class="title">Use in Java </div> </div>
|
||||
<div class="title">Use in Java/C-sharp </div> </div>
|
||||
</div><!--header-->
|
||||
<div class="contents">
|
||||
<div class="textblock"><p>There's experimental support for reading FlatBuffers in Java. Generate code for Java with the <code>-j</code> option to <code>flatc</code>.</p>
|
||||
<p>See <code>javaTest.java</code> for an example. Essentially, you read a FlatBuffer binary file into a <code>byte[]</code>, which you then turn into a <code>ByteBuffer</code>, which you pass to the <code>getRootAsMonster</code> function: </p>
|
||||
<pre class="fragment">ByteBuffer bb = ByteBuffer.wrap(data);
|
||||
Monster monster = Monster.getRootAsMonster(bb);
|
||||
</pre><p>Now you can access values much like C++: </p>
|
||||
<pre class="fragment">short hp = monster.hp();
|
||||
Vec3 pos = monster.pos();
|
||||
</pre><p>Note that whenever you access a new object like in the <code>pos</code> example above, a new temporary accessor object gets created. If your code is very performance sensitive (you iterate through a lot of objects), there's a second <code>pos()</code> method to which you can pass a <code>Vec3</code> object you've already created. This allows you to reuse it across many calls and reduce the amount of object allocation (and thus garbage collection) your program does.</p>
|
||||
<p>Sadly the string accessors currently always create a new string when accessed, since FlatBuffer's UTF-8 strings can't be read in-place by Java.</p>
|
||||
<p>Vector access is also a bit different from C++: you pass an extra index to the vector field accessor. Then a second method with the same name suffixed by <code>_length</code> let's you know the number of elements you can access: </p>
|
||||
<pre class="fragment">for (int i = 0; i < monster.inventory_length(); i++)
|
||||
monster.inventory(i); // do something here
|
||||
</pre><p>You can also construct these buffers in Java using the static methods found in the generated code, and the FlatBufferBuilder class: </p>
|
||||
<pre class="fragment">FlatBufferBuilder fbb = new FlatBufferBuilder();
|
||||
</pre><p>Create strings: </p>
|
||||
<pre class="fragment">int str = fbb.createString("MyMonster");
|
||||
</pre><p>Create a table with a struct contained therein: </p>
|
||||
<pre class="fragment">Monster.startMonster(fbb);
|
||||
Monster.addPos(fbb, Vec3.createVec3(fbb, 1.0f, 2.0f, 3.0f, 3.0, (byte)4, (short)5, (byte)6));
|
||||
Monster.addHp(fbb, (short)80);
|
||||
Monster.addName(fbb, str);
|
||||
Monster.addInventory(fbb, inv);
|
||||
Monster.addTest_type(fbb, (byte)1);
|
||||
Monster.addTest(fbb, mon2);
|
||||
Monster.addTest4(fbb, test4s);
|
||||
int mon = Monster.endMonster(fbb);
|
||||
</pre><p>As you can see, the Java code for tables does not use a convenient <code>createMonster</code> call like the C++ code. This is to create the buffer without using temporary object allocation (since the <code>Vec3</code> is an inline component of <code>Monster</code>, it has to be created right where it is added, whereas the name and the inventory are not inline). Structs do have convenient methods that even have arguments for nested structs.</p>
|
||||
<p>Vectors also use this start/end pattern to allow vectors of both scalar types and structs: </p>
|
||||
<pre class="fragment">Monster.startInventoryVector(fbb, 5);
|
||||
for (byte i = 4; i >=0; i--) fbb.addByte(i);
|
||||
int inv = fbb.endVector();
|
||||
</pre><p>You can use the generated method <code>startInventoryVector</code> to conveniently call <code>startVector</code> with the right element size. You pass the number of elements you want to write. You write the elements backwards since the buffer is being constructed back to front.</p>
|
||||
<h2>Text Parsing</h2>
|
||||
<p>There currently is no support for parsing text (Schema's and JSON) directly from Java, though you could use the C++ parser through JNI. Please see the C++ documentation for more on text parsing. </p>
|
||||
<div class="textblock"><p>FlatBuffers supports reading and writing binary FlatBuffers in Java and C#. Generate code for Java with the <code>-j</code> option to <code>flatc</code>, or for C# with <code>-n</code> (think .Net).</p>
|
||||
<p>Note that this document is from the perspective of Java. Code for both languages is generated in the same way, with only minor differences. These differences are <a href="#differences-in-c-sharp">explained in a section below</a>.</p>
|
||||
<p>See <code>javaTest.java</code> for an example. Essentially, you read a FlatBuffer binary file into a <code>byte[]</code>, which you then turn into a <code>ByteBuffer</code>, which you pass to the <code>getRootAsMyRootType</code> function:</p>
|
||||
<div class="fragment"><div class="line">ByteBuffer bb = ByteBuffer.wrap(data);</div>
|
||||
<div class="line">Monster monster = Monster.getRootAsMonster(bb);</div>
|
||||
</div><!-- fragment --><p>Now you can access values much like C++:</p>
|
||||
<div class="fragment"><div class="line"><span class="keywordtype">short</span> hp = monster.hp();</div>
|
||||
<div class="line">Vec3 pos = monster.pos();</div>
|
||||
</div><!-- fragment --><p>Note that whenever you access a new object like in the <code>pos</code> example above, a new temporary accessor object gets created. If your code is very performance sensitive (you iterate through a lot of objects), there's a second <code>pos()</code> method to which you can pass a <code>Vec3</code> object you've already created. This allows you to reuse it across many calls and reduce the amount of object allocation (and thus garbage collection) your program does.</p>
|
||||
<p>Java does not support unsigned scalars. This means that any unsigned types you use in your schema will actually be represented as a signed value. This means all bits are still present, but may represent a negative value when used. For example, to read a <code>byte b</code> as an unsigned number, you can do: <code>(short)(b & 0xFF)</code></p>
|
||||
<p>The default string accessor (e.g. <code>monster.name()</code>) currently always create a new Java <code>String</code> when accessed, since FlatBuffer's UTF-8 strings can't be used in-place by <code>String</code>. Alternatively, use <code>monster.nameAsByteBuffer()</code> which returns a <code>ByteBuffer</code> referring to the UTF-8 data in the original <code>ByteBuffer</code>, which is much more efficient. The <code>ByteBuffer</code>'s <code>position</code> points to the first character, and its <code>limit</code> to just after the last.</p>
|
||||
<p>Vector access is also a bit different from C++: you pass an extra index to the vector field accessor. Then a second method with the same name suffixed by <code>Length</code> let's you know the number of elements you can access:</p>
|
||||
<div class="fragment"><div class="line"><span class="keywordflow">for</span> (<span class="keywordtype">int</span> i = 0; i < monster.inventoryLength(); i++)</div>
|
||||
<div class="line"> monster.inventory(i); <span class="comment">// do something here</span></div>
|
||||
</div><!-- fragment --><p>Alternatively, much like strings, you can use <code>monster.inventoryAsByteBuffer()</code> to get a <code>ByteBuffer</code> referring to the whole vector. Use <code>ByteBuffer</code> methods like <code>asFloatBuffer</code> to get specific views if needed.</p>
|
||||
<p>If you specified a file_indentifier in the schema, you can query if the buffer is of the desired type before accessing it using:</p>
|
||||
<div class="fragment"><div class="line"><span class="keywordflow">if</span> (Monster.MonsterBufferHasIdentifier(bb)) ...</div>
|
||||
</div><!-- fragment --><h2>Buffer construction in Java</h2>
|
||||
<p>You can also construct these buffers in Java using the static methods found in the generated code, and the FlatBufferBuilder class:</p>
|
||||
<div class="fragment"><div class="line">FlatBufferBuilder fbb = <span class="keyword">new</span> FlatBufferBuilder();</div>
|
||||
</div><!-- fragment --><p>Create strings:</p>
|
||||
<div class="fragment"><div class="line"><span class="keywordtype">int</span> str = fbb.createString(<span class="stringliteral">"MyMonster"</span>);</div>
|
||||
</div><!-- fragment --><p>Create a table with a struct contained therein:</p>
|
||||
<div class="fragment"><div class="line">Monster.startMonster(fbb);</div>
|
||||
<div class="line">Monster.addPos(fbb, Vec3.createVec3(fbb, 1.0f, 2.0f, 3.0f, 3.0, (byte)4, (<span class="keywordtype">short</span>)5, (byte)6));</div>
|
||||
<div class="line">Monster.addHp(fbb, (short)80);</div>
|
||||
<div class="line">Monster.addName(fbb, str);</div>
|
||||
<div class="line">Monster.addInventory(fbb, inv);</div>
|
||||
<div class="line">Monster.addTest_type(fbb, (byte)1);</div>
|
||||
<div class="line">Monster.addTest(fbb, mon2);</div>
|
||||
<div class="line">Monster.addTest4(fbb, test4s);</div>
|
||||
<div class="line"><span class="keywordtype">int</span> mon = Monster.endMonster(fbb);</div>
|
||||
</div><!-- fragment --><p>For some simpler types, you can use a convenient <code>create</code> function call that allows you to construct tables in one function call. This example definition however contains an inline struct field, so we have to create the table manually. This is to create the buffer without using temporary object allocation.</p>
|
||||
<p>It's important to understand that fields that are structs are inline (like <code>Vec3</code> above), and MUST thus be created between the start and end calls of a table. Everything else (other tables, strings, vectors) MUST be created before the start of the table they are referenced in.</p>
|
||||
<p>Structs do have convenient methods that even have arguments for nested structs.</p>
|
||||
<p>As you can see, references to other objects (e.g. the string above) are simple ints, and thus do not have the type-safety of the Offset type in C++. Extra care must thus be taken that you set the right offset on the right field.</p>
|
||||
<p>Vectors can be created from the corresponding Java array like so:</p>
|
||||
<div class="fragment"><div class="line"><span class="keywordtype">int</span> inv = Monster.createInventoryVector(fbb, <span class="keyword">new</span> byte[] { 0, 1, 2, 3, 4 });</div>
|
||||
</div><!-- fragment --><p>This works for arrays of scalars and (int) offsets to strings/tables, but not structs. If you want to write structs, or what you want to write does not sit in an array, you can also use the start/end pattern:</p>
|
||||
<div class="fragment"><div class="line">Monster.startInventoryVector(fbb, 5);</div>
|
||||
<div class="line"><span class="keywordflow">for</span> (byte i = 4; i >=0; i--) fbb.addByte(i);</div>
|
||||
<div class="line"><span class="keywordtype">int</span> inv = fbb.endVector();</div>
|
||||
</div><!-- fragment --><p>You can use the generated method <code>startInventoryVector</code> to conveniently call <code>startVector</code> with the right element size. You pass the number of elements you want to write. Note how you write the elements backwards since the buffer is being constructed back to front. You then pass <code>inv</code> to the corresponding <code>Add</code> call when you construct the table containing it afterwards.</p>
|
||||
<p>There are <code>add</code> functions for all the scalar types. You use <code>addOffset</code> for any previously constructed objects (such as other tables, strings, vectors). For structs, you use the appropriate <code>create</code> function in-line, as shown above in the <code>Monster</code> example.</p>
|
||||
<p>To finish the buffer, call:</p>
|
||||
<div class="fragment"><div class="line">Monster.finishMonsterBuffer(fbb, mon);</div>
|
||||
</div><!-- fragment --><p>The buffer is now ready to be transmitted. It is contained in the <code>ByteBuffer</code> which you can obtain from <code>fbb.dataBuffer()</code>. Importantly, the valid data does not start from offset 0 in this buffer, but from <code>fbb.dataBuffer().position()</code> (this is because the data was built backwards in memory). It ends at <code>fbb.capacity()</code>.</p>
|
||||
<h2>Differences in C-sharp</h2>
|
||||
<p>C# code works almost identically to Java, with only a few minor differences. You can see an example of C# code in <code>tests/FlatBuffers.Test/FlatBuffersExampleTests.cs</code>.</p>
|
||||
<p>First of all, naming follows standard C# style with <code>PascalCasing</code> identifiers, e.g. <code>GetRootAsMyRootType</code>. Also, values (except vectors and unions) are available as properties instead of parameterless accessor methods as in Java. The performance-enhancing methods to which you can pass an already created object are prefixed with <code>Get</code>, e.g.:</p>
|
||||
<div class="fragment"><div class="line"><span class="comment">// property</span></div>
|
||||
<div class="line">var pos = monster.Pos;</div>
|
||||
<div class="line"><span class="comment">// method filling a preconstructed object</span></div>
|
||||
<div class="line">var preconstructedPos = <span class="keyword">new</span> Vec3();</div>
|
||||
<div class="line">monster.GetPos(preconstructedPos);</div>
|
||||
</div><!-- fragment --><h2>Text parsing</h2>
|
||||
<p>There currently is no support for parsing text (Schema's and JSON) directly from Java or C#, though you could use the C++ parser through native call interfaces available to each language. Please see the C++ documentation for more on text parsing.</p>
|
||||
<h3>Mutating FlatBuffers</h3>
|
||||
<p>As you saw above, typically once you have created a FlatBuffer, it is read-only from that moment on. There are however cases where you have just received a FlatBuffer, and you'd like to modify something about it before sending it on to another recipient. With the above functionality, you'd have to generate an entirely new FlatBuffer, while tracking what you modify in your own data structures. This is inconvenient.</p>
|
||||
<p>For this reason FlatBuffers can also be mutated in-place. While this is great for making small fixes to an existing buffer, you generally want to create buffers from scratch whenever possible, since it is much more efficient and the API is much more general purpose.</p>
|
||||
<p>To get non-const accessors, invoke <code>flatc</code> with <code>--gen-mutable</code>.</p>
|
||||
<p>You now can:</p>
|
||||
<div class="fragment"><div class="line">Monster monster = Monster.getRootAsMonster(bb);</div>
|
||||
<div class="line">monster.mutateHp(10); <span class="comment">// Set table field.</span></div>
|
||||
<div class="line">monster.pos().mutateZ(4); <span class="comment">// Set struct field.</span></div>
|
||||
<div class="line">monster.mutateInventory(0, 1); <span class="comment">// Set vector element.</span></div>
|
||||
</div><!-- fragment --><p>We use the somewhat verbose term <code>mutate</code> instead of <code>set</code> to indicate that this is a special use case, not to be confused with the default way of constructing FlatBuffer data.</p>
|
||||
<p>After the above mutations, you can send on the FlatBuffer to a new recipient without any further work!</p>
|
||||
<p>Note that any <code>mutate</code> functions on tables return a boolean, which is false if the field we're trying to set isn't present in the buffer. Fields are not present if they weren't set, or even if they happen to be equal to the default value. For example, in the creation code above we set the <code>mana</code> field to <code>150</code>, which is the default value, so it was never stored in the buffer. Trying to call mutateMana() on such data will return false, and the value won't actually be modified!</p>
|
||||
<p>One way to solve this is to call <code>forceDefaults()</code> on a <code>FlatBufferBuilder</code> to force all fields you set to actually be written. This of course increases the size of the buffer somewhat, but this may be acceptable for a mutable buffer. </p>
|
||||
</div></div><!-- contents -->
|
||||
</div><!-- doc-content -->
|
||||
<!-- Google Analytics -->
|
||||
|
||||
120
docs/html/md__python_usage.html
Normal file
120
docs/html/md__python_usage.html
Normal file
@@ -0,0 +1,120 @@
|
||||
<!-- HTML header for doxygen 1.8.6-->
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
||||
<html xmlns="http://www.w3.org/1999/xhtml">
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
|
||||
<meta name="generator" content="Doxygen 1.8.7"/>
|
||||
<title>FlatBuffers: Use in Python</title>
|
||||
<link href="tabs.css" rel="stylesheet" type="text/css"/>
|
||||
<script type="text/javascript" src="jquery.js"></script>
|
||||
<script type="text/javascript" src="dynsections.js"></script>
|
||||
<link href="navtree.css" rel="stylesheet" type="text/css"/>
|
||||
<script type="text/javascript" src="resize.js"></script>
|
||||
<script type="text/javascript" src="navtree.js"></script>
|
||||
<script type="text/javascript">
|
||||
$(document).ready(initResizable);
|
||||
$(window).load(resizeHeight);
|
||||
</script>
|
||||
<link href="style.css" rel="stylesheet" type="text/css" />
|
||||
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,400italic,500,500italic,700,700italic|Roboto+Mono:400,700" rel="stylesheet">
|
||||
</head>
|
||||
<body>
|
||||
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
|
||||
<div id="titlearea" style="height: 110px;">
|
||||
<table cellspacing="0" cellpadding="0">
|
||||
<tbody>
|
||||
<tr style="height: 56px;">
|
||||
<td id="commonprojectlogo">
|
||||
<img alt="Logo" src="fpl_logo_small.png"/>
|
||||
</td>
|
||||
<td style="padding-left: 0.5em;">
|
||||
<div id="projectname">FlatBuffers
|
||||
</div>
|
||||
<div style="font-size:12px;">
|
||||
An open source project by <a href="https://developers.google.com/games/#Tools">FPL</a>.
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<!-- end header part -->
|
||||
<!-- Generated by Doxygen 1.8.7 -->
|
||||
</div><!-- top -->
|
||||
<div id="side-nav" class="ui-resizable side-nav-resizable">
|
||||
<div id="nav-tree">
|
||||
<div id="nav-tree-contents">
|
||||
<div id="nav-sync" class="sync"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="splitbar" style="-moz-user-select:none;"
|
||||
class="ui-resizable-handle">
|
||||
</div>
|
||||
</div>
|
||||
<script type="text/javascript">
|
||||
$(document).ready(function(){initNavTree('md__python_usage.html','');});
|
||||
</script>
|
||||
<div id="doc-content">
|
||||
<div class="header">
|
||||
<div class="headertitle">
|
||||
<div class="title">Use in Python </div> </div>
|
||||
</div><!--header-->
|
||||
<div class="contents">
|
||||
<div class="textblock"><p>There's experimental support for reading FlatBuffers in Python. Generate code for Python with the <code>-p</code> option to <code>flatc</code>.</p>
|
||||
<p>See <code>py_test.py</code> for an example. You import the generated code, read a FlatBuffer binary file into a <code>bytearray</code>, which you pass to the <code>GetRootAsMonster</code> function:</p>
|
||||
<div class="fragment"><div class="line"><a name="l00001"></a><span class="lineno"> 1</span> import MyGame.Example <span class="keyword">as</span> example</div>
|
||||
<div class="line"><a name="l00002"></a><span class="lineno"> 2</span> <span class="keyword">import</span> flatbuffers</div>
|
||||
<div class="line"><a name="l00003"></a><span class="lineno"> 3</span> </div>
|
||||
<div class="line"><a name="l00004"></a><span class="lineno"> 4</span> buf = open(<span class="stringliteral">'monster.dat'</span>, <span class="stringliteral">'rb'</span>).read()</div>
|
||||
<div class="line"><a name="l00005"></a><span class="lineno"> 5</span> buf = bytearray(buf)</div>
|
||||
<div class="line"><a name="l00006"></a><span class="lineno"> 6</span> monster = example.GetRootAsMonster(buf, 0)</div>
|
||||
</div><!-- fragment --><p>Now you can access values like this:</p>
|
||||
<div class="fragment"><div class="line"><a name="l00001"></a><span class="lineno"> 1</span> hp = monster.Hp()</div>
|
||||
<div class="line"><a name="l00002"></a><span class="lineno"> 2</span> pos = monster.Pos()</div>
|
||||
</div><!-- fragment --><p>To access vectors you pass an extra index to the vector field accessor. Then a second method with the same name suffixed by <code>Length</code> let's you know the number of elements you can access:</p>
|
||||
<div class="fragment"><div class="line"><a name="l00001"></a><span class="lineno"> 1</span> <span class="keywordflow">for</span> i <span class="keywordflow">in</span> xrange(monster.InventoryLength()):</div>
|
||||
<div class="line"><a name="l00002"></a><span class="lineno"> 2</span>  monster.Inventory(i) <span class="comment"># do something here</span></div>
|
||||
</div><!-- fragment --><p>You can also construct these buffers in Python using the functions found in the generated code, and the FlatBufferBuilder class:</p>
|
||||
<div class="fragment"><div class="line"><a name="l00001"></a><span class="lineno"> 1</span> builder = flatbuffers.Builder(0)</div>
|
||||
</div><!-- fragment --><p>Create strings:</p>
|
||||
<div class="fragment"><div class="line"><a name="l00001"></a><span class="lineno"> 1</span> s = builder.CreateString(<span class="stringliteral">"MyMonster"</span>)</div>
|
||||
</div><!-- fragment --><p>Create a table with a struct contained therein:</p>
|
||||
<div class="fragment"><div class="line"><a name="l00001"></a><span class="lineno"> 1</span> example.MonsterStart(builder)</div>
|
||||
<div class="line"><a name="l00002"></a><span class="lineno"> 2</span> example.MonsterAddPos(builder, example.CreateVec3(builder, 1.0, 2.0, 3.0, 3.0, 4, 5, 6))</div>
|
||||
<div class="line"><a name="l00003"></a><span class="lineno"> 3</span> example.MonsterAddHp(builder, 80)</div>
|
||||
<div class="line"><a name="l00004"></a><span class="lineno"> 4</span> example.MonsterAddName(builder, str)</div>
|
||||
<div class="line"><a name="l00005"></a><span class="lineno"> 5</span> example.MonsterAddInventory(builder, inv)</div>
|
||||
<div class="line"><a name="l00006"></a><span class="lineno"> 6</span> example.MonsterAddTest_Type(builder, 1)</div>
|
||||
<div class="line"><a name="l00007"></a><span class="lineno"> 7</span> example.MonsterAddTest(builder, mon2)</div>
|
||||
<div class="line"><a name="l00008"></a><span class="lineno"> 8</span> example.MonsterAddTest4(builder, test4s)</div>
|
||||
<div class="line"><a name="l00009"></a><span class="lineno"> 9</span> mon = example.MonsterEnd(builder)</div>
|
||||
<div class="line"><a name="l00010"></a><span class="lineno"> 10</span> </div>
|
||||
<div class="line"><a name="l00011"></a><span class="lineno"> 11</span> final_flatbuffer = builder.Output()</div>
|
||||
</div><!-- fragment --><p>Unlike C++, Python does not support table creation functions like 'createMonster()'. This is to create the buffer without using temporary object allocation (since the <code>Vec3</code> is an inline component of <code>Monster</code>, it has to be created right where it is added, whereas the name and the inventory are not inline, and <b>must</b> be created outside of the table creation sequence). Structs do have convenient methods that allow you to construct them in one call. These also have arguments for nested structs, e.g. if a struct has a field <code>a</code> and a nested struct field <code>b</code> (which has fields <code>c</code> and <code>d</code>), then the arguments will be <code>a</code>, <code>c</code> and <code>d</code>.</p>
|
||||
<p>Vectors also use this start/end pattern to allow vectors of both scalar types and structs:</p>
|
||||
<div class="fragment"><div class="line"><a name="l00001"></a><span class="lineno"> 1</span> example.MonsterStartInventoryVector(builder, 5)</div>
|
||||
<div class="line"><a name="l00002"></a><span class="lineno"> 2</span> i = 4</div>
|
||||
<div class="line"><a name="l00003"></a><span class="lineno"> 3</span> <span class="keywordflow">while</span> i >= 0:</div>
|
||||
<div class="line"><a name="l00004"></a><span class="lineno"> 4</span>  builder.PrependByte(byte(i))</div>
|
||||
<div class="line"><a name="l00005"></a><span class="lineno"> 5</span>  i -= 1</div>
|
||||
<div class="line"><a name="l00006"></a><span class="lineno"> 6</span> </div>
|
||||
<div class="line"><a name="l00007"></a><span class="lineno"> 7</span> inv = builder.EndVector(5)</div>
|
||||
</div><!-- fragment --><p>The generated method 'StartInventoryVector' is provided as a convenience function which calls 'StartVector' with the correct element size of the vector type which in this case is 'ubyte' or 1 byte per vector element. You pass the number of elements you want to write. You write the elements backwards since the buffer is being constructed back to front. Use the correct <code>Prepend</code> call for the type, or <code>PrependUOffsetT</code> for offsets. You then pass <code>inv</code> to the corresponding <code>Add</code> call when you construct the table containing it afterwards.</p>
|
||||
<p>There are <code>Prepend</code> functions for all the scalar types. You use <code>PrependUOffset</code> for any previously constructed objects (such as other tables, strings, vectors). For structs, you use the appropriate <code>create</code> function in-line, as shown above in the <code>Monster</code> example.</p>
|
||||
<p>Once you're done constructing a buffer, you call <code>Finish</code> with the root object offset (<code>mon</code> in the example above). Your data now resides in Builder.Bytes. Important to note is that the real data starts at the index indicated by Head(), for Offset() bytes (this is because the buffer is constructed backwards). If you wanted to read the buffer right after creating it (using <code>GetRootAsMonster</code> above), the second argument, instead of <code>0</code> would thus also be <code>Head()</code>.</p>
|
||||
<h2>Text Parsing</h2>
|
||||
<p>There currently is no support for parsing text (Schema's and JSON) directly from Python, though you could use the C++ parser through SWIG or ctypes. Please see the C++ documentation for more on text parsing. </p>
|
||||
</div></div><!-- contents -->
|
||||
</div><!-- doc-content -->
|
||||
<!-- Google Analytics -->
|
||||
<script>
|
||||
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
|
||||
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
|
||||
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
|
||||
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
|
||||
ga('create', 'UA-49880327-7', 'auto');
|
||||
ga('send', 'pageview');
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,9 +1,10 @@
|
||||
<!-- HTML header for doxygen 1.8.6-->
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
||||
<html xmlns="http://www.w3.org/1999/xhtml">
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
|
||||
<meta name="generator" content="Doxygen 1.8.5"/>
|
||||
<meta name="generator" content="Doxygen 1.8.7"/>
|
||||
<title>FlatBuffers: Writing a schema</title>
|
||||
<link href="tabs.css" rel="stylesheet" type="text/css"/>
|
||||
<script type="text/javascript" src="jquery.js"></script>
|
||||
@@ -15,24 +16,31 @@
|
||||
$(document).ready(initResizable);
|
||||
$(window).load(resizeHeight);
|
||||
</script>
|
||||
<link href="doxygen.css" rel="stylesheet" type="text/css" />
|
||||
<link href="style.css" rel="stylesheet" type="text/css" />
|
||||
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,400italic,500,500italic,700,700italic|Roboto+Mono:400,700" rel="stylesheet">
|
||||
</head>
|
||||
<body>
|
||||
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
|
||||
<div id="titlearea">
|
||||
<div id="titlearea" style="height: 110px;">
|
||||
<table cellspacing="0" cellpadding="0">
|
||||
<tbody>
|
||||
<tr style="height: 56px;">
|
||||
<td id="commonprojectlogo">
|
||||
<img alt="Logo" src="fpl_logo_small.png"/>
|
||||
</td>
|
||||
<td style="padding-left: 0.5em;">
|
||||
<div id="projectname">FlatBuffers
|
||||
</div>
|
||||
<div style="font-size:12px;">
|
||||
An open source project by <a href="https://developers.google.com/games/#Tools">FPL</a>.
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<!-- end header part -->
|
||||
<!-- Generated by Doxygen 1.8.5 -->
|
||||
<!-- Generated by Doxygen 1.8.7 -->
|
||||
</div><!-- top -->
|
||||
<div id="side-nav" class="ui-resizable side-nav-resizable">
|
||||
<div id="nav-tree">
|
||||
@@ -53,11 +61,12 @@ $(document).ready(function(){initNavTree('md__schemas.html','');});
|
||||
<div class="title">Writing a schema </div> </div>
|
||||
</div><!--header-->
|
||||
<div class="contents">
|
||||
<div class="textblock"><p>The syntax of the schema language (aka IDL, Interface Definition Language) should look quite familiar to users of any of the C family of languages, and also to users of other IDLs. Let's look at an example first: </p>
|
||||
<pre class="fragment">// example IDL file
|
||||
<div class="textblock"><p>The syntax of the schema language (aka IDL, Interface Definition Language) should look quite familiar to users of any of the C family of languages, and also to users of other IDLs. Let's look at an example first: </p><pre class="fragment">// example IDL file
|
||||
|
||||
namespace MyGame;
|
||||
|
||||
attribute "priority";
|
||||
|
||||
enum Color : byte { Red = 1, Green, Blue }
|
||||
|
||||
union Any { Monster, Weapon, Pickup }
|
||||
@@ -85,50 +94,96 @@ root_type Monster;
|
||||
<p>Tables are the main way of defining objects in FlatBuffers, and consist of a name (here <code>Monster</code>) and a list of fields. Each field has a name, a type, and optionally a default value (if omitted, it defaults to 0 / NULL).</p>
|
||||
<p>Each field is optional: It does not have to appear in the wire representation, and you can choose to omit fields for each individual object. As a result, you have the flexibility to add fields without fear of bloating your data. This design is also FlatBuffer's mechanism for forward and backwards compatibility. Note that:</p>
|
||||
<ul>
|
||||
<li>You can add new fields in the schema ONLY at the end of a table definition. Older data will still read correctly, and give you the default value when read. Older code will simply ignore the new field.</li>
|
||||
<li>You can add new fields in the schema ONLY at the end of a table definition. Older data will still read correctly, and give you the default value when read. Older code will simply ignore the new field. If you want to have flexibility to use any order for fields in your schema, you can manually assign ids (much like Protocol Buffers), see the <code>id</code> attribute below.</li>
|
||||
<li>You cannot delete fields you don't use anymore from the schema, but you can simply stop writing them into your data for almost the same effect. Additionally you can mark them as <code>deprecated</code> as in the example above, which will prevent the generation of accessors in the generated C++, as a way to enforce the field not being used any more. (careful: this may break code!).</li>
|
||||
<li>You may change field names and table names, if you're ok with your code breaking until you've renamed them there too.</li>
|
||||
</ul>
|
||||
<h3>Structs</h3>
|
||||
<p>Similar to a table, only now none of the fields are optional (so no defaults either), and fields may not be added or be deprecated. Structs may only contain scalars or other structs. Use this for simple objects where you are very sure no changes will ever be made (as quite clear in the example <code>Vec3</code>). Structs use less memory than tables and are even faster to access (they are always stored in-line in their parent object, and use no virtual table).</p>
|
||||
<h3>Types</h3>
|
||||
<p>Builtin scalar types are:</p>
|
||||
<p>Built-in scalar types are:</p>
|
||||
<ul>
|
||||
<li>8 bit: <code>byte ubyte bool</code></li>
|
||||
<li>16 bit: <code>short ushort</code></li>
|
||||
<li>32 bit: <code>int uint float</code></li>
|
||||
<li>64 bit: <code>long ulong double</code></li>
|
||||
<li>Vector of any other type (denoted with <code>[type]</code>). Nesting vectors require you wrap the inner vector in a struct/table rather than writing <code>[[type]]</code>.</li>
|
||||
</ul>
|
||||
<p>Built-in non-scalar types:</p>
|
||||
<ul>
|
||||
<li>Vector of any other type (denoted with <code>[type]</code>). Nesting vectors is not supported, instead you can wrap the inner vector in a table.</li>
|
||||
<li><code>string</code>, which may only hold UTF-8 or 7-bit ASCII. For other text encodings or general binary data use vectors (<code>[byte]</code> or <code>[ubyte]</code>) instead.</li>
|
||||
<li>References to other tables or structs, enums or unions (see below).</li>
|
||||
</ul>
|
||||
<p>You can't change types of fields once they're used, with the exception of same-size data where a <code>reinterpret_cast</code> would give you a desirable result, e.g. you could change a <code>uint</code> to an <code>int</code> if no values in current data use the high bit yet.</p>
|
||||
<h3>(Default) Values</h3>
|
||||
<p>Values are a sequence of digits, optionally followed by a <code>.</code> and more digits for float constants, and optionally prefixed by a <code>-</code>. Non-scalar defaults are currently not supported (always NULL).</p>
|
||||
<p>Values are a sequence of digits, optionally followed by a <code>.</code> and more digits for float constants, and optionally prefixed by a <code>-</code>. Floats may end with an <code>e</code> or <code>E</code>, followed by a <code>+</code> or <code>-</code> and more digits (scientific notation).</p>
|
||||
<p>Only scalar values can have defaults, non-scalar (string/vector/table) fields default to NULL when not present.</p>
|
||||
<p>You generally do not want to change default values after they're initially defined. Fields that have the default value are not actually stored in the serialized data but are generated in code, so when you change the default, you'd now get a different value than from code generated from an older version of the schema. There are situations however where this may be desirable, especially if you can ensure a simultaneous rebuild of all code.</p>
|
||||
<h3>Enums</h3>
|
||||
<p>Define a sequence of named constants, each with a given value, or increasing by one from the previous one. The default first value is <code>0</code>. As you can see in the enum declaration, you specify the underlying integral type of the enum with <code>:</code> (in this case <code>byte</code>), which then determines the type of any fields declared with this enum type. If you omit the underlying type, it will be <code>short</code>.</p>
|
||||
<p>Define a sequence of named constants, each with a given value, or increasing by one from the previous one. The default first value is <code>0</code>. As you can see in the enum declaration, you specify the underlying integral type of the enum with <code>:</code> (in this case <code>byte</code>), which then determines the type of any fields declared with this enum type.</p>
|
||||
<h3>Unions</h3>
|
||||
<p>Unions share a lot of properties with enums, but instead of new names for constants, you use names of tables. You can then declare a union field which can hold a reference to any of those types, and additionally a hidden field with the suffix <code>_type</code> is generated that holds the corresponding enum value, allowing you to know which type to cast to at runtime.</p>
|
||||
<p>Unions are a good way to be able to send multiple message types as a FlatBuffer. Note that because a union field is really two fields, it must always be part of a table, it cannot be the root of a FlatBuffer by itself.</p>
|
||||
<p>If you have a need to distinguish between different FlatBuffers in a more open-ended way, for example for use as files, see the file identification feature below.</p>
|
||||
<h3>Namespaces</h3>
|
||||
<p>These will generate the corresponding namespace in C++ for all helper code, and packages in Java. You can use <code>.</code> to specify nested namespaces / packages.</p>
|
||||
<h3>Includes</h3>
|
||||
<p>You can include other schemas files in your current one, e.g.: </p><pre class="fragment">include "mydefinitions.fbs";
|
||||
</pre><p>This makes it easier to refer to types defined elsewhere. <code>include</code> automatically ensures each file is parsed just once, even when referred to more than once.</p>
|
||||
<p>When using the <code>flatc</code> compiler to generate code for schema definitions, only definitions in the current file will be generated, not those from the included files (those you still generate separately).</p>
|
||||
<h3>Root type</h3>
|
||||
<p>This declares what you consider to be the root table (or struct) of the serialized data.</p>
|
||||
<h3>Comments & documentation</h3>
|
||||
<p>This declares what you consider to be the root table (or struct) of the serialized data. This is particular important for parsing JSON data, which doesn't include object type information.</p>
|
||||
<h3>File identification and extension</h3>
|
||||
<p>Typically, a FlatBuffer binary buffer is not self-describing, i.e. it needs you to know its schema to parse it correctly. But if you want to use a FlatBuffer as a file format, it would be convenient to be able to have a "magic number" in there, like most file formats have, to be able to do a sanity check to see if you're reading the kind of file you're expecting.</p>
|
||||
<p>Now, you can always prefix a FlatBuffer with your own file header, but FlatBuffers has a built-in way to add an identifier to a FlatBuffer that takes up minimal space, and keeps the buffer compatible with buffers that don't have such an identifier.</p>
|
||||
<p>You can specify in a schema, similar to <code>root_type</code>, that you intend for this type of FlatBuffer to be used as a file format: </p><pre class="fragment">file_identifier "MYFI";
|
||||
</pre><p>Identifiers must always be exactly 4 characters long. These 4 characters will end up as bytes at offsets 4-7 (inclusive) in the buffer.</p>
|
||||
<p>For any schema that has such an identifier, <code>flatc</code> will automatically add the identifier to any binaries it generates (with <code>-b</code>), and generated calls like <code>FinishMonsterBuffer</code> also add the identifier. If you have specified an identifier and wish to generate a buffer without one, you can always still do so by calling <code>FlatBufferBuilder::Finish</code> explicitly.</p>
|
||||
<p>After loading a buffer, you can use a call like <code>MonsterBufferHasIdentifier</code> to check if the identifier is present.</p>
|
||||
<p>Note that this is best for open-ended uses such as files. If you simply wanted to send one of a set of possible messages over a network for example, you'd be better off with a union.</p>
|
||||
<p>Additionally, by default <code>flatc</code> will output binary files as <code>.bin</code>. This declaration in the schema will change that to whatever you want: </p><pre class="fragment">file_extension "ext";
|
||||
</pre><h3>Comments & documentation</h3>
|
||||
<p>May be written as in most C-based languages. Additionally, a triple comment (<code>///</code>) on a line by itself signals that a comment is documentation for whatever is declared on the line after it (table/struct/field/enum/union/element), and the comment is output in the corresponding C++ code. Multiple such lines per item are allowed.</p>
|
||||
<h3>Attributes</h3>
|
||||
<p>Attributes may be attached to a declaration, behind a field, or after the name of a table/struct/enum/union. These may either have a value or not. Some attributes like <code>deprecated</code> are understood by the compiler, others are simply ignored (like <code>priority</code>), but are available to query if you parse the schema at runtime. This is useful if you write your own code generators/editors etc., and you wish to add additional information specific to your tool (such as a help text).</p>
|
||||
<p>Attributes may be attached to a declaration, behind a field, or after the name of a table/struct/enum/union. These may either have a value or not. Some attributes like <code>deprecated</code> are understood by the compiler, user defined ones need to be declared with the attribute declaration (like <code>priority</code> in the example above), and are available to query if you parse the schema at runtime. This is useful if you write your own code generators/editors etc., and you wish to add additional information specific to your tool (such as a help text).</p>
|
||||
<p>Current understood attributes:</p>
|
||||
<ul>
|
||||
<li><code>id: n</code> (on a table field): manually set the field identifier to <code>n</code>. If you use this attribute, you must use it on ALL fields of this table, and the numbers must be a contiguous range from 0 onwards. Additionally, since a union type effectively adds two fields, its id must be that of the second field (the first field is the type field and not explicitly declared in the schema). For example, if the last field before the union field had id 6, the union field should have id 8, and the unions type field will implicitly be 7. IDs allow the fields to be placed in any order in the schema. When a new field is added to the schema is must use the next available ID.</li>
|
||||
<li><code>deprecated</code> (on a field): do not generate accessors for this field anymore, code should stop using this data.</li>
|
||||
<li><code>required</code> (on a non-scalar table field): this field must always be set. By default, all fields are optional, i.e. may be left out. This is desirable, as it helps with forwards/backwards compatibility, and flexibility of data structures. It is also a burden on the reading code, since for non-scalar fields it requires you to check against NULL and take appropriate action. By specifying this field, you force code that constructs FlatBuffers to ensure this field is initialized, so the reading code may access it directly, without checking for NULL. If the constructing code does not initialize this field, they will get an assert, and also the verifier will fail on buffers that have missing required fields.</li>
|
||||
<li><code>original_order</code> (on a table): since elements in a table do not need to be stored in any particular order, they are often optimized for space by sorting them to size. This attribute stops that from happening.</li>
|
||||
<li><code>force_align: size</code> (on a struct): force the alignment of this struct to be something higher than what it is naturally aligned to. Causes these structs to be aligned to that amount inside a buffer, IF that buffer is allocated with that alignment (which is not necessarily the case for buffers accessed directly inside a <code>FlatBufferBuilder</code>).</li>
|
||||
<li><code>bit_flags</code> (on an enum): the values of this field indicate bits, meaning that any value N specified in the schema will end up representing 1<<N, or if you don't specify values at all, you'll get the sequence 1, 2, 4, 8, ...</li>
|
||||
<li><code>nested_flatbuffer: "table_name"</code> (on a field): this indicates that the field (which must be a vector of ubyte) contains flatbuffer data, for which the root type is given by <code>table_name</code>. The generated code will then produce a convenient accessor for the nested FlatBuffer.</li>
|
||||
<li><code>key</code> (on a field): this field is meant to be used as a key when sorting a vector of the type of table it sits in. Can be used for in-place binary search.</li>
|
||||
</ul>
|
||||
<h2>JSON Parsing</h2>
|
||||
<p>The same parser that parses the schema declarations above is also able to parse JSON objects that conform to this schema. So, unlike other JSON parsers, this parser is strongly typed, and parses directly into a FlatBuffer (see the compiler documentation on how to do this from the command line, or the C++ documentation on how to do this at runtime).</p>
|
||||
<p>Besides needing a schema, there are a few other changes to how it parses JSON:</p>
|
||||
<ul>
|
||||
<li>It accepts field names with and without quotes, like many JSON parsers already do. It outputs them without quotes as well, though can be made to output them using the <code>strict_json</code> flag.</li>
|
||||
<li>If a field has an enum type, the parser will recognize symbolic enum values (with or without quotes) instead of numbers, e.g. <code>field: EnumVal</code>. If a field is of integral type, you can still use symbolic names, but values need to be prefixed with their type and need to be quoted, e.g. <code>field: "Enum.EnumVal"</code>. For enums representing flags, you may place multiple inside a string separated by spaces to OR them, e.g. <code>field: "EnumVal1 EnumVal2"</code> or <code>field: "Enum.EnumVal1 Enum.EnumVal2"</code>.</li>
|
||||
<li>Similarly, for unions, these need to specified with two fields much like you do when serializing from code. E.g. for a field <code>foo</code>, you must add a field <code>foo_type: FooOne</code> right before the <code>foo</code> field, where <code>FooOne</code> would be the table out of the union you want to use.</li>
|
||||
</ul>
|
||||
<p>When parsing JSON, it recognizes the following escape codes in strings:</p>
|
||||
<ul>
|
||||
<li><code>\n</code> - linefeed.</li>
|
||||
<li><code>\t</code> - tab.</li>
|
||||
<li><code>\r</code> - carriage return.</li>
|
||||
<li><code>\b</code> - backspace.</li>
|
||||
<li><code>\f</code> - form feed.</li>
|
||||
<li><code>\"</code> - double quote.</li>
|
||||
<li><code>\\</code> - backslash.</li>
|
||||
<li><code>\/</code> - forward slash.</li>
|
||||
<li><code>\uXXXX</code> - 16-bit unicode code point, converted to the equivalent UTF-8 representation.</li>
|
||||
<li><code>\xXX</code> - 8-bit binary hexadecimal number XX. This is the only one that is not in the JSON spec (see <a href="http://json.org/">http://json.org/</a>), but is needed to be able to encode arbitrary binary in strings to text and back without losing information (e.g. the byte 0xFF can't be represented in standard JSON).</li>
|
||||
</ul>
|
||||
<p>It also generates these escape codes back again when generating JSON from a binary representation.</p>
|
||||
<h2>Gotchas</h2>
|
||||
<h3>Schemas and version control</h3>
|
||||
<p>FlatBuffers relies on new field declarations being added at the end, and earlier declarations to not be removed, but be marked deprecated when needed. We think this is an improvement over the manual number assignment that happens in Protocol Buffers.</p>
|
||||
<p>FlatBuffers relies on new field declarations being added at the end, and earlier declarations to not be removed, but be marked deprecated when needed. We think this is an improvement over the manual number assignment that happens in Protocol Buffers (and which is still an option using the <code>id</code> attribute mentioned above).</p>
|
||||
<p>One place where this is possibly problematic however is source control. If user A adds a field, generates new binary data with this new schema, then tries to commit both to source control after user B already committed a new field also, and just auto-merges the schema, the binary files are now invalid compared to the new schema.</p>
|
||||
<p>The solution of course is that you should not be generating binary data before your schema changes have been committed, ensuring consistency with the rest of the world. </p>
|
||||
<p>The solution of course is that you should not be generating binary data before your schema changes have been committed, ensuring consistency with the rest of the world. If this is not practical for you, use explicit field ids, which should always generate a merge conflict if two people try to allocate the same id. </p>
|
||||
</div></div><!-- contents -->
|
||||
</div><!-- doc-content -->
|
||||
<!-- Google Analytics -->
|
||||
|
||||
122
docs/html/md__support.html
Normal file
122
docs/html/md__support.html
Normal file
@@ -0,0 +1,122 @@
|
||||
<!-- HTML header for doxygen 1.8.6-->
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
||||
<html xmlns="http://www.w3.org/1999/xhtml">
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
|
||||
<meta name="generator" content="Doxygen 1.8.7"/>
|
||||
<title>FlatBuffers: Platform / Language / Feature support</title>
|
||||
<link href="tabs.css" rel="stylesheet" type="text/css"/>
|
||||
<script type="text/javascript" src="jquery.js"></script>
|
||||
<script type="text/javascript" src="dynsections.js"></script>
|
||||
<link href="navtree.css" rel="stylesheet" type="text/css"/>
|
||||
<script type="text/javascript" src="resize.js"></script>
|
||||
<script type="text/javascript" src="navtree.js"></script>
|
||||
<script type="text/javascript">
|
||||
$(document).ready(initResizable);
|
||||
$(window).load(resizeHeight);
|
||||
</script>
|
||||
<link href="style.css" rel="stylesheet" type="text/css" />
|
||||
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,400italic,500,500italic,700,700italic|Roboto+Mono:400,700" rel="stylesheet">
|
||||
</head>
|
||||
<body>
|
||||
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
|
||||
<div id="titlearea" style="height: 110px;">
|
||||
<table cellspacing="0" cellpadding="0">
|
||||
<tbody>
|
||||
<tr style="height: 56px;">
|
||||
<td id="commonprojectlogo">
|
||||
<img alt="Logo" src="fpl_logo_small.png"/>
|
||||
</td>
|
||||
<td style="padding-left: 0.5em;">
|
||||
<div id="projectname">FlatBuffers
|
||||
</div>
|
||||
<div style="font-size:12px;">
|
||||
An open source project by <a href="https://developers.google.com/games/#Tools">FPL</a>.
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<!-- end header part -->
|
||||
<!-- Generated by Doxygen 1.8.7 -->
|
||||
</div><!-- top -->
|
||||
<div id="side-nav" class="ui-resizable side-nav-resizable">
|
||||
<div id="nav-tree">
|
||||
<div id="nav-tree-contents">
|
||||
<div id="nav-sync" class="sync"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="splitbar" style="-moz-user-select:none;"
|
||||
class="ui-resizable-handle">
|
||||
</div>
|
||||
</div>
|
||||
<script type="text/javascript">
|
||||
$(document).ready(function(){initNavTree('md__support.html','');});
|
||||
</script>
|
||||
<div id="doc-content">
|
||||
<div class="header">
|
||||
<div class="headertitle">
|
||||
<div class="title">Platform / Language / Feature support </div> </div>
|
||||
</div><!--header-->
|
||||
<div class="contents">
|
||||
<div class="textblock"><p>FlatBuffers is actively being worked on, which means that certain platform / language / feature combinations may not be available yet.</p>
|
||||
<p>This page tries to track those issues, to make informed decisions easier. In general:</p>
|
||||
<ul>
|
||||
<li>Languages: language support beyond the ones created by the original FlatBuffer authors typically depends on community contributions.</li>
|
||||
<li>Features: C++ was the first language supported, since our original target was high performance game development. It thus has the richest feature set, and is likely most robust. Other languages are catching up however.</li>
|
||||
<li>Platforms: All language implementations are typically portable to most platforms, unless where noted otherwise.</li>
|
||||
</ul>
|
||||
<p>NOTE: this table is a start, it needs to be extended.</p>
|
||||
<table class="doxtable">
|
||||
<tr>
|
||||
<th>Feature </th><th>C++ </th><th>Java </th><th>C# </th><th>Go </th><th>Python </th><th>JS </th></tr>
|
||||
<tr>
|
||||
<td>Codegen for all basic features </td><td>Yes </td><td>Yes </td><td>Yes </td><td>Yes </td><td>Yes </td><td>WIP </td></tr>
|
||||
<tr>
|
||||
<td>JSON parsing </td><td>Yes </td><td>No </td><td>No </td><td>No </td><td>No </td><td>No </td></tr>
|
||||
<tr>
|
||||
<td>Simple mutation </td><td>Yes </td><td>WIP </td><td>WIP </td><td>No </td><td>No </td><td>No </td></tr>
|
||||
<tr>
|
||||
<td>Reflection </td><td>Yes </td><td>No </td><td>No </td><td>No </td><td>No </td><td>No </td></tr>
|
||||
<tr>
|
||||
<td>Buffer verifier </td><td>Yes </td><td>No </td><td>No </td><td>No </td><td>No </td><td>No </td></tr>
|
||||
<tr>
|
||||
<td>Testing: basic </td><td>Yes </td><td>Yes </td><td>Yes </td><td>Yes </td><td>Yes </td><td>WIP </td></tr>
|
||||
<tr>
|
||||
<td>Testing: fuzz </td><td>Yes </td><td>No </td><td>No </td><td>Yes </td><td>Yes </td><td>No </td></tr>
|
||||
<tr>
|
||||
<td>Performance: </td><td>Superb </td><td>Great </td><td>Great </td><td>Great </td><td>Ok </td><td>? </td></tr>
|
||||
<tr>
|
||||
<td>Platform: Windows </td><td>VS2010 </td><td>Yes </td><td>Yes </td><td>? </td><td>? </td><td>? </td></tr>
|
||||
<tr>
|
||||
<td>Platform: Linux </td><td>GCC282 </td><td>Yes </td><td>? </td><td>Yes </td><td>Yes </td><td>? </td></tr>
|
||||
<tr>
|
||||
<td>Platform: OS X </td><td>Xcode4 </td><td>? </td><td>? </td><td>? </td><td>Yes </td><td>? </td></tr>
|
||||
<tr>
|
||||
<td>Platform: Android </td><td>NDK10d </td><td>Yes </td><td>? </td><td>? </td><td>? </td><td>? </td></tr>
|
||||
<tr>
|
||||
<td>Platform: iOS </td><td>? </td><td>? </td><td>? </td><td>? </td><td>? </td><td>? </td></tr>
|
||||
<tr>
|
||||
<td>Engine: Unity </td><td>? </td><td>? </td><td>Yes </td><td>? </td><td>? </td><td>? </td></tr>
|
||||
<tr>
|
||||
<td>Primary authors (github) </td><td>wvo </td><td>wvo </td><td>(ev/js)</td><td>rw </td><td>rw </td><td>(ev) </td></tr>
|
||||
</table>
|
||||
<ul>
|
||||
<li>ev = evolutional</li>
|
||||
<li>js = jonsimantov </li>
|
||||
</ul>
|
||||
</div></div><!-- contents -->
|
||||
</div><!-- doc-content -->
|
||||
<!-- Google Analytics -->
|
||||
<script>
|
||||
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
|
||||
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
|
||||
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
|
||||
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
|
||||
ga('create', 'UA-49880327-7', 'auto');
|
||||
ga('send', 'pageview');
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,9 +1,10 @@
|
||||
<!-- HTML header for doxygen 1.8.6-->
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
||||
<html xmlns="http://www.w3.org/1999/xhtml">
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
|
||||
<meta name="generator" content="Doxygen 1.8.5"/>
|
||||
<meta name="generator" content="Doxygen 1.8.7"/>
|
||||
<title>FlatBuffers: FlatBuffers white paper</title>
|
||||
<link href="tabs.css" rel="stylesheet" type="text/css"/>
|
||||
<script type="text/javascript" src="jquery.js"></script>
|
||||
@@ -15,24 +16,31 @@
|
||||
$(document).ready(initResizable);
|
||||
$(window).load(resizeHeight);
|
||||
</script>
|
||||
<link href="doxygen.css" rel="stylesheet" type="text/css" />
|
||||
<link href="style.css" rel="stylesheet" type="text/css" />
|
||||
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,400italic,500,500italic,700,700italic|Roboto+Mono:400,700" rel="stylesheet">
|
||||
</head>
|
||||
<body>
|
||||
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
|
||||
<div id="titlearea">
|
||||
<div id="titlearea" style="height: 110px;">
|
||||
<table cellspacing="0" cellpadding="0">
|
||||
<tbody>
|
||||
<tr style="height: 56px;">
|
||||
<td id="commonprojectlogo">
|
||||
<img alt="Logo" src="fpl_logo_small.png"/>
|
||||
</td>
|
||||
<td style="padding-left: 0.5em;">
|
||||
<div id="projectname">FlatBuffers
|
||||
</div>
|
||||
<div style="font-size:12px;">
|
||||
An open source project by <a href="https://developers.google.com/games/#Tools">FPL</a>.
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<!-- end header part -->
|
||||
<!-- Generated by Doxygen 1.8.5 -->
|
||||
<!-- Generated by Doxygen 1.8.7 -->
|
||||
</div><!-- top -->
|
||||
<div id="side-nav" class="ui-resizable side-nav-resizable">
|
||||
<div id="nav-tree">
|
||||
|
||||
@@ -5,11 +5,14 @@ var NAVTREE =
|
||||
[ "Using the schema compiler", "md__compiler.html", null ],
|
||||
[ "Writing a schema", "md__schemas.html", null ],
|
||||
[ "Use in C++", "md__cpp_usage.html", null ],
|
||||
[ "Use in Java", "md__java_usage.html", null ],
|
||||
[ "Use in Go", "md__go_usage.html", null ],
|
||||
[ "Use in Java/C-sharp", "md__java_usage.html", null ],
|
||||
[ "Use in Python", "md__python_usage.html", null ],
|
||||
[ "Platform / Language / Feature support", "md__support.html", null ],
|
||||
[ "Benchmarks", "md__benchmarks.html", null ],
|
||||
[ "FlatBuffers white paper", "md__white_paper.html", null ],
|
||||
[ "FlatBuffer Internals", "md__internals.html", null ],
|
||||
[ "Formal Grammar of the schema language", "md__grammar.html", null ]
|
||||
[ "Grammar of the schema language", "md__grammar.html", null ]
|
||||
] ]
|
||||
];
|
||||
|
||||
@@ -18,8 +21,6 @@ var NAVTREEINDEX =
|
||||
"index.html"
|
||||
];
|
||||
|
||||
var SYNCONMSG = 'click to disable panel synchronisation';
|
||||
var SYNCOFFMSG = 'click to enable panel synchronisation';
|
||||
var SYNCONMSG = 'click to disable panel synchronisation';
|
||||
var SYNCOFFMSG = 'click to enable panel synchronisation';
|
||||
var navTreeSubIndices = new Array();
|
||||
@@ -44,6 +45,21 @@ function stripPath2(uri)
|
||||
return m ? uri.substring(i-6) : s;
|
||||
}
|
||||
|
||||
function hashValue()
|
||||
{
|
||||
return $(location).attr('hash').substring(1).replace(/[^\w\-]/g,'');
|
||||
}
|
||||
|
||||
function hashUrl()
|
||||
{
|
||||
return '#'+hashValue();
|
||||
}
|
||||
|
||||
function pathName()
|
||||
{
|
||||
return $(location).attr('pathname').replace(/[^-A-Za-z0-9+&@#/%?=~_|!:,.;\(\)]/g, '');
|
||||
}
|
||||
|
||||
function localStorageSupported()
|
||||
{
|
||||
try {
|
||||
@@ -66,7 +82,7 @@ function deleteLink()
|
||||
{
|
||||
if (localStorageSupported()) {
|
||||
window.localStorage.setItem('navpath','');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function cachedLink()
|
||||
@@ -128,7 +144,7 @@ function createIndent(o,domNode,node,level)
|
||||
span.style.display = 'inline-block';
|
||||
span.style.width = 16*(level+1)+'px';
|
||||
span.style.height = '22px';
|
||||
span.innerHTML = ' ';
|
||||
span.innerHTML = ' ';
|
||||
domNode.appendChild(span);
|
||||
}
|
||||
}
|
||||
@@ -138,11 +154,13 @@ var animationInProgress = false;
|
||||
function gotoAnchor(anchor,aname,updateLocation)
|
||||
{
|
||||
var pos, docContent = $('#doc-content');
|
||||
if (anchor.parent().attr('class')=='memItemLeft' ||
|
||||
anchor.parent().attr('class')=='fieldtype' ||
|
||||
anchor.parent().is(':header'))
|
||||
var ancParent = $(anchor.parent());
|
||||
if (ancParent.hasClass('memItemLeft') ||
|
||||
ancParent.hasClass('fieldname') ||
|
||||
ancParent.hasClass('fieldtype') ||
|
||||
ancParent.is(':header'))
|
||||
{
|
||||
pos = anchor.parent().position().top;
|
||||
pos = ancParent.position().top;
|
||||
} else if (anchor.position()) {
|
||||
pos = anchor.position().top;
|
||||
}
|
||||
@@ -200,7 +218,7 @@ function newNode(o, po, text, link, childrenData, lastNode)
|
||||
a.className = stripPath(link.replace('#',':'));
|
||||
if (link.indexOf('#')!=-1) {
|
||||
var aname = '#'+link.split('#')[1];
|
||||
var srcPage = stripPath($(location).attr('pathname'));
|
||||
var srcPage = stripPath(pathName());
|
||||
var targetPage = stripPath(link.split('#')[0]);
|
||||
a.href = srcPage!=targetPage ? url : "javascript:void(0)";
|
||||
a.onclick = function(){
|
||||
@@ -294,14 +312,13 @@ function glowEffect(n,duration)
|
||||
|
||||
function highlightAnchor()
|
||||
{
|
||||
var aname = $(location).attr('hash');
|
||||
var aname = hashUrl();
|
||||
var anchor = $(aname);
|
||||
if (anchor.parent().attr('class')=='memItemLeft'){
|
||||
var rows = $('.memberdecls tr[class$="'+
|
||||
window.location.hash.substring(1)+'"]');
|
||||
var rows = $('.memberdecls tr[class$="'+hashValue()+'"]');
|
||||
glowEffect(rows.children(),300); // member without details
|
||||
} else if (anchor.parents().slice(2).prop('tagName')=='TR') {
|
||||
glowEffect(anchor.parents('div.memitem'),1000); // enum value
|
||||
} else if (anchor.parent().attr('class')=='fieldname'){
|
||||
glowEffect(anchor.parent().parent(),1000); // enum value
|
||||
} else if (anchor.parent().attr('class')=='fieldtype'){
|
||||
glowEffect(anchor.parent().parent(),1000); // struct field
|
||||
} else if (anchor.parent().is(":header")) {
|
||||
@@ -316,7 +333,7 @@ function selectAndHighlight(hash,n)
|
||||
{
|
||||
var a;
|
||||
if (hash) {
|
||||
var link=stripPath($(location).attr('pathname'))+':'+hash.substring(1);
|
||||
var link=stripPath(pathName())+':'+hash.substring(1);
|
||||
a=$('.item a[class$="'+link+'"]');
|
||||
}
|
||||
if (a && a.length) {
|
||||
@@ -427,14 +444,13 @@ function navTo(o,root,hash,relpath)
|
||||
if (link) {
|
||||
var parts = link.split('#');
|
||||
root = parts[0];
|
||||
if (parts.length>1) hash = '#'+parts[1];
|
||||
if (parts.length>1) hash = '#'+parts[1].replace(/[^\w\-]/g,'');
|
||||
else hash='';
|
||||
}
|
||||
if (hash.match(/^#l\d+$/)) {
|
||||
var anchor=$('a[name='+hash.substring(1)+']');
|
||||
glowEffect(anchor.parent(),1000); // line number
|
||||
hash=''; // strip line number anchors
|
||||
//root=root.replace(/_source\./,'.'); // source link to doc link
|
||||
}
|
||||
var url=root+hash;
|
||||
var i=-1;
|
||||
@@ -468,7 +484,7 @@ function toggleSyncButton(relpath)
|
||||
if (navSync.hasClass('sync')) {
|
||||
navSync.removeClass('sync');
|
||||
showSyncOff(navSync,relpath);
|
||||
storeLink(stripPath2($(location).attr('pathname'))+$(location).attr('hash'));
|
||||
storeLink(stripPath2(pathName())+hashUrl());
|
||||
} else {
|
||||
navSync.addClass('sync');
|
||||
showSyncOn(navSync,relpath);
|
||||
@@ -508,7 +524,7 @@ function initNavTree(toroot,relpath)
|
||||
}
|
||||
|
||||
$(window).load(function(){
|
||||
navTo(o,toroot,window.location.hash,relpath);
|
||||
navTo(o,toroot,hashUrl(),relpath);
|
||||
showRoot();
|
||||
});
|
||||
|
||||
@@ -516,21 +532,20 @@ function initNavTree(toroot,relpath)
|
||||
if (window.location.hash && window.location.hash.length>1){
|
||||
var a;
|
||||
if ($(location).attr('hash')){
|
||||
var clslink=stripPath($(location).attr('pathname'))+':'+
|
||||
$(location).attr('hash').substring(1);
|
||||
a=$('.item a[class$="'+clslink+'"]');
|
||||
var clslink=stripPath(pathName())+':'+hashValue();
|
||||
a=$('.item a[class$="'+clslink.replace(/</g,'\\3c ')+'"]');
|
||||
}
|
||||
if (a==null || !$(a).parent().parent().hasClass('selected')){
|
||||
$('.item').removeClass('selected');
|
||||
$('.item').removeAttr('id');
|
||||
}
|
||||
var link=stripPath2($(location).attr('pathname'));
|
||||
navTo(o,link,$(location).attr('hash'),relpath);
|
||||
var link=stripPath2(pathName());
|
||||
navTo(o,link,hashUrl(),relpath);
|
||||
} else if (!animationInProgress) {
|
||||
$('#doc-content').scrollTop(0);
|
||||
$('.item').removeClass('selected');
|
||||
$('.item').removeAttr('id');
|
||||
navTo(o,toroot,window.location.hash,relpath);
|
||||
navTo(o,toroot,hashUrl(),relpath);
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,14 +1,17 @@
|
||||
var NAVTREEINDEX0 =
|
||||
{
|
||||
"index.html":[],
|
||||
"md__benchmarks.html":[5],
|
||||
"md__benchmarks.html":[8],
|
||||
"md__building.html":[0],
|
||||
"md__compiler.html":[1],
|
||||
"md__cpp_usage.html":[3],
|
||||
"md__grammar.html":[8],
|
||||
"md__internals.html":[7],
|
||||
"md__java_usage.html":[4],
|
||||
"md__go_usage.html":[4],
|
||||
"md__grammar.html":[11],
|
||||
"md__internals.html":[10],
|
||||
"md__java_usage.html":[5],
|
||||
"md__python_usage.html":[6],
|
||||
"md__schemas.html":[2],
|
||||
"md__white_paper.html":[6],
|
||||
"md__support.html":[7],
|
||||
"md__white_paper.html":[9],
|
||||
"pages.html":[]
|
||||
};
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
<!-- HTML header for doxygen 1.8.6-->
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
||||
<html xmlns="http://www.w3.org/1999/xhtml">
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
|
||||
<meta name="generator" content="Doxygen 1.8.5"/>
|
||||
<meta name="generator" content="Doxygen 1.8.7"/>
|
||||
<title>FlatBuffers: Related Pages</title>
|
||||
<link href="tabs.css" rel="stylesheet" type="text/css"/>
|
||||
<script type="text/javascript" src="jquery.js"></script>
|
||||
@@ -15,24 +16,31 @@
|
||||
$(document).ready(initResizable);
|
||||
$(window).load(resizeHeight);
|
||||
</script>
|
||||
<link href="doxygen.css" rel="stylesheet" type="text/css" />
|
||||
<link href="style.css" rel="stylesheet" type="text/css" />
|
||||
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,400italic,500,500italic,700,700italic|Roboto+Mono:400,700" rel="stylesheet">
|
||||
</head>
|
||||
<body>
|
||||
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
|
||||
<div id="titlearea">
|
||||
<div id="titlearea" style="height: 110px;">
|
||||
<table cellspacing="0" cellpadding="0">
|
||||
<tbody>
|
||||
<tr style="height: 56px;">
|
||||
<td id="commonprojectlogo">
|
||||
<img alt="Logo" src="fpl_logo_small.png"/>
|
||||
</td>
|
||||
<td style="padding-left: 0.5em;">
|
||||
<div id="projectname">FlatBuffers
|
||||
</div>
|
||||
<div style="font-size:12px;">
|
||||
An open source project by <a href="https://developers.google.com/games/#Tools">FPL</a>.
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<!-- end header part -->
|
||||
<!-- Generated by Doxygen 1.8.5 -->
|
||||
<!-- Generated by Doxygen 1.8.7 -->
|
||||
</div><!-- top -->
|
||||
<div id="side-nav" class="ui-resizable side-nav-resizable">
|
||||
<div id="nav-tree">
|
||||
@@ -55,15 +63,18 @@ $(document).ready(function(){initNavTree('pages.html','');});
|
||||
<div class="contents">
|
||||
<div class="textblock">Here is a list of all related documentation pages:</div><div class="directory">
|
||||
<table class="directory">
|
||||
<tr id="row_0_" class="even"><td class="entry"><img src="ftv2node.png" alt="o" width="16" height="22" /><a class="el" href="md__building.html" target="_self">Building</a></td><td class="desc"></td></tr>
|
||||
<tr id="row_1_"><td class="entry"><img src="ftv2node.png" alt="o" width="16" height="22" /><a class="el" href="md__compiler.html" target="_self">Using the schema compiler</a></td><td class="desc"></td></tr>
|
||||
<tr id="row_2_" class="even"><td class="entry"><img src="ftv2node.png" alt="o" width="16" height="22" /><a class="el" href="md__schemas.html" target="_self">Writing a schema</a></td><td class="desc"></td></tr>
|
||||
<tr id="row_3_"><td class="entry"><img src="ftv2node.png" alt="o" width="16" height="22" /><a class="el" href="md__cpp_usage.html" target="_self">Use in C++</a></td><td class="desc"></td></tr>
|
||||
<tr id="row_4_" class="even"><td class="entry"><img src="ftv2node.png" alt="o" width="16" height="22" /><a class="el" href="md__java_usage.html" target="_self">Use in Java</a></td><td class="desc"></td></tr>
|
||||
<tr id="row_5_"><td class="entry"><img src="ftv2node.png" alt="o" width="16" height="22" /><a class="el" href="md__benchmarks.html" target="_self">Benchmarks</a></td><td class="desc"></td></tr>
|
||||
<tr id="row_6_" class="even"><td class="entry"><img src="ftv2node.png" alt="o" width="16" height="22" /><a class="el" href="md__white_paper.html" target="_self">FlatBuffers white paper</a></td><td class="desc"></td></tr>
|
||||
<tr id="row_7_"><td class="entry"><img src="ftv2node.png" alt="o" width="16" height="22" /><a class="el" href="md__internals.html" target="_self">FlatBuffer Internals</a></td><td class="desc"></td></tr>
|
||||
<tr id="row_8_" class="even"><td class="entry"><img src="ftv2lastnode.png" alt="\" width="16" height="22" /><a class="el" href="md__grammar.html" target="_self">Formal Grammar of the schema language</a></td><td class="desc"></td></tr>
|
||||
<tr id="row_0_" class="even"><td class="entry"><span style="width:16px;display:inline-block;"> </span><a class="el" href="md__building.html" target="_self">Building</a></td><td class="desc"></td></tr>
|
||||
<tr id="row_1_"><td class="entry"><span style="width:16px;display:inline-block;"> </span><a class="el" href="md__compiler.html" target="_self">Using the schema compiler</a></td><td class="desc"></td></tr>
|
||||
<tr id="row_2_" class="even"><td class="entry"><span style="width:16px;display:inline-block;"> </span><a class="el" href="md__schemas.html" target="_self">Writing a schema</a></td><td class="desc"></td></tr>
|
||||
<tr id="row_3_"><td class="entry"><span style="width:16px;display:inline-block;"> </span><a class="el" href="md__cpp_usage.html" target="_self">Use in C++</a></td><td class="desc"></td></tr>
|
||||
<tr id="row_4_" class="even"><td class="entry"><span style="width:16px;display:inline-block;"> </span><a class="el" href="md__go_usage.html" target="_self">Use in Go</a></td><td class="desc"></td></tr>
|
||||
<tr id="row_5_"><td class="entry"><span style="width:16px;display:inline-block;"> </span><a class="el" href="md__java_usage.html" target="_self">Use in Java/C-sharp</a></td><td class="desc"></td></tr>
|
||||
<tr id="row_6_" class="even"><td class="entry"><span style="width:16px;display:inline-block;"> </span><a class="el" href="md__python_usage.html" target="_self">Use in Python</a></td><td class="desc"></td></tr>
|
||||
<tr id="row_7_"><td class="entry"><span style="width:16px;display:inline-block;"> </span><a class="el" href="md__support.html" target="_self">Platform / Language / Feature support</a></td><td class="desc"></td></tr>
|
||||
<tr id="row_8_" class="even"><td class="entry"><span style="width:16px;display:inline-block;"> </span><a class="el" href="md__benchmarks.html" target="_self">Benchmarks</a></td><td class="desc"></td></tr>
|
||||
<tr id="row_9_"><td class="entry"><span style="width:16px;display:inline-block;"> </span><a class="el" href="md__white_paper.html" target="_self">FlatBuffers white paper</a></td><td class="desc"></td></tr>
|
||||
<tr id="row_10_" class="even"><td class="entry"><span style="width:16px;display:inline-block;"> </span><a class="el" href="md__internals.html" target="_self">FlatBuffer Internals</a></td><td class="desc"></td></tr>
|
||||
<tr id="row_11_"><td class="entry"><span style="width:16px;display:inline-block;"> </span><a class="el" href="md__grammar.html" target="_self">Grammar of the schema language</a></td><td class="desc"></td></tr>
|
||||
</table>
|
||||
</div><!-- directory -->
|
||||
</div><!-- contents -->
|
||||
|
||||
@@ -77,15 +77,19 @@ function initResizable()
|
||||
var _preventDefault = function(evt) { evt.preventDefault(); };
|
||||
$("#splitbar").bind("dragstart", _preventDefault).bind("selectstart", _preventDefault);
|
||||
$(document).bind('touchmove',function(e){
|
||||
try {
|
||||
var target = e.target;
|
||||
while (target) {
|
||||
if ($(target).css('-webkit-overflow-scrolling')=='touch') return;
|
||||
target = target.parentNode;
|
||||
var device = navigator.userAgent.toLowerCase();
|
||||
var ios = device.match(/(iphone|ipod|ipad)/);
|
||||
if (ios) {
|
||||
try {
|
||||
var target = e.target;
|
||||
while (target) {
|
||||
if ($(target).css('-webkit-overflow-scrolling')=='touch') return;
|
||||
target = target.parentNode;
|
||||
}
|
||||
e.preventDefault();
|
||||
} catch(err) {
|
||||
e.preventDefault();
|
||||
}
|
||||
e.preventDefault();
|
||||
} catch(err) {
|
||||
e.preventDefault();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
396
docs/html/style.css
Normal file
396
docs/html/style.css
Normal file
@@ -0,0 +1,396 @@
|
||||
body,
|
||||
#projectname,
|
||||
table,
|
||||
div,
|
||||
p,
|
||||
dl,
|
||||
.title,
|
||||
.tabs,
|
||||
.tabs2,
|
||||
.tabs3,
|
||||
#nav-tree .label {
|
||||
font-family: roboto, sans-serif;
|
||||
}
|
||||
|
||||
#commonprojectlogo {
|
||||
padding: 5px 0px 5px 15px;
|
||||
}
|
||||
|
||||
#projectname {
|
||||
color: #00bcd4;
|
||||
font-size: 280%;
|
||||
padding: 15px 0px;
|
||||
font-weight: 300;
|
||||
}
|
||||
|
||||
#titlearea {
|
||||
border-bottom: 2px solid #e5e5e5;
|
||||
}
|
||||
|
||||
.title {
|
||||
color: #212121;
|
||||
font: 300 34px/40px Roboto,sans-serif;
|
||||
}
|
||||
|
||||
#nav-tree {
|
||||
background-color: #fff;
|
||||
}
|
||||
|
||||
#navrow1, #navrow2 {
|
||||
border-bottom: 2px solid #e7e7e7;
|
||||
}
|
||||
|
||||
.tabs, .tabs2, .tabs3 {
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.tabs,
|
||||
.tabs2,
|
||||
.tabs3,
|
||||
.tablist li,
|
||||
.tablist li.current a {
|
||||
background-image: none;
|
||||
}
|
||||
|
||||
.tablist {
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.tablist li, .tablist li p {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.tablist li a,
|
||||
.tablist li.current a {
|
||||
color: #757575;
|
||||
text-shadow: none;
|
||||
}
|
||||
|
||||
.tablist li.current a {
|
||||
background: #00bcd4;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.tablist a {
|
||||
background-image: none;
|
||||
border-right: 2px solid #e5e5e5;
|
||||
font-weight: normal;
|
||||
}
|
||||
|
||||
.tablist a:hover,
|
||||
.tablist li.current a:hover {
|
||||
background-image: none;
|
||||
text-decoration: underline;
|
||||
text-shadow: none;
|
||||
}
|
||||
|
||||
.tablist a:hover {
|
||||
color: #00bcd4;
|
||||
}
|
||||
|
||||
.tablist li.current a:hover {
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
div.header {
|
||||
background-color: #f7f7f7;
|
||||
background-image: none;
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
#MSearchBox {
|
||||
border: 1px solid #ccc;
|
||||
border-radius: 5px;
|
||||
display: inline-block;
|
||||
height: 20px;
|
||||
right: 10px;
|
||||
}
|
||||
|
||||
#MSearchBox .left,
|
||||
#MSearchBox .right,
|
||||
#MSearchField {
|
||||
background: none;
|
||||
}
|
||||
|
||||
a.SelectItem:hover {
|
||||
background-color: #00bcd4;
|
||||
}
|
||||
|
||||
#nav-tree {
|
||||
background-image: none;
|
||||
}
|
||||
|
||||
#nav-tree .selected {
|
||||
background-image: none;
|
||||
text-shadow: none;
|
||||
background-color: #f7f7f7;
|
||||
}
|
||||
|
||||
#nav-tree a {
|
||||
color: #212121;
|
||||
}
|
||||
|
||||
#nav-tree .selected a {
|
||||
color: #0288d1;
|
||||
}
|
||||
|
||||
#nav-tree .item:hover {
|
||||
background-color: #f7f7f7;
|
||||
}
|
||||
|
||||
#nav-tree .item:hover a {
|
||||
color: #0288d1;
|
||||
}
|
||||
|
||||
#nav-tree .label {
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
#nav-sync {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.ui-resizable-e {
|
||||
background: #ebebeb;
|
||||
border-left: 1px solid #ddd;
|
||||
border-right: 1px solid #ddd;
|
||||
}
|
||||
|
||||
.contents tr td .image {
|
||||
margin-top: 24px;
|
||||
}
|
||||
|
||||
.image {
|
||||
text-align: left;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
a:link,
|
||||
a:visited,
|
||||
.contents a:link,
|
||||
.contents a:visited,
|
||||
a.el {
|
||||
color: #0288d1;
|
||||
font-weight: normal;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
div.contents {
|
||||
margin-right: 12px;
|
||||
}
|
||||
|
||||
.directory tr, .directory tr.even {
|
||||
background: #7cb342;
|
||||
border-top: 1px solid #7cb342;
|
||||
}
|
||||
|
||||
.directory td,
|
||||
.directory td.entry,
|
||||
.directory td.desc {
|
||||
background: rgba(255,255,255,.95);
|
||||
border-left: none;
|
||||
color: #212121;
|
||||
padding-top: 10px;
|
||||
padding-bottom: 10px;
|
||||
padding-left: 8px;
|
||||
padding-right: 8px;
|
||||
}
|
||||
|
||||
.directory tr#row_0_ {
|
||||
border-top-color: #7cb342;
|
||||
}
|
||||
|
||||
.directory tr#row_0_ td {
|
||||
background: #7cb342;
|
||||
color: #fff;
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.memSeparator {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.memitem {
|
||||
background: #7cb342;
|
||||
}
|
||||
|
||||
.memproto, dl.reflist dt {
|
||||
background: #7cb342;
|
||||
background-image: none;
|
||||
border: none;
|
||||
box-shadow: none;
|
||||
-webkit-box-shadow: none;
|
||||
color: #fff;
|
||||
text-shadow: none;
|
||||
}
|
||||
|
||||
.memproto .memtemplate,
|
||||
.memproto a.el,
|
||||
.memproto .paramname {
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.memdoc, dl.reflist dd {
|
||||
border: none;
|
||||
background-color: rgba(255,255,255,.95);
|
||||
background-image: none;
|
||||
box-shadow: none;
|
||||
-webkit-box-shadow: none;
|
||||
-webkit-border-bottom-left-radius: 0;
|
||||
-webkit-border-bottom-right-radius: 0;
|
||||
}
|
||||
|
||||
.memitem, table.doxtable, table.memberdecls {
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
table.doxtable th {
|
||||
background: #7cb342;
|
||||
}
|
||||
|
||||
table.doxtable tr {
|
||||
background: #7cb342;
|
||||
border-top: 1px solid #7cb342;
|
||||
}
|
||||
|
||||
table.doxtable td, table.doxtable th {
|
||||
border: none;
|
||||
padding: 10px 8px;
|
||||
}
|
||||
|
||||
table.doxtable td {
|
||||
background-color: rgba(255,255,255,.95);
|
||||
}
|
||||
|
||||
.memberdecls {
|
||||
background: #7cb342;
|
||||
border-top: 1px solid #7cb342;
|
||||
}
|
||||
|
||||
.memberdecls .heading h2 {
|
||||
border-bottom: none;
|
||||
color: #fff;
|
||||
font-size: 110%;
|
||||
font-weight: bold;
|
||||
margin: 0 0 0 6px;
|
||||
}
|
||||
|
||||
.memberdecls tr:not(.heading) td {
|
||||
background-color: rgba(255,255,255,.95);
|
||||
}
|
||||
|
||||
h1, h2, h2.groupheader, h3, h4, h5, h6 {
|
||||
color: #212121;
|
||||
}
|
||||
|
||||
h1 {
|
||||
border-bottom: 1px solid #ebebeb;
|
||||
font: 400 28px/32px Roboto,sans-serif;
|
||||
letter-spacing: -.01em;
|
||||
margin: 40px 0 20px;
|
||||
padding-bottom: 3px;
|
||||
}
|
||||
|
||||
h2, h2.groupheader {
|
||||
border-bottom: 1px solid #ebebeb;
|
||||
font: 400 23px/32px Roboto,sans-serif;
|
||||
letter-spacing: -.01em;
|
||||
margin: 40px 0 20px;
|
||||
padding-bottom: 3px;
|
||||
}
|
||||
|
||||
h3 {
|
||||
font: 500 20px/32px Roboto,sans-serif;
|
||||
margin: 32px 0 16px;
|
||||
}
|
||||
|
||||
h4 {
|
||||
font: 500 18px/32px Roboto,sans-serif;
|
||||
margin: 32px 0 16px;
|
||||
}
|
||||
|
||||
ol,
|
||||
ul {
|
||||
margin: 0;
|
||||
padding-left: 40px;
|
||||
}
|
||||
|
||||
ol {
|
||||
list-style: decimal outside;
|
||||
}
|
||||
|
||||
ol ol {
|
||||
list-style-type: lower-alpha;
|
||||
}
|
||||
|
||||
ol ol ol {
|
||||
list-style-type: lower-roman;
|
||||
}
|
||||
|
||||
ul {
|
||||
list-style: disc outside;
|
||||
}
|
||||
|
||||
li,
|
||||
li p {
|
||||
margin: 8px 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
div.summary
|
||||
{
|
||||
float: none;
|
||||
font-size: 8pt;
|
||||
padding-left: 5px;
|
||||
width: calc(100% - 10px);
|
||||
text-align: left;
|
||||
display: block;
|
||||
}
|
||||
|
||||
div.ingroups {
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
div.fragment {
|
||||
border: 1px solid #ddd;
|
||||
color: #455a64;
|
||||
font: 14px/20px Roboto Mono, monospace;
|
||||
padding: 8px;
|
||||
}
|
||||
|
||||
div.line {
|
||||
line-height: 1.5;
|
||||
font-size: inherit;
|
||||
}
|
||||
|
||||
code, pre {
|
||||
color: #455a64;
|
||||
background: #f7f7f7;
|
||||
font: 400 100%/1 Roboto Mono,monospace;
|
||||
padding: 1px 4px;
|
||||
}
|
||||
|
||||
span.preprocessor, span.comment {
|
||||
color: #0b8043;
|
||||
}
|
||||
|
||||
span.keywordtype {
|
||||
color: #0097a7;
|
||||
}
|
||||
|
||||
.paramname {
|
||||
color: #ef6c00;
|
||||
}
|
||||
|
||||
.memTemplParams {
|
||||
color: #ef6c00;
|
||||
}
|
||||
|
||||
span.mlabel {
|
||||
background: rgba(255,255,255,.25);
|
||||
border: none;
|
||||
}
|
||||
|
||||
blockquote {
|
||||
border: 1px solid #ddd;
|
||||
}
|
||||
BIN
docs/images/fpl_logo_small.png
Normal file
BIN
docs/images/fpl_logo_small.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 5.0 KiB |
BIN
docs/images/ftv2mnode.png
Normal file
BIN
docs/images/ftv2mnode.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 1.0 KiB |
BIN
docs/images/ftv2pnode.png
Normal file
BIN
docs/images/ftv2pnode.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 1.0 KiB |
@@ -2,7 +2,14 @@
|
||||
|
||||
Comparing against other serialization solutions, running on Windows 7
|
||||
64bit. We use the LITE runtime for Protocol Buffers (less code / lower
|
||||
overhead), and Rapid JSON, one of the fastest C++ JSON parsers around.
|
||||
overhead), Rapid JSON (one of the fastest C++ JSON parsers around),
|
||||
and pugixml, also one of the fastest XML parsers.
|
||||
|
||||
We also compare against code that doesn't use a serialization library
|
||||
at all (the column "Raw structs"), which is what you get if you write
|
||||
hardcoded code that just writes structs. This is the fastest possible,
|
||||
but of course is not cross platform nor has any kind of forwards /
|
||||
backwards compatibility.
|
||||
|
||||
We compare against Flatbuffers with the binary wire format (as
|
||||
intended), and also with JSON as the wire format with the optional JSON
|
||||
@@ -13,17 +20,17 @@ The benchmark object is a set of about 10 objects containing an array, 4
|
||||
strings, and a large variety of int/float scalar values of all sizes,
|
||||
meant to be representative of game data, e.g. a scene format.
|
||||
|
||||
| | FlatBuffers (binary) | Protocol Buffers LITE | Rapid JSON | FlatBuffers (JSON) |
|
||||
|--------------------------------------------------------|-----------------------|-----------------------|-----------------------|-----------------------|
|
||||
| Decode + Traverse + Dealloc (1 million times, seconds) | 0.08 | 305 | 583 | 105 |
|
||||
| Decode / Traverse / Dealloc (breakdown) | 0 / 0.08 / 0 | 220 / 3.6 / 81 | 294 / 0.9 / 287 | 70 / 0.08 / 35 |
|
||||
| Encode (1 million times, seconds) | 3.2 | 185 | 650 | 169 |
|
||||
| Wire format size (normal / zlib, bytes) | 344 / 220 | 228 / 174 | 1475 / 322 | 1029 / 298 |
|
||||
| Memory needed to store decoded wire (bytes / blocks) | 0 / 0 | 760 / 20 | 65689 / 40 | 328 / 1 |
|
||||
| Transient memory allocated during decode (KB) | 0 | 1 | 131 | 4 |
|
||||
| Generated source code size (KB) | 4 | 61 | 0 | 4 |
|
||||
| Field access in handwritten traversal code | accessors | accessors | manual error checking | accessors |
|
||||
| Library source code (KB) | 15 | some subset of 3800 | 87 | 43 |
|
||||
| | FlatBuffers (binary) | Protocol Buffers LITE | Rapid JSON | FlatBuffers (JSON) | pugixml | Raw structs |
|
||||
|--------------------------------------------------------|-----------------------|-----------------------|-----------------------|-----------------------| ----------------------| ----------------------|
|
||||
| Decode + Traverse + Dealloc (1 million times, seconds) | 0.08 | 302 | 583 | 105 | 196 | 0.02 |
|
||||
| Decode / Traverse / Dealloc (breakdown) | 0 / 0.08 / 0 | 220 / 0.15 / 81 | 294 / 0.9 / 287 | 70 / 0.08 / 35 | 41 / 3.9 / 150 | 0 / 0.02 / 0 |
|
||||
| Encode (1 million times, seconds) | 3.2 | 185 | 650 | 169 | 273 | 0.15 |
|
||||
| Wire format size (normal / zlib, bytes) | 344 / 220 | 228 / 174 | 1475 / 322 | 1029 / 298 | 1137 / 341 | 312 / 187 |
|
||||
| Memory needed to store decoded wire (bytes / blocks) | 0 / 0 | 760 / 20 | 65689 / 4 | 328 / 1 | 34194 / 3 | 0 / 0 |
|
||||
| Transient memory allocated during decode (KB) | 0 | 1 | 131 | 4 | 34 | 0 |
|
||||
| Generated source code size (KB) | 4 | 61 | 0 | 4 | 0 | 0 |
|
||||
| Field access in handwritten traversal code | typed accessors | typed accessors | manual error checking | typed accessors | manual error checking | typed but no safety |
|
||||
| Library source code (KB) | 15 | some subset of 3800 | 87 | 43 | 327 | 0 |
|
||||
|
||||
### Some other serialization systems we compared against but did not benchmark (yet), in rough order of applicability:
|
||||
|
||||
@@ -32,12 +39,10 @@ meant to be representative of game data, e.g. a scene format.
|
||||
optional fields to allow deprecating fields or serializing with missing
|
||||
fields for which defaults exist).
|
||||
It currently also isn't fully cross-platform portable (lack of VS support).
|
||||
- msgpack: has very minimal forwards/backwards compatability support when used
|
||||
- msgpack: has very minimal forwards/backwards compatibility support when used
|
||||
with the typed C++ interface. Also lacks VS2010 support.
|
||||
- Thrift: very similar to Protocol Buffers, but appears to be less efficient,
|
||||
and have more dependencies.
|
||||
- XML: typically even slower than JSON, but has the advantage that it can be
|
||||
parsed with a schema to reduce error-checking boilerplate code.
|
||||
- YAML: a superset of JSON and otherwise very similar. Used by e.g. Unity.
|
||||
- C# comes with built-in serialization functionality, as used by Unity also.
|
||||
Being tied to the language, and having no automatic versioning support
|
||||
|
||||
@@ -18,9 +18,11 @@ Note that to use clang instead of gcc, you may need to set up your environment
|
||||
variables, e.g.
|
||||
`CC=/usr/bin/clang CXX=/usr/bin/clang++ cmake -G "Unix Makefiles"`.
|
||||
|
||||
Optionally, run the `flattests` executable.
|
||||
to ensure everything is working correctly on your system. If this fails,
|
||||
please contact us!
|
||||
Optionally, run the `flattests` executable to ensure everything is working
|
||||
correctly on your system. If this fails, please contact us!
|
||||
|
||||
Note that you MUST be in the root of the FlatBuffers distribution when you
|
||||
run 'flattests' (and the samples), or it will fail to load its files.
|
||||
|
||||
Building should also produce two sample executables, `sample_binary` and
|
||||
`sample_text`, see the corresponding `.cpp` file in the samples directory.
|
||||
|
||||
@@ -2,21 +2,83 @@
|
||||
|
||||
Usage:
|
||||
|
||||
flatc [ -c ] [ -j ] [ -b ] [ -t ] file1 file2 ..
|
||||
flatc [ -c ] [ -j ] [ -b ] [ -t ] [ -o PATH ] [ -I PATH ] [ -S ] FILES...
|
||||
[ -- FILES...]
|
||||
|
||||
The files are read and parsed in order, and can contain either schemas
|
||||
or data (see below). Later files can make use of definitions in earlier
|
||||
files. Depending on the flags passed, additional files may
|
||||
files.
|
||||
|
||||
`--` indicates that the following files are binary files in
|
||||
FlatBuffer format conforming to the schema(s) indicated before it.
|
||||
Incompatible binary files currently will give unpredictable results (!)
|
||||
|
||||
Depending on the flags passed, additional files may
|
||||
be generated for each file processed:
|
||||
|
||||
- `-c` : Generate a C++ header for all definitions in this file (as
|
||||
`filename_generated.h`). Skips data.
|
||||
`filename_generated.h`). Skipped for data.
|
||||
|
||||
- `-j` : Generate Java classes.
|
||||
- `-j` : Generate Java classes. Skipped for data.
|
||||
|
||||
- `-n` : Generate C# classes. Skipped for data.
|
||||
|
||||
- `-g` : Generate Go classes. Skipped for data.
|
||||
|
||||
- `-b` : If data is contained in this file, generate a
|
||||
`filename_wire.bin` containing the binary flatbuffer.
|
||||
`filename.bin` containing the binary flatbuffer.
|
||||
|
||||
- `-t` : If data is contained in this file, generate a
|
||||
`filename_wire.txt` (for debugging).
|
||||
`filename.json` representing the data in the flatbuffer.
|
||||
|
||||
- `-o PATH` : Output all generated files to PATH (either absolute, or
|
||||
relative to the current directory). If omitted, PATH will be the
|
||||
current directory. PATH should end in your systems path separator,
|
||||
e.g. `/` or `\`.
|
||||
|
||||
- `-I PATH` : when encountering `include` statements, attempt to load the
|
||||
files from this path. Paths will be tried in the order given, and if all
|
||||
fail (or none are specified) it will try to load relative to the path of
|
||||
the schema file being parsed.
|
||||
|
||||
- `-M` : Print make rules for generated files.
|
||||
|
||||
- `--strict-json` : Require & generate strict JSON (field names are enclosed
|
||||
in quotes, no trailing commas in tables/vectors). By default, no quotes are
|
||||
required/generated, and trailing commas are allowed.
|
||||
|
||||
- `--defaults-json` : Output fields whose value is equal to the default value
|
||||
when writing JSON text.
|
||||
|
||||
- `--no-prefix` : Don't prefix enum values in generated C++ by their enum
|
||||
type.
|
||||
|
||||
- `--scoped-enums` : Use C++11 style scoped and strongly typed enums in
|
||||
generated C++. This also implies `--no-prefix`.
|
||||
|
||||
- `--gen-includes` : (deprecated), this is the default behavior.
|
||||
If the original behavior is required (no include
|
||||
statements) use `--no-includes.`
|
||||
|
||||
- `--no-includes` : Don't generate include statements for included schemas the
|
||||
generated file depends on (C++).
|
||||
|
||||
- `--gen-mutable` : Generate additional non-const accessors for mutating
|
||||
FlatBuffers in-place.
|
||||
|
||||
- `--gen-onefile` : Generate single output file (useful for C#)
|
||||
|
||||
- `--raw-binary` : Allow binaries without a file_indentifier to be read.
|
||||
This may crash flatc given a mismatched schema.
|
||||
|
||||
- `--proto`: Expect input files to be .proto files (protocol buffers).
|
||||
Output the corresponding .fbs file.
|
||||
Currently supports: `package`, `message`, `enum`, nested declarations,
|
||||
`import` (use `-I` for paths), `extend`, `oneof`, `group`.
|
||||
Does not support, but will skip without error: `option`, `service`,
|
||||
`extensions`, and most everything else.
|
||||
|
||||
- `--schema`: Serialize schemas instead of JSON (use with -b). This will
|
||||
output a binary version of the specified schema that itself corresponds
|
||||
to the reflection/reflection.fbs schema. Loading this binary file is the
|
||||
basis for reflection functionality.
|
||||
|
||||
@@ -12,17 +12,21 @@ your program by including the header. As noted, this header relies on
|
||||
To start creating a buffer, create an instance of `FlatBufferBuilder`
|
||||
which will contain the buffer as it grows:
|
||||
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
|
||||
FlatBufferBuilder fbb;
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Before we serialize a Monster, we need to first serialize any objects
|
||||
that are contained there-in, i.e. we serialize the data tree using
|
||||
depth first, pre-order traversal. This is generally easy to do on
|
||||
any tree structures. For example:
|
||||
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
|
||||
auto name = fbb.CreateString("MyMonster");
|
||||
|
||||
unsigned char inv[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
|
||||
auto inventory = fbb.CreateVector(inv, 10);
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
`CreateString` and `CreateVector` serialize these two built-in
|
||||
datatypes, and return offsets into the serialized data indicating where
|
||||
@@ -38,7 +42,14 @@ correct type below. To create a vector of struct objects (which will
|
||||
be stored as contiguous memory in the buffer, use `CreateVectorOfStructs`
|
||||
instead.
|
||||
|
||||
To create a vector of nested objects (e.g. tables, strings or other vectors)
|
||||
collect their offsets in a temporary array/vector, then call `CreateVector`
|
||||
on that (see e.g. the array of strings example in `test.cpp`
|
||||
`CreateFlatBufferTest`).
|
||||
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
|
||||
Vec3 vec(1, 2, 3);
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
`Vec3` is the first example of code from our generated
|
||||
header. Structs (unlike tables) translate to simple structs in C++, so
|
||||
@@ -47,7 +58,9 @@ we can construct them in a familiar way.
|
||||
We have now serialized the non-scalar components of of the monster
|
||||
example, so we could create the monster something like this:
|
||||
|
||||
auto mloc = CreateMonster(fbb, &vec, 150, 80, name, inventory, Color_Red, Offset<void>(0), Any_NONE);
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
|
||||
auto mloc = CreateMonster(fbb, &vec, 150, 80, name, inventory, Color_Red, 0, Any_NONE);
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Note that we're passing `150` for the `mana` field, which happens to be the
|
||||
default value: this means the field will not actually be written to the buffer,
|
||||
@@ -58,7 +71,10 @@ since they won't bloat up the buffer sizes if they're not actually used.
|
||||
|
||||
We do something similarly for the union field `test` by specifying a `0` offset
|
||||
and the `NONE` enum value (part of every union) to indicate we don't actually
|
||||
want to write this field.
|
||||
want to write this field. You can use `0` also as a default for other
|
||||
non-scalar types, such as strings, vectors and tables. To pass an actual
|
||||
table, pass a preconstructed table as `mytable.Union()` that corresponds to
|
||||
union enum you're passing.
|
||||
|
||||
Tables (like `Monster`) give you full flexibility on what fields you write
|
||||
(unlike `Vec3`, which always has all fields set because it is a `struct`).
|
||||
@@ -66,12 +82,14 @@ If you want even more control over this (i.e. skip fields even when they are
|
||||
not default), instead of the convenient `CreateMonster` call we can also
|
||||
build the object field-by-field manually:
|
||||
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
|
||||
MonsterBuilder mb(fbb);
|
||||
mb.add_pos(&vec);
|
||||
mb.add_hp(80);
|
||||
mb.add_name(name);
|
||||
mb.add_inventory(inventory);
|
||||
auto mloc = mb.Finish();
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
We start with a temporary helper class `MonsterBuilder` (which is
|
||||
defined in our generated code also), then call the various `add_`
|
||||
@@ -87,13 +105,21 @@ Regardless of whether you used `CreateMonster` or `MonsterBuilder`, you
|
||||
now have an offset to the root of your data, and you can finish the
|
||||
buffer using:
|
||||
|
||||
fbb.Finish(mloc);
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
|
||||
FinishMonsterBuffer(fbb, mloc);
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
The buffer is now ready to be stored somewhere, sent over the network,
|
||||
be compressed, or whatever you'd like to do with it. You can access the
|
||||
start of the buffer with `fbb.GetBufferPointer()`, and it's size from
|
||||
`fbb.GetSize()`.
|
||||
|
||||
Calling code may take ownership of the buffer with `fbb.ReleaseBufferPointer()`.
|
||||
Should you do it, the `FlatBufferBuilder` will be in an invalid state,
|
||||
and *must* be cleared before it can be used again.
|
||||
However, it also means you are able to destroy the builder while keeping
|
||||
the buffer in your application.
|
||||
|
||||
`samples/sample_binary.cpp` is a complete code sample similar to
|
||||
the code above, that also includes the reading code below.
|
||||
|
||||
@@ -102,33 +128,137 @@ the code above, that also includes the reading code below.
|
||||
If you've received a buffer from somewhere (disk, network, etc.) you can
|
||||
directly start traversing it using:
|
||||
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
|
||||
auto monster = GetMonster(buffer_pointer);
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
`monster` is of type `Monster *`, and points to somewhere inside your
|
||||
buffer. If you look in your generated header, you'll see it has
|
||||
`monster` is of type `Monster *`, and points to somewhere *inside* your
|
||||
buffer (root object pointers are not the same as `buffer_pointer` !).
|
||||
If you look in your generated header, you'll see it has
|
||||
convenient accessors for all fields, e.g.
|
||||
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
|
||||
assert(monster->hp() == 80);
|
||||
assert(monster->mana() == 150); // default
|
||||
assert(strcmp(monster->name()->c_str(), "MyMonster") == 0);
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
These should all be true. Note that we never stored a `mana` value, so
|
||||
it will return the default.
|
||||
|
||||
To access sub-objects, in this case the `Vec3`:
|
||||
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
|
||||
auto pos = monster->pos();
|
||||
assert(pos);
|
||||
assert(pos->z() == 3);
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
If we had not set the `pos` field during serialization, it would be
|
||||
`NULL`.
|
||||
|
||||
Similarly, we can access elements of the inventory array:
|
||||
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
|
||||
auto inv = monster->inventory();
|
||||
assert(inv);
|
||||
assert(inv->Get(9) == 9);
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
### Mutating FlatBuffers
|
||||
|
||||
As you saw above, typically once you have created a FlatBuffer, it is
|
||||
read-only from that moment on. There are however cases where you have just
|
||||
received a FlatBuffer, and you'd like to modify something about it before
|
||||
sending it on to another recipient. With the above functionality, you'd have
|
||||
to generate an entirely new FlatBuffer, while tracking what you modify in your
|
||||
own data structures. This is inconvenient.
|
||||
|
||||
For this reason FlatBuffers can also be mutated in-place. While this is great
|
||||
for making small fixes to an existing buffer, you generally want to create
|
||||
buffers from scratch whenever possible, since it is much more efficient and
|
||||
the API is much more general purpose.
|
||||
|
||||
To get non-const accessors, invoke `flatc` with `--gen-mutable`.
|
||||
|
||||
Similar to the reading API above, you now can:
|
||||
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
|
||||
auto monster = GetMutableMonster(buffer_pointer); // non-const
|
||||
monster->mutate_hp(10); // Set table field.
|
||||
monster->mutable_pos()->mutate_z(4); // Set struct field.
|
||||
monster->mutable_inventory()->Mutate(0, 1); // Set vector element.
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
We use the somewhat verbose term `mutate` instead of `set` to indicate that
|
||||
this is a special use case, not to be confused with the default way of
|
||||
constructing FlatBuffer data.
|
||||
|
||||
After the above mutations, you can send on the FlatBuffer to a new recipient
|
||||
without any further work!
|
||||
|
||||
Note that any `mutate_` functions on tables return a bool, which is false
|
||||
if the field we're trying to set isn't present in the buffer. Fields are not
|
||||
present if they weren't set, or even if they happen to be equal to the
|
||||
default value. For example, in the creation code above we set the `mana` field
|
||||
to `150`, which is the default value, so it was never stored in the buffer.
|
||||
Trying to call mutate_mana() on such data will return false, and the value won't
|
||||
actually be modified!
|
||||
|
||||
One way to solve this is to call `ForceDefaults()` on a
|
||||
`FlatBufferBuilder` to force all fields you set to actually be written. This
|
||||
of course increases the size of the buffer somewhat, but this may be
|
||||
acceptable for a mutable buffer.
|
||||
|
||||
Alternatively, you can use the more powerful reflection functionality:
|
||||
|
||||
### Reflection (& Resizing)
|
||||
|
||||
If the above ways of accessing a buffer are still too static for you, there is
|
||||
experimental support for reflection in FlatBuffers, allowing you to read and
|
||||
write data even if you don't know the exact format of a buffer, and even allows
|
||||
you to change sizes of strings and vectors in-place.
|
||||
|
||||
The way this works is very elegant, there is actually a FlatBuffer schema that
|
||||
describes schemas (!) which you can find in `reflection/reflection.fbs`.
|
||||
The compiler `flatc` can write out any schemas it has just parsed as a binary
|
||||
FlatBuffer, corresponding to this meta-schema.
|
||||
|
||||
Loading in one of these binary schemas at runtime allows you traverse any
|
||||
FlatBuffer data that corresponds to it without knowing the exact format. You
|
||||
can query what fields are present, and then read/write them after.
|
||||
|
||||
For convenient field manipulation, you can include the header
|
||||
`flatbuffers/reflection.h` which includes both the generated code from the meta
|
||||
schema, as well as a lot of helper functions.
|
||||
|
||||
And example of usage for the moment you can find in `test.cpp/ReflectionTest()`.
|
||||
|
||||
### Storing maps / dictionaries in a FlatBuffer
|
||||
|
||||
FlatBuffers doesn't support maps natively, but there is support to
|
||||
emulate their behavior with vectors and binary search, which means you
|
||||
can have fast lookups directly from a FlatBuffer without having to unpack
|
||||
your data into a `std::map` or similar.
|
||||
|
||||
To use it:
|
||||
- Designate one of the fields in a table as they "key" field. You do this
|
||||
by setting the `key` attribute on this field, e.g.
|
||||
`name:string (key)`.
|
||||
You may only have one key field, and it must be of string or scalar type.
|
||||
- Write out tables of this type as usual, collect their offsets in an
|
||||
array or vector.
|
||||
- Instead of `CreateVector`, call `CreateVectorOfSortedTables`,
|
||||
which will first sort all offsets such that the tables they refer to
|
||||
are sorted by the key field, then serialize it.
|
||||
- Now when you're accessing the FlatBuffer, you can use `Vector::LookupByKey`
|
||||
instead of just `Vector::Get` to access elements of the vector, e.g.:
|
||||
`myvector->LookupByKey("Fred")`, which returns a pointer to the
|
||||
corresponding table type, or `nullptr` if not found.
|
||||
`LookupByKey` performs a binary search, so should have a similar speed to
|
||||
`std::map`, though may be faster because of better caching. `LookupByKey`
|
||||
only works if the vector has been sorted, it will likely not find elements
|
||||
if it hasn't been sorted.
|
||||
|
||||
### Direct memory access
|
||||
|
||||
@@ -155,6 +285,47 @@ machines, so only use tricks like this if you can guarantee you're not
|
||||
shipping on a big endian machine (an `assert(FLATBUFFERS_LITTLEENDIAN)`
|
||||
would be wise).
|
||||
|
||||
### Access of untrusted buffers
|
||||
|
||||
The generated accessor functions access fields over offsets, which is
|
||||
very quick. These offsets are not verified at run-time, so a malformed
|
||||
buffer could cause a program to crash by accessing random memory.
|
||||
|
||||
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
|
||||
data from the network that can potentially have been modified by an
|
||||
attacker, this is undesirable.
|
||||
|
||||
For this reason, you can optionally use a buffer verifier before you
|
||||
access the data. This verifier will check all offsets, all sizes of
|
||||
fields, and null termination of strings to ensure that when a buffer
|
||||
is accessed, all reads will end up inside the buffer.
|
||||
|
||||
Each root type will have a verification function generated for it,
|
||||
e.g. for `Monster`, you can call:
|
||||
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
|
||||
bool ok = VerifyMonsterBuffer(Verifier(buf, len));
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
if `ok` is true, the buffer is safe to read.
|
||||
|
||||
Besides untrusted data, this function may be useful to call in debug
|
||||
mode, as extra insurance against data being corrupted somewhere along
|
||||
the way.
|
||||
|
||||
While verifying a buffer isn't "free", it is typically faster than
|
||||
a full traversal (since any scalar data is not actually touched),
|
||||
and since it may cause the buffer to be brought into cache before
|
||||
reading, the actual overhead may be even lower than expected.
|
||||
|
||||
In specialized cases where a denial of service attack is possible,
|
||||
the verifier has two additional constructor arguments that allow
|
||||
you to limit the nesting depth and total amount of tables the
|
||||
verifier may encounter before declaring the buffer malformed. The default is
|
||||
`Verifier(buf, len, 64 /* max depth */, 1000000, /* max tables */)` which
|
||||
should be sufficient for most uses.
|
||||
|
||||
## Text & schema parsing
|
||||
|
||||
Using binary buffers with the generated header provides a super low
|
||||
@@ -166,6 +337,9 @@ Another reason might be that you already have a lot of data in JSON
|
||||
format, or a tool that generates JSON, and if you can write a schema for
|
||||
it, this will provide you an easy way to use that data directly.
|
||||
|
||||
(see the schema documentation for some specifics on the JSON format
|
||||
accepted).
|
||||
|
||||
There are two ways to use text formats:
|
||||
|
||||
### Using the compiler as a conversion tool
|
||||
@@ -196,11 +370,15 @@ Load text (either a schema or json) into an in-memory buffer (there is a
|
||||
convenient `LoadFile()` utility function in `flatbuffers/util.h` if you
|
||||
wish). Construct a parser:
|
||||
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
|
||||
flatbuffers::Parser parser;
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Now you can parse any number of text files in sequence:
|
||||
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
|
||||
parser.Parse(text_file.c_str());
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
This works similarly to how the command-line compiler works: a sequence
|
||||
of files parsed by the same `Parser` object allow later files to
|
||||
@@ -208,6 +386,10 @@ reference definitions in earlier files. Typically this means you first
|
||||
load a schema file (which populates `Parser` with definitions), followed
|
||||
by one or more JSON files.
|
||||
|
||||
As optional argument to `Parse`, you may specify a null-terminated list of
|
||||
include paths. If not specified, any include statements try to resolve from
|
||||
the current directory.
|
||||
|
||||
If there were any parsing errors, `Parse` will return `false`, and
|
||||
`Parser::err` contains a human readable error string with a line number
|
||||
etc, which you should present to the creator of that file.
|
||||
@@ -220,7 +402,14 @@ file, that you can access as described above.
|
||||
|
||||
### Threading
|
||||
|
||||
None of the code is thread-safe, by design. That said, since currently a
|
||||
FlatBuffer is read-only and entirely `const`, reading by multiple threads
|
||||
is possible.
|
||||
Reading a FlatBuffer does not touch any memory outside the original buffer,
|
||||
and is entirely read-only (all const), so is safe to access from multiple
|
||||
threads even without synchronisation primitives.
|
||||
|
||||
Creating a FlatBuffer is not thread safe. All state related to building
|
||||
a FlatBuffer is contained in a FlatBufferBuilder instance, and no memory
|
||||
outside of it is touched. To make this thread safe, either do not
|
||||
share instances of FlatBufferBuilder between threads (recommended), or
|
||||
manually wrap it in synchronisation primites. There's no automatic way to
|
||||
accomplish this, by design, as we feel multithreaded construction
|
||||
of a single buffer will be rare, and synchronisation overhead would be costly.
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
# FlatBuffers
|
||||
|
||||
FlatBuffers is an efficient cross platform serialization library in for C++ and
|
||||
Java. It was created at Google specifically for game development and other
|
||||
performance-critical applications.
|
||||
FlatBuffers is an efficient cross platform serialization library for C++,
|
||||
with support for Java, C# and Go. It was created at Google specifically for game
|
||||
development and other performance-critical applications.
|
||||
|
||||
It is available as open source under the Apache license, v2 (see LICENSE.txt).
|
||||
It is available as Open Source on [GitHub](http://github.com/google/flatbuffers)
|
||||
under the Apache license, v2 (see LICENSE.txt).
|
||||
|
||||
## Why use FlatBuffers?
|
||||
|
||||
@@ -46,10 +47,10 @@ It is available as open source under the Apache license, v2 (see LICENSE.txt).
|
||||
needed (faster and more memory efficient than other JSON
|
||||
parsers).
|
||||
|
||||
Java code supports object-reuse.
|
||||
Java and Go code supports object-reuse.
|
||||
|
||||
- **Cross platform C++11/Java code with no dependencies** - will work with
|
||||
any recent gcc/clang and VS2010. Comes with build files for the tests &
|
||||
- **Cross platform C++11/Java/C#/Go code with no dependencies** - will work
|
||||
with any recent gcc/clang and VS2010. Comes with build files for the tests &
|
||||
samples (Android .mk files, and cmake for all other platforms).
|
||||
|
||||
### Why not use Protocol Buffers, or .. ?
|
||||
@@ -75,6 +76,17 @@ little to no information ahead of time about what data needs to be stored.
|
||||
Read more about the "why" of FlatBuffers in the
|
||||
[white paper](md__white_paper.html).
|
||||
|
||||
### Who uses FlatBuffers?
|
||||
- [Cocos2d-x](http://www.cocos2d-x.org/), the #1 open source mobile game
|
||||
engine, uses it to serialize all their
|
||||
[game data](http://www.cocos2d-x.org/reference/native-cpp/V3.5/d7/d2d/namespaceflatbuffers.html).
|
||||
- [Facebook](http://facebook.com/) uses it for client-server communication in
|
||||
their Android app. They have a nice
|
||||
[article](https://code.facebook.com/posts/872547912839369/improving-facebook-s-performance-on-android-with-flatbuffers/)
|
||||
explaining how it speeds up loading their posts.
|
||||
- [Fun Propulsion Labs](https://developers.google.com/games/#Tools)
|
||||
at Google uses it extensively in all their libraries and games.
|
||||
|
||||
## Usage in brief
|
||||
|
||||
This section is a quick rundown of how to use this system. Subsequent
|
||||
@@ -87,10 +99,10 @@ sections provide a more in-depth usage guide.
|
||||
Fields are optional and have defaults, so they don't need to be
|
||||
present for every object instance.
|
||||
|
||||
- Use `flatc` (the FlatBuffer compiler) to generate a C++ header (or Java
|
||||
classes) with helper classes to access and construct serialized data. This
|
||||
header (say `mydata_generated.h`) only depends on `flatbuffers.h`, which
|
||||
defines the core functionality.
|
||||
- Use `flatc` (the FlatBuffer compiler) to generate a C++ header (or
|
||||
Java/C#/Go/Python.. classes) with helper classes to access and construct
|
||||
serialized data. This header (say `mydata_generated.h`) only depends on
|
||||
`flatbuffers.h`, which defines the core functionality.
|
||||
|
||||
- Use the `FlatBufferBuilder` class to construct a flat binary buffer.
|
||||
The generated functions allow you to add objects to this
|
||||
@@ -110,8 +122,11 @@ sections provide a more in-depth usage guide.
|
||||
- How to [write a schema](md__schemas.html).
|
||||
- How to [use the generated C++ code](md__cpp_usage.html) in your own
|
||||
programs.
|
||||
- How to [use the generated Java code](md__java_usage.html) in your own
|
||||
- How to [use the generated Java/C# code](md__java_usage.html) in your own
|
||||
programs.
|
||||
- How to [use the generated Go code](md__go_usage.html) in your own
|
||||
programs.
|
||||
- [Support matrix](md__support.html) for platforms/languages/features.
|
||||
- Some [benchmarks](md__benchmarks.html) showing the advantage of using
|
||||
FlatBuffers.
|
||||
- A [white paper](md__white_paper.html) explaining the "why" of FlatBuffers.
|
||||
@@ -120,7 +135,15 @@ sections provide a more in-depth usage guide.
|
||||
|
||||
## Online resources
|
||||
|
||||
- [github repository](http://github.com/google/flatbuffers)
|
||||
- [landing page](http://google.github.io/flatbuffers)
|
||||
- [GitHub repository](http://github.com/google/flatbuffers)
|
||||
- [Landing page](http://google.github.io/flatbuffers)
|
||||
- [FlatBuffers Google Group](http://group.google.com/group/flatbuffers)
|
||||
- [FlatBuffers Issues Tracker](http://github.com/google/flatbuffers/issues)
|
||||
- Videos:
|
||||
- Colt's [DevByte](https://www.youtube.com/watch?v=iQTxMkSJ1dQ).
|
||||
- GDC 2015 [Lightning Talk](https://www.youtube.com/watch?v=olmL1fUnQAQ).
|
||||
- FlatBuffers for [Go](https://www.youtube.com/watch?v=-BPVId_lA5w).
|
||||
- Evolution of FlatBuffers
|
||||
[visualization](https://www.youtube.com/watch?v=a0QE0xS8rKM).
|
||||
- Useful documentation created by others:
|
||||
- [Using FlatBuffers in Unity](http://exiin.com/blog/flatbuffers-for-unity-sample-code/)
|
||||
|
||||
122
docs/source/GoUsage.md
Normal file
122
docs/source/GoUsage.md
Normal file
@@ -0,0 +1,122 @@
|
||||
# Use in Go
|
||||
|
||||
There's experimental support for reading FlatBuffers in Go. Generate code
|
||||
for Go with the `-g` option to `flatc`.
|
||||
|
||||
See `go_test.go` for an example. You import the generated code, read a
|
||||
FlatBuffer binary file into a `[]byte`, which you pass to the
|
||||
`GetRootAsMonster` function:
|
||||
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.go}
|
||||
import (
|
||||
example "MyGame/Example"
|
||||
flatbuffers "github.com/google/flatbuffers/go"
|
||||
|
||||
io/ioutil
|
||||
)
|
||||
|
||||
buf, err := ioutil.ReadFile("monster.dat")
|
||||
// handle err
|
||||
monster := example.GetRootAsMonster(buf, 0)
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Now you can access values like this:
|
||||
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.go}
|
||||
hp := monster.Hp()
|
||||
pos := monster.Pos(nil)
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Note that whenever you access a new object like in the `Pos` example above,
|
||||
a new temporary accessor object gets created. If your code is very performance
|
||||
sensitive (you iterate through a lot of objects), you can replace nil with a
|
||||
pointer to a `Vec3` object you've already created. This allows
|
||||
you to reuse it across many calls and reduce the amount of object allocation
|
||||
(and thus garbage collection) your program does.
|
||||
|
||||
To access vectors you pass an extra index to the
|
||||
vector field accessor. Then a second method with the same name suffixed
|
||||
by `Length` let's you know the number of elements you can access:
|
||||
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.go}
|
||||
for i := 0; i < monster.InventoryLength(); i++ {
|
||||
monster.Inventory(i) // do something here
|
||||
}
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
You can also construct these buffers in Go using the functions found in the
|
||||
generated code, and the FlatBufferBuilder class:
|
||||
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.go}
|
||||
builder := flatbuffers.NewBuilder(0)
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Create strings:
|
||||
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.go}
|
||||
str := builder.CreateString("MyMonster")
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Create a table with a struct contained therein:
|
||||
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.go}
|
||||
example.MonsterStart(builder)
|
||||
example.MonsterAddPos(builder, example.CreateVec3(builder, 1.0, 2.0, 3.0, 3.0, 4, 5, 6))
|
||||
example.MonsterAddHp(builder, 80)
|
||||
example.MonsterAddName(builder, str)
|
||||
example.MonsterAddInventory(builder, inv)
|
||||
example.MonsterAddTest_Type(builder, 1)
|
||||
example.MonsterAddTest(builder, mon2)
|
||||
example.MonsterAddTest4(builder, test4s)
|
||||
mon := example.MonsterEnd(builder)
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Unlike C++, Go does not support table creation functions like 'createMonster()'.
|
||||
This is to create the buffer without
|
||||
using temporary object allocation (since the `Vec3` is an inline component of
|
||||
`Monster`, it has to be created right where it is added, whereas the name and
|
||||
the inventory are not inline, and **must** be created outside of the table
|
||||
creation sequence).
|
||||
Structs do have convenient methods that allow you to construct them in one call.
|
||||
These also have arguments for nested structs, e.g. if a struct has a field `a`
|
||||
and a nested struct field `b` (which has fields `c` and `d`), then the arguments
|
||||
will be `a`, `c` and `d`.
|
||||
|
||||
Vectors also use this start/end pattern to allow vectors of both scalar types
|
||||
and structs:
|
||||
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.go}
|
||||
example.MonsterStartInventoryVector(builder, 5)
|
||||
for i := 4; i >= 0; i-- {
|
||||
builder.PrependByte(byte(i))
|
||||
}
|
||||
inv := builder.EndVector(5)
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
The generated method 'StartInventoryVector' is provided as a convenience
|
||||
function which calls 'StartVector' with the correct element size of the vector
|
||||
type which in this case is 'ubyte' or 1 byte per vector element.
|
||||
You pass the number of elements you want to write.
|
||||
You write the elements backwards since the buffer
|
||||
is being constructed back to front. Use the correct `Prepend` call for the type,
|
||||
or `PrependUOffsetT` for offsets. You then pass `inv` to the corresponding
|
||||
`Add` call when you construct the table containing it afterwards.
|
||||
|
||||
There are `Prepend` functions for all the scalar types. You use
|
||||
`PrependUOffset` for any previously constructed objects (such as other tables,
|
||||
strings, vectors). For structs, you use the appropriate `create` function
|
||||
in-line, as shown above in the `Monster` example.
|
||||
|
||||
Once you're done constructing a buffer, you call `Finish` with the root object
|
||||
offset (`mon` in the example above). Your data now resides in Builder.Bytes.
|
||||
Important to note is that the real data starts at the index indicated by Head(),
|
||||
for Offset() bytes (this is because the buffer is constructed backwards).
|
||||
If you wanted to read the buffer right after creating it (using
|
||||
`GetRootAsMonster` above), the second argument, instead of `0` would thus
|
||||
also be `Head()`.
|
||||
|
||||
## Text Parsing
|
||||
|
||||
There currently is no support for parsing text (Schema's and JSON) directly
|
||||
from Go, though you could use the C++ parser through cgo. Please see the
|
||||
C++ documentation for more on text parsing.
|
||||
@@ -1,9 +1,16 @@
|
||||
# Formal Grammar of the schema language
|
||||
# Grammar of the schema language
|
||||
|
||||
schema = namespace\_decl | type\_decl | enum\_decl | root\_decl | object
|
||||
schema = include*
|
||||
( namespace\_decl | type\_decl | enum\_decl | root\_decl |
|
||||
file_extension_decl | file_identifier_decl |
|
||||
attribute\_decl | object )*
|
||||
|
||||
include = `include` string\_constant `;`
|
||||
|
||||
namespace\_decl = `namespace` ident ( `.` ident )* `;`
|
||||
|
||||
attribute\_decl = `attribute` string\_constant `;`
|
||||
|
||||
type\_decl = ( `table` | `struct` ) ident metadata `{` field\_decl+ `}`
|
||||
|
||||
enum\_decl = ( `enum` | `union` ) ident [ `:` type ] metadata `{` commasep(
|
||||
@@ -11,7 +18,7 @@ enumval\_decl ) `}`
|
||||
|
||||
root\_decl = `root_type` ident `;`
|
||||
|
||||
field\_decl = type `:` ident [ `=` scalar ] metadata `;`
|
||||
field\_decl = ident `:` type [ `=` scalar ] metadata `;`
|
||||
|
||||
type = `bool` | `byte` | `ubyte` | `short` | `ushort` | `int` | `uint` |
|
||||
`float` | `long` | `ulong` | `double`
|
||||
@@ -19,12 +26,22 @@ type = `bool` | `byte` | `ubyte` | `short` | `ushort` | `int` | `uint` |
|
||||
|
||||
enumval\_decl = ident [ `=` integer\_constant ]
|
||||
|
||||
metadata = [ `(` commasep( ident [ `:` scalar ] ) `)` ]
|
||||
metadata = [ `(` commasep( ident [ `:` single\_value ] ) `)` ]
|
||||
|
||||
scalar = integer\_constant | float\_constant | `true` | `false`
|
||||
scalar = integer\_constant | float\_constant
|
||||
|
||||
object = { commasep( ident `:` value ) }
|
||||
|
||||
value = scalar | object | string\_constant | `[` commasep( value ) `]`
|
||||
single\_value = scalar | string\_constant
|
||||
|
||||
value = single\_value | object | `[` commasep( value ) `]`
|
||||
|
||||
commasep(x) = [ x ( `,` x )\* ]
|
||||
|
||||
file_extension_decl = `file_extension` string\_constant `;`
|
||||
|
||||
file_identifier_decl = `file_identifier` string\_constant `;`
|
||||
|
||||
integer\_constant = -?[0-9]+ | `true` | `false`
|
||||
|
||||
float\_constant = -?[0-9]+.[0-9]+((e|E)(+|-)?[0-9]+)?
|
||||
|
||||
@@ -20,7 +20,9 @@ order, and objects to some extend can be stored in many orders. This is
|
||||
because the format doesn't need this information to be efficient, and it
|
||||
leaves room for optimization and extension (for example, fields can be
|
||||
packed in a way that is most compact). Instead, the format is defined in
|
||||
terms of offsets and adjacency only.
|
||||
terms of offsets and adjacency only. This may mean two different
|
||||
implementations may produce different binaries given the same input
|
||||
values, and this is perfectly valid.
|
||||
|
||||
### Format identification
|
||||
|
||||
@@ -43,8 +45,9 @@ than just a variation.
|
||||
### Offsets
|
||||
|
||||
The most important and generic offset type (see `flatbuffers.h`) is
|
||||
`offset_t`, which is currently always a `uint32_t`, and is used to
|
||||
refer to all tables/unions/strings/vectors. 32bit is
|
||||
`uoffset_t`, which is currently always a `uint32_t`, and is used to
|
||||
refer to all tables/unions/strings/vectors (these are never stored
|
||||
in-line). 32bit is
|
||||
intentional, since we want to keep the format binary compatible between
|
||||
32 and 64bit systems, and a 64bit offset would bloat the size for almost
|
||||
all uses. A version of this format with 64bit (or 16bit) offsets is easy to set
|
||||
@@ -52,7 +55,7 @@ when needed. Unsigned means they can only point in one direction, which
|
||||
typically is forward (towards a higher memory location). Any backwards
|
||||
offsets will be explicitly marked as such.
|
||||
|
||||
The format starts with an `offset_t` to the root object in the buffer.
|
||||
The format starts with an `uoffset_t` to the root object in the buffer.
|
||||
|
||||
We have two kinds of objects, structs and tables.
|
||||
|
||||
@@ -70,21 +73,23 @@ code.
|
||||
|
||||
### Tables
|
||||
|
||||
These start with an `soffset_t` to a vtable (signed version of
|
||||
`offset_t`, since vtables may be stored anywhere), followed by all the
|
||||
fields as aligned scalars. Unlike structs, not all fields need to be
|
||||
present. There is no set order and layout.
|
||||
These start with an `soffset_t` to a vtable. This is a signed version of
|
||||
`uoffset_t`, since vtables may be stored anywhere relative to the object.
|
||||
This offset is substracted (not added) from the object start to arrive at
|
||||
the vtable start. This offset is followed by all the
|
||||
fields as aligned scalars (or offsets). Unlike structs, not all fields
|
||||
need to be present. There is no set order and layout.
|
||||
|
||||
To be able to access fields regardless of these uncertainties, we go
|
||||
through a vtable of offsets. Vtables are shared between any objects that
|
||||
happen to have the same vtable values.
|
||||
|
||||
The elements of a vtable are all of type `voffset_t`, which is currently
|
||||
a `uint16_t`. The first element is the number of elements of the vtable,
|
||||
including this one. The second one is the size of the object, in bytes
|
||||
(including the vtable offset). This size is used for streaming, to know
|
||||
The elements of a vtable are all of type `voffset_t`, which is
|
||||
a `uint16_t`. The first element is the size of the vtable in bytes,
|
||||
including the size element. The second one is the size of the object, in bytes
|
||||
(including the vtable offset). This size could be used for streaming, to know
|
||||
how many bytes to read to be able to access all fields of the object.
|
||||
The remaining elements are N the offsets, where N is the amount of field
|
||||
The remaining elements are the N offsets, where N is the amount of fields
|
||||
declared in the schema when the code that constructed this buffer was
|
||||
compiled (thus, the size of the table is N + 2).
|
||||
|
||||
@@ -100,11 +105,13 @@ field to be read.
|
||||
|
||||
Strings are simply a vector of bytes, and are always
|
||||
null-terminated. Vectors are stored as contiguous aligned scalar
|
||||
elements prefixed by a count.
|
||||
elements prefixed by a 32bit element count (not including any
|
||||
null termination).
|
||||
|
||||
### Construction
|
||||
|
||||
The current implementation constructs these buffers backwards, since
|
||||
The current implementation constructs these buffers backwards (starting
|
||||
at the highest memory address of the buffer), since
|
||||
that significantly reduces the amount of bookkeeping and simplifies the
|
||||
construction API.
|
||||
|
||||
@@ -154,7 +161,8 @@ Unions share a lot with enums.
|
||||
struct Vec3;
|
||||
struct Monster;
|
||||
|
||||
Predeclare all datatypes since there may be circular references.
|
||||
Predeclare all data types since circular references between types are allowed
|
||||
(circular references between object are not, though).
|
||||
|
||||
MANUALLY_ALIGNED_STRUCT(4) Vec3 {
|
||||
private:
|
||||
|
||||
@@ -1,48 +1,88 @@
|
||||
# Use in Java
|
||||
# Use in Java/C-sharp
|
||||
|
||||
There's experimental support for reading FlatBuffers in Java. Generate code
|
||||
for Java with the `-j` option to `flatc`.
|
||||
FlatBuffers supports reading and writing binary FlatBuffers in Java and C#.
|
||||
Generate code for Java with the `-j` option to `flatc`, or for C# with `-n`
|
||||
(think .Net).
|
||||
|
||||
Note that this document is from the perspective of Java. Code for both languages
|
||||
is generated in the same way, with only minor differences. These differences
|
||||
are [explained in a section below](#differences-in-c-sharp).
|
||||
|
||||
See `javaTest.java` for an example. Essentially, you read a FlatBuffer binary
|
||||
file into a `byte[]`, which you then turn into a `ByteBuffer`, which you pass to
|
||||
the `getRootAsMonster` function:
|
||||
the `getRootAsMyRootType` function:
|
||||
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.java}
|
||||
ByteBuffer bb = ByteBuffer.wrap(data);
|
||||
Monster monster = Monster.getRootAsMonster(bb);
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Now you can access values much like C++:
|
||||
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.java}
|
||||
short hp = monster.hp();
|
||||
Vec3 pos = monster.pos();
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Note that whenever you access a new object like in the `pos` example above,
|
||||
a new temporary accessor object gets created. If your code is very performance
|
||||
sensitive (you iterate through a lot of objects), there's a second `pos()`
|
||||
method to which you can pass a `Vec3` object you've already created. This allows
|
||||
you to reuse it across many calls and reduce the amount of object allocation (and
|
||||
thus garbage collection) your program does.
|
||||
you to reuse it across many calls and reduce the amount of object allocation
|
||||
(and thus garbage collection) your program does.
|
||||
|
||||
Sadly the string accessors currently always create a new string when accessed,
|
||||
since FlatBuffer's UTF-8 strings can't be read in-place by Java.
|
||||
Java does not support unsigned scalars. This means that any unsigned types you
|
||||
use in your schema will actually be represented as a signed value. This means
|
||||
all bits are still present, but may represent a negative value when used.
|
||||
For example, to read a `byte b` as an unsigned number, you can do:
|
||||
`(short)(b & 0xFF)`
|
||||
|
||||
The default string accessor (e.g. `monster.name()`) currently always create
|
||||
a new Java `String` when accessed, since FlatBuffer's UTF-8 strings can't be
|
||||
used in-place by `String`. Alternatively, use `monster.nameAsByteBuffer()`
|
||||
which returns a `ByteBuffer` referring to the UTF-8 data in the original
|
||||
`ByteBuffer`, which is much more efficient. The `ByteBuffer`'s `position`
|
||||
points to the first character, and its `limit` to just after the last.
|
||||
|
||||
Vector access is also a bit different from C++: you pass an extra index
|
||||
to the vector field accessor. Then a second method with the same name
|
||||
suffixed by `_length` let's you know the number of elements you can access:
|
||||
suffixed by `Length` let's you know the number of elements you can access:
|
||||
|
||||
for (int i = 0; i < monster.inventory_length(); i++)
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.java}
|
||||
for (int i = 0; i < monster.inventoryLength(); i++)
|
||||
monster.inventory(i); // do something here
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Alternatively, much like strings, you can use `monster.inventoryAsByteBuffer()`
|
||||
to get a `ByteBuffer` referring to the whole vector. Use `ByteBuffer` methods
|
||||
like `asFloatBuffer` to get specific views if needed.
|
||||
|
||||
If you specified a file_indentifier in the schema, you can query if the
|
||||
buffer is of the desired type before accessing it using:
|
||||
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.java}
|
||||
if (Monster.MonsterBufferHasIdentifier(bb)) ...
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
|
||||
## Buffer construction in Java
|
||||
|
||||
You can also construct these buffers in Java using the static methods found
|
||||
in the generated code, and the FlatBufferBuilder class:
|
||||
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.java}
|
||||
FlatBufferBuilder fbb = new FlatBufferBuilder();
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Create strings:
|
||||
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.java}
|
||||
int str = fbb.createString("MyMonster");
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Create a table with a struct contained therein:
|
||||
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.java}
|
||||
Monster.startMonster(fbb);
|
||||
Monster.addPos(fbb, Vec3.createVec3(fbb, 1.0f, 2.0f, 3.0f, 3.0, (byte)4, (short)5, (byte)6));
|
||||
Monster.addHp(fbb, (short)80);
|
||||
@@ -52,28 +92,133 @@ Create a table with a struct contained therein:
|
||||
Monster.addTest(fbb, mon2);
|
||||
Monster.addTest4(fbb, test4s);
|
||||
int mon = Monster.endMonster(fbb);
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
For some simpler types, you can use a convenient `create` function call that
|
||||
allows you to construct tables in one function call. This example definition
|
||||
however contains an inline struct field, so we have to create the table
|
||||
manually.
|
||||
This is to create the buffer without using temporary object allocation.
|
||||
|
||||
It's important to understand that fields that are structs are inline (like
|
||||
`Vec3` above), and MUST thus be created between the start and end calls of
|
||||
a table. Everything else (other tables, strings, vectors) MUST be created
|
||||
before the start of the table they are referenced in.
|
||||
|
||||
As you can see, the Java code for tables does not use a convenient
|
||||
`createMonster` call like the C++ code. This is to create the buffer without
|
||||
using temporary object allocation (since the `Vec3` is an inline component of
|
||||
`Monster`, it has to be created right where it is added, whereas the name and
|
||||
the inventory are not inline).
|
||||
Structs do have convenient methods that even have arguments for nested structs.
|
||||
|
||||
Vectors also use this start/end pattern to allow vectors of both scalar types
|
||||
and structs:
|
||||
As you can see, references to other objects (e.g. the string above) are simple
|
||||
ints, and thus do not have the type-safety of the Offset type in C++. Extra
|
||||
care must thus be taken that you set the right offset on the right field.
|
||||
|
||||
Vectors can be created from the corresponding Java array like so:
|
||||
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.java}
|
||||
int inv = Monster.createInventoryVector(fbb, new byte[] { 0, 1, 2, 3, 4 });
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
This works for arrays of scalars and (int) offsets to strings/tables,
|
||||
but not structs. If you want to write structs, or what you want to write
|
||||
does not sit in an array, you can also use the start/end pattern:
|
||||
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.java}
|
||||
Monster.startInventoryVector(fbb, 5);
|
||||
for (byte i = 4; i >=0; i--) fbb.addByte(i);
|
||||
int inv = fbb.endVector();
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
You can use the generated method `startInventoryVector` to conveniently call
|
||||
`startVector` with the right element size. You pass the number of
|
||||
elements you want to write. You write the elements backwards since the buffer
|
||||
is being constructed back to front.
|
||||
elements you want to write. Note how you write the elements backwards since
|
||||
the buffer is being constructed back to front. You then pass `inv` to the
|
||||
corresponding `Add` call when you construct the table containing it afterwards.
|
||||
|
||||
## Text Parsing
|
||||
There are `add` functions for all the scalar types. You use `addOffset` for
|
||||
any previously constructed objects (such as other tables, strings, vectors).
|
||||
For structs, you use the appropriate `create` function in-line, as shown
|
||||
above in the `Monster` example.
|
||||
|
||||
To finish the buffer, call:
|
||||
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.java}
|
||||
Monster.finishMonsterBuffer(fbb, mon);
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
The buffer is now ready to be transmitted. It is contained in the `ByteBuffer`
|
||||
which you can obtain from `fbb.dataBuffer()`. Importantly, the valid data does
|
||||
not start from offset 0 in this buffer, but from `fbb.dataBuffer().position()`
|
||||
(this is because the data was built backwards in memory).
|
||||
It ends at `fbb.capacity()`.
|
||||
|
||||
|
||||
## Differences in C-sharp
|
||||
|
||||
C# code works almost identically to Java, with only a few minor differences.
|
||||
You can see an example of C# code in `tests/FlatBuffers.Test/FlatBuffersExampleTests.cs`.
|
||||
|
||||
First of all, naming follows standard C# style with `PascalCasing` identifiers,
|
||||
e.g. `GetRootAsMyRootType`. Also, values (except vectors and unions) are available
|
||||
as properties instead of parameterless accessor methods as in Java. The
|
||||
performance-enhancing methods to which you can pass an already created object
|
||||
are prefixed with `Get`, e.g.:
|
||||
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cs}
|
||||
// property
|
||||
var pos = monster.Pos;
|
||||
// method filling a preconstructed object
|
||||
var preconstructedPos = new Vec3();
|
||||
monster.GetPos(preconstructedPos);
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
|
||||
## Text parsing
|
||||
|
||||
There currently is no support for parsing text (Schema's and JSON) directly
|
||||
from Java, though you could use the C++ parser through JNI. Please see the
|
||||
from Java or C#, though you could use the C++ parser through native call
|
||||
interfaces available to each language. Please see the
|
||||
C++ documentation for more on text parsing.
|
||||
|
||||
### Mutating FlatBuffers
|
||||
|
||||
As you saw above, typically once you have created a FlatBuffer, it is
|
||||
read-only from that moment on. There are however cases where you have just
|
||||
received a FlatBuffer, and you'd like to modify something about it before
|
||||
sending it on to another recipient. With the above functionality, you'd have
|
||||
to generate an entirely new FlatBuffer, while tracking what you modify in your
|
||||
own data structures. This is inconvenient.
|
||||
|
||||
For this reason FlatBuffers can also be mutated in-place. While this is great
|
||||
for making small fixes to an existing buffer, you generally want to create
|
||||
buffers from scratch whenever possible, since it is much more efficient and
|
||||
the API is much more general purpose.
|
||||
|
||||
To get non-const accessors, invoke `flatc` with `--gen-mutable`.
|
||||
|
||||
You now can:
|
||||
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.java}
|
||||
Monster monster = Monster.getRootAsMonster(bb);
|
||||
monster.mutateHp(10); // Set table field.
|
||||
monster.pos().mutateZ(4); // Set struct field.
|
||||
monster.mutateInventory(0, 1); // Set vector element.
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
We use the somewhat verbose term `mutate` instead of `set` to indicate that
|
||||
this is a special use case, not to be confused with the default way of
|
||||
constructing FlatBuffer data.
|
||||
|
||||
After the above mutations, you can send on the FlatBuffer to a new recipient
|
||||
without any further work!
|
||||
|
||||
Note that any `mutate` functions on tables return a boolean, which is false
|
||||
if the field we're trying to set isn't present in the buffer. Fields are not
|
||||
present if they weren't set, or even if they happen to be equal to the
|
||||
default value. For example, in the creation code above we set the `mana` field
|
||||
to `150`, which is the default value, so it was never stored in the buffer.
|
||||
Trying to call mutateMana() on such data will return false, and the value won't
|
||||
actually be modified!
|
||||
|
||||
One way to solve this is to call `forceDefaults()` on a
|
||||
`FlatBufferBuilder` to force all fields you set to actually be written. This
|
||||
of course increases the size of the buffer somewhat, but this may be
|
||||
acceptable for a mutable buffer.
|
||||
|
||||
115
docs/source/PythonUsage.md
Executable file
115
docs/source/PythonUsage.md
Executable file
@@ -0,0 +1,115 @@
|
||||
# Use in Python
|
||||
|
||||
There's experimental support for reading FlatBuffers in Python. Generate
|
||||
code for Python with the `-p` option to `flatc`.
|
||||
|
||||
See `py_test.py` for an example. You import the generated code, read a
|
||||
FlatBuffer binary file into a `bytearray`, which you pass to the
|
||||
`GetRootAsMonster` function:
|
||||
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.py}
|
||||
import MyGame.Example as example
|
||||
import flatbuffers
|
||||
|
||||
buf = open('monster.dat', 'rb').read()
|
||||
buf = bytearray(buf)
|
||||
monster = example.GetRootAsMonster(buf, 0)
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Now you can access values like this:
|
||||
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.py}
|
||||
hp = monster.Hp()
|
||||
pos = monster.Pos()
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
To access vectors you pass an extra index to the
|
||||
vector field accessor. Then a second method with the same name suffixed
|
||||
by `Length` let's you know the number of elements you can access:
|
||||
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.py}
|
||||
for i in xrange(monster.InventoryLength()):
|
||||
monster.Inventory(i) # do something here
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
You can also construct these buffers in Python using the functions found
|
||||
in the generated code, and the FlatBufferBuilder class:
|
||||
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.py}
|
||||
builder = flatbuffers.Builder(0)
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Create strings:
|
||||
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.py}
|
||||
s = builder.CreateString("MyMonster")
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Create a table with a struct contained therein:
|
||||
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.py}
|
||||
example.MonsterStart(builder)
|
||||
example.MonsterAddPos(builder, example.CreateVec3(builder, 1.0, 2.0, 3.0, 3.0, 4, 5, 6))
|
||||
example.MonsterAddHp(builder, 80)
|
||||
example.MonsterAddName(builder, str)
|
||||
example.MonsterAddInventory(builder, inv)
|
||||
example.MonsterAddTest_Type(builder, 1)
|
||||
example.MonsterAddTest(builder, mon2)
|
||||
example.MonsterAddTest4(builder, test4s)
|
||||
mon = example.MonsterEnd(builder)
|
||||
|
||||
final_flatbuffer = builder.Output()
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Unlike C++, Python does not support table creation functions like 'createMonster()'.
|
||||
This is to create the buffer without
|
||||
using temporary object allocation (since the `Vec3` is an inline component of
|
||||
`Monster`, it has to be created right where it is added, whereas the name and
|
||||
the inventory are not inline, and **must** be created outside of the table
|
||||
creation sequence).
|
||||
Structs do have convenient methods that allow you to construct them in one call.
|
||||
These also have arguments for nested structs, e.g. if a struct has a field `a`
|
||||
and a nested struct field `b` (which has fields `c` and `d`), then the arguments
|
||||
will be `a`, `c` and `d`.
|
||||
|
||||
Vectors also use this start/end pattern to allow vectors of both scalar types
|
||||
and structs:
|
||||
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.py}
|
||||
example.MonsterStartInventoryVector(builder, 5)
|
||||
i = 4
|
||||
while i >= 0:
|
||||
builder.PrependByte(byte(i))
|
||||
i -= 1
|
||||
|
||||
inv = builder.EndVector(5)
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
The generated method 'StartInventoryVector' is provided as a convenience
|
||||
function which calls 'StartVector' with the correct element size of the vector
|
||||
type which in this case is 'ubyte' or 1 byte per vector element.
|
||||
You pass the number of elements you want to write.
|
||||
You write the elements backwards since the buffer
|
||||
is being constructed back to front. Use the correct `Prepend` call for the type,
|
||||
or `PrependUOffsetT` for offsets. You then pass `inv` to the corresponding
|
||||
`Add` call when you construct the table containing it afterwards.
|
||||
|
||||
There are `Prepend` functions for all the scalar types. You use
|
||||
`PrependUOffset` for any previously constructed objects (such as other tables,
|
||||
strings, vectors). For structs, you use the appropriate `create` function
|
||||
in-line, as shown above in the `Monster` example.
|
||||
|
||||
Once you're done constructing a buffer, you call `Finish` with the root object
|
||||
offset (`mon` in the example above). Your data now resides in Builder.Bytes.
|
||||
Important to note is that the real data starts at the index indicated by Head(),
|
||||
for Offset() bytes (this is because the buffer is constructed backwards).
|
||||
If you wanted to read the buffer right after creating it (using
|
||||
`GetRootAsMonster` above), the second argument, instead of `0` would thus
|
||||
also be `Head()`.
|
||||
|
||||
## Text Parsing
|
||||
|
||||
There currently is no support for parsing text (Schema's and JSON) directly
|
||||
from Python, though you could use the C++ parser through SWIG or ctypes. Please
|
||||
see the C++ documentation for more on text parsing.
|
||||
|
||||
@@ -9,6 +9,8 @@ first:
|
||||
|
||||
namespace MyGame;
|
||||
|
||||
attribute "priority";
|
||||
|
||||
enum Color : byte { Red = 1, Green, Blue }
|
||||
|
||||
union Any { Monster, Weapon, Pickup }
|
||||
@@ -51,6 +53,9 @@ and backwards compatibility. Note that:
|
||||
definition. Older data will still
|
||||
read correctly, and give you the default value when read. Older code
|
||||
will simply ignore the new field.
|
||||
If you want to have flexibility to use any order for fields in your
|
||||
schema, you can manually assign ids (much like Protocol Buffers),
|
||||
see the `id` attribute below.
|
||||
|
||||
- You cannot delete fields you don't use anymore from the schema,
|
||||
but you can simply
|
||||
@@ -77,7 +82,7 @@ parent object, and use no virtual table).
|
||||
|
||||
### Types
|
||||
|
||||
Builtin scalar types are:
|
||||
Built-in scalar types are:
|
||||
|
||||
- 8 bit: `byte ubyte bool`
|
||||
|
||||
@@ -87,9 +92,10 @@ Builtin scalar types are:
|
||||
|
||||
- 64 bit: `long ulong double`
|
||||
|
||||
Built-in non-scalar types:
|
||||
|
||||
- Vector of any other type (denoted with `[type]`). Nesting vectors
|
||||
require you wrap the inner vector in a struct/table rather than
|
||||
writing `[[type]]`.
|
||||
is not supported, instead you can wrap the inner vector in a table.
|
||||
|
||||
- `string`, which may only hold UTF-8 or 7-bit ASCII. For other text encodings
|
||||
or general binary data use vectors (`[byte]` or `[ubyte]`) instead.
|
||||
@@ -105,8 +111,11 @@ high bit yet.
|
||||
### (Default) Values
|
||||
|
||||
Values are a sequence of digits, optionally followed by a `.` and more digits
|
||||
for float constants, and optionally prefixed by a `-`. Non-scalar defaults are
|
||||
currently not supported (always NULL).
|
||||
for float constants, and optionally prefixed by a `-`. Floats may end with an
|
||||
`e` or `E`, followed by a `+` or `-` and more digits (scientific notation).
|
||||
|
||||
Only scalar values can have defaults, non-scalar (string/vector/table) fields
|
||||
default to NULL when not present.
|
||||
|
||||
You generally do not want to change default values after they're initially
|
||||
defined. Fields that have the default value are not actually stored in the
|
||||
@@ -122,8 +131,7 @@ Define a sequence of named constants, each with a given value, or
|
||||
increasing by one from the previous one. The default first value
|
||||
is `0`. As you can see in the enum declaration, you specify the underlying
|
||||
integral type of the enum with `:` (in this case `byte`), which then determines
|
||||
the type of any fields declared with this enum type. If you omit the underlying
|
||||
type, it will be `short`.
|
||||
the type of any fields declared with this enum type.
|
||||
|
||||
### Unions
|
||||
|
||||
@@ -134,16 +142,80 @@ additionally a hidden field with the suffix `_type` is generated that
|
||||
holds the corresponding enum value, allowing you to know which type to
|
||||
cast to at runtime.
|
||||
|
||||
Unions are a good way to be able to send multiple message types as a FlatBuffer.
|
||||
Note that because a union field is really two fields, it must always be
|
||||
part of a table, it cannot be the root of a FlatBuffer by itself.
|
||||
|
||||
If you have a need to distinguish between different FlatBuffers in a more
|
||||
open-ended way, for example for use as files, see the file identification
|
||||
feature below.
|
||||
|
||||
### Namespaces
|
||||
|
||||
These will generate the corresponding namespace in C++ for all helper
|
||||
code, and packages in Java. You can use `.` to specify nested namespaces /
|
||||
packages.
|
||||
|
||||
### Includes
|
||||
|
||||
You can include other schemas files in your current one, e.g.:
|
||||
|
||||
include "mydefinitions.fbs";
|
||||
|
||||
This makes it easier to refer to types defined elsewhere. `include`
|
||||
automatically ensures each file is parsed just once, even when referred to
|
||||
more than once.
|
||||
|
||||
When using the `flatc` compiler to generate code for schema definitions,
|
||||
only definitions in the current file will be generated, not those from the
|
||||
included files (those you still generate separately).
|
||||
|
||||
### Root type
|
||||
|
||||
This declares what you consider to be the root table (or struct) of the
|
||||
serialized data.
|
||||
serialized data. This is particular important for parsing JSON data,
|
||||
which doesn't include object type information.
|
||||
|
||||
### File identification and extension
|
||||
|
||||
Typically, a FlatBuffer binary buffer is not self-describing, i.e. it
|
||||
needs you to know its schema to parse it correctly. But if you
|
||||
want to use a FlatBuffer as a file format, it would be convenient
|
||||
to be able to have a "magic number" in there, like most file formats
|
||||
have, to be able to do a sanity check to see if you're reading the
|
||||
kind of file you're expecting.
|
||||
|
||||
Now, you can always prefix a FlatBuffer with your own file header,
|
||||
but FlatBuffers has a built-in way to add an identifier to a
|
||||
FlatBuffer that takes up minimal space, and keeps the buffer
|
||||
compatible with buffers that don't have such an identifier.
|
||||
|
||||
You can specify in a schema, similar to `root_type`, that you intend
|
||||
for this type of FlatBuffer to be used as a file format:
|
||||
|
||||
file_identifier "MYFI";
|
||||
|
||||
Identifiers must always be exactly 4 characters long. These 4 characters
|
||||
will end up as bytes at offsets 4-7 (inclusive) in the buffer.
|
||||
|
||||
For any schema that has such an identifier, `flatc` will automatically
|
||||
add the identifier to any binaries it generates (with `-b`),
|
||||
and generated calls like `FinishMonsterBuffer` also add the identifier.
|
||||
If you have specified an identifier and wish to generate a buffer
|
||||
without one, you can always still do so by calling
|
||||
`FlatBufferBuilder::Finish` explicitly.
|
||||
|
||||
After loading a buffer, you can use a call like
|
||||
`MonsterBufferHasIdentifier` to check if the identifier is present.
|
||||
|
||||
Note that this is best for open-ended uses such as files. If you simply wanted
|
||||
to send one of a set of possible messages over a network for example, you'd
|
||||
be better off with a union.
|
||||
|
||||
Additionally, by default `flatc` will output binary files as `.bin`.
|
||||
This declaration in the schema will change that to whatever you want:
|
||||
|
||||
file_extension "ext";
|
||||
|
||||
### Comments & documentation
|
||||
|
||||
@@ -158,16 +230,38 @@ in the corresponding C++ code. Multiple such lines per item are allowed.
|
||||
Attributes may be attached to a declaration, behind a field, or after
|
||||
the name of a table/struct/enum/union. These may either have a value or
|
||||
not. Some attributes like `deprecated` are understood by the compiler,
|
||||
others are simply ignored (like `priority`), but are available to query
|
||||
if you parse the schema at runtime.
|
||||
user defined ones need to be declared with the attribute declaration
|
||||
(like `priority` in the example above), and are
|
||||
available to query if you parse the schema at runtime.
|
||||
This is useful if you write your own code generators/editors etc., and
|
||||
you wish to add additional information specific to your tool (such as a
|
||||
help text).
|
||||
|
||||
Current understood attributes:
|
||||
|
||||
- `id: n` (on a table field): manually set the field identifier to `n`.
|
||||
If you use this attribute, you must use it on ALL fields of this table,
|
||||
and the numbers must be a contiguous range from 0 onwards.
|
||||
Additionally, since a union type effectively adds two fields, its
|
||||
id must be that of the second field (the first field is the type
|
||||
field and not explicitly declared in the schema).
|
||||
For example, if the last field before the union field had id 6,
|
||||
the union field should have id 8, and the unions type field will
|
||||
implicitly be 7.
|
||||
IDs allow the fields to be placed in any order in the schema.
|
||||
When a new field is added to the schema is must use the next available ID.
|
||||
- `deprecated` (on a field): do not generate accessors for this field
|
||||
anymore, code should stop using this data.
|
||||
- `required` (on a non-scalar table field): this field must always be set.
|
||||
By default, all fields are optional, i.e. may be left out. This is
|
||||
desirable, as it helps with forwards/backwards compatibility, and
|
||||
flexibility of data structures. It is also a burden on the reading code,
|
||||
since for non-scalar fields it requires you to check against NULL and
|
||||
take appropriate action. By specifying this field, you force code that
|
||||
constructs FlatBuffers to ensure this field is initialized, so the reading
|
||||
code may access it directly, without checking for NULL. If the constructing
|
||||
code does not initialize this field, they will get an assert, and also
|
||||
the verifier will fail on buffers that have missing required fields.
|
||||
- `original_order` (on a table): since elements in a table do not need
|
||||
to be stored in any particular order, they are often optimized for
|
||||
space by sorting them to size. This attribute stops that from happening.
|
||||
@@ -176,6 +270,64 @@ Current understood attributes:
|
||||
these structs to be aligned to that amount inside a buffer, IF that
|
||||
buffer is allocated with that alignment (which is not necessarily
|
||||
the case for buffers accessed directly inside a `FlatBufferBuilder`).
|
||||
- `bit_flags` (on an enum): the values of this field indicate bits,
|
||||
meaning that any value N specified in the schema will end up
|
||||
representing 1<<N, or if you don't specify values at all, you'll get
|
||||
the sequence 1, 2, 4, 8, ...
|
||||
- `nested_flatbuffer: "table_name"` (on a field): this indicates that the field
|
||||
(which must be a vector of ubyte) contains flatbuffer data, for which the
|
||||
root type is given by `table_name`. The generated code will then produce
|
||||
a convenient accessor for the nested FlatBuffer.
|
||||
- `key` (on a field): this field is meant to be used as a key when sorting
|
||||
a vector of the type of table it sits in. Can be used for in-place
|
||||
binary search.
|
||||
|
||||
## JSON Parsing
|
||||
|
||||
The same parser that parses the schema declarations above is also able
|
||||
to parse JSON objects that conform to this schema. So, unlike other JSON
|
||||
parsers, this parser is strongly typed, and parses directly into a FlatBuffer
|
||||
(see the compiler documentation on how to do this from the command line, or
|
||||
the C++ documentation on how to do this at runtime).
|
||||
|
||||
Besides needing a schema, there are a few other changes to how it parses
|
||||
JSON:
|
||||
|
||||
- It accepts field names with and without quotes, like many JSON parsers
|
||||
already do. It outputs them without quotes as well, though can be made
|
||||
to output them using the `strict_json` flag.
|
||||
- If a field has an enum type, the parser will recognize symbolic enum
|
||||
values (with or without quotes) instead of numbers, e.g.
|
||||
`field: EnumVal`. If a field is of integral type, you can still use
|
||||
symbolic names, but values need to be prefixed with their type and
|
||||
need to be quoted, e.g. `field: "Enum.EnumVal"`. For enums
|
||||
representing flags, you may place multiple inside a string
|
||||
separated by spaces to OR them, e.g.
|
||||
`field: "EnumVal1 EnumVal2"` or `field: "Enum.EnumVal1 Enum.EnumVal2"`.
|
||||
- Similarly, for unions, these need to specified with two fields much like
|
||||
you do when serializing from code. E.g. for a field `foo`, you must
|
||||
add a field `foo_type: FooOne` right before the `foo` field, where
|
||||
`FooOne` would be the table out of the union you want to use.
|
||||
|
||||
When parsing JSON, it recognizes the following escape codes in strings:
|
||||
|
||||
- `\n` - linefeed.
|
||||
- `\t` - tab.
|
||||
- `\r` - carriage return.
|
||||
- `\b` - backspace.
|
||||
- `\f` - form feed.
|
||||
- `\"` - double quote.
|
||||
- `\\` - backslash.
|
||||
- `\/` - forward slash.
|
||||
- `\uXXXX` - 16-bit unicode code point, converted to the equivalent UTF-8
|
||||
representation.
|
||||
- `\xXX` - 8-bit binary hexadecimal number XX. This is the only one that is
|
||||
not in the JSON spec (see http://json.org/), but is needed to be able to
|
||||
encode arbitrary binary in strings to text and back without losing
|
||||
information (e.g. the byte 0xFF can't be represented in standard JSON).
|
||||
|
||||
It also generates these escape codes back again when generating JSON from a
|
||||
binary representation.
|
||||
|
||||
## Gotchas
|
||||
|
||||
@@ -184,7 +336,8 @@ Current understood attributes:
|
||||
FlatBuffers relies on new field declarations being added at the end, and earlier
|
||||
declarations to not be removed, but be marked deprecated when needed. We think
|
||||
this is an improvement over the manual number assignment that happens in
|
||||
Protocol Buffers.
|
||||
Protocol Buffers (and which is still an option using the `id` attribute
|
||||
mentioned above).
|
||||
|
||||
One place where this is possibly problematic however is source control. If user
|
||||
A adds a field, generates new binary data with this new schema, then tries to
|
||||
@@ -194,5 +347,7 @@ the new schema.
|
||||
|
||||
The solution of course is that you should not be generating binary data before
|
||||
your schema changes have been committed, ensuring consistency with the rest of
|
||||
the world.
|
||||
the world. If this is not practical for you, use explicit field ids, which
|
||||
should always generate a merge conflict if two people try to allocate the same
|
||||
id.
|
||||
|
||||
|
||||
39
docs/source/Support.md
Executable file
39
docs/source/Support.md
Executable file
@@ -0,0 +1,39 @@
|
||||
# Platform / Language / Feature support
|
||||
|
||||
FlatBuffers is actively being worked on, which means that certain platform /
|
||||
language / feature combinations may not be available yet.
|
||||
|
||||
This page tries to track those issues, to make informed decisions easier.
|
||||
In general:
|
||||
|
||||
* Languages: language support beyond the ones created by the original
|
||||
FlatBuffer authors typically depends on community contributions.
|
||||
* Features: C++ was the first language supported, since our original
|
||||
target was high performance game development. It thus has the richest
|
||||
feature set, and is likely most robust. Other languages are catching up
|
||||
however.
|
||||
* Platforms: All language implementations are typically portable to most
|
||||
platforms, unless where noted otherwise.
|
||||
|
||||
NOTE: this table is a start, it needs to be extended.
|
||||
|
||||
Feature | C++ | Java | C# | Go | Python | JS
|
||||
------------------------------ | ------ | ------ | ------ | ------ | ------ | ------
|
||||
Codegen for all basic features | Yes | Yes | Yes | Yes | Yes | WIP
|
||||
JSON parsing | Yes | No | No | No | No | No
|
||||
Simple mutation | Yes | WIP | WIP | No | No | No
|
||||
Reflection | Yes | No | No | No | No | No
|
||||
Buffer verifier | Yes | No | No | No | No | No
|
||||
Testing: basic | Yes | Yes | Yes | Yes | Yes | WIP
|
||||
Testing: fuzz | Yes | No | No | Yes | Yes | No
|
||||
Performance: | Superb | Great | Great | Great | Ok | ?
|
||||
Platform: Windows | VS2010 | Yes | Yes | ? | ? | ?
|
||||
Platform: Linux | GCC282 | Yes | ? | Yes | Yes | ?
|
||||
Platform: OS X | Xcode4 | ? | ? | ? | Yes | ?
|
||||
Platform: Android | NDK10d | Yes | ? | ? | ? | ?
|
||||
Platform: iOS | ? | ? | ? | ? | ? | ?
|
||||
Engine: Unity | ? | ? | Yes | ? | ? | ?
|
||||
Primary authors (github) | wvo | wvo | (ev/js)| rw | rw | (ev)
|
||||
|
||||
* ev = evolutional
|
||||
* js = jonsimantov
|
||||
@@ -748,7 +748,10 @@ INPUT = "FlatBuffers.md" \
|
||||
"Compiler.md" \
|
||||
"Schemas.md" \
|
||||
"CppUsage.md" \
|
||||
"GoUsage.md" \
|
||||
"JavaUsage.md" \
|
||||
"PythonUsage.md" \
|
||||
"Support.md" \
|
||||
"Benchmarks.md" \
|
||||
"WhitePaper.md" \
|
||||
"Internals.md" \
|
||||
@@ -1104,7 +1107,7 @@ HTML_FILE_EXTENSION = .html
|
||||
# of the possible markers and block names see the documentation.
|
||||
# This tag requires that the tag GENERATE_HTML is set to YES.
|
||||
|
||||
HTML_HEADER =
|
||||
HTML_HEADER = ../header.html
|
||||
|
||||
# The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each
|
||||
# generated HTML page. If the tag is left blank doxygen will generate a standard
|
||||
@@ -1126,7 +1129,7 @@ HTML_FOOTER = ../footer.html
|
||||
# obsolete.
|
||||
# This tag requires that the tag GENERATE_HTML is set to YES.
|
||||
|
||||
HTML_STYLESHEET =
|
||||
HTML_STYLESHEET = style.css
|
||||
|
||||
# The HTML_EXTRA_STYLESHEET tag can be used to specify an additional user-
|
||||
# defined cascading style sheet that is included after the standard style sheets
|
||||
@@ -1147,7 +1150,7 @@ HTML_EXTRA_STYLESHEET =
|
||||
# files will be copied as-is; there are no commands or markers available.
|
||||
# This tag requires that the tag GENERATE_HTML is set to YES.
|
||||
|
||||
HTML_EXTRA_FILES =
|
||||
HTML_EXTRA_FILES = ../images/fpl_logo_small.png ../images/ftv2mnode.png ../images/ftv2pnode.png
|
||||
|
||||
# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen
|
||||
# will adjust the colors in the stylesheet and background images according to
|
||||
|
||||
396
docs/source/style.css
Normal file
396
docs/source/style.css
Normal file
@@ -0,0 +1,396 @@
|
||||
body,
|
||||
#projectname,
|
||||
table,
|
||||
div,
|
||||
p,
|
||||
dl,
|
||||
.title,
|
||||
.tabs,
|
||||
.tabs2,
|
||||
.tabs3,
|
||||
#nav-tree .label {
|
||||
font-family: roboto, sans-serif;
|
||||
}
|
||||
|
||||
#commonprojectlogo {
|
||||
padding: 5px 0px 5px 15px;
|
||||
}
|
||||
|
||||
#projectname {
|
||||
color: #00bcd4;
|
||||
font-size: 280%;
|
||||
padding: 15px 0px;
|
||||
font-weight: 300;
|
||||
}
|
||||
|
||||
#titlearea {
|
||||
border-bottom: 2px solid #e5e5e5;
|
||||
}
|
||||
|
||||
.title {
|
||||
color: #212121;
|
||||
font: 300 34px/40px Roboto,sans-serif;
|
||||
}
|
||||
|
||||
#nav-tree {
|
||||
background-color: #fff;
|
||||
}
|
||||
|
||||
#navrow1, #navrow2 {
|
||||
border-bottom: 2px solid #e7e7e7;
|
||||
}
|
||||
|
||||
.tabs, .tabs2, .tabs3 {
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.tabs,
|
||||
.tabs2,
|
||||
.tabs3,
|
||||
.tablist li,
|
||||
.tablist li.current a {
|
||||
background-image: none;
|
||||
}
|
||||
|
||||
.tablist {
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.tablist li, .tablist li p {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.tablist li a,
|
||||
.tablist li.current a {
|
||||
color: #757575;
|
||||
text-shadow: none;
|
||||
}
|
||||
|
||||
.tablist li.current a {
|
||||
background: #00bcd4;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.tablist a {
|
||||
background-image: none;
|
||||
border-right: 2px solid #e5e5e5;
|
||||
font-weight: normal;
|
||||
}
|
||||
|
||||
.tablist a:hover,
|
||||
.tablist li.current a:hover {
|
||||
background-image: none;
|
||||
text-decoration: underline;
|
||||
text-shadow: none;
|
||||
}
|
||||
|
||||
.tablist a:hover {
|
||||
color: #00bcd4;
|
||||
}
|
||||
|
||||
.tablist li.current a:hover {
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
div.header {
|
||||
background-color: #f7f7f7;
|
||||
background-image: none;
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
#MSearchBox {
|
||||
border: 1px solid #ccc;
|
||||
border-radius: 5px;
|
||||
display: inline-block;
|
||||
height: 20px;
|
||||
right: 10px;
|
||||
}
|
||||
|
||||
#MSearchBox .left,
|
||||
#MSearchBox .right,
|
||||
#MSearchField {
|
||||
background: none;
|
||||
}
|
||||
|
||||
a.SelectItem:hover {
|
||||
background-color: #00bcd4;
|
||||
}
|
||||
|
||||
#nav-tree {
|
||||
background-image: none;
|
||||
}
|
||||
|
||||
#nav-tree .selected {
|
||||
background-image: none;
|
||||
text-shadow: none;
|
||||
background-color: #f7f7f7;
|
||||
}
|
||||
|
||||
#nav-tree a {
|
||||
color: #212121;
|
||||
}
|
||||
|
||||
#nav-tree .selected a {
|
||||
color: #0288d1;
|
||||
}
|
||||
|
||||
#nav-tree .item:hover {
|
||||
background-color: #f7f7f7;
|
||||
}
|
||||
|
||||
#nav-tree .item:hover a {
|
||||
color: #0288d1;
|
||||
}
|
||||
|
||||
#nav-tree .label {
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
#nav-sync {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.ui-resizable-e {
|
||||
background: #ebebeb;
|
||||
border-left: 1px solid #ddd;
|
||||
border-right: 1px solid #ddd;
|
||||
}
|
||||
|
||||
.contents tr td .image {
|
||||
margin-top: 24px;
|
||||
}
|
||||
|
||||
.image {
|
||||
text-align: left;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
a:link,
|
||||
a:visited,
|
||||
.contents a:link,
|
||||
.contents a:visited,
|
||||
a.el {
|
||||
color: #0288d1;
|
||||
font-weight: normal;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
div.contents {
|
||||
margin-right: 12px;
|
||||
}
|
||||
|
||||
.directory tr, .directory tr.even {
|
||||
background: #7cb342;
|
||||
border-top: 1px solid #7cb342;
|
||||
}
|
||||
|
||||
.directory td,
|
||||
.directory td.entry,
|
||||
.directory td.desc {
|
||||
background: rgba(255,255,255,.95);
|
||||
border-left: none;
|
||||
color: #212121;
|
||||
padding-top: 10px;
|
||||
padding-bottom: 10px;
|
||||
padding-left: 8px;
|
||||
padding-right: 8px;
|
||||
}
|
||||
|
||||
.directory tr#row_0_ {
|
||||
border-top-color: #7cb342;
|
||||
}
|
||||
|
||||
.directory tr#row_0_ td {
|
||||
background: #7cb342;
|
||||
color: #fff;
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.memSeparator {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.memitem {
|
||||
background: #7cb342;
|
||||
}
|
||||
|
||||
.memproto, dl.reflist dt {
|
||||
background: #7cb342;
|
||||
background-image: none;
|
||||
border: none;
|
||||
box-shadow: none;
|
||||
-webkit-box-shadow: none;
|
||||
color: #fff;
|
||||
text-shadow: none;
|
||||
}
|
||||
|
||||
.memproto .memtemplate,
|
||||
.memproto a.el,
|
||||
.memproto .paramname {
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.memdoc, dl.reflist dd {
|
||||
border: none;
|
||||
background-color: rgba(255,255,255,.95);
|
||||
background-image: none;
|
||||
box-shadow: none;
|
||||
-webkit-box-shadow: none;
|
||||
-webkit-border-bottom-left-radius: 0;
|
||||
-webkit-border-bottom-right-radius: 0;
|
||||
}
|
||||
|
||||
.memitem, table.doxtable, table.memberdecls {
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
table.doxtable th {
|
||||
background: #7cb342;
|
||||
}
|
||||
|
||||
table.doxtable tr {
|
||||
background: #7cb342;
|
||||
border-top: 1px solid #7cb342;
|
||||
}
|
||||
|
||||
table.doxtable td, table.doxtable th {
|
||||
border: none;
|
||||
padding: 10px 8px;
|
||||
}
|
||||
|
||||
table.doxtable td {
|
||||
background-color: rgba(255,255,255,.95);
|
||||
}
|
||||
|
||||
.memberdecls {
|
||||
background: #7cb342;
|
||||
border-top: 1px solid #7cb342;
|
||||
}
|
||||
|
||||
.memberdecls .heading h2 {
|
||||
border-bottom: none;
|
||||
color: #fff;
|
||||
font-size: 110%;
|
||||
font-weight: bold;
|
||||
margin: 0 0 0 6px;
|
||||
}
|
||||
|
||||
.memberdecls tr:not(.heading) td {
|
||||
background-color: rgba(255,255,255,.95);
|
||||
}
|
||||
|
||||
h1, h2, h2.groupheader, h3, h4, h5, h6 {
|
||||
color: #212121;
|
||||
}
|
||||
|
||||
h1 {
|
||||
border-bottom: 1px solid #ebebeb;
|
||||
font: 400 28px/32px Roboto,sans-serif;
|
||||
letter-spacing: -.01em;
|
||||
margin: 40px 0 20px;
|
||||
padding-bottom: 3px;
|
||||
}
|
||||
|
||||
h2, h2.groupheader {
|
||||
border-bottom: 1px solid #ebebeb;
|
||||
font: 400 23px/32px Roboto,sans-serif;
|
||||
letter-spacing: -.01em;
|
||||
margin: 40px 0 20px;
|
||||
padding-bottom: 3px;
|
||||
}
|
||||
|
||||
h3 {
|
||||
font: 500 20px/32px Roboto,sans-serif;
|
||||
margin: 32px 0 16px;
|
||||
}
|
||||
|
||||
h4 {
|
||||
font: 500 18px/32px Roboto,sans-serif;
|
||||
margin: 32px 0 16px;
|
||||
}
|
||||
|
||||
ol,
|
||||
ul {
|
||||
margin: 0;
|
||||
padding-left: 40px;
|
||||
}
|
||||
|
||||
ol {
|
||||
list-style: decimal outside;
|
||||
}
|
||||
|
||||
ol ol {
|
||||
list-style-type: lower-alpha;
|
||||
}
|
||||
|
||||
ol ol ol {
|
||||
list-style-type: lower-roman;
|
||||
}
|
||||
|
||||
ul {
|
||||
list-style: disc outside;
|
||||
}
|
||||
|
||||
li,
|
||||
li p {
|
||||
margin: 8px 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
div.summary
|
||||
{
|
||||
float: none;
|
||||
font-size: 8pt;
|
||||
padding-left: 5px;
|
||||
width: calc(100% - 10px);
|
||||
text-align: left;
|
||||
display: block;
|
||||
}
|
||||
|
||||
div.ingroups {
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
div.fragment {
|
||||
border: 1px solid #ddd;
|
||||
color: #455a64;
|
||||
font: 14px/20px Roboto Mono, monospace;
|
||||
padding: 8px;
|
||||
}
|
||||
|
||||
div.line {
|
||||
line-height: 1.5;
|
||||
font-size: inherit;
|
||||
}
|
||||
|
||||
code, pre {
|
||||
color: #455a64;
|
||||
background: #f7f7f7;
|
||||
font: 400 100%/1 Roboto Mono,monospace;
|
||||
padding: 1px 4px;
|
||||
}
|
||||
|
||||
span.preprocessor, span.comment {
|
||||
color: #0b8043;
|
||||
}
|
||||
|
||||
span.keywordtype {
|
||||
color: #0097a7;
|
||||
}
|
||||
|
||||
.paramname {
|
||||
color: #ef6c00;
|
||||
}
|
||||
|
||||
.memTemplParams {
|
||||
color: #ef6c00;
|
||||
}
|
||||
|
||||
span.mlabel {
|
||||
background: rgba(255,255,255,.25);
|
||||
border: none;
|
||||
}
|
||||
|
||||
blockquote {
|
||||
border: 1px solid #ddd;
|
||||
}
|
||||
703
go/builder.go
Normal file
703
go/builder.go
Normal file
@@ -0,0 +1,703 @@
|
||||
package flatbuffers
|
||||
|
||||
// Builder is a state machine for creating FlatBuffer objects.
|
||||
// Use a Builder to construct object(s) starting from leaf nodes.
|
||||
//
|
||||
// A Builder constructs byte buffers in a last-first manner for simplicity and
|
||||
// performance.
|
||||
type Builder struct {
|
||||
Bytes []byte
|
||||
|
||||
minalign int
|
||||
vtable []UOffsetT
|
||||
objectEnd UOffsetT
|
||||
insideObject bool
|
||||
vtables []UOffsetT
|
||||
head UOffsetT
|
||||
}
|
||||
|
||||
// NewBuilder initializes a Builder of size `initial_size`.
|
||||
// The internal buffer is grown as needed.
|
||||
func NewBuilder(initialSize int) *Builder {
|
||||
if initialSize <= 0 {
|
||||
initialSize = 0
|
||||
}
|
||||
|
||||
b := &Builder{}
|
||||
b.Bytes = make([]byte, initialSize)
|
||||
b.head = UOffsetT(initialSize)
|
||||
b.minalign = 1
|
||||
b.vtables = make([]UOffsetT, 0, 16) // sensible default capacity
|
||||
|
||||
return b
|
||||
}
|
||||
|
||||
// Reset truncates the underlying Builder buffer, facilitating alloc-free
|
||||
// reuse of a Builder.
|
||||
func (b *Builder) Reset() {
|
||||
if b.Bytes != nil {
|
||||
b.Bytes = b.Bytes[:cap(b.Bytes)]
|
||||
}
|
||||
|
||||
if b.vtables != nil {
|
||||
b.vtables = b.vtables[:0]
|
||||
}
|
||||
|
||||
if b.vtable != nil {
|
||||
b.vtable = b.vtable[:0]
|
||||
}
|
||||
|
||||
b.head = UOffsetT(len(b.Bytes))
|
||||
b.minalign = 1
|
||||
}
|
||||
|
||||
// StartObject initializes bookkeeping for writing a new object.
|
||||
func (b *Builder) StartObject(numfields int) {
|
||||
b.notNested()
|
||||
b.insideObject = true
|
||||
|
||||
// use 32-bit offsets so that arithmetic doesn't overflow.
|
||||
if cap(b.vtable) < numfields || b.vtable == nil {
|
||||
b.vtable = make([]UOffsetT, numfields)
|
||||
} else {
|
||||
b.vtable = b.vtable[:numfields]
|
||||
for i := 0; i < len(b.vtable); i++ {
|
||||
b.vtable[i] = 0
|
||||
}
|
||||
}
|
||||
|
||||
b.objectEnd = b.Offset()
|
||||
b.minalign = 1
|
||||
}
|
||||
|
||||
// WriteVtable serializes the vtable for the current object, if applicable.
|
||||
//
|
||||
// Before writing out the vtable, this checks pre-existing vtables for equality
|
||||
// to this one. If an equal vtable is found, point the object to the existing
|
||||
// vtable and return.
|
||||
//
|
||||
// Because vtable values are sensitive to alignment of object data, not all
|
||||
// logically-equal vtables will be deduplicated.
|
||||
//
|
||||
// A vtable has the following format:
|
||||
// <VOffsetT: size of the vtable in bytes, including this value>
|
||||
// <VOffsetT: size of the object in bytes, including the vtable offset>
|
||||
// <VOffsetT: offset for a field> * N, where N is the number of fields in
|
||||
// the schema for this type. Includes deprecated fields.
|
||||
// Thus, a vtable is made of 2 + N elements, each SizeVOffsetT bytes wide.
|
||||
//
|
||||
// An object has the following format:
|
||||
// <SOffsetT: offset to this object's vtable (may be negative)>
|
||||
// <byte: data>+
|
||||
func (b *Builder) WriteVtable() (n UOffsetT) {
|
||||
// Prepend a zero scalar to the object. Later in this function we'll
|
||||
// write an offset here that points to the object's vtable:
|
||||
b.PrependSOffsetT(0)
|
||||
|
||||
objectOffset := b.Offset()
|
||||
existingVtable := UOffsetT(0)
|
||||
|
||||
// Search backwards through existing vtables, because similar vtables
|
||||
// are likely to have been recently appended. See
|
||||
// BenchmarkVtableDeduplication for a case in which this heuristic
|
||||
// saves about 30% of the time used in writing objects with duplicate
|
||||
// tables.
|
||||
for i := len(b.vtables) - 1; i >= 0; i-- {
|
||||
// Find the other vtable, which is associated with `i`:
|
||||
vt2Offset := b.vtables[i]
|
||||
vt2Start := len(b.Bytes) - int(vt2Offset)
|
||||
vt2Len := GetVOffsetT(b.Bytes[vt2Start:])
|
||||
|
||||
metadata := VtableMetadataFields * SizeVOffsetT
|
||||
vt2End := vt2Start + int(vt2Len)
|
||||
vt2 := b.Bytes[vt2Start+metadata : vt2End]
|
||||
|
||||
// Compare the other vtable to the one under consideration.
|
||||
// If they are equal, store the offset and break:
|
||||
if vtableEqual(b.vtable, objectOffset, vt2) {
|
||||
existingVtable = vt2Offset
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if existingVtable == 0 {
|
||||
// Did not find a vtable, so write this one to the buffer.
|
||||
|
||||
// Write out the current vtable in reverse , because
|
||||
// serialization occurs in last-first order:
|
||||
for i := len(b.vtable) - 1; i >= 0; i-- {
|
||||
var off UOffsetT
|
||||
if b.vtable[i] != 0 {
|
||||
// Forward reference to field;
|
||||
// use 32bit number to ensure no overflow:
|
||||
off = objectOffset - b.vtable[i]
|
||||
}
|
||||
|
||||
b.PrependVOffsetT(VOffsetT(off))
|
||||
}
|
||||
|
||||
// The two metadata fields are written last.
|
||||
|
||||
// First, store the object bytesize:
|
||||
objectSize := objectOffset - b.objectEnd
|
||||
b.PrependVOffsetT(VOffsetT(objectSize))
|
||||
|
||||
// Second, store the vtable bytesize:
|
||||
vBytes := (len(b.vtable) + VtableMetadataFields) * SizeVOffsetT
|
||||
b.PrependVOffsetT(VOffsetT(vBytes))
|
||||
|
||||
// Next, write the offset to the new vtable in the
|
||||
// already-allocated SOffsetT at the beginning of this object:
|
||||
objectStart := SOffsetT(len(b.Bytes)) - SOffsetT(objectOffset)
|
||||
WriteSOffsetT(b.Bytes[objectStart:],
|
||||
SOffsetT(b.Offset())-SOffsetT(objectOffset))
|
||||
|
||||
// Finally, store this vtable in memory for future
|
||||
// deduplication:
|
||||
b.vtables = append(b.vtables, b.Offset())
|
||||
} else {
|
||||
// Found a duplicate vtable.
|
||||
|
||||
objectStart := SOffsetT(len(b.Bytes)) - SOffsetT(objectOffset)
|
||||
b.head = UOffsetT(objectStart)
|
||||
|
||||
// Write the offset to the found vtable in the
|
||||
// already-allocated SOffsetT at the beginning of this object:
|
||||
WriteSOffsetT(b.Bytes[b.head:],
|
||||
SOffsetT(existingVtable)-SOffsetT(objectOffset))
|
||||
}
|
||||
|
||||
b.vtable = b.vtable[:0]
|
||||
return objectOffset
|
||||
}
|
||||
|
||||
// EndObject writes data necessary to finish object construction.
|
||||
func (b *Builder) EndObject() UOffsetT {
|
||||
if !b.insideObject {
|
||||
panic("not in object")
|
||||
}
|
||||
n := b.WriteVtable()
|
||||
b.insideObject = false
|
||||
return n
|
||||
}
|
||||
|
||||
// Doubles the size of the byteslice, and copies the old data towards the
|
||||
// end of the new byteslice (since we build the buffer backwards).
|
||||
func (b *Builder) growByteBuffer() {
|
||||
if (int64(len(b.Bytes)) & int64(0xC0000000)) != 0 {
|
||||
panic("cannot grow buffer beyond 2 gigabytes")
|
||||
}
|
||||
newLen := len(b.Bytes) * 2
|
||||
if newLen == 0 {
|
||||
newLen = 1
|
||||
}
|
||||
|
||||
if cap(b.Bytes) >= newLen {
|
||||
b.Bytes = b.Bytes[:newLen]
|
||||
} else {
|
||||
extension := make([]byte, newLen-len(b.Bytes))
|
||||
b.Bytes = append(b.Bytes, extension...)
|
||||
}
|
||||
|
||||
middle := newLen / 2
|
||||
copy(b.Bytes[middle:], b.Bytes[:middle])
|
||||
}
|
||||
|
||||
// Head gives the start of useful data in the underlying byte buffer.
|
||||
// Note: unlike other functions, this value is interpreted as from the left.
|
||||
func (b *Builder) Head() UOffsetT {
|
||||
return b.head
|
||||
}
|
||||
|
||||
// Offset relative to the end of the buffer.
|
||||
func (b *Builder) Offset() UOffsetT {
|
||||
return UOffsetT(len(b.Bytes)) - b.head
|
||||
}
|
||||
|
||||
// Pad places zeros at the current offset.
|
||||
func (b *Builder) Pad(n int) {
|
||||
for i := 0; i < n; i++ {
|
||||
b.PlaceByte(0)
|
||||
}
|
||||
}
|
||||
|
||||
// Prep prepares to write an element of `size` after `additional_bytes`
|
||||
// have been written, e.g. if you write a string, you need to align such
|
||||
// the int length field is aligned to SizeInt32, and the string data follows it
|
||||
// directly.
|
||||
// If all you need to do is align, `additionalBytes` will be 0.
|
||||
func (b *Builder) Prep(size, additionalBytes int) {
|
||||
// Track the biggest thing we've ever aligned to.
|
||||
if size > b.minalign {
|
||||
b.minalign = size
|
||||
}
|
||||
// Find the amount of alignment needed such that `size` is properly
|
||||
// aligned after `additionalBytes`:
|
||||
alignSize := (^(len(b.Bytes) - int(b.Head()) + additionalBytes)) + 1
|
||||
alignSize &= (size - 1)
|
||||
|
||||
// Reallocate the buffer if needed:
|
||||
for int(b.head) <= alignSize+size+additionalBytes {
|
||||
oldBufSize := len(b.Bytes)
|
||||
b.growByteBuffer()
|
||||
b.head += UOffsetT(len(b.Bytes) - oldBufSize)
|
||||
}
|
||||
b.Pad(alignSize)
|
||||
}
|
||||
|
||||
// PrependSOffsetT prepends an SOffsetT, relative to where it will be written.
|
||||
func (b *Builder) PrependSOffsetT(off SOffsetT) {
|
||||
b.Prep(SizeSOffsetT, 0) // Ensure alignment is already done.
|
||||
if !(UOffsetT(off) <= b.Offset()) {
|
||||
panic("unreachable: off <= b.Offset()")
|
||||
}
|
||||
off2 := SOffsetT(b.Offset()) - off + SOffsetT(SizeSOffsetT)
|
||||
b.PlaceSOffsetT(off2)
|
||||
}
|
||||
|
||||
// PrependUOffsetT prepends an UOffsetT, relative to where it will be written.
|
||||
func (b *Builder) PrependUOffsetT(off UOffsetT) {
|
||||
b.Prep(SizeUOffsetT, 0) // Ensure alignment is already done.
|
||||
if !(off <= b.Offset()) {
|
||||
panic("unreachable: off <= b.Offset()")
|
||||
}
|
||||
off2 := b.Offset() - off + UOffsetT(SizeUOffsetT)
|
||||
b.PlaceUOffsetT(off2)
|
||||
}
|
||||
|
||||
// StartVector initializes bookkeeping for writing a new vector.
|
||||
//
|
||||
// A vector has the following format:
|
||||
// <UOffsetT: number of elements in this vector>
|
||||
// <T: data>+, where T is the type of elements of this vector.
|
||||
func (b *Builder) StartVector(elemSize, numElems, alignment int) UOffsetT {
|
||||
b.notNested()
|
||||
b.Prep(SizeUint32, elemSize*numElems)
|
||||
b.Prep(alignment, elemSize*numElems) // Just in case alignment > int.
|
||||
return b.Offset()
|
||||
}
|
||||
|
||||
// EndVector writes data necessary to finish vector construction.
|
||||
func (b *Builder) EndVector(vectorNumElems int) UOffsetT {
|
||||
// we already made space for this, so write without PrependUint32
|
||||
b.PlaceUOffsetT(UOffsetT(vectorNumElems))
|
||||
return b.Offset()
|
||||
}
|
||||
|
||||
// CreateString writes a null-terminated string as a vector.
|
||||
func (b *Builder) CreateString(s string) UOffsetT {
|
||||
b.notNested()
|
||||
|
||||
b.Prep(int(SizeUOffsetT), (len(s)+1)*SizeByte)
|
||||
b.PlaceByte(0)
|
||||
|
||||
l := UOffsetT(len(s))
|
||||
|
||||
b.head -= l
|
||||
copy(b.Bytes[b.head:b.head+l], s)
|
||||
|
||||
return b.EndVector(len(s))
|
||||
}
|
||||
|
||||
// CreateByteString writes a byte slice as a string (null-terminated).
|
||||
func (b *Builder) CreateByteString(s []byte) UOffsetT {
|
||||
b.notNested()
|
||||
|
||||
b.Prep(int(SizeUOffsetT), (len(s)+1)*SizeByte)
|
||||
b.PlaceByte(0)
|
||||
|
||||
l := UOffsetT(len(s))
|
||||
|
||||
b.head -= l
|
||||
copy(b.Bytes[b.head:b.head+l], s)
|
||||
|
||||
return b.EndVector(len(s))
|
||||
}
|
||||
|
||||
// CreateByteVector writes a ubyte vector
|
||||
func (b *Builder) CreateByteVector(v []byte) UOffsetT {
|
||||
b.Prep(int(SizeUOffsetT), len(v)*SizeByte)
|
||||
|
||||
l := UOffsetT(len(v))
|
||||
|
||||
b.head -= l
|
||||
copy(b.Bytes[b.head:b.head+l], v)
|
||||
|
||||
return b.EndVector(len(v))
|
||||
}
|
||||
|
||||
func (b *Builder) notNested() {
|
||||
// Check that no other objects are being built while making this
|
||||
// object. If not, panic:
|
||||
if b.insideObject {
|
||||
panic("non-inline data write inside of object")
|
||||
}
|
||||
}
|
||||
|
||||
func (b *Builder) nested(obj UOffsetT) {
|
||||
// Structs are always stored inline, so need to be created right
|
||||
// where they are used. You'll get this panic if you created it
|
||||
// elsewhere:
|
||||
if obj != b.Offset() {
|
||||
panic("inline data write outside of object")
|
||||
}
|
||||
}
|
||||
|
||||
// PrependBoolSlot prepends a bool onto the object at vtable slot `o`.
|
||||
// If value `x` equals default `d`, then the slot will be set to zero and no
|
||||
// other data will be written.
|
||||
func (b *Builder) PrependBoolSlot(o int, x, d bool) {
|
||||
val := byte(0)
|
||||
if x {
|
||||
val = 1
|
||||
}
|
||||
def := byte(0)
|
||||
if d {
|
||||
def = 1
|
||||
}
|
||||
b.PrependByteSlot(o, val, def)
|
||||
}
|
||||
|
||||
// PrependByteSlot prepends a byte onto the object at vtable slot `o`.
|
||||
// If value `x` equals default `d`, then the slot will be set to zero and no
|
||||
// other data will be written.
|
||||
func (b *Builder) PrependByteSlot(o int, x, d byte) {
|
||||
if x != d {
|
||||
b.PrependByte(x)
|
||||
b.Slot(o)
|
||||
}
|
||||
}
|
||||
|
||||
// PrependUint8Slot prepends a uint8 onto the object at vtable slot `o`.
|
||||
// If value `x` equals default `d`, then the slot will be set to zero and no
|
||||
// other data will be written.
|
||||
func (b *Builder) PrependUint8Slot(o int, x, d uint8) {
|
||||
if x != d {
|
||||
b.PrependUint8(x)
|
||||
b.Slot(o)
|
||||
}
|
||||
}
|
||||
|
||||
// PrependUint16Slot prepends a uint16 onto the object at vtable slot `o`.
|
||||
// If value `x` equals default `d`, then the slot will be set to zero and no
|
||||
// other data will be written.
|
||||
func (b *Builder) PrependUint16Slot(o int, x, d uint16) {
|
||||
if x != d {
|
||||
b.PrependUint16(x)
|
||||
b.Slot(o)
|
||||
}
|
||||
}
|
||||
|
||||
// PrependUint32Slot prepends a uint32 onto the object at vtable slot `o`.
|
||||
// If value `x` equals default `d`, then the slot will be set to zero and no
|
||||
// other data will be written.
|
||||
func (b *Builder) PrependUint32Slot(o int, x, d uint32) {
|
||||
if x != d {
|
||||
b.PrependUint32(x)
|
||||
b.Slot(o)
|
||||
}
|
||||
}
|
||||
|
||||
// PrependUint64Slot prepends a uint64 onto the object at vtable slot `o`.
|
||||
// If value `x` equals default `d`, then the slot will be set to zero and no
|
||||
// other data will be written.
|
||||
func (b *Builder) PrependUint64Slot(o int, x, d uint64) {
|
||||
if x != d {
|
||||
b.PrependUint64(x)
|
||||
b.Slot(o)
|
||||
}
|
||||
}
|
||||
|
||||
// PrependInt8Slot prepends a int8 onto the object at vtable slot `o`.
|
||||
// If value `x` equals default `d`, then the slot will be set to zero and no
|
||||
// other data will be written.
|
||||
func (b *Builder) PrependInt8Slot(o int, x, d int8) {
|
||||
if x != d {
|
||||
b.PrependInt8(x)
|
||||
b.Slot(o)
|
||||
}
|
||||
}
|
||||
|
||||
// PrependInt16Slot prepends a int16 onto the object at vtable slot `o`.
|
||||
// If value `x` equals default `d`, then the slot will be set to zero and no
|
||||
// other data will be written.
|
||||
func (b *Builder) PrependInt16Slot(o int, x, d int16) {
|
||||
if x != d {
|
||||
b.PrependInt16(x)
|
||||
b.Slot(o)
|
||||
}
|
||||
}
|
||||
|
||||
// PrependInt32Slot prepends a int32 onto the object at vtable slot `o`.
|
||||
// If value `x` equals default `d`, then the slot will be set to zero and no
|
||||
// other data will be written.
|
||||
func (b *Builder) PrependInt32Slot(o int, x, d int32) {
|
||||
if x != d {
|
||||
b.PrependInt32(x)
|
||||
b.Slot(o)
|
||||
}
|
||||
}
|
||||
|
||||
// PrependInt64Slot prepends a int64 onto the object at vtable slot `o`.
|
||||
// If value `x` equals default `d`, then the slot will be set to zero and no
|
||||
// other data will be written.
|
||||
func (b *Builder) PrependInt64Slot(o int, x, d int64) {
|
||||
if x != d {
|
||||
b.PrependInt64(x)
|
||||
b.Slot(o)
|
||||
}
|
||||
}
|
||||
|
||||
// PrependFloat32Slot prepends a float32 onto the object at vtable slot `o`.
|
||||
// If value `x` equals default `d`, then the slot will be set to zero and no
|
||||
// other data will be written.
|
||||
func (b *Builder) PrependFloat32Slot(o int, x, d float32) {
|
||||
if x != d {
|
||||
b.PrependFloat32(x)
|
||||
b.Slot(o)
|
||||
}
|
||||
}
|
||||
|
||||
// PrependFloat64Slot prepends a float64 onto the object at vtable slot `o`.
|
||||
// If value `x` equals default `d`, then the slot will be set to zero and no
|
||||
// other data will be written.
|
||||
func (b *Builder) PrependFloat64Slot(o int, x, d float64) {
|
||||
if x != d {
|
||||
b.PrependFloat64(x)
|
||||
b.Slot(o)
|
||||
}
|
||||
}
|
||||
|
||||
// PrependUOffsetTSlot prepends an UOffsetT onto the object at vtable slot `o`.
|
||||
// If value `x` equals default `d`, then the slot will be set to zero and no
|
||||
// other data will be written.
|
||||
func (b *Builder) PrependUOffsetTSlot(o int, x, d UOffsetT) {
|
||||
if x != d {
|
||||
b.PrependUOffsetT(x)
|
||||
b.Slot(o)
|
||||
}
|
||||
}
|
||||
|
||||
// PrependStructSlot prepends a struct onto the object at vtable slot `o`.
|
||||
// Structs are stored inline, so nothing additional is being added.
|
||||
// In generated code, `d` is always 0.
|
||||
func (b *Builder) PrependStructSlot(voffset int, x, d UOffsetT) {
|
||||
if x != d {
|
||||
b.nested(x)
|
||||
b.Slot(voffset)
|
||||
}
|
||||
}
|
||||
|
||||
// Slot sets the vtable key `voffset` to the current location in the buffer.
|
||||
func (b *Builder) Slot(slotnum int) {
|
||||
b.vtable[slotnum] = UOffsetT(b.Offset())
|
||||
}
|
||||
|
||||
// Finish finalizes a buffer, pointing to the given `rootTable`.
|
||||
func (b *Builder) Finish(rootTable UOffsetT) {
|
||||
b.Prep(b.minalign, SizeUOffsetT)
|
||||
b.PrependUOffsetT(rootTable)
|
||||
}
|
||||
|
||||
// vtableEqual compares an unwritten vtable to a written vtable.
|
||||
func vtableEqual(a []UOffsetT, objectStart UOffsetT, b []byte) bool {
|
||||
if len(a)*SizeVOffsetT != len(b) {
|
||||
return false
|
||||
}
|
||||
|
||||
for i := 0; i < len(a); i++ {
|
||||
x := GetVOffsetT(b[i*SizeVOffsetT : (i+1)*SizeVOffsetT])
|
||||
|
||||
// Skip vtable entries that indicate a default value.
|
||||
if x == 0 && a[i] == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
y := SOffsetT(objectStart) - SOffsetT(a[i])
|
||||
if SOffsetT(x) != y {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// PrependBool prepends a bool to the Builder buffer.
|
||||
// Aligns and checks for space.
|
||||
func (b *Builder) PrependBool(x bool) {
|
||||
b.Prep(SizeBool, 0)
|
||||
b.PlaceBool(x)
|
||||
}
|
||||
|
||||
// PrependUint8 prepends a uint8 to the Builder buffer.
|
||||
// Aligns and checks for space.
|
||||
func (b *Builder) PrependUint8(x uint8) {
|
||||
b.Prep(SizeUint8, 0)
|
||||
b.PlaceUint8(x)
|
||||
}
|
||||
|
||||
// PrependUint16 prepends a uint16 to the Builder buffer.
|
||||
// Aligns and checks for space.
|
||||
func (b *Builder) PrependUint16(x uint16) {
|
||||
b.Prep(SizeUint16, 0)
|
||||
b.PlaceUint16(x)
|
||||
}
|
||||
|
||||
// PrependUint32 prepends a uint32 to the Builder buffer.
|
||||
// Aligns and checks for space.
|
||||
func (b *Builder) PrependUint32(x uint32) {
|
||||
b.Prep(SizeUint32, 0)
|
||||
b.PlaceUint32(x)
|
||||
}
|
||||
|
||||
// PrependUint64 prepends a uint64 to the Builder buffer.
|
||||
// Aligns and checks for space.
|
||||
func (b *Builder) PrependUint64(x uint64) {
|
||||
b.Prep(SizeUint64, 0)
|
||||
b.PlaceUint64(x)
|
||||
}
|
||||
|
||||
// PrependInt8 prepends a int8 to the Builder buffer.
|
||||
// Aligns and checks for space.
|
||||
func (b *Builder) PrependInt8(x int8) {
|
||||
b.Prep(SizeInt8, 0)
|
||||
b.PlaceInt8(x)
|
||||
}
|
||||
|
||||
// PrependInt16 prepends a int16 to the Builder buffer.
|
||||
// Aligns and checks for space.
|
||||
func (b *Builder) PrependInt16(x int16) {
|
||||
b.Prep(SizeInt16, 0)
|
||||
b.PlaceInt16(x)
|
||||
}
|
||||
|
||||
// PrependInt32 prepends a int32 to the Builder buffer.
|
||||
// Aligns and checks for space.
|
||||
func (b *Builder) PrependInt32(x int32) {
|
||||
b.Prep(SizeInt32, 0)
|
||||
b.PlaceInt32(x)
|
||||
}
|
||||
|
||||
// PrependInt64 prepends a int64 to the Builder buffer.
|
||||
// Aligns and checks for space.
|
||||
func (b *Builder) PrependInt64(x int64) {
|
||||
b.Prep(SizeInt64, 0)
|
||||
b.PlaceInt64(x)
|
||||
}
|
||||
|
||||
// PrependFloat32 prepends a float32 to the Builder buffer.
|
||||
// Aligns and checks for space.
|
||||
func (b *Builder) PrependFloat32(x float32) {
|
||||
b.Prep(SizeFloat32, 0)
|
||||
b.PlaceFloat32(x)
|
||||
}
|
||||
|
||||
// PrependFloat64 prepends a float64 to the Builder buffer.
|
||||
// Aligns and checks for space.
|
||||
func (b *Builder) PrependFloat64(x float64) {
|
||||
b.Prep(SizeFloat64, 0)
|
||||
b.PlaceFloat64(x)
|
||||
}
|
||||
|
||||
// PrependByte prepends a byte to the Builder buffer.
|
||||
// Aligns and checks for space.
|
||||
func (b *Builder) PrependByte(x byte) {
|
||||
b.Prep(SizeByte, 0)
|
||||
b.PlaceByte(x)
|
||||
}
|
||||
|
||||
// PrependVOffsetT prepends a VOffsetT to the Builder buffer.
|
||||
// Aligns and checks for space.
|
||||
func (b *Builder) PrependVOffsetT(x VOffsetT) {
|
||||
b.Prep(SizeVOffsetT, 0)
|
||||
b.PlaceVOffsetT(x)
|
||||
}
|
||||
|
||||
// PlaceBool prepends a bool to the Builder, without checking for space.
|
||||
func (b *Builder) PlaceBool(x bool) {
|
||||
b.head -= UOffsetT(SizeBool)
|
||||
WriteBool(b.Bytes[b.head:], x)
|
||||
}
|
||||
|
||||
// PlaceUint8 prepends a uint8 to the Builder, without checking for space.
|
||||
func (b *Builder) PlaceUint8(x uint8) {
|
||||
b.head -= UOffsetT(SizeUint8)
|
||||
WriteUint8(b.Bytes[b.head:], x)
|
||||
}
|
||||
|
||||
// PlaceUint16 prepends a uint16 to the Builder, without checking for space.
|
||||
func (b *Builder) PlaceUint16(x uint16) {
|
||||
b.head -= UOffsetT(SizeUint16)
|
||||
WriteUint16(b.Bytes[b.head:], x)
|
||||
}
|
||||
|
||||
// PlaceUint32 prepends a uint32 to the Builder, without checking for space.
|
||||
func (b *Builder) PlaceUint32(x uint32) {
|
||||
b.head -= UOffsetT(SizeUint32)
|
||||
WriteUint32(b.Bytes[b.head:], x)
|
||||
}
|
||||
|
||||
// PlaceUint64 prepends a uint64 to the Builder, without checking for space.
|
||||
func (b *Builder) PlaceUint64(x uint64) {
|
||||
b.head -= UOffsetT(SizeUint64)
|
||||
WriteUint64(b.Bytes[b.head:], x)
|
||||
}
|
||||
|
||||
// PlaceInt8 prepends a int8 to the Builder, without checking for space.
|
||||
func (b *Builder) PlaceInt8(x int8) {
|
||||
b.head -= UOffsetT(SizeInt8)
|
||||
WriteInt8(b.Bytes[b.head:], x)
|
||||
}
|
||||
|
||||
// PlaceInt16 prepends a int16 to the Builder, without checking for space.
|
||||
func (b *Builder) PlaceInt16(x int16) {
|
||||
b.head -= UOffsetT(SizeInt16)
|
||||
WriteInt16(b.Bytes[b.head:], x)
|
||||
}
|
||||
|
||||
// PlaceInt32 prepends a int32 to the Builder, without checking for space.
|
||||
func (b *Builder) PlaceInt32(x int32) {
|
||||
b.head -= UOffsetT(SizeInt32)
|
||||
WriteInt32(b.Bytes[b.head:], x)
|
||||
}
|
||||
|
||||
// PlaceInt64 prepends a int64 to the Builder, without checking for space.
|
||||
func (b *Builder) PlaceInt64(x int64) {
|
||||
b.head -= UOffsetT(SizeInt64)
|
||||
WriteInt64(b.Bytes[b.head:], x)
|
||||
}
|
||||
|
||||
// PlaceFloat32 prepends a float32 to the Builder, without checking for space.
|
||||
func (b *Builder) PlaceFloat32(x float32) {
|
||||
b.head -= UOffsetT(SizeFloat32)
|
||||
WriteFloat32(b.Bytes[b.head:], x)
|
||||
}
|
||||
|
||||
// PlaceFloat64 prepends a float64 to the Builder, without checking for space.
|
||||
func (b *Builder) PlaceFloat64(x float64) {
|
||||
b.head -= UOffsetT(SizeFloat64)
|
||||
WriteFloat64(b.Bytes[b.head:], x)
|
||||
}
|
||||
|
||||
// PlaceByte prepends a byte to the Builder, without checking for space.
|
||||
func (b *Builder) PlaceByte(x byte) {
|
||||
b.head -= UOffsetT(SizeByte)
|
||||
WriteByte(b.Bytes[b.head:], x)
|
||||
}
|
||||
|
||||
// PlaceVOffsetT prepends a VOffsetT to the Builder, without checking for space.
|
||||
func (b *Builder) PlaceVOffsetT(x VOffsetT) {
|
||||
b.head -= UOffsetT(SizeVOffsetT)
|
||||
WriteVOffsetT(b.Bytes[b.head:], x)
|
||||
}
|
||||
|
||||
// PlaceSOffsetT prepends a SOffsetT to the Builder, without checking for space.
|
||||
func (b *Builder) PlaceSOffsetT(x SOffsetT) {
|
||||
b.head -= UOffsetT(SizeSOffsetT)
|
||||
WriteSOffsetT(b.Bytes[b.head:], x)
|
||||
}
|
||||
|
||||
// PlaceUOffsetT prepends a UOffsetT to the Builder, without checking for space.
|
||||
func (b *Builder) PlaceUOffsetT(x UOffsetT) {
|
||||
b.head -= UOffsetT(SizeUOffsetT)
|
||||
WriteUOffsetT(b.Bytes[b.head:], x)
|
||||
}
|
||||
3
go/doc.go
Normal file
3
go/doc.go
Normal file
@@ -0,0 +1,3 @@
|
||||
// Package flatbuffers provides facilities to read and write flatbuffers
|
||||
// objects.
|
||||
package flatbuffers
|
||||
216
go/encode.go
Normal file
216
go/encode.go
Normal file
@@ -0,0 +1,216 @@
|
||||
package flatbuffers
|
||||
|
||||
import (
|
||||
"math"
|
||||
)
|
||||
|
||||
type (
|
||||
// A SOffsetT stores a signed offset into arbitrary data.
|
||||
SOffsetT int32
|
||||
// A UOffsetT stores an unsigned offset into vector data.
|
||||
UOffsetT uint32
|
||||
// A VOffsetT stores an unsigned offset in a vtable.
|
||||
VOffsetT uint16
|
||||
)
|
||||
|
||||
const (
|
||||
// VtableMetadataFields is the count of metadata fields in each vtable.
|
||||
VtableMetadataFields = 2
|
||||
)
|
||||
|
||||
// GetByte decodes a little-endian byte from a byte slice.
|
||||
func GetByte(buf []byte) byte {
|
||||
return byte(GetUint8(buf))
|
||||
}
|
||||
|
||||
// GetBool decodes a little-endian bool from a byte slice.
|
||||
func GetBool(buf []byte) bool {
|
||||
return buf[0] == 1
|
||||
}
|
||||
|
||||
// GetUint8 decodes a little-endian uint8 from a byte slice.
|
||||
func GetUint8(buf []byte) (n uint8) {
|
||||
n = uint8(buf[0])
|
||||
return
|
||||
}
|
||||
|
||||
// GetUint16 decodes a little-endian uint16 from a byte slice.
|
||||
func GetUint16(buf []byte) (n uint16) {
|
||||
n |= uint16(buf[0])
|
||||
n |= uint16(buf[1]) << 8
|
||||
return
|
||||
}
|
||||
|
||||
// GetUint32 decodes a little-endian uint32 from a byte slice.
|
||||
func GetUint32(buf []byte) (n uint32) {
|
||||
n |= uint32(buf[0])
|
||||
n |= uint32(buf[1]) << 8
|
||||
n |= uint32(buf[2]) << 16
|
||||
n |= uint32(buf[3]) << 24
|
||||
return
|
||||
}
|
||||
|
||||
// GetUint64 decodes a little-endian uint64 from a byte slice.
|
||||
func GetUint64(buf []byte) (n uint64) {
|
||||
n |= uint64(buf[0])
|
||||
n |= uint64(buf[1]) << 8
|
||||
n |= uint64(buf[2]) << 16
|
||||
n |= uint64(buf[3]) << 24
|
||||
n |= uint64(buf[4]) << 32
|
||||
n |= uint64(buf[5]) << 40
|
||||
n |= uint64(buf[6]) << 48
|
||||
n |= uint64(buf[7]) << 56
|
||||
return
|
||||
}
|
||||
|
||||
// GetInt8 decodes a little-endian int8 from a byte slice.
|
||||
func GetInt8(buf []byte) (n int8) {
|
||||
n = int8(buf[0])
|
||||
return
|
||||
}
|
||||
|
||||
// GetInt16 decodes a little-endian int16 from a byte slice.
|
||||
func GetInt16(buf []byte) (n int16) {
|
||||
n |= int16(buf[0])
|
||||
n |= int16(buf[1]) << 8
|
||||
return
|
||||
}
|
||||
|
||||
// GetInt32 decodes a little-endian int32 from a byte slice.
|
||||
func GetInt32(buf []byte) (n int32) {
|
||||
n |= int32(buf[0])
|
||||
n |= int32(buf[1]) << 8
|
||||
n |= int32(buf[2]) << 16
|
||||
n |= int32(buf[3]) << 24
|
||||
return
|
||||
}
|
||||
|
||||
// GetInt64 decodes a little-endian int64 from a byte slice.
|
||||
func GetInt64(buf []byte) (n int64) {
|
||||
n |= int64(buf[0])
|
||||
n |= int64(buf[1]) << 8
|
||||
n |= int64(buf[2]) << 16
|
||||
n |= int64(buf[3]) << 24
|
||||
n |= int64(buf[4]) << 32
|
||||
n |= int64(buf[5]) << 40
|
||||
n |= int64(buf[6]) << 48
|
||||
n |= int64(buf[7]) << 56
|
||||
return
|
||||
}
|
||||
|
||||
// GetFloat32 decodes a little-endian float32 from a byte slice.
|
||||
func GetFloat32(buf []byte) float32 {
|
||||
x := GetUint32(buf)
|
||||
return math.Float32frombits(x)
|
||||
}
|
||||
|
||||
// GetFloat64 decodes a little-endian float64 from a byte slice.
|
||||
func GetFloat64(buf []byte) float64 {
|
||||
x := GetUint64(buf)
|
||||
return math.Float64frombits(x)
|
||||
}
|
||||
|
||||
// GetUOffsetT decodes a little-endian UOffsetT from a byte slice.
|
||||
func GetUOffsetT(buf []byte) UOffsetT {
|
||||
return UOffsetT(GetInt32(buf))
|
||||
}
|
||||
|
||||
// GetSOffsetT decodes a little-endian SOffsetT from a byte slice.
|
||||
func GetSOffsetT(buf []byte) SOffsetT {
|
||||
return SOffsetT(GetInt32(buf))
|
||||
}
|
||||
|
||||
// GetVOffsetT decodes a little-endian VOffsetT from a byte slice.
|
||||
func GetVOffsetT(buf []byte) VOffsetT {
|
||||
return VOffsetT(GetUint16(buf))
|
||||
}
|
||||
|
||||
// WriteByte encodes a little-endian uint8 into a byte slice.
|
||||
func WriteByte(buf []byte, n byte) {
|
||||
WriteUint8(buf, uint8(n))
|
||||
}
|
||||
|
||||
// WriteBool encodes a little-endian bool into a byte slice.
|
||||
func WriteBool(buf []byte, b bool) {
|
||||
buf[0] = 0
|
||||
if b {
|
||||
buf[0] = 1
|
||||
}
|
||||
}
|
||||
|
||||
// WriteUint8 encodes a little-endian uint8 into a byte slice.
|
||||
func WriteUint8(buf []byte, n uint8) {
|
||||
buf[0] = byte(n)
|
||||
}
|
||||
|
||||
// WriteUint16 encodes a little-endian uint16 into a byte slice.
|
||||
func WriteUint16(buf []byte, n uint16) {
|
||||
buf[0] = byte(n)
|
||||
buf[1] = byte(n >> 8)
|
||||
}
|
||||
|
||||
// WriteUint32 encodes a little-endian uint32 into a byte slice.
|
||||
func WriteUint32(buf []byte, n uint32) {
|
||||
buf[0] = byte(n)
|
||||
buf[1] = byte(n >> 8)
|
||||
buf[2] = byte(n >> 16)
|
||||
buf[3] = byte(n >> 24)
|
||||
}
|
||||
|
||||
// WriteUint64 encodes a little-endian uint64 into a byte slice.
|
||||
func WriteUint64(buf []byte, n uint64) {
|
||||
for i := uint(0); i < uint(SizeUint64); i++ {
|
||||
buf[i] = byte(n >> (i * 8))
|
||||
}
|
||||
}
|
||||
|
||||
// WriteInt8 encodes a little-endian int8 into a byte slice.
|
||||
func WriteInt8(buf []byte, n int8) {
|
||||
buf[0] = byte(n)
|
||||
}
|
||||
|
||||
// WriteInt16 encodes a little-endian int16 into a byte slice.
|
||||
func WriteInt16(buf []byte, n int16) {
|
||||
buf[0] = byte(n)
|
||||
buf[1] = byte(n >> 8)
|
||||
}
|
||||
|
||||
// WriteInt32 encodes a little-endian int32 into a byte slice.
|
||||
func WriteInt32(buf []byte, n int32) {
|
||||
buf[0] = byte(n)
|
||||
buf[1] = byte(n >> 8)
|
||||
buf[2] = byte(n >> 16)
|
||||
buf[3] = byte(n >> 24)
|
||||
}
|
||||
|
||||
// WriteInt64 encodes a little-endian int64 into a byte slice.
|
||||
func WriteInt64(buf []byte, n int64) {
|
||||
for i := uint(0); i < uint(SizeInt64); i++ {
|
||||
buf[i] = byte(n >> (i * 8))
|
||||
}
|
||||
}
|
||||
|
||||
// WriteFloat32 encodes a little-endian float32 into a byte slice.
|
||||
func WriteFloat32(buf []byte, n float32) {
|
||||
WriteUint32(buf, math.Float32bits(n))
|
||||
}
|
||||
|
||||
// WriteFloat64 encodes a little-endian float64 into a byte slice.
|
||||
func WriteFloat64(buf []byte, n float64) {
|
||||
WriteUint64(buf, math.Float64bits(n))
|
||||
}
|
||||
|
||||
// WriteVOffsetT encodes a little-endian VOffsetT into a byte slice.
|
||||
func WriteVOffsetT(buf []byte, n VOffsetT) {
|
||||
WriteUint16(buf, uint16(n))
|
||||
}
|
||||
|
||||
// WriteSOffsetT encodes a little-endian SOffsetT into a byte slice.
|
||||
func WriteSOffsetT(buf []byte, n SOffsetT) {
|
||||
WriteInt32(buf, int32(n))
|
||||
}
|
||||
|
||||
// WriteUOffsetT encodes a little-endian UOffsetT into a byte slice.
|
||||
func WriteUOffsetT(buf []byte, n UOffsetT) {
|
||||
WriteUint32(buf, uint32(n))
|
||||
}
|
||||
8
go/struct.go
Normal file
8
go/struct.go
Normal file
@@ -0,0 +1,8 @@
|
||||
package flatbuffers
|
||||
|
||||
// Struct wraps a byte slice and provides read access to its data.
|
||||
//
|
||||
// Structs do not have a vtable.
|
||||
type Struct struct {
|
||||
Table
|
||||
}
|
||||
294
go/table.go
Normal file
294
go/table.go
Normal file
@@ -0,0 +1,294 @@
|
||||
package flatbuffers
|
||||
|
||||
// Table wraps a byte slice and provides read access to its data.
|
||||
//
|
||||
// The variable `Pos` indicates the root of the FlatBuffers object therein.
|
||||
type Table struct {
|
||||
Bytes []byte
|
||||
Pos UOffsetT // Always < 1<<31.
|
||||
}
|
||||
|
||||
// Offset provides access into the Table's vtable.
|
||||
//
|
||||
// Deprecated fields are ignored by checking against the vtable's length.
|
||||
func (t *Table) Offset(vtableOffset VOffsetT) VOffsetT {
|
||||
vtable := UOffsetT(SOffsetT(t.Pos) - t.GetSOffsetT(t.Pos))
|
||||
if vtableOffset < t.GetVOffsetT(vtable) {
|
||||
return t.GetVOffsetT(vtable + UOffsetT(vtableOffset))
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// Indirect retrieves the relative offset stored at `offset`.
|
||||
func (t *Table) Indirect(off UOffsetT) UOffsetT {
|
||||
return off + GetUOffsetT(t.Bytes[off:])
|
||||
}
|
||||
|
||||
// String gets a string from data stored inside the flatbuffer.
|
||||
func (t *Table) String(off UOffsetT) string {
|
||||
return string(t.ByteVector(off))
|
||||
}
|
||||
|
||||
// ByteVector gets a byte slice from data stored inside the flatbuffer.
|
||||
func (t *Table) ByteVector(off UOffsetT) []byte {
|
||||
off += GetUOffsetT(t.Bytes[off:])
|
||||
start := off + UOffsetT(SizeUOffsetT)
|
||||
length := GetUOffsetT(t.Bytes[off:])
|
||||
return t.Bytes[start : start+length]
|
||||
}
|
||||
|
||||
// VectorLen retrieves the length of the vector whose offset is stored at
|
||||
// "off" in this object.
|
||||
func (t *Table) VectorLen(off UOffsetT) int {
|
||||
off += t.Pos
|
||||
off += GetUOffsetT(t.Bytes[off:])
|
||||
return int(GetUOffsetT(t.Bytes[off:]))
|
||||
}
|
||||
|
||||
// Vector retrieves the start of data of the vector whose offset is stored
|
||||
// at "off" in this object.
|
||||
func (t *Table) Vector(off UOffsetT) UOffsetT {
|
||||
off += t.Pos
|
||||
x := off + GetUOffsetT(t.Bytes[off:])
|
||||
// data starts after metadata containing the vector length
|
||||
x += UOffsetT(SizeUOffsetT)
|
||||
return x
|
||||
}
|
||||
|
||||
// Union initializes any Table-derived type to point to the union at the given
|
||||
// offset.
|
||||
func (t *Table) Union(t2 *Table, off UOffsetT) {
|
||||
off += t.Pos
|
||||
t2.Pos = off + t.GetUOffsetT(off)
|
||||
t2.Bytes = t.Bytes
|
||||
}
|
||||
|
||||
// GetBool retrieves a bool at the given offset.
|
||||
func (t *Table) GetBool(off UOffsetT) bool {
|
||||
return GetBool(t.Bytes[off:])
|
||||
}
|
||||
|
||||
// GetByte retrieves a byte at the given offset.
|
||||
func (t *Table) GetByte(off UOffsetT) byte {
|
||||
return GetByte(t.Bytes[off:])
|
||||
}
|
||||
|
||||
// GetUint8 retrieves a uint8 at the given offset.
|
||||
func (t *Table) GetUint8(off UOffsetT) uint8 {
|
||||
return GetUint8(t.Bytes[off:])
|
||||
}
|
||||
|
||||
// GetUint16 retrieves a uint16 at the given offset.
|
||||
func (t *Table) GetUint16(off UOffsetT) uint16 {
|
||||
return GetUint16(t.Bytes[off:])
|
||||
}
|
||||
|
||||
// GetUint32 retrieves a uint32 at the given offset.
|
||||
func (t *Table) GetUint32(off UOffsetT) uint32 {
|
||||
return GetUint32(t.Bytes[off:])
|
||||
}
|
||||
|
||||
// GetUint64 retrieves a uint64 at the given offset.
|
||||
func (t *Table) GetUint64(off UOffsetT) uint64 {
|
||||
return GetUint64(t.Bytes[off:])
|
||||
}
|
||||
|
||||
// GetInt8 retrieves a int8 at the given offset.
|
||||
func (t *Table) GetInt8(off UOffsetT) int8 {
|
||||
return GetInt8(t.Bytes[off:])
|
||||
}
|
||||
|
||||
// GetInt16 retrieves a int16 at the given offset.
|
||||
func (t *Table) GetInt16(off UOffsetT) int16 {
|
||||
return GetInt16(t.Bytes[off:])
|
||||
}
|
||||
|
||||
// GetInt32 retrieves a int32 at the given offset.
|
||||
func (t *Table) GetInt32(off UOffsetT) int32 {
|
||||
return GetInt32(t.Bytes[off:])
|
||||
}
|
||||
|
||||
// GetInt64 retrieves a int64 at the given offset.
|
||||
func (t *Table) GetInt64(off UOffsetT) int64 {
|
||||
return GetInt64(t.Bytes[off:])
|
||||
}
|
||||
|
||||
// GetFloat32 retrieves a float32 at the given offset.
|
||||
func (t *Table) GetFloat32(off UOffsetT) float32 {
|
||||
return GetFloat32(t.Bytes[off:])
|
||||
}
|
||||
|
||||
// GetFloat64 retrieves a float64 at the given offset.
|
||||
func (t *Table) GetFloat64(off UOffsetT) float64 {
|
||||
return GetFloat64(t.Bytes[off:])
|
||||
}
|
||||
|
||||
// GetUOffsetT retrieves a UOffsetT at the given offset.
|
||||
func (t *Table) GetUOffsetT(off UOffsetT) UOffsetT {
|
||||
return GetUOffsetT(t.Bytes[off:])
|
||||
}
|
||||
|
||||
// GetVOffsetT retrieves a VOffsetT at the given offset.
|
||||
func (t *Table) GetVOffsetT(off UOffsetT) VOffsetT {
|
||||
return GetVOffsetT(t.Bytes[off:])
|
||||
}
|
||||
|
||||
// GetSOffsetT retrieves a SOffsetT at the given offset.
|
||||
func (t *Table) GetSOffsetT(off UOffsetT) SOffsetT {
|
||||
return GetSOffsetT(t.Bytes[off:])
|
||||
}
|
||||
|
||||
// GetBoolSlot retrieves the bool that the given vtable location
|
||||
// points to. If the vtable value is zero, the default value `d`
|
||||
// will be returned.
|
||||
func (t *Table) GetBoolSlot(slot VOffsetT, d bool) bool {
|
||||
off := t.Offset(slot)
|
||||
if off == 0 {
|
||||
return d
|
||||
}
|
||||
|
||||
return t.GetBool(t.Pos + UOffsetT(off))
|
||||
}
|
||||
|
||||
// GetByteSlot retrieves the byte that the given vtable location
|
||||
// points to. If the vtable value is zero, the default value `d`
|
||||
// will be returned.
|
||||
func (t *Table) GetByteSlot(slot VOffsetT, d byte) byte {
|
||||
off := t.Offset(slot)
|
||||
if off == 0 {
|
||||
return d
|
||||
}
|
||||
|
||||
return t.GetByte(t.Pos + UOffsetT(off))
|
||||
}
|
||||
|
||||
// GetInt8Slot retrieves the int8 that the given vtable location
|
||||
// points to. If the vtable value is zero, the default value `d`
|
||||
// will be returned.
|
||||
func (t *Table) GetInt8Slot(slot VOffsetT, d int8) int8 {
|
||||
off := t.Offset(slot)
|
||||
if off == 0 {
|
||||
return d
|
||||
}
|
||||
|
||||
return t.GetInt8(t.Pos + UOffsetT(off))
|
||||
}
|
||||
|
||||
// GetUint8Slot retrieves the uint8 that the given vtable location
|
||||
// points to. If the vtable value is zero, the default value `d`
|
||||
// will be returned.
|
||||
func (t *Table) GetUint8Slot(slot VOffsetT, d uint8) uint8 {
|
||||
off := t.Offset(slot)
|
||||
if off == 0 {
|
||||
return d
|
||||
}
|
||||
|
||||
return t.GetUint8(t.Pos + UOffsetT(off))
|
||||
}
|
||||
|
||||
// GetInt16Slot retrieves the int16 that the given vtable location
|
||||
// points to. If the vtable value is zero, the default value `d`
|
||||
// will be returned.
|
||||
func (t *Table) GetInt16Slot(slot VOffsetT, d int16) int16 {
|
||||
off := t.Offset(slot)
|
||||
if off == 0 {
|
||||
return d
|
||||
}
|
||||
|
||||
return t.GetInt16(t.Pos + UOffsetT(off))
|
||||
}
|
||||
|
||||
// GetUint16Slot retrieves the uint16 that the given vtable location
|
||||
// points to. If the vtable value is zero, the default value `d`
|
||||
// will be returned.
|
||||
func (t *Table) GetUint16Slot(slot VOffsetT, d uint16) uint16 {
|
||||
off := t.Offset(slot)
|
||||
if off == 0 {
|
||||
return d
|
||||
}
|
||||
|
||||
return t.GetUint16(t.Pos + UOffsetT(off))
|
||||
}
|
||||
|
||||
// GetInt32Slot retrieves the int32 that the given vtable location
|
||||
// points to. If the vtable value is zero, the default value `d`
|
||||
// will be returned.
|
||||
func (t *Table) GetInt32Slot(slot VOffsetT, d int32) int32 {
|
||||
off := t.Offset(slot)
|
||||
if off == 0 {
|
||||
return d
|
||||
}
|
||||
|
||||
return t.GetInt32(t.Pos + UOffsetT(off))
|
||||
}
|
||||
|
||||
// GetUint32Slot retrieves the uint32 that the given vtable location
|
||||
// points to. If the vtable value is zero, the default value `d`
|
||||
// will be returned.
|
||||
func (t *Table) GetUint32Slot(slot VOffsetT, d uint32) uint32 {
|
||||
off := t.Offset(slot)
|
||||
if off == 0 {
|
||||
return d
|
||||
}
|
||||
|
||||
return t.GetUint32(t.Pos + UOffsetT(off))
|
||||
}
|
||||
|
||||
// GetInt64Slot retrieves the int64 that the given vtable location
|
||||
// points to. If the vtable value is zero, the default value `d`
|
||||
// will be returned.
|
||||
func (t *Table) GetInt64Slot(slot VOffsetT, d int64) int64 {
|
||||
off := t.Offset(slot)
|
||||
if off == 0 {
|
||||
return d
|
||||
}
|
||||
|
||||
return t.GetInt64(t.Pos + UOffsetT(off))
|
||||
}
|
||||
|
||||
// GetUint64Slot retrieves the uint64 that the given vtable location
|
||||
// points to. If the vtable value is zero, the default value `d`
|
||||
// will be returned.
|
||||
func (t *Table) GetUint64Slot(slot VOffsetT, d uint64) uint64 {
|
||||
off := t.Offset(slot)
|
||||
if off == 0 {
|
||||
return d
|
||||
}
|
||||
|
||||
return t.GetUint64(t.Pos + UOffsetT(off))
|
||||
}
|
||||
|
||||
// GetFloat32Slot retrieves the float32 that the given vtable location
|
||||
// points to. If the vtable value is zero, the default value `d`
|
||||
// will be returned.
|
||||
func (t *Table) GetFloat32Slot(slot VOffsetT, d float32) float32 {
|
||||
off := t.Offset(slot)
|
||||
if off == 0 {
|
||||
return d
|
||||
}
|
||||
|
||||
return t.GetFloat32(t.Pos + UOffsetT(off))
|
||||
}
|
||||
|
||||
// GetFloat64Slot retrieves the float64 that the given vtable location
|
||||
// points to. If the vtable value is zero, the default value `d`
|
||||
// will be returned.
|
||||
func (t *Table) GetFloat64Slot(slot VOffsetT, d float64) float64 {
|
||||
off := t.Offset(slot)
|
||||
if off == 0 {
|
||||
return d
|
||||
}
|
||||
|
||||
return t.GetFloat64(t.Pos + UOffsetT(off))
|
||||
}
|
||||
|
||||
// GetVOffsetTSlot retrieves the VOffsetT that the given vtable location
|
||||
// points to. If the vtable value is zero, the default value `d`
|
||||
// will be returned.
|
||||
func (t *Table) GetVOffsetTSlot(slot VOffsetT, d VOffsetT) VOffsetT {
|
||||
off := t.Offset(slot)
|
||||
if off == 0 {
|
||||
return d
|
||||
}
|
||||
return VOffsetT(off)
|
||||
}
|
||||
45
go/unsafe.go
Normal file
45
go/unsafe.go
Normal file
@@ -0,0 +1,45 @@
|
||||
package flatbuffers
|
||||
|
||||
import "unsafe"
|
||||
|
||||
var (
|
||||
// See http://golang.org/ref/spec#Numeric_types
|
||||
|
||||
// SizeUint8 is the byte size of a uint8.
|
||||
SizeUint8 = int(unsafe.Sizeof(uint8(0)))
|
||||
// SizeUint16 is the byte size of a uint16.
|
||||
SizeUint16 = int(unsafe.Sizeof(uint16(0)))
|
||||
// SizeUint32 is the byte size of a uint32.
|
||||
SizeUint32 = int(unsafe.Sizeof(uint32(0)))
|
||||
// SizeUint64 is the byte size of a uint64.
|
||||
SizeUint64 = int(unsafe.Sizeof(uint64(0)))
|
||||
|
||||
// SizeInt8 is the byte size of a int8.
|
||||
SizeInt8 = int(unsafe.Sizeof(int8(0)))
|
||||
// SizeInt16 is the byte size of a int16.
|
||||
SizeInt16 = int(unsafe.Sizeof(int16(0)))
|
||||
// SizeInt32 is the byte size of a int32.
|
||||
SizeInt32 = int(unsafe.Sizeof(int32(0)))
|
||||
// SizeInt64 is the byte size of a int64.
|
||||
SizeInt64 = int(unsafe.Sizeof(int64(0)))
|
||||
|
||||
// SizeFloat32 is the byte size of a float32.
|
||||
SizeFloat32 = int(unsafe.Sizeof(float32(0)))
|
||||
// SizeFloat64 is the byte size of a float64.
|
||||
SizeFloat64 = int(unsafe.Sizeof(float64(0)))
|
||||
|
||||
// SizeByte is the byte size of a byte.
|
||||
// The `byte` type is aliased (by Go definition) to uint8.
|
||||
SizeByte = SizeUint8
|
||||
|
||||
// SizeBool is the byte size of a bool.
|
||||
// The `bool` type is aliased (by flatbuffers convention) to uint8.
|
||||
SizeBool = SizeUint8
|
||||
|
||||
// SizeSOffsetT is the byte size of an SOffsetT.
|
||||
SizeSOffsetT = int(unsafe.Sizeof(SOffsetT(0)))
|
||||
// SizeUOffsetT is the byte size of an UOffsetT.
|
||||
SizeUOffsetT = int(unsafe.Sizeof(UOffsetT(0)))
|
||||
// SizeVOffsetT is the byte size of an VOffsetT.
|
||||
SizeVOffsetT = int(unsafe.Sizeof(VOffsetT(0)))
|
||||
)
|
||||
File diff suppressed because it is too large
Load Diff
105
include/flatbuffers/hash.h
Normal file
105
include/flatbuffers/hash.h
Normal file
@@ -0,0 +1,105 @@
|
||||
/*
|
||||
* Copyright 2015 Google Inc. All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#ifndef FLATBUFFERS_HASH_H_
|
||||
#define FLATBUFFERS_HASH_H_
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
|
||||
namespace flatbuffers {
|
||||
|
||||
template <typename T>
|
||||
struct FnvTraits {
|
||||
static const T kFnvPrime;
|
||||
static const T kOffsetBasis;
|
||||
};
|
||||
|
||||
template <>
|
||||
struct FnvTraits<uint32_t> {
|
||||
static const uint32_t kFnvPrime = 0x01000193;
|
||||
static const uint32_t kOffsetBasis = 0x811C9DC5;
|
||||
};
|
||||
|
||||
template <>
|
||||
struct FnvTraits<uint64_t> {
|
||||
static const uint64_t kFnvPrime = 0x00000100000001b3;
|
||||
static const uint64_t kOffsetBasis = 0xcbf29ce484222645;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
T HashFnv1(const char *input) {
|
||||
T hash = FnvTraits<T>::kOffsetBasis;
|
||||
for (const char *c = input; *c; ++c) {
|
||||
hash *= FnvTraits<T>::kFnvPrime;
|
||||
hash ^= static_cast<unsigned char>(*c);
|
||||
}
|
||||
return hash;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
T HashFnv1a(const char *input) {
|
||||
T hash = FnvTraits<T>::kOffsetBasis;
|
||||
for (const char *c = input; *c; ++c) {
|
||||
hash ^= static_cast<unsigned char>(*c);
|
||||
hash *= FnvTraits<T>::kFnvPrime;
|
||||
}
|
||||
return hash;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
struct NamedHashFunction {
|
||||
const char *name;
|
||||
|
||||
typedef T (*HashFunction)(const char*);
|
||||
HashFunction function;
|
||||
};
|
||||
|
||||
const NamedHashFunction<uint32_t> kHashFunctions32[] = {
|
||||
{ "fnv1_32", HashFnv1<uint32_t> },
|
||||
{ "fnv1a_32", HashFnv1a<uint32_t> },
|
||||
};
|
||||
|
||||
const NamedHashFunction<uint64_t> kHashFunctions64[] = {
|
||||
{ "fnv1_64", HashFnv1<uint64_t> },
|
||||
{ "fnv1a_64", HashFnv1a<uint64_t> },
|
||||
};
|
||||
|
||||
inline NamedHashFunction<uint32_t>::HashFunction FindHashFunction32(
|
||||
const char *name) {
|
||||
std::size_t size = sizeof(kHashFunctions32) / sizeof(kHashFunctions32[0]);
|
||||
for (std::size_t i = 0; i < size; ++i) {
|
||||
if (std::strcmp(name, kHashFunctions32[i].name) == 0) {
|
||||
return kHashFunctions32[i].function;
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
inline NamedHashFunction<uint64_t>::HashFunction FindHashFunction64(
|
||||
const char *name) {
|
||||
std::size_t size = sizeof(kHashFunctions64) / sizeof(kHashFunctions64[0]);
|
||||
for (std::size_t i = 0; i < size; ++i) {
|
||||
if (std::strcmp(name, kHashFunctions64[i].name) == 0) {
|
||||
return kHashFunctions64[i].function;
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
} // namespace flatbuffers
|
||||
|
||||
#endif // FLATBUFFERS_HASH_H_
|
||||
@@ -18,9 +18,14 @@
|
||||
#define FLATBUFFERS_IDL_H_
|
||||
|
||||
#include <map>
|
||||
#include <set>
|
||||
#include <stack>
|
||||
#include <memory>
|
||||
#include <functional>
|
||||
|
||||
#include "flatbuffers/flatbuffers.h"
|
||||
#include "flatbuffers/hash.h"
|
||||
#include "flatbuffers/reflection.h"
|
||||
|
||||
// This file defines the data types representing a parsed IDL (Interface
|
||||
// Definition Language) / schema file.
|
||||
@@ -31,31 +36,39 @@ namespace flatbuffers {
|
||||
// Additionally, Parser::ParseType assumes bool..string is a contiguous range
|
||||
// of type tokens.
|
||||
#define FLATBUFFERS_GEN_TYPES_SCALAR(TD) \
|
||||
TD(NONE, "", uint8_t, byte ) \
|
||||
TD(UTYPE, "", uint8_t, byte ) /* begin scalars, ints */ \
|
||||
TD(BOOL, "bool", uint8_t, byte ) \
|
||||
TD(CHAR, "byte", int8_t, byte ) \
|
||||
TD(UCHAR, "ubyte", uint8_t, byte ) \
|
||||
TD(SHORT, "short", int16_t, short ) \
|
||||
TD(USHORT, "ushort", uint16_t, short ) \
|
||||
TD(INT, "int", int32_t, int ) \
|
||||
TD(UINT, "uint", uint32_t, int ) \
|
||||
TD(LONG, "long", int64_t, long ) \
|
||||
TD(ULONG, "ulong", uint64_t, long ) /* end ints */ \
|
||||
TD(FLOAT, "float", float, float ) /* begin floats */ \
|
||||
TD(DOUBLE, "double", double, double) /* end floats, scalars */
|
||||
TD(NONE, "", uint8_t, byte, byte, byte, uint8) \
|
||||
TD(UTYPE, "", uint8_t, byte, byte, byte, uint8) /* begin scalar/int */ \
|
||||
TD(BOOL, "bool", uint8_t, boolean,byte, bool, bool) \
|
||||
TD(CHAR, "byte", int8_t, byte, int8, sbyte, int8) \
|
||||
TD(UCHAR, "ubyte", uint8_t, byte, byte, byte, uint8) \
|
||||
TD(SHORT, "short", int16_t, short, int16, short, int16) \
|
||||
TD(USHORT, "ushort", uint16_t, short, uint16, ushort, uint16) \
|
||||
TD(INT, "int", int32_t, int, int32, int, int32) \
|
||||
TD(UINT, "uint", uint32_t, int, uint32, uint, uint32) \
|
||||
TD(LONG, "long", int64_t, long, int64, long, int64) \
|
||||
TD(ULONG, "ulong", uint64_t, long, uint64, ulong, uint64) /* end int */ \
|
||||
TD(FLOAT, "float", float, float, float32, float, float32) /* begin float */ \
|
||||
TD(DOUBLE, "double", double, double, float64, double, float64) /* end float/scalar */
|
||||
#define FLATBUFFERS_GEN_TYPES_POINTER(TD) \
|
||||
TD(STRING, "string", Offset<void>, int) \
|
||||
TD(VECTOR, "", Offset<void>, int) \
|
||||
TD(STRUCT, "", Offset<void>, int) \
|
||||
TD(UNION, "", Offset<void>, int)
|
||||
TD(STRING, "string", Offset<void>, int, int, StringOffset, int) \
|
||||
TD(VECTOR, "", Offset<void>, int, int, VectorOffset, int) \
|
||||
TD(STRUCT, "", Offset<void>, int, int, int, int) \
|
||||
TD(UNION, "", Offset<void>, int, int, int, int)
|
||||
|
||||
// The fields are:
|
||||
// - enum
|
||||
// - FlatBuffers schema type.
|
||||
// - C++ type.
|
||||
// - Java type.
|
||||
// - Go type.
|
||||
// - C# / .Net type.
|
||||
// - Python type.
|
||||
|
||||
// using these macros, we can now write code dealing with types just once, e.g.
|
||||
|
||||
/*
|
||||
switch (type) {
|
||||
#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE) \
|
||||
#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE, PTYPE) \
|
||||
case BASE_TYPE_ ## ENUM: \
|
||||
// do something specific to CTYPE here
|
||||
FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
|
||||
@@ -67,14 +80,18 @@ switch (type) {
|
||||
FLATBUFFERS_GEN_TYPES_SCALAR(TD) \
|
||||
FLATBUFFERS_GEN_TYPES_POINTER(TD)
|
||||
|
||||
// Create an enum for all the types above
|
||||
// Create an enum for all the types above.
|
||||
#ifdef __GNUC__
|
||||
__extension__ // Stop GCC complaining about trailing comma with -Wpendantic.
|
||||
#endif
|
||||
enum BaseType {
|
||||
#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE) BASE_TYPE_ ## ENUM,
|
||||
#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE, PTYPE) \
|
||||
BASE_TYPE_ ## ENUM,
|
||||
FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
|
||||
#undef FLATBUFFERS_TD
|
||||
};
|
||||
|
||||
#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE) \
|
||||
#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE, PTYPE) \
|
||||
static_assert(sizeof(CTYPE) <= sizeof(largest_scalar_t), \
|
||||
"define largest_scalar_t as " #CTYPE);
|
||||
FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
|
||||
@@ -100,28 +117,37 @@ struct EnumDef;
|
||||
// Represents any type in the IDL, which is a combination of the BaseType
|
||||
// and additional information for vectors/structs_.
|
||||
struct Type {
|
||||
explicit Type(BaseType _base_type = BASE_TYPE_NONE, StructDef *_sd = nullptr)
|
||||
explicit Type(BaseType _base_type = BASE_TYPE_NONE,
|
||||
StructDef *_sd = nullptr, EnumDef *_ed = nullptr)
|
||||
: base_type(_base_type),
|
||||
element(BASE_TYPE_NONE),
|
||||
struct_def(_sd),
|
||||
enum_def(nullptr)
|
||||
enum_def(_ed)
|
||||
{}
|
||||
|
||||
Type VectorType() const { return Type(element, struct_def); }
|
||||
bool operator==(const Type &o) {
|
||||
return base_type == o.base_type && element == o.element &&
|
||||
struct_def == o.struct_def && enum_def == o.enum_def;
|
||||
}
|
||||
|
||||
Type VectorType() const { return Type(element, struct_def, enum_def); }
|
||||
|
||||
Offset<reflection::Type> Serialize(FlatBufferBuilder *builder) const;
|
||||
|
||||
BaseType base_type;
|
||||
BaseType element; // only set if t == BASE_TYPE_VECTOR
|
||||
StructDef *struct_def; // only set if t or element == BASE_TYPE_STRUCT
|
||||
EnumDef *enum_def; // only set if t == BASE_TYPE_UNION / BASE_TYPE_UTYPE
|
||||
EnumDef *enum_def; // set if t == BASE_TYPE_UNION / BASE_TYPE_UTYPE,
|
||||
// or for an integral type derived from an enum.
|
||||
};
|
||||
|
||||
// Represents a parsed scalar value, it's type, and field offset.
|
||||
struct Value {
|
||||
Value() : constant("0"), offset(-1) {}
|
||||
|
||||
Value() : constant("0"), offset(static_cast<voffset_t>(
|
||||
~(static_cast<voffset_t>(0U)))) {}
|
||||
Type type;
|
||||
std::string constant;
|
||||
int offset;
|
||||
voffset_t offset;
|
||||
};
|
||||
|
||||
// Helper class that retains the original order of a set of identifiers and
|
||||
@@ -142,6 +168,17 @@ template<typename T> class SymbolTable {
|
||||
return false;
|
||||
}
|
||||
|
||||
void Move(const std::string &oldname, const std::string &newname) {
|
||||
auto it = dict.find(oldname);
|
||||
if (it != dict.end()) {
|
||||
auto obj = it->second;
|
||||
dict.erase(it);
|
||||
dict[newname] = obj;
|
||||
} else {
|
||||
assert(false);
|
||||
}
|
||||
}
|
||||
|
||||
T *Lookup(const std::string &name) const {
|
||||
auto it = dict.find(name);
|
||||
return it == dict.end() ? nullptr : it->second;
|
||||
@@ -154,22 +191,49 @@ template<typename T> class SymbolTable {
|
||||
std::vector<T *> vec; // Used to iterate in order of insertion
|
||||
};
|
||||
|
||||
// A name space, as set in the schema.
|
||||
struct Namespace {
|
||||
std::vector<std::string> components;
|
||||
|
||||
// Given a (potentally unqualified) name, return the "fully qualified" name
|
||||
// which has a full namespaced descriptor.
|
||||
// With max_components you can request less than the number of components
|
||||
// the current namespace has.
|
||||
std::string GetFullyQualifiedName(const std::string &name,
|
||||
size_t max_components = 1000) const;
|
||||
};
|
||||
|
||||
// Base class for all definition types (fields, structs_, enums_).
|
||||
struct Definition {
|
||||
Definition() : generated(false) {}
|
||||
Definition() : generated(false), defined_namespace(nullptr),
|
||||
serialized_location(0), index(-1) {}
|
||||
|
||||
std::string name;
|
||||
std::string doc_comment;
|
||||
std::string file;
|
||||
std::vector<std::string> doc_comment;
|
||||
SymbolTable<Value> attributes;
|
||||
bool generated; // did we already output code for this definition?
|
||||
Namespace *defined_namespace; // Where it was defined.
|
||||
|
||||
// For use with Serialize()
|
||||
uoffset_t serialized_location;
|
||||
int index; // Inside the vector it is stored.
|
||||
};
|
||||
|
||||
struct FieldDef : public Definition {
|
||||
FieldDef() : deprecated(false), padding(0) {}
|
||||
FieldDef() : deprecated(false), required(false), key(false), padding(0),
|
||||
used(false) {}
|
||||
|
||||
Offset<reflection::Field> Serialize(FlatBufferBuilder *builder, uint16_t id)
|
||||
const;
|
||||
|
||||
Value value;
|
||||
bool deprecated;
|
||||
size_t padding; // bytes to always pad after this field
|
||||
bool deprecated; // Field is allowed to be present in old data, but can't be
|
||||
// written in new data nor accessed in new code.
|
||||
bool required; // Field must always be present.
|
||||
bool key; // Field functions as a key for creating sorted vectors.
|
||||
size_t padding; // Bytes to always pad after this field.
|
||||
bool used; // Used during JSON parsing to check for repeated fields.
|
||||
};
|
||||
|
||||
struct StructDef : public Definition {
|
||||
@@ -177,20 +241,24 @@ struct StructDef : public Definition {
|
||||
: fixed(false),
|
||||
predecl(true),
|
||||
sortbysize(true),
|
||||
has_key(false),
|
||||
minalign(1),
|
||||
bytesize(0)
|
||||
{}
|
||||
|
||||
void PadLastField(size_t minalign) {
|
||||
auto padding = PaddingBytes(bytesize, minalign);
|
||||
void PadLastField(size_t min_align) {
|
||||
auto padding = PaddingBytes(bytesize, min_align);
|
||||
bytesize += padding;
|
||||
if (fields.vec.size()) fields.vec.back()->padding = padding;
|
||||
}
|
||||
|
||||
Offset<reflection::Object> Serialize(FlatBufferBuilder *builder) const;
|
||||
|
||||
SymbolTable<FieldDef> fields;
|
||||
bool fixed; // If it's struct, not a table.
|
||||
bool predecl; // If it's used before it was defined.
|
||||
bool sortbysize; // Whether fields come in the declaration or size order.
|
||||
bool has_key; // It has a key field.
|
||||
size_t minalign; // What the whole object needs to be aligned to.
|
||||
size_t bytesize; // Size if fixed.
|
||||
};
|
||||
@@ -208,28 +276,33 @@ inline size_t InlineAlignment(const Type &type) {
|
||||
}
|
||||
|
||||
struct EnumVal {
|
||||
EnumVal(const std::string &_name, int _val)
|
||||
EnumVal(const std::string &_name, int64_t _val)
|
||||
: name(_name), value(_val), struct_def(nullptr) {}
|
||||
|
||||
Offset<reflection::EnumVal> Serialize(FlatBufferBuilder *builder) const;
|
||||
|
||||
std::string name;
|
||||
std::string doc_comment;
|
||||
int value;
|
||||
std::vector<std::string> doc_comment;
|
||||
int64_t value;
|
||||
StructDef *struct_def; // only set if this is a union
|
||||
};
|
||||
|
||||
struct EnumDef : public Definition {
|
||||
EnumDef() : is_union(false) {}
|
||||
|
||||
StructDef *ReverseLookup(int enum_idx) {
|
||||
assert(is_union);
|
||||
for (auto it = vals.vec.begin() + 1; it != vals.vec.end(); ++it) {
|
||||
EnumVal *ReverseLookup(int enum_idx, bool skip_union_default = true) {
|
||||
for (auto it = vals.vec.begin() + static_cast<int>(is_union &&
|
||||
skip_union_default);
|
||||
it != vals.vec.end(); ++it) {
|
||||
if ((*it)->value == enum_idx) {
|
||||
return (*it)->struct_def;
|
||||
return *it;
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
Offset<reflection::Enum> Serialize(FlatBufferBuilder *builder) const;
|
||||
|
||||
SymbolTable<EnumVal> vals;
|
||||
bool is_union;
|
||||
Type underlying_type;
|
||||
@@ -237,23 +310,69 @@ struct EnumDef : public Definition {
|
||||
|
||||
class Parser {
|
||||
public:
|
||||
Parser() :
|
||||
root_struct_def(nullptr),
|
||||
source_(nullptr),
|
||||
cursor_(nullptr),
|
||||
line_(1) {}
|
||||
Parser(bool strict_json = false, bool proto_mode = false)
|
||||
: root_struct_def_(nullptr),
|
||||
source_(nullptr),
|
||||
cursor_(nullptr),
|
||||
line_(1),
|
||||
proto_mode_(proto_mode),
|
||||
strict_json_(strict_json),
|
||||
anonymous_counter(0) {
|
||||
// Just in case none are declared:
|
||||
namespaces_.push_back(new Namespace());
|
||||
known_attributes_.insert("deprecated");
|
||||
known_attributes_.insert("required");
|
||||
known_attributes_.insert("key");
|
||||
known_attributes_.insert("hash");
|
||||
known_attributes_.insert("id");
|
||||
known_attributes_.insert("force_align");
|
||||
known_attributes_.insert("bit_flags");
|
||||
known_attributes_.insert("original_order");
|
||||
known_attributes_.insert("nested_flatbuffer");
|
||||
}
|
||||
|
||||
~Parser() {
|
||||
for (auto it = namespaces_.begin(); it != namespaces_.end(); ++it) {
|
||||
delete *it;
|
||||
}
|
||||
}
|
||||
|
||||
// Parse the string containing either schema or JSON data, which will
|
||||
// populate the SymbolTable's or the FlatBufferBuilder above.
|
||||
bool Parse(const char *_source);
|
||||
// include_paths is used to resolve any include statements, and typically
|
||||
// should at least include the project path (where you loaded source_ from).
|
||||
// include_paths must be nullptr terminated if specified.
|
||||
// If include_paths is nullptr, it will attempt to load from the current
|
||||
// directory.
|
||||
// If the source was loaded from a file and isn't an include file,
|
||||
// supply its name in source_filename.
|
||||
bool Parse(const char *_source, const char **include_paths = nullptr,
|
||||
const char *source_filename = nullptr);
|
||||
|
||||
// Set the root type. May override the one set in the schema.
|
||||
bool SetRootType(const char *name);
|
||||
|
||||
// Mark all definitions as already having code generated.
|
||||
void MarkGenerated();
|
||||
|
||||
// Get the files recursively included by the given file. The returned
|
||||
// container will have at least the given file.
|
||||
std::set<std::string> GetIncludedFilesRecursive(
|
||||
const std::string &file_name) const;
|
||||
|
||||
// Fills builder_ with a binary version of the schema parsed.
|
||||
// See reflection/reflection.fbs
|
||||
void Serialize();
|
||||
|
||||
private:
|
||||
int64_t ParseHexNum(int nibbles);
|
||||
void Next();
|
||||
bool IsNext(int t);
|
||||
void Expect(int t);
|
||||
std::string TokenToStringId(int t);
|
||||
EnumDef *LookupEnum(const std::string &id);
|
||||
void ParseNamespacing(std::string *id, std::string *last);
|
||||
void ParseTypeIdent(Type &type);
|
||||
void ParseType(Type &type);
|
||||
FieldDef &AddField(StructDef &struct_def,
|
||||
const std::string &name,
|
||||
@@ -266,50 +385,217 @@ class Parser {
|
||||
uoffset_t ParseVector(const Type &type);
|
||||
void ParseMetaData(Definition &def);
|
||||
bool TryTypedValue(int dtoken, bool check, Value &e, BaseType req);
|
||||
void ParseHash(Value &e, FieldDef* field);
|
||||
void ParseSingleValue(Value &e);
|
||||
StructDef *LookupCreateStruct(const std::string &name);
|
||||
void ParseEnum(bool is_union);
|
||||
int64_t ParseIntegerFromString(Type &type);
|
||||
StructDef *LookupCreateStruct(const std::string &name,
|
||||
bool create_if_new = true,
|
||||
bool definition = false);
|
||||
EnumDef &ParseEnum(bool is_union);
|
||||
void ParseNamespace();
|
||||
StructDef &StartStruct(const std::string &name);
|
||||
void ParseDecl();
|
||||
void ParseProtoFields(StructDef *struct_def, bool isextend,
|
||||
bool inside_oneof);
|
||||
void ParseProtoOption();
|
||||
void ParseProtoKey();
|
||||
void ParseProtoDecl();
|
||||
void ParseProtoCurliesOrIdent();
|
||||
Type ParseTypeFromProtoType();
|
||||
|
||||
public:
|
||||
SymbolTable<StructDef> structs_;
|
||||
SymbolTable<EnumDef> enums_;
|
||||
std::vector<std::string> name_space_; // As set in the schema.
|
||||
std::vector<Namespace *> namespaces_;
|
||||
std::string error_; // User readable error_ if Parse() == false
|
||||
|
||||
FlatBufferBuilder builder_; // any data contained in the file
|
||||
StructDef *root_struct_def;
|
||||
StructDef *root_struct_def_;
|
||||
std::string file_identifier_;
|
||||
std::string file_extension_;
|
||||
|
||||
std::map<std::string, bool> included_files_;
|
||||
std::map<std::string, std::set<std::string>> files_included_per_file_;
|
||||
|
||||
private:
|
||||
const char *source_, *cursor_;
|
||||
int line_; // the current line being parsed
|
||||
int token_;
|
||||
std::string attribute_, doc_comment_;
|
||||
std::stack<std::string> files_being_parsed_;
|
||||
bool proto_mode_;
|
||||
bool strict_json_;
|
||||
std::string attribute_;
|
||||
std::vector<std::string> doc_comment_;
|
||||
|
||||
std::vector<std::pair<Value, FieldDef *>> field_stack_;
|
||||
std::vector<uint8_t> struct_stack_;
|
||||
|
||||
std::set<std::string> known_attributes_;
|
||||
|
||||
int anonymous_counter;
|
||||
};
|
||||
|
||||
// Utility functions for multiple generators:
|
||||
|
||||
extern std::string MakeCamel(const std::string &in, bool first = true);
|
||||
|
||||
struct CommentConfig;
|
||||
|
||||
extern void GenComment(const std::vector<std::string> &dc,
|
||||
std::string *code_ptr,
|
||||
const CommentConfig *config,
|
||||
const char *prefix = "");
|
||||
|
||||
// Container of options that may apply to any of the source/text generators.
|
||||
struct GeneratorOptions {
|
||||
bool strict_json;
|
||||
bool skip_js_exports;
|
||||
bool output_default_scalars_in_json;
|
||||
int indent_step;
|
||||
bool output_enum_identifiers;
|
||||
bool prefixed_enums;
|
||||
bool scoped_enums;
|
||||
bool include_dependence_headers;
|
||||
bool mutable_buffer;
|
||||
bool one_file;
|
||||
|
||||
// Possible options for the more general generator below.
|
||||
enum Language { kJava, kCSharp, kGo, kMAX };
|
||||
|
||||
Language lang;
|
||||
|
||||
GeneratorOptions() : strict_json(false),
|
||||
skip_js_exports(false),
|
||||
output_default_scalars_in_json(false),
|
||||
indent_step(2),
|
||||
output_enum_identifiers(true), prefixed_enums(true), scoped_enums(false),
|
||||
include_dependence_headers(true),
|
||||
mutable_buffer(false),
|
||||
one_file(false),
|
||||
lang(GeneratorOptions::kJava) {}
|
||||
};
|
||||
|
||||
// Generate text (JSON) from a given FlatBuffer, and a given Parser
|
||||
// object that has been populated with the corresponding schema.
|
||||
// If ident_step is 0, no indentation will be generated. Additionally,
|
||||
// if it is less than 0, no linefeeds will be generated either.
|
||||
// See idl_gen_text.cpp.
|
||||
// strict_json adds "quotes" around field names if true.
|
||||
extern void GenerateText(const Parser &parser,
|
||||
const void *flatbuffer,
|
||||
int indent_step,
|
||||
const GeneratorOptions &opts,
|
||||
std::string *text);
|
||||
extern bool GenerateTextFile(const Parser &parser,
|
||||
const std::string &path,
|
||||
const std::string &file_name,
|
||||
const GeneratorOptions &opts);
|
||||
|
||||
// Generate binary files from a given FlatBuffer, and a given Parser
|
||||
// object that has been populated with the corresponding schema.
|
||||
// See idl_gen_general.cpp.
|
||||
extern bool GenerateBinary(const Parser &parser,
|
||||
const std::string &path,
|
||||
const std::string &file_name,
|
||||
const GeneratorOptions &opts);
|
||||
|
||||
// Generate a C++ header from the definitions in the Parser object.
|
||||
// See idl_gen_cpp.
|
||||
extern std::string GenerateCPP(const Parser &parser);
|
||||
extern std::string GenerateCPP(const Parser &parser,
|
||||
const std::string &include_guard_ident,
|
||||
const GeneratorOptions &opts);
|
||||
extern bool GenerateCPP(const Parser &parser,
|
||||
const std::string &path,
|
||||
const std::string &file_name);
|
||||
const std::string &file_name,
|
||||
const GeneratorOptions &opts);
|
||||
|
||||
// Generate JavaScript code from the definitions in the Parser object.
|
||||
// See idl_gen_js.
|
||||
extern std::string GenerateJS(const Parser &parser,
|
||||
const GeneratorOptions &opts);
|
||||
extern bool GenerateJS(const Parser &parser,
|
||||
const std::string &path,
|
||||
const std::string &file_name,
|
||||
const GeneratorOptions &opts);
|
||||
|
||||
// Generate Go files from the definitions in the Parser object.
|
||||
// See idl_gen_go.cpp.
|
||||
extern bool GenerateGo(const Parser &parser,
|
||||
const std::string &path,
|
||||
const std::string &file_name,
|
||||
const GeneratorOptions &opts);
|
||||
|
||||
// Generate Java files from the definitions in the Parser object.
|
||||
// See idl_gen_java.cpp.
|
||||
extern bool GenerateJava(const Parser &parser,
|
||||
const std::string &path,
|
||||
const std::string &file_name);
|
||||
const std::string &file_name,
|
||||
const GeneratorOptions &opts);
|
||||
|
||||
// Generate Python files from the definitions in the Parser object.
|
||||
// See idl_gen_python.cpp.
|
||||
extern bool GeneratePython(const Parser &parser,
|
||||
const std::string &path,
|
||||
const std::string &file_name,
|
||||
const GeneratorOptions &opts);
|
||||
|
||||
// Generate C# files from the definitions in the Parser object.
|
||||
// See idl_gen_csharp.cpp.
|
||||
extern bool GenerateCSharp(const Parser &parser,
|
||||
const std::string &path,
|
||||
const std::string &file_name,
|
||||
const GeneratorOptions &opts);
|
||||
|
||||
// Generate Java/C#/.. files from the definitions in the Parser object.
|
||||
// See idl_gen_general.cpp.
|
||||
extern bool GenerateGeneral(const Parser &parser,
|
||||
const std::string &path,
|
||||
const std::string &file_name,
|
||||
const GeneratorOptions &opts);
|
||||
|
||||
// Generate a schema file from the internal representation, useful after
|
||||
// parsing a .proto schema.
|
||||
extern std::string GenerateFBS(const Parser &parser,
|
||||
const std::string &file_name,
|
||||
const GeneratorOptions &opts);
|
||||
extern bool GenerateFBS(const Parser &parser,
|
||||
const std::string &path,
|
||||
const std::string &file_name,
|
||||
const GeneratorOptions &opts);
|
||||
|
||||
// Generate a make rule for the generated JavaScript code.
|
||||
// See idl_gen_js.cpp.
|
||||
extern std::string JSMakeRule(const Parser &parser,
|
||||
const std::string &path,
|
||||
const std::string &file_name,
|
||||
const GeneratorOptions &opts);
|
||||
|
||||
// Generate a make rule for the generated C++ header.
|
||||
// See idl_gen_cpp.cpp.
|
||||
extern std::string CPPMakeRule(const Parser &parser,
|
||||
const std::string &path,
|
||||
const std::string &file_name,
|
||||
const GeneratorOptions &opts);
|
||||
|
||||
// Generate a make rule for the generated Java/C#/... files.
|
||||
// See idl_gen_general.cpp.
|
||||
extern std::string GeneralMakeRule(const Parser &parser,
|
||||
const std::string &path,
|
||||
const std::string &file_name,
|
||||
const GeneratorOptions &opts);
|
||||
|
||||
// Generate a make rule for the generated text (JSON) files.
|
||||
// See idl_gen_text.cpp.
|
||||
extern std::string TextMakeRule(const Parser &parser,
|
||||
const std::string &path,
|
||||
const std::string &file_name,
|
||||
const GeneratorOptions &opts);
|
||||
|
||||
// Generate a make rule for the generated binary files.
|
||||
// See idl_gen_general.cpp.
|
||||
extern std::string BinaryMakeRule(const Parser &parser,
|
||||
const std::string &path,
|
||||
const std::string &file_name,
|
||||
const GeneratorOptions &opts);
|
||||
|
||||
} // namespace flatbuffers
|
||||
|
||||
|
||||
427
include/flatbuffers/reflection.h
Normal file
427
include/flatbuffers/reflection.h
Normal file
@@ -0,0 +1,427 @@
|
||||
/*
|
||||
* Copyright 2015 Google Inc. All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#ifndef FLATBUFFERS_REFLECTION_H_
|
||||
#define FLATBUFFERS_REFLECTION_H_
|
||||
|
||||
// This is somewhat of a circular dependency because flatc (and thus this
|
||||
// file) is needed to generate this header in the first place.
|
||||
// Should normally not be a problem since it can be generated by the
|
||||
// previous version of flatc whenever this code needs to change.
|
||||
// See reflection/generate_code.sh
|
||||
#include "flatbuffers/reflection_generated.h"
|
||||
|
||||
// Helper functionality for reflection.
|
||||
|
||||
namespace flatbuffers {
|
||||
|
||||
// ------------------------- GETTERS -------------------------
|
||||
|
||||
// Size of a basic type, don't use with structs.
|
||||
inline size_t GetTypeSize(reflection::BaseType base_type) {
|
||||
// This needs to correspond to the BaseType enum.
|
||||
static size_t sizes[] = { 0, 1, 1, 1, 1, 2, 2, 4, 4, 8, 8, 4, 8, 4, 4, 4, 4 };
|
||||
return sizes[base_type];
|
||||
}
|
||||
|
||||
// Same as above, but now correctly returns the size of a struct if
|
||||
// the field (or vector element) is a struct.
|
||||
inline size_t GetTypeSizeInline(reflection::BaseType base_type,
|
||||
int type_index,
|
||||
const reflection::Schema &schema) {
|
||||
if (base_type == reflection::Obj &&
|
||||
schema.objects()->Get(type_index)->is_struct()) {
|
||||
return schema.objects()->Get(type_index)->bytesize();
|
||||
} else {
|
||||
return GetTypeSize(base_type);
|
||||
}
|
||||
}
|
||||
|
||||
// Get the root, regardless of what type it is.
|
||||
inline Table *GetAnyRoot(uint8_t *flatbuf) {
|
||||
return GetMutableRoot<Table>(flatbuf);
|
||||
}
|
||||
inline const Table *GetAnyRoot(const uint8_t *flatbuf) {
|
||||
return GetRoot<Table>(flatbuf);
|
||||
}
|
||||
|
||||
// Get a field, if you know it's an integer, and its exact type.
|
||||
template<typename T> T GetFieldI(const Table &table,
|
||||
const reflection::Field &field) {
|
||||
assert(sizeof(T) == GetTypeSize(field.type()->base_type()));
|
||||
return table.GetField<T>(field.offset(),
|
||||
static_cast<T>(field.default_integer()));
|
||||
}
|
||||
|
||||
// Get a field, if you know it's floating point and its exact type.
|
||||
template<typename T> T GetFieldF(const Table &table,
|
||||
const reflection::Field &field) {
|
||||
assert(sizeof(T) == GetTypeSize(field.type()->base_type()));
|
||||
return table.GetField<T>(field.offset(),
|
||||
static_cast<T>(field.default_real()));
|
||||
}
|
||||
|
||||
// Get a field, if you know it's a string.
|
||||
inline const String *GetFieldS(const Table &table,
|
||||
const reflection::Field &field) {
|
||||
assert(field.type()->base_type() == reflection::String);
|
||||
return table.GetPointer<const String *>(field.offset());
|
||||
}
|
||||
|
||||
// Get a field, if you know it's a vector.
|
||||
template<typename T> Vector<T> *GetFieldV(const Table &table,
|
||||
const reflection::Field &field) {
|
||||
assert(field.type()->base_type() == reflection::Vector &&
|
||||
sizeof(T) == GetTypeSize(field.type()->element()));
|
||||
return table.GetPointer<Vector<T> *>(field.offset());
|
||||
}
|
||||
|
||||
// Get a field, if you know it's a vector, generically.
|
||||
// To actually access elements, use the return value together with
|
||||
// field.type()->element() in any of GetAnyVectorElemI below etc.
|
||||
inline VectorOfAny *GetFieldAnyV(const Table &table,
|
||||
const reflection::Field &field) {
|
||||
return table.GetPointer<VectorOfAny *>(field.offset());
|
||||
}
|
||||
|
||||
// Get a field, if you know it's a table.
|
||||
inline Table *GetFieldT(const Table &table,
|
||||
const reflection::Field &field) {
|
||||
assert(field.type()->base_type() == reflection::Obj ||
|
||||
field.type()->base_type() == reflection::Union);
|
||||
return table.GetPointer<Table *>(field.offset());
|
||||
}
|
||||
|
||||
// Raw helper functions used below: get any value in memory as a 64bit int, a
|
||||
// double or a string.
|
||||
// All scalars get static_cast to an int64_t, strings use strtoull, every other
|
||||
// data type returns 0.
|
||||
int64_t GetAnyValueI(reflection::BaseType type, const uint8_t *data);
|
||||
// All scalars static cast to double, strings use strtod, every other data
|
||||
// type is 0.0.
|
||||
double GetAnyValueF(reflection::BaseType type, const uint8_t *data);
|
||||
// All scalars converted using stringstream, strings as-is, and all other
|
||||
// data types provide some level of debug-pretty-printing.
|
||||
std::string GetAnyValueS(reflection::BaseType type, const uint8_t *data,
|
||||
const reflection::Schema *schema,
|
||||
int type_index);
|
||||
|
||||
// Get any table field as a 64bit int, regardless of what type it is.
|
||||
inline int64_t GetAnyFieldI(const Table &table,
|
||||
const reflection::Field &field) {
|
||||
auto field_ptr = table.GetAddressOf(field.offset());
|
||||
return field_ptr ? GetAnyValueI(field.type()->base_type(), field_ptr)
|
||||
: field.default_integer();
|
||||
}
|
||||
|
||||
// Get any table field as a double, regardless of what type it is.
|
||||
inline double GetAnyFieldF(const Table &table,
|
||||
const reflection::Field &field) {
|
||||
auto field_ptr = table.GetAddressOf(field.offset());
|
||||
return field_ptr ? GetAnyValueF(field.type()->base_type(), field_ptr)
|
||||
: field.default_real();
|
||||
}
|
||||
|
||||
|
||||
// Get any table field as a string, regardless of what type it is.
|
||||
// You may pass nullptr for the schema if you don't care to have fields that
|
||||
// are of table type pretty-printed.
|
||||
inline std::string GetAnyFieldS(const Table &table,
|
||||
const reflection::Field &field,
|
||||
const reflection::Schema *schema) {
|
||||
auto field_ptr = table.GetAddressOf(field.offset());
|
||||
return field_ptr ? GetAnyValueS(field.type()->base_type(), field_ptr, schema,
|
||||
field.type()->index())
|
||||
: "";
|
||||
}
|
||||
|
||||
// Get any struct field as a 64bit int, regardless of what type it is.
|
||||
inline int64_t GetAnyFieldI(const Struct &st,
|
||||
const reflection::Field &field) {
|
||||
return GetAnyValueI(field.type()->base_type(),
|
||||
st.GetAddressOf(field.offset()));
|
||||
}
|
||||
|
||||
// Get any struct field as a double, regardless of what type it is.
|
||||
inline double GetAnyFieldF(const Struct &st,
|
||||
const reflection::Field &field) {
|
||||
return GetAnyValueF(field.type()->base_type(),
|
||||
st.GetAddressOf(field.offset()));
|
||||
}
|
||||
|
||||
// Get any struct field as a string, regardless of what type it is.
|
||||
inline std::string GetAnyFieldS(const Struct &st,
|
||||
const reflection::Field &field) {
|
||||
return GetAnyValueS(field.type()->base_type(),
|
||||
st.GetAddressOf(field.offset()), nullptr, -1);
|
||||
}
|
||||
|
||||
// Get any vector element as a 64bit int, regardless of what type it is.
|
||||
inline int64_t GetAnyVectorElemI(const VectorOfAny *vec,
|
||||
reflection::BaseType elem_type, size_t i) {
|
||||
return GetAnyValueI(elem_type, vec->Data() + GetTypeSize(elem_type) * i);
|
||||
}
|
||||
|
||||
// Get any vector element as a double, regardless of what type it is.
|
||||
inline double GetAnyVectorElemF(const VectorOfAny *vec,
|
||||
reflection::BaseType elem_type, size_t i) {
|
||||
return GetAnyValueF(elem_type, vec->Data() + GetTypeSize(elem_type) * i);
|
||||
}
|
||||
|
||||
// Get any vector element as a string, regardless of what type it is.
|
||||
inline std::string GetAnyVectorElemS(const VectorOfAny *vec,
|
||||
reflection::BaseType elem_type, size_t i) {
|
||||
return GetAnyValueS(elem_type, vec->Data() + GetTypeSize(elem_type) * i,
|
||||
nullptr, -1);
|
||||
}
|
||||
|
||||
// Get a vector element that's a table/string/vector from a generic vector.
|
||||
// Pass Table/String/VectorOfAny as template parameter.
|
||||
// Warning: does no typechecking.
|
||||
template<typename T> T *GetAnyVectorElemPointer(const VectorOfAny *vec,
|
||||
size_t i) {
|
||||
auto elem_ptr = vec->Data() + sizeof(uoffset_t) * i;
|
||||
return (T *)(elem_ptr + ReadScalar<uoffset_t>(elem_ptr));
|
||||
}
|
||||
|
||||
// Get the inline-address of a vector element. Useful for Structs (pass Struct
|
||||
// as template arg), or being able to address a range of scalars in-line.
|
||||
// Get elem_size from GetTypeSizeInline().
|
||||
// Note: little-endian data on all platforms, use EndianScalar() instead of
|
||||
// raw pointer access with scalars).
|
||||
template<typename T> T *GetAnyVectorElemAddressOf(const VectorOfAny *vec,
|
||||
size_t i,
|
||||
size_t elem_size) {
|
||||
// C-cast to allow const conversion.
|
||||
return (T *)(vec->Data() + elem_size * i);
|
||||
}
|
||||
|
||||
// Similarly, for elements of tables.
|
||||
template<typename T> T *GetAnyFieldAddressOf(const Table &table,
|
||||
const reflection::Field &field) {
|
||||
return (T *)table.GetAddressOf(field.offset());
|
||||
}
|
||||
|
||||
// Similarly, for elements of structs.
|
||||
template<typename T> T *GetAnyFieldAddressOf(const Struct &st,
|
||||
const reflection::Field &field) {
|
||||
return (T *)st.GetAddressOf(field.offset());
|
||||
}
|
||||
|
||||
// ------------------------- SETTERS -------------------------
|
||||
|
||||
// Set any scalar field, if you know its exact type.
|
||||
template<typename T> bool SetField(Table *table, const reflection::Field &field,
|
||||
T val) {
|
||||
assert(sizeof(T) == GetTypeSize(field.type()->base_type()));
|
||||
return table->SetField(field.offset(), val);
|
||||
}
|
||||
|
||||
// Raw helper functions used below: set any value in memory as a 64bit int, a
|
||||
// double or a string.
|
||||
// These work for all scalar values, but do nothing for other data types.
|
||||
// To set a string, see SetString below.
|
||||
void SetAnyValueI(reflection::BaseType type, uint8_t *data, int64_t val);
|
||||
void SetAnyValueF(reflection::BaseType type, uint8_t *data, double val);
|
||||
void SetAnyValueS(reflection::BaseType type, uint8_t *data, const char *val);
|
||||
|
||||
// Set any table field as a 64bit int, regardless of type what it is.
|
||||
inline bool SetAnyFieldI(Table *table, const reflection::Field &field,
|
||||
int64_t val) {
|
||||
auto field_ptr = table->GetAddressOf(field.offset());
|
||||
if (!field_ptr) return false;
|
||||
SetAnyValueI(field.type()->base_type(), field_ptr, val);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Set any table field as a double, regardless of what type it is.
|
||||
inline bool SetAnyFieldF(Table *table, const reflection::Field &field,
|
||||
double val) {
|
||||
auto field_ptr = table->GetAddressOf(field.offset());
|
||||
if (!field_ptr) return false;
|
||||
SetAnyValueF(field.type()->base_type(), field_ptr, val);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Set any table field as a string, regardless of what type it is.
|
||||
inline bool SetAnyFieldS(Table *table, const reflection::Field &field,
|
||||
const char *val) {
|
||||
auto field_ptr = table->GetAddressOf(field.offset());
|
||||
if (!field_ptr) return false;
|
||||
SetAnyValueS(field.type()->base_type(), field_ptr, val);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Set any struct field as a 64bit int, regardless of type what it is.
|
||||
inline void SetAnyFieldI(Struct *st, const reflection::Field &field,
|
||||
int64_t val) {
|
||||
SetAnyValueI(field.type()->base_type(), st->GetAddressOf(field.offset()),
|
||||
val);
|
||||
}
|
||||
|
||||
// Set any struct field as a double, regardless of type what it is.
|
||||
inline void SetAnyFieldF(Struct *st, const reflection::Field &field,
|
||||
double val) {
|
||||
SetAnyValueF(field.type()->base_type(), st->GetAddressOf(field.offset()),
|
||||
val);
|
||||
}
|
||||
|
||||
// Set any struct field as a string, regardless of type what it is.
|
||||
inline void SetAnyFieldS(Struct *st, const reflection::Field &field,
|
||||
const char *val) {
|
||||
SetAnyValueS(field.type()->base_type(), st->GetAddressOf(field.offset()),
|
||||
val);
|
||||
}
|
||||
|
||||
// Set any vector element as a 64bit int, regardless of type what it is.
|
||||
inline void SetAnyVectorElemI(VectorOfAny *vec, reflection::BaseType elem_type,
|
||||
size_t i, int64_t val) {
|
||||
SetAnyValueI(elem_type, vec->Data() + GetTypeSize(elem_type) * i, val);
|
||||
}
|
||||
|
||||
// Set any vector element as a double, regardless of type what it is.
|
||||
inline void SetAnyVectorElemF(VectorOfAny *vec, reflection::BaseType elem_type,
|
||||
size_t i, double val) {
|
||||
SetAnyValueF(elem_type, vec->Data() + GetTypeSize(elem_type) * i, val);
|
||||
}
|
||||
|
||||
// Set any vector element as a string, regardless of type what it is.
|
||||
inline void SetAnyVectorElemS(VectorOfAny *vec, reflection::BaseType elem_type,
|
||||
size_t i, const char *val) {
|
||||
SetAnyValueS(elem_type, vec->Data() + GetTypeSize(elem_type) * i, val);
|
||||
}
|
||||
|
||||
|
||||
// ------------------------- RESIZING SETTERS -------------------------
|
||||
|
||||
// "smart" pointer for use with resizing vectors: turns a pointer inside
|
||||
// a vector into a relative offset, such that it is not affected by resizes.
|
||||
template<typename T, typename U> class pointer_inside_vector {
|
||||
public:
|
||||
pointer_inside_vector(T *ptr, std::vector<U> &vec)
|
||||
: offset_(reinterpret_cast<uint8_t *>(ptr) -
|
||||
reinterpret_cast<uint8_t *>(vec.data())),
|
||||
vec_(vec) {}
|
||||
|
||||
T *operator*() const {
|
||||
return reinterpret_cast<T *>(
|
||||
reinterpret_cast<uint8_t *>(vec_.data()) + offset_);
|
||||
}
|
||||
T *operator->() const {
|
||||
return operator*();
|
||||
}
|
||||
void operator=(const pointer_inside_vector &piv);
|
||||
private:
|
||||
size_t offset_;
|
||||
std::vector<U> &vec_;
|
||||
};
|
||||
|
||||
// Helper to create the above easily without specifying template args.
|
||||
template<typename T, typename U> pointer_inside_vector<T, U> piv(T *ptr,
|
||||
std::vector<U> &vec) {
|
||||
return pointer_inside_vector<T, U>(ptr, vec);
|
||||
}
|
||||
|
||||
// Helper to figure out the actual table type a union refers to.
|
||||
inline const reflection::Object &GetUnionType(
|
||||
const reflection::Schema &schema, const reflection::Object &parent,
|
||||
const reflection::Field &unionfield, const Table &table) {
|
||||
auto enumdef = schema.enums()->Get(unionfield.type()->index());
|
||||
// TODO: this is clumsy and slow, but no other way to find it?
|
||||
auto type_field = parent.fields()->LookupByKey(
|
||||
(unionfield.name()->str() + "_type").c_str());
|
||||
assert(type_field);
|
||||
auto union_type = GetFieldI<uint8_t>(table, *type_field);
|
||||
auto enumval = enumdef->values()->LookupByKey(union_type);
|
||||
return *enumval->object();
|
||||
}
|
||||
|
||||
// Changes the contents of a string inside a FlatBuffer. FlatBuffer must
|
||||
// live inside a std::vector so we can resize the buffer if needed.
|
||||
// "str" must live inside "flatbuf" and may be invalidated after this call.
|
||||
// If your FlatBuffer's root table is not the schema's root table, you should
|
||||
// pass in your root_table type as well.
|
||||
void SetString(const reflection::Schema &schema, const std::string &val,
|
||||
const String *str, std::vector<uint8_t> *flatbuf,
|
||||
const reflection::Object *root_table = nullptr);
|
||||
|
||||
// Resizes a flatbuffers::Vector inside a FlatBuffer. FlatBuffer must
|
||||
// live inside a std::vector so we can resize the buffer if needed.
|
||||
// "vec" must live inside "flatbuf" and may be invalidated after this call.
|
||||
// If your FlatBuffer's root table is not the schema's root table, you should
|
||||
// pass in your root_table type as well.
|
||||
uint8_t *ResizeAnyVector(const reflection::Schema &schema, uoffset_t newsize,
|
||||
const VectorOfAny *vec, uoffset_t num_elems,
|
||||
uoffset_t elem_size, std::vector<uint8_t> *flatbuf,
|
||||
const reflection::Object *root_table = nullptr);
|
||||
|
||||
template <typename T>
|
||||
void ResizeVector(const reflection::Schema &schema, uoffset_t newsize, T val,
|
||||
const Vector<T> *vec, std::vector<uint8_t> *flatbuf,
|
||||
const reflection::Object *root_table = nullptr) {
|
||||
auto delta_elem = static_cast<int>(newsize) - static_cast<int>(vec->size());
|
||||
auto newelems = ResizeAnyVector(schema, newsize,
|
||||
reinterpret_cast<const VectorOfAny *>(vec),
|
||||
vec->size(),
|
||||
static_cast<uoffset_t>(sizeof(T)), flatbuf,
|
||||
root_table);
|
||||
// Set new elements to "val".
|
||||
for (int i = 0; i < delta_elem; i++) {
|
||||
auto loc = newelems + i * sizeof(T);
|
||||
auto is_scalar = std::is_scalar<T>::value;
|
||||
if (is_scalar) {
|
||||
WriteScalar(loc, val);
|
||||
} else { // struct
|
||||
*reinterpret_cast<T *>(loc) = val;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Adds any new data (in the form of a new FlatBuffer) to an existing
|
||||
// FlatBuffer. This can be used when any of the above methods are not
|
||||
// sufficient, in particular for adding new tables and new fields.
|
||||
// This is potentially slightly less efficient than a FlatBuffer constructed
|
||||
// in one piece, since the new FlatBuffer doesn't share any vtables with the
|
||||
// existing one.
|
||||
// The return value can now be set using Vector::MutateOffset or SetFieldT
|
||||
// below.
|
||||
const uint8_t *AddFlatBuffer(std::vector<uint8_t> &flatbuf,
|
||||
const uint8_t *newbuf, size_t newlen);
|
||||
|
||||
inline bool SetFieldT(Table *table, const reflection::Field &field,
|
||||
const uint8_t *val) {
|
||||
assert(sizeof(uoffset_t) == GetTypeSize(field.type()->base_type()));
|
||||
return table->SetPointer(field.offset(), val);
|
||||
}
|
||||
|
||||
// ------------------------- COPYING -------------------------
|
||||
|
||||
// Generic copying of tables from a FlatBuffer into a FlatBuffer builder.
|
||||
// Can be used to do any kind of merging/selecting you may want to do out
|
||||
// of existing buffers. Also useful to reconstruct a whole buffer if the
|
||||
// above resizing functionality has introduced garbage in a buffer you want
|
||||
// to remove.
|
||||
// Note: this does not deal with DAGs correctly. If the table passed forms a
|
||||
// DAG, the copy will be a tree instead (with duplicates).
|
||||
|
||||
Offset<const Table *> CopyTable(FlatBufferBuilder &fbb,
|
||||
const reflection::Schema &schema,
|
||||
const reflection::Object &objectdef,
|
||||
const Table &table);
|
||||
|
||||
} // namespace flatbuffers
|
||||
|
||||
#endif // FLATBUFFERS_REFLECTION_H_
|
||||
378
include/flatbuffers/reflection_generated.h
Normal file
378
include/flatbuffers/reflection_generated.h
Normal file
@@ -0,0 +1,378 @@
|
||||
// automatically generated by the FlatBuffers compiler, do not modify
|
||||
|
||||
#ifndef FLATBUFFERS_GENERATED_REFLECTION_REFLECTION_H_
|
||||
#define FLATBUFFERS_GENERATED_REFLECTION_REFLECTION_H_
|
||||
|
||||
#include "flatbuffers/flatbuffers.h"
|
||||
|
||||
|
||||
namespace reflection {
|
||||
|
||||
struct Type;
|
||||
struct EnumVal;
|
||||
struct Enum;
|
||||
struct Field;
|
||||
struct Object;
|
||||
struct Schema;
|
||||
|
||||
enum BaseType {
|
||||
None = 0,
|
||||
UType = 1,
|
||||
Bool = 2,
|
||||
Byte = 3,
|
||||
UByte = 4,
|
||||
Short = 5,
|
||||
UShort = 6,
|
||||
Int = 7,
|
||||
UInt = 8,
|
||||
Long = 9,
|
||||
ULong = 10,
|
||||
Float = 11,
|
||||
Double = 12,
|
||||
String = 13,
|
||||
Vector = 14,
|
||||
Obj = 15,
|
||||
Union = 16
|
||||
};
|
||||
|
||||
inline const char **EnumNamesBaseType() {
|
||||
static const char *names[] = { "None", "UType", "Bool", "Byte", "UByte", "Short", "UShort", "Int", "UInt", "Long", "ULong", "Float", "Double", "String", "Vector", "Obj", "Union", nullptr };
|
||||
return names;
|
||||
}
|
||||
|
||||
inline const char *EnumNameBaseType(BaseType e) { return EnumNamesBaseType()[e]; }
|
||||
|
||||
struct Type FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
|
||||
BaseType base_type() const { return static_cast<BaseType>(GetField<int8_t>(4, 0)); }
|
||||
BaseType element() const { return static_cast<BaseType>(GetField<int8_t>(6, 0)); }
|
||||
int32_t index() const { return GetField<int32_t>(8, -1); }
|
||||
bool Verify(flatbuffers::Verifier &verifier) const {
|
||||
return VerifyTableStart(verifier) &&
|
||||
VerifyField<int8_t>(verifier, 4 /* base_type */) &&
|
||||
VerifyField<int8_t>(verifier, 6 /* element */) &&
|
||||
VerifyField<int32_t>(verifier, 8 /* index */) &&
|
||||
verifier.EndTable();
|
||||
}
|
||||
};
|
||||
|
||||
struct TypeBuilder {
|
||||
flatbuffers::FlatBufferBuilder &fbb_;
|
||||
flatbuffers::uoffset_t start_;
|
||||
void add_base_type(BaseType base_type) { fbb_.AddElement<int8_t>(4, static_cast<int8_t>(base_type), 0); }
|
||||
void add_element(BaseType element) { fbb_.AddElement<int8_t>(6, static_cast<int8_t>(element), 0); }
|
||||
void add_index(int32_t index) { fbb_.AddElement<int32_t>(8, index, -1); }
|
||||
TypeBuilder(flatbuffers::FlatBufferBuilder &_fbb) : fbb_(_fbb) { start_ = fbb_.StartTable(); }
|
||||
TypeBuilder &operator=(const TypeBuilder &);
|
||||
flatbuffers::Offset<Type> Finish() {
|
||||
auto o = flatbuffers::Offset<Type>(fbb_.EndTable(start_, 3));
|
||||
return o;
|
||||
}
|
||||
};
|
||||
|
||||
inline flatbuffers::Offset<Type> CreateType(flatbuffers::FlatBufferBuilder &_fbb,
|
||||
BaseType base_type = None,
|
||||
BaseType element = None,
|
||||
int32_t index = -1) {
|
||||
TypeBuilder builder_(_fbb);
|
||||
builder_.add_index(index);
|
||||
builder_.add_element(element);
|
||||
builder_.add_base_type(base_type);
|
||||
return builder_.Finish();
|
||||
}
|
||||
|
||||
struct EnumVal FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
|
||||
const flatbuffers::String *name() const { return GetPointer<const flatbuffers::String *>(4); }
|
||||
int64_t value() const { return GetField<int64_t>(6, 0); }
|
||||
bool KeyCompareLessThan(const EnumVal *o) const { return value() < o->value(); }
|
||||
int KeyCompareWithValue(int64_t val) const { return value() < val ? -1 : value() > val; }
|
||||
const Object *object() const { return GetPointer<const Object *>(8); }
|
||||
bool Verify(flatbuffers::Verifier &verifier) const {
|
||||
return VerifyTableStart(verifier) &&
|
||||
VerifyFieldRequired<flatbuffers::uoffset_t>(verifier, 4 /* name */) &&
|
||||
verifier.Verify(name()) &&
|
||||
VerifyField<int64_t>(verifier, 6 /* value */) &&
|
||||
VerifyField<flatbuffers::uoffset_t>(verifier, 8 /* object */) &&
|
||||
verifier.VerifyTable(object()) &&
|
||||
verifier.EndTable();
|
||||
}
|
||||
};
|
||||
|
||||
struct EnumValBuilder {
|
||||
flatbuffers::FlatBufferBuilder &fbb_;
|
||||
flatbuffers::uoffset_t start_;
|
||||
void add_name(flatbuffers::Offset<flatbuffers::String> name) { fbb_.AddOffset(4, name); }
|
||||
void add_value(int64_t value) { fbb_.AddElement<int64_t>(6, value, 0); }
|
||||
void add_object(flatbuffers::Offset<Object> object) { fbb_.AddOffset(8, object); }
|
||||
EnumValBuilder(flatbuffers::FlatBufferBuilder &_fbb) : fbb_(_fbb) { start_ = fbb_.StartTable(); }
|
||||
EnumValBuilder &operator=(const EnumValBuilder &);
|
||||
flatbuffers::Offset<EnumVal> Finish() {
|
||||
auto o = flatbuffers::Offset<EnumVal>(fbb_.EndTable(start_, 3));
|
||||
fbb_.Required(o, 4); // name
|
||||
return o;
|
||||
}
|
||||
};
|
||||
|
||||
inline flatbuffers::Offset<EnumVal> CreateEnumVal(flatbuffers::FlatBufferBuilder &_fbb,
|
||||
flatbuffers::Offset<flatbuffers::String> name = 0,
|
||||
int64_t value = 0,
|
||||
flatbuffers::Offset<Object> object = 0) {
|
||||
EnumValBuilder builder_(_fbb);
|
||||
builder_.add_value(value);
|
||||
builder_.add_object(object);
|
||||
builder_.add_name(name);
|
||||
return builder_.Finish();
|
||||
}
|
||||
|
||||
struct Enum FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
|
||||
const flatbuffers::String *name() const { return GetPointer<const flatbuffers::String *>(4); }
|
||||
bool KeyCompareLessThan(const Enum *o) const { return *name() < *o->name(); }
|
||||
int KeyCompareWithValue(const char *val) const { return strcmp(name()->c_str(), val); }
|
||||
const flatbuffers::Vector<flatbuffers::Offset<EnumVal>> *values() const { return GetPointer<const flatbuffers::Vector<flatbuffers::Offset<EnumVal>> *>(6); }
|
||||
uint8_t is_union() const { return GetField<uint8_t>(8, 0); }
|
||||
const Type *underlying_type() const { return GetPointer<const Type *>(10); }
|
||||
bool Verify(flatbuffers::Verifier &verifier) const {
|
||||
return VerifyTableStart(verifier) &&
|
||||
VerifyFieldRequired<flatbuffers::uoffset_t>(verifier, 4 /* name */) &&
|
||||
verifier.Verify(name()) &&
|
||||
VerifyFieldRequired<flatbuffers::uoffset_t>(verifier, 6 /* values */) &&
|
||||
verifier.Verify(values()) &&
|
||||
verifier.VerifyVectorOfTables(values()) &&
|
||||
VerifyField<uint8_t>(verifier, 8 /* is_union */) &&
|
||||
VerifyFieldRequired<flatbuffers::uoffset_t>(verifier, 10 /* underlying_type */) &&
|
||||
verifier.VerifyTable(underlying_type()) &&
|
||||
verifier.EndTable();
|
||||
}
|
||||
};
|
||||
|
||||
struct EnumBuilder {
|
||||
flatbuffers::FlatBufferBuilder &fbb_;
|
||||
flatbuffers::uoffset_t start_;
|
||||
void add_name(flatbuffers::Offset<flatbuffers::String> name) { fbb_.AddOffset(4, name); }
|
||||
void add_values(flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<EnumVal>>> values) { fbb_.AddOffset(6, values); }
|
||||
void add_is_union(uint8_t is_union) { fbb_.AddElement<uint8_t>(8, is_union, 0); }
|
||||
void add_underlying_type(flatbuffers::Offset<Type> underlying_type) { fbb_.AddOffset(10, underlying_type); }
|
||||
EnumBuilder(flatbuffers::FlatBufferBuilder &_fbb) : fbb_(_fbb) { start_ = fbb_.StartTable(); }
|
||||
EnumBuilder &operator=(const EnumBuilder &);
|
||||
flatbuffers::Offset<Enum> Finish() {
|
||||
auto o = flatbuffers::Offset<Enum>(fbb_.EndTable(start_, 4));
|
||||
fbb_.Required(o, 4); // name
|
||||
fbb_.Required(o, 6); // values
|
||||
fbb_.Required(o, 10); // underlying_type
|
||||
return o;
|
||||
}
|
||||
};
|
||||
|
||||
inline flatbuffers::Offset<Enum> CreateEnum(flatbuffers::FlatBufferBuilder &_fbb,
|
||||
flatbuffers::Offset<flatbuffers::String> name = 0,
|
||||
flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<EnumVal>>> values = 0,
|
||||
uint8_t is_union = 0,
|
||||
flatbuffers::Offset<Type> underlying_type = 0) {
|
||||
EnumBuilder builder_(_fbb);
|
||||
builder_.add_underlying_type(underlying_type);
|
||||
builder_.add_values(values);
|
||||
builder_.add_name(name);
|
||||
builder_.add_is_union(is_union);
|
||||
return builder_.Finish();
|
||||
}
|
||||
|
||||
struct Field FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
|
||||
const flatbuffers::String *name() const { return GetPointer<const flatbuffers::String *>(4); }
|
||||
bool KeyCompareLessThan(const Field *o) const { return *name() < *o->name(); }
|
||||
int KeyCompareWithValue(const char *val) const { return strcmp(name()->c_str(), val); }
|
||||
const Type *type() const { return GetPointer<const Type *>(6); }
|
||||
uint16_t id() const { return GetField<uint16_t>(8, 0); }
|
||||
uint16_t offset() const { return GetField<uint16_t>(10, 0); }
|
||||
int64_t default_integer() const { return GetField<int64_t>(12, 0); }
|
||||
double default_real() const { return GetField<double>(14, 0.0); }
|
||||
uint8_t deprecated() const { return GetField<uint8_t>(16, 0); }
|
||||
uint8_t required() const { return GetField<uint8_t>(18, 0); }
|
||||
uint8_t key() const { return GetField<uint8_t>(20, 0); }
|
||||
bool Verify(flatbuffers::Verifier &verifier) const {
|
||||
return VerifyTableStart(verifier) &&
|
||||
VerifyFieldRequired<flatbuffers::uoffset_t>(verifier, 4 /* name */) &&
|
||||
verifier.Verify(name()) &&
|
||||
VerifyFieldRequired<flatbuffers::uoffset_t>(verifier, 6 /* type */) &&
|
||||
verifier.VerifyTable(type()) &&
|
||||
VerifyField<uint16_t>(verifier, 8 /* id */) &&
|
||||
VerifyField<uint16_t>(verifier, 10 /* offset */) &&
|
||||
VerifyField<int64_t>(verifier, 12 /* default_integer */) &&
|
||||
VerifyField<double>(verifier, 14 /* default_real */) &&
|
||||
VerifyField<uint8_t>(verifier, 16 /* deprecated */) &&
|
||||
VerifyField<uint8_t>(verifier, 18 /* required */) &&
|
||||
VerifyField<uint8_t>(verifier, 20 /* key */) &&
|
||||
verifier.EndTable();
|
||||
}
|
||||
};
|
||||
|
||||
struct FieldBuilder {
|
||||
flatbuffers::FlatBufferBuilder &fbb_;
|
||||
flatbuffers::uoffset_t start_;
|
||||
void add_name(flatbuffers::Offset<flatbuffers::String> name) { fbb_.AddOffset(4, name); }
|
||||
void add_type(flatbuffers::Offset<Type> type) { fbb_.AddOffset(6, type); }
|
||||
void add_id(uint16_t id) { fbb_.AddElement<uint16_t>(8, id, 0); }
|
||||
void add_offset(uint16_t offset) { fbb_.AddElement<uint16_t>(10, offset, 0); }
|
||||
void add_default_integer(int64_t default_integer) { fbb_.AddElement<int64_t>(12, default_integer, 0); }
|
||||
void add_default_real(double default_real) { fbb_.AddElement<double>(14, default_real, 0.0); }
|
||||
void add_deprecated(uint8_t deprecated) { fbb_.AddElement<uint8_t>(16, deprecated, 0); }
|
||||
void add_required(uint8_t required) { fbb_.AddElement<uint8_t>(18, required, 0); }
|
||||
void add_key(uint8_t key) { fbb_.AddElement<uint8_t>(20, key, 0); }
|
||||
FieldBuilder(flatbuffers::FlatBufferBuilder &_fbb) : fbb_(_fbb) { start_ = fbb_.StartTable(); }
|
||||
FieldBuilder &operator=(const FieldBuilder &);
|
||||
flatbuffers::Offset<Field> Finish() {
|
||||
auto o = flatbuffers::Offset<Field>(fbb_.EndTable(start_, 9));
|
||||
fbb_.Required(o, 4); // name
|
||||
fbb_.Required(o, 6); // type
|
||||
return o;
|
||||
}
|
||||
};
|
||||
|
||||
inline flatbuffers::Offset<Field> CreateField(flatbuffers::FlatBufferBuilder &_fbb,
|
||||
flatbuffers::Offset<flatbuffers::String> name = 0,
|
||||
flatbuffers::Offset<Type> type = 0,
|
||||
uint16_t id = 0,
|
||||
uint16_t offset = 0,
|
||||
int64_t default_integer = 0,
|
||||
double default_real = 0.0,
|
||||
uint8_t deprecated = 0,
|
||||
uint8_t required = 0,
|
||||
uint8_t key = 0) {
|
||||
FieldBuilder builder_(_fbb);
|
||||
builder_.add_default_real(default_real);
|
||||
builder_.add_default_integer(default_integer);
|
||||
builder_.add_type(type);
|
||||
builder_.add_name(name);
|
||||
builder_.add_offset(offset);
|
||||
builder_.add_id(id);
|
||||
builder_.add_key(key);
|
||||
builder_.add_required(required);
|
||||
builder_.add_deprecated(deprecated);
|
||||
return builder_.Finish();
|
||||
}
|
||||
|
||||
struct Object FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
|
||||
const flatbuffers::String *name() const { return GetPointer<const flatbuffers::String *>(4); }
|
||||
bool KeyCompareLessThan(const Object *o) const { return *name() < *o->name(); }
|
||||
int KeyCompareWithValue(const char *val) const { return strcmp(name()->c_str(), val); }
|
||||
const flatbuffers::Vector<flatbuffers::Offset<Field>> *fields() const { return GetPointer<const flatbuffers::Vector<flatbuffers::Offset<Field>> *>(6); }
|
||||
uint8_t is_struct() const { return GetField<uint8_t>(8, 0); }
|
||||
int32_t minalign() const { return GetField<int32_t>(10, 0); }
|
||||
int32_t bytesize() const { return GetField<int32_t>(12, 0); }
|
||||
bool Verify(flatbuffers::Verifier &verifier) const {
|
||||
return VerifyTableStart(verifier) &&
|
||||
VerifyFieldRequired<flatbuffers::uoffset_t>(verifier, 4 /* name */) &&
|
||||
verifier.Verify(name()) &&
|
||||
VerifyFieldRequired<flatbuffers::uoffset_t>(verifier, 6 /* fields */) &&
|
||||
verifier.Verify(fields()) &&
|
||||
verifier.VerifyVectorOfTables(fields()) &&
|
||||
VerifyField<uint8_t>(verifier, 8 /* is_struct */) &&
|
||||
VerifyField<int32_t>(verifier, 10 /* minalign */) &&
|
||||
VerifyField<int32_t>(verifier, 12 /* bytesize */) &&
|
||||
verifier.EndTable();
|
||||
}
|
||||
};
|
||||
|
||||
struct ObjectBuilder {
|
||||
flatbuffers::FlatBufferBuilder &fbb_;
|
||||
flatbuffers::uoffset_t start_;
|
||||
void add_name(flatbuffers::Offset<flatbuffers::String> name) { fbb_.AddOffset(4, name); }
|
||||
void add_fields(flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Field>>> fields) { fbb_.AddOffset(6, fields); }
|
||||
void add_is_struct(uint8_t is_struct) { fbb_.AddElement<uint8_t>(8, is_struct, 0); }
|
||||
void add_minalign(int32_t minalign) { fbb_.AddElement<int32_t>(10, minalign, 0); }
|
||||
void add_bytesize(int32_t bytesize) { fbb_.AddElement<int32_t>(12, bytesize, 0); }
|
||||
ObjectBuilder(flatbuffers::FlatBufferBuilder &_fbb) : fbb_(_fbb) { start_ = fbb_.StartTable(); }
|
||||
ObjectBuilder &operator=(const ObjectBuilder &);
|
||||
flatbuffers::Offset<Object> Finish() {
|
||||
auto o = flatbuffers::Offset<Object>(fbb_.EndTable(start_, 5));
|
||||
fbb_.Required(o, 4); // name
|
||||
fbb_.Required(o, 6); // fields
|
||||
return o;
|
||||
}
|
||||
};
|
||||
|
||||
inline flatbuffers::Offset<Object> CreateObject(flatbuffers::FlatBufferBuilder &_fbb,
|
||||
flatbuffers::Offset<flatbuffers::String> name = 0,
|
||||
flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Field>>> fields = 0,
|
||||
uint8_t is_struct = 0,
|
||||
int32_t minalign = 0,
|
||||
int32_t bytesize = 0) {
|
||||
ObjectBuilder builder_(_fbb);
|
||||
builder_.add_bytesize(bytesize);
|
||||
builder_.add_minalign(minalign);
|
||||
builder_.add_fields(fields);
|
||||
builder_.add_name(name);
|
||||
builder_.add_is_struct(is_struct);
|
||||
return builder_.Finish();
|
||||
}
|
||||
|
||||
struct Schema FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
|
||||
const flatbuffers::Vector<flatbuffers::Offset<Object>> *objects() const { return GetPointer<const flatbuffers::Vector<flatbuffers::Offset<Object>> *>(4); }
|
||||
const flatbuffers::Vector<flatbuffers::Offset<Enum>> *enums() const { return GetPointer<const flatbuffers::Vector<flatbuffers::Offset<Enum>> *>(6); }
|
||||
const flatbuffers::String *file_ident() const { return GetPointer<const flatbuffers::String *>(8); }
|
||||
const flatbuffers::String *file_ext() const { return GetPointer<const flatbuffers::String *>(10); }
|
||||
const Object *root_table() const { return GetPointer<const Object *>(12); }
|
||||
bool Verify(flatbuffers::Verifier &verifier) const {
|
||||
return VerifyTableStart(verifier) &&
|
||||
VerifyFieldRequired<flatbuffers::uoffset_t>(verifier, 4 /* objects */) &&
|
||||
verifier.Verify(objects()) &&
|
||||
verifier.VerifyVectorOfTables(objects()) &&
|
||||
VerifyFieldRequired<flatbuffers::uoffset_t>(verifier, 6 /* enums */) &&
|
||||
verifier.Verify(enums()) &&
|
||||
verifier.VerifyVectorOfTables(enums()) &&
|
||||
VerifyField<flatbuffers::uoffset_t>(verifier, 8 /* file_ident */) &&
|
||||
verifier.Verify(file_ident()) &&
|
||||
VerifyField<flatbuffers::uoffset_t>(verifier, 10 /* file_ext */) &&
|
||||
verifier.Verify(file_ext()) &&
|
||||
VerifyField<flatbuffers::uoffset_t>(verifier, 12 /* root_table */) &&
|
||||
verifier.VerifyTable(root_table()) &&
|
||||
verifier.EndTable();
|
||||
}
|
||||
};
|
||||
|
||||
struct SchemaBuilder {
|
||||
flatbuffers::FlatBufferBuilder &fbb_;
|
||||
flatbuffers::uoffset_t start_;
|
||||
void add_objects(flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Object>>> objects) { fbb_.AddOffset(4, objects); }
|
||||
void add_enums(flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Enum>>> enums) { fbb_.AddOffset(6, enums); }
|
||||
void add_file_ident(flatbuffers::Offset<flatbuffers::String> file_ident) { fbb_.AddOffset(8, file_ident); }
|
||||
void add_file_ext(flatbuffers::Offset<flatbuffers::String> file_ext) { fbb_.AddOffset(10, file_ext); }
|
||||
void add_root_table(flatbuffers::Offset<Object> root_table) { fbb_.AddOffset(12, root_table); }
|
||||
SchemaBuilder(flatbuffers::FlatBufferBuilder &_fbb) : fbb_(_fbb) { start_ = fbb_.StartTable(); }
|
||||
SchemaBuilder &operator=(const SchemaBuilder &);
|
||||
flatbuffers::Offset<Schema> Finish() {
|
||||
auto o = flatbuffers::Offset<Schema>(fbb_.EndTable(start_, 5));
|
||||
fbb_.Required(o, 4); // objects
|
||||
fbb_.Required(o, 6); // enums
|
||||
return o;
|
||||
}
|
||||
};
|
||||
|
||||
inline flatbuffers::Offset<Schema> CreateSchema(flatbuffers::FlatBufferBuilder &_fbb,
|
||||
flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Object>>> objects = 0,
|
||||
flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Enum>>> enums = 0,
|
||||
flatbuffers::Offset<flatbuffers::String> file_ident = 0,
|
||||
flatbuffers::Offset<flatbuffers::String> file_ext = 0,
|
||||
flatbuffers::Offset<Object> root_table = 0) {
|
||||
SchemaBuilder builder_(_fbb);
|
||||
builder_.add_root_table(root_table);
|
||||
builder_.add_file_ext(file_ext);
|
||||
builder_.add_file_ident(file_ident);
|
||||
builder_.add_enums(enums);
|
||||
builder_.add_objects(objects);
|
||||
return builder_.Finish();
|
||||
}
|
||||
|
||||
inline const reflection::Schema *GetSchema(const void *buf) { return flatbuffers::GetRoot<reflection::Schema>(buf); }
|
||||
|
||||
inline bool VerifySchemaBuffer(flatbuffers::Verifier &verifier) { return verifier.VerifyBuffer<reflection::Schema>(); }
|
||||
|
||||
inline const char *SchemaIdentifier() { return "BFBS"; }
|
||||
|
||||
inline bool SchemaBufferHasIdentifier(const void *buf) { return flatbuffers::BufferHasIdentifier(buf, SchemaIdentifier()); }
|
||||
|
||||
inline const char *SchemaExtension() { return "bfbs"; }
|
||||
|
||||
inline void FinishSchemaBuffer(flatbuffers::FlatBufferBuilder &fbb, flatbuffers::Offset<reflection::Schema> root) { fbb.Finish(root, SchemaIdentifier()); }
|
||||
|
||||
} // namespace reflection
|
||||
|
||||
#endif // FLATBUFFERS_GENERATED_REFLECTION_REFLECTION_H_
|
||||
@@ -22,29 +22,67 @@
|
||||
#include <string>
|
||||
#include <sstream>
|
||||
#include <stdlib.h>
|
||||
#include <assert.h>
|
||||
#ifdef _WIN32
|
||||
#ifndef WIN32_LEAN_AND_MEAN
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#endif
|
||||
#ifndef NOMINMAX
|
||||
#define NOMINMAX
|
||||
#endif
|
||||
#include <windows.h>
|
||||
#include <winbase.h>
|
||||
#include <direct.h>
|
||||
#else
|
||||
#include <sys/stat.h>
|
||||
#include <limits.h>
|
||||
#endif
|
||||
|
||||
namespace flatbuffers {
|
||||
|
||||
// Convert an integer or floating point value to a string.
|
||||
// In contrast to std::stringstream, "char" values are
|
||||
// converted to a string of digits.
|
||||
// converted to a string of digits, and we don't use scientific notation.
|
||||
template<typename T> std::string NumToString(T t) {
|
||||
std::stringstream ss;
|
||||
ss << t;
|
||||
return ss.str();
|
||||
}
|
||||
// Avoid char types used as character data.
|
||||
template<> inline std::string NumToString<signed char>(signed char t) {
|
||||
return NumToString(static_cast<int>(t));
|
||||
}
|
||||
template<> inline std::string NumToString<unsigned char>(unsigned char t) {
|
||||
return NumToString(static_cast<int>(t));
|
||||
}
|
||||
|
||||
// Special versions for floats/doubles.
|
||||
template<> inline std::string NumToString<double>(double t) {
|
||||
// to_string() prints different numbers of digits for floats depending on
|
||||
// platform and isn't available on Android, so we use stringstream
|
||||
std::stringstream ss;
|
||||
if (sizeof(T) > 1) ss << t;
|
||||
else ss << static_cast<int>(t); // Avoid char types used as character data.
|
||||
return ss.str();
|
||||
// Use std::fixed to surpress scientific notation.
|
||||
ss << std::fixed << t;
|
||||
auto s = ss.str();
|
||||
// Sadly, std::fixed turns "1" into "1.00000", so here we undo that.
|
||||
auto p = s.find_last_not_of('0');
|
||||
if (p != std::string::npos) {
|
||||
s.resize(p + 1); // Strip trailing zeroes.
|
||||
if (s.back() == '.')
|
||||
s.erase(s.size() - 1, 1); // Strip '.' if a whole number.
|
||||
}
|
||||
return s;
|
||||
}
|
||||
template<> inline std::string NumToString<float>(float t) {
|
||||
return NumToString(static_cast<double>(t));
|
||||
}
|
||||
|
||||
// Convert an integer value to a hexadecimal string.
|
||||
// The returned string length is the number of nibbles in
|
||||
// the supplied value prefixed by 0 digits. For example,
|
||||
// IntToStringHex(static_cast<int>(0x23)) returns the
|
||||
// string "00000023".
|
||||
template<typename T> std::string IntToStringHex(T i) {
|
||||
// The returned string length is always xdigits long, prefixed by 0 digits.
|
||||
// For example, IntToStringHex(0x23, 8) returns the string "00000023".
|
||||
inline std::string IntToStringHex(int i, int xdigits) {
|
||||
std::stringstream ss;
|
||||
ss << std::setw(sizeof(T) * 2)
|
||||
ss << std::setw(xdigits)
|
||||
<< std::setfill('0')
|
||||
<< std::hex
|
||||
<< std::uppercase
|
||||
@@ -52,15 +90,30 @@ template<typename T> std::string IntToStringHex(T i) {
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
// Portable implementation of strtoull().
|
||||
inline int64_t StringToInt(const char *str) {
|
||||
// Portable implementation of strtoll().
|
||||
inline int64_t StringToInt(const char *str, int base = 10) {
|
||||
#ifdef _MSC_VER
|
||||
return _strtoui64(str, nullptr, 10);
|
||||
return _strtoi64(str, nullptr, base);
|
||||
#else
|
||||
return strtoull(str, nullptr, 10);
|
||||
return strtoll(str, nullptr, base);
|
||||
#endif
|
||||
}
|
||||
|
||||
// Portable implementation of strtoull().
|
||||
inline int64_t StringToUInt(const char *str, int base = 10) {
|
||||
#ifdef _MSC_VER
|
||||
return _strtoui64(str, nullptr, base);
|
||||
#else
|
||||
return strtoull(str, nullptr, base);
|
||||
#endif
|
||||
}
|
||||
|
||||
// Check if file "name" exists.
|
||||
inline bool FileExists(const char *name) {
|
||||
std::ifstream ifs(name);
|
||||
return ifs.good();
|
||||
}
|
||||
|
||||
// Load file "name" into "buf" returning true if successful
|
||||
// false otherwise. If "binary" is false data is read
|
||||
// using ifstream's text mode, otherwise data is read with
|
||||
@@ -68,8 +121,18 @@ inline int64_t StringToInt(const char *str) {
|
||||
inline bool LoadFile(const char *name, bool binary, std::string *buf) {
|
||||
std::ifstream ifs(name, binary ? std::ifstream::binary : std::ifstream::in);
|
||||
if (!ifs.is_open()) return false;
|
||||
*buf = std::string(std::istreambuf_iterator<char>(ifs),
|
||||
std::istreambuf_iterator<char>());
|
||||
if (binary) {
|
||||
// The fastest way to read a file into a string.
|
||||
ifs.seekg(0, std::ios::end);
|
||||
(*buf).resize(static_cast<size_t>(ifs.tellg()));
|
||||
ifs.seekg(0, std::ios::beg);
|
||||
ifs.read(&(*buf)[0], (*buf).size());
|
||||
} else {
|
||||
// This is slower, but works correctly on all platforms for text files.
|
||||
std::ostringstream oss;
|
||||
oss << ifs.rdbuf();
|
||||
*buf = oss.str();
|
||||
}
|
||||
return !ifs.bad();
|
||||
}
|
||||
|
||||
@@ -94,6 +157,154 @@ inline bool SaveFile(const char *name, const std::string &buf, bool binary) {
|
||||
return SaveFile(name, buf.c_str(), buf.size(), binary);
|
||||
}
|
||||
|
||||
// Functionality for minimalistic portable path handling:
|
||||
|
||||
static const char kPosixPathSeparator = '/';
|
||||
#ifdef _WIN32
|
||||
static const char kPathSeparator = '\\';
|
||||
static const char *PathSeparatorSet = "\\/"; // Intentionally no ':'
|
||||
#else
|
||||
static const char kPathSeparator = kPosixPathSeparator;
|
||||
static const char *PathSeparatorSet = "/";
|
||||
#endif // _WIN32
|
||||
|
||||
// Returns the path with the extension, if any, removed.
|
||||
inline std::string StripExtension(const std::string &filepath) {
|
||||
size_t i = filepath.find_last_of(".");
|
||||
return i != std::string::npos ? filepath.substr(0, i) : filepath;
|
||||
}
|
||||
|
||||
// Return the last component of the path, after the last separator.
|
||||
inline std::string StripPath(const std::string &filepath) {
|
||||
size_t i = filepath.find_last_of(PathSeparatorSet);
|
||||
return i != std::string::npos ? filepath.substr(i + 1) : filepath;
|
||||
}
|
||||
|
||||
// Strip the last component of the path + separator.
|
||||
inline std::string StripFileName(const std::string &filepath) {
|
||||
size_t i = filepath.find_last_of(PathSeparatorSet);
|
||||
return i != std::string::npos ? filepath.substr(0, i) : "";
|
||||
}
|
||||
|
||||
// Concatenates a path with a filename, regardless of wether the path
|
||||
// ends in a separator or not.
|
||||
inline std::string ConCatPathFileName(const std::string &path,
|
||||
const std::string &filename) {
|
||||
std::string filepath = path;
|
||||
if (path.length() && path.back() != kPathSeparator &&
|
||||
path.back() != kPosixPathSeparator)
|
||||
filepath += kPathSeparator;
|
||||
filepath += filename;
|
||||
return filepath;
|
||||
}
|
||||
|
||||
// This function ensure a directory exists, by recursively
|
||||
// creating dirs for any parts of the path that don't exist yet.
|
||||
inline void EnsureDirExists(const std::string &filepath) {
|
||||
auto parent = StripFileName(filepath);
|
||||
if (parent.length()) EnsureDirExists(parent);
|
||||
#ifdef _WIN32
|
||||
_mkdir(filepath.c_str());
|
||||
#else
|
||||
mkdir(filepath.c_str(), S_IRWXU|S_IRGRP|S_IXGRP);
|
||||
#endif
|
||||
}
|
||||
|
||||
// Obtains the absolute path from any other path.
|
||||
// Returns the input path if the absolute path couldn't be resolved.
|
||||
inline std::string AbsolutePath(const std::string &filepath) {
|
||||
#ifdef _WIN32
|
||||
char abs_path[MAX_PATH];
|
||||
return GetFullPathNameA(filepath.c_str(), MAX_PATH, abs_path, nullptr)
|
||||
#else
|
||||
char abs_path[PATH_MAX];
|
||||
return realpath(filepath.c_str(), abs_path)
|
||||
#endif
|
||||
? abs_path
|
||||
: filepath;
|
||||
}
|
||||
|
||||
// To and from UTF-8 unicode conversion functions
|
||||
|
||||
// Convert a unicode code point into a UTF-8 representation by appending it
|
||||
// to a string. Returns the number of bytes generated.
|
||||
inline int ToUTF8(uint32_t ucc, std::string *out) {
|
||||
assert(!(ucc & 0x80000000)); // Top bit can't be set.
|
||||
// 6 possible encodings: http://en.wikipedia.org/wiki/UTF-8
|
||||
for (int i = 0; i < 6; i++) {
|
||||
// Max bits this encoding can represent.
|
||||
uint32_t max_bits = 6 + i * 5 + static_cast<int>(!i);
|
||||
if (ucc < (1u << max_bits)) { // does it fit?
|
||||
// Remaining bits not encoded in the first byte, store 6 bits each
|
||||
uint32_t remain_bits = i * 6;
|
||||
// Store first byte:
|
||||
(*out) += static_cast<char>((0xFE << (max_bits - remain_bits)) |
|
||||
(ucc >> remain_bits));
|
||||
// Store remaining bytes:
|
||||
for (int j = i - 1; j >= 0; j--) {
|
||||
(*out) += static_cast<char>(((ucc >> (j * 6)) & 0x3F) | 0x80);
|
||||
}
|
||||
return i + 1; // Return the number of bytes added.
|
||||
}
|
||||
}
|
||||
assert(0); // Impossible to arrive here.
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Converts whatever prefix of the incoming string corresponds to a valid
|
||||
// UTF-8 sequence into a unicode code. The incoming pointer will have been
|
||||
// advanced past all bytes parsed.
|
||||
// returns -1 upon corrupt UTF-8 encoding (ignore the incoming pointer in
|
||||
// this case).
|
||||
inline int FromUTF8(const char **in) {
|
||||
int len = 0;
|
||||
// Count leading 1 bits.
|
||||
for (int mask = 0x80; mask >= 0x04; mask >>= 1) {
|
||||
if (**in & mask) {
|
||||
len++;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if ((**in << len) & 0x80) return -1; // Bit after leading 1's must be 0.
|
||||
if (!len) return *(*in)++;
|
||||
// Grab initial bits of the code.
|
||||
int ucc = *(*in)++ & ((1 << (7 - len)) - 1);
|
||||
for (int i = 0; i < len - 1; i++) {
|
||||
if ((**in & 0xC0) != 0x80) return -1; // Upper bits must 1 0.
|
||||
ucc <<= 6;
|
||||
ucc |= *(*in)++ & 0x3F; // Grab 6 more bits of the code.
|
||||
}
|
||||
return ucc;
|
||||
}
|
||||
|
||||
// Wraps a string to a maximum length, inserting new lines where necessary. Any
|
||||
// existing whitespace will be collapsed down to a single space. A prefix or
|
||||
// suffix can be provided, which will be inserted before or after a wrapped
|
||||
// line, respectively.
|
||||
inline std::string WordWrap(const std::string in, size_t max_length,
|
||||
const std::string wrapped_line_prefix,
|
||||
const std::string wrapped_line_suffix) {
|
||||
std::istringstream in_stream(in);
|
||||
std::string wrapped, line, word;
|
||||
|
||||
in_stream >> word;
|
||||
line = word;
|
||||
|
||||
while (in_stream >> word) {
|
||||
if ((line.length() + 1 + word.length() + wrapped_line_suffix.length()) <
|
||||
max_length) {
|
||||
line += " " + word;
|
||||
} else {
|
||||
wrapped += line + wrapped_line_suffix + "\n";
|
||||
line = wrapped_line_prefix + word;
|
||||
}
|
||||
}
|
||||
wrapped += line;
|
||||
|
||||
return wrapped;
|
||||
}
|
||||
|
||||
} // namespace flatbuffers
|
||||
|
||||
#endif // FLATBUFFERS_UTIL_H_
|
||||
|
||||
27
java/com/google/flatbuffers/Constants.java
Normal file
27
java/com/google/flatbuffers/Constants.java
Normal file
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* Copyright 2014 Google Inc. All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.google.flatbuffers;
|
||||
|
||||
// Class that holds shared constants.
|
||||
|
||||
public class Constants {
|
||||
// Java doesn't seem to have these.
|
||||
static final int SIZEOF_SHORT = 2;
|
||||
static final int SIZEOF_INT = 4;
|
||||
static final int FILE_IDENTIFIER_LENGTH = 4;
|
||||
}
|
||||
|
||||
523
java/com/google/flatbuffers/FlatBufferBuilder.java
Normal file
523
java/com/google/flatbuffers/FlatBufferBuilder.java
Normal file
@@ -0,0 +1,523 @@
|
||||
/*
|
||||
* Copyright 2014 Google Inc. All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.google.flatbuffers;
|
||||
|
||||
import static com.google.flatbuffers.Constants.*;
|
||||
import java.util.Arrays;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.nio.charset.Charset;
|
||||
|
||||
/**
|
||||
* Class that helps you build a FlatBuffer. See the section
|
||||
* <a href="http://google.github.io/flatbuffers/md__java_usage.html">"Use in Java"</a> in the
|
||||
* main FlatBuffers documentation.
|
||||
*/
|
||||
public class FlatBufferBuilder {
|
||||
ByteBuffer bb; // Where we construct the FlatBuffer.
|
||||
int space; // Remaining space in the ByteBuffer.
|
||||
static final Charset utf8charset = Charset.forName("UTF-8");
|
||||
int minalign = 1; // Minimum alignment encountered so far.
|
||||
int[] vtable = null; // The vtable for the current table.
|
||||
int vtable_in_use = 0; // The amount of fields we're actually using.
|
||||
boolean nested = false; // Whether we are currently serializing a table.
|
||||
int object_start; // Starting offset of the current struct/table.
|
||||
int[] vtables = new int[16]; // List of offsets of all vtables.
|
||||
int num_vtables = 0; // Number of entries in `vtables` in use.
|
||||
int vector_num_elems = 0; // For the current vector being built.
|
||||
boolean force_defaults = false; // False omits default values from the serialized data
|
||||
|
||||
/**
|
||||
* Start with a buffer of size {@code initial_size}, then grow as required.
|
||||
*
|
||||
* @param initial_size The initial size of the internal buffer to use
|
||||
*/
|
||||
public FlatBufferBuilder(int initial_size) {
|
||||
if (initial_size <= 0) initial_size = 1;
|
||||
space = initial_size;
|
||||
bb = newByteBuffer(initial_size);
|
||||
}
|
||||
|
||||
/**
|
||||
* Start with a buffer of 1KiB, then grow as required.
|
||||
*/
|
||||
public FlatBufferBuilder() {
|
||||
this(1024);
|
||||
}
|
||||
|
||||
/**
|
||||
* Alternative constructor allowing reuse of {@link ByteBuffer}s. The builder
|
||||
* can still grow the buffer as necessary. User classes should make sure
|
||||
* to call {@link #dataBuffer()} to obtain the resulting encoded message
|
||||
*
|
||||
* @param existing_bb The byte buffer to reuse
|
||||
*/
|
||||
public FlatBufferBuilder(ByteBuffer existing_bb) {
|
||||
init(existing_bb);
|
||||
}
|
||||
|
||||
/**
|
||||
* Alternative initializer that allows reusing this object on an existing
|
||||
* ByteBuffer. This method resets the builder's internal state, but keeps
|
||||
* objects that have been allocated for temporary storage.
|
||||
*
|
||||
* @param existing_bb The byte buffer to reuse
|
||||
* @return this
|
||||
*/
|
||||
public FlatBufferBuilder init(ByteBuffer existing_bb){
|
||||
bb = existing_bb;
|
||||
bb.clear();
|
||||
bb.order(ByteOrder.LITTLE_ENDIAN);
|
||||
minalign = 1;
|
||||
space = bb.capacity();
|
||||
vtable_in_use = 0;
|
||||
nested = false;
|
||||
object_start = 0;
|
||||
num_vtables = 0;
|
||||
vector_num_elems = 0;
|
||||
return this;
|
||||
}
|
||||
|
||||
static ByteBuffer newByteBuffer(int capacity) {
|
||||
ByteBuffer newbb = ByteBuffer.allocate(capacity);
|
||||
newbb.order(ByteOrder.LITTLE_ENDIAN);
|
||||
return newbb;
|
||||
}
|
||||
|
||||
/**
|
||||
* Doubles the size of the backing {link ByteBuffer} and copies the old data towards the
|
||||
* end of the new buffer (since we build the buffer backwards).
|
||||
*
|
||||
* @param bb The current buffer with the existing data
|
||||
* @return A new byte buffer with the old data copied copied to it. The data is
|
||||
* located at the end of the buffer.
|
||||
*/
|
||||
static ByteBuffer growByteBuffer(ByteBuffer bb) {
|
||||
int old_buf_size = bb.capacity();
|
||||
if ((old_buf_size & 0xC0000000) != 0) // Ensure we don't grow beyond what fits in an int.
|
||||
throw new AssertionError("FlatBuffers: cannot grow buffer beyond 2 gigabytes.");
|
||||
int new_buf_size = old_buf_size << 1;
|
||||
bb.position(0);
|
||||
ByteBuffer nbb = newByteBuffer(new_buf_size);
|
||||
nbb.position(new_buf_size - old_buf_size);
|
||||
nbb.put(bb);
|
||||
return nbb;
|
||||
}
|
||||
|
||||
/**
|
||||
* Offset relative to the end of the buffer.
|
||||
*
|
||||
* @return Offset relative to the end of the buffer.
|
||||
*/
|
||||
public int offset() {
|
||||
return bb.capacity() - space;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add zero valued bytes to prepare a new entry to be added
|
||||
*
|
||||
* @param byte_size Number of bytes to add.
|
||||
*/
|
||||
public void pad(int byte_size) {
|
||||
for (int i = 0; i < byte_size; i++) bb.put(--space, (byte)0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare to write an element of {@code size} after {@code additional_bytes}
|
||||
* have been written, e.g. if you write a string, you need to align such
|
||||
* the int length field is aligned to {@link com.google.flatbuffers.Constants#SIZEOF_INT}, and
|
||||
* the string data follows it directly. If all you need to do is alignment, {@code additional_bytes}
|
||||
* will be 0.
|
||||
*
|
||||
* @param size This is the of the new element to write
|
||||
* @param additional_bytes The padding size
|
||||
*/
|
||||
public void prep(int size, int additional_bytes) {
|
||||
// Track the biggest thing we've ever aligned to.
|
||||
if (size > minalign) minalign = size;
|
||||
// Find the amount of alignment needed such that `size` is properly
|
||||
// aligned after `additional_bytes`
|
||||
int align_size = ((~(bb.capacity() - space + additional_bytes)) + 1) & (size - 1);
|
||||
// Reallocate the buffer if needed.
|
||||
while (space < align_size + size + additional_bytes) {
|
||||
int old_buf_size = bb.capacity();
|
||||
bb = growByteBuffer(bb);
|
||||
space += bb.capacity() - old_buf_size;
|
||||
}
|
||||
pad(align_size);
|
||||
}
|
||||
|
||||
// Add a scalar to the buffer, backwards from the current location.
|
||||
// Doesn't align nor check for space.
|
||||
public void putBoolean(boolean x) { bb.put (space -= 1, (byte)(x ? 1 : 0)); }
|
||||
public void putByte (byte x) { bb.put (space -= 1, x); }
|
||||
public void putShort (short x) { bb.putShort (space -= 2, x); }
|
||||
public void putInt (int x) { bb.putInt (space -= 4, x); }
|
||||
public void putLong (long x) { bb.putLong (space -= 8, x); }
|
||||
public void putFloat (float x) { bb.putFloat (space -= 4, x); }
|
||||
public void putDouble (double x) { bb.putDouble(space -= 8, x); }
|
||||
|
||||
// Adds a scalar to the buffer, properly aligned, and the buffer grown
|
||||
// if needed.
|
||||
public void addBoolean(boolean x) { prep(1, 0); putBoolean(x); }
|
||||
public void addByte (byte x) { prep(1, 0); putByte (x); }
|
||||
public void addShort (short x) { prep(2, 0); putShort (x); }
|
||||
public void addInt (int x) { prep(4, 0); putInt (x); }
|
||||
public void addLong (long x) { prep(8, 0); putLong (x); }
|
||||
public void addFloat (float x) { prep(4, 0); putFloat (x); }
|
||||
public void addDouble (double x) { prep(8, 0); putDouble (x); }
|
||||
|
||||
/**
|
||||
* Adds on offset, relative to where it will be written.
|
||||
*
|
||||
* @param off The offset to add
|
||||
*/
|
||||
public void addOffset(int off) {
|
||||
prep(SIZEOF_INT, 0); // Ensure alignment is already done.
|
||||
assert off <= offset();
|
||||
off = offset() - off + SIZEOF_INT;
|
||||
putInt(off);
|
||||
}
|
||||
|
||||
/**
|
||||
* Start a new array/vector of objects. Users usually will not call
|
||||
* this directly. The {@code FlatBuffers} compiler will create a start/end
|
||||
* method for vector types in generated code.
|
||||
* <p>
|
||||
* The expected sequence of calls is:
|
||||
* <ol>
|
||||
* <li>Start the array using this method.</li>
|
||||
* <li>Call {@link #addOffset(int)} {@code num_elems} number of times to set
|
||||
* the offset of each element in the array.</li>
|
||||
* <li>Call {@link #endVector()} to retrieve the offset of the array.</li>
|
||||
* </ol>
|
||||
* <p>
|
||||
* For example, to create an array of strings, do:
|
||||
* <pre>{@code
|
||||
* // Need 10 strings
|
||||
* FlatBufferBuilder builder = new FlatBufferBuilder(existingBuffer);
|
||||
* int[] offsets = new int[10];
|
||||
*
|
||||
* for (int i = 0; i < 10; i++) {
|
||||
* offsets[i] = fbb.createString(" " + i);
|
||||
* }
|
||||
*
|
||||
* // Have the strings in the buffer, but don't have a vector.
|
||||
* // Add a vector that references the newly created strings:
|
||||
* builder.startVector(4, offsets.length, 4);
|
||||
*
|
||||
* // Add each string to the newly created vector
|
||||
* // The strings are added in reverse order since the buffer
|
||||
* // is filled in back to front
|
||||
* for (int i = offsets.length - 1; i >= 0; i--) {
|
||||
* builder.addOffset(offsets[i]);
|
||||
* }
|
||||
*
|
||||
* // Finish off the vector
|
||||
* int offsetOfTheVector = fbb.endVector();
|
||||
* }</pre>
|
||||
*
|
||||
* @param elem_size The size of each element in the array
|
||||
* @param num_elems The number of elements in the array
|
||||
* @param alignment The alignment of the array
|
||||
*/
|
||||
public void startVector(int elem_size, int num_elems, int alignment) {
|
||||
notNested();
|
||||
vector_num_elems = num_elems;
|
||||
prep(SIZEOF_INT, elem_size * num_elems);
|
||||
prep(alignment, elem_size * num_elems); // Just in case alignment > int.
|
||||
}
|
||||
|
||||
/**
|
||||
* Finish off the creation of an array and all its elements. The array
|
||||
* must be created with {@link #startVector(int, int, int)}.
|
||||
*
|
||||
* @return The offset at which the newly created array starts.
|
||||
* @see #startVector(int, int, int)
|
||||
*/
|
||||
public int endVector() {
|
||||
putInt(vector_num_elems);
|
||||
return offset();
|
||||
}
|
||||
|
||||
/**
|
||||
* Encode the string {@code s} in the buffer using UTF-8.
|
||||
*
|
||||
* @param s The string to encode
|
||||
* @return The offset in the buffer where the encoded string starts
|
||||
*/
|
||||
public int createString(String s) {
|
||||
byte[] utf8 = s.getBytes(utf8charset);
|
||||
addByte((byte)0);
|
||||
startVector(1, utf8.length, 1);
|
||||
bb.position(space -= utf8.length);
|
||||
bb.put(utf8, 0, utf8.length);
|
||||
return endVector();
|
||||
}
|
||||
|
||||
/**
|
||||
* Encode the string {@code s} in the buffer using UTF-8.
|
||||
*
|
||||
* @param s An already encoded UTF-8 string
|
||||
* @return The offset in the buffer where the encoded string starts
|
||||
*/
|
||||
public int createString(ByteBuffer s) {
|
||||
int length = s.remaining();
|
||||
addByte((byte)0);
|
||||
startVector(1, length, 1);
|
||||
bb.position(space -= length);
|
||||
bb.put(s);
|
||||
return endVector();
|
||||
}
|
||||
|
||||
/**
|
||||
* Should not be creating any other object, string or vector
|
||||
* while an object is being constructed
|
||||
*/
|
||||
public void notNested() {
|
||||
if (nested)
|
||||
throw new AssertionError("FlatBuffers: object serialization must not be nested.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Structures are always stored inline, they need to be created right
|
||||
* where they're used. You'll get this assertion failure if you
|
||||
* created it elsewhere.
|
||||
*
|
||||
* @param obj The offset of the created object
|
||||
*/
|
||||
public void Nested(int obj) {
|
||||
if (obj != offset())
|
||||
throw new AssertionError("FlatBuffers: struct must be serialized inline.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Start encoding a new object in the buffer. Users will not usually need to
|
||||
* call this directly. The {@code FlatBuffers} compiler will generate helper methods
|
||||
* that call this method internally.
|
||||
* <p>
|
||||
* For example, using the "Monster" code found on the
|
||||
* <a href="http://google.github.io/flatbuffers/md__java_usage.html">landing page</a>. An
|
||||
* object of type {@code Monster} can be created using the following code:
|
||||
*
|
||||
* <pre>{@code
|
||||
* int testArrayOfString = Monster.createTestarrayofstringVector(fbb, new int[] {
|
||||
* fbb.createString("test1"),
|
||||
* fbb.createString("test2")
|
||||
* });
|
||||
*
|
||||
* Monster.startMonster(fbb);
|
||||
* Monster.addPos(fbb, Vec3.createVec3(fbb, 1.0f, 2.0f, 3.0f, 3.0,
|
||||
* Color.Green, (short)5, (byte)6));
|
||||
* Monster.addHp(fbb, (short)80);
|
||||
* Monster.addName(fbb, str);
|
||||
* Monster.addInventory(fbb, inv);
|
||||
* Monster.addTestType(fbb, (byte)Any.Monster);
|
||||
* Monster.addTest(fbb, mon2);
|
||||
* Monster.addTest4(fbb, test4);
|
||||
* Monster.addTestarrayofstring(fbb, testArrayOfString);
|
||||
* int mon = Monster.endMonster(fbb);
|
||||
* }</pre>
|
||||
* <p>
|
||||
* Here:
|
||||
* <ul>
|
||||
* <li>The call to {@code Monster#startMonster(FlatBufferBuilder)} will call this
|
||||
* method with the right number of fields set.</li>
|
||||
* <li>{@code Monster#endMonster(FlatBufferBuilder)} will ensure {@link #endObject()} is called.</li>
|
||||
* </ul>
|
||||
* <p>
|
||||
* It's not recommended to call this method directly. If it's called manually, you must ensure
|
||||
* to audit all calls to it whenever fields are added or removed from your schema. This is
|
||||
* automatically done by the code generated by the {@code FlatBuffers} compiler.
|
||||
*
|
||||
* @param numfields The number of fields found in this object.
|
||||
*/
|
||||
public void startObject(int numfields) {
|
||||
notNested();
|
||||
if (vtable == null || vtable.length < numfields) vtable = new int[numfields];
|
||||
vtable_in_use = numfields;
|
||||
Arrays.fill(vtable, 0, vtable_in_use, 0);
|
||||
nested = true;
|
||||
object_start = offset();
|
||||
}
|
||||
|
||||
// Add a scalar to a table at `o` into its vtable, with value `x` and default `d`
|
||||
public void addBoolean(int o, boolean x, boolean d) { if(force_defaults || x != d) { addBoolean(x); slot(o); } }
|
||||
public void addByte (int o, byte x, int d) { if(force_defaults || x != d) { addByte (x); slot(o); } }
|
||||
public void addShort (int o, short x, int d) { if(force_defaults || x != d) { addShort (x); slot(o); } }
|
||||
public void addInt (int o, int x, int d) { if(force_defaults || x != d) { addInt (x); slot(o); } }
|
||||
public void addLong (int o, long x, long d) { if(force_defaults || x != d) { addLong (x); slot(o); } }
|
||||
public void addFloat (int o, float x, double d) { if(force_defaults || x != d) { addFloat (x); slot(o); } }
|
||||
public void addDouble (int o, double x, double d) { if(force_defaults || x != d) { addDouble (x); slot(o); } }
|
||||
public void addOffset (int o, int x, int d) { if(force_defaults || x != d) { addOffset (x); slot(o); } }
|
||||
|
||||
// Structs are stored inline, so nothing additional is being added. `d` is always 0.
|
||||
public void addStruct(int voffset, int x, int d) {
|
||||
if(x != d) {
|
||||
Nested(x);
|
||||
slot(voffset);
|
||||
}
|
||||
}
|
||||
|
||||
// Set the current vtable at `voffset` to the current location in the buffer.
|
||||
public void slot(int voffset) {
|
||||
vtable[voffset] = offset();
|
||||
}
|
||||
|
||||
/**
|
||||
* Finish off writing the object that is under construction.
|
||||
*
|
||||
* @return The offset to the object inside {@link #dataBuffer()}
|
||||
* @see #startObject(int)
|
||||
*/
|
||||
public int endObject() {
|
||||
if (vtable == null || !nested)
|
||||
throw new AssertionError("FlatBuffers: endObject called without startObject");
|
||||
addInt(0);
|
||||
int vtableloc = offset();
|
||||
// Write out the current vtable.
|
||||
for (int i = vtable_in_use - 1; i >= 0 ; i--) {
|
||||
// Offset relative to the start of the table.
|
||||
short off = (short)(vtable[i] != 0 ? vtableloc - vtable[i] : 0);
|
||||
addShort(off);
|
||||
}
|
||||
|
||||
final int standard_fields = 2; // The fields below:
|
||||
addShort((short)(vtableloc - object_start));
|
||||
addShort((short)((vtable_in_use + standard_fields) * SIZEOF_SHORT));
|
||||
|
||||
// Search for an existing vtable that matches the current one.
|
||||
int existing_vtable = 0;
|
||||
outer_loop:
|
||||
for (int i = 0; i < num_vtables; i++) {
|
||||
int vt1 = bb.capacity() - vtables[i];
|
||||
int vt2 = space;
|
||||
short len = bb.getShort(vt1);
|
||||
if (len == bb.getShort(vt2)) {
|
||||
for (int j = SIZEOF_SHORT; j < len; j += SIZEOF_SHORT) {
|
||||
if (bb.getShort(vt1 + j) != bb.getShort(vt2 + j)) {
|
||||
continue outer_loop;
|
||||
}
|
||||
}
|
||||
existing_vtable = vtables[i];
|
||||
break outer_loop;
|
||||
}
|
||||
}
|
||||
|
||||
if (existing_vtable != 0) {
|
||||
// Found a match:
|
||||
// Remove the current vtable.
|
||||
space = bb.capacity() - vtableloc;
|
||||
// Point table to existing vtable.
|
||||
bb.putInt(space, existing_vtable - vtableloc);
|
||||
} else {
|
||||
// No match:
|
||||
// Add the location of the current vtable to the list of vtables.
|
||||
if (num_vtables == vtables.length) vtables = Arrays.copyOf(vtables, num_vtables * 2);
|
||||
vtables[num_vtables++] = offset();
|
||||
// Point table to current vtable.
|
||||
bb.putInt(bb.capacity() - vtableloc, offset() - vtableloc);
|
||||
}
|
||||
|
||||
nested = false;
|
||||
return vtableloc;
|
||||
}
|
||||
|
||||
// This checks a required field has been set in a given table that has
|
||||
// just been constructed.
|
||||
public void required(int table, int field) {
|
||||
int table_start = bb.capacity() - table;
|
||||
int vtable_start = table_start - bb.getInt(table_start);
|
||||
boolean ok = bb.getShort(vtable_start + field) != 0;
|
||||
// If this fails, the caller will show what field needs to be set.
|
||||
if (!ok)
|
||||
throw new AssertionError("FlatBuffers: field " + field + " must be set");
|
||||
}
|
||||
|
||||
public void finish(int root_table) {
|
||||
prep(minalign, SIZEOF_INT);
|
||||
addOffset(root_table);
|
||||
bb.position(space);
|
||||
}
|
||||
|
||||
public void finish(int root_table, String file_identifier) {
|
||||
prep(minalign, SIZEOF_INT + FILE_IDENTIFIER_LENGTH);
|
||||
if (file_identifier.length() != FILE_IDENTIFIER_LENGTH)
|
||||
throw new AssertionError("FlatBuffers: file identifier must be length " +
|
||||
FILE_IDENTIFIER_LENGTH);
|
||||
for (int i = FILE_IDENTIFIER_LENGTH - 1; i >= 0; i--) {
|
||||
addByte((byte)file_identifier.charAt(i));
|
||||
}
|
||||
finish(root_table);
|
||||
}
|
||||
|
||||
/**
|
||||
* In order to save space, fields that are set to their default value
|
||||
* don't get serialized into the buffer. Forcing defaults provides a
|
||||
* way to manually disable this optimization.
|
||||
*
|
||||
* @param forceDefaults true always serializes default values
|
||||
* @return this
|
||||
*/
|
||||
public FlatBufferBuilder forceDefaults(boolean forceDefaults){
|
||||
this.force_defaults = forceDefaults;
|
||||
return this;
|
||||
}
|
||||
|
||||
// Get the ByteBuffer representing the FlatBuffer. Only call this after you've
|
||||
// called finish(). The actual data starts at the ByteBuffer's current position,
|
||||
// not necessarily at 0.
|
||||
public ByteBuffer dataBuffer() { return bb; }
|
||||
|
||||
/**
|
||||
* The FlatBuffer data doesn't start at offset 0 in the {@link ByteBuffer}, but
|
||||
* now the {@code ByteBuffer}'s position is set to that location upon {@link #finish(int)}.
|
||||
*
|
||||
* @return The {@link ByteBuffer#position() position} the data starts in {@link #dataBuffer()}
|
||||
* @deprecated This method should not be needed anymore, but is left
|
||||
* here for the moment to document this API change. It will be removed in the future.
|
||||
*/
|
||||
@Deprecated
|
||||
private int dataStart() {
|
||||
return space;
|
||||
}
|
||||
|
||||
/**
|
||||
* Utility function for copying a byte array from {@code start} to
|
||||
* {@code start} + {@code length}
|
||||
*
|
||||
* @param start Start copying at this offset
|
||||
* @param length How many bytes to copy
|
||||
* @return A range copy of the {@link #dataBuffer() data buffer}
|
||||
* @throws IndexOutOfBoundsException If the range of bytes is ouf of bound
|
||||
*/
|
||||
public byte[] sizedByteArray(int start, int length){
|
||||
byte[] array = new byte[length];
|
||||
bb.position(start);
|
||||
bb.get(array);
|
||||
return array;
|
||||
}
|
||||
|
||||
/**
|
||||
* Utility function for copying a byte array that starts at 0.
|
||||
*
|
||||
* @return A full copy of the {@link #dataBuffer() data buffer}
|
||||
*/
|
||||
public byte[] sizedByteArray() {
|
||||
return sizedByteArray(space, bb.capacity() - space);
|
||||
}
|
||||
}
|
||||
2
java/flatbuffers/Struct.java → java/com/google/flatbuffers/Struct.java
Executable file → Normal file
2
java/flatbuffers/Struct.java → java/com/google/flatbuffers/Struct.java
Executable file → Normal file
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package flatbuffers;
|
||||
package com.google.flatbuffers;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
|
||||
107
java/com/google/flatbuffers/Table.java
Normal file
107
java/com/google/flatbuffers/Table.java
Normal file
@@ -0,0 +1,107 @@
|
||||
/*
|
||||
* Copyright 2014 Google Inc. All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.google.flatbuffers;
|
||||
|
||||
import static com.google.flatbuffers.Constants.*;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
|
||||
// All tables in the generated code derive from this class, and add their own accessors.
|
||||
public class Table {
|
||||
protected int bb_pos;
|
||||
protected ByteBuffer bb;
|
||||
|
||||
public ByteBuffer getByteBuffer() { return bb; }
|
||||
|
||||
// Look up a field in the vtable, return an offset into the object, or 0 if the field is not
|
||||
// present.
|
||||
protected int __offset(int vtable_offset) {
|
||||
int vtable = bb_pos - bb.getInt(bb_pos);
|
||||
return vtable_offset < bb.getShort(vtable) ? bb.getShort(vtable + vtable_offset) : 0;
|
||||
}
|
||||
|
||||
// Retrieve the relative offset stored at "offset"
|
||||
protected int __indirect(int offset) {
|
||||
return offset + bb.getInt(offset);
|
||||
}
|
||||
|
||||
// Create a java String from UTF-8 data stored inside the flatbuffer.
|
||||
// This allocates a new string and converts to wide chars upon each access,
|
||||
// which is not very efficient. Instead, each FlatBuffer string also comes with an
|
||||
// accessor based on __vector_as_bytebuffer below, which is much more efficient,
|
||||
// assuming your Java program can handle UTF-8 data directly.
|
||||
protected String __string(int offset) {
|
||||
offset += bb.getInt(offset);
|
||||
if (bb.hasArray()) {
|
||||
return new String(bb.array(), bb.arrayOffset() + offset + SIZEOF_INT, bb.getInt(offset), FlatBufferBuilder.utf8charset);
|
||||
} else {
|
||||
// We can't access .array(), since the ByteBuffer is read-only,
|
||||
// off-heap or a memory map
|
||||
ByteBuffer bb = this.bb.duplicate().order(ByteOrder.LITTLE_ENDIAN);
|
||||
// We're forced to make an extra copy:
|
||||
byte[] copy = new byte[bb.getInt(offset)];
|
||||
bb.position(offset + SIZEOF_INT);
|
||||
bb.get(copy);
|
||||
return new String(copy, 0, copy.length, FlatBufferBuilder.utf8charset);
|
||||
}
|
||||
}
|
||||
|
||||
// Get the length of a vector whose offset is stored at "offset" in this object.
|
||||
protected int __vector_len(int offset) {
|
||||
offset += bb_pos;
|
||||
offset += bb.getInt(offset);
|
||||
return bb.getInt(offset);
|
||||
}
|
||||
|
||||
// Get the start of data of a vector whose offset is stored at "offset" in this object.
|
||||
protected int __vector(int offset) {
|
||||
offset += bb_pos;
|
||||
return offset + bb.getInt(offset) + SIZEOF_INT; // data starts after the length
|
||||
}
|
||||
|
||||
// Get a whole vector as a ByteBuffer. This is efficient, since it only allocates a new
|
||||
// bytebuffer object, but does not actually copy the data, it still refers to the same
|
||||
// bytes as the original ByteBuffer.
|
||||
// Also useful with nested FlatBuffers etc.
|
||||
protected ByteBuffer __vector_as_bytebuffer(int vector_offset, int elem_size) {
|
||||
int o = __offset(vector_offset);
|
||||
if (o == 0) return null;
|
||||
ByteBuffer bb = this.bb.duplicate().order(ByteOrder.LITTLE_ENDIAN);
|
||||
int vectorstart = __vector(o);
|
||||
bb.position(vectorstart);
|
||||
bb.limit(vectorstart + __vector_len(o) * elem_size);
|
||||
return bb;
|
||||
}
|
||||
|
||||
// Initialize any Table-derived type to point to the union at the given offset.
|
||||
protected Table __union(Table t, int offset) {
|
||||
offset += bb_pos;
|
||||
t.bb_pos = offset + bb.getInt(offset);
|
||||
t.bb = bb;
|
||||
return t;
|
||||
}
|
||||
|
||||
protected static boolean __has_identifier(ByteBuffer bb, String ident) {
|
||||
if (ident.length() != FILE_IDENTIFIER_LENGTH)
|
||||
throw new AssertionError("FlatBuffers: file identifier must be length " +
|
||||
FILE_IDENTIFIER_LENGTH);
|
||||
for (int i = 0; i < FILE_IDENTIFIER_LENGTH; i++) {
|
||||
if (ident.charAt(i) != (char)bb.get(bb.position() + SIZEOF_INT + i)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -1,248 +0,0 @@
|
||||
/*
|
||||
* Copyright 2014 Google Inc. All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package flatbuffers;
|
||||
|
||||
import java.lang.String;
|
||||
import java.util.Arrays;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.nio.charset.Charset;
|
||||
|
||||
// Class that helps you build a FlatBuffer.
|
||||
// See the section "Use in Java" in the main FlatBuffers documentation.
|
||||
|
||||
public class FlatBufferBuilder {
|
||||
ByteBuffer bb; // Where we construct the FlatBuffer.
|
||||
int space; // Remaining space in the ByteBuffer.
|
||||
final Charset utf8charset = Charset.forName("UTF-8");
|
||||
int minalign = 1; // Minimum alignment encountered so far.
|
||||
int[] vtable; // The vtable for the current table, null otherwise.
|
||||
int object_start; // Starting offset of the current struct/table.
|
||||
int[] vtables = new int[16]; // List of offsets of all vtables.
|
||||
int num_vtables = 0; // Number of entries in `vtables` in use.
|
||||
int vector_num_elems = 0; // For the current vector being built.
|
||||
|
||||
// Java doesn't seem to have these.
|
||||
final int SIZEOF_SHORT = 2;
|
||||
final int SIZEOF_INT = 4;
|
||||
|
||||
// Start with a buffer of size `initial_size`, then grow as required.
|
||||
public FlatBufferBuilder(int initial_size) {
|
||||
space = initial_size;
|
||||
bb = newByteBuffer(new byte[initial_size]);
|
||||
}
|
||||
|
||||
ByteBuffer newByteBuffer(byte[] buf) {
|
||||
ByteBuffer newbb = ByteBuffer.wrap(buf);
|
||||
newbb.order(ByteOrder.LITTLE_ENDIAN);
|
||||
return newbb;
|
||||
}
|
||||
|
||||
// Doubles the size of the ByteBuffer, and copies the old data towards the
|
||||
// end of the new buffer (since we build the buffer backwards).
|
||||
ByteBuffer growByteBuffer(ByteBuffer bb) {
|
||||
byte[] old_buf = bb.array();
|
||||
int old_buf_size = old_buf.length;
|
||||
int new_buf_size = old_buf_size * 2;
|
||||
byte[] new_buf = new byte[new_buf_size];
|
||||
System.arraycopy(old_buf, 0, new_buf, new_buf_size - old_buf_size, old_buf_size);
|
||||
ByteBuffer nbb = newByteBuffer(new_buf);
|
||||
nbb.position(bb.position());
|
||||
return nbb;
|
||||
}
|
||||
|
||||
// Offset relative to the end of the buffer.
|
||||
public int offset() {
|
||||
return bb.array().length - space;
|
||||
}
|
||||
|
||||
public void pad(int byte_size) {
|
||||
for (int i = 0; i < byte_size; i++) bb.put(--space, (byte)0);
|
||||
}
|
||||
|
||||
// Prepare to write an element of `size` after `additional_bytes`
|
||||
// have been written, e.g. if you write a string, you need to align such
|
||||
// the int length field is aligned to SIZEOF_INT, and the string data follows it
|
||||
// directly.
|
||||
// If all you need to do is align, `additional_bytes` will be 0.
|
||||
public void prep(int size, int additional_bytes) {
|
||||
// Track the biggest thing we've ever aligned to.
|
||||
if (size > minalign) minalign = size;
|
||||
// Find the amount of alignment needed such that `size` is properly
|
||||
// aligned after `additional_bytes`
|
||||
int align_size = ((~(bb.array().length - space + additional_bytes)) + 1) & (size - 1);
|
||||
// Reallocate the buffer if needed.
|
||||
while (space < align_size + size + additional_bytes) {
|
||||
int old_buf_size = bb.array().length;
|
||||
bb = growByteBuffer(bb);
|
||||
space += bb.array().length - old_buf_size;
|
||||
}
|
||||
pad(align_size);
|
||||
}
|
||||
|
||||
// Add a scalar to the buffer, backwards from the current location.
|
||||
// Doesn't align nor check for space.
|
||||
public void putByte (byte x) { bb.put (space -= 1, x); }
|
||||
public void putShort (short x) { bb.putShort (space -= 2, x); }
|
||||
public void putInt (int x) { bb.putInt (space -= 4, x); }
|
||||
public void putLong (long x) { bb.putLong (space -= 8, x); }
|
||||
public void putFloat (float x) { bb.putFloat (space -= 4, x); }
|
||||
public void putDouble(double x) { bb.putDouble(space -= 8, x); }
|
||||
|
||||
// Adds a scalar to the buffer, properly aligned, and the buffer grown
|
||||
// if needed.
|
||||
public void addByte (byte x) { prep(1, 0); putByte (x); }
|
||||
public void addShort (short x) { prep(2, 0); putShort (x); }
|
||||
public void addInt (int x) { prep(4, 0); putInt (x); }
|
||||
public void addLong (long x) { prep(8, 0); putLong (x); }
|
||||
public void addFloat (float x) { prep(4, 0); putFloat (x); }
|
||||
public void addDouble(double x) { prep(8, 0); putDouble(x); }
|
||||
|
||||
// Adds on offset, relative to where it will be written.
|
||||
public void addOffset(int off) {
|
||||
prep(SIZEOF_INT, 0); // Ensure alignment is already done.
|
||||
assert off <= offset();
|
||||
off = offset() - off + SIZEOF_INT;
|
||||
putInt(off);
|
||||
}
|
||||
|
||||
public void startVector(int elem_size, int num_elems) {
|
||||
notNested();
|
||||
vector_num_elems = num_elems;
|
||||
prep(SIZEOF_INT, elem_size * num_elems);
|
||||
}
|
||||
|
||||
public int endVector() {
|
||||
putInt(vector_num_elems);
|
||||
return offset();
|
||||
}
|
||||
|
||||
public int createString(String s) {
|
||||
byte[] utf8 = s.getBytes(utf8charset);
|
||||
bb.put(--space, (byte)0);
|
||||
startVector(1, utf8.length);
|
||||
System.arraycopy(utf8, 0, bb.array(), space -= utf8.length, utf8.length);
|
||||
return endVector();
|
||||
}
|
||||
|
||||
public void notNested() {
|
||||
// You should not be creating any other objects or strings/vectors
|
||||
// while an object is being constructed
|
||||
if (vtable != null)
|
||||
throw new AssertionError("FlatBuffers: object serialization must not be nested.");
|
||||
}
|
||||
|
||||
public void Nested(int obj) {
|
||||
// Structs are always stored inline, so need to be created right
|
||||
// where they are used. You'll get this assert if you created it
|
||||
// elsewhere.
|
||||
if (obj != offset())
|
||||
throw new AssertionError("FlatBuffers: struct must be serialized inline.");
|
||||
}
|
||||
|
||||
public void startObject(int numfields) {
|
||||
notNested();
|
||||
vtable = new int[numfields];
|
||||
object_start = offset();
|
||||
}
|
||||
|
||||
// Add a scalar to a table at `o` into its vtable, with value `x` and default `d`
|
||||
public void addByte (int o, byte x, int d) { if(x != d) { addByte (x); slot(o); } }
|
||||
public void addShort (int o, short x, int d) { if(x != d) { addShort (x); slot(o); } }
|
||||
public void addInt (int o, int x, int d) { if(x != d) { addInt (x); slot(o); } }
|
||||
public void addLong (int o, long x, long d) { if(x != d) { addLong (x); slot(o); } }
|
||||
public void addFloat (int o, float x, double d) { if(x != d) { addFloat (x); slot(o); } }
|
||||
public void addDouble(int o, double x, double d) { if(x != d) { addDouble(x); slot(o); } }
|
||||
public void addOffset(int o, int x, int d) { if(x != d) { addOffset(x); slot(o); } }
|
||||
|
||||
// Structs are stored inline, so nothing additional is being added. `d` is always 0.
|
||||
public void addStruct(int voffset, int x, int d) {
|
||||
if(x != d) {
|
||||
Nested(x);
|
||||
slot(voffset);
|
||||
}
|
||||
}
|
||||
|
||||
// Set the current vtable at `voffset` to the current location in the buffer.
|
||||
public void slot(int voffset) {
|
||||
vtable[voffset] = offset();
|
||||
}
|
||||
|
||||
public int endObject() {
|
||||
assert vtable != null; // calling endObject without a startObject
|
||||
addInt(0);
|
||||
int vtableloc = offset();
|
||||
// Write out the current vtable.
|
||||
for (int i = vtable.length - 1; i >= 0 ; i--) {
|
||||
// Offset relative to the start of the table.
|
||||
short off = (short)(vtable[i] != 0 ? vtableloc - vtable[i] : 0);
|
||||
putShort(off);
|
||||
}
|
||||
|
||||
final int standard_fields = 2; // The fields below:
|
||||
putShort((short)(vtableloc - object_start));
|
||||
putShort((short)((vtable.length + standard_fields) * SIZEOF_SHORT));
|
||||
|
||||
// Search for an existing vtable that matches the current one.
|
||||
int existing_vtable = 0;
|
||||
outer_loop:
|
||||
for (int i = 0; i < num_vtables; i++) {
|
||||
int vt1 = bb.array().length - vtables[i];
|
||||
int vt2 = space;
|
||||
short len = bb.getShort(vt1);
|
||||
if (len == bb.getShort(vt2)) {
|
||||
for (int j = SIZEOF_SHORT; j < len; j += SIZEOF_SHORT) {
|
||||
if (bb.getShort(vt1 + j) != bb.getShort(vt2 + j)) {
|
||||
continue outer_loop;
|
||||
}
|
||||
}
|
||||
existing_vtable = vtables[i];
|
||||
break outer_loop;
|
||||
}
|
||||
}
|
||||
|
||||
if (existing_vtable != 0) {
|
||||
// Found a match:
|
||||
// Remove the current vtable.
|
||||
space = bb.array().length - vtableloc;
|
||||
// Point table to existing vtable.
|
||||
bb.putInt(space, existing_vtable - vtableloc);
|
||||
} else {
|
||||
// No match:
|
||||
// Add the location of the current vtable to the list of vtables.
|
||||
if (num_vtables == vtables.length) vtables = Arrays.copyOf(vtables, num_vtables * 2);
|
||||
vtables[num_vtables++] = offset();
|
||||
// Point table to current vtable.
|
||||
bb.putInt(bb.array().length - vtableloc, offset() - vtableloc);
|
||||
}
|
||||
|
||||
vtable = null;
|
||||
return vtableloc;
|
||||
}
|
||||
|
||||
public void finish(int root_table) {
|
||||
prep(minalign, SIZEOF_INT);
|
||||
addOffset(root_table);
|
||||
}
|
||||
|
||||
public ByteBuffer dataBuffer() { return bb; }
|
||||
|
||||
// The FlatBuffer data doesn't start at offset 0 in the ByteBuffer:
|
||||
public int dataStart() {
|
||||
return bb.array().length - offset();
|
||||
}
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
/*
|
||||
* Copyright 2014 Google Inc. All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package flatbuffers;
|
||||
|
||||
import java.lang.String;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.Charset;
|
||||
|
||||
// All tables in the generated code derive from this class, and add their own accessors.
|
||||
public class Table {
|
||||
protected int bb_pos;
|
||||
protected ByteBuffer bb;
|
||||
|
||||
final int SIZEOF_INT = 4;
|
||||
|
||||
// Look up a field in the vtable, return an offset into the object, or 0 if the field is not
|
||||
// present.
|
||||
protected int __offset(int vtable_offset) {
|
||||
int vtable = bb_pos - bb.getInt(bb_pos);
|
||||
return vtable_offset < bb.getShort(vtable) ? bb.getShort(vtable + vtable_offset) : 0;
|
||||
}
|
||||
|
||||
// Retrieve the relative offset stored at "offset"
|
||||
protected int __indirect(int offset) {
|
||||
return offset + bb.getInt(offset);
|
||||
}
|
||||
|
||||
// Create a java String from UTF-8 data stored inside the flatbuffer.
|
||||
protected String __string(int offset) {
|
||||
offset += bb_pos;
|
||||
offset += bb.getInt(offset);
|
||||
return new String(bb.array(), offset + SIZEOF_INT, bb.getInt(offset), Charset.forName("UTF-8"));
|
||||
}
|
||||
|
||||
// Get the length of a vector whose offset is stored at "offset" in this object.
|
||||
protected int __vector_len(int offset) {
|
||||
offset += bb_pos;
|
||||
offset += bb.getInt(offset);
|
||||
return bb.getInt(offset);
|
||||
}
|
||||
|
||||
// Get the start of data of a vector whose offset is stored at "offset" in this object.
|
||||
protected int __vector(int offset) {
|
||||
offset += bb_pos;
|
||||
return offset + bb.getInt(offset) + SIZEOF_INT; // data starts after the length
|
||||
}
|
||||
|
||||
// Initialize any Table-derived type to point to the union at the given offset.
|
||||
protected Table __union(Table t, int offset) {
|
||||
offset += bb_pos;
|
||||
t.bb_pos = offset + bb.getInt(offset);
|
||||
t.bb = bb;
|
||||
return t;
|
||||
}
|
||||
}
|
||||
84
java/pom.xml
Normal file
84
java/pom.xml
Normal file
@@ -0,0 +1,84 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.google.flatbuffers</groupId>
|
||||
<artifactId>flatbuffers-java</artifactId>
|
||||
<version>1.2.0-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>FlatBuffers Java API</name>
|
||||
<description>
|
||||
Memory Efficient Serialization Library
|
||||
</description>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
|
||||
<url>https://github.com/google/flatbuffers</url>
|
||||
<licenses>
|
||||
<license>
|
||||
<name>Apache License V2.0</name>
|
||||
<url>https://raw.githubusercontent.com/google/flatbuffers/master/LICENSE.txt</url>
|
||||
<distribution>repo</distribution>
|
||||
</license>
|
||||
</licenses>
|
||||
<scm>
|
||||
<url>https://github.com/google/flatbuffers</url>
|
||||
<connection>
|
||||
scm:git:https://github.com/google/flatbuffers.git
|
||||
</connection>
|
||||
</scm>
|
||||
<dependencies>
|
||||
</dependencies>
|
||||
<build>
|
||||
<sourceDirectory>./</sourceDirectory>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>1.6</source>
|
||||
<target>1.6</target>
|
||||
</configuration>
|
||||
<version>3.2</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<includes>
|
||||
<include>**/*Test.java</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
<version>2.18.1</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-source-plugin</artifactId>
|
||||
<version>2.3</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>attach-sources</id>
|
||||
<goals>
|
||||
<goal>jar</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-javadoc-plugin</artifactId>
|
||||
<version>2.9.1</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>attach-javadocs</id>
|
||||
<goals>
|
||||
<goal>jar</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
|
||||
1072
js/flatbuffers.js
Normal file
1072
js/flatbuffers.js
Normal file
File diff suppressed because it is too large
Load Diff
444
net/FlatBuffers/ByteBuffer.cs
Executable file
444
net/FlatBuffers/ByteBuffer.cs
Executable file
@@ -0,0 +1,444 @@
|
||||
/*
|
||||
* Copyright 2014 Google Inc. All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
//#define UNSAFE_BYTEBUFFER // uncomment this line to use faster ByteBuffer
|
||||
|
||||
using System;
|
||||
|
||||
namespace FlatBuffers
|
||||
{
|
||||
/// <summary>
|
||||
/// Class to mimic Java's ByteBuffer which is used heavily in Flatbuffers.
|
||||
/// If your execution environment allows unsafe code, you should enable
|
||||
/// unsafe code in your project and #define UNSAFE_BYTEBUFFER to use a
|
||||
/// MUCH faster version of ByteBuffer.
|
||||
/// </summary>
|
||||
public class ByteBuffer
|
||||
{
|
||||
private readonly byte[] _buffer;
|
||||
private int _pos; // Must track start of the buffer.
|
||||
|
||||
public int Length { get { return _buffer.Length; } }
|
||||
|
||||
public byte[] Data { get { return _buffer; } }
|
||||
|
||||
public ByteBuffer(byte[] buffer) : this(buffer, 0) { }
|
||||
|
||||
public ByteBuffer(byte[] buffer, int pos)
|
||||
{
|
||||
_buffer = buffer;
|
||||
_pos = pos;
|
||||
}
|
||||
|
||||
public int Position {
|
||||
get { return _pos; }
|
||||
set { _pos = value; }
|
||||
}
|
||||
|
||||
public void Reset()
|
||||
{
|
||||
_pos = 0;
|
||||
}
|
||||
|
||||
// Pre-allocated helper arrays for convertion.
|
||||
private float[] floathelper = new[] { 0.0f };
|
||||
private int[] inthelper = new[] { 0 };
|
||||
private double[] doublehelper = new[] { 0.0 };
|
||||
private ulong[] ulonghelper = new[] { 0UL };
|
||||
|
||||
// Helper functions for the unsafe version.
|
||||
static public ushort ReverseBytes(ushort input)
|
||||
{
|
||||
return (ushort)(((input & 0x00FFU) << 8) |
|
||||
((input & 0xFF00U) >> 8));
|
||||
}
|
||||
static public uint ReverseBytes(uint input)
|
||||
{
|
||||
return ((input & 0x000000FFU) << 24) |
|
||||
((input & 0x0000FF00U) << 8) |
|
||||
((input & 0x00FF0000U) >> 8) |
|
||||
((input & 0xFF000000U) >> 24);
|
||||
}
|
||||
static public ulong ReverseBytes(ulong input)
|
||||
{
|
||||
return (((input & 0x00000000000000FFUL) << 56) |
|
||||
((input & 0x000000000000FF00UL) << 40) |
|
||||
((input & 0x0000000000FF0000UL) << 24) |
|
||||
((input & 0x00000000FF000000UL) << 8) |
|
||||
((input & 0x000000FF00000000UL) >> 8) |
|
||||
((input & 0x0000FF0000000000UL) >> 24) |
|
||||
((input & 0x00FF000000000000UL) >> 40) |
|
||||
((input & 0xFF00000000000000UL) >> 56));
|
||||
}
|
||||
|
||||
#if !UNSAFE_BYTEBUFFER
|
||||
// Helper functions for the safe (but slower) version.
|
||||
protected void WriteLittleEndian(int offset, int count, ulong data)
|
||||
{
|
||||
if (BitConverter.IsLittleEndian)
|
||||
{
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
_buffer[offset + i] = (byte)(data >> i * 8);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
_buffer[offset + count - 1 - i] = (byte)(data >> i * 8);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected ulong ReadLittleEndian(int offset, int count)
|
||||
{
|
||||
AssertOffsetAndLength(offset, count);
|
||||
ulong r = 0;
|
||||
if (BitConverter.IsLittleEndian)
|
||||
{
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
r |= (ulong)_buffer[offset + i] << i * 8;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
r |= (ulong)_buffer[offset + count - 1 - i] << i * 8;
|
||||
}
|
||||
}
|
||||
return r;
|
||||
}
|
||||
#endif // !UNSAFE_BYTEBUFFER
|
||||
|
||||
private void AssertOffsetAndLength(int offset, int length)
|
||||
{
|
||||
if (offset < 0 ||
|
||||
offset >= _buffer.Length ||
|
||||
offset + length > _buffer.Length)
|
||||
throw new ArgumentOutOfRangeException();
|
||||
}
|
||||
|
||||
public void PutSbyte(int offset, sbyte value)
|
||||
{
|
||||
AssertOffsetAndLength(offset, sizeof(sbyte));
|
||||
_buffer[offset] = (byte)value;
|
||||
}
|
||||
|
||||
public void PutByte(int offset, byte value)
|
||||
{
|
||||
AssertOffsetAndLength(offset, sizeof(byte));
|
||||
_buffer[offset] = value;
|
||||
}
|
||||
|
||||
// this method exists in order to conform with Java ByteBuffer standards
|
||||
public void Put(int offset, byte value)
|
||||
{
|
||||
PutByte(offset, value);
|
||||
}
|
||||
|
||||
#if UNSAFE_BYTEBUFFER
|
||||
// Unsafe but more efficient versions of Put*.
|
||||
public void PutShort(int offset, short value)
|
||||
{
|
||||
PutUshort(offset, (ushort)value);
|
||||
}
|
||||
|
||||
public unsafe void PutUshort(int offset, ushort value)
|
||||
{
|
||||
AssertOffsetAndLength(offset, sizeof(ushort));
|
||||
fixed (byte* ptr = _buffer)
|
||||
{
|
||||
*(ushort*)(ptr + offset) = BitConverter.IsLittleEndian
|
||||
? value
|
||||
: ReverseBytes(value);
|
||||
}
|
||||
_pos = offset;
|
||||
}
|
||||
|
||||
public void PutInt(int offset, int value)
|
||||
{
|
||||
PutUint(offset, (uint)value);
|
||||
}
|
||||
|
||||
public unsafe void PutUint(int offset, uint value)
|
||||
{
|
||||
AssertOffsetAndLength(offset, sizeof(uint));
|
||||
fixed (byte* ptr = _buffer)
|
||||
{
|
||||
*(uint*)(ptr + offset) = BitConverter.IsLittleEndian
|
||||
? value
|
||||
: ReverseBytes(value);
|
||||
}
|
||||
_pos = offset;
|
||||
}
|
||||
|
||||
public unsafe void PutLong(int offset, long value)
|
||||
{
|
||||
PutUlong(offset, (ulong)value);
|
||||
}
|
||||
|
||||
public unsafe void PutUlong(int offset, ulong value)
|
||||
{
|
||||
AssertOffsetAndLength(offset, sizeof(ulong));
|
||||
|
||||
fixed (byte* ptr = _buffer)
|
||||
{
|
||||
*(ulong*)(ptr + offset) = BitConverter.IsLittleEndian
|
||||
? value
|
||||
: ReverseBytes(value);
|
||||
}
|
||||
_pos = offset;
|
||||
}
|
||||
|
||||
public unsafe void PutFloat(int offset, float value)
|
||||
{
|
||||
AssertOffsetAndLength(offset, sizeof(float));
|
||||
fixed (byte* ptr = _buffer)
|
||||
{
|
||||
if (BitConverter.IsLittleEndian)
|
||||
{
|
||||
*(float*)(ptr + offset) = value;
|
||||
}
|
||||
else
|
||||
{
|
||||
*(uint*)(ptr + offset) = ReverseBytes(*(uint*)(&value));
|
||||
}
|
||||
}
|
||||
_pos = offset;
|
||||
}
|
||||
|
||||
public unsafe void PutDouble(int offset, double value)
|
||||
{
|
||||
AssertOffsetAndLength(offset, sizeof(double));
|
||||
fixed (byte* ptr = _buffer)
|
||||
{
|
||||
if (BitConverter.IsLittleEndian)
|
||||
{
|
||||
*(double*)(ptr + offset) = value;
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
*(ulong*)(ptr + offset) = ReverseBytes(*(ulong*)(ptr + offset));
|
||||
}
|
||||
}
|
||||
_pos = offset;
|
||||
}
|
||||
#else // !UNSAFE_BYTEBUFFER
|
||||
// Slower versions of Put* for when unsafe code is not allowed.
|
||||
public void PutShort(int offset, short value)
|
||||
{
|
||||
AssertOffsetAndLength(offset, sizeof(short));
|
||||
WriteLittleEndian(offset, sizeof(short), (ulong)value);
|
||||
}
|
||||
|
||||
public void PutUshort(int offset, ushort value)
|
||||
{
|
||||
AssertOffsetAndLength(offset, sizeof(ushort));
|
||||
WriteLittleEndian(offset, sizeof(ushort), (ulong)value);
|
||||
}
|
||||
|
||||
public void PutInt(int offset, int value)
|
||||
{
|
||||
AssertOffsetAndLength(offset, sizeof(int));
|
||||
WriteLittleEndian(offset, sizeof(int), (ulong)value);
|
||||
}
|
||||
|
||||
public void PutUint(int offset, uint value)
|
||||
{
|
||||
AssertOffsetAndLength(offset, sizeof(uint));
|
||||
WriteLittleEndian(offset, sizeof(uint), (ulong)value);
|
||||
}
|
||||
|
||||
public void PutLong(int offset, long value)
|
||||
{
|
||||
AssertOffsetAndLength(offset, sizeof(long));
|
||||
WriteLittleEndian(offset, sizeof(long), (ulong)value);
|
||||
}
|
||||
|
||||
public void PutUlong(int offset, ulong value)
|
||||
{
|
||||
AssertOffsetAndLength(offset, sizeof(ulong));
|
||||
WriteLittleEndian(offset, sizeof(ulong), value);
|
||||
}
|
||||
|
||||
public void PutFloat(int offset, float value)
|
||||
{
|
||||
AssertOffsetAndLength(offset, sizeof(float));
|
||||
floathelper[0] = value;
|
||||
Buffer.BlockCopy(floathelper, 0, inthelper, 0, sizeof(float));
|
||||
WriteLittleEndian(offset, sizeof(float), (ulong)inthelper[0]);
|
||||
}
|
||||
|
||||
public void PutDouble(int offset, double value)
|
||||
{
|
||||
AssertOffsetAndLength(offset, sizeof(double));
|
||||
doublehelper[0] = value;
|
||||
Buffer.BlockCopy(doublehelper, 0, ulonghelper, 0, sizeof(double));
|
||||
WriteLittleEndian(offset, sizeof(double), ulonghelper[0]);
|
||||
}
|
||||
|
||||
#endif // UNSAFE_BYTEBUFFER
|
||||
|
||||
public sbyte GetSbyte(int index)
|
||||
{
|
||||
AssertOffsetAndLength(index, sizeof(sbyte));
|
||||
return (sbyte)_buffer[index];
|
||||
}
|
||||
|
||||
public byte Get(int index)
|
||||
{
|
||||
AssertOffsetAndLength(index, sizeof(byte));
|
||||
return _buffer[index];
|
||||
}
|
||||
|
||||
#if UNSAFE_BYTEBUFFER
|
||||
// Unsafe but more efficient versions of Get*.
|
||||
public short GetShort(int offset)
|
||||
{
|
||||
return (short)GetUshort(offset);
|
||||
}
|
||||
|
||||
public unsafe ushort GetUshort(int offset)
|
||||
{
|
||||
AssertOffsetAndLength(offset, sizeof(ushort));
|
||||
fixed (byte* ptr = _buffer)
|
||||
{
|
||||
return BitConverter.IsLittleEndian
|
||||
? *(ushort*)(ptr + offset)
|
||||
: ReverseBytes(*(ushort*)(ptr + offset));
|
||||
}
|
||||
}
|
||||
|
||||
public int GetInt(int offset)
|
||||
{
|
||||
return (int)GetUint(offset);
|
||||
}
|
||||
|
||||
public unsafe uint GetUint(int offset)
|
||||
{
|
||||
AssertOffsetAndLength(offset, sizeof(uint));
|
||||
fixed (byte* ptr = _buffer)
|
||||
{
|
||||
return BitConverter.IsLittleEndian
|
||||
? *(uint*)(ptr + offset)
|
||||
: ReverseBytes(*(uint*)(ptr + offset));
|
||||
}
|
||||
}
|
||||
|
||||
public long GetLong(int offset)
|
||||
{
|
||||
return (long)GetUlong(offset);
|
||||
}
|
||||
|
||||
public unsafe ulong GetUlong(int offset)
|
||||
{
|
||||
AssertOffsetAndLength(offset, sizeof(ulong));
|
||||
fixed (byte* ptr = _buffer)
|
||||
{
|
||||
return BitConverter.IsLittleEndian
|
||||
? *(ulong*)(ptr + offset)
|
||||
: ReverseBytes(*(ulong*)(ptr + offset));
|
||||
}
|
||||
}
|
||||
|
||||
public unsafe float GetFloat(int offset)
|
||||
{
|
||||
AssertOffsetAndLength(offset, sizeof(float));
|
||||
fixed (byte* ptr = _buffer)
|
||||
{
|
||||
if (BitConverter.IsLittleEndian)
|
||||
{
|
||||
return *(float*)(ptr + offset);
|
||||
}
|
||||
else
|
||||
{
|
||||
uint uvalue = ReverseBytes(*(uint*)(ptr + offset));
|
||||
return *(float*)(&uvalue);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public unsafe double GetDouble(int offset)
|
||||
{
|
||||
AssertOffsetAndLength(offset, sizeof(double));
|
||||
fixed (byte* ptr = _buffer)
|
||||
{
|
||||
if (BitConverter.IsLittleEndian)
|
||||
{
|
||||
return *(double*)(ptr + offset);
|
||||
}
|
||||
else
|
||||
{
|
||||
ulong uvalue = ReverseBytes(*(ulong*)(ptr + offset));
|
||||
return *(double*)(&uvalue);
|
||||
}
|
||||
}
|
||||
}
|
||||
#else // !UNSAFE_BYTEBUFFER
|
||||
// Slower versions of Get* for when unsafe code is not allowed.
|
||||
public short GetShort(int index)
|
||||
{
|
||||
return (short)ReadLittleEndian(index, sizeof(short));
|
||||
}
|
||||
|
||||
public ushort GetUshort(int index)
|
||||
{
|
||||
return (ushort)ReadLittleEndian(index, sizeof(ushort));
|
||||
}
|
||||
|
||||
public int GetInt(int index)
|
||||
{
|
||||
return (int)ReadLittleEndian(index, sizeof(int));
|
||||
}
|
||||
|
||||
public uint GetUint(int index)
|
||||
{
|
||||
return (uint)ReadLittleEndian(index, sizeof(uint));
|
||||
}
|
||||
|
||||
public long GetLong(int index)
|
||||
{
|
||||
return (long)ReadLittleEndian(index, sizeof(long));
|
||||
}
|
||||
|
||||
public ulong GetUlong(int index)
|
||||
{
|
||||
return ReadLittleEndian(index, sizeof(ulong));
|
||||
}
|
||||
|
||||
public float GetFloat(int index)
|
||||
{
|
||||
int i = (int)ReadLittleEndian(index, sizeof(float));
|
||||
inthelper[0] = i;
|
||||
Buffer.BlockCopy(inthelper, 0, floathelper, 0, sizeof(float));
|
||||
return floathelper[0];
|
||||
}
|
||||
|
||||
public double GetDouble(int index)
|
||||
{
|
||||
ulong i = ReadLittleEndian(index, sizeof(double));
|
||||
// There's Int64BitsToDouble but it uses unsafe code internally.
|
||||
ulonghelper[0] = i;
|
||||
Buffer.BlockCopy(ulonghelper, 0, doublehelper, 0, sizeof(double));
|
||||
return doublehelper[0];
|
||||
}
|
||||
#endif // UNSAFE_BYTEBUFFER
|
||||
}
|
||||
}
|
||||
406
net/FlatBuffers/FlatBufferBuilder.cs
Normal file
406
net/FlatBuffers/FlatBufferBuilder.cs
Normal file
@@ -0,0 +1,406 @@
|
||||
/*
|
||||
* Copyright 2014 Google Inc. All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Text;
|
||||
|
||||
namespace FlatBuffers
|
||||
{
|
||||
/// <summary>
|
||||
/// Responsible for building up and accessing a flatbuffer formatted byte
|
||||
/// array (via ByteBuffer)
|
||||
/// </summary>
|
||||
public class FlatBufferBuilder
|
||||
{
|
||||
private int _space;
|
||||
private ByteBuffer _bb;
|
||||
private int _minAlign = 1;
|
||||
|
||||
// The vtable for the current table, null otherwise.
|
||||
private int[] _vtable;
|
||||
// Starting offset of the current struct/table.
|
||||
private int _objectStart;
|
||||
// List of offsets of all vtables.
|
||||
private int[] _vtables = new int[16];
|
||||
// Number of entries in `vtables` in use.
|
||||
private int _numVtables = 0;
|
||||
// For the current vector being built.
|
||||
private int _vectorNumElems = 0;
|
||||
|
||||
public FlatBufferBuilder(int initialSize)
|
||||
{
|
||||
if (initialSize <= 0)
|
||||
throw new ArgumentOutOfRangeException("initialSize",
|
||||
initialSize, "Must be greater than zero");
|
||||
_space = initialSize;
|
||||
_bb = new ByteBuffer(new byte[initialSize]);
|
||||
}
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
_space = _bb.Length;
|
||||
_bb.Reset();
|
||||
_minAlign = 1;
|
||||
_vtable = null;
|
||||
_objectStart = 0;
|
||||
_vtables = new int[16];
|
||||
_numVtables = 0;
|
||||
_vectorNumElems = 0;
|
||||
}
|
||||
|
||||
public int Offset { get { return _bb.Length - _space; } }
|
||||
|
||||
public void Pad(int size)
|
||||
{
|
||||
for (var i = 0; i < size; i++)
|
||||
{
|
||||
_bb.PutByte(--_space, 0);
|
||||
}
|
||||
}
|
||||
|
||||
// Doubles the size of the ByteBuffer, and copies the old data towards
|
||||
// the end of the new buffer (since we build the buffer backwards).
|
||||
void GrowBuffer()
|
||||
{
|
||||
var oldBuf = _bb.Data;
|
||||
var oldBufSize = oldBuf.Length;
|
||||
if ((oldBufSize & 0xC0000000) != 0)
|
||||
throw new Exception(
|
||||
"FlatBuffers: cannot grow buffer beyond 2 gigabytes.");
|
||||
|
||||
var newBufSize = oldBufSize << 1;
|
||||
var newBuf = new byte[newBufSize];
|
||||
|
||||
Buffer.BlockCopy(oldBuf, 0, newBuf, newBufSize - oldBufSize,
|
||||
oldBufSize);
|
||||
_bb = new ByteBuffer(newBuf, newBufSize);
|
||||
}
|
||||
|
||||
// Prepare to write an element of `size` after `additional_bytes`
|
||||
// have been written, e.g. if you write a string, you need to align
|
||||
// such the int length field is aligned to SIZEOF_INT, and the string
|
||||
// data follows it directly.
|
||||
// If all you need to do is align, `additional_bytes` will be 0.
|
||||
public void Prep(int size, int additionalBytes)
|
||||
{
|
||||
// Track the biggest thing we've ever aligned to.
|
||||
if (size > _minAlign)
|
||||
_minAlign = size;
|
||||
// Find the amount of alignment needed such that `size` is properly
|
||||
// aligned after `additional_bytes`
|
||||
var alignSize =
|
||||
((~((int)_bb.Length - _space + additionalBytes)) + 1) &
|
||||
(size - 1);
|
||||
// Reallocate the buffer if needed.
|
||||
while (_space < alignSize + size + additionalBytes)
|
||||
{
|
||||
var oldBufSize = (int)_bb.Length;
|
||||
GrowBuffer();
|
||||
_space += (int)_bb.Length - oldBufSize;
|
||||
|
||||
}
|
||||
Pad(alignSize);
|
||||
}
|
||||
|
||||
public void PutBool(bool x)
|
||||
{
|
||||
_bb.PutByte(_space -= sizeof(byte), (byte)(x ? 1 : 0));
|
||||
}
|
||||
|
||||
public void PutSbyte(sbyte x)
|
||||
{
|
||||
_bb.PutSbyte(_space -= sizeof(sbyte), x);
|
||||
}
|
||||
|
||||
public void PutByte(byte x)
|
||||
{
|
||||
_bb.PutByte(_space -= sizeof(byte), x);
|
||||
}
|
||||
|
||||
public void PutShort(short x)
|
||||
{
|
||||
_bb.PutShort(_space -= sizeof(short), x);
|
||||
}
|
||||
|
||||
public void PutUshort(ushort x)
|
||||
{
|
||||
_bb.PutUshort(_space -= sizeof(ushort), x);
|
||||
}
|
||||
|
||||
public void PutInt(int x)
|
||||
{
|
||||
_bb.PutInt(_space -= sizeof(int), x);
|
||||
}
|
||||
|
||||
public void PutUint(uint x)
|
||||
{
|
||||
_bb.PutUint(_space -= sizeof(uint), x);
|
||||
}
|
||||
|
||||
public void PutLong(long x)
|
||||
{
|
||||
_bb.PutLong(_space -= sizeof(long), x);
|
||||
}
|
||||
|
||||
public void PutUlong(ulong x)
|
||||
{
|
||||
_bb.PutUlong(_space -= sizeof(ulong), x);
|
||||
}
|
||||
|
||||
public void PutFloat(float x)
|
||||
{
|
||||
_bb.PutFloat(_space -= sizeof(float), x);
|
||||
}
|
||||
|
||||
public void PutDouble(double x)
|
||||
{
|
||||
_bb.PutDouble(_space -= sizeof(double), x);
|
||||
}
|
||||
|
||||
// Adds a scalar to the buffer, properly aligned, and the buffer grown
|
||||
// if needed.
|
||||
public void AddBool(bool x) { Prep(sizeof(byte), 0); PutBool(x); }
|
||||
public void AddSbyte(sbyte x) { Prep(sizeof(sbyte), 0); PutSbyte(x); }
|
||||
public void AddByte(byte x) { Prep(sizeof(byte), 0); PutByte(x); }
|
||||
public void AddShort(short x) { Prep(sizeof(short), 0); PutShort(x); }
|
||||
public void AddUshort(ushort x) { Prep(sizeof(ushort), 0); PutUshort(x); }
|
||||
public void AddInt(int x) { Prep(sizeof(int), 0); PutInt(x); }
|
||||
public void AddUint(uint x) { Prep(sizeof(uint), 0); PutUint(x); }
|
||||
public void AddLong(long x) { Prep(sizeof(long), 0); PutLong(x); }
|
||||
public void AddUlong(ulong x) { Prep(sizeof(ulong), 0); PutUlong(x); }
|
||||
public void AddFloat(float x) { Prep(sizeof(float), 0); PutFloat(x); }
|
||||
public void AddDouble(double x) { Prep(sizeof(double), 0);
|
||||
PutDouble(x); }
|
||||
|
||||
|
||||
|
||||
// Adds on offset, relative to where it will be written.
|
||||
public void AddOffset(int off)
|
||||
{
|
||||
Prep(sizeof(int), 0); // Ensure alignment is already done.
|
||||
if (off > Offset)
|
||||
throw new ArgumentException();
|
||||
|
||||
off = Offset - off + sizeof(int);
|
||||
PutInt(off);
|
||||
}
|
||||
|
||||
public void StartVector(int elemSize, int count, int alignment)
|
||||
{
|
||||
NotNested();
|
||||
_vectorNumElems = count;
|
||||
Prep(sizeof(int), elemSize * count);
|
||||
Prep(alignment, elemSize * count); // Just in case alignment > int.
|
||||
}
|
||||
|
||||
public VectorOffset EndVector()
|
||||
{
|
||||
PutInt(_vectorNumElems);
|
||||
return new VectorOffset(Offset);
|
||||
}
|
||||
|
||||
public void Nested(int obj)
|
||||
{
|
||||
// Structs are always stored inline, so need to be created right
|
||||
// where they are used. You'll get this assert if you created it
|
||||
// elsewhere.
|
||||
if (obj != Offset)
|
||||
throw new Exception(
|
||||
"FlatBuffers: struct must be serialized inline.");
|
||||
}
|
||||
|
||||
public void NotNested()
|
||||
{
|
||||
// You should not be creating any other objects or strings/vectors
|
||||
// while an object is being constructed
|
||||
if (_vtable != null)
|
||||
throw new Exception(
|
||||
"FlatBuffers: object serialization must not be nested.");
|
||||
}
|
||||
|
||||
public void StartObject(int numfields)
|
||||
{
|
||||
NotNested();
|
||||
_vtable = new int[numfields];
|
||||
_objectStart = Offset;
|
||||
}
|
||||
|
||||
|
||||
// Set the current vtable at `voffset` to the current location in the
|
||||
// buffer.
|
||||
public void Slot(int voffset)
|
||||
{
|
||||
_vtable[voffset] = Offset;
|
||||
}
|
||||
|
||||
// Add a scalar to a table at `o` into its vtable, with value `x` and default `d`
|
||||
public void AddBool(int o, bool x, bool d) { if (x != d) { AddBool(x); Slot(o); } }
|
||||
public void AddSbyte(int o, sbyte x, sbyte d) { if (x != d) { AddSbyte(x); Slot(o); } }
|
||||
public void AddByte(int o, byte x, byte d) { if (x != d) { AddByte(x); Slot(o); } }
|
||||
public void AddShort(int o, short x, int d) { if (x != d) { AddShort(x); Slot(o); } }
|
||||
public void AddUshort(int o, ushort x, ushort d) { if (x != d) { AddUshort(x); Slot(o); } }
|
||||
public void AddInt(int o, int x, int d) { if (x != d) { AddInt(x); Slot(o); } }
|
||||
public void AddUint(int o, uint x, uint d) { if (x != d) { AddUint(x); Slot(o); } }
|
||||
public void AddLong(int o, long x, long d) { if (x != d) { AddLong(x); Slot(o); } }
|
||||
public void AddUlong(int o, ulong x, ulong d) { if (x != d) { AddUlong(x); Slot(o); } }
|
||||
public void AddFloat(int o, float x, double d) { if (x != d) { AddFloat(x); Slot(o); } }
|
||||
public void AddDouble(int o, double x, double d) { if (x != d) { AddDouble(x); Slot(o); } }
|
||||
public void AddOffset(int o, int x, int d) { if (x != d) { AddOffset(x); Slot(o); } }
|
||||
|
||||
public StringOffset CreateString(string s)
|
||||
{
|
||||
NotNested();
|
||||
byte[] utf8 = Encoding.UTF8.GetBytes(s);
|
||||
AddByte((byte)0);
|
||||
StartVector(1, utf8.Length, 1);
|
||||
Buffer.BlockCopy(utf8, 0, _bb.Data, _space -= utf8.Length,
|
||||
utf8.Length);
|
||||
return new StringOffset(EndVector().Value);
|
||||
}
|
||||
|
||||
// Structs are stored inline, so nothing additional is being added.
|
||||
// `d` is always 0.
|
||||
public void AddStruct(int voffset, int x, int d)
|
||||
{
|
||||
if (x != d)
|
||||
{
|
||||
Nested(x);
|
||||
Slot(voffset);
|
||||
}
|
||||
}
|
||||
|
||||
public int EndObject()
|
||||
{
|
||||
|
||||
if (_vtable == null)
|
||||
throw new InvalidOperationException(
|
||||
"Flatbuffers: calling endObject without a startObject");
|
||||
|
||||
AddInt((int)0);
|
||||
var vtableloc = Offset;
|
||||
// Write out the current vtable.
|
||||
for (int i = _vtable.Length - 1; i >= 0 ; i--) {
|
||||
// Offset relative to the start of the table.
|
||||
short off = (short)(_vtable[i] != 0
|
||||
? vtableloc - _vtable[i]
|
||||
: 0);
|
||||
AddShort(off);
|
||||
}
|
||||
|
||||
const int standardFields = 2; // The fields below:
|
||||
AddShort((short)(vtableloc - _objectStart));
|
||||
AddShort((short)((_vtable.Length + standardFields) *
|
||||
sizeof(short)));
|
||||
|
||||
// Search for an existing vtable that matches the current one.
|
||||
int existingVtable = 0;
|
||||
|
||||
for (int i = 0; i < _numVtables; i++) {
|
||||
int vt1 = _bb.Length - _vtables[i];
|
||||
int vt2 = _space;
|
||||
short len = _bb.GetShort(vt1);
|
||||
if (len == _bb.GetShort(vt2)) {
|
||||
for (int j = sizeof(short); j < len; j += sizeof(short)) {
|
||||
if (_bb.GetShort(vt1 + j) != _bb.GetShort(vt2 + j)) {
|
||||
goto endLoop;
|
||||
}
|
||||
}
|
||||
existingVtable = _vtables[i];
|
||||
break;
|
||||
}
|
||||
|
||||
endLoop: { }
|
||||
}
|
||||
|
||||
if (existingVtable != 0) {
|
||||
// Found a match:
|
||||
// Remove the current vtable.
|
||||
_space = _bb.Length - vtableloc;
|
||||
// Point table to existing vtable.
|
||||
_bb.PutInt(_space, existingVtable - vtableloc);
|
||||
} else {
|
||||
// No match:
|
||||
// Add the location of the current vtable to the list of
|
||||
// vtables.
|
||||
if (_numVtables == _vtables.Length)
|
||||
{
|
||||
// Arrays.CopyOf(vtables num_vtables * 2);
|
||||
var newvtables = new int[ _numVtables * 2];
|
||||
Array.Copy(_vtables, newvtables, _vtables.Length);
|
||||
|
||||
_vtables = newvtables;
|
||||
};
|
||||
_vtables[_numVtables++] = Offset;
|
||||
// Point table to current vtable.
|
||||
_bb.PutInt(_bb.Length - vtableloc, Offset - vtableloc);
|
||||
}
|
||||
|
||||
_vtable = null;
|
||||
return vtableloc;
|
||||
}
|
||||
|
||||
// This checks a required field has been set in a given table that has
|
||||
// just been constructed.
|
||||
public void Required(int table, int field)
|
||||
{
|
||||
int table_start = _bb.Length - table;
|
||||
int vtable_start = table_start - _bb.GetInt(table_start);
|
||||
bool ok = _bb.GetShort(vtable_start + field) != 0;
|
||||
// If this fails, the caller will show what field needs to be set.
|
||||
if (!ok)
|
||||
throw new InvalidOperationException("FlatBuffers: field " + field +
|
||||
" must be set");
|
||||
}
|
||||
|
||||
public void Finish(int rootTable)
|
||||
{
|
||||
Prep(_minAlign, sizeof(int));
|
||||
AddOffset(rootTable);
|
||||
_bb.Position = _space;
|
||||
}
|
||||
|
||||
public ByteBuffer DataBuffer { get { return _bb; } }
|
||||
|
||||
// Utility function for copying a byte array that starts at 0.
|
||||
public byte[] SizedByteArray()
|
||||
{
|
||||
var newArray = new byte[_bb.Data.Length - _bb.Position];
|
||||
Buffer.BlockCopy(_bb.Data, _bb.Position, newArray, 0,
|
||||
_bb.Data.Length - _bb.Position);
|
||||
return newArray;
|
||||
}
|
||||
|
||||
public void Finish(int rootTable, string fileIdentifier)
|
||||
{
|
||||
Prep(_minAlign, sizeof(int) +
|
||||
FlatBufferConstants.FileIdentifierLength);
|
||||
if (fileIdentifier.Length !=
|
||||
FlatBufferConstants.FileIdentifierLength)
|
||||
throw new ArgumentException(
|
||||
"FlatBuffers: file identifier must be length " +
|
||||
FlatBufferConstants.FileIdentifierLength,
|
||||
"fileIdentifier");
|
||||
for (int i = FlatBufferConstants.FileIdentifierLength - 1; i >= 0;
|
||||
i--)
|
||||
{
|
||||
AddByte((byte)fileIdentifier[i]);
|
||||
}
|
||||
Finish(rootTable);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
28
net/FlatBuffers/FlatBufferConstants.cs
Normal file
28
net/FlatBuffers/FlatBufferConstants.cs
Normal file
@@ -0,0 +1,28 @@
|
||||
/*
|
||||
* Copyright 2014 Google Inc. All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace FlatBuffers
|
||||
{
|
||||
public static class FlatBufferConstants
|
||||
{
|
||||
public const int FileIdentifierLength = 4;
|
||||
}
|
||||
}
|
||||
53
net/FlatBuffers/FlatBuffers.csproj
Normal file
53
net/FlatBuffers/FlatBuffers.csproj
Normal file
@@ -0,0 +1,53 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
|
||||
<PropertyGroup>
|
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
||||
<ProjectGuid>{28C00774-1E73-4A75-AD8F-844CD21A064D}</ProjectGuid>
|
||||
<OutputType>Library</OutputType>
|
||||
<AppDesignerFolder>Properties</AppDesignerFolder>
|
||||
<RootNamespace>FlatBuffers</RootNamespace>
|
||||
<AssemblyName>FlatBuffers</AssemblyName>
|
||||
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
|
||||
<FileAlignment>512</FileAlignment>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<DebugType>full</DebugType>
|
||||
<Optimize>false</Optimize>
|
||||
<OutputPath>bin\Debug\</OutputPath>
|
||||
<DefineConstants>DEBUG;TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<Optimize>true</Optimize>
|
||||
<OutputPath>bin\Release\</OutputPath>
|
||||
<DefineConstants>TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="System" />
|
||||
<Reference Include="System.Core" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="ByteBuffer.cs" />
|
||||
<Compile Include="FlatBufferBuilder.cs" />
|
||||
<Compile Include="FlatBufferConstants.cs" />
|
||||
<Compile Include="Offset.cs" />
|
||||
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||
<Compile Include="Struct.cs" />
|
||||
<Compile Include="Table.cs" />
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
|
||||
Other similar extension points exist, see Microsoft.Common.targets.
|
||||
<Target Name="BeforeBuild">
|
||||
</Target>
|
||||
<Target Name="AfterBuild">
|
||||
</Target>
|
||||
-->
|
||||
</Project>
|
||||
48
net/FlatBuffers/Offset.cs
Normal file
48
net/FlatBuffers/Offset.cs
Normal file
@@ -0,0 +1,48 @@
|
||||
/*
|
||||
* Copyright 2014 Google Inc. All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
namespace FlatBuffers
|
||||
{
|
||||
/// <summary>
|
||||
/// Offset class for typesafe assignments.
|
||||
/// </summary>
|
||||
public struct Offset<T> where T : class
|
||||
{
|
||||
public int Value;
|
||||
public Offset(int value)
|
||||
{
|
||||
Value = value;
|
||||
}
|
||||
}
|
||||
|
||||
public struct StringOffset
|
||||
{
|
||||
public int Value;
|
||||
public StringOffset(int value)
|
||||
{
|
||||
Value = value;
|
||||
}
|
||||
}
|
||||
|
||||
public struct VectorOffset
|
||||
{
|
||||
public int Value;
|
||||
public VectorOffset(int value)
|
||||
{
|
||||
Value = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
52
net/FlatBuffers/Properties/AssemblyInfo.cs
Normal file
52
net/FlatBuffers/Properties/AssemblyInfo.cs
Normal file
@@ -0,0 +1,52 @@
|
||||
/*
|
||||
* Copyright 2014 Google Inc. All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
// General Information about an assembly is controlled through the following
|
||||
// set of attributes. Change these attribute values to modify the information
|
||||
// associated with an assembly.
|
||||
[assembly: AssemblyTitle("FlatBuffers")]
|
||||
[assembly: AssemblyDescription("")]
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[assembly: AssemblyCompany("")]
|
||||
[assembly: AssemblyProduct("FlatBuffers")]
|
||||
[assembly: AssemblyCopyright("Copyright © 2015 Google Inc")]
|
||||
[assembly: AssemblyTrademark("")]
|
||||
[assembly: AssemblyCulture("")]
|
||||
|
||||
// Setting ComVisible to false makes the types in this assembly not visible
|
||||
// to COM components. If you need to access a type in this assembly from
|
||||
// COM, set the ComVisible attribute to true on that type.
|
||||
[assembly: ComVisible(false)]
|
||||
|
||||
// The following GUID is for the ID of the typelib if this project is exposed to COM
|
||||
[assembly: Guid("91c32e64-ef20-47df-9c9f-cec9207bc6df")]
|
||||
|
||||
// Version information for an assembly consists of the following four values:
|
||||
//
|
||||
// Major Version
|
||||
// Minor Version
|
||||
// Build Number
|
||||
// Revision
|
||||
//
|
||||
// You can specify all the values or you can default the Build and Revision Numbers
|
||||
// by using the '*' as shown below:
|
||||
// [assembly: AssemblyVersion("1.0.*")]
|
||||
[assembly: AssemblyVersion("1.0.0.0")]
|
||||
[assembly: AssemblyFileVersion("1.0.0.0")]
|
||||
27
net/FlatBuffers/Struct.cs
Normal file
27
net/FlatBuffers/Struct.cs
Normal file
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* Copyright 2014 Google Inc. All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
namespace FlatBuffers
|
||||
{
|
||||
/// <summary>
|
||||
/// All structs in the generated code derive from this class, and add their own accessors.
|
||||
/// </summary>
|
||||
public abstract class Struct
|
||||
{
|
||||
protected int bb_pos;
|
||||
protected ByteBuffer bb;
|
||||
}
|
||||
}
|
||||
92
net/FlatBuffers/Table.cs
Normal file
92
net/FlatBuffers/Table.cs
Normal file
@@ -0,0 +1,92 @@
|
||||
/*
|
||||
* Copyright 2014 Google Inc. All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Text;
|
||||
|
||||
namespace FlatBuffers
|
||||
{
|
||||
/// <summary>
|
||||
/// All tables in the generated code derive from this class, and add their own accessors.
|
||||
/// </summary>
|
||||
public abstract class Table
|
||||
{
|
||||
protected int bb_pos;
|
||||
protected ByteBuffer bb;
|
||||
|
||||
// Look up a field in the vtable, return an offset into the object, or 0 if the field is not
|
||||
// present.
|
||||
protected int __offset(int vtableOffset)
|
||||
{
|
||||
int vtable = bb_pos - bb.GetInt(bb_pos);
|
||||
return vtableOffset < bb.GetShort(vtable) ? (int)bb.GetShort(vtable + vtableOffset) : 0;
|
||||
}
|
||||
|
||||
// Retrieve the relative offset stored at "offset"
|
||||
protected int __indirect(int offset)
|
||||
{
|
||||
return offset + bb.GetInt(offset);
|
||||
}
|
||||
|
||||
// Create a .NET String from UTF-8 data stored inside the flatbuffer.
|
||||
protected string __string(int offset)
|
||||
{
|
||||
offset += bb.GetInt(offset);
|
||||
var len = bb.GetInt(offset);
|
||||
var startPos = offset + sizeof(int);
|
||||
return Encoding.UTF8.GetString(bb.Data, startPos , len);
|
||||
}
|
||||
|
||||
// Get the length of a vector whose offset is stored at "offset" in this object.
|
||||
protected int __vector_len(int offset)
|
||||
{
|
||||
offset += bb_pos;
|
||||
offset += bb.GetInt(offset);
|
||||
return bb.GetInt(offset);
|
||||
}
|
||||
|
||||
// Get the start of data of a vector whose offset is stored at "offset" in this object.
|
||||
protected int __vector(int offset)
|
||||
{
|
||||
offset += bb_pos;
|
||||
return offset + bb.GetInt(offset) + sizeof(int); // data starts after the length
|
||||
}
|
||||
|
||||
// Initialize any Table-derived type to point to the union at the given offset.
|
||||
protected TTable __union<TTable>(TTable t, int offset) where TTable : Table
|
||||
{
|
||||
offset += bb_pos;
|
||||
t.bb_pos = offset + bb.GetInt(offset);
|
||||
t.bb = bb;
|
||||
return t;
|
||||
}
|
||||
|
||||
protected static bool __has_identifier(ByteBuffer bb, string ident)
|
||||
{
|
||||
if (ident.Length != FlatBufferConstants.FileIdentifierLength)
|
||||
throw new ArgumentException("FlatBuffers: file identifier must be length " + FlatBufferConstants.FileIdentifierLength, "ident");
|
||||
|
||||
for (var i = 0; i < FlatBufferConstants.FileIdentifierLength; i++)
|
||||
{
|
||||
if (ident[i] != (char)bb.Get(bb.Position + sizeof(int) + i)) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
0
python/__init__.py
Normal file
0
python/__init__.py
Normal file
17
python/flatbuffers/__init__.py
Normal file
17
python/flatbuffers/__init__.py
Normal file
@@ -0,0 +1,17 @@
|
||||
# Copyright 2014 Google Inc. All rights reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from .builder import Builder
|
||||
from .table import Table
|
||||
from .compat import range_func as compat_range
|
||||
558
python/flatbuffers/builder.py
Normal file
558
python/flatbuffers/builder.py
Normal file
@@ -0,0 +1,558 @@
|
||||
# Copyright 2014 Google Inc. All rights reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from . import number_types as N
|
||||
from .number_types import (UOffsetTFlags, SOffsetTFlags, VOffsetTFlags)
|
||||
|
||||
from . import encode
|
||||
from . import packer
|
||||
|
||||
from . import compat
|
||||
from .compat import range_func
|
||||
from .compat import memoryview_type
|
||||
|
||||
|
||||
class OffsetArithmeticError(RuntimeError):
|
||||
"""
|
||||
Error caused by an Offset arithmetic error. Probably caused by bad
|
||||
writing of fields. This is considered an unreachable situation in
|
||||
normal circumstances.
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
class NotInObjectError(RuntimeError):
|
||||
"""
|
||||
Error caused by using a Builder to write Object data when not inside
|
||||
an Object.
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
class ObjectIsNestedError(RuntimeError):
|
||||
"""
|
||||
Error caused by using a Builder to begin an Object when an Object is
|
||||
already being built.
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
class StructIsNotInlineError(RuntimeError):
|
||||
"""
|
||||
Error caused by using a Builder to write a Struct at a location that
|
||||
is not the current Offset.
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
class BuilderSizeError(RuntimeError):
|
||||
"""
|
||||
Error caused by causing a Builder to exceed the hardcoded limit of 2
|
||||
gigabytes.
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
# VtableMetadataFields is the count of metadata fields in each vtable.
|
||||
VtableMetadataFields = 2
|
||||
|
||||
|
||||
class Builder(object):
|
||||
"""
|
||||
A Builder is used to construct one or more FlatBuffers. Typically, Builder
|
||||
objects will be used from code generated by the `flatc` compiler.
|
||||
|
||||
A Builder constructs byte buffers in a last-first manner for simplicity and
|
||||
performance during reading.
|
||||
|
||||
Internally, a Builder is a state machine for creating FlatBuffer objects.
|
||||
|
||||
It holds the following internal state:
|
||||
Bytes: an array of bytes.
|
||||
current_vtable: a list of integers.
|
||||
vtables: a list of vtable entries (i.e. a list of list of integers).
|
||||
"""
|
||||
|
||||
__slots__ = ("Bytes", "current_vtable", "head", "minalign", "objectEnd",
|
||||
"vtables")
|
||||
|
||||
"""
|
||||
Maximum buffer size constant, in bytes.
|
||||
Builder will never allow it's buffer grow over this size.
|
||||
Currently equals 2Gb.
|
||||
"""
|
||||
MAX_BUFFER_SIZE = 2**31
|
||||
|
||||
def __init__(self, initialSize):
|
||||
"""
|
||||
Initializes a Builder of size `initial_size`.
|
||||
The internal buffer is grown as needed.
|
||||
"""
|
||||
|
||||
if not (0 <= initialSize <= Builder.MAX_BUFFER_SIZE):
|
||||
msg = "flatbuffers: Cannot create Builder larger than 2 gigabytes."
|
||||
raise BuilderSizeError(msg)
|
||||
|
||||
self.Bytes = bytearray(initialSize)
|
||||
self.current_vtable = None
|
||||
self.head = UOffsetTFlags.py_type(initialSize)
|
||||
self.minalign = 1
|
||||
self.objectEnd = None
|
||||
self.vtables = []
|
||||
|
||||
def Output(self):
|
||||
"""
|
||||
Output returns the portion of the buffer that has been used for
|
||||
writing data.
|
||||
"""
|
||||
|
||||
return self.Bytes[self.Head():]
|
||||
|
||||
def StartObject(self, numfields):
|
||||
"""StartObject initializes bookkeeping for writing a new object."""
|
||||
|
||||
self.assertNotNested()
|
||||
|
||||
# use 32-bit offsets so that arithmetic doesn't overflow.
|
||||
self.current_vtable = [0 for _ in range_func(numfields)]
|
||||
self.objectEnd = self.Offset()
|
||||
self.minalign = 1
|
||||
|
||||
def WriteVtable(self):
|
||||
"""
|
||||
WriteVtable serializes the vtable for the current object, if needed.
|
||||
|
||||
Before writing out the vtable, this checks pre-existing vtables for
|
||||
equality to this one. If an equal vtable is found, point the object to
|
||||
the existing vtable and return.
|
||||
|
||||
Because vtable values are sensitive to alignment of object data, not
|
||||
all logically-equal vtables will be deduplicated.
|
||||
|
||||
A vtable has the following format:
|
||||
<VOffsetT: size of the vtable in bytes, including this value>
|
||||
<VOffsetT: size of the object in bytes, including the vtable offset>
|
||||
<VOffsetT: offset for a field> * N, where N is the number of fields
|
||||
in the schema for this type. Includes deprecated fields.
|
||||
Thus, a vtable is made of 2 + N elements, each VOffsetT bytes wide.
|
||||
|
||||
An object has the following format:
|
||||
<SOffsetT: offset to this object's vtable (may be negative)>
|
||||
<byte: data>+
|
||||
"""
|
||||
|
||||
# Prepend a zero scalar to the object. Later in this function we'll
|
||||
# write an offset here that points to the object's vtable:
|
||||
self.PrependSOffsetTRelative(0)
|
||||
|
||||
objectOffset = self.Offset()
|
||||
existingVtable = None
|
||||
|
||||
# Search backwards through existing vtables, because similar vtables
|
||||
# are likely to have been recently appended. See
|
||||
# BenchmarkVtableDeduplication for a case in which this heuristic
|
||||
# saves about 30% of the time used in writing objects with duplicate
|
||||
# tables.
|
||||
|
||||
i = len(self.vtables) - 1
|
||||
while i >= 0:
|
||||
# Find the other vtable, which is associated with `i`:
|
||||
vt2Offset = self.vtables[i]
|
||||
vt2Start = len(self.Bytes) - vt2Offset
|
||||
vt2Len = encode.Get(packer.voffset, self.Bytes, vt2Start)
|
||||
|
||||
metadata = VtableMetadataFields * N.VOffsetTFlags.bytewidth
|
||||
vt2End = vt2Start + vt2Len
|
||||
vt2 = self.Bytes[vt2Start+metadata:vt2End]
|
||||
|
||||
# Compare the other vtable to the one under consideration.
|
||||
# If they are equal, store the offset and break:
|
||||
if vtableEqual(self.current_vtable, objectOffset, vt2):
|
||||
existingVtable = vt2Offset
|
||||
break
|
||||
|
||||
i -= 1
|
||||
|
||||
if existingVtable is None:
|
||||
# Did not find a vtable, so write this one to the buffer.
|
||||
|
||||
# Write out the current vtable in reverse , because
|
||||
# serialization occurs in last-first order:
|
||||
i = len(self.current_vtable) - 1
|
||||
while i >= 0:
|
||||
off = 0
|
||||
if self.current_vtable[i] != 0:
|
||||
# Forward reference to field;
|
||||
# use 32bit number to ensure no overflow:
|
||||
off = objectOffset - self.current_vtable[i]
|
||||
|
||||
self.PrependVOffsetT(off)
|
||||
i -= 1
|
||||
|
||||
# The two metadata fields are written last.
|
||||
|
||||
# First, store the object bytesize:
|
||||
objectSize = UOffsetTFlags.py_type(objectOffset - self.objectEnd)
|
||||
self.PrependVOffsetT(VOffsetTFlags.py_type(objectSize))
|
||||
|
||||
# Second, store the vtable bytesize:
|
||||
vBytes = len(self.current_vtable) + VtableMetadataFields
|
||||
vBytes *= N.VOffsetTFlags.bytewidth
|
||||
self.PrependVOffsetT(VOffsetTFlags.py_type(vBytes))
|
||||
|
||||
# Next, write the offset to the new vtable in the
|
||||
# already-allocated SOffsetT at the beginning of this object:
|
||||
objectStart = SOffsetTFlags.py_type(len(self.Bytes) - objectOffset)
|
||||
encode.Write(packer.soffset, self.Bytes, objectStart,
|
||||
SOffsetTFlags.py_type(self.Offset() - objectOffset))
|
||||
|
||||
# Finally, store this vtable in memory for future
|
||||
# deduplication:
|
||||
self.vtables.append(self.Offset())
|
||||
else:
|
||||
# Found a duplicate vtable.
|
||||
|
||||
objectStart = SOffsetTFlags.py_type(len(self.Bytes) - objectOffset)
|
||||
self.head = UOffsetTFlags.py_type(objectStart)
|
||||
|
||||
# Write the offset to the found vtable in the
|
||||
# already-allocated SOffsetT at the beginning of this object:
|
||||
encode.Write(packer.soffset, self.Bytes, self.Head(),
|
||||
SOffsetTFlags.py_type(existingVtable - objectOffset))
|
||||
|
||||
self.current_vtable = None
|
||||
return objectOffset
|
||||
|
||||
def EndObject(self):
|
||||
"""EndObject writes data necessary to finish object construction."""
|
||||
if self.current_vtable is None:
|
||||
msg = ("flatbuffers: Tried to write the end of an Object when "
|
||||
"the Builder was not currently writing an Object.")
|
||||
raise NotInObjectError(msg)
|
||||
return self.WriteVtable()
|
||||
|
||||
def growByteBuffer(self):
|
||||
"""Doubles the size of the byteslice, and copies the old data towards
|
||||
the end of the new buffer (since we build the buffer backwards)."""
|
||||
if len(self.Bytes) == Builder.MAX_BUFFER_SIZE:
|
||||
msg = "flatbuffers: cannot grow buffer beyond 2 gigabytes"
|
||||
raise BuilderSizeError(msg)
|
||||
|
||||
newSize = min(len(self.Bytes) * 2, Builder.MAX_BUFFER_SIZE)
|
||||
if newSize == 0:
|
||||
newSize = 1
|
||||
bytes2 = bytearray(newSize)
|
||||
bytes2[newSize-len(self.Bytes):] = self.Bytes
|
||||
self.Bytes = bytes2
|
||||
|
||||
def Head(self):
|
||||
"""
|
||||
Head gives the start of useful data in the underlying byte buffer.
|
||||
Note: unlike other functions, this value is interpreted as from the left.
|
||||
"""
|
||||
return self.head
|
||||
|
||||
def Offset(self):
|
||||
"""Offset relative to the end of the buffer."""
|
||||
return UOffsetTFlags.py_type(len(self.Bytes) - self.Head())
|
||||
|
||||
def Pad(self, n):
|
||||
"""Pad places zeros at the current offset."""
|
||||
for i in range_func(n):
|
||||
self.Place(0, N.Uint8Flags)
|
||||
|
||||
def Prep(self, size, additionalBytes):
|
||||
"""
|
||||
Prep prepares to write an element of `size` after `additional_bytes`
|
||||
have been written, e.g. if you write a string, you need to align
|
||||
such the int length field is aligned to SizeInt32, and the string
|
||||
data follows it directly.
|
||||
If all you need to do is align, `additionalBytes` will be 0.
|
||||
"""
|
||||
|
||||
# Track the biggest thing we've ever aligned to.
|
||||
if size > self.minalign:
|
||||
self.minalign = size
|
||||
|
||||
# Find the amount of alignment needed such that `size` is properly
|
||||
# aligned after `additionalBytes`:
|
||||
alignSize = (~(len(self.Bytes) - self.Head() + additionalBytes)) + 1
|
||||
alignSize &= (size - 1)
|
||||
|
||||
# Reallocate the buffer if needed:
|
||||
while self.Head() < alignSize+size+additionalBytes:
|
||||
oldBufSize = len(self.Bytes)
|
||||
self.growByteBuffer()
|
||||
updated_head = self.head + len(self.Bytes) - oldBufSize
|
||||
self.head = UOffsetTFlags.py_type(updated_head)
|
||||
self.Pad(alignSize)
|
||||
|
||||
def PrependSOffsetTRelative(self, off):
|
||||
"""
|
||||
PrependSOffsetTRelative prepends an SOffsetT, relative to where it
|
||||
will be written.
|
||||
"""
|
||||
|
||||
# Ensure alignment is already done:
|
||||
self.Prep(N.SOffsetTFlags.bytewidth, 0)
|
||||
if not (off <= self.Offset()):
|
||||
msg = "flatbuffers: Offset arithmetic error."
|
||||
raise OffsetArithmeticError(msg)
|
||||
off2 = self.Offset() - off + N.SOffsetTFlags.bytewidth
|
||||
self.PlaceSOffsetT(off2)
|
||||
|
||||
def PrependUOffsetTRelative(self, off):
|
||||
"""
|
||||
PrependUOffsetTRelative prepends an UOffsetT, relative to where it
|
||||
will be written.
|
||||
"""
|
||||
|
||||
# Ensure alignment is already done:
|
||||
self.Prep(N.UOffsetTFlags.bytewidth, 0)
|
||||
if not (off <= self.Offset()):
|
||||
msg = "flatbuffers: Offset arithmetic error."
|
||||
raise OffsetArithmeticError(msg)
|
||||
off2 = self.Offset() - off + N.UOffsetTFlags.bytewidth
|
||||
self.PlaceUOffsetT(off2)
|
||||
|
||||
def StartVector(self, elemSize, numElems, alignment):
|
||||
"""
|
||||
StartVector initializes bookkeeping for writing a new vector.
|
||||
|
||||
A vector has the following format:
|
||||
<UOffsetT: number of elements in this vector>
|
||||
<T: data>+, where T is the type of elements of this vector.
|
||||
"""
|
||||
|
||||
self.assertNotNested()
|
||||
self.Prep(N.Uint32Flags.bytewidth, elemSize*numElems)
|
||||
self.Prep(alignment, elemSize*numElems) # In case alignment > int.
|
||||
return self.Offset()
|
||||
|
||||
def EndVector(self, vectorNumElems):
|
||||
"""EndVector writes data necessary to finish vector construction."""
|
||||
|
||||
# we already made space for this, so write without PrependUint32
|
||||
self.PlaceUOffsetT(vectorNumElems)
|
||||
return self.Offset()
|
||||
|
||||
def CreateString(self, s):
|
||||
"""CreateString writes a null-terminated byte string as a vector."""
|
||||
|
||||
self.assertNotNested()
|
||||
|
||||
if isinstance(s, compat.string_types):
|
||||
x = s.encode()
|
||||
elif isinstance(s, compat.binary_type):
|
||||
x = s
|
||||
else:
|
||||
raise TypeError("non-string passed to CreateString")
|
||||
|
||||
self.Prep(N.UOffsetTFlags.bytewidth, (len(x)+1)*N.Uint8Flags.bytewidth)
|
||||
self.Place(0, N.Uint8Flags)
|
||||
|
||||
l = UOffsetTFlags.py_type(len(s))
|
||||
|
||||
self.head = UOffsetTFlags.py_type(self.Head() - l)
|
||||
self.Bytes[self.Head():self.Head()+l] = x
|
||||
|
||||
return self.EndVector(len(x))
|
||||
|
||||
def assertNotNested(self):
|
||||
"""
|
||||
Check that no other objects are being built while making this
|
||||
object. If not, raise an exception.
|
||||
"""
|
||||
|
||||
if self.current_vtable is not None:
|
||||
msg = ("flatbuffers: Tried to write a new Object when the "
|
||||
"Builder was already writing an Object.")
|
||||
raise ObjectIsNestedError(msg)
|
||||
|
||||
def assertNested(self, obj):
|
||||
"""
|
||||
Structs are always stored inline, so need to be created right
|
||||
where they are used. You'll get this error if you created it
|
||||
elsewhere.
|
||||
"""
|
||||
|
||||
N.enforce_number(obj, N.UOffsetTFlags)
|
||||
if obj != self.Offset():
|
||||
msg = ("flatbuffers: Tried to write a Struct at an Offset that "
|
||||
"is different from the current Offset of the Builder.")
|
||||
raise StructIsNotInlineError(msg)
|
||||
|
||||
def Slot(self, slotnum):
|
||||
"""
|
||||
Slot sets the vtable key `voffset` to the current location in the
|
||||
buffer.
|
||||
|
||||
"""
|
||||
if self.current_vtable is None:
|
||||
msg = ("flatbuffers: Tried to write an Object field when "
|
||||
"the Builder was not currently writing an Object.")
|
||||
raise NotInObjectError(msg)
|
||||
|
||||
self.current_vtable[slotnum] = self.Offset()
|
||||
|
||||
def Finish(self, rootTable):
|
||||
"""Finish finalizes a buffer, pointing to the given `rootTable`."""
|
||||
N.enforce_number(rootTable, N.UOffsetTFlags)
|
||||
self.Prep(self.minalign, N.UOffsetTFlags.bytewidth)
|
||||
self.PrependUOffsetTRelative(rootTable)
|
||||
return self.Head()
|
||||
|
||||
def Prepend(self, flags, off):
|
||||
self.Prep(flags.bytewidth, 0)
|
||||
self.Place(off, flags)
|
||||
|
||||
def PrependSlot(self, flags, o, x, d):
|
||||
N.enforce_number(x, flags)
|
||||
N.enforce_number(d, flags)
|
||||
if x != d:
|
||||
self.Prepend(flags, x)
|
||||
self.Slot(o)
|
||||
|
||||
def PrependBoolSlot(self, *args): self.PrependSlot(N.BoolFlags, *args)
|
||||
|
||||
def PrependByteSlot(self, *args): self.PrependSlot(N.Uint8Flags, *args)
|
||||
|
||||
def PrependUint8Slot(self, *args): self.PrependSlot(N.Uint8Flags, *args)
|
||||
|
||||
def PrependUint16Slot(self, *args): self.PrependSlot(N.Uint16Flags, *args)
|
||||
|
||||
def PrependUint32Slot(self, *args): self.PrependSlot(N.Uint32Flags, *args)
|
||||
|
||||
def PrependUint64Slot(self, *args): self.PrependSlot(N.Uint64Flags, *args)
|
||||
|
||||
def PrependInt8Slot(self, *args): self.PrependSlot(N.Int8Flags, *args)
|
||||
|
||||
def PrependInt16Slot(self, *args): self.PrependSlot(N.Int16Flags, *args)
|
||||
|
||||
def PrependInt32Slot(self, *args): self.PrependSlot(N.Int32Flags, *args)
|
||||
|
||||
def PrependInt64Slot(self, *args): self.PrependSlot(N.Int64Flags, *args)
|
||||
|
||||
def PrependFloat32Slot(self, *args): self.PrependSlot(N.Float32Flags,
|
||||
*args)
|
||||
|
||||
def PrependFloat64Slot(self, *args): self.PrependSlot(N.Float64Flags,
|
||||
*args)
|
||||
|
||||
def PrependUOffsetTRelativeSlot(self, o, x, d):
|
||||
"""
|
||||
PrependUOffsetTRelativeSlot prepends an UOffsetT onto the object at
|
||||
vtable slot `o`. If value `x` equals default `d`, then the slot will
|
||||
be set to zero and no other data will be written.
|
||||
"""
|
||||
|
||||
if x != d:
|
||||
self.PrependUOffsetTRelative(x)
|
||||
self.Slot(o)
|
||||
|
||||
def PrependStructSlot(self, v, x, d):
|
||||
"""
|
||||
PrependStructSlot prepends a struct onto the object at vtable slot `o`.
|
||||
Structs are stored inline, so nothing additional is being added.
|
||||
In generated code, `d` is always 0.
|
||||
"""
|
||||
|
||||
N.enforce_number(d, N.UOffsetTFlags)
|
||||
if x != d:
|
||||
self.assertNested(x)
|
||||
self.Slot(v)
|
||||
|
||||
def PrependBool(self, x): self.Prepend(N.BoolFlags, x)
|
||||
|
||||
def PrependByte(self, x): self.Prepend(N.Uint8Flags, x)
|
||||
|
||||
def PrependUint8(self, x): self.Prepend(N.Uint8Flags, x)
|
||||
|
||||
def PrependUint16(self, x): self.Prepend(N.Uint16Flags, x)
|
||||
|
||||
def PrependUint32(self, x): self.Prepend(N.Uint32Flags, x)
|
||||
|
||||
def PrependUint64(self, x): self.Prepend(N.Uint64Flags, x)
|
||||
|
||||
def PrependInt8(self, x): self.Prepend(N.Int8Flags, x)
|
||||
|
||||
def PrependInt16(self, x): self.Prepend(N.Int16Flags, x)
|
||||
|
||||
def PrependInt32(self, x): self.Prepend(N.Int32Flags, x)
|
||||
|
||||
def PrependInt64(self, x): self.Prepend(N.Int64Flags, x)
|
||||
|
||||
def PrependFloat32(self, x): self.Prepend(N.Float32Flags, x)
|
||||
|
||||
def PrependFloat64(self, x): self.Prepend(N.Float64Flags, x)
|
||||
|
||||
def PrependVOffsetT(self, x): self.Prepend(N.VOffsetTFlags, x)
|
||||
|
||||
def Place(self, x, flags):
|
||||
"""
|
||||
Place prepends a value specified by `flags` to the Builder,
|
||||
without checking for available space.
|
||||
"""
|
||||
|
||||
N.enforce_number(x, flags)
|
||||
self.head = self.head - flags.bytewidth
|
||||
encode.Write(flags.packer_type, self.Bytes, self.Head(), x)
|
||||
|
||||
def PlaceVOffsetT(self, x):
|
||||
"""
|
||||
PlaceVOffsetT prepends a VOffsetT to the Builder, without checking for
|
||||
space.
|
||||
"""
|
||||
N.enforce_number(x, N.VOffsetTFlags)
|
||||
self.head = self.head - N.VOffsetTFlags.bytewidth
|
||||
encode.Write(packer.voffset, self.Bytes, self.Head(), x)
|
||||
|
||||
def PlaceSOffsetT(self, x):
|
||||
"""
|
||||
PlaceSOffsetT prepends a SOffsetT to the Builder, without checking for
|
||||
space.
|
||||
"""
|
||||
N.enforce_number(x, N.SOffsetTFlags)
|
||||
self.head = self.head - N.SOffsetTFlags.bytewidth
|
||||
encode.Write(packer.soffset, self.Bytes, self.Head(), x)
|
||||
|
||||
def PlaceUOffsetT(self, x):
|
||||
"""
|
||||
PlaceUOffsetT prepends a UOffsetT to the Builder, without checking for
|
||||
space.
|
||||
"""
|
||||
N.enforce_number(x, N.UOffsetTFlags)
|
||||
self.head = self.head - N.UOffsetTFlags.bytewidth
|
||||
encode.Write(packer.uoffset, self.Bytes, self.Head(), x)
|
||||
|
||||
|
||||
def vtableEqual(a, objectStart, b):
|
||||
"""vtableEqual compares an unwritten vtable to a written vtable."""
|
||||
|
||||
N.enforce_number(objectStart, N.UOffsetTFlags)
|
||||
|
||||
if len(a) * N.VOffsetTFlags.bytewidth != len(b):
|
||||
return False
|
||||
|
||||
for i, elem in enumerate(a):
|
||||
x = encode.Get(packer.voffset, b, i * N.VOffsetTFlags.bytewidth)
|
||||
|
||||
# Skip vtable entries that indicate a default value.
|
||||
if x == 0 and elem == 0:
|
||||
pass
|
||||
else:
|
||||
y = objectStart - elem
|
||||
if x != y:
|
||||
return False
|
||||
return True
|
||||
27
python/flatbuffers/compat.py
Normal file
27
python/flatbuffers/compat.py
Normal file
@@ -0,0 +1,27 @@
|
||||
""" A tiny version of `six` to help with backwards compability. """
|
||||
|
||||
import sys
|
||||
|
||||
PY2 = sys.version_info[0] == 2
|
||||
PY26 = sys.version_info[0:2] == (2, 6)
|
||||
PY3 = sys.version_info[0] == 3
|
||||
PY34 = sys.version_info[0:2] >= (3, 4)
|
||||
|
||||
if PY3:
|
||||
string_types = (str,)
|
||||
binary_type = bytes
|
||||
range_func = range
|
||||
memoryview_type = memoryview
|
||||
struct_bool_decl = "?"
|
||||
else:
|
||||
string_types = (basestring,)
|
||||
binary_type = str
|
||||
range_func = xrange
|
||||
if PY26:
|
||||
memoryview_type = buffer
|
||||
struct_bool_decl = "<b"
|
||||
else:
|
||||
memoryview_type = memoryview
|
||||
struct_bool_decl = "?"
|
||||
|
||||
# NOTE: Future Jython support may require code here (look at `six`).
|
||||
29
python/flatbuffers/encode.py
Normal file
29
python/flatbuffers/encode.py
Normal file
@@ -0,0 +1,29 @@
|
||||
# Copyright 2014 Google Inc. All rights reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import ctypes
|
||||
|
||||
from . import number_types as N
|
||||
from . import packer
|
||||
from .compat import memoryview_type
|
||||
|
||||
|
||||
def Get(packer_type, buf, head):
|
||||
""" Get decodes a value at buf[head:] using `packer_type`. """
|
||||
return packer_type.unpack_from(memoryview_type(buf), head)[0]
|
||||
|
||||
|
||||
def Write(packer_type, buf, head, n):
|
||||
""" Write encodes `n` at buf[head:] using `packer_type`. """
|
||||
packer_type.pack_into(buf, head, n)
|
||||
174
python/flatbuffers/number_types.py
Normal file
174
python/flatbuffers/number_types.py
Normal file
@@ -0,0 +1,174 @@
|
||||
# Copyright 2014 Google Inc. All rights reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import ctypes
|
||||
import collections
|
||||
import struct
|
||||
from ctypes import sizeof
|
||||
|
||||
from . import packer
|
||||
|
||||
|
||||
# For reference, see:
|
||||
# https://docs.python.org/2/library/ctypes.html#ctypes-fundamental-data-types-2
|
||||
|
||||
# These classes could be collections.namedtuple instances, but those are new
|
||||
# in 2.6 and we want to work towards 2.5 compatability.
|
||||
|
||||
class BoolFlags(object):
|
||||
bytewidth = 1
|
||||
min_val = False
|
||||
max_val = True
|
||||
py_type = bool
|
||||
name = "bool"
|
||||
packer_type = packer.boolean
|
||||
|
||||
|
||||
class Uint8Flags(object):
|
||||
bytewidth = 1
|
||||
min_val = 0
|
||||
max_val = (2**8) - 1
|
||||
py_type = int
|
||||
name = "uint8"
|
||||
packer_type = packer.uint8
|
||||
|
||||
|
||||
class Uint16Flags(object):
|
||||
bytewidth = 2
|
||||
min_val = 0
|
||||
max_val = (2**16) - 1
|
||||
py_type = int
|
||||
name = "uint16"
|
||||
packer_type = packer.uint16
|
||||
|
||||
|
||||
class Uint32Flags(object):
|
||||
bytewidth = 4
|
||||
min_val = 0
|
||||
max_val = (2**32) - 1
|
||||
py_type = int
|
||||
name = "uint32"
|
||||
packer_type = packer.uint32
|
||||
|
||||
|
||||
class Uint64Flags(object):
|
||||
bytewidth = 8
|
||||
min_val = 0
|
||||
max_val = (2**64) - 1
|
||||
py_type = int
|
||||
name = "uint64"
|
||||
packer_type = packer.uint64
|
||||
|
||||
|
||||
class Int8Flags(object):
|
||||
bytewidth = 1
|
||||
min_val = -(2**7)
|
||||
max_val = (2**7) - 1
|
||||
py_type = int
|
||||
name = "int8"
|
||||
packer_type = packer.int8
|
||||
|
||||
|
||||
class Int16Flags(object):
|
||||
bytewidth = 2
|
||||
min_val = -(2**15)
|
||||
max_val = (2**15) - 1
|
||||
py_type = int
|
||||
name = "int16"
|
||||
packer_type = packer.int16
|
||||
|
||||
|
||||
class Int32Flags(object):
|
||||
bytewidth = 4
|
||||
min_val = -(2**31)
|
||||
max_val = (2**31) - 1
|
||||
py_type = int
|
||||
name = "int32"
|
||||
packer_type = packer.int32
|
||||
|
||||
|
||||
class Int64Flags(object):
|
||||
bytewidth = 8
|
||||
min_val = -(2**63)
|
||||
max_val = (2**63) - 1
|
||||
py_type = int
|
||||
name = "int64"
|
||||
packer_type = packer.int64
|
||||
|
||||
|
||||
class Float32Flags(object):
|
||||
bytewidth = 4
|
||||
min_val = None
|
||||
max_val = None
|
||||
py_type = float
|
||||
name = "float32"
|
||||
packer_type = packer.float32
|
||||
|
||||
|
||||
class Float64Flags(object):
|
||||
bytewidth = 8
|
||||
min_val = None
|
||||
max_val = None
|
||||
py_type = float
|
||||
name = "float64"
|
||||
packer_type = packer.float64
|
||||
|
||||
|
||||
class SOffsetTFlags(Int32Flags):
|
||||
pass
|
||||
|
||||
|
||||
class UOffsetTFlags(Uint32Flags):
|
||||
pass
|
||||
|
||||
|
||||
class VOffsetTFlags(Uint16Flags):
|
||||
pass
|
||||
|
||||
|
||||
def valid_number(n, flags):
|
||||
if flags.min_val is None and flags.max_val is None:
|
||||
return True
|
||||
return flags.min_val <= n <= flags.max_val
|
||||
|
||||
|
||||
def enforce_number(n, flags):
|
||||
if flags.min_val is None and flags.max_val is None:
|
||||
return
|
||||
if not flags.min_val <= n <= flags.max_val:
|
||||
raise TypeError("bad number %s for type %s" % (str(n), flags.name))
|
||||
|
||||
|
||||
def float32_to_uint32(n):
|
||||
packed = struct.pack("<1f", n)
|
||||
(converted,) = struct.unpack("<1L", packed)
|
||||
return converted
|
||||
|
||||
|
||||
def uint32_to_float32(n):
|
||||
packed = struct.pack("<1L", n)
|
||||
(unpacked,) = struct.unpack("<1f", packed)
|
||||
return unpacked
|
||||
|
||||
|
||||
def float64_to_uint64(n):
|
||||
packed = struct.pack("<1d", n)
|
||||
(converted,) = struct.unpack("<1Q", packed)
|
||||
return converted
|
||||
|
||||
|
||||
def uint64_to_float64(n):
|
||||
packed = struct.pack("<1Q", n)
|
||||
(unpacked,) = struct.unpack("<1d", packed)
|
||||
return unpacked
|
||||
28
python/flatbuffers/packer.py
Normal file
28
python/flatbuffers/packer.py
Normal file
@@ -0,0 +1,28 @@
|
||||
"""
|
||||
Provide pre-compiled struct packers for encoding and decoding.
|
||||
|
||||
See: https://docs.python.org/2/library/struct.html#format-characters
|
||||
"""
|
||||
|
||||
import struct
|
||||
from . import compat
|
||||
|
||||
|
||||
boolean = struct.Struct(compat.struct_bool_decl)
|
||||
|
||||
uint8 = struct.Struct("<B")
|
||||
uint16 = struct.Struct("<H")
|
||||
uint32 = struct.Struct("<I")
|
||||
uint64 = struct.Struct("<Q")
|
||||
|
||||
int8 = struct.Struct("<b")
|
||||
int16 = struct.Struct("<h")
|
||||
int32 = struct.Struct("<i")
|
||||
int64 = struct.Struct("<q")
|
||||
|
||||
float32 = struct.Struct("<f")
|
||||
float64 = struct.Struct("<d")
|
||||
|
||||
uoffset = uint32
|
||||
soffset = int32
|
||||
voffset = uint16
|
||||
117
python/flatbuffers/table.py
Normal file
117
python/flatbuffers/table.py
Normal file
@@ -0,0 +1,117 @@
|
||||
# Copyright 2014 Google Inc. All rights reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from . import encode
|
||||
from . import number_types as N
|
||||
|
||||
|
||||
class Table(object):
|
||||
"""Table wraps a byte slice and provides read access to its data.
|
||||
|
||||
The variable `Pos` indicates the root of the FlatBuffers object therein."""
|
||||
|
||||
__slots__ = ("Bytes", "Pos")
|
||||
|
||||
def __init__(self, buf, pos):
|
||||
N.enforce_number(pos, N.UOffsetTFlags)
|
||||
|
||||
self.Bytes = buf
|
||||
self.Pos = pos
|
||||
|
||||
def Offset(self, vtableOffset):
|
||||
"""Offset provides access into the Table's vtable.
|
||||
|
||||
Deprecated fields are ignored by checking the vtable's length."""
|
||||
|
||||
vtable = self.Pos - self.Get(N.SOffsetTFlags, self.Pos)
|
||||
vtableEnd = self.Get(N.VOffsetTFlags, vtable)
|
||||
if vtableOffset < vtableEnd:
|
||||
return self.Get(N.VOffsetTFlags, vtable + vtableOffset)
|
||||
return 0
|
||||
|
||||
def Indirect(self, off):
|
||||
"""Indirect retrieves the relative offset stored at `offset`."""
|
||||
N.enforce_number(off, N.UOffsetTFlags)
|
||||
return off + encode.Get(N.UOffsetTFlags.packer_type, self.Bytes, off)
|
||||
|
||||
def String(self, off):
|
||||
"""String gets a string from data stored inside the flatbuffer."""
|
||||
N.enforce_number(off, N.UOffsetTFlags)
|
||||
off += encode.Get(N.UOffsetTFlags.packer_type, self.Bytes, off)
|
||||
start = off + N.UOffsetTFlags.bytewidth
|
||||
length = encode.Get(N.UOffsetTFlags.packer_type, self.Bytes, off)
|
||||
return bytes(self.Bytes[start:start+length])
|
||||
|
||||
def VectorLen(self, off):
|
||||
"""VectorLen retrieves the length of the vector whose offset is stored
|
||||
at "off" in this object."""
|
||||
N.enforce_number(off, N.UOffsetTFlags)
|
||||
|
||||
off += self.Pos
|
||||
off += encode.Get(N.UOffsetTFlags.packer_type, self.Bytes, off)
|
||||
ret = encode.Get(N.UOffsetTFlags.packer_type, self.Bytes, off)
|
||||
return ret
|
||||
|
||||
def Vector(self, off):
|
||||
"""Vector retrieves the start of data of the vector whose offset is
|
||||
stored at "off" in this object."""
|
||||
N.enforce_number(off, N.UOffsetTFlags)
|
||||
|
||||
off += self.Pos
|
||||
x = off + self.Get(N.UOffsetTFlags, off)
|
||||
# data starts after metadata containing the vector length
|
||||
x += N.UOffsetTFlags.bytewidth
|
||||
return x
|
||||
|
||||
def Union(self, t2, off):
|
||||
"""Union initializes any Table-derived type to point to the union at
|
||||
the given offset."""
|
||||
assert type(t2) is Table
|
||||
N.enforce_number(off, N.UOffsetTFlags)
|
||||
|
||||
off += self.Pos
|
||||
t2.Pos = off + self.Get(N.UOffsetTFlags, off)
|
||||
t2.Bytes = self.Bytes
|
||||
|
||||
def Get(self, flags, off):
|
||||
"""
|
||||
Get retrieves a value of the type specified by `flags` at the
|
||||
given offset.
|
||||
"""
|
||||
N.enforce_number(off, N.UOffsetTFlags)
|
||||
return flags.py_type(encode.Get(flags.packer_type, self.Bytes, off))
|
||||
|
||||
def GetSlot(self, slot, d, validator_flags):
|
||||
N.enforce_number(slot, N.VOffsetTFlags)
|
||||
if validator_flags is not None:
|
||||
N.enforce_number(d, validator_flags)
|
||||
off = self.Offset(slot)
|
||||
if off == 0:
|
||||
return d
|
||||
return self.Get(validator_flags, self.Pos + off)
|
||||
|
||||
def GetVOffsetTSlot(self, slot, d):
|
||||
"""
|
||||
GetVOffsetTSlot retrieves the VOffsetT that the given vtable location
|
||||
points to. If the vtable value is zero, the default value `d`
|
||||
will be returned.
|
||||
"""
|
||||
|
||||
N.enforce_number(slot, N.VOffsetTFlags)
|
||||
N.enforce_number(d, N.VOffsetTFlags)
|
||||
|
||||
off = self.Offset(slot)
|
||||
if off == 0:
|
||||
return d
|
||||
return off
|
||||
16
python/setup.py
Normal file
16
python/setup.py
Normal file
@@ -0,0 +1,16 @@
|
||||
from setuptools import setup
|
||||
|
||||
setup(
|
||||
name='flatbuffers',
|
||||
version='2015.05.14.0',
|
||||
license='Apache 2.0',
|
||||
author='FlatBuffers Contributors',
|
||||
author_email='me@rwinslow.com',
|
||||
url='https://github.com/google/flatbuffers',
|
||||
long_description=('Python runtime library for use with the Flatbuffers'
|
||||
'serialization format.'),
|
||||
packages=['flatbuffers'],
|
||||
include_package_data=True,
|
||||
requires=[],
|
||||
description='The FlatBuffers serialization format for Python',
|
||||
)
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user